@chen_hu_hu/pi-qq 1.0.2 → 1.2.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 +49 -36
- package/doc/features-v1.md +51 -51
- package/doc/features-v2.md +209 -0
- package/doc/plan-v1.md +20 -20
- package/doc/plan-v2.md +331 -0
- package/index.ts +64 -10
- package/package.json +1 -1
- package/src/append-stream.ts +1 -1
- package/src/bot.ts +46 -6
- package/src/config.ts +7 -3
- package/src/download.ts +8 -8
- package/src/files.ts +166 -43
- package/src/images.ts +19 -7
- package/src/inbound.ts +138 -24
- package/src/logger.ts +180 -0
- package/src/outbound.ts +20 -3
- package/src/run-feedback.ts +24 -36
- package/src/voice.ts +25 -0
package/src/download.ts
CHANGED
|
@@ -21,7 +21,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
21
21
|
if (!response.body) {
|
|
22
22
|
const body = Buffer.from(await response.arrayBuffer());
|
|
23
23
|
if (body.byteLength > limit) {
|
|
24
|
-
throw new Error(`${kind}
|
|
24
|
+
throw new Error(`${kind} too large (${formatBytes(body.byteLength)} > ${formatBytes(limit)})`);
|
|
25
25
|
}
|
|
26
26
|
return body;
|
|
27
27
|
}
|
|
@@ -37,14 +37,14 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
37
37
|
total += value.byteLength;
|
|
38
38
|
if (total > limit) {
|
|
39
39
|
await reader.cancel();
|
|
40
|
-
throw new Error(`${kind}
|
|
40
|
+
throw new Error(`${kind} too large (>${formatBytes(limit)})`);
|
|
41
41
|
}
|
|
42
42
|
chunks.push(value);
|
|
43
43
|
}
|
|
44
44
|
} finally {
|
|
45
45
|
reader.releaseLock();
|
|
46
46
|
}
|
|
47
|
-
if (total === 0) throw new Error(
|
|
47
|
+
if (total === 0) throw new Error(`empty ${kind} content`);
|
|
48
48
|
return Buffer.concat(chunks, total);
|
|
49
49
|
}
|
|
50
50
|
|
|
@@ -55,10 +55,10 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
|
55
55
|
try {
|
|
56
56
|
parsed = new URL(opts.url);
|
|
57
57
|
} catch {
|
|
58
|
-
throw new Error(
|
|
58
|
+
throw new Error(`invalid ${opts.kind} URL`);
|
|
59
59
|
}
|
|
60
60
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
61
|
-
throw new Error(
|
|
61
|
+
throw new Error(`unsupported ${opts.kind} URL protocol`);
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
const controller = new AbortController();
|
|
@@ -67,19 +67,19 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
|
67
67
|
try {
|
|
68
68
|
const response = await fetchImpl(parsed.toString(), { signal: controller.signal, redirect: "follow" });
|
|
69
69
|
if (!response.ok) {
|
|
70
|
-
throw new Error(
|
|
70
|
+
throw new Error(`download failed (HTTP ${response.status})`);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
const lengthHeader = response.headers.get("content-length");
|
|
74
74
|
const contentLength = lengthHeader ? Number(lengthHeader) : NaN;
|
|
75
75
|
if (Number.isFinite(contentLength) && contentLength > limit) {
|
|
76
76
|
await response.body?.cancel();
|
|
77
|
-
throw new Error(`${opts.kind}
|
|
77
|
+
throw new Error(`${opts.kind} too large (${formatBytes(contentLength)} > ${formatBytes(limit)})`);
|
|
78
78
|
}
|
|
79
79
|
return await readBodyLimited(response, limit, opts.kind);
|
|
80
80
|
} catch (err) {
|
|
81
81
|
if (controller.signal.aborted) {
|
|
82
|
-
throw new Error(
|
|
82
|
+
throw new Error(`download timed out after ${opts.timeoutMs / 1000}s`);
|
|
83
83
|
}
|
|
84
84
|
throw err;
|
|
85
85
|
} finally {
|
package/src/files.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
/** Save QQ non-image attachments in the workspace
|
|
2
|
-
import {
|
|
1
|
+
/** Save QQ non-image attachments in the workspace, with session-scoped deduplication. */
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
3
4
|
import { basename, extname, join } from "node:path";
|
|
4
5
|
import { downloadLimited, type InboundAttachmentLike } from "./download";
|
|
5
6
|
import { formatBytes } from "./format";
|
|
7
|
+
import { log } from "./logger";
|
|
6
8
|
|
|
7
9
|
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
8
|
-
const
|
|
10
|
+
const UPLOAD_INDEX_FILENAME = ".index.json";
|
|
9
11
|
|
|
10
12
|
export interface SavedFile {
|
|
11
13
|
path: string;
|
|
@@ -18,13 +20,15 @@ export interface FileFailure {
|
|
|
18
20
|
reason: string;
|
|
19
21
|
}
|
|
20
22
|
|
|
23
|
+
/** fileName -> SHA-256. Paths are derived from uploadDir. */
|
|
24
|
+
export type UploadIndex = Record<string, string>;
|
|
25
|
+
|
|
21
26
|
export interface SaveFilesOptions {
|
|
22
27
|
maxSize: number;
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
|
|
27
|
-
now?: Date;
|
|
28
|
+
/** `<cwd>/.pi/pi-qq/<sessionId>/uploads`. */
|
|
29
|
+
uploadDir: string;
|
|
30
|
+
/** Test/caller override; loaded from uploadDir when omitted. Mutated in place. */
|
|
31
|
+
index?: UploadIndex;
|
|
28
32
|
fetchImpl?: typeof fetch;
|
|
29
33
|
}
|
|
30
34
|
|
|
@@ -33,18 +37,18 @@ export interface SaveFilesResult {
|
|
|
33
37
|
failures: FileFailure[];
|
|
34
38
|
}
|
|
35
39
|
|
|
36
|
-
function
|
|
37
|
-
|
|
40
|
+
function safePathSegment(key: string): string {
|
|
41
|
+
const cleaned = key.replace(/[^A-Za-z0-9._-]/g, "_").replace(/^[._]+|[._]+$/g, "");
|
|
42
|
+
return cleaned.slice(0, 64) || "session";
|
|
38
43
|
}
|
|
39
44
|
|
|
40
|
-
|
|
41
|
-
|
|
45
|
+
/** Session-scoped upload directory; no date or msgId subdirectories. */
|
|
46
|
+
export function sessionUploadDir(cwd: string, sessionId: string): string {
|
|
47
|
+
return join(cwd, ".pi", "pi-qq", safePathSegment(sessionId), "uploads");
|
|
42
48
|
}
|
|
43
49
|
|
|
44
|
-
function
|
|
45
|
-
|
|
46
|
-
const stem = filename.slice(0, filename.length - ext.length);
|
|
47
|
-
return `${stem}-${suffix}${ext}`;
|
|
50
|
+
export function uploadIndexPath(uploadDir: string): string {
|
|
51
|
+
return join(uploadDir, UPLOAD_INDEX_FILENAME);
|
|
48
52
|
}
|
|
49
53
|
|
|
50
54
|
/** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
|
|
@@ -62,23 +66,135 @@ export function sanitizeFilename(filename: string | undefined, fallback: string)
|
|
|
62
66
|
return `${stem.slice(0, maxStemLength)}${ext}`;
|
|
63
67
|
}
|
|
64
68
|
|
|
65
|
-
function
|
|
66
|
-
const
|
|
67
|
-
|
|
69
|
+
function withSuffix(filename: string, suffix: number): string {
|
|
70
|
+
const ext = extname(filename);
|
|
71
|
+
const stem = filename.slice(0, filename.length - ext.length);
|
|
72
|
+
return `${stem}-${suffix}${ext}`;
|
|
68
73
|
}
|
|
69
74
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
75
|
+
function isSafeIndexKey(filename: string): boolean {
|
|
76
|
+
return (
|
|
77
|
+
filename.length > 0 &&
|
|
78
|
+
filename !== "." &&
|
|
79
|
+
filename !== ".." &&
|
|
80
|
+
filename !== UPLOAD_INDEX_FILENAME &&
|
|
81
|
+
basename(filename) === filename
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function sha256Hex(body: Buffer): string {
|
|
86
|
+
return createHash("sha256").update(body).digest("hex");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function isFile(path: string): Promise<boolean> {
|
|
90
|
+
try {
|
|
91
|
+
return (await stat(path)).isFile();
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function loadUploadIndex(uploadDir: string): Promise<UploadIndex> {
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(await readFile(uploadIndexPath(uploadDir), "utf8")) as unknown;
|
|
100
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
101
|
+
const index: UploadIndex = {};
|
|
102
|
+
for (const [filename, hash] of Object.entries(parsed as Record<string, unknown>)) {
|
|
103
|
+
if (isSafeIndexKey(filename) && typeof hash === "string") index[filename] = hash;
|
|
79
104
|
}
|
|
105
|
+
return index;
|
|
106
|
+
} catch {
|
|
107
|
+
return {};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function persistUploadIndex(uploadDir: string, index: UploadIndex): Promise<void> {
|
|
112
|
+
const path = uploadIndexPath(uploadDir);
|
|
113
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
114
|
+
try {
|
|
115
|
+
await mkdir(uploadDir, { recursive: true });
|
|
116
|
+
await writeFile(tmp, `${JSON.stringify(index, null, 2)}\n`, "utf8");
|
|
117
|
+
await rename(tmp, path);
|
|
118
|
+
} catch (err) {
|
|
119
|
+
log.warn("files", "failed to write upload index", { path, err });
|
|
80
120
|
}
|
|
81
|
-
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Load the index and drop entries whose files no longer exist. No content hashing. */
|
|
124
|
+
export async function pruneUploadIndex(uploadDir: string): Promise<UploadIndex> {
|
|
125
|
+
const index = await loadUploadIndex(uploadDir);
|
|
126
|
+
let changed = false;
|
|
127
|
+
for (const filename of Object.keys(index)) {
|
|
128
|
+
if (!(await isFile(join(uploadDir, filename)))) {
|
|
129
|
+
delete index[filename];
|
|
130
|
+
changed = true;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (changed) await persistUploadIndex(uploadDir, index);
|
|
134
|
+
return index;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function hashExistingFile(path: string): Promise<string> {
|
|
138
|
+
return sha256Hex(await readFile(path));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function saveOrReuse(
|
|
142
|
+
uploadDir: string,
|
|
143
|
+
filename: string,
|
|
144
|
+
body: Buffer,
|
|
145
|
+
index: UploadIndex,
|
|
146
|
+
): Promise<{ file: SavedFile; changed: boolean }> {
|
|
147
|
+
const hash = sha256Hex(body);
|
|
148
|
+
const target = join(uploadDir, filename);
|
|
149
|
+
let changed = false;
|
|
150
|
+
|
|
151
|
+
if (!(await isFile(target))) {
|
|
152
|
+
// A stale index entry must not make a missing file look reusable.
|
|
153
|
+
if (index[filename]) {
|
|
154
|
+
delete index[filename];
|
|
155
|
+
changed = true;
|
|
156
|
+
}
|
|
157
|
+
await writeFile(target, body, { flag: "wx" });
|
|
158
|
+
index[filename] = hash;
|
|
159
|
+
return { file: { path: target, originalName: filename, size: body.byteLength }, changed: true };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
let existingHash = index[filename];
|
|
163
|
+
if (!existingHash) {
|
|
164
|
+
existingHash = await hashExistingFile(target);
|
|
165
|
+
index[filename] = existingHash;
|
|
166
|
+
changed = true;
|
|
167
|
+
}
|
|
168
|
+
if (existingHash === hash) {
|
|
169
|
+
return { file: { path: target, originalName: filename, size: body.byteLength }, changed };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
for (let suffix = 1; suffix < 100; suffix++) {
|
|
173
|
+
const candidate = withSuffix(filename, suffix);
|
|
174
|
+
const candidatePath = join(uploadDir, candidate);
|
|
175
|
+
if (await isFile(candidatePath)) {
|
|
176
|
+
let candidateHash = index[candidate];
|
|
177
|
+
if (!candidateHash) {
|
|
178
|
+
candidateHash = await hashExistingFile(candidatePath);
|
|
179
|
+
index[candidate] = candidateHash;
|
|
180
|
+
changed = true;
|
|
181
|
+
}
|
|
182
|
+
if (candidateHash === hash) {
|
|
183
|
+
return { file: { path: candidatePath, originalName: candidate, size: body.byteLength }, changed };
|
|
184
|
+
}
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (index[candidate]) {
|
|
189
|
+
delete index[candidate];
|
|
190
|
+
changed = true;
|
|
191
|
+
}
|
|
192
|
+
await writeFile(candidatePath, body, { flag: "wx" });
|
|
193
|
+
index[candidate] = hash;
|
|
194
|
+
return { file: { path: candidatePath, originalName: candidate, size: body.byteLength }, changed: true };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
throw new Error("Could not allocate a unique filename");
|
|
82
198
|
}
|
|
83
199
|
|
|
84
200
|
/** Save non-image attachments in order; one failure does not stop the others. */
|
|
@@ -86,23 +202,28 @@ export async function saveInboundFiles(
|
|
|
86
202
|
attachments: readonly InboundAttachmentLike[],
|
|
87
203
|
options: SaveFilesOptions,
|
|
88
204
|
): Promise<SaveFilesResult> {
|
|
89
|
-
const
|
|
90
|
-
const baseDir = options.baseDir ?? DEFAULT_BASE_DIR;
|
|
91
|
-
const dir = options.dirKey
|
|
92
|
-
? join(baseDir, dateStamp(now), safeDirKey(options.dirKey))
|
|
93
|
-
: join(baseDir, dateStamp(now));
|
|
205
|
+
const uploadDir = options.uploadDir;
|
|
94
206
|
const limit = Math.max(1, options.maxSize);
|
|
95
207
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
96
|
-
|
|
208
|
+
const index = options.index ?? (await loadUploadIndex(uploadDir));
|
|
97
209
|
const files: SavedFile[] = [];
|
|
98
210
|
const failures: FileFailure[] = [];
|
|
99
|
-
|
|
211
|
+
const seenPaths = new Set<string>();
|
|
212
|
+
let indexChanged = false;
|
|
213
|
+
|
|
214
|
+
if (attachments.length > 0) await mkdir(uploadDir, { recursive: true });
|
|
215
|
+
|
|
216
|
+
const addFile = (file: SavedFile) => {
|
|
217
|
+
if (seenPaths.has(file.path)) return;
|
|
218
|
+
seenPaths.add(file.path);
|
|
219
|
+
files.push(file);
|
|
220
|
+
};
|
|
100
221
|
|
|
101
|
-
for (const [
|
|
102
|
-
const fallback = `file-${
|
|
222
|
+
for (const [position, attachment] of attachments.entries()) {
|
|
223
|
+
const fallback = `file-${position + 1}`;
|
|
103
224
|
const filename = sanitizeFilename(attachment.filename, fallback);
|
|
104
225
|
if (typeof attachment.size === "number" && attachment.size > limit) {
|
|
105
|
-
failures.push({ filename, reason:
|
|
226
|
+
failures.push({ filename, reason: `file too large (${formatBytes(attachment.size)} > ${formatBytes(limit)})` });
|
|
106
227
|
continue;
|
|
107
228
|
}
|
|
108
229
|
|
|
@@ -111,16 +232,18 @@ export async function saveInboundFiles(
|
|
|
111
232
|
url: attachment.url,
|
|
112
233
|
maxSize: limit,
|
|
113
234
|
timeoutMs: DOWNLOAD_TIMEOUT_MS,
|
|
114
|
-
kind: "
|
|
235
|
+
kind: "file",
|
|
115
236
|
fetchImpl,
|
|
116
237
|
});
|
|
117
|
-
const
|
|
118
|
-
|
|
238
|
+
const result = await saveOrReuse(uploadDir, filename, body, index);
|
|
239
|
+
indexChanged ||= result.changed;
|
|
240
|
+
addFile(result.file);
|
|
119
241
|
} catch (err) {
|
|
120
|
-
failures.push({ filename, reason: err instanceof Error ? err.message : "
|
|
242
|
+
failures.push({ filename, reason: err instanceof Error ? err.message : "Download failed" });
|
|
121
243
|
}
|
|
122
244
|
}
|
|
123
245
|
|
|
246
|
+
if (indexChanged) await persistUploadIndex(uploadDir, index);
|
|
124
247
|
return { files, failures };
|
|
125
248
|
}
|
|
126
249
|
|
package/src/images.ts
CHANGED
|
@@ -78,13 +78,15 @@ export function buildImageMessageContent(
|
|
|
78
78
|
|
|
79
79
|
export function formatImageFailures(failures: readonly ImageFailure[], successCount: number): string {
|
|
80
80
|
const title =
|
|
81
|
-
successCount > 0
|
|
82
|
-
|
|
81
|
+
successCount > 0
|
|
82
|
+
? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
|
|
83
|
+
: "⚠️ Attachment failed:";
|
|
84
|
+
return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
|
|
83
85
|
}
|
|
84
86
|
|
|
85
87
|
function attachmentLabel(filename: string | undefined, index: number): string {
|
|
86
88
|
const name = filename?.trim();
|
|
87
|
-
return name ||
|
|
89
|
+
return name || `Image ${index + 1}`;
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
async function downloadOne(
|
|
@@ -96,10 +98,20 @@ async function downloadOne(
|
|
|
96
98
|
const filename = attachmentLabel(attachment.filename, index);
|
|
97
99
|
const mimeType = resolveImageMime(attachment.content_type, attachment.filename);
|
|
98
100
|
if (!mimeType) {
|
|
99
|
-
return {
|
|
101
|
+
return {
|
|
102
|
+
failure: {
|
|
103
|
+
filename,
|
|
104
|
+
reason: `Unsupported attachment type (${attachment.content_type || "unknown"})`,
|
|
105
|
+
},
|
|
106
|
+
};
|
|
100
107
|
}
|
|
101
108
|
if (typeof attachment.size === "number" && attachment.size > maxSize) {
|
|
102
|
-
return {
|
|
109
|
+
return {
|
|
110
|
+
failure: {
|
|
111
|
+
filename,
|
|
112
|
+
reason: `image too large (${formatBytes(attachment.size)} > ${formatBytes(maxSize)})`,
|
|
113
|
+
},
|
|
114
|
+
};
|
|
103
115
|
}
|
|
104
116
|
|
|
105
117
|
try {
|
|
@@ -107,12 +119,12 @@ async function downloadOne(
|
|
|
107
119
|
url: attachment.url,
|
|
108
120
|
maxSize,
|
|
109
121
|
timeoutMs: DOWNLOAD_TIMEOUT_MS,
|
|
110
|
-
kind: "
|
|
122
|
+
kind: "image",
|
|
111
123
|
fetchImpl,
|
|
112
124
|
});
|
|
113
125
|
return { image: { type: "image", data: body.toString("base64"), mimeType } };
|
|
114
126
|
} catch (err) {
|
|
115
|
-
return { failure: { filename, reason: err instanceof Error ? err.message : "
|
|
127
|
+
return { failure: { filename, reason: err instanceof Error ? err.message : "Download failed" } };
|
|
116
128
|
}
|
|
117
129
|
}
|
|
118
130
|
|
package/src/inbound.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import { join } from "node:path";
|
|
3
2
|
import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
4
3
|
import { sendReply, type ReplyChannel } from "./outbound";
|
|
5
4
|
import type { ReplyBudget } from "./reply-budget";
|
|
@@ -10,7 +9,9 @@ import {
|
|
|
10
9
|
resolveInboundImages,
|
|
11
10
|
type ImageContentLike,
|
|
12
11
|
} from "./images";
|
|
13
|
-
import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
|
|
12
|
+
import { formatFilePrompt, saveInboundFiles, sessionUploadDir, type SavedFile } from "./files";
|
|
13
|
+
import { log } from "./logger";
|
|
14
|
+
import { isVoiceAttachment, resolveVoiceTranscript } from "./voice";
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* F2: QQ → pi inbound handling.
|
|
@@ -38,14 +39,52 @@ export interface InboundDeps {
|
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
export function createInboundHandler(deps: InboundDeps) {
|
|
42
|
+
// F10: files uploaded without text wait for the next text/voice instruction.
|
|
43
|
+
let pendingFiles: SavedFile[] = [];
|
|
44
|
+
const takePendingFiles = (): SavedFile[] => {
|
|
45
|
+
const files = pendingFiles;
|
|
46
|
+
pendingFiles = [];
|
|
47
|
+
return files;
|
|
48
|
+
};
|
|
49
|
+
|
|
41
50
|
return async (bot: QQBot, msg: QQBotInboundMessage): Promise<void> => {
|
|
42
|
-
|
|
51
|
+
log.debug("inbound", "message received", {
|
|
52
|
+
kind: msg.kind,
|
|
53
|
+
rawEventType: msg.rawEventType,
|
|
54
|
+
messageId: msg.messageId,
|
|
55
|
+
senderId: msg.senderId,
|
|
56
|
+
senderName: msg.senderName,
|
|
57
|
+
senderIsBot: msg.senderIsBot,
|
|
58
|
+
content: msg.content,
|
|
59
|
+
msgType: msg.msgType,
|
|
60
|
+
timestamp: msg.timestamp,
|
|
61
|
+
msgIdx: msg.msgIdx,
|
|
62
|
+
refMsgIdx: msg.refMsgIdx,
|
|
63
|
+
messageScene: msg.messageScene,
|
|
64
|
+
attachments: msg.attachments,
|
|
65
|
+
msgElements: msg.msgElements,
|
|
66
|
+
raw: msg.raw,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
if (msg.kind !== "c2c") {
|
|
70
|
+
log.debug("inbound", "skipped non-c2c message", { kind: msg.kind });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
43
73
|
|
|
44
74
|
const allowed = deps.getAllowedOpenid();
|
|
45
|
-
if (!allowed || msg.senderId !== allowed)
|
|
75
|
+
if (!allowed || msg.senderId !== allowed) {
|
|
76
|
+
log.debug("inbound", "skipped non-allowlisted sender", { senderId: msg.senderId });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
46
79
|
|
|
47
80
|
// Record passive reply target/freshness for outbound budget.
|
|
48
81
|
deps.budget.observeInbound(msg.senderId, msg.messageId);
|
|
82
|
+
log.info("inbound", "message received", {
|
|
83
|
+
messageId: msg.messageId,
|
|
84
|
+
senderId: msg.senderId,
|
|
85
|
+
contentLength: (msg.content ?? "").length,
|
|
86
|
+
attachmentCount: (msg.attachments ?? []).length,
|
|
87
|
+
});
|
|
49
88
|
|
|
50
89
|
const channel: ReplyChannel = {
|
|
51
90
|
budget: deps.budget,
|
|
@@ -57,13 +96,47 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
57
96
|
|
|
58
97
|
const text = (msg.content ?? "").trim();
|
|
59
98
|
if (text.startsWith("/")) {
|
|
99
|
+
const command = text.split(/\s+/)[0];
|
|
100
|
+
log.info("inbound", "QQ command", { command });
|
|
101
|
+
if (command === "/new" && deps.ctx.isIdle() && pendingFiles.length > 0) {
|
|
102
|
+
log.info("inbound", "cleared pending files for /new", { count: pendingFiles.length });
|
|
103
|
+
pendingFiles = [];
|
|
104
|
+
}
|
|
60
105
|
await handleCommand(text, reply, deps);
|
|
61
106
|
return;
|
|
62
107
|
}
|
|
63
108
|
|
|
64
109
|
const attachments = msg.attachments ?? [];
|
|
65
110
|
if (!text && attachments.length === 0) {
|
|
66
|
-
|
|
111
|
+
log.warn("inbound", "unsupported message: no text and no attachments", { messageId: msg.messageId });
|
|
112
|
+
await reply("Unsupported message type.");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// F8: voice messages use QQ built-in ASR; never download or save the audio.
|
|
117
|
+
const voiceAttachments = attachments.filter(isVoiceAttachment);
|
|
118
|
+
if (voiceAttachments.length > 0) {
|
|
119
|
+
const transcript = resolveVoiceTranscript(voiceAttachments);
|
|
120
|
+
log.info("inbound", "voice message", {
|
|
121
|
+
messageId: msg.messageId,
|
|
122
|
+
hasAsr: Boolean(transcript),
|
|
123
|
+
asrLength: transcript?.length ?? 0,
|
|
124
|
+
});
|
|
125
|
+
if (!transcript) {
|
|
126
|
+
log.warn("inbound", "voice ASR returned no text", { messageId: msg.messageId });
|
|
127
|
+
await reply("Could not transcribe this voice message; please resend or type it.");
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
log.debug("inbound", "voice transcript", { messageId: msg.messageId, transcript });
|
|
131
|
+
const pending = takePendingFiles();
|
|
132
|
+
const promptText = formatFilePrompt(pending, transcript);
|
|
133
|
+
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
134
|
+
deps.pi.sendUserMessage(promptText, { deliverAs: deps.getDeliverAs() });
|
|
135
|
+
log.info("inbound", "voice sent to pi", {
|
|
136
|
+
messageId: msg.messageId,
|
|
137
|
+
asrLength: transcript.length,
|
|
138
|
+
pendingFiles: pending.length,
|
|
139
|
+
});
|
|
67
140
|
return;
|
|
68
141
|
}
|
|
69
142
|
|
|
@@ -76,7 +149,11 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
76
149
|
if (imageAttachments.length > 0) {
|
|
77
150
|
const supportsImages = deps.ctx.model?.input.includes("image") ?? false;
|
|
78
151
|
if (!supportsImages) {
|
|
79
|
-
|
|
152
|
+
log.warn("inbound", "model does not support images; skipped", {
|
|
153
|
+
messageId: msg.messageId,
|
|
154
|
+
count: imageAttachments.length,
|
|
155
|
+
});
|
|
156
|
+
await reply(`Model does not support image input; skipped ${imageAttachments.length} image(s).`);
|
|
80
157
|
} else {
|
|
81
158
|
const result = await resolveInboundImages(imageAttachments, deps.getImageMaxSize());
|
|
82
159
|
images = result.images;
|
|
@@ -86,24 +163,61 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
86
163
|
|
|
87
164
|
let files: SavedFile[] = [];
|
|
88
165
|
if (fileAttachments.length > 0) {
|
|
166
|
+
const uploadDir = sessionUploadDir(deps.ctx.cwd, deps.ctx.sessionManager.getSessionId());
|
|
167
|
+
log.debug("inbound", "saving files", {
|
|
168
|
+
messageId: msg.messageId,
|
|
169
|
+
count: fileAttachments.length,
|
|
170
|
+
uploadDir,
|
|
171
|
+
});
|
|
89
172
|
const result = await saveFiles(fileAttachments, {
|
|
90
173
|
maxSize: deps.getFileMaxSize(),
|
|
91
|
-
|
|
92
|
-
dirKey: msg.messageId,
|
|
174
|
+
uploadDir,
|
|
93
175
|
});
|
|
94
176
|
files = result.files;
|
|
95
177
|
failures.push(...result.failures);
|
|
96
178
|
}
|
|
97
179
|
|
|
98
180
|
if (failures.length > 0) {
|
|
181
|
+
log.warn("inbound", "attachment failure summary", {
|
|
182
|
+
messageId: msg.messageId,
|
|
183
|
+
failures,
|
|
184
|
+
successCount: images.length + files.length,
|
|
185
|
+
});
|
|
99
186
|
await reply(formatImageFailures(failures, images.length + files.length));
|
|
100
187
|
}
|
|
101
|
-
if (!text && images.length === 0 && files.length === 0)
|
|
188
|
+
if (!text && images.length === 0 && files.length === 0) {
|
|
189
|
+
log.warn("inbound", "no injectable content after attachment handling", {
|
|
190
|
+
messageId: msg.messageId,
|
|
191
|
+
failures: failures.length,
|
|
192
|
+
});
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// F10: a file-only message waits for the next text/voice instruction.
|
|
197
|
+
if (!text && images.length === 0 && files.length > 0) {
|
|
198
|
+
pendingFiles.push(...files);
|
|
199
|
+
log.info("inbound", "files pending for instruction", {
|
|
200
|
+
messageId: msg.messageId,
|
|
201
|
+
count: files.length,
|
|
202
|
+
pendingCount: pendingFiles.length,
|
|
203
|
+
});
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
102
206
|
|
|
103
207
|
// F7: mark a QQ-triggered run; do not send a start confirmation.
|
|
104
208
|
deps.markQQTrigger(msg.senderId, msg.messageId);
|
|
105
|
-
const
|
|
209
|
+
const pending = text ? takePendingFiles() : [];
|
|
210
|
+
const promptFiles = [...pending, ...files];
|
|
211
|
+
const promptText = formatFilePrompt(promptFiles, text);
|
|
106
212
|
deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
|
|
213
|
+
log.info("inbound", "sent to pi", {
|
|
214
|
+
messageId: msg.messageId,
|
|
215
|
+
textLength: text.length,
|
|
216
|
+
images: images.length,
|
|
217
|
+
files: promptFiles.length,
|
|
218
|
+
pendingFiles: pending.length,
|
|
219
|
+
deliverAs: deps.getDeliverAs(),
|
|
220
|
+
});
|
|
107
221
|
};
|
|
108
222
|
}
|
|
109
223
|
|
|
@@ -113,30 +227,30 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
|
|
|
113
227
|
case "/help":
|
|
114
228
|
await reply(
|
|
115
229
|
[
|
|
116
|
-
"pi-qq
|
|
117
|
-
"• /stop —
|
|
118
|
-
"• /compact —
|
|
119
|
-
"• /status —
|
|
120
|
-
"• /new —
|
|
121
|
-
"• /help —
|
|
122
|
-
"
|
|
230
|
+
"pi-qq commands:",
|
|
231
|
+
"• /stop — abort the current task",
|
|
232
|
+
"• /compact — compact the context",
|
|
233
|
+
"• /status — show status",
|
|
234
|
+
"• /new — reset the session",
|
|
235
|
+
"• /help — this help",
|
|
236
|
+
"Other text is sent to pi.",
|
|
123
237
|
].join("\n"),
|
|
124
238
|
);
|
|
125
239
|
break;
|
|
126
240
|
case "/stop":
|
|
127
241
|
if (deps.ctx.isIdle()) {
|
|
128
|
-
await reply("
|
|
242
|
+
await reply("No task is running.");
|
|
129
243
|
} else {
|
|
130
244
|
deps.ctx.abort();
|
|
131
|
-
await reply("
|
|
245
|
+
await reply("Abort requested.");
|
|
132
246
|
}
|
|
133
247
|
break;
|
|
134
248
|
case "/compact":
|
|
135
249
|
if (deps.ctx.isIdle()) {
|
|
136
250
|
deps.ctx.compact();
|
|
137
|
-
await reply("
|
|
251
|
+
await reply("Context compaction triggered.");
|
|
138
252
|
} else {
|
|
139
|
-
await reply("
|
|
253
|
+
await reply("Task is running; use /stop before /compact.");
|
|
140
254
|
}
|
|
141
255
|
break;
|
|
142
256
|
case "/status":
|
|
@@ -144,14 +258,14 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
|
|
|
144
258
|
break;
|
|
145
259
|
case "/new":
|
|
146
260
|
if (!deps.ctx.isIdle()) {
|
|
147
|
-
await reply("
|
|
261
|
+
await reply("Task is running; use /stop before resetting.");
|
|
148
262
|
} else {
|
|
149
|
-
await reply("
|
|
263
|
+
await reply("Resetting the session…");
|
|
150
264
|
// Built-in /new is interactive-only; dispatch the extension command instead.
|
|
151
265
|
deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
|
|
152
266
|
}
|
|
153
267
|
break;
|
|
154
268
|
default:
|
|
155
|
-
await reply(
|
|
269
|
+
await reply(`Unknown command ${cmd}; use /help.`);
|
|
156
270
|
}
|
|
157
271
|
}
|