@kodelyth/feishu 2026.5.42 → 2026.6.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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
@@ -1,219 +0,0 @@
1
- import "./lifecycle.test-support.js";
2
- import { createRuntimeEnv } from "klaw/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.KLAW_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("klaw-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
- });
@@ -1,86 +0,0 @@
1
- import { normalizeOptionalString } from "klaw/plugin-sdk/string-coerce-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
- }
@@ -1,165 +0,0 @@
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
- }
@@ -1,224 +0,0 @@
1
- import { createRuntimeEnv } from "klaw/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.KLAW_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("klaw-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
- });