@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,483 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 飞书 CardKit 真正的流式卡片:
|
|
3
|
+
* streaming_mode + print_frequency_ms/print_step 由客户端逐字打印。
|
|
4
|
+
* 我们侧只需定期 PUT 完整 markdown 内容。
|
|
5
|
+
* running 卡必须带「停止」按钮(与 card-builder 契约一致)。
|
|
6
|
+
*/
|
|
7
|
+
import { buildCardKitCardJson, type ReplyCardStatus } from "./card-builder.ts";
|
|
8
|
+
import { stripLocalImageMarkdown } from "./image-send.ts";
|
|
9
|
+
import { ProgressChannel } from "./progress-channel.ts";
|
|
10
|
+
import { byteLength } from "./progress-note.ts";
|
|
11
|
+
import { sendOversizeProgressCard } from "./oversize-progress-card.ts";
|
|
12
|
+
import { debugLog } from "./debug.ts";
|
|
13
|
+
import { withRetry } from "./retry.ts";
|
|
14
|
+
|
|
15
|
+
type CardKitResponse = { code: number; msg: string; data?: any };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* 卡片发到哪里:
|
|
19
|
+
* - chatId:平铺成一条新消息(默认;多条 reply 会被飞书折叠成同一个回复簇,后到的盖住先到的)
|
|
20
|
+
* - replyToMessageId:回复某条消息(话题群/回复链必须用这个,否则会新开话题)
|
|
21
|
+
*/
|
|
22
|
+
export type CardKitTarget = { chatId: string } | { replyToMessageId: string };
|
|
23
|
+
|
|
24
|
+
/** CardKit 卡片可写入的状态(paused/answered 是中间态,允许重复全量更新) */
|
|
25
|
+
export type CardKitCardStatus = Extract<
|
|
26
|
+
ReplyCardStatus,
|
|
27
|
+
"running" | "paused" | "answered" | "done" | "stopped" | "failed"
|
|
28
|
+
>;
|
|
29
|
+
|
|
30
|
+
export type CardKitStreamOptions = {
|
|
31
|
+
/** 客户端打印频率 ms(默认 50,越小越跟手) */
|
|
32
|
+
printFrequencyMs?: number;
|
|
33
|
+
/** 客户端每次打印字符数(默认 1 = 逐字) */
|
|
34
|
+
printStep?: number;
|
|
35
|
+
/** 服务端把 fullText 推到 CardKit 的间隔 ms(默认 120) */
|
|
36
|
+
pushIntervalMs?: number;
|
|
37
|
+
/** 会话 key,用于停止按钮回调 */
|
|
38
|
+
conversationKey?: string;
|
|
39
|
+
/** 本轮 runId,用于停止按钮回调 */
|
|
40
|
+
runId?: string;
|
|
41
|
+
/** 覆盖卡片默认标题(续段用「回复(接上条)」) */
|
|
42
|
+
title?: string;
|
|
43
|
+
/** 卡片正文上方的说明(续段用来交代「承接上一条回复」) */
|
|
44
|
+
note?: string;
|
|
45
|
+
/**
|
|
46
|
+
* 是否在卡片上预留工具过程清单元件(element_id: progress)。
|
|
47
|
+
* true 时建卡即插入该元件:CardKit 只能按 element_id 更新已存在的元件,
|
|
48
|
+
* 建卡时不留位,后续再想写清单就 PUT 不上去。
|
|
49
|
+
*/
|
|
50
|
+
progressEnabled?: boolean;
|
|
51
|
+
/** 是否把清单收进折叠面板(默认 true;action / timeout 档只有一行,不必收) */
|
|
52
|
+
progressCollapsed?: boolean;
|
|
53
|
+
/** 记录本 bot 发出的消息 id(供 groupAlsoOnReply) */
|
|
54
|
+
onOutboundMessageId?: (messageId: string) => void;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
export class CardKitStream {
|
|
58
|
+
private cardId: string | null = null;
|
|
59
|
+
private fullText = "";
|
|
60
|
+
private lastSent = "";
|
|
61
|
+
/** 工具过程清单通道(内容 + 折叠面板标题) */
|
|
62
|
+
private readonly progress: ProgressChannel;
|
|
63
|
+
private token: string | null = null;
|
|
64
|
+
private tokenExpiry = 0;
|
|
65
|
+
private sequence = 1;
|
|
66
|
+
private interval: ReturnType<typeof setInterval> | null = null;
|
|
67
|
+
private startPromise: Promise<void> | null = null;
|
|
68
|
+
private closed = false;
|
|
69
|
+
private failed = false;
|
|
70
|
+
private readonly printFrequencyMs: number;
|
|
71
|
+
private readonly printStep: number;
|
|
72
|
+
private readonly pushIntervalMs: number;
|
|
73
|
+
private readonly conversationKey?: string;
|
|
74
|
+
private readonly runId?: string;
|
|
75
|
+
private readonly title?: string;
|
|
76
|
+
private readonly note?: string;
|
|
77
|
+
private readonly progressEnabled: boolean;
|
|
78
|
+
private readonly progressCollapsed: boolean;
|
|
79
|
+
private readonly onOutboundMessageId?: (messageId: string) => void;
|
|
80
|
+
private readonly appId: string;
|
|
81
|
+
private readonly appSecret: string;
|
|
82
|
+
private readonly domain: "feishu" | "lark";
|
|
83
|
+
private readonly target: CardKitTarget;
|
|
84
|
+
private readonly fallbackReply: (text: string) => Promise<void>;
|
|
85
|
+
|
|
86
|
+
constructor(
|
|
87
|
+
appId: string,
|
|
88
|
+
appSecret: string,
|
|
89
|
+
domain: "feishu" | "lark",
|
|
90
|
+
target: string | CardKitTarget,
|
|
91
|
+
fallbackReply: (text: string) => Promise<void>,
|
|
92
|
+
options?: CardKitStreamOptions,
|
|
93
|
+
) {
|
|
94
|
+
this.appId = appId;
|
|
95
|
+
this.appSecret = appSecret;
|
|
96
|
+
this.domain = domain;
|
|
97
|
+
this.target = typeof target === "string" ? { replyToMessageId: target } : target;
|
|
98
|
+
this.fallbackReply = fallbackReply;
|
|
99
|
+
this.printFrequencyMs = Math.max(20, options?.printFrequencyMs ?? 50);
|
|
100
|
+
this.printStep = Math.max(1, options?.printStep ?? 1);
|
|
101
|
+
this.pushIntervalMs = Math.max(50, options?.pushIntervalMs ?? 120);
|
|
102
|
+
this.conversationKey = options?.conversationKey;
|
|
103
|
+
this.runId = options?.runId;
|
|
104
|
+
this.title = options?.title;
|
|
105
|
+
this.note = options?.note;
|
|
106
|
+
this.progressEnabled = options?.progressEnabled === true;
|
|
107
|
+
this.progressCollapsed = options?.progressCollapsed !== false;
|
|
108
|
+
this.progress = new ProgressChannel({
|
|
109
|
+
enabled: this.progressEnabled,
|
|
110
|
+
collapsed: this.progressCollapsed,
|
|
111
|
+
baseUrl: () => this.baseUrl(),
|
|
112
|
+
cardId: () => this.cardId ?? undefined,
|
|
113
|
+
getToken: () => this.getToken(),
|
|
114
|
+
nextSequence: () => ++this.sequence,
|
|
115
|
+
});
|
|
116
|
+
this.onOutboundMessageId = options?.onOutboundMessageId;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
private baseUrl() {
|
|
120
|
+
return this.domain === "lark" ? "https://open.larksuite.com" : "https://open.feishu.cn";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
private async getToken(): Promise<string> {
|
|
124
|
+
if (this.token && this.tokenExpiry > Date.now() + 60_000) return this.token!;
|
|
125
|
+
const res = await fetch(`${this.baseUrl()}/open-apis/auth/v3/tenant_access_token/internal`, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: { "Content-Type": "application/json" },
|
|
128
|
+
body: JSON.stringify({ app_id: this.appId, app_secret: this.appSecret }),
|
|
129
|
+
});
|
|
130
|
+
const j = (await res.json()) as CardKitResponse & { tenant_access_token?: string; expire?: number };
|
|
131
|
+
if (j.code !== 0 || !j.tenant_access_token) throw new Error(`token: ${j.msg || res.status}`);
|
|
132
|
+
this.token = j.tenant_access_token;
|
|
133
|
+
this.tokenExpiry = Date.now() + (j.expire ?? 7200) * 1000;
|
|
134
|
+
return this.token!;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async start(): Promise<void> {
|
|
138
|
+
if (this.closed || this.cardId || this.failed) return;
|
|
139
|
+
await withRetry(async () => {
|
|
140
|
+
const t = await this.getToken();
|
|
141
|
+
// 必须带停止按钮;禁止只建 markdown 导致无法中止
|
|
142
|
+
const card = buildCardKitCardJson({
|
|
143
|
+
status: "running",
|
|
144
|
+
body: "",
|
|
145
|
+
key: this.conversationKey,
|
|
146
|
+
runId: this.runId,
|
|
147
|
+
title: this.title,
|
|
148
|
+
note: this.note,
|
|
149
|
+
// 建卡时就留好清单位(此时清单多半还是空的,但后面要往里 PUT)
|
|
150
|
+
progress: this.progressEnabled ? this.progress.snapshot().body : undefined,
|
|
151
|
+
progressTitle: this.progress.snapshot().title,
|
|
152
|
+
progressCollapsed: this.progressCollapsed,
|
|
153
|
+
streaming: true,
|
|
154
|
+
printFrequencyMs: this.printFrequencyMs,
|
|
155
|
+
printStep: this.printStep,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const cr = await fetch(`${this.baseUrl()}/open-apis/cardkit/v1/cards`, {
|
|
159
|
+
method: "POST",
|
|
160
|
+
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
|
|
161
|
+
body: JSON.stringify({ type: "card_json", data: JSON.stringify(card) }),
|
|
162
|
+
});
|
|
163
|
+
const c = (await cr.json()) as CardKitResponse;
|
|
164
|
+
if (c.code !== 0 || !c.data?.card_id) {
|
|
165
|
+
throw Object.assign(new Error(`create_card: ${c.msg || c.code}`), { code: c.code });
|
|
166
|
+
}
|
|
167
|
+
this.cardId = c.data.card_id as string;
|
|
168
|
+
|
|
169
|
+
// 平铺(create)还是回复(reply):多条 reply 会被飞书折叠,见 CardKitTarget 说明
|
|
170
|
+
const isCreate = "chatId" in this.target;
|
|
171
|
+
const sendUrl = isCreate
|
|
172
|
+
? `${this.baseUrl()}/open-apis/im/v1/messages?receive_id_type=chat_id`
|
|
173
|
+
: `${this.baseUrl()}/open-apis/im/v1/messages/${(this.target as { replyToMessageId: string }).replyToMessageId}/reply`;
|
|
174
|
+
const sr = await fetch(sendUrl, {
|
|
175
|
+
method: "POST",
|
|
176
|
+
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
|
|
177
|
+
body: JSON.stringify({
|
|
178
|
+
...(isCreate ? { receive_id: (this.target as { chatId: string }).chatId } : {}),
|
|
179
|
+
msg_type: "interactive",
|
|
180
|
+
content: JSON.stringify({ type: "card", data: { card_id: this.cardId } }),
|
|
181
|
+
}),
|
|
182
|
+
});
|
|
183
|
+
const s = (await sr.json()) as CardKitResponse & { data?: { message_id?: string } };
|
|
184
|
+
if (s.code !== 0) {
|
|
185
|
+
throw Object.assign(new Error(`send_card: ${s.msg || s.code}`), { code: s.code });
|
|
186
|
+
}
|
|
187
|
+
const outboundId = s.data?.message_id;
|
|
188
|
+
if (outboundId) this.onOutboundMessageId?.(outboundId);
|
|
189
|
+
debugLog("feishu.cardkit.started", {
|
|
190
|
+
cardId: this.cardId,
|
|
191
|
+
messageId: outboundId,
|
|
192
|
+
mode: isCreate ? "create" : "reply",
|
|
193
|
+
printFrequencyMs: this.printFrequencyMs,
|
|
194
|
+
printStep: this.printStep,
|
|
195
|
+
});
|
|
196
|
+
}, { maxRetries: 2, label: "feishu.cardkit.start" });
|
|
197
|
+
|
|
198
|
+
// 如果在建卡期间本轮回复已结束,close() 会负责把卡收尾;这里无需再留下定时推送。
|
|
199
|
+
if (!this.closed && !this.interval) {
|
|
200
|
+
this.interval = setInterval(() => {
|
|
201
|
+
void this.tick();
|
|
202
|
+
}, this.pushIntervalMs);
|
|
203
|
+
// 不吊住进程退出:调用方忘了 close(例如单测里断言先失败)时,
|
|
204
|
+
// 定时器会让 node 永远不退出,表现为「测试卡住」而不是「测试失败」。
|
|
205
|
+
(this.interval as { unref?: () => void }).unref?.();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 收到用户消息后立刻创建唯一的一张「回复中」卡。
|
|
211
|
+
* 不等待首段正文,避免用户把较慢的 Pi 回复误认为卡住了。
|
|
212
|
+
*/
|
|
213
|
+
startImmediately(): Promise<void> {
|
|
214
|
+
if (this.closed || this.failed || this.cardId) return Promise.resolve();
|
|
215
|
+
if (this.startPromise) return this.startPromise;
|
|
216
|
+
|
|
217
|
+
this.startPromise = this.start()
|
|
218
|
+
.catch((e) => {
|
|
219
|
+
this.failed = true;
|
|
220
|
+
debugLog("feishu.cardkit.start_error", {
|
|
221
|
+
error: e instanceof Error ? e.message : String(e),
|
|
222
|
+
});
|
|
223
|
+
})
|
|
224
|
+
.finally(() => {
|
|
225
|
+
this.startPromise = null;
|
|
226
|
+
});
|
|
227
|
+
return this.startPromise;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** 同步攒字;建卡已在收到消息时提前触发,这里只保证未漏启动。 */
|
|
231
|
+
append(delta: string): void {
|
|
232
|
+
if (this.closed || this.failed || !delta) return;
|
|
233
|
+
this.fullText += delta;
|
|
234
|
+
void this.startImmediately();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
ensureFinal(text: string): void {
|
|
238
|
+
if (!text) return;
|
|
239
|
+
if (!this.fullText.trim() || text.length >= this.fullText.length) {
|
|
240
|
+
this.fullText = text;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* 设置过程清单的取数函数(转发给 ProgressChannel)。
|
|
245
|
+
*
|
|
246
|
+
* 用回调而不是一次性字符串:timeout / action 档的「已执行 Ns」必须随时间长,
|
|
247
|
+
* 而 Pi 在单个工具运行期间不发任何事件,只有 tick 能驱动刷新。
|
|
248
|
+
* 回调方已把耗时量化到 5 秒粒度,因此文本不会每个 tick 都变。
|
|
249
|
+
*/
|
|
250
|
+
setProgressSource(source: (() => { title: string; body: string }) | undefined): void {
|
|
251
|
+
this.progress.setSource(source);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private async tick() {
|
|
255
|
+
if (!this.cardId || this.closed) return;
|
|
256
|
+
await this.putContent(this.fullText);
|
|
257
|
+
if (this.progressEnabled) await this.progress.tick();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 写入正文元件(全量文本);sequence 与进度通道共享同一个递增计数器 */
|
|
261
|
+
private async putContent(raw: string) {
|
|
262
|
+
// 本地图片语法必须先降级:卡片只认 image_key,传本地路径会让整张卡更新被拒(200570)
|
|
263
|
+
const text = stripLocalImageMarkdown(raw);
|
|
264
|
+
if (!this.cardId || text === this.lastSent) return;
|
|
265
|
+
try {
|
|
266
|
+
const t = await this.getToken();
|
|
267
|
+
const seq = ++this.sequence;
|
|
268
|
+
const res = await fetch(
|
|
269
|
+
`${this.baseUrl()}/open-apis/cardkit/v1/cards/${this.cardId}/elements/content/content`,
|
|
270
|
+
{
|
|
271
|
+
method: "PUT",
|
|
272
|
+
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
|
|
273
|
+
body: JSON.stringify({
|
|
274
|
+
content: text,
|
|
275
|
+
sequence: seq,
|
|
276
|
+
uuid: `${this.cardId}_content_${seq}`,
|
|
277
|
+
}),
|
|
278
|
+
},
|
|
279
|
+
);
|
|
280
|
+
if (!res.ok) {
|
|
281
|
+
debugLog("feishu.cardkit.update_error", {
|
|
282
|
+
seq,
|
|
283
|
+
status: res.status,
|
|
284
|
+
body: (await res.text()).slice(0, 200),
|
|
285
|
+
});
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
this.lastSent = text;
|
|
289
|
+
} catch (e) {
|
|
290
|
+
debugLog("feishu.cardkit.update_throw", {
|
|
291
|
+
error: e instanceof Error ? e.message : String(e),
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* 结束流式:
|
|
298
|
+
* 1) 推送最终正文
|
|
299
|
+
* 2) 关闭 streaming_mode(只做一次)
|
|
300
|
+
* 3) 全量更新卡片(header 改为「回复」/绿,避免一直停在「回复中」)
|
|
301
|
+
*
|
|
302
|
+
* 可重复调用:暂停(paused)之后这张卡还要刷成终态,那一步走 updateFinal。
|
|
303
|
+
*/
|
|
304
|
+
async close(
|
|
305
|
+
finalText?: string,
|
|
306
|
+
finalStatus: CardKitCardStatus = "done",
|
|
307
|
+
note?: string,
|
|
308
|
+
): Promise<void> {
|
|
309
|
+
if (finalText) this.ensureFinal(finalText);
|
|
310
|
+
if (this.interval) {
|
|
311
|
+
clearInterval(this.interval);
|
|
312
|
+
this.interval = null;
|
|
313
|
+
}
|
|
314
|
+
if (this.startPromise) await this.startPromise.catch(() => {});
|
|
315
|
+
|
|
316
|
+
const firstClose = !this.closed;
|
|
317
|
+
this.closed = true;
|
|
318
|
+
|
|
319
|
+
if (this.failed || !this.cardId) {
|
|
320
|
+
if (this.fullText.trim()) {
|
|
321
|
+
debugLog("feishu.cardkit.fallback_text", { length: this.fullText.length });
|
|
322
|
+
await this.fallbackReply(this.fullText);
|
|
323
|
+
}
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
try {
|
|
328
|
+
if (firstClose) {
|
|
329
|
+
await this.putContent(this.fullText);
|
|
330
|
+
// 清单必须赶在关流式之前写:关掉 streaming_mode 后这条接口就不能再用了
|
|
331
|
+
if (this.progressEnabled) await this.progress.flush();
|
|
332
|
+
// 给客户端一点时间把剩余字符打完
|
|
333
|
+
await sleep(Math.max(200, this.printFrequencyMs * 4));
|
|
334
|
+
await this.stopStreaming();
|
|
335
|
+
}
|
|
336
|
+
// putFinalCard 失败意味着卡片会永远停在「回复中」,补一条只带清单的消息
|
|
337
|
+
if (!(await this.putFinalCard(finalStatus, note))) {
|
|
338
|
+
await this.sendOversizeFallback(finalStatus);
|
|
339
|
+
}
|
|
340
|
+
} catch (e) {
|
|
341
|
+
debugLog("feishu.cardkit.close_error", {
|
|
342
|
+
error: e instanceof Error ? e.message : String(e),
|
|
343
|
+
});
|
|
344
|
+
if (this.fullText.trim()) await this.fallbackReply(this.fullText);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* 全量更新卡片(流式已关也能再刷)。
|
|
350
|
+
* 暂停卡要能翻成「已选择 / 已停止」,否则会永远停在「等你选择」。
|
|
351
|
+
*/
|
|
352
|
+
async updateFinal(finalStatus: CardKitCardStatus, note?: string): Promise<void> {
|
|
353
|
+
try {
|
|
354
|
+
if (!(await this.putFinalCard(finalStatus, note))) {
|
|
355
|
+
await this.sendOversizeFallback(finalStatus);
|
|
356
|
+
}
|
|
357
|
+
} catch (e) {
|
|
358
|
+
debugLog("feishu.cardkit.full_update_throw", {
|
|
359
|
+
status: finalStatus,
|
|
360
|
+
error: e instanceof Error ? e.message : String(e),
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 关闭 streaming_mode(只做一次) */
|
|
366
|
+
private async stopStreaming(): Promise<void> {
|
|
367
|
+
const t = await withRetry(() => this.getToken(), {
|
|
368
|
+
maxRetries: 3,
|
|
369
|
+
label: "feishu.cardkit.close_token",
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// 收尾这一步必须重试:CardKit 卡的 header 还是「回复中」,
|
|
373
|
+
// 一次 fetch failed 就会让这张卡永远停在「回复中」,只能靠人手动忽略。
|
|
374
|
+
const settingsRes = await withRetry(() =>
|
|
375
|
+
fetch(`${this.baseUrl()}/open-apis/cardkit/v1/cards/${this.cardId}/settings`, {
|
|
376
|
+
method: "PATCH",
|
|
377
|
+
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
|
|
378
|
+
body: JSON.stringify({
|
|
379
|
+
settings: JSON.stringify({
|
|
380
|
+
config: {
|
|
381
|
+
streaming_mode: false,
|
|
382
|
+
summary: { content: (this.fullText.slice(0, 50) || "Pi").replace(/\s+/g, " ") },
|
|
383
|
+
},
|
|
384
|
+
}),
|
|
385
|
+
sequence: ++this.sequence,
|
|
386
|
+
uuid: `c_${this.cardId}_${this.sequence}`,
|
|
387
|
+
}),
|
|
388
|
+
}),
|
|
389
|
+
{ maxRetries: 3, label: "feishu.cardkit.close_settings" },
|
|
390
|
+
);
|
|
391
|
+
if (!settingsRes.ok) {
|
|
392
|
+
debugLog("feishu.cardkit.settings_error", {
|
|
393
|
+
status: settingsRes.status,
|
|
394
|
+
body: (await settingsRes.text()).slice(0, 300),
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 全量更新卡片正文与 header(不做流式收尾,可重复调用)。
|
|
401
|
+
* 返回是否更新成功:失败时调用方要跑兜底流程(整卡超 30KB 时卡片会一直停在「回复中」)。
|
|
402
|
+
*/
|
|
403
|
+
private async putFinalCard(finalStatus: CardKitCardStatus, note?: string): Promise<boolean> {
|
|
404
|
+
if (!this.cardId) return false;
|
|
405
|
+
const t = await withRetry(() => this.getToken(), {
|
|
406
|
+
maxRetries: 3,
|
|
407
|
+
label: "feishu.cardkit.close_token",
|
|
408
|
+
});
|
|
409
|
+
const finalCard = buildCardKitCardJson({
|
|
410
|
+
status: finalStatus,
|
|
411
|
+
body: stripLocalImageMarkdown(this.fullText),
|
|
412
|
+
note,
|
|
413
|
+
key: this.conversationKey,
|
|
414
|
+
runId: this.runId,
|
|
415
|
+
title: this.title,
|
|
416
|
+
streaming: false,
|
|
417
|
+
// 终态卡保留定格后的清单,让用户能回看这一轮干了什么
|
|
418
|
+
progress: this.progressEnabled ? this.progress.snapshot().body : undefined,
|
|
419
|
+
progressTitle: this.progress.snapshot().title,
|
|
420
|
+
progressCollapsed: this.progressCollapsed,
|
|
421
|
+
});
|
|
422
|
+
const updateRes = await withRetry(() =>
|
|
423
|
+
fetch(`${this.baseUrl()}/open-apis/cardkit/v1/cards/${this.cardId}`, {
|
|
424
|
+
method: "PUT",
|
|
425
|
+
headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" },
|
|
426
|
+
body: JSON.stringify({
|
|
427
|
+
card: {
|
|
428
|
+
type: "card_json",
|
|
429
|
+
data: JSON.stringify(finalCard),
|
|
430
|
+
},
|
|
431
|
+
sequence: ++this.sequence,
|
|
432
|
+
uuid: `u_${this.cardId}_${this.sequence}`,
|
|
433
|
+
}),
|
|
434
|
+
}),
|
|
435
|
+
{ maxRetries: 3, label: "feishu.cardkit.close_update" },
|
|
436
|
+
);
|
|
437
|
+
const updateJson = (await updateRes.json().catch(() => ({}))) as CardKitResponse;
|
|
438
|
+
if (!updateRes.ok || (updateJson.code != null && updateJson.code !== 0)) {
|
|
439
|
+
debugLog("feishu.cardkit.full_update_error", {
|
|
440
|
+
status: updateRes.status,
|
|
441
|
+
code: updateJson.code,
|
|
442
|
+
msg: updateJson.msg,
|
|
443
|
+
bodyBytes: byteLength(this.fullText),
|
|
444
|
+
progressBytes: byteLength(this.progress.snapshot().body),
|
|
445
|
+
});
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
debugLog("feishu.cardkit.closed", {
|
|
450
|
+
cardId: this.cardId,
|
|
451
|
+
length: this.fullText.length,
|
|
452
|
+
finalStatus,
|
|
453
|
+
headerTitle: (finalCard as any).header?.title?.content,
|
|
454
|
+
hasStopButton: JSON.stringify(finalCard).includes("停止"),
|
|
455
|
+
});
|
|
456
|
+
return true;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* 整卡更新失败时的兜底:交给 oversize-progress-card 新发一条只带清单的消息。
|
|
461
|
+
*
|
|
462
|
+
* 背景:正文本就是撑爆整卡(≤ 30KB)的主因,而正文用户已经从流式输出里看完了,
|
|
463
|
+
* 真正丢掉的是「这轮结束了」和清单 —— 用一条体积可控的新消息补回来。
|
|
464
|
+
*/
|
|
465
|
+
private async sendOversizeFallback(finalStatus: CardKitCardStatus): Promise<void> {
|
|
466
|
+
if (!this.progressEnabled) return;
|
|
467
|
+
await sendOversizeProgressCard({
|
|
468
|
+
baseUrl: this.baseUrl(),
|
|
469
|
+
getToken: () => this.getToken(),
|
|
470
|
+
target: this.target,
|
|
471
|
+
conversationKey: this.conversationKey,
|
|
472
|
+
runId: this.runId,
|
|
473
|
+
title: this.title,
|
|
474
|
+
finalStatus,
|
|
475
|
+
progress: this.progress.snapshot().body,
|
|
476
|
+
onOutboundMessageId: this.onOutboundMessageId,
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function sleep(ms: number) {
|
|
482
|
+
return new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
483
|
+
}
|