telegramProvider.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /* eslint-disable max-lines -- Telegram provider 集中处理 Bot API 文本、按钮、媒体解析和附件下载。 */
  2. import type {
  3. BotInboundAttachment,
  4. BotConfig,
  5. BotInboundMessage,
  6. BotOutboundMessage,
  7. SelectionPrompt,
  8. } from "@zcode/shared";
  9. import { BOT_MENU_COMMAND_ORDER } from "../commandOrder.js";
  10. import type { BotProviderAdapter } from "./types.js";
  11. import { fetchBotProvider, fetchBotProviderJson } from "#src/bots/providers/providerRequest.js";
  12. interface TelegramProviderDeps {
  13. loadCredential(key: string): Promise<string | null>;
  14. }
  15. interface TelegramBotCommand {
  16. command: string;
  17. description: string;
  18. }
  19. const TELEGRAM_ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30_000;
  20. interface TelegramGetMeResponse {
  21. ok?: boolean;
  22. description?: string;
  23. result?: {
  24. username?: string;
  25. first_name?: string;
  26. };
  27. }
  28. interface TelegramFileResponse {
  29. ok?: boolean;
  30. description?: string;
  31. result?: {
  32. file_path?: string;
  33. file_size?: number;
  34. };
  35. }
  36. const telegramCommandDescriptions = {
  37. bind: "Bind this chat",
  38. help: "Show help",
  39. status: "Show current status",
  40. new: "Create a new task",
  41. workspace: "Select project",
  42. model: "Select model",
  43. mode: "Select mode",
  44. thoughtLevel: "Select thinking level",
  45. reply: "Select reply detail",
  46. } as const;
  47. const telegramCommandNames = {
  48. bind: "bind",
  49. help: "help",
  50. status: "status",
  51. new: "new",
  52. workspace: "project",
  53. model: "model",
  54. mode: "mode",
  55. thoughtLevel: "think",
  56. reply: "reply",
  57. } as const;
  58. function isRecord(value: unknown): value is Record<string, unknown> {
  59. return typeof value === "object" && value !== null;
  60. }
  61. function splitTelegramText(text: string): string[] {
  62. const limit = 3900;
  63. const chunks: string[] = [];
  64. for (let index = 0; index < text.length; index += limit) {
  65. chunks.push(text.slice(index, index + limit));
  66. }
  67. return chunks.length > 0 ? chunks : [text];
  68. }
  69. function truncateCallbackToast(text: string): string {
  70. const normalized = text.trim().replace(/\s+/gu, " ");
  71. return normalized.length > 180 ? `${normalized.slice(0, 177)}...` : normalized;
  72. }
  73. function readTelegramPrivateMessage(
  74. botId: string,
  75. update: Record<string, unknown>,
  76. ): BotInboundMessage | null {
  77. const message = isRecord(update.message) ? update.message : null;
  78. if (!message) {
  79. return null;
  80. }
  81. const chat = isRecord(message.chat) ? message.chat : null;
  82. const from = isRecord(message.from) ? message.from : null;
  83. const text =
  84. typeof message.text === "string"
  85. ? message.text
  86. : typeof message.caption === "string"
  87. ? message.caption
  88. : "";
  89. const userId =
  90. typeof from?.id === "number" || typeof from?.id === "string" ? String(from.id) : "";
  91. const chatType = chat?.type === "private" ? "private" : "group";
  92. const attachments = readTelegramAttachments(message);
  93. if ((!text && attachments.length === 0) || !userId) {
  94. return null;
  95. }
  96. return {
  97. botId,
  98. text,
  99. ...(attachments.length > 0 ? { attachments } : {}),
  100. actor: {
  101. provider: "telegram",
  102. botId,
  103. providerUserId: userId,
  104. displayName:
  105. typeof from?.username === "string"
  106. ? from.username
  107. : typeof from?.first_name === "string"
  108. ? from.first_name
  109. : undefined,
  110. chatType,
  111. chatId:
  112. typeof chat?.id === "number" || typeof chat?.id === "string" ? String(chat.id) : undefined,
  113. providerMessageId:
  114. typeof message.message_id === "number" || typeof message.message_id === "string"
  115. ? String(message.message_id)
  116. : undefined,
  117. },
  118. };
  119. }
  120. function readTelegramFileAttachment(
  121. value: unknown,
  122. kind: BotInboundAttachment["kind"],
  123. fallbackName: string,
  124. ): BotInboundAttachment | null {
  125. if (!isRecord(value)) {
  126. return null;
  127. }
  128. const providerFileId = typeof value.file_id === "string" ? value.file_id : "";
  129. if (!providerFileId) {
  130. return null;
  131. }
  132. const filename =
  133. typeof value.file_name === "string" && value.file_name.trim() ? value.file_name : fallbackName;
  134. return {
  135. id: providerFileId,
  136. kind,
  137. filename,
  138. mimeType:
  139. typeof value.mime_type === "string" && value.mime_type.trim()
  140. ? value.mime_type
  141. : defaultMimeTypeForAttachmentKind(kind),
  142. ...(typeof value.file_size === "number" ? { sizeBytes: value.file_size } : {}),
  143. providerFileId,
  144. };
  145. }
  146. function readTelegramPhotoAttachment(
  147. message: Record<string, unknown>,
  148. ): BotInboundAttachment | null {
  149. if (!Array.isArray(message.photo) || message.photo.length === 0) {
  150. return null;
  151. }
  152. const photo = message.photo.filter(isRecord).at(-1);
  153. if (!photo) {
  154. return null;
  155. }
  156. return readTelegramFileAttachment(photo, "image", "telegram-photo.jpg");
  157. }
  158. function defaultMimeTypeForAttachmentKind(kind: BotInboundAttachment["kind"]): string {
  159. if (kind === "image") return "image/jpeg";
  160. if (kind === "audio") return "audio/mpeg";
  161. if (kind === "video") return "video/mp4";
  162. return "application/octet-stream";
  163. }
  164. function readTelegramAttachments(message: Record<string, unknown>): BotInboundAttachment[] {
  165. return [
  166. readTelegramPhotoAttachment(message),
  167. readTelegramFileAttachment(message.document, "file", "telegram-document"),
  168. readTelegramFileAttachment(message.video, "video", "telegram-video.mp4"),
  169. readTelegramFileAttachment(message.audio, "audio", "telegram-audio"),
  170. readTelegramFileAttachment(message.voice, "audio", "telegram-voice.ogg"),
  171. ].filter((attachment): attachment is BotInboundAttachment => attachment !== null);
  172. }
  173. function readTelegramCallbackMessage(
  174. botId: string,
  175. update: Record<string, unknown>,
  176. ): BotInboundMessage | null {
  177. const callbackQuery = isRecord(update.callback_query) ? update.callback_query : null;
  178. if (!callbackQuery) {
  179. return null;
  180. }
  181. const message = isRecord(callbackQuery.message) ? callbackQuery.message : null;
  182. const chat = isRecord(message?.chat) ? message.chat : null;
  183. const from = isRecord(callbackQuery.from) ? callbackQuery.from : null;
  184. const data = typeof callbackQuery.data === "string" ? callbackQuery.data : "";
  185. const userId =
  186. typeof from?.id === "number" || typeof from?.id === "string" ? String(from.id) : "";
  187. if (!data || !userId) {
  188. return null;
  189. }
  190. const commandText = decodeTelegramCallbackData(data);
  191. return {
  192. botId,
  193. text: commandText,
  194. actor: {
  195. provider: "telegram",
  196. botId,
  197. providerUserId: userId,
  198. displayName:
  199. typeof from?.username === "string"
  200. ? from.username
  201. : typeof from?.first_name === "string"
  202. ? from.first_name
  203. : undefined,
  204. chatType: chat?.type === "private" ? "private" : "group",
  205. chatId:
  206. typeof chat?.id === "number" || typeof chat?.id === "string" ? String(chat.id) : undefined,
  207. providerMessageId:
  208. typeof callbackQuery.id === "string"
  209. ? callbackQuery.id
  210. : typeof message?.message_id === "number" || typeof message?.message_id === "string"
  211. ? String(message.message_id)
  212. : undefined,
  213. },
  214. };
  215. }
  216. function readTelegramCallbackId(payload: unknown): string | null {
  217. if (!isRecord(payload)) {
  218. return null;
  219. }
  220. const update = isRecord(payload.update) ? payload.update : payload;
  221. const callbackQuery = isRecord(update.callback_query) ? update.callback_query : null;
  222. return typeof callbackQuery?.id === "string" ? callbackQuery.id : null;
  223. }
  224. function readTelegramCallbackMessageRef(
  225. payload: unknown,
  226. ): { chatId: string; messageId: number } | null {
  227. if (!isRecord(payload)) {
  228. return null;
  229. }
  230. const update = isRecord(payload.update) ? payload.update : payload;
  231. const callbackQuery = isRecord(update.callback_query) ? update.callback_query : null;
  232. const message = isRecord(callbackQuery?.message) ? callbackQuery.message : null;
  233. const chat = isRecord(message?.chat) ? message.chat : null;
  234. const chatId =
  235. typeof chat?.id === "number" || typeof chat?.id === "string" ? String(chat.id) : "";
  236. const messageId = typeof message?.message_id === "number" ? message.message_id : null;
  237. return chatId && messageId !== null ? { chatId, messageId } : null;
  238. }
  239. function buildSelectionCallbackData(
  240. selection: SelectionPrompt,
  241. optionId: string,
  242. index: number,
  243. ): string {
  244. if (selection.action === "permission.respond") {
  245. return `zc:permission:${index + 1}`;
  246. }
  247. if (selection.action === "elicitation.respond") {
  248. return selection.token ? `zc:e:${selection.token}:${index + 1}` : `zc:elicitation:${index + 1}`;
  249. }
  250. if (selection.action === "model.provider.set") {
  251. return `zc:cmd:/model provider ${index + 1}`;
  252. }
  253. if (selection.action === "model.set") {
  254. return `zc:cmd:/model model ${index + 1}`;
  255. }
  256. // Telegram callback_data 最多 64 字节,workspace/task id 可能是远程 identity 或长路径。
  257. // 这里只回传当前列表序号,后续命令解析复用已有的数字选项解析,避免长 id 被 Telegram 拒收。
  258. return `zc:${selection.action.replace(".set", "")}:${index + 1}`;
  259. }
  260. function buildSelectionReplyMarkup(selection: SelectionPrompt): {
  261. inline_keyboard: Array<Array<{ text: string; callback_data: string }>>;
  262. } {
  263. const cancelRows =
  264. selection.showCancel === false
  265. ? []
  266. : [
  267. // Bugfix: Telegram 原生按钮以前没有取消入口,用户只能手敲 0 才能退出 pending selection。
  268. [{ text: selection.cancelLabel ?? "Cancel", callback_data: "zc:cancel" }],
  269. ];
  270. return {
  271. inline_keyboard: [
  272. ...selection.options.map((option, index) => [
  273. {
  274. text: option.label,
  275. callback_data: buildSelectionCallbackData(selection, option.id, index),
  276. },
  277. ]),
  278. ...cancelRows,
  279. ],
  280. };
  281. }
  282. function decodeTelegramCallbackData(data: string): string {
  283. if (data === "zc:cancel") {
  284. return "/cancel";
  285. }
  286. if (data.startsWith("zc:e:")) {
  287. const [, , token, value] = data.split(":");
  288. return token && value ? `/elicitation ${token} ${value}` : "/elicitation";
  289. }
  290. if (data.startsWith("zc:cmd:")) {
  291. return data.slice("zc:cmd:".length);
  292. }
  293. if (data.startsWith("zc:")) {
  294. return `/${data.slice(3).replace(":", " ")}`;
  295. }
  296. return data;
  297. }
  298. function buildTelegramCommands(bot: BotConfig): TelegramBotCommand[] {
  299. return BOT_MENU_COMMAND_ORDER.filter(
  300. (command) => command === "help" || command === "bind" || bot.allowedCommands[command] !== false,
  301. ).map((command) => ({
  302. command: telegramCommandNames[command],
  303. description: telegramCommandDescriptions[command],
  304. }));
  305. }
  306. export function createTelegramBotProvider(deps: TelegramProviderDeps): BotProviderAdapter {
  307. async function loadToken(bot: BotConfig): Promise<string | null> {
  308. return bot.credentialRef ? deps.loadCredential(bot.credentialRef) : null;
  309. }
  310. async function getMe(bot: BotConfig): Promise<TelegramGetMeResponse | null> {
  311. const token = await loadToken(bot);
  312. if (!token?.trim()) {
  313. return null;
  314. }
  315. const response = await fetchBotProviderJson<TelegramGetMeResponse>(
  316. `https://api.telegram.org/bot${token}/getMe`,
  317. );
  318. if (!response.ok) {
  319. return null;
  320. }
  321. return response.payload ?? {};
  322. }
  323. return {
  324. async test(bot) {
  325. if (!bot.credentialRef) {
  326. return { ok: false, message: "Telegram bot token is missing." };
  327. }
  328. const payload = await getMe(bot);
  329. if (!payload) {
  330. return { ok: false, message: "Telegram getMe failed." };
  331. }
  332. const name = payload.result?.first_name || payload.result?.username;
  333. return {
  334. ok: payload.ok === true,
  335. name,
  336. message:
  337. payload.ok === true
  338. ? "Telegram bot is reachable."
  339. : (payload.description ?? "Telegram getMe failed."),
  340. };
  341. },
  342. async resolveName(bot) {
  343. const payload = await getMe(bot);
  344. return payload?.ok === true
  345. ? payload.result?.first_name || payload.result?.username || null
  346. : null;
  347. },
  348. async syncCommands(bot) {
  349. const token = await loadToken(bot);
  350. if (!token?.trim()) {
  351. return;
  352. }
  353. if (!bot.enabled) {
  354. await fetchBotProvider(`https://api.telegram.org/bot${token}/deleteMyCommands`, {
  355. method: "POST",
  356. headers: { "content-type": "application/json" },
  357. body: JSON.stringify({}),
  358. }).catch(() => undefined);
  359. return;
  360. }
  361. const defaultCommands = buildTelegramCommands(bot);
  362. // Bugfix: Telegram 菜单不会自动从我们支持的 slash commands 推导。
  363. // 这里只同步默认英文菜单;中文命令由 parser 支持,避免 Telegram 客户端菜单显示中英混杂。
  364. await fetchBotProvider(`https://api.telegram.org/bot${token}/setMyCommands`, {
  365. method: "POST",
  366. headers: { "content-type": "application/json" },
  367. body: JSON.stringify({ commands: defaultCommands }),
  368. });
  369. },
  370. async send(bot: BotConfig, message: BotOutboundMessage) {
  371. const token = await loadToken(bot);
  372. if (!token?.trim()) throw new Error("Telegram bot token is missing");
  373. const selection = message.selection;
  374. const replyMarkup = selection ? buildSelectionReplyMarkup(selection) : undefined;
  375. const chunks = splitTelegramText(message.text);
  376. for (const [index, text] of chunks.entries()) {
  377. // Bugfix: 长 Plan 会被拆成多条消息,审批提示位于最后一条。
  378. // 按钮必须跟随最终决策上下文,不能挂在尚未发送完整正文的第一条上。
  379. const shouldAttachReplyMarkup = index === chunks.length - 1 && replyMarkup;
  380. const send = (markdown: boolean) =>
  381. fetchBotProviderJson<{
  382. ok?: boolean;
  383. description?: string;
  384. error_code?: number;
  385. parameters?: { retry_after?: number };
  386. }>(`https://api.telegram.org/bot${token}/sendMessage`, {
  387. method: "POST",
  388. headers: { "content-type": "application/json" },
  389. body: JSON.stringify({
  390. chat_id: message.providerUserId,
  391. text,
  392. ...(markdown ? { parse_mode: "Markdown" } : {}),
  393. ...(shouldAttachReplyMarkup ? { reply_markup: replyMarkup } : {}),
  394. }),
  395. });
  396. let response = await send(true);
  397. // 只有明确的格式拒绝才改纯文本;限流、封禁和结果未知不能盲目重发。
  398. if (
  399. response.status === 400 &&
  400. (!response.payload?.description ||
  401. /parse|entities|markdown/i.test(response.payload.description))
  402. )
  403. response = await send(false);
  404. if (!response.ok || response.payload?.ok !== true) {
  405. throw Object.assign(
  406. new Error(
  407. `Telegram send failed (${response.payload?.error_code ?? response.status}): ${response.payload?.description ?? "unknown delivery result"}`,
  408. ),
  409. {
  410. deliveryRejected: response.payload?.ok === false,
  411. retryAfter: response.payload?.parameters?.retry_after,
  412. },
  413. );
  414. }
  415. }
  416. },
  417. async sendTyping(bot: BotConfig, target) {
  418. const token = await loadToken(bot);
  419. if (!token?.trim()) {
  420. return;
  421. }
  422. await fetchBotProvider(`https://api.telegram.org/bot${token}/sendChatAction`, {
  423. method: "POST",
  424. headers: { "content-type": "application/json" },
  425. body: JSON.stringify({
  426. chat_id: target.providerUserId,
  427. action: "typing",
  428. }),
  429. });
  430. },
  431. async acknowledgeCallback(
  432. bot: BotConfig,
  433. payload: unknown,
  434. text?: string,
  435. _message?: BotOutboundMessage,
  436. signal?: AbortSignal,
  437. ) {
  438. const token = await loadToken(bot);
  439. const callbackQueryId = readTelegramCallbackId(payload);
  440. if (!token?.trim() || !callbackQueryId) {
  441. return;
  442. }
  443. await fetchBotProvider(`https://api.telegram.org/bot${token}/answerCallbackQuery`, {
  444. method: "POST",
  445. headers: { "content-type": "application/json" },
  446. signal,
  447. body: JSON.stringify({
  448. callback_query_id: callbackQueryId,
  449. ...(text?.trim() ? { text: truncateCallbackToast(text) } : {}),
  450. }),
  451. });
  452. const messageRef = readTelegramCallbackMessageRef(payload);
  453. if (messageRef && text?.trim()) {
  454. await fetchBotProvider(`https://api.telegram.org/bot${token}/editMessageReplyMarkup`, {
  455. method: "POST",
  456. headers: { "content-type": "application/json" },
  457. signal,
  458. body: JSON.stringify({
  459. chat_id: messageRef.chatId,
  460. message_id: messageRef.messageId,
  461. reply_markup: { inline_keyboard: [] },
  462. }),
  463. }).catch(() => undefined);
  464. }
  465. },
  466. async downloadAttachment(bot, attachment) {
  467. const token = await loadToken(bot);
  468. if (!token?.trim() || !attachment.providerFileId) {
  469. return null;
  470. }
  471. const controller = new AbortController();
  472. const timeout = setTimeout(() => controller.abort(), TELEGRAM_ATTACHMENT_DOWNLOAD_TIMEOUT_MS);
  473. try {
  474. const fileResponse = await fetch(`https://api.telegram.org/bot${token}/getFile`, {
  475. method: "POST",
  476. headers: { "content-type": "application/json" },
  477. body: JSON.stringify({ file_id: attachment.providerFileId }),
  478. signal: controller.signal,
  479. });
  480. if (!fileResponse.ok) {
  481. throw new Error(`Telegram getFile failed: HTTP ${fileResponse.status}`);
  482. }
  483. const filePayload = (await fileResponse.json()) as TelegramFileResponse;
  484. const filePath = filePayload.result?.file_path;
  485. if (filePayload.ok !== true || !filePath) {
  486. throw new Error(filePayload.description ?? "Telegram getFile did not return file_path.");
  487. }
  488. const response = await fetch(`https://api.telegram.org/file/bot${token}/${filePath}`, {
  489. signal: controller.signal,
  490. });
  491. if (!response.ok) {
  492. throw new Error(`Telegram file download failed: HTTP ${response.status}`);
  493. }
  494. return {
  495. attachment: {
  496. ...attachment,
  497. ...(typeof filePayload.result?.file_size === "number"
  498. ? { sizeBytes: filePayload.result.file_size }
  499. : {}),
  500. },
  501. data: new Uint8Array(await response.arrayBuffer()),
  502. };
  503. } catch (error) {
  504. if ((error as { name?: unknown })?.name === "AbortError") {
  505. // Bugfix: Telegram 文件接口卡住时要快速失败,避免 bot 回调一直没有可见结果。
  506. throw new Error("Telegram file download timed out.");
  507. }
  508. throw error;
  509. } finally {
  510. clearTimeout(timeout);
  511. }
  512. },
  513. parseCallback(payload): BotInboundMessage[] {
  514. if (!isRecord(payload)) {
  515. return [];
  516. }
  517. const botId = typeof payload.botId === "string" ? payload.botId : "";
  518. const update = isRecord(payload.update) ? payload.update : payload;
  519. if (!botId) {
  520. return [];
  521. }
  522. const message =
  523. readTelegramPrivateMessage(botId, update) ?? readTelegramCallbackMessage(botId, update);
  524. return message ? [message] : [];
  525. },
  526. };
  527. }