@openclaw-plugins/feishu-plus 0.1.7

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.
@@ -0,0 +1,165 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import { createFeishuClient } from "./client.js";
3
+ import { resolveFeishuAccount } from "./accounts.js";
4
+ import { normalizeFeishuTarget } from "./targets.js";
5
+
6
+ export type FeishuDirectoryPeer = {
7
+ kind: "user";
8
+ id: string;
9
+ name?: string;
10
+ };
11
+
12
+ export type FeishuDirectoryGroup = {
13
+ kind: "group";
14
+ id: string;
15
+ name?: string;
16
+ };
17
+
18
+ export async function listFeishuDirectoryPeers(params: {
19
+ cfg: ClawdbotConfig;
20
+ query?: string;
21
+ limit?: number;
22
+ accountId?: string;
23
+ }): Promise<FeishuDirectoryPeer[]> {
24
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
25
+ const feishuCfg = account.config;
26
+ const q = params.query?.trim().toLowerCase() || "";
27
+ const ids = new Set<string>();
28
+
29
+ for (const entry of feishuCfg?.allowFrom ?? []) {
30
+ const trimmed = String(entry).trim();
31
+ if (trimmed && trimmed !== "*") ids.add(trimmed);
32
+ }
33
+
34
+ for (const userId of Object.keys(feishuCfg?.dms ?? {})) {
35
+ const trimmed = userId.trim();
36
+ if (trimmed) ids.add(trimmed);
37
+ }
38
+
39
+ return Array.from(ids)
40
+ .map((raw) => raw.trim())
41
+ .filter(Boolean)
42
+ .map((raw) => normalizeFeishuTarget(raw) ?? raw)
43
+ .filter((id) => (q ? id.toLowerCase().includes(q) : true))
44
+ .slice(0, params.limit && params.limit > 0 ? params.limit : undefined)
45
+ .map((id) => ({ kind: "user" as const, id }));
46
+ }
47
+
48
+ export async function listFeishuDirectoryGroups(params: {
49
+ cfg: ClawdbotConfig;
50
+ query?: string;
51
+ limit?: number;
52
+ accountId?: string;
53
+ }): Promise<FeishuDirectoryGroup[]> {
54
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
55
+ const feishuCfg = account.config;
56
+ const q = params.query?.trim().toLowerCase() || "";
57
+ const ids = new Set<string>();
58
+
59
+ for (const groupId of Object.keys(feishuCfg?.groups ?? {})) {
60
+ const trimmed = groupId.trim();
61
+ if (trimmed && trimmed !== "*") ids.add(trimmed);
62
+ }
63
+
64
+ for (const entry of feishuCfg?.groupAllowFrom ?? []) {
65
+ const trimmed = String(entry).trim();
66
+ if (trimmed && trimmed !== "*") ids.add(trimmed);
67
+ }
68
+
69
+ return Array.from(ids)
70
+ .map((raw) => raw.trim())
71
+ .filter(Boolean)
72
+ .filter((id) => (q ? id.toLowerCase().includes(q) : true))
73
+ .slice(0, params.limit && params.limit > 0 ? params.limit : undefined)
74
+ .map((id) => ({ kind: "group" as const, id }));
75
+ }
76
+
77
+ export async function listFeishuDirectoryPeersLive(params: {
78
+ cfg: ClawdbotConfig;
79
+ query?: string;
80
+ limit?: number;
81
+ accountId?: string;
82
+ }): Promise<FeishuDirectoryPeer[]> {
83
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
84
+ if (!account.configured) {
85
+ return listFeishuDirectoryPeers(params);
86
+ }
87
+
88
+ try {
89
+ const client = createFeishuClient(account);
90
+ const peers: FeishuDirectoryPeer[] = [];
91
+ const limit = params.limit ?? 50;
92
+
93
+ const response = await client.contact.user.list({
94
+ params: {
95
+ page_size: Math.min(limit, 50),
96
+ },
97
+ });
98
+
99
+ if (response.code === 0 && response.data?.items) {
100
+ for (const user of response.data.items) {
101
+ if (user.open_id) {
102
+ const q = params.query?.trim().toLowerCase() || "";
103
+ const name = user.name || "";
104
+ if (!q || user.open_id.toLowerCase().includes(q) || name.toLowerCase().includes(q)) {
105
+ peers.push({
106
+ kind: "user",
107
+ id: user.open_id,
108
+ name: name || undefined,
109
+ });
110
+ }
111
+ }
112
+ if (peers.length >= limit) break;
113
+ }
114
+ }
115
+
116
+ return peers;
117
+ } catch {
118
+ return listFeishuDirectoryPeers(params);
119
+ }
120
+ }
121
+
122
+ export async function listFeishuDirectoryGroupsLive(params: {
123
+ cfg: ClawdbotConfig;
124
+ query?: string;
125
+ limit?: number;
126
+ accountId?: string;
127
+ }): Promise<FeishuDirectoryGroup[]> {
128
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
129
+ if (!account.configured) {
130
+ return listFeishuDirectoryGroups(params);
131
+ }
132
+
133
+ try {
134
+ const client = createFeishuClient(account);
135
+ const groups: FeishuDirectoryGroup[] = [];
136
+ const limit = params.limit ?? 50;
137
+
138
+ const response = await client.im.chat.list({
139
+ params: {
140
+ page_size: Math.min(limit, 100),
141
+ },
142
+ });
143
+
144
+ if (response.code === 0 && response.data?.items) {
145
+ for (const chat of response.data.items) {
146
+ if (chat.chat_id) {
147
+ const q = params.query?.trim().toLowerCase() || "";
148
+ const name = chat.name || "";
149
+ if (!q || chat.chat_id.toLowerCase().includes(q) || name.toLowerCase().includes(q)) {
150
+ groups.push({
151
+ kind: "group",
152
+ id: chat.chat_id,
153
+ name: name || undefined,
154
+ });
155
+ }
156
+ }
157
+ if (groups.length >= limit) break;
158
+ }
159
+ }
160
+
161
+ return groups;
162
+ } catch {
163
+ return listFeishuDirectoryGroups(params);
164
+ }
165
+ }
@@ -0,0 +1,47 @@
1
+ import { Type, type Static } from "@sinclair/typebox";
2
+
3
+ export const FeishuDocSchema = Type.Union([
4
+ Type.Object({
5
+ action: Type.Literal("read"),
6
+ doc_token: Type.String({ description: "Document token (extract from URL /docx/XXX)" }),
7
+ }),
8
+ Type.Object({
9
+ action: Type.Literal("write"),
10
+ doc_token: Type.String({ description: "Document token" }),
11
+ content: Type.String({
12
+ description: "Markdown content to write (replaces entire document content)",
13
+ }),
14
+ }),
15
+ Type.Object({
16
+ action: Type.Literal("append"),
17
+ doc_token: Type.String({ description: "Document token" }),
18
+ content: Type.String({ description: "Markdown content to append to end of document" }),
19
+ }),
20
+ Type.Object({
21
+ action: Type.Literal("create"),
22
+ title: Type.String({ description: "Document title" }),
23
+ folder_token: Type.Optional(Type.String({ description: "Target folder token (optional)" })),
24
+ }),
25
+ Type.Object({
26
+ action: Type.Literal("list_blocks"),
27
+ doc_token: Type.String({ description: "Document token" }),
28
+ }),
29
+ Type.Object({
30
+ action: Type.Literal("get_block"),
31
+ doc_token: Type.String({ description: "Document token" }),
32
+ block_id: Type.String({ description: "Block ID (from list_blocks)" }),
33
+ }),
34
+ Type.Object({
35
+ action: Type.Literal("update_block"),
36
+ doc_token: Type.String({ description: "Document token" }),
37
+ block_id: Type.String({ description: "Block ID (from list_blocks)" }),
38
+ content: Type.String({ description: "New text content" }),
39
+ }),
40
+ Type.Object({
41
+ action: Type.Literal("delete_block"),
42
+ doc_token: Type.String({ description: "Document token" }),
43
+ block_id: Type.String({ description: "Block ID" }),
44
+ }),
45
+ ]);
46
+
47
+ export type FeishuDocParams = Static<typeof FeishuDocSchema>;
package/src/docx.ts ADDED
@@ -0,0 +1,480 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
3
+ import { createFeishuClient } from "./client.js";
4
+ import { resolveFeishuAccount, listEnabledFeishuAccounts } from "./accounts.js";
5
+ import type * as Lark from "@larksuiteoapi/node-sdk";
6
+ import { Readable } from "stream";
7
+ import { FeishuDocSchema, type FeishuDocParams } from "./doc-schema.js";
8
+ import { resolveToolsConfig } from "./tools-config.js";
9
+
10
+ // ============ Helpers ============
11
+
12
+ function json(data: unknown) {
13
+ return {
14
+ content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
15
+ details: data,
16
+ };
17
+ }
18
+
19
+ /** Extract image URLs from markdown content */
20
+ function extractImageUrls(markdown: string): string[] {
21
+ const regex = /!\[[^\]]*\]\(([^)]+)\)/g;
22
+ const urls: string[] = [];
23
+ let match;
24
+ while ((match = regex.exec(markdown)) !== null) {
25
+ const url = match[1].trim();
26
+ if (url.startsWith("http://") || url.startsWith("https://")) {
27
+ urls.push(url);
28
+ }
29
+ }
30
+ return urls;
31
+ }
32
+
33
+ const BLOCK_TYPE_NAMES: Record<number, string> = {
34
+ 1: "Page",
35
+ 2: "Text",
36
+ 3: "Heading1",
37
+ 4: "Heading2",
38
+ 5: "Heading3",
39
+ 12: "Bullet",
40
+ 13: "Ordered",
41
+ 14: "Code",
42
+ 15: "Quote",
43
+ 17: "Todo",
44
+ 18: "Bitable",
45
+ 21: "Diagram",
46
+ 22: "Divider",
47
+ 23: "File",
48
+ 27: "Image",
49
+ 30: "Sheet",
50
+ 31: "Table",
51
+ 32: "TableCell",
52
+ };
53
+
54
+ // Block types that cannot be created via documentBlockChildren.create API
55
+ const UNSUPPORTED_CREATE_TYPES = new Set([31, 32]);
56
+
57
+ /** Clean blocks for insertion (remove unsupported types and read-only fields) */
58
+ function cleanBlocksForInsert(blocks: any[]): { cleaned: any[]; skipped: string[] } {
59
+ const skipped: string[] = [];
60
+ const cleaned = blocks
61
+ .filter((block) => {
62
+ if (UNSUPPORTED_CREATE_TYPES.has(block.block_type)) {
63
+ const typeName = BLOCK_TYPE_NAMES[block.block_type] || `type_${block.block_type}`;
64
+ skipped.push(typeName);
65
+ return false;
66
+ }
67
+ return true;
68
+ })
69
+ .map((block) => {
70
+ if (block.block_type === 31 && block.table?.merge_info) {
71
+ const { merge_info, ...tableRest } = block.table;
72
+ return { ...block, table: tableRest };
73
+ }
74
+ return block;
75
+ });
76
+ return { cleaned, skipped };
77
+ }
78
+
79
+ // ============ Core Functions ============
80
+
81
+ async function convertMarkdown(client: Lark.Client, markdown: string) {
82
+ const res = await client.docx.document.convert({
83
+ data: { content_type: "markdown", content: markdown },
84
+ });
85
+ if (res.code !== 0) throw new Error(res.msg);
86
+ return {
87
+ blocks: res.data?.blocks ?? [],
88
+ firstLevelBlockIds: res.data?.first_level_block_ids ?? [],
89
+ };
90
+ }
91
+
92
+ async function insertBlocks(
93
+ client: Lark.Client,
94
+ docToken: string,
95
+ blocks: any[],
96
+ parentBlockId?: string,
97
+ ): Promise<{ children: any[]; skipped: string[] }> {
98
+ const { cleaned, skipped } = cleanBlocksForInsert(blocks);
99
+ const blockId = parentBlockId ?? docToken;
100
+
101
+ if (cleaned.length === 0) {
102
+ return { children: [], skipped };
103
+ }
104
+
105
+ const res = await client.docx.documentBlockChildren.create({
106
+ path: { document_id: docToken, block_id: blockId },
107
+ data: { children: cleaned },
108
+ });
109
+ if (res.code !== 0) throw new Error(res.msg);
110
+ return { children: res.data?.children ?? [], skipped };
111
+ }
112
+
113
+ async function clearDocumentContent(client: Lark.Client, docToken: string) {
114
+ const existing = await client.docx.documentBlock.list({
115
+ path: { document_id: docToken },
116
+ });
117
+ if (existing.code !== 0) throw new Error(existing.msg);
118
+
119
+ const childIds =
120
+ existing.data?.items
121
+ ?.filter((b) => b.parent_id === docToken && b.block_type !== 1)
122
+ .map((b) => b.block_id) ?? [];
123
+
124
+ if (childIds.length > 0) {
125
+ const res = await client.docx.documentBlockChildren.batchDelete({
126
+ path: { document_id: docToken, block_id: docToken },
127
+ data: { start_index: 0, end_index: childIds.length },
128
+ });
129
+ if (res.code !== 0) throw new Error(res.msg);
130
+ }
131
+
132
+ return childIds.length;
133
+ }
134
+
135
+ async function uploadImageToDocx(
136
+ client: Lark.Client,
137
+ blockId: string,
138
+ imageBuffer: Buffer,
139
+ fileName: string,
140
+ ): Promise<string> {
141
+ const res = await client.drive.media.uploadAll({
142
+ data: {
143
+ file_name: fileName,
144
+ parent_type: "docx_image",
145
+ parent_node: blockId,
146
+ size: imageBuffer.length,
147
+ file: Readable.from(imageBuffer) as any,
148
+ },
149
+ });
150
+
151
+ const fileToken = res?.file_token;
152
+ if (!fileToken) {
153
+ throw new Error("Image upload failed: no file_token returned");
154
+ }
155
+ return fileToken;
156
+ }
157
+
158
+ async function downloadImage(url: string): Promise<Buffer> {
159
+ const response = await fetch(url);
160
+ if (!response.ok) {
161
+ throw new Error(`Failed to download image: ${response.status} ${response.statusText}`);
162
+ }
163
+ return Buffer.from(await response.arrayBuffer());
164
+ }
165
+
166
+ async function processImages(
167
+ client: Lark.Client,
168
+ docToken: string,
169
+ markdown: string,
170
+ insertedBlocks: any[],
171
+ ): Promise<number> {
172
+ const imageUrls = extractImageUrls(markdown);
173
+ if (imageUrls.length === 0) return 0;
174
+
175
+ const imageBlocks = insertedBlocks.filter((b) => b.block_type === 27);
176
+
177
+ let processed = 0;
178
+ for (let i = 0; i < Math.min(imageUrls.length, imageBlocks.length); i++) {
179
+ const url = imageUrls[i];
180
+ const blockId = imageBlocks[i].block_id;
181
+
182
+ try {
183
+ const buffer = await downloadImage(url);
184
+ const urlPath = new URL(url).pathname;
185
+ const fileName = urlPath.split("/").pop() || `image_${i}.png`;
186
+ const fileToken = await uploadImageToDocx(client, blockId, buffer, fileName);
187
+
188
+ await client.docx.documentBlock.patch({
189
+ path: { document_id: docToken, block_id: blockId },
190
+ data: {
191
+ replace_image: { token: fileToken },
192
+ },
193
+ });
194
+
195
+ processed++;
196
+ } catch (err) {
197
+ console.error(`Failed to process image ${url}:`, err);
198
+ }
199
+ }
200
+
201
+ return processed;
202
+ }
203
+
204
+ // ============ Actions ============
205
+
206
+ const STRUCTURED_BLOCK_TYPES = new Set([14, 18, 21, 23, 27, 30, 31, 32]);
207
+
208
+ async function readDoc(client: Lark.Client, docToken: string) {
209
+ const [contentRes, infoRes, blocksRes] = await Promise.all([
210
+ client.docx.document.rawContent({ path: { document_id: docToken } }),
211
+ client.docx.document.get({ path: { document_id: docToken } }),
212
+ client.docx.documentBlock.list({ path: { document_id: docToken } }),
213
+ ]);
214
+
215
+ if (contentRes.code !== 0) throw new Error(contentRes.msg);
216
+
217
+ const blocks = blocksRes.data?.items ?? [];
218
+ const blockCounts: Record<string, number> = {};
219
+ const structuredTypes: string[] = [];
220
+
221
+ for (const b of blocks) {
222
+ const type = b.block_type ?? 0;
223
+ const name = BLOCK_TYPE_NAMES[type] || `type_${type}`;
224
+ blockCounts[name] = (blockCounts[name] || 0) + 1;
225
+
226
+ if (STRUCTURED_BLOCK_TYPES.has(type) && !structuredTypes.includes(name)) {
227
+ structuredTypes.push(name);
228
+ }
229
+ }
230
+
231
+ let hint: string | undefined;
232
+ if (structuredTypes.length > 0) {
233
+ hint = `This document contains ${structuredTypes.join(", ")} which are NOT included in the plain text above. Use feishu_doc with action: "list_blocks" to get full content.`;
234
+ }
235
+
236
+ return {
237
+ title: infoRes.data?.document?.title,
238
+ content: contentRes.data?.content,
239
+ revision_id: infoRes.data?.document?.revision_id,
240
+ block_count: blocks.length,
241
+ block_types: blockCounts,
242
+ ...(hint && { hint }),
243
+ };
244
+ }
245
+
246
+ async function createDoc(client: Lark.Client, title: string, folderToken?: string) {
247
+ const res = await client.docx.document.create({
248
+ data: { title, folder_token: folderToken },
249
+ });
250
+ if (res.code !== 0) throw new Error(res.msg);
251
+ const doc = res.data?.document;
252
+ return {
253
+ document_id: doc?.document_id,
254
+ title: doc?.title,
255
+ url: `https://feishu.cn/docx/${doc?.document_id}`,
256
+ };
257
+ }
258
+
259
+ async function writeDoc(client: Lark.Client, docToken: string, markdown: string) {
260
+ const deleted = await clearDocumentContent(client, docToken);
261
+
262
+ const { blocks } = await convertMarkdown(client, markdown);
263
+ if (blocks.length === 0) {
264
+ return { success: true, blocks_deleted: deleted, blocks_added: 0, images_processed: 0 };
265
+ }
266
+
267
+ const { children: inserted, skipped } = await insertBlocks(client, docToken, blocks);
268
+ const imagesProcessed = await processImages(client, docToken, markdown, inserted);
269
+
270
+ return {
271
+ success: true,
272
+ blocks_deleted: deleted,
273
+ blocks_added: inserted.length,
274
+ images_processed: imagesProcessed,
275
+ ...(skipped.length > 0 && {
276
+ warning: `Skipped unsupported block types: ${skipped.join(", ")}. Tables are not supported via this API.`,
277
+ }),
278
+ };
279
+ }
280
+
281
+ async function appendDoc(client: Lark.Client, docToken: string, markdown: string) {
282
+ const { blocks } = await convertMarkdown(client, markdown);
283
+ if (blocks.length === 0) {
284
+ throw new Error("Content is empty");
285
+ }
286
+
287
+ const { children: inserted, skipped } = await insertBlocks(client, docToken, blocks);
288
+ const imagesProcessed = await processImages(client, docToken, markdown, inserted);
289
+
290
+ return {
291
+ success: true,
292
+ blocks_added: inserted.length,
293
+ images_processed: imagesProcessed,
294
+ block_ids: inserted.map((b: any) => b.block_id),
295
+ ...(skipped.length > 0 && {
296
+ warning: `Skipped unsupported block types: ${skipped.join(", ")}. Tables are not supported via this API.`,
297
+ }),
298
+ };
299
+ }
300
+
301
+ async function updateBlock(
302
+ client: Lark.Client,
303
+ docToken: string,
304
+ blockId: string,
305
+ content: string,
306
+ ) {
307
+ const blockInfo = await client.docx.documentBlock.get({
308
+ path: { document_id: docToken, block_id: blockId },
309
+ });
310
+ if (blockInfo.code !== 0) throw new Error(blockInfo.msg);
311
+
312
+ const res = await client.docx.documentBlock.patch({
313
+ path: { document_id: docToken, block_id: blockId },
314
+ data: {
315
+ update_text_elements: {
316
+ elements: [{ text_run: { content } }],
317
+ },
318
+ },
319
+ });
320
+ if (res.code !== 0) throw new Error(res.msg);
321
+
322
+ return { success: true, block_id: blockId };
323
+ }
324
+
325
+ async function deleteBlock(client: Lark.Client, docToken: string, blockId: string) {
326
+ const blockInfo = await client.docx.documentBlock.get({
327
+ path: { document_id: docToken, block_id: blockId },
328
+ });
329
+ if (blockInfo.code !== 0) throw new Error(blockInfo.msg);
330
+
331
+ const parentId = blockInfo.data?.block?.parent_id ?? docToken;
332
+
333
+ const children = await client.docx.documentBlockChildren.get({
334
+ path: { document_id: docToken, block_id: parentId },
335
+ });
336
+ if (children.code !== 0) throw new Error(children.msg);
337
+
338
+ const items = children.data?.items ?? [];
339
+ const index = items.findIndex((item: any) => item.block_id === blockId);
340
+ if (index === -1) throw new Error("Block not found");
341
+
342
+ const res = await client.docx.documentBlockChildren.batchDelete({
343
+ path: { document_id: docToken, block_id: parentId },
344
+ data: { start_index: index, end_index: index + 1 },
345
+ });
346
+ if (res.code !== 0) throw new Error(res.msg);
347
+
348
+ return { success: true, deleted_block_id: blockId };
349
+ }
350
+
351
+ async function listBlocks(client: Lark.Client, docToken: string) {
352
+ const res = await client.docx.documentBlock.list({
353
+ path: { document_id: docToken },
354
+ });
355
+ if (res.code !== 0) throw new Error(res.msg);
356
+
357
+ return {
358
+ blocks: res.data?.items ?? [],
359
+ };
360
+ }
361
+
362
+ async function getBlock(client: Lark.Client, docToken: string, blockId: string) {
363
+ const res = await client.docx.documentBlock.get({
364
+ path: { document_id: docToken, block_id: blockId },
365
+ });
366
+ if (res.code !== 0) throw new Error(res.msg);
367
+
368
+ return {
369
+ block: res.data?.block,
370
+ };
371
+ }
372
+
373
+ async function listAppScopes(client: Lark.Client) {
374
+ const res = await client.application.scope.list({});
375
+ if (res.code !== 0) throw new Error(res.msg);
376
+
377
+ const scopes = res.data?.scopes ?? [];
378
+ const granted = scopes.filter((s) => s.grant_status === 1);
379
+ const pending = scopes.filter((s) => s.grant_status !== 1);
380
+
381
+ return {
382
+ granted: granted.map((s) => ({ name: s.scope_name, type: s.scope_type })),
383
+ pending: pending.map((s) => ({ name: s.scope_name, type: s.scope_type })),
384
+ summary: `${granted.length} granted, ${pending.length} pending`,
385
+ };
386
+ }
387
+
388
+ // ============ Tool Registration ============
389
+
390
+ export function registerFeishuDocTools(api: OpenClawPluginApi) {
391
+ if (!api.config) {
392
+ api.logger.debug?.("feishu_doc: No config available, skipping doc tools");
393
+ return;
394
+ }
395
+
396
+ // Check if any account is configured
397
+ const accounts = listEnabledFeishuAccounts(api.config);
398
+ if (accounts.length === 0) {
399
+ api.logger.debug?.("feishu_doc: No Feishu accounts configured, skipping doc tools");
400
+ return;
401
+ }
402
+
403
+ // Use first account's config for tools configuration
404
+ const firstAccount = accounts[0];
405
+ const toolsCfg = resolveToolsConfig(firstAccount.config.tools);
406
+
407
+ // Helper to get client for the default account
408
+ const getClient = () => createFeishuClient(firstAccount);
409
+ const registered: string[] = [];
410
+
411
+ // Main document tool with action-based dispatch
412
+ if (toolsCfg.doc) {
413
+ api.registerTool(
414
+ {
415
+ name: "feishu_doc",
416
+ label: "Feishu Doc",
417
+ description:
418
+ "Feishu document operations. Actions: read, write, append, create, list_blocks, get_block, update_block, delete_block",
419
+ parameters: FeishuDocSchema,
420
+ async execute(_toolCallId, params) {
421
+ const p = params as FeishuDocParams;
422
+ try {
423
+ const client = getClient();
424
+ switch (p.action) {
425
+ case "read":
426
+ return json(await readDoc(client, p.doc_token));
427
+ case "write":
428
+ return json(await writeDoc(client, p.doc_token, p.content));
429
+ case "append":
430
+ return json(await appendDoc(client, p.doc_token, p.content));
431
+ case "create":
432
+ return json(await createDoc(client, p.title, p.folder_token));
433
+ case "list_blocks":
434
+ return json(await listBlocks(client, p.doc_token));
435
+ case "get_block":
436
+ return json(await getBlock(client, p.doc_token, p.block_id));
437
+ case "update_block":
438
+ return json(await updateBlock(client, p.doc_token, p.block_id, p.content));
439
+ case "delete_block":
440
+ return json(await deleteBlock(client, p.doc_token, p.block_id));
441
+ default:
442
+ return json({ error: `Unknown action: ${(p as any).action}` });
443
+ }
444
+ } catch (err) {
445
+ return json({ error: err instanceof Error ? err.message : String(err) });
446
+ }
447
+ },
448
+ },
449
+ { name: "feishu_doc" },
450
+ );
451
+ registered.push("feishu_doc");
452
+ }
453
+
454
+ // Keep feishu_app_scopes as independent tool
455
+ if (toolsCfg.scopes) {
456
+ api.registerTool(
457
+ {
458
+ name: "feishu_app_scopes",
459
+ label: "Feishu App Scopes",
460
+ description:
461
+ "List current app permissions (scopes). Use to debug permission issues or check available capabilities.",
462
+ parameters: Type.Object({}),
463
+ async execute() {
464
+ try {
465
+ const result = await listAppScopes(getClient());
466
+ return json(result);
467
+ } catch (err) {
468
+ return json({ error: err instanceof Error ? err.message : String(err) });
469
+ }
470
+ },
471
+ },
472
+ { name: "feishu_app_scopes" },
473
+ );
474
+ registered.push("feishu_app_scopes");
475
+ }
476
+
477
+ if (registered.length > 0) {
478
+ api.logger.info?.(`feishu_doc: Registered ${registered.join(", ")}`);
479
+ }
480
+ }