@chen_hu_hu/pi-qq 1.3.0 → 1.3.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/CHANGELOG.md +61 -0
- package/README-zh.md +67 -47
- package/README.md +70 -50
- package/doc/archive/README.md +18 -0
- package/doc/{delivery-v1-zh.md → archive/delivery-v1-zh.md} +9 -8
- package/doc/{delivery-v1.md → archive/delivery-v1.md} +4 -3
- package/doc/{delivery-v2-zh.md → archive/delivery-v2-zh.md} +3 -2
- package/doc/{delivery-v2.md → archive/delivery-v2.md} +3 -2
- package/doc/{delivery-v3-zh.md → archive/delivery-v3-zh.md} +5 -2
- package/doc/{delivery-v3.md → archive/delivery-v3.md} +6 -3
- package/index.ts +70 -156
- package/package.json +5 -1
- package/src/attachments/attachment-failure.ts +12 -0
- package/src/attachments/file-attachments.ts +16 -19
- package/src/infra/file-logger.ts +21 -9
- package/src/infra/settings.ts +62 -8
- package/src/qq/inbound-attachments.ts +101 -0
- package/src/qq/inbound-command.ts +74 -0
- package/src/qq/qq-bot.ts +2 -2
- package/src/qq/qq-diagnostics.ts +129 -0
- package/src/qq/qq-message-handler.ts +42 -156
- package/src/qq/qr-login.ts +4 -1
- package/src/qq/reply-sender.ts +5 -4
- package/src/relay/bubble-writer.ts +338 -0
- package/src/relay/run-stream-relay.ts +50 -348
- package/src/relay/stream-block-format.ts +7 -4
- package/src/attachments/image-attachments.ts +0 -142
package/index.ts
CHANGED
|
@@ -1,16 +1,15 @@
|
|
|
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 {
|
|
13
|
-
import { configureLogger, log, previewForLog } from "./src/infra/file-logger";
|
|
12
|
+
import { configureLogger, flushLogs, isLogEnabled, log, previewForLog } from "./src/infra/file-logger";
|
|
14
13
|
import { pruneUploadIndex, sessionUploadDir } from "./src/attachments/file-attachments";
|
|
15
14
|
|
|
16
15
|
interface LoginState {
|
|
@@ -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: () =>
|
|
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
|
|
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
|
|
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 =
|
|
60
|
-
const 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 =
|
|
90
|
+
const settings = activeSettings;
|
|
76
91
|
configureLogger(settings.logLevel, join(ctx.cwd, ".pi", "pi-qq", "logs"));
|
|
77
|
-
|
|
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
|
-
|
|
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 {
|
|
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", {
|
|
@@ -145,11 +149,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
145
149
|
}
|
|
146
150
|
});
|
|
147
151
|
|
|
148
|
-
pi.on("session_shutdown", () => {
|
|
152
|
+
pi.on("session_shutdown", async () => {
|
|
149
153
|
log.info("session", "shutting down");
|
|
150
154
|
stopIfRunning();
|
|
151
|
-
|
|
152
|
-
runFeedback.dispose();
|
|
155
|
+
await flushLogs();
|
|
153
156
|
});
|
|
154
157
|
|
|
155
158
|
pi.on("agent_start", () => {
|
|
@@ -163,21 +166,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
163
166
|
});
|
|
164
167
|
|
|
165
168
|
pi.on("tool_execution_start", (event) => {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
169
|
+
if (isLogEnabled("debug")) {
|
|
170
|
+
log.debug("tool", "start", {
|
|
171
|
+
toolName: event.toolName,
|
|
172
|
+
toolCallId: event.toolCallId,
|
|
173
|
+
args: previewForLog(event.args),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
171
176
|
void runFeedback.onToolStart(event.toolName, event.args, event.toolCallId);
|
|
172
177
|
});
|
|
173
178
|
|
|
174
179
|
pi.on("tool_execution_end", (event) => {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
180
|
+
if (isLogEnabled("debug")) {
|
|
181
|
+
log.debug("tool", "end", {
|
|
182
|
+
toolName: event.toolName,
|
|
183
|
+
toolCallId: event.toolCallId,
|
|
184
|
+
isError: event.isError,
|
|
185
|
+
result: previewForLog(event.result),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
181
188
|
runFeedback.onToolEnd(event.toolName, event.isError, event.result, event.toolCallId);
|
|
182
189
|
});
|
|
183
190
|
|
|
@@ -200,17 +207,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
200
207
|
if (msg.role !== "assistant" || !running) return;
|
|
201
208
|
|
|
202
209
|
const fromQQ = runFeedback.isQQRunActive();
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
.
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
210
|
+
if (isLogEnabled("debug")) {
|
|
211
|
+
log.debug("pi", "assistant message ended", {
|
|
212
|
+
fromQQ,
|
|
213
|
+
stopReason: msg.stopReason,
|
|
214
|
+
contentTypes: msg.content.map((block) => block.type),
|
|
215
|
+
textPreview: previewForLog(
|
|
216
|
+
msg.content
|
|
217
|
+
.filter((block) => block.type === "text")
|
|
218
|
+
.map((block) => block.text)
|
|
219
|
+
.join("\n"),
|
|
220
|
+
),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
214
223
|
if (!fromQQ) return;
|
|
215
224
|
|
|
216
225
|
const isError = msg.stopReason === "error";
|
|
@@ -232,7 +241,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
232
241
|
}
|
|
233
242
|
|
|
234
243
|
const streamTookOver = await runFeedback.onAssistantFinal(text, isError);
|
|
235
|
-
|
|
244
|
+
if (isLogEnabled("debug")) {
|
|
245
|
+
log.debug("pi", "stream takeover decision", { streamTookOver, isError, textPreview: previewForLog(text) });
|
|
246
|
+
}
|
|
236
247
|
if (streamTookOver) return;
|
|
237
248
|
|
|
238
249
|
const payload = markdownToPlain(text);
|
|
@@ -255,12 +266,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
255
266
|
pi.registerCommand("qq-login", {
|
|
256
267
|
description: "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
257
268
|
handler: async (_args, ctx) => {
|
|
258
|
-
|
|
259
|
-
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
260
|
-
|
|
269
|
+
applyConfig(ctx);
|
|
261
270
|
stopIfRunning();
|
|
262
271
|
setLoginState(undefined);
|
|
263
|
-
let result;
|
|
272
|
+
let result: QrLoginResult | undefined;
|
|
264
273
|
try {
|
|
265
274
|
result = await runQrLogin(ctx);
|
|
266
275
|
} catch (err) {
|
|
@@ -289,14 +298,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
289
298
|
pi.registerCommand("qq-status", {
|
|
290
299
|
description: "pi-qq: show login, connection, and bound QQ user",
|
|
291
300
|
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");
|
|
301
|
+
ctx.ui.notify(getStatusLines(ctx).join("\n"), "info");
|
|
300
302
|
},
|
|
301
303
|
});
|
|
302
304
|
|
|
@@ -321,97 +323,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
321
323
|
},
|
|
322
324
|
});
|
|
323
325
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
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
|
-
},
|
|
326
|
+
registerQQDiagnostics(pi, {
|
|
327
|
+
getRunning: () => running,
|
|
328
|
+
budget,
|
|
329
|
+
getBoundOpenid: () => getLoginState()?.allowedOpenid,
|
|
416
330
|
});
|
|
417
331
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chen_hu_hu/pi-qq",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.2",
|
|
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
|
},
|
|
@@ -34,6 +37,7 @@
|
|
|
34
37
|
"index.ts",
|
|
35
38
|
"src",
|
|
36
39
|
"doc",
|
|
40
|
+
"CHANGELOG.md",
|
|
37
41
|
"README.md",
|
|
38
42
|
"README-zh.md",
|
|
39
43
|
"LICENSE"
|
|
@@ -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:
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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:
|
|
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
|
|
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
|
-
"
|
|
245
|
-
...files.map((file) =>
|
|
238
|
+
"# Attachments:",
|
|
239
|
+
...files.map((file) => {
|
|
240
|
+
const displayPath = relative(cwd, file.path);
|
|
241
|
+
return `- ${displayPath && !displayPath.startsWith("..") ? displayPath : file.path}`;
|
|
242
|
+
}),
|
|
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
|
}
|
package/src/infra/file-logger.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
|
|
4
4
|
export type LogLevel = "silent" | "error" | "warn" | "info" | "debug";
|
|
@@ -16,6 +16,7 @@ const DEFAULT_LOG_LEVEL: LogLevel = "silent";
|
|
|
16
16
|
|
|
17
17
|
let activeLevel: LogLevel = DEFAULT_LOG_LEVEL;
|
|
18
18
|
let activeDir: string | undefined;
|
|
19
|
+
let writeQueue: Promise<void> = Promise.resolve();
|
|
19
20
|
|
|
20
21
|
function isLogLevel(value: unknown): value is LogLevel {
|
|
21
22
|
return typeof value === "string" && Object.hasOwn(LEVEL_WEIGHT, value);
|
|
@@ -29,6 +30,15 @@ export function isLevelEnabled(configured: LogLevel, level: Exclude<LogLevel, "s
|
|
|
29
30
|
return configured !== "silent" && LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[configured];
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
export function isLogEnabled(level: Exclude<LogLevel, "silent">): boolean {
|
|
34
|
+
return isLevelEnabled(activeLevel, level);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Resolve once every queued log record has been written (or dropped). */
|
|
38
|
+
export async function flushLogs(): Promise<void> {
|
|
39
|
+
await writeQueue;
|
|
40
|
+
}
|
|
41
|
+
|
|
32
42
|
export function configureLogger(level: LogLevel, dir?: string): void {
|
|
33
43
|
activeLevel = normalizeLogLevel(level);
|
|
34
44
|
activeDir = dir;
|
|
@@ -100,17 +110,19 @@ function writeRecord(level: Exclude<LogLevel, "silent">, scope: string, message:
|
|
|
100
110
|
});
|
|
101
111
|
}
|
|
102
112
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
113
|
+
const dir = resolveLogDir();
|
|
114
|
+
const path = join(dir, logFileName());
|
|
115
|
+
writeQueue = writeQueue
|
|
116
|
+
.then(async () => {
|
|
117
|
+
try {
|
|
118
|
+
await mkdir(dir, { recursive: true });
|
|
119
|
+
await appendFile(path, `${line}\n`, "utf8");
|
|
120
|
+
} catch {}
|
|
121
|
+
})
|
|
122
|
+
.catch(() => {});
|
|
108
123
|
}
|
|
109
124
|
|
|
110
125
|
export const log = {
|
|
111
|
-
get level(): LogLevel {
|
|
112
|
-
return activeLevel;
|
|
113
|
-
},
|
|
114
126
|
debug(scope: string, message: string, data?: unknown): void {
|
|
115
127
|
writeRecord("debug", scope, message, data);
|
|
116
128
|
},
|
package/src/infra/settings.ts
CHANGED
|
@@ -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
|
-
|
|
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():
|
|
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
|
|
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:
|
|
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
|
};
|