@openclaw/feishu 2026.3.13 → 2026.5.2-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 (187) 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 +1827 -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 +1253 -309
  48. package/src/chat-schema.ts +5 -4
  49. package/src/chat.test.ts +135 -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 +406 -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 +33 -95
  70. package/src/directory.static.ts +61 -0
  71. package/src/directory.test.ts +116 -20
  72. package/src/directory.ts +60 -92
  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 +403 -26
  91. package/src/media.ts +509 -132
  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.startup.test.ts +11 -9
  114. package/src/monitor.startup.ts +26 -16
  115. package/src/monitor.state.ts +20 -5
  116. package/src/monitor.synthetic-error.ts +18 -0
  117. package/src/monitor.test-mocks.ts +2 -2
  118. package/src/monitor.transport.ts +220 -60
  119. package/src/monitor.ts +15 -10
  120. package/src/monitor.webhook-e2e.test.ts +65 -7
  121. package/src/monitor.webhook-security.test.ts +122 -0
  122. package/src/monitor.webhook.test-helpers.ts +44 -26
  123. package/src/outbound-runtime-api.ts +1 -0
  124. package/src/outbound.test.ts +616 -37
  125. package/src/outbound.ts +623 -81
  126. package/src/perm-schema.ts +1 -1
  127. package/src/perm.ts +1 -7
  128. package/src/pins.ts +108 -0
  129. package/src/policy.test.ts +297 -117
  130. package/src/policy.ts +142 -29
  131. package/src/post.ts +7 -6
  132. package/src/probe.test.ts +14 -9
  133. package/src/probe.ts +26 -16
  134. package/src/processing-claims.ts +59 -0
  135. package/src/qr-terminal.ts +1 -0
  136. package/src/reactions.ts +4 -34
  137. package/src/reasoning-preview.test.ts +59 -0
  138. package/src/reasoning-preview.ts +20 -0
  139. package/src/reply-dispatcher-runtime-api.ts +7 -0
  140. package/src/reply-dispatcher.test.ts +660 -29
  141. package/src/reply-dispatcher.ts +407 -154
  142. package/src/runtime.ts +6 -3
  143. package/src/secret-contract.ts +145 -0
  144. package/src/secret-input.ts +1 -13
  145. package/src/security-audit-shared.ts +69 -0
  146. package/src/security-audit.test.ts +61 -0
  147. package/src/security-audit.ts +1 -0
  148. package/src/send-result.ts +1 -1
  149. package/src/send-target.test.ts +9 -3
  150. package/src/send-target.ts +10 -4
  151. package/src/send.reply-fallback.test.ts +105 -2
  152. package/src/send.test.ts +386 -4
  153. package/src/send.ts +414 -95
  154. package/src/sequential-key.test.ts +72 -0
  155. package/src/sequential-key.ts +28 -0
  156. package/src/sequential-queue.test.ts +92 -0
  157. package/src/sequential-queue.ts +16 -0
  158. package/src/session-conversation.ts +42 -0
  159. package/src/session-route.ts +48 -0
  160. package/src/setup-core.ts +51 -0
  161. package/src/{onboarding.test.ts → setup-surface.test.ts} +52 -21
  162. package/src/setup-surface.ts +581 -0
  163. package/src/streaming-card.test.ts +138 -2
  164. package/src/streaming-card.ts +134 -18
  165. package/src/subagent-hooks.test.ts +603 -0
  166. package/src/subagent-hooks.ts +397 -0
  167. package/src/targets.ts +3 -13
  168. package/src/test-support/lifecycle-test-support.ts +453 -0
  169. package/src/thread-bindings.test.ts +143 -0
  170. package/src/thread-bindings.ts +330 -0
  171. package/src/tool-account-routing.test.ts +66 -8
  172. package/src/tool-account.test.ts +44 -0
  173. package/src/tool-account.ts +40 -17
  174. package/src/tool-factory-test-harness.ts +11 -8
  175. package/src/tool-result.ts +3 -1
  176. package/src/tools-config.ts +1 -1
  177. package/src/types.ts +16 -15
  178. package/src/typing.ts +10 -6
  179. package/src/wiki-schema.ts +1 -1
  180. package/src/wiki.ts +1 -7
  181. package/subagent-hooks-api.ts +31 -0
  182. package/tsconfig.json +16 -0
  183. package/src/feishu-command-handler.ts +0 -59
  184. package/src/onboarding.status.test.ts +0 -25
  185. package/src/onboarding.ts +0 -489
  186. package/src/send-message.ts +0 -71
  187. 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,27 +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
- const EVENT_DEDUP_TTL_MS = 5 * 60 * 1000;
14
- const EVENT_MEMORY_MAX_SIZE = 2_000;
15
- type PersistentDedupeData = Record<string, number>;
16
-
17
- const memoryDedupe = createDedupeCache({ ttlMs: DEDUP_TTL_MS, maxSize: MEMORY_MAX_SIZE });
18
- const processingClaims = createDedupeCache({
19
- ttlMs: EVENT_DEDUP_TTL_MS,
20
- maxSize: EVENT_MEMORY_MAX_SIZE,
21
- });
22
13
 
23
14
  function resolveStateDirFromEnv(env: NodeJS.ProcessEnv = process.env): string {
24
- const stateOverride = env.OPENCLAW_STATE_DIR?.trim() || env.CLAWDBOT_STATE_DIR?.trim();
15
+ const stateOverride = env.OPENCLAW_STATE_DIR?.trim();
25
16
  if (stateOverride) {
26
17
  return stateOverride;
27
18
  }
@@ -43,45 +34,30 @@ const persistentDedupe = createPersistentDedupe({
43
34
  resolveFilePath: resolveNamespaceFilePath,
44
35
  });
45
36
 
46
- function resolveEventDedupeKey(
47
- namespace: string,
48
- messageId: string | undefined | null,
49
- ): string | null {
50
- const trimmed = messageId?.trim();
51
- if (!trimmed) {
52
- return null;
53
- }
54
- return `${namespace}:${trimmed}`;
55
- }
56
-
57
37
  function normalizeMessageId(messageId: string | undefined | null): string | null {
58
38
  const trimmed = messageId?.trim();
59
39
  return trimmed ? trimmed : null;
60
40
  }
61
41
 
62
- function resolveMemoryDedupeKey(
63
- namespace: string,
64
- messageId: string | undefined | null,
65
- ): string | null {
66
- const trimmed = normalizeMessageId(messageId);
67
- if (!trimmed) {
68
- return null;
69
- }
70
- return `${namespace}:${trimmed}`;
71
- }
72
-
73
- export function tryBeginFeishuMessageProcessing(
74
- messageId: string | undefined | null,
75
- namespace = "global",
76
- ): boolean {
77
- return !processingClaims.check(resolveEventDedupeKey(namespace, messageId));
78
- }
42
+ export { releaseFeishuMessageProcessing, tryBeginFeishuMessageProcessing };
79
43
 
80
- export function releaseFeishuMessageProcessing(
81
- messageId: string | undefined | null,
82
- namespace = "global",
83
- ): void {
84
- processingClaims.delete(resolveEventDedupeKey(namespace, messageId));
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";
85
61
  }
86
62
 
87
63
  export async function finalizeFeishuMessageProcessing(params: {
@@ -92,17 +68,12 @@ export async function finalizeFeishuMessageProcessing(params: {
92
68
  }): Promise<boolean> {
93
69
  const { messageId, namespace = "global", log, claimHeld = false } = params;
94
70
  const normalizedMessageId = normalizeMessageId(messageId);
95
- const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
96
- if (!memoryKey || !normalizedMessageId) {
71
+ if (!normalizedMessageId) {
97
72
  return false;
98
73
  }
99
74
  if (!claimHeld && !tryBeginFeishuMessageProcessing(normalizedMessageId, namespace)) {
100
75
  return false;
101
76
  }
102
- if (!tryRecordMessage(memoryKey)) {
103
- releaseFeishuMessageProcessing(normalizedMessageId, namespace);
104
- return false;
105
- }
106
77
  if (!(await tryRecordMessagePersistent(normalizedMessageId, namespace, log))) {
107
78
  releaseFeishuMessageProcessing(normalizedMessageId, namespace);
108
79
  return false;
@@ -116,11 +87,9 @@ export async function recordProcessedFeishuMessage(
116
87
  log?: (...args: unknown[]) => void,
117
88
  ): Promise<boolean> {
118
89
  const normalizedMessageId = normalizeMessageId(messageId);
119
- const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
120
- if (!memoryKey || !normalizedMessageId) {
90
+ if (!normalizedMessageId) {
121
91
  return false;
122
92
  }
123
- tryRecordMessage(memoryKey);
124
93
  return await tryRecordMessagePersistent(normalizedMessageId, namespace, log);
125
94
  }
126
95
 
@@ -130,32 +99,12 @@ export async function hasProcessedFeishuMessage(
130
99
  log?: (...args: unknown[]) => void,
131
100
  ): Promise<boolean> {
132
101
  const normalizedMessageId = normalizeMessageId(messageId);
133
- const memoryKey = resolveMemoryDedupeKey(namespace, messageId);
134
- if (!memoryKey || !normalizedMessageId) {
102
+ if (!normalizedMessageId) {
135
103
  return false;
136
104
  }
137
- if (hasRecordedMessage(memoryKey)) {
138
- return true;
139
- }
140
105
  return hasRecordedMessagePersistent(normalizedMessageId, namespace, log);
141
106
  }
142
107
 
143
- /**
144
- * Synchronous dedup — memory only.
145
- * Kept for backward compatibility; prefer {@link tryRecordMessagePersistent}.
146
- */
147
- export function tryRecordMessage(messageId: string): boolean {
148
- return !memoryDedupe.check(messageId);
149
- }
150
-
151
- export function hasRecordedMessage(messageId: string): boolean {
152
- const trimmed = messageId.trim();
153
- if (!trimmed) {
154
- return false;
155
- }
156
- return memoryDedupe.peek(trimmed);
157
- }
158
-
159
108
  export async function tryRecordMessagePersistent(
160
109
  messageId: string,
161
110
  namespace = "global",
@@ -169,28 +118,17 @@ export async function tryRecordMessagePersistent(
169
118
  });
170
119
  }
171
120
 
172
- export async function hasRecordedMessagePersistent(
121
+ async function hasRecordedMessagePersistent(
173
122
  messageId: string,
174
123
  namespace = "global",
175
124
  log?: (...args: unknown[]) => void,
176
125
  ): Promise<boolean> {
177
- const trimmed = messageId.trim();
178
- if (!trimmed) {
179
- return false;
180
- }
181
- const now = Date.now();
182
- const filePath = resolveNamespaceFilePath(namespace);
183
- try {
184
- const { value } = await readJsonFileWithFallback<PersistentDedupeData>(filePath, {});
185
- const seenAt = value[trimmed];
186
- if (typeof seenAt !== "number" || !Number.isFinite(seenAt)) {
187
- return false;
188
- }
189
- return DEDUP_TTL_MS <= 0 || now - seenAt < DEDUP_TTL_MS;
190
- } catch (error) {
191
- log?.(`feishu-dedup: persistent peek failed: ${String(error)}`);
192
- return false;
193
- }
126
+ return persistentDedupe.hasRecent(messageId, {
127
+ namespace,
128
+ onDiskError: (error) => {
129
+ log?.(`feishu-dedup: persistent peek failed: ${String(error)}`);
130
+ },
131
+ });
194
132
  }
195
133
 
196
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,136 @@
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 { listFeishuDirectoryGroupsLive, listFeishuDirectoryPeersLive } = await importFreshModule<
12
+ typeof import("./directory.js")
13
+ >(import.meta.url, "./directory.js?directory-test");
14
+ const { listFeishuDirectoryGroups, listFeishuDirectoryPeers } = await importFreshModule<
15
+ typeof import("./directory.static.js")
16
+ >(import.meta.url, "./directory.static.js?directory-test");
17
+
18
+ function makeStaticCfg(): ClawdbotConfig {
19
+ return {
20
+ channels: {
21
+ feishu: {
22
+ allowFrom: ["user:alice", "user:bob"],
23
+ dms: {
24
+ "user:carla": {},
25
+ },
26
+ groups: {
27
+ "chat-1": {},
28
+ },
29
+ groupAllowFrom: ["chat-2"],
14
30
  },
15
- groupAllowFrom: ["chat-2"],
16
31
  },
17
- })),
18
- }));
32
+ } as ClawdbotConfig;
33
+ }
19
34
 
20
- import { listFeishuDirectoryGroups, listFeishuDirectoryPeers } from "./directory.js";
35
+ function makeConfiguredCfg(): ClawdbotConfig {
36
+ return {
37
+ channels: {
38
+ feishu: {
39
+ ...makeStaticCfg().channels?.feishu,
40
+ appId: "cli_test_app_id",
41
+ appSecret: "cli_test_app_secret",
42
+ },
43
+ },
44
+ } as ClawdbotConfig;
45
+ }
21
46
 
22
47
  describe("feishu directory (config-backed)", () => {
23
- const cfg = {} as ClawdbotConfig;
48
+ beforeEach(() => {
49
+ createFeishuClientMock.mockReset();
50
+ });
24
51
 
25
52
  it("merges allowFrom + dms into peer entries", async () => {
26
- const peers = await listFeishuDirectoryPeers({ cfg, query: "a" });
53
+ const peers = await listFeishuDirectoryPeers({ cfg: makeStaticCfg(), query: "a" });
27
54
  expect(peers).toEqual([
28
55
  { kind: "user", id: "alice" },
29
56
  { kind: "user", id: "carla" },
30
57
  ]);
31
58
  });
32
59
 
60
+ it("normalizes spaced provider-prefixed peer entries", async () => {
61
+ const cfg = {
62
+ channels: {
63
+ feishu: {
64
+ allowFrom: [" feishu:user:ou_alice "],
65
+ dms: {
66
+ " lark:dm:ou_carla ": {},
67
+ },
68
+ groups: {},
69
+ groupAllowFrom: [],
70
+ },
71
+ },
72
+ } as ClawdbotConfig;
73
+
74
+ const peers = await listFeishuDirectoryPeers({ cfg });
75
+ expect(peers).toEqual([
76
+ { kind: "user", id: "ou_alice" },
77
+ { kind: "user", id: "ou_carla" },
78
+ ]);
79
+ });
80
+
33
81
  it("merges groups map + groupAllowFrom into group entries", async () => {
34
- const groups = await listFeishuDirectoryGroups({ cfg });
82
+ const groups = await listFeishuDirectoryGroups({ cfg: makeStaticCfg() });
35
83
  expect(groups).toEqual([
36
84
  { kind: "group", id: "chat-1" },
37
85
  { kind: "group", id: "chat-2" },
38
86
  ]);
39
87
  });
88
+
89
+ it("falls back to static peers on live lookup failure by default", async () => {
90
+ createFeishuClientMock.mockReturnValueOnce({
91
+ contact: {
92
+ user: {
93
+ list: vi.fn(async () => {
94
+ throw new Error("token expired");
95
+ }),
96
+ },
97
+ },
98
+ });
99
+
100
+ const peers = await listFeishuDirectoryPeersLive({ cfg: makeConfiguredCfg(), query: "a" });
101
+ expect(peers).toEqual([
102
+ { kind: "user", id: "alice" },
103
+ { kind: "user", id: "carla" },
104
+ ]);
105
+ });
106
+
107
+ it("surfaces live peer lookup failures when fallback is disabled", async () => {
108
+ createFeishuClientMock.mockReturnValueOnce({
109
+ contact: {
110
+ user: {
111
+ list: vi.fn(async () => {
112
+ throw new Error("token expired");
113
+ }),
114
+ },
115
+ },
116
+ });
117
+
118
+ await expect(
119
+ listFeishuDirectoryPeersLive({ cfg: makeConfiguredCfg(), fallbackToStatic: false }),
120
+ ).rejects.toThrow("token expired");
121
+ });
122
+
123
+ it("surfaces live group lookup failures when fallback is disabled", async () => {
124
+ createFeishuClientMock.mockReturnValueOnce({
125
+ im: {
126
+ chat: {
127
+ list: vi.fn(async () => ({ code: 999, msg: "forbidden" })),
128
+ },
129
+ },
130
+ });
131
+
132
+ await expect(
133
+ listFeishuDirectoryGroupsLive({ cfg: makeConfiguredCfg(), fallbackToStatic: false }),
134
+ ).rejects.toThrow("forbidden");
135
+ });
40
136
  });