@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,450 @@
|
|
|
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
|
+
|
|
52
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
53
|
+
|
|
54
|
+
export type ConcurrencyStrategy = "queue" | "drop" | "abort" | "merge";
|
|
55
|
+
|
|
56
|
+
export interface ConcurrencyGuardOptions {
|
|
57
|
+
/**
|
|
58
|
+
* How to handle a new message when the target is busy.
|
|
59
|
+
* - "queue": Wait for the current message to finish (default).
|
|
60
|
+
* - "drop": Silently skip the new message.
|
|
61
|
+
* - "abort": Abort current processing via AbortController, then process new.
|
|
62
|
+
* - "merge": Buffer new messages while busy; when the active message
|
|
63
|
+
* finishes, merge & dispatch the batch.
|
|
64
|
+
*/
|
|
65
|
+
strategy?: ConcurrencyStrategy;
|
|
66
|
+
/**
|
|
67
|
+
* Maximum processing time (ms) for a single active message. When the
|
|
68
|
+
* active chain exceeds this duration, the guard **aborts** the chain
|
|
69
|
+
* via `ctx.abort()`, releases the lock, and drains any buffered
|
|
70
|
+
* messages.
|
|
71
|
+
*
|
|
72
|
+
* Aborting propagates the `AbortSignal` through the remaining middleware
|
|
73
|
+
* chain and downstream agent pipeline, canceling in-flight LLM calls,
|
|
74
|
+
* tool executions, and streaming.
|
|
75
|
+
*
|
|
76
|
+
* Set to `0` to disable the timeout (no limit). Default: `0` (disabled).
|
|
77
|
+
*/
|
|
78
|
+
maxProcessingMs?: number;
|
|
79
|
+
/** Max queued messages per target (for "queue") or max buffered messages (for "merge"). Default: 3. */
|
|
80
|
+
maxQueue?: number;
|
|
81
|
+
/** Called when a message is dropped (strategy=drop or queue/buffer overflow). */
|
|
82
|
+
onDrop?: (ctx: MiddlewareContext) => void | Promise<void>;
|
|
83
|
+
/**
|
|
84
|
+
* Merge function for "merge" strategy. Receives the array of buffered
|
|
85
|
+
* contexts in arrival order and must return one of them (the "survivor"),
|
|
86
|
+
* mutated in place to represent the merged result.
|
|
87
|
+
*
|
|
88
|
+
* If not provided, {@link defaultMerge} is used: the first context is
|
|
89
|
+
* kept and all message contents are concatenated with newline separators.
|
|
90
|
+
*/
|
|
91
|
+
onMerge?: (buffered: MiddlewareContext[]) => MiddlewareContext;
|
|
92
|
+
/**
|
|
93
|
+
* @deprecated Legacy merge-dispatch callback. When set, merged batches
|
|
94
|
+
* are dispatched via `onDispatch(mergedCtx)` instead of flowing through
|
|
95
|
+
* the survivor's own `next()`. Prefer the default chain-based mechanism.
|
|
96
|
+
*/
|
|
97
|
+
onDispatch?: (ctx: MiddlewareContext) => void | Promise<void>;
|
|
98
|
+
/**
|
|
99
|
+
* Predicate signaling an urgent message that should skip the queue.
|
|
100
|
+
* When true (e.g. `/stop`), all buffered/waiting messages for the
|
|
101
|
+
* same target are silently dropped and the ctx proceeds through the
|
|
102
|
+
* remaining middleware chain immediately (parallel to active owner).
|
|
103
|
+
* Only meaningful with "merge" strategy.
|
|
104
|
+
*/
|
|
105
|
+
urgentPredicate?: (ctx: MiddlewareContext) => boolean;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface QueueEntry {
|
|
109
|
+
run: () => void;
|
|
110
|
+
ctx?: MiddlewareContext;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** A buffered ctx waiting for the current batch to finish. */
|
|
114
|
+
interface MergeWaiter {
|
|
115
|
+
ctx: MiddlewareContext;
|
|
116
|
+
resolve: () => void;
|
|
117
|
+
/** Set when this waiter's ctx is chosen as the survivor. */
|
|
118
|
+
markSurvivor: () => void;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
interface TargetState {
|
|
122
|
+
busy: boolean;
|
|
123
|
+
queue: QueueEntry[];
|
|
124
|
+
activeCtx?: MiddlewareContext;
|
|
125
|
+
mergeBuffer?: MiddlewareContext[];
|
|
126
|
+
mergeWaiters?: MergeWaiter[];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function concurrencyGuard(options: ConcurrencyGuardOptions = {}): Middleware {
|
|
130
|
+
const strategy = options.strategy ?? "queue";
|
|
131
|
+
const maxQueue = options.maxQueue ?? 3;
|
|
132
|
+
const { onDrop, onMerge, onDispatch, urgentPredicate, maxProcessingMs } = options;
|
|
133
|
+
|
|
134
|
+
const locks = new Map<string, TargetState>();
|
|
135
|
+
|
|
136
|
+
function getState(key: string): TargetState {
|
|
137
|
+
let s = locks.get(key);
|
|
138
|
+
if (!s) {
|
|
139
|
+
s = { busy: false, queue: [] };
|
|
140
|
+
locks.set(key, s);
|
|
141
|
+
}
|
|
142
|
+
return s;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function cleanupState(key: string): void {
|
|
146
|
+
const s = locks.get(key);
|
|
147
|
+
if (
|
|
148
|
+
s &&
|
|
149
|
+
!s.busy &&
|
|
150
|
+
s.queue.length === 0 &&
|
|
151
|
+
(!s.mergeBuffer || s.mergeBuffer.length === 0)
|
|
152
|
+
) {
|
|
153
|
+
locks.delete(key);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function targetKey(ctx: MiddlewareContext): string {
|
|
158
|
+
const t = ctx.message.replyTarget;
|
|
159
|
+
return `${t.scope}:${t.targetId}`;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const guard: Middleware = async (ctx, next) => {
|
|
163
|
+
const key = targetKey(ctx);
|
|
164
|
+
const state = getState(key);
|
|
165
|
+
|
|
166
|
+
if (!state.busy) {
|
|
167
|
+
// No active processing — proceed immediately.
|
|
168
|
+
state.busy = true;
|
|
169
|
+
state.activeCtx = ctx;
|
|
170
|
+
|
|
171
|
+
if (strategy === "merge") {
|
|
172
|
+
state.mergeBuffer = [];
|
|
173
|
+
state.mergeWaiters = [];
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Timeout watchdog: abort the active chain after maxProcessingMs.
|
|
177
|
+
// ctx.abort() propagates AbortSignal through the remaining middleware
|
|
178
|
+
// chain and downstream agent pipeline, canceling in-flight LLM calls,
|
|
179
|
+
// tool executions, and streaming.
|
|
180
|
+
let timedOut = false;
|
|
181
|
+
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
182
|
+
if (maxProcessingMs && maxProcessingMs > 0) {
|
|
183
|
+
timeoutId = setTimeout(() => {
|
|
184
|
+
timedOut = true;
|
|
185
|
+
ctx.log.warn?.(
|
|
186
|
+
`[concurrency] aborting active chain ${key} after ${maxProcessingMs}ms`,
|
|
187
|
+
);
|
|
188
|
+
ctx.abort('concurrency:processing-timeout');
|
|
189
|
+
// Release lock BEFORE draining — the next message in queue will
|
|
190
|
+
// set busy=true, which would be overwritten if we did it after.
|
|
191
|
+
state.busy = false;
|
|
192
|
+
state.activeCtx = undefined;
|
|
193
|
+
if (strategy === 'merge') {
|
|
194
|
+
drainMergeBuffer(key, state, ctx).catch(() => {});
|
|
195
|
+
} else {
|
|
196
|
+
drainQueue(key);
|
|
197
|
+
}
|
|
198
|
+
cleanupState(key);
|
|
199
|
+
}, maxProcessingMs);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
try {
|
|
203
|
+
await next();
|
|
204
|
+
} finally {
|
|
205
|
+
if (timeoutId) clearTimeout(timeoutId);
|
|
206
|
+
|
|
207
|
+
if (!timedOut) {
|
|
208
|
+
// timeout not triggered, release lock normally
|
|
209
|
+
state.activeCtx = undefined;
|
|
210
|
+
|
|
211
|
+
if (strategy === "merge") {
|
|
212
|
+
await drainMergeBuffer(key, state, ctx);
|
|
213
|
+
state.busy = false;
|
|
214
|
+
} else {
|
|
215
|
+
state.busy = false;
|
|
216
|
+
if (strategy === "queue" || strategy === "abort") {
|
|
217
|
+
drainQueue(key);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
cleanupState(key);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Target is busy — apply strategy
|
|
228
|
+
switch (strategy) {
|
|
229
|
+
case "merge": {
|
|
230
|
+
if (!state.mergeBuffer || !state.mergeWaiters) {
|
|
231
|
+
state.mergeBuffer = [];
|
|
232
|
+
state.mergeWaiters = [];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Urgent message: flush buffered waiters, continue remaining chain
|
|
236
|
+
// immediately via next() in parallel to active owner.
|
|
237
|
+
if (urgentPredicate?.(ctx)) {
|
|
238
|
+
ctx.log.debug?.(`[concurrency:merge] urgent for ${key}`);
|
|
239
|
+
for (const w of state.mergeWaiters) w.resolve();
|
|
240
|
+
state.mergeBuffer.length = 0;
|
|
241
|
+
state.mergeWaiters.length = 0;
|
|
242
|
+
await next();
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (state.mergeBuffer.length >= maxQueue) {
|
|
247
|
+
ctx.log.debug?.(`[concurrency:merge] buffer full (${maxQueue}), drop for ${key}`);
|
|
248
|
+
await onDrop?.(ctx);
|
|
249
|
+
ctx.stop("concurrency:merge-full");
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
ctx.log.debug?.(
|
|
254
|
+
`[concurrency:merge] buffered: ${key} (msgId=${ctx.message.messageId} ` +
|
|
255
|
+
`pos=${state.mergeBuffer.length + 1})`,
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
// Buffer the ctx and pause — do NOT stop the chain.
|
|
259
|
+
state.mergeBuffer.push(ctx);
|
|
260
|
+
|
|
261
|
+
// Wait until the batch is processed. If we are the survivor,
|
|
262
|
+
// proceed to next(); otherwise return silently.
|
|
263
|
+
let isSurvivor = false;
|
|
264
|
+
await new Promise<void>((resolve) => {
|
|
265
|
+
state.mergeWaiters!.push({
|
|
266
|
+
ctx,
|
|
267
|
+
resolve,
|
|
268
|
+
markSurvivor: () => {
|
|
269
|
+
isSurvivor = true;
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
if (isSurvivor) {
|
|
275
|
+
await next();
|
|
276
|
+
}
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
case "drop": {
|
|
281
|
+
ctx.log.debug?.(`[concurrency] drop message for busy target ${key}`);
|
|
282
|
+
await onDrop?.(ctx);
|
|
283
|
+
ctx.stop("concurrency:drop");
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
case "abort": {
|
|
288
|
+
ctx.log.debug?.(`[concurrency] abort previous for ${key}`);
|
|
289
|
+
|
|
290
|
+
state.activeCtx?.abort("concurrency:abort");
|
|
291
|
+
|
|
292
|
+
for (const entry of state.queue) {
|
|
293
|
+
entry.ctx?.abort("concurrency:superseded");
|
|
294
|
+
entry.run();
|
|
295
|
+
}
|
|
296
|
+
state.queue.length = 0;
|
|
297
|
+
|
|
298
|
+
await waitForRelease(state, ctx);
|
|
299
|
+
|
|
300
|
+
if (ctx.signal.aborted) {
|
|
301
|
+
ctx.log.debug?.(`[concurrency] superseded while waiting for ${key}`);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
state.busy = true;
|
|
306
|
+
state.activeCtx = ctx;
|
|
307
|
+
try {
|
|
308
|
+
await next();
|
|
309
|
+
} finally {
|
|
310
|
+
state.busy = false;
|
|
311
|
+
state.activeCtx = undefined;
|
|
312
|
+
drainQueue(key);
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
case "queue":
|
|
318
|
+
default: {
|
|
319
|
+
if (state.queue.length >= maxQueue) {
|
|
320
|
+
ctx.log.debug?.(`[concurrency] queue full (${maxQueue}), drop for ${key}`);
|
|
321
|
+
await onDrop?.(ctx);
|
|
322
|
+
ctx.stop("concurrency:queue-full");
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
ctx.log.debug?.(`[concurrency] queued message for ${key} (pos=${state.queue.length + 1})`);
|
|
327
|
+
await new Promise<void>((resolve) => {
|
|
328
|
+
state.queue.push({ run: resolve });
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
state.busy = true;
|
|
332
|
+
state.activeCtx = ctx;
|
|
333
|
+
try {
|
|
334
|
+
await next();
|
|
335
|
+
} finally {
|
|
336
|
+
state.busy = false;
|
|
337
|
+
state.activeCtx = undefined;
|
|
338
|
+
drainQueue(key);
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Drain the merge buffer: merge buffered ctxs into one survivor,
|
|
347
|
+
* mark it, and resolve all waiters. The survivor then proceeds
|
|
348
|
+
* through its own `next()`. If `onDispatch` is set (legacy),
|
|
349
|
+
* dispatch via callback instead.
|
|
350
|
+
*/
|
|
351
|
+
async function drainMergeBuffer(
|
|
352
|
+
key: string,
|
|
353
|
+
state: TargetState,
|
|
354
|
+
ownerCtx: MiddlewareContext,
|
|
355
|
+
): Promise<void> {
|
|
356
|
+
while (state.mergeBuffer && state.mergeBuffer.length > 0) {
|
|
357
|
+
const buffered = state.mergeBuffer.splice(0);
|
|
358
|
+
const waiters = state.mergeWaiters?.splice(0) ?? [];
|
|
359
|
+
|
|
360
|
+
// Merge the buffered ctxs.
|
|
361
|
+
const survivor = onMerge ? onMerge(buffered) : defaultMerge(buffered);
|
|
362
|
+
const validSurvivor = buffered.includes(survivor) ? survivor : buffered[0]!;
|
|
363
|
+
|
|
364
|
+
ownerCtx.log.debug?.(
|
|
365
|
+
`[concurrency:merge] flushing batch: ${key} (count=${buffered.length})`,
|
|
366
|
+
);
|
|
367
|
+
|
|
368
|
+
// Dispatch: onDispatch (legacy) or survivor self-proceeds via next().
|
|
369
|
+
if (onDispatch) {
|
|
370
|
+
state.activeCtx = validSurvivor;
|
|
371
|
+
try {
|
|
372
|
+
await onDispatch(validSurvivor);
|
|
373
|
+
} catch (err) {
|
|
374
|
+
validSurvivor.log.error?.(
|
|
375
|
+
`[concurrency:merge] onDispatch error: ${err instanceof Error ? err.message : String(err)}`,
|
|
376
|
+
);
|
|
377
|
+
} finally {
|
|
378
|
+
state.activeCtx = undefined;
|
|
379
|
+
}
|
|
380
|
+
// All waiters resolve — none are survivors.
|
|
381
|
+
for (const w of waiters) w.resolve();
|
|
382
|
+
} else {
|
|
383
|
+
// Mark the survivor's waiter; resolve all.
|
|
384
|
+
for (const w of waiters) {
|
|
385
|
+
if (w.ctx === validSurvivor) w.markSurvivor();
|
|
386
|
+
w.resolve();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
state.mergeBuffer = undefined;
|
|
392
|
+
state.mergeWaiters = undefined;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function drainQueue(key: string) {
|
|
396
|
+
const state = locks.get(key);
|
|
397
|
+
if (!state) return;
|
|
398
|
+
const entry = state.queue.shift();
|
|
399
|
+
if (entry) {
|
|
400
|
+
entry.run();
|
|
401
|
+
} else if (!state.busy) {
|
|
402
|
+
locks.delete(key);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function waitForRelease(
|
|
407
|
+
state: { busy: boolean; queue: QueueEntry[] },
|
|
408
|
+
ctx?: MiddlewareContext,
|
|
409
|
+
): Promise<void> {
|
|
410
|
+
if (!state.busy) return Promise.resolve();
|
|
411
|
+
return new Promise<void>((resolve) => {
|
|
412
|
+
state.queue.unshift({ run: resolve, ctx });
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Default merge: concatenate contents with newline, keep first ctx as survivor.
|
|
418
|
+
*/
|
|
419
|
+
function defaultMerge(buffered: MiddlewareContext[]): MiddlewareContext {
|
|
420
|
+
const first = buffered[0]!;
|
|
421
|
+
if (buffered.length === 1) return first;
|
|
422
|
+
|
|
423
|
+
const contentBearingCtxs = buffered.filter(
|
|
424
|
+
(ctx) => (ctx.message.content ?? "") !== "",
|
|
425
|
+
);
|
|
426
|
+
|
|
427
|
+
const contents = contentBearingCtxs.map((ctx) => ctx.message.content as string);
|
|
428
|
+
if (contents.length > 0) {
|
|
429
|
+
first.message.content = contents.join("\n");
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const envelopes = contentBearingCtxs
|
|
433
|
+
.map((ctx) => ctx.state.envelope as string | undefined)
|
|
434
|
+
.filter(Boolean);
|
|
435
|
+
if (envelopes.length > 0) {
|
|
436
|
+
first.state.envelope = envelopes.join("\n\n");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const allAttachments = contentBearingCtxs.flatMap(
|
|
440
|
+
(ctx) => ctx.message.attachments ?? [],
|
|
441
|
+
);
|
|
442
|
+
if (allAttachments.length > 0) {
|
|
443
|
+
first.message.attachments = allAttachments;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
return first;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
return guard;
|
|
450
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
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
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
14
|
+
|
|
15
|
+
export interface ContentSanitizerOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Whether to strip `<@!{appId}>` / `<@{appId}>` mention markers.
|
|
18
|
+
* Defaults to `true`.
|
|
19
|
+
*/
|
|
20
|
+
stripBotMention?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* Whether to strip all `<@!{id}>` markers (not just the bot's).
|
|
23
|
+
* Defaults to `false`.
|
|
24
|
+
*/
|
|
25
|
+
stripAllMentions?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Whether to collapse multiple consecutive whitespace / newlines into
|
|
28
|
+
* a single space. Defaults to `false`.
|
|
29
|
+
*/
|
|
30
|
+
collapseWhitespace?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Whether to parse QQ face tags `[<face,id=xx/>]` into emoji text.
|
|
33
|
+
* Defaults to `false` (just strip them).
|
|
34
|
+
*/
|
|
35
|
+
parseFaceTags?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* Custom transform applied after all built-in sanitization.
|
|
38
|
+
*/
|
|
39
|
+
transform?: (content: string, ctx: MiddlewareContext) => string;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* bot.use(contentSanitizer()); // Default: strip bot mention + trim
|
|
46
|
+
* bot.use(contentSanitizer({ stripAllMentions: true, collapseWhitespace: true }));
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export function contentSanitizer(options: ContentSanitizerOptions = {}): Middleware {
|
|
50
|
+
const {
|
|
51
|
+
stripBotMention = true,
|
|
52
|
+
stripAllMentions = false,
|
|
53
|
+
collapseWhitespace = false,
|
|
54
|
+
parseFaceTags = false,
|
|
55
|
+
transform,
|
|
56
|
+
} = options;
|
|
57
|
+
|
|
58
|
+
return async (ctx, next) => {
|
|
59
|
+
let content = ctx.message.content ?? "";
|
|
60
|
+
|
|
61
|
+
// Strip mention markers
|
|
62
|
+
if (stripAllMentions) {
|
|
63
|
+
content = content.replace(/<@!?\d+>\s*/g, "");
|
|
64
|
+
} else if (stripBotMention) {
|
|
65
|
+
const appId = ctx.bot.appId;
|
|
66
|
+
if (appId) {
|
|
67
|
+
const re = new RegExp(`<@!?${appId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}>\\s*`, "g");
|
|
68
|
+
content = re[Symbol.replace](content, "");
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Face tags: old format [<face,id=xx/>] + new format <faceType=xx,faceId="xx",ext="base64">
|
|
73
|
+
if (parseFaceTags) {
|
|
74
|
+
// Old format: map face ids to emoji
|
|
75
|
+
content = content.replace(/\[<face,id=(\d+)\/?>]/g, (_m, id) => faceToEmoji(id) ?? "");
|
|
76
|
+
// New format: decode base64 ext to get face name
|
|
77
|
+
content = content.replace(/<faceType=\d+,faceId="[^"]*",ext="([^"]*)">/g, (_m, ext) => {
|
|
78
|
+
try {
|
|
79
|
+
const decoded = Buffer.from(ext, 'base64').toString('utf-8');
|
|
80
|
+
const parsed = JSON.parse(decoded);
|
|
81
|
+
return `【表情: ${parsed.text || '未知表情'}】`;
|
|
82
|
+
} catch {
|
|
83
|
+
return _m;
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
} else {
|
|
87
|
+
// Strip both formats
|
|
88
|
+
content = content.replace(/\[<face,id=\d+\/?>]/g, "");
|
|
89
|
+
content = content.replace(/<faceType=\d+,faceId="[^"]*",ext="[^"]*">/g, "");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Collapse whitespace
|
|
93
|
+
if (collapseWhitespace) {
|
|
94
|
+
content = content.replace(/\s+/g, " ");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Trim
|
|
98
|
+
content = content.trim();
|
|
99
|
+
|
|
100
|
+
// Custom transform
|
|
101
|
+
if (transform) {
|
|
102
|
+
content = transform(content, ctx);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
ctx.message.content = content;
|
|
106
|
+
await next();
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Simplified face-id → emoji mapping (QQ common faces). */
|
|
111
|
+
function faceToEmoji(id: string): string | undefined {
|
|
112
|
+
const map: Record<string, string> = {
|
|
113
|
+
"0": "😊", "1": "😣", "2": "😍", "4": "😎", "5": "😭",
|
|
114
|
+
"6": "😳", "7": "🤐", "8": "😴", "9": "😢", "10": "😰",
|
|
115
|
+
"11": "😡", "12": "🤗", "13": "⭐", "14": "🌟", "15": "🌙",
|
|
116
|
+
"16": "👍", "18": "✊", "21": "😊", "23": "😢", "25": "🤔",
|
|
117
|
+
"26": "😱", "27": "😅", "28": "😁", "29": "🤮", "30": "💪",
|
|
118
|
+
"32": "🎉", "33": "😤", "34": "😏", "35": "🥺", "49": "🐷",
|
|
119
|
+
"53": "🎂", "60": "☕", "63": "🌹", "66": "❤️", "74": "🌞",
|
|
120
|
+
"75": "🌛", "76": "👏", "78": "🤝", "79": "✌️", "85": "🎅",
|
|
121
|
+
"89": "🍉", "96": "😓", "97": "😲", "100": "😂", "101": "😊",
|
|
122
|
+
"104": "😭", "106": "😱", "109": "😘", "111": "🥰",
|
|
123
|
+
};
|
|
124
|
+
return map[id];
|
|
125
|
+
}
|