dsh-lifecard 0.1.2 → 0.2.1

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/lib/index.js CHANGED
@@ -25,8 +25,36 @@ import * as memory from './memory.js'
25
25
  import * as jobs from './jobs.js'
26
26
  import * as jobsStore from './jobs-store.js'
27
27
  import * as interview from './jobs-interview.js'
28
- import * as tavern from './tavern.js'
29
- import * as novel from './novel.js'
28
+ // 这四个是「可以整个删掉」的功能模块:酒馆、写小说、预设、文字游戏。
29
+ // 用「用到才加载」而不是文件顶上的静态 import —— 静态 import 一个不存在的
30
+ // 文件会让整个插件起不来,那就不是「能删」而是「删了就全废」。
31
+ // 删掉对应文件之后,只有那个功能报「这个功能没装」,别的照常。
32
+ import * as lifecardTools from '../lifecard-tools.js'
33
+
34
+ let tavern = null
35
+ let novel = null
36
+ let presets = null
37
+ let game = null
38
+ let career = null
39
+ /** 哪个功能没装(给用户看的名字)。 */
40
+ const FEATURE_NAMES = { tavern: '酒馆', novel: '写小说', presets: '预设', game: '文字小说游戏', career: '简历与规划' }
41
+ /**
42
+ * 按需把四个模块加载进来。已经加载过的不会重复加载。
43
+ * @returns {Promise<Record<string, boolean>>} 每个模块现在在不在
44
+ */
45
+ async function ensureModules() {
46
+ if (tavern === null) tavern = await import('./tavern.js').catch(() => null)
47
+ if (novel === null) novel = await import('./novel.js').catch(() => null)
48
+ if (presets === null) presets = await import('./presets.js').catch(() => null)
49
+ if (game === null) game = await import('./game.js').catch(() => null)
50
+ if (career === null) career = await import('./career.js').catch(() => null)
51
+ return { tavern: tavern !== null, novel: novel !== null, presets: presets !== null, game: game !== null, career: career !== null }
52
+ }
53
+ /** 这个功能没装的时候,统一回一句人话。 */
54
+ function missingFeature(name) {
55
+ const label = FEATURE_NAMES[name] ?? name
56
+ return { ok: false, error: `「${label}」这个功能没装(对应的文件被删掉了)。别的功能不受影响。`, missingFeature: name }
57
+ }
30
58
  export const name = 'dsh-lifecard'
31
59
 
32
60
  /** 需要宿主提供的服务。缺 webServer 就什么都不做(明确失败胜过静默半死)。 */
@@ -485,6 +513,13 @@ async function collectStream(handle) {
485
513
  const eat = (chunk) => {
486
514
  if (chunk === null || chunk === undefined) return
487
515
  if (typeof chunk === 'string') { text += chunk; return }
516
+ // 模型「想」的那一段走的是另一条事件(实测:{ type: 'reasoning-delta', text })。
517
+ // 它不是回答,也**不能**当成回答拼进来:拼进去之后 JSON 前面多出几千字
518
+ // 「Thinking Process: …」,解析必失败——「整理进卡里」于是等五十秒、
519
+ // 试两次、报「AI 这次没给出能用的结果」,用户看到的是一直转圈。
520
+ // 下面那些「只要是 .text 就收」的兜底分支会让它漏进来,所以必须先在
521
+ // 这里按类型挡掉。
522
+ if (typeof chunk.type === 'string' && /reasoning|thinking|analysis/i.test(chunk.type)) return
488
523
  // 真实的流事件形状(实测):{ type: 'text-delta', index, text }
489
524
  // block-start / block-end / text-start / text-end / finish 都不带正文
490
525
  if (chunk.type === 'text-delta' && typeof chunk.text === 'string') { text += chunk.text; return }
@@ -845,8 +880,13 @@ function buildApi(ctx, workspace, config, options) {
845
880
  const ws = await root(body)
846
881
  const data = body?.data
847
882
  if (data === null || typeof data !== 'object') return { ok: false, error: '没收到卡片内容,重新试一次。' }
883
+ // 判空必须在 safeId **之前**:`core.safeId('')` 返回 `'unnamed'`,
884
+ // 于是下面那句 `if (id === '')` 永远不成立——没起名字的新卡会悄悄
885
+ // 变成一张叫「unnamed」的卡,之后所有空名字的卡还会互相覆盖。
886
+ if (String(data.id ?? data.name ?? '').trim() === '') {
887
+ return { ok: false, error: '这张卡还没有名字,先给它起一个。' }
888
+ }
848
889
  const id = core.safeId(data.id ?? data.name ?? '')
849
- if (id === '') return { ok: false, error: '这张卡还没有名字,先给它起一个。' }
850
890
  data.id = id
851
891
  data.lifecard = core.DATA_VERSION
852
892
  let rel
@@ -941,6 +981,35 @@ function buildApi(ctx, workspace, config, options) {
941
981
  },
942
982
 
943
983
  /** 看某张卡以前的样子(快照在每次保存时自动留,只是以前没露出来)。 */
984
+ // 三扇门各自「现在用哪张卡」。存成 id,读的时候再按 id 找卡:
985
+ // 卡改名、换文件夹都不会让这条记录失效。
986
+ 'card.defaults.get': async (body) => {
987
+ const ws = await root(body)
988
+ const cfg = await store.readConfigState(ws)
989
+ const pins = cfg.config?.default_cards ?? {}
990
+ return {
991
+ ok: true,
992
+ cards: {
993
+ real: String(pins.real ?? ''),
994
+ tavern: String(pins.tavern ?? ''),
995
+ novel: String(pins.novel ?? ''),
996
+ },
997
+ }
998
+ },
999
+ 'card.defaults.set': async (body) => {
1000
+ const ws = await root(body)
1001
+ const mode = String(body?.mode ?? '')
1002
+ if (mode !== 'real' && mode !== 'tavern' && mode !== 'novel') {
1003
+ return { ok: false, error: '不知道你说的是哪扇门。' }
1004
+ }
1005
+ const id = String(body?.id ?? '').trim()
1006
+ const cfg = await store.readConfigState(ws)
1007
+ if (cfg.ok !== true) return { ok: false, error: cfg.error ?? '这个文件夹里的设置读不出来。' }
1008
+ const pins = { real: '', tavern: '', novel: '', ...(cfg.config?.default_cards ?? {}) }
1009
+ pins[mode] = id
1010
+ await store.writeConfig(ws, { default_cards: pins })
1011
+ return { ok: true, cards: pins }
1012
+ },
944
1013
  'card.history': async (body) => {
945
1014
  const ws = await root(body)
946
1015
  const safe = await insideWorkspace(ws, body?.path)
@@ -1198,7 +1267,9 @@ function buildApi(ctx, workspace, config, options) {
1198
1267
  const name = String(body?.name ?? about ?? 'material')
1199
1268
  const block = body?.meta === undefined ? content : `${content}\n\n\`\`\`\n${body.meta}\n\`\`\``
1200
1269
  const saved = await store.appendMaterial(ws, name, block)
1201
- return { ok: true, ...saved }
1270
+ // 以前这里无条件 `ok:true` 再展开 saved,把 `ok:false` 盖掉了:
1271
+ // 存失败时界面照样说「已保存」。别的路由都是先判 saved.ok 再往下走。
1272
+ if (saved?.ok !== true) return { ok: false, error: saved?.error ?? '这段材料没存进去。', ...saved }
1202
1273
  },
1203
1274
 
1204
1275
  /** 材料列表 + 全文(分析用)。 */
@@ -1879,7 +1950,7 @@ function buildApi(ctx, workspace, config, options) {
1879
1950
  ? all.filter((p) => body.people.includes(keyOf(p)))
1880
1951
  : all
1881
1952
  if (wanted.length === 0) return { ok: false, error: '勾选的人一个都没对上。' }
1882
- const at = new Date().toISOString().slice(0, 10)
1953
+ const at = store.localDate()
1883
1954
  const files = []
1884
1955
  for (const p of wanted) {
1885
1956
  const label = p.name !== '' ? p.name : p.kin
@@ -1923,7 +1994,7 @@ function buildApi(ctx, workspace, config, options) {
1923
1994
  ? all.filter((p) => body.people.includes(p.name !== '' ? `${p.kin}:${p.name}` : p.kin))
1924
1995
  : all
1925
1996
  if (wanted.length === 0) return { ok: false, error: '勾选的人一个都没对上。' }
1926
- const md = memory.renderMemoryMaterial(wanted, { read_at: new Date().toISOString().slice(0, 10) })
1997
+ const md = memory.renderMemoryMaterial(wanted, { read_at: store.localDate() })
1927
1998
  const saved = await store.appendMaterial(ws, `记忆里认出来的人`, md)
1928
1999
  if (saved.ok !== true) return saved
1929
2000
  // 记下「这些人还缺什么」。等他们变成卡之后,卡上那个红色感叹号
@@ -2252,6 +2323,7 @@ function buildApi(ctx, workspace, config, options) {
2252
2323
 
2253
2324
  /** 酒馆:说过的这几场。 */
2254
2325
  'tavern.list': async (body) => {
2326
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2255
2327
  const ws = await root(body)
2256
2328
  return await tavern.listChats(ws)
2257
2329
  },
@@ -2263,6 +2335,7 @@ function buildApi(ctx, workspace, config, options) {
2263
2335
  * 而不是对着一个空框想「我该说什么」。
2264
2336
  */
2265
2337
  'tavern.start': async (body) => {
2338
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2266
2339
  const ws = await root(body)
2267
2340
  const want = String(body?.card ?? '').trim()
2268
2341
  if (want === '') return { ok: false, error: '得先挑一个人,才能开始。' }
@@ -2304,6 +2377,7 @@ function buildApi(ctx, workspace, config, options) {
2304
2377
 
2305
2378
  /** 酒馆:读这一场。 */
2306
2379
  'tavern.get': async (body) => {
2380
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2307
2381
  const ws = await root(body)
2308
2382
  const id = String(body?.id ?? '').trim()
2309
2383
  if (id === '') return { ok: false, error: '这一场找不到了' }
@@ -2331,6 +2405,8 @@ function buildApi(ctx, workspace, config, options) {
2331
2405
  * 断网一次就全没了。
2332
2406
  */
2333
2407
  'tavern.say': async (body) => {
2408
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2409
+ if ((await ensureModules()).presets !== true) return missingFeature('presets')
2334
2410
  const id = String(body?.id ?? '').trim()
2335
2411
  if (id === '') return { ok: false, error: '这一场找不到了' }
2336
2412
  // 同一场会话一次只处理一句:读-改-写之间夹着一次模型调用,
@@ -2374,7 +2450,11 @@ function buildApi(ctx, workspace, config, options) {
2374
2450
  const memoryNote = (Array.isArray(got.notes) ? got.notes : [])
2375
2451
  .find((n) => String(n?.title ?? '').trim() === tavern.MEMORY_TITLE)
2376
2452
  const memory = memoryNote === undefined ? '' : String(memoryNote.body ?? '')
2377
- const system = tavern.buildRoleplaySystem({ cardName, persona: persona.text, worldNotes, memory })
2453
+ // 演法预设:选了就把它那套要求拼在最后。找不到预设(用户删了)就不拼,
2454
+ // 不能因为这一条让整场对话报错。
2455
+ const roleplayPreset = await presets.resolve(ws, body?.preset)
2456
+ const presetNote = roleplayPreset.ok === true && roleplayPreset.preset !== null ? String(roleplayPreset.preset.prompt ?? '') : ''
2457
+ const system = tavern.buildRoleplaySystem({ cardName, persona: persona.text, worldNotes, memory, preset: presetNote })
2378
2458
  const user = tavern.buildRoleplayUser({ cardName, turns })
2379
2459
  const called = await callModel(ctx, { system, user, model: body?.model })
2380
2460
  const now = tavernStamp()
@@ -2407,9 +2487,13 @@ function buildApi(ctx, workspace, config, options) {
2407
2487
  * 让它别把之前发生过的事记错。
2408
2488
  */
2409
2489
  'tavern.summarize': async (body) => {
2490
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2410
2491
  const ws = await root(body)
2411
2492
  const id = String(body?.id ?? '').trim()
2412
2493
  if (id === '') return { ok: false, error: '这一场找不到了' }
2494
+ // 收尾也是一次「读 → 调模型(十几二十秒)→ 整文件写回」,跟 tavern.say 同一个形状。
2495
+ // 不收进来排队的话,这段时间里说的任何一句都会被回写成收尾前那一版 —— 而且不留痕迹。
2496
+ return oneAtATime(id, async () => {
2413
2497
  const got = await tavern.readChat(ws, id)
2414
2498
  if (got.ok !== true) return got
2415
2499
  const turns = Array.isArray(got.turns) ? got.turns.slice() : []
@@ -2429,10 +2513,112 @@ function buildApi(ctx, workspace, config, options) {
2429
2513
  const saved = await tavern.writeChat(ws, id, { ...got.data, notes, turns: turns.length, updated_at: tavernStamp() }, turns)
2430
2514
  if (saved.ok !== true) return { ok: false, error: `收好了,但没存下来:${saved.error}`, summary, turns }
2431
2515
  return { ok: true, id, summary, notes, turns }
2516
+ })
2517
+ },
2518
+
2519
+ /**
2520
+ * 把这一场里最能代表 TA 的几句,写进那张卡的「对话示例」。
2521
+ *
2522
+ * 「对话示例」是下次演 TA 时最管用的材料:比「性格:沉默寡言」具体得多,
2523
+ * 因为它就是那个人真的说过的话。演着演着发现 TA 说话的样子比卡上写的准,
2524
+ * 这里就能把它固化下来。
2525
+ */
2526
+ 'tavern.toExample': async (body) => {
2527
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2528
+ const ws = await root(body)
2529
+ const id = String(body?.id ?? '').trim()
2530
+ if (id === '') return { ok: false, error: '这一场找不到了' }
2531
+ return oneAtATime(id, async () => {
2532
+ const got = await tavern.readChat(ws, id)
2533
+ if (got.ok !== true) return got
2534
+ const turns = Array.isArray(got.turns) ? got.turns : []
2535
+ if (turns.filter((t) => String(t?.who ?? '').trim() !== '我').length === 0) {
2536
+ return { ok: false, error: 'TA 还没说过话,挑不出例句。' }
2537
+ }
2538
+ const cardName = String(got.data?.card_name ?? '').trim()
2539
+ const prompt = tavern.buildExamplePrompt({ cardName, turns })
2540
+ const called = await callModel(ctx, { system: prompt.system, user: prompt.user, model: body?.model })
2541
+ if (called.ok !== true) return { ok: false, error: `没挑出来:${called.error ?? '过一会儿再试一次'}` }
2542
+ const picked = tavern.cleanExamples(called.text)
2543
+ if (picked.length === 0) return { ok: false, error: '这一次没挑出能用的句子,过一会儿再试一次。' }
2544
+
2545
+ const want = String(got.data?.card ?? '').trim()
2546
+ if (want === '') return { ok: false, error: '这一场不知道是跟哪张卡演的,存不回去。' }
2547
+ const card = await store.findCardByRelOrId(ws, want)
2548
+ if (card === null) return { ok: false, error: '那张卡找不到了,它可能被删掉了。' }
2549
+ const read = await store.readCard(ws, card)
2550
+ if (read.ok !== true) return read
2551
+ const sections = Array.isArray(read.sections) ? read.sections.map((x) => ({ ...x })) : []
2552
+ const title = '对话示例'
2553
+ const at = sections.findIndex((x) => String(x.title ?? '').trim() === title)
2554
+ const block = picked.map((line) => `- ${line}`).join('\n')
2555
+ if (at === -1) sections.push({ title, body: block })
2556
+ else {
2557
+ const oldBody = String(sections[at].body ?? '').trim()
2558
+ const merged = oldBody === '' || oldBody === '_(还没写)_' ? block : `${oldBody}\n${block}`
2559
+ // 例句越攒越多会把这个小节撑爆,之后每演一句都把这些全塞进提示词。
2560
+ // 只留最后 24 行——它们是最靠近「现在这个人」的样子。
2561
+ const lines = merged.split(/\r?\n/).filter((x) => x.trim() !== '')
2562
+ sections[at] = { ...sections[at], body: lines.slice(-24).join('\n') }
2563
+ }
2564
+ const written = await store.writeCard(ws, card, read.data, sections)
2565
+ if (written.ok !== true) return written
2566
+ return { ok: true, path: written.path, picked }
2567
+ })
2432
2568
  },
2433
2569
 
2434
2570
  /** 酒馆:这一场不要了。 */
2435
- 'tavern.delete': async (body) => {
2571
+ /**
2572
+ * 把酒馆里聊出来的一场,变成某本小说的一章。
2573
+ *
2574
+ * 这是「三扇门其实是一件事」的那一步:先在酒馆里把人立起来、把话演一遍,
2575
+ * 演得满意的那一场直接变成小说的正文,而不是再从头写一遍。
2576
+ */
2577
+ 'tavern.toChapter': async (body) => {
2578
+ const ws = await root(body)
2579
+ const mods = await ensureModules()
2580
+ if (mods.tavern !== true) return missingFeature('tavern')
2581
+ if (mods.novel !== true) return missingFeature('novel')
2582
+
2583
+ const id = String(body?.id ?? '').trim()
2584
+ if (id === '') return { ok: false, error: '得先挑一场聊过的。' }
2585
+ const book = String(body?.book ?? '').trim()
2586
+ if (book === '') return { ok: false, error: '得先挑一本书。没有书的话,先回「写小说」那扇门建一本。' }
2587
+
2588
+ const chat = await tavern.readChat(ws, id)
2589
+ if (chat.ok !== true) return chat
2590
+ const turns = chat.turns ?? []
2591
+ if (turns.length === 0) return { ok: false, error: '这一场还什么都没说。先在酒馆里聊几句,再变。' }
2592
+
2593
+ const target = await novel.readBook(ws, book)
2594
+ if (target.ok !== true) return target
2595
+ if (target.book === null) return { ok: false, error: '找不到这本书。它可能被删了。' }
2596
+
2597
+ const built = novel.buildChatToChapterPrompt({
2598
+ cardName: chat.data?.card_name ?? '',
2599
+ bookTitle: target.book?.title ?? '',
2600
+ turns,
2601
+ note: String(body?.note ?? ''),
2602
+ })
2603
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
2604
+ if (called.ok !== true) return { ok: false, error: `这次没改出来:${called.error ?? '过一会儿再试一次'}` }
2605
+
2606
+ const text = String(called.text ?? '').trim()
2607
+ if (text === '') return { ok: false, error: '它这次什么都没写出来,再试一次。' }
2608
+
2609
+ // 章号接着最后一章往后排。用「最后一章的号 + 1」而不是「章数 + 1」:
2610
+ // 中间删过章的话(第 2 章被删),章数是 2、最后一章是第 3 章,
2611
+ // 用章数算出来的 3 会覆盖掉现成的第 3 章。
2612
+ const list = Array.isArray(target.chapters) ? target.chapters : []
2613
+ const last = list.length === 0 ? 0 : Number(list[list.length - 1]?.index ?? 0)
2614
+ const next = (Number.isFinite(last) ? last : 0) + 1
2615
+ const written = await novel.writeChapter(ws, book, next, text)
2616
+ if (written.ok !== true) return written
2617
+ return { ok: true, book, chapter: written.index ?? next, text, turns: turns.length }
2618
+ },
2619
+
2620
+ 'tavern.delete': async (body) => {
2621
+ if ((await ensureModules()).tavern !== true) return missingFeature('tavern')
2436
2622
  const ws = await root(body)
2437
2623
  const id = String(body?.id ?? '').trim()
2438
2624
  if (id === '') return { ok: false, error: '这一场找不到了' }
@@ -2443,12 +2629,14 @@ function buildApi(ctx, workspace, config, options) {
2443
2629
 
2444
2630
  /** 书架:所有书。 */
2445
2631
  'novel.books': async (body) => {
2632
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2446
2633
  const ws = await root(body)
2447
2634
  return await novel.listBooks(ws)
2448
2635
  },
2449
2636
 
2450
2637
  /** 新开一本。 */
2451
2638
  'novel.create': async (body) => {
2639
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2452
2640
  const ws = await root(body)
2453
2641
  return await novel.createBook(ws, {
2454
2642
  title: body?.title,
@@ -2459,6 +2647,7 @@ function buildApi(ctx, workspace, config, options) {
2459
2647
 
2460
2648
  /** 打开一本书(含章节清单)。 */
2461
2649
  'novel.get': async (body) => {
2650
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2462
2651
  const ws = await root(body)
2463
2652
  const id = String(body?.id ?? '').trim()
2464
2653
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2467,6 +2656,7 @@ function buildApi(ctx, workspace, config, options) {
2467
2656
 
2468
2657
  /** 改书的元信息(书名 / 题材 / 一句话)。 */
2469
2658
  'novel.update': async (body) => {
2659
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2470
2660
  const ws = await root(body)
2471
2661
  const id = String(body?.id ?? '').trim()
2472
2662
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2479,6 +2669,7 @@ function buildApi(ctx, workspace, config, options) {
2479
2669
 
2480
2670
  /** 这一章不要了。 */
2481
2671
  'novel.chapter.delete': async (body) => {
2672
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2482
2673
  const ws = await root(body)
2483
2674
  const id = String(body?.id ?? '').trim()
2484
2675
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2487,6 +2678,7 @@ function buildApi(ctx, workspace, config, options) {
2487
2678
 
2488
2679
  /** 整本书不要了。 */
2489
2680
  'novel.delete': async (body) => {
2681
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2490
2682
  const ws = await root(body)
2491
2683
  const id = String(body?.id ?? '').trim()
2492
2684
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2497,6 +2689,7 @@ function buildApi(ctx, workspace, config, options) {
2497
2689
 
2498
2690
  /** 读大纲。 */
2499
2691
  'novel.outline.get': async (body) => {
2692
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2500
2693
  const ws = await root(body)
2501
2694
  const id = String(body?.id ?? '').trim()
2502
2695
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2505,6 +2698,7 @@ function buildApi(ctx, workspace, config, options) {
2505
2698
 
2506
2699
  /** 自己写 / 改大纲(人也在这里改)。 */
2507
2700
  'novel.outline.save': async (body) => {
2701
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2508
2702
  const ws = await root(body)
2509
2703
  const id = String(body?.id ?? '').trim()
2510
2704
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2518,6 +2712,8 @@ function buildApi(ctx, workspace, config, options) {
2518
2712
  * 改完再一章一章让它写。不落盘的话刷新一下就没了,白等一次模型。
2519
2713
  */
2520
2714
  'novel.outline.draft': async (body) => {
2715
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2716
+ if ((await ensureModules()).presets !== true) return missingFeature('presets')
2521
2717
  const ws = await root(body)
2522
2718
  const id = String(body?.id ?? '').trim()
2523
2719
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2544,8 +2740,13 @@ function buildApi(ctx, workspace, config, options) {
2544
2740
  chapters: Number(body?.chapters) || 12,
2545
2741
  ask: body?.ask,
2546
2742
  })
2743
+ const outlinePreset = await presets.resolve(ws, body?.preset)
2744
+ const outlineNote = outlinePreset.ok === true && outlinePreset.preset !== null ? String(outlinePreset.preset.prompt ?? '') : ''
2547
2745
  const called = await callModel(ctx, {
2548
- system: '你是一个会写长篇小说的人。你先想清楚整本书怎么走,再动手写。',
2746
+ system: [
2747
+ '你是一个会写长篇小说的人。你先想清楚整本书怎么走,再动手写。',
2748
+ outlineNote === '' ? '' : `\n【这本书怎么写】\n${outlineNote}`,
2749
+ ].filter((x) => x !== '').join('\n'),
2549
2750
  user: users,
2550
2751
  model: body?.model,
2551
2752
  })
@@ -2554,7 +2755,55 @@ function buildApi(ctx, workspace, config, options) {
2554
2755
  if (text === '') return { ok: false, error: 'AI 这次没给出东西,再点一次试试。' }
2555
2756
  const saved = await novel.writeOutline(ws, id, text)
2556
2757
  if (saved.ok !== true) return saved
2557
- return { ok: true, text, ...novel.parseOutline(text), path: saved.path }
2758
+ // 以前这里把 parseOutline 的结果展开在 ok:true 后面,而它自带一个
2759
+ // ok(=「扒到几章」是否大于 0)。AI 写得散、一行「第 N 章:」都没有时,
2760
+ // 文件其实已经写进去了,却返回 ok:false,界面报「这次没想出一个字」。
2761
+ const parsed = novel.parseOutline(text)
2762
+ return {
2763
+ ok: true,
2764
+ text,
2765
+ path: saved.path,
2766
+ theme: parsed.theme,
2767
+ ending: parsed.ending,
2768
+ chapters: parsed.chapters,
2769
+ ...(parsed.chapters.length > 0 ? {} : { warning: '这一版大纲里没认出「第 N 章:」这样的行,文件已经存下了,你可以自己补上章号。' }),
2770
+ }
2771
+ },
2772
+
2773
+ /**
2774
+ * 整本导出成一整篇文字。
2775
+ *
2776
+ * 用户电脑上只有这个插件,不会去翻 books/ 底下那一堆 001.md。
2777
+ * 写完一本书要能一口气复制走,而不是一章一章点开来复制。
2778
+ */
2779
+ 'novel.export': async (body) => {
2780
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2781
+ const ws = await root(body)
2782
+ const id = String(body?.id ?? '').trim()
2783
+ if (id === '') return { ok: false, error: '没有说是哪本书' }
2784
+ const got = await novel.readBook(ws, id)
2785
+ if (got.ok !== true) return got
2786
+
2787
+ const lines = []
2788
+ const title = String(got.data?.title ?? id).trim()
2789
+ lines.push(`# ${title === '' ? '未命名' : title}`)
2790
+ lines.push('')
2791
+ if (String(got.idea ?? '').trim() !== '') {
2792
+ lines.push(`> ${String(got.idea).trim()}`)
2793
+ lines.push('')
2794
+ }
2795
+ let total = 0
2796
+ for (const chapter of got.chapters) {
2797
+ const one = await novel.readChapter(ws, id, chapter.index)
2798
+ if (one.ok !== true) continue
2799
+ lines.push(`## 第 ${chapter.index} 章`)
2800
+ lines.push('')
2801
+ lines.push(String(one.body ?? '').trim())
2802
+ lines.push('')
2803
+ total += 1
2804
+ }
2805
+ if (total === 0) return { ok: false, error: '这本书还一章都没有。先写一章,再导出。' }
2806
+ return { ok: true, title, chapters: total, text: lines.join('\n').trim() + '\n' }
2558
2807
  },
2559
2808
 
2560
2809
  /**
@@ -2564,51 +2813,336 @@ function buildApi(ctx, workspace, config, options) {
2564
2813
  * 不要它夸——「写得很好」这种话对写东西的人毫无用处。
2565
2814
  */
2566
2815
  'novel.chapter.review': async (body) => {
2816
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2567
2817
  const ws = await root(body)
2568
2818
  const id = String(body?.id ?? '').trim()
2569
2819
  if (id === '') return { ok: false, error: '没有说是哪本书' }
2570
- const book = await novel.readBook(ws, id)
2571
- if (book.ok !== true) return book
2572
2820
  const index = Number(body?.index) || 0
2573
2821
  const got = await novel.readChapter(ws, id, index)
2574
2822
  if (got.ok !== true) return got
2575
2823
  const bodyText = String(got.body ?? '').trim()
2576
2824
  if (bodyText === '') return { ok: false, error: '这一章还是空的,没什么可审的。' }
2825
+ if (bodyText.length > 20000) {
2826
+ return { ok: false, error: '这一章太长(超过两万字),一次读不完。先分成两章再挑毛病。' }
2827
+ }
2828
+
2829
+ // 盲审:只给正文,不给书名、不给大纲、不给「这一章本来想写什么」。
2830
+ //
2831
+ // 为什么不给:写的人心里有一套意图,看的时候会不自觉地按意图去读,
2832
+ // 于是「我本来想写这个」会替「我实际写出来的是什么」作证。
2833
+ // 换成一个什么都不知道的读者,才是这本书真正的处境。
2577
2834
  const user = [
2578
- `下面是一本小说《${String(book.data?.title ?? id)}》的第 ${index} 章。`,
2579
- String(book.idea ?? '').trim() === '' ? '' : `这本书想讲的是:${String(book.idea).trim()}`,
2835
+ '下面是一段小说正文。你之前没看过这本书,也不知道作者想写什么。',
2836
+ '你就是一个第一次读到这里的读者。',
2580
2837
  '',
2581
2838
  '【正文】',
2582
- bodyText.slice(0, 8000),
2583
- '',
2584
- '【怎么审】',
2585
- '只指出具体的问题,每条都要说清在哪一句、为什么是问题。按这个顺序:',
2586
- '1. 哪里读不懂 / 情节跳了(读者会卡住的地方)',
2587
- '2. 哪里人物不像(说话方式、做的事和前面的人设对不上)',
2588
- '3. 哪里在替读者总结(「这说明他很孤独」这类,应该把事写出来)',
2589
- '4. 哪里是空话、套话、可以整段删掉',
2839
+ bodyText,
2590
2840
  '',
2591
- '【别做的事】',
2592
- '- 不要夸。一句夸奖都不要。',
2593
- '- 不要整段重写、不要给「参考版本」。我要的是问题清单,不是替我写。',
2594
- '- 不要评论「主题」「深度」这种大词,只说字面上的问题。',
2841
+ '【读完告诉我这些】',
2842
+ '1. 你读到哪儿卡住了(那句话说不上来、那段跳了、回头看了两遍才懂)',
2843
+ '2. 你读到哪儿不信(这个人不会这么做、这件事不会这么发生)',
2844
+ '3. 你读到哪儿想跳过(哪几段你在心里划过去了)',
2845
+ '4. 哪句话是空话,删掉不影响(直接引原句)',
2595
2846
  '',
2596
- '每条一行,开头写「问题:」,然后写「怎么改:」。最多 8 条,按严重程度排。',
2597
- '如果这一章确实没什么大问题,就只说一句「没看出硬伤,只有下面这几处小地方」。',
2598
- ].filter((x) => x !== '').join('\n')
2847
+ '【怎么答】',
2848
+ '- 每条一行,先写「哪里:」再写「为什么:」。要引原句。',
2849
+ '- 最多 8 条,按你读的时候的不舒服程度排。',
2850
+ '- 不夸。一句夸奖都不要。',
2851
+ '- 不给改写版本——你只是读者,不是代笔。',
2852
+ '- 没看出问题就直接说「没卡住的地方」,不要凑条数。',
2853
+ ].join('\n')
2599
2854
  const called = await callModel(ctx, {
2600
- system: '你是一个挑毛病的编辑。你的任务不是说好话,是把问题指出来。',
2855
+ // 换了一张纸:这段系统提示只要求它当读者,不要求它当编辑,
2856
+ // 免得它从「怎么写更好」的角度出发,跑回写作者的位置上。
2857
+ system: [
2858
+ '你是一个普通读者,刚读完一段小说。',
2859
+ '你没有写过这段,也不知道作者是谁、想写什么。',
2860
+ '你只会说读的时候哪里不顺、哪里不信、哪里想跳过。',
2861
+ '你不会改稿,也不会替作者想句子。',
2862
+ body?.model === undefined || String(body.model).trim() === '' ? '' : '',
2863
+ ].filter((x) => x !== '').join('\n'),
2601
2864
  user,
2602
2865
  model: body?.model,
2603
2866
  })
2604
2867
  if (called.ok !== true) return { ok: false, error: `这次没审成:${called.error ?? '过一会儿再试一次'}` }
2605
2868
  const review = String(called.text ?? '').trim()
2606
2869
  if (review === '') return { ok: false, error: 'AI 这次没给出意见,再点一次试试。' }
2607
- return { ok: true, index, review }
2870
+ return { ok: true, index, review, chars: bodyText.length, blind: true, model: String(body?.model ?? '') }
2608
2871
  },
2609
2872
 
2610
2873
  /** 读一章。 */
2874
+ // ── 简历与规划:写简历、看差距、规划怎么走 ─────────────────
2875
+
2876
+ /** 读简历和规划(还没写过也正常,返回 null)。 */
2877
+ 'career.get': async (body) => {
2878
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2879
+ const profile = await career.readProfile(ws)
2880
+ if (profile.ok !== true) return profile
2881
+ const plan = await career.readPlan(ws)
2882
+ if (plan.ok !== true) return plan
2883
+ return {
2884
+ ok: true,
2885
+ profile: profile.data,
2886
+ profileSections: profile.sections,
2887
+ plan: plan.data,
2888
+ planSections: plan.sections,
2889
+ }
2890
+ },
2891
+
2892
+ /** 存简历。 */
2893
+ 'career.profile.save': async (body) => {
2894
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2895
+ const saved = await career.writeProfile(ws, body?.profile ?? {})
2896
+ if (saved.ok !== true) return saved
2897
+ return { ok: true, path: career.PROFILE_REL }
2898
+ },
2899
+
2900
+ /** 存规划。 */
2901
+ 'career.plan.save': async (body) => {
2902
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2903
+ const saved = await career.writePlan(ws, body?.plan ?? {})
2904
+ if (saved.ok !== true) return saved
2905
+ return { ok: true, path: career.PURPOSE_REL }
2906
+ },
2907
+
2908
+ /** 让 AI 照简历写一份投这个岗位/学校的简历。 */
2909
+ 'career.resume': async (body) => {
2910
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2911
+ const profile = await career.readProfile(ws)
2912
+ if (profile.ok !== true) return profile
2913
+ if (profile.data === null) return { ok: false, error: '还没有简历。先填一下基本情况、学过什么、做过什么。' }
2914
+ const target = String(body?.target ?? '').trim()
2915
+ if (target === '') return { ok: false, error: '先写清楚要投哪儿——公司加岗位,或者学校加专业。' }
2916
+ const built = career.buildResumePrompt({ profile: profile.sections, target })
2917
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
2918
+ if (called.ok !== true) return { ok: false, error: `这次没写出来:${called.error ?? '过一会儿再试一次'}` }
2919
+ return { ok: true, target, text: String(called.text ?? '').trim() }
2920
+ },
2921
+
2922
+ /** 看差距:目标要求的 vs 你现在有的。 */
2923
+ 'career.gap': async (body) => {
2924
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2925
+ const profile = await career.readProfile(ws)
2926
+ if (profile.ok !== true) return profile
2927
+ if (profile.data === null) return { ok: false, error: '还没有简历。先填一下基本情况、学过什么、做过什么。' }
2928
+ const target = String(body?.target ?? '').trim()
2929
+ if (target === '') return { ok: false, error: '先写清楚要够到哪儿——公司加岗位,或者学校加专业。' }
2930
+ const built = career.buildGapPrompt({ profile: profile.sections, target })
2931
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
2932
+ if (called.ok !== true) return { ok: false, error: `这次没算出来:${called.error ?? '过一会儿再试一次'}` }
2933
+ return { ok: true, target, text: String(called.text ?? '').trim() }
2934
+ },
2935
+
2936
+ /** 规划怎么走。 */
2937
+ 'career.path': async (body) => {
2938
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
2939
+ const profile = await career.readProfile(ws)
2940
+ if (profile.ok !== true) return profile
2941
+ if (profile.data === null) return { ok: false, error: '还没有简历。先填一下基本情况、学过什么、做过什么。' }
2942
+ const goal = String(body?.goal ?? '').trim()
2943
+ if (goal === '') return { ok: false, error: '先写一句「想到哪儿去」——具体的岗位、学校或状态。' }
2944
+ const horizon = String(body?.horizon ?? '1年').trim()
2945
+ const built = career.buildPathPrompt({ profile: profile.sections, goal, horizon })
2946
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
2947
+ if (called.ok !== true) return { ok: false, error: `这次没规划出来:${called.error ?? '过一会儿再试一次'}` }
2948
+ const text = String(called.text ?? '').trim()
2949
+ return { ok: true, goal, horizon, text, steps: career.parseSteps(text) }
2950
+ },
2951
+
2952
+ // ── 文字小说游戏:进到情节里,你来选,它来推 ────────────────
2953
+
2954
+ /** 一本书能开哪几局。 */
2955
+ 'game.list': async (body) => {
2956
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
2957
+ const id = String(body?.book ?? '').trim()
2958
+ if (id === '') return { ok: false, error: '没有说是哪本书' }
2959
+ return await game.listPlays(ws, id)
2960
+ },
2961
+
2962
+ /** 读一局(回到上次那个地方)。 */
2963
+ 'game.get': async (body) => {
2964
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
2965
+ const book = String(body?.book ?? '').trim()
2966
+ const id = String(body?.id ?? '').trim()
2967
+ if (book === '' || id === '') return { ok: false, error: '这一局找不到了' }
2968
+ const got = await game.readPlay(ws, book, id)
2969
+ if (got.ok !== true) return got
2970
+ const last = [...got.turns].reverse().find((t) => t.kind === 'narrate')
2971
+ return {
2972
+ ok: true, id, book, path: got.path,
2973
+ chapter: Number(got.data?.chapter) || 0,
2974
+ preset: String(got.data?.preset ?? ''),
2975
+ scene: got.scene,
2976
+ holding: got.holding,
2977
+ turns: got.turns,
2978
+ choices: game.parseChoices(String(last?.text ?? '')).choices,
2979
+ }
2980
+ },
2981
+
2982
+ /** 开一局:从某一章接着演。 */
2983
+ 'game.start': async (body) => {
2984
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
2985
+ if (mods.novel !== true) return missingFeature('novel')
2986
+ const bookId = String(body?.book ?? '').trim()
2987
+ if (bookId === '') return { ok: false, error: '没有说是哪本书' }
2988
+ const book = await novel.readBook(ws, bookId)
2989
+ if (book.ok !== true) return book
2990
+ const chapter = Number(body?.chapter) || (book.chapters.length === 0 ? 0 : book.chapters[0].index)
2991
+ // 开局那一段:优先用这一章的正文;没有就让 AI 自己起头。
2992
+ let fromChapter = ''
2993
+ if (chapter > 0) {
2994
+ const got = await novel.readChapter(ws, bookId, chapter)
2995
+ if (got.ok === true) fromChapter = novel.tailOf(got.body, 1600)
2996
+ }
2997
+ const picked = mods.presets === true ? await presets.resolve(ws, body?.preset) : { ok: true, preset: null }
2998
+ const presetNote = picked.ok === true && picked.preset !== null ? String(picked.preset.prompt ?? '') : ''
2999
+ const system = game.buildGmSystem({ bookTitle: String(book.data?.title ?? bookId), scene: '', holding: [], preset: presetNote })
3000
+ const user = game.buildGmUser({ turns: [], move: '', fromChapter })
3001
+ const called = await callModel(ctx, { system, user, model: body?.model })
3002
+ if (called.ok !== true) return { ok: false, error: `这一局开不起来:${called.error ?? '过一会儿再试一次'}` }
3003
+ const parsed = game.parseChoices(called.text)
3004
+ const id = game.newPlayId()
3005
+ const now = new Date()
3006
+ const turns = [{ kind: 'narrate', text: parsed.body }]
3007
+ const data = {
3008
+ id, book: bookId, chapter, preset: String(body?.preset ?? ''),
3009
+ created_at: now.toISOString(), updated_at: now.toISOString(), turn: 0, scene: '', holding: [],
3010
+ }
3011
+ const saved = await game.writePlay(ws, bookId, id, data, turns)
3012
+ if (saved.ok !== true) return saved
3013
+ return { ok: true, id, book: bookId, chapter, path: saved.path, text: parsed.body, choices: parsed.choices, turns }
3014
+ },
3015
+
3016
+ /** 走一步。 */
3017
+ 'game.say': async (body) => {
3018
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
3019
+ const bookId = String(body?.book ?? '').trim()
3020
+ const id = String(body?.id ?? '').trim()
3021
+ if (bookId === '' || id === '') return { ok: false, error: '这一局找不到了' }
3022
+ // 同一局的两步必须排队:这里也是「读 → 调模型(几十秒)→ 整文件写回」。
3023
+ // 键要带 bookId —— 两本书里各自有一局 `play-1` 是很正常的。
3024
+ return oneAtATime(`game:${bookId}/${id}`, async () => {
3025
+ const got = await game.readPlay(ws, bookId, id)
3026
+ if (got.ok !== true) return got
3027
+ const turns = Array.isArray(got.turns) ? got.turns : []
3028
+ const moves = turns.filter((t) => t.kind === 'choose' || t.kind === 'say').length
3029
+ if (moves >= game.MAX_TURNS) {
3030
+ return { ok: false, error: `这一局已经走了 ${moves} 步,太长了记不住前面。在这里收个尾,或者另开一局。`, turns }
3031
+ }
3032
+ const move = String(body?.move ?? '').trim()
3033
+ if (move === '') return { ok: false, error: '先选一个方向,或者自己写一句' }
3034
+ const book = mods.novel === true ? await novel.readBook(ws, bookId) : { ok: true, data: { title: bookId } }
3035
+ if (book.ok !== true) return book
3036
+ const picked = mods.presets === true ? await presets.resolve(ws, String(got.data?.preset ?? '')) : { ok: true, preset: null }
3037
+ const presetNote = picked.ok === true && picked.preset !== null ? String(picked.preset.prompt ?? '') : ''
3038
+ const system = game.buildGmSystem({ bookTitle: String(book.data?.title ?? bookId), scene: got.scene, holding: got.holding, preset: presetNote })
3039
+ const user = game.buildGmUser({ turns, move })
3040
+ const called = await callModel(ctx, { system, user, model: body?.model })
3041
+ // 模型没接上也要把你这一步记下来:不然你选过什么,下一轮它完全不知道。
3042
+ const parsed = game.parseChoices(called.ok === true ? called.text : '')
3043
+ const nextTurns = [...turns, { kind: 'choose', text: move, result: called.ok === true ? parsed.body : '' }]
3044
+ const now = new Date()
3045
+ const data = { ...got.data, updated_at: now.toISOString(), turn: moves + 1 }
3046
+ const saved = await game.writePlay(ws, bookId, id, data, nextTurns)
3047
+ if (saved.ok !== true) return saved
3048
+ if (called.ok !== true) {
3049
+ return { ok: false, error: `这一步记下了,但它没接上话:${called.error ?? '过一会儿再试一次'}`, turns: nextTurns, kept: true }
3050
+ }
3051
+ return { ok: true, id, text: parsed.body, choices: parsed.choices, turns: nextTurns }
3052
+ })
3053
+ },
3054
+
3055
+ /**
3056
+ * 把这一局演出来的东西,写成这本书的一章。
3057
+ *
3058
+ * 和酒馆那条是一个意思:演着演着发现这一段真好,就把它定下来变成正文,
3059
+ * 而不是让人自己回去照着复述一遍。
3060
+ */
3061
+ 'game.toChapter': async (body) => {
3062
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
3063
+ if (mods.novel !== true) return missingFeature('novel')
3064
+ const bookId = String(body?.book ?? '').trim()
3065
+ const id = String(body?.id ?? '').trim()
3066
+ if (bookId === '' || id === '') return { ok: false, error: '这一局找不到了' }
3067
+ const got = await game.readPlay(ws, bookId, id)
3068
+ if (got.ok !== true) return got
3069
+ const turns = Array.isArray(got.turns) ? got.turns : []
3070
+ if (turns.length === 0) return { ok: false, error: '这一局还什么都没发生,先走一步再变成一章。' }
3071
+ const book = await novel.readBook(ws, bookId)
3072
+ if (book.ok !== true) return book
3073
+ const prompt = game.buildPlayToChapterPrompt({
3074
+ bookTitle: String(book.data?.title ?? bookId),
3075
+ turns,
3076
+ note: body?.note,
3077
+ })
3078
+ const called = await callModel(ctx, { system: prompt.system, user: prompt.user, model: body?.model })
3079
+ if (called.ok !== true) return { ok: false, error: `没写成:${called.error ?? '过一会儿再试一次'}`, kept: true }
3080
+ const text = String(called.text ?? '').trim()
3081
+ if (text === '') return { ok: false, error: '这次什么都没写出来,过一会儿再试一次。' }
3082
+ const list = Array.isArray(book.chapters) ? book.chapters : []
3083
+ const last = list.length === 0 ? 0 : Number(list[list.length - 1]?.index ?? 0)
3084
+ const next = (Number.isFinite(last) ? last : 0) + 1
3085
+ const saved = await novel.writeChapter(ws, bookId, next, text)
3086
+ if (saved.ok !== true) return saved
3087
+ return { ok: true, chapter: next, text, warning: saved.warning }
3088
+ },
3089
+
3090
+ /** 这一局不要了。 */
3091
+ 'game.delete': async (body) => {
3092
+ const ws = await root(body); const mods = await ensureModules(); if (mods.game !== true) return missingFeature('game')
3093
+ const book = String(body?.book ?? '').trim()
3094
+ const id = String(body?.id ?? '').trim()
3095
+ if (book === '' || id === '') return { ok: false, error: '这一局找不到了' }
3096
+ return await game.deletePlay(ws, book, id)
3097
+ },
3098
+
3099
+ // ── 预设:三种玩法各自的演法/写法 ─────────────────────────
3100
+
3101
+ /** 哪些功能装了、哪些没装。界面按这个决定显示什么。 */
3102
+ 'features.list': async (body) => {
3103
+ const mods = await ensureModules()
3104
+ return {
3105
+ ok: true,
3106
+ features: {
3107
+ real: true,
3108
+ jobs: true,
3109
+ tavern: mods.tavern === true,
3110
+ novel: mods.novel === true,
3111
+ presets: mods.presets === true,
3112
+ game: mods.game === true && mods.novel === true,
3113
+ career: mods.career === true,
3114
+ },
3115
+ }
3116
+ },
3117
+
3118
+ /** 列预设(内置 + 自己的)。 */
3119
+ 'preset.list': async (body) => {
3120
+ const ws = await root(body); const mods = await ensureModules(); if (mods.presets !== true) return missingFeature('presets')
3121
+ return await presets.listAll(ws)
3122
+ },
3123
+
3124
+ /** 把一份内置的复制成自己的,之后能随便改。 */
3125
+ 'preset.copy': async (body) => {
3126
+ const ws = await root(body); const mods = await ensureModules(); if (mods.presets !== true) return missingFeature('presets')
3127
+ return await presets.copyBuiltin(ws, body?.id, body?.as)
3128
+ },
3129
+
3130
+ /** 存一份自己的预设(新建或改)。 */
3131
+ 'preset.save': async (body) => {
3132
+ const ws = await root(body); const mods = await ensureModules(); if (mods.presets !== true) return missingFeature('presets')
3133
+ return await presets.saveCustom(ws, { id: body?.id, mode: body?.mode, name: body?.name, desc: body?.desc, prompt: body?.prompt })
3134
+ },
3135
+
3136
+ /** 删一份自己的预设。 */
3137
+ 'preset.delete': async (body) => {
3138
+ const ws = await root(body); const mods = await ensureModules(); if (mods.presets !== true) return missingFeature('presets')
3139
+ const id = String(body?.id ?? '').trim()
3140
+ if (id === '') return { ok: false, error: '没有说是哪一份' }
3141
+ return await presets.deleteCustom(ws, id)
3142
+ },
3143
+
2611
3144
  'novel.chapter.get': async (body) => {
3145
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2612
3146
  const ws = await root(body)
2613
3147
  const id = String(body?.id ?? '').trim()
2614
3148
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2617,6 +3151,7 @@ function buildApi(ctx, workspace, config, options) {
2617
3151
 
2618
3152
  /** 自己写(或改)一章,直接在编辑器里手写。 */
2619
3153
  'novel.chapter.save': async (body) => {
3154
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2620
3155
  const ws = await root(body)
2621
3156
  const id = String(body?.id ?? '').trim()
2622
3157
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2631,6 +3166,7 @@ function buildApi(ctx, workspace, config, options) {
2631
3166
  * 只给上一章它不知道这本书要往哪走。
2632
3167
  */
2633
3168
  'novel.chapter.draft': async (body) => {
3169
+ if ((await ensureModules()).novel !== true) return missingFeature('novel')
2634
3170
  const ws = await root(body)
2635
3171
  const id = String(body?.id ?? '').trim()
2636
3172
  if (id === '') return { ok: false, error: '没有说是哪本书' }
@@ -2672,7 +3208,12 @@ function buildApi(ctx, workspace, config, options) {
2672
3208
  const outline = await novel.readOutline(ws, id)
2673
3209
  const outlineText = outline.ok === true && outline.text !== '' ? outline.text : ''
2674
3210
  const planItem = outline.ok === true ? (outline.chapters ?? []).find((c) => c.index === index) : undefined
2675
- const system = '你是一个写小说的人。你的任务是把故事写下去,不是解释、不是评论、不是总结。'
3211
+ const writePreset = await presets.resolve(ws, body?.preset)
3212
+ const presetNote = writePreset.ok === true && writePreset.preset !== null ? String(writePreset.preset.prompt ?? '') : ''
3213
+ const system = [
3214
+ '你是一个写小说的人。你的任务是把故事写下去,不是解释、不是评论、不是总结。',
3215
+ presetNote === '' ? '' : `\n【这一段怎么写】\n${presetNote}`,
3216
+ ].filter((x) => x !== '').join('\n')
2676
3217
  const user = novel.buildChapterPrompt({
2677
3218
  title: String(book.data?.title ?? id),
2678
3219
  idea: String(book.idea ?? ''),
@@ -2719,9 +3260,22 @@ async function gatherCast(ws, wants) {
2719
3260
  if (rel === '') continue
2720
3261
  const card = await store.readCard(ws, rel)
2721
3262
  if (card.ok !== true) continue
2722
- const persona = tavern.personaFromCard(card.data, card.sections)
2723
- if (persona.text === '') continue
2724
- out.push(`【${persona.name}】${persona.text.slice(0, 500)}`)
3263
+ // 酒馆模块被删掉时,这里自己拼一份最小的人设——
3264
+ // 「写小说」不该因为「酒馆」没了就用不了。
3265
+ let name = String(card.data?.name ?? '').trim()
3266
+ let text = ''
3267
+ if (tavern !== null) {
3268
+ const persona = tavern.personaFromCard(card.data, card.sections)
3269
+ name = persona.name
3270
+ text = persona.text
3271
+ } else {
3272
+ const parts = ['自述', '性格', '口癖', '外貌']
3273
+ .map((title) => core.sectionBody(card.sections, title).trim())
3274
+ .filter((x) => x !== '')
3275
+ text = parts.join('\n')
3276
+ }
3277
+ if (text === '') continue
3278
+ out.push(`【${name === '' ? '这个人' : name}】${text.slice(0, 500)}`)
2725
3279
  }
2726
3280
  return out
2727
3281
  }
@@ -2962,45 +3516,118 @@ function blankPng() {
2962
3516
  * skill,而不是整个插件起不来。
2963
3517
  */
2964
3518
  function registerInterviewSkill(ctx) {
3519
+ registerBundledSkill(ctx, {
3520
+ dir: 'lifecard-interview',
3521
+ name: 'lifecard-interview',
3522
+ fallback: '引导式对话访谈,把一张人物卡问出来。',
3523
+ label: '访谈',
3524
+ })
3525
+ registerBundledSkill(ctx, {
3526
+ dir: 'lifecard-novel-writing',
3527
+ name: 'lifecard-novel-writing',
3528
+ fallback: '中文小说与长文的写法:先分清用不用人物卡,按传统文学的标准写正文,要连载节奏就切。',
3529
+ label: '写作',
3530
+ })
3531
+ // 这三份是写作用得上的通用手艺,随包一起发:装插件即等于有,
3532
+ // 换台机器不必再单独装一遍。名字与内容都保持原样,方便用户照旧用
3533
+ // `/human-writing`、`/blind-review-loop`、`/visual-novel` 唤起。
3534
+ //
3535
+ // 同名冲突时让位:用户自己那份通常更新,硬盖上去等于拿旧版本把新版本
3536
+ // 顶掉,而且他看不出来。
3537
+ registerBundledSkill(ctx, {
3538
+ dir: 'human-writing',
3539
+ name: 'human-writing',
3540
+ fallback: '通用中文创作与改稿:先看材料够不够,再写成有人在说话的样子。',
3541
+ label: '写作手艺',
3542
+ yieldToExisting: true,
3543
+ })
3544
+ registerBundledSkill(ctx, {
3545
+ dir: 'blind-review-loop',
3546
+ name: 'blind-review-loop',
3547
+ fallback: '盲评迭代改稿:冻结副本、开无上下文评审员、把意见分诊后定向改,再评一轮。',
3548
+ label: '盲评改稿',
3549
+ yieldToExisting: true,
3550
+ })
3551
+ registerBundledSkill(ctx, {
3552
+ dir: 'visual-novel',
3553
+ name: 'visual-novel',
3554
+ fallback: '视觉小说:分支剧本、对话框、存档、回放这些读者以为本来就在的东西。',
3555
+ label: '视觉小说',
3556
+ yieldToExisting: true,
3557
+ })
3558
+ }
3559
+
3560
+ /**
3561
+ * 注册一个随包 skill。两处共同点都在这里:skills/SKILL.md 与 lib/ 同包,
3562
+ * 用 import.meta.url 定位(不依赖 cwd);没有 skills 服务时只少一个 skill,
3563
+ * 不能让整个插件起不来。
3564
+ */
3565
+ function registerBundledSkill(ctx, spec) {
2965
3566
  const skills = ctx.reflect?.get?.('skills', false)
2966
3567
  if (skills === undefined || skills === null || typeof skills.register !== 'function') {
2967
- ctx.logger?.warn?.('[lifecard] 没有 skills 服务,访谈 skill 未注册(不影响卡库功能)')
3568
+ ctx.logger?.warn?.(`[lifecard] 没有 skills 服务,${spec.label} skill 未注册(不影响卡库功能)`)
2968
3569
  return
2969
3570
  }
2970
- const body = interviewSkillBody()
3571
+ if (spec.yieldToExisting === true && hasSkillNamed(skills, spec.name)) {
3572
+ // 用户已经有一份同名的:他的更新,别盖。
3573
+ ctx.logger?.info?.(`[lifecard] 已经有 ${spec.name} 这个 skill,插件这份不再注册`)
3574
+ return
3575
+ }
3576
+ const body = bundledSkillBody(spec.dir)
2971
3577
  if (body === '') {
2972
- ctx.logger?.warn?.('[lifecard] 找不到 skills/lifecard-interview/SKILL.md,访谈 skill 未注册')
3578
+ ctx.logger?.warn?.(`[lifecard] 找不到 skills/${spec.dir}/SKILL.md,${spec.label} skill 未注册`)
2973
3579
  return
2974
3580
  }
2975
3581
  const { frontmatter, content } = splitSkillFile(body)
2976
3582
  ctx.effect(
2977
3583
  () => skills.register({
2978
- name: 'lifecard-interview',
2979
- description: frontmatter.description ?? '引导式对话访谈,把一张人物卡问出来。',
3584
+ name: spec.name,
3585
+ description: frontmatter.description ?? spec.fallback,
2980
3586
  whenToUse: frontmatter.whenToUse,
2981
3587
  content,
2982
3588
  source: 'lifecard',
3589
+ // 带上目录:SKILL.md 里说的 references/xxx.md、scripts/xxx.py
3590
+ // 才有地方可查。不带 resourceBase,模型看到「读取 references/…」
3591
+ // 只能瞎猜路径。
3592
+ resourceBase: { kind: 'directory', path: bundledSkillDir(spec.dir) },
2983
3593
  invocation: { modelInvocable: true, userInvocable: true },
2984
3594
  }),
2985
- 'dsh-lifecard: lifecard-interview skill',
3595
+ `dsh-lifecard: ${spec.name} skill`,
2986
3596
  )
2987
3597
  }
2988
3598
 
3599
+ /** 目录里有没有同名 skill(用户自己装的那份)。问不到就当没有。 */
3600
+ function hasSkillNamed(skills, name) {
3601
+ if (typeof skills.list !== 'function') return false
3602
+ try {
3603
+ const list = skills.list()
3604
+ if (!Array.isArray(list)) return false
3605
+ return list.some((s) => String(s?.name ?? '') === name)
3606
+ } catch {
3607
+ return false
3608
+ }
3609
+ }
3610
+
2989
3611
  /** SKILL.md 与 lib/ 同包,用 import.meta.url 定位,不依赖 cwd。 */
2990
- function interviewSkillPath() {
2991
- return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'lifecard-interview', 'SKILL.md')
3612
+ function bundledSkillPath(dir) {
3613
+ return path.join(bundledSkillDir(dir), 'SKILL.md')
2992
3614
  }
2993
3615
 
2994
- let interviewSkillCache
2995
- function interviewSkillBody() {
2996
- if (interviewSkillCache === undefined) {
3616
+ /** 这份 skill 的目录(references/、scripts/ 都在它下面)。 */
3617
+ function bundledSkillDir(dir) {
3618
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', dir)
3619
+ }
3620
+
3621
+ const bundledSkillCache = new Map()
3622
+ function bundledSkillBody(dir) {
3623
+ if (!bundledSkillCache.has(dir)) {
2997
3624
  try {
2998
- interviewSkillCache = readFileSync(interviewSkillPath(), 'utf8')
3625
+ bundledSkillCache.set(dir, readFileSync(bundledSkillPath(dir), 'utf8'))
2999
3626
  } catch {
3000
- interviewSkillCache = ''
3627
+ bundledSkillCache.set(dir, '')
3001
3628
  }
3002
3629
  }
3003
- return interviewSkillCache
3630
+ return bundledSkillCache.get(dir)
3004
3631
  }
3005
3632
 
3006
3633
  /** 拆 YAML frontmatter(只认 `key: value` 单行,够用且不引依赖)。 */
@@ -3053,6 +3680,20 @@ export function apply(ctx, config) {
3053
3680
 
3054
3681
  registerInterviewSkill(ctx)
3055
3682
 
3683
+ // 把人物卡、世界书交给模型的那几个只读工具。挂在宿主这一层,所以不只是
3684
+ // 「LC 酒馆 / LC 小说 / LC 现实」三个预设,任何预览里都能调。
3685
+ // 用 ctx.inject 等 tools 服务就绪:apply 跑的时候它可能还没起来,
3686
+ // 直接 ctx.get('tools') 会拿到 undefined,工具就静默少了。
3687
+ if (typeof ctx.inject === 'function') {
3688
+ ctx.inject(['tools'], (toolCtx) => {
3689
+ try {
3690
+ lifecardTools.registerTools(toolCtx, settings)
3691
+ } catch (error) {
3692
+ console.error('[lifecard] 只读工具没挂上:', error)
3693
+ }
3694
+ })
3695
+ }
3696
+
3056
3697
  ctx.effect(
3057
3698
  () => ctx.webServer.register({
3058
3699
  kind: 'prefix',