@mushinjs/plugin-bots 0.2.0-next.20261113105814 → 0.3.0-next.20261122141505

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/bot.d.ts CHANGED
@@ -160,6 +160,7 @@ export declare class Bot extends Service {
160
160
  receive(message: IncomingMessage, options?: {
161
161
  source?: Provenance;
162
162
  }): Promise<Session>;
163
+ private handle;
163
164
  /**
164
165
  * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the
165
166
  * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.
package/dist/bot.js CHANGED
@@ -372,6 +372,18 @@ var Bot = class extends Service {
372
372
  timestamp: message.timestamp ?? Date.now(),
373
373
  source: options.source ?? { kind: "user" }
374
374
  });
375
+ const outer = this.hooks.usageScope?.(this, record);
376
+ const scope = {
377
+ botId: this.id,
378
+ messageId: record.id,
379
+ report: (event) => {
380
+ outer?.report(event);
381
+ this.logUsage(event);
382
+ }
383
+ };
384
+ return usage.run(scope, () => this.handle(record, started));
385
+ }
386
+ async handle(record, started) {
375
387
  this.ctx.logger("message").info("received from %s%s: %s", who(record.user), record.channel.type === "group" ? ` in ${chat(record.channel)}` : "", preview(record.segments));
376
388
  const session = new Session(this, record);
377
389
  const entry = session.command?.entry;
@@ -413,16 +425,7 @@ var Bot = class extends Service {
413
425
  this.ctx.logger("bot").warn("middleware of %s failed: %s", entry.plugin, error);
414
426
  }
415
427
  };
416
- const outer = this.hooks.usageScope?.(this, record);
417
- const scope = {
418
- botId: this.id,
419
- messageId: record.id,
420
- report: (event) => {
421
- outer?.report(event);
422
- this.logUsage(event);
423
- }
424
- };
425
- await usage.run(scope, () => run(0));
428
+ await run(0);
426
429
  this.ctx.logger("bot").info("processed in %s%s", duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : "");
427
430
  return session;
428
431
  }
package/dist/bot.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\n type ChannelInfo, type Content, Context, type MessageRecord, type Provenance, type Segment, segmentsToText,\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\n} from '@mushinjs/core'\nimport {\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\n usageReply,\n} from './commands'\nimport {\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\n type MediaResolver, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\n} from './types'\n\nexport type Sendable = Content | SourcedContent\n\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\n\ninterface MiddlewareEntry {\n plugin: string\n callback: Middleware\n priority: number\n}\n\nexport interface MiddlewareOptions {\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\n priority?: number\n}\n\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\nexport interface BotHooks {\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\n status(bot: Bot): void\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\n commands?(bot: Bot): CommandEntry[]\n /** A message ran a registered command. */\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\n /** The answer to a built-in command such as `/help`. */\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\n roleOf?(bot: Bot, userId: string): BotRole | undefined\n /** A command that an app plugin answers on every bot, such as `/persona`. */\n appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined\n /** Where the costs of handling a message go; see `usage` in core. */\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\n}\n\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\n\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\nconst BUILTIN_PLUGIN = 'bots'\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\nexport const BUILTIN_PRIORITY = 5\n\nfunction isSourced(value: Sendable): value is SourcedContent {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\n}\n\n/** One incoming message, as seen by a bot plugin's middleware. */\nexport class Session {\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\n plugin?: string\n private parsed?: { value: ParsedCommand | undefined }\n\n constructor(public bot: Bot, public record: MessageRecord) {}\n\n get channel() {\n return this.record.channel\n }\n\n get user() {\n return this.record.user\n }\n\n get segments() {\n return this.record.segments\n }\n\n get isDirect() {\n return this.record.channel.type === 'private'\n }\n\n /** True when the message @-mentions this bot. */\n get mentioned() {\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\n }\n\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\n get command(): ParsedCommand | undefined {\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\n return this.parsed.value\n }\n\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\n role(): BotRole | undefined {\n return this.bot.roleOf(this.user.id)\n }\n\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\n groupRole(): Promise<GroupRole | undefined> {\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\n }\n\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\n get isAdmin() {\n return roleAtLeast(this.role(), 'admin')\n }\n\n /** Plain text with mentions of this bot removed. */\n get text() {\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\n return segmentsToText(segments).trim()\n }\n\n send(content: Sendable) {\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\n }\n\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\n reply(content: Sendable) {\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\n if (isSourced(content)) {\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\n }\n return this.send([...quote, ...toSegments(content)])\n }\n\n /** A view of this session attributed to another plugin. */\n as(plugin: string) {\n const view = Object.create(this) as Session\n view.plugin = plugin\n return view\n }\n}\n\n/**\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\n * always means that plugin's bot.\n */\nexport class Bot extends Service {\n status: BotStatus = 'offline'\n error?: string\n selfId?: string\n selfName?: string\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\n selfAvatar?: string\n record: BotRecord\n private hooks: BotHooks\n private transport?: Transport\n private middlewares: MiddlewareEntry[] = []\n private eventHandlers = new Set<(event: BotEvent) => void>()\n private ownCommands = new Set<{ def: CommandDef; plugin: string }>()\n private commandProviders = new Set<() => CommandEntry[]>()\n private roleResolver?: GroupRoleResolver\n private mediaResolver?: MediaResolver\n private contactResolver?: ContactResolver\n\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\n super(ctx, 'bot')\n this.record = config.record\n this.hooks = config.hooks\n }\n\n get id() {\n return this.record.id\n }\n\n get platform() {\n return this.record.adapter.type\n }\n\n setStatus(status: BotStatus, error?: string) {\n const nextError = status === 'error' ? error : undefined\n if (status !== this.status || nextError !== this.error) {\n const logger = this.ctx.logger('bot')\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\n else logger.info('status: %s', status)\n }\n this.status = status\n this.error = status === 'error' ? error : undefined\n this.hooks.status(this)\n }\n\n setSelf(id: string, name?: string, avatar?: string) {\n this.selfId = id\n this.selfName = name\n this.selfAvatar = avatar\n this.hooks.status(this)\n }\n\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\n useTransport(transport: Transport) {\n return this.ctx.effect(() => {\n this.transport = transport\n return () => {\n if (this.transport !== transport) return\n this.transport = undefined\n this.setStatus('offline')\n }\n }, 'bot.useTransport()')\n }\n\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\n useRoleResolver(resolver: GroupRoleResolver) {\n return this.ctx.effect(() => {\n this.roleResolver = resolver\n return () => {\n if (this.roleResolver === resolver) this.roleResolver = undefined\n }\n }, 'bot.useRoleResolver()')\n }\n\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\n useMediaResolver(resolver: MediaResolver) {\n return this.ctx.effect(() => {\n this.mediaResolver = resolver\n return () => {\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\n }\n }, 'bot.useMediaResolver()')\n }\n\n /** Called by adapters that can list the account's friends and groups. */\n useContacts(resolver: ContactResolver) {\n return this.ctx.effect(() => {\n this.contactResolver = resolver\n return () => {\n if (this.contactResolver === resolver) this.contactResolver = undefined\n }\n }, 'bot.useContacts()')\n }\n\n /** The account's friends and groups; empty when the adapter cannot list them. */\n async contacts() {\n return this.contactResolver ? this.contactResolver() : []\n }\n\n /**\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\n */\n sandbox(text: string) {\n const mention = /^@\\S*\\s*/.exec(text)\n const rest = mention ? text.slice(mention[0].length) : text\n const segments: Segment[] = [\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\n ]\n // Not awaited: a flow may wait for the next message, which comes through another call.\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\n })\n }\n\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\n }\n\n /** The messages of a forwarded chat history. */\n async forward(id: string) {\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\n return this.mediaResolver.forward(id)\n }\n\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\n roleOf(userId: string): BotRole | undefined {\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\n if (userId === SANDBOX_USER.id) return 'master'\n return this.hooks.roleOf?.(this, userId)\n }\n\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\n if (target.channel.type !== 'group' || !target.user.id) return\n if (target.user.role) return target.user.role\n try {\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\n } catch (error) {\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\n }\n }\n\n /** Whether a command's role requirement lets this session run it; logs why not. */\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\n const required = requiredRole(def)\n if (!required) return true\n const role = session.role()\n if (role === undefined) {\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\n return false\n }\n return roleAtLeast(role, required)\n }\n\n /** Registers middleware for incoming messages; runs in registration order. */\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\n const ctx = this.ctx\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, callback, priority: options.priority ?? 0 }\n return ctx.effect(() => {\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\n if (index < 0) this.middlewares.push(entry)\n else this.middlewares.splice(index, 0, entry)\n return () => {\n const index = this.middlewares.indexOf(entry)\n if (index >= 0) this.middlewares.splice(index, 1)\n }\n }, 'bot.middleware()')\n }\n\n get prefixes() {\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\n }\n\n /**\n * Splits text into a command, with the registered command it names. Commands with prefixes of\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\n */\n parseCommand(text: string): ParsedCommand | undefined {\n const entries = this.hooks.commands?.(this) ?? []\n for (const entry of entries) {\n if (!entry.prefixes?.length) continue\n const parsed = splitCommand(text, entry.prefixes)\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\n }\n const parsed = splitCommand(text, this.prefixes)\n if (!parsed) return\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\n return entry ? { ...parsed, entry } : parsed\n }\n\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\n localCommands(): CommandEntry[] {\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider())\n } catch (error) {\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\n }\n }\n return entries\n }\n\n /**\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\n */\n defineCommands(provider: () => CommandEntry[]) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bot.defineCommands()')\n }\n\n /**\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\n * replies with how to write the command.\n */\n command(def: CommandDef, handler: CommandHandler) {\n const ctx = this.ctx\n const entry = { def, plugin: ctx.fiber.name }\n ctx.effect(() => {\n this.ownCommands.add(entry)\n return () => this.ownCommands.delete(entry)\n }, `bot.command(${def.name})`)\n return this.middleware(async (session, next) => {\n const parsed = session.command\n if (!parsed || !commandMatches(def, parsed.name)) return next()\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\n if (!this.allows(def, session)) return\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\n if (!values.ok) {\n await session.reply(usageReply(def, parsed.prefix))\n return\n }\n await handler(session, values.values, parsed)\n })\n }\n\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\n middlewareOrder() {\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\n }\n\n /** Listens for adapter events that are not messages (notices, requests). */\n onEvent(handler: (event: BotEvent) => void) {\n return this.ctx.effect(() => {\n this.eventHandlers.add(handler)\n return () => this.eventHandlers.delete(handler)\n }, 'bot.onEvent()')\n }\n\n /** Called by adapters for non-message events. */\n dispatchEvent(event: BotEvent) {\n this.logEvent(event)\n for (const handler of this.eventHandlers) {\n try {\n handler(event)\n } catch (error) {\n this.ctx.logger('bot').warn(error)\n }\n }\n }\n\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\n const started = Date.now()\n const record = this.hooks.record({\n botId: this.id,\n messageId: message.messageId,\n direction: 'in',\n channel: message.channel,\n user: message.user,\n segments: message.segments,\n timestamp: message.timestamp ?? Date.now(),\n source: options.source ?? { kind: 'user' },\n })\n this.ctx.logger('message').info('received from %s%s: %s', who(record.user), record.channel.type === 'group' ? ` in ${chat(record.channel)}` : '', preview(record.segments))\n const session = new Session(this, record)\n const entry = session.command?.entry\n if (entry) {\n try {\n this.hooks.commandCalled?.(this, entry, session)\n } catch {}\n }\n const chain = [...this.middlewares]\n const appHandler = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\n if (entry?.source.kind === 'builtin' || appHandler) {\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\n const builtin: MiddlewareEntry = {\n plugin: appHandler ? entry!.source.id : BUILTIN_PLUGIN,\n priority: BUILTIN_PRIORITY,\n callback: async (view, next) => {\n if (!this.allows(entry!, view)) return next()\n if (appHandler) {\n await appHandler(view)\n return\n }\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\n if (answer !== undefined) await view.reply(answer)\n },\n }\n const index = chain.findIndex((item) => item.priority < builtin.priority)\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\n }\n /** The plugin that kept the message from the ones after it, if one did. */\n let stoppedAt: string | undefined\n const run = async (index: number): Promise<void> => {\n const entry = chain[index]\n if (!entry) return\n let passed = false\n try {\n await entry.callback(session.as(entry.plugin), () => {\n passed = true\n return run(index + 1)\n })\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\n } catch (error) {\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\n }\n }\n const outer = this.hooks.usageScope?.(this, record)\n const scope: UsageScope = {\n botId: this.id,\n messageId: record.id,\n report: (event) => {\n outer?.report(event)\n this.logUsage(event)\n },\n }\n await usage.run(scope, () => run(0))\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\n return session\n }\n\n /**\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\n */\n private logEvent(event: BotEvent) {\n const name = event.name ?? event.type\n const target = event.data?.target_id ?? undefined\n const parts = [\n event.user && `from ${who(event.user)}`,\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\n target !== undefined && target !== null && `to ${target}`,\n event.message?.text && `: ${preview(event.message.segments)}`,\n ].filter(Boolean).join(' ').replace(' :', ':')\n const quiet = !event.name || event.name === 'notify.input_status'\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\n }\n\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\n private logUsage(event: UsageEvent) {\n const logger = this.ctx.logger('llm')\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\n }\n\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\n }\n\n /** Raw adapter API, e.g. a NapCat extension action. */\n async call(action: string, params: Record<string, any> = {}) {\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\n return this.transport.call(action, params)\n }\n\n async deliver(\n channel: ChannelInfo,\n content: Sendable,\n options: { plugin?: string; source?: Provenance; replyTo?: string },\n ) {\n const sandbox = isSandbox(channel)\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\n let segments: Segment[]\n let source: Provenance | undefined = options.source\n if (isSourced(content)) {\n segments = content.segments ?? toSegments(content.text ?? '')\n source ??= content.source\n } else {\n segments = toSegments(content)\n }\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\n return\n }\n const started = Date.now()\n const logger = this.ctx.logger('message')\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\n let messageId: string | undefined\n try {\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\n } catch (error) {\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\n throw error\n }\n const ms = Date.now() - started\n const bytes = byteSize(segments)\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\n const record = this.hooks.record({\n botId: this.id,\n messageId,\n direction: 'out',\n channel,\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\n segments,\n timestamp: Date.now(),\n replyTo: options.replyTo,\n source,\n })\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause: usage.current()?.messageId })\n return record\n }\n}\n\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\nexport function byteSize(segments: Segment[]) {\n return Buffer.byteLength(JSON.stringify(segments))\n}\n\n/** A message on one line for the bot's log, cut to a readable length. */\nfunction preview(segments: Segment[]) {\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\n}\n\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\nfunction chat(channel: ChannelInfo) {\n if (isSandbox(channel)) return 'the sandbox'\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\n return channel.type === 'group' ? `group ${name}` : name\n}\n\nfunction who(user: UserInfo) {\n return user.name ? `${user.name} (${user.id})` : user.id\n}\n\nfunction duration(ms: number) {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\n}\n\nfunction size(bytes: number) {\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`\n}\n"],"mappings":";;;;;AAmDA,MAAM,iBAAiB;;AAEvB,MAAa,mBAAmB;AAEhC,SAAS,UAAU,OAA0C;CAC3D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,UAAU;AAC7F;;AAGA,IAAa,UAAb,MAAqB;CAKA;CAAiB;;CAHpC;CACA;CAEA,YAAY,KAAiB,QA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AAK,MAAO,GAAG,GAAG,MAAM,IAAI,KAAK,IAAA,CAAM,QAAQ,KAAK,MAAQ,IAAI,CAAC,EAAE;AAC5E;AAEA,SAAS,KAAK,OAAe;CAC3B,OAAO,QAAQ,OAAO,GAAG,MAAM,MAAM,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;AACpE"}
1
+ {"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\n type ChannelInfo, type Content, Context, type MessageRecord, type Provenance, type Segment, segmentsToText,\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\n} from '@mushinjs/core'\nimport {\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\n usageReply,\n} from './commands'\nimport {\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\n type MediaResolver, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\n} from './types'\n\nexport type Sendable = Content | SourcedContent\n\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\n\ninterface MiddlewareEntry {\n plugin: string\n callback: Middleware\n priority: number\n}\n\nexport interface MiddlewareOptions {\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\n priority?: number\n}\n\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\nexport interface BotHooks {\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\n status(bot: Bot): void\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\n commands?(bot: Bot): CommandEntry[]\n /** A message ran a registered command. */\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\n /** The answer to a built-in command such as `/help`. */\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\n roleOf?(bot: Bot, userId: string): BotRole | undefined\n /** A command that an app plugin answers on every bot, such as `/persona`. */\n appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined\n /** Where the costs of handling a message go; see `usage` in core. */\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\n}\n\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\n\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\nconst BUILTIN_PLUGIN = 'bots'\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\nexport const BUILTIN_PRIORITY = 5\n\nfunction isSourced(value: Sendable): value is SourcedContent {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\n}\n\n/** One incoming message, as seen by a bot plugin's middleware. */\nexport class Session {\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\n plugin?: string\n private parsed?: { value: ParsedCommand | undefined }\n\n constructor(public bot: Bot, public record: MessageRecord) {}\n\n get channel() {\n return this.record.channel\n }\n\n get user() {\n return this.record.user\n }\n\n get segments() {\n return this.record.segments\n }\n\n get isDirect() {\n return this.record.channel.type === 'private'\n }\n\n /** True when the message @-mentions this bot. */\n get mentioned() {\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\n }\n\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\n get command(): ParsedCommand | undefined {\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\n return this.parsed.value\n }\n\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\n role(): BotRole | undefined {\n return this.bot.roleOf(this.user.id)\n }\n\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\n groupRole(): Promise<GroupRole | undefined> {\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\n }\n\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\n get isAdmin() {\n return roleAtLeast(this.role(), 'admin')\n }\n\n /** Plain text with mentions of this bot removed. */\n get text() {\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\n return segmentsToText(segments).trim()\n }\n\n send(content: Sendable) {\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\n }\n\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\n reply(content: Sendable) {\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\n if (isSourced(content)) {\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\n }\n return this.send([...quote, ...toSegments(content)])\n }\n\n /** A view of this session attributed to another plugin. */\n as(plugin: string) {\n const view = Object.create(this) as Session\n view.plugin = plugin\n return view\n }\n}\n\n/**\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\n * always means that plugin's bot.\n */\nexport class Bot extends Service {\n status: BotStatus = 'offline'\n error?: string\n selfId?: string\n selfName?: string\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\n selfAvatar?: string\n record: BotRecord\n private hooks: BotHooks\n private transport?: Transport\n private middlewares: MiddlewareEntry[] = []\n private eventHandlers = new Set<(event: BotEvent) => void>()\n private ownCommands = new Set<{ def: CommandDef; plugin: string }>()\n private commandProviders = new Set<() => CommandEntry[]>()\n private roleResolver?: GroupRoleResolver\n private mediaResolver?: MediaResolver\n private contactResolver?: ContactResolver\n\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\n super(ctx, 'bot')\n this.record = config.record\n this.hooks = config.hooks\n }\n\n get id() {\n return this.record.id\n }\n\n get platform() {\n return this.record.adapter.type\n }\n\n setStatus(status: BotStatus, error?: string) {\n const nextError = status === 'error' ? error : undefined\n if (status !== this.status || nextError !== this.error) {\n const logger = this.ctx.logger('bot')\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\n else logger.info('status: %s', status)\n }\n this.status = status\n this.error = status === 'error' ? error : undefined\n this.hooks.status(this)\n }\n\n setSelf(id: string, name?: string, avatar?: string) {\n this.selfId = id\n this.selfName = name\n this.selfAvatar = avatar\n this.hooks.status(this)\n }\n\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\n useTransport(transport: Transport) {\n return this.ctx.effect(() => {\n this.transport = transport\n return () => {\n if (this.transport !== transport) return\n this.transport = undefined\n this.setStatus('offline')\n }\n }, 'bot.useTransport()')\n }\n\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\n useRoleResolver(resolver: GroupRoleResolver) {\n return this.ctx.effect(() => {\n this.roleResolver = resolver\n return () => {\n if (this.roleResolver === resolver) this.roleResolver = undefined\n }\n }, 'bot.useRoleResolver()')\n }\n\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\n useMediaResolver(resolver: MediaResolver) {\n return this.ctx.effect(() => {\n this.mediaResolver = resolver\n return () => {\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\n }\n }, 'bot.useMediaResolver()')\n }\n\n /** Called by adapters that can list the account's friends and groups. */\n useContacts(resolver: ContactResolver) {\n return this.ctx.effect(() => {\n this.contactResolver = resolver\n return () => {\n if (this.contactResolver === resolver) this.contactResolver = undefined\n }\n }, 'bot.useContacts()')\n }\n\n /** The account's friends and groups; empty when the adapter cannot list them. */\n async contacts() {\n return this.contactResolver ? this.contactResolver() : []\n }\n\n /**\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\n */\n sandbox(text: string) {\n const mention = /^@\\S*\\s*/.exec(text)\n const rest = mention ? text.slice(mention[0].length) : text\n const segments: Segment[] = [\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\n ]\n // Not awaited: a flow may wait for the next message, which comes through another call.\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\n })\n }\n\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\n }\n\n /** The messages of a forwarded chat history. */\n async forward(id: string) {\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\n return this.mediaResolver.forward(id)\n }\n\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\n roleOf(userId: string): BotRole | undefined {\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\n if (userId === SANDBOX_USER.id) return 'master'\n return this.hooks.roleOf?.(this, userId)\n }\n\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\n if (target.channel.type !== 'group' || !target.user.id) return\n if (target.user.role) return target.user.role\n try {\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\n } catch (error) {\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\n }\n }\n\n /** Whether a command's role requirement lets this session run it; logs why not. */\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\n const required = requiredRole(def)\n if (!required) return true\n const role = session.role()\n if (role === undefined) {\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\n return false\n }\n return roleAtLeast(role, required)\n }\n\n /** Registers middleware for incoming messages; runs in registration order. */\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\n const ctx = this.ctx\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, callback, priority: options.priority ?? 0 }\n return ctx.effect(() => {\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\n if (index < 0) this.middlewares.push(entry)\n else this.middlewares.splice(index, 0, entry)\n return () => {\n const index = this.middlewares.indexOf(entry)\n if (index >= 0) this.middlewares.splice(index, 1)\n }\n }, 'bot.middleware()')\n }\n\n get prefixes() {\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\n }\n\n /**\n * Splits text into a command, with the registered command it names. Commands with prefixes of\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\n */\n parseCommand(text: string): ParsedCommand | undefined {\n const entries = this.hooks.commands?.(this) ?? []\n for (const entry of entries) {\n if (!entry.prefixes?.length) continue\n const parsed = splitCommand(text, entry.prefixes)\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\n }\n const parsed = splitCommand(text, this.prefixes)\n if (!parsed) return\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\n return entry ? { ...parsed, entry } : parsed\n }\n\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\n localCommands(): CommandEntry[] {\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider())\n } catch (error) {\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\n }\n }\n return entries\n }\n\n /**\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\n */\n defineCommands(provider: () => CommandEntry[]) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bot.defineCommands()')\n }\n\n /**\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\n * replies with how to write the command.\n */\n command(def: CommandDef, handler: CommandHandler) {\n const ctx = this.ctx\n const entry = { def, plugin: ctx.fiber.name }\n ctx.effect(() => {\n this.ownCommands.add(entry)\n return () => this.ownCommands.delete(entry)\n }, `bot.command(${def.name})`)\n return this.middleware(async (session, next) => {\n const parsed = session.command\n if (!parsed || !commandMatches(def, parsed.name)) return next()\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\n if (!this.allows(def, session)) return\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\n if (!values.ok) {\n await session.reply(usageReply(def, parsed.prefix))\n return\n }\n await handler(session, values.values, parsed)\n })\n }\n\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\n middlewareOrder() {\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\n }\n\n /** Listens for adapter events that are not messages (notices, requests). */\n onEvent(handler: (event: BotEvent) => void) {\n return this.ctx.effect(() => {\n this.eventHandlers.add(handler)\n return () => this.eventHandlers.delete(handler)\n }, 'bot.onEvent()')\n }\n\n /** Called by adapters for non-message events. */\n dispatchEvent(event: BotEvent) {\n this.logEvent(event)\n for (const handler of this.eventHandlers) {\n try {\n handler(event)\n } catch (error) {\n this.ctx.logger('bot').warn(error)\n }\n }\n }\n\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\n const started = Date.now()\n const record = this.hooks.record({\n botId: this.id,\n messageId: message.messageId,\n direction: 'in',\n channel: message.channel,\n user: message.user,\n segments: message.segments,\n timestamp: message.timestamp ?? Date.now(),\n source: options.source ?? { kind: 'user' },\n })\n // Everything logged or spent while handling the message is tied to its record id.\n const outer = this.hooks.usageScope?.(this, record)\n const scope: UsageScope = {\n botId: this.id,\n messageId: record.id,\n report: (event) => {\n outer?.report(event)\n this.logUsage(event)\n },\n }\n return usage.run(scope, () => this.handle(record, started))\n }\n\n private async handle(record: MessageRecord, started: number) {\n this.ctx.logger('message').info('received from %s%s: %s', who(record.user), record.channel.type === 'group' ? ` in ${chat(record.channel)}` : '', preview(record.segments))\n const session = new Session(this, record)\n const entry = session.command?.entry\n if (entry) {\n try {\n this.hooks.commandCalled?.(this, entry, session)\n } catch {}\n }\n const chain = [...this.middlewares]\n const appHandler = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\n if (entry?.source.kind === 'builtin' || appHandler) {\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\n const builtin: MiddlewareEntry = {\n plugin: appHandler ? entry!.source.id : BUILTIN_PLUGIN,\n priority: BUILTIN_PRIORITY,\n callback: async (view, next) => {\n if (!this.allows(entry!, view)) return next()\n if (appHandler) {\n await appHandler(view)\n return\n }\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\n if (answer !== undefined) await view.reply(answer)\n },\n }\n const index = chain.findIndex((item) => item.priority < builtin.priority)\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\n }\n /** The plugin that kept the message from the ones after it, if one did. */\n let stoppedAt: string | undefined\n const run = async (index: number): Promise<void> => {\n const entry = chain[index]\n if (!entry) return\n let passed = false\n try {\n await entry.callback(session.as(entry.plugin), () => {\n passed = true\n return run(index + 1)\n })\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\n } catch (error) {\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\n }\n }\n await run(0)\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\n return session\n }\n\n /**\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\n */\n private logEvent(event: BotEvent) {\n const name = event.name ?? event.type\n const target = event.data?.target_id ?? undefined\n const parts = [\n event.user && `from ${who(event.user)}`,\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\n target !== undefined && target !== null && `to ${target}`,\n event.message?.text && `: ${preview(event.message.segments)}`,\n ].filter(Boolean).join(' ').replace(' :', ':')\n const quiet = !event.name || event.name === 'notify.input_status'\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\n }\n\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\n private logUsage(event: UsageEvent) {\n const logger = this.ctx.logger('llm')\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\n }\n\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\n }\n\n /** Raw adapter API, e.g. a NapCat extension action. */\n async call(action: string, params: Record<string, any> = {}) {\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\n return this.transport.call(action, params)\n }\n\n async deliver(\n channel: ChannelInfo,\n content: Sendable,\n options: { plugin?: string; source?: Provenance; replyTo?: string },\n ) {\n const sandbox = isSandbox(channel)\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\n let segments: Segment[]\n let source: Provenance | undefined = options.source\n if (isSourced(content)) {\n segments = content.segments ?? toSegments(content.text ?? '')\n source ??= content.source\n } else {\n segments = toSegments(content)\n }\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\n return\n }\n const started = Date.now()\n const logger = this.ctx.logger('message')\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\n let messageId: string | undefined\n try {\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\n } catch (error) {\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\n throw error\n }\n const ms = Date.now() - started\n const bytes = byteSize(segments)\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\n const record = this.hooks.record({\n botId: this.id,\n messageId,\n direction: 'out',\n channel,\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\n segments,\n timestamp: Date.now(),\n replyTo: options.replyTo,\n source,\n })\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause: usage.current()?.messageId })\n return record\n }\n}\n\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\nexport function byteSize(segments: Segment[]) {\n return Buffer.byteLength(JSON.stringify(segments))\n}\n\n/** A message on one line for the bot's log, cut to a readable length. */\nfunction preview(segments: Segment[]) {\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\n}\n\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\nfunction chat(channel: ChannelInfo) {\n if (isSandbox(channel)) return 'the sandbox'\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\n return channel.type === 'group' ? `group ${name}` : name\n}\n\nfunction who(user: UserInfo) {\n return user.name ? `${user.name} (${user.id})` : user.id\n}\n\nfunction duration(ms: number) {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\n}\n\nfunction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,MAAM,GAAG,KAAK,MAAM,GAAG,GAAG,EAAE,KAAK,QAAQ;AAChE;;AAGA,SAAS,KAAK,SAAsB;CAClC,IAAI,UAAU,OAAO,GAAG,OAAO;CAC/B,MAAM,OAAO,QAAQ,OAAO,GAAG,QAAQ,KAAK,IAAI,QAAQ,GAAG,KAAK,QAAQ;CACxE,OAAO,QAAQ,SAAS,UAAU,SAAS,SAAS;AACtD;AAEA,SAAS,IAAI,MAAgB;CAC3B,OAAO,KAAK,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,GAAG,KAAK,KAAK;AACxD;AAEA,SAAS,SAAS,IAAY;CAC5B,OAAO,KAAK,MAAO,GAAG,GAAG,MAAM,IAAI,KAAK,IAAA,CAAM,QAAQ,KAAK,MAAQ,IAAI,CAAC,EAAE;AAC5E;AAEA,SAAS,KAAK,OAAe;CAC3B,OAAO,QAAQ,OAAO,GAAG,MAAM,MAAM,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;AACpE"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, MessageUsage, RunCommandInput } from "./manager.js";
1
+ import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, LogFilter, MessageUsage, RunCommandInput } from "./manager.js";
2
2
  import { MessageArchive, MessageQuery, MessageRow, fromRow, toRow } from "./archive.js";
3
3
  import { BUILTIN_PRIORITY, Bot, BotHooks, CommandHandler, Middleware, MiddlewareOptions, 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 { AdapterType, BotConnectionInfo, BotEvent, BotPluginEntry, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PermissionProvider, ROLE_RANK, ResolvedMedia, SANDBOX_CHANNEL, SANDBOX_USER, SourcedContent, Transport, isSandbox, roleAtLeast } from "./types.js";
6
- export { AdapterType, 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, MediaResolver, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, 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, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
6
+ export { AdapterType, 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, MediaResolver, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, 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, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
package/dist/manager.d.ts CHANGED
@@ -24,6 +24,21 @@ export interface BotLogLine {
24
24
  name: string;
25
25
  tag: LogTag;
26
26
  text: string;
27
+ /** Record id of the message being handled when the line was written. */
28
+ message?: string;
29
+ }
30
+ /** What `bots.logs` can narrow the lines to. */
31
+ export interface LogFilter {
32
+ limit?: number;
33
+ /** Only lines written while handling this message (its record id). */
34
+ message?: string;
35
+ /** Times in ms since the epoch. */
36
+ since?: number;
37
+ until?: number;
38
+ /** Case-insensitive text the line contains. */
39
+ query?: string;
40
+ /** This level and above. */
41
+ level?: 'debug' | 'info' | 'warn' | 'error';
27
42
  }
28
43
  /** A message ran a registered command. */
29
44
  export interface CommandCall {
@@ -304,6 +319,8 @@ export declare class BotManager extends Service {
304
319
  optional: import("@mushinjs/core").DependencyState[];
305
320
  };
306
321
  } | undefined>;
322
+ /** Puts the plain values of a bot plugin's secret fields into .env and returns the config with `${NAME}` references. */
323
+ private securePlugin;
307
324
  private reloadPlugin;
308
325
  /** Adds commands to every bot's list. Removed when the calling plugin unloads. */
309
326
  defineCommands(provider: CommandProvider): import("cordis").Disposable<Promise<void>>;
@@ -356,7 +373,7 @@ export declare class BotManager extends Service {
356
373
  /** True when a log line was written inside a bot; it belongs in that bot's log, not the global one. */
357
374
  isBotLog(message: Message): boolean;
358
375
  private captureLog;
359
- logLines(id: string, limit?: number): Promise<BotLogLine[]>;
376
+ logLines(id: string, filter?: LogFilter): Promise<BotLogLine[]>;
360
377
  /** Messages recorded since Mushin started, for the live conversation. */
361
378
  private recent;
362
379
  /** What handling each recent message cost, in memory only; see `bots.usage`. */
package/dist/manager.js CHANGED
@@ -2,8 +2,27 @@ import { MessageArchive } from "./archive.js";
2
2
  import { Bot, byteSize } from "./bot.js";
3
3
  import { DEFAULT_PREFIXES, commandConflicts, commandMatches, commandUsage, helpText, parseArgs, requiredRole, splitCommand } from "./commands.js";
4
4
  import { isSandbox, roleAtLeast } from "./types.js";
5
- import { Logger, MushinError, Service, currentPackageName, dependencyReport, describeMissing, envReference, fiberError, fiberStatus, isMasked, logTag, mask, messageType, pluginSchema, randomId, resolveEnvReferences, segmentsToText, toJsonSchema, validatePluginConfig, z } from "@mushinjs/core";
5
+ import { Logger, MushinError, Service, currentPackageName, dependencyReport, describeMissing, envReference, fiberError, fiberStatus, isMasked, logTag, mask, maskSecrets, messageType, pluginSchema, randomId, resolveEnvReferences, restoreMasked, secretFields, segmentsToText, toJsonSchema, usage, validatePluginConfig, z } from "@mushinjs/core";
6
6
  // src/manager.ts
7
+ /** A time as an ISO date-time or ms since the epoch, as ms. */
8
+ const timeInput = z.union([z.number(), z.string()]).transform((value, check) => {
9
+ const ms = typeof value === "number" ? value : Date.parse(value);
10
+ if (Number.isNaN(ms)) {
11
+ check.addIssue({
12
+ code: "custom",
13
+ message: `"${value}" is not a time`
14
+ });
15
+ return z.NEVER;
16
+ }
17
+ return ms;
18
+ });
19
+ const LEVELS = [
20
+ "debug",
21
+ "info",
22
+ "warn",
23
+ "error"
24
+ ];
25
+ const DAY = 864e5;
7
26
  const STORAGE_KEY = "bots";
8
27
  const BUFFER_SIZE = 500;
9
28
  const LOG_BUFFER_SIZE = 500;
@@ -259,7 +278,7 @@ var BotManager = class extends Service {
259
278
  record.plugins.push({
260
279
  package: item.package,
261
280
  enabled: true,
262
- config: item.config ?? {}
281
+ config: await this.securePlugin(record, item.package, plugin, item.config ?? {})
263
282
  });
264
283
  }
265
284
  this.records.push(record);
@@ -325,9 +344,15 @@ var BotManager = class extends Service {
325
344
  for (const entry of record.plugins) {
326
345
  if (!entry.enabled) continue;
327
346
  try {
347
+ const plugin = await this.loadBotPlugin(entry.package);
348
+ const secured = await this.securePlugin(record, entry.package, plugin, entry.config ?? {}, entry.config);
349
+ if (JSON.stringify(secured) !== JSON.stringify(entry.config ?? {})) {
350
+ entry.config = secured;
351
+ await this.save();
352
+ }
328
353
  loaded.push({
329
354
  entry,
330
- plugin: await this.loadBotPlugin(entry.package)
355
+ plugin
331
356
  });
332
357
  } catch (error) {
333
358
  runtime.pluginErrors.set(entry.package, error instanceof Error ? error.message : String(error));
@@ -447,8 +472,11 @@ var BotManager = class extends Service {
447
472
  return Promise.all(catalog.map(async (entry) => {
448
473
  const configured = record.plugins.find((item) => item.package === entry.package);
449
474
  let configSchema;
475
+ let secrets = [];
450
476
  try {
451
- configSchema = pluginSchema(await this.home.manager.loadPlugin(entry.package));
477
+ const plugin = await this.home.manager.loadPlugin(entry.package);
478
+ configSchema = pluginSchema(plugin);
479
+ secrets = secretFields(plugin);
452
480
  } catch {}
453
481
  const fiber = runtime?.plugins.get(entry.package);
454
482
  const report = dependencyReport(graph, entry.package);
@@ -460,7 +488,7 @@ var BotManager = class extends Service {
460
488
  version: entry.version,
461
489
  manifest: entry.manifest,
462
490
  enabled: !!configured?.enabled,
463
- config: configured?.config ?? {},
491
+ config: maskSecrets(configured?.config ?? {}, secrets),
464
492
  configSchema,
465
493
  status,
466
494
  error: runtime?.pluginErrors.get(entry.package) ?? (status === "missing" ? describeMissing(missing) : fiberError(fiber)),
@@ -487,8 +515,9 @@ var BotManager = class extends Service {
487
515
  const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires);
488
516
  if (missing.length) throw new MushinError("unavailable", `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing });
489
517
  let entry = record.plugins.find((item) => item.package === name);
490
- const nextConfig = config ?? entry?.config ?? {};
518
+ let nextConfig = restoreMasked(config ?? entry?.config ?? {}, entry?.config, secretFields(plugin));
491
519
  validatePluginConfig(plugin, nextConfig);
520
+ nextConfig = await this.securePlugin(record, name, plugin, nextConfig, entry?.config);
492
521
  if (!entry) {
493
522
  entry = {
494
523
  package: name,
@@ -522,13 +551,29 @@ var BotManager = class extends Service {
522
551
  const entry = record.plugins.find((item) => item.package === name);
523
552
  if (!entry) return this.enablePlugin(id, name, config);
524
553
  const plugin = await this.loadBotPlugin(name);
525
- validatePluginConfig(plugin, config);
526
- entry.config = config;
554
+ const next = restoreMasked(config, entry.config, secretFields(plugin));
555
+ validatePluginConfig(plugin, next);
556
+ entry.config = await this.securePlugin(record, name, plugin, next, entry.config);
527
557
  await this.save();
528
558
  this.logger.info("config of plugin %s on bot %s changed", name, this.label(record));
529
559
  if (entry.enabled) this.reloadPlugin(id, entry, plugin);
530
560
  return this.plugins(id).then((list) => list.find((item) => item.package === name));
531
561
  }
562
+ /** Puts the plain values of a bot plugin's secret fields into .env and returns the config with `${NAME}` references. */
563
+ async securePlugin(record, name, plugin, config, previous) {
564
+ const keys = secretFields(plugin);
565
+ if (!keys.length) return config;
566
+ const short = name.replace(/^@[^/]+\//, "").replace(/^(?:mushin-)?(?:bot-)?plugin-/, "");
567
+ return (await this.home.storage.secrets.moveIn(config, {
568
+ keys,
569
+ name: [
570
+ "bot",
571
+ record.name || record.id,
572
+ short
573
+ ],
574
+ previous
575
+ })).config;
576
+ }
532
577
  reloadPlugin(id, entry, plugin) {
533
578
  const runtime = this.runtimes.get(id);
534
579
  if (!runtime?.ctx) return;
@@ -713,6 +758,8 @@ var BotManager = class extends Service {
713
758
  tag: logTag(message.name),
714
759
  text: Logger.format(plainExporter, message)
715
760
  };
761
+ const handling = usage.current();
762
+ if (handling?.botId === botId) line.message = handling.messageId;
716
763
  let buffer = this.logs.get(botId);
717
764
  if (!buffer) this.logs.set(botId, buffer = []);
718
765
  buffer.push(line);
@@ -721,18 +768,33 @@ var BotManager = class extends Service {
721
768
  const day = new Date(line.ts).toISOString().slice(0, 10);
722
769
  this.home.storage.append(`logs/${botId}/${day}`, line).catch(() => {});
723
770
  }
724
- async logLines(id, limit = 200) {
771
+ async logLines(id, filter = {}) {
725
772
  this.get(id);
726
- let buffer = this.logs.get(id);
727
- if (!buffer) {
728
- const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
729
- buffer = (await this.home.storage.tail(`logs/${id}/${day}`, LOG_BUFFER_SIZE)).map((line) => line.tag ? line : {
730
- ...line,
731
- tag: logTag(line.name)
732
- });
733
- this.logs.set(id, buffer);
773
+ const limit = filter.limit ?? 200;
774
+ let lines;
775
+ if (filter.since !== void 0 || filter.until !== void 0 || filter.message) {
776
+ const until = filter.until ?? Date.now();
777
+ const since = filter.since ?? (filter.message ? until - 2 * DAY : until);
778
+ const days = [];
779
+ const first = Date.parse(new Date(Math.max(since, until - 31 * DAY)).toISOString().slice(0, 10));
780
+ for (let at = first; at <= until; at += DAY) days.push(new Date(at).toISOString().slice(0, 10));
781
+ lines = (await Promise.all(days.map((day) => this.home.storage.tail(`logs/${id}/${day}`, 1e5)))).flat();
782
+ lines = lines.filter((line) => line.ts >= (filter.since ?? 0) && line.ts <= until);
783
+ } else {
784
+ let buffer = this.logs.get(id);
785
+ if (!buffer) {
786
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
787
+ buffer = await this.home.storage.tail(`logs/${id}/${day}`, LOG_BUFFER_SIZE);
788
+ this.logs.set(id, buffer);
789
+ }
790
+ lines = buffer;
734
791
  }
735
- return buffer.slice(-limit);
792
+ const query = filter.query?.toLowerCase();
793
+ const level = filter.level ? LEVELS.indexOf(filter.level) : -1;
794
+ return lines.map((line) => line.tag ? line : {
795
+ ...line,
796
+ tag: logTag(line.name)
797
+ }).filter((line) => (!filter.message || line.message === filter.message) && (!query || line.text.toLowerCase().includes(query)) && (level < 0 || LEVELS.indexOf(line.type) >= level)).slice(-limit);
736
798
  }
737
799
  /** Messages recorded since Mushin started, for the live conversation. */
738
800
  recent = /* @__PURE__ */ new WeakSet();
@@ -1076,10 +1138,22 @@ var BotManager = class extends Service {
1076
1138
  });
1077
1139
  yield actions.define({
1078
1140
  name: "bots.logs",
1079
- description: "Recent log lines of one bot, oldest first: connection events, adapter errors, plugin warnings, and why LLM chat skipped messages. Read this first when a bot misbehaves.",
1141
+ 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.",
1080
1142
  risk: "read",
1081
- input: idInput.extend({ limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional() }),
1082
- handler: ({ id, limit }) => this.logLines(id, limit)
1143
+ input: idInput.extend({
1144
+ limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional(),
1145
+ message: z.string().optional().describe("Only lines written while handling this message: its record id, from bots.messages"),
1146
+ since: timeInput.optional().describe("From this time: an ISO date-time or ms since the epoch"),
1147
+ until: timeInput.optional().describe("Up to this time: an ISO date-time or ms since the epoch"),
1148
+ query: z.string().optional().describe("Only lines containing this text, ignoring case"),
1149
+ level: z.enum([
1150
+ "debug",
1151
+ "info",
1152
+ "warn",
1153
+ "error"
1154
+ ]).optional().describe("Only lines at this level or above")
1155
+ }),
1156
+ handler: ({ id, ...filter }) => this.logLines(id, filter)
1083
1157
  });
1084
1158
  yield actions.define({
1085
1159
  name: "bots.channels",
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import {\n type ChannelInfo, Context, currentPackageName, 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 Provenance, pluginSchema, randomId, resolveEnvReferences, type Segment, segmentsToText, Service, toJsonSchema,\n type UsageEvent, validatePluginConfig, z,\n} from '@mushinjs/core'\nimport type {} from '@mushinjs/plugin-storage'\nimport { MessageArchive } from './archive'\nimport { Bot, type BotHooks, byteSize, 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, 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 }\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}\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/** A command an app plugin answers on every bot, or on the bots `bots` picks. */\ninterface AppCommand {\n def: CommandDef\n plugin: string\n handler: (session: Session) => Promise<unknown> | unknown\n bots?: (botId: string) => boolean\n}\n\nexport interface BotStatusInfo {\n id: string\n status: BotStatus\n error?: string\n selfId?: string\n selfName?: string\n selfAvatar?: 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\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('Bot plugin package name from bots.plugins.list') })\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 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[] }>(STORAGE_KEY)\n this.records = stored?.bots ?? []\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 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.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.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 adapters() {\n return [...this.adapterStore.values()].map((adapter) => ({\n id: adapter.id,\n displayName: adapter.displayName,\n configSchema: toJsonSchema(adapter.config),\n secrets: adapter.secrets ?? [],\n segments: adapter.segments,\n groupRoles: !!adapter.groupRoles,\n avatars: adapter.avatars ?? {},\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 }\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 })\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 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.validateAdapter(input.adapter.type, input.adapter.config))).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: 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 // Command settings are read on every message, so changing only them needs no restart.\n const restart = patch.name !== undefined || 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.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) continue\n try {\n loaded.push({ entry, plugin: await this.loadBotPlugin(entry.package) })\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)?.handler,\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 async plugins(id: string) {\n const record = this.get(id)\n const runtime = this.runtimes.get(id)\n const graph = await this.home.manager.graph()\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 try {\n configSchema = pluginSchema(await this.home.manager.loadPlugin(entry.package))\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 let status: string = configured?.enabled ? (runtime ? fiberStatus(fiber) : 'disabled') : 'disabled'\n if (status === 'pending' && missing.length) status = 'missing'\n return {\n package: entry.package,\n version: entry.version,\n manifest: entry.manifest,\n enabled: !!configured?.enabled,\n config: configured?.config ?? {},\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 async enablePlugin(id: string, name: string, config?: Record<string, any>) {\n const record = this.get(id)\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 const nextConfig = config ?? entry?.config ?? {}\n validatePluginConfig(plugin, nextConfig)\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.plugins(id).then((list) => list.find((item) => item.package === name))\n }\n\n async disablePlugin(id: string, name: string) {\n const record = this.get(id)\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.plugins(id).then((list) => list.find((item) => item.package === name))\n }\n\n async configurePlugin(id: string, name: string, config: Record<string, any>) {\n const record = this.get(id)\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 validatePluginConfig(plugin, config)\n entry.config = 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.plugins(id).then((list) => list.find((item) => item.package === name))\n }\n\n private reloadPlugin(id: string, entry: BotPluginEntry, plugin: Plugin) {\n const runtime = this.runtimes.get(id)\n if (!runtime?.ctx) 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 // ---- 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 on every bot (or those `bots` picks) from an app plugin, such as `/persona`.\n * It answers after flows, like `/help`, and shows in each bot's command list.\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, 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) && (item.bots?.(botId) ?? true))\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 (command.bots && !command.bots(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 // ---- 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 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, limit = 200) {\n this.get(id)\n let buffer = this.logs.get(id)\n if (!buffer) {\n const day = new Date().toISOString().slice(0, 10)\n // Lines stored before tags existed get one from their logger name.\n buffer = (await this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, LOG_BUFFER_SIZE))\n .map((line) => (line.tag ? line : { ...line, tag: logTag(line.name) }))\n this.logs.set(id, buffer)\n }\n return buffer.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. For NapCat use adapter type \"onebot\" with mode \"forward\" (url of NapCat\\'s WebSocket server, e.g. ws://127.0.0.1:3001) or mode \"reverse\" (NapCat connects to Mushin). Returns the bot with its id.',\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, unless only command settings change.',\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 === 'agent' && caller.session ? { kind: 'agent', 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 every installed bot plugin with whether it is enabled on this bot, its config and status.',\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: 'Enable a bot plugin on one bot, optionally with config.',\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: 'Disable a bot plugin on one bot. Its 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.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: 'Recent log lines of one bot, oldest first: connection events, adapter errors, plugin warnings, and why LLM chat skipped messages. Read this first when a bot misbehaves.',\n risk: 'read',\n input: idInput.extend({ limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional() }),\n handler: ({ id, limit }) => this.logLines(id, limit),\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":";;;;;;AAqFA,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,MAAM,kBAAkB;AACxB,MAAM,gBAA0B;CAAE,QAAQ;CAAO,SAAS,CAAC;AAAE;AAE7D,MAAM,eAAe,EAAE,OAAO;CAC5B,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,qDAAmD;CAC7E,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS,uDAAuD;AACxG,CAAC;;AAGD,MAAM,iBAAiB;;AAEvB,MAAM,2BAA2B;AAejC,MAAM,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,SAAS,uBAAuB,EAAE,CAAC;AAC7E,MAAM,uBAAuB,EAAE,OAAO;CACpC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,mCAAiC;CAC1F,MAAM,EAAE,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,yDAAyD;CAC/F,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,8BAA8B;CACxE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAA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O,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, 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 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 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, 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 }\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/** A command an app plugin answers on every bot, or on the bots `bots` picks. */\ninterface AppCommand {\n def: CommandDef\n plugin: string\n handler: (session: Session) => Promise<unknown> | unknown\n bots?: (botId: string) => boolean\n}\n\nexport interface BotStatusInfo {\n id: string\n status: BotStatus\n error?: string\n selfId?: string\n selfName?: string\n selfAvatar?: 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\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('Bot plugin package name from bots.plugins.list') })\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 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[] }>(STORAGE_KEY)\n this.records = stored?.bots ?? []\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 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.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.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 adapters() {\n return [...this.adapterStore.values()].map((adapter) => ({\n id: adapter.id,\n displayName: adapter.displayName,\n configSchema: toJsonSchema(adapter.config),\n secrets: adapter.secrets ?? [],\n segments: adapter.segments,\n groupRoles: !!adapter.groupRoles,\n avatars: adapter.avatars ?? {},\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 }\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 })\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 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.validateAdapter(input.adapter.type, input.adapter.config))).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 // Command settings are read on every message, so changing only them needs no restart.\n const restart = patch.name !== undefined || 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.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) 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)?.handler,\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 async plugins(id: string) {\n const record = this.get(id)\n const runtime = this.runtimes.get(id)\n const graph = await this.home.manager.graph()\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 let status: string = configured?.enabled ? (runtime ? fiberStatus(fiber) : 'disabled') : 'disabled'\n if (status === 'pending' && missing.length) status = 'missing'\n return {\n package: entry.package,\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 async enablePlugin(id: string, name: string, config?: Record<string, any>) {\n const record = this.get(id)\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.plugins(id).then((list) => list.find((item) => item.package === name))\n }\n\n async disablePlugin(id: string, name: string) {\n const record = this.get(id)\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.plugins(id).then((list) => list.find((item) => item.package === name))\n }\n\n async configurePlugin(id: string, name: string, config: Record<string, any>) {\n const record = this.get(id)\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.plugins(id).then((list) => list.find((item) => item.package === 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) 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 // ---- 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 on every bot (or those `bots` picks) from an app plugin, such as `/persona`.\n * It answers after flows, like `/help`, and shows in each bot's command list.\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, 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) && (item.bots?.(botId) ?? true))\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 (command.bots && !command.bots(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 // ---- 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. For NapCat use adapter type \"onebot\" with mode \"forward\" (url of NapCat\\'s WebSocket server, e.g. ws://127.0.0.1:3001) or mode \"reverse\" (NapCat connects to Mushin). Returns the bot with its id.',\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, unless only command settings change.',\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 === 'agent' && caller.session ? { kind: 'agent', 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 every installed bot plugin with whether it is enabled on this bot, its config and status.',\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: 'Enable a bot plugin on one bot, optionally with config.',\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: 'Disable a bot plugin on one bot. Its 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.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":";;;;;;;AAwCA,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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ACN,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"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mushinjs/plugin-bots",
3
- "version": "0.2.0-next.20261113105814",
3
+ "version": "0.3.0-next.20261122141505",
4
4
  "description": "Bot manager and per-bot runtimes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,9 +52,9 @@
52
52
  }
53
53
  },
54
54
  "dependencies": {
55
- "@mushinjs/core": "0.2.0-next.20261113105814",
56
- "@mushinjs/plugin-database": "0.2.0-next.20261113105814",
57
- "@mushinjs/plugin-storage": "0.2.0-next.20261113105814",
55
+ "@mushinjs/core": "0.3.0-next.20261122141505",
56
+ "@mushinjs/plugin-database": "0.3.0-next.20261122141505",
57
+ "@mushinjs/plugin-storage": "0.3.0-next.20261122141505",
58
58
  "minato": "4.0.1"
59
59
  }
60
60
  }