@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
@@ -1,303 +0,0 @@
1
- import { resolveChannelConfigWrites } from "klaw/plugin-sdk/channel-config-writes";
2
- import type { ResolvedAgentRoute } from "klaw/plugin-sdk/routing";
3
- import { resolveFeishuRuntimeAccount } from "./accounts.js";
4
- import { createFeishuClient } from "./client.js";
5
- import { createFeishuCommentReplyDispatcher } from "./comment-dispatcher.js";
6
- import {
7
- createChannelPairingController,
8
- type ClawdbotConfig,
9
- type RuntimeEnv,
10
- } from "./comment-handler-runtime-api.js";
11
- import { buildFeishuCommentTarget } from "./comment-target.js";
12
- import { deliverCommentThreadText } from "./drive.js";
13
- import { maybeCreateDynamicAgent } from "./dynamic-agent.js";
14
- import {
15
- resolveDriveCommentEventTurn,
16
- type FeishuDriveCommentNoticeEvent,
17
- } from "./monitor.comment.js";
18
- import { resolveFeishuDmIngressAccess } from "./policy.js";
19
- import { getFeishuRuntime } from "./runtime.js";
20
- import type { DynamicAgentCreationConfig } from "./types.js";
21
-
22
- type HandleFeishuCommentEventParams = {
23
- cfg: ClawdbotConfig;
24
- accountId: string;
25
- runtime?: RuntimeEnv;
26
- event: FeishuDriveCommentNoticeEvent;
27
- botOpenId?: string;
28
- };
29
-
30
- function buildCommentSessionKey(params: {
31
- core: ReturnType<typeof getFeishuRuntime>;
32
- route: ResolvedAgentRoute;
33
- fileType: string;
34
- fileToken: string;
35
- }): string {
36
- return params.core.channel.routing.buildAgentSessionKey({
37
- agentId: params.route.agentId,
38
- channel: "feishu",
39
- accountId: params.route.accountId,
40
- peer: {
41
- kind: "direct",
42
- id: `comment-doc:${params.fileType}:${params.fileToken}`,
43
- },
44
- dmScope: "per-account-channel-peer",
45
- });
46
- }
47
-
48
- function parseTimestampMs(value: string | undefined): number {
49
- const parsed = value ? Number.parseInt(value, 10) : Number.NaN;
50
- return Number.isFinite(parsed) ? parsed : Date.now();
51
- }
52
-
53
- export async function handleFeishuCommentEvent(
54
- params: HandleFeishuCommentEventParams,
55
- ): Promise<void> {
56
- const account = resolveFeishuRuntimeAccount({ cfg: params.cfg, accountId: params.accountId });
57
- const feishuCfg = account.config;
58
- const core = getFeishuRuntime();
59
- const log = params.runtime?.log ?? console.log;
60
- const error = params.runtime?.error ?? console.error;
61
- const runtime = (params.runtime ?? { log, error }) as RuntimeEnv;
62
-
63
- const turn = await resolveDriveCommentEventTurn({
64
- cfg: params.cfg,
65
- accountId: account.accountId,
66
- event: params.event,
67
- botOpenId: params.botOpenId,
68
- logger: log,
69
- });
70
- if (!turn) {
71
- log(
72
- `feishu[${account.accountId}]: drive comment notice skipped ` +
73
- `event=${params.event.event_id ?? "unknown"} comment=${params.event.comment_id ?? "unknown"}`,
74
- );
75
- return;
76
- }
77
-
78
- const commentTarget = buildFeishuCommentTarget({
79
- fileType: turn.fileType,
80
- fileToken: turn.fileToken,
81
- commentId: turn.commentId,
82
- });
83
- const dmPolicy = feishuCfg?.dmPolicy ?? "pairing";
84
- const configAllowFrom = feishuCfg?.allowFrom ?? [];
85
- const pairing = createChannelPairingController({
86
- core,
87
- channel: "feishu",
88
- accountId: account.accountId,
89
- });
90
- const dmIngress = await resolveFeishuDmIngressAccess({
91
- cfg: params.cfg,
92
- accountId: account.accountId,
93
- dmPolicy,
94
- allowFrom: configAllowFrom,
95
- readAllowFromStore: pairing.readAllowFromStore,
96
- senderOpenId: turn.senderId,
97
- senderUserId: turn.senderUserId,
98
- conversationId: turn.senderId,
99
- mayPair: true,
100
- });
101
- if (dmIngress.ingress.admission !== "dispatch") {
102
- if (dmIngress.ingress.admission === "pairing-required") {
103
- const client = createFeishuClient(account);
104
- await pairing.issueChallenge({
105
- senderId: turn.senderId,
106
- senderIdLine: `Your Feishu user id: ${turn.senderId}`,
107
- meta: { name: turn.senderId },
108
- onCreated: ({ code }) => {
109
- log(
110
- `feishu[${account.accountId}]: comment pairing request sender=${turn.senderId} code=${code}`,
111
- );
112
- },
113
- sendPairingReply: async (text) => {
114
- await deliverCommentThreadText(client, {
115
- file_token: turn.fileToken,
116
- file_type: turn.fileType,
117
- comment_id: turn.commentId,
118
- content: text,
119
- is_whole_comment: turn.isWholeComment,
120
- });
121
- },
122
- onReplyError: (err) => {
123
- log(
124
- `feishu[${account.accountId}]: comment pairing reply failed for ${turn.senderId}: ${String(err)}`,
125
- );
126
- },
127
- });
128
- } else {
129
- log(
130
- `feishu[${account.accountId}]: blocked unauthorized comment sender ${turn.senderId} ` +
131
- `(dmPolicy=${dmPolicy}, comment=${turn.commentId})`,
132
- );
133
- }
134
- return;
135
- }
136
-
137
- let effectiveCfg = params.cfg;
138
- let route = core.channel.routing.resolveAgentRoute({
139
- cfg: params.cfg,
140
- channel: "feishu",
141
- accountId: account.accountId,
142
- peer: {
143
- kind: "direct",
144
- id: turn.senderId,
145
- },
146
- });
147
- if (route.matchedBy === "default") {
148
- const dynamicCfg = feishuCfg?.dynamicAgentCreation as DynamicAgentCreationConfig | undefined;
149
- if (dynamicCfg?.enabled) {
150
- const dynamicResult = await maybeCreateDynamicAgent({
151
- cfg: params.cfg,
152
- runtime: core,
153
- senderOpenId: turn.senderId,
154
- dynamicCfg,
155
- configWritesAllowed: resolveChannelConfigWrites({
156
- cfg: params.cfg,
157
- channelId: "feishu",
158
- accountId: account.accountId,
159
- }),
160
- log: (message) => log(message),
161
- });
162
- if (dynamicResult.created) {
163
- effectiveCfg = dynamicResult.updatedCfg;
164
- route = core.channel.routing.resolveAgentRoute({
165
- cfg: dynamicResult.updatedCfg,
166
- channel: "feishu",
167
- accountId: account.accountId,
168
- peer: {
169
- kind: "direct",
170
- id: turn.senderId,
171
- },
172
- });
173
- log(
174
- `feishu[${account.accountId}]: dynamic agent created for comment flow, route=${route.sessionKey}`,
175
- );
176
- }
177
- }
178
- }
179
-
180
- const commentSessionKey = buildCommentSessionKey({
181
- core,
182
- route,
183
- fileType: turn.fileType,
184
- fileToken: turn.fileToken,
185
- });
186
- const bodyForAgent = `[message_id: ${turn.messageId}]\n${turn.prompt}`;
187
- const ctxPayload = core.channel.reply.finalizeInboundContext({
188
- Body: bodyForAgent,
189
- BodyForAgent: bodyForAgent,
190
- RawBody: turn.targetReplyText ?? turn.rootCommentText ?? turn.prompt,
191
- CommandBody: turn.targetReplyText ?? turn.rootCommentText ?? turn.prompt,
192
- From: `feishu:${turn.senderId}`,
193
- To: commentTarget,
194
- SessionKey: commentSessionKey,
195
- AccountId: route.accountId,
196
- ChatType: "direct",
197
- ConversationLabel: turn.documentTitle
198
- ? `Feishu comment · ${turn.documentTitle}`
199
- : "Feishu comment",
200
- SenderName: turn.senderId,
201
- SenderId: turn.senderId,
202
- Provider: "feishu",
203
- Surface: "feishu-comment",
204
- MessageSid: turn.messageId,
205
- // For Feishu comment turns, MessageThreadId carries the inbound reply_id so
206
- // comment-aware tools can clean typing reaction before sending visible output.
207
- MessageThreadId: turn.replyId,
208
- Timestamp: parseTimestampMs(turn.timestamp),
209
- WasMentioned: turn.isMentioned,
210
- CommandAuthorized: false,
211
- OriginatingChannel: "feishu",
212
- OriginatingTo: commentTarget,
213
- });
214
-
215
- const storePath = core.channel.session.resolveStorePath(effectiveCfg.session?.store, {
216
- agentId: route.agentId,
217
- });
218
-
219
- const { dispatcher, replyOptions, markDispatchIdle, markRunComplete, cleanupTypingReaction } =
220
- createFeishuCommentReplyDispatcher({
221
- cfg: effectiveCfg,
222
- agentId: route.agentId,
223
- runtime,
224
- accountId: account.accountId,
225
- fileToken: turn.fileToken,
226
- fileType: turn.fileType,
227
- commentId: turn.commentId,
228
- replyId: turn.replyId,
229
- isWholeComment: turn.isWholeComment,
230
- });
231
-
232
- let dispatchSettledBeforeStart = false;
233
- try {
234
- log(
235
- `feishu[${account.accountId}]: dispatching drive comment to agent ` +
236
- `(session=${commentSessionKey} comment=${turn.commentId} type=${turn.noticeType})`,
237
- );
238
- const turnResult = await core.channel.turn.run({
239
- channel: "feishu",
240
- accountId: route.accountId,
241
- raw: turn,
242
- adapter: {
243
- ingest: () => ({
244
- id: turn.messageId,
245
- timestamp: parseTimestampMs(turn.timestamp),
246
- rawText: ctxPayload.RawBody ?? "",
247
- textForAgent: ctxPayload.BodyForAgent,
248
- textForCommands: ctxPayload.CommandBody,
249
- raw: turn,
250
- }),
251
- resolveTurn: () => ({
252
- channel: "feishu",
253
- accountId: route.accountId,
254
- routeSessionKey: commentSessionKey,
255
- storePath,
256
- ctxPayload,
257
- recordInboundSession: core.channel.session.recordInboundSession,
258
- record: {
259
- onRecordError: (err) => {
260
- error(
261
- `feishu[${account.accountId}]: failed to record comment inbound session ${commentSessionKey}: ${String(err)}`,
262
- );
263
- },
264
- },
265
- onPreDispatchFailure: async () => {
266
- dispatchSettledBeforeStart = true;
267
- await core.channel.reply.settleReplyDispatcher({
268
- dispatcher,
269
- onSettled: () => {
270
- markRunComplete();
271
- markDispatchIdle();
272
- },
273
- });
274
- },
275
- runDispatch: () =>
276
- core.channel.reply.withReplyDispatcher({
277
- dispatcher,
278
- run: () =>
279
- core.channel.reply.dispatchReplyFromConfig({
280
- ctx: ctxPayload,
281
- cfg: effectiveCfg,
282
- dispatcher,
283
- replyOptions,
284
- }),
285
- }),
286
- }),
287
- },
288
- });
289
- const dispatchResult = turnResult.dispatched ? turnResult.dispatchResult : undefined;
290
- const queuedFinal = dispatchResult?.queuedFinal ?? false;
291
- const counts = dispatchResult?.counts ?? { tool: 0, block: 0, final: 0 };
292
- log(
293
- `feishu[${account.accountId}]: drive comment dispatch complete ` +
294
- `(queuedFinal=${queuedFinal}, replies=${counts.final}, session=${commentSessionKey})`,
295
- );
296
- } finally {
297
- if (!dispatchSettledBeforeStart) {
298
- markRunComplete();
299
- markDispatchIdle();
300
- }
301
- void cleanupTypingReaction();
302
- }
303
- }
@@ -1,138 +0,0 @@
1
- import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
2
- import type { ClawdbotConfig } from "../runtime-api.js";
3
- import {
4
- cleanupAmbientCommentTypingReaction,
5
- createCommentTypingReactionLifecycle,
6
- } from "./comment-reaction.js";
7
-
8
- const resolveFeishuRuntimeAccountMock = vi.hoisted(() => vi.fn());
9
- const createFeishuClientMock = vi.hoisted(() => vi.fn());
10
-
11
- vi.mock("./accounts.js", () => ({
12
- resolveFeishuRuntimeAccount: resolveFeishuRuntimeAccountMock,
13
- }));
14
-
15
- vi.mock("./client.js", () => ({
16
- createFeishuClient: createFeishuClientMock,
17
- }));
18
-
19
- describe("createCommentTypingReactionLifecycle", () => {
20
- const request = vi.fn();
21
- const commentReactionUrl =
22
- "/open-apis/drive/v2/files/doc_token_1/comments/reaction?file_type=docx";
23
-
24
- function expectedTypingReactionRequest(action: "add" | "delete") {
25
- return {
26
- method: "POST",
27
- url: commentReactionUrl,
28
- data: {
29
- action,
30
- reply_id: "reply_1",
31
- reaction_type: "Typing",
32
- },
33
- timeout: 30_000,
34
- };
35
- }
36
-
37
- afterAll(() => {
38
- vi.doUnmock("./accounts.js");
39
- vi.doUnmock("./client.js");
40
- vi.resetModules();
41
- });
42
-
43
- beforeEach(() => {
44
- vi.clearAllMocks();
45
- resolveFeishuRuntimeAccountMock.mockReturnValue({
46
- accountId: "default",
47
- configured: true,
48
- config: {
49
- typingIndicator: true,
50
- },
51
- });
52
- createFeishuClientMock.mockReturnValue({
53
- request,
54
- });
55
- request.mockResolvedValue({
56
- code: 0,
57
- data: {},
58
- });
59
- });
60
-
61
- function createTypingReactionLifecycle(...args: [replyId?: string]) {
62
- return createCommentTypingReactionLifecycle({
63
- cfg: {} as ClawdbotConfig,
64
- fileToken: "doc_token_1",
65
- fileType: "docx",
66
- replyId: args.length === 0 ? "reply_1" : args[0],
67
- runtime: {
68
- log: vi.fn(),
69
- } as never,
70
- });
71
- }
72
-
73
- const cleanupAmbientReply = () =>
74
- cleanupAmbientCommentTypingReaction({
75
- client: { request } as never,
76
- deliveryContext: {
77
- channel: "feishu",
78
- to: "comment:docx:doc_token_1:comment_1",
79
- threadId: "reply_1",
80
- },
81
- });
82
-
83
- it("adds and removes a comment typing reaction using reply_id", async () => {
84
- const lifecycle = createTypingReactionLifecycle();
85
-
86
- await lifecycle.start();
87
- await lifecycle.cleanup();
88
-
89
- expect(request).toHaveBeenNthCalledWith(1, expectedTypingReactionRequest("add"));
90
- expect(request).toHaveBeenNthCalledWith(2, expectedTypingReactionRequest("delete"));
91
- });
92
-
93
- it("skips requests when reply_id is missing", async () => {
94
- const lifecycle = createTypingReactionLifecycle(undefined);
95
-
96
- await lifecycle.start();
97
- await lifecycle.cleanup();
98
-
99
- expect(request).not.toHaveBeenCalled();
100
- });
101
-
102
- it("shares cleanup state so ambient cleanup and finally cleanup do not delete twice", async () => {
103
- const lifecycle = createTypingReactionLifecycle();
104
-
105
- await lifecycle.start();
106
- await cleanupAmbientReply();
107
- await lifecycle.cleanup();
108
-
109
- expect(request).toHaveBeenCalledTimes(2);
110
- expect(request).toHaveBeenNthCalledWith(2, expectedTypingReactionRequest("delete"));
111
- });
112
-
113
- it("retries delete during later cleanup after an ambient delete failure", async () => {
114
- request
115
- .mockResolvedValueOnce({
116
- code: 0,
117
- data: {},
118
- })
119
- .mockResolvedValueOnce({
120
- code: 5001,
121
- msg: "temporary failure",
122
- })
123
- .mockResolvedValueOnce({
124
- code: 0,
125
- data: {},
126
- });
127
-
128
- const lifecycle = createTypingReactionLifecycle();
129
-
130
- await lifecycle.start();
131
- await cleanupAmbientReply();
132
- await lifecycle.cleanup();
133
-
134
- expect(request).toHaveBeenCalledTimes(3);
135
- expect(request).toHaveBeenNthCalledWith(2, expectedTypingReactionRequest("delete"));
136
- expect(request).toHaveBeenNthCalledWith(3, expectedTypingReactionRequest("delete"));
137
- });
138
- });
@@ -1,259 +0,0 @@
1
- import type { ClawdbotConfig, RuntimeEnv } from "../runtime-api.js";
2
- import { resolveFeishuRuntimeAccount } from "./accounts.js";
3
- import { createFeishuClient } from "./client.js";
4
- import { encodeQuery, formatFeishuApiError } from "./comment-shared.js";
5
- import { parseFeishuCommentTarget, type CommentFileType } from "./comment-target.js";
6
-
7
- const COMMENT_TYPING_REACTION_TYPE = "Typing";
8
- const COMMENT_REACTION_TIMEOUT_MS = 30_000;
9
- const commentTypingReactionState = new Map<
10
- string,
11
- {
12
- active: boolean;
13
- cleaned: boolean;
14
- cleanupPromise?: Promise<boolean>;
15
- }
16
- >();
17
-
18
- type FeishuCommentReactionClient = ReturnType<typeof createFeishuClient> & {
19
- request(params: {
20
- method: "POST";
21
- url: string;
22
- data: unknown;
23
- timeout: number;
24
- }): Promise<unknown>;
25
- };
26
-
27
- function buildCommentTypingReactionKey(params: {
28
- fileToken: string;
29
- fileType: CommentFileType;
30
- replyId: string;
31
- }): string {
32
- return `${params.fileType}:${params.fileToken}:${params.replyId}`;
33
- }
34
-
35
- function ensureCommentTypingReactionState(key: string) {
36
- const existing = commentTypingReactionState.get(key);
37
- if (existing) {
38
- return existing;
39
- }
40
- const created = {
41
- active: false,
42
- cleaned: false,
43
- cleanupPromise: undefined,
44
- };
45
- commentTypingReactionState.set(key, created);
46
- return created;
47
- }
48
-
49
- async function requestCommentTypingReactionWithClient(params: {
50
- client: FeishuCommentReactionClient;
51
- fileToken: string;
52
- fileType: CommentFileType;
53
- replyId: string;
54
- action: "add" | "delete";
55
- runtime?: RuntimeEnv;
56
- logPrefix?: string;
57
- }): Promise<boolean> {
58
- try {
59
- const response = (await params.client.request({
60
- method: "POST",
61
- url:
62
- `/open-apis/drive/v2/files/${encodeURIComponent(params.fileToken)}/comments/reaction` +
63
- encodeQuery({
64
- file_type: params.fileType,
65
- }),
66
- data: {
67
- action: params.action,
68
- reply_id: params.replyId,
69
- reaction_type: COMMENT_TYPING_REACTION_TYPE,
70
- },
71
- timeout: COMMENT_REACTION_TIMEOUT_MS,
72
- })) as {
73
- code?: number;
74
- msg?: string;
75
- log_id?: string;
76
- error?: { log_id?: string };
77
- };
78
- if (response.code === 0) {
79
- return true;
80
- }
81
- params.runtime?.log?.(
82
- `${params.logPrefix ?? "[feishu]"}: comment typing reaction ${params.action} failed ` +
83
- `reply=${params.replyId} file=${params.fileType}:${params.fileToken} ` +
84
- `code=${response.code ?? "unknown"} msg=${response.msg ?? "unknown"} ` +
85
- `log_id=${response.log_id ?? response.error?.log_id ?? "unknown"}`,
86
- );
87
- } catch (error) {
88
- params.runtime?.log?.(
89
- `${params.logPrefix ?? "[feishu]"}: comment typing reaction ${params.action} threw ` +
90
- `reply=${params.replyId} file=${params.fileType}:${params.fileToken} ` +
91
- `error=${formatCommentReactionFailure(error)}`,
92
- );
93
- }
94
- return false;
95
- }
96
-
97
- function formatCommentReactionFailure(error: unknown): string {
98
- return formatFeishuApiError(error, { includeNestedErrorLogId: true });
99
- }
100
-
101
- async function requestCommentTypingReaction(params: {
102
- cfg: ClawdbotConfig;
103
- fileToken: string;
104
- fileType: CommentFileType;
105
- replyId: string;
106
- action: "add" | "delete";
107
- accountId?: string;
108
- runtime?: RuntimeEnv;
109
- }): Promise<boolean> {
110
- const account = resolveFeishuRuntimeAccount({ cfg: params.cfg, accountId: params.accountId });
111
- if (!account.configured || !(account.config.typingIndicator ?? true)) {
112
- return false;
113
- }
114
- const client = createFeishuClient(account) as FeishuCommentReactionClient;
115
- return requestCommentTypingReactionWithClient({
116
- client,
117
- fileToken: params.fileToken,
118
- fileType: params.fileType,
119
- replyId: params.replyId,
120
- action: params.action,
121
- runtime: params.runtime,
122
- logPrefix: `feishu[${account.accountId}]`,
123
- });
124
- }
125
-
126
- async function cleanupCommentTypingReactionByKey(params: {
127
- key: string;
128
- performDelete: () => Promise<boolean>;
129
- }): Promise<boolean> {
130
- const state = ensureCommentTypingReactionState(params.key);
131
- if (state.cleaned) {
132
- return false;
133
- }
134
- if (state.cleanupPromise) {
135
- return await state.cleanupPromise;
136
- }
137
- const cleanupPromise = (async (): Promise<boolean> => {
138
- if (!state.active) {
139
- state.cleaned = true;
140
- return false;
141
- }
142
- const deleted = await params.performDelete();
143
- if (deleted) {
144
- state.cleaned = true;
145
- state.active = false;
146
- }
147
- return deleted;
148
- })();
149
- state.cleanupPromise = cleanupPromise;
150
- try {
151
- return await cleanupPromise;
152
- } finally {
153
- state.cleanupPromise = undefined;
154
- if (state.cleaned) {
155
- state.active = false;
156
- commentTypingReactionState.delete(params.key);
157
- }
158
- }
159
- }
160
-
161
- export async function cleanupAmbientCommentTypingReaction(params: {
162
- client: FeishuCommentReactionClient;
163
- deliveryContext?: {
164
- channel?: string;
165
- to?: string;
166
- threadId?: string | number;
167
- };
168
- runtime?: RuntimeEnv;
169
- }): Promise<boolean> {
170
- const deliveryContext = params.deliveryContext;
171
- if (
172
- deliveryContext?.channel &&
173
- deliveryContext.channel !== "feishu" &&
174
- deliveryContext.channel !== "feishu-comment"
175
- ) {
176
- return false;
177
- }
178
- const target = parseFeishuCommentTarget(deliveryContext?.to);
179
- const replyId =
180
- typeof deliveryContext?.threadId === "string" || typeof deliveryContext?.threadId === "number"
181
- ? String(deliveryContext.threadId).trim()
182
- : "";
183
- if (!target || !replyId) {
184
- return false;
185
- }
186
- const key = buildCommentTypingReactionKey({
187
- fileToken: target.fileToken,
188
- fileType: target.fileType,
189
- replyId,
190
- });
191
- return cleanupCommentTypingReactionByKey({
192
- key,
193
- performDelete: () =>
194
- requestCommentTypingReactionWithClient({
195
- client: params.client,
196
- fileToken: target.fileToken,
197
- fileType: target.fileType,
198
- replyId,
199
- action: "delete",
200
- runtime: params.runtime,
201
- logPrefix: "[feishu]",
202
- }),
203
- });
204
- }
205
-
206
- export function createCommentTypingReactionLifecycle(params: {
207
- cfg: ClawdbotConfig;
208
- fileToken: string;
209
- fileType: CommentFileType;
210
- replyId?: string;
211
- accountId?: string;
212
- runtime?: RuntimeEnv;
213
- }) {
214
- const key = params.replyId?.trim()
215
- ? buildCommentTypingReactionKey({
216
- fileToken: params.fileToken,
217
- fileType: params.fileType,
218
- replyId: params.replyId.trim(),
219
- })
220
- : undefined;
221
- const state = key ? ensureCommentTypingReactionState(key) : undefined;
222
-
223
- return {
224
- start: async (): Promise<void> => {
225
- const replyId = params.replyId?.trim();
226
- if (!state || state.cleaned || state.active || !replyId) {
227
- return;
228
- }
229
- state.active = await requestCommentTypingReaction({
230
- cfg: params.cfg,
231
- fileToken: params.fileToken,
232
- fileType: params.fileType,
233
- replyId,
234
- action: "add",
235
- accountId: params.accountId,
236
- runtime: params.runtime,
237
- });
238
- },
239
- cleanup: async (): Promise<void> => {
240
- const replyId = params.replyId?.trim();
241
- if (!key || !replyId) {
242
- return;
243
- }
244
- await cleanupCommentTypingReactionByKey({
245
- key,
246
- performDelete: () =>
247
- requestCommentTypingReaction({
248
- cfg: params.cfg,
249
- fileToken: params.fileToken,
250
- fileType: params.fileType,
251
- replyId,
252
- action: "delete",
253
- accountId: params.accountId,
254
- runtime: params.runtime,
255
- }),
256
- });
257
- },
258
- };
259
- }