@mushinjs/plugin-bots 0.3.0 → 0.4.0-next.20261127155650

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.
package/dist/manager.js CHANGED
@@ -25,6 +25,8 @@ const LEVELS = [
25
25
  const DAY = 864e5;
26
26
  const STORAGE_KEY = "bots";
27
27
  const BUFFER_SIZE = 500;
28
+ /** Plugin runs kept in memory for each bot; older ones stay in the daily files. */
29
+ const RUN_BUFFER_SIZE = 300;
28
30
  const LOG_BUFFER_SIZE = 500;
29
31
  const LOG_LEVEL_DEBUG = 3;
30
32
  const plainExporter = {
@@ -52,7 +54,7 @@ const HELP_COMMAND = {
52
54
  name: "help",
53
55
  description: "列出所有指令"
54
56
  };
55
- const pluginInput = idInput.extend({ package: z.string().describe("Bot plugin package name from bots.plugins.list") });
57
+ const pluginInput = idInput.extend({ package: z.string().describe("Plugin package name from bots.plugins.list: a bot plugin, or an app plugin with chat commands") });
56
58
  /**
57
59
  * Owns bot records and runs each enabled bot in its own isolated context:
58
60
  * the `bot` service, the adapter connection and the bot's plugins live there.
@@ -78,6 +80,11 @@ var BotManager = class extends Service {
78
80
  botLogSns = /* @__PURE__ */ new Set();
79
81
  commandProviders = /* @__PURE__ */ new Set();
80
82
  appCommands = /* @__PURE__ */ new Set();
83
+ /** Bot plugins turned off for the whole project; they run on no bot, whatever each bot says. */
84
+ projectOff = /* @__PURE__ */ new Set();
85
+ runs = /* @__PURE__ */ new Map();
86
+ /** The context that registered each adapter, to tell which installed plugin adds it. */
87
+ adapterFibers = /* @__PURE__ */ new Map();
81
88
  permissionProvider;
82
89
  constructor(ctx) {
83
90
  super(ctx, "bots");
@@ -93,6 +100,7 @@ var BotManager = class extends Service {
93
100
  async *[Service.init]() {
94
101
  const stored = await this.home.storage.get(STORAGE_KEY);
95
102
  this.records = stored?.bots ?? [];
103
+ this.projectOff = new Set(stored?.off ?? []);
96
104
  for (const record of this.records) for (const plugin of record.plugins ?? []) plugin.package = currentPackageName(plugin.package);
97
105
  this.logger.info("loaded %d bot(s)", this.records.length);
98
106
  yield this.home.logger.exporter({
@@ -101,6 +109,7 @@ var BotManager = class extends Service {
101
109
  export: (message) => this.captureLog(message)
102
110
  });
103
111
  yield* this.defineActions();
112
+ yield this.home.manager.defineProvides(() => this.provided());
104
113
  this.home.inject(["model", "database"], async (ctx) => {
105
114
  const archive = new MessageArchive(ctx, (error) => this.logger.warn("saving a message to the database failed: %s", error));
106
115
  this.archive = archive;
@@ -124,6 +133,7 @@ var BotManager = class extends Service {
124
133
  return ctx.effect(() => {
125
134
  if (this.adapterStore.has(adapter.id)) throw new Error(`adapter "${adapter.id}" is already defined`);
126
135
  this.adapterStore.set(adapter.id, adapter);
136
+ this.adapterFibers.set(adapter.id, ctx.fiber);
127
137
  this.logger.info("adapter %s is available", adapter.id);
128
138
  this.secureRecords(adapter).catch((error) => this.logger.warn("could not move the %s secrets of bots to .env: %s", adapter.id, error));
129
139
  for (const record of this.records) {
@@ -133,6 +143,7 @@ var BotManager = class extends Service {
133
143
  ctx.emit("bots/changed");
134
144
  return async () => {
135
145
  this.adapterStore.delete(adapter.id);
146
+ this.adapterFibers.delete(adapter.id);
136
147
  this.logger.info("adapter %s was removed", adapter.id);
137
148
  for (const record of this.records) {
138
149
  if (record.adapter.type !== adapter.id || !this.runtimes.has(record.id)) continue;
@@ -144,15 +155,24 @@ var BotManager = class extends Service {
144
155
  };
145
156
  }, `bots.defineAdapter(${adapter.id})`);
146
157
  }
158
+ /** The adapters by their `order`, then in the order they were added. */
147
159
  adapters() {
148
- return [...this.adapterStore.values()].map((adapter) => ({
160
+ const list = [...this.adapterStore.values()];
161
+ list.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
162
+ return list.map((adapter) => ({
149
163
  id: adapter.id,
150
164
  displayName: adapter.displayName,
165
+ ...adapter.description ? { description: adapter.description } : {},
166
+ ...adapter.icon ? { icon: adapter.icon } : {},
167
+ ...adapter.color ? { color: adapter.color } : {},
151
168
  configSchema: toJsonSchema(adapter.config),
152
169
  secrets: adapter.secrets ?? [],
153
170
  segments: adapter.segments,
154
171
  groupRoles: !!adapter.groupRoles,
155
- avatars: adapter.avatars ?? {}
172
+ avatars: adapter.avatars ?? {},
173
+ hiddenFields: adapter.hiddenFields ?? {},
174
+ links: adapter.links ?? [],
175
+ ...adapter.qrSetup ? { qrSetup: adapter.qrSetup } : {}
156
176
  }));
157
177
  }
158
178
  /** Adapters that can send every segment in a message. */
@@ -175,7 +195,8 @@ var BotManager = class extends Service {
175
195
  error: bot.error,
176
196
  selfId: bot.selfId,
177
197
  selfName: bot.selfName,
178
- selfAvatar: bot.selfAvatar
198
+ selfAvatar: bot.selfAvatar,
199
+ invite: bot.invite
179
200
  };
180
201
  const error = this.startErrors.get(id);
181
202
  return {
@@ -241,7 +262,10 @@ var BotManager = class extends Service {
241
262
  return this.records.map((record) => this.describe(record));
242
263
  }
243
264
  async save() {
244
- await this.home.storage.set(STORAGE_KEY, { bots: this.records });
265
+ await this.home.storage.set(STORAGE_KEY, {
266
+ bots: this.records,
267
+ ...this.projectOff.size ? { off: [...this.projectOff] } : {}
268
+ });
245
269
  this.home.emit("bots/changed");
246
270
  }
247
271
  validateAdapter(type, config) {
@@ -254,6 +278,18 @@ var BotManager = class extends Service {
254
278
  if (!result.success) throw new MushinError("invalid_input", z.prettifyError(result.error), result.error.issues);
255
279
  return result.data;
256
280
  }
281
+ /**
282
+ * A new bot's adapter config. A bot created stopped may be saved half filled in (its connection
283
+ * set up later, e.g. "connect later" in the dashboard); it is checked again when it starts.
284
+ */
285
+ adapterConfigFor(input) {
286
+ try {
287
+ return this.validateAdapter(input.adapter.type, input.adapter.config);
288
+ } catch (error) {
289
+ if (input.enabled !== false || !this.adapterStore.has(input.adapter.type)) throw error;
290
+ return { ...input.adapter.config };
291
+ }
292
+ }
257
293
  async create(input) {
258
294
  const id = randomId();
259
295
  const record = {
@@ -265,7 +301,7 @@ var BotManager = class extends Service {
265
301
  config: (await this.secureConfig(input.adapter.type, {
266
302
  id,
267
303
  name: input.name
268
- }, this.validateAdapter(input.adapter.type, input.adapter.config))).config
304
+ }, this.adapterConfigFor(input))).config
269
305
  },
270
306
  plugins: [],
271
307
  provider: input.provider,
@@ -306,7 +342,7 @@ var BotManager = class extends Service {
306
342
  }
307
343
  await this.save();
308
344
  this.logger.info("updated bot %s", this.label(record));
309
- const restart = patch.name !== void 0 || patch.adapter !== void 0 || patch.provider !== void 0;
345
+ const restart = patch.adapter !== void 0 || patch.provider !== void 0;
310
346
  if (record.enabled && restart) await this.start(id).catch(() => {});
311
347
  return this.describe(record);
312
348
  }
@@ -316,6 +352,7 @@ var BotManager = class extends Service {
316
352
  this.records = this.records.filter((item) => item !== record);
317
353
  this.buffers.delete(id);
318
354
  this.logs.delete(id);
355
+ this.runs.delete(id);
319
356
  this.startErrors.delete(id);
320
357
  await this.save();
321
358
  this.logger.info("deleted bot %s", this.label(record));
@@ -342,7 +379,7 @@ var BotManager = class extends Service {
342
379
  };
343
380
  const loaded = [];
344
381
  for (const entry of record.plugins) {
345
- if (!entry.enabled) continue;
382
+ if (!entry.enabled || this.projectOff.has(entry.package)) continue;
346
383
  try {
347
384
  const plugin = await this.loadBotPlugin(entry.package);
348
385
  const secured = await this.securePlugin(record, entry.package, plugin, entry.config ?? {}, entry.config);
@@ -393,7 +430,8 @@ var BotManager = class extends Service {
393
430
  return helpText(entries, bot.record.commands);
394
431
  },
395
432
  roleOf: (bot, userId) => this.permissionProvider?.roleOf(bot.id, userId),
396
- appCommand: (bot, entry) => this.appCommandFor(bot.id, entry)?.handler,
433
+ appCommand: (bot, entry) => this.appCommandFor(bot.id, entry),
434
+ pluginRun: (bot, run, fiber) => this.recordRun(bot.id, run, fiber),
397
435
  usageScope: (bot, message) => {
398
436
  const entry = this.usageEntry(bot.id, message.id, true);
399
437
  entry.bytes = byteSize(message.segments);
@@ -464,10 +502,32 @@ var BotManager = class extends Service {
464
502
  if (entry.manifest.kind !== "bot") throw new MushinError("invalid_input", `"${name}" is an app plugin, not a bot plugin`);
465
503
  return this.home.manager.loadPlugin(name);
466
504
  }
505
+ /**
506
+ * The plugins a bot can turn on: every installed bot plugin, then each app plugin with chat commands (`kind: 'app'`),
507
+ * with whether it is on for this bot and whether it is turned off for the whole project.
508
+ */
467
509
  async plugins(id) {
468
510
  const record = this.get(id);
469
- const runtime = this.runtimes.get(id);
470
511
  const graph = await this.home.manager.graph();
512
+ const apps = this.chatApps();
513
+ const appEntries = graph.catalog.filter((entry) => entry.manifest.kind === "app" && (apps.has(entry.package) || record.appPlugins?.includes(entry.package))).map((entry) => {
514
+ const commands = apps.get(entry.package);
515
+ const enabled = !!record.appPlugins?.includes(entry.package);
516
+ return {
517
+ package: entry.package,
518
+ kind: "app",
519
+ version: entry.version,
520
+ manifest: entry.manifest,
521
+ enabled,
522
+ ...commands ? { commands } : { projectOff: true },
523
+ status: enabled && commands ? "active" : "disabled"
524
+ };
525
+ });
526
+ return [...await this.botPlugins(id, graph), ...appEntries];
527
+ }
528
+ async botPlugins(id, graph) {
529
+ const record = this.get(id);
530
+ const runtime = this.runtimes.get(id);
471
531
  const catalog = graph.catalog.filter((entry) => entry.manifest.kind === "bot");
472
532
  return Promise.all(catalog.map(async (entry) => {
473
533
  const configured = record.plugins.find((item) => item.package === entry.package);
@@ -481,10 +541,13 @@ var BotManager = class extends Service {
481
541
  const fiber = runtime?.plugins.get(entry.package);
482
542
  const report = dependencyReport(graph, entry.package);
483
543
  const missing = this.missingApps(report.requires);
484
- let status = configured?.enabled ? runtime ? fiberStatus(fiber) : "disabled" : "disabled";
544
+ const projectOff = this.projectOff.has(entry.package);
545
+ let status = configured?.enabled && !projectOff ? runtime ? fiberStatus(fiber) : "disabled" : "disabled";
485
546
  if (status === "pending" && missing.length) status = "missing";
486
547
  return {
487
548
  package: entry.package,
549
+ kind: "bot",
550
+ ...projectOff ? { projectOff } : {},
488
551
  version: entry.version,
489
552
  manifest: entry.manifest,
490
553
  enabled: !!configured?.enabled,
@@ -509,8 +572,27 @@ var BotManager = class extends Service {
509
572
  ...dep.version ? { version: dep.version } : {}
510
573
  }));
511
574
  }
575
+ /** The bot's entry for a plugin in `plugins()`. */
576
+ async pluginInfo(id, name) {
577
+ return (await this.plugins(id)).find((item) => item.package === name);
578
+ }
579
+ /** Turns an app plugin's chat commands on or off for one bot. */
580
+ async setAppPlugin(id, name, enabled) {
581
+ const record = this.get(id);
582
+ const list = new Set(record.appPlugins ?? []);
583
+ if (enabled) list.add(name);
584
+ else list.delete(name);
585
+ record.appPlugins = [...list];
586
+ await this.save();
587
+ this.logger.info("%s the commands of %s on bot %s", enabled ? "turned on" : "turned off", name, this.label(record));
588
+ return this.pluginInfo(id, name);
589
+ }
512
590
  async enablePlugin(id, name, config) {
513
591
  const record = this.get(id);
592
+ if ((await this.home.manager.findPackage(name))?.manifest.kind === "app") {
593
+ if (config) throw new MushinError("invalid_input", `${name} is an app plugin: its settings are on the Plugins page (plugins.configure)`);
594
+ return this.setAppPlugin(id, name, true);
595
+ }
514
596
  const plugin = await this.loadBotPlugin(name);
515
597
  const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires);
516
598
  if (missing.length) throw new MushinError("unavailable", `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing });
@@ -531,10 +613,11 @@ var BotManager = class extends Service {
531
613
  await this.save();
532
614
  this.logger.info("enabled plugin %s on bot %s", name, this.label(record));
533
615
  this.reloadPlugin(id, entry, plugin);
534
- return this.plugins(id).then((list) => list.find((item) => item.package === name));
616
+ return this.pluginInfo(id, name);
535
617
  }
536
618
  async disablePlugin(id, name) {
537
619
  const record = this.get(id);
620
+ if ((await this.home.manager.findPackage(name))?.manifest.kind === "app" || record.appPlugins?.includes(name)) return this.setAppPlugin(id, name, false);
538
621
  const entry = record.plugins.find((item) => item.package === name);
539
622
  if (!entry) throw new MushinError("not_found", `${name} is not configured on this bot`);
540
623
  entry.enabled = false;
@@ -544,10 +627,11 @@ var BotManager = class extends Service {
544
627
  const fiber = runtime?.plugins.get(name);
545
628
  runtime?.plugins.delete(name);
546
629
  await fiber?.dispose();
547
- return this.plugins(id).then((list) => list.find((item) => item.package === name));
630
+ return this.pluginInfo(id, name);
548
631
  }
549
632
  async configurePlugin(id, name, config) {
550
633
  const record = this.get(id);
634
+ if ((await this.home.manager.findPackage(name))?.manifest.kind === "app") throw new MushinError("invalid_input", `${name} is an app plugin: its settings are on the Plugins page (plugins.configure), the same for every bot`);
551
635
  const entry = record.plugins.find((item) => item.package === name);
552
636
  if (!entry) return this.enablePlugin(id, name, config);
553
637
  const plugin = await this.loadBotPlugin(name);
@@ -557,7 +641,7 @@ var BotManager = class extends Service {
557
641
  await this.save();
558
642
  this.logger.info("config of plugin %s on bot %s changed", name, this.label(record));
559
643
  if (entry.enabled) this.reloadPlugin(id, entry, plugin);
560
- return this.plugins(id).then((list) => list.find((item) => item.package === name));
644
+ return this.pluginInfo(id, name);
561
645
  }
562
646
  /** Puts the plain values of a bot plugin's secret fields into .env and returns the config with `${NAME}` references. */
563
647
  async securePlugin(record, name, plugin, config, previous) {
@@ -576,11 +660,63 @@ var BotManager = class extends Service {
576
660
  }
577
661
  reloadPlugin(id, entry, plugin) {
578
662
  const runtime = this.runtimes.get(id);
579
- if (!runtime?.ctx) return;
663
+ if (!runtime?.ctx || this.projectOff.has(entry.package)) return;
580
664
  runtime.plugins.get(entry.package)?.dispose();
581
665
  runtime.pluginErrors.delete(entry.package);
582
666
  runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, resolveEnvReferences(entry.config)));
583
667
  }
668
+ /**
669
+ * Turns a bot plugin on or off for the whole project. Off, it runs on no bot; each bot keeps its own switch and
670
+ * settings, so turning it back on starts it again where it was on.
671
+ */
672
+ async setProjectPlugin(name, enabled) {
673
+ const entry = await this.home.manager.findPackage(name);
674
+ if (!entry) throw new MushinError("not_found", `Plugin "${name}" is not installed`);
675
+ if (entry.manifest.kind !== "bot") throw new MushinError("invalid_input", `${name} is an app plugin: turn it on or off for the project with plugins.enable or plugins.disable`);
676
+ if (!enabled && entry.manifest.essential) throw new MushinError("forbidden", `${name} cannot be turned off for the whole project; turn it off on each bot instead`);
677
+ if (enabled === !this.projectOff.has(name)) return this.projectPlugin(name);
678
+ if (enabled) this.projectOff.delete(name);
679
+ else this.projectOff.add(name);
680
+ await this.save();
681
+ this.logger.info("%s %s for every bot", enabled ? "turned on" : "turned off", name);
682
+ for (const record of this.records) {
683
+ const item = record.plugins.find((plugin) => plugin.package === name && plugin.enabled);
684
+ const runtime = this.runtimes.get(record.id);
685
+ if (!item || !runtime) continue;
686
+ if (enabled) try {
687
+ this.reloadPlugin(record.id, item, await this.loadBotPlugin(name));
688
+ } catch (error) {
689
+ runtime.pluginErrors.set(name, error instanceof Error ? error.message : String(error));
690
+ }
691
+ else {
692
+ const fiber = runtime.plugins.get(name);
693
+ runtime.plugins.delete(name);
694
+ await fiber?.dispose();
695
+ }
696
+ }
697
+ return this.projectPlugin(name);
698
+ }
699
+ /**
700
+ * The chat plugins across the project: each bot plugin with its project switch, and each app plugin with chat
701
+ * commands, with the bots that have it on.
702
+ */
703
+ async projectPlugins() {
704
+ const catalog = (await this.home.manager.graph()).catalog;
705
+ const apps = this.chatApps();
706
+ return catalog.filter((entry) => entry.manifest.kind === "bot" || apps.has(entry.package)).map((entry) => {
707
+ const bot = entry.manifest.kind === "bot";
708
+ return {
709
+ package: entry.package,
710
+ kind: bot ? "bot" : "app",
711
+ enabled: bot ? !this.projectOff.has(entry.package) : true,
712
+ ...bot && entry.manifest.essential ? { essential: true } : {},
713
+ bots: this.records.filter((record) => bot ? record.plugins.some((item) => item.package === entry.package && item.enabled) : record.appPlugins?.includes(entry.package)).map((record) => record.id)
714
+ };
715
+ });
716
+ }
717
+ async projectPlugin(name) {
718
+ return (await this.projectPlugins()).find((item) => item.package === name);
719
+ }
584
720
  /** Adds commands to every bot's list. Removed when the calling plugin unloads. */
585
721
  defineCommands(provider) {
586
722
  return this.ctx.effect(() => {
@@ -589,14 +725,17 @@ var BotManager = class extends Service {
589
725
  }, "bots.defineCommands()");
590
726
  }
591
727
  /**
592
- * Answers a command on every bot (or those `bots` picks) from an app plugin, such as `/persona`.
593
- * It answers after flows, like `/help`, and shows in each bot's command list.
728
+ * Answers a command from an app plugin, such as `/persona`, on the bots the user turned the plugin on for (on the
729
+ * bot's Plugins page, or with `bots.plugins.enable`). A plugin that decides itself which bots answer, from its own
730
+ * per-bot settings, passes `bots`, and then has no switch on the bot's page. It answers after flows, like `/help`,
731
+ * and shows in the command list of each bot it answers on.
594
732
  */
595
733
  defineCommand(def, handler, options = {}) {
596
734
  const ctx = this.ctx;
597
735
  const command = {
598
736
  def,
599
737
  plugin: ctx.fiber.name,
738
+ fiber: ctx.fiber,
600
739
  handler,
601
740
  bots: options.bots
602
741
  };
@@ -608,7 +747,26 @@ var BotManager = class extends Service {
608
747
  /** The app plugin command behind a command entry, if an app plugin answers it. */
609
748
  appCommandFor(botId, entry) {
610
749
  if (entry.source.kind !== "plugin") return;
611
- return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && (item.bots?.(botId) ?? true));
750
+ return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && this.answersOn(item, botId));
751
+ }
752
+ /** Whether an app plugin's command answers on a bot: the plugin's own choice, or the bot's switch for the plugin. */
753
+ answersOn(command, botId) {
754
+ if (command.bots) return command.bots(botId);
755
+ const name = this.home.manager.packageOf(command.fiber);
756
+ return !!name && !!this.records.find((record) => record.id === botId)?.appPlugins?.includes(name);
757
+ }
758
+ /** App plugins whose commands have a switch on each bot, with the names of those commands, by package. */
759
+ chatApps() {
760
+ const apps = /* @__PURE__ */ new Map();
761
+ for (const command of this.appCommands) {
762
+ if (command.bots) continue;
763
+ const name = this.home.manager.packageOf(command.fiber);
764
+ if (!name) continue;
765
+ const list = apps.get(name) ?? [];
766
+ if (!list.includes(command.def.name)) list.push(command.def.name);
767
+ apps.set(name, list);
768
+ }
769
+ return apps;
612
770
  }
613
771
  /** Lets the permissions plugin say who is master, admin or user on each bot. */
614
772
  usePermissions(provider) {
@@ -635,7 +793,7 @@ var BotManager = class extends Service {
635
793
  }
636
794
  entries.push(...this.runtimes.get(botId)?.bot?.localCommands() ?? []);
637
795
  for (const command of this.appCommands) {
638
- if (command.bots && !command.bots(botId)) continue;
796
+ if (!this.answersOn(command, botId)) continue;
639
797
  entries.push({
640
798
  ...command.def,
641
799
  botId,
@@ -729,6 +887,75 @@ var BotManager = class extends Service {
729
887
  replies: replies.map((reply) => segmentsToText(reply.segments))
730
888
  };
731
889
  }
890
+ /** The installed plugin a context of a bot belongs to: one of the bot's plugins, else an app plugin. */
891
+ packageIn(botId, fiber) {
892
+ if (!fiber) return;
893
+ const runtime = this.runtimes.get(botId);
894
+ if (runtime) {
895
+ const owners = /* @__PURE__ */ new Map();
896
+ for (const [name, plugin] of runtime.plugins) owners.set(plugin.ctx.fiber, name);
897
+ for (let current = fiber; current; current = current.parent?.fiber === current ? void 0 : current.parent?.fiber) {
898
+ const name = owners.get(current);
899
+ if (name) return name;
900
+ }
901
+ }
902
+ return this.home.manager.packageOf(fiber);
903
+ }
904
+ recordRun(botId, report, fiber) {
905
+ const run = {
906
+ id: randomId(8),
907
+ botId,
908
+ ...report,
909
+ plugin: this.packageIn(botId, fiber) ?? report.plugin
910
+ };
911
+ let buffer = this.runs.get(botId);
912
+ if (!buffer) this.runs.set(botId, buffer = []);
913
+ buffer.push(run);
914
+ if (buffer.length > RUN_BUFFER_SIZE) buffer.splice(0, buffer.length - RUN_BUFFER_SIZE);
915
+ const day = new Date(run.startedAt).toISOString().slice(0, 10);
916
+ this.home.storage.append(`runs/${botId}/${day}`, run).catch(() => {});
917
+ this.home.emit("bots/run", run);
918
+ }
919
+ /**
920
+ * What plugins did with a bot's messages, newest first: each message a plugin replied to, kept from the plugins
921
+ * after it, or failed on. Flow runs are in `flows.history`.
922
+ */
923
+ async pluginRuns(id, query = {}) {
924
+ this.get(id);
925
+ let buffer = this.runs.get(id);
926
+ if (!buffer) {
927
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
928
+ const stored = await this.home.storage.tail(`runs/${id}/${day}`, RUN_BUFFER_SIZE);
929
+ const current = this.runs.get(id) ?? [];
930
+ buffer = [...stored.filter((run) => !current.some((item) => item.id === run.id)), ...current].slice(-300);
931
+ this.runs.set(id, buffer);
932
+ }
933
+ const limit = query.limit ?? 50;
934
+ const matching = buffer.filter((run) => (query.before === void 0 || run.startedAt < query.before) && (!query.plugin || run.plugin === query.plugin) && (!query.status || run.status === query.status));
935
+ return {
936
+ runs: matching.slice(-limit).reverse(),
937
+ more: matching.length > limit
938
+ };
939
+ }
940
+ /** What this plugin knows of what others add: chat commands (app plugins' and bot plugins'), and adapters. */
941
+ *provided() {
942
+ for (const command of this.appCommands) yield {
943
+ kind: "command",
944
+ name: command.def.name,
945
+ fiber: command.fiber
946
+ };
947
+ for (const [id, runtime] of this.runtimes) for (const command of runtime.bot?.ownCommandList() ?? []) yield {
948
+ kind: "command",
949
+ name: command.name,
950
+ package: this.packageIn(id, command.fiber),
951
+ fiber: command.fiber
952
+ };
953
+ for (const [id, fiber] of this.adapterFibers) yield {
954
+ kind: "adapter",
955
+ name: id,
956
+ fiber
957
+ };
958
+ }
732
959
  /** Finds the bot whose context wrote a log message, by walking up from the writing fiber. */
733
960
  botOf(message) {
734
961
  let fiber = message.fiber?.deref();
@@ -998,7 +1225,7 @@ var BotManager = class extends Service {
998
1225
  });
999
1226
  yield actions.define({
1000
1227
  name: "bots.create",
1001
- description: "Create a bot and start it. For NapCat use adapter type \"onebot\" with mode \"forward\" (url of NapCat's WebSocket server, e.g. ws://127.0.0.1:3001) or mode \"reverse\" (NapCat connects to Mushin). Returns the bot with its id.",
1228
+ description: "Create a bot and start it. Pick the adapter type and its config from bots.adapters. With enabled false the bot is saved stopped, and its adapter config may still be incomplete. Returns the bot with its id.",
1002
1229
  risk: "write",
1003
1230
  input: z.object({
1004
1231
  name: z.string().min(1),
@@ -1015,7 +1242,7 @@ var BotManager = class extends Service {
1015
1242
  });
1016
1243
  yield actions.define({
1017
1244
  name: "bots.update",
1018
- description: "Rename a bot, change its adapter connection, default provider or command settings. Restarts the bot if it is enabled, unless only command settings change.",
1245
+ description: "Rename a bot, change its adapter connection, default provider or command settings. Restarts the bot if it is enabled and its connection or provider changes.",
1019
1246
  risk: "write",
1020
1247
  input: idInput.extend({
1021
1248
  name: z.string().min(1).optional(),
@@ -1043,8 +1270,8 @@ var BotManager = class extends Service {
1043
1270
  group: z.string().optional().describe("Group id, with target \"group\""),
1044
1271
  user: z.string().optional().describe("Run as this user id instead of the first master")
1045
1272
  }),
1046
- handler: (input, caller) => this.runCommand(input, caller.kind === "agent" && caller.session ? {
1047
- kind: "agent",
1273
+ handler: (input, caller) => this.runCommand(input, caller.kind === "fairy" && caller.session ? {
1274
+ kind: "fairy",
1048
1275
  session: caller.session
1049
1276
  } : void 0)
1050
1277
  });
@@ -1071,21 +1298,21 @@ var BotManager = class extends Service {
1071
1298
  });
1072
1299
  yield actions.define({
1073
1300
  name: "bots.plugins.list",
1074
- description: "List every installed bot plugin with whether it is enabled on this bot, its config and status.",
1301
+ description: "List the plugins a bot can turn on, with whether each is on for this bot: every installed bot plugin (kind bot, with its config and status), then each app plugin that adds chat commands (kind app, with its commands). projectOff means it is turned off for the whole project, so it does not run even where it is on.",
1075
1302
  risk: "read",
1076
1303
  input: idInput,
1077
1304
  handler: ({ id }) => this.plugins(id)
1078
1305
  });
1079
1306
  yield actions.define({
1080
1307
  name: "bots.plugins.enable",
1081
- description: "Enable a bot plugin on one bot, optionally with config.",
1308
+ description: "Turn a plugin on for one bot: a bot plugin, optionally with config, or an app plugin's chat commands (an app plugin's commands answer only on the bots it is turned on for).",
1082
1309
  risk: "write",
1083
1310
  input: pluginInput.extend({ config: z.record(z.string(), z.any()).optional() }),
1084
1311
  handler: ({ id, package: name, config }) => this.enablePlugin(id, name, config)
1085
1312
  });
1086
1313
  yield actions.define({
1087
1314
  name: "bots.plugins.disable",
1088
- description: "Disable a bot plugin on one bot. Its config is kept.",
1315
+ description: "Turn a bot plugin, or an app plugin's chat commands, off for one bot. A bot plugin's config is kept.",
1089
1316
  risk: "write",
1090
1317
  input: pluginInput,
1091
1318
  handler: ({ id, package: name }) => this.disablePlugin(id, name)
@@ -1097,6 +1324,35 @@ var BotManager = class extends Service {
1097
1324
  input: pluginInput.extend({ config: z.record(z.string(), z.any()) }),
1098
1325
  handler: ({ id, package: name, config }) => this.configurePlugin(id, name, config)
1099
1326
  });
1327
+ yield actions.define({
1328
+ name: "bots.plugins.project",
1329
+ description: "The chat plugins across the project: each bot plugin with its project switch (off, it runs on no bot), and each app plugin that adds chat commands. Lists the bots that have each one on.",
1330
+ risk: "read",
1331
+ input: z.object({}),
1332
+ handler: () => this.projectPlugins()
1333
+ });
1334
+ yield actions.define({
1335
+ name: "bots.plugins.setProject",
1336
+ description: "Turn a bot plugin on or off for the whole project. Off, it runs on no bot; each bot keeps its own switch and settings. App plugins are turned on and off with plugins.enable and plugins.disable.",
1337
+ risk: "write",
1338
+ input: z.object({
1339
+ package: z.string().describe("Bot plugin package name"),
1340
+ enabled: z.boolean()
1341
+ }),
1342
+ handler: ({ package: name, enabled }) => this.setProjectPlugin(name, enabled)
1343
+ });
1344
+ yield actions.define({
1345
+ name: "bots.runs",
1346
+ description: "What plugins did with a bot's messages, newest first: each message a bot plugin or an app plugin's command replied to (replies), kept from the plugins after it (kept), or failed on (status error, with the error). Flow runs are in flows.history. The message field is the record id, for bots.logs and bots.usage.",
1347
+ risk: "read",
1348
+ input: idInput.extend({
1349
+ limit: z.number().int().min(1).max(RUN_BUFFER_SIZE).optional(),
1350
+ before: z.number().optional().describe("Only runs started before this time (ms since 1970), to page back"),
1351
+ plugin: z.string().optional().describe("Only this plugin's runs: its package name"),
1352
+ status: z.enum(["ok", "error"]).optional()
1353
+ }),
1354
+ handler: ({ id, ...query }) => this.pluginRuns(id, query)
1355
+ });
1100
1356
  yield actions.define({
1101
1357
  name: "bots.messages",
1102
1358
  description: "Recent messages of a bot, oldest first, with type, supported platforms and source. Without a channel or `before`, the last 500 the bot saw.",