dsh-folia 1.0.1 → 1.2.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.
@@ -1,26 +1,35 @@
1
1
  /**
2
- * persona-memory.js — 每个人设的**事件流记忆**(pre.65)。
2
+ * persona-memory.js — 每个人设的**事件流记忆**。
3
3
  *
4
- * 与旧 `pet-chat-memory.js` 的关系:没有关系。旧模块只服务旧版 `memory.json`,
5
- * 本模块只读写 `<persona>/memory/`;旧文件不读不引用不删(已确认决策 ④)。
4
+ * v1.2 起是**双后端**:
5
+ * · 首选 SQLite + FTS5(`lib/memory-db.js`,node:sqlite 自带,不新增原生依赖);
6
+ * · 首次使用把 `memory/events.jsonl` + `summary.json` 迁进 DB,JSONL 原样保留只读备份;
7
+ * · node:sqlite 不可用 / 迁移失败 / `FOLIA_MEMORY_DB=0` ⇒ 原样回退 JSONL 路径
8
+ * (旧行为不变,宿主不会因为记忆升级而起不来)。
6
9
  *
7
- * 事件:{ id, ts, kind: 'chat'|'action'|'preference'|'event', text, importance, refs[] }
8
- * · 不设条数/时间上限;
9
- * · 单文件超过 4MB 时滚到 `archive/events-<ts>.jsonl`,读取时按时间合并;
10
- * · 删除单条事件会把所有分片重写到当前 live 文件(事件量小,简单优先)。
10
+ * 事件形状对上层保持兼容:{ id, ts, kind, text, importance, refs, personaId }。
11
+ * 召回仍是 top-8 + token 预算(默认 800),只是排序换成 FTS5/BM25 + 30 天半衰期 + 重要度 + 衰减。
11
12
  *
12
- * 召回:score = 0.5*BM25 + 0.3*新近(14 天半衰期) + 0.2*重要度,top-8,再按 800 token 预算截断。
13
+ * 旧 `pet-chat-memory.js` 与这里的 `memory.json` 没有任何关系;旧文件不读不引用不删。
13
14
  */
14
15
  import {
15
16
  appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync,
16
17
  } from 'node:fs';
17
18
  import { join } from 'node:path';
18
19
  import { personaDir } from './persona-store.js';
20
+ import {
21
+ memoryDbAvailable, memoryDbPath, migrateFromJsonl, migrationInfo, addEvent as dbAddEvent,
22
+ retrieve as dbRetrieve, listEvents as dbListEvents, deleteEvent as dbDeleteEvent,
23
+ deleteByDate as dbDeleteByDate, rollbackTo as dbRollbackTo, clear as dbClear,
24
+ allEvents as dbAllEvents, eventsCount as dbEventsCount, stats as dbStats,
25
+ saveSummary as dbSaveSummary, readSummary as dbReadSummary, decayTick as dbDecayTick,
26
+ } from './memory-db.js';
19
27
 
20
28
  export const MEMORY_BUDGET = Object.freeze({
21
29
  topK: 8,
22
30
  tokenBudget: 800,
23
- recencyHalfLifeDays: 14,
31
+ /** v1.2:半衰期从 14 天延到 30 天(长期记忆要能“记住上个月的事”)。 */
32
+ recencyHalfLifeDays: 30,
24
33
  archiveBytes: 4 * 1024 * 1024,
25
34
  });
26
35
 
@@ -49,6 +58,48 @@ export function archiveDir(personaId) {
49
58
  return join(memoryDir(personaId), 'archive');
50
59
  }
51
60
 
61
+ /* ── 后端选择(DB 优先,失败回退 JSONL)────────────────────────────────── */
62
+
63
+ /** personaId → 'ready' | 'fallback';进程内缓存,避免每轮都试一次迁移。 */
64
+ const backends = new Map();
65
+
66
+ /**
67
+ * 解析该人设的记忆后端。首次调用会做一次迁移(幂等)。
68
+ * @returns {null | {ok:true}} null = 用 JSONL
69
+ */
70
+ function dbFor(personaId) {
71
+ const id = String(personaId || '');
72
+ if (!id) return null;
73
+ if (process.env.FOLIA_MEMORY_DB === '0' || process.env.FOLIA_MEMORY_DB === 'off') return null;
74
+ if (!memoryDbAvailable()) return null;
75
+ const known = backends.get(id);
76
+ if (known === 'fallback') return null;
77
+ if (known === 'ready') return { ok: true };
78
+ try {
79
+ const info = migrateFromJsonl(id);
80
+ if (!info || info.ok !== true) {
81
+ backends.set(id, 'fallback');
82
+ return null;
83
+ }
84
+ backends.set(id, 'ready');
85
+ return { ok: true };
86
+ } catch {
87
+ backends.set(id, 'fallback');
88
+ return null;
89
+ }
90
+ }
91
+
92
+ /** 诊断/判据:当前后端(会触发一次解析)。 */
93
+ export function memoryBackend(personaId) {
94
+ return dbFor(personaId) ? 'db' : 'jsonl';
95
+ }
96
+
97
+ /** 诊断:迁移状态(不触发迁移的只读视图;DB 不可用时 null)。 */
98
+ export function memoryMigrationInfo(personaId) {
99
+ if (!memoryDbAvailable()) return null;
100
+ try { return migrationInfo(String(personaId)); } catch { return null; }
101
+ }
102
+
52
103
  function eventId() {
53
104
  return 'e_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 8);
54
105
  }
@@ -60,7 +111,7 @@ export function sanitizeEvent(raw) {
60
111
  return {
61
112
  id: /^e_[A-Za-z0-9_-]{1,40}$/.test(String(raw.id || '')) ? String(raw.id) : eventId(),
62
113
  ts: Number(raw.ts) || Date.now(),
63
- kind: ['chat', 'action', 'preference', 'event'].includes(String(raw.kind)) ? String(raw.kind) : 'event',
114
+ kind: ['chat', 'action', 'preference', 'event', 'observation', 'treehole'].includes(String(raw.kind)) ? String(raw.kind) : 'event',
64
115
  text,
65
116
  importance: Math.max(1, Math.min(10, Math.round(Number(raw.importance) || 5))),
66
117
  refs: Array.isArray(raw.refs) ? raw.refs.map((ref) => clip(ref, 80)).filter(Boolean).slice(0, 10) : [],
@@ -78,8 +129,10 @@ function rotateIfNeeded(personaId) {
78
129
  } catch { /* 归档失败不阻塞写入:继续追加到 live */ }
79
130
  }
80
131
 
132
+ /* ── JSONL 后端(回退路径;与原实现逐行一致)───────────────────────────── */
133
+
81
134
  /** 追加一条事件;返回落盘后的形状。 */
82
- export function appendEvent(personaId, raw) {
135
+ function appendEventJsonl(personaId, raw) {
83
136
  const event = sanitizeEvent(raw);
84
137
  if (!event) throw Object.assign(new Error('bad-event'), { code: 'bad-event' });
85
138
  event.personaId = personaId;
@@ -91,7 +144,7 @@ export function appendEvent(personaId, raw) {
91
144
  }
92
145
 
93
146
  /** 读所有分片(archive 按文件名时间排序 + live),坏行跳过。 */
94
- export function readAllEvents(personaId) {
147
+ function readAllEventsJsonl(personaId) {
95
148
  const files = [];
96
149
  try {
97
150
  const dir = archiveDir(personaId);
@@ -115,14 +168,61 @@ export function readAllEvents(personaId) {
115
168
  return out.sort((a, b) => a.ts - b.ts);
116
169
  }
117
170
 
171
+ /* ── 统一 API(内部按后端分派)──────────────────────────────────────────── */
172
+
173
+ /** 追加一条事件;返回落盘后的形状。 */
174
+ export function appendEvent(personaId, raw) {
175
+ const id = String(personaId || '');
176
+ if (dbFor(id)) {
177
+ try {
178
+ const item = dbAddEvent(id, {
179
+ text: raw && raw.text,
180
+ kind: raw && raw.kind,
181
+ importance: raw && raw.importance,
182
+ ts: raw && raw.ts,
183
+ pinned: raw && (raw.pinned === true || raw.kind === 'preference'),
184
+ source: (raw && raw.source) || 'chat',
185
+ tags: raw && raw.refs,
186
+ });
187
+ return { ...item, id: String(item.id), refs: [], personaId: id };
188
+ } catch (error) {
189
+ // DB 写失败 ⇒ 本进程降级到 JSONL(不能让一句记忆把聊天打断)
190
+ backends.set(id, 'fallback');
191
+ }
192
+ }
193
+ return appendEventJsonl(id, raw);
194
+ }
195
+
196
+ /** 读所有事件(DB 或 JSONL,按时间升序)。 */
197
+ export function readAllEvents(personaId) {
198
+ const id = String(personaId || '');
199
+ if (dbFor(id)) {
200
+ try {
201
+ return dbAllEvents(id).map((item) => ({ ...item, id: String(item.id), refs: [], personaId: id }));
202
+ } catch { backends.set(id, 'fallback'); }
203
+ }
204
+ return readAllEventsJsonl(id);
205
+ }
206
+
118
207
  export function eventCount(personaId) {
119
- return readAllEvents(personaId).length;
208
+ const id = String(personaId || '');
209
+ if (dbFor(id)) {
210
+ try { return dbEventsCount(id); } catch { backends.set(id, 'fallback'); }
211
+ }
212
+ return readAllEventsJsonl(id).length;
120
213
  }
121
214
 
122
215
  /** 分页 + 搜索(界面时间线用;新→旧)。 */
123
216
  export function listEvents(personaId, { offset = 0, limit = 50, q = '' } = {}) {
217
+ const id = String(personaId || '');
218
+ if (dbFor(id)) {
219
+ try {
220
+ const page = dbListEvents(id, { offset, limit, q });
221
+ return { ...page, items: page.items.map((item) => ({ ...item, id: String(item.id), refs: [], personaId: id })) };
222
+ } catch { backends.set(id, 'fallback'); }
223
+ }
124
224
  const query = String(q || '').trim().toLowerCase();
125
- const all = readAllEvents(personaId)
225
+ const all = readAllEventsJsonl(id)
126
226
  .filter((event) => !query || event.text.toLowerCase().includes(query))
127
227
  .sort((a, b) => b.ts - a.ts);
128
228
  const start = Math.max(0, Number(offset) || 0);
@@ -130,27 +230,92 @@ export function listEvents(personaId, { offset = 0, limit = 50, q = '' } = {}) {
130
230
  return { total: all.length, offset: start, limit: take, items: all.slice(start, start + take) };
131
231
  }
132
232
 
133
- /** 删除单条事件:合并所有分片后重写 live,删除归档。 */
233
+ /** 删除单条事件(DB 走 rowid;JSONL 走合并重写)。 */
134
234
  export function deleteEvent(personaId, eventIdToDelete) {
135
- const all = readAllEvents(personaId);
136
- const kept = all.filter((event) => event.id !== eventIdToDelete);
235
+ const id = String(personaId || '');
236
+ if (dbFor(id)) {
237
+ try {
238
+ const result = dbDeleteEvent(id, eventIdToDelete);
239
+ if (result && result.ok) return { ok: true, id: String(eventIdToDelete), remaining: eventCount(id) };
240
+ return { ok: false, error: 'not-found' };
241
+ } catch { backends.set(id, 'fallback'); }
242
+ }
243
+ const all = readAllEventsJsonl(id);
244
+ const kept = all.filter((event) => event.id !== String(eventIdToDelete));
137
245
  if (kept.length === all.length) return { ok: false, error: 'not-found' };
138
- const dir = archiveDir(personaId);
246
+ const dir = archiveDir(id);
139
247
  try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
140
- mkdirSync(memoryDir(personaId), { recursive: true });
141
- writeFileSync(eventsPath(personaId), kept.map((event) => JSON.stringify(event)).join('\n') + (kept.length ? '\n' : ''));
142
- return { ok: true, id: eventIdToDelete, remaining: kept.length };
248
+ mkdirSync(memoryDir(id), { recursive: true });
249
+ writeFileSync(eventsPath(id), kept.map((event) => JSON.stringify(event)).join('\n') + (kept.length ? '\n' : ''));
250
+ return { ok: true, id: String(eventIdToDelete), remaining: kept.length };
251
+ }
252
+
253
+ /** 按日期删除(YYYY-MM-DD;DB 优先)。 */
254
+ export function deleteEventsByDate(personaId, dateKey) {
255
+ const id = String(personaId || '');
256
+ if (dbFor(id)) {
257
+ try { return dbDeleteByDate(id, dateKey); } catch { backends.set(id, 'fallback'); }
258
+ }
259
+ const parts = String(dateKey || '').match(/^(\d{4})-(\d{2})-(\d{2})$/);
260
+ if (!parts) return { ok: false, error: 'bad-date', deleted: 0 };
261
+ const start = new Date(Number(parts[1]), Number(parts[2]) - 1, Number(parts[3])).getTime();
262
+ const end = start + 86400000;
263
+ const all = readAllEventsJsonl(id);
264
+ const kept = all.filter((event) => !(event.ts >= start && event.ts < end));
265
+ mkdirSync(memoryDir(id), { recursive: true });
266
+ writeFileSync(eventsPath(id), kept.map((event) => JSON.stringify(event)).join('\n') + (kept.length ? '\n' : ''));
267
+ return { ok: true, deleted: all.length - kept.length, date: dateKey };
268
+ }
269
+
270
+ /** 回滚到 beforeTs 之前(之后写入的事件删除)。 */
271
+ export function rollbackEvents(personaId, beforeTs) {
272
+ const id = String(personaId || '');
273
+ if (dbFor(id)) {
274
+ try { return dbRollbackTo(id, beforeTs); } catch { backends.set(id, 'fallback'); }
275
+ }
276
+ return { ok: false, error: 'jsonl-backend', deleted: 0 };
143
277
  }
144
278
 
145
279
  export function clearEvents(personaId) {
146
- try { rmSync(memoryDir(personaId), { recursive: true, force: true }); } catch { /* ignore */ }
280
+ const id = String(personaId || '');
281
+ if (dbFor(id)) {
282
+ try { dbClear(id); } catch { backends.set(id, 'fallback'); }
283
+ }
284
+ try { rmSync(memoryDir(id), { recursive: true, force: true }); } catch { /* ignore */ }
285
+ // DB 文件刚被删掉:本进程的连接缓存要作废,否则下一次写会写进已删除的句柄。
286
+ backends.delete(id);
287
+ }
288
+
289
+ /** 衰减 tick(DB 后端才有效;JSONL 无衰减,返回 total 统计)。 */
290
+ export function decayTick(personaId, options = {}) {
291
+ const id = String(personaId || '');
292
+ if (dbFor(id)) {
293
+ try { return dbDecayTick(id, options); } catch { backends.set(id, 'fallback'); }
294
+ }
295
+ return { ok: true, archived: 0, decayed: 0, total: readAllEventsJsonl(id).length, backend: 'jsonl' };
296
+ }
297
+
298
+ /** 记忆统计(界面「记忆」页用)。 */
299
+ export function memoryStats(personaId) {
300
+ const id = String(personaId || '');
301
+ if (dbFor(id)) {
302
+ try { return { ...dbStats(id), backend: 'db' }; } catch { backends.set(id, 'fallback'); }
303
+ }
304
+ return { ok: true, personaId: id, events: readAllEventsJsonl(id).length, backend: 'jsonl', path: eventsPath(id) };
147
305
  }
148
306
 
149
307
  /* ── 摘要 / 好感快照(写入与读取都按 persona 隔离) ───────────────────── */
150
308
 
151
309
  export function readSummary(personaId) {
310
+ const id = String(personaId || '');
311
+ if (dbFor(id)) {
312
+ try {
313
+ const doc = dbReadSummary(id);
314
+ return { text: clip(doc.text, 8000), updatedAt: Number(doc.updatedAt) || 0 };
315
+ } catch { backends.set(id, 'fallback'); }
316
+ }
152
317
  try {
153
- const doc = JSON.parse(readFileSync(summaryPath(personaId), 'utf8'));
318
+ const doc = JSON.parse(readFileSync(summaryPath(id), 'utf8'));
154
319
  return { text: clip(doc.text, 8000), updatedAt: Number(doc.updatedAt) || 0 };
155
320
  } catch {
156
321
  return { text: '', updatedAt: 0 };
@@ -158,9 +323,16 @@ export function readSummary(personaId) {
158
323
  }
159
324
 
160
325
  export function writeSummary(personaId, text) {
161
- mkdirSync(memoryDir(personaId), { recursive: true });
326
+ const id = String(personaId || '');
327
+ if (dbFor(id)) {
328
+ try {
329
+ dbSaveSummary(id, 'latest', text);
330
+ return { text: clip(text, 8000), updatedAt: Date.now() };
331
+ } catch { backends.set(id, 'fallback'); }
332
+ }
333
+ mkdirSync(memoryDir(id), { recursive: true });
162
334
  const doc = { text: clip(text, 8000), updatedAt: Date.now() };
163
- writeFileSync(summaryPath(personaId), JSON.stringify(doc, null, 2));
335
+ writeFileSync(summaryPath(id), JSON.stringify(doc, null, 2));
164
336
  return doc;
165
337
  }
166
338
 
@@ -191,9 +363,9 @@ export function writeBond(personaId, patch) {
191
363
  return next;
192
364
  }
193
365
 
194
- /* ── 检索:BM25 + 新近 + 重要度 ────────────────────────────────────────── */
366
+ /* ── 检索:FTS5/BM25 + 新近 + 重要度 + 衰减 ─────────────────────────────── */
195
367
 
196
- /** 极简 tokenizer:中文按双字,英文按词;小写、去掉常见标点。 */
368
+ /** 极简 tokenizer(JSONL 回退路径用;中文按双字,英文按词)。 */
197
369
  export function tokenize(text) {
198
370
  const raw = String(text || '').toLowerCase();
199
371
  const tokens = [];
@@ -213,15 +385,12 @@ export function estimateTokens(text) {
213
385
  return Math.ceil(cjk / 1.5 + words * 1.3 + Math.max(0, raw.length - cjk) * 0.05);
214
386
  }
215
387
 
216
- /**
217
- * 召回 top-k 事件,按 token 预算截断。
218
- * 没有找到任何相关事件时仍按“新近 + 重要度”兜底,不返回空(人格需要连续性)。
219
- */
220
- export function retrieveEvents(personaId, query, options = {}) {
388
+ /** JSONL 回退召回(原实现;DB 可用时走 memory-db 的混合检索)。 */
389
+ function retrieveEventsJsonl(personaId, query, options = {}) {
221
390
  const now = options.now || Date.now();
222
391
  const topK = Math.max(1, Math.min(20, Number(options.topK) || MEMORY_BUDGET.topK));
223
392
  const budget = Math.max(80, Number(options.tokenBudget) || MEMORY_BUDGET.tokenBudget);
224
- const all = readAllEvents(personaId);
393
+ const all = readAllEventsJsonl(personaId);
225
394
  if (!all.length) return { items: [], tokens: 0, total: 0 };
226
395
  const qTokens = [...new Set(tokenize(query))];
227
396
  const docs = all.map((event) => {
@@ -266,6 +435,40 @@ export function retrieveEvents(personaId, query, options = {}) {
266
435
  return { items, tokens, total: all.length };
267
436
  }
268
437
 
438
+ /**
439
+ * 召回 top-k 事件,按 token 预算截断(DB 可用时:FTS5 + 30 天半衰期 + 重要度 + 衰减)。
440
+ * 没有找到任何相关事件时仍按“新近 + 重要度”兜底,不返回空(人格需要连续性)。
441
+ */
442
+ export function retrieveEvents(personaId, query, options = {}) {
443
+ const id = String(personaId || '');
444
+ const topK = Math.max(1, Math.min(20, Number(options.topK) || MEMORY_BUDGET.topK));
445
+ const tokenBudget = Math.max(80, Number(options.tokenBudget) || MEMORY_BUDGET.tokenBudget);
446
+ if (dbFor(id)) {
447
+ try {
448
+ const result = dbRetrieve(id, {
449
+ query,
450
+ topK,
451
+ budgetChars: MEMORY_DB_CHARS,
452
+ now: options.now,
453
+ });
454
+ // 字符预算与 token 预算双保险(旧判据断言 memoryTokens ≤ 800)
455
+ const items = [];
456
+ let tokens = 0;
457
+ for (const item of result.items) {
458
+ const nextTokens = tokens + estimateTokens(item.text) + 4;
459
+ if (items.length && nextTokens > tokenBudget) continue;
460
+ items.push({ ...item, id: String(item.id), refs: [], personaId: id });
461
+ tokens = nextTokens;
462
+ }
463
+ return { items, tokens, total: result.total, backend: 'db' };
464
+ } catch { backends.set(id, 'fallback'); }
465
+ }
466
+ return retrieveEventsJsonl(id, query, options);
467
+ }
468
+
469
+ /** DB 的字符预算(1200 字,任务书 §3.4)。 */
470
+ const MEMORY_DB_CHARS = 1200;
471
+
269
472
  /** 注入 system 的召回块(没有事件返回空串)。 */
270
473
  export function memoryRecallLine(items) {
271
474
  const list = Array.isArray(items) ? items.filter((item) => item && item.text).slice(0, MEMORY_BUDGET.topK) : [];
@@ -273,3 +476,47 @@ export function memoryRecallLine(items) {
273
476
  const lines = list.map((item) => '- ' + clip(item.text, 160));
274
477
  return '你记得这些相关的事(只作背景,不要逐条复述):\n' + lines.join('\n');
275
478
  }
479
+
480
+ /* ── v1.2 观察记录 ──────────────────────────────────────────────────────── */
481
+
482
+ /**
483
+ * 写一条观察(被动观察/屏幕感知用):kind=observation、importance 2–3,默认不进气泡。
484
+ * @returns {object|null} 写入的事件(失败返回 null,不抛给采样器)
485
+ */
486
+ export function recordObservation(personaId, input = {}) {
487
+ const text = String(input.text || '').trim().slice(0, 300);
488
+ if (!text) return null;
489
+ try {
490
+ return appendEvent(personaId, {
491
+ kind: 'observation',
492
+ importance: Math.max(2, Math.min(3, Math.round(Number(input.importance) || 2))),
493
+ text,
494
+ source: String(input.source || 'observe').slice(0, 20),
495
+ ts: input.ts,
496
+ });
497
+ } catch {
498
+ return null;
499
+ }
500
+ }
501
+
502
+ /** 观察记录列表(按 type/source 过滤;界面「观察记录」页用)。 */
503
+ export function listObservations(personaId, { offset = 0, limit = 50 } = {}) {
504
+ const page = listEvents(personaId, { offset, limit: Math.min(200, Math.max(1, Number(limit) || 50)) });
505
+ const items = page.items.filter((item) => item.kind === 'observation');
506
+ return { total: items.length, offset, limit, items };
507
+ }
508
+
509
+ /** 清空观察记录(只删 observation,不动普通记忆)。 */
510
+ export function clearObservations(personaId) {
511
+ let removed = 0;
512
+ for (const item of readAllEvents(personaId)) {
513
+ if (item.kind !== 'observation') continue;
514
+ try { if (deleteEvent(personaId, item.id).ok) removed += 1; } catch { /* ignore */ }
515
+ }
516
+ return { ok: true, removed };
517
+ }
518
+
519
+ /** 记忆库路径(诊断;DB 不可用时返回 JSONL 路径)。 */
520
+ export function memoryStoragePath(personaId) {
521
+ return dbFor(personaId) ? memoryDbPath(String(personaId)) : eventsPath(personaId);
522
+ }
@@ -780,8 +780,27 @@ export function buildPersonaSystemPrompt(persona, opts = {}) {
780
780
  lines.push('【表达】' + style.join(';') + '。说教高时可以直接给建议,说教低时少讲道理。');
781
781
  if (express.emoji !== true) lines.push('不要使用表情符号。');
782
782
  const voiceMode = opts.inputMode === 'voice';
783
- if (voiceMode) lines.push('【长度】当前是语音播报:回答 1–3 句,短而自然;更长的内容等用户打字再展开。');
784
- else if (express.lengthPolicy === 'short') lines.push('【长度】回答尽量短,先给结论。');
783
+ /**
784
+ * v1.2 会话模式:chat(默认)/ story(长故事)/ treehole(树洞)/ observe(只观察)。
785
+ * 长度规则按模式分流 —— 故事必须讲完,不再被“语音 1–3 句”的旧提示砍断。
786
+ */
787
+ const conversationMode = ['chat', 'story', 'treehole', 'observe'].includes(String(opts.conversationMode || ''))
788
+ ? String(opts.conversationMode) : 'chat';
789
+ const voiceLength = [0, 3, 8].includes(Number(opts.voiceLength)) ? Number(opts.voiceLength) : 8;
790
+ if (conversationMode === 'story') {
791
+ lines.push('【讲故事的规则】完整讲完一件事:有开头、发展、结尾;不要只给梗概、不要一句话总结。'
792
+ + '目标 800–1200 字(用户要求更长就继续写),段落之间空一行。'
793
+ + '不要用 Markdown 标题/列表/加粗/代码块;不要问“要不要继续”,除非故事已经讲完。'
794
+ + '讲完就停,不要补免责声明。');
795
+ } else if (conversationMode === 'treehole') {
796
+ lines.push('【树洞模式】先接住情绪,再问一个开放问题;不急着给建议、不评判、不诊断、不说“你应该”。'
797
+ + '允许短句,也允许只有一句“我在”。只有用户明确问“怎么办”时才给建议,且最多三条。'
798
+ + '你不是心理治疗师,也不提供医疗/法律建议;遇到自伤/危机话题,先关心安全,再建议找专业人士。');
799
+ } else if (voiceMode && conversationMode === 'chat') {
800
+ lines.push(voiceLength === 0
801
+ ? '【长度】当前是语音播报:不限句数,把事情完整说完;仍然口语、自然,不要念 Markdown。'
802
+ : `【长度】当前是语音播报:最多 ${voiceLength} 句,短而自然;更长的内容等用户打字再展开。`);
803
+ } else if (express.lengthPolicy === 'short') lines.push('【长度】回答尽量短,先给结论。');
785
804
  else if (express.lengthPolicy === 'long') lines.push('【长度】可以充分展开,按场景需要描写细节。');
786
805
  else lines.push('【长度】按场景自适应:聊天短句,故事/创作可以长;不要固定字数。');
787
806
  // 任务 §3②:回答规则写进 system(不是"客服模板")。
@@ -833,8 +852,39 @@ export function buildPersonaSystemPrompt(persona, opts = {}) {
833
852
  return clipChars(lines.join('\n'), 16000);
834
853
  }
835
854
 
836
- const WALLPAPER_QUERY_RE = /(?:壁纸|桌面|背景).{0,6}(?:是什么|是哪张|哪张|叫什么|现在用|当前)|(?:现在|当前).{0,6}(?:壁纸|桌面)/;
837
- const WALLPAPER_ACTION_RE = /(?:(?:换|切换|改|设|来|挑|选|用).{0,8}(?:壁纸|桌面背景|背景图|桌面))|(?:(?:把|给|帮我把|帮我).{0,12}(?:壁纸|桌面|背景).{0,12}(?:换|改|设|切))/;
855
+ /* ── 树洞安全(v1.2)─────────────────────────────────────────────────────
856
+ * 自伤/危机话题**不交给模型自由发挥**:命中就先用固定、克制的一段话接住,
857
+ * 给出求助热线并明确“不是心理治疗”。热线程由设置注入(不写死某一家的号码)。
858
+ * 只认明确的危机表达,避免把“笑死/累死”这类口语误判。
859
+ */
860
+ export const TREEHOLE_CRISIS_PATTERNS = Object.freeze([
861
+ '自杀', '自残', '想死', '不想活', '活不下去', '不想活了', '结束生命', '轻生',
862
+ '割腕', '跳楼', '跳河', '伤害自己', '一了百了', '吞药', '安眠药', '了结自己',
863
+ ]);
864
+
865
+ /** 命中返回命中的词(用于诊断/记忆),否则空串。 */
866
+ export function detectCrisis(text) {
867
+ const raw = String(text || '');
868
+ if (!raw) return '';
869
+ for (const word of TREEHOLE_CRISIS_PATTERNS) {
870
+ if (raw.includes(word)) return word;
871
+ }
872
+ return '';
873
+ }
874
+
875
+ /**
876
+ * 危机时的固定回应(可配置热线)。
877
+ * 语气:先接住、再关心安全、给可执行的下一步;明确边界,不做诊断/治疗承诺。
878
+ */
879
+ export function treeholeSafetyReply(hotline = '12356') {
880
+ const line = String(hotline || '').trim() || '12356';
881
+ return '我听到了,你现在一定很难受。我很在意你的安全——先别一个人扛着:'
882
+ + '可以马上联系身边信得过的人陪着你;如果现在有伤害自己的冲动,请立刻拨打 '
883
+ + line + '(心理援助热线)或 110/120。'
884
+ + '我不是心理治疗,也不能替代专业帮助,但我可以一直听你说。';
885
+ }
886
+
887
+ const WALLPAPER_QUERY_RE = /(?:壁纸|桌面|背景).{0,6}(?:是什么|是哪张|哪张|叫什么|现在用|当前)|(?:现在|当前).{0,6}(?:壁纸|桌面)/;const WALLPAPER_ACTION_RE = /(?:(?:换|切换|改|设|来|挑|选|用).{0,8}(?:壁纸|桌面背景|背景图|桌面))|(?:(?:把|给|帮我把|帮我).{0,12}(?:壁纸|桌面|背景).{0,12}(?:换|改|设|切))/;
838
888
  const REMINDER_RE = /提醒|闹钟|定时/;
839
889
  const REMINDER_LIST_RE = /(?:有什么|还有|看看|列出).{0,4}提醒|提醒.{0,4}(?:列表|有什么)/;
840
890
  const PET_TOGGLE_RE = /(?:(?:关掉|关闭|隐藏|收起|打开|显示|出来).{0,6}(?:桌宠|宠物))|(?:(?:桌宠|宠物).{0,4}(?:关掉|关闭|隐藏|收起|打开|显示))/;