tool-preview.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import type {
  2. TuiStructuredPreview,
  3. TuiStructuredPreviewBlock,
  4. TuiStructuredPreviewState,
  5. } from '../types/runtime-models.js';
  6. const MAX_INLINE_PREVIEW_BYTES = 64 * 1024;
  7. const MAX_INLINE_DIFF_LINES = 400;
  8. export interface BuildTuiToolPreviewInput {
  9. readonly toolName?: string;
  10. readonly status?: string | number;
  11. readonly input?: unknown;
  12. readonly output?: unknown;
  13. readonly error?: unknown;
  14. }
  15. export function buildTuiToolPreview(
  16. call: BuildTuiToolPreviewInput,
  17. ): TuiStructuredPreview | undefined {
  18. const toolName = normalizeToolName(call.toolName);
  19. const input = parseRecord(call.input);
  20. if (!toolName) return undefined;
  21. const state = resolvePreviewState(call.status, call.error);
  22. const blocks = isEditTool(toolName)
  23. ? buildEditBlocks(input ?? {}, call.output)
  24. : isWriteTool(toolName)
  25. ? input
  26. ? buildWriteBlocks(input)
  27. : []
  28. : [];
  29. if (blocks.length === 0) return undefined;
  30. return { schemaVersion: 1, state, blocks };
  31. }
  32. function buildEditBlocks(
  33. input: Readonly<Record<string, unknown>>,
  34. output: unknown,
  35. ): TuiStructuredPreviewBlock[] {
  36. const path = readString(input, ['path', 'filePath', 'file_path']);
  37. const resultDiff = readToolResultDiff(output);
  38. if (resultDiff) return [createDiffBlock(path, resultDiff)];
  39. return readEditPairs(input).map(({ oldText, newText }) => {
  40. const diff = [
  41. ...oldText.split('\n').map((line) => `- ${line}`),
  42. ...newText.split('\n').map((line) => `+ ${line}`),
  43. ].join('\n');
  44. return createDiffBlock(path, diff);
  45. });
  46. }
  47. function buildWriteBlocks(input: Readonly<Record<string, unknown>>): TuiStructuredPreviewBlock[] {
  48. const path = readString(input, ['path', 'filePath', 'file_path']);
  49. const content = readString(input, ['content', 'fileContent', 'file_content']);
  50. if (content === undefined) return [];
  51. const byteCount = utf8ByteLength(content);
  52. if (content.includes('\0')) {
  53. return [
  54. {
  55. kind: 'summary',
  56. ...(path ? { path } : {}),
  57. message: 'Binary content cannot be previewed safely.',
  58. reason: 'binary',
  59. byteCount,
  60. },
  61. ];
  62. }
  63. if (byteCount > MAX_INLINE_PREVIEW_BYTES) {
  64. return [
  65. {
  66. kind: 'summary',
  67. ...(path ? { path } : {}),
  68. message: `File preview omitted because it is ${formatByteCount(byteCount)}.`,
  69. reason: 'too-large',
  70. byteCount,
  71. },
  72. ];
  73. }
  74. return [
  75. {
  76. kind: 'file',
  77. ...(path ? { path } : {}),
  78. content,
  79. lineCount: content.split('\n').length,
  80. truncated: false,
  81. },
  82. ];
  83. }
  84. function createDiffBlock(path: string | undefined, rawDiff: string): TuiStructuredPreviewBlock {
  85. const lines = rawDiff.split('\n');
  86. const byteCount = utf8ByteLength(rawDiff);
  87. const visibleLines = lines.slice(0, MAX_INLINE_DIFF_LINES);
  88. const byteLimited = byteCount > MAX_INLINE_PREVIEW_BYTES;
  89. let diff = visibleLines.join('\n');
  90. if (byteLimited) diff = truncateUtf8(diff, MAX_INLINE_PREVIEW_BYTES);
  91. const omittedLines = Math.max(0, lines.length - diff.split('\n').length);
  92. return {
  93. kind: 'diff',
  94. ...(path ? { path } : {}),
  95. diff,
  96. addedLines: countChangedLines(lines, '+'),
  97. removedLines: countChangedLines(lines, '-'),
  98. truncated: omittedLines > 0 || byteLimited,
  99. ...(omittedLines > 0 ? { omittedLines } : {}),
  100. };
  101. }
  102. function readToolResultDiff(output: unknown): string | undefined {
  103. const root = parseRecord(output);
  104. if (!root) return undefined;
  105. const candidates = [root, parseRecord(root.result), parseRecord(root.output)].filter(
  106. (candidate): candidate is Readonly<Record<string, unknown>> => candidate !== undefined,
  107. );
  108. for (const candidate of candidates) {
  109. const details = parseRecord(candidate.details);
  110. const diff = details ? readString(details, ['diff', 'previewDiff', 'preview_diff']) : undefined;
  111. if (diff) return diff;
  112. }
  113. return undefined;
  114. }
  115. function readEditPairs(
  116. input: Readonly<Record<string, unknown>>,
  117. ): Array<{ oldText: string; newText: string }> {
  118. const rawEdits = parseArray(input.edits);
  119. const pairs = (rawEdits ?? []).flatMap((candidate) => {
  120. const edit = parseRecord(candidate);
  121. const oldText = edit ? readString(edit, ['oldText', 'old_text']) : undefined;
  122. const newText = edit ? readString(edit, ['newText', 'new_text']) : undefined;
  123. return oldText !== undefined && newText !== undefined ? [{ oldText, newText }] : [];
  124. });
  125. const legacyOldText = readString(input, ['oldText', 'old_text']);
  126. const legacyNewText = readString(input, ['newText', 'new_text']);
  127. if (legacyOldText !== undefined && legacyNewText !== undefined) {
  128. pairs.push({ oldText: legacyOldText, newText: legacyNewText });
  129. }
  130. return pairs;
  131. }
  132. function resolvePreviewState(
  133. status: string | number | undefined,
  134. error: unknown,
  135. ): TuiStructuredPreviewState {
  136. if (hasError(error) || isFailedStatus(status)) return 'not-applied';
  137. return isSuccessfulStatus(status) ? 'applied' : 'proposed';
  138. }
  139. function isSuccessfulStatus(status: string | number | undefined): boolean {
  140. return (
  141. status === 2 ||
  142. status === '2' ||
  143. status === 'completed' ||
  144. status === 'complete' ||
  145. status === 'done' ||
  146. status === 'finished' ||
  147. status === 'succeeded' ||
  148. status === 'success'
  149. );
  150. }
  151. function isFailedStatus(status: string | number | undefined): boolean {
  152. return status === 3 || status === '3' || status === 'failed' || status === 'error';
  153. }
  154. function hasError(error: unknown): boolean {
  155. return error !== undefined && error !== null && error !== '';
  156. }
  157. function normalizeToolName(value: string | undefined): string | undefined {
  158. const normalized = value
  159. ?.trim()
  160. .toLocaleLowerCase()
  161. .replace(/[^a-z0-9]/gu, '');
  162. return normalized || undefined;
  163. }
  164. function isEditTool(name: string): boolean {
  165. return name === 'edit' || name === 'editfile' || name === 'replace';
  166. }
  167. function isWriteTool(name: string): boolean {
  168. return name === 'write' || name === 'writefile' || name === 'createfile';
  169. }
  170. function parseRecord(value: unknown): Readonly<Record<string, unknown>> | undefined {
  171. const parsed = parseJson(value);
  172. return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
  173. ? (parsed as Readonly<Record<string, unknown>>)
  174. : undefined;
  175. }
  176. function parseArray(value: unknown): readonly unknown[] | undefined {
  177. const parsed = parseJson(value);
  178. return Array.isArray(parsed) ? parsed : undefined;
  179. }
  180. function parseJson(value: unknown): unknown {
  181. if (typeof value !== 'string') return value;
  182. try {
  183. return JSON.parse(value) as unknown;
  184. } catch {
  185. return undefined;
  186. }
  187. }
  188. function readString(
  189. record: Readonly<Record<string, unknown>>,
  190. keys: readonly string[],
  191. ): string | undefined {
  192. for (const key of keys) {
  193. const value = record[key];
  194. if (typeof value === 'string') return value;
  195. }
  196. return undefined;
  197. }
  198. function countChangedLines(lines: readonly string[], prefix: '+' | '-'): number {
  199. return lines.filter((line) => line.startsWith(prefix) && !line.startsWith(prefix.repeat(3)))
  200. .length;
  201. }
  202. function utf8ByteLength(value: string): number {
  203. return new TextEncoder().encode(value).byteLength;
  204. }
  205. function truncateUtf8(value: string, maxBytes: number): string {
  206. if (utf8ByteLength(value) <= maxBytes) return value;
  207. let low = 0;
  208. let high = value.length;
  209. while (low < high) {
  210. const middle = Math.ceil((low + high) / 2);
  211. if (utf8ByteLength(value.slice(0, middle)) <= maxBytes) low = middle;
  212. else high = middle - 1;
  213. }
  214. return value.slice(0, low);
  215. }
  216. function formatByteCount(bytes: number): string {
  217. if (bytes < 1024) return `${bytes} B`;
  218. return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KiB`;
  219. }