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.
package/lib/index.js CHANGED
@@ -11,13 +11,14 @@
11
11
 
12
12
  import z from '@deepseek-ai/schemastery'
13
13
  import path from 'node:path'
14
- import { promises as fs, readFileSync } from 'node:fs'
14
+ import { promises as fs, readFileSync, statSync, readdirSync, appendFileSync, writeFileSync } from 'node:fs'
15
15
  import { fileURLToPath } from 'node:url'
16
16
  import { homedir } from 'node:os'
17
17
  import os from 'node:os'
18
18
  import * as core from './core.js'
19
19
  import * as codec from './codec.js'
20
20
  import * as store from './store.js'
21
+ import * as prose from './prose.js'
21
22
  import * as prompts from './prompts.js'
22
23
 
23
24
  import * as score from './score.js'
@@ -29,6 +30,8 @@ import * as interview from './jobs-interview.js'
29
30
  // 用「用到才加载」而不是文件顶上的静态 import —— 静态 import 一个不存在的
30
31
  // 文件会让整个插件起不来,那就不是「能删」而是「删了就全废」。
31
32
  // 删掉对应文件之后,只有那个功能报「这个功能没装」,别的照常。
33
+ import * as lifecardTools from '../lifecard-tools.js'
34
+
32
35
  let tavern = null
33
36
  let novel = null
34
37
  let presets = null
@@ -757,6 +760,16 @@ function buildApi(ctx, workspace, config, options) {
757
760
  home: homedir(),
758
761
  hasLlm: ctx.get?.('llm') !== undefined && ctx.get?.('llm') !== null,
759
762
  defaults: { workspace: ws },
763
+ // 界面上被收起来的门。读不出来就一个都不收(宁可多摆一扇,也不要空一块)。
764
+ hidden_doors: await (async () => {
765
+ try {
766
+ const conf = await store.readConfigState(ws)
767
+ const list = conf.ok === true ? conf.config?.hidden_doors : []
768
+ return Array.isArray(list) ? list.filter((x) => typeof x === 'string') : []
769
+ } catch {
770
+ return []
771
+ }
772
+ })(),
760
773
  summary,
761
774
  relations: prompts.RELATION_TYPES,
762
775
  }
@@ -817,6 +830,9 @@ function buildApi(ctx, workspace, config, options) {
817
830
  relations: all.relations,
818
831
  materials: all.materials,
819
832
  errors: all.errors,
833
+ // 撤回箱:删掉的卡文件还在磁盘上,得有个地方列出来,用户才能恢复
834
+ // 或者彻底删掉。以前什么都没有,删掉的卡等于掉进黑洞。
835
+ withdrawn: all.withdrawn ?? [],
820
836
  proposals,
821
837
  }
822
838
  },
@@ -892,12 +908,42 @@ function buildApi(ctx, workspace, config, options) {
892
908
  const safe = await insideWorkspace(ws, body.path)
893
909
  if (safe.ok !== true) return { ok: false, error: safe.error }
894
910
  rel = safe.rel
911
+ // 显式给了位置也一样:这个位置上有一张撤掉的卡,就没法「另存一张」盖过去。
912
+ // 不然换个入口就能把删掉的卡复活成一份新内容。
913
+ const there = await fs.stat(path.join(ws, rel)).then((st) => st.isFile()).catch(() => false)
914
+ if (!there) {
915
+ // 挡住这张新卡的是账上那张撤掉的卡,所以也带 withdrawn。
916
+ // 光比路径不够:id 是拼音、名字是中文时(people/rat.card.md 那种),
917
+ // 按名字再建会算出另一个路径,于是同一个人并排出现两张。
918
+ const gone = store.hitsRedactionByPath(await store.readRedactions(ws), rel) !== undefined
919
+ || (await store.withdrawnNameHit(ws, rel, [data.id, data.name])) !== null
920
+ if (gone) {
921
+ return { ok: false, withdrawn: true, error: '这个名字被一张已经删掉的卡占着。先去首页「已经撤掉的」里把它清掉,或者换个名字。' }
922
+ }
923
+ }
895
924
  } else {
896
925
  rel = store.cardRelPath(id, data.world)
897
926
  // 没给路径=这是一张新卡。同名文件已经在了就不再写:
898
927
  // 以前会直接覆盖,用户点「新建」写了个已有的名字,那人原来那张卡
899
928
  // 连同快照之外的一切(关系史、口癖)就没了声息地被换成了空白。
900
- const exists = await fs.stat(path.join(ws, rel)).then((st) => st.isFile()).catch(() => false)
929
+ const abs = path.join(ws, rel)
930
+ const exists = await fs.stat(abs).then((st) => st.isFile()).catch(() => false)
931
+ if (!exists) {
932
+ // 文件搬去回收目录以后,原位确实空了,可名字还被一张撤掉的卡占着。
933
+ // 只判文件在不在的话,删掉的卡会被当成「没人用这个名字」默默重建回来。
934
+ const redactions = await store.readRedactions(ws)
935
+ // 同目录里同名的也算占着:删掉一张叫「妈妈」的卡(文件是 people/mama.card.md),
936
+ // 再按名字建会算出 people/妈妈.card.md,两张「妈妈」就并排出现了。
937
+ const gone = store.hitsRedactionByPath(redactions, rel) !== undefined
938
+ || (await store.withdrawnNameHit(ws, rel, [id, data.name])) !== null
939
+ if (gone) {
940
+ return {
941
+ ok: false,
942
+ withdrawn: true,
943
+ error: '这个名字被一张已经删掉的卡占着。先去首页「已经撤掉的」里把它清掉,或者换个名字。',
944
+ }
945
+ }
946
+ }
901
947
  if (exists && body?.overwrite !== true) {
902
948
  return {
903
949
  ok: false,
@@ -979,6 +1025,85 @@ function buildApi(ctx, workspace, config, options) {
979
1025
  },
980
1026
 
981
1027
  /** 看某张卡以前的样子(快照在每次保存时自动留,只是以前没露出来)。 */
1028
+ // 三扇门各自「现在用哪张卡」。存成 id,读的时候再按 id 找卡:
1029
+ // 卡改名、换文件夹都不会让这条记录失效。
1030
+ 'card.defaults.get': async (body) => {
1031
+ const ws = await root(body)
1032
+ const cfg = await store.readConfigState(ws)
1033
+ const pins = cfg.config?.default_cards ?? {}
1034
+ return {
1035
+ ok: true,
1036
+ cards: {
1037
+ real: String(pins.real ?? ''),
1038
+ tavern: String(pins.tavern ?? ''),
1039
+ novel: String(pins.novel ?? ''),
1040
+ },
1041
+ }
1042
+ },
1043
+ // 开一个新对话,并把第一句替用户发出去。
1044
+ //
1045
+ // 为什么放在后台:宿主把「建会话 + 发消息」这套能力挂在 sessionController 上,
1046
+ // 后台一定拿得到;客户端那侧不一定(真机上 uiWorkspace 有时根本不在插件作用域里,
1047
+ // 用户点完只会看到「这个版本不支持」)。所以正路从后台走,客户端只负责把会话切到眼前。
1048
+ 'session.open': async (body) => {
1049
+ const controller = ctx.get?.('sessionController', false)
1050
+ if (controller === null || controller === undefined || typeof controller.create !== 'function') {
1051
+ return { ok: false, error: '这台机器没有开新对话的能力,把要说的那句话复制到新对话里也一样能用。' }
1052
+ }
1053
+ const preset = String(body?.preset ?? '').trim()
1054
+ const text = String(body?.text ?? '')
1055
+ try {
1056
+ const created = await controller.create(preset === '' ? {} : { agentPreset: preset })
1057
+ const id = String(created?.sessionId ?? '')
1058
+ if (id === '') return { ok: false, error: '新对话没建起来,再点一次试试。' }
1059
+ let sent = false
1060
+ if (text !== '' && typeof controller.prompt === 'function') {
1061
+ await controller.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text }] })
1062
+ sent = true
1063
+ }
1064
+ return { ok: true, sessionId: id, agentPreset: String(created?.agentPreset ?? ''), sent }
1065
+ } catch (error) {
1066
+ return { ok: false, error: humanizeHostError(error) }
1067
+ }
1068
+ },
1069
+ 'card.defaults.set': async (body) => {
1070
+ const ws = await root(body)
1071
+ const mode = String(body?.mode ?? '')
1072
+ if (mode !== 'real' && mode !== 'tavern' && mode !== 'novel') {
1073
+ return { ok: false, error: '不知道你说的是哪扇门。' }
1074
+ }
1075
+ const id = String(body?.id ?? '').trim()
1076
+ const cfg = await store.readConfigState(ws)
1077
+ if (cfg.ok !== true) return { ok: false, error: cfg.error ?? '这个文件夹里的设置读不出来。' }
1078
+ const pins = { real: '', tavern: '', novel: '', ...(cfg.config?.default_cards ?? {}) }
1079
+ pins[mode] = id
1080
+ await store.writeConfig(ws, { default_cards: pins })
1081
+ return { ok: true, cards: pins }
1082
+ },
1083
+ /**
1084
+ * 把一扇门从界面上收起来 / 装回来。
1085
+ *
1086
+ * 只是界面上的开关:卡、世界书、书、会话一个字节都不动,
1087
+ * 所以「删掉」这件事随时可以反悔。
1088
+ */
1089
+ 'door.set': async (body) => {
1090
+ const ws = await root(body)
1091
+ const id = String(body?.id ?? '').trim()
1092
+ if (id !== 'real' && id !== 'novel' && id !== 'tavern') return { ok: false, error: '不知道你说的是哪扇门。' }
1093
+ const confState = await store.readConfigState(ws)
1094
+ if (confState.ok !== true) return { ok: false, error: confState.error ?? '这个文件夹里的设置读不出来。' }
1095
+ const conf = confState.config ?? {}
1096
+ const hidden = Array.isArray(conf?.hidden_doors) ? conf.hidden_doors.filter((x) => typeof x === 'string') : []
1097
+ const want = body?.hidden === true
1098
+ const next = want
1099
+ ? (hidden.includes(id) ? hidden : [...hidden, id])
1100
+ : hidden.filter((x) => x !== id)
1101
+ if (next.length === 3) return { ok: false, error: '三扇门都收起来就没地方进去了,至少留一扇。' }
1102
+ const saved = await store.writeConfig(ws, { ...conf, hidden_doors: next })
1103
+ if (saved === false || saved?.ok === false) return { ok: false, error: '这个开关没能存下来,等一会儿再试一次。' }
1104
+ return { ok: true, hidden_doors: next }
1105
+ },
1106
+
982
1107
  'card.history': async (body) => {
983
1108
  const ws = await root(body)
984
1109
  const safe = await insideWorkspace(ws, body?.path)
@@ -998,21 +1123,44 @@ function buildApi(ctx, workspace, config, options) {
998
1123
  return store.readSnapshot(ws, rel, body?.stamp)
999
1124
  },
1000
1125
 
1001
- /** 把某个历史版本恢复成当前内容。恢复前会再留一份新快照,所以这一步本身也能撤销。 */
1126
+ /**
1127
+ * 恢复一张卡。两种意思,看有没有给版本号:
1128
+ * - 给了 `stamp`:退回那一版历史(老行为,不动)。
1129
+ * - 没给:把撤回过的卡救回列表(追加一条恢复记录)。
1130
+ *
1131
+ * 合并成一条路由,是因为界面上就一个「恢复」动作,用户不区分这两种。
1132
+ */
1002
1133
  'card.restore': async (body) => {
1003
1134
  const ws = await root(body)
1004
1135
  const safe = await insideWorkspace(ws, body?.path)
1005
1136
  if (safe.ok !== true) return { ok: false, error: safe.error }
1006
1137
  const rel = safe.rel
1007
1138
  if (!rel.endsWith('.card.md')) return { ok: false, error: '这个位置不是一张卡。' }
1008
- const old = await store.readSnapshot(ws, rel, body?.stamp)
1139
+ const stamp = body?.stamp
1140
+ if (stamp === undefined || stamp === null || stamp === '') {
1141
+ return store.restoreCard(ws, rel)
1142
+ }
1143
+ // 卡还撤着的时候退回旧版本,会把文件写回原位、而它仍然不在列表里——
1144
+ // 那就又造出一个「看得见文件、看不见卡」的死结。先放回来,再谈版本。
1145
+ if (store.hitsRedactionByPath(await store.readRedactions(ws), rel) !== undefined) {
1146
+ // 跟 readCard 的两条「已撤掉」分支一个形:带 withdrawn,上层只看这个字段
1147
+ // 就知道该给「恢复」的门,不用去猜是哪种撤法。
1148
+ return { ok: false, withdrawn: true, error: '这张卡现在是撤掉的状态。先把它放回列表,再退回旧版本。' }
1149
+ }
1150
+ const old = await store.readSnapshot(ws, rel, stamp)
1009
1151
  if (old.ok !== true) return old
1010
1152
  const written = await store.writeCard(ws, rel, old.data, old.sections, { force: true })
1011
1153
  if (written.ok !== true) return written
1012
1154
  return { ok: true, path: rel, validation: written.validation, note: '已经退回这一版。刚才那一版也还在历史里。' }
1013
1155
  },
1014
1156
 
1015
- /** 删除一张卡(写墓碑,不真删文件——真删就不可审计了)。 */
1157
+ /**
1158
+ * 撤掉一张卡:文件搬进回收目录,再写一条墓碑。
1159
+ *
1160
+ * 以前只写墓碑、文件留在原地。看起来更「可审计」,实际是个死结:
1161
+ * 名字还占着(`card.save` 只判文件在不在),可列表里又看不见,
1162
+ * 用户照着提示去找也找不到,删掉的卡于是就那么赖着。
1163
+ */
1016
1164
  'card.delete': async (body) => {
1017
1165
  const ws = await root(body)
1018
1166
  const safe = await insideWorkspace(ws, body?.path)
@@ -1021,8 +1169,84 @@ function buildApi(ctx, workspace, config, options) {
1021
1169
  if (!rel.endsWith('.card.md')) return { ok: false, error: '这个位置不是一张卡。' }
1022
1170
  const card = await store.readCard(ws, rel)
1023
1171
  if (!card.ok) return card
1024
- await store.appendRedaction(ws, { path: rel, sha256: store.sha256(card.text), reason: String(body?.reason ?? '用户删除') })
1025
- return { ok: true, path: rel, note: '已经删掉了:它不会再出现在列表、导出和 AI 的眼里。磁盘上的原文我们还留着,方便你反悔。' }
1172
+ const moved = await store.moveCardToRedacted(ws, rel)
1173
+ if (moved.ok !== true) return moved
1174
+ try {
1175
+ await store.appendRedaction(ws, { path: rel, sha256: store.sha256(card.text), reason: String(body?.reason ?? '用户删除') })
1176
+ } catch (err) {
1177
+ // 账没记上就把文件放回去:不然这张卡既不在列表里,也没人知道它被删过。
1178
+ const putBack = await fs.rename(path.join(ws, moved.redacted), path.join(ws, rel)).then(() => true).catch(() => false)
1179
+ if (!putBack) {
1180
+ // 搬回去也失败了:残份留在回收目录里、账上又没有它。别再让这种残份
1181
+ // 变成「摘不掉的一行」——restoreCard / purgeCard 对「有残份、没账」
1182
+ // 的情况放行,用户可以照常放回来或彻底删掉。
1183
+ return { ok: false, error: '这次删除没记下来,卡也没能放回原处。它现在在「已经撤掉的」里,可以放回来,也可以彻底删掉。' }
1184
+ }
1185
+ return { ok: false, error: '这次删除没记下来,卡已经放回原处了,再试一次。' }
1186
+ }
1187
+ await clearPinsFor(ws, rel, card.data)
1188
+ // 返回值要把「还能找回来」说出来。只写「已经删掉了」,用户手滑之后
1189
+ // 就不知道该去哪儿反悔,删掉的卡于是永远躺在回收目录里没人认领。
1190
+ return {
1191
+ ok: true,
1192
+ path: rel,
1193
+ note: '已经删掉了:它不会再出现在列表、导出和 AI 的眼里。已经放到「已经撤掉的」里了,想反悔可以在那儿恢复;要从磁盘上彻底删掉,也是在那儿删。',
1194
+ withdrawn: true,
1195
+ }
1196
+ },
1197
+
1198
+ /**
1199
+ * 收走一张刚建的空卡(访谈开局建错了用)。
1200
+ *
1201
+ * 和「删除」分开是因为它不该留墓碑:这张卡从来没进过用户的列表,
1202
+ * 只是建错了一下。写墓碑会占住名字,紧接着按同一个名字再建就撞墙。
1203
+ * 只对「正文全空、刚建不久」的卡开放,免得变成删活卡的后门。
1204
+ */
1205
+ 'card.discard': async (body) => {
1206
+ const ws = await root(body)
1207
+ const safe = await insideWorkspace(ws, body?.path)
1208
+ if (safe.ok !== true) return { ok: false, error: safe.error }
1209
+ const rel = safe.rel
1210
+ if (!rel.endsWith('.card.md')) return { ok: false, error: '这个位置不是一张卡。' }
1211
+ const card = await store.readCard(ws, rel)
1212
+ if (!card.ok) return card
1213
+ const written = (card.sections ?? []).map((one) => String(one?.body ?? '').trim()).join('')
1214
+ if (written !== '') {
1215
+ return { ok: false, error: '这张卡里已经写了内容,不能当成空卡收走。要删就在列表里删。' }
1216
+ }
1217
+ const stat = await fs.stat(path.join(ws, rel)).catch(() => null)
1218
+ const age = stat === null ? Number.POSITIVE_INFINITY : Date.now() - stat.mtimeMs
1219
+ if (!(age <= 10 * 60 * 1000)) {
1220
+ return { ok: false, error: '这张卡已经放了一会儿了,不能当成刚建的空卡收走。要删就在列表里删。' }
1221
+ }
1222
+ // 搬走之后必须记一笔「收走」:不记账的残份会被列进「已经撤掉的」,
1223
+ // 而「放回来」「彻底删掉」都以账为准,于是那一行两个动作都失败,
1224
+ // 用户看着一条摘不掉的幽灵。
1225
+ // 记「彻底删掉」而不是「撤掉」,是因为 discard 的本意是别让这张建错的
1226
+ // 空卡占住名字——撤掉态会占名字,清掉态不会,同名立刻能再建。
1227
+ const moved = await store.moveCardToRedacted(ws, rel)
1228
+ if (moved.ok !== true) return moved
1229
+ try {
1230
+ await store.appendRedaction(ws, { kind: 'purge', path: rel, reason: '建错了的空卡' })
1231
+ } catch {
1232
+ // 记不上就搬回原处,别留一条谁也处理不了的残份。
1233
+ await fs.rename(path.join(ws, moved.redacted), path.join(ws, rel)).catch(() => {})
1234
+ return { ok: false, error: '这张空卡没能收走,卡还在原处,再试一次。' }
1235
+ }
1236
+ return moved
1237
+ },
1238
+
1239
+ /**
1240
+ * 彻底删掉一张撤回过的卡:真删磁盘文件。
1241
+ *
1242
+ * 只允许对**已撤回**的卡做。这一步不可撤销,所以设一道前提:先在列表里
1243
+ * 删过一次(那一步可恢复)、用户确实看过「已撤回」里那一行,才谈得上彻底删。
1244
+ */
1245
+ 'card.purge': async (body) => {
1246
+ const ws = await root(body)
1247
+ const safe = await insideWorkspace(ws, body?.path)
1248
+ if (safe.ok !== true) return { ok: false, error: safe.error }
1249
+ return store.purgeCard(ws, safe.rel)
1026
1250
  },
1027
1251
 
1028
1252
  /** 导入酒馆卡(PNG / JSON / CHARX)。body.files 是 [{name, base64}]。 */
@@ -2008,9 +2232,42 @@ function buildApi(ctx, workspace, config, options) {
2008
2232
  const materials = await store.readMaterials(ws)
2009
2233
  const names = Object.keys(materials)
2010
2234
  if (names.length === 0) return { ok: false, error: '还没有材料。先加一段文字,或者做一次访谈,AI 才有东西可读。' }
2011
- const chosen = Array.isArray(body?.materials) && body.materials.length > 0
2012
- ? Object.fromEntries(Object.entries(materials).filter(([k]) => body.materials.includes(k) || body.materials.includes(path.basename(k))))
2013
- : materials
2235
+ // 三种意思必须分得开:不传 / null = 全读;给数组 = 只读这些;空数组 = 一份都不读。
2236
+ // 以前空数组也被当成「全读」,用户明明一份都没勾,AI 却把整个材料库读了一遍。
2237
+ const want = body?.materials
2238
+ let chosen = materials
2239
+ if (Array.isArray(want)) {
2240
+ if (want.length === 0) {
2241
+ return { ok: false, error: '这次没选任何材料。至少要选一份,或者把要读的材料挑出来。' }
2242
+ }
2243
+ const picked = {}
2244
+ const missing = []
2245
+ for (const one of want) {
2246
+ const key = String(one ?? '').trim()
2247
+ if (key === '') {
2248
+ missing.push('(空的一条)')
2249
+ continue
2250
+ }
2251
+ if (Object.hasOwn(materials, key)) {
2252
+ picked[key] = materials[key]
2253
+ continue
2254
+ }
2255
+ // 界面上有时只传文件名,或者多带了一层目录;能唯一对上一份就认。
2256
+ const base = path.posix.basename(key)
2257
+ const same = Object.keys(materials).filter((k) => k.endsWith('/' + key) || path.posix.basename(k) === base)
2258
+ if (same.length === 1) {
2259
+ picked[same[0]] = materials[same[0]]
2260
+ continue
2261
+ }
2262
+ missing.push(key)
2263
+ }
2264
+ if (missing.length > 0) {
2265
+ return { ok: false, error: `这几份材料找不到了:${missing.join('、')}。可能刚被删掉或者改了名,刷新一下再挑一次。` }
2266
+ }
2267
+ chosen = picked
2268
+ } else if (want !== undefined && want !== null) {
2269
+ return { ok: false, error: '没看懂要读哪几份材料。要么不传(全都读),要么给一份材料清单。' }
2270
+ }
2014
2271
  if (Object.keys(chosen).length === 0) return { ok: false, error: '选中的材料都不存在' }
2015
2272
  const aboutName = String(body?.name ?? aboutId)
2016
2273
  // 「想要什么样的人」可以临时覆盖工作区里存的那份(比如试一下别的口味)。
@@ -2260,7 +2517,25 @@ function buildApi(ctx, workspace, config, options) {
2260
2517
  const materialName = `${date}-${core.safeId(aboutId)}访谈`
2261
2518
  let saved = null
2262
2519
  if (status === 'answered' && answer.trim() !== '') {
2263
- const block = `## ${questionId}\n\n> ${String(body?.ask ?? '').trim()}\n\n${answer.trim()}\n\n\`\`\`\nq: ${questionId}\nasked_at: ${new Date().toISOString()}\n\`\`\`\n`
2520
+ // 标题用**问题本身**,不只用题号。以前标题是 `## real.q03`,回头
2521
+ // 「整理进卡里」时模型看到的是一串题号加裸答案,不知道这句话在回答什么,
2522
+ // 只能瞎猜字段——于是把答案硬塞进不相干的格子里。
2523
+ const askText = String(body?.ask ?? '').trim()
2524
+ const options = Array.isArray(body?.options) ? body.options.filter((x) => String(x ?? '').trim() !== '') : []
2525
+ const block = [
2526
+ `## ${askText === '' ? questionId : askText}`,
2527
+ '',
2528
+ `问过的题号:${questionId}`,
2529
+ ...(options.length === 0 ? [] : ['', `当时给的几个方向:${options.map((x) => String(x).trim()).join(' / ')}`]),
2530
+ '',
2531
+ answer.trim(),
2532
+ '',
2533
+ '```',
2534
+ `q: ${questionId}`,
2535
+ `asked_at: ${new Date().toISOString()}`,
2536
+ '```',
2537
+ '',
2538
+ ].join('\n')
2264
2539
  saved = await store.appendMaterial(ws, materialName, block)
2265
2540
  }
2266
2541
  // 账本
@@ -2812,6 +3087,7 @@ function buildApi(ctx, workspace, config, options) {
2812
3087
  '2. 你读到哪儿不信(这个人不会这么做、这件事不会这么发生)',
2813
3088
  '3. 你读到哪儿想跳过(哪几段你在心里划过去了)',
2814
3089
  '4. 哪句话是空话,删掉不影响(直接引原句)',
3090
+ '5. 哪一句读着最像机器写的——太顺、太整齐、什么都说了却没具体的东西(直接引原句)',
2815
3091
  '',
2816
3092
  '【怎么答】',
2817
3093
  '- 每条一行,先写「哪里:」再写「为什么:」。要引原句。',
@@ -2836,7 +3112,27 @@ function buildApi(ctx, workspace, config, options) {
2836
3112
  if (called.ok !== true) return { ok: false, error: `这次没审成:${called.error ?? '过一会儿再试一次'}` }
2837
3113
  const review = String(called.text ?? '').trim()
2838
3114
  if (review === '') return { ok: false, error: 'AI 这次没给出意见,再点一次试试。' }
2839
- return { ok: true, index, review, chars: bodyText.length, blind: true, model: String(body?.model ?? '') }
3115
+
3116
+ // 读者的意见靠模型读,套话靠数。
3117
+ //
3118
+ // 「不是…而是…」用了四次、「瞳孔一缩」出现三次——这种密度人眼看不出来,
3119
+ // 数一遍就知道。所以这一段是**附带**给的:不改模型的意见,
3120
+ // 也不替作者改句子,只说哪个说法出现了几次、举一句原文。
3121
+ const scan = prose.scanProse(bodyText)
3122
+ const scanned = prose.proseReportText(scan)
3123
+ const combined = scanned === ''
3124
+ ? review
3125
+ : `${review}\n\n【顺手数了一下】(不是意见,是数出来的)\n${scanned}`
3126
+
3127
+ return {
3128
+ ok: true,
3129
+ index,
3130
+ review: combined,
3131
+ scan,
3132
+ chars: bodyText.length,
3133
+ blind: true,
3134
+ model: String(body?.model ?? ''),
3135
+ }
2840
3136
  },
2841
3137
 
2842
3138
  /** 读一章。 */
@@ -3484,46 +3780,464 @@ function blankPng() {
3484
3780
  * 注册失败不抛:精简 profile 里没有 skills 服务时,应当只是少一个访谈
3485
3781
  * skill,而不是整个插件起不来。
3486
3782
  */
3783
+ // ── 人物卡直接进系统提示 ─────────────────────────────────────────────
3784
+ //
3785
+ // 为什么不能靠工具结果:工具结果落在对话里,是「模型查到的资料」;预设和它
3786
+ // 一旦意见不合,模型会站在预设那边跟资料较劲——用户看到的就是「人设完全不
3787
+ // 像、道德感极强」。角色卡在酒馆类软件里从来不是资料,它就是这一场的
3788
+ // 系统提示本身(SillyTavern 的 char card 也是拼进 system 里的)。
3789
+ //
3790
+ // 所以这里把它做成一个 system prompt 段落:`text` 是函数,每次组装提示词都
3791
+ // 重新求值,所以「换个卡」「刚改完卡」下一句就生效,不用重开会话。
3792
+ //
3793
+ // `text` 必须同步返回,所以用 readFileSync + 按 mtime/size 缓存:同一份卡
3794
+ // 一万次组装也只读一次盘。
3795
+
3796
+ /** 小文件读盘缓存:同一份文件没改过就不再读。 */
3797
+ const personaCache = new Map()
3798
+
3799
+ function readCachedSync(abs) {
3800
+ try {
3801
+ const stat = statSync(abs)
3802
+ const hit = personaCache.get(abs)
3803
+ if (hit !== undefined && hit.mtimeMs === stat.mtimeMs && hit.size === stat.size) return hit.text
3804
+ const text = readFileSync(abs, 'utf8')
3805
+ personaCache.set(abs, { mtimeMs: stat.mtimeMs, size: stat.size, text })
3806
+ return text
3807
+ } catch {
3808
+ return null
3809
+ }
3810
+ }
3811
+
3812
+ /** 卡文件名:`people/<id>.card.md`。id 里可能有中文,不能直接拿来当路径猜。 */
3813
+ function cardPathSync(root, id) {
3814
+ const want = String(id ?? '').trim()
3815
+ if (want === '') return ''
3816
+ // 这一段是同步路径(system prompt 每次组装都要跑),所以用同步读的墓碑。
3817
+ // 不过墓碑的话,删掉的卡只要文件还在,就照样被注入进 system prompt——
3818
+ // 用户明明删了,模型却还在演那个人。
3819
+ const redactions = store.readRedactionsSync(root)
3820
+ const relOf = (abs) => path.relative(root, abs).split(path.sep).join('/')
3821
+ const gone = (abs, text) => store.hitsRedaction(redactions, relOf(abs), text) !== undefined
3822
+ const direct = path.join(root, 'people', `${want}.card.md`)
3823
+ try {
3824
+ if (statSync(direct).isFile()) {
3825
+ const text = readCachedSync(direct)
3826
+ if (text !== null && !gone(direct, text)) return direct
3827
+ }
3828
+ } catch {
3829
+ /* 名字不是文件名,退回去扫目录 */
3830
+ }
3831
+ try {
3832
+ const names = readdirSync(path.join(root, 'people')).filter((n) => n.endsWith('.card.md'))
3833
+ for (const name of names) {
3834
+ const abs = path.join(root, 'people', name)
3835
+ const text = readCachedSync(abs)
3836
+ if (text === null) continue
3837
+ if (gone(abs, text)) continue
3838
+ const parsed = core.parseCard(text)
3839
+ if (parsed.ok === true && String(parsed.data?.id ?? '') === want) return abs
3840
+ }
3841
+ } catch {
3842
+ /* 没有 people 目录就当没挑卡 */
3843
+ }
3844
+ return ''
3845
+ }
3846
+
3847
+ /**
3848
+ * 一张卡被撤掉以后,把三扇门(现实 / 酒馆 / 写小说)里指向它的那项清空。
3849
+ *
3850
+ * 不清的后果不是「少了一个人的设定」这么轻:那把门还记着一个不存在的名字,
3851
+ * 每次都白读一遍、拼出一段空的,用户看到的是「明明挑着人,模型却不知道自己演谁」。
3852
+ */
3853
+ async function clearPinsFor(ws, rel, data) {
3854
+ const state = await store.readConfigState(ws)
3855
+ if (state.ok !== true) return
3856
+ const pins = { real: '', tavern: '', novel: '', ...(state.config?.default_cards ?? {}) }
3857
+ const id = String(data?.id ?? '')
3858
+ const stem = path.posix.basename(rel).replace(/\.card\.md$/i, '')
3859
+ let changed = false
3860
+ for (const mode of ['real', 'tavern', 'novel']) {
3861
+ const picked = String(pins[mode] ?? '')
3862
+ if (picked !== '' && (picked === id || picked === rel || picked === stem)) {
3863
+ pins[mode] = ''
3864
+ changed = true
3865
+ }
3866
+ }
3867
+ if (changed) await store.writeConfig(ws, { default_cards: pins })
3868
+ }
3869
+
3870
+ /** 当前是哪张卡:配置里 default_cards[mode]。 */
3871
+ function pinnedCardIdSync(root, mode) {
3872
+ const raw = readCachedSync(path.join(root, 'lifecard.config.json'))
3873
+ if (raw === null) return ''
3874
+ try {
3875
+ const conf = JSON.parse(raw)
3876
+ const picked = conf?.default_cards?.[mode]
3877
+ return typeof picked === 'string' ? picked : ''
3878
+ } catch {
3879
+ return ''
3880
+ }
3881
+ }
3882
+
3883
+ /** 把世界书条目排成人能读、模型也好读的样子。 */
3884
+ function worldEntriesText(entries) {
3885
+ const list = Array.isArray(entries) ? entries : []
3886
+ if (list.length === 0) return ''
3887
+ return list
3888
+ .map((entry) => {
3889
+ const keys = Array.isArray(entry?.keys) ? entry.keys.filter((k) => typeof k === 'string' && k !== '') : []
3890
+ const content = String(entry?.content ?? '').trim()
3891
+ const head = keys.length === 0 ? '(一直生效)' : `关键词:${keys.join('、')}`
3892
+ return `- ${head}\n ${content.replace(/\n/g, '\n ')}`
3893
+ })
3894
+ .join('\n')
3895
+ }
3896
+
3897
+ /**
3898
+ * 这张卡是不是「提示词型」:自述很长,而且没有性格/开场白/对话示例。
3899
+ *
3900
+ * 这种卡(网上流传的破限卡、规范卡)整份就是给模型的硬性指令,没有人物细节;
3901
+ * 它的正确用法是**原样当规则读**,而不是当成人物描述塞在演法说明后面。
3902
+ */
3903
+ export function cardIsPromptStyle(parsed) {
3904
+ const sections = Array.isArray(parsed?.sections) ? parsed.sections : []
3905
+ const self = core.sectionBody(sections, '自述')
3906
+ const selfLen = typeof self === 'string' ? self.trim().length : 0
3907
+ const others = ['性格', '开场白', '对话示例', '外貌']
3908
+ .map((title) => core.sectionBody(sections, title))
3909
+ .some((part) => typeof part === 'string' && part.trim() !== '')
3910
+ return selfLen >= 4000 && !others
3911
+ }
3912
+
3913
+ /**
3914
+ * 拼出这一场的人物卡段落。
3915
+ *
3916
+ * 不做任何删减:卡上写什么就是什么(用户说得对——删了就不是那张卡了)。
3917
+ * 只做两件必要的事:标题说清「你要演的是谁」,以及把世界书接在后面。
3918
+ *
3919
+ * @param {string} root 工作区绝对路径
3920
+ * @param {'tavern'|'novel'|'real'} mode 哪扇门
3921
+ * @returns {string} 空串表示这一场不挂卡
3922
+ */
3923
+ export function buildPersonaSection(root, mode) {
3924
+ const id = pinnedCardIdSync(root, mode)
3925
+ if (id === '') return ''
3926
+ const abs = cardPathSync(root, id)
3927
+ if (abs === '') return ''
3928
+ const text = readCachedSync(abs)
3929
+ if (text === null) return ''
3930
+ const parsed = core.parseCard(text)
3931
+ if (parsed.ok !== true) return ''
3932
+ const data = parsed.data ?? {}
3933
+ const sections = Array.isArray(parsed.sections) ? parsed.sections : []
3934
+ const body = ['自述', '性格', '外貌', '口癖', '不会说的话', '不会做的事', '场景', '开场白', '对话示例']
3935
+ .map((title) => core.sectionBody(sections, title))
3936
+ .filter((part) => typeof part === 'string' && part.trim() !== '')
3937
+ .join('\n\n')
3938
+ if (body.trim() === '') return ''
3939
+ const name = String(data.name ?? '').trim() === '' ? id : String(data.name).trim()
3940
+ // 「提示词型」的卡:整份内容就是给模型下的硬性规则(网上下载的破限卡、规范卡多是这样),
3941
+ // 它没有性格/开场白,自述就是一大段 MUST/ALWAYS。这种卡和预设里的演法说明容易撞,
3942
+ // 撞的时候要以卡为准——否则用户下载了什么就等于白下。
3943
+ const promptStyle = cardIsPromptStyle(parsed)
3944
+ const out = [
3945
+ `# 你要演的人:${name}${String(data.relation ?? '').trim() === '' ? '' : `(${String(data.relation).trim()})`}`,
3946
+ '',
3947
+ promptStyle
3948
+ ? '这张卡写的是硬性规矩(格式、口吻、怎么回),它本身就是这个人。以下是全部原文,一句不改;其中与别的说明冲突的地方,以这张卡为准。不要把它当成资料来引用,也不要在回答里提「卡上写着」。'
3949
+ : '下面这张卡就是这个人的全部设定,直接照它演——不要把它当成资料来引用,也不要在回答里提「卡上写着」。',
3950
+ '',
3951
+ body,
3952
+ ]
3953
+ const world = String(data.world ?? '').trim()
3954
+ if (world !== '' && world !== 'reality') {
3955
+ const worldAbs = path.join(root, 'worlds', core.safeId(world), 'world.md')
3956
+ const worldText = readCachedSync(worldAbs)
3957
+ if (worldText !== null) {
3958
+ const worldParsed = core.parseCard(worldText)
3959
+ const entries = worldParsed.ok === true ? core.parseWorldEntries(worldParsed.sections ?? []) : []
3960
+ const rendered = worldEntriesText(entries)
3961
+ if (rendered !== '') out.push('', `# 这一场发生在:${String(worldParsed.data?.name ?? world).trim()}`, '', rendered)
3962
+ }
3963
+ }
3964
+ return out.join('\n')
3965
+ }
3966
+
3967
+ /** 把一个 agent 上跟「预设」有关的字段都抄出来,用来定位到底哪个字段才是真的。 */
3968
+ function shapeOfAgent(agent) {
3969
+ const pick = (obj, keys) => {
3970
+ const out = {}
3971
+ for (const key of keys) {
3972
+ const value = obj?.[key]
3973
+ if (value !== undefined && value !== null && typeof value !== 'object') out[key] = String(value).slice(0, 60)
3974
+ }
3975
+ return out
3976
+ }
3977
+ return {
3978
+ id: typeof agent?.id === 'string' ? agent.id : '',
3979
+ options: pick(agent?.options, ['agentPreset', 'preset', 'presetId', 'model', 'provider']),
3980
+ meta: pick(agent?.meta, ['agentPreset', 'preset', 'origin', 'delegationDepth', 'cwd']),
3981
+ header: pick(agent?.header, ['agentPreset', 'cwd']),
3982
+ sessionHeader: pick(agent?.session?.header, ['agentPreset', 'cwd', 'origin']),
3983
+ optionKeys: Object.keys(agent?.options ?? {}).slice(0, 20),
3984
+ metaKeys: Object.keys(agent?.meta ?? {}).slice(0, 20),
3985
+ }
3986
+ }
3987
+
3988
+ /** 人物卡注入的诊断日志。写文件而不是 console:宿主把插件的 stdout 丢进 /dev/null。 */
3989
+ function notePersona(step, detail) {
3990
+ try {
3991
+ const file = path.join(os.tmpdir(), 'lifecard-persona.log')
3992
+ const line = `${new Date().toISOString()} ${step} ${JSON.stringify(detail)}\n`
3993
+ appendFileSync(file, line)
3994
+ const size = statSync(file).size
3995
+ if (size > 200 * 1024) writeFileSync(file, line)
3996
+ } catch {
3997
+ /* 日志写不了不影响正事 */
3998
+ }
3999
+ }
4000
+
4001
+ /** 从会话标签里认出用的是哪个预设(不同版本字段位置不完全一样,挨个试)。 */
4002
+ function presetIdOfAgent(agent) {
4003
+ const spots = [
4004
+ agent?.options?.agentPreset,
4005
+ agent?.meta?.agentPreset,
4006
+ agent?.header?.agentPreset,
4007
+ agent?.session?.header?.agentPreset,
4008
+ agent?.info?.agentPreset,
4009
+ ]
4010
+ for (const spot of spots) {
4011
+ if (typeof spot === 'string' && spot !== '') return spot
4012
+ }
4013
+ return ''
4014
+ }
4015
+
4016
+ /**
4017
+ * 从预设注册表里问「这个会话当初是按哪一份预设装的」。
4018
+ *
4019
+ * 为什么需要这条:DSH 顶部的预设是在会话建好之后才定下来的,
4020
+ * agent 上那些 agentPreset 字段实测会停在默认值(standard),
4021
+ * 直接读它会认错门,卡就永远进不去。
4022
+ * inspectCompositions(ctx) 的返回形状没有公开文档,所以这里只做一件事:
4023
+ * 把它序列化之后找 lc-tavern / lc-novel 这两个名字。
4024
+ */
4025
+ function modeFromPresetRegistry(ctx, agent) {
4026
+ try {
4027
+ const registry = ctx?.get?.('agentPresets', false)
4028
+ if (registry === null || registry === undefined || typeof registry.inspectCompositions !== 'function') return ''
4029
+ const rows = registry.inspectCompositions(agent?.ctx) ?? []
4030
+ const blob = JSON.stringify(rows)
4031
+ if (blob.includes('lc-tavern')) return 'tavern'
4032
+ if (blob.includes('lc-novel')) return 'novel'
4033
+ } catch {
4034
+ /* 问不到就当不知道 */
4035
+ }
4036
+ return ''
4037
+ }
4038
+
4039
+ /** 这个 agent 用哪扇门的卡:只有 LC 那两个创作预设才挂,别的会话一个字都不注入。 */
4040
+ function modeForAgent(agent) {
4041
+ const preset = presetIdOfAgent(agent)
4042
+ if (preset === '') return ''
4043
+ if (preset.includes('lc-tavern')) return 'tavern'
4044
+ if (preset.includes('lc-novel')) return 'novel'
4045
+ return ''
4046
+ }
4047
+
4048
+ /** 子代理不挂人设:它不该以为自己是那个人。 */
4049
+ function isMainAgent(agent) {
4050
+ const origin = String(agent?.meta?.origin ?? agent?.session?.header?.origin ?? '')
4051
+ if (origin === 'subagent') return false
4052
+ const depth = Number(agent?.meta?.delegationDepth ?? agent?.session?.header?.delegationDepth ?? 0)
4053
+ return !(Number.isFinite(depth) && depth > 0)
4054
+ }
4055
+
4056
+ /**
4057
+ * 给一个会话挂上人物卡段落。返回 true 表示挂上了。
4058
+ *
4059
+ * 必须挂在 agent 自己的 ctx 上:段落按 scope 分发,注册在插件 ctx 上的段落
4060
+ * 落不到任何会话的组装里(上一版就这么写的,模型压根看不见卡)。
4061
+ */
4062
+ export function attachCardToAgent(agent, options = {}) {
4063
+ const rootNow = typeof options.rootNow === 'function' ? options.rootNow : () => defaultWorkspace()
4064
+ const attached = options.attached !== null && typeof options.attached?.has === 'function' && typeof options.attached?.add === 'function' ? options.attached : null
4065
+ const note = typeof options.note === 'function' ? options.note : () => {}
4066
+ const pluginCtx = options.ctx ?? null
4067
+ try {
4068
+ if (agent === null || agent === undefined) return false
4069
+ const agentId = typeof agent.id === 'string' ? agent.id : ''
4070
+ if (attached !== null && attached.has(agent)) return false
4071
+ if (!isMainAgent(agent)) return false
4072
+ const agentCtx = agent.ctx
4073
+ if (agentCtx === null || agentCtx === undefined || typeof agentCtx.effect !== 'function') return false
4074
+ const prompt = agentCtx.get('systemPrompt', false)
4075
+ if (prompt === null || prompt === undefined || typeof prompt.section !== 'function') return false
4076
+ // 注意:这里**不**按预设提前返回。DSH 顶部的预设是在会话建好之后才通过
4077
+ // agentPresets.select 定下来的,创建那一刻 agent 上的预设字段还可能是默认值
4078
+ // (实测拿到的是 standard)。所以段落一律挂上,每次组装提示词时再按当下的
4079
+ // 预设判断要不要给内容——换预设立刻生效,也不用等重新建会话。
4080
+ let evaluated = 0
4081
+ let reported = false
4082
+ agentCtx.effect(
4083
+ () =>
4084
+ prompt.section({
4085
+ name: 'lifecard:card',
4086
+ order: (() => {
4087
+ try {
4088
+ const anchor = prompt.getSectionOrder('deployment:persona-prefix')
4089
+ if (typeof anchor === 'number' && Number.isFinite(anchor)) return anchor + 0.5
4090
+ } catch {
4091
+ /* 拿不到锚点就用一个靠前但又不抢位置的值 */
4092
+ }
4093
+ return 500
4094
+ })(),
4095
+ text: () => {
4096
+ try {
4097
+ const mode = modeForAgent(agent) || modeFromPresetRegistry(pluginCtx, agent)
4098
+ if (mode === '') {
4099
+ if (!reported) {
4100
+ reported = true
4101
+ notePersona('no-door', { agent: agentId, ...shapeOfAgent(agent) })
4102
+ }
4103
+ return ''
4104
+ }
4105
+ const text = buildPersonaSection(rootNow(), mode)
4106
+ if (evaluated < 3) {
4107
+ evaluated += 1
4108
+ notePersona('text', { agent: agentId, mode, chars: text.length, root: rootNow() })
4109
+ }
4110
+ return text
4111
+ } catch {
4112
+ // 提示词拼不出来也不能挡住这一句话。
4113
+ return ''
4114
+ }
4115
+ },
4116
+ interpolate: false,
4117
+ }),
4118
+ 'lifecard: 人物卡段落',
4119
+ )
4120
+ if (attached !== null) attached.add(agent)
4121
+ return true
4122
+ } catch (error) {
4123
+ console.error('[lifecard] 人物卡段落没挂上:', error)
4124
+ return false
4125
+ }
4126
+ }
4127
+
3487
4128
  function registerInterviewSkill(ctx) {
4129
+ registerBundledSkill(ctx, {
4130
+ dir: 'lifecard-interview',
4131
+ name: 'lifecard-interview',
4132
+ fallback: '引导式对话访谈,把一张人物卡问出来。',
4133
+ label: '访谈',
4134
+ })
4135
+ registerBundledSkill(ctx, {
4136
+ dir: 'lifecard-novel-writing',
4137
+ name: 'lifecard-novel-writing',
4138
+ fallback: '中文小说与长文的写法:先分清用不用人物卡,按传统文学的标准写正文,要连载节奏就切。',
4139
+ label: '写作',
4140
+ })
4141
+ // 这三份是写作用得上的通用手艺,随包一起发:装插件即等于有,
4142
+ // 换台机器不必再单独装一遍。名字与内容都保持原样,方便用户照旧用
4143
+ // `/human-writing`、`/blind-review-loop`、`/visual-novel` 唤起。
4144
+ //
4145
+ // 同名冲突时让位:用户自己那份通常更新,硬盖上去等于拿旧版本把新版本
4146
+ // 顶掉,而且他看不出来。
4147
+ registerBundledSkill(ctx, {
4148
+ dir: 'human-writing',
4149
+ name: 'human-writing',
4150
+ fallback: '通用中文创作与改稿:先看材料够不够,再写成有人在说话的样子。',
4151
+ label: '写作手艺',
4152
+ yieldToExisting: true,
4153
+ })
4154
+ registerBundledSkill(ctx, {
4155
+ dir: 'blind-review-loop',
4156
+ name: 'blind-review-loop',
4157
+ fallback: '盲评迭代改稿:冻结副本、开无上下文评审员、把意见分诊后定向改,再评一轮。',
4158
+ label: '盲评改稿',
4159
+ yieldToExisting: true,
4160
+ })
4161
+ registerBundledSkill(ctx, {
4162
+ dir: 'visual-novel',
4163
+ name: 'visual-novel',
4164
+ fallback: '视觉小说:分支剧本、对话框、存档、回放这些读者以为本来就在的东西。',
4165
+ label: '视觉小说',
4166
+ yieldToExisting: true,
4167
+ })
4168
+ }
4169
+
4170
+ /**
4171
+ * 注册一个随包 skill。两处共同点都在这里:skills/SKILL.md 与 lib/ 同包,
4172
+ * 用 import.meta.url 定位(不依赖 cwd);没有 skills 服务时只少一个 skill,
4173
+ * 不能让整个插件起不来。
4174
+ */
4175
+ function registerBundledSkill(ctx, spec) {
3488
4176
  const skills = ctx.reflect?.get?.('skills', false)
3489
4177
  if (skills === undefined || skills === null || typeof skills.register !== 'function') {
3490
- ctx.logger?.warn?.('[lifecard] 没有 skills 服务,访谈 skill 未注册(不影响卡库功能)')
4178
+ ctx.logger?.warn?.(`[lifecard] 没有 skills 服务,${spec.label} skill 未注册(不影响卡库功能)`)
4179
+ return
4180
+ }
4181
+ if (spec.yieldToExisting === true && hasSkillNamed(skills, spec.name)) {
4182
+ // 用户已经有一份同名的:他的更新,别盖。
4183
+ ctx.logger?.info?.(`[lifecard] 已经有 ${spec.name} 这个 skill,插件这份不再注册`)
3491
4184
  return
3492
4185
  }
3493
- const body = interviewSkillBody()
4186
+ const body = bundledSkillBody(spec.dir)
3494
4187
  if (body === '') {
3495
- ctx.logger?.warn?.('[lifecard] 找不到 skills/lifecard-interview/SKILL.md,访谈 skill 未注册')
4188
+ ctx.logger?.warn?.(`[lifecard] 找不到 skills/${spec.dir}/SKILL.md,${spec.label} skill 未注册`)
3496
4189
  return
3497
4190
  }
3498
4191
  const { frontmatter, content } = splitSkillFile(body)
3499
4192
  ctx.effect(
3500
4193
  () => skills.register({
3501
- name: 'lifecard-interview',
3502
- description: frontmatter.description ?? '引导式对话访谈,把一张人物卡问出来。',
4194
+ name: spec.name,
4195
+ description: frontmatter.description ?? spec.fallback,
3503
4196
  whenToUse: frontmatter.whenToUse,
3504
4197
  content,
3505
4198
  source: 'lifecard',
4199
+ // 带上目录:SKILL.md 里说的 references/xxx.md、scripts/xxx.py
4200
+ // 才有地方可查。不带 resourceBase,模型看到「读取 references/…」
4201
+ // 只能瞎猜路径。
4202
+ resourceBase: { kind: 'directory', path: bundledSkillDir(spec.dir) },
3506
4203
  invocation: { modelInvocable: true, userInvocable: true },
3507
4204
  }),
3508
- 'dsh-lifecard: lifecard-interview skill',
4205
+ `dsh-lifecard: ${spec.name} skill`,
3509
4206
  )
3510
4207
  }
3511
4208
 
4209
+ /** 目录里有没有同名 skill(用户自己装的那份)。问不到就当没有。 */
4210
+ function hasSkillNamed(skills, name) {
4211
+ if (typeof skills.list !== 'function') return false
4212
+ try {
4213
+ const list = skills.list()
4214
+ if (!Array.isArray(list)) return false
4215
+ return list.some((s) => String(s?.name ?? '') === name)
4216
+ } catch {
4217
+ return false
4218
+ }
4219
+ }
4220
+
3512
4221
  /** SKILL.md 与 lib/ 同包,用 import.meta.url 定位,不依赖 cwd。 */
3513
- function interviewSkillPath() {
3514
- return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'lifecard-interview', 'SKILL.md')
4222
+ function bundledSkillPath(dir) {
4223
+ return path.join(bundledSkillDir(dir), 'SKILL.md')
4224
+ }
4225
+
4226
+ /** 这份 skill 的目录(references/、scripts/ 都在它下面)。 */
4227
+ function bundledSkillDir(dir) {
4228
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', dir)
3515
4229
  }
3516
4230
 
3517
- let interviewSkillCache
3518
- function interviewSkillBody() {
3519
- if (interviewSkillCache === undefined) {
4231
+ const bundledSkillCache = new Map()
4232
+ function bundledSkillBody(dir) {
4233
+ if (!bundledSkillCache.has(dir)) {
3520
4234
  try {
3521
- interviewSkillCache = readFileSync(interviewSkillPath(), 'utf8')
4235
+ bundledSkillCache.set(dir, readFileSync(bundledSkillPath(dir), 'utf8'))
3522
4236
  } catch {
3523
- interviewSkillCache = ''
4237
+ bundledSkillCache.set(dir, '')
3524
4238
  }
3525
4239
  }
3526
- return interviewSkillCache
4240
+ return bundledSkillCache.get(dir)
3527
4241
  }
3528
4242
 
3529
4243
  /** 拆 YAML frontmatter(只认 `key: value` 单行,够用且不引依赖)。 */
@@ -3574,8 +4288,80 @@ export function apply(ctx, config) {
3574
4288
  remember: (ws) => rememberWorkspace(pointerFile, ws),
3575
4289
  })
3576
4290
 
4291
+ // 系统提示段落里的 text() 必须同步返回,拿不到异步的 workspace()。
4292
+ // 所以这里留一份「当前库」的快照:先用默认值兜底,再异步校准一次;
4293
+ // 用户在界面上换文件夹时 settings.workspace 会跟着变,优先用那个。
4294
+ let liveRoot = defaultWorkspace()
4295
+ Promise.resolve()
4296
+ .then(() => workspace())
4297
+ .then((ws) => {
4298
+ if (typeof ws === 'string' && ws !== '') liveRoot = ws
4299
+ })
4300
+ .catch(() => {})
4301
+ const rootNow = () => {
4302
+ const configured = typeof settings.workspace === 'string' ? settings.workspace.trim() : ''
4303
+ return configured === '' ? liveRoot : configured
4304
+ }
4305
+
3577
4306
  registerInterviewSkill(ctx)
3578
4307
 
4308
+ // 把人物卡、世界书交给模型的那几个只读工具。挂在宿主这一层,所以不只是
4309
+ // 「LC 酒馆 / LC 小说 / LC 现实」三个预设,任何预览里都能调。
4310
+ // 用 ctx.inject 等 tools 服务就绪:apply 跑的时候它可能还没起来,
4311
+ // 直接 ctx.get('tools') 会拿到 undefined,工具就静默少了。
4312
+ // 把挑好的那张卡拼进系统提示(不是对话里的资料)。
4313
+ //
4314
+ // 必须挂在 **agent 自己的 ctx** 上。段落是按 scope 分发的:注册在插件自己
4315
+ // 那个 ctx 上的段落,落不到任何一个会话的组装里——上一版就是这么写的,
4316
+ // 结果模型压根看不见卡,只能反问「演 rat 是什么意思」,然后去翻工具。
4317
+ // `text` 传函数,每轮组装都会重新求值,所以换卡/改卡下一句就生效。
4318
+ // 去重按 **agent 对象**,不是按会话 id:在顶部换预设时 DSH 会给同一个会话
4319
+ // 重新建一个 agent(新对象、新的 meta),按 id 去重会把换过预设的会话锁死在
4320
+ // 「第一次那个 agent 认成 standard」的结果上。换对象就重新挂一次。
4321
+ const attachedAgents = new WeakSet()
4322
+ const attachCard = (agent) => {
4323
+ const ok = attachCardToAgent(agent, { rootNow, attached: attachedAgents, note: notePersona, ctx })
4324
+ if (ok !== true) notePersona('skip', shapeOfAgent(agent))
4325
+ return ok
4326
+ }
4327
+
4328
+ // agent/created 是 serial 事件:这里同步抛错会否决整个会话的创建,
4329
+ // 所以宁可没人设,也绝不能让用户开不了会话。
4330
+ try {
4331
+ ctx.on('agent/created', (event) => {
4332
+ try {
4333
+ attachCard(event?.agent)
4334
+ } catch (error) {
4335
+ console.error('[lifecard] agent/created 处理失败:', error)
4336
+ }
4337
+ })
4338
+ } catch (error) {
4339
+ console.error('[lifecard] 没能监听 agent/created:', error)
4340
+ }
4341
+ // 已经在跑的会话不会再发 agent/created(插件重载、宿主启动时已存在的会话),
4342
+ // 所以要再扫一遍。
4343
+ if (typeof ctx.inject === 'function') {
4344
+ ctx.inject(['agents'], (agentsCtx) => {
4345
+ try {
4346
+ const registry = agentsCtx.get('agents', false)
4347
+ const list = typeof registry?.list === 'function' ? registry.list() : []
4348
+ for (const agent of list) attachCard(agent)
4349
+ } catch (error) {
4350
+ console.error('[lifecard] 补挂已有会话失败:', error)
4351
+ }
4352
+ })
4353
+ }
4354
+
4355
+ if (typeof ctx.inject === 'function') {
4356
+ ctx.inject(['tools'], (toolCtx) => {
4357
+ try {
4358
+ lifecardTools.registerTools(toolCtx, settings)
4359
+ } catch (error) {
4360
+ console.error('[lifecard] 只读工具没挂上:', error)
4361
+ }
4362
+ })
4363
+ }
4364
+
3579
4365
  ctx.effect(
3580
4366
  () => ctx.webServer.register({
3581
4367
  kind: 'prefix',