feiyu-brain 1.5.1 → 1.6.1

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,234 @@
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
+ file: seed?.file ?? '',
140
+ source: seed ? `config:${seed.file}` : 'probe',
141
+ });
142
+ break; // 这个端口通了就不试别的 token
143
+ }
144
+ }
145
+ return results;
146
+ }
147
+
148
+ /* ── 记住 ───────────────────────────────────────────────── */
149
+
150
+ function channelsDir(dataDir) {
151
+ return dataDir || path.join(HOME, '.feiyu-brain');
152
+ }
153
+
154
+ function channelsFile(dataDir) {
155
+ return path.join(channelsDir(dataDir), 'channels.json');
156
+ }
157
+
158
+ export function loadChannels(dataDir) {
159
+ try {
160
+ const j = JSON.parse(fs.readFileSync(channelsFile(dataDir), 'utf8'));
161
+ return Array.isArray(j.channels) ? j.channels : [];
162
+ } catch {
163
+ return [];
164
+ }
165
+ }
166
+
167
+ /**
168
+ * 存通道。
169
+ *
170
+ * **不存明文 token**——只存"从哪读"(tokenRef)。
171
+ * 磁盘上多一份明文 token,等于多一个泄漏面。
172
+ *
173
+ * 权限 0600:只有本人能读。
174
+ */
175
+ export function saveChannels(dataDir, channels) {
176
+ if (!dataDir) return 0; // 没指定就不落盘——绝不写第二份
177
+ fs.mkdirSync(channelsDir(dataDir), { recursive: true });
178
+ const safe = channels.map((ch) => {
179
+ const { token, ...rest } = ch;
180
+ // 有来源文件就存引用;否则存 env 名;再否则只能存内存标记
181
+ const tokenRef = ch.tokenRef
182
+ ?? (ch.file ? { kind: 'file', path: ch.file } : (token ? { kind: 'inline-redacted' } : null));
183
+ return { ...rest, tokenRef };
184
+ });
185
+ const file = channelsFile(dataDir);
186
+ fs.writeFileSync(file, `${JSON.stringify({ version: 2, channels: safe }, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
187
+ try { fs.chmodSync(file, 0o600); } catch { /* 平台不支持就算了 */ }
188
+ return safe.length;
189
+ }
190
+
191
+ /** 用的时候才把 token 取出来(从文件/环境变量),不留在磁盘上 */
192
+ export function resolveToken(ch) {
193
+ const ref = ch?.tokenRef;
194
+ if (!ref) return ch?.token ?? '';
195
+ if (ref.kind === 'env') return process.env[ref.name] ?? '';
196
+ if (ref.kind === 'file') {
197
+ try {
198
+ const text = fs.readFileSync(ref.path, 'utf8');
199
+ const m = text.match(/"accessToken"\s*:\s*"([^"]+)"/);
200
+ if (m) return m[1];
201
+ } catch { /* 文件没了 */ }
202
+ return '';
203
+ }
204
+ return '';
205
+ }
206
+
207
+ /**
208
+ * 拿一张能用的嘴:先用手工配的,再用发现的,最后扫一遍。
209
+ */
210
+ export async function resolveMouth({ dataDir, prefer = '' } = {}) {
211
+ const saved = loadChannels(dataDir).filter((c) => c && c.baseUrl);
212
+ const ordered = prefer ? [...saved.filter((c) => c.impl === prefer), ...saved.filter((c) => c.impl !== prefer)] : saved;
213
+
214
+ for (const c of ordered) {
215
+ const r = await probe(c.baseUrl, resolveToken(c));
216
+ if (r.ok) return { ...c, token: resolveToken(c), alive: true, source: 'saved' };
217
+ }
218
+ const found = await detect();
219
+ if (!found.length) return null;
220
+ // 发现到了就存下来,下次直接用
221
+ saveChannels(dataDir, found.map(({ impl, implName, baseUrl, token, uin, nickname, file }) => ({ impl, implName, baseUrl, token, file, uin, nickname })));
222
+ return { ...found[0], source: 'detected' };
223
+ }
224
+
225
+ /** 探活所有已存的通道 */
226
+ export async function statusOf(dataDir) {
227
+ const saved = loadChannels(dataDir);
228
+ const out = [];
229
+ for (const c of saved) {
230
+ const r = await probe(c.baseUrl, resolveToken(c));
231
+ out.push({ ...c, token: '', alive: r.ok, uin: r.data?.user_id ?? c.uin, nickname: r.data?.nickname ?? c.nickname });
232
+ }
233
+ return out;
234
+ }
package/lib/checks.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // 数据侧体检:不是"装没装上",是"能不能长期跑"。
2
+ //
3
+ // 铺到无数条鱼之后,真正出事的是这些:
4
+ // 没有 current-role.json / 口令权限太松 / 审计无限长 / 有隔离档没处理
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ const ok = (key, text) => ({ level: 'ok', key, text });
10
+ const warn = (key, text, fix) => ({ level: 'warn', key, text, fix });
11
+
12
+ export function dataChecks({ dataDir, id = 'default' } = {}) {
13
+ const out = [];
14
+ if (!dataDir) return out;
15
+
16
+ // ① 角色卡指针
17
+ const cur = path.join(dataDir, 'current-role.json');
18
+ if (!fs.existsSync(cur)) {
19
+ out.push(warn(
20
+ 'current-role',
21
+ '没有 current-role.json —— 光把卡放进 roles/ 还不行,她不知道用哪一张',
22
+ `写 {"role":"<卡名>"} 到 ${cur}`,
23
+ ));
24
+ } else {
25
+ out.push(ok('current-role', 'current-role.json 存在'));
26
+ }
27
+
28
+ // ② 通道口令
29
+ const ch = path.join(dataDir, 'channels.json');
30
+ if (fs.existsSync(ch)) {
31
+ let mode = 0;
32
+ try { mode = fs.statSync(ch).mode & 0o777; } catch { /* 忽略 */ }
33
+ // Windows 上 chmod 基本无效(只映射成只读属性),别给假警告
34
+ if (process.platform !== 'win32' && mode && mode !== 0o600) {
35
+ out.push(warn('channels-mode', `channels.json 权限 ${mode.toString(8)},太松`, `chmod 600 ${ch}`));
36
+ } else {
37
+ out.push(ok('channels-mode', process.platform === 'win32' ? 'channels.json 权限(Windows 由 ACL 决定)' : `channels.json 权限 ${mode.toString(8)}`));
38
+ }
39
+ try {
40
+ const raw = fs.readFileSync(ch, 'utf8');
41
+ if (/"(?:token|accessToken)"\s*:\s*"[^"]{8,}"/.test(raw)) {
42
+ out.push(warn('channels-plain', 'channels.json 里还有明文口令', '重跑 npx feiyu mouth detect(会改存引用)'));
43
+ } else {
44
+ out.push(ok('channels-plain', 'channels.json 没有明文口令'));
45
+ }
46
+ } catch { /* 读不了跳过 */ }
47
+ }
48
+
49
+ // ③ 审计体积
50
+ const audit = path.join(dataDir, 'brains', id, 'audit.jsonl');
51
+ if (fs.existsSync(audit)) {
52
+ const size = fs.statSync(audit).size;
53
+ const mb = size / 1024 / 1024;
54
+ out.push(mb > 4
55
+ ? warn('audit-size', `audit.jsonl ${mb.toFixed(1)} MB,该轮转了`)
56
+ : ok('audit-size', `audit.jsonl ${mb.toFixed(1)} MB`));
57
+ }
58
+
59
+ // ④ 隔离档(坏过)
60
+ try {
61
+ const broken = fs.readdirSync(path.join(dataDir, 'brains', id)).filter((f) => f.includes('.broken-'));
62
+ if (broken.length) {
63
+ out.push(warn('broken', `有 ${broken.length} 个隔离档没处理:${broken.join(', ')}`, 'npx feiyu restore <快照名>,或手工看'));
64
+ } else {
65
+ out.push(ok('broken', '没有隔离档'));
66
+ }
67
+ } catch { /* 没有这个鱼 */ }
68
+
69
+ return out;
70
+ }
package/lib/doctor.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  //
8
8
  // 剩下的(数据目录、角色卡)本来就归它自己管。
9
9
 
10
- import fs from 'node:fs';
10
+ import { dataChecks } from './checks.mjs';
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { execFileSync } from 'node:child_process';
@@ -52,12 +52,26 @@ function hasPnpm() {
52
52
  * 体检。只读,不改任何东西。
53
53
  * @returns {{ok:boolean, checks:Array}}
54
54
  */
55
- export function diagnose({ profile = 'desktop', packageName = 'feiyu-brain' } = {}) {
55
+ export function diagnose({ profile = 'desktop', packageName = 'feiyu-brain', dataDir = '', brainId = 'default' } = {}) {
56
56
  const home = dshHome();
57
57
  const profileFile = path.join(home, 'profiles', profile, 'package.json');
58
58
  const allowFile = path.join(home, 'state', 'tool-allow.json');
59
59
  const checks = [];
60
60
 
61
+ // ⓪ 数据侧:能不能长期跑(角色卡指针 / 口令权限 / 审计 / 隔离档)
62
+ try {
63
+ for (const c of dataChecks({ dataDir, id: brainId })) {
64
+ checks.push({
65
+ id: c.key,
66
+ level: c.level,
67
+ title: c.text,
68
+ detail: '',
69
+ fixable: false,
70
+ fix: c.fix ?? '',
71
+ });
72
+ }
73
+ } catch { /* 数据检查失败不影响装机检查 */ }
74
+
61
75
  // ① pnpm
62
76
  const pnpm = hasPnpm();
63
77
  checks.push({
@@ -118,6 +118,18 @@ export function apply(ctx, entryConfig = {}) {
118
118
  try {
119
119
  return safe(await spec.execute(args));
120
120
  } catch (e) {
121
+ // 边界兜底:不把堆栈丢给模型,给一句能照做的话
122
+ const msg = String(e?.message ?? e);
123
+ if (e && e.code === 'E_BRAIN_CORRUPT') return safe(fail(msg, 'E_BRAIN_CORRUPT'));
124
+ if (/找不到角色卡|Cannot convert undefined|undefined or null/.test(msg)) {
125
+ return safe(fail(
126
+ '找不到角色卡:她还没有人设,所以现在只是个空壳。\\n'
127
+ + ' 1. 写一张卡:~/.feiyu-brain/roles/<名字>.md(第一行写你是谁,后面一行一条:性格、说话方式、不能做什么)\\n'
128
+ + ' 2. npx feiyu lint —— 检查卡有没有写歪\\n'
129
+ + ' 3. npx feiyu status —— 再来看她',
130
+ 'E_NO_CARD',
131
+ ));
132
+ }
121
133
  return safe(fail(`工具执行出错:${explain(e)}`, 'E_THROWN'));
122
134
  }
123
135
  },
@@ -337,7 +349,7 @@ export function apply(ctx, entryConfig = {}) {
337
349
  type: 'object',
338
350
  properties: {
339
351
  id: { type: 'string', description: '鱼的 id,默认 default' },
340
- action: { type: 'string', description: 'open / screenshot / uninstall' },
352
+ action: { type: 'string', description: 'open_app / open_url / focus / click / type / key / scroll / screenshot(uninstall 桌面端拒绝;shell 需 force)' },
341
353
  package: { type: 'string', description: 'Android 包名,例如 com.ss.android.ugc.aweme' },
342
354
  target: { type: 'string', description: '电脑上要启动的程序' },
343
355
  why: { type: 'string', description: '卸载 Q1:为什么想删' },
@@ -0,0 +1,22 @@
1
+ // 人格指纹:她还是不是她。
2
+ //
3
+ // 静默漂移只能事后发现,所以每次出生/蜕壳算一次指纹,写进 audit。
4
+ // 升级、降级、从快照恢复之后一比,就知道"人设有没有被动过"。
5
+
6
+ import { createHash } from 'node:crypto';
7
+
8
+ export function fingerprint(units = [], traits = {}) {
9
+ const basis = (units ?? [])
10
+ .map((u) => `${u.id}:${u.kind}:${String(u.text ?? '').slice(0, 40)}`)
11
+ .sort()
12
+ .join('|');
13
+ const t = Object.keys(traits ?? {})
14
+ .sort()
15
+ .map((k) => `${k}=${Number(traits[k]).toFixed(3)}`)
16
+ .join(',');
17
+ return createHash('sha256').update(`${basis}#${t}`).digest('hex').slice(0, 16);
18
+ }
19
+
20
+ export function describe(fp) {
21
+ return fp ? `人设指纹 ${fp}` : '人设指纹(还没算过)';
22
+ }
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 || '', // 不用 OPENAI_API_KEY:那是宿主的 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
+ }