From e489bc68e272229488af32195c8bb7cbed735a25 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 1 Sep 2025 14:35:39 -0700 Subject: [PATCH] feat: parallel tool calls --- extensions/cli/src/stream/handleToolCalls.ts | 21 ++- .../src/stream/streamChatResponse.helpers.ts | 127 ++++++++++++------ extensions/cli/src/ui/hooks/useUserInput.ts | 2 +- 3 files changed, 105 insertions(+), 45 deletions(-) diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index 7499b3a3f..1af7e7a06 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -120,16 +120,29 @@ export async function handleToolCalls( return true; // Signal early return needed } - // Convert tool results from OpenAI format to ChatHistoryItem format - // and add them to the chat history + // Convert tool results and add them to the chat history with per-result status toolResults.forEach((toolResult) => { const resultContent = typeof toolResult.content === "string" ? toolResult.content : ""; + + // Derive per-result status instead of applying batch-wide hasRejection + let status: ToolStatus = "done"; + const lower = resultContent.toLowerCase(); + if ( + lower.includes("permission denied by user") || + lower.includes("cancelled due to previous tool rejection") || + lower.includes("canceled due to previous tool rejection") + ) { + status = "canceled"; + } else if (lower.startsWith("error executing tool") || lower.startsWith("error:")) { + status = "errored" as ToolStatus; + } + if (useService) { chatHistorySvc.addToolResult( toolResult.tool_call_id, resultContent, - hasRejection ? ("canceled" as ToolStatus) : ("done" as ToolStatus), + status, ); } else { // Fallback only when service is unavailable: update local tool state @@ -144,7 +157,7 @@ export async function handleToolCalls( (ts) => ts.toolCallId === toolResult.tool_call_id, ); if (toolState) { - toolState.status = hasRejection ? "canceled" : "done"; + toolState.status = status; toolState.output = [ { content: resultContent, diff --git a/extensions/cli/src/stream/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts index 4ac0a9e88..a4792feac 100644 --- a/extensions/cli/src/stream/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -373,81 +373,128 @@ export async function executeStreamedToolCalls( hasRejection: boolean; chatHistoryEntries: ChatCompletionToolMessageParam[]; }> { - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; - let hasRejection = false; + // Strategy: queue permissions (preserve order), then run approved tools in parallel. + // If any permission is rejected, cancel the remaining tools in this batch. - // Execute each preprocessed tool call - for (const toolCall of preprocessedCalls) { + type IndexedCall = { index: number; call: PreprocessedToolCall }; + const indexedCalls: IndexedCall[] = preprocessedCalls.map((call, index) => ({ + index, + call, + })); + + const entriesByIndex = new Map(); + const approvedCalls: IndexedCall[] = []; + + let hasRejection = false; + let rejectionIndex: number | null = null; + + // Permission phase (sequential) + for (const { index, call } of indexedCalls) { if (hasRejection) { + // Anything after a rejection is cancelled const cancelledMessage = `Cancelled due to previous tool rejection`; - chatHistoryEntries.push({ + entriesByIndex.set(index, { role: "tool", - tool_call_id: toolCall.id, + tool_call_id: call.id, content: cancelledMessage, }); - - callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); + callbacks?.onToolResult?.(cancelledMessage, call.name, "canceled"); continue; } - // Handle remaining tool calls in this batch to maintain chat history consistency try { logger.debug("Checking tool permissions", { - name: toolCall.name, - arguments: toolCall.arguments, + name: call.name, + arguments: call.arguments, }); - // Notify tool start - before permission check - // This ensures the UI shows the tool call even if it's rejected - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); + // Notify tool start before permission check to display in UI fallbacks + callbacks?.onToolStart?.(call.name, call.arguments); - // Check tool permissions using helper const approved = await checkToolPermissionApproval( - toolCall, + call, callbacks, isHeadless, ); if (!approved) { - handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); + // Permission denied: record and mark rejection + const deniedEntry: ChatCompletionToolMessageParam = { + role: "tool", + tool_call_id: call.id, + content: `Permission denied by user`, + }; + entriesByIndex.set(index, deniedEntry); + callbacks?.onToolResult?.(String(deniedEntry.content), call.name, "canceled"); hasRejection = true; + rejectionIndex = index; + // Remaining items will be auto-cancelled in subsequent iterations 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, - }); - - callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); + approvedCalls.push({ index, call }); } catch (error) { - const errorMessage = `Error executing tool ${toolCall.name}: ${ + const errorMessage = `Error checking permissions for ${call.name}: ${ error instanceof Error ? error.message : String(error) }`; - - logger.error("Tool execution failed", { - name: toolCall.name, + logger.error("Permission check failed", { + name: call.name, error: errorMessage, }); - - chatHistoryEntries.push({ + entriesByIndex.set(index, { role: "tool", - tool_call_id: toolCall.id, + tool_call_id: call.id, content: errorMessage, }); - - callbacks?.onToolError?.(errorMessage, toolCall.name); + callbacks?.onToolError?.(errorMessage, call.name); + // Treat permission errors like execution errors but do not stop the batch } } + // Execution phase (parallel) for approved calls prior to any rejection + const toExecute = + rejectionIndex === null + ? approvedCalls + : approvedCalls.filter((c) => c.index < (rejectionIndex as number)); + + const execPromises = toExecute.map(async ({ index, call }) => { + try { + logger.debug("Executing tool", { + name: call.name, + arguments: call.arguments, + }); + const toolResult = await executeToolCall(call); + const entry: ChatCompletionToolMessageParam = { + role: "tool", + tool_call_id: call.id, + content: toolResult, + }; + entriesByIndex.set(index, entry); + callbacks?.onToolResult?.(toolResult, call.name, "done"); + } catch (error) { + const errorMessage = `Error executing tool ${call.name}: ${ + error instanceof Error ? error.message : String(error) + }`; + logger.error("Tool execution failed", { + name: call.name, + error: errorMessage, + }); + entriesByIndex.set(index, { + role: "tool", + tool_call_id: call.id, + content: errorMessage, + }); + callbacks?.onToolError?.(errorMessage, call.name); + } + }); + + await Promise.all(execPromises); + + // Assemble final entries in original order + const chatHistoryEntries: ChatCompletionToolMessageParam[] = preprocessedCalls + .map((_, index) => entriesByIndex.get(index)) + .filter((e): e is ChatCompletionToolMessageParam => !!e); + return { hasRejection, chatHistoryEntries, diff --git a/extensions/cli/src/ui/hooks/useUserInput.ts b/extensions/cli/src/ui/hooks/useUserInput.ts index d10bc8572..deef3ed9c 100644 --- a/extensions/cli/src/ui/hooks/useUserInput.ts +++ b/extensions/cli/src/ui/hooks/useUserInput.ts @@ -65,7 +65,7 @@ interface TextBufferStateOptions { export function updateTextBufferState(options: TextBufferStateOptions) { const { - handled, + handled: _handled, textBuffer, setInputText, setCursorPosition,