@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
@@ -3,10 +3,16 @@ import { watch } from 'node:fs';
3
3
  import { lstat, mkdir, mkdtemp, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
4
4
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { z } from 'zod';
6
+ import { requirementsSchema } from '../capabilities.js';
6
7
  import { deleteConfigValue, writeConfigValue } from '../config/write.js';
8
+ import { groupKeyOf } from '../dispatch/types.js';
7
9
  import { PluginConfigError, PluginError } from '../errors.js';
10
+ import { groupIdentity } from '../identity.js';
11
+ import { mergeConfig } from '../utils/merge.js';
8
12
  import { Context } from './context.js';
9
13
  import { serviceDependencies } from './definition.js';
14
+ import { pluginExecution } from './execution.js';
15
+ import { parsePluginIconUrl, pluginIconFromKeywords } from './icon.js';
10
16
  import { importPlugin, registerPluginRoots } from './loader.js';
11
17
  import { PackageService, redact } from './packages.js';
12
18
  import { ManagementError, uploadContents } from './upload.js';
@@ -27,6 +33,10 @@ function validateDefinition(value) {
27
33
  typeof value.setup !== 'function') {
28
34
  throw new PluginError('Plugin must default-export a definition with a valid name and setup function');
29
35
  }
36
+ if ('defaultOnNewBots' in value &&
37
+ value.defaultOnNewBots !== undefined &&
38
+ typeof value.defaultOnNewBots !== 'boolean')
39
+ throw new PluginError(`Invalid new bot default for plugin "${value.name}"`);
30
40
  if ('depends' in value &&
31
41
  value.depends !== undefined &&
32
42
  (!Array.isArray(value.depends) || !value.depends.every((item) => typeof item === 'string'))) {
@@ -43,6 +53,10 @@ function validateDefinition(value) {
43
53
  throw new PluginError(`Invalid service dependencies for plugin "${value.name}"`);
44
54
  }
45
55
  }
56
+ if ('capabilities' in value &&
57
+ value.capabilities !== undefined &&
58
+ !requirementsSchema.safeParse(value.capabilities).success)
59
+ throw new PluginError(`Invalid capability requirements for plugin "${value.name}"`);
46
60
  return value;
47
61
  }
48
62
  /** 管理插件注册、依赖协调、启停、重载和服务。 */
@@ -61,7 +75,6 @@ export class PluginManager {
61
75
  packageUpdateSubscribers = new Set();
62
76
  timers = new Map();
63
77
  groupConfigCache = new Map();
64
- groupConfigWarnings = new Set();
65
78
  releaseRoots;
66
79
  queue = Promise.resolve();
67
80
  started = false;
@@ -110,10 +123,22 @@ export class PluginManager {
110
123
  return state && { ...state };
111
124
  }
112
125
  provide(plugin, name, value) {
126
+ return this.registerService(name, { plugin, kind: 'shared', value });
127
+ }
128
+ provideScoped(plugin, name, factory) {
129
+ return this.registerService(name, { plugin, kind: 'scoped', factory, instances: new WeakMap() });
130
+ }
131
+ serviceConsumers(name) {
132
+ return [...this.entries.values()]
133
+ .filter(({ state }) => state.inject.some((item) => item.name === name))
134
+ .map(({ state }) => state.name)
135
+ .sort();
136
+ }
137
+ registerService(name, service) {
138
+ const { plugin } = service;
113
139
  const existing = this.services.get(name);
114
140
  if (existing)
115
141
  throw new PluginError(`服务 ${name} 冲突:插件 "${existing.plugin}" 已提供,插件 "${plugin}" 无法重复提供`);
116
- const service = { plugin, value };
117
142
  this.services.set(name, service);
118
143
  this.serviceProviders.set(name, plugin);
119
144
  const entry = this.require(plugin);
@@ -131,14 +156,24 @@ export class PluginManager {
131
156
  this.requestReconcile();
132
157
  };
133
158
  }
134
- inject(name) {
159
+ inject(name, consumer) {
135
160
  const service = this.services.get(name);
136
161
  if (!service)
137
162
  throw new PluginError(`服务 ${name} 不可用`);
138
- return service.value;
163
+ return this.serviceValue(name, service, consumer);
139
164
  }
140
- injectOptional(name) {
141
- return this.services.get(name)?.value;
165
+ injectOptional(name, consumer) {
166
+ const service = this.services.get(name);
167
+ return service && this.serviceValue(name, service, consumer);
168
+ }
169
+ serviceValue(name, service, consumer) {
170
+ if (service.kind === 'shared')
171
+ return service.value;
172
+ if (!consumer)
173
+ throw new PluginError(`服务 ${name} 必须在插件上下文中注入`);
174
+ if (!service.instances.has(consumer))
175
+ service.instances.set(consumer, service.factory(consumer));
176
+ return service.instances.get(consumer);
142
177
  }
143
178
  getConfig(name) {
144
179
  const entry = this.entries.get(name);
@@ -157,47 +192,91 @@ export class PluginManager {
157
192
  }
158
193
  setGroupConfig(name, groupKey, override) {
159
194
  const entry = this.requireAvailable(name);
160
- if (override !== null) {
161
- if (!entry.definition?.config)
162
- throw new PluginConfigError([
163
- { path: `plugins.${name}.config`, message: 'Plugin has no configuration schema' },
164
- ]);
165
- this.validateConfig(entry, {
166
- ...this.app.config.plugins[name]?.config,
167
- ...override,
168
- });
169
- }
195
+ const target = groupIdentity(groupKey);
196
+ this.requireConfig(entry);
197
+ this.validateConfig(entry, this.rawConfig(name, target, { group: override }));
170
198
  this.app.storage.setGroupConfig(name, groupKey, override);
171
- const key = JSON.stringify([name, groupKey]);
172
- this.groupConfigCache.delete(key);
173
- this.groupConfigWarnings.delete(key);
199
+ this.invalidateGroupConfigs(name);
174
200
  }
175
- configFor(name, groupKey) {
176
- const key = JSON.stringify([name, groupKey]);
201
+ setBotConfig(name, bot, override) {
202
+ const entry = this.requireAvailable(name);
203
+ this.requireConfig(entry);
204
+ this.validateConfig(entry, this.rawConfig(name, bot, { bot: override }));
205
+ for (const group of this.app.storage.listGroups(name)) {
206
+ const target = groupIdentity(group.groupKey);
207
+ if (target.platform === bot.platform && target.selfId === bot.selfId)
208
+ this.validateConfig(entry, this.rawConfig(name, target, { bot: override }));
209
+ }
210
+ this.app.policies.setPlugin(bot, name, {
211
+ ...this.app.policies.plugin(bot, name),
212
+ config: override ?? undefined,
213
+ });
214
+ this.invalidateGroupConfigs(name);
215
+ }
216
+ setBotEnabled(name, bot, enabled) {
217
+ this.requireAvailable(name);
218
+ this.app.policies.setPlugin(bot, name, {
219
+ ...this.app.policies.plugin(bot, name),
220
+ enabled: enabled ?? undefined,
221
+ });
222
+ }
223
+ requireConfig(entry) {
224
+ if (!entry.definition?.config)
225
+ throw new PluginConfigError([
226
+ { path: `plugins.${entry.state.name}.config`, message: 'Plugin has no configuration schema' },
227
+ ]);
228
+ }
229
+ rawConfig(name, target, changes = {}) {
230
+ const global = 'global' in changes ? changes.global : this.app.config.plugins[name]?.config;
231
+ const bot = 'bot' in changes ? changes.bot : this.app.policies.plugin(target, name).config;
232
+ const key = groupKeyOf(target);
233
+ const group = 'group' in changes
234
+ ? changes.group
235
+ : key === undefined
236
+ ? undefined
237
+ : this.app.storage.getGroupConfig(name, key);
238
+ return mergeConfig(mergeConfig(global ?? {}, bot ?? {}), group ?? {});
239
+ }
240
+ configFor(name, target) {
241
+ const destination = typeof target === 'string' ? groupIdentity(target) : target;
242
+ const key = JSON.stringify([name, destination.platform, destination.selfId, destination.groupId]);
177
243
  if (this.groupConfigCache.has(key))
178
244
  return this.groupConfigCache.get(key);
179
245
  const entry = this.requireAvailable(name);
180
- const override = this.app.storage.getGroupConfig(name, groupKey);
181
- let result = this.getConfig(name);
182
- if (override !== undefined) {
183
- try {
184
- result = this.validateConfig(entry, {
185
- ...this.app.config.plugins[name]?.config,
186
- ...override,
187
- });
188
- }
189
- catch (error) {
190
- if (!(error instanceof PluginConfigError))
191
- throw error;
192
- if (!this.groupConfigWarnings.has(key)) {
193
- this.groupConfigWarnings.add(key);
194
- this.app.logger.warn({ plugin: name, groupKey, issues: error.issues }, 'Group configuration invalid; using global configuration');
195
- }
196
- }
197
- }
246
+ const result = this.validateConfig(entry, this.rawConfig(name, destination));
198
247
  this.groupConfigCache.set(key, result);
199
248
  return result;
200
249
  }
250
+ configSources(name, target) {
251
+ const key = groupKeyOf(target);
252
+ const layers = [
253
+ ['global', this.app.config.plugins[name]?.config],
254
+ ['bot', this.app.policies.plugin(target, name).config],
255
+ ['group', key === undefined ? undefined : this.app.storage.getGroupConfig(name, key)],
256
+ ];
257
+ const sources = {};
258
+ const walk = (value, path) => {
259
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
260
+ for (const [key, item] of Object.entries(value))
261
+ walk(item, [...path, key]);
262
+ return;
263
+ }
264
+ let source = 'default';
265
+ for (const [name, config] of layers) {
266
+ let current = config;
267
+ for (const part of path)
268
+ current =
269
+ current !== null && typeof current === 'object' && Object.hasOwn(current, part)
270
+ ? current[part]
271
+ : undefined;
272
+ if (current !== undefined)
273
+ source = name;
274
+ }
275
+ sources[path.join('.')] = source;
276
+ };
277
+ walk(this.configFor(name, target), []);
278
+ return sources;
279
+ }
201
280
  invalidateGroupConfigs(name) {
202
281
  for (const key of this.groupConfigCache.keys()) {
203
282
  if (JSON.parse(key)[0] === name)
@@ -208,6 +287,10 @@ export class PluginManager {
208
287
  this.started = true;
209
288
  await this.packages.init();
210
289
  this.releaseRoots = registerPluginRoots([...this.dirs, this.packages.dir]);
290
+ for (const { definition } of this.entries.values()) {
291
+ if (definition)
292
+ await this.initializeDefaultOnNewBots(definition);
293
+ }
211
294
  for (const dir of this.dirs)
212
295
  await this.discover(dir);
213
296
  for (const name of Object.keys(await this.packages.dependencies())) {
@@ -230,6 +313,7 @@ export class PluginManager {
230
313
  pluginName = `${base}-${suffix++}`;
231
314
  const state = {
232
315
  name: pluginName,
316
+ iconUrl: pluginIconFromKeywords(manifest.keywords),
233
317
  source: 'package',
234
318
  state: 'failed',
235
319
  enabled: this.app.config.plugins[pluginName]?.enabled ?? true,
@@ -448,6 +532,12 @@ export class PluginManager {
448
532
  const manifest = this.entries.get(name)?.manifest;
449
533
  return manifest ? this.packages.info(manifest) : undefined;
450
534
  }
535
+ packageReadme(name) {
536
+ const manifest = this.entries.get(name)?.manifest;
537
+ if (!manifest)
538
+ throw new ManagementError(404, 'Plugin package is not installed');
539
+ return this.packages.installedReadme(manifest);
540
+ }
451
541
  subscribePackageUpdates(subscriber) {
452
542
  this.packageUpdateSubscribers.add(subscriber);
453
543
  return () => this.packageUpdateSubscribers.delete(subscriber);
@@ -456,21 +546,42 @@ export class PluginManager {
456
546
  return this.serial(async () => {
457
547
  const entry = this.requireAvailable(name);
458
548
  this.validateConfig(entry, value);
549
+ for (const bot of this.app.policies.configured(name))
550
+ this.validateConfig(entry, this.rawConfig(name, bot, { global: value }));
551
+ for (const group of this.app.storage.listGroups(name))
552
+ this.validateConfig(entry, this.rawConfig(name, groupIdentity(group.groupKey), { global: value }));
459
553
  await this.persist(name, 'config', value);
460
554
  this.entryConfig(name).config = value;
461
555
  this.invalidateGroupConfigs(name);
462
556
  await this.reloadEntry(entry);
463
557
  });
464
558
  }
559
+ setDefaultOnNewBots(name, enabled) {
560
+ return this.serial(async () => {
561
+ const entry = this.requireAvailable(name);
562
+ await this.persist(name, 'defaultOnNewBots', enabled);
563
+ this.entryConfig(name).defaultOnNewBots = enabled;
564
+ this.publishState(entry);
565
+ });
566
+ }
567
+ defaultsForNewBot() {
568
+ return [...this.entries.keys()].filter((name) => this.app.config.plugins[name]?.defaultOnNewBots);
569
+ }
465
570
  setGroupEnabled(name, groupKey, enabled) {
466
571
  this.requireAvailable(name);
467
572
  this.app.storage.setGroupEnabled(name, groupKey, enabled);
468
573
  }
574
+ isEnabledOnBot(name, bot) {
575
+ return (name === 'core' ||
576
+ (this.entries.get(name)?.state.enabled !== false &&
577
+ (this.app.policies.plugin(bot, name).enabled ?? this.app.policies.defaultPluginEnabled(bot, name))));
578
+ }
469
579
  isEnabledFor(name, event) {
470
580
  if (name === 'core')
471
581
  return true;
472
- const groupId = 'groupId' in event ? event.groupId : undefined;
473
- return groupId === undefined || this.app.storage.isGroupEnabled(name, `${event.platform}:${groupId}`);
582
+ const groupKey = groupKeyOf(event);
583
+ return (this.isEnabledOnBot(name, event) &&
584
+ (groupKey === undefined || this.app.storage.isGroupEnabled(name, groupKey)));
474
585
  }
475
586
  serial(work) {
476
587
  const result = this.queue.then(work);
@@ -504,6 +615,12 @@ export class PluginManager {
504
615
  this.app.config.plugins[name] ??= { enabled: true };
505
616
  return this.app.config.plugins[name];
506
617
  }
618
+ async initializeDefaultOnNewBots({ name, defaultOnNewBots = false }) {
619
+ if (this.app.config.plugins[name]?.defaultOnNewBots !== undefined)
620
+ return;
621
+ await this.persist(name, 'defaultOnNewBots', defaultOnNewBots);
622
+ this.entryConfig(name).defaultOnNewBots = defaultOnNewBots;
623
+ }
507
624
  async persist(name, field, value) {
508
625
  if (this.configPath) {
509
626
  await writeConfigValue(this.configPath, ['plugins', name, field], value, field === 'config' ? { previousValue: this.app.config.plugins[name]?.config } : undefined);
@@ -511,7 +628,7 @@ export class PluginManager {
511
628
  else
512
629
  this.app.logger.debug({ plugin: name, field }, 'Plugin configuration changed in memory only');
513
630
  }
514
- add(definition, source, path, files = new Set(), release) {
631
+ add(definition, source, path, files = new Set(), release, manifest) {
515
632
  const name = definition.name;
516
633
  const state = {
517
634
  name,
@@ -521,8 +638,9 @@ export class PluginManager {
521
638
  enabled: this.app.config.plugins[name]?.enabled ?? true,
522
639
  provides: [],
523
640
  inject: [],
641
+ capabilities: definition.capabilities,
524
642
  };
525
- const entry = { state, definition, files, release };
643
+ const entry = { state, definition, files, release, manifest };
526
644
  this.metadata(entry);
527
645
  if (this.entries.has(name)) {
528
646
  entry.failure = 'duplicate';
@@ -540,8 +658,13 @@ export class PluginManager {
540
658
  const definition = entry.definition;
541
659
  if (!definition)
542
660
  return;
661
+ entry.state.capabilities = definition.capabilities;
543
662
  entry.state.version = definition.version;
544
663
  entry.state.description = definition.description;
664
+ entry.state.iconUrl = entry.manifest
665
+ ? pluginIconFromKeywords(entry.manifest.keywords)
666
+ : parsePluginIconUrl(definition.iconUrl);
667
+ entry.state.depends = definition.depends;
545
668
  const dependencies = serviceDependencies(definition.inject);
546
669
  entry.state.inject = [
547
670
  ...dependencies.required.map((name) => ({ name, optional: false })),
@@ -586,7 +709,10 @@ export class PluginManager {
586
709
  try {
587
710
  const imported = await importPlugin(path);
588
711
  try {
589
- this.add(validateDefinition(imported.value), 'file', path, imported.files, imported.release);
712
+ const definition = validateDefinition(imported.value);
713
+ if (!this.entries.has(definition.name))
714
+ await this.initializeDefaultOnNewBots(definition);
715
+ this.add(definition, 'file', path, imported.files, imported.release);
590
716
  }
591
717
  catch (error) {
592
718
  imported.release();
@@ -635,10 +761,8 @@ export class PluginManager {
635
761
  await deleteConfigValue(this.configPath, ['plugins', name]);
636
762
  delete this.app.config.plugins[name];
637
763
  this.app.storage.purgePlugin(name);
764
+ this.app.policies.load();
638
765
  this.invalidateGroupConfigs(name);
639
- for (const key of this.groupConfigWarnings)
640
- if (JSON.parse(key)[0] === name)
641
- this.groupConfigWarnings.delete(key);
642
766
  const path = join(this.app.config.dataDir, 'plugins', name);
643
767
  try {
644
768
  await this.ensureRealInside(this.app.config.dataDir, path);
@@ -733,7 +857,7 @@ export class PluginManager {
733
857
  const target = manifest.exports === undefined ? (manifest.main ?? 'index.js') : select(exports);
734
858
  if (!target || !/\.(?:js|mjs)$/.test(target))
735
859
  throw new ManagementError(400, 'Plugin package entry must be JavaScript');
736
- const root = join(this.packages.dir, 'node_modules', ...manifest.name.split('/'));
860
+ const root = this.packages.packageRoot(manifest.name);
737
861
  const path = resolve(root, target);
738
862
  this.ensureInside(root, path);
739
863
  await this.ensureRealInside(root, path);
@@ -750,9 +874,8 @@ export class PluginManager {
750
874
  if (existing?.definition && definition.name !== existing.state.name)
751
875
  throw new ManagementError(409, 'Updated package changed its plugin name');
752
876
  if (!existing) {
753
- const entry = this.add(definition, 'package', path, imported.files, imported.release);
754
- entry.manifest = manifest;
755
- return entry;
877
+ await this.initializeDefaultOnNewBots(definition);
878
+ return this.add(definition, 'package', path, imported.files, imported.release, manifest);
756
879
  }
757
880
  const oldPath = existing.state.path;
758
881
  const oldManifest = existing.manifest;
@@ -1030,7 +1153,7 @@ export class PluginManager {
1030
1153
  context = new Context(this.app, entry.state.name, parsed, entry.definition?.inject);
1031
1154
  let timedOut = false;
1032
1155
  let timer;
1033
- const setup = Promise.resolve().then(() => entry.definition?.setup(context));
1156
+ const setup = Promise.resolve().then(() => pluginExecution.run(entry.state.name, () => entry.definition?.setup(context)));
1034
1157
  void setup.catch((error) => {
1035
1158
  if (timedOut)
1036
1159
  this.app.logger.error({ err: error, plugin: entry.state.name }, 'Plugin setup failed after timeout');
@@ -1052,8 +1175,8 @@ export class PluginManager {
1052
1175
  }
1053
1176
  entry.context = context;
1054
1177
  entry.failure = undefined;
1055
- context.warnUnregisteredTasks();
1056
1178
  this.setState(entry, 'active');
1179
+ context.activateTasks();
1057
1180
  }
1058
1181
  catch (error) {
1059
1182
  await context?.dispose();
@@ -1077,10 +1200,10 @@ export class PluginManager {
1077
1200
  const imported = await importPlugin(entry.state.path);
1078
1201
  release = imported.release;
1079
1202
  definition = validateDefinition(imported.value);
1203
+ if (definition.name !== entry.state.name && (entry.definition || this.entries.has(definition.name)))
1204
+ throw new PluginError(`Plugin name changed from "${entry.state.name}" to "${definition.name}"`);
1205
+ await this.initializeDefaultOnNewBots(definition);
1080
1206
  if (definition.name !== entry.state.name) {
1081
- if (entry.definition || this.entries.has(definition.name)) {
1082
- throw new PluginError(`Plugin name changed from "${entry.state.name}" to "${definition.name}"`);
1083
- }
1084
1207
  this.entries.delete(entry.state.name);
1085
1208
  entry.state.name = definition.name;
1086
1209
  entry.state.enabled = this.app.config.plugins[definition.name]?.enabled ?? true;
@@ -35,6 +35,7 @@ export interface PackageSearchItem {
35
35
  name: string;
36
36
  version: string;
37
37
  description?: string;
38
+ iconUrl?: string;
38
39
  author?: string;
39
40
  date?: string;
40
41
  links: {
@@ -147,7 +148,9 @@ export declare class PackageService {
147
148
  }, host: PackageHost, options?: PackageOptions);
148
149
  init(): Promise<void>;
149
150
  dependencies(): Promise<Record<string, string>>;
151
+ packageRoot(name: string): string;
150
152
  manifest(name: string): Promise<PackageManifest>;
153
+ installedReadme(manifest: PackageManifest): Promise<string | undefined>;
151
154
  info(manifest: PackageManifest): PackageInfo;
152
155
  private refreshLatest;
153
156
  ensureLatest(): Promise<void>;
@@ -174,6 +177,7 @@ export declare class PackageService {
174
177
  installed?: string | undefined;
175
178
  versions: {
176
179
  version: string;
180
+ iconUrl: string | undefined;
177
181
  date?: string | undefined;
178
182
  peerRange?: string | undefined;
179
183
  compatible: boolean;
@@ -1,11 +1,13 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { access, mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { createReadStream } from 'node:fs';
4
+ import { access, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
4
5
  import { delimiter, isAbsolute, join, resolve } from 'node:path';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { gunzipSync } from 'fflate';
7
8
  import { maxSatisfying, rcompare, satisfies, valid, validRange } from 'semver';
8
9
  import { z } from 'zod';
10
+ import { pluginIconFromKeywords } from './icon.js';
9
11
  import { ManagementError } from './upload.js';
10
12
  const manifestSchema = z.object({
11
13
  name: z.string(),
@@ -83,7 +85,13 @@ export function redact(value) {
83
85
  return result;
84
86
  }
85
87
  const maxTarballBytes = 5 * 1024 * 1024;
86
- const readmePath = /^[^/]+\/readme(?:\.(?:md|markdown|txt))?$/i;
88
+ const maxReadmeBytes = 200 * 1024;
89
+ const readmeFilename = /^readme(?:\.(?:md|markdown|txt))?$/i;
90
+ function decodeReadme(bytes) {
91
+ return new TextDecoder().decode(bytes.subarray(0, maxReadmeBytes), {
92
+ stream: bytes.length > maxReadmeBytes,
93
+ });
94
+ }
87
95
  /** The top-level README of an npm tarball (gzipped ustar), or undefined when there is none. */
88
96
  export function readmeFromTarball(tgz) {
89
97
  const tar = gunzipSync(tgz);
@@ -104,7 +112,8 @@ export function readmeFromTarball(tgz) {
104
112
  const prefix = field(offset + 345, 155);
105
113
  const path = prefix ? `${prefix}/${name}` : name;
106
114
  const start = offset + 512;
107
- if ((type === '' || type === '0') && readmePath.test(path))
115
+ const slash = path.indexOf('/');
116
+ if ((type === '' || type === '0') && slash > 0 && readmeFilename.test(path.slice(slash + 1)))
108
117
  return decoder.decode(tar.subarray(start, start + size));
109
118
  offset = start + Math.ceil(size / 512) * 512;
110
119
  }
@@ -165,6 +174,7 @@ export class FetchRegistry {
165
174
  name: item.name,
166
175
  version: item.version,
167
176
  ...(item.description === undefined ? {} : { description: item.description }),
177
+ iconUrl: pluginIconFromKeywords(item.keywords),
168
178
  ...(item.author === undefined
169
179
  ? {}
170
180
  : { author: typeof item.author === 'string' ? item.author : item.author.name }),
@@ -291,15 +301,35 @@ export class PackageService {
291
301
  const data = JSON.parse(await readFile(join(this.dir, 'package.json'), 'utf8'));
292
302
  return data.dependencies ?? {};
293
303
  }
304
+ packageRoot(name) {
305
+ return join(this.dir, 'node_modules', ...name.split('/'));
306
+ }
294
307
  async manifest(name) {
295
308
  if (!validPackageName(name))
296
309
  throw new ManagementError(400, 'Invalid package name');
297
- const data = JSON.parse(await readFile(join(this.dir, 'node_modules', ...name.split('/'), 'package.json'), 'utf8'));
310
+ const data = JSON.parse(await readFile(join(this.packageRoot(name), 'package.json'), 'utf8'));
298
311
  const parsed = manifestSchema.safeParse(data);
299
312
  if (!parsed.success || parsed.data.name !== name || !valid(parsed.data.version))
300
313
  throw new ManagementError(400, 'Invalid installed package metadata');
301
314
  return parsed.data;
302
315
  }
316
+ async installedReadme(manifest) {
317
+ const root = this.packageRoot(manifest.name);
318
+ try {
319
+ const files = await readdir(root, { withFileTypes: true });
320
+ const readme = files.find((file) => file.isFile() && readmeFilename.test(file.name));
321
+ if (!readme)
322
+ return undefined;
323
+ const stream = createReadStream(join(root, readme.name), { end: maxReadmeBytes });
324
+ const chunks = await stream.toArray();
325
+ return decodeReadme(Buffer.concat(chunks));
326
+ }
327
+ catch (error) {
328
+ if (error.code === 'ENOENT')
329
+ return undefined;
330
+ throw error;
331
+ }
332
+ }
303
333
  info(manifest) {
304
334
  const peerRange = manifest.peerDependencies?.['@asabot/core'];
305
335
  const cached = this.latestCache.get(manifest.name);
@@ -411,10 +441,7 @@ export class PackageService {
411
441
  const data = cached.value;
412
442
  const installed = this.host.installedPackages().get(name)?.manifest.version;
413
443
  const repository = typeof data.repository === 'string' ? data.repository : data.repository?.url;
414
- const bytes = data.readme === undefined ? undefined : Buffer.from(data.readme, 'utf8');
415
- const readme = bytes && bytes.length > 200 * 1024
416
- ? new TextDecoder().decode(bytes.subarray(0, 200 * 1024), { stream: true })
417
- : data.readme;
444
+ const readme = data.readme === undefined ? undefined : decodeReadme(Buffer.from(data.readme, 'utf8'));
418
445
  const versions = Object.keys(data.versions)
419
446
  .filter((version) => valid(version))
420
447
  .sort(rcompare)
@@ -424,6 +451,7 @@ export class PackageService {
424
451
  .object({
425
452
  peerDependencies: z.record(z.string(), z.string()).optional(),
426
453
  deprecated: z.string().optional(),
454
+ keywords: z.unknown().optional(),
427
455
  })
428
456
  .safeParse(data.versions[version]);
429
457
  const peerRange = value.success ? value.data.peerDependencies?.['@asabot/core'] : undefined;
@@ -431,6 +459,7 @@ export class PackageService {
431
459
  const date = data.time?.[version];
432
460
  return {
433
461
  version,
462
+ iconUrl: value.success ? pluginIconFromKeywords(value.data.keywords) : undefined,
434
463
  ...(date === undefined ? {} : { date }),
435
464
  ...(peerRange === undefined ? {} : { peerRange }),
436
465
  compatible: !!peerRange && !!validRange(peerRange) && satisfies(frameworkVersion, peerRange),
@@ -459,7 +488,8 @@ export class PackageService {
459
488
  (version !== undefined &&
460
489
  (version.length > 256 || (!validRange(version) && !/^[a-zA-Z0-9][a-zA-Z0-9._+-]*$/.test(version)))))
461
490
  throw new ManagementError(400, 'Invalid package name or version');
462
- const metadata = await this.registry.metadata(name);
491
+ // The abbreviated npm packument omits keywords from version manifests.
492
+ const metadata = await this.registry.fullMetadata(name);
463
493
  this.latestCache.set(name, { value: metadata['dist-tags']?.latest, expires: Date.now() + 3_600_000 });
464
494
  const selected = version === undefined
465
495
  ? metadata['dist-tags']?.latest