@suwenguang/pi-feishu-bridge 0.0.0-stage → 0.6.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/.pi/extensions/feishu/index.ts +11 -0
- package/.pi/feishu/debug.pi.log +81 -0
- package/.pi/feishu/state.pi.json +12 -0
- package/README.md +210 -2
- package/package.json +57 -4
- package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
- package/src/adapters/pi/index.ts +1169 -0
- package/src/adapters/pi/setup.ts +108 -0
- package/src/feishu/app-register.ts +50 -0
- package/src/feishu/ask.ts +388 -0
- package/src/feishu/attachment-processor.ts +198 -0
- package/src/feishu/attachments.ts +192 -0
- package/src/feishu/bridge-runtime.ts +129 -0
- package/src/feishu/bridge-store.ts +92 -0
- package/src/feishu/card-action-webhook.ts +141 -0
- package/src/feishu/card-actions.ts +241 -0
- package/src/feishu/card-builder.ts +277 -0
- package/src/feishu/cardkit-stream.ts +483 -0
- package/src/feishu/cards.ts +413 -0
- package/src/feishu/config.ts +427 -0
- package/src/feishu/daemon-spec.ts +43 -0
- package/src/feishu/debug.ts +51 -0
- package/src/feishu/dedupe-store.ts +150 -0
- package/src/feishu/delivery.ts +185 -0
- package/src/feishu/gateway-lock.ts +256 -0
- package/src/feishu/group-trigger.ts +128 -0
- package/src/feishu/image-send.ts +256 -0
- package/src/feishu/instance.ts +170 -0
- package/src/feishu/instances.ts +148 -0
- package/src/feishu/interactive-card.ts +236 -0
- package/src/feishu/learn-approval.ts +321 -0
- package/src/feishu/live-cards.ts +128 -0
- package/src/feishu/message-handler.ts +512 -0
- package/src/feishu/messages.ts +356 -0
- package/src/feishu/oversize-progress-card.ts +101 -0
- package/src/feishu/progress-channel.ts +154 -0
- package/src/feishu/progress-note.ts +371 -0
- package/src/feishu/prompt-timeout.ts +81 -0
- package/src/feishu/reply-card-options.ts +73 -0
- package/src/feishu/reply-card.ts +498 -0
- package/src/feishu/restart.ts +286 -0
- package/src/feishu/retry.ts +102 -0
- package/src/feishu/rich-text.ts +387 -0
- package/src/feishu/runtime-config.ts +286 -0
- package/src/feishu/runtime.ts +110 -0
- package/src/feishu/slash-commands.ts +239 -0
- package/src/feishu/thinking.ts +24 -0
- package/src/feishu/transport.ts +792 -0
- package/src/feishu/types.ts +183 -0
- package/src/feishu/ui-notify.ts +44 -0
- package/src/feishu/user-name.ts +121 -0
- package/src/feishu/workspace.ts +42 -0
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 附件处理(图片 / 压缩包 / 文本文件),从 message-handler.ts 拆出来。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独一个文件:message-handler.ts 原本 586 行,已超单文件 500 行硬上限;
|
|
5
|
+
* 附件分流是其中最大的一块(111 行)且与消息路由无关,机械搬出来不承担额外风险。
|
|
6
|
+
*
|
|
7
|
+
* 分流原则:
|
|
8
|
+
* - 图片 → base64 直接给支持视觉的模型;
|
|
9
|
+
* - 压缩包 → 落盘到收件箱,agent 自己解压(日志包动辄几十 MB,塞进上下文只会被截断);
|
|
10
|
+
* - 其余按扩展名判断是否是可解码文本,能解码就贴进 prompt,否则报「类型不支持」。
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
buildArchiveSection,
|
|
14
|
+
buildDocumentSection,
|
|
15
|
+
decodeTextFile,
|
|
16
|
+
detectCodeLanguage,
|
|
17
|
+
detectImageMime,
|
|
18
|
+
isArchiveFile,
|
|
19
|
+
isDocumentFile,
|
|
20
|
+
isSupportedImageMime,
|
|
21
|
+
isSupportedTextFile,
|
|
22
|
+
saveArchiveToInbox,
|
|
23
|
+
type FeishuImageInput,
|
|
24
|
+
} from "./attachments.ts";
|
|
25
|
+
import { debugLog } from "./debug.ts";
|
|
26
|
+
import type { FeishuTransport } from "./transport.ts";
|
|
27
|
+
import type { FeishuMessage } from "./types.ts";
|
|
28
|
+
|
|
29
|
+
/** 从飞书消息里解析出的附件(图片用 image_key,文件用 file_key) */
|
|
30
|
+
export type AttachmentInput = { kind: "image" | "file"; fileKey: string; fileName?: string };
|
|
31
|
+
|
|
32
|
+
/** 附件处理结果:图片喂模型、文件段落贴进 prompt、失败原因回给用户 */
|
|
33
|
+
export type ProcessedAttachments = {
|
|
34
|
+
imageInputs: FeishuImageInput[];
|
|
35
|
+
fileSections: string[];
|
|
36
|
+
downloadErrors: string[];
|
|
37
|
+
skippedImageCount: number;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export async function processAttachments(
|
|
41
|
+
msg: FeishuMessage,
|
|
42
|
+
attachments: AttachmentInput[],
|
|
43
|
+
modelSupportsImage: boolean,
|
|
44
|
+
transport: FeishuTransport | undefined,
|
|
45
|
+
): Promise<ProcessedAttachments> {
|
|
46
|
+
const imageInputs: FeishuImageInput[] = [];
|
|
47
|
+
const fileSections: string[] = [];
|
|
48
|
+
const downloadErrors: string[] = [];
|
|
49
|
+
let skippedImageCount = 0;
|
|
50
|
+
|
|
51
|
+
for (const attachment of attachments) {
|
|
52
|
+
if (attachment.kind === "image") {
|
|
53
|
+
if (!modelSupportsImage) {
|
|
54
|
+
skippedImageCount += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (!transport) {
|
|
58
|
+
downloadErrors.push("飞书连接不可用,图片无法下载");
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const resource = await withTimeout(
|
|
63
|
+
transport.downloadImage(msg.messageId, attachment.fileKey),
|
|
64
|
+
15000,
|
|
65
|
+
"图片下载超时",
|
|
66
|
+
);
|
|
67
|
+
const mimeType = detectImageMime(resource.bytes, resource.mimeType);
|
|
68
|
+
if (!isSupportedImageMime(mimeType)) {
|
|
69
|
+
downloadErrors.push("图片格式暂不支持(仅支持 png/jpg/webp)");
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
imageInputs.push({
|
|
73
|
+
type: "image",
|
|
74
|
+
data: resource.bytes.toString("base64"),
|
|
75
|
+
mimeType,
|
|
76
|
+
});
|
|
77
|
+
} catch (error) {
|
|
78
|
+
debugLog("feishu.handler.image_error", {
|
|
79
|
+
messageId: msg.messageId,
|
|
80
|
+
fileKey: attachment.fileKey,
|
|
81
|
+
error: error instanceof Error ? error.message : String(error),
|
|
82
|
+
});
|
|
83
|
+
downloadErrors.push(error instanceof Error ? error.message : "图片下载失败");
|
|
84
|
+
}
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const fileName = attachment.fileName || "unnamed";
|
|
89
|
+
|
|
90
|
+
// 压缩包:落盘给 agent 自己解压,不塞进 prompt(日志包太大,塞进去只会被截断)
|
|
91
|
+
if (isArchiveFile(fileName)) {
|
|
92
|
+
if (!transport) {
|
|
93
|
+
downloadErrors.push(`飞书连接不可用,压缩包无法下载:${fileName}`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
// 压缩包可能很大,下载超时比普通文件放宽
|
|
98
|
+
const resource = await withTimeout(
|
|
99
|
+
transport.downloadMessageResource(msg.messageId, attachment.fileKey, "file"),
|
|
100
|
+
60000,
|
|
101
|
+
`压缩包下载超时:${fileName}`,
|
|
102
|
+
);
|
|
103
|
+
const savedPath = saveArchiveToInbox(msg.messageId, fileName, resource.bytes);
|
|
104
|
+
debugLog("feishu.handler.archive_saved", {
|
|
105
|
+
messageId: msg.messageId,
|
|
106
|
+
fileKey: attachment.fileKey,
|
|
107
|
+
path: savedPath,
|
|
108
|
+
bytes: resource.bytes.length,
|
|
109
|
+
});
|
|
110
|
+
fileSections.push(buildArchiveSection(fileName, savedPath, resource.bytes.length));
|
|
111
|
+
} catch (error) {
|
|
112
|
+
debugLog("feishu.handler.archive_error", {
|
|
113
|
+
messageId: msg.messageId,
|
|
114
|
+
fileKey: attachment.fileKey,
|
|
115
|
+
error: error instanceof Error ? error.message : String(error),
|
|
116
|
+
});
|
|
117
|
+
downloadErrors.push(error instanceof Error ? error.message : `压缩包下载失败:${fileName}`);
|
|
118
|
+
}
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// 文档类(pdf / Word / Excel / PPT / epub):二进制格式,Read 直接读会乱码,
|
|
123
|
+
// 与压缩包同一套打法 —— 落盘到收件箱,把路径和「按扩展名转换」的命令交给 agent。
|
|
124
|
+
if (isDocumentFile(fileName)) {
|
|
125
|
+
if (!transport) {
|
|
126
|
+
downloadErrors.push(`飞书连接不可用,文档无法下载:${fileName}`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
// 文档可能很大(扫描版 PDF、带图 Word),超时同压缩包放宽
|
|
131
|
+
const resource = await withTimeout(
|
|
132
|
+
transport.downloadMessageResource(msg.messageId, attachment.fileKey, "file"),
|
|
133
|
+
60000,
|
|
134
|
+
`文档下载超时:${fileName}`,
|
|
135
|
+
);
|
|
136
|
+
const savedPath = saveArchiveToInbox(msg.messageId, fileName, resource.bytes);
|
|
137
|
+
debugLog("feishu.handler.document_saved", {
|
|
138
|
+
messageId: msg.messageId,
|
|
139
|
+
fileKey: attachment.fileKey,
|
|
140
|
+
path: savedPath,
|
|
141
|
+
bytes: resource.bytes.length,
|
|
142
|
+
});
|
|
143
|
+
fileSections.push(buildDocumentSection(fileName, savedPath, resource.bytes.length));
|
|
144
|
+
} catch (error) {
|
|
145
|
+
debugLog("feishu.handler.document_error", {
|
|
146
|
+
messageId: msg.messageId,
|
|
147
|
+
fileKey: attachment.fileKey,
|
|
148
|
+
error: error instanceof Error ? error.message : String(error),
|
|
149
|
+
});
|
|
150
|
+
downloadErrors.push(error instanceof Error ? error.message : `文档下载失败:${fileName}`);
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (!isSupportedTextFile(fileName)) {
|
|
156
|
+
downloadErrors.push(`文件类型不支持:${fileName}`);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (!transport) {
|
|
160
|
+
downloadErrors.push(`飞书连接不可用,文件无法下载:${fileName}`);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const resource = await withTimeout(
|
|
165
|
+
transport.downloadMessageResource(msg.messageId, attachment.fileKey, "file"),
|
|
166
|
+
15000,
|
|
167
|
+
`文件下载超时:${fileName}`,
|
|
168
|
+
);
|
|
169
|
+
const decoded = decodeTextFile(fileName, resource.bytes);
|
|
170
|
+
if (!decoded.ok) {
|
|
171
|
+
downloadErrors.push(`文件无法按文本读取:${fileName}`);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const language = detectCodeLanguage(fileName);
|
|
175
|
+
const suffix = decoded.truncated ? "\n[内容过长,已截断]" : "";
|
|
176
|
+
fileSections.push(`[Feishu file: ${fileName}]\n\`\`\`${language}\n${decoded.text}${suffix}\n\`\`\``);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
downloadErrors.push(error instanceof Error ? error.message : `文件下载失败:${fileName}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return { imageInputs, fileSections, downloadErrors, skippedImageCount };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** 给单个下载加超时:飞书资源接口偶发挂住,不能让它拖死整轮回复 */
|
|
186
|
+
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, timeoutMessage: string): Promise<T> {
|
|
187
|
+
let timer: NodeJS.Timeout | undefined;
|
|
188
|
+
try {
|
|
189
|
+
return await Promise.race([
|
|
190
|
+
promise,
|
|
191
|
+
new Promise<T>((_, reject) => {
|
|
192
|
+
timer = setTimeout(() => reject(new Error(timeoutMessage)), timeoutMs);
|
|
193
|
+
}),
|
|
194
|
+
]);
|
|
195
|
+
} finally {
|
|
196
|
+
if (timer) clearTimeout(timer);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { ROOT_DIR } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
export type FeishuImageInput = { type: "image"; data: string; mimeType: string };
|
|
6
|
+
|
|
7
|
+
const SUPPORTED_IMAGE_MIME = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
8
|
+
const SUPPORTED_TEXT_EXT = new Set([
|
|
9
|
+
".txt", ".md", ".csv", ".json", ".log",
|
|
10
|
+
".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx",
|
|
11
|
+
".py", ".java", ".go", ".rs", ".rb", ".php", ".swift",
|
|
12
|
+
".kt", ".kts", ".scala", ".sh", ".bash", ".zsh",
|
|
13
|
+
".sql", ".yaml", ".yml", ".xml", ".html", ".css", ".scss",
|
|
14
|
+
".less", ".vue", ".svelte", ".toml", ".ini", ".conf", ".env",
|
|
15
|
+
".c", ".cc", ".cpp", ".h", ".hpp", ".cs",
|
|
16
|
+
]);
|
|
17
|
+
const SUPPORTED_TEXT_BASENAME = new Set(["dockerfile", "makefile", ".gitignore"]);
|
|
18
|
+
/**
|
|
19
|
+
* 压缩包:不当文本读,也不当「类型不支持」丢掉。
|
|
20
|
+
* 背景:客户端诊断会把 app_logs_*.zip 发进飞书,直接丢弃等于诊断断在半路。
|
|
21
|
+
*/
|
|
22
|
+
const SUPPORTED_ARCHIVE_EXT = new Set([".zip"]);
|
|
23
|
+
const MAX_TEXT_FILE_BYTES = 800_000;
|
|
24
|
+
const MAX_TEXT_FILE_CHARS = 16_000;
|
|
25
|
+
/** 压缩包落地目录(收件箱),agent 从这里自己解压读取 */
|
|
26
|
+
const INBOX_DIR = join(ROOT_DIR, "inbox");
|
|
27
|
+
|
|
28
|
+
export function isSupportedImageMime(mimeType: string | undefined): mimeType is string {
|
|
29
|
+
return Boolean(mimeType && SUPPORTED_IMAGE_MIME.has(mimeType));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function isSupportedTextFile(fileName: string) {
|
|
33
|
+
const lower = fileName.toLowerCase();
|
|
34
|
+
if (SUPPORTED_TEXT_BASENAME.has(lower)) return true;
|
|
35
|
+
const idx = lower.lastIndexOf(".");
|
|
36
|
+
if (idx < 0) return false;
|
|
37
|
+
return SUPPORTED_TEXT_EXT.has(lower.slice(idx));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 是否是压缩包附件(按扩展名判断) */
|
|
41
|
+
export function isArchiveFile(fileName: string) {
|
|
42
|
+
const lower = fileName.toLowerCase();
|
|
43
|
+
const idx = lower.lastIndexOf(".");
|
|
44
|
+
if (idx < 0) return false;
|
|
45
|
+
return SUPPORTED_ARCHIVE_EXT.has(lower.slice(idx));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 清洗附件名 / 消息 ID,只留安全文件名。
|
|
50
|
+
* 必须做:附件名来自用户,`../../x.zip` 这类会把落地路径带出目录。
|
|
51
|
+
*/
|
|
52
|
+
export function sanitizeAttachmentName(name: string) {
|
|
53
|
+
const base = name.split(/[\\/]/).pop() ?? "";
|
|
54
|
+
const cleaned = base
|
|
55
|
+
.replace(/[\u0000-\u001f<>:"|?*]/g, "")
|
|
56
|
+
.replace(/^\.+/, "")
|
|
57
|
+
.trim();
|
|
58
|
+
return cleaned || "attachment";
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 压缩包落盘到收件箱,返回绝对路径。
|
|
63
|
+
* 为什么落盘而不是解压进 prompt:日志包动辄几十 MB,塞进上下文只会被截断。
|
|
64
|
+
* 落盘后由 agent 自己 unzip/grep,诊断链路才是闭环的。
|
|
65
|
+
*
|
|
66
|
+
* 注:文档类附件(pdf/Office)也走这里 —— 都是「二进制、需要先落盘再由 agent 转换」。
|
|
67
|
+
*/
|
|
68
|
+
export function saveArchiveToInbox(messageId: string, fileName: string, bytes: Buffer, baseDir = INBOX_DIR) {
|
|
69
|
+
const dir = join(baseDir, sanitizeAttachmentName(messageId));
|
|
70
|
+
mkdirSync(dir, { recursive: true });
|
|
71
|
+
const path = join(dir, sanitizeAttachmentName(fileName));
|
|
72
|
+
writeFileSync(path, bytes);
|
|
73
|
+
return path;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function formatBytes(size: number) {
|
|
77
|
+
if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`;
|
|
78
|
+
if (size >= 1024) return `${(size / 1024).toFixed(1)} KB`;
|
|
79
|
+
return `${size} B`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 生成压缩包在 prompt 里的说明段(含本地路径与解压提示) */
|
|
83
|
+
export function buildArchiveSection(fileName: string, path: string, bytes: number) {
|
|
84
|
+
return [
|
|
85
|
+
`[Feishu archive: ${fileName}]`,
|
|
86
|
+
`已保存到本地:${path}(${formatBytes(bytes)})`,
|
|
87
|
+
`这是压缩包,未解压。先用 \`unzip -l "${path}"\`(或 \`python3 -m zipfile -l "${path}"\`)看条目,再解压需要的文件读取内容。`,
|
|
88
|
+
].join("\n");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 文档类附件:pdf / Office / 电子书。
|
|
93
|
+
* 单独一类的原因:既不是可解码文本(二进制),也不是压缩包,
|
|
94
|
+
* 但业务上必须能读 —— 合同、报表、需求文档都以这些格式发进飞书。
|
|
95
|
+
* 打法和压缩包一致:落盘到收件箱,把路径 + 转换命令交给 agent,由 agent 自己转成文本。
|
|
96
|
+
*/
|
|
97
|
+
const SUPPORTED_DOCUMENT_EXT = new Set([
|
|
98
|
+
".pdf", ".doc", ".docx", ".rtf", ".odt",
|
|
99
|
+
".xls", ".xlsx", ".ppt", ".pptx", ".epub",
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
/** 是否是文档类附件(按扩展名判断,与压缩包/文本文件互斥) */
|
|
103
|
+
export function isDocumentFile(fileName: string) {
|
|
104
|
+
const lower = fileName.toLowerCase();
|
|
105
|
+
const idx = lower.lastIndexOf(".");
|
|
106
|
+
if (idx < 0) return false;
|
|
107
|
+
return SUPPORTED_DOCUMENT_EXT.has(lower.slice(idx));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 生成文档类附件在 prompt 里的说明段:本地路径 + 按扩展名给的可直接复制命令。
|
|
112
|
+
* 统一用 `sys.argv[1]` 传路径,避免文件名里的引号/空格把命令打断。
|
|
113
|
+
*/
|
|
114
|
+
export function buildDocumentSection(fileName: string, path: string, bytes: number) {
|
|
115
|
+
const lower = fileName.toLowerCase();
|
|
116
|
+
const lines = [
|
|
117
|
+
`[Feishu document: ${fileName}]`,
|
|
118
|
+
`已保存到本地:${path}(${formatBytes(bytes)})`,
|
|
119
|
+
"这是二进制文档,直接读会乱码。先转成文本再读,按扩展名选一条:",
|
|
120
|
+
];
|
|
121
|
+
if (/\.(docx?|rtf|odt)$/.test(lower)) {
|
|
122
|
+
lines.push(`- Word/RTF:\`textutil -convert txt -stdout "${path}"\`(macOS 自带;其他平台用 \`pandoc "${path}" -t plain\`)`);
|
|
123
|
+
} else if (lower.endsWith(".pdf")) {
|
|
124
|
+
lines.push(
|
|
125
|
+
`- PDF:\`python3 -c "import sys;from pypdf import PdfReader;[print(p.extract_text() or '') for p in PdfReader(sys.argv[1]).pages]" "${path}"\``,
|
|
126
|
+
);
|
|
127
|
+
lines.push("- 没装 pypdf 就先 `python3 -m pip install --user pypdf`;装了 poppler 的话 `pdftotext 文件 -` 更省事");
|
|
128
|
+
} else if (/\.(xlsx?)$/.test(lower)) {
|
|
129
|
+
lines.push(
|
|
130
|
+
`- Excel:\`python3 -c "import sys,openpyxl;wb=openpyxl.load_workbook(sys.argv[1],data_only=True);[print(ws.title,ws.max_row,ws.max_column) for ws in wb]" "${path}"\`(先看有几个工作表,再逐表取值)`,
|
|
131
|
+
);
|
|
132
|
+
} else if (/\.(pptx?)$/.test(lower)) {
|
|
133
|
+
lines.push("- PPT:先另存为 PDF 再按 PDF 提取;或 `python3 -m pip install --user python-pptx` 后读每个 shape 的 text");
|
|
134
|
+
} else {
|
|
135
|
+
lines.push(`- 先用 \`file "${path}"\` 确认真实格式,再选对应工具`);
|
|
136
|
+
}
|
|
137
|
+
return lines.join("\n");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function decodeTextFile(fileName: string, bytes: Buffer): { ok: true; text: string; truncated: boolean } | { ok: false } {
|
|
141
|
+
const slice = bytes.length > MAX_TEXT_FILE_BYTES ? bytes.subarray(0, MAX_TEXT_FILE_BYTES) : bytes;
|
|
142
|
+
if (looksBinary(slice)) return { ok: false };
|
|
143
|
+
const text = slice.toString("utf8");
|
|
144
|
+
const truncated = text.length > MAX_TEXT_FILE_CHARS || bytes.length > MAX_TEXT_FILE_BYTES;
|
|
145
|
+
return { ok: true, text: text.slice(0, MAX_TEXT_FILE_CHARS), truncated };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function detectImageMime(bytes: Buffer, headerMime?: string) {
|
|
149
|
+
if (headerMime && SUPPORTED_IMAGE_MIME.has(headerMime)) return headerMime;
|
|
150
|
+
if (bytes.length >= 12) {
|
|
151
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png";
|
|
152
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg";
|
|
153
|
+
if (
|
|
154
|
+
bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
|
|
155
|
+
bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50
|
|
156
|
+
) return "image/webp";
|
|
157
|
+
}
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function detectCodeLanguage(fileName: string) {
|
|
162
|
+
const lower = fileName.toLowerCase();
|
|
163
|
+
const ext = lower.includes(".") ? lower.slice(lower.lastIndexOf(".")) : "";
|
|
164
|
+
const mapping: Record<string, string> = {
|
|
165
|
+
".js": "javascript", ".mjs": "javascript", ".cjs": "javascript",
|
|
166
|
+
".ts": "typescript", ".tsx": "tsx", ".jsx": "jsx",
|
|
167
|
+
".py": "python", ".java": "java", ".go": "go", ".rs": "rust", ".rb": "ruby",
|
|
168
|
+
".php": "php", ".swift": "swift", ".kt": "kotlin", ".kts": "kotlin",
|
|
169
|
+
".scala": "scala", ".sh": "bash", ".bash": "bash", ".zsh": "bash",
|
|
170
|
+
".sql": "sql", ".yaml": "yaml", ".yml": "yaml", ".xml": "xml",
|
|
171
|
+
".html": "html", ".css": "css", ".scss": "scss", ".less": "less",
|
|
172
|
+
".vue": "vue", ".svelte": "svelte", ".toml": "toml", ".ini": "ini",
|
|
173
|
+
".conf": "conf", ".env": "bash", ".c": "c", ".cc": "cpp", ".cpp": "cpp",
|
|
174
|
+
".h": "c", ".hpp": "cpp", ".cs": "csharp", ".md": "markdown",
|
|
175
|
+
".json": "json", ".csv": "csv", ".txt": "text", ".log": "text",
|
|
176
|
+
};
|
|
177
|
+
if (lower === "dockerfile") return "dockerfile";
|
|
178
|
+
if (lower === "makefile") return "makefile";
|
|
179
|
+
return mapping[ext] || "text";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function looksBinary(bytes: Buffer) {
|
|
183
|
+
if (!bytes.length) return false;
|
|
184
|
+
let controlCount = 0;
|
|
185
|
+
const sampleLen = Math.min(bytes.length, 4096);
|
|
186
|
+
for (let i = 0; i < sampleLen; i += 1) {
|
|
187
|
+
const ch = bytes[i]!;
|
|
188
|
+
if (ch === 0) return true;
|
|
189
|
+
if (ch < 8 || (ch > 13 && ch < 32)) controlCount += 1;
|
|
190
|
+
}
|
|
191
|
+
return controlCount / sampleLen > 0.08;
|
|
192
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { FeishuBridgeStore } from "./bridge-store.ts";
|
|
2
|
+
import { FeishuDelivery } from "./delivery.ts";
|
|
3
|
+
import { debugLog } from "./debug.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 桥接输入事件(平台无关):
|
|
7
|
+
* 由各 Runtime 适配器把自身会话事件解析成这些标准化事件后调用 handleJobEvent。
|
|
8
|
+
* "job" 指飞书侧记录的一个可回传结果(例如 Pi 内部定时任务),
|
|
9
|
+
* 对应关系由 FeishuBridgeStore 持久化。
|
|
10
|
+
*/
|
|
11
|
+
export type BridgeJobEvent =
|
|
12
|
+
/** Runtime 会话里创建了一批可回传任务(仅飞书发起的输入会绑定)。 */
|
|
13
|
+
| { kind: "created"; sessionId: string; sessionKey: string | undefined; jobs: Array<{ id: string; name?: string }> }
|
|
14
|
+
/** 一个任务开始执行,等待该会话下一条 assistant 输出作为结果。 */
|
|
15
|
+
| { kind: "marker"; sessionId: string; jobId: string }
|
|
16
|
+
/** 任务直接产出最终结果(如子代理完成)。 */
|
|
17
|
+
| { kind: "done"; sessionId: string; jobId: string; text: string; dedupeKey: string }
|
|
18
|
+
/** 任务执行失败。 */
|
|
19
|
+
| { kind: "error"; sessionId: string; jobId: string; error: string; dedupeKey: string }
|
|
20
|
+
/** 一条 assistant 文本;若该会话有等待中的任务,按顺序匹配队首。 */
|
|
21
|
+
| { kind: "output"; sessionId: string; text: string; messageId?: string; timestamp?: string };
|
|
22
|
+
|
|
23
|
+
export class FeishuBridgeRuntime {
|
|
24
|
+
private readonly pendingBySession = new Map<string, string[]>();
|
|
25
|
+
private readonly activeFeishuInputs = new Set<string>();
|
|
26
|
+
private readonly store: FeishuBridgeStore;
|
|
27
|
+
private readonly delivery: FeishuDelivery;
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
store: FeishuBridgeStore,
|
|
31
|
+
delivery: FeishuDelivery,
|
|
32
|
+
) {
|
|
33
|
+
this.store = store;
|
|
34
|
+
this.delivery = delivery;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
attachSession(sessionKey: string, sessionId: string) {
|
|
38
|
+
this.store.attachSession(sessionKey, sessionId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
beginFeishuInput(sessionId: string) {
|
|
42
|
+
this.activeFeishuInputs.add(sessionId);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
endFeishuInput(sessionId: string) {
|
|
46
|
+
this.activeFeishuInputs.delete(sessionId);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Runtime 适配器把自身事件标准化后调用。 */
|
|
50
|
+
handleJobEvent(event: BridgeJobEvent) {
|
|
51
|
+
switch (event.kind) {
|
|
52
|
+
case "created":
|
|
53
|
+
this.captureCreatedJobs(event);
|
|
54
|
+
return;
|
|
55
|
+
case "marker":
|
|
56
|
+
void this.handleScheduledMarker(event);
|
|
57
|
+
return;
|
|
58
|
+
case "done":
|
|
59
|
+
void this.deliverJobResult(event.jobId, event.text, event.dedupeKey);
|
|
60
|
+
return;
|
|
61
|
+
case "error":
|
|
62
|
+
void this.deliverJobResult(event.jobId, `定时任务执行失败:${event.error}`, event.dedupeKey);
|
|
63
|
+
return;
|
|
64
|
+
case "output":
|
|
65
|
+
void this.handleAssistantOutput(event);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private captureCreatedJobs(event: Extract<BridgeJobEvent, { kind: "created" }>) {
|
|
71
|
+
const { sessionId, sessionKey, jobs } = event;
|
|
72
|
+
if (!sessionKey || !this.activeFeishuInputs.has(sessionId)) return;
|
|
73
|
+
for (const job of jobs) {
|
|
74
|
+
this.store.bindJob(sessionKey, job.id, job.name, sessionId);
|
|
75
|
+
debugLog("feishu.bridge.job_bound", { sessionKey, sessionId, jobId: job.id, jobName: job.name });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private async handleScheduledMarker(event: Extract<BridgeJobEvent, { kind: "marker" }>) {
|
|
80
|
+
const { sessionId, jobId } = event;
|
|
81
|
+
const route = this.store.getJob(jobId);
|
|
82
|
+
if (!route) return;
|
|
83
|
+
const pending = this.pendingBySession.get(sessionId) || [];
|
|
84
|
+
pending.push(jobId);
|
|
85
|
+
this.pendingBySession.set(sessionId, pending);
|
|
86
|
+
debugLog("feishu.bridge.scheduled_started", { sessionId, jobId });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
private async handleAssistantOutput(event: Extract<BridgeJobEvent, { kind: "output" }>) {
|
|
90
|
+
const pending = this.pendingBySession.get(event.sessionId);
|
|
91
|
+
const nextJobId = pending?.[0];
|
|
92
|
+
if (!nextJobId) return;
|
|
93
|
+
|
|
94
|
+
const route = this.store.getJob(nextJobId);
|
|
95
|
+
if (!route) {
|
|
96
|
+
pending?.shift();
|
|
97
|
+
if (!pending?.length) this.pendingBySession.delete(event.sessionId);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const text = event.text;
|
|
102
|
+
if (!text) return;
|
|
103
|
+
const deliveryKey = `assistant:${nextJobId}:${event.messageId || event.timestamp || text}`;
|
|
104
|
+
await this.deliverOnce(deliveryKey, route, text);
|
|
105
|
+
pending?.shift();
|
|
106
|
+
if (!pending?.length) this.pendingBySession.delete(event.sessionId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
private async deliverJobResult(jobId: string, text: string, dedupeKey: string) {
|
|
110
|
+
const route = this.store.getJob(jobId);
|
|
111
|
+
if (!route) return;
|
|
112
|
+
await this.deliverOnce(dedupeKey, route, text);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
private async deliverOnce(deliveryKey: string, route: any, text: string) {
|
|
116
|
+
if (this.store.hasSent(deliveryKey)) return;
|
|
117
|
+
try {
|
|
118
|
+
await this.delivery.send(route, text);
|
|
119
|
+
this.store.markSent(deliveryKey);
|
|
120
|
+
debugLog("feishu.bridge.delivered", { deliveryKey, jobId: route.jobId, sessionKey: route.sessionKey });
|
|
121
|
+
} catch (error) {
|
|
122
|
+
debugLog("feishu.bridge.deliver_failed", {
|
|
123
|
+
deliveryKey,
|
|
124
|
+
jobId: route.jobId,
|
|
125
|
+
error: error instanceof Error ? error.message : String(error),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { getRuntimeSource, readJson, writeJson } from "./config.ts";
|
|
2
|
+
import type { FeishuBridgeState, FeishuJobRoute, FeishuMessage, FeishuRoute } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
const DEFAULT_STATE: FeishuBridgeState = { version: 1, routes: {}, jobs: {}, sent: {} };
|
|
5
|
+
|
|
6
|
+
function bridgePath() {
|
|
7
|
+
return getRuntimeSource().bridgePath;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export class FeishuBridgeStore {
|
|
11
|
+
bindConversation(sessionKey: string, msg: FeishuMessage, sessionId?: string) {
|
|
12
|
+
const state = this.read();
|
|
13
|
+
const previous = state.routes[sessionKey];
|
|
14
|
+
const route: FeishuRoute = {
|
|
15
|
+
sessionKey,
|
|
16
|
+
sessionId: sessionId || previous?.sessionId,
|
|
17
|
+
chatId: msg.chatId,
|
|
18
|
+
chatType: msg.chatType,
|
|
19
|
+
threadMessageId: routeThreadMessageId(msg, previous),
|
|
20
|
+
lastMessageId: msg.messageId,
|
|
21
|
+
senderOpenId: msg.senderOpenId || previous?.senderOpenId,
|
|
22
|
+
updatedAt: Date.now(),
|
|
23
|
+
};
|
|
24
|
+
state.routes[sessionKey] = route;
|
|
25
|
+
this.write(state);
|
|
26
|
+
return route;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
attachSession(sessionKey: string, sessionId: string) {
|
|
30
|
+
const state = this.read();
|
|
31
|
+
const route = state.routes[sessionKey];
|
|
32
|
+
if (!route || route.sessionId === sessionId) return;
|
|
33
|
+
state.routes[sessionKey] = { ...route, sessionId, updatedAt: Date.now() };
|
|
34
|
+
this.write(state);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
getRoute(sessionKey: string): FeishuRoute | undefined {
|
|
38
|
+
return this.read().routes[sessionKey];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
bindJob(sessionKey: string, jobId: string, jobName?: string, sessionId?: string): FeishuJobRoute | undefined {
|
|
42
|
+
const state = this.read();
|
|
43
|
+
const route = state.routes[sessionKey];
|
|
44
|
+
if (!route) return undefined;
|
|
45
|
+
const jobRoute: FeishuJobRoute = {
|
|
46
|
+
...route,
|
|
47
|
+
sessionId: sessionId || route.sessionId,
|
|
48
|
+
jobId,
|
|
49
|
+
jobName,
|
|
50
|
+
createdAt: Date.now(),
|
|
51
|
+
updatedAt: Date.now(),
|
|
52
|
+
};
|
|
53
|
+
state.jobs[jobId] = jobRoute;
|
|
54
|
+
this.write(state);
|
|
55
|
+
return jobRoute;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
getJob(jobId: string): FeishuJobRoute | undefined {
|
|
59
|
+
return this.read().jobs[jobId];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
markSent(deliveryKey: string) {
|
|
63
|
+
const state = this.read();
|
|
64
|
+
state.sent[deliveryKey] = Date.now();
|
|
65
|
+
this.write(state);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
hasSent(deliveryKey: string) {
|
|
69
|
+
return Boolean(this.read().sent[deliveryKey]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private read(): FeishuBridgeState {
|
|
73
|
+
const raw = readJson<FeishuBridgeState>(bridgePath(), DEFAULT_STATE);
|
|
74
|
+
return {
|
|
75
|
+
version: 1,
|
|
76
|
+
routes: { ...(raw.routes || {}) },
|
|
77
|
+
jobs: { ...(raw.jobs || {}) },
|
|
78
|
+
sent: { ...(raw.sent || {}) },
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private write(state: FeishuBridgeState) {
|
|
83
|
+
writeJson(bridgePath(), state);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function routeThreadMessageId(msg: FeishuMessage, previous?: FeishuRoute) {
|
|
88
|
+
if (msg.rootId || msg.parentId) return msg.rootId || msg.parentId;
|
|
89
|
+
if (previous?.threadMessageId) return previous.threadMessageId;
|
|
90
|
+
if (msg.threadId || msg.chatMode === "topic") return msg.messageId;
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|