@mushinjs/plugin-bots 0.0.0-stage → 0.2.0-next.20261113103537

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.
@@ -0,0 +1,1144 @@
1
+ import { MessageArchive } from "./archive.js";
2
+ import { Bot, byteSize } from "./bot.js";
3
+ import { DEFAULT_PREFIXES, commandConflicts, commandMatches, commandUsage, helpText, parseArgs, requiredRole, splitCommand } from "./commands.js";
4
+ import { isSandbox, roleAtLeast } from "./types.js";
5
+ import { Logger, MushinError, Service, currentPackageName, dependencyReport, describeMissing, fiberError, fiberStatus, isMasked, logTag, mask, messageType, pluginSchema, randomId, segmentsToText, toJsonSchema, validatePluginConfig, z } from "@mushinjs/core";
6
+ // src/manager.ts
7
+ const STORAGE_KEY = "bots";
8
+ const BUFFER_SIZE = 500;
9
+ const LOG_BUFFER_SIZE = 500;
10
+ const LOG_LEVEL_DEBUG = 3;
11
+ const plainExporter = {
12
+ colors: false,
13
+ export() {}
14
+ };
15
+ const adapterInput = z.object({
16
+ type: z.string().describe("Adapter type id from bots.adapters, e.g. \"onebot\""),
17
+ config: z.record(z.string(), z.any()).describe("Adapter config matching the schema from bots.adapters")
18
+ });
19
+ /** Messages whose costs are kept; older ones are forgotten. */
20
+ const USAGE_MESSAGES = 2e3;
21
+ /** A runaway loop on one message stops being recorded after this many costs. */
22
+ const USAGE_EVENTS_PER_MESSAGE = 200;
23
+ const idInput = z.object({ id: z.string().describe("Bot id from bots.list") });
24
+ const commandSettingsInput = z.object({
25
+ prefixes: z.array(z.string().min(1)).optional().describe("Command prefixes; default [\"/\"]"),
26
+ help: z.boolean().optional().describe("Answer /help with the list of commands; on unless false"),
27
+ helpTitle: z.string().optional().describe("First line of the /help menu"),
28
+ admins: z.array(z.string()).optional().describe("Deprecated: admins now live in the permissions plugin (permissions.update)"),
29
+ helpByRole: z.boolean().optional().describe("/help lists only the commands the asker may run")
30
+ });
31
+ /** Answers `/help` when nothing else on the bot registers a command called help. */
32
+ const HELP_COMMAND = {
33
+ name: "help",
34
+ description: "列出所有指令"
35
+ };
36
+ const pluginInput = idInput.extend({ package: z.string().describe("Bot plugin package name from bots.plugins.list") });
37
+ /**
38
+ * Owns bot records and runs each enabled bot in its own isolated context:
39
+ * the `bot` service, the adapter connection and the bot's plugins live there.
40
+ */
41
+ var BotManager = class extends Service {
42
+ static inject = [
43
+ "storage",
44
+ "actions",
45
+ "manager"
46
+ ];
47
+ home;
48
+ records = [];
49
+ adapterStore = /* @__PURE__ */ new Map();
50
+ runtimes = /* @__PURE__ */ new Map();
51
+ startErrors = /* @__PURE__ */ new Map();
52
+ buffers = /* @__PURE__ */ new Map();
53
+ /** Messages in the database, when the database plugin runs. */
54
+ archive;
55
+ /** Runtime fiber of each running bot, to attribute log lines to the bot that wrote them. */
56
+ runtimeFibers = /* @__PURE__ */ new Map();
57
+ logs = /* @__PURE__ */ new Map();
58
+ /** Sequence numbers of recent bot log lines; still recognized after the bot that wrote them stops. */
59
+ botLogSns = /* @__PURE__ */ new Set();
60
+ commandProviders = /* @__PURE__ */ new Set();
61
+ appCommands = /* @__PURE__ */ new Set();
62
+ permissionProvider;
63
+ constructor(ctx) {
64
+ super(ctx, "bots");
65
+ this.home = ctx;
66
+ }
67
+ /**
68
+ * Bot lifecycle lines for the global log, tagged `bot` in the dashboard. Written from the manager's
69
+ * own context, so they stay out of the bot's log, which has its own lines from inside the bot.
70
+ */
71
+ get logger() {
72
+ return this.home.logger("bot");
73
+ }
74
+ async *[Service.init]() {
75
+ const stored = await this.home.storage.get(STORAGE_KEY);
76
+ this.records = stored?.bots ?? [];
77
+ for (const record of this.records) for (const plugin of record.plugins ?? []) plugin.package = currentPackageName(plugin.package);
78
+ this.logger.info("loaded %d bot(s)", this.records.length);
79
+ yield this.home.logger.exporter({
80
+ colors: false,
81
+ levels: { default: LOG_LEVEL_DEBUG },
82
+ export: (message) => this.captureLog(message)
83
+ });
84
+ yield* this.defineActions();
85
+ this.home.inject(["model", "database"], async (ctx) => {
86
+ const archive = new MessageArchive(ctx, (error) => this.logger.warn("saving a message to the database failed: %s", error));
87
+ this.archive = archive;
88
+ ctx.effect(() => () => {
89
+ if (this.archive === archive) this.archive = void 0;
90
+ }, "bots message archive");
91
+ try {
92
+ const imported = await archive.start();
93
+ if (imported) this.logger.info("imported %d message(s) from the message logs into the database", imported);
94
+ } catch (error) {
95
+ this.logger.warn("importing the message logs into the database failed: %s", error);
96
+ if (this.archive === archive) this.archive = void 0;
97
+ }
98
+ });
99
+ if (this.home.offline) this.logger.info("offline: bots are not started");
100
+ for (const record of this.home.offline ? [] : this.records) if (record.enabled && this.adapterStore.has(record.adapter.type)) this.startSafely(record.id);
101
+ }
102
+ /** Registers an adapter type. Bots using it start when it loads and stop when it unloads. */
103
+ defineAdapter(adapter) {
104
+ const ctx = this.ctx;
105
+ return ctx.effect(() => {
106
+ if (this.adapterStore.has(adapter.id)) throw new Error(`adapter "${adapter.id}" is already defined`);
107
+ this.adapterStore.set(adapter.id, adapter);
108
+ this.logger.info("adapter %s is available", adapter.id);
109
+ for (const record of this.records) {
110
+ if (this.home.offline) break;
111
+ if (record.enabled && record.adapter.type === adapter.id && !this.runtimes.has(record.id)) this.startSafely(record.id);
112
+ }
113
+ ctx.emit("bots/changed");
114
+ return async () => {
115
+ this.adapterStore.delete(adapter.id);
116
+ this.logger.info("adapter %s was removed", adapter.id);
117
+ for (const record of this.records) {
118
+ if (record.adapter.type !== adapter.id || !this.runtimes.has(record.id)) continue;
119
+ await this.stopRuntime(record.id);
120
+ this.startErrors.set(record.id, `Adapter "${adapter.id}" was unloaded`);
121
+ this.emitStatus(record.id);
122
+ }
123
+ ctx.emit("bots/changed");
124
+ };
125
+ }, `bots.defineAdapter(${adapter.id})`);
126
+ }
127
+ adapters() {
128
+ return [...this.adapterStore.values()].map((adapter) => ({
129
+ id: adapter.id,
130
+ displayName: adapter.displayName,
131
+ configSchema: toJsonSchema(adapter.config),
132
+ secrets: adapter.secrets ?? [],
133
+ segments: adapter.segments,
134
+ groupRoles: !!adapter.groupRoles,
135
+ avatars: adapter.avatars ?? {}
136
+ }));
137
+ }
138
+ /** Adapters that can send every segment in a message. */
139
+ platformsFor(segments) {
140
+ return [...this.adapterStore.values()].filter((adapter) => segments.every((s) => adapter.segments.includes(s.type))).map((adapter) => adapter.id);
141
+ }
142
+ get(id) {
143
+ const record = this.records.find((item) => item.id === id);
144
+ if (!record) throw new MushinError("not_found", `No bot with id "${id}"`);
145
+ return record;
146
+ }
147
+ bot(id) {
148
+ return this.runtimes.get(id)?.bot;
149
+ }
150
+ status(id) {
151
+ const bot = this.bot(id);
152
+ if (bot) return {
153
+ id,
154
+ status: bot.status,
155
+ error: bot.error,
156
+ selfId: bot.selfId,
157
+ selfName: bot.selfName,
158
+ selfAvatar: bot.selfAvatar
159
+ };
160
+ const error = this.startErrors.get(id);
161
+ return {
162
+ id,
163
+ status: error ? "error" : "offline",
164
+ error
165
+ };
166
+ }
167
+ emitStatus(id) {
168
+ this.home.emit("bots/status", this.status(id));
169
+ }
170
+ redact(record) {
171
+ const secrets = this.adapterStore.get(record.adapter.type)?.secrets ?? [];
172
+ const config = { ...record.adapter.config };
173
+ for (const key of secrets) if (typeof config[key] === "string" && config[key]) config[key] = mask(config[key]);
174
+ return {
175
+ ...record,
176
+ adapter: {
177
+ ...record.adapter,
178
+ config
179
+ }
180
+ };
181
+ }
182
+ describe(record) {
183
+ return {
184
+ ...this.redact(record),
185
+ ...this.status(record.id),
186
+ connection: this.connectionOf(record)
187
+ };
188
+ }
189
+ connectionOf(record) {
190
+ try {
191
+ return this.adapterStore.get(record.adapter.type)?.describe?.(record.adapter.config, record.id);
192
+ } catch {}
193
+ }
194
+ list() {
195
+ return this.records.map((record) => this.describe(record));
196
+ }
197
+ async save() {
198
+ await this.home.storage.set(STORAGE_KEY, { bots: this.records });
199
+ this.home.emit("bots/changed");
200
+ }
201
+ validateAdapter(type, config) {
202
+ const adapter = this.adapterStore.get(type);
203
+ if (!adapter) {
204
+ const known = [...this.adapterStore.keys()].join(", ") || "none";
205
+ throw new MushinError("invalid_input", `Unknown adapter "${type}". Loaded adapters: ${known}`);
206
+ }
207
+ const result = adapter.config.safeParse(config);
208
+ if (!result.success) throw new MushinError("invalid_input", z.prettifyError(result.error), result.error.issues);
209
+ return result.data;
210
+ }
211
+ async create(input) {
212
+ const id = randomId();
213
+ const record = {
214
+ id,
215
+ name: input.name,
216
+ enabled: input.enabled ?? true,
217
+ adapter: {
218
+ type: input.adapter.type,
219
+ config: this.validateAdapter(input.adapter.type, input.adapter.config)
220
+ },
221
+ plugins: [],
222
+ provider: input.provider,
223
+ ...input.commands ? { commands: input.commands } : {},
224
+ createdAt: Date.now()
225
+ };
226
+ for (const item of input.plugins ?? []) {
227
+ const plugin = await this.loadBotPlugin(item.package);
228
+ validatePluginConfig(plugin, item.config ?? {});
229
+ record.plugins.push({
230
+ package: item.package,
231
+ enabled: true,
232
+ config: item.config ?? {}
233
+ });
234
+ }
235
+ this.records.push(record);
236
+ await this.save();
237
+ this.logger.info("created bot %s", this.label(record));
238
+ if (record.enabled) await this.start(id).catch(() => {});
239
+ return this.describe(record);
240
+ }
241
+ async update(id, patch) {
242
+ const record = this.get(id);
243
+ if (patch.commands !== void 0) record.commands = {
244
+ ...record.commands,
245
+ ...patch.commands
246
+ };
247
+ if (patch.name !== void 0) record.name = patch.name;
248
+ if (patch.provider !== void 0) record.provider = patch.provider ?? void 0;
249
+ if (patch.adapter) {
250
+ const secrets = this.adapterStore.get(patch.adapter.type)?.secrets ?? [];
251
+ const config = { ...patch.adapter.config };
252
+ for (const key of secrets) if (isMasked(config[key])) config[key] = record.adapter.config[key];
253
+ record.adapter = {
254
+ type: patch.adapter.type,
255
+ config: this.validateAdapter(patch.adapter.type, config)
256
+ };
257
+ }
258
+ await this.save();
259
+ this.logger.info("updated bot %s", this.label(record));
260
+ const restart = patch.name !== void 0 || patch.adapter !== void 0 || patch.provider !== void 0;
261
+ if (record.enabled && restart) await this.start(id).catch(() => {});
262
+ return this.describe(record);
263
+ }
264
+ async remove(id) {
265
+ const record = this.get(id);
266
+ await this.stopRuntime(id);
267
+ this.records = this.records.filter((item) => item !== record);
268
+ this.buffers.delete(id);
269
+ this.logs.delete(id);
270
+ this.startErrors.delete(id);
271
+ await this.save();
272
+ this.logger.info("deleted bot %s", this.label(record));
273
+ return { deleted: id };
274
+ }
275
+ startSafely(id) {
276
+ this.start(id).catch((error) => this.logger.warn("failed to start bot %s: %s", id, error));
277
+ }
278
+ async start(id) {
279
+ const record = this.get(id);
280
+ await this.stopRuntime(id);
281
+ this.startErrors.delete(id);
282
+ const adapter = this.adapterStore.get(record.adapter.type);
283
+ if (!adapter) {
284
+ const message = `Adapter "${record.adapter.type}" is not loaded; enable its plugin`;
285
+ this.startErrors.set(id, message);
286
+ this.emitStatus(id);
287
+ this.logger.warn("cannot start bot %s: %s", this.label(record), message);
288
+ throw new MushinError("unavailable", message);
289
+ }
290
+ const runtime = {
291
+ plugins: /* @__PURE__ */ new Map(),
292
+ pluginErrors: /* @__PURE__ */ new Map()
293
+ };
294
+ const loaded = [];
295
+ for (const entry of record.plugins) {
296
+ if (!entry.enabled) continue;
297
+ try {
298
+ loaded.push({
299
+ entry,
300
+ plugin: await this.loadBotPlugin(entry.package)
301
+ });
302
+ } catch (error) {
303
+ runtime.pluginErrors.set(entry.package, error instanceof Error ? error.message : String(error));
304
+ }
305
+ }
306
+ const hooks = {
307
+ record: (partial) => this.record(partial),
308
+ status: (bot) => {
309
+ runtime.bot = bot;
310
+ if (bot.status !== "connecting" && bot.status !== runtime.logged && (runtime.logged || bot.status !== "offline")) {
311
+ runtime.logged = bot.status;
312
+ if (bot.status === "error") this.logger.warn("bot %s: error (%s)", this.label(record), bot.error ?? "no details");
313
+ else this.logger.info("bot %s is %s", this.label(record), bot.status);
314
+ }
315
+ this.emitStatus(id);
316
+ },
317
+ commands: (bot) => this.commands(bot.id),
318
+ commandCalled: (bot, entry, session) => {
319
+ this.home.emit("bots/command", {
320
+ botId: bot.id,
321
+ name: entry.name,
322
+ source: entry.source,
323
+ userId: session.user.id,
324
+ channel: session.channel,
325
+ at: Date.now()
326
+ });
327
+ },
328
+ builtinCommand: (bot, entry, session) => {
329
+ if (entry.name !== HELP_COMMAND.name) return;
330
+ let entries = this.commands(bot.id);
331
+ if (bot.record.commands?.helpByRole) {
332
+ const role = session.role();
333
+ entries = entries.filter((item) => {
334
+ const required = requiredRole(item);
335
+ return !required || roleAtLeast(role, required);
336
+ });
337
+ }
338
+ return helpText(entries, bot.record.commands);
339
+ },
340
+ roleOf: (bot, userId) => this.permissionProvider?.roleOf(bot.id, userId),
341
+ appCommand: (bot, entry) => this.appCommandFor(bot.id, entry)?.handler,
342
+ usageScope: (bot, message) => {
343
+ const entry = this.usageEntry(bot.id, message.id, true);
344
+ entry.bytes = byteSize(message.segments);
345
+ return {
346
+ botId: bot.id,
347
+ messageId: message.id,
348
+ report: (event) => {
349
+ const target = this.usageEntry(bot.id, message.id, true);
350
+ if (target.events.length < USAGE_EVENTS_PER_MESSAGE) target.events.push(event);
351
+ }
352
+ };
353
+ },
354
+ sent: (bot, message, transfer) => {
355
+ const entry = this.usageEntry(bot.id, message.id, true);
356
+ Object.assign(entry, { bytes: transfer.bytes }, transfer.ms !== void 0 ? { sendMs: transfer.ms } : {}, transfer.cause ? { cause: transfer.cause } : {});
357
+ if (transfer.cause) this.usageEntry(bot.id, transfer.cause)?.replies.push(message.id);
358
+ }
359
+ };
360
+ this.runtimes.set(id, runtime);
361
+ runtime.fiber = this.home.isolate("bot").plugin({
362
+ name: `bot:${record.name}`,
363
+ apply: (ctx) => {
364
+ runtime.ctx = ctx;
365
+ this.runtimeFibers.set(ctx.fiber, id);
366
+ ctx.effect(() => () => this.runtimeFibers.delete(ctx.fiber), "bot log attribution");
367
+ const enabled = loaded.map(({ entry }) => entry.package.replace(/^@mushinjs\/bot-plugin-/, ""));
368
+ ctx.logger("bot").info("starting with the %s adapter; plugins: %s", record.adapter.type, enabled.join(", ") || "none");
369
+ for (const [name, error] of runtime.pluginErrors) ctx.logger("bot").warn("plugin %s did not load: %s", name, error);
370
+ ctx.plugin(Bot, {
371
+ record,
372
+ hooks
373
+ });
374
+ ctx.plugin(adapter.plugin, record.adapter.config);
375
+ for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, entry.config));
376
+ }
377
+ });
378
+ await runtime.fiber;
379
+ runtime.bot = runtime.ctx?.get("bot") ?? runtime.bot;
380
+ const error = fiberError(runtime.fiber);
381
+ if (error) this.logger.warn("bot %s failed to start: %s", this.label(record), error);
382
+ else this.logger.info("started bot %s with the %s adapter", this.label(record), record.adapter.type);
383
+ this.emitStatus(id);
384
+ return this.status(id);
385
+ }
386
+ async stopRuntime(id) {
387
+ const runtime = this.runtimes.get(id);
388
+ if (!runtime) return;
389
+ this.runtimes.delete(id);
390
+ await runtime.fiber?.dispose();
391
+ this.logger.info("stopped bot %s", this.label(this.records.find((item) => item.id === id) ?? id));
392
+ this.emitStatus(id);
393
+ }
394
+ async setEnabled(id, enabled) {
395
+ const record = this.get(id);
396
+ record.enabled = enabled;
397
+ await this.save();
398
+ if (enabled) return this.start(id);
399
+ await this.stopRuntime(id);
400
+ return this.status(id);
401
+ }
402
+ /** Log lines name a bot by its id; the dashboard links it to the bot. */
403
+ label(record) {
404
+ return typeof record === "string" ? record : record.id;
405
+ }
406
+ async loadBotPlugin(name) {
407
+ const entry = await this.home.manager.findPackage(name);
408
+ if (!entry) throw new MushinError("not_found", `Bot plugin "${name}" is not installed`);
409
+ if (entry.manifest.kind !== "bot") throw new MushinError("invalid_input", `"${name}" is an app plugin, not a bot plugin`);
410
+ return this.home.manager.loadPlugin(name);
411
+ }
412
+ async plugins(id) {
413
+ const record = this.get(id);
414
+ const runtime = this.runtimes.get(id);
415
+ const graph = await this.home.manager.graph();
416
+ const catalog = graph.catalog.filter((entry) => entry.manifest.kind === "bot");
417
+ return Promise.all(catalog.map(async (entry) => {
418
+ const configured = record.plugins.find((item) => item.package === entry.package);
419
+ let configSchema;
420
+ try {
421
+ configSchema = pluginSchema(await this.home.manager.loadPlugin(entry.package));
422
+ } catch {}
423
+ const fiber = runtime?.plugins.get(entry.package);
424
+ const report = dependencyReport(graph, entry.package);
425
+ const missing = this.missingApps(report.requires);
426
+ let status = configured?.enabled ? runtime ? fiberStatus(fiber) : "disabled" : "disabled";
427
+ if (status === "pending" && missing.length) status = "missing";
428
+ return {
429
+ package: entry.package,
430
+ version: entry.version,
431
+ manifest: entry.manifest,
432
+ enabled: !!configured?.enabled,
433
+ config: configured?.config ?? {},
434
+ configSchema,
435
+ status,
436
+ error: runtime?.pluginErrors.get(entry.package) ?? (status === "missing" ? describeMissing(missing) : fiberError(fiber)),
437
+ dependencies: {
438
+ requires: report.requires,
439
+ optional: report.optional
440
+ },
441
+ ...missing.length ? { missing } : {}
442
+ };
443
+ }));
444
+ }
445
+ /** Required app plugins that are not installed, do not fit or are disabled. */
446
+ missingApps(requires) {
447
+ return requires.filter((dep) => dep.problem === "not-installed" || dep.problem === "version" || dep.problem === "disabled").map((dep) => ({
448
+ package: dep.package,
449
+ range: dep.range,
450
+ reason: dep.problem,
451
+ ...dep.version ? { version: dep.version } : {}
452
+ }));
453
+ }
454
+ async enablePlugin(id, name, config) {
455
+ const record = this.get(id);
456
+ const plugin = await this.loadBotPlugin(name);
457
+ const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires);
458
+ if (missing.length) throw new MushinError("unavailable", `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing });
459
+ let entry = record.plugins.find((item) => item.package === name);
460
+ const nextConfig = config ?? entry?.config ?? {};
461
+ validatePluginConfig(plugin, nextConfig);
462
+ if (!entry) {
463
+ entry = {
464
+ package: name,
465
+ enabled: true,
466
+ config: nextConfig
467
+ };
468
+ record.plugins.push(entry);
469
+ }
470
+ entry.enabled = true;
471
+ entry.config = nextConfig;
472
+ await this.save();
473
+ this.logger.info("enabled plugin %s on bot %s", name, this.label(record));
474
+ this.reloadPlugin(id, entry, plugin);
475
+ return this.plugins(id).then((list) => list.find((item) => item.package === name));
476
+ }
477
+ async disablePlugin(id, name) {
478
+ const record = this.get(id);
479
+ const entry = record.plugins.find((item) => item.package === name);
480
+ if (!entry) throw new MushinError("not_found", `${name} is not configured on this bot`);
481
+ entry.enabled = false;
482
+ await this.save();
483
+ this.logger.info("disabled plugin %s on bot %s", name, this.label(record));
484
+ const runtime = this.runtimes.get(id);
485
+ const fiber = runtime?.plugins.get(name);
486
+ runtime?.plugins.delete(name);
487
+ await fiber?.dispose();
488
+ return this.plugins(id).then((list) => list.find((item) => item.package === name));
489
+ }
490
+ async configurePlugin(id, name, config) {
491
+ const record = this.get(id);
492
+ const entry = record.plugins.find((item) => item.package === name);
493
+ if (!entry) return this.enablePlugin(id, name, config);
494
+ const plugin = await this.loadBotPlugin(name);
495
+ validatePluginConfig(plugin, config);
496
+ entry.config = config;
497
+ await this.save();
498
+ this.logger.info("config of plugin %s on bot %s changed", name, this.label(record));
499
+ if (entry.enabled) this.reloadPlugin(id, entry, plugin);
500
+ return this.plugins(id).then((list) => list.find((item) => item.package === name));
501
+ }
502
+ reloadPlugin(id, entry, plugin) {
503
+ const runtime = this.runtimes.get(id);
504
+ if (!runtime?.ctx) return;
505
+ runtime.plugins.get(entry.package)?.dispose();
506
+ runtime.pluginErrors.delete(entry.package);
507
+ runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, entry.config));
508
+ }
509
+ /** Adds commands to every bot's list. Removed when the calling plugin unloads. */
510
+ defineCommands(provider) {
511
+ return this.ctx.effect(() => {
512
+ this.commandProviders.add(provider);
513
+ return () => this.commandProviders.delete(provider);
514
+ }, "bots.defineCommands()");
515
+ }
516
+ /**
517
+ * Answers a command on every bot (or those `bots` picks) from an app plugin, such as `/persona`.
518
+ * It answers after flows, like `/help`, and shows in each bot's command list.
519
+ */
520
+ defineCommand(def, handler, options = {}) {
521
+ const ctx = this.ctx;
522
+ const command = {
523
+ def,
524
+ plugin: ctx.fiber.name,
525
+ handler,
526
+ bots: options.bots
527
+ };
528
+ return ctx.effect(() => {
529
+ this.appCommands.add(command);
530
+ return () => this.appCommands.delete(command);
531
+ }, `bots.defineCommand(${def.name})`);
532
+ }
533
+ /** The app plugin command behind a command entry, if an app plugin answers it. */
534
+ appCommandFor(botId, entry) {
535
+ if (entry.source.kind !== "plugin") return;
536
+ return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && (item.bots?.(botId) ?? true));
537
+ }
538
+ /** Lets the permissions plugin say who is master, admin or user on each bot. */
539
+ usePermissions(provider) {
540
+ return this.ctx.effect(() => {
541
+ this.permissionProvider = provider;
542
+ return () => {
543
+ if (this.permissionProvider === provider) this.permissionProvider = void 0;
544
+ };
545
+ }, "bots.usePermissions()");
546
+ }
547
+ /** A user's role on a bot; nothing when the permissions plugin is not running. */
548
+ roleOf(botId, userId) {
549
+ return this.permissionProvider?.roleOf(botId, userId);
550
+ }
551
+ /** Commands registered on one bot: from command providers such as flows, its plugins, and the built-in help. */
552
+ commands(botId) {
553
+ const record = this.records.find((item) => item.id === botId);
554
+ if (!record) return [];
555
+ const entries = [];
556
+ for (const provider of this.commandProviders) try {
557
+ entries.push(...provider(botId));
558
+ } catch (error) {
559
+ this.logger.warn("listing commands failed: %s", error);
560
+ }
561
+ entries.push(...this.runtimes.get(botId)?.bot?.localCommands() ?? []);
562
+ for (const command of this.appCommands) {
563
+ if (command.bots && !command.bots(botId)) continue;
564
+ entries.push({
565
+ ...command.def,
566
+ botId,
567
+ source: {
568
+ kind: "plugin",
569
+ id: command.plugin,
570
+ name: command.plugin
571
+ }
572
+ });
573
+ }
574
+ if (record.commands?.help !== false && !entries.some((entry) => commandMatches(entry, HELP_COMMAND.name))) entries.push({
575
+ ...HELP_COMMAND,
576
+ botId,
577
+ source: {
578
+ kind: "builtin",
579
+ id: "help",
580
+ name: "help"
581
+ }
582
+ });
583
+ return entries;
584
+ }
585
+ /** Commands of one bot or of every bot, with names that more than one source registers. */
586
+ commandList(botId) {
587
+ if (botId) this.get(botId);
588
+ const entries = (botId ? [botId] : this.records.map((record) => record.id)).flatMap((id) => this.commands(id));
589
+ return {
590
+ commands: entries,
591
+ conflicts: commandConflicts(entries).map((item) => ({
592
+ botId: item.botId,
593
+ name: item.name,
594
+ sources: item.entries.map((entry) => entry.source)
595
+ }))
596
+ };
597
+ }
598
+ /**
599
+ * Runs a command as if a master sent it. With a target it really runs on the bot: in that group,
600
+ * or in the master's private chat, and the replies are sent. Without one it only previews where
601
+ * the message would go (through flows), so nothing is sent.
602
+ */
603
+ async runCommand(input, source) {
604
+ const record = this.get(input.bot);
605
+ const prefix = record.commands?.prefixes?.find(Boolean) ?? "/";
606
+ const text = /^\p{L}/u.test(input.command) && !input.command.startsWith(prefix) ? `${prefix}${input.command}` : input.command;
607
+ if (!input.target) {
608
+ const flows = this.home.get("flows");
609
+ if (!flows) throw new MushinError("unavailable", "Previewing a command needs the flows plugin; give a target to run it for real");
610
+ return {
611
+ simulated: true,
612
+ text,
613
+ route: await flows.route(record.id, {
614
+ text,
615
+ role: "master"
616
+ })
617
+ };
618
+ }
619
+ const bot = this.bot(record.id);
620
+ if (!bot || this.status(record.id).status !== "online") throw new MushinError("unavailable", `Bot "${record.name}" is not online`);
621
+ const permissions = this.home.get("permissions");
622
+ const userId = input.user ?? permissions?.get(record.id).masters[0];
623
+ if (!userId) throw new MushinError("invalid_input", `Bot "${record.name}" has no master; add one with permissions.update or pass user`);
624
+ if (input.target === "group" && !input.group) throw new MushinError("invalid_input", "Pass the group id to run a command in a group");
625
+ const channel = input.target === "group" ? {
626
+ type: "group",
627
+ id: input.group
628
+ } : {
629
+ type: "private",
630
+ id: userId
631
+ };
632
+ const replies = [];
633
+ const collect = (message) => {
634
+ if (message.botId === record.id && message.direction === "out" && message.channel.id === channel.id) replies.push(message);
635
+ };
636
+ const stop = this.home.on("bots/message", collect);
637
+ try {
638
+ await bot.receive({
639
+ channel,
640
+ user: { id: userId },
641
+ segments: [{
642
+ type: "text",
643
+ data: { text }
644
+ }]
645
+ }, { source });
646
+ } finally {
647
+ stop();
648
+ }
649
+ return {
650
+ simulated: false,
651
+ text,
652
+ channel,
653
+ user: userId,
654
+ replies: replies.map((reply) => segmentsToText(reply.segments))
655
+ };
656
+ }
657
+ /** Finds the bot whose context wrote a log message, by walking up from the writing fiber. */
658
+ botOf(message) {
659
+ let fiber = message.fiber?.deref();
660
+ while (fiber) {
661
+ const id = this.runtimeFibers.get(fiber);
662
+ if (id) return id;
663
+ const parent = fiber.parent?.fiber;
664
+ if (!parent || parent === fiber) return;
665
+ fiber = parent;
666
+ }
667
+ }
668
+ /** True when a log line was written inside a bot; it belongs in that bot's log, not the global one. */
669
+ isBotLog(message) {
670
+ return this.botLogSns.has(message.sn) || !!this.botOf(message);
671
+ }
672
+ captureLog(message) {
673
+ const botId = this.botOf(message);
674
+ if (!botId) return;
675
+ this.botLogSns.add(message.sn);
676
+ if (this.botLogSns.size > 2e3) this.botLogSns.delete(this.botLogSns.values().next().value);
677
+ const line = {
678
+ botId,
679
+ sn: message.sn,
680
+ ts: message.ts,
681
+ type: message.type,
682
+ name: message.name,
683
+ tag: logTag(message.name),
684
+ text: Logger.format(plainExporter, message)
685
+ };
686
+ let buffer = this.logs.get(botId);
687
+ if (!buffer) this.logs.set(botId, buffer = []);
688
+ buffer.push(line);
689
+ if (buffer.length > LOG_BUFFER_SIZE) buffer.splice(0, buffer.length - LOG_BUFFER_SIZE);
690
+ this.home.emit("bots/log", line);
691
+ const day = new Date(line.ts).toISOString().slice(0, 10);
692
+ this.home.storage.append(`logs/${botId}/${day}`, line).catch(() => {});
693
+ }
694
+ async logLines(id, limit = 200) {
695
+ this.get(id);
696
+ let buffer = this.logs.get(id);
697
+ if (!buffer) {
698
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
699
+ buffer = (await this.home.storage.tail(`logs/${id}/${day}`, LOG_BUFFER_SIZE)).map((line) => line.tag ? line : {
700
+ ...line,
701
+ tag: logTag(line.name)
702
+ });
703
+ this.logs.set(id, buffer);
704
+ }
705
+ return buffer.slice(-limit);
706
+ }
707
+ /** Messages recorded since Mushin started, for the live conversation. */
708
+ recent = /* @__PURE__ */ new WeakSet();
709
+ /** What handling each recent message cost, in memory only; see `bots.usage`. */
710
+ usages = /* @__PURE__ */ new Map();
711
+ usageEntry(botId, messageId, create = false) {
712
+ const key = `${botId}:${messageId}`;
713
+ let entry = this.usages.get(key);
714
+ if (!entry && create) {
715
+ this.usages.set(key, entry = {
716
+ events: [],
717
+ replies: []
718
+ });
719
+ if (this.usages.size > USAGE_MESSAGES) this.usages.delete(this.usages.keys().next().value);
720
+ }
721
+ return entry;
722
+ }
723
+ /** A message's costs, and for a reply the costs of the message it answered. */
724
+ usage(botId, messageId) {
725
+ const entry = this.usageEntry(botId, messageId);
726
+ if (!entry) return null;
727
+ const cause = entry.cause ? this.usageEntry(botId, entry.cause) : void 0;
728
+ return {
729
+ ...entry,
730
+ ...cause ? { causeEvents: cause.events } : {}
731
+ };
732
+ }
733
+ record(partial) {
734
+ const record = {
735
+ ...partial,
736
+ id: randomId(8),
737
+ type: messageType(partial.segments),
738
+ platforms: this.platformsFor(partial.segments)
739
+ };
740
+ let buffer = this.buffers.get(record.botId);
741
+ if (!buffer) this.buffers.set(record.botId, buffer = []);
742
+ buffer.push(record);
743
+ if (buffer.length > BUFFER_SIZE) buffer.splice(0, buffer.length - BUFFER_SIZE);
744
+ const day = new Date(record.timestamp).toISOString().slice(0, 10);
745
+ this.home.storage.append(`messages/${record.botId}/${day}`, record).catch((error) => {
746
+ this.logger.warn("failed to write message log: %s", error);
747
+ });
748
+ this.recent.add(record);
749
+ this.archive?.add(record);
750
+ this.home.emit("bots/message", record);
751
+ return record;
752
+ }
753
+ /**
754
+ * Recent messages of a bot, oldest first. With the database plugin, a channel's history and
755
+ * older pages (`before`) come from the database; otherwise from today's log and memory.
756
+ */
757
+ async messages(id, options = {}) {
758
+ this.get(id);
759
+ const limit = options.limit ?? 100;
760
+ if (options.sinceStart) return (this.buffers.get(id) ?? []).filter((record) => this.recent.has(record) && (!options.channel || record.channel.id === options.channel)).slice(-limit);
761
+ const archive = this.archive?.ready ? this.archive : void 0;
762
+ if (archive && (options.channel || options.before)) return archive.query(id, {
763
+ ...options,
764
+ limit
765
+ });
766
+ let buffer = this.buffers.get(id);
767
+ if (!buffer) {
768
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
769
+ buffer = archive ? await archive.query(id, { limit: BUFFER_SIZE }) : await this.home.storage.tail(`messages/${id}/${day}`, BUFFER_SIZE);
770
+ const current = this.buffers.get(id);
771
+ if (current) buffer = [...buffer.filter((item) => !current.some((record) => record.id === item.id)), ...current].slice(-500);
772
+ this.buffers.set(id, buffer);
773
+ }
774
+ if (options.before) buffer = buffer.filter((record) => record.timestamp < options.before);
775
+ return (options.channel ? buffer.filter((record) => record.channel.id === options.channel) : buffer).slice(-limit);
776
+ }
777
+ /** Channels seen recently, newest first, for the live view's channel list. */
778
+ async channels(id, options = {}) {
779
+ const seen = /* @__PURE__ */ new Map();
780
+ for (const record of await this.messages(id, {
781
+ limit: BUFFER_SIZE,
782
+ sinceStart: options.sinceStart
783
+ })) {
784
+ const key = `${record.channel.type}:${record.channel.id}`;
785
+ const text = record.segments.map((s) => s.type === "text" ? s.data.text : `[${s.type}]`).join("");
786
+ seen.set(key, {
787
+ ...record.channel,
788
+ name: record.channel.name ?? seen.get(key)?.name,
789
+ lastAt: record.timestamp,
790
+ lastText: text.slice(0, 80)
791
+ });
792
+ }
793
+ return [...seen.values()].sort((a, b) => b.lastAt - a.lastAt);
794
+ }
795
+ /** How a command reads a message; see the `bots.tryCommand` action. */
796
+ tryCommand(input) {
797
+ const own = input.prefixes?.filter(Boolean) ?? [];
798
+ const record = input.bot ? this.records.find((item) => item.id === input.bot) : void 0;
799
+ const prefixes = own.length ? own : record?.commands?.prefixes?.filter(Boolean).length ? record.commands.prefixes.filter(Boolean) : DEFAULT_PREFIXES;
800
+ const def = {
801
+ name: input.name,
802
+ args: input.args,
803
+ prefixes
804
+ };
805
+ const usage = commandUsage(def);
806
+ const parsed = splitCommand(input.text, prefixes);
807
+ if (!parsed) return {
808
+ matched: false,
809
+ reason: "prefix",
810
+ prefixes,
811
+ usage
812
+ };
813
+ if (!commandMatches({
814
+ name: input.name,
815
+ aliases: input.aliases
816
+ }, parsed.name)) return {
817
+ matched: false,
818
+ reason: "name",
819
+ prefixes,
820
+ usage
821
+ };
822
+ return {
823
+ matched: true,
824
+ prefix: parsed.prefix,
825
+ rest: parsed.rest,
826
+ usage,
827
+ ...parseArgs(input.args, parsed.rest)
828
+ };
829
+ }
830
+ /**
831
+ * People or groups the bots have seen recently, newest first, as `{ value, label, group }`
832
+ * choices: the label is `name (id)`, the group the bot's name. For lists such as a permission
833
+ * node's allow and block lists.
834
+ */
835
+ async seen(kind) {
836
+ const found = /* @__PURE__ */ new Map();
837
+ for (const record of this.records) for (const message of await this.messages(record.id, { limit: BUFFER_SIZE }).catch(() => [])) {
838
+ const id = kind === "user" ? message.direction === "in" ? message.user.id : "" : message.channel.type === "group" ? message.channel.id : "";
839
+ if (!id || isSandbox(message.channel)) continue;
840
+ const name = kind === "user" ? message.user.name : message.channel.name;
841
+ const previous = found.get(id);
842
+ const label = name || (previous?.label.endsWith(`(${id})`) ? previous.label : "");
843
+ found.set(id, {
844
+ value: id,
845
+ label: label && !label.endsWith(`(${id})`) ? `${label} (${id})` : label || id,
846
+ group: record.name,
847
+ at: message.timestamp
848
+ });
849
+ }
850
+ return [...found.values()].sort((a, b) => b.at - a.at).map(({ at: _, ...choice }) => choice);
851
+ }
852
+ /** The account's friends and groups, from the platform; empty when the bot is offline or the adapter cannot tell. */
853
+ async contacts(id) {
854
+ const bot = this.bot(id);
855
+ if (!bot || bot.status !== "online") return [];
856
+ return bot.contacts();
857
+ }
858
+ /** The sandbox's test user writes to the bot; see `Bot.sandbox`. */
859
+ sandbox(id, text) {
860
+ const bot = this.bot(id);
861
+ if (!bot) throw new MushinError("unavailable", "The bot is not running");
862
+ bot.sandbox(text);
863
+ return { ok: true };
864
+ }
865
+ async sendManual(id, channel, text) {
866
+ const bot = this.bot(id);
867
+ if (!bot) throw new MushinError("unavailable", "The bot is not running");
868
+ return bot.deliver(channel, text, { source: { kind: "manual" } });
869
+ }
870
+ /** A fresh address of a message's image, video or file, from the platform. */
871
+ async media(id, segment, options) {
872
+ const bot = this.bot(id);
873
+ if (!bot) throw new MushinError("unavailable", "The bot is not running");
874
+ const media = await bot.media(segment, options);
875
+ if (!media) throw new MushinError("not_found", "The platform no longer has this file");
876
+ return media;
877
+ }
878
+ /** The messages of a forwarded chat history, from the platform. */
879
+ async forwarded(id, forward) {
880
+ const bot = this.bot(id);
881
+ if (!bot) throw new MushinError("unavailable", "The bot is not running");
882
+ return { messages: await bot.forward(forward) };
883
+ }
884
+ *defineActions() {
885
+ const actions = this.home.actions;
886
+ yield actions.define({
887
+ name: "bots.adapters",
888
+ description: "List loaded adapter types (e.g. \"onebot\") with their config JSON Schemas.",
889
+ risk: "read",
890
+ input: z.object({}),
891
+ handler: () => this.adapters()
892
+ });
893
+ yield actions.define({
894
+ name: "bots.list",
895
+ description: "List bots with their connection status, adapter and enabled plugins. Secrets are masked.",
896
+ risk: "read",
897
+ input: z.object({}),
898
+ handler: () => this.list()
899
+ });
900
+ yield actions.define({
901
+ name: "bots.get",
902
+ description: "Get one bot with its status.",
903
+ risk: "read",
904
+ input: idInput,
905
+ handler: ({ id }) => this.describe(this.get(id))
906
+ });
907
+ yield actions.define({
908
+ name: "bots.create",
909
+ 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.",
910
+ risk: "write",
911
+ input: z.object({
912
+ name: z.string().min(1),
913
+ adapter: adapterInput,
914
+ plugins: z.array(z.object({
915
+ package: z.string(),
916
+ config: z.record(z.string(), z.any()).optional()
917
+ })).optional().describe("Bot plugins to enable right away, e.g. @mushinjs/bot-plugin-llm-chat"),
918
+ enabled: z.boolean().optional(),
919
+ provider: z.string().optional().describe("Default provider or model profile id for this bot's LLM plugins"),
920
+ commands: commandSettingsInput.optional()
921
+ }),
922
+ handler: (input) => this.create(input)
923
+ });
924
+ yield actions.define({
925
+ name: "bots.update",
926
+ 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.",
927
+ risk: "write",
928
+ input: idInput.extend({
929
+ name: z.string().min(1).optional(),
930
+ adapter: adapterInput.optional(),
931
+ provider: z.string().nullable().optional(),
932
+ commands: commandSettingsInput.optional().describe("Command prefixes and the built-in /help; changing only these does not restart the bot")
933
+ }),
934
+ handler: ({ id, ...patch }) => this.update(id, patch)
935
+ });
936
+ yield actions.define({
937
+ name: "commands.list",
938
+ description: "List the commands (such as /help, /checkin) each bot answers, with where each comes from: a flow's command node, a bot plugin or the built-in help. Also lists names that two sources register on the same bot.",
939
+ risk: "read",
940
+ input: z.object({ bot: z.string().optional().describe("Bot id from bots.list; all bots when omitted") }),
941
+ handler: ({ bot }) => this.commandList(bot)
942
+ });
943
+ yield actions.define({
944
+ name: "bots.commands.run",
945
+ description: "Run a bot command such as /checkin as the bot's master. With target \"group\" (and the group id) or \"master\" (the master's private chat) it runs for real and the bot sends its replies there; without a target it only previews which flow or plugin would answer, and sends nothing.",
946
+ risk: "write",
947
+ input: z.object({
948
+ bot: z.string().describe("Bot id from bots.list"),
949
+ command: z.string().min(1).describe("The command with its arguments, e.g. \"/checkin\" or \"/score 85\""),
950
+ target: z.enum(["master", "group"]).optional().describe("Where to run it for real; omit to only preview"),
951
+ group: z.string().optional().describe("Group id, with target \"group\""),
952
+ user: z.string().optional().describe("Run as this user id instead of the first master")
953
+ }),
954
+ handler: (input, caller) => this.runCommand(input, caller.kind === "agent" && caller.session ? {
955
+ kind: "agent",
956
+ session: caller.session
957
+ } : void 0)
958
+ });
959
+ yield actions.define({
960
+ name: "bots.delete",
961
+ description: "Delete a bot and its settings. Message logs on disk are kept.",
962
+ risk: "dangerous",
963
+ input: idInput,
964
+ handler: ({ id }) => this.remove(id)
965
+ });
966
+ yield actions.define({
967
+ name: "bots.start",
968
+ description: "Enable and start (or restart) a bot.",
969
+ risk: "write",
970
+ input: idInput,
971
+ handler: ({ id }) => this.setEnabled(id, true)
972
+ });
973
+ yield actions.define({
974
+ name: "bots.stop",
975
+ description: "Stop and disable a bot.",
976
+ risk: "write",
977
+ input: idInput,
978
+ handler: ({ id }) => this.setEnabled(id, false)
979
+ });
980
+ yield actions.define({
981
+ name: "bots.plugins.list",
982
+ description: "List every installed bot plugin with whether it is enabled on this bot, its config and status.",
983
+ risk: "read",
984
+ input: idInput,
985
+ handler: ({ id }) => this.plugins(id)
986
+ });
987
+ yield actions.define({
988
+ name: "bots.plugins.enable",
989
+ description: "Enable a bot plugin on one bot, optionally with config.",
990
+ risk: "write",
991
+ input: pluginInput.extend({ config: z.record(z.string(), z.any()).optional() }),
992
+ handler: ({ id, package: name, config }) => this.enablePlugin(id, name, config)
993
+ });
994
+ yield actions.define({
995
+ name: "bots.plugins.disable",
996
+ description: "Disable a bot plugin on one bot. Its config is kept.",
997
+ risk: "write",
998
+ input: pluginInput,
999
+ handler: ({ id, package: name }) => this.disablePlugin(id, name)
1000
+ });
1001
+ yield actions.define({
1002
+ name: "bots.plugins.configure",
1003
+ description: "Replace a bot plugin's config on one bot and reload it.",
1004
+ risk: "write",
1005
+ input: pluginInput.extend({ config: z.record(z.string(), z.any()) }),
1006
+ handler: ({ id, package: name, config }) => this.configurePlugin(id, name, config)
1007
+ });
1008
+ yield actions.define({
1009
+ name: "bots.messages",
1010
+ 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.",
1011
+ risk: "read",
1012
+ input: idInput.extend({
1013
+ limit: z.number().int().min(1).max(BUFFER_SIZE).optional(),
1014
+ channel: z.string().optional().describe("Group or user id to filter by"),
1015
+ before: z.number().optional().describe("Only messages sent before this time (ms since 1970), to page back through older messages; with the database plugin the history goes back to the first message"),
1016
+ sinceStart: z.boolean().optional().describe("Only messages received or sent since Mushin started")
1017
+ }),
1018
+ handler: ({ id, ...options }) => this.messages(id, options)
1019
+ });
1020
+ yield actions.define({
1021
+ name: "bots.media",
1022
+ description: "Fetch an image, video, voice or file from a message again, since the address in the message can expire. Returns { url, name?, size? }; with inline, an image comes back as a data URL.",
1023
+ risk: "read",
1024
+ input: idInput.extend({
1025
+ segment: z.object({
1026
+ type: z.string(),
1027
+ data: z.record(z.string(), z.any())
1028
+ }).describe("The segment from the message record"),
1029
+ channel: z.object({
1030
+ type: z.enum(["group", "private"]),
1031
+ id: z.string()
1032
+ }).optional().describe("Where the message was sent; group files need it"),
1033
+ inline: z.boolean().optional().describe("Return the bytes as a data URL, for showing an image")
1034
+ }),
1035
+ handler: ({ id, segment, channel, inline }) => this.media(id, segment, {
1036
+ channel,
1037
+ inline
1038
+ })
1039
+ });
1040
+ yield actions.define({
1041
+ name: "bots.forward",
1042
+ description: "The messages of a forwarded chat history (a forward segment's id), oldest first, each with its sender, time and segments.",
1043
+ risk: "read",
1044
+ input: idInput.extend({ forward: z.string().min(1).describe("The id in the forward segment") }),
1045
+ handler: ({ id, forward }) => this.forwarded(id, forward)
1046
+ });
1047
+ yield actions.define({
1048
+ name: "bots.logs",
1049
+ description: "Recent log lines of one bot, oldest first: connection events, adapter errors, plugin warnings, and why LLM chat skipped messages. Read this first when a bot misbehaves.",
1050
+ risk: "read",
1051
+ input: idInput.extend({ limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional() }),
1052
+ handler: ({ id, limit }) => this.logLines(id, limit)
1053
+ });
1054
+ yield actions.define({
1055
+ name: "bots.channels",
1056
+ description: "Channels (groups and private chats) a bot has seen recently.",
1057
+ risk: "read",
1058
+ input: idInput.extend({ sinceStart: z.boolean().optional().describe("Only channels with messages since Mushin started") }),
1059
+ handler: ({ id, sinceStart }) => this.channels(id, { sinceStart })
1060
+ });
1061
+ yield actions.define({
1062
+ name: "bots.tryCommand",
1063
+ description: "Check how a message would be read by a command (name, prefixes, arguments) without running anything: whether it matches and the value of each argument, or what is wrong.",
1064
+ risk: "read",
1065
+ input: z.object({
1066
+ name: z.string(),
1067
+ aliases: z.array(z.string()).optional(),
1068
+ prefixes: z.array(z.string()).optional().describe("The command's own prefixes; empty uses the bot's"),
1069
+ args: z.array(z.object({
1070
+ name: z.string(),
1071
+ type: z.enum([
1072
+ "text",
1073
+ "number",
1074
+ "boolean",
1075
+ "user",
1076
+ "choice"
1077
+ ]),
1078
+ optional: z.boolean().optional(),
1079
+ rest: z.boolean().optional(),
1080
+ default: z.union([
1081
+ z.string(),
1082
+ z.number(),
1083
+ z.boolean()
1084
+ ]).optional(),
1085
+ choices: z.array(z.string()).optional()
1086
+ })).default([]),
1087
+ text: z.string(),
1088
+ bot: z.string().optional().describe("Bot whose prefixes apply when the command has none of its own")
1089
+ }),
1090
+ handler: (input) => this.tryCommand(input)
1091
+ });
1092
+ yield actions.define({
1093
+ name: "bots.userChoices",
1094
+ description: "People the bots have seen recently, as { value: user id, label, group: bot } choices.",
1095
+ risk: "read",
1096
+ input: z.object({}),
1097
+ handler: () => this.seen("user")
1098
+ });
1099
+ yield actions.define({
1100
+ name: "bots.groupChoices",
1101
+ description: "Groups the bots have seen recently, as { value: group id, label, group: bot } choices.",
1102
+ risk: "read",
1103
+ input: z.object({}),
1104
+ handler: () => this.seen("group")
1105
+ });
1106
+ yield actions.define({
1107
+ name: "bots.usage",
1108
+ description: "What one recent message cost, kept in memory since Mushin started: model requests made while handling it (kind chat, vision, decision, embed or a plugin's own, with plugin, model, tokens and time), its size in bytes, and for a sent message how long sending took and which message it answered.",
1109
+ risk: "read",
1110
+ input: idInput.extend({ message: z.string().describe("Message record id from bots.messages") }),
1111
+ handler: ({ id, message }) => this.usage(id, message)
1112
+ });
1113
+ yield actions.define({
1114
+ name: "bots.contacts",
1115
+ description: "The friends and groups of a bot's account, from the platform (OneBot: get_friend_list and get_group_list). Empty when the bot is offline.",
1116
+ risk: "read",
1117
+ input: idInput,
1118
+ handler: ({ id }) => this.contacts(id)
1119
+ });
1120
+ yield actions.define({
1121
+ name: "bots.sandbox",
1122
+ description: "Write to a bot as the test user of its sandbox conversation: a private chat that only exists in Mushin. The bot answers through its flows and plugins; nothing reaches the platform. Start with \"@\" to mention the bot.",
1123
+ risk: "write",
1124
+ input: idInput.extend({ text: z.string().min(1) }),
1125
+ handler: ({ id, text }) => this.sandbox(id, text)
1126
+ });
1127
+ yield actions.define({
1128
+ name: "bots.send",
1129
+ description: "Send a text message from a bot to a group or private chat.",
1130
+ risk: "write",
1131
+ input: idInput.extend({
1132
+ channel: z.object({
1133
+ type: z.enum(["group", "private"]),
1134
+ id: z.string()
1135
+ }),
1136
+ text: z.string().min(1)
1137
+ }),
1138
+ handler: ({ id, channel, text }) => this.sendManual(id, channel, text)
1139
+ });
1140
+ }
1141
+ };
1142
+ export { BotManager };
1143
+
1144
+ //# sourceMappingURL=manager.js.map