groupAdminAttention.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import type { BotActor, BotOutboundMessage } from "@zcode/shared";
  2. /** 仅由服务明确识别的配置/连接错误升级,不能扫描模型输出猜测管理员待办。 */
  3. export class BotAdminRequiredError extends Error {
  4. constructor(
  5. public readonly reason: string,
  6. message: string,
  7. ) {
  8. super(message);
  9. }
  10. }
  11. /** 保留准备阶段的结构化提示,避免话题续接把收件人丢成纯文本。 */
  12. export class BotReplyError extends Error {
  13. constructor(public readonly replies: BotOutboundMessage[]) {
  14. super(replies.map((reply) => reply.text).join("\n"));
  15. }
  16. }
  17. /** 通知去重不参与任务接收、授权或执行;重启后允许重新提醒。 */
  18. export function createGroupAdminAttention() {
  19. const sent = new Map<string, true>();
  20. const scope = (actor: BotActor, owner: string) =>
  21. JSON.stringify([actor.botId, actor.chatId, actor.threadId, owner]);
  22. return {
  23. mention(actor: BotActor, owner: string | undefined, reason: string): string[] | undefined {
  24. if (actor.chatType !== "group" || !actor.chatId || !owner) return undefined;
  25. const key = `${scope(actor, owner)}:${reason}`;
  26. if (sent.has(key)) return [];
  27. sent.set(key, true);
  28. if (sent.size > 1000) sent.delete(sent.keys().next().value!);
  29. return [owner];
  30. },
  31. clear(actor?: BotActor, owner?: string, reason?: string) {
  32. if (!actor) {
  33. sent.clear();
  34. return;
  35. }
  36. if (!owner) return;
  37. const prefix = `${scope(actor, owner)}:`;
  38. for (const key of sent.keys()) {
  39. if (
  40. reason
  41. ? key === `${prefix}${reason}`
  42. : key.startsWith(prefix) &&
  43. !key.slice(prefix.length).startsWith("permission:") &&
  44. !key.slice(prefix.length).startsWith("plan:")
  45. )
  46. sent.delete(key);
  47. }
  48. },
  49. };
  50. }