@chen_hu_hu/pi-qq 1.3.1 → 1.3.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/CHANGELOG.md +68 -0
- package/README-zh.md +8 -7
- package/README.md +8 -7
- package/doc/archive/README.md +18 -0
- package/doc/{delivery-v1-zh.md → archive/delivery-v1-zh.md} +2 -1
- package/doc/{delivery-v1.md → archive/delivery-v1.md} +2 -1
- package/doc/{delivery-v2-zh.md → archive/delivery-v2-zh.md} +2 -1
- package/doc/{delivery-v2.md → archive/delivery-v2.md} +2 -1
- package/doc/{delivery-v3-zh.md → archive/delivery-v3-zh.md} +2 -1
- package/doc/{delivery-v3.md → archive/delivery-v3.md} +3 -2
- package/doc/bugfix-v4.md +698 -0
- package/index.ts +36 -25
- package/package.json +2 -1
- package/src/infra/file-logger.ts +21 -6
- package/src/qq/inbound-attachments.ts +101 -0
- package/src/qq/inbound-command.ts +99 -0
- package/src/qq/qq-message-handler.ts +48 -117
- package/src/qq/reply-sender.ts +23 -0
- package/src/relay/bubble-writer.ts +369 -0
- package/src/relay/run-stream-relay.ts +88 -339
package/index.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
|
|
|
9
9
|
import { ReplyBudget } from "./src/quota/reply-quota";
|
|
10
10
|
import { RunFeedback } from "./src/relay/run-stream-relay";
|
|
11
11
|
import { formatTokenCount } from "./src/infra/display-format";
|
|
12
|
-
import { configureLogger, log, previewForLog } from "./src/infra/file-logger";
|
|
12
|
+
import { configureLogger, flushLogs, isLogEnabled, log, previewForLog } from "./src/infra/file-logger";
|
|
13
13
|
import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
|
|
14
14
|
|
|
15
15
|
interface LoginState {
|
|
@@ -114,6 +114,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
114
114
|
getDeliverAs,
|
|
115
115
|
getFileMaxSize: () => activeSettings.fileMaxSize,
|
|
116
116
|
getStatusLines,
|
|
117
|
+
getLastMessage: () => runFeedback.getLastMessage(),
|
|
118
|
+
repushCurrent: (openid, msgId) => runFeedback.repushCurrent(openid, msgId),
|
|
117
119
|
onWarn: onWarn(ctx),
|
|
118
120
|
markQQTrigger: (openid, msgId) => runFeedback.markQQTrigger(openid, msgId),
|
|
119
121
|
waitForEnd: () => runFeedback.waitForEnd(),
|
|
@@ -149,9 +151,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
149
151
|
}
|
|
150
152
|
});
|
|
151
153
|
|
|
152
|
-
pi.on("session_shutdown", () => {
|
|
154
|
+
pi.on("session_shutdown", async () => {
|
|
153
155
|
log.info("session", "shutting down");
|
|
154
156
|
stopIfRunning();
|
|
157
|
+
await flushLogs();
|
|
155
158
|
});
|
|
156
159
|
|
|
157
160
|
pi.on("agent_start", () => {
|
|
@@ -165,21 +168,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
165
168
|
});
|
|
166
169
|
|
|
167
170
|
pi.on("tool_execution_start", (event) => {
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
171
|
+
if (isLogEnabled("debug")) {
|
|
172
|
+
log.debug("tool", "start", {
|
|
173
|
+
toolName: event.toolName,
|
|
174
|
+
toolCallId: event.toolCallId,
|
|
175
|
+
args: previewForLog(event.args),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
173
178
|
void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
|
|
174
179
|
});
|
|
175
180
|
|
|
176
181
|
pi.on("tool_execution_end", (event) => {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
182
|
+
if (isLogEnabled("debug")) {
|
|
183
|
+
log.debug("tool", "end", {
|
|
184
|
+
toolName: event.toolName,
|
|
185
|
+
toolCallId: event.toolCallId,
|
|
186
|
+
isError: event.isError,
|
|
187
|
+
result: previewForLog(event.result),
|
|
188
|
+
});
|
|
189
|
+
}
|
|
183
190
|
runFeedback.onToolEnd(event.toolName, event.isError, event.result, event.toolCallId);
|
|
184
191
|
});
|
|
185
192
|
|
|
@@ -202,17 +209,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
202
209
|
if (msg.role !== "assistant" || !running) return;
|
|
203
210
|
|
|
204
211
|
const fromQQ = runFeedback.isQQRunActive();
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
212
|
+
if (isLogEnabled("debug")) {
|
|
213
|
+
log.debug("pi", "assistant message ended", {
|
|
214
|
+
fromQQ,
|
|
215
|
+
stopReason: msg.stopReason,
|
|
216
|
+
contentTypes: msg.content.map((block) => block.type),
|
|
217
|
+
textPreview: previewForLog(
|
|
218
|
+
msg.content
|
|
219
|
+
.filter((block) => block.type === "text")
|
|
220
|
+
.map((block) => block.text)
|
|
221
|
+
.join("\n"),
|
|
222
|
+
),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
216
225
|
if (!fromQQ) return;
|
|
217
226
|
|
|
218
227
|
const isError = msg.stopReason === "error";
|
|
@@ -234,7 +243,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
234
243
|
}
|
|
235
244
|
|
|
236
245
|
const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
|
|
237
|
-
|
|
246
|
+
if (isLogEnabled("debug")) {
|
|
247
|
+
log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
|
|
248
|
+
}
|
|
238
249
|
if (streamTookOver) return;
|
|
239
250
|
|
|
240
251
|
const payload = markdownToPlain(text);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chen_hu_hu/pi-qq",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.3",
|
|
4
4
|
"description": "Connect pi to QQ private chats.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "CQ-Developer",
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"index.ts",
|
|
38
38
|
"src",
|
|
39
39
|
"doc",
|
|
40
|
+
"CHANGELOG.md",
|
|
40
41
|
"README.md",
|
|
41
42
|
"README-zh.md",
|
|
42
43
|
"LICENSE"
|
package/src/infra/file-logger.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
|
|
4
4
|
export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
@@ -16,6 +16,7 @@ const DEFAULT_LOG_LEVEL: LogLevel = "silent";
|
|
|
16
16
|
|
|
17
17
|
let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
|
|
18
18
|
let activeDir: string | undefined;
|
|
19
|
+
let writeQueue: Promise<void> = Promise.resolve();
|
|
19
20
|
|
|
20
21
|
function isLogLevel(value: unknown): value is LogLevel {
|
|
21
22
|
return typeof value === "string" && Object.hasOwn(LEVEL_WEIGHT, value);
|
|
@@ -29,6 +30,15 @@ export function isLevelEnabled(configured: LogLevel, level: Exclude<LogLevel, "s
|
|
|
29
30
|
return configured !== "silent" && LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[configured];
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
export function isLogEnabled(level: Exclude<LogLevel, "silent">): boolean {
|
|
34
|
+
return isLevelEnabled(activeLevel, level);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Resolve once every queued log record has been written (or dropped). */
|
|
38
|
+
export async function flushLogs(): Promise<void> {
|
|
39
|
+
await writeQueue;
|
|
40
|
+
}
|
|
41
|
+
|
|
32
42
|
export function configureLogger(level: LogLevel, dir?: string): void {
|
|
33
43
|
activeLevel = normalizeLogLevel(level);
|
|
34
44
|
activeDir = dir;
|
|
@@ -100,11 +110,16 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
|
|
|
100
110
|
});
|
|
101
111
|
}
|
|
102
112
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
113
|
+
const dir = resolveLogDir();
|
|
114
|
+
const path = join(dir, logFileName());
|
|
115
|
+
writeQueue = writeQueue
|
|
116
|
+
.then(async () => {
|
|
117
|
+
try {
|
|
118
|
+
await mkdir(dir, { recursive: true });
|
|
119
|
+
await appendFile(path, `${line}\n`, "utf8");
|
|
120
|
+
} catch {}
|
|
121
|
+
})
|
|
122
|
+
.catch(() => {});
|
|
108
123
|
}
|
|
109
124
|
|
|
110
125
|
export const log = {
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
2
|
+
import type { AttachmentFailure } from "../attachments/attachment-failure";
|
|
3
|
+
import { saveInboundFiles, type SavedFile } from "../attachments/file-attachments";
|
|
4
|
+
import { log } from "../infra/file-logger";
|
|
5
|
+
import { isVoiceAttachment, resolveVoiceTranscript } from "../attachments/voice-transcript";
|
|
6
|
+
|
|
7
|
+
export interface ResolveInboundOptions {
|
|
8
|
+
contentText: string;
|
|
9
|
+
maxSize: number;
|
|
10
|
+
uploadDir: string;
|
|
11
|
+
saveFiles: typeof saveInboundFiles;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type ResolvedInbound =
|
|
15
|
+
| { status: "rejected"; reply: string }
|
|
16
|
+
| {
|
|
17
|
+
status: "resolved";
|
|
18
|
+
text: string;
|
|
19
|
+
files: SavedFile[];
|
|
20
|
+
failures: AttachmentFailure[];
|
|
21
|
+
voiceCount: number;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Turn one inbound message into injectable content: prefer ASR for voice,
|
|
26
|
+
* persist every non-voice attachment, and report per-file failures.
|
|
27
|
+
*/
|
|
28
|
+
export async function resolveInboundContent(
|
|
29
|
+
msg: QQBotInboundMessage,
|
|
30
|
+
options: ResolveInboundOptions,
|
|
31
|
+
): Promise<ResolvedInbound> {
|
|
32
|
+
const attachments = msg.attachments ?? [];
|
|
33
|
+
let text = options.contentText;
|
|
34
|
+
|
|
35
|
+
const voiceAttachments = attachments.filter(isVoiceAttachment);
|
|
36
|
+
if (voiceAttachments.length > 0) {
|
|
37
|
+
const transcript = resolveVoiceTranscript(voiceAttachments);
|
|
38
|
+
log.info("inbound", "voice message", {
|
|
39
|
+
messageId: msg.messageId,
|
|
40
|
+
hasAsr: Boolean(transcript),
|
|
41
|
+
asrLength: transcript?.length ?? 0,
|
|
42
|
+
});
|
|
43
|
+
if (!transcript) {
|
|
44
|
+
if (!options.contentText) {
|
|
45
|
+
log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
|
|
46
|
+
return {
|
|
47
|
+
status: "rejected",
|
|
48
|
+
reply: "Could not transcribe this voice message; please resend or type it.",
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
log.warn("inbound", "voice ASR returned no text; using text content", { messageId: msg.messageId });
|
|
52
|
+
} else {
|
|
53
|
+
log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
|
|
54
|
+
text = options.contentText ? `${options.contentText}\n${transcript}` : transcript;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Voice attachments are handled above; all other attachments are stored as files.
|
|
59
|
+
const attachmentsToSave = attachments.filter((attachment) => !isVoiceAttachment(attachment));
|
|
60
|
+
const failures: AttachmentFailure[] = [];
|
|
61
|
+
let files: SavedFile[] = [];
|
|
62
|
+
|
|
63
|
+
if (attachmentsToSave.length > 0) {
|
|
64
|
+
log.debug("inbound", "saving attachments", {
|
|
65
|
+
messageId: msg.messageId,
|
|
66
|
+
count: attachmentsToSave.length,
|
|
67
|
+
uploadDir: options.uploadDir,
|
|
68
|
+
});
|
|
69
|
+
const result = await options.saveFiles(attachmentsToSave, {
|
|
70
|
+
maxSize: options.maxSize,
|
|
71
|
+
uploadDir: options.uploadDir,
|
|
72
|
+
});
|
|
73
|
+
files = result.files;
|
|
74
|
+
failures.push(...result.failures);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return { status: "resolved", text, files, failures, voiceCount: voiceAttachments.length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Attachments that arrived without an instruction, consumed by the next text or voice message. */
|
|
81
|
+
export class PendingAttachments {
|
|
82
|
+
private files: SavedFile[] = [];
|
|
83
|
+
|
|
84
|
+
get count(): number {
|
|
85
|
+
return this.files.length;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
add(files: SavedFile[]): void {
|
|
89
|
+
if (files.length > 0) this.files.push(...files);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
take(): SavedFile[] {
|
|
93
|
+
const files = this.files;
|
|
94
|
+
this.files = [];
|
|
95
|
+
return files;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
clear(): void {
|
|
99
|
+
this.files = [];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
|
|
3
|
+
/** The slice of ExtensionContext used by QQ inbound handling. */
|
|
4
|
+
export interface InboundContext {
|
|
5
|
+
readonly cwd: string;
|
|
6
|
+
isIdle(): boolean;
|
|
7
|
+
abort(): void;
|
|
8
|
+
compact(): void;
|
|
9
|
+
sessionManager: { getSessionId(): string };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type InboundPi = Pick<ExtensionAPI, "sendUserMessage">;
|
|
13
|
+
|
|
14
|
+
export interface InboundCommandDeps {
|
|
15
|
+
pi: InboundPi;
|
|
16
|
+
ctx: InboundContext;
|
|
17
|
+
getStatusLines: () => string[];
|
|
18
|
+
getLastMessage?: () => string | undefined;
|
|
19
|
+
onStop?: () => void;
|
|
20
|
+
waitForEnd?: () => Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface InboundCommandExtras {
|
|
24
|
+
streamReply?: (text: string) => Promise<void>;
|
|
25
|
+
restartPush?: () => void;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function handleInboundCommand(
|
|
29
|
+
text: string,
|
|
30
|
+
reply: (t: string) => Promise<void>,
|
|
31
|
+
deps: InboundCommandDeps,
|
|
32
|
+
extras: InboundCommandExtras = {},
|
|
33
|
+
): Promise<void> {
|
|
34
|
+
const cmd = text.split(/\s+/)[0];
|
|
35
|
+
switch (cmd) {
|
|
36
|
+
case "/help":
|
|
37
|
+
await reply(
|
|
38
|
+
[
|
|
39
|
+
"pi-qq commands:",
|
|
40
|
+
"• /stop — abort the current task",
|
|
41
|
+
"• /compact — compact the context",
|
|
42
|
+
"• /status — show status",
|
|
43
|
+
"• /last — push the last completed message or restart current output",
|
|
44
|
+
"• /new — reset the session",
|
|
45
|
+
"• /help — this help",
|
|
46
|
+
"Other text is sent to pi.",
|
|
47
|
+
].join("\n"),
|
|
48
|
+
);
|
|
49
|
+
break;
|
|
50
|
+
case "/stop":
|
|
51
|
+
deps.onStop?.();
|
|
52
|
+
if (deps.ctx.isIdle()) {
|
|
53
|
+
await reply("No task is running.");
|
|
54
|
+
} else {
|
|
55
|
+
deps.ctx.abort();
|
|
56
|
+
await deps.waitForEnd?.();
|
|
57
|
+
await reply("Abort requested.");
|
|
58
|
+
}
|
|
59
|
+
break;
|
|
60
|
+
case "/compact":
|
|
61
|
+
if (deps.ctx.isIdle()) {
|
|
62
|
+
deps.ctx.compact();
|
|
63
|
+
await reply("Context compaction triggered.");
|
|
64
|
+
} else {
|
|
65
|
+
await reply("Task is running; use /stop before /compact.");
|
|
66
|
+
}
|
|
67
|
+
break;
|
|
68
|
+
case "/status":
|
|
69
|
+
await reply(deps.getStatusLines().join("\n"));
|
|
70
|
+
break;
|
|
71
|
+
case "/last": {
|
|
72
|
+
if (!deps.ctx.isIdle()) {
|
|
73
|
+
extras.restartPush?.();
|
|
74
|
+
} else {
|
|
75
|
+
const text = deps.getLastMessage?.();
|
|
76
|
+
if (text) {
|
|
77
|
+
if (extras.streamReply) {
|
|
78
|
+
await extras.streamReply(text);
|
|
79
|
+
} else {
|
|
80
|
+
await reply(text);
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
await reply("No completed message yet.");
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
case "/new":
|
|
89
|
+
if (!deps.ctx.isIdle()) {
|
|
90
|
+
await reply("Task is running; use /stop before resetting.");
|
|
91
|
+
} else {
|
|
92
|
+
await reply("Resetting the session…");
|
|
93
|
+
deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
|
|
94
|
+
}
|
|
95
|
+
break;
|
|
96
|
+
default:
|
|
97
|
+
await reply(`Unknown command ${cmd}; use /help.`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
1
|
import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
3
|
-
import { sendReply, type ReplyChannel } from "./reply-sender";
|
|
2
|
+
import { sendReply, sendStreamReply, type ReplyChannel } from "./reply-sender";
|
|
4
3
|
import type { ReplyBudget } from "../quota/reply-quota";
|
|
5
|
-
import { formatAttachmentFailures
|
|
4
|
+
import { formatAttachmentFailures } from "../attachments/attachment-failure";
|
|
6
5
|
import {
|
|
7
6
|
formatAttachmentPrompt,
|
|
8
7
|
saveInboundFiles,
|
|
@@ -10,30 +9,23 @@ import {
|
|
|
10
9
|
type SavedFile,
|
|
11
10
|
} from "../attachments/file-attachments";
|
|
12
11
|
import { log } from "../infra/file-logger";
|
|
13
|
-
import {
|
|
12
|
+
import { handleInboundCommand, type InboundCommandDeps } from "./inbound-command";
|
|
13
|
+
import { PendingAttachments, resolveInboundContent } from "./inbound-attachments";
|
|
14
14
|
|
|
15
|
-
export interface InboundDeps {
|
|
16
|
-
pi: ExtensionAPI;
|
|
17
|
-
ctx: ExtensionContext;
|
|
15
|
+
export interface InboundDeps extends InboundCommandDeps {
|
|
18
16
|
budget: ReplyBudget;
|
|
19
17
|
getAllowedOpenid: () => string | undefined;
|
|
20
18
|
getDeliverAs: () => "steer" | "followUp";
|
|
21
19
|
getFileMaxSize: () => number;
|
|
22
20
|
saveFiles?: typeof saveInboundFiles;
|
|
23
|
-
|
|
21
|
+
streamReply?: typeof sendStreamReply;
|
|
22
|
+
repushCurrent: (openid: string, msgId: string) => boolean;
|
|
24
23
|
onWarn: (msg: string) => void;
|
|
25
24
|
markQQTrigger: (openid: string, msgId: string) => void;
|
|
26
|
-
waitForEnd?: () => Promise<void>;
|
|
27
|
-
onStop?: () => void;
|
|
28
25
|
}
|
|
29
26
|
|
|
30
27
|
export function createInboundHandler(deps: InboundDeps) {
|
|
31
|
-
|
|
32
|
-
const takePendingAttachments = (): SavedFile[] => {
|
|
33
|
-
const attachments = pendingAttachments;
|
|
34
|
-
pendingAttachments = [];
|
|
35
|
-
return attachments;
|
|
36
|
-
};
|
|
28
|
+
const pending = new PendingAttachments();
|
|
37
29
|
|
|
38
30
|
return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
|
|
39
31
|
log.debug("inbound", "message received", {
|
|
@@ -79,17 +71,36 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
79
71
|
onWarn: deps.onWarn,
|
|
80
72
|
};
|
|
81
73
|
const reply = (text: string) => sendReply(bot, text, channel);
|
|
82
|
-
const saveFiles = deps.saveFiles ?? saveInboundFiles;
|
|
83
74
|
|
|
84
75
|
const contentText = (msg.content ?? "").trim();
|
|
85
76
|
if (contentText.startsWith("/")) {
|
|
86
77
|
const command = contentText.split(/\s+/)[0];
|
|
87
78
|
log.info("inbound", "QQ command", { command });
|
|
88
|
-
if (command === "/new" && deps.ctx.isIdle() &&
|
|
89
|
-
log.info("inbound", "cleared pending attachments for /new", { count:
|
|
90
|
-
|
|
79
|
+
if (command === "/new" && deps.ctx.isIdle() && pending.count > 0) {
|
|
80
|
+
log.info("inbound", "cleared pending attachments for /new", { count: pending.count });
|
|
81
|
+
pending.clear();
|
|
91
82
|
}
|
|
92
|
-
await
|
|
83
|
+
await handleInboundCommand(contentText, reply, deps, {
|
|
84
|
+
streamReply: async (text) => {
|
|
85
|
+
try {
|
|
86
|
+
await (deps.streamReply ?? sendStreamReply)(
|
|
87
|
+
bot,
|
|
88
|
+
text,
|
|
89
|
+
{ openid: msg.senderId, msgId: msg.messageId },
|
|
90
|
+
deps.budget,
|
|
91
|
+
);
|
|
92
|
+
} catch (err) {
|
|
93
|
+
log.warn("inbound", "stream reply failed; falling back to text", {
|
|
94
|
+
messageId: msg.messageId,
|
|
95
|
+
err,
|
|
96
|
+
});
|
|
97
|
+
await reply(text);
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
restartPush: () => {
|
|
101
|
+
deps.repushCurrent(msg.senderId, msg.messageId);
|
|
102
|
+
},
|
|
103
|
+
});
|
|
93
104
|
return;
|
|
94
105
|
}
|
|
95
106
|
|
|
@@ -100,47 +111,17 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
100
111
|
return;
|
|
101
112
|
}
|
|
102
113
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
if (!transcript) {
|
|
113
|
-
if (!contentText) {
|
|
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.warn("inbound", "voice ASR returned no text; using text content", { messageId: msg.messageId });
|
|
119
|
-
} else {
|
|
120
|
-
log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
|
|
121
|
-
text = contentText ? `${contentText}\n${transcript}` : transcript;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// Voice attachments are handled above; all other attachments are stored as files.
|
|
126
|
-
const attachmentsToSave = attachments.filter((attachment) => !isVoiceAttachment(attachment));
|
|
127
|
-
const failures: AttachmentFailure[] = [];
|
|
128
|
-
|
|
129
|
-
let files: SavedFile[] = [];
|
|
130
|
-
if (attachmentsToSave.length > 0) {
|
|
131
|
-
const uploadDir = sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId());
|
|
132
|
-
log.debug("inbound", "saving attachments", {
|
|
133
|
-
messageId: msg.messageId,
|
|
134
|
-
count: attachmentsToSave.length,
|
|
135
|
-
uploadDir,
|
|
136
|
-
});
|
|
137
|
-
const result = await saveFiles(attachmentsToSave, {
|
|
138
|
-
maxSize: deps.getFileMaxSize(),
|
|
139
|
-
uploadDir,
|
|
140
|
-
});
|
|
141
|
-
files = result.files;
|
|
142
|
-
failures.push(...result.failures);
|
|
114
|
+
const resolved = await resolveInboundContent(msg, {
|
|
115
|
+
contentText,
|
|
116
|
+
maxSize: deps.getFileMaxSize(),
|
|
117
|
+
uploadDir: sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId()),
|
|
118
|
+
saveFiles: deps.saveFiles ?? saveInboundFiles,
|
|
119
|
+
});
|
|
120
|
+
if (resolved.status === "rejected") {
|
|
121
|
+
await reply(resolved.reply);
|
|
122
|
+
return;
|
|
143
123
|
}
|
|
124
|
+
const { text, files, failures, voiceCount } = resolved;
|
|
144
125
|
|
|
145
126
|
if (failures.length > 0) {
|
|
146
127
|
log.warn("inbound", "attachment failure summary", {
|
|
@@ -159,77 +140,27 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
159
140
|
}
|
|
160
141
|
|
|
161
142
|
if (!text && files.length > 0) {
|
|
162
|
-
|
|
143
|
+
pending.add(files);
|
|
163
144
|
log.info("inbound", "attachments pending for instruction", {
|
|
164
145
|
messageId: msg.messageId,
|
|
165
146
|
count: files.length,
|
|
166
|
-
pendingCount:
|
|
147
|
+
pendingCount: pending.count,
|
|
167
148
|
});
|
|
168
149
|
return;
|
|
169
150
|
}
|
|
170
151
|
|
|
171
152
|
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
172
|
-
const
|
|
173
|
-
const promptFiles = [...
|
|
153
|
+
const pendingFiles = text ? pending.take() : [];
|
|
154
|
+
const promptFiles: SavedFile[] = [...pendingFiles, ...files];
|
|
174
155
|
const promptText = formatAttachmentPrompt(promptFiles, text, deps.ctx.cwd);
|
|
175
156
|
deps.pi.sendUserMessage(promptText, { deliverAs: deps.getDeliverAs() });
|
|
176
157
|
log.info("inbound", "sent to pi", {
|
|
177
158
|
messageId: msg.messageId,
|
|
178
159
|
textLength: text.length,
|
|
179
|
-
voice:
|
|
160
|
+
voice: voiceCount > 0,
|
|
180
161
|
attachments: promptFiles.length,
|
|
181
|
-
pendingAttachments:
|
|
162
|
+
pendingAttachments: pendingFiles.length,
|
|
182
163
|
deliverAs: deps.getDeliverAs(),
|
|
183
164
|
});
|
|
184
165
|
};
|
|
185
166
|
}
|
|
186
|
-
|
|
187
|
-
async function handleCommand(text: string, reply: (t: string) => Promise<void>, deps: InboundDeps): Promise<void> {
|
|
188
|
-
const cmd = text.split(/\s+/)[0];
|
|
189
|
-
switch (cmd) {
|
|
190
|
-
case "/help":
|
|
191
|
-
await reply(
|
|
192
|
-
[
|
|
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.",
|
|
200
|
-
].join("\n"),
|
|
201
|
-
);
|
|
202
|
-
break;
|
|
203
|
-
case "/stop":
|
|
204
|
-
deps.onStop?.();
|
|
205
|
-
if (deps.ctx.isIdle()) {
|
|
206
|
-
await reply("No task is running.");
|
|
207
|
-
} else {
|
|
208
|
-
deps.ctx.abort();
|
|
209
|
-
await deps.waitForEnd?.();
|
|
210
|
-
await reply("Abort requested.");
|
|
211
|
-
}
|
|
212
|
-
break;
|
|
213
|
-
case "/compact":
|
|
214
|
-
if (deps.ctx.isIdle()) {
|
|
215
|
-
deps.ctx.compact();
|
|
216
|
-
await reply("Context compaction triggered.");
|
|
217
|
-
} else {
|
|
218
|
-
await reply("Task is running; use /stop before /compact.");
|
|
219
|
-
}
|
|
220
|
-
break;
|
|
221
|
-
case "/status":
|
|
222
|
-
await reply(deps.getStatusLines().join("\n"));
|
|
223
|
-
break;
|
|
224
|
-
case "/new":
|
|
225
|
-
if (!deps.ctx.isIdle()) {
|
|
226
|
-
await reply("Task is running; use /stop before resetting.");
|
|
227
|
-
} else {
|
|
228
|
-
await reply("Resetting the session…");
|
|
229
|
-
deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
|
|
230
|
-
}
|
|
231
|
-
break;
|
|
232
|
-
default:
|
|
233
|
-
await reply(`Unknown command ${cmd}; use /help.`);
|
|
234
|
-
}
|
|
235
|
-
}
|
package/src/qq/reply-sender.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
2
2
|
import { ReplyBudget } from "../quota/reply-quota";
|
|
3
|
+
import { AppendStream } from "../relay/stream-session";
|
|
3
4
|
import { log } from "../infra/file-logger";
|
|
4
5
|
|
|
5
6
|
export const TEXT_CHUNK_LIMIT = 4500;
|
|
@@ -80,6 +81,28 @@ export interface ReplyChannel {
|
|
|
80
81
|
onWarn?: (msg: string) => void;
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
export interface StreamTarget {
|
|
85
|
+
openid: string;
|
|
86
|
+
msgId: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Send a complete message as one new stream bubble. */
|
|
90
|
+
export async function sendStreamReply(
|
|
91
|
+
bot: QQBot,
|
|
92
|
+
text: string,
|
|
93
|
+
target: StreamTarget,
|
|
94
|
+
budget?: ReplyBudget,
|
|
95
|
+
): Promise<void> {
|
|
96
|
+
const stream = new AppendStream(bot.messageApi, bot.getCredentials(), target.openid, target.msgId);
|
|
97
|
+
budget?.noteStreamBubble(target.msgId);
|
|
98
|
+
try {
|
|
99
|
+
await stream.append(text);
|
|
100
|
+
await stream.done();
|
|
101
|
+
} finally {
|
|
102
|
+
stream.dispose();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
83
106
|
export async function sendReply(bot: QQBot, text: string, ch: ReplyChannel): Promise<void> {
|
|
84
107
|
for (const chunk of chunkText(text)) {
|
|
85
108
|
const { mode, openid, msgId } = ch.budget.acquire();
|