@chen_hu_hu/pi-qq 1.0.1 → 1.0.2
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 +5 -6
- package/doc/{features.md → features-v1.md} +28 -50
- package/doc/{plan.md → plan-v1.md} +22 -27
- package/index.ts +14 -54
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +16 -16
- package/src/budget-status.ts +1 -1
- package/src/config.ts +2 -5
- package/src/download.ts +3 -3
- package/src/files.ts +6 -6
- package/src/format.ts +6 -1
- package/src/images.ts +6 -6
- package/src/inbound.ts +7 -7
- package/src/outbound.ts +22 -22
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +70 -75
- package/src/usage.ts +0 -93
package/src/bot.ts
CHANGED
|
@@ -10,36 +10,36 @@ import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
|
10
10
|
import type { Credentials } from "./config";
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* QQBot
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* Session-level QQBot lifecycle: creation, middleware, connection state,
|
|
14
|
+
* and fatal-error reporting. start() blocks until stop()/abort, so it runs
|
|
15
|
+
* in the background (void, not awaited).
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
export type BotState =
|
|
19
|
-
| "stopped" //
|
|
20
|
-
| "starting" //
|
|
21
|
-
| "connected" //
|
|
22
|
-
| "reconnecting" //
|
|
23
|
-
| "blocked"; //
|
|
19
|
+
| "stopped" // Not running/stopped
|
|
20
|
+
| "starting" // Connecting, waiting for READY
|
|
21
|
+
| "connected" // Online (READY/RESUMED)
|
|
22
|
+
| "reconnecting" // Disconnected; the SDK is reconnecting
|
|
23
|
+
| "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
|
|
24
24
|
|
|
25
25
|
export interface StartBotOptions {
|
|
26
26
|
credentials: Credentials;
|
|
27
27
|
/** F2: QR-bound single user; production always provides it */
|
|
28
28
|
allowedOpenid?: string;
|
|
29
29
|
markdownSupport?: boolean;
|
|
30
|
-
/**
|
|
30
|
+
/** Debug mode: print SDK logs (timeouts/rate limits/reconnects) to the terminal. */
|
|
31
31
|
debug?: boolean;
|
|
32
|
-
/**
|
|
32
|
+
/** Inbound message handler. */
|
|
33
33
|
onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
|
|
34
|
-
/**
|
|
34
|
+
/** Connection state changes; the caller decides how to notify the UI. */
|
|
35
35
|
onStateChange?: (state: BotState, detail?: string) => void;
|
|
36
|
-
/**
|
|
36
|
+
/** Recoverable errors; the SDK reconnects automatically. */
|
|
37
37
|
onRecoverableError?: (err: Error) => void;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
export interface RunningBot {
|
|
41
41
|
bot: QQBot;
|
|
42
|
-
/**
|
|
42
|
+
/** Idempotent stop. */
|
|
43
43
|
stop: () => void;
|
|
44
44
|
}
|
|
45
45
|
|
|
@@ -50,13 +50,13 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
50
50
|
markdownSupport: opts.markdownSupport ?? false,
|
|
51
51
|
});
|
|
52
52
|
|
|
53
|
-
//
|
|
53
|
+
// Echo filtering + message deduplication (SDK default 5s window).
|
|
54
54
|
bot.use(messageFilter({ skipSelfEcho: true }));
|
|
55
|
-
//
|
|
55
|
+
// Strip protocol markers such as @mentions and face tags.
|
|
56
56
|
bot.use(contentSanitizer({ stripBotMention: true }));
|
|
57
57
|
// Single-user allowlist for C2C; inbound also rejects when no QR login is active.
|
|
58
58
|
bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
|
|
59
|
-
//
|
|
59
|
+
// Serialize per user so streams and replies do not race.
|
|
60
60
|
bot.use(concurrencyGuard());
|
|
61
61
|
|
|
62
62
|
const report = (state: BotState, detail?: string) => opts.onStateChange?.(state, detail);
|
package/src/budget-status.ts
CHANGED
|
@@ -10,7 +10,7 @@ function mask(value: string): string {
|
|
|
10
10
|
return `${value.slice(0, 8)}…`;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
/** Render `/qq-budget` output lines; pure function for tests. */
|
|
13
|
+
/** Render `/qq-test-budget` output lines; pure function for tests. */
|
|
14
14
|
export function formatBudgetStatus(
|
|
15
15
|
snapshot: BudgetSnapshot,
|
|
16
16
|
last: BudgetTarget | undefined,
|
package/src/config.ts
CHANGED
|
@@ -9,14 +9,12 @@ import { join } from "node:path";
|
|
|
9
9
|
* process memory, so restarting pi requires scanning a new QR code.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
/** Runtime settings (features.md §4). */
|
|
12
|
+
/** Runtime settings (features-v1.md §4). */
|
|
13
13
|
export interface PiQQSettings {
|
|
14
14
|
/** F4: stream assistant replies */
|
|
15
15
|
streamAssistant?: boolean;
|
|
16
16
|
/** F4: bot has QQ markdown permission; pass Markdown through when true */
|
|
17
17
|
markdownSupport?: boolean;
|
|
18
|
-
/** F5/F6: usage summary switch */
|
|
19
|
-
usageRelay?: boolean;
|
|
20
18
|
/** F2: how a busy agent handles new messages */
|
|
21
19
|
deliverAs?: "steer" | "followUp";
|
|
22
20
|
/** F3: QQ image download limit (bytes) */
|
|
@@ -63,12 +61,11 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
|
|
|
63
61
|
|
|
64
62
|
export interface ResolvedSettings extends Required<PiQQSettings> {}
|
|
65
63
|
|
|
66
|
-
/** Settings with defaults applied (features.md §4). */
|
|
64
|
+
/** Settings with defaults applied (features-v1.md §4). */
|
|
67
65
|
export function getSettings(config: PiQQConfig): ResolvedSettings {
|
|
68
66
|
return {
|
|
69
67
|
streamAssistant: config.streamAssistant ?? true,
|
|
70
68
|
markdownSupport: config.markdownSupport ?? false,
|
|
71
|
-
usageRelay: config.usageRelay ?? true,
|
|
72
69
|
deliverAs: config.deliverAs ?? "steer",
|
|
73
70
|
imageMaxSize: config.imageMaxSize ?? 10 * 1024 * 1024,
|
|
74
71
|
fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
|
package/src/download.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { formatBytes } from "./format";
|
|
2
2
|
|
|
3
|
-
/** QQ
|
|
3
|
+
/** Minimal QQ inbound attachment shape shared by images and files. */
|
|
4
4
|
export interface InboundAttachmentLike {
|
|
5
5
|
content_type: string;
|
|
6
6
|
url: string;
|
|
@@ -12,7 +12,7 @@ export interface DownloadOptions {
|
|
|
12
12
|
url: string;
|
|
13
13
|
maxSize: number;
|
|
14
14
|
timeoutMs: number;
|
|
15
|
-
/**
|
|
15
|
+
/** Kind label used in errors, e.g. "image" or "file". */
|
|
16
16
|
kind: string;
|
|
17
17
|
fetchImpl?: typeof fetch;
|
|
18
18
|
}
|
|
@@ -48,7 +48,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
48
48
|
return Buffer.concat(chunks, total);
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
/**
|
|
51
|
+
/** Download an attachment with a timeout and streaming size cap. */
|
|
52
52
|
export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
53
53
|
const limit = Math.max(1, opts.maxSize);
|
|
54
54
|
let parsed: URL;
|
package/src/files.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** QQ
|
|
1
|
+
/** Save QQ non-image attachments in the workspace and reference them in the prompt. */
|
|
2
2
|
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
3
|
import { basename, extname, join } from "node:path";
|
|
4
4
|
import { downloadLimited, type InboundAttachmentLike } from "./download";
|
|
@@ -20,9 +20,9 @@ export interface FileFailure {
|
|
|
20
20
|
|
|
21
21
|
export interface SaveFilesOptions {
|
|
22
22
|
maxSize: number;
|
|
23
|
-
/**
|
|
23
|
+
/** Test override; defaults to <cwd>/.pi/pi-qq. */
|
|
24
24
|
baseDir?: string;
|
|
25
|
-
/**
|
|
25
|
+
/** Directory key for one message (usually msgId). */
|
|
26
26
|
dirKey?: string;
|
|
27
27
|
now?: Date;
|
|
28
28
|
fetchImpl?: typeof fetch;
|
|
@@ -47,7 +47,7 @@ function withSuffix(filename: string, suffix: number): string {
|
|
|
47
47
|
return `${stem}-${suffix}${ext}`;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
/**
|
|
50
|
+
/** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
|
|
51
51
|
export function sanitizeFilename(filename: string | undefined, fallback: string): string {
|
|
52
52
|
const raw = basename((filename ?? "").trim());
|
|
53
53
|
const cleaned = raw
|
|
@@ -81,7 +81,7 @@ async function writeUnique(dir: string, filename: string, body: Buffer): Promise
|
|
|
81
81
|
throw new Error("无法分配唯一文件名");
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
/**
|
|
84
|
+
/** Save non-image attachments in order; one failure does not stop the others. */
|
|
85
85
|
export async function saveInboundFiles(
|
|
86
86
|
attachments: readonly InboundAttachmentLike[],
|
|
87
87
|
options: SaveFilesOptions,
|
|
@@ -124,7 +124,7 @@ export async function saveInboundFiles(
|
|
|
124
124
|
return { files, failures };
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
/**
|
|
127
|
+
/** Combine saved paths and the original user message into the pi prompt. */
|
|
128
128
|
export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
|
|
129
129
|
if (files.length === 0) return userText;
|
|
130
130
|
|
package/src/format.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Human-readable size formatting shared by image/file downloads and prompts. */
|
|
2
2
|
export function formatBytes(bytes: number): string {
|
|
3
3
|
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
|
|
4
4
|
if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
5
5
|
return `${bytes}B`;
|
|
6
6
|
}
|
|
7
|
+
|
|
8
|
+
/** Compact token count used by /qq-status. */
|
|
9
|
+
export function formatTokenCount(n: number): string {
|
|
10
|
+
return n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n);
|
|
11
|
+
}
|
package/src/images.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** QQ
|
|
1
|
+
/** QQ image attachments to pi ImageContent: validation and timeout-limited download. */
|
|
2
2
|
import { downloadLimited, type InboundAttachmentLike } from "./download";
|
|
3
3
|
import { formatBytes } from "./format";
|
|
4
4
|
|
|
@@ -44,12 +44,12 @@ const MIME_BY_EXTENSION: Record<string, string> = {
|
|
|
44
44
|
gif: "image/gif",
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
-
/**
|
|
47
|
+
/** Prefer content_type, fall back to extension; return injectable mime or null. */
|
|
48
48
|
export function resolveImageMime(contentType: string | undefined, filename: string | undefined): string | null {
|
|
49
49
|
const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
50
50
|
if (type) {
|
|
51
51
|
if (MIME_BY_CONTENT_TYPE[type]) return MIME_BY_CONTENT_TYPE[type];
|
|
52
|
-
//
|
|
52
|
+
// Reject unsupported image/* types (e.g. svg) so a wrong extension cannot bypass validation.
|
|
53
53
|
if (type.startsWith("image/")) return null;
|
|
54
54
|
}
|
|
55
55
|
|
|
@@ -57,14 +57,14 @@ export function resolveImageMime(contentType: string | undefined, filename: stri
|
|
|
57
57
|
return ext ? (MIME_BY_EXTENSION[ext] ?? null) : null;
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
/**
|
|
60
|
+
/** Whether the attachment is an image (unsupported image/* is handled by the image path). */
|
|
61
61
|
export function isImageAttachment(attachment: InboundAttachmentLike): boolean {
|
|
62
62
|
const type = (attachment.content_type ?? "").toLowerCase();
|
|
63
63
|
if (type.startsWith("image/")) return true;
|
|
64
64
|
return resolveImageMime(attachment.content_type, attachment.filename) !== null;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
-
/**
|
|
67
|
+
/** Build pi.sendUserMessage content; keep a plain string when there are no images. */
|
|
68
68
|
export function buildImageMessageContent(
|
|
69
69
|
text: string,
|
|
70
70
|
images: readonly ImageContentLike[],
|
|
@@ -116,7 +116,7 @@ async function downloadOne(
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
/**
|
|
119
|
+
/** Download images in order; one failure does not stop the others. */
|
|
120
120
|
export async function resolveInboundImages(
|
|
121
121
|
attachments: readonly InboundAttachmentLike[],
|
|
122
122
|
maxSize: number,
|
package/src/inbound.ts
CHANGED
|
@@ -20,20 +20,20 @@ import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
|
|
|
20
20
|
|
|
21
21
|
export interface InboundDeps {
|
|
22
22
|
pi: ExtensionAPI;
|
|
23
|
-
/** session_start
|
|
23
|
+
/** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
|
|
24
24
|
ctx: ExtensionContext;
|
|
25
25
|
budget: ReplyBudget;
|
|
26
|
-
/**
|
|
26
|
+
/** Read settings live so changes apply immediately. */
|
|
27
27
|
getAllowedOpenid: () => string | undefined;
|
|
28
28
|
getBoundOpenid: () => string | undefined;
|
|
29
29
|
getDeliverAs: () => "steer" | "followUp";
|
|
30
30
|
getImageMaxSize: () => number;
|
|
31
31
|
getFileMaxSize: () => number;
|
|
32
|
-
/**
|
|
32
|
+
/** Test override; defaults to saveInboundFiles. */
|
|
33
33
|
saveFiles?: typeof saveInboundFiles;
|
|
34
34
|
getStatusLines: () => string[];
|
|
35
35
|
onWarn: (msg: string) => void;
|
|
36
|
-
/** F7
|
|
36
|
+
/** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
|
|
37
37
|
markQQTrigger: (openid: string, msgId: string) => void;
|
|
38
38
|
}
|
|
39
39
|
|
|
@@ -67,7 +67,7 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
67
67
|
return;
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
// F3
|
|
70
|
+
// F3: images become ImageContent; other attachments are saved and referenced by path.
|
|
71
71
|
const imageAttachments = attachments.filter(isImageAttachment);
|
|
72
72
|
const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
|
|
73
73
|
const failures: Array<{ filename: string; reason: string }> = [];
|
|
@@ -100,7 +100,7 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
100
100
|
}
|
|
101
101
|
if (!text && images.length === 0 && files.length === 0) return;
|
|
102
102
|
|
|
103
|
-
// F7
|
|
103
|
+
// F7: mark a QQ-triggered run; do not send a start confirmation.
|
|
104
104
|
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
105
105
|
const promptText = formatFilePrompt(files, text);
|
|
106
106
|
deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
|
|
@@ -147,7 +147,7 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
|
|
|
147
147
|
await reply("任务运行中,请先 /stop 再重置会话");
|
|
148
148
|
} else {
|
|
149
149
|
await reply("正在重置会话…");
|
|
150
|
-
//
|
|
150
|
+
// Built-in /new is interactive-only; dispatch the extension command instead.
|
|
151
151
|
deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
|
|
152
152
|
}
|
|
153
153
|
break;
|
package/src/outbound.ts
CHANGED
|
@@ -2,23 +2,23 @@ import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
|
2
2
|
import { ReplyBudget } from "./reply-budget";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* pi → QQ
|
|
6
|
-
*
|
|
5
|
+
* pi → QQ text relay (F4 non-streaming path): lightweight Markdown-to-plain
|
|
6
|
+
* conversion, long-text chunking, and passive-reply budget with fallback.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
/**
|
|
9
|
+
/** Single-text limit; SDK splits around 5000 chars, leaving protocol headroom. */
|
|
10
10
|
export const TEXT_CHUNK_LIMIT = 4500;
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
|
-
* Markdown →
|
|
14
|
-
*
|
|
13
|
+
* Markdown → plain text (features-v1.md F4: no Markdown permission by default).
|
|
14
|
+
* Keep mobile readability; preserve fenced code content and drop only the fences.
|
|
15
15
|
*/
|
|
16
16
|
export function markdownToPlain(md: string): string {
|
|
17
17
|
const out: string[] = [];
|
|
18
18
|
let inFence = false;
|
|
19
19
|
|
|
20
20
|
for (const raw of md.split("\n")) {
|
|
21
|
-
//
|
|
21
|
+
// Code fences: toggle state; drop fence lines, keep content as-is.
|
|
22
22
|
if (/^\s*(```|~~~)/.test(raw)) {
|
|
23
23
|
inFence = !inFence;
|
|
24
24
|
continue;
|
|
@@ -30,7 +30,7 @@ export function markdownToPlain(md: string): string {
|
|
|
30
30
|
|
|
31
31
|
let t = raw;
|
|
32
32
|
|
|
33
|
-
//
|
|
33
|
+
// Tables: drop separator rows; strip edge pipes and trim data rows.
|
|
34
34
|
if (/^\s*\|?[\s:|-]+\|?\s*$/.test(t) && t.includes("-") && t.includes("|")) {
|
|
35
35
|
continue;
|
|
36
36
|
}
|
|
@@ -41,7 +41,7 @@ export function markdownToPlain(md: string): string {
|
|
|
41
41
|
.trim();
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
//
|
|
44
|
+
// Headings / quotes / horizontal rules
|
|
45
45
|
t = t.replace(/^\s{0,3}#{1,6}\s+/, "");
|
|
46
46
|
t = t.replace(/^\s{0,3}>\s?/, "");
|
|
47
47
|
if (/^\s{0,3}([-*_]\s*){3,}$/.test(t)) {
|
|
@@ -49,13 +49,13 @@ export function markdownToPlain(md: string): string {
|
|
|
49
49
|
continue;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
//
|
|
52
|
+
// Images: keep alt text
|
|
53
53
|
t = t.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
54
|
-
//
|
|
54
|
+
// Links: text (url); keep only url when text equals url
|
|
55
55
|
t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, url: string) =>
|
|
56
56
|
text === url ? url : `${text}(${url})`,
|
|
57
57
|
);
|
|
58
|
-
//
|
|
58
|
+
// Emphasis / inline code / strikethrough
|
|
59
59
|
t = t.replace(/\*\*([^*]+)\*\*/g, "$1");
|
|
60
60
|
t = t.replace(/__([^_]+)__/g, "$1");
|
|
61
61
|
t = t.replace(/`([^`]+)`/g, "$1");
|
|
@@ -63,7 +63,7 @@ export function markdownToPlain(md: string): string {
|
|
|
63
63
|
t = t.replace(/\*([^*\n]+)\*/g, "$1");
|
|
64
64
|
t = t.replace(/(?<![A-Za-z0-9_])_([^_\n]+)_(?![A-Za-z0-9_])/g, "$1");
|
|
65
65
|
|
|
66
|
-
//
|
|
66
|
+
// Unordered lists → •; ordered lists unchanged
|
|
67
67
|
t = t.replace(/^(\s*)[-*+]\s+/, "$1• ");
|
|
68
68
|
|
|
69
69
|
out.push(t);
|
|
@@ -76,7 +76,7 @@ export function markdownToPlain(md: string): string {
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
/**
|
|
79
|
-
*
|
|
79
|
+
* Chunk long text at newlines when possible; hard-cut when there is no newline.
|
|
80
80
|
*/
|
|
81
81
|
export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
82
82
|
if (text.length <= limit) return [text];
|
|
@@ -84,7 +84,7 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
84
84
|
let rest = text;
|
|
85
85
|
while (rest.length > limit) {
|
|
86
86
|
let cut = rest.lastIndexOf("\n", limit);
|
|
87
|
-
cut = cut <= 0 ? limit : cut + 1; // +1
|
|
87
|
+
cut = cut <= 0 ? limit : cut + 1; // +1 keeps the newline at the end of the chunk
|
|
88
88
|
chunks.push(rest.slice(0, cut));
|
|
89
89
|
rest = rest.slice(cut);
|
|
90
90
|
}
|
|
@@ -92,21 +92,21 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
92
92
|
return chunks;
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
/**
|
|
95
|
+
/** Send-channel dependencies: budget, fallback recipient, warning sink. */
|
|
96
96
|
export interface ReplyChannel {
|
|
97
97
|
budget: ReplyBudget;
|
|
98
|
-
/**
|
|
98
|
+
/** Bound user openid: fallback recipient for proactive sends. */
|
|
99
99
|
boundOpenid: string;
|
|
100
100
|
onWarn?: (msg: string) => void;
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
/**
|
|
104
|
-
*
|
|
105
|
-
* passive
|
|
104
|
+
* Send one reply (auto-chunked, one budget ticket per chunk).
|
|
105
|
+
* A failed passive send retries once as proactive.
|
|
106
106
|
*
|
|
107
|
-
* QQBot
|
|
108
|
-
* msg_type=2
|
|
109
|
-
*
|
|
107
|
+
* When QQBot is constructed with markdownSupport=true, the SDK's sendText
|
|
108
|
+
* automatically uses msg_type=2 (markdown); callers only decide whether the
|
|
109
|
+
* payload keeps Markdown, with no separate sendMarkdown path needed here.
|
|
110
110
|
*/
|
|
111
111
|
export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
|
|
112
112
|
for (const chunk of chunkText(text)) {
|
|
@@ -119,7 +119,7 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
|
|
|
119
119
|
if (mode === "passive" && msgId) ch.budget.commitPassive(msgId);
|
|
120
120
|
} catch (err) {
|
|
121
121
|
if (mode === "passive") {
|
|
122
|
-
// msgId
|
|
122
|
+
// Passive failure (e.g. stale msgId) → retry once proactively.
|
|
123
123
|
try {
|
|
124
124
|
await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
|
|
125
125
|
ch.onWarn?.("被动回复失败,已降级主动发送");
|
package/src/qrcode-terminal.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/** qrcode-terminal
|
|
1
|
+
/** qrcode-terminal has no bundled types (CJS); declare only the API we use. */
|
|
2
2
|
declare module "qrcode-terminal" {
|
|
3
3
|
export function generate(text: string, options?: { small?: boolean }, cb?: (ascii: string) => void): void;
|
|
4
4
|
export function setErrorLevel(level: number): void;
|
package/src/reply-budget.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { ReplyLimiter } from "@tencent-connect/qqbot-nodejs/protocol";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
4
|
+
* Passive reply budget (features-v1.md §3).
|
|
5
5
|
*
|
|
6
|
-
* QQ
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* QQ allows about 4 passive replies per inbound message (SDK ReplyLimiter default
|
|
7
|
+
* 4/1h); a msgId is usable for about 5 minutes after arrival. Over-limit or stale
|
|
8
|
+
* sends fall back to proactive mode. Counting reuses the SDK ReplyLimiter.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
export type ReplyMode = "passive" | "proactive";
|
|
12
12
|
|
|
13
13
|
export interface AcquireResult {
|
|
14
14
|
mode: ReplyMode;
|
|
15
|
-
/**
|
|
15
|
+
/** Sender of the latest inbound message; the caller falls back to the bound openid. */
|
|
16
16
|
openid?: string;
|
|
17
|
-
/** mode=passive
|
|
17
|
+
/** Present when mode=passive. */
|
|
18
18
|
msgId?: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
@@ -27,9 +27,9 @@ export interface BudgetSnapshot {
|
|
|
27
27
|
remaining: number;
|
|
28
28
|
totalReplies: number;
|
|
29
29
|
trackedMessages: number;
|
|
30
|
-
/**
|
|
30
|
+
/** Stream bubbles created for the current msgId (diagnostic only, not used by acquire). */
|
|
31
31
|
streamBubbles: number;
|
|
32
|
-
/**
|
|
32
|
+
/** Total stream bubbles in this process. */
|
|
33
33
|
streamBubblesTotal: number;
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -46,7 +46,7 @@ export class ReplyBudget {
|
|
|
46
46
|
this.freshMs = opts?.freshMs ?? 5 * 60_000;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
/**
|
|
49
|
+
/** Called on inbound: update the passive target and freshness start. */
|
|
50
50
|
observeInbound(openid: string, msgId: string, now = Date.now()): void {
|
|
51
51
|
if (this.last?.msgId !== msgId) {
|
|
52
52
|
this.streamMsgId = msgId;
|
|
@@ -55,14 +55,14 @@ export class ReplyBudget {
|
|
|
55
55
|
this.last = { openid, msgId, arrivedAt: now };
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
/**
|
|
58
|
+
/** Latest inbound target (diagnostics/passive sends). */
|
|
59
59
|
get lastTarget(): { openid: string; msgId: string; arrivedAt: number } | undefined {
|
|
60
60
|
return this.last;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
64
|
+
* Pick the send mode for the next message. Passive only checks; callers must
|
|
65
|
+
* call commitPassive() after a successful passive send.
|
|
66
66
|
*/
|
|
67
67
|
acquire(now = Date.now()): AcquireResult {
|
|
68
68
|
const last = this.last;
|
|
@@ -74,12 +74,12 @@ export class ReplyBudget {
|
|
|
74
74
|
return { mode: "proactive", openid: last.openid };
|
|
75
75
|
}
|
|
76
76
|
|
|
77
|
-
/**
|
|
77
|
+
/** Record a successful passive send. */
|
|
78
78
|
commitPassive(msgId: string): void {
|
|
79
79
|
this.limiter.record(msgId);
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
/**
|
|
82
|
+
/** Diagnostic: record one new stream bubble (does not affect passive limits). */
|
|
83
83
|
noteStreamBubble(msgId: string): void {
|
|
84
84
|
if (this.streamMsgId !== msgId) {
|
|
85
85
|
this.streamMsgId = msgId;
|
|
@@ -89,7 +89,7 @@ export class ReplyBudget {
|
|
|
89
89
|
this.streamBubblesTotal += 1;
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
/**
|
|
92
|
+
/** Diagnostic snapshot: passive budget, target freshness, and send counts. */
|
|
93
93
|
snapshot(now = Date.now()): BudgetSnapshot {
|
|
94
94
|
const config = this.limiter.getConfig();
|
|
95
95
|
const stats = this.limiter.getStats();
|