@chen_hu_hu/pi-qq 1.2.3 → 1.3.1
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-zh.md +76 -46
- package/README.md +79 -49
- package/doc/delivery-v1-zh.md +160 -0
- package/doc/delivery-v1.md +160 -0
- package/doc/delivery-v2-zh.md +100 -0
- package/doc/delivery-v2.md +98 -0
- package/doc/delivery-v3-zh.md +189 -0
- package/doc/delivery-v3.md +189 -0
- package/index.ts +66 -156
- package/package.json +6 -3
- package/src/{download.ts → attachments/attachment-download.ts} +1 -4
- package/src/attachments/attachment-failure.ts +12 -0
- package/src/{files.ts → attachments/file-attachments.ts} +19 -33
- package/src/{voice.ts → attachments/voice-transcript.ts} +1 -7
- package/src/{format.ts → infra/display-format.ts} +0 -2
- package/src/{logger.ts → infra/file-logger.ts} +6 -31
- package/src/infra/settings.ts +103 -0
- package/src/{bot.ts → qq/qq-bot.ts} +6 -31
- package/src/qq/qq-diagnostics.ts +129 -0
- package/src/{inbound.ts → qq/qq-message-handler.ts} +58 -94
- package/src/{login.ts → qq/qr-login.ts} +24 -17
- package/src/{outbound.ts → qq/reply-sender.ts} +7 -37
- package/src/qrcode-terminal.d.ts +0 -2
- package/src/{budget-status.ts → quota/reply-quota-report.ts} +2 -3
- package/src/{reply-budget.ts → quota/reply-quota.ts} +0 -21
- package/src/relay/run-stream-relay.ts +576 -0
- package/src/relay/stream-block-format.ts +117 -0
- package/src/{append-stream.ts → relay/stream-session.ts} +46 -29
- package/doc/features-v1.md +0 -239
- package/doc/features-v2.md +0 -210
- package/doc/plan-v1.md +0 -190
- package/doc/plan-v2.md +0 -332
- package/src/config.ts +0 -82
- package/src/images.ts +0 -149
- package/src/run-feedback.ts +0 -409
|
@@ -1,40 +1,30 @@
|
|
|
1
|
-
/** Save QQ non-image attachments in the workspace, with session-scoped deduplication. */
|
|
2
1
|
import { createHash } from "node:crypto";
|
|
3
2
|
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
|
4
|
-
import { basename, extname, join } from "node:path";
|
|
5
|
-
import { downloadLimited, type InboundAttachmentLike } from "./download";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
3
|
+
import { basename, extname, join, relative } from "node:path";
|
|
4
|
+
import { downloadLimited, type InboundAttachmentLike } from "./attachment-download";
|
|
5
|
+
import type { AttachmentFailure } from "./attachment-failure";
|
|
6
|
+
import { formatBytes } from "../infra/display-format";
|
|
7
|
+
import { log } from "../infra/file-logger";
|
|
8
8
|
|
|
9
9
|
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
10
10
|
const UPLOAD_INDEX_FILENAME = ".index.json";
|
|
11
11
|
|
|
12
12
|
export interface SavedFile {
|
|
13
13
|
path: string;
|
|
14
|
-
originalName: string;
|
|
15
|
-
size: number;
|
|
16
14
|
}
|
|
17
15
|
|
|
18
|
-
export interface FileFailure {
|
|
19
|
-
filename: string;
|
|
20
|
-
reason: string;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** fileName -> SHA-256. Paths are derived from uploadDir. */
|
|
24
16
|
export type UploadIndex = Record<string, string>;
|
|
25
17
|
|
|
26
18
|
export interface SaveFilesOptions {
|
|
27
19
|
maxSize: number;
|
|
28
|
-
/** `<cwd>/.pi/pi-qq/<sessionId>/uploads`. */
|
|
29
20
|
uploadDir: string;
|
|
30
|
-
/** Test/caller override; loaded from uploadDir when omitted. Mutated in place. */
|
|
31
21
|
index?: UploadIndex;
|
|
32
22
|
fetchImpl?: typeof fetch;
|
|
33
23
|
}
|
|
34
24
|
|
|
35
25
|
export interface SaveFilesResult {
|
|
36
26
|
files: SavedFile[];
|
|
37
|
-
failures:
|
|
27
|
+
failures: AttachmentFailure[];
|
|
38
28
|
}
|
|
39
29
|
|
|
40
30
|
function safePathSegment(key: string): string {
|
|
@@ -42,7 +32,6 @@ function safePathSegment(key: string): string {
|
|
|
42
32
|
return cleaned.slice(0, 64) || "session";
|
|
43
33
|
}
|
|
44
34
|
|
|
45
|
-
/** Session-scoped upload directory; no date or msgId subdirectories. */
|
|
46
35
|
export function sessionUploadDir(cwd: string, sessionId: string): string {
|
|
47
36
|
return join(cwd, ".pi", "pi-qq", safePathSegment(sessionId), "uploads");
|
|
48
37
|
}
|
|
@@ -51,11 +40,9 @@ export function uploadIndexPath(uploadDir: string): string {
|
|
|
51
40
|
return join(uploadDir, UPLOAD_INDEX_FILENAME);
|
|
52
41
|
}
|
|
53
42
|
|
|
54
|
-
/** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
|
|
55
43
|
export function sanitizeFilename(filename: string | undefined, fallback: string): string {
|
|
56
44
|
const raw = basename((filename ?? "").trim());
|
|
57
45
|
const cleaned = raw
|
|
58
|
-
// Control characters are rejected intentionally when normalizing a filename.
|
|
59
46
|
// eslint-disable-next-line no-control-regex
|
|
60
47
|
.replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "_")
|
|
61
48
|
.replace(/^[.\s]+|[.\s]+$/g, "")
|
|
@@ -96,7 +83,7 @@ async function isFile(path: string): Promise<boolean> {
|
|
|
96
83
|
}
|
|
97
84
|
}
|
|
98
85
|
|
|
99
|
-
|
|
86
|
+
async function loadUploadIndex(uploadDir: string): Promise<UploadIndex> {
|
|
100
87
|
try {
|
|
101
88
|
const parsed = JSON.parse(await readFile(uploadIndexPath(uploadDir), "utf8")) as unknown;
|
|
102
89
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
|
|
@@ -122,7 +109,6 @@ async function persistUploadIndex(uploadDir: string, index: UploadIndex): Promis
|
|
|
122
109
|
}
|
|
123
110
|
}
|
|
124
111
|
|
|
125
|
-
/** Load the index and drop entries whose files no longer exist. No content hashing. */
|
|
126
112
|
export async function pruneUploadIndex(uploadDir: string): Promise<UploadIndex> {
|
|
127
113
|
const index = await loadUploadIndex(uploadDir);
|
|
128
114
|
let changed = false;
|
|
@@ -151,13 +137,12 @@ async function saveOrReuse(
|
|
|
151
137
|
let changed = false;
|
|
152
138
|
|
|
153
139
|
if (!(await isFile(target))) {
|
|
154
|
-
// A stale index entry must not make a missing file look reusable.
|
|
155
140
|
if (index[filename]) {
|
|
156
141
|
delete index[filename];
|
|
157
142
|
}
|
|
158
143
|
await writeFile(target, body, { flag: "wx" });
|
|
159
144
|
index[filename] = hash;
|
|
160
|
-
return { file: { path: target
|
|
145
|
+
return { file: { path: target }, changed: true };
|
|
161
146
|
}
|
|
162
147
|
|
|
163
148
|
let existingHash = index[filename];
|
|
@@ -167,7 +152,7 @@ async function saveOrReuse(
|
|
|
167
152
|
changed = true;
|
|
168
153
|
}
|
|
169
154
|
if (existingHash === hash) {
|
|
170
|
-
return { file: { path: target
|
|
155
|
+
return { file: { path: target }, changed };
|
|
171
156
|
}
|
|
172
157
|
|
|
173
158
|
for (let suffix = 1; suffix < 100; suffix++) {
|
|
@@ -181,7 +166,7 @@ async function saveOrReuse(
|
|
|
181
166
|
changed = true;
|
|
182
167
|
}
|
|
183
168
|
if (candidateHash === hash) {
|
|
184
|
-
return { file: { path: candidatePath
|
|
169
|
+
return { file: { path: candidatePath }, changed };
|
|
185
170
|
}
|
|
186
171
|
continue;
|
|
187
172
|
}
|
|
@@ -191,13 +176,12 @@ async function saveOrReuse(
|
|
|
191
176
|
}
|
|
192
177
|
await writeFile(candidatePath, body, { flag: "wx" });
|
|
193
178
|
index[candidate] = hash;
|
|
194
|
-
return { file: { path: candidatePath
|
|
179
|
+
return { file: { path: candidatePath }, changed: true };
|
|
195
180
|
}
|
|
196
181
|
|
|
197
182
|
throw new Error("Could not allocate a unique filename");
|
|
198
183
|
}
|
|
199
184
|
|
|
200
|
-
/** Save non-image attachments in order; one failure does not stop the others. */
|
|
201
185
|
export async function saveInboundFiles(
|
|
202
186
|
attachments: readonly InboundAttachmentLike[],
|
|
203
187
|
options: SaveFilesOptions,
|
|
@@ -207,7 +191,7 @@ export async function saveInboundFiles(
|
|
|
207
191
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
208
192
|
const index = options.index ?? (await loadUploadIndex(uploadDir));
|
|
209
193
|
const files: SavedFile[] = [];
|
|
210
|
-
const failures:
|
|
194
|
+
const failures: AttachmentFailure[] = [];
|
|
211
195
|
const seenPaths = new Set<string>();
|
|
212
196
|
let indexChanged = false;
|
|
213
197
|
|
|
@@ -247,15 +231,17 @@ export async function saveInboundFiles(
|
|
|
247
231
|
return { files, failures };
|
|
248
232
|
}
|
|
249
233
|
|
|
250
|
-
|
|
251
|
-
export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
|
|
234
|
+
export function formatAttachmentPrompt(files: readonly SavedFile[], userText: string, cwd: string): string {
|
|
252
235
|
if (files.length === 0) return userText;
|
|
253
236
|
|
|
254
237
|
const lines = [
|
|
255
|
-
"
|
|
256
|
-
...files.map((file) =>
|
|
238
|
+
"# Attachments:",
|
|
239
|
+
...files.map((file) => {
|
|
240
|
+
const displayPath = relative(cwd, file.path);
|
|
241
|
+
return `- ${displayPath && !displayPath.startsWith("..") ? displayPath : file.path}`;
|
|
242
|
+
}),
|
|
257
243
|
];
|
|
258
244
|
const text = userText.trim();
|
|
259
|
-
if (text) lines.push("", "User message:", text);
|
|
245
|
+
if (text) lines.push("", "# User message:", text);
|
|
260
246
|
return lines.join("\n");
|
|
261
247
|
}
|
|
@@ -1,19 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
import type { InboundAttachmentLike } from "./download";
|
|
1
|
+
import type { InboundAttachmentLike } from "./attachment-download";
|
|
3
2
|
|
|
4
3
|
export interface VoiceAttachmentLike extends InboundAttachmentLike {
|
|
5
4
|
asr_refer_text?: string;
|
|
6
5
|
}
|
|
7
6
|
|
|
8
|
-
/** A QQ voice message has content_type "voice"; other media/file types are excluded. */
|
|
9
7
|
export function isVoiceAttachment(attachment: { content_type?: string }): boolean {
|
|
10
8
|
return (attachment.content_type ?? "").toLowerCase() === "voice";
|
|
11
9
|
}
|
|
12
10
|
|
|
13
|
-
/**
|
|
14
|
-
* Collect non-empty ASR text from voice attachments in order.
|
|
15
|
-
* Returns undefined when no attachment has a usable transcript.
|
|
16
|
-
*/
|
|
17
11
|
export function resolveVoiceTranscript(attachments: readonly VoiceAttachmentLike[]): string | undefined {
|
|
18
12
|
const transcripts: string[] = [];
|
|
19
13
|
for (const attachment of attachments) {
|
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
/** Human-readable size formatting shared by image/file downloads and prompts. */
|
|
2
1
|
export function formatBytes(bytes: number): string {
|
|
3
2
|
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
|
|
4
3
|
if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
5
4
|
return `${bytes}B`;
|
|
6
5
|
}
|
|
7
6
|
|
|
8
|
-
/** Compact token count used by /qq-status. */
|
|
9
7
|
export function formatTokenCount(n: number): string {
|
|
10
8
|
return n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n);
|
|
11
9
|
}
|
|
@@ -1,18 +1,8 @@
|
|
|
1
1
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
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
4
|
export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
15
|
-
|
|
5
|
+
type LogFields = Record<string, unknown>;
|
|
16
6
|
|
|
17
7
|
const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
|
18
8
|
debug: 10,
|
|
@@ -22,35 +12,29 @@ const LEVEL_WEIGHT: Record<LogLevel, number> = {
|
|
|
22
12
|
silent: 100,
|
|
23
13
|
};
|
|
24
14
|
|
|
25
|
-
|
|
15
|
+
const DEFAULT_LOG_LEVEL: LogLevel = "silent";
|
|
26
16
|
|
|
27
17
|
let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
|
|
28
18
|
let activeDir: string | undefined;
|
|
29
19
|
|
|
30
|
-
|
|
31
|
-
return typeof value === "string" && Object.
|
|
20
|
+
function isLogLevel(value: unknown): value is LogLevel {
|
|
21
|
+
return typeof value === "string" && Object.hasOwn(LEVEL_WEIGHT, value);
|
|
32
22
|
}
|
|
33
23
|
|
|
34
24
|
export function normalizeLogLevel(value: unknown): LogLevel {
|
|
35
25
|
return isLogLevel(value) ? value : DEFAULT_LOG_LEVEL;
|
|
36
26
|
}
|
|
37
27
|
|
|
38
|
-
/** Whether an event at `level` passes the configured threshold. */
|
|
39
28
|
export function isLevelEnabled(configured: LogLevel, level: Exclude<LogLevel, "silent">): boolean {
|
|
40
29
|
return configured !== "silent" && LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[configured];
|
|
41
30
|
}
|
|
42
31
|
|
|
43
|
-
/** Set the active threshold and optional directory. */
|
|
44
32
|
export function configureLogger(level: LogLevel, dir?: string): void {
|
|
45
33
|
activeLevel = normalizeLogLevel(level);
|
|
46
34
|
activeDir = dir;
|
|
47
35
|
}
|
|
48
36
|
|
|
49
|
-
|
|
50
|
-
return activeLevel;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export function resolveLogDir(): string {
|
|
37
|
+
function resolveLogDir(): string {
|
|
54
38
|
return process.env.PI_QQ_LOG_DIR ?? activeDir ?? join(process.cwd(), ".pi", "pi-qq", "logs");
|
|
55
39
|
}
|
|
56
40
|
|
|
@@ -58,7 +42,6 @@ function pad(n: number): string {
|
|
|
58
42
|
return String(n).padStart(2, "0");
|
|
59
43
|
}
|
|
60
44
|
|
|
61
|
-
/** Local calendar date used in the log filename. */
|
|
62
45
|
export function dateStamp(now = new Date()): string {
|
|
63
46
|
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
|
64
47
|
}
|
|
@@ -94,7 +77,6 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
|
|
|
94
77
|
const fields = normalizeData(data);
|
|
95
78
|
if (fields) {
|
|
96
79
|
for (const [key, value] of Object.entries(fields)) {
|
|
97
|
-
// Protect the record envelope from accidental overrides.
|
|
98
80
|
if (!(key in record)) record[key] = value;
|
|
99
81
|
}
|
|
100
82
|
}
|
|
@@ -122,15 +104,10 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
|
|
|
122
104
|
const dir = resolveLogDir();
|
|
123
105
|
mkdirSync(dir, { recursive: true });
|
|
124
106
|
appendFileSync(join(dir, logFileName()), `${line}\n`, "utf8");
|
|
125
|
-
} catch {
|
|
126
|
-
// Logging is diagnostic only; never break message handling.
|
|
127
|
-
}
|
|
107
|
+
} catch {}
|
|
128
108
|
}
|
|
129
109
|
|
|
130
110
|
export const log = {
|
|
131
|
-
get level(): LogLevel {
|
|
132
|
-
return activeLevel;
|
|
133
|
-
},
|
|
134
111
|
debug(scope: string, message: string, data?: unknown): void {
|
|
135
112
|
writeRecord("debug", scope, message, data);
|
|
136
113
|
},
|
|
@@ -145,7 +122,6 @@ export const log = {
|
|
|
145
122
|
},
|
|
146
123
|
};
|
|
147
124
|
|
|
148
|
-
/** Adapter for the QQ SDK's Logger interface: (message, meta?) -> record. */
|
|
149
125
|
export const sdkLogger = {
|
|
150
126
|
debug(message: string, meta?: Record<string, unknown>): void {
|
|
151
127
|
log.debug("qqbot", message, meta);
|
|
@@ -161,7 +137,6 @@ export const sdkLogger = {
|
|
|
161
137
|
},
|
|
162
138
|
};
|
|
163
139
|
|
|
164
|
-
/** Short string form for noisy tool payloads. */
|
|
165
140
|
export function previewForLog(value: unknown, maxChars = 2000): string {
|
|
166
141
|
let text: string;
|
|
167
142
|
if (typeof value === "string") {
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { normalizeLogLevel, type LogLevel } from "./file-logger";
|
|
5
|
+
|
|
6
|
+
export interface PiQQSettings {
|
|
7
|
+
thinkingRelay?: boolean;
|
|
8
|
+
deliverAs?: "steer" | "followUp";
|
|
9
|
+
fileMaxSize?: number;
|
|
10
|
+
logLevel?: LogLevel;
|
|
11
|
+
debug?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface Credentials {
|
|
15
|
+
appId: string;
|
|
16
|
+
appSecret: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const CONFIG_PATH = join(homedir(), ".pi", "agent", "pi-qq.json");
|
|
20
|
+
|
|
21
|
+
interface ReadConfigResult {
|
|
22
|
+
config: PiQQSettings;
|
|
23
|
+
error?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
27
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isLogLevel(value: unknown): value is LogLevel {
|
|
31
|
+
return value === "silent" || value === "error" || value === "warn" || value === "info" || value === "debug";
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isPositiveSize(value: unknown): value is number {
|
|
35
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Validate the on-disk shape before it reaches business code. Invalid fields
|
|
40
|
+
* are dropped individually so one typo does not discard the whole config.
|
|
41
|
+
*/
|
|
42
|
+
export function parseConfig(raw: unknown): ReadConfigResult {
|
|
43
|
+
if (!isRecord(raw)) {
|
|
44
|
+
return {
|
|
45
|
+
config: {},
|
|
46
|
+
error: `Invalid config file (${CONFIG_PATH}): expected a JSON object; using defaults.`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const config: PiQQSettings = {};
|
|
51
|
+
const errors: string[] = [];
|
|
52
|
+
|
|
53
|
+
if (raw.thinkingRelay !== undefined) {
|
|
54
|
+
if (typeof raw.thinkingRelay === "boolean") config.thinkingRelay = raw.thinkingRelay;
|
|
55
|
+
else errors.push("thinkingRelay must be a boolean");
|
|
56
|
+
}
|
|
57
|
+
if (raw.deliverAs !== undefined) {
|
|
58
|
+
if (raw.deliverAs === "steer" || raw.deliverAs === "followUp") config.deliverAs = raw.deliverAs;
|
|
59
|
+
else errors.push('deliverAs must be "steer" or "followUp"');
|
|
60
|
+
}
|
|
61
|
+
if (raw.fileMaxSize !== undefined) {
|
|
62
|
+
if (isPositiveSize(raw.fileMaxSize)) config.fileMaxSize = raw.fileMaxSize;
|
|
63
|
+
else errors.push("fileMaxSize must be a positive finite number");
|
|
64
|
+
}
|
|
65
|
+
if (raw.logLevel !== undefined) {
|
|
66
|
+
if (isLogLevel(raw.logLevel)) config.logLevel = raw.logLevel;
|
|
67
|
+
else errors.push('logLevel must be "silent", "error", "warn", "info", or "debug"');
|
|
68
|
+
}
|
|
69
|
+
if (raw.debug !== undefined) {
|
|
70
|
+
if (typeof raw.debug === "boolean") config.debug = raw.debug;
|
|
71
|
+
else errors.push("debug must be a boolean");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return errors.length > 0
|
|
75
|
+
? { config, error: `Invalid config file (${CONFIG_PATH}): ${errors.join("; ")}; invalid values were ignored.` }
|
|
76
|
+
: { config };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function readConfig(): ReadConfigResult {
|
|
80
|
+
let raw: string;
|
|
81
|
+
try {
|
|
82
|
+
raw = readFileSync(CONFIG_PATH, "utf8");
|
|
83
|
+
} catch {
|
|
84
|
+
return { config: {} };
|
|
85
|
+
}
|
|
86
|
+
try {
|
|
87
|
+
return parseConfig(JSON.parse(raw));
|
|
88
|
+
} catch (e) {
|
|
89
|
+
return { config: {}, error: `Failed to parse config file (${CONFIG_PATH}): ${(e as Error).message}` };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type ResolvedSettings = Required<Omit<PiQQSettings, "debug">>;
|
|
94
|
+
|
|
95
|
+
export function getSettings(config: PiQQSettings): ResolvedSettings {
|
|
96
|
+
const logLevel = normalizeLogLevel(config.logLevel ?? (config.debug ? "debug" : undefined));
|
|
97
|
+
return {
|
|
98
|
+
thinkingRelay: config.thinkingRelay ?? true,
|
|
99
|
+
deliverAs: config.deliverAs ?? "steer",
|
|
100
|
+
fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
|
|
101
|
+
logLevel,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -7,38 +7,20 @@ import {
|
|
|
7
7
|
messageFilter,
|
|
8
8
|
} from "@tencent-connect/qqbot-nodejs";
|
|
9
9
|
import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
10
|
-
import type { Credentials } from "
|
|
11
|
-
import { log, sdkLogger } from "
|
|
10
|
+
import type { Credentials } from "../infra/settings";
|
|
11
|
+
import { log, sdkLogger } from "../infra/file-logger";
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
* Session-level QQBot lifecycle: creation, middleware, connection state,
|
|
15
|
-
* and fatal-error reporting. start() blocks until stop()/abort, so it runs
|
|
16
|
-
* in the background (void, not awaited).
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
export type BotState =
|
|
20
|
-
| "stopped" // Not running/stopped
|
|
21
|
-
| "starting" // Connecting, waiting for READY
|
|
22
|
-
| "connected" // Online (READY/RESUMED)
|
|
23
|
-
| "reconnecting" // Disconnected; the SDK is reconnecting
|
|
24
|
-
| "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
|
|
13
|
+
export type BotState = "stopped" | "starting" | "connected" | "reconnecting" | "blocked";
|
|
25
14
|
|
|
26
15
|
export interface StartBotOptions {
|
|
27
16
|
credentials: Credentials;
|
|
28
|
-
|
|
29
|
-
allowedOpenid?: string;
|
|
30
|
-
markdownSupport?: boolean;
|
|
31
|
-
/** Inbound message handler. */
|
|
17
|
+
allowedOpenid: string;
|
|
32
18
|
onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
|
|
33
|
-
/** Connection state changes; the caller decides how to notify the UI. */
|
|
34
19
|
onStateChange?: (state: BotState, detail?: string) => void;
|
|
35
|
-
/** Recoverable errors; the SDK reconnects automatically. */
|
|
36
|
-
onRecoverableError?: (err: Error) => void;
|
|
37
20
|
}
|
|
38
21
|
|
|
39
22
|
export interface RunningBot {
|
|
40
23
|
bot: QQBot;
|
|
41
|
-
/** Idempotent stop. */
|
|
42
24
|
stop: () => void;
|
|
43
25
|
}
|
|
44
26
|
|
|
@@ -46,23 +28,17 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
46
28
|
log.info("bot", "starting", {
|
|
47
29
|
appId: opts.credentials.appId,
|
|
48
30
|
allowedOpenid: opts.allowedOpenid,
|
|
49
|
-
markdownSupport: opts.markdownSupport,
|
|
50
31
|
});
|
|
51
32
|
|
|
52
33
|
const bot = new QQBot({
|
|
53
34
|
appId: opts.credentials.appId,
|
|
54
35
|
appSecret: opts.credentials.appSecret,
|
|
55
|
-
markdownSupport: opts.markdownSupport ?? false,
|
|
56
36
|
logger: sdkLogger,
|
|
57
37
|
});
|
|
58
38
|
|
|
59
|
-
// Echo filtering + message deduplication (SDK default 5s window).
|
|
60
39
|
bot.use(messageFilter({ skipSelfEcho: true }));
|
|
61
|
-
// Strip protocol markers such as @mentions and face tags.
|
|
62
40
|
bot.use(contentSanitizer({ stripBotMention: true }));
|
|
63
|
-
|
|
64
|
-
bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
|
|
65
|
-
// Serialize per user so streams and replies do not race.
|
|
41
|
+
bot.use(accessPolicy({ c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } }));
|
|
66
42
|
bot.use(concurrencyGuard());
|
|
67
43
|
|
|
68
44
|
const report = (state: BotState, detail?: string) => {
|
|
@@ -81,7 +57,6 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
81
57
|
bot.on("disconnected", ({ willReconnect }) => report(willReconnect ? "reconnecting" : "stopped"));
|
|
82
58
|
bot.on("error", (err) => {
|
|
83
59
|
log.error("bot", "error event", { err });
|
|
84
|
-
opts.onRecoverableError?.(err);
|
|
85
60
|
});
|
|
86
61
|
bot.on("message", async (_ctx, msg) => {
|
|
87
62
|
log.debug("bot", "inbound message", {
|
|
@@ -112,7 +87,7 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
112
87
|
let stopped = false;
|
|
113
88
|
report("starting");
|
|
114
89
|
void bot.start().catch((err: unknown) => {
|
|
115
|
-
if (stopped) return;
|
|
90
|
+
if (stopped) return;
|
|
116
91
|
const code = (err as { code?: string }).code;
|
|
117
92
|
if (code === GatewayErrorCode.FATAL_CLOSE) {
|
|
118
93
|
const closeCode = (err as { closeCode?: number }).closeCode;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ReplyBudget } from "../quota/reply-quota";
|
|
3
|
+
import { formatBudgetStatus } from "../quota/reply-quota-report";
|
|
4
|
+
import { AppendStream } from "../relay/stream-session";
|
|
5
|
+
import type { RunningBot } from "./qq-bot";
|
|
6
|
+
|
|
7
|
+
export interface QQDiagnosticsDeps {
|
|
8
|
+
getRunning: () => RunningBot | undefined;
|
|
9
|
+
budget: ReplyBudget;
|
|
10
|
+
getBoundOpenid: () => string | undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Terminal-only protocol probes. Kept out of the entrypoint so index.ts stays
|
|
15
|
+
* a composition root and does not construct stream frames directly.
|
|
16
|
+
*/
|
|
17
|
+
export function registerQQDiagnostics(pi: ExtensionAPI, deps: QQDiagnosticsDeps): void {
|
|
18
|
+
const diagTarget = () => {
|
|
19
|
+
const last = deps.budget.lastTarget;
|
|
20
|
+
if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
|
|
21
|
+
const bound = deps.getBoundOpenid();
|
|
22
|
+
return bound ? { scope: "c2c" as const, targetId: bound } : undefined;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
pi.registerCommand("qq-test-budget", {
|
|
26
|
+
description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
|
|
27
|
+
handler: async (_args, ctx) => {
|
|
28
|
+
ctx.ui.notify(formatBudgetStatus(deps.budget.snapshot(), deps.budget.lastTarget).join("\n"), "info");
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
pi.registerCommand("qq-test-md", {
|
|
33
|
+
description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
|
|
34
|
+
handler: async (args, ctx) => {
|
|
35
|
+
const running = deps.getRunning();
|
|
36
|
+
if (!running) {
|
|
37
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const target = diagTarget();
|
|
41
|
+
if (!target) {
|
|
42
|
+
ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
|
|
46
|
+
try {
|
|
47
|
+
await running.bot.sendMarkdown(target, content);
|
|
48
|
+
ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
|
|
49
|
+
} catch (err) {
|
|
50
|
+
ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
pi.registerCommand("qq-test-stream", {
|
|
56
|
+
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text) or resume probe",
|
|
57
|
+
handler: async (args, ctx) => {
|
|
58
|
+
const running = deps.getRunning();
|
|
59
|
+
if (!running) {
|
|
60
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const last = deps.budget.lastTarget;
|
|
64
|
+
if (!last) {
|
|
65
|
+
ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
70
|
+
let stream: AppendStream | undefined;
|
|
71
|
+
try {
|
|
72
|
+
if (args?.trim() === "resume") {
|
|
73
|
+
const first = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
74
|
+
stream = first;
|
|
75
|
+
await first.append("**Resume probe** frame 1\n");
|
|
76
|
+
await first.flush();
|
|
77
|
+
const checkpoint = first.checkpoint();
|
|
78
|
+
first.dispose();
|
|
79
|
+
stream = undefined;
|
|
80
|
+
if (!checkpoint?.streamMsgId) {
|
|
81
|
+
ctx.ui.notify("Resume probe: frame 1 sent but stream_msg_id is missing; cannot resume.", "error");
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
await sleep(800);
|
|
85
|
+
const second = new AppendStream(
|
|
86
|
+
running.bot.messageApi,
|
|
87
|
+
running.bot.getCredentials(),
|
|
88
|
+
last.openid,
|
|
89
|
+
last.msgId,
|
|
90
|
+
{ resume: checkpoint },
|
|
91
|
+
);
|
|
92
|
+
stream = second;
|
|
93
|
+
await second.append("frame 2 after resume\n");
|
|
94
|
+
await second.done();
|
|
95
|
+
second.dispose();
|
|
96
|
+
stream = undefined;
|
|
97
|
+
ctx.ui.notify(
|
|
98
|
+
`Resume probe: frame 2 sent with index ${checkpoint.index} and stream_msg_id ${checkpoint.streamMsgId}. Check whether both frames are in the same bubble.`,
|
|
99
|
+
"info",
|
|
100
|
+
);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
105
|
+
await stream.append(
|
|
106
|
+
"**💭 思考**\n\nprobe thinking\nsecond line\n\n**💻 bash**\n\n`echo probe`\n\n```text\nprobe\n```\n",
|
|
107
|
+
);
|
|
108
|
+
await sleep(1200);
|
|
109
|
+
await stream.append("\n**Intermediate message**: first-turn reply.\n");
|
|
110
|
+
await sleep(1200);
|
|
111
|
+
await stream.append("\n**📖 read**\n\n`src/index.ts`\n\n```text\nprobe file\n```\n");
|
|
112
|
+
await sleep(800);
|
|
113
|
+
await stream.append("\n**Final reply** (streamed append)");
|
|
114
|
+
let doneNote = "DONE succeeded";
|
|
115
|
+
try {
|
|
116
|
+
await stream.done();
|
|
117
|
+
} catch (doneErr) {
|
|
118
|
+
doneNote = `DONE rejected: ${(doneErr as Error).message}`;
|
|
119
|
+
}
|
|
120
|
+
stream.dispose();
|
|
121
|
+
stream = undefined;
|
|
122
|
+
ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
|
|
123
|
+
} catch (err) {
|
|
124
|
+
stream?.dispose();
|
|
125
|
+
ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|