@cloud411716/fancy-webnovel 4.0.3 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,6 +13,7 @@ import path from 'path';
13
13
  import { fileURLToPath } from 'url';
14
14
 
15
15
  import { askUserQuestion, llmFollowup, notify, spawnScript } from '#infra';
16
+ import { registerCommandWithTasks } from '#task-list';
16
17
  import {
17
18
  localIsoString,
18
19
  readSecrets,
@@ -27,7 +28,7 @@ import { makeWaitForTurn } from '../fancy-story-builder/writing-driver.js';
27
28
  import { exportMaterials } from './exporter.js';
28
29
  import { allKnownGenres } from './genres.js';
29
30
  import { buildExistingIndex, countByKind, countKind } from './inventory.js';
30
- import { KIND_LABELS, MATERIAL_KINDS, focusBlock, renderKindTable, resolveFocus } from './kinds.js';
31
+ import { KIND_LABELS, MATERIAL_KINDS, customFocusBlock, focusBlock, renderKindTable, resolveFocus } from './kinds.js';
31
32
  import { nextBatchRequest, planMaterialQueue } from './queue.js';
32
33
  import { deployMaterialTools } from './tool-deploy.js';
33
34
  import {
@@ -112,13 +113,22 @@ function renderBasePrompt({
112
113
  validateScript,
113
114
  targetPerKind = DEFAULT_TARGET_PER_KIND,
114
115
  batchSize = DEFAULT_BATCH_SIZE,
116
+ focusBlockText = '',
117
+ custom = null,
115
118
  }) {
119
+ const sourceFixed = mode === 'other' ? 'other' : 'builtin';
120
+ const sourceNote = sourceFixed === 'other'
121
+ ? '本次是用户指定题材 + 素材类型的自定义素材,source 固定写 `other`;不要写成 `builtin`。'
122
+ : '`other` 只用于库外手工导入的自定义素材。';
123
+ const kindRule = sourceFixed === 'other'
124
+ ? '下面素材类型总表之一;本次是 `other` 自定义素材,kind 可以不在表内,但同一批所有记录必须使用同一个 kind'
125
+ : '下面素材类型总表之一;builtin 素材必须在表内';
116
126
  return renderPrompt(readPrompt(), {
117
127
  MATERIAL_MODE: mode,
118
128
  GENRES: (genres || []).join('、'),
119
129
  TOPIC_FILE: topicFile || '(无)',
120
130
  KIND_TABLE: renderKindTable(),
121
- FOCUS_BLOCK: focusBlock(focus),
131
+ FOCUS_BLOCK: focusBlockText || focusBlock(focus),
122
132
  TARGET_PER_KIND: String(targetPerKind),
123
133
  BATCH_SIZE: String(batchSize),
124
134
  AUDIENCE: '男频 / 女频 / 通用',
@@ -130,6 +140,9 @@ function renderBasePrompt({
130
140
  QUERY_SCRIPT: queryScript || QUERY_SCRIPT,
131
141
  VALIDATE_SCRIPT: validateScript || VALIDATE_SCRIPT,
132
142
  WORKSPACE: workspace || '(运行时提供)',
143
+ SOURCE_FIXED: sourceFixed,
144
+ SOURCE_NOTE: sourceNote,
145
+ KIND_RULE: kindRule,
133
146
  });
134
147
  }
135
148
 
@@ -229,7 +242,8 @@ function kindCoverageProblem(file, kind) {
229
242
  * (the database defaults it to builtin), but it must not mark entries as
230
243
  * `other` to bypass the builtin kind list.
231
244
  */
232
- function sourceCoverageProblem(file) {
245
+ function sourceCoverageProblem(file, expectedSource = 'builtin') {
246
+ const expected = expectedSource === 'other' ? 'other' : 'builtin';
233
247
  let text;
234
248
  try { text = fs.readFileSync(file, 'utf8'); } catch { return ''; }
235
249
  const lines = text.split(/\r?\n/);
@@ -239,14 +253,58 @@ function sourceCoverageProblem(file) {
239
253
  if (!line) continue;
240
254
  let record;
241
255
  try { record = JSON.parse(line); } catch { continue; }
242
- if (record.source !== undefined && record.source !== 'builtin') {
256
+ if (expected === 'other') {
257
+ // 自定义素材必须显式写 other;省略 source 会被数据库默认成 builtin,
258
+ // 正好落进内置目录的 kind 约束里,后面必然出问题。
259
+ if (record.source !== 'other') {
260
+ bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」是 ${record.source || '未写 source'}`);
261
+ }
262
+ } else if (record.source !== undefined && record.source !== 'builtin') {
243
263
  bad.push(`第 ${i + 1} 条「${record.name || record.id || '未命名'}」是 ${record.source}`);
244
264
  }
245
265
  }
246
266
  if (!bad.length) return '';
247
- return '生成批次只能写 source=builtin,但文件里出现了其它 source:' + bad.slice(0, 8).join('、')
248
- + (bad.length > 8 ? `等 ${bad.length} 条` : '')
249
- + '。请把 source 改成 builtin,或省略 source(数据库默认 builtin)。';
267
+ return expected === 'other'
268
+ ? '自定义素材必须写 source=other,但以下记录不是:' + bad.slice(0, 8).join('、')
269
+ + (bad.length > 8 ? `等 ${bad.length} 条` : '')
270
+ + '。请把 source 改成 other 后重新写入。'
271
+ : '生成批次只能写 source=builtin,但文件里出现了其它 source:' + bad.slice(0, 8).join('、')
272
+ + (bad.length > 8 ? `等 ${bad.length} 条` : '')
273
+ + '。请把 source 改成 builtin,或省略 source(数据库默认 builtin)。';
274
+ }
275
+
276
+ /**
277
+ * 自定义素材第一轮没有预设 kind:由 LLM 自己选。
278
+ * 这里检查同一批是否只出现一个 kind,并把该 kind 返回给插件,
279
+ * 后续批次和计数都沿用它。
280
+ */
281
+ function detectSingleKind(file) {
282
+ let text;
283
+ try { text = fs.readFileSync(file, 'utf8'); } catch {
284
+ return { kind: '', problem: '目标文件读不出来' };
285
+ }
286
+ const kinds = [];
287
+ const seen = new Set();
288
+ const lines = text.split(/\r?\n/);
289
+ for (let i = 0; i < lines.length; i += 1) {
290
+ const line = lines[i].trim();
291
+ if (!line) continue;
292
+ let record;
293
+ try { record = JSON.parse(line); } catch { continue; }
294
+ const kind = String(record.kind || '').trim();
295
+ if (!kind) return { kind: '', problem: `第 ${i + 1} 行没有 kind` };
296
+ // kind 会进文件名、数据库和后续提示词;模型自拟的 kind 必须限制成
297
+ // 安全的小写 snake_case,防止 `/`、`..` 或空格污染路径。
298
+ if (!/^[a-z][a-z0-9_]{0,119}$/.test(kind)) {
299
+ return { kind: '', problem: `第 ${i + 1} 行的 kind 不合法(只允许小写字母/数字/下划线):${kind}` };
300
+ }
301
+ if (!seen.has(kind)) { seen.add(kind); kinds.push(kind); }
302
+ }
303
+ if (!kinds.length) return { kind: '', problem: '文件里没有素材记录' };
304
+ if (kinds.length > 1) {
305
+ return { kind: '', problem: '同一批自定义素材只能使用一个 kind,但出现了:' + kinds.join('、') };
306
+ }
307
+ return { kind: kinds[0], problem: '' };
250
308
  }
251
309
 
252
310
  function importEnv(root) {
@@ -290,7 +348,7 @@ function batchIdOfNow() {
290
348
  return 'material-' + (stamp || String(Date.now()));
291
349
  }
292
350
 
293
- async function runImport(ctx, invocation, session, rawPath) {
351
+ async function runImport(ctx, invocation, session, rawPath, taskList) {
294
352
  const root = workspaceOf(session);
295
353
  const { input, file } = resolveInputFile(rawPath, session, root);
296
354
  if (!input || !file) {
@@ -303,11 +361,13 @@ async function runImport(ctx, invocation, session, rawPath) {
303
361
  return notify(session, 'error', '❌ 未找到素材文件,或目标不是普通文件:' + file);
304
362
  }
305
363
 
364
+ taskList.advance(1);
306
365
  const checked = await checkFile(file);
307
366
  if (checked.code !== 0) {
308
367
  return notify(session, 'error', validationFailedText({ file, detail: scriptDetail(checked) }));
309
368
  }
310
369
 
370
+ taskList.advance(2);
311
371
  await ensureMaterialDatabase(root);
312
372
  const database = materialDatabaseName(readWorkspace(root));
313
373
  let importedText;
@@ -327,9 +387,10 @@ async function runImport(ctx, invocation, session, rawPath) {
327
387
  }));
328
388
  }
329
389
 
330
- async function runInit(ctx, invocation, session) {
390
+ async function runInit(ctx, invocation, session, taskList) {
331
391
  const root = workspaceOf(session);
332
392
  const result = await ensureMaterialDatabase(root);
393
+ taskList.advance(1);
333
394
  const tools = deployMaterialTools(root);
334
395
  if (!tools.ok) {
335
396
  return notify(session, 'error', [
@@ -352,7 +413,7 @@ async function runInit(ctx, invocation, session) {
352
413
  ].join('\n'));
353
414
  }
354
415
 
355
- async function runRemove(ctx, invocation, session) {
416
+ async function runRemove(ctx, invocation, session, taskList) {
356
417
  const root = workspaceOf(session);
357
418
  const asked = await askUserQuestion(ctx, invocation, [{
358
419
  id: 'confirm_material_remove',
@@ -368,6 +429,7 @@ async function runRemove(ctx, invocation, session) {
368
429
  }
369
430
  const selected = asked.answer?.answers?.[0]?.selected?.[0];
370
431
  if (selected !== '删除素材库') return notify(session, 'success', '操作已取消。');
432
+ taskList.advance(1);
371
433
  const result = await removeMaterialDatabase(root);
372
434
  return notify(session, 'success', [
373
435
  '✅ 已删除素材库:' + result.database,
@@ -375,44 +437,64 @@ async function runRemove(ctx, invocation, session) {
375
437
  ].join('\n'));
376
438
  }
377
439
 
378
- async function runExport(ctx, invocation, session) {
440
+ async function runExport(ctx, invocation, session, taskList) {
379
441
  const root = workspaceOf(session);
442
+ taskList.advance(1);
380
443
  await ensureMaterialDatabase(root);
381
444
  const result = await exportMaterials(root);
382
445
  return notify(session, 'success', exportResultText(result));
383
446
  }
384
447
 
385
- async function runGenerate(ctx, invocation, session, focusRaw = '') {
448
+ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, opts = {}) {
386
449
  const root = workspaceOf(session);
450
+ // 两参数形式:/fancy-material <题材> <素材类型>。
451
+ // 题材和素材类型都允许用户随便写:题材直接进提示词,素材类型由 LLM
452
+ // 判断对应哪个 kind(不在 54 个内置 kind 里时自拟 kind)。
453
+ const custom = opts.custom || null;
454
+ const isCustom = Boolean(custom && custom.genre && custom.materialType);
455
+ if (isCustom) focusRaw = custom.materialType;
387
456
  const focus = resolveFocus(focusRaw);
388
- if (focusRaw && !focus.kinds.length) {
457
+ if (!isCustom && focusRaw && !focus.kinds.length) {
389
458
  return notify(session, 'error', '❌ 未识别素材类型:' + focusRaw
390
- + '\n可用示例:地名、人名、姓氏、门派、技能、超能力、武器、颜色、特效、脑洞、人物性格、关系、场景。');
459
+ + '\n可用示例:地名、人名、姓氏、门派、技能、超能力、武器、颜色、特效、脑洞、人物性格、关系、场景。'
460
+ + '\n如果素材类型是自定义的,请用两参数形式:/fancy-material <题材> <素材类型>');
391
461
  }
392
462
  // 素材题材只认用户选题链路:
393
463
  // _novel_topic.json > _novel_topic_suggestion.json > 内置全题材。
394
- // 不再从 topic_decision 里猜题材,避免素材和用户最终选题脱节。
395
- let plan = resolveMaterialTopic(root);
396
- if (!plan.mode) {
397
- const asked = await askUserQuestion(ctx, invocation, [{
398
- id: 'material-builtin-confirm',
399
- header: '没有选题记录',
400
- question: '当前没有执行过扫榜和 /fancy-topic,将使用内置全题材生成素材(男频 + 女频)。是否继续?',
401
- detail: '内置题材共 ' + BUILTIN_GENRES.length + ' 类;确认后所有 kind 都会按全题材生成。',
402
- options: [
403
- { label: '确认', description: '使用内置全题材生成素材' },
404
- { label: '取消', description: '不生成任何素材' },
405
- ],
406
- }]);
407
- if (!asked.ok) {
408
- return notify(session, 'error', asked.failure?.message || '❌ 提问失败');
464
+ // 自定义两参数形式直接用用户给的题材,不走选题链路,也不弹框。
465
+ let plan;
466
+ if (isCustom) {
467
+ plan = {
468
+ mode: 'other',
469
+ genres: [String(custom.genre).trim()],
470
+ topicFile: null,
471
+ customGenre: String(custom.genre).trim(),
472
+ customMaterialType: String(custom.materialType).trim(),
473
+ };
474
+ } else {
475
+ plan = resolveMaterialTopic(root);
476
+ if (!plan.mode) {
477
+ const asked = await askUserQuestion(ctx, invocation, [{
478
+ id: 'material-builtin-confirm',
479
+ header: '没有选题记录',
480
+ question: '当前没有执行过扫榜和 /fancy-topic,将使用内置全题材生成素材(男频 + 女频)。是否继续?',
481
+ detail: '内置题材共 ' + BUILTIN_GENRES.length + ' 类;确认后所有 kind 都会按全题材生成。',
482
+ options: [
483
+ { label: '确认', description: '使用内置全题材生成素材' },
484
+ { label: '取消', description: '不生成任何素材' },
485
+ ],
486
+ }]);
487
+ if (!asked.ok) {
488
+ return notify(session, 'error', asked.failure?.message || '❌ 提问失败');
489
+ }
490
+ const selected = asked.answer?.answers?.[0]?.selected?.[0];
491
+ if (selected !== '确认') return notify(session, 'success', '操作已取消。');
492
+ plan = { mode: 'builtin', genres: [...BUILTIN_GENRES], topicFile: null };
409
493
  }
410
- const selected = asked.answer?.answers?.[0]?.selected?.[0];
411
- if (selected !== '确认') return notify(session, 'success', '操作已取消。');
412
- plan = { mode: 'builtin', genres: [...BUILTIN_GENRES], topicFile: null };
413
494
  }
414
495
 
415
496
  const config = generationConfig();
497
+ taskList.advance(1);
416
498
  await ensureMaterialDatabase(root);
417
499
  const tools = deployMaterialTools(root);
418
500
  if (!tools.ok) {
@@ -420,7 +502,8 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
420
502
  }
421
503
  const database = materialDatabaseName(readWorkspace(root));
422
504
  const counts = await countByKind(root, plan.genres);
423
- const kinds = [...new Set(focus.kinds.length ? focus.kinds : MATERIAL_KINDS)];
505
+ // 自定义素材第一轮 kind 由 LLM 决定,这里先用一个占位项跑一条队列。
506
+ const kinds = [...new Set(focus.kinds.length ? focus.kinds : (isCustom ? ['__custom__'] : MATERIAL_KINDS))];
424
507
  const planned = planMaterialQueue({ kinds, target: config.targetPerKind });
425
508
 
426
509
  const startedAt = Date.now();
@@ -431,6 +514,13 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
431
514
  const progressFile = path.join(runDir, 'progress.json');
432
515
  const batchLog = path.join(runDir, 'batches.jsonl');
433
516
  const existing = await buildExistingIndex(root, plan.genres, stamp);
517
+ const focusBlockText = isCustom
518
+ ? customFocusBlock({
519
+ genre: plan.customGenre,
520
+ materialType: plan.customMaterialType,
521
+ kinds: focus.kinds,
522
+ })
523
+ : '';
434
524
  const base = renderBasePrompt({
435
525
  mode: plan.mode,
436
526
  genres: plan.genres,
@@ -444,11 +534,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
444
534
  validateScript: tools.validateScript,
445
535
  targetPerKind: config.targetPerKind,
446
536
  batchSize: config.batchSize,
537
+ focusBlockText,
538
+ custom: isCustom ? { genre: plan.customGenre, materialType: plan.customMaterialType } : null,
447
539
  });
448
540
 
449
541
  const queue = planned.all.map((item) => ({
450
- kind: item.kind,
451
- label: KIND_LABELS[item.kind] || item.kind,
542
+ kind: item.kind === '__custom__' ? '' : item.kind,
543
+ label: isCustom
544
+ ? plan.customMaterialType
545
+ : (KIND_LABELS[item.kind] || item.kind),
452
546
  db_existing: Number(counts[item.kind]) || 0,
453
547
  generated: item.generated,
454
548
  target: item.target,
@@ -472,6 +566,11 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
472
566
  batch_size: config.batchSize,
473
567
  genre_mode: plan.mode,
474
568
  genres: plan.genres,
569
+ source: plan.mode === 'other' ? 'other' : 'builtin',
570
+ ...(isCustom ? {
571
+ custom_genre: plan.customGenre,
572
+ custom_material_type: plan.customMaterialType,
573
+ } : {}),
475
574
  kinds: queue,
476
575
  };
477
576
  const saveProgress = () => {
@@ -493,6 +592,9 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
493
592
  },
494
593
  });
495
594
 
595
+ taskList.advance(2);
596
+ taskList.watchTurns(invocation);
597
+
496
598
  const completed = [];
497
599
  const incomplete = [];
498
600
  let importedTotal = 0;
@@ -505,6 +607,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
505
607
 
506
608
  for (let index = 0; index < pending.length; index += 1) {
507
609
  const item = pending[index];
610
+ taskList.progress(`分批生成并导入素材(${index + 1}/${pending.length}:${item.label})`);
508
611
  item.status = 'running';
509
612
  let stalled = 0;
510
613
  let lastReason = '';
@@ -525,7 +628,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
525
628
  const batchNo = item.batches + 1;
526
629
  const file = path.join(
527
630
  runDir,
528
- String(index + 1).padStart(3, '0') + '_' + item.kind + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
631
+ String(index + 1).padStart(3, '0') + '_' + (item.kind || 'custom') + '_' + String(batchNo).padStart(2, '0') + '.jsonl',
529
632
  );
530
633
  const includeBase = batchNo === 1 || batchNo % FULL_PROMPT_EVERY === 1;
531
634
  let attemptDetail = '';
@@ -563,6 +666,9 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
563
666
  queryScript: tools.queryScript,
564
667
  existingIndex: existing.file,
565
668
  existingTotal: existing.count,
669
+ custom: isCustom ? { genre: plan.customGenre, materialType: plan.customMaterialType } : null,
670
+ customKindPending: isCustom && !item.kind,
671
+ sourceFixed: plan.mode === 'other' ? 'other' : 'builtin',
566
672
  });
567
673
  const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
568
674
  if (!sent || sent.ok !== true) {
@@ -580,8 +686,26 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
580
686
  if (fs.existsSync(file)) {
581
687
  const checked = await checkFile(file);
582
688
  const genreProblem = checked.code === 0 ? genreCoverageProblem(file, plan.genres) : '';
583
- const kindProblem = checked.code === 0 ? kindCoverageProblem(file, item.kind) : '';
584
- const sourceProblem = checked.code === 0 ? sourceCoverageProblem(file) : '';
689
+ let kindProblem = '';
690
+ if (checked.code === 0) {
691
+ if (isCustom && !item.kind) {
692
+ const detected = detectSingleKind(file);
693
+ if (detected.problem) {
694
+ kindProblem = detected.problem;
695
+ } else {
696
+ item.kind = detected.kind;
697
+ // 首次知道 kind,先把“导入前的库内数量”记下来,
698
+ // 否则 beforeCount=0 会把同 kind 的历史素材也算成本次新增。
699
+ item.db_existing = await countKind(root, item.kind, plan.genres);
700
+ kindProblem = kindCoverageProblem(file, item.kind);
701
+ }
702
+ } else {
703
+ kindProblem = kindCoverageProblem(file, item.kind);
704
+ }
705
+ }
706
+ const sourceProblem = checked.code === 0
707
+ ? sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin')
708
+ : '';
585
709
  if (checked.code === 0 && !genreProblem && !kindProblem && !sourceProblem) {
586
710
  try {
587
711
  await importFile(root, file, { noPrefetch: true });
@@ -641,12 +765,24 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
641
765
  attemptDetail = genreProblem;
642
766
  continue;
643
767
  }
768
+ if (isCustom && !item.kind) {
769
+ // 自定义素材第一轮:模型自己选 kind,插件记住它,
770
+ // 后续批次和计数都沿用同一个 kind。
771
+ const detected = detectSingleKind(file);
772
+ if (detected.problem) {
773
+ attemptDetail = detected.problem;
774
+ continue;
775
+ }
776
+ item.kind = detected.kind;
777
+ // 同上:第一次知道 kind 时先取库内基线。
778
+ item.db_existing = await countKind(root, item.kind, plan.genres);
779
+ }
644
780
  const kindProblem = kindCoverageProblem(file, item.kind);
645
781
  if (kindProblem) {
646
782
  attemptDetail = kindProblem;
647
783
  continue;
648
784
  }
649
- const sourceProblem = sourceCoverageProblem(file);
785
+ const sourceProblem = sourceCoverageProblem(file, plan.mode === 'other' ? 'other' : 'builtin');
650
786
  if (sourceProblem) {
651
787
  attemptDetail = sourceProblem;
652
788
  continue;
@@ -732,12 +868,13 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
732
868
  report.imported_total = importedTotal;
733
869
  report.batches = batchCount;
734
870
  const notStarted = queue.filter((item) => item.status === 'pending' || item.status === 'running');
735
- report.not_started = notStarted.map((item) => item.kind);
871
+ report.not_started = notStarted.map((item) => item.kind || item.label || '自定义素材');
736
872
  report.status = aborted
737
873
  ? 'aborted'
738
874
  : ((incomplete.length || notStarted.length || fatal || stopReason) ? 'incomplete' : 'complete');
739
875
  report.stop_reason = stopReason;
740
876
  saveProgress();
877
+ taskList.advance(3);
741
878
 
742
879
  return notify(session, (aborted || incomplete.length || notStarted.length || stopReason) ? 'error' : 'success', generationRunText({
743
880
  database,
@@ -757,12 +894,28 @@ async function runGenerate(ctx, invocation, session, focusRaw = '') {
757
894
  }));
758
895
  }
759
896
 
897
+ function materialTaskTitles(invocation) {
898
+ const tokens = String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean);
899
+ const command = (tokens[0] || '').toLowerCase();
900
+ if (command === 'help' || command === '?') return ['显示素材库帮助'];
901
+ if (command === 'prompt') return ['读取题材列表', '渲染素材提示词'];
902
+ if (command === 'import') return ['校验素材文件', '校验 JSONL 行', '写入素材库'];
903
+ if (command === 'export') return ['读取素材库', '导出 JSONL'];
904
+ if (command === 'init') return ['检查素材库', '初始化 schema 并部署查询脚本'];
905
+ if (command === 'remove') return ['确认删除范围', '删除素材库数据'];
906
+ const special = new Set(['help', '?', 'import', 'export', 'init', 'remove', 'prompt']);
907
+ if (!special.has(command) && tokens.length >= 2) {
908
+ return ['解析自定义题材与素材类型', '读取已有素材索引', '分批生成并导入素材', '汇总生成结果'];
909
+ }
910
+ return ['解析素材类型与工作区', '读取题材与已有素材索引', '分批生成并导入素材', '汇总生成结果'];
911
+ }
912
+
760
913
  export async function apply(ctx) {
761
- ctx.commands.register({
914
+ registerCommandWithTasks(ctx, {
762
915
  name: 'fancy-material',
763
916
  description: '🧩 素材库 ( usage: /fancy-material [素材类型] | import <文件> | init | remove | prompt | export | help )',
764
917
  input: { hint: '[素材类型] | import <文件> | init | remove | prompt | export' },
765
- handler: async (invocation) => {
918
+ handler: async (invocation, taskList) => {
766
919
  const session = invocation.agent.session;
767
920
  const raw = String(invocation.rawInput || '').trim();
768
921
  const tokens = raw.split(/\s+/).filter(Boolean);
@@ -793,29 +946,42 @@ export async function apply(ctx) {
793
946
  }
794
947
  }
795
948
 
949
+ const SPECIAL = new Set(['import', 'export', 'init', 'remove', 'prompt']);
796
950
  try {
797
- if (!command) return await runGenerate(ctx, invocation, session, '');
951
+ if (!command) return await runGenerate(ctx, invocation, session, '', taskList);
798
952
  if (command === 'import') {
799
953
  if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material import <文件.jsonl>');
800
- return await runImport(ctx, invocation, session, tokens.slice(1).join(' '));
954
+ return await runImport(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
801
955
  }
802
956
  if (command === 'export') {
803
957
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material export(不接受额外参数)');
804
- return await runExport(ctx, invocation, session);
958
+ return await runExport(ctx, invocation, session, taskList);
805
959
  }
806
960
  if (command === 'init') {
807
961
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material init(不接受额外参数)');
808
- return await runInit(ctx, invocation, session);
962
+ return await runInit(ctx, invocation, session, taskList);
809
963
  }
810
964
  if (command === 'remove') {
811
965
  if (tokens.length > 1) return notify(session, 'error', '用法:/fancy-material remove(不接受额外参数)');
812
- return await runRemove(ctx, invocation, session);
966
+ return await runRemove(ctx, invocation, session, taskList);
813
967
  }
814
- // 其它参数视为素材类型重点,例如 /fancy-material 地名
815
- return await runGenerate(ctx, invocation, session, raw);
968
+ // 两参数形式:/fancy-material <题材> <素材类型>。
969
+ // 题材和素材类型都可以随便写;source 记 other,不占用内置目录。
970
+ if (!SPECIAL.has(command) && tokens.length >= 2) {
971
+ const genre = stripQuotes(tokens[0]);
972
+ const materialType = stripQuotes(tokens.slice(1).join(' '));
973
+ if (!genre || !materialType) {
974
+ return notify(session, 'error', '用法:/fancy-material <题材> <素材类型>(两个参数都不能为空)');
975
+ }
976
+ return await runGenerate(ctx, invocation, session, '', taskList, {
977
+ custom: { genre, materialType },
978
+ });
979
+ }
980
+ // 其它单参数视为素材类型重点,例如 /fancy-material 地名
981
+ return await runGenerate(ctx, invocation, session, raw, taskList);
816
982
  } catch (err) {
817
983
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
818
984
  }
819
985
  },
820
- });
986
+ }, materialTaskTitles);
821
987
  }
@@ -311,3 +311,26 @@ export function focusBlock(focus) {
311
311
  const list = focus.kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、');
312
312
  return `本批用户指定的重点是「${focus.query}」,对应 ${list}。插件会按顺序逐个 kind 排队,每个批次只写一个 kind;不要生成其它 kind。其他质量、题材、追加和查询规则继续适用。`;
313
313
  }
314
+
315
+ /**
316
+ * 自定义题材 + 自定义素材类型的本批规则。
317
+ *
318
+ * 与内置目录最大的区别:
319
+ * - source 必须是 other;
320
+ * - 素材类型可以不在 54 个 kind 里,模型可以自拟 kind;
321
+ * - 同一批只能用一个 kind,插件会在第一轮之后记住它。
322
+ */
323
+ export function customFocusBlock({ genre, materialType, kinds = [] }) {
324
+ const known = Array.isArray(kinds) && kinds.length
325
+ ? '用户素材类型匹配到内置 kind:' + kinds.map((kind) => `\`${kind}\`(${KIND_LABELS[kind] || kind})`).join('、') + '。'
326
+ : '用户素材类型不在内置表内;请自拟一个稳定的小写 snake_case kind(例如 `custom_xxx`)。';
327
+ return `本批是**用户自定义素材**:题材「${genre}」,素材类型「${materialType}」。
328
+
329
+ - ${known}
330
+ - 如果素材类型明显对应总表里的某个 kind,优先使用内置 kind;否则自拟 kind。
331
+ - 同一批文件里的所有记录必须使用**同一个** kind;下一批插件会沿用你这次确定的 kind。
332
+ - source 固定写 \`other\`,不要写 \`builtin\`。
333
+ - tags 和 genres 都是数组:先想清楚这个素材能适配哪些题材/标签,再全部写进去。例如「都市高武」相关素材可以写 tags: ["都市","高武","都市高武", ...],genres: ["都市高武","都市","高武"]。
334
+ - genres 必须原样包含用户题材「${genre}」;可以再附加其它适用题材(1–5 个)。
335
+ - 其他质量、查询、追加规则继续适用。`;
336
+ }