@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,106 @@
1
+ import { z } from 'zod';
2
+ const record = z.record(z.string(), z.unknown());
3
+ export const cardSchema = z
4
+ .object({
5
+ schema: z.literal('2.0'),
6
+ body: z.object({ elements: z.array(z.object({ tag: z.string() }).passthrough()) }).passthrough(),
7
+ header: record.optional(),
8
+ config: record.optional(),
9
+ })
10
+ .passthrough();
11
+ export const cardResponseSchema = z
12
+ .object({
13
+ toast: z
14
+ .object({
15
+ type: z.enum(['success', 'info', 'warning', 'error']),
16
+ content: z.string(),
17
+ i18n: z.record(z.string(), z.string()).optional(),
18
+ })
19
+ .strict()
20
+ .optional(),
21
+ card: z
22
+ .discriminatedUnion('type', [
23
+ z.object({ type: z.literal('raw'), data: cardSchema }),
24
+ z.object({ type: z.literal('template'), data: record }),
25
+ ])
26
+ .optional(),
27
+ })
28
+ .strict();
29
+ export function isFeishuCardAction(event) {
30
+ return event.platform === 'feishu' && event.name === 'notice.feishu.card.action' && 'respond' in event;
31
+ }
32
+ const text = (content) => ({ tag: 'plain_text', content });
33
+ /** 飞书消息段及 JSON 2.0 卡片构造器。 */
34
+ export const feishu = {
35
+ card(card) {
36
+ return { type: 'feishu:card', data: { card: cardSchema.parse(card) } };
37
+ },
38
+ emoji(emoji) {
39
+ return { type: 'feishu:emoji', data: { emoji_type: emoji } };
40
+ },
41
+ sticker(fileKey) {
42
+ return { type: 'feishu:sticker', data: { file_key: fileKey } };
43
+ },
44
+ shareChat(chatId) {
45
+ return { type: 'feishu:share_chat', data: { chat_id: chatId } };
46
+ },
47
+ shareUser(openId) {
48
+ return { type: 'feishu:share_user', data: { user_id: openId } };
49
+ },
50
+ message(elements, title) {
51
+ return {
52
+ schema: '2.0',
53
+ config: { update_multi: true },
54
+ ...(title ? { header: { title: text(title) } } : {}),
55
+ body: { elements },
56
+ };
57
+ },
58
+ markdown(content) {
59
+ return { tag: 'markdown', content };
60
+ },
61
+ button(label, options = {}) {
62
+ return {
63
+ tag: 'button',
64
+ text: text(label),
65
+ type: options.type ?? 'default',
66
+ ...(options.name ? { name: options.name } : {}),
67
+ behaviors: options.link
68
+ ? [{ type: 'open_url', default_url: options.link }]
69
+ : [{ type: 'callback', value: options.value ?? {} }],
70
+ };
71
+ },
72
+ input(name, options = {}) {
73
+ return {
74
+ tag: 'input',
75
+ name,
76
+ ...(options.placeholder ? { placeholder: text(options.placeholder) } : {}),
77
+ ...(options.required === undefined ? {} : { required: options.required }),
78
+ ...(options.defaultValue === undefined ? {} : { default_value: options.defaultValue }),
79
+ ...(options.multiline ? { input_type: 'multiline_text' } : {}),
80
+ behaviors: [{ type: 'callback', value: options.value ?? {} }],
81
+ };
82
+ },
83
+ select(name, choices, options = {}) {
84
+ return {
85
+ tag: options.multiple ? 'multi_select_static' : 'select_static',
86
+ name,
87
+ options: choices.map((choice) => ({ text: text(choice.label), value: choice.value })),
88
+ ...(options.placeholder ? { placeholder: text(options.placeholder) } : {}),
89
+ ...(options.required === undefined ? {} : { required: options.required }),
90
+ behaviors: [{ type: 'callback', value: options.value ?? {} }],
91
+ };
92
+ },
93
+ form(name, elements) {
94
+ return { tag: 'form', name, elements };
95
+ },
96
+ submit(label, name, value) {
97
+ return {
98
+ tag: 'button',
99
+ text: text(label),
100
+ type: 'primary',
101
+ name,
102
+ form_action_type: 'submit',
103
+ behaviors: [{ type: 'callback', value: value ?? {} }],
104
+ };
105
+ },
106
+ };
@@ -0,0 +1,13 @@
1
+ import { z } from 'zod';
2
+ export declare const feishuSchema: z.ZodObject<{
3
+ accounts: z.ZodDefault<z.ZodArray<z.ZodObject<{
4
+ appId: z.ZodString;
5
+ appSecret: z.ZodString;
6
+ }, z.core.$strict>>>;
7
+ apiTimeout: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
8
+ mediaMaxBytes: z.ZodDefault<z.ZodNumber>;
9
+ dedupCapacity: z.ZodDefault<z.ZodNumber>;
10
+ dedupTtl: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
11
+ }, z.core.$strict>;
12
+ export type FeishuConfig = z.output<typeof feishuSchema>;
13
+ export type FeishuAccountConfig = FeishuConfig['accounts'][number];
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { durationSchema } from '../../core/config/schema.js';
3
+ export const feishuSchema = z
4
+ .object({
5
+ accounts: z
6
+ .array(z
7
+ .object({
8
+ appId: z
9
+ .string()
10
+ .regex(/^cli_[0-9a-fA-F]{16}$/)
11
+ .meta({ title: 'App ID' }),
12
+ appSecret: z.string().min(1).meta({ title: 'App Secret' }),
13
+ })
14
+ .strict())
15
+ .default([])
16
+ .refine((accounts) => new Set(accounts.map((a) => a.appId)).size === accounts.length, 'App ID 不能重复')
17
+ .meta({ title: '企业自建应用' }),
18
+ apiTimeout: durationSchema
19
+ .refine((n) => n > 0 && n <= 2_147_483_647)
20
+ .default(30_000)
21
+ .meta({ title: 'API / 媒体超时' }),
22
+ mediaMaxBytes: z
23
+ .number()
24
+ .int()
25
+ .min(1)
26
+ .max(100 * 1024 * 1024)
27
+ .default(20 * 1024 * 1024)
28
+ .meta({ title: '媒体大小上限(字节)' }),
29
+ dedupCapacity: z.number().int().positive().default(10_000).meta({ title: '事件去重容量' }),
30
+ dedupTtl: durationSchema
31
+ .refine((n) => n > 0)
32
+ .default(600_000)
33
+ .meta({ title: '事件去重有效期' }),
34
+ })
35
+ .strict()
36
+ .meta({ title: '飞书', description: '企业自建应用,通过长连接接收事件与卡片回调。' });
@@ -0,0 +1,33 @@
1
+ import type { MessageThread } from '../../core/bot.ts';
2
+ import type { AnyEvent, PlatformNoticeEvent } from '../../core/event/index.ts';
3
+ interface ReactionEventFields extends PlatformNoticeEvent {
4
+ readonly name: 'notice.feishu.reaction.added' | 'notice.feishu.reaction.removed';
5
+ readonly platformType: 'im.message.reaction.created_v1' | 'im.message.reaction.deleted_v1';
6
+ readonly messageId: string;
7
+ readonly thread?: MessageThread;
8
+ readonly emoji: string;
9
+ }
10
+ export type FeishuReactionEvent = ReactionEventFields & ({
11
+ readonly operatorType: 'user';
12
+ readonly userId: string;
13
+ } | {
14
+ readonly operatorType: 'app';
15
+ readonly operatorAppId: string;
16
+ });
17
+ export declare function isFeishuReaction(event: AnyEvent): event is FeishuReactionEvent;
18
+ export interface FeishuMessageReadEvent extends PlatformNoticeEvent {
19
+ readonly name: 'notice.feishu.message.read';
20
+ readonly platformType: 'im.message.message_read_v1';
21
+ readonly userId: string;
22
+ readonly messageIds: readonly string[];
23
+ }
24
+ export declare function isFeishuMessageRead(event: AnyEvent): event is FeishuMessageReadEvent;
25
+ export interface FeishuChatUpdatedEvent extends PlatformNoticeEvent {
26
+ readonly name: 'notice.feishu.chat.updated';
27
+ readonly platformType: 'im.chat.updated_v1';
28
+ readonly groupId: string;
29
+ readonly before?: Record<string, unknown>;
30
+ readonly after?: Record<string, unknown>;
31
+ }
32
+ export declare function isFeishuChatUpdated(event: AnyEvent): event is FeishuChatUpdatedEvent;
33
+ export {};
@@ -0,0 +1,14 @@
1
+ export function isFeishuReaction(event) {
2
+ return (event.platform === 'feishu' &&
3
+ (event.name === 'notice.feishu.reaction.added' || event.name === 'notice.feishu.reaction.removed') &&
4
+ 'operatorType' in event);
5
+ }
6
+ export function isFeishuMessageRead(event) {
7
+ return event.platform === 'feishu' && event.name === 'notice.feishu.message.read' && 'messageIds' in event;
8
+ }
9
+ export function isFeishuChatUpdated(event) {
10
+ return (event.platform === 'feishu' &&
11
+ event.name === 'notice.feishu.chat.updated' &&
12
+ 'groupId' in event &&
13
+ typeof event.groupId === 'string');
14
+ }
@@ -0,0 +1,8 @@
1
+ export { FeishuAdapter, type FeishuAdapterOptions } from './adapter.ts';
2
+ export type { FeishuAddMembersResult, FeishuApi, FeishuChatInfo, FeishuListMessagesOptions, FeishuListReactionsOptions, FeishuMergeForwardResult, FeishuMessageContainer, FeishuMessagePage, FeishuPage, FeishuPageOptions, FeishuPin, FeishuReaction, FeishuReadUser, } from './api.ts';
3
+ export { type FeishuBot, isFeishu } from './bot.ts';
4
+ export { type FeishuCard, type FeishuCardActionEvent, type FeishuCardResponse, type FeishuElement, feishu, isFeishuCardAction, } from './cards.ts';
5
+ export { type FeishuAccountConfig, type FeishuConfig, feishuSchema } from './config.ts';
6
+ export { type FeishuChatUpdatedEvent, type FeishuMessageReadEvent, type FeishuReactionEvent, isFeishuChatUpdated, isFeishuMessageRead, isFeishuReaction, } from './events.ts';
7
+ export type { FeishuMessageInfo } from './message.ts';
8
+ export type { FeishuEventHandlers, FeishuLifecycle, FeishuRequest, FeishuTransport, FeishuUploadKind, } from './transport.ts';
@@ -0,0 +1,5 @@
1
+ export { FeishuAdapter } from './adapter.js';
2
+ export { isFeishu } from './bot.js';
3
+ export { feishu, isFeishuCardAction, } from './cards.js';
4
+ export { feishuSchema } from './config.js';
5
+ export { isFeishuChatUpdated, isFeishuMessageRead, isFeishuReaction, } from './events.js';
@@ -0,0 +1,64 @@
1
+ import { z } from 'zod';
2
+ import type { MessageInfo, MessageThread } from '../../core/bot.ts';
3
+ import type { Message } from '../../core/message/index.ts';
4
+ export declare const threadFields: z.ZodObject<{
5
+ message_id: z.ZodString;
6
+ thread_id: z.ZodOptional<z.ZodString>;
7
+ root_id: z.ZodOptional<z.ZodString>;
8
+ parent_id: z.ZodOptional<z.ZodString>;
9
+ }, z.core.$strip>;
10
+ export declare function threadOf(message: z.output<typeof threadFields>): MessageThread | undefined;
11
+ export declare const messageResource: z.ZodIntersection<z.ZodObject<{
12
+ message_id: z.ZodString;
13
+ thread_id: z.ZodOptional<z.ZodString>;
14
+ root_id: z.ZodOptional<z.ZodString>;
15
+ parent_id: z.ZodOptional<z.ZodString>;
16
+ msg_type: z.ZodString;
17
+ chat_id: z.ZodString;
18
+ create_time: z.ZodCoercedNumber<unknown>;
19
+ sender: z.ZodObject<{
20
+ id: z.ZodString;
21
+ sender_type: z.ZodString;
22
+ }, z.core.$strip>;
23
+ mentions: z.ZodDefault<z.ZodArray<z.ZodObject<{
24
+ key: z.ZodString;
25
+ id: z.ZodString;
26
+ name: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strip>>>;
28
+ upper_message_id: z.ZodOptional<z.ZodString>;
29
+ updated: z.ZodOptional<z.ZodBoolean>;
30
+ }, z.core.$strip>, z.ZodDiscriminatedUnion<[z.ZodObject<{
31
+ deleted: z.ZodLiteral<true>;
32
+ body: z.ZodOptional<z.ZodObject<{
33
+ content: z.ZodOptional<z.ZodString>;
34
+ }, z.core.$strip>>;
35
+ }, z.core.$strip>, z.ZodObject<{
36
+ deleted: z.ZodOptional<z.ZodLiteral<false>>;
37
+ body: z.ZodObject<{
38
+ content: z.ZodString;
39
+ }, z.core.$strip>;
40
+ }, z.core.$strip>], "deleted">>;
41
+ export interface FeishuMessageInfo extends MessageInfo {
42
+ chatId: string;
43
+ senderType: string;
44
+ deleted: boolean;
45
+ updated: boolean;
46
+ parentMessageId?: string;
47
+ }
48
+ export declare function decodeMessageResource(source: z.output<typeof messageResource>, messageType: MessageInfo['messageType']): FeishuMessageInfo;
49
+ export declare const mentionSchema: z.ZodObject<{
50
+ key: z.ZodString;
51
+ id: z.ZodOptional<z.ZodObject<{
52
+ open_id: z.ZodOptional<z.ZodString>;
53
+ }, z.core.$strip>>;
54
+ name: z.ZodOptional<z.ZodString>;
55
+ }, z.core.$strip>;
56
+ export interface FeishuMention {
57
+ key: string;
58
+ id: string;
59
+ name?: string;
60
+ }
61
+ /** Decode Feishu's JSON message body, preserving rich-text order and references. */
62
+ export declare function incomingMessage(type: string, json: string, mentions?: FeishuMention[], parentId?: string, messageId?: string): Message;
63
+ /** One deadline covers media headers and body. Opaque platform keys return undefined. */
64
+ export declare function readMedia(source: string, limit: number, timeout: number, shutdown: AbortSignal): Promise<Buffer | undefined>;
@@ -0,0 +1,197 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { z } from 'zod';
4
+ import { seg } from '../../core/message/index.js';
5
+ const object = z.record(z.string(), z.unknown());
6
+ const textStyles = new Set(['bold', 'italic', 'underline', 'strike', 'code']);
7
+ export const threadFields = z.object({
8
+ message_id: z.string().min(1),
9
+ thread_id: z.string().optional(),
10
+ root_id: z.string().optional(),
11
+ parent_id: z.string().optional(),
12
+ });
13
+ export function threadOf(message) {
14
+ if (!message.thread_id)
15
+ return undefined;
16
+ return {
17
+ id: message.thread_id,
18
+ rootMessageId: message.root_id || message.parent_id || message.message_id,
19
+ };
20
+ }
21
+ const timeSchema = z.coerce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
22
+ const storedMessageContent = z.discriminatedUnion('deleted', [
23
+ z.object({ deleted: z.literal(true), body: z.object({ content: z.string().optional() }).optional() }),
24
+ z.object({ deleted: z.literal(false).optional(), body: z.object({ content: z.string() }) }),
25
+ ]);
26
+ export const messageResource = threadFields
27
+ .extend({
28
+ msg_type: z.string(),
29
+ chat_id: z.string().min(1),
30
+ create_time: timeSchema,
31
+ sender: z.object({ id: z.string(), sender_type: z.string() }),
32
+ mentions: z
33
+ .array(z.object({ key: z.string().min(1), id: z.string(), name: z.string().optional() }))
34
+ .default([]),
35
+ upper_message_id: z.string().optional(),
36
+ updated: z.boolean().optional(),
37
+ })
38
+ .and(storedMessageContent);
39
+ export function decodeMessageResource(source, messageType) {
40
+ const thread = threadOf(source);
41
+ return {
42
+ messageId: source.message_id,
43
+ messageType,
44
+ userId: source.sender.id,
45
+ ...(messageType === 'group' ? { groupId: source.chat_id } : {}),
46
+ ...(thread === undefined ? {} : { thread }),
47
+ ...(source.parent_id ? { parentMessageId: source.parent_id } : {}),
48
+ time: source.create_time,
49
+ message: source.deleted
50
+ ? []
51
+ : incomingMessage(source.msg_type, source.body.content, source.mentions, source.parent_id, source.message_id),
52
+ sender: { userId: source.sender.id, nickname: source.sender.id },
53
+ chatId: source.chat_id,
54
+ senderType: source.sender.sender_type,
55
+ deleted: source.deleted === true,
56
+ updated: source.updated === true,
57
+ };
58
+ }
59
+ export const mentionSchema = z.object({
60
+ key: z.string().min(1),
61
+ id: z.object({ open_id: z.string().optional() }).optional(),
62
+ name: z.string().optional(),
63
+ });
64
+ function textWithMentions(text, mentions) {
65
+ const result = [];
66
+ let remaining = text;
67
+ const keys = new Map(mentions.map((mention) => [mention.key, mention.id]));
68
+ while (remaining) {
69
+ const next = [...keys]
70
+ .map(([key, id]) => ({ key, id, index: remaining.indexOf(key) }))
71
+ .filter((m) => m.key && m.index >= 0)
72
+ .sort((a, b) => a.index - b.index || b.key.length - a.key.length)[0];
73
+ if (!next) {
74
+ result.push(seg.text(remaining));
75
+ break;
76
+ }
77
+ if (next.index)
78
+ result.push(seg.text(remaining.slice(0, next.index)));
79
+ result.push(seg.at(next.id));
80
+ remaining = remaining.slice(next.index + next.key.length);
81
+ }
82
+ return result;
83
+ }
84
+ /** Decode Feishu's JSON message body, preserving rich-text order and references. */
85
+ export function incomingMessage(type, json, mentions = [], parentId, messageId) {
86
+ const result = parentId ? [seg.reply(parentId)] : [];
87
+ // The Feishu API can use a display string rather than JSON for forwarded messages.
88
+ if (type === 'merge_forward' && messageId)
89
+ return [...result, seg.forward(messageId)];
90
+ const content = object.parse(JSON.parse(json));
91
+ if (type === 'text')
92
+ result.push(...textWithMentions(z.string().parse(content.text), mentions));
93
+ else if (type === 'image')
94
+ result.push(seg.image(z.string().parse(content.image_key)));
95
+ else if (type === 'audio')
96
+ result.push(seg.audio(z.string().parse(content.file_key)));
97
+ else if (type === 'media')
98
+ result.push(seg.video(z.string().parse(content.file_key)));
99
+ else if (type === 'file')
100
+ result.push(seg.file(z.string().parse(content.file_key), { name: z.string().optional().parse(content.file_name) }));
101
+ else if (type === 'post') {
102
+ const post = Array.isArray(content.content)
103
+ ? content
104
+ : object.parse(content.zh_cn ?? content.en_us ?? Object.values(content)[0]);
105
+ if (typeof post.title === 'string' && post.title)
106
+ result.push(seg.text(`${post.title}\n`));
107
+ const lines = z.array(z.array(object)).parse(post.content);
108
+ lines.forEach((line, index) => {
109
+ if (index)
110
+ result.push(seg.text('\n'));
111
+ for (const item of line) {
112
+ if (item.tag === 'text') {
113
+ const style = z
114
+ .array(z.string())
115
+ .optional()
116
+ .parse(item.style)
117
+ ?.filter((s) => textStyles.has(s));
118
+ result.push(seg.text(z.string().parse(item.text), style));
119
+ }
120
+ else if (item.tag === 'at') {
121
+ const id = z.string().parse(item.user_id);
122
+ result.push(seg.at(mentions.find((mention) => mention.key === id)?.id ?? id));
123
+ }
124
+ else if (item.tag === 'a')
125
+ result.push(seg.text(`${z.string().parse(item.text)} (${z.string().parse(item.href)})`));
126
+ else if (item.tag === 'img')
127
+ result.push(seg.image(z.string().parse(item.image_key)));
128
+ else if (item.tag === 'media')
129
+ result.push(seg.video(z.string().parse(item.file_key)));
130
+ else if (item.tag === 'emotion')
131
+ result.push({ type: 'feishu:emoji', data: { emoji_type: z.string().parse(item.emoji_type) } });
132
+ else if (item.tag === 'md')
133
+ result.push(seg.markdown(z.string().parse(item.text)));
134
+ else
135
+ result.push({ type: 'feishu:post.element', data: item });
136
+ }
137
+ });
138
+ }
139
+ else
140
+ result.push({ type: `feishu:${type}`, data: content });
141
+ return result;
142
+ }
143
+ /** One deadline covers media headers and body. Opaque platform keys return undefined. */
144
+ export async function readMedia(source, limit, timeout, shutdown) {
145
+ const signal = AbortSignal.any([shutdown, AbortSignal.timeout(timeout)]);
146
+ signal.throwIfAborted();
147
+ if (source.startsWith('base64://')) {
148
+ if ((source.length - 9) * 0.75 > limit + 2)
149
+ throw new Error('Media exceeds mediaMaxBytes');
150
+ const value = source.slice(9);
151
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
152
+ throw new Error('Invalid base64 media');
153
+ const bytes = Buffer.from(value, 'base64');
154
+ if (bytes.length > limit)
155
+ throw new Error('Media exceeds mediaMaxBytes');
156
+ return bytes;
157
+ }
158
+ if (source.startsWith('file://')) {
159
+ const path = fileURLToPath(source);
160
+ if ((await stat(path)).size > limit)
161
+ throw new Error('Media exceeds mediaMaxBytes');
162
+ const bytes = await readFile(path, { signal });
163
+ if (bytes.length > limit)
164
+ throw new Error('Media exceeds mediaMaxBytes');
165
+ return bytes;
166
+ }
167
+ if (!/^https?:\/\//.test(source))
168
+ return undefined;
169
+ const response = await fetch(source, { signal });
170
+ if (!response.ok) {
171
+ await response.body?.cancel();
172
+ throw new Error(`Media HTTP ${response.status}`);
173
+ }
174
+ const reader = response.body?.getReader();
175
+ if (!reader)
176
+ throw new Error('Media response has no body');
177
+ const chunks = [];
178
+ let length = 0;
179
+ try {
180
+ if (Number(response.headers.get('content-length')) > limit)
181
+ throw new Error('Media exceeds mediaMaxBytes');
182
+ while (true) {
183
+ const part = await reader.read();
184
+ if (part.done)
185
+ break;
186
+ length += part.value.length;
187
+ if (length > limit)
188
+ throw new Error('Media exceeds mediaMaxBytes');
189
+ chunks.push(Buffer.from(part.value));
190
+ }
191
+ return Buffer.concat(chunks);
192
+ }
193
+ finally {
194
+ await reader.cancel();
195
+ reader.releaseLock();
196
+ }
197
+ }
@@ -0,0 +1,34 @@
1
+ import type { Logger } from 'pino';
2
+ import type { FeishuAccountConfig, FeishuConfig } from './config.ts';
3
+ export type FeishuEventHandlers = Record<string, (event: unknown) => Promise<unknown>>;
4
+ export interface FeishuLifecycle {
5
+ ready(): void;
6
+ reconnecting(): void;
7
+ error(error: unknown): void;
8
+ }
9
+ export interface FeishuRequest {
10
+ data?: Record<string, unknown>;
11
+ params?: Record<string, string | number>;
12
+ }
13
+ export type FeishuUploadKind = 'image' | 'file' | 'audio' | 'video';
14
+ /** Injectable SDK boundary; protocol payloads are validated by the adapter. */
15
+ export interface FeishuTransport {
16
+ request(method: string, path: string, input?: FeishuRequest): Promise<unknown>;
17
+ upload(type: FeishuUploadKind, content: Buffer, name: string): Promise<unknown>;
18
+ download(messageId: string, key: string, type: 'image' | 'file'): Promise<Buffer>;
19
+ start(handlers: FeishuEventHandlers): Promise<void>;
20
+ close(): void;
21
+ }
22
+ export declare class SDKTransport implements FeishuTransport {
23
+ private readonly client;
24
+ private readonly ws;
25
+ private readonly config;
26
+ private readonly sdkLogger;
27
+ private readonly controller;
28
+ constructor(account: FeishuAccountConfig, config: FeishuConfig, lifecycle: FeishuLifecycle, logger: Logger);
29
+ request(method: string, path: string, input?: FeishuRequest): Promise<unknown>;
30
+ upload(type: FeishuUploadKind, content: Buffer, name: string): Promise<unknown>;
31
+ download(messageId: string, key: string, type: 'image' | 'file'): Promise<Buffer>;
32
+ start(handlers: FeishuEventHandlers): Promise<void>;
33
+ close(): void;
34
+ }
@@ -0,0 +1,110 @@
1
+ import { Client, Domain, defaultHttpInstance, EventDispatcher, LoggerLevel, WSClient, } from '@larksuiteoapi/node-sdk';
2
+ import { redactText } from '../../core/utils/redact.js';
3
+ export class SDKTransport {
4
+ client;
5
+ ws;
6
+ config;
7
+ sdkLogger;
8
+ controller = new AbortController();
9
+ constructor(account, config, lifecycle, logger) {
10
+ this.config = config;
11
+ const report = (...items) => logger.warn({
12
+ platform: 'feishu',
13
+ appId: account.appId,
14
+ reason: redactText(items
15
+ .map((item) => item instanceof Error ? item.message : typeof item === 'string' ? item : '[SDK detail]')
16
+ .join(' '), account),
17
+ }, 'Feishu SDK');
18
+ const sdkLogger = { error: report, warn: report, info() { }, debug() { }, trace() { } };
19
+ this.sdkLogger = sdkLogger;
20
+ const signal = this.controller.signal;
21
+ function request(options) {
22
+ return defaultHttpInstance.request({
23
+ ...options,
24
+ timeout: config.apiTimeout,
25
+ signal,
26
+ maxContentLength: config.mediaMaxBytes,
27
+ maxBodyLength: config.mediaMaxBytes + 65536,
28
+ });
29
+ }
30
+ const http = {
31
+ request,
32
+ get: (url, options) => request({ ...options, url, method: 'GET' }),
33
+ delete: (url, options) => request({ ...options, url, method: 'DELETE' }),
34
+ head: (url, options) => request({ ...options, url, method: 'HEAD' }),
35
+ options: (url, options) => request({ ...options, url, method: 'OPTIONS' }),
36
+ post: (url, data, options) => request({ ...options, url, data, method: 'POST' }),
37
+ put: (url, data, options) => request({ ...options, url, data, method: 'PUT' }),
38
+ patch: (url, data, options) => request({ ...options, url, data, method: 'PATCH' }),
39
+ };
40
+ const base = {
41
+ ...account,
42
+ domain: Domain.Feishu,
43
+ logger: sdkLogger,
44
+ loggerLevel: LoggerLevel.warn,
45
+ httpInstance: http,
46
+ };
47
+ this.client = new Client(base);
48
+ this.ws = new WSClient({
49
+ ...base,
50
+ handshakeTimeoutMs: config.apiTimeout,
51
+ onReady: lifecycle.ready,
52
+ onReconnected: lifecycle.ready,
53
+ onReconnecting: lifecycle.reconnecting,
54
+ onError: lifecycle.error,
55
+ });
56
+ }
57
+ request(method, path, input = {}) {
58
+ return this.client.request({ method, url: `https://open.feishu.cn/open-apis${path}`, ...input });
59
+ }
60
+ upload(type, content, name) {
61
+ return type === 'image'
62
+ ? this.client.im.image.create({ data: { image_type: 'message', image: content } })
63
+ : this.client.im.file.create({
64
+ data: {
65
+ file_type: type === 'audio' ? 'opus' : type === 'video' ? 'mp4' : 'stream',
66
+ file_name: name,
67
+ file: content,
68
+ },
69
+ });
70
+ }
71
+ async download(messageId, key, type) {
72
+ const result = await this.client.im.messageResource.get({
73
+ path: { message_id: messageId, file_key: key },
74
+ params: { type },
75
+ });
76
+ const stream = result.getReadableStream();
77
+ const signal = AbortSignal.any([this.controller.signal, AbortSignal.timeout(this.config.apiTimeout)]);
78
+ const abort = () => stream.destroy(new Error('Resource download aborted'));
79
+ signal.addEventListener('abort', abort, { once: true });
80
+ const chunks = [];
81
+ let size = 0;
82
+ try {
83
+ signal.throwIfAborted();
84
+ for await (const chunk of stream) {
85
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
86
+ size += bytes.length;
87
+ if (size > this.config.mediaMaxBytes)
88
+ throw new Error('Resource exceeds mediaMaxBytes');
89
+ chunks.push(bytes);
90
+ }
91
+ return Buffer.concat(chunks);
92
+ }
93
+ finally {
94
+ signal.removeEventListener('abort', abort);
95
+ stream.destroy();
96
+ }
97
+ }
98
+ async start(handlers) {
99
+ await this.ws.start({
100
+ eventDispatcher: new EventDispatcher({
101
+ logger: this.sdkLogger,
102
+ loggerLevel: LoggerLevel.error,
103
+ }).register(handlers),
104
+ });
105
+ }
106
+ close() {
107
+ this.controller.abort();
108
+ this.ws.close({ force: true });
109
+ }
110
+ }
@@ -1,7 +1 @@
1
- import type { z } from 'zod';
2
- import type { Adapter, AdapterHost } from '../core/adapter.ts';
3
- export interface AdapterDefinition {
4
- configSchema: z.ZodType;
5
- create(config: unknown, host: AdapterHost): Adapter;
6
- }
7
- export declare const adapters: Record<string, AdapterDefinition>;
1
+ export declare const adapters: import("../core/adapter.ts").AdapterDefinition[];