ocean-crew 0.0.0-stage → 0.4.0
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/LICENSE +21 -0
- package/README.md +156 -2
- package/THIRD_PARTY_NOTICES.md +159 -0
- package/client.js +31389 -0
- package/cordis.patch.yml +6 -0
- package/dist/host/chat/btw.js +436 -0
- package/dist/host/chat/channel.js +1241 -0
- package/dist/host/chat/chat-index.js +344 -0
- package/dist/host/chat/delivery.js +231 -0
- package/dist/host/chat/feed.js +165 -0
- package/dist/host/chat/handoffs.js +625 -0
- package/dist/host/chat/parts.js +2033 -0
- package/dist/host/chat/requests.js +155 -0
- package/dist/host/chat/resume.js +364 -0
- package/dist/host/chat/side.js +457 -0
- package/dist/host/chat/steer.js +346 -0
- package/dist/host/chat/turns.js +1457 -0
- package/dist/host/connectors/catalog.js +331 -0
- package/dist/host/connectors/gateway.js +339 -0
- package/dist/host/connectors/index.js +1235 -0
- package/dist/host/connectors/mail/index.js +912 -0
- package/dist/host/connectors/mail/presets.js +53 -0
- package/dist/host/connectors/mail/transport.js +519 -0
- package/dist/host/connectors/oauth.js +337 -0
- package/dist/host/core/constants.js +123 -0
- package/dist/host/core/diagnostics.js +310 -0
- package/dist/host/core/dsh-update.js +212 -0
- package/dist/host/core/events.js +16 -0
- package/dist/host/core/files.js +37 -0
- package/dist/host/core/folders.js +283 -0
- package/dist/host/core/home-lock.js +137 -0
- package/dist/host/core/links.js +52 -0
- package/dist/host/core/runtime.js +5 -0
- package/dist/host/core/store.js +662 -0
- package/dist/host/core/text.js +59 -0
- package/dist/host/core/thinking.js +60 -0
- package/dist/host/core/time-context.js +69 -0
- package/dist/host/core/update.js +466 -0
- package/dist/host/groups/calls.js +684 -0
- package/dist/host/groups/index.js +79 -0
- package/dist/host/groups/log.js +334 -0
- package/dist/host/groups/prompt.js +124 -0
- package/dist/host/groups/relay.js +489 -0
- package/dist/host/groups/round.js +992 -0
- package/dist/host/groups/tasks.js +217 -0
- package/dist/host/groups/tools.js +478 -0
- package/dist/host/groups/types.js +8 -0
- package/dist/host/im/format.js +228 -0
- package/dist/host/im/index.js +2461 -0
- package/dist/host/im/platforms/feishu.js +1134 -0
- package/dist/host/im/platforms/index.js +6 -0
- package/dist/host/im/platforms/media-type.js +70 -0
- package/dist/host/im/platforms/weixin.js +1117 -0
- package/dist/host/im/reaction.js +51 -0
- package/dist/host/im/supervisor.js +56 -0
- package/dist/host/team/agents.js +161 -0
- package/dist/host/team/models.js +427 -0
- package/dist/host/team/permissions.js +263 -0
- package/dist/host/team/privacy.js +108 -0
- package/dist/host/team/prompt.js +86 -0
- package/dist/host/team/providers.js +461 -0
- package/dist/host/team/roster.js +1011 -0
- package/dist/host/team/tools.js +1638 -0
- package/dist/host/work/approvals.js +290 -0
- package/dist/host/work/avatar-library.js +155 -0
- package/dist/host/work/avatar.js +132 -0
- package/dist/host/work/capabilities.js +862 -0
- package/dist/host/work/companion.js +306 -0
- package/dist/host/work/goal-skills.js +91 -0
- package/dist/host/work/goals.js +1337 -0
- package/dist/host/work/images.js +283 -0
- package/dist/host/work/learning.js +1021 -0
- package/dist/host/work/memory-pending.js +108 -0
- package/dist/host/work/memory.js +3237 -0
- package/dist/host/work/notify.js +146 -0
- package/dist/host/work/reset.js +43 -0
- package/dist/host/work/schedules.js +309 -0
- package/dist/host/work/secrets.js +702 -0
- package/dist/host/work/steward.js +166 -0
- package/dist/host/work/tts.js +192 -0
- package/dist/host/work/usage.js +84 -0
- package/dist/index.js +137 -0
- package/dist/shared/api.js +32 -0
- package/dist/shared/companion.js +110 -0
- package/dist/shared/config.js +3 -0
- package/dist/shared/coordination.js +6 -0
- package/dist/shared/group-replies.js +95 -0
- package/dist/shared/im-platforms.js +35 -0
- package/dist/shared/im.js +3 -0
- package/dist/shared/mentions.js +85 -0
- package/dist/shared/state.js +25 -0
- package/package.json +81 -5
|
@@ -0,0 +1,1134 @@
|
|
|
1
|
+
// Feishu / Lark through the official @larksuiteoapi/node-sdk: its WSClient owns
|
|
2
|
+
// the pbbp2 long connection (handshake, heartbeat, liveness, reconnect with
|
|
3
|
+
// backoff) and its Client owns the OpenAPI calls. This adapter maps those
|
|
4
|
+
// events onto the Ocean Crew IM contract: a p2p chat is direct, a group message
|
|
5
|
+
// counts when the bot's open_id is in its mentions; text goes out in 4000-char
|
|
6
|
+
// chunks with the last chunk an interactive card when buttons are given, edited
|
|
7
|
+
// by PATCH; images and files are fetched from messageResource.
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import * as Lark from "@larksuiteoapi/node-sdk";
|
|
10
|
+
import { chunkMarkdown, toPlain } from "../format.js";
|
|
11
|
+
import { imageMediaTypeOf } from "./media-type.js";
|
|
12
|
+
const TEXT_LIMIT = 4000;
|
|
13
|
+
const HANDSHAKE_TIMEOUT_MS = 15_000;
|
|
14
|
+
const PING_TIMEOUT_S = 30;
|
|
15
|
+
const BOT_INFO_TIMEOUT_MS = 15_000;
|
|
16
|
+
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
17
|
+
const MAX_SEEN_MESSAGES = 1000;
|
|
18
|
+
const MENTION = /@_user_\d+/g;
|
|
19
|
+
// Feishu answers a refused request with HTTP 200 and a non-zero business code.
|
|
20
|
+
// Authentication, parameter and IM request codes stay refused on a retry;
|
|
21
|
+
// 230020 is rate limiting and 230049 means the send result is unknown.
|
|
22
|
+
const TRANSIENT_CODES = new Set([230020, 230049]);
|
|
23
|
+
const UNKNOWN_RESULT_CODE = 230049;
|
|
24
|
+
const NETWORK_CODES = new Set([
|
|
25
|
+
"ECONNRESET",
|
|
26
|
+
"ECONNABORTED",
|
|
27
|
+
"ETIMEDOUT",
|
|
28
|
+
"EPIPE",
|
|
29
|
+
"ENOTFOUND",
|
|
30
|
+
"EAI_AGAIN",
|
|
31
|
+
"EHOSTUNREACH",
|
|
32
|
+
"ENETUNREACH",
|
|
33
|
+
"ECONNREFUSED",
|
|
34
|
+
"ERR_NETWORK",
|
|
35
|
+
"ERR_SOCKET_CONNECTION_TIMEOUT",
|
|
36
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
37
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
38
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
39
|
+
"UND_ERR_SOCKET",
|
|
40
|
+
]);
|
|
41
|
+
const scrubText = (text, secret) => {
|
|
42
|
+
const value = String(text ?? "");
|
|
43
|
+
return (secret === "" ? value : value.replaceAll(String(secret), "***")).slice(0, 300) || "error";
|
|
44
|
+
};
|
|
45
|
+
const reason = (error) => String(error?.message ?? error ?? "").slice(0, 300) || "error";
|
|
46
|
+
const fieldsOf = (fields) => ({
|
|
47
|
+
appId: String(fields?.appId ?? "").trim(),
|
|
48
|
+
appSecret: String(fields?.appSecret ?? "").trim(),
|
|
49
|
+
});
|
|
50
|
+
const domainOf = (lark, fields) => String(fields?.domain ?? "feishu") === "lark" ? lark.Domain.Lark : lark.Domain.Feishu;
|
|
51
|
+
const parseJson = (text) => {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(String(text ?? "{}"));
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const withoutMentions = (text) => String(text ?? "")
|
|
60
|
+
.replace(MENTION, "")
|
|
61
|
+
.trim();
|
|
62
|
+
const withDeadline = (promise, ms, onTimeout) => {
|
|
63
|
+
let timer;
|
|
64
|
+
const deadline = new Promise((resolve) => {
|
|
65
|
+
timer = setTimeout(() => {
|
|
66
|
+
onTimeout();
|
|
67
|
+
resolve(undefined);
|
|
68
|
+
}, ms);
|
|
69
|
+
timer.unref?.();
|
|
70
|
+
});
|
|
71
|
+
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
|
|
72
|
+
};
|
|
73
|
+
const isPermanentCode = (code) => !TRANSIENT_CODES.has(code) &&
|
|
74
|
+
((code >= 10000 && code < 20000) || code >= 99991000 || (code >= 230000 && code < 240000));
|
|
75
|
+
const businessError = (what, body, scrub) => {
|
|
76
|
+
const code = Number(body?.code);
|
|
77
|
+
const error = new Error(scrub(`${what} failed: ${String(body?.msg ?? "unknown error")} (code ${code})`));
|
|
78
|
+
error.platformCode = code;
|
|
79
|
+
if (code === UNKNOWN_RESULT_CODE)
|
|
80
|
+
error.unknown = true;
|
|
81
|
+
else if (isPermanentCode(code))
|
|
82
|
+
error.permanent = true;
|
|
83
|
+
return error;
|
|
84
|
+
};
|
|
85
|
+
const isNetworkError = (cause) => {
|
|
86
|
+
if (cause?.response !== undefined)
|
|
87
|
+
return false;
|
|
88
|
+
if (cause?.isAxiosError === true)
|
|
89
|
+
return true;
|
|
90
|
+
if (NETWORK_CODES.has(String(cause?.code ?? "")))
|
|
91
|
+
return true;
|
|
92
|
+
return cause?.name === "TimeoutError" || cause?.name === "AbortError";
|
|
93
|
+
};
|
|
94
|
+
const retryAfterSeconds = (cause) => {
|
|
95
|
+
const headers = cause?.response?.headers;
|
|
96
|
+
const value = typeof headers?.get === "function" ? headers.get("retry-after") : headers?.["retry-after"];
|
|
97
|
+
const seconds = Number(value);
|
|
98
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined;
|
|
99
|
+
};
|
|
100
|
+
const transportError = (what, cause, scrub) => {
|
|
101
|
+
const status = Number(cause?.response?.status);
|
|
102
|
+
const body = cause?.response?.data;
|
|
103
|
+
const code = Number(body?.code);
|
|
104
|
+
const detail = body?.msg ?? cause?.message ?? String(cause ?? "unknown error");
|
|
105
|
+
const error = new Error(scrub(`${what} failed: ${detail}${Number.isFinite(code) && code !== 0 ? ` (code ${code})` : ""}`));
|
|
106
|
+
// The platform code is kept whichever branch below decides the failure class: callers
|
|
107
|
+
// such as the reply fallback need to tell one Feishu code from another.
|
|
108
|
+
if (Number.isFinite(code) && code !== 0)
|
|
109
|
+
error.platformCode = code;
|
|
110
|
+
if (Number.isFinite(status)) {
|
|
111
|
+
if (status === 429) {
|
|
112
|
+
const after = retryAfterSeconds(cause);
|
|
113
|
+
if (after !== undefined)
|
|
114
|
+
error.retryAfter = after;
|
|
115
|
+
}
|
|
116
|
+
else if (status >= 400 && status < 500) {
|
|
117
|
+
error.permanent = true;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
else if (Number.isFinite(code) && code !== 0) {
|
|
121
|
+
if (code === UNKNOWN_RESULT_CODE)
|
|
122
|
+
error.unknown = true;
|
|
123
|
+
else if (isPermanentCode(code))
|
|
124
|
+
error.permanent = true;
|
|
125
|
+
}
|
|
126
|
+
else if (isNetworkError(cause)) {
|
|
127
|
+
error.unknown = true;
|
|
128
|
+
}
|
|
129
|
+
return error;
|
|
130
|
+
};
|
|
131
|
+
// One SDK call: a thrown transport error is classified, a returned non-zero
|
|
132
|
+
// business code is turned into a thrown error with the platform message.
|
|
133
|
+
const call = async (what, operation, scrub) => {
|
|
134
|
+
let body;
|
|
135
|
+
try {
|
|
136
|
+
body = await operation();
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
throw transportError(what, error, scrub);
|
|
140
|
+
}
|
|
141
|
+
if (body?.code !== undefined && Number(body.code) !== 0)
|
|
142
|
+
throw businessError(what, body, scrub);
|
|
143
|
+
return body;
|
|
144
|
+
};
|
|
145
|
+
const botInfo = async (client, scrub) => {
|
|
146
|
+
const body = await call("Feishu bot info", () => client.request({ method: "GET", url: "/open-apis/bot/v3/info" }), scrub);
|
|
147
|
+
const bot = body?.bot ?? body ?? {};
|
|
148
|
+
return { id: String(bot.open_id ?? bot.app_id ?? ""), name: String(bot.app_name ?? "") };
|
|
149
|
+
};
|
|
150
|
+
const contentLength = (headers) => {
|
|
151
|
+
const value = typeof headers?.get === "function" ? headers.get("content-length") : headers?.["content-length"];
|
|
152
|
+
const length = Number(value);
|
|
153
|
+
return Number.isFinite(length) && length >= 0 ? length : undefined;
|
|
154
|
+
};
|
|
155
|
+
const messageResource = async (client, messageId, fileKey, type, limit) => {
|
|
156
|
+
const response = await client.im.messageResource.get({
|
|
157
|
+
path: { message_id: messageId, file_key: fileKey },
|
|
158
|
+
params: { type },
|
|
159
|
+
});
|
|
160
|
+
const declared = contentLength(response?.headers);
|
|
161
|
+
if (limit !== undefined && declared !== undefined && declared > limit)
|
|
162
|
+
throw new Error(`resource is larger than ${limit} bytes`);
|
|
163
|
+
const stream = response?.getReadableStream?.();
|
|
164
|
+
if (stream === undefined || stream === null)
|
|
165
|
+
throw new Error("Feishu returned no resource stream");
|
|
166
|
+
const chunks = [];
|
|
167
|
+
let size = 0;
|
|
168
|
+
for await (const chunk of stream) {
|
|
169
|
+
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
170
|
+
size += data.length;
|
|
171
|
+
if (limit !== undefined && size > limit)
|
|
172
|
+
throw new Error(`resource is larger than ${limit} bytes`);
|
|
173
|
+
chunks.push(data);
|
|
174
|
+
}
|
|
175
|
+
return Buffer.concat(chunks);
|
|
176
|
+
};
|
|
177
|
+
// Feishu sends a post (and forwarded history) as paragraphs of typed elements. Rendering
|
|
178
|
+
// the element tags keeps what the sender meant: a mention keeps its name, a code block
|
|
179
|
+
// keeps its fence, and a line break stays a line break. Dropping them loses structure
|
|
180
|
+
// that the model needs to answer.
|
|
181
|
+
const postPayload = (content) => {
|
|
182
|
+
if (content === null || typeof content !== "object")
|
|
183
|
+
return undefined;
|
|
184
|
+
// A post may arrive wrapped, and its body may sit under one locale key per language.
|
|
185
|
+
if (content.post !== undefined && typeof content.post === "object")
|
|
186
|
+
return content.post;
|
|
187
|
+
if (Array.isArray(content.content))
|
|
188
|
+
return content;
|
|
189
|
+
for (const [key, value] of Object.entries(content)) {
|
|
190
|
+
if (/^[a-z]{2}_[a-z]{2}$/i.test(key) && value !== null && typeof value === "object")
|
|
191
|
+
return value;
|
|
192
|
+
}
|
|
193
|
+
return content;
|
|
194
|
+
};
|
|
195
|
+
const renderPostElement = (element) => {
|
|
196
|
+
if (element === null || typeof element !== "object")
|
|
197
|
+
return "";
|
|
198
|
+
const tag = String(element.tag ?? element.type ?? "");
|
|
199
|
+
switch (tag) {
|
|
200
|
+
case "text":
|
|
201
|
+
return String(element.text ?? "");
|
|
202
|
+
case "a":
|
|
203
|
+
case "link": {
|
|
204
|
+
const label = String(element.text ?? "").trim();
|
|
205
|
+
const href = String(element.href ?? element.url ?? "");
|
|
206
|
+
if (href === "")
|
|
207
|
+
return label;
|
|
208
|
+
return label === "" ? href : `[${label}](${href})`;
|
|
209
|
+
}
|
|
210
|
+
case "at":
|
|
211
|
+
// @all is the platform's everyone marker; a person keeps the name it was given.
|
|
212
|
+
return `@${String(element.user_name ?? element.user_id ?? "all")}`;
|
|
213
|
+
case "emotion":
|
|
214
|
+
case "emoji":
|
|
215
|
+
return `:${String(element.emoji_type ?? element.emoji_key ?? "")}:`;
|
|
216
|
+
case "br":
|
|
217
|
+
return "\n";
|
|
218
|
+
case "hr":
|
|
219
|
+
case "divider":
|
|
220
|
+
return "\n---\n";
|
|
221
|
+
case "code_block":
|
|
222
|
+
case "pre": {
|
|
223
|
+
const language = String(element.language ?? "").replace(/[^\w+#.-]/g, "");
|
|
224
|
+
const code = String(element.text ?? element.content ?? "");
|
|
225
|
+
return `\n\`\`\`${language}\n${code}\n\`\`\`\n`;
|
|
226
|
+
}
|
|
227
|
+
case "img":
|
|
228
|
+
case "image":
|
|
229
|
+
return "[Image]";
|
|
230
|
+
case "media":
|
|
231
|
+
case "file":
|
|
232
|
+
case "audio":
|
|
233
|
+
case "video": {
|
|
234
|
+
const name = String(element.file_name ?? element.file_key ?? "").trim();
|
|
235
|
+
return name === "" ? "[Attachment]" : `[Attachment: ${name}]`;
|
|
236
|
+
}
|
|
237
|
+
default:
|
|
238
|
+
for (const key of ["text", "title", "content", "children", "elements"]) {
|
|
239
|
+
const value = element[key];
|
|
240
|
+
if (Array.isArray(value))
|
|
241
|
+
return value.map(renderPostElement).join("");
|
|
242
|
+
if (typeof value === "string" && value !== "")
|
|
243
|
+
return value;
|
|
244
|
+
}
|
|
245
|
+
return "";
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
const postText = (content) => {
|
|
249
|
+
const payload = postPayload(content);
|
|
250
|
+
if (payload === undefined || payload === null)
|
|
251
|
+
return "";
|
|
252
|
+
const lines = [];
|
|
253
|
+
const title = withoutMentions(String(payload.title ?? ""));
|
|
254
|
+
if (title !== "")
|
|
255
|
+
lines.push(title);
|
|
256
|
+
for (const paragraph of Array.isArray(payload.content) ? payload.content : []) {
|
|
257
|
+
if (!Array.isArray(paragraph))
|
|
258
|
+
continue;
|
|
259
|
+
const text = paragraph.map(renderPostElement).join("");
|
|
260
|
+
for (const line of withoutMentions(text).split("\n"))
|
|
261
|
+
if (line.trim() !== "")
|
|
262
|
+
lines.push(line.trimEnd());
|
|
263
|
+
}
|
|
264
|
+
return lines.join("\n");
|
|
265
|
+
};
|
|
266
|
+
// Every image inside a post, in reading order, so the files can be fetched.
|
|
267
|
+
const postImageKeys = (content) => {
|
|
268
|
+
const payload = postPayload(content);
|
|
269
|
+
const keys = [];
|
|
270
|
+
for (const paragraph of Array.isArray(payload?.content) ? payload.content : []) {
|
|
271
|
+
if (!Array.isArray(paragraph))
|
|
272
|
+
continue;
|
|
273
|
+
for (const element of paragraph) {
|
|
274
|
+
const tag = String(element?.tag ?? element?.type ?? "");
|
|
275
|
+
if (tag !== "img" && tag !== "image")
|
|
276
|
+
continue;
|
|
277
|
+
const key = String(element?.image_key ?? element?.imageKey ?? "");
|
|
278
|
+
if (key !== "")
|
|
279
|
+
keys.push(key);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return keys;
|
|
283
|
+
};
|
|
284
|
+
const firstText = (payload, keys, depth = 0) => {
|
|
285
|
+
if (payload === null || typeof payload !== "object" || depth > 4)
|
|
286
|
+
return "";
|
|
287
|
+
for (const key of keys) {
|
|
288
|
+
const value = payload[key];
|
|
289
|
+
if (typeof value === "string" && value.trim() !== "")
|
|
290
|
+
return value.trim();
|
|
291
|
+
// Feishu wraps a card title as {title: {tag, content}} rather than a bare string.
|
|
292
|
+
if (value !== null && typeof value === "object" && typeof value.content === "string") {
|
|
293
|
+
if (value.content.trim() !== "")
|
|
294
|
+
return value.content.trim();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
for (const value of Object.values(payload)) {
|
|
298
|
+
if (value !== null && typeof value === "object") {
|
|
299
|
+
const found = firstText(value, keys, depth + 1);
|
|
300
|
+
if (found !== "")
|
|
301
|
+
return found;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return "";
|
|
305
|
+
};
|
|
306
|
+
// A forwarded conversation arrives as a title plus entries; the first few carry the
|
|
307
|
+
// context the user is pointing at, and a silent drop loses the whole message.
|
|
308
|
+
const mergeForwardText = (content) => {
|
|
309
|
+
const lines = [];
|
|
310
|
+
const title = firstText(content, ["title", "summary", "preview"]);
|
|
311
|
+
if (title !== "")
|
|
312
|
+
lines.push(title);
|
|
313
|
+
const entries = [];
|
|
314
|
+
for (const key of ["messages", "items", "message_list", "records", "content"]) {
|
|
315
|
+
const value = content?.[key];
|
|
316
|
+
if (Array.isArray(value))
|
|
317
|
+
entries.push(...value);
|
|
318
|
+
}
|
|
319
|
+
for (const entry of entries.slice(0, 8)) {
|
|
320
|
+
if (entry === null || typeof entry !== "object") {
|
|
321
|
+
const text = String(entry ?? "").trim();
|
|
322
|
+
if (text !== "")
|
|
323
|
+
lines.push(`- ${text}`);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
const sender = firstText(entry, ["sender_name", "user_name", "sender", "name"]);
|
|
327
|
+
const type = String(entry.message_type ?? entry.msg_type ?? "");
|
|
328
|
+
const body = type === "post"
|
|
329
|
+
? postText(entry.content ?? entry)
|
|
330
|
+
: firstText(entry, ["text", "summary", "preview", "content", "title"]);
|
|
331
|
+
if (body !== "")
|
|
332
|
+
lines.push(`- ${sender === "" ? body : `${sender}: ${body}`}`);
|
|
333
|
+
}
|
|
334
|
+
return lines.join("\n");
|
|
335
|
+
};
|
|
336
|
+
const mergeForwardImages = (content) => {
|
|
337
|
+
const entries = [];
|
|
338
|
+
for (const key of ["messages", "items", "message_list", "records", "content"]) {
|
|
339
|
+
const value = content?.[key];
|
|
340
|
+
if (Array.isArray(value))
|
|
341
|
+
entries.push(...value);
|
|
342
|
+
}
|
|
343
|
+
const parts = [];
|
|
344
|
+
for (const entry of entries.slice(0, 8)) {
|
|
345
|
+
if (entry === null || typeof entry !== "object")
|
|
346
|
+
continue;
|
|
347
|
+
const messageId = String(entry.message_id ?? entry.messageId ?? "");
|
|
348
|
+
if (messageId === "")
|
|
349
|
+
continue;
|
|
350
|
+
const type = String(entry.message_type ?? entry.msg_type ?? "");
|
|
351
|
+
const parsed = typeof entry.content === "string" ? parseJson(entry.content) : (entry.content ?? {});
|
|
352
|
+
if (type === "image") {
|
|
353
|
+
const key = String(parsed?.image_key ?? "");
|
|
354
|
+
if (key !== "")
|
|
355
|
+
parts.push({ messageId, imageKey: key });
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (type === "post") {
|
|
359
|
+
for (const key of postImageKeys(parsed))
|
|
360
|
+
parts.push({ messageId, imageKey: key });
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
return parts.slice(0, 4);
|
|
364
|
+
};
|
|
365
|
+
const shareChatText = (content) => {
|
|
366
|
+
const name = firstText(content, ["chat_name", "name", "title"]);
|
|
367
|
+
const id = String(content?.chat_id ?? content?.open_chat_id ?? content?.share_chat_id ?? "");
|
|
368
|
+
const lines = [name === "" ? "Shared chat" : `Shared chat: ${name}`];
|
|
369
|
+
if (id !== "")
|
|
370
|
+
lines.push(`Chat ID: ${id}`);
|
|
371
|
+
return lines.join("\n");
|
|
372
|
+
};
|
|
373
|
+
// A card carries its title, a few text lines and its buttons; rendering those is what
|
|
374
|
+
// lets the model answer a question that arrived as a card.
|
|
375
|
+
const interactiveText = (content) => {
|
|
376
|
+
const card = content?.card !== undefined && typeof content.card === "object" ? content.card : content;
|
|
377
|
+
const lines = [];
|
|
378
|
+
const actions = [];
|
|
379
|
+
const title = firstText(card, ["title", "summary", "subtitle"]);
|
|
380
|
+
if (title !== "")
|
|
381
|
+
lines.push(title);
|
|
382
|
+
const walk = (node, depth) => {
|
|
383
|
+
if (node === null || typeof node !== "object" || depth > 5)
|
|
384
|
+
return;
|
|
385
|
+
if (Array.isArray(node)) {
|
|
386
|
+
for (const item of node)
|
|
387
|
+
walk(item, depth + 1);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (node.tag === "button" || node.tag === "action") {
|
|
391
|
+
const label = String(node.text?.content ?? node.text ?? "").trim();
|
|
392
|
+
if (label !== "")
|
|
393
|
+
actions.push(label);
|
|
394
|
+
for (const action of Array.isArray(node.actions) ? node.actions : [])
|
|
395
|
+
walk(action, depth + 1);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
for (const key of ["elements", "body", "content", "children"]) {
|
|
399
|
+
if (node[key] !== undefined)
|
|
400
|
+
walk(node[key], depth + 1);
|
|
401
|
+
}
|
|
402
|
+
const text = typeof node.content === "string" ? node.content : typeof node.text === "string" ? node.text : "";
|
|
403
|
+
if (text.trim() !== "")
|
|
404
|
+
lines.push(text.trim());
|
|
405
|
+
};
|
|
406
|
+
walk(card, 0);
|
|
407
|
+
const body = lines.filter((line, index) => index === 0 || line !== title).slice(0, 12);
|
|
408
|
+
if (actions.length > 0)
|
|
409
|
+
body.push(`Actions: ${actions.join(", ")}`);
|
|
410
|
+
return body.join("\n");
|
|
411
|
+
};
|
|
412
|
+
// A reply as Feishu renders Markdown, so **bold**, lists, links and `code` show as
|
|
413
|
+
// themselves instead of as punctuation. Feishu's md renderer drops what follows a fenced
|
|
414
|
+
// code block inside one element, so the reply is split at real fences: prose in one row,
|
|
415
|
+
// each fenced block in its own.
|
|
416
|
+
const POST_ROWS = (content) => {
|
|
417
|
+
const rows = [];
|
|
418
|
+
let current = [];
|
|
419
|
+
let fenced = false;
|
|
420
|
+
const flush = () => {
|
|
421
|
+
if (current.length === 0)
|
|
422
|
+
return;
|
|
423
|
+
const text = current.join("\n");
|
|
424
|
+
if (text.trim() !== "")
|
|
425
|
+
rows.push([{ tag: "md", text }]);
|
|
426
|
+
current = [];
|
|
427
|
+
};
|
|
428
|
+
for (const line of content.split("\n")) {
|
|
429
|
+
const fence = /^\s*(?:```|~~~)/.test(line);
|
|
430
|
+
if (fence && !fenced)
|
|
431
|
+
flush();
|
|
432
|
+
current.push(line);
|
|
433
|
+
if (fence) {
|
|
434
|
+
fenced = !fenced;
|
|
435
|
+
if (!fenced)
|
|
436
|
+
flush();
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
flush();
|
|
440
|
+
return rows.length > 0 ? rows : [[{ tag: "md", text: content }]];
|
|
441
|
+
};
|
|
442
|
+
const post = (content) => JSON.stringify({ zh_cn: { content: POST_ROWS(content) } });
|
|
443
|
+
// A post whose only element is a markdown block reads as a code-like block on some
|
|
444
|
+
// Feishu clients, so plain prose goes out as a text message; markdown-shaped prose is
|
|
445
|
+
// rendered by the platform. The shapes are what the reference platform client uses.
|
|
446
|
+
const MARKDOWN_HINT = /(^#{1,6}\s)|(^\s*[-*]\s)|(^\s*\d+\.\s)|(^\s*---+\s*$)|(```)|(`[^`\n]+`)|(\*\*[^*\n].+?\*\*)|(~~[^~\n].+?~~)|(<u>.+?<\/u>)|(\*[^*\n]+\*)|(\[[^\]]+\]\([^)]+\))|(^>\s)/m;
|
|
447
|
+
// A card is an event, not a paragraph: a coloured header makes an approval read as one
|
|
448
|
+
// at a glance, the way a chat client shows a pending decision. The body and the button
|
|
449
|
+
// row follow the shapes the platform's own client renders as a normal card; a legacy
|
|
450
|
+
// `action` container leaves the card unstyled (a grey block) on current clients.
|
|
451
|
+
const FILE_ROUTES = {
|
|
452
|
+
pdf: { upload: "pdf", msgType: "file" },
|
|
453
|
+
doc: { upload: "doc", msgType: "file" },
|
|
454
|
+
docx: { upload: "doc", msgType: "file" },
|
|
455
|
+
xls: { upload: "xls", msgType: "file" },
|
|
456
|
+
xlsx: { upload: "xls", msgType: "file" },
|
|
457
|
+
ppt: { upload: "ppt", msgType: "file" },
|
|
458
|
+
pptx: { upload: "ppt", msgType: "file" },
|
|
459
|
+
ogg: { upload: "opus", msgType: "audio" },
|
|
460
|
+
opus: { upload: "opus", msgType: "audio" },
|
|
461
|
+
mp4: { upload: "mp4", msgType: "media" },
|
|
462
|
+
mov: { upload: "mp4", msgType: "media" },
|
|
463
|
+
avi: { upload: "mp4", msgType: "media" },
|
|
464
|
+
m4v: { upload: "mp4", msgType: "media" },
|
|
465
|
+
};
|
|
466
|
+
const routeOf = (name) => {
|
|
467
|
+
const ext = name.split(".").pop()?.toLowerCase() ?? "";
|
|
468
|
+
return FILE_ROUTES[ext] ?? { upload: "stream", msgType: "file" };
|
|
469
|
+
};
|
|
470
|
+
const postWith = (text, rows) => {
|
|
471
|
+
const content = POST_ROWS(text);
|
|
472
|
+
for (const row of rows)
|
|
473
|
+
content.push([row]);
|
|
474
|
+
return JSON.stringify({ zh_cn: { content } });
|
|
475
|
+
};
|
|
476
|
+
const replyCard = (text, title) => JSON.stringify({
|
|
477
|
+
schema: "2.0",
|
|
478
|
+
...(title === undefined ? {} : { header: { title: { tag: "plain_text", content: title }, template: "blue" } }),
|
|
479
|
+
body: { elements: [{ tag: "markdown", content: text }] },
|
|
480
|
+
});
|
|
481
|
+
const cardForm = (form) => ({
|
|
482
|
+
tag: "form",
|
|
483
|
+
name: "oc_form",
|
|
484
|
+
elements: [
|
|
485
|
+
...form.fields.map((field) => field.kind === "multi" || field.kind === "select"
|
|
486
|
+
? {
|
|
487
|
+
tag: field.kind === "multi" ? "multi_select_static" : "select_static",
|
|
488
|
+
name: field.name,
|
|
489
|
+
placeholder: { tag: "plain_text", content: field.label },
|
|
490
|
+
options: (field.options ?? []).map((option) => ({
|
|
491
|
+
text: { tag: "plain_text", content: option },
|
|
492
|
+
value: option,
|
|
493
|
+
})),
|
|
494
|
+
...(Array.isArray(field.initial)
|
|
495
|
+
? {}
|
|
496
|
+
: field.initial === undefined
|
|
497
|
+
? {}
|
|
498
|
+
: { initial_option: field.initial }),
|
|
499
|
+
}
|
|
500
|
+
: {
|
|
501
|
+
tag: "input",
|
|
502
|
+
name: field.name,
|
|
503
|
+
label: { tag: "plain_text", content: field.label },
|
|
504
|
+
placeholder: { tag: "plain_text", content: field.label },
|
|
505
|
+
...(field.multiline === true ? { input_type: "multiline_text" } : {}),
|
|
506
|
+
...(typeof field.initial === "string" ? { default_value: field.initial } : {}),
|
|
507
|
+
}),
|
|
508
|
+
{
|
|
509
|
+
tag: "button",
|
|
510
|
+
name: "oc_submit",
|
|
511
|
+
text: { tag: "plain_text", content: form.submit.label },
|
|
512
|
+
type: "primary",
|
|
513
|
+
form_action_type: "submit",
|
|
514
|
+
},
|
|
515
|
+
...(form.cancel === undefined
|
|
516
|
+
? []
|
|
517
|
+
: [
|
|
518
|
+
{
|
|
519
|
+
tag: "button",
|
|
520
|
+
name: "oc_cancel",
|
|
521
|
+
text: { tag: "plain_text", content: form.cancel.label },
|
|
522
|
+
type: "default",
|
|
523
|
+
behaviors: [{ type: "callback", value: { action: form.cancel.data } }],
|
|
524
|
+
},
|
|
525
|
+
]),
|
|
526
|
+
],
|
|
527
|
+
});
|
|
528
|
+
const card = (text, buttons, title, form) => {
|
|
529
|
+
const row = buttons === undefined || buttons.length === 0
|
|
530
|
+
? []
|
|
531
|
+
: [
|
|
532
|
+
{ tag: "hr" },
|
|
533
|
+
{
|
|
534
|
+
tag: "column_set",
|
|
535
|
+
flex_mode: "none",
|
|
536
|
+
columns: buttons.slice(0, 5).map((button) => ({
|
|
537
|
+
tag: "column",
|
|
538
|
+
width: "weighted",
|
|
539
|
+
weight: 1,
|
|
540
|
+
elements: [
|
|
541
|
+
{
|
|
542
|
+
tag: "button",
|
|
543
|
+
text: { tag: "plain_text", content: String(button.label ?? "").slice(0, 20) },
|
|
544
|
+
type: "default",
|
|
545
|
+
width: "fill",
|
|
546
|
+
behaviors: [{ type: "callback", value: { action: button.data } }],
|
|
547
|
+
},
|
|
548
|
+
],
|
|
549
|
+
})),
|
|
550
|
+
},
|
|
551
|
+
];
|
|
552
|
+
return JSON.stringify({
|
|
553
|
+
schema: "2.0",
|
|
554
|
+
header: {
|
|
555
|
+
title: { tag: "plain_text", content: title ?? "Action needed" },
|
|
556
|
+
template: "blue",
|
|
557
|
+
},
|
|
558
|
+
body: {
|
|
559
|
+
elements: [
|
|
560
|
+
{ tag: "div", text: { tag: "lark_md", content: text } },
|
|
561
|
+
...(form === undefined ? row : [cardForm(form)]),
|
|
562
|
+
],
|
|
563
|
+
},
|
|
564
|
+
});
|
|
565
|
+
};
|
|
566
|
+
/** A quoted message renders to the same text a live one would; cached per message. */
|
|
567
|
+
const quotedCache = new Map();
|
|
568
|
+
const quotedText = async (client, messageId, scrub, warn) => {
|
|
569
|
+
const held = quotedCache.get(messageId);
|
|
570
|
+
if (held !== undefined)
|
|
571
|
+
return held;
|
|
572
|
+
let text = "";
|
|
573
|
+
try {
|
|
574
|
+
const body = await call("Feishu quoted message", () => client.im.message.get({ path: { message_id: messageId } }), scrub);
|
|
575
|
+
const item = Array.isArray(body?.data?.items) ? body.data.items[0] : undefined;
|
|
576
|
+
const type = String(item?.msg_type ?? item?.message_type ?? "");
|
|
577
|
+
const content = parseJson(item?.body?.content ?? item?.content);
|
|
578
|
+
if (type === "post")
|
|
579
|
+
text = postText(content);
|
|
580
|
+
else if (type === "text")
|
|
581
|
+
text = String(content?.text ?? "");
|
|
582
|
+
else if (type === "merge_forward")
|
|
583
|
+
text = mergeForwardText(content);
|
|
584
|
+
else if (type === "share_chat")
|
|
585
|
+
text = shareChatText(content);
|
|
586
|
+
else if (type === "interactive")
|
|
587
|
+
text = interactiveText(content);
|
|
588
|
+
else if (type === "image")
|
|
589
|
+
text = "[Image]";
|
|
590
|
+
else if (type === "file" || type === "audio" || type === "media") {
|
|
591
|
+
text = `[Attachment: ${String(content?.file_name ?? type)}]`;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
catch (error) {
|
|
595
|
+
warn("ocean-crew im: feishu quoted message not readable: %s", error);
|
|
596
|
+
}
|
|
597
|
+
if (quotedCache.size > MAX_SEEN_MESSAGES)
|
|
598
|
+
quotedCache.clear();
|
|
599
|
+
quotedCache.set(messageId, text);
|
|
600
|
+
return text;
|
|
601
|
+
};
|
|
602
|
+
/** A sender's display name, so the Bot does not read opaque open_ids. Cached with a TTL. */
|
|
603
|
+
const SENDER_TTL_MS = 10 * 60_000;
|
|
604
|
+
const senderNames = new Map();
|
|
605
|
+
const senderName = async (client, senderId, scrub) => {
|
|
606
|
+
if (senderId === "")
|
|
607
|
+
return "";
|
|
608
|
+
const held = senderNames.get(senderId);
|
|
609
|
+
if (held !== undefined && Date.now() - held.at < SENDER_TTL_MS)
|
|
610
|
+
return held.name;
|
|
611
|
+
let name = "";
|
|
612
|
+
try {
|
|
613
|
+
const body = await call("Feishu sender", () => client.contact.v3.user.get({
|
|
614
|
+
params: { user_id_type: "open_id" },
|
|
615
|
+
path: { user_id: senderId },
|
|
616
|
+
}), scrub);
|
|
617
|
+
name = String(body?.data?.user?.name ?? body?.data?.user?.en_name ?? "");
|
|
618
|
+
}
|
|
619
|
+
catch {
|
|
620
|
+
// A bot or a user outside the app's scope has no contact record; the id is enough.
|
|
621
|
+
}
|
|
622
|
+
if (senderNames.size > MAX_SEEN_MESSAGES)
|
|
623
|
+
senderNames.clear();
|
|
624
|
+
senderNames.set(senderId, { name, at: Date.now() });
|
|
625
|
+
return name;
|
|
626
|
+
};
|
|
627
|
+
/** The Feishu adapter the host registers; env carries runtime/log and the SDK (tests inject it). */
|
|
628
|
+
const feishu = {
|
|
629
|
+
id: "feishu",
|
|
630
|
+
async check(fields, env) {
|
|
631
|
+
const lark = env.lark ?? Lark;
|
|
632
|
+
const { appId, appSecret } = fieldsOf(fields);
|
|
633
|
+
if (appId === "" || appSecret === "")
|
|
634
|
+
throw new Error("Feishu needs an App ID and an App Secret");
|
|
635
|
+
const scrub = (text) => scrubText(text, appSecret);
|
|
636
|
+
const client = new lark.Client({
|
|
637
|
+
appId,
|
|
638
|
+
appSecret,
|
|
639
|
+
domain: domainOf(lark, fields),
|
|
640
|
+
loggerLevel: lark.LoggerLevel.warn,
|
|
641
|
+
});
|
|
642
|
+
const bot = await botInfo(client, scrub);
|
|
643
|
+
return { account: { id: bot.id || appId, name: bot.name || appId } };
|
|
644
|
+
},
|
|
645
|
+
connect(fields, env, handlers) {
|
|
646
|
+
const lark = env.lark ?? Lark;
|
|
647
|
+
const { appId, appSecret } = fieldsOf(fields);
|
|
648
|
+
if (appId === "" || appSecret === "")
|
|
649
|
+
throw new Error("Feishu needs an App ID and an App Secret");
|
|
650
|
+
const scrub = (text) => scrubText(text, appSecret);
|
|
651
|
+
const client = new lark.Client({
|
|
652
|
+
appId,
|
|
653
|
+
appSecret,
|
|
654
|
+
domain: domainOf(lark, fields),
|
|
655
|
+
loggerLevel: lark.LoggerLevel.warn,
|
|
656
|
+
});
|
|
657
|
+
const chats = new Map();
|
|
658
|
+
// Message ids remembered across redeliveries and restarts: the SDK may
|
|
659
|
+
// deliver an event again after a reconnect, and dispatching it twice would
|
|
660
|
+
// run the Bot turn twice. In-flight ids also block a near-simultaneous copy.
|
|
661
|
+
const remembered = env.runtime?.get?.()?.seenMessageIds;
|
|
662
|
+
const seen = new Set(Array.isArray(remembered) ? remembered.filter((id) => typeof id === "string") : []);
|
|
663
|
+
const delivering = new Set();
|
|
664
|
+
while (seen.size > MAX_SEEN_MESSAGES)
|
|
665
|
+
seen.delete(seen.values().next().value);
|
|
666
|
+
let botOpenId = "";
|
|
667
|
+
let stopped = false;
|
|
668
|
+
const warn = (template, error) => env.log?.warn?.(template, scrub(reason(error)));
|
|
669
|
+
const remember = (messageId) => {
|
|
670
|
+
seen.add(messageId);
|
|
671
|
+
while (seen.size > MAX_SEEN_MESSAGES)
|
|
672
|
+
seen.delete(seen.values().next().value);
|
|
673
|
+
try {
|
|
674
|
+
env.runtime?.set?.({ seenMessageIds: [...seen] });
|
|
675
|
+
}
|
|
676
|
+
catch (error) {
|
|
677
|
+
warn("ocean-crew im: feishu seen messages not saved: %s", error);
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
// Chat names and kinds are remembered per chat_id: a chat.get per message
|
|
681
|
+
// would be a REST call on every event.
|
|
682
|
+
const chatOf = async (chatId, kind) => {
|
|
683
|
+
if (chatId === "")
|
|
684
|
+
return { title: "", kind: kind ?? "direct" };
|
|
685
|
+
const held = chats.get(chatId);
|
|
686
|
+
if (held !== undefined)
|
|
687
|
+
return held;
|
|
688
|
+
let title = "";
|
|
689
|
+
let mode = "";
|
|
690
|
+
try {
|
|
691
|
+
const body = await call("Feishu chat info", () => client.im.chat.get({ path: { chat_id: chatId } }), scrub);
|
|
692
|
+
title = String(body?.data?.name ?? "");
|
|
693
|
+
mode = String(body?.data?.chat_mode ?? body?.data?.chat_type ?? "");
|
|
694
|
+
}
|
|
695
|
+
catch (error) {
|
|
696
|
+
warn("ocean-crew im: feishu chat info failed: %s", error);
|
|
697
|
+
}
|
|
698
|
+
const chat = {
|
|
699
|
+
title: title || chatId,
|
|
700
|
+
kind: kind ?? (mode === "p2p" ? "direct" : mode === "" ? "direct" : "group"),
|
|
701
|
+
};
|
|
702
|
+
chats.set(chatId, chat);
|
|
703
|
+
return chat;
|
|
704
|
+
};
|
|
705
|
+
const onMessage = async (data) => {
|
|
706
|
+
if (stopped)
|
|
707
|
+
return;
|
|
708
|
+
try {
|
|
709
|
+
const event = data?.event ?? data ?? {};
|
|
710
|
+
const message = event.message ?? {};
|
|
711
|
+
const messageId = String(message.message_id ?? "");
|
|
712
|
+
const chatId = String(message.chat_id ?? "");
|
|
713
|
+
if (chatId === "" || messageId === "")
|
|
714
|
+
return;
|
|
715
|
+
if (seen.has(messageId) || delivering.has(messageId))
|
|
716
|
+
return;
|
|
717
|
+
delivering.add(messageId);
|
|
718
|
+
try {
|
|
719
|
+
const direct = message.chat_type === "p2p";
|
|
720
|
+
const mentions = Array.isArray(message.mentions) ? message.mentions : [];
|
|
721
|
+
// Until the bot's open_id is known, any mention has to count.
|
|
722
|
+
const mentioned = direct
|
|
723
|
+
? false
|
|
724
|
+
: botOpenId === ""
|
|
725
|
+
? mentions.length > 0
|
|
726
|
+
: mentions.some((mention) => String(mention?.id?.open_id ?? "") === botOpenId);
|
|
727
|
+
const content = parseJson(message.content);
|
|
728
|
+
const type = String(message.message_type ?? "");
|
|
729
|
+
const rendered = type === "text"
|
|
730
|
+
? withoutMentions(content.text)
|
|
731
|
+
: type === "post"
|
|
732
|
+
? postText(content)
|
|
733
|
+
: type === "merge_forward"
|
|
734
|
+
? mergeForwardText(content)
|
|
735
|
+
: type === "share_chat"
|
|
736
|
+
? shareChatText(content)
|
|
737
|
+
: type === "interactive"
|
|
738
|
+
? interactiveText(content)
|
|
739
|
+
: "";
|
|
740
|
+
const images = [];
|
|
741
|
+
const files = [];
|
|
742
|
+
let renderedText = rendered;
|
|
743
|
+
if (type === "merge_forward") {
|
|
744
|
+
for (const part of mergeForwardImages(content)) {
|
|
745
|
+
try {
|
|
746
|
+
const bytes = await messageResource(client, part.messageId, part.imageKey, "image");
|
|
747
|
+
images.push({ mediaType: imageMediaTypeOf(bytes), data: bytes.toString("base64") });
|
|
748
|
+
renderedText = renderedText.replace(/\[Image\]/, "");
|
|
749
|
+
}
|
|
750
|
+
catch (error) {
|
|
751
|
+
warn("ocean-crew im: feishu forwarded image download failed: %s", error);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
renderedText = renderedText.replace(/\n{3,}/g, "\n\n").trim();
|
|
755
|
+
}
|
|
756
|
+
if (type === "post") {
|
|
757
|
+
const keys = postImageKeys(content);
|
|
758
|
+
let read = 0;
|
|
759
|
+
for (const key of keys.slice(0, 4)) {
|
|
760
|
+
try {
|
|
761
|
+
const bytes = await messageResource(client, messageId, key, "image");
|
|
762
|
+
images.push({ mediaType: imageMediaTypeOf(bytes), data: bytes.toString("base64") });
|
|
763
|
+
read += 1;
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
warn("ocean-crew im: feishu post image download failed: %s", error);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
// The placeholder only stays for an image whose bytes could not be read.
|
|
770
|
+
if (read === keys.length)
|
|
771
|
+
renderedText = renderedText
|
|
772
|
+
.replace(/\[Image\]/g, "")
|
|
773
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
774
|
+
.trim();
|
|
775
|
+
}
|
|
776
|
+
if (type === "image" && typeof content.image_key === "string" && content.image_key !== "") {
|
|
777
|
+
try {
|
|
778
|
+
const bytes = await messageResource(client, messageId, content.image_key, "image");
|
|
779
|
+
images.push({ mediaType: imageMediaTypeOf(bytes), data: bytes.toString("base64") });
|
|
780
|
+
}
|
|
781
|
+
catch (error) {
|
|
782
|
+
warn("ocean-crew im: feishu image download failed: %s", error);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (type === "file" && typeof content.file_key === "string" && content.file_key !== "") {
|
|
786
|
+
try {
|
|
787
|
+
const bytes = await messageResource(client, messageId, content.file_key, "file", MAX_FILE_BYTES);
|
|
788
|
+
files.push({ name: String(content.file_name ?? content.file_key), data: bytes });
|
|
789
|
+
}
|
|
790
|
+
catch (error) {
|
|
791
|
+
warn("ocean-crew im: feishu file download failed: %s", error);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
// A voice note and a video are attachments inside the message body, and
|
|
795
|
+
// their bytes come from the same resource endpoint. The Bot gets the file
|
|
796
|
+
// plus one line saying what it is; a download that failed is named as such
|
|
797
|
+
// instead of the message being dropped silently.
|
|
798
|
+
let attachment = "";
|
|
799
|
+
if (type === "audio" || type === "media") {
|
|
800
|
+
const kind = type === "audio" ? "Voice message" : "Video";
|
|
801
|
+
const seconds = Math.round(Number(content.duration) / 1000);
|
|
802
|
+
const length = Number.isFinite(seconds) && seconds > 0 ? `, ${seconds}s` : "";
|
|
803
|
+
const key = String(content.file_key ?? "");
|
|
804
|
+
const fallback = type === "audio" ? `voice-${messageId}.opus` : `video-${messageId}.mp4`;
|
|
805
|
+
let read = false;
|
|
806
|
+
if (key !== "") {
|
|
807
|
+
try {
|
|
808
|
+
const bytes = await messageResource(client, messageId, key, "file", MAX_FILE_BYTES);
|
|
809
|
+
files.push({ name: String(content.file_name ?? fallback), data: bytes });
|
|
810
|
+
read = true;
|
|
811
|
+
}
|
|
812
|
+
catch (error) {
|
|
813
|
+
warn(`ocean-crew im: feishu ${type} download failed: %s`, error);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
attachment = read ? `[${kind}${length}]` : `[${kind}${length}: could not be read]`;
|
|
817
|
+
}
|
|
818
|
+
// A reply quotes the message it answers; without it the model cannot tell
|
|
819
|
+
// which earlier message this one refers to.
|
|
820
|
+
const quotedId = String(message.parent_id ?? message.upper_message_id ?? "");
|
|
821
|
+
const quoted = quotedId === "" ? "" : await quotedText(client, quotedId, scrub, warn);
|
|
822
|
+
const text = quoted === "" ? renderedText : `[Replying to: "${quoted.slice(0, 500)}"]\n\n${renderedText}`.trim();
|
|
823
|
+
const body = attachment === "" ? text : [text, attachment].filter(Boolean).join("\n\n").trim();
|
|
824
|
+
// A text that was nothing but a mention still matters: the host turns
|
|
825
|
+
// it into a pairing request. Other types without readable content are
|
|
826
|
+
// skipped rather than dispatched empty.
|
|
827
|
+
if (type !== "text" && body === "" && images.length === 0 && files.length === 0)
|
|
828
|
+
return;
|
|
829
|
+
const chat = await chatOf(chatId, direct ? "direct" : "group");
|
|
830
|
+
if (stopped)
|
|
831
|
+
return;
|
|
832
|
+
const sender = event.sender ?? {};
|
|
833
|
+
const senderId = String(sender.sender_id?.open_id ?? sender.sender_id?.user_id ?? "");
|
|
834
|
+
const senderLabel = String(sender.sender_name ?? "") || (await senderName(client, senderId, scrub));
|
|
835
|
+
await handlers.onMessage({
|
|
836
|
+
chat: { key: chatId, kind: chat.kind, title: chat.title },
|
|
837
|
+
sender: { id: senderId, name: senderLabel === "" ? senderId : senderLabel },
|
|
838
|
+
text: body,
|
|
839
|
+
images,
|
|
840
|
+
files,
|
|
841
|
+
mentioned,
|
|
842
|
+
messageId,
|
|
843
|
+
});
|
|
844
|
+
remember(messageId);
|
|
845
|
+
}
|
|
846
|
+
finally {
|
|
847
|
+
delivering.delete(messageId);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
catch (error) {
|
|
851
|
+
warn("ocean-crew im: feishu message failed: %s", error);
|
|
852
|
+
}
|
|
853
|
+
};
|
|
854
|
+
const onAction = async (data) => {
|
|
855
|
+
if (stopped)
|
|
856
|
+
return;
|
|
857
|
+
try {
|
|
858
|
+
const event = data?.event ?? data ?? {};
|
|
859
|
+
const context = event.context ?? {};
|
|
860
|
+
const chatId = String(context.open_chat_id ?? event.open_chat_id ?? "");
|
|
861
|
+
const messageId = String(context.open_message_id ?? event.open_message_id ?? "");
|
|
862
|
+
const action = event.action ?? {};
|
|
863
|
+
const value = action.value;
|
|
864
|
+
const buttonData = value !== null && typeof value === "object" ? (value.action ?? value.v ?? JSON.stringify(value)) : value;
|
|
865
|
+
const collected = action.form_value ?? action.formValue;
|
|
866
|
+
const form = collected !== null && typeof collected === "object" && !Array.isArray(collected)
|
|
867
|
+
? collected
|
|
868
|
+
: undefined;
|
|
869
|
+
const operator = event.operator ?? {};
|
|
870
|
+
const operatorId = String(operator.open_id ?? operator.user_id ?? "");
|
|
871
|
+
const chat = await chatOf(chatId);
|
|
872
|
+
if (stopped)
|
|
873
|
+
return;
|
|
874
|
+
await handlers.onAction({
|
|
875
|
+
chat: { key: chatId, kind: chat.kind, title: chat.title },
|
|
876
|
+
sender: { id: operatorId, name: String(operator.name ?? operatorId) },
|
|
877
|
+
data: String(buttonData ?? ""),
|
|
878
|
+
messageId,
|
|
879
|
+
...(form === undefined ? {} : { form }),
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
catch (error) {
|
|
883
|
+
warn("ocean-crew im: feishu card action failed: %s", error);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
const socket = new lark.WSClient({
|
|
887
|
+
appId,
|
|
888
|
+
appSecret,
|
|
889
|
+
domain: domainOf(lark, fields),
|
|
890
|
+
loggerLevel: lark.LoggerLevel.warn,
|
|
891
|
+
handshakeTimeoutMs: HANDSHAKE_TIMEOUT_MS,
|
|
892
|
+
autoReconnect: true,
|
|
893
|
+
onReady: () => {
|
|
894
|
+
if (!stopped)
|
|
895
|
+
handlers.onStatus({ state: "ready" });
|
|
896
|
+
},
|
|
897
|
+
onReconnecting: () => {
|
|
898
|
+
if (!stopped)
|
|
899
|
+
handlers.onStatus({ state: "connecting" });
|
|
900
|
+
},
|
|
901
|
+
onReconnected: () => {
|
|
902
|
+
if (!stopped)
|
|
903
|
+
handlers.onStatus({ state: "ready" });
|
|
904
|
+
},
|
|
905
|
+
onError: (error) => {
|
|
906
|
+
if (!stopped)
|
|
907
|
+
handlers.onStatus({ state: "error", error: scrub(reason(error)) });
|
|
908
|
+
},
|
|
909
|
+
wsConfig: { pingTimeout: PING_TIMEOUT_S },
|
|
910
|
+
});
|
|
911
|
+
handlers.onStatus({ state: "connecting" });
|
|
912
|
+
const boot = async () => {
|
|
913
|
+
// The bot identity only sharpens group @ detection; it must not hold the
|
|
914
|
+
// long connection back, and a mention counts until it arrives.
|
|
915
|
+
const identity = botInfo(client, scrub).then((bot) => bot.id, (error) => {
|
|
916
|
+
warn("ocean-crew im: feishu bot info failed: %s", error);
|
|
917
|
+
return "";
|
|
918
|
+
});
|
|
919
|
+
// Acknowledge the frame before dispatch: the SDK answers after the
|
|
920
|
+
// handler returns, and a slow host turn must not make Feishu redeliver.
|
|
921
|
+
const dispatcher = new lark.EventDispatcher({ loggerLevel: lark.LoggerLevel.warn }).register({
|
|
922
|
+
"im.message.receive_v1": (event) => {
|
|
923
|
+
void onMessage(event);
|
|
924
|
+
},
|
|
925
|
+
"card.action.trigger": (event) => {
|
|
926
|
+
void onAction(event);
|
|
927
|
+
},
|
|
928
|
+
});
|
|
929
|
+
const started = socket.start({ eventDispatcher: dispatcher }).catch((error) => {
|
|
930
|
+
if (!stopped)
|
|
931
|
+
handlers.onStatus({ state: "error", error: scrub(reason(error)) });
|
|
932
|
+
});
|
|
933
|
+
botOpenId =
|
|
934
|
+
(await withDeadline(identity, BOT_INFO_TIMEOUT_MS, () => env.log?.warn?.("ocean-crew im: feishu bot info timed out"))) ?? "";
|
|
935
|
+
await started;
|
|
936
|
+
};
|
|
937
|
+
void boot().catch((error) => {
|
|
938
|
+
if (!stopped)
|
|
939
|
+
handlers.onStatus({ state: "error", error: scrub(reason(error)) });
|
|
940
|
+
});
|
|
941
|
+
return {
|
|
942
|
+
// An answer threads under the message that asked for it, which is what makes a
|
|
943
|
+
// private chat read as a conversation rather than a wall of separate bubbles.
|
|
944
|
+
send: async (chat, { text, buttons, replyTo, media, card: asCard, title, form } = {}) => {
|
|
945
|
+
// No text at all means no empty bubble: the attachments go on their own.
|
|
946
|
+
const raw = String(text ?? "");
|
|
947
|
+
const chunks = raw.trim() === "" ? [] : chunkMarkdown(raw, TEXT_LIMIT);
|
|
948
|
+
const createBody = (type, body) => ({
|
|
949
|
+
params: { receive_id_type: "chat_id" },
|
|
950
|
+
data: {
|
|
951
|
+
receive_id: String(chat?.key ?? ""),
|
|
952
|
+
msg_type: type,
|
|
953
|
+
content: body,
|
|
954
|
+
// A retried send must not arrive twice.
|
|
955
|
+
uuid: randomUUID(),
|
|
956
|
+
},
|
|
957
|
+
});
|
|
958
|
+
let messageId;
|
|
959
|
+
let replyToId = typeof replyTo === "string" && replyTo !== "" ? replyTo : undefined;
|
|
960
|
+
// Attachments are uploaded first: a caption and its attachment then leave as
|
|
961
|
+
// one post message, and the upload failing loses nothing that was already said.
|
|
962
|
+
const uploadedImages = [];
|
|
963
|
+
const uploadedFiles = [];
|
|
964
|
+
for (const item of Array.isArray(media) ? media : []) {
|
|
965
|
+
const bytes = Buffer.from(item.data);
|
|
966
|
+
const name = String(item.name ?? "file");
|
|
967
|
+
if (item.kind === "image") {
|
|
968
|
+
const answer = await call("Feishu image upload", () => client.im.image.create({ data: { image_type: "message", image: bytes } }), scrub);
|
|
969
|
+
const key = String(answer?.data?.image_key ?? answer?.image_key ?? "");
|
|
970
|
+
if (key === "")
|
|
971
|
+
throw Object.assign(new Error(`Feishu returned no key for ${name}`), { permanent: true });
|
|
972
|
+
uploadedImages.push({
|
|
973
|
+
row: { tag: "img", image_key: key },
|
|
974
|
+
msgType: "image",
|
|
975
|
+
content: JSON.stringify({ image_key: key }),
|
|
976
|
+
});
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
const route = routeOf(name);
|
|
980
|
+
const answer = await call("Feishu file upload", () => client.im.file.create({ data: { file_type: route.upload, file_name: name, file: bytes } }), scrub);
|
|
981
|
+
const key = String(answer?.data?.file_key ?? answer?.file_key ?? "");
|
|
982
|
+
if (key === "")
|
|
983
|
+
throw Object.assign(new Error(`Feishu returned no key for ${name}`), { permanent: true });
|
|
984
|
+
uploadedFiles.push({
|
|
985
|
+
row: { tag: "media", file_key: key, file_name: name },
|
|
986
|
+
msgType: route.msgType,
|
|
987
|
+
content: JSON.stringify({ file_key: key }),
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
// What is left after the caption: no text, a button card, or a plain-text
|
|
991
|
+
// fallback leaves the attachment as its own message.
|
|
992
|
+
const sendAttachments = async () => {
|
|
993
|
+
for (const held of [...uploadedImages.splice(0), ...uploadedFiles.splice(0)]) {
|
|
994
|
+
const sent = await call("Feishu send", () => client.im.message.create(createBody(held.msgType, held.content)), scrub);
|
|
995
|
+
messageId = String(sent?.data?.message_id ?? messageId ?? "");
|
|
996
|
+
}
|
|
997
|
+
};
|
|
998
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
999
|
+
// A form is an interactive card as well: its submit button reports the answer.
|
|
1000
|
+
const interactive = (buttons !== undefined || form !== undefined) && index === chunks.length - 1;
|
|
1001
|
+
// A Bot's answer reads as a card on this platform; only the first part
|
|
1002
|
+
// carries the header, so a split answer is not a stack of headers.
|
|
1003
|
+
const replyCardMode = asCard === true && !interactive;
|
|
1004
|
+
const markup = MARKDOWN_HINT.test(chunk);
|
|
1005
|
+
// Images ride on the last part of the answer, as a caption with its media,
|
|
1006
|
+
// unless a button card has to be that part. Other files are their own
|
|
1007
|
+
// message: a post's media element does not accept every upload type.
|
|
1008
|
+
const caption = !interactive && index === chunks.length - 1 && uploadedImages.length > 0
|
|
1009
|
+
? uploadedImages.splice(0)
|
|
1010
|
+
: [];
|
|
1011
|
+
const msgType = interactive || replyCardMode ? "interactive" : caption.length > 0 ? "post" : markup ? "post" : "text";
|
|
1012
|
+
const content = interactive
|
|
1013
|
+
? card(chunk, buttons, title, form)
|
|
1014
|
+
: replyCardMode
|
|
1015
|
+
? replyCard(chunk, index === 0 ? title : undefined)
|
|
1016
|
+
: caption.length > 0
|
|
1017
|
+
? postWith(chunk, caption.map((held) => held.row))
|
|
1018
|
+
: msgType === "post"
|
|
1019
|
+
? post(chunk)
|
|
1020
|
+
: JSON.stringify({ text: toPlain(chunk) });
|
|
1021
|
+
const plain = msgType === "interactive" ? msgType : "text";
|
|
1022
|
+
const plainContent = msgType === "interactive" ? content : JSON.stringify({ text: toPlain(chunk) });
|
|
1023
|
+
const create = () => call("Feishu send", () => client.im.message.create(createBody(msgType, content)), scrub).catch(async (failure) => {
|
|
1024
|
+
if (msgType === "interactive" && !interactive) {
|
|
1025
|
+
// A card refused for its content falls back to plain text below.
|
|
1026
|
+
env.log?.warn?.("ocean-crew im: feishu rejected the reply card; sending plain text");
|
|
1027
|
+
return call("Feishu send", () => client.im.message.create(createBody("text", JSON.stringify({ text: toPlain(chunk) }))), scrub);
|
|
1028
|
+
}
|
|
1029
|
+
if (msgType === "interactive" || !POST_INVALID.test(String(failure?.message ?? ""))) {
|
|
1030
|
+
throw failure;
|
|
1031
|
+
}
|
|
1032
|
+
env.log?.warn?.("ocean-crew im: feishu rejected the post; sending plain text");
|
|
1033
|
+
// The caption could not carry them: they follow as their own messages.
|
|
1034
|
+
if (caption.length > 0)
|
|
1035
|
+
uploadedImages.unshift(...caption);
|
|
1036
|
+
return call("Feishu send", () => client.im.message.create(createBody(plain, plainContent)), scrub);
|
|
1037
|
+
});
|
|
1038
|
+
let body;
|
|
1039
|
+
if (replyToId === undefined)
|
|
1040
|
+
body = await create();
|
|
1041
|
+
else {
|
|
1042
|
+
try {
|
|
1043
|
+
body = await call("Feishu send", () => client.im.message.reply({
|
|
1044
|
+
path: { message_id: replyToId },
|
|
1045
|
+
data: { msg_type: msgType, content, uuid: randomUUID() },
|
|
1046
|
+
}), scrub);
|
|
1047
|
+
}
|
|
1048
|
+
catch (failure) {
|
|
1049
|
+
// The message being answered is gone (recalled, or from an expired context).
|
|
1050
|
+
// That code is otherwise classified as a permanent send failure, so it is
|
|
1051
|
+
// handled here: post the answer on its own instead of losing it.
|
|
1052
|
+
if (!isReplyGone(failure))
|
|
1053
|
+
throw failure;
|
|
1054
|
+
env.log?.warn?.("ocean-crew im: feishu reply target is gone; sending plainly");
|
|
1055
|
+
body = await create();
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
messageId = String(body?.data?.message_id ?? messageId ?? "");
|
|
1059
|
+
// Only the first bubble threads under the question.
|
|
1060
|
+
replyToId = undefined;
|
|
1061
|
+
}
|
|
1062
|
+
await sendAttachments();
|
|
1063
|
+
return { messageId };
|
|
1064
|
+
},
|
|
1065
|
+
// Which endpoint settles a message depends on how it was sent: a card is patched
|
|
1066
|
+
// (the only endpoint that accepts one), a post or text is updated in place. Using
|
|
1067
|
+
// patch for everything would fail on any message that is not an interactive card.
|
|
1068
|
+
edit: async (_chat, messageId, { text, buttons } = {}) => {
|
|
1069
|
+
const body = String(text ?? "").slice(0, TEXT_LIMIT);
|
|
1070
|
+
if (buttons !== undefined && buttons.length > 0) {
|
|
1071
|
+
await call("Feishu edit", () => client.im.message.patch({
|
|
1072
|
+
path: { message_id: String(messageId ?? "") },
|
|
1073
|
+
data: { content: card(body, buttons) },
|
|
1074
|
+
}), scrub);
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
try {
|
|
1078
|
+
await call("Feishu edit", () => client.im.message.patch({
|
|
1079
|
+
path: { message_id: String(messageId ?? "") },
|
|
1080
|
+
data: { content: card(body, []) },
|
|
1081
|
+
}), scrub);
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
catch (failure) {
|
|
1085
|
+
// A message sent before replies became cards is updated in place instead.
|
|
1086
|
+
env.log?.warn?.("ocean-crew im: feishu card patch failed; updating the message instead");
|
|
1087
|
+
}
|
|
1088
|
+
const markup = MARKDOWN_HINT.test(body);
|
|
1089
|
+
await call("Feishu update", () => client.im.message.update({
|
|
1090
|
+
path: { message_id: String(messageId ?? "") },
|
|
1091
|
+
data: {
|
|
1092
|
+
msg_type: markup ? "post" : "text",
|
|
1093
|
+
content: markup ? post(body) : JSON.stringify({ text: toPlain(body) }),
|
|
1094
|
+
},
|
|
1095
|
+
}), scrub);
|
|
1096
|
+
},
|
|
1097
|
+
// Status reactions are best effort: the host marks the message that asked
|
|
1098
|
+
// for the work, and a refused reaction must never hold up the reply.
|
|
1099
|
+
addReaction: async (_chat, messageId, emoji) => {
|
|
1100
|
+
const body = await call("Feishu reaction", () => client.im.messageReaction.create({
|
|
1101
|
+
path: { message_id: String(messageId ?? "") },
|
|
1102
|
+
data: { reaction_type: { emoji_type: String(emoji ?? "") } },
|
|
1103
|
+
}), scrub);
|
|
1104
|
+
const id = String(body?.data?.reaction_id ?? "");
|
|
1105
|
+
return id === "" ? undefined : id;
|
|
1106
|
+
},
|
|
1107
|
+
removeReaction: async (_chat, messageId, reactionId) => {
|
|
1108
|
+
await call("Feishu reaction remove", () => client.im.messageReaction.delete({
|
|
1109
|
+
path: { message_id: String(messageId ?? ""), reaction_id: String(reactionId ?? "") },
|
|
1110
|
+
}), scrub);
|
|
1111
|
+
},
|
|
1112
|
+
stop: () => {
|
|
1113
|
+
stopped = true;
|
|
1114
|
+
try {
|
|
1115
|
+
socket.close({ force: true });
|
|
1116
|
+
}
|
|
1117
|
+
catch {
|
|
1118
|
+
/* already gone */
|
|
1119
|
+
}
|
|
1120
|
+
},
|
|
1121
|
+
};
|
|
1122
|
+
},
|
|
1123
|
+
};
|
|
1124
|
+
// A reply whose target no longer exists: Feishu says so with one of these codes.
|
|
1125
|
+
// Feishu says a post payload was rejected with this message; the same content as text
|
|
1126
|
+
// usually goes through, and a plain answer beats no answer.
|
|
1127
|
+
const POST_INVALID = /content format of the post type is incorrect/i;
|
|
1128
|
+
const REPLY_GONE = new Set([230011, 231003]);
|
|
1129
|
+
const isReplyGone = (failure) => {
|
|
1130
|
+
// The adapter's own errors carry the Feishu code on `platformCode`.
|
|
1131
|
+
const code = Number(failure?.platformCode ?? failure?.code ?? failure?.response?.data?.code);
|
|
1132
|
+
return REPLY_GONE.has(code);
|
|
1133
|
+
};
|
|
1134
|
+
export default feishu;
|