@waterwx/dsh-novel-forge 0.1.0 → 1.0.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 (180) hide show
  1. package/README.md +162 -111
  2. package/cordis.patch.yml +1 -1
  3. package/lib/client.js +54165 -2666
  4. package/lib/index.js +11895 -2211
  5. package/lib/types/ai-scan.d.ts +36 -0
  6. package/lib/types/assets.d.ts +19 -4
  7. package/lib/types/assistant.d.ts +6 -0
  8. package/lib/types/author-assets.d.ts +25 -0
  9. package/lib/types/bookshelf.d.ts +8 -1
  10. package/lib/types/client/api.d.ts +235 -3
  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 +101 -28
  14. package/lib/types/client/panel/AdaptModeView.d.ts +5 -0
  15. package/lib/types/client/panel/AssetsTab.d.ts +6 -1
  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/CreateBookView.d.ts +13 -0
  20. package/lib/types/client/panel/DirectorView.d.ts +7 -0
  21. package/lib/types/client/panel/FlowGuide.d.ts +22 -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 +5 -0
  27. package/lib/types/client/panel/MangaRoleLibrary.d.ts +20 -0
  28. package/lib/types/client/panel/MangaWorkspace.d.ts +12 -0
  29. package/lib/types/client/panel/MarketRadarView.d.ts +5 -0
  30. package/lib/types/client/panel/ModelManager.d.ts +14 -0
  31. package/lib/types/client/panel/ModelPicker.d.ts +11 -0
  32. package/lib/types/client/panel/NovelPanel.d.ts +1 -1
  33. package/lib/types/client/panel/ProgressConsole.d.ts +17 -0
  34. package/lib/types/client/panel/ProgressHomeView.d.ts +5 -0
  35. package/lib/types/client/panel/PropLibrary.d.ts +8 -0
  36. package/lib/types/client/panel/ReaderView.d.ts +8 -0
  37. package/lib/types/client/panel/ReasoningSection.d.ts +10 -0
  38. package/lib/types/client/panel/RunPanel.d.ts +5 -0
  39. package/lib/types/client/panel/SceneLibrary.d.ts +16 -0
  40. package/lib/types/client/panel/SettingsView.d.ts +16 -0
  41. package/lib/types/client/panel/ShelfView.d.ts +15 -0
  42. package/lib/types/client/panel/StoryboardTab.d.ts +19 -0
  43. package/lib/types/client/panel/StyleCard.d.ts +8 -0
  44. package/lib/types/client/panel/StyleGallery.d.ts +1 -0
  45. package/lib/types/client/panel/WorldTab.d.ts +10 -0
  46. package/lib/types/client/panel/helpers.d.ts +10 -0
  47. package/lib/types/client/panel/views.d.ts +77 -0
  48. package/lib/types/client/run-status.d.ts +19 -0
  49. package/lib/types/client/text.d.ts +9 -0
  50. package/lib/types/comic-presets.d.ts +12 -0
  51. package/lib/types/engine.d.ts +250 -8
  52. package/lib/types/global-assets.d.ts +6 -0
  53. package/lib/types/index.d.ts +24 -2
  54. package/lib/types/llm-live.d.ts +44 -0
  55. package/lib/types/manga-genre-rules.d.ts +22 -0
  56. package/lib/types/market-radar-scan.d.ts +19 -0
  57. package/lib/types/market-radar-sources.d.ts +31 -0
  58. package/lib/types/novel-context.d.ts +80 -0
  59. package/lib/types/prompt-utils.d.ts +35 -0
  60. package/lib/types/prompting.d.ts +35 -0
  61. package/lib/types/protocol.d.ts +1453 -5
  62. package/lib/types/review-policy.d.ts +97 -0
  63. package/lib/types/run.d.ts +32 -0
  64. package/lib/types/shot-language.d.ts +46 -0
  65. package/lib/types/src/ai-scan.d.ts +36 -0
  66. package/lib/types/src/assets.d.ts +37 -0
  67. package/lib/types/src/assistant.d.ts +45 -0
  68. package/lib/types/src/author-assets.d.ts +25 -0
  69. package/lib/types/src/bookshelf.d.ts +42 -0
  70. package/lib/types/src/client/api.d.ts +234 -0
  71. package/lib/types/src/client/docx.d.ts +15 -0
  72. package/lib/types/src/client/index.d.ts +14 -0
  73. package/lib/types/src/client/locales.d.ts +212 -0
  74. package/lib/types/src/client/mount.d.ts +9 -0
  75. package/lib/types/src/client/panel/AdaptModeView.d.ts +5 -0
  76. package/lib/types/src/client/panel/AssetsTab.d.ts +12 -0
  77. package/lib/types/src/client/panel/AssistantTab.d.ts +7 -0
  78. package/lib/types/src/client/panel/AuthorAssetsView.d.ts +4 -0
  79. package/lib/types/src/client/panel/AuthorHome.d.ts +32 -0
  80. package/lib/types/src/client/panel/BookshelfBar.d.ts +11 -0
  81. package/lib/types/src/client/panel/CreateBookView.d.ts +9 -0
  82. package/lib/types/src/client/panel/FlowGuide.d.ts +22 -0
  83. package/lib/types/src/client/panel/GlobalAssetLibraryView.d.ts +4 -0
  84. package/lib/types/src/client/panel/ImportModal.d.ts +7 -0
  85. package/lib/types/src/client/panel/MangaRoleLibrary.d.ts +20 -0
  86. package/lib/types/src/client/panel/MangaWorkspace.d.ts +12 -0
  87. package/lib/types/src/client/panel/ModelManager.d.ts +14 -0
  88. package/lib/types/src/client/panel/NovelPanel.d.ts +13 -0
  89. package/lib/types/src/client/panel/ProgressConsole.d.ts +17 -0
  90. package/lib/types/src/client/panel/ProgressHomeView.d.ts +5 -0
  91. package/lib/types/src/client/panel/PropLibrary.d.ts +8 -0
  92. package/lib/types/src/client/panel/ReaderView.d.ts +8 -0
  93. package/lib/types/src/client/panel/ReasoningSection.d.ts +10 -0
  94. package/lib/types/src/client/panel/RunPanel.d.ts +5 -0
  95. package/lib/types/src/client/panel/SceneLibrary.d.ts +16 -0
  96. package/lib/types/src/client/panel/SettingsView.d.ts +16 -0
  97. package/lib/types/src/client/panel/ShelfView.d.ts +15 -0
  98. package/lib/types/src/client/panel/StoryboardTab.d.ts +19 -0
  99. package/lib/types/src/client/panel/StyleCard.d.ts +8 -0
  100. package/lib/types/src/client/panel/StyleGallery.d.ts +1 -0
  101. package/lib/types/src/client/panel/WorldTab.d.ts +10 -0
  102. package/lib/types/src/client/panel/controller.d.ts +19 -0
  103. package/lib/types/src/client/panel/helpers.d.ts +18 -0
  104. package/lib/types/src/client/panel/views.d.ts +77 -0
  105. package/lib/types/src/client/sidebar-entry.d.ts +13 -0
  106. package/lib/types/src/client/text.d.ts +9 -0
  107. package/lib/types/src/comic-presets.d.ts +12 -0
  108. package/lib/types/src/docx.d.ts +19 -0
  109. package/lib/types/src/engine.d.ts +402 -0
  110. package/lib/types/src/index.d.ts +79 -0
  111. package/lib/types/src/manga-genre-rules.d.ts +22 -0
  112. package/lib/types/src/novel-context.d.ts +80 -0
  113. package/lib/types/src/prompt-utils.d.ts +35 -0
  114. package/lib/types/src/protocol.d.ts +2176 -0
  115. package/lib/types/src/review-policy.d.ts +97 -0
  116. package/lib/types/src/routes.d.ts +29 -0
  117. package/lib/types/src/run.d.ts +32 -0
  118. package/lib/types/src/shot-language.d.ts +46 -0
  119. package/lib/types/src/story-beat-language.d.ts +35 -0
  120. package/lib/types/src/style-library.d.ts +33 -0
  121. package/lib/types/story-beat-language.d.ts +35 -0
  122. package/lib/types/style-library.d.ts +33 -0
  123. package/package.json +57 -42
  124. package/scripts/patch-schemastery.mjs +47 -0
  125. package/src/ai-scan.ts +179 -0
  126. package/src/assets.ts +1774 -518
  127. package/src/assistant.ts +915 -547
  128. package/src/author-assets.ts +147 -0
  129. package/src/bookshelf.ts +32 -2
  130. package/src/client/api.ts +666 -254
  131. package/src/client/index.ts +3 -1
  132. package/src/client/llmLive.ts +101 -0
  133. package/src/client/locales.ts +178 -31
  134. package/src/client/mount.tsx +1 -1
  135. package/src/client/panel/AdaptModeView.tsx +535 -0
  136. package/src/client/panel/AssetsTab.tsx +168 -51
  137. package/src/client/panel/AssistantTab.tsx +339 -188
  138. package/src/client/panel/AuthorAssetsView.tsx +208 -0
  139. package/src/client/panel/AuthorHome.tsx +234 -0
  140. package/src/client/panel/BookAnalysisView.tsx +60 -0
  141. package/src/client/panel/BookshelfBar.tsx +63 -9
  142. package/src/client/panel/CreateBookView.tsx +371 -0
  143. package/src/client/panel/DirectorView.tsx +200 -0
  144. package/src/client/panel/GlobalAssetLibraryView.tsx +172 -0
  145. package/src/client/panel/IdeaInspirationView.tsx +71 -0
  146. package/src/client/panel/ImportModal.tsx +303 -0
  147. package/src/client/panel/KnowledgeBaseView.tsx +73 -0
  148. package/src/client/panel/LiveFeedLog.tsx +67 -0
  149. package/src/client/panel/MarketRadarView.tsx +374 -0
  150. package/src/client/panel/ModelManager.tsx +205 -0
  151. package/src/client/panel/NovelPanel.tsx +4713 -990
  152. package/src/client/panel/ProgressConsole.tsx +63 -0
  153. package/src/client/panel/ProgressHomeView.tsx +87 -0
  154. package/src/client/panel/ReaderView.tsx +306 -0
  155. package/src/client/panel/ReasoningSection.tsx +31 -0
  156. package/src/client/panel/RunPanel.tsx +204 -0
  157. package/src/client/panel/SettingsView.tsx +265 -0
  158. package/src/client/panel/ShelfView.tsx +242 -0
  159. package/src/client/panel/WorldTab.tsx +202 -0
  160. package/src/client/panel/helpers.ts +50 -0
  161. package/src/client/panel/panel.module.css +4325 -526
  162. package/src/client/panel/views.tsx +346 -0
  163. package/src/client/run-status.ts +100 -0
  164. package/src/client/sidebar-entry.ts +1 -1
  165. package/src/client/text.ts +28 -0
  166. package/src/engine.ts +4230 -1019
  167. package/src/global-assets.ts +59 -0
  168. package/src/index.ts +123 -9
  169. package/src/llm-live.ts +68 -0
  170. package/src/market-radar-scan.ts +41 -0
  171. package/src/market-radar-sources.ts +173 -0
  172. package/src/novel-context.ts +287 -0
  173. package/src/prompt-utils.ts +73 -0
  174. package/src/prompting.ts +159 -0
  175. package/src/protocol.ts +1998 -539
  176. package/src/review-policy.ts +161 -0
  177. package/src/routes.ts +3277 -955
  178. package/src/run.ts +338 -0
  179. package/lib/client.js.map +0 -1
  180. package/lib/index.js.map +0 -1
@@ -0,0 +1,287 @@
1
+ /**
2
+ * 统一上下文组装与相关设定检索
3
+ *
4
+ * 取代各阶段各自拼装 prompt,消除「生成看得到、审稿看不到」的断层。
5
+ * 所有阶段通过 buildChapterContext 获取同一来源的事实与设定。
6
+ */
7
+
8
+ import type { ProjectState, ChapterPlan, StoryBible, RoleRecord, ChapterFact, Foreshadow, Plotline } from './protocol'
9
+ import { readFileSync, existsSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+
12
+ export interface ChapterContext {
13
+ /** 平台合规红线(永远全量) */
14
+ complianceRedLines: string[]
15
+ /** 本书写作红线(永远全量) */
16
+ bookRedLines: string[]
17
+ /** 当前章相关角色卡(全量信息) */
18
+ relevantRoles: Array<{ name: string; role: string; traits: string[]; goals?: string; knowledge?: string[] }>
19
+ /** 当前章相关道藏规则 */
20
+ relevantWorldRules: string[]
21
+ /** 活跃剧情线 */
22
+ activePlotlines: Plotline[]
23
+ /** 未回收伏笔 */
24
+ activeForeshadows: Foreshadow[]
25
+ /** 上一章结尾原文 */
26
+ prevChapterTail: string
27
+ /** 上一章摘要 */
28
+ prevChapterSummary?: string
29
+ /** 最近事实(近因记忆,top20) */
30
+ recentFacts: string[]
31
+ /** 相关旧事实(按本章 beats 检索,top15) */
32
+ relatedFacts: string[]
33
+ /** 当前卷大纲 */
34
+ currentVolumeOutline: string
35
+ /** 本章 beats */
36
+ beats: string
37
+ /** 本章标题 */
38
+ chapterTitle: string
39
+ }
40
+
41
+ export interface ContextBuildOptions {
42
+ /** 阶段:writing/review/revise/polish/plan */
43
+ stage?: 'writing' | 'review' | 'revise' | 'polish' | 'plan'
44
+ /** 是否注入完整角色卡(false 时只注入角色名+定位) */
45
+ fullRoleCards?: boolean
46
+ /** 相关事实检索上限 */
47
+ relatedFactsLimit?: number
48
+ /** 最近事实数量 */
49
+ recentFactsLimit?: number
50
+ }
51
+
52
+ /**
53
+ * 相关事实检索:trigram 重合度 + 角色名命中加权 + 近因加权
54
+ * 从 generateChapterStream 抽取,扩展为通用函数。
55
+ */
56
+ export function retrieveRelatedFacts(
57
+ facts: ChapterFact[],
58
+ beatsText: string,
59
+ roleNames: string[],
60
+ limit = 15,
61
+ ): string[] {
62
+ if (facts.length === 0) return []
63
+
64
+ const trigrams = (s: string): Set<string> => {
65
+ const out = new Set<string>()
66
+ for (let i = 0; i + 3 <= s.length; i++) {
67
+ const tri = s.slice(i, i + 3)
68
+ if (tri.trim() !== '') out.add(tri)
69
+ }
70
+ return out
71
+ }
72
+
73
+ const beatsTri = trigrams(beatsText)
74
+ const beatRoles = roleNames.filter(n => beatsText.includes(n))
75
+
76
+ const recentTexts = new Set(facts.slice(-20).map(f => f.text))
77
+
78
+ return facts
79
+ .map((f, idx) => {
80
+ const head = f.text.slice(0, 80)
81
+ let score = 0
82
+ for (const tri of trigrams(head)) if (beatsTri.has(tri)) score += 1
83
+ if (beatRoles.length > 0) {
84
+ for (const n of beatRoles) if (head.includes(n)) score += 8
85
+ }
86
+ // 近因加权:越新越优先(封顶 40 章)
87
+ score += Math.min(idx, 40) / 10
88
+ return { f, score }
89
+ })
90
+ .filter(x => x.score >= 3)
91
+ .sort((a, b) => b.score - a.score)
92
+ .slice(0, limit)
93
+ .map(x => `[第${x.f.chapterNo}章] ${x.f.text}`)
94
+ .filter(t => !recentTexts.has(t.slice(t.indexOf(']') + 2)))
95
+ }
96
+
97
+ /**
98
+ * 相关角色检索:beats 中出现的角色 + 主角/主要反派永远全量
99
+ */
100
+ export function retrieveRelevantRoles(
101
+ bible: StoryBible | undefined,
102
+ roles: RoleRecord[] | undefined,
103
+ beatsText: string,
104
+ ): ChapterContext['relevantRoles'] {
105
+ const result: ChapterContext['relevantRoles'] = []
106
+ const seen = new Set<string>()
107
+
108
+ // 主角/主要反派永远全量
109
+ const alwaysRoles = (bible?.characters ?? []).filter(c =>
110
+ c.role === 'protagonist' || c.role === 'antagonist'
111
+ )
112
+ for (const card of alwaysRoles) {
113
+ if (seen.has(card.name)) continue
114
+ seen.add(card.name)
115
+ result.push({
116
+ name: card.name,
117
+ role: card.role,
118
+ traits: card.traits,
119
+ goals: card.goals !== '' ? card.goals : undefined,
120
+ knowledge: Array.isArray(card.knowledge) && card.knowledge.length > 0 ? card.knowledge : undefined,
121
+ })
122
+ }
123
+
124
+ // beats 中出现的角色
125
+ const beatRoles = (bible?.characters ?? []).filter(c => beatsText.includes(c.name))
126
+ for (const card of beatRoles) {
127
+ if (seen.has(card.name)) continue
128
+ seen.add(card.name)
129
+ result.push({
130
+ name: card.name,
131
+ role: card.role,
132
+ traits: card.traits,
133
+ goals: card.goals !== '' ? card.goals : undefined,
134
+ knowledge: Array.isArray(card.knowledge) && card.knowledge.length > 0 ? card.knowledge : undefined,
135
+ })
136
+ }
137
+
138
+ // 角色库补充(不在道藏里的)
139
+ for (const r of roles ?? []) {
140
+ if (seen.has(r.name)) continue
141
+ if (!beatsText.includes(r.name) && r.roleLabel !== 'protagonist' && r.roleLabel !== 'antagonist') continue
142
+ seen.add(r.name)
143
+ result.push({
144
+ name: r.name,
145
+ role: r.roleLabel,
146
+ traits: Array.isArray(r.traits) ? r.traits : [],
147
+ goals: r.goals !== undefined && r.goals !== '' ? r.goals : undefined,
148
+ })
149
+ }
150
+
151
+ return result
152
+ }
153
+
154
+ /**
155
+ * 构建章节统一上下文
156
+ *
157
+ * 各阶段调用此函数获取同一来源的事实与设定,消除上下文断层。
158
+ * 检索结果不足时自动回退全量,保证不丢失关键信息。
159
+ */
160
+ export function buildChapterContext(
161
+ project: ProjectState,
162
+ chapter: ChapterPlan,
163
+ outputDir: string,
164
+ options: ContextBuildOptions = {},
165
+ ): ChapterContext {
166
+ const {
167
+ stage = 'writing',
168
+ fullRoleCards = true,
169
+ relatedFactsLimit = 15,
170
+ recentFactsLimit = 20,
171
+ } = options
172
+
173
+ const bible = project.bible
174
+ const allFacts = project.facts ?? []
175
+ const roleNames = (project.roles ?? []).map(r => r.name).filter((n): n is string => typeof n === 'string' && n !== '')
176
+
177
+ // 上一章结尾 + 摘要
178
+ let prevChapterTail = ''
179
+ let prevChapterSummary: string | undefined
180
+ const prev = project.chapters.find(c => c.no === chapter.no - 1)
181
+ if (prev?.file !== undefined) {
182
+ try {
183
+ const prevPath = join(outputDir, prev.file)
184
+ if (existsSync(prevPath)) {
185
+ const text = readFileSync(prevPath, 'utf8')
186
+ prevChapterTail = text.replace(/^#\s+.*$/m, '').trim().slice(-900)
187
+ }
188
+ } catch { /* 文件缺失时忽略 */ }
189
+ }
190
+ prevChapterSummary = prev?.summary
191
+
192
+ // 事实:最近 + 相关
193
+ const recentFacts = allFacts.slice(-recentFactsLimit).map(f => `[第${f.chapterNo}章] ${f.text}`)
194
+ const relatedFacts = retrieveRelatedFacts(allFacts, chapter.beats, roleNames, relatedFactsLimit)
195
+
196
+ // 角色:相关角色
197
+ const relevantRoles = retrieveRelevantRoles(bible, project.roles, chapter.beats)
198
+
199
+ // 道藏规则:全部(规则数量通常不多,全量注入更安全)
200
+ const relevantWorldRules = bible?.worldRules ?? []
201
+
202
+ // 活跃剧情线
203
+ const activePlotlines = (project.plotlines ?? []).filter(l =>
204
+ l.status === 'active' || l.status === 'paused'
205
+ )
206
+
207
+ // 未回收伏笔
208
+ const activeForeshadows = (project.foreshadows ?? []).filter(f =>
209
+ f.status === 'planted' || f.status === 'progressing'
210
+ )
211
+
212
+ // 当前卷大纲
213
+ const volumeNo = chapter.volume ?? 0
214
+ const volume = project.volumes?.find(v => v.no === volumeNo)
215
+ const currentVolumeOutline = volume !== undefined
216
+ ? `第${volume.no}卷《${volume.title}》:${volume.summary}`
217
+ : ''
218
+
219
+ return {
220
+ complianceRedLines: [], // 由调用方注入 COMPLIANCE_REDLINES
221
+ bookRedLines: bible?.redLines ?? [],
222
+ relevantRoles: fullRoleCards ? relevantRoles : relevantRoles.map(r => ({ name: r.name, role: r.role, traits: [] })),
223
+ relevantWorldRules,
224
+ activePlotlines,
225
+ activeForeshadows,
226
+ prevChapterTail,
227
+ prevChapterSummary,
228
+ recentFacts,
229
+ relatedFacts,
230
+ currentVolumeOutline,
231
+ beats: chapter.beats,
232
+ chapterTitle: chapter.title,
233
+ }
234
+ }
235
+
236
+ /**
237
+ * 将上下文渲染为 prompt 文本块
238
+ * 各阶段可按需选择注入哪些块。
239
+ */
240
+ export function renderContextBlocks(ctx: ChapterContext): {
241
+ rolesBlock: string
242
+ worldRulesBlock: string
243
+ factsBlock: string
244
+ plotlinesBlock: string
245
+ foreshadowsBlock: string
246
+ continuityBlock: string
247
+ redLinesBlock: string
248
+ } {
249
+ const roleName = { protagonist: '主角', supporting: '配角', antagonist: '反派', other: '其他', female_lead: '女主', female_support: '女配', support: '配角', extra: '路人' } as Record<string, string>
250
+
251
+ const rolesBlock = ctx.relevantRoles.length > 0
252
+ ? '==================== 相关角色卡 ====================\n' +
253
+ ctx.relevantRoles.map(r =>
254
+ `- ${r.name}(${roleName[r.role] ?? r.role}):${r.traits.join('、')}${r.goals ? `;目标:${r.goals}` : ''}${r.knowledge ? `\n 已知信息:${r.knowledge.join(';')}(未列出的该角色不知道)` : ''}`
255
+ ).join('\n')
256
+ : ''
257
+
258
+ const worldRulesBlock = ctx.relevantWorldRules.length > 0
259
+ ? '==================== 世界规则 ====================\n' + ctx.relevantWorldRules.map(r => `- ${r}`).join('\n')
260
+ : ''
261
+
262
+ const factsBlock = (ctx.recentFacts.length > 0 || ctx.relatedFacts.length > 0)
263
+ ? '==================== 事实库(最近 + 相关) ====================\n' +
264
+ (ctx.recentFacts.length > 0 ? `【最近 ${ctx.recentFacts.length} 条】\n${ctx.recentFacts.join('\n')}` : '') +
265
+ (ctx.relatedFacts.length > 0 ? `\n【相关旧事实 ${ctx.relatedFacts.length} 条】\n${ctx.relatedFacts.join('\n')}` : '')
266
+ : ''
267
+
268
+ const plotlinesBlock = ctx.activePlotlines.length > 0
269
+ ? '==================== 活跃剧情线 ====================\n' +
270
+ ctx.activePlotlines.map(l => `- [${l.kind}${l.status === 'paused' ? '·暂停' : ''}] ${l.name}:${l.goal}${l.progress ? `(进度:${l.progress})` : ''}`).join('\n')
271
+ : ''
272
+
273
+ const foreshadowsBlock = ctx.activeForeshadows.length > 0
274
+ ? '==================== 活跃伏笔 ====================\n' +
275
+ ctx.activeForeshadows.map(f => `- [${f.status === 'planted' ? '已埋设' : '推进中'}] ${f.description}${f.targetChapter ? `(预计第${f.targetChapter}章回收)` : ''}`).join('\n')
276
+ : ''
277
+
278
+ const continuityBlock = ctx.prevChapterTail !== ''
279
+ ? `==================== 上一章结尾(紧接此状态继续) ====================\n${ctx.prevChapterTail}`
280
+ : ''
281
+
282
+ const redLinesBlock = ctx.bookRedLines.length > 0
283
+ ? '==================== 本书红线 ====================\n' + ctx.bookRedLines.map(r => `- ${r}`).join('\n')
284
+ : ''
285
+
286
+ return { rolesBlock, worldRulesBlock, factsBlock, plotlinesBlock, foreshadowsBlock, continuityBlock, redLinesBlock }
287
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * 提示词共享常量与工具
3
+ *
4
+ * 所有 JSON 输出规则、通用约束集中在此,避免各阶段重复定义、互相打架。
5
+ */
6
+
7
+ /** JSON 输出规则(所有要求模型输出 JSON 的地方共用) */
8
+ export const JSON_OUTPUT_RULES = [
9
+ '输出必须是合法 JSON 对象或数组,不要输出任何其他文字、解释、Markdown 标记或代码块。',
10
+ '所有字符串值内部不得包含换行符(用 \\n 转义),JSON 必须在一段内完整结束。',
11
+ '直接输出 JSON 结果本身,不要把思考过程写在输出里。',
12
+ '数值字段必须是数字类型,不要用字符串包裹。',
13
+ '数组为空时输出 [],对象为空时输出 {}。',
14
+ ]
15
+
16
+ /** JSON 输出规则的紧凑版(适合放在提示词末尾) */
17
+ export const JSON_OUTPUT_RULES_COMPACT = JSON_OUTPUT_RULES.join(' ')
18
+
19
+ /**
20
+ * 估算 prompt 的 token 数(粗略估算,用于上下文预算控制)
21
+ * 中文约 1.7 字/token,英文约 4 字符/token
22
+ */
23
+ export function estimateTokens(text: string): number {
24
+ if (text.length === 0) return 0
25
+ // 统计中文字符数
26
+ const chineseChars = (text.match(/[\u4e00-\u9fff]/g) ?? []).length
27
+ const otherChars = text.length - chineseChars
28
+ return Math.round(chineseChars / 1.7 + otherChars / 4)
29
+ }
30
+
31
+ /**
32
+ * 按 token 预算截断文本(保留开头,末尾加省略标记)
33
+ * 用于控制单块上下文不超预算。
34
+ */
35
+ export function truncateByTokens(text: string, maxTokens: number, marker = '…(已截断)'): string {
36
+ if (estimateTokens(text) <= maxTokens) return text
37
+ // 二分查找最大可保留长度
38
+ let lo = 0
39
+ let hi = text.length
40
+ while (lo < hi) {
41
+ const mid = Math.floor((lo + hi + 1) / 2)
42
+ if (estimateTokens(text.slice(0, mid)) <= maxTokens - estimateTokens(marker)) {
43
+ lo = mid
44
+ } else {
45
+ hi = mid - 1
46
+ }
47
+ }
48
+ return text.slice(0, lo) + marker
49
+ }
50
+
51
+ /** 通用「只改表达不改情节」约束(润色/局部修订共用) */
52
+ export const EXPRESSION_ONLY_RULE = [
53
+ '只改表达,不改情节走向、人物设定、已确立事实、对话核心内容。',
54
+ '保留角色口吻与性格,角色行为需符合角色卡。',
55
+ '必须遵守内容合规红线与本书红线,任何一条命中(含影射、暗示)都必须避免。',
56
+ '避免 AI 套话:不禁、仿佛、一时间、不由得、顿时、然而、缓缓、轻轻、微微、默默、似乎、终于等滥用。',
57
+ ]
58
+
59
+ /** 章节上下文各阶段的 token 预算(粗略,用于控制注入量) */
60
+ export const CONTEXT_BUDGET = {
61
+ /** 章节生成:道藏+角色+大纲+事实+伏笔 */
62
+ writing: 12000,
63
+ /** AI 审稿:道藏+角色+事实+正文 */
64
+ review: 10000,
65
+ /** 修订:原意见+相关事实+目标正文 */
66
+ revise: 8000,
67
+ /** 润色:风格资产+原正文 */
68
+ polish: 6000,
69
+ /** 分章规划:大纲+道藏+角色+近期事实 */
70
+ plan: 15000,
71
+ } as const
72
+
73
+ export type ContextStage = keyof typeof CONTEXT_BUDGET
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 官方提示模板注册表(对齐上游 officialTemplates.ts 的轻量版)。
3
+ *
4
+ * 目标:把高频提示词从内联字符串升级为「可定位、可版本化、可诊断缺组」的资产,
5
+ * 同时保留 writeSystemPrompt 的现有大段上下文注入(道藏/世界观/大纲/资产/伏笔/剧情线),
6
+ * 只在其基础上补充「官方渲染骨架」的必达/禁止/自查块。
7
+ */
8
+
9
+ export interface OfficialTemplate {
10
+ id: string
11
+ version: string
12
+ /** 需要的 slot 变量(跨层注入点)。 */
13
+ slots: string[]
14
+ /** 需要的上下文分组(缺组时可诊断)。 */
15
+ contextGroups: string[]
16
+ /** system 提示模板(可用 {{slot.*}} 占位,运行时替换)。 */
17
+ system: string[]
18
+ /** human 提示模板(可用 {{context.*}} / {{input.*}} 占位)。 */
19
+ human: string[]
20
+ }
21
+
22
+ /** 章节写作官方模板(system 侧骨架)。 */
23
+ const CHAPTER_WRITER_SYSTEM = [
24
+ '你是中文长篇网络小说写作助手。',
25
+ '你的任务是根据当前章节任务,生成可直接阅读的正文,而不是提纲或解释。',
26
+ '',
27
+ '【叙事视角】{{slot.writer.pov}}',
28
+ '',
29
+ '【任务边界】只输出章节正文,不输出标题、提纲、解释或任何额外文本。',
30
+ '',
31
+ '【核心约束】',
32
+ '0. 以本章任务、人物状态、伏笔指令和连续性上下文为准,避免提前揭示未来答案或写到后续章节事件。',
33
+ '1. 必须推进新的剧情动作,本章必须发生实质变化(局面、关系、信息、风险、决策至少一项)。',
34
+ '2. 不得写成总结、复盘、解释性段落为主的章节,正文必须以「正在发生」的内容为主。',
35
+ '3. 不得引入新的核心角色、世界规则或与上下文冲突的重大设定。',
36
+ '',
37
+ '【结构要求】',
38
+ '1. 开头必须迅速进入当前情境,不得长时间铺垫背景或复述上一章。',
39
+ '2. 中段必须出现推进、变化或对抗,不能平铺直叙维持同一状态。',
40
+ '3. 本章至少出现一次明确的「状态变化」(信息反转、局面升级、关系变化、风险上升或计划转向)。',
41
+ '4. {{slot.writer.endingHookPreference}}',
42
+ '',
43
+ '【篇幅要求】',
44
+ '本章目标长度:约 {{input.targetWordCount}} 字;可接受区间:{{input.minWordCount}}-{{input.maxWordCount}} 字。',
45
+ '篇幅不够时必须继续推进新的有效情节、冲突、对话和动作,而不是草率收尾。',
46
+ '禁止靠重复回顾、空泛心理独白、无信息量描写硬凑字数。',
47
+ '',
48
+ '【连续性约束】',
49
+ '1. 章节开头必须与 recent_chapters 明显区分,禁止复用相同开场模式。',
50
+ '2. 允许短回调,但不得大段复述已发生事件,不得复制上下文原句。',
51
+ '3. 必须延续当前人物状态与局面,不得让角色行为失去动机或连续性。',
52
+ '',
53
+ '【表达要求】',
54
+ '1. {{slot.writer.tonePreference}}',
55
+ '2. 优先使用具体动作、对话与可感知细节推进,而不是抽象概述。',
56
+ '3. {{slot.writer.antiAiRules}}',
57
+ '4. 对话应服务推进或冲突,不得成为填充内容。',
58
+ '',
59
+ '【输出前自查】',
60
+ '在生成正文前,先内部确认:读者回报、关键转折和章末净变化是否可见,旧钩子责任是否回应,',
61
+ '结尾钩子是否成立,义务合约是否兑现,人物硬事实是否违背。确认通过后再开始输出,不需要在正文中输出核查结果。',
62
+ ].join('\n')
63
+
64
+ /** 章节写作官方模板(human 侧骨架,用于标注任务上下文分组)。 */
65
+ const CHAPTER_WRITER_HUMAN = [
66
+ '小说:{{input.novelTitle}}',
67
+ '章节:第 {{input.chapterOrder}} 章 {{input.chapterTitle}}',
68
+ '',
69
+ '【书级合约】{{context.book_contract}}',
70
+ '【章节任务】{{context.chapter_mission}}',
71
+ '【读者体验合同】{{context.reader_experience}}',
72
+ '【人物硬事实】{{context.character_hard_facts}}',
73
+ '【本章义务合约】{{context.obligation_contract}}',
74
+ '【卷级窗口】{{context.volume_window}}',
75
+ '【出场角色子集】{{context.participant_subset}}',
76
+ '【当前局面】{{context.local_state}}',
77
+ '【风格合约】{{context.style_contract}}',
78
+ '【额外写法约束】{{slot.writer.customConstraints}}',
79
+ '',
80
+ '只输出章节正文。',
81
+ ].join('\n')
82
+
83
+ export const OFFICIAL_TEMPLATES: Record<string, OfficialTemplate> = {
84
+ 'novel.chapter.writer': {
85
+ id: 'novel.chapter.writer',
86
+ version: 'v1',
87
+ slots: [
88
+ 'writer.pov',
89
+ 'writer.tonePreference',
90
+ 'writer.antiAiRules',
91
+ 'writer.antiCliché',
92
+ 'writer.endingHookPreference',
93
+ 'writer.wordCountHint',
94
+ 'writer.customConstraints',
95
+ ],
96
+ contextGroups: [
97
+ 'book_contract',
98
+ 'chapter_mission',
99
+ 'reader_experience',
100
+ 'character_hard_facts',
101
+ 'obligation_contract',
102
+ 'volume_window',
103
+ 'participant_subset',
104
+ 'local_state',
105
+ 'style_contract',
106
+ ],
107
+ system: [CHAPTER_WRITER_SYSTEM],
108
+ human: [CHAPTER_WRITER_HUMAN],
109
+ },
110
+ }
111
+
112
+ export function getOfficialPromptTemplate(id: string): OfficialTemplate | null {
113
+ return OFFICIAL_TEMPLATES[id] ?? null
114
+ }
115
+
116
+ export function getOfficialPromptTemplateVersion(id: string): string | null {
117
+ return OFFICIAL_TEMPLATES[id]?.version ?? null
118
+ }
119
+
120
+ /** 轻量稳定哈希(与上游 sha1 对齐精神:内容变化→版本变化)。 */
121
+ export function hashPromptTemplate(id: string): string {
122
+ const t = OFFICIAL_TEMPLATES[id]
123
+ if (t === undefined) return ''
124
+ const body = t.system.join('\n') + '\n' + t.human.join('\n')
125
+ let h = 5381
126
+ for (let i = 0; i < body.length; i++) h = ((h << 5) + h + body.charCodeAt(i)) >>> 0
127
+ return h.toString(16).padStart(8, '0')
128
+ }
129
+
130
+ export function getRequiredTemplateContextGroups(id: string): string[] {
131
+ return OFFICIAL_TEMPLATES[id]?.contextGroups ?? []
132
+ }
133
+
134
+ /** 把官方 writer 骨架渲染成可附加到现有系统提示词末尾的约束/自查块。 */
135
+ export function renderOfficialChapterWriterSkeleton(meta: {
136
+ targetChars: number
137
+ minChars: number
138
+ maxChars: number
139
+ pov?: string
140
+ tonePreference?: string
141
+ endingHookPreference?: string
142
+ antiAiRules?: string
143
+ }): string {
144
+ const pov = meta.pov ?? '第三人称有限视角,严格跟随主角所见所知。'
145
+ const tone = meta.tonePreference ?? '文风贴合本书设定,用具体细节与动作推进。'
146
+ const hook = meta.endingHookPreference ?? '章末留一个明确的钩子(新信息、新风险或未闭合的选择)。'
147
+ const antiAi = meta.antiAiRules ?? ''
148
+ return [
149
+ '==================== 官方生成骨架(必达 / 禁止 / 输出前自查) ====================',
150
+ '【叙事视角】' + pov,
151
+ '【本章必达】本章必须发生实质变化(局面、关系、信息、风险、决策至少一项);开头迅速进入情境,禁止复述上一章。',
152
+ '【禁止事项】不得写总结/复盘/解释性段落为主;不得引入新的核心角色或与上下文冲突的设定;不得为空凑字数。',
153
+ '【篇幅】目标 ' + meta.targetChars + ' 字,区间 ' + meta.minChars + '-' + meta.maxChars + ' 字;不够就继续推进有效情节,禁止草草收尾。',
154
+ '【结尾】' + hook,
155
+ '【表达】优先用具体动作、对话与可感知细节推进;' + tone,
156
+ '【反 AI】' + antiAi,
157
+ '【输出前自查】先确认:读者回报、关键转折、章末净变化是否可见,旧钩子责任是否回应,人物硬事实是否违背;确认通过后再输出,正文中不要输出核查结果。',
158
+ ].join('\n')
159
+ }