@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,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Concurrency-guard middleware — per-target serial message processing.
|
|
3
|
+
*
|
|
4
|
+
* Ensures only one message is being processed at a time for each
|
|
5
|
+
* target (user or group). Prevents concurrent stream_messages calls
|
|
6
|
+
* to the same QQ user/group which causes platform 500 errors.
|
|
7
|
+
*
|
|
8
|
+
* Strategy:
|
|
9
|
+
* - "queue": New messages wait until the current one finishes.
|
|
10
|
+
* - "drop": New messages are silently dropped while busy.
|
|
11
|
+
* - "abort": Cancel the current processing, start the new one.
|
|
12
|
+
* - "merge": Buffer new messages while the active one is being
|
|
13
|
+
* processed. When the active message finishes, all
|
|
14
|
+
* buffered messages are merged via `onMerge` into one
|
|
15
|
+
* survivor ctx. The survivor proceeds through the rest
|
|
16
|
+
* of the chain via its own `next()`. Non-survivors
|
|
17
|
+
* return silently (chain stops).
|
|
18
|
+
*
|
|
19
|
+
* The concurrency key is `${scope}:${targetId}` (e.g. "c2c:OPENID"
|
|
20
|
+
* or "group:GROUPID").
|
|
21
|
+
*
|
|
22
|
+
* Implementation note on "merge" — the "queue + batch" model:
|
|
23
|
+
*
|
|
24
|
+
* The active message (A) runs through the full chain normally via
|
|
25
|
+
* `next()`. Incoming messages (B, C, D) pause on a promise without
|
|
26
|
+
* calling `ctx.stop()` — they do not advance the chain. When A
|
|
27
|
+
* finishes, all buffered ctxs are merged. One survivor is chosen;
|
|
28
|
+
* its waiter is marked and proceeds to call `next()`. All other
|
|
29
|
+
* waiters return silently.
|
|
30
|
+
*
|
|
31
|
+
* This guarantees:
|
|
32
|
+
* 1. A runs immediately with zero delay and its content stays
|
|
33
|
+
* untouched.
|
|
34
|
+
* 2. Buffered messages are merged and processed exactly once per
|
|
35
|
+
* batch via the survivor's own `next()`.
|
|
36
|
+
* 3. Non-survivors' chains stop naturally (no upstream `next()`
|
|
37
|
+
* call), no `ctx.stop()` needed.
|
|
38
|
+
* 4. No suspended-promise complexity, no framework coupling.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* bot.use(concurrencyGuard({ strategy: "queue", maxQueue: 3 }));
|
|
43
|
+
* bot.use(concurrencyGuard({
|
|
44
|
+
* strategy: "merge",
|
|
45
|
+
* maxQueue: 50,
|
|
46
|
+
* onMerge: (buffered) => mergeContexts(buffered),
|
|
47
|
+
* onDispatch: (merged) => bot.sendText(...), // legacy
|
|
48
|
+
* }));
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export function concurrencyGuard(options = {}) {
|
|
52
|
+
const strategy = options.strategy ?? "queue";
|
|
53
|
+
const maxQueue = options.maxQueue ?? 3;
|
|
54
|
+
const { onDrop, onMerge, onDispatch, urgentPredicate, maxProcessingMs } = options;
|
|
55
|
+
const locks = new Map();
|
|
56
|
+
function getState(key) {
|
|
57
|
+
let s = locks.get(key);
|
|
58
|
+
if (!s) {
|
|
59
|
+
s = { busy: false, queue: [] };
|
|
60
|
+
locks.set(key, s);
|
|
61
|
+
}
|
|
62
|
+
return s;
|
|
63
|
+
}
|
|
64
|
+
function cleanupState(key) {
|
|
65
|
+
const s = locks.get(key);
|
|
66
|
+
if (s &&
|
|
67
|
+
!s.busy &&
|
|
68
|
+
s.queue.length === 0 &&
|
|
69
|
+
(!s.mergeBuffer || s.mergeBuffer.length === 0)) {
|
|
70
|
+
locks.delete(key);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function targetKey(ctx) {
|
|
74
|
+
const t = ctx.message.replyTarget;
|
|
75
|
+
return `${t.scope}:${t.targetId}`;
|
|
76
|
+
}
|
|
77
|
+
const guard = async (ctx, next) => {
|
|
78
|
+
const key = targetKey(ctx);
|
|
79
|
+
const state = getState(key);
|
|
80
|
+
if (!state.busy) {
|
|
81
|
+
// No active processing — proceed immediately.
|
|
82
|
+
state.busy = true;
|
|
83
|
+
state.activeCtx = ctx;
|
|
84
|
+
if (strategy === "merge") {
|
|
85
|
+
state.mergeBuffer = [];
|
|
86
|
+
state.mergeWaiters = [];
|
|
87
|
+
}
|
|
88
|
+
// Timeout watchdog: abort the active chain after maxProcessingMs.
|
|
89
|
+
// ctx.abort() propagates AbortSignal through the remaining middleware
|
|
90
|
+
// chain and downstream agent pipeline, canceling in-flight LLM calls,
|
|
91
|
+
// tool executions, and streaming.
|
|
92
|
+
let timedOut = false;
|
|
93
|
+
let timeoutId;
|
|
94
|
+
if (maxProcessingMs && maxProcessingMs > 0) {
|
|
95
|
+
timeoutId = setTimeout(() => {
|
|
96
|
+
timedOut = true;
|
|
97
|
+
ctx.log.warn?.(`[concurrency] aborting active chain ${key} after ${maxProcessingMs}ms`);
|
|
98
|
+
ctx.abort('concurrency:processing-timeout');
|
|
99
|
+
// Release lock BEFORE draining — the next message in queue will
|
|
100
|
+
// set busy=true, which would be overwritten if we did it after.
|
|
101
|
+
state.busy = false;
|
|
102
|
+
state.activeCtx = undefined;
|
|
103
|
+
if (strategy === 'merge') {
|
|
104
|
+
drainMergeBuffer(key, state, ctx).catch(() => { });
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
drainQueue(key);
|
|
108
|
+
}
|
|
109
|
+
cleanupState(key);
|
|
110
|
+
}, maxProcessingMs);
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
await next();
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
if (timeoutId)
|
|
117
|
+
clearTimeout(timeoutId);
|
|
118
|
+
if (!timedOut) {
|
|
119
|
+
// timeout not triggered, release lock normally
|
|
120
|
+
state.activeCtx = undefined;
|
|
121
|
+
if (strategy === "merge") {
|
|
122
|
+
await drainMergeBuffer(key, state, ctx);
|
|
123
|
+
state.busy = false;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
state.busy = false;
|
|
127
|
+
if (strategy === "queue" || strategy === "abort") {
|
|
128
|
+
drainQueue(key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
cleanupState(key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
// Target is busy — apply strategy
|
|
137
|
+
switch (strategy) {
|
|
138
|
+
case "merge": {
|
|
139
|
+
if (!state.mergeBuffer || !state.mergeWaiters) {
|
|
140
|
+
state.mergeBuffer = [];
|
|
141
|
+
state.mergeWaiters = [];
|
|
142
|
+
}
|
|
143
|
+
// Urgent message: flush buffered waiters, continue remaining chain
|
|
144
|
+
// immediately via next() in parallel to active owner.
|
|
145
|
+
if (urgentPredicate?.(ctx)) {
|
|
146
|
+
ctx.log.debug?.(`[concurrency:merge] urgent for ${key}`);
|
|
147
|
+
for (const w of state.mergeWaiters)
|
|
148
|
+
w.resolve();
|
|
149
|
+
state.mergeBuffer.length = 0;
|
|
150
|
+
state.mergeWaiters.length = 0;
|
|
151
|
+
await next();
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (state.mergeBuffer.length >= maxQueue) {
|
|
155
|
+
ctx.log.debug?.(`[concurrency:merge] buffer full (${maxQueue}), drop for ${key}`);
|
|
156
|
+
await onDrop?.(ctx);
|
|
157
|
+
ctx.stop("concurrency:merge-full");
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
ctx.log.debug?.(`[concurrency:merge] buffered: ${key} (msgId=${ctx.message.messageId} ` +
|
|
161
|
+
`pos=${state.mergeBuffer.length + 1})`);
|
|
162
|
+
// Buffer the ctx and pause — do NOT stop the chain.
|
|
163
|
+
state.mergeBuffer.push(ctx);
|
|
164
|
+
// Wait until the batch is processed. If we are the survivor,
|
|
165
|
+
// proceed to next(); otherwise return silently.
|
|
166
|
+
let isSurvivor = false;
|
|
167
|
+
await new Promise((resolve) => {
|
|
168
|
+
state.mergeWaiters.push({
|
|
169
|
+
ctx,
|
|
170
|
+
resolve,
|
|
171
|
+
markSurvivor: () => {
|
|
172
|
+
isSurvivor = true;
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
if (isSurvivor) {
|
|
177
|
+
await next();
|
|
178
|
+
}
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
case "drop": {
|
|
182
|
+
ctx.log.debug?.(`[concurrency] drop message for busy target ${key}`);
|
|
183
|
+
await onDrop?.(ctx);
|
|
184
|
+
ctx.stop("concurrency:drop");
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
case "abort": {
|
|
188
|
+
ctx.log.debug?.(`[concurrency] abort previous for ${key}`);
|
|
189
|
+
state.activeCtx?.abort("concurrency:abort");
|
|
190
|
+
for (const entry of state.queue) {
|
|
191
|
+
entry.ctx?.abort("concurrency:superseded");
|
|
192
|
+
entry.run();
|
|
193
|
+
}
|
|
194
|
+
state.queue.length = 0;
|
|
195
|
+
await waitForRelease(state, ctx);
|
|
196
|
+
if (ctx.signal.aborted) {
|
|
197
|
+
ctx.log.debug?.(`[concurrency] superseded while waiting for ${key}`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
state.busy = true;
|
|
201
|
+
state.activeCtx = ctx;
|
|
202
|
+
try {
|
|
203
|
+
await next();
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
state.busy = false;
|
|
207
|
+
state.activeCtx = undefined;
|
|
208
|
+
drainQueue(key);
|
|
209
|
+
}
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
case "queue":
|
|
213
|
+
default: {
|
|
214
|
+
if (state.queue.length >= maxQueue) {
|
|
215
|
+
ctx.log.debug?.(`[concurrency] queue full (${maxQueue}), drop for ${key}`);
|
|
216
|
+
await onDrop?.(ctx);
|
|
217
|
+
ctx.stop("concurrency:queue-full");
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
ctx.log.debug?.(`[concurrency] queued message for ${key} (pos=${state.queue.length + 1})`);
|
|
221
|
+
await new Promise((resolve) => {
|
|
222
|
+
state.queue.push({ run: resolve });
|
|
223
|
+
});
|
|
224
|
+
state.busy = true;
|
|
225
|
+
state.activeCtx = ctx;
|
|
226
|
+
try {
|
|
227
|
+
await next();
|
|
228
|
+
}
|
|
229
|
+
finally {
|
|
230
|
+
state.busy = false;
|
|
231
|
+
state.activeCtx = undefined;
|
|
232
|
+
drainQueue(key);
|
|
233
|
+
}
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* Drain the merge buffer: merge buffered ctxs into one survivor,
|
|
240
|
+
* mark it, and resolve all waiters. The survivor then proceeds
|
|
241
|
+
* through its own `next()`. If `onDispatch` is set (legacy),
|
|
242
|
+
* dispatch via callback instead.
|
|
243
|
+
*/
|
|
244
|
+
async function drainMergeBuffer(key, state, ownerCtx) {
|
|
245
|
+
while (state.mergeBuffer && state.mergeBuffer.length > 0) {
|
|
246
|
+
const buffered = state.mergeBuffer.splice(0);
|
|
247
|
+
const waiters = state.mergeWaiters?.splice(0) ?? [];
|
|
248
|
+
// Merge the buffered ctxs.
|
|
249
|
+
const survivor = onMerge ? onMerge(buffered) : defaultMerge(buffered);
|
|
250
|
+
const validSurvivor = buffered.includes(survivor) ? survivor : buffered[0];
|
|
251
|
+
ownerCtx.log.debug?.(`[concurrency:merge] flushing batch: ${key} (count=${buffered.length})`);
|
|
252
|
+
// Dispatch: onDispatch (legacy) or survivor self-proceeds via next().
|
|
253
|
+
if (onDispatch) {
|
|
254
|
+
state.activeCtx = validSurvivor;
|
|
255
|
+
try {
|
|
256
|
+
await onDispatch(validSurvivor);
|
|
257
|
+
}
|
|
258
|
+
catch (err) {
|
|
259
|
+
validSurvivor.log.error?.(`[concurrency:merge] onDispatch error: ${err instanceof Error ? err.message : String(err)}`);
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
state.activeCtx = undefined;
|
|
263
|
+
}
|
|
264
|
+
// All waiters resolve — none are survivors.
|
|
265
|
+
for (const w of waiters)
|
|
266
|
+
w.resolve();
|
|
267
|
+
}
|
|
268
|
+
else {
|
|
269
|
+
// Mark the survivor's waiter; resolve all.
|
|
270
|
+
for (const w of waiters) {
|
|
271
|
+
if (w.ctx === validSurvivor)
|
|
272
|
+
w.markSurvivor();
|
|
273
|
+
w.resolve();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
state.mergeBuffer = undefined;
|
|
278
|
+
state.mergeWaiters = undefined;
|
|
279
|
+
}
|
|
280
|
+
function drainQueue(key) {
|
|
281
|
+
const state = locks.get(key);
|
|
282
|
+
if (!state)
|
|
283
|
+
return;
|
|
284
|
+
const entry = state.queue.shift();
|
|
285
|
+
if (entry) {
|
|
286
|
+
entry.run();
|
|
287
|
+
}
|
|
288
|
+
else if (!state.busy) {
|
|
289
|
+
locks.delete(key);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function waitForRelease(state, ctx) {
|
|
293
|
+
if (!state.busy)
|
|
294
|
+
return Promise.resolve();
|
|
295
|
+
return new Promise((resolve) => {
|
|
296
|
+
state.queue.unshift({ run: resolve, ctx });
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Default merge: concatenate contents with newline, keep first ctx as survivor.
|
|
301
|
+
*/
|
|
302
|
+
function defaultMerge(buffered) {
|
|
303
|
+
const first = buffered[0];
|
|
304
|
+
if (buffered.length === 1)
|
|
305
|
+
return first;
|
|
306
|
+
const contentBearingCtxs = buffered.filter((ctx) => (ctx.message.content ?? "") !== "");
|
|
307
|
+
const contents = contentBearingCtxs.map((ctx) => ctx.message.content);
|
|
308
|
+
if (contents.length > 0) {
|
|
309
|
+
first.message.content = contents.join("\n");
|
|
310
|
+
}
|
|
311
|
+
const envelopes = contentBearingCtxs
|
|
312
|
+
.map((ctx) => ctx.state.envelope)
|
|
313
|
+
.filter(Boolean);
|
|
314
|
+
if (envelopes.length > 0) {
|
|
315
|
+
first.state.envelope = envelopes.join("\n\n");
|
|
316
|
+
}
|
|
317
|
+
const allAttachments = contentBearingCtxs.flatMap((ctx) => ctx.message.attachments ?? []);
|
|
318
|
+
if (allAttachments.length > 0) {
|
|
319
|
+
first.message.attachments = allAttachments;
|
|
320
|
+
}
|
|
321
|
+
return first;
|
|
322
|
+
}
|
|
323
|
+
return guard;
|
|
324
|
+
}
|
|
325
|
+
//# sourceMappingURL=concurrency-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"concurrency-guard.js","sourceRoot":"","sources":["../../src/middleware/concurrency-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AA+EH,MAAM,UAAU,gBAAgB,CAAC,UAAmC,EAAE;IACpE,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,OAAO,CAAC;IAC7C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC;IACvC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,eAAe,EAAE,GAAG,OAAO,CAAC;IAElF,MAAM,KAAK,GAAG,IAAI,GAAG,EAAuB,CAAC;IAE7C,SAAS,QAAQ,CAAC,GAAW;QAC3B,IAAI,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,CAAC,CAAC,EAAE,CAAC;YACP,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE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C;YAC9B,KAAK,CAAC,OAAO,CAAC,WAAW,GAAG,cAAc,CAAC;QAC7C,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content-sanitizer middleware — clean up raw message text.
|
|
3
|
+
*
|
|
4
|
+
* QQ delivers messages with `<@!{appId}>` mention markers, extra whitespace,
|
|
5
|
+
* and sometimes face-tag markup. This middleware strips those artifacts so
|
|
6
|
+
* downstream middleware (and the user's `onMessage` handler) receives clean
|
|
7
|
+
* human-readable text.
|
|
8
|
+
*
|
|
9
|
+
* Operates on `ctx.message.content` in-place — downstream sees the
|
|
10
|
+
* sanitized version.
|
|
11
|
+
*/
|
|
12
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
13
|
+
export interface ContentSanitizerOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Whether to strip `<@!{appId}>` / `<@{appId}>` mention markers.
|
|
16
|
+
* Defaults to `true`.
|
|
17
|
+
*/
|
|
18
|
+
stripBotMention?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Whether to strip all `<@!{id}>` markers (not just the bot's).
|
|
21
|
+
* Defaults to `false`.
|
|
22
|
+
*/
|
|
23
|
+
stripAllMentions?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Whether to collapse multiple consecutive whitespace / newlines into
|
|
26
|
+
* a single space. Defaults to `false`.
|
|
27
|
+
*/
|
|
28
|
+
collapseWhitespace?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Whether to parse QQ face tags `[<face,id=xx/>]` into emoji text.
|
|
31
|
+
* Defaults to `false` (just strip them).
|
|
32
|
+
*/
|
|
33
|
+
parseFaceTags?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Custom transform applied after all built-in sanitization.
|
|
36
|
+
*/
|
|
37
|
+
transform?: (content: string, ctx: MiddlewareContext) => string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* bot.use(contentSanitizer()); // Default: strip bot mention + trim
|
|
43
|
+
* bot.use(contentSanitizer({ stripAllMentions: true, collapseWhitespace: true }));
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function contentSanitizer(options?: ContentSanitizerOptions): Middleware;
|
|
47
|
+
//# sourceMappingURL=content-sanitizer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"content-sanitizer.d.ts","sourceRoot":"","sources":["../../src/middleware/content-sanitizer.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,WAAW,uBAAuB;IACtC;;;OAGG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,iBAAiB,KAAK,MAAM,CAAC;CACjE;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,uBAA4B,GAAG,UAAU,CA2DlF"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content-sanitizer middleware — clean up raw message text.
|
|
3
|
+
*
|
|
4
|
+
* QQ delivers messages with `<@!{appId}>` mention markers, extra whitespace,
|
|
5
|
+
* and sometimes face-tag markup. This middleware strips those artifacts so
|
|
6
|
+
* downstream middleware (and the user's `onMessage` handler) receives clean
|
|
7
|
+
* human-readable text.
|
|
8
|
+
*
|
|
9
|
+
* Operates on `ctx.message.content` in-place — downstream sees the
|
|
10
|
+
* sanitized version.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* bot.use(contentSanitizer()); // Default: strip bot mention + trim
|
|
16
|
+
* bot.use(contentSanitizer({ stripAllMentions: true, collapseWhitespace: true }));
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export function contentSanitizer(options = {}) {
|
|
20
|
+
const { stripBotMention = true, stripAllMentions = false, collapseWhitespace = false, parseFaceTags = false, transform, } = options;
|
|
21
|
+
return async (ctx, next) => {
|
|
22
|
+
let content = ctx.message.content ?? "";
|
|
23
|
+
// Strip mention markers
|
|
24
|
+
if (stripAllMentions) {
|
|
25
|
+
content = content.replace(/<@!?\d+>\s*/g, "");
|
|
26
|
+
}
|
|
27
|
+
else if (stripBotMention) {
|
|
28
|
+
const appId = ctx.bot.appId;
|
|
29
|
+
if (appId) {
|
|
30
|
+
const re = new RegExp(`<@!?${appId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}>\\s*`, "g");
|
|
31
|
+
content = re[Symbol.replace](content, "");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Face tags: old format [<face,id=xx/>] + new format <faceType=xx,faceId="xx",ext="base64">
|
|
35
|
+
if (parseFaceTags) {
|
|
36
|
+
// Old format: map face ids to emoji
|
|
37
|
+
content = content.replace(/\[<face,id=(\d+)\/?>]/g, (_m, id) => faceToEmoji(id) ?? "");
|
|
38
|
+
// New format: decode base64 ext to get face name
|
|
39
|
+
content = content.replace(/<faceType=\d+,faceId="[^"]*",ext="([^"]*)">/g, (_m, ext) => {
|
|
40
|
+
try {
|
|
41
|
+
const decoded = Buffer.from(ext, 'base64').toString('utf-8');
|
|
42
|
+
const parsed = JSON.parse(decoded);
|
|
43
|
+
return `【表情: ${parsed.text || '未知表情'}】`;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return _m;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
// Strip both formats
|
|
52
|
+
content = content.replace(/\[<face,id=\d+\/?>]/g, "");
|
|
53
|
+
content = content.replace(/<faceType=\d+,faceId="[^"]*",ext="[^"]*">/g, "");
|
|
54
|
+
}
|
|
55
|
+
// Collapse whitespace
|
|
56
|
+
if (collapseWhitespace) {
|
|
57
|
+
content = content.replace(/\s+/g, " ");
|
|
58
|
+
}
|
|
59
|
+
// Trim
|
|
60
|
+
content = content.trim();
|
|
61
|
+
// Custom transform
|
|
62
|
+
if (transform) {
|
|
63
|
+
content = transform(content, ctx);
|
|
64
|
+
}
|
|
65
|
+
ctx.message.content = content;
|
|
66
|
+
await next();
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** Simplified face-id → emoji mapping (QQ common faces). */
|
|
70
|
+
function faceToEmoji(id) {
|
|
71
|
+
const map = {
|
|
72
|
+
"0": "😊", "1": "😣", "2": "😍", "4": "😎", "5": "😭",
|
|
73
|
+
"6": "😳", "7": "🤐", "8": "😴", "9": "😢", "10": "😰",
|
|
74
|
+
"11": "😡", "12": "🤗", "13": "⭐", "14": "🌟", "15": "🌙",
|
|
75
|
+
"16": "👍", "18": "✊", "21": "😊", "23": "😢", "25": "🤔",
|
|
76
|
+
"26": "😱", "27": "😅", "28": "😁", "29": "🤮", "30": "💪",
|
|
77
|
+
"32": "🎉", "33": "😤", "34": "😏", "35": "🥺", "49": "🐷",
|
|
78
|
+
"53": "🎂", "60": "☕", "63": "🌹", "66": "❤️", "74": "🌞",
|
|
79
|
+
"75": "🌛", "76": "👏", "78": "🤝", "79": "✌️", "85": "🎅",
|
|
80
|
+
"89": "🍉", "96": "😓", "97": "😲", "100": "😂", "101": "😊",
|
|
81
|
+
"104": "😭", "106": "😱", "109": "😘", "111": "🥰",
|
|
82
|
+
};
|
|
83
|
+
return map[id];
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=content-sanitizer.js.map
|
|
@@ -0,0 +1 @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ention
|
|
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
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
14
|
+
export interface EnvelopeFormatterOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Maximum number of history entries to include.
|
|
17
|
+
* Defaults to `5`.
|
|
18
|
+
*/
|
|
19
|
+
historyLimit?: number;
|
|
20
|
+
/**
|
|
21
|
+
* Whether to include the resolved quote in the envelope.
|
|
22
|
+
* Defaults to `true`.
|
|
23
|
+
*/
|
|
24
|
+
includeQuote?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Whether to include sender name / id as context.
|
|
27
|
+
* Defaults to `true`.
|
|
28
|
+
*/
|
|
29
|
+
includeSender?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Custom formatter override. If provided, replaces the default logic
|
|
32
|
+
* entirely. Receives the same ctx and should return the formatted string.
|
|
33
|
+
*/
|
|
34
|
+
format?: (ctx: MiddlewareContext) => string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* @example
|
|
38
|
+
* ```ts
|
|
39
|
+
* bot.use(historyBuffer({ limit: 10 }));
|
|
40
|
+
* bot.use(quoteResolver({ store: refStore }));
|
|
41
|
+
* bot.use(envelopeFormatter({ historyLimit: 5 }));
|
|
42
|
+
*
|
|
43
|
+
* bot.on("message", async (msg) => {
|
|
44
|
+
* const envelope = msg._ctx?.state.envelope as string;
|
|
45
|
+
* const response = await llm.chat(envelope + "\n" + msg.content);
|
|
46
|
+
* await bot.sendText(msg.replyTarget, response);
|
|
47
|
+
* });
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function envelopeFormatter(options?: EnvelopeFormatterOptions): Middleware;
|
|
51
|
+
//# sourceMappingURL=envelope-formatter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"envelope-formatter.d.ts","sourceRoot":"","sources":["../../src/middleware/envelope-formatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAIhE,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,MAAM,CAAC;CAC7C;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,wBAA6B,GAAG,UAAU,CAsBpF"}
|
|
@@ -0,0 +1,97 @@
|
|
|
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
|
+
* @example
|
|
15
|
+
* ```ts
|
|
16
|
+
* bot.use(historyBuffer({ limit: 10 }));
|
|
17
|
+
* bot.use(quoteResolver({ store: refStore }));
|
|
18
|
+
* bot.use(envelopeFormatter({ historyLimit: 5 }));
|
|
19
|
+
*
|
|
20
|
+
* bot.on("message", async (msg) => {
|
|
21
|
+
* const envelope = msg._ctx?.state.envelope as string;
|
|
22
|
+
* const response = await llm.chat(envelope + "\n" + msg.content);
|
|
23
|
+
* await bot.sendText(msg.replyTarget, response);
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export function envelopeFormatter(options = {}) {
|
|
28
|
+
const { historyLimit = 5, includeQuote = true, includeSender = true, format, } = options;
|
|
29
|
+
return async (ctx, next) => {
|
|
30
|
+
if (format) {
|
|
31
|
+
ctx.state.envelope = format(ctx);
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
ctx.state.envelope = buildEnvelope(ctx, { historyLimit, includeQuote, includeSender });
|
|
35
|
+
}
|
|
36
|
+
ctx.log.debug?.(`[envelope] built ${ctx.state.envelope.length} chars` +
|
|
37
|
+
` (sender=${includeSender}, quote=${includeQuote}, history=${ctx.state.history?.length ?? 0}/${historyLimit})`);
|
|
38
|
+
await next();
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function buildEnvelope(ctx, opts) {
|
|
42
|
+
const sections = [];
|
|
43
|
+
// ── Context meta ──
|
|
44
|
+
if (opts.includeSender) {
|
|
45
|
+
const name = ctx.message.senderName || ctx.message.senderId;
|
|
46
|
+
const scope = ctx.message.kind === "group"
|
|
47
|
+
? `group(${ctx.message.groupOpenid ?? "unknown"})`
|
|
48
|
+
: ctx.message.kind;
|
|
49
|
+
sections.push(`<from>\nuser: ${name}\nscope: ${scope}\n</from>`);
|
|
50
|
+
}
|
|
51
|
+
// ── Quoted message (reply-to) ──
|
|
52
|
+
if (opts.includeQuote) {
|
|
53
|
+
const quote = ctx.state.quote;
|
|
54
|
+
if (quote && quote.text) {
|
|
55
|
+
const sender = quote.entry?.senderName || quote.entry?.senderId;
|
|
56
|
+
const line = sender ? `${sender}: ${quote.text}` : quote.text;
|
|
57
|
+
sections.push(`<reply_to>\n${line}\n</reply_to>`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
// ── Conversation history ──
|
|
61
|
+
const history = ctx.state.history;
|
|
62
|
+
if (history && history.length > 0) {
|
|
63
|
+
const recent = history.slice(-opts.historyLimit);
|
|
64
|
+
const lines = recent.map((h) => {
|
|
65
|
+
const name = h.senderName || h.senderId;
|
|
66
|
+
return `${name}: ${h.content.slice(0, 200)}`;
|
|
67
|
+
});
|
|
68
|
+
sections.push(`<history>\n${lines.join("\n")}\n</history>`);
|
|
69
|
+
}
|
|
70
|
+
// ── Current message ──
|
|
71
|
+
const content = (ctx.message.content ?? "").trim();
|
|
72
|
+
const attachments = ctx.message.attachments;
|
|
73
|
+
const hasAttachments = attachments && attachments.length > 0;
|
|
74
|
+
if (content || hasAttachments) {
|
|
75
|
+
const parts = [];
|
|
76
|
+
if (content) {
|
|
77
|
+
parts.push(content);
|
|
78
|
+
}
|
|
79
|
+
if (hasAttachments) {
|
|
80
|
+
for (const att of attachments) {
|
|
81
|
+
const t = att.content_type.toLowerCase();
|
|
82
|
+
if (t.startsWith("image/"))
|
|
83
|
+
parts.push(`[image: ${att.filename ?? "image"}]`);
|
|
84
|
+
else if (t.startsWith("audio/") || t === "voice") {
|
|
85
|
+
parts.push(att.asr_refer_text ? `[voice: ${att.asr_refer_text}]` : "[voice]");
|
|
86
|
+
}
|
|
87
|
+
else if (t.startsWith("video/"))
|
|
88
|
+
parts.push("[video]");
|
|
89
|
+
else
|
|
90
|
+
parts.push(`[file: ${att.filename ?? "file"}]`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
sections.push(`<message>\n${parts.join("\n")}\n</message>`);
|
|
94
|
+
}
|
|
95
|
+
return sections.join("\n\n");
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=envelope-formatter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"envelope-formatter.js","sourceRoot":"","sources":["../../src/middleware/envelope-formatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;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