@kodelyth/feishu 2026.5.42 → 2026.6.2

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 +19 -6
  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
package/src/probe.test.ts DELETED
@@ -1,283 +0,0 @@
1
- import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import { clearProbeCache, FEISHU_PROBE_REQUEST_TIMEOUT_MS, probeFeishu } from "./probe.js";
3
-
4
- const createFeishuClientMock = vi.hoisted(() => vi.fn());
5
-
6
- vi.mock("./client.js", () => ({
7
- createFeishuClient: createFeishuClientMock,
8
- }));
9
-
10
- const DEFAULT_CREDS = { appId: "cli_123", appSecret: "secret" } as const; // pragma: allowlist secret
11
- const DEFAULT_SUCCESS_RESPONSE = {
12
- code: 0,
13
- data: { pingBotInfo: { botName: "TestBot", botID: "ou_abc123" } },
14
- } as const;
15
- const DEFAULT_SUCCESS_RESULT = {
16
- ok: true,
17
- appId: "cli_123",
18
- botName: "TestBot",
19
- botOpenId: "ou_abc123",
20
- } as const;
21
- const BOT1_RESPONSE = {
22
- code: 0,
23
- data: { pingBotInfo: { botName: "Bot1", botID: "ou_1" } },
24
- } as const;
25
-
26
- afterAll(() => {
27
- vi.doUnmock("./client.js");
28
- vi.resetModules();
29
- });
30
-
31
- function makeRequestFn(response: Record<string, unknown>) {
32
- return vi.fn().mockResolvedValue(response);
33
- }
34
-
35
- function setupClient(response: Record<string, unknown>) {
36
- const requestFn = makeRequestFn(response);
37
- createFeishuClientMock.mockReturnValue({ request: requestFn });
38
- return requestFn;
39
- }
40
-
41
- function setupSuccessClient() {
42
- return setupClient(DEFAULT_SUCCESS_RESPONSE);
43
- }
44
-
45
- async function expectDefaultSuccessResult(
46
- creds = DEFAULT_CREDS,
47
- expected: {
48
- ok: true;
49
- appId: string;
50
- botName: string;
51
- botOpenId: string;
52
- } = DEFAULT_SUCCESS_RESULT,
53
- ) {
54
- const result = await probeFeishu(creds);
55
- expect(result).toEqual(expected);
56
- }
57
-
58
- async function withFakeTimers(run: () => Promise<void>) {
59
- vi.useFakeTimers();
60
- try {
61
- await run();
62
- } finally {
63
- vi.useRealTimers();
64
- }
65
- }
66
-
67
- async function expectErrorResultCached(params: {
68
- requestFn: ReturnType<typeof vi.fn>;
69
- expectedError: string;
70
- ttlMs: number;
71
- }) {
72
- createFeishuClientMock.mockReturnValue({ request: params.requestFn });
73
-
74
- const first = await probeFeishu(DEFAULT_CREDS);
75
- const second = await probeFeishu(DEFAULT_CREDS);
76
- const expected = { ok: false, appId: DEFAULT_CREDS.appId, error: params.expectedError };
77
- expect(first).toEqual(expected);
78
- expect(second).toEqual(expected);
79
- expect(params.requestFn).toHaveBeenCalledTimes(1);
80
-
81
- vi.advanceTimersByTime(params.ttlMs + 1);
82
-
83
- await probeFeishu(DEFAULT_CREDS);
84
- expect(params.requestFn).toHaveBeenCalledTimes(2);
85
- }
86
-
87
- async function expectFreshDefaultProbeAfter(
88
- requestFn: ReturnType<typeof vi.fn>,
89
- invalidate: () => void,
90
- ) {
91
- await probeFeishu(DEFAULT_CREDS);
92
- expect(requestFn).toHaveBeenCalledTimes(1);
93
-
94
- invalidate();
95
-
96
- await probeFeishu(DEFAULT_CREDS);
97
- expect(requestFn).toHaveBeenCalledTimes(2);
98
- }
99
-
100
- async function readSequentialDefaultProbePair() {
101
- const first = await probeFeishu(DEFAULT_CREDS);
102
- return { first, second: await probeFeishu(DEFAULT_CREDS) };
103
- }
104
-
105
- describe("probeFeishu", () => {
106
- beforeEach(() => {
107
- clearProbeCache();
108
- vi.restoreAllMocks();
109
- });
110
-
111
- afterEach(() => {
112
- clearProbeCache();
113
- });
114
-
115
- it("returns error when credentials are missing", async () => {
116
- const result = await probeFeishu();
117
- expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
118
- });
119
-
120
- it("returns error when appId is missing", async () => {
121
- const result = await probeFeishu({ appSecret: "secret" } as never); // pragma: allowlist secret
122
- expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
123
- });
124
-
125
- it("returns error when appSecret is missing", async () => {
126
- const result = await probeFeishu({ appId: "cli_123" } as never);
127
- expect(result).toEqual({ ok: false, error: "missing credentials (appId, appSecret)" });
128
- });
129
-
130
- it("returns bot info on successful probe", async () => {
131
- const requestFn = setupSuccessClient();
132
-
133
- await expectDefaultSuccessResult();
134
- expect(requestFn).toHaveBeenCalledTimes(1);
135
- });
136
-
137
- it("passes the probe timeout to the Feishu request", async () => {
138
- const requestFn = setupSuccessClient();
139
-
140
- await probeFeishu(DEFAULT_CREDS);
141
-
142
- expect(requestFn).toHaveBeenCalledWith({
143
- method: "POST",
144
- url: "/open-apis/bot/v1/klaw_bot/ping",
145
- data: { needBotInfo: true },
146
- timeout: FEISHU_PROBE_REQUEST_TIMEOUT_MS,
147
- });
148
- });
149
-
150
- it("returns timeout error when request exceeds timeout", async () => {
151
- await withFakeTimers(async () => {
152
- const requestFn = vi.fn().mockImplementation(() => new Promise(() => {}));
153
- createFeishuClientMock.mockReturnValue({ request: requestFn });
154
-
155
- const promise = probeFeishu(DEFAULT_CREDS, { timeoutMs: 1_000 });
156
- await vi.advanceTimersByTimeAsync(1_000);
157
- const result = await promise;
158
-
159
- expect(result).toEqual({
160
- ok: false,
161
- appId: DEFAULT_CREDS.appId,
162
- error: "probe timed out after 1000ms",
163
- });
164
- });
165
- });
166
-
167
- it("returns aborted when abort signal is already aborted", async () => {
168
- createFeishuClientMock.mockClear();
169
- const abortController = new AbortController();
170
- abortController.abort();
171
-
172
- const result = await probeFeishu(
173
- { appId: "cli_123", appSecret: "secret" }, // pragma: allowlist secret
174
- { abortSignal: abortController.signal },
175
- );
176
-
177
- expect(result).toEqual({ ok: false, appId: "cli_123", error: "probe aborted" });
178
- expect(createFeishuClientMock).not.toHaveBeenCalled();
179
- });
180
- it("returns cached result on subsequent calls within TTL", async () => {
181
- const requestFn = setupSuccessClient();
182
-
183
- const { first, second } = await readSequentialDefaultProbePair();
184
-
185
- expect(first).toEqual(second);
186
- // Only one API call should have been made
187
- expect(requestFn).toHaveBeenCalledTimes(1);
188
- });
189
-
190
- it("makes a fresh API call after cache expires", async () => {
191
- await withFakeTimers(async () => {
192
- const requestFn = setupSuccessClient();
193
-
194
- await expectFreshDefaultProbeAfter(requestFn, () => {
195
- vi.advanceTimersByTime(10 * 60 * 1000 + 1);
196
- });
197
- });
198
- });
199
-
200
- it("caches failed probe results (API error) for the error TTL", async () => {
201
- await withFakeTimers(async () => {
202
- await expectErrorResultCached({
203
- requestFn: makeRequestFn({ code: 99, msg: "token expired" }),
204
- expectedError: "API error: token expired",
205
- ttlMs: 60 * 1000,
206
- });
207
- });
208
- });
209
-
210
- it("caches thrown request errors for the error TTL", async () => {
211
- await withFakeTimers(async () => {
212
- await expectErrorResultCached({
213
- requestFn: vi.fn().mockRejectedValue(new Error("network error")),
214
- expectedError: "network error",
215
- ttlMs: 60 * 1000,
216
- });
217
- });
218
- });
219
-
220
- it("caches per account independently", async () => {
221
- const requestFn = setupClient(BOT1_RESPONSE);
222
-
223
- await probeFeishu({ appId: "cli_aaa", appSecret: "s1" }); // pragma: allowlist secret
224
- expect(requestFn).toHaveBeenCalledTimes(1);
225
-
226
- // Different appId should trigger a new API call
227
- await probeFeishu({ appId: "cli_bbb", appSecret: "s2" }); // pragma: allowlist secret
228
- expect(requestFn).toHaveBeenCalledTimes(2);
229
-
230
- // Same appId + appSecret as first call should return cached
231
- await probeFeishu({ appId: "cli_aaa", appSecret: "s1" }); // pragma: allowlist secret
232
- expect(requestFn).toHaveBeenCalledTimes(2);
233
- });
234
-
235
- it("does not share cache between accounts with same appId but different appSecret", async () => {
236
- const requestFn = setupClient(BOT1_RESPONSE);
237
-
238
- // First account with appId + secret A
239
- await probeFeishu({ appId: "cli_shared", appSecret: "secret_aaa" }); // pragma: allowlist secret
240
- expect(requestFn).toHaveBeenCalledTimes(1);
241
-
242
- // Second account with same appId but different secret (e.g. after rotation)
243
- // must NOT reuse the cached result
244
- await probeFeishu({ appId: "cli_shared", appSecret: "secret_bbb" }); // pragma: allowlist secret
245
- expect(requestFn).toHaveBeenCalledTimes(2);
246
- });
247
-
248
- it("uses accountId for cache key when available", async () => {
249
- const requestFn = setupClient(BOT1_RESPONSE);
250
-
251
- // Two accounts with same appId+appSecret but different accountIds are cached separately
252
- await probeFeishu({ accountId: "acct-1", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
253
- expect(requestFn).toHaveBeenCalledTimes(1);
254
-
255
- await probeFeishu({ accountId: "acct-2", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
256
- expect(requestFn).toHaveBeenCalledTimes(2);
257
-
258
- // Same accountId should return cached
259
- await probeFeishu({ accountId: "acct-1", appId: "cli_123", appSecret: "secret" }); // pragma: allowlist secret
260
- expect(requestFn).toHaveBeenCalledTimes(2);
261
- });
262
-
263
- it("clearProbeCache forces fresh API call", async () => {
264
- const requestFn = setupSuccessClient();
265
-
266
- await expectFreshDefaultProbeAfter(requestFn, () => {
267
- clearProbeCache();
268
- });
269
- });
270
-
271
- it("handles response with pingBotInfo in data", async () => {
272
- setupClient({
273
- code: 0,
274
- data: { pingBotInfo: { botName: "DataBot", botID: "ou_data" } },
275
- });
276
-
277
- await expectDefaultSuccessResult(DEFAULT_CREDS, {
278
- ...DEFAULT_SUCCESS_RESULT,
279
- botName: "DataBot",
280
- botOpenId: "ou_data",
281
- });
282
- });
283
- });
package/src/probe.ts DELETED
@@ -1,166 +0,0 @@
1
- import { formatErrorMessage } from "klaw/plugin-sdk/error-runtime";
2
- import { raceWithTimeoutAndAbort } from "./async.js";
3
- import { createFeishuClient, type FeishuClientCredentials } from "./client.js";
4
- import type { FeishuProbeResult } from "./types.js";
5
-
6
- /** Cache probe results to reduce repeated health-check calls.
7
- * Gateway health checks call probeFeishu() every minute; without caching this
8
- * burns ~43,200 calls/month, easily exceeding Feishu's free-tier quota.
9
- * Successful bot info is effectively static, while failures are cached briefly
10
- * to avoid hammering the API during transient outages. */
11
- const probeCache = new Map<string, { result: FeishuProbeResult; expiresAt: number }>();
12
- const PROBE_SUCCESS_TTL_MS = 10 * 60 * 1000; // 10 minutes
13
- const PROBE_ERROR_TTL_MS = 60 * 1000; // 1 minute
14
- const MAX_PROBE_CACHE_SIZE = 64;
15
- export const FEISHU_PROBE_REQUEST_TIMEOUT_MS = 10_000;
16
- export type ProbeFeishuOptions = {
17
- timeoutMs?: number;
18
- abortSignal?: AbortSignal;
19
- };
20
-
21
- type FeishuPingResponse = {
22
- code: number;
23
- msg?: string;
24
- data?: { pingBotInfo?: { botID?: string; botName?: string } };
25
- };
26
-
27
- type FeishuRequestClient = ReturnType<typeof createFeishuClient> & {
28
- request(params: {
29
- method: "POST";
30
- url: string;
31
- data: Record<string, unknown>;
32
- timeout: number;
33
- }): Promise<FeishuPingResponse>;
34
- };
35
-
36
- function setCachedProbeResult(
37
- cacheKey: string,
38
- result: FeishuProbeResult,
39
- ttlMs: number,
40
- ): FeishuProbeResult {
41
- probeCache.set(cacheKey, { result, expiresAt: Date.now() + ttlMs });
42
- if (probeCache.size > MAX_PROBE_CACHE_SIZE) {
43
- const oldest = probeCache.keys().next().value;
44
- if (oldest !== undefined) {
45
- probeCache.delete(oldest);
46
- }
47
- }
48
- return result;
49
- }
50
-
51
- export async function probeFeishu(
52
- creds?: FeishuClientCredentials,
53
- options: ProbeFeishuOptions = {},
54
- ): Promise<FeishuProbeResult> {
55
- if (!creds?.appId || !creds?.appSecret) {
56
- return {
57
- ok: false,
58
- error: "missing credentials (appId, appSecret)",
59
- };
60
- }
61
- if (options.abortSignal?.aborted) {
62
- return {
63
- ok: false,
64
- appId: creds.appId,
65
- error: "probe aborted",
66
- };
67
- }
68
-
69
- const timeoutMs = options.timeoutMs ?? FEISHU_PROBE_REQUEST_TIMEOUT_MS;
70
-
71
- // Return cached result if still valid.
72
- // Use accountId when available; otherwise include appSecret prefix so two
73
- // accounts sharing the same appId (e.g. after secret rotation) don't
74
- // pollute each other's cache entry.
75
- const cacheKey = creds.accountId ?? `${creds.appId}:${creds.appSecret.slice(0, 8)}`;
76
- const cached = probeCache.get(cacheKey);
77
- if (cached && cached.expiresAt > Date.now()) {
78
- return cached.result;
79
- }
80
-
81
- try {
82
- const client = createFeishuClient(creds) as FeishuRequestClient;
83
- // Feishu-provided endpoint for Klaw, supported on both Feishu (CN)
84
- // and Lark (international). No OAuth scopes required. Validates
85
- // credentials and registers the app as an AI agent (智能体).
86
- const responseResult = await raceWithTimeoutAndAbort<FeishuPingResponse>(
87
- client.request({
88
- method: "POST",
89
- url: "/open-apis/bot/v1/klaw_bot/ping",
90
- data: { needBotInfo: true },
91
- timeout: timeoutMs,
92
- }),
93
- {
94
- timeoutMs,
95
- abortSignal: options.abortSignal,
96
- },
97
- );
98
-
99
- if (responseResult.status === "aborted") {
100
- return {
101
- ok: false,
102
- appId: creds.appId,
103
- error: "probe aborted",
104
- };
105
- }
106
- if (responseResult.status === "timeout") {
107
- return setCachedProbeResult(
108
- cacheKey,
109
- {
110
- ok: false,
111
- appId: creds.appId,
112
- error: `probe timed out after ${timeoutMs}ms`,
113
- },
114
- PROBE_ERROR_TTL_MS,
115
- );
116
- }
117
-
118
- const response = responseResult.value;
119
- if (options.abortSignal?.aborted) {
120
- return {
121
- ok: false,
122
- appId: creds.appId,
123
- error: "probe aborted",
124
- };
125
- }
126
-
127
- if (response.code !== 0) {
128
- return setCachedProbeResult(
129
- cacheKey,
130
- {
131
- ok: false,
132
- appId: creds.appId,
133
- error: `API error: ${response.msg || `code ${response.code}`}`,
134
- },
135
- PROBE_ERROR_TTL_MS,
136
- );
137
- }
138
-
139
- const botInfo = response.data?.pingBotInfo;
140
- return setCachedProbeResult(
141
- cacheKey,
142
- {
143
- ok: true,
144
- appId: creds.appId,
145
- botName: botInfo?.botName,
146
- botOpenId: botInfo?.botID,
147
- },
148
- PROBE_SUCCESS_TTL_MS,
149
- );
150
- } catch (err) {
151
- return setCachedProbeResult(
152
- cacheKey,
153
- {
154
- ok: false,
155
- appId: creds.appId,
156
- error: formatErrorMessage(err),
157
- },
158
- PROBE_ERROR_TTL_MS,
159
- );
160
- }
161
- }
162
-
163
- /** Clear the probe cache (for testing). */
164
- export function clearProbeCache(): void {
165
- probeCache.clear();
166
- }
@@ -1,59 +0,0 @@
1
- const EVENT_DEDUP_TTL_MS = 5 * 60 * 1000;
2
- const EVENT_MEMORY_MAX_SIZE = 2_000;
3
-
4
- const processingClaims = new Map<string, number>();
5
-
6
- function resolveEventDedupeKey(
7
- namespace: string,
8
- messageId: string | undefined | null,
9
- ): string | null {
10
- const trimmed = messageId?.trim();
11
- return trimmed ? `${namespace}:${trimmed}` : null;
12
- }
13
-
14
- function pruneProcessingClaims(now: number): void {
15
- const cutoff = now - EVENT_DEDUP_TTL_MS;
16
- for (const [key, seenAt] of processingClaims) {
17
- if (seenAt < cutoff) {
18
- processingClaims.delete(key);
19
- }
20
- }
21
- while (processingClaims.size > EVENT_MEMORY_MAX_SIZE) {
22
- const oldestKey = processingClaims.keys().next().value;
23
- if (!oldestKey) {
24
- return;
25
- }
26
- processingClaims.delete(oldestKey);
27
- }
28
- }
29
-
30
- export function tryBeginFeishuMessageProcessing(
31
- messageId: string | undefined | null,
32
- namespace = "global",
33
- ): boolean {
34
- const key = resolveEventDedupeKey(namespace, messageId);
35
- if (!key) {
36
- return true;
37
- }
38
- const now = Date.now();
39
- pruneProcessingClaims(now);
40
- if (processingClaims.has(key)) {
41
- processingClaims.delete(key);
42
- processingClaims.set(key, now);
43
- pruneProcessingClaims(now);
44
- return false;
45
- }
46
- processingClaims.set(key, now);
47
- pruneProcessingClaims(now);
48
- return true;
49
- }
50
-
51
- export function releaseFeishuMessageProcessing(
52
- messageId: string | undefined | null,
53
- namespace = "global",
54
- ): void {
55
- const key = resolveEventDedupeKey(namespace, messageId);
56
- if (key) {
57
- processingClaims.delete(key);
58
- }
59
- }
@@ -1 +0,0 @@
1
- export { renderQrTerminal } from "klaw/plugin-sdk/media-runtime";
package/src/reactions.ts DELETED
@@ -1,123 +0,0 @@
1
- import type { ClawdbotConfig } from "../runtime-api.js";
2
- import { resolveFeishuRuntimeAccount } from "./accounts.js";
3
- import { createFeishuClient } from "./client.js";
4
-
5
- type FeishuReaction = {
6
- reactionId: string;
7
- emojiType: string;
8
- operatorType: "app" | "user";
9
- operatorId: string;
10
- };
11
-
12
- function resolveConfiguredFeishuClient(params: { cfg: ClawdbotConfig; accountId?: string }) {
13
- const account = resolveFeishuRuntimeAccount(params);
14
- if (!account.configured) {
15
- throw new Error(`Feishu account "${account.accountId}" not configured`);
16
- }
17
- return createFeishuClient(account);
18
- }
19
-
20
- function assertFeishuReactionApiSuccess(response: { code?: number; msg?: string }, action: string) {
21
- if (response.code !== 0) {
22
- throw new Error(`Feishu ${action} failed: ${response.msg || `code ${response.code}`}`);
23
- }
24
- }
25
-
26
- /**
27
- * Add a reaction (emoji) to a message.
28
- * @param emojiType - Feishu emoji type, e.g., "SMILE", "THUMBSUP", "HEART"
29
- * @see https://open.feishu.cn/document/server-docs/im-v1/message-reaction/emojis-introduce
30
- */
31
- export async function addReactionFeishu(params: {
32
- cfg: ClawdbotConfig;
33
- messageId: string;
34
- emojiType: string;
35
- accountId?: string;
36
- }): Promise<{ reactionId: string }> {
37
- const { cfg, messageId, emojiType, accountId } = params;
38
- const client = resolveConfiguredFeishuClient({ cfg, accountId });
39
-
40
- const response = (await client.im.messageReaction.create({
41
- path: { message_id: messageId },
42
- data: {
43
- reaction_type: {
44
- emoji_type: emojiType,
45
- },
46
- },
47
- })) as {
48
- code?: number;
49
- msg?: string;
50
- data?: { reaction_id?: string };
51
- };
52
-
53
- assertFeishuReactionApiSuccess(response, "add reaction");
54
-
55
- const reactionId = response.data?.reaction_id;
56
- if (!reactionId) {
57
- throw new Error("Feishu add reaction failed: no reaction_id returned");
58
- }
59
-
60
- return { reactionId };
61
- }
62
-
63
- /**
64
- * Remove a reaction from a message.
65
- */
66
- export async function removeReactionFeishu(params: {
67
- cfg: ClawdbotConfig;
68
- messageId: string;
69
- reactionId: string;
70
- accountId?: string;
71
- }): Promise<void> {
72
- const { cfg, messageId, reactionId, accountId } = params;
73
- const client = resolveConfiguredFeishuClient({ cfg, accountId });
74
-
75
- const response = (await client.im.messageReaction.delete({
76
- path: {
77
- message_id: messageId,
78
- reaction_id: reactionId,
79
- },
80
- })) as { code?: number; msg?: string };
81
-
82
- assertFeishuReactionApiSuccess(response, "remove reaction");
83
- }
84
-
85
- /**
86
- * List all reactions for a message.
87
- */
88
- export async function listReactionsFeishu(params: {
89
- cfg: ClawdbotConfig;
90
- messageId: string;
91
- emojiType?: string;
92
- accountId?: string;
93
- }): Promise<FeishuReaction[]> {
94
- const { cfg, messageId, emojiType, accountId } = params;
95
- const client = resolveConfiguredFeishuClient({ cfg, accountId });
96
-
97
- const response = (await client.im.messageReaction.list({
98
- path: { message_id: messageId },
99
- params: emojiType ? { reaction_type: emojiType } : undefined,
100
- })) as {
101
- code?: number;
102
- msg?: string;
103
- data?: {
104
- items?: Array<{
105
- reaction_id?: string;
106
- reaction_type?: { emoji_type?: string };
107
- operator_type?: string;
108
- operator_id?: { open_id?: string; user_id?: string; union_id?: string };
109
- }>;
110
- };
111
- };
112
-
113
- assertFeishuReactionApiSuccess(response, "list reactions");
114
-
115
- const items = response.data?.items ?? [];
116
- return items.map((item) => ({
117
- reactionId: item.reaction_id ?? "",
118
- emojiType: item.reaction_type?.emoji_type ?? "",
119
- operatorType: item.operator_type === "app" ? "app" : "user",
120
- operatorId:
121
- item.operator_id?.open_id ?? item.operator_id?.user_id ?? item.operator_id?.union_id ?? "",
122
- }));
123
- }