@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.
Files changed (52) hide show
  1. package/.pi/extensions/feishu/index.ts +11 -0
  2. package/.pi/feishu/debug.pi.log +81 -0
  3. package/.pi/feishu/state.pi.json +12 -0
  4. package/README.md +210 -2
  5. package/package.json +57 -4
  6. package/src/adapters/pi/PiConversationRuntime.ts +1559 -0
  7. package/src/adapters/pi/index.ts +1169 -0
  8. package/src/adapters/pi/setup.ts +108 -0
  9. package/src/feishu/app-register.ts +50 -0
  10. package/src/feishu/ask.ts +388 -0
  11. package/src/feishu/attachment-processor.ts +198 -0
  12. package/src/feishu/attachments.ts +192 -0
  13. package/src/feishu/bridge-runtime.ts +129 -0
  14. package/src/feishu/bridge-store.ts +92 -0
  15. package/src/feishu/card-action-webhook.ts +141 -0
  16. package/src/feishu/card-actions.ts +241 -0
  17. package/src/feishu/card-builder.ts +277 -0
  18. package/src/feishu/cardkit-stream.ts +483 -0
  19. package/src/feishu/cards.ts +413 -0
  20. package/src/feishu/config.ts +427 -0
  21. package/src/feishu/daemon-spec.ts +43 -0
  22. package/src/feishu/debug.ts +51 -0
  23. package/src/feishu/dedupe-store.ts +150 -0
  24. package/src/feishu/delivery.ts +185 -0
  25. package/src/feishu/gateway-lock.ts +256 -0
  26. package/src/feishu/group-trigger.ts +128 -0
  27. package/src/feishu/image-send.ts +256 -0
  28. package/src/feishu/instance.ts +170 -0
  29. package/src/feishu/instances.ts +148 -0
  30. package/src/feishu/interactive-card.ts +236 -0
  31. package/src/feishu/learn-approval.ts +321 -0
  32. package/src/feishu/live-cards.ts +128 -0
  33. package/src/feishu/message-handler.ts +512 -0
  34. package/src/feishu/messages.ts +356 -0
  35. package/src/feishu/oversize-progress-card.ts +101 -0
  36. package/src/feishu/progress-channel.ts +154 -0
  37. package/src/feishu/progress-note.ts +371 -0
  38. package/src/feishu/prompt-timeout.ts +81 -0
  39. package/src/feishu/reply-card-options.ts +73 -0
  40. package/src/feishu/reply-card.ts +498 -0
  41. package/src/feishu/restart.ts +286 -0
  42. package/src/feishu/retry.ts +102 -0
  43. package/src/feishu/rich-text.ts +387 -0
  44. package/src/feishu/runtime-config.ts +286 -0
  45. package/src/feishu/runtime.ts +110 -0
  46. package/src/feishu/slash-commands.ts +239 -0
  47. package/src/feishu/thinking.ts +24 -0
  48. package/src/feishu/transport.ts +792 -0
  49. package/src/feishu/types.ts +183 -0
  50. package/src/feishu/ui-notify.ts +44 -0
  51. package/src/feishu/user-name.ts +121 -0
  52. package/src/feishu/workspace.ts +42 -0
@@ -0,0 +1,512 @@
1
+ import { processAttachments } from "./attachment-processor.ts";
2
+ import type { FeishuImageInput } from "./attachments.ts";
3
+ import { buildDeliveryCard, buildModelCard, buildResumeCard, buildThinkingCard } from "./cards.ts";
4
+ import type { ConversationRuntime } from "./runtime.ts";
5
+ import { claimFeishuMessage, markFeishuMessage } from "./dedupe-store.ts";
6
+ import { debugLog } from "./debug.ts";
7
+ import { loadConfig } from "./config.ts";
8
+ import {
9
+ clearRuntimeOverrides,
10
+ formatRuntimeConfig,
11
+ getRuntimeOverrides,
12
+ setRuntimeConfig,
13
+ } from "./runtime-config.ts";
14
+ import { conversationKey, conversationLabel, buildPromptWithQuote, buildRequesterMarker, getCommandList, normalizeForDedupe, parseBotCommand, parseMessageInput, pruneRecentMap, stripRerunMarker, textSimilarity, NEAR_DUPLICATE_THRESHOLD } from "./messages.ts";
15
+ import { resolveUserName } from "./user-name.ts";
16
+ import { ReplyCard, resolveCardTarget } from "./reply-card.ts";
17
+ import type { FeishuBridgeStore } from "./bridge-store.ts";
18
+ import type { FeishuTransport } from "./transport.ts";
19
+ import type { FeishuMessage } from "./types.ts";
20
+
21
+ const CONTENT_DEDUPE_TTL_MS = 5_000;
22
+ /**
23
+ * 「同一句话重发」的拦截窗口。
24
+ * 回归背景:用户把同一句话改一个错别字重发,桥接会再跑一轮,模型于是把同一个
25
+ * 选择题又问一遍(看起来像重复回复)。这里拦下来,并告诉他怎么强制重跑。
26
+ */
27
+ const NEAR_DUPLICATE_TTL_MS = 10 * 60 * 1000;
28
+ /** 短消息(「好」「继续」)不参与近重复判断:误拦概率远大于收益 */
29
+ const NEAR_DUPLICATE_MIN_CHARS = 8;
30
+
31
+ /** `/restart` 的宿主实现由 Pi 适配器注入(只有它知道 daemon 启动形状与扩展入口) */
32
+ export type RestartRequest = {
33
+ trigger: { messageId: string; chatId: string };
34
+ force?: boolean;
35
+ hasActiveRun: boolean;
36
+ };
37
+
38
+ export type FeishuMessageHandlerHooks = {
39
+ restart?: (request: RestartRequest) => Promise<{ ok: boolean; error?: string }>;
40
+ };
41
+
42
+ export class FeishuMessageHandler {
43
+ private readonly seen = new Set<string>();
44
+ private readonly recentContent = new Map<string, number>();
45
+ /** 每个会话最近一次送进模型的正文,用于「同一句话重发」拦截 */
46
+ private readonly recentPrompts = new Map<string, { text: string; at: number }>();
47
+ private readonly conversations: ConversationRuntime;
48
+ private readonly getTransport: () => FeishuTransport | undefined;
49
+ private readonly bridgeStore?: FeishuBridgeStore;
50
+ private readonly hooks: FeishuMessageHandlerHooks;
51
+
52
+ constructor(
53
+ conversations: ConversationRuntime,
54
+ getTransport: () => FeishuTransport | undefined,
55
+ bridgeStore?: FeishuBridgeStore,
56
+ hooks?: FeishuMessageHandlerHooks,
57
+ ) {
58
+ this.conversations = conversations;
59
+ this.getTransport = getTransport;
60
+ this.bridgeStore = bridgeStore;
61
+ this.hooks = hooks ?? {};
62
+ }
63
+
64
+ reset() {
65
+ this.seen.clear();
66
+ this.recentContent.clear();
67
+ this.recentPrompts.clear();
68
+ }
69
+
70
+ async handle(msg: FeishuMessage) {
71
+ const transport = this.getTransport();
72
+ if (!transport) return;
73
+
74
+ /**
75
+ * 本轮结局,finally 里据此把「收到消息」时贴的表情收尾:
76
+ * done → DONE,failed → CRY,ignored(去重命中 / 空消息)→ 直接摘掉。
77
+ */
78
+ let outcome: "done" | "failed" | "ignored" = "ignored";
79
+ /** 本地包装 markFeishuMessage:顺手记下结局,避免每个出口各写一遍 */
80
+ const mark = async (status: "replied" | "ignored" | "failed", error?: string) => {
81
+ if (status === "replied") outcome = "done";
82
+ else if (status === "failed") outcome = "failed";
83
+ await markFeishuMessage(msg.messageId, status, error);
84
+ };
85
+
86
+ try {
87
+ if (this.seen.has(msg.messageId)) return;
88
+ if (!(await claimFeishuMessage(msg.messageId))) return;
89
+ this.seen.add(msg.messageId);
90
+ if (this.seen.size > 2000) this.seen.clear();
91
+
92
+ const cfg = loadConfig();
93
+ const parsed = parseMessageInput(msg, transport.getBotOpenId(), {
94
+ parseInteractiveCards: cfg?.parseInteractiveCards !== false,
95
+ });
96
+ let text = parsed.text || "";
97
+ const key = conversationKey(msg);
98
+ this.bridgeStore?.bindConversation(key, msg);
99
+
100
+ // 展开引用/回复的父消息(告警卡片场景)
101
+ let quoted: { msgType: string; text: string } | null = null;
102
+ if (cfg?.includeQuotedMessage !== false && (msg.parentId || msg.rootId)) {
103
+ const q = await transport.getQuotedContext(
104
+ msg,
105
+ transport.getBotOpenId(),
106
+ cfg?.quotedMessageMaxChars ?? 8000,
107
+ );
108
+ if (q?.text) {
109
+ quoted = { msgType: q.msgType, text: q.text };
110
+ for (const a of q.attachments || []) parsed.attachments.push(a);
111
+ }
112
+ }
113
+
114
+ debugLog("feishu.handler.parsed", {
115
+ messageId: msg.messageId,
116
+ key,
117
+ chatMode: msg.chatMode,
118
+ threadId: msg.threadId || msg.rootId || msg.parentId,
119
+ textLength: text.length,
120
+ source: parsed.source,
121
+ quoted: Boolean(quoted),
122
+ attachments: parsed.attachments.map((item) => ({
123
+ kind: item.kind,
124
+ fileKey: item.fileKey,
125
+ fileName: item.fileName,
126
+ })),
127
+ });
128
+
129
+ if (!parsed.attachments.length) {
130
+ if (!text && !quoted) {
131
+ await mark("ignored");
132
+ return;
133
+ }
134
+ if (text) {
135
+ const handled = await this.handleCommand(msg, key, text);
136
+ if (handled) {
137
+ await mark("replied");
138
+ return;
139
+ }
140
+ }
141
+ }
142
+
143
+ // 「重发 / /again」是显式要求重跑:剥掉前缀后照常开新一轮
144
+ const withoutMarker = stripRerunMarker(text);
145
+ const forceRerun = withoutMarker !== text;
146
+ if (forceRerun) text = withoutMarker;
147
+
148
+ if (!forceRerun && this.isDuplicateContent(msg, key, text, parsed.attachments)) {
149
+ await mark("ignored");
150
+ return;
151
+ }
152
+
153
+ if (!forceRerun && (await this.guardNearDuplicate(msg, key, text))) {
154
+ await mark("replied");
155
+ return;
156
+ }
157
+
158
+ const model = await this.conversations.getSelectedModel(key);
159
+ const modelSupportsImage = Boolean(model?.supportsImage);
160
+ debugLog("feishu.handler.model", {
161
+ messageId: msg.messageId,
162
+ key,
163
+ model: model ? `${model.provider}/${model.id}` : undefined,
164
+ modelSupportsImage,
165
+ });
166
+
167
+ const processed = await processAttachments(msg, parsed.attachments, modelSupportsImage, transport);
168
+ const { imageInputs, fileSections, downloadErrors, skippedImageCount } = processed;
169
+
170
+ if (skippedImageCount > 0 && imageInputs.length === 0 && !fileSections.length && !text.trim()) {
171
+ await transport.replyText(
172
+ msg.messageId,
173
+ "当前模型不支持图片解析。请先发送 /model 并切换到支持图片的模型后,再重发图片。",
174
+ );
175
+ await mark("replied");
176
+ return;
177
+ }
178
+
179
+ if (downloadErrors.length && !imageInputs.length && !fileSections.length && !text.trim()) {
180
+ await transport.replyText(msg.messageId, `没有可处理的内容:${downloadErrors.join(";")}`);
181
+ await mark("replied");
182
+ return;
183
+ }
184
+
185
+ // 提出人姓名(可选增强):查不到(缺 contact 字段权限 / 超时 / 网络)就降级回 open_id,
186
+ // 绝不阻塞消息处理,也不抛错(见 user-name.ts 的口径)。
187
+ const senderName = await resolveUserName(msg.senderOpenId, cfg);
188
+ const basePrompt = buildPrompt(msg, text, fileSections, imageInputs, skippedImageCount, modelSupportsImage, downloadErrors, senderName);
189
+ const prompt = buildPromptWithQuote(basePrompt, quoted);
190
+ // 单卡:全程 header;流式参数来自 config/env
191
+ const useStreaming = cfg?.streamingReply !== false;
192
+ // 发到哪里由 resolveCardTarget 统一决定:普通会话平铺,话题群才 reply
193
+ const route = this.bridgeStore?.getRoute(key) ?? {
194
+ chatId: msg.chatId,
195
+ chatType: msg.chatType,
196
+ lastMessageId: msg.messageId,
197
+ threadMessageId: msg.threadId || msg.rootId || msg.parentId,
198
+ };
199
+ const card = new ReplyCard(key, resolveCardTarget(route), transport, {
200
+ enabled: useStreaming,
201
+ printFrequencyMs: cfg?.streamPrintFrequencyMs,
202
+ printStep: cfg?.streamPrintStep,
203
+ pushIntervalMs: cfg?.streamPushIntervalMs,
204
+ });
205
+ await card.start();
206
+
207
+ await this.conversations.promptWithImages(
208
+ key,
209
+ prompt,
210
+ imageInputs,
211
+ async (reply) => {
212
+ await card.completeWithAnswer(reply || "(无内容)");
213
+ },
214
+ card,
215
+ useStreaming ? (delta) => card.append(delta) : undefined,
216
+ );
217
+ await mark("replied");
218
+ } catch (error) {
219
+ const message = error instanceof Error ? error.message : String(error);
220
+ debugLog("feishu.handler.error", { messageId: msg.messageId, error: message });
221
+ await mark("failed", message);
222
+ await this.getTransport()?.replyText(msg.messageId, `Pi error: ${message}`);
223
+ } finally {
224
+ // 任何出口都要收尾,否则「收到」表情会一直贴在消息上
225
+ await transport.settleReaction(msg.messageId, outcome);
226
+ }
227
+ }
228
+
229
+ private async handleCommand(msg: FeishuMessage, key: string, text: string) {
230
+ const command = parseBotCommand(text);
231
+ if (!command) return false;
232
+
233
+ const transport = this.getTransport();
234
+ if (!transport) return true;
235
+
236
+ if (command.name === "new") {
237
+ await this.conversations.newConversation(key, async (reply) => {
238
+ await transport.replyText(msg.messageId, reply);
239
+ });
240
+ return true;
241
+ }
242
+
243
+ if (command.name === "model") {
244
+ const models = await this.conversations.getAvailableModels();
245
+ if (!models.length) {
246
+ await transport.replyText(msg.messageId, "当前没有可用模型。请先在 Pi 里完成模型登录或 API Key 配置。");
247
+ return true;
248
+ }
249
+ const currentModel = await this.conversations.getSelectedModel(key);
250
+ await transport.replyCard(msg.messageId, buildModelCard(key, models, currentModel));
251
+ return true;
252
+ }
253
+
254
+ if (command.name === "thinking") {
255
+ const [currentModel, thinking] = await Promise.all([
256
+ this.conversations.getSelectedModel(key),
257
+ this.conversations.getThinkingStatus(key),
258
+ ]);
259
+ await transport.replyCard(msg.messageId, buildThinkingCard(key, currentModel, thinking));
260
+ return true;
261
+ }
262
+
263
+ if (command.name === "resume") {
264
+ const page = await this.conversations.listResumeSessions(key, "current", 0);
265
+ await transport.replyCard(msg.messageId, buildResumeCard(page));
266
+ return true;
267
+ }
268
+
269
+ if (command.name === "stop") {
270
+ await this.conversations.stopConversation(key, async (reply) => {
271
+ await transport.replyText(msg.messageId, reply);
272
+ });
273
+ return true;
274
+ }
275
+
276
+ if (command.name === "workspace") {
277
+ await this.conversations.switchWorkspace(key, command.path, async (reply) => {
278
+ await transport.replyText(msg.messageId, reply);
279
+ });
280
+ return true;
281
+ }
282
+
283
+ if (command.name === "status") {
284
+ const st = this.conversations.getStatus(key);
285
+ const ctx = await this.conversations.getContextStatus(key);
286
+ const model = await this.conversations.getActualModel(key);
287
+ const thinking = await this.conversations.getThinkingStatus(key);
288
+ const formatTokens = (n: number) => {
289
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
290
+ if (n >= 1_000) return `${(n / 1_000).toFixed(0)}k`;
291
+ return `${n}`;
292
+ };
293
+ const ctxLine = ctx && ctx.tokens !== null && ctx.contextWindow
294
+ ? `${(ctx.percent ?? 0).toFixed(1)}% / ${formatTokens(ctx.contextWindow)} (↑${formatTokens(ctx.tokens ?? 0)} tokens)`
295
+ : "暂无数据(发送一条消息后才会显示)";
296
+ const stateLine = st.hasActiveRun
297
+ ? (st.activeStopped ? "⏹ 已停止" : "🟢 正在生成回复")
298
+ : "⚪ 空闲";
299
+ await transport.replyText(
300
+ msg.messageId,
301
+ [
302
+ "📊 当前状态",
303
+ "",
304
+ `状态: ${stateLine}`,
305
+ `目录: ${st.cwd}`,
306
+ `模型: ${model}`,
307
+ `thinking: ${thinking.available ? thinking.currentLevel || "(unknown)" : "(unavailable)"}`,
308
+ `上下文: ${ctxLine}`,
309
+ ].join("\n"),
310
+ );
311
+ return true;
312
+ }
313
+
314
+ if (command.name === "delivery") {
315
+ // 该配置是全局的(runtime-overrides.json),群聊里改会连带影响所有人,所以限私聊
316
+ if (msg.chatType !== "p2p") {
317
+ await transport.replyText(
318
+ msg.messageId,
319
+ "为避免群聊成员改到所有人的消息处理方式,/delivery 仅支持在与机器人的私聊中使用。",
320
+ );
321
+ return true;
322
+ }
323
+ await transport.replyCard(msg.messageId, buildDeliveryCard(loadConfig()?.messageDelivery));
324
+ return true;
325
+ }
326
+
327
+ if (command.name === "restart") {
328
+ // 重启会把当前连接掐断、所有会话的卡片收尾,群聊里手滑一次就影响全员
329
+ if (msg.chatType !== "p2p") {
330
+ await transport.replyText(
331
+ msg.messageId,
332
+ "为避免群聊成员重启服务影响所有人,/restart 仅支持在与机器人的私聊中使用。",
333
+ );
334
+ return true;
335
+ }
336
+ const restart = this.hooks.restart;
337
+ if (!restart) {
338
+ await transport.replyText(msg.messageId, "当前运行方式不支持在聊天里重启。请在 Pi 终端执行 `/feishu restart`。");
339
+ return true;
340
+ }
341
+ const status = this.conversations.getStatus(key);
342
+ if (status.hasActiveRun && command.force) {
343
+ await this.conversations.stopConversation(key, async (reply) => {
344
+ await transport.replyText(msg.messageId, reply);
345
+ });
346
+ }
347
+ const result = await restart({
348
+ trigger: { messageId: msg.messageId, chatId: msg.chatId },
349
+ force: command.force,
350
+ hasActiveRun: status.hasActiveRun && !command.force,
351
+ });
352
+ if (!result.ok) {
353
+ await transport.replyText(msg.messageId, `❌ 无法重启:${result.error || "未知原因"}`);
354
+ }
355
+ return true;
356
+ }
357
+
358
+ if (command.name === "commands") {
359
+ await transport.replyText(msg.messageId, `可用命令:\n${getCommandList()}`);
360
+ return true;
361
+ }
362
+
363
+ if (command.name === "config") {
364
+ if (msg.chatType !== "p2p") {
365
+ await transport.replyText(
366
+ msg.messageId,
367
+ "为避免群聊成员意外修改机器人配置,/config 仅支持在与机器人的私聊中使用。",
368
+ );
369
+ return true;
370
+ }
371
+ if (command.clearTarget) {
372
+ const cleared = clearRuntimeOverrides(command.clearTarget);
373
+ if (cleared.ok === false) {
374
+ await transport.replyText(msg.messageId, `❌ ${cleared.error}`);
375
+ return true;
376
+ }
377
+ const cfg = loadConfig();
378
+ await transport.replyText(
379
+ msg.messageId,
380
+ [
381
+ command.clearTarget === "all" ? "已清除全部 runtime overrides" : `已清除 override: ${command.clearTarget}`,
382
+ "",
383
+ cfg ? formatRuntimeConfig(cfg, getRuntimeOverrides()) : "配置不可用",
384
+ ].join("\n"),
385
+ );
386
+ return true;
387
+ }
388
+ if (command.key) {
389
+ if (command.value === undefined || command.value === "") {
390
+ await transport.replyText(
391
+ msg.messageId,
392
+ `用法: /config ${command.key} <value>\n或: /config clear ${command.key}`,
393
+ );
394
+ return true;
395
+ }
396
+ const set = setRuntimeConfig(command.key, command.value);
397
+ if (set.ok === false) {
398
+ await transport.replyText(msg.messageId, `❌ ${set.error}`);
399
+ return true;
400
+ }
401
+ const cfg = loadConfig();
402
+ await transport.replyText(
403
+ msg.messageId,
404
+ [
405
+ `✅ 已更新 ${set.key} = ${Array.isArray(set.value) ? set.value.join(", ") : String(set.value)}`,
406
+ "已热更新并落盘(runtime-overrides.json)",
407
+ "",
408
+ cfg ? formatRuntimeConfig(cfg, getRuntimeOverrides()) : "",
409
+ ].filter(Boolean).join("\n"),
410
+ );
411
+ return true;
412
+ }
413
+ const cfg = loadConfig();
414
+ await transport.replyText(
415
+ msg.messageId,
416
+ cfg ? formatRuntimeConfig(cfg, getRuntimeOverrides()) : "配置不可用(缺少 FEISHU_APP_ID/SECRET)",
417
+ );
418
+ return true;
419
+ }
420
+
421
+ return false;
422
+ }
423
+
424
+ private isDuplicateContent(msg: FeishuMessage, key: string, text: string, attachments: Array<{ kind: string; fileKey: string; fileName?: string }>) {
425
+ const now = Date.now();
426
+ const attachmentKey = attachments.map((a) => `${a.kind}:${a.fileKey}:${a.fileName || ""}`).join("|");
427
+ const contentKey = [key, msg.senderOpenId, normalizeForDedupe(text), attachmentKey].join("\u0000");
428
+ const previousContentAt = this.recentContent.get(contentKey);
429
+ if (previousContentAt && now - previousContentAt <= CONTENT_DEDUPE_TTL_MS) return true;
430
+ this.recentContent.set(contentKey, now);
431
+ if (this.recentContent.size > 2000) pruneRecentMap(this.recentContent, now, CONTENT_DEDUPE_TTL_MS);
432
+ return false;
433
+ }
434
+
435
+ /**
436
+ * 近重复消息拦截(同一会话、同一人、10 分钟内、内容高度相似)。
437
+ *
438
+ * 为什么要拦:用户把同一句话改个错别字重发,会再开一轮,模型把同一个选择题
439
+ * 又问一遍,看起来像「重复回复」。拦下时会告诉他怎么显式重跑(「重发」前缀)。
440
+ * 返回 true = 已拦下(调用方结束本轮)。
441
+ */
442
+ private async guardNearDuplicate(msg: FeishuMessage, key: string, text: string): Promise<boolean> {
443
+ const probe = normalizeForDedupe(text);
444
+ const memoryKey = `${key}\u0000${msg.senderOpenId}`;
445
+ const now = Date.now();
446
+ const previous = this.recentPrompts.get(memoryKey);
447
+
448
+ // 短消息不参与判断,但仍然记下来(后续长消息可以拿来比)
449
+ if (probe.replace(/\s+/g, "").length >= NEAR_DUPLICATE_MIN_CHARS) {
450
+ this.recentPrompts.set(memoryKey, { text: probe, at: now });
451
+ if (this.recentPrompts.size > 2000) {
452
+ for (const [entryKey, entry] of this.recentPrompts) {
453
+ if (now - entry.at > NEAR_DUPLICATE_TTL_MS) this.recentPrompts.delete(entryKey);
454
+ }
455
+ }
456
+ }
457
+
458
+ if (!previous || now - previous.at > NEAR_DUPLICATE_TTL_MS) return false;
459
+ const score = textSimilarity(previous.text, probe);
460
+ if (score < NEAR_DUPLICATE_THRESHOLD) return false;
461
+
462
+ const seconds = Math.round((now - previous.at) / 1000);
463
+ debugLog("feishu.handler.near_duplicate", {
464
+ messageId: msg.messageId,
465
+ key,
466
+ score: Number(score.toFixed(3)),
467
+ secondsAgo: seconds,
468
+ });
469
+ await this.getTransport()?.replyText(
470
+ msg.messageId,
471
+ `这条和 ${seconds} 秒前那条几乎一样(相似度 ${Math.round(score * 100)}%),我就不重开一轮了。\n`
472
+ + `确实要我再跑一遍,就在开头加「重发」,例如:重发 ${text.slice(0, 40)}`,
473
+ );
474
+ return true;
475
+ }
476
+
477
+ }
478
+
479
+ export function buildPrompt(
480
+ msg: FeishuMessage,
481
+ text: string,
482
+ fileSections: string[],
483
+ imageInputs: FeishuImageInput[],
484
+ skippedImageCount: number,
485
+ modelSupportsImage: boolean,
486
+ downloadErrors: string[],
487
+ senderName?: string,
488
+ ) {
489
+ const contentParts: string[] = [];
490
+ if (text.trim()) contentParts.push(text.trim());
491
+ if (fileSections.length) contentParts.push(fileSections.join("\n\n"));
492
+ if (!contentParts.length && imageInputs.length) {
493
+ contentParts.push("请根据图片内容进行分析。");
494
+ }
495
+
496
+ if (skippedImageCount > 0 && !modelSupportsImage) {
497
+ contentParts.push("[提示:当前模型不支持图片,本次仅处理文本/文件内容。]");
498
+ }
499
+
500
+ if (downloadErrors.length) {
501
+ contentParts.push(`[部分附件未处理:${downloadErrors.join(";")}]`);
502
+ }
503
+
504
+ const promptBody = contentParts.join("\n\n").trim();
505
+ // 首行固定标记(谁提的):**必须放在正文之前**,且只在此处注入 ——
506
+ // 不要塞进 buildPromptWithQuote 的引用块(那会把引用者的身份当成提出人)。
507
+ const marked = [buildRequesterMarker(msg.senderOpenId, msg.chatType, senderName), promptBody]
508
+ .filter(Boolean)
509
+ .join("\n");
510
+ const label = conversationLabel(msg);
511
+ return label ? `${label} ${marked}` : marked;
512
+ }