@kodelyth/feishu 2026.5.39 → 2026.5.42

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 (238) hide show
  1. package/api.ts +32 -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/dist/accounts-D0ow-lRb.js +429 -0
  6. package/dist/api.js +2308 -0
  7. package/dist/app-registration-DBSnysKJ.js +184 -0
  8. package/dist/audio-preflight.runtime-Dpjbn-7r.js +7 -0
  9. package/dist/channel-13WQvQ0u.js +2115 -0
  10. package/dist/channel-entry.js +22 -0
  11. package/dist/channel-plugin-api.js +2 -0
  12. package/dist/channel.runtime-JMJonrJ4.js +729 -0
  13. package/dist/client-D1pzbBGo.js +157 -0
  14. package/dist/contract-api.js +9 -0
  15. package/dist/conversation-id-_58ecqlx.js +139 -0
  16. package/dist/drive-CgHOluXx.js +883 -0
  17. package/dist/index.js +68 -0
  18. package/dist/monitor-oWptK0zL.js +60 -0
  19. package/dist/monitor.account-DHaWlslg.js +5207 -0
  20. package/dist/monitor.state-C211a4tX.js +100 -0
  21. package/dist/probe-CF4duEpK.js +149 -0
  22. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  23. package/dist/runtime-DSh5rL_d.js +8 -0
  24. package/dist/runtime-api.js +14 -0
  25. package/dist/secret-contract-NSee-WzN.js +119 -0
  26. package/dist/secret-contract-api.js +2 -0
  27. package/dist/security-audit-DWVC0vSK.js +11 -0
  28. package/dist/security-audit-shared-Dpcwxeft.js +38 -0
  29. package/dist/security-contract-api.js +2 -0
  30. package/dist/send-DfZuV4Fi.js +1212 -0
  31. package/dist/session-conversation-Duaukbnl.js +27 -0
  32. package/dist/session-key-api.js +2 -0
  33. package/dist/setup-api.js +2 -0
  34. package/dist/setup-entry.js +15 -0
  35. package/dist/subagent-hooks-Dtegs0kh.js +235 -0
  36. package/dist/subagent-hooks-api.js +23 -0
  37. package/dist/targets-DFskxX4p.js +48 -0
  38. package/dist/thread-bindings-DI7lVSOE.js +222 -0
  39. package/index.ts +82 -0
  40. package/klaw.plugin.json +47 -1712
  41. package/package.json +4 -4
  42. package/runtime-api.ts +52 -0
  43. package/secret-contract-api.ts +5 -0
  44. package/security-contract-api.ts +1 -0
  45. package/session-key-api.ts +1 -0
  46. package/setup-api.ts +3 -0
  47. package/setup-entry.test.ts +19 -0
  48. package/setup-entry.ts +13 -0
  49. package/src/accounts.test.ts +480 -0
  50. package/src/accounts.ts +333 -0
  51. package/src/agent-config.ts +21 -0
  52. package/src/app-registration.ts +331 -0
  53. package/src/approval-auth.test.ts +24 -0
  54. package/src/approval-auth.ts +25 -0
  55. package/src/async.test.ts +35 -0
  56. package/src/async.ts +104 -0
  57. package/src/audio-preflight.runtime.ts +9 -0
  58. package/src/bitable.test.ts +136 -0
  59. package/src/bitable.ts +762 -0
  60. package/src/bot-content.ts +485 -0
  61. package/src/bot-group-name.test.ts +116 -0
  62. package/src/bot-runtime-api.ts +12 -0
  63. package/src/bot-sender-name.ts +125 -0
  64. package/src/bot.broadcast.test.ts +523 -0
  65. package/src/bot.card-action.test.ts +552 -0
  66. package/src/bot.checkBotMentioned.test.ts +265 -0
  67. package/src/bot.helpers.test.ts +135 -0
  68. package/src/bot.stripBotMention.test.ts +126 -0
  69. package/src/bot.test.ts +3671 -0
  70. package/src/bot.ts +1703 -0
  71. package/src/card-action.ts +447 -0
  72. package/src/card-interaction.test.ts +131 -0
  73. package/src/card-interaction.ts +159 -0
  74. package/src/card-test-helpers.ts +54 -0
  75. package/src/card-ux-approval.ts +65 -0
  76. package/src/card-ux-launcher.test.ts +106 -0
  77. package/src/card-ux-launcher.ts +121 -0
  78. package/src/card-ux-shared.ts +33 -0
  79. package/src/channel-runtime-api.ts +16 -0
  80. package/src/channel.runtime.ts +47 -0
  81. package/src/channel.test.ts +1151 -0
  82. package/src/channel.ts +1423 -0
  83. package/src/chat-schema.ts +25 -0
  84. package/src/chat.test.ts +240 -0
  85. package/src/chat.ts +188 -0
  86. package/src/client-timeout.ts +42 -0
  87. package/src/client.test.ts +447 -0
  88. package/src/client.ts +262 -0
  89. package/src/comment-dispatcher-runtime-api.ts +6 -0
  90. package/src/comment-dispatcher.test.ts +185 -0
  91. package/src/comment-dispatcher.ts +107 -0
  92. package/src/comment-handler-runtime-api.ts +3 -0
  93. package/src/comment-handler.test.ts +592 -0
  94. package/src/comment-handler.ts +303 -0
  95. package/src/comment-reaction.test.ts +138 -0
  96. package/src/comment-reaction.ts +259 -0
  97. package/src/comment-shared.test.ts +183 -0
  98. package/src/comment-shared.ts +406 -0
  99. package/src/comment-target.ts +44 -0
  100. package/src/config-schema.test.ts +326 -0
  101. package/src/config-schema.ts +335 -0
  102. package/src/conversation-id.test.ts +18 -0
  103. package/src/conversation-id.ts +199 -0
  104. package/src/dedup-runtime-api.ts +1 -0
  105. package/src/dedup.ts +141 -0
  106. package/src/dedupe-key.ts +72 -0
  107. package/src/directory.static.ts +61 -0
  108. package/src/directory.test.ts +141 -0
  109. package/src/directory.ts +124 -0
  110. package/src/doc-schema.ts +182 -0
  111. package/src/docx-batch-insert.test.ts +116 -0
  112. package/src/docx-batch-insert.ts +223 -0
  113. package/src/docx-color-text.ts +154 -0
  114. package/src/docx-table-ops.test.ts +53 -0
  115. package/src/docx-table-ops.ts +316 -0
  116. package/src/docx-types.ts +38 -0
  117. package/src/docx.account-selection.test.ts +95 -0
  118. package/src/docx.test.ts +701 -0
  119. package/src/docx.ts +1596 -0
  120. package/src/drive-schema.ts +92 -0
  121. package/src/drive.test.ts +1237 -0
  122. package/src/drive.ts +829 -0
  123. package/src/dynamic-agent.test.ts +155 -0
  124. package/src/dynamic-agent.ts +143 -0
  125. package/src/event-types.ts +45 -0
  126. package/src/external-keys.test.ts +20 -0
  127. package/src/external-keys.ts +19 -0
  128. package/src/lifecycle.test-support.ts +220 -0
  129. package/src/media.test.ts +955 -0
  130. package/src/media.ts +1105 -0
  131. package/src/mention-target.types.ts +5 -0
  132. package/src/mention.ts +114 -0
  133. package/src/message-action-contract.ts +13 -0
  134. package/src/monitor-state-runtime-api.ts +7 -0
  135. package/src/monitor-transport-runtime-api.ts +10 -0
  136. package/src/monitor.account.ts +492 -0
  137. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  138. package/src/monitor.bot-identity.ts +86 -0
  139. package/src/monitor.bot-menu-handler.ts +165 -0
  140. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  141. package/src/monitor.bot-menu.test.ts +188 -0
  142. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  143. package/src/monitor.card-action.lifecycle.test-support.ts +421 -0
  144. package/src/monitor.cleanup.test.ts +383 -0
  145. package/src/monitor.comment-notice-handler.ts +105 -0
  146. package/src/monitor.comment.test.ts +967 -0
  147. package/src/monitor.comment.ts +1386 -0
  148. package/src/monitor.lifecycle.test.ts +4 -0
  149. package/src/monitor.message-handler.ts +350 -0
  150. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  151. package/src/monitor.reaction.test.ts +739 -0
  152. package/src/monitor.startup.test.ts +213 -0
  153. package/src/monitor.startup.ts +74 -0
  154. package/src/monitor.state.defaults.test.ts +46 -0
  155. package/src/monitor.state.ts +170 -0
  156. package/src/monitor.synthetic-error.ts +18 -0
  157. package/src/monitor.test-mocks.ts +46 -0
  158. package/src/monitor.transport.ts +451 -0
  159. package/src/monitor.ts +100 -0
  160. package/src/monitor.webhook-e2e.test.ts +279 -0
  161. package/src/monitor.webhook-security.test.ts +389 -0
  162. package/src/monitor.webhook.test-helpers.ts +116 -0
  163. package/src/outbound-runtime-api.ts +1 -0
  164. package/src/outbound.test.ts +1118 -0
  165. package/src/outbound.ts +785 -0
  166. package/src/perm-schema.ts +52 -0
  167. package/src/perm.ts +170 -0
  168. package/src/pins.ts +108 -0
  169. package/src/policy.test.ts +223 -0
  170. package/src/policy.ts +318 -0
  171. package/src/post.test.ts +105 -0
  172. package/src/post.ts +275 -0
  173. package/src/probe.test.ts +283 -0
  174. package/src/probe.ts +166 -0
  175. package/src/processing-claims.ts +59 -0
  176. package/src/qr-terminal.ts +1 -0
  177. package/src/reactions.ts +123 -0
  178. package/src/reasoning-preview.test.ts +113 -0
  179. package/src/reasoning-preview.ts +28 -0
  180. package/src/reply-dispatcher-runtime-api.ts +7 -0
  181. package/src/reply-dispatcher.test.ts +1513 -0
  182. package/src/reply-dispatcher.ts +748 -0
  183. package/src/runtime.ts +9 -0
  184. package/src/secret-contract.ts +145 -0
  185. package/src/secret-input.ts +1 -0
  186. package/src/security-audit-shared.ts +69 -0
  187. package/src/security-audit.test.ts +59 -0
  188. package/src/security-audit.ts +1 -0
  189. package/src/send-result.ts +80 -0
  190. package/src/send-target.test.ts +86 -0
  191. package/src/send-target.ts +35 -0
  192. package/src/send.reply-fallback.test.ts +417 -0
  193. package/src/send.test.ts +621 -0
  194. package/src/send.ts +861 -0
  195. package/src/sequential-key.test.ts +72 -0
  196. package/src/sequential-key.ts +25 -0
  197. package/src/sequential-queue.test.ts +165 -0
  198. package/src/sequential-queue.ts +86 -0
  199. package/src/session-conversation.ts +42 -0
  200. package/src/session-route.ts +48 -0
  201. package/src/setup-core.ts +51 -0
  202. package/src/setup-surface.test.ts +484 -0
  203. package/src/setup-surface.ts +618 -0
  204. package/src/streaming-card.test.ts +397 -0
  205. package/src/streaming-card.ts +571 -0
  206. package/src/subagent-hooks.test.ts +627 -0
  207. package/src/subagent-hooks.ts +413 -0
  208. package/src/targets.ts +97 -0
  209. package/src/test-support/lifecycle-test-support.ts +454 -0
  210. package/src/thread-bindings.test.ts +180 -0
  211. package/src/thread-bindings.ts +331 -0
  212. package/src/tool-account-routing.test.ts +250 -0
  213. package/src/tool-account.test.ts +44 -0
  214. package/src/tool-account.ts +93 -0
  215. package/src/tool-factory-test-harness.ts +79 -0
  216. package/src/tool-result.test.ts +32 -0
  217. package/src/tool-result.ts +16 -0
  218. package/src/tools-config.test.ts +21 -0
  219. package/src/tools-config.ts +22 -0
  220. package/src/types.ts +106 -0
  221. package/src/typing.test.ts +144 -0
  222. package/src/typing.ts +214 -0
  223. package/src/wiki-schema.ts +69 -0
  224. package/src/wiki.ts +270 -0
  225. package/subagent-hooks-api.ts +31 -0
  226. package/tsconfig.json +16 -0
  227. package/api.js +0 -7
  228. package/channel-entry.js +0 -7
  229. package/channel-plugin-api.js +0 -7
  230. package/contract-api.js +0 -7
  231. package/index.js +0 -7
  232. package/runtime-api.js +0 -7
  233. package/secret-contract-api.js +0 -7
  234. package/security-contract-api.js +0 -7
  235. package/session-key-api.js +0 -7
  236. package/setup-api.js +0 -7
  237. package/setup-entry.js +0 -7
  238. package/subagent-hooks-api.js +0 -7
@@ -0,0 +1,125 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
2
+ import { createFeishuClient } from "./client.js";
3
+ import type { ResolvedFeishuAccount } from "./types.js";
4
+
5
+ export type FeishuPermissionError = {
6
+ code: number;
7
+ message: string;
8
+ grantUrl?: string;
9
+ };
10
+
11
+ type SenderNameResult = {
12
+ name?: string;
13
+ permissionError?: FeishuPermissionError;
14
+ };
15
+
16
+ type FeishuContactUserGetResponse = Awaited<
17
+ ReturnType<ReturnType<typeof createFeishuClient>["contact"]["user"]["get"]>
18
+ >;
19
+
20
+ type FeishuLogger = (...args: unknown[]) => void;
21
+
22
+ const IGNORED_PERMISSION_SCOPE_TOKENS = ["contact:contact.base:readonly"];
23
+ const FEISHU_SCOPE_CORRECTIONS: Record<string, string> = {
24
+ "contact:contact.base:readonly": "contact:user.base:readonly",
25
+ };
26
+ const SENDER_NAME_TTL_MS = 10 * 60 * 1000;
27
+ const senderNameCache = new Map<string, { name: string; expireAt: number }>();
28
+
29
+ function correctFeishuScopeInUrl(url: string): string {
30
+ let corrected = url;
31
+ for (const [wrong, right] of Object.entries(FEISHU_SCOPE_CORRECTIONS)) {
32
+ corrected = corrected.replaceAll(encodeURIComponent(wrong), encodeURIComponent(right));
33
+ corrected = corrected.replaceAll(wrong, right);
34
+ }
35
+ return corrected;
36
+ }
37
+
38
+ function shouldSuppressPermissionErrorNotice(permissionError: FeishuPermissionError): boolean {
39
+ const message = normalizeLowercaseStringOrEmpty(permissionError.message);
40
+ return IGNORED_PERMISSION_SCOPE_TOKENS.some((token) => message.includes(token));
41
+ }
42
+
43
+ function extractPermissionError(err: unknown): FeishuPermissionError | null {
44
+ if (!err || typeof err !== "object") {
45
+ return null;
46
+ }
47
+ const axiosErr = err as { response?: { data?: unknown } };
48
+ const data = axiosErr.response?.data;
49
+ if (!data || typeof data !== "object") {
50
+ return null;
51
+ }
52
+ const feishuErr = data as { code?: number; msg?: string };
53
+ if (feishuErr.code !== 99991672) {
54
+ return null;
55
+ }
56
+ const msg = feishuErr.msg ?? "";
57
+ const urlMatch = msg.match(/https:\/\/[^\s,]+\/app\/[^\s,]+/);
58
+ return {
59
+ code: feishuErr.code,
60
+ message: msg,
61
+ grantUrl: urlMatch?.[0] ? correctFeishuScopeInUrl(urlMatch[0]) : undefined,
62
+ };
63
+ }
64
+
65
+ function resolveSenderLookupIdType(senderId: string): "open_id" | "user_id" | "union_id" {
66
+ const trimmed = senderId.trim();
67
+ if (trimmed.startsWith("ou_")) {
68
+ return "open_id";
69
+ }
70
+ if (trimmed.startsWith("on_")) {
71
+ return "union_id";
72
+ }
73
+ return "user_id";
74
+ }
75
+
76
+ export async function resolveFeishuSenderName(params: {
77
+ account: ResolvedFeishuAccount;
78
+ senderId: string;
79
+ log: FeishuLogger;
80
+ }): Promise<SenderNameResult> {
81
+ const { account, senderId, log } = params;
82
+ if (!account.configured) {
83
+ return {};
84
+ }
85
+
86
+ const normalizedSenderId = senderId.trim();
87
+ if (!normalizedSenderId) {
88
+ return {};
89
+ }
90
+
91
+ const cached = senderNameCache.get(normalizedSenderId);
92
+ const now = Date.now();
93
+ if (cached && cached.expireAt > now) {
94
+ return { name: cached.name };
95
+ }
96
+
97
+ try {
98
+ const client = createFeishuClient(account);
99
+ const userIdType = resolveSenderLookupIdType(normalizedSenderId);
100
+ const res: FeishuContactUserGetResponse = await client.contact.user.get({
101
+ path: { user_id: normalizedSenderId },
102
+ params: { user_id_type: userIdType },
103
+ });
104
+ const user = res.data?.user;
105
+ const name = user?.name ?? user?.nickname ?? user?.en_name;
106
+
107
+ if (name) {
108
+ senderNameCache.set(normalizedSenderId, { name, expireAt: now + SENDER_NAME_TTL_MS });
109
+ return { name };
110
+ }
111
+ return {};
112
+ } catch (err) {
113
+ const permErr = extractPermissionError(err);
114
+ if (permErr) {
115
+ if (shouldSuppressPermissionErrorNotice(permErr)) {
116
+ log(`feishu: ignoring stale permission scope error: ${permErr.message}`);
117
+ return {};
118
+ }
119
+ log(`feishu: permission error resolving sender name: code=${permErr.code}`);
120
+ return { permissionError: permErr };
121
+ }
122
+ log(`feishu: failed to resolve sender name for ${normalizedSenderId}: ${String(err)}`);
123
+ return {};
124
+ }
125
+ }
@@ -0,0 +1,523 @@
1
+ import type { EnvelopeFormatOptions } from "klaw/plugin-sdk/channel-inbound";
2
+ import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
3
+ import type { ClawdbotConfig, PluginRuntime } from "../runtime-api.js";
4
+ import type { FeishuMessageEvent } from "./bot.js";
5
+ import { clearGroupNameCache, handleFeishuMessage } from "./bot.js";
6
+ import { setFeishuRuntime } from "./runtime.js";
7
+
8
+ const { mockCreateFeishuReplyDispatcher, mockCreateFeishuClient, mockResolveAgentRoute } =
9
+ vi.hoisted(() => ({
10
+ mockCreateFeishuReplyDispatcher: vi.fn((_params?: unknown) => ({
11
+ dispatcher: {
12
+ sendToolResult: vi.fn(),
13
+ sendBlockReply: vi.fn(),
14
+ sendFinalReply: vi.fn(),
15
+ waitForIdle: vi.fn(),
16
+ getQueuedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
17
+ getFailedCounts: vi.fn(() => ({ tool: 0, block: 0, final: 0 })),
18
+ markComplete: vi.fn(),
19
+ },
20
+ replyOptions: {},
21
+ markDispatchIdle: vi.fn(),
22
+ })),
23
+ mockCreateFeishuClient: vi.fn(),
24
+ mockResolveAgentRoute: vi.fn(),
25
+ }));
26
+
27
+ vi.mock("./reply-dispatcher.js", () => ({
28
+ createFeishuReplyDispatcher: mockCreateFeishuReplyDispatcher,
29
+ }));
30
+
31
+ vi.mock("./client.js", () => ({
32
+ createFeishuClient: mockCreateFeishuClient,
33
+ }));
34
+
35
+ function createRuntimeEnv() {
36
+ return {
37
+ log: vi.fn(),
38
+ error: vi.fn(),
39
+ writeStdout: vi.fn(),
40
+ writeJson: vi.fn(),
41
+ exit: vi.fn((code: number): never => {
42
+ throw new Error(`exit ${code}`);
43
+ }),
44
+ };
45
+ }
46
+
47
+ describe("broadcast dispatch", () => {
48
+ const finalizeInboundContextCalls: Array<Record<string, unknown>> = [];
49
+ const mockGetChatInfo = vi.fn();
50
+ const mockFinalizeInboundContext: PluginRuntime["channel"]["reply"]["finalizeInboundContext"] = (
51
+ ctx,
52
+ ) => {
53
+ finalizeInboundContextCalls.push(ctx);
54
+ return {
55
+ ...ctx,
56
+ CommandAuthorized: typeof ctx.CommandAuthorized === "boolean" ? ctx.CommandAuthorized : false,
57
+ CommandTurn: {
58
+ kind: "normal",
59
+ source: "message",
60
+ authorized: false,
61
+ },
62
+ };
63
+ };
64
+ const mockDispatchReplyFromConfig = vi
65
+ .fn()
66
+ .mockResolvedValue({ queuedFinal: false, counts: { final: 1 } });
67
+ const mockWithReplyDispatcher: PluginRuntime["channel"]["reply"]["withReplyDispatcher"] = async ({
68
+ dispatcher,
69
+ run,
70
+ onSettled,
71
+ }) => {
72
+ try {
73
+ return await run();
74
+ } finally {
75
+ dispatcher.markComplete();
76
+ try {
77
+ await dispatcher.waitForIdle();
78
+ } finally {
79
+ await onSettled?.();
80
+ }
81
+ }
82
+ };
83
+ const resolveEnvelopeFormatOptionsMock: PluginRuntime["channel"]["reply"]["resolveEnvelopeFormatOptions"] =
84
+ () => ({}) satisfies EnvelopeFormatOptions;
85
+ const mockShouldComputeCommandAuthorized = vi.fn(() => false);
86
+ const mockSaveMediaBuffer = vi.fn().mockResolvedValue({
87
+ path: "/tmp/inbound-clip.mp4",
88
+ contentType: "video/mp4",
89
+ });
90
+ const runtimeStub = {
91
+ system: {
92
+ enqueueSystemEvent: vi.fn(),
93
+ },
94
+ channel: {
95
+ routing: {
96
+ resolveAgentRoute: (params: unknown) => mockResolveAgentRoute(params),
97
+ },
98
+ session: {
99
+ resolveStorePath: vi.fn(() => "/tmp/feishu-session-store.json"),
100
+ recordInboundSession: vi.fn().mockResolvedValue(undefined),
101
+ },
102
+ reply: {
103
+ resolveEnvelopeFormatOptions: resolveEnvelopeFormatOptionsMock,
104
+ formatAgentEnvelope: vi.fn((params: { body: string }) => params.body),
105
+ finalizeInboundContext:
106
+ mockFinalizeInboundContext as unknown as PluginRuntime["channel"]["reply"]["finalizeInboundContext"],
107
+ dispatchReplyFromConfig: mockDispatchReplyFromConfig,
108
+ withReplyDispatcher:
109
+ mockWithReplyDispatcher as unknown as PluginRuntime["channel"]["reply"]["withReplyDispatcher"],
110
+ },
111
+ commands: {
112
+ shouldComputeCommandAuthorized: mockShouldComputeCommandAuthorized,
113
+ resolveCommandAuthorizedFromAuthorizers: vi.fn(() => false),
114
+ },
115
+ media: {
116
+ saveMediaBuffer: mockSaveMediaBuffer,
117
+ },
118
+ turn: {
119
+ run: vi.fn(async (params: Parameters<PluginRuntime["channel"]["turn"]["run"]>[0]) => {
120
+ const input = await params.adapter.ingest(params.raw);
121
+ if (!input) {
122
+ return {
123
+ admission: { kind: "drop" as const, reason: "ingest-null" },
124
+ dispatched: false,
125
+ };
126
+ }
127
+ const eventClass = {
128
+ kind: "message" as const,
129
+ canStartAgentTurn: true,
130
+ };
131
+ const turn = await params.adapter.resolveTurn(input, eventClass, {});
132
+ if (!("runDispatch" in turn)) {
133
+ throw new Error("feishu broadcast test runtime only supports prepared turns");
134
+ }
135
+ await turn.recordInboundSession({
136
+ storePath: turn.storePath,
137
+ sessionKey: turn.ctxPayload.SessionKey ?? turn.routeSessionKey,
138
+ ctx: turn.ctxPayload,
139
+ groupResolution: turn.record?.groupResolution,
140
+ createIfMissing: turn.record?.createIfMissing,
141
+ updateLastRoute: turn.record?.updateLastRoute,
142
+ onRecordError: turn.record?.onRecordError ?? (() => undefined),
143
+ });
144
+ return {
145
+ admission: { kind: "dispatch" as const },
146
+ dispatched: true,
147
+ ctxPayload: turn.ctxPayload,
148
+ routeSessionKey: turn.routeSessionKey,
149
+ dispatchResult: await turn.runDispatch(),
150
+ };
151
+ }),
152
+ runPrepared: vi.fn(
153
+ async (turn: Parameters<PluginRuntime["channel"]["turn"]["runPrepared"]>[0]) => {
154
+ await turn.recordInboundSession({
155
+ storePath: turn.storePath,
156
+ sessionKey: turn.ctxPayload.SessionKey ?? turn.routeSessionKey,
157
+ ctx: turn.ctxPayload,
158
+ groupResolution: turn.record?.groupResolution,
159
+ createIfMissing: turn.record?.createIfMissing,
160
+ updateLastRoute: turn.record?.updateLastRoute,
161
+ onRecordError: turn.record?.onRecordError ?? (() => undefined),
162
+ });
163
+ return {
164
+ admission: { kind: "dispatch" as const },
165
+ dispatched: true,
166
+ ctxPayload: turn.ctxPayload,
167
+ routeSessionKey: turn.routeSessionKey,
168
+ dispatchResult: await turn.runDispatch(),
169
+ };
170
+ },
171
+ ),
172
+ },
173
+ pairing: {
174
+ readAllowFromStore: vi.fn().mockResolvedValue([]),
175
+ upsertPairingRequest: vi.fn().mockResolvedValue({ code: "ABCDEFGH", created: false }),
176
+ buildPairingReply: vi.fn(() => "Pairing response"),
177
+ },
178
+ },
179
+ media: {
180
+ detectMime: vi.fn(async () => "application/octet-stream"),
181
+ },
182
+ } as unknown as PluginRuntime;
183
+
184
+ afterAll(() => {
185
+ vi.doUnmock("./reply-dispatcher.js");
186
+ vi.doUnmock("./client.js");
187
+ vi.resetModules();
188
+ });
189
+
190
+ function createBroadcastConfig(): ClawdbotConfig {
191
+ return {
192
+ broadcast: { "oc-broadcast-group": ["susan", "main"] },
193
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
194
+ channels: {
195
+ feishu: {
196
+ appId: "cli_test",
197
+ appSecret: "sec_test", // pragma: allowlist secret
198
+ groups: {
199
+ "oc-broadcast-group": {
200
+ requireMention: true,
201
+ },
202
+ },
203
+ },
204
+ },
205
+ };
206
+ }
207
+
208
+ function createBroadcastEvent(options: {
209
+ messageId: string;
210
+ text: string;
211
+ botMentioned?: boolean;
212
+ }): FeishuMessageEvent {
213
+ return {
214
+ sender: { sender_id: { open_id: "ou-sender" } },
215
+ message: {
216
+ message_id: options.messageId,
217
+ chat_id: "oc-broadcast-group",
218
+ chat_type: "group",
219
+ message_type: "text",
220
+ content: JSON.stringify({ text: options.text }),
221
+ ...(options.botMentioned
222
+ ? {
223
+ mentions: [
224
+ {
225
+ key: "@_user_1",
226
+ id: { open_id: "bot-open-id" },
227
+ name: "Bot",
228
+ tenant_key: "",
229
+ },
230
+ ],
231
+ }
232
+ : {}),
233
+ },
234
+ };
235
+ }
236
+
237
+ beforeEach(() => {
238
+ vi.clearAllMocks();
239
+ clearGroupNameCache();
240
+ finalizeInboundContextCalls.length = 0;
241
+ mockResolveAgentRoute.mockReturnValue({
242
+ agentId: "main",
243
+ channel: "feishu",
244
+ accountId: "default",
245
+ sessionKey: "agent:main:feishu:group:oc-broadcast-group",
246
+ mainSessionKey: "agent:main:main",
247
+ lastRoutePolicy: "session",
248
+ matchedBy: "default",
249
+ });
250
+ mockCreateFeishuClient.mockReturnValue({
251
+ contact: {
252
+ user: {
253
+ get: vi.fn().mockResolvedValue({ data: { user: { name: "Sender" } } }),
254
+ },
255
+ },
256
+ im: {
257
+ chat: {
258
+ get: mockGetChatInfo.mockResolvedValue({
259
+ code: 0,
260
+ data: { name: "Broadcast Team" },
261
+ }),
262
+ },
263
+ },
264
+ });
265
+ setFeishuRuntime(runtimeStub);
266
+ });
267
+
268
+ it("dispatches to all broadcast agents when bot is mentioned", async () => {
269
+ const cfg = createBroadcastConfig();
270
+ const event = createBroadcastEvent({
271
+ messageId: "msg-broadcast-mentioned",
272
+ text: "hello @bot",
273
+ botMentioned: true,
274
+ });
275
+
276
+ await handleFeishuMessage({
277
+ cfg,
278
+ event,
279
+ botOpenId: "bot-open-id",
280
+ runtime: createRuntimeEnv(),
281
+ });
282
+
283
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(2);
284
+ const sessionKeys = finalizeInboundContextCalls.map((call) => call.SessionKey);
285
+ expect(sessionKeys).toContain("agent:susan:feishu:group:oc-broadcast-group");
286
+ expect(sessionKeys).toContain("agent:main:feishu:group:oc-broadcast-group");
287
+ const recordCalls = (
288
+ runtimeStub.channel.session.recordInboundSession as unknown as {
289
+ mock: {
290
+ calls: Array<
291
+ [
292
+ {
293
+ updateLastRoute?: {
294
+ sessionKey?: unknown;
295
+ channel?: unknown;
296
+ to?: unknown;
297
+ };
298
+ },
299
+ ]
300
+ >;
301
+ };
302
+ }
303
+ ).mock.calls;
304
+ expect(
305
+ recordCalls
306
+ .map(([call]) => ({
307
+ sessionKey: call.updateLastRoute?.["sessionKey"],
308
+ channel: call.updateLastRoute?.["channel"],
309
+ to: call.updateLastRoute?.["to"],
310
+ }))
311
+ .toSorted((left, right) => String(left.sessionKey).localeCompare(String(right.sessionKey))),
312
+ ).toEqual([
313
+ {
314
+ sessionKey: "agent:main:feishu:group:oc-broadcast-group",
315
+ channel: "feishu",
316
+ to: "chat:oc-broadcast-group",
317
+ },
318
+ {
319
+ sessionKey: "agent:susan:feishu:group:oc-broadcast-group",
320
+ channel: "feishu",
321
+ to: "chat:oc-broadcast-group",
322
+ },
323
+ ]);
324
+ expect(mockGetChatInfo).toHaveBeenCalledTimes(1);
325
+ expect(
326
+ finalizeInboundContextCalls
327
+ .map((call) => ({
328
+ sessionKey: call.SessionKey,
329
+ groupSubject: call.GroupSubject,
330
+ conversationLabel: call.ConversationLabel,
331
+ }))
332
+ .toSorted((left, right) => String(left.sessionKey).localeCompare(String(right.sessionKey))),
333
+ ).toEqual([
334
+ {
335
+ sessionKey: "agent:main:feishu:group:oc-broadcast-group",
336
+ groupSubject: "Broadcast Team",
337
+ conversationLabel: "Broadcast Team",
338
+ },
339
+ {
340
+ sessionKey: "agent:susan:feishu:group:oc-broadcast-group",
341
+ groupSubject: "Broadcast Team",
342
+ conversationLabel: "Broadcast Team",
343
+ },
344
+ ]);
345
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledTimes(1);
346
+ const dispatcherParams = mockCreateFeishuReplyDispatcher.mock.calls.at(0)?.[0] as
347
+ | { agentId?: string }
348
+ | undefined;
349
+ expect(dispatcherParams?.agentId).toBe("main");
350
+ });
351
+
352
+ it("skips broadcast dispatch when bot is NOT mentioned (requireMention=true)", async () => {
353
+ const cfg = createBroadcastConfig();
354
+ const event = createBroadcastEvent({
355
+ messageId: "msg-broadcast-not-mentioned",
356
+ text: "hello everyone",
357
+ });
358
+
359
+ await handleFeishuMessage({
360
+ cfg,
361
+ event,
362
+ botOpenId: "ou_known_bot",
363
+ runtime: createRuntimeEnv(),
364
+ });
365
+
366
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
367
+ expect(mockCreateFeishuReplyDispatcher).not.toHaveBeenCalled();
368
+ expect(mockGetChatInfo).not.toHaveBeenCalled();
369
+ });
370
+
371
+ it("skips broadcast dispatch when bot identity is unknown (requireMention=true)", async () => {
372
+ const cfg = createBroadcastConfig();
373
+ const event = createBroadcastEvent({
374
+ messageId: "msg-broadcast-unknown-bot-id",
375
+ text: "hello everyone",
376
+ });
377
+
378
+ await handleFeishuMessage({
379
+ cfg,
380
+ event,
381
+ runtime: createRuntimeEnv(),
382
+ });
383
+
384
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
385
+ expect(mockCreateFeishuReplyDispatcher).not.toHaveBeenCalled();
386
+ expect(mockGetChatInfo).not.toHaveBeenCalled();
387
+ });
388
+
389
+ it("preserves single-agent dispatch when no broadcast config", async () => {
390
+ const cfg: ClawdbotConfig = {
391
+ channels: {
392
+ feishu: {
393
+ appId: "cli_test",
394
+ appSecret: "sec_test", // pragma: allowlist secret
395
+ groups: {
396
+ "oc-broadcast-group": {
397
+ requireMention: false,
398
+ },
399
+ },
400
+ },
401
+ },
402
+ };
403
+
404
+ const event: FeishuMessageEvent = {
405
+ sender: { sender_id: { open_id: "ou-sender" } },
406
+ message: {
407
+ message_id: "msg-no-broadcast",
408
+ chat_id: "oc-broadcast-group",
409
+ chat_type: "group",
410
+ message_type: "text",
411
+ content: JSON.stringify({ text: "hello" }),
412
+ },
413
+ };
414
+
415
+ await handleFeishuMessage({
416
+ cfg,
417
+ event,
418
+ runtime: createRuntimeEnv(),
419
+ });
420
+
421
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
422
+ expect(mockCreateFeishuReplyDispatcher).toHaveBeenCalledTimes(1);
423
+ expect(finalizeInboundContextCalls).toHaveLength(1);
424
+ expect(finalizeInboundContextCalls[0]?.SessionKey).toBe(
425
+ "agent:main:feishu:group:oc-broadcast-group",
426
+ );
427
+ expect(finalizeInboundContextCalls[0]?.GroupSubject).toBe("Broadcast Team");
428
+ expect(finalizeInboundContextCalls[0]?.ConversationLabel).toBe("Broadcast Team");
429
+ expect(mockGetChatInfo).toHaveBeenCalledTimes(1);
430
+ });
431
+
432
+ it("cross-account broadcast dedup: second account skips dispatch", async () => {
433
+ const cfg: ClawdbotConfig = {
434
+ broadcast: { "oc-broadcast-group": ["susan", "main"] },
435
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
436
+ channels: {
437
+ feishu: {
438
+ appId: "cli_test",
439
+ appSecret: "sec_test", // pragma: allowlist secret
440
+ groups: {
441
+ "oc-broadcast-group": {
442
+ requireMention: false,
443
+ },
444
+ },
445
+ },
446
+ },
447
+ };
448
+
449
+ const event: FeishuMessageEvent = {
450
+ sender: { sender_id: { open_id: "ou-sender" } },
451
+ message: {
452
+ message_id: "msg-multi-account-dedup",
453
+ chat_id: "oc-broadcast-group",
454
+ chat_type: "group",
455
+ message_type: "text",
456
+ content: JSON.stringify({ text: "hello" }),
457
+ },
458
+ };
459
+
460
+ await handleFeishuMessage({
461
+ cfg,
462
+ event,
463
+ runtime: createRuntimeEnv(),
464
+ accountId: "account-A",
465
+ });
466
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(2);
467
+
468
+ mockDispatchReplyFromConfig.mockClear();
469
+ mockGetChatInfo.mockClear();
470
+ finalizeInboundContextCalls.length = 0;
471
+
472
+ await handleFeishuMessage({
473
+ cfg,
474
+ event,
475
+ runtime: createRuntimeEnv(),
476
+ accountId: "account-B",
477
+ });
478
+ expect(mockDispatchReplyFromConfig).not.toHaveBeenCalled();
479
+ expect(mockGetChatInfo).not.toHaveBeenCalled();
480
+ });
481
+
482
+ it("skips unknown agents not in agents.list", async () => {
483
+ const cfg: ClawdbotConfig = {
484
+ broadcast: { "oc-broadcast-group": ["susan", "unknown-agent"] },
485
+ agents: { list: [{ id: "main" }, { id: "susan" }] },
486
+ channels: {
487
+ feishu: {
488
+ appId: "cli_test",
489
+ appSecret: "sec_test", // pragma: allowlist secret
490
+ groups: {
491
+ "oc-broadcast-group": {
492
+ requireMention: false,
493
+ },
494
+ },
495
+ },
496
+ },
497
+ };
498
+
499
+ const event: FeishuMessageEvent = {
500
+ sender: { sender_id: { open_id: "ou-sender" } },
501
+ message: {
502
+ message_id: "msg-broadcast-unknown-agent",
503
+ chat_id: "oc-broadcast-group",
504
+ chat_type: "group",
505
+ message_type: "text",
506
+ content: JSON.stringify({ text: "hello" }),
507
+ },
508
+ };
509
+
510
+ await handleFeishuMessage({
511
+ cfg,
512
+ event,
513
+ runtime: createRuntimeEnv(),
514
+ });
515
+
516
+ expect(mockDispatchReplyFromConfig).toHaveBeenCalledTimes(1);
517
+ const sessionKey =
518
+ typeof finalizeInboundContextCalls[0]?.SessionKey === "string"
519
+ ? finalizeInboundContextCalls[0].SessionKey
520
+ : "";
521
+ expect(sessionKey).toBe("agent:susan:feishu:group:oc-broadcast-group");
522
+ });
523
+ });