@tencent-connect/qqbot-nodejs 1.0.3
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/README.md +205 -0
- package/USAGE.md +804 -0
- package/dist/QQBot.d.ts +536 -0
- package/dist/QQBot.d.ts.map +1 -0
- package/dist/QQBot.js +752 -0
- package/dist/QQBot.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +66 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/access-policy.d.ts +54 -0
- package/dist/middleware/access-policy.d.ts.map +1 -0
- package/dist/middleware/access-policy.js +93 -0
- package/dist/middleware/access-policy.js.map +1 -0
- package/dist/middleware/concurrency-guard.d.ts +105 -0
- package/dist/middleware/concurrency-guard.d.ts.map +1 -0
- package/dist/middleware/concurrency-guard.js +325 -0
- package/dist/middleware/concurrency-guard.js.map +1 -0
- package/dist/middleware/content-sanitizer.d.ts +47 -0
- package/dist/middleware/content-sanitizer.d.ts.map +1 -0
- package/dist/middleware/content-sanitizer.js +85 -0
- package/dist/middleware/content-sanitizer.js.map +1 -0
- package/dist/middleware/envelope-formatter.d.ts +51 -0
- package/dist/middleware/envelope-formatter.d.ts.map +1 -0
- package/dist/middleware/envelope-formatter.js +97 -0
- package/dist/middleware/envelope-formatter.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +36 -0
- package/dist/middleware/error-handler.d.ts.map +1 -0
- package/dist/middleware/error-handler.js +59 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/history-buffer.d.ts +84 -0
- package/dist/middleware/history-buffer.d.ts.map +1 -0
- package/dist/middleware/history-buffer.js +113 -0
- package/dist/middleware/history-buffer.js.map +1 -0
- package/dist/middleware/index.d.ts +71 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +48 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/mention-gate.d.ts +99 -0
- package/dist/middleware/mention-gate.d.ts.map +1 -0
- package/dist/middleware/mention-gate.js +117 -0
- package/dist/middleware/mention-gate.js.map +1 -0
- package/dist/middleware/message-filter.d.ts +38 -0
- package/dist/middleware/message-filter.d.ts.map +1 -0
- package/dist/middleware/message-filter.js +60 -0
- package/dist/middleware/message-filter.js.map +1 -0
- package/dist/middleware/quote-ref.d.ts +106 -0
- package/dist/middleware/quote-ref.d.ts.map +1 -0
- package/dist/middleware/quote-ref.js +168 -0
- package/dist/middleware/quote-ref.js.map +1 -0
- package/dist/middleware/rate-limiter.d.ts +43 -0
- package/dist/middleware/rate-limiter.d.ts.map +1 -0
- package/dist/middleware/rate-limiter.js +77 -0
- package/dist/middleware/rate-limiter.js.map +1 -0
- package/dist/middleware/slash-command.d.ts +112 -0
- package/dist/middleware/slash-command.d.ts.map +1 -0
- package/dist/middleware/slash-command.js +203 -0
- package/dist/middleware/slash-command.js.map +1 -0
- package/dist/middleware/types.d.ts +175 -0
- package/dist/middleware/types.d.ts.map +1 -0
- package/dist/middleware/types.js +138 -0
- package/dist/middleware/types.js.map +1 -0
- package/dist/middleware/typing-indicator.d.ts +54 -0
- package/dist/middleware/typing-indicator.d.ts.map +1 -0
- package/dist/middleware/typing-indicator.js +68 -0
- package/dist/middleware/typing-indicator.js.map +1 -0
- package/dist/protocol/api/api-client.d.ts +27 -0
- package/dist/protocol/api/api-client.d.ts.map +1 -0
- package/dist/protocol/api/api-client.js +119 -0
- package/dist/protocol/api/api-client.js.map +1 -0
- package/dist/protocol/api/media-chunked.d.ts +68 -0
- package/dist/protocol/api/media-chunked.d.ts.map +1 -0
- package/dist/protocol/api/media-chunked.js +298 -0
- package/dist/protocol/api/media-chunked.js.map +1 -0
- package/dist/protocol/api/media.d.ts +46 -0
- package/dist/protocol/api/media.d.ts.map +1 -0
- package/dist/protocol/api/media.js +101 -0
- package/dist/protocol/api/media.js.map +1 -0
- package/dist/protocol/api/messages.d.ts +86 -0
- package/dist/protocol/api/messages.d.ts.map +1 -0
- package/dist/protocol/api/messages.js +200 -0
- package/dist/protocol/api/messages.js.map +1 -0
- package/dist/protocol/api/retry.d.ts +23 -0
- package/dist/protocol/api/retry.d.ts.map +1 -0
- package/dist/protocol/api/retry.js +102 -0
- package/dist/protocol/api/retry.js.map +1 -0
- package/dist/protocol/api/routes.d.ts +23 -0
- package/dist/protocol/api/routes.d.ts.map +1 -0
- package/dist/protocol/api/routes.js +50 -0
- package/dist/protocol/api/routes.js.map +1 -0
- package/dist/protocol/api/token.d.ts +38 -0
- package/dist/protocol/api/token.d.ts.map +1 -0
- package/dist/protocol/api/token.js +191 -0
- package/dist/protocol/api/token.js.map +1 -0
- package/dist/protocol/gateway/codec.d.ts +9 -0
- package/dist/protocol/gateway/codec.d.ts.map +1 -0
- package/dist/protocol/gateway/codec.js +32 -0
- package/dist/protocol/gateway/codec.js.map +1 -0
- package/dist/protocol/gateway/constants.d.ts +71 -0
- package/dist/protocol/gateway/constants.d.ts.map +1 -0
- package/dist/protocol/gateway/constants.js +91 -0
- package/dist/protocol/gateway/constants.js.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts +97 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.js +155 -0
- package/dist/protocol/gateway/event-dispatcher.js.map +1 -0
- package/dist/protocol/gateway/gateway-connection.d.ts +73 -0
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -0
- package/dist/protocol/gateway/gateway-connection.js +293 -0
- package/dist/protocol/gateway/gateway-connection.js.map +1 -0
- package/dist/protocol/gateway/reconnect.d.ts +25 -0
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -0
- package/dist/protocol/gateway/reconnect.js +118 -0
- package/dist/protocol/gateway/reconnect.js.map +1 -0
- package/dist/protocol/index.d.ts +41 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +46 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/protocol/transport/index.d.ts +8 -0
- package/dist/protocol/transport/index.d.ts.map +1 -0
- package/dist/protocol/transport/index.js +4 -0
- package/dist/protocol/transport/index.js.map +1 -0
- package/dist/protocol/transport/types.d.ts +109 -0
- package/dist/protocol/transport/types.d.ts.map +1 -0
- package/dist/protocol/transport/types.js +15 -0
- package/dist/protocol/transport/types.js.map +1 -0
- package/dist/protocol/transport/webhook-server-node.d.ts +14 -0
- package/dist/protocol/transport/webhook-server-node.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-server-node.js +57 -0
- package/dist/protocol/transport/webhook-server-node.js.map +1 -0
- package/dist/protocol/transport/webhook-verify.d.ts +49 -0
- package/dist/protocol/transport/webhook-verify.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-verify.js +98 -0
- package/dist/protocol/transport/webhook-verify.js.map +1 -0
- package/dist/protocol/transport/webhook.d.ts +37 -0
- package/dist/protocol/transport/webhook.d.ts.map +1 -0
- package/dist/protocol/transport/webhook.js +183 -0
- package/dist/protocol/transport/webhook.js.map +1 -0
- package/dist/protocol/types.d.ts +270 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +59 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/protocol/utils/audio.d.ts +79 -0
- package/dist/protocol/utils/audio.d.ts.map +1 -0
- package/dist/protocol/utils/audio.js +501 -0
- package/dist/protocol/utils/audio.js.map +1 -0
- package/dist/protocol/utils/decode-media-path.d.ts +26 -0
- package/dist/protocol/utils/decode-media-path.d.ts.map +1 -0
- package/dist/protocol/utils/decode-media-path.js +79 -0
- package/dist/protocol/utils/decode-media-path.js.map +1 -0
- package/dist/protocol/utils/ffmpeg.d.ts +38 -0
- package/dist/protocol/utils/ffmpeg.d.ts.map +1 -0
- package/dist/protocol/utils/ffmpeg.js +119 -0
- package/dist/protocol/utils/ffmpeg.js.map +1 -0
- package/dist/protocol/utils/file-utils.d.ts +42 -0
- package/dist/protocol/utils/file-utils.d.ts.map +1 -0
- package/dist/protocol/utils/file-utils.js +108 -0
- package/dist/protocol/utils/file-utils.js.map +1 -0
- package/dist/protocol/utils/format.d.ts +10 -0
- package/dist/protocol/utils/format.d.ts.map +1 -0
- package/dist/protocol/utils/format.js +68 -0
- package/dist/protocol/utils/format.js.map +1 -0
- package/dist/protocol/utils/image-size.d.ts +56 -0
- package/dist/protocol/utils/image-size.d.ts.map +1 -0
- package/dist/protocol/utils/image-size.js +185 -0
- package/dist/protocol/utils/image-size.js.map +1 -0
- package/dist/protocol/utils/media-source.d.ts +145 -0
- package/dist/protocol/utils/media-source.d.ts.map +1 -0
- package/dist/protocol/utils/media-source.js +175 -0
- package/dist/protocol/utils/media-source.js.map +1 -0
- package/dist/protocol/utils/media-tags.d.ts +15 -0
- package/dist/protocol/utils/media-tags.d.ts.map +1 -0
- package/dist/protocol/utils/media-tags.js +150 -0
- package/dist/protocol/utils/media-tags.js.map +1 -0
- package/dist/protocol/utils/media-type.d.ts +41 -0
- package/dist/protocol/utils/media-type.d.ts.map +1 -0
- package/dist/protocol/utils/media-type.js +89 -0
- package/dist/protocol/utils/media-type.js.map +1 -0
- package/dist/protocol/utils/payload.d.ts +52 -0
- package/dist/protocol/utils/payload.d.ts.map +1 -0
- package/dist/protocol/utils/payload.js +100 -0
- package/dist/protocol/utils/payload.js.map +1 -0
- package/dist/protocol/utils/ref-attachments.d.ts +80 -0
- package/dist/protocol/utils/ref-attachments.d.ts.map +1 -0
- package/dist/protocol/utils/ref-attachments.js +121 -0
- package/dist/protocol/utils/ref-attachments.js.map +1 -0
- package/dist/protocol/utils/ref-index-store.d.ts +69 -0
- package/dist/protocol/utils/ref-index-store.d.ts.map +1 -0
- package/dist/protocol/utils/ref-index-store.js +227 -0
- package/dist/protocol/utils/ref-index-store.js.map +1 -0
- package/dist/protocol/utils/reply-limiter.d.ts +75 -0
- package/dist/protocol/utils/reply-limiter.d.ts.map +1 -0
- package/dist/protocol/utils/reply-limiter.js +123 -0
- package/dist/protocol/utils/reply-limiter.js.map +1 -0
- package/dist/protocol/utils/session-store.d.ts +73 -0
- package/dist/protocol/utils/session-store.d.ts.map +1 -0
- package/dist/protocol/utils/session-store.js +274 -0
- package/dist/protocol/utils/session-store.js.map +1 -0
- package/dist/protocol/utils/target.d.ts +53 -0
- package/dist/protocol/utils/target.d.ts.map +1 -0
- package/dist/protocol/utils/target.js +104 -0
- package/dist/protocol/utils/target.js.map +1 -0
- package/dist/protocol/utils/text-chunk.d.ts +21 -0
- package/dist/protocol/utils/text-chunk.d.ts.map +1 -0
- package/dist/protocol/utils/text-chunk.js +25 -0
- package/dist/protocol/utils/text-chunk.js.map +1 -0
- package/dist/protocol/utils/text-parsing.d.ts +40 -0
- package/dist/protocol/utils/text-parsing.d.ts.map +1 -0
- package/dist/protocol/utils/text-parsing.js +126 -0
- package/dist/protocol/utils/text-parsing.js.map +1 -0
- package/dist/protocol/utils/upload-cache.d.ts +27 -0
- package/dist/protocol/utils/upload-cache.d.ts.map +1 -0
- package/dist/protocol/utils/upload-cache.js +73 -0
- package/dist/protocol/utils/upload-cache.js.map +1 -0
- package/dist/protocol/utils/voice-text.d.ts +9 -0
- package/dist/protocol/utils/voice-text.d.ts.map +1 -0
- package/dist/protocol/utils/voice-text.js +16 -0
- package/dist/protocol/utils/voice-text.js.map +1 -0
- package/dist/storage/index.d.ts +23 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +21 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/kv-store.d.ts +85 -0
- package/dist/storage/kv-store.d.ts.map +1 -0
- package/dist/storage/kv-store.js +184 -0
- package/dist/storage/kv-store.js.map +1 -0
- package/dist/storage/session-adapter.d.ts +35 -0
- package/dist/storage/session-adapter.d.ts.map +1 -0
- package/dist/storage/session-adapter.js +48 -0
- package/dist/storage/session-adapter.js.map +1 -0
- package/dist/streaming.d.ts +67 -0
- package/dist/streaming.d.ts.map +1 -0
- package/dist/streaming.js +207 -0
- package/dist/streaming.js.map +1 -0
- package/package.json +90 -0
- package/src/QQBot.ts +1123 -0
- package/src/index.ts +175 -0
- package/src/middleware/access-policy.ts +139 -0
- package/src/middleware/concurrency-guard.ts +450 -0
- package/src/middleware/content-sanitizer.ts +125 -0
- package/src/middleware/envelope-formatter.ts +140 -0
- package/src/middleware/error-handler.ts +77 -0
- package/src/middleware/history-buffer.ts +169 -0
- package/src/middleware/index.ts +129 -0
- package/src/middleware/mention-gate.ts +227 -0
- package/src/middleware/message-filter.ts +82 -0
- package/src/middleware/quote-ref.ts +237 -0
- package/src/middleware/rate-limiter.ts +112 -0
- package/src/middleware/slash-command.ts +307 -0
- package/src/middleware/types.ts +273 -0
- package/src/middleware/typing-indicator.ts +107 -0
- package/src/protocol/api/api-client.ts +170 -0
- package/src/protocol/api/media-chunked.ts +517 -0
- package/src/protocol/api/media.ts +188 -0
- package/src/protocol/api/messages.ts +345 -0
- package/src/protocol/api/retry.ts +157 -0
- package/src/protocol/api/routes.ts +62 -0
- package/src/protocol/api/token.ts +250 -0
- package/src/protocol/gateway/codec.ts +33 -0
- package/src/protocol/gateway/constants.ts +98 -0
- package/src/protocol/gateway/event-dispatcher.ts +275 -0
- package/src/protocol/gateway/gateway-connection.ts +375 -0
- package/src/protocol/gateway/reconnect.ts +155 -0
- package/src/protocol/index.ts +238 -0
- package/src/protocol/transport/index.ts +17 -0
- package/src/protocol/transport/types.ts +121 -0
- package/src/protocol/transport/webhook-server-node.ts +64 -0
- package/src/protocol/transport/webhook-verify.ts +118 -0
- package/src/protocol/transport/webhook.ts +237 -0
- package/src/protocol/types.ts +305 -0
- package/src/protocol/utils/audio.ts +663 -0
- package/src/protocol/utils/decode-media-path.ts +88 -0
- package/src/protocol/utils/ffmpeg.ts +131 -0
- package/src/protocol/utils/file-utils.ts +121 -0
- package/src/protocol/utils/format.ts +69 -0
- package/src/protocol/utils/image-size.ts +236 -0
- package/src/protocol/utils/media-source.ts +243 -0
- package/src/protocol/utils/media-tags.ts +177 -0
- package/src/protocol/utils/media-type.ts +102 -0
- package/src/protocol/utils/payload.ts +157 -0
- package/src/protocol/utils/ref-attachments.ts +190 -0
- package/src/protocol/utils/ref-index-store.ts +279 -0
- package/src/protocol/utils/reply-limiter.ts +164 -0
- package/src/protocol/utils/session-store.ts +346 -0
- package/src/protocol/utils/target.ts +121 -0
- package/src/protocol/utils/text-chunk.ts +29 -0
- package/src/protocol/utils/text-parsing.ts +153 -0
- package/src/protocol/utils/upload-cache.ts +107 -0
- package/src/protocol/utils/voice-text.ts +16 -0
- package/src/storage/index.ts +24 -0
- package/src/storage/kv-store.ts +243 -0
- package/src/storage/session-adapter.ts +66 -0
- package/src/streaming.ts +255 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Envelope-formatter middleware — assemble LLM prompt context.
|
|
3
|
+
*
|
|
4
|
+
* Gathers information from upstream middleware (history, quote, mention
|
|
5
|
+
* state, sender info) and formats it into a structured context string
|
|
6
|
+
* attached to `ctx.state.envelope`. This is the "last mile" before the
|
|
7
|
+
* user's LLM call — providing a ready-to-use prompt prefix.
|
|
8
|
+
*
|
|
9
|
+
* This middleware is **optional** — users who prefer to build their own
|
|
10
|
+
* prompt can skip it and read `ctx.state.history` / `ctx.state.quote`
|
|
11
|
+
* directly.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
15
|
+
import type { HistoryEntry } from "./history-buffer.js";
|
|
16
|
+
import type { ResolvedQuote } from "./quote-ref.js";
|
|
17
|
+
|
|
18
|
+
export interface EnvelopeFormatterOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Maximum number of history entries to include.
|
|
21
|
+
* Defaults to `5`.
|
|
22
|
+
*/
|
|
23
|
+
historyLimit?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Whether to include the resolved quote in the envelope.
|
|
26
|
+
* Defaults to `true`.
|
|
27
|
+
*/
|
|
28
|
+
includeQuote?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Whether to include sender name / id as context.
|
|
31
|
+
* Defaults to `true`.
|
|
32
|
+
*/
|
|
33
|
+
includeSender?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Custom formatter override. If provided, replaces the default logic
|
|
36
|
+
* entirely. Receives the same ctx and should return the formatted string.
|
|
37
|
+
*/
|
|
38
|
+
format?: (ctx: MiddlewareContext) => string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* bot.use(historyBuffer({ limit: 10 }));
|
|
45
|
+
* bot.use(quoteResolver({ store: refStore }));
|
|
46
|
+
* bot.use(envelopeFormatter({ historyLimit: 5 }));
|
|
47
|
+
*
|
|
48
|
+
* bot.on("message", async (msg) => {
|
|
49
|
+
* const envelope = msg._ctx?.state.envelope as string;
|
|
50
|
+
* const response = await llm.chat(envelope + "\n" + msg.content);
|
|
51
|
+
* await bot.sendText(msg.replyTarget, response);
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export function envelopeFormatter(options: EnvelopeFormatterOptions = {}): Middleware {
|
|
56
|
+
const {
|
|
57
|
+
historyLimit = 5,
|
|
58
|
+
includeQuote = true,
|
|
59
|
+
includeSender = true,
|
|
60
|
+
format,
|
|
61
|
+
} = options;
|
|
62
|
+
|
|
63
|
+
return async (ctx, next) => {
|
|
64
|
+
if (format) {
|
|
65
|
+
ctx.state.envelope = format(ctx);
|
|
66
|
+
} else {
|
|
67
|
+
ctx.state.envelope = buildEnvelope(ctx, { historyLimit, includeQuote, includeSender });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
ctx.log.debug?.(
|
|
71
|
+
`[envelope] built ${(ctx.state.envelope as string).length} chars` +
|
|
72
|
+
` (sender=${includeSender}, quote=${includeQuote}, history=${(ctx.state.history as unknown[] | undefined)?.length ?? 0}/${historyLimit})`,
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
await next();
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function buildEnvelope(
|
|
80
|
+
ctx: MiddlewareContext,
|
|
81
|
+
opts: { historyLimit: number; includeQuote: boolean; includeSender: boolean },
|
|
82
|
+
): string {
|
|
83
|
+
const sections: string[] = [];
|
|
84
|
+
|
|
85
|
+
// ── Context meta ──
|
|
86
|
+
if (opts.includeSender) {
|
|
87
|
+
const name = ctx.message.senderName || ctx.message.senderId;
|
|
88
|
+
const scope = ctx.message.kind === "group"
|
|
89
|
+
? `group(${ctx.message.groupOpenid ?? "unknown"})`
|
|
90
|
+
: ctx.message.kind;
|
|
91
|
+
sections.push(`<from>\nuser: ${name}\nscope: ${scope}\n</from>`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ── Quoted message (reply-to) ──
|
|
95
|
+
if (opts.includeQuote) {
|
|
96
|
+
const quote = ctx.state.quote as ResolvedQuote | undefined;
|
|
97
|
+
if (quote && quote.text) {
|
|
98
|
+
const sender = quote.entry?.senderName || quote.entry?.senderId;
|
|
99
|
+
const line = sender ? `${sender}: ${quote.text}` : quote.text;
|
|
100
|
+
sections.push(`<reply_to>\n${line}\n</reply_to>`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── Conversation history ──
|
|
105
|
+
const history = ctx.state.history as HistoryEntry[] | undefined;
|
|
106
|
+
if (history && history.length > 0) {
|
|
107
|
+
const recent = history.slice(-opts.historyLimit);
|
|
108
|
+
const lines = recent.map((h) => {
|
|
109
|
+
const name = h.senderName || h.senderId;
|
|
110
|
+
return `${name}: ${h.content.slice(0, 200)}`;
|
|
111
|
+
});
|
|
112
|
+
sections.push(`<history>\n${lines.join("\n")}\n</history>`);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ── Current message ──
|
|
116
|
+
const content = (ctx.message.content ?? "").trim();
|
|
117
|
+
const attachments = ctx.message.attachments;
|
|
118
|
+
const hasAttachments = attachments && attachments.length > 0;
|
|
119
|
+
|
|
120
|
+
if (content || hasAttachments) {
|
|
121
|
+
const parts: string[] = [];
|
|
122
|
+
if (content) {
|
|
123
|
+
parts.push(content);
|
|
124
|
+
}
|
|
125
|
+
if (hasAttachments) {
|
|
126
|
+
for (const att of attachments) {
|
|
127
|
+
const t = att.content_type.toLowerCase();
|
|
128
|
+
if (t.startsWith("image/")) parts.push(`[image: ${att.filename ?? "image"}]`);
|
|
129
|
+
else if (t.startsWith("audio/") || t === "voice") {
|
|
130
|
+
parts.push(att.asr_refer_text ? `[voice: ${att.asr_refer_text}]` : "[voice]");
|
|
131
|
+
}
|
|
132
|
+
else if (t.startsWith("video/")) parts.push("[video]");
|
|
133
|
+
else parts.push(`[file: ${att.filename ?? "file"}]`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
sections.push(`<message>\n${parts.join("\n")}\n</message>`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return sections.join("\n\n");
|
|
140
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error-handler middleware — catch downstream errors and send a friendly reply.
|
|
3
|
+
*
|
|
4
|
+
* Add this **first** in the chain (before any other middleware) so it sees
|
|
5
|
+
* errors from all downstream stages.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* bot.use(errorHandler({
|
|
10
|
+
* format: (err) => `抱歉,处理消息时出错:${err.message}`,
|
|
11
|
+
* }));
|
|
12
|
+
* bot.use(slashCommand(...));
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { ApiError } from "../protocol/types.js";
|
|
17
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
18
|
+
|
|
19
|
+
export interface ErrorHandlerOptions {
|
|
20
|
+
/** Build a user-facing reply from the caught error. */
|
|
21
|
+
format?: (err: Error, ctx: MiddlewareContext) => string;
|
|
22
|
+
/**
|
|
23
|
+
* If true, also re-throw the error so `bot.on("error")` listeners fire.
|
|
24
|
+
* Defaults to `false` (consume the error after replying).
|
|
25
|
+
*/
|
|
26
|
+
rethrow?: boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Filter — only handle errors that match. Defaults to all `Error`
|
|
29
|
+
* instances. Useful to skip e.g. ApiError 4xx (let the user see them).
|
|
30
|
+
*/
|
|
31
|
+
filter?: (err: Error) => boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const DEFAULT_FORMAT = (err: Error): string => {
|
|
35
|
+
if (err instanceof ApiError) {
|
|
36
|
+
if (err.bizMessage) return `[QQ ${err.bizCode ?? err.httpStatus}] ${err.bizMessage}`;
|
|
37
|
+
return `[QQ ${err.httpStatus}] ${err.message}`;
|
|
38
|
+
}
|
|
39
|
+
return err.message || "Unknown error";
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Build an error-handler middleware. The middleware **wraps** the rest of
|
|
44
|
+
* the chain — if any downstream middleware (or the `message` listener)
|
|
45
|
+
* throws, it catches the error, sends a reply, and optionally re-emits.
|
|
46
|
+
*/
|
|
47
|
+
export function errorHandler(options: ErrorHandlerOptions = {}): Middleware {
|
|
48
|
+
const format = options.format ?? DEFAULT_FORMAT;
|
|
49
|
+
const rethrow = options.rethrow ?? false;
|
|
50
|
+
const filter = options.filter ?? (() => true);
|
|
51
|
+
|
|
52
|
+
return async (ctx, next) => {
|
|
53
|
+
try {
|
|
54
|
+
await next();
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
57
|
+
if (!filter(e)) {
|
|
58
|
+
if (rethrow) throw e;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
ctx.log.error?.(`[error-handler] caught: ${e.message}`);
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const reply = format(e, ctx);
|
|
65
|
+
if (reply) {
|
|
66
|
+
await ctx.bot.sendText(ctx.replyTarget, reply);
|
|
67
|
+
}
|
|
68
|
+
} catch (sendErr) {
|
|
69
|
+
ctx.log.error?.(
|
|
70
|
+
`[error-handler] failed to send error reply: ${sendErr instanceof Error ? sendErr.message : String(sendErr)}`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (rethrow) throw e;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* History-buffer middleware — keep recent group messages around.
|
|
3
|
+
*
|
|
4
|
+
* Many bots want to feed the LLM a few rounds of recent context, even for
|
|
5
|
+
* messages that did not directly @-mention the bot. This middleware
|
|
6
|
+
* silently records every group message into a per-group ring buffer, then
|
|
7
|
+
* exposes the buffered list via `ctx.state.history`.
|
|
8
|
+
*
|
|
9
|
+
* **Pluggable storage** — the actual store is whatever object the user
|
|
10
|
+
* passes in. The SDK ships an in-memory implementation; users can drop in
|
|
11
|
+
* Redis / SQL / file-backed stores via the `HistoryStore` interface.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
15
|
+
import { resolvePolicy } from "./types.js";
|
|
16
|
+
|
|
17
|
+
// ============ Types ============
|
|
18
|
+
|
|
19
|
+
/** One buffered message. */
|
|
20
|
+
export interface HistoryEntry {
|
|
21
|
+
senderId: string;
|
|
22
|
+
senderName?: string;
|
|
23
|
+
content: string;
|
|
24
|
+
timestamp: number;
|
|
25
|
+
/** Original message id (for de-duplication). */
|
|
26
|
+
messageId: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Pluggable storage backend. */
|
|
30
|
+
export interface HistoryStore {
|
|
31
|
+
/** Append one entry into a group's buffer. Caller-provided ordering. */
|
|
32
|
+
append(groupKey: string, entry: HistoryEntry, limit: number): void | Promise<void>;
|
|
33
|
+
/** Return the most-recent entries for a group (oldest → newest). */
|
|
34
|
+
list(groupKey: string, limit: number): HistoryEntry[] | Promise<HistoryEntry[]>;
|
|
35
|
+
/** Optional: clear a group's buffer. */
|
|
36
|
+
clear?(groupKey: string): void | Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface HistoryBufferOptions {
|
|
40
|
+
/** Max entries kept per group. Defaults to 50. */
|
|
41
|
+
limit?: number;
|
|
42
|
+
/** Storage backend. Defaults to {@link MemoryHistoryStore}. */
|
|
43
|
+
store?: HistoryStore;
|
|
44
|
+
/**
|
|
45
|
+
* Whether to record the message even when an upstream middleware called
|
|
46
|
+
* `ctx.stop()` (e.g. mention-gate skipped a no-mention group message).
|
|
47
|
+
* Defaults to `true` — history exists precisely to capture the chatter
|
|
48
|
+
* we did not respond to.
|
|
49
|
+
*/
|
|
50
|
+
recordOnSkip?: boolean;
|
|
51
|
+
/** Group-key derivation. Defaults to `groupOpenid`. */
|
|
52
|
+
groupKey?: (ctx: MiddlewareContext) => string | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ============ In-memory store ============
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Default in-memory history store. Keeps a ring buffer per group key.
|
|
59
|
+
*
|
|
60
|
+
* Suitable for single-process bots; for multi-instance deployments use
|
|
61
|
+
* a Redis / SQL backed implementation.
|
|
62
|
+
*/
|
|
63
|
+
export class MemoryHistoryStore implements HistoryStore {
|
|
64
|
+
private readonly buffers = new Map<string, HistoryEntry[]>();
|
|
65
|
+
|
|
66
|
+
append(groupKey: string, entry: HistoryEntry, limit: number): void {
|
|
67
|
+
let buf = this.buffers.get(groupKey);
|
|
68
|
+
if (!buf) {
|
|
69
|
+
buf = [];
|
|
70
|
+
this.buffers.set(groupKey, buf);
|
|
71
|
+
}
|
|
72
|
+
// De-dup by messageId.
|
|
73
|
+
if (buf.some((e) => e.messageId === entry.messageId)) {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
buf.push(entry);
|
|
77
|
+
if (buf.length > limit) {
|
|
78
|
+
buf.splice(0, buf.length - limit);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
list(groupKey: string, limit: number): HistoryEntry[] {
|
|
83
|
+
const buf = this.buffers.get(groupKey);
|
|
84
|
+
if (!buf) return [];
|
|
85
|
+
return buf.slice(-limit);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
clear(groupKey: string): void {
|
|
89
|
+
this.buffers.delete(groupKey);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Diagnostic: number of groups with buffered history. */
|
|
93
|
+
size(): number {
|
|
94
|
+
return this.buffers.size;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ============ Middleware ============
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Build a history-buffer middleware.
|
|
102
|
+
*
|
|
103
|
+
* The middleware:
|
|
104
|
+
* 1. Records the current group message into the store (before downstream).
|
|
105
|
+
* 2. Exposes `ctx.state.history: HistoryEntry[]` to downstream middleware
|
|
106
|
+
* and to the final `bot.on("message")` listener (oldest → newest,
|
|
107
|
+
* excluding the current message).
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* const history = historyBuffer({ limit: 5 });
|
|
112
|
+
* bot.use(mentionGate({ passthrough: true })); // record even on no-mention
|
|
113
|
+
* bot.use(history);
|
|
114
|
+
*
|
|
115
|
+
* bot.on("message", async (msg) => {
|
|
116
|
+
* const buf = msg.history ?? [];
|
|
117
|
+
* const prompt = buf.map(h => `${h.senderName}: ${h.content}`).join("\n");
|
|
118
|
+
* // ...
|
|
119
|
+
* });
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export function historyBuffer(options: HistoryBufferOptions = {}): Middleware {
|
|
123
|
+
const limit = options.limit ?? 50;
|
|
124
|
+
const store = options.store ?? new MemoryHistoryStore();
|
|
125
|
+
const recordOnSkip = options.recordOnSkip ?? true;
|
|
126
|
+
const getKey =
|
|
127
|
+
options.groupKey ??
|
|
128
|
+
((ctx) => (ctx.message.kind === "group" ? ctx.message.groupOpenid : undefined));
|
|
129
|
+
|
|
130
|
+
const m: Middleware = async (ctx, next) => {
|
|
131
|
+
const key = getKey(ctx);
|
|
132
|
+
if (!key) {
|
|
133
|
+
await next();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Effective limit — priority: static option > ctx.state.policy > default 50
|
|
138
|
+
const effectiveLimit = resolvePolicy(ctx, "group.historyLimit", limit, 50);
|
|
139
|
+
|
|
140
|
+
// 1. List buffered (excluding current message)
|
|
141
|
+
const buffered = await store.list(key, effectiveLimit);
|
|
142
|
+
ctx.state.history = buffered;
|
|
143
|
+
|
|
144
|
+
// 2. Record the current message (after exposing previous buffer)
|
|
145
|
+
const entry: HistoryEntry = {
|
|
146
|
+
senderId: ctx.message.senderId,
|
|
147
|
+
senderName: ctx.message.senderName,
|
|
148
|
+
content: ctx.message.content,
|
|
149
|
+
timestamp: Date.parse(ctx.message.timestamp) || Date.now(),
|
|
150
|
+
messageId: ctx.message.messageId,
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
await store.append(key, entry, effectiveLimit);
|
|
155
|
+
} catch (err) {
|
|
156
|
+
ctx.log.error?.(
|
|
157
|
+
`[history-buffer] append failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
if (ctx.stopped && !recordOnSkip) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
await next();
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
return m;
|
|
169
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware module barrel.
|
|
3
|
+
*
|
|
4
|
+
* Provides a Koa-style middleware chain plus a curated set of built-in
|
|
5
|
+
* middleware that cover the most common QQ Bot needs:
|
|
6
|
+
*
|
|
7
|
+
* **Core pipeline (dataflow stages):**
|
|
8
|
+
* - {@link selfEchoFilter} — drop bot's own echo messages
|
|
9
|
+
* - {@link deduplication} — drop duplicate messages (QQ retry overlap)
|
|
10
|
+
* - {@link contentSanitizer} — strip @markers, face tags, whitespace
|
|
11
|
+
* - {@link accessPolicy} — gate by allow / deny lists
|
|
12
|
+
* - {@link mentionGate} — only respond to @mentions in groups
|
|
13
|
+
* - {@link refIndexRecorder} — record messages for quote resolution
|
|
14
|
+
* - {@link quoteResolver} — resolve quoted/referenced messages
|
|
15
|
+
* - {@link slashCommand} — `/cmd` style command dispatch
|
|
16
|
+
* - {@link historyBuffer} — buffer recent group messages
|
|
17
|
+
* - {@link envelopeFormatter} — assemble LLM prompt context
|
|
18
|
+
* - {@link typingIndicator} — auto-show typing for C2C
|
|
19
|
+
* - {@link errorHandler} — catch errors and reply
|
|
20
|
+
*
|
|
21
|
+
* **Policy / protection:**
|
|
22
|
+
* - {@link rateLimiter} — multi-tier sliding-window rate limiting
|
|
23
|
+
*
|
|
24
|
+
* Compose them or replace them — `bot.use(...)` accepts any
|
|
25
|
+
* {@link Middleware} function.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
// Core types
|
|
29
|
+
export type { Middleware, MiddlewareContext } from "./types.js";
|
|
30
|
+
export { runMiddlewareChain, createMiddlewareContext, resolvePolicy } from "./types.js";
|
|
31
|
+
|
|
32
|
+
// ── P0: Filters & protection ──
|
|
33
|
+
|
|
34
|
+
export { messageFilter } from "./message-filter.js";
|
|
35
|
+
export type { MessageFilterOptions } from "./message-filter.js";
|
|
36
|
+
|
|
37
|
+
export { contentSanitizer } from "./content-sanitizer.js";
|
|
38
|
+
export type { ContentSanitizerOptions } from "./content-sanitizer.js";
|
|
39
|
+
|
|
40
|
+
export { rateLimiter } from "./rate-limiter.js";
|
|
41
|
+
export type { RateLimiterOptions, RateLimitTier } from "./rate-limiter.js";
|
|
42
|
+
|
|
43
|
+
export { concurrencyGuard } from "./concurrency-guard.js";
|
|
44
|
+
export type { ConcurrencyGuardOptions, ConcurrencyStrategy } from "./concurrency-guard.js";
|
|
45
|
+
|
|
46
|
+
// ── Access & gating ──
|
|
47
|
+
|
|
48
|
+
export { accessPolicy } from "./access-policy.js";
|
|
49
|
+
export type {
|
|
50
|
+
AccessMatcher,
|
|
51
|
+
AccessPolicy,
|
|
52
|
+
ScopePolicy,
|
|
53
|
+
} from "./access-policy.js";
|
|
54
|
+
|
|
55
|
+
export { mentionGate } from "./mention-gate.js";
|
|
56
|
+
export type { MentionDecision, MentionGateOptions } from "./mention-gate.js";
|
|
57
|
+
|
|
58
|
+
// ── Protocol (dataflow stages) ──
|
|
59
|
+
|
|
60
|
+
// ── Quote & ref-index (combined) ──
|
|
61
|
+
|
|
62
|
+
export { quoteRef, MemoryRefIndexStore } from "./quote-ref.js";
|
|
63
|
+
export type {
|
|
64
|
+
QuoteRefOptions,
|
|
65
|
+
RefEntry,
|
|
66
|
+
RefIndexStore,
|
|
67
|
+
ResolvedQuote,
|
|
68
|
+
QuotedAttachment,
|
|
69
|
+
} from "./quote-ref.js";
|
|
70
|
+
|
|
71
|
+
export { envelopeFormatter } from "./envelope-formatter.js";
|
|
72
|
+
export type { EnvelopeFormatterOptions } from "./envelope-formatter.js";
|
|
73
|
+
|
|
74
|
+
// ── Commands ──
|
|
75
|
+
|
|
76
|
+
export { slashCommand } from "./slash-command.js";
|
|
77
|
+
export type {
|
|
78
|
+
ParsedCommand,
|
|
79
|
+
SlashCommand,
|
|
80
|
+
SlashCommandHandlerContext,
|
|
81
|
+
SlashCommandOptions,
|
|
82
|
+
SlashCommandResult,
|
|
83
|
+
} from "./slash-command.js";
|
|
84
|
+
|
|
85
|
+
// ── History ──
|
|
86
|
+
|
|
87
|
+
export {
|
|
88
|
+
historyBuffer,
|
|
89
|
+
MemoryHistoryStore,
|
|
90
|
+
} from "./history-buffer.js";
|
|
91
|
+
export type {
|
|
92
|
+
HistoryBufferOptions,
|
|
93
|
+
HistoryEntry,
|
|
94
|
+
HistoryStore,
|
|
95
|
+
} from "./history-buffer.js";
|
|
96
|
+
|
|
97
|
+
// ── UX ──
|
|
98
|
+
|
|
99
|
+
export { typingIndicator } from "./typing-indicator.js";
|
|
100
|
+
export type { TypingIndicatorOptions } from "./typing-indicator.js";
|
|
101
|
+
|
|
102
|
+
// ── Error handling ──
|
|
103
|
+
|
|
104
|
+
export { errorHandler } from "./error-handler.js";
|
|
105
|
+
export type { ErrorHandlerOptions } from "./error-handler.js";
|
|
106
|
+
|
|
107
|
+
// ============ State augmentation ============
|
|
108
|
+
// Declared here so IDE autocomplete surfaces the well-known keys filled
|
|
109
|
+
// by built-in middleware.
|
|
110
|
+
|
|
111
|
+
import type { MentionDecision } from "./mention-gate.js";
|
|
112
|
+
import type { ParsedCommand } from "./slash-command.js";
|
|
113
|
+
import type { HistoryEntry } from "./history-buffer.js";
|
|
114
|
+
import type { ResolvedQuote } from "./quote-ref.js";
|
|
115
|
+
|
|
116
|
+
declare module "./types.js" {
|
|
117
|
+
interface MiddlewareState {
|
|
118
|
+
/** Set by {@link mentionGate} middleware. */
|
|
119
|
+
mention?: MentionDecision;
|
|
120
|
+
/** Set by {@link slashCommand} middleware when a command matches. */
|
|
121
|
+
command?: ParsedCommand;
|
|
122
|
+
/** Set by {@link historyBuffer} middleware. */
|
|
123
|
+
history?: HistoryEntry[];
|
|
124
|
+
/** Set by {@link quoteResolver} middleware. */
|
|
125
|
+
quote?: ResolvedQuote;
|
|
126
|
+
/** Set by {@link envelopeFormatter} middleware. Formatted LLM context string. */
|
|
127
|
+
envelope?: string;
|
|
128
|
+
}
|
|
129
|
+
}
|