dsh-message-gateway 0.1.29 → 0.1.30

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
@@ -1895,6 +1895,130 @@ function sleep(ms) {
1895
1895
  return new Promise((resolve) => setTimeout(resolve, ms));
1896
1896
  }
1897
1897
 
1898
+ // src/host/feishu-bridge.ts
1899
+ import * as lark from "@larksuiteoapi/node-sdk";
1900
+ var FeishuBridge = class {
1901
+ constructor(cred, callbacks) {
1902
+ this.cred = cred;
1903
+ this.callbacks = callbacks;
1904
+ this.client = new lark.Client({
1905
+ appId: cred.appId,
1906
+ appSecret: cred.appSecret
1907
+ });
1908
+ }
1909
+ client = null;
1910
+ wsClient = null;
1911
+ started = false;
1912
+ status = { state: "idle", detail: "", connectedAt: null };
1913
+ setStatus(state, detail = "") {
1914
+ this.status = {
1915
+ state,
1916
+ detail,
1917
+ connectedAt: state === "connected" ? this.status.connectedAt ?? Date.now() : null
1918
+ };
1919
+ this.callbacks.onStatus(this.status);
1920
+ }
1921
+ /** 获取飞书官方 REST API Client 实例。 */
1922
+ getClient() {
1923
+ return this.client;
1924
+ }
1925
+ /** 建立长连接。 */
1926
+ start() {
1927
+ if (this.started) return;
1928
+ this.started = true;
1929
+ this.setStatus("connecting", "\u6B63\u5728\u8FDE\u63A5\u98DE\u4E66\u957F\u8FDE\u63A5\u2026");
1930
+ try {
1931
+ const eventDispatcher = new lark.EventDispatcher({}).register({
1932
+ "im.message.receive_v1": async (data) => {
1933
+ try {
1934
+ const msg = data.message;
1935
+ if (!msg || msg.message_type !== "text") return;
1936
+ const parsedContent = JSON.parse(msg.content || "{}");
1937
+ let text = parsedContent.text || "";
1938
+ if (msg.chat_type === "group" && Array.isArray(msg.mentions)) {
1939
+ for (const mention of msg.mentions) {
1940
+ if (mention.key) {
1941
+ text = text.replace(new RegExp(mention.key, "g"), "").trim();
1942
+ }
1943
+ }
1944
+ }
1945
+ if (text.trim() === "") return;
1946
+ this.callbacks.onText(text.trim(), {
1947
+ chatId: msg.chat_id,
1948
+ messageId: msg.message_id,
1949
+ senderId: data.sender?.sender_id?.user_id || data.sender?.sender_id?.open_id || "",
1950
+ chatType: msg.chat_type === "group" ? "group" : "single"
1951
+ });
1952
+ } catch (err) {
1953
+ console.error("[dsh-message-gateway] feishu message parsing error", err);
1954
+ }
1955
+ }
1956
+ });
1957
+ this.wsClient = new lark.WSClient({
1958
+ appId: this.cred.appId,
1959
+ appSecret: this.cred.appSecret,
1960
+ loggerLevel: lark.LoggerLevel.info
1961
+ });
1962
+ this.wsClient.start({ eventDispatcher });
1963
+ this.setStatus("connected", `App ID: ${this.cred.appId}`);
1964
+ console.log("[dsh-message-gateway] feishu wsClient connection initiated for", this.cred.appId);
1965
+ } catch (error) {
1966
+ console.error("[dsh-message-gateway] feishu start failed", error);
1967
+ this.setStatus("error", error instanceof Error ? error.message : String(error));
1968
+ }
1969
+ }
1970
+ /**
1971
+ * 回复某条消息(通过 message_id 引用回复)。
1972
+ */
1973
+ async replyMessage(messageId, content) {
1974
+ if (!this.client) return false;
1975
+ try {
1976
+ await this.client.im.message.reply({
1977
+ path: { message_id: messageId },
1978
+ data: {
1979
+ content: JSON.stringify({ text: content }),
1980
+ msg_type: "text"
1981
+ }
1982
+ });
1983
+ return true;
1984
+ } catch (err) {
1985
+ console.error("[dsh-message-gateway] feishu replyMessage error", err);
1986
+ return false;
1987
+ }
1988
+ }
1989
+ /**
1990
+ * 主动发送消息至指定会话(支持单聊 open_id/user_id 或群聊 chat_id)。
1991
+ */
1992
+ async sendMessage(receiveId, content, receiveIdType = "chat_id") {
1993
+ if (!this.client) return false;
1994
+ try {
1995
+ await this.client.im.message.create({
1996
+ params: { receive_id_type: receiveIdType },
1997
+ data: {
1998
+ receive_id: receiveId,
1999
+ msg_type: "text",
2000
+ content: JSON.stringify({ text: content })
2001
+ }
2002
+ });
2003
+ return true;
2004
+ } catch (err) {
2005
+ console.error("[dsh-message-gateway] feishu sendMessage error", err);
2006
+ return false;
2007
+ }
2008
+ }
2009
+ /** 优雅停止长连接。 */
2010
+ stop() {
2011
+ this.started = false;
2012
+ try {
2013
+ this.wsClient?.close({ force: true });
2014
+ } catch (e) {
2015
+ console.warn("[dsh-message-gateway] feishu wsClient close warning", e);
2016
+ }
2017
+ this.wsClient = null;
2018
+ this.setStatus("idle");
2019
+ }
2020
+ };
2021
+
1898
2022
  // src/host/bridge-manager.ts
1899
2023
  var DEFAULT_MAX_CHAT_AGENTS = 40;
1900
2024
  var STREAM_PUSH_INTERVAL = 600;
@@ -2143,6 +2267,8 @@ var BridgeManager = class {
2143
2267
  this.qq = null;
2144
2268
  this.email?.stop();
2145
2269
  this.email = null;
2270
+ this.feishu?.stop();
2271
+ this.feishu = null;
2146
2272
  this.finishAllPending();
2147
2273
  const entries = [...this.agents.values()];
2148
2274
  this.agents.clear();
@@ -2408,30 +2534,32 @@ ${secret}`;
2408
2534
  return r.errcode === 0 ? { ok: true, detail: "sent" } : { ok: false, detail: r.errmsg ?? "dingtalk send failed" };
2409
2535
  }
2410
2536
  case "feishu": {
2411
- const rawUrl = target.startsWith("http") ? target : `https://open.feishu.cn/open-apis/bot/v2/hook/${encodeURIComponent(target)}`;
2412
- const payload = {
2413
- msg_type: "text",
2414
- content: { text }
2415
- };
2537
+ if (this.feishu) {
2538
+ const sent = await this.feishu.sendMessage(target, text, target.startsWith("oc_") ? "chat_id" : target.startsWith("ou_") ? "open_id" : "chat_id");
2539
+ return sent ? { ok: true, detail: "sent" } : { ok: false, detail: "feishu sendMessage failed" };
2540
+ }
2416
2541
  const { loadStore: loadStore2 } = await Promise.resolve().then(() => (init_gateway_store(), gateway_store_exports));
2417
2542
  const store = await loadStore2();
2418
- const secret = store.platforms.feishu?.secret;
2419
- if (secret) {
2420
- const { createHmac: createHmac2 } = await import("node:crypto");
2421
- const timestamp = Math.floor(Date.now() / 1e3);
2422
- const stringToSign = `${timestamp}
2423
- ${secret}`;
2424
- const sign2 = createHmac2("sha256", stringToSign).digest("base64");
2425
- payload.timestamp = String(timestamp);
2426
- payload.sign = sign2;
2543
+ const appId = store.platforms.feishu?.appId;
2544
+ const appSecret = store.platforms.feishu?.appSecret;
2545
+ if (appId && appSecret) {
2546
+ try {
2547
+ const lark2 = await import("@larksuiteoapi/node-sdk");
2548
+ const client = new lark2.Client({ appId, appSecret });
2549
+ await client.im.message.create({
2550
+ params: { receive_id_type: target.startsWith("oc_") ? "chat_id" : target.startsWith("ou_") ? "open_id" : "chat_id" },
2551
+ data: {
2552
+ receive_id: target,
2553
+ msg_type: "text",
2554
+ content: JSON.stringify({ text })
2555
+ }
2556
+ });
2557
+ return { ok: true, detail: "sent" };
2558
+ } catch (err) {
2559
+ return { ok: false, detail: `feishu client send failed: ${err instanceof Error ? err.message : String(err)}` };
2560
+ }
2427
2561
  }
2428
- const resp = await fetch(rawUrl, {
2429
- method: "POST",
2430
- headers: { "content-type": "application/json" },
2431
- body: JSON.stringify(payload)
2432
- });
2433
- const r = await resp.json().catch(() => ({}));
2434
- return r.code === 0 || r.StatusCode === 0 ? { ok: true, detail: "sent" } : { ok: false, detail: r.msg ?? "feishu send failed" };
2562
+ return { ok: false, detail: "feishu not configured or bridge not started" };
2435
2563
  }
2436
2564
  case "bark": {
2437
2565
  const { loadStore: loadStore2 } = await Promise.resolve().then(() => (init_gateway_store(), gateway_store_exports));
@@ -2606,6 +2734,40 @@ ${secret}`;
2606
2734
  discord = null;
2607
2735
  qq = null;
2608
2736
  email = null;
2737
+ feishu = null;
2738
+ /** 启动 Feishu 桥(企业自建应用 WebSocket 长连接)。 */
2739
+ startFeishu(cred) {
2740
+ this.feishu?.stop();
2741
+ const bridge = new FeishuBridge(
2742
+ { appId: cred.appId ?? "", appSecret: cred.appSecret ?? "" },
2743
+ {
2744
+ onStatus: (status) => this.onStatusCallback?.(status),
2745
+ onText: (text, frame) => {
2746
+ const identity = {
2747
+ key: `feishu:${frame.chatId}`,
2748
+ frame,
2749
+ sink: {
2750
+ stream: (_f, _streamId, content, finish) => {
2751
+ if (finish && content.trim()) {
2752
+ void bridge.replyMessage(frame.messageId, content);
2753
+ }
2754
+ },
2755
+ ack: false
2756
+ },
2757
+ chatType: frame.chatType
2758
+ };
2759
+ void this.handleExternalMessage(identity, text);
2760
+ }
2761
+ }
2762
+ );
2763
+ this.feishu = bridge;
2764
+ bridge.start();
2765
+ }
2766
+ /** 停止 Feishu 桥。 */
2767
+ stopFeishu() {
2768
+ this.feishu?.stop();
2769
+ this.feishu = null;
2770
+ }
2609
2771
  /** 启动 Telegram 桥(长轮询)。 */
2610
2772
  startTelegram(cred) {
2611
2773
  this.telegram?.stop();
@@ -2676,12 +2838,13 @@ ${secret}`;
2676
2838
  this.email?.stop();
2677
2839
  this.email = null;
2678
2840
  }
2679
- /** 任意桥接平台的状态(telegram/discord/qq/email)。 */
2841
+ /** 任意桥接平台的状态(telegram/discord/qq/email/feishu)。 */
2680
2842
  bridgeStatus(id) {
2681
2843
  if (id === "telegram") return this.telegram?.status ?? { state: "idle", detail: "", connectedAt: null };
2682
2844
  if (id === "discord") return this.discord?.status ?? { state: "idle", detail: "", connectedAt: null };
2683
2845
  if (id === "qq") return this.qq?.status ?? { state: "idle", detail: "", connectedAt: null };
2684
2846
  if (id === "email") return this.email?.status ?? { state: "idle", detail: "", connectedAt: null };
2847
+ if (id === "feishu") return this.feishu?.status ?? { state: "idle", detail: "", connectedAt: null };
2685
2848
  return { state: "idle", detail: "", connectedAt: null };
2686
2849
  }
2687
2850
  /** 将桥状态并入存储状态。 */
@@ -2755,7 +2918,8 @@ ${secret}`;
2755
2918
  bridgeLine("Telegram", this.bridgeStatus("telegram")),
2756
2919
  bridgeLine("Discord", this.bridgeStatus("discord")),
2757
2920
  bridgeLine("QQ", this.bridgeStatus("qq")),
2758
- bridgeLine("Email", this.bridgeStatus("email"))
2921
+ bridgeLine("Email", this.bridgeStatus("email")),
2922
+ bridgeLine("Feishu", this.bridgeStatus("feishu"))
2759
2923
  ];
2760
2924
  reply(lines.join("\n"));
2761
2925
  return true;
@@ -2924,8 +3088,8 @@ var PLATFORMS = [
2924
3088
  testable: true,
2925
3089
  hintKey: "platform.feishu.hint",
2926
3090
  fields: [
2927
- { key: "webhookUrl", labelKey: "field.webhookUrl", placeholderKey: "field.feishuWebhook.ph", kind: "text" },
2928
- { key: "secret", labelKey: "field.feishuSecret", placeholderKey: "field.secret.ph", kind: "secret" }
3091
+ { key: "appId", labelKey: "field.feishuAppId", placeholderKey: "field.feishuAppId.ph", kind: "text" },
3092
+ { key: "appSecret", labelKey: "field.feishuAppSecret", placeholderKey: "field.feishuAppSecret.ph", kind: "secret" }
2929
3093
  ]
2930
3094
  },
2931
3095
  {
@@ -3099,11 +3263,25 @@ ${cred.secret}`;
3099
3263
  return { ok: false, detail: r.errmsg ?? `HTTP ${status}` };
3100
3264
  }
3101
3265
  case "feishu": {
3266
+ const appId = cred.appId ?? "";
3267
+ const appSecret = cred.appSecret ?? "";
3268
+ if (appId && appSecret) {
3269
+ const { status: status2, body: body2 } = await httpJson("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", {
3270
+ method: "POST",
3271
+ headers: { "content-type": "application/json" },
3272
+ body: JSON.stringify({ app_id: appId, app_secret: appSecret })
3273
+ });
3274
+ const r2 = body2;
3275
+ if (r2.code === 0 && r2.tenant_access_token) {
3276
+ return { ok: true, detail: "\u98DE\u4E66\u5E94\u7528\u9274\u6743\u6210\u529F\uFF08\u957F\u8FDE\u63A5\u5DF2\u5C31\u7EEA\uFF09" };
3277
+ }
3278
+ return { ok: false, detail: r2.msg ?? `HTTP ${status2}` };
3279
+ }
3102
3280
  const rawUrl = cred.webhookUrl ?? "";
3103
- if (!rawUrl.startsWith("http")) return { ok: false, detail: "\u65E0\u6548\u7684 Webhook URL" };
3281
+ if (!rawUrl.startsWith("http")) return { ok: false, detail: "\u8BF7\u586B\u5199 App ID \u4E0E App Secret" };
3104
3282
  const payload = {
3105
3283
  msg_type: "text",
3106
- content: { text: "\u{1F50C} [DSH Message Gateway] \u98DE\u4E66\u81EA\u5B9A\u4E49\u673A\u5668\u4EBA\u8FDE\u63A5\u6D4B\u8BD5\u6210\u529F\uFF01" }
3284
+ content: { text: "\u{1F50C} [DSH Message Gateway] \u98DE\u4E66\u8FDE\u63A5\u6D4B\u8BD5\u6210\u529F\uFF01" }
3107
3285
  };
3108
3286
  if (cred.secret) {
3109
3287
  const { createHmac: createHmac2 } = await import("node:crypto");
@@ -3474,7 +3652,7 @@ async function buildView(manager) {
3474
3652
  let state = stored?.state ?? (def.id === "wechat" || def.id === "webhooks" ? "manual" : "none");
3475
3653
  let detail = stored?.detail ?? "";
3476
3654
  let testedAt = stored?.testedAt ?? null;
3477
- if (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email") {
3655
+ if (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email" || def.id === "feishu") {
3478
3656
  const merged = manager.mergeStatus(stored, def.id);
3479
3657
  state = merged.state;
3480
3658
  detail = merged.detail;
@@ -3823,6 +4001,7 @@ function registerGatewayRoutes(ctx, manager) {
3823
4001
  if (platform === "discord") manager.stopDiscord();
3824
4002
  if (platform === "qq") manager.stopQQ();
3825
4003
  if (platform === "email") manager.stopEmail();
4004
+ if (platform === "feishu") manager.stopFeishu();
3826
4005
  json(res, { ok: true, value: await buildView(manager) });
3827
4006
  return;
3828
4007
  }
@@ -3865,6 +4044,13 @@ function registerGatewayRoutes(ctx, manager) {
3865
4044
  manager.stopEmail();
3866
4045
  }
3867
4046
  }
4047
+ if (platform === "feishu") {
4048
+ if (credentials2.appId !== void 0 && credentials2.appId !== "" && credentials2.appSecret !== void 0 && credentials2.appSecret !== "") {
4049
+ manager.startFeishu(credentials2);
4050
+ } else {
4051
+ manager.stopFeishu();
4052
+ }
4053
+ }
3868
4054
  json(res, { ok: true, value: await buildView(manager) });
3869
4055
  return;
3870
4056
  }
@@ -3904,6 +4090,7 @@ var Config = Schema.object({
3904
4090
  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"),
3905
4091
  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"),
3906
4092
  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"),
4093
+ autoStartFeishu: Schema.boolean().default(true).description("\u542F\u52A8\u65F6\u81EA\u52A8\u7528\u5DF2\u4FDD\u5B58\u7684\u98DE\u4E66\u5E94\u7528\u51ED\u636E\u5EFA\u7ACB\u5E38\u9A7B\u8FDE\u63A5\uFF08WebSocket \u957F\u8FDE\u63A5\uFF09"),
3907
4094
  groupReply: Schema.boolean().default(true).description("\u662F\u5426\u56DE\u590D\u7FA4\u804A\u6D88\u606F\uFF08false \u65F6\u53EA\u5904\u7406\u5355\u804A\uFF09"),
3908
4095
  welcomeReply: Schema.boolean().default(false).description("\u662F\u5426\u5728\u7528\u6237\u5F53\u5929\u9996\u6B21\u8FDB\u5165\u5355\u804A\u65F6\u81EA\u52A8\u53D1\u9001\u6B22\u8FCE\u8BED\uFF08\u9ED8\u8BA4 false \u4FDD\u6301\u514D\u6253\u6270\uFF0C\u8BBE\u4E3A true \u5F00\u542F\uFF09"),
3909
4096
  outboundWebhooks: Schema.array(Schema.object({
@@ -3955,18 +4142,23 @@ function apply(ctx, config = Config({})) {
3955
4142
  manager.startEmail(email);
3956
4143
  console.log("[dsh-message-gateway] email bridge auto-started");
3957
4144
  }
4145
+ const feishu = store.platforms.feishu;
4146
+ if (config.autoStartFeishu && feishu !== void 0 && feishu.appId !== "" && feishu.appSecret !== "") {
4147
+ manager.startFeishu(feishu);
4148
+ console.log("[dsh-message-gateway] feishu bridge auto-started");
4149
+ }
3958
4150
  });
3959
4151
  const disposeRoutes = registerGatewayRoutes(ctx, manager);
3960
4152
  let disposeTools;
3961
4153
  if (ctx.tools) {
3962
4154
  const disposeSend = ctx.tools.register(defineTool({
3963
4155
  name: "send_chat_message",
3964
- description: "\u5411\u5DF2\u8FDE\u63A5\u7684\u6D88\u606F\u5E73\u53F0\uFF08Telegram / Discord / \u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA / Email \u7B49\uFF09\u4E3B\u52A8\u63A8\u9001\u6587\u672C\u6D88\u606F\u3002\u4F8B\u5982\u628A\u4EE3\u7801\u603B\u7ED3\u3001\u4EFB\u52A1\u7ED3\u679C\u63A8\u9001\u81F3\u6307\u5B9A\u7684\u7FA4\u804A\u6216\u79C1\u4FE1\u9891\u9053\u3002",
4156
+ description: "\u5411\u5DF2\u8FDE\u63A5\u7684\u6D88\u606F\u5E73\u53F0\uFF08Telegram / Discord / \u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA / \u98DE\u4E66 / Email \u7B49\uFF09\u4E3B\u52A8\u63A8\u9001\u6587\u672C\u6D88\u606F\u3002\u4F8B\u5982\u628A\u4EE3\u7801\u603B\u7ED3\u3001\u4EFB\u52A1\u7ED3\u679C\u63A8\u9001\u81F3\u6307\u5B9A\u7684\u7FA4\u804A\u6216\u79C1\u4FE1\u9891\u9053\u3002",
3965
4157
  parameters: {
3966
4158
  platform: {
3967
4159
  type: "string",
3968
4160
  required: true,
3969
- description: "\u76EE\u6807\u5E73\u53F0 id\uFF1Atelegram / discord / wecom-aibot / email"
4161
+ description: "\u76EE\u6807\u5E73\u53F0 id\uFF1Atelegram / discord / wecom-aibot / feishu / email"
3970
4162
  },
3971
4163
  target: {
3972
4164
  type: "string",