@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/README.md +70 -104
- package/doc/{features.md → features-v1.md} +55 -92
- package/doc/{plan.md → plan-v1.md} +38 -43
- package/index.ts +111 -159
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +23 -23
- package/src/budget-status.ts +9 -9
- package/src/config.ts +22 -80
- package/src/download.ts +3 -3
- package/src/files.ts +9 -9
- package/src/format.ts +6 -1
- package/src/images.ts +6 -6
- package/src/inbound.ts +12 -19
- package/src/login.ts +19 -20
- package/src/outbound.ts +22 -22
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +70 -75
- package/src/usage.ts +0 -93
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
|
-
*
|
|
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" //
|
|
21
|
-
| "connected" //
|
|
22
|
-
| "reconnecting" //
|
|
23
|
-
| "blocked"; //
|
|
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
|
|
27
|
+
/** F2: QR-bound single user; production always provides it */
|
|
28
28
|
allowedOpenid?: string;
|
|
29
29
|
markdownSupport?: boolean;
|
|
30
|
-
/**
|
|
30
|
+
/** Debug mode: print SDK logs (timeouts/rate limits/reconnects) to the terminal. */
|
|
31
31
|
debug?: boolean;
|
|
32
|
-
/**
|
|
32
|
+
/** Inbound message handler. */
|
|
33
33
|
onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
|
|
34
|
-
/**
|
|
34
|
+
/** Connection state changes; the caller decides how to notify the UI. */
|
|
35
35
|
onStateChange?: (state: BotState, detail?: string) => void;
|
|
36
|
-
/**
|
|
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
|
-
//
|
|
53
|
+
// Echo filtering + message deduplication (SDK default 5s window).
|
|
54
54
|
bot.use(messageFilter({ skipSelfEcho: true }));
|
|
55
|
-
//
|
|
55
|
+
// Strip protocol markers such as @mentions and face tags.
|
|
56
56
|
bot.use(contentSanitizer({ stripBotMention: true }));
|
|
57
|
-
//
|
|
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; //
|
|
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
|
-
|
|
82
|
-
|
|
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",
|
|
85
|
+
report("stopped", `Reconnect budget exhausted: ${(err as Error).message}; run /qq-login to retry.`);
|
|
86
86
|
} else {
|
|
87
|
-
report("stopped",
|
|
87
|
+
report("stopped", `Startup failed: ${(err as Error).message}; check credentials and network.`);
|
|
88
88
|
}
|
|
89
89
|
});
|
|
90
90
|
|
package/src/budget-status.ts
CHANGED
|
@@ -10,7 +10,7 @@ function mask(value: string): string {
|
|
|
10
10
|
return `${value.slice(0, 8)}…`;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
/**
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
`msgId
|
|
30
|
-
|
|
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 {
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import {
|
|
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
|
-
*
|
|
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
|
-
/**
|
|
12
|
+
/** Runtime settings (features-v1.md §4). */
|
|
13
13
|
export interface PiQQSettings {
|
|
14
|
-
/** F4
|
|
14
|
+
/** F4: stream assistant replies */
|
|
15
15
|
streamAssistant?: boolean;
|
|
16
|
-
/** F4
|
|
16
|
+
/** F4: bot has QQ markdown permission; pass Markdown through when true */
|
|
17
17
|
markdownSupport?: boolean;
|
|
18
|
-
/**
|
|
19
|
-
usageRelay?: boolean;
|
|
20
|
-
/** F2:agent 忙碌时新消息的处理方式 */
|
|
18
|
+
/** F2: how a busy agent handles new messages */
|
|
21
19
|
deliverAs?: "steer" | "followUp";
|
|
22
|
-
/** F3
|
|
20
|
+
/** F3: QQ image download limit (bytes) */
|
|
23
21
|
imageMaxSize?: number;
|
|
24
|
-
/** F3
|
|
22
|
+
/** F3: QQ file download limit (bytes), default 50MB */
|
|
25
23
|
fileMaxSize?: number;
|
|
26
|
-
/** F7
|
|
24
|
+
/** F7: heartbeat interval in minutes, 0 disables */
|
|
27
25
|
heartbeatMinutes?: number;
|
|
28
|
-
/** F7
|
|
26
|
+
/** F7: per-run message heartbeat limit */
|
|
29
27
|
heartbeatMaxMessages?: number;
|
|
30
|
-
/** F7
|
|
28
|
+
/** F7: stream summary frame interval (ms, minimum 300) */
|
|
31
29
|
streamFlushMs?: number;
|
|
32
|
-
/**
|
|
30
|
+
/** Diagnostic mode: SDK logs + stream retry/timeout logs */
|
|
33
31
|
debug?: boolean;
|
|
34
|
-
/** F7
|
|
35
|
-
* 无 markdown 权限的机器人必须保持 false(实测:气泡停在 "..." 且结果被流接管丢失) */
|
|
32
|
+
/** F7: append-mode stream relay switch */
|
|
36
33
|
streamRelay?: boolean;
|
|
37
34
|
}
|
|
38
35
|
|
|
39
|
-
/**
|
|
40
|
-
export
|
|
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
|
-
/**
|
|
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:
|
|
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
|
-
/**
|
|
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
|
|
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
|
-
/**
|
|
23
|
+
/** Test override; defaults to <cwd>/.pi/pi-qq. */
|
|
24
24
|
baseDir?: string;
|
|
25
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
"
|
|
133
|
-
...files.map((file) => `- ${file.path}
|
|
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("", "
|
|
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
|
|
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
|
-
/**
|
|
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
|
-
//
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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
|
|
18
|
-
*
|
|
19
|
-
*
|
|
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
|
|
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
|
-
/**
|
|
32
|
+
/** Test override; defaults to saveInboundFiles. */
|
|
34
33
|
saveFiles?: typeof saveInboundFiles;
|
|
35
34
|
getStatusLines: () => string[];
|
|
36
35
|
onWarn: (msg: string) => void;
|
|
37
|
-
/** F7
|
|
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
|
|
45
|
+
if (!allowed || msg.senderId !== allowed) return;
|
|
47
46
|
|
|
48
|
-
//
|
|
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
|
|
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
|
|
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
|
-
//
|
|
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
|
|
8
|
-
* - TUI
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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
|
-
/**
|
|
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
|
-
//
|
|
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
|
-
//
|
|
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; //
|
|
45
|
-
ctx.ui.notify(
|
|
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 = "
|
|
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
|
-
//
|
|
56
|
-
if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq
|
|
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
|
-
//
|
|
68
|
-
ctx.ui.notify("pi-qq
|
|
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
|
|
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
|
-
//
|
|
92
|
+
// Overlay closed by user; success/failure paths already called finish().
|
|
94
93
|
if (!settled) finish();
|
|
95
94
|
});
|
|
96
95
|
});
|