@mushinjs/plugin-bots 0.0.0-stage → 0.2.0-next.20261112165327
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/archive.d.ts +61 -0
- package/dist/archive.js +149 -0
- package/dist/archive.js.map +1 -0
- package/dist/bot.d.ts +183 -0
- package/dist/bot.js +552 -0
- package/dist/bot.js.map +1 -0
- package/dist/commands.d.ts +119 -0
- package/dist/commands.js +186 -0
- package/dist/commands.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/manager.d.ts +458 -0
- package/dist/manager.js +1144 -0
- package/dist/manager.js.map +1 -0
- package/dist/types.d.ts +161 -0
- package/dist/types.js +27 -0
- package/dist/types.js.map +1 -0
- package/package.json +57 -3
- package/README.md +0 -3
package/dist/bot.js
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import { DEFAULT_PREFIXES, commandMatches, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
|
|
2
|
+
import { SANDBOX_CHANNEL, SANDBOX_USER, isSandbox, roleAtLeast } from "./types.js";
|
|
3
|
+
import { Service, randomId, seg, segmentsToText, toSegments, usage } from "@mushinjs/core";
|
|
4
|
+
// src/bot.ts
|
|
5
|
+
/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */
|
|
6
|
+
const BUILTIN_PLUGIN = "bots";
|
|
7
|
+
/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */
|
|
8
|
+
const BUILTIN_PRIORITY = 5;
|
|
9
|
+
function isSourced(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && !("type" in value);
|
|
11
|
+
}
|
|
12
|
+
/** One incoming message, as seen by a bot plugin's middleware. */
|
|
13
|
+
var Session = class {
|
|
14
|
+
bot;
|
|
15
|
+
record;
|
|
16
|
+
/** Name of the plugin whose middleware is handling this session; replies are attributed to it. */
|
|
17
|
+
plugin;
|
|
18
|
+
parsed;
|
|
19
|
+
constructor(bot, record) {
|
|
20
|
+
this.bot = bot;
|
|
21
|
+
this.record = record;
|
|
22
|
+
}
|
|
23
|
+
get channel() {
|
|
24
|
+
return this.record.channel;
|
|
25
|
+
}
|
|
26
|
+
get user() {
|
|
27
|
+
return this.record.user;
|
|
28
|
+
}
|
|
29
|
+
get segments() {
|
|
30
|
+
return this.record.segments;
|
|
31
|
+
}
|
|
32
|
+
get isDirect() {
|
|
33
|
+
return this.record.channel.type === "private";
|
|
34
|
+
}
|
|
35
|
+
/** True when the message @-mentions this bot. */
|
|
36
|
+
get mentioned() {
|
|
37
|
+
return this.segments.some((s) => s.type === "at" && String(s.data.qq) === this.bot.selfId);
|
|
38
|
+
}
|
|
39
|
+
/** The command this message runs, such as `/score 85`, split by the bot's prefixes. */
|
|
40
|
+
get command() {
|
|
41
|
+
this.parsed ??= { value: this.bot.parseCommand(this.text) };
|
|
42
|
+
return this.parsed.value;
|
|
43
|
+
}
|
|
44
|
+
/** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */
|
|
45
|
+
role() {
|
|
46
|
+
return this.bot.roleOf(this.user.id);
|
|
47
|
+
}
|
|
48
|
+
/** The sender's role in this group, when the adapter can tell; nothing in private chats. */
|
|
49
|
+
groupRole() {
|
|
50
|
+
return this.bot.groupRoleOf({
|
|
51
|
+
channel: this.channel,
|
|
52
|
+
user: this.user
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/** True when the sender is an admin or master of the bot, who may run admin-only commands. */
|
|
56
|
+
get isAdmin() {
|
|
57
|
+
return roleAtLeast(this.role(), "admin");
|
|
58
|
+
}
|
|
59
|
+
/** Plain text with mentions of this bot removed. */
|
|
60
|
+
get text() {
|
|
61
|
+
const segments = this.segments.filter((s) => !(s.type === "at" && String(s.data.qq) === this.bot.selfId));
|
|
62
|
+
return segmentsToText(segments).trim();
|
|
63
|
+
}
|
|
64
|
+
send(content) {
|
|
65
|
+
return this.bot.deliver(this.channel, content, {
|
|
66
|
+
plugin: this.plugin,
|
|
67
|
+
replyTo: this.record.id
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/** Sends with a reply reference to the incoming message, when the platform supports it. */
|
|
71
|
+
reply(content) {
|
|
72
|
+
const quote = this.record.messageId ? [{
|
|
73
|
+
type: "reply",
|
|
74
|
+
data: { id: this.record.messageId }
|
|
75
|
+
}] : [];
|
|
76
|
+
if (isSourced(content)) return this.send({
|
|
77
|
+
...content,
|
|
78
|
+
segments: [...quote, ...content.segments ?? toSegments(content.text ?? "")]
|
|
79
|
+
});
|
|
80
|
+
return this.send([...quote, ...toSegments(content)]);
|
|
81
|
+
}
|
|
82
|
+
/** A view of this session attributed to another plugin. */
|
|
83
|
+
as(plugin) {
|
|
84
|
+
const view = Object.create(this);
|
|
85
|
+
view.plugin = plugin;
|
|
86
|
+
return view;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
/**
|
|
90
|
+
* The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin
|
|
91
|
+
* always means that plugin's bot.
|
|
92
|
+
*/
|
|
93
|
+
var Bot = class extends Service {
|
|
94
|
+
status = "offline";
|
|
95
|
+
error;
|
|
96
|
+
selfId;
|
|
97
|
+
selfName;
|
|
98
|
+
/** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */
|
|
99
|
+
selfAvatar;
|
|
100
|
+
record;
|
|
101
|
+
hooks;
|
|
102
|
+
transport;
|
|
103
|
+
middlewares = [];
|
|
104
|
+
eventHandlers = /* @__PURE__ */ new Set();
|
|
105
|
+
ownCommands = /* @__PURE__ */ new Set();
|
|
106
|
+
commandProviders = /* @__PURE__ */ new Set();
|
|
107
|
+
roleResolver;
|
|
108
|
+
mediaResolver;
|
|
109
|
+
contactResolver;
|
|
110
|
+
constructor(ctx, config) {
|
|
111
|
+
super(ctx, "bot");
|
|
112
|
+
this.record = config.record;
|
|
113
|
+
this.hooks = config.hooks;
|
|
114
|
+
}
|
|
115
|
+
get id() {
|
|
116
|
+
return this.record.id;
|
|
117
|
+
}
|
|
118
|
+
get platform() {
|
|
119
|
+
return this.record.adapter.type;
|
|
120
|
+
}
|
|
121
|
+
setStatus(status, error) {
|
|
122
|
+
const nextError = status === "error" ? error : void 0;
|
|
123
|
+
if (status !== this.status || nextError !== this.error) {
|
|
124
|
+
const logger = this.ctx.logger("bot");
|
|
125
|
+
if (status === "error") logger.warn("status: error (%s)", error ?? "no details");
|
|
126
|
+
else logger.info("status: %s", status);
|
|
127
|
+
}
|
|
128
|
+
this.status = status;
|
|
129
|
+
this.error = status === "error" ? error : void 0;
|
|
130
|
+
this.hooks.status(this);
|
|
131
|
+
}
|
|
132
|
+
setSelf(id, name, avatar) {
|
|
133
|
+
this.selfId = id;
|
|
134
|
+
this.selfName = name;
|
|
135
|
+
this.selfAvatar = avatar;
|
|
136
|
+
this.hooks.status(this);
|
|
137
|
+
}
|
|
138
|
+
/** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */
|
|
139
|
+
useTransport(transport) {
|
|
140
|
+
return this.ctx.effect(() => {
|
|
141
|
+
this.transport = transport;
|
|
142
|
+
return () => {
|
|
143
|
+
if (this.transport !== transport) return;
|
|
144
|
+
this.transport = void 0;
|
|
145
|
+
this.setStatus("offline");
|
|
146
|
+
};
|
|
147
|
+
}, "bot.useTransport()");
|
|
148
|
+
}
|
|
149
|
+
/** Called by adapters that can tell a sender's group role (owner, admin, member). */
|
|
150
|
+
useRoleResolver(resolver) {
|
|
151
|
+
return this.ctx.effect(() => {
|
|
152
|
+
this.roleResolver = resolver;
|
|
153
|
+
return () => {
|
|
154
|
+
if (this.roleResolver === resolver) this.roleResolver = void 0;
|
|
155
|
+
};
|
|
156
|
+
}, "bot.useRoleResolver()");
|
|
157
|
+
}
|
|
158
|
+
/** Called by adapters that can fetch a message's media and forwarded chat histories. */
|
|
159
|
+
useMediaResolver(resolver) {
|
|
160
|
+
return this.ctx.effect(() => {
|
|
161
|
+
this.mediaResolver = resolver;
|
|
162
|
+
return () => {
|
|
163
|
+
if (this.mediaResolver === resolver) this.mediaResolver = void 0;
|
|
164
|
+
};
|
|
165
|
+
}, "bot.useMediaResolver()");
|
|
166
|
+
}
|
|
167
|
+
/** Called by adapters that can list the account's friends and groups. */
|
|
168
|
+
useContacts(resolver) {
|
|
169
|
+
return this.ctx.effect(() => {
|
|
170
|
+
this.contactResolver = resolver;
|
|
171
|
+
return () => {
|
|
172
|
+
if (this.contactResolver === resolver) this.contactResolver = void 0;
|
|
173
|
+
};
|
|
174
|
+
}, "bot.useContacts()");
|
|
175
|
+
}
|
|
176
|
+
/** The account's friends and groups; empty when the adapter cannot list them. */
|
|
177
|
+
async contacts() {
|
|
178
|
+
return this.contactResolver ? this.contactResolver() : [];
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A
|
|
182
|
+
* leading "@" mentions the bot. Replies stay in the sandbox and never reach the platform.
|
|
183
|
+
*/
|
|
184
|
+
sandbox(text) {
|
|
185
|
+
const mention = /^@\S*\s*/.exec(text);
|
|
186
|
+
const rest = mention ? text.slice(mention[0].length) : text;
|
|
187
|
+
const segments = [...mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : [], ...rest ? [seg.text(mention ? ` ${rest}` : rest)] : []];
|
|
188
|
+
this.receive({
|
|
189
|
+
messageId: randomId(6),
|
|
190
|
+
channel: SANDBOX_CHANNEL,
|
|
191
|
+
user: SANDBOX_USER,
|
|
192
|
+
segments
|
|
193
|
+
}).catch((error) => {
|
|
194
|
+
this.ctx.logger("bot").warn("sandbox message failed: %s", error);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
/** An address for an image, video, voice or file segment; see `MediaResolver.media`. */
|
|
198
|
+
async media(segment, options = {}) {
|
|
199
|
+
if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`);
|
|
200
|
+
return this.mediaResolver.media(segment, {
|
|
201
|
+
channel: options.channel,
|
|
202
|
+
inline: options.inline ?? false
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
/** The messages of a forwarded chat history. */
|
|
206
|
+
async forward(id) {
|
|
207
|
+
if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`);
|
|
208
|
+
return this.mediaResolver.forward(id);
|
|
209
|
+
}
|
|
210
|
+
/** The user's role on this bot, from the permissions plugin; nothing when it is not running. */
|
|
211
|
+
roleOf(userId) {
|
|
212
|
+
if (userId === SANDBOX_USER.id) return "master";
|
|
213
|
+
return this.hooks.roleOf?.(this, userId);
|
|
214
|
+
}
|
|
215
|
+
/** A sender's group role: from the message when the platform sent it, else from the adapter. */
|
|
216
|
+
async groupRoleOf(target) {
|
|
217
|
+
if (target.channel.type !== "group" || !target.user.id) return;
|
|
218
|
+
if (target.user.role) return target.user.role;
|
|
219
|
+
try {
|
|
220
|
+
return await this.roleResolver?.({
|
|
221
|
+
channel: target.channel,
|
|
222
|
+
user: target.user
|
|
223
|
+
});
|
|
224
|
+
} catch (error) {
|
|
225
|
+
this.ctx.logger("bot").debug("group role of %s: %s", target.user.id, error);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/** Whether a command's role requirement lets this session run it; logs why not. */
|
|
229
|
+
allows(def, session) {
|
|
230
|
+
const required = requiredRole(def);
|
|
231
|
+
if (!required) return true;
|
|
232
|
+
const role = session.role();
|
|
233
|
+
if (role === void 0) {
|
|
234
|
+
this.ctx.logger("bot").debug("/%s needs %s, but the permissions plugin is not running; ignored", def.name, required);
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
return roleAtLeast(role, required);
|
|
238
|
+
}
|
|
239
|
+
/** Registers middleware for incoming messages; runs in registration order. */
|
|
240
|
+
middleware(callback, options = {}) {
|
|
241
|
+
const ctx = this.ctx;
|
|
242
|
+
const entry = {
|
|
243
|
+
plugin: ctx.fiber.name,
|
|
244
|
+
callback,
|
|
245
|
+
priority: options.priority ?? 0
|
|
246
|
+
};
|
|
247
|
+
return ctx.effect(() => {
|
|
248
|
+
const index = this.middlewares.findIndex((item) => item.priority < entry.priority);
|
|
249
|
+
if (index < 0) this.middlewares.push(entry);
|
|
250
|
+
else this.middlewares.splice(index, 0, entry);
|
|
251
|
+
return () => {
|
|
252
|
+
const index = this.middlewares.indexOf(entry);
|
|
253
|
+
if (index >= 0) this.middlewares.splice(index, 1);
|
|
254
|
+
};
|
|
255
|
+
}, "bot.middleware()");
|
|
256
|
+
}
|
|
257
|
+
get prefixes() {
|
|
258
|
+
const prefixes = this.record.commands?.prefixes?.filter(Boolean);
|
|
259
|
+
return prefixes?.length ? prefixes : DEFAULT_PREFIXES;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Splits text into a command, with the registered command it names. Commands with prefixes of
|
|
263
|
+
* their own (such as `#`) are matched by those only; the rest by the bot's prefixes.
|
|
264
|
+
*/
|
|
265
|
+
parseCommand(text) {
|
|
266
|
+
const entries = this.hooks.commands?.(this) ?? [];
|
|
267
|
+
for (const entry of entries) {
|
|
268
|
+
if (!entry.prefixes?.length) continue;
|
|
269
|
+
const parsed = splitCommand(text, entry.prefixes);
|
|
270
|
+
if (parsed && commandMatches(entry, parsed.name)) return {
|
|
271
|
+
...parsed,
|
|
272
|
+
entry
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
const parsed = splitCommand(text, this.prefixes);
|
|
276
|
+
if (!parsed) return;
|
|
277
|
+
const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name));
|
|
278
|
+
return entry ? {
|
|
279
|
+
...parsed,
|
|
280
|
+
entry
|
|
281
|
+
} : parsed;
|
|
282
|
+
}
|
|
283
|
+
/** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */
|
|
284
|
+
localCommands() {
|
|
285
|
+
const entries = [...this.ownCommands].map(({ def, plugin }) => ({
|
|
286
|
+
...def,
|
|
287
|
+
botId: this.id,
|
|
288
|
+
source: {
|
|
289
|
+
kind: "plugin",
|
|
290
|
+
id: plugin,
|
|
291
|
+
name: plugin
|
|
292
|
+
}
|
|
293
|
+
}));
|
|
294
|
+
for (const provider of this.commandProviders) try {
|
|
295
|
+
entries.push(...provider());
|
|
296
|
+
} catch (error) {
|
|
297
|
+
this.ctx.logger("bot").warn("listing commands failed: %s", error);
|
|
298
|
+
}
|
|
299
|
+
return entries;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,
|
|
303
|
+
* so they show in `/help` and the command list. Removed when the calling plugin unloads.
|
|
304
|
+
*/
|
|
305
|
+
defineCommands(provider) {
|
|
306
|
+
return this.ctx.effect(() => {
|
|
307
|
+
this.commandProviders.add(provider);
|
|
308
|
+
return () => this.commandProviders.delete(provider);
|
|
309
|
+
}, "bot.defineCommands()");
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.
|
|
313
|
+
* It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot
|
|
314
|
+
* replies with how to write the command.
|
|
315
|
+
*/
|
|
316
|
+
command(def, handler) {
|
|
317
|
+
const ctx = this.ctx;
|
|
318
|
+
const entry = {
|
|
319
|
+
def,
|
|
320
|
+
plugin: ctx.fiber.name
|
|
321
|
+
};
|
|
322
|
+
ctx.effect(() => {
|
|
323
|
+
this.ownCommands.add(entry);
|
|
324
|
+
return () => this.ownCommands.delete(entry);
|
|
325
|
+
}, `bot.command(${def.name})`);
|
|
326
|
+
return this.middleware(async (session, next) => {
|
|
327
|
+
const parsed = session.command;
|
|
328
|
+
if (!parsed || !commandMatches(def, parsed.name)) return next();
|
|
329
|
+
if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next();
|
|
330
|
+
if (!this.allows(def, session)) return;
|
|
331
|
+
const values = parseArgs(def.args ?? [], parsed.rest, session.segments);
|
|
332
|
+
if (!values.ok) {
|
|
333
|
+
await session.reply(usageReply(def, parsed.prefix));
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
await handler(session, values.values, parsed);
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
/** The plugins whose middleware sees incoming messages, in the order they see them. */
|
|
340
|
+
middlewareOrder() {
|
|
341
|
+
return this.middlewares.map(({ plugin, priority }) => ({
|
|
342
|
+
plugin,
|
|
343
|
+
priority
|
|
344
|
+
}));
|
|
345
|
+
}
|
|
346
|
+
/** Listens for adapter events that are not messages (notices, requests). */
|
|
347
|
+
onEvent(handler) {
|
|
348
|
+
return this.ctx.effect(() => {
|
|
349
|
+
this.eventHandlers.add(handler);
|
|
350
|
+
return () => this.eventHandlers.delete(handler);
|
|
351
|
+
}, "bot.onEvent()");
|
|
352
|
+
}
|
|
353
|
+
/** Called by adapters for non-message events. */
|
|
354
|
+
dispatchEvent(event) {
|
|
355
|
+
this.logEvent(event);
|
|
356
|
+
for (const handler of this.eventHandlers) try {
|
|
357
|
+
handler(event);
|
|
358
|
+
} catch (error) {
|
|
359
|
+
this.ctx.logger("bot").warn(error);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** Called by adapters for each incoming message: records it, then runs the middleware chain. */
|
|
363
|
+
async receive(message, options = {}) {
|
|
364
|
+
const started = Date.now();
|
|
365
|
+
const record = this.hooks.record({
|
|
366
|
+
botId: this.id,
|
|
367
|
+
messageId: message.messageId,
|
|
368
|
+
direction: "in",
|
|
369
|
+
channel: message.channel,
|
|
370
|
+
user: message.user,
|
|
371
|
+
segments: message.segments,
|
|
372
|
+
timestamp: message.timestamp ?? Date.now(),
|
|
373
|
+
source: options.source ?? { kind: "user" }
|
|
374
|
+
});
|
|
375
|
+
this.ctx.logger("message").info("received from %s%s: %s", who(record.user), record.channel.type === "group" ? ` in ${chat(record.channel)}` : "", preview(record.segments));
|
|
376
|
+
const session = new Session(this, record);
|
|
377
|
+
const entry = session.command?.entry;
|
|
378
|
+
if (entry) try {
|
|
379
|
+
this.hooks.commandCalled?.(this, entry, session);
|
|
380
|
+
} catch {}
|
|
381
|
+
const chain = [...this.middlewares];
|
|
382
|
+
const appHandler = entry?.source.kind === "plugin" ? this.hooks.appCommand?.(this, entry) : void 0;
|
|
383
|
+
if (entry?.source.kind === "builtin" || appHandler) {
|
|
384
|
+
const builtin = {
|
|
385
|
+
plugin: appHandler ? entry.source.id : BUILTIN_PLUGIN,
|
|
386
|
+
priority: 5,
|
|
387
|
+
callback: async (view, next) => {
|
|
388
|
+
if (!this.allows(entry, view)) return next();
|
|
389
|
+
if (appHandler) {
|
|
390
|
+
await appHandler(view);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const answer = this.hooks.builtinCommand?.(this, entry, view);
|
|
394
|
+
if (answer !== void 0) await view.reply(answer);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
const index = chain.findIndex((item) => item.priority < builtin.priority);
|
|
398
|
+
chain.splice(index < 0 ? chain.length : index, 0, builtin);
|
|
399
|
+
}
|
|
400
|
+
/** The plugin that kept the message from the ones after it, if one did. */
|
|
401
|
+
let stoppedAt;
|
|
402
|
+
const run = async (index) => {
|
|
403
|
+
const entry = chain[index];
|
|
404
|
+
if (!entry) return;
|
|
405
|
+
let passed = false;
|
|
406
|
+
try {
|
|
407
|
+
await entry.callback(session.as(entry.plugin), () => {
|
|
408
|
+
passed = true;
|
|
409
|
+
return run(index + 1);
|
|
410
|
+
});
|
|
411
|
+
if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin;
|
|
412
|
+
} catch (error) {
|
|
413
|
+
this.ctx.logger("bot").warn("middleware of %s failed: %s", entry.plugin, error);
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
const outer = this.hooks.usageScope?.(this, record);
|
|
417
|
+
const scope = {
|
|
418
|
+
botId: this.id,
|
|
419
|
+
messageId: record.id,
|
|
420
|
+
report: (event) => {
|
|
421
|
+
outer?.report(event);
|
|
422
|
+
this.logUsage(event);
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
await usage.run(scope, () => run(0));
|
|
426
|
+
this.ctx.logger("bot").info("processed in %s%s", duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : "");
|
|
427
|
+
return session;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* A notice or request from the platform (a poke, a member joining, a recall…) as a line in the
|
|
431
|
+
* bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.
|
|
432
|
+
*/
|
|
433
|
+
logEvent(event) {
|
|
434
|
+
const name = event.name ?? event.type;
|
|
435
|
+
const target = event.data?.target_id ?? void 0;
|
|
436
|
+
const parts = [
|
|
437
|
+
event.user && `from ${who(event.user)}`,
|
|
438
|
+
event.channel?.type === "group" && `in ${chat(event.channel)}`,
|
|
439
|
+
target !== void 0 && target !== null && `to ${target}`,
|
|
440
|
+
event.message?.text && `: ${preview(event.message.segments)}`
|
|
441
|
+
].filter(Boolean).join(" ").replace(" :", ":");
|
|
442
|
+
const quiet = !event.name || event.name === "notify.input_status";
|
|
443
|
+
this.ctx.logger("message")[quiet ? "debug" : "info"]("event %s%s", name, parts ? ` ${parts}` : "");
|
|
444
|
+
}
|
|
445
|
+
/** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */
|
|
446
|
+
logUsage(event) {
|
|
447
|
+
const logger = this.ctx.logger("llm");
|
|
448
|
+
const target = [
|
|
449
|
+
event.model,
|
|
450
|
+
event.provider && `via ${event.provider}`,
|
|
451
|
+
event.plugin && `for ${event.plugin}`
|
|
452
|
+
].filter(Boolean).join(" ");
|
|
453
|
+
const details = [
|
|
454
|
+
event.inputTokens !== void 0 || event.outputTokens !== void 0 ? `${event.inputTokens ?? "?"} → ${event.outputTokens ?? 0} tokens` : "",
|
|
455
|
+
event.note,
|
|
456
|
+
event.latencyMs !== void 0 && duration(event.latencyMs)
|
|
457
|
+
].filter(Boolean).join(", ");
|
|
458
|
+
if (event.ok === false) logger.warn("%s %s failed%s", event.kind, target, event.latencyMs !== void 0 ? ` after ${duration(event.latencyMs)}` : "");
|
|
459
|
+
else logger.info("%s %s%s", event.kind, target, details ? `: ${details}` : "");
|
|
460
|
+
}
|
|
461
|
+
/** Sends a message from a plugin; the reply is attributed to the calling plugin. */
|
|
462
|
+
send(channel, content, options = {}) {
|
|
463
|
+
return this.deliver(channel, content, {
|
|
464
|
+
plugin: this.ctx.fiber.name,
|
|
465
|
+
source: options.source
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
/** Raw adapter API, e.g. a NapCat extension action. */
|
|
469
|
+
async call(action, params = {}) {
|
|
470
|
+
if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`);
|
|
471
|
+
return this.transport.call(action, params);
|
|
472
|
+
}
|
|
473
|
+
async deliver(channel, content, options) {
|
|
474
|
+
const sandbox = isSandbox(channel);
|
|
475
|
+
if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`);
|
|
476
|
+
let segments;
|
|
477
|
+
let source = options.source;
|
|
478
|
+
if (isSourced(content)) {
|
|
479
|
+
segments = content.segments ?? toSegments(content.text ?? "");
|
|
480
|
+
source ??= content.source;
|
|
481
|
+
} else segments = toSegments(content);
|
|
482
|
+
if (source?.kind === "llm" && !source.plugin && options.plugin) source = {
|
|
483
|
+
...source,
|
|
484
|
+
plugin: options.plugin
|
|
485
|
+
};
|
|
486
|
+
source ??= options.plugin ? {
|
|
487
|
+
kind: "plugin",
|
|
488
|
+
plugin: options.plugin
|
|
489
|
+
} : { kind: "manual" };
|
|
490
|
+
if (!segments.length || segments.length === 1 && segments[0].type === "text" && !segments[0].data.text) return;
|
|
491
|
+
const started = Date.now();
|
|
492
|
+
const logger = this.ctx.logger("message");
|
|
493
|
+
const sender = source.kind === "flow" ? `flow ${source.flow}` : source.kind === "plugin" || source.kind === "llm" ? source.plugin : void 0;
|
|
494
|
+
let messageId;
|
|
495
|
+
try {
|
|
496
|
+
({messageId} = sandbox ? { messageId: randomId(6) } : await this.transport.send(channel, segments));
|
|
497
|
+
} catch (error) {
|
|
498
|
+
logger.warn("sending to %s failed: %s", chat(channel), error instanceof Error ? error.message : error);
|
|
499
|
+
throw error;
|
|
500
|
+
}
|
|
501
|
+
const ms = Date.now() - started;
|
|
502
|
+
const bytes = byteSize(segments);
|
|
503
|
+
logger.info("sent to %s%s: %s (%s%s)", chat(channel), sender ? ` by ${sender}` : "", preview(segments), size(bytes), sandbox ? "" : `, ${duration(ms)}`);
|
|
504
|
+
const record = this.hooks.record({
|
|
505
|
+
botId: this.id,
|
|
506
|
+
messageId,
|
|
507
|
+
direction: "out",
|
|
508
|
+
channel,
|
|
509
|
+
user: {
|
|
510
|
+
id: this.selfId ?? this.id,
|
|
511
|
+
name: this.selfName ?? this.record.name
|
|
512
|
+
},
|
|
513
|
+
segments,
|
|
514
|
+
timestamp: Date.now(),
|
|
515
|
+
replyTo: options.replyTo,
|
|
516
|
+
source
|
|
517
|
+
});
|
|
518
|
+
this.hooks.sent?.(this, record, {
|
|
519
|
+
bytes,
|
|
520
|
+
...sandbox ? {} : { ms },
|
|
521
|
+
cause: usage.current()?.messageId
|
|
522
|
+
});
|
|
523
|
+
return record;
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */
|
|
527
|
+
function byteSize(segments) {
|
|
528
|
+
return Buffer.byteLength(JSON.stringify(segments));
|
|
529
|
+
}
|
|
530
|
+
/** A message on one line for the bot's log, cut to a readable length. */
|
|
531
|
+
function preview(segments) {
|
|
532
|
+
const text = segmentsToText(segments).replace(/\s+/g, " ").trim();
|
|
533
|
+
return text.length > 200 ? `${text.slice(0, 200)}…` : text || "(empty)";
|
|
534
|
+
}
|
|
535
|
+
/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */
|
|
536
|
+
function chat(channel) {
|
|
537
|
+
if (isSandbox(channel)) return "the sandbox";
|
|
538
|
+
const name = channel.name ? `${channel.name} (${channel.id})` : channel.id;
|
|
539
|
+
return channel.type === "group" ? `group ${name}` : name;
|
|
540
|
+
}
|
|
541
|
+
function who(user) {
|
|
542
|
+
return user.name ? `${user.name} (${user.id})` : user.id;
|
|
543
|
+
}
|
|
544
|
+
function duration(ms) {
|
|
545
|
+
return ms < 1e3 ? `${ms}ms` : `${(ms / 1e3).toFixed(ms < 1e4 ? 2 : 1)}s`;
|
|
546
|
+
}
|
|
547
|
+
function size(bytes) {
|
|
548
|
+
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
|
549
|
+
}
|
|
550
|
+
export { BUILTIN_PRIORITY, Bot, Session, byteSize };
|
|
551
|
+
|
|
552
|
+
//# sourceMappingURL=bot.js.map
|
package/dist/bot.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\r\n type ChannelInfo, type Content, Context, type MessageRecord, type Provenance, type Segment, segmentsToText,\r\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\r\n} from '@mushinjs/core'\r\nimport {\r\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\r\n usageReply,\r\n} from './commands'\r\nimport {\r\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\r\n type MediaResolver, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\r\n} from './types'\r\n\r\nexport type Sendable = Content | SourcedContent\r\n\r\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\r\n\r\ninterface MiddlewareEntry {\r\n plugin: string\r\n callback: Middleware\r\n priority: number\r\n}\r\n\r\nexport interface MiddlewareOptions {\r\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\r\n priority?: number\r\n}\r\n\r\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\r\nexport interface BotHooks {\r\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\r\n status(bot: Bot): void\r\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\r\n commands?(bot: Bot): CommandEntry[]\r\n /** A message ran a registered command. */\r\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\r\n /** The answer to a built-in command such as `/help`. */\r\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\r\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\r\n roleOf?(bot: Bot, userId: string): BotRole | undefined\r\n /** A command that an app plugin answers on every bot, such as `/persona`. */\r\n appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined\r\n /** Where the costs of handling a message go; see `usage` in core. */\r\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\r\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\r\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\r\n}\r\n\r\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\r\n\r\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\r\nconst BUILTIN_PLUGIN = 'bots'\r\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\r\nexport const BUILTIN_PRIORITY = 5\r\n\r\nfunction isSourced(value: Sendable): value is SourcedContent {\r\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\r\n}\r\n\r\n/** One incoming message, as seen by a bot plugin's middleware. */\r\nexport class Session {\r\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\r\n plugin?: string\r\n private parsed?: { value: ParsedCommand | undefined }\r\n\r\n constructor(public bot: Bot, public record: MessageRecord) {}\r\n\r\n get channel() {\r\n return this.record.channel\r\n }\r\n\r\n get user() {\r\n return this.record.user\r\n }\r\n\r\n get segments() {\r\n return this.record.segments\r\n }\r\n\r\n get isDirect() {\r\n return this.record.channel.type === 'private'\r\n }\r\n\r\n /** True when the message @-mentions this bot. */\r\n get mentioned() {\r\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\r\n }\r\n\r\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\r\n get command(): ParsedCommand | undefined {\r\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\r\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\r\n return this.parsed.value\r\n }\r\n\r\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\r\n role(): BotRole | undefined {\r\n return this.bot.roleOf(this.user.id)\r\n }\r\n\r\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\r\n groupRole(): Promise<GroupRole | undefined> {\r\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\r\n }\r\n\r\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\r\n get isAdmin() {\r\n return roleAtLeast(this.role(), 'admin')\r\n }\r\n\r\n /** Plain text with mentions of this bot removed. */\r\n get text() {\r\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\r\n return segmentsToText(segments).trim()\r\n }\r\n\r\n send(content: Sendable) {\r\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\r\n }\r\n\r\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\r\n reply(content: Sendable) {\r\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\r\n if (isSourced(content)) {\r\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\r\n }\r\n return this.send([...quote, ...toSegments(content)])\r\n }\r\n\r\n /** A view of this session attributed to another plugin. */\r\n as(plugin: string) {\r\n const view = Object.create(this) as Session\r\n view.plugin = plugin\r\n return view\r\n }\r\n}\r\n\r\n/**\r\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\r\n * always means that plugin's bot.\r\n */\r\nexport class Bot extends Service {\r\n status: BotStatus = 'offline'\r\n error?: string\r\n selfId?: string\r\n selfName?: string\r\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\r\n selfAvatar?: string\r\n record: BotRecord\r\n private hooks: BotHooks\r\n private transport?: Transport\r\n private middlewares: MiddlewareEntry[] = []\r\n private eventHandlers = new Set<(event: BotEvent) => void>()\r\n private ownCommands = new Set<{ def: CommandDef; plugin: string }>()\r\n private commandProviders = new Set<() => CommandEntry[]>()\r\n private roleResolver?: GroupRoleResolver\r\n private mediaResolver?: MediaResolver\r\n private contactResolver?: ContactResolver\r\n\r\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\r\n super(ctx, 'bot')\r\n this.record = config.record\r\n this.hooks = config.hooks\r\n }\r\n\r\n get id() {\r\n return this.record.id\r\n }\r\n\r\n get platform() {\r\n return this.record.adapter.type\r\n }\r\n\r\n setStatus(status: BotStatus, error?: string) {\r\n const nextError = status === 'error' ? error : undefined\r\n if (status !== this.status || nextError !== this.error) {\r\n const logger = this.ctx.logger('bot')\r\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\r\n else logger.info('status: %s', status)\r\n }\r\n this.status = status\r\n this.error = status === 'error' ? error : undefined\r\n this.hooks.status(this)\r\n }\r\n\r\n setSelf(id: string, name?: string, avatar?: string) {\r\n this.selfId = id\r\n this.selfName = name\r\n this.selfAvatar = avatar\r\n this.hooks.status(this)\r\n }\r\n\r\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\r\n useTransport(transport: Transport) {\r\n return this.ctx.effect(() => {\r\n this.transport = transport\r\n return () => {\r\n if (this.transport !== transport) return\r\n this.transport = undefined\r\n this.setStatus('offline')\r\n }\r\n }, 'bot.useTransport()')\r\n }\r\n\r\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\r\n useRoleResolver(resolver: GroupRoleResolver) {\r\n return this.ctx.effect(() => {\r\n this.roleResolver = resolver\r\n return () => {\r\n if (this.roleResolver === resolver) this.roleResolver = undefined\r\n }\r\n }, 'bot.useRoleResolver()')\r\n }\r\n\r\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\r\n useMediaResolver(resolver: MediaResolver) {\r\n return this.ctx.effect(() => {\r\n this.mediaResolver = resolver\r\n return () => {\r\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\r\n }\r\n }, 'bot.useMediaResolver()')\r\n }\r\n\r\n /** Called by adapters that can list the account's friends and groups. */\r\n useContacts(resolver: ContactResolver) {\r\n return this.ctx.effect(() => {\r\n this.contactResolver = resolver\r\n return () => {\r\n if (this.contactResolver === resolver) this.contactResolver = undefined\r\n }\r\n }, 'bot.useContacts()')\r\n }\r\n\r\n /** The account's friends and groups; empty when the adapter cannot list them. */\r\n async contacts() {\r\n return this.contactResolver ? this.contactResolver() : []\r\n }\r\n\r\n /**\r\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\r\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\r\n */\r\n sandbox(text: string) {\r\n const mention = /^@\\S*\\s*/.exec(text)\r\n const rest = mention ? text.slice(mention[0].length) : text\r\n const segments: Segment[] = [\r\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\r\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\r\n ]\r\n // Not awaited: a flow may wait for the next message, which comes through another call.\r\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\r\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\r\n })\r\n }\r\n\r\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\r\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\r\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\r\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\r\n }\r\n\r\n /** The messages of a forwarded chat history. */\r\n async forward(id: string) {\r\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\r\n return this.mediaResolver.forward(id)\r\n }\r\n\r\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\r\n roleOf(userId: string): BotRole | undefined {\r\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\r\n if (userId === SANDBOX_USER.id) return 'master'\r\n return this.hooks.roleOf?.(this, userId)\r\n }\r\n\r\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\r\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\r\n if (target.channel.type !== 'group' || !target.user.id) return\r\n if (target.user.role) return target.user.role\r\n try {\r\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\r\n } catch (error) {\r\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\r\n }\r\n }\r\n\r\n /** Whether a command's role requirement lets this session run it; logs why not. */\r\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\r\n const required = requiredRole(def)\r\n if (!required) return true\r\n const role = session.role()\r\n if (role === undefined) {\r\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\r\n return false\r\n }\r\n return roleAtLeast(role, required)\r\n }\r\n\r\n /** Registers middleware for incoming messages; runs in registration order. */\r\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\r\n const ctx = this.ctx\r\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, callback, priority: options.priority ?? 0 }\r\n return ctx.effect(() => {\r\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\r\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\r\n if (index < 0) this.middlewares.push(entry)\r\n else this.middlewares.splice(index, 0, entry)\r\n return () => {\r\n const index = this.middlewares.indexOf(entry)\r\n if (index >= 0) this.middlewares.splice(index, 1)\r\n }\r\n }, 'bot.middleware()')\r\n }\r\n\r\n get prefixes() {\r\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\r\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\r\n }\r\n\r\n /**\r\n * Splits text into a command, with the registered command it names. Commands with prefixes of\r\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\r\n */\r\n parseCommand(text: string): ParsedCommand | undefined {\r\n const entries = this.hooks.commands?.(this) ?? []\r\n for (const entry of entries) {\r\n if (!entry.prefixes?.length) continue\r\n const parsed = splitCommand(text, entry.prefixes)\r\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\r\n }\r\n const parsed = splitCommand(text, this.prefixes)\r\n if (!parsed) return\r\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\r\n return entry ? { ...parsed, entry } : parsed\r\n }\r\n\r\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\r\n localCommands(): CommandEntry[] {\r\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\r\n for (const provider of this.commandProviders) {\r\n try {\r\n entries.push(...provider())\r\n } catch (error) {\r\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\r\n }\r\n }\r\n return entries\r\n }\r\n\r\n /**\r\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\r\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\r\n */\r\n defineCommands(provider: () => CommandEntry[]) {\r\n return this.ctx.effect(() => {\r\n this.commandProviders.add(provider)\r\n return () => this.commandProviders.delete(provider)\r\n }, 'bot.defineCommands()')\r\n }\r\n\r\n /**\r\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\r\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\r\n * replies with how to write the command.\r\n */\r\n command(def: CommandDef, handler: CommandHandler) {\r\n const ctx = this.ctx\r\n const entry = { def, plugin: ctx.fiber.name }\r\n ctx.effect(() => {\r\n this.ownCommands.add(entry)\r\n return () => this.ownCommands.delete(entry)\r\n }, `bot.command(${def.name})`)\r\n return this.middleware(async (session, next) => {\r\n const parsed = session.command\r\n if (!parsed || !commandMatches(def, parsed.name)) return next()\r\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\r\n if (!this.allows(def, session)) return\r\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\r\n if (!values.ok) {\r\n await session.reply(usageReply(def, parsed.prefix))\r\n return\r\n }\r\n await handler(session, values.values, parsed)\r\n })\r\n }\r\n\r\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\r\n middlewareOrder() {\r\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\r\n }\r\n\r\n /** Listens for adapter events that are not messages (notices, requests). */\r\n onEvent(handler: (event: BotEvent) => void) {\r\n return this.ctx.effect(() => {\r\n this.eventHandlers.add(handler)\r\n return () => this.eventHandlers.delete(handler)\r\n }, 'bot.onEvent()')\r\n }\r\n\r\n /** Called by adapters for non-message events. */\r\n dispatchEvent(event: BotEvent) {\r\n this.logEvent(event)\r\n for (const handler of this.eventHandlers) {\r\n try {\r\n handler(event)\r\n } catch (error) {\r\n this.ctx.logger('bot').warn(error)\r\n }\r\n }\r\n }\r\n\r\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\r\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\r\n const started = Date.now()\r\n const record = this.hooks.record({\r\n botId: this.id,\r\n messageId: message.messageId,\r\n direction: 'in',\r\n channel: message.channel,\r\n user: message.user,\r\n segments: message.segments,\r\n timestamp: message.timestamp ?? Date.now(),\r\n source: options.source ?? { kind: 'user' },\r\n })\r\n this.ctx.logger('message').info('received from %s%s: %s', who(record.user), record.channel.type === 'group' ? ` in ${chat(record.channel)}` : '', preview(record.segments))\r\n const session = new Session(this, record)\r\n const entry = session.command?.entry\r\n if (entry) {\r\n try {\r\n this.hooks.commandCalled?.(this, entry, session)\r\n } catch {}\r\n }\r\n const chain = [...this.middlewares]\r\n const appHandler = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\r\n if (entry?.source.kind === 'builtin' || appHandler) {\r\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\r\n const builtin: MiddlewareEntry = {\r\n plugin: appHandler ? entry!.source.id : BUILTIN_PLUGIN,\r\n priority: BUILTIN_PRIORITY,\r\n callback: async (view, next) => {\r\n if (!this.allows(entry!, view)) return next()\r\n if (appHandler) {\r\n await appHandler(view)\r\n return\r\n }\r\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\r\n if (answer !== undefined) await view.reply(answer)\r\n },\r\n }\r\n const index = chain.findIndex((item) => item.priority < builtin.priority)\r\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\r\n }\r\n /** The plugin that kept the message from the ones after it, if one did. */\r\n let stoppedAt: string | undefined\r\n const run = async (index: number): Promise<void> => {\r\n const entry = chain[index]\r\n if (!entry) return\r\n let passed = false\r\n try {\r\n await entry.callback(session.as(entry.plugin), () => {\r\n passed = true\r\n return run(index + 1)\r\n })\r\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\r\n } catch (error) {\r\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\r\n }\r\n }\r\n const outer = this.hooks.usageScope?.(this, record)\r\n const scope: UsageScope = {\r\n botId: this.id,\r\n messageId: record.id,\r\n report: (event) => {\r\n outer?.report(event)\r\n this.logUsage(event)\r\n },\r\n }\r\n await usage.run(scope, () => run(0))\r\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\r\n return session\r\n }\r\n\r\n /**\r\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\r\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\r\n */\r\n private logEvent(event: BotEvent) {\r\n const name = event.name ?? event.type\r\n const target = event.data?.target_id ?? undefined\r\n const parts = [\r\n event.user && `from ${who(event.user)}`,\r\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\r\n target !== undefined && target !== null && `to ${target}`,\r\n event.message?.text && `: ${preview(event.message.segments)}`,\r\n ].filter(Boolean).join(' ').replace(' :', ':')\r\n const quiet = !event.name || event.name === 'notify.input_status'\r\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\r\n }\r\n\r\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\r\n private logUsage(event: UsageEvent) {\r\n const logger = this.ctx.logger('llm')\r\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\r\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\r\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\r\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\r\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\r\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\r\n }\r\n\r\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\r\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\r\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\r\n }\r\n\r\n /** Raw adapter API, e.g. a NapCat extension action. */\r\n async call(action: string, params: Record<string, any> = {}) {\r\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\r\n return this.transport.call(action, params)\r\n }\r\n\r\n async deliver(\r\n channel: ChannelInfo,\r\n content: Sendable,\r\n options: { plugin?: string; source?: Provenance; replyTo?: string },\r\n ) {\r\n const sandbox = isSandbox(channel)\r\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\r\n let segments: Segment[]\r\n let source: Provenance | undefined = options.source\r\n if (isSourced(content)) {\r\n segments = content.segments ?? toSegments(content.text ?? '')\r\n source ??= content.source\r\n } else {\r\n segments = toSegments(content)\r\n }\r\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\r\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\r\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\r\n return\r\n }\r\n const started = Date.now()\r\n const logger = this.ctx.logger('message')\r\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\r\n let messageId: string | undefined\r\n try {\r\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\r\n } catch (error) {\r\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\r\n throw error\r\n }\r\n const ms = Date.now() - started\r\n const bytes = byteSize(segments)\r\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\r\n const record = this.hooks.record({\r\n botId: this.id,\r\n messageId,\r\n direction: 'out',\r\n channel,\r\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\r\n segments,\r\n timestamp: Date.now(),\r\n replyTo: options.replyTo,\r\n source,\r\n })\r\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause: usage.current()?.messageId })\r\n return record\r\n }\r\n}\r\n\r\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\r\nexport function byteSize(segments: Segment[]) {\r\n return Buffer.byteLength(JSON.stringify(segments))\r\n}\r\n\r\n/** A message on one line for the bot's log, cut to a readable length. */\r\nfunction preview(segments: Segment[]) {\r\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\r\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\r\n}\r\n\r\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\r\nfunction chat(channel: ChannelInfo) {\r\n if (isSandbox(channel)) return 'the sandbox'\r\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\r\n return channel.type === 'group' ? `group ${name}` : name\r\n}\r\n\r\nfunction who(user: UserInfo) {\r\n return user.name ? `${user.name} (${user.id})` : user.id\r\n}\r\n\r\nfunction duration(ms: number) {\r\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\r\n}\r\n\r\nfunction size(bytes: number) {\r\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`\r\n}\r\n"],"mappings":";;;;;AAmDA,MAAM,iBAAiB;;AAEvB,MAAa,mBAAmB;AAEhC,SAAS,UAAU,OAA0C;CAC3D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,UAAU;AAC7F;;AAGA,IAAa,UAAb,MAAqB;CAKA;CAAiB;;CAHpC;CACA;CAEA,YAAY,KAAiB,QAA8B;EAAxC,KAAA,MAAA;EAAiB,KAAA,SAAA;CAAwB;CAE5D,IAAI,UAAU;EACZ,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,OAAO;EACT,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO;CACrB;CAEA,IAAI,WAAW;EACb,OAAO,KAAK,OAAO,QAAQ,SAAS;CACtC;;CAGA,IAAI,YAAY;EACd,OAAO,KAAK,SAAS,MAAM,MAAM,EAAE,SAAS,QAAQ,OAAO,EAAE,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM;CAC3F;;CAGA,IAAI,UAAqC;EAEvC,KAAK,WAAW,EAAE,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