koishi-plugin-dify-ai 0.1.13 → 0.1.15

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
@@ -2,9 +2,8 @@ import { Schema } from 'koishi';
2
2
  import { CooldownSetting, DifyRule } from './types';
3
3
  export type AppTypeSetting = 'auto' | 'chat' | 'agent-chat' | 'advanced-chat' | 'workflow' | 'completion';
4
4
  export interface AppConfigEntry {
5
+ /** 应用标识:填 Dify 的应用 ID(沿用 name 字段名兼容既有绑定键与规则引用) */
5
6
  name: string;
6
- /** 会话绑定用的稳定标识;留空回退应用名 */
7
- appId: string;
8
7
  apiURL: string;
9
8
  apiKey: string;
10
9
  appType: AppTypeSetting;
@@ -96,6 +95,7 @@ export interface Config {
96
95
  requestTimeout: number;
97
96
  historyLimit: number;
98
97
  sendErrors: boolean;
98
+ debugLogging: boolean;
99
99
  cooldown: CooldownEntry;
100
100
  }
101
101
  /**
package/lib/index.d.ts CHANGED
@@ -5,4 +5,6 @@ export declare const inject: {
5
5
  required: string[];
6
6
  };
7
7
  export { Config };
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";
8
10
  export declare function apply(ctx: Context, config: Config): void;
package/lib/index.js CHANGED
@@ -23,7 +23,8 @@ __export(src_exports, {
23
23
  Config: () => Config,
24
24
  apply: () => apply,
25
25
  inject: () => inject,
26
- name: () => name
26
+ name: () => name,
27
+ usage: () => usage
27
28
  });
28
29
  module.exports = __toCommonJS(src_exports);
29
30
 
@@ -33,6 +34,9 @@ var zh_CN_default = {
33
34
  commands: {
34
35
  "conv-empty": "当前频道没有 Dify 会话绑定。",
35
36
  "conv-reset": "已重置 {0} 条会话绑定。"
37
+ },
38
+ errors: {
39
+ "request-failed": "Dify 请求失败:{0}"
36
40
  }
37
41
  }
38
42
  };
@@ -43,6 +47,9 @@ var en_US_default = {
43
47
  commands: {
44
48
  "conv-empty": "No Dify conversation bindings in this channel.",
45
49
  "conv-reset": "Reset {0} conversation binding(s)."
50
+ },
51
+ errors: {
52
+ "request-failed": "Dify request failed: {0}"
46
53
  }
47
54
  }
48
55
  };
@@ -200,8 +207,7 @@ var Config = import_koishi.Schema.intersect([
200
207
  import_koishi.Schema.object({
201
208
  apps: import_koishi.Schema.array(
202
209
  import_koishi.Schema.object({
203
- name: import_koishi.Schema.string().required().description("应用名"),
204
- appId: import_koishi.Schema.string().default("").description("应用 ID,会话绑定用,留空取应用名"),
210
+ name: import_koishi.Schema.string().required().description("应用 ID"),
205
211
  apiURL: import_koishi.Schema.string().required().role("link").description("API 地址"),
206
212
  apiKey: import_koishi.Schema.string().required().role("secret").description("App Key"),
207
213
  appType: appTypeSchema.default("auto").description("应用类型")
@@ -214,7 +220,7 @@ var Config = import_koishi.Schema.intersect([
214
220
  name: import_koishi.Schema.string().required().description("规则名"),
215
221
  enabled: import_koishi.Schema.boolean().default(true).description("启用"),
216
222
  priority: import_koishi.Schema.number().default(-1).description("优先级,大者先匹配"),
217
- app: import_koishi.Schema.string().required().description("应用名"),
223
+ app: import_koishi.Schema.string().required().description("应用 ID"),
218
224
  conversationScope: import_koishi.Schema.union([
219
225
  import_koishi.Schema.const("per-guild").description("按群聊"),
220
226
  import_koishi.Schema.const("per-user").description("按用户"),
@@ -250,6 +256,7 @@ var Config = import_koishi.Schema.intersect([
250
256
  requestTimeout: import_koishi.Schema.natural().role("ms").default(3e5).description("请求超时"),
251
257
  historyLimit: import_koishi.Schema.natural().default(20).min(1).description("历史消息条数"),
252
258
  sendErrors: import_koishi.Schema.boolean().default(false).description("失败时提示错误"),
259
+ debugLogging: import_koishi.Schema.boolean().default(false).description("输出错误调试日志"),
253
260
  cooldown: cooldownSchema.default({ mode: "off" }).description("触发后冷却")
254
261
  }).description("运行参数")
255
262
  ]);
@@ -1262,6 +1269,7 @@ var TriggerEngine = class {
1262
1269
  this.cooldown.begin(channelKey, ruleName, lane, Date.now());
1263
1270
  }
1264
1271
  fireMessage(rule, session, condition, entry) {
1272
+ const queryText = entry ? formatHistoryEntry(entry) : "";
1265
1273
  if (entry) entry.replied = true;
1266
1274
  this.beginCooldown(channelKeyOf(session.platform, session.channelId), rule.name, "message");
1267
1275
  this.run({
@@ -1270,7 +1278,7 @@ var TriggerEngine = class {
1270
1278
  triggerType: condition.type,
1271
1279
  rule,
1272
1280
  // query 为该条消息的统一格式单行;纯 @ / 纯引用等无文本消息 entry 为空,由请求器占位兜底
1273
- queryText: entry ? formatHistoryEntry(entry) : "",
1281
+ queryText,
1274
1282
  contentText: condition.contentText
1275
1283
  });
1276
1284
  }
@@ -1286,12 +1294,12 @@ var TriggerEngine = class {
1286
1294
  }
1287
1295
  /** 冷却到期:把缓冲内的触发消息合并为一次触发,session 取首条(供投递与文件上传) */
1288
1296
  fireMerged(rule, buffer) {
1297
+ const queryText = joinNonEmpty(buffer.map((item) => item.entry ? formatHistoryEntry(item.entry) : ""));
1298
+ const contentText = joinNonEmpty(buffer.map((item) => item.contentText));
1289
1299
  for (const item of buffer) {
1290
1300
  if (item.entry) item.entry.replied = true;
1291
1301
  }
1292
1302
  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
1303
  this.beginCooldown(channelKeyOf(first.session.platform, first.session.channelId), rule.name, "message");
1296
1304
  this.run({
1297
1305
  session: first.session,
@@ -1743,6 +1751,13 @@ function errorMessage(error) {
1743
1751
  return message || String(error);
1744
1752
  }
1745
1753
  __name(errorMessage, "errorMessage");
1754
+ function errorDetail(error) {
1755
+ if (error instanceof DifyApiError) {
1756
+ return `status=${error.status}${error.code ? ` code=${error.code}` : ""} ${error.stack ?? error.message}`;
1757
+ }
1758
+ return error instanceof Error ? error.stack ?? error.message : String(error);
1759
+ }
1760
+ __name(errorDetail, "errorDetail");
1746
1761
 
1747
1762
  // src/requester/runner.ts
1748
1763
  var FALLBACK_QUERY = "(本次触发无文本内容,请参考变量中的上下文)";
@@ -1795,6 +1810,8 @@ var RequestRunner = class {
1795
1810
  static {
1796
1811
  __name(this, "RequestRunner");
1797
1812
  }
1813
+ /** 启动期类型探测任务:auto 应用首次请求在探测完成前等待它(settle 即放行,失败仍回退 chat) */
1814
+ probeTask;
1798
1815
  /** 应用类型:schema 显式指定优先,auto 时用探测结果(未探测到回退 chat) */
1799
1816
  appTypeOf(app) {
1800
1817
  return app.appType !== "auto" ? app.appType : this.appTypes.get(app.name) ?? FALLBACK_APP_TYPE;
@@ -1810,7 +1827,7 @@ var RequestRunner = class {
1810
1827
  const client = createDifyClient(this.ctx, app, this.config.requestTimeout);
1811
1828
  if (!client) return;
1812
1829
  const requestCtx = {
1813
- bindingKey: this.conversationStore.computeBindingKey(app.appId || app.name, rule, fireCtx),
1830
+ bindingKey: this.conversationStore.computeBindingKey(app.name, rule, fireCtx),
1814
1831
  difyUser: this.conversationStore.computeDifyUser(rule, fireCtx),
1815
1832
  inputs: resolveVariables(rule, fireCtx, this.history),
1816
1833
  uploadedFiles: []
@@ -1820,9 +1837,12 @@ var RequestRunner = class {
1820
1837
  try {
1821
1838
  reply = await this.dispatch(app, client, fireCtx, requestCtx);
1822
1839
  } catch (error) {
1823
- this.ctx.logger.warn("规则 %s 请求失败:%s", rule.name, error);
1840
+ if (this.config.debugLogging) {
1841
+ this.ctx.logger.debug("规则 %s 请求失败详情:%s", rule.name, errorDetail(error));
1842
+ }
1843
+ this.ctx.logger.warn("规则 %s 请求失败:%s", rule.name, errorMessage(error));
1824
1844
  if (this.config.sendErrors && fireCtx.session) {
1825
- await fireCtx.session.send(`Dify 请求失败:${errorMessage(error)}`).catch(() => {
1845
+ await fireCtx.session.send(fireCtx.session.text("dify-ai.errors.request-failed", [errorMessage(error)])).catch(() => {
1826
1846
  });
1827
1847
  }
1828
1848
  return;
@@ -1871,6 +1891,10 @@ var RequestRunner = class {
1871
1891
  }
1872
1892
  /** 按应用类型分流:workflow/completion 无会话,chat 系续接 conversation_id */
1873
1893
  async dispatch(app, client, fireCtx, requestCtx) {
1894
+ if (app.appType === "auto" && !this.appTypes.has(app.name) && this.probeTask) {
1895
+ await this.probeTask.catch(() => {
1896
+ });
1897
+ }
1874
1898
  const base = {
1875
1899
  inputs: requestCtx.inputs,
1876
1900
  response_mode: "blocking",
@@ -2045,8 +2069,7 @@ var ConversationStore = class {
2045
2069
  for (const row of matched) {
2046
2070
  if (row.difyConversationId) {
2047
2071
  const { appId } = this.parseBindingKey(row.bindingKey);
2048
- const app = this.apps.get(appId) ?? this.findByAppId(appId);
2049
- const client = app && createDifyClient(this.ctx, app);
2072
+ const client = appId && this.apps.has(appId) ? createDifyClient(this.ctx, this.apps.get(appId)) : void 0;
2050
2073
  if (client) {
2051
2074
  await client.deleteConversation(row.difyConversationId, this.difyUserOfBindingKey(row.bindingKey)).catch((error) => this.ctx.logger.warn("删除 Dify 会话失败:%s", error));
2052
2075
  }
@@ -2056,13 +2079,6 @@ var ConversationStore = class {
2056
2079
  }
2057
2080
  return reset;
2058
2081
  }
2059
- /** 按应用 ID(apps 配置的 appId 字段)反查应用 */
2060
- findByAppId(appId) {
2061
- for (const app of this.apps.values()) {
2062
- if (app.appId && app.appId === appId) return app;
2063
- }
2064
- return void 0;
2065
- }
2066
2082
  };
2067
2083
 
2068
2084
  // src/state/tables.ts
@@ -2073,8 +2089,17 @@ function defineConversationTable(ctx) {
2073
2089
  }, { primary: "bindingKey" });
2074
2090
  }
2075
2091
  __name(defineConversationTable, "defineConversationTable");
2092
+ function defineProbeTable(ctx) {
2093
+ ctx.model.extend("dify_app_probe", {
2094
+ name: "string(255)",
2095
+ mode: "string(32)",
2096
+ updatedAt: "timestamp"
2097
+ }, { primary: "name" });
2098
+ }
2099
+ __name(defineProbeTable, "defineProbeTable");
2076
2100
  function defineTables(ctx) {
2077
2101
  defineConversationTable(ctx);
2102
+ defineProbeTable(ctx);
2078
2103
  }
2079
2104
  __name(defineTables, "defineTables");
2080
2105
 
@@ -2096,6 +2121,25 @@ __name(registerMiscCommands, "registerMiscCommands");
2096
2121
  // src/index.ts
2097
2122
  var name = "dify-ai";
2098
2123
  var inject = { required: ["database"] };
2124
+ var usage = `
2125
+ ## JSON 对象变量的占位符
2126
+
2127
+ 「JSON 对象」分支的模板内可用以下占位符(整个对象注入字段名对应的单一变量):
2128
+
2129
+ | 占位符 | 类型 | 说明 |
2130
+ | --- | --- | --- |
2131
+ | \`{{userId}}\` \`{{botId}}\` \`{{guildId}}\` \`{{channelId}}\` \`{{platform}}\` | 字符串 | 会话身份 |
2132
+ | \`{{messageId}}\` \`{{username}}\` \`{{timestamp}}\` | 字符串 | 消息标识与作者 |
2133
+ | \`{{content}}\` | 字符串 | 消息原貌 |
2134
+ | \`{{quoteContent}}\` \`{{quoteAuthorId}}\` | 字符串 | 被引用消息(引用段 / 作者) |
2135
+ | \`{{triggerType}}\` \`{{ruleName}}\` \`{{triggerTime}}\` | 字符串 | 触发元信息 |
2136
+ | \`{{history}}\` / \`{{history:N}}\` | 字符串 | 历史消息文本,N 指定条数(缺省用全局配置) |
2137
+ | \`{{isDirect}}\` | 布尔 | 是否私聊 |
2138
+
2139
+ - 值恰好为一个占位符(如 \`"is_private": "{{isDirect}}"\`)时保留原生类型
2140
+ - 占位符混入其他文字(如 \`"你好 {{username}}"\`)按字符串拼接,引号换行自动转义
2141
+ - 未知变量得空串
2142
+ `;
2099
2143
  var PROBE_TIMEOUT_MS = 1e4;
2100
2144
  function apply(ctx, config) {
2101
2145
  const startedAt = Date.now();
@@ -2109,11 +2153,16 @@ function apply(ctx, config) {
2109
2153
  const conversationStore = new ConversationStore(ctx, apps);
2110
2154
  const runner = new RequestRunner(ctx, config, conversationStore, history, apps, appTypes);
2111
2155
  const engine = new TriggerEngine(ctx, runner, history, rules, cooldown);
2112
- ctx.on("ready", () => {
2156
+ ctx.on("ready", async () => {
2157
+ const cached = await ctx.database.get("dify_app_probe", {}).catch(() => []);
2158
+ for (const row of cached) {
2159
+ if (apps.has(row.name)) appTypes.set(row.name, row.mode);
2160
+ }
2113
2161
  engine.start();
2114
2162
  ctx.logger.info("插件装配完成,耗时 %dms", Date.now() - startedAt);
2115
2163
  const probeStart = Date.now();
2116
- void probeAppTypes(ctx, apps, appTypes).then(() => {
2164
+ runner.probeTask = probeAppTypes(ctx, apps, appTypes);
2165
+ void runner.probeTask.then(() => {
2117
2166
  ctx.logger.info("应用类型探测完成,耗时 %dms", Date.now() - probeStart);
2118
2167
  });
2119
2168
  });
@@ -2131,6 +2180,7 @@ async function probeAppTypes(ctx, apps, appTypes) {
2131
2180
  try {
2132
2181
  const info = await client.getAppInfo();
2133
2182
  appTypes.set(app.name, info.mode);
2183
+ await ctx.database.upsert("dify_app_probe", [{ name: app.name, mode: info.mode, updatedAt: /* @__PURE__ */ new Date() }]).catch((error) => ctx.logger.warn("探测结果写库失败:%s", error));
2134
2184
  ctx.logger.info("应用 %s 类型探测:%s", app.name, info.mode);
2135
2185
  } catch (error) {
2136
2186
  ctx.logger.warn("应用 %s 类型探测失败(按 chat 处理):%s", app.name, error);
@@ -2144,5 +2194,6 @@ __name(probeAppTypes, "probeAppTypes");
2144
2194
  Config,
2145
2195
  apply,
2146
2196
  inject,
2147
- name
2197
+ name,
2198
+ usage
2148
2199
  });
@@ -4,6 +4,9 @@ declare const _default: {
4
4
  'conv-empty': string;
5
5
  'conv-reset': string;
6
6
  };
7
+ errors: {
8
+ 'request-failed': string;
9
+ };
7
10
  };
8
11
  };
9
12
  export default _default;
@@ -4,6 +4,9 @@ declare const _default: {
4
4
  'conv-empty': string;
5
5
  'conv-reset': string;
6
6
  };
7
+ errors: {
8
+ 'request-failed': string;
9
+ };
7
10
  };
8
11
  };
9
12
  export default _default;
@@ -25,6 +25,8 @@ export declare class RequestRunner {
25
25
  apps: Map<string, AppConfigEntry>,
26
26
  /** 启动探测结果(name → Dify mode),由 index 在 ready 后填充 */
27
27
  appTypes: Map<string, string>);
28
+ /** 启动期类型探测任务:auto 应用首次请求在探测完成前等待它(settle 即放行,失败仍回退 chat) */
29
+ probeTask?: Promise<void>;
28
30
  /** 应用类型:schema 显式指定优先,auto 时用探测结果(未探测到回退 chat) */
29
31
  private appTypeOf;
30
32
  run(fireCtx: FireContext): Promise<void>;
@@ -48,6 +48,4 @@ export declare class ConversationStore {
48
48
  isDirect?: boolean;
49
49
  userId?: string;
50
50
  }): Promise<number>;
51
- /** 按应用 ID(apps 配置的 appId 字段)反查应用 */
52
- private findByAppId;
53
51
  }
@@ -5,9 +5,16 @@ export interface DifyConversationRow {
5
5
  /** Dify 侧 conversation_id;workflow/completion 类应用恒为空 */
6
6
  difyConversationId: string;
7
7
  }
8
+ /** 应用类型探测的持久化缓存:重载后先读缓存分流,后台探测刷新 */
9
+ export interface DifyAppProbeRow {
10
+ name: string;
11
+ mode: string;
12
+ updatedAt: Date;
13
+ }
8
14
  declare module 'koishi' {
9
15
  interface Tables {
10
16
  dify_conversation: DifyConversationRow;
17
+ dify_app_probe: DifyAppProbeRow;
11
18
  }
12
19
  }
13
20
  export declare function defineTables(ctx: Context): void;
@@ -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.13",
4
+ "version": "0.1.15",
5
5
  "author": "PinkElysia",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/PinkElysiaDev/dify-ai-plugin-for-Koishi#readme",