@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/bitable.ts DELETED
@@ -1,762 +0,0 @@
1
- import type * as Lark from "@larksuiteoapi/node-sdk";
2
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
3
- import { Type, type TSchema } from "typebox";
4
- import type { KlawPluginApi } from "../runtime-api.js";
5
- import { listEnabledFeishuAccounts } from "./accounts.js";
6
- import { createFeishuToolClient } from "./tool-account.js";
7
-
8
- // ============ Helpers ============
9
-
10
- function json(data: unknown) {
11
- return {
12
- content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
13
- details: data,
14
- };
15
- }
16
-
17
- type LarkResponse<T = unknown> = { code?: number; msg?: string; data?: T };
18
- type BitableRecordCreatePayload = NonNullable<
19
- Parameters<Lark.Client["bitable"]["appTableRecord"]["create"]>[0]
20
- >;
21
- type BitableRecordUpdatePayload = NonNullable<
22
- Parameters<Lark.Client["bitable"]["appTableRecord"]["update"]>[0]
23
- >;
24
- type BitableRecordFields = NonNullable<NonNullable<BitableRecordCreatePayload["data"]>["fields"]>;
25
- type BitableRecordUpdateFields = NonNullable<
26
- NonNullable<BitableRecordUpdatePayload["data"]>["fields"]
27
- >;
28
-
29
- export class LarkApiError extends Error {
30
- readonly code: number;
31
- readonly api: string;
32
- readonly context?: Record<string, unknown>;
33
- constructor(code: number, message: string, api: string, context?: Record<string, unknown>) {
34
- super(`[${api}] code=${code} message=${message}`);
35
- this.name = "LarkApiError";
36
- this.code = code;
37
- this.api = api;
38
- this.context = context;
39
- }
40
- }
41
-
42
- function ensureLarkSuccess<T>(
43
- res: LarkResponse<T>,
44
- api: string,
45
- context?: Record<string, unknown>,
46
- ): asserts res is LarkResponse<T> & { code: 0 } {
47
- if (res.code !== 0) {
48
- throw new LarkApiError(res.code ?? -1, res.msg ?? "unknown error", api, context);
49
- }
50
- }
51
-
52
- /** Field type ID to human-readable name */
53
- const FIELD_TYPE_NAMES: Record<number, string> = {
54
- 1: "Text",
55
- 2: "Number",
56
- 3: "SingleSelect",
57
- 4: "MultiSelect",
58
- 5: "DateTime",
59
- 7: "Checkbox",
60
- 11: "User",
61
- 13: "Phone",
62
- 15: "URL",
63
- 17: "Attachment",
64
- 18: "SingleLink",
65
- 19: "Lookup",
66
- 20: "Formula",
67
- 21: "DuplexLink",
68
- 22: "Location",
69
- 23: "GroupChat",
70
- 1001: "CreatedTime",
71
- 1002: "ModifiedTime",
72
- 1003: "CreatedUser",
73
- 1004: "ModifiedUser",
74
- 1005: "AutoNumber",
75
- };
76
-
77
- // ============ Core Functions ============
78
-
79
- /** Parse bitable URL and extract tokens */
80
- function parseBitableUrl(url: string): { token: string; tableId?: string; isWiki: boolean } | null {
81
- try {
82
- const u = new URL(url);
83
- const tableId = u.searchParams.get("table") ?? undefined;
84
-
85
- // Wiki format: /wiki/XXXXX?table=YYY
86
- const wikiMatch = u.pathname.match(/\/wiki\/([A-Za-z0-9]+)/);
87
- if (wikiMatch) {
88
- return { token: wikiMatch[1], tableId, isWiki: true };
89
- }
90
-
91
- // Base format: /base/XXXXX?table=YYY
92
- const baseMatch = u.pathname.match(/\/base\/([A-Za-z0-9]+)/);
93
- if (baseMatch) {
94
- return { token: baseMatch[1], tableId, isWiki: false };
95
- }
96
-
97
- return null;
98
- } catch {
99
- return null;
100
- }
101
- }
102
-
103
- /** Get app_token from wiki node_token */
104
- async function getAppTokenFromWiki(client: Lark.Client, nodeToken: string): Promise<string> {
105
- const res = await client.wiki.space.getNode({
106
- params: { token: nodeToken },
107
- });
108
- ensureLarkSuccess(res, "wiki.space.getNode", { nodeToken });
109
-
110
- const node = res.data?.node;
111
- if (!node) {
112
- throw new Error("Node not found");
113
- }
114
- if (node.obj_type !== "bitable") {
115
- throw new Error(`Node is not a bitable (type: ${node.obj_type})`);
116
- }
117
-
118
- return node.obj_token!;
119
- }
120
-
121
- /** Get bitable metadata from URL (handles both /base/ and /wiki/ URLs) */
122
- async function getBitableMeta(client: Lark.Client, url: string) {
123
- const parsed = parseBitableUrl(url);
124
- if (!parsed) {
125
- throw new Error("Invalid URL format. Expected /base/XXX or /wiki/XXX URL");
126
- }
127
-
128
- let appToken: string;
129
- if (parsed.isWiki) {
130
- appToken = await getAppTokenFromWiki(client, parsed.token);
131
- } else {
132
- appToken = parsed.token;
133
- }
134
-
135
- // Get bitable app info
136
- const res = await client.bitable.app.get({
137
- path: { app_token: appToken },
138
- });
139
- ensureLarkSuccess(res, "bitable.app.get", { appToken });
140
-
141
- // List tables if no table_id specified
142
- let tables: { table_id: string; name: string }[] = [];
143
- if (!parsed.tableId) {
144
- const tablesRes = await client.bitable.appTable.list({
145
- path: { app_token: appToken },
146
- });
147
- if (tablesRes.code === 0) {
148
- tables = (tablesRes.data?.items ?? []).map((t) => ({
149
- table_id: t.table_id!,
150
- name: t.name!,
151
- }));
152
- }
153
- }
154
-
155
- return {
156
- app_token: appToken,
157
- table_id: parsed.tableId,
158
- name: res.data?.app?.name,
159
- url_type: parsed.isWiki ? "wiki" : "base",
160
- ...(tables.length > 0 && { tables }),
161
- hint: parsed.tableId
162
- ? `Use app_token="${appToken}" and table_id="${parsed.tableId}" for other bitable tools`
163
- : `Use app_token="${appToken}" for other bitable tools. Select a table_id from the tables list.`,
164
- };
165
- }
166
-
167
- async function listFields(client: Lark.Client, appToken: string, tableId: string) {
168
- const res = await client.bitable.appTableField.list({
169
- path: { app_token: appToken, table_id: tableId },
170
- });
171
- ensureLarkSuccess(res, "bitable.appTableField.list", { appToken, tableId });
172
-
173
- const fields = res.data?.items ?? [];
174
- return {
175
- fields: fields.map((f) => ({
176
- field_id: f.field_id,
177
- field_name: f.field_name,
178
- type: f.type,
179
- type_name: FIELD_TYPE_NAMES[f.type ?? 0] || `type_${f.type}`,
180
- is_primary: f.is_primary,
181
- ...(f.property && { property: f.property }),
182
- })),
183
- total: fields.length,
184
- };
185
- }
186
-
187
- async function listRecords(
188
- client: Lark.Client,
189
- appToken: string,
190
- tableId: string,
191
- pageSize?: number,
192
- pageToken?: string,
193
- ) {
194
- const res = await client.bitable.appTableRecord.list({
195
- path: { app_token: appToken, table_id: tableId },
196
- params: {
197
- page_size: pageSize ?? 100,
198
- ...(pageToken && { page_token: pageToken }),
199
- },
200
- });
201
- ensureLarkSuccess(res, "bitable.appTableRecord.list", { appToken, tableId, pageSize });
202
-
203
- return {
204
- records: res.data?.items ?? [],
205
- has_more: res.data?.has_more ?? false,
206
- page_token: res.data?.page_token,
207
- total: res.data?.total,
208
- };
209
- }
210
-
211
- async function getRecord(client: Lark.Client, appToken: string, tableId: string, recordId: string) {
212
- const res = await client.bitable.appTableRecord.get({
213
- path: { app_token: appToken, table_id: tableId, record_id: recordId },
214
- });
215
- ensureLarkSuccess(res, "bitable.appTableRecord.get", { appToken, tableId, recordId });
216
-
217
- return {
218
- record: res.data?.record,
219
- };
220
- }
221
-
222
- async function createRecord(
223
- client: Lark.Client,
224
- appToken: string,
225
- tableId: string,
226
- fields: BitableRecordFields,
227
- ) {
228
- const res = await client.bitable.appTableRecord.create({
229
- path: { app_token: appToken, table_id: tableId },
230
- data: { fields },
231
- });
232
- ensureLarkSuccess(res, "bitable.appTableRecord.create", { appToken, tableId });
233
-
234
- return {
235
- record: res.data?.record,
236
- };
237
- }
238
-
239
- /** Logger interface for cleanup operations */
240
- type CleanupLogger = {
241
- debug: (msg: string) => void;
242
- warn: (msg: string) => void;
243
- };
244
-
245
- /** Default field types created for new Bitable tables (to be cleaned up) */
246
- const DEFAULT_CLEANUP_FIELD_TYPES = new Set([3, 5, 17]); // SingleSelect, DateTime, Attachment
247
-
248
- function isDefaultEmptyBitableFieldValue(value: unknown): boolean {
249
- if (value === undefined || value === null || value === "") {
250
- return true;
251
- }
252
- if (Array.isArray(value)) {
253
- return value.every(isDefaultEmptyBitableFieldValue);
254
- }
255
- if (typeof value === "object") {
256
- const record = value as Record<string, unknown>;
257
- const keys = Object.keys(record);
258
- if (keys.length === 0) {
259
- return true;
260
- }
261
- if ("text" in record && keys.every((key) => key === "text" || key === "type")) {
262
- return record.text === undefined || record.text === null || record.text === "";
263
- }
264
- return Object.values(record).every(isDefaultEmptyBitableFieldValue);
265
- }
266
- return false;
267
- }
268
-
269
- function isPlaceholderBitableRecord(fields: unknown): boolean {
270
- if (!fields || typeof fields !== "object" || Array.isArray(fields)) {
271
- return true;
272
- }
273
- const values = Object.values(fields);
274
- return values.every(isDefaultEmptyBitableFieldValue);
275
- }
276
-
277
- /** Clean up default placeholder rows and fields in a newly created Bitable table */
278
- async function cleanupNewBitable(
279
- client: Lark.Client,
280
- appToken: string,
281
- tableId: string,
282
- tableName: string,
283
- logger: CleanupLogger,
284
- ): Promise<{ cleanedRows: number; cleanedFields: number }> {
285
- let cleanedRows = 0;
286
- let cleanedFields = 0;
287
-
288
- // Step 1: Clean up default fields
289
- const fieldsRes = await client.bitable.appTableField.list({
290
- path: { app_token: appToken, table_id: tableId },
291
- });
292
-
293
- if (fieldsRes.code === 0 && fieldsRes.data?.items) {
294
- // Step 1a: Rename primary field to the table name (works for both Feishu and Lark)
295
- const primaryField = fieldsRes.data.items.find((f) => f.is_primary);
296
- if (primaryField?.field_id) {
297
- try {
298
- const newFieldName = tableName.length <= 20 ? tableName : "Name";
299
- await client.bitable.appTableField.update({
300
- path: {
301
- app_token: appToken,
302
- table_id: tableId,
303
- field_id: primaryField.field_id,
304
- },
305
- data: {
306
- field_name: newFieldName,
307
- type: 1,
308
- },
309
- });
310
- cleanedFields++;
311
- } catch (err) {
312
- logger.debug(`Failed to rename primary field: ${String(err)}`);
313
- }
314
- }
315
-
316
- // Step 1b: Delete default placeholder fields by type (works for both Feishu and Lark)
317
- const defaultFieldsToDelete = fieldsRes.data.items.filter(
318
- (f) => !f.is_primary && DEFAULT_CLEANUP_FIELD_TYPES.has(f.type ?? 0),
319
- );
320
-
321
- for (const field of defaultFieldsToDelete) {
322
- if (field.field_id) {
323
- try {
324
- await client.bitable.appTableField.delete({
325
- path: {
326
- app_token: appToken,
327
- table_id: tableId,
328
- field_id: field.field_id,
329
- },
330
- });
331
- cleanedFields++;
332
- } catch (err) {
333
- logger.debug(`Failed to delete default field ${field.field_name}: ${String(err)}`);
334
- }
335
- }
336
- }
337
- }
338
-
339
- // Step 2: Delete empty placeholder rows (batch when possible)
340
- const recordsRes = await client.bitable.appTableRecord.list({
341
- path: { app_token: appToken, table_id: tableId },
342
- params: { page_size: 100 },
343
- });
344
-
345
- if (recordsRes.code === 0 && recordsRes.data?.items) {
346
- const emptyRecordIds = recordsRes.data.items
347
- .filter((r) => isPlaceholderBitableRecord(r.fields))
348
- .map((r) => r.record_id)
349
- .filter((id): id is string => Boolean(id));
350
-
351
- if (emptyRecordIds.length > 0) {
352
- try {
353
- await client.bitable.appTableRecord.batchDelete({
354
- path: { app_token: appToken, table_id: tableId },
355
- data: { records: emptyRecordIds },
356
- });
357
- cleanedRows = emptyRecordIds.length;
358
- } catch {
359
- // Fallback: delete one by one if batch API is unavailable
360
- for (const recordId of emptyRecordIds) {
361
- try {
362
- await client.bitable.appTableRecord.delete({
363
- path: { app_token: appToken, table_id: tableId, record_id: recordId },
364
- });
365
- cleanedRows++;
366
- } catch (err) {
367
- logger.debug(`Failed to delete empty row ${recordId}: ${String(err)}`);
368
- }
369
- }
370
- }
371
- }
372
- }
373
-
374
- return { cleanedRows, cleanedFields };
375
- }
376
-
377
- async function createApp(
378
- client: Lark.Client,
379
- name: string,
380
- folderToken?: string,
381
- logger?: CleanupLogger,
382
- ) {
383
- const res = await client.bitable.app.create({
384
- data: {
385
- name,
386
- ...(folderToken && { folder_token: folderToken }),
387
- },
388
- });
389
- ensureLarkSuccess(res, "bitable.app.create", { name, folderToken });
390
-
391
- const appToken = res.data?.app?.app_token;
392
- if (!appToken) {
393
- throw new Error("Failed to create Bitable: no app_token returned");
394
- }
395
-
396
- const log: CleanupLogger = logger ?? { debug: () => {}, warn: () => {} };
397
- let tableId: string | undefined;
398
- let cleanedRows = 0;
399
- let cleanedFields = 0;
400
-
401
- try {
402
- const tablesRes = await client.bitable.appTable.list({
403
- path: { app_token: appToken },
404
- });
405
- if (tablesRes.code === 0 && tablesRes.data?.items && tablesRes.data.items.length > 0) {
406
- tableId = tablesRes.data.items[0].table_id ?? undefined;
407
- if (tableId) {
408
- const cleanup = await cleanupNewBitable(client, appToken, tableId, name, log);
409
- cleanedRows = cleanup.cleanedRows;
410
- cleanedFields = cleanup.cleanedFields;
411
- }
412
- }
413
- } catch (err) {
414
- log.debug(`Cleanup failed (non-critical): ${String(err)}`);
415
- }
416
-
417
- return {
418
- app_token: appToken,
419
- table_id: tableId,
420
- name: res.data?.app?.name,
421
- url: res.data?.app?.url,
422
- cleaned_placeholder_rows: cleanedRows,
423
- cleaned_default_fields: cleanedFields,
424
- hint: tableId
425
- ? `Table created. Use app_token="${appToken}" and table_id="${tableId}" for other bitable tools.`
426
- : "Table created. Use feishu_bitable_get_meta to get table_id and field details.",
427
- };
428
- }
429
-
430
- async function createField(
431
- client: Lark.Client,
432
- appToken: string,
433
- tableId: string,
434
- fieldName: string,
435
- fieldType: number,
436
- property?: Record<string, unknown>,
437
- ) {
438
- const res = await client.bitable.appTableField.create({
439
- path: { app_token: appToken, table_id: tableId },
440
- data: {
441
- field_name: fieldName,
442
- type: fieldType,
443
- ...(property && { property }),
444
- },
445
- });
446
- ensureLarkSuccess(res, "bitable.appTableField.create", {
447
- appToken,
448
- tableId,
449
- fieldName,
450
- fieldType,
451
- });
452
-
453
- return {
454
- field_id: res.data?.field?.field_id,
455
- field_name: res.data?.field?.field_name,
456
- type: res.data?.field?.type,
457
- type_name: FIELD_TYPE_NAMES[res.data?.field?.type ?? 0] || `type_${res.data?.field?.type}`,
458
- };
459
- }
460
-
461
- async function updateRecord(
462
- client: Lark.Client,
463
- appToken: string,
464
- tableId: string,
465
- recordId: string,
466
- fields: NonNullable<NonNullable<BitableRecordUpdatePayload["data"]>["fields"]>,
467
- ) {
468
- const res = await client.bitable.appTableRecord.update({
469
- path: { app_token: appToken, table_id: tableId, record_id: recordId },
470
- data: { fields },
471
- });
472
- ensureLarkSuccess(res, "bitable.appTableRecord.update", { appToken, tableId, recordId });
473
-
474
- return {
475
- record: res.data?.record,
476
- };
477
- }
478
-
479
- // ============ Schemas ============
480
-
481
- const GetMetaSchema = Type.Object({
482
- url: Type.String({
483
- description: "Bitable URL. Supports both formats: /base/XXX?table=YYY or /wiki/XXX?table=YYY",
484
- }),
485
- });
486
-
487
- const ListFieldsSchema = Type.Object({
488
- app_token: Type.String({
489
- description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
490
- }),
491
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
492
- });
493
-
494
- const ListRecordsSchema = Type.Object({
495
- app_token: Type.String({
496
- description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
497
- }),
498
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
499
- page_size: Type.Optional(
500
- Type.Number({
501
- description: "Number of records per page (1-500, default 100)",
502
- minimum: 1,
503
- maximum: 500,
504
- }),
505
- ),
506
- page_token: Type.Optional(
507
- Type.String({ description: "Pagination token from previous response" }),
508
- ),
509
- });
510
-
511
- const GetRecordSchema = Type.Object({
512
- app_token: Type.String({
513
- description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
514
- }),
515
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
516
- record_id: Type.String({ description: "Record ID to retrieve" }),
517
- });
518
-
519
- const CreateRecordSchema = Type.Object({
520
- app_token: Type.String({
521
- description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
522
- }),
523
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
524
- fields: Type.Record(Type.String(), Type.Any(), {
525
- description:
526
- "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://...'}",
527
- }),
528
- });
529
-
530
- const CreateAppSchema = Type.Object({
531
- name: Type.String({
532
- description: "Name for the new Bitable application",
533
- }),
534
- folder_token: Type.Optional(
535
- Type.String({
536
- description: "Optional folder token to place the Bitable in a specific folder",
537
- }),
538
- ),
539
- });
540
-
541
- const CreateFieldSchema = Type.Object({
542
- app_token: Type.String({
543
- description:
544
- "Bitable app token (use feishu_bitable_get_meta to get from URL, or feishu_bitable_create_app to create new)",
545
- }),
546
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
547
- field_name: Type.String({ description: "Name for the new field" }),
548
- field_type: Type.Number({
549
- description:
550
- "Field type ID: 1=Text, 2=Number, 3=SingleSelect, 4=MultiSelect, 5=DateTime, 7=Checkbox, 11=User, 13=Phone, 15=URL, 17=Attachment, 18=SingleLink, 19=Lookup, 20=Formula, 21=DuplexLink, 22=Location, 23=GroupChat, 1001=CreatedTime, 1002=ModifiedTime, 1003=CreatedUser, 1004=ModifiedUser, 1005=AutoNumber",
551
- minimum: 1,
552
- }),
553
- property: Type.Optional(
554
- Type.Record(Type.String(), Type.Any(), {
555
- description: "Field-specific properties (e.g., options for SingleSelect, format for Number)",
556
- }),
557
- ),
558
- });
559
-
560
- const UpdateRecordSchema = Type.Object({
561
- app_token: Type.String({
562
- description: "Bitable app token (use feishu_bitable_get_meta to get from URL)",
563
- }),
564
- table_id: Type.String({ description: "Table ID (from URL: ?table=YYY)" }),
565
- record_id: Type.String({ description: "Record ID to update" }),
566
- fields: Type.Record(Type.String(), Type.Any(), {
567
- description: "Field values to update (same format as create_record)",
568
- }),
569
- });
570
-
571
- // ============ Tool Registration ============
572
-
573
- export function registerFeishuBitableTools(api: KlawPluginApi) {
574
- if (!api.config) {
575
- return;
576
- }
577
-
578
- const accounts = listEnabledFeishuAccounts(api.config);
579
- if (accounts.length === 0) {
580
- return;
581
- }
582
-
583
- type AccountAwareParams = { accountId?: string };
584
-
585
- const getClient = (params: AccountAwareParams | undefined, defaultAccountId?: string) =>
586
- createFeishuToolClient({ api, executeParams: params, defaultAccountId });
587
-
588
- const registerBitableTool = <
589
- // oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Tool params bind each schema-specific executor to its registered tool.
590
- TParams extends AccountAwareParams,
591
- >(params: {
592
- name: string;
593
- label: string;
594
- description: string;
595
- parameters: TSchema;
596
- execute: (args: { params: TParams; defaultAccountId?: string }) => Promise<unknown>;
597
- }) => {
598
- api.registerTool(
599
- (ctx) => ({
600
- name: params.name,
601
- label: params.label,
602
- description: params.description,
603
- parameters: params.parameters,
604
- async execute(_toolCallId, rawParams) {
605
- try {
606
- return json(
607
- await params.execute({
608
- params: rawParams as TParams,
609
- defaultAccountId: ctx.agentAccountId,
610
- }),
611
- );
612
- } catch (err) {
613
- return json({ error: formatErrorMessage(err) });
614
- }
615
- },
616
- }),
617
- { name: params.name },
618
- );
619
- };
620
-
621
- registerBitableTool<{ url: string; accountId?: string }>({
622
- name: "feishu_bitable_get_meta",
623
- label: "Feishu Bitable Get Meta",
624
- description:
625
- "Parse a Bitable URL and get app_token, table_id, and table list. Use this first when given a /wiki/ or /base/ URL.",
626
- parameters: GetMetaSchema,
627
- async execute({ params, defaultAccountId }) {
628
- return getBitableMeta(getClient(params, defaultAccountId), params.url);
629
- },
630
- });
631
-
632
- registerBitableTool<{ app_token: string; table_id: string; accountId?: string }>({
633
- name: "feishu_bitable_list_fields",
634
- label: "Feishu Bitable List Fields",
635
- description: "List all fields (columns) in a Bitable table with their types and properties",
636
- parameters: ListFieldsSchema,
637
- async execute({ params, defaultAccountId }) {
638
- return listFields(getClient(params, defaultAccountId), params.app_token, params.table_id);
639
- },
640
- });
641
-
642
- registerBitableTool<{
643
- app_token: string;
644
- table_id: string;
645
- page_size?: number;
646
- page_token?: string;
647
- accountId?: string;
648
- }>({
649
- name: "feishu_bitable_list_records",
650
- label: "Feishu Bitable List Records",
651
- description: "List records (rows) from a Bitable table with pagination support",
652
- parameters: ListRecordsSchema,
653
- async execute({ params, defaultAccountId }) {
654
- return listRecords(
655
- getClient(params, defaultAccountId),
656
- params.app_token,
657
- params.table_id,
658
- params.page_size,
659
- params.page_token,
660
- );
661
- },
662
- });
663
-
664
- registerBitableTool<{
665
- app_token: string;
666
- table_id: string;
667
- record_id: string;
668
- accountId?: string;
669
- }>({
670
- name: "feishu_bitable_get_record",
671
- label: "Feishu Bitable Get Record",
672
- description: "Get a single record by ID from a Bitable table",
673
- parameters: GetRecordSchema,
674
- async execute({ params, defaultAccountId }) {
675
- return getRecord(
676
- getClient(params, defaultAccountId),
677
- params.app_token,
678
- params.table_id,
679
- params.record_id,
680
- );
681
- },
682
- });
683
-
684
- registerBitableTool<{
685
- app_token: string;
686
- table_id: string;
687
- fields: BitableRecordFields;
688
- accountId?: string;
689
- }>({
690
- name: "feishu_bitable_create_record",
691
- label: "Feishu Bitable Create Record",
692
- description: "Create a new record (row) in a Bitable table",
693
- parameters: CreateRecordSchema,
694
- async execute({ params, defaultAccountId }) {
695
- return createRecord(
696
- getClient(params, defaultAccountId),
697
- params.app_token,
698
- params.table_id,
699
- params.fields,
700
- );
701
- },
702
- });
703
-
704
- registerBitableTool<{
705
- app_token: string;
706
- table_id: string;
707
- record_id: string;
708
- fields: BitableRecordUpdateFields;
709
- accountId?: string;
710
- }>({
711
- name: "feishu_bitable_update_record",
712
- label: "Feishu Bitable Update Record",
713
- description: "Update an existing record (row) in a Bitable table",
714
- parameters: UpdateRecordSchema,
715
- async execute({ params, defaultAccountId }) {
716
- return updateRecord(
717
- getClient(params, defaultAccountId),
718
- params.app_token,
719
- params.table_id,
720
- params.record_id,
721
- params.fields,
722
- );
723
- },
724
- });
725
-
726
- registerBitableTool<{ name: string; folder_token?: string; accountId?: string }>({
727
- name: "feishu_bitable_create_app",
728
- label: "Feishu Bitable Create App",
729
- description: "Create a new Bitable (multidimensional table) application",
730
- parameters: CreateAppSchema,
731
- async execute({ params, defaultAccountId }) {
732
- return createApp(getClient(params, defaultAccountId), params.name, params.folder_token, {
733
- debug: (msg) => api.logger.debug?.(msg),
734
- warn: (msg) => api.logger.warn?.(msg),
735
- });
736
- },
737
- });
738
-
739
- registerBitableTool<{
740
- app_token: string;
741
- table_id: string;
742
- field_name: string;
743
- field_type: number;
744
- property?: Record<string, unknown>;
745
- accountId?: string;
746
- }>({
747
- name: "feishu_bitable_create_field",
748
- label: "Feishu Bitable Create Field",
749
- description: "Create a new field (column) in a Bitable table",
750
- parameters: CreateFieldSchema,
751
- async execute({ params, defaultAccountId }) {
752
- return createField(
753
- getClient(params, defaultAccountId),
754
- params.app_token,
755
- params.table_id,
756
- params.field_name,
757
- params.field_type,
758
- params.property,
759
- );
760
- },
761
- });
762
- }