feishuProvider.ts 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911
  1. import { getUnavailableReplyFallback } from "#src/bots/groupReply.js";
  2. import {
  3. createGroupMemberDirectory,
  4. type GroupMemberPage,
  5. } from "#src/bots/providers/groupMemberDirectory.js";
  6. import { channelContentPartsSchema, channelContentText, botGroupCardSchema } from "@zcode/shared";
  7. import {
  8. isFeishuBotSender,
  9. isGroupControlCard,
  10. readGroupConversationCardText,
  11. readGroupCardText,
  12. readGroupMessage,
  13. readGroupMentionText,
  14. } from "#src/bots/providers/feishuGroupMessages.js";
  15. /* eslint-disable max-lines -- Feishu provider 集中承载鉴权、消息解析、卡片发送和 reaction typing 适配,后续按能力拆分。 */
  16. import { botTopicMessageSchema } from "@zcode/shared";
  17. import { readTopicHistory, TopicHistoryPermissionError } from "#src/bots/topicHistory.js";
  18. import type {
  19. BotInboundAttachment,
  20. BotConfig,
  21. BotInboundMessage,
  22. BotOutboundMessage,
  23. BotProvider,
  24. SelectionPrompt,
  25. } from "@zcode/shared";
  26. import type {
  27. BotProviderAdapter,
  28. BotStreamingReplyCardHandle,
  29. BotStreamingReplyCardState,
  30. BotTransientInteractionCardHandle,
  31. } from "./types.js";
  32. import { formatBotMessage } from "../messages.js";
  33. import { fetchBotProviderJson } from "#src/bots/providers/providerRequest.js";
  34. import { createGroupInputReactionUpdater } from "#src/bots/providers/groupInputReaction.js";
  35. interface FeishuProviderDeps {
  36. loadCredential(key: string): Promise<string | null>;
  37. onDeliveryResult?(bot: BotConfig, error: string | undefined): void;
  38. }
  39. export interface FeishuWebSocketClient {
  40. close(): void;
  41. /** SDK 自动重连耗尽后的终态;旧测试替身可不提供。 */
  42. terminated?: Promise<void>;
  43. }
  44. const FEISHU_APP_ID_PATTERN = /^cli_[0-9a-fA-F]{16}$/;
  45. const FEISHU_WEBSOCKET_START_TIMEOUT_MS = 20_000;
  46. const FEISHU_WEBSOCKET_READY_POLL_MS = 100;
  47. // 修复原因:飞书 Card JSON 2.0 最多允许 200 个组件或元素。预留 20 个元素给
  48. // 状态行和服务端计数差异,避免长任务在更新阶段被 11310 拒绝后整轮熔断。
  49. export const FEISHU_STREAMING_CARD_TAGGED_ELEMENT_BUDGET = 180;
  50. const WEBSOCKET_OPEN_READY_STATE = 1;
  51. interface FeishuAccessTokenResponse {
  52. code?: number;
  53. msg?: string;
  54. tenant_access_token?: string;
  55. expire?: number;
  56. }
  57. interface FeishuSendMessageResponse {
  58. code?: number;
  59. msg?: string;
  60. error?: {
  61. log_id?: string;
  62. };
  63. data?: {
  64. message_id?: string;
  65. };
  66. }
  67. interface FeishuReactionResponse {
  68. code?: number;
  69. msg?: string;
  70. data?: {
  71. reaction_id?: string;
  72. };
  73. }
  74. const FEISHU_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30_000;
  75. interface FeishuAppInfoResponse {
  76. code?: number;
  77. msg?: string;
  78. data?: {
  79. app?: {
  80. app_name?: string;
  81. primary_language?: string;
  82. i18n?: Array<{
  83. i18n_key?: string;
  84. name?: string;
  85. }>;
  86. };
  87. };
  88. }
  89. interface FeishuUserInfoResponse {
  90. code?: number;
  91. msg?: string;
  92. data?: {
  93. user?: {
  94. name?: string;
  95. en_name?: string;
  96. nickname?: string;
  97. };
  98. };
  99. }
  100. const accessTokenCache = new Map<string, { token: string; expiresAt: number }>();
  101. const typingReactionIds = new Map<string, string>();
  102. const userDisplayNameCache = new Map<string, { name: string | null; expiresAt: number }>();
  103. const FEISHU_ELICITATION_FORM_FIELD_NAME = "answer";
  104. const FEISHU_ELICITATION_FORM_VALUE_PREFIX = "__form__:";
  105. const FEISHU_ELICITATION_CUSTOM_OPTION_ID = "__custom__";
  106. function isRecord(value: unknown): value is Record<string, unknown> {
  107. return typeof value === "object" && value !== null;
  108. }
  109. function readPlanApprovalContent(message: BotOutboundMessage): string | null {
  110. const schema = message.elicitation?.schema;
  111. if (!isRecord(schema) || schema.interaction !== "plan_approval") {
  112. return null;
  113. }
  114. return typeof schema.plan === "string" && schema.plan.trim() ? schema.plan.trim() : null;
  115. }
  116. function formatSelectionCommand(selection: SelectionPrompt, optionId: string): string {
  117. if (selection.action === "permission.respond" || selection.action === "queue.cancel") {
  118. return optionId;
  119. }
  120. if (selection.action === "elicitation.respond") {
  121. return selection.token
  122. ? `/elicitation ${selection.token} ${optionId}`
  123. : `/elicitation ${optionId}`;
  124. }
  125. if (selection.action === "model.provider.set") {
  126. return `/model provider ${optionId}`;
  127. }
  128. if (selection.action === "model.set") {
  129. return `/model model ${optionId}`;
  130. }
  131. return `/${selection.action.replace(".set", "")} ${optionId}`;
  132. }
  133. function readElicitationAnswerValues(message: BotOutboundMessage, questionIndex: number): string[] {
  134. return message.elicitation?.answers?.[String(questionIndex)] ?? [];
  135. }
  136. function formatElicitationAnswerLabel(message: BotOutboundMessage, questionIndex: number): string {
  137. const question = message.elicitation?.questions[questionIndex];
  138. const values = readElicitationAnswerValues(message, questionIndex);
  139. if (!question || values.length === 0) {
  140. return "";
  141. }
  142. const labels = values.map((value) => {
  143. const option = question.options.find((item) => item.value === value);
  144. return option?.label ?? value;
  145. });
  146. return labels.join(", ");
  147. }
  148. function formatFeishuPlainText(content: string): Record<string, string> {
  149. return { tag: "plain_text", content };
  150. }
  151. function buildFeishuElicitationFormCommand(token: string, value?: unknown): string {
  152. const suffix =
  153. value === undefined
  154. ? FEISHU_ELICITATION_FORM_VALUE_PREFIX
  155. : `${FEISHU_ELICITATION_FORM_VALUE_PREFIX}${encodeURIComponent(JSON.stringify(value))}`;
  156. return `/elicitation ${token} ${suffix}`;
  157. }
  158. function readFeishuElicitationCustomValues(
  159. message: BotOutboundMessage,
  160. question: NonNullable<BotOutboundMessage["elicitation"]>["questions"][number],
  161. questionIndex: number,
  162. ): string[] {
  163. const optionValues = new Set(question.options.map((option) => option.value));
  164. return readElicitationAnswerValues(message, questionIndex).filter(
  165. (value) => !optionValues.has(value),
  166. );
  167. }
  168. function buildFeishuElicitationChoiceButton(params: {
  169. message: BotOutboundMessage;
  170. question: NonNullable<BotOutboundMessage["elicitation"]>["questions"][number];
  171. option: NonNullable<BotOutboundMessage["elicitation"]>["questions"][number]["options"][number];
  172. selectedValues: readonly string[];
  173. }): Record<string, unknown> {
  174. const selected = params.selectedValues.includes(params.option.value);
  175. const marker = params.question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○";
  176. return buildFeishuButtonElement({
  177. text: `${marker} ${params.option.label}`,
  178. type: selected ? "primary" : "default",
  179. command: buildFeishuElicitationOptionCommand(params.message, params.option.value),
  180. originalText: params.message.text,
  181. });
  182. }
  183. function buildFeishuElicitationOptionCommand(
  184. message: BotOutboundMessage,
  185. optionId: string,
  186. ): string {
  187. const token = message.selection?.token;
  188. return token
  189. ? formatSelectionCommand(
  190. {
  191. id: message.selection?.id ?? "",
  192. token,
  193. title: message.selection?.title ?? message.text,
  194. action: "elicitation.respond",
  195. options: [],
  196. },
  197. optionId,
  198. )
  199. : optionId;
  200. }
  201. function isFeishuElicitationCustomExpanded(
  202. message: BotOutboundMessage,
  203. questionIndex: number,
  204. ): boolean {
  205. return message.elicitation?.expandedCustomAnswerQuestionIndexes?.includes(questionIndex) ?? false;
  206. }
  207. function buildFeishuElicitationCustomButton(
  208. message: BotOutboundMessage,
  209. question: NonNullable<BotOutboundMessage["elicitation"]>["questions"][number],
  210. questionIndex: number,
  211. ): Record<string, unknown> {
  212. const customValues = readFeishuElicitationCustomValues(message, question, questionIndex);
  213. const expanded = isFeishuElicitationCustomExpanded(message, questionIndex);
  214. const selected = expanded || customValues.length > 0;
  215. const marker = question.multiSelect ? (selected ? "☑" : "☐") : selected ? "●" : "○";
  216. const customLabel = formatBotMessage(message.locale, "elicitationCustomOption");
  217. return buildFeishuButtonElement({
  218. text: `${marker} ${customLabel}`,
  219. type: selected ? "primary" : "default",
  220. command: buildFeishuElicitationOptionCommand(message, FEISHU_ELICITATION_CUSTOM_OPTION_ID),
  221. originalText: message.text,
  222. });
  223. }
  224. function buildFeishuElicitationForm(
  225. message: BotOutboundMessage,
  226. question: NonNullable<BotOutboundMessage["elicitation"]>["questions"][number],
  227. questionIndex: number,
  228. ): Record<string, unknown> | null {
  229. const selection = message.selection;
  230. if (!selection?.token) {
  231. return null;
  232. }
  233. const customExpanded = isFeishuElicitationCustomExpanded(message, questionIndex);
  234. const shouldShowInput = question.options.length === 0 || customExpanded;
  235. const shouldShowSubmit = question.multiSelect || shouldShowInput;
  236. if (!shouldShowSubmit) {
  237. return null;
  238. }
  239. const customValues = readFeishuElicitationCustomValues(message, question, questionIndex);
  240. const formElements: Array<Record<string, unknown>> = [];
  241. if (shouldShowInput) {
  242. formElements.push({
  243. tag: "input",
  244. name: FEISHU_ELICITATION_FORM_FIELD_NAME,
  245. required: question.options.length === 0,
  246. width: "fill",
  247. input_type: "multiline_text",
  248. rows: 2,
  249. auto_resize: true,
  250. max_rows: 5,
  251. placeholder: formatFeishuPlainText(
  252. formatBotMessage(message.locale, "elicitationCustomPlaceholder"),
  253. ),
  254. default_value: customValues.join(", "),
  255. });
  256. }
  257. formElements.push({
  258. tag: "button",
  259. text: formatFeishuPlainText(formatBotMessage(message.locale, "elicitationSubmitOption")),
  260. type: "primary",
  261. form_action_type: "submit",
  262. name: "submit",
  263. behaviors: [
  264. {
  265. type: "callback",
  266. value: {
  267. command: buildFeishuElicitationFormCommand(selection.token),
  268. zcodeCardText: message.text,
  269. },
  270. },
  271. ],
  272. });
  273. return {
  274. tag: "form",
  275. name: `elicitation_form_${questionIndex}`,
  276. direction: "vertical",
  277. vertical_spacing: "8px",
  278. elements: formElements,
  279. };
  280. }
  281. function buildFeishuElicitationAnswerElements(
  282. message: BotOutboundMessage,
  283. ): Array<Record<string, unknown>> {
  284. const elicitation = message.elicitation;
  285. if (!elicitation) {
  286. return [];
  287. }
  288. const total = elicitation.questions.length;
  289. const isCompleted = elicitation.status === "completed" || elicitation.status === "cancelled";
  290. const elements: Array<Record<string, unknown>> = [];
  291. elicitation.questions.forEach((question, index) => {
  292. // 修复原因:当前题的多选值只是尚未提交的草稿。如果也放进上方历史区,
  293. // 同一问题会同时显示为“已回答”和“待回答”。进行中只累积此前已提交的题目。
  294. if (!isCompleted && index >= elicitation.currentQuestionIndex) {
  295. return;
  296. }
  297. const answer = formatElicitationAnswerLabel(message, index);
  298. if (!answer) {
  299. return;
  300. }
  301. elements.push(
  302. {
  303. tag: "markdown",
  304. content: formatFeishuCardMarkdownContent(`#### ${index + 1}/${total} ${question.question}`),
  305. },
  306. {
  307. tag: "markdown",
  308. content: formatFeishuCardMarkdownContent(answer),
  309. },
  310. );
  311. });
  312. return elements;
  313. }
  314. function addGroupCardContext(
  315. card: Record<string, unknown>,
  316. message: BotOutboundMessage,
  317. ): Record<string, unknown> {
  318. const bodyMentions = new Set(
  319. message.contentParts?.flatMap((part) =>
  320. part.type === "channelMention" ? [part.targetId] : [],
  321. ) ?? [],
  322. );
  323. if (message.contentParts && isRecord(card.body)) {
  324. card.body.elements = [
  325. {
  326. tag: "markdown",
  327. content: message.contentParts
  328. .map((part) =>
  329. part.type === "channelMention"
  330. ? `<at id=${part.targetId}></at>`
  331. : part.text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;"),
  332. )
  333. .join(""),
  334. },
  335. ];
  336. }
  337. // 只接受服务注入的个人 ID,不把正文/姓名解析成提醒,也不允许 all 扩大通知范围。
  338. const ids = [...new Set(message.mentionedUserIds ?? [])].filter(
  339. (id) => /^ou_[a-zA-Z0-9_-]+$/u.test(id) && !bodyMentions.has(id),
  340. );
  341. if (
  342. message.providerUserId.startsWith("oc_") &&
  343. ids.length &&
  344. isRecord(card.body) &&
  345. Array.isArray(card.body.elements)
  346. ) {
  347. card.body.elements.unshift({
  348. tag: "markdown",
  349. content: ids.map((id) => `<at id=${id}></at>`).join(" "),
  350. });
  351. }
  352. if (!message.groupCard) return card;
  353. const visit = (node: unknown): void => {
  354. if (Array.isArray(node)) {
  355. for (const child of node) visit(child);
  356. return;
  357. }
  358. if (!isRecord(node)) return;
  359. if (isRecord(node.value) && typeof node.value.command === "string")
  360. node.value = { ...node.value, groupCard: message.groupCard };
  361. for (const value of Object.values(node)) visit(value);
  362. };
  363. visit(card);
  364. return card;
  365. }
  366. function buildFeishuElicitationCardPayload(message: BotOutboundMessage): Record<string, unknown> {
  367. return addGroupCardContext(buildFeishuElicitationCardPayloadBody(message), message);
  368. }
  369. function buildFeishuInteractiveCardPayload(message: BotOutboundMessage): Record<string, unknown> {
  370. return addGroupCardContext(buildFeishuInteractiveCardPayloadBody(message), message);
  371. }
  372. function buildFeishuElicitationCardPayloadBody(
  373. message: BotOutboundMessage,
  374. ): Record<string, unknown> {
  375. const elicitation = message.elicitation;
  376. const selection = message.selection;
  377. if (!elicitation) {
  378. return buildFeishuInteractiveCardPayloadBody(message);
  379. }
  380. const currentQuestion =
  381. elicitation.questions[elicitation.currentQuestionIndex] ?? elicitation.questions[0];
  382. const isCompleted = elicitation.status === "completed" || elicitation.status === "cancelled";
  383. const answerElements = buildFeishuElicitationAnswerElements(message);
  384. const planApprovalContent = readPlanApprovalContent(message);
  385. const elements: Array<Record<string, unknown>> = [];
  386. if (isCompleted && planApprovalContent) {
  387. // 修复原因:Plan 交互完成后保留卡片时,旧终态分支只渲染审批答案,导致计划正文消失。
  388. // 只读终态仍需保留完整计划,用户才能在聊天历史中回看自己批准或取消的内容。
  389. elements.push({
  390. tag: "markdown",
  391. content: formatFeishuCardMarkdownContent(planApprovalContent),
  392. });
  393. if (answerElements.length > 0) {
  394. elements.push({ tag: "hr" });
  395. }
  396. }
  397. elements.push(...answerElements);
  398. if (!isCompleted && currentQuestion) {
  399. if (answerElements.length > 0) {
  400. elements.push({ tag: "hr" });
  401. }
  402. if (!planApprovalContent) {
  403. elements.push({
  404. tag: "markdown",
  405. content: formatFeishuCardMarkdownContent(
  406. `#### ${formatBotMessage(message.locale, "elicitationQuestionTitle")}`,
  407. ),
  408. });
  409. }
  410. // 修复原因:ExitPlanMode 不是普通问答。计划正文若只留在流式消息中,审批卡会失去上下文;
  411. // 因此计划审批使用专属正文,而 AskUserQuestion 继续沿用通用“提问”结构。
  412. const contentParts = planApprovalContent
  413. ? [planApprovalContent]
  414. : [
  415. currentQuestion.header && currentQuestion.header !== currentQuestion.question
  416. ? `**${currentQuestion.header}**`
  417. : null,
  418. currentQuestion.question,
  419. ];
  420. elements.push({
  421. tag: "markdown",
  422. content: formatFeishuCardMarkdownContent(
  423. contentParts
  424. .filter((part): part is string => typeof part === "string" && part.length > 0)
  425. .join("\n\n"),
  426. ),
  427. });
  428. if (planApprovalContent) {
  429. elements.push(
  430. { tag: "hr" },
  431. {
  432. tag: "markdown",
  433. content: formatFeishuCardMarkdownContent(
  434. `**${formatBotMessage(message.locale, "planApprovalTitle")}**`,
  435. ),
  436. },
  437. );
  438. }
  439. const selectedValues = readElicitationAnswerValues(message, elicitation.currentQuestionIndex);
  440. for (const option of currentQuestion.options) {
  441. const displayOption = planApprovalContent
  442. ? {
  443. ...option,
  444. label: formatBotMessage(message.locale, "planApprovalApprove"),
  445. description: formatBotMessage(message.locale, "planApprovalApproveDescription"),
  446. }
  447. : option;
  448. elements.push(
  449. buildFeishuElicitationChoiceButton({
  450. message,
  451. question: currentQuestion,
  452. option: displayOption,
  453. selectedValues,
  454. }),
  455. );
  456. }
  457. elements.push(
  458. buildFeishuElicitationCustomButton(
  459. message,
  460. currentQuestion,
  461. elicitation.currentQuestionIndex,
  462. ),
  463. );
  464. const form = buildFeishuElicitationForm(
  465. message,
  466. currentQuestion,
  467. elicitation.currentQuestionIndex,
  468. );
  469. if (form) {
  470. elements.push(form);
  471. }
  472. const shouldShowCancel =
  473. currentQuestion.multiSelect ||
  474. currentQuestion.options.length === 0 ||
  475. isFeishuElicitationCustomExpanded(message, elicitation.currentQuestionIndex);
  476. if (selection && shouldShowCancel) {
  477. const customExpanded = isFeishuElicitationCustomExpanded(
  478. message,
  479. elicitation.currentQuestionIndex,
  480. );
  481. elements.push(
  482. ...(selection.showCancel === false
  483. ? []
  484. : [
  485. buildFeishuButtonElement({
  486. text:
  487. selection.cancelLabel ??
  488. formatBotMessage(message.locale, "selectionCancelOption"),
  489. type: "default",
  490. command:
  491. customExpanded && currentQuestion.options.length > 0
  492. ? buildFeishuElicitationOptionCommand(
  493. message,
  494. FEISHU_ELICITATION_CUSTOM_OPTION_ID,
  495. )
  496. : "/cancel",
  497. originalText: message.text,
  498. }),
  499. ]),
  500. );
  501. }
  502. } else if (elicitation.status === "cancelled") {
  503. elements.push({
  504. tag: "markdown",
  505. content: formatFeishuCardMarkdownContent(
  506. formatBotMessage(message.locale, "elicitationCancelledCard"),
  507. ),
  508. });
  509. }
  510. return {
  511. schema: "2.0",
  512. config: { wide_screen_mode: true },
  513. body: { elements },
  514. };
  515. }
  516. function getFeishuDomainProvider(bot: Pick<BotConfig, "provider">): "feishu" | "lark" {
  517. return bot.provider === "lark" ? "lark" : "feishu";
  518. }
  519. function readFeishuPayloadProvider(payload: Record<string, unknown>): BotProvider {
  520. return readString(payload, "zcodeProvider") === "lark" ? "lark" : "feishu";
  521. }
  522. function getFeishuBaseUrl(bot: Pick<BotConfig, "provider">): string {
  523. return getFeishuDomainProvider(bot) === "lark"
  524. ? "https://open.larksuite.com"
  525. : "https://open.feishu.cn";
  526. }
  527. function readString(record: Record<string, unknown> | null | undefined, key: string): string {
  528. const value = record?.[key];
  529. return typeof value === "string" ? value : "";
  530. }
  531. function readFeishuCallbackEvent(payload: Record<string, unknown>): Record<string, unknown> {
  532. const event = isRecord(payload.event) ? payload.event : null;
  533. return event ?? payload;
  534. }
  535. function readFeishuChatType(value: string): "private" | "group" {
  536. return value === "group" || value === "group_chat" ? "group" : "private";
  537. }
  538. function parseJsonRecord(value: unknown): Record<string, unknown> | null {
  539. if (isRecord(value)) {
  540. return value;
  541. }
  542. if (typeof value !== "string") {
  543. return null;
  544. }
  545. try {
  546. const parsed = JSON.parse(value) as unknown;
  547. return isRecord(parsed) ? parsed : null;
  548. } catch {
  549. return null;
  550. }
  551. }
  552. function stripFeishuMentions(text: string): string {
  553. return text
  554. .replace(/<at\b[^>]*>.*?<\/at>/giu, "")
  555. .replace(/@\S+/gu, "")
  556. .trim();
  557. }
  558. function readFeishuPostLocaleContent(content: Record<string, unknown>): unknown {
  559. const post = isRecord(content.post) ? content.post : null;
  560. const zhCn = isRecord(content.zh_cn) ? content.zh_cn : isRecord(post?.zh_cn) ? post.zh_cn : null;
  561. const enUs = isRecord(content.en_us) ? content.en_us : isRecord(post?.en_us) ? post.en_us : null;
  562. return content.content ?? zhCn?.content ?? enUs?.content;
  563. }
  564. function readFeishuPostLocaleTitle(content: Record<string, unknown>): string {
  565. const post = isRecord(content.post) ? content.post : null;
  566. const zhCn = isRecord(content.zh_cn) ? content.zh_cn : isRecord(post?.zh_cn) ? post.zh_cn : null;
  567. const enUs = isRecord(content.en_us) ? content.en_us : isRecord(post?.en_us) ? post.en_us : null;
  568. return readString(content, "title") || readString(zhCn, "title") || readString(enUs, "title");
  569. }
  570. function formatFeishuPostToken(token: unknown, botOpenId?: string, mentions?: unknown): string {
  571. if (typeof token === "string") {
  572. return token;
  573. }
  574. if (Array.isArray(token)) {
  575. return token
  576. .map((item) => formatFeishuPostToken(item, botOpenId, mentions))
  577. .filter(Boolean)
  578. .join("");
  579. }
  580. if (!isRecord(token)) {
  581. return "";
  582. }
  583. const tag = readString(token, "tag");
  584. if (tag === "at") {
  585. if (!botOpenId) return "";
  586. // 群富文本中的自身 @ 也须进入有序 mention,不能在转文本时提前丢掉。
  587. const id = readString(token, "user_id");
  588. const mention = (Array.isArray(mentions) ? mentions : []).find(
  589. (item) => isRecord(item) && isRecord(item.id) && item.id.open_id === id,
  590. );
  591. if (isRecord(mention) && typeof mention.key === "string") return mention.key;
  592. return id.startsWith("@_") ? id : `@${readString(token, "user_name") || id}`;
  593. }
  594. const nested = token.content ?? token.children ?? token.elements;
  595. const nestedText = Array.isArray(nested)
  596. ? formatFeishuPostToken(nested, botOpenId, mentions)
  597. : "";
  598. const text =
  599. readString(token, "text") ||
  600. readString(token, "un_escape_text") ||
  601. readString(token, "name") ||
  602. nestedText;
  603. if (tag === "a") {
  604. const href = readString(token, "href");
  605. if (href && href !== text) {
  606. return text ? `${text} ${href}` : href;
  607. }
  608. }
  609. return text;
  610. }
  611. function readFeishuPostText(
  612. content: Record<string, unknown> | null,
  613. botOpenId?: string,
  614. mentions?: unknown,
  615. ): string {
  616. if (!content) {
  617. return "";
  618. }
  619. const postContent = readFeishuPostLocaleContent(content);
  620. const lines = Array.isArray(postContent)
  621. ? postContent
  622. .map((line) => formatFeishuPostToken(line, botOpenId, mentions).trim())
  623. .filter(Boolean)
  624. : [];
  625. const title = readFeishuPostLocaleTitle(content).trim();
  626. const body = lines.join("\n").trim();
  627. if (title && body) {
  628. return `${title}\n${body}`;
  629. }
  630. return body || title;
  631. }
  632. function inferFeishuAttachmentKind(msgType: string): BotInboundAttachment["kind"] {
  633. if (msgType === "image") return "image";
  634. if (msgType === "audio") return "audio";
  635. if (msgType === "media" || msgType === "video") return "video";
  636. return "file";
  637. }
  638. function defaultFeishuMimeType(kind: BotInboundAttachment["kind"]): string {
  639. if (kind === "image") return "image/jpeg";
  640. if (kind === "audio") return "audio/mpeg";
  641. if (kind === "video") return "video/mp4";
  642. return "application/octet-stream";
  643. }
  644. function readFeishuAttachment(
  645. msgType: string,
  646. content: Record<string, unknown> | null,
  647. ): BotInboundAttachment | null {
  648. if (!content) {
  649. return null;
  650. }
  651. const providerFileId =
  652. readString(content, "image_key") ||
  653. readString(content, "file_key") ||
  654. readString(content, "media_key") ||
  655. readString(content, "audio_key") ||
  656. readString(content, "key");
  657. if (!providerFileId) {
  658. return null;
  659. }
  660. const kind = inferFeishuAttachmentKind(msgType);
  661. const filename =
  662. readString(content, "file_name") ||
  663. readString(content, "filename") ||
  664. `${msgType}-${providerFileId.slice(0, 8)}`;
  665. const mimeType =
  666. readString(content, "mime_type") ||
  667. readString(content, "mimeType") ||
  668. defaultFeishuMimeType(kind);
  669. return {
  670. id: providerFileId,
  671. kind,
  672. filename,
  673. mimeType,
  674. ...(typeof content.size === "number" ? { sizeBytes: content.size } : {}),
  675. providerFileId,
  676. };
  677. }
  678. function readFeishuTextMessage(
  679. botId: string,
  680. payload: Record<string, unknown>,
  681. ): BotInboundMessage | null {
  682. const provider = readFeishuPayloadProvider(payload);
  683. // Bugfix: 飞书 node-sdk 的 WebSocket EventDispatcher 在不同事件/版本下可能把 event 字段摊平到顶层。
  684. // 之前只读 payload.event.message,长连接确实收到消息时也会解析成 0 条 inbound。
  685. const event = isRecord(payload.event) ? payload.event : payload;
  686. const message = isRecord(event?.message) ? event.message : null;
  687. const sender = isRecord(event?.sender) ? event.sender : null;
  688. const senderId = isRecord(sender?.sender_id) ? sender.sender_id : null;
  689. const content = isRecord(payload.zcodeNativeCardContent)
  690. ? payload.zcodeNativeCardContent
  691. : parseJsonRecord(message?.content);
  692. const msgType = readString(message, "message_type") || readString(message, "msg_type");
  693. // 交互卡及其机器人确认回复属于控制流程,过去提取卡片文字会误触发另一机器人。
  694. if (
  695. payload.zcodeIgnoreInteractionMessage === true ||
  696. (isFeishuBotSender(readString(sender, "sender_type")) &&
  697. msgType === "interactive" &&
  698. isGroupControlCard(content))
  699. )
  700. return null;
  701. const attachment = readFeishuAttachment(msgType, content);
  702. const attachments: BotInboundAttachment[] = attachment ? [attachment] : [];
  703. if (isRecord(payload.zcodeReferencedAttachment)) {
  704. const ref = payload.zcodeReferencedAttachment;
  705. if (
  706. (ref.kind === "image" || ref.kind === "file") &&
  707. typeof ref.providerFileId === "string" &&
  708. typeof ref.filename === "string" &&
  709. typeof ref.mimeType === "string"
  710. ) {
  711. const metadata = isRecord(ref.providerMetadata) ? ref.providerMetadata : null;
  712. const resourceMessageId = readString(metadata, "resourceMessageId");
  713. if (resourceMessageId)
  714. attachments.push({
  715. id: ref.providerFileId,
  716. kind: ref.kind,
  717. providerFileId: ref.providerFileId,
  718. filename: ref.filename,
  719. mimeType: ref.mimeType,
  720. providerMetadata: { resourceMessageId },
  721. });
  722. }
  723. }
  724. if (Array.isArray(payload.zcodeReferencedInlineImages)) {
  725. for (const image of payload.zcodeReferencedInlineImages) {
  726. if (
  727. isRecord(image) &&
  728. typeof image.imageKey === "string" &&
  729. typeof image.messageId === "string"
  730. ) {
  731. const item = readFeishuAttachment("image", { image_key: image.imageKey });
  732. if (item)
  733. attachments.push({ ...item, providerMetadata: { resourceMessageId: image.messageId } });
  734. }
  735. }
  736. }
  737. let malformedInlineImage = false;
  738. if (msgType === "post" && content) {
  739. const visit = (node: unknown): void => {
  740. if (Array.isArray(node)) {
  741. for (const child of node) visit(child);
  742. return;
  743. }
  744. if (!isRecord(node)) return;
  745. if (node.tag === "img") {
  746. const image = readFeishuAttachment("image", node);
  747. if (image) attachments.push(image);
  748. else malformedInlineImage = true;
  749. }
  750. visit(node.content ?? node.children ?? node.elements);
  751. };
  752. visit(readFeishuPostLocaleContent(content));
  753. }
  754. // 缺少图片引用不能静默降级成只执行正文。
  755. if (malformedInlineImage) return null;
  756. // Bugfix: 飞书客户端里看起来像普通文字的富文本/带链接消息会以 message_type=post 推送。
  757. // 之前只读 content.text,post 消息被解析成空文本并直接丢弃,所以用户侧表现为“发了普通消息但 app 没反应”。
  758. const rawText =
  759. (msgType === "interactive" ? readGroupConversationCardText(content, message?.mentions) : "") ||
  760. readString(content, "text") ||
  761. readFeishuPostText(
  762. content,
  763. readString(payload, "zcodeBotOpenId") || undefined,
  764. message?.mentions,
  765. ) ||
  766. readString(event, "text_without_at_bot") ||
  767. readString(event, "text");
  768. const incomingChatType = readString(message, "chat_type") || readString(event, "chat_type");
  769. if (incomingChatType === "topic_group") return null;
  770. const groupMessage =
  771. incomingChatType === "group"
  772. ? readGroupMessage(
  773. rawText,
  774. message?.mentions,
  775. readString(payload, "zcodeBotOpenId"),
  776. readString(sender, "sender_type"),
  777. readString(senderId, "open_id"),
  778. )
  779. : undefined;
  780. // Provider 验证发送者与 mention 身份;机器人群主聊天必须原生 @,群/话题启用状态由服务校验。
  781. if (
  782. isFeishuBotSender(readString(sender, "sender_type")) &&
  783. (incomingChatType !== "group" ||
  784. (!readString(message, "thread_id") && !groupMessage?.mentionedBot))
  785. )
  786. return null;
  787. if (
  788. incomingChatType === "group" &&
  789. (!groupMessage || (!groupMessage.mentionedBot && !readString(message, "thread_id")))
  790. )
  791. return null;
  792. const text = groupMessage?.text ?? stripFeishuMentions(rawText);
  793. // 群权限只使用应用内 open_id,不能把其他 ID 命名空间误当作绑定身份。
  794. if (incomingChatType === "group" && !readString(senderId, "open_id")) return null;
  795. const userId =
  796. readString(senderId, "open_id") ||
  797. readString(senderId, "user_id") ||
  798. readString(senderId, "union_id") ||
  799. readString(event, "open_id") ||
  800. readString(event, "user_id") ||
  801. readString(event, "union_id");
  802. const chatId = readString(message, "chat_id") || readString(event, "open_chat_id");
  803. const messageId = readString(message, "message_id");
  804. // 群内仅 @ 仍是有效唤起,空需求由服务结合引用/话题背景处理。
  805. if ((!text && attachments.length === 0 && incomingChatType !== "group") || !userId) {
  806. return null;
  807. }
  808. const chatType = readFeishuChatType(
  809. readString(message, "chat_type") || readString(event, "chat_type"),
  810. );
  811. return {
  812. botId,
  813. text,
  814. ...(groupMessage
  815. ? {
  816. ...(isFeishuBotSender(readString(sender, "sender_type"))
  817. ? { senderType: "app" as const }
  818. : {}),
  819. botOpenId: readString(payload, "zcodeBotOpenId") || undefined,
  820. mentionedBot: groupMessage.mentionedBot,
  821. commandText: groupMessage.commandText,
  822. ...(groupMessage.contentParts
  823. ? {
  824. contentParts: groupMessage.contentParts.map((part) =>
  825. part.type === "text"
  826. ? part
  827. : {
  828. ...part,
  829. channel: provider === "lark" ? ("lark" as const) : ("feishu" as const),
  830. refId: `${messageId}:${part.refId}`,
  831. },
  832. ),
  833. }
  834. : {}),
  835. topicRootIsCurrentBot: payload.zcodeTopicRootIsCurrentBot === true,
  836. }
  837. : {}),
  838. ...(isRecord(payload.zcodeReferencedMessage) &&
  839. typeof payload.zcodeReferencedMessage.messageId === "string" &&
  840. typeof payload.zcodeReferencedMessage.text === "string"
  841. ? {
  842. referencedMessage: {
  843. ...payload.zcodeReferencedMessage,
  844. messageId: payload.zcodeReferencedMessage.messageId,
  845. text: payload.zcodeReferencedMessage.text,
  846. },
  847. }
  848. : {}),
  849. ...(attachments.length ? { attachments } : {}),
  850. actor: {
  851. provider,
  852. botId,
  853. providerUserId: userId,
  854. displayName: readString(sender, "sender_name") || undefined,
  855. chatType,
  856. chatId: chatType === "group" && chatId ? chatId : undefined,
  857. ...(chatType === "group" && readString(message, "thread_id")
  858. ? {
  859. threadId: readString(message, "thread_id"),
  860. rootMessageId: readString(message, "root_id") || messageId,
  861. }
  862. : {}),
  863. providerMessageId: messageId || undefined,
  864. },
  865. };
  866. }
  867. function readFeishuCardAction(
  868. botId: string,
  869. payload: Record<string, unknown>,
  870. ): BotInboundMessage | null {
  871. const provider = readFeishuPayloadProvider(payload);
  872. const event = readFeishuCallbackEvent(payload);
  873. const action = isRecord(event.action) ? event.action : null;
  874. const value = isRecord(action?.value) ? action.value : null;
  875. const formValue = isRecord(action?.form_value) ? action.form_value : null;
  876. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  877. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  878. const rawCommand =
  879. readString(value, "command") ||
  880. readString(value, "text") ||
  881. readString(behaviorValue, "command") ||
  882. readString(behaviorValue, "text");
  883. const submittedAnswer = formValue?.[FEISHU_ELICITATION_FORM_FIELD_NAME];
  884. const command =
  885. rawCommand && rawCommand.includes(FEISHU_ELICITATION_FORM_VALUE_PREFIX)
  886. ? buildFeishuElicitationFormCommand(rawCommand.split(/\s+/u)[1] ?? "", submittedAnswer)
  887. : rawCommand;
  888. const operator = isRecord(event.operator) ? event.operator : null;
  889. const operatorId = isRecord(operator?.operator_id) ? operator.operator_id : null;
  890. const openId =
  891. readString(operatorId, "open_id") ||
  892. readString(operator, "open_id") ||
  893. readString(event, "open_id") ||
  894. readString(event, "user_id") ||
  895. readString(payload, "open_id") ||
  896. readString(payload, "user_id");
  897. const context = isRecord(event.context) ? event.context : null;
  898. const contextChatType =
  899. readString(context, "chat_type") ||
  900. readString(event, "chat_type") ||
  901. readString(payload, "chat_type");
  902. const chatId = readString(context, "open_chat_id") || readString(context, "chat_id");
  903. const message = isRecord(event.message) ? event.message : null;
  904. const header = isRecord(payload.header) ? payload.header : null;
  905. const providerMessageId =
  906. readString(event, "event_id") ||
  907. readString(header, "event_id") ||
  908. readString(payload, "uuid") ||
  909. readString(payload, "event_id") ||
  910. readString(context, "open_message_id") ||
  911. readString(context, "message_id") ||
  912. readString(message, "message_id") ||
  913. readString(action, "value_id");
  914. if (!command || !openId) {
  915. return null;
  916. }
  917. // Bugfix: 飞书卡片回调的 context.open_chat_id 在私聊按钮里也可能存在。
  918. // 之前用 chatId 是否存在判断群聊,会把私聊里的卡片按钮误拒成“只支持私聊”。
  919. const chatType = readFeishuChatType(readString(payload, "zcodeChatType") || contextChatType);
  920. const groupCard = botGroupCardSchema.safeParse(value?.groupCard ?? behaviorValue?.groupCard);
  921. return {
  922. botId,
  923. ...(chatType === "group"
  924. ? { groupCardAction: true, ...(groupCard.success ? { groupCard: groupCard.data } : {}) }
  925. : {}),
  926. text: command,
  927. actor: {
  928. provider,
  929. botId,
  930. providerUserId: openId,
  931. chatType,
  932. chatId: chatType === "group" && chatId ? chatId : undefined,
  933. ...(chatType === "group" && groupCard.success && groupCard.data.threadId
  934. ? { threadId: groupCard.data.threadId }
  935. : {}),
  936. ...(providerMessageId ? { providerMessageId } : {}),
  937. },
  938. };
  939. }
  940. function readFeishuCardUpdateToken(payload: unknown): string {
  941. if (!isRecord(payload)) {
  942. return "";
  943. }
  944. const event = readFeishuCallbackEvent(payload);
  945. const action = isRecord(event.action) ? event.action : null;
  946. const context = isRecord(event.context) ? event.context : null;
  947. // Bugfix: Card JSON 2.0 回调的更新 token 不总在旧版 action.token 上。
  948. // 新版按钮由 behaviors.callback 触发时,飞书/Lark 可能把 token 放在事件或 context 上;漏读会让 card/update 静默跳过,按钮留在原卡片里。
  949. return (
  950. readString(event, "token") ||
  951. readString(event, "card_update_token") ||
  952. readString(event, "update_token") ||
  953. readString(payload, "token") ||
  954. readString(payload, "card_update_token") ||
  955. readString(payload, "update_token") ||
  956. readString(action, "token") ||
  957. readString(action, "card_update_token") ||
  958. readString(action, "update_token") ||
  959. readString(context, "token") ||
  960. readString(context, "card_update_token") ||
  961. readString(context, "update_token")
  962. );
  963. }
  964. function readFeishuCardUpdateOpenIds(payload: unknown): string[] {
  965. if (!isRecord(payload)) {
  966. return [];
  967. }
  968. const event = readFeishuCallbackEvent(payload);
  969. const operator = isRecord(event.operator) ? event.operator : null;
  970. const operatorId = isRecord(operator?.operator_id) ? operator.operator_id : null;
  971. const openId =
  972. readString(operatorId, "open_id") ||
  973. readString(operator, "open_id") ||
  974. readString(event, "open_id") ||
  975. readString(payload, "open_id");
  976. return openId ? [openId] : [];
  977. }
  978. function readFeishuCardOriginalText(payload: unknown): string | null {
  979. if (!isRecord(payload)) {
  980. return null;
  981. }
  982. const event = readFeishuCallbackEvent(payload);
  983. const action = isRecord(event.action) ? event.action : null;
  984. const value = isRecord(action?.value) ? action.value : null;
  985. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  986. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  987. return (
  988. readString(value, "zcodeCardText") ||
  989. readString(value, "cardText") ||
  990. readString(behaviorValue, "zcodeCardText") ||
  991. readString(behaviorValue, "cardText") ||
  992. null
  993. );
  994. }
  995. function formatFeishuCardMarkdownContent(text: string): string {
  996. const lines: Array<{ text: string; hardBreak: boolean }> = [];
  997. let inCodeFence = false;
  998. for (const line of text.split("\n")) {
  999. if (line.trimStart().startsWith("```")) {
  1000. inCodeFence = !inCodeFence;
  1001. }
  1002. if (!inCodeFence && /^-{3,}$/.test(line.trim())) {
  1003. if (lines.length > 0 && lines.at(-1)?.text !== "") {
  1004. lines.push({ text: "", hardBreak: false });
  1005. }
  1006. lines.push({ text: "---", hardBreak: false }, { text: "", hardBreak: false });
  1007. continue;
  1008. }
  1009. lines.push({ text: line, hardBreak: !inCodeFence });
  1010. }
  1011. return lines
  1012. .map((line, index) => {
  1013. if (!line.text || !line.hardBreak || index >= lines.length - 1 || !lines[index + 1]?.text) {
  1014. return line.text;
  1015. }
  1016. // Bugfix: Card JSON 2.0 的 markdown 按标准 Markdown 处理单换行,会把 /status 多行文本折成一行。
  1017. // 飞书通道内把普通单换行转成 hard break,保留业务层给其他 bot 使用的原始文本。
  1018. return `${line.text} `;
  1019. })
  1020. .join("\n");
  1021. }
  1022. function buildFeishuButtonElement(params: {
  1023. text: string;
  1024. type: "default" | "primary";
  1025. command: string;
  1026. originalText: string;
  1027. }): Record<string, unknown> {
  1028. return {
  1029. tag: "button",
  1030. text: {
  1031. tag: "plain_text",
  1032. content: params.text,
  1033. },
  1034. type: params.type,
  1035. // Bugfix: Card JSON 2.0 不再支持旧版 action/actions 容器。
  1036. // 按钮必须直接作为 body.elements 组件,并通过 behaviors.callback 回传业务值,否则飞书会返回 HTTP 400。
  1037. behaviors: [
  1038. {
  1039. type: "callback",
  1040. value: {
  1041. command: params.command,
  1042. zcodeCardText: params.originalText,
  1043. },
  1044. },
  1045. ],
  1046. };
  1047. }
  1048. function buildFeishuInteractiveCardPayloadBody(
  1049. message: BotOutboundMessage,
  1050. ): Record<string, unknown> {
  1051. const selection = message.selection;
  1052. if (selection?.action === "queue.cancel") {
  1053. return {
  1054. schema: "2.0",
  1055. config: { wide_screen_mode: true },
  1056. body: {
  1057. padding: "8px 12px 8px 12px",
  1058. elements: [
  1059. {
  1060. tag: "column_set",
  1061. flex_mode: "none",
  1062. horizontal_spacing: "8px",
  1063. columns: [
  1064. {
  1065. tag: "column",
  1066. width: "weighted",
  1067. weight: 1,
  1068. vertical_align: "center",
  1069. elements: [
  1070. { tag: "markdown", content: formatFeishuCardMarkdownContent(message.text) },
  1071. ],
  1072. },
  1073. {
  1074. tag: "column",
  1075. width: "auto",
  1076. vertical_align: "center",
  1077. elements: selection.options.map((option) =>
  1078. buildFeishuButtonElement({
  1079. text: option.label,
  1080. type: "default",
  1081. command: formatSelectionCommand(selection, option.id),
  1082. originalText: message.text,
  1083. }),
  1084. ),
  1085. },
  1086. ],
  1087. },
  1088. ],
  1089. },
  1090. };
  1091. }
  1092. const elements: Array<Record<string, unknown>> = [
  1093. {
  1094. tag: "markdown",
  1095. content: formatFeishuCardMarkdownContent(message.text),
  1096. },
  1097. ];
  1098. if (selection) {
  1099. elements.push(
  1100. ...selection.options.map((option, index) =>
  1101. buildFeishuButtonElement({
  1102. text: option.label || String(index + 1),
  1103. type: "primary",
  1104. command: formatSelectionCommand(selection, option.id),
  1105. originalText: message.text,
  1106. }),
  1107. ),
  1108. ...(selection.showCancel === false
  1109. ? []
  1110. : [
  1111. buildFeishuButtonElement({
  1112. text:
  1113. selection.cancelLabel ?? formatBotMessage(message.locale, "selectionCancelOption"),
  1114. type: "default",
  1115. // Bugfix: 飞书走结构化选项卡,不应复用微信纯文本菜单的 0 取消语义。
  1116. command: "/cancel",
  1117. originalText: message.text,
  1118. }),
  1119. ]),
  1120. );
  1121. }
  1122. return {
  1123. schema: "2.0",
  1124. config: { wide_screen_mode: true },
  1125. body: { elements },
  1126. };
  1127. }
  1128. function formatFeishuStreamingStatus(state: BotStreamingReplyCardState): string {
  1129. // Bugfix: 流式卡片状态行由 provider 生成,必须读取 BotService 传入的 locale,
  1130. // 否则中文环境里会固定显示 Running/Completed。
  1131. const locale = state.locale;
  1132. const status = state.status;
  1133. if (status === "completed") {
  1134. return formatBotMessage(locale, "streamingStatusCompleted");
  1135. }
  1136. if (status === "error") {
  1137. return formatBotMessage(locale, "streamingStatusFailed");
  1138. }
  1139. return formatBotMessage(locale, "streamingStatusRunning");
  1140. }
  1141. function buildFeishuStreamingToolPanel(
  1142. toolSummaries: readonly string[],
  1143. options: { expanded: boolean; title: string },
  1144. ): Record<string, unknown> | null {
  1145. const summaries = toolSummaries
  1146. .map((summary) => summary.trim())
  1147. .filter((summary) => summary.length > 0);
  1148. if (summaries.length === 0) {
  1149. return null;
  1150. }
  1151. return {
  1152. tag: "collapsible_panel",
  1153. // Bugfix: 流式卡片运行中需要让用户看到当前工具摘要;任务终态后再自动收起,减少最终消息占用空间。
  1154. expanded: options.expanded,
  1155. // Bugfix: Tool summaries 之前只是裸 collapsible panel,和正文没有清晰视觉边界。
  1156. // 飞书 Card JSON 2.0 的折叠面板本身支持背景与边框,这里把它作为 <tools> 容器承载 header/content。
  1157. background_color: "grey-50",
  1158. border: {
  1159. color: "grey",
  1160. corner_radius: "8px",
  1161. },
  1162. padding: "8px 8px 8px 8px",
  1163. header: {
  1164. title: {
  1165. tag: "plain_text",
  1166. content: `🛠️ ${options.title} (${summaries.length})`,
  1167. },
  1168. vertical_align: "center",
  1169. padding: "8px 8px 8px 8px",
  1170. icon: {
  1171. tag: "standard_icon",
  1172. token: "down-small-ccm_outlined",
  1173. color: "grey",
  1174. size: "16px 16px",
  1175. },
  1176. icon_position: "right",
  1177. icon_expanded_angle: -180,
  1178. },
  1179. elements: [
  1180. {
  1181. tag: "markdown",
  1182. content: formatFeishuCardMarkdownContent(summaries.join("\n")),
  1183. },
  1184. ],
  1185. };
  1186. }
  1187. function buildFeishuStreamingCardPayload(
  1188. state: BotStreamingReplyCardState,
  1189. ): Record<string, unknown> {
  1190. const elements: Array<Record<string, unknown>> = [];
  1191. for (const block of state.blocks) {
  1192. if (block.type === "message") {
  1193. const text = block.text.trim();
  1194. if (text) {
  1195. elements.push({
  1196. tag: "markdown",
  1197. content: formatFeishuCardMarkdownContent(text),
  1198. });
  1199. }
  1200. continue;
  1201. }
  1202. const toolPanel = buildFeishuStreamingToolPanel(block.summaries, {
  1203. expanded: block.expanded ?? state.status === "running",
  1204. title: block.title?.trim() || formatBotMessage(state.locale, "streamingToolSummaries"),
  1205. });
  1206. if (toolPanel) {
  1207. elements.push(toolPanel);
  1208. }
  1209. }
  1210. if (elements.length === 0) {
  1211. elements.push({
  1212. tag: "markdown",
  1213. content: " ",
  1214. });
  1215. }
  1216. if (state.status !== "sealed") {
  1217. elements.push({
  1218. tag: "markdown",
  1219. content: formatFeishuCardMarkdownContent(formatFeishuStreamingStatus(state)),
  1220. });
  1221. }
  1222. return {
  1223. schema: "2.0",
  1224. config: { wide_screen_mode: true },
  1225. body: { elements },
  1226. };
  1227. }
  1228. function countTaggedElements(value: unknown): number {
  1229. if (Array.isArray(value)) {
  1230. return value.reduce((total, item) => total + countTaggedElements(item), 0);
  1231. }
  1232. if (!value || typeof value !== "object") {
  1233. return 0;
  1234. }
  1235. const record = value as Record<string, unknown>;
  1236. return (
  1237. (typeof record.tag === "string" ? 1 : 0) +
  1238. Object.values(record).reduce<number>((total, item) => total + countTaggedElements(item), 0)
  1239. );
  1240. }
  1241. export function countFeishuCardTaggedElements(state: BotStreamingReplyCardState): number {
  1242. return countTaggedElements(buildFeishuStreamingCardPayload(state));
  1243. }
  1244. export function splitFeishuStreamingCardStates(
  1245. state: BotStreamingReplyCardState,
  1246. ): BotStreamingReplyCardState[] {
  1247. const blockGroups: BotStreamingReplyCardState["blocks"][] = [];
  1248. let current: BotStreamingReplyCardState["blocks"] = [];
  1249. for (const block of state.blocks) {
  1250. const candidate = [...current, block];
  1251. // 始终为状态行预留预算,使 running/completed 切换不会改变既有分段边界。
  1252. const candidateState = { ...state, blocks: candidate, status: "running" as const };
  1253. if (
  1254. current.length > 0 &&
  1255. countFeishuCardTaggedElements(candidateState) > FEISHU_STREAMING_CARD_TAGGED_ELEMENT_BUDGET
  1256. ) {
  1257. blockGroups.push(current);
  1258. current = [block];
  1259. } else {
  1260. current = candidate;
  1261. }
  1262. }
  1263. blockGroups.push(current);
  1264. return blockGroups.map((blocks, index) => ({
  1265. ...state,
  1266. blocks,
  1267. status: index === blockGroups.length - 1 ? state.status : "sealed",
  1268. }));
  1269. }
  1270. export function splitFeishuText(text: string): string[] {
  1271. const limit = 1900;
  1272. const chunks: string[] = [];
  1273. for (let index = 0; index < text.length; index += limit) {
  1274. chunks.push(text.slice(index, index + limit));
  1275. }
  1276. return chunks.length > 0 ? chunks : [text];
  1277. }
  1278. async function readTenantAccessToken(
  1279. bot: BotConfig,
  1280. deps: FeishuProviderDeps,
  1281. signal?: AbortSignal,
  1282. ): Promise<string | null> {
  1283. if (!bot.feishuAppId || !bot.credentialRef) {
  1284. return null;
  1285. }
  1286. const appSecret = await deps.loadCredential(bot.credentialRef);
  1287. if (!appSecret) {
  1288. return null;
  1289. }
  1290. const cacheKey = `${getFeishuDomainProvider(bot)}:${bot.feishuAppId}:${bot.credentialRef}`;
  1291. const cached = accessTokenCache.get(cacheKey);
  1292. if (cached && cached.expiresAt > Date.now() + 60_000) {
  1293. return cached.token;
  1294. }
  1295. const requestedAt = Date.now();
  1296. const response = await fetchBotProviderJson<FeishuAccessTokenResponse>(
  1297. `${getFeishuBaseUrl(bot)}/open-apis/auth/v3/tenant_access_token/internal`,
  1298. {
  1299. method: "POST",
  1300. headers: { "content-type": "application/json" },
  1301. body: JSON.stringify({
  1302. app_id: bot.feishuAppId,
  1303. app_secret: appSecret,
  1304. }),
  1305. signal,
  1306. },
  1307. );
  1308. if (!response.ok) {
  1309. throw new Error(`Feishu tenant_access_token failed: HTTP ${response.status}`);
  1310. }
  1311. const payload = response.payload ?? {};
  1312. if (payload.code !== 0 || !payload.tenant_access_token) {
  1313. throw new Error(payload.msg || "Feishu tenant_access_token failed.");
  1314. }
  1315. // 飞书可能返回尚未过期的旧令牌;固定缓存 90 分钟会超过其真实剩余有效期。
  1316. // 从请求开始计时,避免网络耗时被错误计入令牌的可用时间。
  1317. if (typeof payload.expire === "number" && Number.isFinite(payload.expire) && payload.expire > 0) {
  1318. accessTokenCache.set(cacheKey, {
  1319. token: payload.tenant_access_token,
  1320. expiresAt: requestedAt + payload.expire * 1_000,
  1321. });
  1322. } else {
  1323. accessTokenCache.delete(cacheKey);
  1324. }
  1325. return payload.tenant_access_token;
  1326. }
  1327. function resolveFeishuReceiveIdType(receiveId: string): "chat_id" | "open_id" {
  1328. return receiveId.startsWith("oc_") ? "chat_id" : "open_id";
  1329. }
  1330. function createFeishuMessageError(
  1331. operation: string,
  1332. status: number,
  1333. payload: FeishuSendMessageResponse | undefined,
  1334. responseLogId?: string,
  1335. receiveIdType?: string,
  1336. ): Error {
  1337. const details = [
  1338. typeof payload?.code === "number" ? `code=${payload.code}` : null,
  1339. payload?.msg ? `msg=${payload.msg}` : null,
  1340. payload?.error?.log_id || responseLogId
  1341. ? `log_id=${payload?.error?.log_id ?? responseLogId}`
  1342. : null,
  1343. receiveIdType ? `receive_id_type=${receiveIdType}` : null,
  1344. ].filter((detail): detail is string => Boolean(detail));
  1345. // 修复原因:飞书的 HTTP 400 会在响应体中携带业务错误码、原因和排查 log_id。
  1346. // 旧实现先按 HTTP 状态抛错,导致这些已解析的信息永久丢失,无法区分权限、限流和卡片错误。
  1347. return Object.assign(
  1348. new Error(
  1349. `Feishu ${operation} failed: HTTP ${status}${details.length > 0 ? `, ${details.join(", ")}` : ""}`,
  1350. ),
  1351. {
  1352. // 无业务回执的服务端错误,以及“正在发送”,都不能证明本次发送未发生。
  1353. deliveryRejected:
  1354. payload?.code !== 230049 &&
  1355. ((typeof payload?.code === "number" && payload.code !== 0) ||
  1356. (status >= 400 && status < 500 && status !== 408)),
  1357. ...(payload?.code === 230011 ? { deliveryReplyUnavailable: true } : {}),
  1358. ...(status === 429 || payload?.code === 230020 || payload?.code === 99991400
  1359. ? { retryAfterMs: 1000 }
  1360. : {}),
  1361. },
  1362. );
  1363. }
  1364. function resolveFeishuReplyTarget(message: BotOutboundMessage) {
  1365. const replyToMessageId =
  1366. message.replyToMessageId || (message.threadId ? message.rootMessageId : undefined);
  1367. // 原因:临时审批/问答卡曾跳过话题路由,直接发到群主聊天;统一解析并拒绝无锚点投递。
  1368. if (message.threadId && !replyToMessageId)
  1369. throw Object.assign(new Error("Topic reply target is unavailable"), {
  1370. deliveryRejected: true,
  1371. });
  1372. return { replyToMessageId, replyInThread: Boolean(message.threadId) };
  1373. }
  1374. async function sendFeishuInteractiveCard(
  1375. bot: BotConfig,
  1376. token: string,
  1377. receiveId: string,
  1378. card: Record<string, unknown>,
  1379. signal?: AbortSignal,
  1380. delivery?: { replyToMessageId?: string; uuid?: string; replyInThread?: boolean },
  1381. ): Promise<string | null> {
  1382. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1383. delivery?.replyToMessageId
  1384. ? `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(delivery.replyToMessageId)}/reply`
  1385. : `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages?receive_id_type=${resolveFeishuReceiveIdType(receiveId)}`,
  1386. {
  1387. method: "POST",
  1388. headers: {
  1389. authorization: `Bearer ${token}`,
  1390. "content-type": "application/json",
  1391. },
  1392. body: JSON.stringify({
  1393. ...(!delivery?.replyToMessageId ? { receive_id: receiveId } : {}),
  1394. ...(delivery?.uuid ? { uuid: delivery.uuid } : {}),
  1395. ...(delivery?.replyInThread ? { reply_in_thread: true } : {}),
  1396. msg_type: "interactive",
  1397. content: JSON.stringify(card),
  1398. }),
  1399. signal,
  1400. },
  1401. );
  1402. const payload = response.payload ?? {};
  1403. // HTTP 成功也可能携带业务拒绝,必须保留错误码和请求 ID。
  1404. if (!response.ok || payload.code !== 0) {
  1405. throw createFeishuMessageError(
  1406. "send interactive message",
  1407. response.status,
  1408. payload,
  1409. response.responseLogId,
  1410. resolveFeishuReceiveIdType(receiveId),
  1411. );
  1412. }
  1413. if ((delivery?.uuid || delivery?.replyToMessageId) && !payload.data?.message_id)
  1414. throw new Error("Feishu delivery outcome is unknown: no message_id");
  1415. return payload.data?.message_id ?? null;
  1416. }
  1417. async function updateFeishuInteractiveMessage(
  1418. bot: BotConfig,
  1419. token: string,
  1420. handle: BotStreamingReplyCardHandle,
  1421. card: Record<string, unknown>,
  1422. signal?: AbortSignal,
  1423. ): Promise<void> {
  1424. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1425. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(handle.providerMessageId)}`,
  1426. {
  1427. method: "PATCH",
  1428. headers: {
  1429. authorization: `Bearer ${token}`,
  1430. "content-type": "application/json",
  1431. },
  1432. body: JSON.stringify({
  1433. msg_type: "interactive",
  1434. content: JSON.stringify(card),
  1435. }),
  1436. signal,
  1437. },
  1438. );
  1439. const payload = response.payload ?? {};
  1440. // HTTP 成功也可能携带业务拒绝,必须保留错误码和请求 ID。
  1441. if (!response.ok || payload.code !== 0) {
  1442. throw createFeishuMessageError(
  1443. "update streaming card",
  1444. response.status,
  1445. payload,
  1446. response.responseLogId,
  1447. );
  1448. }
  1449. }
  1450. async function deleteFeishuInteractiveMessage(
  1451. bot: BotConfig,
  1452. token: string,
  1453. handle: BotTransientInteractionCardHandle,
  1454. ): Promise<void> {
  1455. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1456. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(handle.providerMessageId)}`,
  1457. {
  1458. method: "DELETE",
  1459. headers: {
  1460. authorization: `Bearer ${token}`,
  1461. },
  1462. },
  1463. );
  1464. if (!response.ok) {
  1465. throw new Error(`Feishu recall interaction card failed: HTTP ${response.status}`);
  1466. }
  1467. const payload = response.payload ?? {};
  1468. if (payload.code !== 0) {
  1469. throw new Error(payload.msg || "Feishu recall interaction card failed.");
  1470. }
  1471. }
  1472. function resolveFeishuAppDisplayName(payload: FeishuAppInfoResponse): string | null {
  1473. const app = payload.data?.app;
  1474. const appName = app?.app_name?.trim();
  1475. if (appName) {
  1476. return appName;
  1477. }
  1478. const primaryLanguage = app?.primary_language?.trim();
  1479. const primaryI18nName = app?.i18n
  1480. ?.find((item) => item.i18n_key === primaryLanguage)
  1481. ?.name?.trim();
  1482. if (primaryI18nName) {
  1483. return primaryI18nName;
  1484. }
  1485. return app?.i18n?.find((item) => item.name?.trim())?.name?.trim() ?? null;
  1486. }
  1487. async function fetchFeishuAppDisplayName(
  1488. bot: BotConfig,
  1489. token: string,
  1490. appId: string,
  1491. ): Promise<string | null> {
  1492. const response = await fetchBotProviderJson<FeishuAppInfoResponse>(
  1493. `${getFeishuBaseUrl(bot)}/open-apis/application/v6/applications/${appId}?lang=zh_cn`,
  1494. {
  1495. headers: {
  1496. authorization: `Bearer ${token}`,
  1497. },
  1498. },
  1499. );
  1500. if (!response.ok) {
  1501. throw new Error(`Feishu get application info failed app=${appId}: HTTP ${response.status}`);
  1502. }
  1503. const payload = response.payload ?? {};
  1504. if (payload.code !== 0) {
  1505. throw new Error(payload.msg || `Feishu get application info failed app=${appId}.`);
  1506. }
  1507. return resolveFeishuAppDisplayName(payload);
  1508. }
  1509. async function readFeishuAppDisplayName(
  1510. bot: BotConfig,
  1511. deps: FeishuProviderDeps,
  1512. ): Promise<string | null> {
  1513. if (!bot.feishuAppId) {
  1514. return null;
  1515. }
  1516. const token = await readTenantAccessToken(bot, deps);
  1517. if (!token) {
  1518. return null;
  1519. }
  1520. let appIdError: unknown;
  1521. try {
  1522. const appName = await fetchFeishuAppDisplayName(bot, token, bot.feishuAppId);
  1523. if (appName?.trim()) {
  1524. return appName;
  1525. }
  1526. } catch (error) {
  1527. appIdError = error;
  1528. }
  1529. try {
  1530. // Bugfix: 飞书 / Lark 扫码创建后 app_id 路径可能因为权限或同步延迟暂不可读;me 路径更适合读取当前应用名称。
  1531. return await fetchFeishuAppDisplayName(bot, token, "me");
  1532. } catch (error) {
  1533. throw appIdError ?? error;
  1534. }
  1535. }
  1536. function resolveFeishuUserIdType(userId: string): "open_id" | "union_id" | "user_id" {
  1537. if (userId.startsWith("ou_")) {
  1538. return "open_id";
  1539. }
  1540. if (userId.startsWith("on_")) {
  1541. return "union_id";
  1542. }
  1543. return "user_id";
  1544. }
  1545. function resolveFeishuUserDisplayName(payload: FeishuUserInfoResponse): string | null {
  1546. const user = payload.data?.user;
  1547. return user?.name?.trim() || user?.en_name?.trim() || user?.nickname?.trim() || null;
  1548. }
  1549. async function readFeishuUserDisplayName(
  1550. bot: BotConfig,
  1551. deps: FeishuProviderDeps,
  1552. userId: string,
  1553. ): Promise<string | null> {
  1554. const trimmedUserId = userId.trim();
  1555. if (!trimmedUserId) {
  1556. return null;
  1557. }
  1558. const cacheKey = `${getFeishuDomainProvider(bot)}:${bot.feishuAppId ?? ""}:${bot.credentialRef ?? ""}:${trimmedUserId}`;
  1559. const cached = userDisplayNameCache.get(cacheKey);
  1560. if (cached && cached.expiresAt > Date.now()) {
  1561. return cached.name;
  1562. }
  1563. const token = await readTenantAccessToken(bot, deps);
  1564. if (!token) {
  1565. return null;
  1566. }
  1567. const userIdType = resolveFeishuUserIdType(trimmedUserId);
  1568. const response = await fetchBotProviderJson<FeishuUserInfoResponse>(
  1569. `${getFeishuBaseUrl(bot)}/open-apis/contact/v3/users/${encodeURIComponent(trimmedUserId)}?user_id_type=${userIdType}`,
  1570. {
  1571. headers: {
  1572. authorization: `Bearer ${token}`,
  1573. },
  1574. },
  1575. );
  1576. if (!response.ok) {
  1577. throw new Error(`Feishu get user info failed user=${trimmedUserId}: HTTP ${response.status}`);
  1578. }
  1579. const payload = response.payload ?? {};
  1580. if (payload.code !== 0) {
  1581. throw new Error(payload.msg || `Feishu get user info failed user=${trimmedUserId}.`);
  1582. }
  1583. const name = resolveFeishuUserDisplayName(payload);
  1584. // Bugfix: 飞书消息事件只稳定携带 sender_id,不携带发送者名称。
  1585. // 这里缓存通讯录查询结果,避免同一个用户连续发消息时每条都请求 contact API。
  1586. userDisplayNameCache.set(cacheKey, {
  1587. name,
  1588. expiresAt: Date.now() + 10 * 60_000,
  1589. });
  1590. return name;
  1591. }
  1592. function getFeishuTypingReactionKey(bot: BotConfig, messageId: string): string {
  1593. return `${bot.id}:${messageId}`;
  1594. }
  1595. async function addFeishuTypingReaction(
  1596. bot: BotConfig,
  1597. deps: FeishuProviderDeps,
  1598. messageId: string,
  1599. ): Promise<void> {
  1600. const token = await readTenantAccessToken(bot, deps);
  1601. if (!token) {
  1602. return;
  1603. }
  1604. const key = getFeishuTypingReactionKey(bot, messageId);
  1605. if (typingReactionIds.has(key)) {
  1606. return;
  1607. }
  1608. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1609. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${messageId}/reactions`,
  1610. {
  1611. method: "POST",
  1612. headers: {
  1613. authorization: `Bearer ${token}`,
  1614. "content-type": "application/json",
  1615. },
  1616. body: JSON.stringify({
  1617. reaction_type: {
  1618. emoji_type: "Typing",
  1619. },
  1620. }),
  1621. },
  1622. );
  1623. if (!response.ok) {
  1624. throw new Error(`Feishu add typing reaction failed: HTTP ${response.status}`);
  1625. }
  1626. const payload = response.payload ?? {};
  1627. if (payload.code !== 0) {
  1628. throw new Error(payload.msg || "Feishu add typing reaction failed.");
  1629. }
  1630. if (payload.data?.reaction_id) {
  1631. typingReactionIds.set(key, payload.data.reaction_id);
  1632. }
  1633. }
  1634. async function deleteFeishuTypingReaction(
  1635. bot: BotConfig,
  1636. deps: FeishuProviderDeps,
  1637. messageId: string,
  1638. ): Promise<void> {
  1639. const key = getFeishuTypingReactionKey(bot, messageId);
  1640. const reactionId = typingReactionIds.get(key);
  1641. if (!reactionId) {
  1642. return;
  1643. }
  1644. const token = await readTenantAccessToken(bot, deps);
  1645. if (!token) {
  1646. return;
  1647. }
  1648. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1649. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${messageId}/reactions/${reactionId}`,
  1650. {
  1651. method: "DELETE",
  1652. headers: {
  1653. authorization: `Bearer ${token}`,
  1654. },
  1655. },
  1656. );
  1657. if (!response.ok) {
  1658. throw new Error(`Feishu delete typing reaction failed: HTTP ${response.status}`);
  1659. }
  1660. const payload = response.payload ?? {};
  1661. if (payload.code !== 0) {
  1662. throw new Error(payload.msg || "Feishu delete typing reaction failed.");
  1663. }
  1664. typingReactionIds.delete(key);
  1665. }
  1666. async function readFeishuAppSecret(
  1667. bot: BotConfig,
  1668. deps: FeishuProviderDeps,
  1669. ): Promise<string | null> {
  1670. if (!bot.feishuAppId || !bot.credentialRef) {
  1671. return null;
  1672. }
  1673. return deps.loadCredential(bot.credentialRef);
  1674. }
  1675. export function createFeishuWebSocketEventHandlers(params: {
  1676. bot: BotConfig;
  1677. onPayload: (payload: unknown) => Promise<BotOutboundMessage | undefined>;
  1678. }) {
  1679. const { bot, onPayload } = params;
  1680. return {
  1681. "im.message.receive_v1": async (payload: unknown) => {
  1682. await onPayload({
  1683. ...(isRecord(payload) ? payload : { payload }),
  1684. botId: bot.id,
  1685. zcodeProvider: bot.provider,
  1686. });
  1687. },
  1688. "im.chat.member.bot.deleted_v1": async (payload: unknown) => {
  1689. await onPayload({
  1690. ...(isRecord(payload) ? payload : {}),
  1691. botId: bot.id,
  1692. zcodeProvider: bot.provider,
  1693. zcodeBotRemoved: true,
  1694. });
  1695. },
  1696. // Bugfix: 我们用 Typing reaction 模拟输入中状态,飞书会把自己创建的 reaction 再推回长连接。
  1697. // 业务不需要处理这个事件,但不注册 handler 时 SDK 会持续打印 warn 干扰排查。
  1698. "im.message.reaction.created_v1": async () => undefined,
  1699. "card.action.trigger": async (payload: unknown) => {
  1700. const responseState = { deferred: false };
  1701. const callbackPayload = {
  1702. ...(isRecord(payload) ? payload : { payload }),
  1703. zcodeFeishuCardResponseState: responseState,
  1704. botId: bot.id,
  1705. zcodeProvider: bot.provider,
  1706. zcodeFeishuSynchronousCardAction: true,
  1707. };
  1708. // 修复原因:飞书点击后的同步响应才是客户端可靠采用的卡片状态。传输层不能再从
  1709. // zcodeCardText 拼简化卡,也不能返回 undefined 后依赖旁路 PATCH;它必须消费业务层
  1710. // 已推进完成的完整 outbound,并用同一份 elicitation 状态生成下一题卡片。
  1711. // 飞书要求三秒内响应。超时只切换卡片投递方式,业务请求仍执行一次。
  1712. let deadline: ReturnType<typeof setTimeout> | undefined;
  1713. const pending = onPayload(callbackPayload);
  1714. const message = await Promise.race([
  1715. pending,
  1716. new Promise<null>((resolve) => {
  1717. deadline = setTimeout(() => {
  1718. responseState.deferred = true;
  1719. resolve(null);
  1720. }, 2000);
  1721. }),
  1722. ]).finally(() => {
  1723. if (deadline) clearTimeout(deadline);
  1724. });
  1725. if (responseState.deferred) return {};
  1726. if (!message) {
  1727. return undefined;
  1728. }
  1729. if (message.callbackToastOnly) return { toast: { type: "error", content: message.text } };
  1730. return {
  1731. card: {
  1732. type: "raw",
  1733. data: message.elicitation
  1734. ? buildFeishuElicitationCardPayload(message)
  1735. : buildFeishuInteractiveCardPayload(message),
  1736. },
  1737. };
  1738. },
  1739. };
  1740. }
  1741. export async function startFeishuBotWebSocket(params: {
  1742. bot: BotConfig;
  1743. deps: FeishuProviderDeps;
  1744. onPayload: (payload: unknown) => Promise<BotOutboundMessage | undefined>;
  1745. signal?: AbortSignal;
  1746. onConnectionStateChange?: (state: "reconnecting" | "connected") => void;
  1747. }): Promise<FeishuWebSocketClient> {
  1748. const { bot, deps, onPayload, signal, onConnectionStateChange } = params;
  1749. const appId = bot.feishuAppId;
  1750. if (!appId || !FEISHU_APP_ID_PATTERN.test(appId)) {
  1751. throw new Error("Invalid Feishu App ID.");
  1752. }
  1753. const appSecret = await readFeishuAppSecret(bot, deps);
  1754. if (!appSecret) {
  1755. throw new Error("Feishu App ID and App Secret are required.");
  1756. }
  1757. if (signal?.aborted) {
  1758. throw new Error("Feishu WebSocket startup aborted.");
  1759. }
  1760. // SDK 全量源码会常驻 Host;只有实际启动长连接才加载,卡片和 HTTP 路径不承担这份开销。
  1761. const Lark = await import("@larksuiteoapi/node-sdk");
  1762. // 加载期间 channel 可能已停用,迟到的模块不能重新创建连接。
  1763. if (signal?.aborted) {
  1764. throw new Error("Feishu WebSocket startup aborted.");
  1765. }
  1766. const eventDispatcher = new Lark.EventDispatcher({});
  1767. eventDispatcher.register(createFeishuWebSocketEventHandlers({ bot, onPayload }));
  1768. return new Promise<FeishuWebSocketClient>((resolve, reject) => {
  1769. let startupSettled = false;
  1770. let lifecycleSettled = false;
  1771. let clientClosed = false;
  1772. let connectionUnavailable = false;
  1773. let startupTimer: ReturnType<typeof setTimeout> | undefined;
  1774. let connectionPoll: ReturnType<typeof setInterval> | undefined;
  1775. let resolveTerminated: (() => void) | undefined;
  1776. let rejectTerminated: ((error: unknown) => void) | undefined;
  1777. const terminated = new Promise<void>((resolveLifecycle, rejectLifecycle) => {
  1778. resolveTerminated = resolveLifecycle;
  1779. rejectTerminated = rejectLifecycle;
  1780. });
  1781. const finishLifecycle = (error?: unknown) => {
  1782. if (lifecycleSettled) return;
  1783. lifecycleSettled = true;
  1784. if (connectionPoll) clearInterval(connectionPoll);
  1785. if (error) {
  1786. rejectTerminated?.(error);
  1787. } else {
  1788. resolveTerminated?.();
  1789. }
  1790. };
  1791. const fail = (error: unknown) => {
  1792. if (startupSettled) return;
  1793. startupSettled = true;
  1794. if (startupTimer) clearTimeout(startupTimer);
  1795. signal?.removeEventListener("abort", handleAbort);
  1796. closeClient();
  1797. reject(error);
  1798. };
  1799. function handleAbort() {
  1800. fail(new Error("Feishu WebSocket startup aborted."));
  1801. }
  1802. function closeClient() {
  1803. if (clientClosed) return;
  1804. clientClosed = true;
  1805. finishLifecycle();
  1806. wsClient.close();
  1807. }
  1808. const wsClient = new Lark.WSClient({
  1809. appId,
  1810. appSecret,
  1811. domain: getFeishuDomainProvider(bot) === "lark" ? Lark.Domain.Lark : Lark.Domain.Feishu,
  1812. loggerLevel: Lark.LoggerLevel.info,
  1813. });
  1814. // 修复原因:当前飞书 SDK 不支持 onReady 回调,start() 也会在连接完成前返回。
  1815. // 必须观察 SDK 持有的真实 WebSocket,避免连接已经 OPEN 后仍触发 20 秒超时并被主动关闭。
  1816. connectionPoll = setInterval(() => {
  1817. const sdkClient = wsClient as unknown as {
  1818. isConnecting?: boolean;
  1819. wsConfig?: {
  1820. getWSInstance?(): { readyState?: number } | null;
  1821. };
  1822. };
  1823. const connected =
  1824. sdkClient.wsConfig?.getWSInstance?.()?.readyState === WEBSOCKET_OPEN_READY_STATE;
  1825. if (!connected) {
  1826. if (!startupSettled || clientClosed) return;
  1827. if (!connectionUnavailable) {
  1828. connectionUnavailable = true;
  1829. onConnectionStateChange?.("reconnecting");
  1830. }
  1831. if (sdkClient.isConnecting === false) {
  1832. const error = new Error("Feishu WebSocket reconnect exhausted.");
  1833. finishLifecycle(error);
  1834. closeClient();
  1835. }
  1836. return;
  1837. }
  1838. if (startupSettled) {
  1839. if (connectionUnavailable) {
  1840. connectionUnavailable = false;
  1841. onConnectionStateChange?.("connected");
  1842. }
  1843. return;
  1844. }
  1845. startupSettled = true;
  1846. if (startupTimer) clearTimeout(startupTimer);
  1847. signal?.removeEventListener("abort", handleAbort);
  1848. resolve({ close: closeClient, terminated });
  1849. }, FEISHU_WEBSOCKET_READY_POLL_MS);
  1850. startupTimer = setTimeout(() => {
  1851. fail(
  1852. new Error(
  1853. `Feishu WebSocket startup timed out after ${FEISHU_WEBSOCKET_START_TIMEOUT_MS}ms.`,
  1854. ),
  1855. );
  1856. }, FEISHU_WEBSOCKET_START_TIMEOUT_MS);
  1857. signal?.addEventListener("abort", handleAbort, { once: true });
  1858. if (signal?.aborted) {
  1859. handleAbort();
  1860. return;
  1861. }
  1862. // 飞书不需要公网回调地址;这里由本机主动建立长连接接收事件,适配家用网络/NAT 环境。
  1863. void wsClient.start({ eventDispatcher }).catch((error: unknown) => {
  1864. if (!startupSettled) {
  1865. fail(error);
  1866. return;
  1867. }
  1868. finishLifecycle(error);
  1869. closeClient();
  1870. });
  1871. });
  1872. }
  1873. export function createFeishuBotProvider(deps: FeishuProviderDeps): BotProviderAdapter {
  1874. const reactionBots = new Map<string, BotConfig>();
  1875. const updateReaction = createGroupInputReactionUpdater(async (key, state) => {
  1876. const [botKey, messageId] = JSON.parse(key) as [string, string];
  1877. const bot = reactionBots.get(botKey)!;
  1878. const token = await readTenantAccessToken(bot, deps);
  1879. if (!token) throw new Error("Feishu reaction credentials unavailable");
  1880. const url = `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}/reactions`;
  1881. const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
  1882. const emoji = {
  1883. waiting: "OneSecond",
  1884. working: "OnIt",
  1885. done: "CheckMark",
  1886. failed: "CrossMark",
  1887. cancelled: null,
  1888. }[state];
  1889. const ownedTypes = new Set(["OK", "OneSecond", "OnIt", "CheckMark", "CrossMark"]);
  1890. const obsolete: string[] = [];
  1891. let found = false;
  1892. let cursor = "";
  1893. const cursors = new Set<string>();
  1894. do {
  1895. if (cursors.has(cursor)) throw new Error("Feishu reaction pagination repeated");
  1896. cursors.add(cursor);
  1897. const response = await fetchBotProviderJson<{
  1898. code?: number;
  1899. msg?: string;
  1900. data?: {
  1901. has_more?: boolean;
  1902. page_token?: string;
  1903. items?: Array<{
  1904. reaction_id: string;
  1905. operator?: { operator_type?: string; operator_id?: string };
  1906. reaction_type?: { emoji_type?: string };
  1907. }>;
  1908. };
  1909. }>(`${url}?page_size=50${cursor ? `&page_token=${encodeURIComponent(cursor)}` : ""}`, {
  1910. method: "GET",
  1911. headers,
  1912. });
  1913. if (!response.ok || response.payload?.code !== 0)
  1914. throw new Error(response.payload?.msg || "Feishu list reactions failed");
  1915. for (const item of response.payload.data?.items ?? []) {
  1916. // 重启后从平台核对本应用状态,绝不删除群成员或其他机器人的表情。
  1917. if (
  1918. item.operator?.operator_type !== "app" ||
  1919. item.operator.operator_id !== bot.feishuAppId ||
  1920. !ownedTypes.has(item.reaction_type?.emoji_type ?? "")
  1921. )
  1922. continue;
  1923. if (item.reaction_type?.emoji_type === emoji && !found) found = true;
  1924. else obsolete.push(item.reaction_id);
  1925. }
  1926. cursor = response.payload.data?.has_more ? (response.payload.data.page_token ?? "") : "";
  1927. if (response.payload.data?.has_more && !cursor)
  1928. throw new Error("Feishu reaction cursor missing");
  1929. } while (cursor);
  1930. for (const id of obsolete) {
  1931. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1932. `${url}/${encodeURIComponent(id)}`,
  1933. { method: "DELETE", headers },
  1934. );
  1935. if (!response.ok || response.payload?.code !== 0)
  1936. throw new Error(response.payload?.msg || "Feishu delete status reaction failed");
  1937. }
  1938. if (emoji && !found) {
  1939. const response = await fetchBotProviderJson<FeishuReactionResponse>(url, {
  1940. method: "POST",
  1941. headers,
  1942. body: JSON.stringify({ reaction_type: { emoji_type: emoji } }),
  1943. });
  1944. if (!response.ok || response.payload?.code !== 0)
  1945. throw new Error(response.payload?.msg || "Feishu add status reaction failed");
  1946. }
  1947. });
  1948. const readDirectory = createGroupMemberDirectory();
  1949. const getGroupMemberNames = (bot: BotConfig, chatId: string) => {
  1950. const key = JSON.stringify([
  1951. getFeishuDomainProvider(bot),
  1952. bot.id,
  1953. bot.feishuAppId,
  1954. bot.credentialRef,
  1955. chatId,
  1956. ]);
  1957. return readDirectory(key, async (cursor) => {
  1958. const token = await readTenantAccessToken(bot, deps);
  1959. if (!token) throw new Error("Feishu credentials are unavailable");
  1960. const query = new URLSearchParams({ member_id_type: "open_id", page_size: "100" });
  1961. if (cursor) query.set("page_token", cursor);
  1962. const response = await fetchBotProviderJson<{
  1963. code?: number;
  1964. msg?: string;
  1965. data?: GroupMemberPage;
  1966. }>(
  1967. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members?${query}`,
  1968. { headers: { authorization: `Bearer ${token}` } },
  1969. );
  1970. if (!response.ok || response.payload?.code !== 0 || !response.payload.data)
  1971. throw new Error(response.payload?.msg || "Cannot read group members");
  1972. return response.payload.data;
  1973. });
  1974. };
  1975. async function trackDelivery<T>(
  1976. bot: BotConfig,
  1977. signal: AbortSignal | undefined,
  1978. write: () => Promise<T>,
  1979. ): Promise<T> {
  1980. try {
  1981. const result = await write();
  1982. if (!signal?.aborted) deps.onDeliveryResult?.(bot, undefined);
  1983. return result;
  1984. } catch (error) {
  1985. // 主动取消不代表飞书拒绝投递,也不能覆盖已有诊断;任务超时仍由 watcher 处理。
  1986. if (!signal?.aborted)
  1987. deps.onDeliveryResult?.(bot, error instanceof Error ? error.message : String(error));
  1988. throw error;
  1989. }
  1990. }
  1991. const sendCard = (...args: Parameters<typeof sendFeishuInteractiveCard>) =>
  1992. trackDelivery(args[0], args[4], () => sendFeishuInteractiveCard(...args));
  1993. const updateCard = (...args: Parameters<typeof updateFeishuInteractiveMessage>) =>
  1994. trackDelivery(args[0], args[4], () => updateFeishuInteractiveMessage(...args));
  1995. const sendReplyCard = async (
  1996. bot: BotConfig,
  1997. token: string,
  1998. message: BotOutboundMessage,
  1999. card: Record<string, unknown>,
  2000. uuid?: string,
  2001. ): Promise<string | null> => {
  2002. let target = message;
  2003. for (;;) {
  2004. try {
  2005. return await sendCard(bot, token, message.providerUserId, card, undefined, {
  2006. ...resolveFeishuReplyTarget(target),
  2007. ...(uuid ? { uuid } : {}),
  2008. });
  2009. } catch (error) {
  2010. const details = error as {
  2011. deliveryRejected?: boolean;
  2012. deliveryReplyUnavailable?: boolean;
  2013. } | null;
  2014. // 持久化结果由 delivery owner 记录降级目标;这里只处理命令和临时卡。
  2015. if (
  2016. message.deliveryId ||
  2017. !message.providerUserId.startsWith("oc_") ||
  2018. !details?.deliveryRejected ||
  2019. !details.deliveryReplyUnavailable
  2020. )
  2021. throw error;
  2022. const fallback = getUnavailableReplyFallback(target);
  2023. if (!fallback) throw error;
  2024. target = { ...target, ...fallback };
  2025. }
  2026. }
  2027. };
  2028. const botOpenIds = new Map<string, string>();
  2029. return {
  2030. getGroupMemberNames,
  2031. async resolveTopic(bot, actor) {
  2032. const token = await readTenantAccessToken(bot, deps);
  2033. if (!token || !actor.chatId || !actor.providerMessageId)
  2034. throw new Error("Topic identity unavailable");
  2035. const get = async (id: string) => {
  2036. const response = await fetchBotProviderJson<{
  2037. code?: number;
  2038. data?: { items?: Array<Record<string, unknown>> };
  2039. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(id)}`, {
  2040. headers: { authorization: `Bearer ${token}` },
  2041. });
  2042. const item = response.payload?.data?.items?.find((entry) => entry.message_id === id);
  2043. if (!response.ok || response.payload?.code !== 0 || !item || item.chat_id !== actor.chatId)
  2044. throw new Error("Topic message scope could not be verified");
  2045. return item;
  2046. };
  2047. const message = await get(actor.providerMessageId);
  2048. const threadId = readString(message, "thread_id");
  2049. if (!threadId || (actor.threadId && actor.threadId !== threadId))
  2050. throw new Error("Topic scope mismatch");
  2051. const rootMessageId = readString(message, "root_id") || actor.providerMessageId;
  2052. const root = rootMessageId === actor.providerMessageId ? message : await get(rootMessageId);
  2053. if (root.thread_id !== threadId) throw new Error("Topic root scope mismatch");
  2054. const body = isRecord(root.body) ? root.body : null;
  2055. const content = parseJsonRecord(readString(body, "content"));
  2056. const title = readString(content, "text") || readFeishuPostText(content) || threadId;
  2057. const position = root.thread_message_position;
  2058. const topicUrl =
  2059. (typeof position === "number" || typeof position === "string") &&
  2060. /^\d+$/.test(String(position))
  2061. ? `https://${bot.provider === "lark" ? "applink.larksuite.com" : "applink.feishu.cn"}/client/thread/open?${new URLSearchParams(
  2062. {
  2063. openthreadid: threadId,
  2064. openchatid: actor.chatId,
  2065. open_thread_id: threadId,
  2066. open_chat_id: actor.chatId,
  2067. thread_position: String(position),
  2068. },
  2069. )}`
  2070. : undefined;
  2071. return {
  2072. threadId,
  2073. rootMessageId,
  2074. topicTitle: title.replace(/\s+/gu, " ").slice(0, 80),
  2075. ...(topicUrl ? { topicUrl } : {}),
  2076. };
  2077. },
  2078. async readTopicResourceMessage(bot, target, signal) {
  2079. signal?.throwIfAborted();
  2080. const token = await readTenantAccessToken(bot, deps, signal);
  2081. if (!token) throw new Error("Feishu credentials unavailable");
  2082. const response = await fetchBotProviderJson<{
  2083. code?: number;
  2084. data?: { items?: Array<Record<string, unknown>> };
  2085. }>(
  2086. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(target.messageId)}`,
  2087. {
  2088. headers: { authorization: `Bearer ${token}` },
  2089. signal,
  2090. },
  2091. );
  2092. const native = response.payload?.data?.items?.find(
  2093. (item) => item.message_id === target.messageId,
  2094. );
  2095. if (
  2096. !response.ok ||
  2097. response.payload?.code !== 0 ||
  2098. !native ||
  2099. native.deleted === true ||
  2100. native.chat_id !== target.chatId ||
  2101. native.thread_id !== target.threadId
  2102. )
  2103. throw new Error("Archived resource must be readable in the same topic");
  2104. const body = isRecord(native.body) ? native.body : null;
  2105. const content = parseJsonRecord(readString(body, "content"));
  2106. const kind = readString(native, "msg_type");
  2107. const attachments: BotInboundAttachment[] = [];
  2108. const add = (attachment: BotInboundAttachment | null | undefined) => {
  2109. if (!attachment) throw new Error("Archived resource metadata unavailable");
  2110. attachments.push({
  2111. ...attachment,
  2112. providerMetadata: { resourceMessageId: target.messageId },
  2113. });
  2114. };
  2115. if (kind === "file" || kind === "image") add(readFeishuAttachment(kind, content));
  2116. else if (kind === "post") {
  2117. const visit = (value: unknown): void => {
  2118. if (Array.isArray(value)) {
  2119. value.forEach(visit);
  2120. return;
  2121. }
  2122. if (!isRecord(value)) return;
  2123. if (value.tag === "img") add(readFeishuAttachment("image", value));
  2124. else Object.values(value).forEach(visit);
  2125. };
  2126. visit(content);
  2127. }
  2128. if (!attachments.length) throw new Error("Archived message has no supported resources");
  2129. return { ...target, attachments };
  2130. },
  2131. async readTopicHistory(bot, request) {
  2132. const token = await readTenantAccessToken(bot, deps);
  2133. if (!token) throw new Error("Feishu credentials unavailable");
  2134. const read = async (suffix: string) => {
  2135. const response = await fetchBotProviderJson<{
  2136. code?: number;
  2137. msg?: string;
  2138. data?: { items?: unknown[]; has_more?: boolean; page_token?: string };
  2139. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages${suffix}`, {
  2140. headers: { authorization: `Bearer ${token}` },
  2141. });
  2142. if (!response.ok || response.payload?.code !== 0) {
  2143. const message = response.payload?.msg || "Topic history unavailable";
  2144. if (response.payload?.code === 99991672 || message.includes("im:message.group_msg"))
  2145. throw new TopicHistoryPermissionError(message);
  2146. throw new Error(message);
  2147. }
  2148. return response.payload.data;
  2149. };
  2150. const readHistoryAttachments = (kind: string, content: Record<string, unknown> | null) => {
  2151. const items: Array<{ name: string; kind: string }> = [];
  2152. const add = (type: "image" | "file", value: Record<string, unknown> | null) => {
  2153. const attachment = readFeishuAttachment(type, value);
  2154. if (attachment) items.push({ name: attachment.filename, kind: type });
  2155. };
  2156. if (kind === "image" || kind === "file") add(kind, content);
  2157. else if (kind === "post") {
  2158. const visit = (value: unknown): void => {
  2159. if (Array.isArray(value)) {
  2160. value.forEach(visit);
  2161. return;
  2162. }
  2163. if (!isRecord(value)) return;
  2164. if (value.tag === "img") add("image", value);
  2165. else Object.values(value).forEach(visit);
  2166. };
  2167. visit(content);
  2168. }
  2169. return items;
  2170. };
  2171. const rawMessages = new Map<string, unknown>();
  2172. const normalize = async (raw: unknown, expandCard = false) => {
  2173. if (!isRecord(raw)) throw new Error("Invalid topic history message");
  2174. const sender = isRecord(raw.sender) ? raw.sender : null;
  2175. const body = isRecord(raw.body) ? raw.body : null;
  2176. let content = parseJsonRecord(readString(body, "content"));
  2177. const kind = readString(raw, "msg_type");
  2178. if (
  2179. expandCard &&
  2180. kind === "interactive" &&
  2181. readString(sender, "sender_type") === "app" &&
  2182. !isRecord(content?.body)
  2183. ) {
  2184. // 历史接口也会返回升级客户端占位图,不能据此把操作卡片误判为普通回复。
  2185. const data = await read(
  2186. `/${encodeURIComponent(readString(raw, "message_id"))}?card_msg_content_type=user_card_content`,
  2187. );
  2188. const native = data?.items?.find(
  2189. (item) => isRecord(item) && item.message_id === readString(raw, "message_id"),
  2190. );
  2191. if (
  2192. !isRecord(native) ||
  2193. native.chat_id !== raw.chat_id ||
  2194. native.thread_id !== raw.thread_id
  2195. )
  2196. throw new Error("History card scope unavailable");
  2197. content = parseJsonRecord(isRecord(native.body) ? native.body.content : undefined);
  2198. if (!content) throw new Error("History card content unavailable");
  2199. }
  2200. rawMessages.set(readString(raw, "message_id"), raw);
  2201. return botTopicMessageSchema.parse({
  2202. id: readString(raw, "message_id"),
  2203. chatId: readString(raw, "chat_id"),
  2204. threadId: readString(raw, "thread_id"),
  2205. senderId: readString(sender, "id"),
  2206. senderType: readString(sender, "sender_type"),
  2207. senderName: readString(sender, "name") || undefined,
  2208. parentId: readString(raw, "parent_id") || undefined,
  2209. attachments: readHistoryAttachments(kind, content),
  2210. createdAt: Number(readString(raw, "create_time")),
  2211. kind,
  2212. ...(kind === "interactive" ? { controlCard: isGroupControlCard(content) } : {}),
  2213. text:
  2214. kind === "interactive"
  2215. ? readGroupCardText(content)
  2216. : kind === "text"
  2217. ? readString(content, "text")
  2218. : kind === "post"
  2219. ? readFeishuPostText(content)
  2220. : `[${kind}${readString(content, "file_name") ? `: ${readString(content, "file_name")}` : ""}]`,
  2221. deleted: raw.deleted === true,
  2222. });
  2223. };
  2224. const history = await readTopicHistory(request, {
  2225. list: async (page) => {
  2226. const query = new URLSearchParams({
  2227. container_id_type: "thread",
  2228. container_id: request.threadId,
  2229. sort_type: "ByCreateTimeDesc",
  2230. page_size: "50",
  2231. ...(page ? { page_token: page } : {}),
  2232. });
  2233. const data = await read(`?${query}`);
  2234. if (!Array.isArray(data?.items)) throw new Error("Topic history page unavailable");
  2235. if (data.has_more && !data.page_token)
  2236. throw new Error("Topic history cursor unavailable");
  2237. return {
  2238. messages: await Promise.all(data.items.map((raw) => normalize(raw))),
  2239. next: data.has_more ? data.page_token : undefined,
  2240. };
  2241. },
  2242. // 由历史读取器先确定窗口,正文展开不再作用于整页消息。
  2243. hydrate: (message) => normalize(rawMessages.get(message.id), true),
  2244. get: async (id) => {
  2245. const data = await read(`/${encodeURIComponent(id)}`);
  2246. const raw = data?.items?.find((item) => isRecord(item) && item.message_id === id);
  2247. return normalize(raw);
  2248. },
  2249. });
  2250. if (history.messages.length) {
  2251. const names = await getGroupMemberNames(bot, request.chatId).catch(
  2252. () => ({}) as Record<string, string>,
  2253. );
  2254. history.messages = history.messages.map((message) => ({
  2255. ...message,
  2256. senderName: names[message.senderId] || message.senderName,
  2257. }));
  2258. }
  2259. return history;
  2260. },
  2261. async getGroupInfo(bot, chatId) {
  2262. const token = await readTenantAccessToken(bot, deps);
  2263. if (!token) throw new Error("Feishu credentials are unavailable");
  2264. const response = await fetchBotProviderJson<{
  2265. code?: number;
  2266. msg?: string;
  2267. data?: { name?: string; chat_mode?: string };
  2268. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}`, {
  2269. headers: { authorization: `Bearer ${token}` },
  2270. });
  2271. if (!response.ok || response.payload?.code !== 0)
  2272. throw new Error(response.payload?.msg || "Cannot read group information");
  2273. return {
  2274. name: response.payload.data?.name || chatId,
  2275. chatMode: response.payload.data?.chat_mode === "topic" ? "topic" : "group",
  2276. };
  2277. },
  2278. async prepareCallbackPayload(bot, payload) {
  2279. if (!isRecord(payload)) return payload;
  2280. const event = isRecord(payload.event) ? payload.event : payload;
  2281. const action = isRecord(event.action) ? event.action : null;
  2282. const actionValue = isRecord(action?.value) ? action.value : null;
  2283. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  2284. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  2285. const card = botGroupCardSchema.safeParse(actionValue?.groupCard ?? behaviorValue?.groupCard);
  2286. if (card.success) {
  2287. const context = isRecord(event.context) ? event.context : null;
  2288. const chatId = readString(context, "open_chat_id") || readString(context, "chat_id");
  2289. const cardId = readString(context, "open_message_id") || readString(context, "message_id");
  2290. // 卡片回调只有短响应窗口,位置验证与 token 请求共用同一 deadline。
  2291. const signal = AbortSignal.timeout(1500);
  2292. const token = await readTenantAccessToken(bot, deps, signal);
  2293. signal.throwIfAborted();
  2294. if (!token || !cardId || chatId !== card.data.chatId)
  2295. throw new Error("Card scope unavailable");
  2296. const response = await fetchBotProviderJson<{
  2297. code?: number;
  2298. data?: { items?: Array<Record<string, unknown>> };
  2299. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(cardId)}`, {
  2300. headers: { authorization: `Bearer ${token}` },
  2301. signal,
  2302. });
  2303. const native = response.payload?.data?.items?.find((item) => item.message_id === cardId);
  2304. // 按钮参数不是原生位置真源;必须验证卡片实际所在的话题。
  2305. if (
  2306. !response.ok ||
  2307. response.payload?.code !== 0 ||
  2308. native?.chat_id !== chatId ||
  2309. (readString(native ?? null, "thread_id") || undefined) !== card.data.threadId
  2310. )
  2311. throw new Error("Card topic scope mismatch");
  2312. return payload;
  2313. }
  2314. const message = isRecord(event.message) ? event.message : null;
  2315. if (readString(message, "chat_type") !== "group") return payload;
  2316. const messageSender = isRecord(event.sender) ? event.sender : null;
  2317. if (
  2318. isFeishuBotSender(readString(messageSender, "sender_type")) &&
  2319. (readString(message, "message_type") || readString(message, "msg_type")) ===
  2320. "interactive" &&
  2321. isGroupControlCard(parseJsonRecord(message?.content))
  2322. )
  2323. return payload;
  2324. const identityKey = `${bot.provider}:${bot.feishuAppId}`;
  2325. let openId = botOpenIds.get(identityKey);
  2326. if (!openId) {
  2327. const token = await readTenantAccessToken(bot, deps);
  2328. if (!token) throw new Error("Feishu credentials are unavailable");
  2329. const response = await fetchBotProviderJson<{
  2330. code?: number;
  2331. msg?: string;
  2332. bot?: { open_id?: string };
  2333. }>(`${getFeishuBaseUrl(bot)}/open-apis/bot/v3/info`, {
  2334. headers: { authorization: `Bearer ${token}` },
  2335. });
  2336. openId = response.payload?.bot?.open_id;
  2337. if (!response.ok || response.payload?.code !== 0 || !openId)
  2338. throw new Error(response.payload?.msg || "Cannot resolve Feishu bot identity");
  2339. botOpenIds.set(identityKey, openId);
  2340. }
  2341. let nativeCardContent: Record<string, unknown> | undefined;
  2342. if (
  2343. isFeishuBotSender(readString(messageSender, "sender_type")) &&
  2344. (readString(message, "message_type") || readString(message, "msg_type")) === "interactive"
  2345. ) {
  2346. const currentContent = parseJsonRecord(message?.content);
  2347. // 默认事件/历史内容可能只是升级客户端占位图;先读取真实正文再分类。
  2348. if (!isRecord(currentContent?.body)) {
  2349. const token = await readTenantAccessToken(bot, deps);
  2350. if (!token) throw new Error("Card credentials unavailable");
  2351. const response = await fetchBotProviderJson<{
  2352. code?: number;
  2353. data?: {
  2354. items?: Array<{
  2355. message_id?: string;
  2356. chat_id?: string;
  2357. thread_id?: string;
  2358. body?: { content?: string };
  2359. }>;
  2360. };
  2361. }>(
  2362. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(readString(message, "message_id"))}?card_msg_content_type=user_card_content`,
  2363. { headers: { authorization: `Bearer ${token}` } },
  2364. );
  2365. const native = response.payload?.data?.items?.[0];
  2366. if (
  2367. !response.ok ||
  2368. response.payload?.code !== 0 ||
  2369. native?.message_id !== readString(message, "message_id") ||
  2370. native.chat_id !== readString(message, "chat_id") ||
  2371. (native.thread_id || "") !== readString(message, "thread_id")
  2372. )
  2373. throw new Error("Card message scope unavailable");
  2374. nativeCardContent = parseJsonRecord(native.body?.content) ?? undefined;
  2375. if (!nativeCardContent) throw new Error("Card content unavailable");
  2376. }
  2377. }
  2378. const sender = isRecord(event.sender) ? event.sender : null;
  2379. const parentId = readString(message, "parent_id");
  2380. const rootId = readString(message, "root_id");
  2381. let topicRootIsCurrentBot = false;
  2382. let referencedAttachment: BotInboundAttachment | undefined;
  2383. let referencedMessage: BotInboundMessage["referencedMessage"];
  2384. const referencedInlineImages: Array<{ imageKey: string; messageId: string }> = [];
  2385. if (
  2386. parentId &&
  2387. (readString(sender, "sender_type") === "user" ||
  2388. (isFeishuBotSender(readString(sender, "sender_type")) &&
  2389. readString(isRecord(sender?.sender_id) ? sender.sender_id : null, "open_id") !==
  2390. openId)) &&
  2391. !(
  2392. payload.zcodeTopicHasAcceptedInput === true &&
  2393. parentId === rootId &&
  2394. !isFeishuBotSender(readString(sender, "sender_type"))
  2395. ) &&
  2396. (Boolean(readString(message, "thread_id")) ||
  2397. readGroupMentionText(
  2398. "",
  2399. message?.mentions,
  2400. openId,
  2401. readString(sender, "sender_type"),
  2402. readString(isRecord(sender?.sender_id) ? sender.sender_id : null, "open_id"),
  2403. ) !== null)
  2404. ) {
  2405. const token = await readTenantAccessToken(bot, deps);
  2406. const response = await fetchBotProviderJson<{
  2407. code?: number;
  2408. msg?: string;
  2409. data?: {
  2410. items?: Array<{
  2411. message_id?: string;
  2412. chat_id?: string;
  2413. thread_id?: string;
  2414. msg_type?: string;
  2415. deleted?: boolean;
  2416. create_time?: string;
  2417. sender?: { id?: string; id_type?: string; sender_type?: string };
  2418. body?: { content?: string };
  2419. }>;
  2420. };
  2421. }>(
  2422. // 默认卡片响应仅含“升级客户端”占位文案;必须请求真实卡片正文供引用解析。
  2423. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(parentId)}?card_msg_content_type=user_card_content`,
  2424. { headers: { authorization: `Bearer ${token}` } },
  2425. );
  2426. const referenced = response.payload?.data?.items?.[0];
  2427. if (
  2428. !response.ok ||
  2429. response.payload?.code !== 0 ||
  2430. referenced?.message_id !== parentId ||
  2431. referenced.chat_id !== readString(message, "chat_id") ||
  2432. referenced.deleted
  2433. )
  2434. throw new Error("Referenced attachment must be readable in the same group");
  2435. // 引用消息可来自同群另一个话题,不能只用 chat_id 证明附件归属。
  2436. if (
  2437. (referenced.thread_id || undefined) !== (readString(message, "thread_id") || undefined) &&
  2438. !(parentId === rootId && !referenced.thread_id)
  2439. )
  2440. throw new Error("Referenced attachment must be readable in the same topic");
  2441. topicRootIsCurrentBot =
  2442. parentId === rootId &&
  2443. referenced.sender?.sender_type === "app" &&
  2444. ((referenced.sender.id_type === "app_id" && referenced.sender.id === bot.feishuAppId) ||
  2445. (referenced.sender.id_type === "open_id" && referenced.sender.id === openId));
  2446. if (!["text", "post", "image", "file", "interactive"].includes(referenced.msg_type ?? "")) {
  2447. throw new Error("Referenced message type is unsupported");
  2448. }
  2449. if (referenced.msg_type === "interactive") {
  2450. // 确认文字没有专用事件类型,须通过可信 parent 消息识别,不能依赖翻译文案。
  2451. if (
  2452. isFeishuBotSender(readString(sender, "sender_type")) &&
  2453. isFeishuBotSender(referenced.sender?.sender_type ?? "") &&
  2454. isGroupControlCard(parseJsonRecord(referenced.body?.content))
  2455. )
  2456. return { ...payload, zcodeIgnoreInteractionMessage: true };
  2457. const text = readGroupCardText(parseJsonRecord(referenced.body?.content));
  2458. if (!text) throw new Error("Referenced message has no readable text");
  2459. referencedMessage = { messageId: parentId, text };
  2460. }
  2461. // 文字引用此前只做权限检查后丢弃,导致仅 @ 被误判为空消息。
  2462. if (referenced.msg_type === "text" || referenced.msg_type === "post") {
  2463. const body = parseJsonRecord(referenced.body?.content);
  2464. const quotedText =
  2465. referenced.msg_type === "text" ? readString(body, "text") : readFeishuPostText(body);
  2466. if (referenced.msg_type === "post") {
  2467. const visit = (value: unknown): void => {
  2468. if (Array.isArray(value)) {
  2469. value.forEach(visit);
  2470. return;
  2471. }
  2472. if (!isRecord(value)) return;
  2473. if (value.tag === "img") {
  2474. const image = readFeishuAttachment("image", value);
  2475. if (!image?.providerFileId) throw new Error("Referenced image is invalid");
  2476. referencedInlineImages.push({
  2477. imageKey: image.providerFileId,
  2478. messageId: parentId,
  2479. });
  2480. }
  2481. visit(value.content ?? value.children ?? value.elements);
  2482. };
  2483. if (body) visit(readFeishuPostLocaleContent(body));
  2484. }
  2485. if (!quotedText.trim() && !referencedInlineImages.length)
  2486. throw new Error("Referenced message is empty or unavailable");
  2487. referencedMessage = { messageId: parentId, text: quotedText };
  2488. }
  2489. if (referencedMessage) {
  2490. const senderId = referenced.sender?.id;
  2491. const names = senderId
  2492. ? await getGroupMemberNames(bot, referenced.chat_id!).catch(
  2493. () => ({}) as Record<string, string>,
  2494. )
  2495. : {};
  2496. const sentAt = Number(referenced.create_time);
  2497. referencedMessage = {
  2498. ...referencedMessage,
  2499. ...(senderId
  2500. ? {
  2501. senderId,
  2502. senderName:
  2503. names[senderId] ||
  2504. (senderId === openId ||
  2505. (referenced.sender?.sender_type === "app" && senderId === bot.feishuAppId)
  2506. ? bot.name
  2507. : undefined),
  2508. }
  2509. : {}),
  2510. ...(Number.isFinite(sentAt) && sentAt > 0
  2511. ? { sentAt: new Date(sentAt).toISOString() }
  2512. : {}),
  2513. };
  2514. }
  2515. if (referenced.msg_type === "image" || referenced.msg_type === "file") {
  2516. const attachment = readFeishuAttachment(
  2517. referenced.msg_type,
  2518. parseJsonRecord(referenced.body?.content),
  2519. );
  2520. if (!attachment) throw new Error("Referenced attachment is invalid");
  2521. referencedAttachment = {
  2522. ...attachment,
  2523. providerMetadata: { resourceMessageId: parentId },
  2524. };
  2525. }
  2526. }
  2527. return {
  2528. ...payload,
  2529. zcodeBotOpenId: openId,
  2530. ...(nativeCardContent ? { zcodeNativeCardContent: nativeCardContent } : {}),
  2531. zcodeTopicRootIsCurrentBot: topicRootIsCurrentBot,
  2532. zcodeReferencedAttachment: referencedAttachment,
  2533. zcodeReferencedMessage: referencedMessage,
  2534. zcodeReferencedInlineImages: referencedInlineImages,
  2535. };
  2536. },
  2537. splitStreamingReplyCardStates: splitFeishuStreamingCardStates,
  2538. async test(bot) {
  2539. if (!bot.enabled) {
  2540. return { ok: false, message: "Feishu bot is disabled." };
  2541. }
  2542. if (!bot.feishuAppId || !bot.credentialRef) {
  2543. return {
  2544. ok: false,
  2545. message: "Feishu App ID and App Secret are required.",
  2546. };
  2547. }
  2548. const token = await readTenantAccessToken(bot, deps);
  2549. return token
  2550. ? { ok: true, message: "Feishu app credentials are valid." }
  2551. : { ok: false, message: "Feishu app credentials are missing." };
  2552. },
  2553. async resolveName(bot) {
  2554. // Bugfix: Feishu 创建向导以前只能使用手填/默认名称,容易和真实机器人名称不一致。
  2555. // 飞书机器人能力挂在自建应用上,这里读取应用信息中的名称作为 bot 展示名。
  2556. return readFeishuAppDisplayName(bot, deps);
  2557. },
  2558. async resolveActorDisplayName(bot, actor) {
  2559. // 群事件不保证携带姓名;群成员接口避免依赖组织通讯录可见范围。
  2560. if (actor.chatType === "group") {
  2561. if (!actor.chatId) return null;
  2562. return (await getGroupMemberNames(bot, actor.chatId))[actor.providerUserId] ?? null;
  2563. }
  2564. return readFeishuUserDisplayName(bot, deps, actor.providerUserId);
  2565. },
  2566. async send(bot, message) {
  2567. resolveFeishuReplyTarget(message);
  2568. if (message.contentParts) {
  2569. const parts = channelContentPartsSchema.parse(message.contentParts);
  2570. if (
  2571. message.selection ||
  2572. !message.providerUserId.startsWith("oc_") ||
  2573. parts.some((part) => part.type === "channelMention" && part.channel !== bot.provider) ||
  2574. channelContentText(parts) !== message.text ||
  2575. message.text.length > 2000
  2576. )
  2577. throw Object.assign(new Error("Invalid native channel reply"), {
  2578. deliveryRejected: true,
  2579. });
  2580. }
  2581. const token = await readTenantAccessToken(bot, deps);
  2582. if (!token) {
  2583. if (message.deliveryId)
  2584. throw Object.assign(new Error("Feishu credentials unavailable"), {
  2585. deliveryRejected: true,
  2586. });
  2587. return;
  2588. }
  2589. if (message.selection) {
  2590. const providerMessageId = await sendReplyCard(
  2591. bot,
  2592. token,
  2593. message,
  2594. message.elicitation
  2595. ? buildFeishuElicitationCardPayload(message)
  2596. : buildFeishuInteractiveCardPayload(message),
  2597. );
  2598. return message.selection.action === "queue.cancel" && providerMessageId
  2599. ? { providerMessageId }
  2600. : undefined;
  2601. }
  2602. let partIndex = 0;
  2603. let providerMessageId: string | null = null;
  2604. for (const text of splitFeishuText(message.text)) {
  2605. // Bugfix: Feishu 普通文本消息会把 Markdown 原样展示,和 Telegram 的 Markdown 回复不一致。
  2606. // 改用交互卡片的 markdown 元素承载普通回复,选择消息也继续复用同一套卡片结构。
  2607. providerMessageId = await sendReplyCard(
  2608. bot,
  2609. token,
  2610. message,
  2611. buildFeishuInteractiveCardPayload({
  2612. ...message,
  2613. text,
  2614. mentionedUserIds: partIndex === 0 ? message.mentionedUserIds : undefined,
  2615. selection: undefined,
  2616. }),
  2617. message.deliveryId ? `${message.deliveryId.slice(0, 40)}-${partIndex}` : undefined,
  2618. );
  2619. partIndex += 1;
  2620. }
  2621. return message.deliveryId && providerMessageId ? { providerMessageId } : undefined;
  2622. },
  2623. async createStreamingReplyCard(bot, state, signal) {
  2624. const token = await readTenantAccessToken(bot, deps, signal);
  2625. if (!token) {
  2626. return null;
  2627. }
  2628. const providerMessageId = await sendCard(
  2629. bot,
  2630. token,
  2631. state.providerUserId,
  2632. buildFeishuStreamingCardPayload(state),
  2633. signal,
  2634. );
  2635. return providerMessageId ? { providerMessageId } : null;
  2636. },
  2637. async updateStreamingReplyCard(bot, handle, state, signal) {
  2638. const token = await readTenantAccessToken(bot, deps, signal);
  2639. if (!token) {
  2640. return;
  2641. }
  2642. await updateCard(bot, token, handle, buildFeishuStreamingCardPayload(state), signal);
  2643. },
  2644. async createTransientInteractionCard(bot, message) {
  2645. resolveFeishuReplyTarget(message);
  2646. if (message.contentParts) {
  2647. const parts = channelContentPartsSchema.parse(message.contentParts);
  2648. if (
  2649. message.selection ||
  2650. !message.providerUserId.startsWith("oc_") ||
  2651. parts.some((part) => part.type === "channelMention" && part.channel !== bot.provider) ||
  2652. channelContentText(parts) !== message.text ||
  2653. message.text.length > 2000
  2654. )
  2655. throw Object.assign(new Error("Invalid native channel reply"), {
  2656. deliveryRejected: true,
  2657. });
  2658. }
  2659. const token = await readTenantAccessToken(bot, deps);
  2660. if (!token) {
  2661. return null;
  2662. }
  2663. const providerMessageId = await sendReplyCard(
  2664. bot,
  2665. token,
  2666. message,
  2667. message.elicitation
  2668. ? buildFeishuElicitationCardPayload(message)
  2669. : buildFeishuInteractiveCardPayload(message),
  2670. );
  2671. return providerMessageId ? { providerMessageId } : null;
  2672. },
  2673. async updateTransientInteractionCard(bot, handle, message) {
  2674. const token = await readTenantAccessToken(bot, deps);
  2675. if (!token) {
  2676. return;
  2677. }
  2678. await updateCard(
  2679. bot,
  2680. token,
  2681. handle,
  2682. message.elicitation
  2683. ? buildFeishuElicitationCardPayload(message)
  2684. : buildFeishuInteractiveCardPayload(message),
  2685. );
  2686. },
  2687. async deleteTransientInteractionCard(bot, handle) {
  2688. const token = await readTenantAccessToken(bot, deps);
  2689. if (!token) {
  2690. return;
  2691. }
  2692. await deleteFeishuInteractiveMessage(bot, token, handle);
  2693. },
  2694. async updateInputReaction(bot, messageId, state) {
  2695. const botKey = JSON.stringify([bot.provider, bot.id, bot.feishuAppId, bot.credentialRef]);
  2696. reactionBots.set(botKey, bot);
  2697. await updateReaction(JSON.stringify([botKey, messageId]), state);
  2698. },
  2699. async sendTyping(bot, target) {
  2700. if (!target.providerMessageId) {
  2701. return;
  2702. }
  2703. // Bugfix: 飞书/Lark 普通命令不会进入长任务 stream,之前只实现 startTyping/stopTyping,
  2704. // 所以 /状态、/项目 等命令没有任何处理中反馈。这里只加 Typing reaction,删除由 BotService 在同步回复发送完成后显式收口。
  2705. await addFeishuTypingReaction(bot, deps, target.providerMessageId);
  2706. },
  2707. async startTyping(bot, target) {
  2708. if (!target.providerMessageId) {
  2709. return;
  2710. }
  2711. // Bugfix: 飞书没有原生 typing 状态,只能用 Typing reaction 模拟。
  2712. // reaction 不会自动消失,所以必须记录 reaction_id,任务结束或进入权限等待时再删除。
  2713. await addFeishuTypingReaction(bot, deps, target.providerMessageId);
  2714. },
  2715. async stopTyping(bot, target) {
  2716. if (!target.providerMessageId) {
  2717. return;
  2718. }
  2719. await deleteFeishuTypingReaction(bot, deps, target.providerMessageId);
  2720. },
  2721. async acknowledgeCallback(bot, payload, text, message, signal) {
  2722. const token = await readTenantAccessToken(bot, deps, signal);
  2723. const cardUpdateToken = readFeishuCardUpdateToken(payload);
  2724. const openIds = readFeishuCardUpdateOpenIds(payload);
  2725. const originalText = readFeishuCardOriginalText(payload);
  2726. if (!token || !cardUpdateToken || (!text?.trim() && !message?.elicitation)) {
  2727. return;
  2728. }
  2729. // Bugfix: 飞书卡片按钮点击后不会像 Telegram inline keyboard 一样自动消失。
  2730. // 使用回调携带的 card update token 更新原卡片为处理结果,避免旧选项继续留在聊天里被重复点击。
  2731. // 非共享卡片延时更新还需要带 open_ids,否则飞书会返回 300090,旧卡片会继续留在会话里。
  2732. // Bugfix: 用户选择后应保留原问题文案并移除按钮;仅依赖 WebSocket 回调 return 的卡片更新不稳定。
  2733. // 因此即使按钮 value 里带了原文,也必须继续调用 card/update,只是更新文案优先使用原文。
  2734. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  2735. `${getFeishuBaseUrl(bot)}/open-apis/interactive/v1/card/update`,
  2736. {
  2737. method: "POST",
  2738. headers: {
  2739. authorization: `Bearer ${token}`,
  2740. "content-type": "application/json",
  2741. },
  2742. signal,
  2743. body: JSON.stringify({
  2744. token: cardUpdateToken,
  2745. // Bugfix: Card JSON 2.0 根节点不接受 open_ids;把 open_ids 塞进 card 会触发
  2746. // “unknown property: open_ids” 并导致按钮点击后原卡片无法移除选项。
  2747. ...(openIds.length > 0 ? { open_ids: openIds } : {}),
  2748. // 修复原因:新建下一题再撤回旧卡会在飞书会话中显示明显的撤回痕迹。
  2749. // callback token 是本次点击对应的权威原地更新能力,问答推进和终态都复用同一张卡。
  2750. card: message?.elicitation
  2751. ? buildFeishuElicitationCardPayload(message)
  2752. : buildFeishuInteractiveCardPayload({
  2753. botId: bot.id,
  2754. provider: bot.provider,
  2755. providerUserId: "",
  2756. // Bugfix: 飞书按钮点击后业务结果会另发一条消息;原卡片只需要移除选项按钮。
  2757. // 之前把原卡片改成结果文案,飞书侧会出现额外状态变化,也不符合用户对“选项消失”的预期。
  2758. text: originalText?.trim() || (text ?? ""),
  2759. }),
  2760. }),
  2761. },
  2762. );
  2763. if (!response.ok) {
  2764. throw new Error(`Feishu update interactive card failed: HTTP ${response.status}`);
  2765. }
  2766. const result = response.payload ?? {};
  2767. if (result.code !== 0) {
  2768. throw new Error(result.msg || "Feishu update interactive card failed.");
  2769. }
  2770. return message?.elicitation ? { handled: true } : undefined;
  2771. },
  2772. async downloadAttachment(bot, attachment, actor, signal) {
  2773. signal?.throwIfAborted();
  2774. const token = await readTenantAccessToken(bot, deps, signal);
  2775. if (!token || !attachment.providerFileId || !actor?.providerMessageId) {
  2776. return null;
  2777. }
  2778. const controller = new AbortController();
  2779. const timeout = setTimeout(() => controller.abort(), FEISHU_ATTACHMENT_DOWNLOAD_TIMEOUT_MS);
  2780. try {
  2781. const response = await fetch(
  2782. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(attachment.providerMetadata?.resourceMessageId ?? actor.providerMessageId)}/resources/${encodeURIComponent(attachment.providerFileId)}?type=${attachment.kind === "image" ? "image" : attachment.kind === "video" ? "media" : attachment.kind}`,
  2783. {
  2784. headers: {
  2785. authorization: `Bearer ${token}`,
  2786. },
  2787. signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
  2788. },
  2789. );
  2790. if (!response.ok) {
  2791. throw new Error(`Feishu attachment download failed: HTTP ${response.status}`);
  2792. }
  2793. return {
  2794. attachment,
  2795. data: new Uint8Array(await response.arrayBuffer()),
  2796. };
  2797. } catch (error) {
  2798. signal?.throwIfAborted();
  2799. if ((error as { name?: unknown })?.name === "AbortError") {
  2800. // Bugfix: 飞书资源接口偶发长时间不返回,必须让 bot 回调在可预期时间内给用户失败提示。
  2801. throw new Error("Feishu attachment download timed out.");
  2802. }
  2803. throw error;
  2804. } finally {
  2805. clearTimeout(timeout);
  2806. }
  2807. },
  2808. parseCallback(payload): BotInboundMessage[] {
  2809. if (!isRecord(payload)) {
  2810. return [];
  2811. }
  2812. const botId = readString(payload, "botId");
  2813. if (!botId) {
  2814. return [];
  2815. }
  2816. const message = readFeishuTextMessage(botId, payload) ?? readFeishuCardAction(botId, payload);
  2817. return message ? [message] : [];
  2818. },
  2819. };
  2820. }