@mushinjs/plugin-bots 0.2.0-next.20261112165327 → 0.2.0-next.20261113105814
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/LICENSE +20 -20
- package/dist/archive.js +2 -5
- package/dist/archive.js.map +1 -1
- package/dist/bot.js.map +1 -1
- package/dist/commands.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/manager.d.ts +4 -0
- package/dist/manager.js +37 -7
- package/dist/manager.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +4 -4
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2026 Setobox
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Setobox
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
package/dist/archive.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { messageType, segmentsToText } from "@mushinjs/core";
|
|
2
|
-
import { readdir } from "node:fs/promises";
|
|
3
|
-
import { join } from "node:path";
|
|
4
2
|
import { $ } from "minato";
|
|
5
3
|
// src/archive.ts
|
|
6
4
|
function toRow(record) {
|
|
@@ -126,12 +124,11 @@ var MessageArchive = class {
|
|
|
126
124
|
* plugin was off. The files stay where they are.
|
|
127
125
|
*/
|
|
128
126
|
async importLogs() {
|
|
129
|
-
const root = join(this.ctx.storage.dir, "messages");
|
|
130
127
|
let imported = 0;
|
|
131
|
-
for (const bot of await
|
|
128
|
+
for (const bot of await this.ctx.storage.children("messages")) {
|
|
132
129
|
const newest = Number(await this.ctx.database.select("bots_message", { bot }).execute((row) => $.max(row.timestamp))) || 0;
|
|
133
130
|
const since = newest ? new Date(newest).toISOString().slice(0, 10) : "";
|
|
134
|
-
const days = (await
|
|
131
|
+
const days = (await this.ctx.storage.children(`messages/${bot}`)).filter((name) => name.endsWith(".jsonl") && name.slice(0, -6) >= since).sort();
|
|
135
132
|
for (const day of days) {
|
|
136
133
|
const records = (await this.ctx.storage.tail(`messages/${bot}/${day.slice(0, -6)}`, Infinity)).filter((record) => record?.id && record.timestamp > newest);
|
|
137
134
|
for (let i = 0; i < records.length; i += IMPORT_BATCH) await this.ctx.database.upsert("bots_message", records.slice(i, i + IMPORT_BATCH).map((record) => toRow({
|
package/dist/archive.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"archive.js","names":[],"sources":["../src/archive.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises'\r\nimport { join } from 'node:path'\r\nimport { type Context, type MessageRecord, messageType, segmentsToText } from '@mushinjs/core'\r\nimport type {} from '@mushinjs/plugin-database'\r\nimport type {} from '@mushinjs/plugin-storage'\r\nimport { $ } from 'minato'\r\n\r\ndeclare module 'minato' {\r\n interface Tables {\r\n bots_message: MessageRow\r\n }\r\n}\r\n\r\n/** A message record as a row: the channel and user flattened so they can be filtered and indexed. */\r\nexport interface MessageRow {\r\n id: string\r\n bot: string\r\n messageId: string\r\n direction: string\r\n channelType: string\r\n channelId: string\r\n channelName: string\r\n fromGroup: string\r\n userId: string\r\n userName: string\r\n userRole: string\r\n /** Plain text, for searching. */\r\n text: string\r\n segments: any\r\n type: string\r\n platforms: any\r\n source: any\r\n replyTo: string\r\n timestamp: number\r\n}\r\n\r\nexport function toRow(record: MessageRecord): MessageRow {\r\n return {\r\n id: record.id,\r\n bot: record.botId,\r\n messageId: record.messageId ?? '',\r\n direction: record.direction,\r\n channelType: record.channel.type,\r\n channelId: record.channel.id,\r\n channelName: record.channel.name ?? '',\r\n fromGroup: record.channel.fromGroup ?? '',\r\n userId: record.user.id,\r\n userName: record.user.name ?? '',\r\n userRole: record.user.role ?? '',\r\n text: segmentsToText(record.segments ?? []),\r\n segments: record.segments ?? [],\r\n type: record.type ?? messageType(record.segments ?? []),\r\n platforms: record.platforms ?? [],\r\n source: record.source ?? { kind: 'user' },\r\n replyTo: record.replyTo ?? '',\r\n timestamp: record.timestamp,\r\n }\r\n}\r\n\r\nexport function fromRow(row: MessageRow): MessageRecord {\r\n return {\r\n id: row.id,\r\n botId: row.bot,\r\n ...(row.messageId ? { messageId: row.messageId } : {}),\r\n direction: row.direction as MessageRecord['direction'],\r\n channel: {\r\n type: row.channelType as 'group' | 'private',\r\n id: row.channelId,\r\n ...(row.channelName ? { name: row.channelName } : {}),\r\n ...(row.fromGroup ? { fromGroup: row.fromGroup } : {}),\r\n },\r\n user: {\r\n id: row.userId,\r\n ...(row.userName ? { name: row.userName } : {}),\r\n ...(row.userRole ? { role: row.userRole as 'owner' | 'admin' | 'member' } : {}),\r\n },\r\n segments: row.segments ?? [],\r\n timestamp: row.timestamp,\r\n ...(row.replyTo ? { replyTo: row.replyTo } : {}),\r\n type: row.type as MessageRecord['type'],\r\n platforms: row.platforms ?? [],\r\n source: row.source ?? { kind: 'user' },\r\n }\r\n}\r\n\r\nconst IMPORT_BATCH = 500\r\n\r\nexport interface MessageQuery {\r\n limit: number\r\n channel?: string\r\n /** Only messages sent before this time (ms). */\r\n before?: number\r\n}\r\n\r\n/**\r\n * Message records in the `bots_message` table, next to the daily JSONL files that are always\r\n * written. Created when the database plugin runs; imports the JSONL lines it does not have yet.\r\n */\r\nexport class MessageArchive {\r\n /** False until the JSONL import is done; until then the JSONL files answer queries. */\r\n ready = false\r\n private pending = new Set<Promise<unknown>>()\r\n /** Records that arrived during the import, saved right after it. */\r\n private queued: MessageRecord[] = []\r\n\r\n constructor(private ctx: Context, private onError: (error: unknown) => void) {\r\n ctx.model.extend('bots_message', {\r\n id: 'string',\r\n bot: 'string',\r\n messageId: 'string',\r\n direction: 'string',\r\n channelType: 'string',\r\n channelId: 'string',\r\n channelName: 'string',\r\n fromGroup: 'string',\r\n userId: 'string',\r\n userName: 'string',\r\n userRole: 'string',\r\n text: 'text',\r\n segments: 'json',\r\n type: 'string',\r\n platforms: 'json',\r\n source: 'json',\r\n replyTo: 'string',\r\n timestamp: 'double',\r\n }, { primary: 'id', indexes: [['bot', 'timestamp'], ['bot', 'channelId', 'timestamp']] })\r\n }\r\n\r\n /** Imports the JSONL files, then saves what arrived meanwhile. Returns how many lines were imported. */\r\n async start() {\r\n const imported = await this.importLogs()\r\n const queued = this.queued.splice(0)\r\n if (queued.length) await this.ctx.database.upsert('bots_message', queued.map(toRow))\r\n this.ready = true\r\n return imported\r\n }\r\n\r\n add(record: MessageRecord) {\r\n if (!this.ready) {\r\n this.queued.push(record)\r\n return\r\n }\r\n const task = this.ctx.database.create('bots_message', toRow(record)).catch(this.onError)\r\n this.pending.add(task)\r\n void task.finally(() => this.pending.delete(task))\r\n }\r\n\r\n /** The newest messages of a bot that match, oldest first. */\r\n async query(bot: string, options: MessageQuery): Promise<MessageRecord[]> {\r\n await Promise.all(this.pending)\r\n const rows = await this.ctx.database\r\n .select('bots_message', {\r\n bot,\r\n ...(options.channel ? { channelId: options.channel } : {}),\r\n ...(options.before ? { timestamp: { $lt: options.before } } : {}),\r\n })\r\n .orderBy('timestamp', 'desc')\r\n .limit(options.limit)\r\n .execute()\r\n return rows.reverse().map(fromRow)\r\n }\r\n\r\n /**\r\n * Imports the daily JSONL files under `messages/<bot>/` that hold messages newer than the newest\r\n * stored for that bot: everything the first time, then whatever was written while the database\r\n * plugin was off. The files stay where they are.\r\n */\r\n private async importLogs() {\r\n const root = join(this.ctx.storage.dir, 'messages')\r\n let imported = 0\r\n for (const bot of await readdir(root).catch(() => [] as string[])) {\r\n const newest = Number(await this.ctx.database.select('bots_message', { bot }).execute((row) => $.max(row.timestamp))) || 0\r\n const since = newest ? new Date(newest).toISOString().slice(0, 10) : ''\r\n const days = (await readdir(join(root, bot)).catch(() => [] as string[]))\r\n .filter((name) => name.endsWith('.jsonl') && name.slice(0, -'.jsonl'.length) >= since)\r\n .sort()\r\n for (const day of days) {\r\n const records = (await this.ctx.storage.tail<MessageRecord>(`messages/${bot}/${day.slice(0, -'.jsonl'.length)}`, Infinity))\r\n .filter((record) => record?.id && record.timestamp > newest)\r\n for (let i = 0; i < records.length; i += IMPORT_BATCH) {\r\n await this.ctx.database.upsert('bots_message', records.slice(i, i + IMPORT_BATCH).map((record) => toRow({ ...record, botId: record.botId ?? bot })))\r\n }\r\n imported += records.length\r\n }\r\n }\r\n return imported\r\n }\r\n}\r\n"],"mappings":";;;;;AAoCA,SAAgB,MAAM,QAAmC;CACvD,OAAO;EACL,IAAI,OAAO;EACX,KAAK,OAAO;EACZ,WAAW,OAAO,aAAa;EAC/B,WAAW,OAAO;EAClB,aAAa,OAAO,QAAQ;EAC5B,WAAW,OAAO,QAAQ;EAC1B,aAAa,OAAO,QAAQ,QAAQ;EACpC,WAAW,OAAO,QAAQ,aAAa;EACvC,QAAQ,OAAO,KAAK;EACpB,UAAU,OAAO,KAAK,QAAQ;EAC9B,UAAU,OAAO,KAAK,QAAQ;EAC9B,MAAM,eAAe,OAAO,YAAY,CAAC,CAAC;EAC1C,UAAU,OAAO,YAAY,CAAC;EAC9B,MAAM,OAAO,QAAQ,YAAY,OAAO,YAAY,CAAC,CAAC;EACtD,WAAW,OAAO,aAAa,CAAC;EAChC,QAAQ,OAAO,UAAU,EAAE,MAAM,OAAO;EACxC,SAAS,OAAO,WAAW;EAC3B,WAAW,OAAO;CACpB;AACF;AAEA,SAAgB,QAAQ,KAAgC;CACtD,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,GAAI,IAAI,YAAY,EAAE,WAAW,IAAI,UAAU,IA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,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,CAAa,EAAA,CACpE,QAAQ,SAAS,KAAK,SAAS,QAAQ,KAAK,KAAK,MAAM,GAAG,EAAgB,KAAK,KAAK,CAAC,CACrF,KAAK;GACR,KAAK,MAAM,OAAO,MAAM;IACtB,MAAM,WAAW,MAAM,KAAK,IAAI,QAAQ,KAAoB,YAAY,IAAI,GAAG,IAAI,MAAM,GAAG,EAAgB,KAAK,QAAQ,EAAA,CACtH,QAAQ,WAAW,QAAQ,MAAM,OAAO,YAAY,MAAM;IAC7D,KAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,cACvC,MAAM,KAAK,IAAI,SAAS,OAAO,gBAAgB,QAAQ,MAAM,GAAG,IAAI,YAAY,CAAC,CAAC,KAAK,WAAW,MAAM;KAAE,GAAG;KAAQ,OAAO,OAAO,SAAS;IAAI,CAAC,CAAC,CAAC;IAErJ,YAAY,QAAQ;GACtB;EACF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"archive.js","names":[],"sources":["../src/archive.ts"],"sourcesContent":["import { type Context, type MessageRecord, messageType, segmentsToText } from '@mushinjs/core'\nimport type {} from '@mushinjs/plugin-database'\nimport type {} from '@mushinjs/plugin-storage'\nimport { $ } from 'minato'\n\ndeclare module 'minato' {\n interface Tables {\n bots_message: MessageRow\n }\n}\n\n/** A message record as a row: the channel and user flattened so they can be filtered and indexed. */\nexport interface MessageRow {\n id: string\n bot: string\n messageId: string\n direction: string\n channelType: string\n channelId: string\n channelName: string\n fromGroup: string\n userId: string\n userName: string\n userRole: string\n /** Plain text, for searching. */\n text: string\n segments: any\n type: string\n platforms: any\n source: any\n replyTo: string\n timestamp: number\n}\n\nexport function toRow(record: MessageRecord): MessageRow {\n return {\n id: record.id,\n bot: record.botId,\n messageId: record.messageId ?? '',\n direction: record.direction,\n channelType: record.channel.type,\n channelId: record.channel.id,\n channelName: record.channel.name ?? '',\n fromGroup: record.channel.fromGroup ?? '',\n userId: record.user.id,\n userName: record.user.name ?? '',\n userRole: record.user.role ?? '',\n text: segmentsToText(record.segments ?? []),\n segments: record.segments ?? [],\n type: record.type ?? messageType(record.segments ?? []),\n platforms: record.platforms ?? [],\n source: record.source ?? { kind: 'user' },\n replyTo: record.replyTo ?? '',\n timestamp: record.timestamp,\n }\n}\n\nexport function fromRow(row: MessageRow): MessageRecord {\n return {\n id: row.id,\n botId: row.bot,\n ...(row.messageId ? { messageId: row.messageId } : {}),\n direction: row.direction as MessageRecord['direction'],\n channel: {\n type: row.channelType as 'group' | 'private',\n id: row.channelId,\n ...(row.channelName ? { name: row.channelName } : {}),\n ...(row.fromGroup ? { fromGroup: row.fromGroup } : {}),\n },\n user: {\n id: row.userId,\n ...(row.userName ? { name: row.userName } : {}),\n ...(row.userRole ? { role: row.userRole as 'owner' | 'admin' | 'member' } : {}),\n },\n segments: row.segments ?? [],\n timestamp: row.timestamp,\n ...(row.replyTo ? { replyTo: row.replyTo } : {}),\n type: row.type as MessageRecord['type'],\n platforms: row.platforms ?? [],\n source: row.source ?? { kind: 'user' },\n }\n}\n\nconst IMPORT_BATCH = 500\n\nexport interface MessageQuery {\n limit: number\n channel?: string\n /** Only messages sent before this time (ms). */\n before?: number\n}\n\n/**\n * Message records in the `bots_message` table, next to the daily JSONL files that are always\n * written. Created when the database plugin runs; imports the JSONL lines it does not have yet.\n */\nexport class MessageArchive {\n /** False until the JSONL import is done; until then the JSONL files answer queries. */\n ready = false\n private pending = new Set<Promise<unknown>>()\n /** Records that arrived during the import, saved right after it. */\n private queued: MessageRecord[] = []\n\n constructor(private ctx: Context, private onError: (error: unknown) => void) {\n ctx.model.extend('bots_message', {\n id: 'string',\n bot: 'string',\n messageId: 'string',\n direction: 'string',\n channelType: 'string',\n channelId: 'string',\n channelName: 'string',\n fromGroup: 'string',\n userId: 'string',\n userName: 'string',\n userRole: 'string',\n text: 'text',\n segments: 'json',\n type: 'string',\n platforms: 'json',\n source: 'json',\n replyTo: 'string',\n timestamp: 'double',\n }, { primary: 'id', indexes: [['bot', 'timestamp'], ['bot', 'channelId', 'timestamp']] })\n }\n\n /** Imports the JSONL files, then saves what arrived meanwhile. Returns how many lines were imported. */\n async start() {\n const imported = await this.importLogs()\n const queued = this.queued.splice(0)\n if (queued.length) await this.ctx.database.upsert('bots_message', queued.map(toRow))\n this.ready = true\n return imported\n }\n\n add(record: MessageRecord) {\n if (!this.ready) {\n this.queued.push(record)\n return\n }\n const task = this.ctx.database.create('bots_message', toRow(record)).catch(this.onError)\n this.pending.add(task)\n void task.finally(() => this.pending.delete(task))\n }\n\n /** The newest messages of a bot that match, oldest first. */\n async query(bot: string, options: MessageQuery): Promise<MessageRecord[]> {\n await Promise.all(this.pending)\n const rows = await this.ctx.database\n .select('bots_message', {\n bot,\n ...(options.channel ? { channelId: options.channel } : {}),\n ...(options.before ? { timestamp: { $lt: options.before } } : {}),\n })\n .orderBy('timestamp', 'desc')\n .limit(options.limit)\n .execute()\n return rows.reverse().map(fromRow)\n }\n\n /**\n * Imports the daily JSONL files under `messages/<bot>/` that hold messages newer than the newest\n * stored for that bot: everything the first time, then whatever was written while the database\n * plugin was off. The files stay where they are.\n */\n private async importLogs() {\n let imported = 0\n for (const bot of await this.ctx.storage.children('messages')) {\n const newest = Number(await this.ctx.database.select('bots_message', { bot }).execute((row) => $.max(row.timestamp))) || 0\n const since = newest ? new Date(newest).toISOString().slice(0, 10) : ''\n const days = (await this.ctx.storage.children(`messages/${bot}`))\n .filter((name) => name.endsWith('.jsonl') && name.slice(0, -'.jsonl'.length) >= since)\n .sort()\n for (const day of days) {\n const records = (await this.ctx.storage.tail<MessageRecord>(`messages/${bot}/${day.slice(0, -'.jsonl'.length)}`, Infinity))\n .filter((record) => record?.id && record.timestamp > newest)\n for (let i = 0; i < records.length; i += IMPORT_BATCH) {\n await this.ctx.database.upsert('bots_message', records.slice(i, i + IMPORT_BATCH).map((record) => toRow({ ...record, botId: record.botId ?? bot })))\n }\n imported += records.length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J,YAAY,QAAQ;GACtB;EACF;EACA,OAAO;CACT;AACF"}
|
package/dist/bot.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\r\n type ChannelInfo, type Content, Context, type MessageRecord, type Provenance, type Segment, segmentsToText,\r\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\r\n} from '@mushinjs/core'\r\nimport {\r\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\r\n usageReply,\r\n} from './commands'\r\nimport {\r\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\r\n type MediaResolver, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\r\n} from './types'\r\n\r\nexport type Sendable = Content | SourcedContent\r\n\r\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\r\n\r\ninterface MiddlewareEntry {\r\n plugin: string\r\n callback: Middleware\r\n priority: number\r\n}\r\n\r\nexport interface MiddlewareOptions {\r\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\r\n priority?: number\r\n}\r\n\r\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\r\nexport interface BotHooks {\r\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\r\n status(bot: Bot): void\r\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\r\n commands?(bot: Bot): CommandEntry[]\r\n /** A message ran a registered command. */\r\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\r\n /** The answer to a built-in command such as `/help`. */\r\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\r\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\r\n roleOf?(bot: Bot, userId: string): BotRole | undefined\r\n /** A command that an app plugin answers on every bot, such as `/persona`. */\r\n appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined\r\n /** Where the costs of handling a message go; see `usage` in core. */\r\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\r\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\r\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\r\n}\r\n\r\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\r\n\r\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\r\nconst BUILTIN_PLUGIN = 'bots'\r\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\r\nexport const BUILTIN_PRIORITY = 5\r\n\r\nfunction isSourced(value: Sendable): value is SourcedContent {\r\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\r\n}\r\n\r\n/** One incoming message, as seen by a bot plugin's middleware. */\r\nexport class Session {\r\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\r\n plugin?: string\r\n private parsed?: { value: ParsedCommand | undefined }\r\n\r\n constructor(public bot: Bot, public record: MessageRecord) {}\r\n\r\n get channel() {\r\n return this.record.channel\r\n }\r\n\r\n get user() {\r\n return this.record.user\r\n }\r\n\r\n get segments() {\r\n return this.record.segments\r\n }\r\n\r\n get isDirect() {\r\n return this.record.channel.type === 'private'\r\n }\r\n\r\n /** True when the message @-mentions this bot. */\r\n get mentioned() {\r\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\r\n }\r\n\r\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\r\n get command(): ParsedCommand | undefined {\r\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\r\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\r\n return this.parsed.value\r\n }\r\n\r\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\r\n role(): BotRole | undefined {\r\n return this.bot.roleOf(this.user.id)\r\n }\r\n\r\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\r\n groupRole(): Promise<GroupRole | undefined> {\r\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\r\n }\r\n\r\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\r\n get isAdmin() {\r\n return roleAtLeast(this.role(), 'admin')\r\n }\r\n\r\n /** Plain text with mentions of this bot removed. */\r\n get text() {\r\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\r\n return segmentsToText(segments).trim()\r\n }\r\n\r\n send(content: Sendable) {\r\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\r\n }\r\n\r\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\r\n reply(content: Sendable) {\r\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\r\n if (isSourced(content)) {\r\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\r\n }\r\n return this.send([...quote, ...toSegments(content)])\r\n }\r\n\r\n /** A view of this session attributed to another plugin. */\r\n as(plugin: string) {\r\n const view = Object.create(this) as Session\r\n view.plugin = plugin\r\n return view\r\n }\r\n}\r\n\r\n/**\r\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\r\n * always means that plugin's bot.\r\n */\r\nexport class Bot extends Service {\r\n status: BotStatus = 'offline'\r\n error?: string\r\n selfId?: string\r\n selfName?: string\r\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\r\n selfAvatar?: string\r\n record: BotRecord\r\n private hooks: BotHooks\r\n private transport?: Transport\r\n private middlewares: MiddlewareEntry[] = []\r\n private eventHandlers = new Set<(event: BotEvent) => void>()\r\n private ownCommands = new Set<{ def: CommandDef; plugin: string }>()\r\n private commandProviders = new Set<() => CommandEntry[]>()\r\n private roleResolver?: GroupRoleResolver\r\n private mediaResolver?: MediaResolver\r\n private contactResolver?: ContactResolver\r\n\r\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\r\n super(ctx, 'bot')\r\n this.record = config.record\r\n this.hooks = config.hooks\r\n }\r\n\r\n get id() {\r\n return this.record.id\r\n }\r\n\r\n get platform() {\r\n return this.record.adapter.type\r\n }\r\n\r\n setStatus(status: BotStatus, error?: string) {\r\n const nextError = status === 'error' ? error : undefined\r\n if (status !== this.status || nextError !== this.error) {\r\n const logger = this.ctx.logger('bot')\r\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\r\n else logger.info('status: %s', status)\r\n }\r\n this.status = status\r\n this.error = status === 'error' ? error : undefined\r\n this.hooks.status(this)\r\n }\r\n\r\n setSelf(id: string, name?: string, avatar?: string) {\r\n this.selfId = id\r\n this.selfName = name\r\n this.selfAvatar = avatar\r\n this.hooks.status(this)\r\n }\r\n\r\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\r\n useTransport(transport: Transport) {\r\n return this.ctx.effect(() => {\r\n this.transport = transport\r\n return () => {\r\n if (this.transport !== transport) return\r\n this.transport = undefined\r\n this.setStatus('offline')\r\n }\r\n }, 'bot.useTransport()')\r\n }\r\n\r\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\r\n useRoleResolver(resolver: GroupRoleResolver) {\r\n return this.ctx.effect(() => {\r\n this.roleResolver = resolver\r\n return () => {\r\n if (this.roleResolver === resolver) this.roleResolver = undefined\r\n }\r\n }, 'bot.useRoleResolver()')\r\n }\r\n\r\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\r\n useMediaResolver(resolver: MediaResolver) {\r\n return this.ctx.effect(() => {\r\n this.mediaResolver = resolver\r\n return () => {\r\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\r\n }\r\n }, 'bot.useMediaResolver()')\r\n }\r\n\r\n /** Called by adapters that can list the account's friends and groups. */\r\n useContacts(resolver: ContactResolver) {\r\n return this.ctx.effect(() => {\r\n this.contactResolver = resolver\r\n return () => {\r\n if (this.contactResolver === resolver) this.contactResolver = undefined\r\n }\r\n }, 'bot.useContacts()')\r\n }\r\n\r\n /** The account's friends and groups; empty when the adapter cannot list them. */\r\n async contacts() {\r\n return this.contactResolver ? this.contactResolver() : []\r\n }\r\n\r\n /**\r\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\r\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\r\n */\r\n sandbox(text: string) {\r\n const mention = /^@\\S*\\s*/.exec(text)\r\n const rest = mention ? text.slice(mention[0].length) : text\r\n const segments: Segment[] = [\r\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\r\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\r\n ]\r\n // Not awaited: a flow may wait for the next message, which comes through another call.\r\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\r\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\r\n })\r\n }\r\n\r\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\r\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\r\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\r\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\r\n }\r\n\r\n /** The messages of a forwarded chat history. */\r\n async forward(id: string) {\r\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\r\n return this.mediaResolver.forward(id)\r\n }\r\n\r\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\r\n roleOf(userId: string): BotRole | undefined {\r\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\r\n if (userId === SANDBOX_USER.id) return 'master'\r\n return this.hooks.roleOf?.(this, userId)\r\n }\r\n\r\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\r\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\r\n if (target.channel.type !== 'group' || !target.user.id) return\r\n if (target.user.role) return target.user.role\r\n try {\r\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\r\n } catch (error) {\r\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\r\n }\r\n }\r\n\r\n /** Whether a command's role requirement lets this session run it; logs why not. */\r\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\r\n const required = requiredRole(def)\r\n if (!required) return true\r\n const role = session.role()\r\n if (role === undefined) {\r\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\r\n return false\r\n }\r\n return roleAtLeast(role, required)\r\n }\r\n\r\n /** Registers middleware for incoming messages; runs in registration order. */\r\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\r\n const ctx = this.ctx\r\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, callback, priority: options.priority ?? 0 }\r\n return ctx.effect(() => {\r\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\r\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\r\n if (index < 0) this.middlewares.push(entry)\r\n else this.middlewares.splice(index, 0, entry)\r\n return () => {\r\n const index = this.middlewares.indexOf(entry)\r\n if (index >= 0) this.middlewares.splice(index, 1)\r\n }\r\n }, 'bot.middleware()')\r\n }\r\n\r\n get prefixes() {\r\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\r\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\r\n }\r\n\r\n /**\r\n * Splits text into a command, with the registered command it names. Commands with prefixes of\r\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\r\n */\r\n parseCommand(text: string): ParsedCommand | undefined {\r\n const entries = this.hooks.commands?.(this) ?? []\r\n for (const entry of entries) {\r\n if (!entry.prefixes?.length) continue\r\n const parsed = splitCommand(text, entry.prefixes)\r\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\r\n }\r\n const parsed = splitCommand(text, this.prefixes)\r\n if (!parsed) return\r\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\r\n return entry ? { ...parsed, entry } : parsed\r\n }\r\n\r\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\r\n localCommands(): CommandEntry[] {\r\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\r\n for (const provider of this.commandProviders) {\r\n try {\r\n entries.push(...provider())\r\n } catch (error) {\r\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\r\n }\r\n }\r\n return entries\r\n }\r\n\r\n /**\r\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\r\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\r\n */\r\n defineCommands(provider: () => CommandEntry[]) {\r\n return this.ctx.effect(() => {\r\n this.commandProviders.add(provider)\r\n return () => this.commandProviders.delete(provider)\r\n }, 'bot.defineCommands()')\r\n }\r\n\r\n /**\r\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\r\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\r\n * replies with how to write the command.\r\n */\r\n command(def: CommandDef, handler: CommandHandler) {\r\n const ctx = this.ctx\r\n const entry = { def, plugin: ctx.fiber.name }\r\n ctx.effect(() => {\r\n this.ownCommands.add(entry)\r\n return () => this.ownCommands.delete(entry)\r\n }, `bot.command(${def.name})`)\r\n return this.middleware(async (session, next) => {\r\n const parsed = session.command\r\n if (!parsed || !commandMatches(def, parsed.name)) return next()\r\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\r\n if (!this.allows(def, session)) return\r\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\r\n if (!values.ok) {\r\n await session.reply(usageReply(def, parsed.prefix))\r\n return\r\n }\r\n await handler(session, values.values, parsed)\r\n })\r\n }\r\n\r\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\r\n middlewareOrder() {\r\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\r\n }\r\n\r\n /** Listens for adapter events that are not messages (notices, requests). */\r\n onEvent(handler: (event: BotEvent) => void) {\r\n return this.ctx.effect(() => {\r\n this.eventHandlers.add(handler)\r\n return () => this.eventHandlers.delete(handler)\r\n }, 'bot.onEvent()')\r\n }\r\n\r\n /** Called by adapters for non-message events. */\r\n dispatchEvent(event: BotEvent) {\r\n this.logEvent(event)\r\n for (const handler of this.eventHandlers) {\r\n try {\r\n handler(event)\r\n } catch (error) {\r\n this.ctx.logger('bot').warn(error)\r\n }\r\n }\r\n }\r\n\r\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\r\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\r\n const started = Date.now()\r\n const record = this.hooks.record({\r\n botId: this.id,\r\n messageId: message.messageId,\r\n direction: 'in',\r\n channel: message.channel,\r\n user: message.user,\r\n segments: message.segments,\r\n timestamp: message.timestamp ?? Date.now(),\r\n source: options.source ?? { kind: 'user' },\r\n })\r\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))\r\n const session = new Session(this, record)\r\n const entry = session.command?.entry\r\n if (entry) {\r\n try {\r\n this.hooks.commandCalled?.(this, entry, session)\r\n } catch {}\r\n }\r\n const chain = [...this.middlewares]\r\n const appHandler = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\r\n if (entry?.source.kind === 'builtin' || appHandler) {\r\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\r\n const builtin: MiddlewareEntry = {\r\n plugin: appHandler ? entry!.source.id : BUILTIN_PLUGIN,\r\n priority: BUILTIN_PRIORITY,\r\n callback: async (view, next) => {\r\n if (!this.allows(entry!, view)) return next()\r\n if (appHandler) {\r\n await appHandler(view)\r\n return\r\n }\r\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\r\n if (answer !== undefined) await view.reply(answer)\r\n },\r\n }\r\n const index = chain.findIndex((item) => item.priority < builtin.priority)\r\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\r\n }\r\n /** The plugin that kept the message from the ones after it, if one did. */\r\n let stoppedAt: string | undefined\r\n const run = async (index: number): Promise<void> => {\r\n const entry = chain[index]\r\n if (!entry) return\r\n let passed = false\r\n try {\r\n await entry.callback(session.as(entry.plugin), () => {\r\n passed = true\r\n return run(index + 1)\r\n })\r\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\r\n } catch (error) {\r\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\r\n }\r\n }\r\n const outer = this.hooks.usageScope?.(this, record)\r\n const scope: UsageScope = {\r\n botId: this.id,\r\n messageId: record.id,\r\n report: (event) => {\r\n outer?.report(event)\r\n this.logUsage(event)\r\n },\r\n }\r\n await usage.run(scope, () => run(0))\r\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\r\n return session\r\n }\r\n\r\n /**\r\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\r\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\r\n */\r\n private logEvent(event: BotEvent) {\r\n const name = event.name ?? event.type\r\n const target = event.data?.target_id ?? undefined\r\n const parts = [\r\n event.user && `from ${who(event.user)}`,\r\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\r\n target !== undefined && target !== null && `to ${target}`,\r\n event.message?.text && `: ${preview(event.message.segments)}`,\r\n ].filter(Boolean).join(' ').replace(' :', ':')\r\n const quiet = !event.name || event.name === 'notify.input_status'\r\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\r\n }\r\n\r\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\r\n private logUsage(event: UsageEvent) {\r\n const logger = this.ctx.logger('llm')\r\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\r\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\r\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\r\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\r\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\r\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\r\n }\r\n\r\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\r\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\r\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\r\n }\r\n\r\n /** Raw adapter API, e.g. a NapCat extension action. */\r\n async call(action: string, params: Record<string, any> = {}) {\r\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\r\n return this.transport.call(action, params)\r\n }\r\n\r\n async deliver(\r\n channel: ChannelInfo,\r\n content: Sendable,\r\n options: { plugin?: string; source?: Provenance; replyTo?: string },\r\n ) {\r\n const sandbox = isSandbox(channel)\r\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\r\n let segments: Segment[]\r\n let source: Provenance | undefined = options.source\r\n if (isSourced(content)) {\r\n segments = content.segments ?? toSegments(content.text ?? '')\r\n source ??= content.source\r\n } else {\r\n segments = toSegments(content)\r\n }\r\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\r\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\r\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\r\n return\r\n }\r\n const started = Date.now()\r\n const logger = this.ctx.logger('message')\r\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\r\n let messageId: string | undefined\r\n try {\r\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\r\n } catch (error) {\r\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\r\n throw error\r\n }\r\n const ms = Date.now() - started\r\n const bytes = byteSize(segments)\r\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\r\n const record = this.hooks.record({\r\n botId: this.id,\r\n messageId,\r\n direction: 'out',\r\n channel,\r\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\r\n segments,\r\n timestamp: Date.now(),\r\n replyTo: options.replyTo,\r\n source,\r\n })\r\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause: usage.current()?.messageId })\r\n return record\r\n }\r\n}\r\n\r\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\r\nexport function byteSize(segments: Segment[]) {\r\n return Buffer.byteLength(JSON.stringify(segments))\r\n}\r\n\r\n/** A message on one line for the bot's log, cut to a readable length. */\r\nfunction preview(segments: Segment[]) {\r\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\r\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\r\n}\r\n\r\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\r\nfunction chat(channel: ChannelInfo) {\r\n if (isSandbox(channel)) return 'the sandbox'\r\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\r\n return channel.type === 'group' ? `group ${name}` : name\r\n}\r\n\r\nfunction who(user: UserInfo) {\r\n return user.name ? `${user.name} (${user.id})` : user.id\r\n}\r\n\r\nfunction duration(ms: number) {\r\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\r\n}\r\n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;;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"}
|
|
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,QAA8B;EAAxC,KAAA,MAAA;EAAiB,KAAA,SAAA;CAAwB;CAE5D,IAAI,UAAU;EACZ,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,OAAO;EACT,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO,QAAQ,SAAS;CACtC;;CAGA,IAAI,YAAY;EACd,OAAO,KAAK,SAAS,MAAM,MAAM,EAAE,SAAS,QAAQ,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM;CAC3F;;CAGA,IAAI,UAAqC;EAEvC,KAAK,WAAW,EAAE,OAAO,KAAK,IAAI,aAAa,KAAK,IAAI,EAAE;EAC1D,OAAO,KAAK,OAAO;CACrB;;CAGA,OAA4B;EAC1B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,EAAE;CACrC;;CAGA,YAA4C;EAC1C,OAAO,KAAK,IAAI,YAAY;GAAE,SAAS,KAAK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UAAqB;CAC5C,OAAO,OAAO,WAAW,KAAK,UAAU,QAAQ,CAAC;AACnD;;AAGA,SAAS,QAAQ,UAAqB;CACpC,MAAM,OAAO,eAAe,QAAQ,CAAC,CAAC,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK;CAChE,OAAO,KAAK,SAAS,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/commands.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["/**\r\n * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the\r\n * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can\r\n * list them in one place.\r\n */\r\n\r\nimport type { Segment } from '@mushinjs/core'\r\n\r\n/**\r\n * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,\r\n * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one\r\n * of `choices`.\r\n */\r\nexport type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice'\r\n\r\n/** One argument of a command, in the order they are written. */\r\nexport interface CommandArg {\r\n name: string\r\n type: CommandArgType\r\n /** Can be left out; then `default` is used, or the argument is missing from the values. */\r\n optional?: boolean\r\n /** Takes the rest of the message. Only text arguments can; the last text argument always does. */\r\n rest?: boolean\r\n default?: string | number | boolean\r\n /** For `choice` arguments. */\r\n choices?: string[]\r\n /** Shown in the usage reply and the editor. */\r\n description?: string\r\n}\r\n\r\nexport type ArgValue = string | number | boolean\r\n\r\nexport interface CommandDef {\r\n /** Without the prefix, e.g. `score`. */\r\n name: string\r\n aliases?: string[]\r\n description?: string\r\n /** What follows the name, in order. */\r\n args?: CommandArg[]\r\n /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */\r\n prefixes?: string[]\r\n /** Left out of `/help`. */\r\n hidden?: boolean\r\n /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */\r\n permission?: 'all' | 'admin' | 'master'\r\n /** The same as `permission`, as a role: `{ role: 'admin' }`. */\r\n role?: 'user' | 'admin' | 'master'\r\n}\r\n\r\nexport interface CommandSource {\r\n kind: 'flow' | 'plugin' | 'builtin'\r\n /** Flow id or plugin name. */\r\n id: string\r\n /** Flow or plugin name, for display. */\r\n name: string\r\n /** The command node, for flows. */\r\n nodeId?: string\r\n}\r\n\r\nexport interface CommandEntry extends CommandDef {\r\n botId: string\r\n source: CommandSource\r\n /** For flow commands: higher answers first when two register the same name. */\r\n priority?: number\r\n}\r\n\r\n/** Per-bot command settings, stored on the bot record. */\r\nexport interface CommandSettings {\r\n /** Defaults to `['/']`. */\r\n prefixes?: string[]\r\n /** Answer `/help` with the list of commands; on unless set to false. */\r\n help?: boolean\r\n /** First line of the help menu. */\r\n helpTitle?: string\r\n /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */\r\n admins?: string[]\r\n /** `/help` lists only the commands the asker may run. */\r\n helpByRole?: boolean\r\n}\r\n\r\nexport const DEFAULT_PREFIXES = ['/']\r\nexport const DEFAULT_HELP_TITLE = '可用指令:'\r\n\r\n/** A message split into prefix, command name and the text after it. */\r\nexport interface ParsedCommand {\r\n prefix: string\r\n /** As written, without the prefix. */\r\n name: string\r\n rest: string\r\n /** The registered command the name or alias belongs to, if any. */\r\n entry?: CommandEntry\r\n}\r\n\r\n/** Splits a message into a command, or nothing when it does not start with a prefix. */\r\nexport function splitCommand(text: string, prefixes: string[] = DEFAULT_PREFIXES): Omit<ParsedCommand, 'entry'> | undefined {\r\n const trimmed = text.trim()\r\n const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item))\r\n if (prefix === undefined) return\r\n const body = trimmed.slice(prefix.length)\r\n const match = /^(\\S+)(?:\\s+([\\s\\S]*))?$/.exec(body)\r\n if (!match) return\r\n return { prefix, name: match[1], rest: (match[2] ?? '').trim() }\r\n}\r\n\r\n/** Whether a command (by name or alias) is the one written. Names are compared without case. */\r\nexport function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string) {\r\n const name = written.toLowerCase()\r\n return [def.name, ...(def.aliases ?? [])].some((item) => !!item && item.toLowerCase() === name)\r\n}\r\n\r\nexport type ArgsResult =\r\n | { ok: true; values: Record<string, ArgValue> }\r\n | { ok: false; error: string; arg?: string }\r\n\r\nconst YES = new Set(['是', '对', '开', '开启', 'yes', 'y', 'true', 'on', '1'])\r\nconst NO = new Set(['否', '不', '关', '关闭', 'no', 'n', 'false', 'off', '0'])\r\n\r\n/**\r\n * Fills a command's arguments from the text after the command. `segments` are the message's, so an\r\n * @mention fills a `user` argument with the id rather than the name shown in the text.\r\n */\r\nexport function parseArgs(args: CommandArg[], rest: string, segments: Segment[] = []): ArgsResult {\r\n const mentions = segments.filter((segment) => segment.type === 'at' && segment.data.qq !== 'all')\r\n const words = tokenize(rest, mentions)\r\n const values: Record<string, ArgValue> = {}\r\n const lastText = args.findLastIndex((arg) => arg.type === 'text')\r\n for (const [index, arg] of args.entries()) {\r\n let word: Token | undefined\r\n if (arg.type === 'text' && (arg.rest || index === lastText) && index === args.length - 1) {\r\n const taken = words.splice(0)\r\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\r\n } else if (arg.type === 'text' && (arg.rest || index === lastText)) {\r\n // Leaves one word for each argument after it.\r\n const later = args.length - 1 - index\r\n const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0))\r\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\r\n } else {\r\n word = words.shift()\r\n }\r\n if (!word?.text) {\r\n if (arg.default !== undefined && arg.default !== '') values[arg.name] = arg.default\r\n else if (!arg.optional) return { ok: false, error: `missing ${arg.name}`, arg: arg.name }\r\n continue\r\n }\r\n const value = convertArg(arg, word)\r\n if (value === undefined) return { ok: false, error: `${arg.name} should be ${argTypeLabel(arg, 'en')}`, arg: arg.name }\r\n values[arg.name] = value\r\n }\r\n return { ok: true, values }\r\n}\r\n\r\ninterface Token {\r\n text: string\r\n /** The user an @mention names. */\r\n user?: string\r\n}\r\n\r\n/** Splits text into words; `@name` words that stand for an @mention carry its user id. */\r\nfunction tokenize(text: string, mentions: Segment[]): Token[] {\r\n const queue = [...mentions]\r\n return (text.trim() ? text.trim().split(/\\s+/) : []).map((word) => {\r\n const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`)\r\n if (index < 0) return { text: word }\r\n const [segment] = queue.splice(index, 1)\r\n return { text: word, user: String(segment.data.qq) }\r\n })\r\n}\r\n\r\nfunction convertArg(arg: CommandArg, word: Token): ArgValue | undefined {\r\n const raw = word.text\r\n switch (arg.type) {\r\n case 'number': {\r\n const number = Number(raw)\r\n return Number.isFinite(number) ? number : undefined\r\n }\r\n case 'boolean': {\r\n const folded = raw.toLowerCase()\r\n return YES.has(folded) ? true : NO.has(folded) ? false : undefined\r\n }\r\n case 'user': {\r\n if (word.user) return word.user\r\n const id = raw.replace(/^@/, '')\r\n return /^\\d{4,}$/.test(id) ? id : undefined\r\n }\r\n case 'choice': {\r\n const found = (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase())\r\n return found\r\n }\r\n default:\r\n return raw\r\n }\r\n}\r\n\r\n/** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */\r\nexport function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale: 'zh-CN' | 'en' = 'zh-CN') {\r\n const zh = locale === 'zh-CN'\r\n switch (arg.type) {\r\n case 'number': return zh ? '数字' : 'a number'\r\n case 'boolean': return zh ? '是/否' : 'yes or no'\r\n case 'user': return zh ? '@某人' : 'an @mention or user id'\r\n case 'choice': return (arg.choices ?? []).join('|') || (zh ? '选项' : 'a choice')\r\n default: return zh ? '文本' : 'text'\r\n }\r\n}\r\n\r\n/** The arguments as written in a usage line: `<分数:数字> [备注]`. */\r\nexport function formatArgs(args: CommandArg[] | undefined) {\r\n return (args ?? []).map((arg) => {\r\n const type = arg.type === 'text' ? '' : `:${argTypeLabel(arg)}`\r\n const body = `${arg.name}${type}${arg.rest ? '...' : ''}`\r\n return arg.optional || (arg.default !== undefined && arg.default !== '') ? `[${body}]` : `<${body}>`\r\n }).join(' ')\r\n}\r\n\r\n/** The prefix a command is shown with: its own first prefix, else the bot's. */\r\nexport function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix = DEFAULT_PREFIXES[0]) {\r\n return def.prefixes?.find(Boolean) ?? botPrefix\r\n}\r\n\r\n/** How a command is written, e.g. `/score <score:数字>`. */\r\nexport function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\r\n const args = formatArgs(def.args)\r\n return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ''}`\r\n}\r\n\r\n/** The reply when a command's arguments do not fit: the usage line, then what each argument is. */\r\nexport function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\r\n const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`)\r\n return [`用法:${commandUsage(def, prefix)}`, ...notes].join('\\n')\r\n}\r\n\r\n/** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */\r\nexport function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined {\r\n const role = def.role ?? (def.permission === 'all' ? undefined : def.permission)\r\n return role === 'admin' || role === 'master' ? role : undefined\r\n}\r\n\r\n/** The help menu for a bot's commands: one line per command, hidden ones left out. */\r\nexport function helpText(entries: CommandEntry[], settings: CommandSettings = {}) {\r\n const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0]\r\n const seen = new Set<string>()\r\n const lines: string[] = []\r\n for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {\r\n const key = entry.name.toLowerCase()\r\n if (entry.hidden || seen.has(key)) continue\r\n seen.add(key)\r\n const prefix = commandPrefix(entry, botPrefix)\r\n const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join('、')\r\n lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ''}${entry.description ? ` —— ${entry.description}` : ''}`)\r\n }\r\n return [settings.helpTitle || DEFAULT_HELP_TITLE, ...lines].join('\\n')\r\n}\r\n\r\n/** Names (and aliases) that more than one source registers on the same bot. */\r\nexport function commandConflicts(entries: CommandEntry[]) {\r\n const owners = new Map<string, CommandEntry[]>()\r\n for (const entry of entries) {\r\n for (const name of new Set([entry.name, ...(entry.aliases ?? [])].filter(Boolean).map((item) => item.toLowerCase()))) {\r\n const key = `${entry.botId}|${name}`\r\n owners.set(key, [...(owners.get(key) ?? []), entry])\r\n }\r\n }\r\n return [...owners.entries()]\r\n .filter(([, list]) => list.length > 1)\r\n // The first entry is the one that answers: highest priority, then registration order.\r\n .map(([key, list]) => ({ botId: key.split('|')[0], name: key.slice(key.indexOf('|') + 1), entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)) }))\r\n}\r\n"],"mappings":";AAgFA,MAAa,mBAAmB,CAAC,GAAG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G,GAAG;EACnC,KAAK,IAAI,GAAG;EACZ,MAAM,SAAS,cAAc,OAAO,SAAS;EAC7C,MAAM,UAAU,MAAM,SAAS,OAAO,OAAO,CAAC,CAAC,KAAK,UAAU,GAAG,SAAS,OAAO,CAAC,CAAC,KAAK,GAAG;EAC3F,MAAM,KAAK,GAAG,aAAa,OAAO,MAAM,IAAI,UAAU,IAAI,QAAQ,KAAK,KAAK,MAAM,cAAc,OAAO,MAAM,gBAAgB,IAAI;CACnI;CACA,OAAO,CAAC,SAAS,aAAA,SAAiC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;AACvE;;AAGA,SAAgB,iBAAiB,SAAyB;CACxD,MAAM,yBAAS,IAAI,IAA4B;CAC/C,KAAK,MAAM,SAAS,SAClB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,MAAM,MAAM,GAAI,MAAM,WAAW,CAAC,CAAE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC,GAAG;EACpH,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG;EAC9B,OAAO,IAAI,KAAK,CAAC,GAAI,OAAO,IAAI,GAAG,KAAK,CAAC,GAAI,KAAK,CAAC;CACrD;CAEF,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,QAAQ,GAAG,UAAU,KAAK,SAAS,CAAC,CAAC,CAErC,KAAK,CAAC,KAAK,WAAW;EAAE,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EAAI,MAAM,IAAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;EAAG,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAAE,EAAE;AACzK"}
|
|
1
|
+
{"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["/**\n * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the\n * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can\n * list them in one place.\n */\n\nimport type { Segment } from '@mushinjs/core'\n\n/**\n * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,\n * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one\n * of `choices`.\n */\nexport type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice'\n\n/** One argument of a command, in the order they are written. */\nexport interface CommandArg {\n name: string\n type: CommandArgType\n /** Can be left out; then `default` is used, or the argument is missing from the values. */\n optional?: boolean\n /** Takes the rest of the message. Only text arguments can; the last text argument always does. */\n rest?: boolean\n default?: string | number | boolean\n /** For `choice` arguments. */\n choices?: string[]\n /** Shown in the usage reply and the editor. */\n description?: string\n}\n\nexport type ArgValue = string | number | boolean\n\nexport interface CommandDef {\n /** Without the prefix, e.g. `score`. */\n name: string\n aliases?: string[]\n description?: string\n /** What follows the name, in order. */\n args?: CommandArg[]\n /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */\n prefixes?: string[]\n /** Left out of `/help`. */\n hidden?: boolean\n /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */\n permission?: 'all' | 'admin' | 'master'\n /** The same as `permission`, as a role: `{ role: 'admin' }`. */\n role?: 'user' | 'admin' | 'master'\n}\n\nexport interface CommandSource {\n kind: 'flow' | 'plugin' | 'builtin'\n /** Flow id or plugin name. */\n id: string\n /** Flow or plugin name, for display. */\n name: string\n /** The command node, for flows. */\n nodeId?: string\n}\n\nexport interface CommandEntry extends CommandDef {\n botId: string\n source: CommandSource\n /** For flow commands: higher answers first when two register the same name. */\n priority?: number\n}\n\n/** Per-bot command settings, stored on the bot record. */\nexport interface CommandSettings {\n /** Defaults to `['/']`. */\n prefixes?: string[]\n /** Answer `/help` with the list of commands; on unless set to false. */\n help?: boolean\n /** First line of the help menu. */\n helpTitle?: string\n /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */\n admins?: string[]\n /** `/help` lists only the commands the asker may run. */\n helpByRole?: boolean\n}\n\nexport const DEFAULT_PREFIXES = ['/']\nexport const DEFAULT_HELP_TITLE = '可用指令:'\n\n/** A message split into prefix, command name and the text after it. */\nexport interface ParsedCommand {\n prefix: string\n /** As written, without the prefix. */\n name: string\n rest: string\n /** The registered command the name or alias belongs to, if any. */\n entry?: CommandEntry\n}\n\n/** Splits a message into a command, or nothing when it does not start with a prefix. */\nexport function splitCommand(text: string, prefixes: string[] = DEFAULT_PREFIXES): Omit<ParsedCommand, 'entry'> | undefined {\n const trimmed = text.trim()\n const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item))\n if (prefix === undefined) return\n const body = trimmed.slice(prefix.length)\n const match = /^(\\S+)(?:\\s+([\\s\\S]*))?$/.exec(body)\n if (!match) return\n return { prefix, name: match[1], rest: (match[2] ?? '').trim() }\n}\n\n/** Whether a command (by name or alias) is the one written. Names are compared without case. */\nexport function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string) {\n const name = written.toLowerCase()\n return [def.name, ...(def.aliases ?? [])].some((item) => !!item && item.toLowerCase() === name)\n}\n\nexport type ArgsResult =\n | { ok: true; values: Record<string, ArgValue> }\n | { ok: false; error: string; arg?: string }\n\nconst YES = new Set(['是', '对', '开', '开启', 'yes', 'y', 'true', 'on', '1'])\nconst NO = new Set(['否', '不', '关', '关闭', 'no', 'n', 'false', 'off', '0'])\n\n/**\n * Fills a command's arguments from the text after the command. `segments` are the message's, so an\n * @mention fills a `user` argument with the id rather than the name shown in the text.\n */\nexport function parseArgs(args: CommandArg[], rest: string, segments: Segment[] = []): ArgsResult {\n const mentions = segments.filter((segment) => segment.type === 'at' && segment.data.qq !== 'all')\n const words = tokenize(rest, mentions)\n const values: Record<string, ArgValue> = {}\n const lastText = args.findLastIndex((arg) => arg.type === 'text')\n for (const [index, arg] of args.entries()) {\n let word: Token | undefined\n if (arg.type === 'text' && (arg.rest || index === lastText) && index === args.length - 1) {\n const taken = words.splice(0)\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else if (arg.type === 'text' && (arg.rest || index === lastText)) {\n // Leaves one word for each argument after it.\n const later = args.length - 1 - index\n const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0))\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else {\n word = words.shift()\n }\n if (!word?.text) {\n if (arg.default !== undefined && arg.default !== '') values[arg.name] = arg.default\n else if (!arg.optional) return { ok: false, error: `missing ${arg.name}`, arg: arg.name }\n continue\n }\n const value = convertArg(arg, word)\n if (value === undefined) return { ok: false, error: `${arg.name} should be ${argTypeLabel(arg, 'en')}`, arg: arg.name }\n values[arg.name] = value\n }\n return { ok: true, values }\n}\n\ninterface Token {\n text: string\n /** The user an @mention names. */\n user?: string\n}\n\n/** Splits text into words; `@name` words that stand for an @mention carry its user id. */\nfunction tokenize(text: string, mentions: Segment[]): Token[] {\n const queue = [...mentions]\n return (text.trim() ? text.trim().split(/\\s+/) : []).map((word) => {\n const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`)\n if (index < 0) return { text: word }\n const [segment] = queue.splice(index, 1)\n return { text: word, user: String(segment.data.qq) }\n })\n}\n\nfunction convertArg(arg: CommandArg, word: Token): ArgValue | undefined {\n const raw = word.text\n switch (arg.type) {\n case 'number': {\n const number = Number(raw)\n return Number.isFinite(number) ? number : undefined\n }\n case 'boolean': {\n const folded = raw.toLowerCase()\n return YES.has(folded) ? true : NO.has(folded) ? false : undefined\n }\n case 'user': {\n if (word.user) return word.user\n const id = raw.replace(/^@/, '')\n return /^\\d{4,}$/.test(id) ? id : undefined\n }\n case 'choice': {\n const found = (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase())\n return found\n }\n default:\n return raw\n }\n}\n\n/** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */\nexport function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale: 'zh-CN' | 'en' = 'zh-CN') {\n const zh = locale === 'zh-CN'\n switch (arg.type) {\n case 'number': return zh ? '数字' : 'a number'\n case 'boolean': return zh ? '是/否' : 'yes or no'\n case 'user': return zh ? '@某人' : 'an @mention or user id'\n case 'choice': return (arg.choices ?? []).join('|') || (zh ? '选项' : 'a choice')\n default: return zh ? '文本' : 'text'\n }\n}\n\n/** The arguments as written in a usage line: `<分数:数字> [备注]`. */\nexport function formatArgs(args: CommandArg[] | undefined) {\n return (args ?? []).map((arg) => {\n const type = arg.type === 'text' ? '' : `:${argTypeLabel(arg)}`\n const body = `${arg.name}${type}${arg.rest ? '...' : ''}`\n return arg.optional || (arg.default !== undefined && arg.default !== '') ? `[${body}]` : `<${body}>`\n }).join(' ')\n}\n\n/** The prefix a command is shown with: its own first prefix, else the bot's. */\nexport function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix = DEFAULT_PREFIXES[0]) {\n return def.prefixes?.find(Boolean) ?? botPrefix\n}\n\n/** How a command is written, e.g. `/score <score:数字>`. */\nexport function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const args = formatArgs(def.args)\n return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ''}`\n}\n\n/** The reply when a command's arguments do not fit: the usage line, then what each argument is. */\nexport function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`)\n return [`用法:${commandUsage(def, prefix)}`, ...notes].join('\\n')\n}\n\n/** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */\nexport function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined {\n const role = def.role ?? (def.permission === 'all' ? undefined : def.permission)\n return role === 'admin' || role === 'master' ? role : undefined\n}\n\n/** The help menu for a bot's commands: one line per command, hidden ones left out. */\nexport function helpText(entries: CommandEntry[], settings: CommandSettings = {}) {\n const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0]\n const seen = new Set<string>()\n const lines: string[] = []\n for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {\n const key = entry.name.toLowerCase()\n if (entry.hidden || seen.has(key)) continue\n seen.add(key)\n const prefix = commandPrefix(entry, botPrefix)\n const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join('、')\n lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ''}${entry.description ? ` —— ${entry.description}` : ''}`)\n }\n return [settings.helpTitle || DEFAULT_HELP_TITLE, ...lines].join('\\n')\n}\n\n/** Names (and aliases) that more than one source registers on the same bot. */\nexport function commandConflicts(entries: CommandEntry[]) {\n const owners = new Map<string, CommandEntry[]>()\n for (const entry of entries) {\n for (const name of new Set([entry.name, ...(entry.aliases ?? [])].filter(Boolean).map((item) => item.toLowerCase()))) {\n const key = `${entry.botId}|${name}`\n owners.set(key, [...(owners.get(key) ?? []), entry])\n }\n }\n return [...owners.entries()]\n .filter(([, list]) => list.length > 1)\n // The first entry is the one that answers: highest priority, then registration order.\n .map(([key, list]) => ({ botId: key.split('|')[0], name: key.slice(key.indexOf('|') + 1), entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)) }))\n}\n"],"mappings":";AAgFA,MAAa,mBAAmB,CAAC,GAAG;AACpC,MAAa,qBAAqB;;AAalC,SAAgB,aAAa,MAAc,WAAqB,kBAA4D;CAC1H,MAAM,UAAU,KAAK,KAAK;CAC1B,MAAM,SAAS,CAAC,GAAG,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,SAAS,QAAQ,WAAW,IAAI,CAAC;CACxH,IAAI,WAAW,KAAA,GAAW;CAC1B,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAM;CACxC,MAAM,QAAQ,2BAA2B,KAAK,IAAI;CAClD,IAAI,CAAC,O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,iBAAiB,SAAyB;CACxD,MAAM,yBAAS,IAAI,IAA4B;CAC/C,KAAK,MAAM,SAAS,SAClB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,MAAM,MAAM,GAAI,MAAM,WAAW,CAAC,CAAE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC,GAAG;EACpH,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG;EAC9B,OAAO,IAAI,KAAK,CAAC,GAAI,OAAO,IAAI,GAAG,KAAK,CAAC,GAAI,KAAK,CAAC;CACrD;CAEF,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,QAAQ,GAAG,UAAU,KAAK,SAAS,CAAC,CAAC,CAErC,KAAK,CAAC,KAAK,WAAW;EAAE,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EAAI,MAAM,IAAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;EAAG,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAAE,EAAE;AACzK"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { BotManager } from './manager'\
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { BotManager } from './manager'\n\nexport * from './archive'\nexport * from './bot'\nexport * from './commands'\nexport * from './manager'\nexport * from './types'\n\nexport default BotManager\n"],"mappings":";;;;;;AAQA,IAAA,cAAe"}
|
package/dist/manager.d.ts
CHANGED
|
@@ -119,6 +119,10 @@ export declare class BotManager extends Service {
|
|
|
119
119
|
bot(id: string): Bot | undefined;
|
|
120
120
|
status(id: string): BotStatusInfo;
|
|
121
121
|
private emitStatus;
|
|
122
|
+
/** Moves adapter secrets an older version saved in plain text to .env, once the adapter is known. */
|
|
123
|
+
private secureRecords;
|
|
124
|
+
/** Puts the secrets of an adapter config into .env and returns the config with `${NAME}` references. */
|
|
125
|
+
private secureConfig;
|
|
122
126
|
private redact;
|
|
123
127
|
describe(record: BotRecord): {
|
|
124
128
|
connection: BotConnectionInfo | undefined;
|
package/dist/manager.js
CHANGED
|
@@ -2,7 +2,7 @@ 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, fiberError, fiberStatus, isMasked, logTag, mask, messageType, pluginSchema, randomId, segmentsToText, toJsonSchema, validatePluginConfig, z } from "@mushinjs/core";
|
|
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";
|
|
6
6
|
// src/manager.ts
|
|
7
7
|
const STORAGE_KEY = "bots";
|
|
8
8
|
const BUFFER_SIZE = 500;
|
|
@@ -106,6 +106,7 @@ var BotManager = class extends Service {
|
|
|
106
106
|
if (this.adapterStore.has(adapter.id)) throw new Error(`adapter "${adapter.id}" is already defined`);
|
|
107
107
|
this.adapterStore.set(adapter.id, adapter);
|
|
108
108
|
this.logger.info("adapter %s is available", adapter.id);
|
|
109
|
+
this.secureRecords(adapter).catch((error) => this.logger.warn("could not move the %s secrets of bots to .env: %s", adapter.id, error));
|
|
109
110
|
for (const record of this.records) {
|
|
110
111
|
if (this.home.offline) break;
|
|
111
112
|
if (record.enabled && record.adapter.type === adapter.id && !this.runtimes.has(record.id)) this.startSafely(record.id);
|
|
@@ -167,10 +168,36 @@ var BotManager = class extends Service {
|
|
|
167
168
|
emitStatus(id) {
|
|
168
169
|
this.home.emit("bots/status", this.status(id));
|
|
169
170
|
}
|
|
171
|
+
/** Moves adapter secrets an older version saved in plain text to .env, once the adapter is known. */
|
|
172
|
+
async secureRecords(adapter) {
|
|
173
|
+
let moved = 0;
|
|
174
|
+
for (const record of this.records) {
|
|
175
|
+
if (record.adapter.type !== adapter.id) continue;
|
|
176
|
+
const result = await this.secureConfig(adapter.id, record, record.adapter.config);
|
|
177
|
+
record.adapter = {
|
|
178
|
+
...record.adapter,
|
|
179
|
+
config: result.config
|
|
180
|
+
};
|
|
181
|
+
moved += result.moved.length;
|
|
182
|
+
}
|
|
183
|
+
if (moved) {
|
|
184
|
+
await this.save();
|
|
185
|
+
this.logger.info("moved %d %s bot secret(s) to .env", moved, adapter.id);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Puts the secrets of an adapter config into .env and returns the config with `${NAME}` references. */
|
|
189
|
+
secureConfig(type, record, config) {
|
|
190
|
+
const owner = /[A-Za-z0-9]/.test(record.name) ? record.name : record.id;
|
|
191
|
+
return this.home.storage.secrets.moveIn(config, {
|
|
192
|
+
keys: this.adapterStore.get(type)?.secrets ?? [],
|
|
193
|
+
name: ["bot", owner],
|
|
194
|
+
previous: record.adapter?.config
|
|
195
|
+
});
|
|
196
|
+
}
|
|
170
197
|
redact(record) {
|
|
171
198
|
const secrets = this.adapterStore.get(record.adapter.type)?.secrets ?? [];
|
|
172
199
|
const config = { ...record.adapter.config };
|
|
173
|
-
for (const key of secrets) if (typeof config[key] === "string" && config[key]) config[key] = mask(config[key]);
|
|
200
|
+
for (const key of secrets) if (typeof config[key] === "string" && config[key] && envReference(config[key]) === void 0) config[key] = mask(config[key]);
|
|
174
201
|
return {
|
|
175
202
|
...record,
|
|
176
203
|
adapter: {
|
|
@@ -216,7 +243,10 @@ var BotManager = class extends Service {
|
|
|
216
243
|
enabled: input.enabled ?? true,
|
|
217
244
|
adapter: {
|
|
218
245
|
type: input.adapter.type,
|
|
219
|
-
config: this.
|
|
246
|
+
config: (await this.secureConfig(input.adapter.type, {
|
|
247
|
+
id,
|
|
248
|
+
name: input.name
|
|
249
|
+
}, this.validateAdapter(input.adapter.type, input.adapter.config))).config
|
|
220
250
|
},
|
|
221
251
|
plugins: [],
|
|
222
252
|
provider: input.provider,
|
|
@@ -252,7 +282,7 @@ var BotManager = class extends Service {
|
|
|
252
282
|
for (const key of secrets) if (isMasked(config[key])) config[key] = record.adapter.config[key];
|
|
253
283
|
record.adapter = {
|
|
254
284
|
type: patch.adapter.type,
|
|
255
|
-
config: this.validateAdapter(patch.adapter.type, config)
|
|
285
|
+
config: (await this.secureConfig(patch.adapter.type, record, this.validateAdapter(patch.adapter.type, config))).config
|
|
256
286
|
};
|
|
257
287
|
}
|
|
258
288
|
await this.save();
|
|
@@ -371,8 +401,8 @@ var BotManager = class extends Service {
|
|
|
371
401
|
record,
|
|
372
402
|
hooks
|
|
373
403
|
});
|
|
374
|
-
ctx.plugin(adapter.plugin, record.adapter.config);
|
|
375
|
-
for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, entry.config));
|
|
404
|
+
ctx.plugin(adapter.plugin, this.home.storage.secrets.resolveAll(record.adapter.config, adapter.secrets ?? []));
|
|
405
|
+
for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, resolveEnvReferences(entry.config)));
|
|
376
406
|
}
|
|
377
407
|
});
|
|
378
408
|
await runtime.fiber;
|
|
@@ -504,7 +534,7 @@ var BotManager = class extends Service {
|
|
|
504
534
|
if (!runtime?.ctx) return;
|
|
505
535
|
runtime.plugins.get(entry.package)?.dispose();
|
|
506
536
|
runtime.pluginErrors.delete(entry.package);
|
|
507
|
-
runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, entry.config));
|
|
537
|
+
runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, resolveEnvReferences(entry.config)));
|
|
508
538
|
}
|
|
509
539
|
/** Adds commands to every bot's list. Removed when the calling plugin unloads. */
|
|
510
540
|
defineCommands(provider) {
|
package/dist/manager.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import {\r\n type ChannelInfo, Context, currentPackageName, describeMissing, dependencyReport, type LogTag, type MissingDependency, logTag, type Exporter, type Fiber, fiberError, fiberStatus, isMasked, Logger, mask, type Message,\r\n type MessageRecord, messageType, MushinError, type Plugin, type Provenance, pluginSchema, randomId, type Segment, segmentsToText, Service, toJsonSchema,\r\n type UsageEvent, validatePluginConfig, z,\r\n} from '@mushinjs/core'\r\nimport type {} from '@mushinjs/plugin-storage'\r\nimport { MessageArchive } from './archive'\r\nimport { Bot, type BotHooks, byteSize, type Session } from './bot'\r\nimport { type CommandArg, type CommandDef, type CommandEntry, commandConflicts, type CommandSettings, commandMatches, commandUsage, DEFAULT_PREFIXES, helpText, parseArgs, requiredRole, splitCommand } from './commands'\r\nimport { type AdapterType, type BotPluginEntry, type BotRecord, type BotStatus, isSandbox, type PermissionProvider, roleAtLeast } from './types'\r\n\r\ndeclare module '@mushinjs/core' {\r\n interface Context {\r\n bots: BotManager\r\n bot: Bot\r\n }\r\n\r\n interface Events {\r\n 'bots/changed'(): void\r\n 'bots/status'(status: BotStatusInfo): void\r\n 'bots/message'(record: MessageRecord): void\r\n 'bots/log'(line: BotLogLine): void\r\n 'bots/command'(call: CommandCall): void\r\n }\r\n}\r\n\r\n/** One log line written inside a bot's context: its adapter, its plugins, or the bot service itself. */\r\nexport interface BotLogLine {\r\n botId: string\r\n sn: number\r\n ts: number\r\n type: string\r\n name: string\r\n tag: LogTag\r\n text: string\r\n}\r\n\r\n/** A message ran a registered command. */\r\nexport interface CommandCall {\r\n botId: string\r\n name: string\r\n source: CommandEntry['source']\r\n userId: string\r\n channel: ChannelInfo\r\n at: number\r\n}\r\n\r\nexport interface RunCommandInput {\r\n bot: string\r\n command: string\r\n target?: 'master' | 'group'\r\n group?: string\r\n user?: string\r\n}\r\n\r\n/** Lists commands a plugin provides on a bot, e.g. the command nodes of the flows attached to it. */\r\nexport type CommandProvider = (botId: string) => CommandEntry[]\r\n\r\n/** A command an app plugin answers on every bot, or on the bots `bots` picks. */\r\ninterface AppCommand {\r\n def: CommandDef\r\n plugin: string\r\n handler: (session: Session) => Promise<unknown> | unknown\r\n bots?: (botId: string) => boolean\r\n}\r\n\r\nexport interface BotStatusInfo {\r\n id: string\r\n status: BotStatus\r\n error?: string\r\n selfId?: string\r\n selfName?: string\r\n selfAvatar?: string\r\n}\r\n\r\ninterface Runtime {\r\n fiber?: Fiber\r\n ctx?: Context\r\n bot?: Bot\r\n plugins: Map<string, Fiber>\r\n pluginErrors: Map<string, string>\r\n /** Last connection status written to the global log. */\r\n logged?: BotStatus\r\n}\r\n\r\nconst STORAGE_KEY = 'bots'\r\nconst BUFFER_SIZE = 500\r\nconst LOG_BUFFER_SIZE = 500\r\n// Bot logs include debug lines (e.g. why llm-chat skipped a message); the main log stream does not.\r\nconst LOG_LEVEL_DEBUG = 3\r\nconst plainExporter: Exporter = { colors: false, export() {} }\r\n\r\nconst adapterInput = z.object({\r\n type: z.string().describe('Adapter type id from bots.adapters, e.g. \"onebot\"'),\r\n config: z.record(z.string(), z.any()).describe('Adapter config matching the schema from bots.adapters'),\r\n})\r\n\r\n/** Messages whose costs are kept; older ones are forgotten. */\r\nconst USAGE_MESSAGES = 2000\r\n/** A runaway loop on one message stops being recorded after this many costs. */\r\nconst USAGE_EVENTS_PER_MESSAGE = 200\r\n\r\n/** What handling one message cost; see `bots.usage`. */\r\nexport interface MessageUsage {\r\n events: UsageEvent[]\r\n /** Size on the wire, roughly. */\r\n bytes?: number\r\n /** For a sent message: how long the platform took to accept it. */\r\n sendMs?: number\r\n /** For a sent message: the incoming message being handled when it was sent. */\r\n cause?: string\r\n /** For an incoming message: what was sent while handling it. */\r\n replies: string[]\r\n}\r\n\r\nconst idInput = z.object({ id: z.string().describe('Bot id from bots.list') })\r\nconst commandSettingsInput = z.object({\r\n prefixes: z.array(z.string().min(1)).optional().describe('Command prefixes; default [\"/\"]'),\r\n help: z.boolean().optional().describe('Answer /help with the list of commands; on unless false'),\r\n helpTitle: z.string().optional().describe('First line of the /help menu'),\r\n admins: z.array(z.string()).optional().describe('Deprecated: admins now live in the permissions plugin (permissions.update)'),\r\n helpByRole: z.boolean().optional().describe('/help lists only the commands the asker may run'),\r\n})\r\n\r\n/** Answers `/help` when nothing else on the bot registers a command called help. */\r\nconst HELP_COMMAND = { name: 'help', description: '列出所有指令' }\r\n\r\nconst pluginInput = idInput.extend({ package: z.string().describe('Bot plugin package name from bots.plugins.list') })\r\n\r\n/**\r\n * Owns bot records and runs each enabled bot in its own isolated context:\r\n * the `bot` service, the adapter connection and the bot's plugins live there.\r\n */\r\nexport class BotManager extends Service {\r\n static inject = ['storage', 'actions', 'manager']\r\n\r\n private home: Context\r\n private records: BotRecord[] = []\r\n private adapterStore = new Map<string, AdapterType>()\r\n private runtimes = new Map<string, Runtime>()\r\n private startErrors = new Map<string, string>()\r\n private buffers = new Map<string, MessageRecord[]>()\r\n /** Messages in the database, when the database plugin runs. */\r\n private archive?: MessageArchive\r\n /** Runtime fiber of each running bot, to attribute log lines to the bot that wrote them. */\r\n private runtimeFibers = new Map<Fiber, string>()\r\n private logs = new Map<string, BotLogLine[]>()\r\n /** Sequence numbers of recent bot log lines; still recognized after the bot that wrote them stops. */\r\n private botLogSns = new Set<number>()\r\n private commandProviders = new Set<CommandProvider>()\r\n private appCommands = new Set<AppCommand>()\r\n private permissionProvider?: PermissionProvider\r\n\r\n constructor(ctx: Context) {\r\n super(ctx, 'bots')\r\n this.home = ctx\r\n }\r\n\r\n /**\r\n * Bot lifecycle lines for the global log, tagged `bot` in the dashboard. Written from the manager's\r\n * own context, so they stay out of the bot's log, which has its own lines from inside the bot.\r\n */\r\n private get logger() {\r\n return this.home.logger('bot')\r\n }\r\n\r\n async *[Service.init]() {\r\n const stored = await this.home.storage.get<{ bots: BotRecord[] }>(STORAGE_KEY)\r\n this.records = stored?.bots ?? []\r\n for (const record of this.records) {\r\n for (const plugin of record.plugins ?? []) plugin.package = currentPackageName(plugin.package)\r\n }\r\n this.logger.info('loaded %d bot(s)', this.records.length)\r\n yield this.home.logger.exporter({\r\n colors: false,\r\n levels: { default: LOG_LEVEL_DEBUG },\r\n export: (message) => this.captureLog(message),\r\n })\r\n yield* this.defineActions()\r\n this.home.inject(['model', 'database'], async (ctx) => {\r\n const archive = new MessageArchive(ctx, (error) => this.logger.warn('saving a message to the database failed: %s', error))\r\n this.archive = archive\r\n ctx.effect(() => () => {\r\n if (this.archive === archive) this.archive = undefined\r\n }, 'bots message archive')\r\n try {\r\n const imported = await archive.start()\r\n if (imported) this.logger.info('imported %d message(s) from the message logs into the database', imported)\r\n } catch (error) {\r\n this.logger.warn('importing the message logs into the database failed: %s', error)\r\n if (this.archive === archive) this.archive = undefined\r\n }\r\n })\r\n if (this.home.offline) this.logger.info('offline: bots are not started')\r\n for (const record of this.home.offline ? [] : this.records) {\r\n if (record.enabled && this.adapterStore.has(record.adapter.type)) this.startSafely(record.id)\r\n }\r\n }\r\n\r\n // ---- adapters ----\r\n\r\n /** Registers an adapter type. Bots using it start when it loads and stop when it unloads. */\r\n defineAdapter<C>(adapter: AdapterType<C>) {\r\n const ctx = this.ctx\r\n return ctx.effect(() => {\r\n if (this.adapterStore.has(adapter.id)) throw new Error(`adapter \"${adapter.id}\" is already defined`)\r\n this.adapterStore.set(adapter.id, adapter)\r\n this.logger.info('adapter %s is available', adapter.id)\r\n for (const record of this.records) {\r\n if (this.home.offline) break\r\n if (record.enabled && record.adapter.type === adapter.id && !this.runtimes.has(record.id)) {\r\n this.startSafely(record.id)\r\n }\r\n }\r\n ctx.emit('bots/changed')\r\n return async () => {\r\n this.adapterStore.delete(adapter.id)\r\n this.logger.info('adapter %s was removed', adapter.id)\r\n for (const record of this.records) {\r\n if (record.adapter.type !== adapter.id || !this.runtimes.has(record.id)) continue\r\n await this.stopRuntime(record.id)\r\n this.startErrors.set(record.id, `Adapter \"${adapter.id}\" was unloaded`)\r\n this.emitStatus(record.id)\r\n }\r\n ctx.emit('bots/changed')\r\n }\r\n }, `bots.defineAdapter(${adapter.id})`)\r\n }\r\n\r\n adapters() {\r\n return [...this.adapterStore.values()].map((adapter) => ({\r\n id: adapter.id,\r\n displayName: adapter.displayName,\r\n configSchema: toJsonSchema(adapter.config),\r\n secrets: adapter.secrets ?? [],\r\n segments: adapter.segments,\r\n groupRoles: !!adapter.groupRoles,\r\n avatars: adapter.avatars ?? {},\r\n }))\r\n }\r\n\r\n /** Adapters that can send every segment in a message. */\r\n platformsFor(segments: Segment[]) {\r\n return [...this.adapterStore.values()]\r\n .filter((adapter) => segments.every((s) => adapter.segments.includes(s.type)))\r\n .map((adapter) => adapter.id)\r\n }\r\n\r\n // ---- records ----\r\n\r\n get(id: string) {\r\n const record = this.records.find((item) => item.id === id)\r\n if (!record) throw new MushinError('not_found', `No bot with id \"${id}\"`)\r\n return record\r\n }\r\n\r\n bot(id: string) {\r\n return this.runtimes.get(id)?.bot\r\n }\r\n\r\n status(id: string): BotStatusInfo {\r\n const bot = this.bot(id)\r\n if (bot) return { id, status: bot.status, error: bot.error, selfId: bot.selfId, selfName: bot.selfName, selfAvatar: bot.selfAvatar }\r\n const error = this.startErrors.get(id)\r\n return { id, status: error ? 'error' : 'offline', error }\r\n }\r\n\r\n private emitStatus(id: string) {\r\n this.home.emit('bots/status', this.status(id))\r\n }\r\n\r\n private redact(record: BotRecord) {\r\n const secrets = this.adapterStore.get(record.adapter.type)?.secrets ?? []\r\n const config = { ...record.adapter.config }\r\n for (const key of secrets) {\r\n if (typeof config[key] === 'string' && config[key]) config[key] = mask(config[key])\r\n }\r\n return { ...record, adapter: { ...record.adapter, config } }\r\n }\r\n\r\n describe(record: BotRecord) {\r\n return { ...this.redact(record), ...this.status(record.id), connection: this.connectionOf(record) }\r\n }\r\n\r\n private connectionOf(record: BotRecord) {\r\n try {\r\n return this.adapterStore.get(record.adapter.type)?.describe?.(record.adapter.config, record.id)\r\n } catch {}\r\n }\r\n\r\n list() {\r\n return this.records.map((record) => this.describe(record))\r\n }\r\n\r\n private async save() {\r\n await this.home.storage.set(STORAGE_KEY, { bots: this.records })\r\n this.home.emit('bots/changed')\r\n }\r\n\r\n private validateAdapter(type: string, config: unknown) {\r\n const adapter = this.adapterStore.get(type)\r\n if (!adapter) {\r\n const known = [...this.adapterStore.keys()].join(', ') || 'none'\r\n throw new MushinError('invalid_input', `Unknown adapter \"${type}\". Loaded adapters: ${known}`)\r\n }\r\n const result = adapter.config.safeParse(config)\r\n if (!result.success) throw new MushinError('invalid_input', z.prettifyError(result.error), result.error.issues)\r\n return result.data as Record<string, any>\r\n }\r\n\r\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 }) {\r\n const id = randomId()\r\n const record: BotRecord = {\r\n id,\r\n name: input.name,\r\n enabled: input.enabled ?? true,\r\n adapter: { type: input.adapter.type, config: this.validateAdapter(input.adapter.type, input.adapter.config) },\r\n plugins: [],\r\n provider: input.provider,\r\n ...(input.commands ? { commands: input.commands } : {}),\r\n createdAt: Date.now(),\r\n }\r\n for (const item of input.plugins ?? []) {\r\n const plugin = await this.loadBotPlugin(item.package)\r\n validatePluginConfig(plugin, item.config ?? {})\r\n record.plugins.push({ package: item.package, enabled: true, config: item.config ?? {} })\r\n }\r\n this.records.push(record)\r\n await this.save()\r\n this.logger.info('created bot %s', this.label(record))\r\n if (record.enabled) await this.start(id).catch(() => {})\r\n return this.describe(record)\r\n }\r\n\r\n async update(id: string, patch: { name?: string; adapter?: { type: string; config: Record<string, any> }; provider?: string | null; commands?: CommandSettings }) {\r\n const record = this.get(id)\r\n if (patch.commands !== undefined) record.commands = { ...record.commands, ...patch.commands }\r\n if (patch.name !== undefined) record.name = patch.name\r\n if (patch.provider !== undefined) record.provider = patch.provider ?? undefined\r\n if (patch.adapter) {\r\n const secrets = this.adapterStore.get(patch.adapter.type)?.secrets ?? []\r\n const config = { ...patch.adapter.config }\r\n for (const key of secrets) {\r\n if (isMasked(config[key])) config[key] = record.adapter.config[key]\r\n }\r\n record.adapter = { type: patch.adapter.type, config: this.validateAdapter(patch.adapter.type, config) }\r\n }\r\n await this.save()\r\n this.logger.info('updated bot %s', this.label(record))\r\n // Command settings are read on every message, so changing only them needs no restart.\r\n const restart = patch.name !== undefined || patch.adapter !== undefined || patch.provider !== undefined\r\n if (record.enabled && restart) await this.start(id).catch(() => {})\r\n return this.describe(record)\r\n }\r\n\r\n async remove(id: string) {\r\n const record = this.get(id)\r\n await this.stopRuntime(id)\r\n this.records = this.records.filter((item) => item !== record)\r\n this.buffers.delete(id)\r\n this.logs.delete(id)\r\n this.startErrors.delete(id)\r\n await this.save()\r\n this.logger.info('deleted bot %s', this.label(record))\r\n return { deleted: id }\r\n }\r\n\r\n // ---- runtimes ----\r\n\r\n private startSafely(id: string) {\r\n this.start(id).catch((error) => this.logger.warn('failed to start bot %s: %s', id, error))\r\n }\r\n\r\n async start(id: string) {\r\n const record = this.get(id)\r\n await this.stopRuntime(id)\r\n this.startErrors.delete(id)\r\n const adapter = this.adapterStore.get(record.adapter.type)\r\n if (!adapter) {\r\n const message = `Adapter \"${record.adapter.type}\" is not loaded; enable its plugin`\r\n this.startErrors.set(id, message)\r\n this.emitStatus(id)\r\n this.logger.warn('cannot start bot %s: %s', this.label(record), message)\r\n throw new MushinError('unavailable', message)\r\n }\r\n\r\n const runtime: Runtime = { plugins: new Map(), pluginErrors: new Map() }\r\n const loaded: { entry: BotPluginEntry; plugin: Plugin }[] = []\r\n for (const entry of record.plugins) {\r\n if (!entry.enabled) continue\r\n try {\r\n loaded.push({ entry, plugin: await this.loadBotPlugin(entry.package) })\r\n } catch (error) {\r\n runtime.pluginErrors.set(entry.package, error instanceof Error ? error.message : String(error))\r\n }\r\n }\r\n\r\n const hooks: BotHooks = {\r\n record: (partial) => this.record(partial),\r\n status: (bot) => {\r\n runtime.bot = bot\r\n // Connecting is left to the bot's own log, so a reconnect loop writes one error line here, not one per try.\r\n if (bot.status !== 'connecting' && bot.status !== runtime.logged && (runtime.logged || bot.status !== 'offline')) {\r\n runtime.logged = bot.status\r\n if (bot.status === 'error') this.logger.warn('bot %s: error (%s)', this.label(record), bot.error ?? 'no details')\r\n else this.logger.info('bot %s is %s', this.label(record), bot.status)\r\n }\r\n this.emitStatus(id)\r\n },\r\n commands: (bot) => this.commands(bot.id),\r\n commandCalled: (bot, entry, session) => {\r\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() })\r\n },\r\n builtinCommand: (bot, entry, session) => {\r\n if (entry.name !== HELP_COMMAND.name) return\r\n let entries = this.commands(bot.id)\r\n if (bot.record.commands?.helpByRole) {\r\n const role = session.role()\r\n entries = entries.filter((item) => {\r\n const required = requiredRole(item)\r\n return !required || roleAtLeast(role, required)\r\n })\r\n }\r\n return helpText(entries, bot.record.commands)\r\n },\r\n roleOf: (bot, userId) => this.permissionProvider?.roleOf(bot.id, userId),\r\n appCommand: (bot, entry) => this.appCommandFor(bot.id, entry)?.handler,\r\n usageScope: (bot, message) => {\r\n const entry = this.usageEntry(bot.id, message.id, true)!\r\n entry.bytes = byteSize(message.segments)\r\n return {\r\n botId: bot.id,\r\n messageId: message.id,\r\n report: (event) => {\r\n const target = this.usageEntry(bot.id, message.id, true)!\r\n if (target.events.length < USAGE_EVENTS_PER_MESSAGE) target.events.push(event)\r\n },\r\n }\r\n },\r\n sent: (bot, message, transfer) => {\r\n const entry = this.usageEntry(bot.id, message.id, true)!\r\n Object.assign(entry, { bytes: transfer.bytes }, transfer.ms !== undefined ? { sendMs: transfer.ms } : {}, transfer.cause ? { cause: transfer.cause } : {})\r\n if (transfer.cause) this.usageEntry(bot.id, transfer.cause)?.replies.push(message.id)\r\n },\r\n }\r\n this.runtimes.set(id, runtime)\r\n runtime.fiber = this.home.isolate('bot').plugin({\r\n name: `bot:${record.name}`,\r\n apply: (ctx: Context) => {\r\n runtime.ctx = ctx\r\n this.runtimeFibers.set(ctx.fiber, id)\r\n ctx.effect(() => () => this.runtimeFibers.delete(ctx.fiber), 'bot log attribution')\r\n const enabled = loaded.map(({ entry }) => entry.package.replace(/^@mushinjs\\/bot-plugin-/, ''))\r\n ctx.logger('bot').info('starting with the %s adapter; plugins: %s', record.adapter.type, enabled.join(', ') || 'none')\r\n for (const [name, error] of runtime.pluginErrors) ctx.logger('bot').warn('plugin %s did not load: %s', name, error)\r\n ctx.plugin(Bot, { record, hooks })\r\n ctx.plugin(adapter.plugin, record.adapter.config)\r\n for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, entry.config))\r\n },\r\n })\r\n await runtime.fiber\r\n runtime.bot = runtime.ctx?.get('bot') ?? runtime.bot\r\n const error = fiberError(runtime.fiber)\r\n if (error) this.logger.warn('bot %s failed to start: %s', this.label(record), error)\r\n else this.logger.info('started bot %s with the %s adapter', this.label(record), record.adapter.type)\r\n this.emitStatus(id)\r\n return this.status(id)\r\n }\r\n\r\n private async stopRuntime(id: string) {\r\n const runtime = this.runtimes.get(id)\r\n if (!runtime) return\r\n this.runtimes.delete(id)\r\n await runtime.fiber?.dispose()\r\n this.logger.info('stopped bot %s', this.label(this.records.find((item) => item.id === id) ?? id))\r\n this.emitStatus(id)\r\n }\r\n\r\n async setEnabled(id: string, enabled: boolean) {\r\n const record = this.get(id)\r\n record.enabled = enabled\r\n await this.save()\r\n if (enabled) return this.start(id)\r\n await this.stopRuntime(id)\r\n return this.status(id)\r\n }\r\n\r\n /** Log lines name a bot by its id; the dashboard links it to the bot. */\r\n private label(record: BotRecord | string) {\r\n return typeof record === 'string' ? record : record.id\r\n }\r\n\r\n // ---- bot plugins ----\r\n\r\n async loadBotPlugin(name: string) {\r\n const entry = await this.home.manager.findPackage(name)\r\n if (!entry) throw new MushinError('not_found', `Bot plugin \"${name}\" is not installed`)\r\n if (entry.manifest.kind !== 'bot') throw new MushinError('invalid_input', `\"${name}\" is an app plugin, not a bot plugin`)\r\n return this.home.manager.loadPlugin(name)\r\n }\r\n\r\n async plugins(id: string) {\r\n const record = this.get(id)\r\n const runtime = this.runtimes.get(id)\r\n const graph = await this.home.manager.graph()\r\n const catalog = graph.catalog.filter((entry) => entry.manifest.kind === 'bot')\r\n return Promise.all(catalog.map(async (entry) => {\r\n const configured = record.plugins.find((item) => item.package === entry.package)\r\n let configSchema\r\n try {\r\n configSchema = pluginSchema(await this.home.manager.loadPlugin(entry.package))\r\n } catch {}\r\n const fiber = runtime?.plugins.get(entry.package)\r\n const report = dependencyReport(graph, entry.package)\r\n const missing = this.missingApps(report.requires)\r\n let status: string = configured?.enabled ? (runtime ? fiberStatus(fiber) : 'disabled') : 'disabled'\r\n if (status === 'pending' && missing.length) status = 'missing'\r\n return {\r\n package: entry.package,\r\n version: entry.version,\r\n manifest: entry.manifest,\r\n enabled: !!configured?.enabled,\r\n config: configured?.config ?? {},\r\n configSchema,\r\n status,\r\n error: runtime?.pluginErrors.get(entry.package) ?? (status === 'missing' ? describeMissing(missing) : fiberError(fiber)),\r\n dependencies: { requires: report.requires, optional: report.optional },\r\n ...(missing.length ? { missing } : {}),\r\n }\r\n }))\r\n }\r\n\r\n /** Required app plugins that are not installed, do not fit or are disabled. */\r\n private missingApps(requires: ReturnType<typeof dependencyReport>['requires']): MissingDependency[] {\r\n return requires\r\n .filter((dep) => dep.problem === 'not-installed' || dep.problem === 'version' || dep.problem === 'disabled')\r\n .map((dep) => ({ package: dep.package, range: dep.range, reason: dep.problem as MissingDependency['reason'], ...(dep.version ? { version: dep.version } : {}) }))\r\n }\r\n\r\n async enablePlugin(id: string, name: string, config?: Record<string, any>) {\r\n const record = this.get(id)\r\n const plugin = await this.loadBotPlugin(name)\r\n const missing = this.missingApps(dependencyReport(await this.home.manager.graph(), name).requires)\r\n if (missing.length) {\r\n throw new MushinError('unavailable', `${name} cannot run on this bot yet. ${describeMissing(missing)}; enable them on the plugins page`, { missing })\r\n }\r\n let entry = record.plugins.find((item) => item.package === name)\r\n const nextConfig = config ?? entry?.config ?? {}\r\n validatePluginConfig(plugin, nextConfig)\r\n if (!entry) {\r\n entry = { package: name, enabled: true, config: nextConfig }\r\n record.plugins.push(entry)\r\n }\r\n entry.enabled = true\r\n entry.config = nextConfig\r\n await this.save()\r\n this.logger.info('enabled plugin %s on bot %s', name, this.label(record))\r\n this.reloadPlugin(id, entry, plugin)\r\n return this.plugins(id).then((list) => list.find((item) => item.package === name))\r\n }\r\n\r\n async disablePlugin(id: string, name: string) {\r\n const record = this.get(id)\r\n const entry = record.plugins.find((item) => item.package === name)\r\n if (!entry) throw new MushinError('not_found', `${name} is not configured on this bot`)\r\n entry.enabled = false\r\n await this.save()\r\n this.logger.info('disabled plugin %s on bot %s', name, this.label(record))\r\n const runtime = this.runtimes.get(id)\r\n const fiber = runtime?.plugins.get(name)\r\n runtime?.plugins.delete(name)\r\n await fiber?.dispose()\r\n return this.plugins(id).then((list) => list.find((item) => item.package === name))\r\n }\r\n\r\n async configurePlugin(id: string, name: string, config: Record<string, any>) {\r\n const record = this.get(id)\r\n const entry = record.plugins.find((item) => item.package === name)\r\n if (!entry) return this.enablePlugin(id, name, config)\r\n const plugin = await this.loadBotPlugin(name)\r\n validatePluginConfig(plugin, config)\r\n entry.config = config\r\n await this.save()\r\n this.logger.info('config of plugin %s on bot %s changed', name, this.label(record))\r\n if (entry.enabled) this.reloadPlugin(id, entry, plugin)\r\n return this.plugins(id).then((list) => list.find((item) => item.package === name))\r\n }\r\n\r\n private reloadPlugin(id: string, entry: BotPluginEntry, plugin: Plugin) {\r\n const runtime = this.runtimes.get(id)\r\n if (!runtime?.ctx) return\r\n runtime.plugins.get(entry.package)?.dispose()\r\n runtime.pluginErrors.delete(entry.package)\r\n runtime.plugins.set(entry.package, runtime.ctx.plugin(plugin, entry.config))\r\n }\r\n\r\n // ---- commands ----\r\n\r\n /** Adds commands to every bot's list. Removed when the calling plugin unloads. */\r\n defineCommands(provider: CommandProvider) {\r\n return this.ctx.effect(() => {\r\n this.commandProviders.add(provider)\r\n return () => this.commandProviders.delete(provider)\r\n }, 'bots.defineCommands()')\r\n }\r\n\r\n /**\r\n * Answers a command on every bot (or those `bots` picks) from an app plugin, such as `/persona`.\r\n * It answers after flows, like `/help`, and shows in each bot's command list.\r\n */\r\n defineCommand(def: CommandDef, handler: AppCommand['handler'], options: { bots?: (botId: string) => boolean } = {}) {\r\n const ctx = this.ctx\r\n const command: AppCommand = { def, plugin: ctx.fiber.name, handler, bots: options.bots }\r\n return ctx.effect(() => {\r\n this.appCommands.add(command)\r\n return () => this.appCommands.delete(command)\r\n }, `bots.defineCommand(${def.name})`)\r\n }\r\n\r\n /** The app plugin command behind a command entry, if an app plugin answers it. */\r\n appCommandFor(botId: string, entry: CommandEntry) {\r\n if (entry.source.kind !== 'plugin') return\r\n return [...this.appCommands].find((item) => item.plugin === entry.source.id && commandMatches(item.def, entry.name) && (item.bots?.(botId) ?? true))\r\n }\r\n\r\n /** Lets the permissions plugin say who is master, admin or user on each bot. */\r\n usePermissions(provider: PermissionProvider) {\r\n return this.ctx.effect(() => {\r\n this.permissionProvider = provider\r\n return () => {\r\n if (this.permissionProvider === provider) this.permissionProvider = undefined\r\n }\r\n }, 'bots.usePermissions()')\r\n }\r\n\r\n /** A user's role on a bot; nothing when the permissions plugin is not running. */\r\n roleOf(botId: string, userId: string) {\r\n return this.permissionProvider?.roleOf(botId, userId)\r\n }\r\n\r\n /** Commands registered on one bot: from command providers such as flows, its plugins, and the built-in help. */\r\n commands(botId: string): CommandEntry[] {\r\n const record = this.records.find((item) => item.id === botId)\r\n if (!record) return []\r\n const entries: CommandEntry[] = []\r\n for (const provider of this.commandProviders) {\r\n try {\r\n entries.push(...provider(botId))\r\n } catch (error) {\r\n this.logger.warn('listing commands failed: %s', error)\r\n }\r\n }\r\n entries.push(...(this.runtimes.get(botId)?.bot?.localCommands() ?? []))\r\n for (const command of this.appCommands) {\r\n if (command.bots && !command.bots(botId)) continue\r\n entries.push({ ...command.def, botId, source: { kind: 'plugin', id: command.plugin, name: command.plugin } })\r\n }\r\n if (record.commands?.help !== false && !entries.some((entry) => commandMatches(entry, HELP_COMMAND.name))) {\r\n entries.push({ ...HELP_COMMAND, botId, source: { kind: 'builtin', id: 'help', name: 'help' } })\r\n }\r\n return entries\r\n }\r\n\r\n /** Commands of one bot or of every bot, with names that more than one source registers. */\r\n commandList(botId?: string) {\r\n if (botId) this.get(botId)\r\n const entries = (botId ? [botId] : this.records.map((record) => record.id)).flatMap((id) => this.commands(id))\r\n const conflicts = commandConflicts(entries).map((item) => ({ botId: item.botId, name: item.name, sources: item.entries.map((entry) => entry.source) }))\r\n return { commands: entries, conflicts }\r\n }\r\n\r\n /**\r\n * Runs a command as if a master sent it. With a target it really runs on the bot: in that group,\r\n * or in the master's private chat, and the replies are sent. Without one it only previews where\r\n * the message would go (through flows), so nothing is sent.\r\n */\r\n async runCommand(input: RunCommandInput, source?: Provenance) {\r\n const record = this.get(input.bot)\r\n const prefix = record.commands?.prefixes?.find(Boolean) ?? '/'\r\n const text = /^\\p{L}/u.test(input.command) && !input.command.startsWith(prefix) ? `${prefix}${input.command}` : input.command\r\n if (!input.target) {\r\n const flows = this.home.get('flows') as { route(botId: string, input: { text: string; role?: string }): Promise<unknown> } | undefined\r\n if (!flows) throw new MushinError('unavailable', 'Previewing a command needs the flows plugin; give a target to run it for real')\r\n return { simulated: true, text, route: await flows.route(record.id, { text, role: 'master' }) }\r\n }\r\n const bot = this.bot(record.id)\r\n if (!bot || this.status(record.id).status !== 'online') throw new MushinError('unavailable', `Bot \"${record.name}\" is not online`)\r\n const permissions = this.home.get('permissions') as { get(botId: string): { masters: string[] } } | undefined\r\n const userId = input.user ?? permissions?.get(record.id).masters[0]\r\n if (!userId) throw new MushinError('invalid_input', `Bot \"${record.name}\" has no master; add one with permissions.update or pass user`)\r\n if (input.target === 'group' && !input.group) throw new MushinError('invalid_input', 'Pass the group id to run a command in a group')\r\n const channel: ChannelInfo = input.target === 'group' ? { type: 'group', id: input.group! } : { type: 'private', id: userId }\r\n const replies: MessageRecord[] = []\r\n const collect = (message: MessageRecord) => {\r\n if (message.botId === record.id && message.direction === 'out' && message.channel.id === channel.id) replies.push(message)\r\n }\r\n const stop = this.home.on('bots/message', collect)\r\n try {\r\n await bot.receive({ channel, user: { id: userId }, segments: [{ type: 'text', data: { text } }] }, { source })\r\n } finally {\r\n stop()\r\n }\r\n return {\r\n simulated: false,\r\n text,\r\n channel,\r\n user: userId,\r\n replies: replies.map((reply) => segmentsToText(reply.segments)),\r\n }\r\n }\r\n\r\n // ---- logs ----\r\n\r\n /** Finds the bot whose context wrote a log message, by walking up from the writing fiber. */\r\n private botOf(message: Message) {\r\n let fiber = message.fiber?.deref()\r\n while (fiber) {\r\n const id = this.runtimeFibers.get(fiber)\r\n if (id) return id\r\n const parent = fiber.parent?.fiber\r\n if (!parent || parent === fiber) return\r\n fiber = parent\r\n }\r\n }\r\n\r\n /** True when a log line was written inside a bot; it belongs in that bot's log, not the global one. */\r\n isBotLog(message: Message) {\r\n return this.botLogSns.has(message.sn) || !!this.botOf(message)\r\n }\r\n\r\n private captureLog(message: Message) {\r\n const botId = this.botOf(message)\r\n if (!botId) return\r\n this.botLogSns.add(message.sn)\r\n // The global log buffer holds 1000 lines; remember a little more than that.\r\n if (this.botLogSns.size > 2000) this.botLogSns.delete(this.botLogSns.values().next().value!)\r\n const line: BotLogLine = {\r\n botId,\r\n sn: message.sn,\r\n ts: message.ts,\r\n type: message.type,\r\n name: message.name,\r\n tag: logTag(message.name),\r\n text: Logger.format(plainExporter, message),\r\n }\r\n let buffer = this.logs.get(botId)\r\n if (!buffer) this.logs.set(botId, buffer = [])\r\n buffer.push(line)\r\n if (buffer.length > LOG_BUFFER_SIZE) buffer.splice(0, buffer.length - LOG_BUFFER_SIZE)\r\n this.home.emit('bots/log', line)\r\n const day = new Date(line.ts).toISOString().slice(0, 10)\r\n this.home.storage.append(`logs/${botId}/${day}`, line).catch(() => {})\r\n }\r\n\r\n async logLines(id: string, limit = 200) {\r\n this.get(id)\r\n let buffer = this.logs.get(id)\r\n if (!buffer) {\r\n const day = new Date().toISOString().slice(0, 10)\r\n // Lines stored before tags existed get one from their logger name.\r\n buffer = (await this.home.storage.tail<BotLogLine>(`logs/${id}/${day}`, LOG_BUFFER_SIZE))\r\n .map((line) => (line.tag ? line : { ...line, tag: logTag(line.name) }))\r\n this.logs.set(id, buffer)\r\n }\r\n return buffer.slice(-limit)\r\n }\r\n\r\n // ---- messages ----\r\n\r\n /** Messages recorded since Mushin started, for the live conversation. */\r\n private recent = new WeakSet<MessageRecord>()\r\n /** What handling each recent message cost, in memory only; see `bots.usage`. */\r\n private usages = new Map<string, MessageUsage>()\r\n\r\n private usageEntry(botId: string, messageId: string, create = false) {\r\n const key = `${botId}:${messageId}`\r\n let entry = this.usages.get(key)\r\n if (!entry && create) {\r\n this.usages.set(key, entry = { events: [], replies: [] })\r\n if (this.usages.size > USAGE_MESSAGES) this.usages.delete(this.usages.keys().next().value!)\r\n }\r\n return entry\r\n }\r\n\r\n /** A message's costs, and for a reply the costs of the message it answered. */\r\n usage(botId: string, messageId: string) {\r\n const entry = this.usageEntry(botId, messageId)\r\n if (!entry) return null\r\n const cause = entry.cause ? this.usageEntry(botId, entry.cause) : undefined\r\n return { ...entry, ...(cause ? { causeEvents: cause.events } : {}) }\r\n }\r\n\r\n private record(partial: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord {\r\n const record: MessageRecord = {\r\n ...partial,\r\n id: randomId(8),\r\n type: messageType(partial.segments),\r\n platforms: this.platformsFor(partial.segments),\r\n }\r\n let buffer = this.buffers.get(record.botId)\r\n if (!buffer) this.buffers.set(record.botId, buffer = [])\r\n buffer.push(record)\r\n if (buffer.length > BUFFER_SIZE) buffer.splice(0, buffer.length - BUFFER_SIZE)\r\n const day = new Date(record.timestamp).toISOString().slice(0, 10)\r\n this.home.storage.append(`messages/${record.botId}/${day}`, record).catch((error) => {\r\n this.logger.warn('failed to write message log: %s', error)\r\n })\r\n this.recent.add(record)\r\n this.archive?.add(record)\r\n this.home.emit('bots/message', record)\r\n return record\r\n }\r\n\r\n /**\r\n * Recent messages of a bot, oldest first. With the database plugin, a channel's history and\r\n * older pages (`before`) come from the database; otherwise from today's log and memory.\r\n */\r\n async messages(id: string, options: { limit?: number; channel?: string; before?: number; sinceStart?: boolean } = {}) {\r\n this.get(id)\r\n const limit = options.limit ?? 100\r\n if (options.sinceStart) {\r\n const list = (this.buffers.get(id) ?? []).filter((record) => this.recent.has(record) && (!options.channel || record.channel.id === options.channel))\r\n return list.slice(-limit)\r\n }\r\n const archive = this.archive?.ready ? this.archive : undefined\r\n if (archive && (options.channel || options.before)) return archive.query(id, { ...options, limit })\r\n let buffer = this.buffers.get(id)\r\n if (!buffer) {\r\n const day = new Date().toISOString().slice(0, 10)\r\n buffer = archive\r\n ? await archive.query(id, { limit: BUFFER_SIZE })\r\n : await this.home.storage.tail<MessageRecord>(`messages/${id}/${day}`, BUFFER_SIZE)\r\n // Messages recorded while loading are already in the buffer that `record` made.\r\n const current = this.buffers.get(id)\r\n if (current) buffer = [...buffer.filter((item) => !current.some((record) => record.id === item.id)), ...current].slice(-BUFFER_SIZE)\r\n this.buffers.set(id, buffer)\r\n }\r\n if (options.before) buffer = buffer.filter((record) => record.timestamp < options.before!)\r\n const list = options.channel ? buffer.filter((record) => record.channel.id === options.channel) : buffer\r\n return list.slice(-limit)\r\n }\r\n\r\n /** Channels seen recently, newest first, for the live view's channel list. */\r\n async channels(id: string, options: { sinceStart?: boolean } = {}) {\r\n const seen = new Map<string, ChannelInfo & { lastAt: number; lastText: string }>()\r\n for (const record of await this.messages(id, { limit: BUFFER_SIZE, sinceStart: options.sinceStart })) {\r\n const key = `${record.channel.type}:${record.channel.id}`\r\n const text = record.segments.map((s) => (s.type === 'text' ? s.data.text : `[${s.type}]`)).join('')\r\n seen.set(key, { ...record.channel, name: record.channel.name ?? seen.get(key)?.name, lastAt: record.timestamp, lastText: text.slice(0, 80) })\r\n }\r\n return [...seen.values()].sort((a, b) => b.lastAt - a.lastAt)\r\n }\r\n\r\n /** How a command reads a message; see the `bots.tryCommand` action. */\r\n tryCommand(input: { name: string; aliases?: string[]; prefixes?: string[]; args: CommandArg[]; text: string; bot?: string }) {\r\n const own = input.prefixes?.filter(Boolean) ?? []\r\n const record = input.bot ? this.records.find((item) => item.id === input.bot) : undefined\r\n const prefixes = own.length ? own : record?.commands?.prefixes?.filter(Boolean).length ? record.commands.prefixes!.filter(Boolean) : DEFAULT_PREFIXES\r\n const def = { name: input.name, args: input.args, prefixes }\r\n const usage = commandUsage(def)\r\n const parsed = splitCommand(input.text, prefixes)\r\n if (!parsed) return { matched: false as const, reason: 'prefix' as const, prefixes, usage }\r\n if (!commandMatches({ name: input.name, aliases: input.aliases }, parsed.name)) return { matched: false as const, reason: 'name' as const, prefixes, usage }\r\n return { matched: true as const, prefix: parsed.prefix, rest: parsed.rest, usage, ...parseArgs(input.args, parsed.rest) }\r\n }\r\n\r\n /**\r\n * People or groups the bots have seen recently, newest first, as `{ value, label, group }`\r\n * choices: the label is `name (id)`, the group the bot's name. For lists such as a permission\r\n * node's allow and block lists.\r\n */\r\n async seen(kind: 'user' | 'group') {\r\n const found = new Map<string, { value: string; label: string; group: string; at: number }>()\r\n for (const record of this.records) {\r\n for (const message of await this.messages(record.id, { limit: BUFFER_SIZE }).catch(() => [])) {\r\n const id = kind === 'user' ? (message.direction === 'in' ? message.user.id : '') : message.channel.type === 'group' ? message.channel.id : ''\r\n if (!id || isSandbox(message.channel)) continue\r\n const name = kind === 'user' ? message.user.name : message.channel.name\r\n const previous = found.get(id)\r\n const label = name || (previous?.label.endsWith(`(${id})`) ? previous.label : '')\r\n found.set(id, { value: id, label: label && !label.endsWith(`(${id})`) ? `${label} (${id})` : label || id, group: record.name, at: message.timestamp })\r\n }\r\n }\r\n return [...found.values()].sort((a, b) => b.at - a.at).map(({ at: _, ...choice }) => choice)\r\n }\r\n\r\n /** The account's friends and groups, from the platform; empty when the bot is offline or the adapter cannot tell. */\r\n async contacts(id: string) {\r\n const bot = this.bot(id)\r\n if (!bot || bot.status !== 'online') return []\r\n return bot.contacts()\r\n }\r\n\r\n /** The sandbox's test user writes to the bot; see `Bot.sandbox`. */\r\n sandbox(id: string, text: string) {\r\n const bot = this.bot(id)\r\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\r\n bot.sandbox(text)\r\n return { ok: true }\r\n }\r\n\r\n async sendManual(id: string, channel: ChannelInfo, text: string) {\r\n const bot = this.bot(id)\r\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\r\n return bot.deliver(channel, text, { source: { kind: 'manual' } })\r\n }\r\n\r\n /** A fresh address of a message's image, video or file, from the platform. */\r\n async media(id: string, segment: Segment, options: { channel?: ChannelInfo; inline?: boolean }) {\r\n const bot = this.bot(id)\r\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\r\n const media = await bot.media(segment, options)\r\n if (!media) throw new MushinError('not_found', 'The platform no longer has this file')\r\n return media\r\n }\r\n\r\n /** The messages of a forwarded chat history, from the platform. */\r\n async forwarded(id: string, forward: string) {\r\n const bot = this.bot(id)\r\n if (!bot) throw new MushinError('unavailable', 'The bot is not running')\r\n return { messages: await bot.forward(forward) }\r\n }\r\n\r\n // ---- actions ----\r\n\r\n private *defineActions() {\r\n const actions = this.home.actions\r\n\r\n yield actions.define({\r\n name: 'bots.adapters',\r\n description: 'List loaded adapter types (e.g. \"onebot\") with their config JSON Schemas.',\r\n risk: 'read',\r\n input: z.object({}),\r\n handler: () => this.adapters(),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.list',\r\n description: 'List bots with their connection status, adapter and enabled plugins. Secrets are masked.',\r\n risk: 'read',\r\n input: z.object({}),\r\n handler: () => this.list(),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.get',\r\n description: 'Get one bot with its status.',\r\n risk: 'read',\r\n input: idInput,\r\n handler: ({ id }) => this.describe(this.get(id)),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.create',\r\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.',\r\n risk: 'write',\r\n input: z.object({\r\n name: z.string().min(1),\r\n adapter: adapterInput,\r\n plugins: z.array(z.object({ package: z.string(), config: z.record(z.string(), z.any()).optional() })).optional()\r\n .describe('Bot plugins to enable right away, e.g. @mushinjs/bot-plugin-llm-chat'),\r\n enabled: z.boolean().optional(),\r\n provider: z.string().optional().describe('Default provider or model profile id for this bot\\'s LLM plugins'),\r\n commands: commandSettingsInput.optional(),\r\n }),\r\n handler: (input) => this.create(input),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.update',\r\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.',\r\n risk: 'write',\r\n input: idInput.extend({\r\n name: z.string().min(1).optional(),\r\n adapter: adapterInput.optional(),\r\n provider: z.string().nullable().optional(),\r\n commands: commandSettingsInput.optional().describe('Command prefixes and the built-in /help; changing only these does not restart the bot'),\r\n }),\r\n handler: ({ id, ...patch }) => this.update(id, patch),\r\n })\r\n\r\n yield actions.define({\r\n name: 'commands.list',\r\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.',\r\n risk: 'read',\r\n input: z.object({ bot: z.string().optional().describe('Bot id from bots.list; all bots when omitted') }),\r\n handler: ({ bot }) => this.commandList(bot),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.commands.run',\r\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.',\r\n risk: 'write',\r\n input: z.object({\r\n bot: z.string().describe('Bot id from bots.list'),\r\n command: z.string().min(1).describe('The command with its arguments, e.g. \"/checkin\" or \"/score 85\"'),\r\n target: z.enum(['master', 'group']).optional().describe('Where to run it for real; omit to only preview'),\r\n group: z.string().optional().describe('Group id, with target \"group\"'),\r\n user: z.string().optional().describe('Run as this user id instead of the first master'),\r\n }),\r\n handler: (input, caller) => this.runCommand(input, caller.kind === 'agent' && caller.session ? { kind: 'agent', session: caller.session } : undefined),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.delete',\r\n description: 'Delete a bot and its settings. Message logs on disk are kept.',\r\n risk: 'dangerous',\r\n input: idInput,\r\n handler: ({ id }) => this.remove(id),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.start',\r\n description: 'Enable and start (or restart) a bot.',\r\n risk: 'write',\r\n input: idInput,\r\n handler: ({ id }) => this.setEnabled(id, true),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.stop',\r\n description: 'Stop and disable a bot.',\r\n risk: 'write',\r\n input: idInput,\r\n handler: ({ id }) => this.setEnabled(id, false),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.plugins.list',\r\n description: 'List every installed bot plugin with whether it is enabled on this bot, its config and status.',\r\n risk: 'read',\r\n input: idInput,\r\n handler: ({ id }) => this.plugins(id),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.plugins.enable',\r\n description: 'Enable a bot plugin on one bot, optionally with config.',\r\n risk: 'write',\r\n input: pluginInput.extend({ config: z.record(z.string(), z.any()).optional() }),\r\n handler: ({ id, package: name, config }) => this.enablePlugin(id, name, config),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.plugins.disable',\r\n description: 'Disable a bot plugin on one bot. Its config is kept.',\r\n risk: 'write',\r\n input: pluginInput,\r\n handler: ({ id, package: name }) => this.disablePlugin(id, name),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.plugins.configure',\r\n description: 'Replace a bot plugin\\'s config on one bot and reload it.',\r\n risk: 'write',\r\n input: pluginInput.extend({ config: z.record(z.string(), z.any()) }),\r\n handler: ({ id, package: name, config }) => this.configurePlugin(id, name, config),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.messages',\r\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.',\r\n risk: 'read',\r\n input: idInput.extend({\r\n limit: z.number().int().min(1).max(BUFFER_SIZE).optional(),\r\n channel: z.string().optional().describe('Group or user id to filter by'),\r\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'),\r\n sinceStart: z.boolean().optional().describe('Only messages received or sent since Mushin started'),\r\n }),\r\n handler: ({ id, ...options }) => this.messages(id, options),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.media',\r\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.',\r\n risk: 'read',\r\n input: idInput.extend({\r\n segment: z.object({ type: z.string(), data: z.record(z.string(), z.any()) }).describe('The segment from the message record'),\r\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }).optional().describe('Where the message was sent; group files need it'),\r\n inline: z.boolean().optional().describe('Return the bytes as a data URL, for showing an image'),\r\n }),\r\n handler: ({ id, segment, channel, inline }) => this.media(id, segment, { channel, inline }),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.forward',\r\n description: 'The messages of a forwarded chat history (a forward segment\\'s id), oldest first, each with its sender, time and segments.',\r\n risk: 'read',\r\n input: idInput.extend({ forward: z.string().min(1).describe('The id in the forward segment') }),\r\n handler: ({ id, forward }) => this.forwarded(id, forward),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.logs',\r\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.',\r\n risk: 'read',\r\n input: idInput.extend({ limit: z.number().int().min(1).max(LOG_BUFFER_SIZE).optional() }),\r\n handler: ({ id, limit }) => this.logLines(id, limit),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.channels',\r\n description: 'Channels (groups and private chats) a bot has seen recently.',\r\n risk: 'read',\r\n input: idInput.extend({ sinceStart: z.boolean().optional().describe('Only channels with messages since Mushin started') }),\r\n handler: ({ id, sinceStart }) => this.channels(id, { sinceStart }),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.tryCommand',\r\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.',\r\n risk: 'read',\r\n input: z.object({\r\n name: z.string(),\r\n aliases: z.array(z.string()).optional(),\r\n prefixes: z.array(z.string()).optional().describe('The command\\'s own prefixes; empty uses the bot\\'s'),\r\n args: z.array(z.object({\r\n name: z.string(),\r\n type: z.enum(['text', 'number', 'boolean', 'user', 'choice']),\r\n optional: z.boolean().optional(),\r\n rest: z.boolean().optional(),\r\n default: z.union([z.string(), z.number(), z.boolean()]).optional(),\r\n choices: z.array(z.string()).optional(),\r\n })).default([]),\r\n text: z.string(),\r\n bot: z.string().optional().describe('Bot whose prefixes apply when the command has none of its own'),\r\n }),\r\n handler: (input) => this.tryCommand(input),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.userChoices',\r\n description: 'People the bots have seen recently, as { value: user id, label, group: bot } choices.',\r\n risk: 'read',\r\n input: z.object({}),\r\n handler: () => this.seen('user'),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.groupChoices',\r\n description: 'Groups the bots have seen recently, as { value: group id, label, group: bot } choices.',\r\n risk: 'read',\r\n input: z.object({}),\r\n handler: () => this.seen('group'),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.usage',\r\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.',\r\n risk: 'read',\r\n input: idInput.extend({ message: z.string().describe('Message record id from bots.messages') }),\r\n handler: ({ id, message }) => this.usage(id, message),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.contacts',\r\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.',\r\n risk: 'read',\r\n input: idInput,\r\n handler: ({ id }) => this.contacts(id),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.sandbox',\r\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.',\r\n risk: 'write',\r\n input: idInput.extend({ text: z.string().min(1) }),\r\n handler: ({ id, text }) => this.sandbox(id, text),\r\n })\r\n\r\n yield actions.define({\r\n name: 'bots.send',\r\n description: 'Send a text message from a bot to a group or private chat.',\r\n risk: 'write',\r\n input: idInput.extend({\r\n channel: z.object({ type: z.enum(['group', 'private']), id: z.string() }),\r\n text: z.string().min(1),\r\n }),\r\n handler: ({ id, channel, text }) => this.sendManual(id, channel, text),\r\n })\r\n }\r\n}\r\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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AO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,sCAAsC,EAAE,CAAC;GAC9F,UAAU,EAAE,IAAI,cAAc,KAAK,MAAM,IAAI,OAAO;EACtD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO;GACP,UAAU,EAAE,SAAS,KAAK,SAAS,EAAE;EACvC,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACjD,UAAU,EAAE,IAAI,WAAW,KAAK,QAAQ,IAAI,IAAI;EAClD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO;IACpB,SAAS,EAAE,OAAO;KAAE,MAAM,EAAE,KAAK,CAAC,SAAS,SAAS,CAAC;KAAG,IAAI,EAAE,OAAO;IAAE,CAAC;IACxE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;GACxB,CAAC;GACD,UAAU,EAAE,IAAI,SAAS,WAAW,KAAK,WAAW,IAAI,SAAS,IAAI;EACvE,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"manager.js","names":[],"sources":["../src/manager.ts"],"sourcesContent":["import {\n type ChannelInfo, Context, currentPackageName, 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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OAAO;EACtD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO;GACP,UAAU,EAAE,SAAS,KAAK,SAAS,EAAE;EACvC,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;GACjD,UAAU,EAAE,IAAI,WAAW,KAAK,QAAQ,IAAI,IAAI;EAClD,CAAC;EAED,MAAM,QAAQ,OAAO;GACnB,MAAM;GACN,aAAa;GACb,MAAM;GACN,OAAO,QAAQ,OAAO;IACpB,SAAS,EAAE,OAAO;KAAE,MAAM,EAAE,KAAK,CAAC,SAAS,SAAS,CAAC;KAAG,IAAI,EAAE,OAAO;IAAE,CAAC;IACxE,MAAM,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;GACxB,CAAC;GACD,UAAU,EAAE,IAAI,SAAS,WAAW,KAAK,WAAW,IAAI,SAAS,IAAI;EACvE,CAAC;CACH;AACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export interface AdapterType<C = any> {
|
|
|
32
32
|
id: string;
|
|
33
33
|
displayName: LocalizedText;
|
|
34
34
|
config: z.ZodType<C>;
|
|
35
|
-
/** Config keys holding secrets
|
|
35
|
+
/** Config keys holding secrets. They are kept in .env (the config holds `${NAME}` references), resolved before the adapter starts, and masked in API responses. */
|
|
36
36
|
secrets?: string[];
|
|
37
37
|
/** Segment types this adapter can send; used to compute a message's supported platforms. */
|
|
38
38
|
segments: string[];
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type { CommandSettings } from './commands'\
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["import type { CommandSettings } from './commands'\nimport type { ChannelInfo, LocalizedText, Plugin, Provenance, Segment, UserInfo, z } from '@mushinjs/core'\n\nexport type BotStatus = 'offline' | 'connecting' | 'online' | 'error'\n\nexport interface BotPluginEntry {\n package: string\n enabled: boolean\n config: Record<string, any>\n}\n\nexport interface BotRecord {\n id: string\n name: string\n enabled: boolean\n adapter: { type: string; config: Record<string, any> }\n plugins: BotPluginEntry[]\n /** Default provider id for this bot's LLM plugins. */\n provider?: string\n /** Command prefixes, the built-in `/help` and admins. */\n commands?: CommandSettings\n createdAt: number\n}\n\n/** How an adapter delivers outgoing messages and raw API calls for one bot. */\nexport interface Transport {\n send(channel: ChannelInfo, segments: Segment[]): Promise<{ messageId?: string }>\n call?(action: string, params: Record<string, any>): Promise<any>\n}\n\nexport interface AdapterType<C = any> {\n id: string\n displayName: LocalizedText\n config: z.ZodType<C>\n /** Config keys holding secrets. They are kept in .env (the config holds `${NAME}` references), resolved before the adapter starts, and masked in API responses. */\n secrets?: string[]\n /** Segment types this adapter can send; used to compute a message's supported platforms. */\n segments: string[]\n /** The adapter can tell a sender's group role (owner, admin, member); its bots call `bot.useRoleResolver()`. */\n groupRoles?: boolean\n /**\n * How a bot with this config connects, for the bots list: a mode such as `ws`, `ws-reverse` or\n * `http`, the address it dials or is reached at, and for HTTP the path events are posted to.\n */\n describe?(config: C, botId: string): BotConnectionInfo\n /**\n * Addresses of people's and groups' pictures, with `{id}` standing for the user or group id,\n * for the dashboard's live conversation view. Left out when the platform has no such addresses.\n */\n avatars?: { user?: string; group?: string }\n /**\n * Loaded inside each bot's isolated context with the bot's adapter config.\n * It injects `bot`, opens the connection and registers a transport.\n */\n plugin: Plugin\n}\n\nexport interface BotConnectionInfo {\n mode: string\n address?: string\n inbound?: string\n}\n\nexport interface IncomingMessage {\n messageId?: string\n channel: ChannelInfo\n user: UserInfo\n segments: Segment[]\n timestamp?: number\n}\n\n/**\n * A sender's role on one bot, from the permissions plugin: `master` owns the bot, `admin` helps\n * manage it, `user` is everyone else. Higher roles include lower ones.\n */\nexport type BotRole = 'master' | 'admin' | 'user'\n\n/** A sender's role in a group, as the platform reports it. Kept apart from bot roles. */\nexport type GroupRole = 'owner' | 'admin' | 'member'\n\nexport const ROLE_RANK: Record<BotRole, number> = { user: 0, admin: 1, master: 2 }\n\n/** Whether `role` meets `required`: a master passes where an admin is required. */\nexport function roleAtLeast(role: BotRole | undefined, required: BotRole) {\n return role !== undefined && ROLE_RANK[role] >= ROLE_RANK[required]\n}\n\n/** Who someone is to a bot; supplied by the permissions plugin through `bots.usePermissions()`. */\nexport interface PermissionProvider {\n roleOf(botId: string, userId: string): BotRole\n}\n\n/** Asks the platform for a sender's group role; registered per bot by adapters that can tell. */\nexport type GroupRoleResolver = (target: { channel: ChannelInfo; user: UserInfo }) => Promise<GroupRole | undefined>\n\n/** A file a message points at, as an address the dashboard can open. */\nexport interface ResolvedMedia {\n /** An http(s) address, or a `data:` URL when the bytes were fetched for showing in place. */\n url: string\n name?: string\n size?: number\n}\n\n/** One message of a forwarded chat history. */\nexport interface ForwardedMessage {\n user: UserInfo\n timestamp: number\n segments: Segment[]\n}\n\n/**\n * Fetches what a message only points at: images, videos and files (whose addresses in the message\n * can expire) and the messages of a forwarded chat history. Registered per bot by adapters.\n */\nexport interface MediaResolver {\n /** `inline`: return the bytes as a data URL, for showing an image in place. */\n media?(segment: Segment, options: { channel?: ChannelInfo; inline: boolean }): Promise<ResolvedMedia | undefined>\n forward?(id: string): Promise<ForwardedMessage[]>\n}\n\n/** A friend or group the bot's account has, from the platform. */\nexport interface Contact extends ChannelInfo {\n /** The name the account gave a friend, when it differs from the friend's own. */\n remark?: string\n /** How many members a group has. */\n members?: number\n}\n\n/** Lists the account's friends and groups; registered per bot by adapters that can. */\nexport type ContactResolver = () => Promise<Contact[]>\n\n/**\n * The sandbox conversation every bot has in the live view: the dashboard plays a test user in a\n * private chat, the bot answers through its flows and plugins, and nothing reaches the platform.\n */\nexport const SANDBOX_CHANNEL: ChannelInfo = { type: 'private', id: '@sandbox', name: 'Sandbox' }\nexport const SANDBOX_USER = { id: '@sandbox', name: 'Sandbox tester' }\n\nexport const isSandbox = (channel: { id: string } | undefined) => channel?.id === SANDBOX_CHANNEL.id\n\n/** Content plus an explicit source, e.g. an LLM result (`{ text, source }`). */\nexport interface SourcedContent {\n text?: string\n segments?: Segment[]\n source?: Provenance\n}\n\n/** A non-message event from an adapter, such as a notice or a request. */\nexport interface BotEvent {\n /** The adapter's event family, e.g. OneBot's `notice` or `request`. */\n type: string\n /** The event as the platform sent it. */\n data: any\n /** A normalized name such as `group_increase` or `notify.poke`; flows only see events that have one. */\n name?: string\n /** Where the event happened, so flows can reply there. */\n channel?: ChannelInfo\n /** Who the event is about. */\n user?: UserInfo\n /** The message the event is about, when it is known (e.g. the text of a recalled message). */\n message?: { id?: string; text: string; segments: Segment[] }\n}\n"],"mappings":";AAgFA,MAAa,YAAqC;CAAE,MAAM;CAAG,OAAO;CAAG,QAAQ;AAAE;;AAGjF,SAAgB,YAAY,MAA2B,UAAmB;CACxE,OAAO,SAAS,KAAA,KAAa,UAAU,SAAS,UAAU;AAC5D;;;;;AAkDA,MAAa,kBAA+B;CAAE,MAAM;CAAW,IAAI;CAAY,MAAM;AAAU;AAC/F,MAAa,eAAe;CAAE,IAAI;CAAY,MAAM;AAAiB;AAErE,MAAa,aAAa,YAAwC,SAAS,OAAO,gBAAgB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mushinjs/plugin-bots",
|
|
3
|
-
"version": "0.2.0-next.
|
|
3
|
+
"version": "0.2.0-next.20261113105814",
|
|
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.
|
|
56
|
-
"@mushinjs/plugin-database": "0.2.0-next.
|
|
57
|
-
"@mushinjs/plugin-storage": "0.2.0-next.
|
|
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",
|
|
58
58
|
"minato": "4.0.1"
|
|
59
59
|
}
|
|
60
60
|
}
|