@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,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unified media-source abstraction for the QQ Bot upload pipeline.
|
|
3
|
+
*
|
|
4
|
+
* All rich-media entry points funnel through {@link normalizeSource}
|
|
5
|
+
* before reaching {@link MediaApi}.
|
|
6
|
+
*
|
|
7
|
+
* ## Why four branches?
|
|
8
|
+
*
|
|
9
|
+
* - `url` — remote http(s) URL that the QQ server can fetch directly.
|
|
10
|
+
* - `base64` — in-memory base64 string (typically from a `data:` URL).
|
|
11
|
+
* - `localPath` — on-disk file; kept as a path so a future chunked-upload
|
|
12
|
+
* implementation can stream it via `fs.createReadStream` without the 4/3×
|
|
13
|
+
* base64 memory overhead.
|
|
14
|
+
* - `buffer` — in-memory raw bytes (e.g. TTS output, downloaded url-fallback).
|
|
15
|
+
*
|
|
16
|
+
* ## Security baseline (localPath branch)
|
|
17
|
+
*
|
|
18
|
+
* `openLocalFile` is the canonical implementation of "safely open a
|
|
19
|
+
* local file for upload":
|
|
20
|
+
*
|
|
21
|
+
* 1. `O_NOFOLLOW` refuses to traverse symlinks (prevents post-whitelist
|
|
22
|
+
* symlink swaps / TOCTOU attacks).
|
|
23
|
+
* 2. `fstat` on the opened descriptor — NOT `fs.stat` on the path —
|
|
24
|
+
* so the size check applies to the exact byte stream we will read.
|
|
25
|
+
* 3. Rejects non-regular files (sockets / devices / directories).
|
|
26
|
+
* 4. Enforces a caller-specified `maxSize` ceiling at open time so
|
|
27
|
+
* oversized files fail fast without allocating a full buffer.
|
|
28
|
+
*
|
|
29
|
+
* Callers are still responsible for *root-whitelist* validation (i.e.
|
|
30
|
+
* "this path must live under the allowed media directory") before
|
|
31
|
+
* passing the path in; this function enforces *file-level* safety only.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import * as fs from "node:fs";
|
|
35
|
+
import { MAX_UPLOAD_SIZE, getMimeType } from "./file-utils.js";
|
|
36
|
+
import { formatFileSize } from "./format.js";
|
|
37
|
+
|
|
38
|
+
// ============ Types ============
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Fully normalized media source. Downstream uploaders switch on `kind`.
|
|
42
|
+
*
|
|
43
|
+
* - `url`: remote URL — upload via `file_data=null; url=...`.
|
|
44
|
+
* - `base64`: already-encoded base64 — upload via `file_data=...`.
|
|
45
|
+
* - `localPath`: on-disk file — one-shot path reads it into a buffer;
|
|
46
|
+
* chunked path streams it via `fs.createReadStream`.
|
|
47
|
+
* - `buffer`: raw bytes in memory — same as above minus disk I/O.
|
|
48
|
+
*/
|
|
49
|
+
export type MediaSource =
|
|
50
|
+
| { kind: "url"; url: string }
|
|
51
|
+
| { kind: "base64"; data: string; mime?: string }
|
|
52
|
+
| { kind: "localPath"; path: string; size: number; mime?: string }
|
|
53
|
+
| { kind: "buffer"; buffer: Buffer; fileName?: string; mime?: string };
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Untyped media source accepted from callers.
|
|
57
|
+
*
|
|
58
|
+
* `url` may be either a remote `http(s)://...` URL or a `data:<mime>;base64,...`
|
|
59
|
+
* data URL — {@link normalizeSource} transparently resolves the latter to a
|
|
60
|
+
* `base64` branch.
|
|
61
|
+
*/
|
|
62
|
+
export type RawMediaSource =
|
|
63
|
+
| { url: string }
|
|
64
|
+
| { base64: string; mime?: string }
|
|
65
|
+
| { localPath: string }
|
|
66
|
+
| { buffer: Buffer; fileName?: string; mime?: string };
|
|
67
|
+
|
|
68
|
+
// ============ data: URL ============
|
|
69
|
+
|
|
70
|
+
const DATA_URL_RE = /^data:([^;,]+);base64,(.+)$/i;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Parse a `data:<mime>;base64,<payload>` URL.
|
|
74
|
+
*
|
|
75
|
+
* Returns `null` when the string is not a data URL or does not declare
|
|
76
|
+
* base64 encoding. Non-base64 data URLs are intentionally rejected
|
|
77
|
+
* because the QQ upload API ingests raw base64, not arbitrary
|
|
78
|
+
* URL-encoded payloads.
|
|
79
|
+
*/
|
|
80
|
+
export function tryParseDataUrl(value: string): { mime: string; data: string } | null {
|
|
81
|
+
if (!value.startsWith("data:")) {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
const m = value.match(DATA_URL_RE);
|
|
85
|
+
if (!m) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
return { mime: m[1], data: m[2] };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ============ Local file safe open ============
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Opened handle to a local file, with metadata already validated against
|
|
95
|
+
* QQ upload limits.
|
|
96
|
+
*
|
|
97
|
+
* Callers MUST call {@link OpenedLocalFile.close} (typically in a `finally`).
|
|
98
|
+
*/
|
|
99
|
+
export interface OpenedLocalFile {
|
|
100
|
+
handle: fs.promises.FileHandle;
|
|
101
|
+
size: number;
|
|
102
|
+
close(): Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Open a local file for upload with defense-in-depth.
|
|
107
|
+
*
|
|
108
|
+
* See module documentation for the security guarantees enforced here.
|
|
109
|
+
*/
|
|
110
|
+
export async function openLocalFile(
|
|
111
|
+
filePath: string,
|
|
112
|
+
opts: { maxSize?: number } = {},
|
|
113
|
+
): Promise<OpenedLocalFile> {
|
|
114
|
+
const maxSize = opts.maxSize ?? MAX_UPLOAD_SIZE;
|
|
115
|
+
const openFlags =
|
|
116
|
+
fs.constants.O_RDONLY | ("O_NOFOLLOW" in fs.constants ? fs.constants.O_NOFOLLOW : 0);
|
|
117
|
+
const handle = await fs.promises.open(filePath, openFlags);
|
|
118
|
+
try {
|
|
119
|
+
const stat = await handle.stat();
|
|
120
|
+
if (!stat.isFile()) {
|
|
121
|
+
throw new Error("Path is not a regular file");
|
|
122
|
+
}
|
|
123
|
+
if (stat.size > maxSize) {
|
|
124
|
+
throw new Error(
|
|
125
|
+
`File is too large (${formatFileSize(stat.size)}); QQ Bot API limit is ${formatFileSize(maxSize)}`,
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
handle,
|
|
130
|
+
size: stat.size,
|
|
131
|
+
close: () => handle.close(),
|
|
132
|
+
};
|
|
133
|
+
} catch (err) {
|
|
134
|
+
await handle.close().catch(() => undefined);
|
|
135
|
+
throw err;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ============ Normalization ============
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Normalize a {@link RawMediaSource} into a {@link MediaSource}.
|
|
143
|
+
*
|
|
144
|
+
* - Strings passed via `{ url }` that start with `data:` are auto-resolved
|
|
145
|
+
* to a `base64` branch.
|
|
146
|
+
* - `localPath` branches open the file with {@link openLocalFile} solely to
|
|
147
|
+
* validate size / regular-file / O_NOFOLLOW invariants. The handle is
|
|
148
|
+
* closed immediately — actual reading is deferred to the uploader so
|
|
149
|
+
* the chunked path can stream without double-reading.
|
|
150
|
+
* - `buffer` branches enforce the same ceiling inline.
|
|
151
|
+
*
|
|
152
|
+
* `maxSize` defaults to {@link MAX_UPLOAD_SIZE} (20MB, one-shot upload limit).
|
|
153
|
+
* Callers that dispatch to the chunked uploader should pass a larger ceiling
|
|
154
|
+
* (e.g. `CHUNKED_UPLOAD_MAX_SIZE`, or a value derived from
|
|
155
|
+
* `getMaxUploadSize(fileType)`).
|
|
156
|
+
*
|
|
157
|
+
* NOTE: Root-whitelist validation is a caller concern. This function
|
|
158
|
+
* assumes the path has already passed such checks.
|
|
159
|
+
*/
|
|
160
|
+
export async function normalizeSource(
|
|
161
|
+
raw: RawMediaSource,
|
|
162
|
+
opts: { maxSize?: number } = {},
|
|
163
|
+
): Promise<MediaSource> {
|
|
164
|
+
const maxSize = opts.maxSize ?? MAX_UPLOAD_SIZE;
|
|
165
|
+
|
|
166
|
+
if ("url" in raw) {
|
|
167
|
+
const parsed = tryParseDataUrl(raw.url);
|
|
168
|
+
if (parsed) {
|
|
169
|
+
return { kind: "base64", data: parsed.data, mime: parsed.mime };
|
|
170
|
+
}
|
|
171
|
+
return { kind: "url", url: raw.url };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if ("base64" in raw) {
|
|
175
|
+
return { kind: "base64", data: raw.base64, mime: raw.mime };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if ("localPath" in raw) {
|
|
179
|
+
const opened = await openLocalFile(raw.localPath, { maxSize });
|
|
180
|
+
try {
|
|
181
|
+
return {
|
|
182
|
+
kind: "localPath",
|
|
183
|
+
path: raw.localPath,
|
|
184
|
+
size: opened.size,
|
|
185
|
+
mime: getMimeType(raw.localPath),
|
|
186
|
+
};
|
|
187
|
+
} finally {
|
|
188
|
+
await opened.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (raw.buffer.length > maxSize) {
|
|
193
|
+
throw new Error(
|
|
194
|
+
`Buffer is too large (${formatFileSize(raw.buffer.length)}); QQ Bot API limit is ${formatFileSize(maxSize)}`,
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
kind: "buffer",
|
|
199
|
+
buffer: raw.buffer,
|
|
200
|
+
fileName: raw.fileName,
|
|
201
|
+
mime: raw.mime,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ============ Materialization helpers ============
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Read a {@link MediaSource} into the `{ url?, fileData?, fileName? }` shape
|
|
209
|
+
* expected by `MediaApi.uploadMedia` (one-shot upload path).
|
|
210
|
+
*
|
|
211
|
+
* Chunked upload should bypass this helper and feed the uploader directly
|
|
212
|
+
* from the `localPath` / `buffer` branch.
|
|
213
|
+
*/
|
|
214
|
+
export async function materializeForOneShotUpload(
|
|
215
|
+
source: MediaSource,
|
|
216
|
+
): Promise<{ url?: string; fileData?: string; fileName?: string }> {
|
|
217
|
+
switch (source.kind) {
|
|
218
|
+
case "url":
|
|
219
|
+
return { url: source.url };
|
|
220
|
+
case "base64":
|
|
221
|
+
return { fileData: source.data };
|
|
222
|
+
case "localPath": {
|
|
223
|
+
const opened = await openLocalFile(source.path);
|
|
224
|
+
try {
|
|
225
|
+
const buf = await opened.handle.readFile();
|
|
226
|
+
return { fileData: buf.toString("base64") };
|
|
227
|
+
} finally {
|
|
228
|
+
await opened.close();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
case "buffer":
|
|
232
|
+
return {
|
|
233
|
+
fileData: source.buffer.toString("base64"),
|
|
234
|
+
fileName: source.fileName,
|
|
235
|
+
};
|
|
236
|
+
default: {
|
|
237
|
+
const _exhaustive: never = source;
|
|
238
|
+
throw new Error(
|
|
239
|
+
`materializeForOneShotUpload: unsupported MediaSource kind: ${JSON.stringify(_exhaustive)}`,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media tag normalization for QQ Bot messages.
|
|
3
|
+
*
|
|
4
|
+
* Normalizes malformed `<qqimg>`, `<qqvoice>`, etc. tags emitted by
|
|
5
|
+
* smaller models into canonical wrapped-tag format.
|
|
6
|
+
*
|
|
7
|
+
* Zero external dependencies.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Lowercase and trim a string, returning empty string for falsy input. */
|
|
11
|
+
function lc(s: string): string {
|
|
12
|
+
return (s ?? "").toLowerCase().trim();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Expand `~` prefix to the process home directory. */
|
|
16
|
+
function expandTilde(p: string): string {
|
|
17
|
+
if (!p) {
|
|
18
|
+
return p;
|
|
19
|
+
}
|
|
20
|
+
const home =
|
|
21
|
+
typeof process !== "undefined" ? (process.env.HOME ?? process.env.USERPROFILE) : undefined;
|
|
22
|
+
if (!home) {
|
|
23
|
+
return p;
|
|
24
|
+
}
|
|
25
|
+
if (p === "~") {
|
|
26
|
+
return home;
|
|
27
|
+
}
|
|
28
|
+
if (p.startsWith("~/") || p.startsWith("~\\")) {
|
|
29
|
+
return `${home}/${p.slice(2)}`;
|
|
30
|
+
}
|
|
31
|
+
return p;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Canonical media tags. `qqmedia` is the generic auto-routing tag.
|
|
35
|
+
const VALID_TAGS = ["qqimg", "qqvoice", "qqvideo", "qqfile", "qqmedia"] as const;
|
|
36
|
+
|
|
37
|
+
// Lowercased aliases that should normalize to the canonical tag set.
|
|
38
|
+
const TAG_ALIASES: Record<string, (typeof VALID_TAGS)[number]> = {
|
|
39
|
+
qq_img: "qqimg",
|
|
40
|
+
qqimage: "qqimg",
|
|
41
|
+
qq_image: "qqimg",
|
|
42
|
+
qqpic: "qqimg",
|
|
43
|
+
qq_pic: "qqimg",
|
|
44
|
+
qqpicture: "qqimg",
|
|
45
|
+
qq_picture: "qqimg",
|
|
46
|
+
qqphoto: "qqimg",
|
|
47
|
+
qq_photo: "qqimg",
|
|
48
|
+
img: "qqimg",
|
|
49
|
+
image: "qqimg",
|
|
50
|
+
pic: "qqimg",
|
|
51
|
+
picture: "qqimg",
|
|
52
|
+
photo: "qqimg",
|
|
53
|
+
qq_voice: "qqvoice",
|
|
54
|
+
qqaudio: "qqvoice",
|
|
55
|
+
qq_audio: "qqvoice",
|
|
56
|
+
voice: "qqvoice",
|
|
57
|
+
audio: "qqvoice",
|
|
58
|
+
qq_video: "qqvideo",
|
|
59
|
+
video: "qqvideo",
|
|
60
|
+
qq_file: "qqfile",
|
|
61
|
+
qqdoc: "qqfile",
|
|
62
|
+
qq_doc: "qqfile",
|
|
63
|
+
file: "qqfile",
|
|
64
|
+
doc: "qqfile",
|
|
65
|
+
document: "qqfile",
|
|
66
|
+
qq_media: "qqmedia",
|
|
67
|
+
media: "qqmedia",
|
|
68
|
+
attachment: "qqmedia",
|
|
69
|
+
attach: "qqmedia",
|
|
70
|
+
qqattachment: "qqmedia",
|
|
71
|
+
qq_attachment: "qqmedia",
|
|
72
|
+
qqsend: "qqmedia",
|
|
73
|
+
qq_send: "qqmedia",
|
|
74
|
+
send: "qqmedia",
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const ALL_TAG_NAMES = [...VALID_TAGS, ...Object.keys(TAG_ALIASES)];
|
|
78
|
+
ALL_TAG_NAMES.sort((a, b) => b.length - a.length);
|
|
79
|
+
|
|
80
|
+
const TAG_NAME_PATTERN = ALL_TAG_NAMES.join("|");
|
|
81
|
+
|
|
82
|
+
const LEFT_BRACKET = "(?:[<\uff1c\u003c]|<)";
|
|
83
|
+
const RIGHT_BRACKET = "(?:[>\uff1e\u003e]|>)";
|
|
84
|
+
|
|
85
|
+
/** Match self-closing media-tag syntax with file/src/path/url attributes. */
|
|
86
|
+
export const SELF_CLOSING_TAG_REGEX = new RegExp(
|
|
87
|
+
"`?" +
|
|
88
|
+
LEFT_BRACKET +
|
|
89
|
+
"\\s*(" +
|
|
90
|
+
TAG_NAME_PATTERN +
|
|
91
|
+
")" +
|
|
92
|
+
"(?:\\s+(?!file|src|path|url)[a-z_-]+\\s*=\\s*[\"']?[^\"'\\s\uff1c<>\uff1e>]*?[\"']?)*" +
|
|
93
|
+
"\\s+(?:file|src|path|url)\\s*=\\s*" +
|
|
94
|
+
"[\"']?" +
|
|
95
|
+
"([^\"'\\s>\uff1e]+?)" +
|
|
96
|
+
"[\"']?" +
|
|
97
|
+
"(?:\\s+[a-z_-]+\\s*=\\s*[\"']?[^\"'\\s\uff1c<>\uff1e>]*?[\"']?)*" +
|
|
98
|
+
"\\s*/?" +
|
|
99
|
+
"\\s*" +
|
|
100
|
+
RIGHT_BRACKET +
|
|
101
|
+
"`?",
|
|
102
|
+
"gi",
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
/** Match malformed wrapped media tags that should be normalized. */
|
|
106
|
+
export const FUZZY_MEDIA_TAG_REGEX = new RegExp(
|
|
107
|
+
"`?" +
|
|
108
|
+
LEFT_BRACKET +
|
|
109
|
+
"\\s*(" +
|
|
110
|
+
TAG_NAME_PATTERN +
|
|
111
|
+
")\\s*" +
|
|
112
|
+
RIGHT_BRACKET +
|
|
113
|
+
"[\"']?\\s*" +
|
|
114
|
+
"([^<\uff1c<\uff1e>\"'`]+?)" +
|
|
115
|
+
"\\s*[\"']?" +
|
|
116
|
+
LEFT_BRACKET +
|
|
117
|
+
"\\s*/?\\s*(?:" +
|
|
118
|
+
TAG_NAME_PATTERN +
|
|
119
|
+
")\\s*" +
|
|
120
|
+
RIGHT_BRACKET +
|
|
121
|
+
"`?",
|
|
122
|
+
"gi",
|
|
123
|
+
);
|
|
124
|
+
|
|
125
|
+
/** Normalize a raw tag name into the canonical tag set. */
|
|
126
|
+
function resolveTagName(raw: string): (typeof VALID_TAGS)[number] {
|
|
127
|
+
const lower = lc(raw);
|
|
128
|
+
if ((VALID_TAGS as readonly string[]).includes(lower)) {
|
|
129
|
+
return lower as (typeof VALID_TAGS)[number];
|
|
130
|
+
}
|
|
131
|
+
return TAG_ALIASES[lower] ?? "qqimg";
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Match wrapped tags whose bodies need newline and tab cleanup. */
|
|
135
|
+
const MULTILINE_TAG_CLEANUP = new RegExp(
|
|
136
|
+
"(" +
|
|
137
|
+
LEFT_BRACKET +
|
|
138
|
+
"\\s*(?:" +
|
|
139
|
+
TAG_NAME_PATTERN +
|
|
140
|
+
")\\s*" +
|
|
141
|
+
RIGHT_BRACKET +
|
|
142
|
+
")" +
|
|
143
|
+
"([\\s\\S]*?)" +
|
|
144
|
+
"(" +
|
|
145
|
+
LEFT_BRACKET +
|
|
146
|
+
"\\s*/?\\s*(?:" +
|
|
147
|
+
TAG_NAME_PATTERN +
|
|
148
|
+
")\\s*" +
|
|
149
|
+
RIGHT_BRACKET +
|
|
150
|
+
")",
|
|
151
|
+
"gi",
|
|
152
|
+
);
|
|
153
|
+
|
|
154
|
+
/** Normalize malformed media-tag output into canonical wrapped tags. */
|
|
155
|
+
export function normalizeMediaTags(text: string): string {
|
|
156
|
+
const normalizeWrappedTag = (_match: string, rawTag: string, content: string): string => {
|
|
157
|
+
const tag = resolveTagName(rawTag);
|
|
158
|
+
const trimmed = content.trim();
|
|
159
|
+
if (!trimmed) {
|
|
160
|
+
return _match;
|
|
161
|
+
}
|
|
162
|
+
const expanded = expandTilde(trimmed);
|
|
163
|
+
return `<${tag}>${expanded}</${tag}>`;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
let cleaned = text.replace(SELF_CLOSING_TAG_REGEX, normalizeWrappedTag);
|
|
167
|
+
|
|
168
|
+
cleaned = cleaned.replace(
|
|
169
|
+
MULTILINE_TAG_CLEANUP,
|
|
170
|
+
(_m, open: string, body: string, close: string) => {
|
|
171
|
+
const flat = body.replace(/[\r\n\t]+/g, " ").replace(/ {2,}/g, " ");
|
|
172
|
+
return open + flat + close;
|
|
173
|
+
},
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
return cleaned.replace(FUZZY_MEDIA_TAG_REGEX, normalizeWrappedTag);
|
|
177
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media-type detection for QQ Bot outbound routing.
|
|
3
|
+
*
|
|
4
|
+
* Classifies a file path (or URL) into one of `image | voice | video |
|
|
5
|
+
* file` based on MIME type first, file extension as fallback. Used by
|
|
6
|
+
* the outbound dispatcher to pick the right send path.
|
|
7
|
+
*
|
|
8
|
+
* Pure string-based — no I/O. The audio detection in
|
|
9
|
+
* {@link "./audio.js"} owns the broader QQ-platform voice-format rules
|
|
10
|
+
* (silk/amr/etc.); this module's `voice` classification is a coarser
|
|
11
|
+
* "any audio file" check matching legacy outbound routing semantics.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { isAudioFile } from "./audio.js";
|
|
15
|
+
|
|
16
|
+
/** Supported media kind for QQ Bot outbound routing. */
|
|
17
|
+
export type MediaKind = "image" | "voice" | "video" | "file";
|
|
18
|
+
|
|
19
|
+
/** Display labels for media kinds. */
|
|
20
|
+
export const MEDIA_KIND_LABELS: Record<MediaKind | "media", string> = {
|
|
21
|
+
image: "Image",
|
|
22
|
+
voice: "Voice",
|
|
23
|
+
video: "Video",
|
|
24
|
+
file: "File",
|
|
25
|
+
media: "Media",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
|
|
29
|
+
const VIDEO_EXTENSIONS = new Set([".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv", ".wmv"]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Extract a lowercase file extension from a path or URL, ignoring query and hash.
|
|
33
|
+
*/
|
|
34
|
+
export function getCleanExtension(filePath: string): string {
|
|
35
|
+
const cleanPath = filePath.split("?")[0].split("#")[0];
|
|
36
|
+
const lastDot = cleanPath.lastIndexOf(".");
|
|
37
|
+
if (lastDot < 0) {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
return cleanPath.slice(lastDot).toLowerCase();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Check whether a file is an image using MIME first and extension as fallback. */
|
|
44
|
+
export function isImageFile(filePath: string, mimeType?: string): boolean {
|
|
45
|
+
if (mimeType?.startsWith("image/")) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
return IMAGE_EXTENSIONS.has(getCleanExtension(filePath));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Check whether a file is a video using MIME first and extension as fallback. */
|
|
52
|
+
export function isVideoFile(filePath: string, mimeType?: string): boolean {
|
|
53
|
+
if (mimeType?.startsWith("video/")) {
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
return VIDEO_EXTENSIONS.has(getCleanExtension(filePath));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Auto-detect the media kind from a file path and optional MIME type.
|
|
61
|
+
*
|
|
62
|
+
* Priority: audio → video → image → file (default). The audio check
|
|
63
|
+
* delegates to {@link isAudioFile} to keep one source of truth for the
|
|
64
|
+
* QQ voice-format extension list.
|
|
65
|
+
*/
|
|
66
|
+
export function detectMediaKind(filePath: string, mimeType?: string): MediaKind {
|
|
67
|
+
if (isAudioFile(filePath, mimeType)) {
|
|
68
|
+
return "voice";
|
|
69
|
+
}
|
|
70
|
+
if (isVideoFile(filePath, mimeType)) {
|
|
71
|
+
return "video";
|
|
72
|
+
}
|
|
73
|
+
if (isImageFile(filePath, mimeType)) {
|
|
74
|
+
return "image";
|
|
75
|
+
}
|
|
76
|
+
return "file";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Return true when the source is a remote HTTP(S) URL. */
|
|
80
|
+
export function isHttpSource(source: string): boolean {
|
|
81
|
+
return source.startsWith("http://") || source.startsWith("https://");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Return true when the source is a Base64 data URL. */
|
|
85
|
+
export function isDataSource(source: string): boolean {
|
|
86
|
+
return source.startsWith("data:");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Return true when the source is a remote URL or data URL. */
|
|
90
|
+
export function isRemoteOrDataSource(source: string): boolean {
|
|
91
|
+
return isHttpSource(source) || isDataSource(source);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Common MIME type mapping for image extensions. */
|
|
95
|
+
export const IMAGE_MIME_TYPES: Record<string, string> = {
|
|
96
|
+
".jpg": "image/jpeg",
|
|
97
|
+
".jpeg": "image/jpeg",
|
|
98
|
+
".png": "image/png",
|
|
99
|
+
".gif": "image/gif",
|
|
100
|
+
".webp": "image/webp",
|
|
101
|
+
".bmp": "image/bmp",
|
|
102
|
+
};
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Structured payload encoding for QQ Bot agentic outputs.
|
|
3
|
+
*
|
|
4
|
+
* Two related but distinct text-encoding protocols:
|
|
5
|
+
*
|
|
6
|
+
* 1. `QQBOT_PAYLOAD:` — emitted by the model in agent output to request
|
|
7
|
+
* structured behaviour (cron reminders, media-by-path sends).
|
|
8
|
+
* 2. `QQBOT_CRON:` — base64 wrapper used to persist cron-reminder
|
|
9
|
+
* payloads in scheduled-job queues.
|
|
10
|
+
*
|
|
11
|
+
* Both are pure string transforms with no I/O.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ChatScope } from "../types.js";
|
|
15
|
+
|
|
16
|
+
// ============ Payload shapes ============
|
|
17
|
+
|
|
18
|
+
/** Structured reminder payload emitted by the model. */
|
|
19
|
+
export interface CronReminderPayload {
|
|
20
|
+
type: "cron_reminder";
|
|
21
|
+
content: string;
|
|
22
|
+
targetType: ChatScope;
|
|
23
|
+
targetAddress: string;
|
|
24
|
+
originalMessageId?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Structured media payload emitted by the model. */
|
|
28
|
+
export interface MediaPayload {
|
|
29
|
+
type: "media";
|
|
30
|
+
mediaType: "image" | "audio" | "video" | "file";
|
|
31
|
+
source: "url" | "file";
|
|
32
|
+
path: string;
|
|
33
|
+
caption?: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type QQBotPayload = CronReminderPayload | MediaPayload;
|
|
37
|
+
|
|
38
|
+
/** Result of parsing model output into a structured payload. */
|
|
39
|
+
export interface ParseResult {
|
|
40
|
+
isPayload: boolean;
|
|
41
|
+
payload?: QQBotPayload;
|
|
42
|
+
text?: string;
|
|
43
|
+
error?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const PAYLOAD_PREFIX = "QQBOT_PAYLOAD:";
|
|
47
|
+
const CRON_PREFIX = "QQBOT_CRON:";
|
|
48
|
+
|
|
49
|
+
function formatErr(e: unknown): string {
|
|
50
|
+
return e instanceof Error ? e.message : String(e);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ============ QQBOT_PAYLOAD: ============
|
|
54
|
+
|
|
55
|
+
/** Parse model output that may start with the QQ Bot structured payload prefix. */
|
|
56
|
+
export function parseQQBotPayload(text: string): ParseResult {
|
|
57
|
+
const trimmedText = text.trim();
|
|
58
|
+
|
|
59
|
+
if (!trimmedText.startsWith(PAYLOAD_PREFIX)) {
|
|
60
|
+
return { isPayload: false, text };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const jsonContent = trimmedText.slice(PAYLOAD_PREFIX.length).trim();
|
|
64
|
+
|
|
65
|
+
if (!jsonContent) {
|
|
66
|
+
return { isPayload: true, error: "Payload body is empty" };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
try {
|
|
70
|
+
const payload = JSON.parse(jsonContent) as QQBotPayload;
|
|
71
|
+
|
|
72
|
+
if (!payload.type) {
|
|
73
|
+
return { isPayload: true, error: "Payload is missing the type field" };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (payload.type === "cron_reminder") {
|
|
77
|
+
if (!payload.content || !payload.targetType || !payload.targetAddress) {
|
|
78
|
+
return {
|
|
79
|
+
isPayload: true,
|
|
80
|
+
error:
|
|
81
|
+
"cron_reminder payload is missing required fields (content, targetType, targetAddress)",
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
} else if (payload.type === "media") {
|
|
85
|
+
if (!payload.mediaType || !payload.source || !payload.path) {
|
|
86
|
+
return {
|
|
87
|
+
isPayload: true,
|
|
88
|
+
error: "media payload is missing required fields (mediaType, source, path)",
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return { isPayload: true, payload };
|
|
94
|
+
} catch (e) {
|
|
95
|
+
return { isPayload: true, error: `Failed to parse JSON: ${formatErr(e)}` };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ============ QQBOT_CRON: ============
|
|
100
|
+
|
|
101
|
+
/** Encode a cron reminder payload into the stored cron-message format. */
|
|
102
|
+
export function encodePayloadForCron(payload: CronReminderPayload): string {
|
|
103
|
+
const jsonString = JSON.stringify(payload);
|
|
104
|
+
const base64 = Buffer.from(jsonString, "utf-8").toString("base64");
|
|
105
|
+
return `${CRON_PREFIX}${base64}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Decode a stored cron payload. */
|
|
109
|
+
export function decodeCronPayload(message: string): {
|
|
110
|
+
isCronPayload: boolean;
|
|
111
|
+
payload?: CronReminderPayload;
|
|
112
|
+
error?: string;
|
|
113
|
+
} {
|
|
114
|
+
const trimmedMessage = message.trim();
|
|
115
|
+
|
|
116
|
+
if (!trimmedMessage.startsWith(CRON_PREFIX)) {
|
|
117
|
+
return { isCronPayload: false };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const base64Content = trimmedMessage.slice(CRON_PREFIX.length);
|
|
121
|
+
|
|
122
|
+
if (!base64Content) {
|
|
123
|
+
return { isCronPayload: true, error: "Cron payload body is empty" };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const jsonString = Buffer.from(base64Content, "base64").toString("utf-8");
|
|
128
|
+
const payload = JSON.parse(jsonString) as CronReminderPayload;
|
|
129
|
+
|
|
130
|
+
if (payload.type !== "cron_reminder") {
|
|
131
|
+
return {
|
|
132
|
+
isCronPayload: true,
|
|
133
|
+
error: `Expected type cron_reminder but got ${String(payload.type)}`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!payload.content || !payload.targetType || !payload.targetAddress) {
|
|
138
|
+
return { isCronPayload: true, error: "Cron payload is missing required fields" };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { isCronPayload: true, payload };
|
|
142
|
+
} catch (e) {
|
|
143
|
+
return { isCronPayload: true, error: `Failed to decode cron payload: ${formatErr(e)}` };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ============ Type guards ============
|
|
148
|
+
|
|
149
|
+
/** Type guard for cron reminder payloads. */
|
|
150
|
+
export function isCronReminderPayload(payload: QQBotPayload): payload is CronReminderPayload {
|
|
151
|
+
return payload.type === "cron_reminder";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Type guard for media payloads. */
|
|
155
|
+
export function isMediaPayload(payload: QQBotPayload): payload is MediaPayload {
|
|
156
|
+
return payload.type === "media";
|
|
157
|
+
}
|