@waterwx/dsh-novel-forge 1.0.0 → 1.1.0-alpha

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.
Files changed (125) hide show
  1. package/README.md +231 -206
  2. package/lib/client.js +55052 -4393
  3. package/lib/index.js +12013 -2524
  4. package/lib/types/ai-scan.d.ts +36 -0
  5. package/lib/types/assets.d.ts +19 -4
  6. package/lib/types/assistant.d.ts +6 -0
  7. package/lib/types/author-assets.d.ts +25 -0
  8. package/lib/types/bookshelf.d.ts +11 -1
  9. package/lib/types/client/api.d.ts +210 -4
  10. package/lib/types/client/docx.d.ts +2 -0
  11. package/lib/types/client/index.d.ts +1 -1
  12. package/lib/types/client/llmLive.d.ts +33 -0
  13. package/lib/types/client/locales.d.ts +102 -29
  14. package/lib/types/client/panel/AdaptModeView.d.ts +5 -0
  15. package/lib/types/client/panel/AiTag.d.ts +1 -0
  16. package/lib/types/client/panel/AuthorAssetsView.d.ts +4 -0
  17. package/lib/types/client/panel/AuthorHome.d.ts +34 -0
  18. package/lib/types/client/panel/BookAnalysisView.d.ts +4 -0
  19. package/lib/types/client/panel/CmdPalette.d.ts +12 -0
  20. package/lib/types/client/panel/CreateBookView.d.ts +13 -0
  21. package/lib/types/client/panel/DirectorView.d.ts +7 -0
  22. package/lib/types/client/panel/GlobalAssetLibraryView.d.ts +4 -0
  23. package/lib/types/client/panel/IdeaInspirationView.d.ts +6 -0
  24. package/lib/types/client/panel/ImportModal.d.ts +7 -0
  25. package/lib/types/client/panel/KnowledgeBaseView.d.ts +4 -0
  26. package/lib/types/client/panel/LiveFeedLog.d.ts +8 -0
  27. package/lib/types/client/panel/MarketRadarView.d.ts +5 -0
  28. package/lib/types/client/panel/ModelManager.d.ts +14 -0
  29. package/lib/types/client/panel/NovelPanel.d.ts +6 -1
  30. package/lib/types/client/panel/PageHeader.d.ts +18 -0
  31. package/lib/types/client/panel/ProgressConsole.d.ts +17 -0
  32. package/lib/types/client/panel/ProgressHomeView.d.ts +5 -0
  33. package/lib/types/client/panel/ReaderView.d.ts +8 -0
  34. package/lib/types/client/panel/ReasoningSection.d.ts +10 -0
  35. package/lib/types/client/panel/RunPanel.d.ts +5 -0
  36. package/lib/types/client/panel/SettingsView.d.ts +19 -0
  37. package/lib/types/client/panel/ShelfView.d.ts +24 -0
  38. package/lib/types/client/panel/SubPage.d.ts +27 -0
  39. package/lib/types/client/panel/WorldTab.d.ts +10 -0
  40. package/lib/types/client/panel/helpers.d.ts +10 -0
  41. package/lib/types/client/panel/toast.d.ts +2 -0
  42. package/lib/types/client/panel/views.d.ts +95 -0
  43. package/lib/types/client/run-status.d.ts +19 -0
  44. package/lib/types/client/text.d.ts +9 -0
  45. package/lib/types/docx-core.d.ts +16 -0
  46. package/lib/types/docx.d.ts +2 -3
  47. package/lib/types/engine.d.ts +228 -5
  48. package/lib/types/global-assets.d.ts +6 -0
  49. package/lib/types/index.d.ts +24 -2
  50. package/lib/types/llm-live.d.ts +44 -0
  51. package/lib/types/market-radar-scan.d.ts +19 -0
  52. package/lib/types/market-radar-sources.d.ts +31 -0
  53. package/lib/types/migrate-output.d.ts +25 -0
  54. package/lib/types/novel-context.d.ts +80 -0
  55. package/lib/types/prompt-utils.d.ts +35 -0
  56. package/lib/types/prompting.d.ts +10 -0
  57. package/lib/types/protocol.d.ts +1418 -7
  58. package/lib/types/review-policy.d.ts +97 -0
  59. package/lib/types/routes.d.ts +4 -0
  60. package/lib/types/run.d.ts +34 -0
  61. package/package.json +120 -93
  62. package/scripts/patch-schemastery.mjs +47 -0
  63. package/src/ai-scan.ts +179 -0
  64. package/src/assets.ts +1774 -518
  65. package/src/assistant.ts +915 -568
  66. package/src/author-assets.ts +149 -0
  67. package/src/bookshelf.ts +187 -148
  68. package/src/client/api.ts +675 -289
  69. package/src/client/docx.ts +37 -69
  70. package/src/client/index.ts +3 -1
  71. package/src/client/llmLive.ts +101 -0
  72. package/src/client/locales.ts +418 -271
  73. package/src/client/mount.tsx +1 -1
  74. package/src/client/panel/AdaptModeView.tsx +535 -0
  75. package/src/client/panel/AiTag.tsx +7 -0
  76. package/src/client/panel/AssetsTab.tsx +448 -456
  77. package/src/client/panel/AssistantTab.tsx +339 -188
  78. package/src/client/panel/AuthorAssetsView.tsx +206 -0
  79. package/src/client/panel/AuthorHome.tsx +309 -0
  80. package/src/client/panel/BookAnalysisView.tsx +63 -0
  81. package/src/client/panel/CmdPalette.tsx +102 -0
  82. package/src/client/panel/CreateBookView.tsx +366 -0
  83. package/src/client/panel/DirectorView.tsx +200 -0
  84. package/src/client/panel/GlobalAssetLibraryView.tsx +168 -0
  85. package/src/client/panel/IdeaInspirationView.tsx +76 -0
  86. package/src/client/panel/ImportModal.tsx +303 -0
  87. package/src/client/panel/KnowledgeBaseView.tsx +125 -0
  88. package/src/client/panel/LiveFeedLog.tsx +67 -0
  89. package/src/client/panel/MarketRadarView.tsx +377 -0
  90. package/src/client/panel/ModelManager.tsx +205 -0
  91. package/src/client/panel/NovelPanel.tsx +5374 -2159
  92. package/src/client/panel/PageHeader.tsx +37 -0
  93. package/src/client/panel/ProgressConsole.tsx +63 -0
  94. package/src/client/panel/ReaderView.tsx +306 -0
  95. package/src/client/panel/ReasoningSection.tsx +31 -0
  96. package/src/client/panel/RunPanel.tsx +223 -0
  97. package/src/client/panel/SettingsView.tsx +305 -0
  98. package/src/client/panel/ShelfView.tsx +266 -0
  99. package/src/client/panel/SubPage.tsx +42 -0
  100. package/src/client/panel/WorldTab.tsx +202 -0
  101. package/src/client/panel/helpers.ts +50 -0
  102. package/src/client/panel/panel.module.css +5764 -1698
  103. package/src/client/panel/toast.ts +51 -0
  104. package/src/client/panel/views.tsx +401 -0
  105. package/src/client/run-status.ts +143 -0
  106. package/src/client/sidebar-entry.ts +1 -1
  107. package/src/client/text.ts +28 -0
  108. package/src/docx-core.ts +53 -0
  109. package/src/docx.ts +44 -83
  110. package/src/engine.ts +4155 -1233
  111. package/src/global-assets.ts +59 -0
  112. package/src/index.ts +311 -184
  113. package/src/llm-live.ts +68 -0
  114. package/src/market-radar-scan.ts +41 -0
  115. package/src/market-radar-sources.ts +173 -0
  116. package/src/migrate-output.ts +76 -0
  117. package/src/novel-context.ts +286 -0
  118. package/src/prompting.ts +26 -0
  119. package/src/protocol.ts +2046 -623
  120. package/src/review-policy.ts +161 -0
  121. package/src/routes.ts +3391 -1172
  122. package/src/run.ts +341 -0
  123. package/lib/client.js.map +0 -1
  124. package/lib/index.js.map +0 -1
  125. package/src/client/panel/BookshelfBar.tsx +0 -170
package/src/routes.ts CHANGED
@@ -1,1172 +1,3391 @@
1
- /**
2
- * The /api/dsh-novel-forge route family: status, docx outline loading, LLM
3
- * story-bible extraction, volume planning, chapter planning, streaming
4
- * generation / rewrite / polish (NDJSON frames), review, summaries,
5
- * foreshadows, export, chapter reading, config patching, and opening the
6
- * output folder. Every route carries the same loopback-only trust fence as
7
- * the family plugins — these endpoints invoke the LLM and write files on the
8
- * host machine.
9
- */
10
-
11
- import type { IncomingMessage, ServerResponse } from 'node:http'
12
- import { exec } from 'node:child_process'
13
- import { copyFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs'
14
- import { join } from 'node:path'
15
- import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
16
- import type { Context } from '@deepseek-ai/cordis'
17
- import {
18
- NOVEL_API,
19
- type AssetsPatch,
20
- type AssetsResponse,
21
- type AssistantFrame,
22
- type AssistantHistoryResponse,
23
- type AssistantRequest,
24
- type AuditResponse,
25
- type BiblePatchRequest,
26
- type BibleRequest,
27
- type BibleResponse,
28
- type BookActivateRequest,
29
- type BookCreateRequest,
30
- type BookRemoveRequest,
31
- type BookshelfSnapshot,
32
- type ChapterResponse,
33
- type ChapterPlan,
34
- type ConfigPatch,
35
- type DraftDecisionRequest,
36
- type ExportRequest,
37
- type ExportResponse,
38
- type ForeshadowRequest,
39
- type ForeshadowResponse,
40
- type JobFrame,
41
- type LoadOutlineRequest,
42
- type LoadOutlineResponse,
43
- type NovelConfig,
44
- type PlanRequest,
45
- type PlanResponse,
46
- type PolishRequest,
47
- type ResetRequest,
48
- type ReviewRequest,
49
- type RewriteRequest,
50
- type StatusResponse,
51
- type StyleEngineRequest,
52
- type SummaryRequest,
53
- type VolumesRequest,
54
- type VolumesResponse,
55
- } from './protocol.ts'
56
- import { readOutlineFromDocx } from './docx.ts'
57
- import { loadAssistantHistory, runAssistantTurn } from './assistant.ts'
58
- import { activateBook, bookshelfSnapshot, createBook, defaultOutputDirFor, loadBookshelf, removeBook, renameBook, seedBookshelfFromOutputDir } from './bookshelf.ts'
59
- import { BUILTIN_ANTI_AI_RULES, BUILTIN_GENRE_LIBRARY, BUILTIN_PROGRESSION_MODES, BUILTIN_STYLE_TEMPLATES, emptyProjectAssets } from './assets.ts'
60
- import {
61
- chapterFileName,
62
- auditBook,
63
- backfillFacts,
64
- createProject,
65
- exportBook,
66
- extractBible,
67
- extractFacts,
68
- extractStyleAsset,
69
- generateChapterStream,
70
- listChapterFiles,
71
- loadProject,
72
- planChapters,
73
- planVolumes,
74
- polishChapterStream,
75
- readChapterFile,
76
- refreshCharacters,
77
- reviewChapter,
78
- rewriteChapterStream,
79
- saveProject,
80
- suggestForeshadows,
81
- summarizeChapter,
82
- syncProjectWithDisk,
83
- } from './engine.ts'
84
-
85
- /** Cap on JSON request bodies. */
86
- const MAX_JSON_BODY_BYTES = 4 * 1024 * 1024
87
-
88
- /** Loopback-only fence (mirrors the family plugins' pairing routes). */
89
- function isLoopbackRequest(request: IncomingMessage): boolean {
90
- const address = request.socket.remoteAddress
91
- if (address !== '127.0.0.1' && address !== '::1' && address !== '::ffff:127.0.0.1') return false
92
- const host = request.headers.host
93
- if (typeof host !== 'string') return false
94
- let hostUrl: URL
95
- try {
96
- hostUrl = new URL(`http://${host}`)
97
- } catch {
98
- return false
99
- }
100
- if (hostUrl.hostname !== '127.0.0.1' && hostUrl.hostname !== 'localhost' && hostUrl.hostname !== '[::1]') return false
101
- if (request.headers['sec-fetch-site'] === 'cross-site') return false
102
- const origin = request.headers.origin
103
- if (origin === undefined) return true
104
- try {
105
- return new URL(origin).host === hostUrl.host
106
- } catch {
107
- return false
108
- }
109
- }
110
-
111
- /** One JSON response. */
112
- function writeJson(res: ServerResponse, status: number, body: unknown): void {
113
- const payload = JSON.stringify(body)
114
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'referrer-policy': 'no-referrer' })
115
- res.end(payload)
116
- }
117
-
118
- /** Read a JSON request body. */
119
- async function readJsonBody<T>(req: IncomingMessage): Promise<T | undefined> {
120
- const chunks: Buffer[] = []
121
- let size = 0
122
- for await (const chunk of req) {
123
- const buffer = chunk as Buffer
124
- size += buffer.length
125
- if (size > MAX_JSON_BODY_BYTES) return undefined
126
- chunks.push(buffer)
127
- }
128
- try {
129
- return JSON.parse(Buffer.concat(chunks).toString('utf8')) as T
130
- } catch {
131
- return undefined
132
- }
133
- }
134
-
135
- /** Route deps. */
136
- export interface NovelRoutesDeps {
137
- ctx: Context
138
- /** Resolve the live plugin config (settings-aware). */
139
- getConfig: () => NovelConfig
140
- /** Persist a config patch through the settings seam. */
141
- patchConfig: (patch: ConfigPatch) => Promise<NovelConfig>
142
- }
143
-
144
- /** Default chapter count for planning when the request omits it. */
145
- const DEFAULT_PLAN_COUNT = 30
146
-
147
- /**
148
- * Build every /api/dsh-novel-forge route.
149
- * @param deps - context, config resolver, config patcher.
150
- * @returns the route list.
151
- */
152
- export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
153
- const { ctx, getConfig, patchConfig } = deps
154
-
155
- /** Guard helper: fence + method check. */
156
- const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
157
- if (!isLoopbackRequest(req)) {
158
- writeJson(res, 403, { error: 'forbidden: loopback-only' })
159
- return false
160
- }
161
- if (req.method !== method) {
162
- writeJson(res, 405, { error: `method not allowed (expected ${method})` })
163
- return false
164
- }
165
- return true
166
- }
167
-
168
- /** Load (and sync) the project, or respond 400. */
169
- const requireProject = (res: ServerResponse): ReturnType<typeof loadProject> => {
170
- const config = getConfig()
171
- const project = loadProject(config.outputDir)
172
- if (project === undefined) {
173
- writeJson(res, 400, { error: '输出目录中没有项目,请先加载大纲' })
174
- return undefined
175
- }
176
- syncProjectWithDisk(project, config.outputDir)
177
- saveProject(config.outputDir, project)
178
- return project
179
- }
180
-
181
- // -------------------------------------------------------------- status
182
- const statusRoute: WebRoute = {
183
- kind: 'exact',
184
- path: NOVEL_API.status,
185
- handler: (req, res) => {
186
- if (!guard(req, res, 'GET')) return
187
- const config = getConfig()
188
- // 书架为空时播种 settings 默认输出目录里的已有项目。
189
- seedBookshelfFromOutputDir(config.outputDir)
190
- const project = loadProject(config.outputDir)
191
- if (project !== undefined) {
192
- syncProjectWithDisk(project, config.outputDir)
193
- saveProject(config.outputDir, project)
194
- }
195
- const response: StatusResponse = {
196
- config,
197
- project: project ?? undefined,
198
- generatedFiles: listChapterFiles(config.outputDir),
199
- }
200
- writeJson(res, 200, response)
201
- },
202
- }
203
-
204
- // -------------------------------------------------------- load-outline
205
- const loadOutlineRoute: WebRoute = {
206
- kind: 'exact',
207
- path: NOVEL_API.loadOutline,
208
- handler: async (req, res) => {
209
- if (!guard(req, res, 'POST')) return
210
- const body = await readJsonBody<LoadOutlineRequest>(req)
211
- const config = getConfig()
212
- try {
213
- let outline: string
214
- let path: string | undefined
215
- if (body?.text !== undefined && body.text.trim() !== '') {
216
- outline = body.text.trim()
217
- } else {
218
- const target = body?.path?.trim() !== '' && body?.path !== undefined ? body.path : config.outlinePath
219
- outline = readOutlineFromDocx(target)
220
- path = target
221
- }
222
- if (outline.length < 50) {
223
- writeJson(res, 400, { error: '大纲内容过短(<50 字符),请检查文件或直接粘贴大纲文本' })
224
- return
225
- }
226
- const response: LoadOutlineResponse = {
227
- outline,
228
- bookName: createProject(outline).bookName,
229
- chars: outline.length,
230
- path,
231
- }
232
- writeJson(res, 200, response)
233
- } catch (error) {
234
- writeJson(res, 400, { error: (error as Error).message })
235
- }
236
- },
237
- }
238
-
239
- // -------------------------------------------------------- save-outline
240
- const saveOutlineRoute: WebRoute = {
241
- kind: 'exact',
242
- path: NOVEL_API.saveOutline,
243
- handler: async (req, res) => {
244
- if (!guard(req, res, 'POST')) return
245
- const body = await readJsonBody<LoadOutlineRequest>(req)
246
- const config = getConfig()
247
- const outline = body?.text ?? ''
248
- if (outline.trim().length < 50) {
249
- writeJson(res, 400, { error: '大纲内容过短(<50 字符)' })
250
- return
251
- }
252
- let project = loadProject(config.outputDir)
253
- const now = new Date().toISOString()
254
- if (project === undefined) {
255
- project = createProject(outline)
256
- } else {
257
- project.outline = outline
258
- project.bookName = createProject(outline).bookName
259
- project.updatedAt = now
260
- }
261
- saveProject(config.outputDir, project)
262
- writeJson(res, 200, { ok: true, bookName: project.bookName })
263
- },
264
- }
265
-
266
- // --------------------------------------------------------------- bible
267
- const bibleRoute: WebRoute = {
268
- kind: 'exact',
269
- path: NOVEL_API.bible,
270
- handler: async (req, res) => {
271
- if (!guard(req, res, 'POST')) return
272
- const body = await readJsonBody<BibleRequest>(req)
273
- const config = getConfig()
274
- const project = loadProject(config.outputDir)
275
- const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
276
- ? body.outline
277
- : project?.outline
278
- if (outline === undefined || outline.length < 50) {
279
- writeJson(res, 400, { error: '请先加载大纲' })
280
- return
281
- }
282
- try {
283
- const bible = await extractBible(ctx, config, outline)
284
- const now = new Date().toISOString()
285
- const next = project ?? createProject(outline)
286
- next.bible = bible
287
- next.updatedAt = now
288
- saveProject(config.outputDir, next)
289
- const response: BibleResponse = { bible }
290
- writeJson(res, 200, response)
291
- } catch (error) {
292
- writeJson(res, 500, { error: (error as Error).message })
293
- }
294
- },
295
- }
296
-
297
- // ------------------------------------------------------------- volumes
298
- const volumesRoute: WebRoute = {
299
- kind: 'exact',
300
- path: NOVEL_API.volumes,
301
- handler: async (req, res) => {
302
- if (!guard(req, res, 'POST')) return
303
- const body = await readJsonBody<VolumesRequest>(req)
304
- const config = getConfig()
305
- const project = loadProject(config.outputDir)
306
- const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
307
- ? body.outline
308
- : project?.outline
309
- if (outline === undefined || outline.length < 50) {
310
- writeJson(res, 400, { error: '请先加载大纲' })
311
- return
312
- }
313
- try {
314
- const volumes = await planVolumes(ctx, config, outline)
315
- const now = new Date().toISOString()
316
- const next = project ?? createProject(outline)
317
- next.volumes = volumes
318
- next.updatedAt = now
319
- saveProject(config.outputDir, next)
320
- const response: VolumesResponse = { volumes }
321
- writeJson(res, 200, response)
322
- } catch (error) {
323
- writeJson(res, 500, { error: (error as Error).message })
324
- }
325
- },
326
- }
327
-
328
- // ----------------------------------------------------------------- plan
329
- const planRoute: WebRoute = {
330
- kind: 'exact',
331
- path: NOVEL_API.plan,
332
- handler: async (req, res) => {
333
- if (!guard(req, res, 'POST')) return
334
- const body = await readJsonBody<PlanRequest>(req)
335
- const config = getConfig()
336
- const project = loadProject(config.outputDir)
337
- const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
338
- ? body.outline
339
- : project?.outline
340
- if (outline === undefined || outline.length < 50) {
341
- writeJson(res, 400, { error: '请先加载大纲(或粘贴大纲文本)' })
342
- return
343
- }
344
- const count = body?.chapterCount ?? DEFAULT_PLAN_COUNT
345
- if (!Number.isInteger(count) || count < 1 || count > 200) {
346
- writeJson(res, 400, { error: 'chapterCount 须为 1-200 的整数' })
347
- return
348
- }
349
- try {
350
- const next = project ?? createProject(outline)
351
- const chapters: ChapterPlan[] = await planChapters(ctx, config, next, count, body?.volume)
352
- next.chapters.push(...chapters)
353
- next.updatedAt = new Date().toISOString()
354
- saveProject(config.outputDir, next)
355
- const response: PlanResponse = { chapters, volumes: next.volumes }
356
- writeJson(res, 200, response)
357
- } catch (error) {
358
- writeJson(res, 500, { error: (error as Error).message })
359
- }
360
- },
361
- }
362
-
363
- // ------------------------------------------------------------- generate
364
- const generateRoute: WebRoute = {
365
- kind: 'exact',
366
- path: NOVEL_API.generate,
367
- handler: async (req, res) => {
368
- if (!guard(req, res, 'POST')) return
369
- const config = getConfig()
370
- const project = requireProject(res)
371
- if (project === undefined) return
372
- const body = await readJsonBody<{ chapterNo?: number; skipReview?: boolean }>(req)
373
- const rawNo = body?.chapterNo
374
- if (!Number.isInteger(rawNo) || rawNo === undefined || rawNo < 1) {
375
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
376
- return
377
- }
378
- const no: number = rawNo
379
- const chapter = project.chapters.find(c => c.no === no)
380
- if (chapter === undefined) {
381
- writeJson(res, 404, { error: `章节 ${no} 不在计划中` })
382
- return
383
- }
384
- if (chapter.status === 'generating') {
385
- writeJson(res, 409, { error: `章节 ${no} 正在生成中` })
386
- return
387
- }
388
-
389
- // NDJSON stream.
390
- res.writeHead(200, {
391
- 'content-type': 'application/x-ndjson; charset=utf-8',
392
- 'cache-control': 'no-cache',
393
- 'x-accel-buffering': 'no',
394
- 'referrer-policy': 'no-referrer',
395
- })
396
- chapter.status = 'generating'
397
- chapter.error = undefined
398
- saveProject(config.outputDir, project)
399
-
400
- const send = (frame: JobFrame): void => {
401
- res.write(JSON.stringify(frame) + '\n')
402
- }
403
-
404
- try {
405
- send({ type: 'start', no, title: chapter.title })
406
- for await (const step of generateChapterStream(ctx, config, project, config.outputDir, no)) {
407
- if (step.frame === 'delta') {
408
- send({ type: 'delta', text: step.text })
409
- } else if (step.frame === 'done') {
410
- send({ type: 'done', no, file: step.file, chars: step.chars, title: chapter.title })
411
- }
412
- }
413
- // Auto pipeline: summary -> facts -> review (unless skipped).
414
- try {
415
- await summarizeChapter(ctx, config, project, config.outputDir, no)
416
- } catch (error) {
417
- console.warn('[dsh-novel-forge] summary failed:', (error as Error).message)
418
- }
419
- try {
420
- await extractFacts(ctx, config, project, config.outputDir, no)
421
- } catch (error) {
422
- console.warn('[dsh-novel-forge] facts extraction failed:', (error as Error).message)
423
- }
424
- if (!(body?.skipReview === true) && (config.autoReview ?? true)) {
425
- const report = await reviewChapter(ctx, config, project, config.outputDir, no)
426
- send({ type: 'review', no, report })
427
- } else {
428
- chapter.status = 'approved'
429
- saveProject(config.outputDir, project)
430
- }
431
- res.end()
432
- } catch (error) {
433
- chapter.status = 'error'
434
- chapter.error = (error as Error).message
435
- saveProject(config.outputDir, project)
436
- if (!res.writableEnded) {
437
- send({ type: 'error', no, message: (error as Error).message })
438
- res.end()
439
- }
440
- }
441
- },
442
- }
443
-
444
- // --------------------------------------------------------------- review
445
- const reviewRoute: WebRoute = {
446
- kind: 'exact',
447
- path: NOVEL_API.review,
448
- handler: async (req, res) => {
449
- if (!guard(req, res, 'POST')) return
450
- const config = getConfig()
451
- const project = requireProject(res)
452
- if (project === undefined) return
453
- const body = await readJsonBody<ReviewRequest>(req)
454
- if (!Number.isInteger(body?.chapterNo)) {
455
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
456
- return
457
- }
458
- const no = body!.chapterNo!
459
- try {
460
- const report = await reviewChapter(ctx, config, project, config.outputDir, no)
461
- writeJson(res, 200, { report })
462
- } catch (error) {
463
- writeJson(res, 500, { error: (error as Error).message })
464
- }
465
- },
466
- }
467
-
468
- // -------------------------------------------------------------- rewrite
469
- const rewriteRoute: WebRoute = {
470
- kind: 'exact',
471
- path: NOVEL_API.rewrite,
472
- handler: async (req, res) => {
473
- if (!guard(req, res, 'POST')) return
474
- const config = getConfig()
475
- const project = requireProject(res)
476
- if (project === undefined) return
477
- const body = await readJsonBody<RewriteRequest>(req)
478
- if (!Number.isInteger(body?.chapterNo)) {
479
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
480
- return
481
- }
482
- const no = body!.chapterNo!
483
- res.writeHead(200, {
484
- 'content-type': 'application/x-ndjson; charset=utf-8',
485
- 'cache-control': 'no-cache',
486
- 'x-accel-buffering': 'no',
487
- 'referrer-policy': 'no-referrer',
488
- })
489
- const send = (frame: JobFrame): void => { res.write(JSON.stringify(frame) + '\n') }
490
- try {
491
- for await (const step of rewriteChapterStream(ctx, config, project, config.outputDir, no, body?.instructions ?? '', body?.target)) {
492
- if (step.frame === 'delta') send({ type: 'delta', text: step.text })
493
- else if (step.frame === 'drafted') send({ type: 'drafted', no, chars: step.chars, draft: step.draft })
494
- }
495
- // Draft mode: no auto re-review — the user reviews the diff and
496
- // decides; re-run review after applying if wanted.
497
- res.end()
498
- } catch (error) {
499
- if (!res.writableEnded) {
500
- send({ type: 'error', no, message: (error as Error).message })
501
- res.end()
502
- }
503
- }
504
- },
505
- }
506
-
507
- // --------------------------------------------------------------- polish
508
- const polishRoute: WebRoute = {
509
- kind: 'exact',
510
- path: NOVEL_API.polish,
511
- handler: async (req, res) => {
512
- if (!guard(req, res, 'POST')) return
513
- const config = getConfig()
514
- const project = requireProject(res)
515
- if (project === undefined) return
516
- const body = await readJsonBody<PolishRequest>(req)
517
- if (!Number.isInteger(body?.chapterNo)) {
518
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
519
- return
520
- }
521
- const no = body!.chapterNo!
522
- res.writeHead(200, {
523
- 'content-type': 'application/x-ndjson; charset=utf-8',
524
- 'cache-control': 'no-cache',
525
- 'x-accel-buffering': 'no',
526
- 'referrer-policy': 'no-referrer',
527
- })
528
- const send = (frame: JobFrame): void => { res.write(JSON.stringify(frame) + '\n') }
529
- try {
530
- for await (const step of polishChapterStream(ctx, config, project, config.outputDir, no)) {
531
- if (step.frame === 'delta') send({ type: 'delta', text: step.text })
532
- else if (step.frame === 'drafted') send({ type: 'drafted', no, chars: step.chars, draft: step.draft })
533
- }
534
- res.end()
535
- } catch (error) {
536
- if (!res.writableEnded) {
537
- send({ type: 'error', no, message: (error as Error).message })
538
- res.end()
539
- }
540
- }
541
- },
542
- }
543
-
544
- // ---------------------------------------------------- draft apply/discard
545
- /** 采纳待确认草稿:覆盖正文文件 + 状态回 written + 清空草稿。 */
546
- const draftApplyRoute: WebRoute = {
547
- kind: 'exact',
548
- path: NOVEL_API.draftApply,
549
- handler: async (req, res) => {
550
- if (!guard(req, res, 'POST')) return
551
- const config = getConfig()
552
- const project = requireProject(res)
553
- if (project === undefined) return
554
- const body = await readJsonBody<DraftDecisionRequest>(req)
555
- if (!Number.isInteger(body?.chapterNo)) {
556
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
557
- return
558
- }
559
- const chapter = project.chapters.find(c => c.no === body!.chapterNo!)
560
- if (chapter === undefined) {
561
- writeJson(res, 404, { error: `章节 ${body!.chapterNo} 不在计划中` })
562
- return
563
- }
564
- if (chapter.pendingDraft === undefined || chapter.pendingDraft === '') {
565
- writeJson(res, 400, { error: `章节 ${chapter.no} 没有待确认的草稿` })
566
- return
567
- }
568
- const draft = chapter.pendingDraft
569
- const fileName = chapterFileName(chapter)
570
- mkdirSync(config.outputDir, { recursive: true })
571
- const targetPath = join(config.outputDir, fileName)
572
- // 采纳前自动备份当前原稿为 .bak.md(每次应用都刷新为最新原稿),可随时回退。
573
- if (existsSync(targetPath)) {
574
- copyFileSync(targetPath, join(config.outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
575
- }
576
- writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${draft}\n`, 'utf8')
577
- chapter.pendingDraft = undefined
578
- chapter.status = 'written'
579
- chapter.chars = draft.length
580
- chapter.file = fileName
581
- chapter.review = undefined
582
- chapter.error = undefined
583
- project.updatedAt = new Date().toISOString()
584
- saveProject(config.outputDir, project)
585
- writeJson(res, 200, { ok: true, chars: draft.length, file: fileName })
586
- },
587
- }
588
-
589
- /** 放弃待确认草稿:保留原稿,仅清空草稿字段。 */
590
- const draftDiscardRoute: WebRoute = {
591
- kind: 'exact',
592
- path: NOVEL_API.draftDiscard,
593
- handler: async (req, res) => {
594
- if (!guard(req, res, 'POST')) return
595
- const config = getConfig()
596
- const project = requireProject(res)
597
- if (project === undefined) return
598
- const body = await readJsonBody<DraftDecisionRequest>(req)
599
- if (!Number.isInteger(body?.chapterNo)) {
600
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
601
- return
602
- }
603
- const chapter = project.chapters.find(c => c.no === body!.chapterNo!)
604
- if (chapter === undefined) {
605
- writeJson(res, 404, { error: `章节 ${body!.chapterNo} 不在计划中` })
606
- return
607
- }
608
- if (chapter.pendingDraft !== undefined) {
609
- chapter.pendingDraft = undefined
610
- project.updatedAt = new Date().toISOString()
611
- saveProject(config.outputDir, project)
612
- }
613
- writeJson(res, 200, { ok: true })
614
- },
615
- }
616
-
617
- // -------------------------------------------------------------- summary
618
- const summaryRoute: WebRoute = {
619
- kind: 'exact',
620
- path: NOVEL_API.summary,
621
- handler: async (req, res) => {
622
- if (!guard(req, res, 'POST')) return
623
- const config = getConfig()
624
- const project = requireProject(res)
625
- if (project === undefined) return
626
- const body = await readJsonBody<SummaryRequest>(req)
627
- if (!Number.isInteger(body?.chapterNo)) {
628
- writeJson(res, 400, { error: 'chapterNo 须为正整数' })
629
- return
630
- }
631
- try {
632
- const summary = await summarizeChapter(ctx, config, project, config.outputDir, body!.chapterNo!)
633
- writeJson(res, 200, { summary })
634
- } catch (error) {
635
- writeJson(res, 500, { error: (error as Error).message })
636
- }
637
- },
638
- }
639
-
640
- // ---------------------------------------------------------- foreshadow
641
- const foreshadowRoute: WebRoute = {
642
- kind: 'exact',
643
- path: NOVEL_API.foreshadow,
644
- handler: async (req, res) => {
645
- if (!guard(req, res, 'POST')) return
646
- const config = getConfig()
647
- const project = requireProject(res)
648
- if (project === undefined) return
649
- const body = await readJsonBody<ForeshadowRequest>(req)
650
- try {
651
- if (body?.suggest === true) {
652
- // AI suggestion pass: create several foreshadows from the outline.
653
- const created = await suggestForeshadows(ctx, config, project)
654
- project.updatedAt = new Date().toISOString()
655
- saveProject(config.outputDir, project)
656
- const response: ForeshadowResponse = { foreshadows: created }
657
- writeJson(res, 200, response)
658
- return
659
- }
660
- if (body?.id !== undefined) {
661
- // Update an existing foreshadow.
662
- const target = project.foreshadows.find(f => f.id === body.id)
663
- if (target === undefined) {
664
- writeJson(res, 404, { error: `伏笔 ${body.id} 不存在` })
665
- return
666
- }
667
- if (body.description !== undefined) target.description = body.description
668
- if (body.plantedChapter !== undefined) target.plantedChapter = body.plantedChapter
669
- if (body.targetChapter !== undefined) target.targetChapter = body.targetChapter
670
- if (body.status !== undefined) target.status = body.status
671
- if (body.resolvedNote !== undefined) target.resolvedNote = body.resolvedNote
672
- } else {
673
- // Create one manually.
674
- const description = body?.description?.trim()
675
- if (description === undefined || description === '') {
676
- writeJson(res, 400, { error: 'description 必填' })
677
- return
678
- }
679
- project.foreshadows.push({
680
- id: `fs-${Date.now().toString(36)}`,
681
- description,
682
- plantedChapter: body?.plantedChapter,
683
- targetChapter: body?.targetChapter,
684
- status: body?.status ?? 'planned',
685
- })
686
- }
687
- project.updatedAt = new Date().toISOString()
688
- saveProject(config.outputDir, project)
689
- const response: ForeshadowResponse = { foreshadows: project.foreshadows }
690
- writeJson(res, 200, response)
691
- } catch (error) {
692
- writeJson(res, 500, { error: (error as Error).message })
693
- }
694
- },
695
- }
696
-
697
- // -------------------------------------------------------------- export
698
- const exportRoute: WebRoute = {
699
- kind: 'exact',
700
- path: NOVEL_API.exportBook,
701
- handler: async (req, res) => {
702
- if (!guard(req, res, 'POST')) return
703
- const config = getConfig()
704
- const project = requireProject(res)
705
- if (project === undefined) return
706
- const body = await readJsonBody<ExportRequest>(req)
707
- const format = body?.format === 'md' ? 'md' : 'txt'
708
- try {
709
- const result = exportBook(config.outputDir, project, format)
710
- const response: ExportResponse = { ...result }
711
- writeJson(res, 200, response)
712
- } catch (error) {
713
- writeJson(res, 500, { error: (error as Error).message })
714
- }
715
- },
716
- }
717
-
718
- // -------------------------------------------------------------- chapter
719
- const chapterRoute: WebRoute = {
720
- kind: 'exact',
721
- path: NOVEL_API.chapter,
722
- handler: async (req, res) => {
723
- if (!guard(req, res, 'GET')) return
724
- const config = getConfig()
725
- const project = requireProject(res)
726
- if (project === undefined) return
727
- const url = new URL(req.url ?? '/', 'http://localhost')
728
- const rawNo = Number(url.searchParams.get('no') ?? '0')
729
- if (!Number.isInteger(rawNo) || rawNo < 1) {
730
- writeJson(res, 400, { error: 'no 须为正整数' })
731
- return
732
- }
733
- const chapter = project.chapters.find(c => c.no === rawNo)
734
- if (chapter === undefined) {
735
- writeJson(res, 404, { error: `章节 ${rawNo} 不在计划中` })
736
- return
737
- }
738
- const markdown = readChapterFile(config.outputDir, chapter)
739
- if (markdown === undefined) {
740
- writeJson(res, 404, { error: `章节 ${rawNo} 尚未生成` })
741
- return
742
- }
743
- const response: ChapterResponse = { no: chapter.no, title: chapter.title, markdown }
744
- writeJson(res, 200, response)
745
- },
746
- }
747
-
748
- // ----------------------------------------------------------- assistant
749
- const assistantRoute: WebRoute = {
750
- kind: 'exact',
751
- path: NOVEL_API.assistant,
752
- handler: async (req, res) => {
753
- if (!guard(req, res, 'POST')) return
754
- const config = getConfig()
755
- const project = requireProject(res)
756
- if (project === undefined) return
757
- const body = await readJsonBody<AssistantRequest>(req)
758
- const message = body?.message?.trim()
759
- if (message === undefined || message === '') {
760
- writeJson(res, 400, { error: '消息不能为空' })
761
- return
762
- }
763
- res.writeHead(200, {
764
- 'content-type': 'application/x-ndjson; charset=utf-8',
765
- 'cache-control': 'no-cache',
766
- 'x-accel-buffering': 'no',
767
- 'referrer-policy': 'no-referrer',
768
- })
769
- const send = (frame: AssistantFrame): void => { res.write(JSON.stringify(frame) + '\n') }
770
- try {
771
- for await (const step of runAssistantTurn(ctx, config, project, config.outputDir, message)) {
772
- if (step.frame === 'delta') send({ type: 'delta', text: step.text })
773
- else if (step.frame === 'tool') send({ type: 'tool', name: step.name, status: step.status, detail: step.detail })
774
- else if (step.frame === 'toolDelta') send({ type: 'toolDelta', name: step.name, text: step.text })
775
- }
776
- send({ type: 'done' })
777
- res.end()
778
- } catch (error) {
779
- if (!res.writableEnded) {
780
- send({ type: 'error', message: (error as Error).message })
781
- res.end()
782
- }
783
- }
784
- },
785
- }
786
-
787
- // -------------------------------------------------- assistant-history
788
- const assistantHistoryRoute: WebRoute = {
789
- kind: 'exact',
790
- path: NOVEL_API.assistantHistory,
791
- handler: (req, res) => {
792
- if (!guard(req, res, 'GET')) return
793
- const config = getConfig()
794
- const response: AssistantHistoryResponse = { messages: loadAssistantHistory(config.outputDir) }
795
- writeJson(res, 200, response)
796
- },
797
- }
798
-
799
- // --------------------------------------------------------------- assets
800
- const assetsRoute: WebRoute = {
801
- kind: 'exact',
802
- path: NOVEL_API.assets,
803
- handler: async (req, res) => {
804
- // GET (read) and POST (patch) are both allowed — check methods first,
805
- // then the loopback fence (guard() would 405 on POST, which is wrong).
806
- if (req.method !== 'GET' && req.method !== 'POST') {
807
- writeJson(res, 405, { error: 'method not allowed (expected GET or POST)' })
808
- return
809
- }
810
- if (!isLoopbackRequest(req)) {
811
- writeJson(res, 403, { error: 'forbidden: loopback-only' })
812
- return
813
- }
814
- const config = getConfig()
815
- const project = loadProject(config.outputDir)
816
- const projectAssets = project?.assets ?? emptyProjectAssets()
817
- if (req.method === 'POST') {
818
- const body = await readJsonBody<AssetsPatch>(req)
819
- if (body === undefined) {
820
- writeJson(res, 400, { error: '无效的 JSON' })
821
- return
822
- }
823
- if (project === undefined) {
824
- writeJson(res, 400, { error: '请先加载大纲创建项目' })
825
- return
826
- }
827
- if (body.genre !== undefined) projectAssets.genre = body.genre
828
- if (body.primaryProgression !== undefined) projectAssets.primaryProgression = body.primaryProgression
829
- if (body.auxiliaryProgressions !== undefined) projectAssets.auxiliaryProgressions = body.auxiliaryProgressions
830
- if (body.antiAiRules !== undefined) projectAssets.antiAiRules = body.antiAiRules
831
- if (body.styleAssets !== undefined) projectAssets.styleAssets = body.styleAssets
832
- projectAssets.updatedAt = new Date().toISOString()
833
- project.assets = projectAssets
834
- project.updatedAt = new Date().toISOString()
835
- saveProject(config.outputDir, project)
836
- }
837
- const response: AssetsResponse = {
838
- projectAssets,
839
- genreLibrary: BUILTIN_GENRE_LIBRARY,
840
- antiAiLibrary: BUILTIN_ANTI_AI_RULES,
841
- styleTemplates: BUILTIN_STYLE_TEMPLATES,
842
- progressionLibrary: BUILTIN_PROGRESSION_MODES,
843
- }
844
- writeJson(res, 200, response)
845
- },
846
- }
847
-
848
- // ----------------------------------------------------------- style-engine
849
- const styleEngineRoute: WebRoute = {
850
- kind: 'exact',
851
- path: NOVEL_API.styleEngine,
852
- handler: async (req, res) => {
853
- if (!guard(req, res, 'POST')) return
854
- const config = getConfig()
855
- const project = loadProject(config.outputDir)
856
- const body = await readJsonBody<StyleEngineRequest>(req)
857
- const sample = body?.sampleText?.trim()
858
- if (sample === undefined || sample.length < 50) {
859
- writeJson(res, 400, { error: '样本文本过短(<50 字符),请粘贴一段能代表目标风格的文字' })
860
- return
861
- }
862
- try {
863
- const rules = await extractStyleAsset(ctx, config, sample)
864
- const name = body?.name?.trim() !== '' && body?.name !== undefined ? body.name : `风格资产 ${Date.now().toString(36)}`
865
- const styleAsset = {
866
- name: name.slice(0, 40),
867
- ...rules,
868
- sourceText: sample.slice(0, 3000),
869
- createdAt: new Date().toISOString(),
870
- }
871
- if (project !== undefined) {
872
- project.assets ??= emptyProjectAssets()
873
- project.assets.styleAssets ??= []
874
- project.assets.styleAssets.push(styleAsset)
875
- project.assets.updatedAt = new Date().toISOString()
876
- project.updatedAt = new Date().toISOString()
877
- saveProject(config.outputDir, project)
878
- }
879
- writeJson(res, 200, { styleAsset })
880
- } catch (error) {
881
- writeJson(res, 500, { error: (error as Error).message })
882
- }
883
- },
884
- }
885
-
886
- // ------------------------------------------------------------- bookshelf
887
- const bookshelfRoute: WebRoute = {
888
- kind: 'exact',
889
- path: NOVEL_API.bookshelf,
890
- handler: async (req, res) => {
891
- // GET = snapshot; POST = create book.
892
- if (req.method === 'GET') {
893
- if (!isLoopbackRequest(req)) {
894
- writeJson(res, 403, { error: 'forbidden: loopback-only' })
895
- return
896
- }
897
- // 书架为空时,把 settings 默认输出目录里已有的项目播种为第一本书。
898
- seedBookshelfFromOutputDir(getConfig().outputDir)
899
- const snapshot: BookshelfSnapshot = bookshelfSnapshot(loadBookshelf())
900
- writeJson(res, 200, snapshot)
901
- return
902
- }
903
- if (req.method === 'POST') {
904
- if (!isLoopbackRequest(req)) {
905
- writeJson(res, 403, { error: 'forbidden: loopback-only' })
906
- return
907
- }
908
- const body = await readJsonBody<BookCreateRequest>(req)
909
- const bookName = body?.bookName?.trim()
910
- if (bookName === undefined || bookName === '') {
911
- writeJson(res, 400, { error: 'bookName 不能为空' })
912
- return
913
- }
914
- const outputDir = body?.outputDir?.trim() !== '' && body?.outputDir !== undefined
915
- ? body.outputDir
916
- : defaultOutputDirFor(bookName)
917
- const book = createBook(bookName, outputDir)
918
- // 开书向导:创建时带大纲 → 立即建立项目(书名以大纲首行为准)。
919
- const outline = body?.outline?.trim()
920
- if (outline !== undefined && outline.length >= 50) {
921
- const project = createProject(outline)
922
- saveProject(outputDir, project)
923
- renameBook(book.id, project.bookName)
924
- }
925
- writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
926
- return
927
- }
928
- writeJson(res, 405, { error: 'method not allowed (expected GET or POST)' })
929
- },
930
- }
931
-
932
- // --------------------------------------------------------------- reset
933
- /** 重置项目:清空设定/卷/章节计划/正文/伏笔/资产/事实库(可携带新大纲)。 */
934
- const resetRoute: WebRoute = {
935
- kind: 'exact',
936
- path: NOVEL_API.reset,
937
- handler: async (req, res) => {
938
- if (!guard(req, res, 'POST')) return
939
- const config = getConfig()
940
- const project = loadProject(config.outputDir)
941
- if (project === undefined) {
942
- writeJson(res, 400, { error: '输出目录中没有项目,无需重置' })
943
- return
944
- }
945
- const body = await readJsonBody<ResetRequest>(req)
946
- const outline = body?.outline?.trim()
947
- if (outline !== undefined && outline.length >= 50) {
948
- project.outline = outline
949
- project.bookName = createProject(outline).bookName
950
- }
951
- project.bible = undefined
952
- project.volumes = undefined
953
- project.chapters = []
954
- project.foreshadows = []
955
- project.assets = emptyProjectAssets()
956
- project.facts = []
957
- project.updatedAt = new Date().toISOString()
958
- saveProject(config.outputDir, project)
959
- writeJson(res, 200, { ok: true, bookName: project.bookName })
960
- },
961
- }
962
-
963
- // --------------------------------------------------- bookshelf activate
964
- const bookshelfActivateRoute: WebRoute = {
965
- kind: 'exact',
966
- path: '/api/dsh-novel-forge/bookshelf/activate',
967
- handler: async (req, res) => {
968
- if (!guard(req, res, 'POST')) return
969
- const body = await readJsonBody<BookActivateRequest>(req)
970
- if (body?.id === undefined || body.id === '') {
971
- writeJson(res, 400, { error: 'id 不能为空' })
972
- return
973
- }
974
- const book = activateBook(body.id)
975
- if (book === undefined) {
976
- writeJson(res, 404, { error: `书 ${body.id} 不存在` })
977
- return
978
- }
979
- writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
980
- },
981
- }
982
-
983
- // ---------------------------------------------------- bookshelf remove
984
- const bookshelfRemoveRoute: WebRoute = {
985
- kind: 'exact',
986
- path: '/api/dsh-novel-forge/bookshelf/remove',
987
- handler: async (req, res) => {
988
- if (!guard(req, res, 'POST')) return
989
- const body = await readJsonBody<BookRemoveRequest>(req)
990
- if (body?.id === undefined || body.id === '') {
991
- writeJson(res, 400, { error: 'id 不能为空' })
992
- return
993
- }
994
- const removed = removeBook(body.id)
995
- if (!removed) {
996
- writeJson(res, 404, { error: `书 ${body.id} 不存在` })
997
- return
998
- }
999
- writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
1000
- },
1001
- }
1002
-
1003
- // ---------------------------------------------------------------- audit
1004
- /** 全书一致性质检。 */
1005
- const auditRoute: WebRoute = {
1006
- kind: 'exact',
1007
- path: NOVEL_API.audit,
1008
- handler: async (req, res) => {
1009
- if (!guard(req, res, 'POST')) return
1010
- const config = getConfig()
1011
- const project = requireProject(res)
1012
- if (project === undefined) return
1013
- try {
1014
- const issues = await auditBook(ctx, config, project, config.outputDir)
1015
- const response: AuditResponse = {
1016
- issues,
1017
- auditedChapters: project.chapters.filter(c => c.status !== 'pending' && c.status !== 'generating').length,
1018
- auditedAt: new Date().toISOString(),
1019
- }
1020
- writeJson(res, 200, response)
1021
- } catch (error) {
1022
- writeJson(res, 500, { error: (error as Error).message })
1023
- }
1024
- },
1025
- }
1026
-
1027
- // ----------------------------------------------------- characters refresh
1028
- /** 角色卡刷新(出场统计精确化 + LLM 聚合状态)。 */
1029
- const charactersRefreshRoute: WebRoute = {
1030
- kind: 'exact',
1031
- path: NOVEL_API.charactersRefresh,
1032
- handler: async (req, res) => {
1033
- if (!guard(req, res, 'POST')) return
1034
- const config = getConfig()
1035
- const project = requireProject(res)
1036
- if (project === undefined) return
1037
- try {
1038
- const cards = await refreshCharacters(ctx, config, project, config.outputDir)
1039
- writeJson(res, 200, { cards })
1040
- } catch (error) {
1041
- writeJson(res, 500, { error: (error as Error).message })
1042
- }
1043
- },
1044
- }
1045
-
1046
- // ------------------------------------------------------- facts backfill
1047
- /** 事实库回填:对历史已生成章节批量抽取事实。 */
1048
- const factsBackfillRoute: WebRoute = {
1049
- kind: 'exact',
1050
- path: NOVEL_API.factsBackfill,
1051
- handler: async (req, res) => {
1052
- if (!guard(req, res, 'POST')) return
1053
- const config = getConfig()
1054
- const project = requireProject(res)
1055
- if (project === undefined) return
1056
- try {
1057
- const filled = await backfillFacts(ctx, config, project, config.outputDir)
1058
- writeJson(res, 200, { ok: true, filled })
1059
- } catch (error) {
1060
- writeJson(res, 500, { error: (error as Error).message })
1061
- }
1062
- },
1063
- }
1064
-
1065
- // ---------------------------------------------------------- bible patch
1066
- /** 设定圣经局部修补(世界观规则/红线/风格)。 */
1067
- const biblePatchRoute: WebRoute = {
1068
- kind: 'exact',
1069
- path: NOVEL_API.biblePatch,
1070
- handler: async (req, res) => {
1071
- if (!guard(req, res, 'POST')) return
1072
- const config = getConfig()
1073
- const project = requireProject(res)
1074
- if (project === undefined) return
1075
- if (project.bible === undefined) {
1076
- writeJson(res, 400, { error: '尚未生成设定圣经,请先生成' })
1077
- return
1078
- }
1079
- const body = await readJsonBody<BiblePatchRequest>(req)
1080
- if (Array.isArray(body?.worldRules)) project.bible.worldRules = body.worldRules.filter(r => r.trim() !== '')
1081
- if (Array.isArray(body?.redLines)) project.bible.redLines = body.redLines.filter(r => r.trim() !== '')
1082
- if (Array.isArray(body?.style)) project.bible.style = body.style.filter(r => r.trim() !== '')
1083
- project.updatedAt = new Date().toISOString()
1084
- saveProject(config.outputDir, project)
1085
- writeJson(res, 200, { bible: project.bible })
1086
- },
1087
- }
1088
-
1089
- // --------------------------------------------------------------- config
1090
- const configRoute: WebRoute = {
1091
- kind: 'exact',
1092
- path: NOVEL_API.config,
1093
- handler: async (req, res) => {
1094
- if (!guard(req, res, 'POST')) return
1095
- const body = await readJsonBody<ConfigPatch>(req)
1096
- if (body === undefined) {
1097
- writeJson(res, 400, { error: '无效的配置 JSON' })
1098
- return
1099
- }
1100
- try {
1101
- const next = await patchConfig(body)
1102
- writeJson(res, 200, { config: next })
1103
- } catch (error) {
1104
- writeJson(res, 400, { error: (error as Error).message })
1105
- }
1106
- },
1107
- }
1108
-
1109
- // ---------------------------------------------------------- open-folder
1110
- const openFolderRoute: WebRoute = {
1111
- kind: 'exact',
1112
- path: NOVEL_API.openFolder,
1113
- handler: async (req, res) => {
1114
- if (!guard(req, res, 'POST')) return
1115
- const config = getConfig()
1116
- const dir = config.outputDir
1117
- exec(`explorer "${dir.replace(/"/g, '')}"`, (error) => {
1118
- if (error) {
1119
- writeJson(res, 500, { ok: false, error: error.message })
1120
- } else {
1121
- writeJson(res, 200, { ok: true })
1122
- }
1123
- })
1124
- },
1125
- }
1126
-
1127
- return [
1128
- statusRoute,
1129
- loadOutlineRoute,
1130
- saveOutlineRoute,
1131
- bibleRoute,
1132
- volumesRoute,
1133
- planRoute,
1134
- generateRoute,
1135
- reviewRoute,
1136
- rewriteRoute,
1137
- polishRoute,
1138
- draftApplyRoute,
1139
- draftDiscardRoute,
1140
- summaryRoute,
1141
- foreshadowRoute,
1142
- exportRoute,
1143
- chapterRoute,
1144
- assetsRoute,
1145
- styleEngineRoute,
1146
- assistantRoute,
1147
- assistantHistoryRoute,
1148
- bookshelfRoute,
1149
- bookshelfActivateRoute,
1150
- bookshelfRemoveRoute,
1151
- resetRoute,
1152
- auditRoute,
1153
- charactersRefreshRoute,
1154
- factsBackfillRoute,
1155
- biblePatchRoute,
1156
- configRoute,
1157
- openFolderRoute,
1158
- ]
1159
- }
1160
-
1161
- // Re-export for tests / type consumers.
1162
- export type {
1163
- ConfigPatch,
1164
- NovelConfig,
1165
- StatusResponse,
1166
- PlanResponse,
1167
- LoadOutlineResponse,
1168
- BibleResponse,
1169
- VolumesResponse,
1170
- ExportResponse,
1171
- }
1172
- export { chapterFileName }
1
+ /**
2
+ * The /api/dsh-novel-forge route family: status, docx outline loading, LLM
3
+ * story-bible extraction, volume planning, chapter planning, streaming
4
+ * generation / rewrite / polish (NDJSON frames), review, summaries,
5
+ * foreshadows, export, chapter reading, config patching, and opening the
6
+ * output folder. Every route carries the same loopback-only trust fence as
7
+ * the family plugins — these endpoints invoke the LLM and write files on the
8
+ * host machine.
9
+ */
10
+
11
+ import type { IncomingMessage, ServerResponse } from 'node:http'
12
+ import { spawn } from 'node:child_process'
13
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
14
+ import { join, basename, extname } from 'node:path'
15
+ import { homedir } from 'node:os'
16
+ import { randomBytes } from 'node:crypto'
17
+ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import { ProductionRunner } from './run.ts'
20
+ import {
21
+ NOVEL_API,
22
+ type AssetsPatch,
23
+ type AssetsResponse,
24
+ type AddModelRequest,
25
+ type AddModelResponse,
26
+ type LlmModelsResponse,
27
+ type LlmProvidersResponse,
28
+ type LlmVendorsResponse,
29
+ type RemoveProviderRequest,
30
+ type RemoveProviderResponse,
31
+ type AssistantFrame,
32
+ type AssistantHistoryResponse,
33
+ type AssistantRequest,
34
+ type AuditResponse,
35
+ type AuditStatus,
36
+ type AuthorReview,
37
+ type BiblePatchRequest,
38
+ type BibleRequest,
39
+ type BlurbRequest,
40
+ type CoverRequest,
41
+ type CoverResponse,
42
+ type RenameRequest,
43
+ type WorldRequest,
44
+ type BibleResponse,
45
+ type BookActivateRequest,
46
+ type BookCreateRequest,
47
+ type BookImportDirRequest,
48
+ type BookImportTextRequest,
49
+ type BookImportTextPreviewRequest,
50
+ type BookRemoveRequest,
51
+ type BookshelfSnapshot,
52
+ type ChapterResponse,
53
+ type ChapterPlan,
54
+ type ChapterSaveResponse,
55
+ type ChapterTextRequest,
56
+ type ConfigPatch,
57
+ type MoveOutputDirRequest,
58
+ type MoveOutputDirResponse,
59
+ type BookSettings,
60
+ type BookSettingsRequest,
61
+ type BookSettingsResponse,
62
+ type DraftDecisionRequest,
63
+ type ExportRequest,
64
+ type ExportResponse,
65
+ type ForeshadowRequest,
66
+ type ForeshadowResponse,
67
+ type JobFrame,
68
+ type LoadOutlineRequest,
69
+ type LoadOutlineResponse,
70
+ type NovelConfig,
71
+ type PlotlinesRequest,
72
+ type PlotlinesResponse,
73
+ type PlanRequest,
74
+ type PlanResponse,
75
+ type PolishRequest,
76
+ type ResetRequest,
77
+ type ReviewReport,
78
+ type ReviewRequest,
79
+ type RunControlRequest,
80
+ type RunStartRequest,
81
+ type RunState,
82
+ type RewriteRequest,
83
+ type RolesRequest,
84
+ type RolesResponse,
85
+ type OutlineSuggestRequest,
86
+ type OutlineSuggestResponse,
87
+ type BreakdownRequest,
88
+ type BreakdownResponse,
89
+ type SensitiveCheckRequest,
90
+ type SensitiveCheckResponse,
91
+ type SensitiveHit,
92
+ type ProjectState,
93
+ type StatusResponse,
94
+ type StoryBible,
95
+ type LlmTestRequest,
96
+ type LlmTestResponse,
97
+ type StyleEngineRequest,
98
+ type SummaryRequest,
99
+ type VolumesRequest,
100
+ type VolumesResponse,
101
+ type AuthorAssetsResponse,
102
+ type AuthorAssetUpsertRequest,
103
+ type AuthorAssetRemoveRequest,
104
+ type AdaptAnalyzeRequest,
105
+ type AdaptAnalyzeResponse,
106
+ type AdaptProposeRequest,
107
+ type AdaptProposeResponse,
108
+ type AdaptExecuteRequest,
109
+ type AdaptExecuteResponse,
110
+ type AdaptSaveRequest,
111
+ type AdaptSaveResponse,
112
+ type AdaptMaterializeRequest,
113
+ type AdaptMaterializeResponse,
114
+ type AdaptMaterializeSaveRequest,
115
+ type AdaptMaterializeSaveResponse,
116
+ type AdaptRewriteFrame,
117
+ type PluginUpdateResponse,
118
+ type MarketRadarRequest,
119
+ type MarketRadarBriefRequest,
120
+ type ProductionFoundation,
121
+ type ProgressionMode,
122
+ type GenreNode,
123
+ type KnowledgeRequest,
124
+ type BookAnalysisRequest,
125
+ type IdeaInspirationRequest,
126
+ type DirectorRequest,
127
+ type DirectorTodo,
128
+ } from './protocol.ts'
129
+ import { readOutlineFromDocx } from './docx.ts'
130
+ import { clearAssistantHistory, loadAssistantHistory, runAssistantTurn } from './assistant.ts'
131
+ import { activateBook, bookshelfSnapshot, createBook, defaultOutputDirFor, importDir, loadBookshelf, removeBook, renameBook, repointBookDirs, seedBookshelfFromOutputDir } from './bookshelf.ts'
132
+ import { copyDirContents, listDirContents, normalizeDir, removeDir } from './migrate-output.ts'
133
+ import { loadAuthorAssets, upsertAuthorAsset, removeAuthorAsset, importDefaultAuthorAssets } from './author-assets.ts'
134
+ import { BUILTIN_ANTI_AI_RULES, BUILTIN_GENRE_LIBRARY, BUILTIN_PLOT_BEATS, BUILTIN_PROGRESSION_MODES, BUILTIN_STARTER_STYLE_PROFILES, BUILTIN_STYLE_TEMPLATES, emptyProjectAssets, ensureBuiltinAssets } from './assets.ts'
135
+ import { scanAiFlavor } from './ai-scan.ts'
136
+ import { emitLive, nextSessionId, subscribeLiveFeed } from './llm-live.ts'
137
+ import { scanMarketRanking } from './market-radar-scan.ts'
138
+ import { addGlobalGenre, addGlobalMode, globalGenreLibrary, globalProgressionLibrary } from './global-assets.ts'
139
+ import {
140
+ chapterFileName,
141
+ auditBook,
142
+ authorReviewChapter,
143
+ autoLinkPlotlines,
144
+ backfillFacts,
145
+ createProject,
146
+ exportBook,
147
+ importBookText,
148
+ importBookTextFromText,
149
+ previewBookText,
150
+ extractBible,
151
+ extractStyleAsset,
152
+ extractStyleFormula,
153
+ runMarketRadar,
154
+ runMarketCreativeBrief,
155
+ runBookAnalysis,
156
+ runIdeaInspiration,
157
+ runMarketIdeaInspiration,
158
+ runDirectorAdvice,
159
+ extractWorld,
160
+ generateBlurb,
161
+ generateChapterStream,
162
+ listChapterFiles,
163
+ loadProject,
164
+ markForeshadowPlanted,
165
+ mergeVolatileFromDisk,
166
+ planChapters,
167
+ planVolumes,
168
+ polishChapterStream,
169
+ readChapterFile,
170
+ refreshCharacters,
171
+ refreshPlotlineProgress,
172
+ reviewChapter,
173
+ reviewChapterText,
174
+ rewriteChapterStream,
175
+ saveProject,
176
+ analyzePlotlineHealth,
177
+ designPlotlinePlan,
178
+ extractRoles,
179
+ suggestOutlines,
180
+ reverseOutlineFromChapters,
181
+ breakdownBook,
182
+ analyzeAdaptation,
183
+ proposeAdaptation,
184
+ applyAdaptationReplacements,
185
+ rewriteAdaptationBook,
186
+ materializeAdaptedBook,
187
+ saveMaterializedBook,
188
+ testLlmModel,
189
+ registerLlmModel,
190
+ listLlmVendors,
191
+ listLlmModels,
192
+ listLlmProviders,
193
+ removeLlmProvider,
194
+ checkSensitiveText,
195
+ suggestForeshadows,
196
+ suggestPlotlines,
197
+ summarizeAndExtractFacts,
198
+ summarizeChapter,
199
+ syncProjectWithDisk,
200
+ } from './engine.ts'
201
+
202
+ /** Cap on JSON request bodies (generous: cover images travel as base64). */
203
+ const MAX_JSON_BODY_BYTES = 64 * 1024 * 1024
204
+
205
+ /** 包内置风格效果图目录(assets/styles,随 npm 包分发)。 */
206
+
207
+ /** 解析请求级目标书目录:优先按请求携带的 bookId 查书架,否则回退全局 active 书目录。 */
208
+ function resolveOutputDir(config: NovelConfig, bookId?: string): string {
209
+ if (bookId !== undefined && bookId !== '') {
210
+ const book = loadBookshelf().books.find(b => b.id === bookId)
211
+ if (book !== undefined && book.outputDir !== '') return book.outputDir
212
+ }
213
+ return config.outputDir
214
+ }
215
+
216
+ /** Loopback-only fence (mirrors the family plugins' pairing routes). */
217
+ function isLoopbackRequest(request: IncomingMessage): boolean {
218
+ const address = request.socket.remoteAddress
219
+ if (address !== '127.0.0.1' && address !== '::1' && address !== '::ffff:127.0.0.1') return false
220
+ const host = request.headers.host
221
+ if (typeof host !== 'string') return false
222
+ let hostUrl: URL
223
+ try {
224
+ hostUrl = new URL(`http://${host}`)
225
+ } catch {
226
+ return false
227
+ }
228
+ if (hostUrl.hostname !== '127.0.0.1' && hostUrl.hostname !== 'localhost' && hostUrl.hostname !== '[::1]') return false
229
+ if (request.headers['sec-fetch-site'] === 'cross-site') return false
230
+ const origin = request.headers.origin
231
+ if (origin === undefined) return true
232
+ try {
233
+ return new URL(origin).host === hostUrl.host
234
+ } catch {
235
+ return false
236
+ }
237
+ }
238
+
239
+ /** One JSON response. */
240
+ function writeJson(res: ServerResponse, status: number, body: unknown): void {
241
+ const payload = JSON.stringify(body)
242
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'referrer-policy': 'no-referrer' })
243
+ res.end(payload)
244
+ }
245
+
246
+ /** Read a JSON request body. */
247
+ async function readJsonBody<T>(req: IncomingMessage): Promise<T | undefined> {
248
+ const chunks: Buffer[] = []
249
+ let size = 0
250
+ for await (const chunk of req) {
251
+ const buffer = chunk as Buffer
252
+ size += buffer.length
253
+ if (size > MAX_JSON_BODY_BYTES) return undefined
254
+ chunks.push(buffer)
255
+ }
256
+ try {
257
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as T
258
+ } catch {
259
+ return undefined
260
+ }
261
+ }
262
+
263
+ /** Route deps. */
264
+ export interface NovelRoutesDeps {
265
+ ctx: Context
266
+ /** Resolve the live plugin config (settings-aware). */
267
+ getConfig: () => NovelConfig
268
+ /** Persist a config patch through the settings seam. */
269
+ patchConfig: (patch: ConfigPatch) => Promise<NovelConfig>
270
+ /** Raw settings config(未与激活书合并)——目录迁移判断默认目录是否需同步用。 */
271
+ rawConfig?: () => { outputDir?: string }
272
+ }
273
+
274
+ /** Default chapter count for planning when the request omits it. */
275
+ const DEFAULT_PLAN_COUNT = 30
276
+
277
+ /**
278
+ * Build every /api/dsh-novel-forge route.
279
+ * @param deps - context, config resolver, config patcher.
280
+ * @returns the route list.
281
+ */
282
+ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
283
+ const { ctx, getConfig, patchConfig } = deps
284
+
285
+ /** 全书质检实时状态(内存态,重启后回到 idle;用于 /status 暴露进度)。 */
286
+ let auditState: AuditStatus = { status: 'idle', totalBatches: 0, completedBatches: 0 }
287
+
288
+ /** Guard helper: fence + method check. */
289
+ const guard = (req: IncomingMessage, res: ServerResponse, method: string): boolean => {
290
+ if (!isLoopbackRequest(req)) {
291
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
292
+ return false
293
+ }
294
+ if (req.method !== method) {
295
+ writeJson(res, 405, { error: `method not allowed (expected ${method})` })
296
+ return false
297
+ }
298
+ return true
299
+ }
300
+
301
+ /** Load (and sync) the project, or respond 400. */
302
+ const requireProject = (res: ServerResponse): ReturnType<typeof loadProject> => {
303
+ const config = getConfig()
304
+ const project = loadProject(config.outputDir)
305
+ if (project === undefined) {
306
+ writeJson(res, 400, { error: '输出目录中没有项目,请先加载大纲' })
307
+ return undefined
308
+ }
309
+ syncProjectWithDisk(project, config.outputDir)
310
+ saveProject(config.outputDir, project)
311
+ return project
312
+ }
313
+
314
+ // -------------------------------------------------------------- status
315
+ const statusRoute: WebRoute = {
316
+ kind: 'exact',
317
+ path: NOVEL_API.status,
318
+ handler: (req, res) => {
319
+ if (!guard(req, res, 'GET')) return
320
+ const config = getConfig()
321
+ const qurl = new URL(req.url ?? '/', 'http://localhost')
322
+ const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
323
+ // 书架为空时播种 settings 默认输出目录里的已有项目。
324
+ seedBookshelfFromOutputDir(outputDir)
325
+ const project = loadProject(outputDir)
326
+ if (project !== undefined) {
327
+ // 自动兜底:generating 超过 10 分钟(正常一章 2-5 分钟)视为卡死/中断,
328
+ // 复位为 pending,避免"生成中"状态卡死无法重新生成。
329
+ const staleMs = 10 * 60 * 1000
330
+ for (const c of project.chapters) {
331
+ if (c.status === 'generating' && c.generatingAt !== undefined) {
332
+ const started = new Date(c.generatingAt).getTime()
333
+ if (Number.isFinite(started) && Date.now() - started > staleMs) {
334
+ c.status = 'pending'
335
+ c.error = undefined
336
+ c.generatingAt = undefined
337
+ }
338
+ }
339
+ }
340
+ syncProjectWithDisk(project, outputDir)
341
+ saveProject(outputDir, project)
342
+ }
343
+ const slim = new URL(req.url ?? '/', 'http://localhost').searchParams.get('slim') === '1'
344
+ let projectPayload: StatusResponse['project']
345
+ if (project === undefined) {
346
+ projectPayload = undefined
347
+ } else if (slim) {
348
+ // slim 瘦身:轮询/角标只需章节状态与分数 + 轻量元数据,
349
+ // 去掉正文、beats、图集(base64)、道藏/大世界/资产等重字段,避免长书轮询反复传输大体积。
350
+ projectPayload = {
351
+ bookName: project.bookName,
352
+ outline: project.outline.slice(0, 200),
353
+ chapters: project.chapters.map(c => ({
354
+ no: c.no,
355
+ volume: c.volume,
356
+ title: c.title,
357
+ status: c.status,
358
+ chars: c.chars,
359
+ error: c.error,
360
+ review: c.review !== undefined ? { score: c.review.score, passed: c.review.passed } : undefined,
361
+ })) as unknown as ProjectState['chapters'],
362
+ createdAt: project.createdAt,
363
+ updatedAt: project.updatedAt,
364
+ } as unknown as ProjectState
365
+ } else {
366
+ // 瘦身:facts 只回最近 80 条(客户端最多展示 60),避免长篇后
367
+ // status 响应体随编年录无限膨胀。
368
+ projectPayload = { ...project, facts: (project.facts ?? []).slice(-80) }
369
+ }
370
+ const response: StatusResponse = {
371
+ config,
372
+ project: projectPayload,
373
+ generatedFiles: listChapterFiles(config.outputDir),
374
+ audit: auditState,
375
+ }
376
+ writeJson(res, 200, response)
377
+ },
378
+ }
379
+
380
+ // -------------------------------------------------------- load-outline
381
+ const loadOutlineRoute: WebRoute = {
382
+ kind: 'exact',
383
+ path: NOVEL_API.loadOutline,
384
+ handler: async (req, res) => {
385
+ if (!guard(req, res, 'POST')) return
386
+ const body = await readJsonBody<LoadOutlineRequest>(req)
387
+ const config = getConfig()
388
+ try {
389
+ let outline: string
390
+ let path: string | undefined
391
+ if (body?.text !== undefined && body.text.trim() !== '') {
392
+ outline = body.text.trim()
393
+ } else {
394
+ const target = body?.path?.trim() !== '' && body?.path !== undefined ? body.path : config.outlinePath
395
+ outline = readOutlineFromDocx(target)
396
+ path = target
397
+ }
398
+ if (outline.length < 50) {
399
+ writeJson(res, 400, { error: '大纲内容过短(<50 字符),请检查文件或直接粘贴大纲文本' })
400
+ return
401
+ }
402
+ const response: LoadOutlineResponse = {
403
+ outline,
404
+ bookName: createProject(outline).bookName,
405
+ chars: outline.length,
406
+ path,
407
+ }
408
+ writeJson(res, 200, response)
409
+ } catch (error) {
410
+ writeJson(res, 400, { error: (error as Error).message })
411
+ }
412
+ },
413
+ }
414
+
415
+ // -------------------------------------------------------- save-outline
416
+ const saveOutlineRoute: WebRoute = {
417
+ kind: 'exact',
418
+ path: NOVEL_API.saveOutline,
419
+ handler: async (req, res) => {
420
+ if (!guard(req, res, 'POST')) return
421
+ const body = await readJsonBody<LoadOutlineRequest>(req)
422
+ const config = getConfig()
423
+ const outline = body?.text ?? ''
424
+ if (outline.trim().length < 50) {
425
+ writeJson(res, 400, { error: '大纲内容过短(<50 字符)' })
426
+ return
427
+ }
428
+ let project = loadProject(config.outputDir)
429
+ const now = new Date().toISOString()
430
+ if (project === undefined) {
431
+ project = createProject(outline)
432
+ } else {
433
+ project.outline = outline
434
+ project.bookName = createProject(outline).bookName
435
+ project.updatedAt = now
436
+ }
437
+ saveProject(config.outputDir, project)
438
+ writeJson(res, 200, { ok: true, bookName: project.bookName })
439
+ },
440
+ }
441
+
442
+ // --------------------------------------------------------------- bible
443
+ const bibleRoute: WebRoute = {
444
+ kind: 'exact',
445
+ path: NOVEL_API.bible,
446
+ handler: async (req, res) => {
447
+ if (!guard(req, res, 'POST')) return
448
+ const body = await readJsonBody<BibleRequest>(req)
449
+ const config = getConfig()
450
+ const project = loadProject(config.outputDir)
451
+ const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
452
+ ? body.outline
453
+ : project?.outline
454
+ if (outline === undefined || outline.length < 50) {
455
+ writeJson(res, 400, { error: '请先加载大纲' })
456
+ return
457
+ }
458
+ try {
459
+ const bible = await extractBible(ctx, config, outline, project)
460
+ const now = new Date().toISOString()
461
+ const next = project ?? createProject(outline)
462
+ next.bible = bible
463
+ next.updatedAt = now
464
+ saveProject(config.outputDir, next)
465
+ const response: BibleResponse = { bible }
466
+ writeJson(res, 200, response)
467
+ } catch (error) {
468
+ writeJson(res, 500, { error: (error as Error).message })
469
+ }
470
+ },
471
+ }
472
+
473
+ // ------------------------------------------------------------- volumes
474
+ const volumesRoute: WebRoute = {
475
+ kind: 'exact',
476
+ path: NOVEL_API.volumes,
477
+ handler: async (req, res) => {
478
+ if (!guard(req, res, 'POST')) return
479
+ const body = await readJsonBody<VolumesRequest & { bookId?: string }>(req)
480
+ const config0 = getConfig()
481
+ const outputDir = resolveOutputDir(config0, body?.bookId)
482
+ const config = { ...config0, outputDir }
483
+ const project = loadProject(outputDir)
484
+ const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
485
+ ? body.outline
486
+ : project?.outline
487
+ if (outline === undefined || outline.length < 50) {
488
+ writeJson(res, 400, { error: '请先加载大纲' })
489
+ return
490
+ }
491
+ try {
492
+ const volumes = await planVolumes(ctx, config, outline)
493
+ const now = new Date().toISOString()
494
+ const next = project ?? createProject(outline)
495
+ next.volumes = volumes
496
+ next.updatedAt = now
497
+ saveProject(outputDir, next)
498
+ const response: VolumesResponse = { volumes }
499
+ writeJson(res, 200, response)
500
+ } catch (error) {
501
+ writeJson(res, 500, { error: (error as Error).message })
502
+ }
503
+ },
504
+ }
505
+
506
+ // ----------------------------------------------------------------- plan
507
+ const planRoute: WebRoute = {
508
+ kind: 'exact',
509
+ path: NOVEL_API.plan,
510
+ handler: async (req, res) => {
511
+ if (!guard(req, res, 'POST')) return
512
+ const body = await readJsonBody<PlanRequest & { bookId?: string }>(req)
513
+ const config0 = getConfig()
514
+ const outputDir = resolveOutputDir(config0, body?.bookId)
515
+ const config = { ...config0, outputDir }
516
+ const project = loadProject(outputDir)
517
+ const outline = body?.outline?.trim() !== '' && body?.outline !== undefined
518
+ ? body.outline
519
+ : project?.outline
520
+ if (outline === undefined || outline.length < 50) {
521
+ writeJson(res, 400, { error: '请先加载大纲(或粘贴大纲文本)' })
522
+ return
523
+ }
524
+ const count = body?.chapterCount ?? DEFAULT_PLAN_COUNT
525
+ if (!Number.isInteger(count) || count < 1 || count > 200) {
526
+ writeJson(res, 400, { error: 'chapterCount 须为 1-200 的整数' })
527
+ return
528
+ }
529
+ try {
530
+ const next = project ?? createProject(outline)
531
+ const chapters: ChapterPlan[] = await planChapters(ctx, config, next, count, body?.volume, config.outputDir)
532
+ // 并发保护:长 LLM 调用期间磁盘可能已被其他请求更新(角色库/剧情线等),
533
+ // 保存前合并磁盘最新易变字段,避免旧快照覆盖新修改。
534
+ mergeVolatileFromDisk(config.outputDir, next)
535
+ next.chapters.push(...chapters)
536
+ next.updatedAt = new Date().toISOString()
537
+ saveProject(config.outputDir, next)
538
+ const response: PlanResponse = { chapters, volumes: next.volumes }
539
+ writeJson(res, 200, response)
540
+ } catch (error) {
541
+ writeJson(res, 500, { error: (error as Error).message })
542
+ }
543
+ },
544
+ }
545
+
546
+ // ------------------------------------------------------------- generate
547
+ const generateRoute: WebRoute = {
548
+ kind: 'exact',
549
+ path: NOVEL_API.generate,
550
+ handler: async (req, res) => {
551
+ if (!guard(req, res, 'POST')) return
552
+ const config0 = getConfig()
553
+ const body = await readJsonBody<{ chapterNo?: number; skipReview?: boolean; bookId?: string }>(req)
554
+ const outputDir = resolveOutputDir(config0, body?.bookId)
555
+ const config = { ...config0, outputDir }
556
+ const project = loadProject(outputDir)
557
+ if (project === undefined) {
558
+ writeJson(res, 400, { error: '输出目录中没有项目' })
559
+ return
560
+ }
561
+ const rawNo = body?.chapterNo
562
+ if (!Number.isInteger(rawNo) || rawNo === undefined || rawNo < 1) {
563
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
564
+ return
565
+ }
566
+ const no: number = rawNo
567
+ const chapter = project.chapters.find(c => c.no === no)
568
+ if (chapter === undefined) {
569
+ writeJson(res, 404, { error: `章节 ${no} 不在计划中` })
570
+ return
571
+ }
572
+ if (chapter.status === 'generating') {
573
+ writeJson(res, 409, { error: `章节 ${no} 正在生成中` })
574
+ return
575
+ }
576
+
577
+ // NDJSON stream.
578
+ res.writeHead(200, {
579
+ 'content-type': 'application/x-ndjson; charset=utf-8',
580
+ 'cache-control': 'no-cache',
581
+ 'x-accel-buffering': 'no',
582
+ 'referrer-policy': 'no-referrer',
583
+ })
584
+ chapter.status = 'generating'
585
+ chapter.error = undefined
586
+ chapter.generatingAt = new Date().toISOString()
587
+ // 并发保护:合并磁盘最新易变字段后保存,避免本请求覆盖并发修改(角色库/剧情线等)。
588
+ mergeVolatileFromDisk(config.outputDir, project)
589
+ saveProject(config.outputDir, project)
590
+
591
+ const send = (frame: JobFrame): void => {
592
+ res.write(JSON.stringify(frame) + '\n')
593
+ }
594
+
595
+ const liveSession = nextSessionId()
596
+ emitLive({ type: 'session_started', sessionId: liveSession, label: '正文生成', model: config.generateModel || config.model, at: new Date().toISOString(), context: { interactionId: liveSession, taskId: `ch-${no}` } })
597
+ emitLive({ type: 'phase_changed', sessionId: liveSession, phase: 'streaming', phaseMessage: '模型正在返回正文', at: new Date().toISOString() })
598
+
599
+ try {
600
+ send({ type: 'start', no, title: chapter.title })
601
+ let genChars = 0
602
+ for await (const step of generateChapterStream(ctx, config, project, config.outputDir, no)) {
603
+ if (step.frame === 'delta') {
604
+ send({ type: 'delta', text: step.text })
605
+ genChars += step.text.length
606
+ emitLive({ type: 'output_delta', sessionId: liveSession, content: step.text, totalChars: genChars, at: new Date().toISOString() })
607
+ } else if (step.frame === 'done') {
608
+ send({ type: 'done', no, file: step.file, chars: step.chars, title: chapter.title, warn: step.warn })
609
+ }
610
+ }
611
+ emitLive({ type: 'session_completed', sessionId: liveSession, totalChars: genChars, preview: '', at: new Date().toISOString(), phase: 'completed' })
612
+ // Auto pipeline: summary + facts(一次调用)-> review(unless skipped)。
613
+ try {
614
+ await summarizeAndExtractFacts(ctx, config, project, config.outputDir, no)
615
+ } catch (error) {
616
+ console.warn('[dsh-novel-forge] summary/facts failed:', (error as Error).message)
617
+ }
618
+ // 伏笔落地标记:正文中命中 planned 伏笔关键词 → 自动标为 planted(暗线管理页与正文同步)。
619
+ try {
620
+ const marked = markForeshadowPlanted(project, config.outputDir, no)
621
+ if (marked > 0) {
622
+ console.log(`[dsh-novel-forge] 第${no}章已埋伏笔 ${marked} 条`)
623
+ }
624
+ } catch (error) {
625
+ console.warn('[dsh-novel-forge] markForeshadowPlanted failed:', (error as Error).message)
626
+ }
627
+ if (!(body?.skipReview === true) && (config.autoReview ?? true)) {
628
+ const report = await reviewChapter(ctx, config, project, config.outputDir, no)
629
+ send({ type: 'review', no, report })
630
+ } else {
631
+ chapter.status = 'approved'
632
+ mergeVolatileFromDisk(config.outputDir, project)
633
+ saveProject(config.outputDir, project)
634
+ }
635
+ // 作者复盘:叙事结构检查(钩子兑现/结尾钩子/推进/连续性/趋势;不改变章节状态)。
636
+ if (config.autoAuthorReview ?? true) {
637
+ try {
638
+ const currentBody = readChapterFile(config.outputDir, chapter)
639
+ let prevTail = ''
640
+ if (no > 1) {
641
+ const prev = project.chapters.find(c => c.no === no - 1)
642
+ if (prev !== undefined) {
643
+ prevTail = (readChapterFile(config.outputDir, prev) ?? '').replace(/^#.*$/m, '').trim().slice(-600)
644
+ }
645
+ }
646
+ if (currentBody !== undefined) {
647
+ const review = await authorReviewChapter(ctx, config, project, no, currentBody, prevTail)
648
+ chapter.authorReview = review
649
+ // 复盘标记推进的剧情线 → 自动关联本章。
650
+ if (review.advancedLines !== undefined) {
651
+ autoLinkPlotlines(project, no, review.advancedLines)
652
+ }
653
+ mergeVolatileFromDisk(config.outputDir, project)
654
+ saveProject(config.outputDir, project)
655
+ send({ type: 'author-review', no, review })
656
+ }
657
+ } catch (error) {
658
+ console.warn('[dsh-novel-forge] author review failed:', (error as Error).message)
659
+ }
660
+ }
661
+ res.end()
662
+ } catch (error) {
663
+ chapter.status = 'error'
664
+ chapter.error = (error as Error).message
665
+ mergeVolatileFromDisk(config.outputDir, project)
666
+ saveProject(config.outputDir, project)
667
+ if (!res.writableEnded) {
668
+ send({ type: 'error', no, message: (error as Error).message })
669
+ res.end()
670
+ }
671
+ }
672
+ },
673
+ }
674
+
675
+ // --------------------------------------------------------------- review
676
+ const reviewRoute: WebRoute = {
677
+ kind: 'exact',
678
+ path: NOVEL_API.review,
679
+ handler: async (req, res) => {
680
+ if (!guard(req, res, 'POST')) return
681
+ const config0 = getConfig()
682
+ const body = await readJsonBody<ReviewRequest & { bookId?: string }>(req)
683
+ const outputDir = resolveOutputDir(config0, body?.bookId)
684
+ const config = { ...config0, outputDir }
685
+ const project = loadProject(outputDir)
686
+ if (project === undefined) {
687
+ writeJson(res, 400, { error: '输出目录中没有项目' })
688
+ return
689
+ }
690
+ if (!Number.isInteger(body?.chapterNo)) {
691
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
692
+ return
693
+ }
694
+ const no = body!.chapterNo!
695
+ try {
696
+ const report = await reviewChapter(ctx, config, project, outputDir, no)
697
+ writeJson(res, 200, { report })
698
+ } catch (error) {
699
+ writeJson(res, 500, { error: (error as Error).message })
700
+ }
701
+ },
702
+ }
703
+
704
+ // -------------------------------------------------------------- rewrite
705
+ const rewriteRoute: WebRoute = {
706
+ kind: 'exact',
707
+ path: NOVEL_API.rewrite,
708
+ handler: async (req, res) => {
709
+ if (!guard(req, res, 'POST')) return
710
+ const config0 = getConfig()
711
+ const body = await readJsonBody<RewriteRequest & { bookId?: string }>(req)
712
+ const outputDir = resolveOutputDir(config0, body?.bookId)
713
+ const config = { ...config0, outputDir }
714
+ const project = loadProject(outputDir)
715
+ if (project === undefined) {
716
+ writeJson(res, 400, { error: '输出目录中没有项目' })
717
+ return
718
+ }
719
+ if (!Number.isInteger(body?.chapterNo)) {
720
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
721
+ return
722
+ }
723
+ const no = body!.chapterNo!
724
+ res.writeHead(200, {
725
+ 'content-type': 'application/x-ndjson; charset=utf-8',
726
+ 'cache-control': 'no-cache',
727
+ 'x-accel-buffering': 'no',
728
+ 'referrer-policy': 'no-referrer',
729
+ })
730
+ const send = (frame: JobFrame): void => { res.write(JSON.stringify(frame) + '\n') }
731
+ try {
732
+ for await (const step of rewriteChapterStream(ctx, config, project, config.outputDir, no, body?.instructions ?? '', body?.target)) {
733
+ if (step.frame === 'delta') send({ type: 'delta', text: step.text })
734
+ else if (step.frame === 'drafted') send({ type: 'drafted', no, chars: step.chars, draft: step.draft })
735
+ }
736
+ // Draft mode: no auto re-review — the user reviews the diff and
737
+ // decides; re-run review after applying if wanted.
738
+ res.end()
739
+ } catch (error) {
740
+ if (!res.writableEnded) {
741
+ send({ type: 'error', no, message: (error as Error).message })
742
+ res.end()
743
+ }
744
+ }
745
+ },
746
+ }
747
+
748
+ // --------------------------------------------------------------- polish
749
+ const polishRoute: WebRoute = {
750
+ kind: 'exact',
751
+ path: NOVEL_API.polish,
752
+ handler: async (req, res) => {
753
+ if (!guard(req, res, 'POST')) return
754
+ const config0 = getConfig()
755
+ const body = await readJsonBody<PolishRequest & { bookId?: string }>(req)
756
+ const outputDir = resolveOutputDir(config0, body?.bookId)
757
+ const config = { ...config0, outputDir }
758
+ const project = loadProject(outputDir)
759
+ if (project === undefined) {
760
+ writeJson(res, 400, { error: '输出目录中没有项目' })
761
+ return
762
+ }
763
+ if (!Number.isInteger(body?.chapterNo)) {
764
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
765
+ return
766
+ }
767
+ const no = body!.chapterNo!
768
+ res.writeHead(200, {
769
+ 'content-type': 'application/x-ndjson; charset=utf-8',
770
+ 'cache-control': 'no-cache',
771
+ 'x-accel-buffering': 'no',
772
+ 'referrer-policy': 'no-referrer',
773
+ })
774
+ const send = (frame: JobFrame): void => { res.write(JSON.stringify(frame) + '\n') }
775
+ try {
776
+ for await (const step of polishChapterStream(ctx, config, project, config.outputDir, no)) {
777
+ if (step.frame === 'delta') send({ type: 'delta', text: step.text })
778
+ else if (step.frame === 'drafted') send({ type: 'drafted', no, chars: step.chars, draft: step.draft })
779
+ }
780
+ res.end()
781
+ } catch (error) {
782
+ if (!res.writableEnded) {
783
+ send({ type: 'error', no, message: (error as Error).message })
784
+ res.end()
785
+ }
786
+ }
787
+ },
788
+ }
789
+
790
+ // ---------------------------------------------------- draft apply/discard
791
+ /** 采纳待确认草稿:覆盖正文文件 + 状态回 written + 清空草稿。 */
792
+ const draftApplyRoute: WebRoute = {
793
+ kind: 'exact',
794
+ path: NOVEL_API.draftApply,
795
+ handler: async (req, res) => {
796
+ if (!guard(req, res, 'POST')) return
797
+ const config = getConfig()
798
+ const project = requireProject(res)
799
+ if (project === undefined) return
800
+ const body = await readJsonBody<DraftDecisionRequest>(req)
801
+ if (!Number.isInteger(body?.chapterNo)) {
802
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
803
+ return
804
+ }
805
+ const chapter = project.chapters.find(c => c.no === body!.chapterNo!)
806
+ if (chapter === undefined) {
807
+ writeJson(res, 404, { error: `章节 ${body!.chapterNo} 不在计划中` })
808
+ return
809
+ }
810
+ if (chapter.pendingDraft === undefined || chapter.pendingDraft === '') {
811
+ writeJson(res, 400, { error: `章节 ${chapter.no} 没有待确认的草稿` })
812
+ return
813
+ }
814
+ const draft = chapter.pendingDraft
815
+ const fileName = chapterFileName(chapter)
816
+ mkdirSync(config.outputDir, { recursive: true })
817
+ const targetPath = join(config.outputDir, fileName)
818
+ // 采纳前自动备份当前原稿为 .bak.md(每次应用都刷新为最新原稿),可随时回退。
819
+ if (existsSync(targetPath)) {
820
+ copyFileSync(targetPath, join(config.outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
821
+ }
822
+ writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${draft}\n`, 'utf8')
823
+ chapter.pendingDraft = undefined
824
+ chapter.chars = draft.length
825
+ chapter.file = fileName
826
+ // 携带审查报告则沿用结论定状态(修订后审查通过 → approved);否则置 written 待审。
827
+ const carried = body?.report
828
+ if (carried !== undefined && typeof carried.score === 'number') {
829
+ chapter.review = carried
830
+ chapter.status = carried.passed ? 'approved' : 'rejected'
831
+ } else {
832
+ chapter.status = 'written'
833
+ chapter.review = undefined
834
+ }
835
+ chapter.error = undefined
836
+ project.updatedAt = new Date().toISOString()
837
+ saveProject(config.outputDir, project)
838
+ writeJson(res, 200, { ok: true, chars: draft.length, file: fileName, markdown: draft })
839
+ },
840
+ }
841
+
842
+ /** 放弃待确认草稿:保留原稿,仅清空草稿字段。 */
843
+ const draftDiscardRoute: WebRoute = {
844
+ kind: 'exact',
845
+ path: NOVEL_API.draftDiscard,
846
+ handler: async (req, res) => {
847
+ if (!guard(req, res, 'POST')) return
848
+ const config = getConfig()
849
+ const project = requireProject(res)
850
+ if (project === undefined) return
851
+ const body = await readJsonBody<DraftDecisionRequest>(req)
852
+ if (!Number.isInteger(body?.chapterNo)) {
853
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
854
+ return
855
+ }
856
+ const chapter = project.chapters.find(c => c.no === body!.chapterNo!)
857
+ if (chapter === undefined) {
858
+ writeJson(res, 404, { error: `章节 ${body!.chapterNo} 不在计划中` })
859
+ return
860
+ }
861
+ if (chapter.pendingDraft !== undefined) {
862
+ chapter.pendingDraft = undefined
863
+ project.updatedAt = new Date().toISOString()
864
+ saveProject(config.outputDir, project)
865
+ }
866
+ writeJson(res, 200, { ok: true })
867
+ },
868
+ }
869
+
870
+ // -------------------------------------------------------------- summary
871
+ const summaryRoute: WebRoute = {
872
+ kind: 'exact',
873
+ path: NOVEL_API.summary,
874
+ handler: async (req, res) => {
875
+ if (!guard(req, res, 'POST')) return
876
+ const config = getConfig()
877
+ const project = requireProject(res)
878
+ if (project === undefined) return
879
+ const body = await readJsonBody<SummaryRequest>(req)
880
+ if (!Number.isInteger(body?.chapterNo)) {
881
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
882
+ return
883
+ }
884
+ try {
885
+ const summary = await summarizeChapter(ctx, config, project, config.outputDir, body!.chapterNo!)
886
+ writeJson(res, 200, { summary })
887
+ } catch (error) {
888
+ writeJson(res, 500, { error: (error as Error).message })
889
+ }
890
+ },
891
+ }
892
+
893
+ // ---------------------------------------------------------- foreshadow
894
+ const foreshadowRoute: WebRoute = {
895
+ kind: 'exact',
896
+ path: NOVEL_API.foreshadow,
897
+ handler: async (req, res) => {
898
+ if (!guard(req, res, 'POST')) return
899
+ const config0 = getConfig()
900
+ const body = await readJsonBody<ForeshadowRequest & { bookId?: string }>(req)
901
+ const outputDir = resolveOutputDir(config0, body?.bookId)
902
+ const config = { ...config0, outputDir }
903
+ const project = loadProject(outputDir)
904
+ if (project === undefined) {
905
+ writeJson(res, 400, { error: '输出目录中没有项目' })
906
+ return
907
+ }
908
+ try {
909
+ if (body?.suggest === true) {
910
+ // AI suggestion pass: create several foreshadows from the outline.
911
+ const created = await suggestForeshadows(ctx, config, project)
912
+ project.updatedAt = new Date().toISOString()
913
+ saveProject(config.outputDir, project)
914
+ const response: ForeshadowResponse = { foreshadows: created }
915
+ writeJson(res, 200, response)
916
+ return
917
+ }
918
+ if (body?.id !== undefined) {
919
+ // Update an existing foreshadow.
920
+ const target = project.foreshadows.find(f => f.id === body.id)
921
+ if (target === undefined) {
922
+ writeJson(res, 404, { error: `伏笔 ${body.id} 不存在` })
923
+ return
924
+ }
925
+ if (body.description !== undefined) target.description = body.description
926
+ if (body.plantedChapter !== undefined) target.plantedChapter = body.plantedChapter
927
+ if (body.targetChapter !== undefined) target.targetChapter = body.targetChapter
928
+ if (body.status !== undefined) target.status = body.status
929
+ if (body.resolvedNote !== undefined) target.resolvedNote = body.resolvedNote
930
+ } else {
931
+ // Create one manually.
932
+ const description = body?.description?.trim()
933
+ if (description === undefined || description === '') {
934
+ writeJson(res, 400, { error: 'description 必填' })
935
+ return
936
+ }
937
+ project.foreshadows.push({
938
+ id: `fs-${Date.now().toString(36)}`,
939
+ description,
940
+ plantedChapter: body?.plantedChapter,
941
+ targetChapter: body?.targetChapter,
942
+ status: body?.status ?? 'planned',
943
+ })
944
+ }
945
+ project.updatedAt = new Date().toISOString()
946
+ saveProject(config.outputDir, project)
947
+ const response: ForeshadowResponse = { foreshadows: project.foreshadows }
948
+ writeJson(res, 200, response)
949
+ } catch (error) {
950
+ writeJson(res, 500, { error: (error as Error).message })
951
+ }
952
+ },
953
+ }
954
+
955
+ // -------------------------------------------------------------- export
956
+ const exportRoute: WebRoute = {
957
+ kind: 'exact',
958
+ path: NOVEL_API.exportBook,
959
+ handler: async (req, res) => {
960
+ if (!guard(req, res, 'POST')) return
961
+ const config0 = getConfig()
962
+ const body = await readJsonBody<ExportRequest & { bookId?: string }>(req)
963
+ const outputDir = resolveOutputDir(config0, body?.bookId)
964
+ const config = { ...config0, outputDir }
965
+ const project = loadProject(outputDir)
966
+ if (project === undefined) {
967
+ writeJson(res, 400, { error: '输出目录中没有项目' })
968
+ return
969
+ }
970
+ const format = body?.format === 'md' ? 'md' : 'txt'
971
+ try {
972
+ const result = exportBook(config.outputDir, project, format)
973
+ const response: ExportResponse = { ...result }
974
+ writeJson(res, 200, response)
975
+ } catch (error) {
976
+ writeJson(res, 500, { error: (error as Error).message })
977
+ }
978
+ },
979
+ }
980
+
981
+ // -------------------------------------------------------------- chapter
982
+ const chapterRoute: WebRoute = {
983
+ kind: 'exact',
984
+ path: NOVEL_API.chapter,
985
+ handler: async (req, res) => {
986
+ if (!guard(req, res, 'GET')) return
987
+ const config = getConfig()
988
+ const url = new URL(req.url ?? '/', 'http://localhost')
989
+ const outputDir = resolveOutputDir(config, url.searchParams.get('bookId') ?? undefined)
990
+ const project = loadProject(outputDir)
991
+ if (project === undefined) {
992
+ writeJson(res, 400, { error: '输出目录中没有项目' })
993
+ return
994
+ }
995
+ const rawNo = Number(url.searchParams.get('no') ?? '0')
996
+ if (!Number.isInteger(rawNo) || rawNo < 1) {
997
+ writeJson(res, 400, { error: 'no 须为正整数' })
998
+ return
999
+ }
1000
+ const chapter = project.chapters.find(c => c.no === rawNo)
1001
+ if (chapter === undefined) {
1002
+ writeJson(res, 404, { error: `章节 ${rawNo} 不在计划中` })
1003
+ return
1004
+ }
1005
+ const markdown = readChapterFile(outputDir, chapter)
1006
+ if (markdown === undefined) {
1007
+ writeJson(res, 404, { error: `章节 ${rawNo} 尚未生成` })
1008
+ return
1009
+ }
1010
+ const response: ChapterResponse = { no: chapter.no, title: chapter.title, markdown }
1011
+ writeJson(res, 200, response)
1012
+ },
1013
+ }
1014
+
1015
+ // ------------------------------------------------------ chapter check/save
1016
+ /** 审查手动编辑的正文(不落盘,返回审稿报告)。 */
1017
+ const chapterCheckRoute: WebRoute = {
1018
+ kind: 'exact',
1019
+ path: NOVEL_API.chapterCheck,
1020
+ handler: async (req, res) => {
1021
+ if (!guard(req, res, 'POST')) return
1022
+ const config = getConfig()
1023
+ const project = requireProject(res)
1024
+ if (project === undefined) return
1025
+ const body = await readJsonBody<ChapterTextRequest>(req)
1026
+ const text = body?.text?.trim() ?? ''
1027
+ if (text.length < 50) {
1028
+ writeJson(res, 400, { error: '正文过短(<50 字),请先编辑内容' })
1029
+ return
1030
+ }
1031
+ try {
1032
+ // 携带上一轮报告 → 验证模式(逐条核对原意见解决情况 + 只挑新增 high)。
1033
+ const report = await reviewChapterText(ctx, config, project, text, body?.previousReport)
1034
+ writeJson(res, 200, { report })
1035
+ } catch (error) {
1036
+ writeJson(res, 500, { error: (error as Error).message })
1037
+ }
1038
+ },
1039
+ }
1040
+
1041
+ /** 保存手动编辑的正文(自动备份 .bak,状态回 written)。 */
1042
+ const chapterSaveRoute: WebRoute = {
1043
+ kind: 'exact',
1044
+ path: NOVEL_API.chapterSave,
1045
+ handler: async (req, res) => {
1046
+ if (!guard(req, res, 'POST')) return
1047
+ const config = getConfig()
1048
+ const project = requireProject(res)
1049
+ if (project === undefined) return
1050
+ const body = await readJsonBody<ChapterTextRequest>(req)
1051
+ if (!Number.isInteger(body?.chapterNo)) {
1052
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
1053
+ return
1054
+ }
1055
+ const chapter = project.chapters.find(c => c.no === body!.chapterNo!)
1056
+ if (chapter === undefined) {
1057
+ writeJson(res, 404, { error: `章节 ${body!.chapterNo} 不在计划中` })
1058
+ return
1059
+ }
1060
+ const text = body?.text?.trim() ?? ''
1061
+ if (text.length < 50) {
1062
+ writeJson(res, 400, { error: '正文过短(<50 字),未保存' })
1063
+ return
1064
+ }
1065
+ const fileName = chapterFileName(chapter)
1066
+ mkdirSync(config.outputDir, { recursive: true })
1067
+ const targetPath = join(config.outputDir, fileName)
1068
+ if (existsSync(targetPath)) {
1069
+ copyFileSync(targetPath, join(config.outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
1070
+ }
1071
+ writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${text}\n`, 'utf8')
1072
+ chapter.status = 'written'
1073
+ chapter.chars = text.length
1074
+ chapter.file = fileName
1075
+ chapter.pendingDraft = undefined
1076
+ // 保存即审稿:携带工作区审查报告则沿用(不重复审);否则自动正式审稿一次。
1077
+ let report: ReviewReport | undefined
1078
+ const carried = body?.report
1079
+ if (carried !== undefined && typeof carried.score === 'number') {
1080
+ report = carried
1081
+ chapter.review = report
1082
+ chapter.status = report.passed ? 'approved' : 'rejected'
1083
+ } else {
1084
+ report = await reviewChapter(ctx, config, project, config.outputDir, chapter.no)
1085
+ }
1086
+ project.updatedAt = new Date().toISOString()
1087
+ saveProject(config.outputDir, project)
1088
+ const response: ChapterSaveResponse = { ok: true, chars: text.length, file: fileName, report }
1089
+ writeJson(res, 200, response)
1090
+ },
1091
+ }
1092
+
1093
+ // ----------------------------------------------------------- assistant
1094
+ const assistantRoute: WebRoute = {
1095
+ kind: 'exact',
1096
+ path: NOVEL_API.assistant,
1097
+ handler: async (req, res) => {
1098
+ if (!guard(req, res, 'POST')) return
1099
+ const config = getConfig()
1100
+ const body = await readJsonBody<AssistantRequest & { bookId?: string }>(req)
1101
+ const outputDir = resolveOutputDir(config, body?.bookId)
1102
+ const project = loadProject(outputDir)
1103
+ if (project === undefined) {
1104
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1105
+ return
1106
+ }
1107
+ const message = body?.message?.trim()
1108
+ if (message === undefined || message === '') {
1109
+ writeJson(res, 400, { error: '消息不能为空' })
1110
+ return
1111
+ }
1112
+ res.writeHead(200, {
1113
+ 'content-type': 'application/x-ndjson; charset=utf-8',
1114
+ 'cache-control': 'no-cache',
1115
+ 'x-accel-buffering': 'no',
1116
+ 'referrer-policy': 'no-referrer',
1117
+ })
1118
+ const send = (frame: AssistantFrame): void => { res.write(JSON.stringify(frame) + '\n') }
1119
+ try {
1120
+ for await (const step of runAssistantTurn(ctx, config, project, outputDir, message)) {
1121
+ if (step.frame === 'delta') send({ type: 'delta', text: step.text })
1122
+ else if (step.frame === 'tool') send({ type: 'tool', name: step.name, status: step.status, detail: step.detail })
1123
+ else if (step.frame === 'toolDelta') send({ type: 'toolDelta', name: step.name, text: step.text })
1124
+ else if (step.frame === 'toolResult') send({ type: 'toolResult', name: step.name, text: step.text })
1125
+ }
1126
+ send({ type: 'done' })
1127
+ res.end()
1128
+ } catch (error) {
1129
+ if (!res.writableEnded) {
1130
+ send({ type: 'error', message: (error as Error).message })
1131
+ res.end()
1132
+ }
1133
+ }
1134
+ },
1135
+ }
1136
+
1137
+ // -------------------------------------------------- assistant-history
1138
+ const assistantHistoryRoute: WebRoute = {
1139
+ kind: 'exact',
1140
+ path: NOVEL_API.assistantHistory,
1141
+ handler: (req, res) => {
1142
+ if (!guard(req, res, 'GET')) return
1143
+ const config = getConfig()
1144
+ const qurl = new URL(req.url ?? '/', 'http://localhost')
1145
+ const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
1146
+ const response: AssistantHistoryResponse = { messages: loadAssistantHistory(outputDir) }
1147
+ writeJson(res, 200, response)
1148
+ },
1149
+ }
1150
+
1151
+ // --------------------------------------------------- assistant-clear
1152
+ /** 清空助手对话记录。 */
1153
+ const assistantClearRoute: WebRoute = {
1154
+ kind: 'exact',
1155
+ path: NOVEL_API.assistantClear,
1156
+ handler: async (req, res) => {
1157
+ if (!guard(req, res, 'POST')) return
1158
+ const config = getConfig()
1159
+ const body = await readJsonBody<{ bookId?: string }>(req)
1160
+ const outputDir = resolveOutputDir(config, body?.bookId)
1161
+ clearAssistantHistory(outputDir)
1162
+ writeJson(res, 200, { ok: true })
1163
+ },
1164
+ }
1165
+
1166
+ // --------------------------------------------------------------- assets
1167
+ const assetsRoute: WebRoute = {
1168
+ kind: 'exact',
1169
+ path: NOVEL_API.assets,
1170
+ handler: async (req, res) => {
1171
+ // GET (read) and POST (patch) are both allowed — check methods first,
1172
+ // then the loopback fence (guard() would 405 on POST, which is wrong).
1173
+ if (req.method !== 'GET' && req.method !== 'POST') {
1174
+ writeJson(res, 405, { error: 'method not allowed (expected GET or POST)' })
1175
+ return
1176
+ }
1177
+ if (!isLoopbackRequest(req)) {
1178
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1179
+ return
1180
+ }
1181
+ const config = getConfig()
1182
+ let postBody: (AssetsPatch & { bookId?: string }) | undefined
1183
+ if (req.method === 'POST') {
1184
+ postBody = await readJsonBody<AssetsPatch & { bookId?: string }>(req)
1185
+ if (postBody === undefined) {
1186
+ writeJson(res, 400, { error: '无效的 JSON' })
1187
+ return
1188
+ }
1189
+ }
1190
+ const qurl = new URL(req.url ?? '/', 'http://localhost')
1191
+ const queryBookId = qurl.searchParams.get('bookId') ?? undefined
1192
+ const outputDir = resolveOutputDir(config, postBody?.bookId ?? queryBookId)
1193
+ const project = loadProject(outputDir)
1194
+ const projectAssets = ensureBuiltinAssets(project?.assets ?? emptyProjectAssets())
1195
+ if (req.method === 'POST') {
1196
+ const body = postBody
1197
+ if (body === undefined) {
1198
+ writeJson(res, 400, { error: '无效的 JSON' })
1199
+ return
1200
+ }
1201
+ if (project === undefined) {
1202
+ writeJson(res, 400, { error: '请先加载大纲创建项目' })
1203
+ return
1204
+ }
1205
+ if (body.genre !== undefined) projectAssets.genre = body.genre
1206
+ if (body.primaryProgression !== undefined) projectAssets.primaryProgression = body.primaryProgression
1207
+ if (body.auxiliaryProgressions !== undefined) projectAssets.auxiliaryProgressions = body.auxiliaryProgressions
1208
+ if (body.antiAiRules !== undefined) projectAssets.antiAiRules = body.antiAiRules
1209
+ if (body.styleAssets !== undefined) projectAssets.styleAssets = body.styleAssets
1210
+ projectAssets.updatedAt = new Date().toISOString()
1211
+ project.assets = projectAssets
1212
+ project.updatedAt = new Date().toISOString()
1213
+ saveProject(outputDir, project)
1214
+ }
1215
+ const response: AssetsResponse = {
1216
+ projectAssets,
1217
+ genreLibrary: [...BUILTIN_GENRE_LIBRARY, ...globalGenreLibrary()],
1218
+ antiAiLibrary: BUILTIN_ANTI_AI_RULES,
1219
+ styleTemplates: BUILTIN_STYLE_TEMPLATES,
1220
+ progressionLibrary: [...BUILTIN_PROGRESSION_MODES, ...globalProgressionLibrary()],
1221
+ starterStyleProfiles: BUILTIN_STARTER_STYLE_PROFILES,
1222
+ plotBeatLibrary: BUILTIN_PLOT_BEATS,
1223
+ }
1224
+ writeJson(res, 200, response)
1225
+ },
1226
+ }
1227
+
1228
+ // ----------------------------------------------------------- style-engine
1229
+ const styleEngineRoute: WebRoute = {
1230
+ kind: 'exact',
1231
+ path: NOVEL_API.styleEngine,
1232
+ handler: async (req, res) => {
1233
+ if (!guard(req, res, 'POST')) return
1234
+ const config = getConfig()
1235
+ const project = loadProject(config.outputDir)
1236
+ const body = await readJsonBody<StyleEngineRequest>(req)
1237
+ const sample = body?.sampleText?.trim()
1238
+ if (sample === undefined || sample.length < 50) {
1239
+ writeJson(res, 400, { error: '样本文本过短(<50 字符),请粘贴一段能代表目标风格的文字' })
1240
+ return
1241
+ }
1242
+ try {
1243
+ const rules = await extractStyleAsset(ctx, config, sample)
1244
+ const name = body?.name?.trim() !== '' && body?.name !== undefined ? body.name : `风格资产 ${Date.now().toString(36)}`
1245
+ const styleAsset = {
1246
+ name: name.slice(0, 40),
1247
+ ...rules,
1248
+ sourceText: sample.slice(0, 3000),
1249
+ createdAt: new Date().toISOString(),
1250
+ }
1251
+ if (project !== undefined) {
1252
+ project.assets ??= emptyProjectAssets()
1253
+ project.assets.styleAssets ??= []
1254
+ project.assets.styleAssets.push(styleAsset)
1255
+ project.assets.updatedAt = new Date().toISOString()
1256
+ project.updatedAt = new Date().toISOString()
1257
+ saveProject(config.outputDir, project)
1258
+ }
1259
+ writeJson(res, 200, { styleAsset })
1260
+ } catch (error) {
1261
+ writeJson(res, 500, { error: (error as Error).message })
1262
+ }
1263
+ },
1264
+ }
1265
+
1266
+ // ----------------------------------------------------------- style-formula
1267
+ const styleFormulaRoute: WebRoute = {
1268
+ kind: 'exact',
1269
+ path: NOVEL_API.styleFormula,
1270
+ handler: async (req, res) => {
1271
+ if (!guard(req, res, 'POST')) return
1272
+ const config = getConfig()
1273
+ const project = loadProject(config.outputDir)
1274
+ const body = await readJsonBody<StyleEngineRequest & { depth?: string }>(req)
1275
+ const sample = body?.sampleText?.trim()
1276
+ if (sample === undefined || sample.length < 50) {
1277
+ writeJson(res, 400, { error: '样本文本过短(<50 字符),请粘贴一段能代表目标风格的文字' })
1278
+ return
1279
+ }
1280
+ const depth = (['basic', 'standard', 'deep'] as const).includes(body?.depth as never)
1281
+ ? body!.depth! as 'basic' | 'standard' | 'deep'
1282
+ : 'standard'
1283
+ try {
1284
+ const formula = await extractStyleFormula(ctx, config, sample, depth)
1285
+ const key = `sf-${Date.now().toString(36)}`
1286
+ const styleFormula = { key, ...formula, depth, createdAt: new Date().toISOString() }
1287
+ if (project !== undefined) {
1288
+ project.assets ??= emptyProjectAssets()
1289
+ project.assets.styleFormulas ??= []
1290
+ project.assets.styleFormulas.push(styleFormula)
1291
+ project.assets.updatedAt = new Date().toISOString()
1292
+ project.updatedAt = new Date().toISOString()
1293
+ saveProject(config.outputDir, project)
1294
+ }
1295
+ writeJson(res, 200, { styleFormula })
1296
+ } catch (error) {
1297
+ writeJson(res, 500, { error: (error as Error).message })
1298
+ }
1299
+ },
1300
+ }
1301
+
1302
+ // ----------------------------------------------------------- style-detect
1303
+ /** 正文实时 AI 味检测(本地确定性扫描,免 LLM)。 */
1304
+ const styleDetectRoute: WebRoute = {
1305
+ kind: 'exact',
1306
+ path: NOVEL_API.styleDetect,
1307
+ handler: async (req, res) => {
1308
+ if (!guard(req, res, 'POST')) return
1309
+ const body = await readJsonBody<{ text?: string }>(req)
1310
+ const text = body?.text?.trim() ?? ''
1311
+ if (text.length < 20) {
1312
+ writeJson(res, 400, { error: '文本过短(<20 字符)' })
1313
+ return
1314
+ }
1315
+ const scan = scanAiFlavor(text.slice(0, 20000))
1316
+ writeJson(res, 200, { scan })
1317
+ },
1318
+ }
1319
+
1320
+ // --------------------------------------------------------- market-radar
1321
+ /** 热门题材雷达:输入平台/题材/榜单文本 → 信号 + 生产底座 + 开书创意。 */
1322
+ const marketRadarRoute: WebRoute = {
1323
+ kind: 'exact',
1324
+ path: NOVEL_API.marketRadar,
1325
+ handler: async (req, res) => {
1326
+ if (!guard(req, res, 'POST')) return
1327
+ const config = getConfig()
1328
+ const body = await readJsonBody<MarketRadarRequest>(req)
1329
+ try {
1330
+ const result = await runMarketRadar(ctx, config, body ?? {})
1331
+ writeJson(res, 200, { result })
1332
+ } catch (error) {
1333
+ writeJson(res, 500, { error: (error as Error).message })
1334
+ }
1335
+ },
1336
+ }
1337
+
1338
+ // ------------------------------------------------- market-radar scan
1339
+ /** 真实榜单扫榜:抓取公开榜单(容错),返回分组候选。 */
1340
+ const marketRadarScanRoute: WebRoute = {
1341
+ kind: 'exact',
1342
+ path: NOVEL_API.marketRadarScan,
1343
+ handler: async (req, res) => {
1344
+ if (!guard(req, res, 'POST')) return
1345
+ const body = await readJsonBody<{ platforms?: string[] }>(req)
1346
+ try {
1347
+ const result = await scanMarketRanking(body?.platforms)
1348
+ writeJson(res, 200, { result })
1349
+ } catch (error) {
1350
+ writeJson(res, 500, { error: (error as Error).message })
1351
+ }
1352
+ },
1353
+ }
1354
+
1355
+ // ------------------------------------------------- market-radar apply
1356
+ /** 把雷达生产底座一键应用到某本书(写入项目资产/开书定盘,供后续规划与生成遵守)。 */
1357
+ const marketRadarApplyRoute: WebRoute = {
1358
+ kind: 'exact',
1359
+ path: NOVEL_API.marketRadarApply,
1360
+ handler: async (req, res) => {
1361
+ if (!guard(req, res, 'POST')) return
1362
+ const body = await readJsonBody<{ bookId?: string; foundation?: ProductionFoundation }>(req)
1363
+ const pf = body?.foundation
1364
+ if (pf === undefined) {
1365
+ writeJson(res, 400, { error: '缺少 foundation' })
1366
+ return
1367
+ }
1368
+ const config = getConfig()
1369
+ const outputDir = resolveOutputDir(config, body?.bookId)
1370
+ const project = loadProject(outputDir)
1371
+ if (project === undefined) {
1372
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1373
+ return
1374
+ }
1375
+ const genreBuiltin = BUILTIN_GENRE_LIBRARY.find(g => g.name === (pf.genre.existingId || pf.genre.name))
1376
+ const genreNode: GenreNode = genreBuiltin !== undefined
1377
+ ? { ...genreBuiltin }
1378
+ : { name: pf.genre.name.slice(0, 40), description: pf.genre.description, template: pf.genre.template, children: [] }
1379
+ const findMode = (m: { existingId?: string; name: string }): ProgressionMode | undefined => BUILTIN_PROGRESSION_MODES.find(x => x.name === (m.existingId || m.name))
1380
+ const primary = findMode(pf.primaryStoryMode) ?? {
1381
+ name: pf.primaryStoryMode.name.slice(0, 40),
1382
+ driver: pf.primaryStoryMode.driver,
1383
+ readerExpectation: pf.primaryStoryMode.readerExpectation,
1384
+ payoffs: [],
1385
+ risks: [],
1386
+ primary: true,
1387
+ }
1388
+ const aux: ProgressionMode[] = []
1389
+ if (pf.secondaryStoryMode !== undefined) {
1390
+ const sec = findMode(pf.secondaryStoryMode) ?? {
1391
+ name: pf.secondaryStoryMode.name.slice(0, 40),
1392
+ driver: pf.secondaryStoryMode.driver,
1393
+ readerExpectation: pf.secondaryStoryMode.readerExpectation,
1394
+ payoffs: [],
1395
+ risks: [],
1396
+ primary: false,
1397
+ }
1398
+ aux.push(sec)
1399
+ }
1400
+ project.assets ??= emptyProjectAssets()
1401
+ project.assets.genre = genreNode
1402
+ project.assets.primaryProgression = primary
1403
+ project.assets.auxiliaryProgressions = aux
1404
+ project.bookContract = {
1405
+ promise: pf.genre.description.slice(0, 120),
1406
+ primaryModeName: pf.primaryStoryMode.name,
1407
+ secondaryModeNames: pf.secondaryStoryMode !== undefined ? [pf.secondaryStoryMode.name] : [],
1408
+ tone: pf.genre.template,
1409
+ targetPlatform: undefined,
1410
+ }
1411
+ project.updatedAt = new Date().toISOString()
1412
+ saveProject(outputDir, project)
1413
+ writeJson(res, 200, { ok: true, bookName: project.bookName })
1414
+ },
1415
+ }
1416
+
1417
+ // ------------------------------------------------- market-radar sync
1418
+ /** 把雷达生产底座里的「新资产」同步进全局资源库(跨书复用;已有名字跳过)。 */
1419
+ const marketRadarSyncRoute: WebRoute = {
1420
+ kind: 'exact',
1421
+ path: NOVEL_API.marketRadarSync,
1422
+ handler: async (req, res) => {
1423
+ if (!guard(req, res, 'POST')) return
1424
+ const body = await readJsonBody<{ foundation?: ProductionFoundation }>(req)
1425
+ const pf = body?.foundation
1426
+ if (pf === undefined) {
1427
+ writeJson(res, 400, { error: '缺少 foundation' })
1428
+ return
1429
+ }
1430
+ const synced = { genre: false, primaryMode: false, secondaryMode: false }
1431
+ if (pf.genre.existingId === undefined && pf.genre.name !== '') {
1432
+ synced.genre = addGlobalGenre({ name: pf.genre.name.slice(0, 40), description: pf.genre.description, template: pf.genre.template, children: [] })
1433
+ }
1434
+ if (pf.primaryStoryMode.existingId === undefined && pf.primaryStoryMode.name !== '') {
1435
+ synced.primaryMode = addGlobalMode({ name: pf.primaryStoryMode.name.slice(0, 40), driver: pf.primaryStoryMode.driver, readerExpectation: pf.primaryStoryMode.readerExpectation, payoffs: [], risks: [], primary: true })
1436
+ }
1437
+ if (pf.secondaryStoryMode !== undefined && pf.secondaryStoryMode !== null && pf.secondaryStoryMode.existingId === undefined && pf.secondaryStoryMode.name !== '') {
1438
+ synced.secondaryMode = addGlobalMode({ name: pf.secondaryStoryMode.name.slice(0, 40), driver: pf.secondaryStoryMode.driver, readerExpectation: pf.secondaryStoryMode.readerExpectation, payoffs: [], risks: [], primary: false })
1439
+ }
1440
+ writeJson(res, 200, { ok: true, synced })
1441
+ },
1442
+ }
1443
+
1444
+ // ------------------------------------------------- market-radar brief
1445
+ /** 开书创意简报:用选中的市场信号 + 影响模式生成。 */
1446
+ const marketRadarBriefRoute: WebRoute = {
1447
+ kind: 'exact',
1448
+ path: NOVEL_API.marketRadarBrief,
1449
+ handler: async (req, res) => {
1450
+ if (!guard(req, res, 'POST')) return
1451
+ const config = getConfig()
1452
+ const body = await readJsonBody<MarketRadarBriefRequest>(req)
1453
+ if (body === undefined || body.influenceMode === undefined) {
1454
+ writeJson(res, 400, { error: '缺少 influenceMode' })
1455
+ return
1456
+ }
1457
+ try {
1458
+ const creativeBrief = await runMarketCreativeBrief(ctx, config, body)
1459
+ writeJson(res, 200, { creativeBrief })
1460
+ } catch (error) {
1461
+ writeJson(res, 500, { error: (error as Error).message })
1462
+ }
1463
+ },
1464
+ }
1465
+
1466
+ // ------------------------------------------------------------- knowledge
1467
+ /** 书内知识库:GET 读取 / POST 增删改(按书路由)。 */
1468
+ const knowledgeRoute: WebRoute = {
1469
+ kind: 'exact',
1470
+ path: NOVEL_API.knowledge,
1471
+ handler: async (req, res) => {
1472
+ if (req.method === 'POST') {
1473
+ if (!guard(req, res, 'POST')) return
1474
+ } else {
1475
+ if (!guard(req, res, 'GET')) return
1476
+ }
1477
+ const config = getConfig()
1478
+ const qurl = new URL(req.url ?? '/', 'http://localhost')
1479
+ const body = req.method === 'POST' ? await readJsonBody<KnowledgeRequest & { bookId?: string }>(req) : undefined
1480
+ const outputDir = resolveOutputDir(config, body?.bookId ?? qurl.searchParams.get('bookId') ?? undefined)
1481
+ const project = loadProject(outputDir)
1482
+ if (project === undefined) {
1483
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1484
+ return
1485
+ }
1486
+ project.knowledgeDocs ??= []
1487
+ if (req.method === 'POST' && body !== undefined) {
1488
+ if (body.action === 'add' && body.doc !== undefined) {
1489
+ project.knowledgeDocs.push({ id: body.doc.id ?? `kd-${Date.now().toString(36)}`, title: body.doc.title, content: body.doc.content, updatedAt: new Date().toISOString() })
1490
+ } else if (body.action === 'remove' && body.id !== undefined) {
1491
+ project.knowledgeDocs = project.knowledgeDocs.filter(d => d.id !== body.id)
1492
+ } else if (body.action === 'replace' && body.doc !== undefined) {
1493
+ project.knowledgeDocs = project.knowledgeDocs.map(d => d.id === body.doc!.id ? { ...d, title: body.doc!.title, content: body.doc!.content, updatedAt: new Date().toISOString() } : d)
1494
+ }
1495
+ project.updatedAt = new Date().toISOString()
1496
+ saveProject(outputDir, project)
1497
+ }
1498
+ writeJson(res, 200, { docs: project.knowledgeDocs })
1499
+ },
1500
+ }
1501
+
1502
+ // ---------------------------------------------------------- book-analysis
1503
+ /** 书分析/拆书:输入文本 → 卖点/结构/可借鉴点/风险。 */
1504
+ const bookAnalysisRoute: WebRoute = {
1505
+ kind: 'exact',
1506
+ path: NOVEL_API.bookAnalysis,
1507
+ handler: async (req, res) => {
1508
+ if (!guard(req, res, 'POST')) return
1509
+ const config = getConfig()
1510
+ const body = await readJsonBody<BookAnalysisRequest>(req)
1511
+ if (body === undefined || (body.text ?? '').trim().length < 50) {
1512
+ writeJson(res, 400, { error: '文本过短(<50 字符)' })
1513
+ return
1514
+ }
1515
+ try {
1516
+ const result = await runBookAnalysis(ctx, config, body)
1517
+ writeJson(res, 200, { result })
1518
+ } catch (error) {
1519
+ writeJson(res, 500, { error: (error as Error).message })
1520
+ }
1521
+ },
1522
+ }
1523
+
1524
+ // ---------------------------------------------------------- idea-inspiration
1525
+ /** 创意灵感:一句话/题材 → 多方向开书灵感。 */
1526
+ const ideaInspirationRoute: WebRoute = {
1527
+ kind: 'exact',
1528
+ path: NOVEL_API.ideaInspiration,
1529
+ handler: async (req, res) => {
1530
+ if (!guard(req, res, 'POST')) return
1531
+ const config = getConfig()
1532
+ const body = await readJsonBody<IdeaInspirationRequest>(req)
1533
+ if (body === undefined || (body.idea ?? '').trim().length < 2) {
1534
+ writeJson(res, 400, { error: '请填写你的方向/一句话想法' })
1535
+ return
1536
+ }
1537
+ try {
1538
+ const result = await runIdeaInspiration(ctx, config, body)
1539
+ writeJson(res, 200, { result })
1540
+ } catch (error) {
1541
+ writeJson(res, 500, { error: (error as Error).message })
1542
+ }
1543
+ },
1544
+ }
1545
+
1546
+ // ------------------------------------------------------- idea-inspiration/market
1547
+ /** 雷达→灵感:基于市场信号/生产底座/创意简报生成开书灵感。 */
1548
+ const marketIdeaInspirationRoute: WebRoute = {
1549
+ kind: 'exact',
1550
+ path: NOVEL_API.ideaInspirationMarket,
1551
+ handler: async (req, res) => {
1552
+ if (!guard(req, res, 'POST')) return
1553
+ const config = getConfig()
1554
+ const body = await readJsonBody<{ signals?: import('./protocol.ts').MarketRadarSignal[]; foundation?: import('./protocol.ts').ProductionFoundation; brief?: import('./protocol.ts').MarketCreativeBrief; count?: number }>(req)
1555
+ if (body === undefined) {
1556
+ writeJson(res, 400, { error: '缺少市场分析参数' })
1557
+ return
1558
+ }
1559
+ try {
1560
+ const result = await runMarketIdeaInspiration(ctx, config, body)
1561
+ writeJson(res, 200, { result })
1562
+ } catch (error) {
1563
+ writeJson(res, 500, { error: (error as Error).message })
1564
+ }
1565
+ },
1566
+ }
1567
+
1568
+ // ------------------------------------------------------------- director
1569
+ /** 自动导演编排建议:基于全书上下文。 */
1570
+ const directorRoute: WebRoute = {
1571
+ kind: 'exact',
1572
+ path: NOVEL_API.director,
1573
+ handler: async (req, res) => {
1574
+ if (!guard(req, res, 'POST')) return
1575
+ const config = getConfig()
1576
+ const body = await readJsonBody<DirectorRequest & { bookId?: string }>(req)
1577
+ const outputDir = resolveOutputDir(config, body?.bookId)
1578
+ const project = loadProject(outputDir)
1579
+ if (project === undefined) {
1580
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1581
+ return
1582
+ }
1583
+ try {
1584
+ const result = await runDirectorAdvice(ctx, config, project, body ?? {})
1585
+ writeJson(res, 200, { result })
1586
+ } catch (error) {
1587
+ writeJson(res, 500, { error: (error as Error).message })
1588
+ }
1589
+ },
1590
+ }
1591
+
1592
+ // ------------------------------------------------------------- director/todos
1593
+ /** 自动导演「采纳」出的书内待办:GET 读取 / POST 增删勾选(按书路由)。 */
1594
+ const directorTodosRoute: WebRoute = {
1595
+ kind: 'exact',
1596
+ path: NOVEL_API.directorTodos,
1597
+ handler: async (req, res) => {
1598
+ type DirectorTodosReq = { op?: 'add' | 'toggle' | 'remove'; text?: string; source?: DirectorTodo['source']; id?: string; bookId?: string }
1599
+ let body: DirectorTodosReq | undefined
1600
+ if (req.method === 'POST') {
1601
+ if (!guard(req, res, 'POST')) return
1602
+ body = await readJsonBody<DirectorTodosReq>(req)
1603
+ } else {
1604
+ if (!guard(req, res, 'GET')) return
1605
+ }
1606
+ const config = getConfig()
1607
+ const outputDir = resolveOutputDir(config, body?.bookId)
1608
+ const project = loadProject(outputDir)
1609
+ if (project === undefined) {
1610
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1611
+ return
1612
+ }
1613
+ project.todos ??= []
1614
+ if (req.method === 'POST' && body !== undefined) {
1615
+ if (body.op === 'add' && (body.text ?? '').trim() !== '') {
1616
+ project.todos.unshift({ id: `td-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`, text: body.text!.trim(), source: body.source ?? 'fix', done: false, createdAt: new Date().toISOString() })
1617
+ } else if (body.op === 'toggle' && body.id !== undefined) {
1618
+ project.todos = project.todos.map(t => t.id === body.id ? { ...t, done: !t.done } : t)
1619
+ } else if (body.op === 'remove' && body.id !== undefined) {
1620
+ project.todos = project.todos.filter(t => t.id !== body.id)
1621
+ }
1622
+ project.updatedAt = new Date().toISOString()
1623
+ saveProject(outputDir, project)
1624
+ }
1625
+ writeJson(res, 200, { todos: project.todos })
1626
+ },
1627
+ }
1628
+
1629
+ // ------------------------------------------------------------- llm-live
1630
+ /** AI 创作实况:订阅 LLM 实时事件流(NDJSON;订阅时先重放最近缓冲)。 */
1631
+ const llmLiveRoute: WebRoute = {
1632
+ kind: 'exact',
1633
+ path: NOVEL_API.llmLive,
1634
+ handler: async (req, res) => {
1635
+ if (req.method !== 'GET') {
1636
+ writeJson(res, 405, { error: 'GET only' })
1637
+ return
1638
+ }
1639
+ if (!isLoopbackRequest(req)) {
1640
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1641
+ return
1642
+ }
1643
+ res.writeHead(200, {
1644
+ 'content-type': 'text/event-stream; charset=utf-8',
1645
+ 'cache-control': 'no-cache',
1646
+ 'x-accel-buffering': 'no',
1647
+ 'referrer-policy': 'no-referrer',
1648
+ })
1649
+ const unsubscribe = subscribeLiveFeed((frame) => {
1650
+ try { res.write('data: ' + JSON.stringify(frame) + '\n\n') } catch { /* client closed */ }
1651
+ })
1652
+ const hb = setInterval(() => { try { res.write(': ping\n\n') } catch { /* closed */ } }, 25000)
1653
+ // 关键:让 handler 一直挂起,直到客户端关闭,避免 WebRoute 框架在 handler 返回后关闭响应。
1654
+ await new Promise<void>((resolve) => {
1655
+ res.on('close', () => {
1656
+ clearInterval(hb)
1657
+ unsubscribe()
1658
+ resolve()
1659
+ })
1660
+ })
1661
+ },
1662
+ }
1663
+
1664
+ // ------------------------------------------------------------- bookshelf
1665
+ const bookshelfRoute: WebRoute = {
1666
+ kind: 'exact',
1667
+ path: NOVEL_API.bookshelf,
1668
+ handler: async (req, res) => {
1669
+ // GET = snapshot; POST = create book.
1670
+ if (req.method === 'GET') {
1671
+ if (!isLoopbackRequest(req)) {
1672
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1673
+ return
1674
+ }
1675
+ // 书架为空时,把 settings 默认输出目录里已有的项目播种为第一本书。
1676
+ seedBookshelfFromOutputDir(getConfig().outputDir)
1677
+ const snapshot: BookshelfSnapshot = bookshelfSnapshot(loadBookshelf())
1678
+ writeJson(res, 200, snapshot)
1679
+ return
1680
+ }
1681
+ if (req.method === 'POST') {
1682
+ if (!isLoopbackRequest(req)) {
1683
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
1684
+ return
1685
+ }
1686
+ const body = await readJsonBody<BookCreateRequest>(req)
1687
+ const bookName = body?.bookName?.trim()
1688
+ if (bookName === undefined || bookName === '') {
1689
+ writeJson(res, 400, { error: 'bookName 不能为空' })
1690
+ return
1691
+ }
1692
+ const outputDir = body?.outputDir?.trim() !== '' && body?.outputDir !== undefined
1693
+ ? body.outputDir
1694
+ : defaultOutputDirFor(bookName)
1695
+ const book = createBook(bookName, outputDir)
1696
+ // 开书向导:创建时带大纲 → 立即建立项目(书名以大纲首行为准)。
1697
+ const outline = body?.outline?.trim()
1698
+ if (outline !== undefined && outline.length >= 50) {
1699
+ const project = createProject(outline)
1700
+ saveProject(outputDir, project)
1701
+ renameBook(book.id, project.bookName)
1702
+ }
1703
+ writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
1704
+ return
1705
+ }
1706
+ writeJson(res, 405, { error: 'method not allowed (expected GET or POST)' })
1707
+ },
1708
+ }
1709
+
1710
+ // --------------------------------------------------------------- reset
1711
+ /** 重置项目:清空设定/卷/章节计划/正文/伏笔/资产/事实库(可携带新大纲)。 */
1712
+ const resetRoute: WebRoute = {
1713
+ kind: 'exact',
1714
+ path: NOVEL_API.reset,
1715
+ handler: async (req, res) => {
1716
+ if (!guard(req, res, 'POST')) return
1717
+ const config = getConfig()
1718
+ const project = loadProject(config.outputDir)
1719
+ if (project === undefined) {
1720
+ writeJson(res, 400, { error: '输出目录中没有项目,无需重置' })
1721
+ return
1722
+ }
1723
+ const body = await readJsonBody<ResetRequest>(req)
1724
+ const outline = body?.outline?.trim()
1725
+ if (outline !== undefined && outline.length >= 50) {
1726
+ project.outline = outline
1727
+ project.bookName = createProject(outline).bookName
1728
+ }
1729
+ project.bible = undefined
1730
+ project.volumes = undefined
1731
+ project.chapters = []
1732
+ project.foreshadows = []
1733
+ project.assets = emptyProjectAssets()
1734
+ project.facts = []
1735
+ project.updatedAt = new Date().toISOString()
1736
+ saveProject(config.outputDir, project)
1737
+ writeJson(res, 200, { ok: true, bookName: project.bookName })
1738
+ },
1739
+ }
1740
+
1741
+ // --------------------------------------------------- bookshelf activate
1742
+ const bookshelfActivateRoute: WebRoute = {
1743
+ kind: 'exact',
1744
+ path: '/api/dsh-novel-forge/bookshelf/activate',
1745
+ handler: async (req, res) => {
1746
+ if (!guard(req, res, 'POST')) return
1747
+ const body = await readJsonBody<BookActivateRequest>(req)
1748
+ if (body?.id === undefined || body.id === '') {
1749
+ writeJson(res, 400, { error: 'id 不能为空' })
1750
+ return
1751
+ }
1752
+ const book = activateBook(body.id)
1753
+ if (book === undefined) {
1754
+ writeJson(res, 404, { error: `书 ${body.id} 不存在` })
1755
+ return
1756
+ }
1757
+ writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
1758
+ },
1759
+ }
1760
+
1761
+ // ---------------------------------------------------- bookshelf remove
1762
+ const bookshelfRemoveRoute: WebRoute = {
1763
+ kind: 'exact',
1764
+ path: '/api/dsh-novel-forge/bookshelf/remove',
1765
+ handler: async (req, res) => {
1766
+ if (!guard(req, res, 'POST')) return
1767
+ const body = await readJsonBody<BookRemoveRequest>(req)
1768
+ if (body?.id === undefined || body.id === '') {
1769
+ writeJson(res, 400, { error: 'id 不能为空' })
1770
+ return
1771
+ }
1772
+ const removed = removeBook(body.id)
1773
+ if (!removed) {
1774
+ writeJson(res, 404, { error: `书 ${body.id} 不存在` })
1775
+ return
1776
+ }
1777
+ writeJson(res, 200, bookshelfSnapshot(loadBookshelf()))
1778
+ },
1779
+ }
1780
+
1781
+ // ------------------------------------------- bookshelf import-dir
1782
+ /** 导入已有项目目录(Mode A):校验 novel-project.json,登记/激活书架。 */
1783
+ const bookshelfImportDirRoute: WebRoute = {
1784
+ kind: 'exact',
1785
+ path: NOVEL_API.bookshelfImportDir,
1786
+ handler: async (req, res) => {
1787
+ if (!guard(req, res, 'POST')) return
1788
+ const body = await readJsonBody<BookImportDirRequest>(req)
1789
+ const outputDir = body?.outputDir?.trim()
1790
+ if (outputDir === undefined || outputDir === '') {
1791
+ writeJson(res, 400, { error: 'outputDir 不能为空' })
1792
+ return
1793
+ }
1794
+ try {
1795
+ const { book, existed } = importDir(outputDir)
1796
+ writeJson(res, 200, { book, existed })
1797
+ } catch (err) {
1798
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
1799
+ }
1800
+ },
1801
+ }
1802
+
1803
+ // ------------------------------------------- bookshelf import-text
1804
+ /** 导入 txt/md 全本(Mode B):拆章落盘建项目,登记书架。支持浏览器上传(text+fileName)与服务器本地文件(filePath)两种模式。 */
1805
+ const bookshelfImportTextRoute: WebRoute = {
1806
+ kind: 'exact',
1807
+ path: NOVEL_API.bookshelfImportText,
1808
+ handler: async (req, res) => {
1809
+ if (!guard(req, res, 'POST')) return
1810
+ const body = await readJsonBody<BookImportTextRequest>(req)
1811
+ try {
1812
+ // 模式二:浏览器上传全文内容
1813
+ if (body?.text !== undefined && body.text.length > 0) {
1814
+ const bookName = (body.fileName ?? '').replace(/\.[^.]+$/, '').trim().slice(0, 40) || '导入小说'
1815
+ const outDir = body?.outputDir?.trim() !== undefined && body.outputDir.trim() !== ''
1816
+ ? body.outputDir.trim()
1817
+ : defaultOutputDirFor(bookName)
1818
+ const result = importBookTextFromText(body.text, outDir, bookName)
1819
+ const { book } = importDir(outDir)
1820
+ writeJson(res, 200, { ...result, book })
1821
+ return
1822
+ }
1823
+ // 模式一:服务器本地文件
1824
+ const filePath = body?.filePath?.trim()
1825
+ if (filePath === undefined || filePath === '') {
1826
+ writeJson(res, 400, { error: 'filePath 不能为空(或请上传文件内容)' })
1827
+ return
1828
+ }
1829
+ if (!existsSync(filePath)) {
1830
+ writeJson(res, 400, { error: `文件不存在:${filePath}` })
1831
+ return
1832
+ }
1833
+ const bookName = basename(filePath, extname(filePath)).slice(0, 40) || '导入小说'
1834
+ const outDir = body?.outputDir?.trim() !== undefined && body.outputDir.trim() !== ''
1835
+ ? body.outputDir.trim()
1836
+ : defaultOutputDirFor(bookName)
1837
+ const result = importBookText(filePath, outDir)
1838
+ const { book } = importDir(outDir)
1839
+ writeJson(res, 200, { ...result, book })
1840
+ } catch (err) {
1841
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
1842
+ }
1843
+ },
1844
+ }
1845
+
1846
+ // --------------------------------------- bookshelf import-text preview
1847
+ /** 上传全文做拆章预览(不落盘、不登记书架)。 */
1848
+ const bookshelfImportTextPreviewRoute: WebRoute = {
1849
+ kind: 'exact',
1850
+ path: NOVEL_API.bookshelfImportTextPreview,
1851
+ handler: async (req, res) => {
1852
+ if (!guard(req, res, 'POST')) return
1853
+ const body = await readJsonBody<BookImportTextPreviewRequest>(req)
1854
+ if (body?.text === undefined || body.text.length === 0) {
1855
+ writeJson(res, 400, { error: 'text 不能为空' })
1856
+ return
1857
+ }
1858
+ try {
1859
+ const bookName = (body.fileName ?? '').replace(/\.[^.]+$/, '').trim().slice(0, 40) || '导入小说'
1860
+ const preview = previewBookText(body.text)
1861
+ writeJson(res, 200, { bookName, ...preview })
1862
+ } catch (err) {
1863
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
1864
+ }
1865
+ },
1866
+ }
1867
+
1868
+ // ---------------------------------------------------------------- audit
1869
+ /** 全书一致性质检。 */
1870
+ const auditRoute: WebRoute = {
1871
+ kind: 'exact',
1872
+ path: NOVEL_API.audit,
1873
+ handler: async (req, res) => {
1874
+ if (!guard(req, res, 'POST')) return
1875
+ const body = await readJsonBody<{ bookId?: string }>(req)
1876
+ const config0 = getConfig()
1877
+ const outputDir = resolveOutputDir(config0, body?.bookId)
1878
+ const config = { ...config0, outputDir }
1879
+ const project = loadProject(outputDir)
1880
+ if (project === undefined) {
1881
+ writeJson(res, 400, { error: '输出目录中没有项目' })
1882
+ return
1883
+ }
1884
+ const startedAt = new Date().toISOString()
1885
+ auditState = { status: 'running', startedAt, totalBatches: 0, completedBatches: 0 }
1886
+ try {
1887
+ const issues = await auditBook(ctx, config, project, config.outputDir, (completed, total) => {
1888
+ auditState.totalBatches = total
1889
+ auditState.completedBatches = completed
1890
+ })
1891
+ const auditedChapters = project.chapters.filter(c => c.status !== 'pending' && c.status !== 'generating').length
1892
+ auditState = {
1893
+ status: 'done',
1894
+ startedAt,
1895
+ finishedAt: new Date().toISOString(),
1896
+ totalBatches: auditState.totalBatches,
1897
+ completedBatches: auditState.totalBatches,
1898
+ auditedChapters,
1899
+ issuesCount: issues.length,
1900
+ issues,
1901
+ }
1902
+ const response: AuditResponse = {
1903
+ issues,
1904
+ auditedChapters,
1905
+ auditedAt: auditState.finishedAt!,
1906
+ model: config.auditModel || config.model,
1907
+ }
1908
+ writeJson(res, 200, response)
1909
+ } catch (error) {
1910
+ auditState = {
1911
+ ...auditState,
1912
+ status: 'error',
1913
+ finishedAt: new Date().toISOString(),
1914
+ error: (error as Error).message,
1915
+ }
1916
+ writeJson(res, 500, { error: (error as Error).message })
1917
+ }
1918
+ },
1919
+ }
1920
+
1921
+ // ----------------------------------------------------- characters refresh
1922
+ /** 角色卡刷新(出场统计精确化 + LLM 聚合状态)。 */
1923
+ const charactersRefreshRoute: WebRoute = {
1924
+ kind: 'exact',
1925
+ path: NOVEL_API.charactersRefresh,
1926
+ handler: async (req, res) => {
1927
+ if (!guard(req, res, 'POST')) return
1928
+ const config = getConfig()
1929
+ const project = requireProject(res)
1930
+ if (project === undefined) return
1931
+ try {
1932
+ const cards = await refreshCharacters(ctx, config, project, config.outputDir)
1933
+ // 存档:人物志聚合结果落盘,下次打开直接显示,无需重新计算。
1934
+ project.roleStatus = cards
1935
+ project.updatedAt = new Date().toISOString()
1936
+ saveProject(config.outputDir, project)
1937
+ writeJson(res, 200, { cards })
1938
+ } catch (error) {
1939
+ writeJson(res, 500, { error: (error as Error).message })
1940
+ }
1941
+ },
1942
+ }
1943
+
1944
+ // ------------------------------------------------------- facts backfill
1945
+ /** 事实库回填:对历史已生成章节批量抽取事实。 */
1946
+ const factsBackfillRoute: WebRoute = {
1947
+ kind: 'exact',
1948
+ path: NOVEL_API.factsBackfill,
1949
+ handler: async (req, res) => {
1950
+ if (!guard(req, res, 'POST')) return
1951
+ const config = getConfig()
1952
+ const project = requireProject(res)
1953
+ if (project === undefined) return
1954
+ try {
1955
+ const filled = await backfillFacts(ctx, config, project, config.outputDir)
1956
+ writeJson(res, 200, { ok: true, filled })
1957
+ } catch (error) {
1958
+ writeJson(res, 500, { error: (error as Error).message })
1959
+ }
1960
+ },
1961
+ }
1962
+
1963
+ // ---------------------------------------------------------- bible patch
1964
+ /** 道藏局部修补(世界观规则/红线/风格)。 */
1965
+ const biblePatchRoute: WebRoute = {
1966
+ kind: 'exact',
1967
+ path: NOVEL_API.biblePatch,
1968
+ handler: async (req, res) => {
1969
+ if (!guard(req, res, 'POST')) return
1970
+ const config = getConfig()
1971
+ const project = requireProject(res)
1972
+ if (project === undefined) return
1973
+ if (project.bible === undefined) {
1974
+ writeJson(res, 400, { error: '尚未生成道藏,请先生成' })
1975
+ return
1976
+ }
1977
+ const body = await readJsonBody<BiblePatchRequest>(req)
1978
+ if (Array.isArray(body?.worldRules)) project.bible.worldRules = body.worldRules.filter(r => r.trim() !== '')
1979
+ if (Array.isArray(body?.redLines)) project.bible.redLines = body.redLines.filter(r => r.trim() !== '')
1980
+ if (Array.isArray(body?.style)) project.bible.style = body.style.filter(r => r.trim() !== '')
1981
+ if (Array.isArray(body?.characters)) {
1982
+ project.bible.characters = body.characters
1983
+ .filter(c => c !== undefined && c !== null && typeof c.name === 'string' && c.name.trim() !== '')
1984
+ .map(c => ({
1985
+ name: c.name.trim(),
1986
+ role: (['protagonist', 'supporting', 'antagonist', 'other'] as const).includes(c.role as never)
1987
+ ? c.role as StoryBible['characters'][number]['role']
1988
+ : 'other',
1989
+ traits: Array.isArray(c.traits) ? c.traits.filter((t): t is string => typeof t === 'string' && t.trim() !== '') : [],
1990
+ goals: typeof c.goals === 'string' ? c.goals : '',
1991
+ relations: typeof c.relations === 'string' ? c.relations : '',
1992
+ knowledge: Array.isArray(c.knowledge)
1993
+ ? c.knowledge.filter((k): k is string => typeof k === 'string' && k.trim() !== '')
1994
+ : undefined,
1995
+ }))
1996
+ }
1997
+ project.updatedAt = new Date().toISOString()
1998
+ saveProject(config.outputDir, project)
1999
+ writeJson(res, 200, { bible: project.bible })
2000
+ },
2001
+ }
2002
+
2003
+ // ---------------------------------------------------------------- blurb
2004
+ /** 小说简介:生成/补全,或手动保存。 */
2005
+ const blurbRoute: WebRoute = {
2006
+ kind: 'exact',
2007
+ path: NOVEL_API.blurb,
2008
+ handler: async (req, res) => {
2009
+ if (!guard(req, res, 'POST')) return
2010
+ const config = getConfig()
2011
+ const project = requireProject(res)
2012
+ if (project === undefined) return
2013
+ const body = await readJsonBody<BlurbRequest>(req)
2014
+ try {
2015
+ if (body?.action === 'save') {
2016
+ const text = body.text?.trim() ?? ''
2017
+ project.blurb = text
2018
+ project.updatedAt = new Date().toISOString()
2019
+ saveProject(config.outputDir, project)
2020
+ writeJson(res, 200, { blurb: text })
2021
+ return
2022
+ }
2023
+ const partial = body?.partial?.trim() ?? ''
2024
+ const blurb = await generateBlurb(ctx, config, project, partial)
2025
+ project.blurb = blurb
2026
+ project.updatedAt = new Date().toISOString()
2027
+ saveProject(config.outputDir, project)
2028
+ writeJson(res, 200, { blurb })
2029
+ } catch (error) {
2030
+ writeJson(res, 500, { error: (error as Error).message })
2031
+ }
2032
+ },
2033
+ }
2034
+
2035
+ // ---------------------------------------------------------------- cover
2036
+ /** 封面:GET 读取(dataUrl);POST 上传(base64)或移除。 */
2037
+ const coverRoute: WebRoute = {
2038
+ kind: 'exact',
2039
+ path: NOVEL_API.cover,
2040
+ handler: async (req, res) => {
2041
+ const config = getConfig()
2042
+ if (req.method === 'GET') {
2043
+ if (!isLoopbackRequest(req)) {
2044
+ writeJson(res, 403, { error: 'forbidden: loopback-only' })
2045
+ return
2046
+ }
2047
+ // 书架页按书读取:?dir=<输出目录>;省略时用当前激活书目录。
2048
+ const url = new URL(req.url ?? '/', 'http://localhost')
2049
+ const dirParam = url.searchParams.get('dir')
2050
+ const targetDir = dirParam !== null && dirParam !== '' ? dirParam : config.outputDir
2051
+ const project = loadProject(targetDir)
2052
+ const coverPath = project?.coverPath
2053
+ if (coverPath === undefined || coverPath === '') {
2054
+ writeJson(res, 200, { dataUrl: null } satisfies CoverResponse)
2055
+ return
2056
+ }
2057
+ const file = join(targetDir, coverPath)
2058
+ if (!existsSync(file)) {
2059
+ writeJson(res, 200, { dataUrl: null } satisfies CoverResponse)
2060
+ return
2061
+ }
2062
+ const mime = coverPath.toLowerCase().endsWith('.png') ? 'image/png'
2063
+ : coverPath.toLowerCase().endsWith('.jpg') || coverPath.toLowerCase().endsWith('.jpeg') ? 'image/jpeg'
2064
+ : coverPath.toLowerCase().endsWith('.webp') ? 'image/webp'
2065
+ : 'image/png'
2066
+ const dataUrl = `data:${mime};base64,${readFileSync(file).toString('base64')}`
2067
+ writeJson(res, 200, { dataUrl } satisfies CoverResponse)
2068
+ return
2069
+ }
2070
+ if (req.method === 'POST') {
2071
+ if (!guard(req, res, 'POST')) return
2072
+ const project = requireProject(res)
2073
+ if (project === undefined) return
2074
+ const body = await readJsonBody<CoverRequest>(req)
2075
+ try {
2076
+ if (body?.action === 'remove') {
2077
+ if (project.coverPath !== undefined && project.coverPath !== '') {
2078
+ const oldFile = join(config.outputDir, project.coverPath)
2079
+ if (existsSync(oldFile)) rmSync(oldFile, { force: true })
2080
+ }
2081
+ project.coverPath = undefined
2082
+ project.updatedAt = new Date().toISOString()
2083
+ saveProject(config.outputDir, project)
2084
+ writeJson(res, 200, { ok: true, coverPath: null })
2085
+ return
2086
+ }
2087
+ const dataUrl = body?.dataUrl ?? ''
2088
+ const match = /^data:(image\/(?:png|jpeg|jpg|webp));base64,(.+)$/s.exec(dataUrl)
2089
+ if (match === null) {
2090
+ writeJson(res, 400, { error: '封面须为 PNG/JPEG/WebP 的 base64 data URL' })
2091
+ return
2092
+ }
2093
+ const mime = match[1]!
2094
+ const ext = mime === 'image/png' ? 'png' : mime === 'image/webp' ? 'webp' : 'jpg'
2095
+ const fileName = `cover.${ext}`
2096
+ const targetPath = join(config.outputDir, fileName)
2097
+ const oldPath = project.coverPath
2098
+ mkdirSync(config.outputDir, { recursive: true })
2099
+ writeFileSync(targetPath, Buffer.from(match[2]!, 'base64'))
2100
+ if (oldPath !== undefined && oldPath !== '' && oldPath !== fileName) {
2101
+ const oldFile = join(config.outputDir, oldPath)
2102
+ if (existsSync(oldFile)) rmSync(oldFile, { force: true })
2103
+ }
2104
+ project.coverPath = fileName
2105
+ project.updatedAt = new Date().toISOString()
2106
+ saveProject(config.outputDir, project)
2107
+ writeJson(res, 200, { ok: true, coverPath: fileName })
2108
+ } catch (error) {
2109
+ writeJson(res, 500, { error: (error as Error).message })
2110
+ }
2111
+ return
2112
+ }
2113
+ writeJson(res, 405, { error: 'method not allowed (expected GET or POST)' })
2114
+ },
2115
+ }
2116
+
2117
+ // ---------------------------------------------------------------- world
2118
+ /** 大世界:提炼或手动保存(境界体系/区域/势力)。 */
2119
+ const worldRoute: WebRoute = {
2120
+ kind: 'exact',
2121
+ path: NOVEL_API.world,
2122
+ handler: async (req, res) => {
2123
+ if (!guard(req, res, 'POST')) return
2124
+ const config = getConfig()
2125
+ const project = requireProject(res)
2126
+ if (project === undefined) return
2127
+ const body = await readJsonBody<WorldRequest>(req)
2128
+ try {
2129
+ if (body?.action === 'save' && body.world !== undefined) {
2130
+ project.world = {
2131
+ realms: Array.isArray(body.world.realms) ? body.world.realms : [],
2132
+ regions: Array.isArray(body.world.regions) ? body.world.regions : [],
2133
+ factions: Array.isArray(body.world.factions) ? body.world.factions : [],
2134
+ }
2135
+ project.updatedAt = new Date().toISOString()
2136
+ saveProject(config.outputDir, project)
2137
+ writeJson(res, 200, { world: project.world })
2138
+ return
2139
+ }
2140
+ const world = await extractWorld(ctx, config, project)
2141
+ project.world = world
2142
+ project.updatedAt = new Date().toISOString()
2143
+ saveProject(config.outputDir, project)
2144
+ writeJson(res, 200, { world })
2145
+ } catch (error) {
2146
+ writeJson(res, 500, { error: (error as Error).message })
2147
+ }
2148
+ },
2149
+ }
2150
+
2151
+ // --------------------------------------------------------------- rename
2152
+ /** 重命名当前书:同步项目 bookName 与书架条目。 */
2153
+ const renameRoute: WebRoute = {
2154
+ kind: 'exact',
2155
+ path: NOVEL_API.rename,
2156
+ handler: async (req, res) => {
2157
+ if (!guard(req, res, 'POST')) return
2158
+ const config = getConfig()
2159
+ const project = requireProject(res)
2160
+ if (project === undefined) return
2161
+ const body = await readJsonBody<RenameRequest>(req)
2162
+ const bookName = body?.bookName?.trim()
2163
+ if (bookName === undefined || bookName === '') {
2164
+ writeJson(res, 400, { error: '书名不能为空' })
2165
+ return
2166
+ }
2167
+ project.bookName = bookName.slice(0, 60)
2168
+ project.updatedAt = new Date().toISOString()
2169
+ saveProject(config.outputDir, project)
2170
+ const store = loadBookshelf()
2171
+ if (store.activeBookId !== null) renameBook(store.activeBookId, project.bookName)
2172
+ writeJson(res, 200, { bookName: project.bookName })
2173
+ },
2174
+ }
2175
+
2176
+ // ------------------------------------------------------------- plotlines
2177
+ /** 剧情线管理:增删改 + 关联章节(主线/支线/人物线/悬念线)。 */
2178
+ const plotlinesRoute: WebRoute = {
2179
+ kind: 'exact',
2180
+ path: NOVEL_API.plotlines,
2181
+ handler: async (req, res) => {
2182
+ if (!guard(req, res, 'POST')) return
2183
+ const config = getConfig()
2184
+ const project = requireProject(res)
2185
+ if (project === undefined) return
2186
+ const body = await readJsonBody<PlotlinesRequest>(req)
2187
+ if (project.plotlines === undefined) project.plotlines = []
2188
+ const op = body?.op
2189
+ if (op === 'add' && body?.line !== undefined) {
2190
+ const line = body.line
2191
+ project.plotlines.push({
2192
+ id: line.id !== '' ? line.id : `pl-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
2193
+ name: line.name.slice(0, 40),
2194
+ kind: line.kind,
2195
+ goal: line.goal.slice(0, 300),
2196
+ progress: line.progress.slice(0, 300),
2197
+ status: line.status,
2198
+ chapters: Array.isArray(line.chapters) ? line.chapters.filter((n): n is number => typeof n === 'number') : [],
2199
+ createdAt: line.createdAt !== '' ? line.createdAt : new Date().toISOString(),
2200
+ })
2201
+ } else if (op === 'update' && body?.line !== undefined && body.line.id !== '') {
2202
+ const idx = project.plotlines.findIndex(l => l.id === body.line!.id)
2203
+ if (idx !== -1) {
2204
+ const line = body.line
2205
+ project.plotlines[idx] = {
2206
+ ...project.plotlines[idx]!,
2207
+ name: line.name.slice(0, 40),
2208
+ kind: line.kind,
2209
+ goal: line.goal.slice(0, 300),
2210
+ progress: line.progress.slice(0, 300),
2211
+ status: line.status,
2212
+ }
2213
+ }
2214
+ } else if (op === 'remove' && body?.id !== undefined) {
2215
+ project.plotlines = project.plotlines.filter(l => l.id !== body.id)
2216
+ } else if (op === 'link' && body?.id !== undefined && typeof body.chapterNo === 'number' && body.chapterNo > 0) {
2217
+ const line = project.plotlines.find(l => l.id === body.id)
2218
+ if (line !== undefined && !line.chapters.includes(body.chapterNo)) {
2219
+ line.chapters.push(body.chapterNo)
2220
+ if (line.status === 'active' && line.progress === '') {
2221
+ line.progress = `推进至第 ${body.chapterNo} 章`
2222
+ }
2223
+ }
2224
+ } else if (op === 'suggest') {
2225
+ try {
2226
+ const suggestions = await suggestPlotlines(ctx, config, project)
2227
+ writeJson(res, 200, { plotlines: project.plotlines, suggestions } satisfies PlotlinesResponse)
2228
+ return
2229
+ } catch (error) {
2230
+ writeJson(res, 500, { error: `建议失败:${(error as Error).message}` })
2231
+ return
2232
+ }
2233
+ } else if (op === 'refresh' && body?.id !== undefined) {
2234
+ const line = project.plotlines.find(l => l.id === body.id)
2235
+ if (line === undefined) {
2236
+ writeJson(res, 404, { error: '剧情线不存在' })
2237
+ return
2238
+ }
2239
+ try {
2240
+ const progress = await refreshPlotlineProgress(ctx, config, project, line)
2241
+ line.progress = progress
2242
+ project.updatedAt = new Date().toISOString()
2243
+ saveProject(config.outputDir, project)
2244
+ writeJson(res, 200, { plotlines: project.plotlines } satisfies PlotlinesResponse)
2245
+ return
2246
+ } catch (error) {
2247
+ writeJson(res, 500, { error: `刷新进度失败:${(error as Error).message}` })
2248
+ return
2249
+ }
2250
+ } else if (op === 'health') {
2251
+ try {
2252
+ const health = await analyzePlotlineHealth(ctx, config, project)
2253
+ writeJson(res, 200, { plotlines: project.plotlines, health } satisfies PlotlinesResponse)
2254
+ return
2255
+ } catch (error) {
2256
+ writeJson(res, 500, { error: `健康检查失败:${(error as Error).message}` })
2257
+ return
2258
+ }
2259
+ } else if (op === 'plan') {
2260
+ try {
2261
+ const health = await analyzePlotlineHealth(ctx, config, project)
2262
+ const plan = await designPlotlinePlan(ctx, config, project, health)
2263
+ writeJson(res, 200, { plotlines: project.plotlines, health, plan } satisfies PlotlinesResponse)
2264
+ return
2265
+ } catch (error) {
2266
+ writeJson(res, 500, { error: `剧情方案生成失败:${(error as Error).message}` })
2267
+ return
2268
+ }
2269
+ }
2270
+ project.updatedAt = new Date().toISOString()
2271
+ saveProject(config.outputDir, project)
2272
+ const response: PlotlinesResponse = { plotlines: project.plotlines }
2273
+ writeJson(res, 200, response)
2274
+ },
2275
+ }
2276
+
2277
+ // --------------------------------------------------------- sensitive
2278
+ /** 敏感词检查:指定章节 / 任意文本 / 全书已写章节。 */
2279
+ const sensitiveRoute: WebRoute = {
2280
+ kind: 'exact',
2281
+ path: NOVEL_API.sensitiveCheck,
2282
+ handler: async (req, res) => {
2283
+ if (!guard(req, res, 'POST')) return
2284
+ const config = getConfig()
2285
+ const project = requireProject(res)
2286
+ if (project === undefined) return
2287
+ const body = await readJsonBody<SensitiveCheckRequest>(req)
2288
+ const hits: SensitiveHit[] = []
2289
+ let scanned = 0
2290
+ if (body?.text !== undefined) {
2291
+ for (const hit of checkSensitiveText(body.text)) {
2292
+ hits.push({ chapterNo: 0, word: hit.word, category: hit.category, count: hit.count })
2293
+ }
2294
+ } else if (typeof body?.chapterNo === 'number') {
2295
+ const chapter = project.chapters.find(c => c.no === body.chapterNo)
2296
+ if (chapter !== undefined) {
2297
+ const text = readChapterFile(config.outputDir, chapter)
2298
+ if (text !== undefined) {
2299
+ scanned = 1
2300
+ for (const hit of checkSensitiveText(text)) {
2301
+ hits.push({ chapterNo: chapter.no, word: hit.word, category: hit.category, count: hit.count })
2302
+ }
2303
+ }
2304
+ }
2305
+ } else if (body?.all === true) {
2306
+ for (const chapter of project.chapters) {
2307
+ if (chapter.status === 'pending' || chapter.status === 'generating') continue
2308
+ const text = readChapterFile(config.outputDir, chapter)
2309
+ if (text === undefined) continue
2310
+ scanned++
2311
+ for (const hit of checkSensitiveText(text)) {
2312
+ hits.push({ chapterNo: chapter.no, word: hit.word, category: hit.category, count: hit.count })
2313
+ }
2314
+ }
2315
+ } else {
2316
+ writeJson(res, 400, { error: '请提供 chapterNo / text / all 之一' })
2317
+ return
2318
+ }
2319
+ const response: SensitiveCheckResponse = { hits, scannedChapters: scanned }
2320
+ writeJson(res, 200, response)
2321
+ },
2322
+ }
2323
+
2324
+ // ---------------------------------------------------------------- roles
2325
+ /** 角色库:提炼 / 采纳 / 更新 / 删除。 */
2326
+ const rolesRoute: WebRoute = {
2327
+ kind: 'exact',
2328
+ path: NOVEL_API.roles,
2329
+ handler: async (req, res) => {
2330
+ if (!guard(req, res, 'POST')) return
2331
+ const config = getConfig()
2332
+ const project = requireProject(res)
2333
+ if (project === undefined) return
2334
+ const body = await readJsonBody<RolesRequest>(req)
2335
+ if (project.roles === undefined) project.roles = []
2336
+ const op = body?.op
2337
+ if (op === 'extract') {
2338
+ try {
2339
+ const candidates = await extractRoles(ctx, config, project)
2340
+ writeJson(res, 200, { roles: project.roles, candidates } satisfies RolesResponse)
2341
+ return
2342
+ } catch (error) {
2343
+ writeJson(res, 500, { error: `角色提炼失败:${(error as Error).message}` })
2344
+ return
2345
+ }
2346
+ } else if ((op === 'adopt' || op === 'update') && body?.role !== undefined) {
2347
+ const r = body.role
2348
+ const idx = project.roles.findIndex(x => x.name === r.name)
2349
+ if (idx === -1) project.roles.push(r)
2350
+ else project.roles[idx] = r
2351
+ } else if (op === 'remove' && body?.name !== undefined) {
2352
+ project.roles = project.roles.filter(x => x.name !== body.name)
2353
+ } else {
2354
+ writeJson(res, 400, { error: '未知的 roles op' })
2355
+ return
2356
+ }
2357
+ project.updatedAt = new Date().toISOString()
2358
+ saveProject(config.outputDir, project)
2359
+ const response: RolesResponse = { roles: project.roles }
2360
+ writeJson(res, 200, response)
2361
+ },
2362
+ }
2363
+
2364
+ // ------------------------------------------------------- chapter reset
2365
+ /** 章节复位:generating 卡死 → pending(可重新生成)。 */
2366
+ const chapterResetRoute: WebRoute = {
2367
+ kind: 'exact',
2368
+ path: NOVEL_API.chapterReset,
2369
+ handler: async (req, res) => {
2370
+ if (!guard(req, res, 'POST')) return
2371
+ const config = getConfig()
2372
+ const project = requireProject(res)
2373
+ if (project === undefined) return
2374
+ const body = await readJsonBody<{ chapterNo?: number }>(req)
2375
+ const no = body?.chapterNo
2376
+ if (!Number.isInteger(no) || no === undefined || no < 1) {
2377
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
2378
+ return
2379
+ }
2380
+ const chapter = project.chapters.find(c => c.no === no)
2381
+ if (chapter === undefined) {
2382
+ writeJson(res, 404, { error: `章节 ${no} 不在计划中` })
2383
+ return
2384
+ }
2385
+ chapter.status = 'pending'
2386
+ chapter.error = undefined
2387
+ chapter.generatingAt = undefined
2388
+ project.updatedAt = new Date().toISOString()
2389
+ saveProject(config.outputDir, project)
2390
+ writeJson(res, 200, { ok: true, no })
2391
+ },
2392
+ }
2393
+
2394
+ // ------------------------------------------------------ chapter approve
2395
+ /** 章节直接通过:作者行使最终决定权(不重审,保留审稿记录)。 */
2396
+ const chapterApproveRoute: WebRoute = {
2397
+ kind: 'exact',
2398
+ path: NOVEL_API.chapterApprove,
2399
+ handler: async (req, res) => {
2400
+ if (!guard(req, res, 'POST')) return
2401
+ const config = getConfig()
2402
+ const project = requireProject(res)
2403
+ if (project === undefined) return
2404
+ const body = await readJsonBody<{ chapterNo?: number }>(req)
2405
+ const no = body?.chapterNo
2406
+ if (!Number.isInteger(no) || no === undefined || no < 1) {
2407
+ writeJson(res, 400, { error: 'chapterNo 须为正整数' })
2408
+ return
2409
+ }
2410
+ const chapter = project.chapters.find(c => c.no === no)
2411
+ if (chapter === undefined) {
2412
+ writeJson(res, 404, { error: `章节 ${no} 不在计划中` })
2413
+ return
2414
+ }
2415
+ chapter.status = 'approved'
2416
+ project.updatedAt = new Date().toISOString()
2417
+ saveProject(config.outputDir, project)
2418
+ writeJson(res, 200, { ok: true, no })
2419
+ },
2420
+ }
2421
+
2422
+ // ------------------------------------------------------ author review backfill
2423
+ /** 作者复盘补跑:对已写章节补齐 authorReview(body.chapterNo=单章 JSON,缺省=全书 NDJSON 流)。 */
2424
+ const reviewBackfillRoute: WebRoute = {
2425
+ kind: 'exact',
2426
+ path: NOVEL_API.reviewBackfill,
2427
+ handler: async (req, res) => {
2428
+ if (!guard(req, res, 'POST')) return
2429
+ const config = getConfig()
2430
+ const project = requireProject(res)
2431
+ if (project === undefined) return
2432
+ const body = await readJsonBody<{ chapterNo?: number }>(req)
2433
+
2434
+ /** 对一章执行作者复盘(读取已落盘正文,不改变章节状态/正文)。 */
2435
+ const runOne = async (chapter: ChapterPlan): Promise<AuthorReview> => {
2436
+ const currentBody = readChapterFile(config.outputDir, chapter)
2437
+ if (currentBody === undefined) throw new Error(`章节 ${chapter.no} 的正文文件不存在`)
2438
+ let prevTail = ''
2439
+ if (chapter.no > 1) {
2440
+ const prev = project.chapters.find(c => c.no === chapter.no - 1)
2441
+ if (prev !== undefined) {
2442
+ prevTail = (readChapterFile(config.outputDir, prev) ?? '').replace(/^#.*$/m, '').trim().slice(-600)
2443
+ }
2444
+ }
2445
+ return authorReviewChapter(ctx, config, project, chapter.no, currentBody, prevTail)
2446
+ }
2447
+
2448
+ // 单章:JSON 响应。
2449
+ if (typeof body?.chapterNo === 'number' && body.chapterNo > 0) {
2450
+ const chapter = project.chapters.find(c => c.no === body.chapterNo)
2451
+ if (chapter === undefined) {
2452
+ writeJson(res, 404, { error: `章节 ${body.chapterNo} 不在计划中` })
2453
+ return
2454
+ }
2455
+ if (chapter.status === 'pending') {
2456
+ writeJson(res, 400, { error: '该章尚未生成正文,无法复盘' })
2457
+ return
2458
+ }
2459
+ try {
2460
+ const review = await runOne(chapter)
2461
+ chapter.authorReview = review
2462
+ if (review.advancedLines !== undefined) {
2463
+ autoLinkPlotlines(project, chapter.no, review.advancedLines)
2464
+ }
2465
+ project.updatedAt = new Date().toISOString()
2466
+ saveProject(config.outputDir, project)
2467
+ writeJson(res, 200, { no: chapter.no, review } satisfies { no: number; review: AuthorReview })
2468
+ return
2469
+ } catch (error) {
2470
+ writeJson(res, 500, { error: (error as Error).message })
2471
+ return
2472
+ }
2473
+ }
2474
+
2475
+ // 全书:NDJSON 流式补跑缺失复盘的已写章节。
2476
+ const missing = project.chapters.filter(c => c.status !== 'pending' && c.status !== 'generating' && c.status !== 'error' && c.authorReview === undefined)
2477
+ if (missing.length === 0) {
2478
+ writeJson(res, 200, { count: 0 })
2479
+ return
2480
+ }
2481
+ res.writeHead(200, {
2482
+ 'content-type': 'application/x-ndjson; charset=utf-8',
2483
+ 'cache-control': 'no-cache',
2484
+ 'referrer-policy': 'no-referrer',
2485
+ })
2486
+ const send = (frame: JobFrame): void => {
2487
+ res.write(JSON.stringify(frame) + '\n')
2488
+ }
2489
+ let done = 0
2490
+ for (const chapter of missing) {
2491
+ try {
2492
+ const review = await runOne(chapter)
2493
+ chapter.authorReview = review
2494
+ if (review.advancedLines !== undefined) {
2495
+ autoLinkPlotlines(project, chapter.no, review.advancedLines)
2496
+ }
2497
+ done++
2498
+ saveProject(config.outputDir, project)
2499
+ send({ type: 'author-review', no: chapter.no, review })
2500
+ } catch (error) {
2501
+ console.warn(`[dsh-novel-forge] author backfill ch.${chapter.no} failed:`, (error as Error).message)
2502
+ }
2503
+ }
2504
+ project.updatedAt = new Date().toISOString()
2505
+ saveProject(config.outputDir, project)
2506
+ send({ type: 'author-backfill-done', count: done })
2507
+ res.end()
2508
+ },
2509
+ }
2510
+
2511
+ // --------------------------------------------------------------- config
2512
+ const configRoute: WebRoute = {
2513
+ kind: 'exact',
2514
+ path: NOVEL_API.config,
2515
+ handler: async (req, res) => {
2516
+ if (!guard(req, res, 'POST')) return
2517
+ const body = await readJsonBody<ConfigPatch>(req)
2518
+ if (body === undefined) {
2519
+ writeJson(res, 400, { error: '无效的配置 JSON' })
2520
+ return
2521
+ }
2522
+ try {
2523
+ const next = await patchConfig(body)
2524
+ writeJson(res, 200, { config: next })
2525
+ } catch (error) {
2526
+ writeJson(res, 400, { error: (error as Error).message })
2527
+ }
2528
+ },
2529
+ }
2530
+
2531
+ // ---------------------------------------------------------- open-folder
2532
+ const openFolderRoute: WebRoute = {
2533
+ kind: 'exact',
2534
+ path: NOVEL_API.openFolder,
2535
+ handler: async (req, res) => {
2536
+ if (!guard(req, res, 'POST')) return
2537
+ const config = getConfig()
2538
+ const dir = config.outputDir
2539
+ const child = spawn('explorer', [dir], { shell: false })
2540
+ let responded = false
2541
+ child.on('error', (error) => {
2542
+ if (responded) return
2543
+ responded = true
2544
+ writeJson(res, 500, { ok: false, error: error.message })
2545
+ })
2546
+ child.on('exit', (code) => {
2547
+ if (responded) return
2548
+ responded = true
2549
+ if (code === 0) writeJson(res, 200, { ok: true })
2550
+ else writeJson(res, 500, { ok: false, error: `explorer 退出码 ${code}` })
2551
+ })
2552
+ },
2553
+ }
2554
+
2555
+ // ---------------------------------------------------------- plugin update
2556
+ /** 插件自更新:在 DSH profile 目录拉取最新 npm 版(仅下载,需重启 DSH 生效)。 */
2557
+ const pluginUpdateRoute: WebRoute = {
2558
+ kind: 'exact',
2559
+ path: NOVEL_API.pluginUpdate,
2560
+ handler: async (req, res) => {
2561
+ if (!guard(req, res, 'POST')) return
2562
+ const profileDir = join(homedir(), '.dsh', 'profiles', 'web')
2563
+ const response: PluginUpdateResponse = await new Promise((resolve) => {
2564
+ const child = spawn('pnpm', ['add', '@waterwx/dsh-novel-forge@latest'], { cwd: profileDir, shell: true })
2565
+ let acc = ''
2566
+ child.stdout.on('data', (d: Buffer) => { acc += String(d) })
2567
+ child.stderr.on('data', (d: Buffer) => { acc += String(d) })
2568
+ child.on('error', (error) => resolve({ ok: false, message: '无法执行更新:' + error.message }))
2569
+ child.on('close', (code) => {
2570
+ if (code === 0) resolve({ ok: true, message: '已更新到最新版本,请重启 DSH 生效。' })
2571
+ else resolve({ ok: false, message: '更新失败(退出码 ' + code + '):' + acc.slice(-400) })
2572
+ })
2573
+ })
2574
+ writeJson(res, 200, response)
2575
+ },
2576
+ }
2577
+
2578
+ // ------------------------------------------------------- outline suggest
2579
+ /** 开书想法 → AI 大纲:2-3 个可选方案(支持暂留换批:count 只补空槽 + exclude 避开已留方向)。 */
2580
+ const outlineSuggestRoute: WebRoute = {
2581
+ kind: 'exact',
2582
+ path: NOVEL_API.outlineSuggest,
2583
+ handler: async (req, res) => {
2584
+ if (!guard(req, res, 'POST')) return
2585
+ const config = getConfig()
2586
+ const body = await readJsonBody<OutlineSuggestRequest>(req)
2587
+ const idea = body?.idea?.trim() ?? ''
2588
+ if (idea.length < 50) {
2589
+ writeJson(res, 400, { error: '想法太短(<50 字),请多写一两句:主角是谁、什么世界、想要什么爽点' })
2590
+ return
2591
+ }
2592
+ const count = body?.count !== undefined ? Math.max(1, Math.min(3, Math.floor(body.count))) : 3
2593
+ const exclude = Array.isArray(body?.exclude) ? body.exclude.filter((e): e is string => typeof e === 'string' && e.trim() !== '').map(e => e.trim().slice(0, 200)) : []
2594
+ try {
2595
+ const candidates = await suggestOutlines(ctx, config, idea, count, exclude)
2596
+ const response: OutlineSuggestResponse = { candidates }
2597
+ writeJson(res, 200, response)
2598
+ } catch (error) {
2599
+ writeJson(res, 500, { error: `大纲方案生成失败:${(error as Error).message}` })
2600
+ }
2601
+ },
2602
+ }
2603
+
2604
+ // ------------------------------------------------- outline reverse
2605
+ /** 反推大纲:从已写章节正文反向生成全书总纲(NDJSON 流式进度)。 */
2606
+ const outlineReverseRoute: WebRoute = {
2607
+ kind: 'exact',
2608
+ path: NOVEL_API.outlineReverse,
2609
+ handler: async (req, res) => {
2610
+ if (!guard(req, res, 'POST')) return
2611
+ const config = getConfig()
2612
+ const project = requireProject(res)
2613
+ if (project === undefined) return
2614
+ res.writeHead(200, {
2615
+ 'content-type': 'application/x-ndjson; charset=utf-8',
2616
+ 'cache-control': 'no-cache',
2617
+ 'x-accel-buffering': 'no',
2618
+ 'referrer-policy': 'no-referrer',
2619
+ })
2620
+ const send = (frame: JobFrame): void => {
2621
+ res.write(JSON.stringify(frame) + '\n')
2622
+ }
2623
+ try {
2624
+ const outline = await reverseOutlineFromChapters(ctx, config, project, config.outputDir, (done, total, phase) => {
2625
+ send({ type: 'outline-progress', done, total, phase })
2626
+ })
2627
+ // 保存总纲(仅更新文本,不动书名/进度)。
2628
+ project.outline = outline
2629
+ project.updatedAt = new Date().toISOString()
2630
+ saveProject(config.outputDir, project)
2631
+ send({ type: 'outline-done', outline, chars: outline.length })
2632
+ } catch (error) {
2633
+ send({ type: 'error', no: 0, message: (error as Error).message })
2634
+ } finally {
2635
+ res.end()
2636
+ }
2637
+ },
2638
+ }
2639
+
2640
+ // ------------------------------------------------------------- llm-test
2641
+ /** LLM 连通性测试:对选中的提供商/模型发一次最小真实调用。 */
2642
+ const llmTestRoute: WebRoute = {
2643
+ kind: 'exact',
2644
+ path: NOVEL_API.llmTest,
2645
+ handler: async (req, res) => {
2646
+ if (!guard(req, res, 'POST')) return
2647
+ const body = await readJsonBody<LlmTestRequest>(req)
2648
+ const provider = (body?.provider ?? '').trim()
2649
+ const model = (body?.model ?? '').trim()
2650
+ if (provider === '' || model === '') {
2651
+ writeJson(res, 400, { error: 'provider 与 model 必填' })
2652
+ return
2653
+ }
2654
+ const result = await testLlmModel(ctx, provider, model)
2655
+ writeJson(res, 200, result satisfies LlmTestResponse)
2656
+ },
2657
+ }
2658
+
2659
+ // ------------------------------------------------------------- llm-add
2660
+ /** 添加模型:厂商直填 API Key,或自定义 OpenAI 兼容路由(写 DSH 凭据 + router)。 */
2661
+ const addModelRoute: WebRoute = {
2662
+ kind: 'exact',
2663
+ path: NOVEL_API.addModel,
2664
+ handler: async (req, res) => {
2665
+ if (!guard(req, res, 'POST')) return
2666
+ const body = await readJsonBody<AddModelRequest>(req)
2667
+ if (body === undefined) {
2668
+ writeJson(res, 400, { error: '缺少请求体' })
2669
+ return
2670
+ }
2671
+ try {
2672
+ const result = await registerLlmModel(ctx, body)
2673
+ writeJson(res, 200, result satisfies AddModelResponse)
2674
+ } catch (error) {
2675
+ writeJson(res, 500, { error: `添加模型失败:${(error as Error).message}` })
2676
+ }
2677
+ },
2678
+ }
2679
+
2680
+ // ---------------------------------------------------------- llm-vendors
2681
+ /** 运行时厂商目录(DSH pi-ai 可配置提供方 + 内置适配器)。 */
2682
+ const llmVendorsRoute: WebRoute = {
2683
+ kind: 'exact',
2684
+ path: NOVEL_API.llmVendors,
2685
+ handler: async (req, res) => {
2686
+ if (!guard(req, res, 'GET')) return
2687
+ try {
2688
+ const result = await listLlmVendors(ctx)
2689
+ writeJson(res, 200, result satisfies LlmVendorsResponse)
2690
+ } catch (error) {
2691
+ writeJson(res, 500, { error: `读取厂商目录失败:${(error as Error).message}` })
2692
+ }
2693
+ },
2694
+ }
2695
+
2696
+ // ---------------------------------------------------------- llm-models
2697
+ /** 查询某个 provider 当前可用的模型(添加成功后可即时刷新下拉)。 */
2698
+ const llmModelsRoute: WebRoute = {
2699
+ kind: 'exact',
2700
+ path: NOVEL_API.llmModels,
2701
+ handler: async (req, res) => {
2702
+ if (!guard(req, res, 'GET')) return
2703
+ const url = new URL(req.url ?? '', 'http://localhost')
2704
+ const provider = decodeURIComponent((url.searchParams.get('provider') ?? '').trim())
2705
+ try {
2706
+ const result = await listLlmModels(ctx, provider)
2707
+ writeJson(res, 200, result satisfies LlmModelsResponse)
2708
+ } catch (error) {
2709
+ writeJson(res, 500, { error: `读取模型列表失败:${(error as Error).message}` })
2710
+ }
2711
+ },
2712
+ }
2713
+
2714
+ // ---------------------------------------------------------- llm-providers
2715
+ /** 已注册的提供方路由列表(提供方管理卡片)。 */
2716
+ const llmProvidersRoute: WebRoute = {
2717
+ kind: 'exact',
2718
+ path: NOVEL_API.llmProviders,
2719
+ handler: async (req, res) => {
2720
+ if (!guard(req, res, 'GET')) return
2721
+ try {
2722
+ const result = await listLlmProviders(ctx)
2723
+ writeJson(res, 200, result satisfies LlmProvidersResponse)
2724
+ } catch (error) {
2725
+ writeJson(res, 500, { error: `读取提供方列表失败:${(error as Error).message}` })
2726
+ }
2727
+ },
2728
+ }
2729
+
2730
+ // ------------------------------------------------------------- llm-remove
2731
+ /** 移除一个提供方(unset key + 移除 llm-pi-ai 路由)。 */
2732
+ const llmRemoveRoute: WebRoute = {
2733
+ kind: 'exact',
2734
+ path: NOVEL_API.llmRemove,
2735
+ handler: async (req, res) => {
2736
+ if (!guard(req, res, 'POST')) return
2737
+ const body = await readJsonBody<RemoveProviderRequest>(req)
2738
+ if (body === undefined) {
2739
+ writeJson(res, 400, { error: '缺少请求体' })
2740
+ return
2741
+ }
2742
+ try {
2743
+ const result = await removeLlmProvider(ctx, body)
2744
+ writeJson(res, 200, result satisfies RemoveProviderResponse)
2745
+ } catch (error) {
2746
+ writeJson(res, 500, { error: `移除提供方失败:${(error as Error).message}` })
2747
+ }
2748
+ },
2749
+ }
2750
+
2751
+
2752
+ // ----------------------------------------------------------- breakdown
2753
+ /** 拆书分析:对已写章节做结构/人物/文风/卖点体检(两阶段:源笔记→分节分析)。 */
2754
+ const breakdownRoute: WebRoute = {
2755
+ kind: 'exact',
2756
+ path: NOVEL_API.breakdown,
2757
+ handler: async (req, res) => {
2758
+ if (!guard(req, res, 'POST')) return
2759
+ const config = getConfig()
2760
+ const project = requireProject(res)
2761
+ if (project === undefined) return
2762
+ const body = await readJsonBody<BreakdownRequest>(req)
2763
+ try {
2764
+ const result = await breakdownBook(
2765
+ ctx,
2766
+ config,
2767
+ project,
2768
+ config.outputDir,
2769
+ body?.scope ?? 'recent',
2770
+ body?.preset ?? 'quick',
2771
+ body?.budgetTokens ?? 50000,
2772
+ )
2773
+ writeJson(res, 200, result satisfies BreakdownResponse)
2774
+ } catch (error) {
2775
+ writeJson(res, 500, { error: `拆书分析失败:${(error as Error).message}` })
2776
+ }
2777
+ },
2778
+ }
2779
+
2780
+
2781
+ // ----------------------------------------------------------- production run
2782
+ /** 生产单执行器(单例):计划补足 → 逐章生成 → 被拒分级处理 → 断点续跑。 */
2783
+ const runner = new ProductionRunner({ ctx, getConfig })
2784
+
2785
+ // --------------------------------------------------------- move-output-dir
2786
+ /**
2787
+ * 输出目录迁移:dryRun 预览;确认后 copy 全部内容 → 书架重指向 → settings
2788
+ * 默认目录同步(仅当默认目录就是被搬目录)→ 最后删源目录(数据零丢失排序)。
2789
+ */
2790
+ const moveOutputDirRoute: WebRoute = {
2791
+ kind: 'exact',
2792
+ path: NOVEL_API.moveOutputDir,
2793
+ handler: async (req, res) => {
2794
+ if (!guard(req, res, 'POST')) return
2795
+ const from = getConfig().outputDir
2796
+ const body = await readJsonBody<MoveOutputDirRequest>(req)
2797
+ // 预览:只列内容,不搬移。
2798
+ if (body?.dryRun === true) {
2799
+ try {
2800
+ const contents = listDirContents(from)
2801
+ writeJson(res, 200, { from, files: contents.files.slice(0, 300), bytes: contents.bytes, movedBooks: 0, defaultUpdated: false } satisfies MoveOutputDirResponse)
2802
+ } catch (error) {
2803
+ writeJson(res, 400, { error: (error as Error).message })
2804
+ }
2805
+ return
2806
+ }
2807
+ if (runner.isWorking()) {
2808
+ writeJson(res, 409, { error: '生产单正在运行中,请先停止后再迁移目录' })
2809
+ return
2810
+ }
2811
+ const to = body?.to?.trim() ?? ''
2812
+ if (to === '') {
2813
+ writeJson(res, 400, { error: '新目录路径不能为空' })
2814
+ return
2815
+ }
2816
+ if (normalizeDir(to) === normalizeDir(from)) {
2817
+ writeJson(res, 400, { error: '新目录与当前目录相同' })
2818
+ return
2819
+ }
2820
+ try {
2821
+ // 1. copy 全部内容(源目录保留;失败即中止,源数据无损)。
2822
+ copyDirContents(from, to)
2823
+ } catch (error) {
2824
+ writeJson(res, 400, { error: `迁移中止:${(error as Error).message}` })
2825
+ return
2826
+ }
2827
+ // 2. 书架重指向(outputDir === from 的条目全部改到 to)。
2828
+ let movedBooks = 0
2829
+ let repointError = ''
2830
+ try { movedBooks = repointBookDirs(from, to) } catch (error) { repointError = (error as Error).message }
2831
+ // 3. settings 默认目录同步(仅当默认目录就是被搬的这个)。
2832
+ let defaultUpdated = false
2833
+ let defaultError = ''
2834
+ const raw = deps.rawConfig?.()
2835
+ if (raw !== undefined && raw.outputDir !== undefined && raw.outputDir !== '' && normalizeDir(raw.outputDir) === normalizeDir(from)) {
2836
+ try {
2837
+ await patchConfig({ outputDir: to })
2838
+ defaultUpdated = true
2839
+ } catch (error) { defaultError = (error as Error).message }
2840
+ }
2841
+ // 4. 收尾:重指向全部成功才删源目录;否则保留源目录兜底并如实上报。
2842
+ if (repointError === '' && defaultError === '') {
2843
+ removeDir(from)
2844
+ const contents = listDirContents(to)
2845
+ writeJson(res, 200, { from, to, files: contents.files.slice(0, 300), bytes: contents.bytes, movedBooks, defaultUpdated } satisfies MoveOutputDirResponse)
2846
+ return
2847
+ }
2848
+ writeJson(res, 500, {
2849
+ error: `文件已复制到 ${to},但收尾未完成${repointError !== '' ? `(书架重指向失败:${repointError})` : ''}${defaultError !== '' ? `(默认目录更新失败:${defaultError})` : ''}。源目录已保留,请检查后重试或手动处理。`,
2850
+ from,
2851
+ to,
2852
+ movedBooks,
2853
+ defaultUpdated,
2854
+ })
2855
+ },
2856
+ }
2857
+
2858
+ // ----------------------------------------------------------- book-settings
2859
+ /**
2860
+ * 本书参数:POST {} 读取当前书的 settings + 生效配置(全局+本书回退链);
2861
+ * POST {patch} 白名单合并保存到 novel-project.json.bookSettings。
2862
+ */
2863
+ const bookSettingsRoute: WebRoute = {
2864
+ kind: 'exact',
2865
+ path: NOVEL_API.bookSettings,
2866
+ handler: async (req, res) => {
2867
+ if (!guard(req, res, 'POST')) return
2868
+ const outputDir = getConfig().outputDir
2869
+ const body = await readJsonBody<BookSettingsRequest>(req)
2870
+ if (body?.patch !== undefined) {
2871
+ const project = loadProject(outputDir)
2872
+ if (project === undefined) {
2873
+ writeJson(res, 400, { error: '当前没有打开的书(未找到 novel-project.json)' })
2874
+ return
2875
+ }
2876
+ const cur: BookSettings = project.bookSettings ?? {}
2877
+ const p = body.patch
2878
+ const next: Record<string, unknown> = { ...cur }
2879
+ for (const key of ['provider', 'model', 'reasoningEffort', 'analysisReasoning', 'chapterChars', 'maxTokens', 'reviewPassScore', 'autoReview', 'autoAuthorReview', 'autoReviewAfterRevise'] as const) {
2880
+ const v = (p as Record<string, unknown>)[key]
2881
+ if (v === null) delete next[key]
2882
+ else if (v !== undefined) next[key] = v
2883
+ }
2884
+ project.bookSettings = next as BookSettings
2885
+ project.updatedAt = new Date().toISOString()
2886
+ saveProject(outputDir, project)
2887
+ }
2888
+ const project = loadProject(outputDir)
2889
+ writeJson(res, 200, { settings: project?.bookSettings ?? {}, effective: getConfig(), hasBook: project !== undefined } satisfies BookSettingsResponse)
2890
+ },
2891
+ }
2892
+
2893
+ const runStartRoute: WebRoute = {
2894
+ kind: 'exact',
2895
+ path: NOVEL_API.runStart,
2896
+ handler: async (req, res) => {
2897
+ if (!guard(req, res, 'POST')) return
2898
+ const body = await readJsonBody<RunStartRequest & { bookId?: string }>(req)
2899
+ const config = getConfig()
2900
+ const outputDir = resolveOutputDir(config, body?.bookId)
2901
+ const project = loadProject(outputDir)
2902
+ if (project === undefined) {
2903
+ writeJson(res, 400, { error: '输出目录中没有项目' })
2904
+ return
2905
+ }
2906
+ const startNo = Number.isInteger(body?.startNo) && (body!.startNo! >= 1) ? body!.startNo! : 1
2907
+ let endNo: number
2908
+ if (Number.isInteger(body?.endNo) && (body!.endNo! >= startNo)) {
2909
+ endNo = body!.endNo!
2910
+ } else if (Number.isInteger(body?.count) && (body!.count! >= 1) && (body!.count! <= 200)) {
2911
+ const last = Math.max(0, ...project.chapters.map(c => c.no))
2912
+ endNo = last + body!.count!
2913
+ } else {
2914
+ writeJson(res, 400, { error: '请提供 endNo 或 count(1-200)' })
2915
+ return
2916
+ }
2917
+ try {
2918
+ const state = await runner.start(startNo, endNo, outputDir)
2919
+ writeJson(res, 200, state satisfies RunState)
2920
+ } catch (error) {
2921
+ writeJson(res, 409, { error: (error as Error).message })
2922
+ }
2923
+ },
2924
+ }
2925
+
2926
+ const runControlRoute: WebRoute = {
2927
+ kind: 'exact',
2928
+ path: NOVEL_API.runControl,
2929
+ handler: async (req, res) => {
2930
+ if (!guard(req, res, 'POST')) return
2931
+ const body = await readJsonBody<RunControlRequest>(req)
2932
+ const state = runner.status()
2933
+ if (state === null) {
2934
+ writeJson(res, 400, { error: '没有生产单' })
2935
+ return
2936
+ }
2937
+ if (body?.action === 'pause') runner.pause()
2938
+ else if (body?.action === 'resume') runner.resume()
2939
+ else if (body?.action === 'stop') runner.stop()
2940
+ else {
2941
+ writeJson(res, 400, { error: 'action 须为 pause / resume / stop' })
2942
+ return
2943
+ }
2944
+ writeJson(res, 200, runner.status())
2945
+ },
2946
+ }
2947
+
2948
+ const runStatusRoute: WebRoute = {
2949
+ kind: 'exact',
2950
+ path: NOVEL_API.runStatus,
2951
+ handler: (req, res) => {
2952
+ if (!guard(req, res, 'GET')) return
2953
+ writeJson(res, 200, runner.status())
2954
+ },
2955
+ }
2956
+
2957
+ // -------------------------------------------------- author assets (总数据)
2958
+ const authorAssetsRoute: WebRoute = {
2959
+ kind: 'exact',
2960
+ path: NOVEL_API.authorAssets,
2961
+ handler: (req, res) => {
2962
+ if (!guard(req, res, 'GET')) return
2963
+ const response: AuthorAssetsResponse = { assets: loadAuthorAssets() }
2964
+ writeJson(res, 200, response)
2965
+ },
2966
+ }
2967
+
2968
+ const authorAssetsUpsertRoute: WebRoute = {
2969
+ kind: 'exact',
2970
+ path: NOVEL_API.authorAssetsUpsert,
2971
+ handler: async (req, res) => {
2972
+ if (!guard(req, res, 'POST')) return
2973
+ const body = await readJsonBody<AuthorAssetUpsertRequest>(req)
2974
+ const asset = body?.asset
2975
+ if (asset === undefined || asset.name.trim() === '' || asset.content.trim() === '') {
2976
+ writeJson(res, 400, { error: 'asset 须含 name / content' })
2977
+ return
2978
+ }
2979
+ const response: AuthorAssetsResponse = { assets: upsertAuthorAsset(asset) }
2980
+ writeJson(res, 200, response)
2981
+ },
2982
+ }
2983
+
2984
+ const authorAssetsRemoveRoute: WebRoute = {
2985
+ kind: 'exact',
2986
+ path: NOVEL_API.authorAssetsRemove,
2987
+ handler: async (req, res) => {
2988
+ if (!guard(req, res, 'POST')) return
2989
+ const body = await readJsonBody<AuthorAssetRemoveRequest>(req)
2990
+ const id = body?.id ?? ''
2991
+ if (id === '') { writeJson(res, 400, { error: 'id 必填' }); return }
2992
+ const response: AuthorAssetsResponse = { assets: removeAuthorAsset(id) }
2993
+ writeJson(res, 200, response)
2994
+ },
2995
+ }
2996
+
2997
+ const authorAssetsImportDefaultRoute: WebRoute = {
2998
+ kind: 'exact',
2999
+ path: NOVEL_API.authorAssetsImportDefault,
3000
+ handler: (req, res) => {
3001
+ if (!guard(req, res, 'POST')) return
3002
+ const response: AuthorAssetsResponse = { assets: importDefaultAuthorAssets() }
3003
+ writeJson(res, 200, response)
3004
+ },
3005
+ }
3006
+
3007
+ // --------------------------------------------------- adaptation (改编 P0 分析)
3008
+ const adaptAnalyzeRoute: WebRoute = {
3009
+ kind: 'exact',
3010
+ path: NOVEL_API.adaptAnalyze,
3011
+ handler: async (req, res) => {
3012
+ if (!guard(req, res, 'POST')) return
3013
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3014
+ const body = await readJsonBody<AdaptAnalyzeRequest>(req)
3015
+ const config = getConfig()
3016
+ let text = body?.text?.trim() ?? ''
3017
+ if (text === '' && body?.filePath !== undefined && body.filePath !== '') {
3018
+ try {
3019
+ text = readFileSync(body.filePath, 'utf8')
3020
+ } catch (err) {
3021
+ writeJson(res, 400, { error: '读取文件失败:' + (err as Error).message })
3022
+ return
3023
+ }
3024
+ }
3025
+ if (text.length < 200) {
3026
+ writeJson(res, 400, { error: '全文内容过短(<200 字符),请上传完整小说文本' })
3027
+ return
3028
+ }
3029
+ try {
3030
+ const response: AdaptAnalyzeResponse = await analyzeAdaptation(ctx, config, text)
3031
+ writeJson(res, 200, response)
3032
+ } catch (err) {
3033
+ writeJson(res, 400, { error: (err as Error).message })
3034
+ }
3035
+ },
3036
+ }
3037
+
3038
+ const adaptProposeRoute: WebRoute = {
3039
+ kind: 'exact',
3040
+ path: NOVEL_API.adaptPropose,
3041
+ handler: async (req, res) => {
3042
+ if (!guard(req, res, 'POST')) return
3043
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3044
+ const body = await readJsonBody<AdaptProposeRequest>(req)
3045
+ const config = getConfig()
3046
+ const text = (body?.text ?? '').trim()
3047
+ const selections = body?.selections ?? []
3048
+ if (text.length < 200 || selections.length === 0) {
3049
+ writeJson(res, 400, { error: '请提供全文与至少一条要改的维度' })
3050
+ return
3051
+ }
3052
+ try {
3053
+ const response: AdaptProposeResponse = await proposeAdaptation(ctx, config, text, selections, body?.dimensions)
3054
+ writeJson(res, 200, response)
3055
+ } catch (err) {
3056
+ writeJson(res, 400, { error: (err as Error).message })
3057
+ }
3058
+ },
3059
+ }
3060
+
3061
+ const adaptExecuteRoute: WebRoute = {
3062
+ kind: 'exact',
3063
+ path: NOVEL_API.adaptExecute,
3064
+ handler: async (req, res) => {
3065
+ if (!guard(req, res, 'POST')) return
3066
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3067
+ const body = await readJsonBody<AdaptExecuteRequest>(req)
3068
+ const text = body?.text ?? ''
3069
+ const mappings = body?.mappings ?? []
3070
+ if (text.length < 200 || mappings.length === 0) {
3071
+ writeJson(res, 400, { error: '请提供全文与映射表' })
3072
+ return
3073
+ }
3074
+ if (body?.mode === 'rewrite') {
3075
+ try {
3076
+ const result = await rewriteAdaptationBook(ctx, getConfig(), text, mappings, body?.rules, { maxChapters: body?.maxChapters, startNo: body?.startNo, endNo: body?.endNo })
3077
+ const response: AdaptExecuteResponse = { adaptedText: result.adaptedText, mappings: mappings.length, hits: result.hits, mode: 'rewrite', rewritten: result.rewritten, skipped: result.skipped }
3078
+ writeJson(res, 200, response)
3079
+ } catch (err) {
3080
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
3081
+ }
3082
+ return
3083
+ }
3084
+ const { adaptedText, hits } = applyAdaptationReplacements(text, mappings)
3085
+ const response: AdaptExecuteResponse = { adaptedText, mappings: mappings.length, hits, mode: 'replace' }
3086
+ writeJson(res, 200, response)
3087
+ },
3088
+ }
3089
+
3090
+ /** rewrite 逐章重写:NDJSON 流式进度(支持分段 startNo/endNo)。 */
3091
+ const adaptRewriteStreamRoute: WebRoute = {
3092
+ kind: 'exact',
3093
+ path: NOVEL_API.adaptRewriteStream,
3094
+ handler: async (req, res) => {
3095
+ if (!guard(req, res, 'POST')) return
3096
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3097
+ const body = await readJsonBody<AdaptExecuteRequest>(req)
3098
+ const text = body?.text ?? ''
3099
+ const mappings = body?.mappings ?? []
3100
+ if (text.length < 200 || mappings.length === 0) { writeJson(res, 400, { error: '请提供全文与映射表' }); return }
3101
+ res.writeHead(200, {
3102
+ 'content-type': 'application/x-ndjson; charset=utf-8',
3103
+ 'cache-control': 'no-cache',
3104
+ 'x-accel-buffering': 'no',
3105
+ 'referrer-policy': 'no-referrer',
3106
+ })
3107
+ const send = (frame: AdaptRewriteFrame): void => { res.write(JSON.stringify(frame) + '\n') }
3108
+ try {
3109
+ const result = await rewriteAdaptationBook(ctx, getConfig(), text, mappings, body?.rules, {
3110
+ maxChapters: body?.maxChapters,
3111
+ startNo: body?.startNo,
3112
+ endNo: body?.endNo,
3113
+ onProgress: (info) => send({ type: 'progress', completed: info.completed, total: info.total, no: info.no, title: info.title }),
3114
+ })
3115
+ const response: AdaptExecuteResponse = { adaptedText: result.adaptedText, mappings: mappings.length, hits: result.hits, mode: 'rewrite', rewritten: result.rewritten, skipped: result.skipped }
3116
+ send({ type: 'done', result: response })
3117
+ } catch (err) {
3118
+ send({ type: 'error', message: err instanceof Error ? err.message : String(err) })
3119
+ } finally {
3120
+ res.end()
3121
+ }
3122
+ },
3123
+ }
3124
+
3125
+ /** 保存改编全文为新书(原书保留,登记书架)。 */
3126
+ const adaptSaveRoute: WebRoute = {
3127
+ kind: 'exact',
3128
+ path: NOVEL_API.adaptSave,
3129
+ handler: async (req, res) => {
3130
+ if (!guard(req, res, 'POST')) return
3131
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3132
+ const body = await readJsonBody<AdaptSaveRequest>(req)
3133
+ const text = (body?.text ?? '').trim()
3134
+ if (text.length < 200) {
3135
+ writeJson(res, 400, { error: '改编全文内容过短(<200 字符)' })
3136
+ return
3137
+ }
3138
+ const bookName = (body?.bookName ?? '').trim().slice(0, 40) || '改编新书'
3139
+ const outDir = (body?.outputDir ?? '').trim() !== '' && body?.outputDir !== undefined && body.outputDir.trim() !== ''
3140
+ ? body.outputDir.trim()
3141
+ : defaultOutputDirFor(bookName)
3142
+ // 原书保留:若目录已被另一本书占用则拒绝,避免误覆盖原书/别的书。
3143
+ const occupied = loadBookshelf().books.find(b => b.outputDir === outDir)
3144
+ if (occupied !== undefined && occupied.bookName !== bookName) {
3145
+ writeJson(res, 409, { error: `目录已被《${occupied.bookName}》占用,请更换书名或输出目录` })
3146
+ return
3147
+ }
3148
+ try {
3149
+ const result = importBookTextFromText(text, outDir, bookName)
3150
+ // 有反推大纲时写进新项目,便于后续续写/编辑(importBookTextFromText 默认 outline=书名)。
3151
+ const outline = (body?.outline ?? '').trim()
3152
+ if (outline !== '') {
3153
+ const project = loadProject(outDir)
3154
+ if (project !== undefined) {
3155
+ project.outline = outline
3156
+ saveProject(outDir, project)
3157
+ }
3158
+ }
3159
+ const { book } = importDir(outDir)
3160
+ const response: AdaptSaveResponse = { book, bookName: result.bookName, chapters: result.chapters, skipped: result.skipped, outputDir: outDir }
3161
+ writeJson(res, 200, response)
3162
+ } catch (err) {
3163
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
3164
+ }
3165
+ },
3166
+ }
3167
+
3168
+ /** 从源全文 + 编辑后方案提炼新书资料并保存为「待写新书」。 */
3169
+ const adaptMaterializeRoute: WebRoute = {
3170
+ kind: 'exact',
3171
+ path: NOVEL_API.adaptMaterialize,
3172
+ handler: async (req, res) => {
3173
+ if (!guard(req, res, 'POST')) return
3174
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3175
+ const body = await readJsonBody<AdaptMaterializeRequest>(req)
3176
+ const text = (body?.text ?? '').trim()
3177
+ if (text.length < 200) { writeJson(res, 400, { error: '源书全文内容过短(<200 字符)' }); return }
3178
+ const proposal = body?.proposal
3179
+ if (proposal === undefined || proposal.mappings.length === 0) { writeJson(res, 400, { error: '请先提供至少一条映射的改编方案' }); return }
3180
+ const bookName = (body?.bookName ?? '').trim().slice(0, 40) || '改编新书'
3181
+ const outDir = (body?.outputDir ?? '').trim() !== '' && body?.outputDir !== undefined && body.outputDir.trim() !== ''
3182
+ ? body.outputDir.trim()
3183
+ : defaultOutputDirFor(bookName)
3184
+ // 原书保留:若目录已被另一本书占用则拒绝。
3185
+ const occupied = loadBookshelf().books.find(b => b.outputDir === outDir)
3186
+ if (occupied !== undefined && occupied.bookName !== bookName) {
3187
+ writeJson(res, 409, { error: `目录已被《${occupied.bookName}》占用,请更换书名或输出目录` })
3188
+ return
3189
+ }
3190
+ try {
3191
+ const result = await materializeAdaptedBook(ctx, getConfig(), {
3192
+ text,
3193
+ bookName,
3194
+ outputDir: outDir,
3195
+ outline: body?.outline,
3196
+ proposal,
3197
+ chapterCount: body?.chapterCount,
3198
+ })
3199
+ // 预览:只返回提炼资料,不落盘;保存走 /adapt/materialize-save。
3200
+ const response: AdaptMaterializeResponse = result
3201
+ writeJson(res, 200, response)
3202
+ } catch (err) {
3203
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
3204
+ }
3205
+ },
3206
+ }
3207
+
3208
+ /** 保存预览/微调后的新书资料为新书(原书保留,登记书架)。 */
3209
+ const adaptMaterializeSaveRoute: WebRoute = {
3210
+ kind: 'exact',
3211
+ path: NOVEL_API.adaptMaterializeSave,
3212
+ handler: async (req, res) => {
3213
+ if (!guard(req, res, 'POST')) return
3214
+ if (!getConfig().enableAdaptMode) { writeJson(res, 404, { error: '改编模式未开启' }); return }
3215
+ const body = await readJsonBody<AdaptMaterializeSaveRequest>(req)
3216
+ if (body === undefined || body === null || (body.outline ?? '').trim() === '') {
3217
+ writeJson(res, 400, { error: '请提供改编后总纲' })
3218
+ return
3219
+ }
3220
+ const bookName = (body.bookName ?? '').trim().slice(0, 40) || '改编新书'
3221
+ const outDir = (body.outputDir ?? '').trim() !== '' && body.outputDir !== undefined && body.outputDir.trim() !== ''
3222
+ ? body.outputDir.trim()
3223
+ : defaultOutputDirFor(bookName)
3224
+ const occupied = loadBookshelf().books.find(b => b.outputDir === outDir)
3225
+ if (occupied !== undefined && occupied.bookName !== bookName) {
3226
+ writeJson(res, 409, { error: `目录已被《${occupied.bookName}》占用,请更换书名或输出目录` })
3227
+ return
3228
+ }
3229
+ try {
3230
+ const result = saveMaterializedBook(outDir, bookName, {
3231
+ outline: body.outline,
3232
+ bible: body.bible,
3233
+ roles: body.roles,
3234
+ world: body.world,
3235
+ volumes: body.volumes,
3236
+ chapters: body.chapters,
3237
+ })
3238
+ const { book } = importDir(outDir)
3239
+ const response: AdaptMaterializeSaveResponse = { ...result, book }
3240
+ writeJson(res, 200, response)
3241
+ } catch (err) {
3242
+ writeJson(res, 400, { error: err instanceof Error ? err.message : String(err) })
3243
+ }
3244
+ },
3245
+ }
3246
+
3247
+ // ------------------------------------------ theme custom background (upload + serve)
3248
+ const THEME_BG_DIR = join(homedir(), '.dsh', 'dsh-novel-forge-assets')
3249
+ const MIME_BY_EXT: Record<string, string> = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif' }
3250
+
3251
+ const themeBackgroundUploadRoute: WebRoute = {
3252
+ kind: 'exact',
3253
+ path: NOVEL_API.themeBackgroundUpload,
3254
+ handler: async (req, res) => {
3255
+ if (!guard(req, res, 'POST')) return
3256
+ const body = await readJsonBody<{ dataUrl?: string }>(req)
3257
+ const dataUrl = body?.dataUrl ?? ''
3258
+ const m = /^data:image\/(png|jpeg|jpg|webp|gif);base64,(.+)$/i.exec(dataUrl)
3259
+ if (m === null) { writeJson(res, 400, { error: '仅支持 PNG/JPG/WebP/GIF 图片' }); return }
3260
+ const ext = m[1]!.toLowerCase() === 'jpg' ? 'jpeg' : m[1]!.toLowerCase()
3261
+ const buf = Buffer.from(m[2]!, 'base64')
3262
+ if (buf.length === 0) { writeJson(res, 400, { error: '图片数据为空' }); return }
3263
+ mkdirSync(THEME_BG_DIR, { recursive: true })
3264
+ const name = 'theme-bg-' + Date.now().toString(36) + '-' + randomBytes(3).toString('hex') + '.' + ext
3265
+ writeFileSync(join(THEME_BG_DIR, name), buf)
3266
+ writeJson(res, 200, { url: NOVEL_API.themeBackgroundGet + '/' + name })
3267
+ },
3268
+ }
3269
+
3270
+ const themeBackgroundGetRoute: WebRoute = {
3271
+ kind: 'prefix',
3272
+ path: NOVEL_API.themeBackgroundGet,
3273
+ handler: (req, res) => {
3274
+ if (!guard(req, res, 'GET')) return
3275
+ let pathName = ''
3276
+ try { pathName = new URL(req.url ?? '', 'http://localhost').pathname } catch { /* ignore */ }
3277
+ const name = basename(pathName)
3278
+ if (!name.startsWith('theme-bg-')) { writeJson(res, 404, { error: 'not found' }); return }
3279
+ const file = join(THEME_BG_DIR, name)
3280
+ if (!existsSync(file)) { writeJson(res, 404, { error: 'not found' }); return }
3281
+ const ext = extname(file).slice(1)
3282
+ const type = MIME_BY_EXT[ext] ?? 'application/octet-stream'
3283
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'public, max-age=31536000' })
3284
+ res.end(readFileSync(file))
3285
+ },
3286
+ }
3287
+
3288
+ return [
3289
+ statusRoute,
3290
+ loadOutlineRoute,
3291
+ saveOutlineRoute,
3292
+ bibleRoute,
3293
+ volumesRoute,
3294
+ planRoute,
3295
+ generateRoute,
3296
+ reviewRoute,
3297
+ rewriteRoute,
3298
+ polishRoute,
3299
+ draftApplyRoute,
3300
+ draftDiscardRoute,
3301
+ summaryRoute,
3302
+ foreshadowRoute,
3303
+ exportRoute,
3304
+ chapterRoute,
3305
+ chapterCheckRoute,
3306
+ chapterSaveRoute,
3307
+ assetsRoute,
3308
+ styleEngineRoute,
3309
+ styleFormulaRoute,
3310
+ styleDetectRoute,
3311
+ marketRadarRoute,
3312
+ marketRadarScanRoute,
3313
+ marketRadarApplyRoute,
3314
+ marketRadarSyncRoute,
3315
+ marketRadarBriefRoute,
3316
+ knowledgeRoute,
3317
+ bookAnalysisRoute,
3318
+ ideaInspirationRoute,
3319
+ marketIdeaInspirationRoute,
3320
+ directorRoute,
3321
+ directorTodosRoute,
3322
+ llmLiveRoute,
3323
+ assistantRoute,
3324
+ assistantHistoryRoute,
3325
+ assistantClearRoute,
3326
+ bookshelfRoute,
3327
+ bookshelfActivateRoute,
3328
+ bookshelfRemoveRoute,
3329
+ bookshelfImportDirRoute,
3330
+ bookshelfImportTextRoute,
3331
+ bookshelfImportTextPreviewRoute,
3332
+ resetRoute,
3333
+ auditRoute,
3334
+ charactersRefreshRoute,
3335
+ factsBackfillRoute,
3336
+ biblePatchRoute,
3337
+ blurbRoute,
3338
+ coverRoute,
3339
+ worldRoute,
3340
+ renameRoute,
3341
+ plotlinesRoute,
3342
+ rolesRoute,
3343
+ sensitiveRoute,
3344
+ reviewBackfillRoute,
3345
+ chapterResetRoute,
3346
+ chapterApproveRoute,
3347
+ configRoute,
3348
+ moveOutputDirRoute,
3349
+ bookSettingsRoute,
3350
+ openFolderRoute,
3351
+ pluginUpdateRoute,
3352
+ outlineSuggestRoute,
3353
+ outlineReverseRoute,
3354
+ llmTestRoute,
3355
+ addModelRoute,
3356
+ llmVendorsRoute,
3357
+ llmModelsRoute,
3358
+ llmProvidersRoute,
3359
+ llmRemoveRoute,
3360
+ breakdownRoute,
3361
+ runStartRoute,
3362
+ runControlRoute,
3363
+ runStatusRoute,
3364
+ authorAssetsRoute,
3365
+ authorAssetsUpsertRoute,
3366
+ authorAssetsRemoveRoute,
3367
+ authorAssetsImportDefaultRoute,
3368
+ adaptAnalyzeRoute,
3369
+ adaptProposeRoute,
3370
+ adaptExecuteRoute,
3371
+ adaptSaveRoute,
3372
+ adaptMaterializeRoute,
3373
+ adaptMaterializeSaveRoute,
3374
+ adaptRewriteStreamRoute,
3375
+ themeBackgroundUploadRoute,
3376
+ themeBackgroundGetRoute,
3377
+ ]
3378
+ }
3379
+
3380
+ // Re-export for tests / type consumers.
3381
+ export type {
3382
+ ConfigPatch,
3383
+ NovelConfig,
3384
+ StatusResponse,
3385
+ PlanResponse,
3386
+ LoadOutlineResponse,
3387
+ BibleResponse,
3388
+ VolumesResponse,
3389
+ ExportResponse,
3390
+ }
3391
+ export { chapterFileName }