@gakr-gakr/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.
Files changed (133) hide show
  1. package/api.ts +32 -0
  2. package/autobot.plugin.json +180 -0
  3. package/channel-entry.ts +20 -0
  4. package/channel-plugin-api.ts +1 -0
  5. package/contract-api.ts +16 -0
  6. package/index.ts +82 -0
  7. package/package.json +62 -0
  8. package/runtime-api.ts +55 -0
  9. package/secret-contract-api.ts +5 -0
  10. package/security-contract-api.ts +1 -0
  11. package/session-key-api.ts +1 -0
  12. package/setup-api.ts +3 -0
  13. package/setup-entry.ts +13 -0
  14. package/skills/feishu-doc/SKILL.md +211 -0
  15. package/skills/feishu-doc/references/block-types.md +103 -0
  16. package/skills/feishu-drive/SKILL.md +97 -0
  17. package/skills/feishu-perm/SKILL.md +119 -0
  18. package/skills/feishu-wiki/SKILL.md +113 -0
  19. package/src/accounts.ts +333 -0
  20. package/src/agent-config.ts +21 -0
  21. package/src/app-registration.ts +331 -0
  22. package/src/approval-auth.ts +25 -0
  23. package/src/async.ts +104 -0
  24. package/src/audio-preflight.runtime.ts +9 -0
  25. package/src/bitable.ts +762 -0
  26. package/src/bot-content.ts +485 -0
  27. package/src/bot-runtime-api.ts +12 -0
  28. package/src/bot-sender-name.ts +125 -0
  29. package/src/bot.ts +1703 -0
  30. package/src/card-action.ts +447 -0
  31. package/src/card-interaction.ts +159 -0
  32. package/src/card-test-helpers.ts +54 -0
  33. package/src/card-ux-approval.ts +65 -0
  34. package/src/card-ux-launcher.ts +121 -0
  35. package/src/card-ux-shared.ts +33 -0
  36. package/src/channel-runtime-api.ts +16 -0
  37. package/src/channel.runtime.ts +47 -0
  38. package/src/channel.ts +1423 -0
  39. package/src/chat-schema.ts +25 -0
  40. package/src/chat.ts +188 -0
  41. package/src/client-timeout.ts +42 -0
  42. package/src/client.ts +262 -0
  43. package/src/comment-dispatcher-runtime-api.ts +6 -0
  44. package/src/comment-dispatcher.ts +107 -0
  45. package/src/comment-handler-runtime-api.ts +3 -0
  46. package/src/comment-handler.ts +303 -0
  47. package/src/comment-reaction.ts +259 -0
  48. package/src/comment-shared.ts +406 -0
  49. package/src/comment-target.ts +44 -0
  50. package/src/config-schema.ts +335 -0
  51. package/src/conversation-id.ts +199 -0
  52. package/src/dedup-runtime-api.ts +1 -0
  53. package/src/dedup.ts +141 -0
  54. package/src/dedupe-key.ts +72 -0
  55. package/src/directory.static.ts +61 -0
  56. package/src/directory.ts +124 -0
  57. package/src/doc-schema.ts +182 -0
  58. package/src/docx-batch-insert.ts +223 -0
  59. package/src/docx-color-text.ts +154 -0
  60. package/src/docx-table-ops.ts +316 -0
  61. package/src/docx-types.ts +38 -0
  62. package/src/docx.ts +1596 -0
  63. package/src/drive-schema.ts +92 -0
  64. package/src/drive.ts +829 -0
  65. package/src/dynamic-agent.ts +143 -0
  66. package/src/event-types.ts +45 -0
  67. package/src/external-keys.ts +19 -0
  68. package/src/lifecycle.test-support.ts +220 -0
  69. package/src/media.ts +1105 -0
  70. package/src/mention-target.types.ts +5 -0
  71. package/src/mention.ts +114 -0
  72. package/src/message-action-contract.ts +13 -0
  73. package/src/monitor-state-runtime-api.ts +7 -0
  74. package/src/monitor-transport-runtime-api.ts +10 -0
  75. package/src/monitor.account.ts +492 -0
  76. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  77. package/src/monitor.bot-identity.ts +86 -0
  78. package/src/monitor.bot-menu-handler.ts +165 -0
  79. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  80. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  81. package/src/monitor.card-action.lifecycle.test-support.ts +421 -0
  82. package/src/monitor.comment-notice-handler.ts +105 -0
  83. package/src/monitor.comment.ts +1386 -0
  84. package/src/monitor.message-handler.ts +350 -0
  85. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  86. package/src/monitor.startup.ts +74 -0
  87. package/src/monitor.state.ts +170 -0
  88. package/src/monitor.synthetic-error.ts +18 -0
  89. package/src/monitor.test-mocks.ts +46 -0
  90. package/src/monitor.transport.ts +451 -0
  91. package/src/monitor.ts +100 -0
  92. package/src/outbound-runtime-api.ts +1 -0
  93. package/src/outbound.ts +785 -0
  94. package/src/perm-schema.ts +52 -0
  95. package/src/perm.ts +170 -0
  96. package/src/pins.ts +108 -0
  97. package/src/policy.ts +321 -0
  98. package/src/post.ts +275 -0
  99. package/src/probe.ts +166 -0
  100. package/src/processing-claims.ts +59 -0
  101. package/src/qr-terminal.ts +1 -0
  102. package/src/reactions.ts +123 -0
  103. package/src/reasoning-preview.ts +28 -0
  104. package/src/reply-dispatcher-runtime-api.ts +7 -0
  105. package/src/reply-dispatcher.ts +748 -0
  106. package/src/runtime.ts +9 -0
  107. package/src/secret-contract.ts +145 -0
  108. package/src/secret-input.ts +1 -0
  109. package/src/security-audit-shared.ts +69 -0
  110. package/src/security-audit.ts +1 -0
  111. package/src/send-result.ts +80 -0
  112. package/src/send-target.ts +35 -0
  113. package/src/send.ts +861 -0
  114. package/src/sequential-key.ts +28 -0
  115. package/src/sequential-queue.ts +86 -0
  116. package/src/session-conversation.ts +42 -0
  117. package/src/session-route.ts +48 -0
  118. package/src/setup-core.ts +51 -0
  119. package/src/setup-surface.ts +618 -0
  120. package/src/streaming-card.ts +571 -0
  121. package/src/subagent-hooks.ts +413 -0
  122. package/src/targets.ts +97 -0
  123. package/src/thread-bindings.ts +331 -0
  124. package/src/tool-account.ts +93 -0
  125. package/src/tool-factory-test-harness.ts +79 -0
  126. package/src/tool-result.ts +16 -0
  127. package/src/tools-config.ts +22 -0
  128. package/src/types.ts +106 -0
  129. package/src/typing.ts +214 -0
  130. package/src/wiki-schema.ts +69 -0
  131. package/src/wiki.ts +270 -0
  132. package/subagent-hooks-api.ts +31 -0
  133. package/tsconfig.json +16 -0
@@ -0,0 +1,25 @@
1
+ import { Type, type Static } from "typebox";
2
+
3
+ const CHAT_ACTION_VALUES = ["members", "info", "member_info"] as const;
4
+ const MEMBER_ID_TYPE_VALUES = ["open_id", "user_id", "union_id"] as const;
5
+
6
+ export const FeishuChatSchema = Type.Object({
7
+ action: Type.Unsafe<(typeof CHAT_ACTION_VALUES)[number]>({
8
+ type: "string",
9
+ enum: [...CHAT_ACTION_VALUES],
10
+ description: "Action to run: members | info | member_info",
11
+ }),
12
+ chat_id: Type.Optional(Type.String({ description: "Chat ID (from URL or event payload)" })),
13
+ member_id: Type.Optional(Type.String({ description: "Member ID for member_info lookups" })),
14
+ page_size: Type.Optional(Type.Number({ description: "Page size (1-100, default 50)" })),
15
+ page_token: Type.Optional(Type.String({ description: "Pagination token" })),
16
+ member_id_type: Type.Optional(
17
+ Type.Unsafe<(typeof MEMBER_ID_TYPE_VALUES)[number]>({
18
+ type: "string",
19
+ enum: [...MEMBER_ID_TYPE_VALUES],
20
+ description: "Member ID type (default: open_id)",
21
+ }),
22
+ ),
23
+ });
24
+
25
+ export type FeishuChatParams = Static<typeof FeishuChatSchema>;
package/src/chat.ts ADDED
@@ -0,0 +1,188 @@
1
+ import type * as Lark from "@larksuiteoapi/node-sdk";
2
+ import type { AutoBotPluginApi } from "../runtime-api.js";
3
+ import { listEnabledFeishuAccounts } from "./accounts.js";
4
+ import { FeishuChatSchema, type FeishuChatParams } from "./chat-schema.js";
5
+ import { createFeishuClient } from "./client.js";
6
+ import { formatFeishuApiError } from "./comment-shared.js";
7
+ import { resolveToolsConfig } from "./tools-config.js";
8
+
9
+ function json(data: unknown) {
10
+ return {
11
+ content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }],
12
+ details: data,
13
+ };
14
+ }
15
+
16
+ export async function getChatInfo(client: Lark.Client, chatId: string) {
17
+ const res = await client.im.chat.get({ path: { chat_id: chatId } });
18
+ if (res.code !== 0) {
19
+ throw new Error(res.msg);
20
+ }
21
+
22
+ const chat = res.data;
23
+ return {
24
+ chat_id: chatId,
25
+ name: chat?.name,
26
+ description: chat?.description,
27
+ owner_id: chat?.owner_id,
28
+ tenant_key: chat?.tenant_key,
29
+ user_count: chat?.user_count,
30
+ chat_mode: chat?.chat_mode,
31
+ chat_type: chat?.chat_type,
32
+ join_message_visibility: chat?.join_message_visibility,
33
+ leave_message_visibility: chat?.leave_message_visibility,
34
+ membership_approval: chat?.membership_approval,
35
+ moderation_permission: chat?.moderation_permission,
36
+ avatar: chat?.avatar,
37
+ };
38
+ }
39
+
40
+ export async function getChatMembers(
41
+ client: Lark.Client,
42
+ chatId: string,
43
+ pageSize?: number,
44
+ pageToken?: string,
45
+ memberIdType?: "open_id" | "user_id" | "union_id",
46
+ ) {
47
+ const page_size = pageSize ? Math.max(1, Math.min(100, pageSize)) : 50;
48
+ const res = await client.im.chatMembers.get({
49
+ path: { chat_id: chatId },
50
+ params: {
51
+ page_size,
52
+ page_token: pageToken,
53
+ member_id_type: memberIdType ?? "open_id",
54
+ },
55
+ });
56
+
57
+ if (res.code !== 0) {
58
+ throw new Error(res.msg);
59
+ }
60
+
61
+ return {
62
+ chat_id: chatId,
63
+ has_more: res.data?.has_more,
64
+ page_token: res.data?.page_token,
65
+ members:
66
+ res.data?.items?.map((item) => ({
67
+ member_id: item.member_id,
68
+ name: item.name,
69
+ tenant_key: item.tenant_key,
70
+ member_id_type: item.member_id_type,
71
+ })) ?? [],
72
+ };
73
+ }
74
+
75
+ export async function getFeishuMemberInfo(
76
+ client: Lark.Client,
77
+ memberId: string,
78
+ memberIdType: "open_id" | "user_id" | "union_id" = "open_id",
79
+ ) {
80
+ const res = await client.contact.user.get({
81
+ path: { user_id: memberId },
82
+ params: {
83
+ user_id_type: memberIdType,
84
+ department_id_type: "open_department_id",
85
+ },
86
+ });
87
+
88
+ if (res.code !== 0) {
89
+ throw new Error(res.msg);
90
+ }
91
+
92
+ const user = res.data?.user;
93
+ return {
94
+ member_id: memberId,
95
+ member_id_type: memberIdType,
96
+ open_id: user?.open_id,
97
+ user_id: user?.user_id,
98
+ union_id: user?.union_id,
99
+ name: user?.name,
100
+ en_name: user?.en_name,
101
+ nickname: user?.nickname,
102
+ email: user?.email,
103
+ enterprise_email: user?.enterprise_email,
104
+ mobile: user?.mobile,
105
+ mobile_visible: user?.mobile_visible,
106
+ status: user?.status,
107
+ avatar: user?.avatar,
108
+ department_ids: user?.department_ids,
109
+ department_path: user?.department_path,
110
+ leader_user_id: user?.leader_user_id,
111
+ city: user?.city,
112
+ country: user?.country,
113
+ work_station: user?.work_station,
114
+ join_time: user?.join_time,
115
+ is_tenant_manager: user?.is_tenant_manager,
116
+ employee_no: user?.employee_no,
117
+ employee_type: user?.employee_type,
118
+ description: user?.description,
119
+ job_title: user?.job_title,
120
+ geo: user?.geo,
121
+ };
122
+ }
123
+
124
+ export function registerFeishuChatTools(api: AutoBotPluginApi) {
125
+ if (!api.config) {
126
+ return;
127
+ }
128
+
129
+ const accounts = listEnabledFeishuAccounts(api.config);
130
+ if (accounts.length === 0) {
131
+ return;
132
+ }
133
+
134
+ const firstAccount = accounts[0];
135
+ const toolsCfg = resolveToolsConfig(firstAccount.config.tools);
136
+ if (!toolsCfg.chat) {
137
+ return;
138
+ }
139
+
140
+ const getClient = () => createFeishuClient(firstAccount);
141
+
142
+ api.registerTool(
143
+ {
144
+ name: "feishu_chat",
145
+ label: "Feishu Chat",
146
+ description: "Feishu chat operations. Actions: members, info, member_info",
147
+ parameters: FeishuChatSchema,
148
+ async execute(_toolCallId, params) {
149
+ const p = params as FeishuChatParams;
150
+ try {
151
+ const client = getClient();
152
+ switch (p.action) {
153
+ case "members":
154
+ if (!p.chat_id) {
155
+ return json({ error: "chat_id is required for action members" });
156
+ }
157
+ return json(
158
+ await getChatMembers(
159
+ client,
160
+ p.chat_id,
161
+ p.page_size,
162
+ p.page_token,
163
+ p.member_id_type,
164
+ ),
165
+ );
166
+ case "info":
167
+ if (!p.chat_id) {
168
+ return json({ error: "chat_id is required for action info" });
169
+ }
170
+ return json(await getChatInfo(client, p.chat_id));
171
+ case "member_info":
172
+ if (!p.member_id) {
173
+ return json({ error: "member_id is required for action member_info" });
174
+ }
175
+ return json(
176
+ await getFeishuMemberInfo(client, p.member_id, p.member_id_type ?? "open_id"),
177
+ );
178
+ default:
179
+ return json({ error: `Unknown action: ${String(p.action)}` });
180
+ }
181
+ } catch (err) {
182
+ return json({ error: formatFeishuApiError(err, { includeNestedErrorLogId: true }) });
183
+ }
184
+ },
185
+ },
186
+ { name: "feishu_chat" },
187
+ );
188
+ }
@@ -0,0 +1,42 @@
1
+ import type { FeishuConfig } from "./types.js";
2
+
3
+ /** Default HTTP timeout for Feishu API requests (30 seconds). */
4
+ export const FEISHU_HTTP_TIMEOUT_MS = 30_000;
5
+ export const FEISHU_HTTP_TIMEOUT_MAX_MS = 300_000;
6
+ export const FEISHU_HTTP_TIMEOUT_ENV_VAR = "AUTOBOT_FEISHU_HTTP_TIMEOUT_MS";
7
+
8
+ export type FeishuClientTimeoutConfig = {
9
+ httpTimeoutMs?: number;
10
+ config?: Pick<FeishuConfig, "httpTimeoutMs">;
11
+ };
12
+
13
+ export function resolveConfiguredHttpTimeoutMs(creds: FeishuClientTimeoutConfig): number {
14
+ const clampTimeout = (value: number): number => {
15
+ const rounded = Math.floor(value);
16
+ return Math.min(Math.max(rounded, 1), FEISHU_HTTP_TIMEOUT_MAX_MS);
17
+ };
18
+
19
+ const fromDirectField = creds.httpTimeoutMs;
20
+ if (
21
+ typeof fromDirectField === "number" &&
22
+ Number.isFinite(fromDirectField) &&
23
+ fromDirectField > 0
24
+ ) {
25
+ return clampTimeout(fromDirectField);
26
+ }
27
+
28
+ const envRaw = process.env[FEISHU_HTTP_TIMEOUT_ENV_VAR];
29
+ if (envRaw) {
30
+ const envValue = Number(envRaw);
31
+ if (Number.isFinite(envValue) && envValue > 0) {
32
+ return clampTimeout(envValue);
33
+ }
34
+ }
35
+
36
+ const fromConfig = creds.config?.httpTimeoutMs;
37
+ const timeout = fromConfig;
38
+ if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0) {
39
+ return FEISHU_HTTP_TIMEOUT_MS;
40
+ }
41
+ return clampTimeout(timeout);
42
+ }
package/src/client.ts ADDED
@@ -0,0 +1,262 @@
1
+ import type { Agent } from "node:https";
2
+ import { createRequire } from "node:module";
3
+ import * as Lark from "@larksuiteoapi/node-sdk";
4
+ import {
5
+ readPluginPackageVersion,
6
+ resolveAmbientNodeProxyAgent,
7
+ } from "autobot/plugin-sdk/extension-shared";
8
+ import {
9
+ FEISHU_HTTP_TIMEOUT_ENV_VAR,
10
+ FEISHU_HTTP_TIMEOUT_MAX_MS,
11
+ FEISHU_HTTP_TIMEOUT_MS,
12
+ resolveConfiguredHttpTimeoutMs,
13
+ } from "./client-timeout.js";
14
+ import type { FeishuConfig, FeishuDomain, ResolvedFeishuAccount } from "./types.js";
15
+
16
+ const require = createRequire(import.meta.url);
17
+ const pluginVersion = readPluginPackageVersion({ require });
18
+
19
+ export { pluginVersion };
20
+
21
+ const FEISHU_USER_AGENT = `autobot-feishu-builtin/${pluginVersion}/${process.platform}`;
22
+ export { FEISHU_USER_AGENT };
23
+
24
+ const FEISHU_WS_CONFIG = {
25
+ PingInterval: 30,
26
+ PingTimeout: 3,
27
+ } as const;
28
+
29
+ /** User-Agent header value for all Feishu API requests. */
30
+ export function getFeishuUserAgent(): string {
31
+ return FEISHU_USER_AGENT;
32
+ }
33
+
34
+ type FeishuClientSdk = Pick<
35
+ typeof Lark,
36
+ | "AppType"
37
+ | "Client"
38
+ | "defaultHttpInstance"
39
+ | "Domain"
40
+ | "EventDispatcher"
41
+ | "LoggerLevel"
42
+ | "WSClient"
43
+ >;
44
+
45
+ const defaultFeishuClientSdk: FeishuClientSdk = {
46
+ AppType: Lark.AppType,
47
+ Client: Lark.Client,
48
+ defaultHttpInstance: Lark.defaultHttpInstance,
49
+ Domain: Lark.Domain,
50
+ EventDispatcher: Lark.EventDispatcher,
51
+ LoggerLevel: Lark.LoggerLevel,
52
+ WSClient: Lark.WSClient,
53
+ };
54
+
55
+ let feishuClientSdk: FeishuClientSdk = defaultFeishuClientSdk;
56
+
57
+ // Override the SDK's default User-Agent interceptor.
58
+ // The Lark SDK registers an axios request interceptor that sets
59
+ // 'oapi-node-sdk/1.0.0'. Axios request interceptors execute in LIFO order
60
+ // (last-registered runs first), so simply appending ours doesn't work — the
61
+ // SDK's interceptor would run last and overwrite our UA. We must clear
62
+ // handlers[] first, then register our own as the sole interceptor.
63
+ //
64
+ // Risk is low: the SDK only registers one interceptor (UA) at init time, and
65
+ // we clear it at module load before any other code can register handlers.
66
+ // If a future SDK version adds more interceptors, the upgrade will need
67
+ // compatibility verification regardless.
68
+ {
69
+ const inst = Lark.defaultHttpInstance as {
70
+ interceptors?: {
71
+ request: { handlers: unknown[]; use: (fn: (req: unknown) => unknown) => void };
72
+ };
73
+ };
74
+ if (inst.interceptors?.request) {
75
+ inst.interceptors.request.handlers = [];
76
+ inst.interceptors.request.use((req: unknown) => {
77
+ const r = req as { headers?: Record<string, string> };
78
+ if (r.headers) {
79
+ r.headers["User-Agent"] = getFeishuUserAgent();
80
+ }
81
+ return req;
82
+ });
83
+ }
84
+ }
85
+
86
+ export { FEISHU_HTTP_TIMEOUT_ENV_VAR, FEISHU_HTTP_TIMEOUT_MAX_MS, FEISHU_HTTP_TIMEOUT_MS };
87
+
88
+ type FeishuHttpInstanceLike = Pick<
89
+ typeof feishuClientSdk.defaultHttpInstance,
90
+ "request" | "get" | "post" | "put" | "patch" | "delete" | "head" | "options"
91
+ >;
92
+
93
+ async function getWsProxyAgent() {
94
+ return resolveAmbientNodeProxyAgent<Agent>();
95
+ }
96
+
97
+ // Multi-account client cache
98
+ const clientCache = new Map<
99
+ string,
100
+ {
101
+ client: Lark.Client;
102
+ config: { appId: string; appSecret: string; domain?: FeishuDomain; httpTimeoutMs: number };
103
+ }
104
+ >();
105
+
106
+ function resolveDomain(domain: FeishuDomain | undefined): Lark.Domain | string {
107
+ if (domain === "lark") {
108
+ return feishuClientSdk.Domain.Lark;
109
+ }
110
+ if (domain === "feishu" || !domain) {
111
+ return feishuClientSdk.Domain.Feishu;
112
+ }
113
+ return domain.replace(/\/+$/, ""); // Custom URL for private deployment
114
+ }
115
+
116
+ /**
117
+ * Create an HTTP instance that delegates to the Lark SDK's default instance
118
+ * but injects a default request timeout and User-Agent header to prevent
119
+ * indefinite hangs and set a standardized User-Agent per OAPI best practices.
120
+ */
121
+ function createTimeoutHttpInstance(defaultTimeoutMs: number): Lark.HttpInstance {
122
+ const base: FeishuHttpInstanceLike = feishuClientSdk.defaultHttpInstance;
123
+
124
+ function injectTimeout<D>(opts?: Lark.HttpRequestOptions<D>): Lark.HttpRequestOptions<D> {
125
+ return { timeout: defaultTimeoutMs, ...opts } as Lark.HttpRequestOptions<D>;
126
+ }
127
+
128
+ return {
129
+ request: (opts) => base.request(injectTimeout(opts)),
130
+ get: (url, opts) => base.get(url, injectTimeout(opts)),
131
+ post: (url, data, opts) => base.post(url, data, injectTimeout(opts)),
132
+ put: (url, data, opts) => base.put(url, data, injectTimeout(opts)),
133
+ patch: (url, data, opts) => base.patch(url, data, injectTimeout(opts)),
134
+ delete: (url, opts) => base.delete(url, injectTimeout(opts)),
135
+ head: (url, opts) => base.head(url, injectTimeout(opts)),
136
+ options: (url, opts) => base.options(url, injectTimeout(opts)),
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Credentials needed to create a Feishu client.
142
+ * Both FeishuConfig and ResolvedFeishuAccount satisfy this interface.
143
+ */
144
+ export type FeishuClientCredentials = {
145
+ accountId?: string;
146
+ appId?: string;
147
+ appSecret?: string;
148
+ domain?: FeishuDomain;
149
+ httpTimeoutMs?: number;
150
+ config?: Pick<FeishuConfig, "httpTimeoutMs">;
151
+ };
152
+
153
+ /**
154
+ * Create or get a cached Feishu client for an account.
155
+ * Accepts any object with appId, appSecret, and optional domain/accountId.
156
+ */
157
+ export function createFeishuClient(creds: FeishuClientCredentials): Lark.Client {
158
+ const { accountId = "default", appId, appSecret, domain } = creds;
159
+ const defaultHttpTimeoutMs = resolveConfiguredHttpTimeoutMs(creds);
160
+
161
+ if (!appId || !appSecret) {
162
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
163
+ }
164
+
165
+ // Check cache
166
+ const cached = clientCache.get(accountId);
167
+ if (
168
+ cached &&
169
+ cached.config.appId === appId &&
170
+ cached.config.appSecret === appSecret &&
171
+ cached.config.domain === domain &&
172
+ cached.config.httpTimeoutMs === defaultHttpTimeoutMs
173
+ ) {
174
+ return cached.client;
175
+ }
176
+
177
+ // Create new client with timeout-aware HTTP instance
178
+ const client = new feishuClientSdk.Client({
179
+ appId,
180
+ appSecret,
181
+ appType: feishuClientSdk.AppType.SelfBuild,
182
+ domain: resolveDomain(domain),
183
+ httpInstance: createTimeoutHttpInstance(defaultHttpTimeoutMs),
184
+ });
185
+
186
+ // Cache it
187
+ clientCache.set(accountId, {
188
+ client,
189
+ config: { appId, appSecret, domain, httpTimeoutMs: defaultHttpTimeoutMs },
190
+ });
191
+
192
+ return client;
193
+ }
194
+
195
+ export type FeishuWsClientCallbacks = Pick<
196
+ ConstructorParameters<typeof feishuClientSdk.WSClient>[0],
197
+ "onError" | "onReady" | "onReconnected" | "onReconnecting"
198
+ >;
199
+
200
+ /**
201
+ * Create a Feishu WebSocket client for an account.
202
+ * Note: WSClient is not cached since each call creates a new connection.
203
+ */
204
+ export async function createFeishuWSClient(
205
+ account: ResolvedFeishuAccount,
206
+ callbacks: FeishuWsClientCallbacks = {},
207
+ ): Promise<Lark.WSClient> {
208
+ const { accountId, appId, appSecret, domain } = account;
209
+
210
+ if (!appId || !appSecret) {
211
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
212
+ }
213
+
214
+ const agent = await getWsProxyAgent();
215
+ return new feishuClientSdk.WSClient({
216
+ appId,
217
+ appSecret,
218
+ domain: resolveDomain(domain),
219
+ ...callbacks,
220
+ loggerLevel: feishuClientSdk.LoggerLevel.info,
221
+ wsConfig: FEISHU_WS_CONFIG,
222
+ ...(agent ? { agent } : {}),
223
+ } as ConstructorParameters<typeof feishuClientSdk.WSClient>[0] & {
224
+ wsConfig: typeof FEISHU_WS_CONFIG;
225
+ });
226
+ }
227
+
228
+ /**
229
+ * Create an event dispatcher for an account.
230
+ */
231
+ export function createEventDispatcher(account: ResolvedFeishuAccount): Lark.EventDispatcher {
232
+ return new feishuClientSdk.EventDispatcher({
233
+ encryptKey: account.encryptKey,
234
+ verificationToken: account.verificationToken,
235
+ });
236
+ }
237
+
238
+ /**
239
+ * Get a cached client for an account (if exists).
240
+ */
241
+ export function getFeishuClient(accountId: string): Lark.Client | null {
242
+ return clientCache.get(accountId)?.client ?? null;
243
+ }
244
+
245
+ /**
246
+ * Clear client cache for a specific account or all accounts.
247
+ */
248
+ export function clearClientCache(accountId?: string): void {
249
+ if (accountId) {
250
+ clientCache.delete(accountId);
251
+ } else {
252
+ clientCache.clear();
253
+ }
254
+ }
255
+
256
+ export function setFeishuClientRuntimeForTest(overrides?: {
257
+ sdk?: Partial<FeishuClientSdk>;
258
+ }): void {
259
+ feishuClientSdk = overrides?.sdk
260
+ ? { ...defaultFeishuClientSdk, ...overrides.sdk }
261
+ : defaultFeishuClientSdk;
262
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ createReplyPrefixContext,
3
+ type ClawdbotConfig,
4
+ type ReplyPayload,
5
+ type RuntimeEnv,
6
+ } from "../runtime-api.js";
@@ -0,0 +1,107 @@
1
+ import { resolveSendableOutboundReplyParts } from "autobot/plugin-sdk/reply-payload";
2
+ import { resolveFeishuRuntimeAccount } from "./accounts.js";
3
+ import { createFeishuClient } from "./client.js";
4
+ import {
5
+ createReplyPrefixContext,
6
+ type ClawdbotConfig,
7
+ type ReplyPayload,
8
+ type RuntimeEnv,
9
+ } from "./comment-dispatcher-runtime-api.js";
10
+ import { createCommentTypingReactionLifecycle } from "./comment-reaction.js";
11
+ import type { CommentFileType } from "./comment-target.js";
12
+ import { deliverCommentThreadText } from "./drive.js";
13
+ import { getFeishuRuntime } from "./runtime.js";
14
+
15
+ type CreateFeishuCommentReplyDispatcherParams = {
16
+ cfg: ClawdbotConfig;
17
+ agentId: string;
18
+ runtime: RuntimeEnv;
19
+ accountId?: string;
20
+ fileToken: string;
21
+ fileType: CommentFileType;
22
+ commentId: string;
23
+ replyId?: string;
24
+ isWholeComment?: boolean;
25
+ };
26
+
27
+ export function createFeishuCommentReplyDispatcher(
28
+ params: CreateFeishuCommentReplyDispatcherParams,
29
+ ) {
30
+ const core = getFeishuRuntime();
31
+ const prefixContext = createReplyPrefixContext({
32
+ cfg: params.cfg,
33
+ agentId: params.agentId,
34
+ channel: "feishu",
35
+ accountId: params.accountId,
36
+ });
37
+ const account = resolveFeishuRuntimeAccount({ cfg: params.cfg, accountId: params.accountId });
38
+ const client = createFeishuClient(account);
39
+ const textChunkLimit = core.channel.text.resolveTextChunkLimit(
40
+ params.cfg,
41
+ "feishu",
42
+ params.accountId,
43
+ {
44
+ fallbackLimit: 4000,
45
+ },
46
+ );
47
+ const chunkMode = core.channel.text.resolveChunkMode(params.cfg, "feishu");
48
+ const typingReaction = createCommentTypingReactionLifecycle({
49
+ cfg: params.cfg,
50
+ fileToken: params.fileToken,
51
+ fileType: params.fileType,
52
+ replyId: params.replyId,
53
+ accountId: params.accountId,
54
+ runtime: params.runtime,
55
+ });
56
+
57
+ const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } =
58
+ core.channel.reply.createReplyDispatcherWithTyping({
59
+ responsePrefix: prefixContext.responsePrefix,
60
+ responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
61
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(params.cfg, params.agentId),
62
+ onReplyStart: async () => {
63
+ await typingReaction.start();
64
+ },
65
+ deliver: async (payload: ReplyPayload, info) => {
66
+ if (info.kind !== "final") {
67
+ return;
68
+ }
69
+ const reply = resolveSendableOutboundReplyParts(payload);
70
+ if (!reply.hasText) {
71
+ if (reply.hasMedia) {
72
+ params.runtime.log?.(
73
+ `feishu[${params.accountId ?? "default"}]: comment reply ignored media-only payload for comment=${params.commentId}`,
74
+ );
75
+ }
76
+ return;
77
+ }
78
+ const chunks = core.channel.text.chunkTextWithMode(reply.text, textChunkLimit, chunkMode);
79
+ for (const chunk of chunks) {
80
+ await deliverCommentThreadText(client, {
81
+ file_token: params.fileToken,
82
+ file_type: params.fileType,
83
+ comment_id: params.commentId,
84
+ content: chunk,
85
+ is_whole_comment: params.isWholeComment,
86
+ });
87
+ }
88
+ },
89
+ onError: (err, info) => {
90
+ params.runtime.error?.(
91
+ `feishu[${params.accountId ?? "default"}]: comment dispatcher failed kind=${info.kind} comment=${params.commentId}: ${String(err)}`,
92
+ );
93
+ },
94
+ onCleanup: () => {
95
+ void typingReaction.cleanup();
96
+ },
97
+ });
98
+
99
+ return {
100
+ dispatcher,
101
+ replyOptions,
102
+ markDispatchIdle,
103
+ markRunComplete,
104
+ startTypingReaction: typingReaction.start,
105
+ cleanupTypingReaction: typingReaction.cleanup,
106
+ };
107
+ }
@@ -0,0 +1,3 @@
1
+ export type { AutoBotConfig as ClawdbotConfig } from "autobot/plugin-sdk/config-contracts";
2
+ export type { RuntimeEnv } from "autobot/plugin-sdk/runtime";
3
+ export { createChannelPairingController } from "autobot/plugin-sdk/channel-pairing";