@openclaw/feishu 2026.7.2-beta.2 → 2026.7.2-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api.js +4 -4
- package/dist/{app-registration-BzkyrVZu.js → app-registration-cN1bVV6s.js} +5 -5
- package/dist/{channel-X30GQVwc.js → channel-DB1x6UJX.js} +33 -24
- package/dist/channel-plugin-api.js +1 -1
- package/dist/{channel.runtime-By2uqa3Q.js → channel.runtime-B5yAAvbT.js} +102 -17
- package/dist/{client-87BmeMpj.js → client-Dee7cKsS.js} +62 -1
- package/dist/{doctor-contract-DXH5hux1.js → doctor-contract-Cw5sdjOm.js} +29 -41
- package/dist/doctor-contract-api.js +1 -1
- package/dist/{drive-B4E8OXZ0.js → drive-_zrcOxzS.js} +2 -2
- package/dist/{send-DrWM_Ilf.js → media-CRJunSRr.js} +1075 -1017
- package/dist/{monitor-CHl0bWzb.js → monitor-8CLu6myv.js} +5 -4
- package/dist/{monitor.account-BSRV2hIF.js → monitor.account-CkYj45PC.js} +2113 -809
- package/dist/monitor.startup-CSUPT_U1.js +143 -0
- package/dist/{probe-BgboTHIn.js → probe-Za1kgUvx.js} +70 -10
- package/dist/{secret-contract-DnlMcrn5.js → secret-contract-BCpDLdg9.js} +17 -26
- package/dist/secret-contract-api.js +1 -1
- package/dist/{send-result-DsqTk27v.js → send-result-DfE5Fhz6.js} +22 -11
- package/dist/setup-api.js +1 -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/npm-shrinkwrap.json +58 -38
- package/openclaw.plugin.json +26 -10
- package/package.json +20 -7
- 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
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { d as isRecord$1, h as requestFeishuApi, s as resolveFeishuRuntimeAccount } from "./accounts-BDoGHJDk.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-DfE5Fhz6.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";
|
|
13
|
+
import { isBlockedHostnameOrIp, resolvePinnedHostnameWithPolicy } from "openclaw/plugin-sdk/ssrf-runtime";
|
|
12
14
|
import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
|
|
13
15
|
import { readRegularFile, writeExternalFileWithinRoot } from "openclaw/plugin-sdk/security-runtime";
|
|
14
16
|
import { Readable } from "node:stream";
|
|
@@ -38,6 +40,33 @@ function resolveFeishuIdentityHeaderTitle(identity) {
|
|
|
38
40
|
return (emoji ? `${emoji} ${name}` : name).trim();
|
|
39
41
|
}
|
|
40
42
|
//#endregion
|
|
43
|
+
//#region extensions/feishu/src/media-fallback.ts
|
|
44
|
+
const FEISHU_MEDIA_UPLOAD_FAILURE_FALLBACK_TEXT = "Media upload failed. Please try again.";
|
|
45
|
+
function hasAsciiControlCharacter(value) {
|
|
46
|
+
return Array.from(value).some((character) => {
|
|
47
|
+
const code = character.charCodeAt(0);
|
|
48
|
+
return code <= 31 || code === 127;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async function resolvePublicFeishuMediaReference(value) {
|
|
52
|
+
const raw = value?.trim();
|
|
53
|
+
if (!raw || hasAsciiControlCharacter(raw)) return;
|
|
54
|
+
try {
|
|
55
|
+
const parsed = new URL(raw);
|
|
56
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return;
|
|
57
|
+
if (parsed.username || parsed.password || isBlockedHostnameOrIp(parsed.hostname)) return;
|
|
58
|
+
await resolvePinnedHostnameWithPolicy(parsed.hostname);
|
|
59
|
+
return parsed.href;
|
|
60
|
+
} catch {
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function buildFeishuMediaFallbackText(params) {
|
|
65
|
+
const mediaUrl = await resolvePublicFeishuMediaReference(params.mediaUrl);
|
|
66
|
+
const attachmentText = mediaUrl ? `${params.mediaLinkStyle === "plain" ? "" : "📎 "}${mediaUrl}` : FEISHU_MEDIA_UPLOAD_FAILURE_FALLBACK_TEXT;
|
|
67
|
+
return [params.text?.trim(), attachmentText].filter(Boolean).join("\n\n");
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
41
70
|
//#region extensions/feishu/src/external-keys.ts
|
|
42
71
|
const CONTROL_CHARS_RE = /\p{Cc}/u;
|
|
43
72
|
const MAX_EXTERNAL_KEY_LENGTH = 512;
|
|
@@ -117,1172 +146,1201 @@ function resolveFeishuSendTarget(params) {
|
|
|
117
146
|
};
|
|
118
147
|
}
|
|
119
148
|
//#endregion
|
|
120
|
-
//#region extensions/feishu/src/
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const FEISHU_VOICE_SAMPLE_RATE_HZ = 48e3;
|
|
124
|
-
const FEISHU_VOICE_BITRATE = "64k";
|
|
125
|
-
const FEISHU_TRANSCODABLE_AUDIO_EXTS = /* @__PURE__ */ new Set([
|
|
126
|
-
".aac",
|
|
127
|
-
".aiff",
|
|
128
|
-
".alac",
|
|
129
|
-
".amr",
|
|
130
|
-
".caf",
|
|
131
|
-
".flac",
|
|
132
|
-
".m4a",
|
|
133
|
-
".mp3",
|
|
134
|
-
".oga",
|
|
135
|
-
".wav",
|
|
136
|
-
".webm",
|
|
137
|
-
".wma"
|
|
138
|
-
]);
|
|
139
|
-
function createConfiguredFeishuMediaClient(params) {
|
|
140
|
-
const account = resolveFeishuRuntimeAccount({
|
|
141
|
-
cfg: params.cfg,
|
|
142
|
-
accountId: params.accountId
|
|
143
|
-
});
|
|
144
|
-
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
145
|
-
return {
|
|
146
|
-
account,
|
|
147
|
-
client: createFeishuClient({
|
|
148
|
-
...account,
|
|
149
|
-
httpTimeoutMs: FEISHU_MEDIA_HTTP_TIMEOUT_MS
|
|
150
|
-
})
|
|
151
|
-
};
|
|
149
|
+
//#region extensions/feishu/src/types.ts
|
|
150
|
+
function isFeishuGroupChatType(chatType) {
|
|
151
|
+
return chatType === "group" || chatType === "topic_group";
|
|
152
152
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
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");
|
|
157
163
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
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
|
+
}));
|
|
165
177
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
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;
|
|
176
194
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (typeof status === "number") return status;
|
|
183
|
-
}
|
|
184
|
-
const status = error.status;
|
|
185
|
-
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>`;
|
|
186
200
|
}
|
|
187
|
-
|
|
188
|
-
|
|
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}`;
|
|
189
207
|
}
|
|
190
|
-
|
|
191
|
-
|
|
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 : "";
|
|
192
214
|
}
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
if (recovered !== value && !recovered.includes("�") && containsEastAsianScript(recovered)) return recovered;
|
|
196
|
-
return value;
|
|
215
|
+
function escapeMarkdownText(text) {
|
|
216
|
+
return text.replace(MARKDOWN_SPECIAL_CHARS, "\\$1");
|
|
197
217
|
}
|
|
198
|
-
function
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
218
|
+
function toBoolean(value) {
|
|
219
|
+
return value === true || value === 1 || value === "true";
|
|
220
|
+
}
|
|
221
|
+
function isStyleEnabled(style, key) {
|
|
222
|
+
if (!style) return false;
|
|
223
|
+
return toBoolean(style[key]);
|
|
224
|
+
}
|
|
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}`;
|
|
229
|
+
}
|
|
230
|
+
function sanitizeFenceLanguage(language) {
|
|
231
|
+
return language.trim().replace(/[^A-Za-z0-9_+#.-]/g, "");
|
|
232
|
+
}
|
|
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;
|
|
244
|
+
}
|
|
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})`;
|
|
251
|
+
}
|
|
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)}`;
|
|
256
|
+
}
|
|
257
|
+
function renderEmotionElement(element) {
|
|
258
|
+
return escapeMarkdownText(toStringOrEmpty(element.emoji) || toStringOrEmpty(element.text) || toStringOrEmpty(element.emoji_type));
|
|
259
|
+
}
|
|
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"}\`\`\``;
|
|
264
|
+
}
|
|
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);
|
|
274
|
+
}
|
|
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]" : "";
|
|
280
|
+
}
|
|
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
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return renderMediaPlaceholders ? "[media]" : "";
|
|
291
|
+
}
|
|
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));
|
|
204
304
|
}
|
|
205
|
-
const plainFileName = value.match(/filename="?([^";]+)"?/i)?.[1]?.trim();
|
|
206
|
-
return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : void 0;
|
|
207
305
|
}
|
|
208
|
-
function
|
|
209
|
-
|
|
210
|
-
const headers = asHeaderMap(responseWithOptionalFields.headers) ?? asHeaderMap(responseWithOptionalFields.header);
|
|
211
|
-
const contentType = readHeaderValue(headers, "content-type") ?? responseWithOptionalFields.contentType ?? responseWithOptionalFields.mime_type ?? responseWithOptionalFields.data?.contentType ?? responseWithOptionalFields.data?.mime_type;
|
|
212
|
-
const disposition = readHeaderValue(headers, "content-disposition");
|
|
306
|
+
function toPostPayload(candidate) {
|
|
307
|
+
if (!isRecord$1(candidate) || !Array.isArray(candidate.content)) return null;
|
|
213
308
|
return {
|
|
214
|
-
|
|
215
|
-
|
|
309
|
+
title: toStringOrEmpty(candidate.title),
|
|
310
|
+
content: candidate.content
|
|
216
311
|
};
|
|
217
312
|
}
|
|
218
|
-
function
|
|
219
|
-
|
|
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;
|
|
220
322
|
}
|
|
221
|
-
|
|
222
|
-
const
|
|
223
|
-
if (
|
|
224
|
-
if (
|
|
225
|
-
const
|
|
226
|
-
if (
|
|
227
|
-
|
|
228
|
-
if (responseWithOptionalFields.data instanceof ArrayBuffer) return saveMediaBuffer(Buffer.from(responseWithOptionalFields.data), contentType, "inbound", maxBytes, fileName);
|
|
229
|
-
const save = (stream, ct = contentType, mb = maxBytes, fn = fileName) => saveMediaStreamWithIdleTimeout(stream, ct, mb, fn, FEISHU_MEDIA_HTTP_TIMEOUT_MS);
|
|
230
|
-
if (typeof response.getReadableStream === "function") return save(response.getReadableStream());
|
|
231
|
-
if (typeof response.writeFile === "function") return await withTempDownloadPath({ prefix: params.tmpDirPrefix }, async (tmpPath) => {
|
|
232
|
-
await response.writeFile(tmpPath);
|
|
233
|
-
if ((await fs.promises.stat(tmpPath)).size > maxBytes) throw mediaLimitError(maxBytes);
|
|
234
|
-
return await save(fs.createReadStream(tmpPath));
|
|
235
|
-
});
|
|
236
|
-
if (responseWithOptionalFields[Symbol.asyncIterator]) return save(responseWithOptionalFields);
|
|
237
|
-
if (response instanceof Readable) return save(response);
|
|
238
|
-
const keys = Object.keys(response);
|
|
239
|
-
throw new Error(`${params.errorPrefix}: unexpected response format. Keys: [${keys.join(", ")}]`);
|
|
240
|
-
}
|
|
241
|
-
async function saveMessageResourceWithType(params) {
|
|
242
|
-
const response = await params.client.im.messageResource.get({
|
|
243
|
-
path: {
|
|
244
|
-
message_id: params.messageId,
|
|
245
|
-
file_key: params.fileKey
|
|
246
|
-
},
|
|
247
|
-
params: { type: params.type }
|
|
248
|
-
});
|
|
249
|
-
const meta = extractFeishuDownloadMetadata(response);
|
|
250
|
-
return {
|
|
251
|
-
saved: await saveFeishuResponseMedia({
|
|
252
|
-
response,
|
|
253
|
-
tmpDirPrefix: "openclaw-feishu-resource-",
|
|
254
|
-
errorPrefix: "Feishu message resource download failed",
|
|
255
|
-
maxBytes: params.maxBytes,
|
|
256
|
-
contentType: meta.contentType,
|
|
257
|
-
fileName: meta.fileName ?? (params.originalFilename ? recoverUtf8FileNameFromLatin1Header(params.originalFilename) : void 0)
|
|
258
|
-
}),
|
|
259
|
-
...meta
|
|
260
|
-
};
|
|
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);
|
|
261
330
|
}
|
|
262
|
-
|
|
263
|
-
const { cfg, messageId, fileKey, type, accountId, maxBytes, originalFilename } = params;
|
|
264
|
-
const normalizedFileKey = normalizeFeishuExternalKey(fileKey);
|
|
265
|
-
if (!normalizedFileKey) throw new Error("Feishu message resource download failed: invalid file_key");
|
|
266
|
-
const { client } = createConfiguredFeishuMediaClient({
|
|
267
|
-
cfg,
|
|
268
|
-
accountId
|
|
269
|
-
});
|
|
331
|
+
function parsePostContent(content, options = {}) {
|
|
270
332
|
try {
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
maxBytes,
|
|
288
|
-
originalFilename
|
|
289
|
-
});
|
|
290
|
-
} catch {
|
|
291
|
-
throw err;
|
|
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);
|
|
292
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
|
+
};
|
|
356
|
+
} catch {
|
|
357
|
+
return {
|
|
358
|
+
textContent: FALLBACK_POST_TEXT,
|
|
359
|
+
imageKeys: [],
|
|
360
|
+
mediaKeys: [],
|
|
361
|
+
mentionedOpenIds: []
|
|
362
|
+
};
|
|
293
363
|
}
|
|
294
364
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
});
|
|
305
|
-
const imageData = typeof image === "string" ? (await readRegularFile({ filePath: image })).buffer : image;
|
|
306
|
-
return { imageKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.image.create({ data: {
|
|
307
|
-
image_type: imageType,
|
|
308
|
-
image: imageData
|
|
309
|
-
} }), "Feishu image upload failed", { includeNestedErrorLogId: true }), {
|
|
310
|
-
key: "image_key",
|
|
311
|
-
errorPrefix: "Feishu image upload failed"
|
|
312
|
-
}) };
|
|
313
|
-
}
|
|
314
|
-
/**
|
|
315
|
-
* Sanitize a filename for safe use in Feishu multipart/form-data uploads.
|
|
316
|
-
* Strips control characters and multipart-injection vectors (CWE-93) while
|
|
317
|
-
* preserving the original UTF-8 display name (Chinese, emoji, etc.).
|
|
318
|
-
*
|
|
319
|
-
* Previous versions percent-encoded non-ASCII characters, but the Feishu
|
|
320
|
-
* `im.file.create` API uses `file_name` as a literal display name — it does
|
|
321
|
-
* NOT decode percent-encoding — so encoded filenames appeared as garbled text
|
|
322
|
-
* in chat (regression in v2026.3.2).
|
|
323
|
-
*/
|
|
324
|
-
function sanitizeFileNameForUpload(fileName) {
|
|
325
|
-
return fileName.replace(/[\p{Cc}"\\]/gu, "_");
|
|
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");
|
|
326
374
|
}
|
|
327
|
-
/**
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
const fileData = typeof file === "string" ? (await readRegularFile({ filePath: file })).buffer : file;
|
|
338
|
-
const safeFileName = sanitizeFileNameForUpload(fileName);
|
|
339
|
-
return { fileKey: extractFeishuUploadKey(await requestFeishuApi(() => client.im.file.create({ data: {
|
|
340
|
-
file_type: fileType,
|
|
341
|
-
file_name: safeFileName,
|
|
342
|
-
file: fileData,
|
|
343
|
-
...duration !== void 0 ? { duration } : {}
|
|
344
|
-
} }), "Feishu file upload failed", { includeNestedErrorLogId: true }), {
|
|
345
|
-
key: "file_key",
|
|
346
|
-
errorPrefix: "Feishu file upload failed"
|
|
347
|
-
}) };
|
|
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;
|
|
348
385
|
}
|
|
349
|
-
/**
|
|
350
|
-
|
|
351
|
-
*/
|
|
352
|
-
async function sendImageFeishu(params) {
|
|
353
|
-
const { cfg, to, imageKey, replyToMessageId, replyInThread, accountId } = params;
|
|
354
|
-
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
355
|
-
cfg,
|
|
356
|
-
to,
|
|
357
|
-
accountId
|
|
358
|
-
});
|
|
359
|
-
const content = JSON.stringify({ image_key: imageKey });
|
|
360
|
-
if (replyToMessageId) {
|
|
361
|
-
const response = await requestFeishuApi(() => client.im.message.reply({
|
|
362
|
-
path: { message_id: replyToMessageId },
|
|
363
|
-
data: {
|
|
364
|
-
content,
|
|
365
|
-
msg_type: "image",
|
|
366
|
-
...replyInThread ? { reply_in_thread: true } : {}
|
|
367
|
-
}
|
|
368
|
-
}), "Feishu image reply failed", { includeNestedErrorLogId: true });
|
|
369
|
-
assertFeishuMessageApiSuccess(response, "Feishu image reply failed");
|
|
370
|
-
return toFeishuSendResult(response, receiveId, "media");
|
|
371
|
-
}
|
|
386
|
+
/** Send a direct message as a fallback when a reply target is unavailable. */
|
|
387
|
+
async function sendFallbackDirect(client, params, errorPrefix) {
|
|
372
388
|
const response = await requestFeishuApi(() => client.im.message.create({
|
|
373
|
-
params: { receive_id_type: receiveIdType },
|
|
389
|
+
params: { receive_id_type: params.receiveIdType },
|
|
374
390
|
data: {
|
|
375
|
-
receive_id: receiveId,
|
|
376
|
-
content,
|
|
377
|
-
msg_type:
|
|
391
|
+
receive_id: params.receiveId,
|
|
392
|
+
content: params.content,
|
|
393
|
+
msg_type: params.msgType
|
|
378
394
|
}
|
|
379
|
-
}),
|
|
380
|
-
assertFeishuMessageApiSuccess(response,
|
|
381
|
-
return toFeishuSendResult(response, receiveId,
|
|
395
|
+
}), errorPrefix, { includeNestedErrorLogId: true });
|
|
396
|
+
assertFeishuMessageApiSuccess(response, errorPrefix);
|
|
397
|
+
return toFeishuSendResult(response, params.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
382
398
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
*/
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
cfg,
|
|
391
|
-
to,
|
|
392
|
-
accountId
|
|
393
|
-
});
|
|
394
|
-
const content = JSON.stringify({ file_key: fileKey });
|
|
395
|
-
if (replyToMessageId) {
|
|
396
|
-
const response = await requestFeishuApi(() => client.im.message.reply({
|
|
397
|
-
path: { message_id: replyToMessageId },
|
|
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;
|
|
403
|
+
try {
|
|
404
|
+
response = await requestFeishuApi(() => client.im.message.reply({
|
|
405
|
+
path: { message_id: params.replyToMessageId },
|
|
398
406
|
data: {
|
|
399
|
-
content,
|
|
400
|
-
msg_type: msgType,
|
|
401
|
-
...replyInThread ? { reply_in_thread: true } : {}
|
|
407
|
+
content: params.content,
|
|
408
|
+
msg_type: params.msgType,
|
|
409
|
+
...params.replyInThread ? { reply_in_thread: true } : {}
|
|
402
410
|
}
|
|
403
|
-
}),
|
|
404
|
-
|
|
405
|
-
|
|
411
|
+
}), params.replyErrorPrefix, { includeNestedErrorLogId: true });
|
|
412
|
+
} catch (err) {
|
|
413
|
+
if (!isWithdrawnReplyError(err)) throw err;
|
|
414
|
+
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
415
|
+
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
406
416
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
}
|
|
414
|
-
}), "Feishu file send failed", { includeNestedErrorLogId: true });
|
|
415
|
-
assertFeishuMessageApiSuccess(response, "Feishu file send failed");
|
|
416
|
-
return toFeishuSendResult(response, receiveId, resolveFeishuReceiptKind(msgType));
|
|
417
|
+
if (shouldFallbackFromReplyTarget(response)) {
|
|
418
|
+
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
419
|
+
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
420
|
+
}
|
|
421
|
+
assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
|
|
422
|
+
return toFeishuSendResult(response, params.directParams.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
417
423
|
}
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
case ".docx": return "doc";
|
|
431
|
-
case ".xls":
|
|
432
|
-
case ".xlsx": return "xls";
|
|
433
|
-
case ".ppt":
|
|
434
|
-
case ".pptx": return "ppt";
|
|
435
|
-
default: return "stream";
|
|
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
436
|
}
|
|
437
|
+
return variables;
|
|
437
438
|
}
|
|
438
|
-
function
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
".jpeg",
|
|
445
|
-
".png",
|
|
446
|
-
".gif",
|
|
447
|
-
".webp",
|
|
448
|
-
".bmp",
|
|
449
|
-
".ico",
|
|
450
|
-
".tiff"
|
|
451
|
-
].includes(ext) || mimeKind === "image") return { msgType: "image" };
|
|
452
|
-
if (ext === ".opus" || ext === ".ogg" || contentType === "audio/ogg" || contentType === "audio/opus") return {
|
|
453
|
-
fileType: "opus",
|
|
454
|
-
msgType: "audio"
|
|
455
|
-
};
|
|
456
|
-
if ([
|
|
457
|
-
".mp4",
|
|
458
|
-
".mov",
|
|
459
|
-
".avi"
|
|
460
|
-
].includes(ext) || contentType === "video/mp4" || contentType === "video/quicktime" || contentType === "video/x-msvideo") return {
|
|
461
|
-
fileType: "mp4",
|
|
462
|
-
msgType: "media"
|
|
463
|
-
};
|
|
464
|
-
const fileType = detectFileType(fileName);
|
|
465
|
-
return {
|
|
466
|
-
fileType,
|
|
467
|
-
msgType: fileType === "stream" ? "file" : fileType === "opus" ? "audio" : fileType === "mp4" ? "media" : "file"
|
|
468
|
-
};
|
|
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
|
+
});
|
|
469
445
|
}
|
|
470
|
-
function
|
|
471
|
-
|
|
472
|
-
const
|
|
473
|
-
|
|
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);
|
|
474
453
|
}
|
|
475
|
-
function
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
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);
|
|
480
459
|
}
|
|
460
|
+
return texts.join("\n").trim();
|
|
481
461
|
}
|
|
482
|
-
function
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
contentType: params.contentType
|
|
492
|
-
});
|
|
493
|
-
}
|
|
494
|
-
function isLikelyTranscodableAudio(params) {
|
|
495
|
-
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
496
|
-
const contentType = normalizeLowercaseStringOrEmpty(params.contentType);
|
|
497
|
-
return FEISHU_TRANSCODABLE_AUDIO_EXTS.has(ext) || mediaKindFromMime(contentType) === "audio";
|
|
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;
|
|
498
471
|
}
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
prefix: "feishu-voice-"
|
|
503
|
-
}, async (workspace) => {
|
|
504
|
-
const ext = normalizeLowercaseStringOrEmpty(path.extname(params.fileName));
|
|
505
|
-
const inputExt = ext && ext.length <= 12 ? ext : ".audio";
|
|
506
|
-
const inputPath = await workspace.write(`input${inputExt}`, params.buffer);
|
|
507
|
-
await writeExternalFileWithinRoot({
|
|
508
|
-
rootDir: workspace.dir,
|
|
509
|
-
path: FEISHU_VOICE_FILE_NAME,
|
|
510
|
-
write: async (outputPath) => {
|
|
511
|
-
await runFfmpeg([
|
|
512
|
-
"-hide_banner",
|
|
513
|
-
"-loglevel",
|
|
514
|
-
"error",
|
|
515
|
-
"-y",
|
|
516
|
-
"-i",
|
|
517
|
-
inputPath,
|
|
518
|
-
"-vn",
|
|
519
|
-
"-sn",
|
|
520
|
-
"-dn",
|
|
521
|
-
"-t",
|
|
522
|
-
String(MEDIA_FFMPEG_MAX_AUDIO_DURATION_SECS),
|
|
523
|
-
"-ar",
|
|
524
|
-
String(FEISHU_VOICE_SAMPLE_RATE_HZ),
|
|
525
|
-
"-ac",
|
|
526
|
-
"1",
|
|
527
|
-
"-c:a",
|
|
528
|
-
"libopus",
|
|
529
|
-
"-b:a",
|
|
530
|
-
FEISHU_VOICE_BITRATE,
|
|
531
|
-
"-f",
|
|
532
|
-
"ogg",
|
|
533
|
-
outputPath
|
|
534
|
-
]);
|
|
535
|
-
}
|
|
536
|
-
});
|
|
537
|
-
return {
|
|
538
|
-
buffer: await workspace.read(FEISHU_VOICE_FILE_NAME),
|
|
539
|
-
fileName: FEISHU_VOICE_FILE_NAME,
|
|
540
|
-
contentType: "audio/ogg"
|
|
541
|
-
};
|
|
542
|
-
});
|
|
472
|
+
function parseInteractivePostFallback(parsed) {
|
|
473
|
+
const textContent = parsePostContent(JSON.stringify(parsed)).textContent.trim();
|
|
474
|
+
return textContent && textContent !== POST_FALLBACK_TEXT ? textContent : void 0;
|
|
543
475
|
}
|
|
544
|
-
|
|
545
|
-
if (
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
console.warn(`[feishu] audioAsVoice transcode failed; sending ${params.fileName} as a file attachment:`, err);
|
|
551
|
-
return params;
|
|
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;
|
|
552
482
|
}
|
|
483
|
+
return parseInteractivePostFallback(parsed) ?? INTERACTIVE_CARD_FALLBACK_TEXT;
|
|
553
484
|
}
|
|
554
|
-
|
|
485
|
+
function parseFeishuMessageContent(rawContent, msgType) {
|
|
486
|
+
if (!rawContent) return "";
|
|
487
|
+
let parsed;
|
|
555
488
|
try {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
"-v",
|
|
564
|
-
"error",
|
|
565
|
-
"-show_entries",
|
|
566
|
-
"format=duration",
|
|
567
|
-
"-of",
|
|
568
|
-
"csv=p=0",
|
|
569
|
-
await workspace.write(`input${inferredExt}`, params.buffer)
|
|
570
|
-
], { timeoutMs: 5e3 });
|
|
571
|
-
const seconds = Number.parseFloat(stdout.trim());
|
|
572
|
-
if (!Number.isFinite(seconds) || seconds <= 0) return;
|
|
573
|
-
return Math.max(1, Math.round(seconds * 1e3));
|
|
574
|
-
});
|
|
575
|
-
} catch (err) {
|
|
576
|
-
console.warn("[feishu] failed to probe media duration; upload will omit it:", err);
|
|
577
|
-
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]";
|
|
578
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]`;
|
|
579
505
|
}
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
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
|
+
};
|
|
583
521
|
}
|
|
584
522
|
/**
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
* 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.
|
|
588
525
|
*/
|
|
589
|
-
async function
|
|
590
|
-
const { cfg,
|
|
526
|
+
async function getMessageFeishu(params) {
|
|
527
|
+
const { cfg, messageId, accountId } = params;
|
|
591
528
|
const account = resolveFeishuRuntimeAccount({
|
|
592
529
|
cfg,
|
|
593
530
|
accountId
|
|
594
531
|
});
|
|
595
532
|
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
596
|
-
const
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
buffer = mediaBuffer;
|
|
602
|
-
name = fileName ?? "file";
|
|
603
|
-
} else if (mediaUrl) {
|
|
604
|
-
const loaded = await getFeishuRuntime().media.loadWebMedia(mediaUrl, {
|
|
605
|
-
maxBytes: mediaMaxBytes,
|
|
606
|
-
optimizeImages: false,
|
|
607
|
-
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 }
|
|
608
538
|
});
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
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
|
|
632
581
|
});
|
|
633
|
-
|
|
634
|
-
...await sendImageFeishu({
|
|
635
|
-
cfg,
|
|
636
|
-
to,
|
|
637
|
-
imageKey,
|
|
638
|
-
replyToMessageId,
|
|
639
|
-
replyInThread,
|
|
640
|
-
accountId
|
|
641
|
-
}),
|
|
642
|
-
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
643
|
-
};
|
|
582
|
+
if (results.length >= limit) break;
|
|
644
583
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
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
|
|
650
593
|
});
|
|
651
|
-
const
|
|
594
|
+
const tableMode = resolveMarkdownTableMode({
|
|
652
595
|
cfg,
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
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,
|
|
657
625
|
accountId
|
|
658
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({
|
|
647
|
+
cfg,
|
|
648
|
+
accountId
|
|
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}`}`);
|
|
659
675
|
return {
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
to,
|
|
663
|
-
fileKey,
|
|
664
|
-
msgType: routing.msgType,
|
|
665
|
-
replyToMessageId,
|
|
666
|
-
replyInThread,
|
|
667
|
-
accountId
|
|
668
|
-
}),
|
|
669
|
-
...voiceIntentDegradedToFile ? { voiceIntentDegradedToFile: true } : {}
|
|
676
|
+
messageId,
|
|
677
|
+
contentType: "post"
|
|
670
678
|
};
|
|
671
679
|
}
|
|
672
|
-
//#endregion
|
|
673
|
-
//#region extensions/feishu/src/types.ts
|
|
674
|
-
function isFeishuGroupChatType(chatType) {
|
|
675
|
-
return chatType === "group" || chatType === "topic_group";
|
|
676
|
-
}
|
|
677
|
-
//#endregion
|
|
678
|
-
//#region extensions/feishu/src/mention.ts
|
|
679
|
-
function isFeishuBroadcastMention(mention) {
|
|
680
|
-
const normalizedKey = mention.key?.trim().toLowerCase();
|
|
681
|
-
if (normalizedKey === "@all" || normalizedKey === "@_all") return true;
|
|
682
|
-
return [
|
|
683
|
-
mention.id?.open_id,
|
|
684
|
-
mention.id?.user_id,
|
|
685
|
-
mention.id?.union_id
|
|
686
|
-
].some((id) => id?.trim().toLowerCase() === "all");
|
|
687
|
-
}
|
|
688
680
|
/**
|
|
689
|
-
*
|
|
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.
|
|
690
684
|
*/
|
|
691
|
-
function
|
|
692
|
-
return
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
}));
|
|
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
|
+
};
|
|
701
694
|
}
|
|
702
695
|
/**
|
|
703
|
-
*
|
|
704
|
-
*
|
|
705
|
-
* - Group: message mentions bot + at least one other user
|
|
706
|
-
* - 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.
|
|
707
698
|
*/
|
|
708
|
-
function
|
|
709
|
-
const
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
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;
|
|
718
724
|
}
|
|
719
725
|
/**
|
|
720
|
-
*
|
|
726
|
+
* Send a message as a structured card with optional header and note.
|
|
721
727
|
*/
|
|
722
|
-
function
|
|
723
|
-
|
|
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
|
+
});
|
|
724
744
|
}
|
|
725
745
|
/**
|
|
726
|
-
*
|
|
746
|
+
* Send a message as a markdown card (interactive message).
|
|
747
|
+
* This renders markdown properly in Feishu (code blocks, tables, bold/italic, etc.)
|
|
727
748
|
*/
|
|
728
|
-
function
|
|
729
|
-
|
|
730
|
-
|
|
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
|
+
});
|
|
731
762
|
}
|
|
732
763
|
//#endregion
|
|
733
|
-
//#region extensions/feishu/src/
|
|
734
|
-
const
|
|
735
|
-
const
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
const text = toStringOrEmpty(element.text);
|
|
759
|
-
const style = isRecord$1(element.style) ? element.style : void 0;
|
|
760
|
-
if (isStyleEnabled(style, "code")) return wrapInlineCode(text);
|
|
761
|
-
let rendered = escapeMarkdownText(text);
|
|
762
|
-
if (!rendered) return "";
|
|
763
|
-
if (isStyleEnabled(style, "bold")) rendered = `**${rendered}**`;
|
|
764
|
-
if (isStyleEnabled(style, "italic")) rendered = `*${rendered}*`;
|
|
765
|
-
if (isStyleEnabled(style, "underline")) rendered = `<u>${rendered}</u>`;
|
|
766
|
-
if (isStyleEnabled(style, "strikethrough") || isStyleEnabled(style, "line_through") || isStyleEnabled(style, "lineThrough")) rendered = `~~${rendered}~~`;
|
|
767
|
-
return rendered;
|
|
768
|
-
}
|
|
769
|
-
function renderLinkElement(element) {
|
|
770
|
-
const href = toStringOrEmpty(element.href).trim();
|
|
771
|
-
const text = toStringOrEmpty(element.text) || href;
|
|
772
|
-
if (!text) return "";
|
|
773
|
-
if (!href) return escapeMarkdownText(text);
|
|
774
|
-
return `[${escapeMarkdownText(text)}](${href})`;
|
|
775
|
-
}
|
|
776
|
-
function renderMentionElement(element) {
|
|
777
|
-
const mention = toStringOrEmpty(element.user_name) || toStringOrEmpty(element.user_id) || toStringOrEmpty(element.open_id);
|
|
778
|
-
if (!mention) return "";
|
|
779
|
-
return `@${escapeMarkdownText(mention)}`;
|
|
780
|
-
}
|
|
781
|
-
function renderEmotionElement(element) {
|
|
782
|
-
return escapeMarkdownText(toStringOrEmpty(element.emoji) || toStringOrEmpty(element.text) || toStringOrEmpty(element.emoji_type));
|
|
783
|
-
}
|
|
784
|
-
function renderCodeBlockElement(element) {
|
|
785
|
-
const language = sanitizeFenceLanguage(toStringOrEmpty(element.language) || toStringOrEmpty(element.lang));
|
|
786
|
-
const code = (toStringOrEmpty(element.text) || toStringOrEmpty(element.content)).replace(/\r\n/g, "\n");
|
|
787
|
-
return `\`\`\`${language}\n${code}${code.endsWith("\n") ? "" : "\n"}\`\`\``;
|
|
788
|
-
}
|
|
789
|
-
function renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, renderMediaPlaceholders) {
|
|
790
|
-
if (!isRecord$1(element)) return escapeMarkdownText(toStringOrEmpty(element));
|
|
791
|
-
switch (normalizeLowercaseStringOrEmpty(toStringOrEmpty(element.tag))) {
|
|
792
|
-
case "text": return renderTextElement(element);
|
|
793
|
-
case "a": return renderLinkElement(element);
|
|
794
|
-
case "at":
|
|
795
|
-
{
|
|
796
|
-
const normalizedMention = normalizeFeishuExternalKey(toStringOrEmpty(element.open_id) || toStringOrEmpty(element.user_id));
|
|
797
|
-
if (normalizedMention) mentionedOpenIds.push(normalizedMention);
|
|
798
|
-
}
|
|
799
|
-
return renderMentionElement(element);
|
|
800
|
-
case "img": {
|
|
801
|
-
const imageKey = normalizeFeishuExternalKey(toStringOrEmpty(element.image_key));
|
|
802
|
-
if (imageKey) imageKeys.push(imageKey);
|
|
803
|
-
return renderMediaPlaceholders ? "![image]" : "";
|
|
804
|
-
}
|
|
805
|
-
case "media": {
|
|
806
|
-
const fileKey = normalizeFeishuExternalKey(toStringOrEmpty(element.file_key));
|
|
807
|
-
if (fileKey) {
|
|
808
|
-
const fileName = toStringOrEmpty(element.file_name) || void 0;
|
|
809
|
-
mediaKeys.push({
|
|
810
|
-
fileKey,
|
|
811
|
-
fileName
|
|
812
|
-
});
|
|
813
|
-
}
|
|
814
|
-
return renderMediaPlaceholders ? "[media]" : "";
|
|
815
|
-
}
|
|
816
|
-
case "emotion": return renderEmotionElement(element);
|
|
817
|
-
case "md":
|
|
818
|
-
case "lark_md": return toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
819
|
-
case "br": return "\n";
|
|
820
|
-
case "hr": return "\n\n---\n\n";
|
|
821
|
-
case "code": {
|
|
822
|
-
const code = toStringOrEmpty(element.text) || toStringOrEmpty(element.content);
|
|
823
|
-
return code ? wrapInlineCode(code) : "";
|
|
824
|
-
}
|
|
825
|
-
case "code_block":
|
|
826
|
-
case "pre": return renderCodeBlockElement(element);
|
|
827
|
-
default: return escapeMarkdownText(toStringOrEmpty(element.text));
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
function toPostPayload(candidate) {
|
|
831
|
-
if (!isRecord$1(candidate) || !Array.isArray(candidate.content)) return null;
|
|
832
|
-
return {
|
|
833
|
-
title: toStringOrEmpty(candidate.title),
|
|
834
|
-
content: candidate.content
|
|
835
|
-
};
|
|
836
|
-
}
|
|
837
|
-
function resolveLocalePayload(candidate) {
|
|
838
|
-
const direct = toPostPayload(candidate);
|
|
839
|
-
if (direct) return direct;
|
|
840
|
-
if (!isRecord$1(candidate)) return null;
|
|
841
|
-
for (const value of Object.values(candidate)) {
|
|
842
|
-
const localePayload = toPostPayload(value);
|
|
843
|
-
if (localePayload) return localePayload;
|
|
844
|
-
}
|
|
845
|
-
return null;
|
|
846
|
-
}
|
|
847
|
-
function resolvePostPayload(parsed) {
|
|
848
|
-
const direct = toPostPayload(parsed);
|
|
849
|
-
if (direct) return direct;
|
|
850
|
-
if (!isRecord$1(parsed)) return null;
|
|
851
|
-
const wrappedPost = resolveLocalePayload(parsed.post);
|
|
852
|
-
if (wrappedPost) return wrappedPost;
|
|
853
|
-
return resolveLocalePayload(parsed);
|
|
854
|
-
}
|
|
855
|
-
function parsePostContent(content, options = {}) {
|
|
856
|
-
try {
|
|
857
|
-
const payload = resolvePostPayload(JSON.parse(content));
|
|
858
|
-
if (!payload) return {
|
|
859
|
-
textContent: FALLBACK_POST_TEXT,
|
|
860
|
-
imageKeys: [],
|
|
861
|
-
mediaKeys: [],
|
|
862
|
-
mentionedOpenIds: []
|
|
863
|
-
};
|
|
864
|
-
const imageKeys = [];
|
|
865
|
-
const mediaKeys = [];
|
|
866
|
-
const mentionedOpenIds = [];
|
|
867
|
-
const paragraphs = [];
|
|
868
|
-
for (const paragraph of payload.content) {
|
|
869
|
-
if (!Array.isArray(paragraph)) continue;
|
|
870
|
-
let renderedParagraph = "";
|
|
871
|
-
for (const element of paragraph) renderedParagraph += renderElement(element, imageKeys, mediaKeys, mentionedOpenIds, options.renderMediaPlaceholders !== false);
|
|
872
|
-
paragraphs.push(renderedParagraph);
|
|
873
|
-
}
|
|
874
|
-
return {
|
|
875
|
-
textContent: [escapeMarkdownText(payload.title.trim()), paragraphs.join("\n").trim()].filter(Boolean).join("\n\n").trim() || (options.emptyTextFallback ?? FALLBACK_POST_TEXT),
|
|
876
|
-
imageKeys,
|
|
877
|
-
mediaKeys,
|
|
878
|
-
mentionedOpenIds
|
|
879
|
-
};
|
|
880
|
-
} catch {
|
|
881
|
-
return {
|
|
882
|
-
textContent: FALLBACK_POST_TEXT,
|
|
883
|
-
imageKeys: [],
|
|
884
|
-
mediaKeys: [],
|
|
885
|
-
mentionedOpenIds: []
|
|
886
|
-
};
|
|
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 });
|
|
887
789
|
}
|
|
888
790
|
}
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
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
|
+
};
|
|
898
804
|
}
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
if (typeof code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(code)) return true;
|
|
904
|
-
const response = err.response;
|
|
905
|
-
if (typeof response?.data?.code === "number" && WITHDRAWN_REPLY_ERROR_CODES.has(response.data.code)) return true;
|
|
906
|
-
const cause = err.cause;
|
|
907
|
-
if (cause && cause !== err) return isWithdrawnReplyError(cause);
|
|
908
|
-
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);
|
|
909
809
|
}
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
const
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
msg_type: params.msgType
|
|
918
|
-
}
|
|
919
|
-
}), errorPrefix, { includeNestedErrorLogId: true });
|
|
920
|
-
assertFeishuMessageApiSuccess(response, errorPrefix);
|
|
921
|
-
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;
|
|
922
817
|
}
|
|
923
|
-
|
|
924
|
-
if (!
|
|
925
|
-
const
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
msg_type: params.msgType,
|
|
933
|
-
...params.replyInThread ? { reply_in_thread: true } : {}
|
|
934
|
-
}
|
|
935
|
-
}), params.replyErrorPrefix, { includeNestedErrorLogId: true });
|
|
936
|
-
} catch (err) {
|
|
937
|
-
if (!isWithdrawnReplyError(err)) throw err;
|
|
938
|
-
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
939
|
-
return sendFallbackDirect(client, params.directParams, params.directErrorPrefix);
|
|
940
|
-
}
|
|
941
|
-
if (shouldFallbackFromReplyTarget(response)) {
|
|
942
|
-
if (replyTargetFallbackError) throw replyTargetFallbackError;
|
|
943
|
-
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
|
+
}
|
|
944
827
|
}
|
|
945
|
-
assertFeishuMessageApiSuccess(response, params.replyErrorPrefix);
|
|
946
|
-
return toFeishuSendResult(response, params.directParams.receiveId, resolveFeishuReceiptKind(params.msgType));
|
|
947
|
-
}
|
|
948
|
-
function normalizeCardTemplateVariable(value) {
|
|
949
|
-
if (typeof value === "string") return value;
|
|
950
|
-
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
|
|
951
828
|
}
|
|
952
|
-
function
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
if (normalized !== void 0) variables.set(key, normalized);
|
|
959
|
-
}
|
|
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;
|
|
960
835
|
}
|
|
961
|
-
|
|
836
|
+
const status = error.status;
|
|
837
|
+
return typeof status === "number" ? status : void 0;
|
|
962
838
|
}
|
|
963
|
-
function
|
|
964
|
-
|
|
965
|
-
return text.replace(/\$\{([A-Za-z0-9_.-]+)\}|\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}/g, (match, a, b) => {
|
|
966
|
-
const variableName = typeof a === "string" ? a : b;
|
|
967
|
-
return variables.get(variableName) ?? match;
|
|
968
|
-
});
|
|
839
|
+
function isHttpStatusError(error, status) {
|
|
840
|
+
return readHttpStatusFromError(error) === status;
|
|
969
841
|
}
|
|
970
|
-
function
|
|
971
|
-
|
|
972
|
-
const tag = typeof element.tag === "string" ? element.tag : "";
|
|
973
|
-
const text = isRecord(element.text) ? element.text : void 0;
|
|
974
|
-
if (tag === "div" && typeof text?.content === "string") return applyCardTemplateVariables(text.content, variables);
|
|
975
|
-
if ((tag === "markdown" || tag === "lark_md") && typeof element.content === "string") return applyCardTemplateVariables(element.content, variables);
|
|
976
|
-
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);
|
|
977
844
|
}
|
|
978
|
-
function
|
|
979
|
-
const
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
if (text !== void 0) texts.push(text);
|
|
983
|
-
}
|
|
984
|
-
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;
|
|
985
849
|
}
|
|
986
|
-
function
|
|
987
|
-
const
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
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");
|
|
993
856
|
}
|
|
994
|
-
|
|
857
|
+
const plainFileName = value.match(/filename="?([^";]+)"?/i)?.[1]?.trim();
|
|
858
|
+
return plainFileName ? recoverUtf8FileNameFromLatin1Header(plainFileName) : void 0;
|
|
995
859
|
}
|
|
996
|
-
function
|
|
997
|
-
const
|
|
998
|
-
|
|
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
|
+
};
|
|
999
869
|
}
|
|
1000
|
-
function
|
|
1001
|
-
|
|
1002
|
-
const variables = readCardTemplateVariables(parsed);
|
|
1003
|
-
for (const elements of readInteractiveElementArrays(parsed)) {
|
|
1004
|
-
const text = extractInteractiveElementsText(elements, variables);
|
|
1005
|
-
if (text) return text;
|
|
1006
|
-
}
|
|
1007
|
-
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`);
|
|
1008
872
|
}
|
|
1009
|
-
function
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
if (
|
|
1026
|
-
const
|
|
1027
|
-
|
|
1028
|
-
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(", ")}]`);
|
|
1029
892
|
}
|
|
1030
|
-
function
|
|
1031
|
-
const
|
|
1032
|
-
|
|
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);
|
|
1033
902
|
return {
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
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
|
|
1044
912
|
};
|
|
1045
913
|
}
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
const { cfg, messageId, accountId } = params;
|
|
1052
|
-
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({
|
|
1053
919
|
cfg,
|
|
1054
920
|
accountId
|
|
1055
921
|
});
|
|
1056
|
-
if (!account.configured) throw new Error(`Feishu account "${account.accountId}" not configured`);
|
|
1057
|
-
const client = createFeishuClient(account);
|
|
1058
922
|
try {
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
923
|
+
return await saveMessageResourceWithType({
|
|
924
|
+
client,
|
|
925
|
+
messageId,
|
|
926
|
+
fileKey: normalizedFileKey,
|
|
927
|
+
type,
|
|
928
|
+
maxBytes,
|
|
929
|
+
originalFilename
|
|
1062
930
|
});
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
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
|
+
}
|
|
1070
945
|
}
|
|
1071
946
|
}
|
|
1072
947
|
/**
|
|
1073
|
-
*
|
|
1074
|
-
*
|
|
1075
|
-
* 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
|
|
1076
950
|
*/
|
|
1077
|
-
async function
|
|
1078
|
-
const { cfg,
|
|
1079
|
-
const
|
|
951
|
+
async function uploadImageFeishu(params) {
|
|
952
|
+
const { cfg, image, imageType = "message", accountId } = params;
|
|
953
|
+
const { client } = createConfiguredFeishuMediaClient({
|
|
1080
954
|
cfg,
|
|
1081
955
|
accountId
|
|
1082
956
|
});
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
} }
|
|
1091
|
-
if (response.code !== 0) throw new Error(`Feishu thread list failed: code=${response.code} msg=${response.msg ?? "unknown"}`);
|
|
1092
|
-
const items = response.data?.items ?? [];
|
|
1093
|
-
const results = [];
|
|
1094
|
-
for (const item of items) {
|
|
1095
|
-
if (currentMessageId && item.message_id === currentMessageId) continue;
|
|
1096
|
-
if (rootMessageId && item.message_id === rootMessageId) continue;
|
|
1097
|
-
const parsed = parseFeishuMessageItem(item);
|
|
1098
|
-
results.push({
|
|
1099
|
-
messageId: parsed.messageId,
|
|
1100
|
-
senderId: parsed.senderId,
|
|
1101
|
-
senderType: parsed.senderType,
|
|
1102
|
-
content: parsed.content,
|
|
1103
|
-
contentType: parsed.contentType,
|
|
1104
|
-
createTime: parsed.createTime
|
|
1105
|
-
});
|
|
1106
|
-
if (results.length >= limit) break;
|
|
1107
|
-
}
|
|
1108
|
-
results.reverse();
|
|
1109
|
-
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
|
+
}) };
|
|
1110
965
|
}
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
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({
|
|
1114
986
|
cfg,
|
|
1115
|
-
to,
|
|
1116
987
|
accountId
|
|
1117
988
|
});
|
|
1118
|
-
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({
|
|
1119
1007
|
cfg,
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
const content = buildFeishuPostMessageContent({
|
|
1123
|
-
messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text ?? "", tableMode)),
|
|
1124
|
-
mentions
|
|
1008
|
+
to,
|
|
1009
|
+
accountId
|
|
1125
1010
|
});
|
|
1126
|
-
const
|
|
1127
|
-
|
|
1128
|
-
return sendReplyOrFallbackDirect(client, {
|
|
1011
|
+
const content = JSON.stringify({ image_key: imageKey });
|
|
1012
|
+
if (replyToMessageId) return sendReplyOrFallbackDirect(client, {
|
|
1129
1013
|
replyToMessageId,
|
|
1130
1014
|
replyInThread,
|
|
1131
1015
|
allowTopLevelReplyFallback,
|
|
1132
1016
|
content,
|
|
1133
|
-
msgType,
|
|
1017
|
+
msgType: "image",
|
|
1134
1018
|
directParams: {
|
|
1135
1019
|
receiveId,
|
|
1136
1020
|
receiveIdType,
|
|
1137
1021
|
content,
|
|
1138
|
-
msgType
|
|
1022
|
+
msgType: "image"
|
|
1139
1023
|
},
|
|
1140
|
-
directErrorPrefix: "Feishu send failed",
|
|
1141
|
-
replyErrorPrefix: "Feishu reply failed"
|
|
1024
|
+
directErrorPrefix: "Feishu image send failed",
|
|
1025
|
+
replyErrorPrefix: "Feishu image reply failed"
|
|
1142
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");
|
|
1143
1037
|
}
|
|
1144
|
-
|
|
1145
|
-
|
|
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";
|
|
1146
1044
|
const { client, receiveId, receiveIdType } = resolveFeishuSendTarget({
|
|
1147
1045
|
cfg,
|
|
1148
1046
|
to,
|
|
1149
1047
|
accountId
|
|
1150
1048
|
});
|
|
1151
|
-
const content = JSON.stringify(
|
|
1152
|
-
return sendReplyOrFallbackDirect(client, {
|
|
1049
|
+
const content = JSON.stringify({ file_key: fileKey });
|
|
1050
|
+
if (replyToMessageId) return sendReplyOrFallbackDirect(client, {
|
|
1153
1051
|
replyToMessageId,
|
|
1154
1052
|
replyInThread,
|
|
1155
1053
|
allowTopLevelReplyFallback,
|
|
1156
1054
|
content,
|
|
1157
|
-
msgType
|
|
1055
|
+
msgType,
|
|
1158
1056
|
directParams: {
|
|
1159
1057
|
receiveId,
|
|
1160
1058
|
receiveIdType,
|
|
1161
1059
|
content,
|
|
1162
|
-
msgType
|
|
1060
|
+
msgType
|
|
1163
1061
|
},
|
|
1164
|
-
directErrorPrefix: "Feishu
|
|
1165
|
-
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
|
|
1166
1151
|
});
|
|
1167
1152
|
}
|
|
1168
|
-
|
|
1169
|
-
const
|
|
1170
|
-
const
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
const
|
|
1179
|
-
const
|
|
1180
|
-
|
|
1181
|
-
|
|
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
|
+
}
|
|
1182
1195
|
});
|
|
1183
|
-
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
1184
1196
|
return {
|
|
1185
|
-
|
|
1186
|
-
|
|
1197
|
+
buffer: await workspace.read(FEISHU_VOICE_FILE_NAME),
|
|
1198
|
+
fileName: FEISHU_VOICE_FILE_NAME,
|
|
1199
|
+
contentType: "audio/ogg"
|
|
1187
1200
|
};
|
|
1188
|
-
}
|
|
1189
|
-
const content = buildFeishuPostMessageContent({ messageText: materializeFeishuPostMarkdownSoftBreaks(convertMarkdownTables(text, resolveMarkdownTableMode({
|
|
1190
|
-
cfg,
|
|
1191
|
-
channel: "feishu"
|
|
1192
|
-
}))) });
|
|
1193
|
-
assertFeishuPostWithinEnvelope(content, "Feishu message edit");
|
|
1194
|
-
const response = await client.im.message.patch({
|
|
1195
|
-
path: { message_id: messageId },
|
|
1196
|
-
data: { content }
|
|
1197
1201
|
});
|
|
1198
|
-
if (response.code !== 0) throw new Error(`Feishu message edit failed: ${response.msg || `code ${response.code}`}`);
|
|
1199
|
-
return {
|
|
1200
|
-
messageId,
|
|
1201
|
-
contentType: "post"
|
|
1202
|
-
};
|
|
1203
1202
|
}
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
body: { elements: [{
|
|
1214
|
-
tag: "markdown",
|
|
1215
|
-
content: text
|
|
1216
|
-
}] }
|
|
1217
|
-
};
|
|
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
|
+
}
|
|
1218
1212
|
}
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
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));
|
|
1233
1233
|
});
|
|
1234
|
+
} catch (err) {
|
|
1235
|
+
console.warn("[feishu] failed to probe media duration; upload will omit it:", err);
|
|
1236
|
+
return;
|
|
1234
1237
|
}
|
|
1235
|
-
const card = {
|
|
1236
|
-
schema: "2.0",
|
|
1237
|
-
config: { width_mode: "fill" },
|
|
1238
|
-
body: { elements }
|
|
1239
|
-
};
|
|
1240
|
-
if (options?.header) card.header = {
|
|
1241
|
-
title: {
|
|
1242
|
-
tag: "plain_text",
|
|
1243
|
-
content: options.header.title
|
|
1244
|
-
},
|
|
1245
|
-
template: resolveFeishuCardTemplate(options.header.template) ?? "blue"
|
|
1246
|
-
};
|
|
1247
|
-
return card;
|
|
1248
1238
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
async function sendStructuredCardFeishu(params) {
|
|
1253
|
-
const { cfg, to, text, replyToMessageId, replyInThread, allowTopLevelReplyFallback, mentions, accountId, header, note } = params;
|
|
1254
|
-
let cardText = text;
|
|
1255
|
-
if (mentions && mentions.length > 0) cardText = buildMentionedCardContent(mentions, text);
|
|
1256
|
-
return sendCardFeishu({
|
|
1257
|
-
cfg,
|
|
1258
|
-
to,
|
|
1259
|
-
card: buildStructuredCard(cardText, {
|
|
1260
|
-
header,
|
|
1261
|
-
note
|
|
1262
|
-
}),
|
|
1263
|
-
replyToMessageId,
|
|
1264
|
-
replyInThread,
|
|
1265
|
-
allowTopLevelReplyFallback,
|
|
1266
|
-
accountId
|
|
1267
|
-
});
|
|
1239
|
+
async function maybeProbeUploadDurationMs(params) {
|
|
1240
|
+
if (params.msgType !== "audio" && params.msgType !== "media") return;
|
|
1241
|
+
return await probeMediaDurationMs(params);
|
|
1268
1242
|
}
|
|
1269
1243
|
/**
|
|
1270
|
-
*
|
|
1271
|
-
*
|
|
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).
|
|
1272
1247
|
*/
|
|
1273
|
-
async function
|
|
1274
|
-
const { cfg, to,
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
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({
|
|
1278
1324
|
cfg,
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
allowTopLevelReplyFallback,
|
|
1325
|
+
file: buffer,
|
|
1326
|
+
fileName: name,
|
|
1327
|
+
fileType: routing.fileType ?? "stream",
|
|
1328
|
+
...durationMs !== void 0 ? { duration: durationMs } : {},
|
|
1284
1329
|
accountId
|
|
1285
|
-
});
|
|
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
|
+
};
|
|
1286
1344
|
}
|
|
1287
1345
|
//#endregion
|
|
1288
|
-
export {
|
|
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 };
|