@openclaw/feishu 2026.3.12 → 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 +115 -22
  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 +798 -786
  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 +77 -25
  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 +76 -35
  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 +413 -87
  91. package/src/media.ts +488 -154
  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 +220 -313
  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 +194 -92
  113. package/src/monitor.reply-once.lifecycle.test-support.ts +190 -0
  114. package/src/monitor.startup.test.ts +24 -36
  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 +297 -39
  120. package/src/monitor.ts +15 -10
  121. package/src/monitor.webhook-e2e.test.ts +272 -0
  122. package/src/monitor.webhook-security.test.ts +125 -91
  123. package/src/monitor.webhook.test-helpers.ts +116 -0
  124. package/src/outbound-runtime-api.ts +1 -0
  125. package/src/outbound.test.ts +627 -53
  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 +122 -118
  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 +23 -60
  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 +721 -168
  142. package/src/reply-dispatcher.ts +422 -172
  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 +127 -42
  153. package/src/send.test.ts +386 -4
  154. package/src/send.ts +486 -164
  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,199 @@
1
+ import { normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/text-runtime";
2
+
3
+ export type FeishuGroupSessionScope =
4
+ | "group"
5
+ | "group_sender"
6
+ | "group_topic"
7
+ | "group_topic_sender";
8
+
9
+ function normalizeText(value: unknown): string | undefined {
10
+ if (typeof value !== "string") {
11
+ return undefined;
12
+ }
13
+ const trimmed = value.trim();
14
+ return trimmed || undefined;
15
+ }
16
+
17
+ export function buildFeishuConversationId(params: {
18
+ chatId: string;
19
+ scope: FeishuGroupSessionScope;
20
+ senderOpenId?: string;
21
+ topicId?: string;
22
+ }): string {
23
+ const chatId = normalizeText(params.chatId) ?? "unknown";
24
+ const senderOpenId = normalizeText(params.senderOpenId);
25
+ const topicId = normalizeText(params.topicId);
26
+
27
+ switch (params.scope) {
28
+ case "group_sender":
29
+ return senderOpenId ? `${chatId}:sender:${senderOpenId}` : chatId;
30
+ case "group_topic":
31
+ return topicId ? `${chatId}:topic:${topicId}` : chatId;
32
+ case "group_topic_sender":
33
+ if (topicId && senderOpenId) {
34
+ return `${chatId}:topic:${topicId}:sender:${senderOpenId}`;
35
+ }
36
+ if (topicId) {
37
+ return `${chatId}:topic:${topicId}`;
38
+ }
39
+ return senderOpenId ? `${chatId}:sender:${senderOpenId}` : chatId;
40
+ case "group":
41
+ default:
42
+ return chatId;
43
+ }
44
+ }
45
+
46
+ export function parseFeishuTargetId(raw: unknown): string | undefined {
47
+ const target = normalizeText(raw);
48
+ if (!target) {
49
+ return undefined;
50
+ }
51
+ const withoutProvider = target.replace(/^(feishu|lark):/i, "").trim();
52
+ if (!withoutProvider) {
53
+ return undefined;
54
+ }
55
+ const lowered = normalizeLowercaseStringOrEmpty(withoutProvider);
56
+ for (const prefix of ["chat:", "group:", "channel:", "user:", "dm:", "open_id:"]) {
57
+ if (lowered.startsWith(prefix)) {
58
+ return normalizeText(withoutProvider.slice(prefix.length));
59
+ }
60
+ }
61
+ return withoutProvider;
62
+ }
63
+
64
+ export function parseFeishuDirectConversationId(raw: unknown): string | undefined {
65
+ const target = normalizeText(raw);
66
+ if (!target) {
67
+ return undefined;
68
+ }
69
+ const withoutProvider = target.replace(/^(feishu|lark):/i, "").trim();
70
+ if (!withoutProvider) {
71
+ return undefined;
72
+ }
73
+ const lowered = normalizeLowercaseStringOrEmpty(withoutProvider);
74
+ for (const prefix of ["user:", "dm:", "open_id:"]) {
75
+ if (lowered.startsWith(prefix)) {
76
+ return normalizeText(withoutProvider.slice(prefix.length));
77
+ }
78
+ }
79
+ const id = parseFeishuTargetId(target);
80
+ if (!id) {
81
+ return undefined;
82
+ }
83
+ if (id.startsWith("ou_") || id.startsWith("on_")) {
84
+ return id;
85
+ }
86
+ return undefined;
87
+ }
88
+
89
+ export function parseFeishuConversationId(params: {
90
+ conversationId: string;
91
+ parentConversationId?: string;
92
+ }): {
93
+ canonicalConversationId: string;
94
+ chatId: string;
95
+ topicId?: string;
96
+ senderOpenId?: string;
97
+ scope: FeishuGroupSessionScope;
98
+ } | null {
99
+ const conversationId = normalizeText(params.conversationId);
100
+ const parentConversationId = normalizeText(params.parentConversationId);
101
+ if (!conversationId) {
102
+ return null;
103
+ }
104
+
105
+ const topicSenderMatch = conversationId.match(/^(.+):topic:([^:]+):sender:([^:]+)$/i);
106
+ if (topicSenderMatch) {
107
+ const [, chatId, topicId, senderOpenId] = topicSenderMatch;
108
+ return {
109
+ canonicalConversationId: buildFeishuConversationId({
110
+ chatId,
111
+ scope: "group_topic_sender",
112
+ topicId,
113
+ senderOpenId,
114
+ }),
115
+ chatId,
116
+ topicId,
117
+ senderOpenId,
118
+ scope: "group_topic_sender",
119
+ };
120
+ }
121
+
122
+ const topicMatch = conversationId.match(/^(.+):topic:([^:]+)$/i);
123
+ if (topicMatch) {
124
+ const [, chatId, topicId] = topicMatch;
125
+ return {
126
+ canonicalConversationId: buildFeishuConversationId({
127
+ chatId,
128
+ scope: "group_topic",
129
+ topicId,
130
+ }),
131
+ chatId,
132
+ topicId,
133
+ scope: "group_topic",
134
+ };
135
+ }
136
+
137
+ const senderMatch = conversationId.match(/^(.+):sender:([^:]+)$/i);
138
+ if (senderMatch) {
139
+ const [, chatId, senderOpenId] = senderMatch;
140
+ return {
141
+ canonicalConversationId: buildFeishuConversationId({
142
+ chatId,
143
+ scope: "group_sender",
144
+ senderOpenId,
145
+ }),
146
+ chatId,
147
+ senderOpenId,
148
+ scope: "group_sender",
149
+ };
150
+ }
151
+
152
+ if (parentConversationId) {
153
+ return {
154
+ canonicalConversationId: buildFeishuConversationId({
155
+ chatId: parentConversationId,
156
+ scope: "group_topic",
157
+ topicId: conversationId,
158
+ }),
159
+ chatId: parentConversationId,
160
+ topicId: conversationId,
161
+ scope: "group_topic",
162
+ };
163
+ }
164
+
165
+ return {
166
+ canonicalConversationId: conversationId,
167
+ chatId: conversationId,
168
+ scope: "group",
169
+ };
170
+ }
171
+
172
+ export function buildFeishuModelOverrideParentCandidates(
173
+ parentConversationId?: string | null,
174
+ ): string[] {
175
+ const rawId = normalizeText(parentConversationId);
176
+ if (!rawId) {
177
+ return [];
178
+ }
179
+ const topicSenderMatch = rawId.match(/^(.+):topic:([^:]+):sender:([^:]+)$/i);
180
+ if (topicSenderMatch) {
181
+ const chatId = normalizeLowercaseStringOrEmpty(topicSenderMatch[1]);
182
+ const topicId = normalizeLowercaseStringOrEmpty(topicSenderMatch[2]);
183
+ if (chatId && topicId) {
184
+ return [`${chatId}:topic:${topicId}`, chatId];
185
+ }
186
+ return [];
187
+ }
188
+ const topicMatch = rawId.match(/^(.+):topic:([^:]+)$/i);
189
+ if (topicMatch) {
190
+ const chatId = normalizeLowercaseStringOrEmpty(topicMatch[1]);
191
+ return chatId ? [chatId] : [];
192
+ }
193
+ const senderMatch = rawId.match(/^(.+):sender:([^:]+)$/i);
194
+ if (senderMatch) {
195
+ const chatId = normalizeLowercaseStringOrEmpty(senderMatch[1]);
196
+ return chatId ? [chatId] : [];
197
+ }
198
+ return [];
199
+ }
@@ -0,0 +1 @@
1
+ export { createPersistentDedupe } from "openclaw/plugin-sdk/persistent-dedupe";
package/src/dedup.ts CHANGED
@@ -1,21 +1,18 @@
1
1
  import os from "node:os";
2
2
  import path from "node:path";
3
+ import { createPersistentDedupe } from "./dedup-runtime-api.js";
3
4
  import {
4
- createDedupeCache,
5
- createPersistentDedupe,
6
- readJsonFileWithFallback,
7
- } from "openclaw/plugin-sdk/feishu";
5
+ releaseFeishuMessageProcessing,
6
+ tryBeginFeishuMessageProcessing,
7
+ } from "./processing-claims.js";
8
8
 
9
9
  // Persistent TTL: 24 hours — survives restarts & WebSocket reconnects.
10
10
  const DEDUP_TTL_MS = 24 * 60 * 60 * 1000;
11
11
  const MEMORY_MAX_SIZE = 1_000;
12
12
  const FILE_MAX_ENTRIES = 10_000;
13
- type PersistentDedupeData = Record<string, number>;
14
-
15
- const memoryDedupe = createDedupeCache({ ttlMs: DEDUP_TTL_MS, maxSize: MEMORY_MAX_SIZE });
16
13
 
17
14
  function resolveStateDirFromEnv(env: NodeJS.ProcessEnv = process.env): string {
18
- const stateOverride = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
15
+ const stateOverride = env.OPENCLAW_STATE_DIR?.trim();
19
16
  if (stateOverride) {
20
17
  return stateOverride;
21
18
  }
@@ -37,20 +34,75 @@ const persistentDedupe = createPersistentDedupe({
37
34
  resolveFilePath: resolveNamespaceFilePath,
38
35
  });
39
36
 
40
- /**
41
- * Synchronous dedup — memory only.
42
- * Kept for backward compatibility; prefer {@link tryRecordMessagePersistent}.
43
- */
44
- export function tryRecordMessage(messageId: string): boolean {
45
- return !memoryDedupe.check(messageId);
37
+ function normalizeMessageId(messageId: string | undefined | null): string | null {
38
+ const trimmed = messageId?.trim();
39
+ return trimmed ? trimmed : null;
46
40
  }
47
41
 
48
- export function hasRecordedMessage(messageId: string): boolean {
49
- const trimmed = messageId.trim();
50
- if (!trimmed) {
42
+ export { releaseFeishuMessageProcessing, tryBeginFeishuMessageProcessing };
43
+
44
+ export async function claimUnprocessedFeishuMessage(params: {
45
+ messageId: string | undefined | null;
46
+ namespace?: string;
47
+ log?: (...args: unknown[]) => void;
48
+ }): Promise<"claimed" | "duplicate" | "inflight" | "invalid"> {
49
+ const { messageId, namespace = "global", log } = params;
50
+ const normalizedMessageId = normalizeMessageId(messageId);
51
+ if (!normalizedMessageId) {
52
+ return "invalid";
53
+ }
54
+ if (await hasProcessedFeishuMessage(normalizedMessageId, namespace, log)) {
55
+ return "duplicate";
56
+ }
57
+ if (!tryBeginFeishuMessageProcessing(normalizedMessageId, namespace)) {
58
+ return "inflight";
59
+ }
60
+ return "claimed";
61
+ }
62
+
63
+ export async function finalizeFeishuMessageProcessing(params: {
64
+ messageId: string | undefined | null;
65
+ namespace?: string;
66
+ log?: (...args: unknown[]) => void;
67
+ claimHeld?: boolean;
68
+ }): Promise<boolean> {
69
+ const { messageId, namespace = "global", log, claimHeld = false } = params;
70
+ const normalizedMessageId = normalizeMessageId(messageId);
71
+ if (!normalizedMessageId) {
72
+ return false;
73
+ }
74
+ if (!claimHeld && !tryBeginFeishuMessageProcessing(normalizedMessageId, namespace)) {
51
75
  return false;
52
76
  }
53
- return memoryDedupe.peek(trimmed);
77
+ if (!(await tryRecordMessagePersistent(normalizedMessageId, namespace, log))) {
78
+ releaseFeishuMessageProcessing(normalizedMessageId, namespace);
79
+ return false;
80
+ }
81
+ return true;
82
+ }
83
+
84
+ export async function recordProcessedFeishuMessage(
85
+ messageId: string | undefined | null,
86
+ namespace = "global",
87
+ log?: (...args: unknown[]) => void,
88
+ ): Promise<boolean> {
89
+ const normalizedMessageId = normalizeMessageId(messageId);
90
+ if (!normalizedMessageId) {
91
+ return false;
92
+ }
93
+ return await tryRecordMessagePersistent(normalizedMessageId, namespace, log);
94
+ }
95
+
96
+ export async function hasProcessedFeishuMessage(
97
+ messageId: string | undefined | null,
98
+ namespace = "global",
99
+ log?: (...args: unknown[]) => void,
100
+ ): Promise<boolean> {
101
+ const normalizedMessageId = normalizeMessageId(messageId);
102
+ if (!normalizedMessageId) {
103
+ return false;
104
+ }
105
+ return hasRecordedMessagePersistent(normalizedMessageId, namespace, log);
54
106
  }
55
107
 
56
108
  export async function tryRecordMessagePersistent(
@@ -71,23 +123,12 @@ export async function hasRecordedMessagePersistent(
71
123
  namespace = "global",
72
124
  log?: (...args: unknown[]) => void,
73
125
  ): Promise<boolean> {
74
- const trimmed = messageId.trim();
75
- if (!trimmed) {
76
- return false;
77
- }
78
- const now = Date.now();
79
- const filePath = resolveNamespaceFilePath(namespace);
80
- try {
81
- const { value } = await readJsonFileWithFallback<PersistentDedupeData>(filePath, {});
82
- const seenAt = value[trimmed];
83
- if (typeof seenAt !== "number" || !Number.isFinite(seenAt)) {
84
- return false;
85
- }
86
- return DEDUP_TTL_MS <= 0 || now - seenAt < DEDUP_TTL_MS;
87
- } catch (error) {
88
- log?.(`feishu-dedup: persistent peek failed: ${String(error)}`);
89
- return false;
90
- }
126
+ return persistentDedupe.hasRecent(messageId, {
127
+ namespace,
128
+ onDiskError: (error) => {
129
+ log?.(`feishu-dedup: persistent peek failed: ${String(error)}`);
130
+ },
131
+ });
91
132
  }
92
133
 
93
134
  export async function warmupDedupFromDisk(
@@ -0,0 +1,61 @@
1
+ import {
2
+ listDirectoryGroupEntriesFromMapKeysAndAllowFrom,
3
+ listDirectoryUserEntriesFromAllowFromAndMapKeys,
4
+ } from "openclaw/plugin-sdk/directory-runtime";
5
+ import type { ClawdbotConfig } from "../runtime-api.js";
6
+ import { resolveFeishuAccount } from "./accounts.js";
7
+ import { normalizeFeishuTarget } from "./targets.js";
8
+
9
+ export type FeishuDirectoryPeer = {
10
+ kind: "user";
11
+ id: string;
12
+ name?: string;
13
+ };
14
+
15
+ export type FeishuDirectoryGroup = {
16
+ kind: "group";
17
+ id: string;
18
+ name?: string;
19
+ };
20
+
21
+ function toFeishuDirectoryPeers(ids: string[]): FeishuDirectoryPeer[] {
22
+ return ids.map((id) => ({ kind: "user", id }));
23
+ }
24
+
25
+ function toFeishuDirectoryGroups(ids: string[]): FeishuDirectoryGroup[] {
26
+ return ids.map((id) => ({ kind: "group", id }));
27
+ }
28
+
29
+ export async function listFeishuDirectoryPeers(params: {
30
+ cfg: ClawdbotConfig;
31
+ query?: string;
32
+ limit?: number;
33
+ accountId?: string;
34
+ }): Promise<FeishuDirectoryPeer[]> {
35
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
36
+ const entries = listDirectoryUserEntriesFromAllowFromAndMapKeys({
37
+ allowFrom: account.config.allowFrom,
38
+ map: account.config.dms,
39
+ query: params.query,
40
+ limit: params.limit,
41
+ normalizeAllowFromId: (entry) => normalizeFeishuTarget(entry) ?? entry,
42
+ normalizeMapKeyId: (entry) => normalizeFeishuTarget(entry) ?? entry,
43
+ });
44
+ return toFeishuDirectoryPeers(entries.map((entry) => entry.id));
45
+ }
46
+
47
+ export async function listFeishuDirectoryGroups(params: {
48
+ cfg: ClawdbotConfig;
49
+ query?: string;
50
+ limit?: number;
51
+ accountId?: string;
52
+ }): Promise<FeishuDirectoryGroup[]> {
53
+ const account = resolveFeishuAccount({ cfg: params.cfg, accountId: params.accountId });
54
+ const entries = listDirectoryGroupEntriesFromMapKeysAndAllowFrom({
55
+ groups: account.config.groups,
56
+ allowFrom: account.config.groupAllowFrom,
57
+ query: params.query,
58
+ limit: params.limit,
59
+ });
60
+ return toFeishuDirectoryGroups(entries.map((entry) => entry.id));
61
+ }
@@ -1,40 +1,139 @@
1
- import type { ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
2
- import { describe, expect, it, vi } from "vitest";
3
-
4
- vi.mock("./accounts.js", () => ({
5
- resolveFeishuAccount: vi.fn(() => ({
6
- configured: false,
7
- config: {
8
- allowFrom: ["user:alice", "user:bob"],
9
- dms: {
10
- "user:carla": {},
11
- },
12
- groups: {
13
- "chat-1": {},
1
+ import { importFreshModule } from "openclaw/plugin-sdk/test-fixtures";
2
+ import { beforeEach, describe, expect, it, vi } from "vitest";
3
+ import type { ClawdbotConfig } from "../runtime-api.js";
4
+
5
+ const createFeishuClientMock = vi.hoisted(() => vi.fn());
6
+
7
+ vi.mock("./client.js", () => ({
8
+ createFeishuClient: createFeishuClientMock,
9
+ }));
10
+
11
+ const {
12
+ listFeishuDirectoryGroups,
13
+ listFeishuDirectoryGroupsLive,
14
+ listFeishuDirectoryPeers,
15
+ listFeishuDirectoryPeersLive,
16
+ } = await importFreshModule<typeof import("./directory.js")>(
17
+ import.meta.url,
18
+ "./directory.js?directory-test",
19
+ );
20
+
21
+ function makeStaticCfg(): ClawdbotConfig {
22
+ return {
23
+ channels: {
24
+ feishu: {
25
+ allowFrom: ["user:alice", "user:bob"],
26
+ dms: {
27
+ "user:carla": {},
28
+ },
29
+ groups: {
30
+ "chat-1": {},
31
+ },
32
+ groupAllowFrom: ["chat-2"],
14
33
  },
15
- groupAllowFrom: ["chat-2"],
16
34
  },
17
- })),
18
- }));
35
+ } as ClawdbotConfig;
36
+ }
19
37
 
20
- import { listFeishuDirectoryGroups, listFeishuDirectoryPeers } from "./directory.js";
38
+ function makeConfiguredCfg(): ClawdbotConfig {
39
+ return {
40
+ channels: {
41
+ feishu: {
42
+ ...makeStaticCfg().channels?.feishu,
43
+ appId: "cli_test_app_id",
44
+ appSecret: "cli_test_app_secret",
45
+ },
46
+ },
47
+ } as ClawdbotConfig;
48
+ }
21
49
 
22
50
  describe("feishu directory (config-backed)", () => {
23
- const cfg = {} as ClawdbotConfig;
51
+ beforeEach(() => {
52
+ createFeishuClientMock.mockReset();
53
+ });
24
54
 
25
55
  it("merges allowFrom + dms into peer entries", async () => {
26
- const peers = await listFeishuDirectoryPeers({ cfg, query: "a" });
56
+ const peers = await listFeishuDirectoryPeers({ cfg: makeStaticCfg(), query: "a" });
27
57
  expect(peers).toEqual([
28
58
  { kind: "user", id: "alice" },
29
59
  { kind: "user", id: "carla" },
30
60
  ]);
31
61
  });
32
62
 
63
+ it("normalizes spaced provider-prefixed peer entries", async () => {
64
+ const cfg = {
65
+ channels: {
66
+ feishu: {
67
+ allowFrom: [" feishu:user:ou_alice "],
68
+ dms: {
69
+ " lark:dm:ou_carla ": {},
70
+ },
71
+ groups: {},
72
+ groupAllowFrom: [],
73
+ },
74
+ },
75
+ } as ClawdbotConfig;
76
+
77
+ const peers = await listFeishuDirectoryPeers({ cfg });
78
+ expect(peers).toEqual([
79
+ { kind: "user", id: "ou_alice" },
80
+ { kind: "user", id: "ou_carla" },
81
+ ]);
82
+ });
83
+
33
84
  it("merges groups map + groupAllowFrom into group entries", async () => {
34
- const groups = await listFeishuDirectoryGroups({ cfg });
85
+ const groups = await listFeishuDirectoryGroups({ cfg: makeStaticCfg() });
35
86
  expect(groups).toEqual([
36
87
  { kind: "group", id: "chat-1" },
37
88
  { kind: "group", id: "chat-2" },
38
89
  ]);
39
90
  });
91
+
92
+ it("falls back to static peers on live lookup failure by default", async () => {
93
+ createFeishuClientMock.mockReturnValueOnce({
94
+ contact: {
95
+ user: {
96
+ list: vi.fn(async () => {
97
+ throw new Error("token expired");
98
+ }),
99
+ },
100
+ },
101
+ });
102
+
103
+ const peers = await listFeishuDirectoryPeersLive({ cfg: makeConfiguredCfg(), query: "a" });
104
+ expect(peers).toEqual([
105
+ { kind: "user", id: "alice" },
106
+ { kind: "user", id: "carla" },
107
+ ]);
108
+ });
109
+
110
+ it("surfaces live peer lookup failures when fallback is disabled", async () => {
111
+ createFeishuClientMock.mockReturnValueOnce({
112
+ contact: {
113
+ user: {
114
+ list: vi.fn(async () => {
115
+ throw new Error("token expired");
116
+ }),
117
+ },
118
+ },
119
+ });
120
+
121
+ await expect(
122
+ listFeishuDirectoryPeersLive({ cfg: makeConfiguredCfg(), fallbackToStatic: false }),
123
+ ).rejects.toThrow("token expired");
124
+ });
125
+
126
+ it("surfaces live group lookup failures when fallback is disabled", async () => {
127
+ createFeishuClientMock.mockReturnValueOnce({
128
+ im: {
129
+ chat: {
130
+ list: vi.fn(async () => ({ code: 999, msg: "forbidden" })),
131
+ },
132
+ },
133
+ });
134
+
135
+ await expect(
136
+ listFeishuDirectoryGroupsLive({ cfg: makeConfiguredCfg(), fallbackToStatic: false }),
137
+ ).rejects.toThrow("forbidden");
138
+ });
40
139
  });