replyFormatter.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* eslint-disable max-lines -- Bot bot reply formatter 集中维护第三方消息的文本颗粒度、工具摘要和权限摘要,避免 provider 间文案分叉。 */
  2. import type {
  3. ZCodePermissionRequest,
  4. ZCodeStreamEvent,
  5. ZCodeTaskChangeSummary,
  6. Locale,
  7. } from "@zcode/shared";
  8. import {
  9. getCompactToolCallSummary,
  10. getPermissionRequestPreview,
  11. } from "@zcode/shared";
  12. import { normalizeBotMessageLocale } from "./messages.js";
  13. export interface BotReplyToolCallState {
  14. toolId: string;
  15. parentToolUseId?: string | null;
  16. title?: string;
  17. kind?: string;
  18. input?: unknown;
  19. output?: unknown;
  20. status?: "pending" | "in_progress" | "completed" | "failed" | "denied" | "stopped";
  21. error?: string;
  22. raw?: unknown;
  23. }
  24. interface BotReplyFormatOptions {
  25. workspacePath?: string;
  26. locale?: Locale;
  27. }
  28. export type BotAssistantReplyBlock =
  29. | {
  30. type: "content";
  31. content: string;
  32. }
  33. | {
  34. type: "tool-call";
  35. toolCall: BotReplyToolCallState;
  36. }
  37. | {
  38. type: "change-summary";
  39. changeSummary: ZCodeTaskChangeSummary;
  40. };
  41. const MAX_TOOL_SUMMARY_ITEMS = 10;
  42. const MAX_FIELD_LENGTH = 160;
  43. const MAX_COMMAND_FIELD_LENGTH = 96;
  44. const MAX_REPLY_MESSAGE_LENGTH = 3500;
  45. const DIFF_ADDED_MARKER = "🟢";
  46. const DIFF_REMOVED_MARKER = "🔴";
  47. const formatterMessages = {
  48. "zh-CN": {
  49. toolCalls: "工具调用:",
  50. completed: "完成",
  51. failed: "失败",
  52. denied: "已拒绝",
  53. inProgress: "⏳ 运行中",
  54. pending: "等待中",
  55. permissionRequired: "需要权限:",
  56. editWriting: "写入中",
  57. editUpdating: "更新中",
  58. editDeleting: "删除中",
  59. editEditing: "编辑中",
  60. changeSummary: "变更摘要",
  61. moreToolCalls: "还有 {count} 个工具调用",
  62. moreFiles: "还有 {count} 个文件",
  63. },
  64. "en-US": {
  65. toolCalls: "Tool calls:",
  66. completed: "Completed",
  67. failed: "Failed",
  68. denied: "Denied",
  69. inProgress: "Running",
  70. pending: "Pending",
  71. permissionRequired: "Permission required:",
  72. editWriting: "Writing",
  73. editUpdating: "Updating",
  74. editDeleting: "Deleting",
  75. editEditing: "Editing",
  76. changeSummary: "Change summary",
  77. moreToolCalls: "{count} more tool calls",
  78. moreFiles: "{count} more files",
  79. },
  80. } as const;
  81. function t(locale: Locale | undefined, key: keyof (typeof formatterMessages)["zh-CN"]): string {
  82. return formatterMessages[normalizeBotMessageLocale(locale)][key];
  83. }
  84. function isRecord(value: unknown): value is Record<string, unknown> {
  85. return typeof value === "object" && value !== null && !Array.isArray(value);
  86. }
  87. function normalizeInlineText(value: string): string {
  88. return value.trim().replace(/\s+/g, " ");
  89. }
  90. function truncateText(value: string, maxLength = MAX_FIELD_LENGTH): string {
  91. return value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;
  92. }
  93. function truncateMiddleText(value: string, maxLength = MAX_COMMAND_FIELD_LENGTH): string {
  94. if (value.length <= maxLength) {
  95. return value;
  96. }
  97. const headLength = Math.ceil((maxLength - 5) * 0.65);
  98. const tailLength = Math.max(0, maxLength - 5 - headLength);
  99. return `${value.slice(0, headLength)} ... ${value.slice(value.length - tailLength)}`;
  100. }
  101. function formatMarkdownInlineCode(value: string): string {
  102. // Telegram Markdown 的 inline code 需要转义反斜杠和反引号,否则路径/命令里的特殊字符会导致文本退回裸显示。
  103. return `\`${value.replace(/\\/gu, "\\\\").replace(/`/gu, "\\`")}\``;
  104. }
  105. function normalizePathSeparators(value: string): string {
  106. return value.replace(/\\/gu, "/");
  107. }
  108. function stripTrailingSlash(value: string): string {
  109. return value.length > 1 ? value.replace(/\/+$/u, "") : value;
  110. }
  111. function toWorkspaceRelativePath(pathValue: string, workspacePath?: string): string {
  112. const normalizedPath = stripTrailingSlash(normalizePathSeparators(pathValue.trim()));
  113. if (!workspacePath?.trim()) {
  114. return normalizedPath;
  115. }
  116. const normalizedWorkspace = stripTrailingSlash(normalizePathSeparators(workspacePath.trim()));
  117. const comparablePath = normalizedPath.toLowerCase();
  118. const comparableWorkspace = normalizedWorkspace.toLowerCase();
  119. if (comparablePath === comparableWorkspace) {
  120. return ".";
  121. }
  122. if (comparablePath.startsWith(`${comparableWorkspace}/`)) {
  123. return normalizedPath.slice(normalizedWorkspace.length + 1);
  124. }
  125. return normalizedPath;
  126. }
  127. function normalizeToolCallSummaryInput(
  128. toolCall: BotReplyToolCallState,
  129. options?: BotReplyFormatOptions,
  130. ): unknown {
  131. if (!isRecord(toolCall.input) || toolCall.kind !== "edit") {
  132. return toolCall.input;
  133. }
  134. const nextInput = { ...toolCall.input };
  135. for (const key of ["path", "file_path", "filePath"] as const) {
  136. const value = nextInput[key];
  137. if (typeof value === "string") {
  138. nextInput[key] = toWorkspaceRelativePath(value, options?.workspacePath);
  139. }
  140. }
  141. return nextInput;
  142. }
  143. function formatCompactSummaryDetail(
  144. summary: ReturnType<typeof getCompactToolCallSummary>,
  145. ): string | undefined {
  146. const parts: string[] = [];
  147. if (summary.secondaryText) {
  148. parts.push(formatMarkdownInlineCode(truncateMiddleText(normalizeInlineText(summary.secondaryText))));
  149. }
  150. if (summary.changeStat) {
  151. const stat = formatBotDiffCount(summary.changeStat);
  152. if (stat) {
  153. parts.push(stat);
  154. }
  155. }
  156. return parts.length > 0 ? parts.join(" · ") : undefined;
  157. }
  158. function formatBotDiffCount(changeStat: { added: number; removed: number }): string {
  159. const parts: string[] = [];
  160. if (changeStat.added > 0) {
  161. parts.push(`${DIFF_ADDED_MARKER} ${formatMarkdownInlineCode(`+${changeStat.added}`)}`);
  162. }
  163. if (changeStat.removed > 0) {
  164. parts.push(`${DIFF_REMOVED_MARKER} ${formatMarkdownInlineCode(`-${changeStat.removed}`)}`);
  165. }
  166. return parts.join(" ");
  167. }
  168. function formatPermissionRequestHeader(
  169. request: Pick<ZCodePermissionRequest, "title" | "description" | "kind" | "raw">,
  170. options?: BotReplyFormatOptions,
  171. ): string {
  172. const preview = getPermissionRequestPreview(request);
  173. return `${t(options?.locale, "permissionRequired")}\n${formatPermissionRequestTitle(request, preview, options)}`;
  174. }
  175. function formatPermissionRequestTitle(
  176. request: Pick<ZCodePermissionRequest, "title" | "description" | "kind" | "raw">,
  177. preview: ReturnType<typeof getPermissionRequestPreview>,
  178. options?: BotReplyFormatOptions,
  179. ): string {
  180. if (request.kind !== "edit" || (preview.scope !== "file" && preview.fileChanges.length === 0)) {
  181. return preview.title;
  182. }
  183. const label = formatEditPermissionKindLabel(request, preview, options?.locale);
  184. const titleWithoutEdit = preview.title.replace(/^edit\b[::]?\s*/iu, "").trim();
  185. const targetText =
  186. titleWithoutEdit && titleWithoutEdit !== preview.title
  187. ? titleWithoutEdit
  188. : preview.filePaths.length === 1 || preview.fileChanges.length === 1
  189. ? toWorkspaceRelativePath((preview.filePaths[0] ?? preview.fileChanges[0]?.path)!, options?.workspacePath)
  190. : "";
  191. return targetText ? `${label} ${targetText}` : label;
  192. }
  193. function formatEditPermissionKindLabel(
  194. request: Pick<ZCodePermissionRequest, "title" | "description" | "kind" | "raw">,
  195. preview: ReturnType<typeof getPermissionRequestPreview>,
  196. locale?: Locale,
  197. ): string {
  198. const rawText = [
  199. request.title,
  200. request.description,
  201. isRecord(request.raw) && typeof request.raw.kind === "string" ? request.raw.kind : undefined,
  202. isRecord(request.raw) && typeof request.raw.title === "string" ? request.raw.title : undefined,
  203. ].filter((value): value is string => typeof value === "string").join(" ");
  204. const normalizedText = rawText.trim().toLowerCase();
  205. const fileChangeType = preview.fileChange?.type;
  206. if (/\b(delete|deleted|remove|removed|erase|erased|unlink|rm)\b/u.test(normalizedText)) {
  207. return t(locale, "editDeleting");
  208. }
  209. if (fileChangeType === "add" || /\b(write|wrote|create|created|add|added|save|saved|new)\b/u.test(normalizedText)) {
  210. return t(locale, "editWriting");
  211. }
  212. if (/\b(update|updating|updated)\b/u.test(normalizedText)) {
  213. return t(locale, "editUpdating");
  214. }
  215. // Bugfix: edit 权限标题直接透传 ZCode Agent 的 "Edit <path>" 时,第三方消息无法像 UI kindLabel 一样区分写入/更新/删除。
  216. // 这里至少把泛化的 Edit 换成 edit kind label,具体操作能从 raw/fileChange 推断时再细分。
  217. return t(locale, "editEditing");
  218. }
  219. export function formatBotToolCallSummaryLine(
  220. toolCall: BotReplyToolCallState,
  221. options?: BotReplyFormatOptions,
  222. ): string {
  223. const summary = getCompactToolCallSummary({
  224. title: toolCall.title,
  225. kind: toolCall.kind ?? "tool",
  226. input: normalizeToolCallSummaryInput(toolCall, options),
  227. output: toolCall.output,
  228. raw: toolCall.raw,
  229. });
  230. const status = formatToolStatus(toolCall.status, toolCall.error, options?.locale);
  231. const detail = formatCompactSummaryDetail(summary);
  232. return `- ${status} · ${summary.primaryText}${detail ? ` · ${detail}` : ""}`;
  233. }
  234. function formatToolStatus(
  235. status?: BotReplyToolCallState["status"],
  236. error?: string,
  237. locale?: Locale,
  238. ): string {
  239. if (status === "completed") return t(locale, "completed");
  240. if (status === "failed") return `${t(locale, "failed")}${error ? `: ${truncateText(normalizeInlineText(error))}` : ""}`;
  241. if (status === "denied") return t(locale, "denied");
  242. if (status === "in_progress") return t(locale, "inProgress");
  243. return t(locale, "pending");
  244. }
  245. function splitLongReplyText(text: string): string[] {
  246. const chunks: string[] = [];
  247. let remaining = text.trim();
  248. while (remaining.length > MAX_REPLY_MESSAGE_LENGTH) {
  249. const breakpoint = Math.max(
  250. remaining.lastIndexOf("\n", MAX_REPLY_MESSAGE_LENGTH),
  251. remaining.lastIndexOf(" ", MAX_REPLY_MESSAGE_LENGTH),
  252. );
  253. const end = breakpoint > 0 ? breakpoint : MAX_REPLY_MESSAGE_LENGTH;
  254. chunks.push(remaining.slice(0, end).trim());
  255. remaining = remaining.slice(end).trim();
  256. }
  257. if (remaining) {
  258. chunks.push(remaining);
  259. }
  260. return chunks;
  261. }
  262. export function extractBotAssistantResponseMessages(
  263. buffer: string,
  264. force = false,
  265. ): { messages: string[]; rest: string } {
  266. const normalizedBuffer = buffer.replace(/\r\n/g, "\n");
  267. if (!force) {
  268. return { messages: [], rest: normalizedBuffer };
  269. }
  270. // Bugfix: Bot channel 的 provider chunk 常按词或子词到达,非终态时必须继续留在
  271. // assistantReplyBuffer 里合并;真正的发送边界由 tool_call / task_complete 等 force flush 决定。
  272. return {
  273. messages: splitLongReplyText(normalizedBuffer),
  274. rest: "",
  275. };
  276. }
  277. export function formatBotToolCallReply(
  278. toolCall: BotReplyToolCallState,
  279. options?: BotReplyFormatOptions,
  280. ): string {
  281. return `${t(options?.locale, "toolCalls")}\n${formatBotToolCallSummaryLine(toolCall, options)}`;
  282. }
  283. export function formatBotPermissionRequestSummary(
  284. request: Pick<ZCodePermissionRequest, "title" | "description" | "kind" | "raw">,
  285. options?: BotReplyFormatOptions,
  286. ): string {
  287. const preview = getPermissionRequestPreview(request);
  288. const header = formatPermissionRequestHeader(request, options);
  289. if (preview.command) {
  290. return `${header}\n${formatMarkdownInlineCode(truncateMiddleText(preview.command))}`;
  291. }
  292. const previewFilePaths = preview.filePaths.length > 0
  293. ? preview.filePaths
  294. : preview.fileChanges.map((change) => change.path);
  295. if (previewFilePaths.length > 0) {
  296. const paths = previewFilePaths
  297. .slice(0, 3)
  298. .map((path) => toWorkspaceRelativePath(path, options?.workspacePath))
  299. .map((path) => formatMarkdownInlineCode(path))
  300. .join(", ");
  301. return `${header}\n${truncateText(paths)}`;
  302. }
  303. return header;
  304. }
  305. export function isBotToolCallReplyTerminal(
  306. status?: BotReplyToolCallState["status"],
  307. ): boolean {
  308. return status === "completed" ||
  309. status === "failed" ||
  310. status === "denied" ||
  311. status === "stopped";
  312. }
  313. function formatBotChangeSummary(
  314. changeSummary?: ZCodeTaskChangeSummary | null,
  315. options?: Pick<BotReplyFormatOptions, "locale">,
  316. ): string {
  317. if (!changeSummary || changeSummary.fileCount <= 0 || changeSummary.files.length === 0) {
  318. return "";
  319. }
  320. const lines = [
  321. options?.locale === "en-US"
  322. ? `${t(options.locale, "changeSummary")}: ${changeSummary.fileCount} files, ${formatBotDiffCount(changeSummary)}`
  323. : `${t(options?.locale, "changeSummary")}:${changeSummary.fileCount} 个文件,${formatBotDiffCount(changeSummary)}`,
  324. ];
  325. for (const file of changeSummary.files.slice(0, MAX_TOOL_SUMMARY_ITEMS)) {
  326. lines.push(`- ${formatMarkdownInlineCode(file.path)} (${formatBotDiffCount(file)})`);
  327. }
  328. if (changeSummary.files.length > MAX_TOOL_SUMMARY_ITEMS) {
  329. lines.push(`- ${t(options?.locale, "moreFiles").replace("{count}", String(changeSummary.files.length - MAX_TOOL_SUMMARY_ITEMS))}`);
  330. }
  331. return lines.join("\n");
  332. }
  333. export function updateBotReplyToolCalls(
  334. toolCalls: Map<string, BotReplyToolCallState>,
  335. event: ZCodeStreamEvent,
  336. ): void {
  337. if (event.type === "tool_call") {
  338. toolCalls.set(event.toolId, {
  339. toolId: event.toolId,
  340. parentToolUseId: event.parentToolUseId ?? null,
  341. title: event.title,
  342. kind: event.kind,
  343. input: event.input,
  344. raw: event.raw,
  345. status: "pending",
  346. });
  347. return;
  348. }
  349. if (event.type !== "tool_call_update") {
  350. return;
  351. }
  352. const existing = toolCalls.get(event.toolId) ?? { toolId: event.toolId };
  353. toolCalls.set(event.toolId, {
  354. ...existing,
  355. parentToolUseId: event.parentToolUseId ?? existing.parentToolUseId ?? null,
  356. title: event.title ?? existing.title,
  357. kind: event.kind ?? existing.kind,
  358. input: event.input ?? existing.input,
  359. output: event.content ?? existing.output,
  360. status: event.status,
  361. error: event.error ?? existing.error,
  362. raw: event.raw ?? existing.raw,
  363. });
  364. }
  365. export function formatBotAssistantReplyBlocks(
  366. blocks: readonly BotAssistantReplyBlock[],
  367. options?: BotReplyFormatOptions,
  368. ): string[] {
  369. const messages: string[] = [];
  370. for (const block of blocks) {
  371. if (block.type === "content") {
  372. messages.push(...splitLongReplyText(block.content.replace(/\r\n/g, "\n")));
  373. continue;
  374. }
  375. if (block.type === "tool-call") {
  376. const text = formatBotToolCallReply(block.toolCall, options);
  377. messages.push(...splitLongReplyText(text));
  378. continue;
  379. }
  380. const text = formatBotChangeSummary(block.changeSummary, {
  381. locale: options?.locale,
  382. });
  383. if (text) {
  384. messages.push(...splitLongReplyText(text));
  385. }
  386. }
  387. return messages;
  388. }