@mushinjs/plugin-bots 0.3.0 → 0.4.0-next.20261124175848

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bot.d.ts CHANGED
@@ -1,12 +1,24 @@
1
- import { BotEvent, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, ResolvedMedia, SourcedContent, Transport } from "./types.js";
1
+ import { BotEvent, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PluginRun, ResolvedMedia, SourcedContent, Transport } from "./types.js";
2
2
  import { ArgValue, CommandDef, CommandEntry, ParsedCommand } from "./commands.js";
3
- import { ChannelInfo, Content, Context, MessageRecord, Provenance, Segment, Service, UsageScope, UserInfo } from "@mushinjs/core";
3
+ import { ChannelInfo, Content, Context, Fiber, MessageRecord, Provenance, Segment, Service, UsageScope, UserInfo } from "@mushinjs/core";
4
4
  export type Sendable = Content | SourcedContent;
5
5
  export type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void;
6
6
  export interface MiddlewareOptions {
7
7
  /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */
8
8
  priority?: number;
9
+ /**
10
+ * False when the plugin keeps its own record of the messages it handles, as flows do with their runs.
11
+ * Otherwise each message the middleware answers, keeps from the plugins after it or fails on is a plugin run.
12
+ */
13
+ runs?: false;
9
14
  }
15
+ /** A command an app plugin answers on this bot, and the context that registered it. */
16
+ export interface AppCommandTarget {
17
+ handler: (session: Session) => Promise<unknown> | unknown;
18
+ fiber?: Fiber;
19
+ }
20
+ /** A plugin handled a message; the bot manager adds the id and the package. */
21
+ export type PluginRunReport = Omit<PluginRun, 'id' | 'botId'>;
10
22
  /** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */
11
23
  export interface BotHooks {
12
24
  record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord;
@@ -19,8 +31,10 @@ export interface BotHooks {
19
31
  builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined;
20
32
  /** The sender's role on this bot; nothing when the permissions plugin is not running. */
21
33
  roleOf?(bot: Bot, userId: string): BotRole | undefined;
22
- /** A command that an app plugin answers on every bot, such as `/persona`. */
23
- appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined;
34
+ /** A command that an app plugin answers on this bot, such as `/persona`. */
35
+ appCommand?(bot: Bot, entry: CommandEntry): AppCommandTarget | undefined;
36
+ /** A plugin replied to a message, kept it from the plugins after it, or failed on it. */
37
+ pluginRun?(bot: Bot, run: PluginRunReport, fiber?: Fiber): void;
24
38
  /** Where the costs of handling a message go; see `usage` in core. */
25
39
  usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined;
26
40
  /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */
@@ -74,12 +88,16 @@ export declare class Bot extends Service {
74
88
  selfName?: string;
75
89
  /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */
76
90
  selfAvatar?: string;
91
+ /** An address that adds the bot to a group or server (a Telegram start link, a Discord invite). */
92
+ invite?: string;
77
93
  record: BotRecord;
78
94
  private hooks;
79
95
  private transport?;
80
96
  private middlewares;
81
97
  private eventHandlers;
82
98
  private ownCommands;
99
+ /** Replies sent while each message is handled, by plugin: the message's record id → plugin name → count. */
100
+ private replying;
83
101
  private commandProviders;
84
102
  private roleResolver?;
85
103
  private mediaResolver?;
@@ -92,6 +110,8 @@ export declare class Bot extends Service {
92
110
  get platform(): string;
93
111
  setStatus(status: BotStatus, error?: string): void;
94
112
  setSelf(id: string, name?: string, avatar?: string): void;
113
+ /** Called by adapters once they know the address that adds the bot to a group or server. */
114
+ setInvite(url: string | undefined): void;
95
115
  /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */
96
116
  useTransport(transport: Transport): import("cordis").Disposable<Promise<void>>;
97
117
  /** Called by adapters that can tell a sender's group role (owner, admin, member). */
@@ -134,6 +154,11 @@ export declare class Bot extends Service {
134
154
  * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.
135
155
  */
136
156
  parseCommand(text: string): ParsedCommand | undefined;
157
+ /** The commands plugins of this bot registered with `bot.command()`, with the context of each. */
158
+ ownCommandList(): {
159
+ name: string;
160
+ fiber: Fiber;
161
+ }[];
137
162
  /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */
138
163
  localCommands(): CommandEntry[];
139
164
  /**
@@ -161,6 +186,7 @@ export declare class Bot extends Service {
161
186
  source?: Provenance;
162
187
  }): Promise<Session>;
163
188
  private handle;
189
+ private reportRun;
164
190
  /**
165
191
  * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the
166
192
  * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.
package/dist/bot.js CHANGED
@@ -97,12 +97,16 @@ var Bot = class extends Service {
97
97
  selfName;
98
98
  /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */
99
99
  selfAvatar;
100
+ /** An address that adds the bot to a group or server (a Telegram start link, a Discord invite). */
101
+ invite;
100
102
  record;
101
103
  hooks;
102
104
  transport;
103
105
  middlewares = [];
104
106
  eventHandlers = /* @__PURE__ */ new Set();
105
107
  ownCommands = /* @__PURE__ */ new Set();
108
+ /** Replies sent while each message is handled, by plugin: the message's record id → plugin name → count. */
109
+ replying = /* @__PURE__ */ new Map();
106
110
  commandProviders = /* @__PURE__ */ new Set();
107
111
  roleResolver;
108
112
  mediaResolver;
@@ -135,6 +139,12 @@ var Bot = class extends Service {
135
139
  this.selfAvatar = avatar;
136
140
  this.hooks.status(this);
137
141
  }
142
+ /** Called by adapters once they know the address that adds the bot to a group or server. */
143
+ setInvite(url) {
144
+ if (url === this.invite) return;
145
+ this.invite = url;
146
+ this.hooks.status(this);
147
+ }
138
148
  /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */
139
149
  useTransport(transport) {
140
150
  return this.ctx.effect(() => {
@@ -241,8 +251,10 @@ var Bot = class extends Service {
241
251
  const ctx = this.ctx;
242
252
  const entry = {
243
253
  plugin: ctx.fiber.name,
254
+ fiber: ctx.fiber,
244
255
  callback,
245
- priority: options.priority ?? 0
256
+ priority: options.priority ?? 0,
257
+ runs: options.runs
246
258
  };
247
259
  return ctx.effect(() => {
248
260
  const index = this.middlewares.findIndex((item) => item.priority < entry.priority);
@@ -280,6 +292,13 @@ var Bot = class extends Service {
280
292
  entry
281
293
  } : parsed;
282
294
  }
295
+ /** The commands plugins of this bot registered with `bot.command()`, with the context of each. */
296
+ ownCommandList() {
297
+ return [...this.ownCommands].map(({ def, fiber }) => ({
298
+ name: def.name,
299
+ fiber
300
+ }));
301
+ }
283
302
  /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */
284
303
  localCommands() {
285
304
  const entries = [...this.ownCommands].map(({ def, plugin }) => ({
@@ -317,7 +336,8 @@ var Bot = class extends Service {
317
336
  const ctx = this.ctx;
318
337
  const entry = {
319
338
  def,
320
- plugin: ctx.fiber.name
339
+ plugin: ctx.fiber.name,
340
+ fiber: ctx.fiber
321
341
  };
322
342
  ctx.effect(() => {
323
343
  this.ownCommands.add(entry);
@@ -391,15 +411,16 @@ var Bot = class extends Service {
391
411
  this.hooks.commandCalled?.(this, entry, session);
392
412
  } catch {}
393
413
  const chain = [...this.middlewares];
394
- const appHandler = entry?.source.kind === "plugin" ? this.hooks.appCommand?.(this, entry) : void 0;
395
- if (entry?.source.kind === "builtin" || appHandler) {
414
+ const app = entry?.source.kind === "plugin" ? this.hooks.appCommand?.(this, entry) : void 0;
415
+ if (entry?.source.kind === "builtin" || app) {
396
416
  const builtin = {
397
- plugin: appHandler ? entry.source.id : BUILTIN_PLUGIN,
417
+ plugin: app ? entry.source.id : BUILTIN_PLUGIN,
418
+ fiber: app ? app.fiber : this.ctx.fiber,
398
419
  priority: 5,
399
420
  callback: async (view, next) => {
400
421
  if (!this.allows(entry, view)) return next();
401
- if (appHandler) {
402
- await appHandler(view);
422
+ if (app) {
423
+ await app.handler(view);
403
424
  return;
404
425
  }
405
426
  const answer = this.hooks.builtinCommand?.(this, entry, view);
@@ -411,24 +432,75 @@ var Bot = class extends Service {
411
432
  }
412
433
  /** The plugin that kept the message from the ones after it, if one did. */
413
434
  let stoppedAt;
435
+ const replies = /* @__PURE__ */ new Map();
436
+ this.replying.set(record.id, replies);
414
437
  const run = async (index) => {
415
438
  const entry = chain[index];
416
439
  if (!entry) return;
417
440
  let passed = false;
441
+ let failure;
442
+ const began = Date.now();
443
+ const sent = () => replies.get(entry.plugin) ?? 0;
444
+ const sentBefore = sent();
445
+ let laterMs = 0;
446
+ let laterSent = 0;
418
447
  try {
419
- await entry.callback(session.as(entry.plugin), () => {
448
+ await entry.callback(session.as(entry.plugin), async () => {
420
449
  passed = true;
421
- return run(index + 1);
450
+ const at = Date.now();
451
+ const before = sent();
452
+ try {
453
+ await run(index + 1);
454
+ } finally {
455
+ laterMs += Date.now() - at;
456
+ laterSent += sent() - before;
457
+ }
422
458
  });
423
459
  if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin;
424
460
  } catch (error) {
461
+ failure = error;
425
462
  this.ctx.logger("bot").warn("middleware of %s failed: %s", entry.plugin, error);
426
463
  }
464
+ const own = sent() - sentBefore - laterSent;
465
+ const kept = !passed && !failure && index < chain.length - 1;
466
+ if (entry.runs !== false && (own || kept || failure)) this.reportRun(entry, session, {
467
+ began,
468
+ ms: Date.now() - began - laterMs,
469
+ replies: own,
470
+ kept,
471
+ failure
472
+ });
427
473
  };
428
- await run(0);
474
+ try {
475
+ await run(0);
476
+ } finally {
477
+ this.replying.delete(record.id);
478
+ }
429
479
  this.ctx.logger("bot").info("processed in %s%s", duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : "");
430
480
  return session;
431
481
  }
482
+ reportRun(entry, session, result) {
483
+ const command = session.command?.entry;
484
+ const text = session.text;
485
+ try {
486
+ this.hooks.pluginRun?.(this, {
487
+ plugin: entry.plugin,
488
+ ...command && answers(command, entry.plugin) ? { command: command.name } : {},
489
+ text: text.length > 200 ? `${text.slice(0, 200)}…` : text,
490
+ user: session.user,
491
+ channel: `${session.channel.type}:${session.channel.id}`,
492
+ message: session.record.id,
493
+ status: result.failure ? "error" : "ok",
494
+ replies: result.replies,
495
+ kept: result.kept,
496
+ startedAt: result.began,
497
+ ms: result.ms,
498
+ ...result.failure ? { error: result.failure instanceof Error ? result.failure.message : String(result.failure) } : {}
499
+ }, entry.fiber);
500
+ } catch (error) {
501
+ this.ctx.logger("bot").debug("recording what %s did failed: %s", entry.plugin, error);
502
+ }
503
+ }
432
504
  /**
433
505
  * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the
434
506
  * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.
@@ -518,11 +590,14 @@ var Bot = class extends Service {
518
590
  replyTo: options.replyTo,
519
591
  source
520
592
  });
593
+ const cause = usage.current()?.messageId;
521
594
  this.hooks.sent?.(this, record, {
522
595
  bytes,
523
596
  ...sandbox ? {} : { ms },
524
- cause: usage.current()?.messageId
597
+ cause
525
598
  });
599
+ const replies = cause ? this.replying.get(cause) : void 0;
600
+ if (replies && options.plugin) replies.set(options.plugin, (replies.get(options.plugin) ?? 0) + 1);
526
601
  return record;
527
602
  }
528
603
  };
@@ -530,6 +605,10 @@ var Bot = class extends Service {
530
605
  function byteSize(segments) {
531
606
  return Buffer.byteLength(JSON.stringify(segments));
532
607
  }
608
+ /** Whether a plugin is the one answering a command: the plugin that registered it, or the bots plugin for `/help`. */
609
+ function answers(command, plugin) {
610
+ return command.source.kind === "builtin" ? plugin === BUILTIN_PLUGIN : command.source.kind === "plugin" && command.source.id === plugin;
611
+ }
533
612
  /** A message on one line for the bot's log, cut to a readable length. */
534
613
  function preview(segments) {
535
614
  const text = segmentsToText(segments).replace(/\s+/g, " ").trim();
package/dist/bot.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\n type ChannelInfo, type Content, Context, type MessageRecord, type Provenance, type Segment, segmentsToText,\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\n} from '@mushinjs/core'\nimport {\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\n usageReply,\n} from './commands'\nimport {\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\n type MediaResolver, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\n} from './types'\n\nexport type Sendable = Content | SourcedContent\n\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\n\ninterface MiddlewareEntry {\n plugin: string\n callback: Middleware\n priority: number\n}\n\nexport interface MiddlewareOptions {\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\n priority?: number\n}\n\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\nexport interface BotHooks {\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\n status(bot: Bot): void\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\n commands?(bot: Bot): CommandEntry[]\n /** A message ran a registered command. */\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\n /** The answer to a built-in command such as `/help`. */\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\n roleOf?(bot: Bot, userId: string): BotRole | undefined\n /** A command that an app plugin answers on every bot, such as `/persona`. */\n appCommand?(bot: Bot, entry: CommandEntry): ((session: Session) => Promise<unknown> | unknown) | undefined\n /** Where the costs of handling a message go; see `usage` in core. */\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\n}\n\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\n\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\nconst BUILTIN_PLUGIN = 'bots'\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\nexport const BUILTIN_PRIORITY = 5\n\nfunction isSourced(value: Sendable): value is SourcedContent {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\n}\n\n/** One incoming message, as seen by a bot plugin's middleware. */\nexport class Session {\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\n plugin?: string\n private parsed?: { value: ParsedCommand | undefined }\n\n constructor(public bot: Bot, public record: MessageRecord) {}\n\n get channel() {\n return this.record.channel\n }\n\n get user() {\n return this.record.user\n }\n\n get segments() {\n return this.record.segments\n }\n\n get isDirect() {\n return this.record.channel.type === 'private'\n }\n\n /** True when the message @-mentions this bot. */\n get mentioned() {\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\n }\n\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\n get command(): ParsedCommand | undefined {\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\n return this.parsed.value\n }\n\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\n role(): BotRole | undefined {\n return this.bot.roleOf(this.user.id)\n }\n\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\n groupRole(): Promise<GroupRole | undefined> {\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\n }\n\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\n get isAdmin() {\n return roleAtLeast(this.role(), 'admin')\n }\n\n /** Plain text with mentions of this bot removed. */\n get text() {\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\n return segmentsToText(segments).trim()\n }\n\n send(content: Sendable) {\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\n }\n\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\n reply(content: Sendable) {\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\n if (isSourced(content)) {\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\n }\n return this.send([...quote, ...toSegments(content)])\n }\n\n /** A view of this session attributed to another plugin. */\n as(plugin: string) {\n const view = Object.create(this) as Session\n view.plugin = plugin\n return view\n }\n}\n\n/**\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\n * always means that plugin's bot.\n */\nexport class Bot extends Service {\n status: BotStatus = 'offline'\n error?: string\n selfId?: string\n selfName?: string\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\n selfAvatar?: string\n record: BotRecord\n private hooks: BotHooks\n private transport?: Transport\n private middlewares: MiddlewareEntry[] = []\n private eventHandlers = new Set<(event: BotEvent) => void>()\n private ownCommands = new Set<{ def: CommandDef; plugin: string }>()\n private commandProviders = new Set<() => CommandEntry[]>()\n private roleResolver?: GroupRoleResolver\n private mediaResolver?: MediaResolver\n private contactResolver?: ContactResolver\n\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\n super(ctx, 'bot')\n this.record = config.record\n this.hooks = config.hooks\n }\n\n get id() {\n return this.record.id\n }\n\n get platform() {\n return this.record.adapter.type\n }\n\n setStatus(status: BotStatus, error?: string) {\n const nextError = status === 'error' ? error : undefined\n if (status !== this.status || nextError !== this.error) {\n const logger = this.ctx.logger('bot')\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\n else logger.info('status: %s', status)\n }\n this.status = status\n this.error = status === 'error' ? error : undefined\n this.hooks.status(this)\n }\n\n setSelf(id: string, name?: string, avatar?: string) {\n this.selfId = id\n this.selfName = name\n this.selfAvatar = avatar\n this.hooks.status(this)\n }\n\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\n useTransport(transport: Transport) {\n return this.ctx.effect(() => {\n this.transport = transport\n return () => {\n if (this.transport !== transport) return\n this.transport = undefined\n this.setStatus('offline')\n }\n }, 'bot.useTransport()')\n }\n\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\n useRoleResolver(resolver: GroupRoleResolver) {\n return this.ctx.effect(() => {\n this.roleResolver = resolver\n return () => {\n if (this.roleResolver === resolver) this.roleResolver = undefined\n }\n }, 'bot.useRoleResolver()')\n }\n\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\n useMediaResolver(resolver: MediaResolver) {\n return this.ctx.effect(() => {\n this.mediaResolver = resolver\n return () => {\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\n }\n }, 'bot.useMediaResolver()')\n }\n\n /** Called by adapters that can list the account's friends and groups. */\n useContacts(resolver: ContactResolver) {\n return this.ctx.effect(() => {\n this.contactResolver = resolver\n return () => {\n if (this.contactResolver === resolver) this.contactResolver = undefined\n }\n }, 'bot.useContacts()')\n }\n\n /** The account's friends and groups; empty when the adapter cannot list them. */\n async contacts() {\n return this.contactResolver ? this.contactResolver() : []\n }\n\n /**\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\n */\n sandbox(text: string) {\n const mention = /^@\\S*\\s*/.exec(text)\n const rest = mention ? text.slice(mention[0].length) : text\n const segments: Segment[] = [\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\n ]\n // Not awaited: a flow may wait for the next message, which comes through another call.\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\n })\n }\n\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\n }\n\n /** The messages of a forwarded chat history. */\n async forward(id: string) {\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\n return this.mediaResolver.forward(id)\n }\n\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\n roleOf(userId: string): BotRole | undefined {\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\n if (userId === SANDBOX_USER.id) return 'master'\n return this.hooks.roleOf?.(this, userId)\n }\n\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\n if (target.channel.type !== 'group' || !target.user.id) return\n if (target.user.role) return target.user.role\n try {\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\n } catch (error) {\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\n }\n }\n\n /** Whether a command's role requirement lets this session run it; logs why not. */\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\n const required = requiredRole(def)\n if (!required) return true\n const role = session.role()\n if (role === undefined) {\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\n return false\n }\n return roleAtLeast(role, required)\n }\n\n /** Registers middleware for incoming messages; runs in registration order. */\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\n const ctx = this.ctx\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, callback, priority: options.priority ?? 0 }\n return ctx.effect(() => {\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\n if (index < 0) this.middlewares.push(entry)\n else this.middlewares.splice(index, 0, entry)\n return () => {\n const index = this.middlewares.indexOf(entry)\n if (index >= 0) this.middlewares.splice(index, 1)\n }\n }, 'bot.middleware()')\n }\n\n get prefixes() {\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\n }\n\n /**\n * Splits text into a command, with the registered command it names. Commands with prefixes of\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\n */\n parseCommand(text: string): ParsedCommand | undefined {\n const entries = this.hooks.commands?.(this) ?? []\n for (const entry of entries) {\n if (!entry.prefixes?.length) continue\n const parsed = splitCommand(text, entry.prefixes)\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\n }\n const parsed = splitCommand(text, this.prefixes)\n if (!parsed) return\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\n return entry ? { ...parsed, entry } : parsed\n }\n\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\n localCommands(): CommandEntry[] {\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider())\n } catch (error) {\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\n }\n }\n return entries\n }\n\n /**\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\n */\n defineCommands(provider: () => CommandEntry[]) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bot.defineCommands()')\n }\n\n /**\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\n * replies with how to write the command.\n */\n command(def: CommandDef, handler: CommandHandler) {\n const ctx = this.ctx\n const entry = { def, plugin: ctx.fiber.name }\n ctx.effect(() => {\n this.ownCommands.add(entry)\n return () => this.ownCommands.delete(entry)\n }, `bot.command(${def.name})`)\n return this.middleware(async (session, next) => {\n const parsed = session.command\n if (!parsed || !commandMatches(def, parsed.name)) return next()\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\n if (!this.allows(def, session)) return\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\n if (!values.ok) {\n await session.reply(usageReply(def, parsed.prefix))\n return\n }\n await handler(session, values.values, parsed)\n })\n }\n\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\n middlewareOrder() {\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\n }\n\n /** Listens for adapter events that are not messages (notices, requests). */\n onEvent(handler: (event: BotEvent) => void) {\n return this.ctx.effect(() => {\n this.eventHandlers.add(handler)\n return () => this.eventHandlers.delete(handler)\n }, 'bot.onEvent()')\n }\n\n /** Called by adapters for non-message events. */\n dispatchEvent(event: BotEvent) {\n this.logEvent(event)\n for (const handler of this.eventHandlers) {\n try {\n handler(event)\n } catch (error) {\n this.ctx.logger('bot').warn(error)\n }\n }\n }\n\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\n const started = Date.now()\n const record = this.hooks.record({\n botId: this.id,\n messageId: message.messageId,\n direction: 'in',\n channel: message.channel,\n user: message.user,\n segments: message.segments,\n timestamp: message.timestamp ?? Date.now(),\n source: options.source ?? { kind: 'user' },\n })\n // Everything logged or spent while handling the message is tied to its record id.\n const outer = this.hooks.usageScope?.(this, record)\n const scope: UsageScope = {\n botId: this.id,\n messageId: record.id,\n report: (event) => {\n outer?.report(event)\n this.logUsage(event)\n },\n }\n return usage.run(scope, () => this.handle(record, started))\n }\n\n private async handle(record: MessageRecord, started: number) {\n this.ctx.logger('message').info('received from %s%s: %s', who(record.user), record.channel.type === 'group' ? ` in ${chat(record.channel)}` : '', preview(record.segments))\n const session = new Session(this, record)\n const entry = session.command?.entry\n if (entry) {\n try {\n this.hooks.commandCalled?.(this, entry, session)\n } catch {}\n }\n const chain = [...this.middlewares]\n const appHandler = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\n if (entry?.source.kind === 'builtin' || appHandler) {\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\n const builtin: MiddlewareEntry = {\n plugin: appHandler ? entry!.source.id : BUILTIN_PLUGIN,\n priority: BUILTIN_PRIORITY,\n callback: async (view, next) => {\n if (!this.allows(entry!, view)) return next()\n if (appHandler) {\n await appHandler(view)\n return\n }\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\n if (answer !== undefined) await view.reply(answer)\n },\n }\n const index = chain.findIndex((item) => item.priority < builtin.priority)\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\n }\n /** The plugin that kept the message from the ones after it, if one did. */\n let stoppedAt: string | undefined\n const run = async (index: number): Promise<void> => {\n const entry = chain[index]\n if (!entry) return\n let passed = false\n try {\n await entry.callback(session.as(entry.plugin), () => {\n passed = true\n return run(index + 1)\n })\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\n } catch (error) {\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\n }\n }\n await run(0)\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\n return session\n }\n\n /**\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\n */\n private logEvent(event: BotEvent) {\n const name = event.name ?? event.type\n const target = event.data?.target_id ?? undefined\n const parts = [\n event.user && `from ${who(event.user)}`,\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\n target !== undefined && target !== null && `to ${target}`,\n event.message?.text && `: ${preview(event.message.segments)}`,\n ].filter(Boolean).join(' ').replace(' :', ':')\n const quiet = !event.name || event.name === 'notify.input_status'\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\n }\n\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\n private logUsage(event: UsageEvent) {\n const logger = this.ctx.logger('llm')\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\n }\n\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\n }\n\n /** Raw adapter API, e.g. a NapCat extension action. */\n async call(action: string, params: Record<string, any> = {}) {\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\n return this.transport.call(action, params)\n }\n\n async deliver(\n channel: ChannelInfo,\n content: Sendable,\n options: { plugin?: string; source?: Provenance; replyTo?: string },\n ) {\n const sandbox = isSandbox(channel)\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\n let segments: Segment[]\n let source: Provenance | undefined = options.source\n if (isSourced(content)) {\n segments = content.segments ?? toSegments(content.text ?? '')\n source ??= content.source\n } else {\n segments = toSegments(content)\n }\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\n return\n }\n const started = Date.now()\n const logger = this.ctx.logger('message')\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\n let messageId: string | undefined\n try {\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\n } catch (error) {\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\n throw error\n }\n const ms = Date.now() - started\n const bytes = byteSize(segments)\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\n const record = this.hooks.record({\n botId: this.id,\n messageId,\n direction: 'out',\n channel,\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\n segments,\n timestamp: Date.now(),\n replyTo: options.replyTo,\n source,\n })\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause: usage.current()?.messageId })\n return record\n }\n}\n\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\nexport function byteSize(segments: Segment[]) {\n return Buffer.byteLength(JSON.stringify(segments))\n}\n\n/** A message on one line for the bot's log, cut to a readable length. */\nfunction preview(segments: Segment[]) {\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\n}\n\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\nfunction chat(channel: ChannelInfo) {\n if (isSandbox(channel)) return 'the sandbox'\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\n return channel.type === 'group' ? `group ${name}` : name\n}\n\nfunction who(user: UserInfo) {\n return user.name ? `${user.name} (${user.id})` : user.id\n}\n\nfunction duration(ms: number) {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\n}\n\nfunction size(bytes: number) {\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`\n}\n"],"mappings":";;;;;AAmDA,MAAM,iBAAiB;;AAEvB,MAAa,mBAAmB;AAEhC,SAAS,UAAU,OAA0C;CAC3D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,UAAU;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AS,SAAS;AACtD;AAEA,SAAS,IAAI,MAAgB;CAC3B,OAAO,KAAK,OAAO,GAAG,KAAK,KAAK,IAAI,KAAK,GAAG,KAAK,KAAK;AACxD;AAEA,SAAS,SAAS,IAAY;CAC5B,OAAO,KAAK,MAAO,GAAG,GAAG,MAAM,IAAI,KAAK,IAAA,CAAM,QAAQ,KAAK,MAAQ,IAAI,CAAC,EAAE;AAC5E;AAEA,SAAS,KAAK,OAAe;CAC3B,OAAO,QAAQ,OAAO,GAAG,MAAM,MAAM,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE;AACpE"}
1
+ {"version":3,"file":"bot.js","names":[],"sources":["../src/bot.ts"],"sourcesContent":["import {\n type ChannelInfo, type Content, Context, type Fiber, type MessageRecord, type Provenance, type Segment, segmentsToText,\n randomId, Service, seg, toSegments, usage, type UsageEvent, type UsageScope, type UserInfo,\n} from '@mushinjs/core'\nimport {\n type ArgValue, type CommandDef, type CommandEntry, commandMatches, DEFAULT_PREFIXES, parseArgs, type ParsedCommand, requiredRole, splitCommand,\n usageReply,\n} from './commands'\nimport {\n type BotEvent, type BotRecord, type BotRole, type BotStatus, type ContactResolver, type GroupRole, type GroupRoleResolver, type IncomingMessage, isSandbox,\n type MediaResolver, type PluginRun, roleAtLeast, SANDBOX_CHANNEL, SANDBOX_USER, type SourcedContent, type Transport,\n} from './types'\n\nexport type Sendable = Content | SourcedContent\n\nexport type Middleware = (session: Session, next: () => Promise<void>) => Promise<void> | void\n\ninterface MiddlewareEntry {\n plugin: string\n /** The context that registered it, to tell which installed plugin it belongs to. */\n fiber?: Fiber\n callback: Middleware\n priority: number\n /** False when the plugin keeps its own record of what it handled, as flows do. */\n runs?: false\n}\n\nexport interface MiddlewareOptions {\n /** Higher runs earlier; plugins with the same priority run in registration order. Default 0. */\n priority?: number\n /**\n * False when the plugin keeps its own record of the messages it handles, as flows do with their runs.\n * Otherwise each message the middleware answers, keeps from the plugins after it or fails on is a plugin run.\n */\n runs?: false\n}\n\n/** A command an app plugin answers on this bot, and the context that registered it. */\nexport interface AppCommandTarget {\n handler: (session: Session) => Promise<unknown> | unknown\n fiber?: Fiber\n}\n\n/** A plugin handled a message; the bot manager adds the id and the package. */\nexport type PluginRunReport = Omit<PluginRun, 'id' | 'botId'>\n\n/** Supplied by the bot manager: `record` stores and broadcasts a message, `status` reports changes. */\nexport interface BotHooks {\n record(record: Omit<MessageRecord, 'id' | 'type' | 'platforms'>): MessageRecord\n status(bot: Bot): void\n /** Every command registered on this bot, from flows, plugins and the built-in help. */\n commands?(bot: Bot): CommandEntry[]\n /** A message ran a registered command. */\n commandCalled?(bot: Bot, entry: CommandEntry, session: Session): void\n /** The answer to a built-in command such as `/help`. */\n builtinCommand?(bot: Bot, entry: CommandEntry, session: Session): string | undefined\n /** The sender's role on this bot; nothing when the permissions plugin is not running. */\n roleOf?(bot: Bot, userId: string): BotRole | undefined\n /** A command that an app plugin answers on this bot, such as `/persona`. */\n appCommand?(bot: Bot, entry: CommandEntry): AppCommandTarget | undefined\n /** A plugin replied to a message, kept it from the plugins after it, or failed on it. */\n pluginRun?(bot: Bot, run: PluginRunReport, fiber?: Fiber): void\n /** Where the costs of handling a message go; see `usage` in core. */\n usageScope?(bot: Bot, record: MessageRecord): UsageScope | undefined\n /** An outgoing message was sent: its size, how long the platform took (not for the sandbox), and the message being handled. */\n sent?(bot: Bot, record: MessageRecord, transfer: { bytes: number; ms?: number; cause?: string }): void\n}\n\nexport type CommandHandler = (session: Session, args: Record<string, ArgValue>, command: ParsedCommand) => Promise<unknown> | unknown\n\n/** Replies from built-in commands such as `/help` are attributed to the bots plugin. */\nconst BUILTIN_PLUGIN = 'bots'\n/** Built-in commands answer after flows (priority 10) and before plugins with the default priority. */\nexport const BUILTIN_PRIORITY = 5\n\nfunction isSourced(value: Sendable): value is SourcedContent {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && !('type' in value)\n}\n\n/** One incoming message, as seen by a bot plugin's middleware. */\nexport class Session {\n /** Name of the plugin whose middleware is handling this session; replies are attributed to it. */\n plugin?: string\n private parsed?: { value: ParsedCommand | undefined }\n\n constructor(public bot: Bot, public record: MessageRecord) {}\n\n get channel() {\n return this.record.channel\n }\n\n get user() {\n return this.record.user\n }\n\n get segments() {\n return this.record.segments\n }\n\n get isDirect() {\n return this.record.channel.type === 'private'\n }\n\n /** True when the message @-mentions this bot. */\n get mentioned() {\n return this.segments.some((s) => s.type === 'at' && String(s.data.qq) === this.bot.selfId)\n }\n\n /** The command this message runs, such as `/score 85`, split by the bot's prefixes. */\n get command(): ParsedCommand | undefined {\n // Read once when the message arrives, before plugin views of the session exist, so they share it.\n this.parsed ??= { value: this.bot.parseCommand(this.text) }\n return this.parsed.value\n }\n\n /** The sender's role on this bot (master, admin or user); nothing when the permissions plugin is off. */\n role(): BotRole | undefined {\n return this.bot.roleOf(this.user.id)\n }\n\n /** The sender's role in this group, when the adapter can tell; nothing in private chats. */\n groupRole(): Promise<GroupRole | undefined> {\n return this.bot.groupRoleOf({ channel: this.channel, user: this.user })\n }\n\n /** True when the sender is an admin or master of the bot, who may run admin-only commands. */\n get isAdmin() {\n return roleAtLeast(this.role(), 'admin')\n }\n\n /** Plain text with mentions of this bot removed. */\n get text() {\n const segments = this.segments.filter((s) => !(s.type === 'at' && String(s.data.qq) === this.bot.selfId))\n return segmentsToText(segments).trim()\n }\n\n send(content: Sendable) {\n return this.bot.deliver(this.channel, content, { plugin: this.plugin, replyTo: this.record.id })\n }\n\n /** Sends with a reply reference to the incoming message, when the platform supports it. */\n reply(content: Sendable) {\n const quote: Segment[] = this.record.messageId ? [{ type: 'reply', data: { id: this.record.messageId } }] : []\n if (isSourced(content)) {\n return this.send({ ...content, segments: [...quote, ...(content.segments ?? toSegments(content.text ?? ''))] })\n }\n return this.send([...quote, ...toSegments(content)])\n }\n\n /** A view of this session attributed to another plugin. */\n as(plugin: string) {\n const view = Object.create(this) as Session\n view.plugin = plugin\n return view\n }\n}\n\n/**\n * The `bot` service. Each bot runs in its own isolated context, so `ctx.bot` in a bot plugin\n * always means that plugin's bot.\n */\nexport class Bot extends Service {\n status: BotStatus = 'offline'\n error?: string\n selfId?: string\n selfName?: string\n /** The account's picture, as a URL the dashboard can load; adapters set it when the platform has one. */\n selfAvatar?: string\n /** An address that adds the bot to a group or server (a Telegram start link, a Discord invite). */\n invite?: string\n record: BotRecord\n private hooks: BotHooks\n private transport?: Transport\n private middlewares: MiddlewareEntry[] = []\n private eventHandlers = new Set<(event: BotEvent) => void>()\n private ownCommands = new Set<{ def: CommandDef; plugin: string; fiber: Fiber }>()\n /** Replies sent while each message is handled, by plugin: the message's record id → plugin name → count. */\n private replying = new Map<string, Map<string, number>>()\n private commandProviders = new Set<() => CommandEntry[]>()\n private roleResolver?: GroupRoleResolver\n private mediaResolver?: MediaResolver\n private contactResolver?: ContactResolver\n\n constructor(ctx: Context, config: { record: BotRecord; hooks: BotHooks }) {\n super(ctx, 'bot')\n this.record = config.record\n this.hooks = config.hooks\n }\n\n get id() {\n return this.record.id\n }\n\n get platform() {\n return this.record.adapter.type\n }\n\n setStatus(status: BotStatus, error?: string) {\n const nextError = status === 'error' ? error : undefined\n if (status !== this.status || nextError !== this.error) {\n const logger = this.ctx.logger('bot')\n if (status === 'error') logger.warn('status: error (%s)', error ?? 'no details')\n else logger.info('status: %s', status)\n }\n this.status = status\n this.error = status === 'error' ? error : undefined\n this.hooks.status(this)\n }\n\n setSelf(id: string, name?: string, avatar?: string) {\n this.selfId = id\n this.selfName = name\n this.selfAvatar = avatar\n this.hooks.status(this)\n }\n\n /** Called by adapters once they know the address that adds the bot to a group or server. */\n setInvite(url: string | undefined) {\n if (url === this.invite) return\n this.invite = url\n this.hooks.status(this)\n }\n\n /** Called by adapters. Removed, and the bot marked offline, when the adapter unloads. */\n useTransport(transport: Transport) {\n return this.ctx.effect(() => {\n this.transport = transport\n return () => {\n if (this.transport !== transport) return\n this.transport = undefined\n this.setStatus('offline')\n }\n }, 'bot.useTransport()')\n }\n\n /** Called by adapters that can tell a sender's group role (owner, admin, member). */\n useRoleResolver(resolver: GroupRoleResolver) {\n return this.ctx.effect(() => {\n this.roleResolver = resolver\n return () => {\n if (this.roleResolver === resolver) this.roleResolver = undefined\n }\n }, 'bot.useRoleResolver()')\n }\n\n /** Called by adapters that can fetch a message's media and forwarded chat histories. */\n useMediaResolver(resolver: MediaResolver) {\n return this.ctx.effect(() => {\n this.mediaResolver = resolver\n return () => {\n if (this.mediaResolver === resolver) this.mediaResolver = undefined\n }\n }, 'bot.useMediaResolver()')\n }\n\n /** Called by adapters that can list the account's friends and groups. */\n useContacts(resolver: ContactResolver) {\n return this.ctx.effect(() => {\n this.contactResolver = resolver\n return () => {\n if (this.contactResolver === resolver) this.contactResolver = undefined\n }\n }, 'bot.useContacts()')\n }\n\n /** The account's friends and groups; empty when the adapter cannot list them. */\n async contacts() {\n return this.contactResolver ? this.contactResolver() : []\n }\n\n /**\n * A message from the sandbox's test user, as if they wrote it to the bot in a private chat. A\n * leading \"@\" mentions the bot. Replies stay in the sandbox and never reach the platform.\n */\n sandbox(text: string) {\n const mention = /^@\\S*\\s*/.exec(text)\n const rest = mention ? text.slice(mention[0].length) : text\n const segments: Segment[] = [\n ...(mention ? [seg.at(this.selfId ?? this.id, this.selfName ?? this.record.name)] : []),\n ...(rest ? [seg.text(mention ? ` ${rest}` : rest)] : []),\n ]\n // Not awaited: a flow may wait for the next message, which comes through another call.\n this.receive({ messageId: randomId(6), channel: SANDBOX_CHANNEL, user: SANDBOX_USER, segments }).catch((error) => {\n this.ctx.logger('bot').warn('sandbox message failed: %s', error)\n })\n }\n\n /** An address for an image, video, voice or file segment; see `MediaResolver.media`. */\n async media(segment: Segment, options: { channel?: ChannelInfo; inline?: boolean } = {}) {\n if (!this.mediaResolver?.media) throw new Error(`the ${this.platform} adapter cannot fetch media`)\n return this.mediaResolver.media(segment, { channel: options.channel, inline: options.inline ?? false })\n }\n\n /** The messages of a forwarded chat history. */\n async forward(id: string) {\n if (!this.mediaResolver?.forward) throw new Error(`the ${this.platform} adapter cannot read forwarded messages`)\n return this.mediaResolver.forward(id)\n }\n\n /** The user's role on this bot, from the permissions plugin; nothing when it is not running. */\n roleOf(userId: string): BotRole | undefined {\n // Whoever plays the sandbox's test user is signed in to the dashboard, so they own the bot.\n if (userId === SANDBOX_USER.id) return 'master'\n return this.hooks.roleOf?.(this, userId)\n }\n\n /** A sender's group role: from the message when the platform sent it, else from the adapter. */\n async groupRoleOf(target: { channel: ChannelInfo; user: { id: string; role?: GroupRole } }): Promise<GroupRole | undefined> {\n if (target.channel.type !== 'group' || !target.user.id) return\n if (target.user.role) return target.user.role\n try {\n return await this.roleResolver?.({ channel: target.channel, user: target.user })\n } catch (error) {\n this.ctx.logger('bot').debug('group role of %s: %s', target.user.id, error)\n }\n }\n\n /** Whether a command's role requirement lets this session run it; logs why not. */\n allows(def: Pick<CommandDef, 'name' | 'permission' | 'role'>, session: Session) {\n const required = requiredRole(def)\n if (!required) return true\n const role = session.role()\n if (role === undefined) {\n this.ctx.logger('bot').debug('/%s needs %s, but the permissions plugin is not running; ignored', def.name, required)\n return false\n }\n return roleAtLeast(role, required)\n }\n\n /** Registers middleware for incoming messages; runs in registration order. */\n middleware(callback: Middleware, options: MiddlewareOptions = {}) {\n const ctx = this.ctx\n const entry: MiddlewareEntry = { plugin: ctx.fiber.name, fiber: ctx.fiber, callback, priority: options.priority ?? 0, runs: options.runs }\n return ctx.effect(() => {\n // Insert after every entry with the same or higher priority, keeping registration order within a priority.\n const index = this.middlewares.findIndex((item) => item.priority < entry.priority)\n if (index < 0) this.middlewares.push(entry)\n else this.middlewares.splice(index, 0, entry)\n return () => {\n const index = this.middlewares.indexOf(entry)\n if (index >= 0) this.middlewares.splice(index, 1)\n }\n }, 'bot.middleware()')\n }\n\n get prefixes() {\n const prefixes = this.record.commands?.prefixes?.filter(Boolean)\n return prefixes?.length ? prefixes : DEFAULT_PREFIXES\n }\n\n /**\n * Splits text into a command, with the registered command it names. Commands with prefixes of\n * their own (such as `#`) are matched by those only; the rest by the bot's prefixes.\n */\n parseCommand(text: string): ParsedCommand | undefined {\n const entries = this.hooks.commands?.(this) ?? []\n for (const entry of entries) {\n if (!entry.prefixes?.length) continue\n const parsed = splitCommand(text, entry.prefixes)\n if (parsed && commandMatches(entry, parsed.name)) return { ...parsed, entry }\n }\n const parsed = splitCommand(text, this.prefixes)\n if (!parsed) return\n const entry = entries.find((item) => !item.prefixes?.length && commandMatches(item, parsed.name))\n return entry ? { ...parsed, entry } : parsed\n }\n\n /** The commands plugins of this bot registered with `bot.command()`, with the context of each. */\n ownCommandList() {\n return [...this.ownCommands].map(({ def, fiber }) => ({ name: def.name, fiber }))\n }\n\n /** Commands that plugins of this bot registered with `bot.command()` or `bot.defineCommands()`. */\n localCommands(): CommandEntry[] {\n const entries: CommandEntry[] = [...this.ownCommands].map(({ def, plugin }) => ({ ...def, botId: this.id, source: { kind: 'plugin', id: plugin, name: plugin } }))\n for (const provider of this.commandProviders) {\n try {\n entries.push(...provider())\n } catch (error) {\n this.ctx.logger('bot').warn('listing commands failed: %s', error)\n }\n }\n return entries\n }\n\n /**\n * Lists commands that a plugin answers itself, e.g. the command nodes of the flows on this bot,\n * so they show in `/help` and the command list. Removed when the calling plugin unloads.\n */\n defineCommands(provider: () => CommandEntry[]) {\n return this.ctx.effect(() => {\n this.commandProviders.add(provider)\n return () => this.commandProviders.delete(provider)\n }, 'bot.defineCommands()')\n }\n\n /**\n * Registers a command, e.g. `bot.command({ name: 'roll', args: [{ name: 'sides', type: 'number', optional: true }] }, handler)`.\n * It shows in `/help`, and the handler gets the parsed arguments; when they do not fit, the bot\n * replies with how to write the command.\n */\n command(def: CommandDef, handler: CommandHandler) {\n const ctx = this.ctx\n const entry = { def, plugin: ctx.fiber.name, fiber: ctx.fiber }\n ctx.effect(() => {\n this.ownCommands.add(entry)\n return () => this.ownCommands.delete(entry)\n }, `bot.command(${def.name})`)\n return this.middleware(async (session, next) => {\n const parsed = session.command\n if (!parsed || !commandMatches(def, parsed.name)) return next()\n if (def.prefixes?.length ? !def.prefixes.includes(parsed.prefix) : parsed.entry?.prefixes?.length) return next()\n if (!this.allows(def, session)) return\n const values = parseArgs(def.args ?? [], parsed.rest, session.segments)\n if (!values.ok) {\n await session.reply(usageReply(def, parsed.prefix))\n return\n }\n await handler(session, values.values, parsed)\n })\n }\n\n /** The plugins whose middleware sees incoming messages, in the order they see them. */\n middlewareOrder() {\n return this.middlewares.map(({ plugin, priority }) => ({ plugin, priority }))\n }\n\n /** Listens for adapter events that are not messages (notices, requests). */\n onEvent(handler: (event: BotEvent) => void) {\n return this.ctx.effect(() => {\n this.eventHandlers.add(handler)\n return () => this.eventHandlers.delete(handler)\n }, 'bot.onEvent()')\n }\n\n /** Called by adapters for non-message events. */\n dispatchEvent(event: BotEvent) {\n this.logEvent(event)\n for (const handler of this.eventHandlers) {\n try {\n handler(event)\n } catch (error) {\n this.ctx.logger('bot').warn(error)\n }\n }\n }\n\n /** Called by adapters for each incoming message: records it, then runs the middleware chain. */\n async receive(message: IncomingMessage, options: { source?: Provenance } = {}) {\n const started = Date.now()\n const record = this.hooks.record({\n botId: this.id,\n messageId: message.messageId,\n direction: 'in',\n channel: message.channel,\n user: message.user,\n segments: message.segments,\n timestamp: message.timestamp ?? Date.now(),\n source: options.source ?? { kind: 'user' },\n })\n // Everything logged or spent while handling the message is tied to its record id.\n const outer = this.hooks.usageScope?.(this, record)\n const scope: UsageScope = {\n botId: this.id,\n messageId: record.id,\n report: (event) => {\n outer?.report(event)\n this.logUsage(event)\n },\n }\n return usage.run(scope, () => this.handle(record, started))\n }\n\n private async handle(record: MessageRecord, started: number) {\n this.ctx.logger('message').info('received from %s%s: %s', who(record.user), record.channel.type === 'group' ? ` in ${chat(record.channel)}` : '', preview(record.segments))\n const session = new Session(this, record)\n const entry = session.command?.entry\n if (entry) {\n try {\n this.hooks.commandCalled?.(this, entry, session)\n } catch {}\n }\n const chain = [...this.middlewares]\n const app = entry?.source.kind === 'plugin' ? this.hooks.appCommand?.(this, entry) : undefined\n if (entry?.source.kind === 'builtin' || app) {\n // After flows, so a flow that answers the same text (say a keyword trigger on /help) still wins.\n const builtin: MiddlewareEntry = {\n plugin: app ? entry!.source.id : BUILTIN_PLUGIN,\n fiber: app ? app.fiber : this.ctx.fiber,\n priority: BUILTIN_PRIORITY,\n callback: async (view, next) => {\n if (!this.allows(entry!, view)) return next()\n if (app) {\n await app.handler(view)\n return\n }\n const answer = this.hooks.builtinCommand?.(this, entry!, view)\n if (answer !== undefined) await view.reply(answer)\n },\n }\n const index = chain.findIndex((item) => item.priority < builtin.priority)\n chain.splice(index < 0 ? chain.length : index, 0, builtin)\n }\n /** The plugin that kept the message from the ones after it, if one did. */\n let stoppedAt: string | undefined\n const replies = new Map<string, number>()\n this.replying.set(record.id, replies)\n const run = async (index: number): Promise<void> => {\n const entry = chain[index]\n if (!entry) return\n let passed = false\n let failure: unknown\n // What the plugins after this one did is not this one's: their time and, for a plugin with several middlewares, their replies.\n const began = Date.now()\n const sent = () => replies.get(entry.plugin) ?? 0\n const sentBefore = sent()\n let laterMs = 0\n let laterSent = 0\n try {\n await entry.callback(session.as(entry.plugin), async () => {\n passed = true\n const at = Date.now()\n const before = sent()\n try {\n await run(index + 1)\n } finally {\n laterMs += Date.now() - at\n laterSent += sent() - before\n }\n })\n if (!passed && index < chain.length - 1) stoppedAt ??= entry.plugin\n } catch (error) {\n failure = error\n this.ctx.logger('bot').warn('middleware of %s failed: %s', entry.plugin, error)\n }\n const own = sent() - sentBefore - laterSent\n const kept = !passed && !failure && index < chain.length - 1\n if (entry.runs !== false && (own || kept || failure)) this.reportRun(entry, session, { began, ms: Date.now() - began - laterMs, replies: own, kept, failure })\n }\n try {\n await run(0)\n } finally {\n this.replying.delete(record.id)\n }\n this.ctx.logger('bot').info('processed in %s%s', duration(Date.now() - started), stoppedAt ? `; ${stoppedAt} kept it from the plugins after it` : '')\n return session\n }\n\n private reportRun(entry: MiddlewareEntry, session: Session, result: { began: number; ms: number; replies: number; kept: boolean; failure: unknown }) {\n const command = session.command?.entry\n const text = session.text\n try {\n this.hooks.pluginRun?.(this, {\n plugin: entry.plugin,\n ...(command && answers(command, entry.plugin) ? { command: command.name } : {}),\n text: text.length > 200 ? `${text.slice(0, 200)}…` : text,\n user: session.user,\n channel: `${session.channel.type}:${session.channel.id}`,\n message: session.record.id,\n status: result.failure ? 'error' : 'ok',\n replies: result.replies,\n kept: result.kept,\n startedAt: result.began,\n ms: result.ms,\n ...(result.failure ? { error: result.failure instanceof Error ? result.failure.message : String(result.failure) } : {}),\n }, entry.fiber)\n } catch (error) {\n this.ctx.logger('bot').debug('recording what %s did failed: %s', entry.plugin, error)\n }\n }\n\n /**\n * A notice or request from the platform (a poke, a member joining, a recall…) as a line in the\n * bot's log. Typing indicators come often and say little, so they and unnamed events are debug lines.\n */\n private logEvent(event: BotEvent) {\n const name = event.name ?? event.type\n const target = event.data?.target_id ?? undefined\n const parts = [\n event.user && `from ${who(event.user)}`,\n event.channel?.type === 'group' && `in ${chat(event.channel)}`,\n target !== undefined && target !== null && `to ${target}`,\n event.message?.text && `: ${preview(event.message.segments)}`,\n ].filter(Boolean).join(' ').replace(' :', ':')\n const quiet = !event.name || event.name === 'notify.input_status'\n this.ctx.logger('message')[quiet ? 'debug' : 'info']('event %s%s', name, parts ? ` ${parts}` : '')\n }\n\n /** A model request or a plugin's own work made while handling a message, as a line in the bot's log. */\n private logUsage(event: UsageEvent) {\n const logger = this.ctx.logger('llm')\n const target = [event.model, event.provider && `via ${event.provider}`, event.plugin && `for ${event.plugin}`].filter(Boolean).join(' ')\n const tokens = event.inputTokens !== undefined || event.outputTokens !== undefined\n ? `${event.inputTokens ?? '?'} → ${event.outputTokens ?? 0} tokens` : ''\n const details = [tokens, event.note, event.latencyMs !== undefined && duration(event.latencyMs)].filter(Boolean).join(', ')\n if (event.ok === false) logger.warn('%s %s failed%s', event.kind, target, event.latencyMs !== undefined ? ` after ${duration(event.latencyMs)}` : '')\n else logger.info('%s %s%s', event.kind, target, details ? `: ${details}` : '')\n }\n\n /** Sends a message from a plugin; the reply is attributed to the calling plugin. */\n send(channel: ChannelInfo, content: Sendable, options: { source?: Provenance } = {}) {\n return this.deliver(channel, content, { plugin: this.ctx.fiber.name, source: options.source })\n }\n\n /** Raw adapter API, e.g. a NapCat extension action. */\n async call(action: string, params: Record<string, any> = {}) {\n if (!this.transport?.call) throw new Error(`bot ${this.record.name} has no API transport`)\n return this.transport.call(action, params)\n }\n\n async deliver(\n channel: ChannelInfo,\n content: Sendable,\n options: { plugin?: string; source?: Provenance; replyTo?: string },\n ) {\n const sandbox = isSandbox(channel)\n if (!this.transport && !sandbox) throw new Error(`bot ${this.record.name} is not connected`)\n let segments: Segment[]\n let source: Provenance | undefined = options.source\n if (isSourced(content)) {\n segments = content.segments ?? toSegments(content.text ?? '')\n source ??= content.source\n } else {\n segments = toSegments(content)\n }\n if (source?.kind === 'llm' && !source.plugin && options.plugin) source = { ...source, plugin: options.plugin }\n source ??= options.plugin ? { kind: 'plugin', plugin: options.plugin } : { kind: 'manual' }\n if (!segments.length || (segments.length === 1 && segments[0].type === 'text' && !segments[0].data.text)) {\n return\n }\n const started = Date.now()\n const logger = this.ctx.logger('message')\n const sender = source.kind === 'flow' ? `flow ${source.flow}` : source.kind === 'plugin' || source.kind === 'llm' ? source.plugin : undefined\n let messageId: string | undefined\n try {\n ;({ messageId } = sandbox ? { messageId: randomId(6) } : await this.transport!.send(channel, segments))\n } catch (error) {\n logger.warn('sending to %s failed: %s', chat(channel), error instanceof Error ? error.message : error)\n throw error\n }\n const ms = Date.now() - started\n const bytes = byteSize(segments)\n logger.info('sent to %s%s: %s (%s%s)', chat(channel), sender ? ` by ${sender}` : '', preview(segments), size(bytes), sandbox ? '' : `, ${duration(ms)}`)\n const record = this.hooks.record({\n botId: this.id,\n messageId,\n direction: 'out',\n channel,\n user: { id: this.selfId ?? this.id, name: this.selfName ?? this.record.name },\n segments,\n timestamp: Date.now(),\n replyTo: options.replyTo,\n source,\n })\n const cause = usage.current()?.messageId\n this.hooks.sent?.(this, record, { bytes, ...(sandbox ? {} : { ms }), cause })\n const replies = cause ? this.replying.get(cause) : undefined\n if (replies && options.plugin) replies.set(options.plugin, (replies.get(options.plugin) ?? 0) + 1)\n return record\n }\n}\n\n/** How big a message is on the wire, roughly: its segments as JSON. Inline images count in full. */\nexport function byteSize(segments: Segment[]) {\n return Buffer.byteLength(JSON.stringify(segments))\n}\n\n/** Whether a plugin is the one answering a command: the plugin that registered it, or the bots plugin for `/help`. */\nfunction answers(command: CommandEntry, plugin: string) {\n return command.source.kind === 'builtin' ? plugin === BUILTIN_PLUGIN : command.source.kind === 'plugin' && command.source.id === plugin\n}\n\n/** A message on one line for the bot's log, cut to a readable length. */\nfunction preview(segments: Segment[]) {\n const text = segmentsToText(segments).replace(/\\s+/g, ' ').trim()\n return text.length > 200 ? `${text.slice(0, 200)}…` : text || '(empty)'\n}\n\n/** A chat for the bot's log: `group Tea room (500)`, a person for a private chat, or the sandbox. */\nfunction chat(channel: ChannelInfo) {\n if (isSandbox(channel)) return 'the sandbox'\n const name = channel.name ? `${channel.name} (${channel.id})` : channel.id\n return channel.type === 'group' ? `group ${name}` : name\n}\n\nfunction who(user: UserInfo) {\n return user.name ? `${user.name} (${user.id})` : user.id\n}\n\nfunction duration(ms: number) {\n return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(ms < 10000 ? 2 : 1)}s`\n}\n\nfunction size(bytes: number) {\n return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`\n}\n"],"mappings":";;;;;AAuEA,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,MA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such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the
3
- * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can
3
+ * built-in `/help` all register commands per bot, so help menus, Fairy and the overview can
4
4
  * list them in one place.
5
5
  */
6
6
  import { Segment } from "@mushinjs/core";
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["/**\n * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the\n * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can\n * list them in one place.\n */\n\nimport type { Segment } from '@mushinjs/core'\n\n/**\n * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,\n * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one\n * of `choices`.\n */\nexport type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice'\n\n/** One argument of a command, in the order they are written. */\nexport interface CommandArg {\n name: string\n type: CommandArgType\n /** Can be left out; then `default` is used, or the argument is missing from the values. */\n optional?: boolean\n /** Takes the rest of the message. Only text arguments can; the last text argument always does. */\n rest?: boolean\n default?: string | number | boolean\n /** For `choice` arguments. */\n choices?: string[]\n /** Shown in the usage reply and the editor. */\n description?: string\n}\n\nexport type ArgValue = string | number | boolean\n\nexport interface CommandDef {\n /** Without the prefix, e.g. `score`. */\n name: string\n aliases?: string[]\n description?: string\n /** What follows the name, in order. */\n args?: CommandArg[]\n /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */\n prefixes?: string[]\n /** Left out of `/help`. */\n hidden?: boolean\n /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */\n permission?: 'all' | 'admin' | 'master'\n /** The same as `permission`, as a role: `{ role: 'admin' }`. */\n role?: 'user' | 'admin' | 'master'\n}\n\nexport interface CommandSource {\n kind: 'flow' | 'plugin' | 'builtin'\n /** Flow id or plugin name. */\n id: string\n /** Flow or plugin name, for display. */\n name: string\n /** The command node, for flows. */\n nodeId?: string\n}\n\nexport interface CommandEntry extends CommandDef {\n botId: string\n source: CommandSource\n /** For flow commands: higher answers first when two register the same name. */\n priority?: number\n}\n\n/** Per-bot command settings, stored on the bot record. */\nexport interface CommandSettings {\n /** Defaults to `['/']`. */\n prefixes?: string[]\n /** Answer `/help` with the list of commands; on unless set to false. */\n help?: boolean\n /** First line of the help menu. */\n helpTitle?: string\n /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */\n admins?: string[]\n /** `/help` lists only the commands the asker may run. */\n helpByRole?: boolean\n}\n\nexport const DEFAULT_PREFIXES = ['/']\nexport const DEFAULT_HELP_TITLE = '可用指令:'\n\n/** A message split into prefix, command name and the text after it. */\nexport interface ParsedCommand {\n prefix: string\n /** As written, without the prefix. */\n name: string\n rest: string\n /** The registered command the name or alias belongs to, if any. */\n entry?: CommandEntry\n}\n\n/** Splits a message into a command, or nothing when it does not start with a prefix. */\nexport function splitCommand(text: string, prefixes: string[] = DEFAULT_PREFIXES): Omit<ParsedCommand, 'entry'> | undefined {\n const trimmed = text.trim()\n const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item))\n if (prefix === undefined) return\n const body = trimmed.slice(prefix.length)\n const match = /^(\\S+)(?:\\s+([\\s\\S]*))?$/.exec(body)\n if (!match) return\n return { prefix, name: match[1], rest: (match[2] ?? '').trim() }\n}\n\n/** Whether a command (by name or alias) is the one written. Names are compared without case. */\nexport function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string) {\n const name = written.toLowerCase()\n return [def.name, ...(def.aliases ?? [])].some((item) => !!item && item.toLowerCase() === name)\n}\n\nexport type ArgsResult =\n | { ok: true; values: Record<string, ArgValue> }\n | { ok: false; error: string; arg?: string }\n\nconst YES = new Set(['是', '对', '开', '开启', 'yes', 'y', 'true', 'on', '1'])\nconst NO = new Set(['否', '不', '关', '关闭', 'no', 'n', 'false', 'off', '0'])\n\n/**\n * Fills a command's arguments from the text after the command. `segments` are the message's, so an\n * @mention fills a `user` argument with the id rather than the name shown in the text.\n */\nexport function parseArgs(args: CommandArg[], rest: string, segments: Segment[] = []): ArgsResult {\n const mentions = segments.filter((segment) => segment.type === 'at' && segment.data.qq !== 'all')\n const words = tokenize(rest, mentions)\n const values: Record<string, ArgValue> = {}\n const lastText = args.findLastIndex((arg) => arg.type === 'text')\n for (const [index, arg] of args.entries()) {\n let word: Token | undefined\n if (arg.type === 'text' && (arg.rest || index === lastText) && index === args.length - 1) {\n const taken = words.splice(0)\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else if (arg.type === 'text' && (arg.rest || index === lastText)) {\n // Leaves one word for each argument after it.\n const later = args.length - 1 - index\n const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0))\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else {\n word = words.shift()\n }\n if (!word?.text) {\n if (arg.default !== undefined && arg.default !== '') values[arg.name] = arg.default\n else if (!arg.optional) return { ok: false, error: `missing ${arg.name}`, arg: arg.name }\n continue\n }\n const value = convertArg(arg, word)\n if (value === undefined) return { ok: false, error: `${arg.name} should be ${argTypeLabel(arg, 'en')}`, arg: arg.name }\n values[arg.name] = value\n }\n return { ok: true, values }\n}\n\ninterface Token {\n text: string\n /** The user an @mention names. */\n user?: string\n}\n\n/** Splits text into words; `@name` words that stand for an @mention carry its user id. */\nfunction tokenize(text: string, mentions: Segment[]): Token[] {\n const queue = [...mentions]\n return (text.trim() ? text.trim().split(/\\s+/) : []).map((word) => {\n const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`)\n if (index < 0) return { text: word }\n const [segment] = queue.splice(index, 1)\n return { text: word, user: String(segment.data.qq) }\n })\n}\n\nfunction convertArg(arg: CommandArg, word: Token): ArgValue | undefined {\n const raw = word.text\n switch (arg.type) {\n case 'number': {\n const number = Number(raw)\n return Number.isFinite(number) ? number : undefined\n }\n case 'boolean': {\n const folded = raw.toLowerCase()\n return YES.has(folded) ? true : NO.has(folded) ? false : undefined\n }\n case 'user': {\n if (word.user) return word.user\n const id = raw.replace(/^@/, '')\n return /^\\d{4,}$/.test(id) ? id : undefined\n }\n case 'choice': {\n const found = (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase())\n return found\n }\n default:\n return raw\n }\n}\n\n/** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */\nexport function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale: 'zh-CN' | 'en' = 'zh-CN') {\n const zh = locale === 'zh-CN'\n switch (arg.type) {\n case 'number': return zh ? '数字' : 'a number'\n case 'boolean': return zh ? '是/否' : 'yes or no'\n case 'user': return zh ? '@某人' : 'an @mention or user id'\n case 'choice': return (arg.choices ?? []).join('|') || (zh ? '选项' : 'a choice')\n default: return zh ? '文本' : 'text'\n }\n}\n\n/** The arguments as written in a usage line: `<分数:数字> [备注]`. */\nexport function formatArgs(args: CommandArg[] | undefined) {\n return (args ?? []).map((arg) => {\n const type = arg.type === 'text' ? '' : `:${argTypeLabel(arg)}`\n const body = `${arg.name}${type}${arg.rest ? '...' : ''}`\n return arg.optional || (arg.default !== undefined && arg.default !== '') ? `[${body}]` : `<${body}>`\n }).join(' ')\n}\n\n/** The prefix a command is shown with: its own first prefix, else the bot's. */\nexport function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix = DEFAULT_PREFIXES[0]) {\n return def.prefixes?.find(Boolean) ?? botPrefix\n}\n\n/** How a command is written, e.g. `/score <score:数字>`. */\nexport function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const args = formatArgs(def.args)\n return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ''}`\n}\n\n/** The reply when a command's arguments do not fit: the usage line, then what each argument is. */\nexport function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`)\n return [`用法:${commandUsage(def, prefix)}`, ...notes].join('\\n')\n}\n\n/** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */\nexport function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined {\n const role = def.role ?? (def.permission === 'all' ? undefined : def.permission)\n return role === 'admin' || role === 'master' ? role : undefined\n}\n\n/** The help menu for a bot's commands: one line per command, hidden ones left out. */\nexport function helpText(entries: CommandEntry[], settings: CommandSettings = {}) {\n const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0]\n const seen = new Set<string>()\n const lines: string[] = []\n for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {\n const key = entry.name.toLowerCase()\n if (entry.hidden || seen.has(key)) continue\n seen.add(key)\n const prefix = commandPrefix(entry, botPrefix)\n const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join('、')\n lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ''}${entry.description ? ` —— ${entry.description}` : ''}`)\n }\n return [settings.helpTitle || DEFAULT_HELP_TITLE, ...lines].join('\\n')\n}\n\n/** Names (and aliases) that more than one source registers on the same bot. */\nexport function commandConflicts(entries: CommandEntry[]) {\n const owners = new Map<string, CommandEntry[]>()\n for (const entry of entries) {\n for (const name of new Set([entry.name, ...(entry.aliases ?? [])].filter(Boolean).map((item) => item.toLowerCase()))) {\n const key = `${entry.botId}|${name}`\n owners.set(key, [...(owners.get(key) ?? []), entry])\n }\n }\n return [...owners.entries()]\n .filter(([, list]) => list.length > 1)\n // The first entry is the one that answers: highest priority, then registration order.\n .map(([key, list]) => ({ botId: key.split('|')[0], name: key.slice(key.indexOf('|') + 1), entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)) }))\n}\n"],"mappings":";AAgFA,MAAa,mBAAmB,CAAC,GAAG;AACpC,MAAa,qBAAqB;;AAalC,SAAgB,aAAa,MAAc,WAAqB,kBAA4D;CAC1H,MAAM,UAAU,KAAK,K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AM,SAAS,OAAO,OAAO,CAAC,CAAC,KAAK,UAAU,GAAG,SAAS,OAAO,CAAC,CAAC,KAAK,GAAG;EAC3F,MAAM,KAAK,GAAG,aAAa,OAAO,MAAM,IAAI,UAAU,IAAI,QAAQ,KAAK,KAAK,MAAM,cAAc,OAAO,MAAM,gBAAgB,IAAI;CACnI;CACA,OAAO,CAAC,SAAS,aAAA,SAAiC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;AACvE;;AAGA,SAAgB,iBAAiB,SAAyB;CACxD,MAAM,yBAAS,IAAI,IAA4B;CAC/C,KAAK,MAAM,SAAS,SAClB,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,MAAM,MAAM,GAAI,MAAM,WAAW,CAAC,CAAE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC,GAAG;EACpH,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG;EAC9B,OAAO,IAAI,KAAK,CAAC,GAAI,OAAO,IAAI,GAAG,KAAK,CAAC,GAAI,KAAK,CAAC;CACrD;CAEF,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,QAAQ,GAAG,UAAU,KAAK,SAAS,CAAC,CAAC,CAErC,KAAK,CAAC,KAAK,WAAW;EAAE,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EAAI,MAAM,IAAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;EAAG,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAAE,EAAE;AACzK"}
1
+ {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["/**\n * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the\n * built-in `/help` all register commands per bot, so help menus, Fairy and the overview can\n * list them in one place.\n */\n\nimport type { Segment } from '@mushinjs/core'\n\n/**\n * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,\n * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one\n * of `choices`.\n */\nexport type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice'\n\n/** One argument of a command, in the order they are written. */\nexport interface CommandArg {\n name: string\n type: CommandArgType\n /** Can be left out; then `default` is used, or the argument is missing from the values. */\n optional?: boolean\n /** Takes the rest of the message. Only text arguments can; the last text argument always does. */\n rest?: boolean\n default?: string | number | boolean\n /** For `choice` arguments. */\n choices?: string[]\n /** Shown in the usage reply and the editor. */\n description?: string\n}\n\nexport type ArgValue = string | number | boolean\n\nexport interface CommandDef {\n /** Without the prefix, e.g. `score`. */\n name: string\n aliases?: string[]\n description?: string\n /** What follows the name, in order. */\n args?: CommandArg[]\n /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */\n prefixes?: string[]\n /** Left out of `/help`. */\n hidden?: boolean\n /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */\n permission?: 'all' | 'admin' | 'master'\n /** The same as `permission`, as a role: `{ role: 'admin' }`. */\n role?: 'user' | 'admin' | 'master'\n}\n\nexport interface CommandSource {\n kind: 'flow' | 'plugin' | 'builtin'\n /** Flow id or plugin name. */\n id: string\n /** Flow or plugin name, for display. */\n name: string\n /** The command node, for flows. */\n nodeId?: string\n}\n\nexport interface CommandEntry extends CommandDef {\n botId: string\n source: CommandSource\n /** For flow commands: higher answers first when two register the same name. */\n priority?: number\n}\n\n/** Per-bot command settings, stored on the bot record. */\nexport interface CommandSettings {\n /** Defaults to `['/']`. */\n prefixes?: string[]\n /** Answer `/help` with the list of commands; on unless set to false. */\n help?: boolean\n /** First line of the help menu. */\n helpTitle?: string\n /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */\n admins?: string[]\n /** `/help` lists only the commands the asker may run. */\n helpByRole?: boolean\n}\n\nexport const DEFAULT_PREFIXES = ['/']\nexport const DEFAULT_HELP_TITLE = '可用指令:'\n\n/** A message split into prefix, command name and the text after it. */\nexport interface ParsedCommand {\n prefix: string\n /** As written, without the prefix. */\n name: string\n rest: string\n /** The registered command the name or alias belongs to, if any. */\n entry?: CommandEntry\n}\n\n/** Splits a message into a command, or nothing when it does not start with a prefix. */\nexport function splitCommand(text: string, prefixes: string[] = DEFAULT_PREFIXES): Omit<ParsedCommand, 'entry'> | undefined {\n const trimmed = text.trim()\n const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item))\n if (prefix === undefined) return\n const body = trimmed.slice(prefix.length)\n const match = /^(\\S+)(?:\\s+([\\s\\S]*))?$/.exec(body)\n if (!match) return\n return { prefix, name: match[1], rest: (match[2] ?? '').trim() }\n}\n\n/** Whether a command (by name or alias) is the one written. Names are compared without case. */\nexport function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string) {\n const name = written.toLowerCase()\n return [def.name, ...(def.aliases ?? [])].some((item) => !!item && item.toLowerCase() === name)\n}\n\nexport type ArgsResult =\n | { ok: true; values: Record<string, ArgValue> }\n | { ok: false; error: string; arg?: string }\n\nconst YES = new Set(['是', '对', '开', '开启', 'yes', 'y', 'true', 'on', '1'])\nconst NO = new Set(['否', '不', '关', '关闭', 'no', 'n', 'false', 'off', '0'])\n\n/**\n * Fills a command's arguments from the text after the command. `segments` are the message's, so an\n * @mention fills a `user` argument with the id rather than the name shown in the text.\n */\nexport function parseArgs(args: CommandArg[], rest: string, segments: Segment[] = []): ArgsResult {\n const mentions = segments.filter((segment) => segment.type === 'at' && segment.data.qq !== 'all')\n const words = tokenize(rest, mentions)\n const values: Record<string, ArgValue> = {}\n const lastText = args.findLastIndex((arg) => arg.type === 'text')\n for (const [index, arg] of args.entries()) {\n let word: Token | undefined\n if (arg.type === 'text' && (arg.rest || index === lastText) && index === args.length - 1) {\n const taken = words.splice(0)\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else if (arg.type === 'text' && (arg.rest || index === lastText)) {\n // Leaves one word for each argument after it.\n const later = args.length - 1 - index\n const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0))\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else {\n word = words.shift()\n }\n if (!word?.text) {\n if (arg.default !== undefined && arg.default !== '') values[arg.name] = arg.default\n else if (!arg.optional) return { ok: false, error: `missing ${arg.name}`, arg: arg.name }\n continue\n }\n const value = convertArg(arg, word)\n if (value === undefined) return { ok: false, error: `${arg.name} should be ${argTypeLabel(arg, 'en')}`, arg: arg.name }\n values[arg.name] = value\n }\n return { ok: true, values }\n}\n\ninterface Token {\n text: string\n /** The user an @mention names. */\n user?: string\n}\n\n/** Splits text into words; `@name` words that stand for an @mention carry its user id. */\nfunction tokenize(text: string, mentions: Segment[]): Token[] {\n const queue = [...mentions]\n return (text.trim() ? text.trim().split(/\\s+/) : []).map((word) => {\n const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`)\n if (index < 0) return { text: word }\n const [segment] = queue.splice(index, 1)\n return { text: word, user: String(segment.data.qq) }\n })\n}\n\nfunction convertArg(arg: CommandArg, word: Token): ArgValue | undefined {\n const raw = word.text\n switch (arg.type) {\n case 'number': {\n const number = Number(raw)\n return Number.isFinite(number) ? number : undefined\n }\n case 'boolean': {\n const folded = raw.toLowerCase()\n return YES.has(folded) ? true : NO.has(folded) ? false : undefined\n }\n case 'user': {\n if (word.user) return word.user\n const id = raw.replace(/^@/, '')\n return /^\\d{4,}$/.test(id) ? id : undefined\n }\n case 'choice': {\n const found = (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase())\n return found\n }\n default:\n return raw\n }\n}\n\n/** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */\nexport function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale: 'zh-CN' | 'en' = 'zh-CN') {\n const zh = locale === 'zh-CN'\n switch (arg.type) {\n case 'number': return zh ? '数字' : 'a number'\n case 'boolean': return zh ? '是/否' : 'yes or no'\n case 'user': return zh ? '@某人' : 'an @mention or user id'\n case 'choice': return (arg.choices ?? []).join('|') || (zh ? '选项' : 'a choice')\n default: return zh ? '文本' : 'text'\n }\n}\n\n/** The arguments as written in a usage line: `<分数:数字> [备注]`. */\nexport function formatArgs(args: CommandArg[] | undefined) {\n return (args ?? []).map((arg) => {\n const type = arg.type === 'text' ? '' : `:${argTypeLabel(arg)}`\n const body = `${arg.name}${type}${arg.rest ? '...' : ''}`\n return arg.optional || (arg.default !== undefined && arg.default !== '') ? `[${body}]` : `<${body}>`\n }).join(' ')\n}\n\n/** The prefix a command is shown with: its own first prefix, else the bot's. */\nexport function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix = DEFAULT_PREFIXES[0]) {\n return def.prefixes?.find(Boolean) ?? botPrefix\n}\n\n/** How a command is written, e.g. `/score <score:数字>`. */\nexport function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const args = formatArgs(def.args)\n return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ''}`\n}\n\n/** The reply when a command's arguments do not fit: the usage line, then what each argument is. */\nexport function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`)\n return [`用法:${commandUsage(def, prefix)}`, ...notes].join('\\n')\n}\n\n/** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */\nexport function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined {\n const role = def.role ?? (def.permission === 'all' ? undefined : def.permission)\n return role === 'admin' || role === 'master' ? role : undefined\n}\n\n/** The help menu for a bot's commands: one line per command, hidden ones left out. */\nexport function helpText(entries: CommandEntry[], settings: CommandSettings = {}) {\n const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0]\n const seen = new Set<string>()\n const lines: string[] = []\n for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {\n const key = entry.name.toLowerCase()\n if (entry.hidden || seen.has(key)) continue\n seen.add(key)\n const prefix = commandPrefix(entry, botPrefix)\n const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join('、')\n lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ''}${entry.description ? ` —— ${entry.description}` : ''}`)\n }\n return [settings.helpTitle || DEFAULT_HELP_TITLE, ...lines].join('\\n')\n}\n\n/** Names (and aliases) that more than one source registers on the same bot. */\nexport function commandConflicts(entries: CommandEntry[]) {\n const owners = new Map<string, CommandEntry[]>()\n for (const entry of entries) {\n for (const name of new Set([entry.name, ...(entry.aliases ?? [])].filter(Boolean).map((item) => item.toLowerCase()))) {\n const key = `${entry.botId}|${name}`\n owners.set(key, [...(owners.get(key) ?? []), entry])\n }\n }\n return [...owners.entries()]\n .filter(([, list]) => list.length > 1)\n // The first entry is the one that answers: highest priority, then registration order.\n .map(([key, list]) => ({ botId: key.split('|')[0], name: key.slice(key.indexOf('|') + 1), entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)) }))\n}\n"],"mappings":";AAgFA,MAAa,mBAAmB,CAAC,GAAG;AACpC,MAAa,qBAAqB;;AAalC,SAAgB,aAAa,MAAc,WAAqB,kBAA4D;CAC1H,MAAM,UAAU,KAAK,KAAK;CAC1B,MAAM,SAAS,CAAC,GAAG,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,SAAS,QAAQ,WAAW,IAAI,CAAC;CACxH,IAAI,WAAW,KAAA,GAAW;CAC1B,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAM;CACxC,MAAM,QAAQ,2BAA2B,KAAK,IAAI;CAClD,IAAI,CAAC,OAAO;CACZ,OAAO;EAAE;EAAQ,MAAM,MAAM;EAAI,OAAO,MAAM,MAAM,GAAA,CAAI,KAAK;CAAE;AACjE;;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,IAAI,IAAI,CAAC,MAAM,MAAM,GAAI,MAAM,WAAW,CAAC,CAAE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC,GAAG;EACpH,MAAM,MAAM,GAAG,MAAM,MAAM,GAAG;EAC9B,OAAO,IAAI,KAAK,CAAC,GAAI,OAAO,IAAI,GAAG,KAAK,CAAC,GAAI,KAAK,CAAC;CACrD;CAEF,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,QAAQ,GAAG,UAAU,KAAK,SAAS,CAAC,CAAC,CAErC,KAAK,CAAC,KAAK,WAAW;EAAE,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EAAI,MAAM,IAAI,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;EAAG,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,MAAM,GAAG,OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAAE,EAAE;AACzK"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, LogFilter, MessageUsage, RunCommandInput } from "./manager.js";
1
+ import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, LogFilter, MessageUsage, ProjectChatPlugin, RunCommandInput } from "./manager.js";
2
2
  import { MessageArchive, MessageQuery, MessageRow, fromRow, toRow } from "./archive.js";
3
- import { BUILTIN_PRIORITY, Bot, BotHooks, CommandHandler, Middleware, MiddlewareOptions, Sendable, Session, byteSize } from "./bot.js";
3
+ import { AppCommandTarget, BUILTIN_PRIORITY, Bot, BotHooks, CommandHandler, Middleware, MiddlewareOptions, PluginRunReport, Sendable, Session, byteSize } from "./bot.js";
4
4
  import { ArgValue, ArgsResult, CommandArg, CommandArgType, CommandDef, CommandEntry, CommandSettings, CommandSource, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ParsedCommand, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
5
- import { AdapterType, BotConnectionInfo, BotEvent, BotPluginEntry, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PermissionProvider, ROLE_RANK, ResolvedMedia, SANDBOX_CHANNEL, SANDBOX_USER, SourcedContent, Transport, isSandbox, roleAtLeast } from "./types.js";
6
- export { AdapterType, ArgValue, ArgsResult, BUILTIN_PRIORITY, Bot, BotConnectionInfo, BotEvent, BotHooks, BotLogLine, BotManager, BotPluginEntry, BotRecord, BotRole, BotStatus, BotStatusInfo, CommandArg, CommandArgType, CommandCall, CommandDef, CommandEntry, CommandHandler, CommandProvider, CommandSettings, CommandSource, Contact, ContactResolver, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, LogFilter, MediaResolver, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, ROLE_RANK, ResolvedMedia, RunCommandInput, SANDBOX_CHANNEL, SANDBOX_USER, Sendable, Session, SourcedContent, Transport, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, BotManager as default, formatArgs, fromRow, helpText, isSandbox, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
5
+ import { MEDIA_SEGMENTS, MediaSource, mediaBytes, mediaSource, mimeOf } from "./media.js";
6
+ import { AdapterType, BotConnectionInfo, BotEvent, BotPluginEntry, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PermissionProvider, PluginRun, ROLE_RANK, ResolvedMedia, SANDBOX_CHANNEL, SANDBOX_USER, SourcedContent, Transport, isSandbox, roleAtLeast } from "./types.js";
7
+ export { AdapterType, AppCommandTarget, ArgValue, ArgsResult, BUILTIN_PRIORITY, Bot, BotConnectionInfo, BotEvent, BotHooks, BotLogLine, BotManager, BotPluginEntry, BotRecord, BotRole, BotStatus, BotStatusInfo, CommandArg, CommandArgType, CommandCall, CommandDef, CommandEntry, CommandHandler, CommandProvider, CommandSettings, CommandSource, Contact, ContactResolver, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, LogFilter, MEDIA_SEGMENTS, MediaResolver, MediaSource, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, PluginRun, PluginRunReport, ProjectChatPlugin, ROLE_RANK, ResolvedMedia, RunCommandInput, SANDBOX_CHANNEL, SANDBOX_USER, Sendable, Session, SourcedContent, Transport, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, BotManager as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
package/dist/index.js CHANGED
@@ -2,9 +2,10 @@ import { BotManager } from "./manager.js";
2
2
  import { MessageArchive, fromRow, toRow } from "./archive.js";
3
3
  import { BUILTIN_PRIORITY, Bot, Session, byteSize } from "./bot.js";
4
4
  import { DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
5
+ import { MEDIA_SEGMENTS, mediaBytes, mediaSource, mimeOf } from "./media.js";
5
6
  import { ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, isSandbox, roleAtLeast } from "./types.js";
6
7
  // src/index.ts
7
8
  var src_default = BotManager;
8
- export { BUILTIN_PRIORITY, Bot, BotManager, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, MessageArchive, ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, Session, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, src_default as default, formatArgs, fromRow, helpText, isSandbox, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
9
+ export { BUILTIN_PRIORITY, Bot, BotManager, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, MEDIA_SEGMENTS, MessageArchive, ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, Session, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, src_default as default, formatArgs, fromRow, helpText, isSandbox, mediaBytes, mediaSource, mimeOf, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
9
10
 
10
11
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { BotManager } from './manager'\n\nexport * from './archive'\nexport * from './bot'\nexport * from './commands'\nexport * from './manager'\nexport * from './types'\n\nexport default BotManager\n"],"mappings":";;;;;;AAQA,IAAA,cAAe"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { BotManager } from './manager'\n\nexport * from './archive'\nexport * from './bot'\nexport * from './commands'\nexport * from './manager'\nexport * from './media'\nexport * from './types'\n\nexport default BotManager\n"],"mappings":";;;;;;;AASA,IAAA,cAAe"}