@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.
package/src/bitable.ts ADDED
@@ -0,0 +1,441 @@
1
+ import { Type } from "@sinclair/typebox";
2
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
3
+ import { createFeishuClient } from "./client.js";
4
+ import type { FeishuConfig } from "./types.js";
5
+
6
+ // ============ Helpers ============
7
+
8
+ function json(data: unknown) {
9
+ return {
10
+ content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
11
+ details: data,
12
+ };
13
+ }
14
+
15
+ /** Field type ID to human-readable name */
16
+ const FIELD_TYPE_NAMES: Record<number, string> = {
17
+ 1: "Text",
18
+ 2: "Number",
19
+ 3: "SingleSelect",
20
+ 4: "MultiSelect",
21
+ 5: "DateTime",
22
+ 7: "Checkbox",
23
+ 11: "User",
24
+ 13: "Phone",
25
+ 15: "URL",
26
+ 17: "Attachment",
27
+ 18: "SingleLink",
28
+ 19: "Lookup",
29
+ 20: "Formula",
30
+ 21: "DuplexLink",
31
+ 22: "Location",
32
+ 23: "GroupChat",
33
+ 1001: "CreatedTime",
34
+ 1002: "ModifiedTime",
35
+ 1003: "CreatedUser",
36
+ 1004: "ModifiedUser",
37
+ 1005: "AutoNumber",
38
+ };
39
+
40
+ // ============ Core Functions ============
41
+
42
+ /** Parse bitable URL and extract tokens */
43
+ function parseBitableUrl(url: string): { token: string; tableId?: string; isWiki: boolean } | null {
44
+ try {
45
+ const u = new URL(url);
46
+ const tableId = u.searchParams.get("table") ?? undefined;
47
+
48
+ // Wiki format: /wiki/XXXXX?table=YYY
49
+ const wikiMatch = u.pathname.match(/\/wiki\/([A-Za-z0-9]+)/);
50
+ if (wikiMatch) {
51
+ return { token: wikiMatch[1], tableId, isWiki: true };
52
+ }
53
+
54
+ // Base format: /base/XXXXX?table=YYY
55
+ const baseMatch = u.pathname.match(/\/base\/([A-Za-z0-9]+)/);
56
+ if (baseMatch) {
57
+ return { token: baseMatch[1], tableId, isWiki: false };
58
+ }
59
+
60
+ return null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ /** Get app_token from wiki node_token */
67
+ async function getAppTokenFromWiki(
68
+ client: ReturnType<typeof createFeishuClient>,
69
+ nodeToken: string,
70
+ ): Promise<string> {
71
+ const res = await client.wiki.space.getNode({
72
+ params: { token: nodeToken },
73
+ });
74
+ if (res.code !== 0) throw new Error(res.msg);
75
+
76
+ const node = res.data?.node;
77
+ if (!node) throw new Error("Node not found");
78
+ if (node.obj_type !== "bitable") {
79
+ throw new Error(`Node is not a bitable (type: ${node.obj_type})`);
80
+ }
81
+
82
+ return node.obj_token!;
83
+ }
84
+
85
+ /** Get bitable metadata from URL (handles both /base/ and /wiki/ URLs) */
86
+ async function getBitableMeta(
87
+ client: ReturnType<typeof createFeishuClient>,
88
+ url: string,
89
+ ) {
90
+ const parsed = parseBitableUrl(url);
91
+ if (!parsed) {
92
+ throw new Error("Invalid URL format. Expected /base/XXX or /wiki/XXX URL");
93
+ }
94
+
95
+ let appToken: string;
96
+ if (parsed.isWiki) {
97
+ appToken = await getAppTokenFromWiki(client, parsed.token);
98
+ } else {
99
+ appToken = parsed.token;
100
+ }
101
+
102
+ // Get bitable app info
103
+ const res = await client.bitable.app.get({
104
+ path: { app_token: appToken },
105
+ });
106
+ if (res.code !== 0) throw new Error(res.msg);
107
+
108
+ // List tables if no table_id specified
109
+ let tables: { table_id: string; name: string }[] = [];
110
+ if (!parsed.tableId) {
111
+ const tablesRes = await client.bitable.appTable.list({
112
+ path: { app_token: appToken },
113
+ });
114
+ if (tablesRes.code === 0) {
115
+ tables = (tablesRes.data?.items ?? []).map((t) => ({
116
+ table_id: t.table_id!,
117
+ name: t.name!,
118
+ }));
119
+ }
120
+ }
121
+
122
+ return {
123
+ app_token: appToken,
124
+ table_id: parsed.tableId,
125
+ name: res.data?.app?.name,
126
+ url_type: parsed.isWiki ? "wiki" : "base",
127
+ ...(tables.length > 0 && { tables }),
128
+ hint: parsed.tableId
129
+ ? `Use app_token="${appToken}" and table_id="${parsed.tableId}" for other bitable tools`
130
+ : `Use app_token="${appToken}" for other bitable tools. Select a table_id from the tables list.`,
131
+ };
132
+ }
133
+
134
+ async function listFields(
135
+ client: ReturnType<typeof createFeishuClient>,
136
+ appToken: string,
137
+ tableId: string,
138
+ ) {
139
+ const res = await client.bitable.appTableField.list({
140
+ path: { app_token: appToken, table_id: tableId },
141
+ });
142
+ if (res.code !== 0) throw new Error(res.msg);
143
+
144
+ const fields = res.data?.items ?? [];
145
+ return {
146
+ fields: fields.map((f) => ({
147
+ field_id: f.field_id,
148
+ field_name: f.field_name,
149
+ type: f.type,
150
+ type_name: FIELD_TYPE_NAMES[f.type ?? 0] || `type_${f.type}`,
151
+ is_primary: f.is_primary,
152
+ ...(f.property && { property: f.property }),
153
+ })),
154
+ total: fields.length,
155
+ };
156
+ }
157
+
158
+ async function listRecords(
159
+ client: ReturnType<typeof createFeishuClient>,
160
+ appToken: string,
161
+ tableId: string,
162
+ pageSize?: number,
163
+ pageToken?: string,
164
+ ) {
165
+ const res = await client.bitable.appTableRecord.list({
166
+ path: { app_token: appToken, table_id: tableId },
167
+ params: {
168
+ page_size: pageSize ?? 100,
169
+ ...(pageToken && { page_token: pageToken }),
170
+ },
171
+ });
172
+ if (res.code !== 0) throw new Error(res.msg);
173
+
174
+ return {
175
+ records: res.data?.items ?? [],
176
+ has_more: res.data?.has_more ?? false,
177
+ page_token: res.data?.page_token,
178
+ total: res.data?.total,
179
+ };
180
+ }
181
+
182
+ async function getRecord(
183
+ client: ReturnType<typeof createFeishuClient>,
184
+ appToken: string,
185
+ tableId: string,
186
+ recordId: string,
187
+ ) {
188
+ const res = await client.bitable.appTableRecord.get({
189
+ path: { app_token: appToken, table_id: tableId, record_id: recordId },
190
+ });
191
+ if (res.code !== 0) throw new Error(res.msg);
192
+
193
+ return {
194
+ record: res.data?.record,
195
+ };
196
+ }
197
+
198
+ async function createRecord(
199
+ client: ReturnType<typeof createFeishuClient>,
200
+ appToken: string,
201
+ tableId: string,
202
+ fields: Record<string, unknown>,
203
+ ) {
204
+ const res = await client.bitable.appTableRecord.create({
205
+ path: { app_token: appToken, table_id: tableId },
206
+ data: { fields },
207
+ });
208
+ if (res.code !== 0) throw new Error(res.msg);
209
+
210
+ return {
211
+ record: res.data?.record,
212
+ };
213
+ }
214
+
215
+ async function updateRecord(
216
+ client: ReturnType<typeof createFeishuClient>,
217
+ appToken: string,
218
+ tableId: string,
219
+ recordId: string,
220
+ fields: Record<string, unknown>,
221
+ ) {
222
+ const res = await client.bitable.appTableRecord.update({
223
+ path: { app_token: appToken, table_id: tableId, record_id: recordId },
224
+ data: { fields },
225
+ });
226
+ if (res.code !== 0) throw new Error(res.msg);
227
+
228
+ return {
229
+ record: res.data?.record,
230
+ };
231
+ }
232
+
233
+ // ============ Schemas ============
234
+
235
+ const GetMetaSchema = Type.Object({
236
+ url: Type.String({
237
+ description:
238
+ "Bitable URL. Supports both formats: /base/XXX?table=YYY or /wiki/XXX?table=YYY",
239
+ }),
240
+ });
241
+
242
+ const ListFieldsSchema = Type.Object({
243
+ app_token: Type.String({
244
+ description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
245
+ }),
246
+ table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
247
+ });
248
+
249
+ const ListRecordsSchema = Type.Object({
250
+ app_token: Type.String({
251
+ description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
252
+ }),
253
+ table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
254
+ page_size: Type.Optional(
255
+ Type.Number({ description: "Number of records per page (1-500, default 100)", minimum: 1, maximum: 500 }),
256
+ ),
257
+ page_token: Type.Optional(Type.String({ description: "Pagination token from previous response" })),
258
+ });
259
+
260
+ const GetRecordSchema = Type.Object({
261
+ app_token: Type.String({
262
+ description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
263
+ }),
264
+ table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
265
+ record_id: Type.String({ description: "Record ID to retrieve" }),
266
+ });
267
+
268
+ const CreateRecordSchema = Type.Object({
269
+ app_token: Type.String({
270
+ description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
271
+ }),
272
+ table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
273
+ fields: Type.Record(Type.String(), Type.Any(), {
274
+ description:
275
+ "Field values keyed by field name. Format by type: Text='string', Number=123, SingleSelect='Option', MultiSelect=['A','B'], DateTime=timestamp_ms, User=[{id:'ou_xxx'}], URL={text:'Display',link:'https://...'}",
276
+ }),
277
+ });
278
+
279
+ const UpdateRecordSchema = Type.Object({
280
+ app_token: Type.String({
281
+ description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
282
+ }),
283
+ table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
284
+ record_id: Type.String({ description: "Record ID to update" }),
285
+ fields: Type.Record(Type.String(), Type.Any(), {
286
+ description: "Field values to update (same format as create_record)",
287
+ }),
288
+ });
289
+
290
+ // ============ Tool Registration ============
291
+
292
+ export function registerFeishuBitableTools(api: OpenClawPluginApi) {
293
+ const feishuCfg = api.config?.channels?.feishu as FeishuConfig | undefined;
294
+ if (!feishuCfg?.appId || !feishuCfg?.appSecret) {
295
+ api.logger.debug?.("feishu_bitable: Feishu credentials not configured, skipping bitable tools");
296
+ return;
297
+ }
298
+
299
+ const getClient = () => createFeishuClient(feishuCfg);
300
+
301
+ // Tool 0: feishu_bitable_get_meta (helper to parse URLs)
302
+ api.registerTool(
303
+ {
304
+ name: "feishu_bitable_get_meta",
305
+ label: "Feishu Bitable Get Meta",
306
+ description:
307
+ "Parse a Bitable URL and get app_token, table_id, and table list. Use this first when given a /wiki/ or /base/ URL.",
308
+ parameters: GetMetaSchema,
309
+ async execute(_toolCallId, params) {
310
+ const { url } = params as { url: string };
311
+ try {
312
+ const result = await getBitableMeta(getClient(), url);
313
+ return json(result);
314
+ } catch (err) {
315
+ return json({ error: err instanceof Error ? err.message : String(err) });
316
+ }
317
+ },
318
+ },
319
+ { name: "feishu_bitable_get_meta" },
320
+ );
321
+
322
+ // Tool 1: feishu_bitable_list_fields
323
+ api.registerTool(
324
+ {
325
+ name: "feishu_bitable_list_fields",
326
+ label: "Feishu Bitable List Fields",
327
+ description: "List all fields (columns) in a Bitable table with their types and properties",
328
+ parameters: ListFieldsSchema,
329
+ async execute(_toolCallId, params) {
330
+ const { app_token, table_id } = params as { app_token: string; table_id: string };
331
+ try {
332
+ const result = await listFields(getClient(), app_token, table_id);
333
+ return json(result);
334
+ } catch (err) {
335
+ return json({ error: err instanceof Error ? err.message : String(err) });
336
+ }
337
+ },
338
+ },
339
+ { name: "feishu_bitable_list_fields" },
340
+ );
341
+
342
+ // Tool 2: feishu_bitable_list_records
343
+ api.registerTool(
344
+ {
345
+ name: "feishu_bitable_list_records",
346
+ label: "Feishu Bitable List Records",
347
+ description: "List records (rows) from a Bitable table with pagination support",
348
+ parameters: ListRecordsSchema,
349
+ async execute(_toolCallId, params) {
350
+ const { app_token, table_id, page_size, page_token } = params as {
351
+ app_token: string;
352
+ table_id: string;
353
+ page_size?: number;
354
+ page_token?: string;
355
+ };
356
+ try {
357
+ const result = await listRecords(getClient(), app_token, table_id, page_size, page_token);
358
+ return json(result);
359
+ } catch (err) {
360
+ return json({ error: err instanceof Error ? err.message : String(err) });
361
+ }
362
+ },
363
+ },
364
+ { name: "feishu_bitable_list_records" },
365
+ );
366
+
367
+ // Tool 3: feishu_bitable_get_record
368
+ api.registerTool(
369
+ {
370
+ name: "feishu_bitable_get_record",
371
+ label: "Feishu Bitable Get Record",
372
+ description: "Get a single record by ID from a Bitable table",
373
+ parameters: GetRecordSchema,
374
+ async execute(_toolCallId, params) {
375
+ const { app_token, table_id, record_id } = params as {
376
+ app_token: string;
377
+ table_id: string;
378
+ record_id: string;
379
+ };
380
+ try {
381
+ const result = await getRecord(getClient(), app_token, table_id, record_id);
382
+ return json(result);
383
+ } catch (err) {
384
+ return json({ error: err instanceof Error ? err.message : String(err) });
385
+ }
386
+ },
387
+ },
388
+ { name: "feishu_bitable_get_record" },
389
+ );
390
+
391
+ // Tool 4: feishu_bitable_create_record
392
+ api.registerTool(
393
+ {
394
+ name: "feishu_bitable_create_record",
395
+ label: "Feishu Bitable Create Record",
396
+ description: "Create a new record (row) in a Bitable table",
397
+ parameters: CreateRecordSchema,
398
+ async execute(_toolCallId, params) {
399
+ const { app_token, table_id, fields } = params as {
400
+ app_token: string;
401
+ table_id: string;
402
+ fields: Record<string, unknown>;
403
+ };
404
+ try {
405
+ const result = await createRecord(getClient(), app_token, table_id, fields);
406
+ return json(result);
407
+ } catch (err) {
408
+ return json({ error: err instanceof Error ? err.message : String(err) });
409
+ }
410
+ },
411
+ },
412
+ { name: "feishu_bitable_create_record" },
413
+ );
414
+
415
+ // Tool 5: feishu_bitable_update_record
416
+ api.registerTool(
417
+ {
418
+ name: "feishu_bitable_update_record",
419
+ label: "Feishu Bitable Update Record",
420
+ description: "Update an existing record (row) in a Bitable table",
421
+ parameters: UpdateRecordSchema,
422
+ async execute(_toolCallId, params) {
423
+ const { app_token, table_id, record_id, fields } = params as {
424
+ app_token: string;
425
+ table_id: string;
426
+ record_id: string;
427
+ fields: Record<string, unknown>;
428
+ };
429
+ try {
430
+ const result = await updateRecord(getClient(), app_token, table_id, record_id, fields);
431
+ return json(result);
432
+ } catch (err) {
433
+ return json({ error: err instanceof Error ? err.message : String(err) });
434
+ }
435
+ },
436
+ },
437
+ { name: "feishu_bitable_update_record" },
438
+ );
439
+
440
+ api.logger.info?.(`feishu_bitable: Registered 6 bitable tools`);
441
+ }