dsh-bagu 0.9.0 → 0.10.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/dsh-plugin.json CHANGED
@@ -3,9 +3,9 @@
3
3
  "manifestVersion": "0.15",
4
4
  "id": "dsh-bagu",
5
5
  "name": "dsh-bagu",
6
- "version": "0.9.0",
6
+ "version": "0.10.1",
7
7
  "license": "MIT",
8
- "description": "AI 对外说话前的一道门:像八股就打回,接梗走会话模型。",
8
+ "description": "AI 对外说话两道门:八股打回,梗接住。",
9
9
  "facets": {
10
10
  "host": {
11
11
  "entry": "lib/index.js",
@@ -29,7 +29,7 @@
29
29
  "x-display": [
30
30
  {
31
31
  "title": "dsh-bagu",
32
- "description": "所有对外文本发出前过一遍,像八股就打回。接梗默认走会话模型,不用填 key。"
32
+ "description": "发出去的话像八股就打回;对方抛梗,模型开始想之前就已经把族查好塞进上下文。"
33
33
  }
34
34
  ]
35
35
  }
package/lib/bridge.js CHANGED
@@ -42,8 +42,9 @@ export function bridge(text, memes, opts = {}) {
42
42
  }
43
43
 
44
44
  const hitWords = [];
45
+ const srcLow = src.toLowerCase();
45
46
  for (const k of idx.keys()) {
46
- if (src.toLowerCase().includes(k)) hitWords.push(k);
47
+ if (srcLow.includes(k)) hitWords.push(k);
47
48
  }
48
49
 
49
50
  // 2. 先算「真的提到了」—— 按 slug / title / alias 直接命中,不靠 keyword
@@ -71,8 +72,10 @@ export function bridge(text, memes, opts = {}) {
71
72
  for (const t of (m && m.tags) || []) tags.add(t);
72
73
  }
73
74
 
75
+ // 再兜一道:by 里不许出现 same 已提到的
76
+ const byClean = [...by].filter((x) => !same.has(x));
74
77
  return {
75
- by: [...by].slice(0, max),
78
+ by: byClean.slice(0, max),
76
79
  same: [...same].slice(0, max),
77
80
  tags: [...tags].slice(0, max),
78
81
  };
package/lib/index.js CHANGED
@@ -30,6 +30,16 @@ const syncers = new Set();
30
30
  /** 每次会话都注入,多一个字都是白烧。 */
31
31
  const PROMPT = `要发出去的话,先过 bagu_guard。被打回就改,别硬发。`;
32
32
 
33
+ /** 梗库开着时的追加。告诉 agent 有个查梗工具,遇到不认识的梗先查再答。 */
34
+ const PROMPT_MEME = `
35
+ 遇到网络梗(谐音、缩写、人名外号、视频台词)拿不准意思,先调 bagu_meme 查,别猜。
36
+ 要接梗就传 text(对方原话),它会给出同族能接的;要查单个词就传 q。
37
+ `;
38
+
39
+ /** AI 接梗开着时再加一句。 */
40
+ const PROMPT_AI = `
41
+ 接梗要给出具体那句话,调 bagu_meme 传 text,会自动调模型拼一句。`;
42
+
33
43
  /** 60 字。 */
34
44
  /** 一个工具,三种模式。描述只占一份。 */
35
45
  const TOOL_GUARD = `发出去之前过一遍。默认只回 OK 或一行改法。mode=report 给详细报告,mode=ask 给问句。`;
@@ -92,14 +102,59 @@ export function apply(root, config = {}) {
92
102
  }
93
103
 
94
104
  root.inject(['systemPrompt'], (ctx) => {
105
+ /** 当轮用户消息。agent/pre-step 里抓,预查注入用这份 —— session 里翻到的常是上一轮。 */
106
+ let currentUserText = '';
107
+ try {
108
+ ctx.on('agent/pre-step', async ({ messages }, next) => {
109
+ try {
110
+ const arr = Array.isArray(messages) ? messages : [];
111
+ for (let i = arr.length - 1; i >= 0; i--) {
112
+ const m = arr[i];
113
+ if (!m || m.role !== 'user') continue;
114
+ const t = payloadText(m);
115
+ if (t) { currentUserText = t; break; }
116
+ }
117
+ } catch { /* 抓不到就算了 */ }
118
+ return next();
119
+ });
120
+ } catch { /* 宿主没这个事件 */ }
95
121
  let dispose = null;
96
122
  const sync = () => {
97
123
  if (dispose) { dispose(); dispose = null; }
98
124
  if (!live.enabled || !live.prompt) return;
125
+ // ── 预查注入:用户消息一进来就先查梗,塞进上下文 ──────────
126
+ // 这是「会玩梗」和「能查梗」的分界:前者是模型还没开始想就已经知道,
127
+ // 后者要模型主动调工具(它经常不调)。
128
+ if (live.memes) {
129
+ try {
130
+ ctx.effect(() => ctx.systemPrompt.context({
131
+ name: 'bagu:prefetch',
132
+ order: 950,
133
+ text: (context) => {
134
+ try {
135
+ const text = currentUserText || lastUserText(context);
136
+ if (!text) return '';
137
+ currentUserText = '';
138
+ const list = loadMemes();
139
+ const hint = bridgeHint(text, list);
140
+ if (!hint) return '';
141
+ return '[梗]\n' + hint + '\n照这个接,别解释梗是什么意思。';
142
+ } catch {
143
+ return '';
144
+ }
145
+ },
146
+ }), 'dsh-bagu: 预查注入');
147
+ } catch {
148
+ /* 宿主没有这个接口就算了 */
149
+ }
150
+ }
151
+
99
152
  dispose = ctx.systemPrompt.section({
100
153
  name: 'bagu:voice',
101
154
  order: live.order,
102
- text: PROMPT,
155
+ text: PROMPT +
156
+ (live.memes ? PROMPT_MEME : '') +
157
+ (live.aiBridge && live.memes ? PROMPT_AI : ''),
103
158
  });
104
159
  };
105
160
  sync();
@@ -118,58 +173,59 @@ export function apply(root, config = {}) {
118
173
 
119
174
  root.inject(['tools'], (ctx) => {
120
175
  // 一个工具,三种模式。mode 缺省是守门(日常路径),另外两个是调试用。
121
- if (live.memes) {
122
- ctx.tools.register({
123
- name: 'bagu_meme',
124
- description: '接梗用:看对方说了什么梗,给出同族能接的。也能查单个词什么意思。',
125
- parameters: {
126
- type: 'object',
127
- properties: {
128
- text: { type: 'string', description: '对方说的话。给了就找能接的梗。' },
129
- q: { type: 'string', description: '单个词,查它什么意思。' },
130
- },
176
+ // 始终注册 —— 配置热更新时不用重注册。开关在 execute 里判。
177
+ ctx.tools.register({
178
+ name: 'bagu_meme',
179
+ description: '接梗用:看对方说了什么梗,给出同族能接的。也能查单个词什么意思。',
180
+ parameters: {
181
+ type: 'object',
182
+ properties: {
183
+ text: { type: 'string', description: '对方说的话。给了就找能接的梗。' },
184
+ q: { type: 'string', description: '单个词,查它什么意思。' },
131
185
  },
132
- output: toolOutput(),
133
- execute: async (args) => {
134
- const q = String(args?.q ?? '').trim();
135
- if (q) {
136
- const rows = lookup(q);
137
- const entry = rows && rows[0];
138
- if (!entry) return { ok: true, text: `没查到「${q}」` };
139
- const body = String(entry.summary || '')
140
- .replace(/\s+/g, ' ')
141
- .replace(/^(?:含义|来源|用法|简介|解释)\s*/g, '')
142
- .slice(0, 100);
143
- return { ok: true, text: `${entry.title}:${body}` };
144
- }
145
- const src = String(args?.text ?? '').trim();
146
- if (!src) return { ok: false, text: '给 text(对方说的话)或 q(要查的词)。' };
147
- const list = loadMemes();
148
- const hint = bridgeHint(src, list);
149
-
150
- // aiBridge 开着就走模型拼一句。两条路,先试会话自己的,再试自己配的 key。
151
- if (live.aiBridge) {
152
- const r = bridge(src, list);
153
- if (r.same.length || r.by.length) {
154
- // 路子一:DSH 会话自己的模型(不用填 key)
155
- const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
156
- if (llm) {
157
- const viaSession = await sessionBridge(llm, getRoute(), src, r);
158
- if (viaSession) return { ok: true, text: viaSession };
159
- }
160
- // 路子二:另配的 OpenAI 兼容端点(aiUseOwn 开着才走)
161
- if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
162
- const viaApi = await aiBridge(src, r, {
163
- baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
164
- });
165
- if (viaApi) return { ok: true, text: viaApi };
166
- }
186
+ },
187
+ output: toolOutput(),
188
+ execute: async (args) => {
189
+ // 这个工具始终注册,但梗库关着时不该被调用
190
+ if (!live.memes) return { ok: false, text: '梗库没开。设置 → 八股检测里打开。' };
191
+ const q = String(args?.q ?? '').trim();
192
+ if (q) {
193
+ const rows = lookup(q);
194
+ const entry = rows && rows[0];
195
+ if (!entry) return { ok: true, text: `没查到「${q}」` };
196
+ const body = String(entry.summary || '')
197
+ .replace(/\s+/g, ' ')
198
+ .replace(/^(?:含义|来源|用法|简介|解释)\s*/g, '')
199
+ .slice(0, 240);
200
+ return { ok: true, text: `${entry.title}:${body}` };
201
+ }
202
+ const src = String(args?.text ?? '').trim();
203
+ if (!src) return { ok: false, text: '给 text(对方说的话)或 q(要查的词)。' };
204
+ const list = loadMemes();
205
+ const hint = bridgeHint(src, list);
206
+
207
+ // aiBridge 开着就走模型拼一句。两条路,先试会话自己的,再试自己配的 key。
208
+ if (live.aiBridge) {
209
+ const r = bridge(src, list);
210
+ if (r.same.length || r.by.length) {
211
+ // 路子一:DSH 会话自己的模型(不用填 key)
212
+ const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
213
+ if (llm) {
214
+ const viaSession = await sessionBridge(llm, getRoute(), src, r);
215
+ if (viaSession) return { ok: true, text: viaSession };
216
+ }
217
+ // 路子二:另配的 OpenAI 兼容端点(aiUseOwn 开着才走)
218
+ if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
219
+ const viaApi = await aiBridge(src, r, {
220
+ baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
221
+ });
222
+ if (viaApi) return { ok: true, text: viaApi };
167
223
  }
168
224
  }
169
- return { ok: true, text: hint || '没接的。' };
170
- },
171
- });
172
- }
225
+ }
226
+ return { ok: true, text: hint || '没接的。' };
227
+ },
228
+ });
173
229
 
174
230
  ctx.tools.register({
175
231
  name: 'bagu_guard',
@@ -212,9 +268,26 @@ export function apply(root, config = {}) {
212
268
  const g = guard(src, { strict: args?.strict ?? live.strict });
213
269
  // 梗库是选装的,默认关。开着就在结果后面附一句,不改判定。
214
270
  if (live.memes) {
215
- // 接梗:不是「这段用了哪些梗」,是「顺着这些能接什么」
271
+ // 发现梗就直接把接梗答案带上 —— agent 不用再调一次 bagu_meme。
216
272
  const hint = bridgeHint(src, loadMemes());
217
- if (hint) return { ok: true, text: `${g.line}|${hint}` };
273
+ if (hint) {
274
+ // AI 接梗开着就拼具体那句,失败退回族提示
275
+ const r = bridge(src, loadMemes());
276
+ if (live.aiBridge && (r.same.length || r.by.length)) {
277
+ const llm = ctx.llm || (typeof ctx.get === 'function' ? ctx.get('llm') : undefined);
278
+ if (llm) {
279
+ const viaSession = await sessionBridge(llm, getRoute(), src, r);
280
+ if (viaSession) return { ok: true, text: `${g.line}|接:${viaSession}` };
281
+ }
282
+ if (live.aiUseOwn && live.aiBaseUrl && live.aiModel && live.aiApiKey) {
283
+ const viaApi = await aiBridge(src, r, {
284
+ baseUrl: live.aiBaseUrl, model: live.aiModel, apiKey: live.aiApiKey,
285
+ });
286
+ if (viaApi) return { ok: true, text: `${g.line}|接:${viaApi}` };
287
+ }
288
+ }
289
+ return { ok: true, text: `${g.line}|${hint}` };
290
+ }
218
291
  }
219
292
  return { ok: true, text: g.line };
220
293
  },
@@ -278,3 +351,41 @@ export function apply(root, config = {}) {
278
351
  } catch { /* headless 没有 webServer 正常 */ }
279
352
  });
280
353
  }
354
+
355
+ /** 从 context 里取最后一条用户消息。抄 thawline/dsh-memewiki 的做法。 */
356
+ function lastUserText(context) {
357
+ try {
358
+ const session = context && context.agent && context.agent.session;
359
+ if (!session || typeof session.snapshotEvents !== 'function') return '';
360
+ const events = session.snapshotEvents() || [];
361
+ for (let i = events.length - 1; i >= 0; i--) {
362
+ const e = events[i];
363
+ const kind = e && (e.type || e.kind);
364
+ if (kind !== 'user/message') continue;
365
+ const payload = e.payload !== undefined ? e.payload : e.data;
366
+ const src = payload && payload.source && payload.source.kind ? String(payload.source.kind) : '';
367
+ if (src && src !== 'user') continue;
368
+ const txt = payloadText(payload);
369
+ if (txt) return txt;
370
+ }
371
+ } catch { /* 取不到就算了 */ }
372
+ return '';
373
+ }
374
+
375
+ /** 从消息 payload 里抠文本。 */
376
+ function payloadText(payload) {
377
+ if (!payload) return '';
378
+ if (typeof payload === 'string') return payload;
379
+ const parts = payload.parts || payload.content || payload.message;
380
+ if (typeof parts === 'string') return parts;
381
+ if (Array.isArray(parts)) {
382
+ return parts
383
+ .map((p) => {
384
+ if (typeof p === 'string') return p;
385
+ if (p && typeof p.text === 'string') return p.text;
386
+ return '';
387
+ })
388
+ .join('\n');
389
+ }
390
+ return '';
391
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-bagu",
3
- "version": "0.9.0",
4
- "description": "给 AI 对外说话的一道门:像八股就打回。接梗走会话自己的模型,不用填 key。",
3
+ "version": "0.10.1",
4
+ "description": "两道门:八股打回,梗接住。接梗在模型开始想之前就把族查好。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -0,0 +1,141 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ // 预查注入是「会玩梗」的关键:用户消息一进来就先查好塞进上下文,
6
+ // 不等模型主动调工具。这里测的是「注册了、能算出来、没梗不算」。
7
+ //
8
+ // lastUserText / payloadText 是 index.js 里的内部函数,不导出。
9
+ // 所以这里用搭假宿主 + 读注册出来的 context 函数来测。
10
+
11
+ const SRC = readFileSync('lib/index.js', 'utf8');
12
+
13
+ test('lastUserText 和 payloadText 都有定义', () => {
14
+ // 曾经踩过的坑:函数被引用但没定义,抛 ReferenceError 被 try/catch 吞成空,
15
+ // 外面看不出来,预查永远不命中。
16
+ assert.match(SRC, /function lastUserText\(/, 'lastUserText 没定义');
17
+ assert.match(SRC, /function payloadText\(/, 'payloadText 没定义');
18
+ const refs = (SRC.match(/lastUserText\(/g) || []).length;
19
+ const defs = (SRC.match(/function lastUserText\(/g) || []).length;
20
+ assert.ok(defs >= 1, '有引用 ' + refs + ' 处,定义 ' + defs + ' 处');
21
+ });
22
+
23
+ test('注册了 bagu:prefetch', async () => {
24
+ const { apply } = await import('../lib/index.js');
25
+ const ctxs = [];
26
+ const root = {
27
+ inject(deps, fn) {
28
+ if (deps.includes('llm')) return;
29
+ fn({
30
+ systemPrompt: {
31
+ section() { return () => {} },
32
+ context(o) { ctxs.push(o); return () => {} },
33
+ },
34
+ tools: { register() {} },
35
+ webServer: { register() { return () => {} } },
36
+ effect(fn) { return fn() },
37
+ });
38
+ },
39
+ };
40
+ // memes 默认关,先开
41
+ const fs = await import('node:fs');
42
+ const had = fs.existsSync('./config.json');
43
+ const bak = had ? fs.readFileSync('./config.json', 'utf8') : null;
44
+ fs.writeFileSync('./config.json', JSON.stringify({ enabled: true, memes: true }));
45
+ try {
46
+ apply(root, {});
47
+ } finally {
48
+ if (bak !== null) fs.writeFileSync('./config.json', bak);
49
+ else fs.unlinkSync('./config.json');
50
+ }
51
+ assert.ok(ctxs.length > 0, '没注册 context');
52
+ const c = ctxs[0];
53
+ assert.equal(c.name, 'bagu:prefetch');
54
+ assert.equal(typeof c.text, 'function', 'text 得是函数,才能每轮现算');
55
+ });
56
+
57
+ test('有梗的消息能算出注入文本', async () => {
58
+ const { apply } = await import('../lib/index.js');
59
+ const ctxs = [];
60
+ const root = {
61
+ inject(deps, fn) {
62
+ if (deps.includes('llm')) return;
63
+ fn({
64
+ systemPrompt: {
65
+ section() { return () => {} },
66
+ context(o) { ctxs.push(o); return () => {} },
67
+ },
68
+ tools: { register() {} },
69
+ webServer: { register() { return () => {} } },
70
+ effect(fn) { return fn() },
71
+ });
72
+ },
73
+ };
74
+ const fs = await import('node:fs');
75
+ const bak = fs.existsSync('./config.json') ? fs.readFileSync('./config.json', 'utf8') : null;
76
+ fs.writeFileSync('./config.json', JSON.stringify({ enabled: true, memes: true }));
77
+ try {
78
+ apply(root, {});
79
+ const c = ctxs[0];
80
+ const fake = {
81
+ agent: {
82
+ session: {
83
+ snapshotEvents: () => [
84
+ { type: 'user/message', payload: { content: '这不就是瞎问虾猜那个系列吗' } },
85
+ ],
86
+ },
87
+ },
88
+ };
89
+ const out = c.text(fake);
90
+ assert.ok(out.length > 0, '含梗的消息该算出注入文本');
91
+ assert.match(out, /瞎猜/, '该提到摸到的梗');
92
+
93
+ // 不含梗的不注入
94
+ const fake2 = {
95
+ agent: {
96
+ session: {
97
+ snapshotEvents: () => [
98
+ { type: 'user/message', payload: { content: '帮我看看这个报错' } },
99
+ ],
100
+ },
101
+ },
102
+ };
103
+ assert.equal(c.text(fake2), '', '不含梗不该注入');
104
+ } finally {
105
+ if (bak !== null) fs.writeFileSync('./config.json', bak);
106
+ else if (fs.existsSync('./config.json')) fs.unlinkSync('./config.json');
107
+ }
108
+ });
109
+
110
+ test('取不到 session 时返回空,不崩', async () => {
111
+ const { apply } = await import('../lib/index.js');
112
+ const ctxs = [];
113
+ const root = {
114
+ inject(deps, fn) {
115
+ if (deps.includes('llm')) return;
116
+ fn({
117
+ systemPrompt: {
118
+ section() { return () => {} },
119
+ context(o) { ctxs.push(o); return () => {} },
120
+ },
121
+ tools: { register() {} },
122
+ webServer: { register() { return () => {} } },
123
+ effect(fn) { return fn() },
124
+ });
125
+ },
126
+ };
127
+ const fs = await import('node:fs');
128
+ const bak = fs.existsSync('./config.json') ? fs.readFileSync('./config.json', 'utf8') : null;
129
+ fs.writeFileSync('./config.json', JSON.stringify({ enabled: true, memes: true }));
130
+ try {
131
+ apply(root, {});
132
+ const c = ctxs[0];
133
+ for (const bad of [null, {}, { agent: {} }, { agent: { session: {} } }]) {
134
+ assert.doesNotThrow(() => c.text(bad), '崩在 ' + JSON.stringify(bad));
135
+ assert.equal(c.text(bad), '');
136
+ }
137
+ } finally {
138
+ if (bak !== null) fs.writeFileSync('./config.json', bak);
139
+ else if (fs.existsSync('./config.json')) fs.unlinkSync('./config.json');
140
+ }
141
+ });
@@ -0,0 +1,50 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readFileSync } from 'node:fs';
4
+
5
+ // 真机反馈暴露的两个 bug:
6
+ // 1. bagu_meme 只在 apply 时按 live.memes 注册 → 设置页改了不生效,
7
+ // 提示里说有这个工具,实际函数列表里没有(模型原话:「没有 bagu_meme 工具在函数列表里」)
8
+ // 2. 预查注入从 session 翻消息 → 那时当轮 user/message 还没 append,
9
+ // 拿到的是上一轮的(模型原话:「对方提的是 67 —— 这是承接上一条 67 的」)
10
+ //
11
+ // 这两条都得锁住,不然下次改回去又静默失效。
12
+
13
+ const SRC = readFileSync('lib/index.js', 'utf8');
14
+
15
+ test('bagu_meme 必须无条件注册', () => {
16
+ // 不允许出现 if (live.memes) { ctx.tools.register
17
+ const pat = /if\s*\(\s*live\.memes\s*\)\s*\{\s*ctx\.tools\.register/;
18
+ assert.doesNotMatch(SRC, pat, 'bagu_meme 又被条件包裹了,热更新会失效');
19
+ });
20
+
21
+ test('bagu_meme 的 execute 里有开关检查', () => {
22
+ const i = SRC.indexOf("name: 'bagu_meme'");
23
+ assert.ok(i > 0, '找不到 bagu_meme');
24
+ const tail = SRC.slice(i, i + 600);
25
+ assert.match(tail, /if \(!live\.memes\)/, 'execute 里得判 live.memes,否则关了还能用');
26
+ });
27
+
28
+ test('预查优先用当轮消息,不靠 session 翻', () => {
29
+ assert.match(SRC, /currentUserText \|\| lastUserText/, '预查得优先用 pre-step 抓到的当轮消息');
30
+ });
31
+
32
+ test('注册了 agent/pre-step 钩子', () => {
33
+ assert.match(SRC, /ctx\.on\('agent\/pre-step'/, '没挂 pre-step,当轮消息抓不到');
34
+ });
35
+
36
+ test('pre-step 里取的是 role === user', () => {
37
+ const i = SRC.indexOf("ctx.on('agent/pre-step'");
38
+ assert.ok(i > 0);
39
+ const tail = SRC.slice(i, i + 400);
40
+ assert.match(tail, /role !== 'user'/, '只取 user,别把 assistant 也算进去');
41
+ });
42
+
43
+ test('用完就清,不残留上一轮', () => {
44
+ assert.match(SRC, /currentUserText = '';/, '取完得清掉,不然下一轮没新消息时会复用旧的');
45
+ });
46
+
47
+ test('payloadText 和 lastUserText 都有定义', () => {
48
+ assert.match(SRC, /function payloadText\(/);
49
+ assert.match(SRC, /function lastUserText\(/);
50
+ });