koishi-plugin-dify-ai 0.1.10 → 0.1.11

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,12 +20,11 @@ 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
28
  export declare function formatHistoryEntry(entry: HistoryEntry): string;
29
29
  /** 多条消息逐行拼接 */
30
30
  export declare function formatHistoryEntries(entries: HistoryEntry[]): string;
package/lib/index.js CHANGED
@@ -618,11 +618,18 @@ 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");
621
625
  function formatHistoryEntry(entry) {
626
+ if (entry.role === "event") {
627
+ return `[${formatTimestamp(entry.timestamp)}] ${entry.content}${entryAnnotations(entry)}`;
628
+ }
622
629
  const quote = entry.quote ? `(引用了 [${formatTimestamp(entry.quote.timestamp)}] ${entry.quote.username} (${entry.quote.userId}) 说:${entry.quote.content})` : "";
623
630
  const messageId = entry.messageId ? ` [msg:${entry.messageId}]` : "";
624
631
  const separator = quote ? "" : " ";
625
- return `[${formatTimestamp(entry.timestamp)}] ${entry.username} (${entry.userId})${messageId}${quote}${separator}说:${entry.content}`;
632
+ return `[${formatTimestamp(entry.timestamp)}] ${entry.username} (${entry.userId})${messageId}${quote}${separator}说:${entry.content}${entryAnnotations(entry)}`;
626
633
  }
627
634
  __name(formatHistoryEntry, "formatHistoryEntry");
628
635
  function formatHistoryEntries(entries) {
@@ -630,7 +637,10 @@ function formatHistoryEntries(entries) {
630
637
  }
631
638
  __name(formatHistoryEntries, "formatHistoryEntries");
632
639
  function formatHistoryBrief(entries) {
633
- return entries.map((entry) => entry.messageId ? `[msg:${entry.messageId}] ${entry.contentText}` : entry.contentText).join("\n");
640
+ return entries.map((entry) => {
641
+ const line = entry.messageId ? `[msg:${entry.messageId}] ${entry.contentText}` : entry.contentText;
642
+ return `${line}${entryAnnotations(entry)}`;
643
+ }).join("\n");
634
644
  }
635
645
  __name(formatHistoryBrief, "formatHistoryBrief");
636
646
  function buildQuote(session) {
@@ -812,11 +822,11 @@ var MessagePool = class {
812
822
  pool.entries.splice(0, pool.entries.length - POOL_CAPACITY);
813
823
  }
814
824
  }
815
- /** 时效内且通过规则作用域的真人条数(bot 行不推高密度,防自激励) */
825
+ /** 时效内且通过规则作用域的真人条数(bot 行不推高密度防自激励;已即时回复过的消息不重复计数防双触发) */
816
826
  countQualified(pool, rule, condition, now) {
817
827
  const windowMs = condition.densityWindowSeconds * 1e3;
818
828
  return pool.entries.filter(
819
- (item) => item.role === "user" && now - item.timestamp <= windowMs && matchScope(rule.scope, scopeSessionOf(pool, item))
829
+ (item) => item.role === "user" && !item.replied && now - item.timestamp <= windowMs && matchScope(rule.scope, scopeSessionOf(pool, item))
820
830
  ).length;
821
831
  }
822
832
  /**
@@ -842,6 +852,17 @@ var MessagePool = class {
842
852
  }
843
853
  return [];
844
854
  }
855
+ /** 给池内已有条目标注已撤回(按消息 ID 定位,找不到忽略——不新建条目) */
856
+ markDeleted(channelKey, messageId) {
857
+ const pool = this.channels.get(channelKey);
858
+ if (!pool) return;
859
+ for (let i = pool.entries.length - 1; i >= 0; i--) {
860
+ if (pool.entries[i].messageId === messageId) {
861
+ pool.entries[i].deleted = true;
862
+ return;
863
+ }
864
+ }
865
+ }
845
866
  /** 冷却到期复查:按条件参数统计该频道池(now 为复查时刻),达标即取走整池,未达标返回 null */
846
867
  takeDensityChannel(rule, condition, channelKey, now) {
847
868
  const pool = this.channels.get(channelKey);
@@ -863,6 +884,91 @@ var MessagePool = class {
863
884
  }
864
885
  };
865
886
 
887
+ // src/trigger/pool-events.ts
888
+ function actorOf(session) {
889
+ return `${session.username || session.userId} (${session.userId})`;
890
+ }
891
+ __name(actorOf, "actorOf");
892
+ function eventEntry(session, content) {
893
+ return {
894
+ role: "event",
895
+ userId: session.userId ?? "",
896
+ username: session.username || session.userId || "",
897
+ content,
898
+ contentText: content,
899
+ timestamp: session.timestamp ?? Date.now()
900
+ };
901
+ }
902
+ __name(eventEntry, "eventEntry");
903
+ function buildNoticeEntry(session) {
904
+ const actor = actorOf(session);
905
+ switch (session.subtype) {
906
+ case "poke": {
907
+ const target = session.targetId;
908
+ if (!target) return null;
909
+ return eventEntry(session, `${actor} 戳了 ${target === session.selfId ? "bot" : target}`);
910
+ }
911
+ case "lucky-king":
912
+ return eventEntry(session, `${actor} 成为红包运气王`);
913
+ case "honor":
914
+ return eventEntry(session, `${actor} 获得群荣誉`);
915
+ default:
916
+ return null;
917
+ }
918
+ }
919
+ __name(buildNoticeEntry, "buildNoticeEntry");
920
+ function buildMemberEntry(session) {
921
+ const actor = actorOf(session);
922
+ const payload = session.onebot ?? {};
923
+ switch (session.subtype) {
924
+ // set/remove 被 adapter 覆盖为 role,原始值只在载荷
925
+ case "role":
926
+ return eventEntry(session, `${actor} ${payload.sub_type === "remove" ? "被取消管理员" : "被设为管理员"}`);
927
+ case "ban": {
928
+ if (payload.sub_type === "lift_ban") return eventEntry(session, `${actor} 被解除禁言`);
929
+ const seconds = Number(payload.duration) || 0;
930
+ return eventEntry(session, `${actor} 被禁言${seconds > 0 ? ` ${seconds} 秒` : ""}`);
931
+ }
932
+ case "nickname":
933
+ return eventEntry(session, `${actor} 修改了群名片`);
934
+ default:
935
+ return null;
936
+ }
937
+ }
938
+ __name(buildMemberEntry, "buildMemberEntry");
939
+ function buildJoinEntry(session) {
940
+ const invitedBy = session.subtype === "passive" && session.operatorId;
941
+ return eventEntry(session, `${actorOf(session)} 加入群聊${invitedBy ? `(由 ${session.operatorId} 邀请)` : ""}`);
942
+ }
943
+ __name(buildJoinEntry, "buildJoinEntry");
944
+ function buildLeaveEntry(session) {
945
+ if (session.subtype === "passive" && session.operatorId) {
946
+ return eventEntry(session, `${actorOf(session)} 被 ${session.operatorId} 移出群聊`);
947
+ }
948
+ return eventEntry(session, `${actorOf(session)} 离开群聊`);
949
+ }
950
+ __name(buildLeaveEntry, "buildLeaveEntry");
951
+ function recordable(session) {
952
+ return !!session.channelId && !!session.userId && session.userId !== session.selfId;
953
+ }
954
+ __name(recordable, "recordable");
955
+ function registerPoolEvents(ctx, pool) {
956
+ const collect = /* @__PURE__ */ __name((build) => (session) => {
957
+ if (!recordable(session)) return;
958
+ const entry = build(session);
959
+ if (entry) pool.record(session, entry);
960
+ }, "collect");
961
+ ctx.on("notice", collect(buildNoticeEntry));
962
+ ctx.on("guild-member", collect(buildMemberEntry));
963
+ ctx.on("guild-member-added", collect(buildJoinEntry));
964
+ ctx.on("guild-member-removed", collect(buildLeaveEntry));
965
+ ctx.on("message-deleted", (session) => {
966
+ if (!session.channelId || !session.messageId) return;
967
+ pool.markDeleted(channelKeyOf(session.platform, session.channelId), session.messageId);
968
+ });
969
+ }
970
+ __name(registerPoolEvents, "registerPoolEvents");
971
+
866
972
  // src/trigger/scheduler.ts
867
973
  var import_cron_parser = require("cron-parser");
868
974
  var MS_PER_MINUTE = 6e4;
@@ -1091,6 +1197,7 @@ var TriggerEngine = class {
1091
1197
  this.history.recordEntry(key, entry);
1092
1198
  this.pool.record(session, entry);
1093
1199
  });
1200
+ registerPoolEvents(this.ctx, this.pool);
1094
1201
  this.scheduler.sync(this.rules);
1095
1202
  this.ctx.logger.info("已加载 %d 条启用规则", this.rules.length);
1096
1203
  }
@@ -1148,6 +1255,7 @@ var TriggerEngine = class {
1148
1255
  this.cooldown.begin(channelKey, ruleName, lane, Date.now());
1149
1256
  }
1150
1257
  fireMessage(rule, session, condition, entry) {
1258
+ if (entry) entry.replied = true;
1151
1259
  this.beginCooldown(channelKeyOf(session.platform, session.channelId), rule.name, "message");
1152
1260
  this.run({
1153
1261
  session,
@@ -1171,6 +1279,9 @@ var TriggerEngine = class {
1171
1279
  }
1172
1280
  /** 冷却到期:把缓冲内的触发消息合并为一次触发,session 取首条(供投递与文件上传) */
1173
1281
  fireMerged(rule, buffer) {
1282
+ for (const item of buffer) {
1283
+ if (item.entry) item.entry.replied = true;
1284
+ }
1174
1285
  const first = buffer[0];
1175
1286
  const queryText = joinNonEmpty(buffer.map((item) => item.entry ? formatHistoryEntry(item.entry) : ""));
1176
1287
  const contentText = joinNonEmpty(buffer.map((item) => item.contentText));
@@ -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.11",
5
5
  "author": "PinkElysia",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/PinkElysiaDev/dify-ai-plugin-for-Koishi#readme",