@cloud411716/fancy-webnovel 4.30.22 → 4.30.24

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.30.22",
3
+ "version": "4.30.24",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -1831,6 +1831,8 @@ export async function runGenerationWithPlan(ctx, invocation, session, taskList,
1831
1831
  manualBlock,
1832
1832
  team,
1833
1833
  signal: invocation.signal,
1834
+ validate: (candidate) => validateBatch(candidate, item, groupId),
1835
+ batchLabel: item.kind + (item.subkind ? '_' + item.subkind : ''),
1834
1836
  batchId,
1835
1837
  batchNo,
1836
1838
  });
@@ -153,6 +153,26 @@ function service(ctx, name) {
153
153
  }
154
154
  }
155
155
 
156
+ /** Read the child's terminal error from its durable session when available. */
157
+ async function subagentFailureDetail(ctx, childId) {
158
+ if (!childId) return '';
159
+ const query = service(ctx, 'sessionQuery');
160
+ if (!query || typeof query.readSession !== 'function') return '';
161
+ try {
162
+ const snapshot = await query.readSession(childId);
163
+ const events = Array.isArray(snapshot && snapshot.events) ? snapshot.events : [];
164
+ for (let index = events.length - 1; index >= 0; index -= 1) {
165
+ const event = events[index];
166
+ if (!event || event.type !== 'turn/end') continue;
167
+ const reason = event.data && event.data.reason;
168
+ if (!reason || reason.kind !== 'error') continue;
169
+ const message = reason.error && reason.error.message;
170
+ if (message) return String(message);
171
+ }
172
+ } catch { /* diagnostics only */ }
173
+ return '';
174
+ }
175
+
156
176
  function retargetPrompt(prompt, from, to) {
157
177
  return String(prompt || '').split(`目标文件(**绝对路径**):\`${from}\``).join(`目标文件(**绝对路径**):\`${to}\``);
158
178
  }
@@ -171,6 +191,27 @@ function writeJsonFile(file, value) {
171
191
  fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
172
192
  }
173
193
 
194
+ /** Preserve the previous attempt's A/B/review artifacts before a retry overwrites them. */
195
+ function archivePreviousTeamArtifacts(runDir) {
196
+ const metaFile = path.join(runDir, 'team-meta.json');
197
+ let meta;
198
+ try { meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')); } catch { return; }
199
+ const label = String(meta.batchLabel || meta.batchNo || 'batch').replace(/[^\w\u4e00-\u9fa5.-]+/g, '-');
200
+ const stamp = String(meta.startedAt || Date.now()).replace(/[:.]/g, '-');
201
+ const dir = path.join(runDir, 'team', `${label}-${stamp}`);
202
+ try {
203
+ fs.mkdirSync(dir, { recursive: true });
204
+ for (const name of [
205
+ 'team-prompt-a.txt', 'team-prompt-b.txt', 'team-rubric.md',
206
+ 'team-a.jsonl', 'team-b.jsonl', 'team-final.jsonl',
207
+ 'team-meta.json', 'team-review.json',
208
+ ]) {
209
+ const source = path.join(runDir, name);
210
+ if (fs.existsSync(source)) fs.copyFileSync(source, path.join(dir, name));
211
+ }
212
+ } catch { /* best-effort diagnostics */ }
213
+ }
214
+
174
215
  const TEAM_RUBRIC = `
175
216
  # Team 评审 rubric
176
217
 
@@ -260,7 +301,7 @@ function textFromBlocks(blocks) {
260
301
  .join('');
261
302
  }
262
303
 
263
- async function callSubagent({ subagents, parent, prompt, route, label, schema, signal }) {
304
+ async function callSubagent({ ctx, subagents, parent, prompt, route, label, schema, signal }) {
264
305
  let activation;
265
306
  try {
266
307
  activation = await subagents.startActivation({
@@ -286,7 +327,11 @@ async function callSubagent({ subagents, parent, prompt, route, label, schema, s
286
327
  }),
287
328
  ]);
288
329
  if (!result || result.stopReason !== 'completed') {
289
- return { ok: false, error: (result && (result.diagnostic || result.stopReason)) || '子 agent 未完成' };
330
+ const detail = (result && result.diagnostic)
331
+ || await subagentFailureDetail(ctx, activation.childId)
332
+ || (result && result.stopReason)
333
+ || '子 agent 未完成';
334
+ return { ok: false, error: detail, childId: activation.childId };
290
335
  }
291
336
  if (schema) {
292
337
  if (result.structured === undefined) return { ok: false, error: '子 agent 没有返回结构化结果' };
@@ -298,6 +343,7 @@ async function callSubagent({ subagents, parent, prompt, route, label, schema, s
298
343
  ok: false,
299
344
  error: err && err.message ? err.message : String(err),
300
345
  stack: err && err.stack ? String(err.stack) : '',
346
+ childId: activation && activation.childId,
301
347
  };
302
348
  } finally {
303
349
  if (timer) clearTimeout(timer);
@@ -340,6 +386,13 @@ const judgePrompt = (round, aPassed, bPassed, history, fileA, fileB, finalFile,
340
386
  '如果选择 PICK_A、PICK_B 或 MERGE,把最终 JSONL 写到 ' + finalFile + '。' +
341
387
  '返回 {"decision":"...","rationale":"..."}。';
342
388
 
389
+ const repairPrompt = (candidateFile, detail, finalFile) =>
390
+ '你是主编。当前最终文件没有通过插件校验。\n读取 ' + candidateFile + '。\n' +
391
+ '校验失败原因:\n' + String(detail || '').slice(0, 12000) + '\n' +
392
+ '只修复被点名的条目;保持其余条目、条数、group_id、subkind、world_id、genres 和 source 不变。' +
393
+ '把修复后的完整 JSONL 写到 ' + finalFile + '。' +
394
+ '返回 {"decision":"MERGE","rationale":"..."}。';
395
+
343
396
  /**
344
397
  * Run one batch through two generators, bounded cross-review, and a judge.
345
398
  * Uses the host subagent service directly so the plugin does not depend on a
@@ -355,6 +408,8 @@ export async function runTeamBatch({
355
408
  manualBlock = '',
356
409
  team,
357
410
  signal,
411
+ validate,
412
+ batchLabel = 'batch',
358
413
  batchId = '',
359
414
  batchNo = 1,
360
415
  }) {
@@ -372,6 +427,7 @@ export async function runTeamBatch({
372
427
  const promptAFile = path.join(runDir, 'team-prompt-a.txt');
373
428
  const promptBFile = path.join(runDir, 'team-prompt-b.txt');
374
429
  const rubricFile = path.join(runDir, 'team-rubric.md');
430
+ archivePreviousTeamArtifacts(runDir);
375
431
  for (const stale of [aFile, bFile, finalFile]) {
376
432
  try { fs.unlinkSync(stale); } catch { /* first run */ }
377
433
  }
@@ -383,6 +439,7 @@ export async function runTeamBatch({
383
439
  const reviewFile = path.join(runDir, 'team-review.json');
384
440
  const meta = {
385
441
  batchId,
442
+ batchLabel,
386
443
  batchNo,
387
444
  startedAt: new Date().toISOString(),
388
445
  generatorA: team.generatorA,
@@ -400,7 +457,7 @@ export async function runTeamBatch({
400
457
  const call = async (promptText, route, label, schema) => {
401
458
  if (calls >= maxCalls) return { ok: false, error: 'team workflow reached maxTotalCalls' };
402
459
  calls += 1;
403
- return callSubagent({ subagents, parent, prompt: promptText, route, label, schema, signal: parentSignal });
460
+ return callSubagent({ ctx, subagents, parent, prompt: promptText, route, label, schema, signal: parentSignal });
404
461
  };
405
462
 
406
463
  const [genA, genB] = await Promise.all([
@@ -433,7 +490,8 @@ export async function runTeamBatch({
433
490
 
434
491
  // Keep one call in reserve for the judge. A full review-response-revision
435
492
  // round costs up to six calls, so the budget check happens before each stage.
436
- const canSpend = (n) => calls + n <= maxCalls - 1;
493
+ const reserve = typeof validate === 'function' ? 2 : 1;
494
+ const canSpend = (n) => calls + n <= maxCalls - reserve;
437
495
 
438
496
  const saveReview = () => writeJsonFile(reviewFile, { round, aPassed, bPassed, calls, stopReason, history });
439
497
 
@@ -547,22 +605,69 @@ export async function runTeamBatch({
547
605
  meta.calls = calls;
548
606
  meta.finishedAt = new Date().toISOString();
549
607
 
550
- if (fs.existsSync(finalFile)) {
551
- fs.copyFileSync(finalFile, file);
552
- meta.finalFile = finalFile;
553
- writeJsonFile(metaFile, meta);
554
- return { ok: true, result: { round, aPassed, bPassed, calls, judge: judge.value }, finalFile };
608
+ let candidate = fs.existsSync(finalFile) ? finalFile : '';
609
+ let fallback = false;
610
+ if (!candidate) {
611
+ const decision = judge.value && judge.value.decision;
612
+ const pick = decision === 'PICK_A' ? aFile : decision === 'PICK_B' ? bFile : '';
613
+ if (pick && fs.existsSync(pick)) {
614
+ candidate = pick;
615
+ fallback = true;
616
+ }
555
617
  }
556
- const decision = judge.value && judge.value.decision;
557
- const fallback = decision === 'PICK_A' ? aFile : decision === 'PICK_B' ? bFile : '';
558
- if (fallback && fs.existsSync(fallback)) {
559
- fs.copyFileSync(fallback, file);
560
- meta.finalFile = fallback;
561
- meta.fallback = true;
618
+ if (!candidate) {
619
+ meta.error = '裁判没有写出 final.jsonl(decision=' + ((judge.value && judge.value.decision) || 'none') + ')';
562
620
  writeJsonFile(metaFile, meta);
563
- return { ok: true, result: { round, aPassed, bPassed, calls, judge: judge.value }, finalFile: fallback, fallback: true };
621
+ return { ok: false, error: 'team workflow 完成,但' + meta.error + '。' };
622
+ }
623
+
624
+ if (typeof validate === 'function') {
625
+ let checked = await validate(candidate);
626
+ if (!checked.ok) {
627
+ meta.validationError = checked.detail;
628
+ writeJsonFile(metaFile, meta);
629
+ if (calls >= maxCalls) {
630
+ meta.error = '最终文件未通过校验,且没有剩余调用可修复:' + checked.detail;
631
+ writeJsonFile(metaFile, meta);
632
+ return { ok: false, error: meta.error };
633
+ }
634
+ const repaired = await call(
635
+ repairPrompt(candidate, checked.detail, finalFile),
636
+ team.judge,
637
+ 'repair',
638
+ JUDGE_SCHEMA,
639
+ );
640
+ if (!repaired.ok) {
641
+ meta.error = '裁判修复失败:' + repaired.error;
642
+ writeJsonFile(metaFile, meta);
643
+ return { ok: false, error: meta.error };
644
+ }
645
+ meta.repair = repaired.value;
646
+ if (!fs.existsSync(finalFile)) {
647
+ meta.error = '裁判修复后没有写出 final.jsonl';
648
+ writeJsonFile(metaFile, meta);
649
+ return { ok: false, error: meta.error };
650
+ }
651
+ checked = await validate(finalFile);
652
+ if (!checked.ok) {
653
+ meta.error = '裁判修复后仍未通过校验:' + checked.detail;
654
+ writeJsonFile(metaFile, meta);
655
+ return { ok: false, error: meta.error };
656
+ }
657
+ candidate = finalFile;
658
+ fallback = false;
659
+ }
564
660
  }
565
- meta.error = '裁判没有写出 final.jsonl(decision=' + (decision || 'none') + ')';
661
+
662
+ fs.copyFileSync(candidate, file);
663
+ meta.finalFile = candidate;
664
+ meta.fallback = fallback;
665
+ meta.validated = typeof validate === 'function';
566
666
  writeJsonFile(metaFile, meta);
567
- return { ok: false, error: 'team workflow 完成,但' + meta.error + '。' };
667
+ return {
668
+ ok: true,
669
+ result: { round, aPassed, bPassed, calls, judge: judge.value },
670
+ finalFile: candidate,
671
+ fallback,
672
+ };
568
673
  }