@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,204 @@
1
+ // Feishu plugin module implements presentation card behavior.
2
+ import {
3
+ normalizeMessagePresentation,
4
+ renderMessagePresentationFallbackText,
5
+ type MessagePresentationBlock,
6
+ type MessagePresentationButton,
7
+ } from "actagent/plugin-sdk/interactive-runtime";
8
+ import { createFeishuCardInteractionEnvelope } from "./card-interaction.js";
9
+
10
+ type NormalizedMessagePresentation = NonNullable<ReturnType<typeof normalizeMessagePresentation>>;
11
+
12
+ function escapeFeishuCardMarkdownText(text: string): string {
13
+ return text.replace(/[&<>]/g, (char) => {
14
+ switch (char) {
15
+ case "&":
16
+ return "&amp;";
17
+ case "<":
18
+ return "&lt;";
19
+ case ">":
20
+ return "&gt;";
21
+ default:
22
+ return char;
23
+ }
24
+ });
25
+ }
26
+
27
+ function resolveSafeFeishuButtonUrl(url: string | undefined): string | undefined {
28
+ const trimmed = url?.trim();
29
+ if (!trimmed) {
30
+ return undefined;
31
+ }
32
+ try {
33
+ const parsed = new URL(trimmed);
34
+ return parsed.protocol === "https:" || parsed.protocol === "http:" ? trimmed : undefined;
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ function resolveFeishuButtonUrl(button: MessagePresentationButton): string | undefined {
41
+ return button.url ?? button.webApp?.url ?? button.web_app?.url;
42
+ }
43
+
44
+ function resolveFeishuCommandButtonValue(button: MessagePresentationButton): string | undefined {
45
+ if (button.action?.type === "callback") {
46
+ return undefined;
47
+ }
48
+ if (button.action?.type === "command") {
49
+ return button.action.command;
50
+ }
51
+ return button.value;
52
+ }
53
+
54
+ function mapFeishuButtonType(style: MessagePresentationButton["style"]) {
55
+ if (style === "primary" || style === "success") {
56
+ return "primary";
57
+ }
58
+ if (style === "danger") {
59
+ return "danger";
60
+ }
61
+ return "default";
62
+ }
63
+
64
+ function buildFeishuPayloadButton(
65
+ button: MessagePresentationButton,
66
+ ): Record<string, unknown> | undefined {
67
+ const behaviors: Record<string, unknown>[] = [];
68
+ const rendered: Record<string, unknown> = {
69
+ tag: "button",
70
+ text: {
71
+ tag: "plain_text",
72
+ content: button.label,
73
+ },
74
+ type: mapFeishuButtonType(button.style),
75
+ };
76
+ const url = resolveFeishuButtonUrl(button);
77
+ if (url) {
78
+ const safeUrl = resolveSafeFeishuButtonUrl(url);
79
+ if (safeUrl) {
80
+ behaviors.push({ type: "open_url", default_url: safeUrl });
81
+ }
82
+ }
83
+ const value = resolveFeishuCommandButtonValue(button);
84
+ if (value) {
85
+ behaviors.push({
86
+ type: "callback",
87
+ value: createFeishuCardInteractionEnvelope({
88
+ k: "quick",
89
+ a: "feishu.payload.button",
90
+ q: value,
91
+ }),
92
+ });
93
+ }
94
+ if (behaviors.length === 0) {
95
+ return undefined;
96
+ }
97
+ rendered.behaviors = behaviors;
98
+ return rendered;
99
+ }
100
+
101
+ export function buildFeishuCardElementsForBlock(
102
+ block: MessagePresentationBlock,
103
+ ): Record<string, unknown>[] {
104
+ if (block.type === "text") {
105
+ return [{ tag: "markdown", content: escapeFeishuCardMarkdownText(block.text) }];
106
+ }
107
+ if (block.type === "context") {
108
+ return [
109
+ {
110
+ tag: "markdown",
111
+ content: `<font color='grey'>${escapeFeishuCardMarkdownText(block.text)}</font>`,
112
+ },
113
+ ];
114
+ }
115
+ if (block.type === "divider") {
116
+ return [{ tag: "hr" }];
117
+ }
118
+ if (block.type === "buttons") {
119
+ return block.buttons
120
+ .map((button) => buildFeishuPayloadButton(button))
121
+ .filter((button): button is Record<string, unknown> => Boolean(button));
122
+ }
123
+ const labels = block.options.map((option) => `- ${option.label}`).join("\n");
124
+ return [
125
+ {
126
+ tag: "markdown",
127
+ content: `${escapeFeishuCardMarkdownText(
128
+ block.placeholder?.trim() || "Options",
129
+ )}:\n${escapeFeishuCardMarkdownText(labels)}`,
130
+ },
131
+ ];
132
+ }
133
+
134
+ function resolvePresentationHeaderTemplate(tone: NormalizedMessagePresentation["tone"]) {
135
+ if (tone === "danger") {
136
+ return "red";
137
+ }
138
+ if (tone === "warning") {
139
+ return "orange";
140
+ }
141
+ if (tone === "success") {
142
+ return "green";
143
+ }
144
+ return "blue";
145
+ }
146
+
147
+ export function buildFeishuPresentationCardElements(params: {
148
+ presentation: NormalizedMessagePresentation;
149
+ fallbackText?: string;
150
+ }): Record<string, unknown>[] {
151
+ const elements: Record<string, unknown>[] = [];
152
+ const fallbackText = params.fallbackText?.trim();
153
+ if (fallbackText) {
154
+ elements.push({
155
+ tag: "markdown",
156
+ content: escapeFeishuCardMarkdownText(fallbackText),
157
+ });
158
+ }
159
+ for (const block of params.presentation.blocks) {
160
+ for (const element of buildFeishuCardElementsForBlock(block)) {
161
+ elements.push(element);
162
+ }
163
+ }
164
+ if (elements.length > 0) {
165
+ return elements;
166
+ }
167
+ return [
168
+ {
169
+ tag: "markdown",
170
+ content: renderMessagePresentationFallbackText({
171
+ text: params.fallbackText,
172
+ presentation: params.presentation.title
173
+ ? {
174
+ ...(params.presentation.tone ? { tone: params.presentation.tone } : {}),
175
+ blocks: params.presentation.blocks,
176
+ }
177
+ : params.presentation,
178
+ }),
179
+ },
180
+ ];
181
+ }
182
+
183
+ export function buildFeishuPresentationCard(params: {
184
+ presentation: NormalizedMessagePresentation;
185
+ fallbackText?: string;
186
+ }): Record<string, unknown> {
187
+ return {
188
+ schema: "2.0",
189
+ config: {
190
+ width_mode: "fill",
191
+ },
192
+ ...(params.presentation.title
193
+ ? {
194
+ header: {
195
+ title: { tag: "plain_text", content: params.presentation.title },
196
+ template: resolvePresentationHeaderTemplate(params.presentation.tone),
197
+ },
198
+ }
199
+ : {}),
200
+ body: {
201
+ elements: buildFeishuPresentationCardElements(params),
202
+ },
203
+ };
204
+ }
@@ -0,0 +1,310 @@
1
+ // Feishu tests cover probe plugin behavior.
2
+ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import { clearProbeCache, FEISHU_PROBE_REQUEST_TIMEOUT_MS, probeFeishu } from "./probe.js";
4
+
5
+ const createFeishuClientMock = vi.hoisted(() => vi.fn());
6
+
7
+ vi.mock("./client.js", () => ({
8
+ createFeishuClient: createFeishuClientMock,
9
+ }));
10
+
11
+ const DEFAULT_CREDS = { appId: "cli_123", appSecret: "secret" } as const; // pragma: allowlist secret
12
+ const DEFAULT_SUCCESS_RESPONSE = {
13
+ code: 0,
14
+ data: { pingBotInfo: { botName: "TestBot", botID: "ou_abc123" } },
15
+ } as const;
16
+ const DEFAULT_SUCCESS_RESULT = {
17
+ ok: true,
18
+ appId: "cli_123",
19
+ botName: "TestBot",
20
+ botOpenId: "ou_abc123",
21
+ } as const;
22
+ const BOT1_RESPONSE = {
23
+ code: 0,
24
+ data: { pingBotInfo: { botName: "Bot1", botID: "ou_1" } },
25
+ } as const;
26
+
27
+ afterAll(() => {
28
+ vi.doUnmock("./client.js");
29
+ vi.resetModules();
30
+ });
31
+
32
+ function makeRequestFn(response: Record<string, unknown>) {
33
+ return vi.fn().mockResolvedValue(response);
34
+ }
35
+
36
+ function setupClient(response: Record<string, unknown>) {
37
+ const requestFn = makeRequestFn(response);
38
+ createFeishuClientMock.mockReturnValue({ request: requestFn });
39
+ return requestFn;
40
+ }
41
+
42
+ function setupSuccessClient() {
43
+ return setupClient(DEFAULT_SUCCESS_RESPONSE);
44
+ }
45
+
46
+ async function expectDefaultSuccessResult(
47
+ creds = DEFAULT_CREDS,
48
+ expected: {
49
+ ok: true;
50
+ appId: string;
51
+ botName: string;
52
+ botOpenId: string;
53
+ } = DEFAULT_SUCCESS_RESULT,
54
+ ) {
55
+ const result = await probeFeishu(creds);
56
+ expect(result).toEqual(expected);
57
+ }
58
+
59
+ async function withFakeTimers(run: () => Promise<void>) {
60
+ vi.useFakeTimers();
61
+ try {
62
+ await run();
63
+ } finally {
64
+ vi.useRealTimers();
65
+ }
66
+ }
67
+
68
+ async function expectErrorResultCached(params: {
69
+ requestFn: ReturnType<typeof vi.fn>;
70
+ expectedError: string;
71
+ ttlMs: number;
72
+ }) {
73
+ createFeishuClientMock.mockReturnValue({ request: params.requestFn });
74
+
75
+ const first = await probeFeishu(DEFAULT_CREDS);
76
+ const second = await probeFeishu(DEFAULT_CREDS);
77
+ const expected = { ok: false, appId: DEFAULT_CREDS.appId, error: params.expectedError };
78
+ expect(first).toEqual(expected);
79
+ expect(second).toEqual(expected);
80
+ expect(params.requestFn).toHaveBeenCalledTimes(1);
81
+
82
+ vi.advanceTimersByTime(params.ttlMs + 1);
83
+
84
+ await probeFeishu(DEFAULT_CREDS);
85
+ expect(params.requestFn).toHaveBeenCalledTimes(2);
86
+ }
87
+
88
+ async function expectFreshDefaultProbeAfter(
89
+ requestFn: ReturnType<typeof vi.fn>,
90
+ invalidate: () => void,
91
+ ) {
92
+ await probeFeishu(DEFAULT_CREDS);
93
+ expect(requestFn).toHaveBeenCalledTimes(1);
94
+
95
+ invalidate();
96
+
97
+ await probeFeishu(DEFAULT_CREDS);
98
+ expect(requestFn).toHaveBeenCalledTimes(2);
99
+ }
100
+
101
+ async function readSequentialDefaultProbePair() {
102
+ const first = await probeFeishu(DEFAULT_CREDS);
103
+ return { first, second: await probeFeishu(DEFAULT_CREDS) };
104
+ }
105
+
106
+ describe("probeFeishu", () => {
107
+ beforeEach(() => {
108
+ clearProbeCache();
109
+ vi.restoreAllMocks();
110
+ });
111
+
112
+ afterEach(() => {
113
+ clearProbeCache();
114
+ });
115
+
116
+ it("returns error when credentials are missing", async () => {
117
+ const result = await probeFeishu();
118
+ expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
119
+ });
120
+
121
+ it("returns error when appId is missing", async () => {
122
+ const result = await probeFeishu({ appSecret: "secret" } as never); // pragma: allowlist secret
123
+ expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
124
+ });
125
+
126
+ it("returns error when appSecret is missing", async () => {
127
+ const result = await probeFeishu({ appId: "cli_123" } as never);
128
+ expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
129
+ });
130
+
131
+ it("returns bot info on successful probe", async () => {
132
+ const requestFn = setupSuccessClient();
133
+
134
+ await expectDefaultSuccessResult();
135
+ expect(requestFn).toHaveBeenCalledTimes(1);
136
+ });
137
+
138
+ it("passes the probe timeout to the Feishu request", async () => {
139
+ const requestFn = setupSuccessClient();
140
+
141
+ await probeFeishu(DEFAULT_CREDS);
142
+
143
+ expect(requestFn).toHaveBeenCalledWith({
144
+ method: "POST",
145
+ url: "/open-apis/bot/v1/actagent_bot/ping",
146
+ data: { needBotInfo: true },
147
+ timeout: FEISHU_PROBE_REQUEST_TIMEOUT_MS,
148
+ });
149
+ });
150
+
151
+ it("returns timeout error when request exceeds timeout", async () => {
152
+ await withFakeTimers(async () => {
153
+ const requestFn = vi.fn().mockImplementation(() => new Promise(() => {}));
154
+ createFeishuClientMock.mockReturnValue({ request: requestFn });
155
+
156
+ const promise = probeFeishu(DEFAULT_CREDS, { timeoutMs: 1_000 });
157
+ await vi.advanceTimersByTimeAsync(1_000);
158
+ const result = await promise;
159
+
160
+ expect(result).toEqual({
161
+ ok: false,
162
+ appId: DEFAULT_CREDS.appId,
163
+ error: "probe timed out after 1000ms",
164
+ });
165
+ });
166
+ });
167
+
168
+ it("returns aborted when abort signal is already aborted", async () => {
169
+ createFeishuClientMock.mockClear();
170
+ const abortController = new AbortController();
171
+ abortController.abort();
172
+
173
+ const result = await probeFeishu(
174
+ { appId: "cli_123", appSecret: "secret" }, // pragma: allowlist secret
175
+ { abortSignal: abortController.signal },
176
+ );
177
+
178
+ expect(result).toEqual({ ok: false, appId: "cli_123", error: "probe aborted" });
179
+ expect(createFeishuClientMock).not.toHaveBeenCalled();
180
+ });
181
+ it("returns cached result on subsequent calls within TTL", async () => {
182
+ const requestFn = setupSuccessClient();
183
+
184
+ const { first, second } = await readSequentialDefaultProbePair();
185
+
186
+ expect(first).toEqual(second);
187
+ // Only one API call should have been made
188
+ expect(requestFn).toHaveBeenCalledTimes(1);
189
+ });
190
+
191
+ it("does not cache probe results when the expiry would exceed a valid Date", async () => {
192
+ await withFakeTimers(async () => {
193
+ vi.setSystemTime(new Date(8_640_000_000_000_000));
194
+ const requestFn = setupSuccessClient();
195
+
196
+ const { first, second } = await readSequentialDefaultProbePair();
197
+
198
+ expect(first).toEqual(second);
199
+ expect(requestFn).toHaveBeenCalledTimes(2);
200
+ });
201
+ });
202
+
203
+ it("evicts cached probe results when the current clock is invalid", async () => {
204
+ const requestFn = setupSuccessClient();
205
+
206
+ await probeFeishu(DEFAULT_CREDS);
207
+ const dateNow = vi.spyOn(Date, "now").mockReturnValue(Number.NaN);
208
+ try {
209
+ await probeFeishu(DEFAULT_CREDS);
210
+ } finally {
211
+ dateNow.mockRestore();
212
+ }
213
+
214
+ expect(requestFn).toHaveBeenCalledTimes(2);
215
+ });
216
+
217
+ it("makes a fresh API call after cache expires", async () => {
218
+ await withFakeTimers(async () => {
219
+ const requestFn = setupSuccessClient();
220
+
221
+ await expectFreshDefaultProbeAfter(requestFn, () => {
222
+ vi.advanceTimersByTime(10 * 60 * 1000 + 1);
223
+ });
224
+ });
225
+ });
226
+
227
+ it("caches failed probe results (API error) for the error TTL", async () => {
228
+ await withFakeTimers(async () => {
229
+ await expectErrorResultCached({
230
+ requestFn: makeRequestFn({ code: 99, msg: "token expired" }),
231
+ expectedError: "API error: token expired",
232
+ ttlMs: 60 * 1000,
233
+ });
234
+ });
235
+ });
236
+
237
+ it("caches thrown request errors for the error TTL", async () => {
238
+ await withFakeTimers(async () => {
239
+ await expectErrorResultCached({
240
+ requestFn: vi.fn().mockRejectedValue(new Error("network error")),
241
+ expectedError: "network error",
242
+ ttlMs: 60 * 1000,
243
+ });
244
+ });
245
+ });
246
+
247
+ it("caches per account independently", async () => {
248
+ const requestFn = setupClient(BOT1_RESPONSE);
249
+
250
+ await probeFeishu({ appId: "cli_aaa", appSecret: "s1" }); // pragma: allowlist secret
251
+ expect(requestFn).toHaveBeenCalledTimes(1);
252
+
253
+ // Different appId should trigger a new API call
254
+ await probeFeishu({ appId: "cli_bbb", appSecret: "s2" }); // pragma: allowlist secret
255
+ expect(requestFn).toHaveBeenCalledTimes(2);
256
+
257
+ // Same appId + appSecret as first call should return cached
258
+ await probeFeishu({ appId: "cli_aaa", appSecret: "s1" }); // pragma: allowlist secret
259
+ expect(requestFn).toHaveBeenCalledTimes(2);
260
+ });
261
+
262
+ it("does not share cache between accounts with same appId but different appSecret", async () => {
263
+ const requestFn = setupClient(BOT1_RESPONSE);
264
+
265
+ // First account with appId + secret A
266
+ await probeFeishu({ appId: "cli_shared", appSecret: "secret_aaa" }); // pragma: allowlist secret
267
+ expect(requestFn).toHaveBeenCalledTimes(1);
268
+
269
+ // Second account with same appId but different secret (e.g. after rotation)
270
+ // must NOT reuse the cached result
271
+ await probeFeishu({ appId: "cli_shared", appSecret: "secret_bbb" }); // pragma: allowlist secret
272
+ expect(requestFn).toHaveBeenCalledTimes(2);
273
+ });
274
+
275
+ it("uses accountId for cache key when available", async () => {
276
+ const requestFn = setupClient(BOT1_RESPONSE);
277
+
278
+ // Two accounts with same appId+appSecret but different accountIds are cached separately
279
+ await probeFeishu({ accountId: "acct-1", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
280
+ expect(requestFn).toHaveBeenCalledTimes(1);
281
+
282
+ await probeFeishu({ accountId: "acct-2", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
283
+ expect(requestFn).toHaveBeenCalledTimes(2);
284
+
285
+ // Same accountId should return cached
286
+ await probeFeishu({ accountId: "acct-1", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
287
+ expect(requestFn).toHaveBeenCalledTimes(2);
288
+ });
289
+
290
+ it("clearProbeCache forces fresh API call", async () => {
291
+ const requestFn = setupSuccessClient();
292
+
293
+ await expectFreshDefaultProbeAfter(requestFn, () => {
294
+ clearProbeCache();
295
+ });
296
+ });
297
+
298
+ it("handles response with pingBotInfo in data", async () => {
299
+ setupClient({
300
+ code: 0,
301
+ data: { pingBotInfo: { botName: "DataBot", botID: "ou_data" } },
302
+ });
303
+
304
+ await expectDefaultSuccessResult(DEFAULT_CREDS, {
305
+ ...DEFAULT_SUCCESS_RESULT,
306
+ botName: "DataBot",
307
+ botOpenId: "ou_data",
308
+ });
309
+ });
310
+ });
package/src/probe.ts ADDED
@@ -0,0 +1,181 @@
1
+ // Feishu plugin module implements probe behavior.
2
+ import { formatErrorMessage } from "actagent/plugin-sdk/error-runtime";
3
+ import {
4
+ asDateTimestampMs,
5
+ resolveExpiresAtMsFromDurationMs,
6
+ } from "actagent/plugin-sdk/number-runtime";
7
+ import { raceWithTimeoutAndAbort } from "./async.js";
8
+ import { createFeishuClient, type FeishuClientCredentials } from "./client.js";
9
+ import type { FeishuProbeResult } from "./types.js";
10
+
11
+ /** Cache probe results to reduce repeated health-check calls.
12
+ * Gateway health checks call probeFeishu() every minute; without caching this
13
+ * burns ~43,200 calls/month, easily exceeding Feishu's free-tier quota.
14
+ * Successful bot info is effectively static, while failures are cached briefly
15
+ * to avoid hammering the API during transient outages. */
16
+ const probeCache = new Map<string, { result: FeishuProbeResult; expiresAt: number }>();
17
+ const PROBE_SUCCESS_TTL_MS = 10 * 60 * 1000; // 10 minutes
18
+ const PROBE_ERROR_TTL_MS = 60 * 1000; // 1 minute
19
+ const MAX_PROBE_CACHE_SIZE = 64;
20
+ export const FEISHU_PROBE_REQUEST_TIMEOUT_MS = 10_000;
21
+ export type ProbeFeishuOptions = {
22
+ timeoutMs?: number;
23
+ abortSignal?: AbortSignal;
24
+ };
25
+
26
+ type FeishuPingResponse = {
27
+ code: number;
28
+ msg?: string;
29
+ data?: { pingBotInfo?: { botID?: string; botName?: string } };
30
+ };
31
+
32
+ type FeishuRequestClient = ReturnType<typeof createFeishuClient> & {
33
+ request(params: {
34
+ method: "POST";
35
+ url: string;
36
+ data: Record<string, unknown>;
37
+ timeout: number;
38
+ }): Promise<FeishuPingResponse>;
39
+ };
40
+
41
+ function setCachedProbeResult(
42
+ cacheKey: string,
43
+ result: FeishuProbeResult,
44
+ ttlMs: number,
45
+ ): FeishuProbeResult {
46
+ const expiresAt = resolveExpiresAtMsFromDurationMs(ttlMs);
47
+ if (expiresAt === undefined) {
48
+ probeCache.delete(cacheKey);
49
+ return result;
50
+ }
51
+ probeCache.set(cacheKey, { result, expiresAt });
52
+ if (probeCache.size > MAX_PROBE_CACHE_SIZE) {
53
+ const oldest = probeCache.keys().next().value;
54
+ if (oldest !== undefined) {
55
+ probeCache.delete(oldest);
56
+ }
57
+ }
58
+ return result;
59
+ }
60
+
61
+ export async function probeFeishu(
62
+ creds?: FeishuClientCredentials,
63
+ options: ProbeFeishuOptions = {},
64
+ ): Promise<FeishuProbeResult> {
65
+ if (!creds?.appId || !creds?.appSecret) {
66
+ return {
67
+ ok: false,
68
+ error: "missing credentials (appId, appSecret)",
69
+ };
70
+ }
71
+ if (options.abortSignal?.aborted) {
72
+ return {
73
+ ok: false,
74
+ appId: creds.appId,
75
+ error: "probe aborted",
76
+ };
77
+ }
78
+
79
+ const timeoutMs = options.timeoutMs ?? FEISHU_PROBE_REQUEST_TIMEOUT_MS;
80
+
81
+ // Return cached result if still valid.
82
+ // Use accountId when available; otherwise include appSecret prefix so two
83
+ // accounts sharing the same appId (e.g. after secret rotation) don't
84
+ // pollute each other's cache entry.
85
+ const cacheKey = creds.accountId ?? `${creds.appId}:${creds.appSecret.slice(0, 8)}`;
86
+ const cached = probeCache.get(cacheKey);
87
+ if (cached) {
88
+ const now = asDateTimestampMs(Date.now());
89
+ const expiresAt = asDateTimestampMs(cached.expiresAt);
90
+ if (now !== undefined && expiresAt !== undefined && expiresAt > now) {
91
+ return cached.result;
92
+ }
93
+ probeCache.delete(cacheKey);
94
+ }
95
+
96
+ try {
97
+ const client = createFeishuClient(creds) as FeishuRequestClient;
98
+ // Feishu-provided endpoint for ACTAgent, supported on both Feishu (CN)
99
+ // and Lark (international). No OAuth scopes required. Validates
100
+ // credentials and registers the app as an AI agent (智能体).
101
+ const responseResult = await raceWithTimeoutAndAbort<FeishuPingResponse>(
102
+ client.request({
103
+ method: "POST",
104
+ url: "/open-apis/bot/v1/actagent_bot/ping",
105
+ data: { needBotInfo: true },
106
+ timeout: timeoutMs,
107
+ }),
108
+ {
109
+ timeoutMs,
110
+ abortSignal: options.abortSignal,
111
+ },
112
+ );
113
+
114
+ if (responseResult.status === "aborted") {
115
+ return {
116
+ ok: false,
117
+ appId: creds.appId,
118
+ error: "probe aborted",
119
+ };
120
+ }
121
+ if (responseResult.status === "timeout") {
122
+ return setCachedProbeResult(
123
+ cacheKey,
124
+ {
125
+ ok: false,
126
+ appId: creds.appId,
127
+ error: `probe timed out after ${timeoutMs}ms`,
128
+ },
129
+ PROBE_ERROR_TTL_MS,
130
+ );
131
+ }
132
+
133
+ const response = responseResult.value;
134
+ if (options.abortSignal?.aborted) {
135
+ return {
136
+ ok: false,
137
+ appId: creds.appId,
138
+ error: "probe aborted",
139
+ };
140
+ }
141
+
142
+ if (response.code !== 0) {
143
+ return setCachedProbeResult(
144
+ cacheKey,
145
+ {
146
+ ok: false,
147
+ appId: creds.appId,
148
+ error: `API error: ${response.msg || `code ${response.code}`}`,
149
+ },
150
+ PROBE_ERROR_TTL_MS,
151
+ );
152
+ }
153
+
154
+ const botInfo = response.data?.pingBotInfo;
155
+ return setCachedProbeResult(
156
+ cacheKey,
157
+ {
158
+ ok: true,
159
+ appId: creds.appId,
160
+ botName: botInfo?.botName,
161
+ botOpenId: botInfo?.botID,
162
+ },
163
+ PROBE_SUCCESS_TTL_MS,
164
+ );
165
+ } catch (err) {
166
+ return setCachedProbeResult(
167
+ cacheKey,
168
+ {
169
+ ok: false,
170
+ appId: creds.appId,
171
+ error: formatErrorMessage(err),
172
+ },
173
+ PROBE_ERROR_TTL_MS,
174
+ );
175
+ }
176
+ }
177
+
178
+ /** Clear the probe cache (for testing). */
179
+ export function clearProbeCache(): void {
180
+ probeCache.clear();
181
+ }