@kodelyth/feishu 2026.5.42 → 2026.6.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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
package/src/media.test.ts DELETED
@@ -1,955 +0,0 @@
1
- import { realpathSync } from "node:fs";
2
- import fs from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { Readable } from "node:stream";
6
- import { resolvePreferredKlawTmpDir } from "klaw/plugin-sdk/temp-path";
7
- import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
8
- import type { ClawdbotConfig } from "../runtime-api.js";
9
-
10
- const createFeishuClientMock = vi.hoisted(() => vi.fn());
11
- const resolveFeishuAccountMock = vi.hoisted(() => vi.fn());
12
- const normalizeFeishuTargetMock = vi.hoisted(() => vi.fn());
13
- const resolveReceiveIdTypeMock = vi.hoisted(() => vi.fn());
14
- const loadWebMediaMock = vi.hoisted(() => vi.fn());
15
- const runFfmpegMock = vi.hoisted(() => vi.fn());
16
-
17
- const fileCreateMock = vi.hoisted(() => vi.fn());
18
- const imageCreateMock = vi.hoisted(() => vi.fn());
19
- const imageGetMock = vi.hoisted(() => vi.fn());
20
- const messageCreateMock = vi.hoisted(() => vi.fn());
21
- const messageResourceGetMock = vi.hoisted(() => vi.fn());
22
- const messageReplyMock = vi.hoisted(() => vi.fn());
23
-
24
- const FEISHU_MEDIA_HTTP_TIMEOUT_MS = 120_000;
25
- const emptyConfig: ClawdbotConfig = {};
26
-
27
- vi.mock("./client.js", () => ({
28
- createFeishuClient: createFeishuClientMock,
29
- }));
30
-
31
- vi.mock("./accounts.js", () => ({
32
- resolveFeishuAccount: resolveFeishuAccountMock,
33
- resolveFeishuRuntimeAccount: resolveFeishuAccountMock,
34
- }));
35
-
36
- vi.mock("./targets.js", () => ({
37
- normalizeFeishuTarget: normalizeFeishuTargetMock,
38
- resolveReceiveIdType: resolveReceiveIdTypeMock,
39
- }));
40
-
41
- vi.mock("./runtime.js", () => ({
42
- getFeishuRuntime: () => ({
43
- media: {
44
- loadWebMedia: loadWebMediaMock,
45
- },
46
- }),
47
- }));
48
-
49
- vi.mock("klaw/plugin-sdk/media-runtime", async (importOriginal) => {
50
- const actual = await importOriginal<typeof import("klaw/plugin-sdk/media-runtime")>();
51
- return {
52
- ...actual,
53
- runFfmpeg: runFfmpegMock,
54
- };
55
- });
56
-
57
- let downloadImageFeishu: typeof import("./media.js").downloadImageFeishu;
58
- let downloadMessageResourceFeishu: typeof import("./media.js").downloadMessageResourceFeishu;
59
- let saveMessageResourceFeishu: typeof import("./media.js").saveMessageResourceFeishu;
60
- let sanitizeFileNameForUpload: typeof import("./media.js").sanitizeFileNameForUpload;
61
- let sendMediaFeishu: typeof import("./media.js").sendMediaFeishu;
62
- let shouldSuppressFeishuTextForVoiceMedia: typeof import("./media.js").shouldSuppressFeishuTextForVoiceMedia;
63
-
64
- function expectPathIsolatedToTmpRoot(pathValue: string, key: string): void {
65
- expect(pathValue).not.toContain(key);
66
- expect(pathValue).not.toContain("..");
67
-
68
- const tmpRoot = realpathSync(resolvePreferredKlawTmpDir());
69
- const resolved = path.resolve(pathValue);
70
- const rel = path.relative(tmpRoot, resolved);
71
- expect(rel === ".." || rel.startsWith(`..${path.sep}`)).toBe(false);
72
- }
73
-
74
- function expectMediaTimeoutClientConfigured(): void {
75
- const options = mockCallArg<{ httpTimeoutMs?: number }>(createFeishuClientMock, 0, 0);
76
- expect(options.httpTimeoutMs).toBe(FEISHU_MEDIA_HTTP_TIMEOUT_MS);
77
- }
78
-
79
- function mockResolvedFeishuAccount() {
80
- resolveFeishuAccountMock.mockReturnValue({
81
- configured: true,
82
- accountId: "main",
83
- config: {},
84
- appId: "app_id",
85
- appSecret: "app_secret",
86
- domain: "feishu",
87
- });
88
- }
89
-
90
- function mockCallArg<T>(
91
- mock: { mock: { calls: unknown[][] } },
92
- callIndex: number,
93
- argIndex: number,
94
- _type?: (value: unknown) => value is T,
95
- ): T {
96
- const call = mock.mock.calls[callIndex];
97
- if (!call) {
98
- throw new Error(`Expected mock call at index ${callIndex}`);
99
- }
100
- return call[argIndex] as T;
101
- }
102
-
103
- function callData<T>(
104
- mock: { mock: { calls: unknown[][] } },
105
- callIndex = 0,
106
- _type?: (value: unknown) => value is T,
107
- ): T {
108
- const arg = mockCallArg<{ data?: unknown }>(mock, callIndex, 0);
109
- if (arg.data === undefined) {
110
- throw new Error(`Expected mock call data at index ${callIndex}`);
111
- }
112
- return arg.data as T;
113
- }
114
-
115
- describe("sendMediaFeishu msg_type routing", () => {
116
- beforeAll(async () => {
117
- ({
118
- downloadImageFeishu,
119
- downloadMessageResourceFeishu,
120
- saveMessageResourceFeishu,
121
- sanitizeFileNameForUpload,
122
- sendMediaFeishu,
123
- shouldSuppressFeishuTextForVoiceMedia,
124
- } = await import("./media.js"));
125
- });
126
-
127
- afterAll(() => {
128
- vi.doUnmock("./client.js");
129
- vi.doUnmock("./accounts.js");
130
- vi.doUnmock("./targets.js");
131
- vi.doUnmock("./runtime.js");
132
- vi.doUnmock("klaw/plugin-sdk/media-runtime");
133
- vi.resetModules();
134
- });
135
-
136
- beforeEach(() => {
137
- vi.clearAllMocks();
138
- mockResolvedFeishuAccount();
139
-
140
- normalizeFeishuTargetMock.mockReturnValue("ou_target");
141
- resolveReceiveIdTypeMock.mockReturnValue("open_id");
142
-
143
- createFeishuClientMock.mockReturnValue({
144
- im: {
145
- file: {
146
- create: fileCreateMock,
147
- },
148
- image: {
149
- create: imageCreateMock,
150
- get: imageGetMock,
151
- },
152
- message: {
153
- create: messageCreateMock,
154
- reply: messageReplyMock,
155
- },
156
- messageResource: {
157
- get: messageResourceGetMock,
158
- },
159
- },
160
- });
161
-
162
- fileCreateMock.mockResolvedValue({
163
- code: 0,
164
- data: { file_key: "file_key_1" },
165
- });
166
- imageCreateMock.mockResolvedValue({
167
- code: 0,
168
- data: { image_key: "image_key_1" },
169
- });
170
-
171
- messageCreateMock.mockResolvedValue({
172
- code: 0,
173
- data: { message_id: "msg_1" },
174
- });
175
-
176
- messageReplyMock.mockResolvedValue({
177
- code: 0,
178
- data: { message_id: "reply_1" },
179
- });
180
-
181
- loadWebMediaMock.mockResolvedValue({
182
- buffer: Buffer.from("remote-audio"),
183
- fileName: "remote.opus",
184
- kind: "audio",
185
- contentType: "audio/ogg",
186
- });
187
-
188
- imageGetMock.mockResolvedValue(Buffer.from("image-bytes"));
189
- messageResourceGetMock.mockResolvedValue(Buffer.from("resource-bytes"));
190
- runFfmpegMock.mockImplementation(async (args: string[]) => {
191
- await fs.writeFile(args.at(-1) ?? "", Buffer.from("opus-output"));
192
- return "";
193
- });
194
- });
195
-
196
- it("suppresses reply text only for voice-intent or native voice media", () => {
197
- expect(
198
- shouldSuppressFeishuTextForVoiceMedia({
199
- mediaUrl: "https://example.com/reply.mp3",
200
- audioAsVoice: true,
201
- }),
202
- ).toBe(true);
203
- expect(
204
- shouldSuppressFeishuTextForVoiceMedia({
205
- mediaUrl: "https://example.com/reply.ogg?download=1",
206
- }),
207
- ).toBe(true);
208
- expect(
209
- shouldSuppressFeishuTextForVoiceMedia({
210
- mediaUrl: "https://example.com/song.mp3",
211
- }),
212
- ).toBe(false);
213
- });
214
-
215
- it("uses msg_type=media for mp4 video", async () => {
216
- await sendMediaFeishu({
217
- cfg: emptyConfig,
218
- to: "user:ou_target",
219
- mediaBuffer: Buffer.from("video"),
220
- fileName: "clip.mp4",
221
- });
222
-
223
- expect(callData<{ file_type?: string }>(fileCreateMock).file_type).toBe("mp4");
224
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("media");
225
- });
226
-
227
- it("uses msg_type=audio for opus", async () => {
228
- await sendMediaFeishu({
229
- cfg: emptyConfig,
230
- to: "user:ou_target",
231
- mediaBuffer: Buffer.from("audio"),
232
- fileName: "voice.opus",
233
- });
234
-
235
- expect(callData<{ file_type?: string }>(fileCreateMock).file_type).toBe("opus");
236
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("audio");
237
- });
238
-
239
- it("uses msg_type=file for documents", async () => {
240
- await sendMediaFeishu({
241
- cfg: emptyConfig,
242
- to: "user:ou_target",
243
- mediaBuffer: Buffer.from("doc"),
244
- fileName: "paper.pdf",
245
- });
246
-
247
- expect(callData<{ file_type?: string }>(fileCreateMock).file_type).toBe("pdf");
248
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("file");
249
- });
250
-
251
- it("uses msg_type=media for remote mp4 content even when the filename is generic", async () => {
252
- loadWebMediaMock.mockResolvedValueOnce({
253
- buffer: Buffer.from("remote-video"),
254
- fileName: "download",
255
- kind: "video",
256
- contentType: "video/mp4",
257
- });
258
-
259
- await sendMediaFeishu({
260
- cfg: emptyConfig,
261
- to: "user:ou_target",
262
- mediaUrl: "https://example.com/video",
263
- });
264
-
265
- expect(callData<{ file_type?: string }>(fileCreateMock).file_type).toBe("mp4");
266
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("media");
267
- });
268
-
269
- it("falls back to generic file for unsupported audio formats", async () => {
270
- loadWebMediaMock.mockResolvedValueOnce({
271
- buffer: Buffer.from("remote-mp3"),
272
- fileName: "song.mp3",
273
- kind: "audio",
274
- contentType: "audio/mpeg",
275
- });
276
-
277
- await sendMediaFeishu({
278
- cfg: emptyConfig,
279
- to: "user:ou_target",
280
- mediaUrl: "https://example.com/song.mp3",
281
- });
282
-
283
- expect(callData<{ file_type?: string }>(fileCreateMock).file_type).toBe("stream");
284
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("file");
285
- expect(runFfmpegMock).not.toHaveBeenCalled();
286
- });
287
-
288
- it("transcodes voice-intent mp3 to msg_type=audio", async () => {
289
- loadWebMediaMock.mockResolvedValueOnce({
290
- buffer: Buffer.from("remote-mp3"),
291
- fileName: "reply.mp3",
292
- kind: "audio",
293
- contentType: "audio/mpeg",
294
- });
295
-
296
- await sendMediaFeishu({
297
- cfg: emptyConfig,
298
- to: "user:ou_target",
299
- mediaUrl: "https://example.com/reply.mp3",
300
- audioAsVoice: true,
301
- });
302
-
303
- const ffmpegArgs = mockCallArg<string[]>(runFfmpegMock, 0, 0);
304
- for (const arg of ["-c:a", "libopus", "-ar", "48000", "-b:a", "64k", "-f", "ogg"]) {
305
- expect(ffmpegArgs).toContain(arg);
306
- }
307
- expect(ffmpegArgs.slice(-3, -1)).toEqual(["-f", "ogg"]);
308
- const fileData = callData<{ file?: Buffer; file_name?: string; file_type?: string }>(
309
- fileCreateMock,
310
- );
311
- expect(fileData.file_type).toBe("opus");
312
- expect(fileData.file_name).toBe("voice.ogg");
313
- expect(fileData.file).toEqual(Buffer.from("opus-output"));
314
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("audio");
315
- });
316
-
317
- it("leaves native voice audio unchanged when audioAsVoice is true", async () => {
318
- await sendMediaFeishu({
319
- cfg: emptyConfig,
320
- to: "user:ou_target",
321
- mediaBuffer: Buffer.from("opus"),
322
- fileName: "reply.ogg",
323
- audioAsVoice: true,
324
- });
325
-
326
- expect(runFfmpegMock).not.toHaveBeenCalled();
327
- const fileData = callData<{ file_name?: string; file_type?: string }>(fileCreateMock);
328
- expect(fileData.file_type).toBe("opus");
329
- expect(fileData.file_name).toBe("reply.ogg");
330
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("audio");
331
- });
332
-
333
- it("falls back to file when voice-intent audio cannot be transcoded", async () => {
334
- const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
335
- runFfmpegMock.mockRejectedValueOnce(new Error("ffmpeg missing"));
336
- loadWebMediaMock.mockResolvedValueOnce({
337
- buffer: Buffer.from("remote-mp3"),
338
- fileName: "reply.mp3",
339
- kind: "audio",
340
- contentType: "audio/mpeg",
341
- });
342
-
343
- const result = await sendMediaFeishu({
344
- cfg: emptyConfig,
345
- to: "user:ou_target",
346
- mediaUrl: "https://example.com/reply.mp3",
347
- audioAsVoice: true,
348
- });
349
-
350
- const fileData = callData<{ file?: Buffer; file_name?: string; file_type?: string }>(
351
- fileCreateMock,
352
- );
353
- expect(fileData.file_type).toBe("stream");
354
- expect(fileData.file_name).toBe("reply.mp3");
355
- expect(fileData.file).toEqual(Buffer.from("remote-mp3"));
356
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("file");
357
- expect(result.voiceIntentDegradedToFile).toBe(true);
358
- expect(mockCallArg<string>(warnSpy, 0, 0)).toContain("audioAsVoice transcode failed");
359
- expect(mockCallArg<unknown>(warnSpy, 0, 1)).toBeInstanceOf(Error);
360
- warnSpy.mockRestore();
361
- });
362
-
363
- it("configures the media client timeout for image uploads", async () => {
364
- await sendMediaFeishu({
365
- cfg: emptyConfig,
366
- to: "user:ou_target",
367
- mediaBuffer: Buffer.from("image"),
368
- fileName: "photo.png",
369
- });
370
-
371
- expectMediaTimeoutClientConfigured();
372
- expect(callData<{ msg_type?: string }>(messageCreateMock).msg_type).toBe("image");
373
- });
374
-
375
- it("preserves Feishu diagnostics when media sends reject before response checks", async () => {
376
- messageCreateMock.mockRejectedValueOnce(
377
- Object.assign(new Error("Request failed with status code 400"), {
378
- response: {
379
- status: 400,
380
- data: {
381
- code: 9499,
382
- msg: "Bad Request",
383
- error: {
384
- log_id: "20260429124731MEDIA",
385
- troubleshooter: "https://open.feishu.cn/search?log_id=20260429124731MEDIA",
386
- },
387
- },
388
- },
389
- }),
390
- );
391
-
392
- const send = sendMediaFeishu({
393
- cfg: emptyConfig,
394
- to: "user:ou_target",
395
- mediaBuffer: Buffer.from("image"),
396
- fileName: "photo.png",
397
- });
398
-
399
- await expect(send).rejects.toThrow(/Feishu image send failed: .*"feishu_code":9499/);
400
- await expect(send).rejects.toThrow(/"feishu_log_id":"20260429124731MEDIA"/);
401
- });
402
-
403
- it("uses msg_type=media when replying with mp4", async () => {
404
- await sendMediaFeishu({
405
- cfg: emptyConfig,
406
- to: "user:ou_target",
407
- mediaBuffer: Buffer.from("video"),
408
- fileName: "reply.mp4",
409
- replyToMessageId: "om_parent",
410
- });
411
-
412
- const replyRequest = mockCallArg<{
413
- data?: { msg_type?: string };
414
- path?: { message_id?: string };
415
- }>(messageReplyMock, 0, 0);
416
- expect(replyRequest.path).toEqual({ message_id: "om_parent" });
417
- expect(replyRequest.data?.msg_type).toBe("media");
418
-
419
- expect(messageCreateMock).not.toHaveBeenCalled();
420
- });
421
-
422
- it("passes reply_in_thread when replyInThread is true", async () => {
423
- await sendMediaFeishu({
424
- cfg: emptyConfig,
425
- to: "user:ou_target",
426
- mediaBuffer: Buffer.from("video"),
427
- fileName: "reply.mp4",
428
- replyToMessageId: "om_parent",
429
- replyInThread: true,
430
- });
431
-
432
- const replyRequest = mockCallArg<{
433
- data?: { msg_type?: string; reply_in_thread?: boolean };
434
- path?: { message_id?: string };
435
- }>(messageReplyMock, 0, 0);
436
- expect(replyRequest.path).toEqual({ message_id: "om_parent" });
437
- expect(replyRequest.data?.msg_type).toBe("media");
438
- expect(replyRequest.data?.reply_in_thread).toBe(true);
439
- });
440
-
441
- it("omits reply_in_thread when replyInThread is false", async () => {
442
- await sendMediaFeishu({
443
- cfg: emptyConfig,
444
- to: "user:ou_target",
445
- mediaBuffer: Buffer.from("video"),
446
- fileName: "reply.mp4",
447
- replyToMessageId: "om_parent",
448
- replyInThread: false,
449
- });
450
-
451
- expect(callData<Record<string, unknown>>(messageReplyMock)).not.toHaveProperty(
452
- "reply_in_thread",
453
- );
454
- });
455
-
456
- it("passes mediaLocalRoots as localRoots to loadWebMedia for local paths (#27884)", async () => {
457
- loadWebMediaMock.mockResolvedValue({
458
- buffer: Buffer.from("local-file"),
459
- fileName: "doc.pdf",
460
- kind: "document",
461
- contentType: "application/pdf",
462
- });
463
-
464
- const roots = ["/allowed/workspace", "/tmp/klaw"];
465
- await sendMediaFeishu({
466
- cfg: emptyConfig,
467
- to: "user:ou_target",
468
- mediaUrl: "/allowed/workspace/file.pdf",
469
- mediaLocalRoots: roots,
470
- });
471
-
472
- expect(mockCallArg(loadWebMediaMock, 0, 0)).toBe("/allowed/workspace/file.pdf");
473
- const options = mockCallArg<{
474
- localRoots?: string[];
475
- maxBytes?: number;
476
- optimizeImages?: boolean;
477
- }>(loadWebMediaMock, 0, 1);
478
- expect(typeof options.maxBytes).toBe("number");
479
- expect(options.optimizeImages).toBe(false);
480
- expect(options.localRoots).toBe(roots);
481
- });
482
-
483
- it("fails closed when media URL fetch is blocked", async () => {
484
- loadWebMediaMock.mockRejectedValueOnce(
485
- new Error("Blocked: resolves to private/internal IP address"),
486
- );
487
-
488
- await expect(
489
- sendMediaFeishu({
490
- cfg: emptyConfig,
491
- to: "user:ou_target",
492
- mediaUrl: "https://x/img",
493
- fileName: "voice.opus",
494
- }),
495
- ).rejects.toThrow(/private\/internal/i);
496
-
497
- expect(fileCreateMock).not.toHaveBeenCalled();
498
- expect(messageCreateMock).not.toHaveBeenCalled();
499
- expect(messageReplyMock).not.toHaveBeenCalled();
500
- });
501
-
502
- it("uses isolated temp paths for image downloads", async () => {
503
- const imageKey = "img_v3_01abc123";
504
- let capturedPath: string | undefined;
505
-
506
- imageGetMock.mockResolvedValueOnce({
507
- writeFile: async (tmpPath: string) => {
508
- capturedPath = tmpPath;
509
- await fs.writeFile(tmpPath, Buffer.from("image-data"));
510
- },
511
- });
512
-
513
- const result = await downloadImageFeishu({
514
- cfg: emptyConfig,
515
- imageKey,
516
- });
517
-
518
- const request = mockCallArg<{ path?: { image_key?: string } }>(imageGetMock, 0, 0);
519
- expect(request.path).toEqual({ image_key: imageKey });
520
- expectMediaTimeoutClientConfigured();
521
- expect(result.buffer).toEqual(Buffer.from("image-data"));
522
- if (!capturedPath) {
523
- throw new Error("expected Feishu image temp path");
524
- }
525
- expectPathIsolatedToTmpRoot(capturedPath, imageKey);
526
- });
527
-
528
- it("uses isolated temp paths for message resource downloads", async () => {
529
- const fileKey = "file_v3_01abc123";
530
- let capturedPath: string | undefined;
531
-
532
- messageResourceGetMock.mockResolvedValueOnce({
533
- writeFile: async (tmpPath: string) => {
534
- capturedPath = tmpPath;
535
- await fs.writeFile(tmpPath, Buffer.from("resource-data"));
536
- },
537
- });
538
-
539
- const result = await downloadMessageResourceFeishu({
540
- cfg: emptyConfig,
541
- messageId: "om_123",
542
- fileKey,
543
- type: "image",
544
- });
545
-
546
- expect(result.buffer).toEqual(Buffer.from("resource-data"));
547
- if (!capturedPath) {
548
- throw new Error("expected Feishu resource temp path");
549
- }
550
- expectPathIsolatedToTmpRoot(capturedPath, fileKey);
551
- });
552
-
553
- it("rejects oversized message resource streams before buffering the rest", async () => {
554
- messageResourceGetMock.mockResolvedValueOnce({
555
- getReadableStream: () => Readable.from([Buffer.alloc(4), Buffer.alloc(4)]),
556
- });
557
-
558
- await expect(
559
- downloadMessageResourceFeishu({
560
- cfg: emptyConfig,
561
- messageId: "om_123",
562
- fileKey: "file_v3_01abc123",
563
- type: "file",
564
- maxBytes: 7,
565
- }),
566
- ).rejects.toThrow(/Media exceeds/i);
567
- });
568
-
569
- it("rejects oversized writeFile downloads before reading the temp file", async () => {
570
- messageResourceGetMock.mockResolvedValueOnce({
571
- writeFile: async (tmpPath: string) => {
572
- await fs.writeFile(tmpPath, Buffer.alloc(8));
573
- },
574
- });
575
-
576
- await expect(
577
- downloadMessageResourceFeishu({
578
- cfg: emptyConfig,
579
- messageId: "om_123",
580
- fileKey: "file_v3_01abc123",
581
- type: "file",
582
- maxBytes: 7,
583
- }),
584
- ).rejects.toThrow(/Media exceeds/i);
585
- });
586
-
587
- it("rejects invalid image keys before calling feishu api", async () => {
588
- await expect(
589
- downloadImageFeishu({
590
- cfg: emptyConfig,
591
- imageKey: "a/../../bad",
592
- }),
593
- ).rejects.toThrow("invalid image_key");
594
-
595
- expect(imageGetMock).not.toHaveBeenCalled();
596
- });
597
-
598
- it("rejects invalid file keys before calling feishu api", async () => {
599
- await expect(
600
- downloadMessageResourceFeishu({
601
- cfg: emptyConfig,
602
- messageId: "om_123",
603
- fileKey: "x/../../bad",
604
- type: "file",
605
- }),
606
- ).rejects.toThrow("invalid file_key");
607
-
608
- expect(messageResourceGetMock).not.toHaveBeenCalled();
609
- });
610
-
611
- it("preserves Chinese filenames for file uploads", async () => {
612
- await sendMediaFeishu({
613
- cfg: emptyConfig,
614
- to: "user:ou_target",
615
- mediaBuffer: Buffer.from("doc"),
616
- fileName: "测试文档.pdf",
617
- });
618
-
619
- expect(callData<{ file_name?: string }>(fileCreateMock).file_name).toBe("测试文档.pdf");
620
- });
621
-
622
- it("preserves ASCII filenames unchanged for file uploads", async () => {
623
- await sendMediaFeishu({
624
- cfg: emptyConfig,
625
- to: "user:ou_target",
626
- mediaBuffer: Buffer.from("doc"),
627
- fileName: "report-2026.pdf",
628
- });
629
-
630
- expect(callData<{ file_name?: string }>(fileCreateMock).file_name).toBe("report-2026.pdf");
631
- });
632
-
633
- it("preserves special Unicode characters (em-dash, full-width brackets) in filenames", async () => {
634
- await sendMediaFeishu({
635
- cfg: emptyConfig,
636
- to: "user:ou_target",
637
- mediaBuffer: Buffer.from("doc"),
638
- fileName: "报告—详情(2026).md",
639
- });
640
-
641
- expect(callData<{ file_name?: string }>(fileCreateMock).file_name).toBe("报告—详情(2026).md");
642
- });
643
- });
644
-
645
- describe("sanitizeFileNameForUpload", () => {
646
- it("returns ASCII filenames unchanged", () => {
647
- expect(sanitizeFileNameForUpload("report.pdf")).toBe("report.pdf");
648
- expect(sanitizeFileNameForUpload("my-file_v2.txt")).toBe("my-file_v2.txt");
649
- });
650
-
651
- it("preserves Chinese characters", () => {
652
- expect(sanitizeFileNameForUpload("测试文件.md")).toBe("测试文件.md");
653
- expect(sanitizeFileNameForUpload("武汉15座山登山信息汇总.csv")).toBe(
654
- "武汉15座山登山信息汇总.csv",
655
- );
656
- });
657
-
658
- it("preserves em-dash and full-width brackets", () => {
659
- expect(sanitizeFileNameForUpload("文件—说明(v2).pdf")).toBe("文件—说明(v2).pdf");
660
- });
661
-
662
- it("preserves single quotes and parentheses", () => {
663
- expect(sanitizeFileNameForUpload("文件'(test).txt")).toBe("文件'(test).txt");
664
- });
665
-
666
- it("preserves filenames without extension", () => {
667
- expect(sanitizeFileNameForUpload("测试文件")).toBe("测试文件");
668
- });
669
-
670
- it("preserves mixed ASCII and non-ASCII", () => {
671
- expect(sanitizeFileNameForUpload("Report_报告_2026.xlsx")).toBe("Report_报告_2026.xlsx");
672
- });
673
-
674
- it("preserves emoji filenames", () => {
675
- expect(sanitizeFileNameForUpload("report_😀.txt")).toBe("report_😀.txt");
676
- });
677
-
678
- it("strips control characters", () => {
679
- expect(sanitizeFileNameForUpload("bad\x00file.txt")).toBe("bad_file.txt");
680
- expect(sanitizeFileNameForUpload("inject\r\nheader.txt")).toBe("inject__header.txt");
681
- });
682
-
683
- it("strips quotes and backslashes to prevent header injection", () => {
684
- expect(sanitizeFileNameForUpload('file"name.txt')).toBe("file_name.txt");
685
- expect(sanitizeFileNameForUpload("file\\name.txt")).toBe("file_name.txt");
686
- });
687
- });
688
-
689
- describe("downloadMessageResourceFeishu", () => {
690
- function httpStatusError(status: number): Error & { response: { status: number } } {
691
- return Object.assign(new Error(`Request failed with status code ${status}`), {
692
- response: { status },
693
- });
694
- }
695
-
696
- beforeEach(() => {
697
- vi.clearAllMocks();
698
- mockResolvedFeishuAccount();
699
-
700
- createFeishuClientMock.mockReturnValue({
701
- im: {
702
- messageResource: {
703
- get: messageResourceGetMock,
704
- },
705
- },
706
- });
707
-
708
- messageResourceGetMock.mockResolvedValue(Buffer.from("fake-audio-data"));
709
- });
710
-
711
- // Regression: Feishu API only supports type=image|file for messageResource.get.
712
- // Audio/video resources must use type=file, not type=audio (#8746).
713
- it("forwards provided type=file for non-image resources", async () => {
714
- const result = await downloadMessageResourceFeishu({
715
- cfg: emptyConfig,
716
- messageId: "om_audio_msg",
717
- fileKey: "file_key_audio",
718
- type: "file",
719
- });
720
-
721
- const request = mockCallArg<{
722
- params?: { type?: string };
723
- path?: { file_key?: string; message_id?: string };
724
- }>(messageResourceGetMock, 0, 0);
725
- expect(request.path).toEqual({ message_id: "om_audio_msg", file_key: "file_key_audio" });
726
- expect(request.params).toEqual({ type: "file" });
727
- expectMediaTimeoutClientConfigured();
728
- expect(result.buffer).toBeInstanceOf(Buffer);
729
- });
730
-
731
- it("image uses type=image", async () => {
732
- messageResourceGetMock.mockResolvedValue(Buffer.from("fake-image-data"));
733
-
734
- const result = await downloadMessageResourceFeishu({
735
- cfg: emptyConfig,
736
- messageId: "om_img_msg",
737
- fileKey: "img_key_1",
738
- type: "image",
739
- });
740
-
741
- const request = mockCallArg<{
742
- params?: { type?: string };
743
- path?: { file_key?: string; message_id?: string };
744
- }>(messageResourceGetMock, 0, 0);
745
- expect(request.path).toEqual({ message_id: "om_img_msg", file_key: "img_key_1" });
746
- expect(request.params).toEqual({ type: "image" });
747
- expectMediaTimeoutClientConfigured();
748
- expect(result.buffer).toBeInstanceOf(Buffer);
749
- });
750
-
751
- it("extracts content-type and filename metadata from download headers", async () => {
752
- messageResourceGetMock.mockResolvedValueOnce({
753
- data: Buffer.from("fake-video-data"),
754
- headers: {
755
- "content-type": "video/mp4",
756
- "content-disposition": `attachment; filename="clip.mp4"`,
757
- },
758
- });
759
-
760
- const result = await downloadMessageResourceFeishu({
761
- cfg: emptyConfig,
762
- messageId: "om_video_msg",
763
- fileKey: "file_key_video",
764
- type: "file",
765
- });
766
-
767
- expect(result.buffer).toEqual(Buffer.from("fake-video-data"));
768
- expect(result.contentType).toBe("video/mp4");
769
- expect(result.fileName).toBe("clip.mp4");
770
- });
771
-
772
- it("retries file resources as media after HTTP 502", async () => {
773
- const originalError = httpStatusError(502);
774
- messageResourceGetMock.mockRejectedValueOnce(originalError).mockResolvedValueOnce({
775
- data: Buffer.from("fake-ios-video-data"),
776
- headers: {
777
- "content-type": "video/mp4",
778
- "content-disposition": `attachment; filename="ios-video.mp4"`,
779
- },
780
- });
781
-
782
- const result = await downloadMessageResourceFeishu({
783
- cfg: emptyConfig,
784
- messageId: "om_ios_video_msg",
785
- fileKey: "file_key_ios_video",
786
- type: "file",
787
- });
788
-
789
- const firstRequest = mockCallArg<{
790
- params?: { type?: string };
791
- path?: { file_key?: string; message_id?: string };
792
- }>(messageResourceGetMock, 0, 0);
793
- expect(firstRequest.path).toEqual({
794
- message_id: "om_ios_video_msg",
795
- file_key: "file_key_ios_video",
796
- });
797
- expect(firstRequest.params).toEqual({ type: "file" });
798
- const secondRequest = mockCallArg<{
799
- params?: { type?: string };
800
- path?: { file_key?: string; message_id?: string };
801
- }>(messageResourceGetMock, 1, 0);
802
- expect(secondRequest.path).toEqual({
803
- message_id: "om_ios_video_msg",
804
- file_key: "file_key_ios_video",
805
- });
806
- expect(secondRequest.params).toEqual({ type: "media" });
807
- expect(result.buffer).toEqual(Buffer.from("fake-ios-video-data"));
808
- expect(result.contentType).toBe("video/mp4");
809
- expect(result.fileName).toBe("ios-video.mp4");
810
- });
811
-
812
- it("rethrows the original HTTP 502 when the media retry fails", async () => {
813
- const originalError = httpStatusError(502);
814
- messageResourceGetMock
815
- .mockRejectedValueOnce(originalError)
816
- .mockRejectedValueOnce(new Error("media retry failed"));
817
-
818
- await expect(
819
- downloadMessageResourceFeishu({
820
- cfg: emptyConfig,
821
- messageId: "om_ios_video_msg",
822
- fileKey: "file_key_ios_video",
823
- type: "file",
824
- }),
825
- ).rejects.toBe(originalError);
826
-
827
- expect(
828
- mockCallArg<{ params?: { type?: string } }>(messageResourceGetMock, 0, 0).params,
829
- ).toEqual({ type: "file" });
830
- expect(
831
- mockCallArg<{ params?: { type?: string } }>(messageResourceGetMock, 1, 0).params,
832
- ).toEqual({ type: "media" });
833
- });
834
-
835
- it("does not retry non-fallback download failures", async () => {
836
- for (const scenario of [
837
- { messageId: "om_image_msg", fileKey: "img_key_502", type: "image" as const, status: 502 },
838
- { messageId: "om_file_msg", fileKey: "file_key_500", type: "file" as const, status: 500 },
839
- ]) {
840
- const originalError = httpStatusError(scenario.status);
841
- messageResourceGetMock.mockClear();
842
- messageResourceGetMock.mockRejectedValueOnce(originalError);
843
-
844
- await expect(
845
- downloadMessageResourceFeishu({
846
- cfg: emptyConfig,
847
- messageId: scenario.messageId,
848
- fileKey: scenario.fileKey,
849
- type: scenario.type,
850
- }),
851
- ).rejects.toBe(originalError);
852
-
853
- expect(messageResourceGetMock).toHaveBeenCalledTimes(1);
854
- const request = mockCallArg<{
855
- params?: { type?: string };
856
- path?: { file_key?: string; message_id?: string };
857
- }>(messageResourceGetMock, 0, 0);
858
- expect(request.path).toEqual({ message_id: scenario.messageId, file_key: scenario.fileKey });
859
- expect(request.params).toEqual({ type: scenario.type });
860
- }
861
- });
862
-
863
- it("recovers CJK filenames from plain Content-Disposition headers decoded as Latin-1", async () => {
864
- const fileName = "武汉15座山登山信息汇总.csv";
865
- const latin1HeaderFileName = Buffer.from(fileName, "utf8").toString("latin1");
866
- messageResourceGetMock.mockResolvedValueOnce({
867
- data: Buffer.from("fake-file-data"),
868
- headers: {
869
- "content-disposition": `attachment; filename="${latin1HeaderFileName}"`,
870
- },
871
- });
872
-
873
- const result = await downloadMessageResourceFeishu({
874
- cfg: emptyConfig,
875
- messageId: "om_file_msg",
876
- fileKey: "file_key_csv",
877
- type: "file",
878
- });
879
-
880
- expect(result.fileName).toBe(fileName);
881
- });
882
-
883
- it("keeps valid Latin-1 filenames from plain Content-Disposition headers unchanged", async () => {
884
- messageResourceGetMock.mockResolvedValueOnce({
885
- data: Buffer.from("fake-file-data"),
886
- headers: {
887
- "content-disposition": `attachment; filename="café-©.txt"`,
888
- },
889
- });
890
-
891
- const result = await downloadMessageResourceFeishu({
892
- cfg: emptyConfig,
893
- messageId: "om_latin1_msg",
894
- fileKey: "file_key_latin1",
895
- type: "file",
896
- });
897
-
898
- expect(result.fileName).toBe("café-©.txt");
899
- });
900
-
901
- it("keeps JSON-derived file_name metadata unchanged", async () => {
902
- const fileName = "武汉15座山登山信息汇总.csv";
903
- const latin1LookingFileName = Buffer.from(fileName, "utf8").toString("latin1");
904
- messageResourceGetMock.mockResolvedValueOnce({
905
- data: Buffer.from("fake-file-data"),
906
- file_name: latin1LookingFileName,
907
- });
908
-
909
- const result = await downloadMessageResourceFeishu({
910
- cfg: emptyConfig,
911
- messageId: "om_json_file_msg",
912
- fileKey: "file_key_json",
913
- type: "file",
914
- });
915
-
916
- expect(result.fileName).toBe(latin1LookingFileName);
917
- });
918
-
919
- it("saves message resource streams directly to the media store", async () => {
920
- const originalHome = process.env.HOME;
921
- const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "klaw-feishu-media-"));
922
- try {
923
- process.env.HOME = tempHome;
924
- messageResourceGetMock.mockResolvedValueOnce({
925
- getReadableStream: () => Readable.from([Buffer.from([0xff, 0xd8, 0xff, 0x00])]),
926
- headers: {
927
- "content-type": "image/jpeg",
928
- "content-disposition": `attachment; filename="photo.jpg"`,
929
- },
930
- });
931
-
932
- const result = await saveMessageResourceFeishu({
933
- cfg: emptyConfig,
934
- messageId: "om_stream_msg",
935
- fileKey: "img_key_stream",
936
- type: "image",
937
- maxBytes: 1024,
938
- });
939
-
940
- expect(result.saved.path).toContain(`${path.sep}.klaw${path.sep}media${path.sep}inbound`);
941
- expect(result.saved.id).toMatch(/^photo---[a-f0-9-]{36}\.jpg$/);
942
- expect(result.saved.size).toBe(4);
943
- await expect(fs.readFile(result.saved.path)).resolves.toEqual(
944
- Buffer.from([0xff, 0xd8, 0xff, 0x00]),
945
- );
946
- } finally {
947
- if (originalHome === undefined) {
948
- delete process.env.HOME;
949
- } else {
950
- process.env.HOME = originalHome;
951
- }
952
- await fs.rm(tempHome, { recursive: true, force: true });
953
- }
954
- });
955
- });