dsh-message-gateway 0.1.7 → 0.1.8

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/index.js CHANGED
@@ -266,6 +266,11 @@ var TelegramBridge = class {
266
266
  this.working.delete(streamId);
267
267
  }
268
268
  }
269
+ /** 主动推送:以机器人身份向指定 chat 发送文本(不经回复管线,无编辑)。 */
270
+ async send(chatId, content) {
271
+ const result = await this.sendText(chatId, content);
272
+ return result !== null;
273
+ }
269
274
  /** 发送文本(Markdown 失败自动降级纯文本)。 */
270
275
  async sendText(chatId, text) {
271
276
  const body = { chat_id: chatId, text: text.slice(0, MSG_LIMIT), parse_mode: "Markdown", disable_web_page_preview: true };
@@ -477,6 +482,18 @@ var DiscordBridge = class {
477
482
  this.working.delete(streamId);
478
483
  }
479
484
  }
485
+ /** 主动推送:向指定频道发送文本消息(不经回复管线)。 */
486
+ async send(channelId, content) {
487
+ try {
488
+ const result = await this.rest("POST", `/channels/${encodeURIComponent(channelId)}/messages`, {
489
+ content: content.slice(0, MSG_LIMIT2)
490
+ });
491
+ return result?.id !== void 0;
492
+ } catch (error) {
493
+ console.error("[dsh-message-gateway] discord send failed", error);
494
+ return false;
495
+ }
496
+ }
480
497
  /** 停止网关连接。 */
481
498
  stop() {
482
499
  this.stopped = true;
@@ -1471,6 +1488,22 @@ var EmailBridge = class {
1471
1488
  console.error("[dsh-message-gateway] email reply failed", error);
1472
1489
  }
1473
1490
  }
1491
+ /** 主动推送:向任意收件人发送邮件(SMTP 配置复用桥凭据)。 */
1492
+ async send(to, subject, content) {
1493
+ try {
1494
+ const smtpHost = this.cred.smtpHost ?? this.cred.imapHost;
1495
+ const smtpPort = Number(this.cred.smtpPort || "465");
1496
+ const smtpUser = this.cred.smtpUser ?? this.cred.imapUser;
1497
+ const smtpPass = this.cred.smtpPass ?? this.cred.imapPass;
1498
+ const smtp = new SmtpClient(smtpHost, smtpPort, smtpUser, smtpPass, smtpUser);
1499
+ const ok = await smtp.send(to, subject, content);
1500
+ console.log("[dsh-message-gateway] email push sent", { to, subject: subject.slice(0, 40), ok });
1501
+ return ok;
1502
+ } catch (error) {
1503
+ console.error("[dsh-message-gateway] email push failed", error);
1504
+ return false;
1505
+ }
1506
+ }
1474
1507
  /** 停止轮询。 */
1475
1508
  stop() {
1476
1509
  this.stopped = true;
@@ -1586,10 +1619,11 @@ var BridgeManager = class {
1586
1619
  this.onStatusCallback = fn;
1587
1620
  }
1588
1621
  /** 创建/获取某聊天的独立 agent:独立会话 + 模型配置(默认跟随部署,可被 botModel 覆盖)。 */
1589
- async ensureAgentForKey(key) {
1590
- const existing = this.agents.get(key);
1622
+ async ensureAgentForKey(key, route) {
1623
+ const sessionKey = route?.agentPreset !== void 0 || route?.skill !== void 0 ? `${key}::${route?.agentPreset ?? ""}#${route?.skill ?? ""}` : key;
1624
+ const existing = this.agents.get(sessionKey);
1591
1625
  if (existing !== void 0) return existing.agent;
1592
- const override = this.config.botModel;
1626
+ const override = route?.botModel ?? this.config.botModel;
1593
1627
  let selection;
1594
1628
  if (override !== void 0 && override.provider !== "" && override.model !== "") {
1595
1629
  selection = { provider: override.provider, model: override.model };
@@ -1628,18 +1662,34 @@ var BridgeManager = class {
1628
1662
  const presets = agentCtx.get?.("agentPresets");
1629
1663
  if (presets !== void 0) {
1630
1664
  try {
1631
- await presets.mount(agentCtx);
1665
+ await presets.mount(agentCtx, route?.agentPreset);
1632
1666
  } catch (error) {
1633
1667
  console.warn("[dsh-message-gateway] agent preset mount skipped", String(error));
1634
1668
  }
1635
1669
  }
1670
+ if (route?.skill !== void 0) {
1671
+ const skills = agentCtx.get?.("skills");
1672
+ if (skills !== void 0) {
1673
+ try {
1674
+ if (typeof skills.mount === "function") {
1675
+ await skills.mount(agentCtx, route.skill);
1676
+ } else {
1677
+ const catalog = await skills.list?.();
1678
+ const found = catalog?.find((s) => s.id === route.skill);
1679
+ if (found !== void 0) console.log("[dsh-message-gateway] route skill available", route.skill);
1680
+ }
1681
+ } catch (error) {
1682
+ console.warn("[dsh-message-gateway] route skill mount skipped", String(error));
1683
+ }
1684
+ }
1685
+ }
1636
1686
  if (selection !== void 0) {
1637
1687
  installModelSelection(agentCtx, { current: selection, assembled: void 0 });
1638
1688
  }
1639
1689
  }
1640
1690
  });
1641
- this.agents.set(key, { agent: handle.agent, dispose: () => handle.dispose() });
1642
- console.log("[dsh-message-gateway] dedicated agent ready", { key, session: handle.agent.session.id, provider, model });
1691
+ this.agents.set(sessionKey, { agent: handle.agent, dispose: () => handle.dispose() });
1692
+ console.log("[dsh-message-gateway] dedicated agent ready", { key: sessionKey, session: handle.agent.session.id, provider, model, preset: route?.agentPreset ?? "(default)", skill: route?.skill ?? void 0 });
1643
1693
  return handle.agent;
1644
1694
  } catch (error) {
1645
1695
  console.error("[dsh-message-gateway] create agent failed", error);
@@ -1692,7 +1742,9 @@ var BridgeManager = class {
1692
1742
  id.sink.stream(id.frame, `busy-${Date.now().toString(36)}`, this.t("busy"), true);
1693
1743
  return;
1694
1744
  }
1695
- const agent = await this.ensureAgentForKey(id.key);
1745
+ const route = this.matchRoute(id.key, text);
1746
+ const routedText = route !== null && route.prefix !== "" ? text.slice(route.prefix.length).trim() : text;
1747
+ const agent = await this.ensureAgentForKey(id.key, route?.rule);
1696
1748
  if (agent === null) {
1697
1749
  console.warn("[dsh-message-gateway] no dedicated agent available");
1698
1750
  return;
@@ -1700,7 +1752,7 @@ var BridgeManager = class {
1700
1752
  const message = {
1701
1753
  id: MessageId(`dsh-gateway-${Date.now().toString(36)}`),
1702
1754
  role: "user",
1703
- content: [{ type: "text", text }],
1755
+ content: [{ type: "text", text: routedText }],
1704
1756
  source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
1705
1757
  };
1706
1758
  const session = agent.session;
@@ -1846,6 +1898,48 @@ var BridgeManager = class {
1846
1898
  if (this.wecom === null) return false;
1847
1899
  return this.wecom.sendMessage(chatid, content);
1848
1900
  }
1901
+ /**
1902
+ * 主动推送:向任意平台的目标会话发送文本(供 cron 通知、其他插件调用)。
1903
+ * 支持平台:wecom-aibot(企微智能机器人)/ telegram / discord / email。
1904
+ * 不支持主动推送的平台(qq 等)返回明确错误。
1905
+ * @param platform 平台 id(见 PLATFORMS)。
1906
+ * @param target 目标(telegram=chatId 数字串;discord=channelId;wecom-aibot=userid/群ID;email=收件地址)。
1907
+ * @param content 文本内容。
1908
+ * @param opts.title 可选标题(email 作为主题;其他平台拼在正文前)。
1909
+ */
1910
+ async pushMessage(platform, target, content, opts = {}) {
1911
+ const text = opts.title !== void 0 && opts.title !== "" ? `\u3010${opts.title}\u3011
1912
+ ${content}` : content;
1913
+ switch (platform) {
1914
+ case "wecom-aibot": {
1915
+ if (this.wecom === null) return { ok: false, detail: "wecom-aibot bridge not connected" };
1916
+ const sent = await this.wecom.sendMessage(target, text);
1917
+ return sent ? { ok: true, detail: "sent" } : { ok: false, detail: "wecom send failed" };
1918
+ }
1919
+ case "telegram": {
1920
+ if (this.telegram === null) return { ok: false, detail: "telegram bridge not connected" };
1921
+ const chatId = Number(target);
1922
+ if (!Number.isInteger(chatId) || chatId <= 0) return { ok: false, detail: "telegram target must be a numeric chatId" };
1923
+ const sent = await this.telegram.send(chatId, text);
1924
+ return sent ? { ok: true, detail: "sent" } : { ok: false, detail: "telegram send failed" };
1925
+ }
1926
+ case "discord": {
1927
+ if (this.discord === null) return { ok: false, detail: "discord bridge not connected" };
1928
+ const sent = await this.discord.send(target, text);
1929
+ return sent ? { ok: true, detail: "sent" } : { ok: false, detail: "discord send failed" };
1930
+ }
1931
+ case "email": {
1932
+ if (this.email === null) return { ok: false, detail: "email bridge not connected" };
1933
+ const subject = opts.title ?? "DSH \u901A\u77E5";
1934
+ const sent = await this.email.send(target, subject, content);
1935
+ return sent ? { ok: true, detail: "sent" } : { ok: false, detail: "email send failed" };
1936
+ }
1937
+ case "qq":
1938
+ return { ok: false, detail: "QQ \u5E73\u53F0\u81EA 2025-04-21 \u8D77\u4E0D\u652F\u6301\u4E3B\u52A8\u63A8\u9001\uFF08\u4EC5\u88AB\u52A8\u56DE\u590D\uFF09\uFF0C\u65E0\u6CD5\u53D1\u9001\u4E3B\u52A8\u6D88\u606F" };
1939
+ default:
1940
+ return { ok: false, detail: `platform "${platform}" does not support push` };
1941
+ }
1942
+ }
1849
1943
  // ==================== Telegram / Discord / QQ / Email ====================
1850
1944
  telegram = null;
1851
1945
  discord = null;
@@ -1943,6 +2037,26 @@ var BridgeManager = class {
1943
2037
  }
1944
2038
  return stored ?? { state: "none", detail: "", testedAt: null };
1945
2039
  }
2040
+ /**
2041
+ * 消息路由匹配:按「平台 + 关键词前缀」在配置的 routes 中找第一条命中。
2042
+ * @param key 聊天键(`platform:chatKey`)。
2043
+ * @param text 原始消息文本。
2044
+ * @returns 命中的规则与匹配到的前缀(前缀需从消息中剥离后进入路由);未命中返回 null。
2045
+ */
2046
+ matchRoute(key, text) {
2047
+ const platform = key.split(":")[0] ?? "";
2048
+ const routes = this.config.routes ?? [];
2049
+ for (const rule of routes) {
2050
+ if (rule.matchPlatform !== void 0 && rule.matchPlatform !== "" && rule.matchPlatform !== platform) continue;
2051
+ const prefix = rule.matchPrefix ?? "";
2052
+ if (prefix !== "") {
2053
+ if (!text.startsWith(prefix)) continue;
2054
+ return { rule, prefix };
2055
+ }
2056
+ return { rule, prefix: "" };
2057
+ }
2058
+ return null;
2059
+ }
1946
2060
  /** 斜杠命令 / 关键词命令;已处理返回 true(不经 agent)。 */
1947
2061
  async handleCommand(text, key, reply) {
1948
2062
  if (text === "/help" || text === "\u5E2E\u52A9" || text === "\u83DC\u5355" || text === "\uFF1F" || text === "?") {
@@ -1968,6 +2082,23 @@ var BridgeManager = class {
1968
2082
  );
1969
2083
  return true;
1970
2084
  }
2085
+ if (text === "/stats" || text === "\u7EDF\u8BA1") {
2086
+ const bridgeLine = (label, status) => {
2087
+ const mark = status.state === "connected" ? "\u{1F7E2}" : status.state === "connecting" ? "\u{1F7E1}" : status.state === "error" ? "\u{1F534}" : "\u26AA";
2088
+ return `- ${label}: ${mark} ${status.detail || status.state}`;
2089
+ };
2090
+ const lines = [
2091
+ `${this.t("statusTitle")} /stats`,
2092
+ `- ${this.t("statusChats")}: ${this.chatCount()}`,
2093
+ bridgeLine("WeCom AI Bot", this.wecomStatus()),
2094
+ bridgeLine("Telegram", this.bridgeStatus("telegram")),
2095
+ bridgeLine("Discord", this.bridgeStatus("discord")),
2096
+ bridgeLine("QQ", this.bridgeStatus("qq")),
2097
+ bridgeLine("Email", this.bridgeStatus("email"))
2098
+ ];
2099
+ reply(lines.join("\n"));
2100
+ return true;
2101
+ }
1971
2102
  return false;
1972
2103
  }
1973
2104
  };
@@ -2853,6 +2984,24 @@ function registerGatewayRoutes(ctx, manager) {
2853
2984
  }
2854
2985
  return;
2855
2986
  }
2987
+ if (path === "/gateway/push") {
2988
+ const body = payload;
2989
+ const platform = typeof body?.platform === "string" ? body.platform.trim() : "";
2990
+ const target = typeof body?.target === "string" ? body.target.trim() : "";
2991
+ const content = typeof body?.content === "string" ? body.content.trim() : "";
2992
+ const title = typeof body?.title === "string" ? body.title.trim() : "";
2993
+ if (platform === "" || target === "" || content === "") {
2994
+ json(res, { ok: false, error: { code: "internal", message: "missing platform/target/content" } }, 400);
2995
+ return;
2996
+ }
2997
+ const result = await manager.pushMessage(platform, target, content, { title: title === "" ? void 0 : title });
2998
+ if (!result.ok) {
2999
+ json(res, { ok: false, error: { code: "internal", message: result.detail } }, 409);
3000
+ return;
3001
+ }
3002
+ json(res, { ok: true, value: { sent: true } });
3003
+ return;
3004
+ }
2856
3005
  if (path === "/gateway/send") {
2857
3006
  const body = payload;
2858
3007
  const chatid = typeof body?.chatid === "string" ? body.chatid.trim() : "";
@@ -2970,7 +3119,18 @@ var Config = Schema.object({
2970
3119
  autoStartDiscord: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 Discord \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2971
3120
  autoStartQQ: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 QQ \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5"),
2972
3121
  autoStartEmail: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684 Email \u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5\uFF08IMAP \u8F6E\u8BE2\uFF09"),
2973
- groupReply: Schema.boolean().default(true).description("\u662F\u5426\u56DE\u590D\u7FA4\u804A\u6D88\u606F\uFF08false \u65F6\u53EA\u5904\u7406\u5355\u804A\uFF09")
3122
+ groupReply: Schema.boolean().default(true).description("\u662F\u5426\u56DE\u590D\u7FA4\u804A\u6D88\u606F\uFF08false \u65F6\u53EA\u5904\u7406\u5355\u804A\uFF09"),
3123
+ routes: Schema.array(Schema.object({
3124
+ id: Schema.string().required().description("\u89C4\u5219 id\uFF08\u552F\u4E00\u6807\u8BC6\uFF09"),
3125
+ matchPlatform: Schema.string().description("\u5339\u914D\u5E73\u53F0 id\uFF08telegram/discord/qq/wecom-aibot/email/webhook \u7B49\uFF09\uFF1B\u7F3A\u7701=\u5168\u90E8\u5E73\u53F0"),
3126
+ matchPrefix: Schema.string().description('\u6D88\u606F\u524D\u7F00\u5173\u952E\u8BCD\uFF08\u5982 "code " \u6216 "@code"\uFF09\uFF1B\u547D\u4E2D\u540E\u6D88\u606F\u53BB\u6389\u8BE5\u524D\u7F00\u8FDB\u5165\u8DEF\u7531'),
3127
+ agentPreset: Schema.string().description('\u8DEF\u7531\u5230\u7684 agent \u9884\u8BBE id\uFF08\u5982 "code"\uFF09\uFF1B\u7F3A\u7701=\u9ED8\u8BA4\u9884\u8BBE'),
3128
+ botModel: Schema.object({
3129
+ provider: Schema.string().required().description("\u6A21\u578B\u4F9B\u5E94\u5546"),
3130
+ model: Schema.string().required().description("\u6A21\u578B id")
3131
+ }).default(void 0).description("\u53EF\u9009\uFF1A\u8BE5\u8DEF\u7531\u4E13\u7528\u6A21\u578B\uFF0C\u4F18\u5148\u4E8E botModel \u4E0E\u9ED8\u8BA4\u6A21\u578B"),
3132
+ skill: Schema.string().description('\u53EF\u9009\uFF1A\u4E3A\u8BE5\u8DEF\u7531\u4F1A\u8BDD\u6302\u8F7D\u7684 skill \u540D\uFF08\u5982 "pmx-api"\uFF09')
3133
+ })).default([]).description("\u6D88\u606F\u8DEF\u7531\u89C4\u5219\u5217\u8868\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF0C\u7B2C\u4E00\u6761\u547D\u4E2D\u751F\u6548\uFF09")
2974
3134
  });
2975
3135
 
2976
3136
  // src/index.ts