@nextclaw/channel-plugin-feishu 0.2.13 → 0.2.14
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/README.md +3 -1
- package/index.ts +65 -0
- package/openclaw.plugin.json +3 -7
- package/package.json +33 -9
- package/skills/feishu-doc/SKILL.md +211 -0
- package/skills/feishu-doc/references/block-types.md +103 -0
- package/skills/feishu-drive/SKILL.md +97 -0
- package/skills/feishu-perm/SKILL.md +119 -0
- package/skills/feishu-wiki/SKILL.md +111 -0
- package/src/accounts.test.ts +371 -0
- package/src/accounts.ts +244 -0
- package/src/async.ts +62 -0
- package/src/bitable.ts +725 -0
- package/src/bot.card-action.test.ts +63 -0
- package/src/bot.checkBotMentioned.test.ts +193 -0
- package/src/bot.stripBotMention.test.ts +134 -0
- package/src/bot.test.ts +2107 -0
- package/src/bot.ts +1556 -0
- package/src/card-action.ts +79 -0
- package/src/channel.test.ts +48 -0
- package/src/channel.ts +369 -0
- package/src/chat-schema.ts +24 -0
- package/src/chat.test.ts +89 -0
- package/src/chat.ts +130 -0
- package/src/client.test.ts +324 -0
- package/src/client.ts +196 -0
- package/src/config-schema.test.ts +247 -0
- package/src/config-schema.ts +306 -0
- package/src/dedup.ts +203 -0
- package/src/directory.test.ts +40 -0
- package/src/directory.ts +156 -0
- package/src/doc-schema.ts +182 -0
- package/src/docx-batch-insert.test.ts +90 -0
- package/src/docx-batch-insert.ts +187 -0
- package/src/docx-color-text.ts +149 -0
- package/src/docx-table-ops.ts +298 -0
- package/src/docx.account-selection.test.ts +70 -0
- package/src/docx.test.ts +445 -0
- package/src/docx.ts +1460 -0
- package/src/drive-schema.ts +46 -0
- package/src/drive.ts +228 -0
- package/src/dynamic-agent.ts +131 -0
- package/src/external-keys.test.ts +20 -0
- package/src/external-keys.ts +19 -0
- package/src/feishu-command-handler.ts +59 -0
- package/src/media.test.ts +523 -0
- package/src/media.ts +484 -0
- package/src/mention.ts +133 -0
- package/src/monitor.account.ts +562 -0
- package/src/monitor.reaction.test.ts +653 -0
- package/src/monitor.startup.test.ts +190 -0
- package/src/monitor.startup.ts +64 -0
- package/src/monitor.state.defaults.test.ts +46 -0
- package/src/monitor.state.ts +155 -0
- package/src/monitor.test-mocks.ts +45 -0
- package/src/monitor.transport.ts +264 -0
- package/src/monitor.ts +95 -0
- package/src/monitor.webhook-e2e.test.ts +214 -0
- package/src/monitor.webhook-security.test.ts +142 -0
- package/src/monitor.webhook.test-helpers.ts +98 -0
- package/src/onboarding.status.test.ts +25 -0
- package/src/onboarding.test.ts +143 -0
- package/src/onboarding.ts +489 -0
- package/src/outbound.test.ts +356 -0
- package/src/outbound.ts +176 -0
- package/src/perm-schema.ts +52 -0
- package/src/perm.ts +176 -0
- package/src/policy.test.ts +154 -0
- package/src/policy.ts +123 -0
- package/src/post.test.ts +105 -0
- package/src/post.ts +274 -0
- package/src/probe.test.ts +270 -0
- package/src/probe.ts +156 -0
- package/src/reactions.ts +153 -0
- package/src/reply-dispatcher.test.ts +513 -0
- package/src/reply-dispatcher.ts +397 -0
- package/src/runtime.ts +6 -0
- package/src/secret-input.ts +13 -0
- package/src/send-message.ts +71 -0
- package/src/send-result.ts +29 -0
- package/src/send-target.test.ts +74 -0
- package/src/send-target.ts +29 -0
- package/src/send.reply-fallback.test.ts +189 -0
- package/src/send.test.ts +168 -0
- package/src/send.ts +481 -0
- package/src/streaming-card.test.ts +54 -0
- package/src/streaming-card.ts +374 -0
- package/src/targets.test.ts +70 -0
- package/src/targets.ts +107 -0
- package/src/tool-account-routing.test.ts +129 -0
- package/src/tool-account.ts +70 -0
- package/src/tool-factory-test-harness.ts +76 -0
- package/src/tool-result.test.ts +32 -0
- package/src/tool-result.ts +14 -0
- package/src/tools-config.test.ts +21 -0
- package/src/tools-config.ts +22 -0
- package/src/types.ts +103 -0
- package/src/typing.test.ts +144 -0
- package/src/typing.ts +210 -0
- package/src/wiki-schema.ts +55 -0
- package/src/wiki.ts +233 -0
- package/index.js +0 -27
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Batch insertion for large Feishu documents (>1000 blocks).
|
|
3
|
+
*
|
|
4
|
+
* The Feishu Descendant API has a limit of 1000 blocks per request.
|
|
5
|
+
* This module handles splitting large documents into batches while
|
|
6
|
+
* preserving parent-child relationships between blocks.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type * as Lark from "@larksuiteoapi/node-sdk";
|
|
10
|
+
import { cleanBlocksForDescendant } from "./docx-table-ops.js";
|
|
11
|
+
|
|
12
|
+
export const BATCH_SIZE = 1000; // Feishu API limit per request
|
|
13
|
+
|
|
14
|
+
type Logger = { info?: (msg: string) => void };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Collect all descendant blocks for a given first-level block ID.
|
|
18
|
+
* Recursively traverses the block tree to gather all children.
|
|
19
|
+
*/
|
|
20
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK block types
|
|
21
|
+
function collectDescendants(blockMap: Map<string, any>, rootId: string): any[] {
|
|
22
|
+
const result: any[] = [];
|
|
23
|
+
const visited = new Set<string>();
|
|
24
|
+
|
|
25
|
+
function collect(blockId: string) {
|
|
26
|
+
if (visited.has(blockId)) return;
|
|
27
|
+
visited.add(blockId);
|
|
28
|
+
|
|
29
|
+
const block = blockMap.get(blockId);
|
|
30
|
+
if (!block) return;
|
|
31
|
+
|
|
32
|
+
result.push(block);
|
|
33
|
+
|
|
34
|
+
// Recursively collect children
|
|
35
|
+
const children = block.children;
|
|
36
|
+
if (Array.isArray(children)) {
|
|
37
|
+
for (const childId of children) {
|
|
38
|
+
collect(childId);
|
|
39
|
+
}
|
|
40
|
+
} else if (typeof children === "string") {
|
|
41
|
+
collect(children);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
collect(rootId);
|
|
46
|
+
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Insert a single batch of blocks using Descendant API.
|
|
52
|
+
*
|
|
53
|
+
* @param parentBlockId - Parent block to insert into (defaults to docToken)
|
|
54
|
+
* @param index - Position within parent's children (-1 = end)
|
|
55
|
+
*/
|
|
56
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK block types
|
|
57
|
+
async function insertBatch(
|
|
58
|
+
client: Lark.Client,
|
|
59
|
+
docToken: string,
|
|
60
|
+
blocks: any[],
|
|
61
|
+
firstLevelBlockIds: string[],
|
|
62
|
+
parentBlockId: string = docToken,
|
|
63
|
+
index: number = -1,
|
|
64
|
+
): Promise<any[]> {
|
|
65
|
+
const descendants = cleanBlocksForDescendant(blocks);
|
|
66
|
+
|
|
67
|
+
if (descendants.length === 0) {
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const res = await client.docx.documentBlockDescendant.create({
|
|
72
|
+
path: { document_id: docToken, block_id: parentBlockId },
|
|
73
|
+
data: {
|
|
74
|
+
children_id: firstLevelBlockIds,
|
|
75
|
+
descendants,
|
|
76
|
+
index,
|
|
77
|
+
},
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
if (res.code !== 0) {
|
|
81
|
+
throw new Error(`${res.msg} (code: ${res.code})`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return res.data?.children ?? [];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Insert blocks in batches for large documents (>1000 blocks).
|
|
89
|
+
*
|
|
90
|
+
* Batches are split to ensure BOTH children_id AND descendants
|
|
91
|
+
* arrays stay under the 1000 block API limit.
|
|
92
|
+
*
|
|
93
|
+
* @param client - Feishu API client
|
|
94
|
+
* @param docToken - Document ID
|
|
95
|
+
* @param blocks - All blocks from Convert API
|
|
96
|
+
* @param firstLevelBlockIds - IDs of top-level blocks to insert
|
|
97
|
+
* @param logger - Optional logger for progress updates
|
|
98
|
+
* @param parentBlockId - Parent block to insert into (defaults to docToken = document root)
|
|
99
|
+
* @param startIndex - Starting position within parent (-1 = end). For multi-batch inserts,
|
|
100
|
+
* each batch advances this by the number of first-level IDs inserted so far.
|
|
101
|
+
* @returns Inserted children blocks and any skipped block IDs
|
|
102
|
+
*/
|
|
103
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK block types
|
|
104
|
+
export async function insertBlocksInBatches(
|
|
105
|
+
client: Lark.Client,
|
|
106
|
+
docToken: string,
|
|
107
|
+
blocks: any[],
|
|
108
|
+
firstLevelBlockIds: string[],
|
|
109
|
+
logger?: Logger,
|
|
110
|
+
parentBlockId: string = docToken,
|
|
111
|
+
startIndex: number = -1,
|
|
112
|
+
): Promise<{ children: any[]; skipped: string[] }> {
|
|
113
|
+
const allChildren: any[] = [];
|
|
114
|
+
|
|
115
|
+
// Build batches ensuring each batch has ≤1000 total descendants
|
|
116
|
+
const batches: { firstLevelIds: string[]; blocks: any[] }[] = [];
|
|
117
|
+
let currentBatch: { firstLevelIds: string[]; blocks: any[] } = { firstLevelIds: [], blocks: [] };
|
|
118
|
+
const usedBlockIds = new Set<string>();
|
|
119
|
+
const blockMap = new Map<string, any>();
|
|
120
|
+
for (const block of blocks) {
|
|
121
|
+
blockMap.set(block.block_id, block);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
for (const firstLevelId of firstLevelBlockIds) {
|
|
125
|
+
const descendants = collectDescendants(blockMap, firstLevelId);
|
|
126
|
+
const newBlocks = descendants.filter((b) => !usedBlockIds.has(b.block_id));
|
|
127
|
+
|
|
128
|
+
// A single block whose subtree exceeds the API limit cannot be split
|
|
129
|
+
// (a table or other compound block must be inserted atomically).
|
|
130
|
+
if (newBlocks.length > BATCH_SIZE) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`Block "${firstLevelId}" has ${newBlocks.length} descendants, which exceeds the ` +
|
|
133
|
+
`Feishu API limit of ${BATCH_SIZE} blocks per request. ` +
|
|
134
|
+
`Please split the content into smaller sections.`,
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// If adding this first-level block would exceed limit, start new batch
|
|
139
|
+
if (
|
|
140
|
+
currentBatch.blocks.length + newBlocks.length > BATCH_SIZE &&
|
|
141
|
+
currentBatch.blocks.length > 0
|
|
142
|
+
) {
|
|
143
|
+
batches.push(currentBatch);
|
|
144
|
+
currentBatch = { firstLevelIds: [], blocks: [] };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Add to current batch
|
|
148
|
+
currentBatch.firstLevelIds.push(firstLevelId);
|
|
149
|
+
for (const block of newBlocks) {
|
|
150
|
+
currentBatch.blocks.push(block);
|
|
151
|
+
usedBlockIds.add(block.block_id);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Don't forget the last batch
|
|
156
|
+
if (currentBatch.blocks.length > 0) {
|
|
157
|
+
batches.push(currentBatch);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Insert each batch, advancing index for position-aware inserts.
|
|
161
|
+
// When startIndex == -1 (append to end), each batch appends after the previous.
|
|
162
|
+
// When startIndex >= 0, each batch starts at startIndex + count of first-level IDs already inserted.
|
|
163
|
+
let currentIndex = startIndex;
|
|
164
|
+
for (let i = 0; i < batches.length; i++) {
|
|
165
|
+
const batch = batches[i];
|
|
166
|
+
logger?.info?.(
|
|
167
|
+
`feishu_doc: Inserting batch ${i + 1}/${batches.length} (${batch.blocks.length} blocks)...`,
|
|
168
|
+
);
|
|
169
|
+
|
|
170
|
+
const children = await insertBatch(
|
|
171
|
+
client,
|
|
172
|
+
docToken,
|
|
173
|
+
batch.blocks,
|
|
174
|
+
batch.firstLevelIds,
|
|
175
|
+
parentBlockId,
|
|
176
|
+
currentIndex,
|
|
177
|
+
);
|
|
178
|
+
allChildren.push(...children);
|
|
179
|
+
|
|
180
|
+
// Advance index only for explicit positions; -1 always means "after last inserted"
|
|
181
|
+
if (currentIndex !== -1) {
|
|
182
|
+
currentIndex += batch.firstLevelIds.length;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return { children: allChildren, skipped: [] };
|
|
187
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Colored text support for Feishu documents.
|
|
3
|
+
*
|
|
4
|
+
* Parses a simple color markup syntax and updates a text block
|
|
5
|
+
* with native Feishu text_run color styles.
|
|
6
|
+
*
|
|
7
|
+
* Syntax: [color]text[/color]
|
|
8
|
+
* Supported colors: red, orange, yellow, green, blue, purple, grey
|
|
9
|
+
*
|
|
10
|
+
* Example:
|
|
11
|
+
* "Revenue [green]+15%[/green] YoY, Costs [red]-3%[/red]"
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type * as Lark from "@larksuiteoapi/node-sdk";
|
|
15
|
+
|
|
16
|
+
// Feishu text_color values (1-7)
|
|
17
|
+
const TEXT_COLOR: Record<string, number> = {
|
|
18
|
+
red: 1, // Pink (closest to red in Feishu)
|
|
19
|
+
orange: 2,
|
|
20
|
+
yellow: 3,
|
|
21
|
+
green: 4,
|
|
22
|
+
blue: 5,
|
|
23
|
+
purple: 6,
|
|
24
|
+
grey: 7,
|
|
25
|
+
gray: 7,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// Feishu background_color values (1-15)
|
|
29
|
+
const BACKGROUND_COLOR: Record<string, number> = {
|
|
30
|
+
red: 1,
|
|
31
|
+
orange: 2,
|
|
32
|
+
yellow: 3,
|
|
33
|
+
green: 4,
|
|
34
|
+
blue: 5,
|
|
35
|
+
purple: 6,
|
|
36
|
+
grey: 7,
|
|
37
|
+
gray: 7,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
interface Segment {
|
|
41
|
+
text: string;
|
|
42
|
+
textColor?: number;
|
|
43
|
+
bgColor?: number;
|
|
44
|
+
bold?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Parse color markup into segments.
|
|
49
|
+
*
|
|
50
|
+
* Supports:
|
|
51
|
+
* [red]text[/red] → red text
|
|
52
|
+
* [bg:yellow]text[/bg] → yellow background
|
|
53
|
+
* [bold]text[/bold] → bold
|
|
54
|
+
* [green bold]text[/green] → green + bold
|
|
55
|
+
*/
|
|
56
|
+
export function parseColorMarkup(content: string): Segment[] {
|
|
57
|
+
const segments: Segment[] = [];
|
|
58
|
+
// Only [known_tag]...[/...] pairs are treated as markup. Using an open
|
|
59
|
+
// pattern like \[([^\]]+)\] would match any bracket token — e.g. [Q1] —
|
|
60
|
+
// and cause it to consume a later real closing tag ([/red]), silently
|
|
61
|
+
// corrupting the surrounding styled spans. Restricting the opening tag to
|
|
62
|
+
// the set of recognised colour/style names prevents that: [Q1] does not
|
|
63
|
+
// match the tag alternative and each of its characters falls through to the
|
|
64
|
+
// plain-text alternatives instead.
|
|
65
|
+
//
|
|
66
|
+
// Closing tag name is still not validated against the opening tag:
|
|
67
|
+
// [red]text[/green] is treated as [red]text[/red] — opening style applies
|
|
68
|
+
// and the closing tag is consumed regardless of its name.
|
|
69
|
+
const KNOWN = "(?:bg:[a-z]+|bold|red|orange|yellow|green|blue|purple|gr[ae]y)";
|
|
70
|
+
const tagPattern = new RegExp(
|
|
71
|
+
`\\[(${KNOWN}(?:\\s+${KNOWN})*)\\](.*?)\\[\\/(?:[^\\]]+)\\]|([^[]+|\\[)`,
|
|
72
|
+
"gis",
|
|
73
|
+
);
|
|
74
|
+
let match;
|
|
75
|
+
|
|
76
|
+
while ((match = tagPattern.exec(content)) !== null) {
|
|
77
|
+
if (match[3] !== undefined) {
|
|
78
|
+
// Plain text segment
|
|
79
|
+
if (match[3]) {
|
|
80
|
+
segments.push({ text: match[3] });
|
|
81
|
+
}
|
|
82
|
+
} else {
|
|
83
|
+
// Tagged segment
|
|
84
|
+
const tagStr = match[1].toLowerCase().trim();
|
|
85
|
+
const text = match[2];
|
|
86
|
+
const tags = tagStr.split(/\s+/);
|
|
87
|
+
|
|
88
|
+
const segment: Segment = { text };
|
|
89
|
+
|
|
90
|
+
for (const tag of tags) {
|
|
91
|
+
if (tag.startsWith("bg:")) {
|
|
92
|
+
const color = tag.slice(3);
|
|
93
|
+
if (BACKGROUND_COLOR[color]) {
|
|
94
|
+
segment.bgColor = BACKGROUND_COLOR[color];
|
|
95
|
+
}
|
|
96
|
+
} else if (tag === "bold") {
|
|
97
|
+
segment.bold = true;
|
|
98
|
+
} else if (TEXT_COLOR[tag]) {
|
|
99
|
+
segment.textColor = TEXT_COLOR[tag];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (text) {
|
|
104
|
+
segments.push(segment);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return segments;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Update a text block with colored segments.
|
|
114
|
+
*/
|
|
115
|
+
export async function updateColorText(
|
|
116
|
+
client: Lark.Client,
|
|
117
|
+
docToken: string,
|
|
118
|
+
blockId: string,
|
|
119
|
+
content: string,
|
|
120
|
+
) {
|
|
121
|
+
const segments = parseColorMarkup(content);
|
|
122
|
+
|
|
123
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK type
|
|
124
|
+
const elements: any[] = segments.map((seg) => ({
|
|
125
|
+
text_run: {
|
|
126
|
+
content: seg.text,
|
|
127
|
+
text_element_style: {
|
|
128
|
+
...(seg.textColor && { text_color: seg.textColor }),
|
|
129
|
+
...(seg.bgColor && { background_color: seg.bgColor }),
|
|
130
|
+
...(seg.bold && { bold: true }),
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
}));
|
|
134
|
+
|
|
135
|
+
const res = await client.docx.documentBlock.patch({
|
|
136
|
+
path: { document_id: docToken, block_id: blockId },
|
|
137
|
+
data: { update_text_elements: { elements } },
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
if (res.code !== 0) {
|
|
141
|
+
throw new Error(res.msg);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
success: true,
|
|
146
|
+
segments: segments.length,
|
|
147
|
+
block: res.data?.block,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -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,70 @@
|
|
|
1
|
+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/feishu";
|
|
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
|
+
function createDocEnabledConfig(): OpenClawPluginApi["config"] {
|
|
25
|
+
return {
|
|
26
|
+
channels: {
|
|
27
|
+
feishu: {
|
|
28
|
+
enabled: true,
|
|
29
|
+
accounts: {
|
|
30
|
+
a: { appId: "app-a", appSecret: "sec-a", tools: { doc: true } }, // pragma: allowlist secret
|
|
31
|
+
b: { appId: "app-b", appSecret: "sec-b", tools: { doc: true } }, // pragma: allowlist secret
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
} as OpenClawPluginApi["config"];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test("uses agentAccountId context when params omit accountId", async () => {
|
|
39
|
+
const cfg = createDocEnabledConfig();
|
|
40
|
+
|
|
41
|
+
const { api, resolveTool } = createToolFactoryHarness(cfg);
|
|
42
|
+
registerFeishuDocTools(api);
|
|
43
|
+
|
|
44
|
+
const docToolA = resolveTool("feishu_doc", { agentAccountId: "a" });
|
|
45
|
+
const docToolB = resolveTool("feishu_doc", { agentAccountId: "b" });
|
|
46
|
+
|
|
47
|
+
await docToolA.execute("call-a", { action: "list_blocks", doc_token: "d" });
|
|
48
|
+
await docToolB.execute("call-b", { action: "list_blocks", doc_token: "d" });
|
|
49
|
+
|
|
50
|
+
expect(createFeishuClientMock).toHaveBeenCalledTimes(2);
|
|
51
|
+
expect(createFeishuClientMock.mock.calls[0]?.[0]?.appId).toBe("app-a");
|
|
52
|
+
expect(createFeishuClientMock.mock.calls[1]?.[0]?.appId).toBe("app-b");
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("explicit accountId param overrides agentAccountId context", async () => {
|
|
56
|
+
const cfg = createDocEnabledConfig();
|
|
57
|
+
|
|
58
|
+
const { api, resolveTool } = createToolFactoryHarness(cfg);
|
|
59
|
+
registerFeishuDocTools(api);
|
|
60
|
+
|
|
61
|
+
const docTool = resolveTool("feishu_doc", { agentAccountId: "b" });
|
|
62
|
+
await docTool.execute("call-override", {
|
|
63
|
+
action: "list_blocks",
|
|
64
|
+
doc_token: "d",
|
|
65
|
+
accountId: "a",
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
expect(createFeishuClientMock.mock.calls.at(-1)?.[0]?.appId).toBe("app-a");
|
|
69
|
+
});
|
|
70
|
+
});
|