@chen_hu_hu/pi-qq 1.0.0 → 1.0.2

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/src/bot.ts CHANGED
@@ -10,36 +10,36 @@ import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
10
10
  import type { Credentials } from "./config";
11
11
 
12
12
  /**
13
- * QQBot 实例的会话级生命周期管理:
14
- * 创建、中间件装配、连接状态跟踪、终态错误上报。
15
- * start() 阻塞至 stop()/abort,因此在后台运行(void 不等待)。
13
+ * Session-level QQBot lifecycle: creation, middleware, connection state,
14
+ * and fatal-error reporting. start() blocks until stop()/abort, so it runs
15
+ * in the background (void, not awaited).
16
16
  */
17
17
 
18
18
  export type BotState =
19
- | "stopped" // 未运行 / 已停止
20
- | "starting" // 已发起连接,等待 READY
21
- | "connected" // 在线(READY / RESUMED)
22
- | "reconnecting" // 断线,SDK 自动重连中
23
- | "blocked"; // 致命关闭(4914 下线 / 4915 封禁),需人工介入
19
+ | "stopped" // Not running/stopped
20
+ | "starting" // Connecting, waiting for READY
21
+ | "connected" // Online (READY/RESUMED)
22
+ | "reconnecting" // Disconnected; the SDK is reconnecting
23
+ | "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
24
24
 
25
25
  export interface StartBotOptions {
26
26
  credentials: Credentials;
27
- /** F2 单人绑定;未提供时 accessPolicy 放行,由 M2 的"首个私聊用户自动绑定"兜底 */
27
+ /** F2: QR-bound single user; production always provides it */
28
28
  allowedOpenid?: string;
29
29
  markdownSupport?: boolean;
30
- /** 诊断模式:SDK 内部日志(超时/限流/重连等)打到终端 */
30
+ /** Debug mode: print SDK logs (timeouts/rate limits/reconnects) to the terminal. */
31
31
  debug?: boolean;
32
- /** 入站消息接线点(M2 起;M1 为空) */
32
+ /** Inbound message handler. */
33
33
  onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
34
- /** 连接状态变化(UI 通知由调用方决定) */
34
+ /** Connection state changes; the caller decides how to notify the UI. */
35
35
  onStateChange?: (state: BotState, detail?: string) => void;
36
- /** 可恢复错误(SDK 自动重连,不打扰用户) */
36
+ /** Recoverable errors; the SDK reconnects automatically. */
37
37
  onRecoverableError?: (err: Error) => void;
38
38
  }
39
39
 
40
40
  export interface RunningBot {
41
41
  bot: QQBot;
42
- /** 幂等停止 */
42
+ /** Idempotent stop. */
43
43
  stop: () => void;
44
44
  }
45
45
 
@@ -50,13 +50,13 @@ export function startBot(opts: StartBotOptions): RunningBot {
50
50
  markdownSupport: opts.markdownSupport ?? false,
51
51
  });
52
52
 
53
- // 回声过滤 + 消息去重(SDK 默认 5s 窗口)
53
+ // Echo filtering + message deduplication (SDK default 5s window).
54
54
  bot.use(messageFilter({ skipSelfEcho: true }));
55
- // 清洗 @marker / face tags 等协议标记,只留纯文本
55
+ // Strip protocol markers such as @mentions and face tags.
56
56
  bot.use(contentSanitizer({ stripBotMention: true }));
57
- // 单人白名单:仅 C2C 生效;未绑定时放行(自动绑定逻辑在 inbound 层)
57
+ // Single-user allowlist for C2C; inbound also rejects when no QR login is active.
58
58
  bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
59
- // 同用户串行处理,避免流式与回复互相踩踏
59
+ // Serialize per user so streams and replies do not race.
60
60
  bot.use(concurrencyGuard());
61
61
 
62
62
  const report = (state: BotState, detail?: string) => opts.onStateChange?.(state, detail);
@@ -72,19 +72,19 @@ export function startBot(opts: StartBotOptions): RunningBot {
72
72
  let stopped = false;
73
73
  report("starting");
74
74
  void bot.start().catch((err: unknown) => {
75
- if (stopped) return; // 主动 stop() 的正常返回,不算错误
75
+ if (stopped) return; // Normal return from an explicit stop().
76
76
  const code = (err as { code?: string }).code;
77
77
  if (code === GatewayErrorCode.FATAL_CLOSE) {
78
78
  const closeCode = (err as { closeCode?: number }).closeCode;
79
79
  report(
80
80
  "blocked",
81
- `连接被服务端致命关闭(${closeCode ?? "未知关闭码"},4914=已下线/仅沙箱、4915=封禁):` +
82
- `请到 QQ 开放平台确认机器人状态,或 /qq-login 重新换绑`,
81
+ `Connection closed by the server (${closeCode ?? "unknown"}, 4914=offline/sandbox, 4915=banned). ` +
82
+ `Check the bot status on the QQ Open Platform, or run /qq-login again.`,
83
83
  );
84
84
  } else if (code === GatewayErrorCode.RETRY_EXHAUSTED) {
85
- report("stopped", `重连预算耗尽:${(err as Error).message};可执行 /qq-login 重试`);
85
+ report("stopped", `Reconnect budget exhausted: ${(err as Error).message}; run /qq-login to retry.`);
86
86
  } else {
87
- report("stopped", `启动失败:${(err as Error).message};请检查凭据与网络`);
87
+ report("stopped", `Startup failed: ${(err as Error).message}; check credentials and network.`);
88
88
  }
89
89
  });
90
90
 
@@ -10,7 +10,7 @@ function mask(value: string): string {
10
10
  return `${value.slice(0, 8)}…`;
11
11
  }
12
12
 
13
- /** 生成 `/qq-budget` 的显示行;纯函数便于单测 */
13
+ /** Render `/qq-test-budget` output lines; pure function for tests. */
14
14
  export function formatBudgetStatus(
15
15
  snapshot: BudgetSnapshot,
16
16
  last: BudgetTarget | undefined,
@@ -20,13 +20,13 @@ export function formatBudgetStatus(
20
20
  const estimated = snapshot.hasTarget ? Math.max(0, snapshot.remaining - snapshot.streamBubbles) : null;
21
21
 
22
22
  return [
23
- "pi-qq 被动回复预算",
24
- `上限:${snapshot.limit} 条/msg(${snapshot.ttlHours}h)`,
25
- `最近入站:${last ? `${mask(last.openid)} / ${mask(last.msgId)},${ageSec}s 前` : "无"}`,
26
- `普通被动剩余:${snapshot.hasTarget ? snapshot.remaining : "—"}`,
27
- `流式气泡:${snapshot.streamBubbles} 条(当前 msgId)`,
28
- `估算剩余:${estimated ?? "—"} 条(仅诊断)`,
29
- `msgId 窗口:${snapshot.hasTarget ? (snapshot.fresh ? "有效" : "已过期") : "—"}`,
30
- `已记录:普通 ${snapshot.totalReplies} 条 / 流式 ${snapshot.streamBubblesTotal} 条 / 跟踪 ${snapshot.trackedMessages} 个 msgId`,
23
+ "pi-qq passive reply budget",
24
+ `Limit: ${snapshot.limit}/msg (${snapshot.ttlHours}h)`,
25
+ `Last inbound: ${last ? `${mask(last.openid)} / ${mask(last.msgId)}, ${ageSec}s ago` : "none"}`,
26
+ `Passive remaining: ${snapshot.hasTarget ? snapshot.remaining : "—"}`,
27
+ `Stream bubbles: ${snapshot.streamBubbles} (current msgId)`,
28
+ `Estimated remaining: ${estimated ?? "—"} (diagnostic only)`,
29
+ `msgId window: ${snapshot.hasTarget ? (snapshot.fresh ? "valid" : "expired") : "—"}`,
30
+ `Recorded: passive ${snapshot.totalReplies} / stream ${snapshot.streamBubblesTotal} / ${snapshot.trackedMessages} msgId(s)`,
31
31
  ];
32
32
  }
package/src/config.ts CHANGED
@@ -1,52 +1,42 @@
1
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { dirname, join } from "node:path";
3
+ import { join } from "node:path";
4
4
 
5
5
  /**
6
- * ~/.pi/agent/pi-qq.json 的类型与读写。
6
+ * ~/.pi/agent/pi-qq.json contains non-secret settings only.
7
7
  *
8
- * 凭据键名以用户手写 schema(AppID/AppSecret)为准,读取时兼容小写;
9
- * 扩展写入(扫码成功后)统一归一化为大写键名,避免同一文件里出现两套键。
8
+ * QQ credentials are intentionally never written to disk: QR login keeps them in
9
+ * process memory, so restarting pi requires scanning a new QR code.
10
10
  */
11
11
 
12
- /** 可调设置(features.md §4),与凭据共存于同一文件。 */
12
+ /** Runtime settings (features-v1.md §4). */
13
13
  export interface PiQQSettings {
14
- /** F4:assistant 流式回传开关 */
14
+ /** F4: stream assistant replies */
15
15
  streamAssistant?: boolean;
16
- /** F4:机器人是否有 markdown 权限;true 时回传透传 Markdown */
16
+ /** F4: bot has QQ markdown permission; pass Markdown through when true */
17
17
  markdownSupport?: boolean;
18
- /** F5/F6:用量摘要(本次 run token/缓存命中率/上下文占比)开关 */
19
- usageRelay?: boolean;
20
- /** F2:agent 忙碌时新消息的处理方式 */
18
+ /** F2: how a busy agent handles new messages */
21
19
  deliverAs?: "steer" | "followUp";
22
- /** F3:QQ 图片下载上限(字节) */
20
+ /** F3: QQ image download limit (bytes) */
23
21
  imageMaxSize?: number;
24
- /** F3:QQ 文件下载上限(字节);默认 50MB */
22
+ /** F3: QQ file download limit (bytes), default 50MB */
25
23
  fileMaxSize?: number;
26
- /** F7:节流心跳间隔(分钟),0 关闭 */
24
+ /** F7: heartbeat interval in minutes, 0 disables */
27
25
  heartbeatMinutes?: number;
28
- /** F7:每 run 消息心跳上限(流式心跳不受限) */
26
+ /** F7: per-run message heartbeat limit */
29
27
  heartbeatMaxMessages?: number;
30
- /** F7:流式汇总帧间隔(毫秒,最小 300,默认 10s);帧内容为窗口内思考/工具计数/文本增量 */
28
+ /** F7: stream summary frame interval (ms, minimum 300) */
31
29
  streamFlushMs?: number;
32
- /** 诊断模式:SDK 内部日志打到终端 + 文本帧也带时间戳(定位超时/限流用) */
30
+ /** Diagnostic mode: SDK logs + stream retry/timeout logs */
33
31
  debug?: boolean;
34
- /** F7:流式载体开关。QQ stream_messages 仅支持 markdown 内容(无权限时帧被接受但不渲染),
35
- * 无 markdown 权限的机器人必须保持 false(实测:气泡停在 "..." 且结果被流接管丢失) */
32
+ /** F7: append-mode stream relay switch */
36
33
  streamRelay?: boolean;
37
34
  }
38
35
 
39
- /** 完整配置文件结构:凭据 + 单人绑定 + 可调设置。 */
40
- export interface PiQQConfig extends PiQQSettings {
41
- AppID?: string;
42
- AppSecret?: string;
43
- /** 兼容小写写法(仅读取) */
44
- appId?: string;
45
- appSecret?: string;
46
- /** F2:单人绑定的 openid 白名单 */
47
- allowedOpenid?: string;
48
- }
36
+ /** Settings file schema (legacy credential keys are ignored). */
37
+ export type PiQQConfig = PiQQSettings;
49
38
 
39
+ /** QR login result; kept in memory only. */
50
40
  export interface Credentials {
51
41
  appId: string;
52
42
  appSecret: string;
@@ -54,7 +44,7 @@ export interface Credentials {
54
44
 
55
45
  export const CONFIG_PATH = join(homedir(), ".pi", "agent", "pi-qq.json");
56
46
 
57
- /** 读配置;文件不存在视为空配置,JSON 损坏时返回 error(调用方不得覆盖写入)。 */
47
+ /** Read settings; missing file yields empty settings, malformed JSON returns an error. */
58
48
  export function readConfig(): { config: PiQQConfig; error?: string } {
59
49
  let raw: string;
60
50
  try {
@@ -65,64 +55,17 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
65
55
  try {
66
56
  return { config: JSON.parse(raw) as PiQQConfig };
67
57
  } catch (e) {
68
- return { config: {}, error: `配置文件解析失败(${CONFIG_PATH}):${(e as Error).message}` };
58
+ return { config: {}, error: `Failed to parse config file (${CONFIG_PATH}): ${(e as Error).message}` };
69
59
  }
70
60
  }
71
61
 
72
- /** 从配置提取机器人凭据(大写/小写键均可),不完整返回 null。 */
73
- export function getCredentials(config: PiQQConfig): Credentials | null {
74
- const appId = config.AppID ?? config.appId;
75
- const appSecret = config.AppSecret ?? config.appSecret;
76
- if (appId && appSecret) return { appId, appSecret };
77
- return null;
78
- }
79
-
80
- function writeConfig(config: PiQQConfig): void {
81
- mkdirSync(dirname(CONFIG_PATH), { recursive: true });
82
- // mode 只在新建文件时生效,已存在文件需显式 chmod 回 0600
83
- writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
84
- chmodSync(CONFIG_PATH, 0o600);
85
- }
86
-
87
- /** 写入凭据(归一化为大写键名,清除兼容小写键);userOpenid 提供时覆盖单人绑定。 */
88
- export function saveCredentials(creds: Credentials, opts?: { userOpenid?: string }): void {
89
- const { config, error } = readConfig();
90
- if (error) throw new Error(`拒绝写入:${error}`);
91
- delete config.appId;
92
- delete config.appSecret;
93
- config.AppID = creds.appId;
94
- config.AppSecret = creds.appSecret;
95
- if (opts?.userOpenid) config.allowedOpenid = opts.userOpenid;
96
- writeConfig(config);
97
- }
98
-
99
- /** /qq-logout:清除凭据,保留 allowedOpenid 与其余设置(下次登录同一用户无需重配)。 */
100
- export function clearCredentials(): void {
101
- const { config, error } = readConfig();
102
- if (error) return;
103
- delete config.AppID;
104
- delete config.AppSecret;
105
- delete config.appId;
106
- delete config.appSecret;
107
- writeConfig(config);
108
- }
109
-
110
- /** F2 的"首个私聊用户自动绑定"(M2 接线使用)。 */
111
- export function setAllowedOpenid(openid: string): void {
112
- const { config, error } = readConfig();
113
- if (error) return;
114
- config.allowedOpenid = openid;
115
- writeConfig(config);
116
- }
117
-
118
62
  export interface ResolvedSettings extends Required<PiQQSettings> {}
119
63
 
120
- /** 填充默认值后的设置视图(features.md §4 默认列)。 */
64
+ /** Settings with defaults applied (features-v1.md §4). */
121
65
  export function getSettings(config: PiQQConfig): ResolvedSettings {
122
66
  return {
123
67
  streamAssistant: config.streamAssistant ?? true,
124
68
  markdownSupport: config.markdownSupport ?? false,
125
- usageRelay: config.usageRelay ?? true,
126
69
  deliverAs: config.deliverAs ?? "steer",
127
70
  imageMaxSize: config.imageMaxSize ?? 10 * 1024 * 1024,
128
71
  fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
@@ -130,7 +73,6 @@ export function getSettings(config: PiQQConfig): ResolvedSettings {
130
73
  heartbeatMaxMessages: config.heartbeatMaxMessages ?? 3,
131
74
  streamFlushMs: config.streamFlushMs ?? 10_000,
132
75
  debug: config.debug ?? false,
133
- // append 语义已实测可用(含节流与限流退避);失败自动降级消息路径,默认开启
134
76
  streamRelay: config.streamRelay ?? true,
135
77
  };
136
78
  }
package/src/download.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { formatBytes } from "./format";
2
2
 
3
- /** QQ 入站附件的最小结构(图片与文件共用)。 */
3
+ /** Minimal QQ inbound attachment shape shared by images and files. */
4
4
  export interface InboundAttachmentLike {
5
5
  content_type: string;
6
6
  url: string;
@@ -12,7 +12,7 @@ export interface DownloadOptions {
12
12
  url: string;
13
13
  maxSize: number;
14
14
  timeoutMs: number;
15
- /** 错误文案中的类型名,如“图片”/“文件” */
15
+ /** Kind label used in errors, e.g. "image" or "file". */
16
16
  kind: string;
17
17
  fetchImpl?: typeof fetch;
18
18
  }
@@ -48,7 +48,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
48
48
  return Buffer.concat(chunks, total);
49
49
  }
50
50
 
51
- /** 带超时与流式大小上限的附件下载。 */
51
+ /** Download an attachment with a timeout and streaming size cap. */
52
52
  export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
53
53
  const limit = Math.max(1, opts.maxSize);
54
54
  let parsed: URL;
package/src/files.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** QQ 非图片附件 → 当前工作空间保存,并在提示词中给出路径供 pi 使用。 */
1
+ /** Save QQ non-image attachments in the workspace and reference them in the prompt. */
2
2
  import { mkdir, writeFile } from "node:fs/promises";
3
3
  import { basename, extname, join } from "node:path";
4
4
  import { downloadLimited, type InboundAttachmentLike } from "./download";
@@ -20,9 +20,9 @@ export interface FileFailure {
20
20
 
21
21
  export interface SaveFilesOptions {
22
22
  maxSize: number;
23
- /** 测试可覆盖;默认 <cwd>/.pi/pi-qq */
23
+ /** Test override; defaults to <cwd>/.pi/pi-qq. */
24
24
  baseDir?: string;
25
- /** 用于隔离同一消息的文件目录(通常传 msgId) */
25
+ /** Directory key for one message (usually msgId). */
26
26
  dirKey?: string;
27
27
  now?: Date;
28
28
  fetchImpl?: typeof fetch;
@@ -47,7 +47,7 @@ function withSuffix(filename: string, suffix: number): string {
47
47
  return `${stem}-${suffix}${ext}`;
48
48
  }
49
49
 
50
- /** 只保留安全文件名(去掉路径、控制符和 Windows 非法字符),超长时截断 stem。 */
50
+ /** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
51
51
  export function sanitizeFilename(filename: string | undefined, fallback: string): string {
52
52
  const raw = basename((filename ?? "").trim());
53
53
  const cleaned = raw
@@ -81,7 +81,7 @@ async function writeUnique(dir: string, filename: string, body: Buffer): Promise
81
81
  throw new Error("无法分配唯一文件名");
82
82
  }
83
83
 
84
- /** 将非图片附件按原顺序保存到本地,单文件失败不影响其他文件。 */
84
+ /** Save non-image attachments in order; one failure does not stop the others. */
85
85
  export async function saveInboundFiles(
86
86
  attachments: readonly InboundAttachmentLike[],
87
87
  options: SaveFilesOptions,
@@ -124,15 +124,15 @@ export async function saveInboundFiles(
124
124
  return { files, failures };
125
125
  }
126
126
 
127
- /** 将保存路径与用户原消息组合成 pi 提示词。 */
127
+ /** Combine saved paths and the original user message into the pi prompt. */
128
128
  export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
129
129
  if (files.length === 0) return userText;
130
130
 
131
131
  const lines = [
132
- "用户通过 QQ 发送了以下文件(已保存到本机,可用 read/bash 等工具访问):",
133
- ...files.map((file) => `- ${file.path}(${formatBytes(file.size)},原始名:${file.originalName})`),
132
+ "User sent the following file(s) via QQ (saved locally; use read/bash or other tools to access):",
133
+ ...files.map((file) => `- ${file.path} (${formatBytes(file.size)}, original name: ${file.originalName})`),
134
134
  ];
135
135
  const text = userText.trim();
136
- if (text) lines.push("", "用户消息:", text);
136
+ if (text) lines.push("", "User message:", text);
137
137
  return lines.join("\n");
138
138
  }
package/src/format.ts CHANGED
@@ -1,6 +1,11 @@
1
- /** 人类可读的大小格式化,供图片/文件下载与提示词共享。 */
1
+ /** Human-readable size formatting shared by image/file downloads and prompts. */
2
2
  export function formatBytes(bytes: number): string {
3
3
  if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
4
4
  if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)}KB`;
5
5
  return `${bytes}B`;
6
6
  }
7
+
8
+ /** Compact token count used by /qq-status. */
9
+ export function formatTokenCount(n: number): string {
10
+ return n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, "")}k` : String(n);
11
+ }
package/src/images.ts CHANGED
@@ -1,4 +1,4 @@
1
- /** QQ 图片附件 → pi ImageContent:类型/大小校验、带超时的受限下载。 */
1
+ /** QQ image attachments to pi ImageContent: validation and timeout-limited download. */
2
2
  import { downloadLimited, type InboundAttachmentLike } from "./download";
3
3
  import { formatBytes } from "./format";
4
4
 
@@ -44,12 +44,12 @@ const MIME_BY_EXTENSION: Record<string, string> = {
44
44
  gif: "image/gif",
45
45
  };
46
46
 
47
- /** 按 content_type 优先、文件名扩展名兜底,返回可注入的 mime;不支持返回 null。 */
47
+ /** Prefer content_type, fall back to extension; return injectable mime or null. */
48
48
  export function resolveImageMime(contentType: string | undefined, filename: string | undefined): string | null {
49
49
  const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
50
50
  if (type) {
51
51
  if (MIME_BY_CONTENT_TYPE[type]) return MIME_BY_CONTENT_TYPE[type];
52
- // 明确声明为 image/* 但不支持(如 svg)时拒绝,避免错误扩展名绕过校验
52
+ // Reject unsupported image/* types (e.g. svg) so a wrong extension cannot bypass validation.
53
53
  if (type.startsWith("image/")) return null;
54
54
  }
55
55
 
@@ -57,14 +57,14 @@ export function resolveImageMime(contentType: string | undefined, filename: stri
57
57
  return ext ? (MIME_BY_EXTENSION[ext] ?? null) : null;
58
58
  }
59
59
 
60
- /** 是否为图片附件(含不支持的 image/*,由图片流程给出失败提示)。 */
60
+ /** Whether the attachment is an image (unsupported image/* is handled by the image path). */
61
61
  export function isImageAttachment(attachment: InboundAttachmentLike): boolean {
62
62
  const type = (attachment.content_type ?? "").toLowerCase();
63
63
  if (type.startsWith("image/")) return true;
64
64
  return resolveImageMime(attachment.content_type, attachment.filename) !== null;
65
65
  }
66
66
 
67
- /** 文本 + 图片组合为 pi.sendUserMessage 的内容;无图片时保持纯字符串。 */
67
+ /** Build pi.sendUserMessage content; keep a plain string when there are no images. */
68
68
  export function buildImageMessageContent(
69
69
  text: string,
70
70
  images: readonly ImageContentLike[],
@@ -116,7 +116,7 @@ async function downloadOne(
116
116
  }
117
117
  }
118
118
 
119
- /** 按原顺序下载所有图片;单张失败不影响其他图片。 */
119
+ /** Download images in order; one failure does not stop the others. */
120
120
  export async function resolveInboundImages(
121
121
  attachments: readonly InboundAttachmentLike[],
122
122
  maxSize: number,
package/src/inbound.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { join } from "node:path";
3
3
  import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
4
- import { setAllowedOpenid } from "./config";
5
4
  import { sendReply, type ReplyChannel } from "./outbound";
6
5
  import type { ReplyBudget } from "./reply-budget";
7
6
  import {
@@ -14,27 +13,27 @@ import {
14
13
  import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
15
14
 
16
15
  /**
17
- * F2:QQ → pi 入站处理。
18
- * 链路:C2C 过滤 → 单人白名单(含首个用户自动绑定)→ QQ 侧命令拦截 → 文本注入 pi。
19
- * 注意:注入消息必须用 pi.sendUserMessage(ExtensionContext 上没有该 API)。
16
+ * F2: QQ → pi inbound handling.
17
+ * Chain: C2C filter → QR-bound user whitelist → QQ commands → text/image/file injection.
18
+ * Use pi.sendUserMessage (ExtensionContext has no such API).
20
19
  */
21
20
 
22
21
  export interface InboundDeps {
23
22
  pi: ExtensionAPI;
24
- /** session_start 时捕获的会话上下文:ui/isIdle/abort/compact/getContextUsage */
23
+ /** Session context captured at session_start: ui/isIdle/abort/compact/getContextUsage. */
25
24
  ctx: ExtensionContext;
26
25
  budget: ReplyBudget;
27
- /** 均实时读配置,绑定关系变更即时生效 */
26
+ /** Read settings live so changes apply immediately. */
28
27
  getAllowedOpenid: () => string | undefined;
29
28
  getBoundOpenid: () => string | undefined;
30
29
  getDeliverAs: () => "steer" | "followUp";
31
30
  getImageMaxSize: () => number;
32
31
  getFileMaxSize: () => number;
33
- /** 测试可注入;默认 saveInboundFiles */
32
+ /** Test override; defaults to saveInboundFiles. */
34
33
  saveFiles?: typeof saveInboundFiles;
35
34
  getStatusLines: () => string[];
36
35
  onWarn: (msg: string) => void;
37
- /** F7:标记接下来的 run 由 QQ 触发(供 RunFeedback 建立确认/心跳/typing) */
36
+ /** F7: mark the next run as QQ-triggered (for typing/heartbeat/timeline). */
38
37
  markQQTrigger: (openid: string, msgId: string) => void;
39
38
  }
40
39
 
@@ -43,15 +42,9 @@ export function createInboundHandler(deps: InboundDeps) {
43
42
  if (msg.kind !== "c2c") return;
44
43
 
45
44
  const allowed = deps.getAllowedOpenid();
46
- if (allowed && msg.senderId !== allowed) return;
45
+ if (!allowed || msg.senderId !== allowed) return;
47
46
 
48
- // 未绑定 → 首个私聊用户自动绑定(features.md F1 方式 A 说明)
49
- if (!allowed) {
50
- setAllowedOpenid(msg.senderId);
51
- deps.ctx.ui.notify(`pi-qq:已自动绑定首个私聊用户(${msg.senderId.slice(0, 8)}…)`, "info");
52
- }
53
-
54
- // 记录被动回复目标与新鲜度起点(供 outbound 发牌)
47
+ // Record passive reply target/freshness for outbound budget.
55
48
  deps.budget.observeInbound(msg.senderId, msg.messageId);
56
49
 
57
50
  const channel: ReplyChannel = {
@@ -74,7 +67,7 @@ export function createInboundHandler(deps: InboundDeps) {
74
67
  return;
75
68
  }
76
69
 
77
- // F3:图片转 ImageContent,非图片附件保存到本地并在提示词中给出路径
70
+ // F3: images become ImageContent; other attachments are saved and referenced by path.
78
71
  const imageAttachments = attachments.filter(isImageAttachment);
79
72
  const fileAttachments = attachments.filter((attachment) => !isImageAttachment(attachment));
80
73
  const failures: Array<{ filename: string; reason: string }> = [];
@@ -107,7 +100,7 @@ export function createInboundHandler(deps: InboundDeps) {
107
100
  }
108
101
  if (!text && images.length === 0 && files.length === 0) return;
109
102
 
110
- // F7:标记 QQ 触发的 run(RunFeedback 据此建立 typing/时间线),不发送开始确认
103
+ // F7: mark a QQ-triggered run; do not send a start confirmation.
111
104
  deps.markQQTrigger(msg.senderId, msg.messageId);
112
105
  const promptText = formatFilePrompt(files, text);
113
106
  deps.pi.sendUserMessage(buildImageMessageContent(promptText, images), { deliverAs: deps.getDeliverAs() });
@@ -154,7 +147,7 @@ async function handleCommand(text: string, reply: (t: string) => Promise<void>,
154
147
  await reply("任务运行中,请先 /stop 再重置会话");
155
148
  } else {
156
149
  await reply("正在重置会话…");
157
- // 内置 /new 仅在交互模式处理;这里通过扩展命令调用 ctx.newSession
150
+ // Built-in /new is interactive-only; dispatch the extension command instead.
158
151
  deps.pi.sendUserMessage("/qq-new", { expandPromptTemplates: true });
159
152
  }
160
153
  break;
package/src/login.ts CHANGED
@@ -4,23 +4,22 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
4
4
  import type { Credentials } from "./config";
5
5
 
6
6
  /**
7
- * F1 方式 B:扫码登录。
8
- * - TUI:ctx.ui.custom 弹窗展示二维码(qrcode-terminal 画 ASCII),Esc 取消;
9
- * 扫码成功/失败自动关闭弹窗。
10
- * - 非 TUI:仅提示二维码 URL,后台轮询直到扫码完成(M1 简化,无取消入口)。
11
- * connector 负责登录协议(生成绑定任务/轮询/解密),本模块只做展示与编排。
7
+ * F1: QR-code login only.
8
+ * - TUI: show an ASCII QR code in ctx.ui.custom; Esc cancels.
9
+ * - Non-TUI: print the QR URL and poll until the scan completes.
10
+ * Credentials are returned to the caller and kept in memory only.
12
11
  */
13
12
 
14
13
  export interface QrLoginResult extends Credentials {
15
- /** 扫码人的 openid(机器人内用户标识),作为默认单人绑定 */
14
+ /** openid of the scanning user, used as the single bound QQ user */
16
15
  userOpenid?: string;
17
16
  }
18
17
 
19
18
  export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult | undefined> {
20
19
  const ac = new AbortController();
21
20
 
22
- // 二维码展示的共享状态:轮询回调与弹窗组件解耦,render 时读取最新值
23
- const qr = { lines: [] as string[], hint: "正在获取二维码…" };
21
+ // Shared QR state so polling callbacks and the TUI component stay decoupled.
22
+ const qr = { lines: [] as string[], hint: "Fetching QR code…" };
24
23
  let requestRender: (() => void) | undefined;
25
24
  let closeOverlay: (() => void) | undefined;
26
25
 
@@ -35,28 +34,28 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
35
34
 
36
35
  const stopPolling = startQrConnect(
37
36
  {
38
- // 官方说明:返回数组当前恒为 1 个元素,按遍历处理以兼容未来多机器人
37
+ // The connector currently returns one entry; iterate for future compatibility.
39
38
  onSuccess: ([first]) => {
40
39
  finish(first ? { appId: first.appId, appSecret: first.appSecret, userOpenid: first.userOpenid } : undefined);
41
40
  closeOverlay?.();
42
41
  },
43
42
  onFailure: (err) => {
44
- if (settled) return; // 用户取消(abort)导致的失败不必提示
45
- ctx.ui.notify(`扫码登录失败:${err.message}`, "error");
43
+ if (settled) return; // User cancelled (abort); no error toast.
44
+ ctx.ui.notify(`QR login failed: ${err.message}`, "error");
46
45
  finish();
47
46
  closeOverlay?.();
48
47
  },
49
48
  onQrDisplayed: (url) => {
50
- qr.hint = "请用手机 QQ 扫码";
49
+ qr.hint = "Scan with mobile QQ";
51
50
  generate(url, { small: true }, (ascii) => {
52
51
  qr.lines = ascii.split("\n").filter((line) => line.trim().length > 0);
53
52
  });
54
53
  requestRender?.();
55
- // 非 TUI 模式拿不到弹窗,至少给出 URL
56
- if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq 扫码地址:${url}`, "info");
54
+ // Non-TUI mode has no overlay; show the URL.
55
+ if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq QR URL: ${url}`, "info");
57
56
  },
58
57
  onQrExpired: () => {
59
- qr.hint = "二维码已过期,正在自动刷新…";
58
+ qr.hint = "QR code expired; refreshing…";
60
59
  requestRender?.();
61
60
  },
62
61
  },
@@ -64,8 +63,8 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
64
63
  );
65
64
 
66
65
  if (ctx.mode !== "tui") {
67
- // 非 TUI:无弹窗、无取消入口,等待扫码完成(M1 简化)
68
- ctx.ui.notify("pi-qq:等待手机 QQ 扫码…", "info");
66
+ // Non-TUI: no overlay or cancel affordance; wait for the scan.
67
+ ctx.ui.notify("pi-qq: waiting for mobile QQ scan…", "info");
69
68
  return;
70
69
  }
71
70
 
@@ -75,8 +74,8 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
75
74
  requestRender = () => tui.requestRender();
76
75
  return {
77
76
  render(width: number): string[] {
78
- const lines = qr.lines.length > 0 ? qr.lines : ["(获取二维码中…)"];
79
- return [...lines, "", qr.hint, theme.fg("dim", "Esc 取消扫码")].map((line) =>
77
+ const lines = qr.lines.length > 0 ? qr.lines : ["(fetching QR code…)"];
78
+ return [...lines, "", qr.hint, theme.fg("dim", "Esc to cancel")].map((line) =>
80
79
  line.length > width ? line.slice(0, width) : line,
81
80
  );
82
81
  },
@@ -90,7 +89,7 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
90
89
  };
91
90
  })
92
91
  .then(() => {
93
- // 弹窗因用户取消而关闭;成功/失败路径已先 finish
92
+ // Overlay closed by user; success/failure paths already called finish().
94
93
  if (!settled) finish();
95
94
  });
96
95
  });