@actagent/feishu 2026.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +11 -0
  2. package/actagent.plugin.json +224 -0
  3. package/api.ts +33 -0
  4. package/channel-entry.ts +21 -0
  5. package/channel-plugin-api.ts +2 -0
  6. package/contract-api.ts +17 -0
  7. package/index.ts +83 -0
  8. package/legacy-state-migrations-api.ts +2 -0
  9. package/npm-shrinkwrap.json +539 -0
  10. package/package.json +64 -0
  11. package/runtime-api.ts +58 -0
  12. package/runtime-setter-api.ts +3 -0
  13. package/secret-contract-api.ts +6 -0
  14. package/security-contract-api.ts +2 -0
  15. package/session-key-api.ts +2 -0
  16. package/setup-api.ts +4 -0
  17. package/setup-entry.test.ts +33 -0
  18. package/setup-entry.ts +25 -0
  19. package/skills/feishu-doc/SKILL.md +211 -0
  20. package/skills/feishu-doc/references/block-types.md +103 -0
  21. package/skills/feishu-drive/SKILL.md +97 -0
  22. package/skills/feishu-perm/SKILL.md +119 -0
  23. package/skills/feishu-wiki/SKILL.md +113 -0
  24. package/src/accounts.test.ts +481 -0
  25. package/src/accounts.ts +380 -0
  26. package/src/agent-config.ts +22 -0
  27. package/src/app-registration.test.ts +62 -0
  28. package/src/app-registration.ts +355 -0
  29. package/src/approval-auth.test.ts +25 -0
  30. package/src/approval-auth.ts +26 -0
  31. package/src/async.test.ts +68 -0
  32. package/src/async.ts +109 -0
  33. package/src/audio-preflight.runtime.ts +10 -0
  34. package/src/bitable.test.ts +174 -0
  35. package/src/bitable.ts +781 -0
  36. package/src/bot-content.ts +488 -0
  37. package/src/bot-group-name.test.ts +148 -0
  38. package/src/bot-runtime-api.ts +13 -0
  39. package/src/bot-sender-name.test.ts +68 -0
  40. package/src/bot-sender-name.ts +137 -0
  41. package/src/bot.broadcast.test.ts +643 -0
  42. package/src/bot.card-action.test.ts +647 -0
  43. package/src/bot.checkBotMentioned.test.ts +266 -0
  44. package/src/bot.helpers.test.ts +136 -0
  45. package/src/bot.stripBotMention.test.ts +127 -0
  46. package/src/bot.test.ts +3817 -0
  47. package/src/bot.ts +1788 -0
  48. package/src/card-action.ts +515 -0
  49. package/src/card-interaction.test.ts +132 -0
  50. package/src/card-interaction.ts +160 -0
  51. package/src/card-test-helpers.ts +55 -0
  52. package/src/card-ux-approval.ts +66 -0
  53. package/src/card-ux-launcher.test.ts +126 -0
  54. package/src/card-ux-launcher.ts +136 -0
  55. package/src/card-ux-shared.ts +34 -0
  56. package/src/channel-runtime-api.ts +17 -0
  57. package/src/channel.runtime.ts +48 -0
  58. package/src/channel.test.ts +1337 -0
  59. package/src/channel.ts +1401 -0
  60. package/src/chat-schema.ts +30 -0
  61. package/src/chat.test.ts +295 -0
  62. package/src/chat.ts +198 -0
  63. package/src/client-timeout.ts +44 -0
  64. package/src/client.test.ts +463 -0
  65. package/src/client.ts +263 -0
  66. package/src/comment-dispatcher-runtime-api.ts +7 -0
  67. package/src/comment-dispatcher.test.ts +186 -0
  68. package/src/comment-dispatcher.ts +108 -0
  69. package/src/comment-handler-runtime-api.ts +4 -0
  70. package/src/comment-handler.test.ts +588 -0
  71. package/src/comment-handler.ts +304 -0
  72. package/src/comment-reaction.test.ts +139 -0
  73. package/src/comment-reaction.ts +260 -0
  74. package/src/comment-shared.test.ts +184 -0
  75. package/src/comment-shared.ts +405 -0
  76. package/src/comment-target.ts +45 -0
  77. package/src/config-schema.test.ts +327 -0
  78. package/src/config-schema.ts +338 -0
  79. package/src/conversation-id.test.ts +19 -0
  80. package/src/conversation-id.ts +199 -0
  81. package/src/dedup-migrations.test.ts +90 -0
  82. package/src/dedup-migrations.ts +103 -0
  83. package/src/dedup.test.ts +95 -0
  84. package/src/dedup.ts +304 -0
  85. package/src/dedupe-key.ts +68 -0
  86. package/src/directory.static.ts +62 -0
  87. package/src/directory.test.ts +142 -0
  88. package/src/directory.ts +125 -0
  89. package/src/doc-schema.ts +183 -0
  90. package/src/doctor.test.ts +382 -0
  91. package/src/doctor.ts +876 -0
  92. package/src/docx-batch-insert.test.ts +117 -0
  93. package/src/docx-batch-insert.ts +223 -0
  94. package/src/docx-color-text.ts +154 -0
  95. package/src/docx-table-ops.test.ts +54 -0
  96. package/src/docx-table-ops.ts +316 -0
  97. package/src/docx-types.ts +39 -0
  98. package/src/docx.account-selection.test.ts +96 -0
  99. package/src/docx.test.ts +706 -0
  100. package/src/docx.ts +1598 -0
  101. package/src/drive-schema.ts +93 -0
  102. package/src/drive.test.ts +1240 -0
  103. package/src/drive.ts +830 -0
  104. package/src/dynamic-agent.test.ts +156 -0
  105. package/src/dynamic-agent.ts +144 -0
  106. package/src/event-types.ts +46 -0
  107. package/src/external-keys.test.ts +21 -0
  108. package/src/external-keys.ts +20 -0
  109. package/src/lifecycle.test-support.ts +223 -0
  110. package/src/media.test.ts +956 -0
  111. package/src/media.ts +1106 -0
  112. package/src/mention-target.types.ts +6 -0
  113. package/src/mention.ts +115 -0
  114. package/src/message-action-contract.ts +14 -0
  115. package/src/monitor-state-runtime-api.ts +8 -0
  116. package/src/monitor-transport-runtime-api.ts +11 -0
  117. package/src/monitor.account.ts +501 -0
  118. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +215 -0
  119. package/src/monitor.bot-identity.ts +87 -0
  120. package/src/monitor.bot-menu-handler.ts +164 -0
  121. package/src/monitor.bot-menu.lifecycle.test-support.ts +221 -0
  122. package/src/monitor.bot-menu.test.ts +200 -0
  123. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +265 -0
  124. package/src/monitor.card-action.lifecycle.test-support.ts +418 -0
  125. package/src/monitor.cleanup.test.ts +384 -0
  126. package/src/monitor.comment-notice-handler.ts +106 -0
  127. package/src/monitor.comment.test.ts +968 -0
  128. package/src/monitor.comment.ts +1386 -0
  129. package/src/monitor.lifecycle.test.ts +5 -0
  130. package/src/monitor.message-handler.ts +346 -0
  131. package/src/monitor.reaction.test.ts +770 -0
  132. package/src/monitor.startup.test.ts +232 -0
  133. package/src/monitor.startup.ts +76 -0
  134. package/src/monitor.state.defaults.test.ts +47 -0
  135. package/src/monitor.state.ts +171 -0
  136. package/src/monitor.synthetic-error.ts +19 -0
  137. package/src/monitor.test-mocks.ts +47 -0
  138. package/src/monitor.transport.ts +451 -0
  139. package/src/monitor.ts +104 -0
  140. package/src/monitor.webhook-e2e.test.ts +284 -0
  141. package/src/monitor.webhook-security.test.ts +394 -0
  142. package/src/monitor.webhook.test-helpers.ts +138 -0
  143. package/src/outbound-runtime-api.ts +2 -0
  144. package/src/outbound.test.ts +1255 -0
  145. package/src/outbound.ts +742 -0
  146. package/src/perm-schema.ts +53 -0
  147. package/src/perm.ts +171 -0
  148. package/src/pins.ts +109 -0
  149. package/src/policy.test.ts +224 -0
  150. package/src/policy.ts +322 -0
  151. package/src/post.test.ts +106 -0
  152. package/src/post.ts +276 -0
  153. package/src/presentation-card.ts +204 -0
  154. package/src/probe.test.ts +310 -0
  155. package/src/probe.ts +181 -0
  156. package/src/processing-claims.ts +60 -0
  157. package/src/qr-terminal.ts +2 -0
  158. package/src/reactions.ts +124 -0
  159. package/src/reasoning-preview.test.ts +114 -0
  160. package/src/reasoning-preview.ts +29 -0
  161. package/src/reply-dispatcher-runtime-api.ts +8 -0
  162. package/src/reply-dispatcher.test.ts +2009 -0
  163. package/src/reply-dispatcher.ts +865 -0
  164. package/src/runtime.ts +10 -0
  165. package/src/secret-contract.ts +146 -0
  166. package/src/secret-input.ts +2 -0
  167. package/src/security-audit-shared.ts +70 -0
  168. package/src/security-audit.test.ts +60 -0
  169. package/src/security-audit.ts +2 -0
  170. package/src/send-result.ts +81 -0
  171. package/src/send-target.test.ts +87 -0
  172. package/src/send-target.ts +36 -0
  173. package/src/send.reply-fallback.test.ts +418 -0
  174. package/src/send.test.ts +661 -0
  175. package/src/send.ts +860 -0
  176. package/src/sequential-key.test.ts +73 -0
  177. package/src/sequential-key.ts +29 -0
  178. package/src/sequential-queue.test.ts +184 -0
  179. package/src/sequential-queue.ts +90 -0
  180. package/src/session-conversation.ts +42 -0
  181. package/src/session-route.ts +49 -0
  182. package/src/setup-core.ts +52 -0
  183. package/src/setup-surface.test.ts +485 -0
  184. package/src/setup-surface.ts +620 -0
  185. package/src/streaming-card.test.ts +549 -0
  186. package/src/streaming-card.ts +611 -0
  187. package/src/subagent-hooks.test.ts +632 -0
  188. package/src/subagent-hooks.ts +414 -0
  189. package/src/targets.ts +98 -0
  190. package/src/test-support/lifecycle-test-support.ts +459 -0
  191. package/src/thread-bindings.test.ts +181 -0
  192. package/src/thread-bindings.ts +332 -0
  193. package/src/tool-account-routing.test.ts +419 -0
  194. package/src/tool-account.test.ts +45 -0
  195. package/src/tool-account.ts +98 -0
  196. package/src/tool-factory-test-harness.ts +83 -0
  197. package/src/tool-result.test.ts +33 -0
  198. package/src/tool-result.ts +17 -0
  199. package/src/tools-config.test.ts +52 -0
  200. package/src/tools-config.ts +29 -0
  201. package/src/types.ts +111 -0
  202. package/src/typing.test.ts +145 -0
  203. package/src/typing.ts +215 -0
  204. package/src/wiki-schema.ts +70 -0
  205. package/src/wiki.ts +271 -0
  206. package/subagent-hooks-api.ts +22 -0
  207. package/tsconfig.json +16 -0
package/src/client.ts ADDED
@@ -0,0 +1,263 @@
1
+ // Feishu plugin module implements client behavior.
2
+ import type { Agent } from "node:https";
3
+ import { createRequire } from "node:module";
4
+ import * as Lark from "@larksuiteoapi/node-sdk";
5
+ import {
6
+ readPluginPackageVersion,
7
+ resolveAmbientNodeProxyAgent,
8
+ } from "actagent/plugin-sdk/extension-shared";
9
+ import {
10
+ FEISHU_HTTP_TIMEOUT_ENV_VAR,
11
+ FEISHU_HTTP_TIMEOUT_MAX_MS,
12
+ FEISHU_HTTP_TIMEOUT_MS,
13
+ resolveConfiguredHttpTimeoutMs,
14
+ } from "./client-timeout.js";
15
+ import type { FeishuConfig, FeishuDomain, ResolvedFeishuAccount } from "./types.js";
16
+
17
+ const require = createRequire(import.meta.url);
18
+ const pluginVersion = readPluginPackageVersion({ require });
19
+
20
+ export { pluginVersion };
21
+
22
+ const FEISHU_USER_AGENT = `actagent-feishu-builtin/${pluginVersion}/${process.platform}`;
23
+ export { FEISHU_USER_AGENT };
24
+
25
+ const FEISHU_WS_CONFIG = {
26
+ PingInterval: 30,
27
+ PingTimeout: 3,
28
+ } as const;
29
+
30
+ /** User-Agent header value for all Feishu API requests. */
31
+ export function getFeishuUserAgent(): string {
32
+ return FEISHU_USER_AGENT;
33
+ }
34
+
35
+ type FeishuClientSdk = Pick<
36
+ typeof Lark,
37
+ | "AppType"
38
+ | "Client"
39
+ | "defaultHttpInstance"
40
+ | "Domain"
41
+ | "EventDispatcher"
42
+ | "LoggerLevel"
43
+ | "WSClient"
44
+ >;
45
+
46
+ const defaultFeishuClientSdk: FeishuClientSdk = {
47
+ AppType: Lark.AppType,
48
+ Client: Lark.Client,
49
+ defaultHttpInstance: Lark.defaultHttpInstance,
50
+ Domain: Lark.Domain,
51
+ EventDispatcher: Lark.EventDispatcher,
52
+ LoggerLevel: Lark.LoggerLevel,
53
+ WSClient: Lark.WSClient,
54
+ };
55
+
56
+ let feishuClientSdk: FeishuClientSdk = defaultFeishuClientSdk;
57
+
58
+ // Override the SDK's default User-Agent interceptor.
59
+ // The Lark SDK registers an axios request interceptor that sets
60
+ // 'oapi-node-sdk/1.0.0'. Axios request interceptors execute in LIFO order
61
+ // (last-registered runs first), so simply appending ours doesn't work — the
62
+ // SDK's interceptor would run last and overwrite our UA. We must clear
63
+ // handlers[] first, then register our own as the sole interceptor.
64
+ //
65
+ // Risk is low: the SDK only registers one interceptor (UA) at init time, and
66
+ // we clear it at module load before any other code can register handlers.
67
+ // If a future SDK version adds more interceptors, the upgrade will need
68
+ // compatibility verification regardless.
69
+ {
70
+ const inst = Lark.defaultHttpInstance as {
71
+ interceptors?: {
72
+ request: { handlers: unknown[]; use: (fn: (req: unknown) => unknown) => void };
73
+ };
74
+ };
75
+ if (inst.interceptors?.request) {
76
+ inst.interceptors.request.handlers = [];
77
+ inst.interceptors.request.use((req: unknown) => {
78
+ const r = req as { headers?: Record<string, string> };
79
+ if (r.headers) {
80
+ r.headers["User-Agent"] = getFeishuUserAgent();
81
+ }
82
+ return req;
83
+ });
84
+ }
85
+ }
86
+
87
+ export { FEISHU_HTTP_TIMEOUT_ENV_VAR, FEISHU_HTTP_TIMEOUT_MAX_MS, FEISHU_HTTP_TIMEOUT_MS };
88
+
89
+ type FeishuHttpInstanceLike = Pick<
90
+ typeof feishuClientSdk.defaultHttpInstance,
91
+ "request" | "get" | "post" | "put" | "patch" | "delete" | "head" | "options"
92
+ >;
93
+
94
+ async function getWsProxyAgent() {
95
+ return resolveAmbientNodeProxyAgent<Agent>();
96
+ }
97
+
98
+ // Multi-account client cache
99
+ const clientCache = new Map<
100
+ string,
101
+ {
102
+ client: Lark.Client;
103
+ config: { appId: string; appSecret: string; domain?: FeishuDomain; httpTimeoutMs: number };
104
+ }
105
+ >();
106
+
107
+ function resolveDomain(domain: FeishuDomain | undefined): Lark.Domain | string {
108
+ if (domain === "lark") {
109
+ return feishuClientSdk.Domain.Lark;
110
+ }
111
+ if (domain === "feishu" || !domain) {
112
+ return feishuClientSdk.Domain.Feishu;
113
+ }
114
+ return domain.replace(/\/+$/, ""); // Custom URL for private deployment
115
+ }
116
+
117
+ /**
118
+ * Create an HTTP instance that delegates to the Lark SDK's default instance
119
+ * but injects a default request timeout and User-Agent header to prevent
120
+ * indefinite hangs and set a standardized User-Agent per OAPI best practices.
121
+ */
122
+ function createTimeoutHttpInstance(defaultTimeoutMs: number): Lark.HttpInstance {
123
+ const base: FeishuHttpInstanceLike = feishuClientSdk.defaultHttpInstance;
124
+
125
+ function injectTimeout<D>(opts?: Lark.HttpRequestOptions<D>): Lark.HttpRequestOptions<D> {
126
+ return { timeout: defaultTimeoutMs, ...opts } as Lark.HttpRequestOptions<D>;
127
+ }
128
+
129
+ return {
130
+ request: (opts) => base.request(injectTimeout(opts)),
131
+ get: (url, opts) => base.get(url, injectTimeout(opts)),
132
+ post: (url, data, opts) => base.post(url, data, injectTimeout(opts)),
133
+ put: (url, data, opts) => base.put(url, data, injectTimeout(opts)),
134
+ patch: (url, data, opts) => base.patch(url, data, injectTimeout(opts)),
135
+ delete: (url, opts) => base.delete(url, injectTimeout(opts)),
136
+ head: (url, opts) => base.head(url, injectTimeout(opts)),
137
+ options: (url, opts) => base.options(url, injectTimeout(opts)),
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Credentials needed to create a Feishu client.
143
+ * Both FeishuConfig and ResolvedFeishuAccount satisfy this interface.
144
+ */
145
+ export type FeishuClientCredentials = {
146
+ accountId?: string;
147
+ appId?: string;
148
+ appSecret?: string;
149
+ domain?: FeishuDomain;
150
+ httpTimeoutMs?: number;
151
+ config?: Pick<FeishuConfig, "httpTimeoutMs">;
152
+ };
153
+
154
+ /**
155
+ * Create or get a cached Feishu client for an account.
156
+ * Accepts any object with appId, appSecret, and optional domain/accountId.
157
+ */
158
+ export function createFeishuClient(creds: FeishuClientCredentials): Lark.Client {
159
+ const { accountId = "default", appId, appSecret, domain } = creds;
160
+ const defaultHttpTimeoutMs = resolveConfiguredHttpTimeoutMs(creds);
161
+
162
+ if (!appId || !appSecret) {
163
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
164
+ }
165
+
166
+ // Check cache
167
+ const cached = clientCache.get(accountId);
168
+ if (
169
+ cached &&
170
+ cached.config.appId === appId &&
171
+ cached.config.appSecret === appSecret &&
172
+ cached.config.domain === domain &&
173
+ cached.config.httpTimeoutMs === defaultHttpTimeoutMs
174
+ ) {
175
+ return cached.client;
176
+ }
177
+
178
+ // Create new client with timeout-aware HTTP instance
179
+ const client = new feishuClientSdk.Client({
180
+ appId,
181
+ appSecret,
182
+ appType: feishuClientSdk.AppType.SelfBuild,
183
+ domain: resolveDomain(domain),
184
+ httpInstance: createTimeoutHttpInstance(defaultHttpTimeoutMs),
185
+ });
186
+
187
+ // Cache it
188
+ clientCache.set(accountId, {
189
+ client,
190
+ config: { appId, appSecret, domain, httpTimeoutMs: defaultHttpTimeoutMs },
191
+ });
192
+
193
+ return client;
194
+ }
195
+
196
+ export type FeishuWsClientCallbacks = Pick<
197
+ ConstructorParameters<typeof feishuClientSdk.WSClient>[0],
198
+ "onError" | "onReady" | "onReconnected" | "onReconnecting"
199
+ >;
200
+
201
+ /**
202
+ * Create a Feishu WebSocket client for an account.
203
+ * Note: WSClient is not cached since each call creates a new connection.
204
+ */
205
+ export async function createFeishuWSClient(
206
+ account: ResolvedFeishuAccount,
207
+ callbacks: FeishuWsClientCallbacks = {},
208
+ ): Promise<Lark.WSClient> {
209
+ const { accountId, appId, appSecret, domain } = account;
210
+
211
+ if (!appId || !appSecret) {
212
+ throw new Error(`Feishu credentials not configured for account "${accountId}"`);
213
+ }
214
+
215
+ const agent = await getWsProxyAgent();
216
+ return new feishuClientSdk.WSClient({
217
+ appId,
218
+ appSecret,
219
+ domain: resolveDomain(domain),
220
+ ...callbacks,
221
+ loggerLevel: feishuClientSdk.LoggerLevel.info,
222
+ wsConfig: FEISHU_WS_CONFIG,
223
+ ...(agent ? { agent } : {}),
224
+ } as ConstructorParameters<typeof feishuClientSdk.WSClient>[0] & {
225
+ wsConfig: typeof FEISHU_WS_CONFIG;
226
+ });
227
+ }
228
+
229
+ /**
230
+ * Create an event dispatcher for an account.
231
+ */
232
+ export function createEventDispatcher(account: ResolvedFeishuAccount): Lark.EventDispatcher {
233
+ return new feishuClientSdk.EventDispatcher({
234
+ encryptKey: account.encryptKey,
235
+ verificationToken: account.verificationToken,
236
+ });
237
+ }
238
+
239
+ /**
240
+ * Get a cached client for an account (if exists).
241
+ */
242
+ export function getFeishuClient(accountId: string): Lark.Client | null {
243
+ return clientCache.get(accountId)?.client ?? null;
244
+ }
245
+
246
+ /**
247
+ * Clear client cache for a specific account or all accounts.
248
+ */
249
+ export function clearClientCache(accountId?: string): void {
250
+ if (accountId) {
251
+ clientCache.delete(accountId);
252
+ } else {
253
+ clientCache.clear();
254
+ }
255
+ }
256
+
257
+ export function setFeishuClientRuntimeForTest(overrides?: {
258
+ sdk?: Partial<FeishuClientSdk>;
259
+ }): void {
260
+ feishuClientSdk = overrides?.sdk
261
+ ? { ...defaultFeishuClientSdk, ...overrides.sdk }
262
+ : defaultFeishuClientSdk;
263
+ }
@@ -0,0 +1,7 @@
1
+ // Feishu API module exposes the plugin public contract.
2
+ export {
3
+ createReplyPrefixContext,
4
+ type ACTAgentBotConfig,
5
+ type ReplyPayload,
6
+ type RuntimeEnv,
7
+ } from "../runtime-api.js";
@@ -0,0 +1,186 @@
1
+ // Feishu tests cover comment dispatcher plugin behavior.
2
+ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
3
+
4
+ const resolveFeishuRuntimeAccountMock = vi.hoisted(() => vi.fn());
5
+ const createFeishuClientMock = vi.hoisted(() => vi.fn());
6
+ const createReplyPrefixContextMock = vi.hoisted(() => vi.fn());
7
+ const createCommentTypingReactionLifecycleMock = vi.hoisted(() => vi.fn());
8
+ const deliverCommentThreadTextMock = vi.hoisted(() => vi.fn());
9
+ const createReplyDispatcherWithTypingMock = vi.hoisted(() => vi.fn());
10
+ const getFeishuRuntimeMock = vi.hoisted(() => vi.fn());
11
+
12
+ vi.mock("./accounts.js", () => ({
13
+ resolveFeishuRuntimeAccount: resolveFeishuRuntimeAccountMock,
14
+ }));
15
+
16
+ vi.mock("./client.js", () => ({
17
+ createFeishuClient: createFeishuClientMock,
18
+ }));
19
+
20
+ vi.mock("./comment-dispatcher-runtime-api.js", () => ({
21
+ createReplyPrefixContext: createReplyPrefixContextMock,
22
+ }));
23
+
24
+ vi.mock("./comment-reaction.js", () => ({
25
+ createCommentTypingReactionLifecycle: createCommentTypingReactionLifecycleMock,
26
+ }));
27
+
28
+ vi.mock("./drive.js", () => ({
29
+ deliverCommentThreadText: deliverCommentThreadTextMock,
30
+ }));
31
+
32
+ vi.mock("./runtime.js", () => ({
33
+ getFeishuRuntime: getFeishuRuntimeMock,
34
+ }));
35
+
36
+ import { createFeishuCommentReplyDispatcher } from "./comment-dispatcher.js";
37
+
38
+ async function raceWithNextMacrotask<T>(promise: Promise<T>): Promise<T | "pending"> {
39
+ return await Promise.race([
40
+ promise,
41
+ new Promise<"pending">((resolve) => {
42
+ setImmediate(() => resolve("pending"));
43
+ }),
44
+ ]);
45
+ }
46
+
47
+ describe("createFeishuCommentReplyDispatcher", () => {
48
+ afterAll(() => {
49
+ vi.doUnmock("./accounts.js");
50
+ vi.doUnmock("./client.js");
51
+ vi.doUnmock("./comment-dispatcher-runtime-api.js");
52
+ vi.doUnmock("./comment-reaction.js");
53
+ vi.doUnmock("./drive.js");
54
+ vi.doUnmock("./runtime.js");
55
+ vi.resetModules();
56
+ });
57
+
58
+ function createTestCommentReplyDispatcher() {
59
+ createFeishuCommentReplyDispatcher({
60
+ cfg: {} as never,
61
+ agentId: "main",
62
+ runtime: { log: vi.fn(), error: vi.fn() } as never,
63
+ accountId: "main",
64
+ fileToken: "doc_token_1",
65
+ fileType: "docx",
66
+ commentId: "comment_1",
67
+ replyId: "reply_1",
68
+ isWholeComment: false,
69
+ });
70
+ }
71
+
72
+ function latestReplyDispatcherOptions() {
73
+ const options = createReplyDispatcherWithTypingMock.mock.calls.at(-1)?.[0];
74
+ if (!options) {
75
+ throw new Error("expected reply dispatcher options");
76
+ }
77
+ return options as {
78
+ deliver: (payload: { text: string }, phase: { kind: string }) => Promise<void> | void;
79
+ onCleanup?: () => Promise<void> | void;
80
+ onReplyStart?: () => Promise<void> | void;
81
+ };
82
+ }
83
+
84
+ beforeEach(() => {
85
+ vi.clearAllMocks();
86
+ resolveFeishuRuntimeAccountMock.mockReturnValue({
87
+ accountId: "main",
88
+ appId: "app_id",
89
+ appSecret: "app_secret",
90
+ domain: "feishu",
91
+ config: {},
92
+ });
93
+ createFeishuClientMock.mockReturnValue({});
94
+ createReplyPrefixContextMock.mockReturnValue({
95
+ responsePrefix: undefined,
96
+ responsePrefixContextProvider: undefined,
97
+ });
98
+ deliverCommentThreadTextMock.mockResolvedValue({
99
+ delivery_mode: "reply_comment",
100
+ reply_id: "reply_1",
101
+ });
102
+ createCommentTypingReactionLifecycleMock.mockReturnValue({
103
+ start: vi.fn(async () => {}),
104
+ cleanup: vi.fn(async () => {}),
105
+ });
106
+ createReplyDispatcherWithTypingMock.mockImplementation(() => ({
107
+ dispatcher: {
108
+ markComplete: vi.fn(),
109
+ waitForIdle: vi.fn(async () => {}),
110
+ },
111
+ replyOptions: {},
112
+ markDispatchIdle: vi.fn(),
113
+ markRunComplete: vi.fn(),
114
+ }));
115
+ getFeishuRuntimeMock.mockReturnValue({
116
+ channel: {
117
+ text: {
118
+ resolveTextChunkLimit: vi.fn(() => 4000),
119
+ resolveChunkMode: vi.fn(() => "line"),
120
+ chunkTextWithMode: vi.fn((text: string) => [text]),
121
+ },
122
+ reply: {
123
+ createReplyDispatcherWithTyping: createReplyDispatcherWithTypingMock,
124
+ resolveHumanDelayConfig: vi.fn(() => undefined),
125
+ },
126
+ },
127
+ });
128
+ });
129
+
130
+ it("sends final comment text without waiting for typing cleanup", async () => {
131
+ let resolveCleanup: (() => void) | undefined;
132
+ const cleanup = vi.fn(
133
+ () =>
134
+ new Promise<void>((resolve) => {
135
+ resolveCleanup = resolve;
136
+ }),
137
+ );
138
+ createCommentTypingReactionLifecycleMock.mockReturnValue({
139
+ start: vi.fn(async () => {}),
140
+ cleanup,
141
+ });
142
+
143
+ createTestCommentReplyDispatcher();
144
+
145
+ const options = latestReplyDispatcherOptions();
146
+ const deliverPromise = Promise.resolve(
147
+ options.deliver({ text: "hello world" }, { kind: "final" }),
148
+ );
149
+ const status = await raceWithNextMacrotask(deliverPromise.then(() => "done"));
150
+
151
+ expect(status).toBe("done");
152
+ const client = createFeishuClientMock.mock.results[0]?.value;
153
+ if (!client) {
154
+ throw new Error("Expected Feishu client");
155
+ }
156
+ expect(deliverCommentThreadTextMock).toHaveBeenCalledWith(client, {
157
+ file_token: "doc_token_1",
158
+ file_type: "docx",
159
+ comment_id: "comment_1",
160
+ content: "hello world",
161
+ is_whole_comment: false,
162
+ });
163
+ expect(cleanup).not.toHaveBeenCalled();
164
+
165
+ void options.onCleanup?.();
166
+ expect(cleanup).toHaveBeenCalledTimes(1);
167
+
168
+ resolveCleanup?.();
169
+ await deliverPromise;
170
+ });
171
+
172
+ it("starts the typing reaction from dispatcher onReplyStart", async () => {
173
+ const start = vi.fn(async () => {});
174
+ createCommentTypingReactionLifecycleMock.mockReturnValue({
175
+ start,
176
+ cleanup: vi.fn(async () => {}),
177
+ });
178
+
179
+ createTestCommentReplyDispatcher();
180
+
181
+ const options = latestReplyDispatcherOptions();
182
+ await options.onReplyStart?.();
183
+
184
+ expect(start).toHaveBeenCalledTimes(1);
185
+ });
186
+ });
@@ -0,0 +1,108 @@
1
+ // Feishu plugin module implements comment dispatcher behavior.
2
+ import { resolveSendableOutboundReplyParts } from "actagent/plugin-sdk/reply-payload";
3
+ import { resolveFeishuRuntimeAccount } from "./accounts.js";
4
+ import { createFeishuClient } from "./client.js";
5
+ import {
6
+ createReplyPrefixContext,
7
+ type ACTAgentBotConfig,
8
+ type ReplyPayload,
9
+ type RuntimeEnv,
10
+ } from "./comment-dispatcher-runtime-api.js";
11
+ import { createCommentTypingReactionLifecycle } from "./comment-reaction.js";
12
+ import type { CommentFileType } from "./comment-target.js";
13
+ import { deliverCommentThreadText } from "./drive.js";
14
+ import { getFeishuRuntime } from "./runtime.js";
15
+
16
+ type CreateFeishuCommentReplyDispatcherParams = {
17
+ cfg: ACTAgentBotConfig;
18
+ agentId: string;
19
+ runtime: RuntimeEnv;
20
+ accountId?: string;
21
+ fileToken: string;
22
+ fileType: CommentFileType;
23
+ commentId: string;
24
+ replyId?: string;
25
+ isWholeComment?: boolean;
26
+ };
27
+
28
+ export function createFeishuCommentReplyDispatcher(
29
+ params: CreateFeishuCommentReplyDispatcherParams,
30
+ ) {
31
+ const core = getFeishuRuntime();
32
+ const prefixContext = createReplyPrefixContext({
33
+ cfg: params.cfg,
34
+ agentId: params.agentId,
35
+ channel: "feishu",
36
+ accountId: params.accountId,
37
+ });
38
+ const account = resolveFeishuRuntimeAccount({ cfg: params.cfg, accountId: params.accountId });
39
+ const client = createFeishuClient(account);
40
+ const textChunkLimit = core.channel.text.resolveTextChunkLimit(
41
+ params.cfg,
42
+ "feishu",
43
+ params.accountId,
44
+ {
45
+ fallbackLimit: 4000,
46
+ },
47
+ );
48
+ const chunkMode = core.channel.text.resolveChunkMode(params.cfg, "feishu");
49
+ const typingReaction = createCommentTypingReactionLifecycle({
50
+ cfg: params.cfg,
51
+ fileToken: params.fileToken,
52
+ fileType: params.fileType,
53
+ replyId: params.replyId,
54
+ accountId: params.accountId,
55
+ runtime: params.runtime,
56
+ });
57
+
58
+ const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } =
59
+ core.channel.reply.createReplyDispatcherWithTyping({
60
+ responsePrefix: prefixContext.responsePrefix,
61
+ responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
62
+ humanDelay: core.channel.reply.resolveHumanDelayConfig(params.cfg, params.agentId),
63
+ onReplyStart: async () => {
64
+ await typingReaction.start();
65
+ },
66
+ deliver: async (payload: ReplyPayload, info) => {
67
+ if (info.kind !== "final") {
68
+ return;
69
+ }
70
+ const reply = resolveSendableOutboundReplyParts(payload);
71
+ if (!reply.hasText) {
72
+ if (reply.hasMedia) {
73
+ params.runtime.log?.(
74
+ `feishu[${params.accountId ?? "default"}]: comment reply ignored media-only payload for comment=${params.commentId}`,
75
+ );
76
+ }
77
+ return;
78
+ }
79
+ const chunks = core.channel.text.chunkTextWithMode(reply.text, textChunkLimit, chunkMode);
80
+ for (const chunk of chunks) {
81
+ await deliverCommentThreadText(client, {
82
+ file_token: params.fileToken,
83
+ file_type: params.fileType,
84
+ comment_id: params.commentId,
85
+ content: chunk,
86
+ is_whole_comment: params.isWholeComment,
87
+ });
88
+ }
89
+ },
90
+ onError: (err, info) => {
91
+ params.runtime.error?.(
92
+ `feishu[${params.accountId ?? "default"}]: comment dispatcher failed kind=${info.kind} comment=${params.commentId}: ${String(err)}`,
93
+ );
94
+ },
95
+ onCleanup: () => {
96
+ void typingReaction.cleanup();
97
+ },
98
+ });
99
+
100
+ return {
101
+ dispatcher,
102
+ replyOptions,
103
+ markDispatchIdle,
104
+ markRunComplete,
105
+ startTypingReaction: typingReaction.start,
106
+ cleanupTypingReaction: typingReaction.cleanup,
107
+ };
108
+ }
@@ -0,0 +1,4 @@
1
+ // Feishu API module exposes the plugin public contract.
2
+ export type { ACTAgentConfig as ACTAgentBotConfig } from "actagent/plugin-sdk/config-contracts";
3
+ export type { RuntimeEnv } from "actagent/plugin-sdk/runtime";
4
+ export { createChannelPairingController } from "actagent/plugin-sdk/channel-pairing";