@openclaw/feishu 2026.3.13 → 2026.5.1-beta.1

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 (188) hide show
  1. package/api.ts +31 -0
  2. package/channel-entry.ts +20 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +16 -0
  5. package/index.ts +70 -53
  6. package/openclaw.plugin.json +1653 -4
  7. package/package.json +32 -7
  8. package/runtime-api.ts +55 -0
  9. package/secret-contract-api.ts +5 -0
  10. package/security-contract-api.ts +1 -0
  11. package/session-key-api.ts +1 -0
  12. package/setup-api.ts +3 -0
  13. package/setup-entry.test.ts +14 -0
  14. package/setup-entry.ts +13 -0
  15. package/src/accounts.test.ts +95 -7
  16. package/src/accounts.ts +199 -117
  17. package/src/app-registration.ts +331 -0
  18. package/src/approval-auth.test.ts +24 -0
  19. package/src/approval-auth.ts +25 -0
  20. package/src/async.test.ts +35 -0
  21. package/src/async.ts +43 -1
  22. package/src/audio-preflight.runtime.ts +9 -0
  23. package/src/bitable.test.ts +131 -0
  24. package/src/bitable.ts +59 -22
  25. package/src/bot-content.ts +474 -0
  26. package/src/bot-group-name.test.ts +108 -0
  27. package/src/bot-runtime-api.ts +12 -0
  28. package/src/bot-sender-name.ts +125 -0
  29. package/src/bot.broadcast.test.ts +463 -0
  30. package/src/bot.card-action.test.ts +519 -5
  31. package/src/bot.checkBotMentioned.test.ts +92 -20
  32. package/src/bot.helpers.test.ts +118 -0
  33. package/src/bot.stripBotMention.test.ts +13 -21
  34. package/src/bot.test.ts +1334 -401
  35. package/src/bot.ts +778 -775
  36. package/src/card-action.ts +408 -40
  37. package/src/card-interaction.test.ts +129 -0
  38. package/src/card-interaction.ts +159 -0
  39. package/src/card-test-helpers.ts +47 -0
  40. package/src/card-ux-approval.ts +65 -0
  41. package/src/card-ux-launcher.test.ts +99 -0
  42. package/src/card-ux-launcher.ts +121 -0
  43. package/src/card-ux-shared.ts +33 -0
  44. package/src/channel-runtime-api.ts +16 -0
  45. package/src/channel.runtime.ts +47 -0
  46. package/src/channel.test.ts +914 -3
  47. package/src/channel.ts +1252 -309
  48. package/src/chat-schema.ts +5 -4
  49. package/src/chat.test.ts +84 -28
  50. package/src/chat.ts +68 -10
  51. package/src/client.test.ts +212 -103
  52. package/src/client.ts +115 -21
  53. package/src/comment-dispatcher-runtime-api.ts +6 -0
  54. package/src/comment-dispatcher.test.ts +169 -0
  55. package/src/comment-dispatcher.ts +107 -0
  56. package/src/comment-handler-runtime-api.ts +3 -0
  57. package/src/comment-handler.test.ts +486 -0
  58. package/src/comment-handler.ts +309 -0
  59. package/src/comment-reaction.test.ts +166 -0
  60. package/src/comment-reaction.ts +259 -0
  61. package/src/comment-shared.test.ts +182 -0
  62. package/src/comment-shared.ts +365 -0
  63. package/src/comment-target.ts +44 -0
  64. package/src/config-schema.test.ts +63 -1
  65. package/src/config-schema.ts +31 -4
  66. package/src/conversation-id.test.ts +18 -0
  67. package/src/conversation-id.ts +199 -0
  68. package/src/dedup-runtime-api.ts +1 -0
  69. package/src/dedup.ts +32 -94
  70. package/src/directory.static.ts +61 -0
  71. package/src/directory.test.ts +119 -20
  72. package/src/directory.ts +61 -91
  73. package/src/doc-schema.ts +1 -1
  74. package/src/docx-batch-insert.test.ts +39 -38
  75. package/src/docx-batch-insert.ts +55 -19
  76. package/src/docx-color-text.ts +9 -4
  77. package/src/docx-table-ops.test.ts +53 -0
  78. package/src/docx-table-ops.ts +52 -34
  79. package/src/docx-types.ts +38 -0
  80. package/src/docx.account-selection.test.ts +12 -3
  81. package/src/docx.test.ts +314 -74
  82. package/src/docx.ts +278 -122
  83. package/src/drive-schema.ts +47 -1
  84. package/src/drive.test.ts +1219 -0
  85. package/src/drive.ts +614 -13
  86. package/src/dynamic-agent.ts +10 -4
  87. package/src/event-types.ts +45 -0
  88. package/src/external-keys.ts +1 -1
  89. package/src/lifecycle.test-support.ts +220 -0
  90. package/src/media.test.ts +375 -26
  91. package/src/media.ts +434 -88
  92. package/src/mention-target.types.ts +5 -0
  93. package/src/mention.ts +32 -51
  94. package/src/message-action-contract.ts +13 -0
  95. package/src/monitor-state-runtime-api.ts +7 -0
  96. package/src/monitor-transport-runtime-api.ts +7 -0
  97. package/src/monitor.account.ts +218 -312
  98. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  99. package/src/monitor.bot-identity.ts +86 -0
  100. package/src/monitor.bot-menu-handler.ts +165 -0
  101. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  102. package/src/monitor.bot-menu.test.ts +178 -0
  103. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  104. package/src/monitor.card-action.lifecycle.test-support.ts +373 -0
  105. package/src/monitor.cleanup.test.ts +376 -0
  106. package/src/monitor.comment-notice-handler.ts +105 -0
  107. package/src/monitor.comment.test.ts +937 -0
  108. package/src/monitor.comment.ts +1386 -0
  109. package/src/monitor.lifecycle.test.ts +4 -0
  110. package/src/monitor.message-handler.ts +339 -0
  111. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  112. package/src/monitor.reaction.test.ts +108 -48
  113. package/src/monitor.reply-once.lifecycle.test-support.ts +190 -0
  114. package/src/monitor.startup.test.ts +11 -9
  115. package/src/monitor.startup.ts +26 -16
  116. package/src/monitor.state.ts +20 -5
  117. package/src/monitor.synthetic-error.ts +18 -0
  118. package/src/monitor.test-mocks.ts +2 -2
  119. package/src/monitor.transport.ts +220 -60
  120. package/src/monitor.ts +15 -10
  121. package/src/monitor.webhook-e2e.test.ts +65 -7
  122. package/src/monitor.webhook-security.test.ts +122 -0
  123. package/src/monitor.webhook.test-helpers.ts +44 -26
  124. package/src/outbound-runtime-api.ts +1 -0
  125. package/src/outbound.test.ts +616 -37
  126. package/src/outbound.ts +623 -81
  127. package/src/perm-schema.ts +1 -1
  128. package/src/perm.ts +1 -7
  129. package/src/pins.ts +108 -0
  130. package/src/policy.test.ts +297 -117
  131. package/src/policy.ts +142 -29
  132. package/src/post.ts +7 -6
  133. package/src/probe.test.ts +14 -9
  134. package/src/probe.ts +26 -16
  135. package/src/processing-claims.ts +59 -0
  136. package/src/qr-terminal.ts +1 -0
  137. package/src/reactions.ts +4 -34
  138. package/src/reasoning-preview.test.ts +59 -0
  139. package/src/reasoning-preview.ts +20 -0
  140. package/src/reply-dispatcher-runtime-api.ts +7 -0
  141. package/src/reply-dispatcher.test.ts +660 -29
  142. package/src/reply-dispatcher.ts +407 -154
  143. package/src/runtime.ts +6 -3
  144. package/src/secret-contract.ts +145 -0
  145. package/src/secret-input.ts +1 -13
  146. package/src/security-audit-shared.ts +69 -0
  147. package/src/security-audit.test.ts +61 -0
  148. package/src/security-audit.ts +1 -0
  149. package/src/send-result.ts +1 -1
  150. package/src/send-target.test.ts +9 -3
  151. package/src/send-target.ts +10 -4
  152. package/src/send.reply-fallback.test.ts +77 -2
  153. package/src/send.test.ts +386 -4
  154. package/src/send.ts +399 -86
  155. package/src/sequential-key.test.ts +72 -0
  156. package/src/sequential-key.ts +28 -0
  157. package/src/sequential-queue.test.ts +92 -0
  158. package/src/sequential-queue.ts +16 -0
  159. package/src/session-conversation.ts +42 -0
  160. package/src/session-route.ts +48 -0
  161. package/src/setup-core.ts +51 -0
  162. package/src/{onboarding.test.ts → setup-surface.test.ts} +52 -21
  163. package/src/setup-surface.ts +581 -0
  164. package/src/streaming-card.test.ts +138 -2
  165. package/src/streaming-card.ts +134 -18
  166. package/src/subagent-hooks.test.ts +603 -0
  167. package/src/subagent-hooks.ts +397 -0
  168. package/src/targets.ts +3 -13
  169. package/src/test-support/lifecycle-test-support.ts +479 -0
  170. package/src/thread-bindings.test.ts +143 -0
  171. package/src/thread-bindings.ts +330 -0
  172. package/src/tool-account-routing.test.ts +66 -8
  173. package/src/tool-account.test.ts +44 -0
  174. package/src/tool-account.ts +40 -17
  175. package/src/tool-factory-test-harness.ts +11 -8
  176. package/src/tool-result.ts +3 -1
  177. package/src/tools-config.ts +1 -1
  178. package/src/types.ts +16 -15
  179. package/src/typing.ts +10 -6
  180. package/src/wiki-schema.ts +1 -1
  181. package/src/wiki.ts +1 -7
  182. package/subagent-hooks-api.ts +31 -0
  183. package/tsconfig.json +16 -0
  184. package/src/feishu-command-handler.ts +0 -59
  185. package/src/onboarding.status.test.ts +0 -25
  186. package/src/onboarding.ts +0 -489
  187. package/src/send-message.ts +0 -71
  188. package/src/targets.test.ts +0 -70
@@ -0,0 +1,219 @@
1
+ import "./lifecycle.test-support.js";
2
+ import { createRuntimeEnv } from "openclaw/plugin-sdk/plugin-test-runtime";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import type { ClawdbotConfig } from "../runtime-api.js";
5
+ import {
6
+ getFeishuLifecycleTestMocks,
7
+ resetFeishuLifecycleTestMocks,
8
+ } from "./lifecycle.test-support.js";
9
+ import {
10
+ createFeishuLifecycleFixture,
11
+ createFeishuTextMessageEvent,
12
+ expectFeishuSingleEffectAcrossReplay,
13
+ installFeishuLifecycleReplyRuntime,
14
+ restoreFeishuLifecycleStateDir,
15
+ setFeishuLifecycleStateDir,
16
+ setupFeishuLifecycleHandler,
17
+ } from "./test-support/lifecycle-test-support.js";
18
+ import type { ResolvedFeishuAccount } from "./types.js";
19
+
20
+ const {
21
+ createEventDispatcherMock,
22
+ dispatchReplyFromConfigMock,
23
+ ensureConfiguredBindingRouteReadyMock,
24
+ finalizeInboundContextMock,
25
+ resolveAgentRouteMock,
26
+ resolveBoundConversationMock,
27
+ resolveConfiguredBindingRouteMock,
28
+ sendMessageFeishuMock,
29
+ withReplyDispatcherMock,
30
+ } = getFeishuLifecycleTestMocks();
31
+
32
+ let _handlers: Record<string, (data: unknown) => Promise<void>> = {};
33
+ let lastRuntime = createRuntimeEnv();
34
+ const originalStateDir = process.env.OPENCLAW_STATE_DIR;
35
+ const { cfg: lifecycleConfig, account: lifecycleAccount } = createFeishuLifecycleFixture({
36
+ accountId: "acct-acp",
37
+ appId: "cli_test",
38
+ appSecret: "secret_test",
39
+ channelConfig: {
40
+ groupPolicy: "open",
41
+ allowFrom: ["ou_sender_1"],
42
+ },
43
+ accountConfig: {
44
+ groupPolicy: "open",
45
+ groups: {
46
+ oc_group_topic: {
47
+ requireMention: false,
48
+ groupSessionScope: "group_topic",
49
+ replyInThread: "enabled",
50
+ },
51
+ },
52
+ },
53
+ extraConfig: {
54
+ session: { mainKey: "main", scope: "per-sender" },
55
+ },
56
+ }) as {
57
+ cfg: ClawdbotConfig;
58
+ account: ResolvedFeishuAccount;
59
+ };
60
+
61
+ async function setupLifecycleMonitor() {
62
+ lastRuntime = createRuntimeEnv();
63
+ return setupFeishuLifecycleHandler({
64
+ createEventDispatcherMock,
65
+ onRegister: (registered) => {
66
+ _handlers = registered;
67
+ },
68
+ runtime: lastRuntime,
69
+ cfg: lifecycleConfig,
70
+ account: lifecycleAccount,
71
+ handlerKey: "im.message.receive_v1",
72
+ missingHandlerMessage: "missing im.message.receive_v1 handler",
73
+ });
74
+ }
75
+
76
+ describe("Feishu ACP-init failure lifecycle", () => {
77
+ beforeEach(() => {
78
+ vi.useRealTimers();
79
+ resetFeishuLifecycleTestMocks();
80
+ _handlers = {};
81
+ lastRuntime = createRuntimeEnv();
82
+ setFeishuLifecycleStateDir("openclaw-feishu-acp-failure");
83
+
84
+ resolveBoundConversationMock.mockReturnValue(null);
85
+ resolveAgentRouteMock.mockReturnValue({
86
+ agentId: "main",
87
+ channel: "feishu",
88
+ accountId: "acct-acp",
89
+ sessionKey: "agent:main:feishu:group:oc_group_topic",
90
+ mainSessionKey: "agent:main:main",
91
+ matchedBy: "default",
92
+ });
93
+ resolveConfiguredBindingRouteMock.mockReturnValue({
94
+ bindingResolution: {
95
+ configuredBinding: {
96
+ spec: {
97
+ channel: "feishu",
98
+ accountId: "acct-acp",
99
+ conversationId: "oc_group_topic:topic:om_topic_root_1",
100
+ agentId: "codex",
101
+ mode: "persistent",
102
+ },
103
+ record: {
104
+ bindingId: "config:acp:feishu:acct-acp:oc_group_topic:topic:om_topic_root_1",
105
+ targetSessionKey: "agent:codex:acp:binding:feishu:acct-acp:abc123",
106
+ targetKind: "session",
107
+ conversation: {
108
+ channel: "feishu",
109
+ accountId: "acct-acp",
110
+ conversationId: "oc_group_topic:topic:om_topic_root_1",
111
+ parentConversationId: "oc_group_topic",
112
+ },
113
+ status: "active",
114
+ boundAt: 0,
115
+ metadata: { source: "config" },
116
+ },
117
+ },
118
+ statefulTarget: {
119
+ kind: "stateful",
120
+ driverId: "acp",
121
+ sessionKey: "agent:codex:acp:binding:feishu:acct-acp:abc123",
122
+ agentId: "codex",
123
+ },
124
+ },
125
+ configuredBinding: {
126
+ spec: {
127
+ channel: "feishu",
128
+ accountId: "acct-acp",
129
+ conversationId: "oc_group_topic:topic:om_topic_root_1",
130
+ agentId: "codex",
131
+ mode: "persistent",
132
+ },
133
+ },
134
+ route: {
135
+ agentId: "codex",
136
+ channel: "feishu",
137
+ accountId: "acct-acp",
138
+ sessionKey: "agent:codex:acp:binding:feishu:acct-acp:abc123",
139
+ mainSessionKey: "agent:codex:main",
140
+ matchedBy: "binding.channel",
141
+ },
142
+ });
143
+ ensureConfiguredBindingRouteReadyMock.mockResolvedValue({
144
+ ok: false,
145
+ error: "runtime unavailable",
146
+ });
147
+
148
+ dispatchReplyFromConfigMock.mockResolvedValue({
149
+ queuedFinal: false,
150
+ counts: { final: 0 },
151
+ });
152
+ withReplyDispatcherMock.mockImplementation(async ({ run }) => await run());
153
+
154
+ installFeishuLifecycleReplyRuntime({
155
+ resolveAgentRouteMock,
156
+ finalizeInboundContextMock,
157
+ dispatchReplyFromConfigMock,
158
+ withReplyDispatcherMock,
159
+ storePath: "/tmp/feishu-acp-failure-sessions.json",
160
+ });
161
+ });
162
+
163
+ afterEach(() => {
164
+ vi.useRealTimers();
165
+ restoreFeishuLifecycleStateDir(originalStateDir);
166
+ });
167
+
168
+ it("sends one ACP failure notice to the topic root across replay", async () => {
169
+ const onMessage = await setupLifecycleMonitor();
170
+ const event = createFeishuTextMessageEvent({
171
+ messageId: "om_topic_msg_1",
172
+ chatId: "oc_group_topic",
173
+ rootId: "om_topic_root_1",
174
+ threadId: "omt_topic_1",
175
+ text: "hello topic",
176
+ });
177
+
178
+ await expectFeishuSingleEffectAcrossReplay({
179
+ handler: onMessage,
180
+ event,
181
+ effectMock: sendMessageFeishuMock,
182
+ });
183
+
184
+ expect(lastRuntime?.error).not.toHaveBeenCalled();
185
+ expect(resolveConfiguredBindingRouteMock).toHaveBeenCalledTimes(1);
186
+ expect(ensureConfiguredBindingRouteReadyMock).toHaveBeenCalledTimes(1);
187
+ expect(sendMessageFeishuMock).toHaveBeenCalledTimes(1);
188
+ expect(sendMessageFeishuMock).toHaveBeenCalledWith(
189
+ expect.objectContaining({
190
+ accountId: "acct-acp",
191
+ to: "chat:oc_group_topic",
192
+ replyToMessageId: "om_topic_root_1",
193
+ replyInThread: true,
194
+ text: expect.stringContaining("runtime unavailable"),
195
+ }),
196
+ );
197
+ expect(dispatchReplyFromConfigMock).not.toHaveBeenCalled();
198
+ });
199
+
200
+ it("does not duplicate the ACP failure notice after the first send succeeds", async () => {
201
+ const onMessage = await setupLifecycleMonitor();
202
+ const event = createFeishuTextMessageEvent({
203
+ messageId: "om_topic_msg_2",
204
+ chatId: "oc_group_topic",
205
+ rootId: "om_topic_root_1",
206
+ threadId: "omt_topic_1",
207
+ text: "hello topic",
208
+ });
209
+
210
+ await expectFeishuSingleEffectAcrossReplay({
211
+ handler: onMessage,
212
+ event,
213
+ effectMock: sendMessageFeishuMock,
214
+ });
215
+
216
+ expect(sendMessageFeishuMock).toHaveBeenCalledTimes(1);
217
+ expect(lastRuntime?.error).not.toHaveBeenCalled();
218
+ });
219
+ });
@@ -0,0 +1,86 @@
1
+ import { normalizeOptionalString } from "openclaw/plugin-sdk/text-runtime";
2
+ import type { RuntimeEnv } from "../runtime-api.js";
3
+ import { waitForAbortableDelay } from "./async.js";
4
+ import { fetchBotIdentityForMonitor, type FeishuMonitorBotIdentity } from "./monitor.startup.js";
5
+ import { botNames, botOpenIds } from "./monitor.state.js";
6
+ import type { ResolvedFeishuAccount } from "./types.js";
7
+
8
+ // Delays must be >= PROBE_ERROR_TTL_MS (60s) so each retry makes a real network request
9
+ // instead of silently hitting the probe error cache.
10
+ const BOT_IDENTITY_RETRY_DELAYS_MS = [60_000, 120_000, 300_000, 600_000, 900_000];
11
+
12
+ export function applyBotIdentityState(
13
+ accountId: string,
14
+ identity: FeishuMonitorBotIdentity,
15
+ ): { botOpenId?: string; botName?: string } {
16
+ const botOpenId = normalizeOptionalString(identity.botOpenId);
17
+ const botName = normalizeOptionalString(identity.botName);
18
+
19
+ botOpenIds.set(accountId, botOpenId ?? "");
20
+ if (botName) {
21
+ botNames.set(accountId, botName);
22
+ } else {
23
+ botNames.delete(accountId);
24
+ }
25
+
26
+ return { botOpenId, botName };
27
+ }
28
+
29
+ async function retryBotIdentityProbe(
30
+ account: ResolvedFeishuAccount,
31
+ accountId: string,
32
+ runtime: RuntimeEnv | undefined,
33
+ abortSignal: AbortSignal | undefined,
34
+ ): Promise<void> {
35
+ const log = runtime?.log ?? console.log;
36
+ const error = runtime?.error ?? console.error;
37
+
38
+ for (let i = 0; i < BOT_IDENTITY_RETRY_DELAYS_MS.length; i += 1) {
39
+ if (abortSignal?.aborted) {
40
+ return;
41
+ }
42
+
43
+ const delayElapsed = await waitForAbortableDelay(BOT_IDENTITY_RETRY_DELAYS_MS[i], abortSignal);
44
+ if (!delayElapsed) {
45
+ return;
46
+ }
47
+
48
+ const identity = await fetchBotIdentityForMonitor(account, { runtime, abortSignal });
49
+ const resolved = applyBotIdentityState(accountId, identity);
50
+ if (resolved.botOpenId) {
51
+ log(
52
+ `feishu[${accountId}]: bot open_id recovered via background retry: ${resolved.botOpenId}`,
53
+ );
54
+ return;
55
+ }
56
+
57
+ const nextDelay = BOT_IDENTITY_RETRY_DELAYS_MS[i + 1];
58
+ error(
59
+ `feishu[${accountId}]: bot identity background retry ${i + 1}/${BOT_IDENTITY_RETRY_DELAYS_MS.length} failed` +
60
+ (nextDelay ? `; next attempt in ${nextDelay / 1000}s` : ""),
61
+ );
62
+ }
63
+
64
+ error(
65
+ `feishu[${accountId}]: bot identity background retry exhausted; requireMention group messages may be skipped until restart`,
66
+ );
67
+ }
68
+
69
+ export function startBotIdentityRecovery(params: {
70
+ account: ResolvedFeishuAccount;
71
+ accountId: string;
72
+ runtime?: RuntimeEnv;
73
+ abortSignal?: AbortSignal;
74
+ }): void {
75
+ const { account, accountId, runtime, abortSignal } = params;
76
+ const log = runtime?.log ?? console.log;
77
+
78
+ log(
79
+ `feishu[${accountId}]: bot open_id unknown; starting background retry (delays: ${BOT_IDENTITY_RETRY_DELAYS_MS.map((delay) => `${delay / 1000}s`).join(", ")})`,
80
+ );
81
+ log(
82
+ `feishu[${accountId}]: requireMention group messages stay gated until bot identity recovery succeeds`,
83
+ );
84
+
85
+ void retryBotIdentityProbe(account, accountId, runtime, abortSignal);
86
+ }
@@ -0,0 +1,165 @@
1
+ import type { ClawdbotConfig, HistoryEntry, RuntimeEnv } from "../runtime-api.js";
2
+ import { handleFeishuMessage, type FeishuMessageEvent } from "./bot.js";
3
+ import { maybeHandleFeishuQuickActionMenu } from "./card-ux-launcher.js";
4
+ import {
5
+ claimUnprocessedFeishuMessage,
6
+ recordProcessedFeishuMessage,
7
+ releaseFeishuMessageProcessing,
8
+ } from "./dedup.js";
9
+ import { botNames, botOpenIds } from "./monitor.state.js";
10
+ import { isFeishuRetryableSyntheticEventError } from "./monitor.synthetic-error.js";
11
+
12
+ type FeishuBotMenuEvent = {
13
+ event_key?: string;
14
+ timestamp?: string | number;
15
+ operator?: {
16
+ operator_name?: string;
17
+ operator_id?: { open_id?: string; user_id?: string; union_id?: string };
18
+ };
19
+ };
20
+
21
+ function readString(value: unknown): string | undefined {
22
+ return typeof value === "string" ? value : undefined;
23
+ }
24
+
25
+ function readStringOrNumber(value: unknown): string | number | undefined {
26
+ return typeof value === "string" || typeof value === "number" ? value : undefined;
27
+ }
28
+
29
+ function isRecord(value: unknown): value is Record<string, unknown> {
30
+ return typeof value === "object" && value !== null && !Array.isArray(value);
31
+ }
32
+
33
+ function parseFeishuBotMenuEvent(value: unknown): FeishuBotMenuEvent | null {
34
+ if (!isRecord(value)) {
35
+ return null;
36
+ }
37
+ const operator = value.operator;
38
+ if (operator !== undefined && !isRecord(operator)) {
39
+ return null;
40
+ }
41
+ return {
42
+ event_key: readString(value.event_key),
43
+ timestamp: readStringOrNumber(value.timestamp),
44
+ operator: operator
45
+ ? {
46
+ operator_name: readString(operator.operator_name),
47
+ operator_id: isRecord(operator.operator_id)
48
+ ? {
49
+ open_id: readString(operator.operator_id.open_id),
50
+ user_id: readString(operator.operator_id.user_id),
51
+ union_id: readString(operator.operator_id.union_id),
52
+ }
53
+ : undefined,
54
+ }
55
+ : undefined,
56
+ };
57
+ }
58
+
59
+ export function createFeishuBotMenuHandler(params: {
60
+ cfg: ClawdbotConfig;
61
+ accountId: string;
62
+ runtime?: RuntimeEnv;
63
+ chatHistories: Map<string, HistoryEntry[]>;
64
+ fireAndForget?: boolean;
65
+ getBotOpenId?: (accountId: string) => string | undefined;
66
+ getBotName?: (accountId: string) => string | undefined;
67
+ }): (data: unknown) => Promise<void> {
68
+ const { cfg, accountId, runtime, chatHistories, fireAndForget } = params;
69
+ const log = runtime?.log ?? console.log;
70
+ const error = runtime?.error ?? console.error;
71
+ const getBotOpenId = params.getBotOpenId ?? ((id) => botOpenIds.get(id));
72
+ const getBotName = params.getBotName ?? ((id) => botNames.get(id));
73
+
74
+ return async (data) => {
75
+ try {
76
+ const event = parseFeishuBotMenuEvent(data);
77
+ if (!event) {
78
+ return;
79
+ }
80
+ const operatorOpenId = event.operator?.operator_id?.open_id?.trim();
81
+ const eventKey = event.event_key?.trim();
82
+ if (!operatorOpenId || !eventKey) {
83
+ return;
84
+ }
85
+ const syntheticEvent: FeishuMessageEvent = {
86
+ sender: {
87
+ sender_id: {
88
+ open_id: operatorOpenId,
89
+ user_id: event.operator?.operator_id?.user_id,
90
+ union_id: event.operator?.operator_id?.union_id,
91
+ },
92
+ sender_type: "user",
93
+ },
94
+ message: {
95
+ message_id: `bot-menu:${eventKey}:${event.timestamp ?? Date.now()}`,
96
+ suppress_reply_target: true,
97
+ chat_id: `p2p:${operatorOpenId}`,
98
+ chat_type: "p2p",
99
+ message_type: "text",
100
+ content: JSON.stringify({
101
+ text: `/menu ${eventKey}`,
102
+ }),
103
+ },
104
+ };
105
+ const syntheticMessageId = syntheticEvent.message.message_id;
106
+ const claim = await claimUnprocessedFeishuMessage({
107
+ messageId: syntheticMessageId,
108
+ namespace: accountId,
109
+ log,
110
+ });
111
+ if (claim === "duplicate") {
112
+ log(`feishu[${accountId}]: dropping duplicate bot-menu event for ${syntheticMessageId}`);
113
+ return;
114
+ }
115
+ if (claim === "inflight") {
116
+ log(`feishu[${accountId}]: dropping in-flight bot-menu event for ${syntheticMessageId}`);
117
+ return;
118
+ }
119
+ const handleLegacyMenu = () =>
120
+ handleFeishuMessage({
121
+ cfg,
122
+ event: syntheticEvent,
123
+ botOpenId: getBotOpenId(accountId),
124
+ botName: getBotName(accountId),
125
+ runtime,
126
+ chatHistories,
127
+ accountId,
128
+ processingClaimHeld: true,
129
+ });
130
+
131
+ const promise = maybeHandleFeishuQuickActionMenu({
132
+ cfg,
133
+ eventKey,
134
+ operatorOpenId,
135
+ runtime,
136
+ accountId,
137
+ })
138
+ .then(async (handledMenu) => {
139
+ if (handledMenu) {
140
+ await recordProcessedFeishuMessage(syntheticMessageId, accountId, log);
141
+ releaseFeishuMessageProcessing(syntheticMessageId, accountId);
142
+ return;
143
+ }
144
+ return await handleLegacyMenu();
145
+ })
146
+ .catch(async (err) => {
147
+ if (isFeishuRetryableSyntheticEventError(err)) {
148
+ releaseFeishuMessageProcessing(syntheticMessageId, accountId);
149
+ } else {
150
+ await recordProcessedFeishuMessage(syntheticMessageId, accountId, log);
151
+ }
152
+ throw err;
153
+ });
154
+ if (fireAndForget) {
155
+ promise.catch((err) => {
156
+ error(`feishu[${accountId}]: error handling bot menu event: ${String(err)}`);
157
+ });
158
+ return;
159
+ }
160
+ await promise;
161
+ } catch (err) {
162
+ error(`feishu[${accountId}]: error handling bot menu event: ${String(err)}`);
163
+ }
164
+ };
165
+ }
@@ -0,0 +1,224 @@
1
+ import { createRuntimeEnv } from "openclaw/plugin-sdk/plugin-test-runtime";
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import "./lifecycle.test-support.js";
4
+ import {
5
+ getFeishuLifecycleTestMocks,
6
+ resetFeishuLifecycleTestMocks,
7
+ } from "./lifecycle.test-support.js";
8
+ import {
9
+ createFeishuLifecycleConfig,
10
+ createFeishuLifecycleReplyDispatcher,
11
+ createResolvedFeishuLifecycleAccount,
12
+ expectFeishuReplyDispatcherSentFinalReplyOnce,
13
+ expectFeishuReplyPipelineDedupedAcrossReplay,
14
+ expectFeishuReplyPipelineDedupedAfterPostSendFailure,
15
+ expectFeishuSingleEffectAcrossReplay,
16
+ installFeishuLifecycleReplyRuntime,
17
+ mockFeishuReplyOnceDispatch,
18
+ restoreFeishuLifecycleStateDir,
19
+ setFeishuLifecycleStateDir,
20
+ setupFeishuLifecycleHandler,
21
+ } from "./test-support/lifecycle-test-support.js";
22
+
23
+ const {
24
+ createEventDispatcherMock,
25
+ createFeishuReplyDispatcherMock,
26
+ dispatchReplyFromConfigMock,
27
+ finalizeInboundContextMock,
28
+ resolveAgentRouteMock,
29
+ resolveBoundConversationMock,
30
+ sendCardFeishuMock,
31
+ touchBindingMock,
32
+ withReplyDispatcherMock,
33
+ } = getFeishuLifecycleTestMocks();
34
+
35
+ let _handlers: Record<string, (data: unknown) => Promise<void>> = {};
36
+ let lastRuntime = createRuntimeEnv();
37
+ const originalStateDir = process.env.OPENCLAW_STATE_DIR;
38
+ const lifecycleConfig = createFeishuLifecycleConfig({
39
+ accountId: "acct-menu",
40
+ appId: "cli_test",
41
+ appSecret: "secret_test",
42
+ channelConfig: {
43
+ dmPolicy: "open",
44
+ allowFrom: ["ou_user1"],
45
+ },
46
+ accountConfig: {
47
+ dmPolicy: "open",
48
+ allowFrom: ["ou_user1"],
49
+ },
50
+ });
51
+
52
+ const lifecycleAccount = createResolvedFeishuLifecycleAccount({
53
+ accountId: "acct-menu",
54
+ appId: "cli_test",
55
+ appSecret: "secret_test",
56
+ config: {
57
+ dmPolicy: "open",
58
+ allowFrom: ["ou_user1"],
59
+ },
60
+ });
61
+
62
+ function createBotMenuEvent(params: { eventKey: string; timestamp: string }) {
63
+ return {
64
+ event_key: params.eventKey,
65
+ timestamp: params.timestamp,
66
+ operator: {
67
+ operator_id: {
68
+ open_id: "ou_user1",
69
+ user_id: "user_1",
70
+ union_id: "union_1",
71
+ },
72
+ },
73
+ };
74
+ }
75
+
76
+ async function setupLifecycleMonitor() {
77
+ lastRuntime = createRuntimeEnv();
78
+ return setupFeishuLifecycleHandler({
79
+ createEventDispatcherMock,
80
+ onRegister: (registered) => {
81
+ _handlers = registered;
82
+ },
83
+ runtime: lastRuntime,
84
+ cfg: lifecycleConfig,
85
+ account: lifecycleAccount,
86
+ handlerKey: "application.bot.menu_v6",
87
+ missingHandlerMessage: "missing application.bot.menu_v6 handler",
88
+ });
89
+ }
90
+
91
+ describe("Feishu bot-menu lifecycle", () => {
92
+ beforeEach(() => {
93
+ vi.useRealTimers();
94
+ resetFeishuLifecycleTestMocks();
95
+ _handlers = {};
96
+ lastRuntime = createRuntimeEnv();
97
+ setFeishuLifecycleStateDir("openclaw-feishu-bot-menu");
98
+
99
+ createFeishuReplyDispatcherMock.mockReturnValue(createFeishuLifecycleReplyDispatcher());
100
+
101
+ resolveBoundConversationMock.mockImplementation(() => ({
102
+ bindingId: "binding-menu",
103
+ targetSessionKey: "agent:bound-agent:feishu:direct:ou_user1",
104
+ }));
105
+
106
+ resolveAgentRouteMock.mockReturnValue({
107
+ agentId: "main",
108
+ channel: "feishu",
109
+ accountId: "acct-menu",
110
+ sessionKey: "agent:main:feishu:direct:ou_user1",
111
+ mainSessionKey: "agent:main:main",
112
+ matchedBy: "default",
113
+ });
114
+
115
+ mockFeishuReplyOnceDispatch({
116
+ dispatchReplyFromConfigMock,
117
+ replyText: "menu reply once",
118
+ });
119
+
120
+ withReplyDispatcherMock.mockImplementation(async ({ run }) => await run());
121
+
122
+ installFeishuLifecycleReplyRuntime({
123
+ resolveAgentRouteMock,
124
+ finalizeInboundContextMock,
125
+ dispatchReplyFromConfigMock,
126
+ withReplyDispatcherMock,
127
+ storePath: "/tmp/feishu-bot-menu-sessions.json",
128
+ });
129
+ });
130
+
131
+ afterEach(() => {
132
+ vi.useRealTimers();
133
+ restoreFeishuLifecycleStateDir(originalStateDir);
134
+ });
135
+
136
+ it("opens one launcher card across duplicate quick-actions replay", async () => {
137
+ const onBotMenu = await setupLifecycleMonitor();
138
+ const event = createBotMenuEvent({
139
+ eventKey: "quick-actions",
140
+ timestamp: "1700000000000",
141
+ });
142
+
143
+ await expectFeishuSingleEffectAcrossReplay({
144
+ handler: onBotMenu,
145
+ event,
146
+ effectMock: sendCardFeishuMock,
147
+ });
148
+
149
+ expect(lastRuntime?.error).not.toHaveBeenCalled();
150
+ expect(sendCardFeishuMock).toHaveBeenCalledTimes(1);
151
+ expect(sendCardFeishuMock).toHaveBeenCalledWith(
152
+ expect.objectContaining({
153
+ accountId: "acct-menu",
154
+ to: "user:ou_user1",
155
+ }),
156
+ );
157
+ expect(dispatchReplyFromConfigMock).not.toHaveBeenCalled();
158
+ expect(createFeishuReplyDispatcherMock).not.toHaveBeenCalled();
159
+ });
160
+
161
+ it("falls back once to the legacy routed reply path when launcher rendering fails", async () => {
162
+ const onBotMenu = await setupLifecycleMonitor();
163
+ const event = createBotMenuEvent({
164
+ eventKey: "quick-actions",
165
+ timestamp: "1700000000001",
166
+ });
167
+ sendCardFeishuMock.mockRejectedValueOnce(new Error("boom"));
168
+
169
+ await expectFeishuReplyPipelineDedupedAcrossReplay({
170
+ handler: onBotMenu,
171
+ event,
172
+ dispatchReplyFromConfigMock,
173
+ createFeishuReplyDispatcherMock,
174
+ waitTimeoutMs: 5_000,
175
+ });
176
+
177
+ expect(lastRuntime?.error).not.toHaveBeenCalled();
178
+ expect(sendCardFeishuMock).toHaveBeenCalledTimes(1);
179
+ expect(dispatchReplyFromConfigMock).toHaveBeenCalledTimes(1);
180
+ expect(createFeishuReplyDispatcherMock).toHaveBeenCalledTimes(1);
181
+ expect(createFeishuReplyDispatcherMock).toHaveBeenCalledWith(
182
+ expect.objectContaining({
183
+ accountId: "acct-menu",
184
+ chatId: "p2p:ou_user1",
185
+ replyToMessageId: undefined,
186
+ }),
187
+ );
188
+ expect(finalizeInboundContextMock).toHaveBeenCalledWith(
189
+ expect.objectContaining({
190
+ AccountId: "acct-menu",
191
+ SessionKey: "agent:bound-agent:feishu:direct:ou_user1",
192
+ MessageSid: "bot-menu:quick-actions:1700000000001",
193
+ }),
194
+ );
195
+ expect(touchBindingMock).toHaveBeenCalledWith("binding-menu");
196
+
197
+ expectFeishuReplyDispatcherSentFinalReplyOnce({ createFeishuReplyDispatcherMock });
198
+ });
199
+
200
+ it("does not duplicate delivery when launcher fallback hits a post-send failure", async () => {
201
+ const onBotMenu = await setupLifecycleMonitor();
202
+ const event = createBotMenuEvent({
203
+ eventKey: "quick-actions",
204
+ timestamp: "1700000000002",
205
+ });
206
+ sendCardFeishuMock.mockRejectedValueOnce(new Error("boom"));
207
+ dispatchReplyFromConfigMock.mockImplementationOnce(async ({ dispatcher }) => {
208
+ await dispatcher.sendFinalReply({ text: "menu reply once" });
209
+ throw new Error("post-send failure");
210
+ });
211
+
212
+ await expectFeishuReplyPipelineDedupedAfterPostSendFailure({
213
+ handler: onBotMenu,
214
+ event,
215
+ dispatchReplyFromConfigMock,
216
+ runtimeErrorMock: lastRuntime?.error as ReturnType<typeof vi.fn>,
217
+ waitTimeoutMs: 5_000,
218
+ });
219
+
220
+ expect(sendCardFeishuMock).toHaveBeenCalledTimes(1);
221
+ expect(dispatchReplyFromConfigMock).toHaveBeenCalledTimes(1);
222
+ expectFeishuReplyDispatcherSentFinalReplyOnce({ createFeishuReplyDispatcherMock });
223
+ });
224
+ });