koishi-plugin-chatluna-think-viewer 2.0.0 → 2.1.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.
Files changed (3) hide show
  1. package/README.md +10 -9
  2. package/index.js +328 -313
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -6,11 +6,11 @@
6
6
  - 依赖 `chatluna-character` 存储的思考上下文,支持命令与前缀关键词调用。
7
7
  - 支持群聊使用(可配置是否允许私聊)。
8
8
  - **异常格式自动撤回/拦截**:默认检测 `<think>`、`<status>`、`<output>`、`<analysis>`、`<system>` 等块或调试 JSON、think/json/yaml 代码块;命中后可选择先发后撤回(recall)或直接阻止(block)。
9
- - **严格输出模式(小白化)**:可选仅允许 `<output><message>…</message></output>` 结构;@ 仅允许数字 user_id,1~5 条 message,不符合即拦截/撤回。
9
+ - **关键词模式**(默认开启):`guardKeywordMode=true` 时按不区分大小写的子串匹配拦截;想用正则可把它关掉。
10
+ - **严格输出模式**(可选):仅当开启 `guardStrictOutputOnly` 时,要求 `<output><message>…</message></output>` 结构;@ 仅允许数字 user_id,1~5 条 message。默认关闭以避免误撤回。
10
11
 
11
12
  ## 安装
12
13
  ```bash
13
- # Koishi 控制台市场搜索 chatluna-think-viewer 安装
14
14
  npm install koishi-plugin-chatluna-think-viewer
15
15
  ```
16
16
 
@@ -24,21 +24,22 @@ plugins:
24
24
  - 查看思考
25
25
  allowPrivate: false
26
26
  emptyMessage: 暂时没有可用的思考记录。
27
- # 异常撤回/拦截
27
+ # 守卫配置
28
28
  guardEnabled: true
29
29
  guardMode: recall # recall | block
30
30
  guardDelay: 1 # 撤回延迟(秒),block 模式忽略
31
- guardStrictOutputOnly: true # 只允许 <output><message>…</message></output>
32
- guardStrictPattern: '^\s*<output>\s*(<message>(?:<at>\d+<\/at>\s*)?(?:<sticker>[^<]*<\/sticker>|[^<]*)<\/message>\s*){1,5}<\/output>\s*$'
31
+ guardKeywordMode: true # 子串匹配关键词(默认)
32
+ guardStrictOutputOnly: false # 严格格式校验默认关闭
33
33
  guardForbiddenPatterns:
34
- - '<think>[\\s\\S]*?<\\/think>'
35
- - '<status>[\\s\\S]*?<\\/status>'
36
- - '```\\s*think[\\s\\S]*?```'
34
+ - '<think>'
35
+ - '<status>'
36
+ - '<output>'
37
+ - '```think'
37
38
  ```
38
39
 
39
40
  ## 使用
40
41
  - 群聊里发送 `think` 或配置的关键词查看最近一次 `<think>` 内容;`think 2` 查看倒数第 2 条。
41
- - 异常/严格模式:当 bot 发送的消息命中禁用规则或不符合严格输出结构时,记录日志并撤回(或直接阻止发送)。
42
+ - 守卫:当 bot 发送的消息命中禁用规则(或在你开启严格模式时不符合格式)会记录日志并阻止/撤回发送。
42
43
 
43
44
  ## 依赖
44
45
  - koishi >= 4.18.0
package/index.js CHANGED
@@ -1,313 +1,328 @@
1
- const { Schema, h } = require('koishi');
2
- const { Bot } = require('@satorijs/core');
3
-
4
- const name = 'chatluna-think-viewer';
5
-
6
- const inject = {
7
- chatluna_character: { required: true },
8
- chatluna: { required: false },
9
- };
10
-
11
- const defaultForbidden = [
12
- '<think>[\\s\\S]*?<\\/think>',
13
- '<status>[\\s\\S]*?<\\/status>',
14
- '<output>[\\s\\S]*?<\\/output>',
15
- '<analysis>[\\s\\S]*?<\\/analysis>',
16
- '<system>[\\s\\S]*?<\\/system>',
17
- '```\\s*think[\\s\\S]*?```',
18
- '```\\s*(json|yaml|yml)[\\s\\S]*?```',
19
- '"role"\\s*:\\s*"assistant"',
20
- '"analysis"\\s*:',
21
- '"thought"\\s*:',
22
- '(?:human_relations|人际关系)\\s*[:=]',
23
- '(?:memory|记忆|记忆点|总结)\\s*[:=]',
24
- ];
25
-
26
- // 严格 <output><message>... 结构:允许文本 / <at>user_id</at> 文本 / <sticker>url</sticker>
27
- // 1~5 条 message,@ 仅允许数字 user_id
28
- const strictOutputPattern =
29
- '^\\s*<output>\\s*(<message>(?:<at>\\d+<\\/at>\\s*)?(?:<sticker>[^<]*<\\/sticker>|[^<]*)<\\/message>\\s*){1,5}<\\/output>\\s*$';
30
-
31
- const Config = Schema.intersect([
32
- Schema.object({
33
- command: Schema.string().default('think').description('\u67e5\u770b\u601d\u8003\u5185\u5bb9\u7684\u6307\u4ee4\u540d'),
34
- keywords: Schema.array(Schema.string()).default(['\u67e5\u770b\u601d\u8003', '\u4e0a\u6b21\u601d\u8003']).description('\u53ef\u65e0\u524d\u7f00\u89e6\u53d1\u7684\u5173\u952e\u8bcd'),
35
- allowPrivate: Schema.boolean().default(false).description('\u662f\u5426\u5141\u8bb8\u5728\u79c1\u804a\u4e2d\u4f7f\u7528'),
36
- emptyMessage: Schema.string().default('\u6682\u65f6\u6ca1\u6709\u53ef\u7528\u7684\u601d\u8003\u8bb0\u5f55\u3002').description('\u6ca1\u6709\u8bb0\u5f55\u65f6\u7684\u63d0\u793a\u6587\u672c'),
37
- renderImage: Schema.boolean().default(false).description('\u662f\u5426\u901a\u8fc7\u0020\u0043\u0068\u0061\u0074\u004c\u0075\u006e\u0061\u0020\u0069\u006d\u0061\u0067\u0065\u0020\u0072\u0065\u006e\u0064\u0065\u0072\u0065\u0072\u0020\u5c06\u601d\u8003\u6e32\u67d3\u4e3a\u56fe\u7247\uff0c\u5931\u8d25\u65f6\u56de\u9000\u6587\u672c'),
38
- }).description('\u601d\u8003\u67e5\u770b\u914d\u7f6e'),
39
- Schema.object({
40
- guardEnabled: Schema.boolean().default(true).description('\u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u62e6\u622a\u5f00\u5173'),
41
- guardMode: Schema.union(['recall', 'block']).default('recall').description('\u0072\u0065\u0063\u0061\u006c\u006c\u003d\u5148\u53d1\u9001\u540e\u64a4\u56de\uff0c\u0062\u006c\u006f\u0063\u006b\u003d\u76f4\u63a5\u963b\u6b62\u53d1\u9001'),
42
- guardDelay: Schema.number().default(1).min(0).max(60).description('\u64a4\u56de\u5ef6\u8fdf\uff08\u79d2\uff09'),
43
- guardAllowPrivate: Schema.boolean().default(true).description('\u662f\u5426\u5728\u79c1\u804a\u4e2d\u4e5f\u542f\u7528\u62e6\u622a'),
44
- guardGroups: Schema.array(Schema.string()).default([]).description('\u53ea\u5728\u8fd9\u4e9b\u7fa4\u751f\u6548\uff0c\u7559\u7a7a\u8868\u793a\u5168\u90e8'),
45
- guardForbiddenPatterns: Schema.array(Schema.string())
46
- .default(defaultForbidden)
47
- .description('\u547d\u4e2d\u5373\u89c6\u4e3a\u5f02\u5e38\u7684\u6a21\u5f0f\uff0c\u7528\u4e8e\u907f\u514d\u601d\u8003\u6cc4\u9732\u6216\u0020\u004a\u0053\u004f\u004e\u0020\u751f\u51fa'),
48
- guardAllowedPatterns: Schema.array(Schema.string())
49
- .default(['[\\s\\S]+'])
50
- .description('\u53ef\u9009\u767d\u540d\u5355\uff0c\u81f3\u5c11\u5339\u914d\u4e00\u4e2a\u624d\u7b97\u6b63\u5e38'),
51
- guardStrictOutputOnly: Schema.boolean()
52
- .default(false)
53
- .description('\u53ea\u5141\u8bb8\u7b26\u5408 <output><message>\u2026</message></output> \u7ed3\u6784\u7684\u6d88\u606f\uff0c\u4e0d\u7b26\u5408\u5373\u62e6\u622a/\u64a4\u56de'),
54
- guardStrictPattern: Schema.string()
55
- .default(strictOutputPattern)
56
- .description('\u81ea\u5b9a\u4e49\u4e25\u683c\u8f93\u51fa\u6b63\u5219\uff1b\u4e3a\u7a7a\u65f6\u4f7f\u7528\u5185\u7f6e\u7684 <output><message>\u2026</message> \u89c4\u5219'),
57
- guardLog: Schema.boolean().default(true).description('\u662f\u5426\u5728\u65e5\u5fd7\u8bb0\u5f55\u5f02\u5e38\u539f\u56e0\u548c\u5185\u5bb9'),
58
- guardContentPreview: Schema.number().default(80).min(10).max(500).description('\u65e5\u5fd7\u5185\u5bb9\u9884\u89c8\u957f\u5ea6'),
59
- }).description('\u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u5904\u7406'),
60
- ]);
61
-
62
- function extractText(content) {
63
- if (content == null) return '';
64
- const normalized = h.normalize(content);
65
- const parts = [];
66
- for (const el of normalized) {
67
- if (typeof el === 'string') {
68
- parts.push(el);
69
- continue;
70
- }
71
- if (Array.isArray(el.children) && el.children.length) {
72
- parts.push(extractText(el.children));
73
- }
74
- const textLike = el.attrs?.content ?? el.attrs?.text ?? el.children?.join?.('') ?? '';
75
- if (textLike) parts.push(textLike);
76
- }
77
- return parts.join('');
78
- }
79
-
80
- function extractThink(text) {
81
- // \u67d0\u4e9b\u6a21\u578b/\u4e2d\u95f4\u4ef6\u4f1a\u5728\u540c\u4e00\u6761\u6d88\u606f\u91cc\u591a\u6b21\u51fa\u73b0 <think>\uff0c\u53d6\u6700\u540e\u4e00\u6b21
82
- let last = '';
83
- const regex = /<think>([\s\S]*?)<\/think>/gi;
84
- let m;
85
- while ((m = regex.exec(text)) !== null) {
86
- last = m[1];
87
- }
88
- return last.trim();
89
- }
90
-
91
- function formatThink(text) {
92
- if (!text) return text;
93
- // \u5c1d\u8bd5\u683c\u5f0f\u5316 JSON\uff0c\u5931\u8d25\u5219\u505a\u57fa\u7840\u53bb\u7a7a\u884c/\u7f29\u8fdb\u7f8e\u5316
94
- try {
95
- const parsed = JSON.parse(text);
96
- return JSON.stringify(parsed, null, 2);
97
- } catch {
98
- const lines = text.split('\n').map((l) => l.trimEnd());
99
- const filtered = lines.filter((l, idx, arr) => !(l === '' && arr[idx - 1] === ''));
100
- const nonEmpty = filtered.filter((l) => l.trim().length > 0);
101
- const minIndent = nonEmpty.length
102
- ? Math.min(
103
- ...nonEmpty.map((l) => {
104
- const m = l.match(/^(\s*)/);
105
- return m ? m[1].length : 0;
106
- }),
107
- )
108
- : 0;
109
- return filtered.map((l) => l.slice(minIndent)).join('\n');
110
- }
111
- }
112
-
113
- function parseIndex(rawIndex) {
114
- if (!rawIndex) return 1;
115
- if (typeof rawIndex === 'number' && Number.isFinite(rawIndex) && rawIndex > 0) return Math.floor(rawIndex);
116
- const match = String(rawIndex).match(/\d+/);
117
- if (!match) return 1;
118
- const num = parseInt(match[0], 10);
119
- return Number.isFinite(num) && num > 0 ? num : 1;
120
- }
121
-
122
- function getNthAiMessage(messages, n = 1) {
123
- if (!Array.isArray(messages) || n < 1) return null;
124
- let count = 0;
125
- for (let i = messages.length - 1; i >= 0; i--) {
126
- const msg = messages[i];
127
- const type = typeof msg?._getType === 'function' ? msg._getType() : msg?.type || msg?.role;
128
- if (type === 'ai' || type === 'assistant') {
129
- count += 1;
130
- if (count === n) return msg;
131
- }
132
- }
133
- return null;
134
- }
135
-
136
- function getNthThink(messages, n = 1) {
137
- if (!Array.isArray(messages) || n < 1) return null;
138
- let count = 0;
139
- for (let i = messages.length - 1; i >= 0; i--) {
140
- const msg = messages[i];
141
- const type = typeof msg?._getType === 'function' ? msg._getType() : msg?.type || msg?.role;
142
- if (type !== 'ai' && type !== 'assistant') continue;
143
- const think = extractThink(extractText(msg.content));
144
- if (!think) continue;
145
- count += 1;
146
- if (count === n) return think;
147
- }
148
- return null;
149
- }
150
-
151
- function getLatestRawThink(temp) {
152
- if (!temp) return '';
153
- const candidates = [
154
- temp?.lastCompletion?.raw?.choices?.[0]?.message?.content,
155
- temp?.lastCompletion?.raw?.content,
156
- temp?.lastCompletion?.content,
157
- ];
158
- for (const c of candidates) {
159
- const think = extractThink(extractText(c));
160
- if (think) return think;
161
- }
162
- return '';
163
- }
164
-
165
- function compileRegex(list) {
166
- return (list || [])
167
- .map((p) => {
168
- try {
169
- return new RegExp(p, 'i');
170
- } catch (err) {
171
- return null;
172
- }
173
- })
174
- .filter(Boolean);
175
- }
176
-
177
- function detectAbnormal(text, forbidden, allowed) {
178
- if (!text) return null;
179
- for (const re of forbidden) {
180
- if (re.test(text)) return `\u547d\u4e2d\u7981\u6b62\u6a21\u5f0f: /${re.source}/`;
181
- }
182
- if (allowed.length && !allowed.some((re) => re.test(text))) {
183
- return '\u672a\u5339\u914d\u4efb\u4f55\u5141\u8bb8\u6a21\u5f0f';
184
- }
185
- return null;
186
- }
187
-
188
- function shorten(text, limit = 80) {
189
- if (!text) return '';
190
- if (text.length <= limit) return text;
191
- return `${text.slice(0, limit)}...(${text.length} chars)`;
192
- }
193
-
194
- function shouldGuard(config, options) {
195
- const session = options?.session;
196
- if (!session) return false;
197
- const guildId = session.guildId || session.event?.guild?.id;
198
- const isGroup = !!guildId;
199
- if (!config.guardAllowPrivate && !isGroup) return false;
200
- if (config.guardGroups?.length && isGroup && !config.guardGroups.includes(guildId)) return false;
201
- return true;
202
- }
203
-
204
- function applyGuard(ctx, config) {
205
- if (!config.guardEnabled) return;
206
- const logger = ctx.logger(`${name}:guard`);
207
- const forbidden = compileRegex(config.guardForbiddenPatterns);
208
- const allowed = config.guardStrictOutputOnly
209
- ? compileRegex([config.guardStrictPattern || strictOutputPattern])
210
- : compileRegex(config.guardAllowedPatterns);
211
- const original = Bot.prototype.sendMessage;
212
-
213
- Bot.prototype.sendMessage = async function patched(channelId, content, referrer, options = {}) {
214
- if (!shouldGuard(config, options)) {
215
- return original.call(this, channelId, content, referrer, options);
216
- }
217
-
218
- const text = extractText(content);
219
- const reason = detectAbnormal(text, forbidden, allowed);
220
-
221
- if (!reason) {
222
- return original.call(this, channelId, content, referrer, options);
223
- }
224
-
225
- const preview = shorten(text, config.guardContentPreview);
226
- if (config.guardMode === 'block') {
227
- if (config.guardLog) logger.warn(`[block] ${reason} | content: ${preview}`);
228
- return [];
229
- }
230
-
231
- const ids = await original.call(this, channelId, content, referrer, options);
232
- if (config.guardLog) logger.warn(`[recall] ${reason} | content: ${preview}`);
233
- const delay = Math.max(0, config.guardDelay) * 1000;
234
- if (Array.isArray(ids) && ids.length && typeof this.deleteMessage === 'function') {
235
- setTimeout(() => {
236
- for (const id of ids) {
237
- this.deleteMessage(channelId, id).catch((err) => {
238
- logger.warn(`[recall-failed] id=${id} reason=${err?.message || err}`);
239
- });
240
- }
241
- }, delay);
242
- }
243
- return ids;
244
- };
245
-
246
- ctx.on('dispose', () => {
247
- Bot.prototype.sendMessage = original;
248
- });
249
- }
250
-
251
- function apply(ctx, config) {
252
- // \u601d\u8003\u67e5\u770b\u6307\u4ee4
253
- const cmd = ctx
254
- .command(`${config.command} [index:string]`, '\u8bfb\u53d6\u4e0a\u4e00\u6761\u542b <think> \u7684\u5185\u5bb9\uff0c\u53ef\u6307\u5b9a\u5012\u6570\u7b2c N \u6761')
255
- .usage('\u4e0d\u5e26\u53c2\u6570\u9ed8\u8ba4\u6700\u65b0\uff1b\u793a\u4f8b\uff1athink 2 \u67e5\u8be2\u5012\u6570\u7b2c 2 \u6761 AI \u56de\u590d\u7684\u601d\u8003');
256
-
257
- for (const keyword of config.keywords || []) {
258
- cmd.shortcut(keyword, { prefix: false });
259
- }
260
-
261
- cmd.action(async ({ session, args }, rawIndex) => {
262
- if (!config.allowPrivate && !session.guildId) {
263
- return '\u4e0d\u652f\u6301\u5728\u79c1\u804a\u4e2d\u67e5\u8be2\u3002';
264
- }
265
-
266
- const service = ctx.chatluna_character;
267
- if (!service) return 'chatluna-character \u672a\u52a0\u8f7d\u3002';
268
-
269
- const temp = await service.getTemp(session);
270
- const targetIndex = parseIndex(rawIndex ?? args?.[0]);
271
-
272
- // 1) \u4f18\u5148\u8bfb\u53d6\u6700\u65b0\u4e00\u6b21\u539f\u59cb\u54cd\u5e94\uff08\u901a\u5e38\u4ecd\u542b <think>\uff09\uff0c\u4ec5\u5bf9\u7b2c 1 \u6761\u6709\u6548
273
- const thinkFromRaw = targetIndex === 1 ? getLatestRawThink(temp) : '';
274
-
275
- // 2) \u5386\u53f2 completionMessages \u4e2d\u771f\u6b63\u5e26 <think> \u7684 AI \u6d88\u606f
276
- const messages = temp?.completionMessages || [];
277
- const thinkFromHistory = thinkFromRaw ? '' : getNthThink(messages, targetIndex);
278
-
279
- // 3) \u56de\u9000\uff1a\u7b2c N \u6761 AI \u6d88\u606f\u518d\u5c1d\u8bd5\u62bd\u53d6 <think>
280
- const fallbackMsg = thinkFromRaw || thinkFromHistory ? null : getNthAiMessage(messages, targetIndex);
281
- const think = thinkFromRaw || thinkFromHistory || extractThink(extractText(fallbackMsg?.content));
282
- const formatted = formatThink(think);
283
- if (!formatted) return config.emptyMessage;
284
-
285
- if (config.renderImage && ctx.chatluna?.renderer) {
286
- try {
287
- const title = `### \u4e0a\u4e00\u6761\u601d\u8003\uff08\u5012\u6570\u7b2c ${targetIndex} \u6761\uff09`;
288
- const markdown = `<div align="center">\n${title}\n</div>\n\n<div align="left">\n${formatted}\n</div>`;
289
- const rendered = await ctx.chatluna.renderer.render(
290
- {
291
- content: [{ type: 'text', text: markdown }],
292
- },
293
- { type: 'image', session },
294
- );
295
- if (rendered?.length) return rendered.map((r) => r.element);
296
- } catch (err) {
297
- ctx.logger?.warn?.('[think-viewer] image render failed, fallback text', err);
298
- }
299
- }
300
-
301
- return `\u4e0a\u4e00\u6761\u601d\u8003\uff08\u5012\u6570\u7b2c ${targetIndex} \u6761\uff09\n${formatted}`;
302
- });
303
-
304
- // \u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u5904\u7406
305
- applyGuard(ctx, config);
306
- }
307
-
308
- module.exports = {
309
- name,
310
- apply,
311
- Config,
312
- inject,
313
- };
1
+ const { Schema, h } = require('koishi');
2
+ const { Bot } = require('@satorijs/core');
3
+
4
+ const name = 'chatluna-think-viewer';
5
+
6
+ const inject = {
7
+ chatluna_character: { required: true },
8
+ chatluna: { required: false },
9
+ };
10
+
11
+ const defaultForbidden = [
12
+ '<think>[\\s\\S]*?<\\/think>',
13
+ '<status>[\\s\\S]*?<\\/status>',
14
+ '<output>[\\s\\S]*?<\\/output>',
15
+ '<analysis>[\\s\\S]*?<\\/analysis>',
16
+ '<system>[\\s\\S]*?<\\/system>',
17
+ '```\\s*think[\\s\\S]*?```',
18
+ '```\\s*(json|yaml|yml)[\\s\\S]*?```',
19
+ '"role"\\s*:\\s*"assistant"',
20
+ '"analysis"\\s*:',
21
+ '"thought"\\s*:',
22
+ '(?:human_relations|人际关系)\\s*[:=]',
23
+ '(?:memory|记忆|记忆点|总结)\\s*[:=]',
24
+ ];
25
+
26
+ // 严格 <output><message>... 结构:允许文本 / <at>user_id</at> 文本 / <sticker>url</sticker>
27
+ // 1~5 条 message,@ 仅允许数字 user_id
28
+ const strictOutputPattern =
29
+ '^\\s*<output>\\s*(<message>(?:<at>\\d+<\\/at>\\s*)?(?:<sticker>[^<]*<\\/sticker>|[^<]*)<\\/message>\\s*){1,5}<\\/output>\\s*$';
30
+
31
+ const Config = Schema.intersect([
32
+ Schema.object({
33
+ command: Schema.string().default('think').description('\u67e5\u770b\u601d\u8003\u5185\u5bb9\u7684\u6307\u4ee4\u540d'),
34
+ keywords: Schema.array(Schema.string()).default(['\u67e5\u770b\u601d\u8003', '\u4e0a\u6b21\u601d\u8003']).description('\u53ef\u65e0\u524d\u7f00\u89e6\u53d1\u7684\u5173\u952e\u8bcd'),
35
+ allowPrivate: Schema.boolean().default(false).description('\u662f\u5426\u5141\u8bb8\u5728\u79c1\u804a\u4e2d\u4f7f\u7528'),
36
+ emptyMessage: Schema.string().default('\u6682\u65f6\u6ca1\u6709\u53ef\u7528\u7684\u601d\u8003\u8bb0\u5f55\u3002').description('\u6ca1\u6709\u8bb0\u5f55\u65f6\u7684\u63d0\u793a\u6587\u672c'),
37
+ renderImage: Schema.boolean().default(false).description('\u662f\u5426\u901a\u8fc7\u0020\u0043\u0068\u0061\u0074\u004c\u0075\u006e\u0061\u0020\u0069\u006d\u0061\u0067\u0065\u0020\u0072\u0065\u006e\u0064\u0065\u0072\u0065\u0072\u0020\u5c06\u601d\u8003\u6e32\u67d3\u4e3a\u56fe\u7247\uff0c\u5931\u8d25\u65f6\u56de\u9000\u6587\u672c'),
38
+ }).description('\u601d\u8003\u67e5\u770b\u914d\u7f6e'),
39
+ Schema.object({
40
+ guardEnabled: Schema.boolean().default(true).description('\u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u62e6\u622a\u5f00\u5173'),
41
+ guardMode: Schema.union(['recall', 'block']).default('recall').description('\u0072\u0065\u0063\u0061\u006c\u006c\u003d\u5148\u53d1\u9001\u540e\u64a4\u56de\uff0c\u0062\u006c\u006f\u0063\u006b\u003d\u76f4\u63a5\u963b\u6b62\u53d1\u9001'),
42
+ guardDelay: Schema.number().default(1).min(0).max(60).description('\u64a4\u56de\u5ef6\u8fdf\uff08\u79d2\uff09'),
43
+ guardAllowPrivate: Schema.boolean().default(true).description('\u662f\u5426\u5728\u79c1\u804a\u4e2d\u4e5f\u542f\u7528\u62e6\u622a'),
44
+ guardGroups: Schema.array(Schema.string()).default([]).description('\u53ea\u5728\u8fd9\u4e9b\u7fa4\u751f\u6548\uff0c\u7559\u7a7a\u8868\u793a\u5168\u90e8'),
45
+ guardKeywordMode: Schema.boolean().default(true).description('true \u65f6\u6309\u5173\u952e\u8bcd\u5b50\u4e32\u5339\u914d(\u4e0d\u533a\u5206\u5927\u5c0f\u5199)\uff0cfalse \u65f6\u6309\u6b63\u5219\u5339\u914d'),
46
+ guardForbiddenPatterns: Schema.array(Schema.string())
47
+ .default(defaultForbidden)
48
+ .description('\u547d\u4e2d\u5373\u89c6\u4e3a\u5f02\u5e38\u7684\u6a21\u5f0f\uff0c\u7528\u4e8e\u907f\u514d\u601d\u8003\u6cc4\u9732\u6216\u0020\u004a\u0053\u004f\u004e\u0020\u751f\u51fa'),
49
+ guardAllowedPatterns: Schema.array(Schema.string())
50
+ .default(['[\\s\\S]+'])
51
+ .description('\u53ef\u9009\u767d\u540d\u5355\uff0c\u81f3\u5c11\u5339\u914d\u4e00\u4e2a\u624d\u7b97\u6b63\u5e38'),
52
+ guardStrictOutputOnly: Schema.boolean()
53
+ .default(false)
54
+ .description('\u53ea\u5141\u8bb8\u7b26\u5408 <output><message>\u2026</message></output> \u7ed3\u6784\u7684\u6d88\u606f\uff0c\u4e0d\u7b26\u5408\u5373\u62e6\u622a/\u64a4\u56de'),
55
+ guardStrictPattern: Schema.string()
56
+ .default(strictOutputPattern)
57
+ .description('\u81ea\u5b9a\u4e49\u4e25\u683c\u8f93\u51fa\u6b63\u5219\uff1b\u4e3a\u7a7a\u65f6\u4f7f\u7528\u5185\u7f6e\u7684 <output><message>\u2026</message> \u89c4\u5219'),
58
+ guardLog: Schema.boolean().default(true).description('\u662f\u5426\u5728\u65e5\u5fd7\u8bb0\u5f55\u5f02\u5e38\u539f\u56e0\u548c\u5185\u5bb9'),
59
+ guardContentPreview: Schema.number().default(80).min(10).max(500).description('\u65e5\u5fd7\u5185\u5bb9\u9884\u89c8\u957f\u5ea6'),
60
+ }).description('\u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u5904\u7406'),
61
+ ]);
62
+
63
+ function extractText(content) {
64
+ if (content == null) return '';
65
+ const normalized = h.normalize(content);
66
+ const parts = [];
67
+ for (const el of normalized) {
68
+ if (typeof el === 'string') {
69
+ parts.push(el);
70
+ continue;
71
+ }
72
+ if (Array.isArray(el.children) && el.children.length) {
73
+ parts.push(extractText(el.children));
74
+ }
75
+ const textLike = el.attrs?.content ?? el.attrs?.text ?? el.children?.join?.('') ?? '';
76
+ if (textLike) parts.push(textLike);
77
+ }
78
+ return parts.join('');
79
+ }
80
+
81
+ function extractThink(text) {
82
+ // \u67d0\u4e9b\u6a21\u578b/\u4e2d\u95f4\u4ef6\u4f1a\u5728\u540c\u4e00\u6761\u6d88\u606f\u91cc\u591a\u6b21\u51fa\u73b0 <think>\uff0c\u53d6\u6700\u540e\u4e00\u6b21
83
+ let last = '';
84
+ const regex = /<think>([\s\S]*?)<\/think>/gi;
85
+ let m;
86
+ while ((m = regex.exec(text)) !== null) {
87
+ last = m[1];
88
+ }
89
+ return last.trim();
90
+ }
91
+
92
+ function formatThink(text) {
93
+ if (!text) return text;
94
+ // \u5c1d\u8bd5\u683c\u5f0f\u5316 JSON\uff0c\u5931\u8d25\u5219\u505a\u57fa\u7840\u53bb\u7a7a\u884c/\u7f29\u8fdb\u7f8e\u5316
95
+ try {
96
+ const parsed = JSON.parse(text);
97
+ return JSON.stringify(parsed, null, 2);
98
+ } catch {
99
+ const lines = text.split('\n').map((l) => l.trimEnd());
100
+ const filtered = lines.filter((l, idx, arr) => !(l === '' && arr[idx - 1] === ''));
101
+ const nonEmpty = filtered.filter((l) => l.trim().length > 0);
102
+ const minIndent = nonEmpty.length
103
+ ? Math.min(
104
+ ...nonEmpty.map((l) => {
105
+ const m = l.match(/^(\s*)/);
106
+ return m ? m[1].length : 0;
107
+ }),
108
+ )
109
+ : 0;
110
+ return filtered.map((l) => l.slice(minIndent)).join('\n');
111
+ }
112
+ }
113
+
114
+ function parseIndex(rawIndex) {
115
+ if (!rawIndex) return 1;
116
+ if (typeof rawIndex === 'number' && Number.isFinite(rawIndex) && rawIndex > 0) return Math.floor(rawIndex);
117
+ const match = String(rawIndex).match(/\d+/);
118
+ if (!match) return 1;
119
+ const num = parseInt(match[0], 10);
120
+ return Number.isFinite(num) && num > 0 ? num : 1;
121
+ }
122
+
123
+ function getNthAiMessage(messages, n = 1) {
124
+ if (!Array.isArray(messages) || n < 1) return null;
125
+ let count = 0;
126
+ for (let i = messages.length - 1; i >= 0; i--) {
127
+ const msg = messages[i];
128
+ const type = typeof msg?._getType === 'function' ? msg._getType() : msg?.type || msg?.role;
129
+ if (type === 'ai' || type === 'assistant') {
130
+ count += 1;
131
+ if (count === n) return msg;
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+
137
+ function getNthThink(messages, n = 1) {
138
+ if (!Array.isArray(messages) || n < 1) return null;
139
+ let count = 0;
140
+ for (let i = messages.length - 1; i >= 0; i--) {
141
+ const msg = messages[i];
142
+ const type = typeof msg?._getType === 'function' ? msg._getType() : msg?.type || msg?.role;
143
+ if (type !== 'ai' && type !== 'assistant') continue;
144
+ const think = extractThink(extractText(msg.content));
145
+ if (!think) continue;
146
+ count += 1;
147
+ if (count === n) return think;
148
+ }
149
+ return null;
150
+ }
151
+
152
+ function getLatestRawThink(temp) {
153
+ if (!temp) return '';
154
+ const candidates = [
155
+ temp?.lastCompletion?.raw?.choices?.[0]?.message?.content,
156
+ temp?.lastCompletion?.raw?.content,
157
+ temp?.lastCompletion?.content,
158
+ ];
159
+ for (const c of candidates) {
160
+ const think = extractThink(extractText(c));
161
+ if (think) return think;
162
+ }
163
+ return '';
164
+ }
165
+
166
+ function compileMatchers(list, keywordMode = true) {
167
+ return (list || [])
168
+ .map((p) => {
169
+ const source = String(p || '');
170
+ if (keywordMode) {
171
+ const needle = source.toLowerCase();
172
+ return { test: (text = '') => text.toLowerCase().includes(needle) };
173
+ }
174
+ try {
175
+ const re = new RegExp(source, 'i');
176
+ return { test: (text = '') => re.test(text) };
177
+ } catch (err) {
178
+ return null;
179
+ }
180
+ })
181
+ .filter(Boolean);
182
+ }
183
+
184
+ function detectAbnormal(text, forbidden, allowed, strictMode = false) {
185
+ if (!text) return null;
186
+ for (const m of forbidden) {
187
+ if (m.test(text)) return '??????';
188
+ }
189
+ if (strictMode) {
190
+ if (!allowed.length || !allowed.some((m) => m.test(text))) {
191
+ return '?????????';
192
+ }
193
+ return null;
194
+ }
195
+ if (allowed.length && !allowed.some((m) => m.test(text))) {
196
+ return '?????????';
197
+ }
198
+ return null;
199
+ }
200
+
201
+ function shorten(text, limit = 80) {
202
+ if (!text) return '';
203
+ if (text.length <= limit) return text;
204
+ return `${text.slice(0, limit)}...(${text.length} chars)`;
205
+ }
206
+
207
+ function shouldGuard(config, options) {
208
+ const session = options?.session;
209
+ if (!session) return false;
210
+ const guildId = session.guildId || session.event?.guild?.id;
211
+ const isGroup = !!guildId;
212
+ if (!config.guardAllowPrivate && !isGroup) return false;
213
+ if (config.guardGroups?.length && isGroup && !config.guardGroups.includes(guildId)) return false;
214
+ return true;
215
+ }
216
+
217
+ function applyGuard(ctx, config) {
218
+ if (!config.guardEnabled) return;
219
+ const logger = ctx.logger(`${name}:guard`);
220
+ const strictMode = !!config.guardStrictOutputOnly;
221
+ const keywordMode = config.guardKeywordMode !== false;
222
+ const forbidden = compileMatchers(config.guardForbiddenPatterns, keywordMode);
223
+ const allowed = strictMode
224
+ ? compileMatchers([config.guardStrictPattern || strictOutputPattern], false)
225
+ : compileMatchers(config.guardAllowedPatterns, keywordMode);
226
+ const original = Bot.prototype.sendMessage;
227
+
228
+ Bot.prototype.sendMessage = async function patched(channelId, content, referrer, options = {}) {
229
+ if (!shouldGuard(config, options)) {
230
+ return original.call(this, channelId, content, referrer, options);
231
+ }
232
+
233
+ const text = extractText(content);
234
+ const reason = detectAbnormal(text, forbidden, allowed);
235
+
236
+ if (!reason) {
237
+ return original.call(this, channelId, content, referrer, options);
238
+ }
239
+
240
+ const preview = shorten(text, config.guardContentPreview);
241
+ if (config.guardMode === 'block') {
242
+ if (config.guardLog) logger.warn(`[block] ${reason} | content: ${preview}`);
243
+ return [];
244
+ }
245
+
246
+ const ids = await original.call(this, channelId, content, referrer, options);
247
+ if (config.guardLog) logger.warn(`[recall] ${reason} | content: ${preview}`);
248
+ const delay = Math.max(0, config.guardDelay) * 1000;
249
+ if (Array.isArray(ids) && ids.length && typeof this.deleteMessage === 'function') {
250
+ setTimeout(() => {
251
+ for (const id of ids) {
252
+ this.deleteMessage(channelId, id).catch((err) => {
253
+ logger.warn(`[recall-failed] id=${id} reason=${err?.message || err}`);
254
+ });
255
+ }
256
+ }, delay);
257
+ }
258
+ return ids;
259
+ };
260
+
261
+ ctx.on('dispose', () => {
262
+ Bot.prototype.sendMessage = original;
263
+ });
264
+ }
265
+
266
+ function apply(ctx, config) {
267
+ // \u601d\u8003\u67e5\u770b\u6307\u4ee4
268
+ const cmd = ctx
269
+ .command(`${config.command} [index:string]`, '\u8bfb\u53d6\u4e0a\u4e00\u6761\u542b <think> \u7684\u5185\u5bb9\uff0c\u53ef\u6307\u5b9a\u5012\u6570\u7b2c N \u6761')
270
+ .usage('\u4e0d\u5e26\u53c2\u6570\u9ed8\u8ba4\u6700\u65b0\uff1b\u793a\u4f8b\uff1athink 2 \u67e5\u8be2\u5012\u6570\u7b2c 2 \u6761 AI \u56de\u590d\u7684\u601d\u8003');
271
+
272
+ for (const keyword of config.keywords || []) {
273
+ cmd.shortcut(keyword, { prefix: false });
274
+ }
275
+
276
+ cmd.action(async ({ session, args }, rawIndex) => {
277
+ if (!config.allowPrivate && !session.guildId) {
278
+ return '\u4e0d\u652f\u6301\u5728\u79c1\u804a\u4e2d\u67e5\u8be2\u3002';
279
+ }
280
+
281
+ const service = ctx.chatluna_character;
282
+ if (!service) return 'chatluna-character \u672a\u52a0\u8f7d\u3002';
283
+
284
+ const temp = await service.getTemp(session);
285
+ const targetIndex = parseIndex(rawIndex ?? args?.[0]);
286
+
287
+ // 1) \u4f18\u5148\u8bfb\u53d6\u6700\u65b0\u4e00\u6b21\u539f\u59cb\u54cd\u5e94\uff08\u901a\u5e38\u4ecd\u542b <think>\uff09\uff0c\u4ec5\u5bf9\u7b2c 1 \u6761\u6709\u6548
288
+ const thinkFromRaw = targetIndex === 1 ? getLatestRawThink(temp) : '';
289
+
290
+ // 2) \u5386\u53f2 completionMessages \u4e2d\u771f\u6b63\u5e26 <think> \u7684 AI \u6d88\u606f
291
+ const messages = temp?.completionMessages || [];
292
+ const thinkFromHistory = thinkFromRaw ? '' : getNthThink(messages, targetIndex);
293
+
294
+ // 3) \u56de\u9000\uff1a\u7b2c N \u6761 AI \u6d88\u606f\u518d\u5c1d\u8bd5\u62bd\u53d6 <think>
295
+ const fallbackMsg = thinkFromRaw || thinkFromHistory ? null : getNthAiMessage(messages, targetIndex);
296
+ const think = thinkFromRaw || thinkFromHistory || extractThink(extractText(fallbackMsg?.content));
297
+ const formatted = formatThink(think);
298
+ if (!formatted) return config.emptyMessage;
299
+
300
+ if (config.renderImage && ctx.chatluna?.renderer) {
301
+ try {
302
+ const title = `### \u4e0a\u4e00\u6761\u601d\u8003\uff08\u5012\u6570\u7b2c ${targetIndex} \u6761\uff09`;
303
+ const markdown = `<div align="center">\n${title}\n</div>\n\n<div align="left">\n${formatted}\n</div>`;
304
+ const rendered = await ctx.chatluna.renderer.render(
305
+ {
306
+ content: [{ type: 'text', text: markdown }],
307
+ },
308
+ { type: 'image', session },
309
+ );
310
+ if (rendered?.length) return rendered.map((r) => r.element);
311
+ } catch (err) {
312
+ ctx.logger?.warn?.('[think-viewer] image render failed, fallback text', err);
313
+ }
314
+ }
315
+
316
+ return `\u4e0a\u4e00\u6761\u601d\u8003\uff08\u5012\u6570\u7b2c ${targetIndex} \u6761\uff09\n${formatted}`;
317
+ });
318
+
319
+ // \u5f02\u5e38\u8f93\u51fa\u81ea\u52a8\u5904\u7406
320
+ applyGuard(ctx, config);
321
+ }
322
+
323
+ module.exports = {
324
+ name,
325
+ apply,
326
+ Config,
327
+ inject,
328
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-chatluna-think-viewer",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "main": "index.js",
5
5
  "description": "View chatluna <think> blocks and auto recall abnormal formatted replies.",
6
6
  "license": "MIT",