@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,356 @@
1
+ import { extractTextFromInteractiveCard } from "./interactive-card.ts";
2
+ import type { FeishuAttachment, FeishuMessage, ParsedMessageInput } from "./types.ts";
3
+
4
+ export type BotCommand =
5
+ | { name: "new" }
6
+ | { name: "resume" }
7
+ | { name: "model" }
8
+ | { name: "thinking" }
9
+ | { name: "stop" }
10
+ | { name: "workspace"; path?: string }
11
+ | { name: "status" }
12
+ | { name: "commands" }
13
+ | { name: "delivery" }
14
+ | { name: "config"; key?: string; value?: string; clearTarget?: string }
15
+ | { name: "restart"; force?: boolean };
16
+
17
+ type PostBody = {
18
+ title?: string;
19
+ content?: unknown[];
20
+ };
21
+
22
+ export function normalizeForDedupe(text: string) {
23
+ return text.replace(/\s+/g, " ").trim();
24
+ }
25
+
26
+ /**
27
+ * 归一化到「只留内容」的形态:去空白、去中英文标点、统一小写。
28
+ * 近重复判断用它,避免「只改了个错别字 / 少打一个逗号」被当成两条不同消息。
29
+ */
30
+ export function normalizeForSimilarity(text: string) {
31
+ return text
32
+ .toLowerCase()
33
+ .replace(/\s+/g, "")
34
+ .replace(/[\u3000-\u303f\uff00-\uffef!-/:-@[-`{-~]/g, "");
35
+ }
36
+
37
+ /** 相似度超过这个值就算「同一句话」 */
38
+ export const NEAR_DUPLICATE_THRESHOLD = 0.9;
39
+
40
+ /**
41
+ * 文本相似度(1 = 完全相同,0 = 毫无关系):按编辑距离归一化。
42
+ * 实测:改一个错别字的重复请求 0.952(拦下);补一句追问「…了吗」0.8(放行)。
43
+ */
44
+ export function textSimilarity(a: string, b: string): number {
45
+ const x = normalizeForSimilarity(a);
46
+ const y = normalizeForSimilarity(b);
47
+ if (!x && !y) return 1;
48
+ if (!x || !y) return 0;
49
+ if (x === y) return 1;
50
+ // 超长文本(粘贴日志等)不做逐字编辑距离:代价高且它们本来就不像重复请求
51
+ const CAP = 2000;
52
+ const left = x.slice(0, CAP);
53
+ const right = y.slice(0, CAP);
54
+ return 1 - levenshteinDistance(left, right) / Math.max(left.length, right.length);
55
+ }
56
+
57
+ function levenshteinDistance(a: string, b: string): number {
58
+ const m = a.length;
59
+ const n = b.length;
60
+ if (!m) return n;
61
+ if (!n) return m;
62
+ let prev = Array.from({ length: n + 1 }, (_, i) => i);
63
+ let cur = new Array<number>(n + 1);
64
+ for (let i = 1; i <= m; i++) {
65
+ cur[0] = i;
66
+ for (let j = 1; j <= n; j++) {
67
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
68
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + cost);
69
+ }
70
+ [prev, cur] = [cur, prev];
71
+ }
72
+ return prev[n];
73
+ }
74
+
75
+ /** 强制重跑的标记前缀:加了就直接开新一轮,不再被近重复拦住 */
76
+ export const RERUN_MARKERS = ["重发", "/again", "/重发"];
77
+
78
+ /**
79
+ * 去掉「重发 / /again」前缀,返回真正要送给模型的正文。
80
+ * 没有前缀时原样返回(调用方据此判断用户是否显式要求重跑)。
81
+ */
82
+ export function stripRerunMarker(text: string): string {
83
+ const trimmed = text.trimStart();
84
+ const lower = trimmed.toLowerCase();
85
+ for (const marker of RERUN_MARKERS) {
86
+ if (!lower.startsWith(marker.toLowerCase())) continue;
87
+ return trimmed.slice(marker.length).replace(/^[\s::,,、-]+/, "");
88
+ }
89
+ return text;
90
+ }
91
+
92
+ export function pruneRecentMap(map: Map<string, number>, now: number, ttlMs: number) {
93
+ for (const [key, timestamp] of map) {
94
+ if (now - timestamp > ttlMs) map.delete(key);
95
+ }
96
+ }
97
+
98
+ export function conversationKey(msg: FeishuMessage) {
99
+ if (msg.chatType === "p2p") return `p2p:${msg.senderOpenId}`;
100
+ const threadId = msg.threadId || msg.rootId || msg.parentId;
101
+ if (threadId) return `group:${msg.chatId}:thread:${threadId}`;
102
+ if (msg.chatMode === "topic") return `group:${msg.chatId}:thread:${msg.messageId}`;
103
+ return `group:${msg.chatId}`;
104
+ }
105
+
106
+ export function conversationLabel(_msg: FeishuMessage) {
107
+ // 不再给消息加渠道标签:已验证这类前缀会诱发模型把工具调用写成 DSML 文本草稿,
108
+ // 导致整轮没有可发送的回答。消息文本保持与网页直输一致。
109
+ return "";
110
+ }
111
+
112
+ export function parseMessageInput(
113
+ msg: FeishuMessage,
114
+ botOpenId?: string,
115
+ options?: { parseInteractiveCards?: boolean },
116
+ ): ParsedMessageInput {
117
+ const attachments: FeishuAttachment[] = [];
118
+ const parseInteractive = options?.parseInteractiveCards !== false;
119
+ try {
120
+ const json = JSON.parse(msg.content || "{}");
121
+ if (msg.msgType === "text") {
122
+ let text = String(json.text || "");
123
+ if (botOpenId) text = text.replace(new RegExp(`@?${botOpenId}`, "g"), "");
124
+ // 去掉飞书 @ 人的占位符(如 @_user_1):对模型是无意义噪音
125
+ text = text.replace(/@_user_\d+/g, "");
126
+ return { text: text.trim(), attachments, source: "text" };
127
+ }
128
+ if (msg.msgType === "post") {
129
+ const post = json.post || json;
130
+ const locale = resolvePostBody(post);
131
+ const parts: string[] = [];
132
+ if (typeof locale?.title === "string" && locale.title.trim()) {
133
+ parts.push(locale.title.trim());
134
+ }
135
+ for (const para of locale?.content || []) {
136
+ const paragraphText = extractPostText(para, attachments).trim();
137
+ if (paragraphText) parts.push(paragraphText);
138
+ }
139
+ collectAttachments(json, attachments);
140
+ return { text: parts.join("\n").trim(), attachments, source: "post" };
141
+ }
142
+ if (msg.msgType === "interactive" && parseInteractive) {
143
+ const extracted = extractTextFromInteractiveCard(msg.content || "{}");
144
+ return { text: extracted.text, attachments: extracted.attachments, source: "interactive" };
145
+ }
146
+ if (msg.msgType === "image" && typeof json.image_key === "string" && json.image_key) {
147
+ attachments.push({ kind: "image", fileKey: json.image_key });
148
+ collectAttachments(json, attachments);
149
+ return { text: "", attachments, source: "image" };
150
+ }
151
+ if (msg.msgType === "file" && typeof json.file_key === "string" && json.file_key) {
152
+ attachments.push({
153
+ kind: "file",
154
+ fileKey: json.file_key,
155
+ fileName: typeof json.file_name === "string" ? json.file_name : undefined,
156
+ });
157
+ collectAttachments(json, attachments);
158
+ return { text: "", attachments, source: "file" };
159
+ }
160
+ collectAttachments(json, attachments);
161
+ if (attachments.length) return { text: "", attachments, source: msg.msgType };
162
+ } catch {}
163
+ // 未知类型:不要静默丢弃,至少给 agent 一个占位
164
+ if (msg.msgType === "text") return { text: msg.content, attachments, source: "text-raw" };
165
+ if (msg.msgType === "interactive") {
166
+ return {
167
+ text: `[interactive]\n${(msg.content || "").slice(0, 1500)}`,
168
+ attachments,
169
+ source: "interactive-fallback",
170
+ };
171
+ }
172
+ return { text: `[${msg.msgType}]`, attachments, source: "unknown" };
173
+ }
174
+
175
+ export function parseBotCommand(text: string): BotCommand | undefined {
176
+ const trimmed = text.trim();
177
+ const normalized = trimmed.replace(/\s+/g, " ");
178
+ if (normalized === "/new") return { name: "new" };
179
+ if (normalized === "/resume") return { name: "resume" };
180
+ if (normalized === "/model") return { name: "model" };
181
+ if (normalized === "/thinking") return { name: "thinking" };
182
+ if (normalized === "/stop") return { name: "stop" };
183
+ if (normalized === "/status") return { name: "status" };
184
+ if (normalized === "/commands") return { name: "commands" };
185
+ if (normalized === "/delivery") return { name: "delivery" };
186
+ // /restart:重启桥接进程(保留会话上下文)。force = 有回复在生成时强行中止后重启。
187
+ if (normalized === "/restart") return { name: "restart" };
188
+ if (normalized === "/restart force") return { name: "restart", force: true };
189
+ const workspaceMatch = trimmed.match(/^\/workspace(?:\s+(.+))?$/s);
190
+ if (workspaceMatch) {
191
+ return { name: "workspace", path: workspaceMatch[1]?.trim() };
192
+ }
193
+ const configMatch = trimmed.match(/^\/config(?:\s+(.+))?$/s);
194
+ if (configMatch) {
195
+ const rest = (configMatch[1] || "").trim();
196
+ if (!rest) return { name: "config" };
197
+ const parts = rest.split(/\s+/);
198
+ if (parts[0] === "clear") {
199
+ return { name: "config", clearTarget: parts[1] || "all" };
200
+ }
201
+ const key = parts[0];
202
+ const value = rest.slice(key.length).trim();
203
+ return { name: "config", key, value: value || undefined };
204
+ }
205
+ return undefined;
206
+ }
207
+
208
+ export function getCommandList(): string {
209
+ return [
210
+ "【桥接命令】由桥接直接处理",
211
+ "/new — 新建会话",
212
+ "/resume — 恢复历史会话(卡片选择)",
213
+ "/model — 切换模型",
214
+ "/thinking — 调整当前会话的思考强度",
215
+ "/workspace [path] — 切换工作区",
216
+ "/status — 查看当前模型、思考强度、目录和状态",
217
+ "/stop — 停止当前生成",
218
+ "/delivery — 设置「正在生成时又收到新消息」怎么处理(排队 / 立即打断,仅私聊)",
219
+ "/restart — 重启桥接进程,加载最新代码(保留会话上下文;/restart force 强制中止在跑的回复)",
220
+ "/config — 查看/修改运行时配置(群触发、流式等)",
221
+ "/config <key> <value> — 设置白名单配置并立即生效",
222
+ "/config clear [key|all] — 清除 runtime overrides",
223
+ "/commands — 显示命令列表",
224
+ "",
225
+ "【Pi 流程命令】交回 Pi 执行(仅 Pi runtime,见 .pi/extensions/knowledge-flow)",
226
+ "/learn [反馈原文] — 把反馈落成 .pi/ 下的规范改动(无参数则复盘本会话)",
227
+ "/deploy-test [端名] — 测试环境部署(rust_server / quasar / quasar_h5 / quasar-offical-web / senlan-official-web)",
228
+ "",
229
+ "【透传给模型】/req、/kb、/test 在飞书里不派发命令处理,斜杠文本原样交给模型——直接说需求即可。",
230
+ ].join("\n");
231
+ }
232
+
233
+ /**
234
+ * 「谁提的」标记:桥接把本条消息的发送者身份作为**固定首行**注入 prompt。
235
+ *
236
+ * 用途:`/req 新` 建需求时把 open_id 落进 `manifest.json` 的 `requester`(提出人),
237
+ * 否则需求池里的需求事后完全查不出是谁提的(见 `.pi/extensions/knowledge-flow/index.ts`
238
+ * 的 `kb_need_create` 与 `prompts/需求-命名.md` 第 1 步)。
239
+ *
240
+ * 口径:群聊里这个 open_id 只是**本条消息的发送者**(同一需求可能多人接话),
241
+ * 不等于「需求提出人」——流程侧按「拿不到就写未记录、不许猜」处理。
242
+ * 缺字段时用「未知」占位,但标记行**必须始终存在且形状不变**(流程靠它做字符串匹配)。
243
+ */
244
+ export function buildRequesterMarker(openId?: string, chatType?: string, name?: string): string {
245
+ const id = openId?.trim() || "未知";
246
+ const type = chatType?.trim() || "未知";
247
+ const who = name?.trim();
248
+ // name 追加在最后:`[飞书提出人] open_id=` 这个前缀形状保持不变,
249
+ // 流程侧(需求-命名 / 需求-分析 / 需求-开发)靠它原样读 open_id,加个尾巴不影响。
250
+ // 查不到姓名时完全退回旧形状(见 user-name.ts:缺 contact 字段权限就会查不到)。
251
+ return who
252
+ ? `[飞书提出人] open_id=${id} chat_type=${type} name=${who}`
253
+ : `[飞书提出人] open_id=${id} chat_type=${type}`;
254
+ }
255
+
256
+ /** 合并用户文本与引用父消息,供 agent 调查告警卡片等场景 */
257
+ export function buildPromptWithQuote(userText: string, quoted?: { msgType: string; text: string } | null): string {
258
+ if (!quoted?.text?.trim()) return userText;
259
+ // 引用块**只带正文**,不带引用消息的发送者:否则「提出人」会被引用者身份污染
260
+ // (引用别人的话去提需求,会被记成那个人的需求)。
261
+ const blocks = [
262
+ "[Quoted message]",
263
+ `type: ${quoted.msgType}`,
264
+ "---",
265
+ quoted.text.trim(),
266
+ "---",
267
+ "[User]",
268
+ userText || "(no text)",
269
+ ];
270
+ return blocks.join("\n");
271
+ }
272
+
273
+ function resolvePostBody(post: unknown): PostBody | undefined {
274
+ if (isPostBody(post)) return post;
275
+ if (!post || typeof post !== "object" || Array.isArray(post)) return undefined;
276
+
277
+ const record = post as Record<string, unknown>;
278
+ const candidates = [record.zh_cn, record.en_us, ...Object.values(record)];
279
+ return candidates.find(isPostBody);
280
+ }
281
+
282
+ function isPostBody(value: unknown): value is PostBody {
283
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
284
+ const record = value as Record<string, unknown>;
285
+ return Array.isArray(record.content);
286
+ }
287
+
288
+ function extractPostText(node: unknown, attachments: FeishuAttachment[]): string {
289
+ if (typeof node === "string") return node;
290
+ if (!node || typeof node !== "object") return "";
291
+ if (Array.isArray(node)) return node.map((item) => extractPostText(item, attachments)).join("");
292
+
293
+ const obj = node as Record<string, unknown>;
294
+ const tag = typeof obj.tag === "string" ? obj.tag : undefined;
295
+
296
+ if ((tag === "img" || tag === "image") && typeof obj.image_key === "string" && obj.image_key) {
297
+ attachments.push({ kind: "image", fileKey: obj.image_key });
298
+ return "";
299
+ }
300
+
301
+ if (tag === "at") {
302
+ // @ 人占位:不保留名字,避免给模型引入无意义噪音
303
+ return "";
304
+ }
305
+
306
+ // 有序列表 / 无序列表:飞书 post 常见 tag,避免 #4 空解析
307
+ if (tag === "ol" || tag === "ul" || tag === "li") {
308
+ return Object.values(obj)
309
+ .map((item) => extractPostText(item, attachments))
310
+ .join(tag === "li" ? "\n" : "");
311
+ }
312
+
313
+ if ((tag === "text" || tag === "a") && typeof obj.text === "string") {
314
+ return obj.text;
315
+ }
316
+
317
+ if (typeof obj.text === "string") return obj.text;
318
+
319
+ return Object.values(obj)
320
+ .map((item) => extractPostText(item, attachments))
321
+ .join("");
322
+ }
323
+
324
+ function collectAttachments(value: unknown, attachments: FeishuAttachment[]) {
325
+ const seen = new Set(attachments.map((item) => `${item.kind}:${item.fileKey}`));
326
+ walk(value);
327
+
328
+ function add(attachment: FeishuAttachment) {
329
+ const key = `${attachment.kind}:${attachment.fileKey}`;
330
+ if (seen.has(key)) return;
331
+ seen.add(key);
332
+ attachments.push(attachment);
333
+ }
334
+
335
+ function walk(node: unknown) {
336
+ if (!node || typeof node !== "object") return;
337
+ if (Array.isArray(node)) {
338
+ for (const item of node) walk(item);
339
+ return;
340
+ }
341
+
342
+ const obj = node as Record<string, unknown>;
343
+ if (typeof obj.image_key === "string" && obj.image_key) {
344
+ add({ kind: "image", fileKey: obj.image_key });
345
+ }
346
+ if (typeof obj.file_key === "string" && obj.file_key) {
347
+ add({
348
+ kind: "file",
349
+ fileKey: obj.file_key,
350
+ fileName: typeof obj.file_name === "string" ? obj.file_name : undefined,
351
+ });
352
+ }
353
+
354
+ for (const item of Object.values(obj)) walk(item);
355
+ }
356
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * 卡片体积超限时的兜底:新发一条「只带执行清单」的消息卡片。
3
+ *
4
+ * 背景:飞书卡片 JSON 有个约 30KB 的硬上限(错误码 200860)。收尾时要把整张卡
5
+ * 重发一遍(为了把标题从「回复中」改成「回复」),一旦正文把整卡撑爆,这次
6
+ * 更新就失败,卡片会**永远停在「回复中」**——正是本改造要消灭的症状。
7
+ *
8
+ * 为什么不原地重试:正文本身就是撑爆整卡的主因,去掉清单也未必救得回来;
9
+ * 而正文用户已经从流式输出里看完了,真正丢的是「这轮结束了」+ 执行清单。
10
+ * 新开一条消息,体积只由清单决定,先裁到 8KB 再发,就不会再撞。
11
+ *
12
+ * 本模块不碰 CardKitStream 的内部状态,只收参数、发消息,便于单测。
13
+ */
14
+ import { buildReplyCard, type ReplyCardStatus } from "./card-builder.ts";
15
+ import { OVERSIZE_PROGRESS_BYTES, byteLength, trimProgressToBytes } from "./progress-note.ts";
16
+ import { debugLog } from "./debug.ts";
17
+ import { withRetry } from "./retry.ts";
18
+
19
+ type SendTarget = { chatId: string } | { replyToMessageId: string };
20
+
21
+ type ApiResponse = { code?: number; msg?: string; data?: { message_id?: string } };
22
+
23
+ export type OversizeProgressCardInput = {
24
+ baseUrl: string;
25
+ /** 取 tenant_access_token(带缓存由调用方负责) */
26
+ getToken: () => Promise<string>;
27
+ target: SendTarget;
28
+ conversationKey?: string;
29
+ runId?: string;
30
+ /** 原卡标题,兜底卡会加「· 执行过程」后缀 */
31
+ title?: string;
32
+ finalStatus: ReplyCardStatus;
33
+ /** 已渲染好的清单全文(会按字节裁剪) */
34
+ progress: string;
35
+ onOutboundMessageId?: (messageId: string) => void;
36
+ };
37
+
38
+ /**
39
+ * 发送兜底清单卡。**失败不抛**:这是补救流程,它自己挂了不能反过来搞砸主流程。
40
+ */
41
+ export async function sendOversizeProgressCard(input: OversizeProgressCardInput): Promise<boolean> {
42
+ const progress = input.progress.trim();
43
+ if (!progress) return false; // 没有清单就没什么可补的,别多刷一条消息
44
+
45
+ try {
46
+ const token = await withRetry(input.getToken, {
47
+ maxRetries: 3,
48
+ label: "feishu.cardkit.oversize_token",
49
+ });
50
+ const trimmed = trimProgressToBytes(progress, OVERSIZE_PROGRESS_BYTES);
51
+ const card = buildReplyCard({
52
+ key: input.conversationKey ?? "",
53
+ runId: input.runId,
54
+ status: input.finalStatus,
55
+ title: `${input.title ?? "回复"} · 执行过程`,
56
+ body: `${trimmed}\n\n> 正文见上一条(卡片体积超限,未随本条重复发送)`,
57
+ });
58
+
59
+ const isCreate = "chatId" in input.target;
60
+ const url = isCreate
61
+ ? `${input.baseUrl}/open-apis/im/v1/messages?receive_id_type=chat_id`
62
+ : `${input.baseUrl}/open-apis/im/v1/messages/${(input.target as { replyToMessageId: string }).replyToMessageId}/reply`;
63
+
64
+ const res = await withRetry(() =>
65
+ fetch(url, {
66
+ method: "POST",
67
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
68
+ body: JSON.stringify({
69
+ ...(isCreate ? { receive_id: (input.target as { chatId: string }).chatId } : {}),
70
+ msg_type: "interactive",
71
+ content: JSON.stringify(card),
72
+ }),
73
+ }),
74
+ { maxRetries: 2, label: "feishu.cardkit.oversize_send" },
75
+ );
76
+ const json = (await res.json().catch(() => ({}))) as ApiResponse;
77
+ if (!res.ok || (json.code != null && json.code !== 0)) {
78
+ debugLog("feishu.cardkit.oversize_error", {
79
+ status: res.status,
80
+ code: json.code,
81
+ msg: json.msg,
82
+ });
83
+ return false;
84
+ }
85
+
86
+ const messageId = json.data?.message_id;
87
+ if (messageId) input.onOutboundMessageId?.(messageId);
88
+ debugLog("feishu.cardkit.oversize_fallback_sent", {
89
+ messageId,
90
+ rawBytes: byteLength(progress),
91
+ trimmedBytes: byteLength(trimmed),
92
+ finalStatus: input.finalStatus,
93
+ });
94
+ return true;
95
+ } catch (e) {
96
+ debugLog("feishu.cardkit.oversize_throw", {
97
+ error: e instanceof Error ? e.message : String(e),
98
+ });
99
+ return false;
100
+ }
101
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * 进度通道:把卡片上的「过程清单」推上去的唯一出口。
3
+ *
4
+ * 两个目标元件:
5
+ * - `progress`(markdown):清单正文,走 `PUT /elements/progress/content`
6
+ * - `progress_panel`(collapsible_panel):只在收起模式下存在,走 `PATCH /elements/progress_panel`
7
+ * 改标题 —— 面板一收,标题就是用户唯一能看出「还在干活」的地方
8
+ *
9
+ * 从 CardKitStream 抽出来的一层:那边只保留「正文怎么发」,
10
+ * 「进度怎么发」的元件定位、去重、节流都在这里。
11
+ */
12
+ import { debugLog } from "./debug.ts";
13
+
14
+ export type ProgressSnapshot = { title: string; body: string };
15
+
16
+ export type ProgressChannelDeps = {
17
+ /** progressMode=off 时为 false:所有推送直接跳过,零开销 */
18
+ enabled: boolean;
19
+ /** 是否用了折叠面板(没折叠就没有标题可改) */
20
+ collapsed: boolean;
21
+ baseUrl: () => string;
22
+ /** 卡片还没建好时返回 undefined,此时此刻所有推送都要跳过 */
23
+ cardId: () => string | undefined;
24
+ getToken: () => Promise<string>;
25
+ /** 取下一个严格递增的 sequence —— 全卡共享,两个元件与正文都从它取号 */
26
+ nextSequence: () => number;
27
+ };
28
+
29
+ export class ProgressChannel {
30
+ private readonly deps: ProgressChannelDeps;
31
+ private source: (() => ProgressSnapshot) | undefined;
32
+ /** 去重键用「实际发出去的 content」:原文可能带空白,用原文比较会重复发送 */
33
+ private lastBody: string | null = null;
34
+ private lastTitle: string | null = null;
35
+
36
+ constructor(deps: ProgressChannelDeps) {
37
+ this.deps = deps;
38
+ }
39
+
40
+ /**
41
+ * 设置取数回调。用回调而不是一次性字符串:`timeout` / `action` 档的
42
+ * 「已执行 Ns」必须随时间长,而 Pi 在单个工具运行期间**不发任何事件**,
43
+ * 只有 tick 能驱动刷新。
44
+ */
45
+ setSource(source: (() => ProgressSnapshot) | undefined): void {
46
+ if (!this.deps.enabled) return;
47
+ this.source = source;
48
+ }
49
+
50
+ /** 当前快照(收尾时要拿它定格到终态卡上) */
51
+ snapshot(): ProgressSnapshot {
52
+ if (!this.source) return { title: "", body: "" };
53
+ try {
54
+ const snap = this.source();
55
+ return { title: snap?.title ?? "", body: snap?.body ?? "" };
56
+ } catch (e) {
57
+ debugLog("feishu.progress.source_error", {
58
+ error: e instanceof Error ? e.message : String(e),
59
+ });
60
+ return { title: "", body: "" };
61
+ }
62
+ }
63
+
64
+ /** 推送最新快照;内容与标题各走一条接口,各自去重 */
65
+ async tick(): Promise<void> {
66
+ if (!this.deps.enabled || !this.deps.cardId()) return;
67
+ const snap = this.snapshot();
68
+ await this.putBody(snap.body);
69
+ await this.patchTitle(snap.title);
70
+ }
71
+
72
+ /**
73
+ * 关流式前强制推一次。
74
+ * 关掉 streaming_mode 后内容接口就不能再用了,此刻不推就永远推不上去。
75
+ */
76
+ async flush(): Promise<void> {
77
+ await this.tick();
78
+ }
79
+
80
+ private async putBody(text: string) {
81
+ const content = text.trim() || " "; // 飞书不接受空内容,空清单用一个空格占位
82
+ if (content === this.lastBody) return;
83
+ const cardId = this.deps.cardId();
84
+ if (!cardId) return;
85
+ try {
86
+ const token = await this.deps.getToken();
87
+ const seq = this.deps.nextSequence();
88
+ const res = await fetch(
89
+ `${this.deps.baseUrl()}/open-apis/cardkit/v1/cards/${cardId}/elements/progress/content`,
90
+ {
91
+ method: "PUT",
92
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
93
+ body: JSON.stringify({ content, sequence: seq, uuid: `${cardId}_progress_${seq}` }),
94
+ },
95
+ );
96
+ if (!res.ok) {
97
+ debugLog("feishu.cardkit.progress_error", {
98
+ seq,
99
+ status: res.status,
100
+ body: (await res.text()).slice(0, 200),
101
+ });
102
+ return;
103
+ }
104
+ this.lastBody = content;
105
+ } catch (e) {
106
+ debugLog("feishu.cardkit.progress_throw", {
107
+ error: e instanceof Error ? e.message : String(e),
108
+ });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 改折叠面板标题。
114
+ * 注意 `partial_element` 是 **JSON 字符串**(官方文档示例未转义,直接传对象会报错)。
115
+ */
116
+ private async patchTitle(title: string) {
117
+ if (!this.deps.collapsed) return; // 没折叠面板就没标题可改
118
+ const content = title.trim();
119
+ if (!content || content === this.lastTitle) return;
120
+ const cardId = this.deps.cardId();
121
+ if (!cardId) return;
122
+ try {
123
+ const token = await this.deps.getToken();
124
+ const seq = this.deps.nextSequence();
125
+ const res = await fetch(
126
+ `${this.deps.baseUrl()}/open-apis/cardkit/v1/cards/${cardId}/elements/progress_panel`,
127
+ {
128
+ method: "PATCH",
129
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
130
+ body: JSON.stringify({
131
+ partial_element: JSON.stringify({
132
+ header: { title: { tag: "plain_text", content } },
133
+ }),
134
+ sequence: seq,
135
+ uuid: `${cardId}_panel_${seq}`,
136
+ }),
137
+ },
138
+ );
139
+ if (!res.ok) {
140
+ debugLog("feishu.cardkit.progress_title_error", {
141
+ seq,
142
+ status: res.status,
143
+ body: (await res.text()).slice(0, 200),
144
+ });
145
+ return;
146
+ }
147
+ this.lastTitle = content;
148
+ } catch (e) {
149
+ debugLog("feishu.cardkit.progress_title_throw", {
150
+ error: e instanceof Error ? e.message : String(e),
151
+ });
152
+ }
153
+ }
154
+ }