@waterwx/dsh-novel-forge 1.2.1-alpha → 1.3.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.
- package/README.md +4 -5
- package/lib/client.js +2470 -858
- package/lib/index.js +2155 -388
- package/lib/types/action-guard.d.ts +1 -1
- package/lib/types/assets.d.ts +7 -7
- package/lib/types/client/api.d.ts +31 -1
- package/lib/types/client/llmLive.d.ts +12 -14
- package/lib/types/client/panel/LiveFeedLog.d.ts +5 -0
- package/lib/types/client/panel/ModelManager.d.ts +2 -2
- package/lib/types/client/panel/PromptSlotsView.d.ts +11 -0
- package/lib/types/client/panel/TensionView.d.ts +14 -0
- package/lib/types/client/panel/TimelineView.d.ts +14 -0
- package/lib/types/engine.d.ts +40 -2
- package/lib/types/index.d.ts +4 -0
- package/lib/types/llm-live.d.ts +65 -34
- package/lib/types/llm-retry.d.ts +38 -0
- package/lib/types/market-radar-sources.d.ts +1 -1
- package/lib/types/prompt-slots.d.ts +57 -0
- package/lib/types/prompting.d.ts +2 -2
- package/lib/types/protocol.d.ts +283 -3
- package/lib/types/snapshots.d.ts +46 -0
- package/lib/types/stage-contract.d.ts +1 -1
- package/lib/types/tension.d.ts +65 -0
- package/lib/types/timeline.d.ts +37 -0
- package/package.json +3 -2
- package/src/action-guard.ts +1 -1
- package/src/assets.ts +300 -268
- package/src/assistant.ts +45 -29
- package/src/client/api.ts +76 -2
- package/src/client/llmLive.ts +26 -16
- package/src/client/panel/AssetsTab.tsx +2 -2
- package/src/client/panel/LiveFeedLog.tsx +204 -67
- package/src/client/panel/ModelManager.tsx +2 -2
- package/src/client/panel/NovelPanel.tsx +127 -13
- package/src/client/panel/PromptSlotsView.tsx +97 -0
- package/src/client/panel/SettingsView.tsx +35 -0
- package/src/client/panel/TensionView.tsx +196 -0
- package/src/client/panel/TimelineView.tsx +192 -0
- package/src/engine.ts +549 -108
- package/src/index.ts +12 -0
- package/src/llm-live.ts +260 -68
- package/src/llm-retry.ts +77 -0
- package/src/market-radar-sources.ts +173 -173
- package/src/prompt-slots.ts +125 -0
- package/src/prompting.ts +8 -8
- package/src/protocol.ts +314 -3
- package/src/routes.ts +325 -6
- package/src/run.ts +4 -0
- package/src/snapshots.ts +174 -0
- package/src/stage-contract.ts +189 -189
- package/src/tension.ts +240 -0
- package/src/timeline.ts +159 -0
package/src/routes.ts
CHANGED
|
@@ -18,6 +18,7 @@ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'
|
|
|
18
18
|
import type { Context } from '@deepseek-ai/cordis'
|
|
19
19
|
import { ProductionRunner } from './run.ts'
|
|
20
20
|
import {
|
|
21
|
+
EXPORT_SCOPE_VALUES,
|
|
21
22
|
NOVEL_API,
|
|
22
23
|
type AssetsPatch,
|
|
23
24
|
type AssetsResponse,
|
|
@@ -67,6 +68,15 @@ import {
|
|
|
67
68
|
type JobFrame,
|
|
68
69
|
type LoadOutlineRequest,
|
|
69
70
|
type LoadOutlineResponse,
|
|
71
|
+
type ExportScope,
|
|
72
|
+
type PromptSlotsRequest,
|
|
73
|
+
type PromptSlotsResponse,
|
|
74
|
+
type SnapshotRequest,
|
|
75
|
+
type SnapshotResponse,
|
|
76
|
+
type TensionRequest,
|
|
77
|
+
type TensionResponse,
|
|
78
|
+
type TimelineRequest,
|
|
79
|
+
type TimelineResponse,
|
|
70
80
|
type NovelConfig,
|
|
71
81
|
type PlotlinesRequest,
|
|
72
82
|
type PlotlinesResponse,
|
|
@@ -133,7 +143,7 @@ import { copyDirContents, listDirContents, normalizeDir, removeDir } from './mig
|
|
|
133
143
|
import { loadAuthorAssets, upsertAuthorAsset, removeAuthorAsset, importDefaultAuthorAssets } from './author-assets.ts'
|
|
134
144
|
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
145
|
import { scanAiFlavor } from './ai-scan.ts'
|
|
136
|
-
import { emitLive, nextSessionId, subscribeLiveFeed } from './llm-live.ts'
|
|
146
|
+
import { emitLive, livePrompt, liveUsage, nextSessionId, resetLiveUsage, subscribeLiveFeed } from './llm-live.ts'
|
|
137
147
|
import { scanMarketRanking } from './market-radar-scan.ts'
|
|
138
148
|
import { addGlobalGenre, addGlobalMode, globalGenreLibrary, globalProgressionLibrary } from './global-assets.ts'
|
|
139
149
|
import {
|
|
@@ -143,7 +153,7 @@ import {
|
|
|
143
153
|
autoLinkPlotlines,
|
|
144
154
|
backfillFacts,
|
|
145
155
|
createProject,
|
|
146
|
-
|
|
156
|
+
exportScope,
|
|
147
157
|
importBookText,
|
|
148
158
|
importBookTextFromText,
|
|
149
159
|
previewBookText,
|
|
@@ -195,11 +205,17 @@ import {
|
|
|
195
205
|
suggestForeshadows,
|
|
196
206
|
suggestPlotlines,
|
|
197
207
|
summarizeAndExtractFacts,
|
|
208
|
+
extractTimelineForChapter,
|
|
209
|
+
reviewTimeline,
|
|
198
210
|
summarizeChapter,
|
|
199
211
|
syncProjectWithDisk,
|
|
200
212
|
} from './engine.ts'
|
|
201
213
|
import { countHanzi } from './engine.ts'
|
|
202
214
|
import { computeBookStage } from './stage-contract.ts'
|
|
215
|
+
import { createSnapshot, loadSnapshots, pruneSnapshots, removeSnapshot, restoreSnapshot, snapshotsBytes } from './snapshots.ts'
|
|
216
|
+
import { detectTimelineIssues } from './timeline.ts'
|
|
217
|
+
import { buildCurveData, detectTensionIssues, TENSION_MAX, TENSION_MIN, TENSION_PRESETS, clampTension } from './tension.ts'
|
|
218
|
+
import { PROMPT_SLOTS, normalizeSlotValue, readPromptSlots } from './prompt-slots.ts'
|
|
203
219
|
|
|
204
220
|
/** Cap on JSON request bodies (generous: cover images travel as base64). */
|
|
205
221
|
const MAX_JSON_BODY_BYTES = 64 * 1024 * 1024
|
|
@@ -385,6 +401,8 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
385
401
|
audit: auditState,
|
|
386
402
|
// 阶段契约:宿主算一次,面板角标、助手提示词、外部自动化共用同一结论。
|
|
387
403
|
stage: computeBookStage(project),
|
|
404
|
+
// 本次运行(进程内)的 LLM 用量:调用次数 / 输入·输出·思考 token / 耗时。
|
|
405
|
+
usage: liveUsage(),
|
|
388
406
|
...(truncations.length > 0 ? { truncations } : {}),
|
|
389
407
|
}
|
|
390
408
|
writeJson(res, 200, response)
|
|
@@ -623,12 +641,21 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
623
641
|
}
|
|
624
642
|
}
|
|
625
643
|
emitLive({ type: 'session_completed', sessionId: liveSession, totalChars: genChars, preview: '', at: new Date().toISOString(), phase: 'completed' })
|
|
626
|
-
// Auto pipeline: summary + facts(一次调用)-> review(unless skipped)。
|
|
644
|
+
// Auto pipeline: summary + facts(一次调用)-> timeline -> review(unless skipped)。
|
|
627
645
|
try {
|
|
628
646
|
await summarizeAndExtractFacts(ctx, config, project, config.outputDir, no)
|
|
629
647
|
} catch (error) {
|
|
630
648
|
console.warn('[dsh-novel-forge] summary/facts failed:', (error as Error).message)
|
|
631
649
|
}
|
|
650
|
+
// 故事时间线:抽取本章事件(失败不阻断出章,作者可在时间线页手工补)。
|
|
651
|
+
if (config.autoTimeline ?? true) {
|
|
652
|
+
try {
|
|
653
|
+
await extractTimelineForChapter(ctx, config, project, config.outputDir, no)
|
|
654
|
+
saveProject(config.outputDir, project)
|
|
655
|
+
} catch (error) {
|
|
656
|
+
console.warn('[dsh-novel-forge] timeline extract failed:', (error as Error).message)
|
|
657
|
+
}
|
|
658
|
+
}
|
|
632
659
|
// 伏笔落地标记:正文中命中 planned 伏笔关键词 → 自动标为 planted(暗线管理页与正文同步)。
|
|
633
660
|
try {
|
|
634
661
|
const marked = markForeshadowPlanted(project, config.outputDir, no)
|
|
@@ -981,10 +1008,12 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
981
1008
|
writeJson(res, 400, { error: '输出目录中没有项目' })
|
|
982
1009
|
return
|
|
983
1010
|
}
|
|
984
|
-
const format = body?.format === 'md' ? 'md' : 'txt'
|
|
1011
|
+
const format: 'txt' | 'md' | 'json' = body?.format === 'json' ? 'json' : body?.format === 'md' ? 'md' : 'txt'
|
|
1012
|
+
// 导出范围:整本正文 / 设定 / 规划 / 角色 / 质检记录 / 项目 JSON。
|
|
1013
|
+
const scope: ExportScope = body?.scope !== undefined && EXPORT_SCOPE_VALUES.includes(body.scope) ? body.scope : 'book'
|
|
985
1014
|
try {
|
|
986
|
-
const result =
|
|
987
|
-
const response: ExportResponse = { ...result }
|
|
1015
|
+
const result = exportScope(config.outputDir, project, scope, format)
|
|
1016
|
+
const response: ExportResponse = { ...result, scope, format }
|
|
988
1017
|
writeJson(res, 200, response)
|
|
989
1018
|
} catch (error) {
|
|
990
1019
|
writeJson(res, 500, { error: (error as Error).message })
|
|
@@ -1082,6 +1111,8 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
1082
1111
|
if (existsSync(targetPath)) {
|
|
1083
1112
|
copyFileSync(targetPath, join(config.outputDir, `${fileName.replace(/\.md$/, '')}.bak.md`))
|
|
1084
1113
|
}
|
|
1114
|
+
// 覆盖前留一份历史版本:采纳草稿改坏了可以回滚。
|
|
1115
|
+
createSnapshot(config.outputDir, chapter, '采纳草稿前')
|
|
1085
1116
|
writeFileSync(targetPath, `# 第${chapter.no}章 ${chapter.title}\n\n${text}\n`, 'utf8')
|
|
1086
1117
|
chapter.status = 'written'
|
|
1087
1118
|
chapter.chars = countHanzi(text)
|
|
@@ -1675,6 +1706,288 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
1675
1706
|
},
|
|
1676
1707
|
}
|
|
1677
1708
|
|
|
1709
|
+
// --------------------------------------------------- llm-live prompt/usage
|
|
1710
|
+
/** 查看某次调用实际发送的 Prompt(面板「查看 Prompt」按钮用)。 */
|
|
1711
|
+
const llmPromptRoute: WebRoute = {
|
|
1712
|
+
kind: 'exact',
|
|
1713
|
+
path: NOVEL_API.llmPrompt,
|
|
1714
|
+
handler: (req, res) => {
|
|
1715
|
+
if (!guard(req, res, 'GET')) return
|
|
1716
|
+
const qurl = new URL(req.url ?? '/', 'http://localhost')
|
|
1717
|
+
const sessionId = qurl.searchParams.get('sessionId') ?? ''
|
|
1718
|
+
const record = livePrompt(sessionId)
|
|
1719
|
+
if (record === undefined) {
|
|
1720
|
+
writeJson(res, 404, { error: '该调用的 Prompt 记录已过期(只保留最近 40 次调用)' })
|
|
1721
|
+
return
|
|
1722
|
+
}
|
|
1723
|
+
writeJson(res, 200, record)
|
|
1724
|
+
},
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/** 清零本次运行的用量账本。 */
|
|
1728
|
+
const usageResetRoute: WebRoute = {
|
|
1729
|
+
kind: 'exact',
|
|
1730
|
+
path: NOVEL_API.usageReset,
|
|
1731
|
+
handler: (req, res) => {
|
|
1732
|
+
if (!guard(req, res, 'POST')) return
|
|
1733
|
+
resetLiveUsage()
|
|
1734
|
+
writeJson(res, 200, { ok: true, usage: liveUsage() })
|
|
1735
|
+
},
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
// ------------------------------------------------------------- timeline
|
|
1739
|
+
/**
|
|
1740
|
+
* 故事时间线:GET 列表(含规则初筛问题);POST op=extract|check|update|remove|clear。
|
|
1741
|
+
*/
|
|
1742
|
+
const timelineRoute: WebRoute = {
|
|
1743
|
+
kind: 'exact',
|
|
1744
|
+
path: NOVEL_API.timeline,
|
|
1745
|
+
handler: async (req, res) => {
|
|
1746
|
+
const config = getConfig()
|
|
1747
|
+
const qurl = new URL(req.url ?? '/', 'http://localhost')
|
|
1748
|
+
if (req.method === 'GET') {
|
|
1749
|
+
if (!isLoopbackRequest(req)) { writeJson(res, 403, { error: 'forbidden: loopback-only' }); return }
|
|
1750
|
+
const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
|
|
1751
|
+
const project = loadProject(outputDir)
|
|
1752
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1753
|
+
const response: TimelineResponse = {
|
|
1754
|
+
events: project.timeline ?? [],
|
|
1755
|
+
issues: detectTimelineIssues(project),
|
|
1756
|
+
}
|
|
1757
|
+
writeJson(res, 200, response)
|
|
1758
|
+
return
|
|
1759
|
+
}
|
|
1760
|
+
if (!guard(req, res, 'POST')) return
|
|
1761
|
+
const body = await readJsonBody<TimelineRequest & { bookId?: string }>(req)
|
|
1762
|
+
const outputDir = resolveOutputDir(config, body?.bookId)
|
|
1763
|
+
const project = loadProject(outputDir)
|
|
1764
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1765
|
+
try {
|
|
1766
|
+
if (body?.op === 'extract') {
|
|
1767
|
+
const no = body.chapterNo
|
|
1768
|
+
if (typeof no !== 'number' || !Number.isFinite(no)) { writeJson(res, 400, { error: 'extract 需要 chapterNo' }); return }
|
|
1769
|
+
const events = await extractTimelineForChapter(ctx, config, project, outputDir, no)
|
|
1770
|
+
saveProject(outputDir, project)
|
|
1771
|
+
writeJson(res, 200, { events, all: project.timeline ?? [] })
|
|
1772
|
+
return
|
|
1773
|
+
}
|
|
1774
|
+
if (body?.op === 'check') {
|
|
1775
|
+
const ruleIssues = detectTimelineIssues(project)
|
|
1776
|
+
let aiIssues: typeof ruleIssues = []
|
|
1777
|
+
try {
|
|
1778
|
+
aiIssues = await reviewTimeline(ctx, config, project)
|
|
1779
|
+
} catch (error) {
|
|
1780
|
+
// AI 复核失败不阻断:规则初筛结果照常返回,并说明原因。
|
|
1781
|
+
writeJson(res, 200, { issues: ruleIssues, aiError: (error as Error).message })
|
|
1782
|
+
return
|
|
1783
|
+
}
|
|
1784
|
+
writeJson(res, 200, { issues: [...ruleIssues, ...aiIssues] })
|
|
1785
|
+
return
|
|
1786
|
+
}
|
|
1787
|
+
if (body?.op === 'update') {
|
|
1788
|
+
const event = body.event
|
|
1789
|
+
if (event === undefined || typeof event.id !== 'string') { writeJson(res, 400, { error: 'update 需要 event' }); return }
|
|
1790
|
+
const list = project.timeline ?? []
|
|
1791
|
+
const idx = list.findIndex(e => e.id === event.id)
|
|
1792
|
+
if (idx === -1) { writeJson(res, 404, { error: '时间线事件不存在' }); return }
|
|
1793
|
+
list[idx] = { ...event, source: 'manual' }
|
|
1794
|
+
project.timeline = list
|
|
1795
|
+
project.updatedAt = new Date().toISOString()
|
|
1796
|
+
saveProject(outputDir, project)
|
|
1797
|
+
writeJson(res, 200, { events: project.timeline })
|
|
1798
|
+
return
|
|
1799
|
+
}
|
|
1800
|
+
if (body?.op === 'remove') {
|
|
1801
|
+
project.timeline = (project.timeline ?? []).filter(e => e.id !== body.id)
|
|
1802
|
+
project.updatedAt = new Date().toISOString()
|
|
1803
|
+
saveProject(outputDir, project)
|
|
1804
|
+
writeJson(res, 200, { events: project.timeline })
|
|
1805
|
+
return
|
|
1806
|
+
}
|
|
1807
|
+
if (body?.op === 'clear') {
|
|
1808
|
+
project.timeline = []
|
|
1809
|
+
project.updatedAt = new Date().toISOString()
|
|
1810
|
+
saveProject(outputDir, project)
|
|
1811
|
+
writeJson(res, 200, { events: [] })
|
|
1812
|
+
return
|
|
1813
|
+
}
|
|
1814
|
+
writeJson(res, 400, { error: `未知 op:${String(body?.op)}` })
|
|
1815
|
+
} catch (error) {
|
|
1816
|
+
writeJson(res, 500, { error: (error as Error).message })
|
|
1817
|
+
}
|
|
1818
|
+
},
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
// ------------------------------------------------------------ snapshots
|
|
1822
|
+
/** 章节历史版本:GET 列表;POST op=create|restore|remove|prune。 */
|
|
1823
|
+
const snapshotRoute: WebRoute = {
|
|
1824
|
+
kind: 'exact',
|
|
1825
|
+
path: NOVEL_API.snapshot,
|
|
1826
|
+
handler: async (req, res) => {
|
|
1827
|
+
const config = getConfig()
|
|
1828
|
+
const qurl = new URL(req.url ?? '/', 'http://localhost')
|
|
1829
|
+
if (req.method === 'GET') {
|
|
1830
|
+
if (!isLoopbackRequest(req)) { writeJson(res, 403, { error: 'forbidden: loopback-only' }); return }
|
|
1831
|
+
const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
|
|
1832
|
+
const response: SnapshotResponse = { snapshots: loadSnapshots(outputDir), bytes: snapshotsBytes(outputDir) }
|
|
1833
|
+
writeJson(res, 200, response)
|
|
1834
|
+
return
|
|
1835
|
+
}
|
|
1836
|
+
if (!guard(req, res, 'POST')) return
|
|
1837
|
+
const body = await readJsonBody<SnapshotRequest & { bookId?: string }>(req)
|
|
1838
|
+
const outputDir = resolveOutputDir(config, body?.bookId)
|
|
1839
|
+
const project = loadProject(outputDir)
|
|
1840
|
+
try {
|
|
1841
|
+
if (body?.op === 'create') {
|
|
1842
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1843
|
+
const chapter = project.chapters.find(c => c.no === body.chapterNo)
|
|
1844
|
+
if (chapter === undefined) { writeJson(res, 404, { error: `章节 ${String(body.chapterNo)} 不在计划中` }); return }
|
|
1845
|
+
const snapshot = createSnapshot(outputDir, chapter, '手工存档')
|
|
1846
|
+
if (snapshot === undefined) { writeJson(res, 400, { error: '该章暂无正文文件,无法存档' }); return }
|
|
1847
|
+
writeJson(res, 200, { snapshot, snapshots: loadSnapshots(outputDir) })
|
|
1848
|
+
return
|
|
1849
|
+
}
|
|
1850
|
+
if (body?.op === 'restore') {
|
|
1851
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1852
|
+
const id = body.id ?? ''
|
|
1853
|
+
const snap = loadSnapshots(outputDir).find(x => x.id === id)
|
|
1854
|
+
if (snap === undefined) { writeJson(res, 404, { error: '快照不存在' }); return }
|
|
1855
|
+
const chapter = project.chapters.find(c => c.no === snap.chapterNo)
|
|
1856
|
+
if (chapter === undefined) { writeJson(res, 404, { error: `章节 ${snap.chapterNo} 不在计划中` }); return }
|
|
1857
|
+
const chars = restoreSnapshot(outputDir, chapter, id)
|
|
1858
|
+
chapter.chars = countHanzi(readChapterFile(outputDir, chapter) ?? '')
|
|
1859
|
+
chapter.status = chapter.status === 'approved' ? 'written' : chapter.status
|
|
1860
|
+
chapter.review = undefined
|
|
1861
|
+
project.updatedAt = new Date().toISOString()
|
|
1862
|
+
saveProject(outputDir, project)
|
|
1863
|
+
writeJson(res, 200, { ok: true, chapterNo: chapter.no, chars, snapshots: loadSnapshots(outputDir) })
|
|
1864
|
+
return
|
|
1865
|
+
}
|
|
1866
|
+
if (body?.op === 'remove') {
|
|
1867
|
+
const ok = removeSnapshot(outputDir, body.id ?? '')
|
|
1868
|
+
writeJson(res, ok ? 200 : 404, { ok, snapshots: loadSnapshots(outputDir) })
|
|
1869
|
+
return
|
|
1870
|
+
}
|
|
1871
|
+
if (body?.op === 'prune') {
|
|
1872
|
+
const removed = pruneSnapshots(outputDir, body.keep)
|
|
1873
|
+
writeJson(res, 200, { removed, snapshots: loadSnapshots(outputDir), bytes: snapshotsBytes(outputDir) })
|
|
1874
|
+
return
|
|
1875
|
+
}
|
|
1876
|
+
writeJson(res, 400, { error: `未知 op:${String(body?.op)}` })
|
|
1877
|
+
} catch (error) {
|
|
1878
|
+
writeJson(res, 500, { error: (error as Error).message })
|
|
1879
|
+
}
|
|
1880
|
+
},
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
// --------------------------------------------------------------- tension
|
|
1884
|
+
/** 张力曲线:GET 数据(含规则核对);POST op=preset|set|clear。 */
|
|
1885
|
+
const tensionRoute: WebRoute = {
|
|
1886
|
+
kind: 'exact',
|
|
1887
|
+
path: NOVEL_API.tension,
|
|
1888
|
+
handler: async (req, res) => {
|
|
1889
|
+
const config = getConfig()
|
|
1890
|
+
const qurl = new URL(req.url ?? '/', 'http://localhost')
|
|
1891
|
+
if (req.method === 'GET') {
|
|
1892
|
+
if (!isLoopbackRequest(req)) { writeJson(res, 403, { error: 'forbidden: loopback-only' }); return }
|
|
1893
|
+
const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
|
|
1894
|
+
const project = loadProject(outputDir)
|
|
1895
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1896
|
+
const curve = buildCurveData(project)
|
|
1897
|
+
const response: TensionResponse = { preset: curve.preset, points: curve.points, issues: detectTensionIssues(project) }
|
|
1898
|
+
writeJson(res, 200, response)
|
|
1899
|
+
return
|
|
1900
|
+
}
|
|
1901
|
+
if (!guard(req, res, 'POST')) return
|
|
1902
|
+
const body = await readJsonBody<TensionRequest & { bookId?: string }>(req)
|
|
1903
|
+
const outputDir = resolveOutputDir(config, body?.bookId)
|
|
1904
|
+
const project = loadProject(outputDir)
|
|
1905
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1906
|
+
if (body?.op === 'preset') {
|
|
1907
|
+
const preset = body.preset
|
|
1908
|
+
if (preset === undefined || !TENSION_PRESETS.includes(preset)) { writeJson(res, 400, { error: '未知的张力曲线预设' }); return }
|
|
1909
|
+
project.tensionCurve = { ...(project.tensionCurve ?? {}), preset }
|
|
1910
|
+
project.updatedAt = new Date().toISOString()
|
|
1911
|
+
saveProject(outputDir, project)
|
|
1912
|
+
writeJson(res, 200, { ok: true, preset })
|
|
1913
|
+
return
|
|
1914
|
+
}
|
|
1915
|
+
if (body?.op === 'set') {
|
|
1916
|
+
const no = body.chapterNo
|
|
1917
|
+
if (typeof no !== 'number' || !Number.isFinite(no)) { writeJson(res, 400, { error: 'set 需要 chapterNo' }); return }
|
|
1918
|
+
const chapter = project.chapters.find(c => c.no === no)
|
|
1919
|
+
if (chapter === undefined) { writeJson(res, 404, { error: `章节 ${no} 不在计划中` }); return }
|
|
1920
|
+
if (body.tension === undefined) {
|
|
1921
|
+
chapter.tension = undefined
|
|
1922
|
+
} else {
|
|
1923
|
+
if (body.tension < TENSION_MIN || body.tension > TENSION_MAX) { writeJson(res, 400, { error: `张力需在 ${TENSION_MIN}-${TENSION_MAX} 之间` }); return }
|
|
1924
|
+
chapter.tension = clampTension(body.tension)
|
|
1925
|
+
}
|
|
1926
|
+
project.updatedAt = new Date().toISOString()
|
|
1927
|
+
saveProject(outputDir, project)
|
|
1928
|
+
writeJson(res, 200, { ok: true, chapterNo: no, tension: chapter.tension })
|
|
1929
|
+
return
|
|
1930
|
+
}
|
|
1931
|
+
if (body?.op === 'clear') {
|
|
1932
|
+
for (const c of project.chapters) c.tension = undefined
|
|
1933
|
+
project.updatedAt = new Date().toISOString()
|
|
1934
|
+
saveProject(outputDir, project)
|
|
1935
|
+
writeJson(res, 200, { ok: true })
|
|
1936
|
+
return
|
|
1937
|
+
}
|
|
1938
|
+
writeJson(res, 400, { error: `未知 op:${String(body?.op)}` })
|
|
1939
|
+
},
|
|
1940
|
+
}
|
|
1941
|
+
|
|
1942
|
+
// ---------------------------------------------------------- prompt slots
|
|
1943
|
+
/** 提示词槽位:GET 列表(含说明与上限);POST 写入或清空单个槽位。 */
|
|
1944
|
+
const promptSlotsRoute: WebRoute = {
|
|
1945
|
+
kind: 'exact',
|
|
1946
|
+
path: NOVEL_API.promptSlots,
|
|
1947
|
+
handler: async (req, res) => {
|
|
1948
|
+
const config = getConfig()
|
|
1949
|
+
const qurl = new URL(req.url ?? '/', 'http://localhost')
|
|
1950
|
+
if (req.method === 'GET') {
|
|
1951
|
+
if (!isLoopbackRequest(req)) { writeJson(res, 403, { error: 'forbidden: loopback-only' }); return }
|
|
1952
|
+
const outputDir = resolveOutputDir(config, qurl.searchParams.get('bookId') ?? undefined)
|
|
1953
|
+
const project = loadProject(outputDir)
|
|
1954
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1955
|
+
const values = new Map(readPromptSlots(project).map(s => [s.id, s.text] as const))
|
|
1956
|
+
const response: PromptSlotsResponse = {
|
|
1957
|
+
slots: PROMPT_SLOTS.map(spec => ({
|
|
1958
|
+
id: spec.id,
|
|
1959
|
+
label: spec.label,
|
|
1960
|
+
hint: spec.hint,
|
|
1961
|
+
placeholder: spec.placeholder,
|
|
1962
|
+
maxChars: spec.maxChars,
|
|
1963
|
+
value: values.get(spec.id) ?? '',
|
|
1964
|
+
})),
|
|
1965
|
+
}
|
|
1966
|
+
writeJson(res, 200, response)
|
|
1967
|
+
return
|
|
1968
|
+
}
|
|
1969
|
+
if (!guard(req, res, 'POST')) return
|
|
1970
|
+
const body = await readJsonBody<PromptSlotsRequest & { bookId?: string }>(req)
|
|
1971
|
+
const outputDir = resolveOutputDir(config, body?.bookId)
|
|
1972
|
+
const project = loadProject(outputDir)
|
|
1973
|
+
if (project === undefined) { writeJson(res, 400, { error: '输出目录中没有项目' }); return }
|
|
1974
|
+
let value: string
|
|
1975
|
+
try {
|
|
1976
|
+
value = normalizeSlotValue(String(body?.id ?? ''), String(body?.value ?? ''))
|
|
1977
|
+
} catch (error) {
|
|
1978
|
+
writeJson(res, 400, { error: (error as Error).message })
|
|
1979
|
+
return
|
|
1980
|
+
}
|
|
1981
|
+
const slots = { ...(project.promptSlots ?? {}) }
|
|
1982
|
+
if (value === '') delete slots[body!.id]
|
|
1983
|
+
else slots[body!.id] = value
|
|
1984
|
+
project.promptSlots = slots
|
|
1985
|
+
project.updatedAt = new Date().toISOString()
|
|
1986
|
+
saveProject(outputDir, project)
|
|
1987
|
+
writeJson(res, 200, { ok: true, id: body!.id, chars: value.length })
|
|
1988
|
+
},
|
|
1989
|
+
}
|
|
1990
|
+
|
|
1678
1991
|
// ------------------------------------------------------------- bookshelf
|
|
1679
1992
|
const bookshelfRoute: WebRoute = {
|
|
1680
1993
|
kind: 'exact',
|
|
@@ -3336,6 +3649,12 @@ export function makeRoutes(deps: NovelRoutesDeps): WebRoute[] {
|
|
|
3336
3649
|
llmLiveRoute,
|
|
3337
3650
|
assistantRoute,
|
|
3338
3651
|
assistantHistoryRoute,
|
|
3652
|
+
llmPromptRoute,
|
|
3653
|
+
usageResetRoute,
|
|
3654
|
+
timelineRoute,
|
|
3655
|
+
snapshotRoute,
|
|
3656
|
+
tensionRoute,
|
|
3657
|
+
promptSlotsRoute,
|
|
3339
3658
|
assistantClearRoute,
|
|
3340
3659
|
bookshelfRoute,
|
|
3341
3660
|
bookshelfActivateRoute,
|
package/src/run.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
planChapters,
|
|
16
16
|
generateChapterStream,
|
|
17
17
|
summarizeAndExtractFacts,
|
|
18
|
+
extractTimelineForChapter,
|
|
18
19
|
markForeshadowPlanted,
|
|
19
20
|
reviewChapter,
|
|
20
21
|
reviewChapterText,
|
|
@@ -224,6 +225,9 @@ export class ProductionRunner {
|
|
|
224
225
|
try {
|
|
225
226
|
for await (const _step of generateChapterStream(ctx, config, project, outputDir, no)) { /* drain */ }
|
|
226
227
|
try { await summarizeAndExtractFacts(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run summary/facts:', (e as Error).message) }
|
|
228
|
+
if (config.autoTimeline ?? true) {
|
|
229
|
+
try { await extractTimelineForChapter(ctx, config, project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run timeline:', (e as Error).message) }
|
|
230
|
+
}
|
|
227
231
|
try { markForeshadowPlanted(project, outputDir, no) } catch (e) { console.warn('[dsh-novel-forge] run foreshadow:', (e as Error).message) }
|
|
228
232
|
if (config.autoReview ?? true) {
|
|
229
233
|
const report = await reviewChapter(ctx, config, project, outputDir, no)
|
package/src/snapshots.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 章节历史版本(快照):覆盖写入前自动留存正文,支持列表 / 回滚 / 清理。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:生成、按意见重写、去 AI 味润色、采纳草稿都会**覆盖** `第N章_*.md`,
|
|
5
|
+
* 一旦改差(尤其是自动修订把好稿改坏)就没有退路。这里在覆盖前把旧稿存到
|
|
6
|
+
* `<书目录>/snapshots/`,并维护一份 `snapshots/index.json` 索引。
|
|
7
|
+
*
|
|
8
|
+
* 纯 Node 文件操作,不依赖模型;路由层只做参数校验与响应。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
12
|
+
import { join } from 'node:path'
|
|
13
|
+
import type { ChapterPlan, ChapterSnapshot } from './protocol.ts'
|
|
14
|
+
|
|
15
|
+
/** 快照目录名(书目录下)。 */
|
|
16
|
+
export const SNAPSHOT_DIR = 'snapshots'
|
|
17
|
+
|
|
18
|
+
/** 索引文件名。 */
|
|
19
|
+
const INDEX_FILE = 'index.json'
|
|
20
|
+
|
|
21
|
+
/** 每章默认保留的快照数(超出后按时间淘汰最旧的)。 */
|
|
22
|
+
export const DEFAULT_SNAPSHOT_KEEP = 20
|
|
23
|
+
|
|
24
|
+
/** 快照目录绝对路径。 */
|
|
25
|
+
export function snapshotDir(outputDir: string): string {
|
|
26
|
+
return join(outputDir, SNAPSHOT_DIR)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 读取索引(缺失/损坏时返回空数组)。 */
|
|
30
|
+
export function loadSnapshots(outputDir: string): ChapterSnapshot[] {
|
|
31
|
+
const file = join(snapshotDir(outputDir), INDEX_FILE)
|
|
32
|
+
if (!existsSync(file)) return []
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8')) as { snapshots?: ChapterSnapshot[] }
|
|
35
|
+
return Array.isArray(parsed.snapshots) ? parsed.snapshots : []
|
|
36
|
+
} catch {
|
|
37
|
+
return []
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 写回索引。 */
|
|
42
|
+
function saveSnapshots(outputDir: string, snapshots: ChapterSnapshot[]): void {
|
|
43
|
+
const dir = snapshotDir(outputDir)
|
|
44
|
+
mkdirSync(dir, { recursive: true })
|
|
45
|
+
writeFileSync(join(dir, INDEX_FILE), JSON.stringify({ snapshots }, null, 2), 'utf8')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 快照占用字节数(索引 + 正文)。 */
|
|
49
|
+
export function snapshotsBytes(outputDir: string): number {
|
|
50
|
+
const dir = snapshotDir(outputDir)
|
|
51
|
+
if (!existsSync(dir)) return 0
|
|
52
|
+
let total = 0
|
|
53
|
+
try {
|
|
54
|
+
for (const name of readdirSync(dir)) {
|
|
55
|
+
try { total += statSync(join(dir, name)).size } catch { /* 跳过读不到的条目 */ }
|
|
56
|
+
}
|
|
57
|
+
} catch { /* 目录不可读时按 0 计 */ }
|
|
58
|
+
return total
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 生成快照文件名(章节 + 时间戳 + 原因短标识)。 */
|
|
62
|
+
function snapshotFileName(chapterNo: number, reason: string, at: string): string {
|
|
63
|
+
const stamp = at.replace(/[:.]/g, '-')
|
|
64
|
+
const tag = reason.replace(/[^\w\u4e00-\u9fa5-]+/g, '').slice(0, 12) || 'snap'
|
|
65
|
+
return `ch${String(chapterNo).padStart(4, '0')}_${stamp}_${tag}.md`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 为一个章节留存快照(覆盖写入前调用)。
|
|
70
|
+
*
|
|
71
|
+
* @param outputDir 书目录。
|
|
72
|
+
* @param chapter 章节(需要已存在正文文件)。
|
|
73
|
+
* @param reason 留存原因(生成覆盖 / 采纳草稿 / 修订 / 润色 / 手工)。
|
|
74
|
+
* @param keep 每章保留数量(超出淘汰最旧)。
|
|
75
|
+
* @returns 新建的快照;无正文文件时返回 undefined(不产生空快照)。
|
|
76
|
+
*/
|
|
77
|
+
export function createSnapshot(
|
|
78
|
+
outputDir: string,
|
|
79
|
+
chapter: ChapterPlan,
|
|
80
|
+
reason: string,
|
|
81
|
+
keep = DEFAULT_SNAPSHOT_KEEP,
|
|
82
|
+
): ChapterSnapshot | undefined {
|
|
83
|
+
if (chapter.file === undefined || chapter.file === '') return undefined
|
|
84
|
+
const source = join(outputDir, chapter.file)
|
|
85
|
+
if (!existsSync(source)) return undefined
|
|
86
|
+
const at = new Date().toISOString()
|
|
87
|
+
const dir = snapshotDir(outputDir)
|
|
88
|
+
mkdirSync(dir, { recursive: true })
|
|
89
|
+
const name = snapshotFileName(chapter.no, reason, at)
|
|
90
|
+
const target = join(dir, name)
|
|
91
|
+
try {
|
|
92
|
+
copyFileSync(source, target)
|
|
93
|
+
} catch {
|
|
94
|
+
return undefined
|
|
95
|
+
}
|
|
96
|
+
const chars = chapter.chars ?? 0
|
|
97
|
+
const snapshot: ChapterSnapshot = {
|
|
98
|
+
id: name,
|
|
99
|
+
chapterNo: chapter.no,
|
|
100
|
+
file: `${SNAPSHOT_DIR}/${name}`,
|
|
101
|
+
reason,
|
|
102
|
+
chars,
|
|
103
|
+
at,
|
|
104
|
+
}
|
|
105
|
+
const snapshots = [...loadSnapshots(outputDir), snapshot]
|
|
106
|
+
saveSnapshots(outputDir, pruneList(snapshots, keep))
|
|
107
|
+
return snapshot
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** 按「每章保留最近 keep 个」裁剪列表,并删除被淘汰的文件。 */
|
|
111
|
+
function pruneList(snapshots: ChapterSnapshot[], keep: number): ChapterSnapshot[] {
|
|
112
|
+
const byChapter = new Map<number, ChapterSnapshot[]>()
|
|
113
|
+
for (const s of snapshots) {
|
|
114
|
+
const list = byChapter.get(s.chapterNo) ?? []
|
|
115
|
+
list.push(s)
|
|
116
|
+
byChapter.set(s.chapterNo, list)
|
|
117
|
+
}
|
|
118
|
+
const kept: ChapterSnapshot[] = []
|
|
119
|
+
for (const list of byChapter.values()) {
|
|
120
|
+
list.sort((a, b) => b.at.localeCompare(a.at))
|
|
121
|
+
kept.push(...list.slice(0, Math.max(1, keep)))
|
|
122
|
+
}
|
|
123
|
+
return kept.sort((a, b) => a.at.localeCompare(b.at))
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 回滚到某个快照:把快照内容写回章节正文文件。
|
|
128
|
+
*
|
|
129
|
+
* 回滚前会**先给当前正文留一份快照**(reason=回滚前自动留存),所以回滚本身也可撤销。
|
|
130
|
+
*
|
|
131
|
+
* @param outputDir 书目录。
|
|
132
|
+
* @param chapter 目标章节。
|
|
133
|
+
* @param snapshotId 快照 id。
|
|
134
|
+
* @returns 回滚后的字符数。
|
|
135
|
+
* @throws 快照不存在或章节无正文文件时抛错。
|
|
136
|
+
*/
|
|
137
|
+
export function restoreSnapshot(outputDir: string, chapter: ChapterPlan, snapshotId: string): number {
|
|
138
|
+
const snapshots = loadSnapshots(outputDir)
|
|
139
|
+
const snapshot = snapshots.find(s => s.id === snapshotId)
|
|
140
|
+
if (snapshot === undefined) throw new Error(`快照不存在:${snapshotId}`)
|
|
141
|
+
if (snapshot.chapterNo !== chapter.no) throw new Error(`快照属于第 ${snapshot.chapterNo} 章,与目标第 ${chapter.no} 章不符`)
|
|
142
|
+
const source = join(outputDir, snapshot.file)
|
|
143
|
+
if (!existsSync(source)) throw new Error(`快照文件已丢失:${snapshot.file}`)
|
|
144
|
+
if (chapter.file === undefined || chapter.file === '') throw new Error(`第 ${chapter.no} 章没有正文文件,无法回滚`)
|
|
145
|
+
createSnapshot(outputDir, chapter, '回滚前留存')
|
|
146
|
+
const body = readFileSync(source, 'utf8')
|
|
147
|
+
writeFileSync(join(outputDir, chapter.file), body, 'utf8')
|
|
148
|
+
return body.length
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 删除一个快照(连同文件)。 */
|
|
152
|
+
export function removeSnapshot(outputDir: string, snapshotId: string): boolean {
|
|
153
|
+
const snapshots = loadSnapshots(outputDir)
|
|
154
|
+
const snapshot = snapshots.find(s => s.id === snapshotId)
|
|
155
|
+
if (snapshot === undefined) return false
|
|
156
|
+
try { rmSync(join(outputDir, snapshot.file), { force: true }) } catch { /* 文件已不在 */ }
|
|
157
|
+
saveSnapshots(outputDir, snapshots.filter(s => s.id !== snapshotId))
|
|
158
|
+
return true
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 按每章保留数量清理(连文件一起删)。 */
|
|
162
|
+
export function pruneSnapshots(outputDir: string, keep = DEFAULT_SNAPSHOT_KEEP): number {
|
|
163
|
+
const snapshots = loadSnapshots(outputDir)
|
|
164
|
+
const kept = pruneList(snapshots, keep)
|
|
165
|
+
const keptIds = new Set(kept.map(s => s.id))
|
|
166
|
+
let removed = 0
|
|
167
|
+
for (const s of snapshots) {
|
|
168
|
+
if (keptIds.has(s.id)) continue
|
|
169
|
+
try { rmSync(join(outputDir, s.file), { force: true }) } catch { /* ignore */ }
|
|
170
|
+
removed++
|
|
171
|
+
}
|
|
172
|
+
saveSnapshots(outputDir, kept)
|
|
173
|
+
return removed
|
|
174
|
+
}
|