feishuProvider.ts 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918
  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. // 文字与文件一起发送时,文件位于顶层 files;只遍历正文图片会静默丢掉 PDF 等附件。
  740. if (Array.isArray(content.files)) {
  741. for (const file of content.files) {
  742. const attachment = readFeishuAttachment("file", isRecord(file) ? file : null);
  743. if (attachment) attachments.push(attachment);
  744. }
  745. }
  746. const visit = (node: unknown): void => {
  747. if (Array.isArray(node)) {
  748. for (const child of node) visit(child);
  749. return;
  750. }
  751. if (!isRecord(node)) return;
  752. if (node.tag === "img") {
  753. const image = readFeishuAttachment("image", node);
  754. if (image) attachments.push(image);
  755. else malformedInlineImage = true;
  756. }
  757. visit(node.content ?? node.children ?? node.elements);
  758. };
  759. visit(readFeishuPostLocaleContent(content));
  760. }
  761. // 缺少图片引用不能静默降级成只执行正文。
  762. if (malformedInlineImage) return null;
  763. // Bugfix: 飞书客户端里看起来像普通文字的富文本/带链接消息会以 message_type=post 推送。
  764. // 之前只读 content.text,post 消息被解析成空文本并直接丢弃,所以用户侧表现为“发了普通消息但 app 没反应”。
  765. const rawText =
  766. (msgType === "interactive" ? readGroupConversationCardText(content, message?.mentions) : "") ||
  767. readString(content, "text") ||
  768. readFeishuPostText(
  769. content,
  770. readString(payload, "zcodeBotOpenId") || undefined,
  771. message?.mentions,
  772. ) ||
  773. readString(event, "text_without_at_bot") ||
  774. readString(event, "text");
  775. const incomingChatType = readString(message, "chat_type") || readString(event, "chat_type");
  776. if (incomingChatType === "topic_group") return null;
  777. const groupMessage =
  778. incomingChatType === "group"
  779. ? readGroupMessage(
  780. rawText,
  781. message?.mentions,
  782. readString(payload, "zcodeBotOpenId"),
  783. readString(sender, "sender_type"),
  784. readString(senderId, "open_id"),
  785. )
  786. : undefined;
  787. // Provider 验证发送者与 mention 身份;机器人群主聊天必须原生 @,群/话题启用状态由服务校验。
  788. if (
  789. isFeishuBotSender(readString(sender, "sender_type")) &&
  790. (incomingChatType !== "group" ||
  791. (!readString(message, "thread_id") && !groupMessage?.mentionedBot))
  792. )
  793. return null;
  794. if (
  795. incomingChatType === "group" &&
  796. (!groupMessage || (!groupMessage.mentionedBot && !readString(message, "thread_id")))
  797. )
  798. return null;
  799. const text = groupMessage?.text ?? stripFeishuMentions(rawText);
  800. // 群权限只使用应用内 open_id,不能把其他 ID 命名空间误当作绑定身份。
  801. if (incomingChatType === "group" && !readString(senderId, "open_id")) return null;
  802. const userId =
  803. readString(senderId, "open_id") ||
  804. readString(senderId, "user_id") ||
  805. readString(senderId, "union_id") ||
  806. readString(event, "open_id") ||
  807. readString(event, "user_id") ||
  808. readString(event, "union_id");
  809. const chatId = readString(message, "chat_id") || readString(event, "open_chat_id");
  810. const messageId = readString(message, "message_id");
  811. // 群内仅 @ 仍是有效唤起,空需求由服务结合引用/话题背景处理。
  812. if ((!text && attachments.length === 0 && incomingChatType !== "group") || !userId) {
  813. return null;
  814. }
  815. const chatType = readFeishuChatType(
  816. readString(message, "chat_type") || readString(event, "chat_type"),
  817. );
  818. return {
  819. botId,
  820. text,
  821. ...(groupMessage
  822. ? {
  823. ...(isFeishuBotSender(readString(sender, "sender_type"))
  824. ? { senderType: "app" as const }
  825. : {}),
  826. botOpenId: readString(payload, "zcodeBotOpenId") || undefined,
  827. mentionedBot: groupMessage.mentionedBot,
  828. commandText: groupMessage.commandText,
  829. ...(groupMessage.contentParts
  830. ? {
  831. contentParts: groupMessage.contentParts.map((part) =>
  832. part.type === "text"
  833. ? part
  834. : {
  835. ...part,
  836. channel: provider === "lark" ? ("lark" as const) : ("feishu" as const),
  837. refId: `${messageId}:${part.refId}`,
  838. },
  839. ),
  840. }
  841. : {}),
  842. topicRootIsCurrentBot: payload.zcodeTopicRootIsCurrentBot === true,
  843. }
  844. : {}),
  845. ...(isRecord(payload.zcodeReferencedMessage) &&
  846. typeof payload.zcodeReferencedMessage.messageId === "string" &&
  847. typeof payload.zcodeReferencedMessage.text === "string"
  848. ? {
  849. referencedMessage: {
  850. ...payload.zcodeReferencedMessage,
  851. messageId: payload.zcodeReferencedMessage.messageId,
  852. text: payload.zcodeReferencedMessage.text,
  853. },
  854. }
  855. : {}),
  856. ...(attachments.length ? { attachments } : {}),
  857. actor: {
  858. provider,
  859. botId,
  860. providerUserId: userId,
  861. displayName: readString(sender, "sender_name") || undefined,
  862. chatType,
  863. chatId: chatType === "group" && chatId ? chatId : undefined,
  864. ...(chatType === "group" && readString(message, "thread_id")
  865. ? {
  866. threadId: readString(message, "thread_id"),
  867. rootMessageId: readString(message, "root_id") || messageId,
  868. }
  869. : {}),
  870. providerMessageId: messageId || undefined,
  871. },
  872. };
  873. }
  874. function readFeishuCardAction(
  875. botId: string,
  876. payload: Record<string, unknown>,
  877. ): BotInboundMessage | null {
  878. const provider = readFeishuPayloadProvider(payload);
  879. const event = readFeishuCallbackEvent(payload);
  880. const action = isRecord(event.action) ? event.action : null;
  881. const value = isRecord(action?.value) ? action.value : null;
  882. const formValue = isRecord(action?.form_value) ? action.form_value : null;
  883. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  884. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  885. const rawCommand =
  886. readString(value, "command") ||
  887. readString(value, "text") ||
  888. readString(behaviorValue, "command") ||
  889. readString(behaviorValue, "text");
  890. const submittedAnswer = formValue?.[FEISHU_ELICITATION_FORM_FIELD_NAME];
  891. const command =
  892. rawCommand && rawCommand.includes(FEISHU_ELICITATION_FORM_VALUE_PREFIX)
  893. ? buildFeishuElicitationFormCommand(rawCommand.split(/\s+/u)[1] ?? "", submittedAnswer)
  894. : rawCommand;
  895. const operator = isRecord(event.operator) ? event.operator : null;
  896. const operatorId = isRecord(operator?.operator_id) ? operator.operator_id : null;
  897. const openId =
  898. readString(operatorId, "open_id") ||
  899. readString(operator, "open_id") ||
  900. readString(event, "open_id") ||
  901. readString(event, "user_id") ||
  902. readString(payload, "open_id") ||
  903. readString(payload, "user_id");
  904. const context = isRecord(event.context) ? event.context : null;
  905. const contextChatType =
  906. readString(context, "chat_type") ||
  907. readString(event, "chat_type") ||
  908. readString(payload, "chat_type");
  909. const chatId = readString(context, "open_chat_id") || readString(context, "chat_id");
  910. const message = isRecord(event.message) ? event.message : null;
  911. const header = isRecord(payload.header) ? payload.header : null;
  912. const providerMessageId =
  913. readString(event, "event_id") ||
  914. readString(header, "event_id") ||
  915. readString(payload, "uuid") ||
  916. readString(payload, "event_id") ||
  917. readString(context, "open_message_id") ||
  918. readString(context, "message_id") ||
  919. readString(message, "message_id") ||
  920. readString(action, "value_id");
  921. if (!command || !openId) {
  922. return null;
  923. }
  924. // Bugfix: 飞书卡片回调的 context.open_chat_id 在私聊按钮里也可能存在。
  925. // 之前用 chatId 是否存在判断群聊,会把私聊里的卡片按钮误拒成“只支持私聊”。
  926. const chatType = readFeishuChatType(readString(payload, "zcodeChatType") || contextChatType);
  927. const groupCard = botGroupCardSchema.safeParse(value?.groupCard ?? behaviorValue?.groupCard);
  928. return {
  929. botId,
  930. ...(chatType === "group"
  931. ? { groupCardAction: true, ...(groupCard.success ? { groupCard: groupCard.data } : {}) }
  932. : {}),
  933. text: command,
  934. actor: {
  935. provider,
  936. botId,
  937. providerUserId: openId,
  938. chatType,
  939. chatId: chatType === "group" && chatId ? chatId : undefined,
  940. ...(chatType === "group" && groupCard.success && groupCard.data.threadId
  941. ? { threadId: groupCard.data.threadId }
  942. : {}),
  943. ...(providerMessageId ? { providerMessageId } : {}),
  944. },
  945. };
  946. }
  947. function readFeishuCardUpdateToken(payload: unknown): string {
  948. if (!isRecord(payload)) {
  949. return "";
  950. }
  951. const event = readFeishuCallbackEvent(payload);
  952. const action = isRecord(event.action) ? event.action : null;
  953. const context = isRecord(event.context) ? event.context : null;
  954. // Bugfix: Card JSON 2.0 回调的更新 token 不总在旧版 action.token 上。
  955. // 新版按钮由 behaviors.callback 触发时,飞书/Lark 可能把 token 放在事件或 context 上;漏读会让 card/update 静默跳过,按钮留在原卡片里。
  956. return (
  957. readString(event, "token") ||
  958. readString(event, "card_update_token") ||
  959. readString(event, "update_token") ||
  960. readString(payload, "token") ||
  961. readString(payload, "card_update_token") ||
  962. readString(payload, "update_token") ||
  963. readString(action, "token") ||
  964. readString(action, "card_update_token") ||
  965. readString(action, "update_token") ||
  966. readString(context, "token") ||
  967. readString(context, "card_update_token") ||
  968. readString(context, "update_token")
  969. );
  970. }
  971. function readFeishuCardUpdateOpenIds(payload: unknown): string[] {
  972. if (!isRecord(payload)) {
  973. return [];
  974. }
  975. const event = readFeishuCallbackEvent(payload);
  976. const operator = isRecord(event.operator) ? event.operator : null;
  977. const operatorId = isRecord(operator?.operator_id) ? operator.operator_id : null;
  978. const openId =
  979. readString(operatorId, "open_id") ||
  980. readString(operator, "open_id") ||
  981. readString(event, "open_id") ||
  982. readString(payload, "open_id");
  983. return openId ? [openId] : [];
  984. }
  985. function readFeishuCardOriginalText(payload: unknown): string | null {
  986. if (!isRecord(payload)) {
  987. return null;
  988. }
  989. const event = readFeishuCallbackEvent(payload);
  990. const action = isRecord(event.action) ? event.action : null;
  991. const value = isRecord(action?.value) ? action.value : null;
  992. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  993. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  994. return (
  995. readString(value, "zcodeCardText") ||
  996. readString(value, "cardText") ||
  997. readString(behaviorValue, "zcodeCardText") ||
  998. readString(behaviorValue, "cardText") ||
  999. null
  1000. );
  1001. }
  1002. function formatFeishuCardMarkdownContent(text: string): string {
  1003. const lines: Array<{ text: string; hardBreak: boolean }> = [];
  1004. let inCodeFence = false;
  1005. for (const line of text.split("\n")) {
  1006. if (line.trimStart().startsWith("```")) {
  1007. inCodeFence = !inCodeFence;
  1008. }
  1009. if (!inCodeFence && /^-{3,}$/.test(line.trim())) {
  1010. if (lines.length > 0 && lines.at(-1)?.text !== "") {
  1011. lines.push({ text: "", hardBreak: false });
  1012. }
  1013. lines.push({ text: "---", hardBreak: false }, { text: "", hardBreak: false });
  1014. continue;
  1015. }
  1016. lines.push({ text: line, hardBreak: !inCodeFence });
  1017. }
  1018. return lines
  1019. .map((line, index) => {
  1020. if (!line.text || !line.hardBreak || index >= lines.length - 1 || !lines[index + 1]?.text) {
  1021. return line.text;
  1022. }
  1023. // Bugfix: Card JSON 2.0 的 markdown 按标准 Markdown 处理单换行,会把 /status 多行文本折成一行。
  1024. // 飞书通道内把普通单换行转成 hard break,保留业务层给其他 bot 使用的原始文本。
  1025. return `${line.text} `;
  1026. })
  1027. .join("\n");
  1028. }
  1029. function buildFeishuButtonElement(params: {
  1030. text: string;
  1031. type: "default" | "primary";
  1032. command: string;
  1033. originalText: string;
  1034. }): Record<string, unknown> {
  1035. return {
  1036. tag: "button",
  1037. text: {
  1038. tag: "plain_text",
  1039. content: params.text,
  1040. },
  1041. type: params.type,
  1042. // Bugfix: Card JSON 2.0 不再支持旧版 action/actions 容器。
  1043. // 按钮必须直接作为 body.elements 组件,并通过 behaviors.callback 回传业务值,否则飞书会返回 HTTP 400。
  1044. behaviors: [
  1045. {
  1046. type: "callback",
  1047. value: {
  1048. command: params.command,
  1049. zcodeCardText: params.originalText,
  1050. },
  1051. },
  1052. ],
  1053. };
  1054. }
  1055. function buildFeishuInteractiveCardPayloadBody(
  1056. message: BotOutboundMessage,
  1057. ): Record<string, unknown> {
  1058. const selection = message.selection;
  1059. if (selection?.action === "queue.cancel") {
  1060. return {
  1061. schema: "2.0",
  1062. config: { wide_screen_mode: true },
  1063. body: {
  1064. padding: "8px 12px 8px 12px",
  1065. elements: [
  1066. {
  1067. tag: "column_set",
  1068. flex_mode: "none",
  1069. horizontal_spacing: "8px",
  1070. columns: [
  1071. {
  1072. tag: "column",
  1073. width: "weighted",
  1074. weight: 1,
  1075. vertical_align: "center",
  1076. elements: [
  1077. { tag: "markdown", content: formatFeishuCardMarkdownContent(message.text) },
  1078. ],
  1079. },
  1080. {
  1081. tag: "column",
  1082. width: "auto",
  1083. vertical_align: "center",
  1084. elements: selection.options.map((option) =>
  1085. buildFeishuButtonElement({
  1086. text: option.label,
  1087. type: "default",
  1088. command: formatSelectionCommand(selection, option.id),
  1089. originalText: message.text,
  1090. }),
  1091. ),
  1092. },
  1093. ],
  1094. },
  1095. ],
  1096. },
  1097. };
  1098. }
  1099. const elements: Array<Record<string, unknown>> = [
  1100. {
  1101. tag: "markdown",
  1102. content: formatFeishuCardMarkdownContent(message.text),
  1103. },
  1104. ];
  1105. if (selection) {
  1106. elements.push(
  1107. ...selection.options.map((option, index) =>
  1108. buildFeishuButtonElement({
  1109. text: option.label || String(index + 1),
  1110. type: "primary",
  1111. command: formatSelectionCommand(selection, option.id),
  1112. originalText: message.text,
  1113. }),
  1114. ),
  1115. ...(selection.showCancel === false
  1116. ? []
  1117. : [
  1118. buildFeishuButtonElement({
  1119. text:
  1120. selection.cancelLabel ?? formatBotMessage(message.locale, "selectionCancelOption"),
  1121. type: "default",
  1122. // Bugfix: 飞书走结构化选项卡,不应复用微信纯文本菜单的 0 取消语义。
  1123. command: "/cancel",
  1124. originalText: message.text,
  1125. }),
  1126. ]),
  1127. );
  1128. }
  1129. return {
  1130. schema: "2.0",
  1131. config: { wide_screen_mode: true },
  1132. body: { elements },
  1133. };
  1134. }
  1135. function formatFeishuStreamingStatus(state: BotStreamingReplyCardState): string {
  1136. // Bugfix: 流式卡片状态行由 provider 生成,必须读取 BotService 传入的 locale,
  1137. // 否则中文环境里会固定显示 Running/Completed。
  1138. const locale = state.locale;
  1139. const status = state.status;
  1140. if (status === "completed") {
  1141. return formatBotMessage(locale, "streamingStatusCompleted");
  1142. }
  1143. if (status === "error") {
  1144. return formatBotMessage(locale, "streamingStatusFailed");
  1145. }
  1146. return formatBotMessage(locale, "streamingStatusRunning");
  1147. }
  1148. function buildFeishuStreamingToolPanel(
  1149. toolSummaries: readonly string[],
  1150. options: { expanded: boolean; title: string },
  1151. ): Record<string, unknown> | null {
  1152. const summaries = toolSummaries
  1153. .map((summary) => summary.trim())
  1154. .filter((summary) => summary.length > 0);
  1155. if (summaries.length === 0) {
  1156. return null;
  1157. }
  1158. return {
  1159. tag: "collapsible_panel",
  1160. // Bugfix: 流式卡片运行中需要让用户看到当前工具摘要;任务终态后再自动收起,减少最终消息占用空间。
  1161. expanded: options.expanded,
  1162. // Bugfix: Tool summaries 之前只是裸 collapsible panel,和正文没有清晰视觉边界。
  1163. // 飞书 Card JSON 2.0 的折叠面板本身支持背景与边框,这里把它作为 <tools> 容器承载 header/content。
  1164. background_color: "grey-50",
  1165. border: {
  1166. color: "grey",
  1167. corner_radius: "8px",
  1168. },
  1169. padding: "8px 8px 8px 8px",
  1170. header: {
  1171. title: {
  1172. tag: "plain_text",
  1173. content: `🛠️ ${options.title} (${summaries.length})`,
  1174. },
  1175. vertical_align: "center",
  1176. padding: "8px 8px 8px 8px",
  1177. icon: {
  1178. tag: "standard_icon",
  1179. token: "down-small-ccm_outlined",
  1180. color: "grey",
  1181. size: "16px 16px",
  1182. },
  1183. icon_position: "right",
  1184. icon_expanded_angle: -180,
  1185. },
  1186. elements: [
  1187. {
  1188. tag: "markdown",
  1189. content: formatFeishuCardMarkdownContent(summaries.join("\n")),
  1190. },
  1191. ],
  1192. };
  1193. }
  1194. function buildFeishuStreamingCardPayload(
  1195. state: BotStreamingReplyCardState,
  1196. ): Record<string, unknown> {
  1197. const elements: Array<Record<string, unknown>> = [];
  1198. for (const block of state.blocks) {
  1199. if (block.type === "message") {
  1200. const text = block.text.trim();
  1201. if (text) {
  1202. elements.push({
  1203. tag: "markdown",
  1204. content: formatFeishuCardMarkdownContent(text),
  1205. });
  1206. }
  1207. continue;
  1208. }
  1209. const toolPanel = buildFeishuStreamingToolPanel(block.summaries, {
  1210. expanded: block.expanded ?? state.status === "running",
  1211. title: block.title?.trim() || formatBotMessage(state.locale, "streamingToolSummaries"),
  1212. });
  1213. if (toolPanel) {
  1214. elements.push(toolPanel);
  1215. }
  1216. }
  1217. if (elements.length === 0) {
  1218. elements.push({
  1219. tag: "markdown",
  1220. content: " ",
  1221. });
  1222. }
  1223. if (state.status !== "sealed") {
  1224. elements.push({
  1225. tag: "markdown",
  1226. content: formatFeishuCardMarkdownContent(formatFeishuStreamingStatus(state)),
  1227. });
  1228. }
  1229. return {
  1230. schema: "2.0",
  1231. config: { wide_screen_mode: true },
  1232. body: { elements },
  1233. };
  1234. }
  1235. function countTaggedElements(value: unknown): number {
  1236. if (Array.isArray(value)) {
  1237. return value.reduce((total, item) => total + countTaggedElements(item), 0);
  1238. }
  1239. if (!value || typeof value !== "object") {
  1240. return 0;
  1241. }
  1242. const record = value as Record<string, unknown>;
  1243. return (
  1244. (typeof record.tag === "string" ? 1 : 0) +
  1245. Object.values(record).reduce<number>((total, item) => total + countTaggedElements(item), 0)
  1246. );
  1247. }
  1248. export function countFeishuCardTaggedElements(state: BotStreamingReplyCardState): number {
  1249. return countTaggedElements(buildFeishuStreamingCardPayload(state));
  1250. }
  1251. export function splitFeishuStreamingCardStates(
  1252. state: BotStreamingReplyCardState,
  1253. ): BotStreamingReplyCardState[] {
  1254. const blockGroups: BotStreamingReplyCardState["blocks"][] = [];
  1255. let current: BotStreamingReplyCardState["blocks"] = [];
  1256. for (const block of state.blocks) {
  1257. const candidate = [...current, block];
  1258. // 始终为状态行预留预算,使 running/completed 切换不会改变既有分段边界。
  1259. const candidateState = { ...state, blocks: candidate, status: "running" as const };
  1260. if (
  1261. current.length > 0 &&
  1262. countFeishuCardTaggedElements(candidateState) > FEISHU_STREAMING_CARD_TAGGED_ELEMENT_BUDGET
  1263. ) {
  1264. blockGroups.push(current);
  1265. current = [block];
  1266. } else {
  1267. current = candidate;
  1268. }
  1269. }
  1270. blockGroups.push(current);
  1271. return blockGroups.map((blocks, index) => ({
  1272. ...state,
  1273. blocks,
  1274. status: index === blockGroups.length - 1 ? state.status : "sealed",
  1275. }));
  1276. }
  1277. export function splitFeishuText(text: string): string[] {
  1278. const limit = 1900;
  1279. const chunks: string[] = [];
  1280. for (let index = 0; index < text.length; index += limit) {
  1281. chunks.push(text.slice(index, index + limit));
  1282. }
  1283. return chunks.length > 0 ? chunks : [text];
  1284. }
  1285. async function readTenantAccessToken(
  1286. bot: BotConfig,
  1287. deps: FeishuProviderDeps,
  1288. signal?: AbortSignal,
  1289. ): Promise<string | null> {
  1290. if (!bot.feishuAppId || !bot.credentialRef) {
  1291. return null;
  1292. }
  1293. const appSecret = await deps.loadCredential(bot.credentialRef);
  1294. if (!appSecret) {
  1295. return null;
  1296. }
  1297. const cacheKey = `${getFeishuDomainProvider(bot)}:${bot.feishuAppId}:${bot.credentialRef}`;
  1298. const cached = accessTokenCache.get(cacheKey);
  1299. if (cached && cached.expiresAt > Date.now() + 60_000) {
  1300. return cached.token;
  1301. }
  1302. const requestedAt = Date.now();
  1303. const response = await fetchBotProviderJson<FeishuAccessTokenResponse>(
  1304. `${getFeishuBaseUrl(bot)}/open-apis/auth/v3/tenant_access_token/internal`,
  1305. {
  1306. method: "POST",
  1307. headers: { "content-type": "application/json" },
  1308. body: JSON.stringify({
  1309. app_id: bot.feishuAppId,
  1310. app_secret: appSecret,
  1311. }),
  1312. signal,
  1313. },
  1314. );
  1315. if (!response.ok) {
  1316. throw new Error(`Feishu tenant_access_token failed: HTTP ${response.status}`);
  1317. }
  1318. const payload = response.payload ?? {};
  1319. if (payload.code !== 0 || !payload.tenant_access_token) {
  1320. throw new Error(payload.msg || "Feishu tenant_access_token failed.");
  1321. }
  1322. // 飞书可能返回尚未过期的旧令牌;固定缓存 90 分钟会超过其真实剩余有效期。
  1323. // 从请求开始计时,避免网络耗时被错误计入令牌的可用时间。
  1324. if (typeof payload.expire === "number" && Number.isFinite(payload.expire) && payload.expire > 0) {
  1325. accessTokenCache.set(cacheKey, {
  1326. token: payload.tenant_access_token,
  1327. expiresAt: requestedAt + payload.expire * 1_000,
  1328. });
  1329. } else {
  1330. accessTokenCache.delete(cacheKey);
  1331. }
  1332. return payload.tenant_access_token;
  1333. }
  1334. function resolveFeishuReceiveIdType(receiveId: string): "chat_id" | "open_id" {
  1335. return receiveId.startsWith("oc_") ? "chat_id" : "open_id";
  1336. }
  1337. function createFeishuMessageError(
  1338. operation: string,
  1339. status: number,
  1340. payload: FeishuSendMessageResponse | undefined,
  1341. responseLogId?: string,
  1342. receiveIdType?: string,
  1343. ): Error {
  1344. const details = [
  1345. typeof payload?.code === "number" ? `code=${payload.code}` : null,
  1346. payload?.msg ? `msg=${payload.msg}` : null,
  1347. payload?.error?.log_id || responseLogId
  1348. ? `log_id=${payload?.error?.log_id ?? responseLogId}`
  1349. : null,
  1350. receiveIdType ? `receive_id_type=${receiveIdType}` : null,
  1351. ].filter((detail): detail is string => Boolean(detail));
  1352. // 修复原因:飞书的 HTTP 400 会在响应体中携带业务错误码、原因和排查 log_id。
  1353. // 旧实现先按 HTTP 状态抛错,导致这些已解析的信息永久丢失,无法区分权限、限流和卡片错误。
  1354. return Object.assign(
  1355. new Error(
  1356. `Feishu ${operation} failed: HTTP ${status}${details.length > 0 ? `, ${details.join(", ")}` : ""}`,
  1357. ),
  1358. {
  1359. // 无业务回执的服务端错误,以及“正在发送”,都不能证明本次发送未发生。
  1360. deliveryRejected:
  1361. payload?.code !== 230049 &&
  1362. ((typeof payload?.code === "number" && payload.code !== 0) ||
  1363. (status >= 400 && status < 500 && status !== 408)),
  1364. ...(payload?.code === 230011 ? { deliveryReplyUnavailable: true } : {}),
  1365. ...(status === 429 || payload?.code === 230020 || payload?.code === 99991400
  1366. ? { retryAfterMs: 1000 }
  1367. : {}),
  1368. },
  1369. );
  1370. }
  1371. function resolveFeishuReplyTarget(message: BotOutboundMessage) {
  1372. const replyToMessageId =
  1373. message.replyToMessageId || (message.threadId ? message.rootMessageId : undefined);
  1374. // 原因:临时审批/问答卡曾跳过话题路由,直接发到群主聊天;统一解析并拒绝无锚点投递。
  1375. if (message.threadId && !replyToMessageId)
  1376. throw Object.assign(new Error("Topic reply target is unavailable"), {
  1377. deliveryRejected: true,
  1378. });
  1379. return { replyToMessageId, replyInThread: Boolean(message.threadId) };
  1380. }
  1381. async function sendFeishuInteractiveCard(
  1382. bot: BotConfig,
  1383. token: string,
  1384. receiveId: string,
  1385. card: Record<string, unknown>,
  1386. signal?: AbortSignal,
  1387. delivery?: { replyToMessageId?: string; uuid?: string; replyInThread?: boolean },
  1388. ): Promise<string | null> {
  1389. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1390. delivery?.replyToMessageId
  1391. ? `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(delivery.replyToMessageId)}/reply`
  1392. : `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages?receive_id_type=${resolveFeishuReceiveIdType(receiveId)}`,
  1393. {
  1394. method: "POST",
  1395. headers: {
  1396. authorization: `Bearer ${token}`,
  1397. "content-type": "application/json",
  1398. },
  1399. body: JSON.stringify({
  1400. ...(!delivery?.replyToMessageId ? { receive_id: receiveId } : {}),
  1401. ...(delivery?.uuid ? { uuid: delivery.uuid } : {}),
  1402. ...(delivery?.replyInThread ? { reply_in_thread: true } : {}),
  1403. msg_type: "interactive",
  1404. content: JSON.stringify(card),
  1405. }),
  1406. signal,
  1407. },
  1408. );
  1409. const payload = response.payload ?? {};
  1410. // HTTP 成功也可能携带业务拒绝,必须保留错误码和请求 ID。
  1411. if (!response.ok || payload.code !== 0) {
  1412. throw createFeishuMessageError(
  1413. "send interactive message",
  1414. response.status,
  1415. payload,
  1416. response.responseLogId,
  1417. resolveFeishuReceiveIdType(receiveId),
  1418. );
  1419. }
  1420. if ((delivery?.uuid || delivery?.replyToMessageId) && !payload.data?.message_id)
  1421. throw new Error("Feishu delivery outcome is unknown: no message_id");
  1422. return payload.data?.message_id ?? null;
  1423. }
  1424. async function updateFeishuInteractiveMessage(
  1425. bot: BotConfig,
  1426. token: string,
  1427. handle: BotStreamingReplyCardHandle,
  1428. card: Record<string, unknown>,
  1429. signal?: AbortSignal,
  1430. ): Promise<void> {
  1431. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1432. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(handle.providerMessageId)}`,
  1433. {
  1434. method: "PATCH",
  1435. headers: {
  1436. authorization: `Bearer ${token}`,
  1437. "content-type": "application/json",
  1438. },
  1439. body: JSON.stringify({
  1440. msg_type: "interactive",
  1441. content: JSON.stringify(card),
  1442. }),
  1443. signal,
  1444. },
  1445. );
  1446. const payload = response.payload ?? {};
  1447. // HTTP 成功也可能携带业务拒绝,必须保留错误码和请求 ID。
  1448. if (!response.ok || payload.code !== 0) {
  1449. throw createFeishuMessageError(
  1450. "update streaming card",
  1451. response.status,
  1452. payload,
  1453. response.responseLogId,
  1454. );
  1455. }
  1456. }
  1457. async function deleteFeishuInteractiveMessage(
  1458. bot: BotConfig,
  1459. token: string,
  1460. handle: BotTransientInteractionCardHandle,
  1461. ): Promise<void> {
  1462. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  1463. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(handle.providerMessageId)}`,
  1464. {
  1465. method: "DELETE",
  1466. headers: {
  1467. authorization: `Bearer ${token}`,
  1468. },
  1469. },
  1470. );
  1471. if (!response.ok) {
  1472. throw new Error(`Feishu recall interaction card failed: HTTP ${response.status}`);
  1473. }
  1474. const payload = response.payload ?? {};
  1475. if (payload.code !== 0) {
  1476. throw new Error(payload.msg || "Feishu recall interaction card failed.");
  1477. }
  1478. }
  1479. function resolveFeishuAppDisplayName(payload: FeishuAppInfoResponse): string | null {
  1480. const app = payload.data?.app;
  1481. const appName = app?.app_name?.trim();
  1482. if (appName) {
  1483. return appName;
  1484. }
  1485. const primaryLanguage = app?.primary_language?.trim();
  1486. const primaryI18nName = app?.i18n
  1487. ?.find((item) => item.i18n_key === primaryLanguage)
  1488. ?.name?.trim();
  1489. if (primaryI18nName) {
  1490. return primaryI18nName;
  1491. }
  1492. return app?.i18n?.find((item) => item.name?.trim())?.name?.trim() ?? null;
  1493. }
  1494. async function fetchFeishuAppDisplayName(
  1495. bot: BotConfig,
  1496. token: string,
  1497. appId: string,
  1498. ): Promise<string | null> {
  1499. const response = await fetchBotProviderJson<FeishuAppInfoResponse>(
  1500. `${getFeishuBaseUrl(bot)}/open-apis/application/v6/applications/${appId}?lang=zh_cn`,
  1501. {
  1502. headers: {
  1503. authorization: `Bearer ${token}`,
  1504. },
  1505. },
  1506. );
  1507. if (!response.ok) {
  1508. throw new Error(`Feishu get application info failed app=${appId}: HTTP ${response.status}`);
  1509. }
  1510. const payload = response.payload ?? {};
  1511. if (payload.code !== 0) {
  1512. throw new Error(payload.msg || `Feishu get application info failed app=${appId}.`);
  1513. }
  1514. return resolveFeishuAppDisplayName(payload);
  1515. }
  1516. async function readFeishuAppDisplayName(
  1517. bot: BotConfig,
  1518. deps: FeishuProviderDeps,
  1519. ): Promise<string | null> {
  1520. if (!bot.feishuAppId) {
  1521. return null;
  1522. }
  1523. const token = await readTenantAccessToken(bot, deps);
  1524. if (!token) {
  1525. return null;
  1526. }
  1527. let appIdError: unknown;
  1528. try {
  1529. const appName = await fetchFeishuAppDisplayName(bot, token, bot.feishuAppId);
  1530. if (appName?.trim()) {
  1531. return appName;
  1532. }
  1533. } catch (error) {
  1534. appIdError = error;
  1535. }
  1536. try {
  1537. // Bugfix: 飞书 / Lark 扫码创建后 app_id 路径可能因为权限或同步延迟暂不可读;me 路径更适合读取当前应用名称。
  1538. return await fetchFeishuAppDisplayName(bot, token, "me");
  1539. } catch (error) {
  1540. throw appIdError ?? error;
  1541. }
  1542. }
  1543. function resolveFeishuUserIdType(userId: string): "open_id" | "union_id" | "user_id" {
  1544. if (userId.startsWith("ou_")) {
  1545. return "open_id";
  1546. }
  1547. if (userId.startsWith("on_")) {
  1548. return "union_id";
  1549. }
  1550. return "user_id";
  1551. }
  1552. function resolveFeishuUserDisplayName(payload: FeishuUserInfoResponse): string | null {
  1553. const user = payload.data?.user;
  1554. return user?.name?.trim() || user?.en_name?.trim() || user?.nickname?.trim() || null;
  1555. }
  1556. async function readFeishuUserDisplayName(
  1557. bot: BotConfig,
  1558. deps: FeishuProviderDeps,
  1559. userId: string,
  1560. ): Promise<string | null> {
  1561. const trimmedUserId = userId.trim();
  1562. if (!trimmedUserId) {
  1563. return null;
  1564. }
  1565. const cacheKey = `${getFeishuDomainProvider(bot)}:${bot.feishuAppId ?? ""}:${bot.credentialRef ?? ""}:${trimmedUserId}`;
  1566. const cached = userDisplayNameCache.get(cacheKey);
  1567. if (cached && cached.expiresAt > Date.now()) {
  1568. return cached.name;
  1569. }
  1570. const token = await readTenantAccessToken(bot, deps);
  1571. if (!token) {
  1572. return null;
  1573. }
  1574. const userIdType = resolveFeishuUserIdType(trimmedUserId);
  1575. const response = await fetchBotProviderJson<FeishuUserInfoResponse>(
  1576. `${getFeishuBaseUrl(bot)}/open-apis/contact/v3/users/${encodeURIComponent(trimmedUserId)}?user_id_type=${userIdType}`,
  1577. {
  1578. headers: {
  1579. authorization: `Bearer ${token}`,
  1580. },
  1581. },
  1582. );
  1583. if (!response.ok) {
  1584. throw new Error(`Feishu get user info failed user=${trimmedUserId}: HTTP ${response.status}`);
  1585. }
  1586. const payload = response.payload ?? {};
  1587. if (payload.code !== 0) {
  1588. throw new Error(payload.msg || `Feishu get user info failed user=${trimmedUserId}.`);
  1589. }
  1590. const name = resolveFeishuUserDisplayName(payload);
  1591. // Bugfix: 飞书消息事件只稳定携带 sender_id,不携带发送者名称。
  1592. // 这里缓存通讯录查询结果,避免同一个用户连续发消息时每条都请求 contact API。
  1593. userDisplayNameCache.set(cacheKey, {
  1594. name,
  1595. expiresAt: Date.now() + 10 * 60_000,
  1596. });
  1597. return name;
  1598. }
  1599. function getFeishuTypingReactionKey(bot: BotConfig, messageId: string): string {
  1600. return `${bot.id}:${messageId}`;
  1601. }
  1602. async function addFeishuTypingReaction(
  1603. bot: BotConfig,
  1604. deps: FeishuProviderDeps,
  1605. messageId: string,
  1606. ): Promise<void> {
  1607. const token = await readTenantAccessToken(bot, deps);
  1608. if (!token) {
  1609. return;
  1610. }
  1611. const key = getFeishuTypingReactionKey(bot, messageId);
  1612. if (typingReactionIds.has(key)) {
  1613. return;
  1614. }
  1615. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1616. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${messageId}/reactions`,
  1617. {
  1618. method: "POST",
  1619. headers: {
  1620. authorization: `Bearer ${token}`,
  1621. "content-type": "application/json",
  1622. },
  1623. body: JSON.stringify({
  1624. reaction_type: {
  1625. emoji_type: "Typing",
  1626. },
  1627. }),
  1628. },
  1629. );
  1630. if (!response.ok) {
  1631. throw new Error(`Feishu add typing reaction failed: HTTP ${response.status}`);
  1632. }
  1633. const payload = response.payload ?? {};
  1634. if (payload.code !== 0) {
  1635. throw new Error(payload.msg || "Feishu add typing reaction failed.");
  1636. }
  1637. if (payload.data?.reaction_id) {
  1638. typingReactionIds.set(key, payload.data.reaction_id);
  1639. }
  1640. }
  1641. async function deleteFeishuTypingReaction(
  1642. bot: BotConfig,
  1643. deps: FeishuProviderDeps,
  1644. messageId: string,
  1645. ): Promise<void> {
  1646. const key = getFeishuTypingReactionKey(bot, messageId);
  1647. const reactionId = typingReactionIds.get(key);
  1648. if (!reactionId) {
  1649. return;
  1650. }
  1651. const token = await readTenantAccessToken(bot, deps);
  1652. if (!token) {
  1653. return;
  1654. }
  1655. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1656. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${messageId}/reactions/${reactionId}`,
  1657. {
  1658. method: "DELETE",
  1659. headers: {
  1660. authorization: `Bearer ${token}`,
  1661. },
  1662. },
  1663. );
  1664. if (!response.ok) {
  1665. throw new Error(`Feishu delete typing reaction failed: HTTP ${response.status}`);
  1666. }
  1667. const payload = response.payload ?? {};
  1668. if (payload.code !== 0) {
  1669. throw new Error(payload.msg || "Feishu delete typing reaction failed.");
  1670. }
  1671. typingReactionIds.delete(key);
  1672. }
  1673. async function readFeishuAppSecret(
  1674. bot: BotConfig,
  1675. deps: FeishuProviderDeps,
  1676. ): Promise<string | null> {
  1677. if (!bot.feishuAppId || !bot.credentialRef) {
  1678. return null;
  1679. }
  1680. return deps.loadCredential(bot.credentialRef);
  1681. }
  1682. export function createFeishuWebSocketEventHandlers(params: {
  1683. bot: BotConfig;
  1684. onPayload: (payload: unknown) => Promise<BotOutboundMessage | undefined>;
  1685. }) {
  1686. const { bot, onPayload } = params;
  1687. return {
  1688. "im.message.receive_v1": async (payload: unknown) => {
  1689. await onPayload({
  1690. ...(isRecord(payload) ? payload : { payload }),
  1691. botId: bot.id,
  1692. zcodeProvider: bot.provider,
  1693. });
  1694. },
  1695. "im.chat.member.bot.deleted_v1": async (payload: unknown) => {
  1696. await onPayload({
  1697. ...(isRecord(payload) ? payload : {}),
  1698. botId: bot.id,
  1699. zcodeProvider: bot.provider,
  1700. zcodeBotRemoved: true,
  1701. });
  1702. },
  1703. // Bugfix: 我们用 Typing reaction 模拟输入中状态,飞书会把自己创建的 reaction 再推回长连接。
  1704. // 业务不需要处理这个事件,但不注册 handler 时 SDK 会持续打印 warn 干扰排查。
  1705. "im.message.reaction.created_v1": async () => undefined,
  1706. "card.action.trigger": async (payload: unknown) => {
  1707. const responseState = { deferred: false };
  1708. const callbackPayload = {
  1709. ...(isRecord(payload) ? payload : { payload }),
  1710. zcodeFeishuCardResponseState: responseState,
  1711. botId: bot.id,
  1712. zcodeProvider: bot.provider,
  1713. zcodeFeishuSynchronousCardAction: true,
  1714. };
  1715. // 修复原因:飞书点击后的同步响应才是客户端可靠采用的卡片状态。传输层不能再从
  1716. // zcodeCardText 拼简化卡,也不能返回 undefined 后依赖旁路 PATCH;它必须消费业务层
  1717. // 已推进完成的完整 outbound,并用同一份 elicitation 状态生成下一题卡片。
  1718. // 飞书要求三秒内响应。超时只切换卡片投递方式,业务请求仍执行一次。
  1719. let deadline: ReturnType<typeof setTimeout> | undefined;
  1720. const pending = onPayload(callbackPayload);
  1721. const message = await Promise.race([
  1722. pending,
  1723. new Promise<null>((resolve) => {
  1724. deadline = setTimeout(() => {
  1725. responseState.deferred = true;
  1726. resolve(null);
  1727. }, 2000);
  1728. }),
  1729. ]).finally(() => {
  1730. if (deadline) clearTimeout(deadline);
  1731. });
  1732. if (responseState.deferred) return {};
  1733. if (!message) {
  1734. return undefined;
  1735. }
  1736. if (message.callbackToastOnly) return { toast: { type: "error", content: message.text } };
  1737. return {
  1738. card: {
  1739. type: "raw",
  1740. data: message.elicitation
  1741. ? buildFeishuElicitationCardPayload(message)
  1742. : buildFeishuInteractiveCardPayload(message),
  1743. },
  1744. };
  1745. },
  1746. };
  1747. }
  1748. export async function startFeishuBotWebSocket(params: {
  1749. bot: BotConfig;
  1750. deps: FeishuProviderDeps;
  1751. onPayload: (payload: unknown) => Promise<BotOutboundMessage | undefined>;
  1752. signal?: AbortSignal;
  1753. onConnectionStateChange?: (state: "reconnecting" | "connected") => void;
  1754. }): Promise<FeishuWebSocketClient> {
  1755. const { bot, deps, onPayload, signal, onConnectionStateChange } = params;
  1756. const appId = bot.feishuAppId;
  1757. if (!appId || !FEISHU_APP_ID_PATTERN.test(appId)) {
  1758. throw new Error("Invalid Feishu App ID.");
  1759. }
  1760. const appSecret = await readFeishuAppSecret(bot, deps);
  1761. if (!appSecret) {
  1762. throw new Error("Feishu App ID and App Secret are required.");
  1763. }
  1764. if (signal?.aborted) {
  1765. throw new Error("Feishu WebSocket startup aborted.");
  1766. }
  1767. // SDK 全量源码会常驻 Host;只有实际启动长连接才加载,卡片和 HTTP 路径不承担这份开销。
  1768. const Lark = await import("@larksuiteoapi/node-sdk");
  1769. // 加载期间 channel 可能已停用,迟到的模块不能重新创建连接。
  1770. if (signal?.aborted) {
  1771. throw new Error("Feishu WebSocket startup aborted.");
  1772. }
  1773. const eventDispatcher = new Lark.EventDispatcher({});
  1774. eventDispatcher.register(createFeishuWebSocketEventHandlers({ bot, onPayload }));
  1775. return new Promise<FeishuWebSocketClient>((resolve, reject) => {
  1776. let startupSettled = false;
  1777. let lifecycleSettled = false;
  1778. let clientClosed = false;
  1779. let connectionUnavailable = false;
  1780. let startupTimer: ReturnType<typeof setTimeout> | undefined;
  1781. let connectionPoll: ReturnType<typeof setInterval> | undefined;
  1782. let resolveTerminated: (() => void) | undefined;
  1783. let rejectTerminated: ((error: unknown) => void) | undefined;
  1784. const terminated = new Promise<void>((resolveLifecycle, rejectLifecycle) => {
  1785. resolveTerminated = resolveLifecycle;
  1786. rejectTerminated = rejectLifecycle;
  1787. });
  1788. const finishLifecycle = (error?: unknown) => {
  1789. if (lifecycleSettled) return;
  1790. lifecycleSettled = true;
  1791. if (connectionPoll) clearInterval(connectionPoll);
  1792. if (error) {
  1793. rejectTerminated?.(error);
  1794. } else {
  1795. resolveTerminated?.();
  1796. }
  1797. };
  1798. const fail = (error: unknown) => {
  1799. if (startupSettled) return;
  1800. startupSettled = true;
  1801. if (startupTimer) clearTimeout(startupTimer);
  1802. signal?.removeEventListener("abort", handleAbort);
  1803. closeClient();
  1804. reject(error);
  1805. };
  1806. function handleAbort() {
  1807. fail(new Error("Feishu WebSocket startup aborted."));
  1808. }
  1809. function closeClient() {
  1810. if (clientClosed) return;
  1811. clientClosed = true;
  1812. finishLifecycle();
  1813. wsClient.close();
  1814. }
  1815. const wsClient = new Lark.WSClient({
  1816. appId,
  1817. appSecret,
  1818. domain: getFeishuDomainProvider(bot) === "lark" ? Lark.Domain.Lark : Lark.Domain.Feishu,
  1819. loggerLevel: Lark.LoggerLevel.info,
  1820. });
  1821. // 修复原因:当前飞书 SDK 不支持 onReady 回调,start() 也会在连接完成前返回。
  1822. // 必须观察 SDK 持有的真实 WebSocket,避免连接已经 OPEN 后仍触发 20 秒超时并被主动关闭。
  1823. connectionPoll = setInterval(() => {
  1824. const sdkClient = wsClient as unknown as {
  1825. isConnecting?: boolean;
  1826. wsConfig?: {
  1827. getWSInstance?(): { readyState?: number } | null;
  1828. };
  1829. };
  1830. const connected =
  1831. sdkClient.wsConfig?.getWSInstance?.()?.readyState === WEBSOCKET_OPEN_READY_STATE;
  1832. if (!connected) {
  1833. if (!startupSettled || clientClosed) return;
  1834. if (!connectionUnavailable) {
  1835. connectionUnavailable = true;
  1836. onConnectionStateChange?.("reconnecting");
  1837. }
  1838. if (sdkClient.isConnecting === false) {
  1839. const error = new Error("Feishu WebSocket reconnect exhausted.");
  1840. finishLifecycle(error);
  1841. closeClient();
  1842. }
  1843. return;
  1844. }
  1845. if (startupSettled) {
  1846. if (connectionUnavailable) {
  1847. connectionUnavailable = false;
  1848. onConnectionStateChange?.("connected");
  1849. }
  1850. return;
  1851. }
  1852. startupSettled = true;
  1853. if (startupTimer) clearTimeout(startupTimer);
  1854. signal?.removeEventListener("abort", handleAbort);
  1855. resolve({ close: closeClient, terminated });
  1856. }, FEISHU_WEBSOCKET_READY_POLL_MS);
  1857. startupTimer = setTimeout(() => {
  1858. fail(
  1859. new Error(
  1860. `Feishu WebSocket startup timed out after ${FEISHU_WEBSOCKET_START_TIMEOUT_MS}ms.`,
  1861. ),
  1862. );
  1863. }, FEISHU_WEBSOCKET_START_TIMEOUT_MS);
  1864. signal?.addEventListener("abort", handleAbort, { once: true });
  1865. if (signal?.aborted) {
  1866. handleAbort();
  1867. return;
  1868. }
  1869. // 飞书不需要公网回调地址;这里由本机主动建立长连接接收事件,适配家用网络/NAT 环境。
  1870. void wsClient.start({ eventDispatcher }).catch((error: unknown) => {
  1871. if (!startupSettled) {
  1872. fail(error);
  1873. return;
  1874. }
  1875. finishLifecycle(error);
  1876. closeClient();
  1877. });
  1878. });
  1879. }
  1880. export function createFeishuBotProvider(deps: FeishuProviderDeps): BotProviderAdapter {
  1881. const reactionBots = new Map<string, BotConfig>();
  1882. const updateReaction = createGroupInputReactionUpdater(async (key, state) => {
  1883. const [botKey, messageId] = JSON.parse(key) as [string, string];
  1884. const bot = reactionBots.get(botKey)!;
  1885. const token = await readTenantAccessToken(bot, deps);
  1886. if (!token) throw new Error("Feishu reaction credentials unavailable");
  1887. const url = `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(messageId)}/reactions`;
  1888. const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
  1889. const emoji = {
  1890. waiting: "OneSecond",
  1891. working: "OnIt",
  1892. done: "CheckMark",
  1893. failed: "CrossMark",
  1894. cancelled: null,
  1895. }[state];
  1896. const ownedTypes = new Set(["OK", "OneSecond", "OnIt", "CheckMark", "CrossMark"]);
  1897. const obsolete: string[] = [];
  1898. let found = false;
  1899. let cursor = "";
  1900. const cursors = new Set<string>();
  1901. do {
  1902. if (cursors.has(cursor)) throw new Error("Feishu reaction pagination repeated");
  1903. cursors.add(cursor);
  1904. const response = await fetchBotProviderJson<{
  1905. code?: number;
  1906. msg?: string;
  1907. data?: {
  1908. has_more?: boolean;
  1909. page_token?: string;
  1910. items?: Array<{
  1911. reaction_id: string;
  1912. operator?: { operator_type?: string; operator_id?: string };
  1913. reaction_type?: { emoji_type?: string };
  1914. }>;
  1915. };
  1916. }>(`${url}?page_size=50${cursor ? `&page_token=${encodeURIComponent(cursor)}` : ""}`, {
  1917. method: "GET",
  1918. headers,
  1919. });
  1920. if (!response.ok || response.payload?.code !== 0)
  1921. throw new Error(response.payload?.msg || "Feishu list reactions failed");
  1922. for (const item of response.payload.data?.items ?? []) {
  1923. // 重启后从平台核对本应用状态,绝不删除群成员或其他机器人的表情。
  1924. if (
  1925. item.operator?.operator_type !== "app" ||
  1926. item.operator.operator_id !== bot.feishuAppId ||
  1927. !ownedTypes.has(item.reaction_type?.emoji_type ?? "")
  1928. )
  1929. continue;
  1930. if (item.reaction_type?.emoji_type === emoji && !found) found = true;
  1931. else obsolete.push(item.reaction_id);
  1932. }
  1933. cursor = response.payload.data?.has_more ? (response.payload.data.page_token ?? "") : "";
  1934. if (response.payload.data?.has_more && !cursor)
  1935. throw new Error("Feishu reaction cursor missing");
  1936. } while (cursor);
  1937. for (const id of obsolete) {
  1938. const response = await fetchBotProviderJson<FeishuReactionResponse>(
  1939. `${url}/${encodeURIComponent(id)}`,
  1940. { method: "DELETE", headers },
  1941. );
  1942. if (!response.ok || response.payload?.code !== 0)
  1943. throw new Error(response.payload?.msg || "Feishu delete status reaction failed");
  1944. }
  1945. if (emoji && !found) {
  1946. const response = await fetchBotProviderJson<FeishuReactionResponse>(url, {
  1947. method: "POST",
  1948. headers,
  1949. body: JSON.stringify({ reaction_type: { emoji_type: emoji } }),
  1950. });
  1951. if (!response.ok || response.payload?.code !== 0)
  1952. throw new Error(response.payload?.msg || "Feishu add status reaction failed");
  1953. }
  1954. });
  1955. const readDirectory = createGroupMemberDirectory();
  1956. const getGroupMemberNames = (bot: BotConfig, chatId: string) => {
  1957. const key = JSON.stringify([
  1958. getFeishuDomainProvider(bot),
  1959. bot.id,
  1960. bot.feishuAppId,
  1961. bot.credentialRef,
  1962. chatId,
  1963. ]);
  1964. return readDirectory(key, async (cursor) => {
  1965. const token = await readTenantAccessToken(bot, deps);
  1966. if (!token) throw new Error("Feishu credentials are unavailable");
  1967. const query = new URLSearchParams({ member_id_type: "open_id", page_size: "100" });
  1968. if (cursor) query.set("page_token", cursor);
  1969. const response = await fetchBotProviderJson<{
  1970. code?: number;
  1971. msg?: string;
  1972. data?: GroupMemberPage;
  1973. }>(
  1974. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}/members?${query}`,
  1975. { headers: { authorization: `Bearer ${token}` } },
  1976. );
  1977. if (!response.ok || response.payload?.code !== 0 || !response.payload.data)
  1978. throw new Error(response.payload?.msg || "Cannot read group members");
  1979. return response.payload.data;
  1980. });
  1981. };
  1982. async function trackDelivery<T>(
  1983. bot: BotConfig,
  1984. signal: AbortSignal | undefined,
  1985. write: () => Promise<T>,
  1986. ): Promise<T> {
  1987. try {
  1988. const result = await write();
  1989. if (!signal?.aborted) deps.onDeliveryResult?.(bot, undefined);
  1990. return result;
  1991. } catch (error) {
  1992. // 主动取消不代表飞书拒绝投递,也不能覆盖已有诊断;任务超时仍由 watcher 处理。
  1993. if (!signal?.aborted)
  1994. deps.onDeliveryResult?.(bot, error instanceof Error ? error.message : String(error));
  1995. throw error;
  1996. }
  1997. }
  1998. const sendCard = (...args: Parameters<typeof sendFeishuInteractiveCard>) =>
  1999. trackDelivery(args[0], args[4], () => sendFeishuInteractiveCard(...args));
  2000. const updateCard = (...args: Parameters<typeof updateFeishuInteractiveMessage>) =>
  2001. trackDelivery(args[0], args[4], () => updateFeishuInteractiveMessage(...args));
  2002. const sendReplyCard = async (
  2003. bot: BotConfig,
  2004. token: string,
  2005. message: BotOutboundMessage,
  2006. card: Record<string, unknown>,
  2007. uuid?: string,
  2008. ): Promise<string | null> => {
  2009. let target = message;
  2010. for (;;) {
  2011. try {
  2012. return await sendCard(bot, token, message.providerUserId, card, undefined, {
  2013. ...resolveFeishuReplyTarget(target),
  2014. ...(uuid ? { uuid } : {}),
  2015. });
  2016. } catch (error) {
  2017. const details = error as {
  2018. deliveryRejected?: boolean;
  2019. deliveryReplyUnavailable?: boolean;
  2020. } | null;
  2021. // 持久化结果由 delivery owner 记录降级目标;这里只处理命令和临时卡。
  2022. if (
  2023. message.deliveryId ||
  2024. !message.providerUserId.startsWith("oc_") ||
  2025. !details?.deliveryRejected ||
  2026. !details.deliveryReplyUnavailable
  2027. )
  2028. throw error;
  2029. const fallback = getUnavailableReplyFallback(target);
  2030. if (!fallback) throw error;
  2031. target = { ...target, ...fallback };
  2032. }
  2033. }
  2034. };
  2035. const botOpenIds = new Map<string, string>();
  2036. return {
  2037. getGroupMemberNames,
  2038. async resolveTopic(bot, actor) {
  2039. const token = await readTenantAccessToken(bot, deps);
  2040. if (!token || !actor.chatId || !actor.providerMessageId)
  2041. throw new Error("Topic identity unavailable");
  2042. const get = async (id: string) => {
  2043. const response = await fetchBotProviderJson<{
  2044. code?: number;
  2045. data?: { items?: Array<Record<string, unknown>> };
  2046. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(id)}`, {
  2047. headers: { authorization: `Bearer ${token}` },
  2048. });
  2049. const item = response.payload?.data?.items?.find((entry) => entry.message_id === id);
  2050. if (!response.ok || response.payload?.code !== 0 || !item || item.chat_id !== actor.chatId)
  2051. throw new Error("Topic message scope could not be verified");
  2052. return item;
  2053. };
  2054. const message = await get(actor.providerMessageId);
  2055. const threadId = readString(message, "thread_id");
  2056. if (!threadId || (actor.threadId && actor.threadId !== threadId))
  2057. throw new Error("Topic scope mismatch");
  2058. const rootMessageId = readString(message, "root_id") || actor.providerMessageId;
  2059. const root = rootMessageId === actor.providerMessageId ? message : await get(rootMessageId);
  2060. if (root.thread_id !== threadId) throw new Error("Topic root scope mismatch");
  2061. const body = isRecord(root.body) ? root.body : null;
  2062. const content = parseJsonRecord(readString(body, "content"));
  2063. const title = readString(content, "text") || readFeishuPostText(content) || threadId;
  2064. const position = root.thread_message_position;
  2065. const topicUrl =
  2066. (typeof position === "number" || typeof position === "string") &&
  2067. /^\d+$/.test(String(position))
  2068. ? `https://${bot.provider === "lark" ? "applink.larksuite.com" : "applink.feishu.cn"}/client/thread/open?${new URLSearchParams(
  2069. {
  2070. openthreadid: threadId,
  2071. openchatid: actor.chatId,
  2072. open_thread_id: threadId,
  2073. open_chat_id: actor.chatId,
  2074. thread_position: String(position),
  2075. },
  2076. )}`
  2077. : undefined;
  2078. return {
  2079. threadId,
  2080. rootMessageId,
  2081. topicTitle: title.replace(/\s+/gu, " ").slice(0, 80),
  2082. ...(topicUrl ? { topicUrl } : {}),
  2083. };
  2084. },
  2085. async readTopicResourceMessage(bot, target, signal) {
  2086. signal?.throwIfAborted();
  2087. const token = await readTenantAccessToken(bot, deps, signal);
  2088. if (!token) throw new Error("Feishu credentials unavailable");
  2089. const response = await fetchBotProviderJson<{
  2090. code?: number;
  2091. data?: { items?: Array<Record<string, unknown>> };
  2092. }>(
  2093. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(target.messageId)}`,
  2094. {
  2095. headers: { authorization: `Bearer ${token}` },
  2096. signal,
  2097. },
  2098. );
  2099. const native = response.payload?.data?.items?.find(
  2100. (item) => item.message_id === target.messageId,
  2101. );
  2102. if (
  2103. !response.ok ||
  2104. response.payload?.code !== 0 ||
  2105. !native ||
  2106. native.deleted === true ||
  2107. native.chat_id !== target.chatId ||
  2108. native.thread_id !== target.threadId
  2109. )
  2110. throw new Error("Archived resource must be readable in the same topic");
  2111. const body = isRecord(native.body) ? native.body : null;
  2112. const content = parseJsonRecord(readString(body, "content"));
  2113. const kind = readString(native, "msg_type");
  2114. const attachments: BotInboundAttachment[] = [];
  2115. const add = (attachment: BotInboundAttachment | null | undefined) => {
  2116. if (!attachment) throw new Error("Archived resource metadata unavailable");
  2117. attachments.push({
  2118. ...attachment,
  2119. providerMetadata: { resourceMessageId: target.messageId },
  2120. });
  2121. };
  2122. if (kind === "file" || kind === "image") add(readFeishuAttachment(kind, content));
  2123. else if (kind === "post") {
  2124. const visit = (value: unknown): void => {
  2125. if (Array.isArray(value)) {
  2126. value.forEach(visit);
  2127. return;
  2128. }
  2129. if (!isRecord(value)) return;
  2130. if (value.tag === "img") add(readFeishuAttachment("image", value));
  2131. else Object.values(value).forEach(visit);
  2132. };
  2133. visit(content);
  2134. }
  2135. if (!attachments.length) throw new Error("Archived message has no supported resources");
  2136. return { ...target, attachments };
  2137. },
  2138. async readTopicHistory(bot, request) {
  2139. const token = await readTenantAccessToken(bot, deps);
  2140. if (!token) throw new Error("Feishu credentials unavailable");
  2141. const read = async (suffix: string) => {
  2142. const response = await fetchBotProviderJson<{
  2143. code?: number;
  2144. msg?: string;
  2145. data?: { items?: unknown[]; has_more?: boolean; page_token?: string };
  2146. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages${suffix}`, {
  2147. headers: { authorization: `Bearer ${token}` },
  2148. });
  2149. if (!response.ok || response.payload?.code !== 0) {
  2150. const message = response.payload?.msg || "Topic history unavailable";
  2151. if (response.payload?.code === 99991672 || message.includes("im:message.group_msg"))
  2152. throw new TopicHistoryPermissionError(message);
  2153. throw new Error(message);
  2154. }
  2155. return response.payload.data;
  2156. };
  2157. const readHistoryAttachments = (kind: string, content: Record<string, unknown> | null) => {
  2158. const items: Array<{ name: string; kind: string }> = [];
  2159. const add = (type: "image" | "file", value: Record<string, unknown> | null) => {
  2160. const attachment = readFeishuAttachment(type, value);
  2161. if (attachment) items.push({ name: attachment.filename, kind: type });
  2162. };
  2163. if (kind === "image" || kind === "file") add(kind, content);
  2164. else if (kind === "post") {
  2165. const visit = (value: unknown): void => {
  2166. if (Array.isArray(value)) {
  2167. value.forEach(visit);
  2168. return;
  2169. }
  2170. if (!isRecord(value)) return;
  2171. if (value.tag === "img") add("image", value);
  2172. else Object.values(value).forEach(visit);
  2173. };
  2174. visit(content);
  2175. }
  2176. return items;
  2177. };
  2178. const rawMessages = new Map<string, unknown>();
  2179. const normalize = async (raw: unknown, expandCard = false) => {
  2180. if (!isRecord(raw)) throw new Error("Invalid topic history message");
  2181. const sender = isRecord(raw.sender) ? raw.sender : null;
  2182. const body = isRecord(raw.body) ? raw.body : null;
  2183. let content = parseJsonRecord(readString(body, "content"));
  2184. const kind = readString(raw, "msg_type");
  2185. if (
  2186. expandCard &&
  2187. kind === "interactive" &&
  2188. readString(sender, "sender_type") === "app" &&
  2189. !isRecord(content?.body)
  2190. ) {
  2191. // 历史接口也会返回升级客户端占位图,不能据此把操作卡片误判为普通回复。
  2192. const data = await read(
  2193. `/${encodeURIComponent(readString(raw, "message_id"))}?card_msg_content_type=user_card_content`,
  2194. );
  2195. const native = data?.items?.find(
  2196. (item) => isRecord(item) && item.message_id === readString(raw, "message_id"),
  2197. );
  2198. if (
  2199. !isRecord(native) ||
  2200. native.chat_id !== raw.chat_id ||
  2201. native.thread_id !== raw.thread_id
  2202. )
  2203. throw new Error("History card scope unavailable");
  2204. content = parseJsonRecord(isRecord(native.body) ? native.body.content : undefined);
  2205. if (!content) throw new Error("History card content unavailable");
  2206. }
  2207. rawMessages.set(readString(raw, "message_id"), raw);
  2208. return botTopicMessageSchema.parse({
  2209. id: readString(raw, "message_id"),
  2210. chatId: readString(raw, "chat_id"),
  2211. threadId: readString(raw, "thread_id"),
  2212. senderId: readString(sender, "id"),
  2213. senderType: readString(sender, "sender_type"),
  2214. senderName: readString(sender, "name") || undefined,
  2215. parentId: readString(raw, "parent_id") || undefined,
  2216. attachments: readHistoryAttachments(kind, content),
  2217. createdAt: Number(readString(raw, "create_time")),
  2218. kind,
  2219. ...(kind === "interactive" ? { controlCard: isGroupControlCard(content) } : {}),
  2220. text:
  2221. kind === "interactive"
  2222. ? readGroupCardText(content)
  2223. : kind === "text"
  2224. ? readString(content, "text")
  2225. : kind === "post"
  2226. ? readFeishuPostText(content)
  2227. : `[${kind}${readString(content, "file_name") ? `: ${readString(content, "file_name")}` : ""}]`,
  2228. deleted: raw.deleted === true,
  2229. });
  2230. };
  2231. const history = await readTopicHistory(request, {
  2232. list: async (page) => {
  2233. const query = new URLSearchParams({
  2234. container_id_type: "thread",
  2235. container_id: request.threadId,
  2236. sort_type: "ByCreateTimeDesc",
  2237. page_size: "50",
  2238. ...(page ? { page_token: page } : {}),
  2239. });
  2240. const data = await read(`?${query}`);
  2241. if (!Array.isArray(data?.items)) throw new Error("Topic history page unavailable");
  2242. if (data.has_more && !data.page_token)
  2243. throw new Error("Topic history cursor unavailable");
  2244. return {
  2245. messages: await Promise.all(data.items.map((raw) => normalize(raw))),
  2246. next: data.has_more ? data.page_token : undefined,
  2247. };
  2248. },
  2249. // 由历史读取器先确定窗口,正文展开不再作用于整页消息。
  2250. hydrate: (message) => normalize(rawMessages.get(message.id), true),
  2251. get: async (id) => {
  2252. const data = await read(`/${encodeURIComponent(id)}`);
  2253. const raw = data?.items?.find((item) => isRecord(item) && item.message_id === id);
  2254. return normalize(raw);
  2255. },
  2256. });
  2257. if (history.messages.length) {
  2258. const names = await getGroupMemberNames(bot, request.chatId).catch(
  2259. () => ({}) as Record<string, string>,
  2260. );
  2261. history.messages = history.messages.map((message) => ({
  2262. ...message,
  2263. senderName: names[message.senderId] || message.senderName,
  2264. }));
  2265. }
  2266. return history;
  2267. },
  2268. async getGroupInfo(bot, chatId) {
  2269. const token = await readTenantAccessToken(bot, deps);
  2270. if (!token) throw new Error("Feishu credentials are unavailable");
  2271. const response = await fetchBotProviderJson<{
  2272. code?: number;
  2273. msg?: string;
  2274. data?: { name?: string; chat_mode?: string };
  2275. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/chats/${encodeURIComponent(chatId)}`, {
  2276. headers: { authorization: `Bearer ${token}` },
  2277. });
  2278. if (!response.ok || response.payload?.code !== 0)
  2279. throw new Error(response.payload?.msg || "Cannot read group information");
  2280. return {
  2281. name: response.payload.data?.name || chatId,
  2282. chatMode: response.payload.data?.chat_mode === "topic" ? "topic" : "group",
  2283. };
  2284. },
  2285. async prepareCallbackPayload(bot, payload) {
  2286. if (!isRecord(payload)) return payload;
  2287. const event = isRecord(payload.event) ? payload.event : payload;
  2288. const action = isRecord(event.action) ? event.action : null;
  2289. const actionValue = isRecord(action?.value) ? action.value : null;
  2290. const behavior = Array.isArray(action?.behaviors) ? action.behaviors.find(isRecord) : null;
  2291. const behaviorValue = isRecord(behavior?.value) ? behavior.value : null;
  2292. const card = botGroupCardSchema.safeParse(actionValue?.groupCard ?? behaviorValue?.groupCard);
  2293. if (card.success) {
  2294. const context = isRecord(event.context) ? event.context : null;
  2295. const chatId = readString(context, "open_chat_id") || readString(context, "chat_id");
  2296. const cardId = readString(context, "open_message_id") || readString(context, "message_id");
  2297. // 卡片回调只有短响应窗口,位置验证与 token 请求共用同一 deadline。
  2298. const signal = AbortSignal.timeout(1500);
  2299. const token = await readTenantAccessToken(bot, deps, signal);
  2300. signal.throwIfAborted();
  2301. if (!token || !cardId || chatId !== card.data.chatId)
  2302. throw new Error("Card scope unavailable");
  2303. const response = await fetchBotProviderJson<{
  2304. code?: number;
  2305. data?: { items?: Array<Record<string, unknown>> };
  2306. }>(`${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(cardId)}`, {
  2307. headers: { authorization: `Bearer ${token}` },
  2308. signal,
  2309. });
  2310. const native = response.payload?.data?.items?.find((item) => item.message_id === cardId);
  2311. // 按钮参数不是原生位置真源;必须验证卡片实际所在的话题。
  2312. if (
  2313. !response.ok ||
  2314. response.payload?.code !== 0 ||
  2315. native?.chat_id !== chatId ||
  2316. (readString(native ?? null, "thread_id") || undefined) !== card.data.threadId
  2317. )
  2318. throw new Error("Card topic scope mismatch");
  2319. return payload;
  2320. }
  2321. const message = isRecord(event.message) ? event.message : null;
  2322. if (readString(message, "chat_type") !== "group") return payload;
  2323. const messageSender = isRecord(event.sender) ? event.sender : null;
  2324. if (
  2325. isFeishuBotSender(readString(messageSender, "sender_type")) &&
  2326. (readString(message, "message_type") || readString(message, "msg_type")) ===
  2327. "interactive" &&
  2328. isGroupControlCard(parseJsonRecord(message?.content))
  2329. )
  2330. return payload;
  2331. const identityKey = `${bot.provider}:${bot.feishuAppId}`;
  2332. let openId = botOpenIds.get(identityKey);
  2333. if (!openId) {
  2334. const token = await readTenantAccessToken(bot, deps);
  2335. if (!token) throw new Error("Feishu credentials are unavailable");
  2336. const response = await fetchBotProviderJson<{
  2337. code?: number;
  2338. msg?: string;
  2339. bot?: { open_id?: string };
  2340. }>(`${getFeishuBaseUrl(bot)}/open-apis/bot/v3/info`, {
  2341. headers: { authorization: `Bearer ${token}` },
  2342. });
  2343. openId = response.payload?.bot?.open_id;
  2344. if (!response.ok || response.payload?.code !== 0 || !openId)
  2345. throw new Error(response.payload?.msg || "Cannot resolve Feishu bot identity");
  2346. botOpenIds.set(identityKey, openId);
  2347. }
  2348. let nativeCardContent: Record<string, unknown> | undefined;
  2349. if (
  2350. isFeishuBotSender(readString(messageSender, "sender_type")) &&
  2351. (readString(message, "message_type") || readString(message, "msg_type")) === "interactive"
  2352. ) {
  2353. const currentContent = parseJsonRecord(message?.content);
  2354. // 默认事件/历史内容可能只是升级客户端占位图;先读取真实正文再分类。
  2355. if (!isRecord(currentContent?.body)) {
  2356. const token = await readTenantAccessToken(bot, deps);
  2357. if (!token) throw new Error("Card credentials unavailable");
  2358. const response = await fetchBotProviderJson<{
  2359. code?: number;
  2360. data?: {
  2361. items?: Array<{
  2362. message_id?: string;
  2363. chat_id?: string;
  2364. thread_id?: string;
  2365. body?: { content?: string };
  2366. }>;
  2367. };
  2368. }>(
  2369. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(readString(message, "message_id"))}?card_msg_content_type=user_card_content`,
  2370. { headers: { authorization: `Bearer ${token}` } },
  2371. );
  2372. const native = response.payload?.data?.items?.[0];
  2373. if (
  2374. !response.ok ||
  2375. response.payload?.code !== 0 ||
  2376. native?.message_id !== readString(message, "message_id") ||
  2377. native.chat_id !== readString(message, "chat_id") ||
  2378. (native.thread_id || "") !== readString(message, "thread_id")
  2379. )
  2380. throw new Error("Card message scope unavailable");
  2381. nativeCardContent = parseJsonRecord(native.body?.content) ?? undefined;
  2382. if (!nativeCardContent) throw new Error("Card content unavailable");
  2383. }
  2384. }
  2385. const sender = isRecord(event.sender) ? event.sender : null;
  2386. const parentId = readString(message, "parent_id");
  2387. const rootId = readString(message, "root_id");
  2388. let topicRootIsCurrentBot = false;
  2389. let referencedAttachment: BotInboundAttachment | undefined;
  2390. let referencedMessage: BotInboundMessage["referencedMessage"];
  2391. const referencedInlineImages: Array<{ imageKey: string; messageId: string }> = [];
  2392. if (
  2393. parentId &&
  2394. (readString(sender, "sender_type") === "user" ||
  2395. (isFeishuBotSender(readString(sender, "sender_type")) &&
  2396. readString(isRecord(sender?.sender_id) ? sender.sender_id : null, "open_id") !==
  2397. openId)) &&
  2398. !(
  2399. payload.zcodeTopicHasAcceptedInput === true &&
  2400. parentId === rootId &&
  2401. !isFeishuBotSender(readString(sender, "sender_type"))
  2402. ) &&
  2403. (Boolean(readString(message, "thread_id")) ||
  2404. readGroupMentionText(
  2405. "",
  2406. message?.mentions,
  2407. openId,
  2408. readString(sender, "sender_type"),
  2409. readString(isRecord(sender?.sender_id) ? sender.sender_id : null, "open_id"),
  2410. ) !== null)
  2411. ) {
  2412. const token = await readTenantAccessToken(bot, deps);
  2413. const response = await fetchBotProviderJson<{
  2414. code?: number;
  2415. msg?: string;
  2416. data?: {
  2417. items?: Array<{
  2418. message_id?: string;
  2419. chat_id?: string;
  2420. thread_id?: string;
  2421. msg_type?: string;
  2422. deleted?: boolean;
  2423. create_time?: string;
  2424. sender?: { id?: string; id_type?: string; sender_type?: string };
  2425. body?: { content?: string };
  2426. }>;
  2427. };
  2428. }>(
  2429. // 默认卡片响应仅含“升级客户端”占位文案;必须请求真实卡片正文供引用解析。
  2430. `${getFeishuBaseUrl(bot)}/open-apis/im/v1/messages/${encodeURIComponent(parentId)}?card_msg_content_type=user_card_content`,
  2431. { headers: { authorization: `Bearer ${token}` } },
  2432. );
  2433. const referenced = response.payload?.data?.items?.[0];
  2434. if (
  2435. !response.ok ||
  2436. response.payload?.code !== 0 ||
  2437. referenced?.message_id !== parentId ||
  2438. referenced.chat_id !== readString(message, "chat_id") ||
  2439. referenced.deleted
  2440. )
  2441. throw new Error("Referenced attachment must be readable in the same group");
  2442. // 引用消息可来自同群另一个话题,不能只用 chat_id 证明附件归属。
  2443. if (
  2444. (referenced.thread_id || undefined) !== (readString(message, "thread_id") || undefined) &&
  2445. !(parentId === rootId && !referenced.thread_id)
  2446. )
  2447. throw new Error("Referenced attachment must be readable in the same topic");
  2448. topicRootIsCurrentBot =
  2449. parentId === rootId &&
  2450. referenced.sender?.sender_type === "app" &&
  2451. ((referenced.sender.id_type === "app_id" && referenced.sender.id === bot.feishuAppId) ||
  2452. (referenced.sender.id_type === "open_id" && referenced.sender.id === openId));
  2453. if (!["text", "post", "image", "file", "interactive"].includes(referenced.msg_type ?? "")) {
  2454. throw new Error("Referenced message type is unsupported");
  2455. }
  2456. if (referenced.msg_type === "interactive") {
  2457. // 确认文字没有专用事件类型,须通过可信 parent 消息识别,不能依赖翻译文案。
  2458. if (
  2459. isFeishuBotSender(readString(sender, "sender_type")) &&
  2460. isFeishuBotSender(referenced.sender?.sender_type ?? "") &&
  2461. isGroupControlCard(parseJsonRecord(referenced.body?.content))
  2462. )
  2463. return { ...payload, zcodeIgnoreInteractionMessage: true };
  2464. const text = readGroupCardText(parseJsonRecord(referenced.body?.content));
  2465. if (!text) throw new Error("Referenced message has no readable text");
  2466. referencedMessage = { messageId: parentId, text };
  2467. }
  2468. // 文字引用此前只做权限检查后丢弃,导致仅 @ 被误判为空消息。
  2469. if (referenced.msg_type === "text" || referenced.msg_type === "post") {
  2470. const body = parseJsonRecord(referenced.body?.content);
  2471. const quotedText =
  2472. referenced.msg_type === "text" ? readString(body, "text") : readFeishuPostText(body);
  2473. if (referenced.msg_type === "post") {
  2474. const visit = (value: unknown): void => {
  2475. if (Array.isArray(value)) {
  2476. value.forEach(visit);
  2477. return;
  2478. }
  2479. if (!isRecord(value)) return;
  2480. if (value.tag === "img") {
  2481. const image = readFeishuAttachment("image", value);
  2482. if (!image?.providerFileId) throw new Error("Referenced image is invalid");
  2483. referencedInlineImages.push({
  2484. imageKey: image.providerFileId,
  2485. messageId: parentId,
  2486. });
  2487. }
  2488. visit(value.content ?? value.children ?? value.elements);
  2489. };
  2490. if (body) visit(readFeishuPostLocaleContent(body));
  2491. }
  2492. if (!quotedText.trim() && !referencedInlineImages.length)
  2493. throw new Error("Referenced message is empty or unavailable");
  2494. referencedMessage = { messageId: parentId, text: quotedText };
  2495. }
  2496. if (referencedMessage) {
  2497. const senderId = referenced.sender?.id;
  2498. const names = senderId
  2499. ? await getGroupMemberNames(bot, referenced.chat_id!).catch(
  2500. () => ({}) as Record<string, string>,
  2501. )
  2502. : {};
  2503. const sentAt = Number(referenced.create_time);
  2504. referencedMessage = {
  2505. ...referencedMessage,
  2506. ...(senderId
  2507. ? {
  2508. senderId,
  2509. senderName:
  2510. names[senderId] ||
  2511. (senderId === openId ||
  2512. (referenced.sender?.sender_type === "app" && senderId === bot.feishuAppId)
  2513. ? bot.name
  2514. : undefined),
  2515. }
  2516. : {}),
  2517. ...(Number.isFinite(sentAt) && sentAt > 0
  2518. ? { sentAt: new Date(sentAt).toISOString() }
  2519. : {}),
  2520. };
  2521. }
  2522. if (referenced.msg_type === "image" || referenced.msg_type === "file") {
  2523. const attachment = readFeishuAttachment(
  2524. referenced.msg_type,
  2525. parseJsonRecord(referenced.body?.content),
  2526. );
  2527. if (!attachment) throw new Error("Referenced attachment is invalid");
  2528. referencedAttachment = {
  2529. ...attachment,
  2530. providerMetadata: { resourceMessageId: parentId },
  2531. };
  2532. }
  2533. }
  2534. return {
  2535. ...payload,
  2536. zcodeBotOpenId: openId,
  2537. ...(nativeCardContent ? { zcodeNativeCardContent: nativeCardContent } : {}),
  2538. zcodeTopicRootIsCurrentBot: topicRootIsCurrentBot,
  2539. zcodeReferencedAttachment: referencedAttachment,
  2540. zcodeReferencedMessage: referencedMessage,
  2541. zcodeReferencedInlineImages: referencedInlineImages,
  2542. };
  2543. },
  2544. splitStreamingReplyCardStates: splitFeishuStreamingCardStates,
  2545. async test(bot) {
  2546. if (!bot.enabled) {
  2547. return { ok: false, message: "Feishu bot is disabled." };
  2548. }
  2549. if (!bot.feishuAppId || !bot.credentialRef) {
  2550. return {
  2551. ok: false,
  2552. message: "Feishu App ID and App Secret are required.",
  2553. };
  2554. }
  2555. const token = await readTenantAccessToken(bot, deps);
  2556. return token
  2557. ? { ok: true, message: "Feishu app credentials are valid." }
  2558. : { ok: false, message: "Feishu app credentials are missing." };
  2559. },
  2560. async resolveName(bot) {
  2561. // Bugfix: Feishu 创建向导以前只能使用手填/默认名称,容易和真实机器人名称不一致。
  2562. // 飞书机器人能力挂在自建应用上,这里读取应用信息中的名称作为 bot 展示名。
  2563. return readFeishuAppDisplayName(bot, deps);
  2564. },
  2565. async resolveActorDisplayName(bot, actor) {
  2566. // 群事件不保证携带姓名;群成员接口避免依赖组织通讯录可见范围。
  2567. if (actor.chatType === "group") {
  2568. if (!actor.chatId) return null;
  2569. return (await getGroupMemberNames(bot, actor.chatId))[actor.providerUserId] ?? null;
  2570. }
  2571. return readFeishuUserDisplayName(bot, deps, actor.providerUserId);
  2572. },
  2573. async send(bot, message) {
  2574. resolveFeishuReplyTarget(message);
  2575. if (message.contentParts) {
  2576. const parts = channelContentPartsSchema.parse(message.contentParts);
  2577. if (
  2578. message.selection ||
  2579. !message.providerUserId.startsWith("oc_") ||
  2580. parts.some((part) => part.type === "channelMention" && part.channel !== bot.provider) ||
  2581. channelContentText(parts) !== message.text ||
  2582. message.text.length > 2000
  2583. )
  2584. throw Object.assign(new Error("Invalid native channel reply"), {
  2585. deliveryRejected: true,
  2586. });
  2587. }
  2588. const token = await readTenantAccessToken(bot, deps);
  2589. if (!token) {
  2590. if (message.deliveryId)
  2591. throw Object.assign(new Error("Feishu credentials unavailable"), {
  2592. deliveryRejected: true,
  2593. });
  2594. return;
  2595. }
  2596. if (message.selection) {
  2597. const providerMessageId = await sendReplyCard(
  2598. bot,
  2599. token,
  2600. message,
  2601. message.elicitation
  2602. ? buildFeishuElicitationCardPayload(message)
  2603. : buildFeishuInteractiveCardPayload(message),
  2604. );
  2605. return message.selection.action === "queue.cancel" && providerMessageId
  2606. ? { providerMessageId }
  2607. : undefined;
  2608. }
  2609. let partIndex = 0;
  2610. let providerMessageId: string | null = null;
  2611. for (const text of splitFeishuText(message.text)) {
  2612. // Bugfix: Feishu 普通文本消息会把 Markdown 原样展示,和 Telegram 的 Markdown 回复不一致。
  2613. // 改用交互卡片的 markdown 元素承载普通回复,选择消息也继续复用同一套卡片结构。
  2614. providerMessageId = await sendReplyCard(
  2615. bot,
  2616. token,
  2617. message,
  2618. buildFeishuInteractiveCardPayload({
  2619. ...message,
  2620. text,
  2621. mentionedUserIds: partIndex === 0 ? message.mentionedUserIds : undefined,
  2622. selection: undefined,
  2623. }),
  2624. message.deliveryId ? `${message.deliveryId.slice(0, 40)}-${partIndex}` : undefined,
  2625. );
  2626. partIndex += 1;
  2627. }
  2628. return message.deliveryId && providerMessageId ? { providerMessageId } : undefined;
  2629. },
  2630. async createStreamingReplyCard(bot, state, signal) {
  2631. const token = await readTenantAccessToken(bot, deps, signal);
  2632. if (!token) {
  2633. return null;
  2634. }
  2635. const providerMessageId = await sendCard(
  2636. bot,
  2637. token,
  2638. state.providerUserId,
  2639. buildFeishuStreamingCardPayload(state),
  2640. signal,
  2641. );
  2642. return providerMessageId ? { providerMessageId } : null;
  2643. },
  2644. async updateStreamingReplyCard(bot, handle, state, signal) {
  2645. const token = await readTenantAccessToken(bot, deps, signal);
  2646. if (!token) {
  2647. return;
  2648. }
  2649. await updateCard(bot, token, handle, buildFeishuStreamingCardPayload(state), signal);
  2650. },
  2651. async createTransientInteractionCard(bot, message) {
  2652. resolveFeishuReplyTarget(message);
  2653. if (message.contentParts) {
  2654. const parts = channelContentPartsSchema.parse(message.contentParts);
  2655. if (
  2656. message.selection ||
  2657. !message.providerUserId.startsWith("oc_") ||
  2658. parts.some((part) => part.type === "channelMention" && part.channel !== bot.provider) ||
  2659. channelContentText(parts) !== message.text ||
  2660. message.text.length > 2000
  2661. )
  2662. throw Object.assign(new Error("Invalid native channel reply"), {
  2663. deliveryRejected: true,
  2664. });
  2665. }
  2666. const token = await readTenantAccessToken(bot, deps);
  2667. if (!token) {
  2668. return null;
  2669. }
  2670. const providerMessageId = await sendReplyCard(
  2671. bot,
  2672. token,
  2673. message,
  2674. message.elicitation
  2675. ? buildFeishuElicitationCardPayload(message)
  2676. : buildFeishuInteractiveCardPayload(message),
  2677. );
  2678. return providerMessageId ? { providerMessageId } : null;
  2679. },
  2680. async updateTransientInteractionCard(bot, handle, message) {
  2681. const token = await readTenantAccessToken(bot, deps);
  2682. if (!token) {
  2683. return;
  2684. }
  2685. await updateCard(
  2686. bot,
  2687. token,
  2688. handle,
  2689. message.elicitation
  2690. ? buildFeishuElicitationCardPayload(message)
  2691. : buildFeishuInteractiveCardPayload(message),
  2692. );
  2693. },
  2694. async deleteTransientInteractionCard(bot, handle) {
  2695. const token = await readTenantAccessToken(bot, deps);
  2696. if (!token) {
  2697. return;
  2698. }
  2699. await deleteFeishuInteractiveMessage(bot, token, handle);
  2700. },
  2701. async updateInputReaction(bot, messageId, state) {
  2702. const botKey = JSON.stringify([bot.provider, bot.id, bot.feishuAppId, bot.credentialRef]);
  2703. reactionBots.set(botKey, bot);
  2704. await updateReaction(JSON.stringify([botKey, messageId]), state);
  2705. },
  2706. async sendTyping(bot, target) {
  2707. if (!target.providerMessageId) {
  2708. return;
  2709. }
  2710. // Bugfix: 飞书/Lark 普通命令不会进入长任务 stream,之前只实现 startTyping/stopTyping,
  2711. // 所以 /状态、/项目 等命令没有任何处理中反馈。这里只加 Typing reaction,删除由 BotService 在同步回复发送完成后显式收口。
  2712. await addFeishuTypingReaction(bot, deps, target.providerMessageId);
  2713. },
  2714. async startTyping(bot, target) {
  2715. if (!target.providerMessageId) {
  2716. return;
  2717. }
  2718. // Bugfix: 飞书没有原生 typing 状态,只能用 Typing reaction 模拟。
  2719. // reaction 不会自动消失,所以必须记录 reaction_id,任务结束或进入权限等待时再删除。
  2720. await addFeishuTypingReaction(bot, deps, target.providerMessageId);
  2721. },
  2722. async stopTyping(bot, target) {
  2723. if (!target.providerMessageId) {
  2724. return;
  2725. }
  2726. await deleteFeishuTypingReaction(bot, deps, target.providerMessageId);
  2727. },
  2728. async acknowledgeCallback(bot, payload, text, message, signal) {
  2729. const token = await readTenantAccessToken(bot, deps, signal);
  2730. const cardUpdateToken = readFeishuCardUpdateToken(payload);
  2731. const openIds = readFeishuCardUpdateOpenIds(payload);
  2732. const originalText = readFeishuCardOriginalText(payload);
  2733. if (!token || !cardUpdateToken || (!text?.trim() && !message?.elicitation)) {
  2734. return;
  2735. }
  2736. // Bugfix: 飞书卡片按钮点击后不会像 Telegram inline keyboard 一样自动消失。
  2737. // 使用回调携带的 card update token 更新原卡片为处理结果,避免旧选项继续留在聊天里被重复点击。
  2738. // 非共享卡片延时更新还需要带 open_ids,否则飞书会返回 300090,旧卡片会继续留在会话里。
  2739. // Bugfix: 用户选择后应保留原问题文案并移除按钮;仅依赖 WebSocket 回调 return 的卡片更新不稳定。
  2740. // 因此即使按钮 value 里带了原文,也必须继续调用 card/update,只是更新文案优先使用原文。
  2741. const response = await fetchBotProviderJson<FeishuSendMessageResponse>(
  2742. `${getFeishuBaseUrl(bot)}/open-apis/interactive/v1/card/update`,
  2743. {
  2744. method: "POST",
  2745. headers: {
  2746. authorization: `Bearer ${token}`,
  2747. "content-type": "application/json",
  2748. },
  2749. signal,
  2750. body: JSON.stringify({
  2751. token: cardUpdateToken,
  2752. // Bugfix: Card JSON 2.0 根节点不接受 open_ids;把 open_ids 塞进 card 会触发
  2753. // “unknown property: open_ids” 并导致按钮点击后原卡片无法移除选项。
  2754. ...(openIds.length > 0 ? { open_ids: openIds } : {}),
  2755. // 修复原因:新建下一题再撤回旧卡会在飞书会话中显示明显的撤回痕迹。
  2756. // callback token 是本次点击对应的权威原地更新能力,问答推进和终态都复用同一张卡。
  2757. card: message?.elicitation
  2758. ? buildFeishuElicitationCardPayload(message)
  2759. : buildFeishuInteractiveCardPayload({
  2760. botId: bot.id,
  2761. provider: bot.provider,
  2762. providerUserId: "",
  2763. // Bugfix: 飞书按钮点击后业务结果会另发一条消息;原卡片只需要移除选项按钮。
  2764. // 之前把原卡片改成结果文案,飞书侧会出现额外状态变化,也不符合用户对“选项消失”的预期。
  2765. text: originalText?.trim() || (text ?? ""),
  2766. }),
  2767. }),
  2768. },
  2769. );
  2770. if (!response.ok) {
  2771. throw new Error(`Feishu update interactive card failed: HTTP ${response.status}`);
  2772. }
  2773. const result = response.payload ?? {};
  2774. if (result.code !== 0) {
  2775. throw new Error(result.msg || "Feishu update interactive card failed.");
  2776. }
  2777. return message?.elicitation ? { handled: true } : undefined;
  2778. },
  2779. async downloadAttachment(bot, attachment, actor, signal) {
  2780. signal?.throwIfAborted();
  2781. const token = await readTenantAccessToken(bot, deps, signal);
  2782. if (!token || !attachment.providerFileId || !actor?.providerMessageId) {
  2783. return null;
  2784. }
  2785. const controller = new AbortController();
  2786. const timeout = setTimeout(() => controller.abort(), FEISHU_ATTACHMENT_DOWNLOAD_TIMEOUT_MS);
  2787. try {
  2788. const response = await fetch(
  2789. `${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}`,
  2790. {
  2791. headers: {
  2792. authorization: `Bearer ${token}`,
  2793. },
  2794. signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
  2795. },
  2796. );
  2797. if (!response.ok) {
  2798. throw new Error(`Feishu attachment download failed: HTTP ${response.status}`);
  2799. }
  2800. return {
  2801. attachment,
  2802. data: new Uint8Array(await response.arrayBuffer()),
  2803. };
  2804. } catch (error) {
  2805. signal?.throwIfAborted();
  2806. if ((error as { name?: unknown })?.name === "AbortError") {
  2807. // Bugfix: 飞书资源接口偶发长时间不返回,必须让 bot 回调在可预期时间内给用户失败提示。
  2808. throw new Error("Feishu attachment download timed out.");
  2809. }
  2810. throw error;
  2811. } finally {
  2812. clearTimeout(timeout);
  2813. }
  2814. },
  2815. parseCallback(payload): BotInboundMessage[] {
  2816. if (!isRecord(payload)) {
  2817. return [];
  2818. }
  2819. const botId = readString(payload, "botId");
  2820. if (!botId) {
  2821. return [];
  2822. }
  2823. const message = readFeishuTextMessage(botId, payload) ?? readFeishuCardAction(botId, payload);
  2824. return message ? [message] : [];
  2825. },
  2826. };
  2827. }