@chen_hu_hu/pi-qq 1.0.1 → 1.1.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.md +21 -13
- package/doc/{features.md → features-v1.md} +28 -50
- package/doc/features-v2.md +97 -0
- package/doc/{plan.md → plan-v1.md} +23 -28
- package/doc/plan-v2.md +245 -0
- package/index.ts +68 -59
- package/package.json +2 -2
- package/src/append-stream.ts +21 -20
- package/src/bot.ts +58 -20
- package/src/budget-status.ts +1 -1
- package/src/config.ts +9 -8
- package/src/download.ts +11 -11
- package/src/files.ts +10 -10
- package/src/format.ts +6 -1
- package/src/images.ts +25 -13
- package/src/inbound.ts +103 -26
- package/src/logger.ts +180 -0
- package/src/outbound.ts +42 -25
- package/src/qrcode-terminal.d.ts +1 -1
- package/src/reply-budget.ts +15 -15
- package/src/run-feedback.ts +85 -102
- package/src/voice.ts +25 -0
- package/src/usage.ts +0 -93
package/src/bot.ts
CHANGED
|
@@ -8,65 +8,103 @@ import {
|
|
|
8
8
|
} from "@tencent-connect/qqbot-nodejs";
|
|
9
9
|
import type { QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
10
10
|
import type { Credentials } from "./config";
|
|
11
|
+
import { log, sdkLogger } from "./logger";
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
|
-
* QQBot
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* Session-level QQBot lifecycle: creation, middleware, connection state,
|
|
15
|
+
* and fatal-error reporting. start() blocks until stop()/abort, so it runs
|
|
16
|
+
* in the background (void, not awaited).
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
export type BotState =
|
|
19
|
-
| "stopped" //
|
|
20
|
-
| "starting" //
|
|
21
|
-
| "connected" //
|
|
22
|
-
| "reconnecting" //
|
|
23
|
-
| "blocked"; //
|
|
20
|
+
| "stopped" // Not running/stopped
|
|
21
|
+
| "starting" // Connecting, waiting for READY
|
|
22
|
+
| "connected" // Online (READY/RESUMED)
|
|
23
|
+
| "reconnecting" // Disconnected; the SDK is reconnecting
|
|
24
|
+
| "blocked"; // Fatal close (4914 offline / 4915 banned); manual action required
|
|
24
25
|
|
|
25
26
|
export interface StartBotOptions {
|
|
26
27
|
credentials: Credentials;
|
|
27
28
|
/** F2: QR-bound single user; production always provides it */
|
|
28
29
|
allowedOpenid?: string;
|
|
29
30
|
markdownSupport?: boolean;
|
|
30
|
-
/**
|
|
31
|
-
debug?: boolean;
|
|
32
|
-
/** 入站消息接线点(M2 起;M1 为空) */
|
|
31
|
+
/** Inbound message handler. */
|
|
33
32
|
onMessage?: (bot: QQBot, msg: QQBotInboundMessage) => void | Promise<void>;
|
|
34
|
-
/**
|
|
33
|
+
/** Connection state changes; the caller decides how to notify the UI. */
|
|
35
34
|
onStateChange?: (state: BotState, detail?: string) => void;
|
|
36
|
-
/**
|
|
35
|
+
/** Recoverable errors; the SDK reconnects automatically. */
|
|
37
36
|
onRecoverableError?: (err: Error) => void;
|
|
38
37
|
}
|
|
39
38
|
|
|
40
39
|
export interface RunningBot {
|
|
41
40
|
bot: QQBot;
|
|
42
|
-
/**
|
|
41
|
+
/** Idempotent stop. */
|
|
43
42
|
stop: () => void;
|
|
44
43
|
}
|
|
45
44
|
|
|
46
45
|
export function startBot(opts: StartBotOptions): RunningBot {
|
|
46
|
+
log.info("bot", "starting", {
|
|
47
|
+
appId: opts.credentials.appId,
|
|
48
|
+
allowedOpenid: opts.allowedOpenid,
|
|
49
|
+
markdownSupport: opts.markdownSupport,
|
|
50
|
+
});
|
|
51
|
+
|
|
47
52
|
const bot = new QQBot({
|
|
48
53
|
appId: opts.credentials.appId,
|
|
49
54
|
appSecret: opts.credentials.appSecret,
|
|
50
55
|
markdownSupport: opts.markdownSupport ?? false,
|
|
56
|
+
logger: sdkLogger,
|
|
51
57
|
});
|
|
52
58
|
|
|
53
|
-
//
|
|
59
|
+
// Echo filtering + message deduplication (SDK default 5s window).
|
|
54
60
|
bot.use(messageFilter({ skipSelfEcho: true }));
|
|
55
|
-
//
|
|
61
|
+
// Strip protocol markers such as @mentions and face tags.
|
|
56
62
|
bot.use(contentSanitizer({ stripBotMention: true }));
|
|
57
63
|
// Single-user allowlist for C2C; inbound also rejects when no QR login is active.
|
|
58
64
|
bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
|
|
59
|
-
//
|
|
65
|
+
// Serialize per user so streams and replies do not race.
|
|
60
66
|
bot.use(concurrencyGuard());
|
|
61
67
|
|
|
62
|
-
const report = (state: BotState, detail?: string) =>
|
|
68
|
+
const report = (state: BotState, detail?: string) => {
|
|
69
|
+
if (state === "blocked" || (state === "stopped" && detail)) {
|
|
70
|
+
log.error("bot", state, { detail });
|
|
71
|
+
} else if (state === "reconnecting") {
|
|
72
|
+
log.warn("bot", state, { detail });
|
|
73
|
+
} else {
|
|
74
|
+
log.info("bot", state, { detail });
|
|
75
|
+
}
|
|
76
|
+
opts.onStateChange?.(state, detail);
|
|
77
|
+
};
|
|
63
78
|
|
|
64
79
|
bot.on("ready", () => report("connected"));
|
|
65
80
|
bot.on("resumed", () => report("connected"));
|
|
66
81
|
bot.on("disconnected", ({ willReconnect }) => report(willReconnect ? "reconnecting" : "stopped"));
|
|
67
|
-
bot.on("error", (err) =>
|
|
82
|
+
bot.on("error", (err) => {
|
|
83
|
+
log.error("bot", "error event", { err });
|
|
84
|
+
opts.onRecoverableError?.(err);
|
|
85
|
+
});
|
|
68
86
|
bot.on("message", (_ctx, msg) => {
|
|
69
|
-
|
|
87
|
+
log.debug("bot", "inbound message", {
|
|
88
|
+
kind: msg.kind,
|
|
89
|
+
rawEventType: msg.rawEventType,
|
|
90
|
+
messageId: msg.messageId,
|
|
91
|
+
senderId: msg.senderId,
|
|
92
|
+
senderName: msg.senderName,
|
|
93
|
+
senderIsBot: msg.senderIsBot,
|
|
94
|
+
content: msg.content,
|
|
95
|
+
msgType: msg.msgType,
|
|
96
|
+
timestamp: msg.timestamp,
|
|
97
|
+
replyTarget: msg.replyTarget,
|
|
98
|
+
msgIdx: msg.msgIdx,
|
|
99
|
+
refMsgIdx: msg.refMsgIdx,
|
|
100
|
+
messageScene: msg.messageScene,
|
|
101
|
+
attachments: msg.attachments,
|
|
102
|
+
msgElements: msg.msgElements,
|
|
103
|
+
raw: msg.raw,
|
|
104
|
+
});
|
|
105
|
+
Promise.resolve(opts.onMessage?.(bot, msg)).catch((err: unknown) => {
|
|
106
|
+
log.error("bot", "message handler rejected", { err });
|
|
107
|
+
});
|
|
70
108
|
});
|
|
71
109
|
|
|
72
110
|
let stopped = false;
|
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
|
-
/** Render `/qq-budget` output lines; pure function for tests. */
|
|
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,
|
package/src/config.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
+
import { normalizeLogLevel, type LogLevel } from "./logger";
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* ~/.pi/agent/pi-qq.json contains non-secret settings only.
|
|
@@ -9,14 +10,12 @@ import { join } from "node:path";
|
|
|
9
10
|
* process memory, so restarting pi requires scanning a new QR code.
|
|
10
11
|
*/
|
|
11
12
|
|
|
12
|
-
/** Runtime settings (features.md §4). */
|
|
13
|
+
/** Runtime settings (features-v1.md §4). */
|
|
13
14
|
export interface PiQQSettings {
|
|
14
15
|
/** F4: stream assistant replies */
|
|
15
16
|
streamAssistant?: boolean;
|
|
16
17
|
/** F4: bot has QQ markdown permission; pass Markdown through when true */
|
|
17
18
|
markdownSupport?: boolean;
|
|
18
|
-
/** F5/F6: usage summary switch */
|
|
19
|
-
usageRelay?: boolean;
|
|
20
19
|
/** F2: how a busy agent handles new messages */
|
|
21
20
|
deliverAs?: "steer" | "followUp";
|
|
22
21
|
/** F3: QQ image download limit (bytes) */
|
|
@@ -29,7 +28,9 @@ export interface PiQQSettings {
|
|
|
29
28
|
heartbeatMaxMessages?: number;
|
|
30
29
|
/** F7: stream summary frame interval (ms, minimum 300) */
|
|
31
30
|
streamFlushMs?: number;
|
|
32
|
-
/**
|
|
31
|
+
/** Log threshold: silent, error, warn, info, debug (default: silent) */
|
|
32
|
+
logLevel?: LogLevel;
|
|
33
|
+
/** @deprecated Use logLevel; kept only for config migration. */
|
|
33
34
|
debug?: boolean;
|
|
34
35
|
/** F7: append-mode stream relay switch */
|
|
35
36
|
streamRelay?: boolean;
|
|
@@ -61,21 +62,21 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
|
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
64
|
|
|
64
|
-
export interface ResolvedSettings extends Required<PiQQSettings
|
|
65
|
+
export interface ResolvedSettings extends Required<Omit<PiQQSettings, "debug">> {}
|
|
65
66
|
|
|
66
|
-
/** Settings with defaults applied (features.md §4). */
|
|
67
|
+
/** Settings with defaults applied (features-v1.md §4). */
|
|
67
68
|
export function getSettings(config: PiQQConfig): ResolvedSettings {
|
|
69
|
+
const logLevel = normalizeLogLevel(config.logLevel ?? (config.debug ? "debug" : undefined));
|
|
68
70
|
return {
|
|
69
71
|
streamAssistant: config.streamAssistant ?? true,
|
|
70
72
|
markdownSupport: config.markdownSupport ?? false,
|
|
71
|
-
usageRelay: config.usageRelay ?? true,
|
|
72
73
|
deliverAs: config.deliverAs ?? "steer",
|
|
73
74
|
imageMaxSize: config.imageMaxSize ?? 10 * 1024 * 1024,
|
|
74
75
|
fileMaxSize: config.fileMaxSize ?? 50 * 1024 * 1024,
|
|
75
76
|
heartbeatMinutes: config.heartbeatMinutes ?? 10,
|
|
76
77
|
heartbeatMaxMessages: config.heartbeatMaxMessages ?? 3,
|
|
77
78
|
streamFlushMs: config.streamFlushMs ?? 10_000,
|
|
78
|
-
|
|
79
|
+
logLevel,
|
|
79
80
|
streamRelay: config.streamRelay ?? true,
|
|
80
81
|
};
|
|
81
82
|
}
|
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
|
}
|
|
@@ -21,7 +21,7 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
21
21
|
if (!response.body) {
|
|
22
22
|
const body = Buffer.from(await response.arrayBuffer());
|
|
23
23
|
if (body.byteLength > limit) {
|
|
24
|
-
throw new Error(`${kind}
|
|
24
|
+
throw new Error(`${kind} too large (${formatBytes(body.byteLength)} > ${formatBytes(limit)})`);
|
|
25
25
|
}
|
|
26
26
|
return body;
|
|
27
27
|
}
|
|
@@ -37,28 +37,28 @@ async function readBodyLimited(response: Response, limit: number, kind: string):
|
|
|
37
37
|
total += value.byteLength;
|
|
38
38
|
if (total > limit) {
|
|
39
39
|
await reader.cancel();
|
|
40
|
-
throw new Error(`${kind}
|
|
40
|
+
throw new Error(`${kind} too large (>${formatBytes(limit)})`);
|
|
41
41
|
}
|
|
42
42
|
chunks.push(value);
|
|
43
43
|
}
|
|
44
44
|
} finally {
|
|
45
45
|
reader.releaseLock();
|
|
46
46
|
}
|
|
47
|
-
if (total === 0) throw new Error(
|
|
47
|
+
if (total === 0) throw new Error(`empty ${kind} content`);
|
|
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;
|
|
55
55
|
try {
|
|
56
56
|
parsed = new URL(opts.url);
|
|
57
57
|
} catch {
|
|
58
|
-
throw new Error(
|
|
58
|
+
throw new Error(`invalid ${opts.kind} URL`);
|
|
59
59
|
}
|
|
60
60
|
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
61
|
-
throw new Error(
|
|
61
|
+
throw new Error(`unsupported ${opts.kind} URL protocol`);
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
const controller = new AbortController();
|
|
@@ -67,19 +67,19 @@ export async function downloadLimited(opts: DownloadOptions): Promise<Buffer> {
|
|
|
67
67
|
try {
|
|
68
68
|
const response = await fetchImpl(parsed.toString(), { signal: controller.signal, redirect: "follow" });
|
|
69
69
|
if (!response.ok) {
|
|
70
|
-
throw new Error(
|
|
70
|
+
throw new Error(`download failed (HTTP ${response.status})`);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
const lengthHeader = response.headers.get("content-length");
|
|
74
74
|
const contentLength = lengthHeader ? Number(lengthHeader) : NaN;
|
|
75
75
|
if (Number.isFinite(contentLength) && contentLength > limit) {
|
|
76
76
|
await response.body?.cancel();
|
|
77
|
-
throw new Error(`${opts.kind}
|
|
77
|
+
throw new Error(`${opts.kind} too large (${formatBytes(contentLength)} > ${formatBytes(limit)})`);
|
|
78
78
|
}
|
|
79
79
|
return await readBodyLimited(response, limit, opts.kind);
|
|
80
80
|
} catch (err) {
|
|
81
81
|
if (controller.signal.aborted) {
|
|
82
|
-
throw new Error(
|
|
82
|
+
throw new Error(`download timed out after ${opts.timeoutMs / 1000}s`);
|
|
83
83
|
}
|
|
84
84
|
throw err;
|
|
85
85
|
} finally {
|
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
|
|
@@ -78,10 +78,10 @@ async function writeUnique(dir: string, filename: string, body: Buffer): Promise
|
|
|
78
78
|
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
|
-
throw new Error("
|
|
81
|
+
throw new Error("Could not allocate a unique filename");
|
|
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,
|
|
@@ -102,7 +102,7 @@ export async function saveInboundFiles(
|
|
|
102
102
|
const fallback = `file-${index + 1}`;
|
|
103
103
|
const filename = sanitizeFilename(attachment.filename, fallback);
|
|
104
104
|
if (typeof attachment.size === "number" && attachment.size > limit) {
|
|
105
|
-
failures.push({ filename, reason:
|
|
105
|
+
failures.push({ filename, reason: `file too large (${formatBytes(attachment.size)} > ${formatBytes(limit)})` });
|
|
106
106
|
continue;
|
|
107
107
|
}
|
|
108
108
|
|
|
@@ -111,20 +111,20 @@ export async function saveInboundFiles(
|
|
|
111
111
|
url: attachment.url,
|
|
112
112
|
maxSize: limit,
|
|
113
113
|
timeoutMs: DOWNLOAD_TIMEOUT_MS,
|
|
114
|
-
kind: "
|
|
114
|
+
kind: "file",
|
|
115
115
|
fetchImpl,
|
|
116
116
|
});
|
|
117
117
|
const path = await writeUnique(dir, filename, body);
|
|
118
118
|
files.push({ path, originalName: filename, size: body.byteLength });
|
|
119
119
|
} catch (err) {
|
|
120
|
-
failures.push({ filename, reason: err instanceof Error ? err.message : "
|
|
120
|
+
failures.push({ filename, reason: err instanceof Error ? err.message : "Download failed" });
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
123
|
|
|
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
|
|
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[],
|
|
@@ -78,13 +78,15 @@ export function buildImageMessageContent(
|
|
|
78
78
|
|
|
79
79
|
export function formatImageFailures(failures: readonly ImageFailure[], successCount: number): string {
|
|
80
80
|
const title =
|
|
81
|
-
successCount > 0
|
|
82
|
-
|
|
81
|
+
successCount > 0
|
|
82
|
+
? `⚠️ ${failures.length} attachment(s) failed (${successCount} succeeded):`
|
|
83
|
+
: "⚠️ Attachment failed:";
|
|
84
|
+
return [title, ...failures.map((failure) => `• ${failure.filename}: ${failure.reason}`)].join("\n");
|
|
83
85
|
}
|
|
84
86
|
|
|
85
87
|
function attachmentLabel(filename: string | undefined, index: number): string {
|
|
86
88
|
const name = filename?.trim();
|
|
87
|
-
return name ||
|
|
89
|
+
return name || `Image ${index + 1}`;
|
|
88
90
|
}
|
|
89
91
|
|
|
90
92
|
async function downloadOne(
|
|
@@ -96,10 +98,20 @@ async function downloadOne(
|
|
|
96
98
|
const filename = attachmentLabel(attachment.filename, index);
|
|
97
99
|
const mimeType = resolveImageMime(attachment.content_type, attachment.filename);
|
|
98
100
|
if (!mimeType) {
|
|
99
|
-
return {
|
|
101
|
+
return {
|
|
102
|
+
failure: {
|
|
103
|
+
filename,
|
|
104
|
+
reason: `Unsupported attachment type (${attachment.content_type || "unknown"})`,
|
|
105
|
+
},
|
|
106
|
+
};
|
|
100
107
|
}
|
|
101
108
|
if (typeof attachment.size === "number" && attachment.size > maxSize) {
|
|
102
|
-
return {
|
|
109
|
+
return {
|
|
110
|
+
failure: {
|
|
111
|
+
filename,
|
|
112
|
+
reason: `image too large (${formatBytes(attachment.size)} > ${formatBytes(maxSize)})`,
|
|
113
|
+
},
|
|
114
|
+
};
|
|
103
115
|
}
|
|
104
116
|
|
|
105
117
|
try {
|
|
@@ -107,16 +119,16 @@ async function downloadOne(
|
|
|
107
119
|
url: attachment.url,
|
|
108
120
|
maxSize,
|
|
109
121
|
timeoutMs: DOWNLOAD_TIMEOUT_MS,
|
|
110
|
-
kind: "
|
|
122
|
+
kind: "image",
|
|
111
123
|
fetchImpl,
|
|
112
124
|
});
|
|
113
125
|
return { image: { type: "image", data: body.toString("base64"), mimeType } };
|
|
114
126
|
} catch (err) {
|
|
115
|
-
return { failure: { filename, reason: err instanceof Error ? err.message : "
|
|
127
|
+
return { failure: { filename, reason: err instanceof Error ? err.message : "Download failed" } };
|
|
116
128
|
}
|
|
117
129
|
}
|
|
118
130
|
|
|
119
|
-
/**
|
|
131
|
+
/** Download images in order; one failure does not stop the others. */
|
|
120
132
|
export async function resolveInboundImages(
|
|
121
133
|
attachments: readonly InboundAttachmentLike[],
|
|
122
134
|
maxSize: number,
|