@m1heng-clawd/feishu 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 m1heng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,83 @@
1
+ # clawd-feishu
2
+
3
+ Feishu/Lark (飞书) channel plugin for [Clawdbot](https://github.com/clawdbot/clawdbot).
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ clawdbot plugins install @m1heng-clawd/feishu
9
+ ```
10
+
11
+ Or install via npm:
12
+
13
+ ```bash
14
+ npm install @m1heng-clawd/feishu
15
+ ```
16
+
17
+ ## Configuration
18
+
19
+ 1. Create a self-built app on [Feishu Open Platform](https://open.feishu.cn)
20
+ 2. Get your App ID and App Secret from the Credentials page
21
+ 3. Enable required permissions (see below)
22
+ 4. Configure the plugin:
23
+
24
+ ### Required Permissions
25
+
26
+ | Permission | Scope | Description |
27
+ |------------|-------|-------------|
28
+ | `contact:user.base:readonly` | User info | Get basic user information |
29
+ | `im:message` | Messaging | Send and receive messages |
30
+ | `im:message.p2p_msg:readonly` | DM | Read direct messages to bot |
31
+ | `im:message.group_at_msg:readonly` | Group | Receive @mention messages in groups |
32
+ | `im:message:send_as_bot` | Send | Send messages as the bot |
33
+ | `im:resource` | Media | Upload and download images/files |
34
+
35
+ ### Optional Permissions (for full functionality)
36
+
37
+ | Permission | Scope | Description |
38
+ |------------|-------|-------------|
39
+ | `im:message.group_msg` | Group | Read all group messages (sensitive) |
40
+ | `im:message:readonly` | Read | Get message history |
41
+ | `im:message:update` | Edit | Update/edit sent messages |
42
+ | `im:message:recall` | Recall | Recall sent messages |
43
+ | `im:message.reactions:read` | Reactions | View message reactions |
44
+
45
+ ```bash
46
+ clawdbot config set channels.feishu.appId "cli_xxxxx"
47
+ clawdbot config set channels.feishu.appSecret "your_app_secret"
48
+ clawdbot config set channels.feishu.enabled true
49
+ ```
50
+
51
+ ## Configuration Options
52
+
53
+ ```yaml
54
+ channels:
55
+ feishu:
56
+ enabled: true
57
+ appId: "cli_xxxxx"
58
+ appSecret: "secret"
59
+ # Domain: "feishu" (China) or "lark" (International)
60
+ domain: "feishu"
61
+ # Connection mode: "websocket" (recommended) or "webhook"
62
+ connectionMode: "websocket"
63
+ # DM policy: "pairing" | "open" | "allowlist"
64
+ dmPolicy: "pairing"
65
+ # Group policy: "open" | "allowlist" | "disabled"
66
+ groupPolicy: "allowlist"
67
+ # Require @mention in groups
68
+ requireMention: true
69
+ ```
70
+
71
+ ## Features
72
+
73
+ - WebSocket and Webhook connection modes
74
+ - Direct messages and group chats
75
+ - Message replies and quoted message context
76
+ - Image and file uploads
77
+ - Typing indicator (via emoji reactions)
78
+ - Pairing flow for DM approval
79
+ - User and group directory lookup
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,9 @@
1
+ {
2
+ "id": "feishu",
3
+ "channels": ["feishu"],
4
+ "configSchema": {
5
+ "type": "object",
6
+ "additionalProperties": false,
7
+ "properties": {}
8
+ }
9
+ }
package/index.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { ClawdbotPluginApi } from "clawdbot/plugin-sdk";
2
+ import { emptyPluginConfigSchema } from "clawdbot/plugin-sdk";
3
+ import { feishuPlugin } from "./src/channel.js";
4
+ import { setFeishuRuntime } from "./src/runtime.js";
5
+
6
+ export { monitorFeishuProvider } from "./src/monitor.js";
7
+ export {
8
+ sendMessageFeishu,
9
+ sendCardFeishu,
10
+ updateCardFeishu,
11
+ editMessageFeishu,
12
+ getMessageFeishu,
13
+ } from "./src/send.js";
14
+ export {
15
+ uploadImageFeishu,
16
+ uploadFileFeishu,
17
+ sendImageFeishu,
18
+ sendFileFeishu,
19
+ sendMediaFeishu,
20
+ } from "./src/media.js";
21
+ export { probeFeishu } from "./src/probe.js";
22
+ export {
23
+ addReactionFeishu,
24
+ removeReactionFeishu,
25
+ listReactionsFeishu,
26
+ FeishuEmoji,
27
+ } from "./src/reactions.js";
28
+ export { feishuPlugin } from "./src/channel.js";
29
+
30
+ const plugin = {
31
+ id: "feishu",
32
+ name: "Feishu",
33
+ description: "Feishu/Lark channel plugin",
34
+ configSchema: emptyPluginConfigSchema(),
35
+ register(api: ClawdbotPluginApi) {
36
+ setFeishuRuntime(api.runtime);
37
+ api.registerChannel({ plugin: feishuPlugin });
38
+ },
39
+ };
40
+
41
+ export default plugin;
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@m1heng-clawd/feishu",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "Clawdbot Feishu/Lark channel plugin",
6
+ "license": "MIT",
7
+ "files": [
8
+ "index.ts",
9
+ "src",
10
+ "clawdbot.plugin.json"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/m1heng/clawd-feishu"
15
+ },
16
+ "keywords": [
17
+ "clawdbot",
18
+ "feishu",
19
+ "lark",
20
+ "飞书",
21
+ "chatbot",
22
+ "ai",
23
+ "claude"
24
+ ],
25
+ "clawdbot": {
26
+ "extensions": [
27
+ "./index.ts"
28
+ ],
29
+ "channel": {
30
+ "id": "feishu",
31
+ "label": "Feishu",
32
+ "selectionLabel": "Feishu/Lark (飞书)",
33
+ "docsPath": "/channels/feishu",
34
+ "docsLabel": "feishu",
35
+ "blurb": "飞书/Lark enterprise messaging.",
36
+ "aliases": [
37
+ "lark"
38
+ ],
39
+ "order": 70
40
+ },
41
+ "install": {
42
+ "npmSpec": "@m1heng-clawd/feishu",
43
+ "localPath": ".",
44
+ "defaultChoice": "npm"
45
+ }
46
+ },
47
+ "dependencies": {
48
+ "@larksuiteoapi/node-sdk": "^1.30.0",
49
+ "zod": "^4.3.6"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^25.0.10",
53
+ "clawdbot": "2026.1.24-2",
54
+ "tsx": "^4.21.0",
55
+ "typescript": "^5.7.0"
56
+ },
57
+ "peerDependencies": {
58
+ "clawdbot": ">=2026.1.24"
59
+ }
60
+ }
@@ -0,0 +1,53 @@
1
+ import type { ClawdbotConfig } from "clawdbot/plugin-sdk";
2
+ import { DEFAULT_ACCOUNT_ID } from "clawdbot/plugin-sdk";
3
+ import type { FeishuConfig, FeishuDomain, ResolvedFeishuAccount } from "./types.js";
4
+
5
+ export function resolveFeishuCredentials(cfg?: FeishuConfig): {
6
+ appId: string;
7
+ appSecret: string;
8
+ encryptKey?: string;
9
+ verificationToken?: string;
10
+ domain: FeishuDomain;
11
+ } | null {
12
+ const appId = cfg?.appId?.trim();
13
+ const appSecret = cfg?.appSecret?.trim();
14
+ if (!appId || !appSecret) return null;
15
+ return {
16
+ appId,
17
+ appSecret,
18
+ encryptKey: cfg?.encryptKey?.trim() || undefined,
19
+ verificationToken: cfg?.verificationToken?.trim() || undefined,
20
+ domain: cfg?.domain ?? "feishu",
21
+ };
22
+ }
23
+
24
+ export function resolveFeishuAccount(params: {
25
+ cfg: ClawdbotConfig;
26
+ accountId?: string | null;
27
+ }): ResolvedFeishuAccount {
28
+ const feishuCfg = params.cfg.channels?.feishu as FeishuConfig | undefined;
29
+ const enabled = feishuCfg?.enabled !== false;
30
+ const creds = resolveFeishuCredentials(feishuCfg);
31
+
32
+ return {
33
+ accountId: params.accountId?.trim() || DEFAULT_ACCOUNT_ID,
34
+ enabled,
35
+ configured: Boolean(creds),
36
+ appId: creds?.appId,
37
+ domain: creds?.domain ?? "feishu",
38
+ };
39
+ }
40
+
41
+ export function listFeishuAccountIds(_cfg: ClawdbotConfig): string[] {
42
+ return [DEFAULT_ACCOUNT_ID];
43
+ }
44
+
45
+ export function resolveDefaultFeishuAccountId(_cfg: ClawdbotConfig): string {
46
+ return DEFAULT_ACCOUNT_ID;
47
+ }
48
+
49
+ export function listEnabledFeishuAccounts(cfg: ClawdbotConfig): ResolvedFeishuAccount[] {
50
+ return listFeishuAccountIds(cfg)
51
+ .map((accountId) => resolveFeishuAccount({ cfg, accountId }))
52
+ .filter((account) => account.enabled && account.configured);
53
+ }
package/src/bot.ts ADDED
@@ -0,0 +1,320 @@
1
+ import type { ClawdbotConfig, RuntimeEnv } from "clawdbot/plugin-sdk";
2
+ import {
3
+ buildPendingHistoryContextFromMap,
4
+ recordPendingHistoryEntryIfEnabled,
5
+ clearHistoryEntriesIfEnabled,
6
+ DEFAULT_GROUP_HISTORY_LIMIT,
7
+ type HistoryEntry,
8
+ } from "clawdbot/plugin-sdk";
9
+ import type { FeishuConfig, FeishuMessageContext } from "./types.js";
10
+ import { getFeishuRuntime } from "./runtime.js";
11
+ import {
12
+ resolveFeishuGroupConfig,
13
+ resolveFeishuReplyPolicy,
14
+ resolveFeishuAllowlistMatch,
15
+ isFeishuGroupAllowed,
16
+ } from "./policy.js";
17
+ import { createFeishuReplyDispatcher } from "./reply-dispatcher.js";
18
+ import { getMessageFeishu } from "./send.js";
19
+
20
+ export type FeishuMessageEvent = {
21
+ sender: {
22
+ sender_id: {
23
+ open_id?: string;
24
+ user_id?: string;
25
+ union_id?: string;
26
+ };
27
+ sender_type?: string;
28
+ tenant_key?: string;
29
+ };
30
+ message: {
31
+ message_id: string;
32
+ root_id?: string;
33
+ parent_id?: string;
34
+ chat_id: string;
35
+ chat_type: "p2p" | "group";
36
+ message_type: string;
37
+ content: string;
38
+ mentions?: Array<{
39
+ key: string;
40
+ id: {
41
+ open_id?: string;
42
+ user_id?: string;
43
+ union_id?: string;
44
+ };
45
+ name: string;
46
+ tenant_key?: string;
47
+ }>;
48
+ };
49
+ };
50
+
51
+ export type FeishuBotAddedEvent = {
52
+ chat_id: string;
53
+ operator_id: {
54
+ open_id?: string;
55
+ user_id?: string;
56
+ union_id?: string;
57
+ };
58
+ external: boolean;
59
+ operator_tenant_key?: string;
60
+ };
61
+
62
+ function parseMessageContent(content: string, messageType: string): string {
63
+ try {
64
+ const parsed = JSON.parse(content);
65
+ if (messageType === "text") {
66
+ return parsed.text || "";
67
+ }
68
+ return content;
69
+ } catch {
70
+ return content;
71
+ }
72
+ }
73
+
74
+ function checkBotMentioned(event: FeishuMessageEvent, botOpenId?: string): boolean {
75
+ const mentions = event.message.mentions ?? [];
76
+ if (mentions.length === 0) return false;
77
+ if (!botOpenId) return mentions.length > 0;
78
+ return mentions.some((m) => m.id.open_id === botOpenId);
79
+ }
80
+
81
+ function stripBotMention(text: string, mentions?: FeishuMessageEvent["message"]["mentions"]): string {
82
+ if (!mentions || mentions.length === 0) return text;
83
+ let result = text;
84
+ for (const mention of mentions) {
85
+ result = result.replace(new RegExp(`@${mention.name}\\s*`, "g"), "").trim();
86
+ result = result.replace(new RegExp(mention.key, "g"), "").trim();
87
+ }
88
+ return result;
89
+ }
90
+
91
+ export function parseFeishuMessageEvent(
92
+ event: FeishuMessageEvent,
93
+ botOpenId?: string,
94
+ ): FeishuMessageContext {
95
+ const rawContent = parseMessageContent(event.message.content, event.message.message_type);
96
+ const mentionedBot = checkBotMentioned(event, botOpenId);
97
+ const content = stripBotMention(rawContent, event.message.mentions);
98
+
99
+ return {
100
+ chatId: event.message.chat_id,
101
+ messageId: event.message.message_id,
102
+ senderId: event.sender.sender_id.user_id || event.sender.sender_id.open_id || "",
103
+ senderOpenId: event.sender.sender_id.open_id || "",
104
+ chatType: event.message.chat_type,
105
+ mentionedBot,
106
+ rootId: event.message.root_id || undefined,
107
+ parentId: event.message.parent_id || undefined,
108
+ content,
109
+ contentType: event.message.message_type,
110
+ };
111
+ }
112
+
113
+ export async function handleFeishuMessage(params: {
114
+ cfg: ClawdbotConfig;
115
+ event: FeishuMessageEvent;
116
+ botOpenId?: string;
117
+ runtime?: RuntimeEnv;
118
+ chatHistories?: Map<string, HistoryEntry[]>;
119
+ }): Promise<void> {
120
+ const { cfg, event, botOpenId, runtime, chatHistories } = params;
121
+ const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
122
+ const log = runtime?.log ?? console.log;
123
+ const error = runtime?.error ?? console.error;
124
+
125
+ const ctx = parseFeishuMessageEvent(event, botOpenId);
126
+ const isGroup = ctx.chatType === "group";
127
+
128
+ log(`feishu: received message from ${ctx.senderOpenId} in ${ctx.chatId} (${ctx.chatType})`);
129
+
130
+ const historyLimit = Math.max(
131
+ 0,
132
+ feishuCfg?.historyLimit ?? cfg.messages?.groupChat?.historyLimit ?? DEFAULT_GROUP_HISTORY_LIMIT,
133
+ );
134
+
135
+ if (isGroup) {
136
+ const groupPolicy = feishuCfg?.groupPolicy ?? "open";
137
+ const groupAllowFrom = feishuCfg?.groupAllowFrom ?? [];
138
+ const groupConfig = resolveFeishuGroupConfig({ cfg: feishuCfg, groupId: ctx.chatId });
139
+
140
+ const senderAllowFrom = groupConfig?.allowFrom ?? groupAllowFrom;
141
+ const allowed = isFeishuGroupAllowed({
142
+ groupPolicy,
143
+ allowFrom: senderAllowFrom,
144
+ senderId: ctx.senderOpenId,
145
+ senderName: ctx.senderName,
146
+ });
147
+
148
+ if (!allowed) {
149
+ log(`feishu: sender ${ctx.senderOpenId} not in group allowlist`);
150
+ return;
151
+ }
152
+
153
+ const { requireMention } = resolveFeishuReplyPolicy({
154
+ isDirectMessage: false,
155
+ globalConfig: feishuCfg,
156
+ groupConfig,
157
+ });
158
+
159
+ if (requireMention && !ctx.mentionedBot) {
160
+ log(`feishu: message in group ${ctx.chatId} did not mention bot, recording to history`);
161
+ if (chatHistories) {
162
+ recordPendingHistoryEntryIfEnabled({
163
+ historyMap: chatHistories,
164
+ historyKey: ctx.chatId,
165
+ limit: historyLimit,
166
+ entry: {
167
+ sender: ctx.senderOpenId,
168
+ body: ctx.content,
169
+ timestamp: Date.now(),
170
+ messageId: ctx.messageId,
171
+ },
172
+ });
173
+ }
174
+ return;
175
+ }
176
+ } else {
177
+ const dmPolicy = feishuCfg?.dmPolicy ?? "pairing";
178
+ const allowFrom = feishuCfg?.allowFrom ?? [];
179
+
180
+ if (dmPolicy === "allowlist") {
181
+ const match = resolveFeishuAllowlistMatch({
182
+ allowFrom,
183
+ senderId: ctx.senderOpenId,
184
+ });
185
+ if (!match.allowed) {
186
+ log(`feishu: sender ${ctx.senderOpenId} not in DM allowlist`);
187
+ return;
188
+ }
189
+ }
190
+ }
191
+
192
+ try {
193
+ const core = getFeishuRuntime();
194
+
195
+ const feishuFrom = isGroup ? `feishu:group:${ctx.chatId}` : `feishu:${ctx.senderOpenId}`;
196
+ const feishuTo = isGroup ? `chat:${ctx.chatId}` : `user:${ctx.senderOpenId}`;
197
+
198
+ const route = core.channel.routing.resolveAgentRoute({
199
+ cfg,
200
+ channel: "feishu",
201
+ peer: {
202
+ kind: isGroup ? "group" : "dm",
203
+ id: isGroup ? ctx.chatId : ctx.senderOpenId,
204
+ },
205
+ });
206
+
207
+ const preview = ctx.content.replace(/\s+/g, " ").slice(0, 160);
208
+ const inboundLabel = isGroup
209
+ ? `Feishu message in group ${ctx.chatId}`
210
+ : `Feishu DM from ${ctx.senderOpenId}`;
211
+
212
+ core.system.enqueueSystemEvent(`${inboundLabel}: ${preview}`, {
213
+ sessionKey: route.sessionKey,
214
+ contextKey: `feishu:message:${ctx.chatId}:${ctx.messageId}`,
215
+ });
216
+
217
+ // Fetch quoted/replied message content if parentId exists
218
+ let quotedContent: string | undefined;
219
+ if (ctx.parentId) {
220
+ try {
221
+ const quotedMsg = await getMessageFeishu({ cfg, messageId: ctx.parentId });
222
+ if (quotedMsg) {
223
+ quotedContent = quotedMsg.content;
224
+ log(`feishu: fetched quoted message: ${quotedContent?.slice(0, 100)}`);
225
+ }
226
+ } catch (err) {
227
+ log(`feishu: failed to fetch quoted message: ${String(err)}`);
228
+ }
229
+ }
230
+
231
+ const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(cfg);
232
+
233
+ // Build message body with quoted content if available
234
+ let messageBody = ctx.content;
235
+ if (quotedContent) {
236
+ messageBody = `[Replying to: "${quotedContent}"]\n\n${ctx.content}`;
237
+ }
238
+
239
+ const body = core.channel.reply.formatAgentEnvelope({
240
+ channel: "Feishu",
241
+ from: isGroup ? ctx.chatId : ctx.senderOpenId,
242
+ timestamp: new Date(),
243
+ envelope: envelopeOptions,
244
+ body: messageBody,
245
+ });
246
+
247
+ let combinedBody = body;
248
+ const historyKey = isGroup ? ctx.chatId : undefined;
249
+
250
+ if (isGroup && historyKey && chatHistories) {
251
+ combinedBody = buildPendingHistoryContextFromMap({
252
+ historyMap: chatHistories,
253
+ historyKey,
254
+ limit: historyLimit,
255
+ currentMessage: combinedBody,
256
+ formatEntry: (entry) =>
257
+ core.channel.reply.formatAgentEnvelope({
258
+ channel: "Feishu",
259
+ from: ctx.chatId,
260
+ timestamp: entry.timestamp,
261
+ body: `${entry.sender}: ${entry.body}`,
262
+ envelope: envelopeOptions,
263
+ }),
264
+ });
265
+ }
266
+
267
+ const ctxPayload = core.channel.reply.finalizeInboundContext({
268
+ Body: combinedBody,
269
+ RawBody: ctx.content,
270
+ CommandBody: ctx.content,
271
+ From: feishuFrom,
272
+ To: feishuTo,
273
+ SessionKey: route.sessionKey,
274
+ AccountId: route.accountId,
275
+ ChatType: isGroup ? "group" : "direct",
276
+ GroupSubject: isGroup ? ctx.chatId : undefined,
277
+ SenderName: ctx.senderOpenId,
278
+ SenderId: ctx.senderOpenId,
279
+ Provider: "feishu" as const,
280
+ Surface: "feishu" as const,
281
+ MessageSid: ctx.messageId,
282
+ Timestamp: Date.now(),
283
+ WasMentioned: ctx.mentionedBot,
284
+ CommandAuthorized: true,
285
+ OriginatingChannel: "feishu" as const,
286
+ OriginatingTo: feishuTo,
287
+ });
288
+
289
+ const { dispatcher, replyOptions, markDispatchIdle } = createFeishuReplyDispatcher({
290
+ cfg,
291
+ agentId: route.agentId,
292
+ runtime: runtime as RuntimeEnv,
293
+ chatId: ctx.chatId,
294
+ replyToMessageId: ctx.messageId,
295
+ });
296
+
297
+ log(`feishu: dispatching to agent (session=${route.sessionKey})`);
298
+
299
+ const { queuedFinal, counts } = await core.channel.reply.dispatchReplyFromConfig({
300
+ ctx: ctxPayload,
301
+ cfg,
302
+ dispatcher,
303
+ replyOptions,
304
+ });
305
+
306
+ markDispatchIdle();
307
+
308
+ if (isGroup && historyKey && chatHistories) {
309
+ clearHistoryEntriesIfEnabled({
310
+ historyMap: chatHistories,
311
+ historyKey,
312
+ limit: historyLimit,
313
+ });
314
+ }
315
+
316
+ log(`feishu: dispatch complete (queuedFinal=${queuedFinal}, replies=${counts.final})`);
317
+ } catch (err) {
318
+ error(`feishu: failed to dispatch message: ${String(err)}`);
319
+ }
320
+ }