koishi-plugin-dify-ai 0.1.14 → 0.1.16

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 CHANGED
@@ -25,6 +25,9 @@ export type ConditionEntry = {
25
25
  } | {
26
26
  type: 'quote-user';
27
27
  userIds: string;
28
+ } | {
29
+ type: 'command';
30
+ command: string;
28
31
  } | {
29
32
  type: 'cron';
30
33
  cron?: string;
@@ -95,6 +98,7 @@ export interface Config {
95
98
  requestTimeout: number;
96
99
  historyLimit: number;
97
100
  sendErrors: boolean;
101
+ debugLogging: boolean;
98
102
  cooldown: CooldownEntry;
99
103
  }
100
104
  /**
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
@@ -34,6 +34,10 @@ var zh_CN_default = {
34
34
  commands: {
35
35
  "conv-empty": "当前频道没有 Dify 会话绑定。",
36
36
  "conv-reset": "已重置 {0} 条会话绑定。"
37
+ },
38
+ errors: {
39
+ "request-failed": "Dify 请求失败:{0}",
40
+ "command-args-mismatch": "参数数量不符:需要 {0} 个,收到 {1} 个;不带参数则按默认取值。"
37
41
  }
38
42
  }
39
43
  };
@@ -44,6 +48,10 @@ var en_US_default = {
44
48
  commands: {
45
49
  "conv-empty": "No Dify conversation bindings in this channel.",
46
50
  "conv-reset": "Reset {0} conversation binding(s)."
51
+ },
52
+ errors: {
53
+ "request-failed": "Dify request failed: {0}",
54
+ "command-args-mismatch": "Argument count mismatch: expected {0}, got {1}; omit arguments to use defaults."
47
55
  }
48
56
  }
49
57
  };
@@ -91,6 +99,10 @@ var conditionSchema = import_koishi.Schema.union([
91
99
  type: import_koishi.Schema.const("quote-user").required(),
92
100
  userIds: import_koishi.Schema.string().role("textarea").required().description("用户 ID,每行一个")
93
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("指令"),
94
106
  import_koishi.Schema.object({
95
107
  type: renamedType("cron", "schedule").required(),
96
108
  cron: import_koishi.Schema.string().default("").description("Cron 表达式"),
@@ -106,6 +118,7 @@ var sessionKeySchema = import_koishi.Schema.union([
106
118
  import_koishi.Schema.const("none").description("无"),
107
119
  import_koishi.Schema.const("userId").description("用户 ID"),
108
120
  import_koishi.Schema.const("botId").description("Bot ID"),
121
+ import_koishi.Schema.const("botName").description("Bot 昵称"),
109
122
  import_koishi.Schema.const("guildId").description("群聊 ID"),
110
123
  import_koishi.Schema.const("channelId").description("频道 ID"),
111
124
  import_koishi.Schema.const("platform").description("平台"),
@@ -250,6 +263,7 @@ var Config = import_koishi.Schema.intersect([
250
263
  requestTimeout: import_koishi.Schema.natural().role("ms").default(3e5).description("请求超时"),
251
264
  historyLimit: import_koishi.Schema.natural().default(20).min(1).description("历史消息条数"),
252
265
  sendErrors: import_koishi.Schema.boolean().default(false).description("失败时提示错误"),
266
+ debugLogging: import_koishi.Schema.boolean().default(false).description("输出错误调试日志"),
253
267
  cooldown: cooldownSchema.default({ mode: "off" }).description("触发后冷却")
254
268
  }).description("运行参数")
255
269
  ]);
@@ -273,6 +287,11 @@ function toCondition(entry) {
273
287
  case "at-bot":
274
288
  case "quote-bot":
275
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
+ }
276
295
  case "cron": {
277
296
  const cron = entry.cron?.trim();
278
297
  const intervalMinutes = Number(entry.intervalMinutes);
@@ -1205,9 +1224,50 @@ var TriggerEngine = class {
1205
1224
  this.pool.record(session, entry);
1206
1225
  });
1207
1226
  registerPoolEvents(this.ctx, this.pool);
1227
+ this.registerCommands();
1208
1228
  this.scheduler.sync(this.rules);
1209
1229
  this.ctx.logger.info("已加载 %d 条启用规则", this.rules.length);
1210
1230
  }
1231
+ /** 把规则内的指令条件注册为顶层 koishi 指令(同名只注册首个,指令触发是显式意图不参与冷却) */
1232
+ registerCommands() {
1233
+ const registered = /* @__PURE__ */ new Set();
1234
+ for (const rule of this.rules) {
1235
+ for (const condition of rule.conditions) {
1236
+ if (condition.type !== "command") continue;
1237
+ if (registered.has(condition.command)) {
1238
+ this.ctx.logger.warn("指令 %s 已被注册,跳过后续规则", condition.command);
1239
+ continue;
1240
+ }
1241
+ registered.add(condition.command);
1242
+ this.ctx.command(condition.command).action(({ session, args }) => {
1243
+ if (session) void this.fireCommand(rule, session, args ?? []);
1244
+ });
1245
+ }
1246
+ }
1247
+ }
1248
+ /** 指令触发:位置参数按序覆盖单值变量映射,数量不符报错(本地化),无参按默认取值 */
1249
+ async fireCommand(rule, session, args) {
1250
+ if (!matchScope(rule.scope, session)) return;
1251
+ if (args.length > 0) {
1252
+ const bindings = rule.variables.filter((binding) => binding.source.type !== "json");
1253
+ if (args.length !== bindings.length) {
1254
+ await session.send(session.text("dify-ai.errors.command-args-mismatch", [bindings.length, args.length])).catch(() => {
1255
+ });
1256
+ return;
1257
+ }
1258
+ }
1259
+ const argsText = args.join(" ");
1260
+ this.run({
1261
+ session,
1262
+ ...sessionIdentityOf(session),
1263
+ triggerType: "command",
1264
+ rule,
1265
+ // 无参时空串由请求器占位兜底
1266
+ queryText: argsText,
1267
+ contentText: argsText,
1268
+ commandArgs: args.length ? args : void 0
1269
+ });
1270
+ }
1211
1271
  handleMessage(session, next) {
1212
1272
  if (this.ctx.bots[session.uid] || !session.channelId) return next();
1213
1273
  const channelKey = channelKeyOf(session.platform, session.channelId);
@@ -1262,6 +1322,7 @@ var TriggerEngine = class {
1262
1322
  this.cooldown.begin(channelKey, ruleName, lane, Date.now());
1263
1323
  }
1264
1324
  fireMessage(rule, session, condition, entry) {
1325
+ const queryText = entry ? formatHistoryEntry(entry) : "";
1265
1326
  if (entry) entry.replied = true;
1266
1327
  this.beginCooldown(channelKeyOf(session.platform, session.channelId), rule.name, "message");
1267
1328
  this.run({
@@ -1270,7 +1331,7 @@ var TriggerEngine = class {
1270
1331
  triggerType: condition.type,
1271
1332
  rule,
1272
1333
  // query 为该条消息的统一格式单行;纯 @ / 纯引用等无文本消息 entry 为空,由请求器占位兜底
1273
- queryText: entry ? formatHistoryEntry(entry) : "",
1334
+ queryText,
1274
1335
  contentText: condition.contentText
1275
1336
  });
1276
1337
  }
@@ -1286,12 +1347,12 @@ var TriggerEngine = class {
1286
1347
  }
1287
1348
  /** 冷却到期:把缓冲内的触发消息合并为一次触发,session 取首条(供投递与文件上传) */
1288
1349
  fireMerged(rule, buffer) {
1350
+ const queryText = joinNonEmpty(buffer.map((item) => item.entry ? formatHistoryEntry(item.entry) : ""));
1351
+ const contentText = joinNonEmpty(buffer.map((item) => item.contentText));
1289
1352
  for (const item of buffer) {
1290
1353
  if (item.entry) item.entry.replied = true;
1291
1354
  }
1292
1355
  const first = buffer[0];
1293
- const queryText = joinNonEmpty(buffer.map((item) => item.entry ? formatHistoryEntry(item.entry) : ""));
1294
- const contentText = joinNonEmpty(buffer.map((item) => item.contentText));
1295
1356
  this.beginCooldown(channelKeyOf(first.session.platform, first.session.channelId), rule.name, "message");
1296
1357
  this.run({
1297
1358
  session: first.session,
@@ -1569,6 +1630,8 @@ function resolveSessionField(key, fireCtx, now) {
1569
1630
  return fireCtx.userId ?? session?.userId ?? "";
1570
1631
  case "botId":
1571
1632
  return fireCtx.selfId ?? session?.selfId ?? "";
1633
+ case "botName":
1634
+ return session?.bot?.user?.name || session?.bot?.user?.nick || fireCtx.selfId;
1572
1635
  case "guildId":
1573
1636
  return fireCtx.guildId ?? "";
1574
1637
  case "channelId":
@@ -1679,6 +1742,12 @@ function resolveVariables(rule, fireCtx, history) {
1679
1742
  const value = resolveSource(binding.source, fireCtx, history, now);
1680
1743
  if (value !== void 0) inputs[binding.field] = value;
1681
1744
  }
1745
+ if (fireCtx.commandArgs) {
1746
+ const bindings = rule.variables.filter((binding) => binding.source.type !== "json");
1747
+ fireCtx.commandArgs.forEach((arg, index) => {
1748
+ inputs[bindings[index].field] = arg;
1749
+ });
1750
+ }
1682
1751
  return inputs;
1683
1752
  }
1684
1753
  __name(resolveVariables, "resolveVariables");
@@ -1743,6 +1812,13 @@ function errorMessage(error) {
1743
1812
  return message || String(error);
1744
1813
  }
1745
1814
  __name(errorMessage, "errorMessage");
1815
+ function errorDetail(error) {
1816
+ if (error instanceof DifyApiError) {
1817
+ return `status=${error.status}${error.code ? ` code=${error.code}` : ""} ${error.stack ?? error.message}`;
1818
+ }
1819
+ return error instanceof Error ? error.stack ?? error.message : String(error);
1820
+ }
1821
+ __name(errorDetail, "errorDetail");
1746
1822
 
1747
1823
  // src/requester/runner.ts
1748
1824
  var FALLBACK_QUERY = "(本次触发无文本内容,请参考变量中的上下文)";
@@ -1822,9 +1898,12 @@ var RequestRunner = class {
1822
1898
  try {
1823
1899
  reply = await this.dispatch(app, client, fireCtx, requestCtx);
1824
1900
  } catch (error) {
1825
- this.ctx.logger.warn("规则 %s 请求失败:%s", rule.name, error);
1901
+ if (this.config.debugLogging) {
1902
+ this.ctx.logger.debug("规则 %s 请求失败详情:%s", rule.name, errorDetail(error));
1903
+ }
1904
+ this.ctx.logger.warn("规则 %s 请求失败:%s", rule.name, errorMessage(error));
1826
1905
  if (this.config.sendErrors && fireCtx.session) {
1827
- await fireCtx.session.send(`Dify 请求失败:${errorMessage(error)}`).catch(() => {
1906
+ await fireCtx.session.send(fireCtx.session.text("dify-ai.errors.request-failed", [errorMessage(error)])).catch(() => {
1828
1907
  });
1829
1908
  }
1830
1909
  return;
@@ -2110,7 +2189,7 @@ var usage = `
2110
2189
 
2111
2190
  | 占位符 | 类型 | 说明 |
2112
2191
  | --- | --- | --- |
2113
- | \`{{userId}}\` \`{{botId}}\` \`{{guildId}}\` \`{{channelId}}\` \`{{platform}}\` | 字符串 | 会话身份 |
2192
+ | \`{{userId}}\` \`{{botId}}\` \`{{botName}}\` \`{{guildId}}\` \`{{channelId}}\` \`{{platform}}\` | 字符串 | 会话身份 |
2114
2193
  | \`{{messageId}}\` \`{{username}}\` \`{{timestamp}}\` | 字符串 | 消息标识与作者 |
2115
2194
  | \`{{content}}\` | 字符串 | 消息原貌 |
2116
2195
  | \`{{quoteContent}}\` \`{{quoteAuthorId}}\` | 字符串 | 被引用消息(引用段 / 作者) |
@@ -4,6 +4,10 @@ declare const _default: {
4
4
  'conv-empty': string;
5
5
  'conv-reset': string;
6
6
  };
7
+ errors: {
8
+ 'request-failed': string;
9
+ 'command-args-mismatch': string;
10
+ };
7
11
  };
8
12
  };
9
13
  export default _default;
@@ -4,6 +4,10 @@ declare const _default: {
4
4
  'conv-empty': string;
5
5
  'conv-reset': string;
6
6
  };
7
+ errors: {
8
+ 'request-failed': string;
9
+ 'command-args-mismatch': string;
10
+ };
7
11
  };
8
12
  };
9
13
  export default _default;
@@ -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
  }
@@ -1,2 +1,4 @@
1
1
  /** 统一把 unknown 错误转为可读消息(Error.message 优先,空消息回退 String 形态) */
2
2
  export declare function errorMessage(error: unknown): string;
3
+ /** 调试日志用的错误详情:Dify 报错展开状态码与错误码,附带调用栈 */
4
+ export declare function errorDetail(error: unknown): 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.14",
4
+ "version": "0.1.16",
5
5
  "author": "PinkElysia",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/PinkElysiaDev/dify-ai-plugin-for-Koishi#readme",