chatccc 0.2.190 → 0.2.192
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/agent-prompts/claude_specific.md +45 -45
- package/agent-prompts/codex_specific.md +2 -2
- package/agent-prompts/cursor_specific.md +13 -13
- package/config.sample.json +14 -14
- package/im-skills/feishu-skill/receive-send-file.md +63 -63
- package/im-skills/feishu-skill/receive-send-image.md +24 -24
- package/im-skills/feishu-skill/skill.md +3 -3
- package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
- package/im-skills/wechat-file-skill/send-file.mjs +83 -83
- package/im-skills/wechat-file-skill/skill.md +10 -10
- package/im-skills/wechat-image-skill/skill.md +10 -10
- package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
- package/im-skills/wechat-video-skill/send-video.mjs +79 -79
- package/im-skills/wechat-video-skill/skill.md +10 -10
- package/package.json +1 -1
- package/scripts/postinstall-sharp-check.mjs +58 -58
- package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
- package/src/__tests__/builtin-chat-session.test.ts +76 -0
- package/src/__tests__/builtin-config.test.ts +33 -33
- package/src/__tests__/builtin-context.test.ts +126 -0
- package/src/__tests__/builtin-sigint.test.ts +56 -0
- package/src/__tests__/card-plain-text.test.ts +5 -5
- package/src/__tests__/cardkit.test.ts +60 -60
- package/src/__tests__/cards.test.ts +77 -77
- package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
- package/src/__tests__/chatgpt-subscription.test.ts +135 -135
- package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
- package/src/__tests__/claude-adapter.test.ts +592 -592
- package/src/__tests__/codex-reset-actions.test.ts +146 -146
- package/src/__tests__/config-reload.test.ts +4 -4
- package/src/__tests__/config-sample.test.ts +17 -17
- package/src/__tests__/feishu-api.test.ts +60 -60
- package/src/__tests__/feishu-platform.test.ts +22 -22
- package/src/__tests__/format-message.test.ts +47 -47
- package/src/__tests__/orchestrator.test.ts +120 -120
- package/src/__tests__/privacy.test.ts +198 -198
- package/src/__tests__/raw-stream-log.test.ts +106 -106
- package/src/__tests__/session.test.ts +17 -17
- package/src/__tests__/shared-prefix.test.ts +36 -36
- package/src/__tests__/stream-state.test.ts +42 -42
- package/src/__tests__/web-ui.test.ts +209 -209
- package/src/adapters/claude-adapter.ts +566 -566
- package/src/adapters/claude-session-meta-store.ts +120 -120
- package/src/adapters/codex-adapter.ts +30 -30
- package/src/adapters/cursor-adapter.ts +46 -46
- package/src/adapters/raw-stream-log.ts +124 -124
- package/src/adapters/resource-monitor.ts +140 -140
- package/src/agent-delegate-task-rpc.ts +153 -153
- package/src/agent-delegate-task.ts +81 -81
- package/src/agent-stop-stuck.ts +129 -129
- package/src/builtin/cli.ts +211 -189
- package/src/builtin/context.ts +225 -0
- package/src/builtin/index.ts +232 -170
- package/src/builtin/sigint.ts +50 -0
- package/src/cards.ts +137 -137
- package/src/chatgpt-subscription-rpc.ts +27 -27
- package/src/chatgpt-subscription.ts +299 -299
- package/src/chrome-devtools-guard.ts +318 -318
- package/src/codex-reset-actions.ts +184 -184
- package/src/config.ts +86 -86
- package/src/feishu-platform.ts +20 -20
- package/src/format-message.ts +293 -293
- package/src/litellm-proxy.ts +374 -374
- package/src/orchestrator.ts +143 -143
- package/src/privacy.ts +118 -118
- package/src/session-chat-binding.ts +6 -6
- package/src/session-name.ts +8 -8
- package/src/session.ts +98 -98
- package/src/shared-prefix.ts +29 -29
- package/src/sim-platform.ts +20 -20
- package/src/turn-cards.ts +117 -117
- package/src/web-ui.ts +205 -205
package/src/feishu-platform.ts
CHANGED
|
@@ -29,10 +29,10 @@ export interface FeishuPlatform {
|
|
|
29
29
|
updateChatInfo: typeof realApi.updateChatInfo;
|
|
30
30
|
getChatInfo: typeof realApi.getChatInfo;
|
|
31
31
|
disbandChat: typeof realApi.disbandChat;
|
|
32
|
-
setChatAvatar: typeof realApi.setChatAvatar;
|
|
33
|
-
getCodexUsageSummary: typeof realApi.getCodexUsageSummary;
|
|
34
|
-
consumeCodexRateLimitResetCredit: typeof realApi.consumeCodexRateLimitResetCredit;
|
|
35
|
-
getOrDownloadImage: typeof realApi.getOrDownloadImage;
|
|
32
|
+
setChatAvatar: typeof realApi.setChatAvatar;
|
|
33
|
+
getCodexUsageSummary: typeof realApi.getCodexUsageSummary;
|
|
34
|
+
consumeCodexRateLimitResetCredit: typeof realApi.consumeCodexRateLimitResetCredit;
|
|
35
|
+
getOrDownloadImage: typeof realApi.getOrDownloadImage;
|
|
36
36
|
verifyAllPermissions: typeof realApi.verifyAllPermissions;
|
|
37
37
|
reportPermissionResults: typeof realApi.reportPermissionResults;
|
|
38
38
|
extractSessionInfo: typeof realApi.extractSessionInfo;
|
|
@@ -110,21 +110,21 @@ export function disbandChat(...args: Parameters<typeof realApi.disbandChat>): Re
|
|
|
110
110
|
return _impl.disbandChat(...args);
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
-
export function setChatAvatar(...args: Parameters<typeof realApi.setChatAvatar>): ReturnType<typeof realApi.setChatAvatar> {
|
|
114
|
-
return _impl.setChatAvatar(...args);
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
export function getCodexUsageSummary(...args: Parameters<typeof realApi.getCodexUsageSummary>): ReturnType<typeof realApi.getCodexUsageSummary> {
|
|
118
|
-
return _impl.getCodexUsageSummary(...args);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
export function consumeCodexRateLimitResetCredit(...args: Parameters<typeof realApi.consumeCodexRateLimitResetCredit>): ReturnType<typeof realApi.consumeCodexRateLimitResetCredit> {
|
|
122
|
-
return _impl.consumeCodexRateLimitResetCredit(...args);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
export function getOrDownloadImage(...args: Parameters<typeof realApi.getOrDownloadImage>): ReturnType<typeof realApi.getOrDownloadImage> {
|
|
126
|
-
return _impl.getOrDownloadImage(...args);
|
|
127
|
-
}
|
|
113
|
+
export function setChatAvatar(...args: Parameters<typeof realApi.setChatAvatar>): ReturnType<typeof realApi.setChatAvatar> {
|
|
114
|
+
return _impl.setChatAvatar(...args);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function getCodexUsageSummary(...args: Parameters<typeof realApi.getCodexUsageSummary>): ReturnType<typeof realApi.getCodexUsageSummary> {
|
|
118
|
+
return _impl.getCodexUsageSummary(...args);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function consumeCodexRateLimitResetCredit(...args: Parameters<typeof realApi.consumeCodexRateLimitResetCredit>): ReturnType<typeof realApi.consumeCodexRateLimitResetCredit> {
|
|
122
|
+
return _impl.consumeCodexRateLimitResetCredit(...args);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function getOrDownloadImage(...args: Parameters<typeof realApi.getOrDownloadImage>): ReturnType<typeof realApi.getOrDownloadImage> {
|
|
126
|
+
return _impl.getOrDownloadImage(...args);
|
|
127
|
+
}
|
|
128
128
|
|
|
129
129
|
export function verifyAllPermissions(...args: Parameters<typeof realApi.verifyAllPermissions>): ReturnType<typeof realApi.verifyAllPermissions> {
|
|
130
130
|
return _impl.verifyAllPermissions(...args);
|
|
@@ -156,4 +156,4 @@ export function sendRestartCard(...args: Parameters<typeof realApi.sendRestartCa
|
|
|
156
156
|
|
|
157
157
|
export function getMergeForwardMessages(...args: Parameters<typeof realApi.getMergeForwardMessages>): ReturnType<typeof realApi.getMergeForwardMessages> {
|
|
158
158
|
return _impl.getMergeForwardMessages(...args);
|
|
159
|
-
}
|
|
159
|
+
}
|
package/src/format-message.ts
CHANGED
|
@@ -1,293 +1,293 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* format-message.ts — 飞书消息内容格式化
|
|
3
|
-
*
|
|
4
|
-
* 从 index.ts 中提取,独立模块便于测试。
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { cardJsonToPlainText } from "./card-plain-text.ts";
|
|
8
|
-
import { ts } from "./config.ts";
|
|
9
|
-
import {
|
|
10
|
-
getTenantAccessToken,
|
|
11
|
-
getOrDownloadImage,
|
|
12
|
-
getMergeForwardMessages,
|
|
13
|
-
} from "./feishu-platform.ts";
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* 根据消息类型格式化消息内容为可读文本。
|
|
17
|
-
*/
|
|
18
|
-
export async function formatMessageContent(message: {
|
|
19
|
-
message_id?: string;
|
|
20
|
-
message_type?: string;
|
|
21
|
-
content?: string;
|
|
22
|
-
}): Promise<string> {
|
|
23
|
-
const contentStr = message.content ?? "{}";
|
|
24
|
-
let content: Record<string, unknown>;
|
|
25
|
-
try { content = JSON.parse(contentStr); } catch {
|
|
26
|
-
// merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
|
|
27
|
-
if (message.message_type === "merge_forward") {
|
|
28
|
-
content = {};
|
|
29
|
-
} else {
|
|
30
|
-
return "";
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (message.message_type === "text") {
|
|
35
|
-
let text = (content.text ?? "") as string;
|
|
36
|
-
text = text.replace(/<\/?p[^>]*>/gi, "");
|
|
37
|
-
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
38
|
-
text = text.replace(/ /gi, " ");
|
|
39
|
-
return text.trim();
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (message.message_type === "post") {
|
|
43
|
-
return formatPostContentWithImages(content, message.message_id);
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
if (message.message_type === "image") {
|
|
47
|
-
const imageKey = content.image_key as string | undefined;
|
|
48
|
-
const messageId = message.message_id;
|
|
49
|
-
if (!imageKey || !messageId) return contentStr;
|
|
50
|
-
try {
|
|
51
|
-
const token = await getTenantAccessToken();
|
|
52
|
-
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
53
|
-
return `[图片] ${localPath}`;
|
|
54
|
-
} catch (err) {
|
|
55
|
-
console.error(
|
|
56
|
-
`[${ts()}] [IMAGE] download failed for ${imageKey}: ${(err as Error).message}`,
|
|
57
|
-
);
|
|
58
|
-
return `[图片: ${imageKey}]`;
|
|
59
|
-
}
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
if (message.message_type === "media") {
|
|
63
|
-
const fileKey = content.file_key as string | undefined;
|
|
64
|
-
const fileName = (content.file_name as string) || "video.mp4";
|
|
65
|
-
const messageId = message.message_id;
|
|
66
|
-
if (!fileKey || !messageId) return contentStr;
|
|
67
|
-
return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
if (message.message_type === "file") {
|
|
71
|
-
const fileKey = content.file_key as string | undefined;
|
|
72
|
-
const fileName = (content.file_name as string) || "download.bin";
|
|
73
|
-
const messageId = message.message_id;
|
|
74
|
-
if (!fileKey || !messageId) return contentStr;
|
|
75
|
-
return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
if (message.message_type === "interactive") {
|
|
79
|
-
const raw = JSON.stringify(content);
|
|
80
|
-
const text = cardJsonToPlainText(raw);
|
|
81
|
-
if (text) return `[卡片] ${text}`;
|
|
82
|
-
return contentStr;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
if (message.message_type === "merge_forward") {
|
|
86
|
-
return formatMergeForward(message.message_id ?? "", content);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// 其他类型(audio, sticker 等)直接给原始 JSON
|
|
90
|
-
return contentStr;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
export function formatPostContent(content: Record<string, unknown>): string {
|
|
94
|
-
const paragraphs = getPostParagraphs(content);
|
|
95
|
-
if (!Array.isArray(paragraphs)) return "";
|
|
96
|
-
|
|
97
|
-
const parts: string[] = [];
|
|
98
|
-
for (const line of paragraphs) {
|
|
99
|
-
if (!Array.isArray(line)) continue;
|
|
100
|
-
for (const elem of line) {
|
|
101
|
-
const el = elem as Record<string, unknown>;
|
|
102
|
-
if (!el || typeof el !== "object") continue;
|
|
103
|
-
const text = formatPostTextElement(el);
|
|
104
|
-
if (text) parts.push(text);
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
return parts.join("\n").trim();
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function getPostParagraphs(content: Record<string, unknown>): unknown[][] {
|
|
111
|
-
const direct = content.content;
|
|
112
|
-
if (Array.isArray(direct)) return direct as unknown[][];
|
|
113
|
-
|
|
114
|
-
for (const locale of ["zh_cn", "en_us", "ja_jp"]) {
|
|
115
|
-
const localized = content[locale] as Record<string, unknown> | undefined;
|
|
116
|
-
if (localized && Array.isArray(localized.content)) {
|
|
117
|
-
return localized.content as unknown[][];
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return [];
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function formatPostTextElement(el: Record<string, unknown>): string {
|
|
125
|
-
const t = typeof el.text === "string" ? el.text : "";
|
|
126
|
-
|
|
127
|
-
if (el.tag === "code_block") {
|
|
128
|
-
const lang = typeof el.language === "string" ? el.language : "";
|
|
129
|
-
return "```" + lang + "\n" + t + "\n```";
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
if (el.tag === "p" || el.tag === "text") {
|
|
133
|
-
return t;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
return "";
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function getPostImageKey(el: Record<string, unknown>): string | undefined {
|
|
140
|
-
const imageKey = el.image_key;
|
|
141
|
-
if (typeof imageKey === "string" && imageKey.trim()) return imageKey;
|
|
142
|
-
|
|
143
|
-
if (el.tag === "img") {
|
|
144
|
-
const fileKey = el.file_key;
|
|
145
|
-
if (typeof fileKey === "string" && fileKey.trim()) return fileKey;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
return undefined;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
async function formatPostContentWithImages(
|
|
152
|
-
content: Record<string, unknown>,
|
|
153
|
-
messageId?: string,
|
|
154
|
-
): Promise<string> {
|
|
155
|
-
const paragraphs = getPostParagraphs(content);
|
|
156
|
-
if (!Array.isArray(paragraphs)) return "";
|
|
157
|
-
|
|
158
|
-
const parts: string[] = [];
|
|
159
|
-
for (const line of paragraphs) {
|
|
160
|
-
if (!Array.isArray(line)) continue;
|
|
161
|
-
for (const elem of line) {
|
|
162
|
-
const el = elem as Record<string, unknown>;
|
|
163
|
-
if (!el || typeof el !== "object") continue;
|
|
164
|
-
|
|
165
|
-
const text = formatPostTextElement(el);
|
|
166
|
-
if (text) parts.push(text);
|
|
167
|
-
|
|
168
|
-
const imageKey = getPostImageKey(el);
|
|
169
|
-
if (imageKey) {
|
|
170
|
-
parts.push(await formatPostImageElement(messageId, imageKey));
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return parts.join("\n").trim();
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
async function formatPostImageElement(
|
|
178
|
-
messageId: string | undefined,
|
|
179
|
-
imageKey: string,
|
|
180
|
-
): Promise<string> {
|
|
181
|
-
if (!messageId) return `[图片: ${imageKey}]`;
|
|
182
|
-
|
|
183
|
-
try {
|
|
184
|
-
const token = await getTenantAccessToken();
|
|
185
|
-
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
186
|
-
return `[图片] ${localPath}`;
|
|
187
|
-
} catch (err) {
|
|
188
|
-
console.error(
|
|
189
|
-
`[${ts()}] [IMAGE] download failed for post image ${imageKey}: ${(err as Error).message}`,
|
|
190
|
-
);
|
|
191
|
-
return `[图片: ${imageKey}]`;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// ---------------------------------------------------------------------------
|
|
196
|
-
// 合并转发消息格式化
|
|
197
|
-
// ---------------------------------------------------------------------------
|
|
198
|
-
|
|
199
|
-
/**
|
|
200
|
-
* 格式化合并转发消息。
|
|
201
|
-
*
|
|
202
|
-
* 三阶段降级策略:
|
|
203
|
-
* 1. 调用 GET /im/v1/messages/{messageId} 获取完整子消息列表
|
|
204
|
-
* 2. API 失败时降级使用 content.preview 字段
|
|
205
|
-
* 3. preview 也为空时返回原始 JSON
|
|
206
|
-
*
|
|
207
|
-
* 递归深度限制 MAX_DEPTH=3,避免嵌套合并转发 API 爆炸。
|
|
208
|
-
*/
|
|
209
|
-
export async function formatMergeForward(
|
|
210
|
-
messageId: string,
|
|
211
|
-
content: Record<string, unknown>,
|
|
212
|
-
depth: number = 0,
|
|
213
|
-
): Promise<string> {
|
|
214
|
-
const MAX_DEPTH = 3;
|
|
215
|
-
if (depth >= MAX_DEPTH) {
|
|
216
|
-
return `[合并转发: 超出最大嵌套深度 ${MAX_DEPTH}]`;
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
const title = (content.title as string) || "聊天记录";
|
|
220
|
-
const chatName = (content.chat_name as string) || "";
|
|
221
|
-
const header = `[合并转发: ${title}${chatName ? ` (${chatName})` : ""}]`;
|
|
222
|
-
|
|
223
|
-
// 从 preview 构建 sender ID → name 映射表
|
|
224
|
-
const senderNameMap = new Map<string, string>();
|
|
225
|
-
const preview = content.preview;
|
|
226
|
-
if (Array.isArray(preview)) {
|
|
227
|
-
for (const entry of preview) {
|
|
228
|
-
const e = entry as Record<string, unknown>;
|
|
229
|
-
const s = e.sender as Record<string, unknown> | undefined;
|
|
230
|
-
if (s && typeof s.id === "string" && typeof s.name === "string") {
|
|
231
|
-
senderNameMap.set(s.id, s.name);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
const lines: string[] = [];
|
|
237
|
-
let usedApi = false;
|
|
238
|
-
|
|
239
|
-
// Phase 1: 尝试通过 API 获取完整子消息列表
|
|
240
|
-
try {
|
|
241
|
-
const token = await getTenantAccessToken();
|
|
242
|
-
const items = await getMergeForwardMessages(token, messageId);
|
|
243
|
-
|
|
244
|
-
// 跳过第一个 item(合并转发消息自身,无 upper_message_id)
|
|
245
|
-
const subItems = items.filter((item) => item.upper_message_id);
|
|
246
|
-
|
|
247
|
-
if (subItems.length > 0) {
|
|
248
|
-
for (const item of subItems) {
|
|
249
|
-
const senderId = item.sender?.id ?? "unknown";
|
|
250
|
-
const senderName = senderNameMap.get(senderId) ?? senderId;
|
|
251
|
-
|
|
252
|
-
const subMsgType = item.msg_type ?? "";
|
|
253
|
-
const subContent = item.body?.content ?? "{}";
|
|
254
|
-
|
|
255
|
-
try {
|
|
256
|
-
const formatted = await formatMessageContent({
|
|
257
|
-
message_id: item.message_id,
|
|
258
|
-
message_type: subMsgType,
|
|
259
|
-
content: subContent,
|
|
260
|
-
});
|
|
261
|
-
lines.push(`${senderName}: ${formatted}`);
|
|
262
|
-
} catch {
|
|
263
|
-
lines.push(`${senderName}: ${subContent}`);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
usedApi = true;
|
|
267
|
-
}
|
|
268
|
-
} catch (err) {
|
|
269
|
-
console.error(
|
|
270
|
-
`[${ts()}] [MERGE_FORWARD] API 获取子消息失败 (${messageId}), 降级使用 preview: ${(err as Error).message}`,
|
|
271
|
-
);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Phase 2: API 失败或返回空时降级使用 preview
|
|
275
|
-
if (!usedApi) {
|
|
276
|
-
if (Array.isArray(preview) && preview.length > 0) {
|
|
277
|
-
for (const entry of preview) {
|
|
278
|
-
const e = entry as Record<string, unknown>;
|
|
279
|
-
const s = e.sender as Record<string, unknown> | undefined;
|
|
280
|
-
const senderName = (s?.name as string) ?? "未知用户";
|
|
281
|
-
const text = (e.content as string) ?? "";
|
|
282
|
-
lines.push(`${senderName}: ${text}`);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// Phase 3: 没有任何内容时返回原始 JSON
|
|
288
|
-
if (lines.length === 0) {
|
|
289
|
-
return JSON.stringify(content);
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
return header + "\n" + lines.join("\n");
|
|
293
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* format-message.ts — 飞书消息内容格式化
|
|
3
|
+
*
|
|
4
|
+
* 从 index.ts 中提取,独立模块便于测试。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { cardJsonToPlainText } from "./card-plain-text.ts";
|
|
8
|
+
import { ts } from "./config.ts";
|
|
9
|
+
import {
|
|
10
|
+
getTenantAccessToken,
|
|
11
|
+
getOrDownloadImage,
|
|
12
|
+
getMergeForwardMessages,
|
|
13
|
+
} from "./feishu-platform.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 根据消息类型格式化消息内容为可读文本。
|
|
17
|
+
*/
|
|
18
|
+
export async function formatMessageContent(message: {
|
|
19
|
+
message_id?: string;
|
|
20
|
+
message_type?: string;
|
|
21
|
+
content?: string;
|
|
22
|
+
}): Promise<string> {
|
|
23
|
+
const contentStr = message.content ?? "{}";
|
|
24
|
+
let content: Record<string, unknown>;
|
|
25
|
+
try { content = JSON.parse(contentStr); } catch {
|
|
26
|
+
// merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
|
|
27
|
+
if (message.message_type === "merge_forward") {
|
|
28
|
+
content = {};
|
|
29
|
+
} else {
|
|
30
|
+
return "";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (message.message_type === "text") {
|
|
35
|
+
let text = (content.text ?? "") as string;
|
|
36
|
+
text = text.replace(/<\/?p[^>]*>/gi, "");
|
|
37
|
+
text = text.replace(/<br\s*\/?>/gi, "\n");
|
|
38
|
+
text = text.replace(/ /gi, " ");
|
|
39
|
+
return text.trim();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (message.message_type === "post") {
|
|
43
|
+
return formatPostContentWithImages(content, message.message_id);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (message.message_type === "image") {
|
|
47
|
+
const imageKey = content.image_key as string | undefined;
|
|
48
|
+
const messageId = message.message_id;
|
|
49
|
+
if (!imageKey || !messageId) return contentStr;
|
|
50
|
+
try {
|
|
51
|
+
const token = await getTenantAccessToken();
|
|
52
|
+
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
53
|
+
return `[图片] ${localPath}`;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
console.error(
|
|
56
|
+
`[${ts()}] [IMAGE] download failed for ${imageKey}: ${(err as Error).message}`,
|
|
57
|
+
);
|
|
58
|
+
return `[图片: ${imageKey}]`;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (message.message_type === "media") {
|
|
63
|
+
const fileKey = content.file_key as string | undefined;
|
|
64
|
+
const fileName = (content.file_name as string) || "video.mp4";
|
|
65
|
+
const messageId = message.message_id;
|
|
66
|
+
if (!fileKey || !messageId) return contentStr;
|
|
67
|
+
return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (message.message_type === "file") {
|
|
71
|
+
const fileKey = content.file_key as string | undefined;
|
|
72
|
+
const fileName = (content.file_name as string) || "download.bin";
|
|
73
|
+
const messageId = message.message_id;
|
|
74
|
+
if (!fileKey || !messageId) return contentStr;
|
|
75
|
+
return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (message.message_type === "interactive") {
|
|
79
|
+
const raw = JSON.stringify(content);
|
|
80
|
+
const text = cardJsonToPlainText(raw);
|
|
81
|
+
if (text) return `[卡片] ${text}`;
|
|
82
|
+
return contentStr;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (message.message_type === "merge_forward") {
|
|
86
|
+
return formatMergeForward(message.message_id ?? "", content);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 其他类型(audio, sticker 等)直接给原始 JSON
|
|
90
|
+
return contentStr;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function formatPostContent(content: Record<string, unknown>): string {
|
|
94
|
+
const paragraphs = getPostParagraphs(content);
|
|
95
|
+
if (!Array.isArray(paragraphs)) return "";
|
|
96
|
+
|
|
97
|
+
const parts: string[] = [];
|
|
98
|
+
for (const line of paragraphs) {
|
|
99
|
+
if (!Array.isArray(line)) continue;
|
|
100
|
+
for (const elem of line) {
|
|
101
|
+
const el = elem as Record<string, unknown>;
|
|
102
|
+
if (!el || typeof el !== "object") continue;
|
|
103
|
+
const text = formatPostTextElement(el);
|
|
104
|
+
if (text) parts.push(text);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return parts.join("\n").trim();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function getPostParagraphs(content: Record<string, unknown>): unknown[][] {
|
|
111
|
+
const direct = content.content;
|
|
112
|
+
if (Array.isArray(direct)) return direct as unknown[][];
|
|
113
|
+
|
|
114
|
+
for (const locale of ["zh_cn", "en_us", "ja_jp"]) {
|
|
115
|
+
const localized = content[locale] as Record<string, unknown> | undefined;
|
|
116
|
+
if (localized && Array.isArray(localized.content)) {
|
|
117
|
+
return localized.content as unknown[][];
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function formatPostTextElement(el: Record<string, unknown>): string {
|
|
125
|
+
const t = typeof el.text === "string" ? el.text : "";
|
|
126
|
+
|
|
127
|
+
if (el.tag === "code_block") {
|
|
128
|
+
const lang = typeof el.language === "string" ? el.language : "";
|
|
129
|
+
return "```" + lang + "\n" + t + "\n```";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (el.tag === "p" || el.tag === "text") {
|
|
133
|
+
return t;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return "";
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function getPostImageKey(el: Record<string, unknown>): string | undefined {
|
|
140
|
+
const imageKey = el.image_key;
|
|
141
|
+
if (typeof imageKey === "string" && imageKey.trim()) return imageKey;
|
|
142
|
+
|
|
143
|
+
if (el.tag === "img") {
|
|
144
|
+
const fileKey = el.file_key;
|
|
145
|
+
if (typeof fileKey === "string" && fileKey.trim()) return fileKey;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function formatPostContentWithImages(
|
|
152
|
+
content: Record<string, unknown>,
|
|
153
|
+
messageId?: string,
|
|
154
|
+
): Promise<string> {
|
|
155
|
+
const paragraphs = getPostParagraphs(content);
|
|
156
|
+
if (!Array.isArray(paragraphs)) return "";
|
|
157
|
+
|
|
158
|
+
const parts: string[] = [];
|
|
159
|
+
for (const line of paragraphs) {
|
|
160
|
+
if (!Array.isArray(line)) continue;
|
|
161
|
+
for (const elem of line) {
|
|
162
|
+
const el = elem as Record<string, unknown>;
|
|
163
|
+
if (!el || typeof el !== "object") continue;
|
|
164
|
+
|
|
165
|
+
const text = formatPostTextElement(el);
|
|
166
|
+
if (text) parts.push(text);
|
|
167
|
+
|
|
168
|
+
const imageKey = getPostImageKey(el);
|
|
169
|
+
if (imageKey) {
|
|
170
|
+
parts.push(await formatPostImageElement(messageId, imageKey));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return parts.join("\n").trim();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function formatPostImageElement(
|
|
178
|
+
messageId: string | undefined,
|
|
179
|
+
imageKey: string,
|
|
180
|
+
): Promise<string> {
|
|
181
|
+
if (!messageId) return `[图片: ${imageKey}]`;
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
const token = await getTenantAccessToken();
|
|
185
|
+
const localPath = await getOrDownloadImage(token, messageId, imageKey);
|
|
186
|
+
return `[图片] ${localPath}`;
|
|
187
|
+
} catch (err) {
|
|
188
|
+
console.error(
|
|
189
|
+
`[${ts()}] [IMAGE] download failed for post image ${imageKey}: ${(err as Error).message}`,
|
|
190
|
+
);
|
|
191
|
+
return `[图片: ${imageKey}]`;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
// 合并转发消息格式化
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* 格式化合并转发消息。
|
|
201
|
+
*
|
|
202
|
+
* 三阶段降级策略:
|
|
203
|
+
* 1. 调用 GET /im/v1/messages/{messageId} 获取完整子消息列表
|
|
204
|
+
* 2. API 失败时降级使用 content.preview 字段
|
|
205
|
+
* 3. preview 也为空时返回原始 JSON
|
|
206
|
+
*
|
|
207
|
+
* 递归深度限制 MAX_DEPTH=3,避免嵌套合并转发 API 爆炸。
|
|
208
|
+
*/
|
|
209
|
+
export async function formatMergeForward(
|
|
210
|
+
messageId: string,
|
|
211
|
+
content: Record<string, unknown>,
|
|
212
|
+
depth: number = 0,
|
|
213
|
+
): Promise<string> {
|
|
214
|
+
const MAX_DEPTH = 3;
|
|
215
|
+
if (depth >= MAX_DEPTH) {
|
|
216
|
+
return `[合并转发: 超出最大嵌套深度 ${MAX_DEPTH}]`;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const title = (content.title as string) || "聊天记录";
|
|
220
|
+
const chatName = (content.chat_name as string) || "";
|
|
221
|
+
const header = `[合并转发: ${title}${chatName ? ` (${chatName})` : ""}]`;
|
|
222
|
+
|
|
223
|
+
// 从 preview 构建 sender ID → name 映射表
|
|
224
|
+
const senderNameMap = new Map<string, string>();
|
|
225
|
+
const preview = content.preview;
|
|
226
|
+
if (Array.isArray(preview)) {
|
|
227
|
+
for (const entry of preview) {
|
|
228
|
+
const e = entry as Record<string, unknown>;
|
|
229
|
+
const s = e.sender as Record<string, unknown> | undefined;
|
|
230
|
+
if (s && typeof s.id === "string" && typeof s.name === "string") {
|
|
231
|
+
senderNameMap.set(s.id, s.name);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const lines: string[] = [];
|
|
237
|
+
let usedApi = false;
|
|
238
|
+
|
|
239
|
+
// Phase 1: 尝试通过 API 获取完整子消息列表
|
|
240
|
+
try {
|
|
241
|
+
const token = await getTenantAccessToken();
|
|
242
|
+
const items = await getMergeForwardMessages(token, messageId);
|
|
243
|
+
|
|
244
|
+
// 跳过第一个 item(合并转发消息自身,无 upper_message_id)
|
|
245
|
+
const subItems = items.filter((item) => item.upper_message_id);
|
|
246
|
+
|
|
247
|
+
if (subItems.length > 0) {
|
|
248
|
+
for (const item of subItems) {
|
|
249
|
+
const senderId = item.sender?.id ?? "unknown";
|
|
250
|
+
const senderName = senderNameMap.get(senderId) ?? senderId;
|
|
251
|
+
|
|
252
|
+
const subMsgType = item.msg_type ?? "";
|
|
253
|
+
const subContent = item.body?.content ?? "{}";
|
|
254
|
+
|
|
255
|
+
try {
|
|
256
|
+
const formatted = await formatMessageContent({
|
|
257
|
+
message_id: item.message_id,
|
|
258
|
+
message_type: subMsgType,
|
|
259
|
+
content: subContent,
|
|
260
|
+
});
|
|
261
|
+
lines.push(`${senderName}: ${formatted}`);
|
|
262
|
+
} catch {
|
|
263
|
+
lines.push(`${senderName}: ${subContent}`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
usedApi = true;
|
|
267
|
+
}
|
|
268
|
+
} catch (err) {
|
|
269
|
+
console.error(
|
|
270
|
+
`[${ts()}] [MERGE_FORWARD] API 获取子消息失败 (${messageId}), 降级使用 preview: ${(err as Error).message}`,
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Phase 2: API 失败或返回空时降级使用 preview
|
|
275
|
+
if (!usedApi) {
|
|
276
|
+
if (Array.isArray(preview) && preview.length > 0) {
|
|
277
|
+
for (const entry of preview) {
|
|
278
|
+
const e = entry as Record<string, unknown>;
|
|
279
|
+
const s = e.sender as Record<string, unknown> | undefined;
|
|
280
|
+
const senderName = (s?.name as string) ?? "未知用户";
|
|
281
|
+
const text = (e.content as string) ?? "";
|
|
282
|
+
lines.push(`${senderName}: ${text}`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Phase 3: 没有任何内容时返回原始 JSON
|
|
288
|
+
if (lines.length === 0) {
|
|
289
|
+
return JSON.stringify(content);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return header + "\n" + lines.join("\n");
|
|
293
|
+
}
|