@openclaw/feishu 2026.5.2 → 2026.5.3-beta.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 (224) hide show
  1. package/dist/accounts-Ba3-WP1z.js +423 -0
  2. package/dist/api.js +2280 -0
  3. package/dist/app-registration-B8qc1MCM.js +184 -0
  4. package/dist/audio-preflight.runtime-BPlzkO3l.js +7 -0
  5. package/dist/card-interaction-BfRLgvw_.js +96 -0
  6. package/dist/channel-CSD_Jt8I.js +1668 -0
  7. package/dist/channel-entry.js +22 -0
  8. package/dist/channel-plugin-api.js +2 -0
  9. package/dist/channel.runtime-DYsXcD36.js +700 -0
  10. package/dist/client-DBVoQL5w.js +157 -0
  11. package/dist/contract-api.js +9 -0
  12. package/dist/conversation-id-DWS3Ep2A.js +139 -0
  13. package/dist/directory.static-f3EeoRJd.js +44 -0
  14. package/dist/drive-C5eJLJr7.js +883 -0
  15. package/dist/index.js +68 -0
  16. package/dist/monitor-CT189QfR.js +60 -0
  17. package/dist/monitor.account-dJV2jO8C.js +4990 -0
  18. package/dist/monitor.state-DYM02ipp.js +100 -0
  19. package/dist/policy-D6c-wMPl.js +118 -0
  20. package/dist/probe-BNzzU_uR.js +149 -0
  21. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  22. package/dist/runtime-CG0DuRCy.js +8 -0
  23. package/dist/runtime-api.js +14 -0
  24. package/dist/secret-contract-Dm4Z_zQN.js +119 -0
  25. package/dist/secret-contract-api.js +2 -0
  26. package/dist/security-audit-DqJdocrN.js +11 -0
  27. package/dist/security-audit-shared-ByuMx9cJ.js +38 -0
  28. package/dist/security-contract-api.js +2 -0
  29. package/dist/send-DowxxbpH.js +1218 -0
  30. package/dist/session-conversation-B4nrW-vo.js +27 -0
  31. package/dist/session-key-api.js +2 -0
  32. package/dist/setup-api.js +2 -0
  33. package/dist/setup-entry.js +15 -0
  34. package/dist/subagent-hooks-C3UhPVLV.js +227 -0
  35. package/dist/subagent-hooks-api.js +23 -0
  36. package/dist/targets-JMFJRKSe.js +48 -0
  37. package/dist/thread-bindings-BmS6TLes.js +222 -0
  38. package/package.json +15 -6
  39. package/api.ts +0 -31
  40. package/channel-entry.ts +0 -20
  41. package/channel-plugin-api.ts +0 -1
  42. package/contract-api.ts +0 -16
  43. package/index.ts +0 -82
  44. package/runtime-api.ts +0 -55
  45. package/secret-contract-api.ts +0 -5
  46. package/security-contract-api.ts +0 -1
  47. package/session-key-api.ts +0 -1
  48. package/setup-api.ts +0 -3
  49. package/setup-entry.test.ts +0 -14
  50. package/setup-entry.ts +0 -13
  51. package/src/accounts.test.ts +0 -459
  52. package/src/accounts.ts +0 -326
  53. package/src/app-registration.ts +0 -331
  54. package/src/approval-auth.test.ts +0 -24
  55. package/src/approval-auth.ts +0 -25
  56. package/src/async.test.ts +0 -35
  57. package/src/async.ts +0 -104
  58. package/src/audio-preflight.runtime.ts +0 -9
  59. package/src/bitable.test.ts +0 -131
  60. package/src/bitable.ts +0 -762
  61. package/src/bot-content.ts +0 -474
  62. package/src/bot-group-name.test.ts +0 -108
  63. package/src/bot-runtime-api.ts +0 -12
  64. package/src/bot-sender-name.ts +0 -125
  65. package/src/bot.broadcast.test.ts +0 -463
  66. package/src/bot.card-action.test.ts +0 -577
  67. package/src/bot.checkBotMentioned.test.ts +0 -265
  68. package/src/bot.helpers.test.ts +0 -118
  69. package/src/bot.stripBotMention.test.ts +0 -126
  70. package/src/bot.test.ts +0 -3040
  71. package/src/bot.ts +0 -1559
  72. package/src/card-action.ts +0 -447
  73. package/src/card-interaction.test.ts +0 -129
  74. package/src/card-interaction.ts +0 -159
  75. package/src/card-test-helpers.ts +0 -47
  76. package/src/card-ux-approval.ts +0 -65
  77. package/src/card-ux-launcher.test.ts +0 -99
  78. package/src/card-ux-launcher.ts +0 -121
  79. package/src/card-ux-shared.ts +0 -33
  80. package/src/channel-runtime-api.ts +0 -16
  81. package/src/channel.runtime.ts +0 -47
  82. package/src/channel.test.ts +0 -959
  83. package/src/channel.ts +0 -1313
  84. package/src/chat-schema.ts +0 -25
  85. package/src/chat.test.ts +0 -196
  86. package/src/chat.ts +0 -188
  87. package/src/client.test.ts +0 -433
  88. package/src/client.ts +0 -290
  89. package/src/comment-dispatcher-runtime-api.ts +0 -6
  90. package/src/comment-dispatcher.test.ts +0 -169
  91. package/src/comment-dispatcher.ts +0 -107
  92. package/src/comment-handler-runtime-api.ts +0 -3
  93. package/src/comment-handler.test.ts +0 -486
  94. package/src/comment-handler.ts +0 -309
  95. package/src/comment-reaction.test.ts +0 -166
  96. package/src/comment-reaction.ts +0 -259
  97. package/src/comment-shared.test.ts +0 -182
  98. package/src/comment-shared.ts +0 -406
  99. package/src/comment-target.ts +0 -44
  100. package/src/config-schema.test.ts +0 -309
  101. package/src/config-schema.ts +0 -333
  102. package/src/conversation-id.test.ts +0 -18
  103. package/src/conversation-id.ts +0 -199
  104. package/src/dedup-runtime-api.ts +0 -1
  105. package/src/dedup.ts +0 -141
  106. package/src/directory.static.ts +0 -61
  107. package/src/directory.test.ts +0 -136
  108. package/src/directory.ts +0 -124
  109. package/src/doc-schema.ts +0 -182
  110. package/src/docx-batch-insert.test.ts +0 -91
  111. package/src/docx-batch-insert.ts +0 -223
  112. package/src/docx-color-text.ts +0 -154
  113. package/src/docx-table-ops.test.ts +0 -53
  114. package/src/docx-table-ops.ts +0 -316
  115. package/src/docx-types.ts +0 -38
  116. package/src/docx.account-selection.test.ts +0 -79
  117. package/src/docx.test.ts +0 -685
  118. package/src/docx.ts +0 -1616
  119. package/src/drive-schema.ts +0 -92
  120. package/src/drive.test.ts +0 -1219
  121. package/src/drive.ts +0 -829
  122. package/src/dynamic-agent.ts +0 -137
  123. package/src/event-types.ts +0 -45
  124. package/src/external-keys.test.ts +0 -20
  125. package/src/external-keys.ts +0 -19
  126. package/src/lifecycle.test-support.ts +0 -220
  127. package/src/media.test.ts +0 -900
  128. package/src/media.ts +0 -861
  129. package/src/mention-target.types.ts +0 -5
  130. package/src/mention.ts +0 -114
  131. package/src/message-action-contract.ts +0 -13
  132. package/src/monitor-state-runtime-api.ts +0 -7
  133. package/src/monitor-transport-runtime-api.ts +0 -7
  134. package/src/monitor.account.ts +0 -468
  135. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  136. package/src/monitor.bot-identity.ts +0 -86
  137. package/src/monitor.bot-menu-handler.ts +0 -165
  138. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  139. package/src/monitor.bot-menu.test.ts +0 -178
  140. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  141. package/src/monitor.card-action.lifecycle.test-support.ts +0 -373
  142. package/src/monitor.cleanup.test.ts +0 -376
  143. package/src/monitor.comment-notice-handler.ts +0 -105
  144. package/src/monitor.comment.test.ts +0 -937
  145. package/src/monitor.comment.ts +0 -1386
  146. package/src/monitor.lifecycle.test.ts +0 -4
  147. package/src/monitor.message-handler.ts +0 -339
  148. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  149. package/src/monitor.reaction.test.ts +0 -713
  150. package/src/monitor.startup.test.ts +0 -192
  151. package/src/monitor.startup.ts +0 -74
  152. package/src/monitor.state.defaults.test.ts +0 -46
  153. package/src/monitor.state.ts +0 -170
  154. package/src/monitor.synthetic-error.ts +0 -18
  155. package/src/monitor.test-mocks.ts +0 -45
  156. package/src/monitor.transport.ts +0 -424
  157. package/src/monitor.ts +0 -100
  158. package/src/monitor.webhook-e2e.test.ts +0 -272
  159. package/src/monitor.webhook-security.test.ts +0 -264
  160. package/src/monitor.webhook.test-helpers.ts +0 -116
  161. package/src/outbound-runtime-api.ts +0 -1
  162. package/src/outbound.test.ts +0 -935
  163. package/src/outbound.ts +0 -718
  164. package/src/perm-schema.ts +0 -52
  165. package/src/perm.ts +0 -170
  166. package/src/pins.ts +0 -108
  167. package/src/policy.test.ts +0 -334
  168. package/src/policy.ts +0 -236
  169. package/src/post.test.ts +0 -105
  170. package/src/post.ts +0 -275
  171. package/src/probe.test.ts +0 -275
  172. package/src/probe.ts +0 -166
  173. package/src/processing-claims.ts +0 -59
  174. package/src/qr-terminal.ts +0 -1
  175. package/src/reactions.ts +0 -123
  176. package/src/reasoning-preview.test.ts +0 -59
  177. package/src/reasoning-preview.ts +0 -20
  178. package/src/reply-dispatcher-runtime-api.ts +0 -7
  179. package/src/reply-dispatcher.test.ts +0 -1144
  180. package/src/reply-dispatcher.ts +0 -650
  181. package/src/runtime.ts +0 -9
  182. package/src/secret-contract.ts +0 -145
  183. package/src/secret-input.ts +0 -1
  184. package/src/security-audit-shared.ts +0 -69
  185. package/src/security-audit.test.ts +0 -61
  186. package/src/security-audit.ts +0 -1
  187. package/src/send-result.ts +0 -29
  188. package/src/send-target.test.ts +0 -80
  189. package/src/send-target.ts +0 -35
  190. package/src/send.reply-fallback.test.ts +0 -292
  191. package/src/send.test.ts +0 -550
  192. package/src/send.ts +0 -800
  193. package/src/sequential-key.test.ts +0 -72
  194. package/src/sequential-key.ts +0 -28
  195. package/src/sequential-queue.test.ts +0 -92
  196. package/src/sequential-queue.ts +0 -16
  197. package/src/session-conversation.ts +0 -42
  198. package/src/session-route.ts +0 -48
  199. package/src/setup-core.ts +0 -51
  200. package/src/setup-surface.test.ts +0 -174
  201. package/src/setup-surface.ts +0 -581
  202. package/src/streaming-card.test.ts +0 -190
  203. package/src/streaming-card.ts +0 -490
  204. package/src/subagent-hooks.test.ts +0 -603
  205. package/src/subagent-hooks.ts +0 -397
  206. package/src/targets.ts +0 -97
  207. package/src/test-support/lifecycle-test-support.ts +0 -453
  208. package/src/thread-bindings.test.ts +0 -143
  209. package/src/thread-bindings.ts +0 -330
  210. package/src/tool-account-routing.test.ts +0 -187
  211. package/src/tool-account.test.ts +0 -44
  212. package/src/tool-account.ts +0 -93
  213. package/src/tool-factory-test-harness.ts +0 -79
  214. package/src/tool-result.test.ts +0 -32
  215. package/src/tool-result.ts +0 -16
  216. package/src/tools-config.test.ts +0 -21
  217. package/src/tools-config.ts +0 -22
  218. package/src/types.ts +0 -104
  219. package/src/typing.test.ts +0 -144
  220. package/src/typing.ts +0 -214
  221. package/src/wiki-schema.ts +0 -55
  222. package/src/wiki.ts +0 -227
  223. package/subagent-hooks-api.ts +0 -31
  224. package/tsconfig.json +0 -16
package/src/send.ts DELETED
@@ -1,800 +0,0 @@
1
- import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
2
- import {
3
- convertMarkdownTables,
4
- normalizeLowercaseStringOrEmpty,
5
- normalizeOptionalLowercaseString,
6
- } from "openclaw/plugin-sdk/text-runtime";
7
- import type { ClawdbotConfig } from "../runtime-api.js";
8
- import { resolveFeishuRuntimeAccount } from "./accounts.js";
9
- import { createFeishuClient } from "./client.js";
10
- import { createFeishuApiError, requestFeishuApi } from "./comment-shared.js";
11
- import type { MentionTarget } from "./mention-target.types.js";
12
- import { buildMentionedCardContent, buildMentionedMessage } from "./mention.js";
13
- import { parsePostContent } from "./post.js";
14
- import { assertFeishuMessageApiSuccess, toFeishuSendResult } from "./send-result.js";
15
- import { resolveFeishuSendTarget } from "./send-target.js";
16
- import type { FeishuChatType, FeishuMessageInfo, FeishuSendResult } from "./types.js";
17
-
18
- const WITHDRAWN_REPLY_ERROR_CODES = new Set([230011, 231003]);
19
- const INTERACTIVE_CARD_FALLBACK_TEXT = "[Interactive Card]";
20
- const POST_FALLBACK_TEXT = "[Rich text message]";
21
- const FEISHU_CARD_TEMPLATES = new Set([
22
- "blue",
23
- "green",
24
- "red",
25
- "orange",
26
- "purple",
27
- "indigo",
28
- "wathet",
29
- "turquoise",
30
- "yellow",
31
- "grey",
32
- "carmine",
33
- "violet",
34
- "lime",
35
- ]);
36
-
37
- function shouldFallbackFromReplyTarget(response: { code?: number; msg?: string }): boolean {
38
- if (response.code !== undefined && WITHDRAWN_REPLY_ERROR_CODES.has(response.code)) {
39
- return true;
40
- }
41
- const msg = normalizeLowercaseStringOrEmpty(response.msg);
42
- return msg.includes("withdrawn") || msg.includes("not found");
43
- }
44
-
45
- /** Check whether a thrown error indicates a withdrawn/not-found reply target. */
46
- function isWithdrawnReplyError(err: unknown): boolean {
47
- if (typeof err !== "object" || err === null) {
48
- return false;
49
- }
50
- // SDK error shape: err.code
51
- const code = (err as { code?: number }).code;
52
- if (typeof code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(code)) {
53
- return true;
54
- }
55
- // AxiosError shape: err.response.data.code
56
- const response = (err as { response?: { data?: { code?: number; msg?: string } } }).response;
57
- if (
58
- typeof response?.data?.code === "number" &&
59
- WITHDRAWN_REPLY_ERROR_CODES.has(response.data.code)
60
- ) {
61
- return true;
62
- }
63
- return false;
64
- }
65
-
66
- function isRecord(value: unknown): value is Record<string, unknown> {
67
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
68
- }
69
-
70
- type FeishuCreateMessageClient = {
71
- im: {
72
- message: {
73
- reply: (opts: {
74
- path: { message_id: string };
75
- data: { content: string; msg_type: string; reply_in_thread?: true };
76
- }) => Promise<{ code?: number; msg?: string; data?: { message_id?: string } }>;
77
- create: (opts: {
78
- params: { receive_id_type: "chat_id" | "email" | "open_id" | "union_id" | "user_id" };
79
- data: { receive_id: string; content: string; msg_type: string };
80
- }) => Promise<{ code?: number; msg?: string; data?: { message_id?: string } }>;
81
- };
82
- };
83
- };
84
-
85
- type FeishuMessageSender = {
86
- id?: string;
87
- id_type?: string;
88
- sender_type?: string;
89
- };
90
-
91
- type FeishuMessageGetItem = {
92
- message_id?: string;
93
- chat_id?: string;
94
- chat_type?: FeishuChatType;
95
- thread_id?: string;
96
- msg_type?: string;
97
- body?: { content?: string };
98
- sender?: FeishuMessageSender;
99
- create_time?: string;
100
- };
101
-
102
- type FeishuGetMessageResponse = {
103
- code?: number;
104
- msg?: string;
105
- data?: FeishuMessageGetItem & {
106
- items?: FeishuMessageGetItem[];
107
- };
108
- };
109
-
110
- /** Send a direct message as a fallback when a reply target is unavailable. */
111
- async function sendFallbackDirect(
112
- client: FeishuCreateMessageClient,
113
- params: {
114
- receiveId: string;
115
- receiveIdType: "chat_id" | "email" | "open_id" | "union_id" | "user_id";
116
- content: string;
117
- msgType: string;
118
- },
119
- errorPrefix: string,
120
- ): Promise<FeishuSendResult> {
121
- const response = await requestFeishuApi(
122
- () =>
123
- client.im.message.create({
124
- params: { receive_id_type: params.receiveIdType },
125
- data: {
126
- receive_id: params.receiveId,
127
- content: params.content,
128
- msg_type: params.msgType,
129
- },
130
- }),
131
- errorPrefix,
132
- { includeNestedErrorLogId: true },
133
- );
134
- assertFeishuMessageApiSuccess(response, errorPrefix);
135
- return toFeishuSendResult(response, params.receiveId);
136
- }
137
-
138
- async function sendReplyOrFallbackDirect(
139
- client: FeishuCreateMessageClient,
140
- params: {
141
- replyToMessageId?: string;
142
- replyInThread?: boolean;
143
- content: string;
144
- msgType: string;
145
- directParams: {
146
- receiveId: string;
147
- receiveIdType: "chat_id" | "email" | "open_id" | "union_id" | "user_id";
148
- content: string;
149
- msgType: string;
150
- };
151
- directErrorPrefix: string;
152
- replyErrorPrefix: string;
153
- },
154
- ): Promise<FeishuSendResult> {
155
- if (!params.replyToMessageId) {
156
- return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
157
- }
158
-
159
- const threadReplyFallbackError = params.replyInThread
160
- ? new Error(
161
- "Feishu thread reply failed: reply target is unavailable and cannot safely fall back to a top-level send.",
162
- )
163
- : null;
164
-
165
- let response: { code?: number; msg?: string; data?: { message_id?: string } };
166
- try {
167
- response = await client.im.message.reply({
168
- path: { message_id: params.replyToMessageId },
169
- data: {
170
- content: params.content,
171
- msg_type: params.msgType,
172
- ...(params.replyInThread ? { reply_in_thread: true } : {}),
173
- },
174
- });
175
- } catch (err) {
176
- if (!isWithdrawnReplyError(err)) {
177
- throw createFeishuApiError(err, params.replyErrorPrefix, { includeNestedErrorLogId: true });
178
- }
179
- if (threadReplyFallbackError) {
180
- throw threadReplyFallbackError;
181
- }
182
- return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
183
- }
184
- if (shouldFallbackFromReplyTarget(response)) {
185
- if (threadReplyFallbackError) {
186
- throw threadReplyFallbackError;
187
- }
188
- return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
189
- }
190
- assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
191
- return toFeishuSendResult(response, params.directParams.receiveId);
192
- }
193
-
194
- function normalizeCardTemplateVariable(value: unknown): string | undefined {
195
- if (typeof value === "string") {
196
- return value;
197
- }
198
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
199
- return String(value);
200
- }
201
- return undefined;
202
- }
203
-
204
- function readCardTemplateVariables(parsed: Record<string, unknown>): Map<string, string> {
205
- const variables = new Map<string, string>();
206
- for (const source of [parsed.template_variable, parsed.template_variables]) {
207
- if (!isRecord(source)) {
208
- continue;
209
- }
210
- for (const [key, value] of Object.entries(source)) {
211
- const normalized = normalizeCardTemplateVariable(value);
212
- if (normalized !== undefined) {
213
- variables.set(key, normalized);
214
- }
215
- }
216
- }
217
- return variables;
218
- }
219
-
220
- function applyCardTemplateVariables(text: string, variables: Map<string, string>): string {
221
- if (variables.size === 0) {
222
- return text;
223
- }
224
- return text.replace(/\$\{([A-Za-z0-9_.-]+)\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (match, a, b) => {
225
- const variableName = typeof a === "string" ? a : b;
226
- return variables.get(variableName) ?? match;
227
- });
228
- }
229
-
230
- function extractInteractiveElementText(
231
- element: unknown,
232
- variables: Map<string, string>,
233
- ): string | undefined {
234
- if (!isRecord(element)) {
235
- return undefined;
236
- }
237
- const tag = typeof element.tag === "string" ? element.tag : "";
238
- const text = isRecord(element.text) ? element.text : undefined;
239
-
240
- if (tag === "div" && typeof text?.content === "string") {
241
- return applyCardTemplateVariables(text.content, variables);
242
- }
243
- if ((tag === "markdown" || tag === "lark_md") && typeof element.content === "string") {
244
- return applyCardTemplateVariables(element.content, variables);
245
- }
246
- if (tag === "plain_text" && typeof element.content === "string") {
247
- return applyCardTemplateVariables(element.content, variables);
248
- }
249
- return undefined;
250
- }
251
-
252
- function extractInteractiveElementsText(
253
- elements: unknown[],
254
- variables: Map<string, string>,
255
- ): string {
256
- const texts: string[] = [];
257
- for (const element of elements) {
258
- const text = extractInteractiveElementText(element, variables);
259
- if (text !== undefined) {
260
- texts.push(text);
261
- }
262
- }
263
- return texts.join("\n").trim();
264
- }
265
-
266
- function readInteractiveElementArrays(parsed: Record<string, unknown>): unknown[][] {
267
- const body = isRecord(parsed.body) ? parsed.body : undefined;
268
- const elementArrays: unknown[][] = [];
269
-
270
- for (const candidate of [parsed.elements, body?.elements]) {
271
- if (Array.isArray(candidate)) {
272
- elementArrays.push(candidate);
273
- }
274
- }
275
-
276
- for (const candidate of [parsed.i18n_elements, body?.i18n_elements]) {
277
- if (!isRecord(candidate)) {
278
- continue;
279
- }
280
- for (const localeElements of Object.values(candidate)) {
281
- if (Array.isArray(localeElements)) {
282
- elementArrays.push(localeElements);
283
- }
284
- }
285
- }
286
-
287
- return elementArrays;
288
- }
289
-
290
- function parseInteractivePostFallback(parsed: unknown): string | undefined {
291
- const textContent = parsePostContent(JSON.stringify(parsed)).textContent.trim();
292
- return textContent && textContent !== POST_FALLBACK_TEXT ? textContent : undefined;
293
- }
294
-
295
- function parseInteractiveCardContent(parsed: unknown): string {
296
- if (!isRecord(parsed)) {
297
- return INTERACTIVE_CARD_FALLBACK_TEXT;
298
- }
299
-
300
- const variables = readCardTemplateVariables(parsed);
301
- for (const elements of readInteractiveElementArrays(parsed)) {
302
- const text = extractInteractiveElementsText(elements, variables);
303
- if (text) {
304
- return text;
305
- }
306
- }
307
-
308
- return parseInteractivePostFallback(parsed) ?? INTERACTIVE_CARD_FALLBACK_TEXT;
309
- }
310
-
311
- function parseFeishuMessageContent(rawContent: string, msgType: string): string {
312
- if (!rawContent) {
313
- return "";
314
- }
315
-
316
- let parsed: unknown;
317
- try {
318
- parsed = JSON.parse(rawContent);
319
- } catch {
320
- return rawContent;
321
- }
322
-
323
- if (msgType === "text") {
324
- const text = (parsed as { text?: unknown })?.text;
325
- return typeof text === "string" ? text : "[Text message]";
326
- }
327
-
328
- if (msgType === "post") {
329
- return parsePostContent(rawContent).textContent;
330
- }
331
-
332
- if (msgType === "interactive") {
333
- return parseInteractiveCardContent(parsed);
334
- }
335
-
336
- if (typeof parsed === "string") {
337
- return parsed;
338
- }
339
-
340
- const genericText = (parsed as { text?: unknown; title?: unknown } | null)?.text;
341
- if (typeof genericText === "string" && genericText.trim()) {
342
- return genericText;
343
- }
344
- const genericTitle = (parsed as { title?: unknown } | null)?.title;
345
- if (typeof genericTitle === "string" && genericTitle.trim()) {
346
- return genericTitle;
347
- }
348
-
349
- return `[${msgType || "unknown"} message]`;
350
- }
351
-
352
- function parseFeishuMessageItem(
353
- item: FeishuMessageGetItem,
354
- fallbackMessageId?: string,
355
- ): FeishuMessageInfo {
356
- const msgType = item.msg_type ?? "text";
357
- const rawContent = item.body?.content ?? "";
358
-
359
- return {
360
- messageId: item.message_id ?? fallbackMessageId ?? "",
361
- chatId: item.chat_id ?? "",
362
- chatType:
363
- item.chat_type === "group" ||
364
- item.chat_type === "topic_group" ||
365
- item.chat_type === "private" ||
366
- item.chat_type === "p2p"
367
- ? item.chat_type
368
- : undefined,
369
- senderId: item.sender?.id,
370
- senderOpenId: item.sender?.id_type === "open_id" ? item.sender?.id : undefined,
371
- senderType: item.sender?.sender_type,
372
- content: parseFeishuMessageContent(rawContent, msgType),
373
- contentType: msgType,
374
- createTime: item.create_time ? Number.parseInt(item.create_time, 10) : undefined,
375
- threadId: item.thread_id || undefined,
376
- };
377
- }
378
-
379
- /**
380
- * Get a message by its ID.
381
- * Useful for fetching quoted/replied message content.
382
- */
383
- export async function getMessageFeishu(params: {
384
- cfg: ClawdbotConfig;
385
- messageId: string;
386
- accountId?: string;
387
- }): Promise<FeishuMessageInfo | null> {
388
- const { cfg, messageId, accountId } = params;
389
- const account = resolveFeishuRuntimeAccount({ cfg, accountId });
390
- if (!account.configured) {
391
- throw new Error(`Feishu account "${account.accountId}" not configured`);
392
- }
393
-
394
- const client = createFeishuClient(account);
395
-
396
- try {
397
- const response = (await client.im.message.get({
398
- path: { message_id: messageId },
399
- })) as FeishuGetMessageResponse;
400
-
401
- if (response.code !== 0) {
402
- return null;
403
- }
404
-
405
- // Support both list shape (data.items[0]) and single-object shape (data as message)
406
- const rawItem = response.data?.items?.[0] ?? response.data;
407
- const item =
408
- rawItem &&
409
- (rawItem.body !== undefined || (rawItem as { message_id?: string }).message_id !== undefined)
410
- ? rawItem
411
- : null;
412
- if (!item) {
413
- return null;
414
- }
415
-
416
- return parseFeishuMessageItem(item, messageId);
417
- } catch {
418
- return null;
419
- }
420
- }
421
-
422
- export type FeishuThreadMessageInfo = {
423
- messageId: string;
424
- senderId?: string;
425
- senderType?: string;
426
- content: string;
427
- contentType: string;
428
- createTime?: number;
429
- };
430
-
431
- /**
432
- * List messages in a Feishu thread (topic).
433
- * Uses container_id_type=thread to directly query thread messages,
434
- * which includes both the root message and all replies (including bot replies).
435
- */
436
- export async function listFeishuThreadMessages(params: {
437
- cfg: ClawdbotConfig;
438
- threadId: string;
439
- currentMessageId?: string;
440
- /** Exclude the root message (already provided separately as ThreadStarterBody). */
441
- rootMessageId?: string;
442
- limit?: number;
443
- accountId?: string;
444
- }): Promise<FeishuThreadMessageInfo[]> {
445
- const { cfg, threadId, currentMessageId, rootMessageId, limit = 20, accountId } = params;
446
- const account = resolveFeishuRuntimeAccount({ cfg, accountId });
447
- if (!account.configured) {
448
- throw new Error(`Feishu account "${account.accountId}" not configured`);
449
- }
450
-
451
- const client = createFeishuClient(account);
452
-
453
- const response = (await client.im.message.list({
454
- params: {
455
- container_id_type: "thread",
456
- container_id: threadId,
457
- // Fetch newest messages first so long threads keep the most recent turns.
458
- // Results are reversed below to restore chronological order.
459
- sort_type: "ByCreateTimeDesc",
460
- page_size: Math.min(limit + 1, 50),
461
- },
462
- })) as {
463
- code?: number;
464
- msg?: string;
465
- data?: {
466
- items?: Array<
467
- {
468
- message_id?: string;
469
- root_id?: string;
470
- parent_id?: string;
471
- } & FeishuMessageGetItem
472
- >;
473
- };
474
- };
475
-
476
- if (response.code !== 0) {
477
- throw new Error(
478
- `Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`,
479
- );
480
- }
481
-
482
- const items = response.data?.items ?? [];
483
- const results: FeishuThreadMessageInfo[] = [];
484
-
485
- for (const item of items) {
486
- if (currentMessageId && item.message_id === currentMessageId) {
487
- continue;
488
- }
489
- if (rootMessageId && item.message_id === rootMessageId) {
490
- continue;
491
- }
492
-
493
- const parsed = parseFeishuMessageItem(item);
494
-
495
- results.push({
496
- messageId: parsed.messageId,
497
- senderId: parsed.senderId,
498
- senderType: parsed.senderType,
499
- content: parsed.content,
500
- contentType: parsed.contentType,
501
- createTime: parsed.createTime,
502
- });
503
-
504
- if (results.length >= limit) {
505
- break;
506
- }
507
- }
508
-
509
- // Restore chronological order (oldest first) since we fetched newest-first.
510
- results.reverse();
511
- return results;
512
- }
513
-
514
- export type SendFeishuMessageParams = {
515
- cfg: ClawdbotConfig;
516
- to: string;
517
- text: string;
518
- replyToMessageId?: string;
519
- /** When true, reply creates a Feishu topic thread instead of an inline reply */
520
- replyInThread?: boolean;
521
- /** Mention target users */
522
- mentions?: MentionTarget[];
523
- /** Account ID (optional, uses default if not specified) */
524
- accountId?: string;
525
- };
526
-
527
- export function buildFeishuPostMessagePayload(params: { messageText: string }): {
528
- content: string;
529
- msgType: string;
530
- } {
531
- const { messageText } = params;
532
- return {
533
- content: JSON.stringify({
534
- zh_cn: {
535
- content: [
536
- [
537
- {
538
- tag: "md",
539
- text: messageText,
540
- },
541
- ],
542
- ],
543
- },
544
- }),
545
- msgType: "post",
546
- };
547
- }
548
-
549
- export async function sendMessageFeishu(
550
- params: SendFeishuMessageParams,
551
- ): Promise<FeishuSendResult> {
552
- const { cfg, to, text, replyToMessageId, replyInThread, mentions, accountId } = params;
553
- const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({ cfg, to, accountId });
554
- const tableMode = resolveMarkdownTableMode({
555
- cfg,
556
- channel: "feishu",
557
- });
558
-
559
- // Build message content (with @mention support)
560
- let rawText = text ?? "";
561
- if (mentions && mentions.length > 0) {
562
- rawText = buildMentionedMessage(mentions, rawText);
563
- }
564
- const messageText = convertMarkdownTables(rawText, tableMode);
565
-
566
- const { content, msgType } = buildFeishuPostMessagePayload({ messageText });
567
-
568
- const directParams = { receiveId, receiveIdType, content, msgType };
569
- return sendReplyOrFallbackDirect(client, {
570
- replyToMessageId,
571
- replyInThread,
572
- content,
573
- msgType,
574
- directParams,
575
- directErrorPrefix: "Feishu send failed",
576
- replyErrorPrefix: "Feishu reply failed",
577
- });
578
- }
579
-
580
- export type SendFeishuCardParams = {
581
- cfg: ClawdbotConfig;
582
- to: string;
583
- card: Record<string, unknown>;
584
- replyToMessageId?: string;
585
- /** When true, reply creates a Feishu topic thread instead of an inline reply */
586
- replyInThread?: boolean;
587
- accountId?: string;
588
- };
589
-
590
- export async function sendCardFeishu(params: SendFeishuCardParams): Promise<FeishuSendResult> {
591
- const { cfg, to, card, replyToMessageId, replyInThread, accountId } = params;
592
- const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({ cfg, to, accountId });
593
- const content = JSON.stringify(card);
594
-
595
- const directParams = { receiveId, receiveIdType, content, msgType: "interactive" };
596
- return sendReplyOrFallbackDirect(client, {
597
- replyToMessageId,
598
- replyInThread,
599
- content,
600
- msgType: "interactive",
601
- directParams,
602
- directErrorPrefix: "Feishu card send failed",
603
- replyErrorPrefix: "Feishu card reply failed",
604
- });
605
- }
606
-
607
- export async function editMessageFeishu(params: {
608
- cfg: ClawdbotConfig;
609
- messageId: string;
610
- text?: string;
611
- card?: Record<string, unknown>;
612
- accountId?: string;
613
- }): Promise<{ messageId: string; contentType: "post" | "interactive" }> {
614
- const { cfg, messageId, text, card, accountId } = params;
615
- const account = resolveFeishuRuntimeAccount({ cfg, accountId });
616
- if (!account.configured) {
617
- throw new Error(`Feishu account "${account.accountId}" not configured`);
618
- }
619
-
620
- const hasText = typeof text === "string" && text.trim().length > 0;
621
- const hasCard = Boolean(card);
622
- if (hasText === hasCard) {
623
- throw new Error("Feishu edit requires exactly one of text or card.");
624
- }
625
-
626
- const client = createFeishuClient(account);
627
-
628
- if (card) {
629
- const content = JSON.stringify(card);
630
- const response = await client.im.message.patch({
631
- path: { message_id: messageId },
632
- data: { content },
633
- });
634
-
635
- if (response.code !== 0) {
636
- throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
637
- }
638
-
639
- return { messageId, contentType: "interactive" };
640
- }
641
-
642
- const tableMode = resolveMarkdownTableMode({
643
- cfg,
644
- channel: "feishu",
645
- });
646
- const messageText = convertMarkdownTables(text!, tableMode);
647
- const payload = buildFeishuPostMessagePayload({ messageText });
648
- const response = await client.im.message.patch({
649
- path: { message_id: messageId },
650
- data: { content: payload.content },
651
- });
652
-
653
- if (response.code !== 0) {
654
- throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
655
- }
656
-
657
- return { messageId, contentType: "post" };
658
- }
659
-
660
- export async function updateCardFeishu(params: {
661
- cfg: ClawdbotConfig;
662
- messageId: string;
663
- card: Record<string, unknown>;
664
- accountId?: string;
665
- }): Promise<void> {
666
- const { cfg, messageId, card, accountId } = params;
667
- const account = resolveFeishuRuntimeAccount({ cfg, accountId });
668
- if (!account.configured) {
669
- throw new Error(`Feishu account "${account.accountId}" not configured`);
670
- }
671
-
672
- const client = createFeishuClient(account);
673
- const content = JSON.stringify(card);
674
-
675
- const response = await client.im.message.patch({
676
- path: { message_id: messageId },
677
- data: { content },
678
- });
679
-
680
- if (response.code !== 0) {
681
- throw new Error(`Feishu card update failed: ${response.msg || `code ${response.code}`}`);
682
- }
683
- }
684
-
685
- /**
686
- * Build a Feishu interactive card with markdown content.
687
- * Cards render markdown properly (code blocks, tables, links, etc.)
688
- * Uses schema 2.0 format for proper markdown rendering.
689
- */
690
- export function buildMarkdownCard(text: string): Record<string, unknown> {
691
- return {
692
- schema: "2.0",
693
- config: {
694
- width_mode: "fill",
695
- },
696
- body: {
697
- elements: [
698
- {
699
- tag: "markdown",
700
- content: text,
701
- },
702
- ],
703
- },
704
- };
705
- }
706
-
707
- /** Header configuration for structured Feishu cards. */
708
- export type CardHeaderConfig = {
709
- /** Header title text, e.g. "💻 Coder" */
710
- title: string;
711
- /** Feishu header color template (blue, green, red, orange, purple, grey, etc.). Defaults to "blue". */
712
- template?: string;
713
- };
714
-
715
- export function resolveFeishuCardTemplate(template?: string): string | undefined {
716
- const normalized = normalizeOptionalLowercaseString(template);
717
- if (!normalized || !FEISHU_CARD_TEMPLATES.has(normalized)) {
718
- return undefined;
719
- }
720
- return normalized;
721
- }
722
-
723
- /**
724
- * Build a Feishu interactive card with optional header and note footer.
725
- * When header/note are omitted, behaves identically to buildMarkdownCard.
726
- */
727
- export function buildStructuredCard(
728
- text: string,
729
- options?: {
730
- header?: CardHeaderConfig;
731
- note?: string;
732
- },
733
- ): Record<string, unknown> {
734
- const elements: Record<string, unknown>[] = [{ tag: "markdown", content: text }];
735
- if (options?.note) {
736
- elements.push({ tag: "hr" });
737
- elements.push({ tag: "markdown", content: `<font color='grey'>${options.note}</font>` });
738
- }
739
- const card: Record<string, unknown> = {
740
- schema: "2.0",
741
- config: { width_mode: "fill" },
742
- body: { elements },
743
- };
744
- if (options?.header) {
745
- card.header = {
746
- title: { tag: "plain_text", content: options.header.title },
747
- template: resolveFeishuCardTemplate(options.header.template) ?? "blue",
748
- };
749
- }
750
- return card;
751
- }
752
-
753
- /**
754
- * Send a message as a structured card with optional header and note.
755
- */
756
- export async function sendStructuredCardFeishu(params: {
757
- cfg: ClawdbotConfig;
758
- to: string;
759
- text: string;
760
- replyToMessageId?: string;
761
- /** When true, reply creates a Feishu topic thread instead of an inline reply */
762
- replyInThread?: boolean;
763
- mentions?: MentionTarget[];
764
- accountId?: string;
765
- header?: CardHeaderConfig;
766
- note?: string;
767
- }): Promise<FeishuSendResult> {
768
- const { cfg, to, text, replyToMessageId, replyInThread, mentions, accountId, header, note } =
769
- params;
770
- let cardText = text;
771
- if (mentions && mentions.length > 0) {
772
- cardText = buildMentionedCardContent(mentions, text);
773
- }
774
- const card = buildStructuredCard(cardText, { header, note });
775
- return sendCardFeishu({ cfg, to, card, replyToMessageId, replyInThread, accountId });
776
- }
777
-
778
- /**
779
- * Send a message as a markdown card (interactive message).
780
- * This renders markdown properly in Feishu (code blocks, tables, bold/italic, etc.)
781
- */
782
- export async function sendMarkdownCardFeishu(params: {
783
- cfg: ClawdbotConfig;
784
- to: string;
785
- text: string;
786
- replyToMessageId?: string;
787
- /** When true, reply creates a Feishu topic thread instead of an inline reply */
788
- replyInThread?: boolean;
789
- /** Mention target users */
790
- mentions?: MentionTarget[];
791
- accountId?: string;
792
- }): Promise<FeishuSendResult> {
793
- const { cfg, to, text, replyToMessageId, replyInThread, mentions, accountId } = params;
794
- let cardText = text;
795
- if (mentions && mentions.length > 0) {
796
- cardText = buildMentionedCardContent(mentions, text);
797
- }
798
- const card = buildMarkdownCard(cardText);
799
- return sendCardFeishu({ cfg, to, card, replyToMessageId, replyInThread, accountId });
800
- }