dsh-bagu 0.12.1 → 0.13.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.
package/lib/index.js CHANGED
@@ -1,475 +1,483 @@
1
- /**
2
- * dsh-bagu · 宿主半侧
3
- *
4
- * 三件事:挂一节提示、挂两个只读工具、开 /api/bagu。
5
- *
6
- * 省 token 是这个插件的设计约束,不是优化项:
7
- * - 提示词压到 150 字以内,每次会话都要烧
8
- * - 工具描述压到 60 字以内,每次调用都在上下文里
9
- * - 默认输出三行以内;要看细节传 full: true
10
- *
11
- * 所有判断都在本地正则里做完,不调模型 —— 这是零 token 成本的那一半。
12
- */
13
-
14
- import { analyze } from './analyze.js';
15
- import { render, renderBrief } from './render.js';
16
- import { guard } from './guard.js';
17
- import { findMemes, entry, search, bridge, stats as memeStats } from './memes.js';
18
- import { aiBridge } from './ai-bridge.js';
19
- import { captureRoute, sessionBridge } from './session-bridge.js';
20
- import { updateOnce, dbStatus, isDue, lastUpdate } from './update.js';
21
- import { readConfig, writeConfig, CONFIG_FILE, DEFAULTS } from './config.js';
22
-
23
- export const name = 'dsh-bagu';
24
-
25
- export { analyze, render, renderBrief };
26
-
27
- let live = readConfig();
28
- const syncers = new Set();
29
-
30
- /** 每次会话都注入,多一个字都是白烧。 */
31
- const PROMPT = `要发出去的话,先过 bagu_guard。被打回就改,别硬发。`;
32
-
33
- /** 梗库开着时的追加。告诉 agent 有个查梗工具,遇到不认识的梗先查再答。 */
34
- const PROMPT_MEME = `
35
- 遇到网络梗(谐音、缩写、人名外号、视频台词)拿不准意思,先调 bagu_meme 查,别猜。
36
- 要接梗就传 text(对方原话),它会给出同族能接的;要查单个词就传 q。
37
- `;
38
-
39
- /**
40
- * 玩梗尺度。toneSwitch 关着时不写这段,交给模型自己判断。
41
- *
42
- * 0-100 四档。档位不写在提示里,写行为。
43
- */
44
- function toneRule(cfg) {
45
- if (!cfg.toneSwitch) return '';
46
- const v = Math.max(0, Math.min(100, Number(cfg.toneLevel) || 0));
47
- let line = '';
48
- if (v <= 20) {
49
- line = '玩梗克制。只接正面的、自嘲的、夸人的。外号带贬义的不要复读,不跟着起哄。';
50
- } else if (v <= 45) {
51
- line = '可以损发挥、损操作,不损长相、不损身体。别人先开了头、明显在闹,你接半句;不带头用。';
52
- } else if (v <= 70) {
53
- line = '跟着社区玩。社区在玩什么就接什么,别自己发明。分寸看着对方的调子走。';
54
- } else {
55
- line = '放开玩。带刺的梗也能接,别缩。但收得住——对方认真了、或者真的难受,立刻停。';
56
- }
57
- return '\n' + line;
58
- }
59
-
60
- /** AI 接梗开着时再加一句。 */
61
- const PROMPT_AI = `
62
- 接梗要给出具体那句话,调 bagu_meme 传 text,会自动调模型拼一句。`;
63
-
64
- /** 60 字。 */
65
- /** 一个工具,三种模式。描述只占一份。 */
66
- const TOOL_GUARD = `发出去之前过一遍。默认只回 OK 或一行改法。mode=report 给详细报告,mode=ask 给问句。`;
67
-
68
- function toolOutput() {
69
- return {
70
- schema: {
71
- type: 'object',
72
- additionalProperties: true,
73
- required: ['ok'],
74
- properties: {
75
- ok: { type: 'boolean' },
76
- text: { type: 'string' },
77
- },
78
- },
79
- render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
80
- };
81
- }
82
-
83
- function thresholdsOf(cfg) {
84
- return {
85
- hedgeFloor: cfg.hedgeFloor,
86
- structureTimes: cfg.structureTimes,
87
- concreteFloor: cfg.concreteFloor,
88
- };
89
- }
90
-
91
- function applyLive(next) {
92
- live = next;
93
- for (const sync of syncers) {
94
- try { sync(); } catch { /* 单个失败不影响别的 */ }
95
- }
96
- }
97
-
98
- function sendJson(res, status, body) {
99
- const text = JSON.stringify(body);
100
- res.statusCode = status;
101
- res.setHeader('content-type', 'application/json; charset=utf-8');
102
- res.setHeader('cache-control', 'no-store');
103
- res.end(text);
104
- }
105
-
106
- function readBody(req) {
107
- return new Promise((resolve) => {
108
- let raw = '';
109
- req.on('data', (c) => { raw += c; if (raw.length > 1e6) raw = raw.slice(0, 1e6); });
110
- req.on('end', () => {
111
- try { resolve(raw ? JSON.parse(raw) : {}); } catch { resolve({}); }
112
- });
113
- req.on('error', () => resolve({}));
114
- });
115
- }
116
-
117
- export function apply(root, config = {}) {
118
- live = readConfig();
119
- if (config && typeof config === 'object') {
120
- for (const k of Object.keys(DEFAULTS)) {
121
- if (config[k] !== undefined && live[k] === DEFAULTS[k]) live[k] = config[k];
122
- }
123
- }
124
-
125
- root.inject(['systemPrompt'], (ctx) => {
126
- /** 当轮用户消息。agent/pre-step 里抓,预查注入用这份 —— session 里翻到的常是上一轮。 */
127
- let currentUserText = '';
128
- try {
129
- ctx.on('agent/pre-step', async ({ messages }, next) => {
130
- try {
131
- const arr = Array.isArray(messages) ? messages : [];
132
- for (let i = arr.length - 1; i >= 0; i--) {
133
- const m = arr[i];
134
- if (!m || m.role !== 'user') continue;
135
- const t = payloadText(m);
136
- if (t) { currentUserText = t; break; }
137
- }
138
- } catch { /* 抓不到就算了 */ }
139
- return next();
140
- });
141
- } catch { /* 宿主没这个事件 */ }
142
- let dispose = null;
143
- const sync = () => {
144
- if (dispose) { dispose(); dispose = null; }
145
- if (!live.enabled || !live.prompt) return;
146
- // ── 预查注入:用户消息一进来就先查梗,塞进上下文 ──────────
147
- // 这是「会玩梗」和「能查梗」的分界:前者是模型还没开始想就已经知道,
148
- // 后者要模型主动调工具(它经常不调)。
149
- if (live.memes && live.autoMeme) {
150
- try {
151
- ctx.effect(() => ctx.systemPrompt.context({
152
- name: 'bagu:prefetch',
153
- order: 950,
154
- text: (context) => {
155
- try {
156
- // 只认当轮消息。清空之后不再翻 session —— 那会翻到历史消息,
157
- // 注入一堆跟本轮无关的梗(实测踩过:问「有人味吗」塞进「检测到前方有XX」)。
158
- const text = currentUserText;
159
- if (!text) return '';
160
- currentUserText = '';
161
- const r = bridge(text);
162
- if (!r.hits.length) return '';
163
- const parts = [];
164
- parts.push('[梗] 对方提到:' + r.hits.map((h) => h.title).join('、'));
165
- if (r.usage) parts.push('怎么接:' + r.usage);
166
- else if (r.origin) parts.push('这梗:' + r.origin);
167
- if (r.tags.length) parts.push('这一类:' + r.tags.slice(0, 4).join('/'));
168
- parts.push('照这个接,别念词条出处。');
169
- return parts.join('\n');
170
- } catch {
171
- return '';
172
- }
173
- },
174
- }), 'dsh-bagu: 预查注入');
175
- } catch {
176
- /* 宿主没有这个接口就算了 */
177
- }
178
- }
179
-
180
- dispose = ctx.systemPrompt.section({
181
- name: 'bagu:voice',
182
- order: live.order,
183
- text: PROMPT +
184
- (live.memes ? PROMPT_MEME : '') +
185
- (live.memes ? toneRule(live) : '') +
186
- (live.aiBridge && live.memes ? PROMPT_AI : ''),
187
- });
188
- };
189
- sync();
190
- syncers.add(sync);
191
- ctx.effect(() => () => {
192
- syncers.delete(sync);
193
- if (dispose) dispose();
194
- }, 'dsh-bagu: 说话的念头');
195
- });
196
-
197
- /** 会话自己的路由(provider/model),从 agent/request 抓。抓不到就 null。 */
198
- let getRoute = () => null;
199
- root.inject(['llm'], (ctx) => {
200
- getRoute = captureRoute(ctx);
201
- });
202
-
203
- root.inject(['tools'], (ctx) => {
204
- // 一个工具,三种模式。mode 缺省是守门(日常路径),另外两个是调试用。
205
- // 始终注册 —— 配置热更新时不用重注册。开关在 execute 里判。
206
- ctx.tools.register({
207
- name: 'bagu_meme',
208
- description: '接梗用:看对方说了什么梗,给出同族能接的。也能查单个词什么意思。',
209
- parameters: {
210
- type: 'object',
211
- properties: {
212
- text: { type: 'string', description: '对方说的话。给了就找能接的梗。' },
213
- q: { type: 'string', description: '单个词,查它什么意思。' },
214
- },
215
- },
216
- output: toolOutput(),
217
- execute: async (args) => {
218
- // 这个工具始终注册,但梗库关着时不该被调用
219
- if (!live.memes) return { ok: false, text: '梗库没开。设置 → 八股检测里打开。' };
220
- const q = String(args?.q ?? '').trim();
221
- if (q) {
222
- const row = entry(q);
223
- if (!row) {
224
- const cands = search(q, 3);
225
- return { ok: true, text: cands.length ? '没查到「' + q + '」,接近的:' + cands.map((c) => c.title).join('、') : `没查到「${q}」` };
226
- }
227
- const entryObj = row;
228
- const body = String(entryObj.summary || '')
229
- .replace(/\s+/g, ' ')
230
- .replace(/^(?:含义|来源|用法|简介|解释)\s*/g, '')
231
- .slice(0, 240);
232
- return { ok: true, text: `${entryObj.title}:${body}` };
233
- }
234
- const src = String(args?.text ?? '').trim();
235
- if (!src) return { ok: false, text: '给 text(对方说的话)或 q(要查的词)。' };
236
- const r = bridge(src);
237
- const hint = r.hits.length
238
- ? '[梗] 对方提到:' + r.hits.map((h) => h.title).join('、') +
239
- (r.usage ? '\n怎么接:' + r.usage : '')
240
- : '';
241
-
242
- // aiBridge 开着就走模型拼一句。两条路,先试会话自己的,再试自己配的 key。
243
- if (live.aiBridge) {
244
- const r = bridge(src, list);
245
- if (r.same.length || r.by.length) {
246
- // 路子一:DSH 会话自己的模型(不用填 key)
247
- const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
248
- if (llm) {
249
- const viaSession = await sessionBridge(llm, getRoute(), src, r);
250
- if (viaSession) return { ok: true, text: viaSession };
251
- }
252
- // 路子二:另配的 OpenAI 兼容端点(aiUseOwn 开着才走)
253
- if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
254
- const viaApi = await aiBridge(src, r, {
255
- baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
256
- });
257
- if (viaApi) return { ok: true, text: viaApi };
258
- }
259
- }
260
- }
261
- return { ok: true, text: hint || '没接的。' };
262
- },
263
- });
264
-
265
- ctx.tools.register({
266
- name: 'bagu_guard',
267
- description: TOOL_GUARD,
268
- parameters: {
269
- type: 'object',
270
- properties: {
271
- text: { type: 'string', description: '要发出去的那段话。' },
272
- mode: {
273
- type: 'string',
274
- enum: ['guard', 'report', 'ask'],
275
- description: 'guard 只回 OK/一行改法(默认);report 给详细报告;ask 只给问句。',
276
- },
277
- strict: { type: 'boolean', description: '连轻微信号也拦。' },
278
- full: { type: 'boolean', description: 'mode=report 时给完整输出。' },
279
- n: { type: 'number', description: 'mode=ask 时几条问句,默认 3,最多 6。' },
280
- },
281
- required: ['text'],
282
- },
283
- output: toolOutput(),
284
- execute: async (args) => {
285
- const src = String(args?.text ?? '');
286
- const mode = args?.mode || 'guard';
287
-
288
- if (!src.trim()) {
289
- return { ok: true, text: mode === 'guard' ? 'OK' : '没有文字。' };
290
- }
291
-
292
- if (mode === 'report') {
293
- const r = analyze(src, thresholdsOf(live));
294
- return { ok: true, text: render(r, { full: args?.full === true }) };
295
- }
296
-
297
- if (mode === 'ask') {
298
- const r = analyze(src, thresholdsOf(live));
299
- const n = Math.min(6, Math.max(1, Number(args?.n) || 3));
300
- return { ok: true, text: r.asks.slice(0, n).map((a, i) => `${i + 1}. ${a}`).join('\n') };
301
- }
302
-
303
- const g = guard(src, { strict: args?.strict ?? live.strict });
304
- // 梗库是选装的,默认关。开着就在结果后面附一句,不改判定。
305
- if (live.memes) {
306
- // 发现梗就直接把接梗答案带上 —— agent 不用再调一次 bagu_meme。
307
- const rb = bridge(src);
308
- const hint = rb.hits.length
309
- ? '[梗] 对方提到:' + rb.hits.map((h) => h.title).join('、')
310
- : '';
311
- if (hint) {
312
- // AI 接梗开着就拼具体那句,失败退回族提示
313
- const r = bridge(src);
314
- if (live.aiBridge && (r.same.length || r.by.length)) {
315
- const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
316
- if (llm) {
317
- const viaSession = await sessionBridge(llm, getRoute(), src, r);
318
- if (viaSession) return { ok: true, text: `${g.line}|接:${viaSession}` };
319
- }
320
- if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
321
- const viaApi = await aiBridge(src, r, {
322
- baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
323
- });
324
- if (viaApi) return { ok: true, text: `${g.line}|接:${viaApi}` };
325
- }
326
- }
327
- return { ok: true, text: `${g.line}|${hint}` };
328
- }
329
- }
330
- return { ok: true, text: g.line };
331
- },
332
- });
333
- });
334
-
335
- // ── 词库每日更新 ────────────────────────────────
336
- // 每小时看一次,到点就跑。不用 setInterval(24h) —— 那会跟着启动时刻漂,
337
- // 早上八点开机就永远早上八点更新。按小时对齐才稳定。
338
- root.inject(['timer'], (ctx) => {
339
- let stop = null;
340
- try {
341
- ctx.effect(() => {
342
- const tick = () => {
343
- try {
344
- if (!live.autoUpdate) return;
345
- const st = dbStatus();
346
- if (!st.exists) return;
347
- const hour = new Date().getHours();
348
- const target = Math.max(0, Math.min(23, Number(live.updateHour) || 0));
349
- if (hour !== target) return;
350
- // 今天这个点已经跑过就不再跑
351
- const last = st.lastCheck ? Date.parse(st.lastCheck) : 0;
352
- if (last && new Date(last).toDateString() === new Date().toDateString()) return;
353
- updateOnce({ onLog: () => {} }).catch(() => {});
354
- } catch { /* 定时检查不能炸 */ }
355
- };
356
- // 启动后 30 秒看一次,之后每小时一次
357
- const first = setTimeout(tick, 30000);
358
- const iv = setInterval(tick, 60 * 60 * 1000);
359
- // unref:不阻止进程退出。宿主不调清理函数时也不会挂住。
360
- if (typeof first.unref === 'function') first.unref();
361
- if (typeof iv.unref === 'function') iv.unref();
362
- stop = () => { clearTimeout(first); clearInterval(iv); };
363
- return () => { if (stop) stop(); };
364
- }, 'dsh-bagu: 词库每日更新');
365
- } catch {
366
- /* 宿主没有 timer 服务就算了 */
367
- }
368
- });
369
-
370
- root.inject(['webServer'], (ctx) => {
371
- const handler = async (req, res) => {
372
- const url = new URL(req.url, 'http://127.0.0.1');
373
- const path = url.pathname.replace(/^\/api\/bagu/, '') || '/';
374
-
375
- if (req.method === 'GET' && (path === '/' || path === '/status')) {
376
- return sendJson(res, 200, {
377
- ok: true,
378
- config: live,
379
- defaults: DEFAULTS,
380
- promptActive: live.enabled && live.prompt,
381
- // 词库的规模显示在设置页上 —— 让人知道兜里有多少货
382
- memeTotal: (() => { try { return memeStats().total } catch { return 0 } })(),
383
- // 词库规模与上次检查时间,设置页显示用
384
- lastCheck: (() => {
385
- try {
386
- const st = dbStatus();
387
- return st.lastCheck ? new Date(st.lastCheck).toLocaleString('zh-CN', { hour12: false }) : '';
388
- } catch { return '' }
389
- })(),
390
- memeSizeMB: (() => { try { return dbStatus().sizeMB || 0 } catch { return 0 } })(),
391
- memeWithUsage: (() => { try { return memeStats().withUsage } catch { return 0 } })(),
392
- route: getRoute(),
393
- configFile: CONFIG_FILE,
394
- });
395
- }
396
-
397
- if (req.method === 'POST' && path === '/config') {
398
- const body = await readBody(req);
399
- const next = writeConfig(body);
400
- applyLive(next);
401
- return sendJson(res, 200, { ok: true, config: next });
402
- }
403
-
404
- if (req.method === 'POST' && path === '/guard') {
405
- const body = await readBody(req);
406
- const src = String(body?.text ?? '');
407
- if (!src.trim()) return sendJson(res, 200, { ok: true, line: 'OK' });
408
- const g = guard(src, { strict: body?.strict ?? live.strict });
409
- return sendJson(res, 200, { ok: g.ok, line: g.line, why: g.why, hint: g.hint });
410
- }
411
-
412
- if (req.method === 'POST' && path === '/preview') {
413
- const body = await readBody(req);
414
- const src = String(body?.text ?? '');
415
- if (!src.trim()) return sendJson(res, 200, { ok: false, error: '没有文字' });
416
- const r = analyze(src, thresholdsOf(live));
417
- return sendJson(res, 200, { ok: true, text: render(r, { full: body?.full === true }), band: r.band });
418
- }
419
-
420
- return sendJson(res, 404, { ok: false, error: `unknown ${req.method} ${path}` });
421
- };
422
-
423
- const server = ctx.webServer || (typeof ctx.get === 'function' ? ctx.get('webServer') : undefined);
424
- if (!server || typeof server.register !== 'function') return;
425
- try {
426
- ctx.effect(() => server.register({
427
- kind: 'prefix',
428
- path: '/api/bagu',
429
- handler: (req, res) => {
430
- Promise.resolve(handler(req, res)).catch((e) => {
431
- try { sendJson(res, 500, { ok: false, error: e?.message ?? String(e) }) } catch { /* 已走 */ }
432
- });
433
- },
434
- }), 'dsh-bagu: /api/bagu');
435
- } catch { /* headless 没有 webServer 正常 */ }
436
- });
437
- }
438
-
439
- /** 从 context 里取最后一条用户消息。抄 thawline/dsh-memewiki 的做法。 */
440
- function lastUserText(context) {
441
- try {
442
- const session = context && context.agent && context.agent.session;
443
- if (!session || typeof session.snapshotEvents !== 'function') return '';
444
- const events = session.snapshotEvents() || [];
445
- for (let i = events.length - 1; i >= 0; i--) {
446
- const e = events[i];
447
- const kind = e && (e.type || e.kind);
448
- if (kind !== 'user/message') continue;
449
- const payload = e.payload !== undefined ? e.payload : e.data;
450
- const src = payload && payload.source && payload.source.kind ? String(payload.source.kind) : '';
451
- if (src && src !== 'user') continue;
452
- const txt = payloadText(payload);
453
- if (txt) return txt;
454
- }
455
- } catch { /* 取不到就算了 */ }
456
- return '';
457
- }
458
-
459
- /** 从消息 payload 里抠文本。 */
460
- function payloadText(payload) {
461
- if (!payload) return '';
462
- if (typeof payload === 'string') return payload;
463
- const parts = payload.parts || payload.content || payload.message;
464
- if (typeof parts === 'string') return parts;
465
- if (Array.isArray(parts)) {
466
- return parts
467
- .map((p) => {
468
- if (typeof p === 'string') return p;
469
- if (p && typeof p.text === 'string') return p.text;
470
- return '';
471
- })
472
- .join('\n');
473
- }
474
- return '';
475
- }
1
+ /**
2
+ * dsh-bagu · 宿主半侧
3
+ *
4
+ * 三件事:挂一节提示、挂两个只读工具、开 /api/bagu。
5
+ *
6
+ * 省 token 是这个插件的设计约束,不是优化项:
7
+ * - 提示词压到 150 字以内,每次会话都要烧
8
+ * - 工具描述压到 60 字以内,每次调用都在上下文里
9
+ * - 默认输出三行以内;要看细节传 full: true
10
+ *
11
+ * 所有判断都在本地正则里做完,不调模型 —— 这是零 token 成本的那一半。
12
+ */
13
+
14
+ import { analyze } from './analyze.js';
15
+ import { render, renderBrief } from './render.js';
16
+ import { guard } from './guard.js';
17
+ import { findMemes, entry, search, bridge, stats as memeStats } from './memes.js';
18
+ import { aiBridge } from './ai-bridge.js';
19
+ import { captureRoute, sessionBridge } from './session-bridge.js';
20
+ import { updateOnce, dbStatus, isDue, lastUpdate } from './update.js';
21
+ import { readConfig, writeConfig, CONFIG_FILE, DEFAULTS } from './config.js';
22
+
23
+ export const name = 'dsh-bagu';
24
+
25
+ export { analyze, render, renderBrief };
26
+
27
+ let live = readConfig();
28
+ const syncers = new Set();
29
+
30
+ /** 每次会话都注入,多一个字都是白烧。 */
31
+ const PROMPT = `要发出去的话,先过 bagu_guard。被打回就改,别硬发。`;
32
+
33
+ /** 梗库开着时的追加。告诉 agent 有个查梗工具,遇到不认识的梗先查再答。 */
34
+ const PROMPT_MEME = `
35
+ 遇到网络梗(谐音、缩写、人名外号、视频台词)拿不准意思,先调 bagu_meme 查,别猜。
36
+ 要接梗就传 text(对方原话),它会给出同族能接的;要查单个词就传 q。
37
+ `;
38
+
39
+ /**
40
+ * 玩梗尺度。toneSwitch 关着时不写这段,交给模型自己判断。
41
+ *
42
+ * 0-100 四档。档位不写在提示里,写行为。
43
+ */
44
+ function toneRule(cfg) {
45
+ if (!cfg.toneSwitch) return '';
46
+ const v = Math.max(0, Math.min(100, Number(cfg.toneLevel) || 0));
47
+ let line = '';
48
+ if (v <= 20) {
49
+ line = '玩梗克制。只接正面的、自嘲的、夸人的。外号带贬义的不要复读,不跟着起哄。';
50
+ } else if (v <= 45) {
51
+ line = '可以损发挥、损操作,不损长相、不损身体。别人先开了头、明显在闹,你接半句;不带头用。';
52
+ } else if (v <= 70) {
53
+ line = '跟着社区玩。社区在玩什么就接什么,别自己发明。分寸看着对方的调子走。';
54
+ } else {
55
+ line = '放开玩。带刺的梗也能接,别缩。但收得住——对方认真了、或者真的难受,立刻停。';
56
+ }
57
+ return '\n' + line;
58
+ }
59
+
60
+ /** AI 接梗开着时再加一句。 */
61
+ const PROMPT_AI = `
62
+ 接梗要给出具体那句话,调 bagu_meme 传 text,会自动调模型拼一句。`;
63
+
64
+ /** 60 字。 */
65
+ /** 一个工具,三种模式。描述只占一份。 */
66
+ const TOOL_GUARD = `发出去之前过一遍。默认只回 OK 或一行改法。mode=report 给详细报告,mode=ask 给问句。`;
67
+
68
+ function toolOutput() {
69
+ return {
70
+ schema: {
71
+ type: 'object',
72
+ additionalProperties: true,
73
+ required: ['ok'],
74
+ properties: {
75
+ ok: { type: 'boolean' },
76
+ text: { type: 'string' },
77
+ },
78
+ },
79
+ render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
80
+ };
81
+ }
82
+
83
+ function thresholdsOf(cfg) {
84
+ return {
85
+ hedgeFloor: cfg.hedgeFloor,
86
+ structureTimes: cfg.structureTimes,
87
+ concreteFloor: cfg.concreteFloor,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * memes.js 的 bridge 返回 {hits, usage, origin, tags};
93
+ * AI 接梗(sessionBridge / aiBridge)认的是 {same, by, tags}。
94
+ * 这里转一下 —— 之前直接拿 hits 版去读 r.same.length,
95
+ * AI 接梗一开、文本又命中梗,就是 TypeError: Cannot read properties of undefined (reading 'length')。
96
+ */
97
+ function aiHintOf(r) {
98
+ return { same: (r.hits || []).map((h) => h.title), by: [], tags: r.tags || [] };
99
+ }
100
+
101
+ function applyLive(next) {
102
+ live = next;
103
+ for (const sync of syncers) {
104
+ try { sync(); } catch { /* 单个失败不影响别的 */ }
105
+ }
106
+ }
107
+
108
+ function sendJson(res, status, body) {
109
+ const text = JSON.stringify(body);
110
+ res.statusCode = status;
111
+ res.setHeader('content-type', 'application/json; charset=utf-8');
112
+ res.setHeader('cache-control', 'no-store');
113
+ res.end(text);
114
+ }
115
+
116
+ function readBody(req) {
117
+ return new Promise((resolve) => {
118
+ let raw = '';
119
+ req.on('data', (c) => { raw += c; if (raw.length > 1e6) raw = raw.slice(0, 1e6); });
120
+ req.on('end', () => {
121
+ try { resolve(raw ? JSON.parse(raw) : {}); } catch { resolve({}); }
122
+ });
123
+ req.on('error', () => resolve({}));
124
+ });
125
+ }
126
+
127
+ export function apply(root, config = {}) {
128
+ live = readConfig();
129
+ if (config && typeof config === 'object') {
130
+ for (const k of Object.keys(DEFAULTS)) {
131
+ if (config[k] !== undefined && live[k] === DEFAULTS[k]) live[k] = config[k];
132
+ }
133
+ }
134
+
135
+ root.inject(['systemPrompt'], (ctx) => {
136
+ /** 当轮用户消息。agent/pre-step 里抓,预查注入用这份 —— session 里翻到的常是上一轮。 */
137
+ let currentUserText = '';
138
+ try {
139
+ ctx.on('agent/pre-step', async ({ messages }, next) => {
140
+ try {
141
+ const arr = Array.isArray(messages) ? messages : [];
142
+ for (let i = arr.length - 1; i >= 0; i--) {
143
+ const m = arr[i];
144
+ if (!m || m.role !== 'user') continue;
145
+ const t = payloadText(m);
146
+ if (t) { currentUserText = t; break; }
147
+ }
148
+ } catch { /* 抓不到就算了 */ }
149
+ return next();
150
+ });
151
+ } catch { /* 宿主没这个事件 */ }
152
+ let dispose = null;
153
+ const sync = () => {
154
+ if (dispose) { dispose(); dispose = null; }
155
+ if (!live.enabled || !live.prompt) return;
156
+ // ── 预查注入:用户消息一进来就先查梗,塞进上下文 ──────────
157
+ // 这是「会玩梗」和「能查梗」的分界:前者是模型还没开始想就已经知道,
158
+ // 后者要模型主动调工具(它经常不调)。
159
+ if (live.memes && live.autoMeme) {
160
+ try {
161
+ ctx.effect(() => ctx.systemPrompt.context({
162
+ name: 'bagu:prefetch',
163
+ order: 950,
164
+ text: (context) => {
165
+ try {
166
+ // 只认当轮消息。清空之后不再翻 session —— 那会翻到历史消息,
167
+ // 注入一堆跟本轮无关的梗(实测踩过:问「有人味吗」塞进「检测到前方有XX」)。
168
+ const text = currentUserText;
169
+ if (!text) return '';
170
+ currentUserText = '';
171
+ const r = bridge(text);
172
+ if (!r.hits.length) return '';
173
+ const parts = [];
174
+ parts.push('[梗] 对方提到:' + r.hits.map((h) => h.title).join('、'));
175
+ if (r.usage) parts.push('怎么接:' + r.usage);
176
+ else if (r.origin) parts.push('这梗:' + r.origin);
177
+ if (r.tags.length) parts.push('这一类:' + r.tags.slice(0, 4).join('/'));
178
+ parts.push('照这个接,别念词条出处。');
179
+ return parts.join('\n');
180
+ } catch {
181
+ return '';
182
+ }
183
+ },
184
+ }), 'dsh-bagu: 预查注入');
185
+ } catch {
186
+ /* 宿主没有这个接口就算了 */
187
+ }
188
+ }
189
+
190
+ dispose = ctx.systemPrompt.section({
191
+ name: 'bagu:voice',
192
+ order: live.order,
193
+ text: PROMPT +
194
+ (live.memes ? PROMPT_MEME : '') +
195
+ (live.memes ? toneRule(live) : '') +
196
+ (live.aiBridge && live.memes ? PROMPT_AI : ''),
197
+ });
198
+ };
199
+ sync();
200
+ syncers.add(sync);
201
+ ctx.effect(() => () => {
202
+ syncers.delete(sync);
203
+ if (dispose) dispose();
204
+ }, 'dsh-bagu: 说话的念头');
205
+ });
206
+
207
+ /** 会话自己的路由(provider/model),从 agent/request 抓。抓不到就 null。 */
208
+ let getRoute = () => null;
209
+ root.inject(['llm'], (ctx) => {
210
+ getRoute = captureRoute(ctx);
211
+ });
212
+
213
+ root.inject(['tools'], (ctx) => {
214
+ // 一个工具,三种模式。mode 缺省是守门(日常路径),另外两个是调试用。
215
+ // 始终注册 —— 配置热更新时不用重注册。开关在 execute 里判。
216
+ ctx.tools.register({
217
+ name: 'bagu_meme',
218
+ description: '接梗用:看对方说了什么梗,给出同族能接的。也能查单个词什么意思。',
219
+ parameters: {
220
+ type: 'object',
221
+ properties: {
222
+ text: { type: 'string', description: '对方说的话。给了就找能接的梗。' },
223
+ q: { type: 'string', description: '单个词,查它什么意思。' },
224
+ },
225
+ },
226
+ output: toolOutput(),
227
+ execute: async (args) => {
228
+ // 这个工具始终注册,但梗库关着时不该被调用
229
+ if (!live.memes) return { ok: false, text: '梗库没开。设置 → 八股检测里打开。' };
230
+ const q = String(args?.q ?? '').trim();
231
+ if (q) {
232
+ const row = entry(q);
233
+ if (!row) {
234
+ const cands = search(q, 3);
235
+ return { ok: true, text: cands.length ? '没查到「' + q + '」,接近的:' + cands.map((c) => c.title).join('、') : `没查到「${q}」` };
236
+ }
237
+ const entryObj = row;
238
+ const body = String(entryObj.summary || '')
239
+ .replace(/\s+/g, ' ')
240
+ .replace(/^(?:含义|来源|用法|简介|解释)\s*/g, '')
241
+ .slice(0, 240);
242
+ return { ok: true, text: `${entryObj.title}:${body}` };
243
+ }
244
+ const src = String(args?.text ?? '').trim();
245
+ if (!src) return { ok: false, text: '给 text(对方说的话)或 q(要查的词)。' };
246
+ const r = bridge(src);
247
+ const hint = r.hits.length
248
+ ? '[梗] 对方提到:' + r.hits.map((h) => h.title).join('、') +
249
+ (r.usage ? '\n怎么接:' + r.usage : '')
250
+ : '';
251
+
252
+ // aiBridge 开着就走模型拼一句。两条路,先试会话自己的,再试自己配的 key。
253
+ if (live.aiBridge && r.hits.length) {
254
+ const hintForAi = aiHintOf(r);
255
+ // 路子一:DSH 会话自己的模型(不用填 key)
256
+ const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
257
+ if (llm) {
258
+ const viaSession = await sessionBridge(llm, getRoute(), src, hintForAi);
259
+ if (viaSession) return { ok: true, text: viaSession };
260
+ }
261
+ // 路子二:另配的 OpenAI 兼容端点(aiUseOwn 开着才走)
262
+ if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
263
+ const viaApi = await aiBridge(src, hintForAi, {
264
+ baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
265
+ });
266
+ if (viaApi) return { ok: true, text: viaApi };
267
+ }
268
+ }
269
+ return { ok: true, text: hint || '没接的。' };
270
+ },
271
+ });
272
+
273
+ ctx.tools.register({
274
+ name: 'bagu_guard',
275
+ description: TOOL_GUARD,
276
+ parameters: {
277
+ type: 'object',
278
+ properties: {
279
+ text: { type: 'string', description: '要发出去的那段话。' },
280
+ mode: {
281
+ type: 'string',
282
+ enum: ['guard', 'report', 'ask'],
283
+ description: 'guard 只回 OK/一行改法(默认);report 给详细报告;ask 只给问句。',
284
+ },
285
+ strict: { type: 'boolean', description: '连轻微信号也拦。' },
286
+ full: { type: 'boolean', description: 'mode=report 时给完整输出。' },
287
+ n: { type: 'number', description: 'mode=ask 时几条问句,默认 3,最多 6。' },
288
+ },
289
+ required: ['text'],
290
+ },
291
+ output: toolOutput(),
292
+ execute: async (args) => {
293
+ const src = String(args?.text ?? '');
294
+ const mode = args?.mode || 'guard';
295
+
296
+ if (!src.trim()) {
297
+ return { ok: true, text: mode === 'guard' ? 'OK' : '没有文字。' };
298
+ }
299
+
300
+ if (mode === 'report') {
301
+ const r = analyze(src, thresholdsOf(live));
302
+ return { ok: true, text: render(r, { full: args?.full === true }) };
303
+ }
304
+
305
+ if (mode === 'ask') {
306
+ const r = analyze(src, thresholdsOf(live));
307
+ const n = Math.min(6, Math.max(1, Number(args?.n) || 3));
308
+ return { ok: true, text: r.asks.slice(0, n).map((a, i) => `${i + 1}. ${a}`).join('\n') };
309
+ }
310
+
311
+ const g = guard(src, { strict: args?.strict ?? live.strict });
312
+ // 梗库是选装的,默认关。开着就在结果后面附一句,不改判定。
313
+ if (live.memes) {
314
+ // 发现梗就直接把接梗答案带上 —— agent 不用再调一次 bagu_meme。
315
+ const rb = bridge(src);
316
+ const hint = rb.hits.length
317
+ ? '[梗] 对方提到:' + rb.hits.map((h) => h.title).join('、')
318
+ : '';
319
+ if (hint) {
320
+ // AI 接梗开着就拼具体那句,失败退回族提示
321
+ if (live.aiBridge) {
322
+ const hintForAi = aiHintOf(rb);
323
+ const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
324
+ if (llm) {
325
+ const viaSession = await sessionBridge(llm, getRoute(), src, hintForAi);
326
+ if (viaSession) return { ok: true, text: `${g.line}|接:${viaSession}` };
327
+ }
328
+ if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
329
+ const viaApi = await aiBridge(src, hintForAi, {
330
+ baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
331
+ });
332
+ if (viaApi) return { ok: true, text: `${g.line}|接:${viaApi}` };
333
+ }
334
+ }
335
+ return { ok: true, text: `${g.line}|${hint}` };
336
+ }
337
+ }
338
+ return { ok: true, text: g.line };
339
+ },
340
+ });
341
+ });
342
+
343
+ // ── 词库每日更新 ────────────────────────────────
344
+ // 每小时看一次,到点就跑。不用 setInterval(24h) —— 那会跟着启动时刻漂,
345
+ // 早上八点开机就永远早上八点更新。按小时对齐才稳定。
346
+ root.inject(['timer'], (ctx) => {
347
+ let stop = null;
348
+ try {
349
+ ctx.effect(() => {
350
+ const tick = () => {
351
+ try {
352
+ if (!live.autoUpdate) return;
353
+ const st = dbStatus();
354
+ if (!st.exists) return;
355
+ const hour = new Date().getHours();
356
+ const target = Math.max(0, Math.min(23, Number(live.updateHour) || 0));
357
+ if (hour !== target) return;
358
+ // 今天这个点已经跑过就不再跑
359
+ const last = st.lastCheck ? Date.parse(st.lastCheck) : 0;
360
+ if (last && new Date(last).toDateString() === new Date().toDateString()) return;
361
+ updateOnce({ onLog: () => {} }).catch(() => {});
362
+ } catch { /* 定时检查不能炸 */ }
363
+ };
364
+ // 启动后 30 秒看一次,之后每小时一次
365
+ const first = setTimeout(tick, 30000);
366
+ const iv = setInterval(tick, 60 * 60 * 1000);
367
+ // unref:不阻止进程退出。宿主不调清理函数时也不会挂住。
368
+ if (typeof first.unref === 'function') first.unref();
369
+ if (typeof iv.unref === 'function') iv.unref();
370
+ stop = () => { clearTimeout(first); clearInterval(iv); };
371
+ return () => { if (stop) stop(); };
372
+ }, 'dsh-bagu: 词库每日更新');
373
+ } catch {
374
+ /* 宿主没有 timer 服务就算了 */
375
+ }
376
+ });
377
+
378
+ root.inject(['webServer'], (ctx) => {
379
+ const handler = async (req, res) => {
380
+ const url = new URL(req.url, 'http://127.0.0.1');
381
+ const path = url.pathname.replace(/^\/api\/bagu/, '') || '/';
382
+
383
+ if (req.method === 'GET' && (path === '/' || path === '/status')) {
384
+ return sendJson(res, 200, {
385
+ ok: true,
386
+ config: live,
387
+ defaults: DEFAULTS,
388
+ promptActive: live.enabled && live.prompt,
389
+ // 词库的规模显示在设置页上 —— 让人知道兜里有多少货
390
+ memeTotal: (() => { try { return memeStats().total } catch { return 0 } })(),
391
+ // 词库规模与上次检查时间,设置页显示用
392
+ lastCheck: (() => {
393
+ try {
394
+ const st = dbStatus();
395
+ return st.lastCheck ? new Date(st.lastCheck).toLocaleString('zh-CN', { hour12: false }) : '';
396
+ } catch { return '' }
397
+ })(),
398
+ memeSizeMB: (() => { try { return dbStatus().sizeMB || 0 } catch { return 0 } })(),
399
+ memeWithUsage: (() => { try { return memeStats().withUsage } catch { return 0 } })(),
400
+ route: getRoute(),
401
+ configFile: CONFIG_FILE,
402
+ });
403
+ }
404
+
405
+ if (req.method === 'POST' && path === '/config') {
406
+ const body = await readBody(req);
407
+ const next = writeConfig(body);
408
+ applyLive(next);
409
+ return sendJson(res, 200, { ok: true, config: next });
410
+ }
411
+
412
+ if (req.method === 'POST' && path === '/guard') {
413
+ const body = await readBody(req);
414
+ const src = String(body?.text ?? '');
415
+ if (!src.trim()) return sendJson(res, 200, { ok: true, line: 'OK' });
416
+ const g = guard(src, { strict: body?.strict ?? live.strict });
417
+ return sendJson(res, 200, { ok: g.ok, line: g.line, why: g.why, hint: g.hint });
418
+ }
419
+
420
+ if (req.method === 'POST' && path === '/preview') {
421
+ const body = await readBody(req);
422
+ const src = String(body?.text ?? '');
423
+ if (!src.trim()) return sendJson(res, 200, { ok: false, error: '没有文字' });
424
+ const r = analyze(src, thresholdsOf(live));
425
+ return sendJson(res, 200, { ok: true, text: render(r, { full: body?.full === true }), band: r.band });
426
+ }
427
+
428
+ return sendJson(res, 404, { ok: false, error: `unknown ${req.method} ${path}` });
429
+ };
430
+
431
+ const server = ctx.webServer || (typeof ctx.get === 'function' ? ctx.get('webServer') : undefined);
432
+ if (!server || typeof server.register !== 'function') return;
433
+ try {
434
+ ctx.effect(() => server.register({
435
+ kind: 'prefix',
436
+ path: '/api/bagu',
437
+ handler: (req, res) => {
438
+ Promise.resolve(handler(req, res)).catch((e) => {
439
+ try { sendJson(res, 500, { ok: false, error: e?.message ?? String(e) }) } catch { /* 已走 */ }
440
+ });
441
+ },
442
+ }), 'dsh-bagu: /api/bagu');
443
+ } catch { /* headless 没有 webServer 正常 */ }
444
+ });
445
+ }
446
+
447
+ /** 从 context 里取最后一条用户消息。抄 thawline/dsh-memewiki 的做法。 */
448
+ function lastUserText(context) {
449
+ try {
450
+ const session = context && context.agent && context.agent.session;
451
+ if (!session || typeof session.snapshotEvents !== 'function') return '';
452
+ const events = session.snapshotEvents() || [];
453
+ for (let i = events.length - 1; i >= 0; i--) {
454
+ const e = events[i];
455
+ const kind = e && (e.type || e.kind);
456
+ if (kind !== 'user/message') continue;
457
+ const payload = e.payload !== undefined ? e.payload : e.data;
458
+ const src = payload && payload.source && payload.source.kind ? String(payload.source.kind) : '';
459
+ if (src && src !== 'user') continue;
460
+ const txt = payloadText(payload);
461
+ if (txt) return txt;
462
+ }
463
+ } catch { /* 取不到就算了 */ }
464
+ return '';
465
+ }
466
+
467
+ /** 从消息 payload 里抠文本。 */
468
+ function payloadText(payload) {
469
+ if (!payload) return '';
470
+ if (typeof payload === 'string') return payload;
471
+ const parts = payload.parts || payload.content || payload.message;
472
+ if (typeof parts === 'string') return parts;
473
+ if (Array.isArray(parts)) {
474
+ return parts
475
+ .map((p) => {
476
+ if (typeof p === 'string') return p;
477
+ if (p && typeof p.text === 'string') return p.text;
478
+ return '';
479
+ })
480
+ .join('\n');
481
+ }
482
+ return '';
483
+ }