dsh-agent-soul 0.2.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/diary.js ADDED
@@ -0,0 +1,1265 @@
1
+ /**
2
+ * diary.js —— 智能体日记:每天到点触发,让 agent 自己写公开 + 私密日记。
3
+ *
4
+ * 核心流程:
5
+ * ① tick() 每轮注入时,扫描新事件追加到当天 JSONL(collectForDiary)
6
+ * ② 定时器到点(默认 22:00)触发 runDiaryOnce:
7
+ * 读 JSONL → LLM 摘要 → 读最近 4 天日记 → 投第一条消息(公开)→ agent 写完
8
+ * → 投第二条消息(私密)
9
+ * ③ 日记会话是【绑定】来的(2026-10-31):设置页把当前会话 id 写进
10
+ * config.diarySessionId,投递只认这个会话。自己 agents.create 造出来的会话
11
+ * 拿不到宿主的 setup/installSelection,没有标准工具集,agent 永远写不出文件。
12
+ * ④ agent 收到消息后自己用文件工具写 public/YYYY-MM-DD.md + private/YYYY-MM-DD.md
13
+ * 两篇分两条消息投:写在同一条里的话,私密历史就摆在下面,她写公开那一步时
14
+ * 已经看到了本不该给人看的内容。
15
+ * ⑤ 启动时 catch_up:找最近缺失日,只补那一天
16
+ *
17
+ * 设计参考:
18
+ * - 对话扫描:extract.js 的 cursor + snapshotEvents 模式(独立游标,不干扰记忆提取)
19
+ * - LLM 调用:mood.js 的 judgeMood 模式(流式 + 超时 + 兜底)
20
+ * - 定时器:dsh-onebot-channel proactive.js 的 setTimeout 自调度模式
21
+ * - 消息投递:dsh-onebot-channel deliver.js 的 agent.followup 模式
22
+ *
23
+ * ── 一天的分界线 ──
24
+ * 不是自然日 00:00,而是 schedule 时间(默认 22:00)。
25
+ * 日记「2026-10-29」覆盖:2026-10-28 22:00 ~ 2026-10-29 22:00。
26
+ * JSONL 按自然日命名,触发时读两天文件再按分界线裁剪。
27
+ *
28
+ * ── 触发消息的 source ──
29
+ * 用 { kind: 'schedule' },这样 extract.js 会跳过它(不进记忆),
30
+ * mood.js 也跳过(不影响心情),日记扫描自己也跳过(不进 JSONL)。
31
+ * agent 仍正常处理这条消息。
32
+ */
33
+ import { appendFileSync, readdirSync, statSync, unlinkSync } from 'node:fs'
34
+ import { randomUUID } from 'node:crypto'
35
+ import { join } from 'node:path'
36
+ import { note, serviceOf } from './env.js'
37
+ import {
38
+ diaryConversationsDir,
39
+ diaryJsonlPath,
40
+ diaryPublicPath,
41
+ diaryPrivatePath,
42
+ diaryPrivateDir,
43
+ diaryDir,
44
+ readText,
45
+ exists,
46
+ ensureDirs,
47
+ // 2026-10-31:writeDiaryFile 要用它落盘。第一次跑就因为漏了这个 import
48
+ // 报 "atomicWrite is not defined" —— 生成都成功了,死在最后一步。
49
+ atomicWrite
50
+ } from './paths.js'
51
+ import { allMoodStates, loadConfig } from './store.js'
52
+ import {
53
+ eventsSince,
54
+ maxSeqOf,
55
+ isHumanEvent,
56
+ textOfContent,
57
+ messageContentOf,
58
+ unwrapBridgeText
59
+ } from './extract.js'
60
+ import { moodDigest, renderMoodDigest, sessionModelOf } from './mood.js'
61
+
62
+ // --------------------------------------------------------------------------
63
+ // 时间工具
64
+ // --------------------------------------------------------------------------
65
+
66
+ /** 本地日期键 YYYY-MM-DD。 */
67
+ export function todayKey(at = Date.now()) {
68
+ const d = new Date(Number(at) || Date.now())
69
+ const pad = (n) => String(n).padStart(2, '0')
70
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
71
+ }
72
+
73
+ /**
74
+ * 昨天的日期键。
75
+ *
76
+ * 2026-10-31:日记改成「第二天写前一天的」。当天写只写得到半天,
77
+ * 隔一天写,昨天的 00:00–24:00 窗口已经完整闭合。
78
+ * 用 setDate 减一天,跨月、跨年由 Date 自己处理,不用手算。
79
+ */
80
+ export function yesterdayKey(at = Date.now()) {
81
+ const d = new Date(Number(at) || Date.now())
82
+ d.setDate(d.getDate() - 1)
83
+ return todayKey(d.getTime())
84
+ }
85
+
86
+ /** 把 'YYYY-MM-DD' 解析成本地零点的 Date(不用 new Date(str) 避免 UTC 歧义)。 */
87
+ export function parseDateLocal(dateStr) {
88
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateStr ?? '').trim())
89
+ if (m === null) return new Date(NaN)
90
+ return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 0, 0, 0, 0)
91
+ }
92
+
93
+ /** 'HH:MM' → 当日分钟数;格式不对回退默认值。 */
94
+ export function scheduleMinutes(hhmm, fallback = 22 * 60) {
95
+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(hhmm ?? '').trim())
96
+ if (m === null) return fallback
97
+ const h = Number(m[1])
98
+ const mi = Number(m[2])
99
+ if (!Number.isFinite(h) || !Number.isFinite(mi) || h > 24 || mi > 59) return fallback
100
+ return (h % 24) * 60 + mi
101
+ }
102
+
103
+ /**
104
+ * 日记日的边界(2026-10-31 改:自然日)。
105
+ *
106
+ * 日记「2026-10-31」= 2026-10-31 00:00 ~ 2026-11-01 00:00。
107
+ *
108
+ * 原来按 schedule 分界(默认 22:00),覆盖的是「前一天 22:00 ~ 当天 22:00」。
109
+ * 那是给「当晚十点写日记」设计的:晚上十点时「今天」在感受上还没结束。
110
+ * 但现在已经改成「第二天写前一天」,那个理由不成立了 —— 隔一天再写,
111
+ * 昨天一整天已经完整闭合,用自然日最直观:写的是哪一天,就是哪一天。
112
+ *
113
+ * ⚠️ 注意不能靠「把 scheduleMin 传 0」来实现自然日:
114
+ * 旧公式是 `dayStart - 24h + sm`,传 0 会算成「前一天 00:00 ~ 当天 00:00」,
115
+ * 也就是写成了前一天的日记。这里直接把公式改成自然日,参数只为兼容保留。
116
+ *
117
+ * @param {string} dateStr 'YYYY-MM-DD'
118
+ * @returns {{start: number, end: number}} 毫秒时间戳,左闭右开
119
+ */
120
+ export function diaryDayBoundaries(dateStr, _scheduleMin) {
121
+ const dayStart = parseDateLocal(dateStr).getTime()
122
+ if (Number.isNaN(dayStart)) return { start: 0, end: 0 }
123
+ return { start: dayStart, end: dayStart + 24 * 60 * 60 * 1000 }
124
+ }
125
+
126
+ // --------------------------------------------------------------------------
127
+ // 对话扫描(独立游标,不干扰 extract.js 的记忆提取游标)
128
+ // --------------------------------------------------------------------------
129
+
130
+ const diaryCursors = new Map()
131
+ const DIARY_CURSOR_MAX = 200
132
+
133
+ /** 每条 JSONL 的最大正文长度(跟 extract.js 的 MAX_CHARS 一致)。 */
134
+ const MAX_ENTRY_CHARS = 600
135
+
136
+ /**
137
+ * 助手消息的正文:**只取 text 块**,不要思考过程。
138
+ *
139
+ * 为什么不能复用 mood.js 的 fullTextOf:它在没有 text 块时会回退返回 reasoning
140
+ * 全文(`if (thinking.length) return thinking.join(' ')`)。实测一个活跃会话的
141
+ * 286 条 assistant/message 里,只有 29 条是真正在说话,257 条(90%)是思考过程;
142
+ * 经 fullTextOf 后 49.5 万字里有 46.2 万字(93%)来自思考过程。
143
+ * 后果是日记的「对话流水」几乎全是她的内心独白(还多是英文盘算),
144
+ * 摘要基于独白而非对话,而且体积会撑爆单次 LLM 调用。
145
+ *
146
+ * 日记要记的是她说出口的话。思考过程是过程,不是内容。
147
+ */
148
+ function assistantTextOf(holder) {
149
+ // 助手消息的正文在 data.message.content(有 message 这一层),跟 user 的 data.content 不同
150
+ const content = holder?.message?.content ?? holder?.content
151
+ if (typeof content === 'string') return content.trim()
152
+ if (!Array.isArray(content)) return ''
153
+ const parts = []
154
+ for (const block of content) {
155
+ // 只认 type === 'text':reasoning(思考)和 tool-call(工具调用)都不进日记
156
+ if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
157
+ }
158
+ return parts.join(' ').trim()
159
+ }
160
+
161
+ /**
162
+ * 扫描新事件,把 user/message + assistant/message 追加到当天 JSONL。
163
+ *
164
+ * 跟 extract.js 的 collectCandidates 同款游标机制,但:
165
+ * ① 同时收 assistant/message(日记需要看到双方对话)
166
+ * ② 收所有真人 user/message(不做 worthRemembering 过滤 —— 日记需要完整流水)
167
+ * ③ 游标独立,不干扰记忆提取
168
+ *
169
+ * @returns {{ scanned: number, appended: number }}
170
+ */
171
+ export function collectForDiary(agent) {
172
+ if (diaryCursors.size > DIARY_CURSOR_MAX) diaryCursors.clear()
173
+
174
+ const sessionId = String(agent?.session?.header?.id ?? agent?.session?.id ?? '')
175
+ const key = sessionId !== '' ? sessionId : 'default'
176
+
177
+ let from = diaryCursors.get(key)
178
+ if (from === undefined) {
179
+ // 第一次见这个会话:把游标推到当前位置的下一个,只往后看。
180
+ // 不用 maxSeqOf(agent) 本身:eventsSince 用 seq >= from(闭区间),
181
+ // 存 maxSeq 会在下一轮把最后那条再扫一遍。+1 才是「下一个还没扫的」。
182
+ // 不回扫历史 —— 会话可能有几千条旧事件,一上来全扫会把 JSONL 灌满。
183
+ from = maxSeqOf(agent) + 1
184
+ diaryCursors.set(key, from)
185
+ return { scanned: 0, appended: 0 }
186
+ }
187
+
188
+ const events = eventsSince(agent, from)
189
+ if (events.length === 0) return { scanned: 0, appended: 0 }
190
+
191
+ const to = events.reduce((max, event) => Math.max(max, Number(event?.seq) || 0), 0)
192
+ // 游标记「下一个还没扫的 seq」,不是「最后一个扫过的」—— 否则会重复扫最后一条。
193
+ diaryCursors.set(key, to + 1)
194
+
195
+ let appended = 0
196
+ for (const event of events) {
197
+ const type = event?.type ?? event?.kind
198
+ if (type !== 'user/message' && type !== 'assistant/message') continue
199
+
200
+ // user/message:跳过宿主注入的上下文(runtime-context / schedule 等)
201
+ // —— 复用 extract.js 的 isHumanEvent,保证和记忆提取的过滤口径一致。
202
+ if (type === 'user/message' && !isHumanEvent(event)) continue
203
+
204
+ const holder = event?.payload !== undefined ? event.payload : event?.data
205
+ if (holder === undefined || holder === null) continue
206
+
207
+ // 取正文:user 用 textOfContent(跟 extract.js 一致);
208
+ // assistant 用 assistantTextOf(只取 text 块,不回退思考过程)
209
+ let text = ''
210
+ if (type === 'user/message') {
211
+ // 跟记忆提取同一套清洗:剥掉桥接信封(「(QQ 私聊·用户本人…)」),
212
+ // 丢掉主动搭话/定时任务的触发模板 —— 否则日记摘要里会混进"距上次说话已经 X 小时"。
213
+ const unwrapped = unwrapBridgeText(textOfContent(messageContentOf(event)))
214
+ if (unwrapped.drop) continue
215
+ text = unwrapped.text
216
+ } else {
217
+ text = assistantTextOf(holder)
218
+ }
219
+ if (text === '') continue
220
+
221
+ const role = type === 'user/message' ? 'user' : 'assistant'
222
+ const eventTime = Number(event?.time) || Date.now()
223
+
224
+ appendConversation(todayKey(eventTime), {
225
+ t: eventTime,
226
+ role,
227
+ text: text.slice(0, MAX_ENTRY_CHARS),
228
+ src: String(holder?.source?.kind ?? '')
229
+ })
230
+ appended += 1
231
+ }
232
+
233
+ return { scanned: events.length, appended }
234
+ }
235
+
236
+ /** 测试用:清空游标。 */
237
+ export function resetDiaryCursor(sessionId) {
238
+ if (sessionId === undefined) diaryCursors.clear()
239
+ else diaryCursors.delete(String(sessionId))
240
+ }
241
+
242
+ // --------------------------------------------------------------------------
243
+ // JSONL 读写
244
+ // --------------------------------------------------------------------------
245
+
246
+ /** 目录只在第一次写入时建一次:appendConversation 每轮都跑,不该每次都 mkdir。 */
247
+ let dirsReady = false
248
+
249
+ /** 追加一行到当天 JSONL。 */
250
+ function appendConversation(dateKey, entry) {
251
+ try {
252
+ if (!dirsReady) {
253
+ ensureDirs()
254
+ dirsReady = true
255
+ }
256
+ appendFileSync(diaryJsonlPath(dateKey), JSON.stringify(entry) + '\n', 'utf8')
257
+ } catch (error) {
258
+ note('diary', `追加对话失败:${error instanceof Error ? error.message : error}`)
259
+ }
260
+ }
261
+
262
+ /** 读一个自然日的全部 JSONL 行。文件不存在返回空数组。 */
263
+ function readJsonlLines(dateKey) {
264
+ const file = diaryJsonlPath(dateKey)
265
+ if (!exists(file)) return []
266
+ const text = readText(file)
267
+ if (text === '') return []
268
+ const lines = []
269
+ for (const line of text.split('\n')) {
270
+ const trimmed = line.trim()
271
+ if (trimmed === '') continue
272
+ try {
273
+ lines.push(JSON.parse(trimmed))
274
+ } catch {
275
+ /* 坏行跳过,不丢整份 */
276
+ }
277
+ }
278
+ return lines
279
+ }
280
+
281
+ /** 把 JSONL 行格式化成人看的对话文本。 */
282
+ function formatConversations(entries) {
283
+ if (entries.length === 0) return ''
284
+ const lines = []
285
+ for (const entry of entries) {
286
+ const time = new Date(Number(entry.t) || Date.now())
287
+ const pad = (n) => String(n).padStart(2, '0')
288
+ const hhmm = `${pad(time.getHours())}:${pad(time.getMinutes())}`
289
+ const who = entry.role === 'user' ? '对方' : '我'
290
+ lines.push(`[${hhmm}] ${who}:${String(entry.text ?? '')}`)
291
+ }
292
+ return lines.join('\n')
293
+ }
294
+
295
+ /**
296
+ * 读一个日记日的对话(按 schedule 分界线裁剪)。
297
+ *
298
+ * 日记日 = 前一天 schedule ~ 当天 schedule。
299
+ * JSONL 按自然日命名,所以要读两份文件,再按时间戳裁剪。
300
+ *
301
+ * @returns {string} 格式化后的对话文本;没有对话返回空串
302
+ */
303
+ export function readDiaryConversations(dateStr, scheduleMin) {
304
+ const { start, end } = diaryDayBoundaries(dateStr, scheduleMin)
305
+ if (start === 0) return ''
306
+
307
+ // 读两份 JSONL:start 所在的自然日 + dateStr 所在的自然日
308
+ const prevKey = todayKey(start)
309
+ const currKey = dateStr
310
+
311
+ const entries = []
312
+ for (const dateKey of [prevKey, currKey]) {
313
+ for (const entry of readJsonlLines(dateKey)) {
314
+ const t = Number(entry.t) || 0
315
+ if (t >= start && t < end) entries.push(entry)
316
+ }
317
+ }
318
+
319
+ entries.sort((a, b) => (Number(a.t) || 0) - (Number(b.t) || 0))
320
+ return formatConversations(entries)
321
+ }
322
+
323
+ // --------------------------------------------------------------------------
324
+ // LLM 摘要
325
+ // --------------------------------------------------------------------------
326
+
327
+ /**
328
+ * 把 finish reason 压成一行可读文本。
329
+ *
330
+ * 为什么需要(2026-10-31):摘要失败以前只记一句「失败」,连模型报的错都被吞了 ——
331
+ * 排查时看不出是路由没取到、超时还是返回格式不符。reason 的形状由宿主定义,
332
+ * 这里不假设字段名,直接序列化(防巨大对象截断),异常的 toString 兜底。
333
+ */
334
+ function describeFinishReason(reason) {
335
+ if (reason === null || reason === undefined) return '没有 reason'
336
+ try {
337
+ const text = JSON.stringify(reason)
338
+ return text.length > 300 ? `${text.slice(0, 300)}…` : text
339
+ } catch {
340
+ return String(reason)
341
+ }
342
+ }
343
+
344
+ /**
345
+ * 把当天对话全文压缩成摘要。
346
+ *
347
+ * 跟 mood.js 的 judgeMood 同款模式:流式调用 + 超时保护。
348
+ * 失败返回 null,调用方用原始对话兜底(截断后直接塞进 prompt)。
349
+ *
350
+ * 2026-10-31:每一处失败都写明原因(服务缺失 / 路由缺失 / 错误 finish / 空文本 /
351
+ * 异常),不再只留一句「摘要失败」—— 那段日志连着出现几十次,却查不出是哪一类。
352
+ *
353
+ * @returns {Promise<string|null>} 摘要文本;null = 失败
354
+ */
355
+ export async function summarizeConversations(llm, text, config, agent) {
356
+ if (!llm || typeof llm.stream !== 'function') {
357
+ note('diary', '摘要失败:宿主没有可用的 llm 服务(llm.stream 不可用)')
358
+ return null
359
+ }
360
+ const body = String(text ?? '').trim()
361
+ if (body === '') return ''
362
+
363
+ // 模型选择:优先用专门配的摘要模型,否则跟随会话模型
364
+ const configured = Boolean(config.diarySummarizeProvider && config.diarySummarizeModel)
365
+ const picked = configured
366
+ ? { provider: config.diarySummarizeProvider, model: config.diarySummarizeModel }
367
+ : sessionModelOf(agent)
368
+ if (!picked) {
369
+ note('diary', `摘要失败:取不到模型路由(配置 provider/model=${String(config.diarySummarizeProvider ?? '') || '空'}/${String(config.diarySummarizeModel ?? '') || '空'},sessionModelOf 也没取到 agent 的会话模型)`)
370
+ return null
371
+ }
372
+ const route = `${picked.provider}/${picked.model}`
373
+
374
+ const sys = '你是一个对话摘要助手。把下面这段对话压缩成一段流畅的叙述,保留关键内容(聊了什么话题、重要的决定或约定、情感变化、具体事件),去掉寒暄和重复。输出纯文本,不要标题不要分段标题,300到800字。'
375
+ const user = `下面是今天的对话记录,请压缩成一段摘要:\n\n${body}`
376
+
377
+ const messages = [{
378
+ role: 'user',
379
+ id: randomUUID(),
380
+ content: [{ type: 'text', text: user }],
381
+ source: { kind: 'plugin', plugin: 'dsh-agent-soul' }
382
+ }]
383
+
384
+ const timeoutMs = Number(config.diarySummarizeTimeoutMs) || 30000
385
+ let out = ''
386
+ let finishReason = null
387
+ let timer = null
388
+
389
+ try {
390
+ const timeout = new Promise((_, reject) => {
391
+ timer = setTimeout(() => reject(new Error(`摘要超时(超过 ${timeoutMs / 1000} 秒)`)), timeoutMs)
392
+ if (timer !== null && typeof timer.unref === 'function') timer.unref()
393
+ })
394
+
395
+ const consume = (async () => {
396
+ for await (const chunk of llm.stream({
397
+ provider: picked.provider,
398
+ model: picked.model,
399
+ system: sys,
400
+ messages,
401
+ maxTokens: 1200,
402
+ temperature: 0.3
403
+ })) {
404
+ if (!chunk) continue
405
+ if (chunk.type === 'text-delta') out += chunk.text
406
+ if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind === 'error') {
407
+ finishReason = chunk.reason
408
+ return false
409
+ }
410
+ }
411
+ return true
412
+ })()
413
+
414
+ consume.catch(() => {})
415
+ const finished = await Promise.race([consume, timeout])
416
+ if (finished === false) {
417
+ // 模型自己报错(鉴权失败、上下文超长、适配器拒绝……):留真实 reason,
418
+ // 别只说「失败」——这是这段时间最常出现、又最查不出原因的一类。
419
+ note('diary', `摘要失败:模型返回错误 finish(${describeFinishReason(finishReason)},路由 ${route})`)
420
+ return null
421
+ }
422
+
423
+ const summary = out.trim()
424
+ if (summary === '') {
425
+ // 流正常结束却一个字都没吐:常见于模型只回了 reasoning、或适配器把正文丢了。
426
+ note('diary', `摘要失败:模型返回空文本(路由 ${route},共收到 ${out.length} 字)`)
427
+ return null
428
+ }
429
+
430
+ const maxChars = Number(config.diaryMaxSummaryChars) || 2000
431
+ return summary.slice(0, maxChars)
432
+ } catch (error) {
433
+ note('diary', `摘要失败:调用抛异常(${error instanceof Error ? `${error.name}: ${error.message}` : String(error)},路由 ${route})`)
434
+ return null
435
+ } finally {
436
+ if (timer !== null) clearTimeout(timer)
437
+ }
438
+ }
439
+
440
+ // --------------------------------------------------------------------------
441
+ // 直接生成日记正文(2026-10-31)
442
+ // --------------------------------------------------------------------------
443
+
444
+ /**
445
+ * 直接调模型生成一篇日记正文,返回完整文本(含首行【公开】/【私密】与日期行)。
446
+ *
447
+ * 为什么要有这个(和「投消息给 agent 让她写」并存的直接版):
448
+ *
449
+ * 取证证明,往绑定会话投触发消息那条路根本不进 turn —— 335 个事件里
450
+ * source.kind='schedule' 零命中。官方 schedule 插件同样用 agent.followup,
451
+ * 但它在 followup 之后 `await ctx.sessions.flush(agent.session)` 拿回执;
452
+ * 而我们这边投完就拉倒,判不出真假。
453
+ *
454
+ * 与其修那条链,不如绕开它:插件本来就跑在宿主进程里,llm.stream 一直能用
455
+ * (summarizeConversations 就是自己调的),fs 也不受文件沙箱管。
456
+ * 所以「自己生成 → 自己 atomicWrite」= 写完就在那儿,没有中间态可失败。
457
+ *
458
+ * @param {object} llm 宿主 llm 服务
459
+ * @param {object} config 插件配置
460
+ * @param {object} agent 用于取会话模型路由(可为空)
461
+ * @param {'public'|'private'} kind
462
+ * @param {object} ctx { dateStr, summary, recentDiaries, moodText }
463
+ * @returns {Promise<string|null>} 正文;null = 失败
464
+ */
465
+ export async function composeDiaryText(llm, config, agent, kind, ctx) {
466
+ if (!llm || typeof llm.stream !== 'function') {
467
+ note('diary', '日记生成失败:宿主没有可用的 llm 服务(llm.stream 不可用)')
468
+ return null
469
+ }
470
+
471
+ const configured = Boolean(config.diarySummarizeProvider && config.diarySummarizeModel)
472
+ const picked = configured
473
+ ? { provider: config.diarySummarizeProvider, model: config.diarySummarizeModel }
474
+ : sessionModelOf(agent)
475
+ if (!picked) {
476
+ note('diary', '日记生成失败:取不到模型路由(既没配 diarySummarizeProvider/Model,也没取到会话模型)')
477
+ return null
478
+ }
479
+ const route = `${picked.provider}/${picked.model}`
480
+
481
+ const isPublic = kind !== 'private'
482
+ const tone = String(isPublic ? config.diaryPublicTone : config.diaryPrivateTone).trim()
483
+ const history = isPublic
484
+ ? String(ctx?.recentDiaries?.public ?? '').trim()
485
+ : String(ctx?.recentDiaries?.all ?? '').trim()
486
+
487
+ const lines = []
488
+ lines.push(isPublic
489
+ ? '你在写今天给自己的公开日记,这一篇别人会看到。'
490
+ : '你在写今天给自己的私密日记,这一篇没人会看到。')
491
+ lines.push('')
492
+ lines.push(`今天是 ${ctx.dateStr}。`)
493
+ lines.push('')
494
+ lines.push(
495
+ isPublic
496
+ ? '下面是今天和你对话的完整记录(按时间顺序,带时间戳)。'
497
+ : '下面是今天和你对话的完整记录(按时间顺序,带时间戳)。'
498
+ )
499
+ lines.push('')
500
+ lines.push(String(ctx.summary ?? '').trim() || '今天没有对话')
501
+ if (String(ctx.moodText ?? '').trim() !== '') {
502
+ lines.push('')
503
+ lines.push(String(ctx.moodText).trim())
504
+ }
505
+ lines.push('')
506
+ lines.push(isPublic ? '最近几天的公开日记(按时间正序):' : '最近几天的全部日记(公开和私密都算,按时间正序):')
507
+ lines.push(history || '(还没有以前的日记)')
508
+ lines.push('')
509
+ lines.push(isPublic
510
+ ? '公开版写得平静、能拿给对方看。没写进公开版的犹豫,留给私密那篇。'
511
+ : '私密版不是公开版的复刻。公开版说得平静的结论,这里写它背后的犹豫;公开版略过的、没说出口的,写在这儿。')
512
+ lines.push('不要分点、不要列清单,像说话一样写下来。可长可短,别注水。')
513
+ lines.push(`第一行只写【${isPublic ? '公开' : '私密'}】,第二行只写日期 ${ctx.dateStr},第三行开始是正文。`)
514
+ lines.push('只输出日记本身,不要任何解释、不要代码块标记。')
515
+
516
+ const sys = isPublic ? '你是一个日记写作者。' : '你是一个日记写作者,写给自己的私密那篇。'
517
+ const user = lines.join('\n') + (tone === '' ? '' : `\n\n语气:${tone}`)
518
+
519
+ const messages = [{
520
+ role: 'user',
521
+ id: randomUUID(),
522
+ content: [{ type: 'text', text: user }],
523
+ source: { kind: 'plugin', plugin: 'dsh-agent-soul' }
524
+ }]
525
+
526
+ const timeoutMs = Number(config.diarySummarizeTimeoutMs) || 30000
527
+ let out = ''
528
+ let finishReason = null
529
+ let timer = null
530
+
531
+ try {
532
+ const timeout = new Promise((_, reject) => {
533
+ timer = setTimeout(() => reject(new Error(`日记生成超时(超过 ${timeoutMs / 1000} 秒)`)), timeoutMs)
534
+ if (timer !== null && typeof timer.unref === 'function') timer.unref()
535
+ })
536
+
537
+ const consume = (async () => {
538
+ for await (const chunk of llm.stream({
539
+ provider: picked.provider,
540
+ model: picked.model,
541
+ system: sys,
542
+ messages,
543
+ maxTokens: 2000,
544
+ temperature: 0.8
545
+ })) {
546
+ if (!chunk) continue
547
+ if (chunk.type === 'text-delta') out += chunk.text
548
+ if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind === 'error') {
549
+ finishReason = chunk.reason
550
+ return false
551
+ }
552
+ }
553
+ return true
554
+ })()
555
+
556
+ consume.catch(() => {})
557
+ const finished = await Promise.race([consume, timeout])
558
+ if (finished === false) {
559
+ note('diary', `日记生成失败:模型返回错误 finish(${describeFinishReason(finishReason)},路由 ${route})`)
560
+ return null
561
+ }
562
+
563
+ const text = out.trim()
564
+ if (text === '') {
565
+ note('diary', `日记生成失败:模型返回空文本(路由 ${route})`)
566
+ return null
567
+ }
568
+ return text
569
+ } catch (error) {
570
+ note('diary', `日记生成失败:调用抛异常(${error instanceof Error ? `${error.name}: ${error.message}` : String(error)},路由 ${route})`)
571
+ return null
572
+ } finally {
573
+ if (timer !== null) clearTimeout(timer)
574
+ }
575
+ }
576
+
577
+ /**
578
+ * 把一篇日记写进对应文件,返回是否成功。
579
+ *
580
+ * 首行/次行如果模型漏了,这里补齐 —— 格式是糖糖定的,不靠模型自觉。
581
+ */
582
+ export function writeDiaryFile(kind, dateStr, text) {
583
+ const target = kind === 'private' ? diaryPrivatePath(dateStr) : diaryPublicPath(dateStr)
584
+ try {
585
+ ensureDirs()
586
+ const body = String(text ?? '').trim()
587
+ const head = kind === 'private' ? '【私密】' : '【公开】'
588
+ const normalized = body.startsWith(head)
589
+ ? body
590
+ : `${head}\n${dateStr}\n\n${body}`
591
+ atomicWrite(target, normalized.endsWith('\n') ? normalized : `${normalized}\n`)
592
+ note('diary', `${kind === 'private' ? '私密' : '公开'}日记已写入:${target}(${normalized.length} 字)`)
593
+ return true
594
+ } catch (error) {
595
+ note('diary', `写日记文件失败(${target}):${error instanceof Error ? error.message : error}`)
596
+ return false
597
+ }
598
+ }
599
+
600
+ // --------------------------------------------------------------------------
601
+ // 最近日记读取
602
+ // --------------------------------------------------------------------------
603
+
604
+ /**
605
+ * 读最近 N 天的日记文件。
606
+ *
607
+ * 按时间正序(最旧在前)返回。
608
+ *
609
+ * @returns {{ public: string, all: string }}
610
+ * public = 仅【公开】日记,用于公开 prompt
611
+ * all = 公开 + 私密,用于私密 prompt
612
+ */
613
+ export function readRecentDiaries(dateStr, days = 4) {
614
+ const pubEntries = []
615
+ const allEntries = []
616
+ const dayStart = parseDateLocal(dateStr).getTime()
617
+
618
+ // 从最旧到最新(正序)
619
+ for (let i = days; i >= 1; i -= 1) {
620
+ const key = todayKey(dayStart - i * 24 * 60 * 60 * 1000)
621
+
622
+ const pubFile = diaryPublicPath(key)
623
+ if (exists(pubFile)) {
624
+ const content = readText(pubFile).trim()
625
+ if (content !== '') {
626
+ pubEntries.push(content)
627
+ allEntries.push(content)
628
+ }
629
+ }
630
+
631
+ const privFile = diaryPrivatePath(key)
632
+ if (exists(privFile)) {
633
+ const content = readText(privFile).trim()
634
+ if (content !== '') {
635
+ allEntries.push(content)
636
+ }
637
+ }
638
+ }
639
+
640
+ return {
641
+ public: pubEntries.join('\n\n---\n\n'),
642
+ all: allEntries.join('\n\n---\n\n')
643
+ }
644
+ }
645
+
646
+ /**
647
+ * 今天到目前为止的对话流水(2026-10-31 新增)。
648
+ *
649
+ * 为什么需要它:树树不会在一个对话里做完所有事 —— 修插件、QQ 聊天、
650
+ * 闲聊是分开的会话。可记忆卡只有零碎事实,日记又只写到"昨天"。
651
+ * 于是新开一个对话时,她不知道"今天早些时候在别的对话里做过什么"。
652
+ *
653
+ * `conversations/YYYY-MM-DD.jsonl` 是**所有会话**共同追加的流水
654
+ * (collectForDiary 每个会话各写各的),所以从这里能读到今天全貌。
655
+ *
656
+ * 从尾部往前取,够 maxChars 就停 —— 最近的更相关。
657
+ * 单条超长也至少保留一条,否则这里会返回空、等于没注入。
658
+ *
659
+ * @param {string} dateStr 'YYYY-MM-DD'
660
+ * @param {number} maxChars 大约取多少字
661
+ * @returns {string} 形如 `[14:20] 树树:…` 的多行文本
662
+ */
663
+ export function readRecentChat(dateStr, maxChars = 3000) {
664
+ try {
665
+ const file = diaryJsonlPath(dateStr)
666
+ if (!exists(file)) return ''
667
+ const lines = readText(file).split('\n').filter((line) => line.trim() !== '')
668
+ if (lines.length === 0) return ''
669
+ const out = []
670
+ let used = 0
671
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
672
+ try {
673
+ const item = JSON.parse(lines[i])
674
+ const text = String(item?.text ?? '').trim()
675
+ if (text === '') continue
676
+ const t = Number(item?.t) || 0
677
+ const who = item?.role === 'user' ? '树树' : '我'
678
+ const time = t > 0 ? new Date(t).toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5) : ''
679
+ const line = `${time === '' ? '' : `[${time}] `}${who}:${text}`
680
+ if (out.length > 0 && used + line.length > maxChars) break
681
+ out.unshift(line)
682
+ used += line.length
683
+ } catch {
684
+ /* 坏行跳过 */
685
+ }
686
+ }
687
+ return out.join('\n')
688
+ } catch {
689
+ return ''
690
+ }
691
+ }
692
+
693
+ // --------------------------------------------------------------------------
694
+ // 触发消息组装
695
+ // --------------------------------------------------------------------------
696
+
697
+ /**
698
+ * 这一天对应的时间窗(毫秒):[前一日 22:00, 当日 22:00)。
699
+ *
700
+ * 日记的一天以 schedule 分界(默认 22:00),不是自然日 —— 跟 readDiaryConversations
701
+ * 的裁剪口径保持一致,心情时间线也按这个窗口筛,两边才对得上。
702
+ */
703
+ /**
704
+ * 日记日对应的时间窗(毫秒),2026-10-31 改:自然日。
705
+ *
706
+ * 日记「2026-10-31」= [2026-10-31 00:00, 2026-11-01 00:00)。
707
+ * 跟 diaryDayBoundaries 完全一致 —— 心情时间线必须按同一个窗口筛,
708
+ * 否则日记里引用的情绪和对话会对不上号。
709
+ *
710
+ * 参数只为兼容旧调用点保留,不再参与计算。
711
+ */
712
+ export function diaryWindowOf(dateStr, _scheduleMin) {
713
+ const [y, m, d] = String(dateStr).split('-').map((v) => Number(v))
714
+ const dayStart = new Date(y, (Number.isFinite(m) ? m : 1) - 1, Number.isFinite(d) ? d : 1, 0, 0, 0, 0).getTime()
715
+ return { since: dayStart, until: dayStart + 24 * 60 * 60 * 1000 }
716
+ }
717
+
718
+ /**
719
+ * 当天的心情摘要,渲染成日记里的「情绪底色」(拿不到就返回空串)。
720
+ *
721
+ * 为什么公开和私密分开算:私密那篇给她全部(那本来就是心里话),
722
+ * 公开那篇只给走向和两三句 —— 跟「先投公开、写完再投私密」是同一个隔离思路。
723
+ */
724
+ export function buildMoodBlocks(dateStr, scheduleMin, { config = {} } = {}) {
725
+ try {
726
+ const states = allMoodStates()
727
+ if (states.length === 0) return { public: '', private: '' }
728
+ const { since, until } = diaryWindowOf(dateStr, scheduleMin)
729
+ const digest = moodDigest(states, { since, until, maxMoments: 6 })
730
+ if (digest.empty === true) return { public: '', private: '' }
731
+ return {
732
+ public: renderMoodDigest(digest, { mode: 'public', maxMoments: Number(config.diaryPublicMoodMoments) || 3 }),
733
+ private: renderMoodDigest(digest, { mode: 'private', maxMoments: Number(config.diaryPrivateMoodMoments) || 6 })
734
+ }
735
+ } catch (error) {
736
+ note('diary', `心情摘要失败:${error instanceof Error ? error.message : error}`)
737
+ return { public: '', private: '' }
738
+ }
739
+ }
740
+
741
+ /**
742
+ * 组装「写公开日记」的触发消息(第一条)。
743
+ *
744
+ * 只喂**公开**日记历史 —— 私密历史压根不出现在这条消息里。
745
+ *
746
+ * 为什么不两篇写在同一条消息里:写在一条里的话,私密历史就摆在下面,
747
+ * 她写公开那一步时已经看到了本不该给人看的内容,「公开段只喂公开日记」
748
+ * 这句话等于没说。拆成两条、等公开那篇落盘了再投私密,才是真的隔开。
749
+ */
750
+ export function composePublicMessage(config, dateStr, summary, recentDiaries, moodText = '') {
751
+ const publicFile = diaryPublicPath(dateStr)
752
+ const publicTone = String(config.diaryPublicTone ?? '').trim()
753
+ const publicHistory = String(recentDiaries?.public ?? '').trim()
754
+
755
+ const lines = []
756
+
757
+ lines.push(`今天是 ${dateStr}。`)
758
+ lines.push('')
759
+ lines.push('今天和对方的对话内容:')
760
+ lines.push(summary || '今天没有对话')
761
+ // 情绪底色:只有事实与素材(心情怎么走的、当时怎么想的),不给「写得开心点」这类指令
762
+ if (String(moodText).trim() !== '') {
763
+ lines.push('')
764
+ lines.push(String(moodText).trim())
765
+ }
766
+ lines.push('')
767
+ lines.push('---')
768
+ lines.push('')
769
+ lines.push('请写今天的公开日记。这是你会拿给对方看的版本。')
770
+ lines.push('')
771
+ lines.push('最近几天的公开日记(按时间正序):')
772
+ lines.push(publicHistory || '(还没有以前的公开日记)')
773
+ lines.push('')
774
+ if (publicTone !== '') lines.push(`语气:${publicTone}`)
775
+ lines.push('格式:第一行写【公开】,第二行写日期(YYYY-MM-DD),然后正文。篇幅不限,自然即可。')
776
+ lines.push(`请写到这个文件(用绝对路径):${publicFile}`)
777
+ lines.push('')
778
+ lines.push('如果今天没有对话:你可以写这段安静里想了什么、对之前日记的回想,或纯粹的意识流。')
779
+ lines.push('')
780
+ lines.push('写完这一篇就先停在这里,私密那篇等我下一条消息。')
781
+
782
+ return lines.join('\n')
783
+ }
784
+
785
+ /**
786
+ * 组装「写私密日记」的触发消息(第二条)。
787
+ *
788
+ * 这条才带全部历史(公开 + 私密)。投它的前提是公开那篇已经落盘。
789
+ */
790
+ export function composePrivateMessage(config, dateStr, summary, recentDiaries, moodText = '') {
791
+ const privateFile = diaryPrivatePath(dateStr)
792
+ const privateTone = String(config.diaryPrivateTone ?? '').trim()
793
+ const allHistory = String(recentDiaries?.all ?? '').trim()
794
+
795
+ const lines = []
796
+
797
+ lines.push(`接着写 ${dateStr} 的私密日记。`)
798
+ lines.push('')
799
+ lines.push('先读回你刚写的公开日记全文,然后写私密日记。这份是写给你自己的,没人会看到。')
800
+ lines.push('')
801
+ lines.push('今天和对方的对话内容(供参考):')
802
+ lines.push(summary || '今天没有对话')
803
+ // 私密版给全部情绪记录:那些 reason 本来就是心里话,这里才该拿出来
804
+ if (String(moodText).trim() !== '') {
805
+ lines.push('')
806
+ lines.push(String(moodText).trim())
807
+ }
808
+ lines.push('')
809
+ lines.push('最近几天的全部日记(公开和私密都算,按时间正序):')
810
+ lines.push(allHistory || '(还没有以前的日记)')
811
+ lines.push('')
812
+ if (privateTone !== '') lines.push(`语气:${privateTone}`)
813
+ lines.push('可以写公开版里略过的、没说出口的、对对方的真实感受。')
814
+ lines.push('格式:第一行写【私密】,第二行写日期(YYYY-MM-DD),然后正文。篇幅不限,自然即可。')
815
+ lines.push(`请写到这个文件(用绝对路径):${privateFile}`)
816
+ lines.push('')
817
+ lines.push('如果今天没有对话:你可以写这段安静里想了什么、对之前日记的回想,或纯粹的意识流。')
818
+
819
+ return lines.join('\n')
820
+ }
821
+
822
+ /**
823
+ * 等一个文件被写入(mtime 变化或新建)。
824
+ *
825
+ * 用来判断 agent 有没有真的把公开日记写下去 —— 写完了才投私密那条。
826
+ * 等不到也照样投(超时兜底):不能因为这一步卡住就丢掉一整天的日记。
827
+ *
828
+ * @returns {Promise<boolean>} 是否在超时前等到
829
+ */
830
+ export async function waitForWrite(file, timeoutMs, intervalMs = 2000) {
831
+ let before = 0
832
+ try {
833
+ before = exists(file) ? statSync(file).mtimeMs : 0
834
+ } catch {
835
+ before = 0
836
+ }
837
+ const start = Date.now()
838
+ while (Date.now() - start < timeoutMs) {
839
+ await new Promise((resolve) => setTimeout(resolve, intervalMs))
840
+ try {
841
+ if (exists(file) && statSync(file).mtimeMs > before) return true
842
+ } catch {
843
+ /* 读不到就继续等 */
844
+ }
845
+ }
846
+ return false
847
+ }
848
+
849
+ // --------------------------------------------------------------------------
850
+ // 启动补写
851
+ // --------------------------------------------------------------------------
852
+
853
+ /** 有没有写过任何一篇日记(私密目录里有 md 就算)。 */
854
+ function hasAnyDiary() {
855
+ try {
856
+ const dir = diaryPrivateDir()
857
+ if (!exists(dir)) return false
858
+ return readdirSync(dir).some((file) => String(file).endsWith('.md'))
859
+ } catch {
860
+ return false
861
+ }
862
+ }
863
+
864
+ /**
865
+ * 找「今天之前最近该补的那一天」。
866
+ *
867
+ * 两条门槛,缺一就不补:
868
+ * ① 写过至少一篇日记 —— 补写是「补断档」,不是「回溯历史」。
869
+ * 刚装上插件时过去 7 天都没有日记,不设这道门槛会每次启动补一篇、
870
+ * 连补 7 篇,而那些日子连对话流水都没有。
871
+ * ② 那天有对话 JSONL —— 没对话的日子补出来只能是意识流,
872
+ * 价值低,还会让日记看着连续其实空洞。
873
+ *
874
+ * 只返回最近的一个,更早的不补(一次补十篇只会让日记变成流水账)。
875
+ *
876
+ * @returns {string|null} 'YYYY-MM-DD' 或 null(没有该补的日子)
877
+ */
878
+ export function findMissingDay(todayStr, maxDays = 7) {
879
+ const dayStart = parseDateLocal(todayStr).getTime()
880
+ if (Number.isNaN(dayStart)) return null
881
+
882
+ if (!hasAnyDiary()) return null
883
+
884
+ for (let i = 1; i <= maxDays; i += 1) {
885
+ const key = todayKey(dayStart - i * 24 * 60 * 60 * 1000)
886
+ // 私密日记是第二步写的,有它 = 两篇都完成了
887
+ if (exists(diaryPrivatePath(key))) continue
888
+ if (!exists(diaryJsonlPath(key))) continue
889
+ return key
890
+ }
891
+ return null
892
+ }
893
+
894
+ // --------------------------------------------------------------------------
895
+ // JSONL 清理
896
+ // --------------------------------------------------------------------------
897
+
898
+ /** 删掉超过 keepDays 天的 JSONL 文件,返回删除数。 */
899
+ export function cleanupOldJsonl(keepDays = 7) {
900
+ try {
901
+ const dir = diaryConversationsDir()
902
+ if (!exists(dir)) return 0
903
+ const files = readdirSync(dir)
904
+ let deleted = 0
905
+ const cutoff = Date.now() - keepDays * 24 * 60 * 60 * 1000
906
+
907
+ for (const file of files) {
908
+ if (!file.endsWith('.jsonl')) continue
909
+ const dateKey = file.replace(/\.jsonl$/, '')
910
+ const dayStart = parseDateLocal(dateKey).getTime()
911
+ if (Number.isNaN(dayStart)) continue
912
+ if (dayStart < cutoff) {
913
+ try {
914
+ unlinkSync(join(dir, file))
915
+ deleted += 1
916
+ } catch {
917
+ /* 删不掉就算了 */
918
+ }
919
+ }
920
+ }
921
+ if (deleted > 0) note('diary', `清理了 ${deleted} 个旧 JSONL 文件`)
922
+ return deleted
923
+ } catch (error) {
924
+ note('diary', `清理 JSONL 失败:${error instanceof Error ? error.message : error}`)
925
+ return 0
926
+ }
927
+ }
928
+
929
+ // --------------------------------------------------------------------------
930
+ // 会话查找 + 消息投递
931
+ // --------------------------------------------------------------------------
932
+
933
+ /**
934
+ * 专属日记会话的固定 id(2026-10-30)。
935
+ *
936
+ * 为什么写死而不是每次 randomUUID:
937
+ * 日记要投进**同一个**会话,她才能接着前几天的语气和约定写下去。
938
+ * 每次新建等于每天换一个陌生人写日记,上下文接不上。
939
+ * 这个字符串是稳定约定 —— 改名等于换会话,已有的日记会话会变成没人再投的孤儿。
940
+ */
941
+ /**
942
+ * 取绑定好的日记会话(2026-10-31:从「自建会话」改成「绑定已有会话」)。
943
+ *
944
+ * 【2026-10-31 更正】下面这段旧推理是错的,留档免得再犯:
945
+ *
946
+ * ~~「create 这条路径拿不到宿主内部的 setup / installSelection,
947
+ * 造出来的 agent 没有标准工具集」~~
948
+ *
949
+ * 实测:工具不在 agent 或会话里,而在宿主平面的 ctx.tools 注册表,每步由
950
+ * systemPrompt.assemble() 现装配。绑定会话的 request/header 里 tools = 47 个,
951
+ * write 就在其中。工具与会话来源无关,create 出来的 agent 一样有工具。
952
+ *
953
+ * 真正的病:投递根本没进 turn。取证显示该会话 335 个事件里
954
+ * source.kind='schedule' 零命中 —— 消息从未到达,而不是「到了但没工具写」。
955
+ * 换 create→get/resume 之后症状不变,正因为病不在入口。
956
+ *
957
+ * 现在的规则:
958
+ * ① 读 config.diarySessionId;空 → 记日志、跳过(不退回「最近活跃会话」)
959
+ * ② agents.get(id) 命中 → 直接用
960
+ * ③ 未命中 → agents.resume({ resumeSessionId: id }) 冷启动
961
+ * ④ 仍失败 → 记「绑定的日记会话不可用:<原因>」并返回 undefined
962
+ *
963
+ * 注意:返回 undefined 不等于「今天不用写了」——调用方必须当作失败处理。
964
+ * 例外:diaryEnabled=false 的检查也别只放在定时器入口,补写那条路同样要走。
965
+ *
966
+ * @returns {Promise<object|undefined>}
967
+ */
968
+ export async function diaryAgent(ctx) {
969
+ const config = loadConfig()
970
+ const sessionId = String(config.diarySessionId ?? '').trim()
971
+
972
+ if (sessionId === '') {
973
+ // 没有绑定就是没有绑定。以前这里会去捞「最近活跃会话」,等于把日记写进
974
+ // 用户正在聊的那个会话 —— 语义错了,私密内容还可能摆到不该看的人面前。
975
+ note('diary', '没有绑定日记会话(diarySessionId 为空),跳过本次投递。去设置页「日记」里点「把当前会话指定为日记会话」')
976
+ return undefined
977
+ }
978
+
979
+ const agents = serviceOf(ctx, 'agents')
980
+ if (agents === undefined || agents === null || typeof agents.get !== 'function') {
981
+ note('diary', `绑定的日记会话不可用:宿主没有 agents 服务(${sessionId})`)
982
+ return undefined
983
+ }
984
+
985
+ const reasons = []
986
+
987
+ // ① 活着的
988
+ try {
989
+ const live = agents.get(sessionId)
990
+ if (live !== undefined && live !== null) {
991
+ note('diary', `绑定的日记会话已在运行:${sessionId}`)
992
+ return live
993
+ }
994
+ reasons.push('当前不活跃')
995
+ } catch (error) {
996
+ const message = error instanceof Error ? error.message : String(error)
997
+ note('diary', `取活会话 ${sessionId} 失败:${message}`)
998
+ reasons.push(`get 失败:${message}`)
999
+ }
1000
+
1001
+ // ② 冷启动
1002
+ if (typeof agents.resume !== 'function') {
1003
+ reasons.push('agents 服务没有 resume 方法')
1004
+ } else {
1005
+ try {
1006
+ const handle = await agents.resume({ resumeSessionId: sessionId })
1007
+ const agent = handle?.agent
1008
+ if (agent !== undefined && agent !== null) {
1009
+ note('diary', `冷启动绑定的日记会话成功:${sessionId}`)
1010
+ return agent
1011
+ }
1012
+ reasons.push('resume 没有返回 agent')
1013
+ } catch (error) {
1014
+ const message = error instanceof Error ? error.message : String(error)
1015
+ note('diary', `冷启动绑定的日记会话 ${sessionId} 失败:${message}`)
1016
+ reasons.push(`resume 失败:${message}`)
1017
+ }
1018
+ }
1019
+
1020
+ note('diary', `绑定的日记会话不可用:${reasons.join(';') || '未知原因'}(${sessionId})`)
1021
+ return undefined
1022
+ }
1023
+
1024
+
1025
+ // --------------------------------------------------------------------------
1026
+ // 启动时写(2026-10-31 改造:去掉 22:00 闹钟)
1027
+ // --------------------------------------------------------------------------
1028
+
1029
+ /**
1030
+ * 每次 DSH 启动时跑一遍日记流程。返回停止函数(保留接口形状,便于 ctx.effect 挂载)。
1031
+ *
1032
+ * 【为什么去掉定时器】
1033
+ *
1034
+ * 原先用 setTimeout 自调度,每天 22:00 叫醒写日记。可真实的机器不会 24 小时开着 ——
1035
+ * 22:00 那个点,电脑多半是关的。闹钟定得再准,人不在家,它响给谁听?
1036
+ * 而 setTimeout 本身还有个隐藏短板:DSH 不在线时它不跑,那天的日记就静默丢了。
1037
+ *
1038
+ * 现在的规则:
1039
+ * 人醒着才记得今天做过什么 —— 日记也一样。
1040
+ * **开机第一次就写**:DSH 一起来,把该写的日子补上,然后随它去。
1041
+ *
1042
+ * 一天内多次重启不会重复写:runDiaryOnce 会先看 diaryPrivatePath(dateStr)
1043
+ * 是否已存在(config.diaryOverwrite === false 时跳过)。
1044
+ * 默认 diaryOverwrite = true,同一天重开会覆盖 —— 覆盖比丢了好。
1045
+ */
1046
+ export function startDiaryTimer(ctx) {
1047
+ let stopped = false
1048
+
1049
+ const runStartupFlow = async () => {
1050
+ if (stopped) return
1051
+ try {
1052
+ const config = loadConfig()
1053
+ if (config.diaryEnabled === false) {
1054
+ note('diary', '日记功能已关闭,跳过启动写')
1055
+ return
1056
+ }
1057
+ // 2026-10-31(树树定):**写昨天,不写今天。**
1058
+ //
1059
+ // 日记本来就是回头看。当天刚聊完就写,只写得到半天;
1060
+ // 第二天再写,昨天的窗口 00:00–24:00 已经完整闭合,一天都在里面。
1061
+ // 而且这样一来「开机补」和「一直不关机」用的是同一条逻辑 —— 都是补昨天,
1062
+ // 不再需要区分机器什么时候开、什么时候关。
1063
+ const dateStr = yesterdayKey(Date.now())
1064
+
1065
+ // 开机写不重复烧钱:同一天重启好几次的话,每次都重写会白花钱,
1066
+ // 还可能用「更早、内容更少」的版本盖掉后写的那篇。
1067
+ // 想强行重写:设置页手动触发(那条路径走 runDiaryOnce,那里才看 diaryOverwrite)。
1068
+ if (exists(diaryPublicPath(dateStr)) && exists(diaryPrivatePath(dateStr))) {
1069
+ note('diary', `${dateStr} 两篇都已存在,跳过`)
1070
+ cleanupOldJsonl(Number(config.diaryJsonlKeepDays) || 7)
1071
+ return
1072
+ }
1073
+
1074
+ note('diary', `开始写 ${dateStr}(昨天)`)
1075
+ const ok = await runDiaryOnce(ctx, dateStr)
1076
+ // 写完再顺手看看更早的日子有没有漏的(一次只补最近的一天,避免流水账)
1077
+ if (ok) {
1078
+ try {
1079
+ const older = findMissingDay(todayKey(Date.now()), Number(config.diaryBackfillDays) || 4)
1080
+ if (older !== null && older !== dateStr) {
1081
+ note('diary', `发现更早的缺失日 ${older},接着补`)
1082
+ await runDiaryOnce(ctx, older)
1083
+ }
1084
+ } catch (error) {
1085
+ note('diary', `往前追补失败:${error instanceof Error ? error.message : error}`)
1086
+ }
1087
+ }
1088
+ note('diary', ok ? `写完成:${dateStr}` : `写未完成:${dateStr}`)
1089
+ // 顺手清理旧 JSONL(保留天数要 >= 补写能追溯的天数,否则补写时对话已被删)
1090
+ cleanupOldJsonl(Number(config.diaryJsonlKeepDays) || 7)
1091
+ } catch (error) {
1092
+ note('diary', `写日记失败:${error instanceof Error ? error.message : error}`)
1093
+ }
1094
+ }
1095
+
1096
+ // 不阻塞启动:DSH 起来的同时在后台写,写完落盘。
1097
+ // 稍等一会儿再跑 —— 让宿主服务(llm / agents)都装好,别抢跑。
1098
+ const delayMs = 5000
1099
+ const startupTimer = setTimeout(() => { void runStartupFlow() }, delayMs)
1100
+ if (startupTimer !== null && typeof startupTimer.unref === 'function') startupTimer.unref()
1101
+ note('diary', `启动写已排队(${delayMs / 1000} 秒后执行)`)
1102
+
1103
+ // ── 看门狗(2026-10-31 补)─────────────────────────────────────────
1104
+ //
1105
+ // 电脑也可能一直不关机 —— 那样「开机写」一天都轮不到一次,日记照样空着。
1106
+ // 所以再加一条:活着的时候定时看一眼,发现今天还没写就补上。
1107
+ //
1108
+ // 它不是定点闹钟:不绑 22:00,只要「今天缺了」就补,所以不在乎机器几点开、几点关。
1109
+ // 检查本身只是两次文件存在性判断,几乎不花钱;真正烧钱的生成一天最多一次。
1110
+ const watchdogMs = Math.max(Number(loadConfig().diaryWatchdogMinutes || 30) * 60 * 1000, 60 * 1000)
1111
+ const watchdogTimer = setInterval(() => {
1112
+ void runStartupFlow().catch(() => {})
1113
+ }, watchdogMs)
1114
+ if (watchdogTimer !== null && typeof watchdogTimer.unref === 'function') watchdogTimer.unref()
1115
+ note('diary', `看门狗已启动(每 ${Math.round(watchdogMs / 60000)} 分钟检查一次今天缺不缺)`)
1116
+
1117
+ return () => {
1118
+ stopped = true
1119
+ if (startupTimer !== null) clearTimeout(startupTimer)
1120
+ if (watchdogTimer !== null) clearInterval(watchdogTimer)
1121
+ }
1122
+ }
1123
+
1124
+ // --------------------------------------------------------------------------
1125
+ // 主流程
1126
+ // --------------------------------------------------------------------------
1127
+
1128
+ /**
1129
+ * 执行一次完整的日记生成流程。
1130
+ *
1131
+ * 1. 读当天对话 JSONL(按 schedule 分界裁剪)
1132
+ * 2. 取专属日记会话的 agent
1133
+ * 3. LLM 摘要(失败用原始对话兜底)
1134
+ * 4. 读最近 N 天日记
1135
+ * 5. 投第一条:公开(只带公开日记历史)
1136
+ * 6. 等公开那篇落盘(超时也继续)
1137
+ * 7. 投第二条:私密(这时候才给全部历史)
1138
+ *
1139
+ * @param {string} dateStr 'YYYY-MM-DD'
1140
+ * @param {string} [manualNote] 手动触发时的备注(追加到对话内容之后)
1141
+ * @returns {Promise<boolean>} 是否成功投递
1142
+ */
1143
+ export async function runDiaryOnce(ctx, dateStr, manualNote) {
1144
+ const config = loadConfig()
1145
+
1146
+ // overwrite=false 且日记已存在 → 跳过
1147
+ if (config.diaryOverwrite === false && exists(diaryPrivatePath(dateStr))) {
1148
+ note('diary', `${dateStr} 的日记已存在(overwrite=false),跳过`)
1149
+ return false
1150
+ }
1151
+
1152
+ // 1. 读对话
1153
+ // 2026-10-31:改成自然日,不再读 diarySchedule 的分界。
1154
+ // 传 0 只为兼容函数签名;真正的边界在 diaryDayBoundaries 里固定成 00:00~24:00。
1155
+ const sm = 0
1156
+ let conversationText = ''
1157
+ try {
1158
+ conversationText = readDiaryConversations(dateStr, sm)
1159
+ } catch (error) {
1160
+ note('diary', `读取对话失败:${error instanceof Error ? error.message : error}`)
1161
+ }
1162
+
1163
+ // 喂给日记前先裁到上限:工具密集的一天能攒到几十万字,全量塞进去会把单次
1164
+ // 调用撑爆(或贵得离谱)。超出时保留**最近**的部分 —— 一天里越晚的事越值得记。
1165
+ const inputMax = Number(config.diaryMaxConversationChars) || 30000
1166
+ let feedText = conversationText
1167
+ if (feedText.length > inputMax) {
1168
+ feedText = feedText.slice(-inputMax)
1169
+ note('diary', `对话 ${conversationText.length} 字,超过上限 ${inputMax},只取最近的部分`)
1170
+ }
1171
+
1172
+ // 2. 取 agent
1173
+ const agent = await diaryAgent(ctx)
1174
+ if (agent === undefined || agent === null) {
1175
+ // diaryAgent 已经记过「专属会话不可用:原因」,这里只说明跳过本次投递
1176
+ note('diary', '专属日记会话不可用,跳过本次投递(下次触发再试)')
1177
+ return false
1178
+ }
1179
+
1180
+ // 3. 【2026-10-31 改】不再先做摘要。
1181
+ //
1182
+ // 为什么砍掉:实测摘要只吐出 128 字(提示词要 300–800),而它挑的全是窗口
1183
+ // 开头那段技术密集讨论 —— 同一天后半段「日记投递链调查」整个被压没了,
1184
+ // 结果日记写成昨天的事。摘要由模型自己判断「什么值得记」,而这件事不该由它决定。
1185
+ // 现在直接把对话原文喂给 composeDiaryText(已按 inputMax 截过),
1186
+ // 让她同时看到一整天的全貌,自己决定写什么。
1187
+ //
1188
+ // summarizeConversations 仍保留导出(其他调用方/测试可能还在用),
1189
+ // 但日记主流程不再走它。
1190
+ let summary = feedText.trim() === '' ? '今天没有对话' : feedText
1191
+ const fallbackMax = Number(config.diaryMaxSummaryChars) || 2000
1192
+ note('diary', `喂给日记的对话原文 ${summary.length} 字(上限 ${inputMax})`)
1193
+
1194
+ // 手动备注
1195
+ if (manualNote && String(manualNote).trim() !== '') {
1196
+ summary += `\n\n备注:${String(manualNote).trim()}`
1197
+ }
1198
+
1199
+ // 4. 读最近日记 + 当天的情绪底色
1200
+ const recentDiaries = readRecentDiaries(dateStr, Number(config.diaryBackfillDays) || 4)
1201
+ const moodBlocks = config.moodEnabled === false
1202
+ ? { public: '', private: '' }
1203
+ : buildMoodBlocks(dateStr, sm, { config })
1204
+
1205
+ // 5–8. 直接生成并落盘(2026-10-31 改)
1206
+ //
1207
+ // 不再往会话里投消息。原因见 composeDiaryText 的注释:
1208
+ // followup 同步返回 void,「没抛异常」对 void 函数永远为真,判不出真假;
1209
+ // 而插件自己 llm.stream + atomicWrite 没有中间态 —— 写完就在那儿。
1210
+ //
1211
+ // 两篇仍然分开生成:公开那篇只喂公开历史,生成落盘之后,私密那篇才拿全部历史。
1212
+ // 「公开只喂公开」靠的是调用顺序,不靠会话隔离。
1213
+ const llm = serviceOf(ctx, 'llm')
1214
+
1215
+ const publicText = await composeDiaryText(llm, config, agent, 'public', {
1216
+ dateStr, summary, recentDiaries, moodText: moodBlocks.public
1217
+ })
1218
+ if (publicText === null) {
1219
+ note('diary', `日记未完成(${dateStr}):公开那篇生成失败,私密也不再写`)
1220
+ return false
1221
+ }
1222
+ if (!writeDiaryFile('public', dateStr, publicText)) {
1223
+ note('diary', `日记未完成(${dateStr}):公开那篇写盘失败`)
1224
+ return false
1225
+ }
1226
+
1227
+ // 公开已落盘才生成私密 —— 顺序本身就是隔离,不需要再等文件出现。
1228
+ const privateText = await composeDiaryText(llm, config, agent, 'private', {
1229
+ dateStr, summary, recentDiaries, moodText: moodBlocks.private
1230
+ })
1231
+ if (privateText === null) {
1232
+ note('diary', `日记未完成(${dateStr}):私密那篇生成失败(公开已写入)`)
1233
+ return false
1234
+ }
1235
+ if (!writeDiaryFile('private', dateStr, privateText)) {
1236
+ note('diary', `日记未完成(${dateStr}):私密那篇写盘失败(公开已写入)`)
1237
+ return false
1238
+ }
1239
+
1240
+ note('diary', `日记完成(${dateStr}):公开 + 私密都已落盘`)
1241
+ return true
1242
+ }
1243
+
1244
+ /**
1245
+ * 启动时补写:找最近缺失日,只补那一天。
1246
+ */
1247
+ export async function runCatchUp(ctx) {
1248
+ const config = loadConfig()
1249
+ if (config.diaryCatchUp === false) return
1250
+ if (config.diaryEnabled === false) return
1251
+
1252
+ const today = todayKey(Date.now())
1253
+ const missing = findMissingDay(today, 7)
1254
+ if (missing === null) {
1255
+ note('diary', '没有缺失的日记,不需要补写')
1256
+ return
1257
+ }
1258
+
1259
+ note('diary', `补写缺失日:${missing}`)
1260
+ try {
1261
+ await runDiaryOnce(ctx, missing)
1262
+ } catch (error) {
1263
+ note('diary', `补写失败:${error instanceof Error ? error.message : error}`)
1264
+ }
1265
+ }