koishi-plugin-dify-ai 0.1.16 → 0.1.17

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
@@ -6,35 +6,42 @@ export interface QuotedMessage {
6
6
  username: string;
7
7
  content: string;
8
8
  }
9
+ /** 群事件条目的结构化形态:type 为事件标识,attrs 为各事件的自解释参数 */
10
+ export interface EventPayload {
11
+ type: string;
12
+ attrs?: Record<string, string>;
13
+ }
9
14
  export interface HistoryEntry {
10
- /** event 为群事件条目(戳一戳/入退群等,content 即事件文案,不进历史变量) */
15
+ /** event 为群事件条目(戳一戳/入退群等,结构化呈现,不进历史变量) */
11
16
  role: 'user' | 'assistant' | 'event';
12
17
  userId: string;
13
18
  username: string;
14
19
  messageId?: string;
15
- /** 原貌(含 @bot 渲染与图片占位):统一格式行(query/历史变量)用;event 为事件文案 */
20
+ /** 原貌(satori 标签形态,含 @bot 渲染与图片标签):统一格式行(query/历史变量)用;event 条目为空串 */
16
21
  content: string;
17
- /** 剔除 @bot 的原貌:content 变量与精简行用 */
22
+ /** 剔除 @bot 的原貌:content 变量与精简行用;event 条目为空串 */
18
23
  contentText: string;
19
- /** 图片元素 URL(按元素序,与 content 中 [image:摘要] 序一致):窗口类触发的上传依据 */
24
+ /** role='event' 时的结构化事件载荷(消息条目无此字段) */
25
+ event?: EventPayload;
26
+ /** 图片元素 URL(按元素序,与 content 中 img 标签的 src 序一致):窗口类触发的上传依据 */
20
27
  imageUrls?: string[];
21
28
  timestamp: number;
22
29
  quote?: QuotedMessage;
23
- /** 即时触发已消费过该消息(密度计数排除,渲染行尾注记) */
30
+ /** 即时触发已消费过该消息(密度计数排除,replied 属性注记) */
24
31
  replied?: boolean;
25
- /** 该消息已被撤回(渲染行尾注记) */
32
+ /** 该消息已被撤回(deleted 属性注记) */
26
33
  deleted?: boolean;
27
34
  }
28
- /** 引用段本体:[时间] 昵称 (用户ID) 说:内容(quoteContent 变量与统一格式行同源,不带消息 ID) */
35
+ /** 引用段:<quote time name user>内容</quote>(quoteContent 变量与统一格式行同源,不带消息 ID) */
29
36
  export declare function formatQuotedMessage(quote: QuotedMessage): string;
30
37
  export declare function formatHistoryEntry(entry: HistoryEntry): string;
31
- /** 多条消息逐行拼接 */
38
+ /** 多条消息逐条拼接(条目间空行分隔,正文换行不与相邻条目粘连) */
32
39
  export declare function formatHistoryEntries(entries: HistoryEntry[]): string;
33
- /** 精简行:只记消息 ID 与剔除 @bot 的原貌内容,不带时间与作者前缀——窗口触发的 content 变量用 */
40
+ /** 精简行:只留 id 属性与剔除 @bot 的原貌内容,不带时间与作者——窗口触发的 content 变量用 */
34
41
  export declare function formatHistoryBrief(entries: HistoryEntry[]): string;
35
42
  /** 从会话的引用对象构造引用段数据(quoteContent 变量与消息条目共用) */
36
43
  export declare function buildQuote(session: Session): QuotedMessage | undefined;
37
- /** 从会话消息构造记录条目(历史缓冲 / 消息池共用);assistant 行标注为机器人自己的发言 */
44
+ /** 从会话消息构造记录条目(历史缓冲 / 消息池共用);assistant 行经 role="bot" 属性标注为机器人自己的发言 */
38
45
  export declare function buildHistoryEntry(session: Session, role?: 'user' | 'assistant'): HistoryEntry | null;
39
46
  /**
40
47
  * 每个频道在内存中保留最近消息(含 bot 自己的回复),
@@ -46,6 +53,6 @@ export declare class MessageHistory {
46
53
  constructor(limit?: number);
47
54
  recordEntry(channelKey: string, entry: HistoryEntry): void;
48
55
  get(channelKey: string, limit?: number): HistoryEntry[];
49
- /** 序列化为统一消息格式的逐行拼接(变量值即完整聊天记录文本) */
56
+ /** 序列化为统一消息格式的逐条拼接(变量值即完整聊天记录文本) */
50
57
  toVariable(entries: HistoryEntry[]): string;
51
58
  }
package/lib/index.js CHANGED
@@ -571,17 +571,18 @@ function extractText(session) {
571
571
  return parseTextSafe(session.content);
572
572
  }
573
573
  __name(extractText, "extractText");
574
- var IMAGE_PLACEHOLDER = "[图片]";
575
- function imagePlaceholder(url) {
576
- if (!url) return IMAGE_PLACEHOLDER;
577
- return `[image:${(0, import_crypto.createHash)("sha1").update(url).digest("hex").slice(0, IMAGE_HASH_LENGTH)}]`;
574
+ var IMAGE_FALLBACK_TAG = "<img/>";
575
+ var escapeAttr = /* @__PURE__ */ __name((value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"), "escapeAttr");
576
+ function imageTag(url) {
577
+ if (!url) return IMAGE_FALLBACK_TAG;
578
+ return `<img src="${(0, import_crypto.createHash)("sha1").update(url).digest("hex").slice(0, IMAGE_HASH_LENGTH)}"/>`;
578
579
  }
579
- __name(imagePlaceholder, "imagePlaceholder");
580
+ __name(imageTag, "imageTag");
580
581
  function annotateDroppedPlaceholders(text, droppedUrls) {
581
582
  let result = text;
582
583
  for (const url of droppedUrls) {
583
- const placeholder = imagePlaceholder(url);
584
- result = result.split(placeholder).join(`${placeholder}(已丢弃)`);
584
+ const tag = imageTag(url);
585
+ result = result.split(tag).join(tag.replace("/>", " dropped/>"));
585
586
  }
586
587
  return result;
587
588
  }
@@ -608,16 +609,18 @@ function extractTextWithPlaceholders(session, options = {}) {
608
609
  for (const element of elementsOf(session)) {
609
610
  if (element.type === "text") {
610
611
  const text = element.attrs?.["content"] ?? "";
611
- if (text) parts.push(text);
612
+ if (text) parts.push(import_koishi2.h.escape(text));
612
613
  } else if (element.type === "at") {
613
614
  if (options.excludeBotAt && element.attrs?.["id"] === session.selfId) continue;
614
- const name2 = element.attrs?.["name"] ?? element.attrs?.["id"];
615
- if (name2) parts.push(`@${name2}`);
615
+ const id = element.attrs?.["id"];
616
+ const name2 = element.attrs?.["name"];
617
+ const attrText = id != null ? `id="${escapeAttr(String(id))}"${name2 != null ? ` name="${escapeAttr(String(name2))}"` : ""}` : name2 != null ? `name="${escapeAttr(String(name2))}"` : "";
618
+ if (attrText) parts.push(`<at ${attrText}/>`);
616
619
  } else if (isImageElement(element)) {
617
- parts.push(imagePlaceholder(imageSourceOf(element)));
620
+ parts.push(imageTag(imageSourceOf(element)));
618
621
  }
619
622
  }
620
- return parts.join(" ").replace(/\s+/g, " ").trim();
623
+ return parts.join(" ").replace(/[^\S\n]+/g, " ").trim();
621
624
  }
622
625
  __name(extractTextWithPlaceholders, "extractTextWithPlaceholders");
623
626
  function extractImageUrls(session) {
@@ -640,22 +643,37 @@ function formatTimestamp(timestamp) {
640
643
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
641
644
  }
642
645
  __name(formatTimestamp, "formatTimestamp");
643
- function entryAnnotations(entry) {
644
- return `${entry.replied ? "(已回复)" : ""}${entry.deleted ? "(已撤回)" : ""}`;
645
- }
646
- __name(entryAnnotations, "entryAnnotations");
646
+ var attr = /* @__PURE__ */ __name((key, value) => `${key}="${escapeAttr(value)}"`, "attr");
647
+ function formatEventEntry(entry) {
648
+ const attrs = [
649
+ attr("time", formatTimestamp(entry.timestamp)),
650
+ attr("name", entry.username),
651
+ attr("user", entry.userId),
652
+ attr("type", entry.event.type),
653
+ ...Object.entries(entry.event.attrs ?? {}).map(([key, value]) => attr(key, value))
654
+ ].join(" ");
655
+ return `<event ${attrs}/>`;
656
+ }
657
+ __name(formatEventEntry, "formatEventEntry");
647
658
  function formatQuotedMessage(quote) {
648
- return `[${formatTimestamp(quote.timestamp)}] ${quote.username} (${quote.userId}) 说:${quote.content}`;
659
+ return `<quote ${attr("time", formatTimestamp(quote.timestamp))} ${attr("name", quote.username)} ${attr("user", quote.userId)}>${quote.content}</quote>`;
649
660
  }
650
661
  __name(formatQuotedMessage, "formatQuotedMessage");
651
662
  function formatHistoryEntry(entry) {
652
- if (entry.role === "event") {
653
- return `[${formatTimestamp(entry.timestamp)}] ${entry.content}${entryAnnotations(entry)}`;
654
- }
655
- const quote = entry.quote ? `(引用了 ${formatQuotedMessage(entry.quote)})` : "";
656
- const messageId = entry.messageId ? ` [msg:${entry.messageId}]` : "";
657
- const separator = quote ? "" : " ";
658
- return `[${formatTimestamp(entry.timestamp)}] ${entry.username} (${entry.userId})${messageId}${quote}${separator}说:${entry.content}${entryAnnotations(entry)}`;
663
+ if (entry.role === "event") return formatEventEntry(entry);
664
+ const attrs = [
665
+ ...entry.messageId ? [attr("id", entry.messageId)] : [],
666
+ attr("time", formatTimestamp(entry.timestamp)),
667
+ attr("name", entry.username),
668
+ attr("user", entry.userId),
669
+ ...entry.role === "assistant" ? ['role="bot"'] : [],
670
+ ...entry.replied ? ["replied"] : [],
671
+ ...entry.deleted ? ["deleted"] : []
672
+ ].join(" ");
673
+ const quote = entry.quote ? formatQuotedMessage(entry.quote) : "";
674
+ return `<msg ${attrs}>
675
+ ${quote}${entry.content}
676
+ </msg>`;
659
677
  }
660
678
  __name(formatHistoryEntry, "formatHistoryEntry");
661
679
  function formatHistoryEntries(entries) {
@@ -664,8 +682,11 @@ function formatHistoryEntries(entries) {
664
682
  __name(formatHistoryEntries, "formatHistoryEntries");
665
683
  function formatHistoryBrief(entries) {
666
684
  return entries.map((entry) => {
667
- const line = entry.messageId ? `[msg:${entry.messageId}] ${entry.contentText}` : entry.contentText;
668
- return `${line}${entryAnnotations(entry)}`;
685
+ if (entry.role === "event") return formatEventEntry(entry);
686
+ const id = entry.messageId ? ` ${attr("id", entry.messageId)}` : "";
687
+ return `<msg${id}>
688
+ ${entry.contentText}
689
+ </msg>`;
669
690
  }).join("\n");
670
691
  }
671
692
  __name(formatHistoryBrief, "formatHistoryBrief");
@@ -687,7 +708,8 @@ function buildHistoryEntry(session, role = "user") {
687
708
  return {
688
709
  role,
689
710
  userId: role === "assistant" ? session.selfId : session.userId ?? "未知用户",
690
- username: role === "assistant" ? "你自己的发言" : session.username || session.userId,
711
+ // bot 昵称取适配器登录信息(与 botName 变量同源),缺省回退 bot 账号
712
+ username: role === "assistant" ? session.bot?.user?.name || session.bot?.user?.nick || session.selfId : session.username || session.userId,
691
713
  messageId: session.messageId,
692
714
  content,
693
715
  contentText: extractTextWithPlaceholders(session, { excludeBotAt: true }),
@@ -718,7 +740,7 @@ var MessageHistory = class {
718
740
  get(channelKey, limit = this.limit) {
719
741
  return (this.buffers.get(channelKey) ?? []).slice(-limit);
720
742
  }
721
- /** 序列化为统一消息格式的逐行拼接(变量值即完整聊天记录文本) */
743
+ /** 序列化为统一消息格式的逐条拼接(变量值即完整聊天记录文本) */
722
744
  toVariable(entries) {
723
745
  return formatHistoryEntries(entries);
724
746
  }
@@ -729,9 +751,8 @@ function hasAt(session, id) {
729
751
  return session.elements?.some((element) => element.type === "at" && element.attrs?.["id"] === id) ?? false;
730
752
  }
731
753
  __name(hasAt, "hasAt");
732
- var escapeRegExp = /* @__PURE__ */ __name((text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "escapeRegExp");
733
754
  var NON_TEXT_PREFIX = new RegExp(
734
- `^(?:@\\S+|\\[image:[0-9a-f]{${IMAGE_HASH_LENGTH}}\\]|${escapeRegExp(IMAGE_PLACEHOLDER)}|\\s)*`
755
+ `^(?:<at[^>]*/>|<img(?: src="[0-9a-f]{${IMAGE_HASH_LENGTH}}")?/>|\\s)*`
735
756
  );
736
757
  function stripPrefixKeyword(verbatim, keyword) {
737
758
  const prefix = NON_TEXT_PREFIX.exec(verbatim)?.[0] ?? "";
@@ -911,52 +932,50 @@ var MessagePool = class {
911
932
  };
912
933
 
913
934
  // src/trigger/pool-events.ts
914
- function actorOf(session) {
915
- return `${session.username || session.userId} (${session.userId})`;
916
- }
917
- __name(actorOf, "actorOf");
918
- function eventEntry(session, content) {
935
+ function eventEntry(session, event) {
919
936
  return {
920
937
  role: "event",
921
938
  userId: session.userId ?? "",
922
939
  username: session.username || session.userId || "",
923
- content,
924
- contentText: content,
940
+ content: "",
941
+ contentText: "",
942
+ event,
925
943
  timestamp: session.timestamp ?? Date.now()
926
944
  };
927
945
  }
928
946
  __name(eventEntry, "eventEntry");
929
947
  function buildNoticeEntry(session) {
930
- const actor = actorOf(session);
931
948
  switch (session.subtype) {
932
949
  case "poke": {
933
950
  const target = session.targetId;
934
951
  if (!target) return null;
935
- return eventEntry(session, `${actor} 戳了 ${target === session.selfId ? "bot" : target}`);
952
+ return eventEntry(session, { type: "poke", attrs: { target: String(target) } });
936
953
  }
937
954
  case "lucky-king":
938
- return eventEntry(session, `${actor} 成为红包运气王`);
955
+ return eventEntry(session, { type: "lucky-king" });
939
956
  case "honor":
940
- return eventEntry(session, `${actor} 获得群荣誉`);
957
+ return eventEntry(session, { type: "honor" });
941
958
  default:
942
959
  return null;
943
960
  }
944
961
  }
945
962
  __name(buildNoticeEntry, "buildNoticeEntry");
946
963
  function buildMemberEntry(session) {
947
- const actor = actorOf(session);
948
964
  const payload = session.onebot ?? {};
949
965
  switch (session.subtype) {
950
966
  // set/remove 被 adapter 覆盖为 role,原始值只在载荷
951
967
  case "role":
952
- return eventEntry(session, `${actor} ${payload.sub_type === "remove" ? "被取消管理员" : "被设为管理员"}`);
968
+ return eventEntry(session, { type: payload.sub_type === "remove" ? "admin-unset" : "admin-set" });
953
969
  case "ban": {
954
- if (payload.sub_type === "lift_ban") return eventEntry(session, `${actor} 被解除禁言`);
970
+ if (payload.sub_type === "lift_ban") return eventEntry(session, { type: "unban" });
955
971
  const seconds = Number(payload.duration) || 0;
956
- return eventEntry(session, `${actor} 被禁言${seconds > 0 ? ` ${seconds} 秒` : ""}`);
972
+ return eventEntry(
973
+ session,
974
+ seconds > 0 ? { type: "ban", attrs: { duration: String(seconds) } } : { type: "ban" }
975
+ );
957
976
  }
958
977
  case "nickname":
959
- return eventEntry(session, `${actor} 修改了群名片`);
978
+ return eventEntry(session, { type: "nickname" });
960
979
  default:
961
980
  return null;
962
981
  }
@@ -964,14 +983,17 @@ function buildMemberEntry(session) {
964
983
  __name(buildMemberEntry, "buildMemberEntry");
965
984
  function buildJoinEntry(session) {
966
985
  const invitedBy = session.subtype === "passive" && session.operatorId;
967
- return eventEntry(session, `${actorOf(session)} 加入群聊${invitedBy ? `(由 ${session.operatorId} 邀请)` : ""}`);
986
+ return eventEntry(
987
+ session,
988
+ invitedBy ? { type: "join", attrs: { invitedBy: String(session.operatorId) } } : { type: "join" }
989
+ );
968
990
  }
969
991
  __name(buildJoinEntry, "buildJoinEntry");
970
992
  function buildLeaveEntry(session) {
971
993
  if (session.subtype === "passive" && session.operatorId) {
972
- return eventEntry(session, `${actorOf(session)} 被 ${session.operatorId} 移出群聊`);
994
+ return eventEntry(session, { type: "leave", attrs: { operator: String(session.operatorId) } });
973
995
  }
974
- return eventEntry(session, `${actorOf(session)} 离开群聊`);
996
+ return eventEntry(session, { type: "leave" });
975
997
  }
976
998
  __name(buildLeaveEntry, "buildLeaveEntry");
977
999
  function recordable(session) {
@@ -1330,7 +1352,7 @@ var TriggerEngine = class {
1330
1352
  ...sessionIdentityOf(session),
1331
1353
  triggerType: condition.type,
1332
1354
  rule,
1333
- // query 为该条消息的统一格式单行;纯 @ / 纯引用等无文本消息 entry 为空,由请求器占位兜底
1355
+ // query 为该条消息的统一格式条目;纯 @ / 纯引用等无文本消息 entry 为空,由请求器占位兜底
1334
1356
  queryText,
1335
1357
  contentText: condition.contentText
1336
1358
  });
@@ -2,7 +2,7 @@ import { Session } from 'koishi';
2
2
  import { MessageTriggerType, TriggerCondition, TriggerScope } from '../types';
3
3
  export interface ConditionMatched {
4
4
  type: MessageTriggerType;
5
- /** content 变量的剥离文本,保留 @ 与图片占位(query 由引擎按统一消息格式另行构造) */
5
+ /** content 变量的剥离文本,保留 @ 与图片标签(query 由引擎按统一消息格式另行构造) */
6
6
  contentText: string;
7
7
  }
8
8
  /** 评估单个消息条件;返回 null 表示未命中(匹配基于纯文本,@ 元素不参与判定) */
@@ -10,11 +10,13 @@ export declare const IMAGE_HASH_LENGTH = 8;
10
10
  export declare function parseTextSafe(content: string | undefined): string;
11
11
  /** 会话消息纯文本:优先 elements,退回 content 解析;统一 trim(@ 元素不产生文本,仅供条件匹配) */
12
12
  export declare function extractText(session: Session): string;
13
- /** 消息中的图片元素在文本形态里的占位符(图片无 URL 时的兜底形态) */
14
- export declare const IMAGE_PLACEHOLDER = "[\u56FE\u7247]";
15
- /** 图片占位符带 URL 摘要:同 URL 同标识,query 里的占位符与上传文件可全局对应 */
16
- export declare function imagePlaceholder(url?: string): string;
17
- /** 给被丢弃图片的占位符追加已丢弃注记:按 URL 摘要全局定位,无需与元素顺序对齐 */
13
+ /** 消息中的图片元素在文本形态里的兜底标签(图片无 URL 时) */
14
+ export declare const IMAGE_FALLBACK_TAG = "<img/>";
15
+ /** 属性值转义(satori 属性序列化同款:正文三字符再加引号) */
16
+ export declare const escapeAttr: (value: string) => string;
17
+ /** 图片元素的标签形态:src 为 URL 摘要,同 URL 同标识,query 里的标签与上传文件可全局对应 */
18
+ export declare function imageTag(url?: string): string;
19
+ /** 给被丢弃图片的标签追加 dropped 注记:按 URL 摘要全局定位,无需与元素顺序对齐 */
18
20
  export declare function annotateDroppedPlaceholders(text: string, droppedUrls: string[]): string;
19
21
  interface ExtractVerbatimOptions {
20
22
  /** 跳过 @ 机器人自身的渲染(content 变量语义:@bot 是触发结构而非消息内容) */
@@ -23,8 +25,8 @@ interface ExtractVerbatimOptions {
23
25
  /** 媒体元素的源地址(url 或 src 属性,未定形态原样返回由调用方守卫) */
24
26
  export declare function imageSourceOf(element: h): unknown;
25
27
  /**
26
- * 消息原貌文本:text 元素按序拼接,@ 元素渲染为 @名字(缺名字用 ID),
27
- * img/image 元素渲染为 [image:URL摘要]——统一格式行(query/池/历史)用默认形态,
28
+ * 消息原貌文本(satori 标签形态):text 元素转义后按序拼接,@ 元素渲染为 <at id name/>,
29
+ * img/image 元素渲染为 <img src/>(src 为 URL 摘要)——统一格式行(query/池/历史)用默认形态,
28
30
  * content 变量通道用 excludeBotAt 形态剔除 @bot。
29
31
  */
30
32
  export declare function extractTextWithPlaceholders(session: Session, options?: ExtractVerbatimOptions): string;
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.16",
4
+ "version": "0.1.17",
5
5
  "author": "PinkElysia",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/PinkElysiaDev/dify-ai-plugin-for-Koishi#readme",