dsh-lifecard 0.1.1 → 0.2.0
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 +62 -1
- package/lib/career.js +488 -0
- package/lib/client.js +1121 -67
- package/lib/game.js +373 -0
- package/lib/index.js +816 -7
- package/lib/novel.js +567 -0
- package/lib/presets.js +424 -0
- package/lib/store.js +86 -15
- package/lib/tavern.js +56 -1
- package/package.json +6 -2
package/lib/novel.js
ADDED
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* novel —— 写小说:一本「书」、一章一章写下去。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:写小说和「人物卡」不是同一件事。一张卡是「一个人是谁」,
|
|
5
|
+
* 一本书是「一件事怎么发生」。共用同一份卡和世界书,但章节要的是另一套东西:
|
|
6
|
+
* 顺序、前后文、每章想推进什么。
|
|
7
|
+
*
|
|
8
|
+
* 落盘形状(用户拿 Finder 就能看、能改):
|
|
9
|
+
* ```
|
|
10
|
+
* books/<书 id>/
|
|
11
|
+
* book.md 一本书:书名、题材、一句话讲什么
|
|
12
|
+
* chapters/001.md 第一章
|
|
13
|
+
* chapters/002.md 第二章
|
|
14
|
+
* ```
|
|
15
|
+
* 为什么不塞成一个文件:一章动辄几千字,全挤在一份里既难读也难改;
|
|
16
|
+
* 分文件之后,用户想单独再看某一章、想用别的编辑器改,都方便。
|
|
17
|
+
*
|
|
18
|
+
* 这一层只碰磁盘与文字:不调模型、不碰 HTTP。路由在 index.js,界面在 client.js。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import fs from 'node:fs/promises'
|
|
22
|
+
import path from 'node:path'
|
|
23
|
+
import * as core from './core.js'
|
|
24
|
+
|
|
25
|
+
/** 一本书放在工作区的哪个文件夹里。 */
|
|
26
|
+
export const BOOK_DIR = 'books'
|
|
27
|
+
|
|
28
|
+
/** 一章最多建议多少字——超过就提示「这一章有点长了」。不是硬限制。 */
|
|
29
|
+
export const CHAPTER_SOFT_LIMIT = 6000
|
|
30
|
+
|
|
31
|
+
/** 一本书最多留多少章(防止误操作长出一万个空章)。 */
|
|
32
|
+
export const MAX_CHAPTERS = 999
|
|
33
|
+
|
|
34
|
+
/** 书 id:来自书名,过一遍 safeId(中文保留)。 */
|
|
35
|
+
export function bookIdOf(title) {
|
|
36
|
+
return core.safeId(String(title ?? '').trim() === '' ? '未命名' : title)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 书的目录(工作区相对路径)。 */
|
|
40
|
+
export function bookRelPath(id) {
|
|
41
|
+
return path.posix.join(BOOK_DIR, bookFolderName(id))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 把书名/目录名收成一段安全的文件夹名。
|
|
46
|
+
*
|
|
47
|
+
* `core.safeId` 只替换 `\ / : * ? " < > | # %` 和空白,**`.` 和 `..` 会原样过去**。
|
|
48
|
+
* 而 `path.posix.join('books', '..')` 是 `'.'`、`join('books', '.')` 是 `'books'`,
|
|
49
|
+
* 于是 `deleteBook('..')` 里的 `fs.rm(root + '.', {recursive:true})` 会把**整个工作区**
|
|
50
|
+
* ——卡、材料、提案、`.lifecard/snapshots` ——一次删光。这不是理论问题:
|
|
51
|
+
* id 从书名来,而书名是用户能打出来的。
|
|
52
|
+
*
|
|
53
|
+
* 所以这里单独收一道:去掉首尾的点、把连续的 `.` 压成一个,只剩点的时候退回「未命名」。
|
|
54
|
+
*/
|
|
55
|
+
export function bookFolderName(id) {
|
|
56
|
+
const raw = String(id ?? '').trim()
|
|
57
|
+
let name = core.safeId(raw)
|
|
58
|
+
name = name.replace(/^\.+/, '').replace(/\.+$/, '').replace(/\.{2,}/g, '.')
|
|
59
|
+
if (name === '' || name === '.' || /^\.+$/.test(name)) name = '未命名'
|
|
60
|
+
if (name === BOOK_DIR) name = `${BOOK_DIR}-book`
|
|
61
|
+
return name
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* 书目录的绝对路径。所有读写都从这里出去,并且**再确认一次**落在 `books/` 里面
|
|
66
|
+
* (`bookFolderName` 已经把危险形状挡住,这里是第二道,防以后有人绕过它拼路径)。
|
|
67
|
+
*/
|
|
68
|
+
export function bookAbs(root, id) {
|
|
69
|
+
const rel = bookRelPath(id)
|
|
70
|
+
const abs = path.join(root, rel)
|
|
71
|
+
const base = path.join(root, BOOK_DIR)
|
|
72
|
+
if (abs !== base && !abs.startsWith(base + path.sep)) return null
|
|
73
|
+
return abs
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 章文件名:`001.md` —— 补零到三位,字典序就是章序。 */
|
|
77
|
+
export function chapterFileName(index) {
|
|
78
|
+
const n = Math.max(1, Math.min(MAX_CHAPTERS, Math.floor(Number(index) || 1)))
|
|
79
|
+
return `${String(n).padStart(3, '0')}.md`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 从 `002.md` 反解出章号。认不出返回 0。 */
|
|
83
|
+
export function chapterIndexOf(fileName) {
|
|
84
|
+
const m = /^(\d{1,3})\.md$/i.exec(String(fileName ?? ''))
|
|
85
|
+
return m === null ? 0 : Number(m[1])
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 一本书的 Markdown。
|
|
90
|
+
*
|
|
91
|
+
* 只用 frontmatter + 一段正文,不用 `##` 小节:书的元信息本来就少
|
|
92
|
+
* (书名、题材、一句话、主要人物),塞成小节反而看着空。
|
|
93
|
+
*/
|
|
94
|
+
export function renderBookMarkdown(data) {
|
|
95
|
+
const head = { lifecard: core.DATA_VERSION, kind: 'book', ...data }
|
|
96
|
+
const lines = ['---']
|
|
97
|
+
for (const [key, value] of Object.entries(head)) {
|
|
98
|
+
if (value === undefined) continue
|
|
99
|
+
if (value !== null && typeof value === 'object') continue
|
|
100
|
+
lines.push(`${key}: ${JSON.stringify(String(value))}`)
|
|
101
|
+
}
|
|
102
|
+
lines.push('---', '')
|
|
103
|
+
const idea = String(data?.idea ?? '').trim()
|
|
104
|
+
if (idea !== '') lines.push(idea, '')
|
|
105
|
+
return `${lines.join('\n').trimEnd()}\n`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 反过来:把 book.md 读成 `{data, idea}`。 */
|
|
109
|
+
export function parseBookText(text) {
|
|
110
|
+
const parsed = core.parseCard(String(text ?? ''))
|
|
111
|
+
if (parsed.ok !== true) {
|
|
112
|
+
return { ok: false, error: `这本书的说明读不出来:${(parsed.errors ?? []).join(';') || '格式不对'}` }
|
|
113
|
+
}
|
|
114
|
+
const intro = (parsed.sections ?? []).find((s) => s.title === '_intro')
|
|
115
|
+
return { ok: true, data: parsed.data ?? {}, idea: String(intro?.body ?? '').trim() }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 读一本书(含章节清单,不含各章正文——章节可能很多)。 */
|
|
119
|
+
export async function readBook(root, id) {
|
|
120
|
+
const rel = path.posix.join(bookRelPath(id), 'book.md')
|
|
121
|
+
const abs = path.join(root, rel)
|
|
122
|
+
let text
|
|
123
|
+
try {
|
|
124
|
+
text = await fs.readFile(abs, 'utf8')
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (error?.code === 'ENOENT') return { ok: false, error: '这本书不在了' }
|
|
127
|
+
return { ok: false, error: '这本书的命令行读不出来。检查一下文件夹权限。' }
|
|
128
|
+
}
|
|
129
|
+
const parsed = parseBookText(text)
|
|
130
|
+
if (parsed.ok !== true) return parsed
|
|
131
|
+
const chapters = await listChapters(root, id)
|
|
132
|
+
if (chapters.ok !== true) return chapters
|
|
133
|
+
return { ok: true, path: rel, data: parsed.data, idea: parsed.idea, chapters: chapters.chapters }
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 列一本书的章节(按章号排)。 */
|
|
137
|
+
export async function listChapters(root, id) {
|
|
138
|
+
const dir = path.join(root, bookRelPath(id), 'chapters')
|
|
139
|
+
let names
|
|
140
|
+
try {
|
|
141
|
+
names = await fs.readdir(dir)
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error?.code === 'ENOENT') return { ok: true, chapters: [] }
|
|
144
|
+
return { ok: false, error: '章节列表读不出来。检查一下文件夹权限。' }
|
|
145
|
+
}
|
|
146
|
+
const chapters = []
|
|
147
|
+
for (const name of names) {
|
|
148
|
+
const index = chapterIndexOf(name)
|
|
149
|
+
if (index === 0) continue
|
|
150
|
+
const abs = path.join(dir, name)
|
|
151
|
+
const stat = await fs.stat(abs).catch(() => null)
|
|
152
|
+
if (stat === null || !stat.isFile()) continue
|
|
153
|
+
let title = ''
|
|
154
|
+
try {
|
|
155
|
+
const text = await fs.readFile(abs, 'utf8')
|
|
156
|
+
// 章题取正文第一行(`# 标题`)或第一句
|
|
157
|
+
const first = text.split(/\r?\n/).find((line) => line.trim() !== '') ?? ''
|
|
158
|
+
title = first.replace(/^#+\s*/, '').trim().slice(0, 60)
|
|
159
|
+
} catch {
|
|
160
|
+
title = ''
|
|
161
|
+
}
|
|
162
|
+
chapters.push({
|
|
163
|
+
index,
|
|
164
|
+
file: name,
|
|
165
|
+
path: path.posix.join(bookRelPath(id), 'chapters', name),
|
|
166
|
+
title,
|
|
167
|
+
chars: stat.size,
|
|
168
|
+
mtime: stat.mtime.toISOString(),
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
chapters.sort((a, b) => a.index - b.index)
|
|
172
|
+
return { ok: true, chapters }
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 读一章的正文。 */
|
|
176
|
+
export async function readChapter(root, id, index) {
|
|
177
|
+
const n = chapterIndexOf(chapterFileName(index))
|
|
178
|
+
if (n === 0) return { ok: false, error: '章号不对' }
|
|
179
|
+
const rel = path.posix.join(bookRelPath(id), 'chapters', chapterFileName(n))
|
|
180
|
+
let text
|
|
181
|
+
try {
|
|
182
|
+
text = await fs.readFile(path.join(root, rel), 'utf8')
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error?.code === 'ENOENT') return { ok: false, error: `第 ${n} 章还没写` }
|
|
185
|
+
return { ok: false, error: '这一章读不出来。检查一下文件夹权限。' }
|
|
186
|
+
}
|
|
187
|
+
return { ok: true, index: n, path: rel, body: text }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 写一章。`index` 给 0 表示「接在最后一章后面」。
|
|
192
|
+
*
|
|
193
|
+
* 写盘用「临时文件 + 改名」:正文是整章重写,掉电/磁盘满的时候
|
|
194
|
+
* 原来那一章必须还是完整的(和酒馆会话一个道理)。
|
|
195
|
+
*/
|
|
196
|
+
export async function writeChapter(root, id, index, body, when = new Date()) {
|
|
197
|
+
const book = await readBook(root, id)
|
|
198
|
+
if (book.ok !== true) return book
|
|
199
|
+
const last = book.chapters.length === 0 ? 0 : book.chapters[book.chapters.length - 1].index
|
|
200
|
+
let n = Number(index) || 0
|
|
201
|
+
if (n <= 0) n = last + 1
|
|
202
|
+
if (n > MAX_CHAPTERS) return { ok: false, error: `一本书最多 ${MAX_CHAPTERS} 章。` }
|
|
203
|
+
const rel = path.posix.join(bookRelPath(id), 'chapters', chapterFileName(n))
|
|
204
|
+
const abs = path.join(root, rel)
|
|
205
|
+
await fs.mkdir(path.dirname(abs), { recursive: true })
|
|
206
|
+
const text = String(body ?? '')
|
|
207
|
+
try {
|
|
208
|
+
const tmp = `${abs}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
209
|
+
await fs.writeFile(tmp, text, 'utf8')
|
|
210
|
+
await fs.rename(tmp, abs)
|
|
211
|
+
} catch {
|
|
212
|
+
return { ok: false, error: '这一章没能存下来。检查一下磁盘是不是满了。' }
|
|
213
|
+
}
|
|
214
|
+
// 书的 last_updated 跟着动。这一步失败了也要如实说:章节确实存下来了,
|
|
215
|
+
// 只是书的「最后改过」没更新——不能报成功,也不能报「整章没存」。
|
|
216
|
+
const nextData = { ...book.data, updated_at: when.toISOString() }
|
|
217
|
+
const touched = await writeBookMeta(root, id, nextData, book.idea)
|
|
218
|
+
return { ok: true, index: n, path: rel, chars: text.length, warning: touched.ok === true ? undefined : touched.error }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 删一章。删完不重排章号——用户手里的「第三章」不会突然变成第二章。 */
|
|
222
|
+
export async function deleteChapter(root, id, index) {
|
|
223
|
+
const n = chapterIndexOf(chapterFileName(index))
|
|
224
|
+
if (n === 0) return { ok: false, error: '章号不对' }
|
|
225
|
+
const rel = path.posix.join(bookRelPath(id), 'chapters', chapterFileName(n))
|
|
226
|
+
try {
|
|
227
|
+
await fs.unlink(path.join(root, rel))
|
|
228
|
+
} catch (error) {
|
|
229
|
+
if (error?.code === 'ENOENT') return { ok: true, gone: true }
|
|
230
|
+
return { ok: false, error: '这一章没能删掉。检查一下文件权限。' }
|
|
231
|
+
}
|
|
232
|
+
return { ok: true, index: n }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** 写书的元信息(book.md)。 */
|
|
236
|
+
async function writeBookMeta(root, id, data, idea) {
|
|
237
|
+
const rel = path.posix.join(bookRelPath(id), 'book.md')
|
|
238
|
+
const abs = path.join(root, rel)
|
|
239
|
+
await fs.mkdir(path.dirname(abs), { recursive: true })
|
|
240
|
+
const text = renderBookMarkdown({ ...data, idea: String(idea ?? '').trim() })
|
|
241
|
+
const tmp = `${abs}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
242
|
+
// 这里必须自己兜住:`writeChapter` 是先写章、再更新这本书的
|
|
243
|
+
// 「最后改过的时间」。更新这一步抛出去,调用方只会看到一句通用的失败,
|
|
244
|
+
// 而那一章其实已经在盘上了——用户以为没存,再写一次就多出一章。
|
|
245
|
+
try {
|
|
246
|
+
await fs.writeFile(tmp, text, 'utf8')
|
|
247
|
+
await fs.rename(tmp, abs)
|
|
248
|
+
} catch {
|
|
249
|
+
await fs.rm(tmp, { force: true }).catch(() => {})
|
|
250
|
+
return { ok: false, path: rel, error: '这本书的记录没能更新(章节本身可能已经存下来了)。检查一下磁盘空间。' }
|
|
251
|
+
}
|
|
252
|
+
return { ok: true, path: rel }
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 新建一本书。同名不覆盖——另起一个号。 */
|
|
256
|
+
export async function createBook(root, input = {}) {
|
|
257
|
+
const title = String(input.title ?? '').trim() === '' ? '未命名' : String(input.title).trim()
|
|
258
|
+
const stem = bookIdOf(title)
|
|
259
|
+
let id = stem
|
|
260
|
+
let free = false
|
|
261
|
+
for (let n = 1; n <= 200; n += 1) {
|
|
262
|
+
id = n === 1 ? stem : `${stem}-${n}`
|
|
263
|
+
const exists = await fs.stat(path.join(root, bookRelPath(id), 'book.md')).then((s) => s.isFile()).catch(() => false)
|
|
264
|
+
if (!exists) { free = true; break }
|
|
265
|
+
}
|
|
266
|
+
// 循环跑完还占不到位置时必须报错。以前这里出了循环就直接往下写,
|
|
267
|
+
// 于是同名第 201 本会**覆盖**看上去是第 200 本的那本 —— 而函数注释
|
|
268
|
+
// 明明写着「同名不覆盖」。
|
|
269
|
+
if (!free) return { ok: false, error: `同名「${title}」的书已经太多了,换个书名再建。` }
|
|
270
|
+
const now = new Date()
|
|
271
|
+
const data = {
|
|
272
|
+
id,
|
|
273
|
+
title,
|
|
274
|
+
genre: String(input.genre ?? '').trim(),
|
|
275
|
+
created_at: now.toISOString(),
|
|
276
|
+
updated_at: now.toISOString(),
|
|
277
|
+
}
|
|
278
|
+
const written = await writeBookMeta(root, id, data, input.idea)
|
|
279
|
+
if (written.ok !== true) return written
|
|
280
|
+
return { ok: true, id, path: written.path, title }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** 改一本书的元信息(书名、题材、一句话)。 */
|
|
284
|
+
export async function updateBook(root, id, patch = {}) {
|
|
285
|
+
const book = await readBook(root, id)
|
|
286
|
+
if (book.ok !== true) return book
|
|
287
|
+
const data = { ...book.data }
|
|
288
|
+
if (typeof patch.title === 'string' && patch.title.trim() !== '') data.title = patch.title.trim()
|
|
289
|
+
if (typeof patch.genre === 'string') data.genre = patch.genre.trim()
|
|
290
|
+
data.updated_at = new Date().toISOString()
|
|
291
|
+
const idea = typeof patch.idea === 'string' ? patch.idea : book.idea
|
|
292
|
+
return writeBookMeta(root, id, data, idea)
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** 删一整本书(连章节)。 */
|
|
296
|
+
export async function deleteBook(root, id) {
|
|
297
|
+
const rel = bookRelPath(id)
|
|
298
|
+
// 第二道闸:删之前亲自确认这一条真的在 books/ 里面,且不是 books 本身。
|
|
299
|
+
// 递归删掉的地方错一次就没有第二次机会,所以这里宁可多判一次。
|
|
300
|
+
if (!rel.startsWith(`${BOOK_DIR}/`) || rel === BOOK_DIR || rel.includes('..')) {
|
|
301
|
+
return { ok: false, error: '这个书名不对,没删。' }
|
|
302
|
+
}
|
|
303
|
+
const abs = bookAbs(root, id)
|
|
304
|
+
if (abs === null || abs === path.join(root, BOOK_DIR)) return { ok: false, error: '这个书名不对,没删。' }
|
|
305
|
+
try {
|
|
306
|
+
await fs.rm(abs, { recursive: true, force: true })
|
|
307
|
+
} catch {
|
|
308
|
+
return { ok: false, error: '这本书没能删掉。检查一下文件权限。' }
|
|
309
|
+
}
|
|
310
|
+
return { ok: true }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** 列所有书(按最后改动时间倒序)。 */
|
|
314
|
+
export async function listBooks(root) {
|
|
315
|
+
const dir = path.join(root, BOOK_DIR)
|
|
316
|
+
let names
|
|
317
|
+
try {
|
|
318
|
+
names = await fs.readdir(dir, { withFileTypes: true })
|
|
319
|
+
} catch (error) {
|
|
320
|
+
if (error?.code === 'ENOENT') return { ok: true, books: [] }
|
|
321
|
+
return { ok: false, error: '书架读不出来。检查一下文件夹权限。' }
|
|
322
|
+
}
|
|
323
|
+
const books = []
|
|
324
|
+
for (const entry of names) {
|
|
325
|
+
if (!entry.isDirectory()) continue
|
|
326
|
+
const got = await readBook(root, entry.name)
|
|
327
|
+
if (got.ok !== true) continue
|
|
328
|
+
books.push({
|
|
329
|
+
id: String(got.data?.id ?? entry.name),
|
|
330
|
+
title: String(got.data?.title ?? entry.name),
|
|
331
|
+
genre: String(got.data?.genre ?? ''),
|
|
332
|
+
idea: String(got.idea ?? '').slice(0, 80),
|
|
333
|
+
chapters: got.chapters.length,
|
|
334
|
+
words: got.chapters.reduce((n, c) => n + c.chars, 0),
|
|
335
|
+
updated_at: String(got.data?.updated_at ?? ''),
|
|
336
|
+
})
|
|
337
|
+
}
|
|
338
|
+
books.sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)))
|
|
339
|
+
return { ok: true, books }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* 「先规划,再写」——三段式的第一段:让 AI 把这本书的骨架搭出来。
|
|
344
|
+
*
|
|
345
|
+
* 为什么非要先规划:一口气让它「写一本小说」,它会写出一段很像开头的东西
|
|
346
|
+
* 然后停下来,而且写着写着就跑偏——因为没有人告诉它这本书要往哪走。
|
|
347
|
+
* OpenWrite 那套的核心就是这个:先把大纲钉住,再一章一章往里填。
|
|
348
|
+
*
|
|
349
|
+
* 产出是一份人看得懂的大纲(不是 JSON):每章一行,写清这一章要发生什么。
|
|
350
|
+
* 用户能直接改,改完再让它写——比让它吐结构化数据实在得多。
|
|
351
|
+
*/
|
|
352
|
+
export function buildOutlinePrompt({ title, genre, idea, cast, worldEntries, chapters, ask }) {
|
|
353
|
+
const lines = [
|
|
354
|
+
`你在帮一个人规划一部长篇小说。这本书叫《${title}》。`,
|
|
355
|
+
]
|
|
356
|
+
if (genre !== '') lines.push(`题材:${genre}`)
|
|
357
|
+
if (idea !== '') lines.push(`这本书想讲的是:${idea}`)
|
|
358
|
+
if (Array.isArray(worldEntries) && worldEntries.length > 0) {
|
|
359
|
+
lines.push('', '【这个世界的设定】', worldEntries.join('\n\n'))
|
|
360
|
+
}
|
|
361
|
+
if (Array.isArray(cast) && cast.length > 0) {
|
|
362
|
+
lines.push('', '【主要人物】', cast.join('\n'))
|
|
363
|
+
}
|
|
364
|
+
if (String(ask ?? '').trim() !== '') lines.push('', `作者另外说:${String(ask).trim()}`)
|
|
365
|
+
lines.push(
|
|
366
|
+
'',
|
|
367
|
+
'【怎么做】',
|
|
368
|
+
`先想清楚这本书的整体走向,然后拆成 ${Number(chapters) > 0 ? chapters : 12} 章。`,
|
|
369
|
+
'',
|
|
370
|
+
'输出格式(严格遵守,我要直接拿这份当写作计划):',
|
|
371
|
+
'',
|
|
372
|
+
'第一行写整本书的**主线**,用一句话,开头写「主线:」。',
|
|
373
|
+
'然后每章一段,格式是:',
|
|
374
|
+
'',
|
|
375
|
+
'第1章 这一章要发生的事(一句话,要具体:谁做了什么、结果如何)',
|
|
376
|
+
'第2章 …',
|
|
377
|
+
'',
|
|
378
|
+
'【要求】',
|
|
379
|
+
'- 每章那一句必须是**具体发生的事**,不能是「主角成长了」这种空话。',
|
|
380
|
+
'- 章与章之间要有因果:这一章的结果推动下一章。',
|
|
381
|
+
'- 不要写章节标题的花活(不要「命运的齿轮」这种),就写发生了什么。',
|
|
382
|
+
'- 最后一行写「结局:」加一句话,说清这本书最后落在哪儿。',
|
|
383
|
+
'- 不要解释、不要评论、不要问我要不要继续,直接给这份计划。',
|
|
384
|
+
)
|
|
385
|
+
return lines.join('\n')
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** 从 AI 吐回来的大纲里扒出主线、各章、结局(它常常多写几句废话)。 */
|
|
389
|
+
export function parseOutline(text) {
|
|
390
|
+
const raw = String(text ?? '')
|
|
391
|
+
const line = (re) => {
|
|
392
|
+
const hit = re.exec(raw)
|
|
393
|
+
return hit === null ? '' : String(hit[1] ?? '').trim()
|
|
394
|
+
}
|
|
395
|
+
const theme = line(/(?:^|\n)\s*主线[::]\s*(.+)/)
|
|
396
|
+
const ending = line(/(?:^|\n)\s*结局[::]\s*(.+)/)
|
|
397
|
+
const chapters = []
|
|
398
|
+
const re = /(?:^|\n)\s*第\s*(\d+)\s*章\s*[::、..\s]\s*(.+)/g
|
|
399
|
+
let m = re.exec(raw)
|
|
400
|
+
while (m !== null) {
|
|
401
|
+
chapters.push({ index: Number(m[1]), plan: String(m[2]).trim() })
|
|
402
|
+
m = re.exec(raw)
|
|
403
|
+
}
|
|
404
|
+
chapters.sort((a, b) => a.index - b.index)
|
|
405
|
+
return { ok: chapters.length > 0, theme, ending, chapters }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* 拼「接着写这一章」的话:这一章已经写了什么 + 大纲 + 上一章结尾 + 设定。
|
|
410
|
+
*
|
|
411
|
+
* 四样都给,少一样它就会开始自己编:只给上一章,它不知道这本书要往哪走;
|
|
412
|
+
* 只给设定,它不知道刚才发生了什么;不给大纲,它会一章一章拖成流水账。
|
|
413
|
+
*/
|
|
414
|
+
export function buildChapterPrompt({ title, idea, genre, previousTail, currentBody, ask, worldEntries, cast, outline, chapterPlan }) {
|
|
415
|
+
const lines = []
|
|
416
|
+
lines.push(`你在帮一个人写小说。这本书叫《${title}》。`)
|
|
417
|
+
if (genre !== '') lines.push(`题材:${genre}`)
|
|
418
|
+
if (idea !== '') lines.push(`这本书想讲的是:${idea}`)
|
|
419
|
+
|
|
420
|
+
const plan = String(chapterPlan ?? '').trim()
|
|
421
|
+
if (plan !== '') {
|
|
422
|
+
lines.push('', '【这一章要写的事】', plan)
|
|
423
|
+
}
|
|
424
|
+
const outlineText = String(outline ?? '').trim()
|
|
425
|
+
if (outlineText !== '') {
|
|
426
|
+
lines.push('', '【整本书的计划】(只写你正在写的那一章,别提前写后面的)', outlineText)
|
|
427
|
+
}
|
|
428
|
+
if (Array.isArray(worldEntries) && worldEntries.length > 0) {
|
|
429
|
+
lines.push('', '【这个世界的设定】', worldEntries.join('\n\n'))
|
|
430
|
+
}
|
|
431
|
+
if (Array.isArray(cast) && cast.length > 0) {
|
|
432
|
+
lines.push('', '【出场的人】', cast.join('\n'))
|
|
433
|
+
}
|
|
434
|
+
if (String(previousTail ?? '').trim() !== '') {
|
|
435
|
+
lines.push('', '【上一章的结尾】', String(previousTail).trim())
|
|
436
|
+
}
|
|
437
|
+
if (String(currentBody ?? '').trim() !== '') {
|
|
438
|
+
lines.push('', '【这一章已经写到这里】', String(currentBody).trim())
|
|
439
|
+
}
|
|
440
|
+
lines.push(
|
|
441
|
+
'',
|
|
442
|
+
'【怎么写】',
|
|
443
|
+
'- 直接写正文,不要复述设定,不要写「好的,我来写」这种话。',
|
|
444
|
+
'- 接着上面的情节往下,不要重写已经写过的部分。',
|
|
445
|
+
'- 段落自然、句子长短交错;不要每段都用同一个句式开头。',
|
|
446
|
+
'- 不要替读者总结「这说明了他很孤独」;把事写出来,让读者自己看出来。',
|
|
447
|
+
'- 不写章节标题,标题我自己加。',
|
|
448
|
+
'- 只写这一章,写到该收的地方就停,不要顺手把下一章也开了头。',
|
|
449
|
+
'',
|
|
450
|
+
ask === undefined || String(ask).trim() === '' ? '请写这一章,大约 800 到 1200 字。' : `这次想写的是:${String(ask).trim()}`,
|
|
451
|
+
)
|
|
452
|
+
return lines.join('\n')
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 大纲落盘:`books/<id>/outline.md`。
|
|
457
|
+
*
|
|
458
|
+
* 单独一份文件而不是塞进 book.md:大纲是**人会在上面反复改的东西**,
|
|
459
|
+
* 和「书名、题材」那种填一次就不动的元信息不是一个性质。
|
|
460
|
+
* 它也是「AI 写第几章」时唯一的依据,用户改一行就能改变整本书的走向。
|
|
461
|
+
*/
|
|
462
|
+
export async function readOutline(root, id) {
|
|
463
|
+
const rel = path.posix.join(bookRelPath(id), 'outline.md')
|
|
464
|
+
try {
|
|
465
|
+
const text = await fs.readFile(path.join(root, rel), 'utf8')
|
|
466
|
+
return { ok: true, text, ...parseOutline(text) }
|
|
467
|
+
} catch (error) {
|
|
468
|
+
if (error?.code === 'ENOENT') return { ok: true, text: '', theme: '', ending: '', chapters: [], missing: true }
|
|
469
|
+
return { ok: false, error: '大纲读不出来。检查一下文件权限。' }
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** 写大纲(整份覆盖)。 */
|
|
474
|
+
export async function writeOutline(root, id, text) {
|
|
475
|
+
const rel = path.posix.join(bookRelPath(id), 'outline.md')
|
|
476
|
+
const abs = path.join(root, rel)
|
|
477
|
+
await fs.mkdir(path.dirname(abs), { recursive: true })
|
|
478
|
+
try {
|
|
479
|
+
const tmp = `${abs}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
480
|
+
await fs.writeFile(tmp, String(text ?? ''), 'utf8')
|
|
481
|
+
await fs.rename(tmp, abs)
|
|
482
|
+
} catch {
|
|
483
|
+
return { ok: false, error: '大纲没能存下来。检查一下磁盘是不是满了。' }
|
|
484
|
+
}
|
|
485
|
+
const parsed = parseOutline(text)
|
|
486
|
+
return { ok: true, path: rel, chapters: parsed.chapters.length, theme: parsed.theme, ending: parsed.ending }
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** 取一章结尾的若干字(给下一章当「上一章结尾」)。 */
|
|
490
|
+
/**
|
|
491
|
+
* 把一场酒馆对话改写成小说的正文。
|
|
492
|
+
*
|
|
493
|
+
* 为什么不让它「原样搬」:屏幕上是两个人的对白,直接贴进小说里是剧本,
|
|
494
|
+
* 不是小说。要的是把「谁在什么时候说了什么、说的时候是什么样子」
|
|
495
|
+
* 变成叙述。所以要求它保留对话原意,但不许加新的情节。
|
|
496
|
+
*/
|
|
497
|
+
export function buildChatToChapterPrompt({ cardName, bookTitle, turns, note }) {
|
|
498
|
+
const lines = []
|
|
499
|
+
lines.push('你在把一段已经发生过的对话,改写成小说的正文。')
|
|
500
|
+
lines.push('')
|
|
501
|
+
lines.push('## 对话里的人')
|
|
502
|
+
lines.push(`- ${String(cardName ?? '').trim() === '' ? '对方' : cardName}(对话里的「TA」)`)
|
|
503
|
+
lines.push('- 「我」(对话里的「我」,在小说里也用「我」)')
|
|
504
|
+
lines.push('')
|
|
505
|
+
|
|
506
|
+
lines.push('## 这一场谈了什么')
|
|
507
|
+
for (const turn of turns) {
|
|
508
|
+
const who = String(turn?.who ?? '').trim() === '我' ? '我' : (String(cardName ?? '').trim() === '' ? 'TA' : cardName)
|
|
509
|
+
lines.push(`${who}:${String(turn?.text ?? '').trim()}`)
|
|
510
|
+
}
|
|
511
|
+
lines.push('')
|
|
512
|
+
|
|
513
|
+
if (String(note ?? '').trim() !== '') {
|
|
514
|
+
lines.push('## 这一章要往哪走')
|
|
515
|
+
lines.push(String(note).trim())
|
|
516
|
+
lines.push('')
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const system = [
|
|
520
|
+
'你是在改稿,不是在下判断。只说要做的事,不要评价这段对话好不好。',
|
|
521
|
+
'',
|
|
522
|
+
'硬要求:',
|
|
523
|
+
'1. 写成小说正文,不是剧本。不要「A:xxx」这种一行一句的形式,谁说了什么要揉进叙述里。',
|
|
524
|
+
'2. 对话的意思要保住。别删掉关键的那几句,也别替他们加没说过的内容。',
|
|
525
|
+
'3. 可以把动作、停顿、屋里的样子补出来——只补「当时本来就在那儿」的东西。',
|
|
526
|
+
'4. 不许加新的情节,不许替角色做决定,不许在结尾下判断或总结道理。',
|
|
527
|
+
'5. 写 800 到 1500 字。不要小标题,不要分段编号,不要写「本章完」。',
|
|
528
|
+
'6. 不要用「命运的齿轮」「不禁」「仿佛」这类词。',
|
|
529
|
+
'',
|
|
530
|
+
`这本书叫《${String(bookTitle ?? '').trim() === '' ? '没起名' : bookTitle}》。`,
|
|
531
|
+
].join('\n')
|
|
532
|
+
|
|
533
|
+
return { system, user: lines.join('\n') }
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export function tailOf(body, chars = 600) {
|
|
537
|
+
const text = String(body ?? '').trim()
|
|
538
|
+
if (text.length <= chars) return text
|
|
539
|
+
return `…${text.slice(-chars)}`
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export default {
|
|
543
|
+
BOOK_DIR,
|
|
544
|
+
CHAPTER_SOFT_LIMIT,
|
|
545
|
+
MAX_CHAPTERS,
|
|
546
|
+
bookIdOf,
|
|
547
|
+
bookRelPath,
|
|
548
|
+
chapterFileName,
|
|
549
|
+
chapterIndexOf,
|
|
550
|
+
renderBookMarkdown,
|
|
551
|
+
parseBookText,
|
|
552
|
+
readBook,
|
|
553
|
+
listChapters,
|
|
554
|
+
readChapter,
|
|
555
|
+
writeChapter,
|
|
556
|
+
deleteChapter,
|
|
557
|
+
createBook,
|
|
558
|
+
updateBook,
|
|
559
|
+
deleteBook,
|
|
560
|
+
listBooks,
|
|
561
|
+
buildChapterPrompt,
|
|
562
|
+
buildOutlinePrompt,
|
|
563
|
+
parseOutline,
|
|
564
|
+
readOutline,
|
|
565
|
+
writeOutline,
|
|
566
|
+
tailOf,
|
|
567
|
+
}
|