@cmach_socket/opencode-qq-bot 0.3.4 → 0.5.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/NOTICE +63 -0
- package/README.md +170 -20
- package/package.json +20 -2
- package/src/bot-lock.ts +17 -26
- package/src/config.ts +218 -3
- package/src/emoji/command.ts +189 -0
- package/src/emoji/faces.ts +136 -0
- package/src/emoji/favorite-index.ts +150 -0
- package/src/emoji/favorites.ts +161 -0
- package/src/emoji/label.ts +318 -0
- package/src/home.ts +45 -0
- package/src/index.ts +156 -32
- package/src/instance.ts +30 -17
- package/src/keepalive.ts +222 -0
- package/src/logger.ts +273 -17
- package/src/media-path.ts +186 -0
- package/src/model-view.ts +130 -0
- package/src/naplink/client.ts +10 -19
- package/src/naplink/history.ts +258 -0
- package/src/naplink/media.ts +34 -103
- package/src/naplink/render.ts +96 -32
- package/src/outbound.ts +146 -0
- package/src/rate-limit.ts +161 -0
- package/src/safe-fetch.ts +143 -0
- package/src/sensitive.ts +309 -0
- package/src/session/manager.ts +232 -18
- package/src/session/prompt.ts +4 -1
- package/src/tools/ask-guard.ts +3 -2
- package/src/tools/qq.ts +218 -36
- package/src/tools/send-guard.ts +72 -0
package/src/naplink/render.ts
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import type { MessageEvent, MessageSegment, OneBotApi } from "@naplink/naplink"
|
|
2
2
|
import type { ChatTarget } from "../chat"
|
|
3
3
|
import { targetKey } from "../chat"
|
|
4
|
+
import { isCustomFaceImage } from "../emoji/favorites"
|
|
5
|
+
import { renderFace } from "../emoji/faces"
|
|
4
6
|
import type { Logger } from "../logger"
|
|
7
|
+
import {
|
|
8
|
+
neutralizeStructureTags,
|
|
9
|
+
sanitizeSenderName,
|
|
10
|
+
sanitizeUntrustedText,
|
|
11
|
+
StructureTagGuard,
|
|
12
|
+
} from "../model-view"
|
|
5
13
|
import { hydrateSegment } from "./client"
|
|
6
14
|
import {
|
|
7
15
|
MAX_IMAGE_BYTES,
|
|
@@ -57,21 +65,43 @@ function segments(message: readonly MessageSegment[]): readonly Segment[] {
|
|
|
57
65
|
return message as readonly Segment[]
|
|
58
66
|
}
|
|
59
67
|
|
|
68
|
+
/** 图片段的占位文本;收藏表情保留 NapCat 给的 summary,普通图片用 `[图片]`。 */
|
|
69
|
+
function imagePlaceholder(segment: MessageSegment): string {
|
|
70
|
+
const data = segment.data as { summary?: string; sub_type?: unknown }
|
|
71
|
+
if (!isCustomFaceImage(data)) return "[图片]"
|
|
72
|
+
// summary 由表情主人撰写,属于不受信任文本,进提示词前先净化。
|
|
73
|
+
const summary = typeof data.summary === "string" ? sanitizeUntrustedText(data.summary).trim() : ""
|
|
74
|
+
return summary ? summary : "[收藏表情]"
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 渲染器能产出文本的段类型。
|
|
79
|
+
*
|
|
80
|
+
* 与 renderMessage / renderForwardSegments 的分支保持一致:门卫放行的类型必须能被渲染出来,
|
|
81
|
+
* 否则消息会带着空文本进会话。
|
|
82
|
+
*/
|
|
83
|
+
const RENDERABLE_SEGMENT_TYPES: ReadonlySet<string> = new Set([
|
|
84
|
+
"text",
|
|
85
|
+
"at",
|
|
86
|
+
"face",
|
|
87
|
+
"reply",
|
|
88
|
+
"image",
|
|
89
|
+
"record",
|
|
90
|
+
"audio",
|
|
91
|
+
"video",
|
|
92
|
+
"file",
|
|
93
|
+
"json",
|
|
94
|
+
"xml",
|
|
95
|
+
"markdown",
|
|
96
|
+
"forward",
|
|
97
|
+
])
|
|
98
|
+
|
|
60
99
|
/** 判断消息是否含有值得交给模型的内容。 */
|
|
61
100
|
export function shouldProcess(message: readonly MessageSegment[], userId?: string): boolean {
|
|
62
101
|
if (userId && mentionsUser(message, userId)) return true
|
|
63
102
|
return segments(message).some((segment) => {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
return segment.data.text.trim().length > 0
|
|
67
|
-
case "image":
|
|
68
|
-
case "record":
|
|
69
|
-
case "forward":
|
|
70
|
-
case "reply":
|
|
71
|
-
return true
|
|
72
|
-
default:
|
|
73
|
-
return false
|
|
74
|
-
}
|
|
103
|
+
if (segment.type === "text") return segment.data.text.trim().length > 0
|
|
104
|
+
return RENDERABLE_SEGMENT_TYPES.has(segment.type)
|
|
75
105
|
})
|
|
76
106
|
}
|
|
77
107
|
|
|
@@ -161,6 +191,7 @@ async function renderForwardSegments(
|
|
|
161
191
|
depth: number,
|
|
162
192
|
budget: ImageBudget,
|
|
163
193
|
forwardBudget: ForwardBudget,
|
|
194
|
+
guard: StructureTagGuard,
|
|
164
195
|
): Promise<ForwardContent> {
|
|
165
196
|
const parts: string[] = []
|
|
166
197
|
const images: StoredImage[] = []
|
|
@@ -168,13 +199,13 @@ async function renderForwardSegments(
|
|
|
168
199
|
try {
|
|
169
200
|
switch (segment.type) {
|
|
170
201
|
case "text":
|
|
171
|
-
parts.push(segment.data.text)
|
|
202
|
+
parts.push(sanitizeUntrustedText(segment.data.text))
|
|
172
203
|
break
|
|
173
204
|
case "at":
|
|
174
205
|
parts.push(`@${segment.data.qq} `)
|
|
175
206
|
break
|
|
176
207
|
case "image": {
|
|
177
|
-
parts.push(
|
|
208
|
+
parts.push(imagePlaceholder(segment))
|
|
178
209
|
if (budget.images <= 0) break
|
|
179
210
|
await hydrateSegment(ctx.api, segment, ctx.logger)
|
|
180
211
|
const url = segment.data.url || segment.data.file
|
|
@@ -194,10 +225,10 @@ async function renderForwardSegments(
|
|
|
194
225
|
parts.push("[音频]")
|
|
195
226
|
break
|
|
196
227
|
case "file":
|
|
197
|
-
parts.push(`[文件]${segment.data.name || segment.data.file}`)
|
|
228
|
+
parts.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
198
229
|
break
|
|
199
230
|
case "face":
|
|
200
|
-
parts.push(
|
|
231
|
+
parts.push(renderFace(segment.data.id))
|
|
201
232
|
break
|
|
202
233
|
case "json":
|
|
203
234
|
parts.push("[卡片消息]")
|
|
@@ -216,7 +247,14 @@ async function renderForwardSegments(
|
|
|
216
247
|
parts.push("[嵌套合并转发]")
|
|
217
248
|
break
|
|
218
249
|
}
|
|
219
|
-
const nested = await renderForward(
|
|
250
|
+
const nested = await renderForward(
|
|
251
|
+
ctx,
|
|
252
|
+
segment.data.id,
|
|
253
|
+
guard,
|
|
254
|
+
depth + 1,
|
|
255
|
+
budget,
|
|
256
|
+
forwardBudget,
|
|
257
|
+
)
|
|
220
258
|
parts.push(nested.text)
|
|
221
259
|
images.push(...nested.images)
|
|
222
260
|
break
|
|
@@ -232,10 +270,15 @@ async function renderForwardSegments(
|
|
|
232
270
|
return { text: parts.join("").trim(), images }
|
|
233
271
|
}
|
|
234
272
|
|
|
235
|
-
/**
|
|
273
|
+
/**
|
|
274
|
+
* 把合并转发解析成 ``<forward>`` 文本块,并附带其中的图片。
|
|
275
|
+
*
|
|
276
|
+
* 结构标签用占位符保护:整条消息拼好之后要整体净化,插件自己的标签要原样留下。
|
|
277
|
+
*/
|
|
236
278
|
export async function renderForward(
|
|
237
279
|
ctx: RenderContext,
|
|
238
280
|
id: string | undefined,
|
|
281
|
+
guard: StructureTagGuard,
|
|
239
282
|
depth = 0,
|
|
240
283
|
budget: ImageBudget = createImageBudget(),
|
|
241
284
|
forwardBudget: ForwardBudget = createForwardBudget(),
|
|
@@ -253,8 +296,9 @@ export async function renderForward(
|
|
|
253
296
|
}[]
|
|
254
297
|
}
|
|
255
298
|
nodes = (data.messages ?? []).map((entry) => ({
|
|
256
|
-
name:
|
|
299
|
+
name: sanitizeSenderName(
|
|
257
300
|
entry.sender?.card || entry.sender?.nickname || String(entry.sender?.user_id ?? "未知用户"),
|
|
301
|
+
),
|
|
258
302
|
segments: (entry.message ?? []) as MessageSegment[],
|
|
259
303
|
}))
|
|
260
304
|
} catch (error) {
|
|
@@ -272,7 +316,14 @@ export async function renderForward(
|
|
|
272
316
|
}
|
|
273
317
|
forwardBudget.nodes -= 1
|
|
274
318
|
consumed += 1
|
|
275
|
-
const rendered = await renderForwardSegments(
|
|
319
|
+
const rendered = await renderForwardSegments(
|
|
320
|
+
ctx,
|
|
321
|
+
node.segments,
|
|
322
|
+
depth,
|
|
323
|
+
budget,
|
|
324
|
+
forwardBudget,
|
|
325
|
+
guard,
|
|
326
|
+
)
|
|
276
327
|
const line = `${node.name}:${rendered.text || "[空消息]"}`
|
|
277
328
|
const limited = truncateCodePoints(line, Math.max(0, forwardBudget.chars))
|
|
278
329
|
forwardBudget.chars -= Array.from(limited).length
|
|
@@ -287,7 +338,10 @@ export async function renderForward(
|
|
|
287
338
|
if (Array.from(rendered).length > MAX_FORWARD_CHARS) {
|
|
288
339
|
rendered = `${truncateCodePoints(rendered, MAX_FORWARD_CHARS)}\n...(合并转发过长,已截断)`
|
|
289
340
|
}
|
|
290
|
-
return {
|
|
341
|
+
return {
|
|
342
|
+
text: `${guard.protect("<forward>")}\n${rendered}\n${guard.protect("</forward>")}`,
|
|
343
|
+
images,
|
|
344
|
+
}
|
|
291
345
|
}
|
|
292
346
|
|
|
293
347
|
/** 把语音消息转成文字,转写失败时返回空字符串。 */
|
|
@@ -310,22 +364,26 @@ export async function fetchVoiceText(
|
|
|
310
364
|
*
|
|
311
365
|
* 引用消息会展开成 ``<quote>`` 块,合并转发展开成 ``<forward>`` 块,
|
|
312
366
|
* 图片既留占位文本又内联成附件,语音先转写成文字。
|
|
367
|
+
*
|
|
368
|
+
* `budget` 可以和调用方共享,用于让一批消息共用同一份图片预算。
|
|
313
369
|
*/
|
|
314
370
|
export async function renderMessage(
|
|
315
371
|
ctx: RenderContext,
|
|
316
372
|
event: MessageEvent,
|
|
373
|
+
budget: ImageBudget = createImageBudget(),
|
|
317
374
|
): Promise<RenderedMessage> {
|
|
318
375
|
const textBuffer: string[] = []
|
|
319
376
|
const files: PromptFile[] = []
|
|
320
377
|
const message = segments(event.message)
|
|
321
|
-
const budget = createImageBudget()
|
|
322
378
|
const forwardBudget = createForwardBudget()
|
|
323
379
|
const voiceCache = new Map<string, string>()
|
|
380
|
+
// 插件自己生成的结构标签用占位符保护,整条消息净化完再还原。
|
|
381
|
+
const guard = new StructureTagGuard()
|
|
324
382
|
let imageIndex = 0
|
|
325
383
|
|
|
326
384
|
const replySegments = message.filter((segment) => segment.type === "reply")
|
|
327
385
|
if (replySegments.length > 0) {
|
|
328
|
-
const quoteLines = ["<quote>"]
|
|
386
|
+
const quoteLines = [guard.protect("<quote>")]
|
|
329
387
|
for (const segment of replySegments) {
|
|
330
388
|
if (!segment.data.id) continue
|
|
331
389
|
try {
|
|
@@ -333,7 +391,7 @@ export async function renderMessage(
|
|
|
333
391
|
{ sender?: { user_id?: number }; message?: MessageSegment[] } | undefined
|
|
334
392
|
if (!data) continue
|
|
335
393
|
const name = data.sender?.user_id
|
|
336
|
-
? await resolveUserName(ctx, String(data.sender.user_id))
|
|
394
|
+
? sanitizeSenderName(await resolveUserName(ctx, String(data.sender.user_id)))
|
|
337
395
|
: "未知用户"
|
|
338
396
|
const quoted = await renderForwardSegments(
|
|
339
397
|
ctx,
|
|
@@ -341,6 +399,7 @@ export async function renderMessage(
|
|
|
341
399
|
MAX_FORWARD_DEPTH,
|
|
342
400
|
budget,
|
|
343
401
|
forwardBudget,
|
|
402
|
+
guard,
|
|
344
403
|
)
|
|
345
404
|
quoteLines.push(`${name}:${quoted.text || "[空消息]"}`)
|
|
346
405
|
for (const image of quoted.images) {
|
|
@@ -351,7 +410,7 @@ export async function renderMessage(
|
|
|
351
410
|
ctx.logger.warn(`获取引用消息失败 id=${segment.data.id}`, error)
|
|
352
411
|
}
|
|
353
412
|
}
|
|
354
|
-
quoteLines.push("</quote>")
|
|
413
|
+
quoteLines.push(guard.protect("</quote>"))
|
|
355
414
|
textBuffer.push(`${quoteLines.join("\n")}\n`)
|
|
356
415
|
}
|
|
357
416
|
|
|
@@ -359,13 +418,15 @@ export async function renderMessage(
|
|
|
359
418
|
try {
|
|
360
419
|
switch (segment.type) {
|
|
361
420
|
case "text":
|
|
362
|
-
textBuffer.push(segment.data.text)
|
|
421
|
+
textBuffer.push(sanitizeUntrustedText(segment.data.text))
|
|
363
422
|
break
|
|
364
423
|
case "at":
|
|
365
|
-
textBuffer.push(
|
|
424
|
+
textBuffer.push(
|
|
425
|
+
`@${sanitizeSenderName(await resolveUserName(ctx, String(segment.data.qq)))} `,
|
|
426
|
+
)
|
|
366
427
|
break
|
|
367
428
|
case "image": {
|
|
368
|
-
textBuffer.push(
|
|
429
|
+
textBuffer.push(`${imagePlaceholder(segment)} `)
|
|
369
430
|
if (budget.images <= 0) break
|
|
370
431
|
await hydrateSegment(ctx.api, segment, ctx.logger)
|
|
371
432
|
const url = segment.data.url || segment.data.file
|
|
@@ -390,14 +451,14 @@ export async function renderMessage(
|
|
|
390
451
|
voiceText = await fetchVoiceText(ctx, messageId)
|
|
391
452
|
voiceCache.set(key, voiceText)
|
|
392
453
|
}
|
|
393
|
-
textBuffer.push(voiceText ? `[语音] ${voiceText}` : "[语音]")
|
|
454
|
+
textBuffer.push(voiceText ? `[语音] ${sanitizeUntrustedText(voiceText)}` : "[语音]")
|
|
394
455
|
break
|
|
395
456
|
}
|
|
396
457
|
case "reply":
|
|
397
458
|
// 已在外层 quote 块处理过
|
|
398
459
|
break
|
|
399
460
|
case "forward": {
|
|
400
|
-
const forward = await renderForward(ctx, segment.data.id, 0, budget, forwardBudget)
|
|
461
|
+
const forward = await renderForward(ctx, segment.data.id, guard, 0, budget, forwardBudget)
|
|
401
462
|
const prefix =
|
|
402
463
|
textBuffer.length > 0 && !textBuffer[textBuffer.length - 1]?.endsWith("\n") ? "\n" : ""
|
|
403
464
|
textBuffer.push(`${prefix}${forward.text}\n`)
|
|
@@ -417,10 +478,10 @@ export async function renderMessage(
|
|
|
417
478
|
textBuffer.push("[音频]")
|
|
418
479
|
break
|
|
419
480
|
case "file":
|
|
420
|
-
textBuffer.push(`[文件]${segment.data.name || segment.data.file}`)
|
|
481
|
+
textBuffer.push(`[文件]${sanitizeUntrustedText(segment.data.name || segment.data.file)}`)
|
|
421
482
|
break
|
|
422
483
|
case "face":
|
|
423
|
-
textBuffer.push(
|
|
484
|
+
textBuffer.push(renderFace(segment.data.id))
|
|
424
485
|
break
|
|
425
486
|
case "json":
|
|
426
487
|
textBuffer.push("[卡片消息]")
|
|
@@ -441,5 +502,8 @@ export async function renderMessage(
|
|
|
441
502
|
}
|
|
442
503
|
}
|
|
443
504
|
|
|
444
|
-
|
|
505
|
+
// 整条消息拼好之后再整体净化:群友把结构标签拆成两段发过来,
|
|
506
|
+
// 逐段净化匹配不到,只有整体净化才拦得住。
|
|
507
|
+
const text = guard.restore(neutralizeStructureTags(textBuffer.join("")))
|
|
508
|
+
return { text, files }
|
|
445
509
|
}
|
package/src/outbound.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import removeMd from "remove-markdown"
|
|
2
|
+
|
|
3
|
+
/** QQ 单条消息的保守长度上限,超过时按段发送。 */
|
|
4
|
+
export const MAX_MESSAGE_CHARS = 4000
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 剥离 markdown 的选项。
|
|
8
|
+
*
|
|
9
|
+
* 列表符号全部去掉,只留纯文本;链接与图片保留 URL,
|
|
10
|
+
* 否则用户拿到的是一个没有目标的引用。
|
|
11
|
+
*/
|
|
12
|
+
const MARKDOWN_OPTIONS = {
|
|
13
|
+
stripListLeaders: true,
|
|
14
|
+
listUnicodeChar: "",
|
|
15
|
+
separateLinksAndTexts: ": ",
|
|
16
|
+
} as const
|
|
17
|
+
|
|
18
|
+
/** 按字素簇切分,避免把 emoji 序列、肤色修饰符和组合字符切坏。 */
|
|
19
|
+
const segmenter = new Intl.Segmenter("zh", { granularity: "grapheme" })
|
|
20
|
+
|
|
21
|
+
/** 判断一行是不是 markdown 表格的分隔行:每个单元格都只由 - 和 : 组成。 */
|
|
22
|
+
function isTableDelimiter(line: string): boolean {
|
|
23
|
+
const cells = line
|
|
24
|
+
.split("|")
|
|
25
|
+
.map((cell) => cell.trim())
|
|
26
|
+
.filter((cell) => cell.length > 0)
|
|
27
|
+
if (cells.length === 0) return false
|
|
28
|
+
return cells.every((cell) => /^:?-+:?$/.test(cell))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** 一行的单元格数量:去掉首尾竖线带来的空段。 */
|
|
32
|
+
function cellCount(line: string): number {
|
|
33
|
+
const trimmed = line.trim()
|
|
34
|
+
const inner = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed
|
|
35
|
+
const body = inner.endsWith("|") ? inner.slice(0, -1) : inner
|
|
36
|
+
return body.split("|").length
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 判断一行是不是表格行。
|
|
41
|
+
*
|
|
42
|
+
* 只有首尾都带竖线、且列数与表头一致的行才算;
|
|
43
|
+
* 否则表格后面正文里的一个竖线就会把整条正文当成表格行吞掉。
|
|
44
|
+
*/
|
|
45
|
+
function isTableRow(line: string, columns: number): boolean {
|
|
46
|
+
const trimmed = line.trim()
|
|
47
|
+
if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) return false
|
|
48
|
+
return cellCount(trimmed) === columns
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 丢弃 markdown 表格:表头、分隔行和数据行整块删掉,QQ 里表格没法看。
|
|
53
|
+
*
|
|
54
|
+
* 只认首尾带竖线的标准表格;表格后面的正文带着竖线也不会被当成数据行。
|
|
55
|
+
*/
|
|
56
|
+
export function dropTables(content: string): string {
|
|
57
|
+
const lines = content.split("\n")
|
|
58
|
+
const kept: string[] = []
|
|
59
|
+
let index = 0
|
|
60
|
+
while (index < lines.length) {
|
|
61
|
+
const line = lines[index] ?? ""
|
|
62
|
+
const next = index + 1 < lines.length ? (lines[index + 1] ?? "") : undefined
|
|
63
|
+
const columns = next !== undefined ? cellCount(line) : 0
|
|
64
|
+
// 表头与分隔行的列数一致,才当成一张表。
|
|
65
|
+
if (
|
|
66
|
+
next !== undefined &&
|
|
67
|
+
isTableDelimiter(next) &&
|
|
68
|
+
columns > 0 &&
|
|
69
|
+
cellCount(next) === columns &&
|
|
70
|
+
isTableRow(line, columns)
|
|
71
|
+
) {
|
|
72
|
+
index += 2
|
|
73
|
+
while (index < lines.length && isTableRow(lines[index] ?? "", columns)) index += 1
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
kept.push(line)
|
|
77
|
+
index += 1
|
|
78
|
+
}
|
|
79
|
+
return kept.join("\n")
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 图片语法降级成普通链接,否则剥离后会残留 markdown 的 ! 前缀。 */
|
|
83
|
+
function normalizeImages(content: string): string {
|
|
84
|
+
return content.replace(/!\[([^\]]*)\]\(/g, "[$1](")
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 把 markdown 剥成 QQ 友好的纯文本。
|
|
89
|
+
*
|
|
90
|
+
* 表格整块丢弃;链接和图片保留 URL;列表符号去掉,只留正文。
|
|
91
|
+
*/
|
|
92
|
+
export function toPlainText(content: string): string {
|
|
93
|
+
return removeMd(normalizeImages(dropTables(content)), MARKDOWN_OPTIONS)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 按字素簇切分文本。 */
|
|
97
|
+
export function splitGraphemes(content: string): string[] {
|
|
98
|
+
return Array.from(segmenter.segment(content), (item) => item.segment)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 按长度切分消息,保留原有换行与空行。
|
|
103
|
+
*
|
|
104
|
+
* 长度按字素簇计算,不会把 emoji 序列或组合字符切坏。
|
|
105
|
+
* 首部的空行也算内容,不会被吞掉。
|
|
106
|
+
*/
|
|
107
|
+
export function splitMessage(content: string, max = MAX_MESSAGE_CHARS): string[] {
|
|
108
|
+
const limit = Math.max(1, max)
|
|
109
|
+
const chunks: string[] = []
|
|
110
|
+
let current = ""
|
|
111
|
+
let currentLength = 0
|
|
112
|
+
// 当前这段已经放了几行:空行长度为 0,只能靠行数区分“还没内容”和“有空行”。
|
|
113
|
+
let currentLines = 0
|
|
114
|
+
for (const line of content.split("\n")) {
|
|
115
|
+
const parts = splitGraphemes(line)
|
|
116
|
+
const separator = currentLines > 0 ? 1 : 0
|
|
117
|
+
const candidateLength = currentLength + separator + parts.length
|
|
118
|
+
if (candidateLength <= limit) {
|
|
119
|
+
current = currentLines > 0 ? `${current}\n${line}` : line
|
|
120
|
+
currentLength = candidateLength
|
|
121
|
+
currentLines += 1
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
if (currentLines > 0) {
|
|
125
|
+
chunks.push(current)
|
|
126
|
+
current = ""
|
|
127
|
+
currentLength = 0
|
|
128
|
+
currentLines = 0
|
|
129
|
+
}
|
|
130
|
+
let rest = parts
|
|
131
|
+
while (rest.length > limit) {
|
|
132
|
+
chunks.push(rest.slice(0, limit).join(""))
|
|
133
|
+
rest = rest.slice(limit)
|
|
134
|
+
}
|
|
135
|
+
current = rest.join("")
|
|
136
|
+
currentLength = rest.length
|
|
137
|
+
currentLines = 1
|
|
138
|
+
}
|
|
139
|
+
if (currentLines > 0 && (current.length > 0 || chunks.length === 0)) chunks.push(current)
|
|
140
|
+
return chunks.length > 0 ? chunks : [content]
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** 出站文本的统一处理:剥掉 markdown,再按字素簇切分。 */
|
|
144
|
+
export function prepareOutbound(content: string, max = MAX_MESSAGE_CHARS): string[] {
|
|
145
|
+
return splitMessage(toPlainText(content), max)
|
|
146
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Mutex } from "async-mutex"
|
|
2
|
+
import { type ChatTarget, targetKey } from "./chat"
|
|
3
|
+
import type { RateLimitConfig } from "./config"
|
|
4
|
+
|
|
5
|
+
/** 一分钟的毫秒数。 */
|
|
6
|
+
const MINUTE_MS = 60_000
|
|
7
|
+
/** 一小时的毫秒数。 */
|
|
8
|
+
const HOUR_MS = 60 * MINUTE_MS
|
|
9
|
+
|
|
10
|
+
/** 限流判定结果。 */
|
|
11
|
+
export interface RateLimitVerdict {
|
|
12
|
+
/** 是否放行这次发送。 */
|
|
13
|
+
allowed: boolean
|
|
14
|
+
/** 拒绝原因,直接写给模型看;放行时为空串。 */
|
|
15
|
+
reason: string
|
|
16
|
+
/** 为了放行这次发送实际等待的毫秒数。 */
|
|
17
|
+
waitedMs: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 一次出站发送的记录。 */
|
|
21
|
+
interface SendRecord {
|
|
22
|
+
/** 发送时间(毫秒)。 */
|
|
23
|
+
at: number
|
|
24
|
+
/** 所属发送操作;同一次工具调用拆出的多段共用一个 id。 */
|
|
25
|
+
operation?: string
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface SendRateLimiterOptions {
|
|
29
|
+
/** 取当前时间(毫秒),测试时可注入。 */
|
|
30
|
+
now?: () => number
|
|
31
|
+
/** 等待一段时间,测试时可注入。 */
|
|
32
|
+
sleep?: (ms: number) => Promise<void>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 模型驱动的出站消息按目标计数:同一个群共用一份额度。 */
|
|
36
|
+
export function modelSendScope(target: ChatTarget): string {
|
|
37
|
+
return targetKey(target)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 插件自己生成的出站消息单独计数。
|
|
42
|
+
*
|
|
43
|
+
* 命令结果、任务进度不是模型刷屏,不该占用模型回复的额度,
|
|
44
|
+
* 但同样要和其它出站消息隔开一点时间。
|
|
45
|
+
*/
|
|
46
|
+
export function pluginSendScope(target: ChatTarget): string {
|
|
47
|
+
return `${targetKey(target)}#plugin`
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 出站消息的速率限制。
|
|
52
|
+
*
|
|
53
|
+
* 每个目标单独计数。硬上限(每分钟 / 每小时)超出时直接拒绝这次发送,
|
|
54
|
+
* 让模型立刻停下而不是把群刷爆;相邻两次发送间隔不足时先等一等,
|
|
55
|
+
* 攒成一阵发出去也不会连成一片。
|
|
56
|
+
*
|
|
57
|
+
* 计数与限流状态只存在内存里:插件重启后重新开始计数,
|
|
58
|
+
* 短窗口的计数本来也不该跨重启保留。
|
|
59
|
+
*/
|
|
60
|
+
export class SendRateLimiter {
|
|
61
|
+
/** 每个目标最近的发送记录。 */
|
|
62
|
+
private readonly records = new Map<string, SendRecord[]>()
|
|
63
|
+
/** 每个目标的互斥锁,同一目标的并发发送串行判定。 */
|
|
64
|
+
private readonly locks = new Map<string, Mutex>()
|
|
65
|
+
|
|
66
|
+
constructor(
|
|
67
|
+
private readonly config: RateLimitConfig,
|
|
68
|
+
private readonly options: SendRateLimiterOptions = {},
|
|
69
|
+
) {}
|
|
70
|
+
|
|
71
|
+
private get currentTime(): number {
|
|
72
|
+
return (this.options.now ?? Date.now)()
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private get wait(): (ms: number) => Promise<void> {
|
|
76
|
+
return this.options.sleep ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private lock(scope: string): Mutex {
|
|
80
|
+
let lock = this.locks.get(scope)
|
|
81
|
+
if (!lock) {
|
|
82
|
+
lock = new Mutex()
|
|
83
|
+
this.locks.set(scope, lock)
|
|
84
|
+
}
|
|
85
|
+
return lock
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 取目标最近一小时的发送记录,顺手丢掉过期的那几条。 */
|
|
89
|
+
private recent(scope: string, now: number): SendRecord[] {
|
|
90
|
+
const records = this.records.get(scope) ?? []
|
|
91
|
+
const kept = records.filter((record) => now - record.at < HOUR_MS)
|
|
92
|
+
if (kept.length !== records.length) this.records.set(scope, kept)
|
|
93
|
+
return kept
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 申请一次发送许可。
|
|
98
|
+
*
|
|
99
|
+
* @param scope 计数维度,通常是目标键(`group:123`)。
|
|
100
|
+
* @param operation 同一次工具调用拆出的多段共用一个 id:段与段之间不再额外等待。
|
|
101
|
+
* @returns 放行时 `allowed` 为真;被硬上限拦下时带上原因与等待建议。
|
|
102
|
+
*/
|
|
103
|
+
async acquire(scope: string, operation?: string): Promise<RateLimitVerdict> {
|
|
104
|
+
return await this.lock(scope).runExclusive(() => this.admit(scope, operation, true))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 只做节奏控制,永不拒绝。
|
|
109
|
+
*
|
|
110
|
+
* 插件自己生成的消息(命令结果、任务进度)走这里:
|
|
111
|
+
* 它们不是模型刷屏,但同样不该连成一片发出去。
|
|
112
|
+
*/
|
|
113
|
+
async pace(scope: string, operation?: string): Promise<void> {
|
|
114
|
+
await this.lock(scope).runExclusive(() => this.admit(scope, operation, false))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 判定并记账一次发送。 */
|
|
118
|
+
private async admit(
|
|
119
|
+
scope: string,
|
|
120
|
+
operation: string | undefined,
|
|
121
|
+
enforce: boolean,
|
|
122
|
+
): Promise<RateLimitVerdict> {
|
|
123
|
+
const now = this.currentTime
|
|
124
|
+
const records = this.recent(scope, now)
|
|
125
|
+
if (enforce) {
|
|
126
|
+
const minute = records.filter((record) => now - record.at < MINUTE_MS).length
|
|
127
|
+
if (this.config.maxPerMinute > 0 && minute >= this.config.maxPerMinute) {
|
|
128
|
+
return {
|
|
129
|
+
allowed: false,
|
|
130
|
+
reason: `发送频率超限:本分钟已发出 ${minute} 条,最多为每分钟 ${this.config.maxPerMinute} 条。请停止发送并结束本轮。`,
|
|
131
|
+
waitedMs: 0,
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (this.config.maxPerHour > 0 && records.length >= this.config.maxPerHour) {
|
|
135
|
+
return {
|
|
136
|
+
allowed: false,
|
|
137
|
+
reason: `发送频率超限:本小时已发出 ${records.length} 条,最多为每小时 ${this.config.maxPerHour} 条。请停止发送并结束本轮。`,
|
|
138
|
+
waitedMs: 0,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const waitedMs = this.gapDelay(records, now, operation)
|
|
144
|
+
if (waitedMs > 0) await this.wait(waitedMs)
|
|
145
|
+
this.records.set(scope, [
|
|
146
|
+
...records,
|
|
147
|
+
{ at: this.currentTime, ...(operation ? { operation } : {}) },
|
|
148
|
+
])
|
|
149
|
+
return { allowed: true, reason: "", waitedMs }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 距离上一次发送还差多久;同一次操作的多段之间不再等待。 */
|
|
153
|
+
private gapDelay(records: SendRecord[], now: number, operation?: string): number {
|
|
154
|
+
const gap = this.config.minGapMs
|
|
155
|
+
if (gap <= 0) return 0
|
|
156
|
+
const last = records[records.length - 1]
|
|
157
|
+
if (!last) return 0
|
|
158
|
+
if (operation !== undefined && last.operation === operation) return 0
|
|
159
|
+
return Math.max(0, gap - (now - last.at))
|
|
160
|
+
}
|
|
161
|
+
}
|