@chen_hu_hu/pi-qq 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README-zh.md +48 -24
- package/README.md +40 -16
- 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 +187 -0
- package/doc/delivery-v3.md +187 -0
- package/index.ts +71 -66
- package/package.json +8 -2
- package/src/{download.ts → attachments/attachment-download.ts} +2 -5
- package/src/{files.ts → attachments/file-attachments.ts} +4 -15
- package/src/{images.ts → attachments/image-attachments.ts} +3 -10
- 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 -28
- package/src/infra/settings.ts +49 -0
- package/src/{bot.ts → qq/qq-bot.ts} +4 -29
- package/src/{inbound.ts → qq/qq-message-handler.ts} +10 -23
- package/src/{login.ts → qq/qr-login.ts} +20 -16
- package/src/{outbound.ts → qq/reply-sender.ts} +3 -34
- 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 +586 -0
- package/src/relay/stream-block-format.ts +114 -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/run-feedback.ts +0 -410
package/index.ts
CHANGED
|
@@ -1,24 +1,18 @@
|
|
|
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/
|
|
4
|
-
import { startBot, type BotState, type RunningBot } from "./src/bot";
|
|
5
|
-
import { runQrLogin } from "./src/login";
|
|
6
|
-
import { createInboundHandler } from "./src/
|
|
7
|
-
import { markdownToPlain, sendReply } from "./src/
|
|
8
|
-
import { ReplyBudget } from "./src/reply-
|
|
9
|
-
import { RunFeedback } from "./src/run-
|
|
10
|
-
import { AppendStream } from "./src/
|
|
11
|
-
import { formatTokenCount } from "./src/format";
|
|
12
|
-
import { formatBudgetStatus } from "./src/
|
|
13
|
-
import { configureLogger, log, previewForLog } from "./src/logger";
|
|
14
|
-
import { pruneUploadIndex, sessionUploadDir } from "./src/
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* pi-qq extension entry.
|
|
18
|
-
* QR login only; credentials live in process memory and are never persisted.
|
|
19
|
-
*/
|
|
20
|
-
|
|
21
|
-
/** In-memory login state; survives extension reload/session replacement in one process. */
|
|
3
|
+
import { getSettings, readConfig, type Credentials } from "./src/infra/settings";
|
|
4
|
+
import { startBot, type BotState, type RunningBot } from "./src/qq/qq-bot";
|
|
5
|
+
import { runQrLogin } from "./src/qq/qr-login";
|
|
6
|
+
import { createInboundHandler } from "./src/qq/qq-message-handler";
|
|
7
|
+
import { markdownToPlain, sendReply } from "./src/qq/reply-sender";
|
|
8
|
+
import { ReplyBudget } from "./src/quota/reply-quota";
|
|
9
|
+
import { RunFeedback } from "./src/relay/run-stream-relay";
|
|
10
|
+
import { AppendStream } from "./src/relay/stream-session";
|
|
11
|
+
import { formatTokenCount } from "./src/infra/display-format";
|
|
12
|
+
import { formatBudgetStatus } from "./src/quota/reply-quota-report";
|
|
13
|
+
import { configureLogger, log, previewForLog } from "./src/infra/file-logger";
|
|
14
|
+
import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
|
|
15
|
+
|
|
22
16
|
interface LoginState {
|
|
23
17
|
credentials: Credentials;
|
|
24
18
|
allowedOpenid: string;
|
|
@@ -37,7 +31,6 @@ function setLoginState(state: LoginState | undefined): void {
|
|
|
37
31
|
else delete store[LOGIN_STATE_KEY];
|
|
38
32
|
}
|
|
39
33
|
|
|
40
|
-
/** Session-level runtime state; rebuilt by a new runtime after reload/session switch. */
|
|
41
34
|
let running: RunningBot | undefined;
|
|
42
35
|
let lastState: BotState = "stopped";
|
|
43
36
|
let stateDetail: string | undefined;
|
|
@@ -46,16 +39,7 @@ const budget = new ReplyBudget();
|
|
|
46
39
|
const runFeedback = new RunFeedback({
|
|
47
40
|
bot: () => running?.bot,
|
|
48
41
|
budget,
|
|
49
|
-
|
|
50
|
-
getHeartbeatMinutes: () => getSettings(readConfig().config).heartbeatMinutes,
|
|
51
|
-
getHeartbeatMaxMessages: () => getSettings(readConfig().config).heartbeatMaxMessages,
|
|
52
|
-
getStreamRelay: () => getSettings(readConfig().config).streamRelay,
|
|
53
|
-
getStreamFlushMs: () => getSettings(readConfig().config).streamFlushMs,
|
|
54
|
-
makeChannel: () => ({
|
|
55
|
-
budget,
|
|
56
|
-
boundOpenid: getLoginState()?.allowedOpenid ?? "",
|
|
57
|
-
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
58
|
-
}),
|
|
42
|
+
getThinkingRelay: () => getSettings(readConfig().config).thinkingRelay,
|
|
59
43
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
60
44
|
});
|
|
61
45
|
|
|
@@ -64,8 +48,6 @@ const fmtTokens = (n: number | null): string => (n === null ? "unknown" : format
|
|
|
64
48
|
export default function (pi: ExtensionAPI) {
|
|
65
49
|
const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
|
|
66
50
|
|
|
67
|
-
// Live settings reader (binding/settings changes apply immediately).
|
|
68
|
-
|
|
69
51
|
const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
|
|
70
52
|
const getBoundOpenid = getAllowedOpenid;
|
|
71
53
|
const getDeliverAs = () => getSettings(readConfig().config).deliverAs;
|
|
@@ -89,8 +71,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
89
71
|
];
|
|
90
72
|
};
|
|
91
73
|
|
|
92
|
-
// —— Login and connection ——
|
|
93
|
-
|
|
94
74
|
const startWithCredentials = async (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
|
|
95
75
|
const settings = getSettings(readConfig().config);
|
|
96
76
|
configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
|
|
@@ -104,7 +84,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
104
84
|
allowedOpenid,
|
|
105
85
|
cwd: ctx.cwd,
|
|
106
86
|
model: ctx.model?.name ?? null,
|
|
107
|
-
markdownSupport: settings.markdownSupport,
|
|
108
87
|
logLevel: settings.logLevel,
|
|
109
88
|
uploadDir,
|
|
110
89
|
indexedFiles: Object.keys(uploadIndex).length,
|
|
@@ -112,7 +91,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
112
91
|
running = startBot({
|
|
113
92
|
credentials: creds,
|
|
114
93
|
allowedOpenid,
|
|
115
|
-
markdownSupport: settings.markdownSupport,
|
|
116
94
|
onMessage: createInboundHandler({
|
|
117
95
|
pi,
|
|
118
96
|
ctx,
|
|
@@ -125,6 +103,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
125
103
|
getStatusLines,
|
|
126
104
|
onWarn: onWarn(ctx),
|
|
127
105
|
markQQTrigger: (openid, msgId) => runFeedback.markQQTrigger(openid, msgId),
|
|
106
|
+
waitForEnd: () => runFeedback.waitForEnd(),
|
|
107
|
+
onStop: () => runFeedback.cancelRecovery(),
|
|
128
108
|
}),
|
|
129
109
|
onStateChange: (state, detail) => {
|
|
130
110
|
lastState = state;
|
|
@@ -133,9 +113,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
133
113
|
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "connection blocked"}`, "error");
|
|
134
114
|
else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
|
|
135
115
|
},
|
|
136
|
-
onRecoverableError: () => {
|
|
137
|
-
// Recoverable errors are handled by the SDK reconnect loop.
|
|
138
|
-
},
|
|
139
116
|
});
|
|
140
117
|
};
|
|
141
118
|
|
|
@@ -146,8 +123,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
146
123
|
stateDetail = undefined;
|
|
147
124
|
};
|
|
148
125
|
|
|
149
|
-
// —— Lifecycle ——
|
|
150
|
-
|
|
151
126
|
pi.on("session_start", async (_event, ctx) => {
|
|
152
127
|
const { config, error } = readConfig();
|
|
153
128
|
const settings = getSettings(config);
|
|
@@ -177,8 +152,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
177
152
|
runFeedback.dispose();
|
|
178
153
|
});
|
|
179
154
|
|
|
180
|
-
// F7 run feedback: agent lifecycle / tool counts / text streaming.
|
|
181
|
-
|
|
182
155
|
pi.on("agent_start", () => {
|
|
183
156
|
log.info("agent", "run started");
|
|
184
157
|
runFeedback.onAgentStart();
|
|
@@ -195,7 +168,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
195
168
|
toolCallId: event.toolCallId,
|
|
196
169
|
args: previewForLog(event.args),
|
|
197
170
|
});
|
|
198
|
-
void runFeedback.onToolStart(event.toolName);
|
|
171
|
+
void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
|
|
199
172
|
});
|
|
200
173
|
|
|
201
174
|
pi.on("tool_execution_end", (event) => {
|
|
@@ -205,7 +178,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
205
178
|
isError: event.isError,
|
|
206
179
|
result: previewForLog(event.result),
|
|
207
180
|
});
|
|
208
|
-
runFeedback.onToolEnd(event.toolName, event.isError);
|
|
181
|
+
runFeedback.onToolEnd(event.toolName, event.isError, event.result, event.toolCallId);
|
|
209
182
|
});
|
|
210
183
|
|
|
211
184
|
pi.on("message_update", (event) => {
|
|
@@ -214,16 +187,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
214
187
|
const snapshot = msg.content
|
|
215
188
|
.filter((b) => b.type === "text")
|
|
216
189
|
.map((b) => b.text)
|
|
217
|
-
.join("");
|
|
190
|
+
.join("\n");
|
|
218
191
|
const thinking = msg.content
|
|
219
192
|
.filter((b) => b.type === "thinking")
|
|
220
193
|
.map((b) => b.thinking)
|
|
221
|
-
.join("");
|
|
194
|
+
.join("\n");
|
|
222
195
|
void runFeedback.onAssistantDelta(snapshot, thinking);
|
|
223
196
|
});
|
|
224
197
|
|
|
225
|
-
// pi → QQ: assistant message relay (QQ-triggered runs only).
|
|
226
|
-
|
|
227
198
|
pi.on("message_end", async (event, ctx) => {
|
|
228
199
|
const msg = event.message;
|
|
229
200
|
if (msg.role !== "assistant" || !running) return;
|
|
@@ -242,8 +213,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
242
213
|
});
|
|
243
214
|
if (!fromQQ) return;
|
|
244
215
|
|
|
245
|
-
const { config } = readConfig();
|
|
246
|
-
const settings = getSettings(config);
|
|
247
216
|
const isError = msg.stopReason === "error";
|
|
248
217
|
|
|
249
218
|
let text: string;
|
|
@@ -258,18 +227,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
258
227
|
}
|
|
259
228
|
if (!text) {
|
|
260
229
|
log.debug("pi", "assistant message has no text", { isError });
|
|
261
|
-
// Textless assistant messages also end the feedback turn: reset thinking state
|
|
262
|
-
// and flush pending thinking rows so the next message does not swallow them.
|
|
263
230
|
await runFeedback.onAssistantFinal("", isError);
|
|
264
231
|
return;
|
|
265
232
|
}
|
|
266
233
|
|
|
267
|
-
// F7 stream takeover: stream frames render Markdown; send raw text so lengths match.
|
|
268
234
|
const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
|
|
269
235
|
log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
|
|
270
236
|
if (streamTookOver) return;
|
|
271
237
|
|
|
272
|
-
const payload =
|
|
238
|
+
const payload = markdownToPlain(text);
|
|
273
239
|
|
|
274
240
|
const bound = getLoginState()?.allowedOpenid;
|
|
275
241
|
if (!bound) {
|
|
@@ -286,8 +252,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
286
252
|
});
|
|
287
253
|
});
|
|
288
254
|
|
|
289
|
-
// —— Commands ——
|
|
290
|
-
|
|
291
255
|
pi.registerCommand("qq-login", {
|
|
292
256
|
description: "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
293
257
|
handler: async (_args, ctx) => {
|
|
@@ -296,16 +260,29 @@ export default function (pi: ExtensionAPI) {
|
|
|
296
260
|
|
|
297
261
|
stopIfRunning();
|
|
298
262
|
setLoginState(undefined);
|
|
299
|
-
|
|
263
|
+
let result;
|
|
264
|
+
try {
|
|
265
|
+
result = await runQrLogin(ctx);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
log.error("login", "QR login command failed", { err });
|
|
268
|
+
ctx.ui.notify("Error: QR login failed", "error");
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
300
271
|
if (!result) return;
|
|
301
272
|
if (!result.userOpenid) {
|
|
302
|
-
|
|
273
|
+
log.error("login", "QR login did not return a user openid");
|
|
274
|
+
ctx.ui.notify("Error: QR login failed", "error");
|
|
303
275
|
return;
|
|
304
276
|
}
|
|
305
277
|
|
|
306
278
|
const credentials: Credentials = { appId: result.appId, appSecret: result.appSecret };
|
|
307
279
|
setLoginState({ credentials, allowedOpenid: result.userOpenid });
|
|
308
|
-
|
|
280
|
+
try {
|
|
281
|
+
await startWithCredentials(ctx, credentials, result.userOpenid);
|
|
282
|
+
} catch (err) {
|
|
283
|
+
log.error("login", "starting bot after login failed", { err });
|
|
284
|
+
ctx.ui.notify("Error: QQ bot start failed", "error");
|
|
285
|
+
}
|
|
309
286
|
},
|
|
310
287
|
});
|
|
311
288
|
|
|
@@ -344,8 +321,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
344
321
|
},
|
|
345
322
|
});
|
|
346
323
|
|
|
347
|
-
// —— Diagnostic commands ——
|
|
348
|
-
|
|
349
324
|
const diagTarget = () => {
|
|
350
325
|
const last = budget.lastTarget;
|
|
351
326
|
if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
|
|
@@ -376,8 +351,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
376
351
|
});
|
|
377
352
|
|
|
378
353
|
pi.registerCommand("qq-test-stream", {
|
|
379
|
-
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text)",
|
|
380
|
-
handler: async (
|
|
354
|
+
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text) or resume probe",
|
|
355
|
+
handler: async (args, ctx) => {
|
|
381
356
|
if (!running) {
|
|
382
357
|
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
383
358
|
return;
|
|
@@ -389,12 +364,42 @@ export default function (pi: ExtensionAPI) {
|
|
|
389
364
|
}
|
|
390
365
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
391
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
|
+
}
|
|
392
395
|
const stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
393
|
-
await stream.append(
|
|
396
|
+
await stream.append(
|
|
397
|
+
"**💭 思考**\n\nprobe thinking\nsecond line\n\n**💻 bash**\n\n`echo probe`\n\n```text\nprobe\n```\n",
|
|
398
|
+
);
|
|
394
399
|
await sleep(1200);
|
|
395
400
|
await stream.append("\n**Intermediate message**: first-turn reply.\n");
|
|
396
401
|
await sleep(1200);
|
|
397
|
-
await stream.append("
|
|
402
|
+
await stream.append("\n**📖 read**\n\n`src/index.ts`\n\n```text\nprobe file\n```\n");
|
|
398
403
|
await sleep(800);
|
|
399
404
|
await stream.append("\n**Final reply** (streamed append)");
|
|
400
405
|
let doneNote = "DONE succeeded";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chen_hu_hu/pi-qq",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Connect pi to QQ private chats.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "CQ-Developer",
|
|
@@ -39,7 +39,9 @@
|
|
|
39
39
|
"LICENSE"
|
|
40
40
|
],
|
|
41
41
|
"scripts": {
|
|
42
|
-
"typecheck": "
|
|
42
|
+
"typecheck": "tsc --noEmit",
|
|
43
|
+
"lint": "node --experimental-strip-types node_modules/eslint/bin/eslint.js --flag unstable_native_nodejs_ts_config .",
|
|
44
|
+
"lint:fix": "node --experimental-strip-types node_modules/eslint/bin/eslint.js --flag unstable_native_nodejs_ts_config . --fix",
|
|
43
45
|
"test": "vitest run",
|
|
44
46
|
"format": "prettier --write .",
|
|
45
47
|
"format:check": "prettier --check ."
|
|
@@ -59,8 +61,12 @@
|
|
|
59
61
|
},
|
|
60
62
|
"devDependencies": {
|
|
61
63
|
"@earendil-works/pi-coding-agent": "^1.4.0",
|
|
64
|
+
"@eslint/js": "^10.0.1",
|
|
62
65
|
"@types/node": "^22.20.5",
|
|
66
|
+
"eslint": "^10.14.0",
|
|
63
67
|
"prettier": "^3.9.10",
|
|
68
|
+
"typescript": "^5.9.3",
|
|
69
|
+
"typescript-eslint": "^8.72.1",
|
|
64
70
|
"vitest": "^5.0.5"
|
|
65
71
|
}
|
|
66
72
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { formatBytes } from "
|
|
1
|
+
import { formatBytes } from "../infra/display-format";
|
|
2
2
|
|
|
3
|
-
/** Minimal QQ inbound attachment shape shared by images and files. */
|
|
4
3
|
export interface InboundAttachmentLike {
|
|
5
4
|
content_type: string;
|
|
6
5
|
url: string;
|
|
@@ -12,7 +11,6 @@ export interface DownloadOptions {
|
|
|
12
11
|
url: string;
|
|
13
12
|
maxSize: number;
|
|
14
13
|
timeoutMs: number;
|
|
15
|
-
/** Kind label used in errors, e.g. "image" or "file". */
|
|
16
14
|
kind: string;
|
|
17
15
|
fetchImpl?: typeof fetch;
|
|
18
16
|
}
|
|
@@ -48,7 +46,6 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
48
46
|
return Buffer.concat(chunks, total);
|
|
49
47
|
}
|
|
50
48
|
|
|
51
|
-
/** Download an attachment with a timeout and streaming size cap. */
|
|
52
49
|
export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
53
50
|
const limit = Math.max(1, opts.maxSize);
|
|
54
51
|
let parsed: URL;
|
|
@@ -79,7 +76,7 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
|
79
76
|
return await readBodyLimited(response, limit, opts.kind);
|
|
80
77
|
} catch (err) {
|
|
81
78
|
if (controller.signal.aborted) {
|
|
82
|
-
throw new Error(`download timed out after ${opts.timeoutMs / 1000}s
|
|
79
|
+
throw new Error(`download timed out after ${opts.timeoutMs / 1000}s`, { cause: err });
|
|
83
80
|
}
|
|
84
81
|
throw err;
|
|
85
82
|
} finally {
|
|
@@ -1,10 +1,9 @@
|
|
|
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
3
|
import { basename, extname, join } from "node:path";
|
|
5
|
-
import { downloadLimited, type InboundAttachmentLike } from "./download";
|
|
6
|
-
import { formatBytes } from "
|
|
7
|
-
import { log } from "
|
|
4
|
+
import { downloadLimited, type InboundAttachmentLike } from "./attachment-download";
|
|
5
|
+
import { formatBytes } from "../infra/display-format";
|
|
6
|
+
import { log } from "../infra/file-logger";
|
|
8
7
|
|
|
9
8
|
const DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
10
9
|
const UPLOAD_INDEX_FILENAME = ".index.json";
|
|
@@ -20,14 +19,11 @@ export interface FileFailure {
|
|
|
20
19
|
reason: string;
|
|
21
20
|
}
|
|
22
21
|
|
|
23
|
-
/** fileName -> SHA-256. Paths are derived from uploadDir. */
|
|
24
22
|
export type UploadIndex = Record<string, string>;
|
|
25
23
|
|
|
26
24
|
export interface SaveFilesOptions {
|
|
27
25
|
maxSize: number;
|
|
28
|
-
/** `<cwd>/.pi/pi-qq/<sessionId>/uploads`. */
|
|
29
26
|
uploadDir: string;
|
|
30
|
-
/** Test/caller override; loaded from uploadDir when omitted. Mutated in place. */
|
|
31
27
|
index?: UploadIndex;
|
|
32
28
|
fetchImpl?: typeof fetch;
|
|
33
29
|
}
|
|
@@ -42,7 +38,6 @@ function safePathSegment(key: string): string {
|
|
|
42
38
|
return cleaned.slice(0, 64) || "session";
|
|
43
39
|
}
|
|
44
40
|
|
|
45
|
-
/** Session-scoped upload directory; no date or msgId subdirectories. */
|
|
46
41
|
export function sessionUploadDir(cwd: string, sessionId: string): string {
|
|
47
42
|
return join(cwd, ".pi", "pi-qq", safePathSegment(sessionId), "uploads");
|
|
48
43
|
}
|
|
@@ -51,10 +46,10 @@ export function uploadIndexPath(uploadDir: string): string {
|
|
|
51
46
|
return join(uploadDir, UPLOAD_INDEX_FILENAME);
|
|
52
47
|
}
|
|
53
48
|
|
|
54
|
-
/** Keep only a safe basename (no paths/control/Windows-invalid chars); truncate long stems. */
|
|
55
49
|
export function sanitizeFilename(filename: string | undefined, fallback: string): string {
|
|
56
50
|
const raw = basename((filename ?? "").trim());
|
|
57
51
|
const cleaned = raw
|
|
52
|
+
// eslint-disable-next-line no-control-regex
|
|
58
53
|
.replace(/[\u0000-\u001f\u007f<>:"|?*]/g, "_")
|
|
59
54
|
.replace(/^[.\s]+|[.\s]+$/g, "")
|
|
60
55
|
.trim();
|
|
@@ -120,7 +115,6 @@ async function persistUploadIndex(uploadDir: string, index: UploadIndex): Promis
|
|
|
120
115
|
}
|
|
121
116
|
}
|
|
122
117
|
|
|
123
|
-
/** Load the index and drop entries whose files no longer exist. No content hashing. */
|
|
124
118
|
export async function pruneUploadIndex(uploadDir: string): Promise<UploadIndex> {
|
|
125
119
|
const index = await loadUploadIndex(uploadDir);
|
|
126
120
|
let changed = false;
|
|
@@ -149,10 +143,8 @@ async function saveOrReuse(
|
|
|
149
143
|
let changed = false;
|
|
150
144
|
|
|
151
145
|
if (!(await isFile(target))) {
|
|
152
|
-
// A stale index entry must not make a missing file look reusable.
|
|
153
146
|
if (index[filename]) {
|
|
154
147
|
delete index[filename];
|
|
155
|
-
changed = true;
|
|
156
148
|
}
|
|
157
149
|
await writeFile(target, body, { flag: "wx" });
|
|
158
150
|
index[filename] = hash;
|
|
@@ -187,7 +179,6 @@ async function saveOrReuse(
|
|
|
187
179
|
|
|
188
180
|
if (index[candidate]) {
|
|
189
181
|
delete index[candidate];
|
|
190
|
-
changed = true;
|
|
191
182
|
}
|
|
192
183
|
await writeFile(candidatePath, body, { flag: "wx" });
|
|
193
184
|
index[candidate] = hash;
|
|
@@ -197,7 +188,6 @@ async function saveOrReuse(
|
|
|
197
188
|
throw new Error("Could not allocate a unique filename");
|
|
198
189
|
}
|
|
199
190
|
|
|
200
|
-
/** Save non-image attachments in order; one failure does not stop the others. */
|
|
201
191
|
export async function saveInboundFiles(
|
|
202
192
|
attachments: readonly InboundAttachmentLike[],
|
|
203
193
|
options: SaveFilesOptions,
|
|
@@ -247,7 +237,6 @@ export async function saveInboundFiles(
|
|
|
247
237
|
return { files, failures };
|
|
248
238
|
}
|
|
249
239
|
|
|
250
|
-
/** Combine saved paths and the original user message into the pi prompt. */
|
|
251
240
|
export function formatFilePrompt(files: readonly SavedFile[], userText: string): string {
|
|
252
241
|
if (files.length === 0) return userText;
|
|
253
242
|
|
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { formatBytes } from "./format";
|
|
1
|
+
import { downloadLimited, type InboundAttachmentLike } from "./attachment-download";
|
|
2
|
+
import { formatBytes } from "../infra/display-format";
|
|
4
3
|
|
|
5
|
-
export {
|
|
6
|
-
export type { InboundAttachmentLike } from "./download";
|
|
4
|
+
export type { InboundAttachmentLike } from "./attachment-download";
|
|
7
5
|
|
|
8
6
|
export interface ImageContentLike {
|
|
9
7
|
type: "image";
|
|
@@ -44,12 +42,10 @@ const MIME_BY_EXTENSION: Record<string, string> = {
|
|
|
44
42
|
gif: "image/gif",
|
|
45
43
|
};
|
|
46
44
|
|
|
47
|
-
/** Prefer content_type, fall back to extension; return injectable mime or null. */
|
|
48
45
|
export function resolveImageMime(contentType: string | undefined, filename: string | undefined): string | null {
|
|
49
46
|
const type = (contentType ?? "").split(";")[0].trim().toLowerCase();
|
|
50
47
|
if (type) {
|
|
51
48
|
if (MIME_BY_CONTENT_TYPE[type]) return MIME_BY_CONTENT_TYPE[type];
|
|
52
|
-
// Reject unsupported image/* types (e.g. svg) so a wrong extension cannot bypass validation.
|
|
53
49
|
if (type.startsWith("image/")) return null;
|
|
54
50
|
}
|
|
55
51
|
|
|
@@ -57,14 +53,12 @@ export function resolveImageMime(contentType: string | undefined, filename: stri
|
|
|
57
53
|
return ext ? (MIME_BY_EXTENSION[ext] ?? null) : null;
|
|
58
54
|
}
|
|
59
55
|
|
|
60
|
-
/** Whether the attachment is an image (unsupported image/* is handled by the image path). */
|
|
61
56
|
export function isImageAttachment(attachment: InboundAttachmentLike): boolean {
|
|
62
57
|
const type = (attachment.content_type ?? "").toLowerCase();
|
|
63
58
|
if (type.startsWith("image/")) return true;
|
|
64
59
|
return resolveImageMime(attachment.content_type, attachment.filename) !== null;
|
|
65
60
|
}
|
|
66
61
|
|
|
67
|
-
/** Build pi.sendUserMessage content; keep a plain string when there are no images. */
|
|
68
62
|
export function buildImageMessageContent(
|
|
69
63
|
text: string,
|
|
70
64
|
images: readonly ImageContentLike[],
|
|
@@ -128,7 +122,6 @@ async function downloadOne(
|
|
|
128
122
|
}
|
|
129
123
|
}
|
|
130
124
|
|
|
131
|
-
/** Download images in order; one failure does not stop the others. */
|
|
132
125
|
export async function resolveInboundImages(
|
|
133
126
|
attachments: readonly InboundAttachmentLike[],
|
|
134
127
|
maxSize: number,
|
|
@@ -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,9 +104,7 @@ 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 = {
|
|
@@ -145,7 +125,6 @@ export const log = {
|
|
|
145
125
|
},
|
|
146
126
|
};
|
|
147
127
|
|
|
148
|
-
/** Adapter for the QQ SDK's Logger interface: (message, meta?) -> record. */
|
|
149
128
|
export const sdkLogger = {
|
|
150
129
|
debug(message: string, meta?: Record<string, unknown>): void {
|
|
151
130
|
log.debug("qqbot", message, meta);
|
|
@@ -161,7 +140,6 @@ export const sdkLogger = {
|
|
|
161
140
|
},
|
|
162
141
|
};
|
|
163
142
|
|
|
164
|
-
/** Short string form for noisy tool payloads. */
|
|
165
143
|
export function previewForLog(value: unknown, maxChars = 2000): string {
|
|
166
144
|
let text: string;
|
|
167
145
|
if (typeof value === "string") {
|