@chen_hu_hu/pi-qq 1.0.1 → 1.1.0
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 +21 -13
- package/doc/{features.md → features-v1.md} +28 -50
- package/doc/features-v2.md +97 -0
- package/doc/{plan.md → plan-v1.md} +23 -28
- package/doc/plan-v2.md +245 -0
- package/index.ts +68 -59
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +58 -20
- package/src/budget-status.ts +1 -1
- package/src/config.ts +9 -8
- package/src/download.ts +11 -11
- package/src/files.ts +10 -10
- package/src/format.ts +6 -1
- package/src/images.ts +25 -13
- package/src/inbound.ts +103 -26
- package/src/logger.ts +180 -0
- package/src/outbound.ts +42 -25
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +85 -102
- package/src/voice.ts +25 -0
- package/src/usage.ts +0 -93
package/src/inbound.ts
CHANGED
|
@@ -11,6 +11,8 @@ import {
|
|
|
11
11
|
type ImageContentLike,
|
|
12
12
|
} from "./images";
|
|
13
13
|
import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
|
|
14
|
+
import { log } from "./logger";
|
|
15
|
+
import { isVoiceAttachment, resolveVoiceTranscript } from "./voice";
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* F2: QQ → pi inbound handling.
|
|
@@ -20,32 +22,62 @@ import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
|
|
|
20
22
|
|
|
21
23
|
export interface InboundDeps {
|
|
22
24
|
pi: ExtensionAPI;
|
|
23
|
-
/** session_start
|
|
25
|
+
/** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
|
|
24
26
|
ctx: ExtensionContext;
|
|
25
27
|
budget: ReplyBudget;
|
|
26
|
-
/**
|
|
28
|
+
/** Read settings live so changes apply immediately. */
|
|
27
29
|
getAllowedOpenid: () => string | undefined;
|
|
28
30
|
getBoundOpenid: () => string | undefined;
|
|
29
31
|
getDeliverAs: () => "steer" | "followUp";
|
|
30
32
|
getImageMaxSize: () => number;
|
|
31
33
|
getFileMaxSize: () => number;
|
|
32
|
-
/**
|
|
34
|
+
/** Test override; defaults to saveInboundFiles. */
|
|
33
35
|
saveFiles?: typeof saveInboundFiles;
|
|
34
36
|
getStatusLines: () => string[];
|
|
35
37
|
onWarn: (msg: string) => void;
|
|
36
|
-
/** F7
|
|
38
|
+
/** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
|
|
37
39
|
markQQTrigger: (openid: string, msgId: string) => void;
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
export function createInboundHandler(deps: InboundDeps) {
|
|
41
43
|
return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
|
|
42
|
-
|
|
44
|
+
log.debug("inbound", "message received", {
|
|
45
|
+
kind: msg.kind,
|
|
46
|
+
rawEventType: msg.rawEventType,
|
|
47
|
+
messageId: msg.messageId,
|
|
48
|
+
senderId: msg.senderId,
|
|
49
|
+
senderName: msg.senderName,
|
|
50
|
+
senderIsBot: msg.senderIsBot,
|
|
51
|
+
content: msg.content,
|
|
52
|
+
msgType: msg.msgType,
|
|
53
|
+
timestamp: msg.timestamp,
|
|
54
|
+
msgIdx: msg.msgIdx,
|
|
55
|
+
refMsgIdx: msg.refMsgIdx,
|
|
56
|
+
messageScene: msg.messageScene,
|
|
57
|
+
attachments: msg.attachments,
|
|
58
|
+
msgElements: msg.msgElements,
|
|
59
|
+
raw: msg.raw,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (msg.kind !== "c2c") {
|
|
63
|
+
log.debug("inbound", "skipped non-c2c message", { kind: msg.kind });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
43
66
|
|
|
44
67
|
const allowed = deps.getAllowedOpenid();
|
|
45
|
-
if (!allowed || msg.senderId !== allowed)
|
|
68
|
+
if (!allowed || msg.senderId !== allowed) {
|
|
69
|
+
log.debug("inbound", "skipped non-allowlisted sender", { senderId: msg.senderId });
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
46
72
|
|
|
47
73
|
// Record passive reply target/freshness for outbound budget.
|
|
48
74
|
deps.budget.observeInbound(msg.senderId, msg.messageId);
|
|
75
|
+
log.info("inbound", "message received", {
|
|
76
|
+
messageId: msg.messageId,
|
|
77
|
+
senderId: msg.senderId,
|
|
78
|
+
contentLength: (msg.content ?? "").length,
|
|
79
|
+
attachmentCount: (msg.attachments ?? []).length,
|
|
80
|
+
});
|
|
49
81
|
|
|
50
82
|
const channel: ReplyChannel = {
|
|
51
83
|
budget: deps.budget,
|
|
@@ -57,17 +89,40 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
57
89
|
|
|
58
90
|
const text = (msg.content ?? "").trim();
|
|
59
91
|
if (text.startsWith("/")) {
|
|
92
|
+
log.info("inbound", "QQ command", { command: text.split(/\s+/)[0] });
|
|
60
93
|
await handleCommand(text, reply, deps);
|
|
61
94
|
return;
|
|
62
95
|
}
|
|
63
96
|
|
|
64
97
|
const attachments = msg.attachments ?? [];
|
|
65
98
|
if (!text && attachments.length === 0) {
|
|
66
|
-
|
|
99
|
+
log.warn("inbound", "unsupported message: no text and no attachments", { messageId: msg.messageId });
|
|
100
|
+
await reply("Unsupported message type.");
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// F8: voice messages use QQ built-in ASR; never download or save the audio.
|
|
105
|
+
const voiceAttachments = attachments.filter(isVoiceAttachment);
|
|
106
|
+
if (voiceAttachments.length > 0) {
|
|
107
|
+
const transcript = resolveVoiceTranscript(voiceAttachments);
|
|
108
|
+
log.info("inbound", "voice message", {
|
|
109
|
+
messageId: msg.messageId,
|
|
110
|
+
hasAsr: Boolean(transcript),
|
|
111
|
+
asrLength: transcript?.length ?? 0,
|
|
112
|
+
});
|
|
113
|
+
if (!transcript) {
|
|
114
|
+
log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
|
|
115
|
+
await reply("Could not transcribe this voice message; please resend or type it.");
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
|
|
119
|
+
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
120
|
+
deps.pi.sendUserMessage(transcript, { deliverAs: deps.getDeliverAs() });
|
|
121
|
+
log.info("inbound", "voice sent to pi", { messageId: msg.messageId, asrLength: transcript.length });
|
|
67
122
|
return;
|
|
68
123
|
}
|
|
69
124
|
|
|
70
|
-
// F3
|
|
125
|
+
// F3: images become ImageContent; other attachments are saved and referenced by path.
|
|
71
126
|
const imageAttachments = attachments.filter(isImageAttachment);
|
|
72
127
|
const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
|
|
73
128
|
const failures: Array<{ filename: string; reason: string }> = [];
|
|
@@ -76,7 +131,11 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
76
131
|
if (imageAttachments.length > 0) {
|
|
77
132
|
const supportsImages = deps.ctx.model?.input.includes("image") ?? false;
|
|
78
133
|
if (!supportsImages) {
|
|
79
|
-
|
|
134
|
+
log.warn("inbound", "model does not support images; skipped", {
|
|
135
|
+
messageId: msg.messageId,
|
|
136
|
+
count: imageAttachments.length,
|
|
137
|
+
});
|
|
138
|
+
await reply(`Model does not support image input; skipped ${imageAttachments.length} image(s).`);
|
|
80
139
|
} else {
|
|
81
140
|
const result = await resolveInboundImages(imageAttachments, deps.getImageMaxSize());
|
|
82
141
|
images = result.images;
|
|
@@ -96,14 +155,32 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
96
155
|
}
|
|
97
156
|
|
|
98
157
|
if (failures.length > 0) {
|
|
158
|
+
log.warn("inbound", "attachment failure summary", {
|
|
159
|
+
messageId: msg.messageId,
|
|
160
|
+
failures,
|
|
161
|
+
successCount: images.length + files.length,
|
|
162
|
+
});
|
|
99
163
|
await reply(formatImageFailures(failures, images.length + files.length));
|
|
100
164
|
}
|
|
101
|
-
if (!text && images.length === 0 && files.length === 0)
|
|
165
|
+
if (!text && images.length === 0 && files.length === 0) {
|
|
166
|
+
log.warn("inbound", "no injectable content after attachment handling", {
|
|
167
|
+
messageId: msg.messageId,
|
|
168
|
+
failures: failures.length,
|
|
169
|
+
});
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
102
172
|
|
|
103
|
-
// F7
|
|
173
|
+
// F7: mark a QQ-triggered run; do not send a start confirmation.
|
|
104
174
|
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
105
175
|
const promptText = formatFilePrompt(files, text);
|
|
106
176
|
deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
|
|
177
|
+
log.info("inbound", "sent to pi", {
|
|
178
|
+
messageId: msg.messageId,
|
|
179
|
+
textLength: text.length,
|
|
180
|
+
images: images.length,
|
|
181
|
+
files: files.length,
|
|
182
|
+
deliverAs: deps.getDeliverAs(),
|
|
183
|
+
});
|
|
107
184
|
};
|
|
108
185
|
}
|
|
109
186
|
|
|
@@ -113,30 +190,30 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
|
|
|
113
190
|
case "/help":
|
|
114
191
|
await reply(
|
|
115
192
|
[
|
|
116
|
-
"pi-qq
|
|
117
|
-
"• /stop —
|
|
118
|
-
"• /compact —
|
|
119
|
-
"• /status —
|
|
120
|
-
"• /new —
|
|
121
|
-
"• /help —
|
|
122
|
-
"
|
|
193
|
+
"pi-qq commands:",
|
|
194
|
+
"• /stop — abort the current task",
|
|
195
|
+
"• /compact — compact the context",
|
|
196
|
+
"• /status — show status",
|
|
197
|
+
"• /new — reset the session",
|
|
198
|
+
"• /help — this help",
|
|
199
|
+
"Other text is sent to pi.",
|
|
123
200
|
].join("\n"),
|
|
124
201
|
);
|
|
125
202
|
break;
|
|
126
203
|
case "/stop":
|
|
127
204
|
if (deps.ctx.isIdle()) {
|
|
128
|
-
await reply("
|
|
205
|
+
await reply("No task is running.");
|
|
129
206
|
} else {
|
|
130
207
|
deps.ctx.abort();
|
|
131
|
-
await reply("
|
|
208
|
+
await reply("Abort requested.");
|
|
132
209
|
}
|
|
133
210
|
break;
|
|
134
211
|
case "/compact":
|
|
135
212
|
if (deps.ctx.isIdle()) {
|
|
136
213
|
deps.ctx.compact();
|
|
137
|
-
await reply("
|
|
214
|
+
await reply("Context compaction triggered.");
|
|
138
215
|
} else {
|
|
139
|
-
await reply("
|
|
216
|
+
await reply("Task is running; use /stop before /compact.");
|
|
140
217
|
}
|
|
141
218
|
break;
|
|
142
219
|
case "/status":
|
|
@@ -144,14 +221,14 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
|
|
|
144
221
|
break;
|
|
145
222
|
case "/new":
|
|
146
223
|
if (!deps.ctx.isIdle()) {
|
|
147
|
-
await reply("
|
|
224
|
+
await reply("Task is running; use /stop before resetting.");
|
|
148
225
|
} else {
|
|
149
|
-
await reply("
|
|
150
|
-
//
|
|
226
|
+
await reply("Resetting the session…");
|
|
227
|
+
// Built-in /new is interactive-only; dispatch the extension command instead.
|
|
151
228
|
deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
|
|
152
229
|
}
|
|
153
230
|
break;
|
|
154
231
|
default:
|
|
155
|
-
await reply(
|
|
232
|
+
await reply(`Unknown command ${cmd}; use /help.`);
|
|
156
233
|
}
|
|
157
234
|
}
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Structured logger for pi-qq.
|
|
6
|
+
*
|
|
7
|
+
* One JSON record per line, one file per local day:
|
|
8
|
+
* <cwd>/.pi/pi-qq/logs/pi-qq-YYYY-MM-DD.log
|
|
9
|
+
*
|
|
10
|
+
* The default level is silent. Logging is best-effort and must never break QQ
|
|
11
|
+
* message handling. Tests can override the directory via PI_QQ_LOG_DIR.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
15
|
+
export type LogFields = Record<string, unknown>;
|
|
16
|
+
|
|
17
|
+
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
|
18
|
+
debug: 10,
|
|
19
|
+
info: 20,
|
|
20
|
+
warn: 30,
|
|
21
|
+
error: 40,
|
|
22
|
+
silent: 100,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const DEFAULT_LOG_LEVEL: LogLevel = "silent";
|
|
26
|
+
|
|
27
|
+
let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
|
|
28
|
+
let activeDir: string | undefined;
|
|
29
|
+
|
|
30
|
+
export function isLogLevel(value: unknown): value is LogLevel {
|
|
31
|
+
return typeof value === "string" && Object.prototype.hasOwnProperty.call(LEVEL_WEIGHT, value);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function normalizeLogLevel(value: unknown): LogLevel {
|
|
35
|
+
return isLogLevel(value) ? value : DEFAULT_LOG_LEVEL;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Whether an event at `level` passes the configured threshold. */
|
|
39
|
+
export function isLevelEnabled(configured: LogLevel, level: Exclude<LogLevel, "silent">): boolean {
|
|
40
|
+
return configured !== "silent" && LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[configured];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Set the active threshold and optional directory. */
|
|
44
|
+
export function configureLogger(level: LogLevel, dir?: string): void {
|
|
45
|
+
activeLevel = normalizeLogLevel(level);
|
|
46
|
+
activeDir = dir;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function getLogLevel(): LogLevel {
|
|
50
|
+
return activeLevel;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function resolveLogDir(): string {
|
|
54
|
+
return process.env.PI_QQ_LOG_DIR ?? activeDir ?? join(process.cwd(), ".pi", "pi-qq", "logs");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function pad(n: number): string {
|
|
58
|
+
return String(n).padStart(2, "0");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Local calendar date used in the log filename. */
|
|
62
|
+
export function dateStamp(now = new Date()): string {
|
|
63
|
+
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function logFileName(now = new Date()): string {
|
|
67
|
+
return `pi-qq-${dateStamp(now)}.log`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function getLogFilePath(now = new Date()): string {
|
|
71
|
+
return join(resolveLogDir(), logFileName(now));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function normalizeData(data: unknown): LogFields | undefined {
|
|
75
|
+
if (data === undefined) return undefined;
|
|
76
|
+
if (data instanceof Error) return { err: data };
|
|
77
|
+
if (data !== null && typeof data === "object" && !Array.isArray(data)) return data as LogFields;
|
|
78
|
+
return { data };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function stringifyError(err: unknown): string {
|
|
82
|
+
return err instanceof Error ? err.message : String(err);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message: string, data?: unknown): void {
|
|
86
|
+
if (!isLevelEnabled(activeLevel, level)) return;
|
|
87
|
+
|
|
88
|
+
const record: LogFields = {
|
|
89
|
+
time: new Date().toISOString(),
|
|
90
|
+
level,
|
|
91
|
+
scope,
|
|
92
|
+
msg: message,
|
|
93
|
+
};
|
|
94
|
+
const fields = normalizeData(data);
|
|
95
|
+
if (fields) {
|
|
96
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
97
|
+
// Protect the record envelope from accidental overrides.
|
|
98
|
+
if (!(key in record)) record[key] = value;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let line: string;
|
|
103
|
+
try {
|
|
104
|
+
line = JSON.stringify(record, (_key, value) => {
|
|
105
|
+
if (typeof value === "bigint") return `${value}n`;
|
|
106
|
+
if (value instanceof Error) {
|
|
107
|
+
return { name: value.name, message: value.message, stack: value.stack };
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
});
|
|
111
|
+
} catch (err) {
|
|
112
|
+
line = JSON.stringify({
|
|
113
|
+
time: record.time,
|
|
114
|
+
level,
|
|
115
|
+
scope,
|
|
116
|
+
msg: message,
|
|
117
|
+
serializationError: stringifyError(err),
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
const dir = resolveLogDir();
|
|
123
|
+
mkdirSync(dir, { recursive: true });
|
|
124
|
+
appendFileSync(join(dir, logFileName()), `${line}\n`, "utf8");
|
|
125
|
+
} catch {
|
|
126
|
+
// Logging is diagnostic only; never break message handling.
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export const log = {
|
|
131
|
+
get level(): LogLevel {
|
|
132
|
+
return activeLevel;
|
|
133
|
+
},
|
|
134
|
+
debug(scope: string, message: string, data?: unknown): void {
|
|
135
|
+
writeRecord("debug", scope, message, data);
|
|
136
|
+
},
|
|
137
|
+
info(scope: string, message: string, data?: unknown): void {
|
|
138
|
+
writeRecord("info", scope, message, data);
|
|
139
|
+
},
|
|
140
|
+
warn(scope: string, message: string, data?: unknown): void {
|
|
141
|
+
writeRecord("warn", scope, message, data);
|
|
142
|
+
},
|
|
143
|
+
error(scope: string, message: string, data?: unknown): void {
|
|
144
|
+
writeRecord("error", scope, message, data);
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Adapter for the QQ SDK's Logger interface: (message, meta?) -> record. */
|
|
149
|
+
export const sdkLogger = {
|
|
150
|
+
debug(message: string, meta?: Record<string, unknown>): void {
|
|
151
|
+
log.debug("qqbot", message, meta);
|
|
152
|
+
},
|
|
153
|
+
info(message: string, meta?: Record<string, unknown>): void {
|
|
154
|
+
log.info("qqbot", message, meta);
|
|
155
|
+
},
|
|
156
|
+
warn(message: string, meta?: Record<string, unknown>): void {
|
|
157
|
+
log.warn("qqbot", message, meta);
|
|
158
|
+
},
|
|
159
|
+
error(message: string, meta?: Record<string, unknown>): void {
|
|
160
|
+
log.error("qqbot", message, meta);
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** Short string form for noisy tool payloads. */
|
|
165
|
+
export function previewForLog(value: unknown, maxChars = 2000): string {
|
|
166
|
+
let text: string;
|
|
167
|
+
if (typeof value === "string") {
|
|
168
|
+
text = value;
|
|
169
|
+
} else if (value instanceof Error) {
|
|
170
|
+
text = `${value.name}: ${value.message}`;
|
|
171
|
+
} else {
|
|
172
|
+
try {
|
|
173
|
+
const stringified = JSON.stringify(value);
|
|
174
|
+
text = typeof stringified === "string" ? stringified : String(value);
|
|
175
|
+
} catch {
|
|
176
|
+
text = String(value);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return text.length <= maxChars ? text : `${text.slice(0, maxChars)}…(${text.length} chars)`;
|
|
180
|
+
}
|
package/src/outbound.ts
CHANGED
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
2
2
|
import { ReplyBudget } from "./reply-budget";
|
|
3
|
+
import { log } from "./logger";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
|
-
* pi → QQ
|
|
6
|
-
*
|
|
6
|
+
* pi → QQ text relay (F4 non-streaming path): lightweight Markdown-to-plain
|
|
7
|
+
* conversion, long-text chunking, and passive-reply budget with fallback.
|
|
7
8
|
*/
|
|
8
9
|
|
|
9
|
-
/**
|
|
10
|
+
/** Single-text limit; SDK splits around 5000 chars, leaving protocol headroom. */
|
|
10
11
|
export const TEXT_CHUNK_LIMIT = 4500;
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
|
-
* Markdown →
|
|
14
|
-
*
|
|
14
|
+
* Markdown → plain text (features-v1.md F4: no Markdown permission by default).
|
|
15
|
+
* Keep mobile readability; preserve fenced code content and drop only the fences.
|
|
15
16
|
*/
|
|
16
17
|
export function markdownToPlain(md: string): string {
|
|
17
18
|
const out: string[] = [];
|
|
18
19
|
let inFence = false;
|
|
19
20
|
|
|
20
21
|
for (const raw of md.split("\n")) {
|
|
21
|
-
//
|
|
22
|
+
// Code fences: toggle state; drop fence lines, keep content as-is.
|
|
22
23
|
if (/^\s*(```|~~~)/.test(raw)) {
|
|
23
24
|
inFence = !inFence;
|
|
24
25
|
continue;
|
|
@@ -30,7 +31,7 @@ export function markdownToPlain(md: string): string {
|
|
|
30
31
|
|
|
31
32
|
let t = raw;
|
|
32
33
|
|
|
33
|
-
//
|
|
34
|
+
// Tables: drop separator rows; strip edge pipes and trim data rows.
|
|
34
35
|
if (/^\s*\|?[\s:|-]+\|?\s*$/.test(t) && t.includes("-") && t.includes("|")) {
|
|
35
36
|
continue;
|
|
36
37
|
}
|
|
@@ -41,7 +42,7 @@ export function markdownToPlain(md: string): string {
|
|
|
41
42
|
.trim();
|
|
42
43
|
}
|
|
43
44
|
|
|
44
|
-
//
|
|
45
|
+
// Headings / quotes / horizontal rules
|
|
45
46
|
t = t.replace(/^\s{0,3}#{1,6}\s+/, "");
|
|
46
47
|
t = t.replace(/^\s{0,3}>\s?/, "");
|
|
47
48
|
if (/^\s{0,3}([-*_]\s*){3,}$/.test(t)) {
|
|
@@ -49,13 +50,13 @@ export function markdownToPlain(md: string): string {
|
|
|
49
50
|
continue;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
|
-
//
|
|
53
|
+
// Images: keep alt text
|
|
53
54
|
t = t.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1");
|
|
54
|
-
//
|
|
55
|
+
// Links: text (url); keep only url when text equals url
|
|
55
56
|
t = t.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text: string, url: string) =>
|
|
56
57
|
text === url ? url : `${text}(${url})`,
|
|
57
58
|
);
|
|
58
|
-
//
|
|
59
|
+
// Emphasis / inline code / strikethrough
|
|
59
60
|
t = t.replace(/\*\*([^*]+)\*\*/g, "$1");
|
|
60
61
|
t = t.replace(/__([^_]+)__/g, "$1");
|
|
61
62
|
t = t.replace(/`([^`]+)`/g, "$1");
|
|
@@ -63,7 +64,7 @@ export function markdownToPlain(md: string): string {
|
|
|
63
64
|
t = t.replace(/\*([^*\n]+)\*/g, "$1");
|
|
64
65
|
t = t.replace(/(?<![A-Za-z0-9_])_([^_\n]+)_(?![A-Za-z0-9_])/g, "$1");
|
|
65
66
|
|
|
66
|
-
//
|
|
67
|
+
// Unordered lists → •; ordered lists unchanged
|
|
67
68
|
t = t.replace(/^(\s*)[-*+]\s+/, "$1• ");
|
|
68
69
|
|
|
69
70
|
out.push(t);
|
|
@@ -76,7 +77,7 @@ export function markdownToPlain(md: string): string {
|
|
|
76
77
|
}
|
|
77
78
|
|
|
78
79
|
/**
|
|
79
|
-
*
|
|
80
|
+
* Chunk long text at newlines when possible; hard-cut when there is no newline.
|
|
80
81
|
*/
|
|
81
82
|
export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
82
83
|
if (text.length <= limit) return [text];
|
|
@@ -84,7 +85,7 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
84
85
|
let rest = text;
|
|
85
86
|
while (rest.length > limit) {
|
|
86
87
|
let cut = rest.lastIndexOf("\n", limit);
|
|
87
|
-
cut = cut <= 0 ? limit : cut + 1; // +1
|
|
88
|
+
cut = cut <= 0 ? limit : cut + 1; // +1 keeps the newline at the end of the chunk
|
|
88
89
|
chunks.push(rest.slice(0, cut));
|
|
89
90
|
rest = rest.slice(cut);
|
|
90
91
|
}
|
|
@@ -92,21 +93,21 @@ export function chunkText(text: string, limit = TEXT_CHUNK_LIMIT): string[] {
|
|
|
92
93
|
return chunks;
|
|
93
94
|
}
|
|
94
95
|
|
|
95
|
-
/**
|
|
96
|
+
/** Send-channel dependencies: budget, fallback recipient, warning sink. */
|
|
96
97
|
export interface ReplyChannel {
|
|
97
98
|
budget: ReplyBudget;
|
|
98
|
-
/**
|
|
99
|
+
/** Bound user openid: fallback recipient for proactive sends. */
|
|
99
100
|
boundOpenid: string;
|
|
100
101
|
onWarn?: (msg: string) => void;
|
|
101
102
|
}
|
|
102
103
|
|
|
103
104
|
/**
|
|
104
|
-
*
|
|
105
|
-
* passive
|
|
105
|
+
* Send one reply (auto-chunked, one budget ticket per chunk).
|
|
106
|
+
* A failed passive send retries once as proactive.
|
|
106
107
|
*
|
|
107
|
-
* QQBot
|
|
108
|
-
* msg_type=2
|
|
109
|
-
*
|
|
108
|
+
* When QQBot is constructed with markdownSupport=true, the SDK's sendText
|
|
109
|
+
* automatically uses msg_type=2 (markdown); callers only decide whether the
|
|
110
|
+
* payload keeps Markdown, with no separate sendMarkdown path needed here.
|
|
110
111
|
*/
|
|
111
112
|
export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
|
|
112
113
|
for (const chunk of chunkText(text)) {
|
|
@@ -115,21 +116,37 @@ export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Pro
|
|
|
115
116
|
const replyTarget =
|
|
116
117
|
mode === "passive" && msgId ? { scope: "c2c" as const, targetId, msgId } : { scope: "c2c" as const, targetId };
|
|
117
118
|
try {
|
|
119
|
+
log.debug("outbound", "sending text chunk", {
|
|
120
|
+
mode,
|
|
121
|
+
targetId,
|
|
122
|
+
msgId: msgId ?? null,
|
|
123
|
+
length: chunk.length,
|
|
124
|
+
text: chunk,
|
|
125
|
+
});
|
|
118
126
|
await bot.sendText(replyTarget, chunk);
|
|
119
127
|
if (mode === "passive" && msgId) ch.budget.commitPassive(msgId);
|
|
128
|
+
log.info("outbound", "text chunk sent", { mode, targetId, length: chunk.length });
|
|
120
129
|
} catch (err) {
|
|
130
|
+
log.warn("outbound", "text chunk failed", {
|
|
131
|
+
mode,
|
|
132
|
+
targetId,
|
|
133
|
+
length: chunk.length,
|
|
134
|
+
err,
|
|
135
|
+
});
|
|
121
136
|
if (mode === "passive") {
|
|
122
|
-
// msgId
|
|
137
|
+
// Passive failure (e.g. stale msgId) → retry once proactively.
|
|
123
138
|
try {
|
|
139
|
+
log.warn("outbound", "passive send failed; retrying proactively", { targetId: ch.boundOpenid });
|
|
124
140
|
await bot.sendText({ scope: "c2c", targetId: ch.boundOpenid }, chunk);
|
|
125
|
-
ch.onWarn?.("
|
|
141
|
+
ch.onWarn?.("Passive reply failed; falling back to proactive.");
|
|
126
142
|
continue;
|
|
127
143
|
} catch (retryErr) {
|
|
128
|
-
|
|
144
|
+
log.error("outbound", "proactive retry failed", { targetId: ch.boundOpenid, err: retryErr });
|
|
145
|
+
ch.onWarn?.(`Proactive send failed: ${(retryErr as Error).message}`);
|
|
129
146
|
continue;
|
|
130
147
|
}
|
|
131
148
|
}
|
|
132
|
-
ch.onWarn?.(
|
|
149
|
+
ch.onWarn?.(`Send failed: ${(err as Error).message}`);
|
|
133
150
|
}
|
|
134
151
|
}
|
|
135
152
|
}
|
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();
|