@asabot/core 0.1.0 → 0.2.0

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 (165) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +78 -13
  3. package/asabot.config.example.yaml +47 -29
  4. package/dist/adapters/feishu/adapter.d.ts +19 -0
  5. package/dist/adapters/feishu/adapter.js +621 -0
  6. package/dist/adapters/feishu/api.d.ts +142 -0
  7. package/dist/adapters/feishu/api.js +306 -0
  8. package/dist/adapters/feishu/bot.d.ts +95 -0
  9. package/dist/adapters/feishu/bot.js +539 -0
  10. package/dist/adapters/feishu/cards.d.ts +93 -0
  11. package/dist/adapters/feishu/cards.js +106 -0
  12. package/dist/adapters/feishu/config.d.ts +13 -0
  13. package/dist/adapters/feishu/config.js +36 -0
  14. package/dist/adapters/feishu/events.d.ts +33 -0
  15. package/dist/adapters/feishu/events.js +14 -0
  16. package/dist/adapters/feishu/index.d.ts +8 -0
  17. package/dist/adapters/feishu/index.js +5 -0
  18. package/dist/adapters/feishu/message.d.ts +64 -0
  19. package/dist/adapters/feishu/message.js +197 -0
  20. package/dist/adapters/feishu/transport.d.ts +34 -0
  21. package/dist/adapters/feishu/transport.js +110 -0
  22. package/dist/adapters/index.d.ts +1 -7
  23. package/dist/adapters/index.js +75 -6
  24. package/dist/adapters/loader.d.ts +6 -0
  25. package/dist/adapters/loader.js +73 -0
  26. package/dist/adapters/media-source.d.ts +7 -0
  27. package/dist/adapters/media-source.js +137 -0
  28. package/dist/adapters/onebot11/adapter.d.ts +5 -0
  29. package/dist/adapters/onebot11/adapter.js +23 -11
  30. package/dist/adapters/onebot11/api.d.ts +4 -1
  31. package/dist/adapters/onebot11/api.js +21 -8
  32. package/dist/adapters/onebot11/errors.d.ts +3 -0
  33. package/dist/adapters/onebot11/errors.js +6 -0
  34. package/dist/adapters/virtual/index.js +7 -1
  35. package/dist/adapters/wecom/adapter.d.ts +14 -0
  36. package/dist/adapters/wecom/adapter.js +220 -0
  37. package/dist/adapters/wecom/bot.d.ts +71 -0
  38. package/dist/adapters/wecom/bot.js +312 -0
  39. package/dist/adapters/wecom/cards.d.ts +37 -0
  40. package/dist/adapters/wecom/cards.js +30 -0
  41. package/dist/adapters/wecom/config.d.ts +8 -0
  42. package/dist/adapters/wecom/config.js +10 -0
  43. package/dist/adapters/wecom/events.d.ts +93 -0
  44. package/dist/adapters/wecom/events.js +46 -0
  45. package/dist/adapters/wecom/index.d.ts +7 -0
  46. package/dist/adapters/wecom/index.js +21 -0
  47. package/dist/adapters/wecom/media.d.ts +50 -0
  48. package/dist/adapters/wecom/media.js +149 -0
  49. package/dist/adapters/wecom/message.d.ts +151 -0
  50. package/dist/adapters/wecom/message.js +116 -0
  51. package/dist/adapters/wecom/transport.d.ts +39 -0
  52. package/dist/adapters/wecom/transport.js +116 -0
  53. package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
  54. package/dist/adapters/weixin-clawbot/adapter.js +173 -0
  55. package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
  56. package/dist/adapters/weixin-clawbot/bot.js +254 -0
  57. package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
  58. package/dist/adapters/weixin-clawbot/index.js +19 -0
  59. package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
  60. package/dist/adapters/weixin-clawbot/media.js +196 -0
  61. package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
  62. package/dist/adapters/weixin-clawbot/message.js +79 -0
  63. package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
  64. package/dist/adapters/weixin-clawbot/protocol.js +178 -0
  65. package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
  66. package/dist/adapters/weixin-clawbot/setup.js +121 -0
  67. package/dist/bootstrap.d.ts +5 -0
  68. package/dist/bootstrap.js +5 -20
  69. package/dist/cli.js +9 -3
  70. package/dist/core/adapter.d.ts +69 -3
  71. package/dist/core/adapter.js +11 -1
  72. package/dist/core/app.d.ts +12 -9
  73. package/dist/core/app.js +50 -51
  74. package/dist/core/bot-accounts.d.ts +28 -0
  75. package/dist/core/bot-accounts.js +78 -0
  76. package/dist/core/bot-policies.d.ts +30 -0
  77. package/dist/core/bot-policies.js +112 -0
  78. package/dist/core/bot.d.ts +19 -1
  79. package/dist/core/bot.js +13 -0
  80. package/dist/core/capabilities.d.ts +54 -0
  81. package/dist/core/capabilities.js +25 -0
  82. package/dist/core/config/schema.d.ts +61 -8
  83. package/dist/core/config/schema.js +15 -3
  84. package/dist/core/config/write.js +5 -1
  85. package/dist/core/connections.d.ts +84 -0
  86. package/dist/core/connections.js +326 -0
  87. package/dist/core/delivery.d.ts +53 -0
  88. package/dist/core/delivery.js +115 -0
  89. package/dist/core/dispatch/api.d.ts +3 -1
  90. package/dist/core/dispatch/api.js +12 -5
  91. package/dist/core/dispatch/dispatcher.d.ts +1 -0
  92. package/dist/core/dispatch/dispatcher.js +35 -15
  93. package/dist/core/dispatch/outgoing.d.ts +1 -0
  94. package/dist/core/dispatch/outgoing.js +5 -3
  95. package/dist/core/dispatch/trace.d.ts +2 -0
  96. package/dist/core/dispatch/types.d.ts +6 -0
  97. package/dist/core/dispatch/types.js +1 -2
  98. package/dist/core/errors.d.ts +4 -1
  99. package/dist/core/errors.js +7 -1
  100. package/dist/core/event/session.d.ts +3 -1
  101. package/dist/core/event/session.js +7 -4
  102. package/dist/core/event/types.d.ts +5 -1
  103. package/dist/core/identity.d.ts +18 -0
  104. package/dist/core/identity.js +31 -0
  105. package/dist/core/logger.js +5 -1
  106. package/dist/core/message/types.d.ts +2 -0
  107. package/dist/core/permission.d.ts +2 -1
  108. package/dist/core/permission.js +7 -2
  109. package/dist/core/plugin/context.d.ts +10 -10
  110. package/dist/core/plugin/context.js +20 -18
  111. package/dist/core/plugin/definition.d.ts +5 -0
  112. package/dist/core/plugin/execution.d.ts +3 -0
  113. package/dist/core/plugin/execution.js +3 -0
  114. package/dist/core/plugin/manager.d.ts +18 -4
  115. package/dist/core/plugin/manager.js +137 -45
  116. package/dist/core/plugin/tasks.d.ts +131 -24
  117. package/dist/core/plugin/tasks.js +517 -117
  118. package/dist/core/plugin/types.d.ts +3 -0
  119. package/dist/core/ratelimit.js +6 -1
  120. package/dist/core/storage/index.d.ts +3 -1
  121. package/dist/core/storage/index.js +52 -2
  122. package/dist/core/target.d.ts +24 -6
  123. package/dist/core/target.js +26 -6
  124. package/dist/core/utils/merge.d.ts +3 -0
  125. package/dist/core/utils/merge.js +18 -0
  126. package/dist/core/utils/redact.d.ts +6 -0
  127. package/dist/core/utils/redact.js +76 -0
  128. package/dist/index.d.ts +13 -5
  129. package/dist/index.js +7 -2
  130. package/dist/plugins/admin.js +30 -3
  131. package/dist/plugins/help.js +1 -0
  132. package/dist/plugins/history.d.ts +4 -0
  133. package/dist/plugins/history.js +13 -3
  134. package/dist/plugins/http.js +1 -0
  135. package/dist/plugins/long-message.js +20 -12
  136. package/dist/plugins/status.js +1 -0
  137. package/dist/server/auth.d.ts +5 -1
  138. package/dist/server/auth.js +11 -7
  139. package/dist/server/connection-setups.d.ts +126 -0
  140. package/dist/server/connection-setups.js +188 -0
  141. package/dist/server/groups.d.ts +1 -0
  142. package/dist/server/groups.js +8 -8
  143. package/dist/server/index.d.ts +1 -0
  144. package/dist/server/index.js +229 -29
  145. package/dist/server/schemas.d.ts +6 -2
  146. package/dist/server/settings.d.ts +66 -20
  147. package/dist/server/settings.js +158 -61
  148. package/dist/server/views.d.ts +95 -17
  149. package/dist/server/views.js +48 -13
  150. package/dist/testing/create-test-app.js +2 -2
  151. package/dist/testing/dispatch-fixture.js +2 -1
  152. package/dist/testing/fake-bot.d.ts +2 -1
  153. package/dist/testing/fake-bot.js +4 -1
  154. package/docs/DEPLOY.md +190 -0
  155. package/docs/FEISHU.md +170 -0
  156. package/docs/WECOM.md +107 -0
  157. package/docs/WEIXIN-CLAWBOT.md +56 -0
  158. package/package.json +29 -3
  159. package/web/dist/assets/index-BAbj8e7E.css +2 -0
  160. package/web/dist/assets/index-CMuBy6y5.js +51 -0
  161. package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-MEN1AImu.js} +3 -3
  162. package/web/dist/index.html +2 -2
  163. package/web/dist/plugin-pages/_sdk.js +26 -1
  164. package/web/dist/assets/index-BI5GCpiI.css +0 -2
  165. package/web/dist/assets/index-C-rshHwD.js +0 -51
@@ -0,0 +1,621 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { z } from 'zod';
4
+ import { createSession } from '../../core/event/index.js';
5
+ import { seg } from '../../core/message/index.js';
6
+ import { redactText } from '../../core/utils/redact.js';
7
+ import { FeishuBotImpl } from './bot.js';
8
+ import { cardResponseSchema } from './cards.js';
9
+ import { feishuSchema } from './config.js';
10
+ import { incomingMessage, mentionSchema, threadFields, threadOf } from './message.js';
11
+ import { SDKTransport, } from './transport.js';
12
+ const baseSchema = z.object({ event_id: z.string().min(1), create_time: z.string().optional() });
13
+ const userId = z.object({ open_id: z.string().min(1) });
14
+ const reactionEventSchema = baseSchema
15
+ .extend({
16
+ message_id: z.string().min(1),
17
+ reaction_type: z.object({ emoji_type: z.string().min(1) }),
18
+ action_time: z.coerce.number().int().positive(),
19
+ })
20
+ .and(z.discriminatedUnion('operator_type', [
21
+ z.object({ operator_type: z.literal('user'), user_id: userId }),
22
+ z.object({ operator_type: z.literal('app'), app_id: z.string().min(1) }),
23
+ ]));
24
+ const changeSchema = z.record(z.string(), z.unknown()).optional();
25
+ const chatUpdatedSchema = baseSchema.extend({
26
+ chat_id: z.string().min(1),
27
+ operator_id: userId.partial().optional(),
28
+ before_change: changeSchema,
29
+ after_change: changeSchema,
30
+ });
31
+ const messageReadSchema = baseSchema.extend({
32
+ reader: z.object({ reader_id: userId, read_time: z.coerce.number().int().positive() }),
33
+ message_id_list: z.array(z.string().min(1)).min(1),
34
+ });
35
+ const messageEvent = baseSchema.extend({
36
+ sender: z.object({ sender_id: userId, sender_type: z.string() }),
37
+ message: threadFields.extend({
38
+ chat_id: z.string(),
39
+ chat_type: z.enum(['p2p', 'group']),
40
+ message_type: z.string(),
41
+ content: z.string(),
42
+ create_time: z.string(),
43
+ mentions: z.array(mentionSchema).default([]),
44
+ }),
45
+ });
46
+ const cardEventSchema = baseSchema.extend({
47
+ host: z.literal('im_message'),
48
+ operator: z.object({ open_id: z.string().min(1) }),
49
+ context: z.object({ open_message_id: z.string().min(1), open_chat_id: z.string().min(1) }),
50
+ action: z
51
+ .object({
52
+ tag: z.string(),
53
+ name: z.string().optional(),
54
+ value: z.record(z.string(), z.unknown()).default({}),
55
+ input_value: z.string().optional(),
56
+ option: z.string().optional(),
57
+ options: z.array(z.string()).optional(),
58
+ form_value: z.record(z.string(), z.unknown()).optional(),
59
+ timezone: z.string().optional(),
60
+ })
61
+ .passthrough(),
62
+ });
63
+ class Account {
64
+ config;
65
+ settings;
66
+ host;
67
+ options;
68
+ transport;
69
+ bot;
70
+ closed = false;
71
+ reconnect;
72
+ failures = 0;
73
+ seen = new Map();
74
+ messages = new Map();
75
+ cardResponses = new Set();
76
+ constructor(config, settings, host, options) {
77
+ this.config = config;
78
+ this.settings = settings;
79
+ this.host = host;
80
+ this.options = options;
81
+ }
82
+ async start() {
83
+ if (this.closed)
84
+ return;
85
+ this.host.logger.info({ platform: 'feishu', appId: this.config.appId }, 'Connecting Feishu long connection');
86
+ this.host.connection?.update({ state: 'connecting' });
87
+ const lifecycle = {
88
+ ready: () => {
89
+ if (this.transport !== transport || this.closed)
90
+ return;
91
+ this.failures = 0;
92
+ clearTimeout(this.reconnect);
93
+ this.reconnect = undefined;
94
+ this.status('online');
95
+ this.host.connection?.update({ state: 'online' });
96
+ },
97
+ reconnecting: () => {
98
+ if (this.transport === transport && !this.closed) {
99
+ this.host.logger.info({ platform: 'feishu', appId: this.config.appId, selfId: this.bot?.selfId }, 'Reconnecting Feishu long connection');
100
+ this.status('connecting');
101
+ this.host.connection?.update({ state: 'connecting' });
102
+ }
103
+ },
104
+ error: (error) => {
105
+ if (this.transport !== transport || this.closed)
106
+ return;
107
+ this.status('offline');
108
+ this.recover(error);
109
+ },
110
+ };
111
+ const transport = this.options.createTransport?.(this.config, lifecycle) ??
112
+ new SDKTransport(this.config, this.settings, lifecycle, this.host.logger);
113
+ this.transport = transport;
114
+ try {
115
+ const response = z
116
+ .object({
117
+ code: z.number(),
118
+ msg: z.string().optional(),
119
+ bot: z
120
+ .object({
121
+ open_id: z.string(),
122
+ app_name: z.string().default(''),
123
+ avatar_url: z.string().optional(),
124
+ })
125
+ .optional(),
126
+ })
127
+ .parse(await transport.request('GET', '/bot/v3/info/'));
128
+ if (response.code !== 0 || !response.bot)
129
+ throw new Error(`Feishu bot info ${response.code}: ${response.msg ?? 'missing bot identity'}`);
130
+ if (this.closed || this.transport !== transport)
131
+ return;
132
+ this.bot = new FeishuBotImpl(this.host, transport, { userId: response.bot.open_id, nickname: response.bot.app_name, avatar: response.bot.avatar_url }, this.settings, this.config.appSecret);
133
+ this.host.registerBot(this.bot);
134
+ this.host.setBotInfo(this.bot, { connection: 'long-connection' });
135
+ await transport.start(this.handlers(this.bot));
136
+ }
137
+ catch (error) {
138
+ if (this.closed || this.transport !== transport)
139
+ return;
140
+ this.status('offline');
141
+ this.recover(error);
142
+ }
143
+ }
144
+ recover(error) {
145
+ this.host.logger.warn({
146
+ platform: 'feishu',
147
+ appId: this.config.appId,
148
+ reason: redactText(error instanceof Error ? error.message : String(error), this.config),
149
+ }, 'Feishu connection failed; retrying');
150
+ if (this.reconnect)
151
+ return;
152
+ const delay = Math.min(60_000, 1000 * 2 ** Math.min(6, this.failures++));
153
+ this.host.connection?.update({
154
+ state: 'retrying',
155
+ error: redactText(error instanceof Error ? error.message : String(error), this.config),
156
+ nextRetryAt: Date.now() + delay,
157
+ });
158
+ this.reconnect = setTimeout(() => {
159
+ this.reconnect = undefined;
160
+ this.disconnect();
161
+ void this.start();
162
+ }, delay);
163
+ this.reconnect.unref();
164
+ }
165
+ status(state) {
166
+ const bot = this.bot;
167
+ if (!bot || state === bot.status)
168
+ return;
169
+ const previous = bot.status;
170
+ bot.status = state;
171
+ if (state === 'online' || previous === 'online') {
172
+ const fields = { platform: 'feishu', appId: this.config.appId, selfId: bot.selfId };
173
+ if (state === 'online')
174
+ this.host.logger.info(fields, 'Feishu bot online');
175
+ else if (this.closed)
176
+ this.host.logger.info(fields, 'Feishu bot offline (stopping)');
177
+ else
178
+ this.host.logger.warn(fields, 'Feishu bot offline');
179
+ const common = {
180
+ id: randomUUID(),
181
+ platform: 'feishu',
182
+ selfId: bot.selfId,
183
+ time: Date.now(),
184
+ kind: 'internal',
185
+ raw: undefined,
186
+ bot,
187
+ };
188
+ this.host.emit(state === 'online'
189
+ ? { ...common, name: 'bot.online', status: 'online' }
190
+ : { ...common, name: 'bot.offline', status: 'offline' });
191
+ }
192
+ }
193
+ disconnect() {
194
+ this.status('offline');
195
+ const transport = this.transport;
196
+ this.transport = undefined;
197
+ transport?.close();
198
+ if (this.bot) {
199
+ this.bot.shutdown.abort();
200
+ this.host.unregisterBot(this.bot);
201
+ this.bot = undefined;
202
+ }
203
+ }
204
+ stop() {
205
+ this.closed = true;
206
+ for (const cancel of this.cardResponses)
207
+ cancel();
208
+ clearTimeout(this.reconnect);
209
+ this.disconnect();
210
+ this.seen.clear();
211
+ }
212
+ handlers(bot) {
213
+ const guard = (type, handler) => async (raw) => {
214
+ if (this.closed || this.bot !== bot)
215
+ return {};
216
+ try {
217
+ const event = baseSchema.parse(raw);
218
+ this.host.logger.debug({ platform: 'feishu', selfId: bot.selfId, event: type, eventId: event.event_id }, 'Feishu event received');
219
+ const now = Date.now();
220
+ for (const [key, entry] of this.seen) {
221
+ if (entry.expires > now)
222
+ break;
223
+ this.seen.delete(key);
224
+ }
225
+ const key = `${type}:${event.event_id}`;
226
+ const cached = this.seen.get(key);
227
+ if (cached)
228
+ return await cached.result;
229
+ const result = handler(raw);
230
+ this.seen.set(key, { expires: now + this.settings.dedupTtl, result });
231
+ while (this.seen.size > this.settings.dedupCapacity)
232
+ this.seen.delete(this.seen.keys().next().value);
233
+ try {
234
+ return await result;
235
+ }
236
+ catch (error) {
237
+ this.seen.delete(key);
238
+ throw error;
239
+ }
240
+ }
241
+ catch (error) {
242
+ this.host.logger.warn({
243
+ platform: 'feishu',
244
+ appId: this.config.appId,
245
+ event: type,
246
+ reason: redactText(error instanceof Error ? error.message : String(error), this.config),
247
+ }, 'Feishu event rejected');
248
+ return {};
249
+ }
250
+ };
251
+ const base = (raw) => {
252
+ const event = baseSchema.parse(raw);
253
+ const timestamp = Number(event.create_time);
254
+ return {
255
+ id: event.event_id,
256
+ platform: 'feishu',
257
+ selfId: bot.selfId,
258
+ time: Number.isFinite(timestamp) && timestamp > 0
259
+ ? Math.trunc(timestamp >= 1e15 ? timestamp / 1000 : timestamp)
260
+ : Date.now(),
261
+ raw,
262
+ bot,
263
+ kind: 'notice',
264
+ };
265
+ };
266
+ const handlers = {};
267
+ handlers['im.message.receive_v1'] = guard('im.message.receive_v1', async (raw) => {
268
+ const event = messageEvent.parse(raw);
269
+ const user = event.sender.sender_id.open_id;
270
+ if (this.host.ignoreSelf && (user === bot.selfId || bot.sentMessageIds.has(event.message.message_id)))
271
+ return {};
272
+ const message = event.message;
273
+ const groupId = message.chat_type === 'group' ? message.chat_id : undefined;
274
+ const channel = message.chat_type === 'group'
275
+ ? { messageType: 'group', groupId: message.chat_id }
276
+ : { messageType: 'private' };
277
+ const thread = threadOf(message);
278
+ const sender = await bot.resolveSender(user, groupId);
279
+ if (this.closed || this.bot !== bot)
280
+ return {};
281
+ this.messages.set(message.message_id, { userId: user, ...(groupId ? { groupId } : {}) });
282
+ while (this.messages.size > 1000)
283
+ this.messages.delete(this.messages.keys().next().value);
284
+ const session = createSession({
285
+ ...base(raw),
286
+ ...channel,
287
+ messageId: message.message_id,
288
+ userId: user,
289
+ thread,
290
+ time: z.coerce.number().finite().positive().parse(message.create_time),
291
+ message: incomingMessage(message.message_type, message.content, message.mentions.flatMap((mention) => {
292
+ const id = mention.id?.open_id || (mention.key === '@_all' ? 'all' : undefined);
293
+ return id ? [{ key: mention.key, id }] : [];
294
+ }), message.parent_id, message.message_id),
295
+ sender,
296
+ isSuperuser: this.host.isSuperuser({ platform: 'feishu', selfId: bot.selfId, userId: user }),
297
+ isBotAdmin: this.host.isBotAdmin({ platform: 'feishu', selfId: bot.selfId, userId: user }),
298
+ sentMessageIds: bot.sentMessageIds,
299
+ }, this.host.sessionServices);
300
+ bot.rememberConversation(session.messageId, session.target);
301
+ this.host.logger.info({
302
+ platform: 'feishu',
303
+ selfId: bot.selfId,
304
+ eventId: session.id,
305
+ messageId: session.messageId,
306
+ messageType: session.messageType,
307
+ userId: user,
308
+ ...(groupId ? { groupId } : {}),
309
+ ...(thread ? { threadId: thread.id } : {}),
310
+ isBotAdmin: session.isBotAdmin,
311
+ isSuperuser: session.isSuperuser,
312
+ preview: [...redactText(session.text, this.config)].slice(0, 200).join(''),
313
+ }, 'Feishu message received');
314
+ this.host.emit(session);
315
+ return {};
316
+ });
317
+ for (const [type, join] of [
318
+ ['im.chat.member.user.added_v1', true],
319
+ ['im.chat.member.user.deleted_v1', false],
320
+ ])
321
+ handlers[type] = guard(type, async (raw) => {
322
+ const event = baseSchema
323
+ .extend({
324
+ chat_id: z.string(),
325
+ operator_id: userId.optional(),
326
+ users: z.array(z.object({ user_id: userId })),
327
+ })
328
+ .parse(raw);
329
+ for (const user of event.users) {
330
+ const common = {
331
+ ...base(raw),
332
+ id: `${event.event_id}:${user.user_id.open_id}`,
333
+ groupId: event.chat_id,
334
+ userId: user.user_id.open_id,
335
+ ...(event.operator_id ? { operatorId: event.operator_id.open_id } : {}),
336
+ };
337
+ this.host.emit(join
338
+ ? { ...common, name: 'notice.member.join', joinType: 'unknown' }
339
+ : { ...common, name: 'notice.member.leave', reason: 'unknown' });
340
+ }
341
+ return {};
342
+ });
343
+ for (const [type, name] of [
344
+ ['im.message.reaction.created_v1', 'notice.feishu.reaction.added'],
345
+ ['im.message.reaction.deleted_v1', 'notice.feishu.reaction.removed'],
346
+ ]) {
347
+ handlers[type] = guard(type, async (raw) => {
348
+ const event = reactionEventSchema.parse(raw);
349
+ if (this.host.ignoreSelf && event.operator_type === 'app' && event.app_id === this.config.appId)
350
+ return {};
351
+ const channel = await bot.resolveConversation(event.message_id);
352
+ if (this.closed || this.bot !== bot)
353
+ return {};
354
+ const actor = event.operator_type === 'user'
355
+ ? { operatorType: 'user', userId: event.user_id.open_id }
356
+ : { operatorType: 'app', operatorAppId: event.app_id };
357
+ const notice = {
358
+ ...base(raw),
359
+ name,
360
+ platformType: type,
361
+ ...(channel.groupId === undefined ? {} : { groupId: channel.groupId }),
362
+ ...(channel.thread ? { thread: channel.thread } : {}),
363
+ ...actor,
364
+ time: event.action_time,
365
+ messageId: event.message_id,
366
+ emoji: event.reaction_type.emoji_type,
367
+ };
368
+ this.host.emit(notice);
369
+ return {};
370
+ });
371
+ }
372
+ handlers['im.chat.updated_v1'] = guard('im.chat.updated_v1', async (raw) => {
373
+ const event = chatUpdatedSchema.parse(raw);
374
+ bot.invalidateChat(event.chat_id);
375
+ const notice = {
376
+ ...base(raw),
377
+ name: 'notice.feishu.chat.updated',
378
+ platformType: 'im.chat.updated_v1',
379
+ groupId: event.chat_id,
380
+ ...(event.operator_id?.open_id ? { operatorId: event.operator_id.open_id } : {}),
381
+ ...(event.before_change ? { before: event.before_change } : {}),
382
+ ...(event.after_change ? { after: event.after_change } : {}),
383
+ };
384
+ this.host.emit(notice);
385
+ return {};
386
+ });
387
+ handlers['im.message.message_read_v1'] = guard('im.message.message_read_v1', async (raw) => {
388
+ const event = messageReadSchema.parse(raw);
389
+ const notice = {
390
+ ...base(raw),
391
+ name: 'notice.feishu.message.read',
392
+ platformType: 'im.message.message_read_v1',
393
+ userId: event.reader.reader_id.open_id,
394
+ time: event.reader.read_time,
395
+ messageIds: event.message_id_list,
396
+ };
397
+ this.host.emit(notice);
398
+ return {};
399
+ });
400
+ for (const [type, name] of [
401
+ ['im.chat.member.bot.added_v1', 'notice.feishu.bot.added'],
402
+ ['im.chat.member.bot.deleted_v1', 'notice.feishu.bot.removed'],
403
+ ])
404
+ handlers[type] = guard(type, async (raw) => {
405
+ const event = baseSchema.extend({ chat_id: z.string(), operator_id: userId.optional() }).parse(raw);
406
+ this.host.emit({
407
+ ...base(raw),
408
+ name,
409
+ platformType: type,
410
+ groupId: event.chat_id,
411
+ userId: bot.selfId,
412
+ ...(event.operator_id ? { operatorId: event.operator_id.open_id } : {}),
413
+ });
414
+ return {};
415
+ });
416
+ handlers['im.message.recalled_v1'] = guard('im.message.recalled_v1', async (raw) => {
417
+ const event = baseSchema.extend({ message_id: z.string(), chat_id: z.string() }).parse(raw);
418
+ const source = this.messages.get(event.message_id);
419
+ if (source)
420
+ this.host.emit({
421
+ ...base(raw),
422
+ ...source,
423
+ name: 'notice.message.recall',
424
+ messageId: event.message_id,
425
+ });
426
+ else {
427
+ const channel = await bot.resolveChannel(event.chat_id);
428
+ if (this.closed || this.bot !== bot)
429
+ return {};
430
+ const notice = {
431
+ ...base(raw),
432
+ ...(channel.messageType === 'group' ? { groupId: channel.groupId } : {}),
433
+ name: 'notice.feishu.message.recall',
434
+ platformType: 'im.message.recalled_v1',
435
+ messageId: event.message_id,
436
+ };
437
+ this.host.emit(notice);
438
+ }
439
+ return {};
440
+ });
441
+ handlers['card.action.trigger'] = guard('card.action.trigger', (raw) => this.cardAction(bot, raw));
442
+ return handlers;
443
+ }
444
+ cardAction(bot, raw) {
445
+ const source = cardEventSchema.parse(raw);
446
+ const completion = Promise.withResolvers();
447
+ const deadline = Date.now() + 2000;
448
+ let completed = false;
449
+ const finish = (response) => {
450
+ if (completed)
451
+ return false;
452
+ completed = true;
453
+ clearTimeout(timer);
454
+ this.cardResponses.delete(cancel);
455
+ completion.resolve(response);
456
+ return true;
457
+ };
458
+ const cancel = () => {
459
+ finish({});
460
+ };
461
+ const timer = setTimeout(cancel, 2000);
462
+ timer.unref();
463
+ this.cardResponses.add(cancel);
464
+ const respond = (response) => {
465
+ if (completed || Date.now() >= deadline || this.closed || this.bot !== bot)
466
+ return false;
467
+ return finish(cardResponseSchema.parse(response));
468
+ };
469
+ void (async () => {
470
+ const messageId = source.context.open_message_id;
471
+ const chatId = source.context.open_chat_id;
472
+ const action = source.action;
473
+ const command = action.tag === 'button' && action.form_value === undefined ? bot.commandFrom(action.value) : undefined;
474
+ const known = bot.knownConversation(messageId);
475
+ if (known?.messageType === 'group' && known.groupId !== chatId)
476
+ throw new Error('Feishu card does not belong to the callback chat');
477
+ const channel = known ?? (await bot.resolveChannel(chatId));
478
+ const user = source.operator.open_id;
479
+ const sender = await bot.resolveSender(user, channel.messageType === 'group' ? channel.groupId : undefined);
480
+ if (this.closed || this.bot !== bot)
481
+ return;
482
+ let thread = known?.thread;
483
+ let commandChannelResolved = known !== undefined;
484
+ if (!known) {
485
+ try {
486
+ const message = await bot.getMessageResource(messageId);
487
+ if (message.chat_id !== chatId)
488
+ throw new Error('Feishu message does not belong to the callback chat');
489
+ thread = threadOf(message);
490
+ commandChannelResolved = true;
491
+ }
492
+ catch (error) {
493
+ this.host.logger.debug({ platform: 'feishu', messageId, reason: redactText(String(error), this.config) }, 'Cannot resolve Feishu card thread');
494
+ }
495
+ }
496
+ if (this.closed || this.bot !== bot)
497
+ return;
498
+ const target = {
499
+ platform: 'feishu',
500
+ selfId: bot.selfId,
501
+ type: channel.messageType,
502
+ id: channel.messageType === 'group' ? channel.groupId : user,
503
+ ...(thread ? { thread } : {}),
504
+ };
505
+ if (commandChannelResolved)
506
+ bot.rememberConversation(messageId, target);
507
+ const event = {
508
+ id: source.event_id,
509
+ kind: 'notice',
510
+ name: 'notice.feishu.card.action',
511
+ platform: 'feishu',
512
+ selfId: bot.selfId,
513
+ time: Date.now(),
514
+ raw,
515
+ bot,
516
+ platformType: 'card.action.trigger',
517
+ userId: user,
518
+ sender,
519
+ ...(channel.messageType === 'group' ? { groupId: channel.groupId } : {}),
520
+ chatId,
521
+ messageId,
522
+ ...(thread ? { thread } : {}),
523
+ ...(commandChannelResolved ? { target } : {}),
524
+ action: {
525
+ tag: action.tag,
526
+ value: action.value,
527
+ ...(action.name === undefined ? {} : { name: action.name }),
528
+ ...(action.input_value === undefined ? {} : { inputValue: action.input_value }),
529
+ ...(action.option === undefined ? {} : { option: action.option }),
530
+ ...(action.options === undefined ? {} : { options: action.options }),
531
+ ...(action.form_value === undefined ? {} : { formValue: action.form_value }),
532
+ ...(action.timezone === undefined ? {} : { timezone: action.timezone }),
533
+ raw: action,
534
+ },
535
+ respond,
536
+ };
537
+ this.host.emit(event);
538
+ if (command !== undefined) {
539
+ if (!commandChannelResolved) {
540
+ respond({
541
+ toast: { type: 'warning', content: '无法确认这张卡片所在的会话,请让机器人重新发送卡片' },
542
+ });
543
+ return;
544
+ }
545
+ this.host.emit(createSession({
546
+ id: `${source.event_id}:command`,
547
+ platform: 'feishu',
548
+ selfId: bot.selfId,
549
+ time: event.time,
550
+ raw,
551
+ bot,
552
+ ...channel,
553
+ thread,
554
+ messageId,
555
+ userId: user,
556
+ message: [seg.at(bot.selfId), seg.text(command)],
557
+ sender,
558
+ isSuperuser: this.host.isSuperuser({ platform: 'feishu', selfId: bot.selfId, userId: user }),
559
+ isBotAdmin: this.host.isBotAdmin({ platform: 'feishu', selfId: bot.selfId, userId: user }),
560
+ sentMessageIds: bot.sentMessageIds,
561
+ }, this.host.sessionServices));
562
+ }
563
+ })().catch((error) => {
564
+ this.host.logger.warn({
565
+ platform: 'feishu',
566
+ appId: this.config.appId,
567
+ eventId: source.event_id,
568
+ reason: redactText(error instanceof Error ? error.message : String(error), this.config),
569
+ }, 'Feishu card action failed');
570
+ respond({ toast: { type: 'error', content: '暂时无法处理,请稍后重试' } });
571
+ });
572
+ return completion.promise;
573
+ }
574
+ }
575
+ export class FeishuAdapter {
576
+ platform = 'feishu';
577
+ config;
578
+ host;
579
+ options;
580
+ accounts = new Map();
581
+ running = false;
582
+ constructor(config, host, options = {}) {
583
+ this.config = config;
584
+ this.host = host;
585
+ this.options = options;
586
+ }
587
+ async start() {
588
+ if (this.running)
589
+ return;
590
+ this.running = true;
591
+ await this.apply(this.config);
592
+ }
593
+ async stop() {
594
+ this.running = false;
595
+ for (const account of this.accounts.values())
596
+ account.stop();
597
+ this.accounts.clear();
598
+ }
599
+ async reconfigure(config) {
600
+ const next = feishuSchema.parse(config);
601
+ if (this.running)
602
+ await this.apply(next);
603
+ this.config = next;
604
+ }
605
+ async apply(config) {
606
+ const settingsChanged = !isDeepStrictEqual({ ...this.config, accounts: [] }, { ...config, accounts: [] });
607
+ for (const [id, account] of this.accounts) {
608
+ if (settingsChanged || !config.accounts.some((entry) => isDeepStrictEqual(entry, account.config))) {
609
+ account.stop();
610
+ this.accounts.delete(id);
611
+ }
612
+ }
613
+ await Promise.all(config.accounts
614
+ .filter((entry) => !this.accounts.has(entry.appId))
615
+ .map(async (entry) => {
616
+ const account = new Account(entry, config, this.host, this.options);
617
+ this.accounts.set(entry.appId, account);
618
+ await account.start();
619
+ }));
620
+ }
621
+ }