@asabot/core 0.1.0 → 0.2.1

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 (170) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +93 -14
  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 +9 -2
  106. package/dist/core/message/segment.js +3 -13
  107. package/dist/core/message/types.d.ts +2 -0
  108. package/dist/core/permission.d.ts +2 -1
  109. package/dist/core/permission.js +7 -2
  110. package/dist/core/plugin/context.d.ts +17 -11
  111. package/dist/core/plugin/context.js +48 -21
  112. package/dist/core/plugin/definition.d.ts +7 -0
  113. package/dist/core/plugin/execution.d.ts +3 -0
  114. package/dist/core/plugin/execution.js +3 -0
  115. package/dist/core/plugin/icon.d.ts +2 -0
  116. package/dist/core/plugin/icon.js +14 -0
  117. package/dist/core/plugin/manager.d.ts +26 -7
  118. package/dist/core/plugin/manager.js +179 -56
  119. package/dist/core/plugin/packages.d.ts +4 -0
  120. package/dist/core/plugin/packages.js +39 -9
  121. package/dist/core/plugin/tasks.d.ts +131 -24
  122. package/dist/core/plugin/tasks.js +517 -117
  123. package/dist/core/plugin/types.d.ts +14 -0
  124. package/dist/core/ratelimit.js +6 -1
  125. package/dist/core/storage/index.d.ts +3 -1
  126. package/dist/core/storage/index.js +52 -2
  127. package/dist/core/target.d.ts +24 -6
  128. package/dist/core/target.js +26 -6
  129. package/dist/core/utils/merge.d.ts +3 -0
  130. package/dist/core/utils/merge.js +18 -0
  131. package/dist/core/utils/redact.d.ts +6 -0
  132. package/dist/core/utils/redact.js +76 -0
  133. package/dist/index.d.ts +14 -6
  134. package/dist/index.js +7 -2
  135. package/dist/plugins/admin.js +30 -3
  136. package/dist/plugins/help.js +1 -0
  137. package/dist/plugins/history.d.ts +4 -0
  138. package/dist/plugins/history.js +13 -3
  139. package/dist/plugins/http.js +1 -0
  140. package/dist/plugins/long-message.js +20 -12
  141. package/dist/plugins/status.js +1 -0
  142. package/dist/server/auth.d.ts +5 -1
  143. package/dist/server/auth.js +11 -7
  144. package/dist/server/connection-setups.d.ts +126 -0
  145. package/dist/server/connection-setups.js +188 -0
  146. package/dist/server/groups.d.ts +1 -0
  147. package/dist/server/groups.js +8 -8
  148. package/dist/server/index.d.ts +1 -0
  149. package/dist/server/index.js +230 -29
  150. package/dist/server/schemas.d.ts +6 -2
  151. package/dist/server/settings.d.ts +66 -20
  152. package/dist/server/settings.js +158 -61
  153. package/dist/server/views.d.ts +97 -17
  154. package/dist/server/views.js +48 -13
  155. package/dist/testing/create-test-app.js +2 -2
  156. package/dist/testing/dispatch-fixture.js +2 -1
  157. package/dist/testing/fake-bot.d.ts +2 -1
  158. package/dist/testing/fake-bot.js +4 -1
  159. package/docs/DEPLOY.md +211 -0
  160. package/docs/FEISHU.md +170 -0
  161. package/docs/WECOM.md +107 -0
  162. package/docs/WEIXIN-CLAWBOT.md +56 -0
  163. package/package.json +29 -3
  164. package/web/dist/assets/index-ogXTSYEt.css +2 -0
  165. package/web/dist/assets/index-r9XycpMd.js +51 -0
  166. package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
  167. package/web/dist/index.html +2 -2
  168. package/web/dist/plugin-pages/_sdk.js +26 -1
  169. package/web/dist/assets/index-BI5GCpiI.css +0 -2
  170. package/web/dist/assets/index-C-rshHwD.js +0 -51
@@ -0,0 +1,121 @@
1
+ import { setTimeout as sleep } from 'node:timers/promises';
2
+ import { z } from 'zod';
3
+ import { QrSetupError } from '../../core/errors.js';
4
+ import { accountSchema, apiOrigin, IlinkError, ilink, ilinkOrigin } from './protocol.js';
5
+ const qrSchema = z.object({
6
+ qrcode: z.string().min(1).max(4096),
7
+ qrcode_img_content: z.string().min(1).max(2048),
8
+ });
9
+ const statusSchema = z.object({
10
+ status: z.enum([
11
+ 'wait',
12
+ 'scaned',
13
+ 'scaned_but_redirect',
14
+ 'need_verifycode',
15
+ 'confirmed_but_need_verifycode',
16
+ 'verify_code_blocked',
17
+ 'expired',
18
+ 'binded_redirect',
19
+ 'confirmed',
20
+ ]),
21
+ redirect_host: z.string().optional(),
22
+ bot_token: z.string().optional(),
23
+ ilink_bot_id: z.string().optional(),
24
+ ilink_user_id: z.string().max(512).optional(),
25
+ baseurl: z.string().optional(),
26
+ });
27
+ function throwSetupError(error) {
28
+ if (error instanceof IlinkError)
29
+ throw new QrSetupError(error.retryable ? `${error.message}。请检查 AsaBot 的网络后重试。` : error.message);
30
+ if (error instanceof DOMException && error.name === 'TimeoutError')
31
+ throw new QrSetupError('连接微信超时,请检查 AsaBot 的网络后重试。');
32
+ throw error;
33
+ }
34
+ async function pollStatus(url, signal) {
35
+ for (let attempt = 0;; attempt++) {
36
+ try {
37
+ return await ilink(url, '查询二维码', statusSchema, signal, { timeout: 35_000 });
38
+ }
39
+ catch (error) {
40
+ signal.throwIfAborted();
41
+ if (error instanceof DOMException && error.name === 'TimeoutError')
42
+ return { status: 'wait' };
43
+ if (!(error instanceof IlinkError) || !error.retryable || attempt >= 3)
44
+ throwSetupError(error);
45
+ await sleep(1000 * 2 ** attempt, undefined, { signal, ref: false });
46
+ }
47
+ }
48
+ }
49
+ function setupOrigin(value, label) {
50
+ try {
51
+ return ilinkOrigin(value);
52
+ }
53
+ catch {
54
+ throw new QrSetupError(`微信返回的${label}地址不受支持。`);
55
+ }
56
+ }
57
+ export const weixinSetup = {
58
+ kind: 'qr',
59
+ async start(signal) {
60
+ const { qrcode, qrcode_img_content } = await ilink(new URL('/ilink/bot/get_bot_qrcode?bot_type=3', apiOrigin), '生成二维码', qrSchema, signal, { data: { local_token_list: [] } }).catch(throwSetupError);
61
+ let origin = apiOrigin;
62
+ let redirected = 0;
63
+ let pendingCode;
64
+ return {
65
+ content: qrcode_img_content,
66
+ async poll(verifyCode) {
67
+ if (verifyCode !== undefined)
68
+ pendingCode = verifyCode;
69
+ const url = new URL('/ilink/bot/get_qrcode_status', origin);
70
+ url.searchParams.set('qrcode', qrcode);
71
+ if (pendingCode !== undefined)
72
+ url.searchParams.set('verify_code', pendingCode);
73
+ const result = await pollStatus(url, signal);
74
+ switch (result.status) {
75
+ case 'wait':
76
+ return { status: 'waiting' };
77
+ case 'scaned':
78
+ pendingCode = undefined;
79
+ return { status: 'scanned' };
80
+ case 'scaned_but_redirect':
81
+ if (result.redirect_host) {
82
+ if (++redirected > 5)
83
+ throw new QrSetupError('微信扫码区域反复切换,请刷新二维码后重试。');
84
+ origin = setupOrigin(`https://${result.redirect_host}`, '扫码区域');
85
+ }
86
+ return { status: 'scanned' };
87
+ case 'need_verifycode':
88
+ case 'confirmed_but_need_verifycode': {
89
+ const retry = pendingCode !== undefined;
90
+ pendingCode = undefined;
91
+ return { status: 'verification', retry };
92
+ }
93
+ case 'verify_code_blocked':
94
+ case 'expired':
95
+ return { status: 'expired' };
96
+ case 'binded_redirect':
97
+ return { status: 'already-bound' };
98
+ case 'confirmed': {
99
+ const account = accountSchema.safeParse({
100
+ selfId: result.ilink_bot_id,
101
+ token: result.bot_token,
102
+ apiBaseUrl: result.baseurl ? setupOrigin(result.baseurl, '授权服务') : origin,
103
+ });
104
+ if (!account.success) {
105
+ const labels = { selfId: '机器人 ID', token: '登录令牌', apiBaseUrl: '授权服务地址' };
106
+ const fields = Object.entries(labels)
107
+ .filter(([field]) => account.error.issues.some((issue) => issue.path[0] === field))
108
+ .map(([, label]) => label);
109
+ throw new QrSetupError(`微信已确认扫码,但未返回有效的${fields.join('、')}。`);
110
+ }
111
+ return {
112
+ status: 'authorized',
113
+ config: account.data,
114
+ adminUserId: result.ilink_user_id?.trim() || undefined,
115
+ };
116
+ }
117
+ }
118
+ },
119
+ };
120
+ },
121
+ };
@@ -1,4 +1,5 @@
1
1
  import type { Logger } from 'pino';
2
+ import type { AdapterDefinition } from './core/adapter.ts';
2
3
  import { App } from './core/app.ts';
3
4
  import type { Config } from './core/config/schema.ts';
4
5
  import type { PackageOptions } from './core/plugin/packages.ts';
@@ -7,6 +8,10 @@ export interface CreateAppOptions {
7
8
  configPath?: string;
8
9
  packages?: PackageOptions;
9
10
  setupCode?: string;
11
+ adapters?: {
12
+ definition: AdapterDefinition;
13
+ source: string;
14
+ }[];
10
15
  }
11
16
  /** 根据已校验配置创建应用,注册内置插件和适配器;配置无效或适配器未知时抛出 ConfigError。 */
12
17
  export declare function createApp(config: Config, options?: CreateAppOptions): App;
package/dist/bootstrap.js CHANGED
@@ -1,7 +1,5 @@
1
1
  import { adapters } from './adapters/index.js';
2
2
  import { App } from './core/app.js';
3
- import { formatIssuePath } from './core/config/load.js';
4
- import { ConfigError } from './core/errors.js';
5
3
  import { createLogger } from './core/logger.js';
6
4
  import { createAdminPlugin } from './plugins/admin.js';
7
5
  import { createHelpPlugin } from './plugins/help.js';
@@ -23,24 +21,11 @@ export function createApp(config, options = {}) {
23
21
  app.plugins.register(http);
24
22
  app.plugins.register(history);
25
23
  app.plugins.register(longMessage);
26
- app.configureAdapters((name, value) => {
27
- const definition = adapters[name];
28
- if (!definition)
29
- throw new ConfigError(`Unknown adapter "${name}"`);
30
- return definition.create(value, app);
31
- });
32
- for (const [name, value] of Object.entries(config.adapters)) {
33
- const definition = Object.hasOwn(adapters, name) ? adapters[name] : undefined;
34
- if (definition === undefined) {
35
- throw new ConfigError(`Unknown adapter "${name}". Available adapters: ${Object.keys(adapters).join(', ')}`);
36
- }
37
- const result = definition.configSchema.safeParse(value);
38
- if (!result.success) {
39
- const issues = result.error.issues.map((issue) => `${formatIssuePath(['adapters', name, ...issue.path])}: ${issue.message}`);
40
- throw new ConfigError(`Configuration validation failed:\n${issues.join('\n')}`);
41
- }
42
- app.useConfiguredAdapter(definition.create(result.data, app), result.data);
43
- }
24
+ for (const definition of adapters)
25
+ app.connections.register(definition, 'builtin');
26
+ for (const { definition, source } of options.adapters ?? [])
27
+ app.connections.register(definition, source);
28
+ app.connections.validate(config.connections);
44
29
  app.configureServer(() => new HttpServer(app));
45
30
  return app;
46
31
  }
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { dirname, resolve } from 'node:path';
6
6
  import { pathToFileURL } from 'node:url';
7
7
  import { parseArgs } from 'node:util';
8
8
  import { stringify } from 'yaml';
9
+ import { loadAdapterModules } from './adapters/loader.js';
9
10
  import { createApp } from './bootstrap.js';
10
11
  import { loadConfig } from './core/config/load.js';
11
12
  import { ConfigError } from './core/errors.js';
@@ -79,12 +80,13 @@ export async function loadMainConfig(configPath) {
79
80
  await mkdir(dirname(resolve(configPath)), { recursive: true });
80
81
  await writeFile(configPath, `# 完整配置示例见 asabot.config.example.yaml\n${stringify({
81
82
  superusers: [],
82
- adapters: {},
83
+ adapterModules: [],
84
+ connections: [],
83
85
  server: { host, port, panelPassword: '' },
84
86
  })}`, { encoding: 'utf8', flag: 'wx' });
85
87
  }
86
88
  const config = await loadConfig(configPath);
87
- const setup = missing || (!config.server.panelPassword && Object.keys(config.adapters).length === 0);
89
+ const setup = missing || (!config.server.panelPassword && config.connections.length === 0);
88
90
  const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
89
91
  const characters = setup ? [...randomBytes(8)].map((byte) => alphabet[byte & 31]).join('') : '';
90
92
  const setupCode = setup ? `${characters.slice(0, 4)}-${characters.slice(4)}` : undefined;
@@ -105,7 +107,11 @@ async function start(configOption, dev) {
105
107
  const { config, setupCode } = await loadMainConfig(configPath);
106
108
  if (dev)
107
109
  config.pluginLoader.hotReload = true;
108
- const app = createApp(config, { configPath, setupCode });
110
+ const app = createApp(config, {
111
+ configPath,
112
+ setupCode,
113
+ adapters: await loadAdapterModules(config.adapterModules),
114
+ });
109
115
  installProcessHandlers(app);
110
116
  app.logger.info({ configPath }, 'Starting AsaBot');
111
117
  await app.start();
@@ -1,15 +1,24 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { Duplex } from 'node:stream';
3
3
  import type { Logger } from 'pino';
4
- import type { Bot, MessageTarget, SendResult } from './bot.ts';
4
+ import type { z } from 'zod';
5
+ import type { Bot, BotCapabilities, MessageTarget, MessageThread, SendResult } from './bot.ts';
5
6
  import type { ApiCall } from './dispatch/api.ts';
6
7
  import type { AnyEvent, SessionServices } from './event/index.ts';
7
- import type { Message } from './message/index.ts';
8
+ import type { ActorIdentity } from './identity.ts';
9
+ import type { Message, Sendable } from './message/index.ts';
10
+ import type { KVStore } from './storage/index.ts';
8
11
  /** 发送前钩子接收的机器人、目标和消息。 */
9
12
  export interface OutgoingMessage {
10
13
  bot: Bot;
11
14
  target: MessageTarget;
12
15
  message: Message;
16
+ /** 创建话题时,接管发送的钩子可用它发送首段并获取后续分段的目标。 */
17
+ sendFirst?: (content: Sendable) => Promise<SendResult & {
18
+ thread: MessageThread;
19
+ }>;
20
+ /** 接管发送的钩子可用它沿原回调通道发送每一段。 */
21
+ sendPart?: (content: Sendable) => Promise<SendResult>;
13
22
  }
14
23
  /**
15
24
  * A hook takes over delivery (e.g. as a merged forward or several messages). `deliver` runs after the hook chain,
@@ -36,10 +45,20 @@ export interface Adapter {
36
45
  /** 适配器提供的机器人连接方式及可选地址。 */
37
46
  export interface BotInfo {
38
47
  connection: string;
48
+ connectionId?: string;
39
49
  url?: string;
40
50
  }
41
51
  /** 框架提供给适配器的事件、机器人、发送和 API 服务。 */
42
52
  export interface AdapterHost {
53
+ readonly connection?: {
54
+ id: string;
55
+ store: Pick<KVStore, 'get' | 'set'>;
56
+ update(state: {
57
+ state: 'connecting' | 'waiting' | 'online' | 'retrying' | 'error' | 'offline' | 'reauthorize';
58
+ error?: string;
59
+ nextRetryAt?: number;
60
+ }): void;
61
+ };
43
62
  readonly logger: Logger;
44
63
  readonly sessionServices: SessionServices;
45
64
  readonly ignoreSelf: boolean;
@@ -49,9 +68,56 @@ export interface AdapterHost {
49
68
  registerUpgrade(path: string, handler: UpgradeHandler): () => void;
50
69
  setBotInfo(bot: Bot, info: BotInfo): void;
51
70
  whenIdle(): Promise<void>;
52
- isSuperuser(userId: string): boolean;
71
+ isSuperuser(actor: ActorIdentity): boolean;
72
+ isBotAdmin(actor: ActorIdentity): boolean;
53
73
  prepareOutgoing(input: OutgoingMessage): Promise<PreparedOutgoing>;
54
74
  invokeApi(call: ApiCall, execute: (args: unknown[]) => Promise<unknown>): Promise<unknown>;
55
75
  }
76
+ export type QrSetupUpdate = {
77
+ status: 'waiting' | 'scanned' | 'expired' | 'already-bound';
78
+ } | {
79
+ status: 'verification';
80
+ retry: boolean;
81
+ } | {
82
+ status: 'authorized';
83
+ config: unknown;
84
+ adminUserId?: string;
85
+ };
86
+ export interface QrSetupChallenge {
87
+ content: string;
88
+ poll(verifyCode?: string): Promise<QrSetupUpdate>;
89
+ }
90
+ export interface QrConnectionSetup {
91
+ kind: 'qr';
92
+ start(signal: AbortSignal): Promise<QrSetupChallenge>;
93
+ }
94
+ interface AdapterMetadata {
95
+ id: string;
96
+ platform: string;
97
+ name: string;
98
+ version: string;
99
+ description: string;
100
+ connectionTypes: string[];
101
+ capabilities: BotCapabilities;
102
+ }
103
+ type AdapterOptions<T> = AdapterMetadata & {
104
+ configSchema: z.ZodType<T>;
105
+ /** Identifies a remote account or listener before its platform IDs are known. */
106
+ botBinding?(config: T): {
107
+ key: string;
108
+ multiple?: true;
109
+ };
110
+ create(config: T, host: AdapterHost): Adapter;
111
+ } & ({
112
+ setup: QrConnectionSetup;
113
+ accountId(config: T): string;
114
+ } | {
115
+ setup?: undefined;
116
+ accountId?(config: T): string;
117
+ });
118
+ /** 独立适配器包的公开契约;配置由框架在创建连接前校验。 */
119
+ export type AdapterDefinition = AdapterOptions<unknown>;
120
+ export declare function defineAdapter<T>(definition: AdapterOptions<T>): AdapterDefinition;
56
121
  /** 处理 HTTP 升级请求的适配器回调。 */
57
122
  export type UpgradeHandler = (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
123
+ export {};
@@ -1 +1,11 @@
1
- export {};
1
+ export function defineAdapter(definition) {
2
+ const { setup, accountId, botBinding, ...metadata } = definition;
3
+ const shared = {
4
+ ...metadata,
5
+ ...(botBinding && { botBinding: (config) => botBinding(config) }),
6
+ create: (config, host) => definition.create(config, host),
7
+ };
8
+ if (setup)
9
+ return { ...shared, setup, accountId: (config) => accountId(config) };
10
+ return { ...shared, ...(accountId && { accountId: (config) => accountId(config) }) };
11
+ }
@@ -3,17 +3,21 @@ import type { Hono } from 'hono';
3
3
  import type { Logger } from 'pino';
4
4
  import type { Adapter, AdapterHost, BotInfo, OutgoingMessage, PreparedOutgoing, UpgradeHandler } from './adapter.ts';
5
5
  import { type Bot, BotRegistry, type SendResult } from './bot.ts';
6
+ import { BotAccounts, type BotBinding } from './bot-accounts.ts';
7
+ import { BotPolicies } from './bot-policies.ts';
6
8
  import type { Config } from './config/schema.ts';
9
+ import { Connections } from './connections.ts';
7
10
  import { type ApiCall, ApiInterceptors } from './dispatch/api.ts';
8
11
  import { Dispatcher } from './dispatch/dispatcher.ts';
9
12
  import { OutgoingHooks } from './dispatch/outgoing.ts';
10
13
  import { MessageStats } from './dispatch/stats.ts';
11
14
  import type { DispatchEvent } from './dispatch/types.ts';
12
15
  import type { AnyEvent, EventMap, KnownEventMap, MetaEvent, PlatformNoticeEvent, RequestEvent, SessionServices } from './event/index.ts';
16
+ import type { ActorIdentity } from './identity.ts';
13
17
  import type { Sendable } from './message/index.ts';
14
18
  import { PluginManager } from './plugin/manager.ts';
15
19
  import type { PackageOptions } from './plugin/packages.ts';
16
- import { TaskCoordinator } from './plugin/tasks.ts';
20
+ import { TaskService } from './plugin/tasks.ts';
17
21
  import type { PanelPage, PluginStateEvent } from './plugin/types.ts';
18
22
  import { Storage } from './storage/index.ts';
19
23
  import { type Target } from './target.ts';
@@ -42,10 +46,13 @@ export declare class App implements AdapterHost {
42
46
  readonly dispatcher: Dispatcher;
43
47
  readonly outgoing: OutgoingHooks;
44
48
  readonly apiInterceptors: ApiInterceptors;
45
- readonly tasks: TaskCoordinator;
49
+ readonly tasks: TaskService;
46
50
  readonly sessionServices: SessionServices;
47
51
  readonly events: CoreEvents;
52
+ readonly connections: Connections;
48
53
  readonly bots: BotRegistry;
54
+ readonly botAccounts: BotAccounts;
55
+ readonly policies: BotPolicies;
49
56
  readonly storage: Storage;
50
57
  readonly plugins: PluginManager;
51
58
  readonly stats: MessageStats;
@@ -56,8 +63,6 @@ export declare class App implements AdapterHost {
56
63
  private serverFactory?;
57
64
  private serverStarting?;
58
65
  private readonly adapters;
59
- private readonly managedAdapters;
60
- private adapterFactory?;
61
66
  private readonly botInfo;
62
67
  private readonly upgrades;
63
68
  private readonly untrackedBots;
@@ -97,17 +102,15 @@ export declare class App implements AdapterHost {
97
102
  }) => void): () => void;
98
103
  pushPanelEvent(plugin: string, topic: string, data: unknown): void;
99
104
  useAdapter(adapter: Adapter): void;
100
- configureAdapters(factory: (platform: string, config: unknown) => Adapter): void;
101
- useConfiguredAdapter(adapter: Adapter, config: unknown): void;
102
- reconfigureAdapters(next: Record<string, unknown>): Promise<void>;
103
105
  emit(event: AnyEvent): void;
104
106
  emitPluginState(event: PluginStateEvent): void;
105
107
  whenIdle(): Promise<void>;
106
108
  prepareOutgoing(input: OutgoingMessage): Promise<PreparedOutgoing>;
107
109
  invokeApi(call: ApiCall, execute: (args: unknown[]) => Promise<unknown>): Promise<unknown>;
108
- registerBot(bot: Bot): void;
110
+ registerBot(bot: Bot, binding?: BotBinding): void;
109
111
  unregisterBot(bot: Bot): void;
110
- isSuperuser(userId: string): boolean;
112
+ isSuperuser(actor: ActorIdentity): boolean;
113
+ isBotAdmin(actor: ActorIdentity): boolean;
111
114
  getBot(platform: string, selfId: string): Bot | undefined;
112
115
  send(target: Target | string, content: Sendable): Promise<SendResult>;
113
116
  get status(): AppState;
package/dist/core/app.js CHANGED
@@ -1,14 +1,19 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { BotRegistry } from './bot.js';
1
+ import { BotRegistry, sendTo } from './bot.js';
2
+ import { BotAccounts } from './bot-accounts.js';
3
+ import { BotPolicies } from './bot-policies.js';
4
+ import { Connections } from './connections.js';
5
+ import { DeliveryError } from './delivery.js';
3
6
  import { ApiInterceptors } from './dispatch/api.js';
4
7
  import { Dispatcher } from './dispatch/dispatcher.js';
5
8
  import { OutgoingHooks } from './dispatch/outgoing.js';
6
9
  import { MessageStats } from './dispatch/stats.js';
7
- import { NoBotOnlineError } from './errors.js';
10
+ import { dispatchContext } from './dispatch/trace.js';
11
+ import { PluginError } from './errors.js';
8
12
  import { logger as defaultLogger } from './logger.js';
9
13
  import { lowerMessage } from './message/lower.js';
14
+ import { pluginExecution } from './plugin/execution.js';
10
15
  import { PluginManager } from './plugin/manager.js';
11
- import { TaskCoordinator } from './plugin/tasks.js';
16
+ import { TaskService } from './plugin/tasks.js';
12
17
  import { Storage } from './storage/index.js';
13
18
  import { targetSchema } from './target.js';
14
19
  class CoreEvents {
@@ -30,10 +35,13 @@ export class App {
30
35
  dispatcher;
31
36
  outgoing;
32
37
  apiInterceptors = new ApiInterceptors();
33
- tasks = new TaskCoordinator();
38
+ tasks;
34
39
  sessionServices;
35
40
  events;
41
+ connections;
36
42
  bots = new BotRegistry();
43
+ botAccounts;
44
+ policies;
37
45
  storage;
38
46
  plugins;
39
47
  stats;
@@ -44,8 +52,6 @@ export class App {
44
52
  serverFactory;
45
53
  serverStarting;
46
54
  adapters = [];
47
- managedAdapters = new Map();
48
- adapterFactory;
49
55
  botInfo = new WeakMap();
50
56
  upgrades = new Map();
51
57
  untrackedBots = new WeakSet();
@@ -58,6 +64,7 @@ export class App {
58
64
  state = 'created';
59
65
  constructor(config, logger = defaultLogger, options = {}) {
60
66
  this.config = config;
67
+ this.connections = new Connections(this);
61
68
  this.configPath = options.configPath;
62
69
  this.setupCode = options.setupCode;
63
70
  this.logger = logger;
@@ -67,6 +74,20 @@ export class App {
67
74
  this.sessionServices = this.dispatcher;
68
75
  this.events = new CoreEvents(this.dispatcher);
69
76
  this.storage = new Storage(config.dataDir, logger);
77
+ this.botAccounts = new BotAccounts(this.storage);
78
+ this.policies = new BotPolicies(this.storage);
79
+ this.apiInterceptors.check = (call) => {
80
+ const owner = pluginExecution.getStore() ?? dispatchContext.getStore()?.plugin;
81
+ if (owner && !this.plugins.isEnabledOnBot(owner, call.bot))
82
+ throw new PluginError(`Plugin "${owner}" is disabled for ${call.bot.platform}:${call.bot.selfId}`);
83
+ };
84
+ this.apiInterceptors.enabled = (owner, bot) => this.plugins.isEnabledOnBot(owner, bot);
85
+ this.outgoing.enabled = (owner, input) => this.plugins.isEnabledFor(owner, {
86
+ platform: input.bot.platform,
87
+ selfId: input.bot.selfId,
88
+ ...(input.target.type === 'group' ? { groupId: input.target.id } : {}),
89
+ });
90
+ this.tasks = new TaskService(this.storage, config, logger);
70
91
  this.plugins = new PluginManager(this, options.configPath, options.packages);
71
92
  this.dispatcher.accessFilter = (event) => this.storage.allows(event);
72
93
  this.dispatcher.isEnabledFor = (owner, event) => this.plugins.isEnabledFor(owner, event);
@@ -118,6 +139,8 @@ export class App {
118
139
  }
119
140
  setBotInfo(bot, info) {
120
141
  this.botInfo.set(bot, info);
142
+ if (this.getBot(bot.platform, bot.selfId) === bot)
143
+ this.botAccounts.record(bot, info);
121
144
  }
122
145
  getBotInfo(bot) {
123
146
  return this.botInfo.get(bot);
@@ -206,46 +229,11 @@ export class App {
206
229
  });
207
230
  }
208
231
  }
209
- configureAdapters(factory) {
210
- this.adapterFactory = factory;
211
- }
212
- useConfiguredAdapter(adapter, config) {
213
- this.managedAdapters.set(adapter.platform, { adapter, config });
214
- this.useAdapter(adapter);
215
- }
216
- async reconfigureAdapters(next) {
217
- if (this.state === 'stopped')
218
- throw new Error('Cannot reconfigure a stopped App');
219
- for (const [platform, current] of this.managedAdapters) {
220
- if (!Object.hasOwn(next, platform)) {
221
- await current.adapter.stop();
222
- this.adapters.splice(this.adapters.indexOf(current.adapter), 1);
223
- this.managedAdapters.delete(platform);
224
- }
225
- }
226
- for (const [platform, config] of Object.entries(next)) {
227
- const current = this.managedAdapters.get(platform);
228
- if (current) {
229
- if (!isDeepStrictEqual(current.config, config)) {
230
- await current.adapter.reconfigure(config);
231
- current.config = config;
232
- }
233
- }
234
- else {
235
- if (!this.adapterFactory)
236
- throw new Error('Adapter factory is not configured');
237
- const adapter = this.adapterFactory(platform, config);
238
- this.managedAdapters.set(platform, { adapter, config });
239
- this.adapters.push(adapter);
240
- if (this.state === 'running')
241
- await adapter.start();
242
- }
243
- }
244
- this.config.adapters = next;
245
- }
246
232
  emit(event) {
247
233
  if (this.state === 'stopped')
248
234
  return;
235
+ if (event.name === 'bot.online' && this.getBot(event.platform, event.selfId) === event.bot)
236
+ this.botAccounts.record(event.bot, this.getBotInfo(event.bot), event.time);
249
237
  void this.dispatcher.dispatch(event).catch((error) => {
250
238
  this.logger.error({ err: error, event: event.name, eventId: event.id }, 'Event dispatch failed');
251
239
  });
@@ -267,15 +255,21 @@ export class App {
267
255
  invokeApi(call, execute) {
268
256
  return this.apiInterceptors.invoke(call, execute);
269
257
  }
270
- registerBot(bot) {
258
+ registerBot(bot, binding) {
259
+ this.policies.enroll(bot, () => this.plugins.defaultsForNewBot());
271
260
  this.bots.register(bot);
272
261
  this.apiInterceptors.wrap(bot);
262
+ this.botAccounts.record(bot, this.getBotInfo(bot), bot.status === 'online' ? Date.now() : undefined);
263
+ this.botAccounts.bind(bot, binding);
273
264
  }
274
265
  unregisterBot(bot) {
275
266
  this.bots.unregister(bot);
276
267
  }
277
- isSuperuser(userId) {
278
- return this.config.superusers.includes(userId);
268
+ isSuperuser(actor) {
269
+ return this.config.superusers.some((entry) => entry.platform === actor.platform && entry.selfId === actor.selfId && entry.userId === actor.userId);
270
+ }
271
+ isBotAdmin(actor) {
272
+ return this.isSuperuser(actor) || this.policies.isAdmin(actor);
279
273
  }
280
274
  getBot(platform, selfId) {
281
275
  return this.bots.get(platform, selfId);
@@ -288,10 +282,8 @@ export class App {
288
282
  item.platform === destination.platform &&
289
283
  (destination.selfId === undefined || item.selfId === destination.selfId));
290
284
  if (!bot)
291
- throw new NoBotOnlineError();
292
- return destination.type === 'group'
293
- ? bot.sendGroup(destination.id, content)
294
- : bot.sendPrivate(destination.id, content);
285
+ throw new DeliveryError(destination, { code: 'NO_BOT_ONLINE' });
286
+ return sendTo(bot, destination, content);
295
287
  }
296
288
  get status() {
297
289
  return this.state;
@@ -304,15 +296,20 @@ export class App {
304
296
  throw new Error('A stopped App cannot be restarted');
305
297
  }
306
298
  this.storage.open();
299
+ this.policies.load();
307
300
  try {
301
+ this.tasks.start();
308
302
  await this.plugins.start();
303
+ this.policies.captureExistingDefaults(this.plugins.list().map(({ name }) => name));
309
304
  }
310
305
  catch (error) {
311
306
  await this.plugins.stop();
307
+ this.tasks.stop();
312
308
  this.storage.close();
313
309
  throw error;
314
310
  }
315
311
  this.state = 'running';
312
+ await this.connections.start();
316
313
  for (const adapter of this.adapters) {
317
314
  try {
318
315
  await adapter.start();
@@ -340,6 +337,8 @@ export class App {
340
337
  this.shutdown.abort(new DOMException('App stopped', 'AbortError'));
341
338
  await this.whenIdle();
342
339
  await this.plugins.stop();
340
+ this.tasks.stop();
341
+ await this.connections.stop();
343
342
  for (const adapter of this.adapters) {
344
343
  try {
345
344
  await adapter.stop();
@@ -0,0 +1,28 @@
1
+ import type { BotInfo } from './adapter.ts';
2
+ import { type Bot, type BotCapabilities } from './bot.ts';
3
+ import { type BotIdentity } from './identity.ts';
4
+ import type { Storage } from './storage/index.ts';
5
+ export interface BotAccount extends BotIdentity {
6
+ nickname?: string;
7
+ avatar?: string;
8
+ capabilities?: BotCapabilities;
9
+ connection?: string;
10
+ connectionId?: string;
11
+ lastOnlineAt?: number;
12
+ }
13
+ export interface BotBinding {
14
+ id: string;
15
+ key: string;
16
+ multiple: boolean;
17
+ }
18
+ export declare function botAvatar(bot: Bot): string | undefined;
19
+ /** Known identities and profile data, independent of the live Bot registry. */
20
+ export declare class BotAccounts {
21
+ private readonly storage;
22
+ constructor(storage: Storage);
23
+ get(bot: BotIdentity): BotAccount | undefined;
24
+ list(): BotAccount[];
25
+ record(bot: Bot, info?: BotInfo, lastOnlineAt?: number): void;
26
+ bind(bot: Bot, binding?: BotBinding): void;
27
+ pruneBindings(bindings: ReadonlyMap<string, BotBinding>): void;
28
+ }