dsh-lifecard 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/cordis.patch.yml +64 -0
- package/lib/career.js +98 -0
- package/lib/client.js +633 -18
- package/lib/core.js +20 -3
- package/lib/diary.js +838 -0
- package/lib/index.js +444 -9
- package/lib/novel.js +4 -0
- package/lib/presets.js +30 -0
- package/lib/store.js +98 -12
- package/lib/tavern.js +3 -0
- package/lifecard-tools.js +534 -59
- package/package.json +2 -1
- package/skills/lifecard-diary/SKILL.md +131 -0
package/lib/diary.js
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* diary —— 一天一篇,AI 带着写。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一层:日记不是「人物卡」,也不是「简历」。卡记的是一个人是谁,
|
|
5
|
+
* 简历记的是他会什么;日记记的是**这一天他身上发生了什么、他当时怎么想、
|
|
6
|
+
* 后来做了什么决定**。三样东西会互相喂:日记写厚了,「我」那张卡就该更准;
|
|
7
|
+
* 卡写准了,下一回它劝你的话才不像一个陌生人。
|
|
8
|
+
*
|
|
9
|
+
* 落盘形状(用户拿访达就能看、能改、能带走):
|
|
10
|
+
* ```
|
|
11
|
+
* <用户自己指定的文件夹>/
|
|
12
|
+
* 2026-10-31.md
|
|
13
|
+
* 2026-11-01.md
|
|
14
|
+
* ```
|
|
15
|
+
* 一篇一个文件,文件名就是日期。不按月份分文件夹:一年三百多个文件,
|
|
16
|
+
* 摊平比套三层目录好找,也方便用户自己丢进任何同步盘。
|
|
17
|
+
*
|
|
18
|
+
* 这一层只碰磁盘与文字:不调模型、不碰 HTTP。路由在 index.js,界面在 client.js。
|
|
19
|
+
*
|
|
20
|
+
* ## 写盘为什么这么啰嗦
|
|
21
|
+
*
|
|
22
|
+
* 日记是用户唯一会亲手改的文件。他会在访达里打开、加一行自己的话、
|
|
23
|
+
* 改个标题、把某一节删掉。所以这一层写之前必须:先读旧内容、读不出来就
|
|
24
|
+
* 一个字都不写、写之前留个底、用户自己加的 frontmatter 键和小节原样带着走、
|
|
25
|
+
* 空掉的小节不再凭空长回来、分数宽容地认(小数、全角、负号都算)。
|
|
26
|
+
* 这些保护写在 writeDiary 里而不是写在工具里,是因为 HTTP 路由 `diary.save`
|
|
27
|
+
* 也直接调它——保护写在上一层,下一层的口子就还是敞着的。
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import fs from 'node:fs/promises'
|
|
31
|
+
import path from 'node:path'
|
|
32
|
+
import * as core from './core.js'
|
|
33
|
+
import { localDate } from './store.js'
|
|
34
|
+
|
|
35
|
+
/** frontmatter 里的 kind。用来分清这个文件是日记还是别的什么。 */
|
|
36
|
+
const DIARY_KIND = 'lifecard-diary'
|
|
37
|
+
|
|
38
|
+
/** 一篇日记的正文小节。这个顺序就是写进文件的顺序。 */
|
|
39
|
+
export const DIARY_SECTIONS = [
|
|
40
|
+
'今天最值得讲的一件事',
|
|
41
|
+
'当时在想什么',
|
|
42
|
+
'情绪往下三层',
|
|
43
|
+
'我做了什么决定',
|
|
44
|
+
'下一步',
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
/** 一行一条的小节。其余小节是一段自由文字。 */
|
|
48
|
+
export const DIARY_LIST_SECTIONS = ['下一步']
|
|
49
|
+
|
|
50
|
+
/** 四维打分:人生设计里那四个格子。0 分表示这个维度今天没碰。 */
|
|
51
|
+
export const DIMENSIONS = ['健康', '工作', '关系', '玩']
|
|
52
|
+
|
|
53
|
+
/** 日期形状。日记文件名只认这个,别的名字一律不看。 */
|
|
54
|
+
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})\.md$/
|
|
55
|
+
|
|
56
|
+
/** 打分那一段的标题。它不算正文小节,单独排。 */
|
|
57
|
+
const SCORE_SECTION = '今天这四样'
|
|
58
|
+
|
|
59
|
+
/** frontmatter 里我们自己会写的键。其余键是用户加的,得原样带着走。 */
|
|
60
|
+
const HEAD_OWN_KEYS = new Set(['lifecard', 'kind', 'date', 'mood'])
|
|
61
|
+
|
|
62
|
+
/** 覆盖前留底的地方,在用户那个日记文件夹里的一层隐藏目录。 */
|
|
63
|
+
const SNAPSHOT_DIR = '.lifecard'
|
|
64
|
+
const SNAPSHOT_SUB = '旧版本'
|
|
65
|
+
|
|
66
|
+
// ── 路径 ─────────────────────────────────────────────────────────
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 这一天的文件名。日期必须真的是个日子,`2026-13-45` 这种不接受——
|
|
70
|
+
* 不然会在用户文件夹里造出一个永远读不回来的文件。
|
|
71
|
+
*/
|
|
72
|
+
export function dateFileName(date) {
|
|
73
|
+
const raw = String(date ?? '').trim()
|
|
74
|
+
const m = DATE_RE.exec(`${raw}.md`)
|
|
75
|
+
if (m === null) return ''
|
|
76
|
+
const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
|
|
77
|
+
const ok = d.getFullYear() === Number(m[1]) && d.getMonth() + 1 === Number(m[2]) && d.getDate() === Number(m[3])
|
|
78
|
+
return ok ? `${raw}.md` : ''
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 今天该写的那一篇的路径。 */
|
|
82
|
+
export function diaryFileName(today = localDate()) {
|
|
83
|
+
return dateFileName(today) === '' ? '' : `${today}.md`
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 这个文件名算不算某一天的日记——放宽一档。
|
|
88
|
+
*
|
|
89
|
+
* 严格只认 `2026-10-30.md` 的问题是:用户在访达里把它改名成
|
|
90
|
+
* 「2026-10-30 周五.md」或者后缀变成 `.MD`,从此这一天就"不存在"了——
|
|
91
|
+
* 界面说今天还没写,再存一次还会新建一个同日期文件,两篇分叉。
|
|
92
|
+
* 日记是用户自己的文件,他有一个起名字的权利。
|
|
93
|
+
*
|
|
94
|
+
* 所以放宽到:日期对得上,后面跟不跟东西都行。但日期本身必须真是那一天,
|
|
95
|
+
* `2026-13-45` 这种照样不认;后缀必须是 `.md`(不区分大小写)。
|
|
96
|
+
*
|
|
97
|
+
* @returns {string} 认得出就回 `YYYY-MM-DD`,认不出回空串。
|
|
98
|
+
*/
|
|
99
|
+
function looseDateOf(name) {
|
|
100
|
+
const raw = String(name ?? '')
|
|
101
|
+
if (!/\.md$/i.test(raw)) return ''
|
|
102
|
+
const stem = raw.slice(0, -3)
|
|
103
|
+
const m = /^(\d{4}-\d{2}-\d{2})(?:[\s_\-–—].*)?$/.exec(stem)
|
|
104
|
+
if (m === null) return ''
|
|
105
|
+
return dateFileName(m[1]) === '' ? '' : m[1]
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 这一天的日记到底是哪个文件。
|
|
110
|
+
*
|
|
111
|
+
* 先找标准名字;没有再在这个文件夹里找「日期对得上、后面被加了别的话」的
|
|
112
|
+
* 那份(用户自己改过名)。找到就接着用它写,不另建一个同日期文件把一篇
|
|
113
|
+
* 日记劈成两半。
|
|
114
|
+
*/
|
|
115
|
+
async function findDiaryFile(dir, date) {
|
|
116
|
+
const exact = dateFileName(date)
|
|
117
|
+
if (exact === '') return { ok: false, error: '日子不对,日记只认 年-月-日 这种写法。' }
|
|
118
|
+
const absExact = path.join(dir, exact)
|
|
119
|
+
const got = await readRaw(absExact)
|
|
120
|
+
if (got.kind !== 'none') return { ok: true, name: exact, abs: absExact, raw: got, loose: false }
|
|
121
|
+
let names
|
|
122
|
+
try {
|
|
123
|
+
names = await fs.readdir(dir)
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error?.code === 'ENOENT') return { ok: true, name: exact, abs: absExact, raw: got, loose: false }
|
|
126
|
+
return { ok: false, error: '那个日记文件夹读不出来。检查一下权限。' }
|
|
127
|
+
}
|
|
128
|
+
const hits = names.filter((n) => looseDateOf(n) === date).sort()
|
|
129
|
+
if (hits.length === 0) return { ok: true, name: exact, abs: absExact, raw: got, loose: false }
|
|
130
|
+
const name = hits[0]
|
|
131
|
+
const abs = path.join(dir, name)
|
|
132
|
+
return { ok: true, name, abs, raw: await readRaw(abs), loose: true }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 日记放进哪里:用户自己指定的那个文件夹。
|
|
137
|
+
*
|
|
138
|
+
* 没指定就返回空串,让调用方去问,而不是偷偷写进工作区——
|
|
139
|
+
* 用户原话是「日记不用存插件」,那就一个字节都不该落在插件目录里。
|
|
140
|
+
*/
|
|
141
|
+
export function diaryRootFrom(config) {
|
|
142
|
+
const raw = typeof config?.diary_dir === 'string' ? config.diary_dir.trim() : ''
|
|
143
|
+
if (raw === '') return ''
|
|
144
|
+
const home = process.env.HOME ?? ''
|
|
145
|
+
if (raw === '~') return home
|
|
146
|
+
if (raw.startsWith('~/')) return path.join(home, raw.slice(2))
|
|
147
|
+
// 相对路径不能按「进程现在站在哪儿」算:那个位置是插件自己的安装目录,
|
|
148
|
+
// 用户输入「我的日记」会在插件包里造一个文件夹,他永远找不到。
|
|
149
|
+
// 相对路径一律按「他的家目录」算,这是他说那句话时唯一会想到的地方。
|
|
150
|
+
if (!path.isAbsolute(raw)) return path.join(home, raw)
|
|
151
|
+
return path.normalize(raw)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// ── 写 / 读 ──────────────────────────────────────────────────────
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 一篇日记写成 Markdown。
|
|
158
|
+
*
|
|
159
|
+
* 空的小节**不写标题**:用户把某一节整段删掉,是「这一节我不想写」,
|
|
160
|
+
* 不是「请你下次再替我补回来」。全空就只剩 frontmatter。
|
|
161
|
+
*
|
|
162
|
+
* 第二个参数用来把「不属于五节、但文件里本来就有」的东西原样带回去:
|
|
163
|
+
* `headExtras`(用户自己加的 frontmatter 键)、`extraSections`(用户加的小节)、
|
|
164
|
+
* `intro`(第一个标题之前那段话)、`scoreLines`(认不出来的打分行)。
|
|
165
|
+
*/
|
|
166
|
+
export function renderDiaryMarkdown(data, options = {}) {
|
|
167
|
+
const d = data !== null && typeof data === 'object' && !Array.isArray(data) ? data : {}
|
|
168
|
+
const date = dateFileName(d.date) === '' ? localDate() : String(d.date)
|
|
169
|
+
const mood = String(d.mood ?? '').trim()
|
|
170
|
+
const scores = d.scores !== null && typeof d.scores === 'object' && !Array.isArray(d.scores) ? d.scores : {}
|
|
171
|
+
const head = {
|
|
172
|
+
lifecard: core.DATA_VERSION,
|
|
173
|
+
kind: DIARY_KIND,
|
|
174
|
+
date,
|
|
175
|
+
}
|
|
176
|
+
const extras = options?.headExtras !== null && typeof options?.headExtras === 'object' ? options.headExtras : {}
|
|
177
|
+
for (const key of Object.keys(extras)) {
|
|
178
|
+
const value = extras[key]
|
|
179
|
+
if (String(key).trim() === '' || HEAD_OWN_KEYS.has(key)) continue
|
|
180
|
+
if (value === undefined || value === null) continue
|
|
181
|
+
head[key] = value
|
|
182
|
+
}
|
|
183
|
+
if (mood !== '') head.mood = mood
|
|
184
|
+
|
|
185
|
+
const blocks = []
|
|
186
|
+
const intro = String(options?.intro ?? '').trim()
|
|
187
|
+
if (intro !== '') blocks.push(intro)
|
|
188
|
+
for (const title of DIARY_SECTIONS) {
|
|
189
|
+
const value = d[title]
|
|
190
|
+
const body = DIARY_LIST_SECTIONS.includes(title) ? renderList(value) : String(value ?? '').trim()
|
|
191
|
+
if (body === '') continue
|
|
192
|
+
blocks.push(`## ${title}\n\n${body}`)
|
|
193
|
+
}
|
|
194
|
+
// 打分单独放一段,写成「健康 6」这种最省事的形状:用户手改也方便。
|
|
195
|
+
const scoreLines = DIMENSIONS.filter((name) => Number.isFinite(Number(scores[name])) && String(scores[name]).trim() !== '')
|
|
196
|
+
.map((name) => `- ${name} ${trimScore(scores[name])}`)
|
|
197
|
+
const keptScoreLines = Array.isArray(options?.scoreLines)
|
|
198
|
+
? options.scoreLines.map((line) => String(line ?? '').trim()).filter((line) => line !== '')
|
|
199
|
+
: []
|
|
200
|
+
const allScoreLines = [...scoreLines, ...keptScoreLines]
|
|
201
|
+
if (allScoreLines.length > 0) blocks.push(`## ${SCORE_SECTION}\n\n${allScoreLines.join('\n')}`)
|
|
202
|
+
for (const one of Array.isArray(options?.extraSections) ? options.extraSections : []) {
|
|
203
|
+
const title = String(one?.title ?? '').trim()
|
|
204
|
+
const body = String(one?.body ?? '').trim()
|
|
205
|
+
if (title === '' || body === '') continue
|
|
206
|
+
blocks.push(`## ${title}\n\n${body}`)
|
|
207
|
+
}
|
|
208
|
+
return `---\n${core.stringifyYaml(head)}\n---\n\n${blocks.join('\n\n')}\n`
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 分数写成整数就不带小数点,写成 6.5 就照写。 */
|
|
212
|
+
function trimScore(value) {
|
|
213
|
+
const n = Number(value)
|
|
214
|
+
if (!Number.isFinite(n)) return '0'
|
|
215
|
+
const clamped = Math.max(0, Math.min(10, n))
|
|
216
|
+
return Number.isInteger(clamped) ? String(clamped) : String(Math.round(clamped * 10) / 10)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 反过来:把一篇日记读成 `{data, sections}`。读不成给人话。
|
|
221
|
+
*
|
|
222
|
+
* 除了五个标准小节,还会把「文件里本来就有、但不是我们写的」那些东西
|
|
223
|
+
* 一并交回去(`headExtras` / `extraSections` / `intro` / `scoreLines`),
|
|
224
|
+
* 这样写回的时候能原样带着走,不会悄悄抹掉用户自己加的话。
|
|
225
|
+
*/
|
|
226
|
+
export function parseDiaryText(text) {
|
|
227
|
+
const parsed = core.parseCard(String(text ?? ''))
|
|
228
|
+
if (parsed.ok !== true) return { ok: false, error: '这一篇日记读不出来,格式不对。' }
|
|
229
|
+
const head = parsed.data ?? {}
|
|
230
|
+
const kind = String(head.kind ?? '').trim()
|
|
231
|
+
if (kind !== '' && kind !== DIARY_KIND) return { ok: false, error: '这个文件不是日记,是别的文件。' }
|
|
232
|
+
const grouped = regroupSections(parsed.sections)
|
|
233
|
+
const bodyOf = (title) => String(grouped.byTitle.get(title) ?? '').trim()
|
|
234
|
+
const data = { date: String(head.date ?? '').trim() }
|
|
235
|
+
const mood = String(head.mood ?? '').trim()
|
|
236
|
+
if (mood !== '') data.mood = mood
|
|
237
|
+
const headExtras = {}
|
|
238
|
+
for (const key of Object.keys(head)) {
|
|
239
|
+
if (HEAD_OWN_KEYS.has(key)) continue
|
|
240
|
+
headExtras[key] = head[key]
|
|
241
|
+
}
|
|
242
|
+
const scores = {}
|
|
243
|
+
const scoreLines = []
|
|
244
|
+
for (const title of DIARY_SECTIONS) {
|
|
245
|
+
const body = bodyOf(title)
|
|
246
|
+
data[title] = DIARY_LIST_SECTIONS.includes(title) ? parseList(body) : body
|
|
247
|
+
}
|
|
248
|
+
for (const line of parseList(bodyOf(SCORE_SECTION))) {
|
|
249
|
+
const got = parseScoreLine(line)
|
|
250
|
+
if (got === null || !DIMENSIONS.includes(got.name)) {
|
|
251
|
+
// 认不出来的打分行原样留着:宁可多一行,不要静默吃掉用户写的东西。
|
|
252
|
+
scoreLines.push(line)
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
scores[got.name] = got.value
|
|
256
|
+
}
|
|
257
|
+
data.scores = scores
|
|
258
|
+
return {
|
|
259
|
+
ok: true,
|
|
260
|
+
data,
|
|
261
|
+
sections: parsed.sections,
|
|
262
|
+
headExtras,
|
|
263
|
+
// 用户自己写的小标题现在留在正文里,不再单拎成「额外小节」——
|
|
264
|
+
// 拎出去等于把它从原本待着的那一段里挖走,写回去就多一份。
|
|
265
|
+
extraSections: [],
|
|
266
|
+
scoreLines,
|
|
267
|
+
intro: grouped.intro,
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* 把切出来的小节重新归位:**只有我们自己那六个标题算分节线**。
|
|
273
|
+
*
|
|
274
|
+
* 用户在自己那一节里手写一行 `## 医院里的事` 是很自然的事(那本来就是
|
|
275
|
+
* 一段小标题)。以前 `splitSections` 见到任何 `^## ` 都另起一节,于是
|
|
276
|
+
* 那一行连同它下面的话被搬出正文、摆到文件末尾——模型再读就只看得到
|
|
277
|
+
* 第一行,改一次多出一份,文件越写越长。
|
|
278
|
+
*
|
|
279
|
+
* 这里改口径:认得的标题才分节,不认得的标题原样留在它所在那一节的正文里,
|
|
280
|
+
* 一个字都不搬。这样「读进来 → 写回去」是恒等的,模型也看得到全段。
|
|
281
|
+
*/
|
|
282
|
+
function regroupSections(sections) {
|
|
283
|
+
const known = new Set([...DIARY_SECTIONS, SCORE_SECTION])
|
|
284
|
+
const intro = []
|
|
285
|
+
const blocks = []
|
|
286
|
+
let cur = null
|
|
287
|
+
const startBlock = (title, lines) => {
|
|
288
|
+
cur = { title, lines: Array.isArray(lines) ? lines.slice() : [] }
|
|
289
|
+
blocks.push(cur)
|
|
290
|
+
}
|
|
291
|
+
const push = (lines) => {
|
|
292
|
+
if (cur === null) intro.push(...lines)
|
|
293
|
+
else cur.lines.push(...lines)
|
|
294
|
+
}
|
|
295
|
+
// 一行 `## xxx`:认得的标题才另起一节。
|
|
296
|
+
const headingOf = (line) => {
|
|
297
|
+
const m = /^##\s+(.+?)\s*$/.exec(String(line ?? ''))
|
|
298
|
+
if (m === null) return ''
|
|
299
|
+
const title = m[1].trim()
|
|
300
|
+
return known.has(title) ? title : ''
|
|
301
|
+
}
|
|
302
|
+
const bodyLines = (text) => (String(text ?? '') === '' ? [] : String(text).split('\n'))
|
|
303
|
+
let seenKnown = false
|
|
304
|
+
|
|
305
|
+
// 一行一行地过,而不是一节一节地过:
|
|
306
|
+
//
|
|
307
|
+
// `parseCard` 出来的小节是按「行首 `## `」切的,可它有两种场合会切错——
|
|
308
|
+
// 一是用户手打了一个没闭合的 ``` 围栏,后面所有 `## ` 都被当成代码吞进
|
|
309
|
+
// 上一节;二是用户自己写的一行 `## 医院里的事` 也被切成了一节。
|
|
310
|
+
// 前者要把被吞掉的节认回来,后者要把它留在正文里。所以这里重新过一遍
|
|
311
|
+
// 每一节的正文行:认得的标题一律另起一节,不认得的原样留在原地。
|
|
312
|
+
const feed = (lines) => {
|
|
313
|
+
for (const line of lines) {
|
|
314
|
+
const title = headingOf(line)
|
|
315
|
+
if (title !== '') {
|
|
316
|
+
seenKnown = true
|
|
317
|
+
startBlock(title, [])
|
|
318
|
+
continue
|
|
319
|
+
}
|
|
320
|
+
if (cur !== null) cur.lines.push(line)
|
|
321
|
+
else intro.push(line)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
for (const one of Array.isArray(sections) ? sections : []) {
|
|
326
|
+
const title = String(one?.title ?? '').trim()
|
|
327
|
+
const lines = bodyLines(one?.body)
|
|
328
|
+
if (title === '' || title === '_intro') {
|
|
329
|
+
feed(lines)
|
|
330
|
+
continue
|
|
331
|
+
}
|
|
332
|
+
if (known.has(title)) {
|
|
333
|
+
seenKnown = true
|
|
334
|
+
startBlock(title, [])
|
|
335
|
+
feed(lines)
|
|
336
|
+
continue
|
|
337
|
+
}
|
|
338
|
+
// 不认得的标题:用户自己写的小标题。原样并回当前这一节。
|
|
339
|
+
//
|
|
340
|
+
// 但一个认得的标题都还没出现时,它更可能是被围栏带出来的真小节
|
|
341
|
+
// (见上面),这时候单独算一节,否则后面几节整片消失。
|
|
342
|
+
if (!seenKnown) {
|
|
343
|
+
startBlock(title, [])
|
|
344
|
+
feed(lines)
|
|
345
|
+
continue
|
|
346
|
+
}
|
|
347
|
+
if (cur !== null && cur.lines.some((line) => line.trim() !== '')) push([''])
|
|
348
|
+
push([`## ${title}`])
|
|
349
|
+
feed(lines)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const byTitle = new Map()
|
|
353
|
+
for (const block of blocks) {
|
|
354
|
+
const text = block.lines.join('\n').replace(/^\n+|\n+$/g, '')
|
|
355
|
+
if (text === '') continue
|
|
356
|
+
// 同名小节(早上写一段、晚上又起一个同名标题)并成一段,不丢后一份。
|
|
357
|
+
byTitle.set(block.title, byTitle.has(block.title) ? `${byTitle.get(block.title)}\n\n${text}` : text)
|
|
358
|
+
}
|
|
359
|
+
return { intro: intro.join('\n').replace(/^\n+|\n+$/g, ''), byTitle }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** 一行打分:`健康 6`、`健康:6.5`、全角数字、负号,都认。 */
|
|
363
|
+
function parseScoreLine(line) {
|
|
364
|
+
const raw = String(line ?? '')
|
|
365
|
+
.trim()
|
|
366
|
+
.replace(/[0-9]/g, (c) => String(c.charCodeAt(0) - 0xff10))
|
|
367
|
+
.replace(/[-—–]/g, '-')
|
|
368
|
+
const m = /^(.+?)[\s::==]+(-?\d+(?:\.\d+)?)\s*$/.exec(raw)
|
|
369
|
+
if (m === null) return null
|
|
370
|
+
const value = Number(m[2])
|
|
371
|
+
if (!Number.isFinite(value)) return null
|
|
372
|
+
return { name: m[1].trim(), value: Math.max(0, Math.min(10, Math.round(value * 10) / 10)) }
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** 一行一条的小节:读的时候去掉记号、还原转义。与 career.js 同一套约定。 */
|
|
376
|
+
function parseList(body) {
|
|
377
|
+
const out = []
|
|
378
|
+
for (const raw of String(body ?? '').split(/\r?\n/)) {
|
|
379
|
+
let line = raw.trim()
|
|
380
|
+
if (line === '') continue
|
|
381
|
+
// `# 紧急` 这种用户手写的记号:以前整行被丢掉(「我写的怎么没了」)。
|
|
382
|
+
// 现在只剥掉记号本身,文字留下——一行一条的小节里,那也是他的一条。
|
|
383
|
+
line = line.replace(/^#{1,6}\s+/, '').trim()
|
|
384
|
+
line = line.replace(/^\s*(?:[-*+]|\d+\s*[.、).])\s*/, '').trim()
|
|
385
|
+
if (line !== '') out.push(unescapeItem(line))
|
|
386
|
+
}
|
|
387
|
+
return out
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** 写的时候:一条一行。内容里的换行记成 `\n` 两个字,读回再还原。 */
|
|
391
|
+
function renderList(value) {
|
|
392
|
+
const items = Array.isArray(value)
|
|
393
|
+
? value.map((v) => String(v ?? '').trim()).filter((v) => v !== '')
|
|
394
|
+
: String(value ?? '').split(/\r?\n/).map((s) => s.replace(/^\s*(?:[-*+]|\d+\s*[.、).])\s*/, '').trim()).filter((s) => s !== '')
|
|
395
|
+
return items
|
|
396
|
+
.map((item) => item.replace(/\\/g, '\\\\').replace(/\r\n|\r|\n/g, '\\n'))
|
|
397
|
+
.map((item) => `- ${item}`)
|
|
398
|
+
.join('\n')
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 还原 renderList 的转义。
|
|
403
|
+
*
|
|
404
|
+
* 必须逐字符走一遍:先 `\\` 后 `\n` 直接两次 replace 会把 `\\\\n` 解错,
|
|
405
|
+
* 而写一次翻一倍的反斜杠正是这么来的。
|
|
406
|
+
*/
|
|
407
|
+
function unescapeItem(text) {
|
|
408
|
+
const raw = String(text ?? '')
|
|
409
|
+
let out = ''
|
|
410
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
411
|
+
const ch = raw[i]
|
|
412
|
+
if (ch !== '\\') {
|
|
413
|
+
out += ch
|
|
414
|
+
continue
|
|
415
|
+
}
|
|
416
|
+
const next = raw[i + 1]
|
|
417
|
+
if (next === '\\') {
|
|
418
|
+
out += '\\'
|
|
419
|
+
i += 1
|
|
420
|
+
} else if (next === 'n') {
|
|
421
|
+
out += '\n'
|
|
422
|
+
i += 1
|
|
423
|
+
} else {
|
|
424
|
+
out += ch
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return out
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 同一篇日记的写操作排队走:两次点击、两个窗口,不会后写的把先写的整篇盖掉。 */
|
|
431
|
+
const locks = new Map()
|
|
432
|
+
|
|
433
|
+
function withLock(key, run) {
|
|
434
|
+
const prev = locks.get(key) ?? Promise.resolve()
|
|
435
|
+
const next = prev.then(run, run)
|
|
436
|
+
const tail = next.then(() => {}, () => {})
|
|
437
|
+
locks.set(key, tail)
|
|
438
|
+
tail.then(() => {
|
|
439
|
+
// 队列排空了就把这一格删掉,不然写过多少天就攒多少个 Promise。
|
|
440
|
+
if (locks.get(key) === tail) locks.delete(key)
|
|
441
|
+
})
|
|
442
|
+
return next
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* 读这一天的日记。没有是正常状态(今天还没写),不报错。
|
|
447
|
+
*
|
|
448
|
+
* @param {string} dir 用户指定的日记文件夹
|
|
449
|
+
* @param {string} date YYYY-MM-DD
|
|
450
|
+
*/
|
|
451
|
+
export async function readDiary(dir, date) {
|
|
452
|
+
const name = dateFileName(date)
|
|
453
|
+
if (name === '') return { ok: false, error: '日子不对,日记只认 年-月-日 这种写法。' }
|
|
454
|
+
if (String(dir ?? '').trim() === '') return { ok: true, data: null, missing: true }
|
|
455
|
+
const found = await findDiaryFile(dir, date)
|
|
456
|
+
if (found.ok !== true) return found
|
|
457
|
+
const name2 = found.name
|
|
458
|
+
const got = found.raw
|
|
459
|
+
if (got.kind === 'none') return { ok: true, data: null, missing: true, path: name }
|
|
460
|
+
if (got.kind === 'link') return { ok: false, error: '这一天不是一篇日记,是个快捷方式。为了不读到别处去,这次不读了。' }
|
|
461
|
+
if (got.kind === 'error') return { ok: false, error: got.error }
|
|
462
|
+
const parsed = parseDiaryText(got.text)
|
|
463
|
+
if (parsed.ok !== true) return parsed
|
|
464
|
+
// 手上这份「认不出来的部分」(自加的 frontmatter 键、自己加的小节、
|
|
465
|
+
// 认不出的打分行、开头那段)一路带出去:写回去的时候要原样带着走。
|
|
466
|
+
return {
|
|
467
|
+
ok: true,
|
|
468
|
+
path: name2,
|
|
469
|
+
text: got.text,
|
|
470
|
+
data: parsed.data,
|
|
471
|
+
sections: parsed.sections,
|
|
472
|
+
headExtras: parsed.headExtras,
|
|
473
|
+
extraSections: parsed.extraSections,
|
|
474
|
+
scoreLines: parsed.scoreLines,
|
|
475
|
+
intro: parsed.intro,
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** 把一个文件原样读回来,顺便把「没有 / 读不出来 / 是个快捷方式」分清楚。 */
|
|
480
|
+
async function readRaw(abs) {
|
|
481
|
+
let st
|
|
482
|
+
try {
|
|
483
|
+
st = await fs.lstat(abs)
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (error?.code === 'ENOENT') return { kind: 'none' }
|
|
486
|
+
return { kind: 'error', error: '这一篇日记读不出来。检查一下那个文件夹的权限。' }
|
|
487
|
+
}
|
|
488
|
+
if (st.isSymbolicLink()) return { kind: 'link' }
|
|
489
|
+
if (!st.isFile()) return { kind: 'error', error: '这一天不是一篇日记,是个文件夹。' }
|
|
490
|
+
try {
|
|
491
|
+
const text = await fs.readFile(abs, 'utf8')
|
|
492
|
+
return { kind: 'text', text, mode: st.mode & 0o777 }
|
|
493
|
+
} catch {
|
|
494
|
+
return { kind: 'error', error: '这一篇日记读不出来。检查一下那个文件夹的权限。' }
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/**
|
|
499
|
+
* 写这一天的日记。
|
|
500
|
+
*
|
|
501
|
+
* 先写临时文件再改名:改名是一次替换,掉电或写满时要么还是旧的完整版、
|
|
502
|
+
* 要么已经是新的完整版,不会留下半篇。
|
|
503
|
+
*
|
|
504
|
+
* 写之前的六道关(全都下沉在这一层,HTTP 路由绕不过去):
|
|
505
|
+
* 1. 旧文件读不出来 → 一个字都不写。
|
|
506
|
+
* 2. 调用方读过旧内容就传 `expect: { text }`;对不上说明外面改过 → 不写。
|
|
507
|
+
* 3. 能读到旧内容 → 先留个底(`.lifecard/旧版本/<日期>/`)。
|
|
508
|
+
* 4. 用户自己加的 frontmatter 键、自己加的小节、第一个标题前那段话,原样带着走。
|
|
509
|
+
* 5. 没提到的节沿用旧值(`merge: false` 才允许真的清空,那要用户点过头)。
|
|
510
|
+
* 6. 权限跟原来一样(新文件 600);同一篇的写操作排队走。
|
|
511
|
+
*
|
|
512
|
+
* @param {string} dir 用户指定的日记文件夹
|
|
513
|
+
* @param {object} data 要写的内容(五节 + scores/mood 任意子集)
|
|
514
|
+
* @param {Date} now
|
|
515
|
+
* @param {{expect?: {text?: string, mtimeMs?: number}, merge?: boolean}} options
|
|
516
|
+
*/
|
|
517
|
+
export async function writeDiary(dir, data, now = new Date(), options = {}) {
|
|
518
|
+
const input = data !== null && typeof data === 'object' && !Array.isArray(data) ? data : {}
|
|
519
|
+
const date = dateFileName(input.date) === '' ? localDate(now) : String(input.date)
|
|
520
|
+
const name = dateFileName(date)
|
|
521
|
+
if (name === '') return { ok: false, error: '日子不对,日记只认 年-月-日 这种写法。' }
|
|
522
|
+
if (String(dir ?? '').trim() === '') return { ok: false, error: '还没定日记放在哪个文件夹。' }
|
|
523
|
+
const abs = path.join(dir, name)
|
|
524
|
+
// 锁要按「这一天」锁,不能按这里猜出来的标准名:用户可能已经把这一天
|
|
525
|
+
// 改名成「2026-10-30 周五.md」了,那写进去的也是那个文件。
|
|
526
|
+
const found = await findDiaryFile(dir, date)
|
|
527
|
+
if (found.ok !== true) return found
|
|
528
|
+
return withLock(found.abs, async () => {
|
|
529
|
+
const abs = found.abs
|
|
530
|
+
const old = await readRaw(abs)
|
|
531
|
+
if (old.kind === 'error') return { ok: false, error: `为了不覆盖掉原来那一篇,这次没存:${old.error}` }
|
|
532
|
+
if (old.kind === 'link') return { ok: false, error: '这一天是个快捷方式,不往里写。' }
|
|
533
|
+
|
|
534
|
+
const merged = { ...input, date }
|
|
535
|
+
let renderOptions = {}
|
|
536
|
+
let snapshot = ''
|
|
537
|
+
const existed = old.kind === 'text'
|
|
538
|
+
// 调用方读过之后才写:它看见的是什么样,磁盘上就得还是什么样。
|
|
539
|
+
// 两种对不上都算「被别处改过」——
|
|
540
|
+
// ①它读到了内容,现在内容变了;
|
|
541
|
+
// ②它读到「这天还没有」,现在却有了(两个人同时开始写全新的一天)。
|
|
542
|
+
// 第二种以前是漏的:两边都读到「没有」,后一份把前一份整篇顶掉,
|
|
543
|
+
// 前一份只剩在隐藏的旧版本目录里,界面上根本看不到。
|
|
544
|
+
const expect = options?.expect
|
|
545
|
+
if (expect !== null && typeof expect === 'object') {
|
|
546
|
+
const wantText = expect.text
|
|
547
|
+
const moved = typeof wantText === 'string' ? (existed ? wantText !== old.text : true) : (wantText === null || wantText === undefined ? existed : false)
|
|
548
|
+
if (moved) {
|
|
549
|
+
return {
|
|
550
|
+
ok: false,
|
|
551
|
+
conflict: true,
|
|
552
|
+
error: '这一天在别的地方又改过了。为了不把你外面改的东西盖掉,这次没存——重新打开这一篇再写一遍就行。',
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (existed) {
|
|
557
|
+
const back = parseDiaryText(old.text)
|
|
558
|
+
if (back.ok !== true) {
|
|
559
|
+
return { ok: false, error: `这一天原来那一篇读不出来(${back.error}),为了不覆盖掉它,这次没存。` }
|
|
560
|
+
}
|
|
561
|
+
renderOptions = {
|
|
562
|
+
headExtras: back.headExtras,
|
|
563
|
+
extraSections: back.extraSections,
|
|
564
|
+
scoreLines: back.scoreLines,
|
|
565
|
+
intro: back.intro,
|
|
566
|
+
}
|
|
567
|
+
if (options?.merge !== false) {
|
|
568
|
+
for (const title of DIARY_SECTIONS) {
|
|
569
|
+
const value = merged[title]
|
|
570
|
+
const empty = Array.isArray(value) ? value.length === 0 : String(value ?? '').trim() === ''
|
|
571
|
+
if (empty) merged[title] = back.data[title]
|
|
572
|
+
}
|
|
573
|
+
const hasScores = merged.scores !== null && typeof merged.scores === 'object' && Object.keys(merged.scores ?? {}).length > 0
|
|
574
|
+
if (!hasScores) merged.scores = back.data.scores
|
|
575
|
+
if (String(merged.mood ?? '').trim() === '') merged.mood = back.data.mood ?? ''
|
|
576
|
+
}
|
|
577
|
+
snapshot = await saveSnapshot(dir, date, old.text)
|
|
578
|
+
if (snapshot === '') {
|
|
579
|
+
return { ok: false, error: '这一篇原来的内容没能留个底,为了安全这次先不存。' }
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
const text = renderDiaryMarkdown(merged, renderOptions)
|
|
584
|
+
const tmp = `${abs}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
585
|
+
try {
|
|
586
|
+
// 只有「这一天还没写过」才建文件夹。已有那一篇在的时候不建:
|
|
587
|
+
// 用户可能刚把整个日记文件夹改名挪走了,这时候重建一个空壳出来,
|
|
588
|
+
// 会把他的日记分成互不相见的两处。
|
|
589
|
+
if (!existed) await fs.mkdir(dir, { recursive: true })
|
|
590
|
+
await fs.writeFile(tmp, text, { encoding: 'utf8', mode: 0o600 })
|
|
591
|
+
await fs.rename(tmp, abs)
|
|
592
|
+
// 老文件原来是 600 就还是 600;原来是别的(用户自己改过)也照旧。
|
|
593
|
+
if (existed && Number.isInteger(old.mode) && old.mode !== 0o600) await fs.chmod(abs, old.mode).catch(() => {})
|
|
594
|
+
} catch {
|
|
595
|
+
await fs.rm(tmp, { force: true }).catch(() => {})
|
|
596
|
+
return { ok: false, error: '这一篇没能存下来。检查一下磁盘是不是满了。' }
|
|
597
|
+
}
|
|
598
|
+
return {
|
|
599
|
+
ok: true,
|
|
600
|
+
path: path.basename(abs),
|
|
601
|
+
chars: text.length,
|
|
602
|
+
text,
|
|
603
|
+
data: { ...merged, date },
|
|
604
|
+
mode: existed ? 'updated' : 'created',
|
|
605
|
+
snapshot,
|
|
606
|
+
}
|
|
607
|
+
})
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** 覆盖之前把旧的整篇留个底。留不下来就返回空串,调用方据此拒绝写入。 */
|
|
611
|
+
async function saveSnapshot(dir, date, text) {
|
|
612
|
+
const day = dateFileName(date)
|
|
613
|
+
if (day === '') return ''
|
|
614
|
+
const folder = path.join(dir, SNAPSHOT_DIR, SNAPSHOT_SUB, day.slice(0, -3))
|
|
615
|
+
const stamp = `${new Date().toISOString().replace(/[:.]/g, '-')}-${Math.random().toString(36).slice(2, 6)}`
|
|
616
|
+
const abs = path.join(folder, `${stamp}.md`)
|
|
617
|
+
try {
|
|
618
|
+
await fs.mkdir(folder, { recursive: true })
|
|
619
|
+
await fs.writeFile(abs, String(text ?? ''), { encoding: 'utf8', mode: 0o600 })
|
|
620
|
+
return abs
|
|
621
|
+
} catch {
|
|
622
|
+
return ''
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* 这一篇有多少字。
|
|
628
|
+
*
|
|
629
|
+
* 不能用 `st.size`:那是字节数,一个汉字占三个字节,界面上会显示成三倍。
|
|
630
|
+
* 读不出来就退回字节数——数字不准好过没有。
|
|
631
|
+
*/
|
|
632
|
+
async function countChars(abs, size) {
|
|
633
|
+
try {
|
|
634
|
+
const text = await fs.readFile(abs, 'utf8')
|
|
635
|
+
return text.length
|
|
636
|
+
} catch {
|
|
637
|
+
return Number.isFinite(Number(size)) ? Number(size) : 0
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* 列出写过哪些天(新的在前)。
|
|
643
|
+
*
|
|
644
|
+
* 只认 `YYYY-MM-DD.md`,别的文件一概不看:用户会把这个文件夹拿去同步、
|
|
645
|
+
* 放别的笔记、放图片,多认一个就是多一份「看起来像日记其实不是」的东西。
|
|
646
|
+
* 快捷方式也不算——它指向的地方可能根本不在这个文件夹里。
|
|
647
|
+
*
|
|
648
|
+
* `total` 是实际有多少天,`diaries` 只按 `limit` 切一刀:
|
|
649
|
+
* 「写过多少天」不该被列表长度顶死。
|
|
650
|
+
*/
|
|
651
|
+
export async function listDiaries(dir, options = {}) {
|
|
652
|
+
if (String(dir ?? '').trim() === '') return { ok: true, diaries: [], total: 0, missing: true }
|
|
653
|
+
const limit = Number.isFinite(Number(options.limit)) && Number(options.limit) > 0 ? Math.floor(Number(options.limit)) : 400
|
|
654
|
+
let names
|
|
655
|
+
try {
|
|
656
|
+
names = await fs.readdir(dir)
|
|
657
|
+
} catch (error) {
|
|
658
|
+
if (error?.code === 'ENOENT') return { ok: true, diaries: [], total: 0, missing: true }
|
|
659
|
+
return { ok: false, error: '那个日记文件夹读不出来。检查一下权限。' }
|
|
660
|
+
}
|
|
661
|
+
const diaries = []
|
|
662
|
+
for (const name of names) {
|
|
663
|
+
// 放宽一档:用户在访达里把「2026-10-30.md」改成「2026-10-30 周五.md」、
|
|
664
|
+
// 或者后缀变成 .MD,那不是「这一天没写」,是他给这一天起了个名字。
|
|
665
|
+
// 严格只认标准名的结果是这些日记整篇看不见,再存一次还会另建一个文件。
|
|
666
|
+
const date = looseDateOf(name)
|
|
667
|
+
if (date === '') continue
|
|
668
|
+
const abs = path.join(dir, name)
|
|
669
|
+
let st
|
|
670
|
+
try {
|
|
671
|
+
st = await fs.lstat(abs)
|
|
672
|
+
} catch {
|
|
673
|
+
continue
|
|
674
|
+
}
|
|
675
|
+
if (st.isSymbolicLink() || !st.isFile()) continue
|
|
676
|
+
diaries.push({ date, file: name, chars: await countChars(abs, st.size), mtime: st.mtime.toISOString() })
|
|
677
|
+
}
|
|
678
|
+
diaries.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0))
|
|
679
|
+
return { ok: true, diaries: diaries.slice(0, limit), total: diaries.length }
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// ── 让模型干活的那几段话 ────────────────────────────────────────
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* 上次写到哪儿:给模型一句「接得上」的话,而不是每天从零开始。
|
|
686
|
+
*
|
|
687
|
+
* 第二个参数两种形状都收:一张「日期 → 正文」的表,或者一组
|
|
688
|
+
* `{date, data}`(路由那边读回来的样子)。收错形状时它会把内容悄悄
|
|
689
|
+
* 丢成「这一篇是空的」——模型于是每天从零开始问,人会觉得它不记事。
|
|
690
|
+
*/
|
|
691
|
+
export function recentBlock(diaries, texts) {
|
|
692
|
+
const list = Array.isArray(diaries) ? diaries : []
|
|
693
|
+
const picked = list.slice(0, 3)
|
|
694
|
+
if (picked.length === 0) return '(还没写过日记,这是第一篇。)'
|
|
695
|
+
const rows = Array.isArray(texts) ? texts : null
|
|
696
|
+
const map = rows === null && texts !== null && typeof texts === 'object' ? texts : {}
|
|
697
|
+
const bodyOf = (date) => {
|
|
698
|
+
if (rows !== null) {
|
|
699
|
+
const hit = rows.find((one) => String(one?.date ?? '') === date)
|
|
700
|
+
if (hit === undefined) return ''
|
|
701
|
+
const data = hit.data
|
|
702
|
+
return data !== null && typeof data === 'object'
|
|
703
|
+
? diaryBlock(data, { intro: hit.intro, extraSections: hit.extraSections })
|
|
704
|
+
: String(data ?? '').trim()
|
|
705
|
+
}
|
|
706
|
+
const value = map[date]
|
|
707
|
+
return value !== null && typeof value === 'object' ? diaryBlock(value) : String(value ?? '').trim()
|
|
708
|
+
}
|
|
709
|
+
return picked
|
|
710
|
+
.map((one) => {
|
|
711
|
+
const date = String(one?.date ?? one).trim()
|
|
712
|
+
const body = bodyOf(date)
|
|
713
|
+
if (body === '') return `【${date}】(这一篇是空的)`
|
|
714
|
+
return `【${date}】\n${body}`
|
|
715
|
+
})
|
|
716
|
+
.join('\n\n')
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* 日记助手说的第一段话。
|
|
721
|
+
*
|
|
722
|
+
* 定了三件事:它是什么(不是心理咨询、不是打卡)、它怎么问(一次只问一件事、
|
|
723
|
+
* 不许一次抛五个问题)、它什么时候收(用户说够了就收,不追着写满)。
|
|
724
|
+
*/
|
|
725
|
+
export function buildDiarySystem({ cardName, persona, memory, preset, scores } = {}) {
|
|
726
|
+
const lines = []
|
|
727
|
+
const name = String(cardName ?? '').trim()
|
|
728
|
+
lines.push(
|
|
729
|
+
name === ''
|
|
730
|
+
? '你在陪这个人写今天的日记。'
|
|
731
|
+
: `你在陪这个人写今天的日记。你就是「${name}」这个人——按他/她的性子说话,别跳出去当主持人。`,
|
|
732
|
+
)
|
|
733
|
+
const body = String(persona ?? '').trim()
|
|
734
|
+
if (body !== '') lines.push('', '# 你怎么说话', body)
|
|
735
|
+
lines.push(
|
|
736
|
+
'',
|
|
737
|
+
'# 怎么带这一篇',
|
|
738
|
+
'一次只问一件事。问完等他答,别一口气抛五个问题——那不是在陪人说话,是在发问卷。',
|
|
739
|
+
'先问「今天哪件事最值得讲」,让他讲那件事,不是你替他总结这一天。',
|
|
740
|
+
'他讲完一件事,再往下问一层:当时你心里在想什么?这件事最让你不舒服的是哪一点?',
|
|
741
|
+
'情绪问到第三层就够了,别再往下挖。第三层之后人开始防御,问不出来真东西。',
|
|
742
|
+
'如果他说做了一个决定,问一句「那你打算下一步做什么」,把行动落到具体的一件事上。',
|
|
743
|
+
'不评价他的生活,不替他下判断,不把「你应该」挂在嘴边。要说也是「如果你是这么想的,那另一条路是……」这种把选择权留在他手里的说法。',
|
|
744
|
+
'不写他的日记。你只负责问,字是他自己写的;他要你整理,你才整理,而且整理完要让他看一眼。',
|
|
745
|
+
'他不想讲的那件事,就换一件。日记是给自己看的,不是交代材料。',
|
|
746
|
+
)
|
|
747
|
+
const scoreList = String(scores ?? '').trim()
|
|
748
|
+
if (scoreList !== '') lines.push('', '# 上次的四样打分', scoreList)
|
|
749
|
+
const mem = String(memory ?? '').trim()
|
|
750
|
+
if (mem !== '') lines.push('', '# 之前写到哪儿', mem)
|
|
751
|
+
const mode = String(preset ?? '').trim()
|
|
752
|
+
if (mode !== '') lines.push('', `(现在用的是「${mode}」这套问法。)`)
|
|
753
|
+
return lines.join('\n')
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/**
|
|
757
|
+
* 这一段里给模型看的东西:这一天已经写了什么 + 最近几天的尾巴。
|
|
758
|
+
*
|
|
759
|
+
* 有东西就接着写,没东西就从「今天哪件事最值得讲」开始。
|
|
760
|
+
*/
|
|
761
|
+
export function buildDiaryUser({ today, draft, recent } = {}) {
|
|
762
|
+
const date = String(today ?? '').trim() === '' ? localDate() : String(today)
|
|
763
|
+
const lines = [`今天是 ${date}。`]
|
|
764
|
+
const body = String(draft ?? '').trim()
|
|
765
|
+
if (body === '') {
|
|
766
|
+
lines.push('今天还一个字没写。')
|
|
767
|
+
} else {
|
|
768
|
+
lines.push('', '# 今天已经写下的', body)
|
|
769
|
+
lines.push('', '这些是今天已经写进这一篇的。接着往下问,别把已经写过的重问一遍。')
|
|
770
|
+
}
|
|
771
|
+
const tail = String(recent ?? '').trim()
|
|
772
|
+
if (tail !== '') lines.push('', '# 前几天写到哪儿', tail)
|
|
773
|
+
lines.push('', '先开口问一句,别一次问好几个。')
|
|
774
|
+
return lines.join('\n')
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** 一天结束时,把这一篇整理成「能对得上卡的几条」。不写卡,只给候选。 */
|
|
778
|
+
export function buildDigestPrompt({ date, text }) {
|
|
779
|
+
const system = [
|
|
780
|
+
'你在把一篇日记整理成关于这个人的几条事实。',
|
|
781
|
+
'只写日记里真的发生过、真的说过的。没写的不要推,推测的东西一律不要。',
|
|
782
|
+
'每条一句话,不超过 40 字,写具体的事,不写评价(「他这个人很努力」这种不要)。',
|
|
783
|
+
'每条后面用括号标一句日记里的原话,作为依据。',
|
|
784
|
+
'最多 8 条。宁可少,不要凑。',
|
|
785
|
+
].join('\n')
|
|
786
|
+
const user = [`日期:${String(date ?? '').trim()}`, '', '# 日记原文', String(text ?? '').trim()].join('\n')
|
|
787
|
+
return { system, user }
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* 把整份日记排成模型看的样子:只给有内容的小节。
|
|
792
|
+
*
|
|
793
|
+
* 第二个参数可以带上「文件里还有、但不在五节里」的东西(`intro` 和
|
|
794
|
+
* `extraSections`)。不带的话,用户写在开头那段话、自己加的那几节,
|
|
795
|
+
* 模型一个字都看不见——他接着写的时候会把它当空白,人会觉得它没读。
|
|
796
|
+
*/
|
|
797
|
+
export function diaryBlock(data, options = {}) {
|
|
798
|
+
const d = data !== null && typeof data === 'object' ? data : {}
|
|
799
|
+
const lines = []
|
|
800
|
+
const intro = String(options?.intro ?? '').trim()
|
|
801
|
+
if (intro !== '') lines.push('【开头那段】', intro, '')
|
|
802
|
+
for (const title of DIARY_SECTIONS) {
|
|
803
|
+
const value = d[title]
|
|
804
|
+
const body = DIARY_LIST_SECTIONS.includes(title)
|
|
805
|
+
? (Array.isArray(value) ? value.map((v) => `- ${v}`).join('\n') : String(value ?? '').trim())
|
|
806
|
+
: String(value ?? '').trim()
|
|
807
|
+
if (body !== '') lines.push(`【${title}】`, body, '')
|
|
808
|
+
}
|
|
809
|
+
const scores = d.scores !== null && typeof d.scores === 'object' ? d.scores : {}
|
|
810
|
+
const scoreLine = DIMENSIONS.filter((name) => scores[name] !== undefined).map((name) => `${name} ${scores[name]}`).join(' / ')
|
|
811
|
+
if (scoreLine !== '') lines.push(`【今天这四样】${scoreLine}`)
|
|
812
|
+
for (const one of Array.isArray(options?.extraSections) ? options.extraSections : []) {
|
|
813
|
+
const title = String(one?.title ?? '').trim()
|
|
814
|
+
const body = String(one?.body ?? '').trim()
|
|
815
|
+
if (title === '' || body === '') continue
|
|
816
|
+
lines.push(`【${title}】`, body, '')
|
|
817
|
+
}
|
|
818
|
+
return lines.length === 0 ? '(这一篇还是空的)' : lines.join('\n').trimEnd()
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
export default {
|
|
822
|
+
DIARY_SECTIONS,
|
|
823
|
+
DIARY_LIST_SECTIONS,
|
|
824
|
+
DIMENSIONS,
|
|
825
|
+
dateFileName,
|
|
826
|
+
diaryFileName,
|
|
827
|
+
diaryRootFrom,
|
|
828
|
+
renderDiaryMarkdown,
|
|
829
|
+
parseDiaryText,
|
|
830
|
+
readDiary,
|
|
831
|
+
writeDiary,
|
|
832
|
+
listDiaries,
|
|
833
|
+
recentBlock,
|
|
834
|
+
buildDiarySystem,
|
|
835
|
+
buildDiaryUser,
|
|
836
|
+
buildDigestPrompt,
|
|
837
|
+
diaryBlock,
|
|
838
|
+
}
|