@openclaw/feishu 2026.7.2-beta.3 → 2026.7.2-beta.5
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/README.md +1 -1
- package/dist/{accounts-BDoGHJDk.js → accounts-CKhCa76b.js} +2 -19
- package/dist/api.js +65 -43
- package/dist/{app-registration-BzkyrVZu.js → app-registration-cN1bVV6s.js} +5 -5
- package/dist/{channel-BdnXYU6g.js → channel-CBNICmK9.js} +37 -75
- package/dist/channel-plugin-api.js +1 -1
- package/dist/{channel.runtime-CVIzo2dV.js → channel.runtime-CSlJVqy4.js} +7 -7
- package/dist/{client-87BmeMpj.js → client-Dee7cKsS.js} +62 -1
- package/dist/contract-api.js +2 -2
- package/dist/doctor-contract-BiD9tyIv.js +102 -0
- package/dist/doctor-contract-api.js +1 -1
- package/dist/{drive-BHv8WW9i.js → drive-DG6pKTPE.js} +23 -20
- package/dist/{send-DcrXbqqA.js → media-DOwcLJ1j.js} +1050 -1021
- package/dist/{monitor-BVQf7-Bl.js → monitor-DEHJlyWW.js} +6 -5
- package/dist/{monitor.account-Blbf2T6J.js → monitor.account-DEHl8Non.js} +1556 -592
- package/dist/monitor.startup-CSUPT_U1.js +143 -0
- package/dist/{probe-BgboTHIn.js → probe-Za1kgUvx.js} +70 -10
- package/dist/runtime-api.js +1 -2
- package/dist/{security-audit-BIeA3W3Q.js → security-audit-D7WK_BHh.js} +1 -1
- package/dist/{security-audit-shared-BIHeF-S_.js → security-audit-shared-BgpY7AiJ.js} +6 -11
- package/dist/security-contract-api.js +1 -1
- package/dist/{send-result-DfE5Fhz6.js → send-result-Bcofg0Vv.js} +1 -1
- package/dist/session-binding-contract-api.js +1 -1
- package/dist/setup-api.js +1 -1
- package/dist/{subagent-hooks-BKTOxB-T.js → subagent-hooks-DL2SC5zX.js} +1 -1
- package/dist/subagent-hooks-api.js +1 -1
- package/dist/{thread-bindings-V0bwk0A1.js → thread-bindings-Dqs_A0du.js} +2 -1
- package/node_modules/@larksuiteoapi/node-sdk/README.md +13 -0
- package/node_modules/@larksuiteoapi/node-sdk/README.zh.md +12 -0
- package/node_modules/@larksuiteoapi/node-sdk/es/index.js +8950 -3084
- package/node_modules/@larksuiteoapi/node-sdk/lib/index.js +8951 -3083
- package/node_modules/@larksuiteoapi/node-sdk/package.json +1 -1
- package/node_modules/@larksuiteoapi/node-sdk/types/index.d.ts +12522 -698
- package/node_modules/@protobufjs/utf8/CHANGELOG.md +8 -0
- package/node_modules/@protobufjs/utf8/index.js +29 -18
- package/node_modules/@protobufjs/utf8/package.json +2 -2
- package/node_modules/@protobufjs/utf8/tests/index.js +5 -0
- package/node_modules/@types/node/README.md +1 -1
- package/node_modules/@types/node/fs/promises.d.ts +16 -6
- package/node_modules/@types/node/package.json +2 -2
- package/node_modules/agent-base/README.md +145 -0
- package/node_modules/agent-base/dist/src/index.d.ts +78 -0
- package/node_modules/agent-base/dist/src/index.js +203 -0
- package/node_modules/agent-base/dist/src/index.js.map +1 -0
- package/node_modules/agent-base/dist/src/promisify.d.ts +4 -0
- package/node_modules/agent-base/dist/src/promisify.js +18 -0
- package/node_modules/agent-base/dist/src/promisify.js.map +1 -0
- package/node_modules/agent-base/package.json +64 -0
- package/node_modules/agent-base/src/index.ts +345 -0
- package/node_modules/agent-base/src/promisify.ts +33 -0
- package/node_modules/axios/CHANGELOG.md +197 -1
- package/node_modules/axios/README.md +424 -256
- package/node_modules/axios/dist/axios.js +589 -204
- package/node_modules/axios/dist/axios.min.js +3 -3
- package/node_modules/axios/dist/axios.min.js.map +1 -1
- package/node_modules/axios/dist/browser/axios.cjs +630 -185
- package/node_modules/axios/dist/esm/axios.js +630 -185
- package/node_modules/axios/dist/esm/axios.min.js +2 -2
- package/node_modules/axios/dist/esm/axios.min.js.map +1 -1
- package/node_modules/axios/dist/node/axios.cjs +949 -301
- package/node_modules/axios/index.d.cts +28 -5
- package/node_modules/axios/index.d.ts +24 -3
- package/node_modules/axios/lib/adapters/adapters.js +1 -1
- package/node_modules/axios/lib/adapters/fetch.js +223 -49
- package/node_modules/axios/lib/adapters/http.js +408 -193
- package/node_modules/axios/lib/adapters/xhr.js +3 -1
- package/node_modules/axios/lib/core/Axios.js +4 -2
- package/node_modules/axios/lib/core/AxiosError.js +13 -1
- package/node_modules/axios/lib/core/AxiosHeaders.js +13 -42
- package/node_modules/axios/lib/core/buildFullPath.js +29 -1
- package/node_modules/axios/lib/core/mergeConfig.js +35 -0
- package/node_modules/axios/lib/defaults/transitional.js +2 -0
- package/node_modules/axios/lib/env/data.js +1 -1
- package/node_modules/axios/lib/helpers/AxiosURLSearchParams.js +1 -3
- package/node_modules/axios/lib/helpers/Http2Sessions.js +119 -0
- package/node_modules/axios/lib/helpers/buildURL.js +7 -4
- package/node_modules/axios/lib/helpers/composeSignals.js +48 -47
- package/node_modules/axios/lib/helpers/cookies.js +5 -1
- package/node_modules/axios/lib/helpers/estimateDataURLDecodedBytes.js +16 -11
- package/node_modules/axios/lib/helpers/formDataToJSON.js +26 -4
- package/node_modules/axios/lib/helpers/formDataToStream.js +2 -2
- package/node_modules/axios/lib/helpers/fromDataURI.js +20 -5
- package/node_modules/axios/lib/helpers/progressEventReducer.js +3 -0
- package/node_modules/axios/lib/helpers/resolveConfig.js +26 -13
- package/node_modules/axios/lib/helpers/sanitizeHeaderValue.js +60 -0
- package/node_modules/axios/lib/helpers/shouldBypassProxy.js +33 -1
- package/node_modules/axios/lib/helpers/toFormData.js +48 -12
- package/node_modules/axios/lib/helpers/validator.js +1 -1
- package/node_modules/axios/lib/utils.js +105 -19
- package/node_modules/axios/package.json +31 -13
- package/node_modules/https-proxy-agent/README.md +137 -0
- package/node_modules/https-proxy-agent/dist/agent.d.ts +30 -0
- package/node_modules/https-proxy-agent/dist/agent.js +177 -0
- package/node_modules/https-proxy-agent/dist/agent.js.map +1 -0
- package/node_modules/https-proxy-agent/dist/index.d.ts +23 -0
- package/node_modules/https-proxy-agent/dist/index.js +14 -0
- package/node_modules/https-proxy-agent/dist/index.js.map +1 -0
- package/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts +7 -0
- package/node_modules/https-proxy-agent/dist/parse-proxy-response.js +66 -0
- package/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map +1 -0
- package/node_modules/https-proxy-agent/package.json +56 -0
- package/node_modules/protobufjs/dist/light/protobuf.js +145 -188
- package/node_modules/protobufjs/dist/light/protobuf.js.map +1 -1
- package/node_modules/protobufjs/dist/light/protobuf.min.js +3 -3
- package/node_modules/protobufjs/dist/light/protobuf.min.js.map +1 -1
- package/node_modules/protobufjs/dist/minimal/protobuf.js +33 -76
- package/node_modules/protobufjs/dist/minimal/protobuf.js.map +1 -1
- package/node_modules/protobufjs/dist/minimal/protobuf.min.js +3 -3
- package/node_modules/protobufjs/dist/minimal/protobuf.min.js.map +1 -1
- package/node_modules/protobufjs/dist/protobuf.js +168 -208
- package/node_modules/protobufjs/dist/protobuf.js.map +1 -1
- package/node_modules/protobufjs/dist/protobuf.min.js +3 -3
- package/node_modules/protobufjs/dist/protobuf.min.js.map +1 -1
- package/node_modules/protobufjs/index.d.ts +0 -8
- package/node_modules/protobufjs/package.json +2 -3
- package/node_modules/protobufjs/src/parse.js +3 -0
- package/node_modules/protobufjs/src/util/minimal.js +0 -3
- package/node_modules/qs/CHANGELOG.md +11 -0
- package/node_modules/qs/dist/qs.js +17 -17
- package/node_modules/qs/lib/parse.js +19 -8
- package/node_modules/qs/lib/utils.js +47 -8
- package/node_modules/qs/package.json +6 -5
- package/node_modules/qs/test/parse.js +230 -0
- package/node_modules/qs/test/utils.js +194 -0
- package/node_modules/typebox/build/compile/validator.d.mts +1 -4
- package/node_modules/typebox/build/guard/guard.d.mts +1 -1
- package/node_modules/typebox/build/guard/guard.mjs +5 -2
- package/node_modules/typebox/build/guard/string.mjs +16 -4
- package/node_modules/typebox/build/schema/engine/_functions.mjs +34 -15
- package/node_modules/typebox/build/type/action/readonly_object.d.mts +5 -0
- package/node_modules/typebox/build/type/action/readonly_object.mjs +8 -0
- package/node_modules/typebox/build/typebox.d.mts +1 -1
- package/node_modules/typebox/build/typebox.mjs +1 -1
- package/node_modules/typebox/package.json +1 -1
- package/node_modules/typebox/readme.md +29 -32
- package/node_modules/ws/lib/receiver.js +15 -32
- package/node_modules/ws/lib/websocket-server.js +4 -4
- package/node_modules/ws/lib/websocket.js +4 -4
- package/node_modules/ws/package.json +5 -1
- package/openclaw.plugin.json +2 -16
- package/package.json +20 -8
- package/dist/doctor-contract-DXH5hux1.js +0 -97
- package/dist/monitor.startup-Cy8NPGAX.js +0 -43
- package/node_modules/@protobufjs/inquire/CHANGELOG.md +0 -8
- package/node_modules/@protobufjs/inquire/LICENSE +0 -26
- package/node_modules/@protobufjs/inquire/README.md +0 -13
- package/node_modules/@protobufjs/inquire/index.d.ts +0 -10
- package/node_modules/@protobufjs/inquire/index.js +0 -38
- package/node_modules/@protobufjs/inquire/package.json +0 -21
- package/node_modules/@protobufjs/inquire/tests/data/array.js +0 -1
- package/node_modules/@protobufjs/inquire/tests/data/emptyArray.js +0 -1
- package/node_modules/@protobufjs/inquire/tests/data/emptyObject.js +0 -1
- package/node_modules/@protobufjs/inquire/tests/data/object.js +0 -1
- package/node_modules/@protobufjs/inquire/tests/index.js +0 -20
- package/node_modules/axios/dist/axios.js.map +0 -1
- package/node_modules/axios/dist/browser/axios.cjs.map +0 -1
- package/node_modules/axios/dist/esm/axios.js.map +0 -1
- package/node_modules/axios/dist/node/axios.cjs.map +0 -1
- package/npm-shrinkwrap.json +0 -1354
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { d as isRecord$1, h as requestFeishuApi, s as resolveFeishuRuntimeAccount } from "./accounts-
|
|
1
|
+
import { d as isRecord$1, h as requestFeishuApi, s as resolveFeishuRuntimeAccount } from "./accounts-CKhCa76b.js";
|
|
2
2
|
import { i as resolveReceiveIdType, r as normalizeFeishuTarget } from "./targets-BUjQ1TcA.js";
|
|
3
|
-
import { c as assertFeishuPostWithinEnvelope, f as materializeFeishuPostMarkdownSoftBreaks, i as toFeishuSendResult, l as buildFeishuPostMessageContent, o as resolveFeishuCardTemplate, r as resolveFeishuReceiptKind, t as assertFeishuMessageApiSuccess } from "./send-result-
|
|
4
|
-
import { r as createFeishuClient } from "./client-
|
|
3
|
+
import { c as assertFeishuPostWithinEnvelope, f as materializeFeishuPostMarkdownSoftBreaks, i as toFeishuSendResult, l as buildFeishuPostMessageContent, o as resolveFeishuCardTemplate, r as resolveFeishuReceiptKind, t as assertFeishuMessageApiSuccess } from "./send-result-Bcofg0Vv.js";
|
|
4
|
+
import { r as createFeishuClient } from "./client-Dee7cKsS.js";
|
|
5
5
|
import { t as getFeishuRuntime } from "./runtime-C5JxBWZp.js";
|
|
6
6
|
import { parseStrictNonNegativeInteger } from "openclaw/plugin-sdk/number-runtime";
|
|
7
7
|
import { isRecord, normalizeLowercaseStringOrEmpty } from "openclaw/plugin-sdk/string-coerce-runtime";
|
|
8
8
|
import { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";
|
|
9
9
|
import fs from "node:fs";
|
|
10
10
|
import path from "node:path";
|
|
11
|
+
import { PlatformMessageNotDispatchedError } from "openclaw/plugin-sdk/error-runtime";
|
|
11
12
|
import { MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS, runFfmpeg, runFfprobe } from "openclaw/plugin-sdk/media-runtime";
|
|
12
13
|
import { isBlockedHostnameOrIp, resolvePinnedHostnameWithPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
13
14
|
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
|
|
@@ -145,1173 +146,1201 @@ function resolveFeishuSendTarget(params) {
|
|
|
145
146
|
};
|
|
146
147
|
}
|
|
147
148
|
//#endregion
|
|
148
|
-
//#region extensions/feishu/src/
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const FEISHU_VOICE_SAMPLE_RATE_HZ = 48e3;
|
|
152
|
-
const FEISHU_VOICE_BITRATE = "64k";
|
|
153
|
-
const FEISHU_TRANSCODABLE_AUDIO_EXTS = /* @__PURE__ */ new Set([
|
|
154
|
-
".aac",
|
|
155
|
-
".aiff",
|
|
156
|
-
".alac",
|
|
157
|
-
".amr",
|
|
158
|
-
".caf",
|
|
159
|
-
".flac",
|
|
160
|
-
".m4a",
|
|
161
|
-
".mp3",
|
|
162
|
-
".oga",
|
|
163
|
-
".wav",
|
|
164
|
-
".webm",
|
|
165
|
-
".wma"
|
|
166
|
-
]);
|
|
167
|
-
function createConfiguredFeishuMediaClient(params) {
|
|
168
|
-
const account = resolveFeishuRuntimeAccount({
|
|
169
|
-
cfg: params.cfg,
|
|
170
|
-
accountId: params.accountId
|
|
171
|
-
});
|
|
172
|
-
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
173
|
-
return {
|
|
174
|
-
account,
|
|
175
|
-
client: createFeishuClient({
|
|
176
|
-
...account,
|
|
177
|
-
httpTimeoutMs: FEISHU_MEDIA_HTTP_TIMEOUT_MS
|
|
178
|
-
})
|
|
179
|
-
};
|
|
149
|
+
//#region extensions/feishu/src/types.ts
|
|
150
|
+
function isFeishuGroupChatType(chatType) {
|
|
151
|
+
return chatType === "group" || chatType === "topic_group";
|
|
180
152
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region extensions/feishu/src/mention.ts
|
|
155
|
+
function isFeishuBroadcastMention(mention) {
|
|
156
|
+
const normalizedKey = mention.key?.trim().toLowerCase();
|
|
157
|
+
if (normalizedKey === "@all" || normalizedKey === "@_all") return true;
|
|
158
|
+
return [
|
|
159
|
+
mention.id?.open_id,
|
|
160
|
+
mention.id?.user_id,
|
|
161
|
+
mention.id?.union_id
|
|
162
|
+
].some((id) => id?.trim().toLowerCase() === "all");
|
|
185
163
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
164
|
+
/**
|
|
165
|
+
* Extract mention targets from message event (excluding the bot itself)
|
|
166
|
+
*/
|
|
167
|
+
function extractMentionTargets(event, botOpenId) {
|
|
168
|
+
return (event.message.mentions ?? []).filter((m) => {
|
|
169
|
+
if (isFeishuBroadcastMention(m)) return false;
|
|
170
|
+
if (m.id.open_id === botOpenId) return false;
|
|
171
|
+
return Boolean(m.id.open_id);
|
|
172
|
+
}).map((m) => ({
|
|
173
|
+
openId: m.id.open_id,
|
|
174
|
+
name: m.name,
|
|
175
|
+
key: m.key
|
|
176
|
+
}));
|
|
193
177
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
178
|
+
/**
|
|
179
|
+
* Check if message is a mention forward request
|
|
180
|
+
* Rules:
|
|
181
|
+
* - Group: message mentions bot + at least one other user
|
|
182
|
+
* - DM: message mentions any user (no need to mention bot)
|
|
183
|
+
*/
|
|
184
|
+
function isMentionForwardRequest(event, botOpenId) {
|
|
185
|
+
const mentions = event.message.mentions ?? [];
|
|
186
|
+
if (mentions.length === 0) return false;
|
|
187
|
+
const normalizedBotOpenId = botOpenId?.trim();
|
|
188
|
+
if (!normalizedBotOpenId) return false;
|
|
189
|
+
const isDirectMessage = !isFeishuGroupChatType(event.message.chat_type);
|
|
190
|
+
const userMentions = mentions.filter((m) => !isFeishuBroadcastMention(m));
|
|
191
|
+
const hasOtherMention = userMentions.some((m) => m.id.open_id !== normalizedBotOpenId);
|
|
192
|
+
if (isDirectMessage) return hasOtherMention;
|
|
193
|
+
return userMentions.some((m) => m.id.open_id === normalizedBotOpenId) && hasOtherMention;
|
|
204
194
|
}
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
if (typeof status === "number") return status;
|
|
211
|
-
}
|
|
212
|
-
const status = error.status;
|
|
213
|
-
return typeof status === "number" ? status : void 0;
|
|
195
|
+
/**
|
|
196
|
+
* Format @mention for card message (lark_md)
|
|
197
|
+
*/
|
|
198
|
+
function formatMentionForCard(target) {
|
|
199
|
+
return `<at id=${target.openId}></at>`;
|
|
214
200
|
}
|
|
215
|
-
|
|
216
|
-
|
|
201
|
+
/**
|
|
202
|
+
* Build card content with @mentions (Markdown format)
|
|
203
|
+
*/
|
|
204
|
+
function buildMentionedCardContent(targets, message) {
|
|
205
|
+
if (targets.length === 0) return message;
|
|
206
|
+
return `${targets.map((t) => formatMentionForCard(t)).join(" ")} ${message}`;
|
|
217
207
|
}
|
|
218
|
-
|
|
219
|
-
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region extensions/feishu/src/post.ts
|
|
210
|
+
const FALLBACK_POST_TEXT = "[Rich text message]";
|
|
211
|
+
const MARKDOWN_SPECIAL_CHARS = /([\\`*_{}[\]()#+\-!|>~])/g;
|
|
212
|
+
function toStringOrEmpty(value) {
|
|
213
|
+
return typeof value === "string" ? value : "";
|
|
220
214
|
}
|
|
221
|
-
function
|
|
222
|
-
|
|
223
|
-
if (recovered !== value && !recovered.includes("�") && containsEastAsianScript(recovered)) return recovered;
|
|
224
|
-
return value;
|
|
215
|
+
function escapeMarkdownText(text) {
|
|
216
|
+
return text.replace(MARKDOWN_SPECIAL_CHARS, "\\$1");
|
|
225
217
|
}
|
|
226
|
-
function
|
|
227
|
-
|
|
228
|
-
if (utf8Match?.[1]) try {
|
|
229
|
-
return decodeURIComponent(utf8Match[1].trim().replace(/^"(.*)"$/, "$1"));
|
|
230
|
-
} catch {
|
|
231
|
-
return utf8Match[1].trim().replace(/^"(.*)"$/, "$1");
|
|
232
|
-
}
|
|
233
|
-
const plainFileName = value.match(/filename="?([^";]+)"?/i)?.[1]?.trim();
|
|
234
|
-
return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : void 0;
|
|
218
|
+
function toBoolean(value) {
|
|
219
|
+
return value === true || value === 1 || value === "true";
|
|
235
220
|
}
|
|
236
|
-
function
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const contentType = readHeaderValue(headers, "content-type") ?? responseWithOptionalFields.contentType ?? responseWithOptionalFields.mime_type ?? responseWithOptionalFields.data?.contentType ?? responseWithOptionalFields.data?.mime_type;
|
|
240
|
-
const disposition = readHeaderValue(headers, "content-disposition");
|
|
241
|
-
return {
|
|
242
|
-
contentType,
|
|
243
|
-
fileName: (disposition ? decodeDispositionFileName(disposition) : void 0) ?? responseWithOptionalFields.file_name ?? responseWithOptionalFields.fileName ?? responseWithOptionalFields.data?.file_name ?? responseWithOptionalFields.data?.fileName
|
|
244
|
-
};
|
|
221
|
+
function isStyleEnabled(style, key) {
|
|
222
|
+
if (!style) return false;
|
|
223
|
+
return toBoolean(style[key]);
|
|
245
224
|
}
|
|
246
|
-
function
|
|
247
|
-
|
|
225
|
+
function wrapInlineCode(text) {
|
|
226
|
+
const maxRun = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
|
|
227
|
+
const fence = "`".repeat(maxRun + 1);
|
|
228
|
+
return `${fence}${text.startsWith("`") || text.endsWith("`") ? ` ${text} ` : text}${fence}`;
|
|
248
229
|
}
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
if (Buffer.isBuffer(response)) return saveMediaBuffer(response, contentType, "inbound", maxBytes, fileName);
|
|
252
|
-
if (response instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(response), contentType, "inbound", maxBytes, fileName);
|
|
253
|
-
const responseWithOptionalFields = response;
|
|
254
|
-
if (responseWithOptionalFields.code !== void 0 && responseWithOptionalFields.code !== 0) throw new Error(`${params.errorPrefix}: ${responseWithOptionalFields.msg || `code ${responseWithOptionalFields.code}`}`);
|
|
255
|
-
if (responseWithOptionalFields.data && Buffer.isBuffer(responseWithOptionalFields.data)) return saveMediaBuffer(responseWithOptionalFields.data, contentType, "inbound", maxBytes, fileName);
|
|
256
|
-
if (responseWithOptionalFields.data instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(responseWithOptionalFields.data), contentType, "inbound", maxBytes, fileName);
|
|
257
|
-
const save = (stream, ct = contentType, mb = maxBytes, fn = fileName) => saveMediaStreamWithIdleTimeout(stream, ct, mb, fn, FEISHU_MEDIA_HTTP_TIMEOUT_MS);
|
|
258
|
-
if (typeof response.getReadableStream === "function") return save(response.getReadableStream());
|
|
259
|
-
if (typeof response.writeFile === "function") return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
|
|
260
|
-
await response.writeFile(tmpPath);
|
|
261
|
-
if ((await fs.promises.stat(tmpPath)).size > maxBytes) throw mediaLimitError(maxBytes);
|
|
262
|
-
return await save(fs.createReadStream(tmpPath));
|
|
263
|
-
});
|
|
264
|
-
if (responseWithOptionalFields[Symbol.asyncIterator]) return save(responseWithOptionalFields);
|
|
265
|
-
if (response instanceof Readable) return save(response);
|
|
266
|
-
const keys = Object.keys(response);
|
|
267
|
-
throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${keys.join(", ")}]`);
|
|
230
|
+
function sanitizeFenceLanguage(language) {
|
|
231
|
+
return language.trim().replace(/[^A-Za-z0-9_+#.-]/g, "");
|
|
268
232
|
}
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
response,
|
|
281
|
-
tmpDirPrefix: "openclaw-feishu-resource-",
|
|
282
|
-
errorPrefix: "Feishu message resource download failed",
|
|
283
|
-
maxBytes: params.maxBytes,
|
|
284
|
-
contentType: meta.contentType,
|
|
285
|
-
fileName: meta.fileName ?? (params.originalFilename ? recoverUtf8FileNameFromLatin1Header(params.originalFilename) : void 0)
|
|
286
|
-
}),
|
|
287
|
-
...meta
|
|
288
|
-
};
|
|
233
|
+
function renderTextElement(element) {
|
|
234
|
+
const text = toStringOrEmpty(element.text);
|
|
235
|
+
const style = isRecord$1(element.style) ? element.style : void 0;
|
|
236
|
+
if (isStyleEnabled(style, "code")) return wrapInlineCode(text);
|
|
237
|
+
let rendered = escapeMarkdownText(text);
|
|
238
|
+
if (!rendered) return "";
|
|
239
|
+
if (isStyleEnabled(style, "bold")) rendered = `**${rendered}**`;
|
|
240
|
+
if (isStyleEnabled(style, "italic")) rendered = `*${rendered}*`;
|
|
241
|
+
if (isStyleEnabled(style, "underline")) rendered = `<u>${rendered}</u>`;
|
|
242
|
+
if (isStyleEnabled(style, "strikethrough") || isStyleEnabled(style, "line_through") || isStyleEnabled(style, "lineThrough")) rendered = `~~${rendered}~~`;
|
|
243
|
+
return rendered;
|
|
289
244
|
}
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
if (!
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
accountId
|
|
297
|
-
});
|
|
298
|
-
try {
|
|
299
|
-
return await saveMessageResourceWithType({
|
|
300
|
-
client,
|
|
301
|
-
messageId,
|
|
302
|
-
fileKey: normalizedFileKey,
|
|
303
|
-
type,
|
|
304
|
-
maxBytes,
|
|
305
|
-
originalFilename
|
|
306
|
-
});
|
|
307
|
-
} catch (err) {
|
|
308
|
-
if (type !== "file" || !isHttpStatusError(err, 502)) throw err;
|
|
309
|
-
try {
|
|
310
|
-
return await saveMessageResourceWithType({
|
|
311
|
-
client,
|
|
312
|
-
messageId,
|
|
313
|
-
fileKey: normalizedFileKey,
|
|
314
|
-
type: "media",
|
|
315
|
-
maxBytes,
|
|
316
|
-
originalFilename
|
|
317
|
-
});
|
|
318
|
-
} catch {
|
|
319
|
-
throw err;
|
|
320
|
-
}
|
|
321
|
-
}
|
|
245
|
+
function renderLinkElement(element) {
|
|
246
|
+
const href = toStringOrEmpty(element.href).trim();
|
|
247
|
+
const text = toStringOrEmpty(element.text) || href;
|
|
248
|
+
if (!text) return "";
|
|
249
|
+
if (!href) return escapeMarkdownText(text);
|
|
250
|
+
return `[${escapeMarkdownText(text)}](${href})`;
|
|
322
251
|
}
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
async function uploadImageFeishu(params) {
|
|
328
|
-
const { cfg, image, imageType = "message", accountId } = params;
|
|
329
|
-
const { client } = createConfiguredFeishuMediaClient({
|
|
330
|
-
cfg,
|
|
331
|
-
accountId
|
|
332
|
-
});
|
|
333
|
-
const imageData = typeof image === "string" ? (await readRegularFile({ filePath: image })).buffer : image;
|
|
334
|
-
return { imageKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.image.create({ data: {
|
|
335
|
-
image_type: imageType,
|
|
336
|
-
image: imageData
|
|
337
|
-
} }), "Feishu image upload failed", { includeNestedErrorLogId: true }), {
|
|
338
|
-
key: "image_key",
|
|
339
|
-
errorPrefix: "Feishu image upload failed"
|
|
340
|
-
}) };
|
|
252
|
+
function renderMentionElement(element) {
|
|
253
|
+
const mention = toStringOrEmpty(element.user_name) || toStringOrEmpty(element.user_id) || toStringOrEmpty(element.open_id);
|
|
254
|
+
if (!mention) return "";
|
|
255
|
+
return `@${escapeMarkdownText(mention)}`;
|
|
341
256
|
}
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
* Strips control characters and multipart-injection vectors (CWE-93) while
|
|
345
|
-
* preserving the original UTF-8 display name (Chinese, emoji, etc.).
|
|
346
|
-
*
|
|
347
|
-
* Previous versions percent-encoded non-ASCII characters, but the Feishu
|
|
348
|
-
* `im.file.create` API uses `file_name` as a literal display name — it does
|
|
349
|
-
* NOT decode percent-encoding — so encoded filenames appeared as garbled text
|
|
350
|
-
* in chat (regression in v2026.3.2).
|
|
351
|
-
*/
|
|
352
|
-
function sanitizeFileNameForUpload(fileName) {
|
|
353
|
-
return fileName.replace(/[\p{Cc}"\\]/gu, "_");
|
|
257
|
+
function renderEmotionElement(element) {
|
|
258
|
+
return escapeMarkdownText(toStringOrEmpty(element.emoji) || toStringOrEmpty(element.text) || toStringOrEmpty(element.emoji_type));
|
|
354
259
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
async function uploadFileFeishu(params) {
|
|
360
|
-
const { cfg, file, fileName, fileType, duration, accountId } = params;
|
|
361
|
-
const { client } = createConfiguredFeishuMediaClient({
|
|
362
|
-
cfg,
|
|
363
|
-
accountId
|
|
364
|
-
});
|
|
365
|
-
const fileData = typeof file === "string" ? (await readRegularFile({ filePath: file })).buffer : file;
|
|
366
|
-
const safeFileName = sanitizeFileNameForUpload(fileName);
|
|
367
|
-
return { fileKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.file.create({ data: {
|
|
368
|
-
file_type: fileType,
|
|
369
|
-
file_name: safeFileName,
|
|
370
|
-
file: fileData,
|
|
371
|
-
...duration !== void 0 ? { duration } : {}
|
|
372
|
-
} }), "Feishu file upload failed", { includeNestedErrorLogId: true }), {
|
|
373
|
-
key: "file_key",
|
|
374
|
-
errorPrefix: "Feishu file upload failed"
|
|
375
|
-
}) };
|
|
260
|
+
function renderCodeBlockElement(element) {
|
|
261
|
+
const language = sanitizeFenceLanguage(toStringOrEmpty(element.language) || toStringOrEmpty(element.lang));
|
|
262
|
+
const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(/\r\n/g, "\n");
|
|
263
|
+
return `\`\`\`${language}\n${code}${code.endsWith("\n") ? "" : "\n"}\`\`\``;
|
|
376
264
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
});
|
|
387
|
-
const content = JSON.stringify({ image_key: imageKey });
|
|
388
|
-
if (replyToMessageId) {
|
|
389
|
-
const response = await requestFeishuApi(() => client.im.message.reply({
|
|
390
|
-
path: { message_id: replyToMessageId },
|
|
391
|
-
data: {
|
|
392
|
-
content,
|
|
393
|
-
msg_type: "image",
|
|
394
|
-
...replyInThread ? { reply_in_thread: true } : {}
|
|
265
|
+
function renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, renderMediaPlaceholders) {
|
|
266
|
+
if (!isRecord$1(element)) return escapeMarkdownText(toStringOrEmpty(element));
|
|
267
|
+
switch (normalizeLowercaseStringOrEmpty(toStringOrEmpty(element.tag))) {
|
|
268
|
+
case "text": return renderTextElement(element);
|
|
269
|
+
case "a": return renderLinkElement(element);
|
|
270
|
+
case "at":
|
|
271
|
+
{
|
|
272
|
+
const normalizedMention = normalizeFeishuExternalKey(toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id));
|
|
273
|
+
if (normalizedMention) mentionedOpenIds.push(normalizedMention);
|
|
395
274
|
}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
params: { receive_id_type: receiveIdType },
|
|
402
|
-
data: {
|
|
403
|
-
receive_id: receiveId,
|
|
404
|
-
content,
|
|
405
|
-
msg_type: "image"
|
|
275
|
+
return renderMentionElement(element);
|
|
276
|
+
case "img": {
|
|
277
|
+
const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
|
|
278
|
+
if (imageKey) imageKeys.push(imageKey);
|
|
279
|
+
return renderMediaPlaceholders ? "![image]" : "";
|
|
406
280
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
const { cfg, to, fileKey, replyToMessageId, replyInThread, accountId } = params;
|
|
416
|
-
const msgType = params.msgType ?? "file";
|
|
417
|
-
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
418
|
-
cfg,
|
|
419
|
-
to,
|
|
420
|
-
accountId
|
|
421
|
-
});
|
|
422
|
-
const content = JSON.stringify({ file_key: fileKey });
|
|
423
|
-
if (replyToMessageId) {
|
|
424
|
-
const response = await requestFeishuApi(() => client.im.message.reply({
|
|
425
|
-
path: { message_id: replyToMessageId },
|
|
426
|
-
data: {
|
|
427
|
-
content,
|
|
428
|
-
msg_type: msgType,
|
|
429
|
-
...replyInThread ? { reply_in_thread: true } : {}
|
|
281
|
+
case "media": {
|
|
282
|
+
const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
|
|
283
|
+
if (fileKey) {
|
|
284
|
+
const fileName = toStringOrEmpty(element.file_name) || void 0;
|
|
285
|
+
mediaKeys.push({
|
|
286
|
+
fileKey,
|
|
287
|
+
fileName
|
|
288
|
+
});
|
|
430
289
|
}
|
|
431
|
-
|
|
432
|
-
assertFeishuMessageApiSuccess(response, "Feishu file reply failed");
|
|
433
|
-
return toFeishuSendResult(response, receiveId, resolveFeishuReceiptKind(msgType));
|
|
434
|
-
}
|
|
435
|
-
const response = await requestFeishuApi(() => client.im.message.create({
|
|
436
|
-
params: { receive_id_type: receiveIdType },
|
|
437
|
-
data: {
|
|
438
|
-
receive_id: receiveId,
|
|
439
|
-
content,
|
|
440
|
-
msg_type: msgType
|
|
290
|
+
return renderMediaPlaceholders ? "[media]" : "";
|
|
441
291
|
}
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
case "
|
|
452
|
-
case "
|
|
453
|
-
|
|
454
|
-
case ".mov":
|
|
455
|
-
case ".avi": return "mp4";
|
|
456
|
-
case ".pdf": return "pdf";
|
|
457
|
-
case ".doc":
|
|
458
|
-
case ".docx": return "doc";
|
|
459
|
-
case ".xls":
|
|
460
|
-
case ".xlsx": return "xls";
|
|
461
|
-
case ".ppt":
|
|
462
|
-
case ".pptx": return "ppt";
|
|
463
|
-
default: return "stream";
|
|
292
|
+
case "emotion": return renderEmotionElement(element);
|
|
293
|
+
case "md":
|
|
294
|
+
case "lark_md": return toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
295
|
+
case "br": return "\n";
|
|
296
|
+
case "hr": return "\n\n---\n\n";
|
|
297
|
+
case "code": {
|
|
298
|
+
const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
299
|
+
return code ? wrapInlineCode(code) : "";
|
|
300
|
+
}
|
|
301
|
+
case "code_block":
|
|
302
|
+
case "pre": return renderCodeBlockElement(element);
|
|
303
|
+
default: return escapeMarkdownText(toStringOrEmpty(element.text));
|
|
464
304
|
}
|
|
465
305
|
}
|
|
466
|
-
function
|
|
467
|
-
|
|
468
|
-
const ext = normalizeLowercaseStringOrEmpty(path.extname(fileName));
|
|
469
|
-
const mimeKind = mediaKindFromMime(contentType);
|
|
470
|
-
if ([
|
|
471
|
-
".jpg",
|
|
472
|
-
".jpeg",
|
|
473
|
-
".png",
|
|
474
|
-
".gif",
|
|
475
|
-
".webp",
|
|
476
|
-
".bmp",
|
|
477
|
-
".ico",
|
|
478
|
-
".tiff"
|
|
479
|
-
].includes(ext) || mimeKind === "image") return { msgType: "image" };
|
|
480
|
-
if (ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus") return {
|
|
481
|
-
fileType: "opus",
|
|
482
|
-
msgType: "audio"
|
|
483
|
-
};
|
|
484
|
-
if ([
|
|
485
|
-
".mp4",
|
|
486
|
-
".mov",
|
|
487
|
-
".avi"
|
|
488
|
-
].includes(ext) || contentType === "video/mp4" || contentType === "video/quicktime" || contentType === "video/x-msvideo") return {
|
|
489
|
-
fileType: "mp4",
|
|
490
|
-
msgType: "media"
|
|
491
|
-
};
|
|
492
|
-
const fileType = detectFileType(fileName);
|
|
306
|
+
function toPostPayload(candidate) {
|
|
307
|
+
if (!isRecord$1(candidate) || !Array.isArray(candidate.content)) return null;
|
|
493
308
|
return {
|
|
494
|
-
|
|
495
|
-
|
|
309
|
+
title: toStringOrEmpty(candidate.title),
|
|
310
|
+
content: candidate.content
|
|
496
311
|
};
|
|
497
312
|
}
|
|
498
|
-
function
|
|
499
|
-
const
|
|
500
|
-
|
|
501
|
-
|
|
313
|
+
function resolveLocalePayload(candidate) {
|
|
314
|
+
const direct = toPostPayload(candidate);
|
|
315
|
+
if (direct) return direct;
|
|
316
|
+
if (!isRecord$1(candidate)) return null;
|
|
317
|
+
for (const value of Object.values(candidate)) {
|
|
318
|
+
const localePayload = toPostPayload(value);
|
|
319
|
+
if (localePayload) return localePayload;
|
|
320
|
+
}
|
|
321
|
+
return null;
|
|
502
322
|
}
|
|
503
|
-
function
|
|
323
|
+
function resolvePostPayload(parsed) {
|
|
324
|
+
const direct = toPostPayload(parsed);
|
|
325
|
+
if (direct) return direct;
|
|
326
|
+
if (!isRecord$1(parsed)) return null;
|
|
327
|
+
const wrappedPost = resolveLocalePayload(parsed.post);
|
|
328
|
+
if (wrappedPost) return wrappedPost;
|
|
329
|
+
return resolveLocalePayload(parsed);
|
|
330
|
+
}
|
|
331
|
+
function parsePostContent(content, options = {}) {
|
|
504
332
|
try {
|
|
505
|
-
|
|
333
|
+
const payload = resolvePostPayload(JSON.parse(content));
|
|
334
|
+
if (!payload) return {
|
|
335
|
+
textContent: FALLBACK_POST_TEXT,
|
|
336
|
+
imageKeys: [],
|
|
337
|
+
mediaKeys: [],
|
|
338
|
+
mentionedOpenIds: []
|
|
339
|
+
};
|
|
340
|
+
const imageKeys = [];
|
|
341
|
+
const mediaKeys = [];
|
|
342
|
+
const mentionedOpenIds = [];
|
|
343
|
+
const paragraphs = [];
|
|
344
|
+
for (const paragraph of payload.content) {
|
|
345
|
+
if (!Array.isArray(paragraph)) continue;
|
|
346
|
+
let renderedParagraph = "";
|
|
347
|
+
for (const element of paragraph) renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, options.renderMediaPlaceholders !== false);
|
|
348
|
+
paragraphs.push(renderedParagraph);
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
textContent: [escapeMarkdownText(payload.title.trim()), paragraphs.join("\n").trim()].filter(Boolean).join("\n\n").trim() || (options.emptyTextFallback ?? FALLBACK_POST_TEXT),
|
|
352
|
+
imageKeys,
|
|
353
|
+
mediaKeys,
|
|
354
|
+
mentionedOpenIds
|
|
355
|
+
};
|
|
506
356
|
} catch {
|
|
507
|
-
return
|
|
357
|
+
return {
|
|
358
|
+
textContent: FALLBACK_POST_TEXT,
|
|
359
|
+
imageKeys: [],
|
|
360
|
+
mediaKeys: [],
|
|
361
|
+
mentionedOpenIds: []
|
|
362
|
+
};
|
|
508
363
|
}
|
|
509
364
|
}
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
return
|
|
519
|
-
fileName: normalizeMediaNameForExtension(params.mediaUrl),
|
|
520
|
-
contentType: params.contentType
|
|
521
|
-
});
|
|
522
|
-
}
|
|
523
|
-
function isLikelyTranscodableAudio(params) {
|
|
524
|
-
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
525
|
-
const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
|
|
526
|
-
return FEISHU_TRANSCODABLE_AUDIO_EXTS.has(ext) || mediaKindFromMime(contentType) === "audio";
|
|
365
|
+
//#endregion
|
|
366
|
+
//#region extensions/feishu/src/send.ts
|
|
367
|
+
const WITHDRAWN_REPLY_ERROR_CODES = /* @__PURE__ */ new Set([230011, 231003]);
|
|
368
|
+
const INTERACTIVE_CARD_FALLBACK_TEXT = "[Interactive Card]";
|
|
369
|
+
const POST_FALLBACK_TEXT = "[Rich text message]";
|
|
370
|
+
function shouldFallbackFromReplyTarget(response) {
|
|
371
|
+
if (response.code !== void 0 && WITHDRAWN_REPLY_ERROR_CODES.has(response.code)) return true;
|
|
372
|
+
const msg = normalizeLowercaseStringOrEmpty(response.msg);
|
|
373
|
+
return msg.includes("withdrawn") || msg.includes("not found");
|
|
527
374
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
path: FEISHU_VOICE_FILE_NAME,
|
|
539
|
-
write: async (outputPath) => {
|
|
540
|
-
await runFfmpeg([
|
|
541
|
-
"-hide_banner",
|
|
542
|
-
"-loglevel",
|
|
543
|
-
"error",
|
|
544
|
-
"-y",
|
|
545
|
-
"-i",
|
|
546
|
-
inputPath,
|
|
547
|
-
"-vn",
|
|
548
|
-
"-sn",
|
|
549
|
-
"-dn",
|
|
550
|
-
"-t",
|
|
551
|
-
String(MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS),
|
|
552
|
-
"-ar",
|
|
553
|
-
String(FEISHU_VOICE_SAMPLE_RATE_HZ),
|
|
554
|
-
"-ac",
|
|
555
|
-
"1",
|
|
556
|
-
"-c:a",
|
|
557
|
-
"libopus",
|
|
558
|
-
"-b:a",
|
|
559
|
-
FEISHU_VOICE_BITRATE,
|
|
560
|
-
"-f",
|
|
561
|
-
"ogg",
|
|
562
|
-
outputPath
|
|
563
|
-
]);
|
|
564
|
-
}
|
|
565
|
-
});
|
|
566
|
-
return {
|
|
567
|
-
buffer: await workspace.read(FEISHU_VOICE_FILE_NAME),
|
|
568
|
-
fileName: FEISHU_VOICE_FILE_NAME,
|
|
569
|
-
contentType: "audio/ogg"
|
|
570
|
-
};
|
|
571
|
-
});
|
|
375
|
+
/** Check whether a thrown error indicates a withdrawn/not-found reply target. */
|
|
376
|
+
function isWithdrawnReplyError(err) {
|
|
377
|
+
if (typeof err !== "object" || err === null) return false;
|
|
378
|
+
const code = err.code;
|
|
379
|
+
if (typeof code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(code)) return true;
|
|
380
|
+
const response = err.response;
|
|
381
|
+
if (typeof response?.data?.code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(response.data.code)) return true;
|
|
382
|
+
const cause = err.cause;
|
|
383
|
+
if (cause && cause !== err) return isWithdrawnReplyError(cause);
|
|
384
|
+
return false;
|
|
572
385
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
386
|
+
/** Send a direct message as a fallback when a reply target is unavailable. */
|
|
387
|
+
async function sendFallbackDirect(client, params, errorPrefix) {
|
|
388
|
+
const response = await requestFeishuApi(() => client.im.message.create({
|
|
389
|
+
params: { receive_id_type: params.receiveIdType },
|
|
390
|
+
data: {
|
|
391
|
+
receive_id: params.receiveId,
|
|
392
|
+
content: params.content,
|
|
393
|
+
msg_type: params.msgType
|
|
394
|
+
}
|
|
395
|
+
}), errorPrefix, { includeNestedErrorLogId: true });
|
|
396
|
+
assertFeishuMessageApiSuccess(response, errorPrefix);
|
|
397
|
+
return toFeishuSendResult(response, params.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
398
|
+
}
|
|
399
|
+
async function sendReplyOrFallbackDirect(client, params) {
|
|
400
|
+
if (!params.replyToMessageId) return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
401
|
+
const replyTargetFallbackError = params.replyInThread && params.allowTopLevelReplyFallback !== true ? /* @__PURE__ */ new Error("Feishu thread reply failed: reply target is unavailable and cannot safely fall back to a top-level send.") : null;
|
|
402
|
+
let response;
|
|
576
403
|
try {
|
|
577
|
-
|
|
404
|
+
response = await requestFeishuApi(() => client.im.message.reply({
|
|
405
|
+
path: { message_id: params.replyToMessageId },
|
|
406
|
+
data: {
|
|
407
|
+
content: params.content,
|
|
408
|
+
msg_type: params.msgType,
|
|
409
|
+
...params.replyInThread ? { reply_in_thread: true } : {}
|
|
410
|
+
}
|
|
411
|
+
}), params.replyErrorPrefix, { includeNestedErrorLogId: true });
|
|
578
412
|
} catch (err) {
|
|
579
|
-
|
|
580
|
-
|
|
413
|
+
if (!isWithdrawnReplyError(err)) throw err;
|
|
414
|
+
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
415
|
+
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
416
|
+
}
|
|
417
|
+
if (shouldFallbackFromReplyTarget(response)) {
|
|
418
|
+
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
419
|
+
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
581
420
|
}
|
|
421
|
+
assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
|
|
422
|
+
return toFeishuSendResult(response, params.directParams.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
582
423
|
}
|
|
583
|
-
|
|
424
|
+
function normalizeCardTemplateVariable(value) {
|
|
425
|
+
if (typeof value === "string") return value;
|
|
426
|
+
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
427
|
+
}
|
|
428
|
+
function readCardTemplateVariables(parsed) {
|
|
429
|
+
const variables = /* @__PURE__ */ new Map();
|
|
430
|
+
for (const source of [parsed.template_variable, parsed.template_variables]) {
|
|
431
|
+
if (!isRecord(source)) continue;
|
|
432
|
+
for (const [key, value] of Object.entries(source)) {
|
|
433
|
+
const normalized = normalizeCardTemplateVariable(value);
|
|
434
|
+
if (normalized !== void 0) variables.set(key, normalized);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return variables;
|
|
438
|
+
}
|
|
439
|
+
function applyCardTemplateVariables(text, variables) {
|
|
440
|
+
if (variables.size === 0) return text;
|
|
441
|
+
return text.replace(/\$\{([A-Za-z0-9_.-]+)\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (match, a, b) => {
|
|
442
|
+
const variableName = typeof a === "string" ? a : b;
|
|
443
|
+
return variables.get(variableName) ?? match;
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
function extractInteractiveElementText(element, variables) {
|
|
447
|
+
if (!isRecord(element)) return;
|
|
448
|
+
const tag = typeof element.tag === "string" ? element.tag : "";
|
|
449
|
+
const text = isRecord(element.text) ? element.text : void 0;
|
|
450
|
+
if (tag === "div" && typeof text?.content === "string") return applyCardTemplateVariables(text.content, variables);
|
|
451
|
+
if ((tag === "markdown" || tag === "lark_md") && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
|
|
452
|
+
if (tag === "plain_text" && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
|
|
453
|
+
}
|
|
454
|
+
function extractInteractiveElementsText(elements, variables) {
|
|
455
|
+
const texts = [];
|
|
456
|
+
for (const element of elements) {
|
|
457
|
+
const text = extractInteractiveElementText(element, variables);
|
|
458
|
+
if (text !== void 0) texts.push(text);
|
|
459
|
+
}
|
|
460
|
+
return texts.join("\n").trim();
|
|
461
|
+
}
|
|
462
|
+
function readInteractiveElementArrays(parsed) {
|
|
463
|
+
const body = isRecord(parsed.body) ? parsed.body : void 0;
|
|
464
|
+
const elementArrays = [];
|
|
465
|
+
for (const candidate of [parsed.elements, body?.elements]) if (Array.isArray(candidate)) elementArrays.push(candidate);
|
|
466
|
+
for (const candidate of [parsed.i18n_elements, body?.i18n_elements]) {
|
|
467
|
+
if (!isRecord(candidate)) continue;
|
|
468
|
+
for (const localeElements of Object.values(candidate)) if (Array.isArray(localeElements)) elementArrays.push(localeElements);
|
|
469
|
+
}
|
|
470
|
+
return elementArrays;
|
|
471
|
+
}
|
|
472
|
+
function parseInteractivePostFallback(parsed) {
|
|
473
|
+
const textContent = parsePostContent(JSON.stringify(parsed)).textContent.trim();
|
|
474
|
+
return textContent && textContent !== POST_FALLBACK_TEXT ? textContent : void 0;
|
|
475
|
+
}
|
|
476
|
+
function parseInteractiveCardContent(parsed) {
|
|
477
|
+
if (!isRecord(parsed)) return INTERACTIVE_CARD_FALLBACK_TEXT;
|
|
478
|
+
const variables = readCardTemplateVariables(parsed);
|
|
479
|
+
for (const elements of readInteractiveElementArrays(parsed)) {
|
|
480
|
+
const text = extractInteractiveElementsText(elements, variables);
|
|
481
|
+
if (text) return text;
|
|
482
|
+
}
|
|
483
|
+
return parseInteractivePostFallback(parsed) ?? INTERACTIVE_CARD_FALLBACK_TEXT;
|
|
484
|
+
}
|
|
485
|
+
function parseFeishuMessageContent(rawContent, msgType) {
|
|
486
|
+
if (!rawContent) return "";
|
|
487
|
+
let parsed;
|
|
584
488
|
try {
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
"-v",
|
|
593
|
-
"error",
|
|
594
|
-
"-show_entries",
|
|
595
|
-
"format=duration",
|
|
596
|
-
"-of",
|
|
597
|
-
"csv=p=0",
|
|
598
|
-
await workspace.write(`input${inferredExt}`, params.buffer)
|
|
599
|
-
], { timeoutMs: 5e3 });
|
|
600
|
-
const seconds = Number.parseFloat(stdout.trim());
|
|
601
|
-
if (!Number.isFinite(seconds) || seconds <= 0) return;
|
|
602
|
-
return Math.max(1, Math.round(seconds * 1e3));
|
|
603
|
-
});
|
|
604
|
-
} catch (err) {
|
|
605
|
-
console.warn("[feishu] failed to probe media duration; upload will omit it:", err);
|
|
606
|
-
return;
|
|
489
|
+
parsed = JSON.parse(rawContent);
|
|
490
|
+
} catch {
|
|
491
|
+
return rawContent;
|
|
492
|
+
}
|
|
493
|
+
if (msgType === "text") {
|
|
494
|
+
const text = parsed?.text;
|
|
495
|
+
return typeof text === "string" ? text : "[Text message]";
|
|
607
496
|
}
|
|
497
|
+
if (msgType === "post") return parsePostContent(rawContent).textContent;
|
|
498
|
+
if (msgType === "interactive") return parseInteractiveCardContent(parsed);
|
|
499
|
+
if (typeof parsed === "string") return parsed;
|
|
500
|
+
const genericText = parsed?.text;
|
|
501
|
+
if (typeof genericText === "string" && genericText.trim()) return genericText;
|
|
502
|
+
const genericTitle = parsed?.title;
|
|
503
|
+
if (typeof genericTitle === "string" && genericTitle.trim()) return genericTitle;
|
|
504
|
+
return `[${msgType || "unknown"} message]`;
|
|
608
505
|
}
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
506
|
+
function parseFeishuMessageItem(item, fallbackMessageId) {
|
|
507
|
+
const msgType = item.msg_type ?? "text";
|
|
508
|
+
const rawContent = item.body?.content ?? "";
|
|
509
|
+
return {
|
|
510
|
+
messageId: item.message_id ?? fallbackMessageId ?? "",
|
|
511
|
+
chatId: item.chat_id ?? "",
|
|
512
|
+
chatType: item.chat_type === "group" || item.chat_type === "topic_group" || item.chat_type === "private" || item.chat_type === "p2p" ? item.chat_type : void 0,
|
|
513
|
+
senderId: item.sender?.id,
|
|
514
|
+
senderOpenId: item.sender?.id_type === "open_id" ? item.sender?.id : void 0,
|
|
515
|
+
senderType: item.sender?.sender_type,
|
|
516
|
+
content: parseFeishuMessageContent(rawContent, msgType),
|
|
517
|
+
contentType: msgType,
|
|
518
|
+
createTime: parseStrictNonNegativeInteger(item.create_time),
|
|
519
|
+
threadId: item.thread_id || void 0
|
|
520
|
+
};
|
|
612
521
|
}
|
|
613
522
|
/**
|
|
614
|
-
*
|
|
615
|
-
*
|
|
616
|
-
* must be passed so loadWebMedia allows the path (post CVE-2026-26321).
|
|
523
|
+
* Get a message by its ID.
|
|
524
|
+
* Useful for fetching quoted/replied message content.
|
|
617
525
|
*/
|
|
618
|
-
async function
|
|
619
|
-
const { cfg,
|
|
526
|
+
async function getMessageFeishu(params) {
|
|
527
|
+
const { cfg, messageId, accountId } = params;
|
|
620
528
|
const account = resolveFeishuRuntimeAccount({
|
|
621
529
|
cfg,
|
|
622
530
|
accountId
|
|
623
531
|
});
|
|
624
532
|
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
buffer = mediaBuffer;
|
|
631
|
-
name = fileName ?? "file";
|
|
632
|
-
} else if (mediaUrl) {
|
|
633
|
-
const loaded = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
|
|
634
|
-
maxBytes: mediaMaxBytes,
|
|
635
|
-
optimizeImages: false,
|
|
636
|
-
localRoots: mediaLocalRoots?.length ? mediaLocalRoots : void 0
|
|
533
|
+
const client = createFeishuClient(account);
|
|
534
|
+
try {
|
|
535
|
+
const response = await client.im.message.get({
|
|
536
|
+
params: { card_msg_content_type: "user_card_content" },
|
|
537
|
+
path: { message_id: messageId }
|
|
637
538
|
});
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
539
|
+
if (response.code !== 0) return null;
|
|
540
|
+
const rawItem = response.data?.items?.[0] ?? response.data;
|
|
541
|
+
const item = rawItem && (rawItem.body !== void 0 || rawItem.message_id !== void 0) ? rawItem : null;
|
|
542
|
+
if (!item) return null;
|
|
543
|
+
return parseFeishuMessageItem(item, messageId);
|
|
544
|
+
} catch {
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
/**
|
|
549
|
+
* List messages in a Feishu thread (topic).
|
|
550
|
+
* Uses container_id_type=thread to directly query thread messages,
|
|
551
|
+
* which includes both the root message and all replies (including bot replies).
|
|
552
|
+
*/
|
|
553
|
+
async function listFeishuThreadMessages(params) {
|
|
554
|
+
const { cfg, threadId, currentMessageId, rootMessageId, limit = 20, accountId } = params;
|
|
555
|
+
const account = resolveFeishuRuntimeAccount({
|
|
556
|
+
cfg,
|
|
557
|
+
accountId
|
|
558
|
+
});
|
|
559
|
+
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
560
|
+
const response = await createFeishuClient(account).im.message.list({ params: {
|
|
561
|
+
container_id_type: "thread",
|
|
562
|
+
container_id: threadId,
|
|
563
|
+
sort_type: "ByCreateTimeDesc",
|
|
564
|
+
page_size: Math.min(limit + 1, 50),
|
|
565
|
+
card_msg_content_type: "user_card_content"
|
|
566
|
+
} });
|
|
567
|
+
if (response.code !== 0) throw new Error(`Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`);
|
|
568
|
+
const items = response.data?.items ?? [];
|
|
569
|
+
const results = [];
|
|
570
|
+
for (const item of items) {
|
|
571
|
+
if (currentMessageId && item.message_id === currentMessageId) continue;
|
|
572
|
+
if (rootMessageId && item.message_id === rootMessageId) continue;
|
|
573
|
+
const parsed = parseFeishuMessageItem(item);
|
|
574
|
+
results.push({
|
|
575
|
+
messageId: parsed.messageId,
|
|
576
|
+
senderId: parsed.senderId,
|
|
577
|
+
senderType: parsed.senderType,
|
|
578
|
+
content: parsed.content,
|
|
579
|
+
contentType: parsed.contentType,
|
|
580
|
+
createTime: parsed.createTime
|
|
661
581
|
});
|
|
662
|
-
|
|
663
|
-
...await sendImageFeishu({
|
|
664
|
-
cfg,
|
|
665
|
-
to,
|
|
666
|
-
imageKey,
|
|
667
|
-
replyToMessageId,
|
|
668
|
-
replyInThread,
|
|
669
|
-
accountId
|
|
670
|
-
}),
|
|
671
|
-
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
672
|
-
};
|
|
582
|
+
if (results.length >= limit) break;
|
|
673
583
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
584
|
+
results.reverse();
|
|
585
|
+
return results;
|
|
586
|
+
}
|
|
587
|
+
async function sendMessageFeishu(params) {
|
|
588
|
+
const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId } = params;
|
|
589
|
+
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
590
|
+
cfg,
|
|
591
|
+
to,
|
|
592
|
+
accountId
|
|
679
593
|
});
|
|
680
|
-
const
|
|
594
|
+
const tableMode = resolveMarkdownTableMode({
|
|
595
|
+
cfg,
|
|
596
|
+
channel: "feishu"
|
|
597
|
+
});
|
|
598
|
+
const content = buildFeishuPostMessageContent({
|
|
599
|
+
messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text ?? "", tableMode)),
|
|
600
|
+
mentions
|
|
601
|
+
});
|
|
602
|
+
const msgType = "post";
|
|
603
|
+
assertFeishuPostWithinEnvelope(content, "Feishu post");
|
|
604
|
+
return sendReplyOrFallbackDirect(client, {
|
|
605
|
+
replyToMessageId,
|
|
606
|
+
replyInThread,
|
|
607
|
+
allowTopLevelReplyFallback,
|
|
608
|
+
content,
|
|
609
|
+
msgType,
|
|
610
|
+
directParams: {
|
|
611
|
+
receiveId,
|
|
612
|
+
receiveIdType,
|
|
613
|
+
content,
|
|
614
|
+
msgType
|
|
615
|
+
},
|
|
616
|
+
directErrorPrefix: "Feishu send failed",
|
|
617
|
+
replyErrorPrefix: "Feishu reply failed"
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
async function sendCardFeishu(params) {
|
|
621
|
+
const { cfg, to, card, replyToMessageId, replyInThread, allowTopLevelReplyFallback, accountId } = params;
|
|
622
|
+
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
623
|
+
cfg,
|
|
624
|
+
to,
|
|
625
|
+
accountId
|
|
626
|
+
});
|
|
627
|
+
const content = JSON.stringify(card);
|
|
628
|
+
return sendReplyOrFallbackDirect(client, {
|
|
629
|
+
replyToMessageId,
|
|
630
|
+
replyInThread,
|
|
631
|
+
allowTopLevelReplyFallback,
|
|
632
|
+
content,
|
|
633
|
+
msgType: "interactive",
|
|
634
|
+
directParams: {
|
|
635
|
+
receiveId,
|
|
636
|
+
receiveIdType,
|
|
637
|
+
content,
|
|
638
|
+
msgType: "interactive"
|
|
639
|
+
},
|
|
640
|
+
directErrorPrefix: "Feishu card send failed",
|
|
641
|
+
replyErrorPrefix: "Feishu card reply failed"
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
async function editMessageFeishu(params) {
|
|
645
|
+
const { cfg, messageId, text, card, accountId } = params;
|
|
646
|
+
const account = resolveFeishuRuntimeAccount({
|
|
681
647
|
cfg,
|
|
682
|
-
file: buffer,
|
|
683
|
-
fileName: name,
|
|
684
|
-
fileType: routing.fileType ?? "stream",
|
|
685
|
-
...durationMs !== void 0 ? { duration: durationMs } : {},
|
|
686
648
|
accountId
|
|
687
649
|
});
|
|
650
|
+
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
651
|
+
if ((typeof text === "string" && text.trim().length > 0) === Boolean(card)) throw new Error("Feishu edit requires exactly one of text or card.");
|
|
652
|
+
const client = createFeishuClient(account);
|
|
653
|
+
if (card) {
|
|
654
|
+
const content = JSON.stringify(card);
|
|
655
|
+
const response = await client.im.message.patch({
|
|
656
|
+
path: { message_id: messageId },
|
|
657
|
+
data: { content }
|
|
658
|
+
});
|
|
659
|
+
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
660
|
+
return {
|
|
661
|
+
messageId,
|
|
662
|
+
contentType: "interactive"
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
const content = buildFeishuPostMessageContent({ messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text, resolveMarkdownTableMode({
|
|
666
|
+
cfg,
|
|
667
|
+
channel: "feishu"
|
|
668
|
+
}))) });
|
|
669
|
+
assertFeishuPostWithinEnvelope(content, "Feishu message edit");
|
|
670
|
+
const response = await client.im.message.patch({
|
|
671
|
+
path: { message_id: messageId },
|
|
672
|
+
data: { content }
|
|
673
|
+
});
|
|
674
|
+
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
688
675
|
return {
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
to,
|
|
692
|
-
fileKey,
|
|
693
|
-
msgType: routing.msgType,
|
|
694
|
-
replyToMessageId,
|
|
695
|
-
replyInThread,
|
|
696
|
-
accountId
|
|
697
|
-
}),
|
|
698
|
-
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
676
|
+
messageId,
|
|
677
|
+
contentType: "post"
|
|
699
678
|
};
|
|
700
679
|
}
|
|
701
|
-
//#endregion
|
|
702
|
-
//#region extensions/feishu/src/types.ts
|
|
703
|
-
function isFeishuGroupChatType(chatType) {
|
|
704
|
-
return chatType === "group" || chatType === "topic_group";
|
|
705
|
-
}
|
|
706
|
-
//#endregion
|
|
707
|
-
//#region extensions/feishu/src/mention.ts
|
|
708
|
-
function isFeishuBroadcastMention(mention) {
|
|
709
|
-
const normalizedKey = mention.key?.trim().toLowerCase();
|
|
710
|
-
if (normalizedKey === "@all" || normalizedKey === "@_all") return true;
|
|
711
|
-
return [
|
|
712
|
-
mention.id?.open_id,
|
|
713
|
-
mention.id?.user_id,
|
|
714
|
-
mention.id?.union_id
|
|
715
|
-
].some((id) => id?.trim().toLowerCase() === "all");
|
|
716
|
-
}
|
|
717
680
|
/**
|
|
718
|
-
*
|
|
681
|
+
* Build a Feishu interactive card with markdown content.
|
|
682
|
+
* Cards render markdown properly (code blocks, tables, links, etc.)
|
|
683
|
+
* Uses schema 2.0 format for proper markdown rendering.
|
|
719
684
|
*/
|
|
720
|
-
function
|
|
721
|
-
return
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
}));
|
|
685
|
+
function buildMarkdownCard(text) {
|
|
686
|
+
return {
|
|
687
|
+
schema: "2.0",
|
|
688
|
+
config: { width_mode: "fill" },
|
|
689
|
+
body: { elements: [{
|
|
690
|
+
tag: "markdown",
|
|
691
|
+
content: text
|
|
692
|
+
}] }
|
|
693
|
+
};
|
|
730
694
|
}
|
|
731
695
|
/**
|
|
732
|
-
*
|
|
733
|
-
*
|
|
734
|
-
* - Group: message mentions bot + at least one other user
|
|
735
|
-
* - DM: message mentions any user (no need to mention bot)
|
|
696
|
+
* Build a Feishu interactive card with optional header and note footer.
|
|
697
|
+
* When header/note are omitted, behaves identically to buildMarkdownCard.
|
|
736
698
|
*/
|
|
737
|
-
function
|
|
738
|
-
const
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
699
|
+
function buildStructuredCard(text, options) {
|
|
700
|
+
const elements = [{
|
|
701
|
+
tag: "markdown",
|
|
702
|
+
content: text
|
|
703
|
+
}];
|
|
704
|
+
if (options?.note) {
|
|
705
|
+
elements.push({ tag: "hr" });
|
|
706
|
+
elements.push({
|
|
707
|
+
tag: "markdown",
|
|
708
|
+
content: `<font color='grey'>${options.note}</font>`
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
const card = {
|
|
712
|
+
schema: "2.0",
|
|
713
|
+
config: { width_mode: "fill" },
|
|
714
|
+
body: { elements }
|
|
715
|
+
};
|
|
716
|
+
if (options?.header) card.header = {
|
|
717
|
+
title: {
|
|
718
|
+
tag: "plain_text",
|
|
719
|
+
content: options.header.title
|
|
720
|
+
},
|
|
721
|
+
template: resolveFeishuCardTemplate(options.header.template) ?? "blue"
|
|
722
|
+
};
|
|
723
|
+
return card;
|
|
747
724
|
}
|
|
748
725
|
/**
|
|
749
|
-
*
|
|
726
|
+
* Send a message as a structured card with optional header and note.
|
|
750
727
|
*/
|
|
751
|
-
function
|
|
752
|
-
|
|
728
|
+
async function sendStructuredCardFeishu(params) {
|
|
729
|
+
const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId, header, note } = params;
|
|
730
|
+
let cardText = text;
|
|
731
|
+
if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
|
|
732
|
+
return sendCardFeishu({
|
|
733
|
+
cfg,
|
|
734
|
+
to,
|
|
735
|
+
card: buildStructuredCard(cardText, {
|
|
736
|
+
header,
|
|
737
|
+
note
|
|
738
|
+
}),
|
|
739
|
+
replyToMessageId,
|
|
740
|
+
replyInThread,
|
|
741
|
+
allowTopLevelReplyFallback,
|
|
742
|
+
accountId
|
|
743
|
+
});
|
|
753
744
|
}
|
|
754
745
|
/**
|
|
755
|
-
*
|
|
746
|
+
* Send a message as a markdown card (interactive message).
|
|
747
|
+
* This renders markdown properly in Feishu (code blocks, tables, bold/italic, etc.)
|
|
756
748
|
*/
|
|
757
|
-
function
|
|
758
|
-
|
|
759
|
-
|
|
749
|
+
async function sendMarkdownCardFeishu(params) {
|
|
750
|
+
const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId } = params;
|
|
751
|
+
let cardText = text;
|
|
752
|
+
if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
|
|
753
|
+
return sendCardFeishu({
|
|
754
|
+
cfg,
|
|
755
|
+
to,
|
|
756
|
+
card: buildMarkdownCard(cardText),
|
|
757
|
+
replyToMessageId,
|
|
758
|
+
replyInThread,
|
|
759
|
+
allowTopLevelReplyFallback,
|
|
760
|
+
accountId
|
|
761
|
+
});
|
|
760
762
|
}
|
|
761
763
|
//#endregion
|
|
762
|
-
//#region extensions/feishu/src/
|
|
763
|
-
const
|
|
764
|
-
const
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
const text = toStringOrEmpty(element.text);
|
|
788
|
-
const style = isRecord$1(element.style) ? element.style : void 0;
|
|
789
|
-
if (isStyleEnabled(style, "code")) return wrapInlineCode(text);
|
|
790
|
-
let rendered = escapeMarkdownText(text);
|
|
791
|
-
if (!rendered) return "";
|
|
792
|
-
if (isStyleEnabled(style, "bold")) rendered = `**${rendered}**`;
|
|
793
|
-
if (isStyleEnabled(style, "italic")) rendered = `*${rendered}*`;
|
|
794
|
-
if (isStyleEnabled(style, "underline")) rendered = `<u>${rendered}</u>`;
|
|
795
|
-
if (isStyleEnabled(style, "strikethrough") || isStyleEnabled(style, "line_through") || isStyleEnabled(style, "lineThrough")) rendered = `~~${rendered}~~`;
|
|
796
|
-
return rendered;
|
|
797
|
-
}
|
|
798
|
-
function renderLinkElement(element) {
|
|
799
|
-
const href = toStringOrEmpty(element.href).trim();
|
|
800
|
-
const text = toStringOrEmpty(element.text) || href;
|
|
801
|
-
if (!text) return "";
|
|
802
|
-
if (!href) return escapeMarkdownText(text);
|
|
803
|
-
return `[${escapeMarkdownText(text)}](${href})`;
|
|
804
|
-
}
|
|
805
|
-
function renderMentionElement(element) {
|
|
806
|
-
const mention = toStringOrEmpty(element.user_name) || toStringOrEmpty(element.user_id) || toStringOrEmpty(element.open_id);
|
|
807
|
-
if (!mention) return "";
|
|
808
|
-
return `@${escapeMarkdownText(mention)}`;
|
|
809
|
-
}
|
|
810
|
-
function renderEmotionElement(element) {
|
|
811
|
-
return escapeMarkdownText(toStringOrEmpty(element.emoji) || toStringOrEmpty(element.text) || toStringOrEmpty(element.emoji_type));
|
|
812
|
-
}
|
|
813
|
-
function renderCodeBlockElement(element) {
|
|
814
|
-
const language = sanitizeFenceLanguage(toStringOrEmpty(element.language) || toStringOrEmpty(element.lang));
|
|
815
|
-
const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(/\r\n/g, "\n");
|
|
816
|
-
return `\`\`\`${language}\n${code}${code.endsWith("\n") ? "" : "\n"}\`\`\``;
|
|
817
|
-
}
|
|
818
|
-
function renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, renderMediaPlaceholders) {
|
|
819
|
-
if (!isRecord$1(element)) return escapeMarkdownText(toStringOrEmpty(element));
|
|
820
|
-
switch (normalizeLowercaseStringOrEmpty(toStringOrEmpty(element.tag))) {
|
|
821
|
-
case "text": return renderTextElement(element);
|
|
822
|
-
case "a": return renderLinkElement(element);
|
|
823
|
-
case "at":
|
|
824
|
-
{
|
|
825
|
-
const normalizedMention = normalizeFeishuExternalKey(toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id));
|
|
826
|
-
if (normalizedMention) mentionedOpenIds.push(normalizedMention);
|
|
827
|
-
}
|
|
828
|
-
return renderMentionElement(element);
|
|
829
|
-
case "img": {
|
|
830
|
-
const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
|
|
831
|
-
if (imageKey) imageKeys.push(imageKey);
|
|
832
|
-
return renderMediaPlaceholders ? "![image]" : "";
|
|
833
|
-
}
|
|
834
|
-
case "media": {
|
|
835
|
-
const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
|
|
836
|
-
if (fileKey) {
|
|
837
|
-
const fileName = toStringOrEmpty(element.file_name) || void 0;
|
|
838
|
-
mediaKeys.push({
|
|
839
|
-
fileKey,
|
|
840
|
-
fileName
|
|
841
|
-
});
|
|
842
|
-
}
|
|
843
|
-
return renderMediaPlaceholders ? "[media]" : "";
|
|
844
|
-
}
|
|
845
|
-
case "emotion": return renderEmotionElement(element);
|
|
846
|
-
case "md":
|
|
847
|
-
case "lark_md": return toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
848
|
-
case "br": return "\n";
|
|
849
|
-
case "hr": return "\n\n---\n\n";
|
|
850
|
-
case "code": {
|
|
851
|
-
const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
852
|
-
return code ? wrapInlineCode(code) : "";
|
|
853
|
-
}
|
|
854
|
-
case "code_block":
|
|
855
|
-
case "pre": return renderCodeBlockElement(element);
|
|
856
|
-
default: return escapeMarkdownText(toStringOrEmpty(element.text));
|
|
857
|
-
}
|
|
858
|
-
}
|
|
859
|
-
function toPostPayload(candidate) {
|
|
860
|
-
if (!isRecord$1(candidate) || !Array.isArray(candidate.content)) return null;
|
|
861
|
-
return {
|
|
862
|
-
title: toStringOrEmpty(candidate.title),
|
|
863
|
-
content: candidate.content
|
|
864
|
-
};
|
|
865
|
-
}
|
|
866
|
-
function resolveLocalePayload(candidate) {
|
|
867
|
-
const direct = toPostPayload(candidate);
|
|
868
|
-
if (direct) return direct;
|
|
869
|
-
if (!isRecord$1(candidate)) return null;
|
|
870
|
-
for (const value of Object.values(candidate)) {
|
|
871
|
-
const localePayload = toPostPayload(value);
|
|
872
|
-
if (localePayload) return localePayload;
|
|
873
|
-
}
|
|
874
|
-
return null;
|
|
875
|
-
}
|
|
876
|
-
function resolvePostPayload(parsed) {
|
|
877
|
-
const direct = toPostPayload(parsed);
|
|
878
|
-
if (direct) return direct;
|
|
879
|
-
if (!isRecord$1(parsed)) return null;
|
|
880
|
-
const wrappedPost = resolveLocalePayload(parsed.post);
|
|
881
|
-
if (wrappedPost) return wrappedPost;
|
|
882
|
-
return resolveLocalePayload(parsed);
|
|
883
|
-
}
|
|
884
|
-
function parsePostContent(content, options = {}) {
|
|
885
|
-
try {
|
|
886
|
-
const payload = resolvePostPayload(JSON.parse(content));
|
|
887
|
-
if (!payload) return {
|
|
888
|
-
textContent: FALLBACK_POST_TEXT,
|
|
889
|
-
imageKeys: [],
|
|
890
|
-
mediaKeys: [],
|
|
891
|
-
mentionedOpenIds: []
|
|
892
|
-
};
|
|
893
|
-
const imageKeys = [];
|
|
894
|
-
const mediaKeys = [];
|
|
895
|
-
const mentionedOpenIds = [];
|
|
896
|
-
const paragraphs = [];
|
|
897
|
-
for (const paragraph of payload.content) {
|
|
898
|
-
if (!Array.isArray(paragraph)) continue;
|
|
899
|
-
let renderedParagraph = "";
|
|
900
|
-
for (const element of paragraph) renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, options.renderMediaPlaceholders !== false);
|
|
901
|
-
paragraphs.push(renderedParagraph);
|
|
902
|
-
}
|
|
903
|
-
return {
|
|
904
|
-
textContent: [escapeMarkdownText(payload.title.trim()), paragraphs.join("\n").trim()].filter(Boolean).join("\n\n").trim() || (options.emptyTextFallback ?? FALLBACK_POST_TEXT),
|
|
905
|
-
imageKeys,
|
|
906
|
-
mediaKeys,
|
|
907
|
-
mentionedOpenIds
|
|
908
|
-
};
|
|
909
|
-
} catch {
|
|
910
|
-
return {
|
|
911
|
-
textContent: FALLBACK_POST_TEXT,
|
|
912
|
-
imageKeys: [],
|
|
913
|
-
mediaKeys: [],
|
|
914
|
-
mentionedOpenIds: []
|
|
915
|
-
};
|
|
764
|
+
//#region extensions/feishu/src/media.ts
|
|
765
|
+
const FEISHU_MEDIA_HTTP_TIMEOUT_MS = 12e4;
|
|
766
|
+
const FEISHU_VOICE_FILE_NAME = "voice.ogg";
|
|
767
|
+
const FEISHU_VOICE_SAMPLE_RATE_HZ = 48e3;
|
|
768
|
+
const FEISHU_VOICE_BITRATE = "64k";
|
|
769
|
+
const FEISHU_TRANSCODABLE_AUDIO_EXTS = /* @__PURE__ */ new Set([
|
|
770
|
+
".aac",
|
|
771
|
+
".aiff",
|
|
772
|
+
".alac",
|
|
773
|
+
".amr",
|
|
774
|
+
".caf",
|
|
775
|
+
".flac",
|
|
776
|
+
".m4a",
|
|
777
|
+
".mp3",
|
|
778
|
+
".oga",
|
|
779
|
+
".wav",
|
|
780
|
+
".webm",
|
|
781
|
+
".wma"
|
|
782
|
+
]);
|
|
783
|
+
async function runBeforeFeishuMessageDispatch(operation) {
|
|
784
|
+
try {
|
|
785
|
+
return await operation();
|
|
786
|
+
} catch (error) {
|
|
787
|
+
if (error instanceof PlatformMessageNotDispatchedError) throw error;
|
|
788
|
+
throw new PlatformMessageNotDispatchedError(`Feishu media preparation failed before message dispatch: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
916
789
|
}
|
|
917
790
|
}
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
791
|
+
function createConfiguredFeishuMediaClient(params) {
|
|
792
|
+
const account = resolveFeishuRuntimeAccount({
|
|
793
|
+
cfg: params.cfg,
|
|
794
|
+
accountId: params.accountId
|
|
795
|
+
});
|
|
796
|
+
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
797
|
+
return {
|
|
798
|
+
account,
|
|
799
|
+
client: createFeishuClient({
|
|
800
|
+
...account,
|
|
801
|
+
httpTimeoutMs: FEISHU_MEDIA_HTTP_TIMEOUT_MS
|
|
802
|
+
})
|
|
803
|
+
};
|
|
927
804
|
}
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
if (typeof code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(code)) return true;
|
|
933
|
-
const response = err.response;
|
|
934
|
-
if (typeof response?.data?.code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(response.data.code)) return true;
|
|
935
|
-
const cause = err.cause;
|
|
936
|
-
if (cause && cause !== err) return isWithdrawnReplyError(cause);
|
|
937
|
-
return false;
|
|
805
|
+
function asHeaderMap(value) {
|
|
806
|
+
if (!value) return;
|
|
807
|
+
const entries = Object.entries(value);
|
|
808
|
+
if (entries.every(([, entry]) => typeof entry === "string" || Array.isArray(entry))) return Object.fromEntries(entries);
|
|
938
809
|
}
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
const
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
msg_type: params.msgType
|
|
947
|
-
}
|
|
948
|
-
}), errorPrefix, { includeNestedErrorLogId: true });
|
|
949
|
-
assertFeishuMessageApiSuccess(response, errorPrefix);
|
|
950
|
-
return toFeishuSendResult(response, params.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
810
|
+
function extractFeishuUploadKey(response, params) {
|
|
811
|
+
if (!response) throw new Error(`${params.errorPrefix}: empty response`);
|
|
812
|
+
const wrappedResponse = response;
|
|
813
|
+
if (wrappedResponse.code !== void 0 && wrappedResponse.code !== 0) throw new Error(`${params.errorPrefix}: ${wrappedResponse.msg || `code ${wrappedResponse.code}`}`);
|
|
814
|
+
const key = params.key === "image_key" ? wrappedResponse.image_key ?? wrappedResponse.data?.image_key : wrappedResponse.file_key ?? wrappedResponse.data?.file_key;
|
|
815
|
+
if (!key) throw new Error(`${params.errorPrefix}: no ${params.key} returned`);
|
|
816
|
+
return key;
|
|
951
817
|
}
|
|
952
|
-
|
|
953
|
-
if (!
|
|
954
|
-
const
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
msg_type: params.msgType,
|
|
962
|
-
...params.replyInThread ? { reply_in_thread: true } : {}
|
|
963
|
-
}
|
|
964
|
-
}), params.replyErrorPrefix, { includeNestedErrorLogId: true });
|
|
965
|
-
} catch (err) {
|
|
966
|
-
if (!isWithdrawnReplyError(err)) throw err;
|
|
967
|
-
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
968
|
-
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
969
|
-
}
|
|
970
|
-
if (shouldFallbackFromReplyTarget(response)) {
|
|
971
|
-
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
972
|
-
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
818
|
+
function readHeaderValue(headers, name) {
|
|
819
|
+
if (!headers) return;
|
|
820
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
821
|
+
if (normalizeLowercaseStringOrEmpty(key) !== normalizeLowercaseStringOrEmpty(name)) continue;
|
|
822
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
823
|
+
if (Array.isArray(value)) {
|
|
824
|
+
const first = value.find((entry) => typeof entry === "string" && entry.trim());
|
|
825
|
+
if (typeof first === "string") return first.trim();
|
|
826
|
+
}
|
|
973
827
|
}
|
|
974
|
-
assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
|
|
975
|
-
return toFeishuSendResult(response, params.directParams.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
976
|
-
}
|
|
977
|
-
function normalizeCardTemplateVariable(value) {
|
|
978
|
-
if (typeof value === "string") return value;
|
|
979
|
-
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
980
828
|
}
|
|
981
|
-
function
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
if (normalized !== void 0) variables.set(key, normalized);
|
|
988
|
-
}
|
|
829
|
+
function readHttpStatusFromError(error) {
|
|
830
|
+
if (!error || typeof error !== "object") return;
|
|
831
|
+
const response = error.response;
|
|
832
|
+
if (response && typeof response === "object") {
|
|
833
|
+
const status = response.status;
|
|
834
|
+
if (typeof status === "number") return status;
|
|
989
835
|
}
|
|
990
|
-
|
|
836
|
+
const status = error.status;
|
|
837
|
+
return typeof status === "number" ? status : void 0;
|
|
991
838
|
}
|
|
992
|
-
function
|
|
993
|
-
|
|
994
|
-
return text.replace(/\$\{([A-Za-z0-9_.-]+)\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (match, a, b) => {
|
|
995
|
-
const variableName = typeof a === "string" ? a : b;
|
|
996
|
-
return variables.get(variableName) ?? match;
|
|
997
|
-
});
|
|
839
|
+
function isHttpStatusError(error, status) {
|
|
840
|
+
return readHttpStatusFromError(error) === status;
|
|
998
841
|
}
|
|
999
|
-
function
|
|
1000
|
-
|
|
1001
|
-
const tag = typeof element.tag === "string" ? element.tag : "";
|
|
1002
|
-
const text = isRecord(element.text) ? element.text : void 0;
|
|
1003
|
-
if (tag === "div" && typeof text?.content === "string") return applyCardTemplateVariables(text.content, variables);
|
|
1004
|
-
if ((tag === "markdown" || tag === "lark_md") && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
|
|
1005
|
-
if (tag === "plain_text" && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
|
|
842
|
+
function containsEastAsianScript(value) {
|
|
843
|
+
return /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(value);
|
|
1006
844
|
}
|
|
1007
|
-
function
|
|
1008
|
-
const
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
if (text !== void 0) texts.push(text);
|
|
1012
|
-
}
|
|
1013
|
-
return texts.join("\n").trim();
|
|
845
|
+
function recoverUtf8FileNameFromLatin1Header(value) {
|
|
846
|
+
const recovered = Buffer.from(value, "latin1").toString("utf8");
|
|
847
|
+
if (recovered !== value && !recovered.includes("�") && containsEastAsianScript(recovered)) return recovered;
|
|
848
|
+
return value;
|
|
1014
849
|
}
|
|
1015
|
-
function
|
|
1016
|
-
const
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
for (const localeElements of Object.values(candidate)) if (Array.isArray(localeElements)) elementArrays.push(localeElements);
|
|
850
|
+
function decodeDispositionFileName(value) {
|
|
851
|
+
const utf8Match = value.match(/filename\*=UTF-8''([^;]+)/i);
|
|
852
|
+
if (utf8Match?.[1]) try {
|
|
853
|
+
return decodeURIComponent(utf8Match[1].trim().replace(/^"(.*)"$/, "$1"));
|
|
854
|
+
} catch {
|
|
855
|
+
return utf8Match[1].trim().replace(/^"(.*)"$/, "$1");
|
|
1022
856
|
}
|
|
1023
|
-
|
|
857
|
+
const plainFileName = value.match(/filename="?([^";]+)"?/i)?.[1]?.trim();
|
|
858
|
+
return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : void 0;
|
|
1024
859
|
}
|
|
1025
|
-
function
|
|
1026
|
-
const
|
|
1027
|
-
|
|
860
|
+
function extractFeishuDownloadMetadata(response) {
|
|
861
|
+
const responseWithOptionalFields = response;
|
|
862
|
+
const headers = asHeaderMap(responseWithOptionalFields.headers) ?? asHeaderMap(responseWithOptionalFields.header);
|
|
863
|
+
const contentType = readHeaderValue(headers, "content-type") ?? responseWithOptionalFields.contentType ?? responseWithOptionalFields.mime_type ?? responseWithOptionalFields.data?.contentType ?? responseWithOptionalFields.data?.mime_type;
|
|
864
|
+
const disposition = readHeaderValue(headers, "content-disposition");
|
|
865
|
+
return {
|
|
866
|
+
contentType,
|
|
867
|
+
fileName: (disposition ? decodeDispositionFileName(disposition) : void 0) ?? responseWithOptionalFields.file_name ?? responseWithOptionalFields.fileName ?? responseWithOptionalFields.data?.file_name ?? responseWithOptionalFields.data?.fileName
|
|
868
|
+
};
|
|
1028
869
|
}
|
|
1029
|
-
function
|
|
1030
|
-
|
|
1031
|
-
const variables = readCardTemplateVariables(parsed);
|
|
1032
|
-
for (const elements of readInteractiveElementArrays(parsed)) {
|
|
1033
|
-
const text = extractInteractiveElementsText(elements, variables);
|
|
1034
|
-
if (text) return text;
|
|
1035
|
-
}
|
|
1036
|
-
return parseInteractivePostFallback(parsed) ?? INTERACTIVE_CARD_FALLBACK_TEXT;
|
|
870
|
+
function mediaLimitError(maxBytes) {
|
|
871
|
+
return /* @__PURE__ */ new Error(`Media exceeds ${Math.round(maxBytes / (1024 * 1024))}MB limit`);
|
|
1037
872
|
}
|
|
1038
|
-
function
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
if (
|
|
1055
|
-
const
|
|
1056
|
-
|
|
1057
|
-
return `[${msgType || "unknown"} message]`;
|
|
873
|
+
async function saveFeishuResponseMedia(params) {
|
|
874
|
+
const { response, maxBytes, contentType, fileName } = params;
|
|
875
|
+
if (Buffer.isBuffer(response)) return saveMediaBuffer(response, contentType, "inbound", maxBytes, fileName);
|
|
876
|
+
if (response instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(response), contentType, "inbound", maxBytes, fileName);
|
|
877
|
+
const responseWithOptionalFields = response;
|
|
878
|
+
if (responseWithOptionalFields.code !== void 0 && responseWithOptionalFields.code !== 0) throw new Error(`${params.errorPrefix}: ${responseWithOptionalFields.msg || `code ${responseWithOptionalFields.code}`}`);
|
|
879
|
+
if (responseWithOptionalFields.data && Buffer.isBuffer(responseWithOptionalFields.data)) return saveMediaBuffer(responseWithOptionalFields.data, contentType, "inbound", maxBytes, fileName);
|
|
880
|
+
if (responseWithOptionalFields.data instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(responseWithOptionalFields.data), contentType, "inbound", maxBytes, fileName);
|
|
881
|
+
const save = (stream, ct = contentType, mb = maxBytes, fn = fileName) => saveMediaStreamWithIdleTimeout(stream, ct, mb, fn, FEISHU_MEDIA_HTTP_TIMEOUT_MS);
|
|
882
|
+
if (typeof response.getReadableStream === "function") return save(response.getReadableStream());
|
|
883
|
+
if (typeof response.writeFile === "function") return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
|
|
884
|
+
await response.writeFile(tmpPath);
|
|
885
|
+
if ((await fs.promises.stat(tmpPath)).size > maxBytes) throw mediaLimitError(maxBytes);
|
|
886
|
+
return await save(fs.createReadStream(tmpPath));
|
|
887
|
+
});
|
|
888
|
+
if (responseWithOptionalFields[Symbol.asyncIterator]) return save(responseWithOptionalFields);
|
|
889
|
+
if (response instanceof Readable) return save(response);
|
|
890
|
+
const keys = Object.keys(response);
|
|
891
|
+
throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${keys.join(", ")}]`);
|
|
1058
892
|
}
|
|
1059
|
-
function
|
|
1060
|
-
const
|
|
1061
|
-
|
|
893
|
+
async function saveMessageResourceWithType(params) {
|
|
894
|
+
const response = await params.client.im.messageResource.get({
|
|
895
|
+
path: {
|
|
896
|
+
message_id: params.messageId,
|
|
897
|
+
file_key: params.fileKey
|
|
898
|
+
},
|
|
899
|
+
params: { type: params.type }
|
|
900
|
+
});
|
|
901
|
+
const meta = extractFeishuDownloadMetadata(response);
|
|
1062
902
|
return {
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
threadId: item.thread_id || void 0
|
|
903
|
+
saved: await saveFeishuResponseMedia({
|
|
904
|
+
response,
|
|
905
|
+
tmpDirPrefix: "openclaw-feishu-resource-",
|
|
906
|
+
errorPrefix: "Feishu message resource download failed",
|
|
907
|
+
maxBytes: params.maxBytes,
|
|
908
|
+
contentType: meta.contentType,
|
|
909
|
+
fileName: meta.fileName ?? (params.originalFilename ? recoverUtf8FileNameFromLatin1Header(params.originalFilename) : void 0)
|
|
910
|
+
}),
|
|
911
|
+
...meta
|
|
1073
912
|
};
|
|
1074
913
|
}
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
const { cfg, messageId, accountId } = params;
|
|
1081
|
-
const account = resolveFeishuRuntimeAccount({
|
|
914
|
+
async function saveMessageResourceFeishu(params) {
|
|
915
|
+
const { cfg, messageId, fileKey, type, accountId, maxBytes, originalFilename } = params;
|
|
916
|
+
const normalizedFileKey = normalizeFeishuExternalKey(fileKey);
|
|
917
|
+
if (!normalizedFileKey) throw new Error("Feishu message resource download failed: invalid file_key");
|
|
918
|
+
const { client } = createConfiguredFeishuMediaClient({
|
|
1082
919
|
cfg,
|
|
1083
920
|
accountId
|
|
1084
921
|
});
|
|
1085
|
-
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
1086
|
-
const client = createFeishuClient(account);
|
|
1087
922
|
try {
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
923
|
+
return await saveMessageResourceWithType({
|
|
924
|
+
client,
|
|
925
|
+
messageId,
|
|
926
|
+
fileKey: normalizedFileKey,
|
|
927
|
+
type,
|
|
928
|
+
maxBytes,
|
|
929
|
+
originalFilename
|
|
1091
930
|
});
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
931
|
+
} catch (err) {
|
|
932
|
+
if (type !== "file" || !isHttpStatusError(err, 502)) throw err;
|
|
933
|
+
try {
|
|
934
|
+
return await saveMessageResourceWithType({
|
|
935
|
+
client,
|
|
936
|
+
messageId,
|
|
937
|
+
fileKey: normalizedFileKey,
|
|
938
|
+
type: "media",
|
|
939
|
+
maxBytes,
|
|
940
|
+
originalFilename
|
|
941
|
+
});
|
|
942
|
+
} catch {
|
|
943
|
+
throw err;
|
|
944
|
+
}
|
|
1099
945
|
}
|
|
1100
946
|
}
|
|
1101
947
|
/**
|
|
1102
|
-
*
|
|
1103
|
-
*
|
|
1104
|
-
* which includes both the root message and all replies (including bot replies).
|
|
948
|
+
* Upload an image to Feishu and get an image_key for sending.
|
|
949
|
+
* Supports: JPEG, PNG, WEBP, GIF, TIFF, BMP, ICO
|
|
1105
950
|
*/
|
|
1106
|
-
async function
|
|
1107
|
-
const { cfg,
|
|
1108
|
-
const
|
|
951
|
+
async function uploadImageFeishu(params) {
|
|
952
|
+
const { cfg, image, imageType = "message", accountId } = params;
|
|
953
|
+
const { client } = createConfiguredFeishuMediaClient({
|
|
1109
954
|
cfg,
|
|
1110
955
|
accountId
|
|
1111
956
|
});
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
} }
|
|
1120
|
-
if (response.code !== 0) throw new Error(`Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`);
|
|
1121
|
-
const items = response.data?.items ?? [];
|
|
1122
|
-
const results = [];
|
|
1123
|
-
for (const item of items) {
|
|
1124
|
-
if (currentMessageId && item.message_id === currentMessageId) continue;
|
|
1125
|
-
if (rootMessageId && item.message_id === rootMessageId) continue;
|
|
1126
|
-
const parsed = parseFeishuMessageItem(item);
|
|
1127
|
-
results.push({
|
|
1128
|
-
messageId: parsed.messageId,
|
|
1129
|
-
senderId: parsed.senderId,
|
|
1130
|
-
senderType: parsed.senderType,
|
|
1131
|
-
content: parsed.content,
|
|
1132
|
-
contentType: parsed.contentType,
|
|
1133
|
-
createTime: parsed.createTime
|
|
1134
|
-
});
|
|
1135
|
-
if (results.length >= limit) break;
|
|
1136
|
-
}
|
|
1137
|
-
results.reverse();
|
|
1138
|
-
return results;
|
|
957
|
+
const imageData = typeof image === "string" ? (await readRegularFile({ filePath: image })).buffer : image;
|
|
958
|
+
return { imageKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.image.create({ data: {
|
|
959
|
+
image_type: imageType,
|
|
960
|
+
image: imageData
|
|
961
|
+
} }), "Feishu image upload failed", { includeNestedErrorLogId: true }), {
|
|
962
|
+
key: "image_key",
|
|
963
|
+
errorPrefix: "Feishu image upload failed"
|
|
964
|
+
}) };
|
|
1139
965
|
}
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
966
|
+
/**
|
|
967
|
+
* Sanitize a filename for safe use in Feishu multipart/form-data uploads.
|
|
968
|
+
* Strips control characters and multipart-injection vectors (CWE-93) while
|
|
969
|
+
* preserving the original UTF-8 display name (Chinese, emoji, etc.).
|
|
970
|
+
*
|
|
971
|
+
* Previous versions percent-encoded non-ASCII characters, but the Feishu
|
|
972
|
+
* `im.file.create` API uses `file_name` as a literal display name — it does
|
|
973
|
+
* NOT decode percent-encoding — so encoded filenames appeared as garbled text
|
|
974
|
+
* in chat (regression in v2026.3.2).
|
|
975
|
+
*/
|
|
976
|
+
function sanitizeFileNameForUpload(fileName) {
|
|
977
|
+
return fileName.replace(/[\p{Cc}"\\]/gu, "_");
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Upload a file to Feishu and get a file_key for sending.
|
|
981
|
+
* Max file size: 30MB
|
|
982
|
+
*/
|
|
983
|
+
async function uploadFileFeishu(params) {
|
|
984
|
+
const { cfg, file, fileName, fileType, duration, accountId } = params;
|
|
985
|
+
const { client } = createConfiguredFeishuMediaClient({
|
|
1143
986
|
cfg,
|
|
1144
|
-
to,
|
|
1145
987
|
accountId
|
|
1146
988
|
});
|
|
1147
|
-
const
|
|
989
|
+
const fileData = typeof file === "string" ? (await readRegularFile({ filePath: file })).buffer : file;
|
|
990
|
+
const safeFileName = sanitizeFileNameForUpload(fileName);
|
|
991
|
+
return { fileKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.file.create({ data: {
|
|
992
|
+
file_type: fileType,
|
|
993
|
+
file_name: safeFileName,
|
|
994
|
+
file: fileData,
|
|
995
|
+
...duration !== void 0 ? { duration } : {}
|
|
996
|
+
} }), "Feishu file upload failed", { includeNestedErrorLogId: true }), {
|
|
997
|
+
key: "file_key",
|
|
998
|
+
errorPrefix: "Feishu file upload failed"
|
|
999
|
+
}) };
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Send an image message using an image_key
|
|
1003
|
+
*/
|
|
1004
|
+
async function sendImageFeishu(params) {
|
|
1005
|
+
const { cfg, to, imageKey, replyToMessageId, replyInThread, allowTopLevelReplyFallback, accountId } = params;
|
|
1006
|
+
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
1148
1007
|
cfg,
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
const content = buildFeishuPostMessageContent({
|
|
1152
|
-
messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text ?? "", tableMode)),
|
|
1153
|
-
mentions
|
|
1008
|
+
to,
|
|
1009
|
+
accountId
|
|
1154
1010
|
});
|
|
1155
|
-
const
|
|
1156
|
-
|
|
1157
|
-
return sendReplyOrFallbackDirect(client, {
|
|
1011
|
+
const content = JSON.stringify({ image_key: imageKey });
|
|
1012
|
+
if (replyToMessageId) return sendReplyOrFallbackDirect(client, {
|
|
1158
1013
|
replyToMessageId,
|
|
1159
1014
|
replyInThread,
|
|
1160
1015
|
allowTopLevelReplyFallback,
|
|
1161
1016
|
content,
|
|
1162
|
-
msgType,
|
|
1017
|
+
msgType: "image",
|
|
1163
1018
|
directParams: {
|
|
1164
1019
|
receiveId,
|
|
1165
1020
|
receiveIdType,
|
|
1166
1021
|
content,
|
|
1167
|
-
msgType
|
|
1022
|
+
msgType: "image"
|
|
1168
1023
|
},
|
|
1169
|
-
directErrorPrefix: "Feishu send failed",
|
|
1170
|
-
replyErrorPrefix: "Feishu reply failed"
|
|
1024
|
+
directErrorPrefix: "Feishu image send failed",
|
|
1025
|
+
replyErrorPrefix: "Feishu image reply failed"
|
|
1171
1026
|
});
|
|
1027
|
+
const response = await requestFeishuApi(() => client.im.message.create({
|
|
1028
|
+
params: { receive_id_type: receiveIdType },
|
|
1029
|
+
data: {
|
|
1030
|
+
receive_id: receiveId,
|
|
1031
|
+
content,
|
|
1032
|
+
msg_type: "image"
|
|
1033
|
+
}
|
|
1034
|
+
}), "Feishu image send failed", { includeNestedErrorLogId: true });
|
|
1035
|
+
assertFeishuMessageApiSuccess(response, "Feishu image send failed");
|
|
1036
|
+
return toFeishuSendResult(response, receiveId, "media");
|
|
1172
1037
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
1038
|
+
/**
|
|
1039
|
+
* Send a file message using a file_key
|
|
1040
|
+
*/
|
|
1041
|
+
async function sendFileFeishu(params) {
|
|
1042
|
+
const { cfg, to, fileKey, replyToMessageId, replyInThread, allowTopLevelReplyFallback, accountId } = params;
|
|
1043
|
+
const msgType = params.msgType ?? "file";
|
|
1175
1044
|
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
1176
1045
|
cfg,
|
|
1177
1046
|
to,
|
|
1178
1047
|
accountId
|
|
1179
1048
|
});
|
|
1180
|
-
const content = JSON.stringify(
|
|
1181
|
-
return sendReplyOrFallbackDirect(client, {
|
|
1049
|
+
const content = JSON.stringify({ file_key: fileKey });
|
|
1050
|
+
if (replyToMessageId) return sendReplyOrFallbackDirect(client, {
|
|
1182
1051
|
replyToMessageId,
|
|
1183
1052
|
replyInThread,
|
|
1184
1053
|
allowTopLevelReplyFallback,
|
|
1185
1054
|
content,
|
|
1186
|
-
msgType
|
|
1055
|
+
msgType,
|
|
1187
1056
|
directParams: {
|
|
1188
1057
|
receiveId,
|
|
1189
1058
|
receiveIdType,
|
|
1190
1059
|
content,
|
|
1191
|
-
msgType
|
|
1060
|
+
msgType
|
|
1192
1061
|
},
|
|
1193
|
-
directErrorPrefix: "Feishu
|
|
1194
|
-
replyErrorPrefix: "Feishu
|
|
1062
|
+
directErrorPrefix: "Feishu file send failed",
|
|
1063
|
+
replyErrorPrefix: "Feishu file reply failed"
|
|
1064
|
+
});
|
|
1065
|
+
const response = await requestFeishuApi(() => client.im.message.create({
|
|
1066
|
+
params: { receive_id_type: receiveIdType },
|
|
1067
|
+
data: {
|
|
1068
|
+
receive_id: receiveId,
|
|
1069
|
+
content,
|
|
1070
|
+
msg_type: msgType
|
|
1071
|
+
}
|
|
1072
|
+
}), "Feishu file send failed", { includeNestedErrorLogId: true });
|
|
1073
|
+
assertFeishuMessageApiSuccess(response, "Feishu file send failed");
|
|
1074
|
+
return toFeishuSendResult(response, receiveId, resolveFeishuReceiptKind(msgType));
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Helper to detect file type from extension
|
|
1078
|
+
*/
|
|
1079
|
+
function detectFileType(fileName) {
|
|
1080
|
+
switch (normalizeLowercaseStringOrEmpty(path.extname(fileName))) {
|
|
1081
|
+
case ".opus":
|
|
1082
|
+
case ".ogg": return "opus";
|
|
1083
|
+
case ".mp4":
|
|
1084
|
+
case ".mov":
|
|
1085
|
+
case ".avi": return "mp4";
|
|
1086
|
+
case ".pdf": return "pdf";
|
|
1087
|
+
case ".doc":
|
|
1088
|
+
case ".docx": return "doc";
|
|
1089
|
+
case ".xls":
|
|
1090
|
+
case ".xlsx": return "xls";
|
|
1091
|
+
case ".ppt":
|
|
1092
|
+
case ".pptx": return "ppt";
|
|
1093
|
+
default: return "stream";
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
function resolveFeishuOutboundMediaKind(params) {
|
|
1097
|
+
const { fileName, contentType } = params;
|
|
1098
|
+
const ext = normalizeLowercaseStringOrEmpty(path.extname(fileName));
|
|
1099
|
+
const mimeKind = mediaKindFromMime(contentType);
|
|
1100
|
+
if ([
|
|
1101
|
+
".jpg",
|
|
1102
|
+
".jpeg",
|
|
1103
|
+
".png",
|
|
1104
|
+
".gif",
|
|
1105
|
+
".webp",
|
|
1106
|
+
".bmp",
|
|
1107
|
+
".ico",
|
|
1108
|
+
".tiff"
|
|
1109
|
+
].includes(ext) || mimeKind === "image") return { msgType: "image" };
|
|
1110
|
+
if (ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus") return {
|
|
1111
|
+
fileType: "opus",
|
|
1112
|
+
msgType: "audio"
|
|
1113
|
+
};
|
|
1114
|
+
if ([
|
|
1115
|
+
".mp4",
|
|
1116
|
+
".mov",
|
|
1117
|
+
".avi"
|
|
1118
|
+
].includes(ext) || contentType === "video/mp4" || contentType === "video/quicktime" || contentType === "video/x-msvideo") return {
|
|
1119
|
+
fileType: "mp4",
|
|
1120
|
+
msgType: "media"
|
|
1121
|
+
};
|
|
1122
|
+
const fileType = detectFileType(fileName);
|
|
1123
|
+
return {
|
|
1124
|
+
fileType,
|
|
1125
|
+
msgType: fileType === "stream" ? "file" : fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file"
|
|
1126
|
+
};
|
|
1127
|
+
}
|
|
1128
|
+
function isFeishuNativeVoiceAudio(params) {
|
|
1129
|
+
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
1130
|
+
const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
|
|
1131
|
+
return ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus";
|
|
1132
|
+
}
|
|
1133
|
+
function normalizeMediaNameForExtension(raw) {
|
|
1134
|
+
try {
|
|
1135
|
+
return new URL(raw).pathname;
|
|
1136
|
+
} catch {
|
|
1137
|
+
return raw.split(/[?#]/, 1)[0] ?? raw;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
function shouldSuppressFeishuTextForVoiceMedia(params) {
|
|
1141
|
+
if (params.ttsSupplement) return params.ttsSupplement.visibleTextAlreadyDelivered === true;
|
|
1142
|
+
if (params.audioAsVoice === true) return true;
|
|
1143
|
+
if (params.fileName && isFeishuNativeVoiceAudio({
|
|
1144
|
+
fileName: params.fileName,
|
|
1145
|
+
contentType: params.contentType
|
|
1146
|
+
})) return true;
|
|
1147
|
+
if (!params.mediaUrl) return false;
|
|
1148
|
+
return isFeishuNativeVoiceAudio({
|
|
1149
|
+
fileName: normalizeMediaNameForExtension(params.mediaUrl),
|
|
1150
|
+
contentType: params.contentType
|
|
1195
1151
|
});
|
|
1196
1152
|
}
|
|
1197
|
-
|
|
1198
|
-
const
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
const
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1210
|
-
|
|
1153
|
+
function isLikelyTranscodableAudio(params) {
|
|
1154
|
+
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
1155
|
+
const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
|
|
1156
|
+
return FEISHU_TRANSCODABLE_AUDIO_EXTS.has(ext) || mediaKindFromMime(contentType) === "audio";
|
|
1157
|
+
}
|
|
1158
|
+
async function transcodeToFeishuVoiceOpus(params) {
|
|
1159
|
+
return await withTempWorkspace({
|
|
1160
|
+
rootDir: resolvePreferredOpenClawTmpDir(),
|
|
1161
|
+
prefix: "feishu-voice-"
|
|
1162
|
+
}, async (workspace) => {
|
|
1163
|
+
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
1164
|
+
const inputExt = ext && ext.length <= 12 ? ext : ".audio";
|
|
1165
|
+
const inputPath = await workspace.write(`input${inputExt}`, params.buffer);
|
|
1166
|
+
await writeExternalFileWithinRoot({
|
|
1167
|
+
rootDir: workspace.dir,
|
|
1168
|
+
path: FEISHU_VOICE_FILE_NAME,
|
|
1169
|
+
write: async (outputPath) => {
|
|
1170
|
+
await runFfmpeg([
|
|
1171
|
+
"-hide_banner",
|
|
1172
|
+
"-loglevel",
|
|
1173
|
+
"error",
|
|
1174
|
+
"-y",
|
|
1175
|
+
"-i",
|
|
1176
|
+
inputPath,
|
|
1177
|
+
"-vn",
|
|
1178
|
+
"-sn",
|
|
1179
|
+
"-dn",
|
|
1180
|
+
"-t",
|
|
1181
|
+
String(MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS),
|
|
1182
|
+
"-ar",
|
|
1183
|
+
String(FEISHU_VOICE_SAMPLE_RATE_HZ),
|
|
1184
|
+
"-ac",
|
|
1185
|
+
"1",
|
|
1186
|
+
"-c:a",
|
|
1187
|
+
"libopus",
|
|
1188
|
+
"-b:a",
|
|
1189
|
+
FEISHU_VOICE_BITRATE,
|
|
1190
|
+
"-f",
|
|
1191
|
+
"ogg",
|
|
1192
|
+
outputPath
|
|
1193
|
+
]);
|
|
1194
|
+
}
|
|
1211
1195
|
});
|
|
1212
|
-
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
1213
1196
|
return {
|
|
1214
|
-
|
|
1215
|
-
|
|
1197
|
+
buffer: await workspace.read(FEISHU_VOICE_FILE_NAME),
|
|
1198
|
+
fileName: FEISHU_VOICE_FILE_NAME,
|
|
1199
|
+
contentType: "audio/ogg"
|
|
1216
1200
|
};
|
|
1217
|
-
}
|
|
1218
|
-
const content = buildFeishuPostMessageContent({ messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text, resolveMarkdownTableMode({
|
|
1219
|
-
cfg,
|
|
1220
|
-
channel: "feishu"
|
|
1221
|
-
}))) });
|
|
1222
|
-
assertFeishuPostWithinEnvelope(content, "Feishu message edit");
|
|
1223
|
-
const response = await client.im.message.patch({
|
|
1224
|
-
path: { message_id: messageId },
|
|
1225
|
-
data: { content }
|
|
1226
1201
|
});
|
|
1227
|
-
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
1228
|
-
return {
|
|
1229
|
-
messageId,
|
|
1230
|
-
contentType: "post"
|
|
1231
|
-
};
|
|
1232
1202
|
}
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
body: { elements: [{
|
|
1243
|
-
tag: "markdown",
|
|
1244
|
-
content: text
|
|
1245
|
-
}] }
|
|
1246
|
-
};
|
|
1203
|
+
async function prepareFeishuVoiceMedia(params) {
|
|
1204
|
+
if (isFeishuNativeVoiceAudio(params)) return params;
|
|
1205
|
+
if (params.audioAsVoice !== true || !isLikelyTranscodableAudio(params)) return params;
|
|
1206
|
+
try {
|
|
1207
|
+
return await transcodeToFeishuVoiceOpus(params);
|
|
1208
|
+
} catch (err) {
|
|
1209
|
+
console.warn(`[feishu] audioAsVoice transcode failed; sending ${params.fileName} as a file attachment:`, err);
|
|
1210
|
+
return params;
|
|
1211
|
+
}
|
|
1247
1212
|
}
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1213
|
+
async function probeMediaDurationMs(params) {
|
|
1214
|
+
try {
|
|
1215
|
+
return await withTempWorkspace({
|
|
1216
|
+
rootDir: resolvePreferredOpenClawTmpDir(),
|
|
1217
|
+
prefix: "feishu-media-probe-"
|
|
1218
|
+
}, async (workspace) => {
|
|
1219
|
+
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
1220
|
+
const inferredExt = ext && ext.length <= 12 ? ext : mediaKindFromMime(params.contentType) === "video" ? ".mp4" : ".ogg";
|
|
1221
|
+
const stdout = await runFfprobe([
|
|
1222
|
+
"-v",
|
|
1223
|
+
"error",
|
|
1224
|
+
"-show_entries",
|
|
1225
|
+
"format=duration",
|
|
1226
|
+
"-of",
|
|
1227
|
+
"csv=p=0",
|
|
1228
|
+
await workspace.write(`input${inferredExt}`, params.buffer)
|
|
1229
|
+
], { timeoutMs: 5e3 });
|
|
1230
|
+
const seconds = Number.parseFloat(stdout.trim());
|
|
1231
|
+
if (!Number.isFinite(seconds) || seconds <= 0) return;
|
|
1232
|
+
return Math.max(1, Math.round(seconds * 1e3));
|
|
1262
1233
|
});
|
|
1234
|
+
} catch (err) {
|
|
1235
|
+
console.warn("[feishu] failed to probe media duration; upload will omit it:", err);
|
|
1236
|
+
return;
|
|
1263
1237
|
}
|
|
1264
|
-
const card = {
|
|
1265
|
-
schema: "2.0",
|
|
1266
|
-
config: { width_mode: "fill" },
|
|
1267
|
-
body: { elements }
|
|
1268
|
-
};
|
|
1269
|
-
if (options?.header) card.header = {
|
|
1270
|
-
title: {
|
|
1271
|
-
tag: "plain_text",
|
|
1272
|
-
content: options.header.title
|
|
1273
|
-
},
|
|
1274
|
-
template: resolveFeishuCardTemplate(options.header.template) ?? "blue"
|
|
1275
|
-
};
|
|
1276
|
-
return card;
|
|
1277
1238
|
}
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
async function sendStructuredCardFeishu(params) {
|
|
1282
|
-
const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId, header, note } = params;
|
|
1283
|
-
let cardText = text;
|
|
1284
|
-
if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
|
|
1285
|
-
return sendCardFeishu({
|
|
1286
|
-
cfg,
|
|
1287
|
-
to,
|
|
1288
|
-
card: buildStructuredCard(cardText, {
|
|
1289
|
-
header,
|
|
1290
|
-
note
|
|
1291
|
-
}),
|
|
1292
|
-
replyToMessageId,
|
|
1293
|
-
replyInThread,
|
|
1294
|
-
allowTopLevelReplyFallback,
|
|
1295
|
-
accountId
|
|
1296
|
-
});
|
|
1239
|
+
async function maybeProbeUploadDurationMs(params) {
|
|
1240
|
+
if (params.msgType !== "audio" && params.msgType !== "media") return;
|
|
1241
|
+
return await probeMediaDurationMs(params);
|
|
1297
1242
|
}
|
|
1298
1243
|
/**
|
|
1299
|
-
*
|
|
1300
|
-
*
|
|
1244
|
+
* Upload and send media (image or file) from URL, local path, or buffer.
|
|
1245
|
+
* When mediaUrl is a local path, mediaLocalRoots (from core outbound context)
|
|
1246
|
+
* must be passed so loadWebMedia allows the path (post CVE-2026-26321).
|
|
1301
1247
|
*/
|
|
1302
|
-
async function
|
|
1303
|
-
const { cfg, to,
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1248
|
+
async function sendMediaFeishu(params) {
|
|
1249
|
+
const { cfg, to, mediaUrl, mediaBuffer, fileName, replyToMessageId, replyInThread, allowTopLevelReplyFallback, accountId, mediaLocalRoots, audioAsVoice } = params;
|
|
1250
|
+
const mediaMaxBytes = ((await runBeforeFeishuMessageDispatch(() => {
|
|
1251
|
+
const resolved = resolveFeishuRuntimeAccount({
|
|
1252
|
+
cfg,
|
|
1253
|
+
accountId
|
|
1254
|
+
});
|
|
1255
|
+
if (!resolved.configured) throw new Error(`Feishu account "${resolved.accountId}" not configured`);
|
|
1256
|
+
return resolved;
|
|
1257
|
+
})).config?.mediaMaxMb ?? 30) * 1024 * 1024;
|
|
1258
|
+
let buffer;
|
|
1259
|
+
let name;
|
|
1260
|
+
let contentType;
|
|
1261
|
+
const loaded = await runBeforeFeishuMessageDispatch(async () => {
|
|
1262
|
+
if (mediaBuffer) return {
|
|
1263
|
+
buffer: mediaBuffer,
|
|
1264
|
+
name: fileName ?? "file",
|
|
1265
|
+
contentType: void 0
|
|
1266
|
+
};
|
|
1267
|
+
if (mediaUrl) {
|
|
1268
|
+
const media = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
|
|
1269
|
+
maxBytes: mediaMaxBytes,
|
|
1270
|
+
optimizeImages: false,
|
|
1271
|
+
localRoots: mediaLocalRoots?.length ? mediaLocalRoots : void 0
|
|
1272
|
+
});
|
|
1273
|
+
return {
|
|
1274
|
+
buffer: media.buffer,
|
|
1275
|
+
name: fileName ?? media.fileName ?? "file",
|
|
1276
|
+
contentType: media.contentType
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
throw new Error("Either mediaUrl or mediaBuffer must be provided");
|
|
1280
|
+
});
|
|
1281
|
+
buffer = loaded.buffer;
|
|
1282
|
+
name = loaded.name;
|
|
1283
|
+
contentType = loaded.contentType;
|
|
1284
|
+
const prepared = await runBeforeFeishuMessageDispatch(() => prepareFeishuVoiceMedia({
|
|
1285
|
+
buffer,
|
|
1286
|
+
fileName: name,
|
|
1287
|
+
contentType,
|
|
1288
|
+
audioAsVoice
|
|
1289
|
+
}));
|
|
1290
|
+
buffer = prepared.buffer;
|
|
1291
|
+
name = prepared.fileName;
|
|
1292
|
+
contentType = prepared.contentType;
|
|
1293
|
+
const routing = resolveFeishuOutboundMediaKind({
|
|
1294
|
+
fileName: name,
|
|
1295
|
+
contentType
|
|
1296
|
+
});
|
|
1297
|
+
const voiceIntentDegradedToFile = audioAsVoice === true && routing.msgType !== "audio";
|
|
1298
|
+
if (routing.msgType === "image") {
|
|
1299
|
+
const { imageKey } = await runBeforeFeishuMessageDispatch(() => uploadImageFeishu({
|
|
1300
|
+
cfg,
|
|
1301
|
+
image: buffer,
|
|
1302
|
+
accountId
|
|
1303
|
+
}));
|
|
1304
|
+
return {
|
|
1305
|
+
...await sendImageFeishu({
|
|
1306
|
+
cfg,
|
|
1307
|
+
to,
|
|
1308
|
+
imageKey,
|
|
1309
|
+
replyToMessageId,
|
|
1310
|
+
replyInThread,
|
|
1311
|
+
allowTopLevelReplyFallback,
|
|
1312
|
+
accountId
|
|
1313
|
+
}),
|
|
1314
|
+
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
const durationMs = await maybeProbeUploadDurationMs({
|
|
1318
|
+
buffer,
|
|
1319
|
+
fileName: name,
|
|
1320
|
+
contentType,
|
|
1321
|
+
msgType: routing.msgType
|
|
1322
|
+
});
|
|
1323
|
+
const { fileKey } = await runBeforeFeishuMessageDispatch(() => uploadFileFeishu({
|
|
1307
1324
|
cfg,
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
allowTopLevelReplyFallback,
|
|
1325
|
+
file: buffer,
|
|
1326
|
+
fileName: name,
|
|
1327
|
+
fileType: routing.fileType ?? "stream",
|
|
1328
|
+
...durationMs !== void 0 ? { duration: durationMs } : {},
|
|
1313
1329
|
accountId
|
|
1314
|
-
});
|
|
1330
|
+
}));
|
|
1331
|
+
return {
|
|
1332
|
+
...await sendFileFeishu({
|
|
1333
|
+
cfg,
|
|
1334
|
+
to,
|
|
1335
|
+
fileKey,
|
|
1336
|
+
msgType: routing.msgType,
|
|
1337
|
+
replyToMessageId,
|
|
1338
|
+
replyInThread,
|
|
1339
|
+
allowTopLevelReplyFallback,
|
|
1340
|
+
accountId
|
|
1341
|
+
}),
|
|
1342
|
+
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
1343
|
+
};
|
|
1315
1344
|
}
|
|
1316
1345
|
//#endregion
|
|
1317
|
-
export { buildFeishuMediaFallbackText as _,
|
|
1346
|
+
export { buildFeishuMediaFallbackText as _, getMessageFeishu as a, sendMarkdownCardFeishu as c, parsePostContent as d, extractMentionTargets as f, normalizeFeishuExternalKey as g, isFeishuGroupChatType as h, editMessageFeishu as i, sendMessageFeishu as l, isMentionForwardRequest as m, sendMediaFeishu as n, listFeishuThreadMessages as o, isFeishuBroadcastMention as p, shouldSuppressFeishuTextForVoiceMedia as r, sendCardFeishu as s, saveMessageResourceFeishu as t, sendStructuredCardFeishu as u, resolveFeishuIdentityEmoji as v, resolveFeishuIdentityHeaderTitle as y };
|