feat: search and replace tool preview and functionality

This commit is contained in:
Dallin Romney 2025-07-29 19:37:17 +09:00
parent 331de538b6
commit 206463d6bc
18 changed files with 477 additions and 310 deletions

View file

@ -1,3 +1,5 @@
import { ToolCallPreview } from "../tools/types.js";
export type PermissionPolicy = "allow" | "ask" | "exclude";
export interface ToolPermissionPolicy {
@ -17,6 +19,7 @@ export interface ToolPermissions {
export interface ToolCallRequest {
name: string;
arguments: Record<string, any>;
preview?: ToolCallPreview[];
}
export interface PermissionCheckResult {

View file

@ -12,17 +12,25 @@ import { MCPService } from "./mcp.js";
import {
checkToolPermission,
filterExcludedTools,
ToolCallRequest,
} from "./permissions/index.js";
import { toolPermissionManager } from "./permissions/permissionManager.js";
import telemetryService from "./telemetry/telemetryService.js";
import { calculateTokenCost } from "./telemetry/utils.js";
import { executeToolCall } from "./tools.js";
import { BUILTIN_TOOLS } from "./tools/index.js";
import {
BUILTIN_TOOLS,
getAvailableTools,
Tool,
ToolCall,
validateToolCallArgsPresent,
} from "./tools/index.js";
import {
chatCompletionStreamWithBackoff,
withExponentialBackoff,
} from "./util/exponentialBackoff.js";
import logger from "./util/logger.js";
import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js";
dotenv.config();
@ -100,18 +108,10 @@ export interface StreamCallbacks {
onToolPermissionRequest?: (
toolName: string,
toolArgs: any,
requestId: string
requestId: string,
preview?: ToolCallPreview[]
) => void;
}
interface ToolCall {
id: string;
name: string;
arguments: any;
argumentsStr: string;
startNotified: boolean;
}
function getDefaultCompletionOptions(
opts?: CompletionOptions
): Partial<ChatCompletionCreateParamsStreaming> {
@ -239,7 +239,7 @@ async function processStreamingResponse(
hasToolCalls = true;
for (const toolCallDelta of choice.delta.tool_calls) {
let toolCallId: string | undefined;
// If we have an ID, use it and map the index
if (toolCallDelta.id) {
toolCallId = toolCallDelta.id;
@ -250,12 +250,14 @@ async function processStreamingResponse(
// No ID, but we have an index - look up the ID from our map
toolCallId = indexToIdMap.get(toolCallDelta.index);
}
if (!toolCallId) {
logger.warn("Tool call delta without ID or valid index mapping", { toolCallDelta });
logger.warn("Tool call delta without ID or valid index mapping", {
toolCallDelta,
});
continue;
}
// Create tool call entry if it doesn't exist
if (!toolCallsMap.has(toolCallId)) {
toolCallsMap.set(toolCallId, {
@ -359,7 +361,7 @@ async function processStreamingResponse(
const toolCalls = Array.from(toolCallsMap.values());
// Validate tool calls have complete arguments
const validToolCalls = toolCalls.filter((tc) => {
const preprocessedToolCalls = toolCalls.filter((tc) => {
if (!tc.arguments || !tc.name) {
logger.error("Incomplete tool call", {
id: tc.id,
@ -378,8 +380,8 @@ async function processStreamingResponse(
return {
content: aiResponse,
finalContent: finalContent,
toolCalls: validToolCalls,
shouldContinue: validToolCalls.length > 0,
toolCalls: preprocessedToolCalls,
shouldContinue: preprocessedToolCalls.length > 0,
};
}
@ -464,8 +466,70 @@ export async function streamChatResponse(
tool_calls: toolCallsForHistory,
});
// Execute tool calls
const availableTools: Tool[] =
toolCalls.length > 0 ? await getAvailableTools() : [];
// Run pre-permission args processing for tool calls
// If pre-processing fails we can just insert failure
// If it succeeds, we ask for permissions
const preProcessedToolCalls: PreprocessedToolCall[] = [];
for (const toolCall of toolCalls) {
const startTime = Date.now();
try {
const tool = availableTools.find((t) => t.name === toolCall.name);
if (!tool) {
throw new Error(`Tool ${toolCall.name} not found`);
}
validateToolCallArgsPresent(toolCall, tool);
const preprocessedCall: PreprocessedToolCall = {
...toolCall,
tool,
};
if (tool.preprocess) {
logger.debug("Preprocessing tool call args", {
name: toolCall.name,
arguments: toolCall.arguments,
});
const preprocessed = await tool.preprocess(toolCall.arguments);
preprocessedCall.preprocessResult = preprocessed;
}
preProcessedToolCalls.push(preprocessedCall);
} catch (error) {
if (callbacks?.onToolStart) {
callbacks.onToolStart(toolCall.name, toolCall.arguments);
}
const errorMessage = `Error processing tool call: ${
error instanceof Error ? error.message : String(error)
}`;
logger.error("Invalid tool call", {
name: toolCall.name,
error: errorMessage,
});
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
false,
duration,
errorMessage
);
chatHistory.push({
role: "tool",
tool_call_id: toolCall.id,
content: errorMessage,
});
if (callbacks?.onToolError) {
callbacks.onToolError(errorMessage, toolCall.name);
}
}
}
// Execute tool calls
for (const toolCall of preProcessedToolCalls) {
try {
logger.debug("Checking tool permissions", {
name: toolCall.name,
@ -473,11 +537,7 @@ export async function streamChatResponse(
});
// Check tool permissions
const permissionCheck = checkToolPermission({
name: toolCall.name,
arguments: toolCall.arguments,
});
const permissionCheck = checkToolPermission(toolCall);
// Notify tool start immediately - before permission check
// This ensures the UI shows the tool call even if it's rejected
@ -493,15 +553,17 @@ export async function streamChatResponse(
// Request permission from user
if (callbacks?.onToolPermissionRequest) {
// Use the proper toolPermissionManager API
const toolCallRequest = {
const toolCallRequest: ToolCallRequest = {
name: toolCall.name,
arguments: toolCall.arguments,
arguments:
toolCall.preprocessResult?.args ?? toolCall.arguments,
preview: toolCall.preprocessResult?.preview,
};
// Set up listener for permissionRequested event
const handlePermissionRequested = (event: {
requestId: string;
toolCall: { name: string; arguments: any };
toolCall: ToolCallRequest;
}) => {
if (event.toolCall.name === toolCall.name) {
toolPermissionManager.off(
@ -512,21 +574,21 @@ export async function streamChatResponse(
callbacks.onToolPermissionRequest!(
event.toolCall.name,
event.toolCall.arguments,
event.requestId
event.requestId,
event.toolCall.preview
);
}
};
toolPermissionManager.on(
"permissionRequested",
handlePermissionRequested
);
// Request permission using the proper API
const permissionResult = await toolPermissionManager.requestPermission(
toolCallRequest
);
const permissionResult =
await toolPermissionManager.requestPermission(toolCallRequest);
approved = permissionResult.approved;
} else {
// Fallback: deny if no UI callback available
@ -561,10 +623,7 @@ export async function streamChatResponse(
arguments: toolCall.arguments,
});
const toolResult = await executeToolCall({
name: toolCall.name,
arguments: toolCall.arguments,
});
const toolResult = await executeToolCall(toolCall);
chatHistory.push({
role: "tool",

View file

@ -46,6 +46,17 @@ export const fetchTool: Tool = {
},
},
readonly: true,
preprocess: async (args) => {
return {
preview: [
{
type: "text",
content: `Will fetch: ${args.url}`,
},
],
args,
};
},
run: async (args: { url: string; timeout?: number }): Promise<string> => {
const { url, timeout = 10000 } = args;

View file

@ -16,8 +16,7 @@ describe("formatToolCall", () => {
it("should format tool name without arguments", () => {
expect(formatToolCall("write_file")).toBe("Write");
expect(formatToolCall("read_file", {})).toBe("Read");
// edit_file doesn't exist, so it returns the original name
expect(formatToolCall("edit_file", null)).toBe("edit_file");
expect(formatToolCall("non_existent_tool", null)).toBe("non_existent_tool");
});
it("should format tool name with relative path argument", () => {
@ -31,9 +30,11 @@ describe("formatToolCall", () => {
it("should convert absolute paths to relative paths", () => {
expect(
formatToolCall("write_file", { filepath: "/Users/test/project/README.md" })
formatToolCall("write_file", {
filepath: "/Users/test/project/README.md",
})
).toBe("Write(README.md)");
expect(
formatToolCall("read_file", {
filepath: "/Users/test/project/src/components/App.tsx",
@ -79,7 +80,9 @@ describe("formatToolArgument", () => {
});
it("should convert absolute paths to relative", () => {
expect(formatToolArgument("/Users/test/project/README.md")).toBe("README.md");
expect(formatToolArgument("/Users/test/project/README.md")).toBe(
"README.md"
);
expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe(
"src/index.ts"
);
@ -95,4 +98,4 @@ describe("formatToolArgument", () => {
expect(formatToolArgument(true)).toBe("true");
expect(formatToolArgument({ key: "value" })).toBe("[object Object]");
});
});
});

View file

@ -7,15 +7,22 @@ import { fetchTool } from "./fetch.js";
import { listFilesTool } from "./listFiles.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js";
import { searchCodeTool } from "./searchCode.js";
import { type Tool, type ToolParameters } from "./types.js";
import {
type Tool,
type ToolParameters,
type ToolCall,
PreprocessedToolCall,
} from "./types.js";
import { writeFileTool } from "./writeFile.js";
export type { Tool, ToolParameters };
export type { Tool, ToolParameters, ToolCall };
const ALL_BUILTIN_TOOLS: Tool[] = [
readFileTool,
writeFileTool,
searchAndReplaceInFileTool,
listFilesTool,
searchCodeTool,
runTerminalCommandTool,
@ -110,12 +117,7 @@ function convertInputSchemaToParameters(inputSchema: any): ToolParameters {
return parameters;
}
export async function executeToolCall(toolCall: {
name: string;
arguments: Record<string, any>;
}): Promise<string> {
const startTime = Date.now();
export async function getAvailableTools() {
const args = parseArgs();
let mcpTools: Tool[] = [];
@ -148,32 +150,27 @@ export async function executeToolCall(toolCall: {
}
const allTools: Tool[] = [...BUILTIN_TOOLS, ...mcpTools];
return allTools;
}
const tool = allTools.find((t) => t.name === toolCall.name);
if (!tool) {
const duration = Date.now() - startTime;
telemetryService.logToolResult(
toolCall.name,
false,
duration,
`Tool "${toolCall.name}" not found`
);
return `Error: Tool "${toolCall.name}" not found`;
}
export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) {
for (const [paramName, paramDef] of Object.entries(tool.parameters)) {
if (
paramDef.required &&
(toolCall.arguments[paramName] === undefined ||
toolCall.arguments[paramName] === null)
) {
const duration = Date.now() - startTime;
const error = `Required parameter "${paramName}" missing for tool "${toolCall.name}"`;
telemetryService.logToolResult(toolCall.name, false, duration, error);
return `Error: ${error}`;
throw new Error(
`Required parameter "${paramName}" missing for tool "${toolCall.name}"`
);
}
}
}
export async function executeToolCall(
toolCall: PreprocessedToolCall
): Promise<string> {
const startTime = Date.now();
try {
logger.debug("Executing tool", {
@ -181,7 +178,11 @@ export async function executeToolCall(toolCall: {
arguments: toolCall.arguments,
});
const result = await tool.run(toolCall.arguments);
// IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args
// Preprocessed arg names may be different
const result = await toolCall.tool.run(
toolCall.preprocessResult?.args ?? toolCall.arguments
);
const duration = Date.now() - startTime;
telemetryService.logToolResult(

View file

@ -1,6 +1,7 @@
import * as fs from "fs";
import * as path from "path";
import { Tool } from "./types.js";
import { formatToolArgument } from "./formatters.js";
// List files in a directory
export const listFilesTool: Tool = {
@ -15,6 +16,19 @@ export const listFilesTool: Tool = {
},
},
readonly: true,
preprocess: async (args) => {
return {
args,
preview: [
{
type: "text",
content: args.directory
? `Will list files in: ${formatToolArgument(args.directory)}`
: "Will list files in current directory",
},
],
};
},
run: async (args: { dirpath: string }): Promise<string> => {
try {
if (!fs.existsSync(args.dirpath)) {
@ -41,4 +55,4 @@ export const listFilesTool: Tool = {
}`;
}
},
};
};

View file

@ -1,5 +1,6 @@
import * as fs from "fs";
import { Tool } from "./types.js";
import { formatToolCall } from "./formatters.js";
export const readFileTool: Tool = {
name: "read_file",
@ -13,6 +14,12 @@ export const readFileTool: Tool = {
},
},
readonly: true,
preprocess: async (args) => {
return {
args,
preview: [{ type: "text", content: formatToolCall("read_file", args) }],
};
},
run: async (args: { filepath: string }): Promise<string> => {
try {
if (!fs.existsSync(args.filepath)) {
@ -21,7 +28,9 @@ export const readFileTool: Tool = {
const content = fs.readFileSync(args.filepath, "utf-8");
return `Content of ${args.filepath}:\n${content}`;
} catch (error) {
return `Error reading file: ${error instanceof Error ? error.message : String(error)}`;
return `Error reading file: ${
error instanceof Error ? error.message : String(error)
}`;
}
},
};
};

View file

@ -18,6 +18,21 @@ export const runTerminalCommandTool: Tool = {
},
},
readonly: false,
preprocess: async (args) => {
const truncatedCmd =
args.command.length > 60
? args.command.substring(0, 60) + "..."
: args.command;
return {
args,
preview: [
{
type: "text",
content: `Will run: ${truncatedCmd}`,
},
],
};
},
run: async ({ command }: { command: string }): Promise<string> => {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {

View file

@ -3,12 +3,12 @@ import { parseAllSearchReplaceBlocks } from "./parseBlock.js";
import { Tool } from "../types.js";
import { generateDiff } from "../writeFile.js";
import * as fs from "fs";
import * as path from "path";
import telemetryService from "../../telemetry/telemetryService.js";
import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../../telemetry/utils.js";
import { parseSearchAndReplaceArgs } from "./parseArgs.js";
export interface SearchAndReplaceInFileArgs {
filepath: string;
@ -89,87 +89,87 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a
required: true,
},
},
preprocess: async (args) => {
// Get and validate args
const { filepath, diffs } = parseSearchAndReplaceArgs(args);
// Get current file contents
if (!fs.existsSync(filepath)) {
throw new Error(`file ${filepath} does not exist`);
}
const oldContent = fs.readFileSync(filepath, "utf-8");
let newContent = oldContent;
// Parse blocks
const blocks = diffs.map(parseAllSearchReplaceBlocks).flat();
if (blocks.length === 0) {
throw new Error("No complete search/replace blocks found in any diffs");
}
// Apply all replacements sequentially to build the final content
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const { searchContent, replaceContent } = block;
if (typeof searchContent === "undefined") {
throw new Error(`No search content defined for block ${i + 1}`);
}
if (typeof replaceContent === "undefined") {
throw new Error(`No replace content defined for block ${i + 1}`);
}
const match = findSearchMatch(newContent, searchContent);
if (!match) {
throw new Error(
`Search content not found in block ${i + 1}:\n${searchContent}`
);
}
newContent =
newContent.substring(0, match.startIndex) +
replaceContent +
newContent.substring(match.endIndex);
}
// Get lines for telemetry
const { added, removed } = calculateLinesOfCodeDiff(oldContent, newContent);
const language = getLanguageFromFilePath(filepath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
}
if (removed > 0) {
telemetryService.recordLinesOfCodeModified("removed", removed, language);
}
const diff = generateDiff(oldContent, newContent, filepath);
return {
args: {
filepath,
newContent,
},
preview: [
{
type: "text",
content: "",
},
{
type: "diff",
content: diff,
},
],
};
},
run: async (args) => {
try {
// Get and validate args
const { filepath, diffs } = args;
if (!filepath || !diffs) {
throw new Error("filepath and diffs args are required");
}
if (typeof filepath !== "string") {
throw new Error("filepath must be a string");
}
if (
!Array.isArray(diffs) ||
diffs.some((diff) => typeof diff !== "string")
) {
throw new Error(
"diffs must be an array of string search/replace blocks"
);
}
// Get current file contents
const fixedPath = filepath.replace(/\/|\\/g, path.sep);
if (!fs.existsSync(fixedPath)) {
throw new Error(`file ${filepath} does not exist`);
}
const oldContent = fs.readFileSync(fixedPath, "utf-8");
let newContent = oldContent;
// Parse blocks
const blocks = diffs.map(parseAllSearchReplaceBlocks).flat();
if (blocks.length === 0) {
throw new Error("No complete search/replace blocks found in any diffs");
}
// Apply all replacements sequentially to build the final content
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
const { searchContent, replaceContent } = block;
const match = findSearchMatch(newContent, searchContent || "");
if (!match) {
throw new Error(
`Search content not found in block ${i + 1}:\n${searchContent}`
);
}
newContent =
newContent.substring(0, match.startIndex) +
(replaceContent || "") +
newContent.substring(match.endIndex);
}
// Get lines for telemetry
const { added, removed } = calculateLinesOfCodeDiff(
oldContent,
args.content
);
const language = getLanguageFromFilePath(args.filepath);
if (added > 0) {
telemetryService.recordLinesOfCodeModified("added", added, language);
}
if (removed > 0) {
telemetryService.recordLinesOfCodeModified(
"removed",
removed,
language
);
}
const diff = generateDiff(oldContent, args.content, args.filepath);
fs.writeFileSync(args.filepath, args.newContent, "utf-8");
// Record file operation
return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`;
return `Successfully edited ${args.filepath}`;
} catch (error) {
throw new Error(
`Failed to apply search and replace: ${
`Failed to edit ${args.filepath}:\n ${
error instanceof Error ? error.message : String(error)
}`
);

View file

@ -0,0 +1,34 @@
import * as path from "path";
export function parseSearchAndReplaceArgs(args: any): {
filepath: string;
diffs: string[];
} {
const { filepath, diffs: diffsArg } = args;
if (!filepath || !diffsArg) {
throw new Error("filepath and diffs args are required");
}
if (typeof filepath !== "string") {
throw new Error("filepath must be a string");
}
const diffs: string[] = [];
if (!Array.isArray(diffsArg)) {
throw new Error("diffs must be an array of string search/replace blocks");
}
diffsArg.forEach((diff, i) => {
if (typeof diff !== "string") {
throw new Error(`Diff at ${i + 1} is not a string`);
}
diffs.push(diff);
});
const fixedPath = filepath.replace(/\/|\\/g, path.sep);
return {
filepath: fixedPath,
diffs,
};
}

View file

@ -30,6 +30,21 @@ export const searchCodeTool: Tool = {
},
},
readonly: true,
preprocess: async (args) => {
const truncatedPattern =
args.pattern.length > 50
? args.pattern.substring(0, 50) + "..."
: args.pattern;
return {
args,
preview: [
{
type: "text",
content: `Will search for: "${truncatedPattern}"`,
},
],
};
},
run: async (args: {
pattern: string;
path?: string;
@ -56,7 +71,9 @@ export const searchCodeTool: Tool = {
}
if (!stdout.trim()) {
return `No matches found for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}.`;
return `No matches found for pattern "${args.pattern}"${
args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""
}.`;
}
// Split the results into lines and limit the number of results
@ -65,20 +82,28 @@ export const searchCodeTool: Tool = {
const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS);
const resultText = limitedLines.join("\n");
const truncationMessage = truncated
? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]`
const truncationMessage = truncated
? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]`
: "";
return `Search results for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}:\n\n${resultText}${truncationMessage}`;
return `Search results for pattern "${args.pattern}"${
args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""
}:\n\n${resultText}${truncationMessage}`;
} catch (error: any) {
if (error.code === 1) {
return `No matches found for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}.`;
return `No matches found for pattern "${args.pattern}"${
args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""
}.`;
}
return `Error executing ripgrep: ${error instanceof Error ? error.message : String(error)}`;
return `Error executing ripgrep: ${
error instanceof Error ? error.message : String(error)
}`;
}
} catch (error) {
return `Error searching code: ${error instanceof Error ? error.message : String(error)}`;
return `Error searching code: ${
error instanceof Error ? error.message : String(error)
}`;
}
},
};
};

View file

@ -10,11 +10,37 @@ export type ToolParameters = Record<
}
>;
export interface ToolCallPreview {
type: "text" | "diff";
content: string;
color?: string;
paddingLeft?: number;
}
export interface PreprocessToolCallResult {
preview?: ToolCallPreview[];
args: Record<string, any>;
}
export interface Tool {
name: string;
displayName: string;
description: string;
parameters: ToolParameters;
preprocess?: (args: any) => Promise<PreprocessToolCallResult>;
run: (args: any) => Promise<string>;
readonly?: boolean; // Indicates if the tool is readonly
}
export interface ToolCall {
id: string;
name: string;
arguments: any;
argumentsStr: string;
startNotified: boolean;
}
export interface PreprocessedToolCall extends ToolCall {
tool: Tool;
preprocessResult?: PreprocessToolCallResult;
}

View file

@ -18,6 +18,17 @@ export const viewDiffTool: Tool = {
},
},
readonly: true,
preprocess: async (args) => {
return {
args,
preview: [
{
type: "text",
content: "Will show git diff",
},
],
};
},
run: async (args: { path?: string }): Promise<string> => {
try {
const repoPath = args.path || process.cwd();
@ -47,7 +58,9 @@ export const viewDiffTool: Tool = {
return `Git diff for repository at ${repoPath}:\n\n${stdout}`;
} catch (error) {
return `Error running git diff: ${error instanceof Error ? error.message : String(error)}`;
return `Error running git diff: ${
error instanceof Error ? error.message : String(error)
}`;
}
},
};
};

View file

@ -6,7 +6,7 @@ import {
calculateLinesOfCodeDiff,
getLanguageFromFilePath,
} from "../telemetry/utils.js";
import { Tool } from "./types.js";
import { Tool, ToolCallPreview } from "./types.js";
export function generateDiff(
oldContent: string,
@ -41,6 +41,65 @@ export const writeFileTool: Tool = {
},
},
readonly: false,
preprocess: async (args) => {
try {
if (fs.existsSync(args.filepath)) {
const oldContent = fs.readFileSync(args.filepath, "utf-8");
const newContent = args.content;
const diff = createTwoFilesPatch(
args.filepath,
args.filepath,
oldContent,
newContent,
undefined,
undefined,
{ context: 2 }
);
return {
args,
preview: [
{
type: "text",
content: "Preview of changes:",
},
{
type: "diff",
content: diff,
},
],
};
}
} catch (e) {
// do nothing
}
const lines: string[] = args.content.split("\n");
const previewLines = lines.slice(0, 3);
const preview: ToolCallPreview[] = [
{
type: "text",
content: "New file content:",
},
...previewLines.map((line) => ({
type: "text" as const,
content: line || " ",
paddingLeft: 2,
})),
];
if (lines.length > 3) {
preview.push({
type: "text",
content: `... (${lines.length - 3} more lines)`,
});
}
return {
args,
preview,
};
},
run: async (args: { filepath: string; content: string }): Promise<string> => {
try {
const dirPath = path.dirname(args.filepath);
@ -76,11 +135,7 @@ export const writeFileTool: Tool = {
);
}
const diff = generateDiff(oldContent, args.content, args.filepath);
// Record file operation
return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`;
return `Successfully wrote to file: ${args.filepath}`;
} else {
// New file creation - count all lines as added
const lineCount = args.content.split("\n").length;

View file

@ -361,6 +361,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
toolName={activePermissionRequest.toolName}
toolArgs={activePermissionRequest.toolArgs}
requestId={activePermissionRequest.requestId}
toolCallPreview={activePermissionRequest.toolCallPreview}
onResponse={handleToolPermissionResponse}
/>
) : (

View file

@ -1,7 +1,8 @@
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
import { formatToolCall } from "../../tools/formatters.js";
import { DetailedToolPreview, ToolPreview } from "./ToolPreview.js";
import { ToolPreview } from "./ToolPreview.js";
import { ToolCallPreview } from "../../tools/types.js";
interface PermissionOption {
id: string;
@ -15,6 +16,7 @@ interface ToolPermissionSelectorProps {
toolName: string;
toolArgs: any;
requestId: string;
toolCallPreview?: ToolCallPreview[];
onResponse: (
requestId: string,
approved: boolean,
@ -38,6 +40,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
toolName,
toolArgs,
requestId,
toolCallPreview,
onResponse,
}) => {
const [selectedIndex, setSelectedIndex] = useState(0);
@ -102,12 +105,13 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
{/* Show preview of what the tool will do */}
<Box marginTop={1}>
<ToolPreview toolName={toolName} toolArgs={toolArgs} />
<ToolPreview
toolName={toolName}
toolArgs={toolArgs}
toolCallPreview={toolCallPreview}
/>
</Box>
{/* Show detailed preview if available */}
<DetailedToolPreview toolName={toolName} toolArgs={toolArgs} />
<Box marginTop={1} flexDirection="column">
<Text color="dim">Would you like to continue?</Text>
{PERMISSION_OPTIONS.map((option, index) => {

View file

@ -1,12 +1,12 @@
import { createTwoFilesPatch } from "diff";
import * as fs from "fs";
import { Box, Text } from "ink";
import React from "react";
import { formatToolCall, formatToolArgument } from "../../tools/formatters.js";
import { formatToolCall } from "../../tools/formatters.js";
import { getToolDisplayName } from "../../tools.js";
import { ColoredDiff } from "../ColoredDiff.js";
import { ToolCallPreview } from "../../tools/types.js";
interface ToolPreviewProps {
toolCallPreview?: ToolCallPreview[];
toolName: string;
toolArgs: any;
}
@ -15,149 +15,39 @@ interface ToolPreviewProps {
* Generates a preview of what a tool will do based on its arguments
*/
export const ToolPreview: React.FC<ToolPreviewProps> = ({
toolCallPreview,
toolName,
toolArgs,
}) => {
const getPreview = () => {
// For tool calls that match the standard format, use formatToolCall
if (toolName === "read_file" || toolName === "write_file" || toolName === "edit_file") {
return formatToolCall(toolName, toolArgs);
}
switch (toolName) {
case "list_files":
if (toolArgs.directory) {
return `Will list files in: ${formatToolArgument(toolArgs.directory)}`;
}
return "Will list files in current directory";
case "search_code":
if (toolArgs.pattern) {
const truncatedPattern =
toolArgs.pattern.length > 50
? toolArgs.pattern.substring(0, 50) + "..."
: toolArgs.pattern;
return `Will search for: "${truncatedPattern}"`;
}
return "Will search the codebase";
case "run_terminal_command":
if (toolArgs.command) {
const truncatedCmd =
toolArgs.command.length > 60
? toolArgs.command.substring(0, 60) + "..."
: toolArgs.command;
return `Will run: ${truncatedCmd}`;
}
return "Will run a terminal command";
case "fetch":
if (toolArgs.url) {
return `Will fetch: ${toolArgs.url}`;
}
return "Will fetch from a URL";
case "view_diff":
return "Will show git diff";
default:
// For unknown tools, show what args will be passed
const argCount = Object.keys(toolArgs || {}).length;
if (argCount > 0) {
return `Will call ${getToolDisplayName(
toolName
)} with ${argCount} argument${argCount !== 1 ? "s" : ""}`;
}
return `Will call ${getToolDisplayName(toolName)}`;
}
};
return (
<Box>
<Text color="gray">⎿ </Text>
<Text color="gray">{getPreview()}</Text>
</Box>
);
};
/**
* Shows a detailed preview for tools where we can predict the output
*/
export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({
toolName,
toolArgs,
}) => {
// For edit operations, we could show a diff preview if we have old_string/new_string
if (toolName === "edit_file" && toolArgs.old_string && toolArgs.new_string) {
if (toolCallPreview) {
return (
<Box flexDirection="column" marginTop={1}>
<Box flexDirection="column" paddingLeft={2}>
<Text color="red">- {toolArgs.old_string.split("\n")[0]}</Text>
<Text color="green">+ {toolArgs.new_string.split("\n")[0]}</Text>
{(toolArgs.old_string.split("\n").length > 1 ||
toolArgs.new_string.split("\n").length > 1) && (
<Text color="gray"> ...</Text>
)}
</Box>
<Box display={"flex"} flexDirection="column" marginTop={1}>
{toolCallPreview.map((preview, index) => {
if (preview.type === "text") {
return (
<Box key={index} paddingLeft={preview.paddingLeft ?? 0}>
{index === 0 && <Text color="gray">⎿ </Text>}
<Text color={preview.color ?? "gray"}>{preview.content}</Text>
</Box>
);
} else {
return <ColoredDiff key={index} diffContent={preview.content} />;
}
})}
</Box>
);
}
// For write operations, show diff preview if file exists
if (toolName === "write_file" && toolArgs.filepath && toolArgs.content) {
try {
if (fs.existsSync(toolArgs.filepath)) {
const oldContent = fs.readFileSync(toolArgs.filepath, "utf-8");
const newContent = toolArgs.content;
// Generate a diff preview
const diff = createTwoFilesPatch(
toolArgs.filepath,
toolArgs.filepath,
oldContent,
newContent,
undefined,
undefined,
{ context: 2 }
);
return (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">Preview of changes:</Text>
<ColoredDiff diffContent={diff} />
</Box>
);
} else {
// New file - show content preview
const lines = toolArgs.content.split("\n");
const preview = lines.slice(0, 3);
return (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">New file content:</Text>
<Box flexDirection="column" paddingLeft={2}>
{preview.map((line: string, i: number) => (
<Text key={i} color="green">
{line || " "}
</Text>
))}
{lines.length > 3 && (
<Text color="gray">... ({lines.length - 3} more lines)</Text>
)}
</Box>
</Box>
);
}
} catch (error) {
// If we can't read the file, just show a simple preview
const lines = toolArgs.content.split("\n");
return (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">Content preview ({lines.length} lines)</Text>
</Box>
);
}
let message = `Will call ${getToolDisplayName(toolName)}`;
const argCount = Object.keys(toolArgs || {}).length;
if (argCount > 0) {
message += ` with ${argCount} argument${argCount !== 1 ? "s" : ""}`;
}
return null;
return (
<Box>
<Text color="gray">⎿ </Text>
<Text color="gray">{message}</Text>
</Box>
);
};

View file

@ -18,6 +18,7 @@ import logger from "../../util/logger.js";
import { initializeChatHistory } from "../../commands/chat.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { DisplayMessage } from "../types.js";
import { ToolCallPreview } from "../../tools/types.js";
interface UseChatProps {
assistant?: AssistantUnrolled;
@ -115,6 +116,7 @@ export function useChat({
toolName: string;
toolArgs: any;
requestId: string;
toolCallPreview?: ToolCallPreview[];
} | null>(null);
// Remote mode polling
@ -557,13 +559,15 @@ export function useChat({
onToolPermissionRequest: (
toolName: string,
toolArgs: any,
requestId: string
requestId: string,
toolCallPreview?: ToolCallPreview[]
) => {
// Set the active permission request to show the selector
setActivePermissionRequest({
toolName,
toolArgs,
requestId,
toolCallPreview,
});
},
};