@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,141 @@
1
+ import http from "node:http";
2
+ import { debugLog } from "./debug.ts";
3
+ import type { FeishuCardAction, FeishuConfig } from "./types.ts";
4
+
5
+ export class FeishuCardActionWebhook {
6
+ private server: http.Server | undefined;
7
+ private readonly host: string;
8
+ private readonly port: number;
9
+ private readonly path: string;
10
+ private readonly config: FeishuConfig;
11
+ private readonly onCardAction: (action: FeishuCardAction) => Promise<object | undefined | void>;
12
+
13
+ constructor(
14
+ config: FeishuConfig,
15
+ onCardAction: (action: FeishuCardAction) => Promise<object | undefined | void>,
16
+ ) {
17
+ this.config = config;
18
+ this.onCardAction = onCardAction;
19
+ this.host = config.cardActionWebhookHost || "0.0.0.0";
20
+ this.port = config.cardActionWebhookPort || 3001;
21
+ this.path = config.cardActionWebhookPath || "/webhook/card";
22
+ }
23
+
24
+ isRunning() {
25
+ return Boolean(this.server);
26
+ }
27
+
28
+ getEndpointLabel() {
29
+ return `${this.host}:${this.port}${this.path}`;
30
+ }
31
+
32
+ async start() {
33
+ if (this.server) return;
34
+ const lark = await import("@larksuiteoapi/node-sdk");
35
+ const dispatcher = new lark.CardActionHandler({}, async (data: any) => {
36
+ let action;
37
+ try {
38
+ action = normalizeCardAction(data);
39
+ } catch (normalizeError) {
40
+ debugLog("feishu.card.webhook.normalize_failed", {
41
+ error: normalizeError instanceof Error ? normalizeError.message : String(normalizeError),
42
+ keys: Object.keys(data || {}),
43
+ });
44
+ return undefined;
45
+ }
46
+ debugLog("feishu.card.webhook.action", {
47
+ messageId: action.messageId,
48
+ hasValue: Boolean(action.value),
49
+ value: action.value,
50
+ hasFormValue: Boolean(action.formValue),
51
+ });
52
+ try {
53
+ const result = await this.onCardAction(action);
54
+ // Feishu/Lark requires the webhook response body to use the wrapped format:
55
+ // { "card": { "type": "raw", "data": { ... card JSON ... } } }
56
+ // The Lark SDK's adaptDefault sends the return value as-is, so we wrap here.
57
+ if (result) {
58
+ return { card: { type: "raw", data: result } };
59
+ }
60
+ return result;
61
+ } catch (handlerError) {
62
+ debugLog("feishu.card.webhook.handler_failed", {
63
+ messageId: action.messageId,
64
+ error: handlerError instanceof Error ? handlerError.message : String(handlerError),
65
+ });
66
+ return undefined;
67
+ }
68
+ });
69
+
70
+ this.server = http.createServer();
71
+ const rawHandler = lark.adaptDefault(this.path, dispatcher);
72
+ this.server.on("request", (req, res) => {
73
+ res.setHeader("Content-Type", "application/json");
74
+ rawHandler(req, res);
75
+ });
76
+
77
+ await new Promise<void>((resolve, reject) => {
78
+ const server = this.server!;
79
+ const cleanup = () => {
80
+ server.off("error", onError);
81
+ server.off("listening", onListening);
82
+ };
83
+ const onError = (error: Error) => {
84
+ cleanup();
85
+ reject(error);
86
+ };
87
+ const onListening = () => {
88
+ cleanup();
89
+ resolve();
90
+ };
91
+ server.once("error", onError);
92
+ server.once("listening", onListening);
93
+ server.listen(this.port, this.host);
94
+ });
95
+
96
+ debugLog("feishu.card.webhook.started", {
97
+ host: this.host,
98
+ port: this.port,
99
+ path: this.path,
100
+ });
101
+ }
102
+
103
+ async stop() {
104
+ if (!this.server) return;
105
+ const server = this.server;
106
+ this.server = undefined;
107
+ await new Promise<void>((resolve) => {
108
+ try {
109
+ server.close(() => resolve());
110
+ } catch {
111
+ resolve();
112
+ }
113
+ });
114
+ }
115
+ }
116
+
117
+ function normalizeCardAction(data: any): FeishuCardAction {
118
+ // After Lark SDK's RequestHandle.parse() for v2 schema events,
119
+ // the data is flattened and open_message_id lives under data.context.
120
+ // Check both nested and flat locations to stay compatible with both
121
+ // raw webhook payloads and SDK-parsed structures.
122
+ const messageId = data?.context?.open_message_id || data?.open_message_id;
123
+ const operatorOpenId = data?.operator?.open_id || data?.open_id;
124
+ if (typeof messageId !== "string" || !messageId || typeof operatorOpenId !== "string" || !operatorOpenId) {
125
+ throw new Error("invalid card action payload");
126
+ }
127
+ const chatId =
128
+ typeof data?.context?.open_chat_id === "string"
129
+ ? data.context.open_chat_id
130
+ : typeof data?.open_chat_id === "string"
131
+ ? data.open_chat_id
132
+ : undefined;
133
+ return {
134
+ messageId,
135
+ chatId,
136
+ operatorOpenId,
137
+ token: typeof data?.token === "string" ? data.token : undefined,
138
+ value: data?.action?.value,
139
+ formValue: data?.action?.form_value,
140
+ };
141
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * 飞书交互卡片回调的统一处理(/model、/thinking、/resume、停止按钮、复制按钮)。
3
+ * 只依赖 ConversationRuntime 接口与飞书公共层,各 Runtime 适配器直接复用。
4
+ */
5
+ import { buildCardKitCardJson } from "./card-builder.ts";
6
+ import { answerAsk, askInputName, buildAskCard, type AskSettleStatus } from "./ask.ts";
7
+ import {
8
+ buildDeliveryCard,
9
+ buildModelCard,
10
+ buildResumeCard,
11
+ buildThinkingCard,
12
+ parseDeliveryActionValue,
13
+ parseModelActionValue,
14
+ parseResumePageActionValue,
15
+ parseResumeSelectActionValue,
16
+ parseThinkingActionValue,
17
+ } from "./cards.ts";
18
+ import { debugLog } from "./debug.ts";
19
+ import { loadConfig } from "./config.ts";
20
+ import { setRuntimeConfig } from "./runtime-config.ts";
21
+ import { parseStopTaskActionValue } from "./reply-card.ts";
22
+ import type { ConversationRuntime } from "./runtime.ts";
23
+ import type { FeishuTransport } from "./transport.ts";
24
+ import type { FeishuCardAction } from "./types.ts";
25
+
26
+ export function createCardActionHandler(
27
+ conversations: ConversationRuntime,
28
+ getTransport: () => FeishuTransport | undefined,
29
+ ) {
30
+ return async (action: FeishuCardAction) => {
31
+ const transport = getTransport();
32
+
33
+ // feishu_ask 选择题:记录答案并原地刷新同一张卡
34
+ const askAnswer = parseAskAnswerActionValue(action.value);
35
+ if (askAnswer) {
36
+ const result = answerAsk(askAnswer.askId, askAnswer.questionIndex, askAnswer.label);
37
+ if (!result.found || !result.record) return;
38
+ // 迟到的点击:这条提问已经结算(答完 / 超时 / 取消),本次点击不生效。
39
+ // 必须刷卡片 + 回一句文本,否则用户看到的是「点了没反应」的僵尸卡片。
40
+ if (result.settled) {
41
+ debugLog("feishu.ask.click_after_settled", {
42
+ askId: askAnswer.askId,
43
+ questionIndex: askAnswer.questionIndex,
44
+ label: askAnswer.label,
45
+ status: result.settledStatus,
46
+ });
47
+ await transport?.replyPlainText(action.messageId, settledAskNotice(result.settledStatus));
48
+ return buildAskCard(
49
+ result.record.askId,
50
+ result.record.questions,
51
+ result.record.answers,
52
+ settledCardStatus(result.settledStatus),
53
+ );
54
+ }
55
+ debugLog("feishu.ask.clicked", {
56
+ askId: askAnswer.askId,
57
+ questionIndex: askAnswer.questionIndex,
58
+ label: askAnswer.label,
59
+ allAnswered: result.allAnswered,
60
+ });
61
+ return buildAskCard(
62
+ askAnswer.askId,
63
+ result.record.questions,
64
+ result.record.answers,
65
+ result.allAnswered ? "done" : "pending",
66
+ );
67
+ }
68
+
69
+ // feishu_ask 自由输入:表单容器提交时,输入值在 action.formValue 里(key = 输入框 name)
70
+ const askInput = parseAskInputActionValue(action.value);
71
+ if (askInput) {
72
+ const text = readFormInput(action.formValue, askInputName(askInput.questionIndex));
73
+ const result = answerAsk(askInput.askId, askInput.questionIndex, text, true);
74
+ if (!result.found || !result.record) return;
75
+ // 同上:已结算的提问再提交,给明确提示而不是静默丢弃
76
+ if (result.settled) {
77
+ debugLog("feishu.ask.input_after_settled", {
78
+ askId: askInput.askId,
79
+ questionIndex: askInput.questionIndex,
80
+ status: result.settledStatus,
81
+ });
82
+ await transport?.replyPlainText(action.messageId, settledAskNotice(result.settledStatus));
83
+ return buildAskCard(
84
+ result.record.askId,
85
+ result.record.questions,
86
+ result.record.answers,
87
+ settledCardStatus(result.settledStatus),
88
+ );
89
+ }
90
+ debugLog("feishu.ask.input_submitted", {
91
+ askId: askInput.askId,
92
+ questionIndex: askInput.questionIndex,
93
+ textLength: text.trim().length,
94
+ accepted: result.accepted,
95
+ allAnswered: result.allAnswered,
96
+ });
97
+ return buildAskCard(
98
+ askInput.askId,
99
+ result.record.questions,
100
+ result.record.answers,
101
+ result.allAnswered ? "done" : "pending",
102
+ );
103
+ }
104
+
105
+ const copy = parseCopyMarkdownActionValue(action.value);
106
+ if (copy) {
107
+ const source = transport?.getMarkdownCopySource(copy.copySourceId);
108
+ await transport?.replyPlainText(action.messageId, source || "MD 原文已过期,请重新生成卡片。");
109
+ return;
110
+ }
111
+
112
+ const stopTask = parseStopTaskActionValue(action.value);
113
+ if (stopTask) {
114
+ debugLog("feishu.card.stop_requested", {
115
+ key: stopTask.key,
116
+ runId: stopTask.runId,
117
+ cardMessageId: action.messageId,
118
+ chatId: action.chatId,
119
+ });
120
+ // 停止时由 ReplyCard.stopImmediately 更新同一张卡;回调不再另发文本
121
+ const result = await conversations.stopConversation(stopTask.key, async () => undefined, stopTask.runId);
122
+ const status = result.status === "stopped"
123
+ ? "stopped"
124
+ : result.status === "failed"
125
+ ? "failed"
126
+ : "inactive";
127
+ debugLog("feishu.card.stop_final_update_done", {
128
+ key: stopTask.key,
129
+ runId: stopTask.runId,
130
+ cardMessageId: action.messageId,
131
+ result: result.status,
132
+ });
133
+ // CardKit 流式卡是 schema 2.0;回调必须返回 2.0,否则会 200830/200671
134
+ // body 优先用 cardkit.close() 已写入的累计文本,避免覆盖已输出内容
135
+ // progress 同理:不带的话,回调返回的卡会把刚看到的执行清单刷没
136
+ return buildCardKitCardJson({
137
+ status,
138
+ body: "body" in result ? result.body : result.message || "已停止",
139
+ key: stopTask.key,
140
+ runId: stopTask.runId,
141
+ streaming: false,
142
+ progress: "progress" in result ? result.progress : undefined,
143
+ });
144
+ }
145
+
146
+ const resumePage = parseResumePageActionValue(action.value);
147
+ if (resumePage) {
148
+ const page = await conversations.listResumeSessions(resumePage.key, resumePage.scope, resumePage.page);
149
+ return buildResumeCard(page);
150
+ }
151
+
152
+ const resumeSelect = parseResumeSelectActionValue(action.value);
153
+ if (resumeSelect) {
154
+ await conversations.resumeConversation(resumeSelect.key, resumeSelect.sessionPath, async (reply) => {
155
+ await transport?.replyText(action.messageId, reply);
156
+ });
157
+ const page = await conversations.listResumeSessions(resumeSelect.key, resumeSelect.scope, resumeSelect.page);
158
+ return buildResumeCard(page);
159
+ }
160
+
161
+ const selectedThinking = parseThinkingActionValue(action.value);
162
+ if (selectedThinking) {
163
+ await conversations.selectThinkingLevel(selectedThinking.key, selectedThinking.level, async (reply) => {
164
+ await transport?.replyText(action.messageId, reply);
165
+ });
166
+ const [currentModel, thinking] = await Promise.all([
167
+ conversations.getSelectedModel(selectedThinking.key),
168
+ conversations.getThinkingStatus(selectedThinking.key),
169
+ ]);
170
+ return buildThinkingCard(selectedThinking.key, currentModel, thinking);
171
+ }
172
+
173
+ const selectedDelivery = parseDeliveryActionValue(action.value);
174
+ if (selectedDelivery) {
175
+ const set = setRuntimeConfig("messageDelivery", selectedDelivery.mode);
176
+ if (set.ok === false) {
177
+ await transport?.replyText(action.messageId, `❌ ${set.error}`);
178
+ } else {
179
+ debugLog("feishu.delivery.changed", { mode: selectedDelivery.mode });
180
+ }
181
+ // 原地刷新同一张卡片,让当前值立刻可见
182
+ return buildDeliveryCard(loadConfig()?.messageDelivery);
183
+ }
184
+
185
+ const selected = parseModelActionValue(action.value);
186
+ if (!selected) return;
187
+ await conversations.selectModel(selected.key, selected.provider, selected.modelId, async (reply) => {
188
+ await transport?.replyText(action.messageId, reply);
189
+ });
190
+ const models = await conversations.getAvailableModels();
191
+ const currentModel = await conversations.getSelectedModel(selected.key);
192
+ return buildModelCard(selected.key, models, currentModel);
193
+ };
194
+ }
195
+
196
+ /** 已结算提问被再点时的卡片状态:答完保持绿,超时 / 已结束走灰 */
197
+ function settledCardStatus(status: AskSettleStatus | undefined): "done" | "timeout" | "canceled" {
198
+ if (status === "done") return "done";
199
+ return status === "canceled" ? "canceled" : "timeout";
200
+ }
201
+
202
+ /** 已结算提问被再点时的文本提示:卡片刷新之外再交代一句,让用户不用猜 */
203
+ function settledAskNotice(status: AskSettleStatus | undefined): string {
204
+ if (status === "done") return "✅ 这个问题已经答过了,本次点击未生效。";
205
+ if (status === "timeout") return "⌛ 这个提问已超时,本次点击不会生效。需要的话让 Agent 重新问一次。";
206
+ return "⚠️ 这个提问已结束,本次点击未生效。需要的话让 Agent 重新问一次。";
207
+ }
208
+
209
+ function parseAskAnswerActionValue(value: unknown): { askId: string; questionIndex: number; label: string } | undefined {
210
+ if (!value || typeof value !== "object") return undefined;
211
+ const raw = value as any;
212
+ if (raw.action !== "pi_feishu_ask_answer") return undefined;
213
+ if (typeof raw.askId !== "string" || !raw.askId) return undefined;
214
+ if (!Number.isInteger(raw.questionIndex)) return undefined;
215
+ if (typeof raw.label !== "string" || !raw.label) return undefined;
216
+ return { askId: raw.askId, questionIndex: raw.questionIndex, label: raw.label };
217
+ }
218
+
219
+ function parseAskInputActionValue(value: unknown): { askId: string; questionIndex: number } | undefined {
220
+ if (!value || typeof value !== "object") return undefined;
221
+ const raw = value as any;
222
+ if (raw.action !== "pi_feishu_ask_input") return undefined;
223
+ if (typeof raw.askId !== "string" || !raw.askId) return undefined;
224
+ if (!Number.isInteger(raw.questionIndex)) return undefined;
225
+ return { askId: raw.askId, questionIndex: raw.questionIndex };
226
+ }
227
+
228
+ /** 取表单容器提交的输入框文本;缺失或非字符串一律当空串 */
229
+ function readFormInput(formValue: unknown, name: string): string {
230
+ if (!formValue || typeof formValue !== "object") return "";
231
+ const value = (formValue as Record<string, unknown>)[name];
232
+ return typeof value === "string" ? value : "";
233
+ }
234
+
235
+ function parseCopyMarkdownActionValue(value: unknown): { copySourceId: string } | undefined {
236
+ if (!value || typeof value !== "object") return undefined;
237
+ const raw = value as any;
238
+ if (raw.action !== "pi_feishu_copy_markdown") return undefined;
239
+ if (typeof raw.copySourceId !== "string" || !raw.copySourceId) return undefined;
240
+ return { copySourceId: raw.copySourceId };
241
+ }
@@ -0,0 +1,277 @@
1
+ /** 单卡 UI 纯函数:构建飞书 interactive / CardKit 卡片 JSON(无 IO) */
2
+ /**
3
+ * 卡片状态。
4
+ * - running:正在流式回复
5
+ * - paused:已定格、等用户在选择题卡片上作答(feishu_ask 等待期间)
6
+ * - answered:用户已作答,这张卡已「翻页」,后续内容在新的一张卡上
7
+ * - done/failed/stopped/inactive:终态
8
+ */
9
+ export type ReplyCardStatus = "running" | "paused" | "answered" | "done" | "failed" | "stopped" | "inactive";
10
+
11
+ /** 只能作为终态写入的状态(paused 是中间态,不能被 finish 成 paused) */
12
+ export type ReplyCardFinalStatus = "done" | "failed" | "stopped";
13
+
14
+ export const STOP_ACTION = "pi_feishu_stop_task";
15
+ const MAX_NOTE_CHARS = 96;
16
+ const WAITING_TEXT = "正在回复…";
17
+ const PAUSED_TEXT = "(已暂停,等你在选择题卡片上作答)";
18
+
19
+ /** CardKit JSON 2.0 停止按钮(直接放在 elements 里,不用 1.0 的 action 模块) */
20
+ export function buildStopButton(key: string, runId?: string) {
21
+ return {
22
+ tag: "button",
23
+ type: "danger",
24
+ text: { tag: "plain_text", content: "停止" },
25
+ // 兼容旧 value 回调 + JSON 2.0 behaviors.callback
26
+ value: { action: STOP_ACTION, key, runId },
27
+ behaviors: [
28
+ {
29
+ type: "callback",
30
+ value: { action: STOP_ACTION, key, runId },
31
+ },
32
+ ],
33
+ };
34
+ }
35
+
36
+ /**
37
+ * CardKit schema 2.0 卡片(流式/全量更新共用)。
38
+ * running 必须带停止按钮,避免只有 markdown 无法中止。
39
+ */
40
+ export function buildCardKitCardJson(input: {
41
+ status: ReplyCardStatus;
42
+ body?: string;
43
+ key?: string;
44
+ runId?: string;
45
+ note?: string;
46
+ /**
47
+ * 工具执行过程清单(element_id: progress)。
48
+ * - `undefined` = 不插入该元件(progressMode=off,零开销)
49
+ * - `""` = 插入空元件(清单还没内容,但后面要 PUT 上去,元件必须先存在)
50
+ */
51
+ progress?: string;
52
+ /**
53
+ * 折叠面板标题(收起时唯一能看到的一行,通常是「正在执行 bash · npm test」)。
54
+ * 仅在 progressCollapsed 为 true 时生效。
55
+ */
56
+ progressTitle?: string;
57
+ /**
58
+ * 是否把清单收进折叠面板(默认 true)。
59
+ * steps 档清单很长,必须收起;action / timeout 档本来就一行,展开更直接。
60
+ */
61
+ progressCollapsed?: boolean;
62
+ /** 覆盖默认标题;续段用「回复(接上条)」交代上下文 */
63
+ title?: string;
64
+ streaming?: boolean;
65
+ printFrequencyMs?: number;
66
+ printStep?: number;
67
+ }) {
68
+ const running = input.status === "running";
69
+ // 暂停等选择时必须保留停止按钮:否则用户只能干等(选择题不自动超时),无法中止这一轮
70
+ const showStop = running || input.status === "paused";
71
+ const body = (input.body || "").trim();
72
+ const note = input.note ? normalizeNote(input.note) : undefined;
73
+ // 清单元件必须排在正文之前:CardKit 只支持按 element_id 更新,元件不存在就 PUT 不上去
74
+ const progressMarkdown = input.progress === undefined
75
+ ? undefined
76
+ : { tag: "markdown", content: input.progress.trim() || " ", element_id: "progress" };
77
+ // 清单默认收进折叠面板:50 行清单直接铺开会把对话淹没。
78
+ // 内层 markdown 仍叫 progress,所以推送内容的 PUT 路径不受影响。
79
+ const progressElement = progressMarkdown === undefined
80
+ ? undefined
81
+ : input.progressCollapsed === false
82
+ ? progressMarkdown
83
+ : {
84
+ tag: "collapsible_panel",
85
+ element_id: "progress_panel",
86
+ // 默认收起;用户自己展开过就保持,不强制改回去
87
+ expanded: false,
88
+ header: {
89
+ title: { tag: "plain_text", content: input.progressTitle || "执行过程" },
90
+ icon_position: "right",
91
+ icon_expanded_angle: -180,
92
+ },
93
+ elements: [progressMarkdown],
94
+ };
95
+ const elements: object[] = [];
96
+
97
+ if (running || input.status === "paused") {
98
+ const parts: string[] = [];
99
+ if (note) parts.push(note);
100
+ parts.push(body || (running ? WAITING_TEXT : PAUSED_TEXT));
101
+ if (progressElement) elements.push(progressElement);
102
+ elements.push({
103
+ tag: "markdown",
104
+ content: parts.join("\n\n"),
105
+ element_id: "content",
106
+ });
107
+ if (showStop && input.key) {
108
+ elements.push(buildStopButton(input.key, input.runId));
109
+ }
110
+ } else if (input.status === "done") {
111
+ if (progressElement) elements.push(progressElement);
112
+ elements.push({
113
+ tag: "markdown",
114
+ content: body || " ",
115
+ element_id: "content",
116
+ });
117
+ } else {
118
+ const parts: string[] = [];
119
+ if (note) parts.push(note);
120
+ if (body) parts.push(body);
121
+ if (progressElement) elements.push(progressElement);
122
+ elements.push({
123
+ tag: "markdown",
124
+ content: parts.join("\n\n") || " ",
125
+ element_id: "content",
126
+ });
127
+ }
128
+
129
+ const config: Record<string, unknown> = {
130
+ wide_screen_mode: true,
131
+ update_multi: true,
132
+ streaming_mode: Boolean(input.streaming && running),
133
+ };
134
+ if (input.streaming && running) {
135
+ config.streaming_config = {
136
+ print_frequency_ms: { default: input.printFrequencyMs ?? 50 },
137
+ print_step: { default: input.printStep ?? 1 },
138
+ };
139
+ }
140
+
141
+ return {
142
+ schema: "2.0",
143
+ config,
144
+ header: {
145
+ template: headerTemplate(input.status),
146
+ title: { tag: "plain_text", content: input.title || titleForStatus(input.status) },
147
+ },
148
+ body: { elements },
149
+ };
150
+ }
151
+
152
+ /**
153
+ * 普通 interactive 消息卡片(非 CardKit 实体):
154
+ * - running: 标题「回复中」+ 正文 + [停止]
155
+ * - done: 标题「回复」+ 最终正文
156
+ * - stopped/failed: 标题 + 说明
157
+ */
158
+ export function buildReplyCard(input: {
159
+ key: string;
160
+ status: ReplyCardStatus;
161
+ note?: string;
162
+ body?: string;
163
+ runId?: string;
164
+ title?: string;
165
+ }) {
166
+ const running = input.status === "running";
167
+ const showStop = running || input.status === "paused";
168
+ const body = (input.body || "").trim();
169
+ const note = input.note ? normalizeNote(input.note) : undefined;
170
+ const elements: object[] = [];
171
+
172
+ if (running || input.status === "paused") {
173
+ if (note) {
174
+ elements.push({
175
+ tag: "div",
176
+ text: { tag: "lark_md", content: note },
177
+ });
178
+ }
179
+ elements.push({
180
+ tag: "div",
181
+ text: { tag: "lark_md", content: body || (running ? WAITING_TEXT : PAUSED_TEXT) },
182
+ });
183
+ // 1.0 interactive 仍可用 action 模块;同时附带 2.0 button 以兼容
184
+ if (showStop) {
185
+ elements.push({
186
+ tag: "action",
187
+ actions: [
188
+ {
189
+ tag: "button",
190
+ text: { tag: "plain_text", content: "停止" },
191
+ type: "danger",
192
+ value: { action: STOP_ACTION, key: input.key, runId: input.runId },
193
+ },
194
+ ],
195
+ });
196
+ }
197
+ } else if (input.status === "done") {
198
+ elements.push({
199
+ tag: "div",
200
+ text: { tag: "lark_md", content: body || " " },
201
+ });
202
+ } else {
203
+ if (note) {
204
+ elements.push({
205
+ tag: "div",
206
+ text: { tag: "lark_md", content: note },
207
+ });
208
+ }
209
+ if (body) {
210
+ if (elements.length) elements.push({ tag: "hr" });
211
+ elements.push({
212
+ tag: "div",
213
+ text: { tag: "lark_md", content: body },
214
+ });
215
+ }
216
+ if (!elements.length) {
217
+ elements.push({
218
+ tag: "div",
219
+ text: { tag: "lark_md", content: " " },
220
+ });
221
+ }
222
+ }
223
+
224
+ return {
225
+ config: {
226
+ wide_screen_mode: true,
227
+ update_multi: true,
228
+ },
229
+ header: {
230
+ template: headerTemplate(input.status),
231
+ title: { tag: "plain_text", content: input.title || titleForStatus(input.status) },
232
+ },
233
+ elements,
234
+ };
235
+ }
236
+
237
+ export function parseStopTaskActionValue(value: unknown): { key: string; runId?: string } | undefined {
238
+ if (!value || typeof value !== "object") return undefined;
239
+ const raw = value as any;
240
+ if (raw.action !== STOP_ACTION || typeof raw.key !== "string") return undefined;
241
+ return {
242
+ key: raw.key,
243
+ runId: typeof raw.runId === "string" ? raw.runId : undefined,
244
+ };
245
+ }
246
+
247
+ function normalizeNote(text: string) {
248
+ const compact = text.replace(/\s+/g, " ").trim();
249
+ if (compact.length <= MAX_NOTE_CHARS) return compact;
250
+ return `${compact.slice(0, MAX_NOTE_CHARS - 1)}…`;
251
+ }
252
+
253
+ function titleForStatus(status: ReplyCardStatus) {
254
+ if (status === "done") return "回复";
255
+ if (status === "failed") return "出错了";
256
+ if (status === "stopped") return "已停止";
257
+ if (status === "inactive") return "已结束";
258
+ if (status === "paused") return "等你选择";
259
+ if (status === "answered") return "已选择";
260
+ return "回复中";
261
+ }
262
+
263
+ function headerTemplate(status: ReplyCardStatus) {
264
+ if (status === "done") return "green";
265
+ if (status === "failed") return "red";
266
+ if (status === "stopped") return "grey";
267
+ if (status === "inactive") return "grey";
268
+ if (status === "answered") return "grey";
269
+ if (status === "paused") return "orange";
270
+ return "blue";
271
+ }
272
+
273
+ export function defaultFinalNote(status: ReplyCardFinalStatus): string | undefined {
274
+ if (status === "done") return undefined;
275
+ if (status === "failed") return "处理失败";
276
+ return "已停止";
277
+ }