@chen_hu_hu/pi-qq 1.3.0 → 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/index.ts CHANGED
@@ -1,15 +1,14 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { join } from "node:path";
3
- import { getSettings, readConfig, type Credentials } from "./src/infra/settings";
3
+ import { getSettings, readConfig, type Credentials, type ResolvedSettings } from "./src/infra/settings";
4
4
  import { startBot, type BotState, type RunningBot } from "./src/qq/qq-bot";
5
- import { runQrLogin } from "./src/qq/qr-login";
5
+ import { runQrLogin, type QrLoginResult } from "./src/qq/qr-login";
6
6
  import { createInboundHandler } from "./src/qq/qq-message-handler";
7
+ import { registerQQDiagnostics } from "./src/qq/qq-diagnostics";
7
8
  import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
8
9
  import { ReplyBudget } from "./src/quota/reply-quota";
9
10
  import { RunFeedback } from "./src/relay/run-stream-relay";
10
- import { AppendStream } from "./src/relay/stream-session";
11
11
  import { formatTokenCount } from "./src/infra/display-format";
12
- import { formatBudgetStatus } from "./src/quota/reply-quota-report";
13
12
  import { configureLogger, log, previewForLog } from "./src/infra/file-logger";
14
13
  import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
15
14
 
@@ -35,11 +34,12 @@ let running: RunningBot | undefined;
35
34
  let lastState: BotState = "stopped";
36
35
  let stateDetail: string | undefined;
37
36
  let sessionCtx: ExtensionContext | undefined;
37
+ let activeSettings: ResolvedSettings = getSettings({});
38
38
  const budget = new ReplyBudget();
39
39
  const runFeedback = new RunFeedback({
40
40
  bot: () => running?.bot,
41
41
  budget,
42
- getThinkingRelay: () => getSettings(readConfig().config).thinkingRelay,
42
+ getThinkingRelay: () => activeSettings.thinkingRelay,
43
43
  onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
44
44
  });
45
45
 
@@ -49,15 +49,21 @@ export default function (pi: ExtensionAPI) {
49
49
  const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
50
50
 
51
51
  const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
52
- const getBoundOpenid = getAllowedOpenid;
53
- const getDeliverAs = () => getSettings(readConfig().config).deliverAs;
52
+ const getDeliverAs = () => activeSettings.deliverAs;
54
53
 
55
54
  const onWarn = (ctx: ExtensionContext) => (msg: string) => ctx.ui.notify(`pi-qq ${msg}`, "warning");
56
55
 
57
- const getStatusLines = (): string[] => {
56
+ const applyConfig = (ctx: ExtensionContext) => {
57
+ const { config, error } = readConfig();
58
+ activeSettings = getSettings(config);
59
+ if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
60
+ return { settings: activeSettings, error };
61
+ };
62
+
63
+ const getStatusLines = (ctx: ExtensionContext | undefined = sessionCtx): string[] => {
58
64
  const login = getLoginState();
59
- const usage = sessionCtx?.getContextUsage();
60
- const model = sessionCtx?.model;
65
+ const usage = ctx?.getContextUsage();
66
+ const model = ctx?.model;
61
67
  return [
62
68
  "pi-qq status",
63
69
  `Login: ${login ? `QR login, in memory (AppID ${maskAppId(login.credentials.appId)})` : "not logged in"}`,
@@ -71,10 +77,19 @@ export default function (pi: ExtensionAPI) {
71
77
  ];
72
78
  };
73
79
 
80
+ const stopIfRunning = () => {
81
+ running?.stop();
82
+ running = undefined;
83
+ lastState = "stopped";
84
+ stateDetail = undefined;
85
+ sessionCtx = undefined;
86
+ runFeedback.dispose();
87
+ };
88
+
74
89
  const startWithCredentials = async (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
75
- const settings = getSettings(readConfig().config);
90
+ const settings = activeSettings;
76
91
  configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
77
- running?.stop();
92
+ stopIfRunning();
78
93
  stateDetail = undefined;
79
94
  sessionCtx = ctx;
80
95
  const uploadDir = sessionUploadDir(ctx.cwd, ctx.sessionManager.getSessionId());
@@ -96,10 +111,8 @@ export default function (pi: ExtensionAPI) {
96
111
  ctx,
97
112
  budget,
98
113
  getAllowedOpenid,
99
- getBoundOpenid,
100
114
  getDeliverAs,
101
- getImageMaxSize: () => getSettings(readConfig().config).imageMaxSize,
102
- getFileMaxSize: () => getSettings(readConfig().config).fileMaxSize,
115
+ getFileMaxSize: () => activeSettings.fileMaxSize,
103
116
  getStatusLines,
104
117
  onWarn: onWarn(ctx),
105
118
  markQQTrigger: (openid, msgId) => runFeedback.markQQTrigger(openid, msgId),
@@ -116,18 +129,9 @@ export default function (pi: ExtensionAPI) {
116
129
  });
117
130
  };
118
131
 
119
- const stopIfRunning = () => {
120
- running?.stop();
121
- running = undefined;
122
- lastState = "stopped";
123
- stateDetail = undefined;
124
- };
125
-
126
132
  pi.on("session_start", async (_event, ctx) => {
127
- const { config, error } = readConfig();
128
- const settings = getSettings(config);
133
+ const { settings, error } = applyConfig(ctx);
129
134
  configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
130
- if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
131
135
 
132
136
  const login = getLoginState();
133
137
  log.info("session", "started", {
@@ -148,8 +152,6 @@ export default function (pi: ExtensionAPI) {
148
152
  pi.on("session_shutdown", () => {
149
153
  log.info("session", "shutting down");
150
154
  stopIfRunning();
151
- sessionCtx = undefined;
152
- runFeedback.dispose();
153
155
  });
154
156
 
155
157
  pi.on("agent_start", () => {
@@ -255,12 +257,10 @@ export default function (pi: ExtensionAPI) {
255
257
  pi.registerCommand("qq-login", {
256
258
  description: "pi-qq: log in with a QR code and bind the scanning QQ user",
257
259
  handler: async (_args, ctx) => {
258
- const { error } = readConfig();
259
- if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
260
-
260
+ applyConfig(ctx);
261
261
  stopIfRunning();
262
262
  setLoginState(undefined);
263
- let result;
263
+ let result: QrLoginResult | undefined;
264
264
  try {
265
265
  result = await runQrLogin(ctx);
266
266
  } catch (err) {
@@ -289,14 +289,7 @@ export default function (pi: ExtensionAPI) {
289
289
  pi.registerCommand("qq-status", {
290
290
  description: "pi-qq: show login, connection, and bound QQ user",
291
291
  handler: async (_args, ctx) => {
292
- ctx.ui.notify(getStatusLines().join("\n"), "info");
293
- },
294
- });
295
-
296
- pi.registerCommand("qq-test-budget", {
297
- description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
298
- handler: async (_args, ctx) => {
299
- ctx.ui.notify(formatBudgetStatus(budget.snapshot(), budget.lastTarget).join("\n"), "info");
292
+ ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
300
293
  },
301
294
  });
302
295
 
@@ -321,97 +314,9 @@ export default function (pi: ExtensionAPI) {
321
314
  },
322
315
  });
323
316
 
324
- const diagTarget = () => {
325
- const last = budget.lastTarget;
326
- if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
327
- const bound = getLoginState()?.allowedOpenid;
328
- return bound ? { scope: "c2c" as const, targetId: bound } : undefined;
329
- };
330
-
331
- pi.registerCommand("qq-test-md", {
332
- description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
333
- handler: async (args, ctx) => {
334
- if (!running) {
335
- ctx.ui.notify("pi-qq is not connected.", "warning");
336
- return;
337
- }
338
- const target = diagTarget();
339
- if (!target) {
340
- ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
341
- return;
342
- }
343
- const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
344
- try {
345
- await running.bot.sendMarkdown(target, content);
346
- ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
347
- } catch (err) {
348
- ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
349
- }
350
- },
351
- });
352
-
353
- pi.registerCommand("qq-test-stream", {
354
- description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text) or resume probe",
355
- handler: async (args, ctx) => {
356
- if (!running) {
357
- ctx.ui.notify("pi-qq is not connected.", "warning");
358
- return;
359
- }
360
- const last = budget.lastTarget;
361
- if (!last) {
362
- ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
363
- return;
364
- }
365
- const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
366
- try {
367
- if (args?.trim() === "resume") {
368
- const first = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
369
- await first.append("**Resume probe** frame 1\n");
370
- await first.flush();
371
- const checkpoint = first.checkpoint();
372
- first.dispose();
373
- if (!checkpoint?.streamMsgId) {
374
- ctx.ui.notify("Resume probe: frame 1 sent but stream_msg_id is missing; cannot resume.", "error");
375
- return;
376
- }
377
- await sleep(800);
378
- const second = new AppendStream(
379
- running.bot.messageApi,
380
- running.bot.getCredentials(),
381
- last.openid,
382
- last.msgId,
383
- {
384
- resume: checkpoint,
385
- },
386
- );
387
- await second.append("frame 2 after resume\n");
388
- await second.done();
389
- ctx.ui.notify(
390
- `Resume probe: frame 2 sent with index ${checkpoint.index} and stream_msg_id ${checkpoint.streamMsgId}. Check whether both frames are in the same bubble.`,
391
- "info",
392
- );
393
- return;
394
- }
395
- const stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
396
- await stream.append(
397
- "**💭 思考**\n\nprobe thinking\nsecond line\n\n**💻 bash**\n\n`echo probe`\n\n```text\nprobe\n```\n",
398
- );
399
- await sleep(1200);
400
- await stream.append("\n**Intermediate message**: first-turn reply.\n");
401
- await sleep(1200);
402
- await stream.append("\n**📖 read**\n\n`src/index.ts`\n\n```text\nprobe file\n```\n");
403
- await sleep(800);
404
- await stream.append("\n**Final reply** (streamed append)");
405
- let doneNote = "DONE succeeded";
406
- try {
407
- await stream.done();
408
- } catch (doneErr) {
409
- doneNote = `DONE rejected: ${(doneErr as Error).message}`;
410
- }
411
- ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
412
- } catch (err) {
413
- ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
414
- }
415
- },
317
+ registerQQDiagnostics(pi, {
318
+ getRunning: () => running,
319
+ budget,
320
+ getBoundOpenid: () => getLoginState()?.allowedOpenid,
416
321
  });
417
322
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chen_hu_hu/pi-qq",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "Connect pi to QQ private chats.",
5
5
  "license": "MIT",
6
6
  "author": "CQ-Developer",
@@ -22,6 +22,9 @@
22
22
  "tencent"
23
23
  ],
24
24
  "type": "module",
25
+ "engines": {
26
+ "node": ">=22.19.0"
27
+ },
25
28
  "publishConfig": {
26
29
  "access": "public"
27
30
  },
@@ -0,0 +1,12 @@
1
+ export interface AttachmentFailure {
2
+ filename: string;
3
+ reason: string;
4
+ }
5
+
6
+ export function formatAttachmentFailures(failures: readonly AttachmentFailure[], successCount: number): string {
7
+ const title =
8
+ successCount > 0
9
+ ? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
10
+ : "⚠️ Attachment failed:";
11
+ return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
12
+ }
@@ -1,7 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
3
- import { basename, extname, join } from "node:path";
3
+ import { basename, extname, join, relative } from "node:path";
4
4
  import { downloadLimited, type InboundAttachmentLike } from "./attachment-download";
5
+ import type { AttachmentFailure } from "./attachment-failure";
5
6
  import { formatBytes } from "../infra/display-format";
6
7
  import { log } from "../infra/file-logger";
7
8
 
@@ -10,13 +11,6 @@ const UPLOAD_INDEX_FILENAME = ".index.json";
10
11
 
11
12
  export interface SavedFile {
12
13
  path: string;
13
- originalName: string;
14
- size: number;
15
- }
16
-
17
- export interface FileFailure {
18
- filename: string;
19
- reason: string;
20
14
  }
21
15
 
22
16
  export type UploadIndex = Record<string, string>;
@@ -30,7 +24,7 @@ export interface SaveFilesOptions {
30
24
 
31
25
  export interface SaveFilesResult {
32
26
  files: SavedFile[];
33
- failures: FileFailure[];
27
+ failures: AttachmentFailure[];
34
28
  }
35
29
 
36
30
  function safePathSegment(key: string): string {
@@ -89,7 +83,7 @@ async function isFile(path: string): Promise<boolean> {
89
83
  }
90
84
  }
91
85
 
92
- export async function loadUploadIndex(uploadDir: string): Promise<UploadIndex> {
86
+ async function loadUploadIndex(uploadDir: string): Promise<UploadIndex> {
93
87
  try {
94
88
  const parsed = JSON.parse(await readFile(uploadIndexPath(uploadDir), "utf8")) as unknown;
95
89
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
@@ -148,7 +142,7 @@ async function saveOrReuse(
148
142
  }
149
143
  await writeFile(target, body, { flag: "wx" });
150
144
  index[filename] = hash;
151
- return { file: { path: target, originalName: filename, size: body.byteLength }, changed: true };
145
+ return { file: { path: target }, changed: true };
152
146
  }
153
147
 
154
148
  let existingHash = index[filename];
@@ -158,7 +152,7 @@ async function saveOrReuse(
158
152
  changed = true;
159
153
  }
160
154
  if (existingHash === hash) {
161
- return { file: { path: target, originalName: filename, size: body.byteLength }, changed };
155
+ return { file: { path: target }, changed };
162
156
  }
163
157
 
164
158
  for (let suffix = 1; suffix < 100; suffix++) {
@@ -172,7 +166,7 @@ async function saveOrReuse(
172
166
  changed = true;
173
167
  }
174
168
  if (candidateHash === hash) {
175
- return { file: { path: candidatePath, originalName: candidate, size: body.byteLength }, changed };
169
+ return { file: { path: candidatePath }, changed };
176
170
  }
177
171
  continue;
178
172
  }
@@ -182,7 +176,7 @@ async function saveOrReuse(
182
176
  }
183
177
  await writeFile(candidatePath, body, { flag: "wx" });
184
178
  index[candidate] = hash;
185
- return { file: { path: candidatePath, originalName: candidate, size: body.byteLength }, changed: true };
179
+ return { file: { path: candidatePath }, changed: true };
186
180
  }
187
181
 
188
182
  throw new Error("Could not allocate a unique filename");
@@ -197,7 +191,7 @@ export async function saveInboundFiles(
197
191
  const fetchImpl = options.fetchImpl ?? fetch;
198
192
  const index = options.index ?? (await loadUploadIndex(uploadDir));
199
193
  const files: SavedFile[] = [];
200
- const failures: FileFailure[] = [];
194
+ const failures: AttachmentFailure[] = [];
201
195
  const seenPaths = new Set<string>();
202
196
  let indexChanged = false;
203
197
 
@@ -237,14 +231,17 @@ export async function saveInboundFiles(
237
231
  return { files, failures };
238
232
  }
239
233
 
240
- export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
234
+ export function formatAttachmentPrompt(files: readonly SavedFile[], userText: string, cwd: string): string {
241
235
  if (files.length === 0) return userText;
242
236
 
243
237
  const lines = [
244
- "User sent the following file(s) via QQ (saved locally; use read/bash or other tools to access):",
245
- ...files.map((file) => `- ${file.path} (${formatBytes(file.size)}, original name: ${file.originalName})`),
238
+ "# Attachments:",
239
+ ...files.map((file) => {
240
+ const displayPath = relative(cwd, file.path);
241
+ return `- ${displayPath && !displayPath.startsWith("..") ? displayPath : file.path}`;
242
+ }),
246
243
  ];
247
244
  const text = userText.trim();
248
- if (text) lines.push("", "User message:", text);
245
+ if (text) lines.push("", "# User message:", text);
249
246
  return lines.join("\n");
250
247
  }
@@ -108,9 +108,6 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
108
108
  }
109
109
 
110
110
  export const log = {
111
- get level(): LogLevel {
112
- return activeLevel;
113
- },
114
111
  debug(scope: string, message: string, data?: unknown): void {
115
112
  writeRecord("debug", scope, message, data);
116
113
  },
@@ -6,22 +6,77 @@ import { normalizeLogLevel, type LogLevel } from "./file-logger";
6
6
  export interface PiQQSettings {
7
7
  thinkingRelay?: boolean;
8
8
  deliverAs?: "steer" | "followUp";
9
- imageMaxSize?: number;
10
9
  fileMaxSize?: number;
11
10
  logLevel?: LogLevel;
12
11
  debug?: boolean;
13
12
  }
14
13
 
15
- export type PiQQConfig = PiQQSettings;
16
-
17
14
  export interface Credentials {
18
15
  appId: string;
19
16
  appSecret: string;
20
17
  }
21
18
 
22
- export const CONFIG_PATH = join(homedir(), ".pi", "agent", "pi-qq.json");
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
+ }
23
78
 
24
- export function readConfig(): { config: PiQQConfig; error?: string } {
79
+ export function readConfig(): ReadConfigResult {
25
80
  let raw: string;
26
81
  try {
27
82
  raw = readFileSync(CONFIG_PATH, "utf8");
@@ -29,7 +84,7 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
29
84
  return { config: {} };
30
85
  }
31
86
  try {
32
- return { config: JSON.parse(raw) as PiQQConfig };
87
+ return parseConfig(JSON.parse(raw));
33
88
  } catch (e) {
34
89
  return { config: {}, error: `Failed to parse config file (${CONFIG_PATH}): ${(e as Error).message}` };
35
90
  }
@@ -37,12 +92,11 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
37
92
 
38
93
  export type ResolvedSettings = Required<Omit<PiQQSettings, "debug">>;
39
94
 
40
- export function getSettings(config: PiQQConfig): ResolvedSettings {
95
+ export function getSettings(config: PiQQSettings): ResolvedSettings {
41
96
  const logLevel = normalizeLogLevel(config.logLevel ?? (config.debug ? "debug" : undefined));
42
97
  return {
43
98
  thinkingRelay: config.thinkingRelay ?? true,
44
99
  deliverAs: config.deliverAs ?? "steer",
45
- imageMaxSize: config.imageMaxSize ?? 10 * 1024 * 1024,
46
100
  fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
47
101
  logLevel,
48
102
  };
package/src/qq/qq-bot.ts CHANGED
@@ -14,7 +14,7 @@ export type BotState = "stopped" | "starting" | "connected" | "reconnecting" | "
14
14
 
15
15
  export interface StartBotOptions {
16
16
  credentials: Credentials;
17
- allowedOpenid?: string;
17
+ allowedOpenid: string;
18
18
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
19
19
  onStateChange?: (state: BotState, detail?: string) => void;
20
20
  }
@@ -38,7 +38,7 @@ export function startBot(opts: StartBotOptions): RunningBot {
38
38
 
39
39
  bot.use(messageFilter({ skipSelfEcho: true }));
40
40
  bot.use(contentSanitizer({ stripBotMention: true }));
41
- bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
41
+ bot.use(accessPolicy({ c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } }));
42
42
  bot.use(concurrencyGuard());
43
43
 
44
44
  const report = (state: BotState, detail?: string) => {
@@ -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
+ }