@mushinjs/plugin-bots 0.4.0-next.20261127155650 → 0.4.0-next.20261128121614
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/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/manager.d.ts +11 -0
- package/dist/manager.js +8 -3
- package/dist/manager.js.map +1 -1
- package/package.json +5 -4
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, LogFilter, MessageUsage, ProjectChatPlugin, RunCommandInput } from "./manager.js";
|
|
1
|
+
import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, LogFilter, MessageUsage, ProjectChatPlugin, RunCommandInput, byTime } from "./manager.js";
|
|
2
2
|
import { MessageArchive, MessageQuery, MessageRow, fromRow, toRow } from "./archive.js";
|
|
3
3
|
import { AppCommandTarget, BUILTIN_PRIORITY, Bot, BotHooks, CommandHandler, Middleware, MiddlewareOptions, PluginRunReport, Sendable, Session, byteSize } from "./bot.js";
|
|
4
4
|
import { ArgValue, ArgsResult, CommandArg, CommandArgType, CommandDef, CommandEntry, CommandSettings, CommandSource, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ParsedCommand, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
|
|
5
5
|
import { MEDIA_SEGMENTS, MediaSource, mediaBytes, mediaSource, mimeOf } from "./media.js";
|
|
6
6
|
import { AdapterType, BotConnectionInfo, BotEvent, BotPluginEntry, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PermissionProvider, PluginRun, ROLE_RANK, ResolvedMedia, SANDBOX_CHANNEL, SANDBOX_USER, SourcedContent, Transport, isSandbox, roleAtLeast } from "./types.js";
|
|
7
|
-
export { AdapterType, AppCommandTarget, ArgValue, ArgsResult, BUILTIN_PRIORITY, Bot, BotConnectionInfo, BotEvent, BotHooks, BotLogLine, BotManager, BotPluginEntry, BotRecord, BotRole, BotStatus, BotStatusInfo, CommandArg, CommandArgType, CommandCall, CommandDef, CommandEntry, CommandHandler, CommandProvider, CommandSettings, CommandSource, Contact, ContactResolver, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, LogFilter, MEDIA_SEGMENTS, MediaResolver, MediaSource, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, PluginRun, PluginRunReport, ProjectChatPlugin, ROLE_RANK, ResolvedMedia, RunCommandInput, SANDBOX_CHANNEL, SANDBOX_USER, Sendable, Session, SourcedContent, Transport, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, BotManager as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
|
|
7
|
+
export { AdapterType, AppCommandTarget, ArgValue, ArgsResult, BUILTIN_PRIORITY, Bot, BotConnectionInfo, BotEvent, BotHooks, BotLogLine, BotManager, BotPluginEntry, BotRecord, BotRole, BotStatus, BotStatusInfo, CommandArg, CommandArgType, CommandCall, CommandDef, CommandEntry, CommandHandler, CommandProvider, CommandSettings, CommandSource, Contact, ContactResolver, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, LogFilter, MEDIA_SEGMENTS, MediaResolver, MediaSource, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, PluginRun, PluginRunReport, ProjectChatPlugin, ROLE_RANK, ResolvedMedia, RunCommandInput, SANDBOX_CHANNEL, SANDBOX_USER, Sendable, Session, SourcedContent, Transport, argTypeLabel, byTime, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, BotManager as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BotManager } from "./manager.js";
|
|
1
|
+
import { BotManager, byTime } from "./manager.js";
|
|
2
2
|
import { MessageArchive, fromRow, toRow } from "./archive.js";
|
|
3
3
|
import { BUILTIN_PRIORITY, Bot, Session, byteSize } from "./bot.js";
|
|
4
4
|
import { DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
|
|
@@ -6,6 +6,6 @@ import { MEDIA_SEGMENTS, mediaBytes, mediaSource, mimeOf } from "./media.js";
|
|
|
6
6
|
import { ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, isSandbox, roleAtLeast } from "./types.js";
|
|
7
7
|
// src/index.ts
|
|
8
8
|
var src_default = BotManager;
|
|
9
|
-
export { BUILTIN_PRIORITY, Bot, BotManager, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, MEDIA_SEGMENTS, MessageArchive, ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, Session, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, src_default as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
|
|
9
|
+
export { BUILTIN_PRIORITY, Bot, BotManager, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, MEDIA_SEGMENTS, MessageArchive, ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, Session, argTypeLabel, byTime, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, src_default as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
|
|
10
10
|
|
|
11
11
|
//# sourceMappingURL=index.js.map
|
package/dist/manager.d.ts
CHANGED
|
@@ -41,6 +41,17 @@ export interface LogFilter {
|
|
|
41
41
|
/** This level and above. */
|
|
42
42
|
level?: 'debug' | 'info' | 'warn' | 'error';
|
|
43
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* Orders log lines read from the daily files. Appending is asynchronous, so lines written in the same
|
|
46
|
+
* millisecond can land in the file out of order; the sequence number breaks the tie.
|
|
47
|
+
*/
|
|
48
|
+
export declare const byTime: (a: {
|
|
49
|
+
ts: number;
|
|
50
|
+
sn: number;
|
|
51
|
+
}, b: {
|
|
52
|
+
ts: number;
|
|
53
|
+
sn: number;
|
|
54
|
+
}) => number;
|
|
44
55
|
/** A message ran a registered command. */
|
|
45
56
|
export interface CommandCall {
|
|
46
57
|
botId: string;
|
package/dist/manager.js
CHANGED
|
@@ -22,6 +22,11 @@ const LEVELS = [
|
|
|
22
22
|
"warn",
|
|
23
23
|
"error"
|
|
24
24
|
];
|
|
25
|
+
/**
|
|
26
|
+
* Orders log lines read from the daily files. Appending is asynchronous, so lines written in the same
|
|
27
|
+
* millisecond can land in the file out of order; the sequence number breaks the tie.
|
|
28
|
+
*/
|
|
29
|
+
const byTime = (a, b) => a.ts - b.ts || a.sn - b.sn;
|
|
25
30
|
const DAY = 864e5;
|
|
26
31
|
const STORAGE_KEY = "bots";
|
|
27
32
|
const BUFFER_SIZE = 500;
|
|
@@ -1006,12 +1011,12 @@ var BotManager = class extends Service {
|
|
|
1006
1011
|
const first = Date.parse(new Date(Math.max(since, until - 31 * DAY)).toISOString().slice(0, 10));
|
|
1007
1012
|
for (let at = first; at <= until; at += DAY) days.push(new Date(at).toISOString().slice(0, 10));
|
|
1008
1013
|
lines = (await Promise.all(days.map((day) => this.home.storage.tail(`logs/${id}/${day}`, 1e5)))).flat();
|
|
1009
|
-
lines = lines.filter((line) => line.ts >= (filter.since ?? 0) && line.ts <= until);
|
|
1014
|
+
lines = lines.filter((line) => line.ts >= (filter.since ?? 0) && line.ts <= until).sort(byTime);
|
|
1010
1015
|
} else {
|
|
1011
1016
|
let buffer = this.logs.get(id);
|
|
1012
1017
|
if (!buffer) {
|
|
1013
1018
|
const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1014
|
-
buffer = await this.home.storage.tail(`logs/${id}/${day}`, LOG_BUFFER_SIZE);
|
|
1019
|
+
buffer = (await this.home.storage.tail(`logs/${id}/${day}`, LOG_BUFFER_SIZE)).sort(byTime);
|
|
1015
1020
|
this.logs.set(id, buffer);
|
|
1016
1021
|
}
|
|
1017
1022
|
lines = buffer;
|
|
@@ -1499,6 +1504,6 @@ var BotManager = class extends Service {
|
|
|
1499
1504
|
});
|
|
1500
1505
|
}
|
|
1501
1506
|
};
|
|
1502
|
-
export { BotManager };
|
|
1507
|
+
export { BotManager, byTime };
|
|
1503
1508
|
|
|
1504
1509
|
//# sourceMappingURL=manager.js.map
|
package/dist/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import {\n type ChannelInfo, Context, currentPackageName, type DependencyGraph, describeMissing, dependencyReport, envReference, type LogTag, type MissingDependency, logTag, type Exporter, type Fiber, fiberError, fiberStatus, isMasked, Logger, mask, type Message,\n type MessageRecord, messageType, MushinError, type Plugin, type ProvidedItem, type Provenance, pluginSchema, randomId, resolveEnvReferences, type Segment, segmentsToText, Service, toJsonSchema,\n type UsageEvent, usage, validatePluginConfig, z, maskSecrets, restoreMasked, secretFields,\n} from '@mushinjs/core'\nimport type {} from '@mushinjs/plugin-storage'\nimport { MessageArchive } from './archive'\nimport { Bot, type BotHooks, byteSize, type PluginRunReport, type Session } from './bot'\nimport { type CommandArg, type CommandDef, type CommandEntry, commandConflicts, type CommandSettings, commandMatches, commandUsage, DEFAULT_PREFIXES, helpText, parseArgs, requiredRole, splitCommand } from './commands'\nimport { type AdapterType, type BotPluginEntry, type BotRecord, type BotStatus, isSandbox, type PermissionProvider, type PluginRun, roleAtLeast } from './types'\n\ndeclare module '@mushinjs/core' {\n interface Context {\n bots: BotManager\n bot: Bot\n }\n\n interface Events {\n 'bots/changed'(): void\n 'bots/status'(status: BotStatusInfo): void\n 'bots/message'(record: MessageRecord): void\n 'bots/log'(line: BotLogLine): void\n 'bots/command'(call: CommandCall): void\n 'bots/run'(run: PluginRun): void\n }\n}\n\n/** One log line written inside a bot's context: its adapter, its plugins, or the bot service itself. */\nexport interface BotLogLine {\n botId: string\n sn: number\n ts: number\n type: string\n name: string\n tag: LogTag\n text: string\n /** Record id of the message being handled when the line was written. */\n message?: string\n}\n\n/** A time as an ISO date-time or ms since the epoch, as ms. */\nconst timeInput = z.union([z.number(), z.string()]).transform((value, check) => {\n const ms = typeof value === 'number' ? value : Date.parse(value)\n if (Number.isNaN(ms)) {\n check.addIssue({ code: 'custom', message: `\"${value}\" is not a time` })\n return z.NEVER\n }\n return ms\n})\n\n/** What `bots.logs` can narrow the lines to. */\nexport interface LogFilter {\n limit?: number\n /** Only lines written while handling this message (its record id). */\n message?: string\n /** Times in ms since the epoch. */\n since?: number\n until?: number\n /** Case-insensitive text the line contains. */\n query?: string\n /** This level and above. */\n level?: 'debug' | 'info' | 'warn' | 'error'\n}\n\nconst LEVELS = ['debug', 'info', 'warn', 'error']\nconst DAY = 86_400_000\n\n/** A message ran a registered command. */\nexport interface CommandCall {\n botId: string\n name: string\n source: CommandEntry['source']\n userId: string\n channel: ChannelInfo\n at: number\n}\n\nexport interface RunCommandInput {\n bot: string\n command: string\n target?: 'master' | 'group'\n group?: string\n user?: string\n}\n\n/** Lists commands a plugin provides on a bot, e.g. the command nodes of the flows attached to it. */\nexport type CommandProvider = (botId: string) => CommandEntry[]\n\n/**\n * A command an app plugin answers on the bots it is turned on for (`BotRecord.appPlugins`), or, when the plugin\n * picks the bots itself, on the bots `bots` picks.\n */\ninterface AppCommand {\n def: CommandDef\n plugin: string\n fiber: Fiber\n handler: (session: Session) => Promise<unknown> | unknown\n bots?: (botId: string) => boolean\n}\n\n/** A chat plugin across the project, for the Plugins page: its switch and the bots that have it on. */\nexport interface ProjectChatPlugin {\n package: string\n kind: 'app' | 'bot'\n /** For a bot plugin, its project switch; an app plugin's is its entry on the Plugins page. */\n enabled: boolean\n /** An essential bot plugin has no project switch. */\n essential?: boolean\n /** Bots that have it on. */\n bots: string[]\n}\n\nexport interface BotStatusInfo {\n id: string\n status: BotStatus\n error?: string\n selfId?: string\n selfName?: string\n selfAvatar?: string\n /** An address that adds the bot to a group or server, from `bot.setInvite()`. */\n invite?: string\n}\n\ninterface Runtime {\n fiber?: Fiber\n ctx?: Context\n bot?: Bot\n plugins: Map<string, Fiber>\n pluginErrors: Map<string, string>\n /** Last connection status written to the global log. */\n logged?: BotStatus\n}\n\nconst STORAGE_KEY = 'bots'\nconst BUFFER_SIZE = 500\n/** Plugin runs kept in memory for each bot; older ones stay in the daily files. */\nconst RUN_BUFFER_SIZE = 300\nconst LOG_BUFFER_SIZE = 500\n// Bot logs include debug lines (e.g. why llm-chat skipped a message); the main log stream does not.\nconst LOG_LEVEL_DEBUG = 3\nconst plainExporter: Exporter = { colors: false, export() {} }\n\nconst adapterInput = z.object({\n type: z.string().describe('Adapter type id from bots.adapters, e.g. \"onebot\"'),\n config: z.record(z.string(), z.any()).describe('Adapter config matching the schema from bots.adapters'),\n})\n\n/** Messages whose costs are kept; older ones are forgotten. */\nconst USAGE_MESSAGES = 2000\n/** A runaway loop on one message stops being recorded after this many costs. */\nconst USAGE_EVENTS_PER_MESSAGE = 200\n\n/** What handling one message cost; see `bots.usage`. */\nexport interface MessageUsage {\n events: UsageEvent[]\n /** Size on the wire, roughly. */\n bytes?: number\n /** For a sent message: how long the platform took to accept it. */\n sendMs?: number\n /** For a sent message: the incoming message being handled when it was sent. */\n cause?: string\n /** For an incoming message: what was sent while handling it. */\n replies: string[]\n}\n\nconst idInput = z.object({ id: z.string().describe('Bot id from bots.list') })\nconst commandSettingsInput = z.object({\n prefixes: z.array(z.string().min(1)).optional().describe('Command prefixes; default [\"/\"]'),\n help: z.boolean().optional().describe('Answer /help with the list of commands; on unless false'),\n helpTitle: z.string().optional().describe('First line of the /help menu'),\n admins: z.array(z.string()).optional().describe('Deprecated: admins now live in the permissions plugin (permissions.update)'),\n helpByRole: z.boolean().optional().describe('/help lists only the commands the asker may run'),\n})\n\n/** Answers `/help` when nothing else on the bot registers a command called help. */\nconst HELP_COMMAND = { name: 'help', description: '列出所有指令' }\n\nconst pluginInput = idInput.extend({ package: z.string().describe('Plugin package name from bots.plugins.list: a bot plugin, or an app plugin with chat commands') })\n\n/**\n * Owns bot records and runs each enabled bot in its own isolated context:\n * the `bot` service, the adapter connection and the bot's plugins live there.\n */\nexport class BotManager extends Service {\n static inject = ['storage', 'actions', 'manager']\n\n private home: Context\n private records: BotRecord[] = []\n private adapterStore = new Map<string, AdapterType>()\n private runtimes = new Map<string, Runtime>()\n private startErrors = new Map<string, string>()\n private buffers = new Map<string, MessageRecord[]>()\n /** Messages in the database, when the database plugin runs. */\n private archive?: MessageArchive\n /** Runtime fiber of each running bot, to attribute log lines to the bot that wrote them. */\n private runtimeFibers = new Map<Fiber, string>()\n private logs = new Map<string, BotLogLine[]>()\n /** Sequence numbers of recent bot log lines; still recognized after the bot that wrote them stops. */\n private botLogSns = new Set<number>()\n private commandProviders = new Set<CommandProvider>()\n private appCommands = new Set<AppCommand>()\n /** Bot plugins turned off for the whole project; they run on no bot, whatever each bot says. */\n private projectOff = new Set<string>()\n private runs = new Map<string, PluginRun[]>()\n /** The context that registered each adapter, to tell which installed plugin adds it. */\n private adapterFibers = new Map<string, Fiber>()\n private permissionProvider?: PermissionProvider\n\n constructor(ctx: Context) {\n super(ctx, 'bots')\n this.home = ctx\n }\n\n /**\n * Bot lifecycle lines for the global log, tagged `bot` in the dashboard. Written from the manager's\n * own context, so they stay out of the bot's log, which has its own lines from inside the bot.\n */\n private get logger() {\n return this.home.logger('bot')\n }\n\n async *[Service.init]() {\n const stored = await this.home.storage.get<{ bots: BotRecord[]; off?: string[] }>(STORAGE_KEY)\n this.records = stored?.bots ?? []\n this.projectOff = new Set(stored?.off ?? [])\n for (const record of this.records) {\n for (const plugin of record.plugins ?? []) plugin.package = currentPackageName(plugin.package)\n }\n this.logger.info('loaded %d bot(s)', this.records.length)\n yield this.home.logger.exporter({\n colors: false,\n levels: { default: LOG_LEVEL_DEBUG },\n export: (message) => this.captureLog(message),\n })\n yield* this.defineActions()\n // The Plugins page shows how many commands and adapters each plugin adds.\n yield this.home.manager.defineProvides(() => this.provided())\n this.home.inject(['model', 'database'], async (ctx) => {\n const archive = new MessageArchive(ctx, (error) => this.logger.warn('saving a message to the database failed: %s', error))\n this.archive = archive\n ctx.effect(() => () => {\n if (this.archive === archive) this.archive = undefined\n }, 'bots message archive')\n try {\n const imported = await archive.start()\n if (imported) this.logger.info('imported %d message(s) from the message logs into the database', imported)\n } catch (error) {\n this.logger.warn('importing the message logs into the database failed: %s', error)\n if (this.archive === archive) this.archive = undefined\n }\n })\n if (this.home.offline) this.logger.info('offline: bots are not started')\n for (const record of this.home.offline ? [] : this.records) {\n if (record.enabled && this.adapterStore.has(record.adapter.type)) this.startSafely(record.id)\n }\n }\n\n // ---- adapters ----\n\n /** Registers an adapter type. Bots using it start when it loads and stop when it unloads. */\n defineAdapter<C>(adapter: AdapterType<C>) {\n const ctx = this.ctx\n return ctx.effect(() => {\n if (this.adapterStore.has(adapter.id)) throw new Error(`adapter \"${adapter.id}\" is already defined`)\n this.adapterStore.set(adapter.id, adapter)\n this.adapterFibers.set(adapter.id, ctx.fiber)\n this.logger.info('adapter %s is available', adapter.id)\n this.secureRecords(adapter as AdapterType).catch((error) => this.logger.warn('could not move the %s secrets of bots to .env: %s', adapter.id, error))\n for (const record of this.records) {\n if (this.home.offline) break\n if (record.enabled && record.adapter.type === adapter.id && !this.runtimes.has(record.id)) {\n this.startSafely(record.id)\n }\n }\n ctx.emit('bots/changed')\n return async () => {\n this.adapterStore.delete(adapter.id)\n this.adapterFibers.delete(adapter.id)\n this.logger.info('adapter %s was removed', adapter.id)\n for (const record of this.records) {\n if (record.adapter.type !== adapter.id || !this.runtimes.has(record.id)) continue\n await this.stopRuntime(record.id)\n this.startErrors.set(record.id, `Adapter \"${adapter.id}\" was unloaded`)\n this.emitStatus(record.id)\n }\n ctx.emit('bots/changed')\n }\n }, `bots.defineAdapter(${adapter.id})`)\n }\n\n /** The adapters by their `order`, then in the order they were added. */\n adapters() {\n const list = [...this.adapterStore.values()]\n list.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))\n return list.map((adapter) => ({\n id: adapter.id,\n displayName: adapter.displayName,\n ...(adapter.description ? { description: adapter.description } : {}),\n ...(adapter.icon ? { icon: adapter.icon } : {}),\n ...(adapter.color ? { color: adapter.color } : {}),\n configSchema: toJsonSchema(adapter.config),\n secrets: adapter.secrets ?? [],\n segments: adapter.segments,\n groupRoles: !!adapter.groupRoles,\n avatars: adapter.avatars ?? {},\n hiddenFields: adapter.hiddenFields ?? {},\n links: adapter.links ?? [],\n ...(adapter.qrSetup ? { qrSetup: adapter.qrSetup } : {}),\n }))\n }\n\n /** Adapters that can send every segment in a message. */\n platformsFor(segments: Segment[]) {\n return [...this.adapterStore.values()]\n .filter((adapter) => segments.every((s) => adapter.segments.includes(s.type)))\n .map((adapter) => adapter.id)\n }\n\n // ---- records ----\n\n get(id: string) {\n const record = this.records.find((item) => item.id === id)\n if (!record) throw new MushinError('not_found', `No bot with id \"${id}\"`)\n return record\n }\n\n bot(id: string) {\n return this.runtimes.get(id)?.bot\n }\n\n status(id: string): BotStatusInfo {\n const bot = this.bot(id)\n if (bot) return { id, status: bot.status, error: bot.error, selfId: bot.selfId, selfName: bot.selfName, selfAvatar: bot.selfAvatar, invite: bot.invite }\n const error = this.startErrors.get(id)\n return { id, status: error ? 'error' : 'offline', error }\n }\n\n private emitStatus(id: string) {\n this.home.emit('bots/status', this.status(id))\n }\n\n /** Moves adapter secrets an older version saved in plain text to .env, once the adapter is known. */\n private async secureRecords(adapter: AdapterType) {\n let moved = 0\n for (const record of this.records) {\n if (record.adapter.type !== adapter.id) continue\n const result = await this.secureConfig(adapter.id, record, record.adapter.config)\n record.adapter = { ...record.adapter, config: result.config }\n moved += result.moved.length\n }\n if (moved) {\n await this.save()\n this.logger.info('moved %d %s bot secret(s) to .env', moved, adapter.id)\n }\n }\n\n /** Puts the secrets of an adapter config into .env and returns the config with `${NAME}` references. */\n private secureConfig(type: string, record: Pick<BotRecord, 'id' | 'name'> & { adapter?: BotRecord['adapter'] }, config: Record<string, any>) {\n const owner = /[A-Za-z0-9]/.test(record.name) ? record.name : record.id\n return this.home.storage.secrets.moveIn(config, { keys: this.adapterStore.get(type)?.secrets ?? [], name: ['bot', owner], previous: record.adapter?.config })\n }\n\n private redact(record: BotRecord) {\n const secrets = this.adapterStore.get(record.adapter.type)?.secrets ?? []\n const config = { ...record.adapter.config }\n for (const key of secrets) {\n // A `${NAME}` reference is not a secret: it shows where the value is.\n if (typeof config[key] === 'string' && config[key] && envReference(config[key]) === undefined) config[key] = mask(config[key])\n }\n return { ...record, adapter: { ...record.adapter, config } }\n }\n\n describe(record: BotRecord) {\n return { ...this.redact(record), ...this.status(record.id), connection: this.connectionOf(record) }\n }\n\n private connectionOf(record: BotRecord) {\n try {\n return this.adapterStore.get(record.adapter.type)?.describe?.(record.adapter.config, record.id)\n } catch {}\n }\n\n list() {\n return this.records.map((record) => this.describe(record))\n }\n\n private async save() {\n await this.home.storage.set(STORAGE_KEY, { bots: this.records, ...(this.projectOff.size ? { off: [...this.projectOff] } : {}) })\n this.home.emit('bots/changed')\n }\n\n private validateAdapter(type: string, config: unknown) {\n const adapter = this.adapterStore.get(type)\n if (!adapter) {\n const known = [...this.adapterStore.keys()].join(', ') || 'none'\n throw new MushinError('invalid_input', `Unknown adapter \"${type}\". Loaded adapters: ${known}`)\n }\n const result = adapter.config.safeParse(config)\n if (!result.success) throw new MushinError('invalid_input', z.prettifyError(result.error), result.error.issues)\n return result.data as Record<string, any>\n }\n\n /**\n * A new bot's adapter config. A bot created stopped may be saved half filled in (its connection\n * set up later, e.g. \"connect later\" in the dashboard); it is checked again when it starts.\n */\n private adapterConfigFor(input: { adapter: { type: string; config: Record<string, any> }; enabled?: boolean }) {\n try {\n return this.validateAdapter(input.adapter.type, input.adapter.config)\n } catch (error) {\n if (input.enabled !== false || !this.adapterStore.has(input.adapter.type)) throw error\n return { ...input.adapter.config }\n }\n }\n\n async create(input: { name: string; adapter: { type: string; config: Record<string, any> }; plugins?: { package: string; config?: Record<string, any> }[]; enabled?: boolean; provider?: string; commands?: CommandSettings }) {\n const id = randomId()\n const record: BotRecord = {\n id,\n name: input.name,\n enabled: input.enabled ?? true,\n adapter: { type: input.adapter.type, config: (await this.secureConfig(input.adapter.type, { id, name: input.name }, this.adapterConfigFor(input))).config },\n plugins: [],\n provider: input.provider,\n ...(input.commands ? { commands: input.commands } : {}),\n createdAt: Date.now(),\n }\n for (const item of input.plugins ?? []) {\n const plugin = await this.loadBotPlugin(item.package)\n validatePluginConfig(plugin, item.config ?? {})\n record.plugins.push({ package: item.package, enabled: true, config: await this.securePlugin(record, item.package, plugin, item.config ?? {}) })\n }\n this.records.push(record)\n await this.save()\n this.logger.info('created bot %s', this.label(record))\n if (record.enabled) await this.start(id).catch(() => {})\n return this.describe(record)\n }\n\n async update(id: string, patch: { name?: string; adapter?: { type: string; config: Record<string, any> }; provider?: string | null; commands?: CommandSettings }) {\n const record = this.get(id)\n if (patch.commands !== undefined) record.commands = { ...record.commands, ...patch.commands }\n if (patch.name !== undefined) record.name = patch.name\n if (patch.provider !== undefined) record.provider = patch.provider ?? undefined\n if (patch.adapter) {\n const secrets = this.adapterStore.get(patch.adapter.type)?.secrets ?? []\n const config = { ...patch.adapter.config }\n for (const key of secrets) {\n if (isMasked(config[key])) config[key] = record.adapter.config[key]\n }\n record.adapter = { type: patch.adapter.type, config: (await this.secureConfig(patch.adapter.type, record, this.validateAdapter(patch.adapter.type, config))).config }\n }\n await this.save()\n this.logger.info('updated bot %s', this.label(record))\n // The running bot reads its name and command settings from the record, so changing only them needs no restart.\n const restart = patch.adapter !== undefined || patch.provider !== undefined\n if (record.enabled && restart) await this.start(id).catch(() => {})\n return this.describe(record)\n }\n\n async remove(id: string) {\n const record = this.get(id)\n await this.stopRuntime(id)\n this.records = this.records.filter((item) => item !== record)\n this.buffers.delete(id)\n this.logs.delete(id)\n this.runs.delete(id)\n this.startErrors.delete(id)\n await this.save()\n this.logger.info('deleted bot %s', this.label(record))\n return { deleted: id }\n }\n\n // ---- runtimes ----\n\n private startSafely(id: string) {\n this.start(id).catch((error) => this.logger.warn('failed to start bot %s: %s', id, error))\n }\n\n async start(id: string) {\n const record = this.get(id)\n await this.stopRuntime(id)\n this.startErrors.delete(id)\n const adapter = this.adapterStore.get(record.adapter.type)\n if (!adapter) {\n const message = `Adapter \"${record.adapter.type}\" is not loaded; enable its plugin`\n this.startErrors.set(id, message)\n this.emitStatus(id)\n this.logger.warn('cannot start bot %s: %s', this.label(record), message)\n throw new MushinError('unavailable', message)\n }\n\n const runtime: Runtime = { plugins: new Map(), pluginErrors: new Map() }\n const loaded: { entry: BotPluginEntry; plugin: Plugin }[] = []\n for (const entry of record.plugins) {\n if (!entry.enabled || this.projectOff.has(entry.package)) continue\n try {\n const plugin = await this.loadBotPlugin(entry.package)\n // A key an older version or a hand edit left in plain text moves to .env.\n const secured = await this.securePlugin(record, entry.package, plugin, entry.config ?? {}, entry.config)\n if (JSON.stringify(secured) !== JSON.stringify(entry.config ?? {})) {\n entry.config = secured\n await this.save()\n }\n loaded.push({ entry, plugin })\n } catch (error) {\n runtime.pluginErrors.set(entry.package, error instanceof Error ? error.message : String(error))\n }\n }\n\n const hooks: BotHooks = {\n record: (partial) => this.record(partial),\n status: (bot) => {\n runtime.bot = bot\n // Connecting is left to the bot's own log, so a reconnect loop writes one error line here, not one per try.\n if (bot.status !== 'connecting' && bot.status !== runtime.logged && (runtime.logged || bot.status !== 'offline')) {\n runtime.logged = bot.status\n if (bot.status === 'error') this.logger.warn('bot %s: error (%s)', this.label(record), bot.error ?? 'no details')\n else this.logger.info('bot %s is %s', this.label(record), bot.status)\n }\n this.emitStatus(id)\n },\n commands: (bot) => this.commands(bot.id),\n commandCalled: (bot, entry, session) => {\n this.home.emit('bots/command', { botId: bot.id, name: entry.name, source: entry.source, userId: session.user.id, channel: session.channel, at: Date.now() })\n },\n builtinCommand: (bot, entry, session) => {\n if (entry.name !== HELP_COMMAND.name) return\n let entries = this.commands(bot.id)\n if (bot.record.commands?.helpByRole) {\n const role = session.role()\n entries = entries.filter((item) => {\n const required = requiredRole(item)\n return !required || roleAtLeast(role, required)\n })\n }\n return helpText(entries, bot.record.commands)\n },\n roleOf: (bot, userId) => this.permissionProvider?.roleOf(bot.id, userId),\n appCommand: (bot, entry) => this.appCommandFor(bot.id, entry),\n pluginRun: (bot, run, fiber) => this.recordRun(bot.id, run, fiber),\n usageScope: (bot, message) => {\n const entry = this.usageEntry(bot.id, message.id, true)!\n entry.bytes = byteSize(message.segments)\n return {\n botId: bot.id,\n messageId: message.id,\n report: (event) => {\n const target = this.usageEntry(bot.id, message.id, true)!\n if (target.events.length < USAGE_EVENTS_PER_MESSAGE) target.events.push(event)\n },\n }\n },\n sent: (bot, message, transfer) => {\n const entry = this.usageEntry(bot.id, message.id, true)!\n Object.assign(entry, { bytes: transfer.bytes }, transfer.ms !== undefined ? { sendMs: transfer.ms } : {}, transfer.cause ? { cause: transfer.cause } : {})\n if (transfer.cause) this.usageEntry(bot.id, transfer.cause)?.replies.push(message.id)\n },\n }\n this.runtimes.set(id, runtime)\n runtime.fiber = this.home.isolate('bot').plugin({\n name: `bot:${record.name}`,\n apply: (ctx: Context) => {\n runtime.ctx = ctx\n this.runtimeFibers.set(ctx.fiber, id)\n ctx.effect(() => () => this.runtimeFibers.delete(ctx.fiber), 'bot log attribution')\n const enabled = loaded.map(({ entry }) => entry.package.replace(/^@mushinjs\\/bot-plugin-/, ''))\n ctx.logger('bot').info('starting with the %s adapter; plugins: %s', record.adapter.type, enabled.join(', ') || 'none')\n for (const [name, error] of runtime.pluginErrors) ctx.logger('bot').warn('plugin %s did not load: %s', name, error)\n ctx.plugin(Bot, { record, hooks })\n // Secrets are `${NAME}` references to .env; the adapter and plugins get the values.\n ctx.plugin(adapter.plugin, this.home.storage.secrets.resolveAll(record.adapter.config, adapter.secrets ?? []))\n for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, resolveEnvReferences(entry.config)))\n },\n })\n await runtime.fiber\n runtime.bot = runtime.ctx?.get('bot') ?? runtime.bot\n const error = fiberError(runtime.fiber)\n if (error) this.logger.warn('bot %s failed to start: %s', this.label(record), error)\n else this.logger.info('started bot %s with the %s adapter', this.label(record), record.adapter.type)\n this.emitStatus(id)\n return this.status(id)\n }\n\n private async stopRuntime(id: string) {\n const runtime = this.runtimes.get(id)\n if (!runtime) return\n this.runtimes.delete(id)\n await runtime.fiber?.dispose()\n this.logger.info('stopped bot %s', this.label(this.records.find((item) => item.id === id) ?? id))\n this.emitStatus(id)\n }\n\n async setEnabled(id: string, enabled: boolean) {\n const record = this.get(id)\n record.enabled = enabled\n await this.save()\n if (enabled) return this.start(id)\n await this.stopRuntime(id)\n return this.status(id)\n }\n\n /** Log lines name a bot by its id; the dashboard links it to the bot. */\n private label(record: BotRecord | string) {\n return typeof record === 'string' ? record : record.id\n }\n\n // ---- bot plugins ----\n\n async loadBotPlugin(name: string) {\n const entry = await this.home.manager.findPackage(name)\n if (!entry) throw new MushinError('not_found', `Bot plugin \"${name}\" is not installed`)\n if (entry.manifest.kind !== 'bot') throw new MushinError('invalid_input', `\"${name}\" is an app plugin, not a bot plugin`)\n return this.home.manager.loadPlugin(name)\n }\n\n /**\n * The plugins a bot can turn on: every installed bot plugin, then each app plugin with chat commands (`kind: 'app'`),\n * with whether it is on for this bot and whether it is turned off for the whole project.\n */\n async plugins(id: string) {\n const record = this.get(id)\n const graph = await this.home.manager.graph()\n const apps = this.chatApps()\n const appEntries = graph.catalog\n .filter((entry) => entry.manifest.kind === 'app' && (apps.has(entry.package) || record.appPlugins?.includes(entry.package)))\n .map((entry) => {\n const commands = apps.get(entry.package)\n const enabled = !!record.appPlugins?.includes(entry.package)\n return {\n package: entry.package,\n kind: 'app' as const,\n version: entry.version,\n manifest: entry.manifest,\n enabled,\n // Its commands are only known while it runs; an app plugin that does not run is off on the Plugins page.\n ...(commands ? { commands } : { projectOff: true }),\n status: enabled && commands ? 'active' : 'disabled',\n }\n })\n return [...await this.botPlugins(id, graph), ...appEntries]\n }\n\n private async botPlugins(id: string, graph: DependencyGraph) {\n const record = this.get(id)\n const runtime = this.runtimes.get(id)\n const catalog = graph.catalog.filter((entry) => entry.manifest.kind === 'bot')\n return Promise.all(catalog.map(async (entry) => {\n const configured = record.plugins.find((item) => item.package === entry.package)\n let configSchema\n let secrets: string[] = []\n try {\n const plugin = await this.home.manager.loadPlugin(entry.package)\n configSchema = pluginSchema(plugin)\n secrets = secretFields(plugin)\n } catch {}\n const fiber = runtime?.plugins.get(entry.package)\n const report = dependencyReport(graph, entry.package)\n const missing = this.missingApps(report.requires)\n const projectOff = this.projectOff.has(entry.package)\n let status: string = configured?.enabled && !projectOff ? (runtime ? fiberStatus(fiber) : 'disabled') : 'disabled'\n if (status === 'pending' && missing.length) status = 'missing'\n return {\n package: entry.package,\n kind: 'bot' as const,\n ...(projectOff ? { projectOff } : {}),\n version: entry.version,\n manifest: entry.manifest,\n enabled: !!configured?.enabled,\n config: maskSecrets(configured?.config ?? {}, secrets),\n configSchema,\n status,\n error: runtime?.pluginErrors.get(entry.package) ?? (status === 'missing' ? describeMissing(missing) : fiberError(fiber)),\n dependencies: { requires: report.requires, optional: report.optional },\n ...(missing.length ? { missing } : {}),\n }\n }))\n }\n\n /** Required app plugins that are not installed, do not fit or are disabled. */\n private missingApps(requires: ReturnType<typeof dependencyReport>['requires']): MissingDependency[] {\n return requires\n .filter((dep) => dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled')\n .map((dep) => ({ package: dep.package, range: dep.range, reason: dep.problem as MissingDependency['reason'], ...(dep.version ? { version: dep.version } : {}) }))\n }\n\n /** The bot's entry for a plugin in `plugins()`. */\n private async pluginInfo(id: string, name: string) {\n return (await this.plugins(id)).find((item) => item.package === name)\n }\n\n /** Turns an app plugin's chat commands on or off for one bot. */\n private async setAppPlugin(id: string, name: string, enabled: boolean) {\n const record = this.get(id)\n const list = new Set(record.appPlugins ?? [])\n if (enabled) list.add(name)\n else list.delete(name)\n record.appPlugins = [...list]\n await this.save()\n this.logger.info('%s the commands of %s on bot %s', enabled ? 'turned on' : 'turned off', name, this.label(record))\n return this.pluginInfo(id, name)\n }\n\n async enablePlugin(id: string, name: string, config?: Record<string, any>) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app') {\n if (config) throw new MushinError('invalid_input', `${name} is an app plugin: its settings are on the Plugins page (plugins.configure)`)\n return this.setAppPlugin(id, name, true)\n }\n const plugin = await this.loadBotPlugin(name)\n const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires)\n if (missing.length) {\n throw new MushinError('unavailable', `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing })\n }\n let entry = record.plugins.find((item) => item.package === name)\n let nextConfig = restoreMasked(config ?? entry?.config ?? {}, entry?.config, secretFields(plugin))\n validatePluginConfig(plugin, nextConfig)\n nextConfig = await this.securePlugin(record, name, plugin, nextConfig, entry?.config)\n if (!entry) {\n entry = { package: name, enabled: true, config: nextConfig }\n record.plugins.push(entry)\n }\n entry.enabled = true\n entry.config = nextConfig\n await this.save()\n this.logger.info('enabled plugin %s on bot %s', name, this.label(record))\n this.reloadPlugin(id, entry, plugin)\n return this.pluginInfo(id, name)\n }\n\n async disablePlugin(id: string, name: string) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app' || record.appPlugins?.includes(name)) return this.setAppPlugin(id, name, false)\n const entry = record.plugins.find((item) => item.package === name)\n if (!entry) throw new MushinError('not_found', `${name} is not configured on this bot`)\n entry.enabled = false\n await this.save()\n this.logger.info('disabled plugin %s on bot %s', name, this.label(record))\n const runtime = this.runtimes.get(id)\n const fiber = runtime?.plugins.get(name)\n runtime?.plugins.delete(name)\n await fiber?.dispose()\n return this.pluginInfo(id, name)\n }\n\n async configurePlugin(id: string, name: string, config: Record<string, any>) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app') {\n throw new MushinError('invalid_input', `${name} is an app plugin: its settings are on the Plugins page (plugins.configure), the same for every bot`)\n }\n const entry = record.plugins.find((item) => item.package === name)\n if (!entry) return this.enablePlugin(id, name, config)\n const plugin = await this.loadBotPlugin(name)\n const next = restoreMasked(config, entry.config, secretFields(plugin))\n validatePluginConfig(plugin, next)\n entry.config = await this.securePlugin(record, name, plugin, next, entry.config)\n await this.save()\n this.logger.info('config of plugin %s on bot %s changed', name, this.label(record))\n if (entry.enabled) this.reloadPlugin(id, entry, plugin)\n return this.pluginInfo(id, name)\n }\n\n /** Puts the plain values of a bot plugin's secret fields into .env and returns the config with `${NAME}` references. */\n private async securePlugin(record: Pick<BotRecord, 'id' | 'name'>, name: string, plugin: Plugin, config: Record<string, any>, previous?: Record<string, any>) {\n const keys = secretFields(plugin)\n if (!keys.length) return config\n const short = name.replace(/^@[^/]+\\//, '').replace(/^(?:mushin-)?(?:bot-)?plugin-/, '')\n return (await this.home.storage.secrets.moveIn(config, { keys, name: ['bot', record.name || record.id, short], previous })).config\n }\n\n private reloadPlugin(id: string, entry: BotPluginEntry, plugin: Plugin) {\n const runtime = this.runtimes.get(id)\n if (!runtime?.ctx || this.projectOff.has(entry.package)) return\n runtime.plugins.get(entry.package)?.dispose()\n runtime.pluginErrors.delete(entry.package)\n runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, resolveEnvReferences(entry.config)))\n }\n\n /**\n * Turns a bot plugin on or off for the whole project. Off, it runs on no bot; each bot keeps its own switch and\n * settings, so turning it back on starts it again where it was on.\n */\n async setProjectPlugin(name: string, enabled: boolean) {\n const entry = await this.home.manager.findPackage(name)\n if (!entry) throw new MushinError('not_found', `Plugin \"${name}\" is not installed`)\n 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`)\n 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`)\n if (enabled === !this.projectOff.has(name)) return this.projectPlugin(name)\n if (enabled) this.projectOff.delete(name)\n else this.projectOff.add(name)\n await this.save()\n this.logger.info('%s %s for every bot', enabled ? 'turned on' : 'turned off', name)\n for (const record of this.records) {\n const item = record.plugins.find((plugin) => plugin.package === name && plugin.enabled)\n const runtime = this.runtimes.get(record.id)\n if (!item || !runtime) continue\n if (enabled) {\n try {\n this.reloadPlugin(record.id, item, await this.loadBotPlugin(name))\n } catch (error) {\n runtime.pluginErrors.set(name, error instanceof Error ? error.message : String(error))\n }\n } else {\n const fiber = runtime.plugins.get(name)\n runtime.plugins.delete(name)\n await fiber?.dispose()\n }\n }\n return this.projectPlugin(name)\n }\n\n /**\n * The chat plugins across the project: each bot plugin with its project switch, and each app plugin with chat\n * commands, with the bots that have it on.\n */\n async projectPlugins(): Promise<ProjectChatPlugin[]> {\n const catalog = (await this.home.manager.graph()).catalog\n const apps = this.chatApps()\n return catalog\n .filter((entry) => entry.manifest.kind === 'bot' || apps.has(entry.package))\n .map((entry) => {\n const bot = entry.manifest.kind === 'bot'\n return {\n package: entry.package,\n kind: bot ? 'bot' as const : 'app' as const,\n enabled: bot ? !this.projectOff.has(entry.package) : true,\n ...(bot && entry.manifest.essential ? { essential: true } : {}),\n bots: this.records\n .filter((record) => (bot ? record.plugins.some((item) => item.package === entry.package && item.enabled) : record.appPlugins?.includes(entry.package)))\n .map((record) => record.id),\n }\n })\n }\n\n private async projectPlugin(name: string) {\n return (await this.projectPlugins()).find((item) => item.package === name)\n }\n\n // ---- commands ----\n\n /** Adds commands to every bot's list. Removed when the calling plugin unloads. */\n defineCommands(provider: CommandProvider) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bots.defineCommands()')\n }\n\n /**\n * Answers a command from an app plugin, such as `/persona`, on the bots the user turned the plugin on for (on the\n * bot's Plugins page, or with `bots.plugins.enable`). A plugin that decides itself which bots answer, from its own\n * per-bot settings, passes `bots`, and then has no switch on the bot's page. It answers after flows, like `/help`,\n * and shows in the command list of each bot it answers on.\n */\n defineCommand(def: CommandDef, handler: AppCommand['handler'], options: { bots?: (botId: string) => boolean } = {}) {\n const ctx = this.ctx\n const command: AppCommand = { def, plugin: ctx.fiber.name, fiber: ctx.fiber, handler, bots: options.bots }\n return ctx.effect(() => {\n this.appCommands.add(command)\n return () => this.appCommands.delete(command)\n }, `bots.defineCommand(${def.name})`)\n }\n\n /** The app plugin command behind a command entry, if an app plugin answers it. */\n appCommandFor(botId: string, entry: CommandEntry) {\n if (entry.source.kind !== 'plugin') return\n return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && this.answersOn(item, botId))\n }\n\n /** Whether an app plugin's command answers on a bot: the plugin's own choice, or the bot's switch for the plugin. */\n private answersOn(command: AppCommand, botId: string) {\n if (command.bots) return command.bots(botId)\n const name = this.home.manager.packageOf(command.fiber)\n return !!name && !!this.records.find((record) => record.id === botId)?.appPlugins?.includes(name)\n }\n\n /** App plugins whose commands have a switch on each bot, with the names of those commands, by package. */\n private chatApps() {\n const apps = new Map<string, string[]>()\n for (const command of this.appCommands) {\n if (command.bots) continue\n const name = this.home.manager.packageOf(command.fiber)\n if (!name) continue\n const list = apps.get(name) ?? []\n if (!list.includes(command.def.name)) list.push(command.def.name)\n apps.set(name, list)\n }\n return apps\n }\n\n /** Lets the permissions plugin say who is master, admin or user on each bot. */\n usePermissions(provider: PermissionProvider) {\n return this.ctx.effect(() => {\n this.permissionProvider = provider\n return () => {\n if (this.permissionProvider === provider) this.permissionProvider = undefined\n }\n }, 'bots.usePermissions()')\n }\n\n /** A user's role on a bot; nothing when the permissions plugin is not running. */\n roleOf(botId: string, userId: string) {\n return this.permissionProvider?.roleOf(botId, userId)\n }\n\n /** Commands registered on one bot: from command providers such as flows, its plugins, and the built-in help. */\n commands(botId: string): CommandEntry[] {\n const record = this.records.find((item) => item.id === botId)\n if (!record) return []\n const entries: CommandEntry[] = []\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider(botId))\n } catch (error) {\n this.logger.warn('listing commands failed: %s', error)\n }\n }\n entries.push(...(this.runtimes.get(botId)?.bot?.localCommands() ?? []))\n for (const command of this.appCommands) {\n if (!this.answersOn(command, botId)) continue\n entries.push({ ...command.def, botId, source: { kind: 'plugin', id: command.plugin, name: command.plugin } })\n }\n if (record.commands?.help !== false && !entries.some((entry) => commandMatches(entry, HELP_COMMAND.name))) {\n entries.push({ ...HELP_COMMAND, botId, source: { kind: 'builtin', id: 'help', name: 'help' } })\n }\n return entries\n }\n\n /** Commands of one bot or of every bot, with names that more than one source registers. */\n commandList(botId?: string) {\n if (botId) this.get(botId)\n const entries = (botId ? [botId] : this.records.map((record) => record.id)).flatMap((id) => this.commands(id))\n const conflicts = commandConflicts(entries).map((item) => ({ botId: item.botId, name: item.name, sources: item.entries.map((entry) => entry.source) }))\n return { commands: entries, conflicts }\n }\n\n /**\n * Runs a command as if a master sent it. With a target it really runs on the bot: in that group,\n * or in the master's private chat, and the replies are sent. Without one it only previews where\n * the message would go (through flows), so nothing is sent.\n */\n async runCommand(input: RunCommandInput, source?: Provenance) {\n const record = this.get(input.bot)\n const prefix = record.commands?.prefixes?.find(Boolean) ?? '/'\n const text = /^\\p{L}/u.test(input.command) && !input.command.startsWith(prefix) ? `${prefix}${input.command}` : input.command\n if (!input.target) {\n const flows = this.home.get('flows') as { route(botId: string, input: { text: string; role?: string }): Promise<unknown> } | undefined\n if (!flows) throw new MushinError('unavailable', 'Previewing a command needs the flows plugin; give a target to run it for real')\n return { simulated: true, text, route: await flows.route(record.id, { text, role: 'master' }) }\n }\n const bot = this.bot(record.id)\n if (!bot || this.status(record.id).status !== 'online') throw new MushinError('unavailable', `Bot \"${record.name}\" is not online`)\n const permissions = this.home.get('permissions') as { get(botId: string): { masters: string[] } } | undefined\n const userId = input.user ?? permissions?.get(record.id).masters[0]\n if (!userId) throw new MushinError('invalid_input', `Bot \"${record.name}\" has no master; add one with permissions.update or pass user`)\n if (input.target === 'group' && !input.group) throw new MushinError('invalid_input', 'Pass the group id to run a command in a group')\n const channel: ChannelInfo = input.target === 'group' ? { type: 'group', id: input.group! } : { type: 'private', id: userId }\n const replies: MessageRecord[] = []\n const collect = (message: MessageRecord) => {\n if (message.botId === record.id && message.direction === 'out' && message.channel.id === channel.id) replies.push(message)\n }\n const stop = this.home.on('bots/message', collect)\n try {\n await bot.receive({ channel, user: { id: userId }, segments: [{ type: 'text', data: { text } }] }, { source })\n } finally {\n stop()\n }\n return {\n simulated: false,\n text,\n channel,\n user: userId,\n replies: replies.map((reply) => segmentsToText(reply.segments)),\n }\n }\n\n // ---- plugin runs ----\n\n /** The installed plugin a context of a bot belongs to: one of the bot's plugins, else an app plugin. */\n private packageIn(botId: string, fiber: Fiber | undefined) {\n if (!fiber) return\n const runtime = this.runtimes.get(botId)\n if (runtime) {\n const owners = new Map<Fiber, string>()\n for (const [name, plugin] of runtime.plugins) owners.set(plugin.ctx.fiber, name)\n for (let current: Fiber | undefined = fiber; current; current = current.parent?.fiber === current ? undefined : current.parent?.fiber) {\n const name = owners.get(current)\n if (name) return name\n }\n }\n return this.home.manager.packageOf(fiber)\n }\n\n private recordRun(botId: string, report: PluginRunReport, fiber?: Fiber) {\n const run: PluginRun = { id: randomId(8), botId, ...report, plugin: this.packageIn(botId, fiber) ?? report.plugin }\n let buffer = this.runs.get(botId)\n if (!buffer) this.runs.set(botId, buffer = [])\n buffer.push(run)\n if (buffer.length > RUN_BUFFER_SIZE) buffer.splice(0, buffer.length - RUN_BUFFER_SIZE)\n const day = new Date(run.startedAt).toISOString().slice(0, 10)\n this.home.storage.append(`runs/${botId}/${day}`, run).catch(() => {})\n this.home.emit('bots/run', run)\n }\n\n /**\n * What plugins did with a bot's messages, newest first: each message a plugin replied to, kept from the plugins\n * after it, or failed on. Flow runs are in `flows.history`.\n */\n async pluginRuns(id: string, query: { limit?: number; before?: number; plugin?: string; status?: PluginRun['status'] } = {}) {\n this.get(id)\n let buffer = this.runs.get(id)\n if (!buffer) {\n // Today's runs from the file, with any recorded while it was read.\n const day = new Date().toISOString().slice(0, 10)\n const stored = await this.home.storage.tail<PluginRun>(`runs/${id}/${day}`, RUN_BUFFER_SIZE)\n const current = this.runs.get(id) ?? []\n buffer = [...stored.filter((run) => !current.some((item) => item.id === run.id)), ...current].slice(-RUN_BUFFER_SIZE)\n this.runs.set(id, buffer)\n }\n const limit = query.limit ?? 50\n const matching = buffer.filter((run) => (query.before === undefined || run.startedAt < query.before)\n && (!query.plugin || run.plugin === query.plugin)\n && (!query.status || run.status === query.status))\n return { runs: matching.slice(-limit).reverse(), more: matching.length > limit }\n }\n\n /** What this plugin knows of what others add: chat commands (app plugins' and bot plugins'), and adapters. */\n private *provided(): Iterable<ProvidedItem> {\n for (const command of this.appCommands) yield { kind: 'command', name: command.def.name, fiber: command.fiber }\n for (const [id, runtime] of this.runtimes) {\n for (const command of runtime.bot?.ownCommandList() ?? []) {\n yield { kind: 'command', name: command.name, package: this.packageIn(id, command.fiber), fiber: command.fiber }\n }\n }\n for (const [id, fiber] of this.adapterFibers) yield { kind: 'adapter', name: id, fiber }\n }\n\n // ---- logs ----\n\n /** Finds the bot whose context wrote a log message, by walking up from the writing fiber. */\n private botOf(message: Message) {\n let fiber = message.fiber?.deref()\n while (fiber) {\n const id = this.runtimeFibers.get(fiber)\n if (id) return id\n const parent = fiber.parent?.fiber\n if (!parent || parent === fiber) return\n fiber = parent\n }\n }\n\n /** True when a log line was written inside a bot; it belongs in that bot's log, not the global one. */\n isBotLog(message: Message) {\n return this.botLogSns.has(message.sn) || !!this.botOf(message)\n }\n\n private captureLog(message: Message) {\n const botId = this.botOf(message)\n if (!botId) return\n this.botLogSns.add(message.sn)\n // The global log buffer holds 1000 lines; remember a little more than that.\n if (this.botLogSns.size > 2000) this.botLogSns.delete(this.botLogSns.values().next().value!)\n const line: BotLogLine = {\n botId,\n sn: message.sn,\n ts: message.ts,\n type: message.type,\n name: message.name,\n tag: logTag(message.name),\n text: Logger.format(plainExporter, message),\n }\n const handling = usage.current()\n if (handling?.botId === botId) line.message = handling.messageId\n let buffer = this.logs.get(botId)\n if (!buffer) this.logs.set(botId, buffer = [])\n buffer.push(line)\n if (buffer.length > LOG_BUFFER_SIZE) buffer.splice(0, buffer.length - LOG_BUFFER_SIZE)\n this.home.emit('bots/log', line)\n const day = new Date(line.ts).toISOString().slice(0, 10)\n this.home.storage.append(`logs/${botId}/${day}`, line).catch(() => {})\n }\n\n async logLines(id: string, filter: LogFilter = {}) {\n this.get(id)\n const limit = filter.limit ?? 200\n let lines: BotLogLine[]\n if (filter.since !== undefined || filter.until !== undefined || filter.message) {\n // Older lines are read from the daily files: the days of the time range, or the last three for a message.\n const until = filter.until ?? Date.now()\n const since = filter.since ?? (filter.message ? until - 2 * DAY : until)\n const days: string[] = []\n const first = Date.parse(new Date(Math.max(since, until - 31 * DAY)).toISOString().slice(0, 10))\n for (let at = first; at <= until; at += DAY) days.push(new Date(at).toISOString().slice(0, 10))\n lines = (await Promise.all(days.map((day) => this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, 100_000)))).flat()\n lines = lines.filter((line) => line.ts >= (filter.since ?? 0) && line.ts <= until)\n } else {\n let buffer = this.logs.get(id)\n if (!buffer) {\n const day = new Date().toISOString().slice(0, 10)\n buffer = await this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, LOG_BUFFER_SIZE)\n this.logs.set(id, buffer)\n }\n lines = buffer\n }\n const query = filter.query?.toLowerCase()\n const level = filter.level ? LEVELS.indexOf(filter.level) : -1\n return lines\n // Lines stored before tags existed get one from their logger name.\n .map((line) => (line.tag ? line : { ...line, tag: logTag(line.name) }))\n .filter((line) => (!filter.message || line.message === filter.message)\n && (!query || line.text.toLowerCase().includes(query))\n && (level < 0 || LEVELS.indexOf(line.type) >= level))\n .slice(-limit)\n }\n\n // ---- messages ----\n\n /** Messages recorded since Mushin started, for the live conversation. */\n private recent = new WeakSet<MessageRecord>()\n /** What handling each recent message cost, in memory only; see `bots.usage`. */\n private usages = new Map<string, MessageUsage>()\n\n private usageEntry(botId: string, messageId: string, create = false) {\n const key = `${botId}:${messageId}`\n let entry = this.usages.get(key)\n if (!entry && create) {\n this.usages.set(key, entry = { events: [], replies: [] })\n if (this.usages.size > USAGE_MESSAGES) this.usages.delete(this.usages.keys().next().value!)\n }\n return entry\n }\n\n /** A message's costs, and for a reply the costs of the message it answered. */\n usage(botId: string, messageId: string) {\n const entry = this.usageEntry(botId, messageId)\n if (!entry) return null\n const cause = entry.cause ? this.usageEntry(botId, entry.cause) : undefined\n return { ...entry, ...(cause ? { causeEvents: cause.events } : {}) }\n }\n\n private record(partial: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord {\n const record: MessageRecord = {\n ...partial,\n id: randomId(8),\n type: messageType(partial.segments),\n platforms: this.platformsFor(partial.segments),\n }\n let buffer = this.buffers.get(record.botId)\n if (!buffer) this.buffers.set(record.botId, buffer = [])\n buffer.push(record)\n if (buffer.length > BUFFER_SIZE) buffer.splice(0, buffer.length - BUFFER_SIZE)\n const day = new Date(record.timestamp).toISOString().slice(0, 10)\n this.home.storage.append(`messages/${record.botId}/${day}`, record).catch((error) => {\n this.logger.warn('failed to write message log: %s', error)\n })\n this.recent.add(record)\n this.archive?.add(record)\n this.home.emit('bots/message', record)\n return record\n }\n\n /**\n * Recent messages of a bot, oldest first. With the database plugin, a channel's history and\n * older pages (`before`) come from the database; otherwise from today's log and memory.\n */\n async messages(id: string, options: { limit?: number; channel?: string; before?: number; sinceStart?: boolean } = {}) {\n this.get(id)\n const limit = options.limit ?? 100\n if (options.sinceStart) {\n const list = (this.buffers.get(id) ?? []).filter((record) => this.recent.has(record) && (!options.channel || record.channel.id === options.channel))\n return list.slice(-limit)\n }\n const archive = this.archive?.ready ? this.archive : undefined\n if (archive && (options.channel || options.before)) return archive.query(id, { ...options, limit })\n let buffer = this.buffers.get(id)\n if (!buffer) {\n const day = new Date().toISOString().slice(0, 10)\n buffer = archive\n ? await archive.query(id, { limit: BUFFER_SIZE })\n : await this.home.storage.tail<MessageRecord>(`messages/${id}/${day}`, BUFFER_SIZE)\n // Messages recorded while loading are already in the buffer that `record` made.\n const current = this.buffers.get(id)\n if (current) buffer = [...buffer.filter((item) => !current.some((record) => record.id === item.id)), ...current].slice(-BUFFER_SIZE)\n this.buffers.set(id, buffer)\n }\n if (options.before) buffer = buffer.filter((record) => record.timestamp < options.before!)\n const list = options.channel ? buffer.filter((record) => record.channel.id === options.channel) : buffer\n return list.slice(-limit)\n }\n\n /** Channels seen recently, newest first, for the live view's channel list. */\n async channels(id: string, options: { sinceStart?: boolean } = {}) {\n const seen = new Map<string, ChannelInfo & { lastAt: number; lastText: string }>()\n for (const record of await this.messages(id, { limit: BUFFER_SIZE, sinceStart: options.sinceStart })) {\n const key = `${record.channel.type}:${record.channel.id}`\n const text = record.segments.map((s) => (s.type === 'text' ? s.data.text : `[${s.type}]`)).join('')\n seen.set(key, { ...record.channel, name: record.channel.name ?? seen.get(key)?.name, lastAt: record.timestamp, lastText: text.slice(0, 80) })\n }\n return [...seen.values()].sort((a, b) => b.lastAt - a.lastAt)\n }\n\n /** How a command reads a message; see the `bots.tryCommand` action. */\n tryCommand(input: { name: string; aliases?: string[]; prefixes?: string[]; args: CommandArg[]; text: string; bot?: string }) {\n const own = input.prefixes?.filter(Boolean) ?? []\n const record = input.bot ? this.records.find((item) => item.id === input.bot) : undefined\n const prefixes = own.length ? own : record?.commands?.prefixes?.filter(Boolean).length ? record.commands.prefixes!.filter(Boolean) : DEFAULT_PREFIXES\n const def = { name: input.name, args: input.args, prefixes }\n const usage = commandUsage(def)\n const parsed = splitCommand(input.text, prefixes)\n if (!parsed) return { matched: false as const, reason: 'prefix' as const, prefixes, usage }\n if (!commandMatches({ name: input.name, aliases: input.aliases }, parsed.name)) return { matched: false as const, reason: 'name' as const, prefixes, usage }\n return { matched: true as const, prefix: parsed.prefix, rest: parsed.rest, usage, ...parseArgs(input.args, parsed.rest) }\n }\n\n /**\n * People or groups the bots have seen recently, newest first, as `{ value, label, group }`\n * choices: the label is `name (id)`, the group the bot's name. For lists such as a permission\n * node's allow and block lists.\n */\n async seen(kind: 'user' | 'group') {\n const found = new Map<string, { value: string; label: string; group: string; at: number }>()\n for (const record of this.records) {\n for (const message of await this.messages(record.id, { limit: BUFFER_SIZE }).catch(() => [])) {\n const id = kind === 'user' ? (message.direction === 'in' ? message.user.id : '') : message.channel.type === 'group' ? message.channel.id : ''\n if (!id || isSandbox(message.channel)) continue\n const name = kind === 'user' ? message.user.name : message.channel.name\n const previous = found.get(id)\n const label = name || (previous?.label.endsWith(`(${id})`) ? previous.label : '')\n found.set(id, { value: id, label: label && !label.endsWith(`(${id})`) ? `${label} (${id})` : label || id, group: record.name, at: message.timestamp })\n }\n }\n return [...found.values()].sort((a, b) => b.at - a.at).map(({ at: _, ...choice }) => choice)\n }\n\n /** The account's friends and groups, from the platform; empty when the bot is offline or the adapter cannot tell. */\n async contacts(id: string) {\n const bot = this.bot(id)\n if (!bot || bot.status !== 'online') return []\n return bot.contacts()\n }\n\n /** The sandbox's test user writes to the bot; see `Bot.sandbox`. */\n sandbox(id: string, text: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n bot.sandbox(text)\n return { ok: true }\n }\n\n async sendManual(id: string, channel: ChannelInfo, text: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n return bot.deliver(channel, text, { source: { kind: 'manual' } })\n }\n\n /** A fresh address of a message's image, video or file, from the platform. */\n async media(id: string, segment: Segment, options: { channel?: ChannelInfo; inline?: boolean }) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n const media = await bot.media(segment, options)\n if (!media) throw new MushinError('not_found', 'The platform no longer has this file')\n return media\n }\n\n /** The messages of a forwarded chat history, from the platform. */\n async forwarded(id: string, forward: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n return { messages: await bot.forward(forward) }\n }\n\n // ---- actions ----\n\n private *defineActions() {\n const actions = this.home.actions\n\n yield actions.define({\n name: 'bots.adapters',\n description: 'List loaded adapter types (e.g. \"onebot\") with their config JSON Schemas.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.adapters(),\n })\n\n yield actions.define({\n name: 'bots.list',\n description: 'List bots with their connection status, adapter and enabled plugins. Secrets are masked.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.list(),\n })\n\n yield actions.define({\n name: 'bots.get',\n description: 'Get one bot with its status.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.describe(this.get(id)),\n })\n\n yield actions.define({\n name: 'bots.create',\n 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.',\n risk: 'write',\n input: z.object({\n name: z.string().min(1),\n adapter: adapterInput,\n plugins: z.array(z.object({ package: z.string(), config: z.record(z.string(), z.any()).optional() })).optional()\n .describe('Bot plugins to enable right away, e.g. @mushinjs/bot-plugin-llm-chat'),\n enabled: z.boolean().optional(),\n provider: z.string().optional().describe('Default provider or model profile id for this bot\\'s LLM plugins'),\n commands: commandSettingsInput.optional(),\n }),\n handler: (input) => this.create(input),\n })\n\n yield actions.define({\n name: 'bots.update',\n 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.',\n risk: 'write',\n input: idInput.extend({\n name: z.string().min(1).optional(),\n adapter: adapterInput.optional(),\n provider: z.string().nullable().optional(),\n commands: commandSettingsInput.optional().describe('Command prefixes and the built-in /help; changing only these does not restart the bot'),\n }),\n handler: ({ id, ...patch }) => this.update(id, patch),\n })\n\n yield actions.define({\n name: 'commands.list',\n 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.',\n risk: 'read',\n input: z.object({ bot: z.string().optional().describe('Bot id from bots.list; all bots when omitted') }),\n handler: ({ bot }) => this.commandList(bot),\n })\n\n yield actions.define({\n name: 'bots.commands.run',\n 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.',\n risk: 'write',\n input: z.object({\n bot: z.string().describe('Bot id from bots.list'),\n command: z.string().min(1).describe('The command with its arguments, e.g. \"/checkin\" or \"/score 85\"'),\n target: z.enum(['master', 'group']).optional().describe('Where to run it for real; omit to only preview'),\n group: z.string().optional().describe('Group id, with target \"group\"'),\n user: z.string().optional().describe('Run as this user id instead of the first master'),\n }),\n handler: (input, caller) => this.runCommand(input, caller.kind === 'fairy' && caller.session ? { kind: 'fairy', session: caller.session } : undefined),\n })\n\n yield actions.define({\n name: 'bots.delete',\n description: 'Delete a bot and its settings. Message logs on disk are kept.',\n risk: 'dangerous',\n input: idInput,\n handler: ({ id }) => this.remove(id),\n })\n\n yield actions.define({\n name: 'bots.start',\n description: 'Enable and start (or restart) a bot.',\n risk: 'write',\n input: idInput,\n handler: ({ id }) => this.setEnabled(id, true),\n })\n\n yield actions.define({\n name: 'bots.stop',\n description: 'Stop and disable a bot.',\n risk: 'write',\n input: idInput,\n handler: ({ id }) => this.setEnabled(id, false),\n })\n\n yield actions.define({\n name: 'bots.plugins.list',\n 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.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.plugins(id),\n })\n\n yield actions.define({\n name: 'bots.plugins.enable',\n 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).',\n risk: 'write',\n input: pluginInput.extend({ config: z.record(z.string(), z.any()).optional() }),\n handler: ({ id, package: name, config }) => this.enablePlugin(id, name, config),\n })\n\n yield actions.define({\n name: 'bots.plugins.disable',\n description: 'Turn a bot plugin, or an app plugin\\'s chat commands, off for one bot. A bot plugin\\'s config is kept.',\n risk: 'write',\n input: pluginInput,\n handler: ({ id, package: name }) => this.disablePlugin(id, name),\n })\n\n yield actions.define({\n name: 'bots.plugins.configure',\n description: 'Replace a bot plugin\\'s config on one bot and reload it.',\n risk: 'write',\n input: pluginInput.extend({ config: z.record(z.string(), z.any()) }),\n handler: ({ id, package: name, config }) => this.configurePlugin(id, name, config),\n })\n\n yield actions.define({\n name: 'bots.plugins.project',\n 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.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.projectPlugins(),\n })\n\n yield actions.define({\n name: 'bots.plugins.setProject',\n 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.',\n risk: 'write',\n input: z.object({ package: z.string().describe('Bot plugin package name'), enabled: z.boolean() }),\n handler: ({ package: name, enabled }) => this.setProjectPlugin(name, enabled),\n })\n\n yield actions.define({\n name: 'bots.runs',\n 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.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(RUN_BUFFER_SIZE).optional(),\n before: z.number().optional().describe('Only runs started before this time (ms since 1970), to page back'),\n plugin: z.string().optional().describe('Only this plugin\\'s runs: its package name'),\n status: z.enum(['ok', 'error']).optional(),\n }),\n handler: ({ id, ...query }) => this.pluginRuns(id, query),\n })\n\n yield actions.define({\n name: 'bots.messages',\n 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.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(BUFFER_SIZE).optional(),\n channel: z.string().optional().describe('Group or user id to filter by'),\n 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'),\n sinceStart: z.boolean().optional().describe('Only messages received or sent since Mushin started'),\n }),\n handler: ({ id, ...options }) => this.messages(id, options),\n })\n\n yield actions.define({\n name: 'bots.media',\n 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.',\n risk: 'read',\n input: idInput.extend({\n segment: z.object({ type: z.string(), data: z.record(z.string(), z.any()) }).describe('The segment from the message record'),\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }).optional().describe('Where the message was sent; group files need it'),\n inline: z.boolean().optional().describe('Return the bytes as a data URL, for showing an image'),\n }),\n handler: ({ id, segment, channel, inline }) => this.media(id, segment, { channel, inline }),\n })\n\n yield actions.define({\n name: 'bots.forward',\n description: 'The messages of a forwarded chat history (a forward segment\\'s id), oldest first, each with its sender, time and segments.',\n risk: 'read',\n input: idInput.extend({ forward: z.string().min(1).describe('The id in the forward segment') }),\n handler: ({ id, forward }) => this.forwarded(id, forward),\n })\n\n yield actions.define({\n name: 'bots.logs',\n description: 'Log lines of one bot, oldest first: connection events, adapter errors, plugin warnings, flow lines, and why LLM chat skipped messages. Each line written while handling a message carries its record id (message). Narrow with message (a record id from bots.messages), since and until, query and level. Read this first when a bot misbehaves.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional(),\n message: z.string().optional().describe('Only lines written while handling this message: its record id, from bots.messages'),\n since: timeInput.optional().describe('From this time: an ISO date-time or ms since the epoch'),\n until: timeInput.optional().describe('Up to this time: an ISO date-time or ms since the epoch'),\n query: z.string().optional().describe('Only lines containing this text, ignoring case'),\n level: z.enum(['debug', 'info', 'warn', 'error']).optional().describe('Only lines at this level or above'),\n }),\n handler: ({ id, ...filter }) => this.logLines(id, filter),\n })\n\n yield actions.define({\n name: 'bots.channels',\n description: 'Channels (groups and private chats) a bot has seen recently.',\n risk: 'read',\n input: idInput.extend({ sinceStart: z.boolean().optional().describe('Only channels with messages since Mushin started') }),\n handler: ({ id, sinceStart }) => this.channels(id, { sinceStart }),\n })\n\n yield actions.define({\n name: 'bots.tryCommand',\n 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.',\n risk: 'read',\n input: z.object({\n name: z.string(),\n aliases: z.array(z.string()).optional(),\n prefixes: z.array(z.string()).optional().describe('The command\\'s own prefixes; empty uses the bot\\'s'),\n args: z.array(z.object({\n name: z.string(),\n type: z.enum(['text', 'number', 'boolean', 'user', 'choice']),\n optional: z.boolean().optional(),\n rest: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n choices: z.array(z.string()).optional(),\n })).default([]),\n text: z.string(),\n bot: z.string().optional().describe('Bot whose prefixes apply when the command has none of its own'),\n }),\n handler: (input) => this.tryCommand(input),\n })\n\n yield actions.define({\n name: 'bots.userChoices',\n description: 'People the bots have seen recently, as { value: user id, label, group: bot } choices.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.seen('user'),\n })\n\n yield actions.define({\n name: 'bots.groupChoices',\n description: 'Groups the bots have seen recently, as { value: group id, label, group: bot } choices.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.seen('group'),\n })\n\n yield actions.define({\n name: 'bots.usage',\n 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.',\n risk: 'read',\n input: idInput.extend({ message: z.string().describe('Message record id from bots.messages') }),\n handler: ({ id, message }) => this.usage(id, message),\n })\n\n yield actions.define({\n name: 'bots.contacts',\n 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.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.contacts(id),\n })\n\n yield actions.define({\n name: 'bots.sandbox',\n 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.',\n risk: 'write',\n input: idInput.extend({ text: z.string().min(1) }),\n handler: ({ id, text }) => this.sandbox(id, text),\n })\n\n yield actions.define({\n name: 'bots.send',\n description: 'Send a text message from a bot to a group or private chat.',\n risk: 'write',\n input: idInput.extend({\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }),\n text: z.string().min(1),\n }),\n handler: ({ id, channel, text }) => this.sendManual(id, channel, text),\n })\n }\n}\n"],"mappings":";;;;;;;AAyCA,MAAM,YAAY,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW,OAAO,UAAU;CAC9E,MAAM,KAAK,OAAO,UAAU,WAAW,QAAQ,KAAK,MAAM,KAAK;CAC/D,IAAI,OAAO,MAAM,EAAE,GAAG;EACpB,MAAM,SAAS;GAAE,MAAM;GAAU,SAAS,IAAI,MAAM;EAAiB,CAAC;EACtE,OAAO,EAAE;CACX;CACA,OAAO;AACT,CAAC;AAgBD,MAAM,SAAS;CAAC;CAAS;CAAQ;CAAQ;AAAO;AAChD,MAAM,MAAM;AAoEZ,MAAM,cAAc;AACpB,MAAM,cAAc;;AAEpB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AAExB,MAAM,kBAAkB;AACxB,MAAM,gBAA0B;CAAE,QAAQ;CAAO,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KAAK,OAAO;EAClC,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,sCAAsC,EAAE,CAAC;GAC9F,UAAU,EAAE,IAAI,cAAc,KAAK,MAAM,IAAI,OAAO;EACtD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO;GACP,UAAU,EAAE,SAAS,KAAK,SAAS,EAAE;EACvC,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACjD,UAAU,EAAE,IAAI,WAAW,KAAK,QAAQ,IAAI,IAAI;EAClD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO;IACpB,SAAS,EAAE,OAAO;KAAE,MAAM,EAAE,KAAK,CAAC,SAAS,SAAS,CAAC;KAAG,IAAI,EAAE,OAAO;IAAE,CAAC;IACxE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;GACxB,CAAC;GACD,UAAU,EAAE,IAAI,SAAS,WAAW,KAAK,WAAW,IAAI,SAAS,IAAI;EACvE,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import {\n type ChannelInfo, Context, currentPackageName, type DependencyGraph, describeMissing, dependencyReport, envReference, type LogTag, type MissingDependency, logTag, type Exporter, type Fiber, fiberError, fiberStatus, isMasked, Logger, mask, type Message,\n type MessageRecord, messageType, MushinError, type Plugin, type ProvidedItem, type Provenance, pluginSchema, randomId, resolveEnvReferences, type Segment, segmentsToText, Service, toJsonSchema,\n type UsageEvent, usage, validatePluginConfig, z, maskSecrets, restoreMasked, secretFields,\n} from '@mushinjs/core'\nimport type {} from '@mushinjs/plugin-storage'\nimport { MessageArchive } from './archive'\nimport { Bot, type BotHooks, byteSize, type PluginRunReport, type Session } from './bot'\nimport { type CommandArg, type CommandDef, type CommandEntry, commandConflicts, type CommandSettings, commandMatches, commandUsage, DEFAULT_PREFIXES, helpText, parseArgs, requiredRole, splitCommand } from './commands'\nimport { type AdapterType, type BotPluginEntry, type BotRecord, type BotStatus, isSandbox, type PermissionProvider, type PluginRun, roleAtLeast } from './types'\n\ndeclare module '@mushinjs/core' {\n interface Context {\n bots: BotManager\n bot: Bot\n }\n\n interface Events {\n 'bots/changed'(): void\n 'bots/status'(status: BotStatusInfo): void\n 'bots/message'(record: MessageRecord): void\n 'bots/log'(line: BotLogLine): void\n 'bots/command'(call: CommandCall): void\n 'bots/run'(run: PluginRun): void\n }\n}\n\n/** One log line written inside a bot's context: its adapter, its plugins, or the bot service itself. */\nexport interface BotLogLine {\n botId: string\n sn: number\n ts: number\n type: string\n name: string\n tag: LogTag\n text: string\n /** Record id of the message being handled when the line was written. */\n message?: string\n}\n\n/** A time as an ISO date-time or ms since the epoch, as ms. */\nconst timeInput = z.union([z.number(), z.string()]).transform((value, check) => {\n const ms = typeof value === 'number' ? value : Date.parse(value)\n if (Number.isNaN(ms)) {\n check.addIssue({ code: 'custom', message: `\"${value}\" is not a time` })\n return z.NEVER\n }\n return ms\n})\n\n/** What `bots.logs` can narrow the lines to. */\nexport interface LogFilter {\n limit?: number\n /** Only lines written while handling this message (its record id). */\n message?: string\n /** Times in ms since the epoch. */\n since?: number\n until?: number\n /** Case-insensitive text the line contains. */\n query?: string\n /** This level and above. */\n level?: 'debug' | 'info' | 'warn' | 'error'\n}\n\nconst LEVELS = ['debug', 'info', 'warn', 'error']\n\n/**\n * Orders log lines read from the daily files. Appending is asynchronous, so lines written in the same\n * millisecond can land in the file out of order; the sequence number breaks the tie.\n */\nexport const byTime = (a: { ts: number; sn: number }, b: { ts: number; sn: number }) => a.ts - b.ts || a.sn - b.sn\nconst DAY = 86_400_000\n\n/** A message ran a registered command. */\nexport interface CommandCall {\n botId: string\n name: string\n source: CommandEntry['source']\n userId: string\n channel: ChannelInfo\n at: number\n}\n\nexport interface RunCommandInput {\n bot: string\n command: string\n target?: 'master' | 'group'\n group?: string\n user?: string\n}\n\n/** Lists commands a plugin provides on a bot, e.g. the command nodes of the flows attached to it. */\nexport type CommandProvider = (botId: string) => CommandEntry[]\n\n/**\n * A command an app plugin answers on the bots it is turned on for (`BotRecord.appPlugins`), or, when the plugin\n * picks the bots itself, on the bots `bots` picks.\n */\ninterface AppCommand {\n def: CommandDef\n plugin: string\n fiber: Fiber\n handler: (session: Session) => Promise<unknown> | unknown\n bots?: (botId: string) => boolean\n}\n\n/** A chat plugin across the project, for the Plugins page: its switch and the bots that have it on. */\nexport interface ProjectChatPlugin {\n package: string\n kind: 'app' | 'bot'\n /** For a bot plugin, its project switch; an app plugin's is its entry on the Plugins page. */\n enabled: boolean\n /** An essential bot plugin has no project switch. */\n essential?: boolean\n /** Bots that have it on. */\n bots: string[]\n}\n\nexport interface BotStatusInfo {\n id: string\n status: BotStatus\n error?: string\n selfId?: string\n selfName?: string\n selfAvatar?: string\n /** An address that adds the bot to a group or server, from `bot.setInvite()`. */\n invite?: string\n}\n\ninterface Runtime {\n fiber?: Fiber\n ctx?: Context\n bot?: Bot\n plugins: Map<string, Fiber>\n pluginErrors: Map<string, string>\n /** Last connection status written to the global log. */\n logged?: BotStatus\n}\n\nconst STORAGE_KEY = 'bots'\nconst BUFFER_SIZE = 500\n/** Plugin runs kept in memory for each bot; older ones stay in the daily files. */\nconst RUN_BUFFER_SIZE = 300\nconst LOG_BUFFER_SIZE = 500\n// Bot logs include debug lines (e.g. why llm-chat skipped a message); the main log stream does not.\nconst LOG_LEVEL_DEBUG = 3\nconst plainExporter: Exporter = { colors: false, export() {} }\n\nconst adapterInput = z.object({\n type: z.string().describe('Adapter type id from bots.adapters, e.g. \"onebot\"'),\n config: z.record(z.string(), z.any()).describe('Adapter config matching the schema from bots.adapters'),\n})\n\n/** Messages whose costs are kept; older ones are forgotten. */\nconst USAGE_MESSAGES = 2000\n/** A runaway loop on one message stops being recorded after this many costs. */\nconst USAGE_EVENTS_PER_MESSAGE = 200\n\n/** What handling one message cost; see `bots.usage`. */\nexport interface MessageUsage {\n events: UsageEvent[]\n /** Size on the wire, roughly. */\n bytes?: number\n /** For a sent message: how long the platform took to accept it. */\n sendMs?: number\n /** For a sent message: the incoming message being handled when it was sent. */\n cause?: string\n /** For an incoming message: what was sent while handling it. */\n replies: string[]\n}\n\nconst idInput = z.object({ id: z.string().describe('Bot id from bots.list') })\nconst commandSettingsInput = z.object({\n prefixes: z.array(z.string().min(1)).optional().describe('Command prefixes; default [\"/\"]'),\n help: z.boolean().optional().describe('Answer /help with the list of commands; on unless false'),\n helpTitle: z.string().optional().describe('First line of the /help menu'),\n admins: z.array(z.string()).optional().describe('Deprecated: admins now live in the permissions plugin (permissions.update)'),\n helpByRole: z.boolean().optional().describe('/help lists only the commands the asker may run'),\n})\n\n/** Answers `/help` when nothing else on the bot registers a command called help. */\nconst HELP_COMMAND = { name: 'help', description: '列出所有指令' }\n\nconst pluginInput = idInput.extend({ package: z.string().describe('Plugin package name from bots.plugins.list: a bot plugin, or an app plugin with chat commands') })\n\n/**\n * Owns bot records and runs each enabled bot in its own isolated context:\n * the `bot` service, the adapter connection and the bot's plugins live there.\n */\nexport class BotManager extends Service {\n static inject = ['storage', 'actions', 'manager']\n\n private home: Context\n private records: BotRecord[] = []\n private adapterStore = new Map<string, AdapterType>()\n private runtimes = new Map<string, Runtime>()\n private startErrors = new Map<string, string>()\n private buffers = new Map<string, MessageRecord[]>()\n /** Messages in the database, when the database plugin runs. */\n private archive?: MessageArchive\n /** Runtime fiber of each running bot, to attribute log lines to the bot that wrote them. */\n private runtimeFibers = new Map<Fiber, string>()\n private logs = new Map<string, BotLogLine[]>()\n /** Sequence numbers of recent bot log lines; still recognized after the bot that wrote them stops. */\n private botLogSns = new Set<number>()\n private commandProviders = new Set<CommandProvider>()\n private appCommands = new Set<AppCommand>()\n /** Bot plugins turned off for the whole project; they run on no bot, whatever each bot says. */\n private projectOff = new Set<string>()\n private runs = new Map<string, PluginRun[]>()\n /** The context that registered each adapter, to tell which installed plugin adds it. */\n private adapterFibers = new Map<string, Fiber>()\n private permissionProvider?: PermissionProvider\n\n constructor(ctx: Context) {\n super(ctx, 'bots')\n this.home = ctx\n }\n\n /**\n * Bot lifecycle lines for the global log, tagged `bot` in the dashboard. Written from the manager's\n * own context, so they stay out of the bot's log, which has its own lines from inside the bot.\n */\n private get logger() {\n return this.home.logger('bot')\n }\n\n async *[Service.init]() {\n const stored = await this.home.storage.get<{ bots: BotRecord[]; off?: string[] }>(STORAGE_KEY)\n this.records = stored?.bots ?? []\n this.projectOff = new Set(stored?.off ?? [])\n for (const record of this.records) {\n for (const plugin of record.plugins ?? []) plugin.package = currentPackageName(plugin.package)\n }\n this.logger.info('loaded %d bot(s)', this.records.length)\n yield this.home.logger.exporter({\n colors: false,\n levels: { default: LOG_LEVEL_DEBUG },\n export: (message) => this.captureLog(message),\n })\n yield* this.defineActions()\n // The Plugins page shows how many commands and adapters each plugin adds.\n yield this.home.manager.defineProvides(() => this.provided())\n this.home.inject(['model', 'database'], async (ctx) => {\n const archive = new MessageArchive(ctx, (error) => this.logger.warn('saving a message to the database failed: %s', error))\n this.archive = archive\n ctx.effect(() => () => {\n if (this.archive === archive) this.archive = undefined\n }, 'bots message archive')\n try {\n const imported = await archive.start()\n if (imported) this.logger.info('imported %d message(s) from the message logs into the database', imported)\n } catch (error) {\n this.logger.warn('importing the message logs into the database failed: %s', error)\n if (this.archive === archive) this.archive = undefined\n }\n })\n if (this.home.offline) this.logger.info('offline: bots are not started')\n for (const record of this.home.offline ? [] : this.records) {\n if (record.enabled && this.adapterStore.has(record.adapter.type)) this.startSafely(record.id)\n }\n }\n\n // ---- adapters ----\n\n /** Registers an adapter type. Bots using it start when it loads and stop when it unloads. */\n defineAdapter<C>(adapter: AdapterType<C>) {\n const ctx = this.ctx\n return ctx.effect(() => {\n if (this.adapterStore.has(adapter.id)) throw new Error(`adapter \"${adapter.id}\" is already defined`)\n this.adapterStore.set(adapter.id, adapter)\n this.adapterFibers.set(adapter.id, ctx.fiber)\n this.logger.info('adapter %s is available', adapter.id)\n this.secureRecords(adapter as AdapterType).catch((error) => this.logger.warn('could not move the %s secrets of bots to .env: %s', adapter.id, error))\n for (const record of this.records) {\n if (this.home.offline) break\n if (record.enabled && record.adapter.type === adapter.id && !this.runtimes.has(record.id)) {\n this.startSafely(record.id)\n }\n }\n ctx.emit('bots/changed')\n return async () => {\n this.adapterStore.delete(adapter.id)\n this.adapterFibers.delete(adapter.id)\n this.logger.info('adapter %s was removed', adapter.id)\n for (const record of this.records) {\n if (record.adapter.type !== adapter.id || !this.runtimes.has(record.id)) continue\n await this.stopRuntime(record.id)\n this.startErrors.set(record.id, `Adapter \"${adapter.id}\" was unloaded`)\n this.emitStatus(record.id)\n }\n ctx.emit('bots/changed')\n }\n }, `bots.defineAdapter(${adapter.id})`)\n }\n\n /** The adapters by their `order`, then in the order they were added. */\n adapters() {\n const list = [...this.adapterStore.values()]\n list.sort((a, b) => (a.order ?? 0) - (b.order ?? 0))\n return list.map((adapter) => ({\n id: adapter.id,\n displayName: adapter.displayName,\n ...(adapter.description ? { description: adapter.description } : {}),\n ...(adapter.icon ? { icon: adapter.icon } : {}),\n ...(adapter.color ? { color: adapter.color } : {}),\n configSchema: toJsonSchema(adapter.config),\n secrets: adapter.secrets ?? [],\n segments: adapter.segments,\n groupRoles: !!adapter.groupRoles,\n avatars: adapter.avatars ?? {},\n hiddenFields: adapter.hiddenFields ?? {},\n links: adapter.links ?? [],\n ...(adapter.qrSetup ? { qrSetup: adapter.qrSetup } : {}),\n }))\n }\n\n /** Adapters that can send every segment in a message. */\n platformsFor(segments: Segment[]) {\n return [...this.adapterStore.values()]\n .filter((adapter) => segments.every((s) => adapter.segments.includes(s.type)))\n .map((adapter) => adapter.id)\n }\n\n // ---- records ----\n\n get(id: string) {\n const record = this.records.find((item) => item.id === id)\n if (!record) throw new MushinError('not_found', `No bot with id \"${id}\"`)\n return record\n }\n\n bot(id: string) {\n return this.runtimes.get(id)?.bot\n }\n\n status(id: string): BotStatusInfo {\n const bot = this.bot(id)\n if (bot) return { id, status: bot.status, error: bot.error, selfId: bot.selfId, selfName: bot.selfName, selfAvatar: bot.selfAvatar, invite: bot.invite }\n const error = this.startErrors.get(id)\n return { id, status: error ? 'error' : 'offline', error }\n }\n\n private emitStatus(id: string) {\n this.home.emit('bots/status', this.status(id))\n }\n\n /** Moves adapter secrets an older version saved in plain text to .env, once the adapter is known. */\n private async secureRecords(adapter: AdapterType) {\n let moved = 0\n for (const record of this.records) {\n if (record.adapter.type !== adapter.id) continue\n const result = await this.secureConfig(adapter.id, record, record.adapter.config)\n record.adapter = { ...record.adapter, config: result.config }\n moved += result.moved.length\n }\n if (moved) {\n await this.save()\n this.logger.info('moved %d %s bot secret(s) to .env', moved, adapter.id)\n }\n }\n\n /** Puts the secrets of an adapter config into .env and returns the config with `${NAME}` references. */\n private secureConfig(type: string, record: Pick<BotRecord, 'id' | 'name'> & { adapter?: BotRecord['adapter'] }, config: Record<string, any>) {\n const owner = /[A-Za-z0-9]/.test(record.name) ? record.name : record.id\n return this.home.storage.secrets.moveIn(config, { keys: this.adapterStore.get(type)?.secrets ?? [], name: ['bot', owner], previous: record.adapter?.config })\n }\n\n private redact(record: BotRecord) {\n const secrets = this.adapterStore.get(record.adapter.type)?.secrets ?? []\n const config = { ...record.adapter.config }\n for (const key of secrets) {\n // A `${NAME}` reference is not a secret: it shows where the value is.\n if (typeof config[key] === 'string' && config[key] && envReference(config[key]) === undefined) config[key] = mask(config[key])\n }\n return { ...record, adapter: { ...record.adapter, config } }\n }\n\n describe(record: BotRecord) {\n return { ...this.redact(record), ...this.status(record.id), connection: this.connectionOf(record) }\n }\n\n private connectionOf(record: BotRecord) {\n try {\n return this.adapterStore.get(record.adapter.type)?.describe?.(record.adapter.config, record.id)\n } catch {}\n }\n\n list() {\n return this.records.map((record) => this.describe(record))\n }\n\n private async save() {\n await this.home.storage.set(STORAGE_KEY, { bots: this.records, ...(this.projectOff.size ? { off: [...this.projectOff] } : {}) })\n this.home.emit('bots/changed')\n }\n\n private validateAdapter(type: string, config: unknown) {\n const adapter = this.adapterStore.get(type)\n if (!adapter) {\n const known = [...this.adapterStore.keys()].join(', ') || 'none'\n throw new MushinError('invalid_input', `Unknown adapter \"${type}\". Loaded adapters: ${known}`)\n }\n const result = adapter.config.safeParse(config)\n if (!result.success) throw new MushinError('invalid_input', z.prettifyError(result.error), result.error.issues)\n return result.data as Record<string, any>\n }\n\n /**\n * A new bot's adapter config. A bot created stopped may be saved half filled in (its connection\n * set up later, e.g. \"connect later\" in the dashboard); it is checked again when it starts.\n */\n private adapterConfigFor(input: { adapter: { type: string; config: Record<string, any> }; enabled?: boolean }) {\n try {\n return this.validateAdapter(input.adapter.type, input.adapter.config)\n } catch (error) {\n if (input.enabled !== false || !this.adapterStore.has(input.adapter.type)) throw error\n return { ...input.adapter.config }\n }\n }\n\n async create(input: { name: string; adapter: { type: string; config: Record<string, any> }; plugins?: { package: string; config?: Record<string, any> }[]; enabled?: boolean; provider?: string; commands?: CommandSettings }) {\n const id = randomId()\n const record: BotRecord = {\n id,\n name: input.name,\n enabled: input.enabled ?? true,\n adapter: { type: input.adapter.type, config: (await this.secureConfig(input.adapter.type, { id, name: input.name }, this.adapterConfigFor(input))).config },\n plugins: [],\n provider: input.provider,\n ...(input.commands ? { commands: input.commands } : {}),\n createdAt: Date.now(),\n }\n for (const item of input.plugins ?? []) {\n const plugin = await this.loadBotPlugin(item.package)\n validatePluginConfig(plugin, item.config ?? {})\n record.plugins.push({ package: item.package, enabled: true, config: await this.securePlugin(record, item.package, plugin, item.config ?? {}) })\n }\n this.records.push(record)\n await this.save()\n this.logger.info('created bot %s', this.label(record))\n if (record.enabled) await this.start(id).catch(() => {})\n return this.describe(record)\n }\n\n async update(id: string, patch: { name?: string; adapter?: { type: string; config: Record<string, any> }; provider?: string | null; commands?: CommandSettings }) {\n const record = this.get(id)\n if (patch.commands !== undefined) record.commands = { ...record.commands, ...patch.commands }\n if (patch.name !== undefined) record.name = patch.name\n if (patch.provider !== undefined) record.provider = patch.provider ?? undefined\n if (patch.adapter) {\n const secrets = this.adapterStore.get(patch.adapter.type)?.secrets ?? []\n const config = { ...patch.adapter.config }\n for (const key of secrets) {\n if (isMasked(config[key])) config[key] = record.adapter.config[key]\n }\n record.adapter = { type: patch.adapter.type, config: (await this.secureConfig(patch.adapter.type, record, this.validateAdapter(patch.adapter.type, config))).config }\n }\n await this.save()\n this.logger.info('updated bot %s', this.label(record))\n // The running bot reads its name and command settings from the record, so changing only them needs no restart.\n const restart = patch.adapter !== undefined || patch.provider !== undefined\n if (record.enabled && restart) await this.start(id).catch(() => {})\n return this.describe(record)\n }\n\n async remove(id: string) {\n const record = this.get(id)\n await this.stopRuntime(id)\n this.records = this.records.filter((item) => item !== record)\n this.buffers.delete(id)\n this.logs.delete(id)\n this.runs.delete(id)\n this.startErrors.delete(id)\n await this.save()\n this.logger.info('deleted bot %s', this.label(record))\n return { deleted: id }\n }\n\n // ---- runtimes ----\n\n private startSafely(id: string) {\n this.start(id).catch((error) => this.logger.warn('failed to start bot %s: %s', id, error))\n }\n\n async start(id: string) {\n const record = this.get(id)\n await this.stopRuntime(id)\n this.startErrors.delete(id)\n const adapter = this.adapterStore.get(record.adapter.type)\n if (!adapter) {\n const message = `Adapter \"${record.adapter.type}\" is not loaded; enable its plugin`\n this.startErrors.set(id, message)\n this.emitStatus(id)\n this.logger.warn('cannot start bot %s: %s', this.label(record), message)\n throw new MushinError('unavailable', message)\n }\n\n const runtime: Runtime = { plugins: new Map(), pluginErrors: new Map() }\n const loaded: { entry: BotPluginEntry; plugin: Plugin }[] = []\n for (const entry of record.plugins) {\n if (!entry.enabled || this.projectOff.has(entry.package)) continue\n try {\n const plugin = await this.loadBotPlugin(entry.package)\n // A key an older version or a hand edit left in plain text moves to .env.\n const secured = await this.securePlugin(record, entry.package, plugin, entry.config ?? {}, entry.config)\n if (JSON.stringify(secured) !== JSON.stringify(entry.config ?? {})) {\n entry.config = secured\n await this.save()\n }\n loaded.push({ entry, plugin })\n } catch (error) {\n runtime.pluginErrors.set(entry.package, error instanceof Error ? error.message : String(error))\n }\n }\n\n const hooks: BotHooks = {\n record: (partial) => this.record(partial),\n status: (bot) => {\n runtime.bot = bot\n // Connecting is left to the bot's own log, so a reconnect loop writes one error line here, not one per try.\n if (bot.status !== 'connecting' && bot.status !== runtime.logged && (runtime.logged || bot.status !== 'offline')) {\n runtime.logged = bot.status\n if (bot.status === 'error') this.logger.warn('bot %s: error (%s)', this.label(record), bot.error ?? 'no details')\n else this.logger.info('bot %s is %s', this.label(record), bot.status)\n }\n this.emitStatus(id)\n },\n commands: (bot) => this.commands(bot.id),\n commandCalled: (bot, entry, session) => {\n this.home.emit('bots/command', { botId: bot.id, name: entry.name, source: entry.source, userId: session.user.id, channel: session.channel, at: Date.now() })\n },\n builtinCommand: (bot, entry, session) => {\n if (entry.name !== HELP_COMMAND.name) return\n let entries = this.commands(bot.id)\n if (bot.record.commands?.helpByRole) {\n const role = session.role()\n entries = entries.filter((item) => {\n const required = requiredRole(item)\n return !required || roleAtLeast(role, required)\n })\n }\n return helpText(entries, bot.record.commands)\n },\n roleOf: (bot, userId) => this.permissionProvider?.roleOf(bot.id, userId),\n appCommand: (bot, entry) => this.appCommandFor(bot.id, entry),\n pluginRun: (bot, run, fiber) => this.recordRun(bot.id, run, fiber),\n usageScope: (bot, message) => {\n const entry = this.usageEntry(bot.id, message.id, true)!\n entry.bytes = byteSize(message.segments)\n return {\n botId: bot.id,\n messageId: message.id,\n report: (event) => {\n const target = this.usageEntry(bot.id, message.id, true)!\n if (target.events.length < USAGE_EVENTS_PER_MESSAGE) target.events.push(event)\n },\n }\n },\n sent: (bot, message, transfer) => {\n const entry = this.usageEntry(bot.id, message.id, true)!\n Object.assign(entry, { bytes: transfer.bytes }, transfer.ms !== undefined ? { sendMs: transfer.ms } : {}, transfer.cause ? { cause: transfer.cause } : {})\n if (transfer.cause) this.usageEntry(bot.id, transfer.cause)?.replies.push(message.id)\n },\n }\n this.runtimes.set(id, runtime)\n runtime.fiber = this.home.isolate('bot').plugin({\n name: `bot:${record.name}`,\n apply: (ctx: Context) => {\n runtime.ctx = ctx\n this.runtimeFibers.set(ctx.fiber, id)\n ctx.effect(() => () => this.runtimeFibers.delete(ctx.fiber), 'bot log attribution')\n const enabled = loaded.map(({ entry }) => entry.package.replace(/^@mushinjs\\/bot-plugin-/, ''))\n ctx.logger('bot').info('starting with the %s adapter; plugins: %s', record.adapter.type, enabled.join(', ') || 'none')\n for (const [name, error] of runtime.pluginErrors) ctx.logger('bot').warn('plugin %s did not load: %s', name, error)\n ctx.plugin(Bot, { record, hooks })\n // Secrets are `${NAME}` references to .env; the adapter and plugins get the values.\n ctx.plugin(adapter.plugin, this.home.storage.secrets.resolveAll(record.adapter.config, adapter.secrets ?? []))\n for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, resolveEnvReferences(entry.config)))\n },\n })\n await runtime.fiber\n runtime.bot = runtime.ctx?.get('bot') ?? runtime.bot\n const error = fiberError(runtime.fiber)\n if (error) this.logger.warn('bot %s failed to start: %s', this.label(record), error)\n else this.logger.info('started bot %s with the %s adapter', this.label(record), record.adapter.type)\n this.emitStatus(id)\n return this.status(id)\n }\n\n private async stopRuntime(id: string) {\n const runtime = this.runtimes.get(id)\n if (!runtime) return\n this.runtimes.delete(id)\n await runtime.fiber?.dispose()\n this.logger.info('stopped bot %s', this.label(this.records.find((item) => item.id === id) ?? id))\n this.emitStatus(id)\n }\n\n async setEnabled(id: string, enabled: boolean) {\n const record = this.get(id)\n record.enabled = enabled\n await this.save()\n if (enabled) return this.start(id)\n await this.stopRuntime(id)\n return this.status(id)\n }\n\n /** Log lines name a bot by its id; the dashboard links it to the bot. */\n private label(record: BotRecord | string) {\n return typeof record === 'string' ? record : record.id\n }\n\n // ---- bot plugins ----\n\n async loadBotPlugin(name: string) {\n const entry = await this.home.manager.findPackage(name)\n if (!entry) throw new MushinError('not_found', `Bot plugin \"${name}\" is not installed`)\n if (entry.manifest.kind !== 'bot') throw new MushinError('invalid_input', `\"${name}\" is an app plugin, not a bot plugin`)\n return this.home.manager.loadPlugin(name)\n }\n\n /**\n * The plugins a bot can turn on: every installed bot plugin, then each app plugin with chat commands (`kind: 'app'`),\n * with whether it is on for this bot and whether it is turned off for the whole project.\n */\n async plugins(id: string) {\n const record = this.get(id)\n const graph = await this.home.manager.graph()\n const apps = this.chatApps()\n const appEntries = graph.catalog\n .filter((entry) => entry.manifest.kind === 'app' && (apps.has(entry.package) || record.appPlugins?.includes(entry.package)))\n .map((entry) => {\n const commands = apps.get(entry.package)\n const enabled = !!record.appPlugins?.includes(entry.package)\n return {\n package: entry.package,\n kind: 'app' as const,\n version: entry.version,\n manifest: entry.manifest,\n enabled,\n // Its commands are only known while it runs; an app plugin that does not run is off on the Plugins page.\n ...(commands ? { commands } : { projectOff: true }),\n status: enabled && commands ? 'active' : 'disabled',\n }\n })\n return [...await this.botPlugins(id, graph), ...appEntries]\n }\n\n private async botPlugins(id: string, graph: DependencyGraph) {\n const record = this.get(id)\n const runtime = this.runtimes.get(id)\n const catalog = graph.catalog.filter((entry) => entry.manifest.kind === 'bot')\n return Promise.all(catalog.map(async (entry) => {\n const configured = record.plugins.find((item) => item.package === entry.package)\n let configSchema\n let secrets: string[] = []\n try {\n const plugin = await this.home.manager.loadPlugin(entry.package)\n configSchema = pluginSchema(plugin)\n secrets = secretFields(plugin)\n } catch {}\n const fiber = runtime?.plugins.get(entry.package)\n const report = dependencyReport(graph, entry.package)\n const missing = this.missingApps(report.requires)\n const projectOff = this.projectOff.has(entry.package)\n let status: string = configured?.enabled && !projectOff ? (runtime ? fiberStatus(fiber) : 'disabled') : 'disabled'\n if (status === 'pending' && missing.length) status = 'missing'\n return {\n package: entry.package,\n kind: 'bot' as const,\n ...(projectOff ? { projectOff } : {}),\n version: entry.version,\n manifest: entry.manifest,\n enabled: !!configured?.enabled,\n config: maskSecrets(configured?.config ?? {}, secrets),\n configSchema,\n status,\n error: runtime?.pluginErrors.get(entry.package) ?? (status === 'missing' ? describeMissing(missing) : fiberError(fiber)),\n dependencies: { requires: report.requires, optional: report.optional },\n ...(missing.length ? { missing } : {}),\n }\n }))\n }\n\n /** Required app plugins that are not installed, do not fit or are disabled. */\n private missingApps(requires: ReturnType<typeof dependencyReport>['requires']): MissingDependency[] {\n return requires\n .filter((dep) => dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled')\n .map((dep) => ({ package: dep.package, range: dep.range, reason: dep.problem as MissingDependency['reason'], ...(dep.version ? { version: dep.version } : {}) }))\n }\n\n /** The bot's entry for a plugin in `plugins()`. */\n private async pluginInfo(id: string, name: string) {\n return (await this.plugins(id)).find((item) => item.package === name)\n }\n\n /** Turns an app plugin's chat commands on or off for one bot. */\n private async setAppPlugin(id: string, name: string, enabled: boolean) {\n const record = this.get(id)\n const list = new Set(record.appPlugins ?? [])\n if (enabled) list.add(name)\n else list.delete(name)\n record.appPlugins = [...list]\n await this.save()\n this.logger.info('%s the commands of %s on bot %s', enabled ? 'turned on' : 'turned off', name, this.label(record))\n return this.pluginInfo(id, name)\n }\n\n async enablePlugin(id: string, name: string, config?: Record<string, any>) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app') {\n if (config) throw new MushinError('invalid_input', `${name} is an app plugin: its settings are on the Plugins page (plugins.configure)`)\n return this.setAppPlugin(id, name, true)\n }\n const plugin = await this.loadBotPlugin(name)\n const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires)\n if (missing.length) {\n throw new MushinError('unavailable', `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing })\n }\n let entry = record.plugins.find((item) => item.package === name)\n let nextConfig = restoreMasked(config ?? entry?.config ?? {}, entry?.config, secretFields(plugin))\n validatePluginConfig(plugin, nextConfig)\n nextConfig = await this.securePlugin(record, name, plugin, nextConfig, entry?.config)\n if (!entry) {\n entry = { package: name, enabled: true, config: nextConfig }\n record.plugins.push(entry)\n }\n entry.enabled = true\n entry.config = nextConfig\n await this.save()\n this.logger.info('enabled plugin %s on bot %s', name, this.label(record))\n this.reloadPlugin(id, entry, plugin)\n return this.pluginInfo(id, name)\n }\n\n async disablePlugin(id: string, name: string) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app' || record.appPlugins?.includes(name)) return this.setAppPlugin(id, name, false)\n const entry = record.plugins.find((item) => item.package === name)\n if (!entry) throw new MushinError('not_found', `${name} is not configured on this bot`)\n entry.enabled = false\n await this.save()\n this.logger.info('disabled plugin %s on bot %s', name, this.label(record))\n const runtime = this.runtimes.get(id)\n const fiber = runtime?.plugins.get(name)\n runtime?.plugins.delete(name)\n await fiber?.dispose()\n return this.pluginInfo(id, name)\n }\n\n async configurePlugin(id: string, name: string, config: Record<string, any>) {\n const record = this.get(id)\n if ((await this.home.manager.findPackage(name))?.manifest.kind === 'app') {\n throw new MushinError('invalid_input', `${name} is an app plugin: its settings are on the Plugins page (plugins.configure), the same for every bot`)\n }\n const entry = record.plugins.find((item) => item.package === name)\n if (!entry) return this.enablePlugin(id, name, config)\n const plugin = await this.loadBotPlugin(name)\n const next = restoreMasked(config, entry.config, secretFields(plugin))\n validatePluginConfig(plugin, next)\n entry.config = await this.securePlugin(record, name, plugin, next, entry.config)\n await this.save()\n this.logger.info('config of plugin %s on bot %s changed', name, this.label(record))\n if (entry.enabled) this.reloadPlugin(id, entry, plugin)\n return this.pluginInfo(id, name)\n }\n\n /** Puts the plain values of a bot plugin's secret fields into .env and returns the config with `${NAME}` references. */\n private async securePlugin(record: Pick<BotRecord, 'id' | 'name'>, name: string, plugin: Plugin, config: Record<string, any>, previous?: Record<string, any>) {\n const keys = secretFields(plugin)\n if (!keys.length) return config\n const short = name.replace(/^@[^/]+\\//, '').replace(/^(?:mushin-)?(?:bot-)?plugin-/, '')\n return (await this.home.storage.secrets.moveIn(config, { keys, name: ['bot', record.name || record.id, short], previous })).config\n }\n\n private reloadPlugin(id: string, entry: BotPluginEntry, plugin: Plugin) {\n const runtime = this.runtimes.get(id)\n if (!runtime?.ctx || this.projectOff.has(entry.package)) return\n runtime.plugins.get(entry.package)?.dispose()\n runtime.pluginErrors.delete(entry.package)\n runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, resolveEnvReferences(entry.config)))\n }\n\n /**\n * Turns a bot plugin on or off for the whole project. Off, it runs on no bot; each bot keeps its own switch and\n * settings, so turning it back on starts it again where it was on.\n */\n async setProjectPlugin(name: string, enabled: boolean) {\n const entry = await this.home.manager.findPackage(name)\n if (!entry) throw new MushinError('not_found', `Plugin \"${name}\" is not installed`)\n 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`)\n 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`)\n if (enabled === !this.projectOff.has(name)) return this.projectPlugin(name)\n if (enabled) this.projectOff.delete(name)\n else this.projectOff.add(name)\n await this.save()\n this.logger.info('%s %s for every bot', enabled ? 'turned on' : 'turned off', name)\n for (const record of this.records) {\n const item = record.plugins.find((plugin) => plugin.package === name && plugin.enabled)\n const runtime = this.runtimes.get(record.id)\n if (!item || !runtime) continue\n if (enabled) {\n try {\n this.reloadPlugin(record.id, item, await this.loadBotPlugin(name))\n } catch (error) {\n runtime.pluginErrors.set(name, error instanceof Error ? error.message : String(error))\n }\n } else {\n const fiber = runtime.plugins.get(name)\n runtime.plugins.delete(name)\n await fiber?.dispose()\n }\n }\n return this.projectPlugin(name)\n }\n\n /**\n * The chat plugins across the project: each bot plugin with its project switch, and each app plugin with chat\n * commands, with the bots that have it on.\n */\n async projectPlugins(): Promise<ProjectChatPlugin[]> {\n const catalog = (await this.home.manager.graph()).catalog\n const apps = this.chatApps()\n return catalog\n .filter((entry) => entry.manifest.kind === 'bot' || apps.has(entry.package))\n .map((entry) => {\n const bot = entry.manifest.kind === 'bot'\n return {\n package: entry.package,\n kind: bot ? 'bot' as const : 'app' as const,\n enabled: bot ? !this.projectOff.has(entry.package) : true,\n ...(bot && entry.manifest.essential ? { essential: true } : {}),\n bots: this.records\n .filter((record) => (bot ? record.plugins.some((item) => item.package === entry.package && item.enabled) : record.appPlugins?.includes(entry.package)))\n .map((record) => record.id),\n }\n })\n }\n\n private async projectPlugin(name: string) {\n return (await this.projectPlugins()).find((item) => item.package === name)\n }\n\n // ---- commands ----\n\n /** Adds commands to every bot's list. Removed when the calling plugin unloads. */\n defineCommands(provider: CommandProvider) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bots.defineCommands()')\n }\n\n /**\n * Answers a command from an app plugin, such as `/persona`, on the bots the user turned the plugin on for (on the\n * bot's Plugins page, or with `bots.plugins.enable`). A plugin that decides itself which bots answer, from its own\n * per-bot settings, passes `bots`, and then has no switch on the bot's page. It answers after flows, like `/help`,\n * and shows in the command list of each bot it answers on.\n */\n defineCommand(def: CommandDef, handler: AppCommand['handler'], options: { bots?: (botId: string) => boolean } = {}) {\n const ctx = this.ctx\n const command: AppCommand = { def, plugin: ctx.fiber.name, fiber: ctx.fiber, handler, bots: options.bots }\n return ctx.effect(() => {\n this.appCommands.add(command)\n return () => this.appCommands.delete(command)\n }, `bots.defineCommand(${def.name})`)\n }\n\n /** The app plugin command behind a command entry, if an app plugin answers it. */\n appCommandFor(botId: string, entry: CommandEntry) {\n if (entry.source.kind !== 'plugin') return\n return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && this.answersOn(item, botId))\n }\n\n /** Whether an app plugin's command answers on a bot: the plugin's own choice, or the bot's switch for the plugin. */\n private answersOn(command: AppCommand, botId: string) {\n if (command.bots) return command.bots(botId)\n const name = this.home.manager.packageOf(command.fiber)\n return !!name && !!this.records.find((record) => record.id === botId)?.appPlugins?.includes(name)\n }\n\n /** App plugins whose commands have a switch on each bot, with the names of those commands, by package. */\n private chatApps() {\n const apps = new Map<string, string[]>()\n for (const command of this.appCommands) {\n if (command.bots) continue\n const name = this.home.manager.packageOf(command.fiber)\n if (!name) continue\n const list = apps.get(name) ?? []\n if (!list.includes(command.def.name)) list.push(command.def.name)\n apps.set(name, list)\n }\n return apps\n }\n\n /** Lets the permissions plugin say who is master, admin or user on each bot. */\n usePermissions(provider: PermissionProvider) {\n return this.ctx.effect(() => {\n this.permissionProvider = provider\n return () => {\n if (this.permissionProvider === provider) this.permissionProvider = undefined\n }\n }, 'bots.usePermissions()')\n }\n\n /** A user's role on a bot; nothing when the permissions plugin is not running. */\n roleOf(botId: string, userId: string) {\n return this.permissionProvider?.roleOf(botId, userId)\n }\n\n /** Commands registered on one bot: from command providers such as flows, its plugins, and the built-in help. */\n commands(botId: string): CommandEntry[] {\n const record = this.records.find((item) => item.id === botId)\n if (!record) return []\n const entries: CommandEntry[] = []\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider(botId))\n } catch (error) {\n this.logger.warn('listing commands failed: %s', error)\n }\n }\n entries.push(...(this.runtimes.get(botId)?.bot?.localCommands() ?? []))\n for (const command of this.appCommands) {\n if (!this.answersOn(command, botId)) continue\n entries.push({ ...command.def, botId, source: { kind: 'plugin', id: command.plugin, name: command.plugin } })\n }\n if (record.commands?.help !== false && !entries.some((entry) => commandMatches(entry, HELP_COMMAND.name))) {\n entries.push({ ...HELP_COMMAND, botId, source: { kind: 'builtin', id: 'help', name: 'help' } })\n }\n return entries\n }\n\n /** Commands of one bot or of every bot, with names that more than one source registers. */\n commandList(botId?: string) {\n if (botId) this.get(botId)\n const entries = (botId ? [botId] : this.records.map((record) => record.id)).flatMap((id) => this.commands(id))\n const conflicts = commandConflicts(entries).map((item) => ({ botId: item.botId, name: item.name, sources: item.entries.map((entry) => entry.source) }))\n return { commands: entries, conflicts }\n }\n\n /**\n * Runs a command as if a master sent it. With a target it really runs on the bot: in that group,\n * or in the master's private chat, and the replies are sent. Without one it only previews where\n * the message would go (through flows), so nothing is sent.\n */\n async runCommand(input: RunCommandInput, source?: Provenance) {\n const record = this.get(input.bot)\n const prefix = record.commands?.prefixes?.find(Boolean) ?? '/'\n const text = /^\\p{L}/u.test(input.command) && !input.command.startsWith(prefix) ? `${prefix}${input.command}` : input.command\n if (!input.target) {\n const flows = this.home.get('flows') as { route(botId: string, input: { text: string; role?: string }): Promise<unknown> } | undefined\n if (!flows) throw new MushinError('unavailable', 'Previewing a command needs the flows plugin; give a target to run it for real')\n return { simulated: true, text, route: await flows.route(record.id, { text, role: 'master' }) }\n }\n const bot = this.bot(record.id)\n if (!bot || this.status(record.id).status !== 'online') throw new MushinError('unavailable', `Bot \"${record.name}\" is not online`)\n const permissions = this.home.get('permissions') as { get(botId: string): { masters: string[] } } | undefined\n const userId = input.user ?? permissions?.get(record.id).masters[0]\n if (!userId) throw new MushinError('invalid_input', `Bot \"${record.name}\" has no master; add one with permissions.update or pass user`)\n if (input.target === 'group' && !input.group) throw new MushinError('invalid_input', 'Pass the group id to run a command in a group')\n const channel: ChannelInfo = input.target === 'group' ? { type: 'group', id: input.group! } : { type: 'private', id: userId }\n const replies: MessageRecord[] = []\n const collect = (message: MessageRecord) => {\n if (message.botId === record.id && message.direction === 'out' && message.channel.id === channel.id) replies.push(message)\n }\n const stop = this.home.on('bots/message', collect)\n try {\n await bot.receive({ channel, user: { id: userId }, segments: [{ type: 'text', data: { text } }] }, { source })\n } finally {\n stop()\n }\n return {\n simulated: false,\n text,\n channel,\n user: userId,\n replies: replies.map((reply) => segmentsToText(reply.segments)),\n }\n }\n\n // ---- plugin runs ----\n\n /** The installed plugin a context of a bot belongs to: one of the bot's plugins, else an app plugin. */\n private packageIn(botId: string, fiber: Fiber | undefined) {\n if (!fiber) return\n const runtime = this.runtimes.get(botId)\n if (runtime) {\n const owners = new Map<Fiber, string>()\n for (const [name, plugin] of runtime.plugins) owners.set(plugin.ctx.fiber, name)\n for (let current: Fiber | undefined = fiber; current; current = current.parent?.fiber === current ? undefined : current.parent?.fiber) {\n const name = owners.get(current)\n if (name) return name\n }\n }\n return this.home.manager.packageOf(fiber)\n }\n\n private recordRun(botId: string, report: PluginRunReport, fiber?: Fiber) {\n const run: PluginRun = { id: randomId(8), botId, ...report, plugin: this.packageIn(botId, fiber) ?? report.plugin }\n let buffer = this.runs.get(botId)\n if (!buffer) this.runs.set(botId, buffer = [])\n buffer.push(run)\n if (buffer.length > RUN_BUFFER_SIZE) buffer.splice(0, buffer.length - RUN_BUFFER_SIZE)\n const day = new Date(run.startedAt).toISOString().slice(0, 10)\n this.home.storage.append(`runs/${botId}/${day}`, run).catch(() => {})\n this.home.emit('bots/run', run)\n }\n\n /**\n * What plugins did with a bot's messages, newest first: each message a plugin replied to, kept from the plugins\n * after it, or failed on. Flow runs are in `flows.history`.\n */\n async pluginRuns(id: string, query: { limit?: number; before?: number; plugin?: string; status?: PluginRun['status'] } = {}) {\n this.get(id)\n let buffer = this.runs.get(id)\n if (!buffer) {\n // Today's runs from the file, with any recorded while it was read.\n const day = new Date().toISOString().slice(0, 10)\n const stored = await this.home.storage.tail<PluginRun>(`runs/${id}/${day}`, RUN_BUFFER_SIZE)\n const current = this.runs.get(id) ?? []\n buffer = [...stored.filter((run) => !current.some((item) => item.id === run.id)), ...current].slice(-RUN_BUFFER_SIZE)\n this.runs.set(id, buffer)\n }\n const limit = query.limit ?? 50\n const matching = buffer.filter((run) => (query.before === undefined || run.startedAt < query.before)\n && (!query.plugin || run.plugin === query.plugin)\n && (!query.status || run.status === query.status))\n return { runs: matching.slice(-limit).reverse(), more: matching.length > limit }\n }\n\n /** What this plugin knows of what others add: chat commands (app plugins' and bot plugins'), and adapters. */\n private *provided(): Iterable<ProvidedItem> {\n for (const command of this.appCommands) yield { kind: 'command', name: command.def.name, fiber: command.fiber }\n for (const [id, runtime] of this.runtimes) {\n for (const command of runtime.bot?.ownCommandList() ?? []) {\n yield { kind: 'command', name: command.name, package: this.packageIn(id, command.fiber), fiber: command.fiber }\n }\n }\n for (const [id, fiber] of this.adapterFibers) yield { kind: 'adapter', name: id, fiber }\n }\n\n // ---- logs ----\n\n /** Finds the bot whose context wrote a log message, by walking up from the writing fiber. */\n private botOf(message: Message) {\n let fiber = message.fiber?.deref()\n while (fiber) {\n const id = this.runtimeFibers.get(fiber)\n if (id) return id\n const parent = fiber.parent?.fiber\n if (!parent || parent === fiber) return\n fiber = parent\n }\n }\n\n /** True when a log line was written inside a bot; it belongs in that bot's log, not the global one. */\n isBotLog(message: Message) {\n return this.botLogSns.has(message.sn) || !!this.botOf(message)\n }\n\n private captureLog(message: Message) {\n const botId = this.botOf(message)\n if (!botId) return\n this.botLogSns.add(message.sn)\n // The global log buffer holds 1000 lines; remember a little more than that.\n if (this.botLogSns.size > 2000) this.botLogSns.delete(this.botLogSns.values().next().value!)\n const line: BotLogLine = {\n botId,\n sn: message.sn,\n ts: message.ts,\n type: message.type,\n name: message.name,\n tag: logTag(message.name),\n text: Logger.format(plainExporter, message),\n }\n const handling = usage.current()\n if (handling?.botId === botId) line.message = handling.messageId\n let buffer = this.logs.get(botId)\n if (!buffer) this.logs.set(botId, buffer = [])\n buffer.push(line)\n if (buffer.length > LOG_BUFFER_SIZE) buffer.splice(0, buffer.length - LOG_BUFFER_SIZE)\n this.home.emit('bots/log', line)\n const day = new Date(line.ts).toISOString().slice(0, 10)\n this.home.storage.append(`logs/${botId}/${day}`, line).catch(() => {})\n }\n\n async logLines(id: string, filter: LogFilter = {}) {\n this.get(id)\n const limit = filter.limit ?? 200\n let lines: BotLogLine[]\n if (filter.since !== undefined || filter.until !== undefined || filter.message) {\n // Older lines are read from the daily files: the days of the time range, or the last three for a message.\n const until = filter.until ?? Date.now()\n const since = filter.since ?? (filter.message ? until - 2 * DAY : until)\n const days: string[] = []\n const first = Date.parse(new Date(Math.max(since, until - 31 * DAY)).toISOString().slice(0, 10))\n for (let at = first; at <= until; at += DAY) days.push(new Date(at).toISOString().slice(0, 10))\n lines = (await Promise.all(days.map((day) => this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, 100_000)))).flat()\n lines = lines.filter((line) => line.ts >= (filter.since ?? 0) && line.ts <= until).sort(byTime)\n } else {\n let buffer = this.logs.get(id)\n if (!buffer) {\n const day = new Date().toISOString().slice(0, 10)\n buffer = (await this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, LOG_BUFFER_SIZE)).sort(byTime)\n this.logs.set(id, buffer)\n }\n lines = buffer\n }\n const query = filter.query?.toLowerCase()\n const level = filter.level ? LEVELS.indexOf(filter.level) : -1\n return lines\n // Lines stored before tags existed get one from their logger name.\n .map((line) => (line.tag ? line : { ...line, tag: logTag(line.name) }))\n .filter((line) => (!filter.message || line.message === filter.message)\n && (!query || line.text.toLowerCase().includes(query))\n && (level < 0 || LEVELS.indexOf(line.type) >= level))\n .slice(-limit)\n }\n\n // ---- messages ----\n\n /** Messages recorded since Mushin started, for the live conversation. */\n private recent = new WeakSet<MessageRecord>()\n /** What handling each recent message cost, in memory only; see `bots.usage`. */\n private usages = new Map<string, MessageUsage>()\n\n private usageEntry(botId: string, messageId: string, create = false) {\n const key = `${botId}:${messageId}`\n let entry = this.usages.get(key)\n if (!entry && create) {\n this.usages.set(key, entry = { events: [], replies: [] })\n if (this.usages.size > USAGE_MESSAGES) this.usages.delete(this.usages.keys().next().value!)\n }\n return entry\n }\n\n /** A message's costs, and for a reply the costs of the message it answered. */\n usage(botId: string, messageId: string) {\n const entry = this.usageEntry(botId, messageId)\n if (!entry) return null\n const cause = entry.cause ? this.usageEntry(botId, entry.cause) : undefined\n return { ...entry, ...(cause ? { causeEvents: cause.events } : {}) }\n }\n\n private record(partial: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord {\n const record: MessageRecord = {\n ...partial,\n id: randomId(8),\n type: messageType(partial.segments),\n platforms: this.platformsFor(partial.segments),\n }\n let buffer = this.buffers.get(record.botId)\n if (!buffer) this.buffers.set(record.botId, buffer = [])\n buffer.push(record)\n if (buffer.length > BUFFER_SIZE) buffer.splice(0, buffer.length - BUFFER_SIZE)\n const day = new Date(record.timestamp).toISOString().slice(0, 10)\n this.home.storage.append(`messages/${record.botId}/${day}`, record).catch((error) => {\n this.logger.warn('failed to write message log: %s', error)\n })\n this.recent.add(record)\n this.archive?.add(record)\n this.home.emit('bots/message', record)\n return record\n }\n\n /**\n * Recent messages of a bot, oldest first. With the database plugin, a channel's history and\n * older pages (`before`) come from the database; otherwise from today's log and memory.\n */\n async messages(id: string, options: { limit?: number; channel?: string; before?: number; sinceStart?: boolean } = {}) {\n this.get(id)\n const limit = options.limit ?? 100\n if (options.sinceStart) {\n const list = (this.buffers.get(id) ?? []).filter((record) => this.recent.has(record) && (!options.channel || record.channel.id === options.channel))\n return list.slice(-limit)\n }\n const archive = this.archive?.ready ? this.archive : undefined\n if (archive && (options.channel || options.before)) return archive.query(id, { ...options, limit })\n let buffer = this.buffers.get(id)\n if (!buffer) {\n const day = new Date().toISOString().slice(0, 10)\n buffer = archive\n ? await archive.query(id, { limit: BUFFER_SIZE })\n : await this.home.storage.tail<MessageRecord>(`messages/${id}/${day}`, BUFFER_SIZE)\n // Messages recorded while loading are already in the buffer that `record` made.\n const current = this.buffers.get(id)\n if (current) buffer = [...buffer.filter((item) => !current.some((record) => record.id === item.id)), ...current].slice(-BUFFER_SIZE)\n this.buffers.set(id, buffer)\n }\n if (options.before) buffer = buffer.filter((record) => record.timestamp < options.before!)\n const list = options.channel ? buffer.filter((record) => record.channel.id === options.channel) : buffer\n return list.slice(-limit)\n }\n\n /** Channels seen recently, newest first, for the live view's channel list. */\n async channels(id: string, options: { sinceStart?: boolean } = {}) {\n const seen = new Map<string, ChannelInfo & { lastAt: number; lastText: string }>()\n for (const record of await this.messages(id, { limit: BUFFER_SIZE, sinceStart: options.sinceStart })) {\n const key = `${record.channel.type}:${record.channel.id}`\n const text = record.segments.map((s) => (s.type === 'text' ? s.data.text : `[${s.type}]`)).join('')\n seen.set(key, { ...record.channel, name: record.channel.name ?? seen.get(key)?.name, lastAt: record.timestamp, lastText: text.slice(0, 80) })\n }\n return [...seen.values()].sort((a, b) => b.lastAt - a.lastAt)\n }\n\n /** How a command reads a message; see the `bots.tryCommand` action. */\n tryCommand(input: { name: string; aliases?: string[]; prefixes?: string[]; args: CommandArg[]; text: string; bot?: string }) {\n const own = input.prefixes?.filter(Boolean) ?? []\n const record = input.bot ? this.records.find((item) => item.id === input.bot) : undefined\n const prefixes = own.length ? own : record?.commands?.prefixes?.filter(Boolean).length ? record.commands.prefixes!.filter(Boolean) : DEFAULT_PREFIXES\n const def = { name: input.name, args: input.args, prefixes }\n const usage = commandUsage(def)\n const parsed = splitCommand(input.text, prefixes)\n if (!parsed) return { matched: false as const, reason: 'prefix' as const, prefixes, usage }\n if (!commandMatches({ name: input.name, aliases: input.aliases }, parsed.name)) return { matched: false as const, reason: 'name' as const, prefixes, usage }\n return { matched: true as const, prefix: parsed.prefix, rest: parsed.rest, usage, ...parseArgs(input.args, parsed.rest) }\n }\n\n /**\n * People or groups the bots have seen recently, newest first, as `{ value, label, group }`\n * choices: the label is `name (id)`, the group the bot's name. For lists such as a permission\n * node's allow and block lists.\n */\n async seen(kind: 'user' | 'group') {\n const found = new Map<string, { value: string; label: string; group: string; at: number }>()\n for (const record of this.records) {\n for (const message of await this.messages(record.id, { limit: BUFFER_SIZE }).catch(() => [])) {\n const id = kind === 'user' ? (message.direction === 'in' ? message.user.id : '') : message.channel.type === 'group' ? message.channel.id : ''\n if (!id || isSandbox(message.channel)) continue\n const name = kind === 'user' ? message.user.name : message.channel.name\n const previous = found.get(id)\n const label = name || (previous?.label.endsWith(`(${id})`) ? previous.label : '')\n found.set(id, { value: id, label: label && !label.endsWith(`(${id})`) ? `${label} (${id})` : label || id, group: record.name, at: message.timestamp })\n }\n }\n return [...found.values()].sort((a, b) => b.at - a.at).map(({ at: _, ...choice }) => choice)\n }\n\n /** The account's friends and groups, from the platform; empty when the bot is offline or the adapter cannot tell. */\n async contacts(id: string) {\n const bot = this.bot(id)\n if (!bot || bot.status !== 'online') return []\n return bot.contacts()\n }\n\n /** The sandbox's test user writes to the bot; see `Bot.sandbox`. */\n sandbox(id: string, text: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n bot.sandbox(text)\n return { ok: true }\n }\n\n async sendManual(id: string, channel: ChannelInfo, text: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n return bot.deliver(channel, text, { source: { kind: 'manual' } })\n }\n\n /** A fresh address of a message's image, video or file, from the platform. */\n async media(id: string, segment: Segment, options: { channel?: ChannelInfo; inline?: boolean }) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n const media = await bot.media(segment, options)\n if (!media) throw new MushinError('not_found', 'The platform no longer has this file')\n return media\n }\n\n /** The messages of a forwarded chat history, from the platform. */\n async forwarded(id: string, forward: string) {\n const bot = this.bot(id)\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\n return { messages: await bot.forward(forward) }\n }\n\n // ---- actions ----\n\n private *defineActions() {\n const actions = this.home.actions\n\n yield actions.define({\n name: 'bots.adapters',\n description: 'List loaded adapter types (e.g. \"onebot\") with their config JSON Schemas.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.adapters(),\n })\n\n yield actions.define({\n name: 'bots.list',\n description: 'List bots with their connection status, adapter and enabled plugins. Secrets are masked.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.list(),\n })\n\n yield actions.define({\n name: 'bots.get',\n description: 'Get one bot with its status.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.describe(this.get(id)),\n })\n\n yield actions.define({\n name: 'bots.create',\n 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.',\n risk: 'write',\n input: z.object({\n name: z.string().min(1),\n adapter: adapterInput,\n plugins: z.array(z.object({ package: z.string(), config: z.record(z.string(), z.any()).optional() })).optional()\n .describe('Bot plugins to enable right away, e.g. @mushinjs/bot-plugin-llm-chat'),\n enabled: z.boolean().optional(),\n provider: z.string().optional().describe('Default provider or model profile id for this bot\\'s LLM plugins'),\n commands: commandSettingsInput.optional(),\n }),\n handler: (input) => this.create(input),\n })\n\n yield actions.define({\n name: 'bots.update',\n 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.',\n risk: 'write',\n input: idInput.extend({\n name: z.string().min(1).optional(),\n adapter: adapterInput.optional(),\n provider: z.string().nullable().optional(),\n commands: commandSettingsInput.optional().describe('Command prefixes and the built-in /help; changing only these does not restart the bot'),\n }),\n handler: ({ id, ...patch }) => this.update(id, patch),\n })\n\n yield actions.define({\n name: 'commands.list',\n 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.',\n risk: 'read',\n input: z.object({ bot: z.string().optional().describe('Bot id from bots.list; all bots when omitted') }),\n handler: ({ bot }) => this.commandList(bot),\n })\n\n yield actions.define({\n name: 'bots.commands.run',\n 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.',\n risk: 'write',\n input: z.object({\n bot: z.string().describe('Bot id from bots.list'),\n command: z.string().min(1).describe('The command with its arguments, e.g. \"/checkin\" or \"/score 85\"'),\n target: z.enum(['master', 'group']).optional().describe('Where to run it for real; omit to only preview'),\n group: z.string().optional().describe('Group id, with target \"group\"'),\n user: z.string().optional().describe('Run as this user id instead of the first master'),\n }),\n handler: (input, caller) => this.runCommand(input, caller.kind === 'fairy' && caller.session ? { kind: 'fairy', session: caller.session } : undefined),\n })\n\n yield actions.define({\n name: 'bots.delete',\n description: 'Delete a bot and its settings. Message logs on disk are kept.',\n risk: 'dangerous',\n input: idInput,\n handler: ({ id }) => this.remove(id),\n })\n\n yield actions.define({\n name: 'bots.start',\n description: 'Enable and start (or restart) a bot.',\n risk: 'write',\n input: idInput,\n handler: ({ id }) => this.setEnabled(id, true),\n })\n\n yield actions.define({\n name: 'bots.stop',\n description: 'Stop and disable a bot.',\n risk: 'write',\n input: idInput,\n handler: ({ id }) => this.setEnabled(id, false),\n })\n\n yield actions.define({\n name: 'bots.plugins.list',\n 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.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.plugins(id),\n })\n\n yield actions.define({\n name: 'bots.plugins.enable',\n 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).',\n risk: 'write',\n input: pluginInput.extend({ config: z.record(z.string(), z.any()).optional() }),\n handler: ({ id, package: name, config }) => this.enablePlugin(id, name, config),\n })\n\n yield actions.define({\n name: 'bots.plugins.disable',\n description: 'Turn a bot plugin, or an app plugin\\'s chat commands, off for one bot. A bot plugin\\'s config is kept.',\n risk: 'write',\n input: pluginInput,\n handler: ({ id, package: name }) => this.disablePlugin(id, name),\n })\n\n yield actions.define({\n name: 'bots.plugins.configure',\n description: 'Replace a bot plugin\\'s config on one bot and reload it.',\n risk: 'write',\n input: pluginInput.extend({ config: z.record(z.string(), z.any()) }),\n handler: ({ id, package: name, config }) => this.configurePlugin(id, name, config),\n })\n\n yield actions.define({\n name: 'bots.plugins.project',\n 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.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.projectPlugins(),\n })\n\n yield actions.define({\n name: 'bots.plugins.setProject',\n 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.',\n risk: 'write',\n input: z.object({ package: z.string().describe('Bot plugin package name'), enabled: z.boolean() }),\n handler: ({ package: name, enabled }) => this.setProjectPlugin(name, enabled),\n })\n\n yield actions.define({\n name: 'bots.runs',\n 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.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(RUN_BUFFER_SIZE).optional(),\n before: z.number().optional().describe('Only runs started before this time (ms since 1970), to page back'),\n plugin: z.string().optional().describe('Only this plugin\\'s runs: its package name'),\n status: z.enum(['ok', 'error']).optional(),\n }),\n handler: ({ id, ...query }) => this.pluginRuns(id, query),\n })\n\n yield actions.define({\n name: 'bots.messages',\n 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.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(BUFFER_SIZE).optional(),\n channel: z.string().optional().describe('Group or user id to filter by'),\n 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'),\n sinceStart: z.boolean().optional().describe('Only messages received or sent since Mushin started'),\n }),\n handler: ({ id, ...options }) => this.messages(id, options),\n })\n\n yield actions.define({\n name: 'bots.media',\n 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.',\n risk: 'read',\n input: idInput.extend({\n segment: z.object({ type: z.string(), data: z.record(z.string(), z.any()) }).describe('The segment from the message record'),\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }).optional().describe('Where the message was sent; group files need it'),\n inline: z.boolean().optional().describe('Return the bytes as a data URL, for showing an image'),\n }),\n handler: ({ id, segment, channel, inline }) => this.media(id, segment, { channel, inline }),\n })\n\n yield actions.define({\n name: 'bots.forward',\n description: 'The messages of a forwarded chat history (a forward segment\\'s id), oldest first, each with its sender, time and segments.',\n risk: 'read',\n input: idInput.extend({ forward: z.string().min(1).describe('The id in the forward segment') }),\n handler: ({ id, forward }) => this.forwarded(id, forward),\n })\n\n yield actions.define({\n name: 'bots.logs',\n description: 'Log lines of one bot, oldest first: connection events, adapter errors, plugin warnings, flow lines, and why LLM chat skipped messages. Each line written while handling a message carries its record id (message). Narrow with message (a record id from bots.messages), since and until, query and level. Read this first when a bot misbehaves.',\n risk: 'read',\n input: idInput.extend({\n limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional(),\n message: z.string().optional().describe('Only lines written while handling this message: its record id, from bots.messages'),\n since: timeInput.optional().describe('From this time: an ISO date-time or ms since the epoch'),\n until: timeInput.optional().describe('Up to this time: an ISO date-time or ms since the epoch'),\n query: z.string().optional().describe('Only lines containing this text, ignoring case'),\n level: z.enum(['debug', 'info', 'warn', 'error']).optional().describe('Only lines at this level or above'),\n }),\n handler: ({ id, ...filter }) => this.logLines(id, filter),\n })\n\n yield actions.define({\n name: 'bots.channels',\n description: 'Channels (groups and private chats) a bot has seen recently.',\n risk: 'read',\n input: idInput.extend({ sinceStart: z.boolean().optional().describe('Only channels with messages since Mushin started') }),\n handler: ({ id, sinceStart }) => this.channels(id, { sinceStart }),\n })\n\n yield actions.define({\n name: 'bots.tryCommand',\n 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.',\n risk: 'read',\n input: z.object({\n name: z.string(),\n aliases: z.array(z.string()).optional(),\n prefixes: z.array(z.string()).optional().describe('The command\\'s own prefixes; empty uses the bot\\'s'),\n args: z.array(z.object({\n name: z.string(),\n type: z.enum(['text', 'number', 'boolean', 'user', 'choice']),\n optional: z.boolean().optional(),\n rest: z.boolean().optional(),\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\n choices: z.array(z.string()).optional(),\n })).default([]),\n text: z.string(),\n bot: z.string().optional().describe('Bot whose prefixes apply when the command has none of its own'),\n }),\n handler: (input) => this.tryCommand(input),\n })\n\n yield actions.define({\n name: 'bots.userChoices',\n description: 'People the bots have seen recently, as { value: user id, label, group: bot } choices.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.seen('user'),\n })\n\n yield actions.define({\n name: 'bots.groupChoices',\n description: 'Groups the bots have seen recently, as { value: group id, label, group: bot } choices.',\n risk: 'read',\n input: z.object({}),\n handler: () => this.seen('group'),\n })\n\n yield actions.define({\n name: 'bots.usage',\n 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.',\n risk: 'read',\n input: idInput.extend({ message: z.string().describe('Message record id from bots.messages') }),\n handler: ({ id, message }) => this.usage(id, message),\n })\n\n yield actions.define({\n name: 'bots.contacts',\n 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.',\n risk: 'read',\n input: idInput,\n handler: ({ id }) => this.contacts(id),\n })\n\n yield actions.define({\n name: 'bots.sandbox',\n 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.',\n risk: 'write',\n input: idInput.extend({ text: z.string().min(1) }),\n handler: ({ id, text }) => this.sandbox(id, text),\n })\n\n yield actions.define({\n name: 'bots.send',\n description: 'Send a text message from a bot to a group or private chat.',\n risk: 'write',\n input: idInput.extend({\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }),\n text: z.string().min(1),\n }),\n handler: ({ id, channel, text }) => this.sendManual(id, channel, text),\n })\n }\n}\n"],"mappings":";;;;;;;AAyCA,MAAM,YAAY,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,WAAW,OAAO,UAAU;CAC9E,MAAM,KAAK,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AC,SAAS,SAAS,CAAC;KAAG,IAAI,EAAE,OAAO;IAAE,CAAC;IACxE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;GACxB,CAAC;GACD,UAAU,EAAE,IAAI,SAAS,WAAW,KAAK,WAAW,IAAI,SAAS,IAAI;EACvE,CAAC;CACH;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mushinjs/plugin-bots",
|
|
3
|
-
"version": "0.4.0-next.
|
|
3
|
+
"version": "0.4.0-next.20261128121614",
|
|
4
4
|
"description": "Bot manager and per-bot runtimes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"mushin": {
|
|
29
29
|
"kind": "app",
|
|
30
30
|
"essential": true,
|
|
31
|
+
"category": "adapter",
|
|
31
32
|
"displayName": {
|
|
32
33
|
"en": "Bots",
|
|
33
34
|
"zh-CN": "机器人"
|
|
@@ -52,9 +53,9 @@
|
|
|
52
53
|
}
|
|
53
54
|
},
|
|
54
55
|
"dependencies": {
|
|
55
|
-
"@mushinjs/core": "0.4.0-next.
|
|
56
|
-
"@mushinjs/plugin-database": "0.4.0-next.
|
|
57
|
-
"@mushinjs/plugin-storage": "0.4.0-next.
|
|
56
|
+
"@mushinjs/core": "0.4.0-next.20261128121614",
|
|
57
|
+
"@mushinjs/plugin-database": "0.4.0-next.20261128121614",
|
|
58
|
+
"@mushinjs/plugin-storage": "0.4.0-next.20261128121614",
|
|
58
59
|
"minato": "4.0.1"
|
|
59
60
|
}
|
|
60
61
|
}
|