dsh-lifecard 0.2.0 → 0.2.2

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.
@@ -0,0 +1,805 @@
1
+ /**
2
+ * lifecard-tools — 把 LifeCard 里的人物卡、世界书交给 DSH 自己的对话。
3
+ *
4
+ * 为什么单独一个文件:酒馆和写小说原来是在插件自己的界面里说话。用户要的是
5
+ * 「和正常对话一样,在新会话里打开」——那就不能自建聊天框,得让 DSH 的普通
6
+ * 会话能读到这些卡。这个文件就是那条通路:一组只读工具,模型想演谁、想写谁,
7
+ * 先来这儿把人和世界取走。
8
+ *
9
+ * 只读。改卡还是走插件界面,免得模型手一滑把用户写的东西洗掉。
10
+ *
11
+ * 挂法(见 cordis.patch.yml):宿主那一层插一行本文件,预设里的
12
+ * plugins 再引用一次,于是「LC 酒馆 / LC 小说」这些门里也能用。
13
+ */
14
+ import path from 'node:path'
15
+ import os from 'node:os'
16
+ import { readdir } from 'node:fs/promises'
17
+
18
+ import * as core from './lib/core.js'
19
+ import * as store from './lib/store.js'
20
+
21
+ // 这几个和 lib/index.js 里是同一套约定。故意在这里重写一遍、不从 index.js
22
+ // import:工具是被主插件在 apply 里调起来的,反过来 import index.js 会绕成
23
+ // 循环依赖,宿主加载时可能拿到半截模块。
24
+ function dshHome() {
25
+ const fromEnv = process.env.DSH_HOME
26
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(fromEnv)
27
+ return path.join(os.homedir(), '.dsh')
28
+ }
29
+
30
+ function pointerFile() {
31
+ return path.join(dshHome(), 'plugin-data', 'dsh-lifecard.json')
32
+ }
33
+
34
+ async function recalledWorkspace() {
35
+ try {
36
+ const { readFile } = await import('node:fs/promises')
37
+ const raw = await readFile(pointerFile(), 'utf8')
38
+ const parsed = JSON.parse(raw)
39
+ return typeof parsed?.workspace === 'string' && parsed.workspace.trim() !== '' ? path.resolve(parsed.workspace) : ''
40
+ } catch {
41
+ return ''
42
+ }
43
+ }
44
+
45
+ function defaultRoot() {
46
+ return path.join(os.homedir(), 'LifeCard')
47
+ }
48
+
49
+ const textOutput = {
50
+ schema: {
51
+ type: 'object',
52
+ additionalProperties: false,
53
+ properties: { text: { type: 'string' } },
54
+ required: ['text'],
55
+ },
56
+ render: (_args, value) => [{ type: 'text', text: value.text }],
57
+ }
58
+
59
+ /** 配置里写的路径(支持 ~ 开头)。 */
60
+ function configuredWorkspace(config) {
61
+ const raw = typeof config?.workspace === 'string' ? config.workspace.trim() : ''
62
+ if (raw === '') return ''
63
+ if (raw === '~') return os.homedir()
64
+ if (raw.startsWith('~/')) return path.join(os.homedir(), raw.slice(2))
65
+ return path.resolve(raw)
66
+ }
67
+
68
+ /**
69
+ * 这个工具在哪个文件夹里找卡:
70
+ * ① 预设里写死的 workspace ② 用户在插件里上次选的文件夹 ③ 默认的 ~/LifeCard。
71
+ */
72
+ async function resolveRoot(config) {
73
+ const configured = configuredWorkspace(config)
74
+ if (configured !== '') return configured
75
+ try {
76
+ const recalled = await recalledWorkspace()
77
+ if (typeof recalled === 'string' && recalled !== '') return recalled
78
+ } catch { /* 读不到指针就退回默认位置 */ }
79
+ return defaultRoot()
80
+ }
81
+
82
+ const KIND_LABEL = { real: '现实里的人', fictional: '虚构角色', self: '自己', hybrid: '半真半虚构' }
83
+
84
+ function kindOf(card) {
85
+ const kind = String(card?.kind ?? '')
86
+ return KIND_LABEL[kind] ?? (kind === '' ? '没写是哪种' : kind)
87
+ }
88
+
89
+ /** 「妈妈(现实里的人 · 母亲)」这种一行摘要。 */
90
+ function cardLine(card) {
91
+ const bits = [kindOf(card)]
92
+ const relation = String(card?.relation ?? '').trim()
93
+ if (relation !== '') bits.push(relation)
94
+ const world = String(card?.world ?? '').trim()
95
+ if (world !== '' && world !== 'reality') bits.push(`世界:${world}`)
96
+ return `${card?.name ?? '(还没起名字)'}(${bits.join(' · ')})`
97
+ }
98
+
99
+ /** 按 id / 名字 / 路径找一张卡。 */
100
+ async function findCard(root, wanted) {
101
+ const want = String(wanted ?? '').trim()
102
+ if (want === '') return null
103
+ // findCardByRelOrId 回的是**相对路径**(不是卡本身),按 id 和名字都能查到。
104
+ const rel = await store.findCardByRelOrId(root, want)
105
+ if (typeof rel !== 'string' || rel === '') return null
106
+ const read = await store.readCard(root, rel)
107
+ return read?.ok === true ? read : null
108
+ }
109
+
110
+ /** 读世界书条目;找不到返回空数组。 */
111
+ async function worldEntries(root, wanted) {
112
+ const want = String(wanted ?? '').trim()
113
+ if (want === '') return []
114
+ const all = await store.listAll(root)
115
+ const worlds = Array.isArray(all.worlds) ? all.worlds : []
116
+ const hit = worlds.find((w) => String(w.id ?? '') === want || String(w.name ?? '').trim() === want || String(w.path ?? '') === want)
117
+ if (hit === undefined) return []
118
+ const read = await store.readCard(root, hit.path)
119
+ if (read?.ok !== true) return []
120
+ const parsed = core.parseWorldEntries(read.sections ?? [])
121
+ return Array.isArray(parsed) ? parsed : []
122
+ }
123
+
124
+ function entriesToText(entries) {
125
+ if (entries.length === 0) return '(这本世界书里还没有条目)'
126
+ return entries.map((e, i) => {
127
+ const keys = Array.isArray(e.keys) ? e.keys.join('、') : String(e.keys ?? '')
128
+ const always = e.constant === true ? '(每轮都带上)' : (keys === '' ? '' : `(说到${keys}时带上)`)
129
+ return `${i + 1}. ${String(e.content ?? '').trim()}${always}`
130
+ }).join('\n')
131
+ }
132
+
133
+ /**
134
+ * 把 5 个只读工具挂到 ctx.tools 上。
135
+ *
136
+ * 由 lib/index.js 的 apply 在 tools 服务就绪后调用(宿主那一层注册一次),
137
+ * 所以不只是 LC 三个预设,任何预设里都能调。
138
+ */
139
+ export function registerTools(ctx, config) {
140
+ if (ctx?.tools?.register === undefined) return false
141
+ /** 统一注册:把「字符串或抛错」变成模型看得懂的文本。 */
142
+ function register(toolName, description, properties, required, run) {
143
+ ctx.tools.register({
144
+ name: toolName,
145
+ description,
146
+ parameters: { type: 'object', properties, required, additionalProperties: false },
147
+ output: textOutput,
148
+ async execute(args) {
149
+ try {
150
+ return { text: String(await run(args ?? {}) ?? '') }
151
+ } catch (error) {
152
+ return { text: `这一步没做成:${error instanceof Error ? error.message : String(error)}` }
153
+ }
154
+ },
155
+ })
156
+ }
157
+
158
+ register(
159
+ 'lifecard_cards',
160
+ [
161
+ '列出用户在 LifeCard 里写的人物卡(名字、是现实里的人还是虚构角色、关系)。',
162
+ '演一个人之前、写一章之前先调它,确认要用的卡叫什么。',
163
+ ].join('\n'),
164
+ {
165
+ kind: { type: 'string', enum: ['real', 'fictional'], description: '可选:只要现实里的人,或只要虚构角色。' },
166
+ },
167
+ [],
168
+ async (args) => {
169
+ const root = await resolveRoot(config)
170
+ const all = await store.listAll(root)
171
+ const cards = Array.isArray(all.cards) ? all.cards : []
172
+ if (cards.length === 0) return `这个文件夹里还没有卡:${root}`
173
+ const want = String(args.kind ?? '')
174
+ const picked = want === '' ? cards : cards.filter((c) => String(c.kind ?? '') === want)
175
+ if (picked.length === 0) return `没有「${KIND_LABEL[want] ?? want}」这一类卡。全部卡:\n` + cards.map((c) => `- ${cardLine(c)}`).join('\n')
176
+ return `一共 ${picked.length} 张:\n` + picked.map((c) => `- ${cardLine(c)}`).join('\n')
177
+ },
178
+ )
179
+
180
+ register(
181
+ 'lifecard_card',
182
+ [
183
+ '取一张卡的全部内容:自述、性格、说话习惯、边界、开场白、对话示例。',
184
+ '演这个人的时候,按这里的「说话习惯」和「不会说的话」来说话,别自己编。',
185
+ ].join('\n'),
186
+ {
187
+ card: { type: 'string', description: '卡的名字,或者卡的 id(不知道就先调 lifecard_cards)。' },
188
+ },
189
+ ['card'],
190
+ async (args) => {
191
+ const root = await resolveRoot(config)
192
+ const card = await findCard(root, args.card)
193
+ if (card === null) return `没找到叫「${String(args.card ?? '')}」的卡。`
194
+ const data = card.data ?? {}
195
+ const sections = Array.isArray(card.sections) ? card.sections : []
196
+ const lines = [`${cardLine(data)}`]
197
+ const tags = Array.isArray(data.tags) ? data.tags : []
198
+ if (tags.length > 0) lines.push(`标签:${tags.join('、')}`)
199
+ const body = sections
200
+ .filter((s) => s?.title !== undefined && String(s.body ?? '').trim() !== '')
201
+ .map((s) => `## ${s.title}\n${String(s.body).trim()}`)
202
+ .join('\n\n')
203
+ lines.push(body === '' ? '(这张卡正文还是空的)' : body)
204
+ return lines.join('\n')
205
+ },
206
+ )
207
+
208
+ register(
209
+ 'lifecard_default',
210
+ [
211
+ '用户在 LifeCard 里为每扇门选好的「现在用哪张卡」:酒馆那扇门现在演谁、写小说那扇门现在写谁。',
212
+ '用户没特别指定的时候,就按这里说的来。',
213
+ ].join('\n'),
214
+ {},
215
+ [],
216
+ async () => {
217
+ const root = await resolveRoot(config)
218
+ const state = await store.readConfigState(root)
219
+ const pins = state.config?.default_cards ?? {}
220
+ const rows = [
221
+ ['tavern', '酒馆(现在的演的是谁)'],
222
+ ['novel', '写小说(现在写的是谁)'],
223
+ ['real', '真实人物记录(首页先看谁)'],
224
+ ]
225
+ const out = []
226
+ for (const [key, label] of rows) {
227
+ const id = String(pins[key] ?? '').trim()
228
+ if (id === '') { out.push(`${label}:还没选`); continue }
229
+ const card = await findCard(root, id)
230
+ out.push(`${label}:${card === null ? `${id}(这张卡可能被删了)` : cardLine(card.data)}`)
231
+ }
232
+ return out.join('\n')
233
+ },
234
+ )
235
+
236
+ register(
237
+ 'lifecard_roleplay',
238
+ [
239
+ '一次取齐「演这一段」要用的东西:这个人的全部设定 + 会用到的那本世界书 + 之前收过尾的摘要。',
240
+ '不给 card 就用用户为酒馆门选好的那一张。',
241
+ ].join('\n'),
242
+ {
243
+ card: { type: 'string', description: '可选:要演谁(名字或 id)。不给就按用户选好的默认卡。' },
244
+ world: { type: 'string', description: '可选:要用的世界书名字或 id。不给就用这张卡自己挂的那本。' },
245
+ },
246
+ [],
247
+ async (args) => {
248
+ const root = await resolveRoot(config)
249
+ let wanted = String(args.card ?? '').trim()
250
+ if (wanted === '') {
251
+ const state = await store.readConfigState(root)
252
+ wanted = String(state.config?.default_cards?.tavern ?? '').trim()
253
+ }
254
+ if (wanted === '') return '还没有挑要演谁。先在 LifeCard 的酒馆那扇门里选一张卡(「现在演谁」)。'
255
+ const card = await findCard(root, wanted)
256
+ if (card === null) return `没找到叫「${wanted}」的卡。`
257
+ const data = card.data ?? {}
258
+ const sections = Array.isArray(card.sections) ? card.sections : []
259
+ const persona = [
260
+ core.sectionBody(sections, '自述'),
261
+ core.sectionBody(sections, '性格'),
262
+ core.sectionBody(sections, '口癖'),
263
+ core.sectionBody(sections, '外貌'),
264
+ core.sectionBody(sections, '不会说的话'),
265
+ core.sectionBody(sections, '不会做的事'),
266
+ core.sectionBody(sections, '场景'),
267
+ ].filter((s) => typeof s === 'string' && s.trim() !== '').join('\n\n')
268
+ // 卡上写什么就给什么:不删、不改写。删过的卡就不是那张卡了(用户原话)。
269
+ const personaText = persona
270
+ const worldWant = String(args.world ?? '').trim() === '' ? String(data.world ?? '') : String(args.world)
271
+ const entries = await worldEntries(root, worldWant)
272
+ const out = [`# 要演的人:${cardLine(data)}`, '', personaText === '' ? '(这张卡的正文还是空的,先按名字和关系演)' : personaText]
273
+ if (worldWant !== '' && worldWant !== 'reality') {
274
+ out.push('', `# 世界书:${worldWant}`, entriesToText(entries))
275
+ } else {
276
+ out.push('', '# 世界书', '(这一场没有挂世界书,按现实或你俩当下的场景演)')
277
+ }
278
+ const greeting = String(core.sectionBody(sections, '开场白') ?? '').trim()
279
+ if (greeting !== '') out.push('', '# 卡上写的开场白(可以参考它开口,不必一字不差)', greeting)
280
+ const examples = String(core.sectionBody(sections, '对话示例') ?? '').trim()
281
+ if (examples !== '') out.push('', '# 这个人说话的样例', examples.slice(-1600))
282
+ return out.join('\n')
283
+ },
284
+ )
285
+
286
+ register(
287
+ 'lifecard_world',
288
+ [
289
+ '看一本世界书里有哪些条目:什么情况下会带进来、内容是什么。',
290
+ '写小说要保证设定前后一致时用;演的时候也可以先看一眼规矩。',
291
+ ].join('\n'),
292
+ {
293
+ world: { type: 'string', description: '世界书的名字或 id。' },
294
+ },
295
+ ['world'],
296
+ async (args) => {
297
+ const root = await resolveRoot(config)
298
+ const all = await store.listAll(root)
299
+ const worlds = Array.isArray(all.worlds) ? all.worlds : []
300
+ if (worlds.length === 0) return '这个文件夹里还没有世界书。'
301
+ const names = worlds.map((w) => `- ${w.name ?? w.id}(${w.entry_count ?? 0} 条)`).join('\n')
302
+ const entries = await worldEntries(root, args.world)
303
+ if (entries.length === 0) return `没找到「${String(args.world ?? '')}」这本世界书。现有的:\n${names}`
304
+ return `《${String(args.world)}》里的条目:\n${entriesToText(entries)}`
305
+ },
306
+ )
307
+
308
+ // ── 从导入的材料里提炼:先读,再(经用户同意)写 ───────────────────
309
+ //
310
+ // 这一组是唯一会写盘的。规矩是死的:
311
+ // 1. 没带 approved=true 一律不写,只回「先把候选列给用户看」;
312
+ // 2. 每一段/每一条都必须附一句材料里的原句,写之前逐字比对;
313
+ // 3. 对不上就整次拒绝,并说清是哪一条对不上 —— 不猜、不模糊匹配。
314
+ // 理由:小说和日记一旦被「大概提炼」,卡上就会多出用户没写过的话,
315
+ // 而这种错不会报错,只会慢慢变成「我什么时候写过这个」。
316
+
317
+ register(
318
+ 'lifecard_materials',
319
+ [
320
+ '列出这个文件夹里所有材料(导入的小说、日记、访谈原文)。',
321
+ '想把材料里的人或世界提炼成卡/世界书时,先用它看有哪些材料可用。',
322
+ ].join('\n'),
323
+ {},
324
+ [],
325
+ async () => {
326
+ const root = await resolveRoot(config)
327
+ const materials = await store.readMaterials(root)
328
+ const rels = Object.keys(materials).sort()
329
+ if (rels.length === 0) return '这个文件夹里还没有材料。先把文字导进来,再说提炼。'
330
+ const lines = rels.map((rel) => `- ${rel}(${String(materials[rel] ?? '').length} 字)`)
331
+ return `现有材料 ${rels.length} 份:\n${lines.join('\n')}`
332
+ },
333
+ )
334
+
335
+ register(
336
+ 'lifecard_material',
337
+ [
338
+ '读一份材料的正文。想提炼人物或世界观,先把它读进来。',
339
+ '材料很长时会截断,并告出总字数。',
340
+ ].join('\n'),
341
+ {
342
+ material: { type: 'string', description: '材料的路径或文件名,比如 materials/2026-10-26-某篇小说.md。' },
343
+ },
344
+ ['material'],
345
+ async (args) => {
346
+ const root = await resolveRoot(config)
347
+ const materials = await store.readMaterials(root)
348
+ const picked = pickMaterial(materials, args.material)
349
+ if (picked === null) {
350
+ const rels = Object.keys(materials).sort()
351
+ return rels.length === 0
352
+ ? '这个文件夹里还没有材料。'
353
+ : `没找到「${String(args.material ?? '')}」这份材料。现有的:\n${rels.map((r) => `- ${r}`).join('\n')}`
354
+ }
355
+ const text = String(materials[picked] ?? '')
356
+ const cap = 12000
357
+ const head = text.slice(0, cap)
358
+ const tail = text.length > cap ? `\n\n(后面还有 ${text.length - cap} 字没显示,需要的话按段落分几次读。)` : ''
359
+ return `# ${picked}(共 ${text.length} 字)\n\n${head}${tail}`
360
+ },
361
+ )
362
+
363
+ register(
364
+ 'lifecard_import_character',
365
+ [
366
+ '把材料里的一个人写成角色卡。**只有用户明确同意之后才调用。**',
367
+ '流程:先用 lifecard_materials / lifecard_material 读材料,把打算写成什么列给用户看(名字、几段、每段大意),',
368
+ '等用户说「可以 / 就这么写」,再带 approved: true 调这一次。',
369
+ '每一段都必须附一句材料里的原句(quote),写之前会逐字比对;对不上整次不写。',
370
+ '不给 approved: true 时不会写任何东西,只会告诉你还差哪一步。',
371
+ '已经有同名的卡时,默认只补空缺:原来写过的小节和字段一个字都不动,返回里会说补了哪几节。',
372
+ '只有用户明确要求整张重写时,才带 mode: "replace" 与 confirm_replace: true;缺一次就只回一句确认,不写。',
373
+ ].join('\n'),
374
+ {
375
+ approved: { type: 'boolean', description: '用户是否已经明确同意写入。必须为 true 才会真的建卡。' },
376
+ material: { type: 'string', description: '素材从哪来:材料的路径或文件名。' },
377
+ name: { type: 'string', description: '这个人叫什么。' },
378
+ world: { type: 'string', description: '归到哪本世界书下;不填就是 reality。' },
379
+ relation: { type: 'string', description: '和「我」的关系(可选)。' },
380
+ sections: {
381
+ type: 'array',
382
+ description: '要写进卡的段落。每项 { title, body, quote }:title 用小节名(自述/性格/场景/口癖/外貌/不会说的话…),body 是要写进卡的话,quote 是材料里支撑它的原句。',
383
+ },
384
+ mode: {
385
+ type: 'string',
386
+ enum: ['merge', 'replace'],
387
+ description: '同名已有卡时怎么办:merge(默认)只补空缺;replace 整张重写,必须同时带 confirm_replace: true。',
388
+ },
389
+ confirm_replace: { type: 'boolean', description: '整张重写时的第二次确认。用户第二次明确说要覆盖才传 true。' },
390
+ },
391
+ ['approved', 'material', 'name', 'sections'],
392
+ async (args) => {
393
+ const root = await resolveRoot(config)
394
+ const name = String(args.name ?? '').trim()
395
+ if (name === '') return '这个人的名字是空的,先问清他叫什么。'
396
+
397
+ const materials = await store.readMaterials(root)
398
+ const picked = pickMaterial(materials, args.material)
399
+ if (picked === null) return `没找到「${String(args.material ?? '')}」这份材料,先确认材料名。`
400
+ const source = String(materials[picked] ?? '')
401
+
402
+ const rows = Array.isArray(args.sections) ? args.sections : []
403
+ if (rows.length === 0) return '一段都没有,那就没东西可写。先定下要写哪几段。'
404
+ const bad = []
405
+ const sections = []
406
+ for (const row of rows) {
407
+ const title = String(row?.title ?? '').trim()
408
+ const body = String(row?.body ?? '').trim()
409
+ const quote = String(row?.quote ?? '').trim()
410
+ if (title === '' || body === '') { bad.push(`(有一段没写小节名或内容是空的)`); continue }
411
+ if (quote === '') { bad.push(`「${title}」这一段没给原句`); continue }
412
+ if (!hasQuote(source, quote)) { bad.push(`「${title}」引的原句在材料里找不到:${quote.slice(0, 40)}…`); continue }
413
+ sections.push({ title, body })
414
+ }
415
+ if (bad.length > 0) {
416
+ return `这一版没写。下面这些对不上材料:\n${bad.map((b) => `- ${b}`).join('\n')}\n\n改好之后再来一次。`
417
+ }
418
+
419
+ if (args.approved !== true) {
420
+ const preview = sections.map((x) => `- ${x.title}:${x.body.slice(0, 60)}${x.body.length > 60 ? '…' : ''}`).join('\n')
421
+ return [
422
+ `还没写。先把这一版列给用户看,等他明确说要,再带 approved: true 重调一次。`,
423
+ '',
424
+ `人物:${name}`,
425
+ `材料:${picked}`,
426
+ `段落:`,
427
+ preview,
428
+ ].join('\n')
429
+ }
430
+
431
+ const id = core.safeId(name)
432
+ const incoming = {
433
+ lifecard: core.DATA_VERSION,
434
+ id,
435
+ kind: 'fictional',
436
+ name,
437
+ world: String(args.world ?? '').trim() === '' ? 'reality' : String(args.world).trim(),
438
+ }
439
+ const relation = String(args.relation ?? '').trim()
440
+ if (relation !== '') incoming.relation = relation
441
+ const rel = store.cardRelPath(id, incoming.world)
442
+ const mode = args.mode === 'replace' ? 'replace' : 'merge'
443
+
444
+ const existingRel = await findExisting(root, rel, id)
445
+ if (existingRel !== null) {
446
+ const already = await store.readCard(root, existingRel)
447
+ if (already.ok !== true) {
448
+ if (already.withdrawn === true || isWithdrawnAt(root, existingRel)) return withdrawnNote(existingRel, '卡')
449
+ return `已经有一张同名的卡(${existingRel}),可这会儿读不出来:${String(already.error ?? '读不出来')}。先把它弄好,再来写。`
450
+ }
451
+ if (mode === 'replace') {
452
+ if (args.confirm_replace !== true) {
453
+ return [
454
+ `已经有一张同名的卡:${existingRel}`,
455
+ '整张重写会连身份、关系、原来写过的小节一起换掉,换完就找不回来了。',
456
+ '确定要整张重写,就再调一次,带 mode: "replace" 和 confirm_replace: true。',
457
+ '只想往里补,就不用改参数——默认只补空缺,原来的字一个不动。',
458
+ ].join('\n')
459
+ }
460
+ const replaced = await store.writeCard(root, existingRel, incoming, sections)
461
+ if (replaced.ok !== true) return `没能写成:${String(replaced.error ?? '存盘失败')}`
462
+ return `整张换掉了:${replaced.path}\n${sections.length} 段,每段都对着材料里的原句核过。这次是按用户第二次确认整张覆盖写的。`
463
+ }
464
+ const mergedData = mergeData(already.data, incoming)
465
+ const mergedSections = mergeSections(already.sections, sections)
466
+ if (mergedSections.added.length === 0 && mergedData.filled.length === 0) {
467
+ return `这张卡已经有了,这次没有可补的:${existingRel}\n原有的内容一个字没动。\nmerged: true`
468
+ }
469
+ const saved = await store.writeCard(root, existingRel, mergedData.data, mergedSections.sections)
470
+ if (saved.ok !== true) return `没能写成:${String(saved.error ?? '存盘失败')}`
471
+ const bits = []
472
+ if (mergedSections.added.length > 0) bits.push(`补了 ${mergedSections.added.length} 节:${mergedSections.added.join('、')}`)
473
+ if (mergedData.filled.length > 0) bits.push(`补了 ${mergedData.filled.length} 项:${mergedData.filled.join('、')}`)
474
+ return [
475
+ `补好了(没有重写):${saved.path}`,
476
+ ...bits,
477
+ '原来写过的内容一个字没动,身份也还是原来的。',
478
+ 'merged: true',
479
+ ].join('\n')
480
+ }
481
+
482
+ // 只比路径会漏:id 是拼音、名字是中文时(people/rat.card.md 那种),
483
+ // 按名字再写会算出另一个路径,于是同一个人并排出现两张,点「放回来」就重了。
484
+ const heldCard = await store.withdrawnNameHit(root, rel, [id, name])
485
+ if (isWithdrawnAt(root, rel) || heldCard !== null) {
486
+ return withdrawnNote(heldCard?.path ?? rel, '卡')
487
+ }
488
+ const saved = await store.writeCard(root, rel, incoming, sections)
489
+ if (saved.ok !== true) return `没能写成:${String(saved.error ?? '存盘失败')}`
490
+ return `写好了:${saved.path}\n${sections.length} 段,每段都对着材料里的原句核过。\n要接着补,就再调一次 lifecard_import_character(同名的卡默认只补空缺,已有的字不动)。`
491
+ },
492
+ )
493
+
494
+ register(
495
+ 'lifecard_import_world',
496
+ [
497
+ '把材料里的一套设定整理成世界书。**只有用户明确同意之后才调用。**',
498
+ '流程同 lifecard_import_character:先读材料、把候选条目(触发词 + 内容 + 依据原句)列给用户看,',
499
+ '等用户点头,再带 approved: true 调这一次。每条都要附原句,逐字比对,对不上整次不写。',
500
+ '已经有同名的世界书时,默认只补空缺:新条目加进去,触发词对得上的并进已有条目,原来的条目一个字不动。',
501
+ '只有用户明确要求整份重写时,才带 mode: "replace" 与 confirm_replace: true;缺一次就只回一句确认,不写。',
502
+ ].join('\n'),
503
+ {
504
+ approved: { type: 'boolean', description: '用户是否已经明确同意写入。必须为 true 才会真的建世界书。' },
505
+ material: { type: 'string', description: '素材从哪来:材料的路径或文件名。' },
506
+ name: { type: 'string', description: '这本世界书叫什么(地方/时代/势力都行)。' },
507
+ genre: { type: 'string', description: '一句话说这是什么类型的设定(可选)。' },
508
+ entries: {
509
+ type: 'array',
510
+ description: '条目数组。每项 { keys, content, quote }:keys 是触发用的关键词(字符串或数组),content 是这条设定本身,quote 是材料里支撑它的原句。',
511
+ },
512
+ mode: {
513
+ type: 'string',
514
+ enum: ['merge', 'replace'],
515
+ description: '同名已有世界书时怎么办:merge(默认)只补空缺、按触发词并条目;replace 整份重写,必须同时带 confirm_replace: true。',
516
+ },
517
+ confirm_replace: { type: 'boolean', description: '整份重写时的第二次确认。用户第二次明确说要覆盖才传 true。' },
518
+ },
519
+ ['approved', 'material', 'name', 'entries'],
520
+ async (args) => {
521
+ const root = await resolveRoot(config)
522
+ const name = String(args.name ?? '').trim()
523
+ if (name === '') return '这本世界书的名字是空的,先问清它叫什么。'
524
+
525
+ const materials = await store.readMaterials(root)
526
+ const picked = pickMaterial(materials, args.material)
527
+ if (picked === null) return `没找到「${String(args.material ?? '')}」这份材料,先确认材料名。`
528
+ const source = String(materials[picked] ?? '')
529
+
530
+ const rows = Array.isArray(args.entries) ? args.entries : []
531
+ if (rows.length === 0) return '一条设定都没有,那就没东西可写。'
532
+ const bad = []
533
+ const entries = []
534
+ for (const row of rows) {
535
+ const content = String(row?.content ?? '').trim()
536
+ const quote = String(row?.quote ?? '').trim()
537
+ const rawKeys = row?.keys
538
+ const keys = (Array.isArray(rawKeys) ? rawKeys : String(rawKeys ?? '').split(/[,,、]/))
539
+ .map((k) => String(k).trim()).filter((k) => k !== '')
540
+ if (content === '') { bad.push('有一条没有内容'); continue }
541
+ if (quote === '') { bad.push(`「${content.slice(0, 20)}…」这条没给原句`); continue }
542
+ if (!hasQuote(source, quote)) { bad.push(`「${content.slice(0, 20)}…」引的原句在材料里找不到`); continue }
543
+ entries.push({ keys, content, insertion_order: 100 })
544
+ }
545
+ if (bad.length > 0) {
546
+ return `这一版没写。下面这些对不上材料:\n${bad.map((b) => `- ${b}`).join('\n')}\n\n改好之后再来一次。`
547
+ }
548
+
549
+ if (args.approved !== true) {
550
+ const preview = entries.map((e) => `- [${e.keys.join(' / ') || '常驻'}] ${e.content.slice(0, 50)}${e.content.length > 50 ? '…' : ''}`).join('\n')
551
+ return [
552
+ '还没写。先把这一版列给用户看,等他明确说要,再带 approved: true 重调一次。',
553
+ '',
554
+ `世界书:${name}`,
555
+ `材料:${picked}`,
556
+ `条目:`,
557
+ preview,
558
+ ].join('\n')
559
+ }
560
+
561
+ const id = core.safeId(name)
562
+ const incoming = {
563
+ lifecard: core.DATA_VERSION,
564
+ id,
565
+ kind: 'world',
566
+ name,
567
+ genre: String(args.genre ?? '').trim(),
568
+ entry_count: entries.length,
569
+ }
570
+ const rel = path.posix.join('worlds', id, 'world.md')
571
+ const mode = args.mode === 'replace' ? 'replace' : 'merge'
572
+
573
+ const existingRel = await findWorld(root, rel, name)
574
+ if (existingRel !== null) {
575
+ const already = await store.readCard(root, existingRel)
576
+ if (already.ok !== true) {
577
+ if (already.withdrawn === true || isWithdrawnAt(root, existingRel)) return withdrawnNote(existingRel, '世界书')
578
+ return `已经有一本同名的世界书(${existingRel}),可这会儿读不出来:${String(already.error ?? '读不出来')}。先把它弄好,再来写。`
579
+ }
580
+ if (mode === 'replace') {
581
+ if (args.confirm_replace !== true) {
582
+ return [
583
+ `已经有一本同名的世界书:${existingRel}`,
584
+ '整份重写会把原来的条目全换掉,换完就找不回来了。',
585
+ '确定要整份重写,就再调一次,带 mode: "replace" 和 confirm_replace: true。',
586
+ '只想往里加,就不用改参数——默认只补空缺,原来的条目一个不动。',
587
+ ].join('\n')
588
+ }
589
+ const body = entries.map((e) => renderWorldEntry(e)).join('\n')
590
+ const replaced = await store.writeCard(root, existingRel, incoming, [{ title: '世界书条目', body }])
591
+ if (replaced.ok !== true) return `没能写成:${String(replaced.error ?? '存盘失败')}`
592
+ return `整份换掉了:${replaced.path}\n${entries.length} 条,每条都对着材料里的原句核过。这次是按用户第二次确认整份覆盖写的。`
593
+ }
594
+ const oldBody = core.sectionBody(already.sections ?? [], '世界书条目')
595
+ const merged = mergeWorldBlocks(oldBody, entries)
596
+ const mergedData = mergeData(already.data, { ...incoming, entry_count: 0 })
597
+ mergedData.data.entry_count = merged.total
598
+ const hasSection = (already.sections ?? []).some((one) => one?.title === '世界书条目')
599
+ const sections = hasSection
600
+ ? (already.sections ?? []).map((one) => (one?.title === '世界书条目' ? { title: '世界书条目', body: merged.body } : one))
601
+ : [...(already.sections ?? []), { title: '世界书条目', body: merged.body }]
602
+ const saved = await store.writeCard(root, existingRel, mergedData.data, sections)
603
+ if (saved.ok !== true) return `没能写成:${String(saved.error ?? '存盘失败')}`
604
+ const bits = []
605
+ if (merged.added.length > 0) bits.push(`新加 ${merged.added.length} 条:${merged.added.join('、')}`)
606
+ if (merged.joined.length > 0) bits.push(`并进已有条目 ${merged.joined.length} 条:${merged.joined.join('、')}`)
607
+ if (mergedData.filled.length > 0) bits.push(`补了 ${mergedData.filled.length} 项:${mergedData.filled.join('、')}`)
608
+ if (bits.length === 0) bits.push('这次的条目都已经在里面了')
609
+ return [
610
+ `补好了(没有重写):${saved.path}`,
611
+ ...bits,
612
+ '原来的条目一个字没动。',
613
+ 'merged: true',
614
+ ].join('\n')
615
+ }
616
+
617
+ const heldWorld = await store.withdrawnNameHit(root, rel, [id, name])
618
+ if (isWithdrawnAt(root, rel) || heldWorld !== null) {
619
+ return withdrawnNote(heldWorld?.path ?? rel, '世界书')
620
+ }
621
+ const body = entries.map((e) => renderWorldEntry(e)).join('\n')
622
+ const saved = await store.writeCard(root, rel, incoming, [{ title: '世界书条目', body }])
623
+ if (saved.ok !== true) return `没能写成:${String(saved.error ?? '存盘失败')}`
624
+ return `写好了:${saved.path}\n${entries.length} 条,每条都对着材料里的原句核过。`
625
+ },
626
+ )
627
+
628
+ return true
629
+ }
630
+
631
+ /** 比对原句时先把空白和换行抹平:材料里的一句常被折行,逐字比会假失败。 */
632
+ function squash(text) {
633
+ return String(text ?? '').replace(/\s+/g, '')
634
+ }
635
+
636
+ /** 材料里到底有没有这句话。宁可放过折行,绝不放过「差不多」。 */
637
+ function hasQuote(source, quote) {
638
+ const q = squash(quote)
639
+ if (q === '') return false
640
+ return squash(source).includes(q)
641
+ }
642
+
643
+ /** 按路径、文件名、或独一无二的片段找那份材料。找不到回 null。 */
644
+ function pickMaterial(materials, want) {
645
+ const key = String(want ?? '').trim()
646
+ if (key === '') return null
647
+ const rels = Object.keys(materials)
648
+ if (Object.hasOwn(materials, key)) return key
649
+ const norm = key.replace(/\\/g, '/')
650
+ const same = rels.filter((rel) => rel === norm || rel.endsWith('/' + norm) || path.posix.basename(rel) === norm)
651
+ if (same.length === 1) return same[0]
652
+ if (same.length > 1) return same[0]
653
+ const loose = rels.filter((rel) => rel.includes(norm))
654
+ return loose.length === 1 ? loose[0] : null
655
+ }
656
+
657
+ /** 一条世界书条目 → `- ` 开头的 YAML 块(parseWorldEntries 认这个形状)。 */
658
+ function renderWorldEntry(entry) {
659
+ const keys = Array.isArray(entry.keys) ? entry.keys : []
660
+ const lines = [`- keys: ${JSON.stringify(keys)}`]
661
+ lines.push(` insertion_order: ${Number.isFinite(entry.insertion_order) ? entry.insertion_order : 100}`)
662
+ lines.push(' content: |-')
663
+ for (const line of String(entry.content ?? '').split(/\r?\n/)) lines.push(` ${line}`)
664
+
665
+ return lines.join('\n')
666
+ }
667
+
668
+ /** 这个名字现在是不是被一张已撤掉的卡占着(撤掉记录还在,文件可能还在也可能被彻底删了)。 */
669
+ function isWithdrawnAt(root, rel) {
670
+ const redactions = store.readRedactionsSync(root)
671
+ return store.hitsRedactionByPath(redactions, rel) !== undefined
672
+ }
673
+
674
+ /** 占着名字时的说法:给出两条真能走通的路,别让人再撞一次。 */
675
+ function withdrawnNote(rel, what) {
676
+ return [
677
+ `这个名字被一张已经撤掉的${what}占着:${rel}`,
678
+ `想去救它,就到首页「已经撤掉的」里恢复;不想要了,就在那儿彻底删掉,名字才空出来。`,
679
+ ].join('\n')
680
+ }
681
+
682
+ /** 这张卡是不是已经有了:先看算出来的位置,再按 id 或名字找。找到回相对路径,没有回 null。 */
683
+ async function findExisting(root, rel, id) {
684
+ const direct = await store.findCardByRelOrId(root, rel)
685
+ if (direct !== null) return direct
686
+ return await store.findCardByRelOrId(root, id)
687
+ }
688
+
689
+ /** 这本世界书是不是已经有了:先看算出来的位置,再按名字在所有世界书里找。 */
690
+ async function findWorld(root, rel, name) {
691
+ const direct = await store.readCard(root, rel)
692
+ if (direct.ok === true) return rel
693
+ let dirs = []
694
+ try {
695
+ dirs = await readdir(path.join(root, 'worlds'))
696
+ } catch {
697
+ return null
698
+ }
699
+ for (const dir of dirs) {
700
+ const candidate = path.posix.join('worlds', dir, 'world.md')
701
+ const got = await store.readCard(root, candidate)
702
+ if (got.ok === true && String(got.data?.name ?? '').trim() === name) return candidate
703
+ }
704
+ return null
705
+ }
706
+
707
+ /** 合并前置字段:只填空缺,绝不改已有的(身份、关系、归到哪本书都算已有)。 */
708
+ function mergeData(existingData, incomingData) {
709
+ const data = { ...(existingData ?? {}) }
710
+ const filled = []
711
+ for (const [key, value] of Object.entries(incomingData ?? {})) {
712
+ const cur = data[key]
713
+ const empty = cur === undefined || cur === null || (typeof cur === 'string' && cur.trim() === '')
714
+ if (!empty || value === undefined || value === null) continue
715
+ if (typeof value === 'string' && value.trim() === '') continue
716
+ data[key] = value
717
+ filled.push(key)
718
+ }
719
+ return { data, filled }
720
+ }
721
+
722
+ /** 合并小节:已有正文一个字不动,只补空缺(还没有这一节,或那一节本来是空的)。 */
723
+ function mergeSections(existingSections, incomingSections) {
724
+ const sections = (existingSections ?? []).map((one) => ({ title: one?.title, body: String(one?.body ?? '') }))
725
+ const at = new Map(sections.map((one, i) => [one.title, i]))
726
+ const added = []
727
+ for (const one of incomingSections ?? []) {
728
+ const title = String(one?.title ?? '').trim()
729
+ const body = String(one?.body ?? '').trim()
730
+ if (title === '' || body === '') continue
731
+ if (at.has(title)) {
732
+ const i = at.get(title)
733
+ if (String(sections[i].body ?? '').trim() === '') {
734
+ sections[i].body = body
735
+ added.push(title)
736
+ }
737
+ continue
738
+ }
739
+ sections.push({ title, body })
740
+ at.set(title, sections.length - 1)
741
+ added.push(title)
742
+ }
743
+ return { sections, added }
744
+ }
745
+
746
+ /** 把「世界书条目」小节切成一条块一行数组(`- ` 开头算新的一条),块里原有字段全留着。 */
747
+ function splitWorldBlocks(body) {
748
+ const blocks = []
749
+ let cur = null
750
+ for (const line of String(body ?? '').split(/\r?\n/)) {
751
+ if (/^-\s/.test(line)) {
752
+ if (cur !== null) blocks.push(cur)
753
+ cur = [line]
754
+ continue
755
+ }
756
+ if (cur === null) continue
757
+ cur.push(line)
758
+ }
759
+ if (cur !== null) blocks.push(cur)
760
+ return blocks
761
+ }
762
+
763
+ /** 一条块的触发词。借 parseWorldEntries 认形状,author 手写的 uid/constant 等字段都还在。 */
764
+ function blockKeys(lines) {
765
+ const parsed = core.parseWorldEntries([{ title: '世界书条目', body: lines.join('\n') }])
766
+ const keys = parsed?.[0]?.keys
767
+ return (Array.isArray(keys) ? keys : []).map((k) => String(k).trim()).filter((k) => k !== '')
768
+ }
769
+
770
+ /** 只改一条块里的 keys 那行,别的行一个字不碰。 */
771
+ function blockWithKeys(lines, keys) {
772
+ const text = JSON.stringify(keys)
773
+ let done = false
774
+ const out = lines.map((line) => {
775
+ if (done || !/^\s*keys:/.test(line)) return line
776
+ done = true
777
+ return line.replace(/^(\s*)keys:.*$/, `$1keys: ${text}`)
778
+ })
779
+ if (!done) out.splice(1, 0, ` keys: ${text}`)
780
+ return out
781
+ }
782
+
783
+ /** 世界书合并:触发词对得上的并进已有条目(只把新触发词补进 keys),对不上的追加成新条目。 */
784
+ function mergeWorldBlocks(existingBody, incomingEntries) {
785
+ const blocks = splitWorldBlocks(existingBody)
786
+ const added = []
787
+ const joined = []
788
+ for (const entry of incomingEntries ?? []) {
789
+ const keys = (entry?.keys ?? []).map((k) => String(k).trim()).filter((k) => k !== '')
790
+ const label = keys.join(' / ') || '常驻'
791
+ const hit = keys.length === 0 ? -1 : blocks.findIndex((lines) => blockKeys(lines).some((k) => keys.includes(k)))
792
+ if (hit === -1) {
793
+ const fresh = [`- keys: ${JSON.stringify(keys)}`, ' insertion_order: 100', ' content: |-']
794
+ for (const line of String(entry?.content ?? '').split(/\r?\n/)) fresh.push(` ${line}`)
795
+ blocks.push(fresh)
796
+ added.push(label)
797
+ continue
798
+ }
799
+ const union = blockKeys(blocks[hit])
800
+ for (const k of keys) if (!union.includes(k)) union.push(k)
801
+ blocks[hit] = blockWithKeys(blocks[hit], union)
802
+ joined.push(label)
803
+ }
804
+ return { body: blocks.map((lines) => lines.join('\n')).join('\n'), added, joined, total: blocks.length }
805
+ }