diff --git a/AGENTS.md b/AGENTS.md index 28f7e75e3..936c4e7d7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,6 +71,7 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev - Outputs to `dist/` directory - Source maps and inline sources enabled - JSX support for React components +- Relative import paths require explicit file extensions, e.g. 'from "./test.js"' instead of 'from "./test"' ### Important rules diff --git a/src/streamChatResponse.test.ts b/src/streamChatResponse.test.ts deleted file mode 100644 index 4fa3a6bba..000000000 --- a/src/streamChatResponse.test.ts +++ /dev/null @@ -1,282 +0,0 @@ -import { describe, expect, it, jest } from "@jest/globals"; -import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs"; - -// Test the chunk processing logic that was identified as buggy -describe("streamChatResponse - chunk ordering bug", () => { - // Helper to create a chunk with content - function contentChunk(content: string): ChatCompletionChunk { - return { - id: "test", - object: "chat.completion.chunk", - created: Date.now(), - model: "test-model", - choices: [{ - index: 0, - delta: { content }, - finish_reason: null, - }], - }; - } - - // Helper to create a chunk with tool call - function toolCallChunk( - id: string, - name?: string, - args?: string - ): ChatCompletionChunk { - return { - id: "test", - object: "chat.completion.chunk", - created: Date.now(), - model: "test-model", - choices: [{ - index: 0, - delta: { - tool_calls: [{ - index: 0, - id, - type: "function", - function: { - name: name || undefined, - arguments: args || undefined, - }, - }], - }, - finish_reason: null, - }], - }; - } - - // Simulate the chunk processing logic from streamChatResponse.ts - function processChunks(chunks: ChatCompletionChunk[]): { - content: string; - finalContent: string; - hasToolCalls: boolean; - toolCallsMap: Map; - } { - let aiResponse = ""; - const toolCallsMap = new Map(); - const indexToIdMap = new Map(); // Track index to ID mapping - let hasToolCalls = false; - - for (const chunk of chunks) { - if (!chunk.choices || !chunk.choices[0]) continue; - - const choice = chunk.choices[0]; - if (!choice.delta) continue; - - // Handle content - if (choice.delta.content) { - aiResponse += choice.delta.content; - } - - // Handle tool calls - if (choice.delta.tool_calls) { - 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; - if (toolCallDelta.index !== undefined) { - indexToIdMap.set(toolCallDelta.index, toolCallId); - } - - // Create tool call entry if it doesn't exist - if (!toolCallsMap.has(toolCallId)) { - toolCallsMap.set(toolCallId, { - id: toolCallId, - name: "", - argumentsStr: "", - }); - } - } else if (toolCallDelta.index !== undefined) { - // No ID, but we have an index - look up the ID from our map - toolCallId = indexToIdMap.get(toolCallDelta.index); - } - - if (!toolCallId) continue; - - const toolCall = toolCallsMap.get(toolCallId); - if (!toolCall) continue; - - if (toolCallDelta.function?.name) { - toolCall.name = toolCallDelta.function.name; - } - - if (toolCallDelta.function?.arguments) { - toolCall.argumentsStr += toolCallDelta.function.arguments; - } - } - } - } - - // The fixed behavior: always preserve content - const finalContent = aiResponse; - - return { - content: aiResponse, - finalContent: finalContent, - hasToolCalls, - toolCallsMap, - }; - } - - it("content after tool calls is preserved", () => { - const chunks = [ - contentChunk(""), - toolCallChunk("call_123", "read_file", '{"filepath": "/README.md"}'), - contentChunk(""), - contentChunk("I'll read the README file for you."), - ]; - - const result = processChunks(chunks); - - expect(result.content).toBe("I'll read the README file for you."); - expect(result.hasToolCalls).toBe(true); - - // Fixed: finalContent now preserves the content - expect(result.finalContent).toBe("I'll read the README file for you."); - }); - - it("content before tool calls is preserved", () => { - const chunks = [ - contentChunk("Let me search for that. "), - toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), - ]; - - const result = processChunks(chunks); - - expect(result.content).toBe("Let me search for that. "); - expect(result.hasToolCalls).toBe(true); - - // Fixed: finalContent preserves content before tool calls - expect(result.finalContent).toBe("Let me search for that. "); - }); - - it("handles the exact problematic sequence from the logs", () => { - const chunks = [ - contentChunk(""), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "read_file", ""), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '{"filepath'), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '": "/Use'), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'rs/nate/gh/c'), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'ontinuede'), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, 'v/cli/README'), - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), - contentChunk(""), - contentChunk("I'll read the README file for you."), - ]; - - const result = processChunks(chunks); - - expect(result.content).toBe("I'll read the README file for you."); - expect(result.hasToolCalls).toBe(true); - - // Fixed: content is preserved - expect(result.finalContent).toBe("I'll read the README file for you."); - }); - - it("shows content works fine without tool calls", () => { - const chunks = [ - contentChunk("Hello "), - contentChunk("world!"), - ]; - - const result = processChunks(chunks); - - expect(result.content).toBe("Hello world!"); - expect(result.hasToolCalls).toBe(false); - - // Without tool calls, finalContent is correct - expect(result.finalContent).toBe("Hello world!"); - }); - - // Helper to create a tool call chunk with optional ID - function toolCallChunkWithIndex( - index: number, - id?: string, - name?: string, - args?: string - ): ChatCompletionChunk { - const toolCall: any = { - index, - type: "function" as const, - function: {} - }; - - if (id) toolCall.id = id; - if (name) toolCall.function.name = name; - if (args !== undefined) toolCall.function.arguments = args; - - return { - id: "test", - object: "chat.completion.chunk" as const, - created: Date.now(), - model: "test-model", - choices: [{ - index: 0, - delta: { tool_calls: [toolCall] }, - finish_reason: null, - }], - }; - } - - it("handles provider that only sends tool ID in first chunk then uses index", () => { - // Create chunks that simulate a provider sending ID only in first chunk - const chunks = [ - contentChunk("I'll read the README.md file for you and then say hello!"), - // First chunk has ID - toolCallChunkWithIndex(0, "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", "read_file", ""), - // Subsequent chunks only have index, no ID - toolCallChunkWithIndex(0, undefined, undefined, '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'), - ]; - - const result = processChunks(chunks); - - // Content is captured correctly - expect(result.content).toBe("I'll read the README.md file for you and then say hello!"); - expect(result.hasToolCalls).toBe(true); - - // Fixed: finalContent preserves content - expect(result.finalContent).toBe("I'll read the README.md file for you and then say hello!"); - - // Fixed: tool call arguments are preserved using index mapping - const toolCalls = Array.from(result.toolCallsMap.values()); - expect(toolCalls).toHaveLength(1); - expect(toolCalls[0].argumentsStr).toBe('{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'); - }); - - it("handles realistic fragmented arguments from index-based provider", () => { - // Simulate the exact sequence from the user's logs with fragmented JSON - const chunks = [ - contentChunk("I'll read the README.md file for you and then say hello!"), - // First chunk has ID - toolCallChunkWithIndex(0, "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", "read_file", ""), - // Subsequent chunks fragment the JSON arguments - toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), - toolCallChunkWithIndex(0, undefined, undefined, 'th"'), - toolCallChunkWithIndex(0, undefined, undefined, ': '), - toolCallChunkWithIndex(0, undefined, undefined, '"/U'), - toolCallChunkWithIndex(0, undefined, undefined, 'sers/nate/gh'), - toolCallChunkWithIndex(0, undefined, undefined, '/c'), - toolCallChunkWithIndex(0, undefined, undefined, 'onti'), - toolCallChunkWithIndex(0, undefined, undefined, 'nuedev/cli'), - toolCallChunkWithIndex(0, undefined, undefined, '/READ'), - toolCallChunkWithIndex(0, undefined, undefined, 'ME.m'), - toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), - ]; - - const result = processChunks(chunks); - - // Fixed: Both issues are resolved - // 1. Content is preserved - expect(result.finalContent).toBe("I'll read the README.md file for you and then say hello!"); - - // 2. Tool call arguments are assembled correctly - const toolCalls = Array.from(result.toolCallsMap.values()); - expect(toolCalls[0].argumentsStr).toBe('{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}'); - }); - -}); \ No newline at end of file diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index daaebfb8a..f774836b2 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -6,6 +6,7 @@ import type { ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, + ChatCompletionToolMessageParam, } from "openai/resources.mjs"; import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; @@ -126,7 +127,7 @@ function getDefaultCompletionOptions( } // Process a single streaming response and return whether we need to continue -async function processStreamingResponse( +export async function processStreamingResponse( chatHistory: ChatCompletionMessageParam[], model: ModelConfig, llmApi: BaseLlmApi, @@ -168,7 +169,6 @@ async function processStreamingResponse( let firstTokenTime: number | null = null; let inputTokens = 0; let outputTokens = 0; - let hasToolCalls = false; try { const streamWithBackoff = withExponentialBackoff( @@ -236,7 +236,6 @@ async function processStreamingResponse( // Handle tool calls if (choice.delta.tool_calls) { - hasToolCalls = true; for (const toolCallDelta of choice.delta.tool_calls) { let toolCallId: string | undefined; @@ -361,7 +360,7 @@ async function processStreamingResponse( const toolCalls = Array.from(toolCallsMap.values()); // Validate tool calls have complete arguments - const preprocessedToolCalls = toolCalls.filter((tc) => { + const validToolCalls = toolCalls.filter((tc) => { if (!tc.arguments || !tc.name) { logger.error("Incomplete tool call", { id: tc.id, @@ -380,11 +379,238 @@ async function processStreamingResponse( return { content: aiResponse, finalContent: finalContent, - toolCalls: preprocessedToolCalls, - shouldContinue: preprocessedToolCalls.length > 0, + toolCalls: validToolCalls, + shouldContinue: validToolCalls.length > 0, }; } +/** + * Processes tool calls by validating and preprocessing them + * @param toolCalls - The raw tool calls from the LLM + * @param callbacks - Optional callbacks for notifying of events + * @returns - Preprocessed tool calls that are ready for execution + */ +export async function preprocessStreamedToolCalls( + toolCalls: ToolCall[], + callbacks?: StreamCallbacks +): Promise<{ + preprocessedCalls: PreprocessedToolCall[]; + chatHistoryEntries: { role: "tool"; tool_call_id: string; content: string }[]; +}> { + const preprocessedCalls: PreprocessedToolCall[] = []; + const chatHistoryEntries: { + role: "tool"; + tool_call_id: string; + content: string; + }[] = []; + + // Get all available tools + const availableTools: Tool[] = await getAvailableTools(); + + // Process each tool call + 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; + } + + preprocessedCalls.push(preprocessedCall); + } catch (error) { + // Notify the UI about the tool start, even though it failed + 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 + ); + + // Add error to chat history + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: errorMessage, + }); + + // Notify about the error + if (callbacks?.onToolError) { + callbacks.onToolError(errorMessage, toolCall.name); + } + } + } + + return { preprocessedCalls, chatHistoryEntries }; +} + +/** + * Executes preprocessed tool calls, handling permissions and results + * @param preprocessedCalls - The preprocessed tool calls ready for execution + * @param callbacks - Optional callbacks for notifying of events + * @returns - Chat history entries with tool results + */ +export async function executeStreamedToolCalls( + preprocessedCalls: PreprocessedToolCall[], + callbacks?: StreamCallbacks +): Promise { + const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; + + // Execute each preprocessed tool call + for (const toolCall of preprocessedCalls) { + try { + logger.debug("Checking tool permissions", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + // Notify tool start - before permission check + // This ensures the UI shows the tool call even if it's rejected + if (callbacks?.onToolStart) { + callbacks.onToolStart(toolCall.name, toolCall.arguments); + } + + // Check tool permissions + const permissionCheck = checkToolPermission(toolCall); + let approved = false; + + if (permissionCheck.permission === "allow") { + approved = true; + } else if (permissionCheck.permission === "ask") { + // Request permission from user + if (callbacks?.onToolPermissionRequest) { + // Use the proper toolPermissionManager API + const toolCallRequest: ToolCallRequest = { + name: toolCall.name, + arguments: toolCall.preprocessResult?.args ?? toolCall.arguments, + preview: toolCall.preprocessResult?.preview, + }; + + // Set up listener for permissionRequested event + const handlePermissionRequested = (event: { + requestId: string; + toolCall: ToolCallRequest; + }) => { + if (event.toolCall.name === toolCall.name) { + toolPermissionManager.off( + "permissionRequested", + handlePermissionRequested + ); + // Notify UI about permission request + callbacks.onToolPermissionRequest!( + event.toolCall.name, + event.toolCall.arguments, + event.requestId, + event.toolCall.preview + ); + } + }; + + toolPermissionManager.on( + "permissionRequested", + handlePermissionRequested + ); + + // Request permission using the proper API + const permissionResult = + await toolPermissionManager.requestPermission(toolCallRequest); + + approved = permissionResult.approved; + } else { + // Fallback: deny if no UI callback available + approved = false; + } + } + + if (!approved) { + const deniedMessage = `Permission denied by user`; + logger.info("Tool call denied", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: deniedMessage, + }); + + if (callbacks?.onToolResult) { + callbacks.onToolResult(deniedMessage, toolCall.name); + } + continue; + } + + logger.debug("Executing tool", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + + const toolResult = await executeToolCall(toolCall); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: toolResult, + }); + + if (callbacks?.onToolResult) { + callbacks.onToolResult(toolResult, toolCall.name); + } + } catch (error) { + const errorMessage = `Error executing tool ${toolCall.name}: ${ + error instanceof Error ? error.message : String(error) + }`; + + logger.error("Tool execution failed", { + name: toolCall.name, + error: errorMessage, + }); + + chatHistoryEntries.push({ + role: "tool", + tool_call_id: toolCall.id, + content: errorMessage, + }); + + if (callbacks?.onToolError) { + callbacks.onToolError(errorMessage, toolCall.name); + } + } + } + + return chatHistoryEntries; +} + // Main function that handles the conversation loop export async function streamChatResponse( chatHistory: ChatCompletionMessageParam[], @@ -415,7 +641,7 @@ export async function streamChatResponse( logger.debug("Starting conversation iteration"); // Get response from LLM - const { content, finalContent, toolCalls, shouldContinue } = + const { content, toolCalls, shouldContinue } = await processStreamingResponse( chatHistory, model, @@ -466,194 +692,24 @@ export async function streamChatResponse( tool_calls: toolCallsForHistory, }); - const availableTools: Tool[] = - toolCalls.length > 0 ? await getAvailableTools() : []; + // First preprocess the tool calls + const { preprocessedCalls, chatHistoryEntries: preprocessErrors } = + await preprocessStreamedToolCalls(toolCalls, callbacks); - // 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); - } - } + // Add any preprocessing errors to chat history + for (const entry of preprocessErrors) { + chatHistory.push(entry); } - // Execute tool calls - for (const toolCall of preProcessedToolCalls) { - try { - logger.debug("Checking tool permissions", { - name: toolCall.name, - arguments: toolCall.arguments, - }); + // Execute the valid preprocessed tool calls + const toolResults = await executeStreamedToolCalls( + preprocessedCalls, + callbacks + ); - // Check tool permissions - const permissionCheck = checkToolPermission(toolCall); - - // Notify tool start immediately - before permission check - // This ensures the UI shows the tool call even if it's rejected - if (callbacks?.onToolStart) { - callbacks.onToolStart(toolCall.name, toolCall.arguments); - } - - let approved = false; - - if (permissionCheck.permission === "allow") { - approved = true; - } else if (permissionCheck.permission === "ask") { - // Request permission from user - if (callbacks?.onToolPermissionRequest) { - // Use the proper toolPermissionManager API - const toolCallRequest: ToolCallRequest = { - name: toolCall.name, - arguments: - toolCall.preprocessResult?.args ?? toolCall.arguments, - preview: toolCall.preprocessResult?.preview, - }; - - // Set up listener for permissionRequested event - const handlePermissionRequested = (event: { - requestId: string; - toolCall: ToolCallRequest; - }) => { - if (event.toolCall.name === toolCall.name) { - toolPermissionManager.off( - "permissionRequested", - handlePermissionRequested - ); - // Notify UI about permission request - callbacks.onToolPermissionRequest!( - event.toolCall.name, - event.toolCall.arguments, - event.requestId, - event.toolCall.preview - ); - } - }; - - toolPermissionManager.on( - "permissionRequested", - handlePermissionRequested - ); - - // Request permission using the proper API - const permissionResult = - await toolPermissionManager.requestPermission(toolCallRequest); - - approved = permissionResult.approved; - } else { - // Fallback: deny if no UI callback available - approved = false; - } - } else if (permissionCheck.permission === "exclude") { - // This shouldn't happen as excluded tools are filtered out earlier - approved = false; - } - - if (!approved) { - const deniedMessage = `Permission denied by user`; - logger.info("Tool call denied", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - - chatHistory.push({ - role: "tool", - tool_call_id: toolCall.id, - content: deniedMessage, - }); - - if (callbacks?.onToolResult) { - callbacks.onToolResult(deniedMessage, toolCall.name); - } - continue; - } - - logger.debug("Executing tool", { - name: toolCall.name, - arguments: toolCall.arguments, - }); - - const toolResult = await executeToolCall(toolCall); - - chatHistory.push({ - role: "tool", - tool_call_id: toolCall.id, - content: toolResult, - }); - - if (callbacks?.onToolResult) { - callbacks.onToolResult(toolResult, toolCall.name); - } - } catch (error) { - const errorMessage = `Error executing tool ${toolCall.name}: ${ - error instanceof Error ? error.message : String(error) - }`; - - logger.error("Tool execution failed", { - name: toolCall.name, - error: errorMessage, - }); - - chatHistory.push({ - role: "tool", - tool_call_id: toolCall.id, - content: errorMessage, - }); - - if (callbacks?.onToolError) { - callbacks.onToolError(errorMessage, toolCall.name); - } - } + // Add tool results to chat history + for (const entry of toolResults) { + chatHistory.push(entry); } } else if (content) { // Just content, no tools diff --git a/src/streamChatResponse.vitest.ts b/src/streamChatResponse.vitest.ts new file mode 100644 index 000000000..2beee08a2 --- /dev/null +++ b/src/streamChatResponse.vitest.ts @@ -0,0 +1,639 @@ +import { describe, expect, it, vi, beforeEach } from "vitest"; +import type { + ChatCompletionChunk, + ChatCompletionMessageParam, +} from "openai/resources/chat/completions.mjs"; +import { + preprocessStreamedToolCalls, + executeStreamedToolCalls, + processStreamingResponse, +} from "./streamChatResponse.js"; +import { ToolCall } from "./tools/index.js"; +import { PreprocessedToolCall } from "./tools/types.js"; +import { toolPermissionManager } from "./permissions/permissionManager.js"; +import { readFileTool } from "./tools/readFile.js"; +import { searchCodeTool } from "./tools/searchCode.js"; +import { writeFileTool } from "./tools/writeFile.js"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { ModelConfig } from "@continuedev/config-yaml"; + +vi.mock("./util/logger"); +vi.mock("./telemetry/telemetryService"); + +// Test the chunk processing logic that was identified as buggy +describe("processStreamingResponse - content preservation", () => { + // Mock dependencies + let mockLlmApi: BaseLlmApi; + let mockAbortController: AbortController; + let mockModel: ModelConfig; + let chunks: ChatCompletionChunk[]; + let chatHistory: ChatCompletionMessageParam[]; + + // Helper to create a content chunk + function contentChunk(content: string): ChatCompletionChunk { + return { + id: "test", + object: "chat.completion.chunk", + created: Date.now(), + model: "test-model", + choices: [ + { + index: 0, + delta: { content }, + finish_reason: null, + }, + ], + }; + } + + // Helper to create a tool call chunk + function toolCallChunk( + id: string, + name?: string, + args?: string + ): ChatCompletionChunk { + return { + id: "test", + object: "chat.completion.chunk", + created: Date.now(), + model: "test-model", + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: 0, + id, + type: "function", + function: { + name: name || undefined, + arguments: args || undefined, + }, + }, + ], + }, + finish_reason: null, + }, + ], + }; + } + + // Helper to create a tool call chunk with optional ID + function toolCallChunkWithIndex( + index: number, + id?: string, + name?: string, + args?: string + ): ChatCompletionChunk { + const toolCall: any = { + index, + type: "function" as const, + function: {}, + }; + + if (id) toolCall.id = id; + if (name) toolCall.function.name = name; + if (args !== undefined) toolCall.function.arguments = args; + + return { + id: "test", + object: "chat.completion.chunk" as const, + created: Date.now(), + model: "test-model", + choices: [ + { + index: 0, + delta: { tool_calls: [toolCall] }, + finish_reason: null, + }, + ], + }; + } + + beforeEach(() => { + // Reset chunks for each test + chunks = []; + chatHistory = [{ role: "user", content: "Test prompt" }]; + + // Create a mock LLM API that returns our predefined chunks + mockLlmApi = { + chatCompletionStream: vi.fn().mockImplementation(async function* () { + for (const chunk of chunks) { + yield chunk; + } + }), + } as unknown as BaseLlmApi; + + // Mock abort controller + mockAbortController = { + signal: { aborted: false }, + } as unknown as AbortController; + + // Mock model config + mockModel = { + model: "test-model", + provider: "test-provider", + } as unknown as ModelConfig; + }); + + it("content after tool calls is preserved", async () => { + chunks = [ + contentChunk(""), + toolCallChunk("call_123", "read_file", '{"filepath": "/README.md"}'), + contentChunk(""), + contentChunk("I'll read the README file for you."), + ]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + expect(result.content).toBe("I'll read the README file for you."); + expect(result.toolCalls.length).toBe(1); + + // Fixed: finalContent should preserve the content + expect(result.finalContent).toBe("I'll read the README file for you."); + }); + + it("content before tool calls is preserved", async () => { + chunks = [ + contentChunk("Let me search for that. "), + toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), + ]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + expect(result.content).toBe("Let me search for that. "); + expect(result.toolCalls.length).toBe(1); + + // Fixed: finalContent preserves content before tool calls + expect(result.finalContent).toBe("Let me search for that. "); + }); + + it("handles the exact problematic sequence from the logs", async () => { + chunks = [ + contentChunk(""), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "read_file", ""), + toolCallChunk( + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", + undefined, + '{"filepath' + ), + toolCallChunk( + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", + undefined, + '": "/Use' + ), + toolCallChunk( + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", + undefined, + "rs/nate/gh/c" + ), + toolCallChunk( + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", + undefined, + "ontinuede" + ), + toolCallChunk( + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", + undefined, + "v/cli/README" + ), + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), + contentChunk(""), + contentChunk("I'll read the README file for you."), + ]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + expect(result.content).toBe("I'll read the README file for you."); + expect(result.toolCalls.length).toBe(1); + + // Fixed: content is preserved + expect(result.finalContent).toBe("I'll read the README file for you."); + + // Verify the tool call was assembled correctly + expect(result.toolCalls[0].name).toBe("read_file"); + expect(result.toolCalls[0].argumentsStr).toBe( + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' + ); + }); + + it("shows content works fine without tool calls", async () => { + chunks = [contentChunk("Hello "), contentChunk("world!")]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + expect(result.content).toBe("Hello world!"); + expect(result.toolCalls.length).toBe(0); + + // Without tool calls, finalContent is correct + expect(result.finalContent).toBe("Hello world!"); + }); + + it("handles provider that only sends tool ID in first chunk then uses index", async () => { + chunks = [ + contentChunk("I'll read the README.md file for you and then say hello!"), + // First chunk has ID + toolCallChunkWithIndex( + 0, + "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", + "read_file", + "" + ), + // Subsequent chunks only have index, no ID + toolCallChunkWithIndex( + 0, + undefined, + undefined, + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' + ), + ]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + // Content is captured correctly + expect(result.content).toBe( + "I'll read the README.md file for you and then say hello!" + ); + expect(result.toolCalls.length).toBe(1); + + // Fixed: finalContent preserves content + expect(result.finalContent).toBe( + "I'll read the README.md file for you and then say hello!" + ); + + // Tool call arguments are preserved using index mapping + expect(result.toolCalls[0].name).toBe("read_file"); + expect(result.toolCalls[0].argumentsStr).toBe( + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' + ); + }); + + it("handles realistic fragmented arguments from index-based provider", async () => { + // Simulate the exact sequence from the user's logs with fragmented JSON + chunks = [ + contentChunk("I'll read the README.md file for you and then say hello!"), + // First chunk has ID + toolCallChunkWithIndex( + 0, + "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", + "read_file", + "" + ), + // Subsequent chunks fragment the JSON arguments + toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), + toolCallChunkWithIndex(0, undefined, undefined, 'th"'), + toolCallChunkWithIndex(0, undefined, undefined, ": "), + toolCallChunkWithIndex(0, undefined, undefined, '"/U'), + toolCallChunkWithIndex(0, undefined, undefined, "sers/nate/gh"), + toolCallChunkWithIndex(0, undefined, undefined, "/c"), + toolCallChunkWithIndex(0, undefined, undefined, "onti"), + toolCallChunkWithIndex(0, undefined, undefined, "nuedev/cli"), + toolCallChunkWithIndex(0, undefined, undefined, "/READ"), + toolCallChunkWithIndex(0, undefined, undefined, "ME.m"), + toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), + ]; + + const result = await processStreamingResponse( + chatHistory, + mockModel, + mockLlmApi, + mockAbortController + ); + + // Fixed: Both issues are resolved + // 1. Content is preserved + expect(result.finalContent).toBe( + "I'll read the README.md file for you and then say hello!" + ); + + // 2. Tool call arguments are assembled correctly + expect(result.toolCalls[0].name).toBe("read_file"); + expect(result.toolCalls[0].argumentsStr).toBe( + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}' + ); + }); +}); + +// Tests for preprocessStreamedToolCalls function +describe("preprocessStreamedToolCalls", () => { + // Mock dependencies + beforeEach(async () => { + // Spy on the functions we need to mock + vi.spyOn( + await import("./tools/index.js"), + "getAvailableTools" + ).mockResolvedValue([readFileTool, searchCodeTool]); + vi.spyOn( + await import("./tools/index.js"), + "validateToolCallArgsPresent" + ).mockImplementation(() => {}); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("preprocesses valid tool calls correctly", async () => { + const toolCalls: ToolCall[] = [ + { + id: "call_123", + name: "read_file", + arguments: { filepath: "/path/to/file.txt" }, + argumentsStr: '{"filepath": "/path/to/file.txt"}', + startNotified: false, + }, + ]; + + const callbacks = { + onToolStart: vi.fn(), + onToolError: vi.fn(), + }; + + const { preprocessedCalls, chatHistoryEntries } = + await preprocessStreamedToolCalls(toolCalls, callbacks); + + // Should have one preprocessed call and no errors + expect(preprocessedCalls).toHaveLength(1); + expect(chatHistoryEntries).toHaveLength(0); + expect(preprocessedCalls[0].name).toBe("read_file"); + expect(preprocessedCalls[0].tool).toBeDefined(); + expect(preprocessedCalls[0].preprocessResult).toBeDefined(); + + // Callbacks should not be called for successful preprocessing + expect(callbacks.onToolStart).not.toHaveBeenCalled(); + expect(callbacks.onToolError).not.toHaveBeenCalled(); + }); + + it("handles tool preprocessing errors correctly", async () => { + // Set the spy to throw an error + const toolsModule = await import("./tools/index.js"); + vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce( + () => { + throw new Error("Missing required argument"); + } + ); + + const toolCalls: ToolCall[] = [ + { + id: "call_456", + name: "read_file", + arguments: {}, // Missing required filepath + argumentsStr: "{}", + startNotified: false, + }, + ]; + + const callbacks = { + onToolStart: vi.fn(), + onToolError: vi.fn(), + }; + + const { preprocessedCalls, chatHistoryEntries } = + await preprocessStreamedToolCalls(toolCalls, callbacks); + + // Should have no preprocessed calls and one error + expect(preprocessedCalls).toHaveLength(0); + expect(chatHistoryEntries).toHaveLength(1); + expect(chatHistoryEntries[0].content).toContain( + "Missing required argument" + ); + + // Callbacks should be called for errors + expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", {}); + expect(callbacks.onToolError).toHaveBeenCalledWith( + expect.stringContaining("Missing required argument"), + "read_file" + ); + }); + + it("handles tool not found errors", async () => { + const toolCalls: ToolCall[] = [ + { + id: "call_789", + name: "nonexistent_tool", + arguments: { some: "arg" }, + argumentsStr: '{"some": "arg"}', + startNotified: false, + }, + ]; + + const { preprocessedCalls, chatHistoryEntries } = + await preprocessStreamedToolCalls(toolCalls); + + // Should have no preprocessed calls and one error + expect(preprocessedCalls).toHaveLength(0); + expect(chatHistoryEntries).toHaveLength(1); + expect(chatHistoryEntries[0].content).toContain( + "Tool nonexistent_tool not found" + ); + }); +}); + +// Tests for executeStreamedToolCalls function +describe("executeStreamedToolCalls", () => { + beforeEach(() => { + // Reset spies + vi.spyOn(toolPermissionManager, "requestPermission").mockReset(); + vi.spyOn(toolPermissionManager, "on").mockReset(); + vi.spyOn(toolPermissionManager, "off").mockReset(); + }); + + it("executes tool calls with allowed permissions", async () => { + // Setup spies instead of mocks + const permissionsModule = await import("./permissions/index.js"); + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ + permission: "allow", + }); + + const toolsModule = await import("./tools/index.js"); + const mockedExecuteToolCall = vi + .spyOn(toolsModule, "executeToolCall") + .mockResolvedValue("Tool execution successful"); + + // Create preprocessed tool call + const preprocessedCalls: PreprocessedToolCall[] = [ + { + id: "call_123", + name: "read_file", + arguments: { filepath: "/test.txt" }, + argumentsStr: '{"filepath": "/test.txt"}', + startNotified: false, + tool: readFileTool, + }, + ]; + + const callbacks = { + onToolStart: vi.fn(), + onToolResult: vi.fn(), + onToolError: vi.fn(), + }; + + const chatHistoryEntries = await executeStreamedToolCalls( + preprocessedCalls, + callbacks + ); + + // Verify results + expect(chatHistoryEntries).toHaveLength(1); + expect(chatHistoryEntries[0].content).toBe("Tool execution successful"); + expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", { + filepath: "/test.txt", + }); + expect(callbacks.onToolResult).toHaveBeenCalledWith( + "Tool execution successful", + "read_file" + ); + expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]); + }); + + it("handles permission denied correctly", async () => { + // Setup permission to ask + const permissionsModule = await import("./permissions/index.js"); + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ + permission: "ask", + }); + + // Spy on permission request to be denied + vi.spyOn(toolPermissionManager, "requestPermission").mockResolvedValue({ + approved: false, + }); + + // Add event listener mock + vi.spyOn(toolPermissionManager, "on").mockImplementation( + (event, callback) => { + if (event === "permissionRequested") { + // Immediately trigger the callback to simulate event + callback({ + requestId: "req_123", + toolCall: { + name: "write_file", + arguments: { + filepath: "/test.txt", + content: "data", + }, + }, + }); + } + return toolPermissionManager; + } + ); + + // Create preprocessed tool call + const preprocessedCalls: PreprocessedToolCall[] = [ + { + id: "call_456", + name: "write_file", + arguments: { filepath: "/test.txt", content: "data" }, + argumentsStr: '{"filepath": "/test.txt", "content": "data"}', + startNotified: false, + tool: writeFileTool, + }, + ]; + + const callbacks = { + onToolStart: vi.fn(), + onToolResult: vi.fn(), + onToolPermissionRequest: vi.fn(), + }; + + const chatHistoryEntries = await executeStreamedToolCalls( + preprocessedCalls, + callbacks + ); + + // Verify results + expect(chatHistoryEntries).toHaveLength(1); + expect(chatHistoryEntries[0].content).toBe("Permission denied by user"); + expect(callbacks.onToolStart).toHaveBeenCalledWith("write_file", { + filepath: "/test.txt", + content: "data", + }); + expect(callbacks.onToolResult).toHaveBeenCalledWith( + "Permission denied by user", + "write_file" + ); + expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith( + "write_file", + { filepath: "/test.txt", content: "data" }, + "req_123", + undefined + ); + }); + + it("handles tool execution errors", async () => { + // Setup spies + const permissionsModule = await import("./permissions/index.js"); + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ + permission: "allow", + }); + + const toolsModule = await import("./tools/index.js"); + vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue( + new Error("Execution failed") + ); + + // Create preprocessed tool call + const preprocessedCalls: PreprocessedToolCall[] = [ + { + id: "call_789", + name: "search_code", + arguments: { pattern: "test" }, + argumentsStr: '{"pattern": "test"}', + startNotified: false, + tool: searchCodeTool, + }, + ]; + + const callbacks = { + onToolStart: vi.fn(), + onToolError: vi.fn(), + }; + + const chatHistoryEntries = await executeStreamedToolCalls( + preprocessedCalls, + callbacks + ); + + // Verify results + expect(chatHistoryEntries).toHaveLength(1); + expect(chatHistoryEntries[0].content).toContain( + "Error executing tool search_code" + ); + expect(chatHistoryEntries[0].content).toContain("Execution failed"); + expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", { + pattern: "test", + }); + expect(callbacks.onToolError).toHaveBeenCalledWith( + expect.stringContaining( + "Error executing tool search_code: Execution failed" + ), + "search_code" + ); + }); +}); diff --git a/src/tools/exit.ts b/src/tools/exit.ts index f51f545d6..32102d076 100644 --- a/src/tools/exit.ts +++ b/src/tools/exit.ts @@ -7,7 +7,8 @@ export const exitTool: Tool = { "Exit the current process with status code 1, indicating a failure or error", parameters: {}, readonly: false, + isBuiltIn: true, run: async (args: { dirpath: string }): Promise => { process.exit(1); }, -}; \ No newline at end of file +}; diff --git a/src/tools/fetch.ts b/src/tools/fetch.ts index 6ad9fc22a..ee52123f5 100644 --- a/src/tools/fetch.ts +++ b/src/tools/fetch.ts @@ -46,6 +46,7 @@ export const fetchTool: Tool = { }, }, readonly: true, + isBuiltIn: true, preprocess: async (args) => { return { preview: [ diff --git a/src/tools/index.ts b/src/tools/index.ts index 60216a82a..bafcd1b2a 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -108,6 +108,7 @@ export async function getAvailableTools() { description: t.description ?? "", parameters: convertInputSchemaToParameters(t.inputSchema), readonly: undefined, // MCP tools don't have readonly property, so we include them in readonly mode + isBuiltIn: false, run: async (args: any) => { const result = await MCPService.getInstance()?.runTool( t.name, diff --git a/src/tools/listFiles.ts b/src/tools/listFiles.ts index c6c952293..b8b94f643 100644 --- a/src/tools/listFiles.ts +++ b/src/tools/listFiles.ts @@ -16,6 +16,7 @@ export const listFilesTool: Tool = { }, }, readonly: true, + isBuiltIn: true, preprocess: async (args) => { return { args, diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index c00049ee2..d518b9f31 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -14,6 +14,7 @@ export const readFileTool: Tool = { }, }, readonly: true, + isBuiltIn: true, preprocess: async (args) => { return { args, diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index bf8c06246..3681904ae 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -18,6 +18,7 @@ export const runTerminalCommandTool: Tool = { }, }, readonly: false, + isBuiltIn: true, preprocess: async (args) => { const truncatedCmd = args.command.length > 60 diff --git a/src/tools/searchAndReplace/index.ts b/src/tools/searchAndReplace/index.ts index d2e9c8200..1ff1f1c4e 100644 --- a/src/tools/searchAndReplace/index.ts +++ b/src/tools/searchAndReplace/index.ts @@ -27,6 +27,7 @@ export const searchAndReplaceInFileTool: Tool = { name: "search_and_replace_in_file", displayName: "Search and Replace", readonly: false, + isBuiltIn: true, description: `Request to replace sections of content in an existing file using multiple SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file. ${NO_PARALLEL_TOOL_CALLING_INSRUCTION}`, parameters: { filepath: { diff --git a/src/tools/searchCode.ts b/src/tools/searchCode.ts index 7da99d67b..4e9a20cf7 100644 --- a/src/tools/searchCode.ts +++ b/src/tools/searchCode.ts @@ -30,6 +30,7 @@ export const searchCodeTool: Tool = { }, }, readonly: true, + isBuiltIn: true, preprocess: async (args) => { const truncatedPattern = args.pattern.length > 50 diff --git a/src/tools/types.ts b/src/tools/types.ts index fc3cd9685..7026f3f9f 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -30,6 +30,7 @@ export interface Tool { preprocess?: (args: any) => Promise; run: (args: any) => Promise; readonly?: boolean; // Indicates if the tool is readonly + isBuiltIn: boolean; } export interface ToolCall { diff --git a/src/tools/viewDiff.ts b/src/tools/viewDiff.ts index 9b595d91a..f6b1bfe99 100644 --- a/src/tools/viewDiff.ts +++ b/src/tools/viewDiff.ts @@ -18,6 +18,7 @@ export const viewDiffTool: Tool = { }, }, readonly: true, + isBuiltIn: true, preprocess: async (args) => { return { args, diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index de3a829a4..3a48ba119 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -41,6 +41,7 @@ export const writeFileTool: Tool = { }, }, readonly: false, + isBuiltIn: true, preprocess: async (args) => { try { if (fs.existsSync(args.filepath)) {