@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
@@ -1,8 +1,77 @@
1
- import { OneBotAdapter } from './onebot11/adapter.js';
1
+ import { z } from 'zod';
2
+ import { defineAdapter } from '../core/adapter.js';
3
+ import { FeishuAdapter } from './feishu/adapter.js';
4
+ import { feishuCapabilities } from './feishu/bot.js';
5
+ import { feishuSchema } from './feishu/config.js';
6
+ import { OneBotAdapter, onebotCapabilities } from './onebot11/adapter.js';
2
7
  import { onebot11Schema } from './onebot11/config.js';
3
- function defineAdapter(configSchema, create) {
4
- return { configSchema, create: (config, host) => create(config, host) };
8
+ import { wecomDefinition } from './wecom/index.js';
9
+ import { weixinClawbot } from './weixin-clawbot/index.js';
10
+ const feishuConnection = feishuSchema.omit({ accounts: true }).extend({
11
+ appId: z
12
+ .string()
13
+ .regex(/^cli_[0-9a-fA-F]{16}$/)
14
+ .meta({ title: 'App ID' }),
15
+ appSecret: z.string().min(1).meta({ title: 'App Secret', writeOnly: true }),
16
+ });
17
+ const onebotConnection = onebot11Schema
18
+ .omit({ connections: true, reverse: true })
19
+ .extend({
20
+ type: z.enum(['forward', 'reverse']).default('forward').meta({ title: '连接方式' }),
21
+ url: z
22
+ .url()
23
+ .refine((value) => /^wss?:/.test(value), '请使用 ws:// 或 wss:// 地址')
24
+ .optional()
25
+ .meta({ title: '正向 WebSocket 地址' }),
26
+ accessToken: z.string().default('').meta({ title: '访问令牌', writeOnly: true }),
27
+ })
28
+ .superRefine((value, ctx) => {
29
+ if (value.type === 'forward' && !value.url)
30
+ ctx.addIssue({ code: 'custom', path: ['url'], message: '正向连接需要 WebSocket 地址' });
31
+ });
32
+ function reconfigurable(adapter, convert) {
33
+ return {
34
+ platform: adapter.platform,
35
+ start: () => adapter.start(),
36
+ stop: () => adapter.stop(),
37
+ reconfigure: (config) => adapter.reconfigure(convert(config)),
38
+ };
5
39
  }
6
- export const adapters = {
7
- onebot11: defineAdapter(onebot11Schema, (config, host) => new OneBotAdapter(config, host, { ignoreSelf: host.ignoreSelf })),
8
- };
40
+ function feishuConfig({ appId, appSecret, ...options }) {
41
+ return { ...options, accounts: [{ appId, appSecret }] };
42
+ }
43
+ function onebotConfig({ type, url, accessToken, ...options }) {
44
+ return {
45
+ ...options,
46
+ connections: type === 'forward' ? [{ type: 'forward', url: url, accessToken }] : [],
47
+ reverse: { enabled: type === 'reverse', accessToken },
48
+ };
49
+ }
50
+ export const adapters = [
51
+ defineAdapter({
52
+ id: 'feishu',
53
+ platform: 'feishu',
54
+ name: '飞书',
55
+ version: '0.1.0',
56
+ description: '企业自建应用,通过长连接接收消息、事件和卡片回调。',
57
+ connectionTypes: ['long-connection'],
58
+ capabilities: feishuCapabilities,
59
+ configSchema: feishuConnection,
60
+ botBinding: (config) => ({ key: config.appId }),
61
+ create: (config, host) => reconfigurable(new FeishuAdapter(feishuConfig(config), host), (value) => feishuConfig(feishuConnection.parse(value))),
62
+ }),
63
+ defineAdapter({
64
+ id: 'onebot11',
65
+ platform: 'onebot11',
66
+ name: 'OneBot 11',
67
+ version: '0.1.0',
68
+ description: '连接 NapCat 等 OneBot 11 实现,支持正向连接与反向监听。',
69
+ connectionTypes: ['forward', 'reverse'],
70
+ capabilities: onebotCapabilities,
71
+ configSchema: onebotConnection,
72
+ botBinding: (config) => config.type === 'reverse' ? { key: 'reverse', multiple: true } : { key: `forward:${config.url}` },
73
+ create: (config, host) => reconfigurable(new OneBotAdapter(onebotConfig(config), host, { ignoreSelf: host.ignoreSelf }), (value) => onebotConfig(onebotConnection.parse(value))),
74
+ }),
75
+ wecomDefinition,
76
+ weixinClawbot,
77
+ ];
@@ -0,0 +1,6 @@
1
+ import type { AdapterDefinition } from '../core/adapter.ts';
2
+ /** 从用户项目解析包,保留 Node 的 import 条件导出语义。 */
3
+ export declare function loadAdapterModules(modules: string[], cwd?: string): Promise<{
4
+ definition: AdapterDefinition;
5
+ source: string;
6
+ }[]>;
@@ -0,0 +1,73 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { randomUUID } from 'node:crypto';
10
+ import { registerHooks } from 'node:module';
11
+ import { resolve } from 'node:path';
12
+ import { pathToFileURL } from 'node:url';
13
+ import { z } from 'zod';
14
+ import { capabilitySchema } from '../core/capabilities.js';
15
+ import { ConfigError } from '../core/errors.js';
16
+ const accountId = z.custom((value) => typeof value === 'function');
17
+ const qrSetup = z.object({
18
+ kind: z.literal('qr'),
19
+ start: z.custom((value) => typeof value === 'function'),
20
+ });
21
+ const definitionSchema = z
22
+ .object({
23
+ id: z.string().regex(/^[a-z0-9][a-z0-9_-]*$/),
24
+ platform: z.string().regex(/^[^:\s]+$/),
25
+ name: z.string().min(1),
26
+ version: z.string().min(1),
27
+ description: z.string(),
28
+ connectionTypes: z.array(z.string()),
29
+ capabilities: capabilitySchema,
30
+ configSchema: z.custom((value) => typeof value === 'object' &&
31
+ value !== null &&
32
+ 'safeParse' in value &&
33
+ typeof value.safeParse === 'function'),
34
+ create: z.custom((value) => typeof value === 'function'),
35
+ botBinding: z
36
+ .custom((value) => typeof value === 'function')
37
+ .optional(),
38
+ })
39
+ .and(z.union([
40
+ z.object({ setup: qrSetup, accountId }),
41
+ z.object({ setup: z.undefined().optional(), accountId: accountId.optional() }),
42
+ ]));
43
+ /** 从用户项目解析包,保留 Node 的 import 条件导出语义。 */
44
+ export async function loadAdapterModules(modules, cwd = process.cwd()) {
45
+ const loaded = [];
46
+ for (const specifier of modules) {
47
+ if (!/^(?:@[a-z0-9_.-]+\/)?[a-z0-9][a-z0-9_.-]*(?:\/[a-z0-9_./-]+)?$/i.test(specifier))
48
+ throw new ConfigError(`Invalid adapter package "${specifier}"`);
49
+ const entry = `asabot-adapter:${randomUUID()}`;
50
+ const hooks = registerHooks({
51
+ resolve(name, context, nextResolve) {
52
+ return name === entry
53
+ ? nextResolve(specifier, {
54
+ ...context,
55
+ parentURL: pathToFileURL(resolve(cwd, 'package.json')).href,
56
+ })
57
+ : nextResolve(name, context);
58
+ },
59
+ });
60
+ try {
61
+ const module = await import(__rewriteRelativeImportExtension(entry));
62
+ const definition = definitionSchema.parse(module.default);
63
+ loaded.push({ definition, source: specifier });
64
+ }
65
+ catch (error) {
66
+ throw new ConfigError(`Cannot load adapter package "${specifier}"`, { cause: error });
67
+ }
68
+ finally {
69
+ hooks.deregister();
70
+ }
71
+ }
72
+ return loaded;
73
+ }
@@ -0,0 +1,7 @@
1
+ import { Agent } from 'undici';
2
+ export declare function limitedBytes(response: Response, limit: number): Promise<Buffer>;
3
+ export declare function download(url: URL, signal: AbortSignal, limit: number, dispatcher?: Agent): Promise<Buffer>;
4
+ export declare function remoteMedia(url: URL, signal: AbortSignal, limit: number): Promise<Buffer>;
5
+ export declare function localMedia(url: URL, signal: AbortSignal, limit: number): Promise<Buffer>;
6
+ export declare function mediaName(value: string | undefined): string | undefined;
7
+ export declare function base64Media(encoded: string, limit: number): Buffer;
@@ -0,0 +1,137 @@
1
+ import { lookup } from 'node:dns/promises';
2
+ import { constants } from 'node:fs';
3
+ import { open } from 'node:fs/promises';
4
+ import { BlockList, isIP } from 'node:net';
5
+ import { basename, win32 } from 'node:path';
6
+ import { Agent } from 'undici';
7
+ const privateV4 = new BlockList();
8
+ for (const [address, prefix] of [
9
+ ['0.0.0.0', 8],
10
+ ['10.0.0.0', 8],
11
+ ['100.64.0.0', 10],
12
+ ['127.0.0.0', 8],
13
+ ['169.254.0.0', 16],
14
+ ['172.16.0.0', 12],
15
+ ['192.0.0.0', 24],
16
+ ['192.0.2.0', 24],
17
+ ['192.168.0.0', 16],
18
+ ['198.18.0.0', 15],
19
+ ['198.51.100.0', 24],
20
+ ['203.0.113.0', 24],
21
+ ['224.0.0.0', 3],
22
+ ])
23
+ privateV4.addSubnet(address, prefix);
24
+ const globalV6 = new BlockList();
25
+ globalV6.addSubnet('2000::', 3, 'ipv6');
26
+ const reservedV6 = new BlockList();
27
+ reservedV6.addSubnet('2001::', 23, 'ipv6');
28
+ reservedV6.addSubnet('2001:db8::', 32, 'ipv6');
29
+ reservedV6.addSubnet('2002::', 16, 'ipv6');
30
+ reservedV6.addSubnet('3fff::', 20, 'ipv6');
31
+ function publicAddress(address) {
32
+ return isIP(address) === 4
33
+ ? !privateV4.check(address)
34
+ : globalV6.check(address, 'ipv6') && !reservedV6.check(address, 'ipv6');
35
+ }
36
+ export async function limitedBytes(response, limit) {
37
+ const reader = response.body?.getReader();
38
+ if (!reader)
39
+ return Buffer.alloc(0);
40
+ const chunks = [];
41
+ let size = 0;
42
+ let done = false;
43
+ try {
44
+ if (Number(response.headers.get('content-length')) > limit)
45
+ throw new Error('响应超过大小限制');
46
+ for (;;) {
47
+ const part = await reader.read();
48
+ if (part.done) {
49
+ done = true;
50
+ return Buffer.concat(chunks, size);
51
+ }
52
+ size += part.value.length;
53
+ if (size > limit)
54
+ throw new Error('响应超过大小限制');
55
+ chunks.push(part.value);
56
+ }
57
+ }
58
+ finally {
59
+ if (!done)
60
+ await reader.cancel();
61
+ reader.releaseLock();
62
+ }
63
+ }
64
+ export async function download(url, signal, limit, dispatcher) {
65
+ const init = { signal, redirect: 'error', dispatcher };
66
+ const response = await fetch(url, init);
67
+ if (!response.ok) {
68
+ await response.body?.cancel();
69
+ throw new Error(`媒体 HTTP ${response.status}`);
70
+ }
71
+ return limitedBytes(response, limit);
72
+ }
73
+ export async function remoteMedia(url, signal, limit) {
74
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password)
75
+ throw new Error('媒体来源不受信任');
76
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
77
+ if (isIP(hostname) && !publicAddress(hostname))
78
+ throw new Error('不能访问非公网媒体地址');
79
+ const dispatcher = new Agent({
80
+ connect: {
81
+ lookup(host, options, callback) {
82
+ void lookup(host, { all: true, family: options.family, hints: options.hints }).then((addresses) => {
83
+ const first = addresses[0];
84
+ if (!first || addresses.some(({ address }) => !publicAddress(address))) {
85
+ callback(new Error('不能访问非公网媒体地址'), '');
86
+ }
87
+ else if (options.all)
88
+ callback(null, addresses);
89
+ else
90
+ callback(null, first.address, first.family);
91
+ }, (error) => callback(error, ''));
92
+ },
93
+ },
94
+ });
95
+ try {
96
+ return await download(url, signal, limit, dispatcher);
97
+ }
98
+ finally {
99
+ await dispatcher.destroy();
100
+ }
101
+ }
102
+ export async function localMedia(url, signal, limit) {
103
+ if (url.host)
104
+ throw new Error('不支持网络文件路径');
105
+ const file = await open(url, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
106
+ try {
107
+ const stat = await file.stat();
108
+ if (!stat.isFile() || stat.size > limit)
109
+ throw new Error('媒体文件不可用或超过大小限制');
110
+ signal.throwIfAborted();
111
+ const chunks = [];
112
+ let length = 0;
113
+ for await (const chunk of file.createReadStream({ end: limit, signal, autoClose: false })) {
114
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
115
+ length += bytes.length;
116
+ if (length > limit)
117
+ throw new Error('媒体超过大小限制');
118
+ chunks.push(bytes);
119
+ }
120
+ return Buffer.concat(chunks, length);
121
+ }
122
+ finally {
123
+ await file.close();
124
+ }
125
+ }
126
+ export function mediaName(value) {
127
+ const name = value && win32.basename(basename(value)).trim().slice(0, 255);
128
+ return name && name !== '.' && name !== '..' ? name : undefined;
129
+ }
130
+ export function base64Media(encoded, limit) {
131
+ if (encoded.length > Math.ceil(limit / 3) * 4)
132
+ throw new Error('媒体超过大小限制');
133
+ const bytes = Buffer.from(encoded, 'base64');
134
+ if (bytes.toString('base64').replace(/=+$/, '') !== encoded.replace(/=+$/, ''))
135
+ throw new Error('媒体 base64 格式错误');
136
+ return bytes;
137
+ }
@@ -48,6 +48,11 @@ type SessionTransport = {
48
48
  remoteAddress: string;
49
49
  accessToken: string;
50
50
  };
51
+ export declare const onebotCapabilities: {
52
+ segments: string[];
53
+ textStyles: never[];
54
+ actions: string[];
55
+ };
51
56
  declare class OneBotBotImpl implements OneBotBot {
52
57
  readonly platform = "onebot11";
53
58
  readonly capabilities: {
@@ -6,7 +6,7 @@ import { createSession } from '../../core/event/index.js';
6
6
  import { LruSet } from '../../core/utils/lru.js';
7
7
  import { constantTimeEqual } from '../../core/utils/security.js';
8
8
  import { OneBotApiImpl } from './api.js';
9
- import { ApiError } from './errors.js';
9
+ import { ApiError, ReceiptLostError } from './errors.js';
10
10
  import { incomingMessage } from './message.js';
11
11
  import { SendQueue } from './send-queue.js';
12
12
  const sendActions = new Set([
@@ -53,13 +53,14 @@ function eventTime(raw) {
53
53
  function platformId(value) {
54
54
  return String(value);
55
55
  }
56
+ export const onebotCapabilities = {
57
+ segments: ['text', 'at', 'face', 'image', 'audio', 'video', 'file', 'reply', 'forward', 'onebot11:*'],
58
+ textStyles: [],
59
+ actions: [...botActions, 'getAvatarUrl'],
60
+ };
56
61
  class OneBotBotImpl {
57
62
  platform = 'onebot11';
58
- capabilities = {
59
- segments: ['text', 'at', 'face', 'image', 'audio', 'video', 'file', 'reply', 'forward', 'onebot11:*'],
60
- textStyles: [],
61
- actions: [...botActions, 'getAvatarUrl'],
62
- };
63
+ capabilities = onebotCapabilities;
63
64
  onebot;
64
65
  sentMessageIds = new LruSet(1_000);
65
66
  currentStatus = 'connecting';
@@ -71,7 +72,7 @@ class OneBotBotImpl {
71
72
  this.connection = connection;
72
73
  this.selfId = selfId;
73
74
  this.sendQueue = new SendQueue(options.sendQueue, options.logger, selfId);
74
- this.onebot = new OneBotApiImpl((action, params) => this.call(action, params), {
75
+ this.onebot = new OneBotApiImpl(this, (action, params) => this.call(action, params), {
75
76
  assertOnline: () => this.connection.assertOnline(this),
76
77
  prepareOutgoing: (target, message) => this.connection.prepareOutgoing(this, target, message),
77
78
  executeOutgoing: (action, params, execute) => this.connection.interceptOutgoing(this, action, params, execute),
@@ -459,7 +460,8 @@ class OneBotSession {
459
460
  ...(frame.sender?.card === undefined ? {} : { card: frame.sender.card }),
460
461
  ...(role === undefined ? {} : { role }),
461
462
  },
462
- isSuperuser: this.host.isSuperuser(userId),
463
+ isSuperuser: this.host.isSuperuser({ platform: 'onebot11', selfId: bot.selfId, userId }),
464
+ isBotAdmin: this.host.isBotAdmin({ platform: 'onebot11', selfId: bot.selfId, userId }),
463
465
  sentMessageIds: bot.sentMessageIds,
464
466
  }, this.host.sessionServices);
465
467
  this.logMessage(session);
@@ -716,7 +718,7 @@ class OneBotSession {
716
718
  this.heartbeatPeriod = undefined;
717
719
  this.lastHeartbeatAt = undefined;
718
720
  this.pendingEvents.length = 0;
719
- this.rejectPending(new NotConnectedError());
721
+ this.rejectPending();
720
722
  if (this.currentBot?.usesConnection(this)) {
721
723
  this.currentBot.sendQueue.cancel();
722
724
  if (this.currentBot.status === 'online') {
@@ -729,11 +731,11 @@ class OneBotSession {
729
731
  this.onClose();
730
732
  }
731
733
  }
732
- rejectPending(error) {
734
+ rejectPending() {
733
735
  for (const [echo, pending] of this.pending) {
734
736
  clearTimeout(pending.timer);
735
737
  this.pending.delete(echo);
736
- pending.reject(error);
738
+ pending.reject(sendActions.has(pending.action) ? new ReceiptLostError() : new NotConnectedError());
737
739
  }
738
740
  }
739
741
  emitBotOnline(bot) {
@@ -776,6 +778,7 @@ class OneBotSession {
776
778
  }
777
779
  }
778
780
  class OneBotConnection {
781
+ host;
779
782
  session;
780
783
  config;
781
784
  options;
@@ -784,6 +787,7 @@ class OneBotConnection {
784
787
  backoff;
785
788
  stopped = true;
786
789
  constructor(config, host, options, adapter) {
790
+ this.host = host;
787
791
  this.config = config;
788
792
  this.options = options;
789
793
  this.backoff = options.reconnect.minDelay;
@@ -817,6 +821,7 @@ class OneBotConnection {
817
821
  connect() {
818
822
  if (this.stopped)
819
823
  return;
824
+ this.host.connection?.update({ state: 'connecting' });
820
825
  this.options.logger.debug({ url: sanitizedUrl(this.config.url) }, 'Connecting OneBot forward WebSocket');
821
826
  let socket;
822
827
  try {
@@ -826,11 +831,16 @@ class OneBotConnection {
826
831
  }
827
832
  catch (error) {
828
833
  this.options.logger.warn({ reason: errorReason(error, this.config.accessToken), url: sanitizedUrl(this.config.url) }, 'Failed to create OneBot WebSocket');
834
+ this.host.connection?.update({ state: 'retrying', error: errorReason(error, this.config.accessToken) });
829
835
  this.scheduleReconnect();
830
836
  return;
831
837
  }
832
838
  socket.on('error', (error) => {
833
839
  if (!this.stopped) {
840
+ this.host.connection?.update({
841
+ state: 'retrying',
842
+ error: errorReason(error, this.config.accessToken),
843
+ });
834
844
  this.options.logger.warn({
835
845
  reason: errorReason(error, this.config.accessToken),
836
846
  ...(error.code === undefined ? {} : { code: error.code }),
@@ -846,6 +856,7 @@ class OneBotConnection {
846
856
  const base = Math.min(this.options.reconnect.maxDelay, Math.max(this.options.reconnect.minDelay, this.backoff));
847
857
  const delay = Math.min(this.options.reconnect.maxDelay, Math.max(this.options.reconnect.minDelay, Math.round(base * (0.8 + Math.random() * 0.4))));
848
858
  this.backoff = Math.min(this.options.reconnect.maxDelay, Math.max(this.options.reconnect.minDelay, base * 2));
859
+ this.host.connection?.update({ state: 'retrying', nextRetryAt: Date.now() + delay });
849
860
  this.reconnectTimer = setTimeout(() => {
850
861
  this.reconnectTimer = undefined;
851
862
  this.connect();
@@ -1008,6 +1019,7 @@ export class OneBotAdapter {
1008
1019
  this.stopped = false;
1009
1020
  if (this.reverseEnabled) {
1010
1021
  this.registerReverse();
1022
+ this.host.connection?.update({ state: 'waiting' });
1011
1023
  if (this.reverseToken === '')
1012
1024
  this.options.logger.warn('反向 WS 未设置 token');
1013
1025
  }
@@ -1,5 +1,6 @@
1
1
  import type { PreparedOutgoing } from '../../core/adapter.ts';
2
2
  import type { ForwardMessage, GroupInfo, GroupMemberInfo, MessageTarget, SendResult, UserInfo } from '../../core/bot.ts';
3
+ import type { BotIdentity } from '../../core/identity.ts';
3
4
  import type { Message, Sendable } from '../../core/message/index.ts';
4
5
  import type { OneBotApi, OneBotForwardNode, OneBotMessageInfo, OneBotVersionInfo } from './bot.ts';
5
6
  import type { OneBotMessage } from './types.ts';
@@ -23,9 +24,10 @@ export interface OneBotApiHooks {
23
24
  export declare function normalizeOutbound(content: Sendable): Promise<OneBotMessage>;
24
25
  /** 基于 OneBot 请求函数实现的平台专属 API。 */
25
26
  export declare class OneBotApiImpl implements OneBotApi {
27
+ private readonly bot;
26
28
  private readonly request;
27
29
  private readonly hooks;
28
- constructor(request: Request, hooks?: OneBotApiHooks);
30
+ constructor(bot: BotIdentity, request: Request, hooks?: OneBotApiHooks);
29
31
  sendPrivateMsg(userId: string, content: Sendable): Promise<SendResult>;
30
32
  sendGroupMsg(groupId: string, content: Sendable): Promise<SendResult>;
31
33
  deleteMsg(messageId: string): Promise<void>;
@@ -49,6 +51,7 @@ export declare class OneBotApiImpl implements OneBotApi {
49
51
  sendGroupForwardMsg(groupId: string, messages: OneBotForwardNode[]): Promise<SendResult>;
50
52
  sendPrivateForwardMsg(userId: string, messages: OneBotForwardNode[]): Promise<SendResult>;
51
53
  private sendOutgoing;
54
+ private deliverOutgoing;
52
55
  getForwardMsg(id: string): Promise<ForwardMessage[]>;
53
56
  private prepare;
54
57
  private prepareNodes;
@@ -1,7 +1,9 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { fileURLToPath } from 'node:url';
3
+ import { DeliveryAttempt } from '../../core/delivery.js';
3
4
  import { normalizeSendable, seg } from '../../core/message/index.js';
4
5
  import { idNumber, outgoingSegment } from './conversion.js';
6
+ import { ApiError } from './errors.js';
5
7
  import { incomingMessage } from './message.js';
6
8
  async function normalizeMediaFile(value) {
7
9
  // seg.image() and friends turn local paths into file:// URLs. Only those are read and inlined, because
@@ -127,9 +129,11 @@ function memberInfo(value) {
127
129
  }
128
130
  /** 基于 OneBot 请求函数实现的平台专属 API。 */
129
131
  export class OneBotApiImpl {
132
+ bot;
130
133
  request;
131
134
  hooks;
132
- constructor(request, hooks = {}) {
135
+ constructor(bot, request, hooks = {}) {
136
+ this.bot = bot;
133
137
  this.request = request;
134
138
  this.hooks = hooks;
135
139
  }
@@ -241,7 +245,11 @@ export class OneBotApiImpl {
241
245
  async sendPrivateForwardMsg(userId, messages) {
242
246
  return this.sendOutgoing('send_private_forward_msg', { type: 'private', id: userId }, messages, true);
243
247
  }
244
- async sendOutgoing(action, destination, content, forward) {
248
+ sendOutgoing(action, destination, content, forward) {
249
+ const delivery = new DeliveryAttempt(this.bot, destination);
250
+ return delivery.run(() => this.deliverOutgoing(delivery, action, destination, content, forward));
251
+ }
252
+ async deliverOutgoing(delivery, action, destination, content, forward) {
245
253
  const idKey = destination.type === 'group' ? 'group_id' : 'user_id';
246
254
  const messageKey = forward ? 'messages' : 'message';
247
255
  const params = { [idKey]: idNumber(destination.id), [messageKey]: content };
@@ -269,12 +277,17 @@ export class OneBotApiImpl {
269
277
  wireContent = await normalizeOutbound(prepared);
270
278
  eventMessage = prepared;
271
279
  }
272
- const response = await this.request(actualAction, {
273
- ...actualParams,
274
- [idKey]: idNumber(id),
275
- [messageKey]: wireContent,
276
- });
277
- const result = messageResult(response);
280
+ const wireParams = { ...actualParams, [idKey]: idNumber(id), [messageKey]: wireContent };
281
+ const { response, result } = await new DeliveryAttempt(this.bot, target).request(async () => {
282
+ const response = await this.request(actualAction, wireParams);
283
+ return { response, result: messageResult(response) };
284
+ }, (error) => error instanceof ApiError
285
+ ? {
286
+ code: error.retcode === 1 ? 'DELIVERY_UNCONFIRMED' : 'DELIVERY_REJECTED',
287
+ platformCode: error.retcode,
288
+ }
289
+ : undefined);
290
+ delivery.confirm(result);
278
291
  this.hooks.onMessageSent?.({
279
292
  messageType: destination.type,
280
293
  ...(destination.type === 'group' ? { groupId: id } : { userId: id }),
@@ -5,3 +5,6 @@ export declare class ApiError extends Error {
5
5
  readonly wording: string;
6
6
  constructor(action: string, retcode: number, wording?: string);
7
7
  }
8
+ export declare class ReceiptLostError extends Error {
9
+ constructor();
10
+ }
@@ -11,3 +11,9 @@ export class ApiError extends Error {
11
11
  this.wording = wording;
12
12
  }
13
13
  }
14
+ export class ReceiptLostError extends Error {
15
+ constructor() {
16
+ super('OneBot disconnected while waiting for a send receipt');
17
+ this.name = 'ReceiptLostError';
18
+ }
19
+ }
@@ -244,7 +244,13 @@ export class VirtualAdapter {
244
244
  userId: options.user,
245
245
  message: typeof content === 'string' ? [seg.text(content)] : content,
246
246
  sender: { userId: options.user, nickname: options.nickname ?? options.user, role: options.role },
247
- isSuperuser: options.superuser ?? this.host.isSuperuser(options.user),
247
+ isSuperuser: options.superuser ??
248
+ this.host.isSuperuser({ platform: this.platform, selfId: this.bot.selfId, userId: options.user }),
249
+ isBotAdmin: this.host.isBotAdmin({
250
+ platform: this.platform,
251
+ selfId: this.bot.selfId,
252
+ userId: options.user,
253
+ }),
248
254
  sentMessageIds: this.bot.sentMessageIds,
249
255
  ...(options.group == null
250
256
  ? { messageType: 'private' }
@@ -0,0 +1,14 @@
1
+ import type { Adapter, AdapterHost } from '../../core/adapter.ts';
2
+ import { type WecomConfig } from './config.ts';
3
+ import { type WecomTransport } from './transport.ts';
4
+ export interface WecomAdapterOptions {
5
+ createTransport?: (config: WecomConfig) => WecomTransport;
6
+ }
7
+ export declare class WecomAdapter implements Adapter {
8
+ #private;
9
+ readonly platform = "wecom";
10
+ constructor(config: WecomConfig, host: AdapterHost, options?: WecomAdapterOptions);
11
+ start(): Promise<void>;
12
+ stop(): Promise<void>;
13
+ reconfigure(config: unknown): Promise<void>;
14
+ }