webhookProvider.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import type {
  2. BotInboundAttachment,
  3. BotConfig,
  4. BotInboundMessage,
  5. BotOutboundMessage,
  6. BotStructuredElicitationResponse,
  7. SelectionPrompt,
  8. } from "@zcode/shared";
  9. import type { BotProviderAdapter } from "./types.js";
  10. interface WebhookProviderDeps {
  11. loadCredential(key: string): Promise<string | null>;
  12. }
  13. function isRecord(value: unknown): value is Record<string, unknown> {
  14. return typeof value === "object" && value !== null;
  15. }
  16. function formatSelectionCommand(
  17. selection: SelectionPrompt,
  18. optionId: string,
  19. ): string {
  20. if (selection.action === "permission.respond") {
  21. return optionId;
  22. }
  23. if (selection.action === "elicitation.respond") {
  24. return selection.token ? `/elicitation ${selection.token} ${optionId}` : `/elicitation ${optionId}`;
  25. }
  26. if (selection.action === "model.provider.set") {
  27. return `/model provider ${optionId}`;
  28. }
  29. if (selection.action === "model.set") {
  30. return `/model model ${optionId}`;
  31. }
  32. return `/${selection.action.replace(".set", "")} ${optionId}`;
  33. }
  34. function buildSelectionText(message: BotOutboundMessage): string {
  35. if (!message.selection) {
  36. return message.text;
  37. }
  38. const selection = message.selection;
  39. const lines = selection.options.map((option, index) => {
  40. const description = option.description ? ` - ${option.description}` : "";
  41. return `${index + 1}. ${option.label}${description}\n${formatSelectionCommand(selection, option.id)}`;
  42. });
  43. return `${message.text}\n${lines.join("\n")}`;
  44. }
  45. function delay(ms: number): Promise<void> {
  46. return new Promise((resolve) => setTimeout(resolve, ms));
  47. }
  48. function parseWebhookAttachment(
  49. value: unknown,
  50. index: number,
  51. ): BotInboundAttachment | null {
  52. if (!isRecord(value)) {
  53. return null;
  54. }
  55. const kind = value.kind;
  56. if (
  57. kind !== "image" &&
  58. kind !== "audio" &&
  59. kind !== "video" &&
  60. kind !== "file"
  61. ) {
  62. return null;
  63. }
  64. const id =
  65. typeof value.id === "string" && value.id.trim()
  66. ? value.id
  67. : `webhook-${index + 1}`;
  68. const filename =
  69. typeof value.filename === "string" && value.filename.trim()
  70. ? value.filename
  71. : `${id}.${kind}`;
  72. const mimeType =
  73. typeof value.mimeType === "string" && value.mimeType.trim()
  74. ? value.mimeType
  75. : "application/octet-stream";
  76. return {
  77. id,
  78. kind,
  79. filename,
  80. mimeType,
  81. ...(typeof value.sizeBytes === "number"
  82. ? { sizeBytes: value.sizeBytes }
  83. : {}),
  84. ...(typeof value.providerFileId === "string"
  85. ? { providerFileId: value.providerFileId }
  86. : {}),
  87. ...(typeof value.downloadUrl === "string"
  88. ? { downloadUrl: value.downloadUrl }
  89. : {}),
  90. ...(typeof value.dataBase64 === "string"
  91. ? { dataBase64: value.dataBase64 }
  92. : {}),
  93. ...(typeof value.localPath === "string"
  94. ? { localPath: value.localPath }
  95. : {}),
  96. };
  97. }
  98. function parseWebhookAttachments(
  99. payload: Record<string, unknown>,
  100. ): BotInboundAttachment[] {
  101. return Array.isArray(payload.attachments)
  102. ? payload.attachments
  103. .map((attachment, index) => parseWebhookAttachment(attachment, index))
  104. .filter(
  105. (attachment): attachment is BotInboundAttachment =>
  106. attachment !== null,
  107. )
  108. : [];
  109. }
  110. function parseWebhookElicitationResponse(
  111. payload: Record<string, unknown>,
  112. ): BotStructuredElicitationResponse | undefined {
  113. if (payload.type !== "zcode.bot.elicitation_response") {
  114. return undefined;
  115. }
  116. const requestId =
  117. typeof payload.requestId === "string" && payload.requestId.trim()
  118. ? payload.requestId
  119. : "";
  120. const action = payload.action;
  121. if (
  122. !requestId ||
  123. (action !== "accept" && action !== "decline" && action !== "cancel")
  124. ) {
  125. return undefined;
  126. }
  127. return {
  128. requestId,
  129. action,
  130. ...(isRecord(payload.content) ? { content: payload.content } : {}),
  131. };
  132. }
  133. async function postWebhookWithRetry(
  134. url: string,
  135. init: RequestInit,
  136. ): Promise<Response> {
  137. let lastResponse: Response | null = null;
  138. let lastError: unknown;
  139. for (const retryDelayMs of [0, 500, 1_500]) {
  140. if (retryDelayMs > 0) {
  141. await delay(retryDelayMs);
  142. }
  143. try {
  144. const response = await fetch(url, init);
  145. if (response.ok || (response.status >= 400 && response.status < 500)) {
  146. return response;
  147. }
  148. lastResponse = response;
  149. } catch (error) {
  150. lastError = error;
  151. }
  152. }
  153. if (lastResponse) {
  154. return lastResponse;
  155. }
  156. throw lastError instanceof Error ? lastError : new Error(String(lastError));
  157. }
  158. export function createWebhookBotProvider(
  159. deps: WebhookProviderDeps,
  160. ): BotProviderAdapter {
  161. return {
  162. async test(bot: BotConfig) {
  163. if (!bot.enabled) {
  164. return { ok: false, message: "Webhook bot is disabled." };
  165. }
  166. if (!bot.webhookSecretRef) {
  167. return {
  168. ok: false,
  169. message:
  170. "Webhook secret is missing. Configure a secret before exposing the callback endpoint.",
  171. };
  172. }
  173. if (bot.webhookUrl) {
  174. const secret = await deps.loadCredential(bot.webhookSecretRef);
  175. const response = await postWebhookWithRetry(bot.webhookUrl, {
  176. method: "POST",
  177. headers: {
  178. "content-type": "application/json",
  179. [bot.webhookAuthHeaderName || "x-zcode-bot-secret"]: secret ?? "",
  180. },
  181. body: JSON.stringify({
  182. type: "zcode.bot.test",
  183. botId: bot.id,
  184. provider: "webhook",
  185. sentAt: Date.now(),
  186. }),
  187. });
  188. return {
  189. ok: response.ok,
  190. message: response.ok
  191. ? "Webhook outbound endpoint is reachable."
  192. : `Webhook outbound endpoint returned HTTP ${response.status}.`,
  193. };
  194. }
  195. return {
  196. ok: true,
  197. message: "Webhook bot is enabled for inbound callbacks.",
  198. };
  199. },
  200. async send(bot, message) {
  201. if (!bot.webhookUrl) {
  202. return;
  203. }
  204. const secret = bot.webhookSecretRef
  205. ? await deps.loadCredential(bot.webhookSecretRef)
  206. : null;
  207. const headers: Record<string, string> = {
  208. "content-type": "application/json",
  209. };
  210. if (secret) {
  211. headers[bot.webhookAuthHeaderName || "x-zcode-bot-secret"] = secret;
  212. }
  213. const response = await postWebhookWithRetry(bot.webhookUrl, {
  214. method: "POST",
  215. headers,
  216. body: JSON.stringify({
  217. type: "zcode.bot.message",
  218. botId: bot.id,
  219. provider: "webhook",
  220. userId: message.providerUserId,
  221. text: buildSelectionText(message),
  222. selection: message.selection,
  223. elicitation: message.elicitation,
  224. ...(message.elicitation
  225. ? { type: "zcode.bot.elicitation_request" }
  226. : {}),
  227. sentAt: Date.now(),
  228. }),
  229. });
  230. if (!response.ok) {
  231. throw new Error(
  232. `Webhook outbound endpoint returned HTTP ${response.status}`,
  233. );
  234. }
  235. },
  236. parseCallback(payload: unknown): BotInboundMessage[] {
  237. if (!isRecord(payload)) {
  238. return [];
  239. }
  240. const botId = typeof payload.botId === "string" ? payload.botId : "";
  241. const text = typeof payload.text === "string" ? payload.text : "";
  242. const userId = typeof payload.userId === "string" ? payload.userId : "";
  243. const attachments = parseWebhookAttachments(payload);
  244. const elicitationResponse = parseWebhookElicitationResponse(payload);
  245. if (!botId || (!text && attachments.length === 0 && !elicitationResponse) || !userId) {
  246. return [];
  247. }
  248. return [
  249. {
  250. botId,
  251. text,
  252. ...(attachments.length > 0 ? { attachments } : {}),
  253. ...(elicitationResponse ? { elicitationResponse } : {}),
  254. actor: {
  255. provider: "webhook",
  256. botId,
  257. providerUserId: userId,
  258. displayName:
  259. typeof payload.displayName === "string"
  260. ? payload.displayName
  261. : undefined,
  262. chatType: payload.chatType === "group" ? "group" : "private",
  263. chatId:
  264. typeof payload.chatId === "string" ? payload.chatId : undefined,
  265. // Bugfix: webhook 回调也需要携带消息 id 进入通用幂等层。
  266. // 否则上游重试同一条消息时,Bot 会重复创建/发送任务。
  267. providerMessageId:
  268. typeof payload.messageId === "string"
  269. ? payload.messageId
  270. : typeof payload.id === "string"
  271. ? payload.id
  272. : undefined,
  273. },
  274. },
  275. ];
  276. },
  277. };
  278. }