koishi-plugin-dify-ai 0.1.10 → 0.1.12

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/lib/history.d.ts CHANGED
@@ -7,11 +7,12 @@ export interface QuotedMessage {
7
7
  content: string;
8
8
  }
9
9
  export interface HistoryEntry {
10
- role: 'user' | 'assistant';
10
+ /** event 为群事件条目(戳一戳/入退群等,content 即事件文案,不进历史变量) */
11
+ role: 'user' | 'assistant' | 'event';
11
12
  userId: string;
12
13
  username: string;
13
14
  messageId?: string;
14
- /** 原貌(含 @bot 渲染与图片占位):统一格式行(query/历史变量)用 */
15
+ /** 原貌(含 @bot 渲染与图片占位):统一格式行(query/历史变量)用;event 为事件文案 */
15
16
  content: string;
16
17
  /** 剔除 @bot 的原貌:content 变量与精简行用 */
17
18
  contentText: string;
@@ -19,17 +20,20 @@ export interface HistoryEntry {
19
20
  imageUrls?: string[];
20
21
  timestamp: number;
21
22
  quote?: QuotedMessage;
23
+ /** 即时触发已消费过该消息(密度计数排除,渲染行尾注记) */
24
+ replied?: boolean;
25
+ /** 该消息已被撤回(渲染行尾注记) */
26
+ deleted?: boolean;
22
27
  }
23
- /**
24
- * 统一消息格式(历史消息变量 / 定时摘要 / 密度触发共用):
25
- * `[时间] 昵称 (用户ID) [msg:消息ID](引用了 [时间] 昵称 (用户ID) 说:内容)说:内容`
26
- * 引用段与外层同构但不展示消息 ID;无引用则整段省略。
27
- */
28
+ /** 引用段本体:[时间] 昵称 (用户ID) 说:内容(quoteContent 变量与统一格式行同源,不带消息 ID) */
29
+ export declare function formatQuotedMessage(quote: QuotedMessage): string;
28
30
  export declare function formatHistoryEntry(entry: HistoryEntry): string;
29
31
  /** 多条消息逐行拼接 */
30
32
  export declare function formatHistoryEntries(entries: HistoryEntry[]): string;
31
33
  /** 精简行:只记消息 ID 与剔除 @bot 的原貌内容,不带时间与作者前缀——窗口触发的 content 变量用 */
32
34
  export declare function formatHistoryBrief(entries: HistoryEntry[]): string;
35
+ /** 从会话的引用对象构造引用段数据(quoteContent 变量与消息条目共用) */
36
+ export declare function buildQuote(session: Session): QuotedMessage | undefined;
33
37
  /** 从会话消息构造记录条目(历史缓冲 / 消息池共用);assistant 行标注为机器人自己的发言 */
34
38
  export declare function buildHistoryEntry(session: Session, role?: 'user' | 'assistant'): HistoryEntry | null;
35
39
  /**
package/lib/index.js CHANGED
@@ -618,11 +618,22 @@ function formatTimestamp(timestamp) {
618
618
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
619
619
  }
620
620
  __name(formatTimestamp, "formatTimestamp");
621
+ function entryAnnotations(entry) {
622
+ return `${entry.replied ? "(已回复)" : ""}${entry.deleted ? "(已撤回)" : ""}`;
623
+ }
624
+ __name(entryAnnotations, "entryAnnotations");
625
+ function formatQuotedMessage(quote) {
626
+ return `[${formatTimestamp(quote.timestamp)}] ${quote.username} (${quote.userId}) 说:${quote.content}`;
627
+ }
628
+ __name(formatQuotedMessage, "formatQuotedMessage");
621
629
  function formatHistoryEntry(entry) {
622
- const quote = entry.quote ? `(引用了 [${formatTimestamp(entry.quote.timestamp)}] ${entry.quote.username} (${entry.quote.userId}) 说:${entry.quote.content})` : "";
630
+ if (entry.role === "event") {
631
+ return `[${formatTimestamp(entry.timestamp)}] ${entry.content}${entryAnnotations(entry)}`;
632
+ }
633
+ const quote = entry.quote ? `(引用了 ${formatQuotedMessage(entry.quote)})` : "";
623
634
  const messageId = entry.messageId ? ` [msg:${entry.messageId}]` : "";
624
635
  const separator = quote ? "" : " ";
625
- return `[${formatTimestamp(entry.timestamp)}] ${entry.username} (${entry.userId})${messageId}${quote}${separator}说:${entry.content}`;
636
+ return `[${formatTimestamp(entry.timestamp)}] ${entry.username} (${entry.userId})${messageId}${quote}${separator}说:${entry.content}${entryAnnotations(entry)}`;
626
637
  }
627
638
  __name(formatHistoryEntry, "formatHistoryEntry");
628
639
  function formatHistoryEntries(entries) {
@@ -630,7 +641,10 @@ function formatHistoryEntries(entries) {
630
641
  }
631
642
  __name(formatHistoryEntries, "formatHistoryEntries");
632
643
  function formatHistoryBrief(entries) {
633
- return entries.map((entry) => entry.messageId ? `[msg:${entry.messageId}] ${entry.contentText}` : entry.contentText).join("\n");
644
+ return entries.map((entry) => {
645
+ const line = entry.messageId ? `[msg:${entry.messageId}] ${entry.contentText}` : entry.contentText;
646
+ return `${line}${entryAnnotations(entry)}`;
647
+ }).join("\n");
634
648
  }
635
649
  __name(formatHistoryBrief, "formatHistoryBrief");
636
650
  function buildQuote(session) {
@@ -812,11 +826,11 @@ var MessagePool = class {
812
826
  pool.entries.splice(0, pool.entries.length - POOL_CAPACITY);
813
827
  }
814
828
  }
815
- /** 时效内且通过规则作用域的真人条数(bot 行不推高密度,防自激励) */
829
+ /** 时效内且通过规则作用域的真人条数(bot 行不推高密度防自激励;已即时回复过的消息不重复计数防双触发) */
816
830
  countQualified(pool, rule, condition, now) {
817
831
  const windowMs = condition.densityWindowSeconds * 1e3;
818
832
  return pool.entries.filter(
819
- (item) => item.role === "user" && now - item.timestamp <= windowMs && matchScope(rule.scope, scopeSessionOf(pool, item))
833
+ (item) => item.role === "user" && !item.replied && now - item.timestamp <= windowMs && matchScope(rule.scope, scopeSessionOf(pool, item))
820
834
  ).length;
821
835
  }
822
836
  /**
@@ -842,6 +856,17 @@ var MessagePool = class {
842
856
  }
843
857
  return [];
844
858
  }
859
+ /** 给池内已有条目标注已撤回(按消息 ID 定位,找不到忽略——不新建条目) */
860
+ markDeleted(channelKey, messageId) {
861
+ const pool = this.channels.get(channelKey);
862
+ if (!pool) return;
863
+ for (let i = pool.entries.length - 1; i >= 0; i--) {
864
+ if (pool.entries[i].messageId === messageId) {
865
+ pool.entries[i].deleted = true;
866
+ return;
867
+ }
868
+ }
869
+ }
845
870
  /** 冷却到期复查:按条件参数统计该频道池(now 为复查时刻),达标即取走整池,未达标返回 null */
846
871
  takeDensityChannel(rule, condition, channelKey, now) {
847
872
  const pool = this.channels.get(channelKey);
@@ -863,6 +888,91 @@ var MessagePool = class {
863
888
  }
864
889
  };
865
890
 
891
+ // src/trigger/pool-events.ts
892
+ function actorOf(session) {
893
+ return `${session.username || session.userId} (${session.userId})`;
894
+ }
895
+ __name(actorOf, "actorOf");
896
+ function eventEntry(session, content) {
897
+ return {
898
+ role: "event",
899
+ userId: session.userId ?? "",
900
+ username: session.username || session.userId || "",
901
+ content,
902
+ contentText: content,
903
+ timestamp: session.timestamp ?? Date.now()
904
+ };
905
+ }
906
+ __name(eventEntry, "eventEntry");
907
+ function buildNoticeEntry(session) {
908
+ const actor = actorOf(session);
909
+ switch (session.subtype) {
910
+ case "poke": {
911
+ const target = session.targetId;
912
+ if (!target) return null;
913
+ return eventEntry(session, `${actor} 戳了 ${target === session.selfId ? "bot" : target}`);
914
+ }
915
+ case "lucky-king":
916
+ return eventEntry(session, `${actor} 成为红包运气王`);
917
+ case "honor":
918
+ return eventEntry(session, `${actor} 获得群荣誉`);
919
+ default:
920
+ return null;
921
+ }
922
+ }
923
+ __name(buildNoticeEntry, "buildNoticeEntry");
924
+ function buildMemberEntry(session) {
925
+ const actor = actorOf(session);
926
+ const payload = session.onebot ?? {};
927
+ switch (session.subtype) {
928
+ // set/remove 被 adapter 覆盖为 role,原始值只在载荷
929
+ case "role":
930
+ return eventEntry(session, `${actor} ${payload.sub_type === "remove" ? "被取消管理员" : "被设为管理员"}`);
931
+ case "ban": {
932
+ if (payload.sub_type === "lift_ban") return eventEntry(session, `${actor} 被解除禁言`);
933
+ const seconds = Number(payload.duration) || 0;
934
+ return eventEntry(session, `${actor} 被禁言${seconds > 0 ? ` ${seconds} 秒` : ""}`);
935
+ }
936
+ case "nickname":
937
+ return eventEntry(session, `${actor} 修改了群名片`);
938
+ default:
939
+ return null;
940
+ }
941
+ }
942
+ __name(buildMemberEntry, "buildMemberEntry");
943
+ function buildJoinEntry(session) {
944
+ const invitedBy = session.subtype === "passive" && session.operatorId;
945
+ return eventEntry(session, `${actorOf(session)} 加入群聊${invitedBy ? `(由 ${session.operatorId} 邀请)` : ""}`);
946
+ }
947
+ __name(buildJoinEntry, "buildJoinEntry");
948
+ function buildLeaveEntry(session) {
949
+ if (session.subtype === "passive" && session.operatorId) {
950
+ return eventEntry(session, `${actorOf(session)} 被 ${session.operatorId} 移出群聊`);
951
+ }
952
+ return eventEntry(session, `${actorOf(session)} 离开群聊`);
953
+ }
954
+ __name(buildLeaveEntry, "buildLeaveEntry");
955
+ function recordable(session) {
956
+ return !!session.channelId && !!session.userId && session.userId !== session.selfId;
957
+ }
958
+ __name(recordable, "recordable");
959
+ function registerPoolEvents(ctx, pool) {
960
+ const collect = /* @__PURE__ */ __name((build) => (session) => {
961
+ if (!recordable(session)) return;
962
+ const entry = build(session);
963
+ if (entry) pool.record(session, entry);
964
+ }, "collect");
965
+ ctx.on("notice", collect(buildNoticeEntry));
966
+ ctx.on("guild-member", collect(buildMemberEntry));
967
+ ctx.on("guild-member-added", collect(buildJoinEntry));
968
+ ctx.on("guild-member-removed", collect(buildLeaveEntry));
969
+ ctx.on("message-deleted", (session) => {
970
+ if (!session.channelId || !session.messageId) return;
971
+ pool.markDeleted(channelKeyOf(session.platform, session.channelId), session.messageId);
972
+ });
973
+ }
974
+ __name(registerPoolEvents, "registerPoolEvents");
975
+
866
976
  // src/trigger/scheduler.ts
867
977
  var import_cron_parser = require("cron-parser");
868
978
  var MS_PER_MINUTE = 6e4;
@@ -1091,6 +1201,7 @@ var TriggerEngine = class {
1091
1201
  this.history.recordEntry(key, entry);
1092
1202
  this.pool.record(session, entry);
1093
1203
  });
1204
+ registerPoolEvents(this.ctx, this.pool);
1094
1205
  this.scheduler.sync(this.rules);
1095
1206
  this.ctx.logger.info("已加载 %d 条启用规则", this.rules.length);
1096
1207
  }
@@ -1148,6 +1259,7 @@ var TriggerEngine = class {
1148
1259
  this.cooldown.begin(channelKey, ruleName, lane, Date.now());
1149
1260
  }
1150
1261
  fireMessage(rule, session, condition, entry) {
1262
+ if (entry) entry.replied = true;
1151
1263
  this.beginCooldown(channelKeyOf(session.platform, session.channelId), rule.name, "message");
1152
1264
  this.run({
1153
1265
  session,
@@ -1171,6 +1283,9 @@ var TriggerEngine = class {
1171
1283
  }
1172
1284
  /** 冷却到期:把缓冲内的触发消息合并为一次触发,session 取首条(供投递与文件上传) */
1173
1285
  fireMerged(rule, buffer) {
1286
+ for (const item of buffer) {
1287
+ if (item.entry) item.entry.replied = true;
1288
+ }
1174
1289
  const first = buffer[0];
1175
1290
  const queryText = joinNonEmpty(buffer.map((item) => item.entry ? formatHistoryEntry(item.entry) : ""));
1176
1291
  const contentText = joinNonEmpty(buffer.map((item) => item.contentText));
@@ -1461,8 +1576,10 @@ function resolveSessionField(key, fireCtx, now) {
1461
1576
  return session?.messageId ?? "";
1462
1577
  case "content":
1463
1578
  return fireCtx.contentText;
1464
- case "quoteContent":
1465
- return parseTextSafe(session?.quote?.content);
1579
+ case "quoteContent": {
1580
+ const quote = buildQuote(session);
1581
+ return quote ? formatQuotedMessage(quote) : "";
1582
+ }
1466
1583
  case "quoteAuthorId":
1467
1584
  return session?.quote?.user?.id ?? "";
1468
1585
  case "username":
@@ -0,0 +1,3 @@
1
+ import { Context } from 'koishi';
2
+ import { MessagePool } from './pool';
3
+ export declare function registerPoolEvents(ctx: Context, pool: MessagePool): void;
@@ -27,7 +27,7 @@ export declare class MessagePool {
27
27
  private channels;
28
28
  /** 一条消息(含 bot 自己的发言)入池,全量记录不做规则过滤 */
29
29
  record(session: Session, entry: HistoryEntry): void;
30
- /** 时效内且通过规则作用域的真人条数(bot 行不推高密度,防自激励) */
30
+ /** 时效内且通过规则作用域的真人条数(bot 行不推高密度防自激励;已即时回复过的消息不重复计数防双触发) */
31
31
  private countQualified;
32
32
  /**
33
33
  * 新消息入池后的密度评估:时效内(相对触发消息)且通过规则作用域的真人条数达到阈值。
@@ -35,6 +35,8 @@ export declare class MessagePool {
35
35
  * skip 返回 true 的条件(冷却中的密度条件)不参与判定。
36
36
  */
37
37
  checkDensity(rules: DifyRule[], session: Session, skip?: (rule: DifyRule, condition: DensityCondition, index: number) => boolean): DensityFire[];
38
+ /** 给池内已有条目标注已撤回(按消息 ID 定位,找不到忽略——不新建条目) */
39
+ markDeleted(channelKey: string, messageId: string): void;
38
40
  /** 冷却到期复查:按条件参数统计该频道池(now 为复查时刻),达标即取走整池,未达标返回 null */
39
41
  takeDensityChannel(rule: DifyRule, condition: DensityCondition, channelKey: string, now: number): ChannelPool | null;
40
42
  /** 定时到点:取走该规则作用域内有消息的所有频道(整池清空,含未过作用域的条目) */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-dify-ai",
3
3
  "description": "Invoke Dify apps (chatflow / workflow / completion) in Koishi with triggers and conversation bindings",
4
- "version": "0.1.10",
4
+ "version": "0.1.12",
5
5
  "author": "PinkElysia",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/PinkElysiaDev/dify-ai-plugin-for-Koishi#readme",