@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,78 @@
1
+ import { supports } from './bot.js';
2
+ import { capabilitySchema } from './capabilities.js';
3
+ import { botKey } from './identity.js';
4
+ export function botAvatar(bot) {
5
+ return bot.avatar ?? (supports(bot, 'getAvatarUrl') ? bot.getAvatarUrl?.(bot.selfId) : undefined);
6
+ }
7
+ function publicAvatar(value) {
8
+ if (!value)
9
+ return undefined;
10
+ const url = URL.parse(value);
11
+ if (!url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password)
12
+ return undefined;
13
+ for (const key of url.searchParams.keys()) {
14
+ if (/token|secret|password|credential|authorization|signature|api[_-]?key/i.test(key))
15
+ return undefined;
16
+ }
17
+ url.hash = '';
18
+ return url.href;
19
+ }
20
+ function account(row) {
21
+ const [platform, selfId] = JSON.parse(String(row.bot_key));
22
+ return {
23
+ platform,
24
+ selfId,
25
+ nickname: row.nickname === null ? undefined : String(row.nickname),
26
+ avatar: row.avatar === null ? undefined : String(row.avatar),
27
+ capabilities: row.capabilities === null ? undefined : capabilitySchema.parse(JSON.parse(String(row.capabilities))),
28
+ connection: row.connection === null ? undefined : String(row.connection),
29
+ connectionId: row.connection_id === null ? undefined : String(row.connection_id),
30
+ lastOnlineAt: row.last_online_at === null ? undefined : Number(row.last_online_at),
31
+ };
32
+ }
33
+ /** Known identities and profile data, independent of the live Bot registry. */
34
+ export class BotAccounts {
35
+ storage;
36
+ constructor(storage) {
37
+ this.storage = storage;
38
+ }
39
+ get(bot) {
40
+ const row = this.storage.db.prepare('SELECT * FROM bot_accounts WHERE bot_key = ?').get(botKey(bot));
41
+ return row && account(row);
42
+ }
43
+ list() {
44
+ return this.storage.db.prepare('SELECT * FROM bot_accounts ORDER BY bot_key').all().map(account);
45
+ }
46
+ record(bot, info, lastOnlineAt) {
47
+ if (bot.platform === 'virtual')
48
+ return;
49
+ this.storage.db
50
+ .prepare(`INSERT INTO bot_accounts (bot_key, nickname, avatar, capabilities, connection, last_online_at)
51
+ VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(bot_key) DO UPDATE SET
52
+ nickname = COALESCE(excluded.nickname, nickname), avatar = COALESCE(excluded.avatar, avatar),
53
+ capabilities = excluded.capabilities, connection = COALESCE(excluded.connection, connection),
54
+ last_online_at = COALESCE(excluded.last_online_at, last_online_at)`)
55
+ .run(botKey(bot), bot.nickname || null, publicAvatar(botAvatar(bot)) ?? null, JSON.stringify(bot.capabilities), info?.connection ?? null, lastOnlineAt ?? null);
56
+ }
57
+ bind(bot, binding) {
58
+ if (bot.platform === 'virtual')
59
+ return;
60
+ const db = this.storage.db;
61
+ const key = botKey(bot);
62
+ if (binding && !binding.multiple)
63
+ db.prepare(`UPDATE bot_accounts SET connection_id = NULL, binding_key = NULL
64
+ WHERE connection_id = ? AND bot_key <> ?`).run(binding.id, key);
65
+ db.prepare('UPDATE bot_accounts SET connection_id = ?, binding_key = ? WHERE bot_key = ?').run(binding?.id ?? null, binding?.key ?? null, key);
66
+ }
67
+ pruneBindings(bindings) {
68
+ const db = this.storage.db;
69
+ const clear = db.prepare('UPDATE bot_accounts SET connection_id = NULL, binding_key = NULL WHERE connection_id = ?');
70
+ for (const row of db
71
+ .prepare('SELECT DISTINCT connection_id, binding_key FROM bot_accounts WHERE connection_id IS NOT NULL')
72
+ .all()) {
73
+ const id = String(row.connection_id);
74
+ if (bindings.get(id)?.key !== row.binding_key)
75
+ clear.run(id);
76
+ }
77
+ }
78
+ }
@@ -0,0 +1,30 @@
1
+ import type { ActorIdentity, BotIdentity } from './identity.ts';
2
+ import type { Storage } from './storage/index.ts';
3
+ export declare class BotPolicies {
4
+ private readonly adminUsers;
5
+ private readonly plugins;
6
+ private readonly defaults;
7
+ private readonly subscribers;
8
+ constructor(privateStorage: Storage);
9
+ private readonly storage;
10
+ subscribe(listener: () => void): () => void;
11
+ private publish;
12
+ load(): void;
13
+ captureExistingDefaults(plugins: string[]): void;
14
+ enroll(bot: BotIdentity, initialPlugins: () => string[]): void;
15
+ defaultPluginEnabled(bot: BotIdentity, plugin: string): boolean;
16
+ admins(bot: BotIdentity): string[];
17
+ isAdmin(actor: ActorIdentity): boolean;
18
+ setAdmins(bot: BotIdentity, users: string[]): void;
19
+ plugin(bot: BotIdentity, plugin: string): {
20
+ enabled?: boolean;
21
+ config?: Record<string, unknown>;
22
+ };
23
+ setPlugin(bot: BotIdentity, plugin: string, policy: {
24
+ enabled?: boolean;
25
+ config?: Record<string, unknown>;
26
+ }): void;
27
+ configured(plugin: string): (BotIdentity & {
28
+ config: Record<string, unknown>;
29
+ })[];
30
+ }
@@ -0,0 +1,112 @@
1
+ import { botKey } from './identity.js';
2
+ export class BotPolicies {
3
+ adminUsers = new Map();
4
+ plugins = new Map();
5
+ defaults = new Map();
6
+ subscribers = new Set();
7
+ constructor(privateStorage) {
8
+ this.storage = privateStorage;
9
+ }
10
+ storage;
11
+ subscribe(listener) {
12
+ this.subscribers.add(listener);
13
+ return () => this.subscribers.delete(listener);
14
+ }
15
+ publish() {
16
+ for (const listener of this.subscribers)
17
+ listener();
18
+ }
19
+ load() {
20
+ this.adminUsers.clear();
21
+ this.plugins.clear();
22
+ this.defaults.clear();
23
+ for (const row of this.storage.db.prepare('SELECT bot_key, user_id FROM bot_admins').all()) {
24
+ const key = String(row.bot_key);
25
+ const users = this.adminUsers.get(key) ?? new Set();
26
+ users.add(String(row.user_id));
27
+ this.adminUsers.set(key, users);
28
+ }
29
+ for (const row of this.storage.db.prepare('SELECT * FROM plugin_bot_policy').all()) {
30
+ this.plugins.set(JSON.stringify([String(row.bot_key), String(row.plugin)]), {
31
+ ...(row.enabled === null ? {} : { enabled: row.enabled === 1 }),
32
+ ...(row.config === null ? {} : { config: JSON.parse(String(row.config)) }),
33
+ });
34
+ }
35
+ for (const row of this.storage.db
36
+ .prepare('SELECT * FROM bot_plugin_defaults WHERE plugins IS NOT NULL')
37
+ .all()) {
38
+ this.defaults.set(String(row.bot_key), new Set(JSON.parse(String(row.plugins))));
39
+ }
40
+ }
41
+ captureExistingDefaults(plugins) {
42
+ const defaults = new Set(plugins);
43
+ const migrated = this.storage.db
44
+ .prepare('UPDATE bot_plugin_defaults SET plugins = ? WHERE plugins IS NULL RETURNING bot_key')
45
+ .all(JSON.stringify(plugins));
46
+ for (const row of migrated)
47
+ this.defaults.set(String(row.bot_key), defaults);
48
+ }
49
+ enroll(bot, initialPlugins) {
50
+ if (bot.platform === 'virtual')
51
+ return;
52
+ const key = botKey(bot);
53
+ if (this.defaults.has(key))
54
+ return;
55
+ const plugins = initialPlugins();
56
+ this.storage.db.prepare('INSERT INTO bot_plugin_defaults VALUES (?, ?)').run(key, JSON.stringify(plugins));
57
+ this.defaults.set(key, new Set(plugins));
58
+ }
59
+ defaultPluginEnabled(bot, plugin) {
60
+ // The playground and events without a real account use globally enabled plugins.
61
+ return (bot.platform === 'virtual' ? undefined : this.defaults.get(botKey(bot)))?.has(plugin) ?? true;
62
+ }
63
+ admins(bot) {
64
+ return [...(this.adminUsers.get(botKey(bot)) ?? [])].sort();
65
+ }
66
+ isAdmin(actor) {
67
+ return this.adminUsers.get(botKey(actor))?.has(actor.userId) === true;
68
+ }
69
+ setAdmins(bot, users) {
70
+ const db = this.storage.db;
71
+ db.exec('BEGIN IMMEDIATE');
72
+ try {
73
+ db.prepare('DELETE FROM bot_admins WHERE bot_key = ?').run(botKey(bot));
74
+ for (const user of new Set(users))
75
+ db.prepare('INSERT INTO bot_admins VALUES (?, ?)').run(botKey(bot), user);
76
+ db.exec('COMMIT');
77
+ this.adminUsers.set(botKey(bot), new Set(users));
78
+ }
79
+ catch (error) {
80
+ db.exec('ROLLBACK');
81
+ throw error;
82
+ }
83
+ this.publish();
84
+ }
85
+ plugin(bot, plugin) {
86
+ return this.plugins.get(JSON.stringify([botKey(bot), plugin])) ?? {};
87
+ }
88
+ setPlugin(bot, plugin, policy) {
89
+ if (policy.enabled === undefined && policy.config === undefined) {
90
+ this.storage.db
91
+ .prepare('DELETE FROM plugin_bot_policy WHERE bot_key = ? AND plugin = ?')
92
+ .run(botKey(bot), plugin);
93
+ this.plugins.delete(JSON.stringify([botKey(bot), plugin]));
94
+ }
95
+ else {
96
+ this.storage.db
97
+ .prepare('INSERT INTO plugin_bot_policy (bot_key, plugin, enabled, config) VALUES (?, ?, ?, ?) ON CONFLICT(bot_key, plugin) DO UPDATE SET enabled = excluded.enabled, config = excluded.config')
98
+ .run(botKey(bot), plugin, policy.enabled === undefined ? null : Number(policy.enabled), policy.config === undefined ? null : JSON.stringify(policy.config));
99
+ this.plugins.set(JSON.stringify([botKey(bot), plugin]), policy);
100
+ }
101
+ this.publish();
102
+ }
103
+ configured(plugin) {
104
+ return this.storage.db
105
+ .prepare('SELECT bot_key, config FROM plugin_bot_policy WHERE plugin = ? AND config IS NOT NULL')
106
+ .all(plugin)
107
+ .map((row) => {
108
+ const [platform, selfId] = JSON.parse(String(row.bot_key));
109
+ return { platform, selfId, config: JSON.parse(String(row.config)) };
110
+ });
111
+ }
112
+ }
@@ -15,6 +15,7 @@ export interface MessageInfo {
15
15
  messageType: 'private' | 'group';
16
16
  userId: string;
17
17
  groupId?: string;
18
+ thread?: MessageThread;
18
19
  time: number;
19
20
  message: Message;
20
21
  sender: {
@@ -37,19 +38,30 @@ export interface ForwardMessage {
37
38
  time?: number;
38
39
  message: Message;
39
40
  }
40
- /** 机器人发送消息使用的群聊或私聊目标。 */
41
+ /** 平台话题及其固定的根消息。 */
42
+ export interface MessageThread {
43
+ id: string;
44
+ rootMessageId: string;
45
+ }
46
+ /** 机器人发送消息使用的群聊、私聊或其中的话题。 */
41
47
  export type MessageTarget = {
42
48
  type: 'group' | 'private';
43
49
  id: string;
50
+ thread?: MessageThread;
51
+ };
52
+ export type ThreadTarget = MessageTarget & {
53
+ thread: MessageThread;
44
54
  };
45
55
  /** 发送成功后返回的平台消息 ID。 */
46
56
  export interface SendResult {
47
57
  messageId: string;
58
+ thread?: MessageThread;
48
59
  }
49
60
  /** 平台用户的 ID、昵称及可选扩展信息。 */
50
61
  export interface UserInfo {
51
62
  userId: string;
52
63
  nickname: string;
64
+ avatar?: string;
53
65
  sex?: string;
54
66
  age?: number;
55
67
  [key: string]: unknown;
@@ -82,10 +94,14 @@ export interface Bot {
82
94
  /** Display name of the bot account, known once it has logged in. */
83
95
  /** 登录后已知的机器人昵称。 */
84
96
  readonly nickname?: string;
97
+ /** 平台提供的当前机器人头像,不依赖用户头像查询能力。 */
98
+ readonly avatar?: string;
85
99
  /** 向用户发送私聊消息,返回消息 ID。 */
86
100
  sendPrivate(userId: string, content: Sendable): Promise<SendResult>;
87
101
  /** 向群发送消息,返回消息 ID。 */
88
102
  sendGroup(groupId: string, content: Sendable): Promise<SendResult>;
103
+ /** 向群聊或私聊内的现有话题发送消息。 */
104
+ sendThread?(target: ThreadTarget, content: Sendable): Promise<SendResult>;
89
105
  /** 向指定私聊或群发送合并转发节点。 */
90
106
  sendForward(target: MessageTarget, nodes: ForwardNode[]): Promise<SendResult>;
91
107
  /** 按转发 ID 获取合并转发的节点。 */
@@ -117,6 +133,8 @@ export interface Bot {
117
133
  /** 获取用户头像地址;不可用时返回 undefined,部分平台不提供此方法。 */
118
134
  getAvatarUrl?(userId: string): string | undefined;
119
135
  }
136
+ /** 按完整会话目标发送,话题发送失败时不会回落到所在群聊或私聊。 */
137
+ export declare function sendTo(bot: Bot, target: MessageTarget, content: Sendable): Promise<SendResult>;
120
138
  /** 按平台和账号 ID 管理机器人实例的注册表。 */
121
139
  export declare class BotRegistry {
122
140
  private readonly entries;
package/dist/core/bot.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { DeliveryAttempt } from './delivery.js';
2
+ import { UnsupportedError } from './errors.js';
1
3
  export const botActions = [
2
4
  'sendPrivate',
3
5
  'sendGroup',
@@ -22,6 +24,17 @@ export function supports(bot, feature) {
22
24
  export function supportsSegment(bot, feature) {
23
25
  return bot.capabilities.segments.some((segment) => segment === feature || (segment.endsWith(':*') && feature.startsWith(segment.slice(0, -1))));
24
26
  }
27
+ /** 按完整会话目标发送,话题发送失败时不会回落到所在群聊或私聊。 */
28
+ export async function sendTo(bot, target, content) {
29
+ return new DeliveryAttempt(bot, target).request(async () => {
30
+ if (target.thread) {
31
+ if (!bot.sendThread || !bot.capabilities.actions.includes('sendThread'))
32
+ throw new UnsupportedError(bot.platform, 'sendThread');
33
+ return bot.sendThread({ ...target, thread: target.thread }, content);
34
+ }
35
+ return target.type === 'group' ? bot.sendGroup(target.id, content) : bot.sendPrivate(target.id, content);
36
+ });
37
+ }
25
38
  /** 按平台和账号 ID 管理机器人实例的注册表。 */
26
39
  export class BotRegistry {
27
40
  entries = new Map();
@@ -0,0 +1,54 @@
1
+ import { z } from 'zod';
2
+ import type { BotCapabilities } from './bot.ts';
3
+ export declare const capabilitySchema: z.ZodObject<{
4
+ segments: z.ZodArray<z.ZodString>;
5
+ textStyles: z.ZodArray<z.ZodEnum<{
6
+ bold: "bold";
7
+ code: "code";
8
+ italic: "italic";
9
+ spoiler: "spoiler";
10
+ strike: "strike";
11
+ underline: "underline";
12
+ }>>;
13
+ actions: z.ZodArray<z.ZodString>;
14
+ }, z.core.$strict>;
15
+ export declare const requirementsSchema: z.ZodObject<{
16
+ required: z.ZodOptional<z.ZodObject<{
17
+ segments: z.ZodOptional<z.ZodArray<z.ZodString>>;
18
+ textStyles: z.ZodOptional<z.ZodArray<z.ZodEnum<{
19
+ bold: "bold";
20
+ code: "code";
21
+ italic: "italic";
22
+ spoiler: "spoiler";
23
+ strike: "strike";
24
+ underline: "underline";
25
+ }>>>;
26
+ actions: z.ZodOptional<z.ZodArray<z.ZodString>>;
27
+ }, z.core.$strict>>;
28
+ optional: z.ZodOptional<z.ZodObject<{
29
+ segments: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ textStyles: z.ZodOptional<z.ZodArray<z.ZodEnum<{
31
+ bold: "bold";
32
+ code: "code";
33
+ italic: "italic";
34
+ spoiler: "spoiler";
35
+ strike: "strike";
36
+ underline: "underline";
37
+ }>>>;
38
+ actions: z.ZodOptional<z.ZodArray<z.ZodString>>;
39
+ }, z.core.$strict>>;
40
+ }, z.core.$strict>;
41
+ export interface CapabilityRequirements {
42
+ required?: Partial<BotCapabilities>;
43
+ optional?: Partial<BotCapabilities>;
44
+ }
45
+ export interface CapabilityGap {
46
+ kind: keyof BotCapabilities;
47
+ name: string;
48
+ }
49
+ export interface Compatibility {
50
+ declared: boolean;
51
+ required: CapabilityGap[];
52
+ optional: CapabilityGap[];
53
+ }
54
+ export declare function compatibility(requirements: CapabilityRequirements | undefined, actual: BotCapabilities): Compatibility;
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod';
2
+ export const capabilitySchema = z
3
+ .object({
4
+ segments: z.array(z.string()),
5
+ textStyles: z.array(z.enum(['bold', 'italic', 'underline', 'strike', 'code', 'spoiler'])),
6
+ actions: z.array(z.string()),
7
+ })
8
+ .strict();
9
+ export const requirementsSchema = z
10
+ .object({
11
+ required: capabilitySchema.partial().optional(),
12
+ optional: capabilitySchema.partial().optional(),
13
+ })
14
+ .strict();
15
+ export function compatibility(requirements, actual) {
16
+ const missing = (wanted) => ['segments', 'textStyles', 'actions'].flatMap((kind) => (wanted?.[kind] ?? [])
17
+ .filter((name) => !actual[kind].some((value) => value === name ||
18
+ (kind === 'segments' && value.endsWith(':*') && name.startsWith(value.slice(0, -1)))))
19
+ .map((name) => ({ kind, name })));
20
+ return {
21
+ declared: requirements !== undefined,
22
+ required: missing(requirements?.required),
23
+ optional: missing(requirements?.optional),
24
+ };
25
+ }
@@ -12,6 +12,7 @@ export declare const commandOverrideSchema: z.ZodObject<{
12
12
  enabled: z.ZodOptional<z.ZodBoolean>;
13
13
  aliases: z.ZodOptional<z.ZodArray<z.ZodString>>;
14
14
  permission: z.ZodOptional<z.ZodEnum<{
15
+ "bot.admin": "bot.admin";
15
16
  everyone: "everyone";
16
17
  "group.admin": "group.admin";
17
18
  "group.owner": "group.owner";
@@ -47,7 +48,11 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
47
48
  }, z.core.$strict>>;
48
49
  timezone: z.ZodPrefault<z.ZodString>;
49
50
  dataDir: z.ZodDefault<z.ZodString>;
50
- superusers: z.ZodDefault<z.ZodArray<z.ZodString>>;
51
+ superusers: z.ZodDefault<z.ZodArray<z.ZodObject<{
52
+ platform: z.ZodString;
53
+ selfId: z.ZodString;
54
+ userId: z.ZodString;
55
+ }, z.core.$strict>>>;
51
56
  command: z.ZodDefault<z.ZodObject<{
52
57
  prefixes: z.ZodDefault<z.ZodArray<z.ZodString>>;
53
58
  mentionAsPrefix: z.ZodDefault<z.ZodBoolean>;
@@ -63,6 +68,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
63
68
  enabled: z.ZodOptional<z.ZodBoolean>;
64
69
  aliases: z.ZodOptional<z.ZodArray<z.ZodString>>;
65
70
  permission: z.ZodOptional<z.ZodEnum<{
71
+ "bot.admin": "bot.admin";
66
72
  everyone: "everyone";
67
73
  "group.admin": "group.admin";
68
74
  "group.owner": "group.owner";
@@ -85,7 +91,14 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
85
91
  promptTimeout: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
86
92
  maxPromptTimeout: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
87
93
  }, z.core.$strict>>;
88
- adapters: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
94
+ adapterModules: z.ZodDefault<z.ZodArray<z.ZodString>>;
95
+ connections: z.ZodDefault<z.ZodArray<z.ZodObject<{
96
+ id: z.ZodString;
97
+ name: z.ZodString;
98
+ adapter: z.ZodString;
99
+ enabled: z.ZodDefault<z.ZodBoolean>;
100
+ config: z.ZodUnknown;
101
+ }, z.core.$strict>>>;
89
102
  pluginLoader: z.ZodDefault<z.ZodObject<{
90
103
  dirs: z.ZodDefault<z.ZodArray<z.ZodString>>;
91
104
  uploadDir: z.ZodOptional<z.ZodString>;
@@ -98,8 +111,14 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
98
111
  npm: z.ZodDefault<z.ZodString>;
99
112
  installTimeout: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
100
113
  }, z.core.$strict>>;
114
+ tasks: z.ZodDefault<z.ZodObject<{
115
+ maxConcurrent: z.ZodDefault<z.ZodNumber>;
116
+ historyRetention: z.ZodDefault<z.ZodPipe<z.ZodUnion<readonly [z.ZodNumber, z.ZodString]>, z.ZodTransform<number, string | number>>>;
117
+ maxHistory: z.ZodDefault<z.ZodNumber>;
118
+ }, z.core.$strict>>;
101
119
  plugins: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
102
120
  enabled: z.ZodDefault<z.ZodBoolean>;
121
+ defaultOnNewBots: z.ZodOptional<z.ZodBoolean>;
103
122
  config: z.ZodOptional<z.ZodUnknown>;
104
123
  }, z.core.$strict>>>;
105
124
  server: z.ZodDefault<z.ZodObject<{
@@ -119,7 +138,11 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
119
138
  };
120
139
  timezone: string;
121
140
  dataDir: string;
122
- superusers: string[];
141
+ superusers: {
142
+ platform: string;
143
+ selfId: string;
144
+ userId: string;
145
+ }[];
123
146
  command: {
124
147
  prefixes: string[];
125
148
  mentionAsPrefix: boolean;
@@ -130,7 +153,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
130
153
  overrides: Record<string, {
131
154
  enabled?: boolean | undefined;
132
155
  aliases?: string[] | undefined;
133
- permission?: "everyone" | "group.admin" | "group.owner" | "superuser" | undefined;
156
+ permission?: "bot.admin" | "everyone" | "group.admin" | "group.owner" | "superuser" | undefined;
134
157
  cooldown?: false | {
135
158
  duration: number;
136
159
  scope?: "global" | "group" | "user" | undefined;
@@ -144,9 +167,22 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
144
167
  promptTimeout: number;
145
168
  maxPromptTimeout: number;
146
169
  };
147
- adapters: Record<string, unknown>;
170
+ adapterModules: string[];
171
+ connections: {
172
+ id: string;
173
+ name: string;
174
+ adapter: string;
175
+ enabled: boolean;
176
+ config: unknown;
177
+ }[];
178
+ tasks: {
179
+ maxConcurrent: number;
180
+ historyRetention: number;
181
+ maxHistory: number;
182
+ };
148
183
  plugins: Record<string, {
149
184
  enabled: boolean;
185
+ defaultOnNewBots?: boolean | undefined;
150
186
  config?: unknown;
151
187
  }>;
152
188
  server: {
@@ -178,7 +214,11 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
178
214
  };
179
215
  timezone: string;
180
216
  dataDir: string;
181
- superusers: string[];
217
+ superusers: {
218
+ platform: string;
219
+ selfId: string;
220
+ userId: string;
221
+ }[];
182
222
  command: {
183
223
  prefixes: string[];
184
224
  mentionAsPrefix: boolean;
@@ -189,7 +229,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
189
229
  overrides: Record<string, {
190
230
  enabled?: boolean | undefined;
191
231
  aliases?: string[] | undefined;
192
- permission?: "everyone" | "group.admin" | "group.owner" | "superuser" | undefined;
232
+ permission?: "bot.admin" | "everyone" | "group.admin" | "group.owner" | "superuser" | undefined;
193
233
  cooldown?: false | {
194
234
  duration: number;
195
235
  scope?: "global" | "group" | "user" | undefined;
@@ -203,7 +243,14 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
203
243
  promptTimeout: number;
204
244
  maxPromptTimeout: number;
205
245
  };
206
- adapters: Record<string, unknown>;
246
+ adapterModules: string[];
247
+ connections: {
248
+ id: string;
249
+ name: string;
250
+ adapter: string;
251
+ enabled: boolean;
252
+ config: unknown;
253
+ }[];
207
254
  pluginLoader: {
208
255
  dirs: string[];
209
256
  uploadDir?: string | undefined;
@@ -216,8 +263,14 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
216
263
  npm: string;
217
264
  installTimeout: number;
218
265
  };
266
+ tasks: {
267
+ maxConcurrent: number;
268
+ historyRetention: number;
269
+ maxHistory: number;
270
+ };
219
271
  plugins: Record<string, {
220
272
  enabled: boolean;
273
+ defaultOnNewBots?: boolean | undefined;
221
274
  config?: unknown;
222
275
  }>;
223
276
  server: {
@@ -1,5 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { z } from 'zod';
3
+ import { connectionSchema } from '../connections.js';
4
+ import { actorIdentitySchema } from '../identity.js';
3
5
  import { parseDuration } from '../utils/duration.js';
4
6
  export const durationSchema = z
5
7
  .union([z.number().finite().nonnegative(), z.string()])
@@ -61,7 +63,7 @@ export const commandOverrideSchema = z
61
63
  .object({
62
64
  enabled: z.boolean().optional(),
63
65
  aliases: z.array(z.string().trim().min(1)).optional(),
64
- permission: z.enum(['everyone', 'superuser', 'group.admin', 'group.owner']).optional(),
66
+ permission: z.enum(['everyone', 'superuser', 'bot.admin', 'group.admin', 'group.owner']).optional(),
65
67
  cooldown: z
66
68
  .union([
67
69
  z.literal(false),
@@ -113,9 +115,17 @@ const packagesSchema = z
113
115
  const pluginEntrySchema = z
114
116
  .object({
115
117
  enabled: z.boolean().default(true),
118
+ defaultOnNewBots: z.boolean().optional(),
116
119
  config: z.unknown().optional(),
117
120
  })
118
121
  .strict();
122
+ const tasksSchema = z
123
+ .object({
124
+ maxConcurrent: z.number().int().min(1).default(4),
125
+ historyRetention: durationSchema.default(7 * 86_400_000),
126
+ maxHistory: z.number().int().nonnegative().default(10_000),
127
+ })
128
+ .strict();
119
129
  const serverSchema = z
120
130
  .object({
121
131
  host: z.string().min(1).default('127.0.0.1'),
@@ -130,12 +140,14 @@ export const configSchema = z
130
140
  log: logSchema.default(() => logSchema.parse({})),
131
141
  timezone: timezoneSchema.prefault(() => process.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone),
132
142
  dataDir: z.string().min(1).default('./data'),
133
- superusers: z.array(z.string()).default([]),
143
+ superusers: z.array(actorIdentitySchema).default([]),
134
144
  command: commandSchema.default(() => commandSchema.parse({})),
135
145
  dispatch: dispatchSchema.default(() => dispatchSchema.parse({})),
136
- adapters: z.record(z.string(), z.unknown()).default({}),
146
+ adapterModules: z.array(z.string().min(1)).default([]),
147
+ connections: z.array(connectionSchema).default([]),
137
148
  pluginLoader: pluginLoaderSchema.default(() => pluginLoaderSchema.parse({})),
138
149
  packages: packagesSchema.default(() => packagesSchema.parse({})),
150
+ tasks: tasksSchema.default(() => tasksSchema.parse({})),
139
151
  plugins: z.record(z.string(), pluginEntrySchema).default({}),
140
152
  server: serverSchema.default(() => serverSchema.parse({})),
141
153
  })
@@ -44,6 +44,7 @@ export async function writeConfigValue(path, keyPath, value, options) {
44
44
  await writeFile(temporary, document.toString({ flowCollectionPadding: false }), {
45
45
  encoding: 'utf8',
46
46
  flag: 'wx',
47
+ mode: 0o600,
47
48
  });
48
49
  await rename(temporary, path);
49
50
  }
@@ -71,7 +72,10 @@ export async function deleteConfigValue(path, keyPath) {
71
72
  document.deleteIn(keyPath);
72
73
  const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
73
74
  try {
74
- await writeFile(temporary, document.toString({ flowCollectionPadding: false }), { flag: 'wx' });
75
+ await writeFile(temporary, document.toString({ flowCollectionPadding: false }), {
76
+ flag: 'wx',
77
+ mode: 0o600,
78
+ });
75
79
  await rename(temporary, path);
76
80
  }
77
81
  catch (error) {