koishi-plugin-dify-ai 0.1.15 → 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/config.d.ts +3 -0
- package/lib/history.d.ts +18 -11
- package/lib/index.d.ts +1 -1
- package/lib/index.js +136 -53
- package/lib/locales/en-US.d.ts +1 -0
- package/lib/locales/zh-CN.d.ts +1 -0
- package/lib/trigger/conditions.d.ts +1 -1
- package/lib/trigger/engine.d.ts +4 -0
- package/lib/types.d.ts +10 -3
- package/lib/utils/session-text.d.ts +9 -7
- package/package.json +1 -1
package/lib/config.d.ts
CHANGED
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
|
|
15
|
+
/** event 为群事件条目(戳一戳/入退群等,结构化呈现,不进历史变量) */
|
|
11
16
|
role: 'user' | 'assistant' | 'event';
|
|
12
17
|
userId: string;
|
|
13
18
|
username: string;
|
|
14
19
|
messageId?: string;
|
|
15
|
-
/**
|
|
20
|
+
/** 原貌(satori 标签形态,含 @bot 渲染与图片标签):统一格式行(query/历史变量)用;event 条目为空串 */
|
|
16
21
|
content: string;
|
|
17
|
-
/** 剔除 @bot 的原貌:content
|
|
22
|
+
/** 剔除 @bot 的原貌:content 变量与精简行用;event 条目为空串 */
|
|
18
23
|
contentText: string;
|
|
19
|
-
/**
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
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.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ export declare const inject: {
|
|
|
6
6
|
};
|
|
7
7
|
export { Config };
|
|
8
8
|
/** 控制台插件配置页顶部说明:JSON 对象变量的占位符速查 */
|
|
9
|
-
export declare const usage = "\n## JSON \u5BF9\u8C61\u53D8\u91CF\u7684\u5360\u4F4D\u7B26\n\n\u300CJSON \u5BF9\u8C61\u300D\u5206\u652F\u7684\u6A21\u677F\u5185\u53EF\u7528\u4EE5\u4E0B\u5360\u4F4D\u7B26\uFF08\u6574\u4E2A\u5BF9\u8C61\u6CE8\u5165\u5B57\u6BB5\u540D\u5BF9\u5E94\u7684\u5355\u4E00\u53D8\u91CF\uFF09\uFF1A\n\n| \u5360\u4F4D\u7B26 | \u7C7B\u578B | \u8BF4\u660E |\n| --- | --- | --- |\n| `{{userId}}` `{{botId}}` `{{guildId}}` `{{channelId}}` `{{platform}}` | \u5B57\u7B26\u4E32 | \u4F1A\u8BDD\u8EAB\u4EFD |\n| `{{messageId}}` `{{username}}` `{{timestamp}}` | \u5B57\u7B26\u4E32 | \u6D88\u606F\u6807\u8BC6\u4E0E\u4F5C\u8005 |\n| `{{content}}` | \u5B57\u7B26\u4E32 | \u6D88\u606F\u539F\u8C8C |\n| `{{quoteContent}}` `{{quoteAuthorId}}` | \u5B57\u7B26\u4E32 | \u88AB\u5F15\u7528\u6D88\u606F\uFF08\u5F15\u7528\u6BB5 / \u4F5C\u8005\uFF09 |\n| `{{triggerType}}` `{{ruleName}}` `{{triggerTime}}` | \u5B57\u7B26\u4E32 | \u89E6\u53D1\u5143\u4FE1\u606F |\n| `{{history}}` / `{{history:N}}` | \u5B57\u7B26\u4E32 | \u5386\u53F2\u6D88\u606F\u6587\u672C\uFF0CN \u6307\u5B9A\u6761\u6570\uFF08\u7F3A\u7701\u7528\u5168\u5C40\u914D\u7F6E\uFF09 |\n| `{{isDirect}}` | \u5E03\u5C14 | \u662F\u5426\u79C1\u804A |\n\n- \u503C\u6070\u597D\u4E3A\u4E00\u4E2A\u5360\u4F4D\u7B26\uFF08\u5982 `\"is_private\": \"{{isDirect}}\"`\uFF09\u65F6\u4FDD\u7559\u539F\u751F\u7C7B\u578B\n- \u5360\u4F4D\u7B26\u6DF7\u5165\u5176\u4ED6\u6587\u5B57\uFF08\u5982 `\"\u4F60\u597D {{username}}\"`\uFF09\u6309\u5B57\u7B26\u4E32\u62FC\u63A5\uFF0C\u5F15\u53F7\u6362\u884C\u81EA\u52A8\u8F6C\u4E49\n- \u672A\u77E5\u53D8\u91CF\u5F97\u7A7A\u4E32\n";
|
|
9
|
+
export declare const usage = "\n## JSON \u5BF9\u8C61\u53D8\u91CF\u7684\u5360\u4F4D\u7B26\n\n\u300CJSON \u5BF9\u8C61\u300D\u5206\u652F\u7684\u6A21\u677F\u5185\u53EF\u7528\u4EE5\u4E0B\u5360\u4F4D\u7B26\uFF08\u6574\u4E2A\u5BF9\u8C61\u6CE8\u5165\u5B57\u6BB5\u540D\u5BF9\u5E94\u7684\u5355\u4E00\u53D8\u91CF\uFF09\uFF1A\n\n| \u5360\u4F4D\u7B26 | \u7C7B\u578B | \u8BF4\u660E |\n| --- | --- | --- |\n| `{{userId}}` `{{botId}}` `{{botName}}` `{{guildId}}` `{{channelId}}` `{{platform}}` | \u5B57\u7B26\u4E32 | \u4F1A\u8BDD\u8EAB\u4EFD |\n| `{{messageId}}` `{{username}}` `{{timestamp}}` | \u5B57\u7B26\u4E32 | \u6D88\u606F\u6807\u8BC6\u4E0E\u4F5C\u8005 |\n| `{{content}}` | \u5B57\u7B26\u4E32 | \u6D88\u606F\u539F\u8C8C |\n| `{{quoteContent}}` `{{quoteAuthorId}}` | \u5B57\u7B26\u4E32 | \u88AB\u5F15\u7528\u6D88\u606F\uFF08\u5F15\u7528\u6BB5 / \u4F5C\u8005\uFF09 |\n| `{{triggerType}}` `{{ruleName}}` `{{triggerTime}}` | \u5B57\u7B26\u4E32 | \u89E6\u53D1\u5143\u4FE1\u606F |\n| `{{history}}` / `{{history:N}}` | \u5B57\u7B26\u4E32 | \u5386\u53F2\u6D88\u606F\u6587\u672C\uFF0CN \u6307\u5B9A\u6761\u6570\uFF08\u7F3A\u7701\u7528\u5168\u5C40\u914D\u7F6E\uFF09 |\n| `{{isDirect}}` | \u5E03\u5C14 | \u662F\u5426\u79C1\u804A |\n\n- \u503C\u6070\u597D\u4E3A\u4E00\u4E2A\u5360\u4F4D\u7B26\uFF08\u5982 `\"is_private\": \"{{isDirect}}\"`\uFF09\u65F6\u4FDD\u7559\u539F\u751F\u7C7B\u578B\n- \u5360\u4F4D\u7B26\u6DF7\u5165\u5176\u4ED6\u6587\u5B57\uFF08\u5982 `\"\u4F60\u597D {{username}}\"`\uFF09\u6309\u5B57\u7B26\u4E32\u62FC\u63A5\uFF0C\u5F15\u53F7\u6362\u884C\u81EA\u52A8\u8F6C\u4E49\n- \u672A\u77E5\u53D8\u91CF\u5F97\u7A7A\u4E32\n";
|
|
10
10
|
export declare function apply(ctx: Context, config: Config): void;
|
package/lib/index.js
CHANGED
|
@@ -36,7 +36,8 @@ var zh_CN_default = {
|
|
|
36
36
|
"conv-reset": "已重置 {0} 条会话绑定。"
|
|
37
37
|
},
|
|
38
38
|
errors: {
|
|
39
|
-
"request-failed": "Dify 请求失败:{0}"
|
|
39
|
+
"request-failed": "Dify 请求失败:{0}",
|
|
40
|
+
"command-args-mismatch": "参数数量不符:需要 {0} 个,收到 {1} 个;不带参数则按默认取值。"
|
|
40
41
|
}
|
|
41
42
|
}
|
|
42
43
|
};
|
|
@@ -49,7 +50,8 @@ var en_US_default = {
|
|
|
49
50
|
"conv-reset": "Reset {0} conversation binding(s)."
|
|
50
51
|
},
|
|
51
52
|
errors: {
|
|
52
|
-
"request-failed": "Dify request failed: {0}"
|
|
53
|
+
"request-failed": "Dify request failed: {0}",
|
|
54
|
+
"command-args-mismatch": "Argument count mismatch: expected {0}, got {1}; omit arguments to use defaults."
|
|
53
55
|
}
|
|
54
56
|
}
|
|
55
57
|
};
|
|
@@ -97,6 +99,10 @@ var conditionSchema = import_koishi.Schema.union([
|
|
|
97
99
|
type: import_koishi.Schema.const("quote-user").required(),
|
|
98
100
|
userIds: import_koishi.Schema.string().role("textarea").required().description("用户 ID,每行一个")
|
|
99
101
|
}).default({ type: "quote-user", userIds: "" }).description("引用指定用户"),
|
|
102
|
+
import_koishi.Schema.object({
|
|
103
|
+
type: import_koishi.Schema.const("command").required(),
|
|
104
|
+
command: import_koishi.Schema.string().required().description("指令名")
|
|
105
|
+
}).default({ type: "command", command: "" }).description("指令"),
|
|
100
106
|
import_koishi.Schema.object({
|
|
101
107
|
type: renamedType("cron", "schedule").required(),
|
|
102
108
|
cron: import_koishi.Schema.string().default("").description("Cron 表达式"),
|
|
@@ -112,6 +118,7 @@ var sessionKeySchema = import_koishi.Schema.union([
|
|
|
112
118
|
import_koishi.Schema.const("none").description("无"),
|
|
113
119
|
import_koishi.Schema.const("userId").description("用户 ID"),
|
|
114
120
|
import_koishi.Schema.const("botId").description("Bot ID"),
|
|
121
|
+
import_koishi.Schema.const("botName").description("Bot 昵称"),
|
|
115
122
|
import_koishi.Schema.const("guildId").description("群聊 ID"),
|
|
116
123
|
import_koishi.Schema.const("channelId").description("频道 ID"),
|
|
117
124
|
import_koishi.Schema.const("platform").description("平台"),
|
|
@@ -280,6 +287,11 @@ function toCondition(entry) {
|
|
|
280
287
|
case "at-bot":
|
|
281
288
|
case "quote-bot":
|
|
282
289
|
return { type: entry.type };
|
|
290
|
+
case "command": {
|
|
291
|
+
const command = entry.command?.trim();
|
|
292
|
+
if (!command) return null;
|
|
293
|
+
return { type: "command", command };
|
|
294
|
+
}
|
|
283
295
|
case "cron": {
|
|
284
296
|
const cron = entry.cron?.trim();
|
|
285
297
|
const intervalMinutes = Number(entry.intervalMinutes);
|
|
@@ -559,17 +571,18 @@ function extractText(session) {
|
|
|
559
571
|
return parseTextSafe(session.content);
|
|
560
572
|
}
|
|
561
573
|
__name(extractText, "extractText");
|
|
562
|
-
var
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
574
|
+
var IMAGE_FALLBACK_TAG = "<img/>";
|
|
575
|
+
var escapeAttr = /* @__PURE__ */ __name((value) => value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """), "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)}"/>`;
|
|
566
579
|
}
|
|
567
|
-
__name(
|
|
580
|
+
__name(imageTag, "imageTag");
|
|
568
581
|
function annotateDroppedPlaceholders(text, droppedUrls) {
|
|
569
582
|
let result = text;
|
|
570
583
|
for (const url of droppedUrls) {
|
|
571
|
-
const
|
|
572
|
-
result = result.split(
|
|
584
|
+
const tag = imageTag(url);
|
|
585
|
+
result = result.split(tag).join(tag.replace("/>", " dropped/>"));
|
|
573
586
|
}
|
|
574
587
|
return result;
|
|
575
588
|
}
|
|
@@ -596,16 +609,18 @@ function extractTextWithPlaceholders(session, options = {}) {
|
|
|
596
609
|
for (const element of elementsOf(session)) {
|
|
597
610
|
if (element.type === "text") {
|
|
598
611
|
const text = element.attrs?.["content"] ?? "";
|
|
599
|
-
if (text) parts.push(text);
|
|
612
|
+
if (text) parts.push(import_koishi2.h.escape(text));
|
|
600
613
|
} else if (element.type === "at") {
|
|
601
614
|
if (options.excludeBotAt && element.attrs?.["id"] === session.selfId) continue;
|
|
602
|
-
const
|
|
603
|
-
|
|
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}/>`);
|
|
604
619
|
} else if (isImageElement(element)) {
|
|
605
|
-
parts.push(
|
|
620
|
+
parts.push(imageTag(imageSourceOf(element)));
|
|
606
621
|
}
|
|
607
622
|
}
|
|
608
|
-
return parts.join(" ").replace(
|
|
623
|
+
return parts.join(" ").replace(/[^\S\n]+/g, " ").trim();
|
|
609
624
|
}
|
|
610
625
|
__name(extractTextWithPlaceholders, "extractTextWithPlaceholders");
|
|
611
626
|
function extractImageUrls(session) {
|
|
@@ -628,22 +643,37 @@ function formatTimestamp(timestamp) {
|
|
|
628
643
|
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
629
644
|
}
|
|
630
645
|
__name(formatTimestamp, "formatTimestamp");
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
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");
|
|
635
658
|
function formatQuotedMessage(quote) {
|
|
636
|
-
return
|
|
659
|
+
return `<quote ${attr("time", formatTimestamp(quote.timestamp))} ${attr("name", quote.username)} ${attr("user", quote.userId)}>${quote.content}</quote>`;
|
|
637
660
|
}
|
|
638
661
|
__name(formatQuotedMessage, "formatQuotedMessage");
|
|
639
662
|
function formatHistoryEntry(entry) {
|
|
640
|
-
if (entry.role === "event")
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
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>`;
|
|
647
677
|
}
|
|
648
678
|
__name(formatHistoryEntry, "formatHistoryEntry");
|
|
649
679
|
function formatHistoryEntries(entries) {
|
|
@@ -652,8 +682,11 @@ function formatHistoryEntries(entries) {
|
|
|
652
682
|
__name(formatHistoryEntries, "formatHistoryEntries");
|
|
653
683
|
function formatHistoryBrief(entries) {
|
|
654
684
|
return entries.map((entry) => {
|
|
655
|
-
|
|
656
|
-
|
|
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>`;
|
|
657
690
|
}).join("\n");
|
|
658
691
|
}
|
|
659
692
|
__name(formatHistoryBrief, "formatHistoryBrief");
|
|
@@ -675,7 +708,8 @@ function buildHistoryEntry(session, role = "user") {
|
|
|
675
708
|
return {
|
|
676
709
|
role,
|
|
677
710
|
userId: role === "assistant" ? session.selfId : session.userId ?? "未知用户",
|
|
678
|
-
|
|
711
|
+
// bot 昵称取适配器登录信息(与 botName 变量同源),缺省回退 bot 账号
|
|
712
|
+
username: role === "assistant" ? session.bot?.user?.name || session.bot?.user?.nick || session.selfId : session.username || session.userId,
|
|
679
713
|
messageId: session.messageId,
|
|
680
714
|
content,
|
|
681
715
|
contentText: extractTextWithPlaceholders(session, { excludeBotAt: true }),
|
|
@@ -706,7 +740,7 @@ var MessageHistory = class {
|
|
|
706
740
|
get(channelKey, limit = this.limit) {
|
|
707
741
|
return (this.buffers.get(channelKey) ?? []).slice(-limit);
|
|
708
742
|
}
|
|
709
|
-
/**
|
|
743
|
+
/** 序列化为统一消息格式的逐条拼接(变量值即完整聊天记录文本) */
|
|
710
744
|
toVariable(entries) {
|
|
711
745
|
return formatHistoryEntries(entries);
|
|
712
746
|
}
|
|
@@ -717,9 +751,8 @@ function hasAt(session, id) {
|
|
|
717
751
|
return session.elements?.some((element) => element.type === "at" && element.attrs?.["id"] === id) ?? false;
|
|
718
752
|
}
|
|
719
753
|
__name(hasAt, "hasAt");
|
|
720
|
-
var escapeRegExp = /* @__PURE__ */ __name((text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "escapeRegExp");
|
|
721
754
|
var NON_TEXT_PREFIX = new RegExp(
|
|
722
|
-
`^(
|
|
755
|
+
`^(?:<at[^>]*/>|<img(?: src="[0-9a-f]{${IMAGE_HASH_LENGTH}}")?/>|\\s)*`
|
|
723
756
|
);
|
|
724
757
|
function stripPrefixKeyword(verbatim, keyword) {
|
|
725
758
|
const prefix = NON_TEXT_PREFIX.exec(verbatim)?.[0] ?? "";
|
|
@@ -899,52 +932,50 @@ var MessagePool = class {
|
|
|
899
932
|
};
|
|
900
933
|
|
|
901
934
|
// src/trigger/pool-events.ts
|
|
902
|
-
function
|
|
903
|
-
return `${session.username || session.userId} (${session.userId})`;
|
|
904
|
-
}
|
|
905
|
-
__name(actorOf, "actorOf");
|
|
906
|
-
function eventEntry(session, content) {
|
|
935
|
+
function eventEntry(session, event) {
|
|
907
936
|
return {
|
|
908
937
|
role: "event",
|
|
909
938
|
userId: session.userId ?? "",
|
|
910
939
|
username: session.username || session.userId || "",
|
|
911
|
-
content,
|
|
912
|
-
contentText:
|
|
940
|
+
content: "",
|
|
941
|
+
contentText: "",
|
|
942
|
+
event,
|
|
913
943
|
timestamp: session.timestamp ?? Date.now()
|
|
914
944
|
};
|
|
915
945
|
}
|
|
916
946
|
__name(eventEntry, "eventEntry");
|
|
917
947
|
function buildNoticeEntry(session) {
|
|
918
|
-
const actor = actorOf(session);
|
|
919
948
|
switch (session.subtype) {
|
|
920
949
|
case "poke": {
|
|
921
950
|
const target = session.targetId;
|
|
922
951
|
if (!target) return null;
|
|
923
|
-
return eventEntry(session,
|
|
952
|
+
return eventEntry(session, { type: "poke", attrs: { target: String(target) } });
|
|
924
953
|
}
|
|
925
954
|
case "lucky-king":
|
|
926
|
-
return eventEntry(session,
|
|
955
|
+
return eventEntry(session, { type: "lucky-king" });
|
|
927
956
|
case "honor":
|
|
928
|
-
return eventEntry(session,
|
|
957
|
+
return eventEntry(session, { type: "honor" });
|
|
929
958
|
default:
|
|
930
959
|
return null;
|
|
931
960
|
}
|
|
932
961
|
}
|
|
933
962
|
__name(buildNoticeEntry, "buildNoticeEntry");
|
|
934
963
|
function buildMemberEntry(session) {
|
|
935
|
-
const actor = actorOf(session);
|
|
936
964
|
const payload = session.onebot ?? {};
|
|
937
965
|
switch (session.subtype) {
|
|
938
966
|
// set/remove 被 adapter 覆盖为 role,原始值只在载荷
|
|
939
967
|
case "role":
|
|
940
|
-
return eventEntry(session,
|
|
968
|
+
return eventEntry(session, { type: payload.sub_type === "remove" ? "admin-unset" : "admin-set" });
|
|
941
969
|
case "ban": {
|
|
942
|
-
if (payload.sub_type === "lift_ban") return eventEntry(session,
|
|
970
|
+
if (payload.sub_type === "lift_ban") return eventEntry(session, { type: "unban" });
|
|
943
971
|
const seconds = Number(payload.duration) || 0;
|
|
944
|
-
return eventEntry(
|
|
972
|
+
return eventEntry(
|
|
973
|
+
session,
|
|
974
|
+
seconds > 0 ? { type: "ban", attrs: { duration: String(seconds) } } : { type: "ban" }
|
|
975
|
+
);
|
|
945
976
|
}
|
|
946
977
|
case "nickname":
|
|
947
|
-
return eventEntry(session,
|
|
978
|
+
return eventEntry(session, { type: "nickname" });
|
|
948
979
|
default:
|
|
949
980
|
return null;
|
|
950
981
|
}
|
|
@@ -952,14 +983,17 @@ function buildMemberEntry(session) {
|
|
|
952
983
|
__name(buildMemberEntry, "buildMemberEntry");
|
|
953
984
|
function buildJoinEntry(session) {
|
|
954
985
|
const invitedBy = session.subtype === "passive" && session.operatorId;
|
|
955
|
-
return eventEntry(
|
|
986
|
+
return eventEntry(
|
|
987
|
+
session,
|
|
988
|
+
invitedBy ? { type: "join", attrs: { invitedBy: String(session.operatorId) } } : { type: "join" }
|
|
989
|
+
);
|
|
956
990
|
}
|
|
957
991
|
__name(buildJoinEntry, "buildJoinEntry");
|
|
958
992
|
function buildLeaveEntry(session) {
|
|
959
993
|
if (session.subtype === "passive" && session.operatorId) {
|
|
960
|
-
return eventEntry(session,
|
|
994
|
+
return eventEntry(session, { type: "leave", attrs: { operator: String(session.operatorId) } });
|
|
961
995
|
}
|
|
962
|
-
return eventEntry(session,
|
|
996
|
+
return eventEntry(session, { type: "leave" });
|
|
963
997
|
}
|
|
964
998
|
__name(buildLeaveEntry, "buildLeaveEntry");
|
|
965
999
|
function recordable(session) {
|
|
@@ -1212,9 +1246,50 @@ var TriggerEngine = class {
|
|
|
1212
1246
|
this.pool.record(session, entry);
|
|
1213
1247
|
});
|
|
1214
1248
|
registerPoolEvents(this.ctx, this.pool);
|
|
1249
|
+
this.registerCommands();
|
|
1215
1250
|
this.scheduler.sync(this.rules);
|
|
1216
1251
|
this.ctx.logger.info("已加载 %d 条启用规则", this.rules.length);
|
|
1217
1252
|
}
|
|
1253
|
+
/** 把规则内的指令条件注册为顶层 koishi 指令(同名只注册首个,指令触发是显式意图不参与冷却) */
|
|
1254
|
+
registerCommands() {
|
|
1255
|
+
const registered = /* @__PURE__ */ new Set();
|
|
1256
|
+
for (const rule of this.rules) {
|
|
1257
|
+
for (const condition of rule.conditions) {
|
|
1258
|
+
if (condition.type !== "command") continue;
|
|
1259
|
+
if (registered.has(condition.command)) {
|
|
1260
|
+
this.ctx.logger.warn("指令 %s 已被注册,跳过后续规则", condition.command);
|
|
1261
|
+
continue;
|
|
1262
|
+
}
|
|
1263
|
+
registered.add(condition.command);
|
|
1264
|
+
this.ctx.command(condition.command).action(({ session, args }) => {
|
|
1265
|
+
if (session) void this.fireCommand(rule, session, args ?? []);
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
/** 指令触发:位置参数按序覆盖单值变量映射,数量不符报错(本地化),无参按默认取值 */
|
|
1271
|
+
async fireCommand(rule, session, args) {
|
|
1272
|
+
if (!matchScope(rule.scope, session)) return;
|
|
1273
|
+
if (args.length > 0) {
|
|
1274
|
+
const bindings = rule.variables.filter((binding) => binding.source.type !== "json");
|
|
1275
|
+
if (args.length !== bindings.length) {
|
|
1276
|
+
await session.send(session.text("dify-ai.errors.command-args-mismatch", [bindings.length, args.length])).catch(() => {
|
|
1277
|
+
});
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
const argsText = args.join(" ");
|
|
1282
|
+
this.run({
|
|
1283
|
+
session,
|
|
1284
|
+
...sessionIdentityOf(session),
|
|
1285
|
+
triggerType: "command",
|
|
1286
|
+
rule,
|
|
1287
|
+
// 无参时空串由请求器占位兜底
|
|
1288
|
+
queryText: argsText,
|
|
1289
|
+
contentText: argsText,
|
|
1290
|
+
commandArgs: args.length ? args : void 0
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1218
1293
|
handleMessage(session, next) {
|
|
1219
1294
|
if (this.ctx.bots[session.uid] || !session.channelId) return next();
|
|
1220
1295
|
const channelKey = channelKeyOf(session.platform, session.channelId);
|
|
@@ -1277,7 +1352,7 @@ var TriggerEngine = class {
|
|
|
1277
1352
|
...sessionIdentityOf(session),
|
|
1278
1353
|
triggerType: condition.type,
|
|
1279
1354
|
rule,
|
|
1280
|
-
// query
|
|
1355
|
+
// query 为该条消息的统一格式条目;纯 @ / 纯引用等无文本消息 entry 为空,由请求器占位兜底
|
|
1281
1356
|
queryText,
|
|
1282
1357
|
contentText: condition.contentText
|
|
1283
1358
|
});
|
|
@@ -1577,6 +1652,8 @@ function resolveSessionField(key, fireCtx, now) {
|
|
|
1577
1652
|
return fireCtx.userId ?? session?.userId ?? "";
|
|
1578
1653
|
case "botId":
|
|
1579
1654
|
return fireCtx.selfId ?? session?.selfId ?? "";
|
|
1655
|
+
case "botName":
|
|
1656
|
+
return session?.bot?.user?.name || session?.bot?.user?.nick || fireCtx.selfId;
|
|
1580
1657
|
case "guildId":
|
|
1581
1658
|
return fireCtx.guildId ?? "";
|
|
1582
1659
|
case "channelId":
|
|
@@ -1687,6 +1764,12 @@ function resolveVariables(rule, fireCtx, history) {
|
|
|
1687
1764
|
const value = resolveSource(binding.source, fireCtx, history, now);
|
|
1688
1765
|
if (value !== void 0) inputs[binding.field] = value;
|
|
1689
1766
|
}
|
|
1767
|
+
if (fireCtx.commandArgs) {
|
|
1768
|
+
const bindings = rule.variables.filter((binding) => binding.source.type !== "json");
|
|
1769
|
+
fireCtx.commandArgs.forEach((arg, index) => {
|
|
1770
|
+
inputs[bindings[index].field] = arg;
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1690
1773
|
return inputs;
|
|
1691
1774
|
}
|
|
1692
1775
|
__name(resolveVariables, "resolveVariables");
|
|
@@ -2128,7 +2211,7 @@ var usage = `
|
|
|
2128
2211
|
|
|
2129
2212
|
| 占位符 | 类型 | 说明 |
|
|
2130
2213
|
| --- | --- | --- |
|
|
2131
|
-
| \`{{userId}}\` \`{{botId}}\` \`{{guildId}}\` \`{{channelId}}\` \`{{platform}}\` | 字符串 | 会话身份 |
|
|
2214
|
+
| \`{{userId}}\` \`{{botId}}\` \`{{botName}}\` \`{{guildId}}\` \`{{channelId}}\` \`{{platform}}\` | 字符串 | 会话身份 |
|
|
2132
2215
|
| \`{{messageId}}\` \`{{username}}\` \`{{timestamp}}\` | 字符串 | 消息标识与作者 |
|
|
2133
2216
|
| \`{{content}}\` | 字符串 | 消息原貌 |
|
|
2134
2217
|
| \`{{quoteContent}}\` \`{{quoteAuthorId}}\` | 字符串 | 被引用消息(引用段 / 作者) |
|
package/lib/locales/en-US.d.ts
CHANGED
package/lib/locales/zh-CN.d.ts
CHANGED
|
@@ -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 变量的剥离文本,保留 @
|
|
5
|
+
/** content 变量的剥离文本,保留 @ 与图片标签(query 由引擎按统一消息格式另行构造) */
|
|
6
6
|
contentText: string;
|
|
7
7
|
}
|
|
8
8
|
/** 评估单个消息条件;返回 null 表示未命中(匹配基于纯文本,@ 元素不参与判定) */
|
package/lib/trigger/engine.d.ts
CHANGED
|
@@ -16,6 +16,10 @@ export declare class TriggerEngine {
|
|
|
16
16
|
private cooldown;
|
|
17
17
|
constructor(ctx: Context, runner: RequestRunner, history: MessageHistory, rules: DifyRule[], cooldown: CooldownSetting | null);
|
|
18
18
|
start(): void;
|
|
19
|
+
/** 把规则内的指令条件注册为顶层 koishi 指令(同名只注册首个,指令触发是显式意图不参与冷却) */
|
|
20
|
+
private registerCommands;
|
|
21
|
+
/** 指令触发:位置参数按序覆盖单值变量映射,数量不符报错(本地化),无参按默认取值 */
|
|
22
|
+
private fireCommand;
|
|
19
23
|
private handleMessage;
|
|
20
24
|
private matchRule;
|
|
21
25
|
/** 异步执行一次请求;错误由请求器与这里的兜底记录 */
|
package/lib/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Session } from 'koishi';
|
|
2
2
|
/** 消息驱动的触发原因(merged = 冷却期内多条触发消息合并为一次触发) */
|
|
3
|
-
export type MessageTriggerType = 'keyword-prefix' | 'keyword-contains' | 'at-bot' | 'at-user' | 'quote-bot' | 'quote-user' | 'merged';
|
|
3
|
+
export type MessageTriggerType = 'keyword-prefix' | 'keyword-contains' | 'at-bot' | 'at-user' | 'quote-bot' | 'quote-user' | 'merged' | 'command';
|
|
4
4
|
/** 非消息驱动的触发原因(triggerType 值 0.1.12 起 schedule→cron、density→frequency) */
|
|
5
5
|
export type ProactiveTriggerType = 'cron' | 'frequency';
|
|
6
6
|
export type TriggerType = MessageTriggerType | ProactiveTriggerType;
|
|
@@ -24,6 +24,11 @@ export interface AtBotCondition {
|
|
|
24
24
|
export interface QuoteBotCondition {
|
|
25
25
|
type: 'quote-bot';
|
|
26
26
|
}
|
|
27
|
+
/** 指令触发:指令名注册为顶层 koishi 指令,位置参数按序覆盖单值变量映射 */
|
|
28
|
+
export interface CommandCondition {
|
|
29
|
+
type: 'command';
|
|
30
|
+
command: string;
|
|
31
|
+
}
|
|
27
32
|
/** 定时触发(cron):cron(服务器本地时区)与固定间隔分钟数二选一 */
|
|
28
33
|
export interface ScheduleCondition {
|
|
29
34
|
type: 'cron';
|
|
@@ -40,7 +45,7 @@ export interface DensityCondition {
|
|
|
40
45
|
* 触发条件(判别联合)。规则内多个条件为「或」关系:任一命中即触发。
|
|
41
46
|
* 由 normalizeConfig 保证加载形态合法,消费方无需再兜底必填字段。
|
|
42
47
|
*/
|
|
43
|
-
export type TriggerCondition = KeywordCondition | UserCondition | AtBotCondition | QuoteBotCondition | ScheduleCondition | DensityCondition;
|
|
48
|
+
export type TriggerCondition = KeywordCondition | UserCondition | AtBotCondition | QuoteBotCondition | CommandCondition | ScheduleCondition | DensityCondition;
|
|
44
49
|
/** 触发作用域:留空的维度不做限制 */
|
|
45
50
|
export interface TriggerScope {
|
|
46
51
|
platforms?: string[];
|
|
@@ -53,7 +58,7 @@ export interface TriggerScope {
|
|
|
53
58
|
isDirect?: boolean;
|
|
54
59
|
}
|
|
55
60
|
/** 变量来源:从会话上下文取值 */
|
|
56
|
-
export type SessionField = 'userId' | 'botId' | 'guildId' | 'channelId' | 'platform' | 'messageId' | 'content' | 'quoteContent' | 'quoteAuthorId' | 'username' | 'timestamp' | 'isDirect';
|
|
61
|
+
export type SessionField = 'userId' | 'botId' | 'botName' | 'guildId' | 'channelId' | 'platform' | 'messageId' | 'content' | 'quoteContent' | 'quoteAuthorId' | 'username' | 'timestamp' | 'isDirect';
|
|
57
62
|
/** 变量来源:触发元信息 */
|
|
58
63
|
export type MetaField = 'triggerType' | 'ruleName' | 'triggerTime';
|
|
59
64
|
export type VariableSource = {
|
|
@@ -121,4 +126,6 @@ export interface FireContext {
|
|
|
121
126
|
imageUrls?: string[];
|
|
122
127
|
/** 无 session 的主动触发(定时/密度到期)从消息池透传的私聊标记:会话绑定与 isDirect 变量用 */
|
|
123
128
|
isDirect?: boolean;
|
|
129
|
+
/** 指令触发的位置参数:按序覆盖单值变量映射的值(JSON 分支不占位) */
|
|
130
|
+
commandArgs?: string[];
|
|
124
131
|
}
|
|
@@ -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
|
-
/**
|
|
14
|
-
export declare const
|
|
15
|
-
/**
|
|
16
|
-
export declare
|
|
17
|
-
/**
|
|
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
|
-
*
|
|
27
|
-
* img/image 元素渲染为
|
|
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.
|
|
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",
|