@cloud411716/fancy-webnovel 4.27.3 → 4.29.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.
@@ -25,12 +25,36 @@ import {
25
25
  workspacePaths,
26
26
  } from '#workspace';
27
27
  import { connectMaterial, ensureMaterialDatabase, materialDatabaseName, removeMaterialDatabase } from '#material-db';
28
- import { BUILTIN_GENRES, resolveMaterialTopic } from '#material-topic';
28
+ import { readMinimalTopic, readSuggestion } from '#material-topic';
29
29
  import { makeWaitForTurn } from '../fancy-story-builder/writing-driver.js';
30
30
  import { exportMaterials } from './exporter.js';
31
31
  import { allKnownGenres } from './genres.js';
32
32
  import { buildExistingIndex, countByKind, countKind } from './inventory.js';
33
- import { KIND_LABELS, MATERIAL_KINDS, customFocusBlock, focusBlock, renderKindTable, resolveCustomKinds, resolveFocus } from './kinds.js';
33
+ import { KIND_LABELS, MATERIAL_KINDS, focusBlock, renderKindTable } from './kinds.js';
34
+ import { loadStyleRegistry, selectStyles, styleBatchSummary, stylePromptBlock, styleSummaryText } from './styles.js';
35
+ import {
36
+ EMPTY_FACET_LABEL,
37
+ FACET_STEPS,
38
+ buildWorldPrompt,
39
+ countQuestion,
40
+ expandGenre,
41
+ expandGenres,
42
+ facetQuestion,
43
+ flowPath,
44
+ flowSummaryText,
45
+ normalizeFacetSelection,
46
+ parseCountAnswer,
47
+ parseWorldCandidates,
48
+ readMaterialFlow,
49
+ renderWorldBatchSummary,
50
+ renderWorldBlock,
51
+ resolveScopeKinds,
52
+ scopeQuestion,
53
+ suggestionFingerprint,
54
+ styleQuestion,
55
+ worldCandidateQuestion,
56
+ writeMaterialFlow,
57
+ } from './world.js';
34
58
  import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
35
59
  import { nextBatchRequest, planMaterialQueue } from './queue.js';
36
60
  import { deployMaterialTools } from './tool-deploy.js';
@@ -120,6 +144,10 @@ function renderBasePrompt({
120
144
  batchSize = DEFAULT_BATCH_SIZE,
121
145
  focusBlockText = '',
122
146
  custom = null,
147
+ styleBlock = '',
148
+ styleRules = '',
149
+ worldBlock = '',
150
+ audience = '',
123
151
  }) {
124
152
  const sourceFixed = mode === 'other' ? 'other' : 'builtin';
125
153
  const sourceNote = sourceFixed === 'other'
@@ -130,14 +158,16 @@ function renderBasePrompt({
130
158
  : '下面素材类型总表之一;builtin 素材必须在表内';
131
159
  return renderPrompt(readPrompt(), {
132
160
  MATERIAL_MODE: mode,
133
- GENRES: (genres || []).join('、'),
161
+ GENRES: (genres || []).join('、') || '(未限制,按世界母体推导)',
134
162
  TOPIC_FILE: topicFile || '(无)',
135
163
  KIND_TABLE: renderKindTable(),
136
164
  FOCUS_BLOCK: focusBlockText || focusBlock(focus),
137
165
  TARGET_PER_KIND: String(targetPerKind),
138
166
  BATCH_SIZE: String(batchSize),
139
- AUDIENCE: '男频 / 女频 / 通用',
140
- STYLE_RULES: '未指定(执行通用创作标准)',
167
+ AUDIENCE: audience || '男频 / 女频 / 通用',
168
+ STYLE_RULES: styleRules || '未指定(执行通用创作标准)',
169
+ STYLE_BLOCK: styleBlock || '(本次未选择账号风格,按通用规则生成。)',
170
+ WORLD_BLOCK: worldBlock || '(本次未指定世界母体,按通用规则生成。)',
141
171
  BATCH_ID: batchId || 'material-YYYYMMDD-01',
142
172
  SEED: batchId || 'material-v4',
143
173
  EXISTING_INDEX: existingIndex || '(运行 /fancy-material 时由插件提供)',
@@ -160,6 +190,38 @@ function stripQuotes(value) {
160
190
  return text;
161
191
  }
162
192
 
193
+ /**
194
+ * 从参数里抽取 --style。
195
+ * 支持:--style suci / --style=suci / --style suci,crazy-fish。
196
+ * 返回清洗后的参数(保持其它参数的相对顺序)。
197
+ */
198
+ export function splitStyleOption(rawTokens) {
199
+ const tokens = [];
200
+ const styles = [];
201
+ let missing = false;
202
+ for (let i = 0; i < rawTokens.length; i += 1) {
203
+ const token = rawTokens[i];
204
+ if (token === '--style') {
205
+ const value = rawTokens[i + 1];
206
+ if (!value || value.startsWith('--')) {
207
+ missing = true;
208
+ continue;
209
+ }
210
+ styles.push(value);
211
+ i += 1;
212
+ continue;
213
+ }
214
+ if (token.startsWith('--style=')) {
215
+ const value = token.slice('--style='.length).trim();
216
+ if (!value) missing = true;
217
+ else styles.push(value);
218
+ continue;
219
+ }
220
+ tokens.push(token);
221
+ }
222
+ return { tokens, styleRaw: styles.join(','), missing };
223
+ }
224
+
163
225
  /**
164
226
  * Resolve a user-provided import path. Relative paths are resolved from the
165
227
  * session cwd first, then from the workspace directory.
@@ -200,13 +262,12 @@ async function checkFile(file) {
200
262
  }
201
263
 
202
264
  /**
203
- * Every generated card must keep at least one exact selected genre in `genres`.
204
- * The model may add subgenres, but replacing the selected label with a synonym
205
- * breaks genre filtering and the existing-library index.
265
+ * 本版 facet 是交集语义:每条记录的 genres 必须原样包含本次选中的**全部**
266
+ * 题材。只要缺一个,就不能算满足本次世界母体。
206
267
  */
207
268
  function genreCoverageProblem(file, genres) {
208
- const selected = new Set((genres || []).filter(Boolean));
209
- if (!selected.size) return '';
269
+ const selected = [...new Set((genres || []).filter(Boolean))];
270
+ if (!selected.length) return '';
210
271
  let text;
211
272
  try { text = fs.readFileSync(file, 'utf8'); } catch { return ''; }
212
273
  const lines = text.split(/\r?\n/);
@@ -216,15 +277,17 @@ function genreCoverageProblem(file, genres) {
216
277
  if (!line) continue;
217
278
  let record;
218
279
  try { record = JSON.parse(line); } catch { continue; }
219
- const values = Array.isArray(record.genres) ? record.genres.map(String) : [];
220
- if (!values.some((genre) => selected.has(genre))) {
221
- bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」`);
280
+ const values = new Set(Array.isArray(record.genres) ? record.genres.map(String) : []);
281
+ const missing = selected.filter((genre) => !values.has(genre));
282
+ if (missing.length) {
283
+ bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」缺 ${missing.join('、')}`);
222
284
  }
223
285
  }
224
286
  if (!bad.length) return '';
225
- return '以下素材的 genres 没有原样包含本次主题材:' + bad.slice(0, 8).join('、')
287
+ return '以下素材没有同时满足本次题材交集:' + bad.slice(0, 8).join(';')
226
288
  + (bad.length > 8 ? `等 ${bad.length} 条` : '')
227
- + '。请把本次题材列表中的主题材名原样写进 genres,可再附加子题材。';
289
+ + '。每条素材的 genres 必须原样包含全部选中题材:' + selected.join('、')
290
+ + '。缺任何一个都算废稿。';
228
291
  }
229
292
 
230
293
  /**
@@ -506,71 +569,501 @@ async function runNativeImport(ctx, invocation, session, rawPath, taskList) {
506
569
  }
507
570
  }
508
571
 
509
- async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, opts = {}) {
572
+ async function askOne(ctx, invocation, question) {
573
+ const asked = await askUserQuestion(ctx, invocation, [question]);
574
+ if (!asked.ok) {
575
+ const type = asked.failure?.type;
576
+ if (type === 'cancelled') return { ok: false, message: '🚫 操作已取消。' };
577
+ if (type === 'no_provider') {
578
+ return { ok: false, message: '⚠️ 当前运行环境不支持交互式提问。请在 dsh-tui 中运行,或确认 Web UI 已加载交互组件。' };
579
+ }
580
+ return { ok: false, message: asked.failure?.message || '❌ 提问失败' };
581
+ }
582
+ const answers = asked.answer?.answers;
583
+ return { ok: true, answer: Array.isArray(answers) ? answers[0] : null };
584
+ }
585
+
586
+ function answerList(answer) {
587
+ if (!answer || typeof answer !== 'object') return [];
588
+ const selected = Array.isArray(answer.selected)
589
+ ? answer.selected.map((value) => String(value || '').trim()).filter(Boolean)
590
+ : [];
591
+ const custom = typeof answer.custom === 'string' ? answer.custom.trim() : '';
592
+ if (custom) {
593
+ for (const part of custom.split(/[,,、]/).map((value) => value.trim()).filter(Boolean)) {
594
+ selected.push(part);
595
+ }
596
+ }
597
+ return [...new Set(selected)];
598
+ }
599
+
600
+ function answerSingle(answer) {
601
+ if (!answer || typeof answer !== 'object') return '';
602
+ const custom = typeof answer.custom === 'string' ? answer.custom.trim() : '';
603
+ if (custom) return custom;
604
+ return Array.isArray(answer.selected) ? String(answer.selected[0] || '').trim() : '';
605
+ }
606
+
607
+ function facetStateFromLabels(facetLabels) {
608
+ const facets = {};
609
+ for (const step of FACET_STEPS) {
610
+ const values = normalizeFacetSelection(facetLabels[step.id] || []);
611
+ facets[step.id] = step.id === 'genres' ? expandGenres(values) : values;
612
+ }
613
+ return facets;
614
+ }
615
+
616
+ function chooseTopicGenre(facetGenres, suggestion) {
617
+ const raw = String(suggestion?.genre || '').trim();
618
+ if (raw) {
619
+ const expanded = expandGenre(raw);
620
+ if (!facetGenres.length || expanded.every((genre) => facetGenres.includes(genre))) return raw;
621
+ }
622
+ return facetGenres[0] || raw || '通用';
623
+ }
624
+
625
+ function styleSelectionFromRaw(raw) {
626
+ const value = String(raw || '').trim();
627
+ if (!value || value.toLowerCase() === 'auto') return { mode: 'auto', keys: [] };
628
+ if (value.toLowerCase() === 'none') return { mode: 'none', keys: [] };
629
+ return {
630
+ mode: 'manual',
631
+ keys: value.split(/[,,、]/).map((item) => item.trim()).filter(Boolean),
632
+ };
633
+ }
634
+
635
+ function styleSelectionFromLabels(labels, styles) {
636
+ const values = Array.isArray(labels) ? labels : [];
637
+ if (values.includes('不使用账号风格')) return { mode: 'none', keys: [] };
638
+ const keys = [];
639
+ for (const label of values) {
640
+ if (!label || label === EMPTY_FACET_LABEL || label === '无(自动选择)') continue;
641
+ const exact = styles.find((style) => style.style_key === label);
642
+ if (exact) {
643
+ keys.push(exact.style_key);
644
+ continue;
645
+ }
646
+ const labelled = styles.find((style) => label === `${style.style_key}(${style.style_name})`);
647
+ if (labelled) keys.push(labelled.style_key);
648
+ }
649
+ return keys.length ? { mode: 'manual', keys } : { mode: 'auto', keys: [] };
650
+ }
651
+
652
+ function resolveStyleObjects(registry, { genres = [], selection = { mode: 'auto', keys: [] } } = {}) {
653
+ const explicit = selection.mode === 'none'
654
+ ? 'none'
655
+ : (selection.keys?.length ? selection.keys.join(',') : 'auto');
656
+ return selectStyles(registry.styles, {
657
+ genres,
658
+ explicit,
659
+ limit: 3,
660
+ });
661
+ }
662
+
663
+ async function askFacetSelections(ctx, invocation, suggestion, taskList) {
664
+ const facetLabels = {};
665
+ for (const step of FACET_STEPS) {
666
+ if (taskList && typeof taskList.progress === 'function') {
667
+ taskList.progress(`选择${step.label}(同一层多选=交集)`);
668
+ }
669
+ const asked = await askOne(ctx, invocation, facetQuestion(step, { suggestion }));
670
+ if (!asked.ok) return { ok: false, message: asked.message };
671
+ facetLabels[step.id] = normalizeFacetSelection(answerList(asked.answer));
672
+ }
673
+ return { ok: true, facetLabels };
674
+ }
675
+
676
+ async function generateWorldCandidates({
677
+ root,
678
+ invocation,
679
+ taskList,
680
+ facets,
681
+ facetLabels,
682
+ suggestion,
683
+ scopeKinds,
684
+ styleSummary,
685
+ previousTitles = [],
686
+ }) {
687
+ const stamp = localIsoString().replace(/[-:T+.]/g, '').slice(0, 14) || String(Date.now());
688
+ const file = path.join(workspacePaths(root).tmp, 'fancy_material_world_' + stamp + '.json');
689
+ let failure = '';
690
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
691
+ if (abortRequested(invocation)) return { ok: false, aborted: true, message: '用户中断' };
692
+ if (taskList && typeof taskList.progress === 'function') {
693
+ taskList.progress('生成世界母体候选(第 ' + attempt + ' 次)');
694
+ }
695
+ let before = null;
696
+ try { before = fs.readFileSync(file, 'utf8'); } catch { /* first attempt */ }
697
+ let prompt;
698
+ try {
699
+ prompt = buildWorldPrompt({
700
+ workspace: root,
701
+ resultPath: file,
702
+ facets,
703
+ facetLabels,
704
+ suggestion,
705
+ scopeKinds,
706
+ styleSummary,
707
+ previousTitles,
708
+ });
709
+ } catch (err) {
710
+ return { ok: false, message: err && err.message ? err.message : String(err) };
711
+ }
712
+ if (failure) {
713
+ prompt += '\n\n## 上次输出不可用\n\n' + failure + '\n\n请重新生成完整 JSON,并写入同一个目标文件。';
714
+ }
715
+ const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
716
+ if (!sent || sent.ok !== true) {
717
+ return { ok: false, message: '向 LLM 发送世界母体提示词失败:' + ((sent && sent.error) || '未知错误') };
718
+ }
719
+ taskList.watchTurns(invocation);
720
+ const waitForTurn = makeWaitForTurn(invocation, {
721
+ timeoutMs: 10 * 60 * 1000,
722
+ idleGraceMs: 60 * 1000,
723
+ signal: invocation.signal,
724
+ changed: (files, previous) => {
725
+ try {
726
+ return fs.readFileSync(files[0], 'utf8') !== previous;
727
+ } catch {
728
+ return true;
729
+ }
730
+ },
731
+ });
732
+ const waited = await waitForTurn([file], before);
733
+ if (!waited.ok) {
734
+ failure = waited.reason || waited.code || '等待世界母体结果失败';
735
+ continue;
736
+ }
737
+ try {
738
+ const candidates = parseWorldCandidates(fs.readFileSync(file, 'utf8'), {
739
+ constraintGenres: facets.genres || [],
740
+ });
741
+ return { ok: true, candidates, file };
742
+ } catch (err) {
743
+ failure = err && err.message ? err.message : String(err);
744
+ }
745
+ }
746
+ return { ok: false, message: '世界母体生成失败:' + (failure || '未知错误') };
747
+ }
748
+
749
+ async function chooseWorldCandidate(ctx, invocation, candidates, { allowReroll = true } = {}) {
750
+ const asked = await askOne(ctx, invocation, worldCandidateQuestion(candidates, { allowReroll }));
751
+ if (!asked.ok) return { ok: false, message: asked.message };
752
+ const selected = answerSingle(asked.answer);
753
+ if (!selected || selected === '取消') return { ok: true, cancelled: true };
754
+ if (selected.startsWith('换一批')) return { ok: true, reroll: true };
755
+ const exact = candidates.find((candidate) => candidate.title === selected);
756
+ if (exact) return { ok: true, candidate: exact };
757
+ const prefixed = candidates.find((candidate) => selected.startsWith(candidate.title + '('));
758
+ if (prefixed) return { ok: true, candidate: prefixed };
759
+ return { ok: false, message: '未识别世界母体选择:' + selected };
760
+ }
761
+
762
+ function makeFlow({
763
+ previous = null,
764
+ suggestion = null,
765
+ topic = null,
766
+ facetLabels,
767
+ facets,
768
+ styleSelection,
769
+ world,
770
+ scopeKinds,
771
+ targetPerKind,
772
+ }) {
773
+ return {
774
+ ...(previous && typeof previous === 'object' ? previous : {}),
775
+ status: 'world_selected',
776
+ source: {
777
+ suggestion_file: suggestion ? '_novel_topic_suggestion.json' : '',
778
+ suggestion_snapshot: suggestion || null,
779
+ suggestion_fingerprint: suggestionFingerprint(suggestion),
780
+ topic_file: topic ? '_novel_topic.json' : '',
781
+ topic_genre: topic?.genre || '',
782
+ },
783
+ facets,
784
+ facet_labels: facetLabels,
785
+ topic_genre: chooseTopicGenre(facets.genres || [], suggestion),
786
+ styles: {
787
+ mode: styleSelection.mode,
788
+ keys: [...(styleSelection.keys || [])],
789
+ },
790
+ world,
791
+ scope: {
792
+ kinds: scopeKinds,
793
+ target_per_kind: targetPerKind,
794
+ },
795
+ runs: Array.isArray(previous?.runs) ? previous.runs : [],
796
+ };
797
+ }
798
+
799
+ async function runInteractive(ctx, invocation, session, taskList, opts = {}) {
510
800
  const root = workspaceOf(session);
511
- // 两参数形式:/fancy-material <题材> <素材类型>。
512
- // 题材和素材类型都允许用户随便写:题材直接进提示词,素材类型由 LLM
513
- // 判断对应哪个 kind(不在 58 个内置 kind 里时自拟 kind)。
514
- const custom = opts.custom || null;
515
- const isCustom = Boolean(custom && custom.genre && custom.materialType);
516
- const customAllKinds = Boolean(custom && custom.allKinds);
517
- if (isCustom && !customAllKinds) focusRaw = custom.materialType;
518
- const focus = customAllKinds
519
- ? { query: '全部素材类型(all)', kinds: [] }
520
- : resolveFocus(focusRaw);
521
- if (!isCustom && focusRaw && !focus.kinds.length) {
522
- return notify(session, 'error', '❌ 未识别素材类型:' + focusRaw
523
- + '\n可用示例:地名、人名、姓氏、门派、技能、超能力、武器、颜色、特效、脑洞、人物性格、关系、场景。'
524
- + '\n如果素材类型是自定义的,请用两参数形式:/fancy-material <题材> <素材类型>');
801
+ const suggestion = readSuggestion(root);
802
+ const topic = readMinimalTopic(root);
803
+ const facetHint = suggestion || (topic ? { genre: topic.genre } : null);
804
+ if (abortRequested(invocation)) return notify(session, 'error', '🚫 操作已取消。');
805
+
806
+ const previousFlow = readMaterialFlow(root);
807
+ if (!opts.fresh && previousFlow && previousFlow.world) {
808
+ const asked = await askOne(ctx, invocation, {
809
+ id: 'material-existing-flow',
810
+ header: '素材 · 上次世界',
811
+ question: '检测到上次生成过素材。本次要沿用上次的世界母体,还是重新构建?',
812
+ detail: flowSummaryText(previousFlow),
813
+ options: [
814
+ { label: '沿用上次世界母体(推荐)', description: '只确认追加范围和数量,不重问 facet' },
815
+ { label: '重新构建世界母体', description: '重新选择 facet 和世界母体;旧素材保留' },
816
+ { label: '取消', description: '不生成素材' },
817
+ ],
818
+ });
819
+ if (!asked.ok) return notify(session, 'error', asked.message);
820
+ const choice = answerSingle(asked.answer);
821
+ if (!choice || choice === '取消') return notify(session, 'success', '操作已取消。');
822
+ if (choice.startsWith('沿用上次')) {
823
+ return runContinue(ctx, invocation, session, taskList, { styleRaw: opts.styleRaw });
824
+ }
825
+ }
826
+
827
+ taskList.progress('读取选题建议与 facet 选择');
828
+ await ensureMaterialDatabase(root);
829
+ const tools = deployMaterialTools(root);
830
+ if (!tools.ok) {
831
+ return notify(session, 'error', '❌ 部署素材查询脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
525
832
  }
526
- // 素材题材只认用户选题链路:
527
- // _novel_topic.json > _novel_topic_suggestion.json > 内置全题材。
528
- // 自定义两参数形式直接用用户给的题材,不走选题链路,也不弹框。
529
- let plan;
530
- if (isCustom) {
531
- plan = {
532
- mode: 'other',
533
- genres: [String(custom.genre).trim()],
534
- topicFile: null,
535
- customGenre: String(custom.genre).trim(),
536
- customMaterialType: String(custom.materialType).trim(),
537
- };
833
+ const registry = await loadStyleRegistry(root);
834
+
835
+ const facetResult = await askFacetSelections(ctx, invocation, facetHint, taskList);
836
+ if (!facetResult.ok) {
837
+ return notify(session, 'error', facetResult.message);
838
+ }
839
+ const { facetLabels } = facetResult;
840
+ const facets = facetStateFromLabels(facetLabels);
841
+ taskList.advance(1);
842
+
843
+ let styleSelection;
844
+ if (opts.styleRaw) {
845
+ styleSelection = styleSelectionFromRaw(opts.styleRaw);
538
846
  } else {
539
- plan = resolveMaterialTopic(root);
540
- if (!plan.mode) {
541
- const asked = await askUserQuestion(ctx, invocation, [{
542
- id: 'material-builtin-confirm',
543
- header: '没有选题记录',
544
- question: '当前没有执行过扫榜和 /fancy-topic,将使用内置全题材生成素材(男频 + 女频)。是否继续?',
545
- detail: '内置题材共 ' + BUILTIN_GENRES.length + ' 类;确认后所有 kind 都会按全题材生成。',
546
- options: [
547
- { label: '确认', description: '使用内置全题材生成素材' },
548
- { label: '取消', description: '不生成任何素材' },
549
- ],
550
- }]);
551
- if (!asked.ok) {
552
- return notify(session, 'error', asked.failure?.message || '❌ 提问失败');
553
- }
554
- const selected = asked.answer?.answers?.[0]?.selected?.[0];
555
- if (selected !== '确认') return notify(session, 'success', '操作已取消。');
556
- plan = { mode: 'builtin', genres: [...BUILTIN_GENRES], topicFile: null };
847
+ const asked = await askOne(ctx, invocation, styleQuestion(registry.styles));
848
+ if (!asked.ok) return notify(session, 'error', asked.message);
849
+ styleSelection = styleSelectionFromLabels(answerList(asked.answer), registry.styles);
850
+ }
851
+ const styleGenres = facets.genres.length ? facets.genres : expandGenre(suggestion?.genre || topic?.genre);
852
+ let selectedStyles = [];
853
+ try {
854
+ selectedStyles = resolveStyleObjects(registry, { genres: styleGenres, selection: styleSelection });
855
+ } catch (err) {
856
+ return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
857
+ }
858
+
859
+ const scopeAsked = await askOne(ctx, invocation, scopeQuestion());
860
+ if (!scopeAsked.ok) return notify(session, 'error', scopeAsked.message);
861
+ const scopeLabels = answerList(scopeAsked.answer);
862
+ const scopeKinds = resolveScopeKinds(scopeLabels);
863
+ if (!scopeKinds.length) return notify(session, 'error', '❌ 本次没有选择任何 kind。');
864
+
865
+ const countAsked = await askOne(ctx, invocation, countQuestion());
866
+ if (!countAsked.ok) return notify(session, 'error', countAsked.message);
867
+ const targetPerKind = parseCountAnswer(answerSingle(countAsked.answer));
868
+
869
+ const worldResult = await generateWorldCandidates({
870
+ root,
871
+ invocation,
872
+ taskList,
873
+ facets,
874
+ facetLabels,
875
+ suggestion,
876
+ scopeKinds,
877
+ styleSummary: styleBatchSummary(selectedStyles),
878
+ });
879
+ if (!worldResult.ok) {
880
+ return notify(session, 'error', (worldResult.aborted ? '🚫 ' : '❌ ') + worldResult.message);
881
+ }
882
+
883
+ let candidates = worldResult.candidates;
884
+ let selectedWorld = null;
885
+ let rerolls = 0;
886
+ while (!selectedWorld) {
887
+ if (abortRequested(invocation)) return notify(session, 'error', '🚫 操作已取消。');
888
+ const picked = await chooseWorldCandidate(ctx, invocation, candidates, { allowReroll: rerolls < 1 });
889
+ if (!picked.ok) return notify(session, 'error', picked.message);
890
+ if (picked.cancelled) return notify(session, 'success', '操作已取消。');
891
+ if (picked.reroll) {
892
+ rerolls += 1;
893
+ const again = await generateWorldCandidates({
894
+ root,
895
+ invocation,
896
+ taskList,
897
+ facets,
898
+ facetLabels,
899
+ suggestion,
900
+ scopeKinds,
901
+ styleSummary: styleBatchSummary(selectedStyles),
902
+ previousTitles: candidates.map((candidate) => candidate.title),
903
+ });
904
+ if (!again.ok) return notify(session, 'error', '❌ ' + again.message);
905
+ candidates = again.candidates;
906
+ continue;
557
907
  }
908
+ selectedWorld = picked.candidate;
909
+ }
910
+
911
+ const flow = makeFlow({
912
+ suggestion,
913
+ topic,
914
+ facetLabels,
915
+ facets,
916
+ styleSelection,
917
+ world: selectedWorld,
918
+ scopeKinds,
919
+ targetPerKind,
920
+ });
921
+ flow.styles.keys = selectedStyles.map((style) => style.style_key);
922
+ try {
923
+ writeMaterialFlow(root, flow);
924
+ } catch (err) {
925
+ return notify(session, 'error', '❌ 写入世界母体状态失败:' + (err && err.message ? err.message : String(err)));
558
926
  }
559
927
 
560
- const config = generationConfig();
928
+ return runGenerationWithPlan(ctx, invocation, session, taskList, {
929
+ root,
930
+ plan: {
931
+ mode: 'world',
932
+ genres: facets.genres,
933
+ topicGenre: flow.topic_genre,
934
+ topicFile: suggestion ? '_novel_topic_suggestion.json' : null,
935
+ suggestion,
936
+ kinds: scopeKinds,
937
+ },
938
+ world: selectedWorld,
939
+ facets,
940
+ facetLabels,
941
+ flow,
942
+ styleMode: styleSelection.mode,
943
+ styleKeys: selectedStyles.map((style) => style.style_key),
944
+ targetPerKind,
945
+ batchSize: generationConfig().batchSize,
946
+ });
947
+ }
948
+
949
+ async function runContinue(ctx, invocation, session, taskList, opts = {}) {
950
+ const root = workspaceOf(session);
951
+ const flow = readMaterialFlow(root);
952
+ if (!flow || !flow.world) {
953
+ return notify(session, 'error', [
954
+ '⚠️ 没有可沿用的上次选择。',
955
+ '先运行 /fancy-material 选择 facet 和世界母体;之后再用 /fancy-material continue 追加。',
956
+ ].join('\n'));
957
+ }
958
+ if (opts.fresh) {
959
+ return runInteractive(ctx, invocation, session, taskList, opts);
960
+ }
961
+ taskList.progress('读取上次世界母体选择');
561
962
  taskList.advance(1);
963
+ const scope = scopeQuestion({ currentKinds: flow.scope?.kinds || [] });
964
+ scope.detail = flowSummaryText(flow) + '\n\n' + scope.detail;
965
+ const scopeAsked = await askOne(ctx, invocation, scope);
966
+ if (!scopeAsked.ok) return notify(session, 'error', scopeAsked.message);
967
+ const scopeKinds = resolveScopeKinds(answerList(scopeAsked.answer), {
968
+ currentKinds: flow.scope?.kinds || [],
969
+ });
970
+ if (!scopeKinds.length) return notify(session, 'error', '❌ 本次没有选择任何 kind。');
971
+
972
+ const countAsked = await askOne(ctx, invocation, countQuestion());
973
+ if (!countAsked.ok) return notify(session, 'error', countAsked.message);
974
+ const targetPerKind = parseCountAnswer(answerSingle(countAsked.answer));
975
+
976
+ let styleMode = flow.styles?.mode || 'auto';
977
+ let styleKeys = Array.isArray(flow.styles?.keys) ? flow.styles.keys : [];
978
+ if (opts.styleRaw) {
979
+ const override = styleSelectionFromRaw(opts.styleRaw);
980
+ styleMode = override.mode;
981
+ styleKeys = override.keys;
982
+ }
983
+
984
+ const suggestion = flow.source?.suggestion_snapshot || readSuggestion(root);
985
+ const facets = flow.facets || {};
986
+ const facetLabels = flow.facet_labels || facets;
987
+ const nextFlow = {
988
+ ...flow,
989
+ status: 'world_selected',
990
+ facets,
991
+ facet_labels: facetLabels,
992
+ topic_genre: flow.topic_genre || chooseTopicGenre(facets.genres || [], suggestion),
993
+ styles: { mode: styleMode, keys: styleKeys },
994
+ scope: { kinds: scopeKinds, target_per_kind: targetPerKind },
995
+ };
996
+ try {
997
+ writeMaterialFlow(root, nextFlow);
998
+ } catch (err) {
999
+ return notify(session, 'error', '❌ 更新世界母体状态失败:' + (err && err.message ? err.message : String(err)));
1000
+ }
1001
+ taskList.advance(2);
1002
+ return runGenerationWithPlan(ctx, invocation, session, taskList, {
1003
+ root,
1004
+ plan: {
1005
+ mode: 'world',
1006
+ genres: facets.genres || [],
1007
+ topicGenre: nextFlow.topic_genre,
1008
+ topicFile: flow.source?.suggestion_file || (suggestion ? '_novel_topic_suggestion.json' : null),
1009
+ suggestion,
1010
+ kinds: scopeKinds,
1011
+ },
1012
+ world: flow.world,
1013
+ facets,
1014
+ facetLabels,
1015
+ flow: nextFlow,
1016
+ styleMode,
1017
+ styleKeys,
1018
+ targetPerKind,
1019
+ batchSize: generationConfig().batchSize,
1020
+ });
1021
+ }
1022
+
1023
+ export async function runGenerationWithPlan(ctx, invocation, session, taskList, opts = {}) {
1024
+ const root = opts.root || workspaceOf(session);
1025
+ const plan = opts.plan || {};
1026
+ const world = opts.world || null;
1027
+ const facets = opts.facets || {};
1028
+ const facetLabels = opts.facetLabels || facets;
1029
+ const flow = opts.flow || null;
1030
+ const targetPerKind = Math.max(1, Number(opts.targetPerKind) || generationConfig().targetPerKind);
1031
+ const batchSize = Math.max(1, Number(opts.batchSize) || generationConfig().batchSize);
1032
+ const genres = [...new Set((plan.genres || []).filter(Boolean))];
1033
+
562
1034
  await ensureMaterialDatabase(root);
563
1035
  const tools = deployMaterialTools(root);
564
1036
  if (!tools.ok) {
565
1037
  return notify(session, 'error', '❌ 部署素材查询脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
566
1038
  }
567
1039
  const database = materialDatabaseName(readWorkspace(root));
568
- const counts = await countByKind(root, plan.genres);
569
- // 自定义素材第一轮 kind 由 LLM 决定,这里先用一个占位项跑一条队列。
570
- const kinds = isCustom
571
- ? resolveCustomKinds({ materialType: custom.materialType, kinds: focus.kinds })
572
- : [...new Set(focus.kinds.length ? focus.kinds : MATERIAL_KINDS)];
573
- const planned = planMaterialQueue({ kinds, target: config.targetPerKind });
1040
+ const styleRegistry = await loadStyleRegistry(root);
1041
+ let selectedStyles = [];
1042
+ try {
1043
+ selectedStyles = resolveStyleObjects(styleRegistry, {
1044
+ genres: genres.length ? genres : expandGenre(plan.topicGenre),
1045
+ selection: {
1046
+ mode: opts.styleMode || 'auto',
1047
+ keys: Array.isArray(opts.styleKeys) ? opts.styleKeys : [],
1048
+ },
1049
+ });
1050
+ } catch (err) {
1051
+ return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
1052
+ }
1053
+ const styleBlock = stylePromptBlock(styleRegistry.styles, selectedStyles, { genres });
1054
+ const styleRules = selectedStyles.length
1055
+ ? '本次使用账号风格:' + styleSummaryText(selectedStyles) + ';风格核心优先于题材命名体例。'
1056
+ : '未指定账号风格(执行通用创作标准)。';
1057
+ const styleSummary = styleBatchSummary(selectedStyles);
1058
+ const counts = await countByKind(root, genres);
1059
+ const kinds = [...new Set((plan.kinds || []).filter((kind) => MATERIAL_KINDS.includes(kind)))];
1060
+ if (!kinds.length) {
1061
+ return notify(session, 'error', '❌ 本次没有可生成的 kind。');
1062
+ }
1063
+ const planned = planMaterialQueue({ kinds, target: targetPerKind });
1064
+ const scopeBlockText = '本次世界母体生成范围:'
1065
+ + kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、')
1066
+ + '。插件只按这个范围排队;不要生成未选中的 kind。';
574
1067
 
575
1068
  const startedAt = Date.now();
576
1069
  const batchId = batchIdOfNow();
@@ -579,37 +1072,43 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
579
1072
  fs.mkdirSync(runDir, { recursive: true });
580
1073
  const progressFile = path.join(runDir, 'progress.json');
581
1074
  const batchLog = path.join(runDir, 'batches.jsonl');
582
- const existing = await buildExistingIndex(root, plan.genres, stamp);
583
- const focusBlockText = isCustom
584
- ? customFocusBlock({
585
- genre: plan.customGenre,
586
- materialType: plan.customMaterialType,
587
- kinds: focus.kinds,
588
- allKinds: customAllKinds,
589
- })
590
- : '';
1075
+ const existing = await buildExistingIndex(root, genres, stamp);
1076
+ const worldBlock = renderWorldBlock({
1077
+ world,
1078
+ facets,
1079
+ facetLabels,
1080
+ suggestion: plan.suggestion,
1081
+ constraintGenres: genres,
1082
+ topicGenre: plan.topicGenre,
1083
+ });
1084
+ const worldSummary = renderWorldBatchSummary({
1085
+ world,
1086
+ facets,
1087
+ facetLabels,
1088
+ constraintGenres: genres,
1089
+ });
591
1090
  const base = renderBasePrompt({
592
- mode: plan.mode,
593
- genres: plan.genres,
594
- topicFile: plan.topicFile,
1091
+ mode: 'world',
1092
+ genres,
1093
+ topicFile: plan.topicFile || '(无)',
595
1094
  existingIndex: existing.file,
596
1095
  existingTotal: existing.count,
597
1096
  batchId,
598
1097
  workspace: root,
599
- focus,
1098
+ focus: null,
600
1099
  queryScript: tools.queryScript,
601
1100
  validateScript: tools.validateScript,
602
- targetPerKind: config.targetPerKind,
603
- batchSize: config.batchSize,
604
- focusBlockText,
605
- custom: isCustom ? { genre: plan.customGenre, materialType: plan.customMaterialType } : null,
1101
+ targetPerKind,
1102
+ batchSize,
1103
+ focusBlockText: scopeBlockText,
1104
+ styleBlock,
1105
+ styleRules,
1106
+ worldBlock,
606
1107
  });
607
1108
 
608
1109
  const queue = planned.all.map((item) => ({
609
- kind: item.kind === '__custom__' ? '' : item.kind,
610
- label: isCustom && !customAllKinds
611
- ? plan.customMaterialType
612
- : (KIND_LABELS[item.kind] || item.kind),
1110
+ kind: item.kind,
1111
+ label: KIND_LABELS[item.kind] || item.kind,
613
1112
  db_existing: Number(counts[item.kind]) || 0,
614
1113
  generated: item.generated,
615
1114
  target: item.target,
@@ -620,25 +1119,34 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
620
1119
  reason: '',
621
1120
  }));
622
1121
  const pending = queue.filter((item) => item.remaining > 0);
623
-
624
1122
  const report = {
625
1123
  status: 'running',
626
- mode: 'per_run_quota',
1124
+ mode: 'world',
627
1125
  started_at: new Date(startedAt).toISOString(),
628
1126
  updated_at: new Date(startedAt).toISOString(),
629
1127
  batch_id: batchId,
630
1128
  database,
631
1129
  workspace: root,
632
- target_per_kind: config.targetPerKind,
633
- batch_size: config.batchSize,
634
- genre_mode: plan.mode,
635
- genres: plan.genres,
636
- source: plan.mode === 'other' ? 'other' : 'builtin',
637
- ...(isCustom ? {
638
- custom_genre: plan.customGenre,
639
- custom_material_type: plan.customMaterialType,
640
- custom_all_kinds: customAllKinds,
641
- } : {}),
1130
+ target_per_kind: targetPerKind,
1131
+ batch_size: batchSize,
1132
+ genre_mode: 'world',
1133
+ genres,
1134
+ topic_genre: plan.topicGenre,
1135
+ source: 'builtin',
1136
+ world: world ? {
1137
+ world_id: world.world_id,
1138
+ title: world.title,
1139
+ core_conflict: world.core_conflict,
1140
+ cost: world.cost,
1141
+ } : null,
1142
+ facets,
1143
+ facet_labels: facetLabels,
1144
+ styles: selectedStyles.map((style) => ({
1145
+ style_key: style.style_key,
1146
+ style_name: style.style_name,
1147
+ style_type: style.style_type,
1148
+ genre_tags: style.genre_tags,
1149
+ })),
642
1150
  kinds: queue,
643
1151
  };
644
1152
  const saveProgress = () => {
@@ -647,6 +1155,30 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
647
1155
  };
648
1156
  saveProgress();
649
1157
 
1158
+ if (flow) {
1159
+ try {
1160
+ flow.status = 'generating';
1161
+ flow.facets = facets;
1162
+ flow.facet_labels = facetLabels;
1163
+ flow.topic_genre = plan.topicGenre;
1164
+ flow.world = world;
1165
+ flow.styles = { mode: opts.styleMode || 'auto', keys: selectedStyles.map((style) => style.style_key) };
1166
+ flow.scope = { kinds, target_per_kind: targetPerKind };
1167
+ flow.last_run = {
1168
+ run_id: batchId,
1169
+ run_dir: runDir,
1170
+ started_at: new Date(startedAt).toISOString(),
1171
+ status: 'running',
1172
+ target_per_kind: targetPerKind,
1173
+ kinds,
1174
+ imported: 0,
1175
+ };
1176
+ writeMaterialFlow(root, flow);
1177
+ } catch (err) {
1178
+ console.error('[fancy-material] 写入 flow 失败:' + (err && err.message ? err.message : String(err)));
1179
+ }
1180
+ }
1181
+
650
1182
  const waitForTurn = makeWaitForTurn(invocation, {
651
1183
  timeoutMs: GENERATION_TIMEOUT_MS,
652
1184
  idleGraceMs: GENERATION_IDLE_GRACE_MS,
@@ -671,7 +1203,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
671
1203
  let aborted = false;
672
1204
  let fatal = false;
673
1205
  let kindFailureStreak = 0;
674
- const maxBatchesPerKind = Math.max(1, Math.ceil(config.targetPerKind / config.batchSize) * 4);
1206
+ const maxBatchesPerKind = Math.max(1, Math.ceil(targetPerKind / batchSize) * 4);
675
1207
 
676
1208
  for (let index = 0; index < pending.length; index += 1) {
677
1209
  const item = pending[index];
@@ -680,7 +1212,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
680
1212
  let stalled = 0;
681
1213
  let lastReason = '';
682
1214
 
683
- while (item.generated < config.targetPerKind && item.batches < maxBatchesPerKind) {
1215
+ while (item.generated < targetPerKind && item.batches < maxBatchesPerKind) {
684
1216
  if (abortRequested(invocation)) {
685
1217
  aborted = true;
686
1218
  lastReason = '用户中断';
@@ -688,15 +1220,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
688
1220
  }
689
1221
  const next = nextBatchRequest({
690
1222
  generated: item.generated,
691
- target: config.targetPerKind,
692
- batchSize: config.batchSize,
1223
+ target: targetPerKind,
1224
+ batchSize,
693
1225
  });
694
1226
  if (!next.requestCount) break;
695
1227
 
696
1228
  const batchNo = item.batches + 1;
697
1229
  const file = path.join(
698
1230
  runDir,
699
- String(index + 1).padStart(3, '0') + '_' + (item.kind || 'custom') + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
1231
+ String(index + 1).padStart(3, '0') + '_' + item.kind + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
700
1232
  );
701
1233
  const includeBase = batchNo === 1 || batchNo % FULL_PROMPT_EVERY === 1;
702
1234
  let attemptDetail = '';
@@ -717,11 +1249,11 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
717
1249
  batchId,
718
1250
  attempt,
719
1251
  failures: attemptDetail ? [attemptDetail] : [],
720
- mode: plan.mode,
721
- genres: plan.genres,
722
- focus,
723
- targetPerKind: config.targetPerKind,
724
- batchSize: config.batchSize,
1252
+ mode: 'world',
1253
+ genres,
1254
+ focus: null,
1255
+ targetPerKind,
1256
+ batchSize,
725
1257
  kind: item.kind,
726
1258
  kindLabel: item.label,
727
1259
  kindIndex: index + 1,
@@ -734,11 +1266,12 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
734
1266
  queryScript: tools.queryScript,
735
1267
  existingIndex: existing.file,
736
1268
  existingTotal: existing.count,
737
- custom: isCustom
738
- ? { genre: plan.customGenre, materialType: plan.customMaterialType, allKinds: customAllKinds }
739
- : null,
740
- customKindPending: isCustom && !item.kind,
741
- sourceFixed: plan.mode === 'other' ? 'other' : 'builtin',
1269
+ custom: null,
1270
+ customKindPending: false,
1271
+ sourceFixed: 'builtin',
1272
+ styleSummary,
1273
+ worldBlock,
1274
+ worldSummary,
742
1275
  });
743
1276
  const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
744
1277
  if (!sent || sent.ok !== true) {
@@ -755,27 +1288,9 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
755
1288
  if (!waited.ok && waited.code === 'TIMEOUT') {
756
1289
  if (fs.existsSync(file)) {
757
1290
  const checked = await checkFile(file);
758
- const genreProblem = checked.code === 0 ? genreCoverageProblem(file, plan.genres) : '';
759
- let kindProblem = '';
760
- if (checked.code === 0) {
761
- if (isCustom && !item.kind) {
762
- const detected = detectSingleKind(file);
763
- if (detected.problem) {
764
- kindProblem = detected.problem;
765
- } else {
766
- item.kind = detected.kind;
767
- // 首次知道 kind,先把“导入前的库内数量”记下来,
768
- // 否则 beforeCount=0 会把同 kind 的历史素材也算成本次新增。
769
- item.db_existing = await countKind(root, item.kind, plan.genres);
770
- kindProblem = kindCoverageProblem(file, item.kind);
771
- }
772
- } else {
773
- kindProblem = kindCoverageProblem(file, item.kind);
774
- }
775
- }
776
- const sourceProblem = checked.code === 0
777
- ? sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin')
778
- : '';
1291
+ const genreProblem = checked.code === 0 ? genreCoverageProblem(file, genres) : '';
1292
+ const kindProblem = checked.code === 0 ? kindCoverageProblem(file, item.kind) : '';
1293
+ const sourceProblem = checked.code === 0 ? sourceCoverageProblem(file, 'builtin') : '';
779
1294
  if (checked.code === 0 && !genreProblem && !kindProblem && !sourceProblem) {
780
1295
  try {
781
1296
  await importFile(root, file, { noPrefetch: true });
@@ -785,7 +1300,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
785
1300
  break;
786
1301
  }
787
1302
  const beforeCount = item.db_existing;
788
- const afterCount = await countKind(root, item.kind, plan.genres);
1303
+ const afterCount = await countKind(root, item.kind, genres);
789
1304
  const imported = Math.max(0, afterCount - beforeCount);
790
1305
  item.db_existing = afterCount;
791
1306
  item.generated += imported;
@@ -793,7 +1308,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
793
1308
  batchCount += 1;
794
1309
  item.batches = batchNo;
795
1310
  item.imported += imported;
796
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
1311
+ item.remaining = Math.max(0, targetPerKind - item.generated);
797
1312
  try {
798
1313
  fs.appendFileSync(batchLog, JSON.stringify({
799
1314
  at: new Date().toISOString(),
@@ -830,29 +1345,17 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
830
1345
  attemptDetail = scriptDetail(checked);
831
1346
  continue;
832
1347
  }
833
- const genreProblem = genreCoverageProblem(file, plan.genres);
1348
+ const genreProblem = genreCoverageProblem(file, genres);
834
1349
  if (genreProblem) {
835
1350
  attemptDetail = genreProblem;
836
1351
  continue;
837
1352
  }
838
- if (isCustom && !item.kind) {
839
- // 自定义素材第一轮:模型自己选 kind,插件记住它,
840
- // 后续批次和计数都沿用同一个 kind。
841
- const detected = detectSingleKind(file);
842
- if (detected.problem) {
843
- attemptDetail = detected.problem;
844
- continue;
845
- }
846
- item.kind = detected.kind;
847
- // 同上:第一次知道 kind 时先取库内基线。
848
- item.db_existing = await countKind(root, item.kind, plan.genres);
849
- }
850
1353
  const kindProblem = kindCoverageProblem(file, item.kind);
851
1354
  if (kindProblem) {
852
1355
  attemptDetail = kindProblem;
853
1356
  continue;
854
1357
  }
855
- const sourceProblem = sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin');
1358
+ const sourceProblem = sourceCoverageProblem(file, 'builtin');
856
1359
  if (sourceProblem) {
857
1360
  attemptDetail = sourceProblem;
858
1361
  continue;
@@ -866,7 +1369,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
866
1369
  break;
867
1370
  }
868
1371
  const beforeCount = item.db_existing;
869
- const afterCount = await countKind(root, item.kind, plan.genres);
1372
+ const afterCount = await countKind(root, item.kind, genres);
870
1373
  const imported = Math.max(0, afterCount - beforeCount);
871
1374
  item.db_existing = afterCount;
872
1375
  item.generated += imported;
@@ -874,7 +1377,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
874
1377
  batchCount += 1;
875
1378
  item.batches = batchNo;
876
1379
  item.imported += imported;
877
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
1380
+ item.remaining = Math.max(0, targetPerKind - item.generated);
878
1381
  try {
879
1382
  fs.appendFileSync(batchLog, JSON.stringify({
880
1383
  at: new Date().toISOString(),
@@ -906,15 +1409,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
906
1409
  break;
907
1410
  }
908
1411
  saveProgress();
909
- if (item.generated >= config.targetPerKind) break;
1412
+ if (item.generated >= targetPerKind) break;
910
1413
  if (stalled >= MAX_STALLED_BATCHES) {
911
1414
  lastReason = '连续 ' + stalled + ' 批没有新增素材';
912
1415
  break;
913
1416
  }
914
1417
  }
915
1418
 
916
- item.remaining = Math.max(0, config.targetPerKind - item.generated);
917
- if (item.generated >= config.targetPerKind) {
1419
+ item.remaining = Math.max(0, targetPerKind - item.generated);
1420
+ if (item.generated >= targetPerKind) {
918
1421
  item.status = 'done';
919
1422
  completed.push({ ...item });
920
1423
  kindFailureStreak = 0;
@@ -938,18 +1441,42 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
938
1441
  report.imported_total = importedTotal;
939
1442
  report.batches = batchCount;
940
1443
  const notStarted = queue.filter((item) => item.status === 'pending' || item.status === 'running');
941
- report.not_started = notStarted.map((item) => item.kind || item.label || '自定义素材');
942
- report.status = aborted
1444
+ report.not_started = notStarted.map((item) => item.kind || item.label);
1445
+ const finalStatus = aborted
943
1446
  ? 'aborted'
944
1447
  : ((incomplete.length || notStarted.length || fatal || stopReason) ? 'incomplete' : 'complete');
1448
+ report.status = finalStatus;
945
1449
  report.stop_reason = stopReason;
946
1450
  saveProgress();
947
1451
  taskList.advance(3);
948
1452
 
1453
+ if (flow) {
1454
+ try {
1455
+ const finishedAt = new Date().toISOString();
1456
+ const summary = {
1457
+ run_id: batchId,
1458
+ run_dir: runDir,
1459
+ started_at: new Date(startedAt).toISOString(),
1460
+ finished_at: finishedAt,
1461
+ status: finalStatus,
1462
+ target_per_kind: targetPerKind,
1463
+ kinds,
1464
+ imported: importedTotal,
1465
+ batches: batchCount,
1466
+ };
1467
+ flow.status = finalStatus === 'complete' ? 'generated' : (finalStatus === 'aborted' ? 'aborted' : 'incomplete');
1468
+ flow.last_run = summary;
1469
+ flow.runs = [...(Array.isArray(flow.runs) ? flow.runs : []), summary].slice(-20);
1470
+ writeMaterialFlow(root, flow);
1471
+ } catch (err) {
1472
+ console.error('[fancy-material] 写入 flow 结果失败:' + (err && err.message ? err.message : String(err)));
1473
+ }
1474
+ }
1475
+
949
1476
  return notify(session, (aborted || incomplete.length || notStarted.length || stopReason) ? 'error' : 'success', generationRunText({
950
1477
  database,
951
- targetPerKind: config.targetPerKind,
952
- batchSize: config.batchSize,
1478
+ targetPerKind,
1479
+ batchSize,
953
1480
  elapsedMs: Date.now() - startedAt,
954
1481
  queue,
955
1482
  completed,
@@ -959,13 +1486,17 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
959
1486
  batches: batchCount,
960
1487
  total,
961
1488
  progressFile,
1489
+ styles: selectedStyles.map((style) => ({ style_key: style.style_key, style_name: style.style_name })),
1490
+ worldTitle: world?.title || '',
1491
+ flowFile: flow ? flowPath(root) : '',
962
1492
  aborted,
963
1493
  stopReason,
964
1494
  }));
965
1495
  }
966
1496
 
967
1497
  function materialTaskTitles(invocation) {
968
- const tokens = String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean);
1498
+ const parsed = splitStyleOption(String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean));
1499
+ const tokens = parsed.tokens.filter((token) => token !== '--fresh');
969
1500
  const command = (tokens[0] || '').toLowerCase();
970
1501
  if (command === 'help' || command === '?') return ['显示素材库帮助'];
971
1502
  if (command === 'prompt') return ['读取题材列表', '渲染素材提示词'];
@@ -975,22 +1506,33 @@ function materialTaskTitles(invocation) {
975
1506
  if (command === 'import') return ['检查备份文件', '导入 SurrealQL'];
976
1507
  if (command === 'init') return ['检查素材库', '初始化 schema 并部署查询脚本'];
977
1508
  if (command === 'remove') return ['确认删除范围', '删除素材库数据'];
978
- const special = new Set(['help', '?', 'load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
979
- if (!special.has(command) && tokens.length >= 2) {
980
- return ['解析自定义题材与素材类型', '读取已有素材索引', '分批生成并导入素材', '汇总生成结果'];
1509
+ if (command === 'continue' || command === '继续') {
1510
+ return ['读取上次世界母体', '确认本次追加范围', '分批生成并导入素材', '汇总生成结果'];
981
1511
  }
982
- return ['解析素材类型与工作区', '读取题材与已有素材索引', '分批生成并导入素材', '汇总生成结果'];
1512
+ return ['读取选题建议与 facet', '选择世界母体', '分批生成并导入素材', '汇总生成结果'];
983
1513
  }
984
1514
 
985
1515
  export async function apply(ctx) {
986
1516
  registerCommandWithTasks(ctx, {
987
1517
  name: 'fancy-material',
988
- description: '🧩 素材库 ( usage: /fancy-material [素材类型] | load <文件> | dump | export | import | init | remove | prompt | help )',
989
- input: { hint: '[素材类型] | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
1518
+ description: '🧩 素材库 ( usage: /fancy-material [--style <key>] [--fresh] | continue | load <文件> | dump | export | import | init | remove | prompt | help )',
1519
+ input: { hint: '[--style <key>] [--fresh] | continue | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
990
1520
  handler: async (invocation, taskList) => {
991
1521
  const session = invocation.agent.session;
992
1522
  const raw = String(invocation.rawInput || '').trim();
993
- const tokens = raw.split(/\s+/).filter(Boolean);
1523
+ const parsedStyle = splitStyleOption(raw.split(/\s+/).filter(Boolean));
1524
+ if (parsedStyle.missing) {
1525
+ return notify(session, 'error', '用法:--style <style_key>,多个用逗号分隔;可用 /fancy-douyin list 查看风格 key。');
1526
+ }
1527
+ let fresh = false;
1528
+ const tokens = parsedStyle.tokens.filter((token) => {
1529
+ if (token === '--fresh' || token === 'fresh') {
1530
+ fresh = true;
1531
+ return false;
1532
+ }
1533
+ return true;
1534
+ });
1535
+ const styleRaw = parsedStyle.styleRaw;
994
1536
  const command = (tokens[0] || '').toLowerCase();
995
1537
 
996
1538
  if (command === 'help' || command === '?') return notify(session, 'success', helpText());
@@ -1001,6 +1543,18 @@ export async function apply(ctx) {
1001
1543
  let root = null;
1002
1544
  try { root = workspaceOf(session); } catch { /* prompt also works outside a workspace */ }
1003
1545
  const genres = allKnownGenres(root);
1546
+ let styleBlock = '';
1547
+ let styleRules = '';
1548
+ if (root) {
1549
+ try {
1550
+ const registry = await loadStyleRegistry(root);
1551
+ const selected = selectStyles(registry.styles, { genres, explicit: 'auto', limit: 3 });
1552
+ styleBlock = stylePromptBlock(registry.styles, selected, { genres });
1553
+ styleRules = selected.length
1554
+ ? '本次预览风格:' + styleSummaryText(selected) + '(实际运行时按题材自动选择)'
1555
+ : '未指定账号风格(执行通用创作标准)。';
1556
+ } catch { /* 预览提示词不因风格库失败而中断 */ }
1557
+ }
1004
1558
  const rendered = renderBasePrompt({
1005
1559
  mode: 'builtin',
1006
1560
  genres,
@@ -1011,6 +1565,8 @@ export async function apply(ctx) {
1011
1565
  workspace: root || '(运行时提供)',
1012
1566
  focus: null,
1013
1567
  validateScript: VALIDATE_SCRIPT,
1568
+ styleBlock,
1569
+ styleRules,
1014
1570
  });
1015
1571
  return notify(session, 'success', promptDisplayText(rendered));
1016
1572
  } catch (err) {
@@ -1018,9 +1574,17 @@ export async function apply(ctx) {
1018
1574
  }
1019
1575
  }
1020
1576
 
1021
- const SPECIAL = new Set(['load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
1022
1577
  try {
1023
- if (!command) return await runGenerate(ctx, invocation, session, '', taskList);
1578
+ if (!command) {
1579
+ return await runInteractive(ctx, invocation, session, taskList, { styleRaw, fresh });
1580
+ }
1581
+ if (command === 'continue' || command === '继续') {
1582
+ if (tokens.length > 1) {
1583
+ return notify(session, 'error', '用法:/fancy-material continue(不接受额外参数)');
1584
+ }
1585
+ if (fresh) return await runInteractive(ctx, invocation, session, taskList, { styleRaw, fresh });
1586
+ return await runContinue(ctx, invocation, session, taskList, { styleRaw });
1587
+ }
1024
1588
  if (command === 'load') {
1025
1589
  if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material load <文件.jsonl>');
1026
1590
  return await runLoad(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
@@ -1043,25 +1607,12 @@ export async function apply(ctx) {
1043
1607
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material remove(不接受额外参数)');
1044
1608
  return await runRemove(ctx, invocation, session, taskList);
1045
1609
  }
1046
- // 两参数形式:/fancy-material <题材> <素材类型>。
1047
- // 题材和素材类型都可以随便写;source 记 other,不占用内置目录。
1048
- if (!SPECIAL.has(command) && tokens.length >= 2) {
1049
- const genre = stripQuotes(tokens[0]);
1050
- const materialTypeRaw = stripQuotes(tokens.slice(1).join(' '));
1051
- if (!genre || !materialTypeRaw) {
1052
- return notify(session, 'error', '用法:/fancy-material <题材> <素材类型|all>(两个参数都不能为空)');
1053
- }
1054
- const allKinds = materialTypeRaw.toLowerCase() === 'all';
1055
- return await runGenerate(ctx, invocation, session, '', taskList, {
1056
- custom: {
1057
- genre,
1058
- materialType: allKinds ? 'all' : materialTypeRaw,
1059
- allKinds,
1060
- },
1061
- });
1062
- }
1063
- // 其它单参数视为素材类型重点,例如 /fancy-material 地名
1064
- return await runGenerate(ctx, invocation, session, raw, taskList);
1610
+ return notify(session, 'error', [
1611
+ '❌ 旧的素材类型/题材参数已移除:' + tokens.join(' '),
1612
+ '现在用交互式流程:/fancy-material',
1613
+ '继续上次世界:/fancy-material continue',
1614
+ '重新构建世界:/fancy-material --fresh',
1615
+ ].join('\n'));
1065
1616
  } catch (err) {
1066
1617
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
1067
1618
  }