deep-chapter-generation.ts 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458
  1. import type { LlmConfig } from "@/stores/wiki-store";
  2. import {
  3. streamChat,
  4. type ChatMessage,
  5. type RequestOverrides,
  6. type StreamCallbacks,
  7. } from "@/lib/llm-client";
  8. import { useWikiStore } from "@/stores/wiki-store";
  9. import type { AiWorkflowMode } from "@/lib/agent/workflow-mode";
  10. import type { AgentActivityEvent, AgentActivityKind } from "@/lib/agent/types";
  11. import type { LlmRequestCacheTrace } from "@/lib/llm-request-trace";
  12. import {
  13. isReasoningDisabled,
  14. isReasoningOnlyResponseError,
  15. withReasoningDisabled,
  16. } from "@/lib/reasoning-retry";
  17. import {
  18. charsPerTokenForLanguage,
  19. planChapterRequestBudget,
  20. } from "@/lib/context-budget";
  21. import {
  22. getEffectiveMaxOutputTokens,
  23. thinkingMinMaxTokens,
  24. } from "@/lib/llm-providers";
  25. import { USER_ABORT_MESSAGE, rethrowIfUserAbort, throwIfAborted } from "@/lib/user-abort";
  26. import {
  27. buildContextPack,
  28. contextPackToPrompt,
  29. type ContextPack,
  30. } from "./context-engine";
  31. import {
  32. collectWritingEntityWebSearch,
  33. type CollectWritingEntityWebSearchInput,
  34. type WritingEntityWebSearchResult,
  35. } from "./writing-entity-web-search";
  36. import { resolveDefaultModel, resolveNovelModel } from "./model-resolver";
  37. import { reviewChapter, type NovelReviewResult } from "./review-adapter";
  38. import type { TaskRouteResult } from "./task-router";
  39. import type { GoldenThreeChapterRequest } from "./golden-three-chapters";
  40. import {
  41. type ParsedChapterPlanComplianceResult,
  42. parseChapterPlanComplianceResult,
  43. runChapterPlanComplianceCheck,
  44. runChapterPlanDeviationRepair,
  45. shouldRepairChapterPlanDeviation,
  46. } from "./chapter-plan-compliance";
  47. import { buildChapterPlanExecutionSummary } from "./chapter-plan-execution-summary";
  48. import { capOutlineSourcesToBudget } from "./outline-context-index";
  49. import {
  50. contractToTaskBriefText,
  51. fallbackParseChapterExecutionContract,
  52. runChapterExecutionContractBuild,
  53. type ChapterExecutionContract,
  54. } from "./chapter-execution-contract";
  55. import {
  56. executionReportToToolSummary,
  57. extractExecutionRepairItems,
  58. runChapterExecutionReportCheck,
  59. type ChapterExecutionReport,
  60. } from "./chapter-execution-report";
  61. import {
  62. resolveChapterLengthSpec,
  63. type ChapterLengthSpec,
  64. buildDeepChapterBriefPrompt,
  65. buildDeepChapterDraftPrompt,
  66. buildDeepChapterExpansionPrompt,
  67. buildDeepChapterFinalPolishPrompt,
  68. buildDeepChapterRevisionPrompt,
  69. buildStableContextPrefix,
  70. } from "./deep-chapter-prompts";
  71. export interface DeepChapterGenerationInput {
  72. projectPath: string;
  73. userRequest: string;
  74. chapterNumber?: number;
  75. goldenThreeChapter?: GoldenThreeChapterRequest;
  76. dismantlingReferenceDirective?: string;
  77. llmConfig: LlmConfig;
  78. aiWorkflowMode?: AiWorkflowMode;
  79. resumeCheckpoint?: DeepChapterGenerationResumeCheckpoint;
  80. /** 用户在会话层确认的章节计划,作为写作任务书的权威依据注入 brief 阶段。 */
  81. planBlueprint?: string;
  82. /** 本轮启用的写作 Skill 约束,注入任务书/初稿/返修(稳定缓存前缀之后)。 */
  83. skillsPrompt?: string;
  84. }
  85. export interface DeepChapterGenerationCallbacks {
  86. onThinking?: (content: string) => void;
  87. onFinalContent?: (content: string) => void;
  88. onCheckpoint?: (checkpoint: DeepChapterGenerationResumeCheckpoint) => void;
  89. onWorkflowEvent?: (event: ChapterWorkflowEvent) => void;
  90. onActivityEvent?: (event: AgentActivityEvent) => void;
  91. onRequestTrace?: (trace: LlmRequestCacheTrace) => void;
  92. }
  93. export interface DeepChapterGenerationResult {
  94. finalContent: string;
  95. taskBrief: string;
  96. draftContent: string;
  97. reviewResults: NovelReviewResult[];
  98. revised: boolean;
  99. planCompliance?: string;
  100. executionReport?: string;
  101. }
  102. export type ChapterWorkflowEventType = "started" | "completed" | "error";
  103. export interface ChapterWorkflowEvent {
  104. type: ChapterWorkflowEventType;
  105. id: string;
  106. name: string;
  107. title: string;
  108. detail?: string;
  109. result?: string;
  110. params?: Record<string, unknown>;
  111. timestamp: number;
  112. }
  113. export type DeepChapterGenerationResumeStage =
  114. | "after_context"
  115. | "after_task_brief"
  116. | "after_draft"
  117. | "after_review"
  118. | "after_revision";
  119. export interface DeepChapterGenerationResumeCheckpoint {
  120. version: 1;
  121. originalRequest: string;
  122. chapterNumber?: number;
  123. stage: DeepChapterGenerationResumeStage;
  124. planBlueprint?: string;
  125. executionContract?: ChapterExecutionContract;
  126. taskBrief?: string;
  127. draftContent?: string;
  128. reviewResults?: NovelReviewResult[];
  129. currentContent?: string;
  130. }
  131. export interface DeepChapterGenerationDeps {
  132. buildContextPack: typeof buildContextPack;
  133. contextPackToPrompt: typeof contextPackToPrompt;
  134. reviewChapter: typeof reviewChapter;
  135. runChapterPlanComplianceCheck?: typeof runChapterPlanComplianceCheck;
  136. runChapterPlanDeviationRepair?: typeof runChapterPlanDeviationRepair;
  137. runChapterExecutionContractBuild?: typeof runChapterExecutionContractBuild;
  138. runChapterExecutionReportCheck?: typeof runChapterExecutionReportCheck;
  139. streamChat: (
  140. config: LlmConfig,
  141. messages: ChatMessage[],
  142. callbacks: StreamCallbacks,
  143. signal?: AbortSignal,
  144. requestOverrides?: RequestOverrides,
  145. ) => Promise<void>;
  146. collectWritingEntityWebSearch?: (
  147. input: CollectWritingEntityWebSearchInput,
  148. ) => Promise<WritingEntityWebSearchResult>;
  149. }
  150. const defaultDeps: DeepChapterGenerationDeps = {
  151. buildContextPack,
  152. contextPackToPrompt,
  153. reviewChapter,
  154. streamChat,
  155. };
  156. const REPEAT_CHECK_MIN_CHARS = 600;
  157. const REPEAT_WINDOW_CHARS = 120;
  158. const REPEAT_HIT_LIMIT = 3;
  159. function hasUsableChapterExecutionContract(contract: ChapterExecutionContract | null): contract is ChapterExecutionContract {
  160. if (!contract) return false;
  161. const hasSceneChecks = contract.sceneSteps.some((step) =>
  162. step.title.trim() ||
  163. step.purpose.trim() ||
  164. step.conflict.trim() ||
  165. step.turn.trim() ||
  166. step.requiredOutcome.trim() ||
  167. step.acceptanceCriteria.some((item) => item.trim()),
  168. );
  169. const hasInformationFlow =
  170. contract.informationFlow.reveal.some((item) => item.trim()) ||
  171. contract.informationFlow.hide.some((item) => item.trim()) ||
  172. contract.informationFlow.mislead.some((item) => item.trim()) ||
  173. contract.informationFlow.foreshadow.some((item) => item.trim());
  174. return (
  175. hasSceneChecks ||
  176. contract.mustDo.some((item) => item.trim()) ||
  177. contract.mustAvoid.some((item) => item.trim()) ||
  178. contract.dialogueGoals.some((item) => item.trim()) ||
  179. hasInformationFlow ||
  180. Boolean(contract.finalHook.trim())
  181. );
  182. }
  183. /** The mandatory outline may consume at most this share of the total context
  184. * budget. The remainder is left for memory/settings/search context so the
  185. * outline can never crowd the whole window out on its own. */
  186. const DEEP_CHAPTER_OUTLINE_MAX_FRAC = 0.7;
  187. /** Floor (tokens) for the non-outline context so a huge outline still leaves
  188. * some room for memory/settings/search hits. */
  189. const DEEP_CHAPTER_REST_TOKEN_FLOOR = 2000;
  190. export function shouldUseDeepChapterGeneration(
  191. _route: TaskRouteResult | null,
  192. enabled: boolean,
  193. ): boolean {
  194. void enabled;
  195. return (
  196. _route?.intent === "write_chapter" ||
  197. _route?.intent === "continue_chapter" ||
  198. _route?.intent === "rewrite_chapter" ||
  199. _route?.intent === "polish_chapter"
  200. );
  201. }
  202. interface ChapterWorkflowProfile {
  203. mode: AiWorkflowMode;
  204. runExecutionContractBuild: boolean;
  205. runAiReview: boolean;
  206. runFinalPolish: boolean;
  207. runPostRevisionReview: boolean;
  208. runPostDraftPlanAudits: boolean;
  209. completionTitle: string;
  210. completionResultPrefix: string;
  211. }
  212. function resolveChapterWorkflowProfile(
  213. mode: AiWorkflowMode | undefined,
  214. ): ChapterWorkflowProfile {
  215. const resolvedMode = mode ?? "strict";
  216. if (resolvedMode === "fast") {
  217. return {
  218. mode: "fast",
  219. runExecutionContractBuild: false,
  220. runAiReview: false,
  221. runFinalPolish: false,
  222. runPostRevisionReview: false,
  223. runPostDraftPlanAudits: false,
  224. completionTitle: "完成快速写作",
  225. completionResultPrefix: "快速模式写作完成",
  226. };
  227. }
  228. if (resolvedMode === "standard") {
  229. return {
  230. mode: "standard",
  231. runExecutionContractBuild: false,
  232. runAiReview: false,
  233. runFinalPolish: false,
  234. runPostRevisionReview: false,
  235. runPostDraftPlanAudits: false,
  236. completionTitle: "完成标准写作",
  237. completionResultPrefix: "标准模式写作完成",
  238. };
  239. }
  240. return {
  241. mode: "strict",
  242. runExecutionContractBuild: true,
  243. runAiReview: true,
  244. runFinalPolish: true,
  245. runPostRevisionReview: true,
  246. runPostDraftPlanAudits: true,
  247. completionTitle: "完成多任务写作循环",
  248. completionResultPrefix: "多任务写作循环完成",
  249. };
  250. }
  251. interface ChapterWorkflowStepSpec {
  252. name: string;
  253. title: string;
  254. detail?: string;
  255. params?: Record<string, unknown>;
  256. }
  257. function emitChapterWorkflowEvent(
  258. callbacks: DeepChapterGenerationCallbacks,
  259. type: ChapterWorkflowEventType,
  260. spec: ChapterWorkflowStepSpec,
  261. payload: {
  262. result?: string;
  263. detail?: string;
  264. params?: Record<string, unknown>;
  265. } = {},
  266. ): void {
  267. callbacks.onWorkflowEvent?.({
  268. type,
  269. id: `deep_chapter:${spec.name}`,
  270. name: spec.name,
  271. title: spec.title,
  272. detail: payload.detail ?? spec.detail,
  273. result: payload.result,
  274. params: {
  275. ...(spec.params ?? {}),
  276. ...(payload.params ?? {}),
  277. },
  278. timestamp: Date.now(),
  279. });
  280. }
  281. function emitDeepChapterActivity(
  282. callbacks: DeepChapterGenerationCallbacks,
  283. input: {
  284. id: string;
  285. stageId: string;
  286. kind: AgentActivityKind;
  287. title: string;
  288. content: string;
  289. timestamp?: number;
  290. },
  291. ): void {
  292. callbacks.onActivityEvent?.({
  293. id: input.id,
  294. stageId: input.stageId,
  295. kind: input.kind,
  296. title: input.title,
  297. content: input.content.trim() || "本阶段未返回可展示内容。",
  298. timestamp: input.timestamp ?? Date.now(),
  299. });
  300. }
  301. function emitDeepChapterStageStarted(
  302. callbacks: DeepChapterGenerationCallbacks,
  303. stageId: string,
  304. title: string,
  305. summary: string,
  306. ): void {
  307. emitDeepChapterActivity(callbacks, {
  308. id: `deep_chapter:${stageId}:started:${Date.now()}`,
  309. stageId,
  310. kind: "stage_started",
  311. title: "进入阶段",
  312. content: `${title}\n${summary}`,
  313. });
  314. }
  315. function startChapterWorkflowStep(
  316. callbacks: DeepChapterGenerationCallbacks,
  317. spec: ChapterWorkflowStepSpec,
  318. ): void {
  319. emitChapterWorkflowEvent(callbacks, "started", spec);
  320. }
  321. function completeChapterWorkflowStep(
  322. callbacks: DeepChapterGenerationCallbacks,
  323. spec: ChapterWorkflowStepSpec,
  324. result: string,
  325. params?: Record<string, unknown>,
  326. ): void {
  327. emitChapterWorkflowEvent(callbacks, "completed", spec, { result, params });
  328. }
  329. function errorChapterWorkflowStep(
  330. callbacks: DeepChapterGenerationCallbacks,
  331. spec: ChapterWorkflowStepSpec,
  332. error: unknown,
  333. ): void {
  334. emitChapterWorkflowEvent(callbacks, "error", spec, {
  335. result: getErrorMessage(error),
  336. });
  337. }
  338. async function runChapterWorkflowStep<T>(
  339. callbacks: DeepChapterGenerationCallbacks,
  340. spec: ChapterWorkflowStepSpec,
  341. action: () => Promise<T>,
  342. formatResult: (value: T) => string,
  343. formatParams?: (value: T) => Record<string, unknown>,
  344. ): Promise<T> {
  345. startChapterWorkflowStep(callbacks, spec);
  346. try {
  347. const value = await action();
  348. completeChapterWorkflowStep(
  349. callbacks,
  350. spec,
  351. formatResult(value),
  352. formatParams?.(value),
  353. );
  354. return value;
  355. } catch (error) {
  356. errorChapterWorkflowStep(callbacks, spec, error);
  357. throw error;
  358. }
  359. }
  360. function createResumeCheckpoint(
  361. input: DeepChapterGenerationInput,
  362. stage: DeepChapterGenerationResumeStage,
  363. data: Partial<DeepChapterGenerationResumeCheckpoint> = {},
  364. ): DeepChapterGenerationResumeCheckpoint {
  365. const originalRequest =
  366. input.resumeCheckpoint?.originalRequest?.trim() || input.userRequest.trim();
  367. return {
  368. version: 1,
  369. originalRequest,
  370. chapterNumber: input.resumeCheckpoint?.chapterNumber ?? input.chapterNumber,
  371. stage,
  372. ...data,
  373. };
  374. }
  375. function checkpointStageAtLeast(
  376. checkpoint: DeepChapterGenerationResumeCheckpoint | null | undefined,
  377. target: DeepChapterGenerationResumeStage,
  378. ): boolean {
  379. if (!checkpoint) return false;
  380. const order: DeepChapterGenerationResumeStage[] = [
  381. "after_context",
  382. "after_task_brief",
  383. "after_draft",
  384. "after_review",
  385. "after_revision",
  386. ];
  387. return order.indexOf(checkpoint.stage) >= order.indexOf(target);
  388. }
  389. function hasCheckpointTaskBrief(
  390. checkpoint?: DeepChapterGenerationResumeCheckpoint | null,
  391. ): checkpoint is DeepChapterGenerationResumeCheckpoint & { taskBrief: string } {
  392. return (
  393. Boolean(checkpoint?.taskBrief?.trim()) &&
  394. checkpointStageAtLeast(checkpoint, "after_task_brief")
  395. );
  396. }
  397. function hasCheckpointDraft(
  398. checkpoint?: DeepChapterGenerationResumeCheckpoint | null,
  399. ): checkpoint is DeepChapterGenerationResumeCheckpoint & {
  400. taskBrief: string;
  401. draftContent: string;
  402. } {
  403. return (
  404. hasCheckpointTaskBrief(checkpoint) &&
  405. Boolean(checkpoint.draftContent?.trim()) &&
  406. checkpointStageAtLeast(checkpoint, "after_draft")
  407. );
  408. }
  409. function hasCheckpointReview(
  410. checkpoint?: DeepChapterGenerationResumeCheckpoint | null,
  411. ): checkpoint is DeepChapterGenerationResumeCheckpoint & {
  412. taskBrief: string;
  413. draftContent: string;
  414. reviewResults: NovelReviewResult[];
  415. } {
  416. return (
  417. hasCheckpointDraft(checkpoint) &&
  418. Array.isArray(checkpoint.reviewResults) &&
  419. checkpointStageAtLeast(checkpoint, "after_review")
  420. );
  421. }
  422. function hasCheckpointRevision(
  423. checkpoint?: DeepChapterGenerationResumeCheckpoint | null,
  424. ): checkpoint is DeepChapterGenerationResumeCheckpoint & {
  425. taskBrief: string;
  426. draftContent: string;
  427. reviewResults: NovelReviewResult[];
  428. currentContent: string;
  429. } {
  430. return (
  431. hasCheckpointReview(checkpoint) &&
  432. Boolean(checkpoint.currentContent?.trim()) &&
  433. checkpointStageAtLeast(checkpoint, "after_revision")
  434. );
  435. }
  436. export async function runDeepChapterGeneration(
  437. input: DeepChapterGenerationInput,
  438. callbacks: DeepChapterGenerationCallbacks = {},
  439. deps: DeepChapterGenerationDeps = defaultDeps,
  440. signal?: AbortSignal,
  441. ): Promise<DeepChapterGenerationResult> {
  442. throwIfAborted(signal);
  443. const resumeCheckpoint = input.resumeCheckpoint;
  444. const novelConfig = useWikiStore.getState().novelConfig;
  445. const writingConfig = resolveWritingConfig(input.llmConfig);
  446. const workflowConfig = resolveDefaultModel(input.llmConfig);
  447. const deAiConfig = resolveNovelModel(input.llmConfig, novelConfig, "deAi");
  448. const workflowProfile = resolveChapterWorkflowProfile(input.aiWorkflowMode);
  449. const lengthSpec = resolveCurrentChapterLengthSpec();
  450. const { loadSmartDeAiSkill } = await import("./de-ai-adapter");
  451. const planBlueprint =
  452. input.planBlueprint?.trim() || resumeCheckpoint?.planBlueprint?.trim() || undefined;
  453. const contextRequest = [
  454. input.userRequest.trim(),
  455. planBlueprint ? `用户已确认的章节计划:\n${planBlueprint}` : "",
  456. ].filter(Boolean).join("\n\n");
  457. const workflowBaseParams = {
  458. mode: workflowProfile.mode,
  459. chapterNumber: input.chapterNumber ?? null,
  460. };
  461. const planExecutionSummary = buildChapterPlanExecutionSummary(planBlueprint ?? "");
  462. let executionContract: ChapterExecutionContract | null =
  463. resumeCheckpoint?.executionContract ?? null;
  464. if (executionContract && !hasUsableChapterExecutionContract(executionContract)) {
  465. executionContract = null;
  466. }
  467. let executionContractText = "";
  468. if (!executionContract && workflowProfile.runExecutionContractBuild && planBlueprint) {
  469. try {
  470. const buildContract = deps.runChapterExecutionContractBuild || runChapterExecutionContractBuild;
  471. executionContract = callbacks.onRequestTrace
  472. ? await buildContract(workflowConfig, planBlueprint, signal, callbacks.onRequestTrace)
  473. : await buildContract(workflowConfig, planBlueprint, signal);
  474. } catch (error) {
  475. rethrowIfUserAbort(error, signal);
  476. console.warn("[Deep Chapter] 执行清单生成失败,使用本地兜底解析:", error);
  477. executionContract = fallbackParseChapterExecutionContract(planBlueprint);
  478. }
  479. }
  480. if (hasUsableChapterExecutionContract(executionContract)) {
  481. executionContractText = contractToTaskBriefText(executionContract);
  482. } else {
  483. executionContract = null;
  484. }
  485. const createCheckpoint = (
  486. stage: DeepChapterGenerationResumeStage,
  487. data: Partial<DeepChapterGenerationResumeCheckpoint> = {},
  488. ) => createResumeCheckpoint(input, stage, {
  489. planBlueprint,
  490. executionContract: executionContract ?? undefined,
  491. ...data,
  492. });
  493. const contextWorkflowStep: ChapterWorkflowStepSpec = {
  494. name: "chapter_context",
  495. title: "读取上下文",
  496. detail: "读取大纲、章节目标、近期剧情、人物状态、伏笔和时间线。",
  497. params: workflowBaseParams,
  498. };
  499. if (!resumeCheckpoint) {
  500. startChapterWorkflowStep(callbacks, contextWorkflowStep);
  501. }
  502. // 将在阶段1构建contextPack后再加载skill(需要contextPack用于场景检测)
  503. let customDeAiSkill: string | null = null;
  504. // 阶段0:前情分析。快速模式始终跳过;标准/严格模式跟随写作设置。
  505. // 记忆库的近期摘要与上一章结尾仍会注入。
  506. let previousChaptersAnalysis = "";
  507. if (
  508. workflowProfile.mode !== "fast" &&
  509. input.chapterNumber &&
  510. input.chapterNumber > 1 &&
  511. !resumeCheckpoint &&
  512. novelConfig.deepPreviousChaptersAnalysis
  513. ) {
  514. callbacks.onThinking?.(
  515. formatStageThinking("阶段0:前情分析", "正在读取并分析前3章完整内容..."),
  516. );
  517. const { analyzePreviousChapters } =
  518. await import("./previous-chapters-analysis");
  519. try {
  520. previousChaptersAnalysis = await analyzePreviousChapters(
  521. input.projectPath,
  522. input.chapterNumber,
  523. workflowConfig,
  524. 3,
  525. signal,
  526. );
  527. if (previousChaptersAnalysis) {
  528. callbacks.onThinking?.(
  529. formatStageThinking(
  530. "阶段0:前情分析",
  531. `已完成前情分析(${previousChaptersAnalysis.length}字)\n\n${previousChaptersAnalysis.slice(0, 500)}...`,
  532. ),
  533. );
  534. }
  535. } catch (error) {
  536. rethrowIfUserAbort(error, signal);
  537. console.error("[deep-chapter-generation] 前情分析失败:", error);
  538. }
  539. }
  540. throwIfAborted(signal);
  541. let contextPack = await safeBuildChapterContextPack(
  542. deps,
  543. input.projectPath,
  544. contextRequest,
  545. input.chapterNumber,
  546. signal,
  547. );
  548. assertNotAborted(signal);
  549. if (workflowProfile.mode === "strict") {
  550. contextPack = await maybeInjectWritingEntityWebSearch({
  551. input,
  552. deps,
  553. contextPack,
  554. previousChaptersAnalysis,
  555. planBlueprint,
  556. workflowConfig,
  557. callbacks,
  558. signal,
  559. });
  560. assertNotAborted(signal);
  561. }
  562. if (!resumeCheckpoint) {
  563. emitDeepChapterStageStarted(
  564. callbacks,
  565. "read_context",
  566. "读取上下文",
  567. "读取大纲、上一章结尾、近期剧情、人物状态、伏笔和时间线。",
  568. );
  569. emitDeepChapterActivity(callbacks, {
  570. id: `deep_chapter:read_context:sources:${Date.now()}`,
  571. stageId: "read_context",
  572. kind: "read_source",
  573. title: "读取内容",
  574. content: [
  575. contextPack.outline?.trim()
  576. ? "已读取:作品完整大纲"
  577. : "未读取到:作品完整大纲",
  578. contextPack.previousChapterEnding?.trim()
  579. ? "已读取:上一章结尾"
  580. : "未读取到:上一章结尾",
  581. Array.isArray(contextPack.recentSummaries) &&
  582. contextPack.recentSummaries.length > 0
  583. ? `已读取:近期剧情 ${contextPack.recentSummaries.length} 条`
  584. : "未读取到:近期剧情",
  585. contextPack.characterStates?.trim()
  586. ? "已读取:人物状态"
  587. : "未读取到:人物状态",
  588. contextPack.foreshadowingStates?.trim()
  589. ? "已读取:伏笔状态"
  590. : "未读取到:伏笔状态",
  591. contextPack.timeline?.trim() ? "已读取:时间线" : "未读取到:时间线",
  592. ].join("\n"),
  593. });
  594. emitDeepChapterActivity(callbacks, {
  595. id: `deep_chapter:read_context:goals:${Date.now()}`,
  596. stageId: "read_context",
  597. kind: "extract_goal",
  598. title: "提取目标",
  599. content: [
  600. "上一章结尾",
  601. "本章章节目标",
  602. "大纲要求推进的事件",
  603. "人物当前状态",
  604. "必须承接的伏笔",
  605. "必须完成与禁止违背内容",
  606. ].join("\n"),
  607. });
  608. emitDeepChapterActivity(callbacks, {
  609. id: `deep_chapter:read_context:results:${Date.now()}`,
  610. stageId: "read_context",
  611. kind: "extract_result",
  612. title: "提取结果",
  613. content: formatContextExtractionResult(input, contextPack),
  614. });
  615. emitDeepChapterActivity(callbacks, {
  616. id: `deep_chapter:read_context:output:${Date.now()}`,
  617. stageId: "read_context",
  618. kind: "stage_output",
  619. title: "阶段产物",
  620. content:
  621. "已形成章节生成约束包,将传入写作任务书、正文初稿、审稿和最终去AI味阶段。",
  622. });
  623. }
  624. // 阶段1后:加载智能skill(传递contextPack用于场景检测)
  625. customDeAiSkill = await loadSmartDeAiSkill(
  626. input.projectPath,
  627. contextRequest,
  628. contextPack,
  629. );
  630. throwIfAborted(signal);
  631. // 任务书(workflowConfig)、初稿/返修(writingConfig)、去AI味(deAiConfig)复用同一份
  632. // outlinePrompt + contextPrompt。这三个环节可能用不同模型、各有独立上下文窗口,
  633. // 因此预算取三者窗口的最小值:确保任一环节都不必依赖 llm-client 末级无差别截断
  634. // (末级截断按字符砍,会绕过 ContextPack 的字段优先级),并让各环节看到一致的上下文。
  635. const sharedContextWindows = [
  636. writingConfig.maxContextSize,
  637. workflowConfig.maxContextSize,
  638. deAiConfig.maxContextSize,
  639. ].filter((size): size is number => typeof size === "number" && size > 0);
  640. const sharedContextWindow = sharedContextWindows.length > 0
  641. ? Math.min(...sharedContextWindows)
  642. : input.llmConfig.maxContextSize;
  643. // 大纲与其余上下文共用同一窗口预算:资料包按三阶段最小窗分配。
  644. // 输出上限与思考地板按各阶段实际调用的模型重算,不再只读入口 llmConfig。
  645. const chapterAnalysisBudget = planChapterRequestBudget({
  646. maxContextSize: sharedContextWindow,
  647. chapterTargetChars: novelConfig.chapterTargetChars,
  648. stage: "analysis",
  649. maxOutputTokens: getEffectiveMaxOutputTokens(workflowConfig),
  650. thinkingFloorTokens: thinkingMinMaxTokens(
  651. workflowConfig.reasoning ?? { mode: "auto" },
  652. ),
  653. });
  654. const chapterGenerationBudget = planChapterRequestBudget({
  655. maxContextSize: sharedContextWindow,
  656. chapterTargetChars: novelConfig.chapterTargetChars,
  657. stage: "generation",
  658. maxOutputTokens: getEffectiveMaxOutputTokens(writingConfig),
  659. thinkingFloorTokens: thinkingMinMaxTokens(
  660. writingConfig.reasoning ?? { mode: "auto" },
  661. ),
  662. });
  663. const chapterDeAiBudget = planChapterRequestBudget({
  664. maxContextSize: sharedContextWindow,
  665. chapterTargetChars: novelConfig.chapterTargetChars,
  666. stage: "generation",
  667. maxOutputTokens: getEffectiveMaxOutputTokens(deAiConfig),
  668. thinkingFloorTokens: thinkingMinMaxTokens(
  669. deAiConfig.reasoning ?? { mode: "auto" },
  670. ),
  671. });
  672. const totalContextTokenBudget = chapterGenerationBudget.contextTokenBudget;
  673. const analysisRequestOverrides: RequestOverrides = {
  674. max_tokens: chapterAnalysisBudget.outputTokens,
  675. };
  676. const generationRequestOverrides: RequestOverrides = {
  677. max_tokens: chapterGenerationBudget.outputTokens,
  678. };
  679. const deAiRequestOverrides: RequestOverrides = {
  680. max_tokens: chapterDeAiBudget.outputTokens,
  681. };
  682. // Same density as the token estimator / trimContextPack (CJK 1, English 4).
  683. const charsPerToken = charsPerTokenForLanguage();
  684. const totalContextCharBudget = totalContextTokenBudget * charsPerToken;
  685. const outlineCharCap = Math.floor(
  686. totalContextCharBudget * DEEP_CHAPTER_OUTLINE_MAX_FRAC,
  687. );
  688. const outlineText = capOutlineSourcesToBudget(
  689. contextPack.outline ?? "",
  690. outlineCharCap,
  691. );
  692. // 独立提取大纲,不通过contextPackToPrompt
  693. const outlinePrompt = outlineText
  694. ? [
  695. "# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
  696. "# 【强制遵守】作品完整大纲",
  697. "# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
  698. "",
  699. "**重要:以下是本作品的完整大纲,这是强制性要求。**",
  700. "你必须严格遵守大纲中的情节发展、角色行为、关键事件、故事走向。",
  701. "大纲内容必须完整体现在生成的章节中,不可偏离。",
  702. "",
  703. outlineText,
  704. "",
  705. "# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
  706. "",
  707. ].join("\n")
  708. : "";
  709. // 其余上下文的预算 = 总预算 − 大纲已占用(换算成 token),并保留下限。
  710. // 这样「大纲 + 其余上下文」整体不超过窗口派生的总预算。
  711. const restContextTokenBudget = Math.max(
  712. DEEP_CHAPTER_REST_TOKEN_FLOOR,
  713. totalContextTokenBudget -
  714. Math.ceil(outlineText.length / charsPerToken),
  715. );
  716. const contextPrompt = [
  717. previousChaptersAnalysis
  718. ? `## 前情分析\n\n${previousChaptersAnalysis}`
  719. : "",
  720. deps.contextPackToPrompt(contextPack, restContextTokenBudget, {
  721. excludeOutline: true,
  722. }),
  723. input.dismantlingReferenceDirective,
  724. ]
  725. .filter(Boolean)
  726. .join("\n\n");
  727. // 稳定上下文前缀:与任务书/初稿/扩写/返修/去AI味各阶段提示词开头逐字节一致。
  728. // 作为显式 prompt 缓存断点传入(Anthropic/MiniMax 走 cache_control;
  729. // OpenAI/DeepSeek 该断点被折叠回字符串、由其自动前缀缓存命中)。
  730. const cachePrefix = buildStableContextPrefix(outlinePrompt, contextPrompt);
  731. if (!resumeCheckpoint) {
  732. callbacks.onThinking?.(formatContextThinking(input, contextPack));
  733. callbacks.onCheckpoint?.(createCheckpoint("after_context"));
  734. completeChapterWorkflowStep(
  735. callbacks,
  736. contextWorkflowStep,
  737. "上下文读取完成。",
  738. {
  739. recentSummaryCount: Array.isArray(contextPack.recentSummaries)
  740. ? contextPack.recentSummaries.length
  741. : 0,
  742. hasOutline: Boolean(contextPack.outline?.trim()),
  743. hasPreviousChapterEnding: Boolean(
  744. contextPack.previousChapterEnding?.trim(),
  745. ),
  746. },
  747. );
  748. }
  749. assertNotAborted(signal);
  750. let taskBrief = hasCheckpointTaskBrief(resumeCheckpoint)
  751. ? resumeCheckpoint.taskBrief.trim()
  752. : "";
  753. if (!taskBrief) {
  754. emitDeepChapterStageStarted(
  755. callbacks,
  756. "plot_analysis",
  757. "分析剧情走向",
  758. "根据章节生成约束包拆解本章目标、关键情节和写作约束。",
  759. );
  760. emitDeepChapterActivity(callbacks, {
  761. id: `deep_chapter:plot_analysis:input:${Date.now()}`,
  762. stageId: "plot_analysis",
  763. kind: "stage_input",
  764. title: "接收内容",
  765. content: "章节生成约束包",
  766. });
  767. taskBrief = await runChapterWorkflowStep(
  768. callbacks,
  769. {
  770. name: "chapter_task_brief",
  771. title: "生成写作任务书",
  772. detail: "根据上下文拆解本章目标、关键情节和写作约束。",
  773. params: workflowBaseParams,
  774. },
  775. () =>
  776. collectModelText(
  777. workflowConfig,
  778. [
  779. {
  780. role: "user",
  781. content: buildDeepChapterBriefPrompt(
  782. outlinePrompt,
  783. contextPrompt,
  784. input.userRequest,
  785. input.chapterNumber,
  786. input.goldenThreeChapter,
  787. lengthSpec,
  788. planExecutionSummary,
  789. executionContractText,
  790. input.skillsPrompt,
  791. ),
  792. },
  793. ],
  794. deps,
  795. signal,
  796. (partial) =>
  797. callbacks.onThinking?.(
  798. formatStageThinking("阶段2:写作任务书", partial),
  799. ),
  800. analysisRequestOverrides,
  801. cachePrefix,
  802. callbacks.onRequestTrace,
  803. ),
  804. (value) => `写作任务书完成,约 ${countChapterChars(value)} 字。`,
  805. (value) => ({ chars: countChapterChars(value) }),
  806. );
  807. assertNotAborted(signal);
  808. callbacks.onThinking?.(formatStageThinking("阶段2:写作任务书", taskBrief));
  809. emitDeepChapterActivity(callbacks, {
  810. id: `deep_chapter:task_brief:output:${Date.now()}`,
  811. stageId: "plot_analysis",
  812. kind: "stage_output",
  813. title: "写作任务书",
  814. content: taskBrief,
  815. });
  816. callbacks.onCheckpoint?.(
  817. createCheckpoint("after_task_brief", { taskBrief }),
  818. );
  819. }
  820. let draftContent = hasCheckpointDraft(resumeCheckpoint)
  821. ? resumeCheckpoint.draftContent.trim()
  822. : "";
  823. if (!draftContent) {
  824. emitDeepChapterStageStarted(
  825. callbacks,
  826. "generate_draft",
  827. "生成章节草稿",
  828. "读取章节生成约束包和写作任务书,生成正文初稿。",
  829. );
  830. emitDeepChapterActivity(callbacks, {
  831. id: `deep_chapter:generate_draft:input:${Date.now()}`,
  832. stageId: "generate_draft",
  833. kind: "stage_input",
  834. title: "接收内容",
  835. content: [
  836. "章节生成约束包",
  837. "写作任务书",
  838. input.chapterNumber
  839. ? `目标章节:第${input.chapterNumber}章`
  840. : "目标章节:从用户请求识别",
  841. ].join("\n"),
  842. });
  843. draftContent = await runChapterWorkflowStep(
  844. callbacks,
  845. {
  846. name: "chapter_draft",
  847. title: "生成章节正文初稿",
  848. detail: "按任务书输出本章正文初稿。",
  849. params: workflowBaseParams,
  850. },
  851. () =>
  852. collectModelText(
  853. writingConfig,
  854. [
  855. {
  856. role: "user",
  857. content: buildDeepChapterDraftPrompt(
  858. outlinePrompt,
  859. contextPrompt,
  860. taskBrief,
  861. input.userRequest,
  862. input.chapterNumber,
  863. input.goldenThreeChapter,
  864. lengthSpec,
  865. input.skillsPrompt,
  866. ),
  867. },
  868. ],
  869. deps,
  870. signal,
  871. (partial) =>
  872. callbacks.onThinking?.(
  873. formatStageThinking("阶段3:正文初稿", partial),
  874. ),
  875. generationRequestOverrides,
  876. cachePrefix,
  877. callbacks.onRequestTrace,
  878. ),
  879. (value) => {
  880. const chars = countChapterChars(value);
  881. return chars < lengthSpec.minChars
  882. ? `正文初稿仅约 ${chars} 字,低于最低完成线 ${lengthSpec.minChars} 字,进入扩写补足。`
  883. : `正文初稿完成,约 ${chars} 字。`;
  884. },
  885. (value) => ({ chars: countChapterChars(value) }),
  886. );
  887. assertNotAborted(signal);
  888. if (countChapterChars(draftContent) < lengthSpec.minChars) {
  889. draftContent = await runChapterWorkflowStep(
  890. callbacks,
  891. {
  892. name: "chapter_expansion",
  893. title: "正文扩写补足",
  894. detail: "初稿低于本章目标字数,补足场景和人物行动。",
  895. params: workflowBaseParams,
  896. },
  897. async () => {
  898. const expanded = await collectModelText(
  899. writingConfig,
  900. [
  901. {
  902. role: "user",
  903. content: buildDeepChapterExpansionPrompt(
  904. outlinePrompt,
  905. contextPrompt,
  906. taskBrief,
  907. draftContent,
  908. input.userRequest,
  909. input.chapterNumber,
  910. input.goldenThreeChapter,
  911. lengthSpec,
  912. ),
  913. },
  914. ],
  915. deps,
  916. signal,
  917. (partial) =>
  918. callbacks.onThinking?.(
  919. formatStageThinking("阶段3:正文扩写补足", partial),
  920. ),
  921. generationRequestOverrides,
  922. cachePrefix,
  923. callbacks.onRequestTrace,
  924. );
  925. const expandedChars = countChapterChars(expanded);
  926. if (expandedChars < lengthSpec.minChars) {
  927. throw new Error(
  928. `章节正文生成失败:扩写后仅约 ${expandedChars} 字,低于最低完成线 ${lengthSpec.minChars} 字。`,
  929. );
  930. }
  931. return expanded;
  932. },
  933. (value) => `正文扩写补足完成,约 ${countChapterChars(value)} 字。`,
  934. (value) => ({ chars: countChapterChars(value) }),
  935. );
  936. assertNotAborted(signal);
  937. }
  938. callbacks.onThinking?.(
  939. formatStageThinking(
  940. "阶段3:正文初稿",
  941. [
  942. draftContent,
  943. "",
  944. `初稿生成完成,约 ${countChapterChars(draftContent)} 字。`,
  945. ].join("\n"),
  946. ),
  947. );
  948. emitDeepChapterActivity(callbacks, {
  949. id: `deep_chapter:generate_draft:output:${Date.now()}`,
  950. stageId: "generate_draft",
  951. kind: "stage_output",
  952. title: "章节草稿",
  953. content: `正文初稿完成,约 ${countChapterChars(draftContent)} 字。`,
  954. });
  955. callbacks.onCheckpoint?.(
  956. createCheckpoint("after_draft", { taskBrief, draftContent }),
  957. );
  958. }
  959. if (!workflowProfile.runPostDraftPlanAudits) {
  960. const finalContent = draftContent;
  961. const isFastMode = workflowProfile.mode === "fast";
  962. callbacks.onThinking?.(
  963. formatStageThinking(
  964. isFastMode ? "阶段4:快速完成" : "阶段4:标准完成",
  965. isFastMode
  966. ? "快速模式已完成任务书与正文初稿生成,直接采用正文初稿作为最终正文。"
  967. : "标准模式已完成任务书与正文初稿生成,直接采用正文初稿作为最终正文。",
  968. ),
  969. );
  970. emitDeepChapterActivity(callbacks, {
  971. id: `deep_chapter:final_output:output:${Date.now()}`,
  972. stageId: "final_output",
  973. kind: "final_output",
  974. title: "最终正文",
  975. content: `最终正文已生成,约 ${countChapterChars(finalContent)} 字。`,
  976. });
  977. callbacks.onFinalContent?.(finalContent);
  978. completeChapterWorkflowStep(
  979. callbacks,
  980. {
  981. name: "chapter_complete",
  982. title: workflowProfile.completionTitle,
  983. detail: "汇总本次章节生成结果。",
  984. params: workflowBaseParams,
  985. },
  986. `${workflowProfile.completionResultPrefix},最终正文约 ${countChapterChars(finalContent)} 字。`,
  987. {
  988. chars: countChapterChars(finalContent),
  989. revised: false,
  990. },
  991. );
  992. return {
  993. finalContent,
  994. taskBrief,
  995. draftContent,
  996. reviewResults: [],
  997. revised: false,
  998. planCompliance: "",
  999. executionReport: "",
  1000. };
  1001. }
  1002. let reviewResults = hasCheckpointReview(resumeCheckpoint)
  1003. ? resumeCheckpoint.reviewResults
  1004. : [];
  1005. let reviewFailureMessage = "";
  1006. emitDeepChapterStageStarted(
  1007. callbacks,
  1008. "validate_revision",
  1009. "校验与修正",
  1010. "检查正文完整性、剧情连续性、人物一致性和阻断问题。",
  1011. );
  1012. // 审稿由工作流模式决定:严格模式始终审稿,快速/标准模式跳过。
  1013. const shouldRunAiReview = workflowProfile.runAiReview;
  1014. if (!hasCheckpointReview(resumeCheckpoint)) {
  1015. if (!shouldRunAiReview) {
  1016. completeChapterWorkflowStep(
  1017. callbacks,
  1018. {
  1019. name: "chapter_review",
  1020. title: "执行 AI 审稿",
  1021. detail: "根据当前模式决定是否执行 AI 审稿。",
  1022. params: workflowBaseParams,
  1023. },
  1024. workflowProfile.mode === "fast"
  1025. ? "快速模式跳过 AI 审稿、返修和最终去AI味,直接使用阶段3正文初稿。"
  1026. : "标准模式跳过 AI 审稿与自动返修,初稿将进入阶段6简单审查与去AI味。",
  1027. { skipped: true },
  1028. );
  1029. callbacks.onThinking?.(
  1030. formatStageThinking(
  1031. "阶段4-5:已跳过审稿与返修",
  1032. workflowProfile.mode === "fast"
  1033. ? "快速模式跳过 AI 审稿、返修和最终去AI味,直接使用阶段3正文初稿。"
  1034. : "标准模式跳过 AI 审稿与自动返修,初稿将进入阶段6简单审查与去AI味。",
  1035. ),
  1036. );
  1037. emitDeepChapterActivity(callbacks, {
  1038. id: `deep_chapter:validate_revision:analysis:${Date.now()}`,
  1039. stageId: "validate_revision",
  1040. kind: "analysis",
  1041. title: "审稿分析",
  1042. content:
  1043. workflowProfile.mode === "fast"
  1044. ? "快速模式跳过 AI 审稿、返修和最终去AI味,直接使用阶段3正文初稿。"
  1045. : "标准模式跳过 AI 审稿与自动返修,初稿将进入阶段6简单审查与去AI味。",
  1046. });
  1047. } else {
  1048. const reviewWorkflowStep: ChapterWorkflowStepSpec = {
  1049. name: "chapter_review",
  1050. title: "执行 AI 审稿",
  1051. detail: "检查正文完整性、剧情连续性、截断和阻断问题。",
  1052. params: workflowBaseParams,
  1053. };
  1054. startChapterWorkflowStep(callbacks, reviewWorkflowStep);
  1055. callbacks.onThinking?.(
  1056. formatStageThinking(
  1057. "阶段4:AI审稿",
  1058. "正在检查正文完整性、剧情连续性、是否被截断以及是否存在阻断问题。",
  1059. ),
  1060. );
  1061. try {
  1062. // 复用阶段1已构建的 contextPack,避免审稿内部再 buildContextPack 一次
  1063. // (会重复跑检索 / 向量 / 图谱)。
  1064. reviewResults = signal
  1065. ? await deps.reviewChapter(
  1066. input.projectPath,
  1067. draftContent,
  1068. input.chapterNumber,
  1069. {
  1070. onThinking: callbacks.onThinking,
  1071. contextPack,
  1072. planBlueprint: planExecutionSummary,
  1073. throwOnFailure: true,
  1074. onRequestTrace: callbacks.onRequestTrace,
  1075. },
  1076. signal,
  1077. )
  1078. : await deps.reviewChapter(
  1079. input.projectPath,
  1080. draftContent,
  1081. input.chapterNumber,
  1082. {
  1083. onThinking: callbacks.onThinking,
  1084. contextPack,
  1085. planBlueprint: planExecutionSummary,
  1086. throwOnFailure: true,
  1087. onRequestTrace: callbacks.onRequestTrace,
  1088. },
  1089. );
  1090. } catch (err) {
  1091. rethrowIfUserAbort(err, signal);
  1092. console.error("[Deep Chapter] Review failed:", err);
  1093. reviewFailureMessage = `AI 审稿失败:${getErrorMessage(err)}。已跳过自动返修,请在保存前手动复核正文。`;
  1094. errorChapterWorkflowStep(callbacks, reviewWorkflowStep, err);
  1095. callbacks.onThinking?.(
  1096. formatStageThinking("阶段4:AI审稿", reviewFailureMessage),
  1097. );
  1098. emitDeepChapterActivity(callbacks, {
  1099. id: `deep_chapter:validate_revision:error:${Date.now()}`,
  1100. stageId: "validate_revision",
  1101. kind: "analysis",
  1102. title: "审稿失败",
  1103. content: reviewFailureMessage,
  1104. });
  1105. reviewResults = [];
  1106. }
  1107. reviewResults = reviewResults || [];
  1108. assertNotAborted(signal);
  1109. if (!reviewFailureMessage) {
  1110. completeChapterWorkflowStep(
  1111. callbacks,
  1112. reviewWorkflowStep,
  1113. reviewResults.length === 0
  1114. ? "AI 审稿完成,未发现阻断问题。"
  1115. : `AI 审稿完成,发现 ${reviewResults.length} 个问题,其中 ${reviewResults.filter((item) => item.severity === "error").length} 个阻断问题。`,
  1116. {
  1117. issueCount: reviewResults.length,
  1118. blockingIssueCount: reviewResults.filter(
  1119. (item) => item.severity === "error",
  1120. ).length,
  1121. },
  1122. );
  1123. callbacks.onThinking?.(formatReviewThinking(reviewResults));
  1124. emitDeepChapterActivity(callbacks, {
  1125. id: `deep_chapter:validate_revision:analysis:${Date.now()}`,
  1126. stageId: "validate_revision",
  1127. kind: "analysis",
  1128. title: "审稿分析",
  1129. content: formatReviewThinking(reviewResults)
  1130. .replace(/^##\s*阶段4:AI审稿\s*/, "")
  1131. .trim(),
  1132. });
  1133. callbacks.onCheckpoint?.(
  1134. createCheckpoint("after_review", {
  1135. taskBrief,
  1136. draftContent,
  1137. reviewResults,
  1138. }),
  1139. );
  1140. }
  1141. }
  1142. }
  1143. const blockingIssues = reviewResults.filter(
  1144. (item) => item.severity === "error",
  1145. );
  1146. let currentContent = draftContent;
  1147. let revised = false;
  1148. if (hasCheckpointRevision(resumeCheckpoint)) {
  1149. currentContent = resumeCheckpoint.currentContent.trim();
  1150. revised = true;
  1151. } else if (reviewFailureMessage) {
  1152. completeChapterWorkflowStep(
  1153. callbacks,
  1154. {
  1155. name: "chapter_revision",
  1156. title: "自动返修",
  1157. detail: "根据 AI 审稿结果决定是否返修。",
  1158. params: workflowBaseParams,
  1159. },
  1160. "AI 审稿失败,无法安全判断返修项,已跳过自动返修。",
  1161. { skipped: true, reviewFailed: true },
  1162. );
  1163. callbacks.onThinking?.(
  1164. formatStageThinking(
  1165. "阶段5:已跳过自动返修",
  1166. "AI 审稿失败,无法安全判断阻断问题,已跳过自动返修并继续最终简单审查。",
  1167. ),
  1168. );
  1169. } else if (blockingIssues.length === 0) {
  1170. if (shouldRunAiReview) {
  1171. completeChapterWorkflowStep(
  1172. callbacks,
  1173. {
  1174. name: "chapter_revision",
  1175. title: "自动返修",
  1176. detail: "根据 AI 审稿结果决定是否返修。",
  1177. params: workflowBaseParams,
  1178. },
  1179. "AI审稿未发现阻断问题,跳过自动返修。",
  1180. { skipped: true },
  1181. );
  1182. callbacks.onThinking?.(
  1183. formatStageThinking(
  1184. "阶段5:无需自动返修",
  1185. "AI审稿未发现阻断问题,跳过自动返修,进入阶段6简单审查与去AI味。",
  1186. ),
  1187. );
  1188. }
  1189. } else {
  1190. const revisedContent = await runChapterWorkflowStep(
  1191. callbacks,
  1192. {
  1193. name: "chapter_revision",
  1194. title: "自动返修",
  1195. detail: "根据阻断问题自动返修一次。",
  1196. params: {
  1197. ...workflowBaseParams,
  1198. blockingIssueCount: blockingIssues.length,
  1199. },
  1200. },
  1201. () =>
  1202. collectModelText(
  1203. writingConfig,
  1204. [
  1205. {
  1206. role: "user",
  1207. content: buildDeepChapterRevisionPrompt(
  1208. outlinePrompt,
  1209. contextPrompt,
  1210. taskBrief,
  1211. draftContent,
  1212. blockingIssues,
  1213. input.userRequest,
  1214. input.chapterNumber,
  1215. input.goldenThreeChapter,
  1216. input.skillsPrompt,
  1217. ),
  1218. },
  1219. ],
  1220. deps,
  1221. signal,
  1222. (partial) =>
  1223. callbacks.onThinking?.(
  1224. formatStageThinking("阶段5:自动返修", partial),
  1225. ),
  1226. generationRequestOverrides,
  1227. cachePrefix,
  1228. callbacks.onRequestTrace,
  1229. ),
  1230. (value) =>
  1231. `检测到 ${blockingIssues.length} 个阻断问题,已自动返修一次。返修后正文约 ${countChapterChars(value)} 字。`,
  1232. (value) => ({ chars: countChapterChars(value) }),
  1233. );
  1234. assertNotAborted(signal);
  1235. callbacks.onThinking?.(
  1236. formatStageThinking(
  1237. "阶段5:自动返修",
  1238. [
  1239. `检测到 ${blockingIssues.length} 个阻断问题,已自动返修一次。`,
  1240. "",
  1241. formatReviewIssueList(blockingIssues),
  1242. "",
  1243. `返修后正文约 ${countChapterChars(revisedContent)} 字。`,
  1244. ].join("\n"),
  1245. ),
  1246. );
  1247. currentContent = revisedContent;
  1248. revised = true;
  1249. callbacks.onCheckpoint?.(
  1250. createCheckpoint("after_revision", {
  1251. taskBrief,
  1252. draftContent,
  1253. reviewResults,
  1254. currentContent: revisedContent,
  1255. }),
  1256. );
  1257. }
  1258. emitDeepChapterActivity(callbacks, {
  1259. id: `deep_chapter:validate_revision:output:${Date.now()}`,
  1260. stageId: "validate_revision",
  1261. kind: "stage_output",
  1262. title: "修正结果",
  1263. content: revised
  1264. ? "已根据阻断问题完成一次自动返修。"
  1265. : "未执行自动返修,当前正文进入最终审查。",
  1266. });
  1267. // 阶段5.5:返修后复审(只在发生了返修时执行,只审查角色一致性维度,降低token消耗,不再自动返修避免循环)
  1268. const shouldRunPostRevisionReview = workflowProfile.runPostRevisionReview;
  1269. if (revised && shouldRunPostRevisionReview) {
  1270. const postRevisionWorkflowStep: ChapterWorkflowStepSpec = {
  1271. name: "chapter_post_revision_review",
  1272. title: "返修后复审",
  1273. detail: "对返修后的正文做角色一致性专项复审。",
  1274. params: workflowBaseParams,
  1275. };
  1276. startChapterWorkflowStep(callbacks, postRevisionWorkflowStep);
  1277. callbacks.onThinking?.(
  1278. formatStageThinking(
  1279. "阶段5.5:返修后角色一致性复审",
  1280. "正在对返修后的正文进行角色一致性专项复审(轻量模式,只检查角色相关维度),确认返修是否引入新的角色偏差。",
  1281. ),
  1282. );
  1283. try {
  1284. const postRevisionResults = signal
  1285. ? await deps.reviewChapter(
  1286. input.projectPath,
  1287. currentContent,
  1288. input.chapterNumber,
  1289. {
  1290. onThinking: callbacks.onThinking,
  1291. contextPack,
  1292. characterOnly: true,
  1293. throwOnFailure: true,
  1294. onRequestTrace: callbacks.onRequestTrace,
  1295. },
  1296. signal,
  1297. )
  1298. : await deps.reviewChapter(
  1299. input.projectPath,
  1300. currentContent,
  1301. input.chapterNumber,
  1302. {
  1303. onThinking: callbacks.onThinking,
  1304. contextPack,
  1305. characterOnly: true,
  1306. throwOnFailure: true,
  1307. onRequestTrace: callbacks.onRequestTrace,
  1308. },
  1309. );
  1310. const postBlockingIssues = (postRevisionResults || []).filter(
  1311. (item) => item.severity === "error",
  1312. );
  1313. if (postBlockingIssues.length > 0) {
  1314. callbacks.onThinking?.(
  1315. formatStageThinking(
  1316. "阶段5.5:返修后复审",
  1317. [
  1318. `返修后复审发现 ${postBlockingIssues.length} 个阻断问题(不再自动返修,避免循环):`,
  1319. "",
  1320. formatReviewIssueList(postBlockingIssues),
  1321. "",
  1322. "这些问题将在阶段6去AI味时一并处理,或需要手动修改。",
  1323. ].join("\n"),
  1324. ),
  1325. );
  1326. reviewResults = [...reviewResults, ...(postRevisionResults || [])];
  1327. } else {
  1328. callbacks.onThinking?.(
  1329. formatStageThinking(
  1330. "阶段5.5:返修后复审",
  1331. "返修后复审未发现新的阻断问题,进入阶段6。",
  1332. ),
  1333. );
  1334. }
  1335. completeChapterWorkflowStep(
  1336. callbacks,
  1337. postRevisionWorkflowStep,
  1338. `返修后复审完成,发现 ${postBlockingIssues.length} 个阻断问题。`,
  1339. { blockingIssueCount: postBlockingIssues.length },
  1340. );
  1341. } catch (err) {
  1342. rethrowIfUserAbort(err, signal);
  1343. console.error("[Deep Chapter] 返修后复审失败:", err);
  1344. errorChapterWorkflowStep(callbacks, postRevisionWorkflowStep, err);
  1345. callbacks.onThinking?.(
  1346. formatStageThinking(
  1347. "阶段5.5:返修后复审",
  1348. `返修后复审失败:${getErrorMessage(err)}。已继续进入最终简单审查,请在保存前手动复核正文。`,
  1349. ),
  1350. );
  1351. }
  1352. }
  1353. const finalPolishWorkflowStep: ChapterWorkflowStepSpec = {
  1354. name: "chapter_final_polish",
  1355. title: "简单审查与去AI味",
  1356. detail: "做最后一遍简单审查,减少复读、机械套话和 AI 味。",
  1357. params: workflowBaseParams,
  1358. };
  1359. if (workflowProfile.runFinalPolish) {
  1360. emitDeepChapterStageStarted(
  1361. callbacks,
  1362. "final_polish",
  1363. "去AI味",
  1364. "正在做最后一遍简单审查,去除复读、机械套话和 AI 味。",
  1365. );
  1366. }
  1367. let finalContent = workflowProfile.runFinalPolish
  1368. ? await runChapterWorkflowStep(
  1369. callbacks,
  1370. finalPolishWorkflowStep,
  1371. () =>
  1372. finalPolishChapter(
  1373. deAiConfig,
  1374. outlinePrompt,
  1375. contextPrompt,
  1376. taskBrief,
  1377. currentContent,
  1378. input,
  1379. contextPack,
  1380. callbacks,
  1381. deps,
  1382. signal,
  1383. customDeAiSkill || undefined,
  1384. cachePrefix,
  1385. deAiRequestOverrides,
  1386. ),
  1387. (value) =>
  1388. `简单审查与去AI味完成,最终正文约 ${countChapterChars(value)} 字。`,
  1389. (value) => ({ chars: countChapterChars(value) }),
  1390. )
  1391. : currentContent;
  1392. if (!workflowProfile.runFinalPolish) {
  1393. completeChapterWorkflowStep(
  1394. callbacks,
  1395. finalPolishWorkflowStep,
  1396. "快速模式跳过最终去AI味,直接采用阶段3正文作为最终正文。",
  1397. { skipped: true, chars: countChapterChars(finalContent) },
  1398. );
  1399. } else {
  1400. emitDeepChapterActivity(callbacks, {
  1401. id: `deep_chapter:final_polish:output:${Date.now()}`,
  1402. stageId: "final_polish",
  1403. kind: "stage_output",
  1404. title: "去AI味",
  1405. content: `简单审查与去AI味完成,最终正文约 ${countChapterChars(finalContent)} 字。`,
  1406. });
  1407. }
  1408. callbacks.onThinking?.(
  1409. formatStageThinking(
  1410. "阶段7:完成",
  1411. workflowProfile.runFinalPolish
  1412. ? reviewFailureMessage
  1413. ? "AI 审稿失败;已保留正文并完成最后一遍简单审查与去AI味,请在保存前手动复核。"
  1414. : revised
  1415. ? "采用返修并完成简单审查、去AI味后的正文作为最终正文。"
  1416. : "未发现阻断问题,已完成最后一遍简单审查与去AI味。"
  1417. : "快速模式已完成任务书与正文初稿生成,直接采用阶段3正文作为最终正文。",
  1418. ),
  1419. );
  1420. emitDeepChapterActivity(callbacks, {
  1421. id: `deep_chapter:final_output:output:${Date.now()}`,
  1422. stageId: "final_output",
  1423. kind: "final_output",
  1424. title: "最终正文",
  1425. content: `最终正文已生成,约 ${countChapterChars(finalContent)} 字。`,
  1426. });
  1427. callbacks.onFinalContent?.(finalContent);
  1428. let executionReportSummary = "";
  1429. if (workflowProfile.runPostDraftPlanAudits && executionContract) {
  1430. try {
  1431. const runReport = deps.runChapterExecutionReportCheck || runChapterExecutionReportCheck;
  1432. const report = await runChapterWorkflowStep(
  1433. callbacks,
  1434. {
  1435. name: "chapter_execution_report",
  1436. title: "检查执行清单",
  1437. detail: "按场景验收标准逐项检查最终正文。",
  1438. params: workflowBaseParams,
  1439. },
  1440. () => callbacks.onRequestTrace
  1441. ? runReport(workflowConfig, executionContract!, finalContent, signal, callbacks.onRequestTrace)
  1442. : runReport(workflowConfig, executionContract!, finalContent, signal),
  1443. (value) => executionReportToToolSummary(value),
  1444. (value) => ({
  1445. status: value.status,
  1446. repairItemCount: extractExecutionRepairItems(value).length,
  1447. }),
  1448. );
  1449. const repairItems = extractExecutionRepairItems(report);
  1450. executionReportSummary = executionReportToToolSummary(report);
  1451. emitDeepChapterActivity(callbacks, {
  1452. id: `deep_chapter:execution_report:output:${Date.now()}`,
  1453. stageId: "execution_report",
  1454. kind: "stage_output",
  1455. title: "执行报告",
  1456. content: executionReportSummary,
  1457. });
  1458. if (repairItems.length > 0) {
  1459. const runRepair = deps.runChapterPlanDeviationRepair || runChapterPlanDeviationRepair;
  1460. const repairStep = {
  1461. name: "chapter_execution_repair",
  1462. title: "返修执行失败项",
  1463. detail: "只修复执行报告中的失败项,不重写全章。",
  1464. params: workflowBaseParams,
  1465. };
  1466. startChapterWorkflowStep(callbacks, repairStep);
  1467. let repairedContent = "";
  1468. try {
  1469. repairedContent = callbacks.onRequestTrace
  1470. ? await runRepair(
  1471. writingConfig,
  1472. contractToTaskBriefText(executionContract!),
  1473. finalContent,
  1474. repairItems.join("\n"),
  1475. signal,
  1476. callbacks.onRequestTrace,
  1477. )
  1478. : await runRepair(
  1479. writingConfig,
  1480. contractToTaskBriefText(executionContract!),
  1481. finalContent,
  1482. repairItems.join("\n"),
  1483. signal,
  1484. );
  1485. } catch (error) {
  1486. errorChapterWorkflowStep(callbacks, repairStep, error);
  1487. throw error;
  1488. }
  1489. const validation = validateChapterPlanRepairResult(finalContent, repairedContent);
  1490. if (!validation.accepted) {
  1491. errorChapterWorkflowStep(callbacks, repairStep, new Error(validation.reason));
  1492. } else {
  1493. const repairedCandidate = repairedContent.trim();
  1494. let recheckReport: ChapterExecutionReport;
  1495. try {
  1496. recheckReport = await runChapterWorkflowStep(
  1497. callbacks,
  1498. {
  1499. name: "chapter_execution_recheck",
  1500. title: "复检执行清单",
  1501. detail: "返修后再次检查执行清单失败项是否消除。",
  1502. params: workflowBaseParams,
  1503. },
  1504. () => callbacks.onRequestTrace
  1505. ? runReport(workflowConfig, executionContract!, repairedCandidate, signal, callbacks.onRequestTrace)
  1506. : runReport(workflowConfig, executionContract!, repairedCandidate, signal),
  1507. (value) => executionReportToToolSummary(value),
  1508. (value) => ({
  1509. status: value.status,
  1510. repairItemCount: extractExecutionRepairItems(value).length,
  1511. }),
  1512. );
  1513. } catch (error) {
  1514. errorChapterWorkflowStep(callbacks, repairStep, error);
  1515. throw error;
  1516. }
  1517. const recheckPassed =
  1518. extractExecutionRepairItems(recheckReport).length === 0 &&
  1519. recheckReport.status !== "fail" &&
  1520. recheckReport.status !== "unknown";
  1521. executionReportSummary = executionReportToToolSummary(recheckReport, recheckPassed);
  1522. emitDeepChapterActivity(callbacks, {
  1523. id: `deep_chapter:execution_recheck:output:${Date.now()}`,
  1524. stageId: "execution_recheck",
  1525. kind: "stage_output",
  1526. title: "执行复检",
  1527. content: executionReportSummary,
  1528. });
  1529. if (recheckPassed) {
  1530. completeChapterWorkflowStep(
  1531. callbacks,
  1532. repairStep,
  1533. `执行失败项返修完成,正文约 ${countChapterChars(repairedCandidate)} 字。`,
  1534. { chars: countChapterChars(repairedCandidate), changed: true },
  1535. );
  1536. finalContent = repairedCandidate;
  1537. revised = true;
  1538. callbacks.onFinalContent?.(finalContent);
  1539. } else {
  1540. errorChapterWorkflowStep(
  1541. callbacks,
  1542. repairStep,
  1543. new Error("返修后执行清单复检仍未通过"),
  1544. );
  1545. }
  1546. }
  1547. }
  1548. } catch (error) {
  1549. rethrowIfUserAbort(error, signal);
  1550. executionReportSummary = `执行报告生成失败,已保留正文:${error instanceof Error ? error.message : String(error)}`;
  1551. emitDeepChapterActivity(callbacks, {
  1552. id: `deep_chapter:execution_report:error:${Date.now()}`,
  1553. stageId: "execution_report",
  1554. kind: "stage_output",
  1555. title: "执行报告",
  1556. content: executionReportSummary,
  1557. });
  1558. }
  1559. }
  1560. let planCompliance = "";
  1561. if (workflowProfile.runPostDraftPlanAudits && planExecutionSummary.trim() && !executionContract) {
  1562. let complianceCheckFailed = false;
  1563. const complianceStep = {
  1564. name: "chapter_plan_compliance",
  1565. title: "检查计划履约度",
  1566. detail: "对照用户确认的章节计划检查最终正文是否按计划执行。",
  1567. params: workflowBaseParams,
  1568. };
  1569. const runCompliance = deps.runChapterPlanComplianceCheck || runChapterPlanComplianceCheck;
  1570. try {
  1571. planCompliance = await runChapterWorkflowStep(
  1572. callbacks,
  1573. complianceStep,
  1574. () => callbacks.onRequestTrace
  1575. ? runCompliance(workflowConfig, planExecutionSummary, finalContent, signal, callbacks.onRequestTrace)
  1576. : runCompliance(workflowConfig, planExecutionSummary, finalContent, signal),
  1577. (value) => value ? "计划履约度检查完成。" : "计划履约度检查完成,未返回具体结果。",
  1578. (value) => ({ hasComplianceResult: Boolean(value?.trim()) }),
  1579. );
  1580. } catch (error) {
  1581. rethrowIfUserAbort(error, signal);
  1582. complianceCheckFailed = true;
  1583. planCompliance = `计划履约度检查失败:${error instanceof Error ? error.message : String(error)}`;
  1584. }
  1585. if (planCompliance.trim() && !complianceCheckFailed) {
  1586. const parsedCompliance = parseChapterPlanComplianceResult(planCompliance);
  1587. const shouldRepairPlanDeviation = shouldRepairChapterPlanDeviation(parsedCompliance);
  1588. emitDeepChapterActivity(callbacks, {
  1589. id: `deep_chapter:plan_compliance:output:${Date.now()}`,
  1590. stageId: "plan_compliance",
  1591. kind: "stage_output",
  1592. title: "计划履约度",
  1593. content: formatPlanComplianceActivityContent(parsedCompliance, shouldRepairPlanDeviation),
  1594. });
  1595. if (shouldRepairPlanDeviation) {
  1596. const repairStep = {
  1597. name: "chapter_plan_deviation_repair",
  1598. title: "返修计划偏离点",
  1599. detail: "只修复计划履约检查发现的偏离点,不重写全章。",
  1600. params: workflowBaseParams,
  1601. };
  1602. const runRepair = deps.runChapterPlanDeviationRepair || runChapterPlanDeviationRepair;
  1603. try {
  1604. startChapterWorkflowStep(callbacks, repairStep);
  1605. const complianceBeforeRepair = planCompliance;
  1606. let repairedContent = "";
  1607. try {
  1608. repairedContent = callbacks.onRequestTrace
  1609. ? await runRepair(
  1610. writingConfig,
  1611. planExecutionSummary,
  1612. finalContent,
  1613. complianceBeforeRepair,
  1614. signal,
  1615. callbacks.onRequestTrace,
  1616. )
  1617. : await runRepair(
  1618. writingConfig,
  1619. planExecutionSummary,
  1620. finalContent,
  1621. complianceBeforeRepair,
  1622. signal,
  1623. );
  1624. } catch (error) {
  1625. errorChapterWorkflowStep(callbacks, repairStep, error);
  1626. throw error;
  1627. }
  1628. const validation = validateChapterPlanRepairResult(finalContent, repairedContent);
  1629. const beforeChars = countChapterChars(finalContent);
  1630. if (validation.accepted) {
  1631. const repairedCandidate = repairedContent.trim();
  1632. const recheckStep = {
  1633. name: "chapter_plan_deviation_recheck",
  1634. title: "复检计划履约度",
  1635. detail: "返修后再次检查计划偏离点是否消除。",
  1636. params: workflowBaseParams,
  1637. };
  1638. let recheckResult = "";
  1639. try {
  1640. recheckResult = await runChapterWorkflowStep(
  1641. callbacks,
  1642. recheckStep,
  1643. () => callbacks.onRequestTrace
  1644. ? runCompliance(
  1645. workflowConfig,
  1646. planExecutionSummary,
  1647. repairedCandidate,
  1648. signal,
  1649. callbacks.onRequestTrace,
  1650. )
  1651. : runCompliance(
  1652. workflowConfig,
  1653. planExecutionSummary,
  1654. repairedCandidate,
  1655. signal,
  1656. ),
  1657. (value) => value ? "计划返修复检完成。" : "计划返修复检未返回具体结果。",
  1658. (value) => ({ hasComplianceResult: Boolean(value?.trim()) }),
  1659. );
  1660. } catch (error) {
  1661. errorChapterWorkflowStep(callbacks, repairStep, error);
  1662. throw error;
  1663. }
  1664. const parsedRecheck = parseChapterPlanComplianceResult(recheckResult);
  1665. const recheckPassed =
  1666. parsedRecheck.status === "compliant" ||
  1667. parsedRecheck.status === "mostly_compliant";
  1668. emitDeepChapterActivity(callbacks, {
  1669. id: `deep_chapter:plan_deviation_recheck:output:${Date.now()}`,
  1670. stageId: "plan_deviation_recheck",
  1671. kind: "stage_output",
  1672. title: "计划履约复检",
  1673. content: formatPlanComplianceActivityContent(
  1674. parsedRecheck,
  1675. shouldRepairChapterPlanDeviation(parsedRecheck),
  1676. ),
  1677. });
  1678. if (recheckPassed) {
  1679. completeChapterWorkflowStep(
  1680. callbacks,
  1681. repairStep,
  1682. `计划偏离点返修完成,正文约 ${countChapterChars(repairedCandidate)} 字。`,
  1683. { chars: countChapterChars(repairedCandidate), changed: true },
  1684. );
  1685. finalContent = repairedCandidate;
  1686. revised = true;
  1687. const afterChars = countChapterChars(finalContent);
  1688. planCompliance = buildPlanDeviationRepairReturnContent(parsedCompliance, beforeChars, afterChars);
  1689. emitDeepChapterActivity(callbacks, {
  1690. id: `deep_chapter:plan_deviation_repair:output:${Date.now()}`,
  1691. stageId: "plan_deviation_repair",
  1692. kind: "stage_output",
  1693. title: "计划偏离点返修",
  1694. content: [
  1695. "正文已更新:已按计划履约偏离点完成轻量返修。",
  1696. `返修前:约 ${beforeChars} 字。`,
  1697. `返修后:约 ${afterChars} 字。`,
  1698. "处理范围:只修复履约偏离点,未重写全章。",
  1699. ].join("\n"),
  1700. });
  1701. callbacks.onFinalContent?.(finalContent);
  1702. } else {
  1703. const reason = "返修后计划履约复检仍未通过";
  1704. errorChapterWorkflowStep(callbacks, repairStep, new Error(reason));
  1705. planCompliance = `${reason}:${recheckResult || "未返回有效结果"}`;
  1706. emitDeepChapterActivity(callbacks, {
  1707. id: `deep_chapter:plan_deviation_repair:output:${Date.now()}`,
  1708. stageId: "plan_deviation_repair",
  1709. kind: "stage_output",
  1710. title: "计划偏离点返修",
  1711. content: `${reason},已保留原正文。`,
  1712. });
  1713. }
  1714. } else {
  1715. errorChapterWorkflowStep(callbacks, repairStep, new Error(validation.reason));
  1716. emitDeepChapterActivity(callbacks, {
  1717. id: `deep_chapter:plan_deviation_repair:output:${Date.now()}`,
  1718. stageId: "plan_deviation_repair",
  1719. kind: "stage_output",
  1720. title: "计划偏离点返修",
  1721. content: [
  1722. "返修结果异常,已保留原正文。",
  1723. `原因:${validation.reason}。`,
  1724. `原正文:约 ${beforeChars} 字。`,
  1725. `返修结果:约 ${countChapterChars(repairedContent)} 字。`,
  1726. ].join("\n"),
  1727. });
  1728. }
  1729. } catch (error) {
  1730. rethrowIfUserAbort(error, signal);
  1731. console.error("[Deep Chapter] 计划偏离点返修失败:", error);
  1732. }
  1733. }
  1734. }
  1735. }
  1736. completeChapterWorkflowStep(
  1737. callbacks,
  1738. {
  1739. name: "chapter_complete",
  1740. title: workflowProfile.completionTitle,
  1741. detail: "汇总本次章节生成结果。",
  1742. params: workflowBaseParams,
  1743. },
  1744. `${workflowProfile.completionResultPrefix},最终正文约 ${countChapterChars(finalContent)} 字。`,
  1745. {
  1746. chars: countChapterChars(finalContent),
  1747. revised,
  1748. },
  1749. );
  1750. return {
  1751. finalContent,
  1752. taskBrief,
  1753. draftContent,
  1754. reviewResults,
  1755. revised,
  1756. planCompliance,
  1757. executionReport: executionReportSummary,
  1758. };
  1759. }
  1760. async function finalPolishChapter(
  1761. deAiConfig: LlmConfig,
  1762. outlinePrompt: string,
  1763. contextPrompt: string,
  1764. taskBrief: string,
  1765. currentContent: string,
  1766. input: DeepChapterGenerationInput,
  1767. _contextPack: ContextPack,
  1768. callbacks: DeepChapterGenerationCallbacks,
  1769. deps: DeepChapterGenerationDeps,
  1770. signal?: AbortSignal,
  1771. customDeAiSkill?: string,
  1772. cachePrefix?: string,
  1773. requestOverrides?: RequestOverrides,
  1774. ): Promise<string> {
  1775. assertNotAborted(signal);
  1776. callbacks.onThinking?.(
  1777. formatStageThinking(
  1778. "阶段6:简单审查与去AI味",
  1779. "正在进行最后一遍简单审查,去除复读、机械套话和 AI 味。",
  1780. ),
  1781. );
  1782. const polished = await collectModelText(
  1783. deAiConfig,
  1784. [
  1785. {
  1786. role: "user",
  1787. content: buildDeepChapterFinalPolishPrompt(
  1788. outlinePrompt,
  1789. contextPrompt,
  1790. taskBrief,
  1791. currentContent,
  1792. input.userRequest,
  1793. input.chapterNumber,
  1794. input.goldenThreeChapter,
  1795. customDeAiSkill,
  1796. ),
  1797. },
  1798. ],
  1799. deps,
  1800. signal,
  1801. (partial) =>
  1802. callbacks.onThinking?.(
  1803. formatStageThinking("阶段6:简单审查与去AI味", partial),
  1804. ),
  1805. requestOverrides,
  1806. cachePrefix,
  1807. callbacks.onRequestTrace,
  1808. );
  1809. assertNotAborted(signal);
  1810. return polished.trim() ? polished : currentContent;
  1811. }
  1812. function resolveCurrentChapterLengthSpec(): ChapterLengthSpec {
  1813. const novelConfig = useWikiStore.getState().novelConfig;
  1814. return resolveChapterLengthSpec(novelConfig?.chapterTargetChars);
  1815. }
  1816. function resolveWritingConfig(llmConfig: LlmConfig): LlmConfig {
  1817. // 写作模型已移除,始终使用 AI 会话当前模型。
  1818. // llmConfig 已在 chat-panel.tsx 中通过 effectiveChatLlmConfig 正确解析,
  1819. // 不再通过 resolveNovelModel 重新解析,避免二次解析使用不同 API 端点/密钥
  1820. return llmConfig;
  1821. }
  1822. /**
  1823. * 把以 cachePrefix 开头的 user 字符串消息拆成 [前缀块(cacheControl), 余下块],
  1824. * 让 provider 在稳定上下文前缀上打缓存断点。其余消息原样返回。
  1825. * 注:Anthropic/MiniMax 会据此发出 cache_control;OpenAI/DeepSeek 端纯文本块会被
  1826. * 折叠回与原字符串逐字节一致的内容,不影响其自动前缀缓存。
  1827. */
  1828. function applyCachePrefix(
  1829. messages: ChatMessage[],
  1830. cachePrefix?: string,
  1831. ): ChatMessage[] {
  1832. if (!cachePrefix) return messages;
  1833. return messages.map((message) => {
  1834. if (
  1835. message.role === "user" &&
  1836. typeof message.content === "string" &&
  1837. message.content.startsWith(cachePrefix)
  1838. ) {
  1839. const rest = message.content.slice(cachePrefix.length);
  1840. return {
  1841. role: message.role,
  1842. content: [
  1843. { type: "text" as const, text: cachePrefix, cacheControl: true },
  1844. ...(rest ? [{ type: "text" as const, text: rest }] : []),
  1845. ],
  1846. };
  1847. }
  1848. return message;
  1849. });
  1850. }
  1851. async function collectModelText(
  1852. config: LlmConfig,
  1853. messages: ChatMessage[],
  1854. deps: DeepChapterGenerationDeps,
  1855. signal?: AbortSignal,
  1856. onUpdate?: (content: string) => void,
  1857. requestOverrides?: RequestOverrides,
  1858. cachePrefix?: string,
  1859. onRequestTrace?: StreamCallbacks["onRequestTrace"],
  1860. ): Promise<string> {
  1861. let content = "";
  1862. let reasoningBuffer = "";
  1863. let streamError: Error | null = null;
  1864. let cutoffReason: string | null = null;
  1865. const streamController = new AbortController();
  1866. const combinedSignal = combineAbortSignals(signal, streamController.signal);
  1867. const stopStream = (reason: string) => {
  1868. if (cutoffReason) return;
  1869. cutoffReason = reason;
  1870. streamController.abort();
  1871. };
  1872. assertNotAborted(signal);
  1873. const callbacks: StreamCallbacks = {
  1874. onToken: (token) => {
  1875. if (signal?.aborted) {
  1876. stopStream(USER_ABORT_MESSAGE);
  1877. return;
  1878. }
  1879. content += token;
  1880. const loopStart = findRepeatedTailStart(content);
  1881. if (loopStart !== null) {
  1882. content = content.slice(0, loopStart).trimEnd();
  1883. onUpdate?.(
  1884. `${content}\n\n(已检测到模型重复输出,已自动停止重复内容。)`,
  1885. );
  1886. stopStream("检测到模型重复输出,已自动停止重复内容。");
  1887. return;
  1888. }
  1889. onUpdate?.(content);
  1890. },
  1891. onReasoningToken: (token) => {
  1892. if (signal?.aborted) {
  1893. stopStream(USER_ABORT_MESSAGE);
  1894. return;
  1895. }
  1896. // 推理 token 只用于进度显示,不计入最终 content
  1897. reasoningBuffer += token;
  1898. if (!content) {
  1899. onUpdate?.(reasoningBuffer);
  1900. }
  1901. },
  1902. onDone: () => {},
  1903. onError: (error) => {
  1904. streamError = error;
  1905. },
  1906. onRequestTrace,
  1907. };
  1908. const streamOnce = async (effectiveOverrides?: RequestOverrides) => {
  1909. streamError = null;
  1910. cutoffReason = null;
  1911. await deps.streamChat(
  1912. config,
  1913. applyCachePrefix(messages, cachePrefix),
  1914. callbacks,
  1915. combinedSignal,
  1916. effectiveOverrides,
  1917. );
  1918. };
  1919. await streamOnce(requestOverrides);
  1920. if (
  1921. streamError &&
  1922. isReasoningOnlyResponseError(streamError) &&
  1923. !isReasoningDisabled(config, requestOverrides)
  1924. ) {
  1925. content = "";
  1926. reasoningBuffer = "";
  1927. onUpdate?.("模型只返回思考过程,正在自动切换为非推理模式重试当前阶段。");
  1928. await streamOnce(withReasoningDisabled(requestOverrides));
  1929. }
  1930. if (signal?.aborted) throw new Error(USER_ABORT_MESSAGE);
  1931. if (streamError && !(cutoffReason && isRequestCancelledError(streamError)))
  1932. throw streamError;
  1933. if (cutoffReason) {
  1934. onUpdate?.(`${content.trim()}\n\n(${cutoffReason})`);
  1935. }
  1936. return content.trim();
  1937. }
  1938. function countChapterChars(content: string): number {
  1939. return content.replace(/\s+/g, "").length;
  1940. }
  1941. function formatPlanComplianceActivityContent(
  1942. result: ParsedChapterPlanComplianceResult,
  1943. willRepair: boolean,
  1944. ): string {
  1945. const decision = result.status === "unknown"
  1946. ? "未触发返修"
  1947. : willRepair
  1948. ? "触发轻量返修"
  1949. : "无需返修";
  1950. const lines = [
  1951. `履约状态:${chapterPlanComplianceStatusLabel(result.status)}`,
  1952. `偏离点数量:${result.deviations.length}`,
  1953. `处理决定:${decision}`,
  1954. ];
  1955. if (result.status === "unknown") {
  1956. lines.push("原因:模型未按结构返回,已避免误改正文");
  1957. }
  1958. if (result.summary.trim()) {
  1959. lines.push(`总评:${result.summary.trim()}`);
  1960. }
  1961. if (result.deviations.length > 0) {
  1962. lines.push("");
  1963. lines.push("偏离点:");
  1964. for (const [index, item] of result.deviations.slice(0, 5).entries()) {
  1965. lines.push(`${index + 1}. ${item.point || "未说明偏离点"}`);
  1966. if (item.evidence) lines.push(` 正文证据:${item.evidence}`);
  1967. if (item.suggestion) lines.push(` 建议修正:${item.suggestion}`);
  1968. }
  1969. }
  1970. return lines.join("\n");
  1971. }
  1972. function chapterPlanComplianceStatusLabel(
  1973. status: ParsedChapterPlanComplianceResult["status"],
  1974. ): string {
  1975. if (status === "compliant") return "符合";
  1976. if (status === "mostly_compliant") return "基本符合";
  1977. if (status === "partial_deviation") return "部分偏离";
  1978. if (status === "clear_deviation") return "明显偏离";
  1979. return "未知";
  1980. }
  1981. function buildPlanDeviationRepairReturnContent(
  1982. result: ParsedChapterPlanComplianceResult,
  1983. beforeChars: number,
  1984. afterChars: number,
  1985. ): string {
  1986. const lines = [
  1987. "计划偏离点返修:已完成",
  1988. `返修前履约状态:${chapterPlanComplianceStatusLabel(result.status)}`,
  1989. `已处理偏离点数量:${result.deviations.length}`,
  1990. `返修前:约 ${beforeChars} 字。`,
  1991. `返修后:约 ${afterChars} 字。`,
  1992. "最终正文已按计划偏离点轻量返修结果更新。",
  1993. ];
  1994. const handledPoints = result.deviations
  1995. .map((item) => item.point.trim())
  1996. .filter(Boolean)
  1997. .slice(0, 5);
  1998. if (handledPoints.length > 0) {
  1999. lines.push("");
  2000. lines.push("已处理偏离点:");
  2001. handledPoints.forEach((point, index) => {
  2002. lines.push(`${index + 1}. ${point}`);
  2003. });
  2004. }
  2005. return lines.join("\n");
  2006. }
  2007. function validateChapterPlanRepairResult(
  2008. originalContent: string,
  2009. repairedContent: string,
  2010. ): { accepted: boolean; reason: string } {
  2011. const repaired = repairedContent.trim();
  2012. if (!repaired) {
  2013. return { accepted: false, reason: "返修未返回有效正文" };
  2014. }
  2015. if (
  2016. normalizeContentForAnchorCheck(originalContent) ===
  2017. normalizeContentForAnchorCheck(repaired)
  2018. ) {
  2019. return { accepted: false, reason: "返修正文没有发生有效变化" };
  2020. }
  2021. const originalChars = countChapterChars(originalContent);
  2022. const repairedChars = countChapterChars(repaired);
  2023. if (originalChars >= 1000 && repairedChars < originalChars * 0.7) {
  2024. return { accepted: false, reason: "返修后正文明显变短" };
  2025. }
  2026. if (originalChars >= 1000 && repairedChars > originalChars * 1.5) {
  2027. return { accepted: false, reason: "返修后正文明显变长" };
  2028. }
  2029. if (originalChars >= 1000 && !hasEnoughOriginalContentAnchors(originalContent, repaired)) {
  2030. return { accepted: false, reason: "返修后未保留原正文主要内容" };
  2031. }
  2032. return { accepted: true, reason: "" };
  2033. }
  2034. function hasEnoughOriginalContentAnchors(originalContent: string, repairedContent: string): boolean {
  2035. const original = normalizeContentForAnchorCheck(originalContent);
  2036. const repaired = normalizeContentForAnchorCheck(repairedContent);
  2037. if (original.length < 240 || repaired.length < 240) return true;
  2038. const anchors: string[] = [];
  2039. const windowSize = 14;
  2040. const step = Math.max(80, Math.floor(original.length / 20));
  2041. for (let index = 0; index + windowSize <= original.length; index += step) {
  2042. anchors.push(original.slice(index, index + windowSize));
  2043. if (anchors.length >= 20) break;
  2044. }
  2045. if (anchors.length === 0) return true;
  2046. const preservedCount = anchors.filter((anchor) => repaired.includes(anchor)).length;
  2047. return preservedCount >= Math.max(2, Math.ceil(anchors.length * 0.15));
  2048. }
  2049. function normalizeContentForAnchorCheck(content: string): string {
  2050. return content.replace(/[\s\p{P}\p{S}]+/gu, "");
  2051. }
  2052. function assertNotAborted(signal?: AbortSignal): void {
  2053. throwIfAborted(signal);
  2054. }
  2055. function isRequestCancelledError(error: Error): boolean {
  2056. return /request cancelled|request canceled|aborted|aborterror/i.test(
  2057. error.message,
  2058. );
  2059. }
  2060. function getErrorMessage(error: unknown): string {
  2061. return error instanceof Error ? error.message : String(error);
  2062. }
  2063. function combineAbortSignals(
  2064. ...signals: Array<AbortSignal | undefined>
  2065. ): AbortSignal | undefined {
  2066. const activeSignals = signals.filter(Boolean) as AbortSignal[];
  2067. if (activeSignals.length === 0) return undefined;
  2068. if (activeSignals.length === 1) return activeSignals[0];
  2069. const controller = new AbortController();
  2070. const abort = () => controller.abort();
  2071. for (const signal of activeSignals) {
  2072. if (signal.aborted) {
  2073. controller.abort();
  2074. break;
  2075. }
  2076. signal.addEventListener("abort", abort, { once: true });
  2077. }
  2078. return controller.signal;
  2079. }
  2080. function findRepeatedTailStart(content: string): number | null {
  2081. const normalized = content.replace(/\r\n/g, "\n");
  2082. const compact = normalized.replace(/\s+/g, "");
  2083. if (compact.length < REPEAT_CHECK_MIN_CHARS) return null;
  2084. const tail = compact.slice(-REPEAT_WINDOW_CHARS);
  2085. const first = compact.indexOf(tail);
  2086. if (first === -1 || first >= compact.length - REPEAT_WINDOW_CHARS)
  2087. return null;
  2088. let hits = 0;
  2089. let searchIndex = 0;
  2090. while (true) {
  2091. const found = compact.indexOf(tail, searchIndex);
  2092. if (found === -1) break;
  2093. hits += 1;
  2094. if (hits >= REPEAT_HIT_LIMIT) {
  2095. return sourceIndexFromCompactIndex(
  2096. normalized,
  2097. first + REPEAT_WINDOW_CHARS,
  2098. );
  2099. }
  2100. searchIndex = found + Math.max(1, tail.length);
  2101. }
  2102. return null;
  2103. }
  2104. function sourceIndexFromCompactIndex(
  2105. content: string,
  2106. compactIndex: number,
  2107. ): number {
  2108. let seen = 0;
  2109. for (let index = 0; index < content.length; index += 1) {
  2110. if (/\s/.test(content[index])) continue;
  2111. seen += 1;
  2112. if (seen >= compactIndex) return index + 1;
  2113. }
  2114. return content.length;
  2115. }
  2116. function formatContextThinking(
  2117. input: DeepChapterGenerationInput,
  2118. pack: ContextPack,
  2119. ): string {
  2120. const recentSummaries = Array.isArray(pack.recentSummaries)
  2121. ? pack.recentSummaries
  2122. : [];
  2123. const goldenThreeHints = resolveGoldenThreeThinkingHints(
  2124. input.goldenThreeChapter,
  2125. );
  2126. return formatStageThinking(
  2127. "阶段1:上下文分析",
  2128. [
  2129. ...goldenThreeHints,
  2130. input.chapterNumber
  2131. ? `目标章节:第${input.chapterNumber}章`
  2132. : "目标章节:从用户请求中识别",
  2133. `章节目标:${fallback(pack.chapterGoal, "未读取到明确章节目标")}`,
  2134. `上一章结尾:${fallback(pack.previousChapterEnding, "未读取到上一章结尾")}`,
  2135. `近期剧情:${recentSummaries.length} 条`,
  2136. `人物状态:${summaryText(pack.characterStates)}`,
  2137. `伏笔状态:${summaryText(pack.foreshadowingStates)}`,
  2138. `时间线:${summaryText(pack.timeline)}`,
  2139. `禁止违背:${fallback(pack.mustAvoid, "暂无明确禁止项")}`,
  2140. `必须完成:${fallback(pack.mustDo, "暂无明确必做项")}`,
  2141. ].join("\n"),
  2142. );
  2143. }
  2144. function formatContextExtractionResult(
  2145. input: DeepChapterGenerationInput,
  2146. pack: ContextPack,
  2147. ): string {
  2148. const recentSummaries = Array.isArray(pack.recentSummaries)
  2149. ? pack.recentSummaries
  2150. : [];
  2151. return [
  2152. input.chapterNumber
  2153. ? `目标章节:第${input.chapterNumber}章`
  2154. : "目标章节:从用户请求识别",
  2155. `章节目标:${fallback(pack.chapterGoal, "未读取到明确章节目标")}`,
  2156. `上一章结尾:${fallback(pack.previousChapterEnding, "未读取到上一章结尾")}`,
  2157. `近期剧情:${recentSummaries.length} 条`,
  2158. `人物状态:${summaryText(pack.characterStates)}`,
  2159. `伏笔状态:${summaryText(pack.foreshadowingStates)}`,
  2160. `时间线:${summaryText(pack.timeline)}`,
  2161. `必须完成:${fallback(pack.mustDo, "暂无明确必做项")}`,
  2162. `禁止违背:${fallback(pack.mustAvoid, "暂无明确禁止项")}`,
  2163. ].join("\n");
  2164. }
  2165. function formatReviewThinking(reviewResults: NovelReviewResult[]): string {
  2166. if (reviewResults.length === 0) {
  2167. return formatStageThinking("阶段4:AI审稿", "未发现阻断问题。");
  2168. }
  2169. const characterIssues = reviewResults.filter(
  2170. (item) => item.type === "character_consistency",
  2171. );
  2172. const otherIssues = reviewResults.filter(
  2173. (item) => item.type !== "character_consistency",
  2174. );
  2175. const errorCount = reviewResults.filter(
  2176. (item) => item.severity === "error",
  2177. ).length;
  2178. const sections: string[] = [
  2179. `发现 ${reviewResults.length} 个问题,其中阻断问题 ${errorCount} 个。`,
  2180. ];
  2181. // 角色命中记忆库报告(单独展示 character_consistency 类型的问题)
  2182. if (characterIssues.length > 0) {
  2183. sections.push("");
  2184. sections.push("【角色命中记忆库报告】");
  2185. sections.push(formatReviewIssueList(characterIssues));
  2186. }
  2187. // 其他问题
  2188. if (otherIssues.length > 0) {
  2189. sections.push("");
  2190. sections.push("【其他审查问题】");
  2191. sections.push(formatReviewIssueList(otherIssues));
  2192. }
  2193. return formatStageThinking("阶段4:AI审稿", sections.join("\n"));
  2194. }
  2195. function formatStageThinking(title: string, content: string): string {
  2196. return `## ${title}\n${content.trim()}`;
  2197. }
  2198. function formatReviewIssueList(reviewResults: NovelReviewResult[]): string {
  2199. return reviewResults
  2200. .map((item, index) =>
  2201. [
  2202. `${index + 1}. [${severityLabel(item.severity)}] ${item.message}`,
  2203. item.evidence ? ` - 证据:${item.evidence}` : "",
  2204. item.relatedMemory ? ` - 相关记忆:${item.relatedMemory}` : "",
  2205. item.suggestion ? ` - 建议:${item.suggestion}` : "",
  2206. ]
  2207. .filter(Boolean)
  2208. .join("\n"),
  2209. )
  2210. .join("\n");
  2211. }
  2212. function fallback(
  2213. value: string | null | undefined,
  2214. fallbackText: string,
  2215. ): string {
  2216. const trimmed = typeof value === "string" ? value.trim() : "";
  2217. return trimmed ? trimForThinking(trimmed, 180) : fallbackText;
  2218. }
  2219. function summaryText(value: string | null | undefined): string {
  2220. const trimmed = typeof value === "string" ? value.trim() : "";
  2221. return trimmed ? trimForThinking(trimmed, 140) : "暂无";
  2222. }
  2223. function trimForThinking(value: string, maxLength: number): string {
  2224. const normalized = value.replace(/\s+/g, " ").trim();
  2225. if (normalized.length <= maxLength) return normalized;
  2226. return `${normalized.slice(0, maxLength)}...`;
  2227. }
  2228. function severityLabel(severity: NovelReviewResult["severity"]): string {
  2229. if (severity === "error") return "严重";
  2230. if (severity === "warning") return "提醒";
  2231. return "信息";
  2232. }
  2233. function resolveGoldenThreeThinkingHints(
  2234. goldenThreeChapter?: GoldenThreeChapterRequest,
  2235. ): string[] {
  2236. if (!goldenThreeChapter?.enabled || !goldenThreeChapter.targetChapter)
  2237. return [];
  2238. if (goldenThreeChapter.outputMode === "first_chapter_with_directions") {
  2239. return [
  2240. "黄金三章:已启用",
  2241. "执行策略:当前按黄金三章规则生成第1章正文,并在正文后给出第2章、第3章写作方向。",
  2242. ];
  2243. }
  2244. return [
  2245. "黄金三章:已启用",
  2246. `执行策略:当前按黄金三章规则生成第${goldenThreeChapter.targetChapter}章正文。`,
  2247. ];
  2248. }
  2249. async function maybeInjectWritingEntityWebSearch(args: {
  2250. input: DeepChapterGenerationInput;
  2251. deps: DeepChapterGenerationDeps;
  2252. contextPack: ContextPack;
  2253. previousChaptersAnalysis: string;
  2254. planBlueprint?: string;
  2255. workflowConfig: LlmConfig;
  2256. callbacks: DeepChapterGenerationCallbacks;
  2257. signal?: AbortSignal;
  2258. }): Promise<ContextPack> {
  2259. const collect = args.deps.collectWritingEntityWebSearch ?? collectWritingEntityWebSearch;
  2260. try {
  2261. args.callbacks.onThinking?.(
  2262. formatStageThinking("联网搜索", "正在核对本库实体,必要时联网补搜..."),
  2263. );
  2264. const result = await collect({
  2265. projectPath: args.input.projectPath,
  2266. userRequest: args.input.userRequest,
  2267. outline: args.contextPack.outline,
  2268. planBlueprint: args.planBlueprint,
  2269. contextPack: args.contextPack,
  2270. chapterNumber: args.input.chapterNumber,
  2271. previousChaptersAnalysis: args.previousChaptersAnalysis,
  2272. streamChat: args.deps.streamChat,
  2273. llmConfig: args.workflowConfig,
  2274. searchApiConfig: useWikiStore.getState().searchApiConfig,
  2275. signal: args.signal,
  2276. onRequestTrace: args.callbacks.onRequestTrace,
  2277. });
  2278. if (result.searchedNames.length > 0 || result.markdown.trim()) {
  2279. emitDeepChapterActivity(args.callbacks, {
  2280. id: `deep_chapter:entity_web_search:${Date.now()}`,
  2281. stageId: "read_context",
  2282. kind: "web_search",
  2283. title: "联网搜索",
  2284. content: [
  2285. result.searchedNames.length > 0
  2286. ? `已搜索:${result.searchedNames.join("、")}`
  2287. : "未发起联网搜索",
  2288. ...result.notes,
  2289. ].filter(Boolean).join("\n"),
  2290. });
  2291. }
  2292. if (!result.markdown.trim()) return args.contextPack;
  2293. return {
  2294. ...args.contextPack,
  2295. searchResults: [args.contextPack.searchResults?.trim(), result.markdown.trim()]
  2296. .filter(Boolean)
  2297. .join("\n\n"),
  2298. };
  2299. } catch (error) {
  2300. rethrowIfUserAbort(error, args.signal);
  2301. console.error("[deep-chapter-generation] 实体联网补搜失败:", error);
  2302. return args.contextPack;
  2303. }
  2304. }
  2305. async function safeBuildChapterContextPack(
  2306. deps: DeepChapterGenerationDeps,
  2307. projectPath: string,
  2308. userRequest: string,
  2309. chapterNumber?: number,
  2310. signal?: AbortSignal,
  2311. ): Promise<ContextPack> {
  2312. try {
  2313. throwIfAborted(signal);
  2314. return await waitForAbortable(
  2315. deps.buildContextPack(projectPath, userRequest, chapterNumber),
  2316. signal,
  2317. );
  2318. } catch (error) {
  2319. rethrowIfUserAbort(error, signal);
  2320. return {
  2321. task: userRequest,
  2322. chapterGoal: "",
  2323. outline: "",
  2324. recentSummaries: [],
  2325. previousChapterEnding: "",
  2326. characterStates: "",
  2327. soulDoc: "",
  2328. characterAuras: "",
  2329. storyFrameworkBinding: "",
  2330. cognitionStates: "",
  2331. foreshadowingStates: "",
  2332. timeline: "",
  2333. relatedSettings: "",
  2334. canonRules: "",
  2335. writingStyle: "",
  2336. searchResults: "",
  2337. graphSearchResults: "",
  2338. mustDo: "",
  2339. mustAvoid: "",
  2340. nextChapterAdvice: "",
  2341. revisionDirectives: "",
  2342. };
  2343. }
  2344. }
  2345. function waitForAbortable<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
  2346. if (!signal) return operation;
  2347. throwIfAborted(signal);
  2348. return new Promise<T>((resolve, reject) => {
  2349. const handleAbort = () => reject(new Error(USER_ABORT_MESSAGE));
  2350. signal.addEventListener("abort", handleAbort, { once: true });
  2351. operation.then(
  2352. (value) => {
  2353. signal.removeEventListener("abort", handleAbort);
  2354. resolve(value);
  2355. },
  2356. (error) => {
  2357. signal.removeEventListener("abort", handleAbort);
  2358. reject(error);
  2359. },
  2360. );
  2361. });
  2362. }