@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
@@ -0,0 +1,52 @@
1
+ // Feishu tests cover tools config plugin behavior.
2
+ import { describe, expect, it } from "vitest";
3
+ import { FeishuConfigSchema } from "./config-schema.js";
4
+ import { resolveToolsConfig } from "./tools-config.js";
5
+
6
+ describe("feishu tools config", () => {
7
+ it("enables chat tool by default", () => {
8
+ const resolved = resolveToolsConfig(undefined);
9
+ expect(resolved.chat).toBe(true);
10
+ });
11
+
12
+ it("accepts tools.chat in config schema", () => {
13
+ const parsed = FeishuConfigSchema.parse({
14
+ enabled: true,
15
+ tools: {
16
+ chat: false,
17
+ },
18
+ });
19
+
20
+ expect(parsed.tools?.chat).toBe(false);
21
+ });
22
+
23
+ it("enables bitable tool by default", () => {
24
+ const resolved = resolveToolsConfig(undefined);
25
+ expect(resolved.bitable).toBe(true);
26
+ expect(resolved.base).toBe(true);
27
+ });
28
+
29
+ it("accepts tools.bitable and tools.base in config schema", () => {
30
+ const parsed = FeishuConfigSchema.parse({
31
+ enabled: true,
32
+ tools: {
33
+ bitable: false,
34
+ base: false,
35
+ },
36
+ });
37
+
38
+ expect(parsed.tools?.bitable).toBe(false);
39
+ expect(parsed.tools?.base).toBe(false);
40
+ });
41
+
42
+ it("uses base as a backward-compatible bitable alias", () => {
43
+ expect(resolveToolsConfig({ base: false }).bitable).toBe(false);
44
+ expect(resolveToolsConfig({ base: false }).base).toBe(false);
45
+ });
46
+
47
+ it("prefers explicit bitable over base alias", () => {
48
+ const resolved = resolveToolsConfig({ bitable: true, base: false });
49
+ expect(resolved.bitable).toBe(true);
50
+ expect(resolved.base).toBe(true);
51
+ });
52
+ });
@@ -0,0 +1,29 @@
1
+ // Feishu helper module supports tools config behavior.
2
+ import type { FeishuToolsConfig } from "./types.js";
3
+
4
+ /**
5
+ * Default tool configuration.
6
+ * - doc, chat, wiki, drive, scopes, bitable/base: enabled by default
7
+ * - perm: disabled by default (sensitive operation)
8
+ */
9
+ const DEFAULT_TOOLS_CONFIG: Required<FeishuToolsConfig> = {
10
+ doc: true,
11
+ chat: true,
12
+ wiki: true,
13
+ drive: true,
14
+ perm: false,
15
+ scopes: true,
16
+ bitable: true,
17
+ base: true,
18
+ };
19
+
20
+ /**
21
+ * Resolve tools config with defaults.
22
+ *
23
+ * `base` is a backward-compatible alias for the Bitable tool family. When both
24
+ * keys are present, the explicit `bitable` value wins and `base` mirrors it.
25
+ */
26
+ export function resolveToolsConfig(cfg?: FeishuToolsConfig): Required<FeishuToolsConfig> {
27
+ const bitable = cfg?.bitable ?? cfg?.base ?? DEFAULT_TOOLS_CONFIG.bitable;
28
+ return { ...DEFAULT_TOOLS_CONFIG, ...cfg, bitable, base: bitable };
29
+ }
package/src/types.ts ADDED
@@ -0,0 +1,111 @@
1
+ // Feishu type declarations define plugin contracts.
2
+ import type { MessageReceipt } from "actagent/plugin-sdk/channel-outbound";
3
+ import type { BaseProbeResult } from "actagent/plugin-sdk/core";
4
+ import type { FeishuConfigSchema, FeishuAccountConfigSchema, z } from "./config-schema.js";
5
+ import type { MentionTarget } from "./mention-target.types.js";
6
+
7
+ export type FeishuConfig = z.infer<typeof FeishuConfigSchema>;
8
+ export type FeishuAccountConfig = z.infer<typeof FeishuAccountConfigSchema>;
9
+
10
+ export type FeishuDomain = "feishu" | "lark" | (string & {});
11
+
12
+ export type FeishuDefaultAccountSelectionSource =
13
+ | "explicit-default"
14
+ | "mapped-default"
15
+ | "fallback";
16
+ type FeishuAccountSelectionSource = "explicit" | FeishuDefaultAccountSelectionSource;
17
+
18
+ export type ResolvedFeishuAccount = {
19
+ accountId: string;
20
+ selectionSource: FeishuAccountSelectionSource;
21
+ enabled: boolean;
22
+ configured: boolean;
23
+ name?: string;
24
+ appId?: string;
25
+ appSecret?: string;
26
+ encryptKey?: string;
27
+ verificationToken?: string;
28
+ domain: FeishuDomain;
29
+ /** Merged config (top-level defaults + account-specific overrides) */
30
+ config: FeishuConfig;
31
+ };
32
+
33
+ export type FeishuIdType = "open_id" | "user_id" | "union_id" | "chat_id";
34
+
35
+ export type FeishuMessageContext = {
36
+ chatId: string;
37
+ messageId: string;
38
+ replyTargetMessageId?: string;
39
+ suppressReplyTarget?: boolean;
40
+ senderId: string;
41
+ senderOpenId: string;
42
+ senderName?: string;
43
+ chatType: FeishuChatType;
44
+ mentionedBot: boolean;
45
+ hasAnyMention?: boolean;
46
+ rootId?: string;
47
+ parentId?: string;
48
+ threadId?: string;
49
+ content: string;
50
+ contentType: string;
51
+ /** Mention forward targets (excluding the bot itself) */
52
+ mentionTargets?: MentionTarget[];
53
+ };
54
+
55
+ export type FeishuSendResult = {
56
+ messageId: string;
57
+ chatId: string;
58
+ receipt: MessageReceipt;
59
+ };
60
+
61
+ export type FeishuChatType = "p2p" | "group" | "topic_group" | "private";
62
+
63
+ export function isFeishuGroupChatType(chatType: FeishuChatType | undefined): boolean {
64
+ return chatType === "group" || chatType === "topic_group";
65
+ }
66
+
67
+ export type FeishuMessageInfo = {
68
+ messageId: string;
69
+ chatId: string;
70
+ chatType?: FeishuChatType;
71
+ senderId?: string;
72
+ senderOpenId?: string;
73
+ senderType?: string;
74
+ content: string;
75
+ contentType: string;
76
+ createTime?: number;
77
+ /** Feishu thread ID (omt_xxx) — present when the message belongs to a topic thread. */
78
+ threadId?: string;
79
+ };
80
+
81
+ export interface FeishuProbeResult extends BaseProbeResult {
82
+ appId?: string;
83
+ botName?: string;
84
+ botOpenId?: string;
85
+ }
86
+
87
+ export type FeishuMediaInfo = {
88
+ path: string;
89
+ contentType?: string;
90
+ placeholder: string;
91
+ };
92
+
93
+ export type FeishuToolsConfig = {
94
+ doc?: boolean;
95
+ chat?: boolean;
96
+ wiki?: boolean;
97
+ drive?: boolean;
98
+ perm?: boolean;
99
+ scopes?: boolean;
100
+ /** Bitable/Base operations (default: true). */
101
+ bitable?: boolean;
102
+ /** @deprecated Use bitable. */
103
+ base?: boolean;
104
+ };
105
+
106
+ export type DynamicAgentCreationConfig = {
107
+ enabled?: boolean;
108
+ workspaceTemplate?: string;
109
+ agentDirTemplate?: string;
110
+ maxAgents?: number;
111
+ };
@@ -0,0 +1,145 @@
1
+ // Feishu tests cover typing plugin behavior.
2
+ import { describe, expect, it } from "vitest";
3
+ import { isFeishuBackoffError, getBackoffCodeFromResponse, FeishuBackoffError } from "./typing.js";
4
+
5
+ describe("isFeishuBackoffError", () => {
6
+ it("returns true for HTTP 429 (AxiosError shape)", () => {
7
+ const err = { response: { status: 429, data: {} } };
8
+ expect(isFeishuBackoffError(err)).toBe(true);
9
+ });
10
+
11
+ it("returns true for Feishu quota exceeded code 99991403", () => {
12
+ const err = { response: { status: 200, data: { code: 99991403 } } };
13
+ expect(isFeishuBackoffError(err)).toBe(true);
14
+ });
15
+
16
+ it("returns true for Feishu rate limit code 99991400", () => {
17
+ const err = { response: { status: 200, data: { code: 99991400 } } };
18
+ expect(isFeishuBackoffError(err)).toBe(true);
19
+ });
20
+
21
+ it("returns true for SDK error with code 429", () => {
22
+ const err = { code: 429, message: "too many requests" };
23
+ expect(isFeishuBackoffError(err)).toBe(true);
24
+ });
25
+
26
+ it("returns true for SDK error with top-level code 99991403", () => {
27
+ const err = { code: 99991403, message: "quota exceeded" };
28
+ expect(isFeishuBackoffError(err)).toBe(true);
29
+ });
30
+
31
+ it("returns false for other HTTP errors (e.g. 500)", () => {
32
+ const err = { response: { status: 500, data: {} } };
33
+ expect(isFeishuBackoffError(err)).toBe(false);
34
+ });
35
+
36
+ it("returns false for non-rate-limit Feishu codes", () => {
37
+ const err = { response: { status: 200, data: { code: 99991401 } } };
38
+ expect(isFeishuBackoffError(err)).toBe(false);
39
+ });
40
+
41
+ it("returns false for generic Error", () => {
42
+ expect(isFeishuBackoffError(new Error("network timeout"))).toBe(false);
43
+ });
44
+
45
+ it("returns false for null", () => {
46
+ expect(isFeishuBackoffError(null)).toBe(false);
47
+ });
48
+
49
+ it("returns false for undefined", () => {
50
+ expect(isFeishuBackoffError(undefined)).toBe(false);
51
+ });
52
+
53
+ it("returns false for string", () => {
54
+ expect(isFeishuBackoffError("429")).toBe(false);
55
+ });
56
+
57
+ it("returns true for 429 even without data", () => {
58
+ const err = { response: { status: 429 } };
59
+ expect(isFeishuBackoffError(err)).toBe(true);
60
+ });
61
+ });
62
+
63
+ describe("getBackoffCodeFromResponse", () => {
64
+ it("returns backoff code for response with quota exceeded code", () => {
65
+ const response = { code: 99991403, msg: "quota exceeded", data: null };
66
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
67
+ });
68
+
69
+ it("returns backoff code for response with rate limit code", () => {
70
+ const response = { code: 99991400, msg: "rate limit", data: null };
71
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
72
+ });
73
+
74
+ it("returns backoff code for response with code 429", () => {
75
+ const response = { code: 429, msg: "too many requests", data: null };
76
+ expect(getBackoffCodeFromResponse(response)).toBe(response.code);
77
+ });
78
+
79
+ it("returns undefined for successful response (code 0)", () => {
80
+ const response = { code: 0, msg: "success", data: { reaction_id: "r1" } };
81
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
82
+ });
83
+
84
+ it("returns undefined for other error codes", () => {
85
+ const response = { code: 99991401, msg: "other error", data: null };
86
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
87
+ });
88
+
89
+ it("returns undefined for null", () => {
90
+ expect(getBackoffCodeFromResponse(null)).toBeUndefined();
91
+ });
92
+
93
+ it("returns undefined for undefined", () => {
94
+ expect(getBackoffCodeFromResponse(undefined)).toBeUndefined();
95
+ });
96
+
97
+ it("returns undefined for response without code field", () => {
98
+ const response = { data: { reaction_id: "r1" } };
99
+ expect(getBackoffCodeFromResponse(response)).toBeUndefined();
100
+ });
101
+ });
102
+
103
+ describe("FeishuBackoffError", () => {
104
+ it("is detected by isFeishuBackoffError via .code property", () => {
105
+ const err = new FeishuBackoffError(99991403);
106
+ expect(isFeishuBackoffError(err)).toBe(true);
107
+ });
108
+
109
+ it("is detected for rate limit code 99991400", () => {
110
+ const err = new FeishuBackoffError(99991400);
111
+ expect(isFeishuBackoffError(err)).toBe(true);
112
+ });
113
+
114
+ it("has correct name and message", () => {
115
+ const err = new FeishuBackoffError(99991403);
116
+ expect(err.name).toBe("FeishuBackoffError");
117
+ expect(err.message).toBe("Feishu API backoff: code 99991403");
118
+ expect(err.code).toBe(99991403);
119
+ });
120
+
121
+ it("is an instance of Error", () => {
122
+ const err = new FeishuBackoffError(99991403);
123
+ expect(err instanceof Error).toBe(true);
124
+ });
125
+
126
+ it("survives catch-and-rethrow pattern", () => {
127
+ // Simulates the exact pattern in addTypingIndicator/removeTypingIndicator:
128
+ // thrown inside try, caught by catch, isFeishuBackoffError must match
129
+ let caught: unknown;
130
+ try {
131
+ try {
132
+ throw new FeishuBackoffError(99991403);
133
+ } catch (err) {
134
+ if (isFeishuBackoffError(err)) {
135
+ throw err; // re-thrown — this is the fix
136
+ }
137
+ // would be silently swallowed with plain Error
138
+ caught = "swallowed";
139
+ }
140
+ } catch (err) {
141
+ caught = err;
142
+ }
143
+ expect(caught).toBeInstanceOf(FeishuBackoffError);
144
+ });
145
+ });
package/src/typing.ts ADDED
@@ -0,0 +1,215 @@
1
+ // Feishu plugin module implements typing behavior.
2
+ import type { ACTAgentBotConfig, RuntimeEnv } from "../runtime-api.js";
3
+ import { resolveFeishuRuntimeAccount } from "./accounts.js";
4
+ import { createFeishuClient } from "./client.js";
5
+ import { getFeishuRuntime } from "./runtime.js";
6
+
7
+ // Feishu emoji types for typing indicator
8
+ // See: https://open.feishu.cn/document/server-docs/im-v1/message-reaction/emojis-introduce
9
+ // Full list: https://github.com/go-lark/lark/blob/main/emoji.go
10
+ const TYPING_EMOJI = "Typing"; // Typing indicator emoji
11
+
12
+ /**
13
+ * Feishu API error codes that indicate the caller should back off.
14
+ * These must propagate to the typing circuit breaker so the keepalive loop
15
+ * can trip and stop retrying.
16
+ *
17
+ * - 99991400: Rate limit (too many requests per second)
18
+ * - 99991403: Monthly API call quota exceeded
19
+ * - 429: Standard HTTP 429 returned as a Feishu SDK error code
20
+ *
21
+ * @see https://open.feishu.cn/document/server-docs/api-call-guide/generic-error-code
22
+ */
23
+ const FEISHU_BACKOFF_CODES = new Set([99991400, 99991403, 429]);
24
+
25
+ /**
26
+ * Custom error class for Feishu backoff conditions detected from non-throwing
27
+ * SDK responses. Carries a numeric `.code` so that `isFeishuBackoffError()`
28
+ * recognises it when the error is caught downstream.
29
+ */
30
+ export class FeishuBackoffError extends Error {
31
+ code: number;
32
+ constructor(code: number) {
33
+ super(`Feishu API backoff: code ${code}`);
34
+ this.name = "FeishuBackoffError";
35
+ this.code = code;
36
+ }
37
+ }
38
+
39
+ export type TypingIndicatorState = {
40
+ messageId: string;
41
+ reactionId: string | null;
42
+ };
43
+
44
+ type FeishuMessageReactionCreateResponse = Awaited<
45
+ ReturnType<ReturnType<typeof createFeishuClient>["im"]["messageReaction"]["create"]>
46
+ >;
47
+
48
+ /**
49
+ * Check whether an error represents a rate-limit or quota-exceeded condition
50
+ * from the Feishu API that should stop the typing keepalive loop.
51
+ *
52
+ * Handles two shapes:
53
+ * 1. AxiosError with `response.status` and `response.data.code`
54
+ * 2. Feishu SDK error with a top-level `code` property
55
+ */
56
+ export function isFeishuBackoffError(err: unknown): boolean {
57
+ if (typeof err !== "object" || err === null) {
58
+ return false;
59
+ }
60
+
61
+ // AxiosError shape: err.response.status / err.response.data.code
62
+ const response = (err as { response?: { status?: number; data?: { code?: number } } }).response;
63
+ if (response) {
64
+ if (response.status === 429) {
65
+ return true;
66
+ }
67
+ if (typeof response.data?.code === "number" && FEISHU_BACKOFF_CODES.has(response.data.code)) {
68
+ return true;
69
+ }
70
+ }
71
+
72
+ // Feishu SDK error shape: err.code
73
+ const code = (err as { code?: number }).code;
74
+ if (typeof code === "number" && FEISHU_BACKOFF_CODES.has(code)) {
75
+ return true;
76
+ }
77
+
78
+ return false;
79
+ }
80
+
81
+ /**
82
+ * Check whether a Feishu SDK response object contains a backoff error code.
83
+ *
84
+ * The Feishu SDK sometimes returns a normal response (no throw) with an
85
+ * API-level error code in the response body. This must be detected so the
86
+ * circuit breaker can trip. See codex review on #28157.
87
+ */
88
+ export function getBackoffCodeFromResponse(response: unknown): number | undefined {
89
+ if (typeof response !== "object" || response === null) {
90
+ return undefined;
91
+ }
92
+ const code = (response as { code?: number }).code;
93
+ if (typeof code === "number" && FEISHU_BACKOFF_CODES.has(code)) {
94
+ return code;
95
+ }
96
+ return undefined;
97
+ }
98
+
99
+ /**
100
+ * Add a typing indicator (reaction) to a message.
101
+ *
102
+ * Rate-limit and quota errors are re-thrown so the circuit breaker in
103
+ * `createTypingCallbacks` (typing-start-guard) can trip and stop the
104
+ * keepalive loop. See #28062.
105
+ *
106
+ * Also checks for backoff codes in non-throwing SDK responses (#28157).
107
+ */
108
+ export async function addTypingIndicator(params: {
109
+ cfg: ACTAgentBotConfig;
110
+ messageId: string;
111
+ accountId?: string;
112
+ runtime?: RuntimeEnv;
113
+ }): Promise<TypingIndicatorState> {
114
+ const { cfg, messageId, accountId, runtime } = params;
115
+ const account = resolveFeishuRuntimeAccount({ cfg, accountId });
116
+ if (!account.configured) {
117
+ return { messageId, reactionId: null };
118
+ }
119
+
120
+ const client = createFeishuClient(account);
121
+
122
+ try {
123
+ const response = await client.im.messageReaction.create({
124
+ path: { message_id: messageId },
125
+ data: {
126
+ reaction_type: { emoji_type: TYPING_EMOJI },
127
+ },
128
+ });
129
+
130
+ // Feishu SDK may return a normal response with an API-level error code
131
+ // instead of throwing. Detect backoff codes and throw to trip the breaker.
132
+ const backoffCode = getBackoffCodeFromResponse(response);
133
+ if (backoffCode !== undefined) {
134
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
135
+ runtime?.log?.(
136
+ `[feishu] typing indicator response contains backoff code ${backoffCode}, stopping keepalive`,
137
+ );
138
+ }
139
+ throw new FeishuBackoffError(backoffCode);
140
+ }
141
+
142
+ const typedResponse: FeishuMessageReactionCreateResponse = response;
143
+ const reactionId = typedResponse.data?.reaction_id ?? null;
144
+ return { messageId, reactionId };
145
+ } catch (err) {
146
+ if (isFeishuBackoffError(err)) {
147
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
148
+ runtime?.log?.("[feishu] typing indicator hit rate-limit/quota, stopping keepalive");
149
+ }
150
+ throw err;
151
+ }
152
+ // Silently fail for other non-critical errors (e.g. message deleted, permission issues)
153
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
154
+ runtime?.log?.(`[feishu] failed to add typing indicator: ${String(err)}`);
155
+ }
156
+ return { messageId, reactionId: null };
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Remove a typing indicator (reaction) from a message.
162
+ *
163
+ * Rate-limit and quota errors are re-thrown for the same reason as above.
164
+ */
165
+ export async function removeTypingIndicator(params: {
166
+ cfg: ACTAgentBotConfig;
167
+ state: TypingIndicatorState;
168
+ accountId?: string;
169
+ runtime?: RuntimeEnv;
170
+ }): Promise<void> {
171
+ const { cfg, state, accountId, runtime } = params;
172
+ if (!state.reactionId) {
173
+ return;
174
+ }
175
+
176
+ const account = resolveFeishuRuntimeAccount({ cfg, accountId });
177
+ if (!account.configured) {
178
+ return;
179
+ }
180
+
181
+ const client = createFeishuClient(account);
182
+
183
+ try {
184
+ const result = await client.im.messageReaction.delete({
185
+ path: {
186
+ message_id: state.messageId,
187
+ reaction_id: state.reactionId,
188
+ },
189
+ });
190
+
191
+ // Check for backoff codes in non-throwing SDK responses
192
+ const backoffCode = getBackoffCodeFromResponse(result);
193
+ if (backoffCode !== undefined) {
194
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
195
+ runtime?.log?.(
196
+ `[feishu] typing indicator removal response contains backoff code ${backoffCode}, stopping keepalive`,
197
+ );
198
+ }
199
+ throw new FeishuBackoffError(backoffCode);
200
+ }
201
+ } catch (err) {
202
+ if (isFeishuBackoffError(err)) {
203
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
204
+ runtime?.log?.(
205
+ "[feishu] typing indicator removal hit rate-limit/quota, stopping keepalive",
206
+ );
207
+ }
208
+ throw err;
209
+ }
210
+ // Silently fail for other non-critical errors
211
+ if (getFeishuRuntime().logging.shouldLogVerbose()) {
212
+ runtime?.log?.(`[feishu] failed to remove typing indicator: ${String(err)}`);
213
+ }
214
+ }
215
+ }
@@ -0,0 +1,70 @@
1
+ // Feishu helper module supports wiki schema behavior.
2
+ import { Type, type Static } from "typebox";
3
+
4
+ const WIKI_SPACE_ID_DESCRIPTION =
5
+ "Knowledge space ID. Treat as an opaque string and keep it quoted; never pass numeric-looking IDs as numbers.";
6
+
7
+ export const FeishuWikiSchema = Type.Union([
8
+ Type.Object({
9
+ action: Type.Literal("spaces"),
10
+ }),
11
+ Type.Object({
12
+ action: Type.Literal("nodes"),
13
+ space_id: Type.String({ description: WIKI_SPACE_ID_DESCRIPTION }),
14
+ parent_node_token: Type.Optional(
15
+ Type.String({ description: "Parent node token (optional, omit for root)" }),
16
+ ),
17
+ }),
18
+ Type.Object({
19
+ action: Type.Literal("get"),
20
+ token: Type.String({ description: "Wiki node token (from URL /wiki/XXX)" }),
21
+ }),
22
+ Type.Object({
23
+ action: Type.Literal("search"),
24
+ query: Type.String({ description: "Search query" }),
25
+ space_id: Type.Optional(
26
+ Type.String({
27
+ description:
28
+ "Limit search to this knowledge space. Treat as an opaque string and keep it quoted; never pass numeric-looking IDs as numbers.",
29
+ }),
30
+ ),
31
+ }),
32
+ Type.Object({
33
+ action: Type.Literal("create"),
34
+ space_id: Type.String({ description: WIKI_SPACE_ID_DESCRIPTION }),
35
+ title: Type.String({ description: "Node title" }),
36
+ obj_type: Type.Optional(
37
+ Type.Union([Type.Literal("docx"), Type.Literal("sheet"), Type.Literal("bitable")], {
38
+ description: "Object type (default: docx)",
39
+ }),
40
+ ),
41
+ parent_node_token: Type.Optional(
42
+ Type.String({ description: "Parent node token (optional, omit for root)" }),
43
+ ),
44
+ }),
45
+ Type.Object({
46
+ action: Type.Literal("move"),
47
+ space_id: Type.String({
48
+ description:
49
+ "Source knowledge space ID. Treat as an opaque string and keep it quoted; never pass numeric-looking IDs as numbers.",
50
+ }),
51
+ node_token: Type.String({ description: "Node token to move" }),
52
+ target_space_id: Type.Optional(
53
+ Type.String({
54
+ description:
55
+ "Target knowledge space ID (optional, same space if omitted). Treat as an opaque string and keep it quoted; never pass numeric-looking IDs as numbers.",
56
+ }),
57
+ ),
58
+ target_parent_token: Type.Optional(
59
+ Type.String({ description: "Target parent node token (optional, root if omitted)" }),
60
+ ),
61
+ }),
62
+ Type.Object({
63
+ action: Type.Literal("rename"),
64
+ space_id: Type.String({ description: WIKI_SPACE_ID_DESCRIPTION }),
65
+ node_token: Type.String({ description: "Node token to rename" }),
66
+ title: Type.String({ description: "New title" }),
67
+ }),
68
+ ]);
69
+
70
+ export type FeishuWikiParams = Static<typeof FeishuWikiSchema>;