dsh-lifecard 0.3.1 → 0.5.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/lib/index.js CHANGED
@@ -20,6 +20,7 @@ import * as codec from './codec.js'
20
20
  import * as store from './store.js'
21
21
  import * as prose from './prose.js'
22
22
  import * as prompts from './prompts.js'
23
+ import * as diary from './diary.js'
23
24
 
24
25
  import * as score from './score.js'
25
26
  import * as memory from './memory.js'
@@ -1037,6 +1038,7 @@ function buildApi(ctx, workspace, config, options) {
1037
1038
  real: String(pins.real ?? ''),
1038
1039
  tavern: String(pins.tavern ?? ''),
1039
1040
  novel: String(pins.novel ?? ''),
1041
+ diary: String(pins.diary ?? ''),
1040
1042
  },
1041
1043
  }
1042
1044
  },
@@ -1069,17 +1071,193 @@ function buildApi(ctx, workspace, config, options) {
1069
1071
  'card.defaults.set': async (body) => {
1070
1072
  const ws = await root(body)
1071
1073
  const mode = String(body?.mode ?? '')
1072
- if (mode !== 'real' && mode !== 'tavern' && mode !== 'novel') {
1074
+ if (mode !== 'real' && mode !== 'tavern' && mode !== 'novel' && mode !== 'diary') {
1073
1075
  return { ok: false, error: '不知道你说的是哪扇门。' }
1074
1076
  }
1075
1077
  const id = String(body?.id ?? '').trim()
1076
1078
  const cfg = await store.readConfigState(ws)
1077
1079
  if (cfg.ok !== true) return { ok: false, error: cfg.error ?? '这个文件夹里的设置读不出来。' }
1078
- const pins = { real: '', tavern: '', novel: '', ...(cfg.config?.default_cards ?? {}) }
1080
+ const pins = { real: '', tavern: '', novel: '', diary: '', ...(cfg.config?.default_cards ?? {}) }
1079
1081
  pins[mode] = id
1080
- await store.writeConfig(ws, { default_cards: pins })
1082
+ const saved = await store.writeConfig(ws, { default_cards: pins })
1083
+ if (saved?.ok !== true) return { ok: false, error: saved?.error ?? '这一张没能记住,下次还得再挑一次。', cards: pins }
1081
1084
  return { ok: true, cards: pins }
1082
1085
  },
1086
+
1087
+ /**
1088
+ * 人物关系网:以「我」为中心,把认识的人一圈一圈摆开。
1089
+ *
1090
+ * 这一版不做图,只把「谁是谁、离我多远、多亲」算清楚交给界面。
1091
+ * 距离的口径:
1092
+ * ring 0 = 我自己(kind self,或者老档案里 relation 写「我」的那张)
1093
+ * ring 1 = 直接写着和我有关系的人(他的 relation 是「父亲」「朋友」这种)
1094
+ * ring 2 = 只和某个 ring 1 的人有关系的人(比如「我姨」只和妈妈连着)
1095
+ * 没有任何关系线索的人不进网——放进去也只是一堆没有边的点。
1096
+ */
1097
+ 'relations.net': async (body) => {
1098
+ const ws = await root(body)
1099
+ const all = await store.listAll(ws)
1100
+ const cards = Array.isArray(all.cards) ? all.cards : []
1101
+ const edges = Array.isArray(all.relations) ? all.relations : []
1102
+ const labelOf = new Map(prompts.RELATION_TYPES.map((one) => [String(one.id), String(one.label)]))
1103
+ const selfCard = cards.find((c) => String(c.kind ?? '') === 'self')
1104
+ ?? cards.find((c) => String(c.kind ?? '') === 'real' && String(c.relation ?? '').trim() === '我')
1105
+ ?? null
1106
+ const selfId = selfCard === null ? '' : String(selfCard.id ?? '')
1107
+ const nodeOf = (c) => ({
1108
+ id: String(c.id ?? ''),
1109
+ name: String(c.name ?? '').trim() === '' ? '(还没起名字)' : String(c.name),
1110
+ kind: String(c.kind ?? 'real'),
1111
+ relation: String(c.relation ?? '').trim(),
1112
+ relationLabel: String(c.relation ?? '').trim() === ''
1113
+ ? ''
1114
+ : (labelOf.get(String(c.relation).trim()) ?? String(c.relation).trim()),
1115
+ extras: Array.isArray(c.relation_extra) ? c.relation_extra.filter((x) => typeof x === 'string') : [],
1116
+ tags: Array.isArray(c.tags) ? c.tags : [],
1117
+ intro: String(c.intro ?? ''),
1118
+ coverage: Number(c.coverage ?? 0),
1119
+ path: String(c.path ?? ''),
1120
+ })
1121
+
1122
+ const rings = { 0: [], 1: [], 2: [] }
1123
+ const placed = new Map()
1124
+ if (selfCard !== null) {
1125
+ rings[0].push(nodeOf(selfCard))
1126
+ placed.set(selfId, 0)
1127
+ }
1128
+ // 第一轮:卡上自己写着关系的人,都算直接认识(ring 1)。
1129
+ // 这一轮得排在关系边前面——边只回答「再往外还有谁」,它得有落脚点;
1130
+ // 反过来先处理边,一圈还没人的时候边就没有起点可用,第 2 圈永远是空的。
1131
+ for (const card of cards) {
1132
+ const id = String(card.id ?? '')
1133
+ if (id === '' || placed.has(id)) continue
1134
+ const tag = String(card.relation ?? '').trim()
1135
+ if (tag === '' && String(card.kind ?? '') !== 'self') continue
1136
+ placed.set(id, 1)
1137
+ }
1138
+ // 第二轮:关系边再往外扩一层。两端都是 id,最准。
1139
+ // 只扩一层——再往外的人已经不是「我认识的人」,是「我认识的人认识的人」。
1140
+ for (const edge of edges) {
1141
+ const from = String(edge?.from ?? '')
1142
+ const to = String(edge?.to ?? '')
1143
+ if (from === '' || to === '') continue
1144
+ const depth = placed.get(from)
1145
+ if (depth !== undefined && depth < 2 && !placed.has(to)) placed.set(to, depth + 1)
1146
+ }
1147
+ const byId = new Map(cards.map((c) => [String(c.id ?? ''), c]))
1148
+ for (const [id, depth] of placed) {
1149
+ if (depth === 0) continue
1150
+ const card = byId.get(id)
1151
+ if (card === undefined) continue
1152
+ const node = nodeOf(card)
1153
+ // 越亲的越靠里:ring 2 里如果还带着「也是家人」这种补充关系,也算一回事。
1154
+ rings[depth].push(node)
1155
+ }
1156
+ rings[1].sort((a, b) => (b.coverage - a.coverage) || (a.name < b.name ? -1 : 1))
1157
+ rings[2].sort((a, b) => (b.coverage - a.coverage) || (a.name < b.name ? -1 : 1))
1158
+
1159
+ const inNet = new Set([...rings[0], ...rings[1], ...rings[2]].map((n) => n.id))
1160
+ // 网外的人不是「没有关系的人」,是「卡片在、还没写关系的人」。
1161
+ // 世界书、设定、偏好这几种根本不是人;虚构角色是「扮演用的角色」,
1162
+ // 不是认识的人——这一屏只在真实人物这扇门里给,混进来读着像出了错。
1163
+ // 真写了关系的(relation 非空)仍然进圈,因为那说明用户自己把她当成了一个人。
1164
+ const notPeople = new Set(['world', 'system', 'lens', 'relation', 'fictional'])
1165
+ const outside = cards
1166
+ .filter((c) => !inNet.has(String(c.id ?? '')))
1167
+ .filter((c) => !notPeople.has(String(c.kind ?? 'real')))
1168
+ .map((c) => ({
1169
+ id: String(c.id ?? ''),
1170
+ name: String(c.name ?? ''),
1171
+ kind: String(c.kind ?? 'real'),
1172
+ path: String(c.path ?? ''),
1173
+ }))
1174
+
1175
+ return {
1176
+ ok: true,
1177
+ self: selfCard === null ? null : nodeOf(selfCard),
1178
+ rings: { self: rings[0], inner: rings[1], outer: rings[2] },
1179
+ // 边不只要「谁连谁」,还要能拿回去编辑:路径是它在磁盘上的位置,
1180
+ // 点开一条边要能读到类型、亲疏、当时那句话。
1181
+ edges: edges.map((e) => ({
1182
+ path: String(e.path ?? ''),
1183
+ from: String(e.from ?? ''),
1184
+ to: String(e.to ?? ''),
1185
+ type: String(e.type ?? ''),
1186
+ label: String(e.label ?? ''),
1187
+ affinity: e.affinity,
1188
+ trust: e.trust,
1189
+ authority: e.authority,
1190
+ dependency: e.dependency,
1191
+ note: String(e.note ?? ''),
1192
+ at: String(e.at ?? ''),
1193
+ })),
1194
+ counts: { self: rings[0].length, inner: rings[1].length, outer: rings[2].length, outside: outside.length },
1195
+ outside,
1196
+ }
1197
+ },
1198
+
1199
+ /**
1200
+ * 写一条关系边:谁和谁是什么关系。
1201
+ *
1202
+ * 这一屏以前只能看图不能改——「我表姐也是我妈的女儿」这件事,
1203
+ * 用户只能自己去 relations/ 里手写 YAML。这里补上那条路。
1204
+ *
1205
+ * 只写一条边,不同时改两张卡:卡片上那个 `relation` 是「他和我」
1206
+ * 的关系(一对一),边是「谁和谁」(可以有很多条)。混在一起写,
1207
+ * 一次点保存会同时动两处,出错时说不清是哪一步坏的。
1208
+ */
1209
+ 'relations.save': async (body) => {
1210
+ const ws = await root(body)
1211
+ const all = await store.listAll(ws)
1212
+ const cards = Array.isArray(all.cards) ? all.cards : []
1213
+ // 两端都可以给 id 或名字——界面上拿到的往往是名字,硬要求 id
1214
+ // 等于让用户自己去看文件名。
1215
+ const findId = (want) => {
1216
+ const key = String(want ?? '').trim()
1217
+ if (key === '') return null
1218
+ const hit = cards.find((c) => String(c.id ?? '') === key)
1219
+ ?? cards.find((c) => String(c.name ?? '').trim() === key)
1220
+ return hit === undefined ? null : hit
1221
+ }
1222
+ const fromCard = findId(body?.from)
1223
+ const toCard = findId(body?.to)
1224
+ if (fromCard === null) return { ok: false, error: `没找到「${String(body?.from ?? '').trim()}」这个人。先在卡片里建好,再来连。` }
1225
+ if (toCard === null) return { ok: false, error: `没找到「${String(body?.to ?? '').trim()}」这个人。先在卡片里建好,再来连。` }
1226
+ if (String(fromCard.id) === String(toCard.id)) {
1227
+ return { ok: false, error: '这两个是同一张卡。关系要连两个不同的人。' }
1228
+ }
1229
+ const saved = await store.writeRelation(ws, {
1230
+ from: fromCard.id,
1231
+ to: toCard.id,
1232
+ type: body?.type,
1233
+ label: body?.label,
1234
+ since: body?.since,
1235
+ affinity: body?.affinity,
1236
+ trust: body?.trust,
1237
+ note: body?.note,
1238
+ authority: body?.authority,
1239
+ dependency: body?.dependency,
1240
+ })
1241
+ if (saved.ok !== true) return saved
1242
+ return {
1243
+ ok: true,
1244
+ path: saved.path,
1245
+ created: saved.created === true,
1246
+ note: saved.created === true
1247
+ ? `连上了:「${fromCard.name || fromCard.id}」对「${toCard.name || toCard.id}」是什么,已经记下来。`
1248
+ : '改好了。',
1249
+ }
1250
+ },
1251
+
1252
+ /** 断开一条关系。搬进回收目录,不直接抹掉(和删卡一样能反悔)。 */
1253
+ 'relations.delete': async (body) => {
1254
+ const ws = await root(body)
1255
+ const safe = await insideWorkspace(ws, body?.path)
1256
+ if (safe.ok !== true) return { ok: false, error: safe.error }
1257
+ const gone = await store.deleteRelation(ws, safe.rel)
1258
+ if (gone.ok !== true) return gone
1259
+ return { ok: true, path: gone.path, note: '这条关系断开了。原来的那份还在回收目录里,需要的话能找回来。' }
1260
+ },
1083
1261
  /**
1084
1262
  * 把一扇门从界面上收起来 / 装回来。
1085
1263
  *
@@ -3189,6 +3367,82 @@ function buildApi(ctx, workspace, config, options) {
3189
3367
  return { ok: true, target, text: String(called.text ?? '').trim() }
3190
3368
  },
3191
3369
 
3370
+ /**
3371
+ * 从一张人物卡里把「能写进简历的东西」摘出来。
3372
+ *
3373
+ * 只摘不写:这一趟不碰简历文件。用户先看见摘了什么、来自哪一句,
3374
+ * 自己划掉不要的,再点一次才并进去。模型这一步只许抄原文,
3375
+ * 每条都要过逐字比对(捡不了就整条丢掉,不悄悄放宽)。
3376
+ */
3377
+ 'career.mine': async (body) => {
3378
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
3379
+ const wanted = String(body?.card ?? '').trim()
3380
+ if (wanted === '') return { ok: false, error: '先挑一张卡。挑好我才能从里面往出摘。' }
3381
+ const rel = await store.findCardByRelOrId(ws, wanted)
3382
+ if (rel === null || rel === undefined) return { ok: false, error: `没找到「${wanted}」这张卡。` }
3383
+ const card = await store.readCard(ws, rel)
3384
+ if (card.ok !== true) return { ok: false, error: card.error ?? '这张卡读不出来。' }
3385
+ // 卡的正文才是材料。只拿 name 去问,模型只能靠猜。
3386
+ const text = String(card.text ?? '').trim()
3387
+ if (text === '') return { ok: false, error: '这张卡还是空的,里面没有能摘的东西。' }
3388
+ const name = String(card.data?.name ?? '').trim()
3389
+ const built = career.buildMinePrompt({ cardText: text, name })
3390
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
3391
+ if (called.ok !== true) return { ok: false, error: `这次没摘出来:${called.error ?? '过一会儿再试一次'}` }
3392
+ const parsed = extractJson(called.text)
3393
+ if (parsed === null) return { ok: false, error: '这次回来的东西看不明白,再点一次试试。' }
3394
+ const raw = Array.isArray(parsed?.items) ? parsed.items : []
3395
+ // 材料表:材料名要和模型写的 evidence.material 对得上,这里只有一份,
3396
+ // 所以名字就叫这个(模型写全路径也认,verifyQuote 两头都能对上)。
3397
+ const materials = { [rel]: text }
3398
+ const kept = []
3399
+ const dropped = []
3400
+ for (const one of raw) {
3401
+ if (one === null || typeof one !== 'object') continue
3402
+ const slot = String(one.slot ?? '').trim()
3403
+ const line = String(one.text ?? '').trim()
3404
+ const quote = String(one.quote ?? '').trim()
3405
+ if (!career.MINE_SLOTS.includes(slot) || line === '') { dropped.push({ text: line, why: '这一条没说清放到哪儿' }); continue }
3406
+ const check = core.verifyQuote({ evidence: { material: rel, quote } }, materials)
3407
+ if (check.ok !== true) { dropped.push({ text: line, why: check.reason ?? '原文里找不到这一句' }); continue }
3408
+ kept.push({ slot, text: line, quote, line: check.line })
3409
+ }
3410
+ return {
3411
+ ok: true,
3412
+ card: { id: String(card.data?.id ?? ''), name, path: rel },
3413
+ groups: career.groupMined(kept),
3414
+ items: kept,
3415
+ dropped,
3416
+ labels: career.MINE_SLOT_LABELS,
3417
+ }
3418
+ },
3419
+
3420
+ /**
3421
+ * 把挑中的几条并进简历。只往后加,不改用户自己写的那几行。
3422
+ *
3423
+ * 为什么不在这里再调一次模型:摘出来的那一句就是要写进去的那一句。
3424
+ * 再让它「润色一下」,就会多出没发生过的细节。
3425
+ */
3426
+ 'career.merge': async (body) => {
3427
+ const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
3428
+ const rows = Array.isArray(body?.items) ? body.items : []
3429
+ const items = rows
3430
+ .map((one) => ({
3431
+ slot: String(one?.slot ?? '').trim(),
3432
+ text: String(one?.text ?? '').trim(),
3433
+ }))
3434
+ .filter((one) => career.MINE_SLOTS.includes(one.slot) && one.text !== '')
3435
+ if (items.length === 0) return { ok: false, error: '一条都没挑,那就没东西可并。' }
3436
+ const profile = await career.readProfile(ws)
3437
+ if (profile.ok !== true) return profile
3438
+ const mined = career.groupMined(items)
3439
+ const merged = career.mergeProfile(profile.sections ?? {}, mined)
3440
+ if (merged.added.length === 0) return { ok: true, added: 0, profile: merged.profile, note: '这几条简历里本来就有,没重复加。' }
3441
+ const saved = await career.writeProfile(ws, { ...(profile.data ?? {}), ...merged.profile })
3442
+ if (saved.ok !== true) return saved
3443
+ return { ok: true, added: merged.added.length, profile: merged.profile, path: saved.path }
3444
+ },
3445
+
3192
3446
  /** 看差距:目标要求的 vs 你现在有的。 */
3193
3447
  'career.gap': async (body) => {
3194
3448
  const ws = await root(body); const mods = await ensureModules(); if (mods.career !== true) return missingFeature('career')
@@ -3219,6 +3473,207 @@ function buildApi(ctx, workspace, config, options) {
3219
3473
  return { ok: true, goal, horizon, text, steps: career.parseSteps(text) }
3220
3474
  },
3221
3475
 
3476
+ // ── 写日记:一天一篇,AI 带着写 ──────────────────────────────
3477
+ //
3478
+ // 日记不放在这个工作区里:第一次点「写日记」时问一句放哪儿,
3479
+ // 之后每天那篇就落在那里(见 diary_dir 配置)。这一层只做三件事:
3480
+ // 读写那一天的文件、拼出「今天该问什么」、把写下的东西整理成几条事实。
3481
+
3482
+ /** 日记文件夹在哪儿、今天写了没有。 */
3483
+ 'diary.info': async (body) => {
3484
+ const ws = await root(body)
3485
+ const where = await diaryDirOf(ws)
3486
+ if (where.ok !== true) return where
3487
+ const today = store.localDate()
3488
+ // 第一次用的时候得给个能直接点的位置。客户端不知道用户家目录在哪儿
3489
+ // (宿主交给插件的作用域里没有这一层),所以在这儿算一句带回去。
3490
+ const suggested = path.join(homedir(), 'Documents', '我的日记')
3491
+ if (where.dir === '') return { ok: true, dir: '', ready: false, today, todayDone: false, count: 0, suggest: suggested, recent: [] }
3492
+ // 列最近 40 篇够看「今天写了没有」,但「写过多少天」得用总数报:
3493
+ // 拿列表长度当总数,写到第 401 天起数字就不动了。
3494
+ const listed = await diary.listDiaries(where.dir, { limit: 40 })
3495
+ // 文件夹被删掉 / 挪走 / 没权限时不能装作一切正常:用户会看到
3496
+ // 「今天还没写」,写的时候才发现存不进去。这两种情况如实说。
3497
+ if (listed.ok !== true) {
3498
+ return { ok: true, dir: where.dir, ready: true, today, todayDone: false, count: 0, recent: [], broken: true, error: listed.error ?? '那个文件夹读不出来。' }
3499
+ }
3500
+ const recent = listed.diaries.slice(0, 7)
3501
+ return {
3502
+ ok: true,
3503
+ dir: where.dir,
3504
+ ready: true,
3505
+ today,
3506
+ todayDone: recent.some((d) => d.date === today),
3507
+ count: Number(listed.total ?? listed.diaries.length),
3508
+ recent,
3509
+ missing: listed.missing === true,
3510
+ }
3511
+ },
3512
+
3513
+ /** 定下日记放哪儿(会顺手建好文件夹)。 */
3514
+ 'diary.dir.set': async (body) => {
3515
+ const ws = await root(body)
3516
+ const raw = String(body?.dir ?? '').trim()
3517
+ if (raw === '') return { ok: false, error: '没有说是哪个文件夹。' }
3518
+ const dir = diary.diaryRootFrom({ diary_dir: raw })
3519
+ if (dir === '' || dir === path.parse(dir).root) return { ok: false, error: '不能整个磁盘根目录都当日记文件夹。换一个位置。' }
3520
+ const veto = diaryDirVeto(dir)
3521
+ if (veto !== '') return { ok: false, error: veto }
3522
+ const made = await fs.mkdir(dir, { recursive: true }).then(() => true).catch(() => false)
3523
+ if (!made) return { ok: false, error: '这个文件夹建不出来。换一个位置,或者检查一下有没有写的权限。' }
3524
+ // 探针文件用完就删,但**先看它原本存不存在**:用户文件夹里真有个同名文件时,
3525
+ // 我们既不该覆盖它,也不该删掉它。也不能给它传 undefined 当内容——
3526
+ // Node 对 `writeFile(p, undefined)` 直接抛 TypeError,于是「本来好好的文件夹」
3527
+ // 会被判成写不进去。
3528
+ const probe = path.join(dir, '.lifecard-diary-probe')
3529
+ const hadProbe = await fs.lstat(probe).then(() => true).catch(() => false)
3530
+ const writable = await (hadProbe
3531
+ ? fs.appendFile(probe, '')
3532
+ : fs.writeFile(probe, 'x', { encoding: 'utf8' }).then(() => fs.rm(probe, { force: true }))
3533
+ ).then(() => true).catch(() => false)
3534
+ if (writable !== true) return { ok: false, error: '这个文件夹写不进去。换一个位置,或者检查一下有没有写的权限。' }
3535
+ const saved = await store.writeConfig(ws, { diary_dir: dir })
3536
+ if (saved?.ok !== true) return { ok: false, error: saved?.error ?? '位置没记住,下次还得再挑一次。' }
3537
+ return { ok: true, dir }
3538
+ },
3539
+
3540
+ /** 读某一天(不传就是今天)。 */
3541
+ 'diary.get': async (body) => {
3542
+ const ws = await root(body)
3543
+ const where = await diaryDirOf(ws)
3544
+ if (where.ok !== true) return where
3545
+ if (where.dir === '') return { ok: true, dir: '', ready: false, date: String(body?.date ?? '') || store.localDate(), data: null }
3546
+ const date = String(body?.date ?? '').trim() === '' ? store.localDate() : String(body.date).trim()
3547
+ if (diary.dateFileName(date) === '') return { ok: false, error: '日期看起来不对,应该是 2026-10-31 这种样子。' }
3548
+ const got = await diary.readDiary(where.dir, date)
3549
+ if (got.ok !== true) return got
3550
+ // 除了五节,还得把「文件里本来还有」的东西交出去:用户写在开头那段话、
3551
+ // 自己加的小节。不交的话界面上看不见它们,他会以为存丢了。
3552
+ return {
3553
+ ok: true,
3554
+ dir: where.dir,
3555
+ ready: true,
3556
+ date,
3557
+ data: got.data,
3558
+ intro: got.intro ?? '',
3559
+ extraSections: got.extraSections ?? [],
3560
+ scoreLines: got.scoreLines ?? [],
3561
+ missing: got.missing === true,
3562
+ }
3563
+ },
3564
+
3565
+ /** 存某一天。 */
3566
+ 'diary.save': async (body) => {
3567
+ const ws = await root(body)
3568
+ const where = await diaryDirOf(ws)
3569
+ if (where.ok !== true) return where
3570
+ if (where.dir === '') return { ok: false, error: '还没有定日记放在哪个文件夹。' }
3571
+ const date = String(body?.date ?? '').trim() === '' ? store.localDate() : String(body.date).trim()
3572
+ if (diary.dateFileName(date) === '') return { ok: false, error: '日期看起来不对,应该是 2026-10-31 这种样子。' }
3573
+ // 先读一遍再写:写过的那一天,读出来是什么样,写的时候就得还是那个样子。
3574
+ // 中间被别处改过(用户自己在访达里动了),这次一个字节都不写。
3575
+ // 这条路由以前是裸写,谁调它都能把一整天整篇盖掉。
3576
+ const existing = await diary.readDiary(where.dir, date)
3577
+ if (existing.ok !== true) {
3578
+ return { ok: false, error: `这一天读不出来,为了不覆盖掉原来的东西,这次没存:${String(existing.error ?? '')}` }
3579
+ }
3580
+ const saved = await diary.writeDiary(where.dir, { ...(body?.data ?? {}), date }, new Date(), {
3581
+ expect: typeof existing.text === 'string' ? { text: existing.text } : {},
3582
+ })
3583
+ if (saved.ok !== true) return saved
3584
+ return { ok: true, dir: where.dir, date, path: saved.path, mode: saved.mode }
3585
+ },
3586
+
3587
+ /** 最近写过哪几天。 */
3588
+ 'diary.list': async (body) => {
3589
+ const ws = await root(body)
3590
+ const where = await diaryDirOf(ws)
3591
+ if (where.ok !== true) return where
3592
+ if (where.dir === '') return { ok: true, dir: '', ready: false, diaries: [] }
3593
+ const listed = await diary.listDiaries(where.dir, { limit: Number(body?.limit) > 0 ? Number(body.limit) : 400 })
3594
+ if (listed.ok !== true) return listed
3595
+ return { ok: true, dir: where.dir, ready: true, diaries: listed.diaries }
3596
+ },
3597
+
3598
+ /**
3599
+ * 开今天这一场:给出预设名和第一句。
3600
+ *
3601
+ * 为什么不让客户端自己拼:要带上前几天写的、带着「我」那张卡里已经有的东西,
3602
+ * 还要知道今天写过没有。这些都只有后台读得到。
3603
+ */
3604
+ 'diary.start': async (body) => {
3605
+ const ws = await root(body)
3606
+ const where = await diaryDirOf(ws)
3607
+ if (where.ok !== true) return where
3608
+ const today = store.localDate()
3609
+ let recent = ''
3610
+ let todayDone = false
3611
+ let draft = ''
3612
+ if (where.dir !== '') {
3613
+ const listed = await diary.listDiaries(where.dir, { limit: 40 })
3614
+ if (listed.ok === true) {
3615
+ todayDone = listed.diaries.some((d) => d.date === today)
3616
+ // 今天已经写过的,把正文带上。不带的话模型看不见上午写的那几节,
3617
+ // 只好从头重问一遍;存盘时它照着新问出来的整节重写,上午写的就没了。
3618
+ if (todayDone) {
3619
+ const got = await diary.readDiary(where.dir, today)
3620
+ if (got.ok === true && got.data !== null) draft = diary.diaryBlock(got.data, { intro: got.intro, extraSections: got.extraSections })
3621
+ }
3622
+ const picked = listed.diaries.filter((d) => d.date !== today).slice(0, 3)
3623
+ const texts = []
3624
+ for (const item of picked) {
3625
+ const got = await diary.readDiary(where.dir, item.date)
3626
+ if (got.ok === true && got.data !== null) texts.push({ date: item.date, data: got.data, intro: got.intro, extraSections: got.extraSections })
3627
+ }
3628
+ recent = diary.recentBlock(picked.map((d) => d.date), texts)
3629
+ }
3630
+ }
3631
+ const pin = pinnedCardIdSync(ws, 'diary')
3632
+ let cardName = ''
3633
+ let persona = ''
3634
+ if (pin !== '') {
3635
+ const abs = cardPathSync(ws, pin)
3636
+ const raw = abs === '' ? null : readCachedSync(abs)
3637
+ if (raw !== null) {
3638
+ const parsed = core.parseCard(raw)
3639
+ if (parsed.ok === true) {
3640
+ cardName = String(parsed.data?.name ?? '').trim()
3641
+ persona = ['自述', '性格', '口癖', '不会说的话', '不会做的事']
3642
+ .map((title) => core.sectionBody(parsed.sections, title))
3643
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
3644
+ .join('\n\n')
3645
+ }
3646
+ }
3647
+ }
3648
+ const text = [
3649
+ '/lifecard-diary',
3650
+ `今天是 ${today}。带我写今天这一篇。`,
3651
+ draft === '' ? '' : `\n今天已经写下这些了:\n${draft}`,
3652
+ draft === '' ? '' : '\n接着往下问,别把已经写过的重问一遍。要改哪一节先说清改成什么,我点头了再改。',
3653
+ persona === '' ? '' : `\n带着这张卡里的人来问(${cardName}):\n${persona}`,
3654
+ recent === '' ? '' : `\n前几天写过这些:\n${recent}`,
3655
+ ]
3656
+ .filter((line) => line !== '')
3657
+ .join('\n')
3658
+ return { ok: true, preset: 'lc-diary', date: today, dir: where.dir, todayDone, cardName, personaChars: persona.length, draftChars: draft.length, text }
3659
+ },
3660
+
3661
+ /** 把某一天写下的东西整理成「关于这个人的几条事实」,给改卡用。 */
3662
+ 'diary.digest': async (body) => {
3663
+ const ws = await root(body)
3664
+ const where = await diaryDirOf(ws)
3665
+ if (where.ok !== true) return where
3666
+ if (where.dir === '') return { ok: false, error: '还没有定日记放在哪个文件夹。' }
3667
+ const date = String(body?.date ?? '').trim() === '' ? store.localDate() : String(body.date).trim()
3668
+ const got = await diary.readDiary(where.dir, date)
3669
+ if (got.ok !== true) return got
3670
+ if (got.data === null) return { ok: false, error: '这一天还没写。' }
3671
+ const built = diary.buildDigestPrompt({ date, text: diary.diaryBlock(got.data, { intro: got.intro, extraSections: got.extraSections }) })
3672
+ const called = await callModel(ctx, { system: built.system, user: built.user, model: body?.model })
3673
+ if (called.ok !== true) return { ok: false, error: `这次没整理出来:${called.error ?? '过一会儿再试一次'}` }
3674
+ return { ok: true, date, text: String(called.text ?? '').trim() }
3675
+ },
3676
+
3222
3677
  // ── 文字小说游戏:进到情节里,你来选,它来推 ────────────────
3223
3678
 
3224
3679
  /** 一本书能开哪几局。 */
@@ -4044,11 +4499,11 @@ function cardPathSync(root, id) {
4044
4499
  async function clearPinsFor(ws, rel, data) {
4045
4500
  const state = await store.readConfigState(ws)
4046
4501
  if (state.ok !== true) return
4047
- const pins = { real: '', tavern: '', novel: '', ...(state.config?.default_cards ?? {}) }
4502
+ const pins = { real: '', tavern: '', novel: '', diary: '', ...(state.config?.default_cards ?? {}) }
4048
4503
  const id = String(data?.id ?? '')
4049
4504
  const stem = path.posix.basename(rel).replace(/\.card\.md$/i, '')
4050
4505
  let changed = false
4051
- for (const mode of ['real', 'tavern', 'novel']) {
4506
+ for (const mode of ['real', 'tavern', 'novel', 'diary']) {
4052
4507
  const picked = String(pins[mode] ?? '')
4053
4508
  if (picked !== '' && (picked === id || picked === rel || picked === stem)) {
4054
4509
  pins[mode] = ''
@@ -4071,6 +4526,46 @@ function pinnedCardIdSync(root, mode) {
4071
4526
  }
4072
4527
  }
4073
4528
 
4529
+ /**
4530
+ * 日记放在哪个文件夹。
4531
+ *
4532
+ * 和别的东西不一样:日记**不在这个工作区里**,它是用户在第一次点「写日记」时
4533
+ * 自己挑的一个位置。所以这里不回落到工作区,没定过就老实说没定。
4534
+ */
4535
+ /**
4536
+ * 日记文件夹不能挑在这些地方。
4537
+ *
4538
+ * 以前只挡了文件系统根目录,于是 `~/.ssh`、`~/Library`、`/tmp` 全照收:
4539
+ * 一个手滑把 `.ssh` 设成日记夹,往后每一次「写日记」都往密钥目录里写文件。
4540
+ * 这里只挡「明显不该往里写东西」的几处,不是白名单——用户自己的
4541
+ * `~/Documents/xxx`、外接盘、iCloud 都照旧能选。
4542
+ *
4543
+ * @returns {string} 不许的话,一句人话;可以的话空串。
4544
+ */
4545
+ function diaryDirVeto(dir) {
4546
+ const abs = path.normalize(String(dir ?? ''))
4547
+ const home = homedir()
4548
+ const under = (base) => base !== '' && (abs === base || abs.startsWith(base + path.sep))
4549
+ if (abs === path.parse(abs).root) return '不能整个磁盘根目录都当日记文件夹。换一个位置。'
4550
+ if (abs === os.tmpdir()) {
4551
+ // 只挡临时目录本身:那是系统会整个清掉的地方。它下面自己建的具体文件夹
4552
+ // 不挡——外接盘、同步盘的挂载点有时候就长在系统临时路径下面。
4553
+ return '别把系统临时文件夹本身当日记文件夹——那里会被系统整个清掉,日记会跟着没。换一个位置。'
4554
+ }
4555
+ if (under(path.join(home, '.ssh'))) return '这是放密钥的地方,不能当日记文件夹。换一个位置。'
4556
+ if (under(path.join(home, '.gnupg'))) return '这是放密钥的地方,不能当日记文件夹。换一个位置。'
4557
+ if (under(path.join(home, 'Library'))) return '这是系统自己用的文件夹,别往里写日记。换一个位置,比如「文稿」。'
4558
+ if (abs === home) return '整个家目录太大了,给日记单独建个文件夹吧。换一个位置。'
4559
+ return ''
4560
+ }
4561
+
4562
+ async function diaryDirOf(ws) {
4563
+ const state = await store.readConfigState(ws)
4564
+ if (state.ok !== true) return { ok: false, error: state.error ?? '这个文件夹里的设置读不出来。' }
4565
+ const dir = diary.diaryRootFrom(state.config ?? {})
4566
+ return { ok: true, dir }
4567
+ }
4568
+
4074
4569
  /** 把世界书条目排成人能读、模型也好读的样子。 */
4075
4570
  function worldEntriesText(entries) {
4076
4571
  const list = Array.isArray(entries) ? entries : []
@@ -4221,6 +4716,7 @@ function modeFromPresetRegistry(ctx, agent) {
4221
4716
  const blob = JSON.stringify(rows)
4222
4717
  if (blob.includes('lc-tavern')) return 'tavern'
4223
4718
  if (blob.includes('lc-novel')) return 'novel'
4719
+ if (blob.includes('lc-diary')) return 'diary'
4224
4720
  } catch {
4225
4721
  /* 问不到就当不知道 */
4226
4722
  }
@@ -4233,6 +4729,7 @@ function modeForAgent(agent) {
4233
4729
  if (preset === '') return ''
4234
4730
  if (preset.includes('lc-tavern')) return 'tavern'
4235
4731
  if (preset.includes('lc-novel')) return 'novel'
4732
+ if (preset.includes('lc-diary')) return 'diary'
4236
4733
  return ''
4237
4734
  }
4238
4735
 
@@ -4337,6 +4834,14 @@ function registerInterviewSkill(ctx) {
4337
4834
  fallback: '小说改剧本:分场、把叙述换成 △ 动作、把心理换成演得出来的东西、台词按标点分工。',
4338
4835
  label: '改剧本',
4339
4836
  })
4837
+ // 带写日记的那份手艺。它不只是「怎么问」,还写着写完之后怎么反哺
4838
+ // 「我」那张卡和日记助手那张卡——两条路都在这一份里。
4839
+ registerBundledSkill(ctx, {
4840
+ dir: 'lifecard-diary',
4841
+ name: 'lifecard-diary',
4842
+ fallback: '带写今天这一篇日记:一件事、情绪三层、一个能做的决定,末尾四样各打个分。',
4843
+ label: '日记',
4844
+ })
4340
4845
  // 这三份是写作用得上的通用手艺,随包一起发:装插件即等于有,
4341
4846
  // 换台机器不必再单独装一遍。名字与内容都保持原样,方便用户照旧用
4342
4847
  // `/human-writing`、`/blind-review-loop`、`/visual-novel` 唤起。
@@ -4584,14 +5089,21 @@ export function apply(ctx, config) {
4584
5089
  // 没有 Origin 就是同源请求(浏览器对同源 POST 一般不送);`null` 是
4585
5090
  // 沙箱里的 iframe。这两种放行,只有「明确来自别家站点」才拦。
4586
5091
  if (origin !== '' && origin !== 'null') {
4587
- let sameHost = false
5092
+ // 只比「Origin 和 Host 一致」是不够的:DNS rebinding 下攻击者页面的
5093
+ // Origin 和它请求的 Host 都是它自己的域名,两面一致照样放行,
5094
+ // 于是别人的网页能读、能改你的日记。这里再加一条——这一台服务只在
5095
+ // 本机跑,所以请求的主机名必须真的是回环地址,别的一律不收。
5096
+ let allowed = false
4588
5097
  try {
4589
5098
  const host = String(req.headers?.host ?? '')
4590
- sameHost = host !== '' && new URL(origin).host === host
5099
+ const originUrl = new URL(origin)
5100
+ const hostName = host === '' ? '' : new URL(`http://${host}`).hostname
5101
+ const loopback = hostName === '127.0.0.1' || hostName === 'localhost' || hostName === '::1' || hostName === '[::1]'
5102
+ allowed = loopback && originUrl.host === host
4591
5103
  } catch {
4592
- sameHost = false
5104
+ allowed = false
4593
5105
  }
4594
- if (!sameHost) {
5106
+ if (!allowed) {
4595
5107
  writeJson(res, 403, { ok: false, error: { code: 'forbidden', message: '这个来源不能改档案' } })
4596
5108
  return
4597
5109
  }
package/lib/novel.js CHANGED
@@ -471,6 +471,10 @@ export function buildChapterPrompt({ title, idea, genre, previousTail, currentBo
471
471
  '- 比喻只在现场捞:用的东西得是这一场里真出现过的(门、碗、雨、他手上那根烟)。从别处搬一个漂亮东西过来形容这里,宁可不要。',
472
472
  '- 人物对话里「行」「我记着了」「你先说」这种短回应可以留——对面坐着人,接得住。叙述里不要出现「这句话很稳」这类没有对象的自我表态。',
473
473
  '- 每人按自己的性格和处境行动,不要为了推情节让谁临时变傻或变好。',
474
+ '- 在场的人各有各的落点:谁都得有自己的一个动作或一句话,不要全站着当背景。人一多,就给每人一样不一样的东西——一个在剥橘子,一个在门口看外面,一个只说半句。',
475
+ '- 每句话都得是这个人会说的:不看名字也能认出是谁在开口。几句台词要是可以互换着说,那几句就还没写好。',
476
+ '- 不拿一句总结代替过程:「一番盘问之后」「几个人打量了他一遍」「说完大家都沉默了」——这些是省略,不是写完了。挑一个具体的人,写他那一刻做了什么、说了哪一句,剩下的人怎么接。',
477
+ '- 视角以内写:只写这个视角能看到、听到、闻到的东西。别人的心里想什么,靠他的动作和语气露出来,不直接写出来。',
474
478
  '- 不写章节标题,标题我自己加。',
475
479
  '- 只写这一章,写到该收的地方就停,不要顺手把下一章也开了头。',
476
480
  '',