@kodelyth/feishu 2026.5.42 → 2026.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +19 -6
  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/drive.ts DELETED
@@ -1,829 +0,0 @@
1
- import type * as Lark from "@larksuiteoapi/node-sdk";
2
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
3
- import type { KlawPluginApi } from "../runtime-api.js";
4
- import { listEnabledFeishuAccounts } from "./accounts.js";
5
- import { cleanupAmbientCommentTypingReaction } from "./comment-reaction.js";
6
- import {
7
- encodeQuery,
8
- extractReplyText,
9
- formatFeishuApiError,
10
- isRecord,
11
- readString,
12
- } from "./comment-shared.js";
13
- import { parseFeishuCommentTarget, type CommentFileType } from "./comment-target.js";
14
- import { FeishuDriveSchema, type FeishuDriveParams } from "./drive-schema.js";
15
- import { createFeishuToolClient, resolveAnyEnabledFeishuToolsConfig } from "./tool-account.js";
16
- import {
17
- jsonToolResult,
18
- toolExecutionErrorResult,
19
- unknownToolActionResult,
20
- } from "./tool-result.js";
21
-
22
- // ============ Actions ============
23
-
24
- type FeishuExplorerRootFolderMetaResponse = {
25
- code: number;
26
- msg?: string;
27
- data?: {
28
- token?: string;
29
- };
30
- };
31
-
32
- type FeishuDriveInternalClient = Lark.Client & {
33
- domain?: string;
34
- httpInstance: Pick<Lark.HttpInstance, "get">;
35
- request(params: {
36
- method: "GET" | "POST";
37
- url: string;
38
- params?: Record<string, string | undefined>;
39
- data: unknown;
40
- timeout?: number;
41
- }): Promise<unknown>;
42
- };
43
-
44
- type FeishuDriveApiResponse<T> = {
45
- code: number;
46
- log_id?: string;
47
- msg?: string;
48
- data?: T;
49
- };
50
-
51
- class FeishuReplyCommentError extends Error {
52
- httpStatus?: number;
53
- feishuCode?: number | string;
54
- feishuMsg?: string;
55
- feishuLogId?: string;
56
-
57
- constructor(params: {
58
- message: string;
59
- httpStatus?: number;
60
- feishuCode?: number | string;
61
- feishuMsg?: string;
62
- feishuLogId?: string;
63
- }) {
64
- super(params.message);
65
- this.name = "FeishuReplyCommentError";
66
- this.httpStatus = params.httpStatus;
67
- this.feishuCode = params.feishuCode;
68
- this.feishuMsg = params.feishuMsg;
69
- this.feishuLogId = params.feishuLogId;
70
- }
71
- }
72
-
73
- type FeishuDriveCommentReply = {
74
- reply_id?: string;
75
- user_id?: string;
76
- create_time?: number;
77
- update_time?: number;
78
- content?: {
79
- elements?: unknown[];
80
- };
81
- };
82
-
83
- type FeishuDriveCommentCard = {
84
- comment_id?: string;
85
- user_id?: string;
86
- create_time?: number;
87
- update_time?: number;
88
- is_solved?: boolean;
89
- is_whole?: boolean;
90
- has_more?: boolean;
91
- page_token?: string;
92
- quote?: string;
93
- reply_list?: {
94
- replies?: FeishuDriveCommentReply[];
95
- };
96
- };
97
-
98
- type FeishuDriveListCommentsResponse = FeishuDriveApiResponse<{
99
- has_more?: boolean;
100
- items?: FeishuDriveCommentCard[];
101
- page_token?: string;
102
- }>;
103
-
104
- type FeishuDriveListRepliesResponse = FeishuDriveApiResponse<{
105
- has_more?: boolean;
106
- items?: FeishuDriveCommentReply[];
107
- page_token?: string;
108
- }>;
109
-
110
- type FeishuDriveToolContext = {
111
- deliveryContext?: {
112
- channel?: string;
113
- to?: string;
114
- threadId?: string | number;
115
- };
116
- };
117
-
118
- const FEISHU_DRIVE_REQUEST_TIMEOUT_MS = 30_000;
119
-
120
- function getDriveInternalClient(client: Lark.Client): FeishuDriveInternalClient {
121
- return client as FeishuDriveInternalClient;
122
- }
123
-
124
- function buildReplyElements(content: string) {
125
- return [{ type: "text", text: content }];
126
- }
127
-
128
- async function requestDriveApi<T>(params: {
129
- client: Lark.Client;
130
- method: "GET" | "POST";
131
- url: string;
132
- query?: Record<string, string | undefined>;
133
- data?: unknown;
134
- }): Promise<T> {
135
- const internalClient = getDriveInternalClient(params.client);
136
- return (await internalClient.request({
137
- method: params.method,
138
- url: params.url,
139
- params: params.query ?? {},
140
- data: params.data ?? {},
141
- timeout: FEISHU_DRIVE_REQUEST_TIMEOUT_MS,
142
- })) as T;
143
- }
144
-
145
- function assertDriveApiSuccess<T extends { code: number; msg?: string }>(response: T): T {
146
- if (response.code !== 0) {
147
- throw new Error(response.msg ?? "Feishu Drive API request failed");
148
- }
149
- return response;
150
- }
151
-
152
- function normalizeCommentReply(reply: FeishuDriveCommentReply) {
153
- return {
154
- reply_id: reply.reply_id,
155
- user_id: reply.user_id,
156
- create_time: reply.create_time,
157
- update_time: reply.update_time,
158
- text: extractReplyText(reply),
159
- };
160
- }
161
-
162
- function normalizeCommentCard(comment: FeishuDriveCommentCard) {
163
- const replies = comment.reply_list?.replies ?? [];
164
- const rootReply = replies[0];
165
- return {
166
- comment_id: comment.comment_id,
167
- user_id: comment.user_id,
168
- create_time: comment.create_time,
169
- update_time: comment.update_time,
170
- is_solved: comment.is_solved,
171
- is_whole: comment.is_whole,
172
- quote: comment.quote,
173
- text: extractReplyText(rootReply),
174
- has_more_replies: comment.has_more,
175
- replies_page_token: comment.page_token,
176
- replies: replies.slice(1).map(normalizeCommentReply),
177
- };
178
- }
179
-
180
- function normalizeCommentPageSize(pageSize: number | undefined): string | undefined {
181
- if (typeof pageSize !== "number" || !Number.isFinite(pageSize)) {
182
- return undefined;
183
- }
184
- return String(Math.min(Math.max(Math.floor(pageSize), 1), 100));
185
- }
186
-
187
- function resolveAmbientCommentTarget(context: FeishuDriveToolContext | undefined) {
188
- const deliveryContext = context?.deliveryContext;
189
- if (deliveryContext?.channel && deliveryContext.channel !== "feishu") {
190
- return null;
191
- }
192
- return parseFeishuCommentTarget(deliveryContext?.to);
193
- }
194
-
195
- function applyAmbientCommentDefaults<
196
- T extends {
197
- file_token?: string;
198
- file_type?: CommentFileType;
199
- comment_id?: string;
200
- },
201
- >(params: T, context: FeishuDriveToolContext | undefined): T {
202
- const ambient = resolveAmbientCommentTarget(context);
203
- if (!ambient) {
204
- return params;
205
- }
206
- return {
207
- ...params,
208
- file_token: params.file_token?.trim() || ambient.fileToken,
209
- file_type: params.file_type ?? ambient.fileType,
210
- comment_id: params.comment_id?.trim() || ambient.commentId,
211
- };
212
- }
213
-
214
- function applyAddCommentAmbientDefaults<
215
- T extends {
216
- file_token?: string;
217
- file_type?: "doc" | "docx";
218
- },
219
- >(params: T, context: FeishuDriveToolContext | undefined): T {
220
- const ambient = resolveAmbientCommentTarget(context);
221
- if (!ambient || (ambient.fileType !== "doc" && ambient.fileType !== "docx")) {
222
- return params;
223
- }
224
- return {
225
- ...params,
226
- file_token: params.file_token?.trim() || ambient.fileToken,
227
- file_type: params.file_type ?? ambient.fileType,
228
- };
229
- }
230
-
231
- function applyAddCommentDefaults<
232
- T extends {
233
- file_token?: string;
234
- file_type?: "doc" | "docx";
235
- },
236
- >(params: T): T & { file_type: "doc" | "docx" } {
237
- const fileType = params.file_type ?? "docx";
238
- if (!params.file_type) {
239
- console.info(
240
- `[feishu_drive] add_comment missing file_type; defaulting to docx ` +
241
- `file_token=${params.file_token ?? "unknown"}`,
242
- );
243
- }
244
- return {
245
- ...params,
246
- file_type: fileType,
247
- };
248
- }
249
-
250
- function applyCommentFileTypeDefault<
251
- T extends {
252
- file_token?: string;
253
- file_type?: CommentFileType;
254
- },
255
- >(
256
- params: T,
257
- action: "list_comments" | "list_comment_replies" | "reply_comment",
258
- ): T & {
259
- file_type: CommentFileType;
260
- } {
261
- const fileType = params.file_type ?? "docx";
262
- if (!params.file_type) {
263
- console.info(
264
- `[feishu_drive] ${action} missing file_type; defaulting to docx ` +
265
- `file_token=${params.file_token ?? "unknown"}`,
266
- );
267
- }
268
- return {
269
- ...params,
270
- file_type: fileType,
271
- };
272
- }
273
-
274
- function formatDriveApiError(error: unknown): string {
275
- return formatFeishuApiError(error, { includeConfigParams: true });
276
- }
277
-
278
- function extractDriveApiErrorMeta(error: unknown): {
279
- message: string;
280
- httpStatus?: number;
281
- feishuCode?: number | string;
282
- feishuMsg?: string;
283
- feishuLogId?: string;
284
- } {
285
- if (!isRecord(error)) {
286
- return { message: typeof error === "string" ? error : JSON.stringify(error) };
287
- }
288
- const response = isRecord(error.response) ? error.response : undefined;
289
- const responseData = isRecord(response?.data) ? response?.data : undefined;
290
- return {
291
- message:
292
- typeof error.message === "string"
293
- ? error.message
294
- : typeof error === "string"
295
- ? error
296
- : JSON.stringify(error),
297
- httpStatus: typeof response?.status === "number" ? response.status : undefined,
298
- feishuCode:
299
- typeof responseData?.code === "number" ? responseData.code : readString(responseData?.code),
300
- feishuMsg: readString(responseData?.msg),
301
- feishuLogId: readString(responseData?.log_id),
302
- };
303
- }
304
-
305
- function isReplyNotAllowedError(error: unknown): boolean {
306
- if (!(error instanceof FeishuReplyCommentError)) {
307
- return false;
308
- }
309
- return error.feishuCode === 1069302;
310
- }
311
-
312
- async function getRootFolderToken(client: Lark.Client): Promise<string> {
313
- // Use generic HTTP client to call the root folder meta API
314
- // as it's not directly exposed in the SDK
315
- const internalClient = getDriveInternalClient(client);
316
- const domain = internalClient.domain ?? "https://open.feishu.cn";
317
- const res = (await internalClient.httpInstance.get(
318
- `${domain}/open-apis/drive/explorer/v2/root_folder/meta`,
319
- )) as FeishuExplorerRootFolderMetaResponse;
320
- if (res.code !== 0) {
321
- throw new Error(res.msg ?? "Failed to get root folder");
322
- }
323
- const token = res.data?.token;
324
- if (!token) {
325
- throw new Error("Root folder token not found");
326
- }
327
- return token;
328
- }
329
-
330
- async function listFolder(client: Lark.Client, folderToken?: string) {
331
- // Filter out invalid folder_token values (empty, "0", etc.)
332
- const validFolderToken = folderToken && folderToken !== "0" ? folderToken : undefined;
333
- const res = await client.drive.file.list({
334
- params: validFolderToken ? { folder_token: validFolderToken } : {},
335
- });
336
- if (res.code !== 0) {
337
- throw new Error(res.msg);
338
- }
339
-
340
- return {
341
- files:
342
- res.data?.files?.map((f) => ({
343
- token: f.token,
344
- name: f.name,
345
- type: f.type,
346
- url: f.url,
347
- created_time: f.created_time,
348
- modified_time: f.modified_time,
349
- owner_id: f.owner_id,
350
- })) ?? [],
351
- next_page_token: res.data?.next_page_token,
352
- };
353
- }
354
-
355
- async function getFileInfo(client: Lark.Client, fileToken: string, folderToken?: string) {
356
- // Use list with folder_token to find file info
357
- const res = await client.drive.file.list({
358
- params: folderToken ? { folder_token: folderToken } : {},
359
- });
360
- if (res.code !== 0) {
361
- throw new Error(res.msg);
362
- }
363
-
364
- const file = res.data?.files?.find((f) => f.token === fileToken);
365
- if (!file) {
366
- throw new Error(`File not found: ${fileToken}`);
367
- }
368
-
369
- return {
370
- token: file.token,
371
- name: file.name,
372
- type: file.type,
373
- url: file.url,
374
- created_time: file.created_time,
375
- modified_time: file.modified_time,
376
- owner_id: file.owner_id,
377
- };
378
- }
379
-
380
- async function createFolder(client: Lark.Client, name: string, folderToken?: string) {
381
- // Feishu supports using folder_token="0" as the root folder.
382
- // We *try* to resolve the real root token (explorer API), but fall back to "0"
383
- // because some tenants/apps return 400 for that explorer endpoint.
384
- let effectiveToken = folderToken && folderToken !== "0" ? folderToken : "0";
385
- if (effectiveToken === "0") {
386
- try {
387
- effectiveToken = await getRootFolderToken(client);
388
- } catch {
389
- // ignore and keep "0"
390
- }
391
- }
392
-
393
- const res = await client.drive.file.createFolder({
394
- data: {
395
- name,
396
- folder_token: effectiveToken,
397
- },
398
- });
399
- if (res.code !== 0) {
400
- throw new Error(res.msg);
401
- }
402
-
403
- return {
404
- token: res.data?.token,
405
- url: res.data?.url,
406
- };
407
- }
408
-
409
- async function moveFile(client: Lark.Client, fileToken: string, type: string, folderToken: string) {
410
- const res = await client.drive.file.move({
411
- path: { file_token: fileToken },
412
- data: {
413
- type: type as
414
- | "doc"
415
- | "docx"
416
- | "sheet"
417
- | "bitable"
418
- | "folder"
419
- | "file"
420
- | "mindnote"
421
- | "slides",
422
- folder_token: folderToken,
423
- },
424
- });
425
- if (res.code !== 0) {
426
- throw new Error(res.msg);
427
- }
428
-
429
- return {
430
- success: true,
431
- task_id: res.data?.task_id,
432
- };
433
- }
434
-
435
- async function deleteFile(client: Lark.Client, fileToken: string, type: string) {
436
- const res = await client.drive.file.delete({
437
- path: { file_token: fileToken },
438
- params: {
439
- type: type as
440
- | "doc"
441
- | "docx"
442
- | "sheet"
443
- | "bitable"
444
- | "folder"
445
- | "file"
446
- | "mindnote"
447
- | "slides"
448
- | "shortcut",
449
- },
450
- });
451
- if (res.code !== 0) {
452
- throw new Error(res.msg);
453
- }
454
-
455
- return {
456
- success: true,
457
- task_id: res.data?.task_id,
458
- };
459
- }
460
-
461
- async function listComments(
462
- client: Lark.Client,
463
- params: {
464
- file_token: string;
465
- file_type: CommentFileType;
466
- page_size?: number;
467
- page_token?: string;
468
- },
469
- ) {
470
- const response = assertDriveApiSuccess(
471
- await requestDriveApi<FeishuDriveListCommentsResponse>({
472
- client,
473
- method: "GET",
474
- url:
475
- `/open-apis/drive/v1/files/${encodeURIComponent(params.file_token)}/comments` +
476
- encodeQuery({
477
- file_type: params.file_type,
478
- page_size: normalizeCommentPageSize(params.page_size),
479
- page_token: params.page_token,
480
- user_id_type: "open_id",
481
- }),
482
- }),
483
- );
484
- return {
485
- has_more: response.data?.has_more ?? false,
486
- page_token: response.data?.page_token,
487
- comments: (response.data?.items ?? []).map(normalizeCommentCard),
488
- };
489
- }
490
-
491
- async function listCommentReplies(
492
- client: Lark.Client,
493
- params: {
494
- file_token: string;
495
- file_type: CommentFileType;
496
- comment_id: string;
497
- page_size?: number;
498
- page_token?: string;
499
- },
500
- ) {
501
- const response = assertDriveApiSuccess(
502
- await requestDriveApi<FeishuDriveListRepliesResponse>({
503
- client,
504
- method: "GET",
505
- url:
506
- `/open-apis/drive/v1/files/${encodeURIComponent(params.file_token)}/comments/${encodeURIComponent(
507
- params.comment_id,
508
- )}/replies` +
509
- encodeQuery({
510
- file_type: params.file_type,
511
- page_size: normalizeCommentPageSize(params.page_size),
512
- page_token: params.page_token,
513
- user_id_type: "open_id",
514
- }),
515
- }),
516
- );
517
- return {
518
- has_more: response.data?.has_more ?? false,
519
- page_token: response.data?.page_token,
520
- replies: (response.data?.items ?? []).map(normalizeCommentReply),
521
- };
522
- }
523
-
524
- async function addComment(
525
- client: Lark.Client,
526
- params: {
527
- file_token: string;
528
- file_type: "doc" | "docx";
529
- content: string;
530
- block_id?: string;
531
- },
532
- ): Promise<{ success: true } & Record<string, unknown>> {
533
- if (params.block_id?.trim() && params.file_type !== "docx") {
534
- throw new Error("block_id is only supported for docx comments");
535
- }
536
- const response = assertDriveApiSuccess(
537
- await requestDriveApi<FeishuDriveApiResponse<Record<string, unknown>>>({
538
- client,
539
- method: "POST",
540
- url: `/open-apis/drive/v1/files/${encodeURIComponent(params.file_token)}/new_comments`,
541
- data: {
542
- file_type: params.file_type,
543
- reply_elements: buildReplyElements(params.content),
544
- ...(params.block_id?.trim() ? { anchor: { block_id: params.block_id.trim() } } : {}),
545
- },
546
- }),
547
- );
548
- return {
549
- success: true,
550
- ...response.data,
551
- };
552
- }
553
-
554
- // Fetch comment metadata via batch_query because the single-comment endpoint
555
- // does not support partial comments.
556
- async function queryCommentById(
557
- client: Lark.Client,
558
- params: {
559
- file_token: string;
560
- file_type: CommentFileType;
561
- comment_id: string;
562
- },
563
- ) {
564
- const response = assertDriveApiSuccess(
565
- await requestDriveApi<FeishuDriveListCommentsResponse>({
566
- client,
567
- method: "POST",
568
- url:
569
- `/open-apis/drive/v1/files/${encodeURIComponent(params.file_token)}/comments/batch_query` +
570
- encodeQuery({
571
- file_type: params.file_type,
572
- user_id_type: "open_id",
573
- }),
574
- data: {
575
- comment_ids: [params.comment_id],
576
- },
577
- }),
578
- );
579
- return response.data?.items?.find((comment) => comment.comment_id?.trim() === params.comment_id);
580
- }
581
-
582
- export async function replyComment(
583
- client: Lark.Client,
584
- params: {
585
- file_token: string;
586
- file_type: CommentFileType;
587
- comment_id: string;
588
- content: string;
589
- },
590
- ): Promise<{ success: true; reply_id?: string } & Record<string, unknown>> {
591
- const url = `/open-apis/drive/v1/files/${encodeURIComponent(params.file_token)}/comments/${encodeURIComponent(
592
- params.comment_id,
593
- )}/replies`;
594
- const query = { file_type: params.file_type };
595
- try {
596
- const response = await requestDriveApi<FeishuDriveApiResponse<Record<string, unknown>>>({
597
- client,
598
- method: "POST",
599
- url,
600
- query,
601
- data: {
602
- content: {
603
- elements: [
604
- {
605
- type: "text_run",
606
- text_run: {
607
- text: params.content,
608
- },
609
- },
610
- ],
611
- },
612
- },
613
- });
614
- if (response.code === 0) {
615
- return {
616
- success: true,
617
- ...response.data,
618
- };
619
- }
620
- console.warn(
621
- `[feishu_drive] replyComment failed ` +
622
- `comment=${params.comment_id} file_type=${params.file_type} ` +
623
- `code=${response.code ?? "unknown"} ` +
624
- `msg=${response.msg ?? "unknown"} log_id=${response.log_id ?? "unknown"}`,
625
- );
626
- throw new FeishuReplyCommentError({
627
- message: response.msg ?? "Feishu Drive reply comment failed",
628
- feishuCode: response.code,
629
- feishuMsg: response.msg,
630
- feishuLogId: response.log_id,
631
- });
632
- } catch (error) {
633
- if (error instanceof FeishuReplyCommentError) {
634
- throw error;
635
- }
636
- const meta = extractDriveApiErrorMeta(error);
637
- console.warn(
638
- `[feishu_drive] replyComment threw ` +
639
- `comment=${params.comment_id} file_type=${params.file_type} ` +
640
- `error=${formatDriveApiError(error)}`,
641
- );
642
- throw new FeishuReplyCommentError({
643
- message: meta.message,
644
- httpStatus: meta.httpStatus,
645
- feishuCode: meta.feishuCode,
646
- feishuMsg: meta.feishuMsg,
647
- feishuLogId: meta.feishuLogId,
648
- });
649
- }
650
- }
651
-
652
- export async function deliverCommentThreadText(
653
- client: Lark.Client,
654
- params: {
655
- file_token: string;
656
- file_type: CommentFileType;
657
- comment_id: string;
658
- content: string;
659
- is_whole_comment?: boolean;
660
- },
661
- ): Promise<
662
- | ({ success: true; reply_id?: string } & Record<string, unknown> & {
663
- delivery_mode: "reply_comment";
664
- })
665
- | ({ success: true; comment_id?: string } & Record<string, unknown> & {
666
- delivery_mode: "add_comment";
667
- })
668
- > {
669
- let isWholeComment = params.is_whole_comment;
670
- if (isWholeComment === undefined) {
671
- try {
672
- const comment = await queryCommentById(client, params);
673
- isWholeComment = comment?.is_whole === true;
674
- } catch (error) {
675
- console.warn(
676
- `[feishu_drive] comment metadata preflight failed ` +
677
- `comment=${params.comment_id} file_type=${params.file_type} ` +
678
- `error=${formatErrorMessage(error)}`,
679
- );
680
- isWholeComment = false;
681
- }
682
- }
683
- if (isWholeComment) {
684
- if (params.file_type !== "doc" && params.file_type !== "docx") {
685
- throw new Error(
686
- `Whole-document comment follow-ups are only supported for doc/docx (got ${params.file_type})`,
687
- );
688
- }
689
- const wholeCommentFileType: "doc" | "docx" = params.file_type;
690
- console.info(
691
- `[feishu_drive] whole-comment compatibility path ` +
692
- `comment=${params.comment_id} file_type=${params.file_type} mode=add_comment`,
693
- );
694
- return {
695
- delivery_mode: "add_comment",
696
- ...(await addComment(client, {
697
- file_token: params.file_token,
698
- file_type: wholeCommentFileType,
699
- content: params.content,
700
- })),
701
- };
702
- }
703
- try {
704
- return {
705
- delivery_mode: "reply_comment",
706
- ...(await replyComment(client, params)),
707
- };
708
- } catch (error) {
709
- if (error instanceof FeishuReplyCommentError && isReplyNotAllowedError(error)) {
710
- if (params.file_type !== "doc" && params.file_type !== "docx") {
711
- throw error;
712
- }
713
- const fallbackFileType: "doc" | "docx" = params.file_type;
714
- console.info(
715
- `[feishu_drive] reply-not-allowed compatibility path ` +
716
- `comment=${params.comment_id} file_type=${params.file_type} mode=add_comment ` +
717
- `log_id=${error.feishuLogId ?? "unknown"}`,
718
- );
719
- return {
720
- delivery_mode: "add_comment",
721
- ...(await addComment(client, {
722
- file_token: params.file_token,
723
- file_type: fallbackFileType,
724
- content: params.content,
725
- })),
726
- };
727
- }
728
- throw error;
729
- }
730
- }
731
-
732
- // ============ Tool Registration ============
733
-
734
- export function registerFeishuDriveTools(api: KlawPluginApi) {
735
- if (!api.config) {
736
- return;
737
- }
738
-
739
- const accounts = listEnabledFeishuAccounts(api.config);
740
- if (accounts.length === 0) {
741
- return;
742
- }
743
-
744
- const toolsCfg = resolveAnyEnabledFeishuToolsConfig(accounts);
745
- if (!toolsCfg.drive) {
746
- return;
747
- }
748
-
749
- type FeishuDriveExecuteParams = FeishuDriveParams & { accountId?: string };
750
-
751
- api.registerTool(
752
- (ctx) => {
753
- const defaultAccountId = ctx.agentAccountId;
754
- return {
755
- name: "feishu_drive",
756
- label: "Feishu Drive",
757
- description:
758
- "Feishu cloud storage operations. Actions: list, info, create_folder, move, delete, list_comments, list_comment_replies, add_comment, reply_comment",
759
- parameters: FeishuDriveSchema,
760
- async execute(_toolCallId, params) {
761
- const p = params as FeishuDriveExecuteParams;
762
- try {
763
- const client = createFeishuToolClient({
764
- api,
765
- executeParams: p,
766
- defaultAccountId,
767
- });
768
- switch (p.action) {
769
- case "list":
770
- return jsonToolResult(await listFolder(client, p.folder_token));
771
- case "info":
772
- return jsonToolResult(await getFileInfo(client, p.file_token));
773
- case "create_folder":
774
- return jsonToolResult(await createFolder(client, p.name, p.folder_token));
775
- case "move":
776
- return jsonToolResult(await moveFile(client, p.file_token, p.type, p.folder_token));
777
- case "delete":
778
- return jsonToolResult(await deleteFile(client, p.file_token, p.type));
779
- case "list_comments": {
780
- const resolved = applyCommentFileTypeDefault(
781
- applyAmbientCommentDefaults(p, ctx),
782
- "list_comments",
783
- );
784
- return jsonToolResult(await listComments(client, resolved));
785
- }
786
- case "list_comment_replies": {
787
- const resolved = applyCommentFileTypeDefault(
788
- applyAmbientCommentDefaults(p, ctx),
789
- "list_comment_replies",
790
- );
791
- return jsonToolResult(await listCommentReplies(client, resolved));
792
- }
793
- case "add_comment": {
794
- const resolved = applyAddCommentDefaults(applyAddCommentAmbientDefaults(p, ctx));
795
- try {
796
- return jsonToolResult(await addComment(client, resolved));
797
- } finally {
798
- void cleanupAmbientCommentTypingReaction({
799
- client: getDriveInternalClient(client),
800
- deliveryContext: ctx.deliveryContext,
801
- });
802
- }
803
- }
804
- case "reply_comment": {
805
- const resolved = applyCommentFileTypeDefault(
806
- applyAmbientCommentDefaults(p, ctx),
807
- "reply_comment",
808
- );
809
- try {
810
- return jsonToolResult(await deliverCommentThreadText(client, resolved));
811
- } finally {
812
- void cleanupAmbientCommentTypingReaction({
813
- client: getDriveInternalClient(client),
814
- deliveryContext: ctx.deliveryContext,
815
- });
816
- }
817
- }
818
- default:
819
- return unknownToolActionResult((p as { action?: unknown }).action);
820
- }
821
- } catch (err) {
822
- return toolExecutionErrorResult(err);
823
- }
824
- },
825
- };
826
- },
827
- { name: "feishu_drive" },
828
- );
829
- }