feiyu-brain 1.4.2 → 1.5.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/lib/doctor.mjs ADDED
@@ -0,0 +1,181 @@
1
+ // 装不上 / 装上了不工作 —— 自检 + 自动修。
2
+ //
3
+ // 这三件事插件自己碰不到,但可以替你去改:
4
+ // ① pnpm 有没有 (只能告诉你装什么,不能替你装)
5
+ // ② profile 的 bundles 有没有登记(能自动加)
6
+ // ③ tool-allow 白名单 (能自动加)
7
+ //
8
+ // 剩下的(数据目录、角色卡)本来就归它自己管。
9
+
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { execFileSync } from 'node:child_process';
14
+
15
+ const TOOLS = [
16
+ 'feiyu_status', 'feiyu_wake', 'feiyu_observe', 'feiyu_tick',
17
+ 'feiyu_feel', 'feiyu_app', 'feiyu_lint', 'feiyu_snapshot', 'feiyu_diary',
18
+ ];
19
+
20
+ export function dshHome() {
21
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
22
+ }
23
+
24
+ function readJsonSafe(file, fallback = null) {
25
+ try {
26
+ const t = fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '');
27
+ return JSON.parse(t);
28
+ } catch {
29
+ return fallback;
30
+ }
31
+ }
32
+
33
+ function writeJsonSafe(file, data) {
34
+ fs.mkdirSync(path.dirname(file), { recursive: true });
35
+ const tmp = `${file}.tmp`;
36
+ fs.writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
37
+ fs.renameSync(tmp, file);
38
+ }
39
+
40
+ function hasPnpm() {
41
+ try {
42
+ const out = execFileSync(process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm', ['-v'], {
43
+ encoding: 'utf8', timeout: 8000, stdio: ['ignore', 'pipe', 'ignore'],
44
+ });
45
+ return String(out).trim();
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * 体检。只读,不改任何东西。
53
+ * @returns {{ok:boolean, checks:Array}}
54
+ */
55
+ export function diagnose({ profile = 'desktop', packageName = 'feiyu-brain' } = {}) {
56
+ const home = dshHome();
57
+ const profileFile = path.join(home, 'profiles', profile, 'package.json');
58
+ const allowFile = path.join(home, 'state', 'tool-allow.json');
59
+ const checks = [];
60
+
61
+ // ① pnpm
62
+ const pnpm = hasPnpm();
63
+ checks.push({
64
+ id: 'pnpm',
65
+ level: pnpm ? 'ok' : 'block',
66
+ title: 'pnpm',
67
+ detail: pnpm ? `已安装 ${pnpm}` : '没装 pnpm —— dsh plugin add 底层要用它',
68
+ fixable: false,
69
+ fix: pnpm ? '' : 'npm i -g pnpm (或 corepack enable pnpm)',
70
+ });
71
+
72
+ // ② profile bundles + dependencies
73
+ const profileJson = readJsonSafe(profileFile, null);
74
+ if (!profileJson) {
75
+ checks.push({
76
+ id: 'profile',
77
+ level: 'warn',
78
+ title: 'DSH profile',
79
+ detail: `没找到 ${profileFile}`,
80
+ fixable: false,
81
+ fix: '确认 DSH 装过、profile 名字对不对(默认 desktop)',
82
+ });
83
+ } else {
84
+ const deps = profileJson.dependencies ?? {};
85
+ const bundles = profileJson.dsh?.profile?.bundles ?? [];
86
+ const inDeps = Boolean(deps[packageName]);
87
+ const inBundles = bundles.includes(packageName);
88
+ const level = inDeps && inBundles ? 'ok' : 'block';
89
+ checks.push({
90
+ id: 'bundles',
91
+ level,
92
+ title: '插件登记',
93
+ detail: inDeps && inBundles
94
+ ? `dependencies + bundles 都有(${deps[packageName]})`
95
+ : `dependencies ${inDeps ? '有' : '缺'} / bundles ${inBundles ? '有' : '缺'}(缺 bundles 等于装了不加载)`,
96
+ fixable: true,
97
+ fix: '把 feiyu-brain 补进 dsh.profile.bundles',
98
+ _file: profileFile,
99
+ });
100
+ }
101
+
102
+ // ③ tool-allow
103
+ const allow = readJsonSafe(allowFile, null);
104
+ if (!allow) {
105
+ checks.push({
106
+ id: 'allow',
107
+ level: 'warn',
108
+ title: '工具白名单',
109
+ detail: `没找到 ${allowFile}(有些 DSH 版本没有闸门,属正常)`,
110
+ fixable: false,
111
+ fix: '',
112
+ });
113
+ } else {
114
+ const exact = Array.isArray(allow.exact) ? allow.exact : [];
115
+ const prefixes = Array.isArray(allow.prefix) ? allow.prefix : (Array.isArray(allow.prefixes) ? allow.prefixes : []);
116
+ const missing = TOOLS.filter((t) => !exact.includes(t));
117
+ const covered = prefixes.includes('feiyu_') || prefixes.includes('feiyu');
118
+ const level = covered || missing.length === 0 ? 'ok' : 'block';
119
+ checks.push({
120
+ id: 'allow',
121
+ level,
122
+ title: '工具白名单',
123
+ detail: covered
124
+ ? '前缀 feiyu_ 已放行'
125
+ : (missing.length ? `少了 ${missing.length} 个:${missing.join(', ')}` : `9 个都在`),
126
+ fixable: !covered && missing.length > 0,
127
+ fix: '把 9 个 feiyu_* 加进 exact',
128
+ _file: allowFile,
129
+ });
130
+ }
131
+
132
+ return { ok: checks.every((c) => c.level !== 'block'), home, profile, checks };
133
+ }
134
+
135
+ /**
136
+ * 自动修能修的(bundles + 白名单)。
137
+ * pnpm 和角色卡不修——一个是系统级,一个是「卡必须用户自己写」。
138
+ */
139
+ export function applyFixes(report, { packageName = 'feiyu-brain' } = {}) {
140
+ const done = [];
141
+ for (const c of report.checks) {
142
+ if (!c.fixable || !c._file) continue;
143
+
144
+ if (c.id === 'bundles') {
145
+ const json = readJsonSafe(c._file, null);
146
+ if (!json) continue;
147
+ json.dsh = json.dsh ?? {};
148
+ json.dsh.profile = json.dsh.profile ?? {};
149
+ const bundles = Array.isArray(json.dsh.profile.bundles) ? json.dsh.profile.bundles : [];
150
+ if (!bundles.includes(packageName)) bundles.push(packageName);
151
+ json.dsh.profile.bundles = bundles;
152
+ json.dependencies = json.dependencies ?? {};
153
+ if (!json.dependencies[packageName]) json.dependencies[packageName] = 'latest';
154
+ writeJsonSafe(c._file, json);
155
+ done.push(`已在 ${path.basename(c._file)} 里登记 ${packageName}`);
156
+ }
157
+
158
+ if (c.id === 'allow') {
159
+ const json = readJsonSafe(c._file, null);
160
+ if (!json) continue;
161
+ const exact = Array.isArray(json.exact) ? json.exact : [];
162
+ for (const t of TOOLS) if (!exact.includes(t)) exact.push(t);
163
+ json.exact = exact;
164
+ writeJsonSafe(c._file, json);
165
+ done.push(`已把 ${TOOLS.length} 个工具加进白名单`);
166
+ }
167
+ }
168
+ return done;
169
+ }
170
+
171
+ export function formatReport(report) {
172
+ const icon = { ok: '✔', warn: '!', block: '✘' };
173
+ const lines = [`DSH 目录:${report.home}(profile: ${report.profile})`, ''];
174
+ for (const c of report.checks) {
175
+ lines.push(`${icon[c.level] || '?'} ${c.title} ${c.detail}`);
176
+ if (c.level !== 'ok' && c.fix) lines.push(` → ${c.fix}`);
177
+ }
178
+ lines.push('');
179
+ lines.push(report.ok ? '没有硬阻断。' : '有硬阻断,先修上面的 ✘。');
180
+ return lines.join('\n');
181
+ }
@@ -82,6 +82,8 @@ export function apply(ctx, entryConfig = {}) {
82
82
  brainId: pickStr(entryConfig?.brainId, 'default'),
83
83
  dataDir: pickStr(entryConfig?.dataDir, process.env.FEIYU_DATA_DIR || ''),
84
84
  roleDir: pickStr(entryConfig?.roleDir, process.env.FEIYU_ROLE_DIR || ''),
85
+ // 只注册哪几个工具。数组或逗号字符串都认;不填=全注册。
86
+ tools: entryConfig?.tools,
85
87
  };
86
88
 
87
89
  if (conf.dataDir || conf.roleDir) {
@@ -95,17 +97,32 @@ export function apply(ctx, entryConfig = {}) {
95
97
  return;
96
98
  }
97
99
 
98
- const tool = (spec) => ctx.tools.register(defineTool({
99
- ...spec,
100
- output: spec.output || textOutput,
101
- async execute(args = {}) {
102
- try {
103
- return safe(await spec.execute(args));
104
- } catch (e) {
105
- return safe(fail(`工具执行出错:${explain(e)}`, 'E_THROWN'));
106
- }
107
- },
108
- }));
100
+ // 只注册你要的工具。
101
+ // 插件设置里写 tools: [status, wake, observe, tick] → 不会多出一只"能开 App 的手"
102
+ // 不写 = 全注册(6 个)
103
+ const rawTools = conf.tools;
104
+ const toolList = Array.isArray(rawTools)
105
+ ? rawTools
106
+ : (typeof rawTools === 'string' ? rawTools.split(/[,,\s]+/) : []);
107
+ const enabled = toolList.length
108
+ ? new Set(toolList.map((t) => String(t).trim().replace(/^feiyu_/, '')).filter(Boolean))
109
+ : null;
110
+
111
+ const tool = (spec) => {
112
+ const short = String(spec.name).replace(/^feiyu_/, '');
113
+ if (enabled && !enabled.has(short)) return null;
114
+ return ctx.tools.register(defineTool({
115
+ ...spec,
116
+ output: spec.output || textOutput,
117
+ async execute(args = {}) {
118
+ try {
119
+ return safe(await spec.execute(args));
120
+ } catch (e) {
121
+ return safe(fail(`工具执行出错:${explain(e)}`, 'E_THROWN'));
122
+ }
123
+ },
124
+ }));
125
+ };
109
126
 
110
127
  const idOf = (args) => pickStr(args?.id, conf.brainId);
111
128
 
@@ -138,6 +155,8 @@ export function apply(ctx, entryConfig = {}) {
138
155
  `记忆 经历 ${s.memory.episodes} / 印象 ${s.memory.impressions} / 卡片 ${s.memory.cards} / 蜕皮 ${s.memory.formerSelves} / 遗忘 ${s.memory.forgotten}`,
139
156
  `平台 ${Object.keys(s.apps ?? {}).length ? Object.entries(s.apps).map(([k, v]) => `${k} ${v.seen}条`).join(' · ') : '还没在任何平台上有记录'}`,
140
157
  `情绪 ${s.emotion.stage === 1 ? '只会说"说不清"' : `会 ${s.emotion.words.length} 个词`}`,
158
+ `运行 ${s.runtime?.shadow ? '影子模式(只审计,不动人设)' : '正常'} · TTL ${s.runtime?.ttlPolicy ?? 'hard'} · 情绪源 ${s.runtime?.moodPolicy ?? 'brain'}`,
159
+ `数据 ${s.runtime?.dataDir ?? '?'}${s.runtime?.dataDirInsidePackage ? ' ⚠️ 写进包里了' : ''}`,
141
160
  `观察 ${s.observations} 次`,
142
161
  '',
143
162
  '权重最高的五条:',
@@ -161,17 +180,26 @@ export function apply(ctx, entryConfig = {}) {
161
180
  id: { type: 'string', description: '鱼的 id,默认 default' },
162
181
  sender: { type: 'string', description: '当前说话的人,用于检索对他的记忆' },
163
182
  text: { type: 'string', description: '他说的话,用于关键词检索' },
183
+ sections: {
184
+ type: 'string',
185
+ description: '只要哪几段,逗号分隔:persona / flow / body / mood / memory / search。'
186
+ + '不填=全给。叠加到别人已有的系统里时,填 mood 就只占二十来字,不会让 token 翻倍。',
187
+ },
188
+ budget: { type: 'number', description: '总字数上限,超了从低优先级段开始砍(人设保底不砍)' },
164
189
  },
165
190
  additionalProperties: false,
166
191
  },
167
192
  async execute(args) {
168
193
  const id = idOf(args);
194
+ const raw = pickStr(args?.sections);
195
+ const sections = raw ? raw.split(/[,,\s]+/).map((s) => s.trim()).filter(Boolean) : undefined;
196
+ const budget = Number.isFinite(Number(args?.budget)) ? Number(args.budget) : undefined;
169
197
  const text = brain.wakeLine(id, {
170
198
  sender: pickStr(args?.sender),
171
199
  text: pickStr(args?.text),
172
- });
200
+ }, { ...(sections ? { sections } : {}), ...(budget ? { budget } : {}) });
173
201
  if (!text.trim()) return fail('大脑没有产出内容,先跑 feiyu_status 看看');
174
- return { ok: true, text, chars: text.length };
202
+ return { ok: true, text, chars: text.length, sections: sections ?? 'all' };
175
203
  },
176
204
  });
177
205
 
@@ -191,6 +219,11 @@ export function apply(ctx, entryConfig = {}) {
191
219
  app: { type: 'string', description: '如果是某个平台上的事:douyin / bilibili / wechat / qq' },
192
220
  kind: { type: 'string', description: '内容类型,例如 解压 / 搞笑 / 做饭,用来累计口味' },
193
221
  reaction: { type: 'number', description: '她的反应,-1 到 1,正数表示喜欢' },
222
+ evolve: {
223
+ type: 'boolean',
224
+ description: '是否同时改人设权重,默认 true。填 false = 只记经历、不碰人设——'
225
+ + '叠加到别人已经有人格系统的地方时用这个,免得两套口径打架。',
226
+ },
194
227
  },
195
228
  required: ['text'],
196
229
  additionalProperties: false,
@@ -209,7 +242,7 @@ export function apply(ctx, entryConfig = {}) {
209
242
  feel: pickStr(args?.feel),
210
243
  via: app ? `app:${app}` : 'dsh',
211
244
  ...(app ? { app, kind: pickStr(args?.kind), reaction: Number(args?.reaction ?? 0) } : {}),
212
- });
245
+ }, { evolve: args?.evolve !== false });
213
246
 
214
247
  const changed = r.consistent.length + r.conflicting.length;
215
248
  return {
@@ -217,7 +250,9 @@ export function apply(ctx, entryConfig = {}) {
217
250
  text: [
218
251
  `记下了:${who ? `${who}「${text}」` : `「${text}」`}`,
219
252
  app ? `平台 ${app}${pickStr(args?.kind) ? ` / ${pickStr(args?.kind)}` : ''}` : '',
220
- `权重 一致 ${r.consistent.length} 条 / 冲突 ${r.conflicting.length} 条${changed ? '' : '(没匹配到命题,人设不动)'}`,
253
+ r.evolved === false
254
+ ? '权重 没动(evolve:false,只当记忆库用)'
255
+ : `权重 一致 ${r.consistent.length} 条 / 冲突 ${r.conflicting.length} 条${changed ? '' : '(没匹配到命题,人设不动)'}`,
221
256
  r.label ? `归因 ${r.label}` : '',
222
257
  ].filter(Boolean).join('\n'),
223
258
  matched: changed,
@@ -338,6 +373,153 @@ export function apply(ctx, entryConfig = {}) {
338
373
  },
339
374
  });
340
375
 
376
+ /* ── 7. 卡片体检 ─────────────────────────────────────── */
377
+ tool({
378
+ name: 'feiyu_lint',
379
+ description:
380
+ '体检一份人设卡:哪些行会抽成"她是谁",哪些会被忽略、为什么,'
381
+ + '哪些行其实像操作手册(工具/参数/步骤/命令)建议拆出去。不写任何东西,纯只读。',
382
+ parameters: {
383
+ type: 'object',
384
+ properties: {
385
+ text: { type: 'string', description: '卡的全文;不填就读当前角色卡文件' },
386
+ },
387
+ additionalProperties: false,
388
+ },
389
+ async execute(args) {
390
+ const raw = pickStr(args?.text);
391
+ let text = raw;
392
+ if (!text) {
393
+ const card = brain.resolveRoleCard();
394
+ if (!card?.text) return fail('没有现成的卡可读;把卡内容贴进 text 参数');
395
+ text = card.text;
396
+ }
397
+ const r = brain.lintCard(text);
398
+ const lines = [
399
+ `可抽成命题 ${r.units} 条:${Object.entries(r.byKind).map(([k, v]) => `${k} ${v}`).join(' / ') || '无'}`,
400
+ `被忽略 ${r.dropped.length} 行`,
401
+ '',
402
+ '命题预览:',
403
+ ...r.preview.map((x) => ` ${x}`),
404
+ ];
405
+ if (r.suggestSplit.length) {
406
+ lines.push('', `⚠️ 有 ${r.suggestSplit.length} 行更像操作手册,建议拆出人设:`);
407
+ for (const s of r.suggestSplit.slice(0, 8)) lines.push(` · ${s.text}`);
408
+ }
409
+ return { ok: true, text: lines.join('\n'), report: r };
410
+ },
411
+ });
412
+
413
+ /* ── 8. 存档 / 回滚 ─────────────────────────────────── */
414
+ tool({
415
+ name: 'feiyu_snapshot',
416
+ description:
417
+ '给她存档、回滚、看快照列表。人格被经历改坏了能退回来,'
418
+ + '不用 rebirth(那是重置,会清空记忆)。',
419
+ parameters: {
420
+ type: 'object',
421
+ properties: {
422
+ id: { type: 'string', description: '鱼的 id,默认 default' },
423
+ action: { type: 'string', description: 'save(默认)/ restore / list' },
424
+ name: { type: 'string', description: '快照名;不填就用时间戳' },
425
+ },
426
+ additionalProperties: false,
427
+ },
428
+ async execute(args) {
429
+ const id = idOf(args);
430
+ const action = (pickStr(args?.action, 'save')).toLowerCase();
431
+ const name = pickStr(args?.name);
432
+
433
+ if (action === 'list') {
434
+ const list = brain.listSnapshots(id);
435
+ if (!list.length) return { ok: true, text: '还没有快照。' };
436
+ return {
437
+ ok: true,
438
+ text: ['快照(新的在前):', ...list.map((s) => ` ${s.name} ${(s.size / 1024).toFixed(1)} KB`)].join('\n'),
439
+ snapshots: list,
440
+ };
441
+ }
442
+ if (action === 'restore') {
443
+ const r = brain.restoreBrain(id, name);
444
+ if (!r.ok) {
445
+ return { ok: false, code: 'E_RESTORE', text: `❌ ${r.reason}${r.available?.length ? `\n可用:${r.available.join(', ')}` : ''}` };
446
+ }
447
+ return { ok: true, text: `已退回 ${r.restored}\n体检:${r.check.verdict}`, check: r.check };
448
+ }
449
+ const r = brain.snapshotBrain(id, name);
450
+ return { ok: true, text: `已存档:${r.name}\n${r.file}` };
451
+ },
452
+ });
453
+
454
+ /* ── 9. 日记:她自己的心房 ───────────────────────────── */
455
+ tool({
456
+ name: 'feiyu_diary',
457
+ description:
458
+ '她自己的日记。digest 取今天的素材 + 第一人称骨架(你照着用她的口吻写),'
459
+ + 'write 把写好的存回去(会记进记忆,以后能想起来"我写过什么"),read / list 翻旧账。'
460
+ + '注意:日记是她写给自己看的,不是给用户看的汇报。',
461
+ parameters: {
462
+ type: 'object',
463
+ properties: {
464
+ id: { type: 'string', description: '鱼的 id,默认 default' },
465
+ action: { type: 'string', description: 'digest(默认)/ write / read / list' },
466
+ date: { type: 'string', description: 'YYYY-MM-DD,默认今天' },
467
+ text: { type: 'string', description: 'write 时的日记正文' },
468
+ },
469
+ additionalProperties: false,
470
+ },
471
+ async execute(args) {
472
+ const id = idOf(args);
473
+ const action = (pickStr(args?.action, 'digest')).toLowerCase();
474
+ const date = pickStr(args?.date);
475
+
476
+ if (action === 'write') {
477
+ const r = brain.writeDiary(id, { date, text: pickStr(args?.text) });
478
+ if (!r.ok) return fail(r.reason);
479
+ return {
480
+ ok: true,
481
+ text: [
482
+ `${r.date} 的日记存好了(${r.chars} 字${r.mood ? `,心情 ${r.mood}` : ''})`,
483
+ r.file,
484
+ r.moodAdded ? '(正文里没写心情,替她补了一行)' : '',
485
+ ].filter(Boolean).join('\n'),
486
+ date: r.date,
487
+ mood: r.mood,
488
+ };
489
+ }
490
+
491
+ if (action === 'read') {
492
+ const r = brain.readDiary(id, date);
493
+ if (!r) return { ok: false, code: 'E_NO_DIARY', text: `${date || '今天'}还没有日记。` };
494
+ return { ok: true, text: r.text, date: r.date };
495
+ }
496
+
497
+ if (action === 'list') {
498
+ const list = brain.listDiary(id);
499
+ if (!list.length) return { ok: true, text: '还没写过日记。' };
500
+ return {
501
+ ok: true,
502
+ text: [`写过 ${list.length} 天:`, ...list.slice(0, 20).map((d) => ` ${d.date} ${(d.size / 1024).toFixed(1)} KB`)].join('\n'),
503
+ days: list,
504
+ };
505
+ }
506
+
507
+ // digest
508
+ const d = brain.diaryDigest(id, date);
509
+ return {
510
+ ok: true,
511
+ text: [
512
+ `【${d.date} 的素材】经历 ${d.episodes} 条,见了 ${d.people.length ? d.people.join('、') : '没人'},心情 ${d.mood || '平静'}`,
513
+ '',
514
+ d.draft,
515
+ '',
516
+ `👉 ${d.hint}`,
517
+ ].join('\n'),
518
+ digest: d,
519
+ };
520
+ },
521
+ });
522
+
341
523
  /* ── 配置检查(不注册工具,只打一行日志)───────────── */
342
524
  try {
343
525
  const s = brain.snapshot(conf.brainId);
package/lib/serve.mjs ADDED
@@ -0,0 +1,187 @@
1
+ // HTTP 边车:让任何语言都能用这颗脑。
2
+ //
3
+ // AstrBot 是 Python,脑是 Node。以前只能每条消息 spawn 一个 node(100~300ms 冷启动),
4
+ // 现在起一个常驻进程,Python 侧三行就接上了:
5
+ //
6
+ // r = requests.post('http://127.0.0.1:7788/wake',
7
+ // json={'id':'default','sender':who,'text':msg})
8
+ //
9
+ // 零依赖,只用 node:http。默认只绑 127.0.0.1。
10
+ //
11
+ // 安全:
12
+ // · 默认只监听本机回环,外网连不上
13
+ // · 设了 token 就必须带 x-feiyu-token 头
14
+ // · 没设 token 时,只允许本机来源(remoteAddress 是回环)
15
+
16
+ import http from 'node:http';
17
+ import { createRequire } from 'node:module';
18
+
19
+ const require = createRequire(import.meta.url);
20
+
21
+ function readBody(req, { limit = 1_000_000 } = {}) {
22
+ return new Promise((resolve, reject) => {
23
+ let size = 0;
24
+ const chunks = [];
25
+ req.on('data', (c) => {
26
+ size += c.length;
27
+ if (size > limit) { reject(new Error('body too large')); req.destroy(); return; }
28
+ chunks.push(c);
29
+ });
30
+ req.on('end', () => {
31
+ const raw = Buffer.concat(chunks).toString('utf8');
32
+ if (!raw) return resolve({});
33
+ try { resolve(JSON.parse(raw)); } catch (e) { reject(new Error(`JSON 解析失败:${e.message}`)); }
34
+ });
35
+ req.on('error', reject);
36
+ });
37
+ }
38
+
39
+ function json(res, code, obj) {
40
+ const body = JSON.stringify(obj);
41
+ res.writeHead(code, {
42
+ 'content-type': 'application/json; charset=utf-8',
43
+ 'content-length': Buffer.byteLength(body),
44
+ });
45
+ res.end(body);
46
+ }
47
+
48
+ const isLocal = (req) => {
49
+ const ip = req.socket.remoteAddress ?? '';
50
+ return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
51
+ };
52
+
53
+ /**
54
+ * 造一个边车(不启动)。
55
+ *
56
+ * @param {object} brain index.js 的命名空间
57
+ * @param {object} opts
58
+ * @param {string} [opts.token] 设了就要求 x-feiyu-token
59
+ * @param {string} [opts.id] 默认鱼 id
60
+ */
61
+ export function createServer(brain, { token = '', id = 'default' } = {}) {
62
+ const routes = {
63
+ 'GET /health': async () => ({ ok: true, name: 'feiyu-brain', id }),
64
+ 'GET /status': async (q) => brain.snapshot(q.id ?? id),
65
+ 'GET /version': async () => {
66
+ const pkg = require('../package.json');
67
+ return { version: pkg.version, name: pkg.name };
68
+ },
69
+
70
+ 'POST /wake': async (_q, body) => {
71
+ const text = brain.wakeLine(body.id ?? id, {
72
+ sender: body.sender ?? '',
73
+ text: body.text ?? '',
74
+ }, {
75
+ ...(Array.isArray(body.sections) ? { sections: body.sections } : {}),
76
+ ...(Number.isFinite(Number(body.budget)) ? { budget: Number(body.budget) } : {}),
77
+ });
78
+ return { ok: true, text, chars: text.length };
79
+ },
80
+
81
+ 'POST /observe': async (_q, body) => {
82
+ if (!body.text) return { ok: false, code: 'E_ARGS', text: 'text 不能为空' };
83
+ const app = body.app ?? '';
84
+ const r = brain.observe(body.id ?? id, {
85
+ who: body.who ?? '',
86
+ text: String(body.text),
87
+ what: String(body.text).slice(0, 80),
88
+ feel: body.feel ?? '',
89
+ via: app ? `app:${app}` : 'http',
90
+ ...(app ? { app, kind: body.kind ?? '', reaction: Number(body.reaction) || 0 } : {}),
91
+ ...(Number.isFinite(Number(body.valence)) ? { valence: Number(body.valence), intensity: Number(body.intensity) || 0.5 } : {}),
92
+ }, { evolve: body.evolve !== false });
93
+ return {
94
+ ok: true,
95
+ consistent: r.consistent?.length ?? 0,
96
+ conflicting: r.conflicting?.length ?? 0,
97
+ evolved: r.evolved,
98
+ shadow: r.shadow === true,
99
+ };
100
+ },
101
+
102
+ 'POST /feel': async (_q, body) => brain.feel(body.id ?? id, {
103
+ valence: Number(body.valence) || 0,
104
+ intensity: Number.isFinite(Number(body.intensity)) ? Number(body.intensity) : 0.5,
105
+ what: body.what ?? '',
106
+ }),
107
+
108
+ 'POST /diary': async (_q, body) => {
109
+ const action = String(body.action ?? 'digest').toLowerCase();
110
+ if (action === 'write') return brain.writeDiary(body.id ?? id, { date: body.date ?? '', text: body.text ?? '' });
111
+ if (action === 'read') return brain.readDiary(body.id ?? id, body.date ?? '') ?? { ok: false, code: 'E_NO_DIARY' };
112
+ if (action === 'list') return { ok: true, days: brain.listDiary(body.id ?? id) };
113
+ return { ok: true, digest: brain.diaryDigest(body.id ?? id, body.date ?? '') };
114
+ },
115
+
116
+ 'POST /migrate': async (_q, body) => {
117
+ if (Array.isArray(body.sources)) return brain.migrateAll(body.id ?? id, body.sources, { dryRun: body.dryRun === true });
118
+ return brain.migrateMemory(body.id ?? id, {
119
+ text: body.text ?? '', format: body.format ?? 'jsonl', dryRun: body.dryRun === true,
120
+ });
121
+ },
122
+
123
+ 'POST /snapshot': async (_q, body) => {
124
+ const action = String(body.action ?? 'save').toLowerCase();
125
+ const bid = body.id ?? id;
126
+ if (action === 'list') return { ok: true, snapshots: brain.listSnapshots(bid) };
127
+ if (action === 'restore') return brain.restoreBrain(bid, body.name ?? '');
128
+ return brain.snapshotBrain(bid, body.name ?? '');
129
+ },
130
+
131
+ 'GET /identity': async (q) => brain.identityCheck(q.id ?? id),
132
+ 'GET /verify': async (q) => brain.verifyMemory(q.id ?? id),
133
+ };
134
+
135
+ return http.createServer(async (req, res) => {
136
+ try {
137
+ const url = new URL(req.url ?? '/', 'http://localhost');
138
+ const key = `${req.method} ${url.pathname}`;
139
+
140
+ if (req.method === 'OPTIONS') {
141
+ res.writeHead(204, { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type,x-feiyu-token' });
142
+ return res.end();
143
+ }
144
+
145
+ // 认证
146
+ if (token) {
147
+ if (req.headers['x-feiyu-token'] !== token) return json(res, 401, { ok: false, code: 'E_AUTH', text: '缺 token 或不对' });
148
+ } else if (!isLocal(req)) {
149
+ return json(res, 403, { ok: false, code: 'E_NOT_LOCAL', text: '没设 token 时只允许本机访问' });
150
+ }
151
+
152
+ const handler = routes[key];
153
+ if (!handler) {
154
+ return json(res, 404, {
155
+ ok: false, code: 'E_NO_ROUTE', text: `${key} 没有`, routes: Object.keys(routes),
156
+ });
157
+ }
158
+
159
+ const body = req.method === 'POST' ? await readBody(req) : {};
160
+ const q = Object.fromEntries(url.searchParams.entries());
161
+ const out = await handler(q, body);
162
+ return json(res, 200, out);
163
+ } catch (e) {
164
+ return json(res, 500, { ok: false, code: 'E_SERVER', text: String(e?.message ?? e) });
165
+ }
166
+ });
167
+ }
168
+
169
+ /**
170
+ * 起一个边车,返回 { url, close }。
171
+ * 端口传 0 会随机分配(测试用)。
172
+ */
173
+ export function serve(brain, { port = 7788, host = '127.0.0.1', token = '', id = 'default' } = {}) {
174
+ const server = createServer(brain, { token, id });
175
+ return new Promise((resolve, reject) => {
176
+ server.once('error', reject);
177
+ server.listen(port, host, () => {
178
+ const addr = server.address();
179
+ resolve({
180
+ server,
181
+ url: `http://${host}:${addr.port}`,
182
+ port: addr.port,
183
+ close: () => new Promise((r) => server.close(r)),
184
+ });
185
+ });
186
+ });
187
+ }
@@ -14,5 +14,5 @@ name: fangqiuci/feiyu-brain
14
14
  category: memory
15
15
 
16
16
  description:
17
- en: 'Persona-grounded brain kernel with six tools (feiyu_status, feiyu_wake, feiyu_observe, feiyu_tick, feiyu_feel, feiyu_app): weighted traits that erode into memories, a 30-day recall window, PAD emotions, and phone/tablet/desktop bodies.'
18
- zh: '以人设为根的大脑内核,提供 6 个工具(feiyu_status / feiyu_wake / feiyu_observe / feiyu_tick / feiyu_feel / feiyu_app):带权重的命题随经历涨落、蜕皮成记忆,30 天回忆窗口,PAD 三维情绪,手机/平板/电脑三具身体。'
17
+ en: 'Persona-grounded brain kernel with nine tools (status, wake, observe, tick, feel, app, lint, snapshot, diary): weighted traits that erode into memories, a 30-day recall window, PAD emotions, her own diary, and phone/tablet/desktop bodies.'
18
+ zh: '以人设为根的大脑内核,提供 9 个工具(status / wake / observe / tick / feel / app / lint / snapshot / diary):带权重的命题随经历涨落、蜕皮成记忆,30 天回忆窗口,PAD 三维情绪,她自己的日记,手机/平板/电脑三具身体。'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "feiyu-brain",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "大肥鱼的大脑内核:人设是根,情绪/记忆/意识流/归因都是从人设长出来的。DSH 插件 + 平台无关库。",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -13,7 +13,8 @@
13
13
  "url": "https://github.com/fangqiuci/feiyu-brain/issues"
14
14
  },
15
15
  "engines": {
16
- "node": ">=20"
16
+ "node": ">=20",
17
+ "dsh": ">=0.2.0"
17
18
  },
18
19
  "main": "./lib/dsh-plugin.mjs",
19
20
  "exports": {