@openclaw/feishu 2026.3.13 → 2026.5.2-beta.1

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 (187) hide show
  1. package/api.ts +31 -0
  2. package/channel-entry.ts +20 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +16 -0
  5. package/index.ts +70 -53
  6. package/openclaw.plugin.json +1827 -4
  7. package/package.json +32 -7
  8. package/runtime-api.ts +55 -0
  9. package/secret-contract-api.ts +5 -0
  10. package/security-contract-api.ts +1 -0
  11. package/session-key-api.ts +1 -0
  12. package/setup-api.ts +3 -0
  13. package/setup-entry.test.ts +14 -0
  14. package/setup-entry.ts +13 -0
  15. package/src/accounts.test.ts +95 -7
  16. package/src/accounts.ts +199 -117
  17. package/src/app-registration.ts +331 -0
  18. package/src/approval-auth.test.ts +24 -0
  19. package/src/approval-auth.ts +25 -0
  20. package/src/async.test.ts +35 -0
  21. package/src/async.ts +43 -1
  22. package/src/audio-preflight.runtime.ts +9 -0
  23. package/src/bitable.test.ts +131 -0
  24. package/src/bitable.ts +59 -22
  25. package/src/bot-content.ts +474 -0
  26. package/src/bot-group-name.test.ts +108 -0
  27. package/src/bot-runtime-api.ts +12 -0
  28. package/src/bot-sender-name.ts +125 -0
  29. package/src/bot.broadcast.test.ts +463 -0
  30. package/src/bot.card-action.test.ts +519 -5
  31. package/src/bot.checkBotMentioned.test.ts +92 -20
  32. package/src/bot.helpers.test.ts +118 -0
  33. package/src/bot.stripBotMention.test.ts +13 -21
  34. package/src/bot.test.ts +1334 -401
  35. package/src/bot.ts +778 -775
  36. package/src/card-action.ts +408 -40
  37. package/src/card-interaction.test.ts +129 -0
  38. package/src/card-interaction.ts +159 -0
  39. package/src/card-test-helpers.ts +47 -0
  40. package/src/card-ux-approval.ts +65 -0
  41. package/src/card-ux-launcher.test.ts +99 -0
  42. package/src/card-ux-launcher.ts +121 -0
  43. package/src/card-ux-shared.ts +33 -0
  44. package/src/channel-runtime-api.ts +16 -0
  45. package/src/channel.runtime.ts +47 -0
  46. package/src/channel.test.ts +914 -3
  47. package/src/channel.ts +1253 -309
  48. package/src/chat-schema.ts +5 -4
  49. package/src/chat.test.ts +135 -28
  50. package/src/chat.ts +68 -10
  51. package/src/client.test.ts +212 -103
  52. package/src/client.ts +115 -21
  53. package/src/comment-dispatcher-runtime-api.ts +6 -0
  54. package/src/comment-dispatcher.test.ts +169 -0
  55. package/src/comment-dispatcher.ts +107 -0
  56. package/src/comment-handler-runtime-api.ts +3 -0
  57. package/src/comment-handler.test.ts +486 -0
  58. package/src/comment-handler.ts +309 -0
  59. package/src/comment-reaction.test.ts +166 -0
  60. package/src/comment-reaction.ts +259 -0
  61. package/src/comment-shared.test.ts +182 -0
  62. package/src/comment-shared.ts +406 -0
  63. package/src/comment-target.ts +44 -0
  64. package/src/config-schema.test.ts +63 -1
  65. package/src/config-schema.ts +31 -4
  66. package/src/conversation-id.test.ts +18 -0
  67. package/src/conversation-id.ts +199 -0
  68. package/src/dedup-runtime-api.ts +1 -0
  69. package/src/dedup.ts +33 -95
  70. package/src/directory.static.ts +61 -0
  71. package/src/directory.test.ts +116 -20
  72. package/src/directory.ts +60 -92
  73. package/src/doc-schema.ts +1 -1
  74. package/src/docx-batch-insert.test.ts +39 -38
  75. package/src/docx-batch-insert.ts +55 -19
  76. package/src/docx-color-text.ts +9 -4
  77. package/src/docx-table-ops.test.ts +53 -0
  78. package/src/docx-table-ops.ts +52 -34
  79. package/src/docx-types.ts +38 -0
  80. package/src/docx.account-selection.test.ts +12 -3
  81. package/src/docx.test.ts +314 -74
  82. package/src/docx.ts +278 -122
  83. package/src/drive-schema.ts +47 -1
  84. package/src/drive.test.ts +1219 -0
  85. package/src/drive.ts +614 -13
  86. package/src/dynamic-agent.ts +10 -4
  87. package/src/event-types.ts +45 -0
  88. package/src/external-keys.ts +1 -1
  89. package/src/lifecycle.test-support.ts +220 -0
  90. package/src/media.test.ts +403 -26
  91. package/src/media.ts +509 -132
  92. package/src/mention-target.types.ts +5 -0
  93. package/src/mention.ts +32 -51
  94. package/src/message-action-contract.ts +13 -0
  95. package/src/monitor-state-runtime-api.ts +7 -0
  96. package/src/monitor-transport-runtime-api.ts +7 -0
  97. package/src/monitor.account.ts +218 -312
  98. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  99. package/src/monitor.bot-identity.ts +86 -0
  100. package/src/monitor.bot-menu-handler.ts +165 -0
  101. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  102. package/src/monitor.bot-menu.test.ts +178 -0
  103. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  104. package/src/monitor.card-action.lifecycle.test-support.ts +373 -0
  105. package/src/monitor.cleanup.test.ts +376 -0
  106. package/src/monitor.comment-notice-handler.ts +105 -0
  107. package/src/monitor.comment.test.ts +937 -0
  108. package/src/monitor.comment.ts +1386 -0
  109. package/src/monitor.lifecycle.test.ts +4 -0
  110. package/src/monitor.message-handler.ts +339 -0
  111. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  112. package/src/monitor.reaction.test.ts +108 -48
  113. package/src/monitor.startup.test.ts +11 -9
  114. package/src/monitor.startup.ts +26 -16
  115. package/src/monitor.state.ts +20 -5
  116. package/src/monitor.synthetic-error.ts +18 -0
  117. package/src/monitor.test-mocks.ts +2 -2
  118. package/src/monitor.transport.ts +220 -60
  119. package/src/monitor.ts +15 -10
  120. package/src/monitor.webhook-e2e.test.ts +65 -7
  121. package/src/monitor.webhook-security.test.ts +122 -0
  122. package/src/monitor.webhook.test-helpers.ts +44 -26
  123. package/src/outbound-runtime-api.ts +1 -0
  124. package/src/outbound.test.ts +616 -37
  125. package/src/outbound.ts +623 -81
  126. package/src/perm-schema.ts +1 -1
  127. package/src/perm.ts +1 -7
  128. package/src/pins.ts +108 -0
  129. package/src/policy.test.ts +297 -117
  130. package/src/policy.ts +142 -29
  131. package/src/post.ts +7 -6
  132. package/src/probe.test.ts +14 -9
  133. package/src/probe.ts +26 -16
  134. package/src/processing-claims.ts +59 -0
  135. package/src/qr-terminal.ts +1 -0
  136. package/src/reactions.ts +4 -34
  137. package/src/reasoning-preview.test.ts +59 -0
  138. package/src/reasoning-preview.ts +20 -0
  139. package/src/reply-dispatcher-runtime-api.ts +7 -0
  140. package/src/reply-dispatcher.test.ts +660 -29
  141. package/src/reply-dispatcher.ts +407 -154
  142. package/src/runtime.ts +6 -3
  143. package/src/secret-contract.ts +145 -0
  144. package/src/secret-input.ts +1 -13
  145. package/src/security-audit-shared.ts +69 -0
  146. package/src/security-audit.test.ts +61 -0
  147. package/src/security-audit.ts +1 -0
  148. package/src/send-result.ts +1 -1
  149. package/src/send-target.test.ts +9 -3
  150. package/src/send-target.ts +10 -4
  151. package/src/send.reply-fallback.test.ts +105 -2
  152. package/src/send.test.ts +386 -4
  153. package/src/send.ts +414 -95
  154. package/src/sequential-key.test.ts +72 -0
  155. package/src/sequential-key.ts +28 -0
  156. package/src/sequential-queue.test.ts +92 -0
  157. package/src/sequential-queue.ts +16 -0
  158. package/src/session-conversation.ts +42 -0
  159. package/src/session-route.ts +48 -0
  160. package/src/setup-core.ts +51 -0
  161. package/src/{onboarding.test.ts → setup-surface.test.ts} +52 -21
  162. package/src/setup-surface.ts +581 -0
  163. package/src/streaming-card.test.ts +138 -2
  164. package/src/streaming-card.ts +134 -18
  165. package/src/subagent-hooks.test.ts +603 -0
  166. package/src/subagent-hooks.ts +397 -0
  167. package/src/targets.ts +3 -13
  168. package/src/test-support/lifecycle-test-support.ts +453 -0
  169. package/src/thread-bindings.test.ts +143 -0
  170. package/src/thread-bindings.ts +330 -0
  171. package/src/tool-account-routing.test.ts +66 -8
  172. package/src/tool-account.test.ts +44 -0
  173. package/src/tool-account.ts +40 -17
  174. package/src/tool-factory-test-harness.ts +11 -8
  175. package/src/tool-result.ts +3 -1
  176. package/src/tools-config.ts +1 -1
  177. package/src/types.ts +16 -15
  178. package/src/typing.ts +10 -6
  179. package/src/wiki-schema.ts +1 -1
  180. package/src/wiki.ts +1 -7
  181. package/subagent-hooks-api.ts +31 -0
  182. package/tsconfig.json +16 -0
  183. package/src/feishu-command-handler.ts +0 -59
  184. package/src/onboarding.status.test.ts +0 -25
  185. package/src/onboarding.ts +0 -489
  186. package/src/send-message.ts +0 -71
  187. package/src/targets.test.ts +0 -70
package/src/media.ts CHANGED
@@ -1,15 +1,42 @@
1
- import fs from "fs";
2
- import path from "path";
3
- import { Readable } from "stream";
4
- import { withTempDownloadPath, type ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
5
- import { resolveFeishuAccount } from "./accounts.js";
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { Readable } from "node:stream";
4
+ import type * as Lark from "@larksuiteoapi/node-sdk";
5
+ import { mediaKindFromMime } from "openclaw/plugin-sdk/media-mime";
6
+ import { MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS, runFfmpeg } from "openclaw/plugin-sdk/media-runtime";
7
+ import {
8
+ resolvePreferredOpenClawTmpDir,
9
+ withTempDownloadPath,
10
+ } from "openclaw/plugin-sdk/temp-path";
11
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
12
+ import type { ClawdbotConfig } from "../runtime-api.js";
13
+ import { resolveFeishuRuntimeAccount } from "./accounts.js";
6
14
  import { createFeishuClient } from "./client.js";
15
+ import { requestFeishuApi } from "./comment-shared.js";
7
16
  import { normalizeFeishuExternalKey } from "./external-keys.js";
8
17
  import { getFeishuRuntime } from "./runtime.js";
9
18
  import { assertFeishuMessageApiSuccess, toFeishuSendResult } from "./send-result.js";
10
19
  import { resolveFeishuSendTarget } from "./send-target.js";
11
20
 
12
21
  const FEISHU_MEDIA_HTTP_TIMEOUT_MS = 120_000;
22
+ const FEISHU_VOICE_FILE_NAME = "voice.ogg";
23
+ const FEISHU_VOICE_SAMPLE_RATE_HZ = 48_000;
24
+ const FEISHU_VOICE_BITRATE = "64k";
25
+
26
+ const FEISHU_TRANSCODABLE_AUDIO_EXTS = new Set([
27
+ ".aac",
28
+ ".aiff",
29
+ ".alac",
30
+ ".amr",
31
+ ".caf",
32
+ ".flac",
33
+ ".m4a",
34
+ ".mp3",
35
+ ".oga",
36
+ ".wav",
37
+ ".webm",
38
+ ".wma",
39
+ ]);
13
40
 
14
41
  export type DownloadImageResult = {
15
42
  buffer: Buffer;
@@ -23,10 +50,10 @@ export type DownloadMessageResourceResult = {
23
50
  };
24
51
 
25
52
  function createConfiguredFeishuMediaClient(params: { cfg: ClawdbotConfig; accountId?: string }): {
26
- account: ReturnType<typeof resolveFeishuAccount>;
53
+ account: ReturnType<typeof resolveFeishuRuntimeAccount>;
27
54
  client: ReturnType<typeof createFeishuClient>;
28
55
  } {
29
- const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
56
+ const account = resolveFeishuRuntimeAccount({ cfg: params.cfg, accountId: params.accountId });
30
57
  if (!account.configured) {
31
58
  throw new Error(`Feishu account "${account.accountId}" not configured`);
32
59
  }
@@ -40,83 +67,235 @@ function createConfiguredFeishuMediaClient(params: { cfg: ClawdbotConfig; accoun
40
67
  };
41
68
  }
42
69
 
70
+ type FeishuUploadResponse =
71
+ | Awaited<ReturnType<Lark.Client["im"]["image"]["create"]>>
72
+ | Awaited<ReturnType<Lark.Client["im"]["file"]["create"]>>;
73
+
74
+ type FeishuDownloadResponse =
75
+ | Awaited<ReturnType<Lark.Client["im"]["image"]["get"]>>
76
+ | Awaited<ReturnType<Lark.Client["im"]["file"]["get"]>>
77
+ | Awaited<ReturnType<Lark.Client["im"]["messageResource"]["get"]>>;
78
+
79
+ type FeishuHeaderMap = Record<string, string | string[]>;
80
+ type FeishuMessageResourceDownloadType = "image" | "file" | "media";
81
+
82
+ function asHeaderMap(value: object | undefined): FeishuHeaderMap | undefined {
83
+ if (!value) {
84
+ return undefined;
85
+ }
86
+ const entries = Object.entries(value);
87
+ if (entries.every(([, entry]) => typeof entry === "string" || Array.isArray(entry))) {
88
+ return Object.fromEntries(entries) as FeishuHeaderMap;
89
+ }
90
+ return undefined;
91
+ }
92
+
43
93
  function extractFeishuUploadKey(
44
- response: unknown,
94
+ response: FeishuUploadResponse,
45
95
  params: {
46
96
  key: "image_key" | "file_key";
47
97
  errorPrefix: string;
48
98
  },
49
99
  ): string {
50
- // SDK v1.30+ returns data directly without code wrapper on success.
51
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK response type
52
- const responseAny = response as any;
53
- if (responseAny.code !== undefined && responseAny.code !== 0) {
54
- throw new Error(`${params.errorPrefix}: ${responseAny.msg || `code ${responseAny.code}`}`);
100
+ if (!response) {
101
+ throw new Error(`${params.errorPrefix}: empty response`);
55
102
  }
56
103
 
57
- const key = responseAny[params.key] ?? responseAny.data?.[params.key];
104
+ const wrappedResponse = response as {
105
+ image_key?: string;
106
+ file_key?: string;
107
+ code?: number;
108
+ msg?: string;
109
+ data?: Partial<Record<"image_key" | "file_key", string>>;
110
+ };
111
+ if (wrappedResponse.code !== undefined && wrappedResponse.code !== 0) {
112
+ throw new Error(
113
+ `${params.errorPrefix}: ${wrappedResponse.msg || `code ${wrappedResponse.code}`}`,
114
+ );
115
+ }
116
+
117
+ const key =
118
+ params.key === "image_key"
119
+ ? (wrappedResponse.image_key ?? wrappedResponse.data?.image_key)
120
+ : (wrappedResponse.file_key ?? wrappedResponse.data?.file_key);
58
121
  if (!key) {
59
122
  throw new Error(`${params.errorPrefix}: no ${params.key} returned`);
60
123
  }
61
124
  return key;
62
125
  }
63
126
 
127
+ function readHeaderValue(
128
+ headers: Record<string, unknown> | undefined,
129
+ name: string,
130
+ ): string | undefined {
131
+ if (!headers) {
132
+ return undefined;
133
+ }
134
+ for (const [key, value] of Object.entries(headers)) {
135
+ if (normalizeLowercaseStringOrEmpty(key) !== normalizeLowercaseStringOrEmpty(name)) {
136
+ continue;
137
+ }
138
+ if (typeof value === "string" && value.trim()) {
139
+ return value.trim();
140
+ }
141
+ if (Array.isArray(value)) {
142
+ const first = value.find((entry) => typeof entry === "string" && entry.trim());
143
+ if (typeof first === "string") {
144
+ return first.trim();
145
+ }
146
+ }
147
+ }
148
+ return undefined;
149
+ }
150
+
151
+ function readHttpStatusFromError(error: unknown): number | undefined {
152
+ if (!error || typeof error !== "object") {
153
+ return undefined;
154
+ }
155
+
156
+ const response = (error as { response?: unknown }).response;
157
+ if (response && typeof response === "object") {
158
+ const status = (response as { status?: unknown }).status;
159
+ if (typeof status === "number") {
160
+ return status;
161
+ }
162
+ }
163
+
164
+ const status = (error as { status?: unknown }).status;
165
+ return typeof status === "number" ? status : undefined;
166
+ }
167
+
168
+ function isHttpStatusError(error: unknown, status: number): boolean {
169
+ return readHttpStatusFromError(error) === status;
170
+ }
171
+
172
+ function containsEastAsianScript(value: string): boolean {
173
+ return /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(value);
174
+ }
175
+
176
+ function recoverUtf8FileNameFromLatin1Header(value: string): string {
177
+ const recovered = Buffer.from(value, "latin1").toString("utf8");
178
+ if (recovered !== value && !recovered.includes("\uFFFD") && containsEastAsianScript(recovered)) {
179
+ return recovered;
180
+ }
181
+ return value;
182
+ }
183
+
184
+ function decodeDispositionFileName(value: string): string | undefined {
185
+ const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
186
+ if (utf8Match?.[1]) {
187
+ try {
188
+ return decodeURIComponent(utf8Match[1].trim().replace(/^"(.*)"$/, "$1"));
189
+ } catch {
190
+ return utf8Match[1].trim().replace(/^"(.*)"$/, "$1");
191
+ }
192
+ }
193
+
194
+ const plainMatch = value.match(/filename="?([^";]+)"?/i);
195
+ const plainFileName = plainMatch?.[1]?.trim();
196
+ return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : undefined;
197
+ }
198
+
199
+ function extractFeishuDownloadMetadata(response: FeishuDownloadResponse): {
200
+ contentType?: string;
201
+ fileName?: string;
202
+ } {
203
+ const responseWithOptionalFields = response as FeishuDownloadResponse & {
204
+ header?: object;
205
+ contentType?: string;
206
+ mime_type?: string;
207
+ data?: {
208
+ contentType?: string;
209
+ mime_type?: string;
210
+ file_name?: string;
211
+ fileName?: string;
212
+ };
213
+ file_name?: string;
214
+ fileName?: string;
215
+ };
216
+ const headers =
217
+ asHeaderMap(responseWithOptionalFields.headers) ??
218
+ asHeaderMap(responseWithOptionalFields.header);
219
+
220
+ const contentType =
221
+ readHeaderValue(headers, "content-type") ??
222
+ responseWithOptionalFields.contentType ??
223
+ responseWithOptionalFields.mime_type ??
224
+ responseWithOptionalFields.data?.contentType ??
225
+ responseWithOptionalFields.data?.mime_type;
226
+
227
+ const disposition = readHeaderValue(headers, "content-disposition");
228
+ const fileName =
229
+ (disposition ? decodeDispositionFileName(disposition) : undefined) ??
230
+ responseWithOptionalFields.file_name ??
231
+ responseWithOptionalFields.fileName ??
232
+ responseWithOptionalFields.data?.file_name ??
233
+ responseWithOptionalFields.data?.fileName;
234
+
235
+ return { contentType, fileName };
236
+ }
237
+
238
+ async function readReadableBuffer(stream: Readable): Promise<Buffer> {
239
+ const chunks: Buffer[] = [];
240
+ for await (const chunk of stream) {
241
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
242
+ }
243
+ return Buffer.concat(chunks);
244
+ }
245
+
64
246
  async function readFeishuResponseBuffer(params: {
65
- response: unknown;
247
+ response: FeishuDownloadResponse;
66
248
  tmpDirPrefix: string;
67
249
  errorPrefix: string;
68
250
  }): Promise<Buffer> {
69
251
  const { response } = params;
70
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK response type
71
- const responseAny = response as any;
72
- if (responseAny.code !== undefined && responseAny.code !== 0) {
73
- throw new Error(`${params.errorPrefix}: ${responseAny.msg || `code ${responseAny.code}`}`);
74
- }
75
-
76
252
  if (Buffer.isBuffer(response)) {
77
253
  return response;
78
254
  }
79
255
  if (response instanceof ArrayBuffer) {
80
256
  return Buffer.from(response);
81
257
  }
82
- if (responseAny.data && Buffer.isBuffer(responseAny.data)) {
83
- return responseAny.data;
258
+ const responseWithOptionalFields = response as FeishuDownloadResponse & {
259
+ code?: number;
260
+ msg?: string;
261
+ data?: Buffer | ArrayBuffer;
262
+ [Symbol.asyncIterator]?: () => AsyncIterator<Buffer | Uint8Array | string>;
263
+ };
264
+ if (responseWithOptionalFields.code !== undefined && responseWithOptionalFields.code !== 0) {
265
+ throw new Error(
266
+ `${params.errorPrefix}: ${responseWithOptionalFields.msg || `code ${responseWithOptionalFields.code}`}`,
267
+ );
84
268
  }
85
- if (responseAny.data instanceof ArrayBuffer) {
86
- return Buffer.from(responseAny.data);
269
+
270
+ if (responseWithOptionalFields.data && Buffer.isBuffer(responseWithOptionalFields.data)) {
271
+ return responseWithOptionalFields.data;
87
272
  }
88
- if (typeof responseAny.getReadableStream === "function") {
89
- const stream = responseAny.getReadableStream();
90
- const chunks: Buffer[] = [];
91
- for await (const chunk of stream) {
92
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
93
- }
94
- return Buffer.concat(chunks);
273
+ if (responseWithOptionalFields.data instanceof ArrayBuffer) {
274
+ return Buffer.from(responseWithOptionalFields.data);
275
+ }
276
+ if (typeof response.getReadableStream === "function") {
277
+ return readReadableBuffer(response.getReadableStream());
95
278
  }
96
- if (typeof responseAny.writeFile === "function") {
279
+ if (typeof response.writeFile === "function") {
97
280
  return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
98
- await responseAny.writeFile(tmpPath);
281
+ await response.writeFile(tmpPath);
99
282
  return await fs.promises.readFile(tmpPath);
100
283
  });
101
284
  }
102
- if (typeof responseAny[Symbol.asyncIterator] === "function") {
285
+ if (responseWithOptionalFields[Symbol.asyncIterator]) {
286
+ const asyncIterable = responseWithOptionalFields as AsyncIterable<Buffer | Uint8Array | string>;
103
287
  const chunks: Buffer[] = [];
104
- for await (const chunk of responseAny) {
288
+ for await (const chunk of asyncIterable) {
105
289
  chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
106
290
  }
107
291
  return Buffer.concat(chunks);
108
292
  }
109
- if (typeof responseAny.read === "function") {
110
- const chunks: Buffer[] = [];
111
- for await (const chunk of responseAny as Readable) {
112
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
113
- }
114
- return Buffer.concat(chunks);
293
+ if (response instanceof Readable) {
294
+ return readReadableBuffer(response);
115
295
  }
116
296
 
117
- const keys = Object.keys(responseAny);
118
- const types = keys.map((k) => `${k}: ${typeof responseAny[k]}`).join(", ");
119
- throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${types}]`);
297
+ const keys = Object.keys(response as object);
298
+ throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${keys.join(", ")}]`);
120
299
  }
121
300
 
122
301
  /**
@@ -144,7 +323,27 @@ export async function downloadImageFeishu(params: {
144
323
  tmpDirPrefix: "openclaw-feishu-img-",
145
324
  errorPrefix: "Feishu image download failed",
146
325
  });
147
- return { buffer };
326
+ const meta = extractFeishuDownloadMetadata(response);
327
+ return { buffer, contentType: meta.contentType };
328
+ }
329
+
330
+ async function downloadMessageResourceWithType(params: {
331
+ client: ReturnType<typeof createFeishuClient>;
332
+ messageId: string;
333
+ fileKey: string;
334
+ type: FeishuMessageResourceDownloadType;
335
+ }): Promise<DownloadMessageResourceResult> {
336
+ const response = await params.client.im.messageResource.get({
337
+ path: { message_id: params.messageId, file_key: params.fileKey },
338
+ params: { type: params.type },
339
+ });
340
+
341
+ const buffer = await readFeishuResponseBuffer({
342
+ response,
343
+ tmpDirPrefix: "openclaw-feishu-resource-",
344
+ errorPrefix: "Feishu message resource download failed",
345
+ });
346
+ return { buffer, ...extractFeishuDownloadMetadata(response) };
148
347
  }
149
348
 
150
349
  /**
@@ -165,17 +364,28 @@ export async function downloadMessageResourceFeishu(params: {
165
364
  }
166
365
  const { client } = createConfiguredFeishuMediaClient({ cfg, accountId });
167
366
 
168
- const response = await client.im.messageResource.get({
169
- path: { message_id: messageId, file_key: normalizedFileKey },
170
- params: { type },
171
- });
172
-
173
- const buffer = await readFeishuResponseBuffer({
174
- response,
175
- tmpDirPrefix: "openclaw-feishu-resource-",
176
- errorPrefix: "Feishu message resource download failed",
177
- });
178
- return { buffer };
367
+ try {
368
+ return await downloadMessageResourceWithType({
369
+ client,
370
+ messageId,
371
+ fileKey: normalizedFileKey,
372
+ type,
373
+ });
374
+ } catch (err) {
375
+ if (type !== "file" || !isHttpStatusError(err, 502)) {
376
+ throw err;
377
+ }
378
+ try {
379
+ return await downloadMessageResourceWithType({
380
+ client,
381
+ messageId,
382
+ fileKey: normalizedFileKey,
383
+ type: "media",
384
+ });
385
+ } catch {
386
+ throw err;
387
+ }
388
+ }
179
389
  }
180
390
 
181
391
  export type UploadImageResult = {
@@ -209,13 +419,17 @@ export async function uploadImageFeishu(params: {
209
419
  // See: https://github.com/larksuite/node-sdk/issues/121
210
420
  const imageData = typeof image === "string" ? fs.createReadStream(image) : image;
211
421
 
212
- const response = await client.im.image.create({
213
- data: {
214
- image_type: imageType,
215
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK accepts Buffer or ReadStream
216
- image: imageData as any,
217
- },
218
- });
422
+ const response = await requestFeishuApi(
423
+ () =>
424
+ client.im.image.create({
425
+ data: {
426
+ image_type: imageType,
427
+ image: imageData,
428
+ },
429
+ }),
430
+ "Feishu image upload failed",
431
+ { includeNestedErrorLogId: true },
432
+ );
219
433
 
220
434
  return {
221
435
  imageKey: extractFeishuUploadKey(response, {
@@ -236,7 +450,7 @@ export async function uploadImageFeishu(params: {
236
450
  * in chat (regression in v2026.3.2).
237
451
  */
238
452
  export function sanitizeFileNameForUpload(fileName: string): string {
239
- return fileName.replace(/[\x00-\x1F\x7F\r\n"\\]/g, "_");
453
+ return fileName.replace(/[\p{Cc}"\\]/gu, "_");
240
454
  }
241
455
 
242
456
  /**
@@ -261,15 +475,19 @@ export async function uploadFileFeishu(params: {
261
475
 
262
476
  const safeFileName = sanitizeFileNameForUpload(fileName);
263
477
 
264
- const response = await client.im.file.create({
265
- data: {
266
- file_type: fileType,
267
- file_name: safeFileName,
268
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK accepts Buffer or ReadStream
269
- file: fileData as any,
270
- ...(duration !== undefined && { duration }),
271
- },
272
- });
478
+ const response = await requestFeishuApi(
479
+ () =>
480
+ client.im.file.create({
481
+ data: {
482
+ file_type: fileType,
483
+ file_name: safeFileName,
484
+ file: fileData,
485
+ ...(duration !== undefined && { duration }),
486
+ },
487
+ }),
488
+ "Feishu file upload failed",
489
+ { includeNestedErrorLogId: true },
490
+ );
273
491
 
274
492
  return {
275
493
  fileKey: extractFeishuUploadKey(response, {
@@ -299,26 +517,36 @@ export async function sendImageFeishu(params: {
299
517
  const content = JSON.stringify({ image_key: imageKey });
300
518
 
301
519
  if (replyToMessageId) {
302
- const response = await client.im.message.reply({
303
- path: { message_id: replyToMessageId },
304
- data: {
305
- content,
306
- msg_type: "image",
307
- ...(replyInThread ? { reply_in_thread: true } : {}),
308
- },
309
- });
520
+ const response = await requestFeishuApi(
521
+ () =>
522
+ client.im.message.reply({
523
+ path: { message_id: replyToMessageId },
524
+ data: {
525
+ content,
526
+ msg_type: "image",
527
+ ...(replyInThread ? { reply_in_thread: true } : {}),
528
+ },
529
+ }),
530
+ "Feishu image reply failed",
531
+ { includeNestedErrorLogId: true },
532
+ );
310
533
  assertFeishuMessageApiSuccess(response, "Feishu image reply failed");
311
534
  return toFeishuSendResult(response, receiveId);
312
535
  }
313
536
 
314
- const response = await client.im.message.create({
315
- params: { receive_id_type: receiveIdType },
316
- data: {
317
- receive_id: receiveId,
318
- content,
319
- msg_type: "image",
320
- },
321
- });
537
+ const response = await requestFeishuApi(
538
+ () =>
539
+ client.im.message.create({
540
+ params: { receive_id_type: receiveIdType },
541
+ data: {
542
+ receive_id: receiveId,
543
+ content,
544
+ msg_type: "image",
545
+ },
546
+ }),
547
+ "Feishu image send failed",
548
+ { includeNestedErrorLogId: true },
549
+ );
322
550
  assertFeishuMessageApiSuccess(response, "Feishu image send failed");
323
551
  return toFeishuSendResult(response, receiveId);
324
552
  }
@@ -346,26 +574,36 @@ export async function sendFileFeishu(params: {
346
574
  const content = JSON.stringify({ file_key: fileKey });
347
575
 
348
576
  if (replyToMessageId) {
349
- const response = await client.im.message.reply({
350
- path: { message_id: replyToMessageId },
351
- data: {
352
- content,
353
- msg_type: msgType,
354
- ...(replyInThread ? { reply_in_thread: true } : {}),
355
- },
356
- });
577
+ const response = await requestFeishuApi(
578
+ () =>
579
+ client.im.message.reply({
580
+ path: { message_id: replyToMessageId },
581
+ data: {
582
+ content,
583
+ msg_type: msgType,
584
+ ...(replyInThread ? { reply_in_thread: true } : {}),
585
+ },
586
+ }),
587
+ "Feishu file reply failed",
588
+ { includeNestedErrorLogId: true },
589
+ );
357
590
  assertFeishuMessageApiSuccess(response, "Feishu file reply failed");
358
591
  return toFeishuSendResult(response, receiveId);
359
592
  }
360
593
 
361
- const response = await client.im.message.create({
362
- params: { receive_id_type: receiveIdType },
363
- data: {
364
- receive_id: receiveId,
365
- content,
366
- msg_type: msgType,
367
- },
368
- });
594
+ const response = await requestFeishuApi(
595
+ () =>
596
+ client.im.message.create({
597
+ params: { receive_id_type: receiveIdType },
598
+ data: {
599
+ receive_id: receiveId,
600
+ content,
601
+ msg_type: msgType,
602
+ },
603
+ }),
604
+ "Feishu file send failed",
605
+ { includeNestedErrorLogId: true },
606
+ );
369
607
  assertFeishuMessageApiSuccess(response, "Feishu file send failed");
370
608
  return toFeishuSendResult(response, receiveId);
371
609
  }
@@ -376,7 +614,7 @@ export async function sendFileFeishu(params: {
376
614
  export function detectFileType(
377
615
  fileName: string,
378
616
  ): "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream" {
379
- const ext = path.extname(fileName).toLowerCase();
617
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(fileName));
380
618
  switch (ext) {
381
619
  case ".opus":
382
620
  case ".ogg":
@@ -401,6 +639,136 @@ export function detectFileType(
401
639
  }
402
640
  }
403
641
 
642
+ function resolveFeishuOutboundMediaKind(params: { fileName: string; contentType?: string }): {
643
+ fileType?: "opus" | "mp4" | "pdf" | "doc" | "xls" | "ppt" | "stream";
644
+ msgType: "image" | "file" | "audio" | "media";
645
+ } {
646
+ const { fileName, contentType } = params;
647
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(fileName));
648
+ const mimeKind = mediaKindFromMime(contentType);
649
+
650
+ const isImageExt = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(
651
+ ext,
652
+ );
653
+ if (isImageExt || mimeKind === "image") {
654
+ return { msgType: "image" };
655
+ }
656
+
657
+ if (
658
+ ext === ".opus" ||
659
+ ext === ".ogg" ||
660
+ contentType === "audio/ogg" ||
661
+ contentType === "audio/opus"
662
+ ) {
663
+ return { fileType: "opus", msgType: "audio" };
664
+ }
665
+
666
+ if (
667
+ [".mp4", ".mov", ".avi"].includes(ext) ||
668
+ contentType === "video/mp4" ||
669
+ contentType === "video/quicktime" ||
670
+ contentType === "video/x-msvideo"
671
+ ) {
672
+ return { fileType: "mp4", msgType: "media" };
673
+ }
674
+
675
+ const fileType = detectFileType(fileName);
676
+ return {
677
+ fileType,
678
+ msgType:
679
+ fileType === "stream"
680
+ ? "file"
681
+ : fileType === "opus"
682
+ ? "audio"
683
+ : fileType === "mp4"
684
+ ? "media"
685
+ : "file",
686
+ };
687
+ }
688
+
689
+ function isFeishuNativeVoiceAudio(params: { fileName: string; contentType?: string }): boolean {
690
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
691
+ const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
692
+ return (
693
+ ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus"
694
+ );
695
+ }
696
+
697
+ function isLikelyTranscodableAudio(params: { fileName: string; contentType?: string }): boolean {
698
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
699
+ const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
700
+ return FEISHU_TRANSCODABLE_AUDIO_EXTS.has(ext) || mediaKindFromMime(contentType) === "audio";
701
+ }
702
+
703
+ async function transcodeToFeishuVoiceOpus(params: {
704
+ buffer: Buffer;
705
+ fileName: string;
706
+ contentType?: string;
707
+ }): Promise<{ buffer: Buffer; fileName: string; contentType: string }> {
708
+ const tempRoot = resolvePreferredOpenClawTmpDir();
709
+ await fs.promises.mkdir(tempRoot, { recursive: true, mode: 0o700 });
710
+ const tempDir = await fs.promises.mkdtemp(path.join(tempRoot, "feishu-voice-"));
711
+ try {
712
+ const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
713
+ const inputExt = ext && ext.length <= 12 ? ext : ".audio";
714
+ const inputPath = path.join(tempDir, `input${inputExt}`);
715
+ const outputPath = path.join(tempDir, FEISHU_VOICE_FILE_NAME);
716
+ await fs.promises.writeFile(inputPath, params.buffer, { mode: 0o600 });
717
+ await runFfmpeg([
718
+ "-hide_banner",
719
+ "-loglevel",
720
+ "error",
721
+ "-y",
722
+ "-i",
723
+ inputPath,
724
+ "-vn",
725
+ "-sn",
726
+ "-dn",
727
+ "-t",
728
+ String(MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS),
729
+ "-ar",
730
+ String(FEISHU_VOICE_SAMPLE_RATE_HZ),
731
+ "-ac",
732
+ "1",
733
+ "-c:a",
734
+ "libopus",
735
+ "-b:a",
736
+ FEISHU_VOICE_BITRATE,
737
+ outputPath,
738
+ ]);
739
+ return {
740
+ buffer: await fs.promises.readFile(outputPath),
741
+ fileName: FEISHU_VOICE_FILE_NAME,
742
+ contentType: "audio/ogg",
743
+ };
744
+ } finally {
745
+ await fs.promises.rm(tempDir, { recursive: true, force: true });
746
+ }
747
+ }
748
+
749
+ async function prepareFeishuVoiceMedia(params: {
750
+ buffer: Buffer;
751
+ fileName: string;
752
+ contentType?: string;
753
+ audioAsVoice?: boolean;
754
+ }): Promise<{ buffer: Buffer; fileName: string; contentType?: string }> {
755
+ if (isFeishuNativeVoiceAudio(params)) {
756
+ return params;
757
+ }
758
+ if (params.audioAsVoice !== true || !isLikelyTranscodableAudio(params)) {
759
+ return params;
760
+ }
761
+ try {
762
+ return await transcodeToFeishuVoiceOpus(params);
763
+ } catch (err) {
764
+ console.warn(
765
+ `[feishu] audioAsVoice transcode failed; sending ${params.fileName} as a file attachment:`,
766
+ err,
767
+ );
768
+ return params;
769
+ }
770
+ }
771
+
404
772
  /**
405
773
  * Upload and send media (image or file) from URL, local path, or buffer.
406
774
  * When mediaUrl is a local path, mediaLocalRoots (from core outbound context)
@@ -417,6 +785,8 @@ export async function sendMediaFeishu(params: {
417
785
  accountId?: string;
418
786
  /** Allowed roots for local path reads; required for local filePath to work. */
419
787
  mediaLocalRoots?: readonly string[];
788
+ /** When true, transcode compatible audio to Feishu native Ogg/Opus voice bubbles. */
789
+ audioAsVoice?: boolean;
420
790
  }): Promise<SendMediaResult> {
421
791
  const {
422
792
  cfg,
@@ -428,8 +798,9 @@ export async function sendMediaFeishu(params: {
428
798
  replyInThread,
429
799
  accountId,
430
800
  mediaLocalRoots,
801
+ audioAsVoice,
431
802
  } = params;
432
- const account = resolveFeishuAccount({ cfg, accountId });
803
+ const account = resolveFeishuRuntimeAccount({ cfg, accountId });
433
804
  if (!account.configured) {
434
805
  throw new Error(`Feishu account "${account.accountId}" not configured`);
435
806
  }
@@ -437,6 +808,7 @@ export async function sendMediaFeishu(params: {
437
808
 
438
809
  let buffer: Buffer;
439
810
  let name: string;
811
+ let contentType: string | undefined;
440
812
 
441
813
  if (mediaBuffer) {
442
814
  buffer = mediaBuffer;
@@ -449,36 +821,41 @@ export async function sendMediaFeishu(params: {
449
821
  });
450
822
  buffer = loaded.buffer;
451
823
  name = fileName ?? loaded.fileName ?? "file";
824
+ contentType = loaded.contentType;
452
825
  } else {
453
826
  throw new Error("Either mediaUrl or mediaBuffer must be provided");
454
827
  }
455
828
 
456
- // Determine if it's an image based on extension
457
- const ext = path.extname(name).toLowerCase();
458
- const isImage = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".ico", ".tiff"].includes(ext);
829
+ const prepared = await prepareFeishuVoiceMedia({
830
+ buffer,
831
+ fileName: name,
832
+ contentType,
833
+ audioAsVoice,
834
+ });
835
+ buffer = prepared.buffer;
836
+ name = prepared.fileName;
837
+ contentType = prepared.contentType;
838
+
839
+ const routing = resolveFeishuOutboundMediaKind({ fileName: name, contentType });
459
840
 
460
- if (isImage) {
841
+ if (routing.msgType === "image") {
461
842
  const { imageKey } = await uploadImageFeishu({ cfg, image: buffer, accountId });
462
843
  return sendImageFeishu({ cfg, to, imageKey, replyToMessageId, replyInThread, accountId });
463
- } else {
464
- const fileType = detectFileType(name);
465
- const { fileKey } = await uploadFileFeishu({
466
- cfg,
467
- file: buffer,
468
- fileName: name,
469
- fileType,
470
- accountId,
471
- });
472
- // Feishu API: opus -> "audio", mp4/video -> "media" (playable), others -> "file"
473
- const msgType = fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file";
474
- return sendFileFeishu({
475
- cfg,
476
- to,
477
- fileKey,
478
- msgType,
479
- replyToMessageId,
480
- replyInThread,
481
- accountId,
482
- });
483
844
  }
845
+ const { fileKey } = await uploadFileFeishu({
846
+ cfg,
847
+ file: buffer,
848
+ fileName: name,
849
+ fileType: routing.fileType ?? "stream",
850
+ accountId,
851
+ });
852
+ return sendFileFeishu({
853
+ cfg,
854
+ to,
855
+ fileKey,
856
+ msgType: routing.msgType,
857
+ replyToMessageId,
858
+ replyInThread,
859
+ accountId,
860
+ });
484
861
  }