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.
@@ -0,0 +1,259 @@
1
+ /**
2
+ * pet-chat-mind.js — 主动思维(v1.2 需求三):**偶尔**说一句 / 问一个问题 / 只记不说。
3
+ *
4
+ * 和旧 `pet-chat-proactive.js` 的分工:
5
+ * · 旧模块是 v0.1「零配置」固定策略(40–90 分钟、每天 3 条、4 条模板);
6
+ * · 本模块是 v1.2 的「内心 tick」:间隔可配(默认 15 分钟)、每小时最多 2 次、
7
+ * 输入多一层上下文(前台应用/观察摘要/记忆 top3),决策分四档:
8
+ * speak —— 陈述一句("你今晚一直在写代码。")
9
+ * ask —— 问一个问题("要不要我帮你把这段整理成文档?")
10
+ * record —— 只记不说(把观察写进记忆,不弹气泡)
11
+ * none —— 什么都不做
12
+ *
13
+ * 硬约束(全部在 `mindAllowed()` 里,按顺序短路):
14
+ * · 主动搭话默认关(设置 `proactive.enabled` 默认 false);
15
+ * · 朗读中 / 录音中 / 一轮回答中 / 静音 / 勿扰时段 ⇒ 不打扰;
16
+ * · 每小时最多 2 次;静默口令("别说了")优先于一切;
17
+ * · 不重复最近 3 次说过的话(归一化后比较,避免只差标点就重说)。
18
+ *
19
+ * 状态文件:`<DSH_FOLIA_HOME>/pet-chat/mind.json`(本机、可删;重启后仍生效)。
20
+ */
21
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { homedir } from 'node:os';
23
+ import { dirname, join } from 'node:path';
24
+
25
+ export const MIND_RULES = Object.freeze({
26
+ /** tick 间隔(分钟):任务书 10–20,默认 15。 */
27
+ defaultIntervalMin: 15,
28
+ minIntervalMin: 10,
29
+ maxIntervalMin: 20,
30
+ /** 每小时最多主动 2 次。 */
31
+ perHourCap: 2,
32
+ /** 连续工作多少分钟后可以问一次(验收 P1:45 分钟能触发)。 */
33
+ workAskMinutes: 45,
34
+ /** 最近说过的话保留多少条(去重用)。 */
35
+ recentLines: 3,
36
+ /** 默认勿扰时段(设置里可改)。 */
37
+ quietFrom: '23:00',
38
+ quietTo: '08:00',
39
+ /** 单条内容上限(和旧主动搭话一致,气泡不刷屏)。 */
40
+ maxChars: 60,
41
+ });
42
+
43
+ /** 哪些前台应用算“在写代码 / 看视频 / 开会”。只按进程名判断,不读内容。 */
44
+ const APP_KINDS = Object.freeze([
45
+ { kind: 'code', apps: ['code', 'code-insiders', 'cursor', 'devenv', 'idea64', 'idea', 'webstorm64', 'pycharm64', 'goland64', 'rider64', 'sublime_text', 'notepad++', 'vim', 'emacs', 'windowsterminal', 'wt', 'powershell', 'pwsh', 'cmd'] },
46
+ { kind: 'video', apps: ['vlc', 'potplayermini64', 'potplayermini', 'mpc-hc64', 'mpv', 'bilibili', 'youtube', 'netflix', 'iqiyi', 'youku', 'tencentvideo', 'qqlive'] },
47
+ { kind: 'meeting', apps: ['zoom', 'teams', 'ms-teams', 'dingtalk', 'feishu', 'lark', 'wemeetapp', 'webex', 'skype'] },
48
+ ]);
49
+
50
+ /** 进程名 → code / video / meeting / ''。 */
51
+ export function appKind(app) {
52
+ const name = String(app || '').toLowerCase().trim().replace(/\.exe$/, '');
53
+ if (!name) return '';
54
+ for (const group of APP_KINDS) {
55
+ if (group.apps.some((item) => name === item || name.includes(item))) return group.kind;
56
+ }
57
+ return '';
58
+ }
59
+
60
+ export function mindStatePath() {
61
+ const base = process.env.DSH_FOLIA_HOME || join(homedir(), '.dsh-folia');
62
+ return join(base, 'pet-chat', 'mind.json');
63
+ }
64
+
65
+ const pad = (n) => String(n).padStart(2, '0');
66
+ const dayKey = (date) => {
67
+ const d = new Date(date);
68
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
69
+ };
70
+
71
+ export function emptyMindState(now = Date.now()) {
72
+ return { date: dayKey(now), lastTickAt: 0, saidAt: [], recent: [] };
73
+ }
74
+
75
+ export function readMindState(now = Date.now()) {
76
+ try {
77
+ const file = mindStatePath();
78
+ if (!existsSync(file)) return emptyMindState(now);
79
+ const doc = JSON.parse(readFileSync(file, 'utf8'));
80
+ const base = emptyMindState(now);
81
+ const state = {
82
+ date: typeof doc.date === 'string' ? doc.date : base.date,
83
+ lastTickAt: Number(doc.lastTickAt) || 0,
84
+ saidAt: Array.isArray(doc.saidAt) ? doc.saidAt.map(Number).filter((n) => n > 0).slice(-20) : [],
85
+ recent: Array.isArray(doc.recent) ? doc.recent.filter((x) => typeof x === 'string').slice(-10) : [],
86
+ };
87
+ if (state.date !== base.date) return { ...base, lastTickAt: 0 };
88
+ return state;
89
+ } catch {
90
+ return emptyMindState(now);
91
+ }
92
+ }
93
+
94
+ export function writeMindState(state) {
95
+ const file = mindStatePath();
96
+ mkdirSync(dirname(file), { recursive: true });
97
+ writeFileSync(file, JSON.stringify(state, null, 2));
98
+ return state;
99
+ }
100
+
101
+ export function clearMindState() {
102
+ try {
103
+ const file = mindStatePath();
104
+ if (existsSync(file)) rmSync(file);
105
+ } catch { /* ignore */ }
106
+ }
107
+
108
+ /** 勿扰时段(支持跨零点,格式 HH:MM)。 */
109
+ export function inQuietWindow(from, to, now = Date.now()) {
110
+ const parse = (value) => {
111
+ const hit = String(value || '').match(/^(\d{1,2}):(\d{2})$/);
112
+ return hit ? Number(hit[1]) * 60 + Number(hit[2]) : null;
113
+ };
114
+ const start = parse(from);
115
+ const end = parse(to);
116
+ if (start === null || end === null) return false;
117
+ const d = new Date(now);
118
+ const cur = d.getHours() * 60 + d.getMinutes();
119
+ return start <= end ? (cur >= start && cur < end) : (cur >= start || cur < end);
120
+ }
121
+
122
+ /** 归一化一句话(去掉标点/空白/emoji 后比较,用于“不重复最近 3 次”)。 */
123
+ export function normalizeMindLine(line) {
124
+ return String(line || '')
125
+ .replace(/[\s,。!?、;:,.!?;:…—~"'"'「」『』()()【】[\]]/g, '')
126
+ .toLowerCase();
127
+ }
128
+
129
+ /**
130
+ * 能不能主动(按顺序短路,reason 给排障用)。
131
+ * @param {{
132
+ * now?:number, enabled?:boolean, intervalMin?:number, quietFrom?:string, quietTo?:string,
133
+ * speaking?:boolean, listening?:boolean, turnBusy?:boolean, muted?:boolean, silent?:boolean,
134
+ * activeMinutes?:number, state?:object,
135
+ * }} input
136
+ */
137
+ export function mindAllowed(input = {}) {
138
+ const now = Number(input.now) || Date.now();
139
+ if (input.enabled !== true) return { ok: false, reason: 'disabled' };
140
+ if (input.speaking === true) return { ok: false, reason: 'speaking' };
141
+ if (input.listening === true) return { ok: false, reason: 'listening' };
142
+ if (input.turnBusy === true) return { ok: false, reason: 'turn-busy' };
143
+ if (input.muted === true) return { ok: false, reason: 'muted' };
144
+ if (input.silent === true) return { ok: false, reason: 'silent' };
145
+ const intervalMin = Math.max(MIND_RULES.minIntervalMin, Math.min(MIND_RULES.maxIntervalMin,
146
+ Number(input.intervalMin) || MIND_RULES.defaultIntervalMin));
147
+ const quietFrom = String(input.quietFrom || MIND_RULES.quietFrom);
148
+ const quietTo = String(input.quietTo || MIND_RULES.quietTo);
149
+ if (inQuietWindow(quietFrom, quietTo, now)) return { ok: false, reason: 'quiet-hours' };
150
+ const state = input.state || readMindState(now);
151
+ const hourAgo = now - 3600 * 1000;
152
+ const saidThisHour = state.saidAt.filter((ts) => ts > hourAgo).length;
153
+ if (saidThisHour >= MIND_RULES.perHourCap) return { ok: false, reason: 'hour-cap' };
154
+ if (state.lastTickAt && now - state.lastTickAt < intervalMin * 60000) return { ok: false, reason: 'too-soon' };
155
+ return { ok: true, reason: 'ok', intervalMin };
156
+ }
157
+
158
+ const SLOT_WORD = Object.freeze({
159
+ late: '夜深了', morning: '早上好', noon: '中午了', afternoon: '下午了', evening: '晚上了',
160
+ });
161
+
162
+ function timeSlot(now) {
163
+ const hour = new Date(now).getHours();
164
+ if (hour < 5) return 'late';
165
+ if (hour < 11) return 'morning';
166
+ if (hour < 14) return 'noon';
167
+ if (hour < 18) return 'afternoon';
168
+ if (hour < 23) return 'evening';
169
+ return 'late';
170
+ }
171
+
172
+ /**
173
+ * 生成一条主动内容(纯函数)。
174
+ * @param {{
175
+ * now?:number, app?:string, title?:string, activeMinutes?:number,
176
+ * wallpaperTitle?:string, memories?:Array<{text?:string}>, state?:object,
177
+ * }} input
178
+ * @returns {{action:'speak'|'ask'|'record'|'none', line:string, kind:string, reason:string}}
179
+ */
180
+ export function buildMindDecision(input = {}) {
181
+ const now = Number(input.now) || Date.now();
182
+ const kind = appKind(input.app);
183
+ const title = String(input.title || '').trim().slice(0, 40);
184
+ const activeMinutes = Math.round(Number(input.activeMinutes) || 0);
185
+ const state = input.state || readMindState(now);
186
+ const used = new Set(state.recent.map(normalizeMindLine));
187
+ const slot = SLOT_WORD[timeSlot(now)] || '';
188
+ const candidates = [];
189
+
190
+ if (kind === 'code' && activeMinutes >= MIND_RULES.workAskMinutes) {
191
+ candidates.push({ action: 'ask', line: `你今晚一直在写代码,要不要我帮你把这段整理成文档?`, kind: 'work' });
192
+ }
193
+ if (kind === 'code') {
194
+ candidates.push({ action: 'ask', line: '写了好一会儿了,要不要先歇一下眼睛?', kind: 'code' });
195
+ candidates.push({ action: 'speak', line: '这段看起来快收尾了,需要我帮你顺一遍吗?', kind: 'code' });
196
+ }
197
+ if (kind === 'video') {
198
+ candidates.push({ action: 'ask', line: title ? `在看「${title.slice(0, 16)}」吗?好看的话记我一份。` : '这部片子看到一半停了,是先去忙了吗?', kind: 'video' });
199
+ }
200
+ if (kind === 'meeting') {
201
+ candidates.push({ action: 'ask', line: '会开完了吗?要不要我帮你把要点记下来?', kind: 'meeting' });
202
+ }
203
+ const memories = Array.isArray(input.memories) ? input.memories.filter((item) => item && item.text) : [];
204
+ const firstMemory = memories.length ? String(memories[0].text).replace(/^[^::]{0,6}[::]/, '').slice(0, 20) : '';
205
+ if (firstMemory) {
206
+ candidates.push({ action: 'speak', line: `想起你之前说的「${firstMemory}」,后来怎么样了?`, kind: 'memory' });
207
+ }
208
+ if (activeMinutes >= 60) {
209
+ candidates.push({ action: 'speak', line: '忙了一个小时了,起来动一动吧。', kind: 'rest' });
210
+ }
211
+ const wallpaperTitle = String(input.wallpaperTitle || '').trim().slice(0, 16);
212
+ if (wallpaperTitle) candidates.push({ action: 'speak', line: `「${wallpaperTitle}」这张挺耐看。`, kind: 'wallpaper' });
213
+ candidates.push({ action: 'ask', line: slot ? `${slot},今天过得怎么样?` : '今天过得怎么样?', kind: 'time' });
214
+
215
+ for (const candidate of candidates) {
216
+ const line = candidate.line.slice(0, MIND_RULES.maxChars);
217
+ if (used.has(normalizeMindLine(line))) continue;
218
+ return { action: candidate.action, line, kind: candidate.kind, reason: 'ok' };
219
+ }
220
+ return { action: 'none', line: '', kind: '', reason: 'deduped' };
221
+ }
222
+
223
+ /**
224
+ * 一次完整 tick:先过闸门,再给决策。
225
+ * @returns {{ok:boolean, action:'speak'|'ask'|'record'|'none', line:string, kind:string, reason:string}}
226
+ */
227
+ export function mindTick(input = {}) {
228
+ const now = Number(input.now) || Date.now();
229
+ const state = input.state || readMindState(now);
230
+ const gate = mindAllowed({ ...input, now, state });
231
+ if (!gate.ok) {
232
+ // 不允许打扰时,仍然可以“只记不说”(观察照常入库,由调用方决定是否写)
233
+ if (gate.reason === 'hour-cap' || gate.reason === 'silent' || gate.reason === 'quiet-hours') {
234
+ return { ok: false, action: input.observationText ? 'record' : 'none', line: '', kind: '', reason: gate.reason };
235
+ }
236
+ return { ok: false, action: 'none', line: '', kind: '', reason: gate.reason };
237
+ }
238
+ const decision = buildMindDecision({ ...input, now, state });
239
+ return { ok: decision.action !== 'none', ...decision, reason: decision.reason === 'ok' ? gate.reason : decision.reason };
240
+ }
241
+
242
+ /** 记一条“说了”:更新时间戳 + 去重窗口。 */
243
+ export function markMindSaid(now = Date.now(), line = '', kind = '') {
244
+ const state = readMindState(now);
245
+ const text = String(line || '').trim();
246
+ const recent = text ? [...state.recent, text].slice(-10) : state.recent;
247
+ return writeMindState({
248
+ ...state,
249
+ sayKind: kind || state.sayKind || '',
250
+ saidAt: [...state.saidAt, now].slice(-20),
251
+ recent,
252
+ });
253
+ }
254
+
255
+ /** 记一次 tick(即使什么都没说,也要间隔够了才再 tick)。 */
256
+ export function markMindTick(now = Date.now()) {
257
+ const state = readMindState(now);
258
+ return writeMindState({ ...state, lastTickAt: now });
259
+ }
@@ -22,7 +22,15 @@ import { readToolLog, clearToolLog } from '../persona-tool-log.js';
22
22
  import { resolvePersonaVoice, publicVoiceCenter, VOLC_VOICE_SUGGESTIONS } from '../tts/voice-center.js';
23
23
  import { VOICE_PACKS } from '../tts/packs.js';
24
24
  import { cardToPersonaPatch, parseCardJson, readCardFromPng, personaToCard, buildCardPng, normalizeCard } from '../persona-card.js';
25
- import { listEvents, deleteEvent, eventCount, readSummary, appendEvent } from '../persona-memory.js';
25
+ import {
26
+ listEvents, deleteEvent, eventCount, readSummary, appendEvent,
27
+ memoryStats, memoryBackend, memoryMigrationInfo, memoryStoragePath,
28
+ deleteEventsByDate, rollbackEvents, decayTick, listObservations, clearObservations,
29
+ } from '../persona-memory.js';
30
+ import {
31
+ listRelations, upsertRelation, deleteRelation, addLore, listLore, searchLore, deleteLore,
32
+ exportMemory,
33
+ } from '../memory-db.js';
26
34
  import { rollbackGrowth, deleteTrait } from '../persona-growth.js';
27
35
  import { listLibraryCards, useLibraryCard } from '../persona-library.js';
28
36
  import {
@@ -442,6 +450,13 @@ export function createPersonaApi(deps = {}) {
442
450
  } catch { /* 原文留档失败不影响保存 */ }
443
451
  if (active) {
444
452
  try { appendEvent(active.id, { kind: 'event', importance: 6, text: `从文档导入人设:${String(body.fileName || card.name).slice(0, 120)}` }); } catch { /* ignore */ }
453
+ // v1.2:世界书 RAG —— 文档正文分块进 lore(500–800 字/块),按检索注入而非整本塞 prompt。
454
+ try {
455
+ const raw = typeof body.rawText === 'string' ? body.rawText : '';
456
+ if (raw.trim().length >= 120) {
457
+ addLore(active.id, { title: String(body.fileName || card.name || '文档').slice(0, 120), content: raw, source: 'document-import' });
458
+ }
459
+ } catch { /* lore 失败不影响导入 */ }
445
460
  }
446
461
  sendJson(res, {
447
462
  ok: true, persona: active, opening: card.firstMes || '',
@@ -584,6 +599,11 @@ export function createPersonaApi(deps = {}) {
584
599
  if (savedPersona && body.active === true) savedPersona = setActivePersona(savedPersona.id);
585
600
  if (savedPersona) {
586
601
  try { appendEvent(savedPersona.id, { kind: 'event', importance: 6, text: `从文档导入人设:${fileName}` }); } catch { /* ignore */ }
602
+ try {
603
+ if (extracted.text && extracted.text.trim().length >= 120) {
604
+ addLore(savedPersona.id, { title: fileName, content: extracted.text, source: 'document-import' });
605
+ }
606
+ } catch { /* lore 失败不影响导入 */ }
587
607
  }
588
608
  }
589
609
  sendJson(res, {
@@ -738,6 +758,97 @@ export function createPersonaApi(deps = {}) {
738
758
  });
739
759
  return true;
740
760
  }
761
+ /* ── v1.2 记忆 v2:统计 / 导出 / 衰减 / 回滚 / 观察记录 / 关系 / 世界书 ── */
762
+ if (rest === 'memory/stats' && (method === 'GET' || method === 'HEAD')) {
763
+ sendJson(res, {
764
+ ok: true, personaId: id,
765
+ ...memoryStats(id),
766
+ backend: memoryBackend(id),
767
+ migration: memoryMigrationInfo(id),
768
+ storage: memoryStoragePath(id),
769
+ });
770
+ return true;
771
+ }
772
+ if (rest === 'memory/export' && (method === 'GET' || method === 'HEAD')) {
773
+ const payload = exportMemory(id);
774
+ res.statusCode = 200;
775
+ res.setHeader('content-type', 'application/json; charset=utf-8');
776
+ res.setHeader('cache-control', 'no-store');
777
+ res.setHeader('content-disposition', `attachment; filename="${encodeURIComponent(id)}-memory.json"`);
778
+ res.end(JSON.stringify(payload, null, 2));
779
+ return true;
780
+ }
781
+ if (rest === 'memory/decay' && method === 'POST') {
782
+ const result = decayTick(id);
783
+ sendJson(res, { ok: true, personaId: id, ...result });
784
+ return true;
785
+ }
786
+ if (rest === 'memory/rollback' && method === 'POST') {
787
+ const body = await new Promise((resolveP) => { withBody(req, resolveP).catch(() => resolveP({})); });
788
+ const result = body.date
789
+ ? deleteEventsByDate(id, String(body.date))
790
+ : rollbackEvents(id, Number(body.before || 0));
791
+ sendJson(res, { ...result, personaId: id }, result.ok ? 200 : 400);
792
+ return true;
793
+ }
794
+ if (rest === 'memory/by-date' && method === 'DELETE') {
795
+ const date = url && url.searchParams ? url.searchParams.get('date') : '';
796
+ const result = deleteEventsByDate(id, String(date || ''));
797
+ sendJson(res, { ...result, personaId: id }, result.ok ? 200 : 400);
798
+ return true;
799
+ }
800
+ if (rest === 'observations' && (method === 'GET' || method === 'HEAD')) {
801
+ const offset = Number(url.searchParams.get('offset') || 0);
802
+ const limit = Number(url.searchParams.get('limit') || 50);
803
+ sendJson(res, { ok: true, personaId: id, ...listObservations(id, { offset, limit }) });
804
+ return true;
805
+ }
806
+ if (rest === 'observations' && method === 'DELETE') {
807
+ sendJson(res, { ok: true, personaId: id, ...clearObservations(id) });
808
+ return true;
809
+ }
810
+ const observationMatch = rest.match(/^observations\/([^/]+)$/);
811
+ if (observationMatch && method === 'DELETE') {
812
+ const result = deleteEvent(id, decodeURIComponent(observationMatch[1]));
813
+ sendJson(res, result, result.ok ? 200 : 404);
814
+ return true;
815
+ }
816
+ if (rest === 'relations' && (method === 'GET' || method === 'HEAD')) {
817
+ sendJson(res, { ok: true, personaId: id, items: listRelations(id) });
818
+ return true;
819
+ }
820
+ if (rest === 'relations' && method === 'POST') {
821
+ const body = await new Promise((resolveP) => { withBody(req, resolveP).catch(() => resolveP({})); });
822
+ const result = upsertRelation(id, body.entity, Number(body.delta) || 0, body.note);
823
+ sendJson(res, { ok: result.ok === true, personaId: id, ...result }, result.ok ? 200 : 400);
824
+ return true;
825
+ }
826
+ const relationMatch = rest.match(/^relations\/([^/]+)$/);
827
+ if (relationMatch && method === 'DELETE') {
828
+ const result = deleteRelation(id, decodeURIComponent(relationMatch[1]));
829
+ sendJson(res, { ...result, personaId: id }, result.ok ? 200 : 404);
830
+ return true;
831
+ }
832
+ if (rest === 'lore' && (method === 'GET' || method === 'HEAD')) {
833
+ const q = url.searchParams.get('q') || '';
834
+ sendJson(res, {
835
+ ok: true, personaId: id,
836
+ items: q ? searchLore(id, q, { limit: 20 }) : listLore(id, { limit: 200 }),
837
+ });
838
+ return true;
839
+ }
840
+ if (rest === 'lore' && method === 'POST') {
841
+ const body = await new Promise((resolveP) => { withBody(req, resolveP).catch(() => resolveP({})); });
842
+ const result = addLore(id, { title: body.title, content: body.content, source: body.source });
843
+ sendJson(res, { ok: result.ok === true, personaId: id, ...result }, result.ok ? 200 : 400);
844
+ return true;
845
+ }
846
+ const loreMatch = rest.match(/^lore\/(\d+)$/);
847
+ if (loreMatch && method === 'DELETE') {
848
+ const result = deleteLore(id, Number(loreMatch[1]));
849
+ sendJson(res, { ...result, personaId: id }, result.ok ? 200 : 404);
850
+ return true;
851
+ }
741
852
  const eventMatch = rest.match(/^memory\/([^/]+)$/);
742
853
  if (eventMatch && method === 'DELETE') {
743
854
  const result = deleteEvent(id, decodeURIComponent(eventMatch[1]));