@mushinjs/plugin-bots 0.2.0-next.20261113103537 → 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/dist/archive.js +2 -5
- package/dist/archive.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/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 {
|
|
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\n }\n }\n return imported\n }\n}\n"],"mappings":";;;AAkCA,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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,SAAS,IAAI,KAAK,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,MAAM,GAAG,EAAE,IAAI;GACrE,MAAM,QAAQ,MAAM,KAAK,IAAI,QAAQ,SAAS,YAAY,KAAK,EAAA,CAC5D,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"}
|
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 {\n type ChannelInfo, Context, currentPackageName, describeMissing, dependencyReport, 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, 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 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 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 if (typeof config[key] === 'string' && config[key]) 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: this.validateAdapter(input.adapter.type, input.adapter.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: this.validateAdapter(patch.adapter.type, 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 ctx.plugin(adapter.plugin, record.adapter.config)\n for (const { entry, plugin } of loaded) runtime.plugins.set(entry.package, ctx.plugin(plugin, 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, 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,k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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,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ACF"}
|
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'\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
|
|
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
|
}
|