@xopcai/xopc 0.0.464 → 0.0.465
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/dist/browser-ext/manifest.json +1 -1
- package/dist/extensions/feishu/src/adapters/cli-login.js +23 -49
- package/dist/extensions/feishu/src/adapters/gateway-setup.d.ts +3 -0
- package/dist/extensions/feishu/src/adapters/gateway-setup.js +180 -128
- package/dist/extensions/feishu/src/adapters/onboard-cli.d.ts +1 -1
- package/dist/extensions/feishu/src/adapters/onboard-cli.js +27 -15
- package/dist/extensions/feishu/src/auth/app-registration.d.ts +1 -0
- package/dist/extensions/feishu/src/auth/app-registration.js +12 -9
- package/dist/extensions/feishu/src/outbound/outbound-adapter.js +40 -16
- package/dist/extensions/feishu/src/plugin.d.ts +2 -0
- package/dist/extensions/feishu/src/plugin.js +37 -23
- package/dist/extensions/feishu/src/status/status-adapter.d.ts +1 -1
- package/dist/extensions/feishu/src/status/status-adapter.js +8 -5
- package/dist/extensions/feishu/src/streaming/streaming-adapter.js +97 -69
- package/dist/extensions/feishu/src/transport/client/bot-info.d.ts +10 -0
- package/dist/extensions/feishu/src/transport/client/bot-info.js +34 -0
- package/dist/extensions/feishu/src/transport/client/client.d.ts +7 -1
- package/dist/extensions/feishu/src/transport/client/client.js +6 -5
- package/dist/extensions/feishu/src/transport/client/install-sdk.d.ts +2 -0
- package/dist/extensions/feishu/src/transport/client/install-sdk.js +77 -0
- package/dist/extensions/feishu/src/transport/client/lark-sdk.d.ts +2 -0
- package/dist/extensions/feishu/src/transport/client/lark-sdk.js +27 -3
- package/dist/extensions/feishu/src/transport/client/sdk-catalog.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/client/sdk-catalog.js +317 -0
- package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.d.ts +1 -1
- package/dist/extensions/feishu/src/transport/reliability/inbound-pipeline.js +13 -5
- package/dist/extensions/feishu/src/transport/reliability/message-ingress.d.ts +21 -0
- package/dist/extensions/feishu/src/transport/reliability/message-ingress.js +313 -0
- package/dist/extensions/feishu/src/transport/socket-mode/monitor.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/socket-mode/monitor.js +56 -171
- package/dist/extensions/feishu/src/transport/webhook/monitor.d.ts +1 -0
- package/dist/extensions/feishu/src/transport/webhook/monitor.js +10 -102
- package/dist/extensions/telegram/src/account-manager.d.ts +1 -0
- package/dist/extensions/telegram/src/account-manager.js +3 -0
- package/dist/extensions/telegram/src/adapters/debounce-keys.js +7 -2
- package/dist/extensions/telegram/src/adapters/gateway-setup.js +113 -63
- package/dist/extensions/telegram/src/adapters/streaming-adapter.js +8 -4
- package/dist/extensions/telegram/src/doctor.js +1 -1
- package/dist/extensions/telegram/src/inbound-coalescer.d.ts +8 -6
- package/dist/extensions/telegram/src/inbound-coalescer.js +47 -88
- package/dist/extensions/telegram/src/inbound-processor.js +5 -1
- package/dist/extensions/telegram/src/outbound-sender.js +16 -23
- package/dist/extensions/telegram/src/plugin.js +80 -57
- package/dist/extensions/telegram/src/polling-session.d.ts +3 -6
- package/dist/extensions/telegram/src/polling-session.js +107 -94
- package/dist/extensions/telegram/src/rich-message.d.ts +4 -0
- package/dist/extensions/telegram/src/rich-message.js +23 -0
- package/dist/extensions/telegram/src/timeout-abort.d.ts +1 -1
- package/dist/extensions/telegram/src/timeout-abort.js +9 -3
- package/dist/extensions/telegram/src/update-offset-store.d.ts +1 -0
- package/dist/extensions/telegram/src/update-offset-store.js +6 -1
- package/dist/extensions/telegram/xopc.extension.json +1 -1
- package/dist/extensions/weixin/src/api/api.d.ts +1 -0
- package/dist/extensions/weixin/src/api/api.js +12 -6
- package/dist/extensions/weixin/src/api/types.d.ts +5 -2
- package/dist/extensions/weixin/src/auth/login-qr.d.ts +7 -1
- package/dist/extensions/weixin/src/auth/login-qr.js +48 -13
- package/dist/extensions/weixin/src/cdn/pic-decrypt.d.ts +2 -2
- package/dist/extensions/weixin/src/cdn/pic-decrypt.js +37 -25
- package/dist/extensions/weixin/src/cli/gateway-qr-login.d.ts +8 -0
- package/dist/extensions/weixin/src/cli/gateway-qr-login.js +45 -6
- package/dist/extensions/weixin/src/cli/qr-login.d.ts +1 -1
- package/dist/extensions/weixin/src/cli/qr-login.js +9 -3
- package/dist/extensions/weixin/src/media/media-download.d.ts +1 -0
- package/dist/extensions/weixin/src/media/media-download.js +4 -5
- package/dist/extensions/weixin/src/messaging/process-message.d.ts +2 -0
- package/dist/extensions/weixin/src/messaging/process-message.js +90 -65
- package/dist/extensions/weixin/src/messaging/quote-cache.d.ts +10 -0
- package/dist/extensions/weixin/src/messaging/quote-cache.js +46 -0
- package/dist/extensions/weixin/src/monitor/monitor.d.ts +3 -3
- package/dist/extensions/weixin/src/monitor/monitor.js +108 -104
- package/dist/extensions/weixin/src/plugin.d.ts +5 -1
- package/dist/extensions/weixin/src/plugin.js +138 -42
- package/dist/gateway/static/root/assets/{capabilities-page-rTjkjo71.js → capabilities-page-U_hQx5ou.js} +2 -2
- package/dist/gateway/static/root/assets/channels-BUzno8Pi.js +1 -0
- package/dist/gateway/static/root/assets/extension-settings-page-BvUtZGLT.js +1 -0
- package/dist/gateway/static/root/assets/index-Cdo4_zon.js +11 -0
- package/dist/gateway/static/root/assets/index-DYTktubl.css +1 -0
- package/dist/gateway/static/root/assets/{route-preload-5iwjWERk.js → route-preload-ClsAFFQc.js} +2 -2
- package/dist/gateway/static/root/assets/schema-form-BxBDgLrg.js +1 -0
- package/dist/gateway/static/root/assets/{settings-page-DNiRlM5x.js → settings-page-M6XwzIyu.js} +1 -1
- package/dist/gateway/static/root/assets/understanding-refresh-store-CM6bUcaJ.js +1 -0
- package/dist/gateway/static/root/assets/user-model-page-CBcGMhrR.js +2 -0
- package/dist/gateway/static/root/index.html +4 -4
- package/dist/package.js +1 -1
- package/dist/src/agent/inbound/inbound-loop.js +14 -0
- package/dist/src/agent/messaging/outbound-coordinator.js +1 -1
- package/dist/src/channels/connection-probe.d.ts +23 -0
- package/dist/src/channels/connection-probe.js +98 -0
- package/dist/src/channels/manager.d.ts +2 -0
- package/dist/src/channels/manager.js +5 -0
- package/dist/src/channels/message-journal.d.ts +25 -0
- package/dist/src/channels/message-journal.js +79 -0
- package/dist/src/channels/outbound-sender.d.ts +8 -0
- package/dist/src/channels/outbound-sender.js +60 -1
- package/dist/src/channels/plugins/types.adapters.d.ts +4 -0
- package/dist/src/channels/verified-inbound.js +20 -14
- package/dist/src/gateway/hono/routes/channels.js +23 -10
- package/dist/src/gateway/hono/routes/home.js +1 -1
- package/dist/src/gateway/hono/routes/user-model.js +48 -20
- package/dist/src/gateway/service.js +5 -5
- package/dist/src/home-intelligence/host.js +5 -5
- package/dist/src/infra/bus/index.d.ts +1 -1
- package/dist/src/infra/bus/queue.d.ts +16 -3
- package/dist/src/infra/bus/queue.js +74 -3
- package/dist/src/infra/debounce.d.ts +1 -0
- package/dist/src/infra/debounce.js +40 -35
- package/dist/src/knowledge-memory/index.js +2 -2
- package/dist/src/knowledge-memory/repository.d.ts +9 -0
- package/dist/src/knowledge-memory/repository.js +12 -2
- package/dist/src/runtime-tools/types.d.ts +1 -1
- package/package.json +5 -6
- package/dist/gateway/static/root/assets/channels-DvB2fwPI.js +0 -1
- package/dist/gateway/static/root/assets/extension-settings-page-DKAJE4h9.js +0 -1
- package/dist/gateway/static/root/assets/index-BGA-G-Bp.css +0 -1
- package/dist/gateway/static/root/assets/index-pmlYYCCU.js +0 -11
- package/dist/gateway/static/root/assets/schema-form-C9TYGa0_.js +0 -1
- package/dist/gateway/static/root/assets/understanding-refresh-store-Cf0DUO_C.js +0 -1
- package/dist/gateway/static/root/assets/user-model-page-CdB9qH57.js +0 -2
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { createLogger } from "../../../../../src/utils/logger/index.js";
|
|
2
|
+
import { init_logger } from "../../../../../src/utils/logger.js";
|
|
3
|
+
import { generateConversationId } from "../../../../../src/chat-commands/session-key.js";
|
|
4
|
+
import { ChannelMessageJournal } from "../../../../../src/channels/message-journal.js";
|
|
5
|
+
import { handleChannelConnectionProbe } from "../../../../../src/channels/connection-probe.js";
|
|
6
|
+
import { getMimeType } from "../../../../../src/channels/media.js";
|
|
7
|
+
import { recordFeishuMessageBinding } from "../../state/message-bindings.js";
|
|
8
|
+
import { createFeishuClient } from "../client/client.js";
|
|
9
|
+
import { probeFeishuBot } from "../client/bot-info.js";
|
|
10
|
+
import { sendFeishuPairingPromptIfNeeded } from "../../pairing/feishu-pairing-prompt.js";
|
|
11
|
+
import { stripFeishuMentions } from "../text/mentions.js";
|
|
12
|
+
//#region extensions/feishu/src/transport/reliability/message-ingress.ts
|
|
13
|
+
init_logger();
|
|
14
|
+
const log = createLogger("FeishuIngress");
|
|
15
|
+
const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
|
|
16
|
+
function feishuInboundScope(account) {
|
|
17
|
+
return JSON.stringify([
|
|
18
|
+
account.accountId,
|
|
19
|
+
account.domain,
|
|
20
|
+
account.appId
|
|
21
|
+
]);
|
|
22
|
+
}
|
|
23
|
+
function parseEvent(event) {
|
|
24
|
+
const payload = event?.event ?? event?.data ?? event;
|
|
25
|
+
const message = payload?.message;
|
|
26
|
+
const sender = payload?.sender;
|
|
27
|
+
const chatId = message?.chat_id ?? message?.chatId;
|
|
28
|
+
const messageId = message?.message_id ?? message?.messageId;
|
|
29
|
+
const senderId = sender?.sender_id?.open_id ?? sender?.sender_id?.user_id ?? sender?.open_id ?? sender?.user_id;
|
|
30
|
+
if (![
|
|
31
|
+
chatId,
|
|
32
|
+
messageId,
|
|
33
|
+
senderId
|
|
34
|
+
].every((value) => typeof value === "string" && value.length > 0)) return;
|
|
35
|
+
if (sender?.sender_type === "app" || sender?.sender_type === "bot") return;
|
|
36
|
+
const threadId = message?.thread_id ?? message?.threadId;
|
|
37
|
+
const chatType = message?.chat_type ?? message?.chatType;
|
|
38
|
+
return {
|
|
39
|
+
chatId,
|
|
40
|
+
messageId,
|
|
41
|
+
senderId,
|
|
42
|
+
senderName: sender?.name,
|
|
43
|
+
isGroup: chatType === "group" || chatType === "chat",
|
|
44
|
+
threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0,
|
|
45
|
+
message
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function readContent(raw) {
|
|
49
|
+
if (typeof raw !== "string" || !raw.trim()) return {};
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(raw);
|
|
52
|
+
if (parsed && typeof parsed === "object") return parsed;
|
|
53
|
+
} catch {
|
|
54
|
+
return { text: raw };
|
|
55
|
+
}
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
function readPost(content) {
|
|
59
|
+
const localized = Object.values(content).find((value) => value && typeof value === "object" && "content" in value);
|
|
60
|
+
const post = Array.isArray(content.content) ? content : localized ?? {};
|
|
61
|
+
const text = [];
|
|
62
|
+
const imageKeys = [];
|
|
63
|
+
if (typeof post.title === "string") text.push(post.title);
|
|
64
|
+
if (Array.isArray(post.content)) for (const row of post.content) {
|
|
65
|
+
if (!Array.isArray(row)) continue;
|
|
66
|
+
text.push(row.map((element) => {
|
|
67
|
+
if (element?.tag === "img" && typeof element.image_key === "string") imageKeys.push(element.image_key);
|
|
68
|
+
if (element?.tag === "at") return "";
|
|
69
|
+
return typeof element?.text === "string" ? element.text : "";
|
|
70
|
+
}).join(""));
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
text: text.join("\n"),
|
|
74
|
+
imageKeys
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function createFeishuMessageIngress(options) {
|
|
78
|
+
const { account, abortSignal, enqueueInbound, inboundDebounceDefaultMs, security } = options;
|
|
79
|
+
const scope = feishuInboundScope(account);
|
|
80
|
+
const journal = new ChannelMessageJournal("feishu", scope);
|
|
81
|
+
let pump;
|
|
82
|
+
let api;
|
|
83
|
+
let botOpenId;
|
|
84
|
+
async function download(messageId, key, kind, name, type) {
|
|
85
|
+
api ??= createFeishuClient(account).api;
|
|
86
|
+
const stream = (await api.im.messageResource.get({
|
|
87
|
+
path: {
|
|
88
|
+
message_id: messageId,
|
|
89
|
+
file_key: key
|
|
90
|
+
},
|
|
91
|
+
params: { type: kind }
|
|
92
|
+
}, {
|
|
93
|
+
timeout: 15e3,
|
|
94
|
+
signal: abortSignal
|
|
95
|
+
})).getReadableStream();
|
|
96
|
+
const chunks = [];
|
|
97
|
+
let size = 0;
|
|
98
|
+
for await (const value of stream) {
|
|
99
|
+
abortSignal.throwIfAborted();
|
|
100
|
+
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
101
|
+
size += chunk.length;
|
|
102
|
+
if (size > MAX_ATTACHMENT_BYTES) throw new Error("Feishu attachment size limit exceeded");
|
|
103
|
+
chunks.push(chunk);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
type,
|
|
107
|
+
mimeType: kind === "image" ? getMimeType("image", name) : getMimeType(type, name),
|
|
108
|
+
name,
|
|
109
|
+
size,
|
|
110
|
+
data: Buffer.concat(chunks).toString("base64")
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async function dispatch(event) {
|
|
114
|
+
const parsed = parseEvent(event);
|
|
115
|
+
if (!parsed) return;
|
|
116
|
+
const { chatId, messageId, senderId, senderName, isGroup, threadId, message } = parsed;
|
|
117
|
+
const content = readContent(message.content ?? message.body?.content);
|
|
118
|
+
if (!isGroup && typeof content.text === "string" && await handleChannelConnectionProbe({
|
|
119
|
+
channel: "feishu",
|
|
120
|
+
accountId: account.accountId,
|
|
121
|
+
identity: account.appId,
|
|
122
|
+
senderId,
|
|
123
|
+
text: content.text,
|
|
124
|
+
reply: async (text) => {
|
|
125
|
+
api ??= createFeishuClient(account).api;
|
|
126
|
+
const result = await api.im.message.reply({
|
|
127
|
+
path: { message_id: messageId },
|
|
128
|
+
data: {
|
|
129
|
+
msg_type: "text",
|
|
130
|
+
content: JSON.stringify({ text })
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
if (result?.code !== 0 || !result?.data?.message_id) throw new Error("Feishu did not confirm the verification reply");
|
|
134
|
+
}
|
|
135
|
+
})) return;
|
|
136
|
+
const access = security.checkAccess({
|
|
137
|
+
accountId: account.accountId,
|
|
138
|
+
chatId,
|
|
139
|
+
senderId,
|
|
140
|
+
senderName,
|
|
141
|
+
isGroup,
|
|
142
|
+
threadId
|
|
143
|
+
});
|
|
144
|
+
if (access && !access.allowed) {
|
|
145
|
+
if (!isGroup && access.reason === "pairing-required") await sendFeishuPairingPromptIfNeeded({
|
|
146
|
+
account,
|
|
147
|
+
messageId,
|
|
148
|
+
threadId,
|
|
149
|
+
senderId,
|
|
150
|
+
senderName,
|
|
151
|
+
isGroup
|
|
152
|
+
});
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
if (isGroup && account.requireMention) {
|
|
156
|
+
if (!Array.isArray(message.mentions) || !message.mentions.length) return;
|
|
157
|
+
if (!botOpenId) {
|
|
158
|
+
const identity = await probeFeishuBot(account, AbortSignal.any([abortSignal, AbortSignal.timeout(5e3)])).catch(() => ({ ok: false }));
|
|
159
|
+
if (identity.ok) botOpenId = identity.openId;
|
|
160
|
+
}
|
|
161
|
+
if (!botOpenId || !message.mentions.some((mention) => mention.id?.open_id === botOpenId)) return;
|
|
162
|
+
}
|
|
163
|
+
const kind = message.message_type ?? message.msg_type ?? "text";
|
|
164
|
+
const post = kind === "post" ? readPost(content) : void 0;
|
|
165
|
+
const text = stripFeishuMentions(String(post?.text || content.text || content.title || "")).trim();
|
|
166
|
+
const attachments = [];
|
|
167
|
+
const imageKeys = post?.imageKeys ?? [];
|
|
168
|
+
if (typeof content.image_key === "string" && kind === "image") imageKeys.push(content.image_key);
|
|
169
|
+
const media = imageKeys.map((key) => ({
|
|
170
|
+
key,
|
|
171
|
+
kind: "image",
|
|
172
|
+
name: "image.png",
|
|
173
|
+
type: "image"
|
|
174
|
+
}));
|
|
175
|
+
const fileKey = content.file_key;
|
|
176
|
+
const files = typeof fileKey === "string" && [
|
|
177
|
+
"file",
|
|
178
|
+
"audio",
|
|
179
|
+
"media"
|
|
180
|
+
].includes(kind) ? [{
|
|
181
|
+
key: fileKey,
|
|
182
|
+
kind: "file",
|
|
183
|
+
name: typeof content.file_name === "string" ? content.file_name : kind === "audio" ? "voice.opus" : kind === "media" ? "video.mp4" : "attachment",
|
|
184
|
+
type: kind === "audio" ? "audio" : "file"
|
|
185
|
+
}] : [];
|
|
186
|
+
for (const resource of [...media, ...files].slice(0, 8)) try {
|
|
187
|
+
attachments.push(await download(messageId, resource.key, resource.kind, resource.name, resource.type));
|
|
188
|
+
} catch (err) {
|
|
189
|
+
if (abortSignal.aborted) throw err;
|
|
190
|
+
log.warn({
|
|
191
|
+
accountId: account.accountId,
|
|
192
|
+
messageId
|
|
193
|
+
}, "Feishu message attachment unavailable");
|
|
194
|
+
}
|
|
195
|
+
if (!text && !attachments.length) return;
|
|
196
|
+
const conversationId = generateConversationId({
|
|
197
|
+
source: "feishu",
|
|
198
|
+
chatId,
|
|
199
|
+
senderId,
|
|
200
|
+
isGroup,
|
|
201
|
+
threadId,
|
|
202
|
+
accountId: account.accountId
|
|
203
|
+
});
|
|
204
|
+
recordFeishuMessageBinding({
|
|
205
|
+
messageId,
|
|
206
|
+
conversationId,
|
|
207
|
+
accountId: account.accountId,
|
|
208
|
+
chatId,
|
|
209
|
+
senderId,
|
|
210
|
+
isGroup,
|
|
211
|
+
threadId
|
|
212
|
+
});
|
|
213
|
+
await enqueueInbound({
|
|
214
|
+
kind: "text",
|
|
215
|
+
accountId: account.accountId,
|
|
216
|
+
chatId,
|
|
217
|
+
debounceMs: attachments.length ? 0 : account.inboundDebounceMs ?? inboundDebounceDefaultMs,
|
|
218
|
+
delivery: {
|
|
219
|
+
scope,
|
|
220
|
+
id: messageId
|
|
221
|
+
},
|
|
222
|
+
inbound: {
|
|
223
|
+
channel: "feishu",
|
|
224
|
+
sender_id: senderId,
|
|
225
|
+
chat_id: chatId,
|
|
226
|
+
content: text,
|
|
227
|
+
...attachments.length ? { attachments } : {},
|
|
228
|
+
metadata: {
|
|
229
|
+
conversationId,
|
|
230
|
+
accountId: account.accountId,
|
|
231
|
+
messageId,
|
|
232
|
+
threadId,
|
|
233
|
+
isGroup,
|
|
234
|
+
feishuEventType: "im.message.receive_v1"
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
function schedule() {
|
|
240
|
+
if (pump || abortSignal.aborted) return;
|
|
241
|
+
pump = Promise.resolve().then(async () => {
|
|
242
|
+
while (!abortSignal.aborted) {
|
|
243
|
+
const pending = journal.pending();
|
|
244
|
+
if (!pending.length) return;
|
|
245
|
+
const groups = /* @__PURE__ */ new Map();
|
|
246
|
+
for (const entry of pending) {
|
|
247
|
+
const parsed = parseEvent(entry.payload);
|
|
248
|
+
const key = JSON.stringify([
|
|
249
|
+
parsed?.chatId,
|
|
250
|
+
parsed?.threadId,
|
|
251
|
+
parsed?.senderId
|
|
252
|
+
]);
|
|
253
|
+
const group = groups.get(key) ?? [];
|
|
254
|
+
group.push(entry);
|
|
255
|
+
groups.set(key, group);
|
|
256
|
+
}
|
|
257
|
+
const batches = [...groups.values()];
|
|
258
|
+
for (let index = 0; index < batches.length; index += 4) await Promise.all(batches.slice(index, index + 4).map(async (entries) => {
|
|
259
|
+
for (const { id, payload } of entries) {
|
|
260
|
+
const message = parseEvent(payload)?.message;
|
|
261
|
+
const content = readContent(message?.content ?? message?.body?.content);
|
|
262
|
+
const replayable = !(typeof content.text === "string" && /^xopc_[a-f0-9]{32}$/.test(content.text.trim()));
|
|
263
|
+
if (abortSignal.aborted || !journal.begin(id, replayable)) return;
|
|
264
|
+
try {
|
|
265
|
+
await dispatch(payload);
|
|
266
|
+
journal.finish(id, "completed");
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if (abortSignal.aborted && replayable) return;
|
|
269
|
+
journal.finish(id, "interrupted");
|
|
270
|
+
log.warn({
|
|
271
|
+
accountId: account.accountId,
|
|
272
|
+
messageId: id,
|
|
273
|
+
errorType: err instanceof Error ? err.name : typeof err
|
|
274
|
+
}, "Feishu message dispatch interrupted");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}));
|
|
278
|
+
}
|
|
279
|
+
}).catch((err) => {
|
|
280
|
+
log.error({
|
|
281
|
+
accountId: account.accountId,
|
|
282
|
+
err
|
|
283
|
+
}, "Feishu inbox could not dispatch queued messages");
|
|
284
|
+
}).finally(() => {
|
|
285
|
+
pump = void 0;
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
start() {
|
|
290
|
+
const interrupted = journal.recoverInterrupted();
|
|
291
|
+
if (interrupted) log.warn({
|
|
292
|
+
accountId: account.accountId,
|
|
293
|
+
interrupted
|
|
294
|
+
}, "Feishu messages interrupted during dispatch");
|
|
295
|
+
schedule();
|
|
296
|
+
},
|
|
297
|
+
accept(event) {
|
|
298
|
+
if (abortSignal.aborted) throw new Error("Feishu transport is stopping");
|
|
299
|
+
const parsed = parseEvent(event);
|
|
300
|
+
if (!parsed) return;
|
|
301
|
+
journal.accept([{
|
|
302
|
+
id: parsed.messageId,
|
|
303
|
+
payload: event
|
|
304
|
+
}]);
|
|
305
|
+
schedule();
|
|
306
|
+
},
|
|
307
|
+
async settled() {
|
|
308
|
+
await pump;
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
//#endregion
|
|
313
|
+
export { createFeishuMessageIngress, feishuInboundScope };
|
|
@@ -9,6 +9,7 @@ export interface FeishuSocketModeMonitorDeps {
|
|
|
9
9
|
/** Used when `account.inboundDebounceMs` is unset. */
|
|
10
10
|
inboundDebounceDefaultMs: number;
|
|
11
11
|
abortSignal: AbortSignal;
|
|
12
|
+
onState?: (state: 'connecting' | 'online' | 'error') => void;
|
|
12
13
|
security: {
|
|
13
14
|
checkAccess: (ctx: ChannelSecurityContext) => {
|
|
14
15
|
allowed: boolean;
|
|
@@ -1,19 +1,17 @@
|
|
|
1
1
|
import { createLogger } from "../../../../../src/utils/logger/index.js";
|
|
2
2
|
import { init_logger } from "../../../../../src/utils/logger.js";
|
|
3
3
|
import { generateConversationId } from "../../../../../src/chat-commands/session-key.js";
|
|
4
|
-
import { getFeishuBindingByMessageId
|
|
4
|
+
import { getFeishuBindingByMessageId } from "../../state/message-bindings.js";
|
|
5
5
|
import { createFeishuClient } from "../client/client.js";
|
|
6
|
-
import {
|
|
7
|
-
import { createFeishuDedupe } from "../reliability/dedupe.js";
|
|
8
|
-
import { stripFeishuMentions } from "../text/mentions.js";
|
|
6
|
+
import { createFeishuMessageIngress } from "../reliability/message-ingress.js";
|
|
9
7
|
import { computeBackoffMs } from "./retry.js";
|
|
8
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
10
9
|
//#region extensions/feishu/src/transport/socket-mode/monitor.ts
|
|
11
10
|
init_logger();
|
|
12
11
|
const log = createLogger("FeishuSocketMode");
|
|
13
12
|
function createFeishuSocketModeMonitor(deps) {
|
|
14
|
-
const { account,
|
|
15
|
-
const
|
|
16
|
-
let lastEventAt = 0;
|
|
13
|
+
const { account, enqueueInbound, inboundDebounceDefaultMs, abortSignal } = deps;
|
|
14
|
+
const ingress = createFeishuMessageIngress(deps);
|
|
17
15
|
function resolveTextDebounceMs() {
|
|
18
16
|
if (typeof account.inboundDebounceMs === "number" && Number.isFinite(account.inboundDebounceMs)) return Math.max(0, Math.trunc(account.inboundDebounceMs));
|
|
19
17
|
return Math.max(0, Math.trunc(inboundDebounceDefaultMs));
|
|
@@ -38,7 +36,7 @@ function createFeishuSocketModeMonitor(deps) {
|
|
|
38
36
|
const notifMode = account.reactionNotifications ?? "own";
|
|
39
37
|
if (notifMode === "off") return;
|
|
40
38
|
const binding = getFeishuBindingByMessageId(msgId);
|
|
41
|
-
if (!binding) return;
|
|
39
|
+
if (!binding || binding.accountId !== account.accountId) return;
|
|
42
40
|
const reacted = await fetchFeishuMessageForReaction(api, msgId, 1500);
|
|
43
41
|
if (!reacted && notifMode === "own") return;
|
|
44
42
|
const isBotMessage = reacted?.sender_type === "app" || reacted?.senderType === "app";
|
|
@@ -71,7 +69,15 @@ function createFeishuSocketModeMonitor(deps) {
|
|
|
71
69
|
const senderId = (operator?.open_id ?? "").trim();
|
|
72
70
|
const openMessageId = (ctx?.open_message_id ?? "").trim();
|
|
73
71
|
const binding = openMessageId ? getFeishuBindingByMessageId(openMessageId) : null;
|
|
74
|
-
|
|
72
|
+
if (!senderId || !chatId && !binding || binding && binding.accountId !== account.accountId) return;
|
|
73
|
+
const isGroup = binding?.isGroup ?? chatId.startsWith("oc_");
|
|
74
|
+
const access = deps.security.checkAccess({
|
|
75
|
+
accountId: account.accountId,
|
|
76
|
+
chatId: chatId || binding.chatId,
|
|
77
|
+
senderId,
|
|
78
|
+
isGroup
|
|
79
|
+
});
|
|
80
|
+
if (access && !access.allowed) return;
|
|
75
81
|
const conversationId = binding?.conversationId ?? generateConversationId({
|
|
76
82
|
source: "feishu",
|
|
77
83
|
chatId: chatId || senderId,
|
|
@@ -104,7 +110,7 @@ function createFeishuSocketModeMonitor(deps) {
|
|
|
104
110
|
const chatId = (e?.chat_id ?? "").trim();
|
|
105
111
|
if (!recalledMessageId) return;
|
|
106
112
|
const binding = getFeishuBindingByMessageId(recalledMessageId);
|
|
107
|
-
if (!binding && !chatId) return;
|
|
113
|
+
if (!binding && !chatId || binding && binding.accountId !== account.accountId) return;
|
|
108
114
|
const isGroup = (binding?.isGroup ?? chatId.startsWith("oc_")) === true;
|
|
109
115
|
const conversationId = binding?.conversationId ?? generateConversationId({
|
|
110
116
|
source: "feishu",
|
|
@@ -131,159 +137,58 @@ function createFeishuSocketModeMonitor(deps) {
|
|
|
131
137
|
}
|
|
132
138
|
});
|
|
133
139
|
}
|
|
134
|
-
async function handleMessageReceive(event) {
|
|
135
|
-
lastEventAt = Date.now();
|
|
136
|
-
const msg = event?.event?.message ?? event?.message ?? event?.data?.message;
|
|
137
|
-
const sender = event?.event?.sender ?? event?.sender ?? event?.data?.sender;
|
|
138
|
-
const chatId = msg?.chat_id ?? msg?.chatId ?? "";
|
|
139
|
-
const messageId = msg?.message_id ?? msg?.messageId ?? "";
|
|
140
|
-
const chatType = msg?.chat_type ?? msg?.chatType ?? "";
|
|
141
|
-
const senderId = sender?.sender_id?.open_id ?? sender?.sender_id?.user_id ?? sender?.open_id ?? sender?.user_id ?? "";
|
|
142
|
-
const senderName = sender?.sender_id?.name ?? sender?.sender_name ?? void 0;
|
|
143
|
-
if (!chatId || !messageId || !senderId) {
|
|
144
|
-
log.warn({ accountId: account.accountId }, "Feishu inbound missing ids; dropping");
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
if (!dedupe.claim(messageId)) return;
|
|
148
|
-
const isGroup = chatType === "group" || chatType === "chat";
|
|
149
|
-
const text = msg?.content && typeof msg.content === "string" ? safeJsonText(msg.content) : safeJsonText(msg?.body?.content);
|
|
150
|
-
const normalizedText = stripFeishuMentions(text ?? "").trim();
|
|
151
|
-
if (!normalizedText) return;
|
|
152
|
-
const threadId = msg?.thread_id ?? msg?.threadId ?? void 0;
|
|
153
|
-
const conversationId = generateConversationId({
|
|
154
|
-
source: "feishu",
|
|
155
|
-
chatId,
|
|
156
|
-
senderId,
|
|
157
|
-
isGroup,
|
|
158
|
-
threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0,
|
|
159
|
-
accountId: account.accountId
|
|
160
|
-
});
|
|
161
|
-
recordFeishuMessageBinding({
|
|
162
|
-
messageId,
|
|
163
|
-
conversationId,
|
|
164
|
-
accountId: account.accountId,
|
|
165
|
-
chatId,
|
|
166
|
-
senderId,
|
|
167
|
-
isGroup,
|
|
168
|
-
threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0
|
|
169
|
-
});
|
|
170
|
-
const securityCtx = {
|
|
171
|
-
accountId: account.accountId,
|
|
172
|
-
chatId,
|
|
173
|
-
senderId,
|
|
174
|
-
senderName,
|
|
175
|
-
isGroup,
|
|
176
|
-
threadId
|
|
177
|
-
};
|
|
178
|
-
const access = security.checkAccess(securityCtx);
|
|
179
|
-
if (access && !access.allowed) {
|
|
180
|
-
if (!isGroup && access.reason === "pairing-required") await sendFeishuPairingPromptIfNeeded({
|
|
181
|
-
account,
|
|
182
|
-
messageId,
|
|
183
|
-
threadId: typeof threadId === "string" && threadId.trim() ? threadId : void 0,
|
|
184
|
-
senderId,
|
|
185
|
-
senderName,
|
|
186
|
-
isGroup
|
|
187
|
-
});
|
|
188
|
-
else log.warn({
|
|
189
|
-
accountId: account.accountId,
|
|
190
|
-
chatId,
|
|
191
|
-
senderId,
|
|
192
|
-
reason: access.reason
|
|
193
|
-
}, "Feishu: message dropped by channel security");
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
if (isGroup && account.requireMention) {
|
|
197
|
-
const rawText = text ?? "";
|
|
198
|
-
if (!rawText.includes("<at ") && !rawText.includes("@")) return;
|
|
199
|
-
}
|
|
200
|
-
await pushInbound("text", {
|
|
201
|
-
channel: "feishu",
|
|
202
|
-
sender_id: senderId,
|
|
203
|
-
chat_id: chatId,
|
|
204
|
-
content: normalizedText,
|
|
205
|
-
metadata: {
|
|
206
|
-
conversationId,
|
|
207
|
-
accountId: account.accountId,
|
|
208
|
-
messageId,
|
|
209
|
-
threadId,
|
|
210
|
-
isGroup,
|
|
211
|
-
feishuEventType: "im.message.receive_v1",
|
|
212
|
-
raw: event
|
|
213
|
-
}
|
|
214
|
-
});
|
|
215
|
-
}
|
|
216
140
|
async function run() {
|
|
217
141
|
let attempt = 0;
|
|
218
|
-
|
|
219
|
-
if (abortSignal.aborted) return;
|
|
220
|
-
if (lastEventAt === 0) return;
|
|
221
|
-
const silentForMs = Date.now() - lastEventAt;
|
|
222
|
-
if (silentForMs > 5 * 6e4) log.warn({
|
|
223
|
-
accountId: account.accountId,
|
|
224
|
-
silentForMs
|
|
225
|
-
}, "Feishu socket mode: no events recently");
|
|
226
|
-
}, 6e4);
|
|
142
|
+
ingress.start();
|
|
227
143
|
try {
|
|
228
144
|
while (!abortSignal.aborted) {
|
|
229
|
-
|
|
230
|
-
|
|
145
|
+
deps.onState?.("connecting");
|
|
146
|
+
let onError;
|
|
147
|
+
const failure = new Promise((resolve) => {
|
|
148
|
+
onError = resolve;
|
|
149
|
+
});
|
|
150
|
+
const online = () => {
|
|
151
|
+
attempt = 0;
|
|
152
|
+
if (!abortSignal.aborted) deps.onState?.("online");
|
|
153
|
+
};
|
|
154
|
+
const { wsClient, dispatcher, api } = createFeishuClient(account, {
|
|
155
|
+
onReady: online,
|
|
156
|
+
onReconnected: online,
|
|
157
|
+
onReconnecting: () => {
|
|
158
|
+
if (!abortSignal.aborted) deps.onState?.("connecting");
|
|
159
|
+
},
|
|
160
|
+
onError
|
|
161
|
+
});
|
|
231
162
|
dispatcher.register({
|
|
232
163
|
"im.message.receive_v1": async (data) => {
|
|
233
|
-
|
|
234
|
-
},
|
|
235
|
-
"im.message.reaction.created_v1": async (data) => {
|
|
236
|
-
await handleReactionEvent("created", data, api);
|
|
237
|
-
},
|
|
238
|
-
"im.message.reaction.deleted_v1": async (data) => {
|
|
239
|
-
await handleReactionEvent("deleted", data, api);
|
|
164
|
+
ingress.accept(data);
|
|
240
165
|
},
|
|
241
|
-
"im.message.
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
"card.action.trigger": async (data) =>
|
|
245
|
-
await handleCardAction(data);
|
|
246
|
-
}
|
|
166
|
+
"im.message.reaction.created_v1": async (data) => handleReactionEvent("created", data, api),
|
|
167
|
+
"im.message.reaction.deleted_v1": async (data) => handleReactionEvent("deleted", data, api),
|
|
168
|
+
"im.message.recalled_v1": async (data) => handleMessageRecalled(data),
|
|
169
|
+
"card.action.trigger": async (data) => handleCardAction(data)
|
|
247
170
|
});
|
|
171
|
+
const onAbort = () => onError(void 0);
|
|
172
|
+
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
248
173
|
try {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
174
|
+
if (abortSignal.aborted) return;
|
|
175
|
+
Promise.resolve(wsClient.start({ eventDispatcher: dispatcher })).catch(onError);
|
|
176
|
+
const err = await failure;
|
|
177
|
+
if (!abortSignal.aborted) {
|
|
178
|
+
deps.onState?.("error");
|
|
179
|
+
log.warn({
|
|
180
|
+
accountId: account.accountId,
|
|
181
|
+
errorType: err instanceof Error ? err.name : typeof err
|
|
182
|
+
}, "Feishu socket disconnected");
|
|
183
|
+
}
|
|
184
|
+
} finally {
|
|
185
|
+
abortSignal.removeEventListener("abort", onAbort);
|
|
186
|
+
wsClient.close({ force: true });
|
|
259
187
|
}
|
|
260
|
-
|
|
261
|
-
const onAbort = () => resolve({ ok: true });
|
|
262
|
-
if (abortSignal.aborted) return resolve({ ok: true });
|
|
263
|
-
abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
264
|
-
wsClient?.on?.("error", (err) => resolve({
|
|
265
|
-
ok: false,
|
|
266
|
-
err
|
|
267
|
-
}));
|
|
268
|
-
wsClient?.on?.("close", () => resolve({
|
|
269
|
-
ok: false,
|
|
270
|
-
err: /* @__PURE__ */ new Error("ws closed")
|
|
271
|
-
}));
|
|
272
|
-
});
|
|
273
|
-
try {
|
|
274
|
-
wsClient.stop();
|
|
275
|
-
} catch {}
|
|
276
|
-
if (abortSignal.aborted) return;
|
|
277
|
-
const delayMs = computeBackoffMs(attempt);
|
|
278
|
-
log.warn({
|
|
279
|
-
accountId: account.accountId,
|
|
280
|
-
delayMs,
|
|
281
|
-
err: exited.err ? String(exited.err) : void 0
|
|
282
|
-
}, "Feishu socket mode disconnected; restarting");
|
|
283
|
-
await sleep(delayMs, abortSignal);
|
|
188
|
+
if (!abortSignal.aborted) await setTimeout$1(computeBackoffMs(++attempt), void 0, { signal: abortSignal });
|
|
284
189
|
}
|
|
285
190
|
} finally {
|
|
286
|
-
|
|
191
|
+
await ingress.settled();
|
|
287
192
|
}
|
|
288
193
|
}
|
|
289
194
|
return { run };
|
|
@@ -314,16 +219,6 @@ function summarizeText(text, max) {
|
|
|
314
219
|
if (s.length <= max) return s;
|
|
315
220
|
return s.slice(0, max - 1) + "…";
|
|
316
221
|
}
|
|
317
|
-
function safeJsonText(raw) {
|
|
318
|
-
if (typeof raw !== "string" || !raw.trim()) return void 0;
|
|
319
|
-
try {
|
|
320
|
-
const parsed = JSON.parse(raw);
|
|
321
|
-
const t = typeof parsed?.text === "string" ? parsed.text : typeof parsed?.content === "string" ? parsed.content : typeof parsed?.title === "string" ? parsed.title : void 0;
|
|
322
|
-
return typeof t === "string" ? t : raw;
|
|
323
|
-
} catch {
|
|
324
|
-
return raw;
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
222
|
function extractCardActionCommand(action) {
|
|
328
223
|
const value = action?.value;
|
|
329
224
|
if (!value || typeof value !== "object") return null;
|
|
@@ -334,15 +229,5 @@ function extractCardActionCommand(action) {
|
|
|
334
229
|
if (text) return text;
|
|
335
230
|
return null;
|
|
336
231
|
}
|
|
337
|
-
function sleep(ms, signal) {
|
|
338
|
-
return new Promise((resolve) => {
|
|
339
|
-
if (signal.aborted) return resolve();
|
|
340
|
-
const t = setTimeout(resolve, ms);
|
|
341
|
-
signal.addEventListener("abort", () => {
|
|
342
|
-
clearTimeout(t);
|
|
343
|
-
resolve();
|
|
344
|
-
}, { once: true });
|
|
345
|
-
});
|
|
346
|
-
}
|
|
347
232
|
//#endregion
|
|
348
233
|
export { createFeishuSocketModeMonitor };
|
|
@@ -8,6 +8,7 @@ export interface FeishuWebhookMonitorDeps {
|
|
|
8
8
|
enqueueInbound: (work: FeishuInboundWork) => Promise<void>;
|
|
9
9
|
inboundDebounceDefaultMs: number;
|
|
10
10
|
abortSignal: AbortSignal;
|
|
11
|
+
onState?: (state: 'connecting' | 'online' | 'error') => void;
|
|
11
12
|
security: {
|
|
12
13
|
checkAccess: (ctx: ChannelSecurityContext) => {
|
|
13
14
|
allowed: boolean;
|