feiyu-brain 1.5.0 → 1.6.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 +1 -1
- package/cli.mjs +94 -1
- package/cordis.patch.yml +13 -1
- package/core/bond.js +186 -0
- package/core/concept.js +138 -0
- package/core/driver.js +74 -0
- package/core/extract.js +75 -2
- package/core/memory.js +539 -18
- package/core/persona.js +167 -7
- package/core/relation.js +78 -0
- package/core/self.js +72 -0
- package/docs/CHANGELOG-1.6.md +154 -0
- package/docs/MEMORY.md +180 -15
- package/index.js +679 -44
- package/lib/channels.mjs +199 -0
- package/lib/llm.mjs +105 -0
- package/lib/onebot.mjs +106 -0
- package/lib/say.mjs +120 -0
- package/lib/serve.mjs +42 -1
- package/package.json +10 -3
- package/selftest.mjs +54 -6
- package/smoke.mjs +41 -0
- package/store.js +153 -11
- package/test-adapters.mjs +132 -0
package/index.js
CHANGED
|
@@ -10,12 +10,15 @@ import fs from 'node:fs';
|
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import crypto from 'node:crypto';
|
|
12
12
|
|
|
13
|
-
import { birthFromCard, lintCard } from './core/extract.js';
|
|
14
|
-
import { brief, decay, evolve, shed, weightReport } from './core/persona.js';
|
|
13
|
+
import { birthFromCard, lintCard, TRAIT_LEXICON } from './core/extract.js';
|
|
14
|
+
import { brief, decay, evolve, shed, weightReport, shellSummary, recentShift, speechProfile } from './core/persona.js';
|
|
15
15
|
import { styleVector, flowLevel, flowName, hashTraits, mulberry32 } from './core/derive.js';
|
|
16
16
|
import { createBody, chooseBody, bodyLine, canDo, hasCapability, CAPABILITY, BODY_KINDS, BODY_PROFILES, recordAction } from './core/body.js';
|
|
17
|
-
import { emptyMemory, addEpisode, addImagination, recall, settle, retrieve } from './core/memory.js';
|
|
18
|
-
import {
|
|
17
|
+
import { emptyMemory, addEpisode, addImagination, recall, settle, retrieve, touchByIds, distillGists, distillUmbrellas, nameFaded, detectRepeat, markImportant, markImportantByTopic, isRepeatNoise, textSimilarity, IMPORTANT_REPEAT, IMPORTANT_WINDOW_DAYS } from './core/memory.js';
|
|
18
|
+
import { addBond, bondDelta, bondOf, bondLine, decayBonds, bondSensitivity, markBondAbsent, clearBondAbsent, bondAbsentOf, ABSENT_MIN_TIER, BOND_TIERS, BOND_MAX } from './core/bond.js';
|
|
19
|
+
import { learnConcept, conceptOf, conceptAnswer, conceptsIn, makeQuestion } from './core/concept.js';
|
|
20
|
+
import { composeNarrative, narrativeChanged, NARRATIVE_MAX } from './core/self.js';
|
|
21
|
+
import { createContract, markAbsent as markAbsentContract, clearAbsent as clearAbsentRelation, relationLine, isAbsent } from './core/relation.js';
|
|
19
22
|
import { attribute, LABELS } from './core/attribution.js';
|
|
20
23
|
import { check } from './core/invariants.js';
|
|
21
24
|
import { toCue, toObservation, shouldObserve, normalizeEvent } from './core/event.js';
|
|
@@ -31,15 +34,21 @@ import {
|
|
|
31
34
|
import {
|
|
32
35
|
ROOT, loadBrain, saveBrain, appendAudit, readAudit, listBrains,
|
|
33
36
|
setDataDir, setRoleDir, dataDir, roleDir, brainDir, dataDirSource, isDataDirInsidePackage,
|
|
37
|
+
setEpisodeWindow, episodeWindow, readYear, listYears,
|
|
34
38
|
} from './store.js';
|
|
35
39
|
|
|
36
40
|
const DEFAULT_ID = 'default';
|
|
37
41
|
const cache = new Map();
|
|
38
42
|
|
|
39
43
|
/* 全局开关(configure 改) */
|
|
40
|
-
let shadowMode = false; //
|
|
44
|
+
let shadowMode = false; // 影子模式:算但不写人设,全记进 shadow.jsonl
|
|
41
45
|
let ttlPolicy = 'hard'; // hard | summarize | archive | off
|
|
42
46
|
let moodPolicy = 'brain'; // 情绪双源:brain(脑说了算)| host(宿主说了算)| blend(各一半)
|
|
47
|
+
let compressDays = 21; // 完整期:21 天没人提 → 压成卡片
|
|
48
|
+
let forgetDays = 730; // 卡片期:2 年没人提 → 遗忘
|
|
49
|
+
let briefChars = 300;
|
|
50
|
+
let briefRules = 0.25; // 规章在 brief 里的配额;0 = 一条都不要 // 「此刻的她」多长;老鱼可以调大
|
|
51
|
+
let maxEpisodes = 5000; // 脑里最多存多少条,超了最老的压卡片
|
|
43
52
|
|
|
44
53
|
function nowMs() {
|
|
45
54
|
return Date.now();
|
|
@@ -60,12 +69,34 @@ function logOnce(msg) {
|
|
|
60
69
|
* configure({ shadow: true }) 影子模式:observe 只留审计,不动人设、不落盘
|
|
61
70
|
* configure({ ttlPolicy: 'off' }) hard(默认) | summarize(过期前压卡片) | off(永不遗忘)
|
|
62
71
|
*/
|
|
63
|
-
|
|
72
|
+
/**
|
|
73
|
+
* 宿主初始化。
|
|
74
|
+
*
|
|
75
|
+
* configure({ dataDir, roleDir })
|
|
76
|
+
* configure({ shadow: true }) 影子模式:算但不写人设,全记进 shadow.jsonl
|
|
77
|
+
* configure({ ttlPolicy: 'off' }) hard(默认) | summarize | archive | off
|
|
78
|
+
* configure({ moodPolicy: 'host' }) brain | host | blend
|
|
79
|
+
* configure({ compressDays: 30 }) 多少天没人提就压扁
|
|
80
|
+
* configure({ forgetDays: 90 }) 多少天没人提就遗忘
|
|
81
|
+
* configure({ briefChars: 300 }) 「此刻的她」多长(老鱼可以调到 600)
|
|
82
|
+
* configure({ maxEpisodes: 5000 }) 脑里最多存多少条
|
|
83
|
+
*/
|
|
84
|
+
export function configure({
|
|
85
|
+
dataDir: d, roleDir: r, shadow, ttl, mood, briefRules: br,
|
|
86
|
+
compressDays: cd, forgetDays: fd, briefChars: bc, maxEpisodes: me,
|
|
87
|
+
} = {}) {
|
|
64
88
|
if (d) setDataDir(d);
|
|
65
89
|
if (r) setRoleDir(r);
|
|
66
90
|
if (typeof shadow === 'boolean') shadowMode = shadow;
|
|
67
91
|
if (ttl && ['hard', 'summarize', 'archive', 'off'].includes(ttl)) ttlPolicy = ttl;
|
|
68
92
|
if (mood && ['brain', 'host', 'blend'].includes(mood)) moodPolicy = mood;
|
|
93
|
+
if (Number.isFinite(cd) && cd > 0) compressDays = Math.floor(cd);
|
|
94
|
+
if (Number.isFinite(fd) && fd > compressDays) forgetDays = Math.floor(fd);
|
|
95
|
+
// 经历按年分片:打开时只加载 forgetDays 窗口内的年份(16 年也不会越读越慢)
|
|
96
|
+
setEpisodeWindow(forgetDays);
|
|
97
|
+
if (Number.isFinite(bc) && bc >= 100) briefChars = Math.floor(bc);
|
|
98
|
+
if (br) briefRules = br === 'drop' ? 0 : 0.25;
|
|
99
|
+
if (Number.isFinite(me) && me >= 100) maxEpisodes = Math.floor(me);
|
|
69
100
|
}
|
|
70
101
|
|
|
71
102
|
export function runtimeOptions() {
|
|
@@ -73,6 +104,10 @@ export function runtimeOptions() {
|
|
|
73
104
|
shadow: shadowMode,
|
|
74
105
|
ttlPolicy,
|
|
75
106
|
moodPolicy,
|
|
107
|
+
compressDays,
|
|
108
|
+
forgetDays,
|
|
109
|
+
briefChars,
|
|
110
|
+
maxEpisodes,
|
|
76
111
|
dataDir: dataDir(),
|
|
77
112
|
dataDirSource: dataDirSource(),
|
|
78
113
|
dataDirInsidePackage: isDataDirInsidePackage(),
|
|
@@ -136,7 +171,12 @@ export function resolveRoleCard(roleName) {
|
|
|
136
171
|
}
|
|
137
172
|
|
|
138
173
|
function refreshBrief(brain) {
|
|
139
|
-
|
|
174
|
+
// brief 多长,由人设算——话少的鱼,连介绍自己都懒得说全
|
|
175
|
+
const prof = speechProfile(brain.persona.traits);
|
|
176
|
+
brain.persona.brief = brief(brain.persona.units, {
|
|
177
|
+
maxChars: Math.min(briefChars, prof.chars),
|
|
178
|
+
ruleShare: briefRules,
|
|
179
|
+
});
|
|
140
180
|
return brain;
|
|
141
181
|
}
|
|
142
182
|
|
|
@@ -171,7 +211,10 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
171
211
|
if (fs.existsSync(sidecar)) traitsOverride = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
|
|
172
212
|
} catch { traitsOverride = null; }
|
|
173
213
|
|
|
174
|
-
const { traits, units } = birthFromCard(card.text, { traitsOverride });
|
|
214
|
+
const { traits, units, knownTraits, openTraits } = birthFromCard(card.text, { traitsOverride });
|
|
215
|
+
// 命题的"最后一次被碰到"从出生算起——不然一条新鱼第一天就开始褪色
|
|
216
|
+
const born = nowMs();
|
|
217
|
+
for (const u of units) { u.lastTouched = born; u.born = born; }
|
|
175
218
|
const brain = {
|
|
176
219
|
id,
|
|
177
220
|
schema: 'brain/2',
|
|
@@ -180,8 +223,16 @@ export function birth({ id = DEFAULT_ID, relation = 'parent', address = '', card
|
|
|
180
223
|
persona: {
|
|
181
224
|
seed: cardName ? `card:${card.name}` : `${roleDir()}/${card.name}.md`,
|
|
182
225
|
traits,
|
|
226
|
+
// 已知 12 维(先验)与她自己长出来的维度分开存,方便看"哪些是她的原话"
|
|
227
|
+
knownTraits: knownTraits ?? traits,
|
|
228
|
+
openTraits: openTraits ?? {},
|
|
183
229
|
units,
|
|
184
230
|
brief: '',
|
|
231
|
+
// 一年一度蜕壳:把这一年掉出去的人设打包成永久记忆卡片
|
|
232
|
+
shellYear: new Date(born).getFullYear(),
|
|
233
|
+
shellAt: born,
|
|
234
|
+
// 最近几天的权重变动,用来生成「最近」那一段
|
|
235
|
+
moves: [],
|
|
185
236
|
// 人格主档只有一个:这里。外部卡只是"导入源",导过就记下来。
|
|
186
237
|
source: {
|
|
187
238
|
kind: cardText ? 'inline' : 'file',
|
|
@@ -226,6 +277,8 @@ export function ensureBrain(id = DEFAULT_ID) {
|
|
|
226
277
|
if (cache.has(id)) return cache.get(id);
|
|
227
278
|
let brain = loadBrain(id);
|
|
228
279
|
if (!brain) brain = birth({ id });
|
|
280
|
+
// 老版本存档要补齐形状,否则升级当天她就没法说话
|
|
281
|
+
brain = normalizeBrain(brain);
|
|
229
282
|
cache.set(id, brain);
|
|
230
283
|
return brain;
|
|
231
284
|
}
|
|
@@ -251,9 +304,9 @@ export function getBrief(id = DEFAULT_ID) {
|
|
|
251
304
|
* sections 可选:persona / flow / body / mood / memory / search
|
|
252
305
|
* budget 是**总字数上限**,超了就从低优先级的段开始砍(persona 保底不砍)。
|
|
253
306
|
*/
|
|
254
|
-
export const WAKE_SECTIONS = ['persona', 'flow', 'body', 'mood', 'memory', 'search'];
|
|
307
|
+
export const WAKE_SECTIONS = ['persona', 'self', 'relation', 'bond', 'concept', 'flow', 'body', 'mood', 'recent', 'memory', 'search'];
|
|
255
308
|
/** 预算不够时的砍法:越靠后越先砍 */
|
|
256
|
-
const WAKE_PRIORITY = ['persona', 'mood', 'flow', 'memory', 'body', 'search'];
|
|
309
|
+
const WAKE_PRIORITY = ['persona', 'self', 'relation', 'concept', 'bond', 'mood', 'recent', 'flow', 'memory', 'body', 'search'];
|
|
257
310
|
|
|
258
311
|
export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
259
312
|
const brain = ensureBrain(id);
|
|
@@ -268,6 +321,26 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
|
268
321
|
brain.state.flow = level;
|
|
269
322
|
|
|
270
323
|
const seg = { persona: `【此刻的她】${brain.persona.brief}` };
|
|
324
|
+
|
|
325
|
+
// 「我是谁」——会跟着经历长的那一句
|
|
326
|
+
const nar = brain.self?.narrativeText ?? brain.self?.narrative;
|
|
327
|
+
if (nar) seg.self = `【我是谁】${nar}`;
|
|
328
|
+
|
|
329
|
+
// 缺位:那个人不在了。关系没断,但状态要说出来——
|
|
330
|
+
// 不写"想念",只给事实,怎么感受由她的人设决定。
|
|
331
|
+
const relLine = relationLine(brain.relation);
|
|
332
|
+
if (relLine) seg.relation = `【他】${relLine}`;
|
|
333
|
+
|
|
334
|
+
// 恩情:除了主人,还有谁对她好过——这是她自己算的,不是标签
|
|
335
|
+
const bonded = Object.keys(brain.memory.bonds ?? {})
|
|
336
|
+
.filter((w) => w !== brain.relation?.address)
|
|
337
|
+
.map((w) => bondOf(brain.memory, w))
|
|
338
|
+
.filter((b) => b.tier !== 'stranger')
|
|
339
|
+
.sort((a, b) => b.score - a.score)
|
|
340
|
+
.slice(0, 2);
|
|
341
|
+
if (bonded.length) {
|
|
342
|
+
seg.bond = `【他们】${bonded.map((b) => bondLine(brain.memory, b.who)).join(';')}`;
|
|
343
|
+
}
|
|
271
344
|
if (level !== 1) seg.flow = `【意识流】${flowName(level)}`;
|
|
272
345
|
|
|
273
346
|
const bodyText = bodyLine(brain.body);
|
|
@@ -283,9 +356,21 @@ export function wakeLine(id = DEFAULT_ID, eventOrCue = null, opts = {}) {
|
|
|
283
356
|
}
|
|
284
357
|
|
|
285
358
|
const cue = eventOrCue?.who !== undefined ? eventOrCue : toCue(eventOrCue);
|
|
359
|
+
|
|
360
|
+
// 概念:这次聊到的东西她到底懂不懂
|
|
361
|
+
const cs = conceptsIn(brain.memory, cue?.text ?? '');
|
|
362
|
+
if (cs.length) {
|
|
363
|
+
seg.concept = `【她懂的】${cs.map((c) => `${c.term}:${c.definition}${c.why ? `(${c.why})` : ''}`).join(';')}`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// 「最近」:每天 ±0.01 看不出来,七天攒起来就能说一句
|
|
367
|
+
const shift = recentShift(brain.persona.moves, brain.persona.units, { at: nowMs() });
|
|
368
|
+
if (shift) seg.recent = `【最近】${shift.line}`;
|
|
286
369
|
if (cue) {
|
|
287
370
|
const hit = retrieve(cue, brain.memory);
|
|
288
371
|
if (hit.text) seg.memory = `【想到的】\n${hit.text}`;
|
|
372
|
+
// 「被想起来」也算提起:检索命中的记忆会续命,一直没人想起的才会老化
|
|
373
|
+
if (hit.items?.length) touchByIds(brain.memory, hit.items.map((i) => i.id), nowMs());
|
|
289
374
|
|
|
290
375
|
// 外部检索器(向量/图谱):同步读缓存,不 await
|
|
291
376
|
if (extraRetriever) {
|
|
@@ -340,34 +425,59 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
340
425
|
const conflicting = ev.conflicting ?? matchUnits(brain.persona.units, ev.text ?? '').conflicting;
|
|
341
426
|
|
|
342
427
|
// ── 影子模式 ──
|
|
343
|
-
//
|
|
344
|
-
//
|
|
345
|
-
//
|
|
428
|
+
// 算但不写:人设权重、记忆、brain.json 一个字不动。
|
|
429
|
+
// 但**不是空跑**——这一次的「本来会发生什么」全记进 shadow.jsonl,
|
|
430
|
+
// 跑一百轮之后能看见她会长成什么样,再决定要不要真接。
|
|
346
431
|
if (shadowMode || brain.meta.shadow) {
|
|
347
432
|
const would = brain.persona.units
|
|
348
433
|
.filter((u) => consistent.includes(u.id) || conflicting.includes(u.id))
|
|
349
434
|
.map((u) => ({
|
|
350
435
|
id: u.id,
|
|
436
|
+
text: u.text.slice(0, 30),
|
|
351
437
|
from: Number(u.weight.toFixed(3)),
|
|
352
438
|
to: Number(Math.max(0, Math.min(1, u.weight + (consistent.includes(u.id) ? 1 : -1) * 0.01)).toFixed(3)),
|
|
353
439
|
}));
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
shadow: true,
|
|
440
|
+
|
|
441
|
+
const entry = {
|
|
357
442
|
at,
|
|
358
|
-
text: String(ev.text ?? ev.what ?? '').slice(0,
|
|
443
|
+
text: String(ev.text ?? ev.what ?? '').slice(0, 100),
|
|
359
444
|
wouldChange: would,
|
|
360
|
-
|
|
445
|
+
wouldRemember: String(ev.what ?? ev.text ?? '').slice(0, 80),
|
|
446
|
+
app: ev.app ?? null,
|
|
447
|
+
};
|
|
448
|
+
appendAudit(id, { kind: 'shadow', shadow: true, at, text: entry.text, wouldChange: would });
|
|
449
|
+
try {
|
|
450
|
+
fs.appendFileSync(path.join(brainDir(id), 'shadow.jsonl'), `${JSON.stringify(entry)}\n`, 'utf8');
|
|
451
|
+
} catch (e) {
|
|
452
|
+
logOnce(`[brain] shadow 写入失败(已忽略):${e?.message ?? e}`);
|
|
453
|
+
}
|
|
361
454
|
return {
|
|
362
|
-
brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would,
|
|
455
|
+
brain, consistent, conflicting, label: null, shadow: true, evolved: false, remembered: false, wouldChange: would, shadowFile: path.join(brainDir(id), 'shadow.jsonl'),
|
|
363
456
|
};
|
|
364
457
|
}
|
|
365
458
|
|
|
366
459
|
// step:默认 1(每次 ±0.01)。只有传了 magnitude(重大转折)才放大,上限 5。
|
|
367
460
|
const step = Math.max(1, Math.min(5, Number(ev.magnitude) || 1));
|
|
368
461
|
if (doEvolve) {
|
|
462
|
+
const beforeW = new Map(brain.persona.units.map((u) => [u.id, u.weight]));
|
|
369
463
|
brain.persona.units = evolve(brain.persona.units, { consistent, conflicting, at, step });
|
|
370
464
|
|
|
465
|
+
// 记下这次的变动,攒成「最近」
|
|
466
|
+
const moves = [];
|
|
467
|
+
for (const u of brain.persona.units) {
|
|
468
|
+
const b = beforeW.get(u.id);
|
|
469
|
+
if (b !== undefined && b !== u.weight) {
|
|
470
|
+
moves.push({ id: u.id, delta: Number((u.weight - b).toFixed(4)), at });
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
if (moves.length) {
|
|
474
|
+
brain.persona.moves = [...(brain.persona.moves ?? []), ...moves].slice(-300);
|
|
475
|
+
// 按年累计,供年底蜕壳时总结"这一年我变了什么"
|
|
476
|
+
const ym = brain.persona.yearMoves ?? {};
|
|
477
|
+
for (const m of moves) ym[m.id] = Number(((ym[m.id] ?? 0) + m.delta).toFixed(4));
|
|
478
|
+
brain.persona.yearMoves = ym;
|
|
479
|
+
}
|
|
480
|
+
|
|
371
481
|
// 蜕皮
|
|
372
482
|
const sh = shed(brain.persona.units, { at });
|
|
373
483
|
if (sh.formerSelves.length) {
|
|
@@ -398,7 +508,9 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
398
508
|
? ev
|
|
399
509
|
: (ev.text ? { who: ev.who ?? ev.sender ?? '', what: String(ev.text).slice(0, 80), feel: ev.feel ?? '', via: ev.via ?? 'api' } : null);
|
|
400
510
|
if (doRemember && obs?.what) {
|
|
401
|
-
|
|
511
|
+
// 反复出现的事 → 重要记忆,永不压扁
|
|
512
|
+
const rep = detectRepeat(brain.memory, { who: obs.who ?? '', what: obs.what }, at);
|
|
513
|
+
const ep = addEpisode(brain.memory, {
|
|
402
514
|
who: obs.who ?? '',
|
|
403
515
|
what: obs.what,
|
|
404
516
|
feel: ev.feel ?? '',
|
|
@@ -409,7 +521,14 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
409
521
|
strategy: ev.action?.strategy ?? null,
|
|
410
522
|
evidence: obs.via ?? 'chat',
|
|
411
523
|
source: 'live',
|
|
524
|
+
...(rep.important ? { important: true, longTerm: true, importantCount: rep.count, importantSample: rep.sample } : {}),
|
|
412
525
|
}, at);
|
|
526
|
+
if (rep.important) {
|
|
527
|
+
// 追溯:之前提过的同话题也转重要,别让前两次被压成卡片
|
|
528
|
+
const back = markImportantByTopic(brain.memory, { who: obs.who ?? '', what: obs.what }, at);
|
|
529
|
+
appendAudit(id, { kind: 'important', count: rep.count, backfilled: back, what: String(obs.what).slice(0, 40) });
|
|
530
|
+
void ep;
|
|
531
|
+
}
|
|
413
532
|
}
|
|
414
533
|
|
|
415
534
|
if (doRemember && ev.action) {
|
|
@@ -454,6 +573,21 @@ export function observe(id = DEFAULT_ID, event = {}, opts = {}) {
|
|
|
454
573
|
im.lastAt = at;
|
|
455
574
|
if (ev.feel) im.traits = [...new Set([...(im.traits ?? []), ev.feel])].slice(-6);
|
|
456
575
|
brain.memory.impressions[who] = im;
|
|
576
|
+
|
|
577
|
+
// 恩情:谁对我好,是算出来的,不是写死的
|
|
578
|
+
// care = 真的照顾(充电、开窗、修我)base 8
|
|
579
|
+
// 普通互动 base 1;被凶了会扣
|
|
580
|
+
const isOwner = brain.relation?.address && who === brain.relation.address;
|
|
581
|
+
if (!isOwner) {
|
|
582
|
+
const base = ev.care ? 8 : 1;
|
|
583
|
+
const valence = Number.isFinite(Number(ev.valence)) ? Number(ev.valence) : 1;
|
|
584
|
+
const d = bondDelta({ traits: brain.persona.traits, base, valence });
|
|
585
|
+
if (d) {
|
|
586
|
+
addBond(brain.memory, who, { delta: d, at, what: ev.care ? 'care' : 'talk' });
|
|
587
|
+
const b = bondOf(brain.memory, who);
|
|
588
|
+
if (b.tier !== 'stranger') appendAudit(id, { kind: 'bond', who, delta: d, score: b.score, tier: b.tier });
|
|
589
|
+
}
|
|
590
|
+
}
|
|
457
591
|
}
|
|
458
592
|
|
|
459
593
|
brain.meta.observations += 1;
|
|
@@ -487,34 +621,78 @@ function bigrams(text) {
|
|
|
487
621
|
return set;
|
|
488
622
|
}
|
|
489
623
|
|
|
490
|
-
/**
|
|
624
|
+
/**
|
|
625
|
+
* 每日结算:人设衰减 + 记忆两层老化(压扁 → 遗忘)+ 蜕皮。幂等,可以随便跑。
|
|
626
|
+
*
|
|
627
|
+
* 老化不是"到期删除":先压扁成一句"大概",再更久没人提才真正遗忘。
|
|
628
|
+
* 全程把原文摊进 archive.jsonl——**忘的是检索,不是档案。**
|
|
629
|
+
*/
|
|
491
630
|
export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
|
|
492
631
|
const brain = ensureBrain(id);
|
|
493
632
|
const days = Math.max(0, (now - (brain.meta.lastSettle ?? now)) / (24 * 60 * 60 * 1000));
|
|
494
633
|
if (days >= 1) {
|
|
495
|
-
|
|
634
|
+
// ── 一年一度蜕壳:跨自然年时,把这一年掉出去的人设收进永久卡片 ──
|
|
635
|
+
const thisYear = new Date(now).getFullYear();
|
|
636
|
+
const prevYear = brain.persona.shellYear ?? thisYear;
|
|
637
|
+
if (thisYear > prevYear) {
|
|
638
|
+
const s = shellSummary(brain.persona.units, brain.memory.formerSelves, {
|
|
639
|
+
year: prevYear, at: now, yearMoves: brain.persona.yearMoves ?? {},
|
|
640
|
+
});
|
|
641
|
+
if (s.changed > 0) {
|
|
642
|
+
addCard(brain.memory, {
|
|
643
|
+
id: `shell_${prevYear}`,
|
|
644
|
+
kind: 'card',
|
|
645
|
+
title: s.title,
|
|
646
|
+
text: s.text,
|
|
647
|
+
at: now,
|
|
648
|
+
lastRecall: now,
|
|
649
|
+
expiresAt: now + 1000 * 365 * 24 * 60 * 60 * 1000,
|
|
650
|
+
consecutiveDays: 1,
|
|
651
|
+
longTerm: true,
|
|
652
|
+
// 永久:这是"我以前是谁"的唯一凭证,不许老化
|
|
653
|
+
important: true,
|
|
654
|
+
source: 'shell',
|
|
655
|
+
});
|
|
656
|
+
appendAudit(id, { kind: 'shell', year: prevYear, changed: s.changed, text: s.text.slice(0, 60) });
|
|
657
|
+
}
|
|
658
|
+
brain.persona.shellYear = thisYear;
|
|
659
|
+
brain.persona.shellAt = now;
|
|
660
|
+
brain.persona.yearMoves = {};
|
|
661
|
+
// 蜕了壳,「我是谁」要跟着重写
|
|
662
|
+
refreshNarrative(brain, 'shell');
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// 人设:只有长期没人碰的命题才褪色
|
|
666
|
+
brain.persona.units = decay(brain.persona.units, Math.floor(days), now, { quietDays: compressDays });
|
|
496
667
|
const sh = shed(brain.persona.units, { at: now });
|
|
497
668
|
if (sh.formerSelves.length) {
|
|
498
669
|
brain.persona.units = sh.units;
|
|
499
670
|
brain.memory.formerSelves.push(...sh.formerSelves);
|
|
671
|
+
for (const f of sh.formerSelves) {
|
|
672
|
+
appendAudit(id, { kind: 'shed', id: f.id, weight: Number(f.weight.toFixed(3)), memoir: f.memoir });
|
|
673
|
+
}
|
|
500
674
|
}
|
|
501
675
|
|
|
502
676
|
if (ttlPolicy === 'summarize' || ttlPolicy === 'archive') {
|
|
503
|
-
// 过期前先压一张卡片——"忘了细节,但记得大概"
|
|
504
677
|
const card = makeCard(brain.memory.episodes.slice(-12));
|
|
505
678
|
if (card) addCard(brain.memory, card);
|
|
506
679
|
}
|
|
507
680
|
|
|
508
|
-
const
|
|
509
|
-
if (ttlPolicy !== 'off')
|
|
681
|
+
const archived = [];
|
|
682
|
+
if (ttlPolicy !== 'off') {
|
|
683
|
+
settle(brain.memory, now, {
|
|
684
|
+
compressDays,
|
|
685
|
+
forgetDays,
|
|
686
|
+
onArchive: (item, reason) => archived.push({ ...item, archiveReason: reason }),
|
|
687
|
+
});
|
|
688
|
+
}
|
|
510
689
|
|
|
511
|
-
//
|
|
512
|
-
if (
|
|
690
|
+
// 原文一律留档:压扁的和遗忘的都写进 archive.jsonl
|
|
691
|
+
if (archived.length) {
|
|
513
692
|
try {
|
|
514
|
-
const newly = brain.memory.forgotten.slice(before);
|
|
515
693
|
fs.appendFileSync(
|
|
516
694
|
path.join(brainDir(id), 'archive.jsonl'),
|
|
517
|
-
`${
|
|
695
|
+
`${archived.map((x) => JSON.stringify(x)).join('\n')}\n`,
|
|
518
696
|
'utf8',
|
|
519
697
|
);
|
|
520
698
|
} catch (e) {
|
|
@@ -525,9 +703,18 @@ export function settleBrain(id = DEFAULT_ID, now = nowMs()) {
|
|
|
525
703
|
brain.memory.forgotten = brain.memory.forgotten.slice(-500);
|
|
526
704
|
}
|
|
527
705
|
|
|
706
|
+
// 提炼纲和伞:细节会烂,但"我认识他""这事发生过""我上过学"不能跟着烂
|
|
707
|
+
try {
|
|
708
|
+
distillGists(brain.memory, now);
|
|
709
|
+
distillUmbrellas(brain.memory, now);
|
|
710
|
+
} catch (e) {
|
|
711
|
+
logOnce(`[brain] 纲/伞提炼失败(已忽略):${e?.message ?? e}`);
|
|
712
|
+
}
|
|
713
|
+
|
|
528
714
|
brain.meta.lastSettle = now;
|
|
529
715
|
refreshBrief(brain);
|
|
530
716
|
saveBrain(brain);
|
|
717
|
+
if (archived.length) appendAudit(id, { kind: 'aging', archived: archived.length });
|
|
531
718
|
}
|
|
532
719
|
return brain;
|
|
533
720
|
}
|
|
@@ -596,7 +783,11 @@ export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' }
|
|
|
596
783
|
const what = String(it?.text ?? it?.what ?? '').trim();
|
|
597
784
|
if (!what) { skipped += 1; continue; }
|
|
598
785
|
const at = Number(it?.at) || nowMs();
|
|
786
|
+
// ⚠️ 第三个参数必须是「现在」,不是 at。
|
|
787
|
+
// 它同时决定 lastRecall(多久没被提起);传历史时间会让刚搬进来的记忆
|
|
788
|
+
// 一出生就过期,第一次结算就被清空。
|
|
599
789
|
addEpisode(brain.memory, {
|
|
790
|
+
at,
|
|
600
791
|
who: it.who ?? '',
|
|
601
792
|
what: what.slice(0, 140),
|
|
602
793
|
feel: it.feel ?? '',
|
|
@@ -606,8 +797,10 @@ export function importEpisodes(id = DEFAULT_ID, list = [], { source = 'import' }
|
|
|
606
797
|
context: it.context ?? null,
|
|
607
798
|
strategy: it.strategy ?? null,
|
|
608
799
|
evidence: it.via ?? source,
|
|
609
|
-
source, // live | import
|
|
610
|
-
|
|
800
|
+
source, // live | import | diary
|
|
801
|
+
// 搬进来的是「已经沉淀过的」——它在宿主那边活过了,不该再按新经历老化
|
|
802
|
+
...(source === 'import' ? { longTerm: Boolean(it.longTerm ?? false) } : {}),
|
|
803
|
+
}, nowMs());
|
|
611
804
|
imported += 1;
|
|
612
805
|
const who = String(it.who ?? '').trim();
|
|
613
806
|
if (who) touched.set(who, (touched.get(who) ?? 0) + 1);
|
|
@@ -732,8 +925,7 @@ export function learnEmotion(id = DEFAULT_ID, word, { pad, sources = [], cause =
|
|
|
732
925
|
}
|
|
733
926
|
|
|
734
927
|
/** 阶段三:从 ≥3 个实例里自己归纳出这个词的含义。 */
|
|
735
|
-
export function induceEmotion(id = DEFAULT_ID, word) {
|
|
736
|
-
const brain = ensureBrain(id);
|
|
928
|
+
export function induceEmotion(id = DEFAULT_ID, word) { const brain = ensureBrain(id);
|
|
737
929
|
const r = emotion.induce(brain.vocab, word);
|
|
738
930
|
if (r.induced) {
|
|
739
931
|
brain.vocab = r.vocab;
|
|
@@ -752,6 +944,67 @@ export function vocabOf(id = DEFAULT_ID) {
|
|
|
752
944
|
};
|
|
753
945
|
}
|
|
754
946
|
|
|
947
|
+
/**
|
|
948
|
+
* 给老鱼预装一份情绪词表。
|
|
949
|
+
*
|
|
950
|
+
* **新鱼用不到**——她该从"说不清"开始学。
|
|
951
|
+
* 但一条活了两年的鱼搬进来,不该从"哼哼"开始。
|
|
952
|
+
*/
|
|
953
|
+
export const BASIC_VOCAB = ['委屈', '生气', '高兴', '失落', '烦', '慌', '得意', '无聊', '累', '暖'];
|
|
954
|
+
|
|
955
|
+
export function seedVocab(id = DEFAULT_ID, words = BASIC_VOCAB) {
|
|
956
|
+
const brain = ensureBrain(id);
|
|
957
|
+
let added = 0;
|
|
958
|
+
for (const w of words) {
|
|
959
|
+
if (brain.vocab[w]) continue;
|
|
960
|
+
const p = emotion.PROTOTYPES[w];
|
|
961
|
+
if (!p) continue;
|
|
962
|
+
brain.vocab[w] = {
|
|
963
|
+
pad: [...p.pad],
|
|
964
|
+
cause: p.cause,
|
|
965
|
+
body: p.body,
|
|
966
|
+
action: p.action,
|
|
967
|
+
instances: [],
|
|
968
|
+
sources: ['seed'],
|
|
969
|
+
learnedAt: Date.now(),
|
|
970
|
+
};
|
|
971
|
+
added += 1;
|
|
972
|
+
}
|
|
973
|
+
saveBrain(brain);
|
|
974
|
+
appendAudit(id, { kind: 'seed-vocab', added, total: Object.keys(brain.vocab).length });
|
|
975
|
+
return { ok: true, added, total: Object.keys(brain.vocab).length, stage: emotion.stageOf(brain.vocab) };
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* 精确导入词表(来自 exportPack,或别的系统导出的)。
|
|
980
|
+
* @param {Array} list [{ word, pad:[p,a,d], cause, body, action, instances }]
|
|
981
|
+
*/
|
|
982
|
+
export function importVocab(id = DEFAULT_ID, list = []) {
|
|
983
|
+
const brain = ensureBrain(id);
|
|
984
|
+
let imported = 0;
|
|
985
|
+
for (const it of Array.isArray(list) ? list : []) {
|
|
986
|
+
const word = String(it?.word ?? it?.name ?? '').trim();
|
|
987
|
+
if (!word) continue;
|
|
988
|
+
const proto = emotion.PROTOTYPES[word] ?? {};
|
|
989
|
+
const pad = Array.isArray(it.pad)
|
|
990
|
+
? [0, 1, 2].map((i) => Math.max(-1, Math.min(1, Number(it.pad[i]) || 0)))
|
|
991
|
+
: (proto.pad ?? [0, 0, 0]);
|
|
992
|
+
brain.vocab[word] = {
|
|
993
|
+
pad,
|
|
994
|
+
cause: it.cause ?? proto.cause ?? '',
|
|
995
|
+
body: it.body ?? proto.body ?? '',
|
|
996
|
+
action: it.action ?? proto.action ?? '',
|
|
997
|
+
instances: Array.isArray(it.instances) ? it.instances.slice(-20) : [],
|
|
998
|
+
sources: [...new Set([...(it.sources ?? []), 'import'])].slice(-8),
|
|
999
|
+
learnedAt: Number(it.learnedAt) || Date.now(),
|
|
1000
|
+
};
|
|
1001
|
+
imported += 1;
|
|
1002
|
+
}
|
|
1003
|
+
saveBrain(brain);
|
|
1004
|
+
appendAudit(id, { kind: 'import-vocab', imported, total: Object.keys(brain.vocab).length });
|
|
1005
|
+
return { ok: true, imported, total: Object.keys(brain.vocab).length, stage: emotion.stageOf(brain.vocab) };
|
|
1006
|
+
}
|
|
1007
|
+
|
|
755
1008
|
/* ── 记忆卡片:上下文过长时压缩中段 ───────────────────────────── */
|
|
756
1009
|
|
|
757
1010
|
export function needsCard(id = DEFAULT_ID, contextChars = 0) {
|
|
@@ -1151,28 +1404,35 @@ export const MAX_EPISODES = 5000;
|
|
|
1151
1404
|
|
|
1152
1405
|
/**
|
|
1153
1406
|
* 容量保护:最老的一批压成卡片,原文进 archive.jsonl。
|
|
1154
|
-
*
|
|
1407
|
+
*
|
|
1408
|
+
* 不是"一次吃掉两百条"——按 20 条一张卡片分批压,别让一次溢出把半年吃成 160 字。
|
|
1155
1409
|
*/
|
|
1156
1410
|
function enforceCapacity(brain) {
|
|
1157
1411
|
const eps = brain.memory.episodes;
|
|
1158
|
-
if (eps.length <=
|
|
1159
|
-
const overflow = eps.length -
|
|
1160
|
-
const take = Math.min(overflow
|
|
1412
|
+
if (eps.length <= maxEpisodes) return { compacted: 0, cards: 0 };
|
|
1413
|
+
const overflow = eps.length - maxEpisodes;
|
|
1414
|
+
const take = Math.min(overflow, eps.length);
|
|
1161
1415
|
const oldest = eps.slice(0, take);
|
|
1162
|
-
|
|
1163
|
-
|
|
1416
|
+
|
|
1417
|
+
let cards = 0;
|
|
1418
|
+
for (let i = 0; i < oldest.length; i += 20) {
|
|
1419
|
+
const chunk = oldest.slice(i, i + 20);
|
|
1420
|
+
const card = makeCard(chunk);
|
|
1421
|
+
if (card) { addCard(brain.memory, card); cards += 1; }
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1164
1424
|
try {
|
|
1165
1425
|
fs.appendFileSync(
|
|
1166
1426
|
path.join(brainDir(brain.id), 'archive.jsonl'),
|
|
1167
|
-
`${oldest.map((x) => JSON.stringify(x)).join('\n')}\n`,
|
|
1427
|
+
`${oldest.map((x) => JSON.stringify({ ...x, archiveReason: 'capacity' })).join('\n')}\n`,
|
|
1168
1428
|
'utf8',
|
|
1169
1429
|
);
|
|
1170
1430
|
} catch (e) {
|
|
1171
1431
|
logOnce(`[brain] 容量归档失败(已忽略):${e?.message ?? e}`);
|
|
1172
1432
|
}
|
|
1173
1433
|
brain.memory.episodes = eps.slice(take);
|
|
1174
|
-
appendAudit(brain.id, { kind: 'capacity', compacted: take });
|
|
1175
|
-
return { compacted: take,
|
|
1434
|
+
appendAudit(brain.id, { kind: 'capacity', compacted: take, cards });
|
|
1435
|
+
return { compacted: take, cards };
|
|
1176
1436
|
}
|
|
1177
1437
|
|
|
1178
1438
|
/**
|
|
@@ -1363,6 +1623,35 @@ export function listDiary(id = DEFAULT_ID) {
|
|
|
1363
1623
|
.sort((a, b) => (a.date < b.date ? 1 : -1));
|
|
1364
1624
|
}
|
|
1365
1625
|
|
|
1626
|
+
/**
|
|
1627
|
+
* 把**她以前写过的日记**搬进来。
|
|
1628
|
+
*
|
|
1629
|
+
* 不是把流水账重新生成一遍——那是造假。原样拷贝,一个字不改。
|
|
1630
|
+
* @param {Array} list [{ date:'2025-11-20', text:'...' }]
|
|
1631
|
+
*/
|
|
1632
|
+
export function importDiary(id = DEFAULT_ID, list = [], { overwrite = false } = {}) {
|
|
1633
|
+
const brain = ensureBrain(id);
|
|
1634
|
+
const dir = diaryDir(id);
|
|
1635
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1636
|
+
let imported = 0;
|
|
1637
|
+
let skipped = 0;
|
|
1638
|
+
for (const it of Array.isArray(list) ? list : []) {
|
|
1639
|
+
const date = String(it?.date ?? '').trim();
|
|
1640
|
+
const text = String(it?.text ?? '').trim();
|
|
1641
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !text) { skipped += 1; continue; }
|
|
1642
|
+
const file = diaryPath(id, date);
|
|
1643
|
+
if (fs.existsSync(file) && !overwrite) { skipped += 1; continue; }
|
|
1644
|
+
fs.writeFileSync(file, text.endsWith('\n') ? text : `${text}\n`, 'utf8');
|
|
1645
|
+
if (!Array.isArray(brain.meta.diary)) brain.meta.diary = [];
|
|
1646
|
+
if (!brain.meta.diary.includes(date)) brain.meta.diary.push(date);
|
|
1647
|
+
imported += 1;
|
|
1648
|
+
}
|
|
1649
|
+
brain.meta.diary = (brain.meta.diary ?? []).slice(-400);
|
|
1650
|
+
saveBrain(brain);
|
|
1651
|
+
appendAudit(id, { kind: 'import-diary', imported, skipped });
|
|
1652
|
+
return { ok: true, imported, skipped, days: listDiary(id).length };
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1366
1655
|
/** 日记也能被检索:问"你写过什么"时用它 */
|
|
1367
1656
|
export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
|
|
1368
1657
|
const list = listDiary(id);
|
|
@@ -1378,6 +1667,346 @@ export function recallDiary(id = DEFAULT_ID, word = '', { limit = 3 } = {}) {
|
|
|
1378
1667
|
return hits;
|
|
1379
1668
|
}
|
|
1380
1669
|
|
|
1670
|
+
/* ── 特质:开放维度(她自己长出来的)────────────────────────── */
|
|
1671
|
+
|
|
1672
|
+
/**
|
|
1673
|
+
* 模型提名一个新维度(B 路径)。
|
|
1674
|
+
*
|
|
1675
|
+
* 脑不做"理解"——理解是模型的事。模型读完对话觉得"她今天很上头",
|
|
1676
|
+
* 就调这个把「上头」登记成她的一个维度,脑负责存、算、衰减、蜕皮。
|
|
1677
|
+
*/
|
|
1678
|
+
export function defineTrait(id = DEFAULT_ID, name = '', weight = 0.6, { source = 'model' } = {}) {
|
|
1679
|
+
const brain = ensureBrain(id);
|
|
1680
|
+
const n = String(name ?? '').trim();
|
|
1681
|
+
if (n.length < 2 || n.length > 8) return { ok: false, reason: '维度名 2~8 个字' };
|
|
1682
|
+
const w = Number.isFinite(Number(weight)) ? Math.max(0, Math.min(1, Number(weight))) : 0.6;
|
|
1683
|
+
|
|
1684
|
+
brain.persona.traits = { ...(brain.persona.traits ?? {}), [n]: w };
|
|
1685
|
+
brain.persona.openTraits = { ...(brain.persona.openTraits ?? {}), [n]: w };
|
|
1686
|
+
brain.self.style = styleVector(brain.persona.traits);
|
|
1687
|
+
brain.self.styleName = dominantStyle(brain.self.style);
|
|
1688
|
+
saveBrain(brain);
|
|
1689
|
+
appendAudit(id, { kind: 'define-trait', name: n, weight: w, source });
|
|
1690
|
+
return { ok: true, name: n, weight: w, total: Object.keys(brain.persona.traits).length };
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
/**
|
|
1694
|
+
* 看她现在有哪些维度:哪些是先验的,哪些是她自己长出来的。
|
|
1695
|
+
*/
|
|
1696
|
+
export function traitReport(id = DEFAULT_ID) {
|
|
1697
|
+
const brain = ensureBrain(id);
|
|
1698
|
+
const known = new Set(Object.keys(brain.persona.knownTraits ?? TRAIT_LEXICON));
|
|
1699
|
+
const rows = Object.entries(brain.persona.traits ?? {})
|
|
1700
|
+
.map(([name, weight]) => ({
|
|
1701
|
+
name,
|
|
1702
|
+
weight: Number(Number(weight).toFixed(2)),
|
|
1703
|
+
kind: known.has(name) ? 'known' : 'open',
|
|
1704
|
+
}))
|
|
1705
|
+
.sort((a, b) => b.weight - a.weight);
|
|
1706
|
+
return {
|
|
1707
|
+
total: rows.length,
|
|
1708
|
+
known: rows.filter((r) => r.kind === 'known').length,
|
|
1709
|
+
open: rows.filter((r) => r.kind === 'open').length,
|
|
1710
|
+
rows,
|
|
1711
|
+
openRows: rows.filter((r) => r.kind === 'open'),
|
|
1712
|
+
};
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/**
|
|
1716
|
+
* 模型提名一条纲(B 路径)。
|
|
1717
|
+
*
|
|
1718
|
+
* 算法只能从字面统计出"什么词反复出现",但**"这意味着什么"要靠理解**。
|
|
1719
|
+
* 模型看完对话觉得"她好像把上学当成一件很重的事",就调这个把它记成纲。
|
|
1720
|
+
*/
|
|
1721
|
+
export function defineGist(id = DEFAULT_ID, text = '', { keyword = '', count = 1 } = {}) {
|
|
1722
|
+
const brain = ensureBrain(id);
|
|
1723
|
+
const t = String(text ?? '').trim();
|
|
1724
|
+
if (t.length < 4) return { ok: false, reason: '纲至少 4 个字' };
|
|
1725
|
+
if (!Array.isArray(brain.memory.gists)) brain.memory.gists = [];
|
|
1726
|
+
const key = keyword || t.slice(0, 8);
|
|
1727
|
+
const id2 = `g_${key}`;
|
|
1728
|
+
const existed = brain.memory.gists.find((g) => g.id === id2);
|
|
1729
|
+
if (existed) {
|
|
1730
|
+
existed.text = t;
|
|
1731
|
+
existed.count = Number(count) || existed.count;
|
|
1732
|
+
existed.at = nowMs();
|
|
1733
|
+
} else {
|
|
1734
|
+
brain.memory.gists.push({
|
|
1735
|
+
id: id2, kind: 'gist', topic: 'model', keyword: key, text: t, count: Number(count) || 1, at: nowMs(),
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
saveBrain(brain);
|
|
1739
|
+
appendAudit(id, { kind: 'define-gist', keyword: key, text: t.slice(0, 50) });
|
|
1740
|
+
return { ok: true, id: id2, total: brain.memory.gists.length };
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
/**
|
|
1744
|
+
* 标记「那个人不在了」。
|
|
1745
|
+
*
|
|
1746
|
+
* 不是解除关系——契约照旧永久,称呼照旧,记忆一条不删。
|
|
1747
|
+
* 变的只是:她知道了,他不会再来。
|
|
1748
|
+
*
|
|
1749
|
+
* **必须显式调用。** 不许系统凭"多久没说话"去猜一个人死没死。
|
|
1750
|
+
*/
|
|
1751
|
+
export function markAbsent(id = DEFAULT_ID, { since, note = '', status = 'absent' } = {}) {
|
|
1752
|
+
const brain = ensureBrain(id);
|
|
1753
|
+
if (!brain.relation) return { ok: false, reason: '没有关系契约' };
|
|
1754
|
+
brain.relation = markAbsentContract(brain.relation, { since, note, status });
|
|
1755
|
+
// 他的人物伞改成"曾经一直在"——但伞本身不删
|
|
1756
|
+
for (const u of brain.memory.umbrellas ?? []) {
|
|
1757
|
+
if (u.topic === 'person' && u.who && u.who === brain.relation.address) {
|
|
1758
|
+
u.absent = true;
|
|
1759
|
+
u.text = `${u.who}:曾经一直在的人`;
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
saveBrain(brain);
|
|
1763
|
+
appendAudit(id, { kind: 'absent', address: brain.relation.address, since: brain.relation.absentSince, note });
|
|
1764
|
+
return { ok: true, relation: brain.relation, line: relationLine(brain.relation) };
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
/** 人回来了 / 标错了 */
|
|
1768
|
+
export function clearAbsent(id = DEFAULT_ID) {
|
|
1769
|
+
const brain = ensureBrain(id);
|
|
1770
|
+
brain.relation = clearAbsentRelation(brain.relation);
|
|
1771
|
+
for (const u of brain.memory.umbrellas ?? []) {
|
|
1772
|
+
if (u.topic === 'person' && u.absent) {
|
|
1773
|
+
u.absent = false;
|
|
1774
|
+
u.text = `${u.who}:一直在的人`;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
saveBrain(brain);
|
|
1778
|
+
appendAudit(id, { kind: 'absent-cleared', address: brain.relation?.address ?? '' });
|
|
1779
|
+
return { ok: true, relation: brain.relation };
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
/* ── 概念:什么是什么,为什么要这么做 ───────────────────────── */
|
|
1783
|
+
|
|
1784
|
+
/**
|
|
1785
|
+
* 有人给她解释一个词。
|
|
1786
|
+
*
|
|
1787
|
+
* **这是"想通了"的那一刻**:不是新增记忆,是让过去几十条经历突然有了名字。
|
|
1788
|
+
*
|
|
1789
|
+
* learnConcept('old', '上学', {
|
|
1790
|
+
* definition: '为了学到知识、学会道理',
|
|
1791
|
+
* why: '不然什么都不会',
|
|
1792
|
+
* })
|
|
1793
|
+
*/
|
|
1794
|
+
export function learnNewConcept(id = DEFAULT_ID, term = '', { definition = '', why = '', source = 'told', who = '' } = {}) {
|
|
1795
|
+
const brain = ensureBrain(id);
|
|
1796
|
+
const r = learnConcept(brain.memory, term, { definition, why, source, who, at: nowMs() });
|
|
1797
|
+
if (!r.ok) return r;
|
|
1798
|
+
refreshNarrative(id, 'concept');
|
|
1799
|
+
saveBrain(brain);
|
|
1800
|
+
appendAudit(id, { kind: 'concept', term: r.term, linked: r.linked, source });
|
|
1801
|
+
return r;
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/** 问她「X 是什么」——不知道就说不知道,不编 */
|
|
1805
|
+
export function askWhat(id = DEFAULT_ID, term = '') {
|
|
1806
|
+
return conceptAnswer(ensureBrain(id).memory, term);
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
/** 她自己去问(因为不会才问,这才叫学习) */
|
|
1810
|
+
export function askSomeone(id = DEFAULT_ID, term = '', { knower = '' } = {}) {
|
|
1811
|
+
const brain = ensureBrain(id);
|
|
1812
|
+
const q = makeQuestion(brain.memory, term, { knower });
|
|
1813
|
+
if (q.asked) appendAudit(id, { kind: 'ask', term: q.term, to: knower });
|
|
1814
|
+
return q;
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
export function conceptList(id = DEFAULT_ID) {
|
|
1818
|
+
const brain = ensureBrain(id);
|
|
1819
|
+
const list = Object.values(brain.memory.concepts ?? {});
|
|
1820
|
+
return {
|
|
1821
|
+
total: list.length,
|
|
1822
|
+
terms: list.map((c) => c.term),
|
|
1823
|
+
detail: list,
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
/* ── 自我叙事:我是谁(会长的,不是写死的)────────────────────── */
|
|
1828
|
+
|
|
1829
|
+
/**
|
|
1830
|
+
* 重写「我是谁」。
|
|
1831
|
+
*
|
|
1832
|
+
* 用她自己的零件拼:出身 → 学会的道理 → 变过几次 → 谁一直在。
|
|
1833
|
+
* 每一版都留下来——将来能说"我以前以为自己是……"。
|
|
1834
|
+
*/
|
|
1835
|
+
export function refreshNarrative(idOrBrain = DEFAULT_ID, why = 'auto') {
|
|
1836
|
+
const fromId = typeof idOrBrain === 'string';
|
|
1837
|
+
const brain = fromId ? ensureBrain(idOrBrain) : idOrBrain;
|
|
1838
|
+
if (!brain) return { changed: false, text: '' };
|
|
1839
|
+
const next = composeNarrative({
|
|
1840
|
+
cardName: brain.roleCard ?? '鱼',
|
|
1841
|
+
traits: brain.persona.traits,
|
|
1842
|
+
umbrellas: brain.memory.umbrellas ?? [],
|
|
1843
|
+
concepts: brain.memory.concepts ?? {},
|
|
1844
|
+
shells: (brain.memory.cards ?? []).filter((c) => c.source === 'shell').length,
|
|
1845
|
+
relation: brain.relation,
|
|
1846
|
+
});
|
|
1847
|
+
const prev = brain.self?.narrativeText ?? (typeof brain.self?.narrative === 'string' ? brain.self.narrative : '');
|
|
1848
|
+
if (!narrativeChanged(prev, next)) {
|
|
1849
|
+
if (fromId) { /* 没变也要落盘,保证首版存在 */ saveBrain(brain); }
|
|
1850
|
+
return { changed: false, text: next, version: (brain.self?.narrativeHistory ?? []).length };
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
brain.self = brain.self ?? {};
|
|
1854
|
+
brain.self.narrativeText = next;
|
|
1855
|
+
brain.self.narrative = next;
|
|
1856
|
+
if (!Array.isArray(brain.self.narrativeHistory)) brain.self.narrativeHistory = [];
|
|
1857
|
+
brain.self.narrativeHistory = [...brain.self.narrativeHistory, { text: next, at: nowMs(), why }].slice(-12);
|
|
1858
|
+
if (fromId) { saveBrain(brain); appendAudit(idOrBrain, { kind: 'narrative', why, text: next.slice(0, 60) }); }
|
|
1859
|
+
return { changed: true, text: next, version: brain.self.narrativeHistory.length };
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
/** 模型改写「我是谁」(理解是模型的事,脑只负责存和留档) */
|
|
1863
|
+
export function setNarrative(id = DEFAULT_ID, text = '', { why = 'model' } = {}) {
|
|
1864
|
+
const brain = ensureBrain(id);
|
|
1865
|
+
const t = String(text ?? '').trim();
|
|
1866
|
+
if (t.length < 6) return { ok: false, reason: '太短了' };
|
|
1867
|
+
brain.self = brain.self ?? {};
|
|
1868
|
+
brain.self.narrativeText = t.slice(0, NARRATIVE_MAX);
|
|
1869
|
+
brain.self.narrative = brain.self.narrativeText;
|
|
1870
|
+
if (!Array.isArray(brain.self.narrativeHistory)) brain.self.narrativeHistory = [];
|
|
1871
|
+
brain.self.narrativeHistory = [...brain.self.narrativeHistory, { text: brain.self.narrativeText, at: nowMs(), why }].slice(-12);
|
|
1872
|
+
saveBrain(brain);
|
|
1873
|
+
appendAudit(id, { kind: 'narrative', why, text: brain.self.narrativeText.slice(0, 60) });
|
|
1874
|
+
return { ok: true, text: brain.self.narrativeText, version: brain.self.narrativeHistory.length };
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
export function narrativeOf(id = DEFAULT_ID) {
|
|
1878
|
+
const b = ensureBrain(id);
|
|
1879
|
+
return {
|
|
1880
|
+
text: b.self?.narrativeText ?? b.self?.narrative ?? '',
|
|
1881
|
+
history: b.self?.narrativeHistory ?? [],
|
|
1882
|
+
version: (b.self?.narrativeHistory ?? []).length,
|
|
1883
|
+
};
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* 给一个**不是主人**的人标缺位(B 路径)。
|
|
1888
|
+
*
|
|
1889
|
+
* 主人走的是 relation.absent;爷爷奶奶、小主人这类人走这里。
|
|
1890
|
+
* 门槛:恩情要到「对我挺好的」(close)以上——才配得上"我记住他不在了"。
|
|
1891
|
+
*/
|
|
1892
|
+
export function markAbsentFor(id = DEFAULT_ID, who = '', { since, note = '', status = 'absent' } = {}) {
|
|
1893
|
+
const brain = ensureBrain(id);
|
|
1894
|
+
const name = String(who ?? '').trim();
|
|
1895
|
+
if (!name) return { ok: false, reason: '没说谁' };
|
|
1896
|
+
if (name === brain.relation?.address) {
|
|
1897
|
+
return markAbsent(id, { since, note, status });
|
|
1898
|
+
}
|
|
1899
|
+
const r = markBondAbsent(brain.memory, name, { since: since ?? nowMs(), note, status });
|
|
1900
|
+
if (!r.ok) return r;
|
|
1901
|
+
saveBrain(brain);
|
|
1902
|
+
appendAudit(id, { kind: 'absent-bond', who: name, note });
|
|
1903
|
+
return { ok: true, absence: r.absence, bond: r.bond, line: bondLine(brain.memory, name) };
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
export function clearAbsentFor(id = DEFAULT_ID, who = '') {
|
|
1907
|
+
const brain = ensureBrain(id);
|
|
1908
|
+
if (who === brain.relation?.address) return clearAbsent(id);
|
|
1909
|
+
clearBondAbsent(brain.memory, who);
|
|
1910
|
+
saveBrain(brain);
|
|
1911
|
+
return { ok: true, who };
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/**
|
|
1915
|
+
* 老版本 brain.json 的形状补齐。
|
|
1916
|
+
*
|
|
1917
|
+
* 1.2.0 时代的 brain.json 没有 vocab / gists / concepts / bonds…,
|
|
1918
|
+
* 新版代码直接读就会崩。崩在宿主里 = 注入段拿不到 = **她一夜之间变冷淡**。
|
|
1919
|
+
*
|
|
1920
|
+
* 升级不该让一条活了几年的鱼突然失语,所以这里全部兜住。
|
|
1921
|
+
*/
|
|
1922
|
+
function normalizeBrain(brain) {
|
|
1923
|
+
if (!brain || typeof brain !== 'object') return brain;
|
|
1924
|
+
const M = emptyMemory();
|
|
1925
|
+
brain.memory = { ...M, ...(brain.memory ?? {}) };
|
|
1926
|
+
for (const k of ['facts', 'taste', 'impressions', 'apps', 'strategies']) {
|
|
1927
|
+
if (!brain.memory[k] || typeof brain.memory[k] !== 'object') brain.memory[k] = {};
|
|
1928
|
+
}
|
|
1929
|
+
for (const k of ['episodes', 'imagination', 'cards', 'gists', 'formerSelves', 'forgotten', 'pending', 'umbrellas']) {
|
|
1930
|
+
if (!Array.isArray(brain.memory[k])) brain.memory[k] = [];
|
|
1931
|
+
}
|
|
1932
|
+
for (const k of ['concepts', 'bonds', 'absences']) {
|
|
1933
|
+
if (!brain.memory[k] || typeof brain.memory[k] !== 'object') brain.memory[k] = {};
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
brain.vocab = (brain.vocab && typeof brain.vocab === 'object') ? brain.vocab : {};
|
|
1937
|
+
brain.persona = brain.persona ?? {};
|
|
1938
|
+
if (!Array.isArray(brain.persona.units)) brain.persona.units = [];
|
|
1939
|
+
if (!brain.persona.traits || typeof brain.persona.traits !== 'object') brain.persona.traits = {};
|
|
1940
|
+
if (!Array.isArray(brain.persona.moves)) brain.persona.moves = [];
|
|
1941
|
+
if (!brain.persona.yearMoves || typeof brain.persona.yearMoves !== 'object') brain.persona.yearMoves = {};
|
|
1942
|
+
if (!brain.persona.brief) brain.persona.brief = '';
|
|
1943
|
+
|
|
1944
|
+
brain.self = brain.self ?? {};
|
|
1945
|
+
if (!Array.isArray(brain.self.narrativeHistory)) brain.self.narrativeHistory = [];
|
|
1946
|
+
brain.meta = brain.meta ?? {};
|
|
1947
|
+
if (!Array.isArray(brain.meta.contractWarnings)) brain.meta.contractWarnings = [];
|
|
1948
|
+
if (!Number.isFinite(brain.meta.observations)) brain.meta.observations = 0;
|
|
1949
|
+
return brain;
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/* ── 嘴:她说一句话(接模型)────────────────────────────────── */
|
|
1953
|
+
|
|
1954
|
+
/**
|
|
1955
|
+
* 让她说一句。
|
|
1956
|
+
*
|
|
1957
|
+
* ① 取「此刻的她」→ ② 拼 system → ③ 调模型 → ④ 把这一轮记回去
|
|
1958
|
+
*
|
|
1959
|
+
* 不给 key 不会崩,会明确返回 E_NO_LLM。
|
|
1960
|
+
*
|
|
1961
|
+
* @param {object} [mouth] createMouth() 的返回值;不传就用环境变量现造
|
|
1962
|
+
*/
|
|
1963
|
+
export async function speak(id = DEFAULT_ID, event = {}, { mouth = null, sections = null, budget = 500, extra = '' } = {}) {
|
|
1964
|
+
const brain = ensureBrain(id);
|
|
1965
|
+
const state = wakeLine(id, event, {
|
|
1966
|
+
sections: sections ?? ['persona', 'self', 'relation', 'bond', 'concept', 'mood', 'recent', 'memory'],
|
|
1967
|
+
budget,
|
|
1968
|
+
});
|
|
1969
|
+
|
|
1970
|
+
let m = mouth;
|
|
1971
|
+
if (!m) {
|
|
1972
|
+
const { createMouth } = await import('./lib/llm.mjs');
|
|
1973
|
+
m = createMouth();
|
|
1974
|
+
}
|
|
1975
|
+
if (!m.configured) {
|
|
1976
|
+
return {
|
|
1977
|
+
ok: false,
|
|
1978
|
+
code: 'E_NO_LLM',
|
|
1979
|
+
text: '她张了张嘴,但没地方说话(没配模型:设 FEIYU_LLM_KEY,或传 mouth)',
|
|
1980
|
+
state,
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
const { buildSystemPrompt } = await import('./lib/llm.mjs');
|
|
1985
|
+
const sender = event?.sender ?? event?.who ?? '';
|
|
1986
|
+
const userText = String(event?.text ?? '').slice(0, 400);
|
|
1987
|
+
const r = await m.say({
|
|
1988
|
+
system: buildSystemPrompt(state, { extra }),
|
|
1989
|
+
messages: userText ? [{ role: 'user', content: `${sender ? `${sender}:` : ''}${userText}` }] : [],
|
|
1990
|
+
});
|
|
1991
|
+
if (!r.ok) return { ...r, state };
|
|
1992
|
+
|
|
1993
|
+
// 说出去的话也算一次经历——她会记得自己说过
|
|
1994
|
+
try {
|
|
1995
|
+
observe(id, {
|
|
1996
|
+
who: sender,
|
|
1997
|
+
text: `我说:${r.text}`,
|
|
1998
|
+
what: `我说:${r.text}`.slice(0, 80),
|
|
1999
|
+
via: 'mouth',
|
|
2000
|
+
valence: 0.2,
|
|
2001
|
+
intensity: 0.3,
|
|
2002
|
+
}, { evolve: true });
|
|
2003
|
+
} catch (e) {
|
|
2004
|
+
logOnce(`[brain] 说完没记上(已忽略):${e?.message ?? e}`);
|
|
2005
|
+
}
|
|
2006
|
+
|
|
2007
|
+
return { ok: true, text: r.text, state, model: r.model ?? null, usage: r.usage ?? null };
|
|
2008
|
+
}
|
|
2009
|
+
|
|
1381
2010
|
export function snapshot(id = DEFAULT_ID) {
|
|
1382
2011
|
const brain = ensureBrain(id);
|
|
1383
2012
|
const level = flowLevel(brain.state, { boredom: brain.drive.boredom });
|
|
@@ -1510,6 +2139,10 @@ export function createBrain(options = {}) {
|
|
|
1510
2139
|
writeDiary(opts) { return writeDiary(id, opts); },
|
|
1511
2140
|
readDiary(date) { return readDiary(id, date); },
|
|
1512
2141
|
listDiary() { return listDiary(id); },
|
|
2142
|
+
importDiary(list, opts) { return importDiary(id, list, opts); },
|
|
2143
|
+
/** 老鱼预装情绪词 / 精确导入词表 */
|
|
2144
|
+
seedVocab(words) { return seedVocab(id, words); },
|
|
2145
|
+
importVocab(list) { return importVocab(id, list); },
|
|
1513
2146
|
tick(now) { return settleBrain(id, now); },
|
|
1514
2147
|
brief() { return getBrief(id); },
|
|
1515
2148
|
snapshot() { return snapshot(id); },
|
|
@@ -1554,11 +2187,12 @@ export { LABELS, listBrains, readAudit, addImagination, addEpisode };
|
|
|
1554
2187
|
export { flowLevel, flowName, styleVector };
|
|
1555
2188
|
export { attribute } from './core/attribution.js';
|
|
1556
2189
|
export { PATIENCE_DELTA, applyPatience, isOutburst, whimProbability, wakeReply, sampleStyle } from './core/derive.js';
|
|
1557
|
-
export { retrieve } from './core/memory.js';
|
|
2190
|
+
export { retrieve, settle, recall, touchByIds } from './core/memory.js';
|
|
1558
2191
|
export { brief } from './core/persona.js';
|
|
1559
2192
|
export { normalizeEvent, toCue, toObservation, shouldObserve, keywords } from './core/event.js';
|
|
1560
2193
|
export { dataDir, roleDir } from './store.js';
|
|
1561
2194
|
export { dataDirSource, isDataDirInsidePackage } from './store.js';
|
|
2195
|
+
export { readYear, listYears, setEpisodeWindow, episodeWindow } from './store.js';
|
|
1562
2196
|
export { lintCard } from './core/extract.js';
|
|
1563
2197
|
export { dedupeKey } from './adapters/qq-bridge.js';
|
|
1564
2198
|
export { createBridgeAdapter } from './adapters/qq-bridge.js';
|
|
@@ -1574,9 +2208,10 @@ export {
|
|
|
1574
2208
|
learn as learnWord, induce as induceWord, describeSensation,
|
|
1575
2209
|
} from './core/emotion.js';
|
|
1576
2210
|
|
|
1577
|
-
/* 记忆卡片 */
|
|
2211
|
+
/* 记忆卡片 + 两层老化 */
|
|
1578
2212
|
export {
|
|
1579
2213
|
makeCard, addCard, shouldCompact, CARD_THRESHOLD_CHARS, CARD_MAX_CHARS,
|
|
2214
|
+
COMPRESS_DAYS, FORGET_DAYS,
|
|
1580
2215
|
} from './core/memory.js';
|
|
1581
2216
|
|
|
1582
2217
|
/* 平台记忆 + 口味闭环 */
|