@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
@@ -1,4 +1,5 @@
1
1
  import type { Bot } from '../bot.ts';
2
+ import type { CapabilityRequirements } from '../capabilities.ts';
2
3
  import type { BaseEvent } from '../event/index.ts';
3
4
  /** 插件面板页面的标题、图标、静态目录和可选入口文件。 */
4
5
  export interface PanelPageOptions {
@@ -13,11 +14,23 @@ export interface PanelPage {
13
14
  root: string;
14
15
  entry: string;
15
16
  }
17
+ /** 由框架绑定的服务使用方;事件信息只在该插件的分发处理期间可用。 */
18
+ export interface ServiceConsumer {
19
+ readonly plugin: string;
20
+ readonly signal: AbortSignal;
21
+ event(): {
22
+ eventId: string;
23
+ platform: string;
24
+ selfId: string;
25
+ } | undefined;
26
+ }
16
27
  /** 插件的来源、运行状态、依赖服务及可选错误信息。 */
17
28
  export interface PluginState {
18
29
  name: string;
19
30
  version?: string;
20
31
  description?: string;
32
+ iconUrl?: string;
33
+ depends?: string[];
21
34
  source: 'builtin' | 'file' | 'package';
22
35
  path?: string;
23
36
  state: 'loading' | 'active' | 'failed' | 'disabled';
@@ -29,6 +42,7 @@ export interface PluginState {
29
42
  optional: boolean;
30
43
  }[];
31
44
  configSchema?: Record<string, unknown>;
45
+ capabilities?: CapabilityRequirements;
32
46
  }
33
47
  /** 插件状态变化事件;机器人可能尚未上线,bot 因而可缺省。 */
34
48
  export interface PluginStateEvent extends Omit<BaseEvent, 'bot'> {
@@ -1,10 +1,15 @@
1
1
  import { scheduleTimeout } from './dispatch/timer.js';
2
+ import { formatTarget } from './target.js';
2
3
  export class RateLimiter {
3
4
  entries = new Map();
4
5
  check(command, session, duration, scope) {
5
6
  if (session.isSuperuser || duration === 0)
6
7
  return null;
7
- const key = scope === 'user' ? `${session.platform}:${session.userId}` : scope === 'group' ? session.channelKey : '';
8
+ const key = scope === 'user'
9
+ ? `${session.platform}:${session.userId}`
10
+ : scope === 'group'
11
+ ? formatTarget({ ...session.target, thread: undefined })
12
+ : '';
8
13
  let bucket = this.entries.get(command);
9
14
  if (bucket === undefined) {
10
15
  bucket = { values: new Map() };
@@ -17,6 +17,7 @@ export interface GroupRuleSummary {
17
17
  configs: number;
18
18
  commands: number;
19
19
  }
20
+ type Migration = string | ((db: DatabaseSync) => void);
20
21
  /** SQLite 存储及插件状态、迁移和访问控制管理器。 */
21
22
  export declare class Storage {
22
23
  private database?;
@@ -35,7 +36,7 @@ export declare class Storage {
35
36
  get db(): DatabaseSync;
36
37
  open(): void;
37
38
  close(): void;
38
- migrate(owner: string, steps: string[]): void;
39
+ migrate(owner: string, steps: Migration[]): void;
39
40
  store(owner: string, assertActive?: () => void): KVStore;
40
41
  setGroupEnabled(owner: string, groupKey: string, enabled: boolean): void;
41
42
  isGroupEnabled(owner: string, groupKey: string): boolean;
@@ -68,3 +69,4 @@ export declare class KVStore {
68
69
  delete(key: string): void;
69
70
  keys(prefix?: string): string[];
70
71
  }
72
+ export {};
@@ -16,6 +16,47 @@ const coreMigrations = [
16
16
  PRIMARY KEY (plugin, group_key));
17
17
  CREATE TABLE command_group_state (command TEXT NOT NULL, group_key TEXT NOT NULL, enabled INTEGER NOT NULL,
18
18
  PRIMARY KEY (command, group_key));`,
19
+ `CREATE TABLE tasks (
20
+ id TEXT PRIMARY KEY, plugin TEXT NOT NULL, name TEXT NOT NULL, key TEXT NOT NULL,
21
+ payload TEXT NOT NULL, state TEXT NOT NULL, run_at INTEGER NOT NULL, next_run_at INTEGER NOT NULL,
22
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER,
23
+ attempt INTEGER NOT NULL DEFAULT 0, failures INTEGER NOT NULL DEFAULT 0,
24
+ policy TEXT NOT NULL, error TEXT, cancel_reason TEXT
25
+ );
26
+ CREATE INDEX tasks_due ON tasks(state, next_run_at);
27
+ CREATE INDEX tasks_key ON tasks(plugin, name, key, created_at DESC);
28
+ CREATE TABLE task_attempts (
29
+ id TEXT PRIMARY KEY, task_id TEXT NOT NULL, plugin TEXT NOT NULL, attempt INTEGER NOT NULL,
30
+ started_at INTEGER NOT NULL, finished_at INTEGER, outcome TEXT NOT NULL, error TEXT,
31
+ UNIQUE(task_id, attempt)
32
+ );
33
+ CREATE INDEX task_attempts_task ON task_attempts(task_id, attempt);
34
+ INSERT INTO tasks (id, plugin, name, key, payload, state, run_at, next_run_at, created_at, updated_at, policy)
35
+ SELECT lower(hex(randomblob(16))), plugin, name, key, payload, 'pending', run_at, run_at,
36
+ CAST(unixepoch('subsec') * 1000 AS INTEGER), CAST(unixepoch('subsec') * 1000 AS INTEGER),
37
+ '{"maxRetries":0,"delay":5000,"maxDelay":300000}' FROM scheduled_tasks;
38
+ DROP TABLE scheduled_tasks;`,
39
+ `CREATE TABLE bot_admins (bot_key TEXT NOT NULL, user_id TEXT NOT NULL, PRIMARY KEY (bot_key, user_id));
40
+ CREATE TABLE plugin_bot_policy (bot_key TEXT NOT NULL, plugin TEXT NOT NULL, enabled INTEGER, config TEXT, PRIMARY KEY (bot_key, plugin));`,
41
+ (db) => {
42
+ // NULL marks previously known accounts whose old defaults are captured once plugins are discovered.
43
+ db.exec(`CREATE TABLE bot_plugin_defaults (bot_key TEXT NOT NULL PRIMARY KEY, plugins TEXT);
44
+ INSERT INTO bot_plugin_defaults (bot_key)
45
+ SELECT bot_key FROM bot_admins UNION SELECT bot_key FROM plugin_bot_policy;`);
46
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'p_history_messages'").get()) {
47
+ db.exec(`INSERT OR IGNORE INTO bot_plugin_defaults (bot_key)
48
+ SELECT DISTINCT json_array(platform, self_id) FROM p_history_messages WHERE platform <> 'virtual'`);
49
+ }
50
+ },
51
+ `CREATE TABLE bot_accounts (
52
+ bot_key TEXT PRIMARY KEY, nickname TEXT, avatar TEXT, capabilities TEXT,
53
+ connection TEXT, connection_id TEXT, binding_key TEXT, last_online_at INTEGER
54
+ );
55
+ CREATE INDEX bot_accounts_connection ON bot_accounts(connection_id);
56
+ INSERT INTO bot_accounts (bot_key)
57
+ SELECT bot_key FROM bot_plugin_defaults WHERE json_extract(bot_key, '$[0]') <> 'virtual';`,
58
+ `ALTER TABLE tasks ADD COLUMN delivery_failure TEXT;
59
+ ALTER TABLE task_attempts ADD COLUMN delivery_failure TEXT;`,
19
60
  ];
20
61
  /** SQLite 存储及插件状态、迁移和访问控制管理器。 */
21
62
  export class Storage {
@@ -121,7 +162,11 @@ export class Storage {
121
162
  const changes = [];
122
163
  for (let index = version; index < steps.length; index++) {
123
164
  const before = tables();
124
- db.exec(steps[index]);
165
+ const step = steps[index];
166
+ if (typeof step === 'string')
167
+ db.exec(step);
168
+ else
169
+ step(db);
125
170
  const after = tables();
126
171
  for (const name of before)
127
172
  if (!after.has(name))
@@ -239,10 +284,15 @@ export class Storage {
239
284
  'migrations',
240
285
  'plugin_group_state',
241
286
  'plugin_group_config',
242
- 'scheduled_tasks',
287
+ 'plugin_bot_policy',
288
+ 'task_attempts',
289
+ 'tasks',
243
290
  ]) {
244
291
  db.prepare(`DELETE FROM ${table} WHERE plugin = ?`).run(owner);
245
292
  }
293
+ db.prepare(`UPDATE bot_plugin_defaults
294
+ SET plugins = (SELECT json_group_array(value) FROM json_each(plugins) WHERE value <> ?)
295
+ WHERE EXISTS (SELECT 1 FROM json_each(plugins) WHERE value = ?)`).run(owner, owner);
246
296
  for (const row of db.prepare('SELECT table_name FROM plugin_tables WHERE plugin = ?').all(owner)) {
247
297
  const name = String(row.table_name);
248
298
  db.exec(`DROP TABLE IF EXISTS "${name.replaceAll('"', '""')}"`);
@@ -1,22 +1,40 @@
1
1
  import { z } from 'zod';
2
+ import type { MessageTarget } from './bot.ts';
2
3
  /** 主动发送目标,包含平台、会话类型、ID 和可选机器人账号。 */
3
- export interface Target {
4
+ export interface Target extends MessageTarget {
4
5
  platform: string;
5
6
  selfId?: string;
6
- type: 'group' | 'private';
7
- id: string;
8
7
  }
9
- /** 将 platform[:selfId]:type:id 字符串解析为发送目标;格式无效时抛错。 */
8
+ export declare const threadSchema: z.ZodObject<{
9
+ id: z.ZodString;
10
+ rootMessageId: z.ZodString;
11
+ }, z.core.$strip>;
12
+ export declare const messageTargetSchema: z.ZodObject<{
13
+ type: z.ZodEnum<{
14
+ group: "group";
15
+ private: "private";
16
+ }>;
17
+ id: z.ZodString;
18
+ thread: z.ZodOptional<z.ZodObject<{
19
+ id: z.ZodString;
20
+ rootMessageId: z.ZodString;
21
+ }, z.core.$strip>>;
22
+ }, z.core.$strip>;
23
+ /** 解析普通会话或话题的发送目标;格式无效时抛错。 */
10
24
  export declare function parseTarget(text: string): Target;
11
25
  /** 将发送目标格式化为字符串;目标无效时抛错。 */
12
26
  export declare function formatTarget(target: Target): string;
13
27
  /** 接受目标对象或字符串并转换为 Target 的 zod schema。 */
14
28
  export declare const targetSchema: z.ZodUnion<readonly [z.ZodObject<{
15
- platform: z.ZodString;
16
- selfId: z.ZodOptional<z.ZodString>;
17
29
  type: z.ZodEnum<{
18
30
  group: "group";
19
31
  private: "private";
20
32
  }>;
21
33
  id: z.ZodString;
34
+ thread: z.ZodOptional<z.ZodObject<{
35
+ id: z.ZodString;
36
+ rootMessageId: z.ZodString;
37
+ }, z.core.$strip>>;
38
+ platform: z.ZodString;
39
+ selfId: z.ZodOptional<z.ZodString>;
22
40
  }, z.core.$strip>, z.ZodPipe<z.ZodString, z.ZodTransform<Target, string>>]>;
@@ -1,5 +1,11 @@
1
1
  import { z } from 'zod';
2
- const targetObjectSchema = z.object({
2
+ export const threadSchema = z.object({ id: z.string().min(1), rootMessageId: z.string().min(1) });
3
+ export const messageTargetSchema = z.object({
4
+ type: z.enum(['group', 'private']),
5
+ id: z.string().min(1),
6
+ thread: threadSchema.optional(),
7
+ });
8
+ const targetObjectSchema = messageTargetSchema.extend({
3
9
  platform: z
4
10
  .string()
5
11
  .min(1)
@@ -9,16 +15,25 @@ const targetObjectSchema = z.object({
9
15
  .min(1)
10
16
  .regex(/^[^:]+$/)
11
17
  .optional(),
12
- type: z.enum(['group', 'private']),
13
- id: z.string().min(1),
14
18
  });
15
- /** 将 platform[:selfId]:type:id 字符串解析为发送目标;格式无效时抛错。 */
19
+ const targetKinds = new Set(['group', 'private', 'group-thread', 'private-thread']);
20
+ /** 解析普通会话或话题的发送目标;格式无效时抛错。 */
16
21
  export function parseTarget(text) {
17
22
  const parts = text.split(':');
18
23
  const platform = parts.shift();
19
24
  const second = parts.shift();
20
- const selfId = second === 'group' || second === 'private' ? undefined : second;
25
+ const selfId = second !== undefined && targetKinds.has(second) ? undefined : second;
21
26
  const type = selfId === undefined ? second : parts.shift();
27
+ if (type === 'group-thread' || type === 'private-thread') {
28
+ const [id, threadId, rootMessageId] = z.tuple([z.string(), z.string(), z.string()]).parse(parts);
29
+ return targetObjectSchema.parse({
30
+ platform,
31
+ selfId,
32
+ type: type === 'group-thread' ? 'group' : 'private',
33
+ id: decodeURIComponent(id),
34
+ thread: { id: decodeURIComponent(threadId), rootMessageId: decodeURIComponent(rootMessageId) },
35
+ });
36
+ }
22
37
  return targetObjectSchema.parse({
23
38
  platform,
24
39
  ...(selfId === undefined ? {} : { selfId }),
@@ -29,7 +44,12 @@ export function parseTarget(text) {
29
44
  /** 将发送目标格式化为字符串;目标无效时抛错。 */
30
45
  export function formatTarget(target) {
31
46
  const value = targetObjectSchema.parse(target);
32
- return [value.platform, ...(value.selfId === undefined ? [] : [value.selfId]), value.type, value.id].join(':');
47
+ const bot = value.selfId === undefined ? value.platform : `${value.platform}:${value.selfId}`;
48
+ const thread = value.thread;
49
+ if (!thread)
50
+ return `${bot}:${value.type}:${value.id}`;
51
+ const ids = [value.id, thread.id, thread.rootMessageId].map(encodeURIComponent);
52
+ return [bot, `${value.type}-thread`, ...ids].join(':');
33
53
  }
34
54
  /** 接受目标对象或字符串并转换为 Target 的 zod schema。 */
35
55
  export const targetSchema = z.union([
@@ -0,0 +1,3 @@
1
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
2
+ /** 配置对象递归合并;数组和普通值整体覆盖。 */
3
+ export declare function mergeConfig(base: unknown, override: unknown): unknown;
@@ -0,0 +1,18 @@
1
+ export function isObject(value) {
2
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
3
+ }
4
+ /** 配置对象递归合并;数组和普通值整体覆盖。 */
5
+ export function mergeConfig(base, override) {
6
+ if (!isObject(override))
7
+ return override;
8
+ const result = isObject(base) ? { ...base } : {};
9
+ for (const [key, value] of Object.entries(override)) {
10
+ Object.defineProperty(result, key, {
11
+ value: mergeConfig(result[key], value),
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ });
16
+ }
17
+ return result;
18
+ }
@@ -0,0 +1,6 @@
1
+ /** Redact credentials in free-form external error messages. */
2
+ export declare function redactText(value: string, config?: unknown): string;
3
+ /** Respect third-party schema writeOnly fields even when their names are not conventional secret keys. */
4
+ export declare function redactSchemaText(text: string, config: unknown, schema: unknown): string;
5
+ /** Mask structured payloads before returning them through administrative APIs. */
6
+ export declare function redactValue(value: unknown, config?: unknown, key?: string): unknown;
@@ -0,0 +1,76 @@
1
+ const sensitiveKey = /token|password|secret|authorization|credential|api[_-]?key|private[_-]?key|^_auth$/i;
2
+ function secretsIn(value, key = '') {
3
+ if (typeof value === 'string')
4
+ return sensitiveKey.test(key) && value ? [value] : [];
5
+ if (Array.isArray(value))
6
+ return value.flatMap((item) => secretsIn(item));
7
+ if (value !== null && typeof value === 'object')
8
+ return Object.entries(value).flatMap(([name, item]) => secretsIn(item, name));
9
+ return [];
10
+ }
11
+ /** Redact credentials in free-form external error messages. */
12
+ export function redactText(value, config) {
13
+ let result = value
14
+ .replace(/(\b(?:[\w-]*(?:token|password|secret)|authorization|credential|api[_-]?key|private[_-]?key|_auth)\b["']?\s*[=:]\s*["']?)(?:bearer\s+)?[^\s,"';}]+/gi, '$1[Redacted]')
15
+ .replace(/\bBearer\s+[A-Za-z\d._~+/-]+=*/gi, 'Bearer [Redacted]')
16
+ .replace(/(https?:\/\/)[^\s/@]+(?::[^\s/@]*)?@/gi, '$1[Redacted]@');
17
+ const secrets = [
18
+ ...secretsIn(config),
19
+ ...Object.entries(process.env).flatMap(([key, secret]) => sensitiveKey.test(key) && secret && secret.length >= 4 ? [secret] : []),
20
+ ];
21
+ for (const secret of secrets.sort((a, b) => b.length - a.length))
22
+ result = result.replaceAll(secret, '[Redacted]');
23
+ return result;
24
+ }
25
+ /** Respect third-party schema writeOnly fields even when their names are not conventional secret keys. */
26
+ export function redactSchemaText(text, config, schema) {
27
+ const record = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
28
+ const secrets = new Set();
29
+ const collect = (value) => {
30
+ if (typeof value === 'string' && value)
31
+ secrets.add(value);
32
+ else if (Array.isArray(value))
33
+ value.forEach(collect);
34
+ else if (record(value))
35
+ Object.values(value).forEach(collect);
36
+ };
37
+ const walk = (value, node) => {
38
+ if (!record(node))
39
+ return;
40
+ if (node.writeOnly === true)
41
+ collect(value);
42
+ if (typeof node.$ref === 'string' && node.$ref.startsWith('#/')) {
43
+ let target = schema;
44
+ for (const key of node.$ref.slice(2).split('/'))
45
+ target = record(target) ? target[key.replaceAll('~1', '/').replaceAll('~0', '~')] : undefined;
46
+ walk(value, target);
47
+ }
48
+ for (const kind of ['anyOf', 'oneOf', 'allOf'])
49
+ if (Array.isArray(node[kind]))
50
+ for (const child of node[kind])
51
+ walk(value, child);
52
+ if (Array.isArray(value))
53
+ for (const item of value)
54
+ walk(item, node.items);
55
+ if (record(value) && record(node.properties))
56
+ for (const [key, child] of Object.entries(node.properties))
57
+ walk(value[key], child);
58
+ };
59
+ walk(config, schema);
60
+ let result = redactText(text, config);
61
+ for (const value of [...secrets].sort((a, b) => b.length - a.length))
62
+ result = result.replaceAll(value, '[Redacted]');
63
+ return result;
64
+ }
65
+ /** Mask structured payloads before returning them through administrative APIs. */
66
+ export function redactValue(value, config, key = '') {
67
+ if (sensitiveKey.test(key))
68
+ return '[Redacted]';
69
+ if (typeof value === 'string')
70
+ return redactText(value, config);
71
+ if (Array.isArray(value))
72
+ return value.map((item) => redactValue(item, config));
73
+ if (value !== null && typeof value === 'object')
74
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, redactValue(item, config, name)]));
75
+ return value;
76
+ }
package/dist/index.d.ts CHANGED
@@ -4,10 +4,13 @@ export { z } from 'zod';
4
4
  export interface Services extends Record<never, never> {
5
5
  }
6
6
  export { createApp } from './bootstrap.ts';
7
- export type { Adapter, AdapterHost, BeforeSend, BotInfo, Delivery, OutgoingMessage, PreparedOutgoing, UpgradeHandler, } from './core/adapter.ts';
7
+ export type { Adapter, AdapterDefinition, AdapterHost, BeforeSend, BotInfo, Delivery, OutgoingMessage, PreparedOutgoing, QrConnectionSetup, QrSetupChallenge, QrSetupUpdate, UpgradeHandler, } from './core/adapter.ts';
8
+ export { defineAdapter } from './core/adapter.ts';
8
9
  export { App } from './core/app.ts';
9
- export type { Bot, BotCapabilities, ForwardMessage, ForwardNode, GroupInfo, GroupMemberInfo, MessageInfo, MessageTarget, SendResult, UserInfo, } from './core/bot.ts';
10
- export { BotRegistry, supports } from './core/bot.ts';
10
+ export type { Bot, BotCapabilities, ForwardMessage, ForwardNode, GroupInfo, GroupMemberInfo, MessageInfo, MessageTarget, MessageThread, SendResult, ThreadTarget, UserInfo, } from './core/bot.ts';
11
+ export { BotRegistry, sendTo, supports } from './core/bot.ts';
12
+ export type { CapabilityGap, CapabilityRequirements, Compatibility } from './core/capabilities.ts';
13
+ export { compatibility } from './core/capabilities.ts';
11
14
  export type { CommandDefinition, OptionDefinition, OptionSettings } from './core/command/builder.ts';
12
15
  export { CommandBuilder } from './core/command/builder.ts';
13
16
  export type { ArgumentSettings, ArgumentType } from './core/command/declaration.ts';
@@ -16,14 +19,18 @@ export type { CommandAction, CommandArgs, CommandContext, OptionValue } from './
16
19
  export { interpolateConfigValues, loadConfig } from './core/config/load.ts';
17
20
  export { type CommandOverride, type Config, commandOverrideSchema, configSchema, } from './core/config/schema.ts';
18
21
  export { writeConfigValue } from './core/config/write.ts';
22
+ export type { ConnectionConfig, ConnectionState } from './core/connections.ts';
23
+ export { type DeliveryCode, DeliveryError, type DeliveryFailure, type DeliveryOutcome, } from './core/delivery.ts';
19
24
  export type { ApiCall, ApiInterceptor } from './core/dispatch/api.ts';
20
25
  export { Dispatcher } from './core/dispatch/dispatcher.ts';
21
26
  export type { DispatchTrace, TraceStep } from './core/dispatch/trace.ts';
22
27
  export type { AccessFilter, DispatchEvent, Disposer, EnabledFilter, MatchHandler, MatchPattern, Middleware, Scope, } from './core/dispatch/types.ts';
23
28
  export { groupKeyOf } from './core/dispatch/types.ts';
24
- export { ApiTimeoutError, CommandConflictError, ConfigError, NoBotOnlineError, NotConnectedError, PluginConfigError, PluginError, SendBlockedError, SendQueueFullError, UnsupportedError, } from './core/errors.ts';
29
+ export { ApiTimeoutError, CommandConflictError, ConfigError, NoBotOnlineError, NotConnectedError, PluginConfigError, PluginError, QrSetupError, SendBlockedError, SendQueueFullError, UnsupportedError, } from './core/errors.ts';
25
30
  export type { AnyEvent, BaseEvent, BotOfflineEvent, BotOnlineEvent, DialogueOptions, DispatchTraceEvent, EventMap, FriendRequestEvent, GroupInviteRequestEvent, GroupJoinRequestEvent, GroupRequestEvent, GroupSession, KnownNoticeEvent, MemberJoinEvent, MemberLeaveEvent, MemberMuteEvent, MemberNoticeEvent, MemberRoleEvent, MemberUnmuteEvent, MessageRecallEvent, MessageSentEvent, MetaEvent, NoticeEvent, PlatformNoticeEvent, PokeEvent, PrivateSession, PromptOptions, RequestEvent, Session, SessionServices, } from './core/event/index.ts';
26
31
  export { createSession, stripLeadingMention } from './core/event/index.ts';
32
+ export type { ActorIdentity, BotIdentity } from './core/identity.ts';
33
+ export { actorIdentitySchema, botIdentitySchema, botKey } from './core/identity.ts';
27
34
  export { createLogger, getRecentLogs, type LogLevel, type LogRecord, type LogSubscriber, logger, subscribeLogs, } from './core/logger.ts';
28
35
  export type { KnownSegment, Message, Segment, Sendable, TextStyle, UnknownSegment, } from './core/message/index.ts';
29
36
  export { isSegment, normalizeSendable, plainText, seg, } from './core/message/index.ts';
@@ -32,8 +39,9 @@ export { perm } from './core/permission.ts';
32
39
  export { Context, type FilteredContext } from './core/plugin/context.ts';
33
40
  export { definePlugin, type PluginDefinition } from './core/plugin/definition.ts';
34
41
  export { PluginManager } from './core/plugin/manager.ts';
35
- export type { TaskHandle, TaskHandler, TaskOptions } from './core/plugin/tasks.ts';
36
- export type { PanelPageOptions, PluginState, PluginStateEvent } from './core/plugin/types.ts';
42
+ export type { TaskAttempt, TaskHandle, TaskHandler, TaskOptions, TaskOutcome, TaskPolicy, TaskQuery, TaskRecord, TaskRegistrationOptions, TaskState, } from './core/plugin/tasks.ts';
43
+ export { TaskConflictError } from './core/plugin/tasks.ts';
44
+ export type { PanelPageOptions, PluginState, PluginStateEvent, ServiceConsumer } from './core/plugin/types.ts';
37
45
  export type { CooldownScope } from './core/ratelimit.ts';
38
46
  export { type AccessEntry, type AccessList, type AccessSubject, KVStore, Storage, } from './core/storage/index.ts';
39
47
  export { formatTarget, parseTarget, type Target, targetSchema } from './core/target.ts';
package/dist/index.js CHANGED
@@ -1,23 +1,28 @@
1
1
  /** 框架共用的 zod schema 构造器。 */
2
2
  export { z } from 'zod';
3
3
  export { createApp } from './bootstrap.js';
4
+ export { defineAdapter } from './core/adapter.js';
4
5
  export { App } from './core/app.js';
5
- export { BotRegistry, supports } from './core/bot.js';
6
+ export { BotRegistry, sendTo, supports } from './core/bot.js';
7
+ export { compatibility } from './core/capabilities.js';
6
8
  export { CommandBuilder } from './core/command/builder.js';
7
9
  export { formatUsage } from './core/command/parse.js';
8
10
  export { interpolateConfigValues, loadConfig } from './core/config/load.js';
9
11
  export { commandOverrideSchema, configSchema, } from './core/config/schema.js';
10
12
  export { writeConfigValue } from './core/config/write.js';
13
+ export { DeliveryError, } from './core/delivery.js';
11
14
  export { Dispatcher } from './core/dispatch/dispatcher.js';
12
15
  export { groupKeyOf } from './core/dispatch/types.js';
13
- export { ApiTimeoutError, CommandConflictError, ConfigError, NoBotOnlineError, NotConnectedError, PluginConfigError, PluginError, SendBlockedError, SendQueueFullError, UnsupportedError, } from './core/errors.js';
16
+ export { ApiTimeoutError, CommandConflictError, ConfigError, NoBotOnlineError, NotConnectedError, PluginConfigError, PluginError, QrSetupError, SendBlockedError, SendQueueFullError, UnsupportedError, } from './core/errors.js';
14
17
  export { createSession, stripLeadingMention } from './core/event/index.js';
18
+ export { actorIdentitySchema, botIdentitySchema, botKey } from './core/identity.js';
15
19
  export { createLogger, getRecentLogs, logger, subscribeLogs, } from './core/logger.js';
16
20
  export { isSegment, normalizeSendable, plainText, seg, } from './core/message/index.js';
17
21
  export { perm } from './core/permission.js';
18
22
  export { Context } from './core/plugin/context.js';
19
23
  export { definePlugin } from './core/plugin/definition.js';
20
24
  export { PluginManager } from './core/plugin/manager.js';
25
+ export { TaskConflictError } from './core/plugin/tasks.js';
21
26
  export { KVStore, Storage, } from './core/storage/index.js';
22
27
  export { formatTarget, parseTarget, targetSchema } from './core/target.js';
23
28
  export { parseDuration } from './core/utils/duration.js';
@@ -1,3 +1,4 @@
1
+ import { groupKeyOf } from '../core/dispatch/types.js';
1
2
  import { isSegment, plainText } from '../core/message/index.js';
2
3
  import { definePlugin } from '../core/plugin/definition.js';
3
4
  function reason(error) {
@@ -59,7 +60,9 @@ export function createAdminPlugin(app) {
59
60
  });
60
61
  }
61
62
  function changeAccess(list, subject, id, session) {
62
- if (list === 'block' && subject === 'user' && app.isSuperuser(id))
63
+ if (list === 'block' &&
64
+ subject === 'user' &&
65
+ app.isSuperuser({ platform: session.platform, selfId: session.selfId, userId: id }))
63
66
  return '不能屏蔽超管';
64
67
  const key = `${session.platform}:${id}`;
65
68
  try {
@@ -73,8 +76,19 @@ export function createAdminPlugin(app) {
73
76
  return definePlugin({
74
77
  name: 'admin',
75
78
  description: '管理插件与访问控制',
79
+ defaultOnNewBots: true,
76
80
  setup(ctx) {
77
81
  const log = ctx.logger;
82
+ ctx
83
+ .command('whoami')
84
+ .description('查看自己的用户 ID 和管理权限')
85
+ .action(({ session }) => [
86
+ `平台:${session.platform}`,
87
+ `机器人 ID:${session.selfId}`,
88
+ `用户 ID:${session.userId}`,
89
+ `机器人管理员:${session.isBotAdmin ? '是' : '否'}`,
90
+ `框架管理员:${session.isSuperuser ? '是' : '否'}`,
91
+ ].join('\n'));
78
92
  ctx
79
93
  .command('plugin scan')
80
94
  .description('重新扫描插件目录')
@@ -194,7 +208,7 @@ export function createAdminPlugin(app) {
194
208
  if (!enabled && args.name === 'admin')
195
209
  return '不能在群里关闭 admin 插件';
196
210
  try {
197
- app.plugins.setGroupEnabled(args.name, `${session.platform}:${session.groupId}`, enabled);
211
+ app.plugins.setGroupEnabled(args.name, groupKeyOf({ ...session, groupId: session.groupId }), enabled);
198
212
  return `已在本群${enabled ? '开启' : '关闭'}插件 ${args.name}`;
199
213
  }
200
214
  catch (error) {
@@ -202,6 +216,18 @@ export function createAdminPlugin(app) {
202
216
  }
203
217
  });
204
218
  }
219
+ for (const enabled of [true, false]) {
220
+ ctx
221
+ .command(`bot plugin ${enabled ? 'on' : 'off'} <name>`)
222
+ .description(`${enabled ? '开启' : '关闭'}当前机器人的插件`)
223
+ .permission('bot.admin')
224
+ .action(({ session, args }) => {
225
+ if (!enabled && args.name === 'admin')
226
+ return '不能在聊天中关闭 admin 插件';
227
+ app.plugins.setBotEnabled(args.name, session, enabled);
228
+ return `已在本机器人${enabled ? '开启' : '关闭'}插件 ${args.name}`;
229
+ });
230
+ }
205
231
  ctx
206
232
  .command('acl list')
207
233
  .description('查看访问控制列表')
@@ -247,7 +273,8 @@ export function createAdminPlugin(app) {
247
273
  if (args.subject !== 'user' && args.subject !== 'group')
248
274
  return '对象类型必须是 user 或 group';
249
275
  try {
250
- const key = `${session.platform}:${targetFromRest(args.subject, args.target, session)}`;
276
+ const id = targetFromRest(args.subject, args.target, session);
277
+ const key = `${session.platform}:${id}`;
251
278
  const found = app.storage.access.list(args.list, args.subject).some((entry) => entry.key === key);
252
279
  if (!found)
253
280
  return `没有找到 ${args.list} ${args.subject} ${key}`;
@@ -18,6 +18,7 @@ export function createHelpPlugin(app) {
18
18
  return definePlugin({
19
19
  name: 'help',
20
20
  description: '查看当前会话可用的命令',
21
+ defaultOnNewBots: true,
21
22
  setup(ctx) {
22
23
  ctx
23
24
  .command('help [path:rest]')
@@ -1,7 +1,9 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import { z } from 'zod';
3
+ import type { MessageThread } from '../core/bot.ts';
3
4
  import type { DispatchTrace } from '../core/dispatch/trace.ts';
4
5
  import type { Message } from '../core/message/index.ts';
6
+ import { type Target } from '../core/target.ts';
5
7
  /** 历史记录中的收发消息、会话及可选关联事件。 */
6
8
  export interface HistoryMessage {
7
9
  id: number;
@@ -10,6 +12,7 @@ export interface HistoryMessage {
10
12
  platform: string;
11
13
  selfId: string;
12
14
  channel: string;
15
+ target: Target;
13
16
  userId?: string;
14
17
  nickname?: string;
15
18
  messageId?: string;
@@ -24,6 +27,7 @@ export interface HistoryChannel {
24
27
  selfId: string;
25
28
  type: 'group' | 'private';
26
29
  id: string;
30
+ thread?: MessageThread;
27
31
  count: number;
28
32
  last: HistoryMessage;
29
33
  }
@@ -5,13 +5,15 @@ import { plainText } from '../core/message/index.js';
5
5
  import { definePlugin } from '../core/plugin/definition.js';
6
6
  import { formatTarget, parseTarget } from '../core/target.js';
7
7
  function historyMessage(row) {
8
+ const channel = String(row.channel);
8
9
  return {
9
10
  id: Number(row.id),
10
11
  ...(row.event_id === null ? {} : { eventId: String(row.event_id) }),
11
12
  direction: row.direction,
12
13
  platform: String(row.platform),
13
14
  selfId: String(row.self_id),
14
- channel: String(row.channel),
15
+ channel,
16
+ target: parseTarget(channel),
15
17
  ...(row.user_id === null ? {} : { userId: String(row.user_id) }),
16
18
  ...(row.nickname === null ? {} : { nickname: String(row.nickname) }),
17
19
  ...(row.message_id === null ? {} : { messageId: String(row.message_id) }),
@@ -73,6 +75,7 @@ export function cleanHistory(db, retention, maxMessages, now = Date.now()) {
73
75
  export default definePlugin({
74
76
  name: 'history',
75
77
  description: '记录消息和分发追踪',
78
+ defaultOnNewBots: true,
76
79
  config: z.object({
77
80
  retention: durationSchema.default(7 * 86_400_000),
78
81
  maxMessages: z.number().int().nonnegative().default(100_000),
@@ -106,7 +109,13 @@ export default definePlugin({
106
109
  const id = event.messageType === 'group' ? event.groupId : event.userId;
107
110
  if (id === undefined)
108
111
  throw new Error('Sent message has no target');
109
- insert.run(event.eventId ?? null, 'out', event.platform, event.selfId, formatTarget({ platform: event.platform, selfId: event.selfId, type: event.messageType, id }), event.selfId, event.bot.nickname ?? null, event.messageId, messageJson(event.message), redactBase64(plainText(event.message)), event.time);
112
+ insert.run(event.eventId ?? null, 'out', event.platform, event.selfId, formatTarget({
113
+ platform: event.platform,
114
+ selfId: event.selfId,
115
+ type: event.messageType,
116
+ id,
117
+ thread: event.thread,
118
+ }), event.selfId, event.bot.nickname ?? null, event.messageId, messageJson(event.message), redactBase64(plainText(event.message)), event.time);
110
119
  });
111
120
  ctx.on('dispatch.trace', ({ trace }) => {
112
121
  if (ignored(trace.platform))
@@ -135,13 +144,14 @@ export default definePlugin({
135
144
  .all();
136
145
  const channels = rows.map((row) => {
137
146
  const last = historyMessage(row);
138
- const target = parseTarget(last.channel);
147
+ const { target } = last;
139
148
  return {
140
149
  channel: last.channel,
141
150
  platform: last.platform,
142
151
  selfId: last.selfId,
143
152
  type: target.type,
144
153
  id: target.id,
154
+ ...(target.thread === undefined ? {} : { thread: target.thread }),
145
155
  count: Number(row.channel_count),
146
156
  last,
147
157
  };
@@ -29,6 +29,7 @@ function bypassProxy(hostname, patterns) {
29
29
  export default definePlugin({
30
30
  name: 'http',
31
31
  description: 'HTTP 请求、代理和响应大小限制',
32
+ defaultOnNewBots: true,
32
33
  config: z.object({
33
34
  proxy: z.string().default(''),
34
35
  noProxy: z.array(z.string()).default([]),