@openclaw/feishu 2026.2.25 → 2026.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/index.ts +2 -0
  2. package/package.json +2 -1
  3. package/skills/feishu-doc/SKILL.md +109 -3
  4. package/src/accounts.test.ts +90 -0
  5. package/src/accounts.ts +11 -2
  6. package/src/async.ts +62 -0
  7. package/src/bitable.ts +189 -215
  8. package/src/bot.card-action.test.ts +63 -0
  9. package/src/bot.checkBotMentioned.test.ts +55 -0
  10. package/src/bot.test.ts +863 -9
  11. package/src/bot.ts +414 -200
  12. package/src/card-action.ts +79 -0
  13. package/src/channel.ts +6 -0
  14. package/src/chat-schema.ts +24 -0
  15. package/src/chat.test.ts +89 -0
  16. package/src/chat.ts +130 -0
  17. package/src/client.test.ts +107 -0
  18. package/src/client.ts +13 -0
  19. package/src/config-schema.test.ts +82 -1
  20. package/src/config-schema.ts +54 -3
  21. package/src/doc-schema.ts +141 -0
  22. package/src/docx-batch-insert.ts +190 -0
  23. package/src/docx-color-text.ts +149 -0
  24. package/src/docx-table-ops.ts +298 -0
  25. package/src/docx.account-selection.test.ts +76 -0
  26. package/src/docx.test.ts +470 -0
  27. package/src/docx.ts +996 -72
  28. package/src/drive.ts +38 -33
  29. package/src/media.test.ts +123 -6
  30. package/src/media.ts +31 -10
  31. package/src/monitor.account.ts +286 -0
  32. package/src/monitor.reaction.test.ts +235 -0
  33. package/src/monitor.startup.test.ts +187 -0
  34. package/src/monitor.startup.ts +51 -0
  35. package/src/monitor.state.ts +76 -0
  36. package/src/monitor.transport.ts +163 -0
  37. package/src/monitor.ts +44 -346
  38. package/src/monitor.webhook-security.test.ts +27 -1
  39. package/src/outbound.test.ts +181 -0
  40. package/src/outbound.ts +94 -7
  41. package/src/perm.ts +37 -30
  42. package/src/policy.test.ts +56 -1
  43. package/src/policy.ts +5 -1
  44. package/src/post.test.ts +105 -0
  45. package/src/post.ts +274 -0
  46. package/src/probe.test.ts +253 -0
  47. package/src/probe.ts +99 -7
  48. package/src/reply-dispatcher.test.ts +259 -0
  49. package/src/reply-dispatcher.ts +139 -45
  50. package/src/send.reply-fallback.test.ts +105 -0
  51. package/src/send.test.ts +168 -0
  52. package/src/send.ts +143 -18
  53. package/src/streaming-card.ts +131 -43
  54. package/src/targets.test.ts +26 -1
  55. package/src/targets.ts +11 -6
  56. package/src/tool-account-routing.test.ts +129 -0
  57. package/src/tool-account.ts +70 -0
  58. package/src/tool-factory-test-harness.ts +76 -0
  59. package/src/tools-config.test.ts +21 -0
  60. package/src/tools-config.ts +2 -1
  61. package/src/types.ts +1 -0
  62. package/src/typing.test.ts +144 -0
  63. package/src/typing.ts +140 -10
  64. package/src/wiki.ts +55 -50
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Table utilities and row/column manipulation operations for Feishu documents.
3
+ *
4
+ * Combines:
5
+ * - Adaptive column width calculation (content-proportional, CJK-aware)
6
+ * - Block cleaning for Descendant API (removes read-only fields)
7
+ * - Table row/column insert, delete, and merge operations
8
+ */
9
+
10
+ import type * as Lark from "@larksuiteoapi/node-sdk";
11
+
12
+ // ============ Table Utilities ============
13
+
14
+ // Feishu table constraints
15
+ const MIN_COLUMN_WIDTH = 50; // Feishu API minimum
16
+ const MAX_COLUMN_WIDTH = 400; // Reasonable maximum for readability
17
+ const DEFAULT_TABLE_WIDTH = 730; // Approximate Feishu page content width
18
+
19
+ /**
20
+ * Calculate adaptive column widths based on cell content length.
21
+ *
22
+ * Algorithm:
23
+ * 1. For each column, find the max content length across all rows
24
+ * 2. Weight CJK characters as 2x width (they render wider)
25
+ * 3. Calculate proportional widths based on content length
26
+ * 4. Apply min/max constraints
27
+ * 5. Redistribute remaining space to fill total table width
28
+ *
29
+ * Total width is derived from the original column_width values returned
30
+ * by the Convert API, ensuring tables match Feishu's expected dimensions.
31
+ *
32
+ * @param blocks - Array of blocks from Convert API
33
+ * @param tableBlockId - The block_id of the table block
34
+ * @returns Array of column widths in pixels
35
+ */
36
+ export function calculateAdaptiveColumnWidths(
37
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38
+ blocks: any[],
39
+ tableBlockId: string,
40
+ ): number[] {
41
+ // Find the table block
42
+ const tableBlock = blocks.find((b) => b.block_id === tableBlockId && b.block_type === 31);
43
+
44
+ if (!tableBlock?.table?.property) {
45
+ return [];
46
+ }
47
+
48
+ const { row_size, column_size, column_width: originalWidths } = tableBlock.table.property;
49
+
50
+ // Use original total width from Convert API, or fall back to default
51
+ const totalWidth =
52
+ originalWidths && originalWidths.length > 0
53
+ ? originalWidths.reduce((a: number, b: number) => a + b, 0)
54
+ : DEFAULT_TABLE_WIDTH;
55
+ const cellIds: string[] = tableBlock.children || [];
56
+
57
+ // Build block lookup map
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ const blockMap = new Map<string, any>();
60
+ for (const block of blocks) {
61
+ blockMap.set(block.block_id, block);
62
+ }
63
+
64
+ // Extract text content from a table cell
65
+ function getCellText(cellId: string): string {
66
+ const cell = blockMap.get(cellId);
67
+ if (!cell?.children) return "";
68
+
69
+ let text = "";
70
+ const childIds = Array.isArray(cell.children) ? cell.children : [cell.children];
71
+
72
+ for (const childId of childIds) {
73
+ const child = blockMap.get(childId);
74
+ if (child?.text?.elements) {
75
+ for (const elem of child.text.elements) {
76
+ if (elem.text_run?.content) {
77
+ text += elem.text_run.content;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ return text;
83
+ }
84
+
85
+ // Calculate weighted length (CJK chars count as 2)
86
+ // CJK (Chinese/Japanese/Korean) characters render ~2x wider than ASCII
87
+ function getWeightedLength(text: string): number {
88
+ return [...text].reduce((sum, char) => {
89
+ return sum + (char.charCodeAt(0) > 255 ? 2 : 1);
90
+ }, 0);
91
+ }
92
+
93
+ // Find max content length per column
94
+ const maxLengths: number[] = new Array(column_size).fill(0);
95
+
96
+ for (let row = 0; row < row_size; row++) {
97
+ for (let col = 0; col < column_size; col++) {
98
+ const cellIndex = row * column_size + col;
99
+ const cellId = cellIds[cellIndex];
100
+ if (cellId) {
101
+ const content = getCellText(cellId);
102
+ const length = getWeightedLength(content);
103
+ maxLengths[col] = Math.max(maxLengths[col], length);
104
+ }
105
+ }
106
+ }
107
+
108
+ // Handle empty table: distribute width equally, clamped to [MIN, MAX] so
109
+ // wide tables (e.g. 15+ columns) don't produce sub-50 widths that Feishu
110
+ // rejects as invalid column_width values.
111
+ const totalLength = maxLengths.reduce((a, b) => a + b, 0);
112
+ if (totalLength === 0) {
113
+ const equalWidth = Math.max(
114
+ MIN_COLUMN_WIDTH,
115
+ Math.min(MAX_COLUMN_WIDTH, Math.floor(totalWidth / column_size)),
116
+ );
117
+ return new Array(column_size).fill(equalWidth);
118
+ }
119
+
120
+ // Calculate proportional widths
121
+ let widths = maxLengths.map((len) => {
122
+ const proportion = len / totalLength;
123
+ return Math.round(proportion * totalWidth);
124
+ });
125
+
126
+ // Apply min/max constraints
127
+ widths = widths.map((w) => Math.max(MIN_COLUMN_WIDTH, Math.min(MAX_COLUMN_WIDTH, w)));
128
+
129
+ // Redistribute remaining space to fill total width
130
+ let remaining = totalWidth - widths.reduce((a, b) => a + b, 0);
131
+ while (remaining > 0) {
132
+ // Find columns that can still grow (not at max)
133
+ const growable = widths.map((w, i) => (w < MAX_COLUMN_WIDTH ? i : -1)).filter((i) => i >= 0);
134
+ if (growable.length === 0) break;
135
+
136
+ // Distribute evenly among growable columns
137
+ const perColumn = Math.floor(remaining / growable.length);
138
+ if (perColumn === 0) break;
139
+
140
+ for (const i of growable) {
141
+ const add = Math.min(perColumn, MAX_COLUMN_WIDTH - widths[i]);
142
+ widths[i] += add;
143
+ remaining -= add;
144
+ }
145
+ }
146
+
147
+ return widths;
148
+ }
149
+
150
+ /**
151
+ * Clean blocks for Descendant API with adaptive column widths.
152
+ *
153
+ * - Removes parent_id from all blocks
154
+ * - Fixes children type (string → array) for TableCell blocks
155
+ * - Removes merge_info (read-only, causes API error)
156
+ * - Calculates and applies adaptive column_width for tables
157
+ *
158
+ * @param blocks - Array of blocks from Convert API
159
+ * @returns Cleaned blocks ready for Descendant API
160
+ */
161
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
162
+ export function cleanBlocksForDescendant(blocks: any[]): any[] {
163
+ // Pre-calculate adaptive widths for all tables
164
+ const tableWidths = new Map<string, number[]>();
165
+ for (const block of blocks) {
166
+ if (block.block_type === 31) {
167
+ const widths = calculateAdaptiveColumnWidths(blocks, block.block_id);
168
+ tableWidths.set(block.block_id, widths);
169
+ }
170
+ }
171
+
172
+ return blocks.map((block) => {
173
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
174
+ const { parent_id: _parentId, ...cleanBlock } = block;
175
+
176
+ // Fix: Convert API sometimes returns children as string for TableCell
177
+ if (cleanBlock.block_type === 32 && typeof cleanBlock.children === "string") {
178
+ cleanBlock.children = [cleanBlock.children];
179
+ }
180
+
181
+ // Clean table blocks
182
+ if (cleanBlock.block_type === 31 && cleanBlock.table) {
183
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
184
+ const { cells: _cells, ...tableWithoutCells } = cleanBlock.table;
185
+ const { row_size, column_size } = tableWithoutCells.property || {};
186
+ const adaptiveWidths = tableWidths.get(block.block_id);
187
+
188
+ cleanBlock.table = {
189
+ property: {
190
+ row_size,
191
+ column_size,
192
+ ...(adaptiveWidths?.length && { column_width: adaptiveWidths }),
193
+ },
194
+ };
195
+ }
196
+
197
+ return cleanBlock;
198
+ });
199
+ }
200
+
201
+ // ============ Table Row/Column Operations ============
202
+
203
+ export async function insertTableRow(
204
+ client: Lark.Client,
205
+ docToken: string,
206
+ blockId: string,
207
+ rowIndex: number = -1,
208
+ ) {
209
+ const res = await client.docx.documentBlock.patch({
210
+ path: { document_id: docToken, block_id: blockId },
211
+ data: { insert_table_row: { row_index: rowIndex } },
212
+ });
213
+ if (res.code !== 0) {
214
+ throw new Error(res.msg);
215
+ }
216
+ return { success: true, block: res.data?.block };
217
+ }
218
+
219
+ export async function insertTableColumn(
220
+ client: Lark.Client,
221
+ docToken: string,
222
+ blockId: string,
223
+ columnIndex: number = -1,
224
+ ) {
225
+ const res = await client.docx.documentBlock.patch({
226
+ path: { document_id: docToken, block_id: blockId },
227
+ data: { insert_table_column: { column_index: columnIndex } },
228
+ });
229
+ if (res.code !== 0) {
230
+ throw new Error(res.msg);
231
+ }
232
+ return { success: true, block: res.data?.block };
233
+ }
234
+
235
+ export async function deleteTableRows(
236
+ client: Lark.Client,
237
+ docToken: string,
238
+ blockId: string,
239
+ rowStart: number,
240
+ rowCount: number = 1,
241
+ ) {
242
+ const res = await client.docx.documentBlock.patch({
243
+ path: { document_id: docToken, block_id: blockId },
244
+ data: { delete_table_rows: { row_start_index: rowStart, row_end_index: rowStart + rowCount } },
245
+ });
246
+ if (res.code !== 0) {
247
+ throw new Error(res.msg);
248
+ }
249
+ return { success: true, rows_deleted: rowCount, block: res.data?.block };
250
+ }
251
+
252
+ export async function deleteTableColumns(
253
+ client: Lark.Client,
254
+ docToken: string,
255
+ blockId: string,
256
+ columnStart: number,
257
+ columnCount: number = 1,
258
+ ) {
259
+ const res = await client.docx.documentBlock.patch({
260
+ path: { document_id: docToken, block_id: blockId },
261
+ data: {
262
+ delete_table_columns: {
263
+ column_start_index: columnStart,
264
+ column_end_index: columnStart + columnCount,
265
+ },
266
+ },
267
+ });
268
+ if (res.code !== 0) {
269
+ throw new Error(res.msg);
270
+ }
271
+ return { success: true, columns_deleted: columnCount, block: res.data?.block };
272
+ }
273
+
274
+ export async function mergeTableCells(
275
+ client: Lark.Client,
276
+ docToken: string,
277
+ blockId: string,
278
+ rowStart: number,
279
+ rowEnd: number,
280
+ columnStart: number,
281
+ columnEnd: number,
282
+ ) {
283
+ const res = await client.docx.documentBlock.patch({
284
+ path: { document_id: docToken, block_id: blockId },
285
+ data: {
286
+ merge_table_cells: {
287
+ row_start_index: rowStart,
288
+ row_end_index: rowEnd,
289
+ column_start_index: columnStart,
290
+ column_end_index: columnEnd,
291
+ },
292
+ },
293
+ });
294
+ if (res.code !== 0) {
295
+ throw new Error(res.msg);
296
+ }
297
+ return { success: true, block: res.data?.block };
298
+ }
@@ -0,0 +1,76 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ import { describe, expect, test, vi } from "vitest";
3
+ import { registerFeishuDocTools } from "./docx.js";
4
+ import { createToolFactoryHarness } from "./tool-factory-test-harness.js";
5
+
6
+ const createFeishuClientMock = vi.fn((creds: { appId?: string } | undefined) => ({
7
+ __appId: creds?.appId,
8
+ }));
9
+
10
+ vi.mock("./client.js", () => {
11
+ return {
12
+ createFeishuClient: (creds: { appId?: string } | undefined) => createFeishuClientMock(creds),
13
+ };
14
+ });
15
+
16
+ // Patch SDK import so tool execution can run without network concerns.
17
+ vi.mock("@larksuiteoapi/node-sdk", () => {
18
+ return {
19
+ default: {},
20
+ };
21
+ });
22
+
23
+ describe("feishu_doc account selection", () => {
24
+ test("uses agentAccountId context when params omit accountId", async () => {
25
+ const cfg = {
26
+ channels: {
27
+ feishu: {
28
+ enabled: true,
29
+ accounts: {
30
+ a: { appId: "app-a", appSecret: "sec-a", tools: { doc: true } },
31
+ b: { appId: "app-b", appSecret: "sec-b", tools: { doc: true } },
32
+ },
33
+ },
34
+ },
35
+ } as OpenClawPluginApi["config"];
36
+
37
+ const { api, resolveTool } = createToolFactoryHarness(cfg);
38
+ registerFeishuDocTools(api);
39
+
40
+ const docToolA = resolveTool("feishu_doc", { agentAccountId: "a" });
41
+ const docToolB = resolveTool("feishu_doc", { agentAccountId: "b" });
42
+
43
+ await docToolA.execute("call-a", { action: "list_blocks", doc_token: "d" });
44
+ await docToolB.execute("call-b", { action: "list_blocks", doc_token: "d" });
45
+
46
+ expect(createFeishuClientMock).toHaveBeenCalledTimes(2);
47
+ expect(createFeishuClientMock.mock.calls[0]?.[0]?.appId).toBe("app-a");
48
+ expect(createFeishuClientMock.mock.calls[1]?.[0]?.appId).toBe("app-b");
49
+ });
50
+
51
+ test("explicit accountId param overrides agentAccountId context", async () => {
52
+ const cfg = {
53
+ channels: {
54
+ feishu: {
55
+ enabled: true,
56
+ accounts: {
57
+ a: { appId: "app-a", appSecret: "sec-a", tools: { doc: true } },
58
+ b: { appId: "app-b", appSecret: "sec-b", tools: { doc: true } },
59
+ },
60
+ },
61
+ },
62
+ } as OpenClawPluginApi["config"];
63
+
64
+ const { api, resolveTool } = createToolFactoryHarness(cfg);
65
+ registerFeishuDocTools(api);
66
+
67
+ const docTool = resolveTool("feishu_doc", { agentAccountId: "b" });
68
+ await docTool.execute("call-override", {
69
+ action: "list_blocks",
70
+ doc_token: "d",
71
+ accountId: "a",
72
+ });
73
+
74
+ expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-a");
75
+ });
76
+ });