1 // Meta parser for `write_file` tool calls. Reads the path/content from
2 // the streamed args (partial JSON so we can render before the call
3 // finishes) and surfaces `bytes`, `result`, and `error` from the
6 import { BuiltInTool } from '$lib/enums';
9 FILE_PATH_SEPARATOR_REGEX,
10 TEXT_LANGUAGE_PREFIX_REGEX
11 } from '$lib/constants';
12 import { getFileTypeByExtension, tryParseToolResultObject, type AgenticSection } from '$lib/utils';
13 import { parseToolArgs } from './_shared';
15 export type WriteFileMeta = {
20 bytesWritten?: number;
21 resultMessage?: string;
22 errorMessage?: string;
25 export function parseWriteFileMeta(section: AgenticSection): WriteFileMeta | null {
26 const args = parseToolArgs(BuiltInTool.WRITE_FILE, section, { partial: true });
27 if (!args) return null;
29 // Tool contracts drifted over time: some models emit `path`,
30 // others `file_path` / `filePath`. Accept all three.
31 const rawPath = args.path ?? args.file_path ?? args.filePath;
32 if (typeof rawPath !== 'string' || !rawPath) return null;
34 const fileName = rawPath.split(FILE_PATH_SEPARATOR_REGEX).pop() || rawPath;
35 const content = typeof args.content === 'string' ? args.content : '';
37 getFileTypeByExtension(rawPath)?.replace(TEXT_LANGUAGE_PREFIX_REGEX, '') ?? DEFAULT_LANGUAGE;
39 const resultObj = tryParseToolResultObject(section.toolResult);
41 resultObj && Number.isFinite(Number(resultObj.bytes)) ? Number(resultObj.bytes) : undefined;
42 const resultMessage = typeof resultObj?.result === 'string' ? resultObj.result : undefined;
43 const errorMessage = typeof resultObj?.error === 'string' ? resultObj.error : undefined;