feiyu-brain 1.5.1 → 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.
@@ -0,0 +1,199 @@
1
+ // 通道:面对无数条鱼,不能只认一种网关。
2
+ //
3
+ // 现实里用户的 QQ 通道五花八门:
4
+ // SnowLuma / NapCat / Lagrange / go-cqhttp / 官方机器人 / 自己的 webhook
5
+ //
6
+ // 这套东西要做三件事:
7
+ // ① 自动发现:扫常见端口 + 读常见配置目录,找到能用的通道
8
+ // ② 记住:写进 ~/.feiyu-brain/channels.json,下次直接用
9
+ // ③ 排优先级:谁先试谁后试,失败自动往下掉
10
+ //
11
+ // 目标是**零配置**:装完 `feiyu mouth detect` 就能找到你的网关。
12
+
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+
17
+ /** 常见的 OneBot 实现及其默认端口/配置位置 */
18
+ export const KNOWN_IMPLS = [
19
+ {
20
+ id: 'snowluma',
21
+ name: 'SnowLuma',
22
+ ports: [3000],
23
+ configDirs: ['~/SnowLuma/config', '~/snowluma/config', '~/.snowluma/config'],
24
+ pattern: /^onebot_\d+\.json$/,
25
+ },
26
+ {
27
+ id: 'napcat',
28
+ name: 'NapCat',
29
+ ports: [3000, 6099],
30
+ configDirs: [
31
+ '~/AppData/Roaming/napcat/config',
32
+ '~/AppData/Local/napcat/config',
33
+ '~/.config/napcat',
34
+ '~/napcat/config',
35
+ ],
36
+ pattern: /onebot.*\.json$/i,
37
+ },
38
+ {
39
+ id: 'lagrange',
40
+ name: 'Lagrange.OneBot',
41
+ ports: [8080, 3000],
42
+ configDirs: ['~/.config/Lagrange', '~/Lagrange', '~/Lagrange.OneBot'],
43
+ pattern: /appsettings.*\.json$/i,
44
+ },
45
+ {
46
+ id: 'gocqhttp',
47
+ name: 'go-cqhttp',
48
+ ports: [5700],
49
+ configDirs: ['~/go-cqhttp', '~/.go-cqhttp'],
50
+ pattern: /^config\.yml$/,
51
+ },
52
+ {
53
+ id: 'generic',
54
+ name: '通用 OneBot',
55
+ ports: [3000, 5700, 6700, 8080, 8888],
56
+ configDirs: [],
57
+ pattern: null,
58
+ },
59
+ ];
60
+
61
+ const HOME = os.homedir();
62
+ const expand = (p) => (p.startsWith('~') ? path.join(HOME, p.slice(1)) : p);
63
+
64
+ /** 所有要试的端口(去重保序) */
65
+ export function candidatePorts() {
66
+ const seen = new Set();
67
+ const out = [];
68
+ for (const impl of KNOWN_IMPLS) {
69
+ for (const p of impl.ports) {
70
+ if (!seen.has(p)) { seen.add(p); out.push(p); }
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /** 从各实现的配置文件里挖 token / 端口 */
77
+ export function harvestTokens() {
78
+ const found = [];
79
+ for (const impl of KNOWN_IMPLS) {
80
+ if (!impl.pattern) continue;
81
+ for (const dirRaw of impl.configDirs) {
82
+ const dir = expand(dirRaw);
83
+ let names = [];
84
+ try { names = fs.readdirSync(dir); } catch { continue; }
85
+ for (const name of names) {
86
+ if (!impl.pattern.test(name)) continue;
87
+ let text = '';
88
+ try { text = fs.readFileSync(path.join(dir, name), 'utf8'); } catch { continue; }
89
+ const tokens = [...text.matchAll(/"accessToken"\s*:\s*"([^"]+)"/g)].map((m) => m[1]);
90
+ const ports = [...text.matchAll(/"port"\s*:\s*(\d+)/g)].map((m) => Number(m[1]));
91
+ for (const token of tokens) {
92
+ found.push({ impl: impl.id, implName: impl.name, token, ports, file: path.join(dir, name) });
93
+ }
94
+ }
95
+ }
96
+ }
97
+ return found;
98
+ }
99
+
100
+ async function probe(baseUrl, token, timeoutMs = 2500) {
101
+ const headers = token ? { authorization: `Bearer ${token}` } : {};
102
+ const ctrl = new AbortController();
103
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
104
+ try {
105
+ const res = await fetch(`${baseUrl}/get_login_info`, { headers, signal: ctrl.signal });
106
+ if (!res.ok) return { ok: false, status: res.status };
107
+ const json = await res.json().catch(() => ({}));
108
+ if (json?.retcode && json.retcode !== 0) return { ok: false, status: json.retcode };
109
+ return { ok: true, data: json?.data ?? null };
110
+ } catch {
111
+ return { ok: false, status: 0 };
112
+ } finally {
113
+ clearTimeout(timer);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * 扫一遍,把能用的通道全找出来。
119
+ * @returns {Promise<Array<{impl,implName,baseUrl,token,uin,nickname,source}>>}
120
+ */
121
+ export async function detect({ extraTokens = [], timeoutMs = 2500 } = {}) {
122
+ const results = [];
123
+ const seeds = [...harvestTokens(), ...extraTokens];
124
+ const tokenPool = [...new Set([...seeds.map((s) => s.token), '', ...(process.env.FEISHU_ONEBOT_TOKEN ? [process.env.FEISHU_ONEBOT_TOKEN] : [])])];
125
+
126
+ for (const port of candidatePorts()) {
127
+ const baseUrl = `http://127.0.0.1:${port}`;
128
+ for (const token of tokenPool) {
129
+ const r = await probe(baseUrl, token, timeoutMs);
130
+ if (!r.ok) continue;
131
+ const seed = seeds.find((s) => s.token === token);
132
+ results.push({
133
+ impl: seed?.impl ?? 'generic',
134
+ implName: seed?.implName ?? '通用 OneBot',
135
+ baseUrl,
136
+ token,
137
+ uin: r.data?.user_id ?? null,
138
+ nickname: r.data?.nickname ?? '',
139
+ source: seed ? `config:${seed.file}` : 'probe',
140
+ });
141
+ break; // 这个端口通了就不试别的 token
142
+ }
143
+ }
144
+ return results;
145
+ }
146
+
147
+ /* ── 记住 ───────────────────────────────────────────────── */
148
+
149
+ function channelsDir(dataDir) {
150
+ return dataDir || path.join(HOME, '.feiyu-brain');
151
+ }
152
+
153
+ function channelsFile(dataDir) {
154
+ return path.join(channelsDir(dataDir), 'channels.json');
155
+ }
156
+
157
+ export function loadChannels(dataDir) {
158
+ try {
159
+ const j = JSON.parse(fs.readFileSync(channelsFile(dataDir), 'utf8'));
160
+ return Array.isArray(j.channels) ? j.channels : [];
161
+ } catch {
162
+ return [];
163
+ }
164
+ }
165
+
166
+ export function saveChannels(dataDir, channels) {
167
+ fs.mkdirSync(channelsDir(dataDir), { recursive: true });
168
+ fs.writeFileSync(channelsFile(dataDir), `${JSON.stringify({ version: 1, channels }, null, 2)}\n`, 'utf8');
169
+ return channels.length;
170
+ }
171
+
172
+ /**
173
+ * 拿一张能用的嘴:先用手工配的,再用发现的,最后扫一遍。
174
+ */
175
+ export async function resolveMouth({ dataDir, prefer = '' } = {}) {
176
+ const saved = loadChannels(dataDir).filter((c) => c && c.baseUrl);
177
+ const ordered = prefer ? [...saved.filter((c) => c.impl === prefer), ...saved.filter((c) => c.impl !== prefer)] : saved;
178
+
179
+ for (const c of ordered) {
180
+ const r = await probe(c.baseUrl, c.token);
181
+ if (r.ok) return { ...c, alive: true, source: 'saved' };
182
+ }
183
+ const found = await detect();
184
+ if (!found.length) return null;
185
+ // 发现到了就存下来,下次直接用
186
+ saveChannels(dataDir, found.map(({ impl, implName, baseUrl, token, uin, nickname }) => ({ impl, implName, baseUrl, token, uin, nickname })));
187
+ return { ...found[0], source: 'detected' };
188
+ }
189
+
190
+ /** 探活所有已存的通道 */
191
+ export async function statusOf(dataDir) {
192
+ const saved = loadChannels(dataDir);
193
+ const out = [];
194
+ for (const c of saved) {
195
+ const r = await probe(c.baseUrl, c.token);
196
+ out.push({ ...c, alive: r.ok, uin: r.data?.user_id ?? c.uin, nickname: r.data?.nickname ?? c.nickname });
197
+ }
198
+ return out;
199
+ }
package/lib/llm.mjs ADDED
@@ -0,0 +1,105 @@
1
+ // 嘴:让她能说话。
2
+ //
3
+ // 之前我死守"嘴是宿主的事",结果就是——装上了,但她一句都说不出来。
4
+ // 那不是内核,那是零件。
5
+ //
6
+ // 这里接一个 OpenAI 兼容接口(你自己的 key、你自己的模型),
7
+ // 流程只有四步:
8
+ //
9
+ // ① 取「此刻的她」(wake 段)
10
+ // ② 拼成 system prompt
11
+ // ③ 调模型
12
+ // ④ 把回复记回去(observe)
13
+ //
14
+ // **不给 key 也不崩**:会明确告诉你"她张了张嘴,但没地方说话"。
15
+
16
+ const DEFAULTS = {
17
+ baseUrl: 'https://api.deepseek.com/v1',
18
+ model: 'deepseek-chat',
19
+ timeoutMs: 60000,
20
+ };
21
+
22
+ /**
23
+ * 造一张嘴。
24
+ *
25
+ * @param {object} o
26
+ * @param {string} [o.baseUrl] OpenAI 兼容的 /v1 地址
27
+ * @param {string} [o.apiKey] 也可以走环境变量 FEIYU_LLM_KEY
28
+ * @param {string} [o.model]
29
+ */
30
+ export function createMouth({
31
+ baseUrl = process.env.FEIYU_LLM_BASE || DEFAULTS.baseUrl,
32
+ apiKey = process.env.FEIYU_LLM_KEY || process.env.OPENAI_API_KEY || '',
33
+ model = process.env.FEIYU_LLM_MODEL || DEFAULTS.model,
34
+ timeoutMs = DEFAULTS.timeoutMs,
35
+ } = {}) {
36
+ const configured = Boolean(apiKey && baseUrl);
37
+
38
+ /**
39
+ * 说一句。
40
+ * @param {object} o
41
+ * @param {string} o.system 她此刻的状态(wake 段)
42
+ * @param {Array<{role:string,content:string}>} o.messages 往来
43
+ */
44
+ async function say({ system = '', messages = [], maxTokens = 200, temperature = 0.9 } = {}) {
45
+ if (!configured) {
46
+ return {
47
+ ok: false,
48
+ code: 'E_NO_LLM',
49
+ text: '她张了张嘴,但没地方说话(没配模型:设 FEIYU_LLM_KEY 或用 mouth({apiKey}))',
50
+ configured: false,
51
+ };
52
+ }
53
+ const url = `${String(baseUrl).replace(/\/$/, '')}/chat/completions`;
54
+ const body = {
55
+ model,
56
+ temperature,
57
+ max_tokens: maxTokens,
58
+ messages: [
59
+ ...(system ? [{ role: 'system', content: system }] : []),
60
+ ...messages,
61
+ ],
62
+ };
63
+
64
+ const ctrl = new AbortController();
65
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
66
+ try {
67
+ const res = await fetch(url, {
68
+ method: 'POST',
69
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },
70
+ body: JSON.stringify(body),
71
+ signal: ctrl.signal,
72
+ });
73
+ const json = await res.json().catch(() => ({}));
74
+ if (!res.ok) {
75
+ return { ok: false, code: `E_LLM_${res.status}`, text: String(json?.error?.message ?? `HTTP ${res.status}`), configured: true };
76
+ }
77
+ const text = String(json?.choices?.[0]?.message?.content ?? '').trim();
78
+ if (!text) return { ok: false, code: 'E_LLM_EMPTY', text: '模型回了空话', configured: true };
79
+ return { ok: true, text, model, usage: json?.usage ?? null, configured: true };
80
+ } catch (e) {
81
+ const aborted = String(e?.name ?? '') === 'AbortError';
82
+ return {
83
+ ok: false,
84
+ code: aborted ? 'E_LLM_TIMEOUT' : 'E_LLM',
85
+ text: aborted ? `模型 ${timeoutMs}ms 没回来` : String(e?.message ?? e),
86
+ configured: true,
87
+ };
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
92
+
93
+ return { say, configured, baseUrl, model };
94
+ }
95
+
96
+ /** 把 wake 段变成 system prompt —— 这是"她的嘴"唯一的输入 */
97
+ export function buildSystemPrompt(stateText, { extra = '' } = {}) {
98
+ const parts = [
99
+ stateText || '',
100
+ '',
101
+ '用她的口吻回一句。不要客服腔,不要解释你在做什么,不要复述上面的资料。',
102
+ ];
103
+ if (extra) parts.push(extra);
104
+ return parts.filter(Boolean).join('\n');
105
+ }
package/lib/onebot.mjs ADDED
@@ -0,0 +1,106 @@
1
+ // 外接嘴:不弹窗、不抢焦点,一条 HTTP 就发出去。
2
+ //
3
+ // 之前那套"窗口打字"体验差到不能看:要前台、要清空、打错窗口就发到别处。
4
+ // 真正的嘴应该是——**POST 一下就完事**。
5
+ //
6
+ // 支持三种外接:
7
+ // onebot OneBot 11(SnowLuma / NapCat / Lagrange / go-cqhttp 都认)
8
+ // tencent 腾讯官方 API(走已有的 tencent-official 适配器)
9
+ // http 宿主自己的发送接口
10
+ //
11
+ // 窗口打字留着,但只作最后兜底。
12
+
13
+ const DEFAULT_TIMEOUT = 15000;
14
+
15
+ /**
16
+ * OneBot 11 发消息。
17
+ *
18
+ * 先试 POST JSON,失败再试 GET 查询串——各家实现兼容性不一样。
19
+ *
20
+ * @param {object} o
21
+ * @param {string} o.baseUrl 例如 http://127.0.0.1:3000
22
+ * @param {string} [o.token] 访问令牌(一般走 Authorization: Bearer)
23
+ * @param {'group'|'private'} [o.kind]
24
+ * @param {string|number} o.target 群号 / QQ 号
25
+ * @param {string} o.text
26
+ * @param {boolean} [o.dryRun]
27
+ */
28
+ export async function sendOneBot({
29
+ baseUrl = 'http://127.0.0.1:3000',
30
+ token = '',
31
+ kind = 'group',
32
+ target = '',
33
+ text = '',
34
+ dryRun = false,
35
+ timeoutMs = DEFAULT_TIMEOUT,
36
+ } = {}) {
37
+ const t = String(target ?? '').trim();
38
+ const body = String(text ?? '');
39
+ if (!t) return { ok: false, code: 'E_ARGS', via: 'onebot', text: '要给群号或 QQ 号' };
40
+ if (!body) return { ok: false, code: 'E_ARGS', via: 'onebot', text: '没什么可发的' };
41
+ if (dryRun) {
42
+ return { ok: true, via: 'onebot', dryRun: true, kind, target: t, chars: body.length, evidence: `onebot:dry:${t}` };
43
+ }
44
+
45
+ const action = kind === 'private' ? 'send_private_msg' : 'send_group_msg';
46
+ const idKey = kind === 'private' ? 'user_id' : 'group_id';
47
+ const url = `${String(baseUrl).replace(/\/$/, '')}/${action}`;
48
+ const headers = { 'content-type': 'application/json' };
49
+ if (token) headers.authorization = `Bearer ${token}`;
50
+
51
+ const attempt = async () => {
52
+ const ctrl = new AbortController();
53
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
54
+ try {
55
+ const res = await fetch(url, {
56
+ method: 'POST',
57
+ headers,
58
+ body: JSON.stringify({ [idKey]: Number(t) || t, message: body, auto_escape: false }),
59
+ signal: ctrl.signal,
60
+ });
61
+ const json = await res.json().catch(() => ({}));
62
+ if (!res.ok) return { ok: false, code: `E_ONEBOT_${res.status}`, text: String(json?.message ?? `HTTP ${res.status}`) };
63
+ // OneBot 有些实现在 200 里带 retcode != 0
64
+ if (json && typeof json.retcode === 'number' && json.retcode !== 0) {
65
+ return { ok: false, code: 'E_ONEBOT_RET', text: String(json.message ?? `retcode ${json.retcode}`) };
66
+ }
67
+ const msgId = json?.data?.message_id ?? null;
68
+ return { ok: true, messageId: msgId, evidence: `onebot:${action}:${t}:${msgId ?? '?'}` };
69
+ } catch (e) {
70
+ const aborted = String(e?.name ?? '') === 'AbortError';
71
+ return { ok: false, code: aborted ? 'E_ONEBOT_TIMEOUT' : 'E_ONEBOT', text: String(e?.message ?? e).slice(0, 200) };
72
+ } finally {
73
+ clearTimeout(timer);
74
+ }
75
+ };
76
+
77
+ const r = await attempt();
78
+ if (r.ok) return { ...r, via: 'onebot', kind, target: t };
79
+ // 退回 GET(少数实现不接 JSON 体)
80
+ try {
81
+ const qs = new URLSearchParams({ [idKey]: String(t), message: body });
82
+ const u = `${url}?${qs.toString()}`;
83
+ const h = token ? { authorization: `Bearer ${token}` } : {};
84
+ const res = await fetch(u, { headers: h });
85
+ const json = await res.json().catch(() => ({}));
86
+ if (res.ok && !(typeof json?.retcode === 'number' && json.retcode !== 0)) {
87
+ return { ok: true, via: 'onebot', kind, target: t, messageId: json?.data?.message_id ?? null, evidence: `onebot:get:${action}:${t}` };
88
+ }
89
+ } catch { /* 两种都失败,返回第一次的错误 */ }
90
+
91
+ return { ...r, via: 'onebot', kind, target: t };
92
+ }
93
+
94
+ /** 探活:能连上、能拿到版本/登录信息 */
95
+ export async function pingOneBot({ baseUrl = 'http://127.0.0.1:3000', token = '', timeoutMs = 4000 } = {}) {
96
+ const headers = token ? { authorization: `Bearer ${token}` } : {};
97
+ for (const p of ['get_login_info', 'get_version_info']) {
98
+ try {
99
+ const res = await fetch(`${String(baseUrl).replace(/\/$/, '')}/${p}`, { headers });
100
+ if (!res.ok) continue;
101
+ const json = await res.json().catch(() => ({}));
102
+ if (json?.data) return { ok: true, endpoint: p, data: json.data };
103
+ } catch { /* 试下一个 */ }
104
+ }
105
+ return { ok: false, code: 'E_ONEBOT_DOWN' };
106
+ }
package/lib/say.mjs ADDED
@@ -0,0 +1,120 @@
1
+ // 嘴:把话**发出去**。
2
+ //
3
+ // 之前我把"生成文本"当成嘴——那是错的。
4
+ // 生成是思考,模型本来就有;嘴是**把思考的结果送到别人屏幕上**。
5
+ //
6
+ // 三种嘴:
7
+ // window 往一个窗口打字 + 回车(微信、QQ 客户端、任何输入框)
8
+ // qq 走已有的 QQ 适配器(桥接 / 官方 API)
9
+ // http POST 到宿主自己的发送接口
10
+ //
11
+ // 手和嘴不是一回事:手是"点哪里",嘴是"说什么"。
12
+
13
+ import { execFile } from 'node:child_process';
14
+ import { promisify } from 'node:util';
15
+
16
+ const run = promisify(execFile);
17
+
18
+ /**
19
+ * 往一个窗口里"打一段字并回车"。
20
+ *
21
+ * 用剪贴板粘贴而不是逐键模拟——中文逐键会乱。
22
+ *
23
+ * @param {object} o
24
+ * @param {string} o.title 窗口标题(部分匹配即可,如 "微信" / "QQ")
25
+ * @param {string} o.text 要发的内容
26
+ * @param {boolean} [o.enter] 发完按不按回车(默认按)
27
+ * @param {boolean} [o.dryRun]
28
+ */
29
+ export async function sendToWindow({ title = '', text = '', enter = true, dryRun = false } = {}) {
30
+ const t = String(title ?? '').trim();
31
+ const body = String(text ?? '');
32
+ if (!t) return { ok: false, code: 'E_ARGS', via: 'window', text: '要说明发到哪个窗口(标题)' };
33
+ if (!body) return { ok: false, code: 'E_ARGS', via: 'window', text: '没什么可发的' };
34
+
35
+ if (dryRun) {
36
+ return { ok: true, via: 'window', dryRun: true, title: t, chars: body.length, evidence: `window:dry:${t}` };
37
+ }
38
+
39
+ // ① 聚焦窗口 → ② 放剪贴板 → ③ Ctrl+V → ④ 回车
40
+ const ps = [
41
+ '$ErrorActionPreference="Stop";',
42
+ 'Add-Type -AssemblyName System.Windows.Forms;',
43
+ `$ws = New-Object -ComObject WScript.Shell;`,
44
+ `if (-not $ws.AppActivate(${JSON.stringify(t)})) { Write-Output "NO_WINDOW"; exit 2 };`,
45
+ 'Start-Sleep -Milliseconds 250;',
46
+ `Set-Clipboard -Value ${JSON.stringify(body)};`,
47
+ 'Start-Sleep -Milliseconds 120;',
48
+ '[System.Windows.Forms.SendKeys]::SendWait("^v");',
49
+ 'Start-Sleep -Milliseconds 150;',
50
+ enter ? '[System.Windows.Forms.SendKeys]::SendWait("{ENTER}");' : '',
51
+ ].filter(Boolean).join(' ');
52
+
53
+ try {
54
+ const { stdout } = await run('powershell', ['-NoProfile', '-Command', ps], { timeout: 20000 });
55
+ if (String(stdout).includes('NO_WINDOW')) {
56
+ return { ok: false, code: 'E_NO_WINDOW', via: 'window', text: `没找到标题含「${t}」的窗口` };
57
+ }
58
+ return {
59
+ ok: true,
60
+ via: 'window',
61
+ title: t,
62
+ chars: body.length,
63
+ evidence: `window:${t}:${body.slice(0, 24)}`,
64
+ };
65
+ } catch (e) {
66
+ return { ok: false, code: 'E_SEND', via: 'window', text: String(e?.message ?? e).slice(0, 200) };
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 说话的唯一入口。
72
+ *
73
+ * @param {object} o
74
+ * @param {'window'|'qq'|'http'} [o.via]
75
+ * @param {object} deps { log, bridgeAdapter, brain, id }
76
+ */
77
+ export async function say({ text = '', via = 'auto', title = '', target = '', enter = true, dryRun = false, kind = 'group', baseUrl = '', token = '', dataDir = '' } = {}, deps = {}) {
78
+ // auto:先找用户配过的/能扫到的 OneBot,找不到再退回窗口
79
+ if (via === 'auto') {
80
+ const { resolveMouth } = await import('./channels.mjs');
81
+ const m = await resolveMouth({ dataDir: dataDir || deps.dataDir || '' }).catch(() => null);
82
+ if (m) {
83
+ const { sendOneBot } = await import('./onebot.mjs');
84
+ return sendOneBot({ baseUrl: m.baseUrl, token: m.token, kind, target, text, dryRun });
85
+ }
86
+ via = 'window';
87
+ }
88
+ if (via === 'onebot') {
89
+ const { sendOneBot } = await import('./onebot.mjs');
90
+ return sendOneBot({
91
+ baseUrl: baseUrl || deps.baseUrl || process.env.FEISHU_ONEBOT || 'http://127.0.0.1:3000',
92
+ token: token || deps.token || process.env.FEISHU_ONEBOT_TOKEN || '',
93
+ kind,
94
+ target,
95
+ text,
96
+ dryRun,
97
+ });
98
+ }
99
+ if (via === 'qq') {
100
+ const ad = deps.bridgeAdapter;
101
+ if (!ad || typeof ad.send !== 'function') {
102
+ return { ok: false, code: 'E_NO_QQ', via, text: 'QQ 通道没接(需要宿主传入 bridgeAdapter)' };
103
+ }
104
+ return ad.send(target, text);
105
+ }
106
+ if (via === 'http') {
107
+ if (!target) return { ok: false, code: 'E_ARGS', via, text: 'http 通道要给 target 地址' };
108
+ try {
109
+ const res = await fetch(target, {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json' },
112
+ body: JSON.stringify({ text }),
113
+ });
114
+ return { ok: res.ok, via, status: res.status, evidence: `http:${target}` };
115
+ } catch (e) {
116
+ return { ok: false, code: 'E_SEND', via, text: String(e?.message ?? e).slice(0, 200) };
117
+ }
118
+ }
119
+ return sendToWindow({ title, text, enter, dryRun });
120
+ }
package/lib/serve.mjs CHANGED
@@ -50,6 +50,30 @@ const isLocal = (req) => {
50
50
  return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
51
51
  };
52
52
 
53
+ /**
54
+ * Origin 校验(审查报告 B1)。
55
+ *
56
+ * 只看 remoteAddress 是不够的:**任何网页从浏览器发起的请求,源地址也是 127.0.0.1**。
57
+ * 所以必须看 Origin——只放行本机页面和命令行工具(没有 Origin 头)。
58
+ */
59
+ function originAllowed(req) {
60
+ const origin = req.headers.origin;
61
+ if (!origin) return true; // curl / python requests 不发 Origin
62
+ try {
63
+ const u = new URL(origin);
64
+ return u.hostname === '127.0.0.1' || u.hostname === 'localhost' || u.hostname === '[::1]';
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ const LOCAL_ORIGIN_HEADERS = {
71
+ 'access-control-allow-origin': 'http://127.0.0.1',
72
+ 'access-control-allow-headers': 'content-type,x-feiyu-token',
73
+ 'access-control-allow-methods': 'GET,POST,OPTIONS',
74
+ vary: 'Origin',
75
+ };
76
+
53
77
  /**
54
78
  * 造一个边车(不启动)。
55
79
  *
@@ -105,6 +129,18 @@ export function createServer(brain, { token = '', id = 'default' } = {}) {
105
129
  what: body.what ?? '',
106
130
  }),
107
131
 
132
+ 'POST /say': async (_q, body) => {
133
+ if (!body.text) return { ok: false, code: 'E_ARGS', text: 'text 不能为空' };
134
+ return brain.speak(body.id ?? id, {
135
+ who: body.who ?? '',
136
+ sender: body.who ?? '',
137
+ text: String(body.text),
138
+ }, {
139
+ budget: Number.isFinite(Number(body.budget)) ? Number(body.budget) : 500,
140
+ ...(typeof body.extra === 'string' && body.extra ? { extra: body.extra } : {}),
141
+ });
142
+ },
143
+
108
144
  'POST /diary': async (_q, body) => {
109
145
  const action = String(body.action ?? 'digest').toLowerCase();
110
146
  if (action === 'write') return brain.writeDiary(body.id ?? id, { date: body.date ?? '', text: body.text ?? '' });
@@ -137,8 +173,13 @@ export function createServer(brain, { token = '', id = 'default' } = {}) {
137
173
  const url = new URL(req.url ?? '/', 'http://localhost');
138
174
  const key = `${req.method} ${url.pathname}`;
139
175
 
176
+ // Origin 先查:浏览器发起的跨站请求一律拒(审查报告 B1)
177
+ if (!originAllowed(req)) {
178
+ return json(res, 403, { ok: false, code: 'E_ORIGIN', text: '不允许的 Origin(只放行本机页面)' });
179
+ }
180
+
140
181
  if (req.method === 'OPTIONS') {
141
- res.writeHead(204, { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type,x-feiyu-token' });
182
+ res.writeHead(204, LOCAL_ORIGIN_HEADERS);
142
183
  return res.end();
143
184
  }
144
185
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "feiyu-brain",
3
- "version": "1.5.1",
4
- "description": "大肥鱼的大脑内核:人设是根,情绪/记忆/意识流/归因都是从人设长出来的。DSH 插件 + 平台无关库。",
3
+ "version": "1.6.0",
4
+ "description": "给 AI 装一颗有记忆、有情绪、会变化的脑;带上嘴(外接 OneBot/官方)和手(点、打、滑、执行)。",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -35,6 +35,8 @@
35
35
  "cli.mjs",
36
36
  "demo.mjs",
37
37
  "selftest.mjs",
38
+ "test-adapters.mjs",
39
+ "smoke.mjs",
38
40
  "cordis.patch.yml",
39
41
  "core/",
40
42
  "adapters/",
@@ -58,7 +60,12 @@
58
60
  "brain",
59
61
  "qq-bot",
60
62
  "tencent-qq",
61
- "chatbot"
63
+ "chatbot",
64
+ "onebot",
65
+ "qq",
66
+ "snowluma",
67
+ "napcat",
68
+ "lagrange"
62
69
  ],
63
70
  "scripts": {
64
71
  "test": "node selftest.mjs && node test-adapters.mjs",
package/selftest.mjs CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  import assert from 'node:assert/strict';
6
6
  import fs from 'node:fs';
7
+ import os from 'node:os';
7
8
  import path from 'node:path';
8
9
 
9
10
  import { ROOT } from './store.js';
@@ -26,14 +27,27 @@ function t(name, fn) {
26
27
  }
27
28
 
28
29
  const ID = 'selftest';
29
- const dir = path.join(ROOT, 'state', 'brains', ID);
30
+ // 自测跑在临时目录里,不往包目录写东西(审查报告 A4)
31
+ const TMP = fs.mkdtempSync(path.join(os.tmpdir(), 'feiyu-selftest-'));
32
+ brain.configure({ dataDir: TMP, roleDir: path.join(TMP, 'roles') });
33
+ const dir = path.join(TMP, 'brains', ID);
30
34
  if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
31
35
 
32
36
  console.log('\n── 出生 ──');
33
- const b = brain.birth({ id: ID, relation: 'parent', address: '妈' });
37
+ // 内联一张测试卡:干净机器上不该因为没有角色卡就崩(审查报告 A3)
38
+ const TEST_CARD = [
39
+ '你是测试鱼。',
40
+ '性格:嘴硬=0.8 心软=0.6 好奇=0.7 好动=0.6',
41
+ '- 我嘴硬,被怼会顶回去。',
42
+ '- 我记仇但记不久。',
43
+ '- 不要客服腔。',
44
+ '- 我喜欢解压类的视频。',
45
+ '- 有人认真跟我说话,我会收起腔调。',
46
+ ].join('\n');
47
+ const b = brain.birth({ id: ID, relation: 'parent', address: '妈', cardText: TEST_CARD, cardName: '测试鱼' });
34
48
 
35
49
  t('从角色卡抽出命题', () => {
36
- assert.ok(b.persona.units.length > 20, `只抽到 ${b.persona.units.length} 条`);
50
+ assert.ok(b.persona.units.length > 3, `只抽到 ${b.persona.units.length} 条`);
37
51
  });
38
52
 
39
53
  t('有身份命题', () => {