Changesets · Branches · Tags · Compare
| Changeset | 3de2e40661e91ff43222c8f4c4de236e3ed935e328d6f33d4a96868874a6e609 |
|---|---|
| Author | Nate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-08-27 22:29 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-08-27 22:29 -07:00 |
| Parents | 4b606125a269, 30ad7163f895 |
66 files changed
modified core/util/chatDescriber.ts +62 −0
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; |
| 6 | 6 | import type { IMessenger } from "../protocol/messenger"; |
| 7 | 7 | import { renderChatMessage } from "./messageContent"; |
| 8 | +import { convertFromUnifiedHistory } from "./messageConversion"; | |
| 8 | 9 | |
| 9 | 10 | export class ChatDescriber { |
| 10 | 11 | static maxTokens = 12; |
| @@ -46,6 +47,67 @@ | ||
| 46 | 47 | return removeQuotesAndEscapes(renderChatMessage(titleResponse)); |
| 47 | 48 | } |
| 48 | 49 | |
| 50 | + // CLI-specific method that works with BaseLlmApi | |
| 51 | + static async describeWithBaseLlmApi( | |
| 52 | + llmApi: any, // BaseLlmApi - using any to avoid import issues | |
| 53 | + modelConfig: any, // ModelConfig - using any to avoid import issues | |
| 54 | + message: string, | |
| 55 | + ): Promise<string | undefined> { | |
| 56 | + if (!ChatDescriber.prompt) { | |
| 57 | + return; | |
| 58 | + } | |
| 59 | + | |
| 60 | + // Clean up and distill the message we want to send to the LLM | |
| 61 | + message = removeCodeBlocksAndTrim(message); | |
| 62 | + | |
| 63 | + if (!message) { | |
| 64 | + return; | |
| 65 | + } | |
| 66 | + | |
| 67 | + try { | |
| 68 | + // Create the chat message in the unified format | |
| 69 | + const chatMessage = { | |
| 70 | + role: "user" as const, | |
| 71 | + content: ChatDescriber.prompt + message, | |
| 72 | + }; | |
| 73 | + | |
| 74 | + // Convert to OpenAI format - use a simple fallback to avoid import issues | |
| 75 | + const openaiMessages = convertFromUnifiedHistory([ | |
| 76 | + { | |
| 77 | + message: chatMessage, | |
| 78 | + contextItems: [], | |
| 79 | + }, | |
| 80 | + ]); | |
| 81 | + | |
| 82 | + // Set up completion options for non-streaming | |
| 83 | + const completionOptions = { | |
| 84 | + model: modelConfig.model, | |
| 85 | + messages: openaiMessages, | |
| 86 | + max_tokens: ChatDescriber.maxTokens, | |
| 87 | + stream: false as const, | |
| 88 | + }; | |
| 89 | + | |
| 90 | + // Call the LLM | |
| 91 | + const titleResponse = await llmApi.chatCompletionNonStream( | |
| 92 | + completionOptions, | |
| 93 | + new AbortController().signal, | |
| 94 | + ); | |
| 95 | + | |
| 96 | + // Extract and clean up the response | |
| 97 | + if (titleResponse.choices && titleResponse.choices.length > 0) { | |
| 98 | + const content = titleResponse.choices[0].message.content; | |
| 99 | + if (content) { | |
| 100 | + return removeQuotesAndEscapes(content); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + return undefined; | |
| 105 | + } catch (error) { | |
| 106 | + console.debug("Error generating chat title:", error); | |
| 107 | + return undefined; | |
| 108 | + } | |
| 109 | + } | |
| 110 | + | |
| 49 | 111 | // // TODO: Allow the user to manually set specific/tailored prompts to generate their titles |
| 50 | 112 | // static async setup() { |
| 51 | 113 | // if(config?.prompt) { |
modified core/util/history.test.ts +6 −2
| @@ -93,8 +93,9 @@ | ||
| 93 | 93 | const offset = 10; |
| 94 | 94 | |
| 95 | 95 | const sessions = historyManager.list({ offset: offset, limit: limit }); |
| 96 | + // Sessions are now reversed, so newest (99) comes first | |
| 96 | 97 | const sessionIds = Array.from({ length: limit }, (_, i) => |
| 97 | - (i + offset).toString(), | |
| 98 | + (99 - offset - i).toString(), | |
| 98 | 99 | ); |
| 99 | 100 | const isSessionIdInList = (sessionId: string) => |
| 100 | 101 | sessions.some((session) => session.sessionId === sessionId); |
| @@ -105,7 +106,10 @@ | ||
| 105 | 106 | const limit = 25; |
| 106 | 107 | |
| 107 | 108 | const sessions = historyManager.list({ limit: limit }); |
| 108 | - const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); | |
| 109 | + // Sessions are now reversed, so newest (99) comes first | |
| 110 | + const sessionIds = Array.from({ length: limit }, (_, i) => | |
| 111 | + (99 - i).toString(), | |
| 112 | + ); | |
| 109 | 113 | |
| 110 | 114 | const isSessionIdInList = (sessionId: string) => |
| 111 | 115 | sessions.some((session) => session.sessionId === sessionId); |
modified core/util/history.ts +7 −4
| @@ -30,10 +30,13 @@ | ||
| 30 | 30 | const content = fs.readFileSync(filepath, "utf8"); |
| 31 | 31 | |
| 32 | 32 | let sessions = safeParseArray<SessionMetadata>(content) ?? []; |
| 33 | - sessions = sessions.filter((session: any) => { | |
| 34 | - // Filter out old format | |
| 35 | - return typeof session.session_id !== "string"; | |
| 36 | - }); | |
| 33 | + sessions = sessions | |
| 34 | + .filter((session: any) => { | |
| 35 | + // Filter out old format | |
| 36 | + return typeof session.session_id !== "string"; | |
| 37 | + // Reverse to show newest first; sessions.json is chronological by creation | |
| 38 | + }) | |
| 39 | + .reverse(); | |
| 37 | 40 | |
| 38 | 41 | // Apply limit and offset |
| 39 | 42 | if (options.limit) { |
added core/util/messageConversion.ts +399 −0
| @@ -0,0 +1,399 @@ | ||
| 1 | +/** | |
| 2 | + * Message conversion utilities for transitioning to unified ChatHistoryItem type. | |
| 3 | + * | |
| 4 | + * This module provides conversion functions between the OpenAI ChatCompletionMessageParam | |
| 5 | + * format and the unified ChatHistoryItem format from the core package. | |
| 6 | + */ | |
| 7 | + | |
| 8 | +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 9 | +import type { | |
| 10 | + AssistantChatMessage, | |
| 11 | + ChatHistoryItem, | |
| 12 | + ChatMessage, | |
| 13 | + ContextItemWithId, | |
| 14 | + MessageContent, | |
| 15 | + ToolCall, | |
| 16 | + ToolCallState, | |
| 17 | + ToolStatus, | |
| 18 | +} from "../index.js"; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * Convert ChatCompletionMessageParam to ChatMessage | |
| 22 | + */ | |
| 23 | +export function convertToUnifiedMessage( | |
| 24 | + message: ChatCompletionMessageParam, | |
| 25 | +): ChatMessage { | |
| 26 | + switch (message.role) { | |
| 27 | + case "system": | |
| 28 | + return { | |
| 29 | + role: "system", | |
| 30 | + content: typeof message.content === "string" ? message.content : "", | |
| 31 | + }; | |
| 32 | + | |
| 33 | + case "user": | |
| 34 | + return { | |
| 35 | + role: "user", | |
| 36 | + content: convertMessageContent(message.content), | |
| 37 | + }; | |
| 38 | + | |
| 39 | + case "assistant": { | |
| 40 | + const assistantMessage: AssistantChatMessage = { | |
| 41 | + role: "assistant", | |
| 42 | + content: convertMessageContent(message.content || ""), | |
| 43 | + }; | |
| 44 | + | |
| 45 | + // Convert tool calls if present | |
| 46 | + if ("tool_calls" in message && message.tool_calls) { | |
| 47 | + assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({ | |
| 48 | + id: tc.id, | |
| 49 | + type: "function" as const, | |
| 50 | + function: { | |
| 51 | + name: tc.function?.name || "", | |
| 52 | + arguments: tc.function?.arguments || "", | |
| 53 | + }, | |
| 54 | + })); | |
| 55 | + } | |
| 56 | + | |
| 57 | + return assistantMessage; | |
| 58 | + } | |
| 59 | + | |
| 60 | + case "tool": | |
| 61 | + return { | |
| 62 | + role: "tool", | |
| 63 | + content: typeof message.content === "string" ? message.content : "", | |
| 64 | + toolCallId: message.tool_call_id, | |
| 65 | + }; | |
| 66 | + | |
| 67 | + default: | |
| 68 | + throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +/** | |
| 73 | + * Convert ChatMessage to ChatCompletionMessageParam | |
| 74 | + */ | |
| 75 | +export function convertFromUnifiedMessage( | |
| 76 | + message: ChatMessage, | |
| 77 | +): ChatCompletionMessageParam { | |
| 78 | + switch (message.role) { | |
| 79 | + case "system": | |
| 80 | + return { | |
| 81 | + role: "system", | |
| 82 | + content: message.content, | |
| 83 | + }; | |
| 84 | + | |
| 85 | + case "user": | |
| 86 | + return { | |
| 87 | + role: "user", | |
| 88 | + content: convertFromMessageContent(message.content), | |
| 89 | + }; | |
| 90 | + | |
| 91 | + case "assistant": { | |
| 92 | + const assistantMessage: ChatCompletionMessageParam = { | |
| 93 | + role: "assistant", | |
| 94 | + content: convertFromMessageContent(message.content), | |
| 95 | + }; | |
| 96 | + | |
| 97 | + // Convert tool calls if present | |
| 98 | + if (message.toolCalls && message.toolCalls.length > 0) { | |
| 99 | + (assistantMessage as any).tool_calls = message.toolCalls.map( | |
| 100 | + (tc: any) => ({ | |
| 101 | + id: tc.id, | |
| 102 | + type: "function", | |
| 103 | + function: { | |
| 104 | + name: tc.function?.name || "", | |
| 105 | + arguments: tc.function?.arguments || "", | |
| 106 | + }, | |
| 107 | + }), | |
| 108 | + ); | |
| 109 | + } | |
| 110 | + | |
| 111 | + return assistantMessage; | |
| 112 | + } | |
| 113 | + | |
| 114 | + case "tool": | |
| 115 | + return { | |
| 116 | + role: "tool", | |
| 117 | + content: message.content, | |
| 118 | + tool_call_id: message.toolCallId, | |
| 119 | + }; | |
| 120 | + | |
| 121 | + case "thinking": | |
| 122 | + // Thinking messages don't have a direct equivalent in OpenAI format | |
| 123 | + // Convert to assistant message with content | |
| 124 | + return { | |
| 125 | + role: "assistant", | |
| 126 | + content: convertFromMessageContent(message.content), | |
| 127 | + }; | |
| 128 | + | |
| 129 | + default: | |
| 130 | + throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 131 | + } | |
| 132 | +} | |
| 133 | + | |
| 134 | +/** | |
| 135 | + * Convert OpenAI message content to unified MessageContent format | |
| 136 | + */ | |
| 137 | +function convertMessageContent( | |
| 138 | + content: string | null | Array<any>, | |
| 139 | +): MessageContent { | |
| 140 | + if (content === null) { | |
| 141 | + return ""; | |
| 142 | + } | |
| 143 | + | |
| 144 | + if (typeof content === "string") { | |
| 145 | + return content; | |
| 146 | + } | |
| 147 | + | |
| 148 | + if (Array.isArray(content)) { | |
| 149 | + return content.map((part: any) => { | |
| 150 | + if (part.type === "text") { | |
| 151 | + return { | |
| 152 | + type: "text" as const, | |
| 153 | + text: part.text, | |
| 154 | + }; | |
| 155 | + } else if (part.type === "image_url") { | |
| 156 | + return { | |
| 157 | + type: "imageUrl" as const, | |
| 158 | + imageUrl: { url: part.image_url.url }, | |
| 159 | + }; | |
| 160 | + } | |
| 161 | + throw new Error(`Unsupported content part type: ${part.type}`); | |
| 162 | + }); | |
| 163 | + } | |
| 164 | + | |
| 165 | + throw new Error(`Unsupported content type: ${typeof content}`); | |
| 166 | +} | |
| 167 | + | |
| 168 | +/** | |
| 169 | + * Convert unified MessageContent to OpenAI format | |
| 170 | + */ | |
| 171 | +function convertFromMessageContent( | |
| 172 | + content: MessageContent, | |
| 173 | +): string | Array<any> { | |
| 174 | + if (typeof content === "string") { | |
| 175 | + return content; | |
| 176 | + } | |
| 177 | + | |
| 178 | + if (Array.isArray(content)) { | |
| 179 | + return content.map((part: any) => { | |
| 180 | + if (part.type === "text") { | |
| 181 | + return { | |
| 182 | + type: "text", | |
| 183 | + text: part.text, | |
| 184 | + }; | |
| 185 | + } else if (part.type === "imageUrl") { | |
| 186 | + return { | |
| 187 | + type: "image_url", | |
| 188 | + image_url: { url: part.imageUrl.url }, | |
| 189 | + }; | |
| 190 | + } | |
| 191 | + throw new Error(`Unsupported content part type: ${part.type}`); | |
| 192 | + }); | |
| 193 | + } | |
| 194 | + | |
| 195 | + throw new Error(`Unsupported content type: ${typeof content}`); | |
| 196 | +} | |
| 197 | + | |
| 198 | +/** | |
| 199 | + * Create a ChatHistoryItem from a ChatMessage | |
| 200 | + */ | |
| 201 | +export function createHistoryItem( | |
| 202 | + message: ChatMessage, | |
| 203 | + contextItems: ContextItemWithId[] = [], | |
| 204 | + toolCallStates?: ToolCallState[], | |
| 205 | +): ChatHistoryItem { | |
| 206 | + return { | |
| 207 | + message, | |
| 208 | + contextItems, | |
| 209 | + ...(toolCallStates && { toolCallStates }), | |
| 210 | + }; | |
| 211 | +} | |
| 212 | + | |
| 213 | +/** | |
| 214 | + * Handle tool result message by updating the corresponding tool call state | |
| 215 | + */ | |
| 216 | +function handleToolResult( | |
| 217 | + unifiedMessage: ChatMessage & { role: "tool" }, | |
| 218 | + pendingToolCalls: Map<string, ToolCall>, | |
| 219 | + historyItems: ChatHistoryItem[], | |
| 220 | +): void { | |
| 221 | + const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId); | |
| 222 | + if (!toolCall) return; | |
| 223 | + | |
| 224 | + // Add tool result as context to the previous assistant message | |
| 225 | + let lastAssistantIndex = -1; | |
| 226 | + for (let i = historyItems.length - 1; i >= 0; i--) { | |
| 227 | + if (historyItems[i].message.role === "assistant") { | |
| 228 | + lastAssistantIndex = i; | |
| 229 | + break; | |
| 230 | + } | |
| 231 | + } | |
| 232 | + if (lastAssistantIndex < 0) return; | |
| 233 | + if (!historyItems[lastAssistantIndex].toolCallStates) return; | |
| 234 | + | |
| 235 | + const toolState = historyItems[lastAssistantIndex].toolCallStates?.find( | |
| 236 | + (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId, | |
| 237 | + ); | |
| 238 | + | |
| 239 | + if (toolState) { | |
| 240 | + toolState.output = [ | |
| 241 | + { | |
| 242 | + content: unifiedMessage.content as string, | |
| 243 | + name: `Tool Result: ${toolCall.function.name}`, | |
| 244 | + description: "Tool execution result", | |
| 245 | + }, | |
| 246 | + ]; | |
| 247 | + } | |
| 248 | +} | |
| 249 | + | |
| 250 | +/** | |
| 251 | + * Convert array of ChatCompletionMessageParam to ChatHistoryItem array | |
| 252 | + */ | |
| 253 | +export function convertToUnifiedHistory( | |
| 254 | + messages: ChatCompletionMessageParam[], | |
| 255 | +): ChatHistoryItem[] { | |
| 256 | + const historyItems: ChatHistoryItem[] = []; | |
| 257 | + const pendingToolCalls: Map<string, ToolCall> = new Map(); | |
| 258 | + | |
| 259 | + for (const message of messages) { | |
| 260 | + const unifiedMessage = convertToUnifiedMessage(message); | |
| 261 | + | |
| 262 | + if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) { | |
| 263 | + // Store tool calls for matching with results | |
| 264 | + const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map( | |
| 265 | + (tc: any) => { | |
| 266 | + const toolCall: ToolCall = { | |
| 267 | + id: tc.id || "", | |
| 268 | + type: "function", | |
| 269 | + function: { | |
| 270 | + name: tc.function?.name || "", | |
| 271 | + arguments: tc.function?.arguments || "", | |
| 272 | + }, | |
| 273 | + }; | |
| 274 | + pendingToolCalls.set(toolCall.id, toolCall); | |
| 275 | + | |
| 276 | + return { | |
| 277 | + toolCallId: toolCall.id, | |
| 278 | + toolCall, | |
| 279 | + status: "done" as ToolStatus, // Historical calls are complete | |
| 280 | + parsedArgs: tryParseJson(toolCall.function.arguments), | |
| 281 | + }; | |
| 282 | + }, | |
| 283 | + ); | |
| 284 | + | |
| 285 | + historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates)); | |
| 286 | + } else if (unifiedMessage.role === "tool") { | |
| 287 | + // Tool result - handle separately to reduce nesting | |
| 288 | + handleToolResult(unifiedMessage, pendingToolCalls, historyItems); | |
| 289 | + // Don't add tool messages as separate history items | |
| 290 | + } else { | |
| 291 | + historyItems.push(createHistoryItem(unifiedMessage)); | |
| 292 | + } | |
| 293 | + } | |
| 294 | + | |
| 295 | + return historyItems; | |
| 296 | +} | |
| 297 | + | |
| 298 | +/** | |
| 299 | + * Convert ChatHistoryItem array to ChatCompletionMessageParam array | |
| 300 | + */ | |
| 301 | +export function convertFromUnifiedHistory( | |
| 302 | + historyItems: ChatHistoryItem[], | |
| 303 | +): ChatCompletionMessageParam[] { | |
| 304 | + const messages: ChatCompletionMessageParam[] = []; | |
| 305 | + | |
| 306 | + for (const item of historyItems) { | |
| 307 | + const baseMessage = convertFromUnifiedMessage(item.message); | |
| 308 | + | |
| 309 | + // If this is a user message with context items, expand the content | |
| 310 | + if ( | |
| 311 | + item.message.role === "user" && | |
| 312 | + item.contextItems && | |
| 313 | + item.contextItems.length > 0 | |
| 314 | + ) { | |
| 315 | + const contextContent = item.contextItems | |
| 316 | + .map( | |
| 317 | + (contextItem: ContextItemWithId) => | |
| 318 | + `<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`, | |
| 319 | + ) | |
| 320 | + .join(""); | |
| 321 | + | |
| 322 | + baseMessage.content = | |
| 323 | + typeof baseMessage.content === "string" | |
| 324 | + ? contextContent + baseMessage.content | |
| 325 | + : baseMessage.content; // Keep array format if it's already an array | |
| 326 | + } | |
| 327 | + | |
| 328 | + messages.push(baseMessage); | |
| 329 | + | |
| 330 | + // Add tool result messages if there are completed tool calls | |
| 331 | + if (item.toolCallStates) { | |
| 332 | + for (const toolState of item.toolCallStates) { | |
| 333 | + if (toolState.output && toolState.output.length > 0) { | |
| 334 | + messages.push({ | |
| 335 | + role: "tool", | |
| 336 | + content: toolState.output.map((o: any) => o.content).join("\n"), | |
| 337 | + tool_call_id: toolState.toolCallId, | |
| 338 | + }); | |
| 339 | + } | |
| 340 | + } | |
| 341 | + } | |
| 342 | + } | |
| 343 | + | |
| 344 | + return messages; | |
| 345 | +} | |
| 346 | + | |
| 347 | +/** | |
| 348 | + * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message | |
| 349 | + * @param historyItems - The chat history items | |
| 350 | + * @param systemMessage - The system message to inject at the beginning | |
| 351 | + */ | |
| 352 | +export function convertFromUnifiedHistoryWithSystemMessage( | |
| 353 | + historyItems: ChatHistoryItem[], | |
| 354 | + systemMessage: string, | |
| 355 | +): ChatCompletionMessageParam[] { | |
| 356 | + const messages: ChatCompletionMessageParam[] = []; | |
| 357 | + | |
| 358 | + // Inject system message at the beginning | |
| 359 | + messages.push({ | |
| 360 | + role: "system", | |
| 361 | + content: systemMessage, | |
| 362 | + }); | |
| 363 | + | |
| 364 | + // Convert the rest of the history | |
| 365 | + const convertedMessages = convertFromUnifiedHistory(historyItems); | |
| 366 | + messages.push(...convertedMessages); | |
| 367 | + | |
| 368 | + return messages; | |
| 369 | +} | |
| 370 | + | |
| 371 | +/** | |
| 372 | + * Extract tool call information from a ChatHistoryItem | |
| 373 | + */ | |
| 374 | +export function extractToolCallInfo(historyItem: ChatHistoryItem): { | |
| 375 | + hasToolCalls: boolean; | |
| 376 | + toolCalls?: ToolCall[]; | |
| 377 | + toolStates?: ToolCallState[]; | |
| 378 | +} { | |
| 379 | + const hasToolCalls = !!( | |
| 380 | + historyItem.toolCallStates && historyItem.toolCallStates.length > 0 | |
| 381 | + ); | |
| 382 | + | |
| 383 | + return { | |
| 384 | + hasToolCalls, | |
| 385 | + toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall), | |
| 386 | + toolStates: historyItem.toolCallStates, | |
| 387 | + }; | |
| 388 | +} | |
| 389 | + | |
| 390 | +/** | |
| 391 | + * Helper to safely parse JSON | |
| 392 | + */ | |
| 393 | +function tryParseJson(str: string): any { | |
| 394 | + try { | |
| 395 | + return JSON.parse(str); | |
| 396 | + } catch { | |
| 397 | + return str; | |
| 398 | + } | |
| 399 | +} |
modified extensions/cli/src/commands/chat.ts +44 −23
| @@ -1,9 +1,9 @@ | ||
| 1 | 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | 2 | import chalk from "chalk"; |
| 3 | 3 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 4 | +import { ChatDescriber } from "core/util/chatDescriber.js"; | |
| 4 | 5 | import * as readlineSync from "readline-sync"; |
| 5 | 6 | |
| 6 | -import { getDisplayableAsciiArt } from "../asciiArt.js"; | |
| 7 | 7 | import { |
| 8 | 8 | compactChatHistory, |
| 9 | 9 | findCompactionIndex, |
| @@ -17,9 +17,12 @@ | ||
| 17 | 17 | import { initializeServices } from "../services/index.js"; |
| 18 | 18 | import { serviceContainer } from "../services/ServiceContainer.js"; |
| 19 | 19 | import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; |
| 20 | -import { loadSession, updateSessionHistory } from "../session.js"; | |
| 21 | -import { streamChatResponse } from "../streamChatResponse.js"; | |
| 22 | -import { constructSystemMessage } from "../systemMessage.js"; | |
| 20 | +import { | |
| 21 | + loadSession, | |
| 22 | + updateSessionHistory, | |
| 23 | + updateSessionTitle, | |
| 24 | +} from "../session.js"; | |
| 25 | +import { streamChatResponse } from "../stream/streamChatResponse.js"; | |
| 23 | 26 | import { posthogService } from "../telemetry/posthogService.js"; |
| 24 | 27 | import { telemetryService } from "../telemetry/telemetryService.js"; |
| 25 | 28 | import { startTUIChat } from "../ui/index.js"; |
| @@ -97,21 +100,7 @@ | ||
| 97 | 100 | } |
| 98 | 101 | } |
| 99 | 102 | |
| 100 | - // If no session loaded or not resuming, initialize with system message | |
| 101 | - const chatHistory: ChatHistoryItem[] = []; | |
| 102 | - const systemMessage = await constructSystemMessage( | |
| 103 | - options.rule, | |
| 104 | - options.format, | |
| 105 | - options.headless, | |
| 106 | - ); | |
| 107 | - if (systemMessage) { | |
| 108 | - chatHistory.push({ | |
| 109 | - message: { role: "system", content: systemMessage }, | |
| 110 | - contextItems: [], | |
| 111 | - }); | |
| 112 | - } | |
| 113 | - | |
| 114 | - return chatHistory; | |
| 103 | + return []; | |
| 115 | 104 | } |
| 116 | 105 | |
| 117 | 106 | // Helper function to handle manual compaction |
| @@ -168,7 +157,7 @@ | ||
| 168 | 157 | format?: "json", |
| 169 | 158 | ): Promise<number | null> { |
| 170 | 159 | const { handleAutoCompaction: coreAutoCompaction } = await import( |
| 171 | - "../streamChatResponse.autoCompaction.js" | |
| 160 | + "../stream/streamChatResponse.autoCompaction.js" | |
| 172 | 161 | ); |
| 173 | 162 | |
| 174 | 163 | // Custom callbacks for headless mode console output |
| @@ -234,6 +223,33 @@ | ||
| 234 | 223 | return result.compactionIndex; |
| 235 | 224 | } |
| 236 | 225 | |
| 226 | +/** | |
| 227 | + * Helper to generate and update session title after first assistant response | |
| 228 | + */ | |
| 229 | +async function handleTitleGeneration( | |
| 230 | + assistantResponse: string, | |
| 231 | + llmApi: any, | |
| 232 | + model: ModelConfig, | |
| 233 | +): Promise<void> { | |
| 234 | + try { | |
| 235 | + if (!assistantResponse) return; | |
| 236 | + | |
| 237 | + const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( | |
| 238 | + llmApi, | |
| 239 | + model, | |
| 240 | + assistantResponse, | |
| 241 | + ); | |
| 242 | + | |
| 243 | + if (generatedTitle) { | |
| 244 | + updateSessionTitle(generatedTitle); | |
| 245 | + logger.debug("Generated session title:", generatedTitle); | |
| 246 | + } | |
| 247 | + } catch (error) { | |
| 248 | + // Don't fail the response if title generation fails | |
| 249 | + logger.debug("Session title generation failed:", error); | |
| 250 | + } | |
| 251 | +} | |
| 252 | + | |
| 237 | 253 | interface ProcessMessageOptions { |
| 238 | 254 | userInput: string; |
| 239 | 255 | chatHistory: ChatHistoryItem[]; |
| @@ -243,6 +259,7 @@ | ||
| 243 | 259 | format?: "json"; |
| 244 | 260 | silent?: boolean; |
| 245 | 261 | compactionIndex?: number | null; |
| 262 | + firstAssistantResponse?: boolean; | |
| 246 | 263 | } |
| 247 | 264 | |
| 248 | 265 | async function processMessage( |
| @@ -257,6 +274,7 @@ | ||
| 257 | 274 | format, |
| 258 | 275 | silent, |
| 259 | 276 | compactionIndex: initialCompactionIndex, |
| 277 | + firstAssistantResponse = false, | |
| 260 | 278 | } = options; |
| 261 | 279 | let compactionIndex = initialCompactionIndex; |
| 262 | 280 | // Check for slash commands in headless mode |
| @@ -326,6 +344,11 @@ | ||
| 326 | 344 | // No need to sync back - streamChatResponse modifies chatHistory in place |
| 327 | 345 | } |
| 328 | 346 | |
| 347 | + // Generate session title after first assistant response | |
| 348 | + if (firstAssistantResponse && finalResponse && finalResponse.trim()) { | |
| 349 | + await handleTitleGeneration(finalResponse, llmApi, model); | |
| 350 | + } | |
| 351 | + | |
| 329 | 352 | // In headless mode, only print the final response using safe stdout |
| 330 | 353 | if (isHeadless && finalResponse && finalResponse.trim()) { |
| 331 | 354 | let processedResponse = finalResponse; |
| @@ -433,6 +456,7 @@ | ||
| 433 | 456 | format: options.format, |
| 434 | 457 | silent: options.silent, |
| 435 | 458 | compactionIndex, |
| 459 | + firstAssistantResponse: isFirstMessage && !options.resume, // Only generate title for new conversations | |
| 436 | 460 | }); |
| 437 | 461 | |
| 438 | 462 | // Update compaction index if compaction occurred |
| @@ -474,9 +498,6 @@ | ||
| 474 | 498 | console.log(chalk.green("✓ Setup complete! Starting chat...")); |
| 475 | 499 | } |
| 476 | 500 | |
| 477 | - // Show ASCII art and version for TUI mode | |
| 478 | - console.log(getDisplayableAsciiArt()); | |
| 479 | - | |
| 480 | 501 | // Start TUI with skipOnboarding since we already handled it |
| 481 | 502 | const tuiOptions: any = { |
| 482 | 503 | initialPrompt: prompt, |
modified extensions/cli/src/commands/serve.helpers.ts +2 −2
| @@ -5,8 +5,8 @@ | ||
| 5 | 5 | ToolStatus, |
| 6 | 6 | } from "core/index.js"; |
| 7 | 7 | |
| 8 | -import { streamChatResponse } from "../streamChatResponse.js"; | |
| 9 | -import { StreamCallbacks } from "../streamChatResponse.types.js"; | |
| 8 | +import { streamChatResponse } from "../stream/streamChatResponse.js"; | |
| 9 | +import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; | |
| 10 | 10 | |
| 11 | 11 | // Modified version of streamChatResponse that supports interruption |
| 12 | 12 | export async function streamChatResponseWithInterruption( |
modified extensions/cli/src/commands/serve.ts +1 −1
| @@ -3,11 +3,11 @@ | ||
| 3 | 3 | |
| 4 | 4 | import chalk from "chalk"; |
| 5 | 5 | import type { ChatHistoryItem } from "core/index.js"; |
| 6 | +import { convertFromUnifiedHistory } from "core/util/messageConversion.js"; | |
| 6 | 7 | import express, { Request, Response } from "express"; |
| 7 | 8 | |
| 8 | 9 | import { getAssistantSlug } from "../auth/workos.js"; |
| 9 | 10 | import { processCommandFlags } from "../flags/flagProcessor.js"; |
| 10 | -import { convertFromUnifiedHistory } from "../messageConversion.js"; | |
| 11 | 11 | import { toolPermissionManager } from "../permissions/permissionManager.js"; |
| 12 | 12 | import { |
| 13 | 13 | getService, |
modified extensions/cli/src/compaction.infiniteLoop.test.ts +4 −4
| @@ -1,13 +1,13 @@ | ||
| 1 | 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | -import { describe, it, expect, vi } from "vitest"; | |
| 3 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 4 | +import { describe, expect, it, vi } from "vitest"; | |
| 4 | 5 | |
| 5 | 6 | import { compactChatHistory } from "./compaction.js"; |
| 6 | -import { convertToUnifiedHistory } from "./messageConversion.js"; | |
| 7 | -import { streamChatResponse } from "./streamChatResponse.js"; | |
| 7 | +import { streamChatResponse } from "./stream/streamChatResponse.js"; | |
| 8 | 8 | |
| 9 | 9 | // Mock the dependencies |
| 10 | -vi.mock("./streamChatResponse.js", () => ({ | |
| 10 | +vi.mock("./stream/streamChatResponse.js", () => ({ | |
| 11 | 11 | streamChatResponse: vi.fn(), |
| 12 | 12 | })); |
| 13 | 13 |
modified extensions/cli/src/compaction.pruneLastMessage.test.ts +2 −2
| @@ -1,7 +1,7 @@ | ||
| 1 | -import { describe, it, expect } from "vitest"; | |
| 1 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 2 | +import { describe, expect, it } from "vitest"; | |
| 2 | 3 | |
| 3 | 4 | import { pruneLastMessage } from "./compaction.js"; |
| 4 | -import { convertToUnifiedHistory } from "./messageConversion.js"; | |
| 5 | 5 | import { logger } from "./util/logger.js"; |
| 6 | 6 | |
| 7 | 7 | describe("pruneLastMessage", () => { |
modified extensions/cli/src/compaction.test.ts +3 −3
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { ModelConfig } from "@continuedev/config-yaml"; |
| 2 | 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | 3 | import type { ChatHistoryItem } from "core/index.js"; |
| 4 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 4 | 5 | import { describe, expect, it, vi } from "vitest"; |
| 5 | 6 | |
| 6 | 7 | import { |
| @@ -8,11 +9,10 @@ | ||
| 8 | 9 | findCompactionIndex, |
| 9 | 10 | getHistoryForLLM, |
| 10 | 11 | } from "./compaction.js"; |
| 11 | -import { convertToUnifiedHistory } from "./messageConversion.js"; | |
| 12 | -import { streamChatResponse } from "./streamChatResponse.js"; | |
| 12 | +import { streamChatResponse } from "./stream/streamChatResponse.js"; | |
| 13 | 13 | |
| 14 | 14 | // Mock the streamChatResponse function |
| 15 | -vi.mock("./streamChatResponse.js", () => ({ | |
| 15 | +vi.mock("./stream/streamChatResponse.js", () => ({ | |
| 16 | 16 | streamChatResponse: vi.fn(), |
| 17 | 17 | })); |
| 18 | 18 |
modified extensions/cli/src/compaction.ts +2 −2
| @@ -2,8 +2,8 @@ | ||
| 2 | 2 | import { BaseLlmApi } from "@continuedev/openai-adapters"; |
| 3 | 3 | import type { ChatHistoryItem } from "core/index.js"; |
| 4 | 4 | |
| 5 | -import { streamChatResponse } from "./streamChatResponse.js"; | |
| 6 | -import { StreamCallbacks } from "./streamChatResponse.types.js"; | |
| 5 | +import { streamChatResponse } from "./stream/streamChatResponse.js"; | |
| 6 | +import { StreamCallbacks } from "./stream/streamChatResponse.types.js"; | |
| 7 | 7 | import { logger } from "./util/logger.js"; |
| 8 | 8 | import { |
| 9 | 9 | countChatHistoryTokens, |
modified extensions/cli/src/configLoader.ts +2 −1
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | getConfigUri, |
| 19 | 19 | getOrganizationId, |
| 20 | 20 | isEnvironmentAuthConfig, |
| 21 | + loadAuthConfig, | |
| 21 | 22 | updateConfigUri, |
| 22 | 23 | } from "./auth/workos.js"; |
| 23 | 24 | import { CLIPlatformClient } from "./CLIPlatformClient.js"; |
| @@ -358,7 +359,7 @@ | ||
| 358 | 359 | uriType: "slug", |
| 359 | 360 | fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, |
| 360 | 361 | }, |
| 361 | - null, | |
| 362 | + getAccessToken(loadAuthConfig()), | |
| 362 | 363 | organizationId, |
| 363 | 364 | apiClient, |
| 364 | 365 | ); |
added extensions/cli/src/constants/session.ts +4 −0
| @@ -0,0 +1,4 @@ | ||
| 1 | +/** | |
| 2 | + * Session-related constants | |
| 3 | + */ | |
| 4 | +export const DEFAULT_SESSION_TITLE = "Untitled Session"; |
modified extensions/cli/src/e2e/auth.test.ts +19 −3
| @@ -29,13 +29,23 @@ | ||
| 29 | 29 | await fs.writeFile( |
| 30 | 30 | authPath, |
| 31 | 31 | JSON.stringify({ |
| 32 | + userId: "test-user", | |
| 33 | + userEmail: "test@example.com", | |
| 32 | 34 | accessToken: "test-token", |
| 33 | - user: { id: "test-user", email: "test@example.com" }, | |
| 35 | + refreshToken: "test-refresh-token", | |
| 36 | + expiresAt: Date.now() + 3600000, | |
| 37 | + organizationId: null, | |
| 34 | 38 | }), |
| 35 | 39 | ); |
| 36 | 40 | |
| 37 | 41 | // Run logout |
| 38 | - const result = await runCLI(context, { args: ["logout"] }); | |
| 42 | + const result = await runCLI(context, { | |
| 43 | + args: ["logout"], | |
| 44 | + env: { | |
| 45 | + HOME: context.testDir, | |
| 46 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue") | |
| 47 | + } | |
| 48 | + }); | |
| 39 | 49 | |
| 40 | 50 | expect(result.exitCode).toBe(0); |
| 41 | 51 | expect(result.stdout).toContain("Successfully logged out"); |
| @@ -49,7 +59,13 @@ | ||
| 49 | 59 | }); |
| 50 | 60 | |
| 51 | 61 | it("should handle logout when not logged in", async () => { |
| 52 | - const result = await runCLI(context, { args: ["logout"] }); | |
| 62 | + const result = await runCLI(context, { | |
| 63 | + args: ["logout"], | |
| 64 | + env: { | |
| 65 | + HOME: context.testDir, | |
| 66 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue") | |
| 67 | + } | |
| 68 | + }); | |
| 53 | 69 | |
| 54 | 70 | expect(result.exitCode).toBe(0); |
| 55 | 71 | expect(result.stdout).toContain("No active session found"); |
modified extensions/cli/src/e2e/resume-flag.test.ts +21 −0
| @@ -35,6 +35,7 @@ | ||
| 35 | 35 | env: { |
| 36 | 36 | // Use a fixed session ID so both CLI calls use the same session |
| 37 | 37 | CONTINUE_CLI_TEST_SESSION_ID: "test-session-123", |
| 38 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), | |
| 38 | 39 | }, |
| 39 | 40 | timeout: 15000, |
| 40 | 41 | }); |
| @@ -45,6 +46,14 @@ | ||
| 45 | 46 | |
| 46 | 47 | // Verify that a session file was created |
| 47 | 48 | const sessionDir = path.join(context.testDir, ".continue", "sessions"); |
| 49 | + | |
| 50 | + // Ensure session directory exists | |
| 51 | + try { | |
| 52 | + await fs.mkdir(sessionDir, { recursive: true }); | |
| 53 | + } catch (error) { | |
| 54 | + // Directory already exists, continue | |
| 55 | + } | |
| 56 | + | |
| 48 | 57 | const sessionFiles = (await fs.readdir(sessionDir)).filter( |
| 49 | 58 | f => f.endsWith('.json') && f !== 'sessions.json' |
| 50 | 59 | ); |
| @@ -75,6 +84,7 @@ | ||
| 75 | 84 | args: ["--resume", "--config", context.configPath], |
| 76 | 85 | env: { |
| 77 | 86 | CONTINUE_CLI_TEST_SESSION_ID: "test-session-123", |
| 87 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), | |
| 78 | 88 | }, |
| 79 | 89 | timeout: 15000, |
| 80 | 90 | }); |
| @@ -92,6 +102,7 @@ | ||
| 92 | 102 | args: ["--resume", "--config", context.configPath], |
| 93 | 103 | env: { |
| 94 | 104 | CONTINUE_CLI_TEST_SESSION_ID: "no-session-456", |
| 105 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), | |
| 95 | 106 | }, |
| 96 | 107 | timeout: 15000, |
| 97 | 108 | }); |
| @@ -129,6 +140,7 @@ | ||
| 129 | 140 | args: ["-p", "--config", context.configPath, "first message"], |
| 130 | 141 | env: { |
| 131 | 142 | CONTINUE_CLI_TEST_SESSION_ID: sessionId, |
| 143 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), | |
| 132 | 144 | }, |
| 133 | 145 | timeout: 15000, |
| 134 | 146 | }); |
| @@ -138,6 +150,14 @@ | ||
| 138 | 150 | |
| 139 | 151 | // Verify the first session was saved correctly |
| 140 | 152 | const sessionDir = path.join(context.testDir, ".continue", "sessions"); |
| 153 | + | |
| 154 | + // Ensure session directory exists | |
| 155 | + try { | |
| 156 | + await fs.mkdir(sessionDir, { recursive: true }); | |
| 157 | + } catch (error) { | |
| 158 | + // Directory already exists, continue | |
| 159 | + } | |
| 160 | + | |
| 141 | 161 | let sessionFiles = (await fs.readdir(sessionDir)).filter( |
| 142 | 162 | f => f.endsWith('.json') && f !== 'sessions.json' |
| 143 | 163 | ); |
| @@ -159,6 +179,7 @@ | ||
| 159 | 179 | ], |
| 160 | 180 | env: { |
| 161 | 181 | CONTINUE_CLI_TEST_SESSION_ID: sessionId, |
| 182 | + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), | |
| 162 | 183 | }, |
| 163 | 184 | timeout: 15000, |
| 164 | 185 | }); |
modified extensions/cli/src/messageConversion.test.ts +1 −2
| @@ -1,6 +1,5 @@ | ||
| 1 | 1 | import type { ChatHistoryItem } from "core/index.js"; |
| 2 | - | |
| 3 | -import { convertFromUnifiedHistory } from "./messageConversion.js"; | |
| 2 | +import { convertFromUnifiedHistory } from "core/util/messageConversion.js"; | |
| 4 | 3 | |
| 5 | 4 | describe("convertFromUnifiedHistory", () => { |
| 6 | 5 | it("should expand contextItems into user message content", () => { |
deleted extensions/cli/src/messageConversion.ts +0 −372
| @@ -1,372 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Message conversion utilities for transitioning to unified ChatHistoryItem type. | |
| 3 | - * | |
| 4 | - * This module provides conversion functions between the OpenAI ChatCompletionMessageParam | |
| 5 | - * format and the unified ChatHistoryItem format from the core package. | |
| 6 | - */ | |
| 7 | - | |
| 8 | -import type { | |
| 9 | - AssistantChatMessage, | |
| 10 | - ChatHistoryItem, | |
| 11 | - ChatMessage, | |
| 12 | - ContextItemWithId, | |
| 13 | - MessageContent, | |
| 14 | - ToolCall, | |
| 15 | - ToolCallState, | |
| 16 | - ToolStatus, | |
| 17 | -} from "core/index.js"; | |
| 18 | -import type { ChatCompletionMessageParam } from "openai/resources.mjs"; | |
| 19 | - | |
| 20 | -/** | |
| 21 | - * Convert ChatCompletionMessageParam to ChatMessage | |
| 22 | - */ | |
| 23 | -export function convertToUnifiedMessage( | |
| 24 | - message: ChatCompletionMessageParam, | |
| 25 | -): ChatMessage { | |
| 26 | - switch (message.role) { | |
| 27 | - case "system": | |
| 28 | - return { | |
| 29 | - role: "system", | |
| 30 | - content: typeof message.content === "string" ? message.content : "", | |
| 31 | - }; | |
| 32 | - | |
| 33 | - case "user": | |
| 34 | - return { | |
| 35 | - role: "user", | |
| 36 | - content: convertMessageContent(message.content), | |
| 37 | - }; | |
| 38 | - | |
| 39 | - case "assistant": { | |
| 40 | - const assistantMessage: AssistantChatMessage = { | |
| 41 | - role: "assistant", | |
| 42 | - content: convertMessageContent(message.content || ""), | |
| 43 | - }; | |
| 44 | - | |
| 45 | - // Convert tool calls if present | |
| 46 | - if ("tool_calls" in message && message.tool_calls) { | |
| 47 | - assistantMessage.toolCalls = message.tool_calls.map((tc: any) => ({ | |
| 48 | - id: tc.id, | |
| 49 | - type: "function" as const, | |
| 50 | - function: { | |
| 51 | - name: tc.function?.name || "", | |
| 52 | - arguments: tc.function?.arguments || "", | |
| 53 | - }, | |
| 54 | - })); | |
| 55 | - } | |
| 56 | - | |
| 57 | - return assistantMessage; | |
| 58 | - } | |
| 59 | - | |
| 60 | - case "tool": | |
| 61 | - return { | |
| 62 | - role: "tool", | |
| 63 | - content: typeof message.content === "string" ? message.content : "", | |
| 64 | - toolCallId: message.tool_call_id, | |
| 65 | - }; | |
| 66 | - | |
| 67 | - default: | |
| 68 | - throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 69 | - } | |
| 70 | -} | |
| 71 | - | |
| 72 | -/** | |
| 73 | - * Convert ChatMessage to ChatCompletionMessageParam | |
| 74 | - */ | |
| 75 | -export function convertFromUnifiedMessage( | |
| 76 | - message: ChatMessage, | |
| 77 | -): ChatCompletionMessageParam { | |
| 78 | - switch (message.role) { | |
| 79 | - case "system": | |
| 80 | - return { | |
| 81 | - role: "system", | |
| 82 | - content: message.content, | |
| 83 | - }; | |
| 84 | - | |
| 85 | - case "user": | |
| 86 | - return { | |
| 87 | - role: "user", | |
| 88 | - content: convertFromMessageContent(message.content), | |
| 89 | - }; | |
| 90 | - | |
| 91 | - case "assistant": { | |
| 92 | - const assistantMessage: ChatCompletionMessageParam = { | |
| 93 | - role: "assistant", | |
| 94 | - content: convertFromMessageContent(message.content), | |
| 95 | - }; | |
| 96 | - | |
| 97 | - // Convert tool calls if present | |
| 98 | - if (message.toolCalls && message.toolCalls.length > 0) { | |
| 99 | - (assistantMessage as any).tool_calls = message.toolCalls.map( | |
| 100 | - (tc: any) => ({ | |
| 101 | - id: tc.id, | |
| 102 | - type: "function", | |
| 103 | - function: { | |
| 104 | - name: tc.function?.name || "", | |
| 105 | - arguments: tc.function?.arguments || "", | |
| 106 | - }, | |
| 107 | - }), | |
| 108 | - ); | |
| 109 | - } | |
| 110 | - | |
| 111 | - return assistantMessage; | |
| 112 | - } | |
| 113 | - | |
| 114 | - case "tool": | |
| 115 | - return { | |
| 116 | - role: "tool", | |
| 117 | - content: message.content, | |
| 118 | - tool_call_id: message.toolCallId, | |
| 119 | - }; | |
| 120 | - | |
| 121 | - case "thinking": | |
| 122 | - // Thinking messages don't have a direct equivalent in OpenAI format | |
| 123 | - // Convert to assistant message with content | |
| 124 | - return { | |
| 125 | - role: "assistant", | |
| 126 | - content: convertFromMessageContent(message.content), | |
| 127 | - }; | |
| 128 | - | |
| 129 | - default: | |
| 130 | - throw new Error(`Unsupported message role: ${(message as any).role}`); | |
| 131 | - } | |
| 132 | -} | |
| 133 | - | |
| 134 | -/** | |
| 135 | - * Convert OpenAI message content to unified MessageContent format | |
| 136 | - */ | |
| 137 | -function convertMessageContent( | |
| 138 | - content: string | null | Array<any>, | |
| 139 | -): MessageContent { | |
| 140 | - if (content === null) { | |
| 141 | - return ""; | |
| 142 | - } | |
| 143 | - | |
| 144 | - if (typeof content === "string") { | |
| 145 | - return content; | |
| 146 | - } | |
| 147 | - | |
| 148 | - if (Array.isArray(content)) { | |
| 149 | - return content.map((part: any) => { | |
| 150 | - if (part.type === "text") { | |
| 151 | - return { | |
| 152 | - type: "text" as const, | |
| 153 | - text: part.text, | |
| 154 | - }; | |
| 155 | - } else if (part.type === "image_url") { | |
| 156 | - return { | |
| 157 | - type: "imageUrl" as const, | |
| 158 | - imageUrl: { url: part.image_url.url }, | |
| 159 | - }; | |
| 160 | - } | |
| 161 | - throw new Error(`Unsupported content part type: ${part.type}`); | |
| 162 | - }); | |
| 163 | - } | |
| 164 | - | |
| 165 | - throw new Error(`Unsupported content type: ${typeof content}`); | |
| 166 | -} | |
| 167 | - | |
| 168 | -/** | |
| 169 | - * Convert unified MessageContent to OpenAI format | |
| 170 | - */ | |
| 171 | -function convertFromMessageContent( | |
| 172 | - content: MessageContent, | |
| 173 | -): string | Array<any> { | |
| 174 | - if (typeof content === "string") { | |
| 175 | - return content; | |
| 176 | - } | |
| 177 | - | |
| 178 | - if (Array.isArray(content)) { | |
| 179 | - return content.map((part: any) => { | |
| 180 | - if (part.type === "text") { | |
| 181 | - return { | |
| 182 | - type: "text", | |
| 183 | - text: part.text, | |
| 184 | - }; | |
| 185 | - } else if (part.type === "imageUrl") { | |
| 186 | - return { | |
| 187 | - type: "image_url", | |
| 188 | - image_url: { url: part.imageUrl.url }, | |
| 189 | - }; | |
| 190 | - } | |
| 191 | - throw new Error(`Unsupported content part type: ${part.type}`); | |
| 192 | - }); | |
| 193 | - } | |
| 194 | - | |
| 195 | - throw new Error(`Unsupported content type: ${typeof content}`); | |
| 196 | -} | |
| 197 | - | |
| 198 | -/** | |
| 199 | - * Create a ChatHistoryItem from a ChatMessage | |
| 200 | - */ | |
| 201 | -export function createHistoryItem( | |
| 202 | - message: ChatMessage, | |
| 203 | - contextItems: ContextItemWithId[] = [], | |
| 204 | - toolCallStates?: ToolCallState[], | |
| 205 | -): ChatHistoryItem { | |
| 206 | - return { | |
| 207 | - message, | |
| 208 | - contextItems, | |
| 209 | - ...(toolCallStates && { toolCallStates }), | |
| 210 | - }; | |
| 211 | -} | |
| 212 | - | |
| 213 | -/** | |
| 214 | - * Handle tool result message by updating the corresponding tool call state | |
| 215 | - */ | |
| 216 | -function handleToolResult( | |
| 217 | - unifiedMessage: ChatMessage & { role: "tool" }, | |
| 218 | - pendingToolCalls: Map<string, ToolCall>, | |
| 219 | - historyItems: ChatHistoryItem[], | |
| 220 | -): void { | |
| 221 | - const toolCall = pendingToolCalls.get(unifiedMessage.toolCallId); | |
| 222 | - if (!toolCall) return; | |
| 223 | - | |
| 224 | - // Add tool result as context to the previous assistant message | |
| 225 | - const lastAssistantIndex = historyItems.findLastIndex( | |
| 226 | - (item) => item.message.role === "assistant", | |
| 227 | - ); | |
| 228 | - | |
| 229 | - if (lastAssistantIndex < 0) return; | |
| 230 | - if (!historyItems[lastAssistantIndex].toolCallStates) return; | |
| 231 | - | |
| 232 | - const toolState = historyItems[lastAssistantIndex].toolCallStates?.find( | |
| 233 | - (ts) => ts.toolCallId === unifiedMessage.toolCallId, | |
| 234 | - ); | |
| 235 | - | |
| 236 | - if (toolState) { | |
| 237 | - toolState.output = [ | |
| 238 | - { | |
| 239 | - content: unifiedMessage.content as string, | |
| 240 | - name: `Tool Result: ${toolCall.function.name}`, | |
| 241 | - description: "Tool execution result", | |
| 242 | - }, | |
| 243 | - ]; | |
| 244 | - } | |
| 245 | -} | |
| 246 | - | |
| 247 | -/** | |
| 248 | - * Convert array of ChatCompletionMessageParam to ChatHistoryItem array | |
| 249 | - */ | |
| 250 | -export function convertToUnifiedHistory( | |
| 251 | - messages: ChatCompletionMessageParam[], | |
| 252 | -): ChatHistoryItem[] { | |
| 253 | - const historyItems: ChatHistoryItem[] = []; | |
| 254 | - const pendingToolCalls: Map<string, ToolCall> = new Map(); | |
| 255 | - | |
| 256 | - for (const message of messages) { | |
| 257 | - const unifiedMessage = convertToUnifiedMessage(message); | |
| 258 | - | |
| 259 | - if (unifiedMessage.role === "assistant" && unifiedMessage.toolCalls) { | |
| 260 | - // Store tool calls for matching with results | |
| 261 | - const toolCallStates: ToolCallState[] = unifiedMessage.toolCalls.map( | |
| 262 | - (tc: any) => { | |
| 263 | - const toolCall: ToolCall = { | |
| 264 | - id: tc.id || "", | |
| 265 | - type: "function", | |
| 266 | - function: { | |
| 267 | - name: tc.function?.name || "", | |
| 268 | - arguments: tc.function?.arguments || "", | |
| 269 | - }, | |
| 270 | - }; | |
| 271 | - pendingToolCalls.set(toolCall.id, toolCall); | |
| 272 | - | |
| 273 | - return { | |
| 274 | - toolCallId: toolCall.id, | |
| 275 | - toolCall, | |
| 276 | - status: "done" as ToolStatus, // Historical calls are complete | |
| 277 | - parsedArgs: tryParseJson(toolCall.function.arguments), | |
| 278 | - }; | |
| 279 | - }, | |
| 280 | - ); | |
| 281 | - | |
| 282 | - historyItems.push(createHistoryItem(unifiedMessage, [], toolCallStates)); | |
| 283 | - } else if (unifiedMessage.role === "tool") { | |
| 284 | - // Tool result - handle separately to reduce nesting | |
| 285 | - handleToolResult(unifiedMessage, pendingToolCalls, historyItems); | |
| 286 | - // Don't add tool messages as separate history items | |
| 287 | - } else { | |
| 288 | - historyItems.push(createHistoryItem(unifiedMessage)); | |
| 289 | - } | |
| 290 | - } | |
| 291 | - | |
| 292 | - return historyItems; | |
| 293 | -} | |
| 294 | - | |
| 295 | -/** | |
| 296 | - * Convert ChatHistoryItem array to ChatCompletionMessageParam array | |
| 297 | - */ | |
| 298 | -export function convertFromUnifiedHistory( | |
| 299 | - historyItems: ChatHistoryItem[], | |
| 300 | -): ChatCompletionMessageParam[] { | |
| 301 | - const messages: ChatCompletionMessageParam[] = []; | |
| 302 | - | |
| 303 | - for (const item of historyItems) { | |
| 304 | - const baseMessage = convertFromUnifiedMessage(item.message); | |
| 305 | - | |
| 306 | - // If this is a user message with context items, expand the content | |
| 307 | - if ( | |
| 308 | - item.message.role === "user" && | |
| 309 | - item.contextItems && | |
| 310 | - item.contextItems.length > 0 | |
| 311 | - ) { | |
| 312 | - const contextContent = item.contextItems | |
| 313 | - .map( | |
| 314 | - (contextItem) => | |
| 315 | - `<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`, | |
| 316 | - ) | |
| 317 | - .join(""); | |
| 318 | - | |
| 319 | - baseMessage.content = | |
| 320 | - typeof baseMessage.content === "string" | |
| 321 | - ? contextContent + baseMessage.content | |
| 322 | - : baseMessage.content; // Keep array format if it's already an array | |
| 323 | - } | |
| 324 | - | |
| 325 | - messages.push(baseMessage); | |
| 326 | - | |
| 327 | - // Add tool result messages if there are completed tool calls | |
| 328 | - if (item.toolCallStates) { | |
| 329 | - for (const toolState of item.toolCallStates) { | |
| 330 | - if (toolState.output && toolState.output.length > 0) { | |
| 331 | - messages.push({ | |
| 332 | - role: "tool", | |
| 333 | - content: toolState.output.map((o: any) => o.content).join("\n"), | |
| 334 | - tool_call_id: toolState.toolCallId, | |
| 335 | - }); | |
| 336 | - } | |
| 337 | - } | |
| 338 | - } | |
| 339 | - } | |
| 340 | - | |
| 341 | - return messages; | |
| 342 | -} | |
| 343 | - | |
| 344 | -/** | |
| 345 | - * Extract tool call information from a ChatHistoryItem | |
| 346 | - */ | |
| 347 | -export function extractToolCallInfo(historyItem: ChatHistoryItem): { | |
| 348 | - hasToolCalls: boolean; | |
| 349 | - toolCalls?: ToolCall[]; | |
| 350 | - toolStates?: ToolCallState[]; | |
| 351 | -} { | |
| 352 | - const hasToolCalls = !!( | |
| 353 | - historyItem.toolCallStates && historyItem.toolCallStates.length > 0 | |
| 354 | - ); | |
| 355 | - | |
| 356 | - return { | |
| 357 | - hasToolCalls, | |
| 358 | - toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall), | |
| 359 | - toolStates: historyItem.toolCallStates, | |
| 360 | - }; | |
| 361 | -} | |
| 362 | - | |
| 363 | -/** | |
| 364 | - * Helper to safely parse JSON | |
| 365 | - */ | |
| 366 | -function tryParseJson(str: string): any { | |
| 367 | - try { | |
| 368 | - return JSON.parse(str); | |
| 369 | - } catch { | |
| 370 | - return str; | |
| 371 | - } | |
| 372 | -} |
added extensions/cli/src/services/SystemMessageService.test.ts +187 −0
| @@ -0,0 +1,187 @@ | ||
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { modeService } from "./ModeService.js"; | |
| 4 | +import { SystemMessageService } from "./SystemMessageService.js"; | |
| 5 | + | |
| 6 | +// Mock the systemMessage module | |
| 7 | +vi.mock("../systemMessage.js", () => ({ | |
| 8 | + constructSystemMessage: vi.fn(), | |
| 9 | +})); | |
| 10 | + | |
| 11 | +// Mock the logger | |
| 12 | +vi.mock("../util/logger.js", () => ({ | |
| 13 | + logger: { | |
| 14 | + debug: vi.fn(), | |
| 15 | + info: vi.fn(), | |
| 16 | + warn: vi.fn(), | |
| 17 | + error: vi.fn(), | |
| 18 | + }, | |
| 19 | +})); | |
| 20 | + | |
| 21 | +describe("SystemMessageService", () => { | |
| 22 | + let service: SystemMessageService; | |
| 23 | + let constructSystemMessageMock: any; | |
| 24 | + | |
| 25 | + beforeEach(async () => { | |
| 26 | + // Reset mocks | |
| 27 | + vi.clearAllMocks(); | |
| 28 | + | |
| 29 | + // Get mock reference | |
| 30 | + const { constructSystemMessage } = await import("../systemMessage.js"); | |
| 31 | + constructSystemMessageMock = constructSystemMessage as any; | |
| 32 | + | |
| 33 | + // Create new service instance | |
| 34 | + service = new SystemMessageService(); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + afterEach(async () => { | |
| 38 | + await service.cleanup(); | |
| 39 | + }); | |
| 40 | + | |
| 41 | + describe("initialization", () => { | |
| 42 | + it("should initialize with provided configuration", async () => { | |
| 43 | + const config = { | |
| 44 | + additionalRules: ["rule1", "rule2"], | |
| 45 | + format: "json" as const, | |
| 46 | + headless: true, | |
| 47 | + }; | |
| 48 | + | |
| 49 | + const state = await service.initialize(config); | |
| 50 | + | |
| 51 | + expect(state).toEqual(config); | |
| 52 | + expect(service.isReady()).toBe(true); | |
| 53 | + }); | |
| 54 | + | |
| 55 | + it("should initialize with empty configuration", async () => { | |
| 56 | + const state = await service.initialize({}); | |
| 57 | + | |
| 58 | + expect(state).toEqual({}); | |
| 59 | + expect(service.isReady()).toBe(true); | |
| 60 | + }); | |
| 61 | + }); | |
| 62 | + | |
| 63 | + describe("getSystemMessage", () => { | |
| 64 | + it("should call constructSystemMessage with current configuration and mode", async () => { | |
| 65 | + const config = { | |
| 66 | + additionalRules: ["rule1"], | |
| 67 | + format: "json" as const, | |
| 68 | + headless: true, | |
| 69 | + }; | |
| 70 | + | |
| 71 | + constructSystemMessageMock.mockResolvedValue("Test system message"); | |
| 72 | + | |
| 73 | + await service.initialize(config); | |
| 74 | + const message = await service.getSystemMessage(); | |
| 75 | + | |
| 76 | + expect(constructSystemMessageMock).toHaveBeenCalledWith( | |
| 77 | + ["rule1"], | |
| 78 | + "json", | |
| 79 | + true, | |
| 80 | + "normal", // Default mode | |
| 81 | + ); | |
| 82 | + expect(message).toBe("Test system message"); | |
| 83 | + }); | |
| 84 | + | |
| 85 | + it("should use updated mode when mode changes", async () => { | |
| 86 | + constructSystemMessageMock.mockResolvedValue("Updated system message"); | |
| 87 | + | |
| 88 | + await service.initialize({}); | |
| 89 | + | |
| 90 | + // Simulate mode change | |
| 91 | + modeService.emit("modeChanged", "plan", "normal"); | |
| 92 | + | |
| 93 | + const message = await service.getSystemMessage(); | |
| 94 | + | |
| 95 | + expect(constructSystemMessageMock).toHaveBeenCalledWith( | |
| 96 | + undefined, | |
| 97 | + undefined, | |
| 98 | + undefined, | |
| 99 | + "plan", | |
| 100 | + ); | |
| 101 | + expect(message).toBe("Updated system message"); | |
| 102 | + }); | |
| 103 | + }); | |
| 104 | + | |
| 105 | + describe("updateConfig", () => { | |
| 106 | + it("should update configuration partially", async () => { | |
| 107 | + await service.initialize({ | |
| 108 | + additionalRules: ["rule1"], | |
| 109 | + headless: false, | |
| 110 | + }); | |
| 111 | + | |
| 112 | + service.updateConfig({ | |
| 113 | + format: "json", | |
| 114 | + }); | |
| 115 | + | |
| 116 | + constructSystemMessageMock.mockResolvedValue("Updated message"); | |
| 117 | + await service.getSystemMessage(); | |
| 118 | + | |
| 119 | + expect(constructSystemMessageMock).toHaveBeenCalledWith( | |
| 120 | + ["rule1"], | |
| 121 | + "json", | |
| 122 | + false, | |
| 123 | + "normal", | |
| 124 | + ); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should override existing configuration", async () => { | |
| 128 | + await service.initialize({ | |
| 129 | + additionalRules: ["rule1"], | |
| 130 | + format: "json" as const, | |
| 131 | + }); | |
| 132 | + | |
| 133 | + service.updateConfig({ | |
| 134 | + additionalRules: ["rule2", "rule3"], | |
| 135 | + }); | |
| 136 | + | |
| 137 | + constructSystemMessageMock.mockResolvedValue("Updated message"); | |
| 138 | + await service.getSystemMessage(); | |
| 139 | + | |
| 140 | + expect(constructSystemMessageMock).toHaveBeenCalledWith( | |
| 141 | + ["rule2", "rule3"], | |
| 142 | + "json", | |
| 143 | + undefined, | |
| 144 | + "normal", | |
| 145 | + ); | |
| 146 | + }); | |
| 147 | + }); | |
| 148 | + | |
| 149 | + describe("mode tracking", () => { | |
| 150 | + it("should track current mode from ModeService", async () => { | |
| 151 | + await service.initialize({}); | |
| 152 | + | |
| 153 | + expect(service.getCurrentMode()).toBe("normal"); | |
| 154 | + | |
| 155 | + // Simulate mode change | |
| 156 | + modeService.emit("modeChanged", "auto", "normal"); | |
| 157 | + | |
| 158 | + expect(service.getCurrentMode()).toBe("auto"); | |
| 159 | + }); | |
| 160 | + | |
| 161 | + it("should initialize with current mode from ModeService", async () => { | |
| 162 | + // Mock modeService.getCurrentMode | |
| 163 | + vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); | |
| 164 | + | |
| 165 | + const newService = new SystemMessageService(); | |
| 166 | + await newService.initialize({}); | |
| 167 | + | |
| 168 | + expect(newService.getCurrentMode()).toBe("plan"); | |
| 169 | + | |
| 170 | + await newService.cleanup(); | |
| 171 | + }); | |
| 172 | + }); | |
| 173 | + | |
| 174 | + describe("error handling", () => { | |
| 175 | + it("should handle constructSystemMessage errors gracefully", async () => { | |
| 176 | + constructSystemMessageMock.mockRejectedValue( | |
| 177 | + new Error("Failed to construct"), | |
| 178 | + ); | |
| 179 | + | |
| 180 | + await service.initialize({}); | |
| 181 | + | |
| 182 | + await expect(service.getSystemMessage()).rejects.toThrow( | |
| 183 | + "Failed to construct", | |
| 184 | + ); | |
| 185 | + }); | |
| 186 | + }); | |
| 187 | +}); |
added extensions/cli/src/services/SystemMessageService.ts +106 −0
| @@ -0,0 +1,106 @@ | ||
| 1 | +import { PermissionMode } from "../permissions/types.js"; | |
| 2 | +import { constructSystemMessage } from "../systemMessage.js"; | |
| 3 | +import { logger } from "../util/logger.js"; | |
| 4 | + | |
| 5 | +import { BaseService } from "./BaseService.js"; | |
| 6 | +import { modeService } from "./ModeService.js"; | |
| 7 | + | |
| 8 | +export interface SystemMessageServiceState { | |
| 9 | + additionalRules?: string[]; | |
| 10 | + format?: "json"; | |
| 11 | + headless?: boolean; | |
| 12 | +} | |
| 13 | + | |
| 14 | +/** | |
| 15 | + * Service for managing dynamic system message construction | |
| 16 | + * Provides fresh system messages that reflect current mode and configuration | |
| 17 | + */ | |
| 18 | +export class SystemMessageService extends BaseService<SystemMessageServiceState> { | |
| 19 | + private currentMode: PermissionMode = "normal"; | |
| 20 | + | |
| 21 | + constructor() { | |
| 22 | + super("SystemMessageService", {}); | |
| 23 | + | |
| 24 | + // Listen to mode changes from ModeService | |
| 25 | + this.setupModeListener(); | |
| 26 | + } | |
| 27 | + | |
| 28 | + /** | |
| 29 | + * Set up listener for mode changes | |
| 30 | + */ | |
| 31 | + private setupModeListener(): void { | |
| 32 | + modeService.on("modeChanged", (newMode: PermissionMode) => { | |
| 33 | + logger.debug(`SystemMessageService: Mode changed to ${newMode}`); | |
| 34 | + this.currentMode = newMode; | |
| 35 | + }); | |
| 36 | + | |
| 37 | + // Initialize current mode | |
| 38 | + this.currentMode = modeService.getCurrentMode(); | |
| 39 | + } | |
| 40 | + | |
| 41 | + /** | |
| 42 | + * Initialize the service | |
| 43 | + */ | |
| 44 | + async doInitialize(args: { | |
| 45 | + additionalRules?: string[]; | |
| 46 | + format?: "json"; | |
| 47 | + headless?: boolean; | |
| 48 | + }): Promise<SystemMessageServiceState> { | |
| 49 | + this.setState({ | |
| 50 | + additionalRules: args.additionalRules, | |
| 51 | + format: args.format, | |
| 52 | + headless: args.headless, | |
| 53 | + }); | |
| 54 | + | |
| 55 | + logger.debug("SystemMessageService initialized", { | |
| 56 | + hasAdditionalRules: !!args.additionalRules?.length, | |
| 57 | + format: args.format, | |
| 58 | + headless: args.headless, | |
| 59 | + }); | |
| 60 | + | |
| 61 | + return this.currentState; | |
| 62 | + } | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * Get a fresh system message with current mode and configuration | |
| 66 | + */ | |
| 67 | + public async getSystemMessage(): Promise<string> { | |
| 68 | + const { additionalRules, format, headless } = this.currentState; | |
| 69 | + | |
| 70 | + const systemMessage = await constructSystemMessage( | |
| 71 | + additionalRules, | |
| 72 | + format, | |
| 73 | + headless, | |
| 74 | + this.currentMode, | |
| 75 | + ); | |
| 76 | + | |
| 77 | + logger.debug("Generated fresh system message", { | |
| 78 | + mode: this.currentMode, | |
| 79 | + messageLength: systemMessage.length, | |
| 80 | + }); | |
| 81 | + | |
| 82 | + return systemMessage; | |
| 83 | + } | |
| 84 | + | |
| 85 | + /** | |
| 86 | + * Update configuration that affects system message | |
| 87 | + */ | |
| 88 | + public updateConfig(config: Partial<SystemMessageServiceState>): void { | |
| 89 | + this.setState({ | |
| 90 | + ...this.currentState, | |
| 91 | + ...config, | |
| 92 | + }); | |
| 93 | + | |
| 94 | + logger.debug("SystemMessageService config updated", config); | |
| 95 | + } | |
| 96 | + | |
| 97 | + /** | |
| 98 | + * Get the current mode being used for system messages | |
| 99 | + */ | |
| 100 | + public getCurrentMode(): PermissionMode { | |
| 101 | + return this.currentMode; | |
| 102 | + } | |
| 103 | +} | |
| 104 | + | |
| 105 | +// Export singleton instance | |
| 106 | +export const systemMessageService = new SystemMessageService(); |
modified extensions/cli/src/services/index.ts +14 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { modeService } from "./ModeService.js"; |
| 12 | 12 | import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; |
| 13 | 13 | import { serviceContainer } from "./ServiceContainer.js"; |
| 14 | +import { systemMessageService } from "./SystemMessageService.js"; | |
| 14 | 15 | import { |
| 15 | 16 | ApiClientServiceState, |
| 16 | 17 | AuthServiceState, |
| @@ -111,6 +112,18 @@ | ||
| 111 | 112 | toolPermissionState, |
| 112 | 113 | ); |
| 113 | 114 | |
| 115 | + // Initialize SystemMessageService with command options | |
| 116 | + serviceContainer.register( | |
| 117 | + SERVICE_NAMES.SYSTEM_MESSAGE, | |
| 118 | + () => | |
| 119 | + systemMessageService.initialize({ | |
| 120 | + additionalRules: commandOptions.rule, | |
| 121 | + format: (commandOptions as any).format, // format option from CLI | |
| 122 | + headless: initOptions.headless, | |
| 123 | + }), | |
| 124 | + [], // No dependencies | |
| 125 | + ); | |
| 126 | + | |
| 114 | 127 | serviceContainer.register( |
| 115 | 128 | SERVICE_NAMES.AUTH, |
| 116 | 129 | () => authService.initialize(), |
| @@ -293,6 +306,7 @@ | ||
| 293 | 306 | fileIndex: fileIndexService, |
| 294 | 307 | mode: modeService, |
| 295 | 308 | resourceMonitoring: resourceMonitoringService, |
| 309 | + systemMessage: systemMessageService, | |
| 296 | 310 | } as const; |
| 297 | 311 | |
| 298 | 312 | // Export the service container for advanced usage |
modified extensions/cli/src/services/types.ts +1 −0
| @@ -106,6 +106,7 @@ | ||
| 106 | 106 | TOOL_PERMISSIONS: "toolPermissions", |
| 107 | 107 | FILE_INDEX: "fileIndex", |
| 108 | 108 | RESOURCE_MONITORING: "resourceMonitoring", |
| 109 | + SYSTEM_MESSAGE: "systemMessage", | |
| 109 | 110 | } as const; |
| 110 | 111 | |
| 111 | 112 | /** |
modified extensions/cli/src/session.test.ts +49 −0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import os from "os"; |
| 3 | 3 | |
| 4 | 4 | import type { ChatHistoryItem, Session } from "core/index.js"; |
| 5 | +import { v4 as uuidv4 } from "uuid"; | |
| 5 | 6 | import { beforeEach, describe, expect, it, vi } from "vitest"; |
| 6 | 7 | |
| 7 | 8 | import { |
| @@ -11,6 +12,7 @@ | ||
| 11 | 12 | hasSession, |
| 12 | 13 | loadSession, |
| 13 | 14 | saveSession, |
| 15 | + startNewSession, | |
| 14 | 16 | updateSessionHistory, |
| 15 | 17 | updateSessionTitle, |
| 16 | 18 | } from "./session.js"; |
| @@ -352,4 +354,51 @@ | ||
| 352 | 354 | expect(session.history[0].message.content).toBe("Test message"); |
| 353 | 355 | }); |
| 354 | 356 | }); |
| 357 | + | |
| 358 | + describe("startNewSession", () => { | |
| 359 | + it("should clear the current session and create a new one", () => { | |
| 360 | + const firstSession = createSession(); | |
| 361 | + const firstSessionId = firstSession.sessionId; | |
| 362 | + | |
| 363 | + vi.mocked(uuidv4).mockReturnValue("new-uuid-456" as any); | |
| 364 | + | |
| 365 | + const secondSession = startNewSession(); | |
| 366 | + | |
| 367 | + expect(secondSession.sessionId).toBe("new-uuid-456"); | |
| 368 | + expect(secondSession.sessionId).not.toBe(firstSessionId); | |
| 369 | + expect(secondSession.title).toBe("Untitled Session"); | |
| 370 | + expect(secondSession.history).toEqual([]); | |
| 371 | + }); | |
| 372 | + | |
| 373 | + it("should create a new session with provided history", () => { | |
| 374 | + const history: ChatHistoryItem[] = [ | |
| 375 | + { | |
| 376 | + message: { | |
| 377 | + role: "system", | |
| 378 | + content: "You are a helpful assistant", | |
| 379 | + }, | |
| 380 | + contextItems: [], | |
| 381 | + }, | |
| 382 | + ]; | |
| 383 | + | |
| 384 | + vi.mocked(uuidv4).mockReturnValue("new-uuid-789" as any); | |
| 385 | + | |
| 386 | + const session = startNewSession(history); | |
| 387 | + | |
| 388 | + expect(session.sessionId).toBe("new-uuid-789"); | |
| 389 | + expect(session.history).toBe(history); | |
| 390 | + }); | |
| 391 | + | |
| 392 | + it("should set the new session as current", () => { | |
| 393 | + const originalSession = createSession(); | |
| 394 | + | |
| 395 | + vi.mocked(uuidv4).mockReturnValue("new-session-id" as any); | |
| 396 | + | |
| 397 | + const newSession = startNewSession(); | |
| 398 | + const currentSession = getCurrentSession(); | |
| 399 | + | |
| 400 | + expect(currentSession).toBe(newSession); | |
| 401 | + expect(currentSession).not.toBe(originalSession); | |
| 402 | + }); | |
| 403 | + }); | |
| 355 | 404 | }); |
modified extensions/cli/src/session.ts +37 −8
| @@ -6,11 +6,12 @@ | ||
| 6 | 6 | import historyManager from "core/util/history.js"; |
| 7 | 7 | import { v4 as uuidv4 } from "uuid"; |
| 8 | 8 | |
| 9 | +import { DEFAULT_SESSION_TITLE } from "./constants/session.js"; | |
| 10 | +import { logger } from "./util/logger.js"; | |
| 11 | + | |
| 9 | 12 | // Re-export SessionMetadata for external consumers |
| 10 | 13 | export type { SessionMetadata }; |
| 11 | 14 | |
| 12 | -import { logger } from "./util/logger.js"; | |
| 13 | - | |
| 14 | 15 | // Note: We now use UUID-based session IDs instead of terminal-based IDs. |
| 15 | 16 | // Each new chat session gets a unique UUID. |
| 16 | 17 | // The --resume flag loads the most recent session. |
| @@ -31,8 +32,10 @@ | ||
| 31 | 32 | return sessionDir; |
| 32 | 33 | } |
| 33 | 34 | |
| 34 | - const homeDir = os.homedir(); | |
| 35 | - const sessionDir = path.join(homeDir, ".continue", "sessions"); | |
| 35 | + // Use CONTINUE_GLOBAL_DIR if set (for testing) | |
| 36 | + const continueHome = | |
| 37 | + process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); | |
| 38 | + const sessionDir = path.join(continueHome, "sessions"); | |
| 36 | 39 | |
| 37 | 40 | // Create directory if it doesn't exist |
| 38 | 41 | if (!fs.existsSync(sessionDir)) { |
| @@ -67,9 +70,14 @@ | ||
| 67 | 70 | |
| 68 | 71 | getCurrentSession(): Session { |
| 69 | 72 | if (!this.currentSession) { |
| 73 | + // Use test session ID for testing consistency | |
| 74 | + const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID | |
| 75 | + ? process.env.CONTINUE_CLI_TEST_SESSION_ID | |
| 76 | + : uuidv4(); | |
| 77 | + | |
| 70 | 78 | this.currentSession = { |
| 71 | - sessionId: uuidv4(), | |
| 72 | - title: "Untitled Session", | |
| 79 | + sessionId, | |
| 80 | + title: DEFAULT_SESSION_TITLE, | |
| 73 | 81 | workspaceDirectory: process.cwd(), |
| 74 | 82 | history: [], |
| 75 | 83 | }; |
| @@ -187,7 +195,7 @@ | ||
| 187 | 195 | export function createSession(history: ChatHistoryItem[] = []): Session { |
| 188 | 196 | const session: Session = { |
| 189 | 197 | sessionId: uuidv4(), |
| 190 | - title: "Untitled Session", | |
| 198 | + title: DEFAULT_SESSION_TITLE, | |
| 191 | 199 | workspaceDirectory: process.cwd(), |
| 192 | 200 | history, |
| 193 | 201 | }; |
| @@ -265,7 +273,7 @@ | ||
| 265 | 273 | |
| 266 | 274 | return { |
| 267 | 275 | sessionId: sessionData.sessionId, |
| 268 | - title: sessionData.title || "Untitled Session", | |
| 276 | + title: sessionData.title || DEFAULT_SESSION_TITLE, | |
| 269 | 277 | dateCreated: stats.birthtime.toISOString(), |
| 270 | 278 | workspaceDirectory: sessionData.workspaceDirectory || "", |
| 271 | 279 | firstUserMessage, |
| @@ -347,3 +355,24 @@ | ||
| 347 | 355 | export function getCurrentSession(): Session { |
| 348 | 356 | return SessionManager.getInstance().getCurrentSession(); |
| 349 | 357 | } |
| 358 | + | |
| 359 | +/** | |
| 360 | + * Start a new session with a new sessionId | |
| 361 | + */ | |
| 362 | +export function startNewSession(history: ChatHistoryItem[] = []): Session { | |
| 363 | + const manager = SessionManager.getInstance(); | |
| 364 | + | |
| 365 | + // Clear the current session from memory (don't delete the file) | |
| 366 | + manager.clear(); | |
| 367 | + | |
| 368 | + // Create a new session with a new sessionId | |
| 369 | + const newSession: Session = { | |
| 370 | + sessionId: uuidv4(), | |
| 371 | + title: DEFAULT_SESSION_TITLE, | |
| 372 | + workspaceDirectory: process.cwd(), | |
| 373 | + history, | |
| 374 | + }; | |
| 375 | + | |
| 376 | + manager.setSession(newSession); | |
| 377 | + return newSession; | |
| 378 | +} |
added extensions/cli/src/slashCommands.info.test.ts +139 −0
| @@ -0,0 +1,139 @@ | ||
| 1 | +import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| 2 | + | |
| 3 | +import * as workosModule from "./auth/workos.js"; | |
| 4 | +import { services } from "./services/index.js"; | |
| 5 | +import * as sessionModule from "./session.js"; | |
| 6 | +import { handleSlashCommands } from "./slashCommands.js"; | |
| 7 | +import { posthogService } from "./telemetry/posthogService.js"; | |
| 8 | +import * as versionModule from "./version.js"; | |
| 9 | + | |
| 10 | +// Mock all dependencies | |
| 11 | +vi.mock("./auth/workos.js"); | |
| 12 | +vi.mock("./version.js"); | |
| 13 | +vi.mock("./session.js"); | |
| 14 | +vi.mock("./telemetry/posthogService.js"); | |
| 15 | + | |
| 16 | +vi.mock("./services/index.js", async (importOriginal) => { | |
| 17 | + const actual = await importOriginal<typeof import("./services/index.js")>(); | |
| 18 | + return { | |
| 19 | + ...actual, | |
| 20 | + services: { | |
| 21 | + config: { | |
| 22 | + getState: vi.fn(), | |
| 23 | + }, | |
| 24 | + model: { | |
| 25 | + getModelInfo: vi.fn(), | |
| 26 | + }, | |
| 27 | + }, | |
| 28 | + }; | |
| 29 | +}); | |
| 30 | + | |
| 31 | +describe("handleSlashCommands - /info", () => { | |
| 32 | + const mockAssistant = { | |
| 33 | + prompts: [], | |
| 34 | + }; | |
| 35 | + | |
| 36 | + beforeEach(() => { | |
| 37 | + vi.clearAllMocks(); | |
| 38 | + | |
| 39 | + // Mock process.cwd | |
| 40 | + vi.spyOn(process, "cwd").mockReturnValue("/test/working/directory"); | |
| 41 | + | |
| 42 | + // Mock posthog | |
| 43 | + vi.mocked(posthogService.capture).mockReturnValue(Promise.resolve()); | |
| 44 | + | |
| 45 | + // Mock version | |
| 46 | + vi.mocked(versionModule.getVersion).mockReturnValue("1.2.3"); | |
| 47 | + | |
| 48 | + // Mock session | |
| 49 | + vi.mocked(sessionModule.getSessionFilePath).mockReturnValue( | |
| 50 | + "/test/session.json", | |
| 51 | + ); | |
| 52 | + }); | |
| 53 | + | |
| 54 | + it("should include version and working directory in output", async () => { | |
| 55 | + // Mock auth as not authenticated | |
| 56 | + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); | |
| 57 | + | |
| 58 | + // Mock config service | |
| 59 | + const mockConfigState = { | |
| 60 | + config: { name: "test-config", version: "1.0.0" } as any, | |
| 61 | + configPath: "/test/config.yaml", | |
| 62 | + }; | |
| 63 | + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); | |
| 64 | + vi.mocked(services.model.getModelInfo).mockReturnValue({ | |
| 65 | + provider: "openai", | |
| 66 | + name: "gpt-4", | |
| 67 | + }); | |
| 68 | + | |
| 69 | + const result = await handleSlashCommands("/info", mockAssistant as any); | |
| 70 | + | |
| 71 | + expect(result).toBeDefined(); | |
| 72 | + expect(result?.output).toContain("CLI Information:"); | |
| 73 | + expect(result?.output).toContain("Version: 1.2.3"); | |
| 74 | + expect(result?.output).toContain( | |
| 75 | + "Working Directory: /test/working/directory", | |
| 76 | + ); | |
| 77 | + expect(result?.output).toContain("Configuration:"); | |
| 78 | + expect(result?.output).toContain("Model: gpt-4"); | |
| 79 | + expect(result?.exit).toBe(false); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("should handle authenticated user info", async () => { | |
| 83 | + // Mock auth as authenticated | |
| 84 | + vi.mocked(workosModule.isAuthenticated).mockReturnValue(true); | |
| 85 | + vi.mocked(workosModule.loadAuthConfig).mockReturnValue({ | |
| 86 | + userEmail: "test@example.com", | |
| 87 | + userId: "test-user", | |
| 88 | + } as any); | |
| 89 | + vi.mocked(workosModule.isAuthenticatedConfig).mockReturnValue(true); | |
| 90 | + | |
| 91 | + // Mock config service | |
| 92 | + const mockConfigState = { | |
| 93 | + config: { name: "test-config", version: "1.0.0" } as any, | |
| 94 | + configPath: "/test/config.yaml", | |
| 95 | + }; | |
| 96 | + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); | |
| 97 | + vi.mocked(services.model.getModelInfo).mockReturnValue({ | |
| 98 | + provider: "anthropic", | |
| 99 | + name: "claude-3-sonnet", | |
| 100 | + }); | |
| 101 | + | |
| 102 | + const result = await handleSlashCommands("/info", mockAssistant as any); | |
| 103 | + | |
| 104 | + expect(result?.output).toContain("Authentication:"); | |
| 105 | + expect(result?.output).toContain("Email: test@example.com"); | |
| 106 | + expect(result?.output).toContain("Model: claude-3-sonnet"); | |
| 107 | + }); | |
| 108 | + | |
| 109 | + it("should handle missing model info gracefully", async () => { | |
| 110 | + // Mock auth as not authenticated | |
| 111 | + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); | |
| 112 | + | |
| 113 | + // Mock config service with no model info | |
| 114 | + const mockConfigState = { | |
| 115 | + config: { name: "test-config", version: "1.0.0" } as any, | |
| 116 | + configPath: "/test/config.yaml", | |
| 117 | + }; | |
| 118 | + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); | |
| 119 | + vi.mocked(services.model.getModelInfo).mockReturnValue(null); | |
| 120 | + | |
| 121 | + const result = await handleSlashCommands("/info", mockAssistant as any); | |
| 122 | + | |
| 123 | + expect(result?.output).toContain("Model: Not available"); | |
| 124 | + }); | |
| 125 | + | |
| 126 | + it("should handle config service error", async () => { | |
| 127 | + // Mock auth as not authenticated | |
| 128 | + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); | |
| 129 | + | |
| 130 | + // Mock config service throwing error | |
| 131 | + vi.mocked(services.config.getState).mockImplementation(() => { | |
| 132 | + throw new Error("Service not available"); | |
| 133 | + }); | |
| 134 | + | |
| 135 | + const result = await handleSlashCommands("/info", mockAssistant as any); | |
| 136 | + | |
| 137 | + expect(result?.output).toContain("Configuration service not available"); | |
| 138 | + }); | |
| 139 | +}); |
modified extensions/cli/src/slashCommands.test.ts +19 −0
| @@ -44,11 +44,30 @@ | ||
| 44 | 44 | getAllSlashCommands: vi.fn(() => []), |
| 45 | 45 | })); |
| 46 | 46 | |
| 47 | +// Mock logger to avoid file system operations | |
| 48 | +vi.mock("./util/logger.js", () => ({ | |
| 49 | + logger: { | |
| 50 | + debug: vi.fn(), | |
| 51 | + info: vi.fn(), | |
| 52 | + warn: vi.fn(), | |
| 53 | + error: vi.fn(), | |
| 54 | + }, | |
| 55 | +})); | |
| 56 | + | |
| 57 | +// Mock env.js to avoid file operations | |
| 58 | +vi.mock("./env.js", () => ({ | |
| 59 | + env: { | |
| 60 | + continueHome: "/home/test/.continue", | |
| 61 | + appUrl: "https://hub.continue.dev", | |
| 62 | + }, | |
| 63 | +})); | |
| 64 | + | |
| 47 | 65 | // Mock os and path |
| 48 | 66 | vi.mock("os", () => ({ |
| 49 | 67 | default: { |
| 50 | 68 | homedir: vi.fn(() => "/home/test"), |
| 51 | 69 | }, |
| 70 | + homedir: vi.fn(() => "/home/test"), | |
| 52 | 71 | })); |
| 53 | 72 | |
| 54 | 73 | vi.mock("path", () => ({ |
modified extensions/cli/src/slashCommands.ts +24 −0
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { getSessionFilePath } from "./session.js"; |
| 12 | 12 | import { posthogService } from "./telemetry/posthogService.js"; |
| 13 | 13 | import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; |
| 14 | +import { getVersion } from "./version.js"; | |
| 14 | 15 | |
| 15 | 16 | type CommandHandler = ( |
| 16 | 17 | args: string[], |
| @@ -102,22 +103,33 @@ | ||
| 102 | 103 | |
| 103 | 104 | const infoLines = []; |
| 104 | 105 | |
| 106 | + // Version and working directory info | |
| 107 | + const version = getVersion(); | |
| 108 | + const cwd = process.cwd(); | |
| 109 | + | |
| 110 | + infoLines.push(chalk.white("CLI Information:")); | |
| 111 | + infoLines.push(` Version: ${chalk.green(version)}`); | |
| 112 | + infoLines.push(` Working Directory: ${chalk.blue(cwd)}`); | |
| 113 | + | |
| 105 | 114 | // Auth info |
| 106 | 115 | if (isAuthenticated()) { |
| 107 | 116 | const config = loadAuthConfig(); |
| 108 | 117 | if (config && isAuthenticatedConfig(config)) { |
| 109 | 118 | const email = config.userEmail || config.userId; |
| 110 | 119 | const org = "(no org)"; // Organization info not available in AuthenticatedConfig |
| 120 | + infoLines.push(""); | |
| 111 | 121 | infoLines.push(chalk.white("Authentication:")); |
| 112 | 122 | infoLines.push(` Email: ${chalk.green(email)}`); |
| 113 | 123 | infoLines.push(` Organization: ${chalk.cyan(org)}`); |
| 114 | 124 | } else { |
| 125 | + infoLines.push(""); | |
| 115 | 126 | infoLines.push(chalk.white("Authentication:")); |
| 116 | 127 | infoLines.push( |
| 117 | 128 | ` ${chalk.yellow("Authenticated via environment variable")}`, |
| 118 | 129 | ); |
| 119 | 130 | } |
| 120 | 131 | } else { |
| 132 | + infoLines.push(""); | |
| 121 | 133 | infoLines.push(chalk.white("Authentication:")); |
| 122 | 134 | infoLines.push(` ${chalk.red("Not logged in")}`); |
| 123 | 135 | } |
| @@ -135,6 +147,18 @@ | ||
| 135 | 147 | if (configState.configPath) { |
| 136 | 148 | infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); |
| 137 | 149 | } |
| 150 | + | |
| 151 | + // Add current model info | |
| 152 | + try { | |
| 153 | + const modelInfo = services.model?.getModelInfo(); | |
| 154 | + if (modelInfo) { | |
| 155 | + infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`); | |
| 156 | + } else { | |
| 157 | + infoLines.push(` Model: ${chalk.red("Not available")}`); | |
| 158 | + } | |
| 159 | + } catch { | |
| 160 | + infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`); | |
| 161 | + } | |
| 138 | 162 | } catch { |
| 139 | 163 | infoLines.push(""); |
| 140 | 164 | infoLines.push(chalk.white("Configuration:")); |
added extensions/cli/src/stream/handleToolCalls.ts +224 −0
| @@ -0,0 +1,224 @@ | ||
| 1 | +import type { ChatHistoryItem, ToolStatus } from "core/index.js"; | |
| 2 | +import { stripImages } from "core/util/messageContent.js"; | |
| 3 | +import { createHistoryItem } from "core/util/messageConversion.js"; | |
| 4 | +import type { ChatCompletionTool } from "openai/resources.mjs"; | |
| 5 | + | |
| 6 | +import { filterExcludedTools } from "../permissions/index.js"; | |
| 7 | +import { | |
| 8 | + getServiceSync, | |
| 9 | + MCPServiceState, | |
| 10 | + MCPTool, | |
| 11 | + SERVICE_NAMES, | |
| 12 | +} from "../services/index.js"; | |
| 13 | +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; | |
| 14 | +import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; | |
| 15 | +import { logger } from "../util/logger.js"; | |
| 16 | + | |
| 17 | +import { | |
| 18 | + executeStreamedToolCalls, | |
| 19 | + preprocessStreamedToolCalls, | |
| 20 | +} from "./streamChatResponse.helpers.js"; | |
| 21 | +import { StreamCallbacks } from "./streamChatResponse.types.js"; | |
| 22 | + | |
| 23 | +export async function handleToolCalls( | |
| 24 | + toolCalls: ToolCall[], | |
| 25 | + chatHistory: ChatHistoryItem[], | |
| 26 | + content: string, | |
| 27 | + callbacks: StreamCallbacks | undefined, | |
| 28 | + isHeadless: boolean, | |
| 29 | +): Promise<boolean> { | |
| 30 | + if (toolCalls.length === 0) { | |
| 31 | + if (content) { | |
| 32 | + chatHistory.push( | |
| 33 | + createHistoryItem({ | |
| 34 | + role: "assistant", | |
| 35 | + content, | |
| 36 | + }), | |
| 37 | + ); | |
| 38 | + } | |
| 39 | + return false; | |
| 40 | + } | |
| 41 | + | |
| 42 | + // Create tool call states for the ChatHistoryItem | |
| 43 | + const toolCallStates = toolCalls.map((tc) => ({ | |
| 44 | + toolCallId: tc.id, | |
| 45 | + toolCall: { | |
| 46 | + id: tc.id, | |
| 47 | + type: "function" as const, | |
| 48 | + function: { | |
| 49 | + name: tc.name, | |
| 50 | + arguments: JSON.stringify(tc.arguments), | |
| 51 | + }, | |
| 52 | + }, | |
| 53 | + status: "generated" as ToolStatus, | |
| 54 | + parsedArgs: tc.arguments, | |
| 55 | + })); | |
| 56 | + | |
| 57 | + // Create assistant message with tool calls | |
| 58 | + const assistantMessage = { | |
| 59 | + role: "assistant" as const, | |
| 60 | + content: content || "", | |
| 61 | + toolCalls: toolCalls.map((tc) => ({ | |
| 62 | + id: tc.id, | |
| 63 | + type: "function" as const, | |
| 64 | + function: { | |
| 65 | + name: tc.name, | |
| 66 | + arguments: JSON.stringify(tc.arguments), | |
| 67 | + }, | |
| 68 | + })), | |
| 69 | + }; | |
| 70 | + | |
| 71 | + chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 72 | + | |
| 73 | + // First preprocess the tool calls | |
| 74 | + const { preprocessedCalls, errorChatEntries } = | |
| 75 | + await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 76 | + | |
| 77 | + // Add any preprocessing errors to chat history | |
| 78 | + // Convert error entries from OpenAI format to ChatHistoryItem format | |
| 79 | + errorChatEntries.forEach((errorEntry) => { | |
| 80 | + chatHistory.push( | |
| 81 | + createHistoryItem({ | |
| 82 | + role: "tool", | |
| 83 | + content: stripImages(errorEntry.content) || "", | |
| 84 | + toolCallId: errorEntry.tool_call_id, | |
| 85 | + }), | |
| 86 | + ); | |
| 87 | + }); | |
| 88 | + | |
| 89 | + // Execute the valid preprocessed tool calls | |
| 90 | + const { chatHistoryEntries: toolResults, hasRejection } = | |
| 91 | + await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless); | |
| 92 | + | |
| 93 | + if (isHeadless && hasRejection) { | |
| 94 | + logger.debug( | |
| 95 | + "Tool call rejected in headless mode - returning current content", | |
| 96 | + ); | |
| 97 | + return true; // Signal early return needed | |
| 98 | + } | |
| 99 | + | |
| 100 | + // Convert tool results from OpenAI format to ChatHistoryItem format | |
| 101 | + // and add them to the chat history | |
| 102 | + toolResults.forEach((toolResult) => { | |
| 103 | + // Find the corresponding tool call state to update | |
| 104 | + const lastAssistantIndex = chatHistory.findLastIndex( | |
| 105 | + (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 106 | + ); | |
| 107 | + | |
| 108 | + if ( | |
| 109 | + lastAssistantIndex >= 0 && | |
| 110 | + chatHistory[lastAssistantIndex].toolCallStates | |
| 111 | + ) { | |
| 112 | + const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 113 | + (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 114 | + ); | |
| 115 | + | |
| 116 | + if (toolState) { | |
| 117 | + toolState.status = hasRejection ? "canceled" : "done"; | |
| 118 | + toolState.output = [ | |
| 119 | + { | |
| 120 | + content: | |
| 121 | + typeof toolResult.content === "string" ? toolResult.content : "", | |
| 122 | + name: `Tool Result`, | |
| 123 | + description: "Tool execution result", | |
| 124 | + }, | |
| 125 | + ]; | |
| 126 | + } | |
| 127 | + } | |
| 128 | + }); | |
| 129 | + return false; | |
| 130 | +} | |
| 131 | + | |
| 132 | +export async function getAllTools() { | |
| 133 | + // Get all available tool names | |
| 134 | + const allBuiltinTools = getAllBuiltinTools(); | |
| 135 | + const builtinToolNames = allBuiltinTools.map((tool) => tool.name); | |
| 136 | + | |
| 137 | + let mcpTools: MCPTool[] = []; | |
| 138 | + let mcpToolNames: string[] = []; | |
| 139 | + const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP); | |
| 140 | + if (mcpServiceResult.state === "ready") { | |
| 141 | + mcpTools = mcpServiceResult?.value?.tools ?? []; | |
| 142 | + mcpToolNames = mcpTools.map((t) => t.name); | |
| 143 | + } else { | |
| 144 | + // MCP is lazy | |
| 145 | + // throw new Error("MCP Service not initialized"); | |
| 146 | + } | |
| 147 | + | |
| 148 | + const allToolNames = [...builtinToolNames, ...mcpToolNames]; | |
| 149 | + | |
| 150 | + // Check if the ToolPermissionService is ready | |
| 151 | + const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>( | |
| 152 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 153 | + ); | |
| 154 | + | |
| 155 | + let allowedToolNames: string[]; | |
| 156 | + if ( | |
| 157 | + permissionsServiceResult.state === "ready" && | |
| 158 | + permissionsServiceResult.value | |
| 159 | + ) { | |
| 160 | + // Filter out excluded tools based on permissions | |
| 161 | + allowedToolNames = filterExcludedTools( | |
| 162 | + allToolNames, | |
| 163 | + permissionsServiceResult.value.permissions, | |
| 164 | + ); | |
| 165 | + } else { | |
| 166 | + // Service not ready - this is a critical error since tools should only be | |
| 167 | + // requested after services are properly initialized | |
| 168 | + logger.error( | |
| 169 | + "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", | |
| 170 | + ); | |
| 171 | + throw new Error( | |
| 172 | + "ToolPermissionService not initialized. Services must be initialized before requesting tools.", | |
| 173 | + ); | |
| 174 | + } | |
| 175 | + | |
| 176 | + const allowedToolNamesSet = new Set(allowedToolNames); | |
| 177 | + | |
| 178 | + // Filter builtin tools | |
| 179 | + const allowedBuiltinTools = allBuiltinTools.filter((tool) => | |
| 180 | + allowedToolNamesSet.has(tool.name), | |
| 181 | + ); | |
| 182 | + | |
| 183 | + const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ | |
| 184 | + type: "function" as const, | |
| 185 | + function: { | |
| 186 | + name: tool.name, | |
| 187 | + description: tool.description, | |
| 188 | + parameters: { | |
| 189 | + type: "object", | |
| 190 | + properties: Object.fromEntries( | |
| 191 | + Object.entries(tool.parameters).map(([key, param]) => [ | |
| 192 | + key, | |
| 193 | + { | |
| 194 | + type: param.type, | |
| 195 | + description: param.description, | |
| 196 | + items: param.items, | |
| 197 | + }, | |
| 198 | + ]), | |
| 199 | + ), | |
| 200 | + required: Object.entries(tool.parameters) | |
| 201 | + .filter(([_, param]) => param.required) | |
| 202 | + .map(([key, _]) => key), | |
| 203 | + }, | |
| 204 | + }, | |
| 205 | + })); | |
| 206 | + | |
| 207 | + // Add filtered MCP tools | |
| 208 | + const allowedMcpTools = mcpTools.filter((tool) => | |
| 209 | + allowedToolNamesSet.has(tool.name), | |
| 210 | + ); | |
| 211 | + | |
| 212 | + allTools.push( | |
| 213 | + ...allowedMcpTools.map((tool) => ({ | |
| 214 | + type: "function" as const, | |
| 215 | + function: { | |
| 216 | + name: tool.name, | |
| 217 | + description: tool.description, | |
| 218 | + parameters: tool.inputSchema, | |
| 219 | + }, | |
| 220 | + })), | |
| 221 | + ); | |
| 222 | + | |
| 223 | + return allTools; | |
| 224 | +} |
added extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +249 −0
| @@ -0,0 +1,249 @@ | ||
| 1 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 2 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 3 | +import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 4 | + | |
| 5 | +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 6 | + | |
| 7 | +// Mock dependencies | |
| 8 | +vi.mock("../compaction.js", () => ({ | |
| 9 | + compactChatHistory: vi.fn(), | |
| 10 | +})); | |
| 11 | + | |
| 12 | +vi.mock("../session.js", () => ({ | |
| 13 | + createSession: vi.fn((history) => ({ | |
| 14 | + sessionId: "test", | |
| 15 | + title: "Test", | |
| 16 | + workspaceDirectory: "/test", | |
| 17 | + history, | |
| 18 | + })), | |
| 19 | + saveSession: vi.fn(), | |
| 20 | + updateSessionHistory: vi.fn(), | |
| 21 | +})); | |
| 22 | + | |
| 23 | +vi.mock("../util/tokenizer.js", () => ({ | |
| 24 | + shouldAutoCompact: vi.fn(), | |
| 25 | + getAutoCompactMessage: vi.fn(), | |
| 26 | +})); | |
| 27 | + | |
| 28 | +vi.mock("../util/formatError.js", () => ({ | |
| 29 | + formatError: vi.fn((error) => error.message || String(error)), | |
| 30 | +})); | |
| 31 | + | |
| 32 | +vi.mock("../util/logger.js", () => ({ | |
| 33 | + logger: { | |
| 34 | + info: vi.fn(), | |
| 35 | + debug: vi.fn(), | |
| 36 | + error: vi.fn(), | |
| 37 | + warn: vi.fn(), | |
| 38 | + }, | |
| 39 | +})); | |
| 40 | + | |
| 41 | +vi.mock("os", async (importOriginal) => { | |
| 42 | + const actual = (await importOriginal()) as object; | |
| 43 | + return { | |
| 44 | + ...actual, | |
| 45 | + homedir: vi.fn(() => "/home/test"), | |
| 46 | + }; | |
| 47 | +}); | |
| 48 | + | |
| 49 | +describe("handleAutoCompaction", () => { | |
| 50 | + const mockModel = { | |
| 51 | + provider: "openai", | |
| 52 | + name: "gpt-4", | |
| 53 | + model: "gpt-4", | |
| 54 | + defaultCompletionOptions: { | |
| 55 | + contextLength: 8192, | |
| 56 | + maxTokens: 2048, | |
| 57 | + }, | |
| 58 | + } as any; | |
| 59 | + | |
| 60 | + const mockLlmApi = {} as any; | |
| 61 | + const mockChatHistory: ChatHistoryItem[] = convertToUnifiedHistory([ | |
| 62 | + { role: "system", content: "You are a helpful assistant." }, | |
| 63 | + { role: "user", content: "Hello" }, | |
| 64 | + { role: "assistant", content: "Hi there!" }, | |
| 65 | + ]); | |
| 66 | + | |
| 67 | + beforeEach(() => { | |
| 68 | + vi.clearAllMocks(); | |
| 69 | + }); | |
| 70 | + | |
| 71 | + it("should return original history when auto-compaction is not needed", async () => { | |
| 72 | + const { shouldAutoCompact } = await import("../util/tokenizer.js"); | |
| 73 | + const mockedShouldAutoCompact = shouldAutoCompact as any; | |
| 74 | + mockedShouldAutoCompact.mockReturnValue(false); | |
| 75 | + | |
| 76 | + const result = await handleAutoCompaction( | |
| 77 | + mockChatHistory, | |
| 78 | + mockModel, | |
| 79 | + mockLlmApi, | |
| 80 | + {}, | |
| 81 | + ); | |
| 82 | + | |
| 83 | + expect(result).toEqual({ | |
| 84 | + chatHistory: mockChatHistory, | |
| 85 | + compactionIndex: null, | |
| 86 | + wasCompacted: false, | |
| 87 | + }); | |
| 88 | + | |
| 89 | + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 90 | + }); | |
| 91 | + | |
| 92 | + it("should perform auto-compaction when context limit is approaching", async () => { | |
| 93 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 94 | + "../util/tokenizer.js" | |
| 95 | + ); | |
| 96 | + const { compactChatHistory } = await import("../compaction.js"); | |
| 97 | + const { updateSessionHistory } = await import("../session.js"); | |
| 98 | + | |
| 99 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 100 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 101 | + | |
| 102 | + const mockCompactionResult = { | |
| 103 | + compactedHistory: convertToUnifiedHistory([ | |
| 104 | + { | |
| 105 | + role: "system", | |
| 106 | + content: "You are a helpful assistant.", | |
| 107 | + }, | |
| 108 | + { | |
| 109 | + role: "assistant", | |
| 110 | + content: "[COMPACTED HISTORY]\nConversation summary...", | |
| 111 | + }, | |
| 112 | + ]), | |
| 113 | + compactionIndex: 1, | |
| 114 | + compactionContent: "Conversation summary...", | |
| 115 | + }; | |
| 116 | + | |
| 117 | + const mockedCompactChatHistory = compactChatHistory as any; | |
| 118 | + mockedCompactChatHistory.mockResolvedValue(mockCompactionResult); | |
| 119 | + | |
| 120 | + const mockCallbacks = { | |
| 121 | + onSystemMessage: vi.fn(), | |
| 122 | + }; | |
| 123 | + | |
| 124 | + const result = await handleAutoCompaction( | |
| 125 | + mockChatHistory, | |
| 126 | + mockModel, | |
| 127 | + mockLlmApi, | |
| 128 | + { | |
| 129 | + isHeadless: false, | |
| 130 | + callbacks: mockCallbacks, | |
| 131 | + }, | |
| 132 | + ); | |
| 133 | + | |
| 134 | + expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 135 | + expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel); | |
| 136 | + expect(compactChatHistory).toHaveBeenCalledWith( | |
| 137 | + mockChatHistory, | |
| 138 | + mockModel, | |
| 139 | + mockLlmApi, | |
| 140 | + expect.any(Object), | |
| 141 | + ); | |
| 142 | + expect(updateSessionHistory).toHaveBeenCalledWith( | |
| 143 | + mockCompactionResult.compactedHistory, | |
| 144 | + ); | |
| 145 | + | |
| 146 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 147 | + "Auto-compacting...", | |
| 148 | + ); | |
| 149 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 150 | + "✓ Chat history auto-compacted successfully.", | |
| 151 | + ); | |
| 152 | + | |
| 153 | + expect(result).toEqual({ | |
| 154 | + chatHistory: mockCompactionResult.compactedHistory, | |
| 155 | + compactionIndex: mockCompactionResult.compactionIndex, | |
| 156 | + wasCompacted: true, | |
| 157 | + }); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + it("should handle compaction errors gracefully", async () => { | |
| 161 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 162 | + "../util/tokenizer.js" | |
| 163 | + ); | |
| 164 | + const { compactChatHistory } = await import("../compaction.js"); | |
| 165 | + const { logger } = await import("../util/logger.js"); | |
| 166 | + | |
| 167 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 168 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 169 | + vi.mocked(compactChatHistory).mockRejectedValue( | |
| 170 | + new Error("Compaction failed"), | |
| 171 | + ); | |
| 172 | + | |
| 173 | + const mockCallbacks = { | |
| 174 | + onSystemMessage: vi.fn(), | |
| 175 | + }; | |
| 176 | + | |
| 177 | + const result = await handleAutoCompaction( | |
| 178 | + mockChatHistory, | |
| 179 | + mockModel, | |
| 180 | + mockLlmApi, | |
| 181 | + { | |
| 182 | + isHeadless: false, | |
| 183 | + callbacks: mockCallbacks, | |
| 184 | + }, | |
| 185 | + ); | |
| 186 | + | |
| 187 | + expect(logger.error).toHaveBeenCalledWith( | |
| 188 | + expect.stringContaining("Auto-compaction error"), | |
| 189 | + ); | |
| 190 | + expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 191 | + expect.stringContaining("Warning: Auto-compaction error"), | |
| 192 | + ); | |
| 193 | + | |
| 194 | + // Should return original history on error | |
| 195 | + expect(result.wasCompacted).toBe(false); | |
| 196 | + expect(result).toEqual({ | |
| 197 | + chatHistory: mockChatHistory, | |
| 198 | + compactionIndex: null, | |
| 199 | + wasCompacted: false, | |
| 200 | + }); | |
| 201 | + }); | |
| 202 | + | |
| 203 | + it("should not call system message callback in headless mode", async () => { | |
| 204 | + const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 205 | + "../util/tokenizer.js" | |
| 206 | + ); | |
| 207 | + const { compactChatHistory } = await import("../compaction.js"); | |
| 208 | + | |
| 209 | + vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 210 | + vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 211 | + | |
| 212 | + const mockCompactionResult = { | |
| 213 | + compactedHistory: convertToUnifiedHistory([ | |
| 214 | + { role: "system", content: "System" }, | |
| 215 | + ]), | |
| 216 | + compactionIndex: 0, | |
| 217 | + compactionContent: "Summary", | |
| 218 | + }; | |
| 219 | + | |
| 220 | + const mockedCompactChatHistory = compactChatHistory as any; | |
| 221 | + mockedCompactChatHistory.mockResolvedValue(mockCompactionResult); | |
| 222 | + | |
| 223 | + const mockCallbacks = { | |
| 224 | + onSystemMessage: vi.fn(), | |
| 225 | + }; | |
| 226 | + | |
| 227 | + await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { | |
| 228 | + isHeadless: true, | |
| 229 | + callbacks: mockCallbacks, | |
| 230 | + }); | |
| 231 | + | |
| 232 | + expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); | |
| 233 | + }); | |
| 234 | + | |
| 235 | + it("should handle missing model gracefully", async () => { | |
| 236 | + const result = await handleAutoCompaction( | |
| 237 | + mockChatHistory, | |
| 238 | + null as any, | |
| 239 | + mockLlmApi, | |
| 240 | + {}, | |
| 241 | + ); | |
| 242 | + | |
| 243 | + expect(result).toEqual({ | |
| 244 | + chatHistory: mockChatHistory, | |
| 245 | + compactionIndex: null, | |
| 246 | + wasCompacted: false, | |
| 247 | + }); | |
| 248 | + }); | |
| 249 | +}); |
added extensions/cli/src/stream/streamChatResponse.autoCompaction.ts +176 −0
| @@ -0,0 +1,176 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | +import React from "react"; | |
| 5 | + | |
| 6 | +import { compactChatHistory } from "../compaction.js"; | |
| 7 | +import { updateSessionHistory } from "../session.js"; | |
| 8 | +import { formatError } from "../util/formatError.js"; | |
| 9 | +import { logger } from "../util/logger.js"; | |
| 10 | +import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js"; | |
| 11 | + | |
| 12 | +interface AutoCompactionCallbacks { | |
| 13 | + // For streaming mode | |
| 14 | + onSystemMessage?: (message: string) => void; | |
| 15 | + onContent?: (content: string) => void; | |
| 16 | + | |
| 17 | + // For TUI mode | |
| 18 | + setMessages?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 19 | + setChatHistory?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 20 | + setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>; | |
| 21 | + | |
| 22 | + // For headless mode - no callbacks needed, just return values | |
| 23 | +} | |
| 24 | + | |
| 25 | +interface AutoCompactionOptions { | |
| 26 | + isHeadless?: boolean; | |
| 27 | + format?: "json"; | |
| 28 | + callbacks?: AutoCompactionCallbacks; | |
| 29 | +} | |
| 30 | + | |
| 31 | +/** | |
| 32 | + * Notify user about compaction start | |
| 33 | + */ | |
| 34 | +function notifyCompactionStart( | |
| 35 | + message: string, | |
| 36 | + isHeadless: boolean, | |
| 37 | + callbacks?: AutoCompactionCallbacks, | |
| 38 | +) { | |
| 39 | + if (isHeadless) return; | |
| 40 | + | |
| 41 | + if (callbacks?.onSystemMessage) { | |
| 42 | + callbacks.onSystemMessage(message); | |
| 43 | + } else if (callbacks?.setMessages) { | |
| 44 | + // TUI mode - handled by caller | |
| 45 | + } | |
| 46 | +} | |
| 47 | + | |
| 48 | +/** | |
| 49 | + * Handle successful compaction state updates | |
| 50 | + */ | |
| 51 | +function handleCompactionSuccess( | |
| 52 | + result: any, | |
| 53 | + isHeadless: boolean, | |
| 54 | + callbacks?: AutoCompactionCallbacks, | |
| 55 | +) { | |
| 56 | + if (isHeadless) return; | |
| 57 | + | |
| 58 | + const successMessage = "✓ Chat history auto-compacted successfully."; | |
| 59 | + | |
| 60 | + if (callbacks?.onSystemMessage) { | |
| 61 | + callbacks.onSystemMessage(successMessage); | |
| 62 | + } else if ( | |
| 63 | + callbacks?.setMessages && | |
| 64 | + callbacks?.setChatHistory && | |
| 65 | + callbacks?.setCompactionIndex | |
| 66 | + ) { | |
| 67 | + callbacks.setChatHistory(result.compactedHistory); | |
| 68 | + callbacks.setCompactionIndex(result.compactionIndex); | |
| 69 | + callbacks.setMessages((prev: ChatHistoryItem[]) => [ | |
| 70 | + ...prev, | |
| 71 | + { | |
| 72 | + message: { | |
| 73 | + role: "system", | |
| 74 | + content: successMessage, | |
| 75 | + }, | |
| 76 | + contextItems: [], | |
| 77 | + }, | |
| 78 | + ]); | |
| 79 | + } | |
| 80 | +} | |
| 81 | + | |
| 82 | +/** | |
| 83 | + * Handle compaction error notification | |
| 84 | + */ | |
| 85 | +function handleCompactionError( | |
| 86 | + error: any, | |
| 87 | + isHeadless: boolean, | |
| 88 | + callbacks?: AutoCompactionCallbacks, | |
| 89 | +) { | |
| 90 | + const errorMessage = `Auto-compaction error: ${formatError(error)}`; | |
| 91 | + logger.error(errorMessage); | |
| 92 | + | |
| 93 | + if (isHeadless) return; | |
| 94 | + | |
| 95 | + const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; | |
| 96 | + | |
| 97 | + if (callbacks?.onSystemMessage) { | |
| 98 | + callbacks.onSystemMessage(warningMessage); | |
| 99 | + } else if (callbacks?.setMessages) { | |
| 100 | + callbacks.setMessages((prev: ChatHistoryItem[]) => [ | |
| 101 | + ...prev, | |
| 102 | + { | |
| 103 | + message: { | |
| 104 | + role: "system", | |
| 105 | + content: warningMessage, | |
| 106 | + }, | |
| 107 | + contextItems: [], | |
| 108 | + }, | |
| 109 | + ]); | |
| 110 | + } | |
| 111 | +} | |
| 112 | + | |
| 113 | +/** | |
| 114 | + * Unified auto-compaction handler for all modes (streaming, TUI, headless) | |
| 115 | + * @param chatHistory Current chat history | |
| 116 | + * @param model Model configuration | |
| 117 | + * @param llmApi LLM API instance | |
| 118 | + * @param options Configuration options for different usage contexts | |
| 119 | + * @returns Updated chat history and compaction index, or original if no compaction needed | |
| 120 | + */ | |
| 121 | +export async function handleAutoCompaction( | |
| 122 | + chatHistory: ChatHistoryItem[], | |
| 123 | + model: ModelConfig, | |
| 124 | + llmApi: BaseLlmApi, | |
| 125 | + options: AutoCompactionOptions = {}, | |
| 126 | +): Promise<{ | |
| 127 | + chatHistory: ChatHistoryItem[]; | |
| 128 | + compactionIndex: number | null; | |
| 129 | + wasCompacted: boolean; | |
| 130 | +}> { | |
| 131 | + const { isHeadless = false, callbacks } = options; | |
| 132 | + | |
| 133 | + if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 134 | + return { chatHistory, compactionIndex: null, wasCompacted: false }; | |
| 135 | + } | |
| 136 | + | |
| 137 | + logger.info( | |
| 138 | + `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, | |
| 139 | + ); | |
| 140 | + | |
| 141 | + // Notify about compaction start | |
| 142 | + notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); | |
| 143 | + | |
| 144 | + try { | |
| 145 | + // Compact the history | |
| 146 | + const result = await compactChatHistory( | |
| 147 | + chatHistory, | |
| 148 | + model, | |
| 149 | + llmApi, | |
| 150 | + isHeadless | |
| 151 | + ? undefined | |
| 152 | + : { | |
| 153 | + onStreamContent: callbacks?.onContent, | |
| 154 | + onStreamComplete: () => {}, | |
| 155 | + }, | |
| 156 | + ); | |
| 157 | + | |
| 158 | + // Save the compacted session | |
| 159 | + updateSessionHistory(result.compactedHistory); | |
| 160 | + | |
| 161 | + // Handle success notification | |
| 162 | + handleCompactionSuccess(result, isHeadless, callbacks); | |
| 163 | + | |
| 164 | + return { | |
| 165 | + chatHistory: result.compactedHistory, | |
| 166 | + compactionIndex: result.compactionIndex, | |
| 167 | + wasCompacted: true, | |
| 168 | + }; | |
| 169 | + } catch (error: any) { | |
| 170 | + // Handle error notification | |
| 171 | + handleCompactionError(error, isHeadless, callbacks); | |
| 172 | + | |
| 173 | + // Continue without compaction on error | |
| 174 | + return { chatHistory, compactionIndex: null, wasCompacted: false }; | |
| 175 | + } | |
| 176 | +} |
added extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts +172 −0
| @@ -0,0 +1,172 @@ | ||
| 1 | +import { describe, expect, test } from "vitest"; | |
| 2 | + | |
| 3 | +import { | |
| 4 | + getServiceSync, | |
| 5 | + initializeServices, | |
| 6 | + SERVICE_NAMES, | |
| 7 | + serviceContainer, | |
| 8 | +} from "../services/index.js"; | |
| 9 | +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; | |
| 10 | + | |
| 11 | +import { getAllTools } from "./streamChatResponse.js"; | |
| 12 | + | |
| 13 | +describe("getAllTools - Tool Filtering", () => { | |
| 14 | + beforeEach(() => { | |
| 15 | + // Clean up service container state before each test | |
| 16 | + const services = [ | |
| 17 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 18 | + SERVICE_NAMES.AUTH, | |
| 19 | + SERVICE_NAMES.API_CLIENT, | |
| 20 | + SERVICE_NAMES.CONFIG, | |
| 21 | + SERVICE_NAMES.MODEL, | |
| 22 | + SERVICE_NAMES.MCP, | |
| 23 | + ]; | |
| 24 | + | |
| 25 | + services.forEach((service) => { | |
| 26 | + // Reset service state | |
| 27 | + (serviceContainer as any).services.delete(service); | |
| 28 | + (serviceContainer as any).factories.delete(service); | |
| 29 | + (serviceContainer as any).dependencies.delete(service); | |
| 30 | + }); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + test("should exclude Bash tool in plan mode after service initialization", async () => { | |
| 34 | + // Initialize services in plan mode (simulating `cn -p`) | |
| 35 | + await initializeServices({ | |
| 36 | + headless: true, | |
| 37 | + toolPermissionOverrides: { | |
| 38 | + mode: "plan", | |
| 39 | + }, | |
| 40 | + }); | |
| 41 | + | |
| 42 | + // Verify service is ready | |
| 43 | + const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 44 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 45 | + ); | |
| 46 | + expect(serviceResult.state).toBe("ready"); | |
| 47 | + expect(serviceResult.value?.currentMode).toBe("plan"); | |
| 48 | + | |
| 49 | + // Get available tools - this should include Bash in plan mode | |
| 50 | + const tools = await getAllTools(); | |
| 51 | + const toolNames = tools.map((t) => t.function.name); | |
| 52 | + | |
| 53 | + // Bash should be allowed in plan mode | |
| 54 | + expect(toolNames).toContain("Bash"); | |
| 55 | + | |
| 56 | + // Read-only tools should still be available | |
| 57 | + expect(toolNames).toContain("Read"); | |
| 58 | + expect(toolNames).toContain("List"); | |
| 59 | + expect(toolNames).toContain("Search"); | |
| 60 | + expect(toolNames).toContain("Fetch"); | |
| 61 | + expect(toolNames).toContain("Checklist"); | |
| 62 | + | |
| 63 | + // Write tools should be excluded | |
| 64 | + expect(toolNames).not.toContain("Write"); | |
| 65 | + expect(toolNames).not.toContain("Edit"); | |
| 66 | + }); | |
| 67 | + | |
| 68 | + test("should include Bash tool in normal mode", async () => { | |
| 69 | + // Initialize services in normal mode | |
| 70 | + await initializeServices({ | |
| 71 | + headless: true, | |
| 72 | + toolPermissionOverrides: { | |
| 73 | + mode: "normal", | |
| 74 | + }, | |
| 75 | + }); | |
| 76 | + | |
| 77 | + // Verify service is ready | |
| 78 | + const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 79 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 80 | + ); | |
| 81 | + expect(serviceResult.state).toBe("ready"); | |
| 82 | + expect(serviceResult.value?.currentMode).toBe("normal"); | |
| 83 | + | |
| 84 | + // Get available tools - Bash should be available in normal mode | |
| 85 | + const tools = await getAllTools(); | |
| 86 | + const toolNames = tools.map((t) => t.function.name); | |
| 87 | + | |
| 88 | + // All tools should be available in normal mode | |
| 89 | + expect(toolNames).toContain("Bash"); | |
| 90 | + expect(toolNames).toContain("Read"); | |
| 91 | + expect(toolNames).toContain("Write"); | |
| 92 | + expect(toolNames).toContain("Edit"); | |
| 93 | + }); | |
| 94 | + | |
| 95 | + test("should include all tools in auto mode", async () => { | |
| 96 | + // Initialize services in auto mode | |
| 97 | + await initializeServices({ | |
| 98 | + headless: true, | |
| 99 | + toolPermissionOverrides: { | |
| 100 | + mode: "auto", | |
| 101 | + }, | |
| 102 | + }); | |
| 103 | + | |
| 104 | + // Verify service is ready | |
| 105 | + const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 106 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 107 | + ); | |
| 108 | + expect(serviceResult.state).toBe("ready"); | |
| 109 | + expect(serviceResult.value?.currentMode).toBe("auto"); | |
| 110 | + | |
| 111 | + // Get available tools - all tools should be available in auto mode | |
| 112 | + const tools = await getAllTools(); | |
| 113 | + const toolNames = tools.map((t) => t.function.name); | |
| 114 | + | |
| 115 | + // All tools should be available in auto mode | |
| 116 | + expect(toolNames).toContain("Bash"); | |
| 117 | + expect(toolNames).toContain("Read"); | |
| 118 | + expect(toolNames).toContain("Write"); | |
| 119 | + expect(toolNames).toContain("Edit"); | |
| 120 | + }); | |
| 121 | + | |
| 122 | + test("should respect explicit exclude in normal mode", async () => { | |
| 123 | + // Initialize services in normal mode with Read tool explicitly excluded | |
| 124 | + await initializeServices({ | |
| 125 | + headless: true, | |
| 126 | + toolPermissionOverrides: { | |
| 127 | + mode: "normal", | |
| 128 | + exclude: ["Read"], | |
| 129 | + }, | |
| 130 | + }); | |
| 131 | + | |
| 132 | + const tools = await getAllTools(); | |
| 133 | + const toolNames = tools.map((t) => t.function.name); | |
| 134 | + | |
| 135 | + // Read should be excluded due to explicit exclude | |
| 136 | + expect(toolNames).not.toContain("Read"); | |
| 137 | + | |
| 138 | + // Other tools should still be available in normal mode | |
| 139 | + expect(toolNames).toContain("Bash"); | |
| 140 | + expect(toolNames).toContain("Write"); | |
| 141 | + expect(toolNames).toContain("List"); | |
| 142 | + expect(toolNames).toContain("Search"); | |
| 143 | + }); | |
| 144 | + | |
| 145 | + test("plan mode should override allow flags (regression test for GitHub Actions issue)", async () => { | |
| 146 | + // This test specifically addresses the original issue where plan mode | |
| 147 | + // wasn't properly excluding tools despite being in plan mode | |
| 148 | + await initializeServices({ | |
| 149 | + headless: true, | |
| 150 | + toolPermissionOverrides: { | |
| 151 | + mode: "plan", | |
| 152 | + allow: ["Write", "Edit"], // These should be ignored in plan mode | |
| 153 | + }, | |
| 154 | + }); | |
| 155 | + | |
| 156 | + const tools = await getAllTools(); | |
| 157 | + const toolNames = tools.map((t) => t.function.name); | |
| 158 | + | |
| 159 | + // Plan mode should still exclude write tools despite --allow flags | |
| 160 | + // This tests that plan mode policies have absolute precedence | |
| 161 | + expect(toolNames).not.toContain("Write"); | |
| 162 | + expect(toolNames).not.toContain("Edit"); | |
| 163 | + | |
| 164 | + // Bash should be available in plan mode | |
| 165 | + expect(toolNames).toContain("Bash"); | |
| 166 | + | |
| 167 | + // Read-only tools should be available | |
| 168 | + expect(toolNames).toContain("Read"); | |
| 169 | + expect(toolNames).toContain("List"); | |
| 170 | + expect(toolNames).toContain("Search"); | |
| 171 | + }); | |
| 172 | +}); |
added extensions/cli/src/stream/streamChatResponse.helpers.ts +455 −0
| @@ -0,0 +1,455 @@ | ||
| 1 | +// Helper functions extracted from streamChatResponse.ts to reduce file size | |
| 2 | + | |
| 3 | +import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; | |
| 4 | + | |
| 5 | +import { checkToolPermission } from "../permissions/permissionChecker.js"; | |
| 6 | +import { toolPermissionManager } from "../permissions/permissionManager.js"; | |
| 7 | +import { ToolCallRequest } from "../permissions/types.js"; | |
| 8 | +import { telemetryService } from "../telemetry/telemetryService.js"; | |
| 9 | +import { calculateTokenCost } from "../telemetry/utils.js"; | |
| 10 | +import { | |
| 11 | + executeToolCall, | |
| 12 | + getAllBuiltinTools, | |
| 13 | + getAvailableTools, | |
| 14 | + Tool, | |
| 15 | + validateToolCallArgsPresent, | |
| 16 | +} from "../tools/index.js"; | |
| 17 | +import { PreprocessedToolCall, ToolCall } from "../tools/types.js"; | |
| 18 | +import { logger } from "../util/logger.js"; | |
| 19 | + | |
| 20 | +import { StreamCallbacks } from "./streamChatResponse.types.js"; | |
| 21 | + | |
| 22 | +// Helper function to handle permission denied | |
| 23 | +export function handlePermissionDenied( | |
| 24 | + toolCall: PreprocessedToolCall, | |
| 25 | + chatHistoryEntries: ChatCompletionToolMessageParam[], | |
| 26 | + callbacks?: StreamCallbacks, | |
| 27 | +): void { | |
| 28 | + const deniedMessage = `Permission denied by user`; | |
| 29 | + logger.info("Tool call denied", { | |
| 30 | + name: toolCall.name, | |
| 31 | + arguments: toolCall.arguments, | |
| 32 | + }); | |
| 33 | + | |
| 34 | + chatHistoryEntries.push({ | |
| 35 | + role: "tool", | |
| 36 | + tool_call_id: toolCall.id, | |
| 37 | + content: deniedMessage, | |
| 38 | + }); | |
| 39 | + | |
| 40 | + callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled"); | |
| 41 | + logger.debug("Tool call rejected - stopping stream"); | |
| 42 | +} | |
| 43 | + | |
| 44 | +// Helper function to handle headless mode permission | |
| 45 | +export function handleHeadlessPermission( | |
| 46 | + toolCall: PreprocessedToolCall, | |
| 47 | +): never { | |
| 48 | + const allBuiltinTools = getAllBuiltinTools(); | |
| 49 | + const tool = allBuiltinTools.find((t) => t.name === toolCall.name); | |
| 50 | + const toolName = tool?.displayName || toolCall.name; | |
| 51 | + | |
| 52 | + console.error( | |
| 53 | + `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, | |
| 54 | + ); | |
| 55 | + console.error(`If you want to allow this tool, use --allow ${toolName}.`); | |
| 56 | + console.error( | |
| 57 | + `If you don't want the tool to be included, use --exclude ${toolName}.`, | |
| 58 | + ); | |
| 59 | + | |
| 60 | + process.exit(1); | |
| 61 | +} | |
| 62 | + | |
| 63 | +// Helper function to request user permission | |
| 64 | +export async function requestUserPermission( | |
| 65 | + toolCall: PreprocessedToolCall, | |
| 66 | + callbacks?: StreamCallbacks, | |
| 67 | +): Promise<boolean> { | |
| 68 | + if (!callbacks?.onToolPermissionRequest) { | |
| 69 | + return false; | |
| 70 | + } | |
| 71 | + | |
| 72 | + const toolCallRequest: ToolCallRequest = { | |
| 73 | + name: toolCall.name, | |
| 74 | + arguments: toolCall.preprocessResult?.args ?? toolCall.arguments, | |
| 75 | + preview: toolCall.preprocessResult?.preview, | |
| 76 | + }; | |
| 77 | + | |
| 78 | + // Set up listener for permissionRequested event | |
| 79 | + const handlePermissionRequested = (event: { | |
| 80 | + requestId: string; | |
| 81 | + toolCall: ToolCallRequest; | |
| 82 | + }) => { | |
| 83 | + if (event.toolCall.name === toolCall.name) { | |
| 84 | + toolPermissionManager.off( | |
| 85 | + "permissionRequested", | |
| 86 | + handlePermissionRequested, | |
| 87 | + ); | |
| 88 | + // Notify UI about permission request | |
| 89 | + callbacks.onToolPermissionRequest!( | |
| 90 | + event.toolCall.name, | |
| 91 | + event.toolCall.arguments, | |
| 92 | + event.requestId, | |
| 93 | + event.toolCall.preview, | |
| 94 | + ); | |
| 95 | + } | |
| 96 | + }; | |
| 97 | + | |
| 98 | + toolPermissionManager.on("permissionRequested", handlePermissionRequested); | |
| 99 | + | |
| 100 | + // Request permission using the proper API | |
| 101 | + const permissionResult = | |
| 102 | + await toolPermissionManager.requestPermission(toolCallRequest); | |
| 103 | + | |
| 104 | + // Clean up listener in case the condition above was never met | |
| 105 | + // This is a safety net to ensure no listeners are left behind | |
| 106 | + toolPermissionManager.off("permissionRequested", handlePermissionRequested); | |
| 107 | + | |
| 108 | + return permissionResult.approved; | |
| 109 | +} | |
| 110 | + | |
| 111 | +// Helper function to check if tool permission is needed | |
| 112 | +export async function checkToolPermissionApproval( | |
| 113 | + toolCall: PreprocessedToolCall, | |
| 114 | + callbacks?: StreamCallbacks, | |
| 115 | + isHeadless?: boolean, | |
| 116 | +): Promise<boolean> { | |
| 117 | + const permissionCheck = checkToolPermission(toolCall); | |
| 118 | + | |
| 119 | + if (permissionCheck.permission === "allow") { | |
| 120 | + return true; | |
| 121 | + } else if (permissionCheck.permission === "ask") { | |
| 122 | + if (isHeadless) { | |
| 123 | + handleHeadlessPermission(toolCall); | |
| 124 | + } | |
| 125 | + return await requestUserPermission(toolCall, callbacks); | |
| 126 | + } else if (permissionCheck.permission === "exclude") { | |
| 127 | + // This shouldn't happen as excluded tools are filtered out earlier | |
| 128 | + return false; | |
| 129 | + } | |
| 130 | + | |
| 131 | + return false; | |
| 132 | +} | |
| 133 | + | |
| 134 | +// Helper function to track first token time | |
| 135 | +export function trackFirstTokenTime( | |
| 136 | + firstTokenTime: number | null, | |
| 137 | + chunk: any, | |
| 138 | + requestStartTime: number, | |
| 139 | + model: any, | |
| 140 | + tools?: any[], | |
| 141 | +): number | null { | |
| 142 | + if ( | |
| 143 | + firstTokenTime === null && | |
| 144 | + chunk.choices?.[0]?.delta && | |
| 145 | + (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls) | |
| 146 | + ) { | |
| 147 | + const tokenTime = Date.now(); | |
| 148 | + telemetryService.recordResponseTime( | |
| 149 | + tokenTime - requestStartTime, | |
| 150 | + model.model, | |
| 151 | + "time_to_first_token", | |
| 152 | + (tools?.length || 0) > 0, | |
| 153 | + ); | |
| 154 | + return tokenTime; | |
| 155 | + } | |
| 156 | + return firstTokenTime; | |
| 157 | +} | |
| 158 | + | |
| 159 | +// Helper function to process content from a chunk | |
| 160 | +export function processChunkContent( | |
| 161 | + content: string, | |
| 162 | + aiResponse: string, | |
| 163 | + callbacks?: StreamCallbacks, | |
| 164 | + isHeadless?: boolean, | |
| 165 | +): string { | |
| 166 | + const updatedResponse = aiResponse + content; | |
| 167 | + | |
| 168 | + if (callbacks?.onContent) { | |
| 169 | + callbacks.onContent(content); | |
| 170 | + } else if (!isHeadless) { | |
| 171 | + process.stdout.write(content); | |
| 172 | + } | |
| 173 | + | |
| 174 | + return updatedResponse; | |
| 175 | +} | |
| 176 | + | |
| 177 | +// Helper function to handle tool call delta | |
| 178 | +export function processToolCallDelta( | |
| 179 | + toolCallDelta: any, | |
| 180 | + toolCallsMap: Map<string, ToolCall>, | |
| 181 | + indexToIdMap: Map<number, string>, | |
| 182 | +): void { | |
| 183 | + let toolCallId: string | undefined; | |
| 184 | + | |
| 185 | + // If we have an ID, use it and map the index | |
| 186 | + if (toolCallDelta.id) { | |
| 187 | + toolCallId = toolCallDelta.id; | |
| 188 | + if (toolCallDelta.index !== undefined && toolCallId) { | |
| 189 | + indexToIdMap.set(toolCallDelta.index, toolCallId); | |
| 190 | + } | |
| 191 | + } else if (toolCallDelta.index !== undefined) { | |
| 192 | + // No ID, but we have an index - look up the ID from our map | |
| 193 | + toolCallId = indexToIdMap.get(toolCallDelta.index); | |
| 194 | + } | |
| 195 | + | |
| 196 | + if (!toolCallId) { | |
| 197 | + logger.warn("Tool call delta without ID or valid index mapping", { | |
| 198 | + toolCallDelta, | |
| 199 | + }); | |
| 200 | + return; | |
| 201 | + } | |
| 202 | + | |
| 203 | + // Create tool call entry if it doesn't exist | |
| 204 | + if (!toolCallsMap.has(toolCallId)) { | |
| 205 | + toolCallsMap.set(toolCallId, { | |
| 206 | + id: toolCallId, | |
| 207 | + name: "", | |
| 208 | + arguments: null, | |
| 209 | + argumentsStr: "", | |
| 210 | + startNotified: false, | |
| 211 | + }); | |
| 212 | + } | |
| 213 | + | |
| 214 | + const toolCall = toolCallsMap.get(toolCallId); | |
| 215 | + if (!toolCall) { | |
| 216 | + logger.warn("Tool call not found in map", { toolCallId }); | |
| 217 | + return; | |
| 218 | + } | |
| 219 | + | |
| 220 | + // Update name | |
| 221 | + if (toolCallDelta.function?.name) { | |
| 222 | + toolCall.name = toolCallDelta.function.name; | |
| 223 | + } | |
| 224 | + | |
| 225 | + // Accumulate arguments | |
| 226 | + if (toolCallDelta.function?.arguments) { | |
| 227 | + toolCall.argumentsStr += toolCallDelta.function.arguments; | |
| 228 | + | |
| 229 | + // Try to parse when we might have complete JSON | |
| 230 | + try { | |
| 231 | + toolCall.arguments = JSON.parse(toolCall.argumentsStr); | |
| 232 | + toolCall.startNotified = true; | |
| 233 | + } catch { | |
| 234 | + // JSON not complete yet, continue | |
| 235 | + } | |
| 236 | + } | |
| 237 | +} | |
| 238 | + | |
| 239 | +// Helper function to record telemetry | |
| 240 | +export function recordStreamTelemetry(options: { | |
| 241 | + requestStartTime: number; | |
| 242 | + responseEndTime: number; | |
| 243 | + inputTokens: number; | |
| 244 | + outputTokens: number; | |
| 245 | + model: any; | |
| 246 | + tools?: any[]; | |
| 247 | +}): number { | |
| 248 | + const { | |
| 249 | + requestStartTime, | |
| 250 | + responseEndTime, | |
| 251 | + inputTokens, | |
| 252 | + outputTokens, | |
| 253 | + model, | |
| 254 | + tools, | |
| 255 | + } = options; | |
| 256 | + const totalDuration = responseEndTime - requestStartTime; | |
| 257 | + const cost = calculateTokenCost(inputTokens, outputTokens, model.model); | |
| 258 | + | |
| 259 | + telemetryService.recordTokenUsage(inputTokens, "input", model.model); | |
| 260 | + telemetryService.recordTokenUsage(outputTokens, "output", model.model); | |
| 261 | + telemetryService.recordCost(cost, model.model); | |
| 262 | + | |
| 263 | + telemetryService.recordResponseTime( | |
| 264 | + totalDuration, | |
| 265 | + model.model, | |
| 266 | + "total_response_time", | |
| 267 | + (tools?.length || 0) > 0, | |
| 268 | + ); | |
| 269 | + | |
| 270 | + telemetryService.logApiRequest({ | |
| 271 | + model: model.model, | |
| 272 | + durationMs: totalDuration, | |
| 273 | + success: true, | |
| 274 | + inputTokens, | |
| 275 | + outputTokens, | |
| 276 | + costUsd: cost, | |
| 277 | + }); | |
| 278 | + | |
| 279 | + return cost; | |
| 280 | +} | |
| 281 | + | |
| 282 | +/** | |
| 283 | + * Processes tool calls by validating and preprocessing them | |
| 284 | + * @param toolCalls - The raw tool calls from the LLM | |
| 285 | + * @param callbacks - Optional callbacks for notifying of events | |
| 286 | + * @returns - Preprocessed tool calls that are ready for execution | |
| 287 | + */ | |
| 288 | +export async function preprocessStreamedToolCalls( | |
| 289 | + toolCalls: ToolCall[], | |
| 290 | + callbacks?: StreamCallbacks, | |
| 291 | +): Promise<{ | |
| 292 | + preprocessedCalls: PreprocessedToolCall[]; | |
| 293 | + errorChatEntries: ChatCompletionToolMessageParam[]; | |
| 294 | +}> { | |
| 295 | + const preprocessedCalls: PreprocessedToolCall[] = []; | |
| 296 | + const errorChatEntries: ChatCompletionToolMessageParam[] = []; | |
| 297 | + | |
| 298 | + // Get all available tools | |
| 299 | + const availableTools: Tool[] = await getAvailableTools(); | |
| 300 | + | |
| 301 | + // Process each tool call | |
| 302 | + for (const toolCall of toolCalls) { | |
| 303 | + const startTime = Date.now(); | |
| 304 | + try { | |
| 305 | + const tool = availableTools.find((t) => t.name === toolCall.name); | |
| 306 | + if (!tool) { | |
| 307 | + throw new Error(`Tool ${toolCall.name} not found`); | |
| 308 | + } | |
| 309 | + | |
| 310 | + validateToolCallArgsPresent(toolCall, tool); | |
| 311 | + | |
| 312 | + const preprocessedCall: PreprocessedToolCall = { | |
| 313 | + ...toolCall, | |
| 314 | + tool, | |
| 315 | + }; | |
| 316 | + | |
| 317 | + if (tool.preprocess) { | |
| 318 | + logger.debug("Preprocessing tool call args", { | |
| 319 | + name: toolCall.name, | |
| 320 | + arguments: toolCall.arguments, | |
| 321 | + }); | |
| 322 | + const preprocessed = await tool.preprocess(toolCall.arguments); | |
| 323 | + preprocessedCall.preprocessResult = preprocessed; | |
| 324 | + } | |
| 325 | + | |
| 326 | + preprocessedCalls.push(preprocessedCall); | |
| 327 | + } catch (error) { | |
| 328 | + // Notify the UI about the tool start, even though it failed | |
| 329 | + callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 330 | + | |
| 331 | + const errorMessage = | |
| 332 | + error instanceof Error ? error.message : String(error); | |
| 333 | + | |
| 334 | + logger.error("Invalid tool call", { | |
| 335 | + name: toolCall.name, | |
| 336 | + error: errorMessage, | |
| 337 | + }); | |
| 338 | + | |
| 339 | + const duration = Date.now() - startTime; | |
| 340 | + telemetryService.logToolResult({ | |
| 341 | + toolName: toolCall.name, | |
| 342 | + success: false, | |
| 343 | + durationMs: duration, | |
| 344 | + error: errorMessage, | |
| 345 | + }); | |
| 346 | + | |
| 347 | + // Add error to chat history | |
| 348 | + errorChatEntries.push({ | |
| 349 | + role: "tool", | |
| 350 | + tool_call_id: toolCall.id, | |
| 351 | + content: errorMessage, | |
| 352 | + }); | |
| 353 | + | |
| 354 | + // Notify about the error | |
| 355 | + callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 356 | + } | |
| 357 | + } | |
| 358 | + | |
| 359 | + return { preprocessedCalls, errorChatEntries }; | |
| 360 | +} | |
| 361 | + | |
| 362 | +/** | |
| 363 | + * Executes preprocessed tool calls, handling permissions and results | |
| 364 | + * @param preprocessedCalls - The preprocessed tool calls ready for execution | |
| 365 | + * @param callbacks - Optional callbacks for notifying of events | |
| 366 | + * @returns - Chat history entries with tool results | |
| 367 | + */ | |
| 368 | +export async function executeStreamedToolCalls( | |
| 369 | + preprocessedCalls: PreprocessedToolCall[], | |
| 370 | + callbacks?: StreamCallbacks, | |
| 371 | + isHeadless?: boolean, | |
| 372 | +): Promise<{ | |
| 373 | + hasRejection: boolean; | |
| 374 | + chatHistoryEntries: ChatCompletionToolMessageParam[]; | |
| 375 | +}> { | |
| 376 | + const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; | |
| 377 | + let hasRejection = false; | |
| 378 | + | |
| 379 | + // Execute each preprocessed tool call | |
| 380 | + for (const toolCall of preprocessedCalls) { | |
| 381 | + if (hasRejection) { | |
| 382 | + const cancelledMessage = `Cancelled due to previous tool rejection`; | |
| 383 | + chatHistoryEntries.push({ | |
| 384 | + role: "tool", | |
| 385 | + tool_call_id: toolCall.id, | |
| 386 | + content: cancelledMessage, | |
| 387 | + }); | |
| 388 | + | |
| 389 | + callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); | |
| 390 | + continue; | |
| 391 | + } | |
| 392 | + | |
| 393 | + // Handle remaining tool calls in this batch to maintain chat history consistency | |
| 394 | + try { | |
| 395 | + logger.debug("Checking tool permissions", { | |
| 396 | + name: toolCall.name, | |
| 397 | + arguments: toolCall.arguments, | |
| 398 | + }); | |
| 399 | + | |
| 400 | + // Notify tool start - before permission check | |
| 401 | + // This ensures the UI shows the tool call even if it's rejected | |
| 402 | + callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 403 | + | |
| 404 | + // Check tool permissions using helper | |
| 405 | + const approved = await checkToolPermissionApproval( | |
| 406 | + toolCall, | |
| 407 | + callbacks, | |
| 408 | + isHeadless, | |
| 409 | + ); | |
| 410 | + | |
| 411 | + if (!approved) { | |
| 412 | + handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); | |
| 413 | + hasRejection = true; | |
| 414 | + continue; | |
| 415 | + } | |
| 416 | + | |
| 417 | + logger.debug("Executing tool", { | |
| 418 | + name: toolCall.name, | |
| 419 | + arguments: toolCall.arguments, | |
| 420 | + }); | |
| 421 | + | |
| 422 | + const toolResult = await executeToolCall(toolCall); | |
| 423 | + | |
| 424 | + chatHistoryEntries.push({ | |
| 425 | + role: "tool", | |
| 426 | + tool_call_id: toolCall.id, | |
| 427 | + content: toolResult, | |
| 428 | + }); | |
| 429 | + | |
| 430 | + callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); | |
| 431 | + } catch (error) { | |
| 432 | + const errorMessage = `Error executing tool ${toolCall.name}: ${ | |
| 433 | + error instanceof Error ? error.message : String(error) | |
| 434 | + }`; | |
| 435 | + | |
| 436 | + logger.error("Tool execution failed", { | |
| 437 | + name: toolCall.name, | |
| 438 | + error: errorMessage, | |
| 439 | + }); | |
| 440 | + | |
| 441 | + chatHistoryEntries.push({ | |
| 442 | + role: "tool", | |
| 443 | + tool_call_id: toolCall.id, | |
| 444 | + content: errorMessage, | |
| 445 | + }); | |
| 446 | + | |
| 447 | + callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 448 | + } | |
| 449 | + } | |
| 450 | + | |
| 451 | + return { | |
| 452 | + hasRejection, | |
| 453 | + chatHistoryEntries, | |
| 454 | + }; | |
| 455 | +} |
added extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts +171 −0
| @@ -0,0 +1,171 @@ | ||
| 1 | +import { beforeEach, describe, expect, test, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { | |
| 4 | + SERVICE_NAMES, | |
| 5 | + initializeServices, | |
| 6 | + serviceContainer, | |
| 7 | +} from "../services/index.js"; | |
| 8 | +import { modeService } from "../services/ModeService.js"; | |
| 9 | + | |
| 10 | +import { getAllTools } from "./handleToolCalls.js"; | |
| 11 | + | |
| 12 | +describe("streamChatResponse - Mode Switch During Streaming", () => { | |
| 13 | + beforeEach(async () => { | |
| 14 | + // Clean up service container state before each test | |
| 15 | + const services = [ | |
| 16 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 17 | + SERVICE_NAMES.AUTH, | |
| 18 | + SERVICE_NAMES.API_CLIENT, | |
| 19 | + SERVICE_NAMES.CONFIG, | |
| 20 | + SERVICE_NAMES.MODEL, | |
| 21 | + SERVICE_NAMES.MCP, | |
| 22 | + ]; | |
| 23 | + | |
| 24 | + services.forEach((service) => { | |
| 25 | + (serviceContainer as any).services.delete(service); | |
| 26 | + (serviceContainer as any).factories.delete(service); | |
| 27 | + (serviceContainer as any).dependencies.delete(service); | |
| 28 | + }); | |
| 29 | + | |
| 30 | + // Initialize services in normal mode | |
| 31 | + await initializeServices({ | |
| 32 | + headless: true, | |
| 33 | + toolPermissionOverrides: { | |
| 34 | + mode: "normal", | |
| 35 | + }, | |
| 36 | + }); | |
| 37 | + }); | |
| 38 | + | |
| 39 | + test("should recompute tools on each iteration to handle mode switches", async () => { | |
| 40 | + // Start in normal mode | |
| 41 | + let tools = await getAllTools(); | |
| 42 | + let toolNames = tools.map((t) => t.function.name); | |
| 43 | + | |
| 44 | + // Should include write tools in normal mode | |
| 45 | + expect(toolNames).toContain("Write"); | |
| 46 | + expect(toolNames).toContain("Edit"); | |
| 47 | + | |
| 48 | + // Switch to plan mode (simulating Shift+Tab during streaming) | |
| 49 | + modeService.switchMode("plan"); | |
| 50 | + | |
| 51 | + // Update the service container (this is what UserInput.tsx does) | |
| 52 | + const updatedState = modeService.getToolPermissionService().getState(); | |
| 53 | + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 54 | + | |
| 55 | + // Recompute tools - should now exclude write tools | |
| 56 | + tools = await getAllTools(); | |
| 57 | + toolNames = tools.map((t) => t.function.name); | |
| 58 | + | |
| 59 | + // Should exclude write tools in plan mode | |
| 60 | + expect(toolNames).not.toContain("Write"); | |
| 61 | + expect(toolNames).not.toContain("Edit"); | |
| 62 | + | |
| 63 | + // Should still include read-only tools | |
| 64 | + expect(toolNames).toContain("Read"); | |
| 65 | + expect(toolNames).toContain("Bash"); | |
| 66 | + expect(toolNames).toContain("List"); | |
| 67 | + }); | |
| 68 | + | |
| 69 | + test("getAllTools reflects current mode immediately", async () => { | |
| 70 | + // Start in normal mode | |
| 71 | + expect(modeService.getCurrentMode()).toBe("normal"); | |
| 72 | + let tools = await getAllTools(); | |
| 73 | + expect(tools.map((t) => t.function.name)).toContain("Write"); | |
| 74 | + | |
| 75 | + // Switch to plan mode | |
| 76 | + modeService.switchMode("plan"); | |
| 77 | + let updatedState = modeService.getToolPermissionService().getState(); | |
| 78 | + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 79 | + expect(modeService.getCurrentMode()).toBe("plan"); | |
| 80 | + | |
| 81 | + // getAllTools should immediately reflect the new mode | |
| 82 | + tools = await getAllTools(); | |
| 83 | + expect(tools.map((t) => t.function.name)).not.toContain("Write"); | |
| 84 | + | |
| 85 | + // Switch to auto mode | |
| 86 | + modeService.switchMode("auto"); | |
| 87 | + updatedState = modeService.getToolPermissionService().getState(); | |
| 88 | + serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 89 | + expect(modeService.getCurrentMode()).toBe("auto"); | |
| 90 | + | |
| 91 | + // getAllTools should immediately reflect auto mode (all tools allowed) | |
| 92 | + tools = await getAllTools(); | |
| 93 | + expect(tools.map((t) => t.function.name)).toContain("Write"); | |
| 94 | + expect(tools.map((t) => t.function.name)).toContain("Edit"); | |
| 95 | + expect(tools.map((t) => t.function.name)).toContain("Read"); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + test("demonstrates the fix: no more stale tool lists", async () => { | |
| 99 | + // This test demonstrates that the fix prevents the original race condition | |
| 100 | + | |
| 101 | + // Mock a multi-turn conversation scenario | |
| 102 | + const mockLlmApi = { | |
| 103 | + chatCompletions: { | |
| 104 | + create: vi.fn().mockImplementation(() => { | |
| 105 | + // Return a mock stream that would trigger multiple iterations | |
| 106 | + return { | |
| 107 | + [Symbol.asyncIterator]: async function* () { | |
| 108 | + // First response - content only | |
| 109 | + yield { | |
| 110 | + choices: [ | |
| 111 | + { | |
| 112 | + delta: { content: "I'll help you with that." }, | |
| 113 | + finish_reason: null, | |
| 114 | + }, | |
| 115 | + ], | |
| 116 | + }; | |
| 117 | + | |
| 118 | + // Second response - indicates tool calls coming | |
| 119 | + yield { | |
| 120 | + choices: [ | |
| 121 | + { | |
| 122 | + delta: { | |
| 123 | + tool_calls: [ | |
| 124 | + { | |
| 125 | + index: 0, | |
| 126 | + id: "call_1", | |
| 127 | + function: { | |
| 128 | + name: "Read", | |
| 129 | + arguments: '{"filepath": "test.txt"}', | |
| 130 | + }, | |
| 131 | + }, | |
| 132 | + ], | |
| 133 | + }, | |
| 134 | + finish_reason: null, | |
| 135 | + }, | |
| 136 | + ], | |
| 137 | + }; | |
| 138 | + | |
| 139 | + // Final response | |
| 140 | + yield { | |
| 141 | + choices: [ | |
| 142 | + { | |
| 143 | + delta: {}, | |
| 144 | + finish_reason: "tool_calls", | |
| 145 | + }, | |
| 146 | + ], | |
| 147 | + }; | |
| 148 | + }, | |
| 149 | + }; | |
| 150 | + }), | |
| 151 | + }, | |
| 152 | + }; | |
| 153 | + | |
| 154 | + const mockModel = { | |
| 155 | + model: "gpt-4", | |
| 156 | + defaultCompletionOptions: {}, | |
| 157 | + }; | |
| 158 | + | |
| 159 | + const abortController = new AbortController(); | |
| 160 | + | |
| 161 | + // Start in normal mode - tools should include Write | |
| 162 | + const initialTools = await getAllTools(); | |
| 163 | + expect(initialTools.map((t) => t.function.name)).toContain("Write"); | |
| 164 | + | |
| 165 | + // During streaming, if mode switches, subsequent iterations should use new tools | |
| 166 | + // This is now handled by recomputing tools on each iteration | |
| 167 | + | |
| 168 | + // The fix ensures that each call to processStreamingResponse gets fresh tools | |
| 169 | + // based on the current mode, preventing the race condition | |
| 170 | + }); | |
| 171 | +}); |
added extensions/cli/src/stream/streamChatResponse.test.ts +698 −0
| @@ -0,0 +1,698 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | +import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs"; | |
| 5 | +import { vi } from "vitest"; | |
| 6 | + | |
| 7 | +import { toolPermissionManager } from "../permissions/permissionManager.js"; | |
| 8 | +import { ToolCall } from "../tools/index.js"; | |
| 9 | +import { readFileTool } from "../tools/readFile.js"; | |
| 10 | +import { searchCodeTool } from "../tools/searchCode.js"; | |
| 11 | +import { PreprocessedToolCall } from "../tools/types.js"; | |
| 12 | +import { writeFileTool } from "../tools/writeFile.js"; | |
| 13 | + | |
| 14 | +import { | |
| 15 | + executeStreamedToolCalls, | |
| 16 | + preprocessStreamedToolCalls, | |
| 17 | +} from "./streamChatResponse.helpers.js"; | |
| 18 | +import { processStreamingResponse } from "./streamChatResponse.js"; | |
| 19 | + | |
| 20 | +// Test the chunk processing logic that was identified as buggy | |
| 21 | +describe("processStreamingResponse - content preservation", () => { | |
| 22 | + // Mock dependencies | |
| 23 | + let mockLlmApi: BaseLlmApi; | |
| 24 | + let mockAbortController: AbortController; | |
| 25 | + let mockModel: ModelConfig; | |
| 26 | + let chunks: ChatCompletionChunk[]; | |
| 27 | + let chatHistory: ChatHistoryItem[]; | |
| 28 | + | |
| 29 | + // Helper to create a content chunk | |
| 30 | + function contentChunk(content: string): ChatCompletionChunk { | |
| 31 | + return { | |
| 32 | + id: "test", | |
| 33 | + object: "chat.completion.chunk", | |
| 34 | + created: Date.now(), | |
| 35 | + model: "test-model", | |
| 36 | + choices: [ | |
| 37 | + { | |
| 38 | + index: 0, | |
| 39 | + delta: { content }, | |
| 40 | + finish_reason: null, | |
| 41 | + }, | |
| 42 | + ], | |
| 43 | + }; | |
| 44 | + } | |
| 45 | + | |
| 46 | + // Helper to create a tool call chunk | |
| 47 | + function toolCallChunk( | |
| 48 | + id: string, | |
| 49 | + name?: string, | |
| 50 | + args?: string, | |
| 51 | + ): ChatCompletionChunk { | |
| 52 | + return { | |
| 53 | + id: "test", | |
| 54 | + object: "chat.completion.chunk", | |
| 55 | + created: Date.now(), | |
| 56 | + model: "test-model", | |
| 57 | + choices: [ | |
| 58 | + { | |
| 59 | + index: 0, | |
| 60 | + delta: { | |
| 61 | + tool_calls: [ | |
| 62 | + { | |
| 63 | + index: 0, | |
| 64 | + id, | |
| 65 | + type: "function", | |
| 66 | + function: { | |
| 67 | + name: name || undefined, | |
| 68 | + arguments: args || undefined, | |
| 69 | + }, | |
| 70 | + }, | |
| 71 | + ], | |
| 72 | + }, | |
| 73 | + finish_reason: null, | |
| 74 | + }, | |
| 75 | + ], | |
| 76 | + }; | |
| 77 | + } | |
| 78 | + | |
| 79 | + // Helper to create a tool call chunk with optional ID | |
| 80 | + function toolCallChunkWithIndex( | |
| 81 | + index: number, | |
| 82 | + id?: string, | |
| 83 | + name?: string, | |
| 84 | + args?: string, | |
| 85 | + ): ChatCompletionChunk { | |
| 86 | + const toolCall: any = { | |
| 87 | + index, | |
| 88 | + type: "function" as const, | |
| 89 | + function: {}, | |
| 90 | + }; | |
| 91 | + | |
| 92 | + if (id) toolCall.id = id; | |
| 93 | + if (name) toolCall.function.name = name; | |
| 94 | + if (args !== undefined) toolCall.function.arguments = args; | |
| 95 | + | |
| 96 | + return { | |
| 97 | + id: "test", | |
| 98 | + object: "chat.completion.chunk" as const, | |
| 99 | + created: Date.now(), | |
| 100 | + model: "test-model", | |
| 101 | + choices: [ | |
| 102 | + { | |
| 103 | + index: 0, | |
| 104 | + delta: { tool_calls: [toolCall] }, | |
| 105 | + finish_reason: null, | |
| 106 | + }, | |
| 107 | + ], | |
| 108 | + }; | |
| 109 | + } | |
| 110 | + | |
| 111 | + beforeEach(() => { | |
| 112 | + // Reset chunks for each test | |
| 113 | + chunks = []; | |
| 114 | + chatHistory = [ | |
| 115 | + { | |
| 116 | + message: { role: "user", content: "Test prompt" }, | |
| 117 | + contextItems: [], | |
| 118 | + }, | |
| 119 | + ]; | |
| 120 | + | |
| 121 | + // Create a mock LLM API that returns our predefined chunks | |
| 122 | + mockLlmApi = { | |
| 123 | + chatCompletionStream: vi.fn().mockImplementation(async function* () { | |
| 124 | + for (const chunk of chunks) { | |
| 125 | + yield chunk; | |
| 126 | + } | |
| 127 | + }), | |
| 128 | + } as unknown as BaseLlmApi; | |
| 129 | + | |
| 130 | + // Mock abort controller | |
| 131 | + mockAbortController = { | |
| 132 | + signal: { aborted: false }, | |
| 133 | + } as unknown as AbortController; | |
| 134 | + | |
| 135 | + // Mock model config | |
| 136 | + mockModel = { | |
| 137 | + model: "test-model", | |
| 138 | + provider: "test-provider", | |
| 139 | + } as unknown as ModelConfig; | |
| 140 | + }); | |
| 141 | + | |
| 142 | + it("content after tool calls is preserved", async () => { | |
| 143 | + chunks = [ | |
| 144 | + contentChunk(""), | |
| 145 | + toolCallChunk("call_123", "Read", '{"filepath": "/README.md"}'), | |
| 146 | + contentChunk(""), | |
| 147 | + contentChunk("I'll read the README file for you."), | |
| 148 | + ]; | |
| 149 | + | |
| 150 | + const result = await processStreamingResponse({ | |
| 151 | + chatHistory, | |
| 152 | + model: mockModel, | |
| 153 | + llmApi: mockLlmApi, | |
| 154 | + abortController: mockAbortController, | |
| 155 | + }); | |
| 156 | + | |
| 157 | + expect(result.content).toBe("I'll read the README file for you."); | |
| 158 | + expect(result.toolCalls.length).toBe(1); | |
| 159 | + | |
| 160 | + // Fixed: finalContent should preserve the content | |
| 161 | + expect(result.finalContent).toBe("I'll read the README file for you."); | |
| 162 | + }); | |
| 163 | + | |
| 164 | + it("content before tool calls is preserved", async () => { | |
| 165 | + chunks = [ | |
| 166 | + contentChunk("Let me search for that. "), | |
| 167 | + toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), | |
| 168 | + ]; | |
| 169 | + | |
| 170 | + const result = await processStreamingResponse({ | |
| 171 | + chatHistory, | |
| 172 | + model: mockModel, | |
| 173 | + llmApi: mockLlmApi, | |
| 174 | + abortController: mockAbortController, | |
| 175 | + }); | |
| 176 | + | |
| 177 | + expect(result.content).toBe("Let me search for that. "); | |
| 178 | + expect(result.toolCalls.length).toBe(1); | |
| 179 | + | |
| 180 | + // Fixed: finalContent preserves content before tool calls | |
| 181 | + expect(result.finalContent).toBe("Let me search for that. "); | |
| 182 | + }); | |
| 183 | + | |
| 184 | + it("handles the exact problematic sequence from the logs", async () => { | |
| 185 | + chunks = [ | |
| 186 | + contentChunk(""), | |
| 187 | + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "Read", ""), | |
| 188 | + toolCallChunk( | |
| 189 | + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 190 | + undefined, | |
| 191 | + '{"filepath', | |
| 192 | + ), | |
| 193 | + toolCallChunk( | |
| 194 | + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 195 | + undefined, | |
| 196 | + '": "/Use', | |
| 197 | + ), | |
| 198 | + toolCallChunk( | |
| 199 | + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 200 | + undefined, | |
| 201 | + "rs/nate/gh/c", | |
| 202 | + ), | |
| 203 | + toolCallChunk( | |
| 204 | + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 205 | + undefined, | |
| 206 | + "ontinuede", | |
| 207 | + ), | |
| 208 | + toolCallChunk( | |
| 209 | + "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 210 | + undefined, | |
| 211 | + "v/cli/README", | |
| 212 | + ), | |
| 213 | + toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), | |
| 214 | + contentChunk(""), | |
| 215 | + contentChunk("I'll read the README file for you."), | |
| 216 | + ]; | |
| 217 | + | |
| 218 | + const result = await processStreamingResponse({ | |
| 219 | + chatHistory, | |
| 220 | + model: mockModel, | |
| 221 | + llmApi: mockLlmApi, | |
| 222 | + abortController: mockAbortController, | |
| 223 | + }); | |
| 224 | + | |
| 225 | + expect(result.content).toBe("I'll read the README file for you."); | |
| 226 | + expect(result.toolCalls.length).toBe(1); | |
| 227 | + | |
| 228 | + // Fixed: content is preserved | |
| 229 | + expect(result.finalContent).toBe("I'll read the README file for you."); | |
| 230 | + | |
| 231 | + // Verify the tool call was assembled correctly | |
| 232 | + expect(result.toolCalls[0].name).toBe("Read"); | |
| 233 | + expect(result.toolCalls[0].argumentsStr).toBe( | |
| 234 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 235 | + ); | |
| 236 | + }); | |
| 237 | + | |
| 238 | + it("shows content works fine without tool calls", async () => { | |
| 239 | + chunks = [contentChunk("Hello "), contentChunk("world!")]; | |
| 240 | + | |
| 241 | + const result = await processStreamingResponse({ | |
| 242 | + chatHistory, | |
| 243 | + model: mockModel, | |
| 244 | + llmApi: mockLlmApi, | |
| 245 | + abortController: mockAbortController, | |
| 246 | + }); | |
| 247 | + | |
| 248 | + expect(result.content).toBe("Hello world!"); | |
| 249 | + expect(result.toolCalls.length).toBe(0); | |
| 250 | + | |
| 251 | + // Without tool calls, finalContent is correct | |
| 252 | + expect(result.finalContent).toBe("Hello world!"); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + it("handles provider that only sends tool ID in first chunk then uses index", async () => { | |
| 256 | + chunks = [ | |
| 257 | + contentChunk("I'll read the README.md file for you and then say hello!"), | |
| 258 | + // First chunk has ID | |
| 259 | + toolCallChunkWithIndex( | |
| 260 | + 0, | |
| 261 | + "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", | |
| 262 | + "Read", | |
| 263 | + "", | |
| 264 | + ), | |
| 265 | + // Subsequent chunks only have index, no ID | |
| 266 | + toolCallChunkWithIndex( | |
| 267 | + 0, | |
| 268 | + undefined, | |
| 269 | + undefined, | |
| 270 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 271 | + ), | |
| 272 | + ]; | |
| 273 | + | |
| 274 | + const result = await processStreamingResponse({ | |
| 275 | + chatHistory, | |
| 276 | + model: mockModel, | |
| 277 | + llmApi: mockLlmApi, | |
| 278 | + abortController: mockAbortController, | |
| 279 | + }); | |
| 280 | + | |
| 281 | + // Content is captured correctly | |
| 282 | + expect(result.content).toBe( | |
| 283 | + "I'll read the README.md file for you and then say hello!", | |
| 284 | + ); | |
| 285 | + expect(result.toolCalls.length).toBe(1); | |
| 286 | + | |
| 287 | + // Fixed: finalContent preserves content | |
| 288 | + expect(result.finalContent).toBe( | |
| 289 | + "I'll read the README.md file for you and then say hello!", | |
| 290 | + ); | |
| 291 | + | |
| 292 | + // Tool call arguments are preserved using index mapping | |
| 293 | + expect(result.toolCalls[0].name).toBe("Read"); | |
| 294 | + expect(result.toolCalls[0].argumentsStr).toBe( | |
| 295 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 296 | + ); | |
| 297 | + }); | |
| 298 | + | |
| 299 | + it("handles realistic fragmented arguments from index-based provider", async () => { | |
| 300 | + // Simulate the exact sequence from the user's logs with fragmented JSON | |
| 301 | + chunks = [ | |
| 302 | + contentChunk("I'll read the README.md file for you and then say hello!"), | |
| 303 | + // First chunk has ID | |
| 304 | + toolCallChunkWithIndex( | |
| 305 | + 0, | |
| 306 | + "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", | |
| 307 | + "Read", | |
| 308 | + "", | |
| 309 | + ), | |
| 310 | + // Subsequent chunks fragment the JSON arguments | |
| 311 | + toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), | |
| 312 | + toolCallChunkWithIndex(0, undefined, undefined, 'th"'), | |
| 313 | + toolCallChunkWithIndex(0, undefined, undefined, ": "), | |
| 314 | + toolCallChunkWithIndex(0, undefined, undefined, '"/U'), | |
| 315 | + toolCallChunkWithIndex(0, undefined, undefined, "sers/nate/gh"), | |
| 316 | + toolCallChunkWithIndex(0, undefined, undefined, "/c"), | |
| 317 | + toolCallChunkWithIndex(0, undefined, undefined, "onti"), | |
| 318 | + toolCallChunkWithIndex(0, undefined, undefined, "nuedev/cli"), | |
| 319 | + toolCallChunkWithIndex(0, undefined, undefined, "/READ"), | |
| 320 | + toolCallChunkWithIndex(0, undefined, undefined, "ME.m"), | |
| 321 | + toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), | |
| 322 | + ]; | |
| 323 | + | |
| 324 | + const result = await processStreamingResponse({ | |
| 325 | + chatHistory, | |
| 326 | + model: mockModel, | |
| 327 | + llmApi: mockLlmApi, | |
| 328 | + abortController: mockAbortController, | |
| 329 | + }); | |
| 330 | + | |
| 331 | + // Fixed: Both issues are resolved | |
| 332 | + // 1. Content is preserved | |
| 333 | + expect(result.finalContent).toBe( | |
| 334 | + "I'll read the README.md file for you and then say hello!", | |
| 335 | + ); | |
| 336 | + | |
| 337 | + // 2. Tool call arguments are assembled correctly | |
| 338 | + expect(result.toolCalls[0].name).toBe("Read"); | |
| 339 | + expect(result.toolCalls[0].argumentsStr).toBe( | |
| 340 | + '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 341 | + ); | |
| 342 | + }); | |
| 343 | + | |
| 344 | + it("handles malformed chunk with empty choices array without crashing", async () => { | |
| 345 | + // This reproduces the exact bug from the logs: | |
| 346 | + // {"chunk":{"choices":[],"usage":{"completion_tokens":96,"prompt_tokens":711,"total_tokens":807,"prompt_tokens_details":{"cached_tokens":3353}},"created":1754927672408,"id":"","model":"claude-sonnet-4-20250514","object":"chat.completion.chunk"}} | |
| 347 | + const malformedChunk: ChatCompletionChunk = { | |
| 348 | + id: "", | |
| 349 | + object: "chat.completion.chunk", | |
| 350 | + created: 1754927672408, | |
| 351 | + model: "claude-sonnet-4-20250514", | |
| 352 | + choices: [], // Empty choices array - this causes the bug | |
| 353 | + usage: { | |
| 354 | + completion_tokens: 96, | |
| 355 | + prompt_tokens: 711, | |
| 356 | + total_tokens: 807, | |
| 357 | + prompt_tokens_details: { | |
| 358 | + cached_tokens: 3353, | |
| 359 | + }, | |
| 360 | + }, | |
| 361 | + }; | |
| 362 | + | |
| 363 | + chunks = [ | |
| 364 | + malformedChunk, // Put malformed chunk first to trigger the bug more clearly | |
| 365 | + contentChunk("Hello "), | |
| 366 | + contentChunk("world!"), | |
| 367 | + ]; | |
| 368 | + | |
| 369 | + // This should not throw an error: "Cannot read properties of undefined (reading 'delta')" | |
| 370 | + let caughtError: any = null; | |
| 371 | + try { | |
| 372 | + await processStreamingResponse({ | |
| 373 | + chatHistory, | |
| 374 | + model: mockModel, | |
| 375 | + llmApi: mockLlmApi, | |
| 376 | + abortController: mockAbortController, | |
| 377 | + }); | |
| 378 | + } catch (error) { | |
| 379 | + caughtError = error; | |
| 380 | + } | |
| 381 | + | |
| 382 | + // Should NOT throw error about reading 'delta' property | |
| 383 | + expect(caughtError).toBeNull(); | |
| 384 | + | |
| 385 | + const result = await processStreamingResponse({ | |
| 386 | + chatHistory, | |
| 387 | + model: mockModel, | |
| 388 | + llmApi: mockLlmApi, | |
| 389 | + abortController: mockAbortController, | |
| 390 | + }); | |
| 391 | + | |
| 392 | + expect(result.content).toBe("Hello world!"); | |
| 393 | + expect(result.toolCalls.length).toBe(0); | |
| 394 | + expect(result.finalContent).toBe("Hello world!"); | |
| 395 | + }); | |
| 396 | +}); | |
| 397 | + | |
| 398 | +// Tests for preprocessStreamedToolCalls function | |
| 399 | +describe.skip("preprocessStreamedToolCalls", () => { | |
| 400 | + // Mock dependencies | |
| 401 | + beforeEach(async () => { | |
| 402 | + // Mock setup would go here but is currently causing issues | |
| 403 | + }); | |
| 404 | + | |
| 405 | + afterEach(() => { | |
| 406 | + vi.restoreAllMocks(); | |
| 407 | + }); | |
| 408 | + | |
| 409 | + it("preprocesses valid tool calls correctly", async () => { | |
| 410 | + const toolCalls: ToolCall[] = [ | |
| 411 | + { | |
| 412 | + id: "call_123", | |
| 413 | + name: "Read", | |
| 414 | + arguments: { filepath: "/path/to/file.txt" }, | |
| 415 | + argumentsStr: '{"filepath": "/path/to/file.txt"}', | |
| 416 | + startNotified: false, | |
| 417 | + }, | |
| 418 | + ]; | |
| 419 | + | |
| 420 | + const callbacks = { | |
| 421 | + onToolStart: vi.fn(), | |
| 422 | + onToolError: vi.fn(), | |
| 423 | + }; | |
| 424 | + | |
| 425 | + const { preprocessedCalls, errorChatEntries } = | |
| 426 | + await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 427 | + | |
| 428 | + // Should have one preprocessed call and no errors | |
| 429 | + expect(preprocessedCalls).toHaveLength(1); | |
| 430 | + expect(errorChatEntries).toHaveLength(0); | |
| 431 | + expect(preprocessedCalls[0].name).toBe("Read"); | |
| 432 | + expect(preprocessedCalls[0].tool).toBeDefined(); | |
| 433 | + expect(preprocessedCalls[0].preprocessResult).toBeDefined(); | |
| 434 | + | |
| 435 | + // Callbacks should not be called for successful preprocessing | |
| 436 | + expect(callbacks.onToolStart).not.toHaveBeenCalled(); | |
| 437 | + expect(callbacks.onToolError).not.toHaveBeenCalled(); | |
| 438 | + }); | |
| 439 | + | |
| 440 | + it("handles tool preprocessing errors correctly", async () => { | |
| 441 | + // Set the spy to throw an error | |
| 442 | + const toolsModule = await import("../tools/index.js"); | |
| 443 | + vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce( | |
| 444 | + () => { | |
| 445 | + throw new Error("Missing required argument"); | |
| 446 | + }, | |
| 447 | + ); | |
| 448 | + | |
| 449 | + const toolCalls: ToolCall[] = [ | |
| 450 | + { | |
| 451 | + id: "call_456", | |
| 452 | + name: "Read", | |
| 453 | + arguments: {}, // Missing required filepath | |
| 454 | + argumentsStr: "{}", | |
| 455 | + startNotified: false, | |
| 456 | + }, | |
| 457 | + ]; | |
| 458 | + | |
| 459 | + const callbacks = { | |
| 460 | + onToolStart: vi.fn(), | |
| 461 | + onToolError: vi.fn(), | |
| 462 | + }; | |
| 463 | + | |
| 464 | + const { preprocessedCalls, errorChatEntries } = | |
| 465 | + await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 466 | + | |
| 467 | + // Should have no preprocessed calls and one error | |
| 468 | + expect(preprocessedCalls).toHaveLength(0); | |
| 469 | + expect(errorChatEntries).toHaveLength(1); | |
| 470 | + expect(errorChatEntries[0].content).toContain("Missing required argument"); | |
| 471 | + | |
| 472 | + // Callbacks should be called for errors | |
| 473 | + expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {}); | |
| 474 | + expect(callbacks.onToolError).toHaveBeenCalledWith( | |
| 475 | + expect.stringContaining("Missing required argument"), | |
| 476 | + "Read", | |
| 477 | + ); | |
| 478 | + }); | |
| 479 | + | |
| 480 | + it("handles tool not found errors", async () => { | |
| 481 | + const toolCalls: ToolCall[] = [ | |
| 482 | + { | |
| 483 | + id: "call_789", | |
| 484 | + name: "nonexistent_tool", | |
| 485 | + arguments: { some: "arg" }, | |
| 486 | + argumentsStr: '{"some": "arg"}', | |
| 487 | + startNotified: false, | |
| 488 | + }, | |
| 489 | + ]; | |
| 490 | + | |
| 491 | + const { preprocessedCalls, errorChatEntries } = | |
| 492 | + await preprocessStreamedToolCalls(toolCalls); | |
| 493 | + | |
| 494 | + // Should have no preprocessed calls and one error | |
| 495 | + expect(preprocessedCalls).toHaveLength(0); | |
| 496 | + expect(errorChatEntries).toHaveLength(1); | |
| 497 | + expect(errorChatEntries[0].content).toContain( | |
| 498 | + "Tool nonexistent_tool not found", | |
| 499 | + ); | |
| 500 | + }); | |
| 501 | +}); | |
| 502 | + | |
| 503 | +// Tests for executeStreamedToolCalls function | |
| 504 | +describe.skip("executeStreamedToolCalls", () => { | |
| 505 | + beforeEach(() => { | |
| 506 | + // Reset spies | |
| 507 | + vi.spyOn(toolPermissionManager, "requestPermission").mockReset(); | |
| 508 | + vi.spyOn(toolPermissionManager, "on").mockReset(); | |
| 509 | + vi.spyOn(toolPermissionManager, "off").mockReset(); | |
| 510 | + }); | |
| 511 | + | |
| 512 | + it("executes tool calls with allowed permissions", async () => { | |
| 513 | + // Setup spies instead of mocks | |
| 514 | + const permissionsModule = await import("../permissions/index.js"); | |
| 515 | + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 516 | + permission: "allow", | |
| 517 | + }); | |
| 518 | + | |
| 519 | + const toolsModule = await import("../tools/index.js"); | |
| 520 | + const mockedExecuteToolCall = vi | |
| 521 | + .spyOn(toolsModule, "executeToolCall") | |
| 522 | + .mockResolvedValue("Tool execution successful"); | |
| 523 | + | |
| 524 | + // Create preprocessed tool call | |
| 525 | + const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 526 | + { | |
| 527 | + id: "call_123", | |
| 528 | + name: "Read", | |
| 529 | + arguments: { filepath: "/test.txt" }, | |
| 530 | + argumentsStr: '{"filepath": "/test.txt"}', | |
| 531 | + startNotified: false, | |
| 532 | + tool: readFileTool, | |
| 533 | + }, | |
| 534 | + ]; | |
| 535 | + | |
| 536 | + const callbacks = { | |
| 537 | + onToolStart: vi.fn(), | |
| 538 | + onToolResult: vi.fn(), | |
| 539 | + onToolError: vi.fn(), | |
| 540 | + }; | |
| 541 | + | |
| 542 | + const { chatHistoryEntries } = await executeStreamedToolCalls( | |
| 543 | + preprocessedCalls, | |
| 544 | + callbacks, | |
| 545 | + ); | |
| 546 | + | |
| 547 | + // Verify results | |
| 548 | + expect(chatHistoryEntries).toHaveLength(1); | |
| 549 | + expect(chatHistoryEntries[0].content).toBe("Tool execution successful"); | |
| 550 | + expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", { | |
| 551 | + filepath: "/test.txt", | |
| 552 | + }); | |
| 553 | + expect(callbacks.onToolResult).toHaveBeenCalledWith( | |
| 554 | + "Tool execution successful", | |
| 555 | + "Read", | |
| 556 | + "done", | |
| 557 | + ); | |
| 558 | + expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]); | |
| 559 | + }); | |
| 560 | + | |
| 561 | + it("handles permission denied correctly", async () => { | |
| 562 | + // Setup permission to ask | |
| 563 | + const permissionsModule = await import("../permissions/index.js"); | |
| 564 | + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 565 | + permission: "ask", | |
| 566 | + }); | |
| 567 | + | |
| 568 | + // Spy on permission request to be denied | |
| 569 | + vi.spyOn(toolPermissionManager, "requestPermission").mockResolvedValue({ | |
| 570 | + approved: false, | |
| 571 | + }); | |
| 572 | + | |
| 573 | + // Add event listener mock | |
| 574 | + vi.spyOn(toolPermissionManager, "on").mockImplementation( | |
| 575 | + (event: any, callback: any) => { | |
| 576 | + if (event === "permissionRequested") { | |
| 577 | + // Immediately trigger the callback to simulate event | |
| 578 | + callback({ | |
| 579 | + requestId: "req_123", | |
| 580 | + toolCall: { | |
| 581 | + name: "Write", | |
| 582 | + arguments: { | |
| 583 | + filepath: "/test.txt", | |
| 584 | + content: "data", | |
| 585 | + }, | |
| 586 | + }, | |
| 587 | + }); | |
| 588 | + } | |
| 589 | + return toolPermissionManager; | |
| 590 | + }, | |
| 591 | + ); | |
| 592 | + | |
| 593 | + // Create preprocessed tool call | |
| 594 | + const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 595 | + { | |
| 596 | + id: "call_456", | |
| 597 | + name: "Write", | |
| 598 | + arguments: { filepath: "/test.txt", content: "data" }, | |
| 599 | + argumentsStr: '{"filepath": "/test.txt", "content": "data"}', | |
| 600 | + startNotified: false, | |
| 601 | + tool: writeFileTool, | |
| 602 | + }, | |
| 603 | + { | |
| 604 | + id: "call_457", | |
| 605 | + name: "Write", | |
| 606 | + arguments: { filepath: "/test.txt", content: "data" }, | |
| 607 | + argumentsStr: '{"filepath": "/test.txt", "content": "data"}', | |
| 608 | + startNotified: false, | |
| 609 | + tool: writeFileTool, | |
| 610 | + }, | |
| 611 | + ]; | |
| 612 | + | |
| 613 | + const callbacks = { | |
| 614 | + onToolStart: vi.fn(), | |
| 615 | + onToolResult: vi.fn(), | |
| 616 | + onToolPermissionRequest: vi.fn(), | |
| 617 | + }; | |
| 618 | + | |
| 619 | + const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( | |
| 620 | + preprocessedCalls, | |
| 621 | + callbacks, | |
| 622 | + ); | |
| 623 | + | |
| 624 | + // Verify results | |
| 625 | + expect(hasRejection).toEqual(true); | |
| 626 | + expect(chatHistoryEntries).toHaveLength(2); | |
| 627 | + expect(chatHistoryEntries[0].content).toBe("Permission denied by user"); | |
| 628 | + expect(chatHistoryEntries[1].content).toBe( | |
| 629 | + "Cancelled due to previous tool rejection", | |
| 630 | + ); | |
| 631 | + expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", { | |
| 632 | + filepath: "/test.txt", | |
| 633 | + content: "data", | |
| 634 | + }); | |
| 635 | + expect(callbacks.onToolResult).toHaveBeenCalledWith( | |
| 636 | + "Permission denied by user", | |
| 637 | + "Write", | |
| 638 | + "canceled", | |
| 639 | + ); | |
| 640 | + expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith( | |
| 641 | + "Write", | |
| 642 | + { filepath: "/test.txt", content: "data" }, | |
| 643 | + "req_123", | |
| 644 | + undefined, | |
| 645 | + ); | |
| 646 | + }); | |
| 647 | + | |
| 648 | + it("handles tool execution errors", async () => { | |
| 649 | + // Setup spies | |
| 650 | + const permissionsModule = await import("../permissions/index.js"); | |
| 651 | + vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 652 | + permission: "allow", | |
| 653 | + }); | |
| 654 | + | |
| 655 | + const toolsModule = await import("../tools/index.js"); | |
| 656 | + vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue( | |
| 657 | + new Error("Execution failed"), | |
| 658 | + ); | |
| 659 | + | |
| 660 | + // Create preprocessed tool call | |
| 661 | + const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 662 | + { | |
| 663 | + id: "call_789", | |
| 664 | + name: "search_code", | |
| 665 | + arguments: { pattern: "test" }, | |
| 666 | + argumentsStr: '{"pattern": "test"}', | |
| 667 | + startNotified: false, | |
| 668 | + tool: searchCodeTool, | |
| 669 | + }, | |
| 670 | + ]; | |
| 671 | + | |
| 672 | + const callbacks = { | |
| 673 | + onToolStart: vi.fn(), | |
| 674 | + onToolError: vi.fn(), | |
| 675 | + }; | |
| 676 | + | |
| 677 | + const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( | |
| 678 | + preprocessedCalls, | |
| 679 | + callbacks, | |
| 680 | + ); | |
| 681 | + | |
| 682 | + // Verify results | |
| 683 | + expect(chatHistoryEntries).toHaveLength(1); | |
| 684 | + expect(chatHistoryEntries[0].content).toContain( | |
| 685 | + "Error executing tool search_code", | |
| 686 | + ); | |
| 687 | + expect(chatHistoryEntries[0].content).toContain("Execution failed"); | |
| 688 | + expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", { | |
| 689 | + pattern: "test", | |
| 690 | + }); | |
| 691 | + expect(callbacks.onToolError).toHaveBeenCalledWith( | |
| 692 | + expect.stringContaining( | |
| 693 | + "Error executing tool search_code: Execution failed", | |
| 694 | + ), | |
| 695 | + "search_code", | |
| 696 | + ); | |
| 697 | + }); | |
| 698 | +}); |
added extensions/cli/src/stream/streamChatResponse.ts +403 −0
| @@ -0,0 +1,403 @@ | ||
| 1 | +import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | +import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | +import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | +import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js"; | |
| 5 | +import * as dotenv from "dotenv"; | |
| 6 | +import type { | |
| 7 | + ChatCompletionMessageParam, | |
| 8 | + ChatCompletionTool, | |
| 9 | +} from "openai/resources.mjs"; | |
| 10 | + | |
| 11 | +import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; | |
| 12 | +import { systemMessageService } from "../services/SystemMessageService.js"; | |
| 13 | +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; | |
| 14 | +import { telemetryService } from "../telemetry/telemetryService.js"; | |
| 15 | +import { ToolCall } from "../tools/index.js"; | |
| 16 | +import { | |
| 17 | + chatCompletionStreamWithBackoff, | |
| 18 | + withExponentialBackoff, | |
| 19 | +} from "../util/exponentialBackoff.js"; | |
| 20 | +import { logger } from "../util/logger.js"; | |
| 21 | + | |
| 22 | +import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; | |
| 23 | +import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 24 | +import { | |
| 25 | + processChunkContent, | |
| 26 | + processToolCallDelta, | |
| 27 | + recordStreamTelemetry, | |
| 28 | + trackFirstTokenTime, | |
| 29 | +} from "./streamChatResponse.helpers.js"; | |
| 30 | +import { | |
| 31 | + getDefaultCompletionOptions, | |
| 32 | + StreamCallbacks, | |
| 33 | +} from "./streamChatResponse.types.js"; | |
| 34 | + | |
| 35 | +dotenv.config(); | |
| 36 | + | |
| 37 | +function updateFinalResponse( | |
| 38 | + content: string, | |
| 39 | + shouldContinue: boolean, | |
| 40 | + isHeadless: boolean, | |
| 41 | + currentFinalResponse: string, | |
| 42 | +): string { | |
| 43 | + if (!shouldContinue) { | |
| 44 | + return content; | |
| 45 | + } else if (isHeadless && content) { | |
| 46 | + return content; | |
| 47 | + } | |
| 48 | + return currentFinalResponse; | |
| 49 | +} | |
| 50 | + | |
| 51 | +function handleContentDisplay( | |
| 52 | + content: string, | |
| 53 | + callbacks: StreamCallbacks | undefined, | |
| 54 | + isHeadless: boolean, | |
| 55 | +): void { | |
| 56 | + // Add newline after content if needed | |
| 57 | + if (!callbacks?.onContent && !isHeadless && content) { | |
| 58 | + logger.info(""); | |
| 59 | + } | |
| 60 | + | |
| 61 | + // Notify content complete | |
| 62 | + if (content && callbacks?.onContentComplete) { | |
| 63 | + callbacks.onContentComplete(content); | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +// Helper function to process a single chunk | |
| 68 | +interface ProcessChunkOptions { | |
| 69 | + chunk: any; | |
| 70 | + aiResponse: string; | |
| 71 | + toolCallsMap: Map<string, ToolCall>; | |
| 72 | + indexToIdMap: Map<number, string>; | |
| 73 | + callbacks?: StreamCallbacks; | |
| 74 | + isHeadless?: boolean; | |
| 75 | +} | |
| 76 | + | |
| 77 | +function processChunk(options: ProcessChunkOptions): { | |
| 78 | + aiResponse: string; | |
| 79 | + shouldContinue: boolean; | |
| 80 | +} { | |
| 81 | + const { | |
| 82 | + chunk, | |
| 83 | + aiResponse, | |
| 84 | + toolCallsMap, | |
| 85 | + indexToIdMap, | |
| 86 | + callbacks, | |
| 87 | + isHeadless, | |
| 88 | + } = options; | |
| 89 | + // Safety check: ensure chunk has the expected structure | |
| 90 | + if (!chunk.choices || !chunk.choices[0]) { | |
| 91 | + return { aiResponse, shouldContinue: true }; | |
| 92 | + } | |
| 93 | + | |
| 94 | + const choice = chunk.choices[0]; | |
| 95 | + if (!choice.delta) { | |
| 96 | + return { aiResponse, shouldContinue: true }; | |
| 97 | + } | |
| 98 | + | |
| 99 | + let updatedResponse = aiResponse; | |
| 100 | + | |
| 101 | + // Handle content streaming | |
| 102 | + if (choice.delta.content) { | |
| 103 | + updatedResponse = processChunkContent( | |
| 104 | + choice.delta.content, | |
| 105 | + aiResponse, | |
| 106 | + callbacks, | |
| 107 | + isHeadless, | |
| 108 | + ); | |
| 109 | + } | |
| 110 | + | |
| 111 | + // Handle tool calls | |
| 112 | + if (choice.delta.tool_calls) { | |
| 113 | + for (const toolCallDelta of choice.delta.tool_calls) { | |
| 114 | + processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap); | |
| 115 | + } | |
| 116 | + } | |
| 117 | + | |
| 118 | + return { aiResponse: updatedResponse, shouldContinue: true }; | |
| 119 | +} | |
| 120 | + | |
| 121 | +interface ProcessStreamingResponseOptions { | |
| 122 | + chatHistory: ChatHistoryItem[]; | |
| 123 | + model: ModelConfig; | |
| 124 | + llmApi: BaseLlmApi; | |
| 125 | + abortController: AbortController; | |
| 126 | + callbacks?: StreamCallbacks; | |
| 127 | + isHeadless?: boolean; | |
| 128 | + tools?: ChatCompletionTool[]; | |
| 129 | +} | |
| 130 | + | |
| 131 | +// Process a single streaming response and return whether we need to continue | |
| 132 | +export async function processStreamingResponse( | |
| 133 | + options: ProcessStreamingResponseOptions, | |
| 134 | +): Promise<{ | |
| 135 | + content: string; | |
| 136 | + finalContent: string; // Added field for final content only | |
| 137 | + toolCalls: ToolCall[]; | |
| 138 | + shouldContinue: boolean; | |
| 139 | +}> { | |
| 140 | + const { | |
| 141 | + chatHistory, | |
| 142 | + model, | |
| 143 | + llmApi, | |
| 144 | + abortController, | |
| 145 | + callbacks, | |
| 146 | + isHeadless, | |
| 147 | + tools, | |
| 148 | + } = options; | |
| 149 | + | |
| 150 | + // Get fresh system message and inject it | |
| 151 | + const systemMessage = await systemMessageService.getSystemMessage(); | |
| 152 | + const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( | |
| 153 | + chatHistory, | |
| 154 | + systemMessage, | |
| 155 | + ) as ChatCompletionMessageParam[]; | |
| 156 | + const requestStartTime = Date.now(); | |
| 157 | + | |
| 158 | + const streamFactory = async (retryAbortSignal: AbortSignal) => { | |
| 159 | + logger.debug("Creating chat completion stream", { | |
| 160 | + model, | |
| 161 | + messageCount: chatHistory.length, | |
| 162 | + toolCount: tools?.length || 0, | |
| 163 | + }); | |
| 164 | + return await chatCompletionStreamWithBackoff( | |
| 165 | + llmApi, | |
| 166 | + { | |
| 167 | + model: model.model, | |
| 168 | + messages: openaiChatHistory, | |
| 169 | + stream: true, | |
| 170 | + tools, | |
| 171 | + ...getDefaultCompletionOptions(model.defaultCompletionOptions), | |
| 172 | + }, | |
| 173 | + retryAbortSignal, | |
| 174 | + ); | |
| 175 | + }; | |
| 176 | + | |
| 177 | + let aiResponse = ""; | |
| 178 | + let finalContent = ""; | |
| 179 | + const toolCallsMap = new Map<string, ToolCall>(); | |
| 180 | + const indexToIdMap = new Map<number, string>(); // Track index to ID mapping | |
| 181 | + let firstTokenTime: number | null = null; | |
| 182 | + let inputTokens = 0; | |
| 183 | + let outputTokens = 0; | |
| 184 | + | |
| 185 | + try { | |
| 186 | + const streamWithBackoff = withExponentialBackoff( | |
| 187 | + streamFactory, | |
| 188 | + abortController.signal, | |
| 189 | + ); | |
| 190 | + | |
| 191 | + let chunkCount = 0; | |
| 192 | + for await (const chunk of streamWithBackoff) { | |
| 193 | + chunkCount++; | |
| 194 | + | |
| 195 | + logger.debug("Received chunk", { chunkCount, chunk }); | |
| 196 | + | |
| 197 | + // Track token usage if available | |
| 198 | + if (chunk.usage) { | |
| 199 | + inputTokens = chunk.usage.prompt_tokens || 0; | |
| 200 | + outputTokens = chunk.usage.completion_tokens || 0; | |
| 201 | + } | |
| 202 | + | |
| 203 | + // Check if we should abort | |
| 204 | + if (abortController?.signal.aborted) { | |
| 205 | + logger.debug("Stream aborted"); | |
| 206 | + break; | |
| 207 | + } | |
| 208 | + | |
| 209 | + // Track first token time | |
| 210 | + firstTokenTime = trackFirstTokenTime( | |
| 211 | + firstTokenTime, | |
| 212 | + chunk, | |
| 213 | + requestStartTime, | |
| 214 | + model, | |
| 215 | + tools, | |
| 216 | + ); | |
| 217 | + | |
| 218 | + const result = processChunk({ | |
| 219 | + chunk, | |
| 220 | + aiResponse, | |
| 221 | + toolCallsMap, | |
| 222 | + indexToIdMap, | |
| 223 | + callbacks, | |
| 224 | + isHeadless, | |
| 225 | + }); | |
| 226 | + aiResponse = result.aiResponse; | |
| 227 | + if (!result.shouldContinue) break; | |
| 228 | + } | |
| 229 | + | |
| 230 | + const responseEndTime = Date.now(); | |
| 231 | + const cost = recordStreamTelemetry({ | |
| 232 | + requestStartTime, | |
| 233 | + responseEndTime, | |
| 234 | + inputTokens, | |
| 235 | + outputTokens, | |
| 236 | + model, | |
| 237 | + tools, | |
| 238 | + }); | |
| 239 | + const totalDuration = responseEndTime - requestStartTime; | |
| 240 | + | |
| 241 | + logger.debug("Stream complete", { | |
| 242 | + chunkCount, | |
| 243 | + responseLength: aiResponse.length, | |
| 244 | + toolCallsCount: toolCallsMap.size, | |
| 245 | + inputTokens, | |
| 246 | + outputTokens, | |
| 247 | + cost, | |
| 248 | + duration: totalDuration, | |
| 249 | + }); | |
| 250 | + } catch (error: any) { | |
| 251 | + const errorDuration = Date.now() - requestStartTime; | |
| 252 | + | |
| 253 | + // Log failed API request | |
| 254 | + telemetryService.logApiRequest({ | |
| 255 | + model: model.model, | |
| 256 | + durationMs: errorDuration, | |
| 257 | + success: false, | |
| 258 | + error: error.message || String(error), | |
| 259 | + }); | |
| 260 | + | |
| 261 | + if (error.name === "AbortError" || abortController?.signal.aborted) { | |
| 262 | + logger.debug("Stream aborted by user"); | |
| 263 | + return { | |
| 264 | + content: aiResponse, | |
| 265 | + finalContent: aiResponse, | |
| 266 | + toolCalls: [], | |
| 267 | + shouldContinue: false, | |
| 268 | + }; | |
| 269 | + } | |
| 270 | + throw error; | |
| 271 | + } | |
| 272 | + | |
| 273 | + const toolCalls = Array.from(toolCallsMap.values()); | |
| 274 | + | |
| 275 | + // Validate tool calls have complete arguments | |
| 276 | + const validToolCalls = toolCalls.filter((tc) => { | |
| 277 | + if (!tc.arguments || !tc.name) { | |
| 278 | + logger.error("Incomplete tool call", { | |
| 279 | + id: tc.id, | |
| 280 | + name: tc.name, | |
| 281 | + hasArguments: !!tc.arguments, | |
| 282 | + argumentsStr: tc.argumentsStr, | |
| 283 | + }); | |
| 284 | + return false; | |
| 285 | + } | |
| 286 | + return true; | |
| 287 | + }); | |
| 288 | + | |
| 289 | + // Always preserve the content - it should be displayed regardless of tool calls | |
| 290 | + finalContent = aiResponse; | |
| 291 | + | |
| 292 | + return { | |
| 293 | + content: aiResponse, | |
| 294 | + finalContent: finalContent, | |
| 295 | + toolCalls: validToolCalls, | |
| 296 | + shouldContinue: validToolCalls.length > 0, | |
| 297 | + }; | |
| 298 | +} | |
| 299 | + | |
| 300 | +// Main function that handles the conversation loop | |
| 301 | +export async function streamChatResponse( | |
| 302 | + chatHistory: ChatHistoryItem[], | |
| 303 | + model: ModelConfig, | |
| 304 | + llmApi: BaseLlmApi, | |
| 305 | + abortController: AbortController, | |
| 306 | + callbacks?: StreamCallbacks, | |
| 307 | +) { | |
| 308 | + logger.debug("streamChatResponse called", { | |
| 309 | + model, | |
| 310 | + historyLength: chatHistory.length, | |
| 311 | + hasCallbacks: !!callbacks, | |
| 312 | + }); | |
| 313 | + | |
| 314 | + const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 315 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 316 | + ); | |
| 317 | + const isHeadless = serviceResult.value?.isHeadless ?? false; | |
| 318 | + | |
| 319 | + let fullResponse = ""; | |
| 320 | + let finalResponse = ""; | |
| 321 | + | |
| 322 | + while (true) { | |
| 323 | + logger.debug("Starting conversation iteration"); | |
| 324 | + | |
| 325 | + // Recompute tools on each iteration to handle mode changes during streaming | |
| 326 | + const tools = await getAllTools(); | |
| 327 | + | |
| 328 | + logger.debug("Tools prepared", { | |
| 329 | + toolCount: tools.length, | |
| 330 | + toolNames: tools.map((t) => t.function.name), | |
| 331 | + }); | |
| 332 | + | |
| 333 | + // Get response from LLM | |
| 334 | + const { content, toolCalls, shouldContinue } = | |
| 335 | + await processStreamingResponse({ | |
| 336 | + chatHistory, | |
| 337 | + model, | |
| 338 | + llmApi, | |
| 339 | + abortController, | |
| 340 | + callbacks, | |
| 341 | + isHeadless, | |
| 342 | + tools, | |
| 343 | + }); | |
| 344 | + | |
| 345 | + fullResponse += content; | |
| 346 | + | |
| 347 | + // Update final response based on mode | |
| 348 | + finalResponse = updateFinalResponse( | |
| 349 | + content, | |
| 350 | + shouldContinue, | |
| 351 | + isHeadless, | |
| 352 | + finalResponse, | |
| 353 | + ); | |
| 354 | + | |
| 355 | + // Handle content display | |
| 356 | + handleContentDisplay(content, callbacks, isHeadless); | |
| 357 | + | |
| 358 | + // Handle tool calls and check for early return | |
| 359 | + const shouldReturn = await handleToolCalls( | |
| 360 | + toolCalls, | |
| 361 | + chatHistory, | |
| 362 | + content, | |
| 363 | + callbacks, | |
| 364 | + isHeadless, | |
| 365 | + ); | |
| 366 | + | |
| 367 | + if (shouldReturn) { | |
| 368 | + return finalResponse || content || fullResponse; | |
| 369 | + } | |
| 370 | + | |
| 371 | + // Check for auto-compaction after tool execution | |
| 372 | + if (shouldContinue) { | |
| 373 | + const { wasCompacted, chatHistory: updatedChatHistory } = | |
| 374 | + await handleAutoCompaction(chatHistory, model, llmApi, { | |
| 375 | + isHeadless, | |
| 376 | + callbacks: { | |
| 377 | + onSystemMessage: callbacks?.onSystemMessage, | |
| 378 | + onContent: callbacks?.onContent, | |
| 379 | + }, | |
| 380 | + }); | |
| 381 | + | |
| 382 | + // Only update chat history if compaction actually occurred | |
| 383 | + if (wasCompacted) { | |
| 384 | + chatHistory = [...updatedChatHistory]; | |
| 385 | + } | |
| 386 | + } | |
| 387 | + | |
| 388 | + // Check if we should continue | |
| 389 | + if (!shouldContinue) { | |
| 390 | + break; | |
| 391 | + } | |
| 392 | + } | |
| 393 | + | |
| 394 | + logger.debug("streamChatResponse complete", { | |
| 395 | + totalResponseLength: fullResponse.length, | |
| 396 | + totalMessages: chatHistory.length, | |
| 397 | + }); | |
| 398 | + | |
| 399 | + // For headless mode, we return only the final response | |
| 400 | + // Otherwise, return the full response | |
| 401 | + return isHeadless ? finalResponse : fullResponse; | |
| 402 | +} | |
| 403 | +export { getAllTools }; |
added extensions/cli/src/stream/streamChatResponse.types.ts +33 −0
| @@ -0,0 +1,33 @@ | ||
| 1 | +import { CompletionOptions } from "@continuedev/config-yaml"; | |
| 2 | +import type { ToolStatus } from "core/index.js"; | |
| 3 | +import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; | |
| 4 | + | |
| 5 | +import { ToolCallPreview } from "../tools/types.js"; | |
| 6 | + | |
| 7 | +export interface StreamCallbacks { | |
| 8 | + onContent?: (content: string) => void; | |
| 9 | + onContentComplete?: (content: string) => void; | |
| 10 | + onToolStart?: (toolName: string, toolArgs?: any) => void; | |
| 11 | + onToolResult?: (result: string, toolName: string, status: ToolStatus) => void; | |
| 12 | + onToolError?: (error: string, toolName?: string) => void; | |
| 13 | + onToolPermissionRequest?: ( | |
| 14 | + toolName: string, | |
| 15 | + toolArgs: any, | |
| 16 | + requestId: string, | |
| 17 | + preview?: ToolCallPreview[], | |
| 18 | + ) => void; | |
| 19 | + onSystemMessage?: (message: string) => void; | |
| 20 | +} | |
| 21 | + | |
| 22 | +export function getDefaultCompletionOptions( | |
| 23 | + opts?: CompletionOptions, | |
| 24 | +): Partial<ChatCompletionCreateParamsStreaming> { | |
| 25 | + if (!opts) return {}; | |
| 26 | + return { | |
| 27 | + max_tokens: opts.maxTokens, | |
| 28 | + temperature: opts.temperature, | |
| 29 | + frequency_penalty: opts.frequencyPenalty, | |
| 30 | + presence_penalty: opts.presencePenalty, | |
| 31 | + top_p: opts.topP, | |
| 32 | + }; | |
| 33 | +} |
deleted extensions/cli/src/streamChatResponse.autoCompaction.test.ts +0 −246
| @@ -1,246 +0,0 @@ | ||
| 1 | -import type { ChatHistoryItem } from "core/index.js"; | |
| 2 | -import { beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | - | |
| 4 | -import { convertToUnifiedHistory } from "./messageConversion.js"; | |
| 5 | -import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 6 | - | |
| 7 | -// Mock dependencies | |
| 8 | -vi.mock("./compaction.js", () => ({ | |
| 9 | - compactChatHistory: vi.fn(), | |
| 10 | -})); | |
| 11 | - | |
| 12 | -vi.mock("./session.js", () => ({ | |
| 13 | - createSession: vi.fn((history) => ({ | |
| 14 | - sessionId: "test", | |
| 15 | - title: "Test", | |
| 16 | - workspaceDirectory: "/test", | |
| 17 | - history, | |
| 18 | - })), | |
| 19 | - saveSession: vi.fn(), | |
| 20 | - updateSessionHistory: vi.fn(), | |
| 21 | -})); | |
| 22 | - | |
| 23 | -vi.mock("./util/tokenizer.js", () => ({ | |
| 24 | - shouldAutoCompact: vi.fn(), | |
| 25 | - getAutoCompactMessage: vi.fn(), | |
| 26 | -})); | |
| 27 | - | |
| 28 | -vi.mock("./util/formatError.js", () => ({ | |
| 29 | - formatError: vi.fn((error) => error.message || String(error)), | |
| 30 | -})); | |
| 31 | - | |
| 32 | -vi.mock("./util/logger.js", () => ({ | |
| 33 | - logger: { | |
| 34 | - info: vi.fn(), | |
| 35 | - debug: vi.fn(), | |
| 36 | - error: vi.fn(), | |
| 37 | - warn: vi.fn(), | |
| 38 | - }, | |
| 39 | -})); | |
| 40 | - | |
| 41 | -vi.mock("os", async (importOriginal) => { | |
| 42 | - const actual = (await importOriginal()) as object; | |
| 43 | - return { | |
| 44 | - ...actual, | |
| 45 | - homedir: vi.fn(() => "/home/test"), | |
| 46 | - }; | |
| 47 | -}); | |
| 48 | - | |
| 49 | -describe("handleAutoCompaction", () => { | |
| 50 | - const mockModel = { | |
| 51 | - provider: "openai", | |
| 52 | - name: "gpt-4", | |
| 53 | - model: "gpt-4", | |
| 54 | - defaultCompletionOptions: { | |
| 55 | - contextLength: 8192, | |
| 56 | - maxTokens: 2048, | |
| 57 | - }, | |
| 58 | - } as any; | |
| 59 | - | |
| 60 | - const mockLlmApi = {} as any; | |
| 61 | - const mockChatHistory: ChatHistoryItem[] = convertToUnifiedHistory([ | |
| 62 | - { role: "system", content: "You are a helpful assistant." }, | |
| 63 | - { role: "user", content: "Hello" }, | |
| 64 | - { role: "assistant", content: "Hi there!" }, | |
| 65 | - ]); | |
| 66 | - | |
| 67 | - beforeEach(() => { | |
| 68 | - vi.clearAllMocks(); | |
| 69 | - }); | |
| 70 | - | |
| 71 | - it("should return original history when auto-compaction is not needed", async () => { | |
| 72 | - const { shouldAutoCompact } = await import("./util/tokenizer.js"); | |
| 73 | - vi.mocked(shouldAutoCompact).mockReturnValue(false); | |
| 74 | - | |
| 75 | - const result = await handleAutoCompaction( | |
| 76 | - mockChatHistory, | |
| 77 | - mockModel, | |
| 78 | - mockLlmApi, | |
| 79 | - {}, | |
| 80 | - ); | |
| 81 | - | |
| 82 | - expect(result).toEqual({ | |
| 83 | - chatHistory: mockChatHistory, | |
| 84 | - compactionIndex: null, | |
| 85 | - wasCompacted: false, | |
| 86 | - }); | |
| 87 | - | |
| 88 | - expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 89 | - }); | |
| 90 | - | |
| 91 | - it("should perform auto-compaction when context limit is approaching", async () => { | |
| 92 | - const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 93 | - "./util/tokenizer.js" | |
| 94 | - ); | |
| 95 | - const { compactChatHistory } = await import("./compaction.js"); | |
| 96 | - const { updateSessionHistory } = await import("./session.js"); | |
| 97 | - | |
| 98 | - vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 99 | - vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 100 | - | |
| 101 | - const mockCompactionResult = { | |
| 102 | - compactedHistory: convertToUnifiedHistory([ | |
| 103 | - { | |
| 104 | - role: "system", | |
| 105 | - content: "You are a helpful assistant.", | |
| 106 | - }, | |
| 107 | - { | |
| 108 | - role: "assistant", | |
| 109 | - content: "[COMPACTED HISTORY]\nConversation summary...", | |
| 110 | - }, | |
| 111 | - ]), | |
| 112 | - compactionIndex: 1, | |
| 113 | - compactionContent: "Conversation summary...", | |
| 114 | - }; | |
| 115 | - | |
| 116 | - vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); | |
| 117 | - | |
| 118 | - const mockCallbacks = { | |
| 119 | - onSystemMessage: vi.fn(), | |
| 120 | - }; | |
| 121 | - | |
| 122 | - const result = await handleAutoCompaction( | |
| 123 | - mockChatHistory, | |
| 124 | - mockModel, | |
| 125 | - mockLlmApi, | |
| 126 | - { | |
| 127 | - isHeadless: false, | |
| 128 | - callbacks: mockCallbacks, | |
| 129 | - }, | |
| 130 | - ); | |
| 131 | - | |
| 132 | - expect(shouldAutoCompact).toHaveBeenCalledWith(mockChatHistory, mockModel); | |
| 133 | - expect(getAutoCompactMessage).toHaveBeenCalledWith(mockModel); | |
| 134 | - expect(compactChatHistory).toHaveBeenCalledWith( | |
| 135 | - mockChatHistory, | |
| 136 | - mockModel, | |
| 137 | - mockLlmApi, | |
| 138 | - expect.any(Object), | |
| 139 | - ); | |
| 140 | - expect(updateSessionHistory).toHaveBeenCalledWith( | |
| 141 | - mockCompactionResult.compactedHistory, | |
| 142 | - ); | |
| 143 | - | |
| 144 | - expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 145 | - "Auto-compacting...", | |
| 146 | - ); | |
| 147 | - expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 148 | - "✓ Chat history auto-compacted successfully.", | |
| 149 | - ); | |
| 150 | - | |
| 151 | - expect(result).toEqual({ | |
| 152 | - chatHistory: mockCompactionResult.compactedHistory, | |
| 153 | - compactionIndex: mockCompactionResult.compactionIndex, | |
| 154 | - wasCompacted: true, | |
| 155 | - }); | |
| 156 | - }); | |
| 157 | - | |
| 158 | - it("should handle compaction errors gracefully", async () => { | |
| 159 | - const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 160 | - "./util/tokenizer.js" | |
| 161 | - ); | |
| 162 | - const { compactChatHistory } = await import("./compaction.js"); | |
| 163 | - const { logger } = await import("./util/logger.js"); | |
| 164 | - | |
| 165 | - vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 166 | - vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 167 | - vi.mocked(compactChatHistory).mockRejectedValue( | |
| 168 | - new Error("Compaction failed"), | |
| 169 | - ); | |
| 170 | - | |
| 171 | - const mockCallbacks = { | |
| 172 | - onSystemMessage: vi.fn(), | |
| 173 | - }; | |
| 174 | - | |
| 175 | - const result = await handleAutoCompaction( | |
| 176 | - mockChatHistory, | |
| 177 | - mockModel, | |
| 178 | - mockLlmApi, | |
| 179 | - { | |
| 180 | - isHeadless: false, | |
| 181 | - callbacks: mockCallbacks, | |
| 182 | - }, | |
| 183 | - ); | |
| 184 | - | |
| 185 | - expect(logger.error).toHaveBeenCalledWith( | |
| 186 | - expect.stringContaining("Auto-compaction error"), | |
| 187 | - ); | |
| 188 | - expect(mockCallbacks.onSystemMessage).toHaveBeenCalledWith( | |
| 189 | - expect.stringContaining("Warning: Auto-compaction error"), | |
| 190 | - ); | |
| 191 | - | |
| 192 | - // Should return original history on error | |
| 193 | - expect(result.wasCompacted).toBe(false); | |
| 194 | - expect(result).toEqual({ | |
| 195 | - chatHistory: mockChatHistory, | |
| 196 | - compactionIndex: null, | |
| 197 | - wasCompacted: false, | |
| 198 | - }); | |
| 199 | - }); | |
| 200 | - | |
| 201 | - it("should not call system message callback in headless mode", async () => { | |
| 202 | - const { shouldAutoCompact, getAutoCompactMessage } = await import( | |
| 203 | - "./util/tokenizer.js" | |
| 204 | - ); | |
| 205 | - const { compactChatHistory } = await import("./compaction.js"); | |
| 206 | - | |
| 207 | - vi.mocked(shouldAutoCompact).mockReturnValue(true); | |
| 208 | - vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); | |
| 209 | - | |
| 210 | - const mockCompactionResult = { | |
| 211 | - compactedHistory: convertToUnifiedHistory([ | |
| 212 | - { role: "system", content: "System" }, | |
| 213 | - ]), | |
| 214 | - compactionIndex: 0, | |
| 215 | - compactionContent: "Summary", | |
| 216 | - }; | |
| 217 | - | |
| 218 | - vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); | |
| 219 | - | |
| 220 | - const mockCallbacks = { | |
| 221 | - onSystemMessage: vi.fn(), | |
| 222 | - }; | |
| 223 | - | |
| 224 | - await handleAutoCompaction(mockChatHistory, mockModel, mockLlmApi, { | |
| 225 | - isHeadless: true, | |
| 226 | - callbacks: mockCallbacks, | |
| 227 | - }); | |
| 228 | - | |
| 229 | - expect(mockCallbacks.onSystemMessage).not.toHaveBeenCalled(); | |
| 230 | - }); | |
| 231 | - | |
| 232 | - it("should handle missing model gracefully", async () => { | |
| 233 | - const result = await handleAutoCompaction( | |
| 234 | - mockChatHistory, | |
| 235 | - null as any, | |
| 236 | - mockLlmApi, | |
| 237 | - {}, | |
| 238 | - ); | |
| 239 | - | |
| 240 | - expect(result).toEqual({ | |
| 241 | - chatHistory: mockChatHistory, | |
| 242 | - compactionIndex: null, | |
| 243 | - wasCompacted: false, | |
| 244 | - }); | |
| 245 | - }); | |
| 246 | -}); |
deleted extensions/cli/src/streamChatResponse.autoCompaction.ts +0 −176
| @@ -1,176 +0,0 @@ | ||
| 1 | -import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | -import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | -import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | -import React from "react"; | |
| 5 | - | |
| 6 | -import { compactChatHistory } from "./compaction.js"; | |
| 7 | -import { updateSessionHistory } from "./session.js"; | |
| 8 | -import { formatError } from "./util/formatError.js"; | |
| 9 | -import { logger } from "./util/logger.js"; | |
| 10 | -import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js"; | |
| 11 | - | |
| 12 | -interface AutoCompactionCallbacks { | |
| 13 | - // For streaming mode | |
| 14 | - onSystemMessage?: (message: string) => void; | |
| 15 | - onContent?: (content: string) => void; | |
| 16 | - | |
| 17 | - // For TUI mode | |
| 18 | - setMessages?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 19 | - setChatHistory?: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; | |
| 20 | - setCompactionIndex?: React.Dispatch<React.SetStateAction<number | null>>; | |
| 21 | - | |
| 22 | - // For headless mode - no callbacks needed, just return values | |
| 23 | -} | |
| 24 | - | |
| 25 | -interface AutoCompactionOptions { | |
| 26 | - isHeadless?: boolean; | |
| 27 | - format?: "json"; | |
| 28 | - callbacks?: AutoCompactionCallbacks; | |
| 29 | -} | |
| 30 | - | |
| 31 | -/** | |
| 32 | - * Notify user about compaction start | |
| 33 | - */ | |
| 34 | -function notifyCompactionStart( | |
| 35 | - message: string, | |
| 36 | - isHeadless: boolean, | |
| 37 | - callbacks?: AutoCompactionCallbacks, | |
| 38 | -) { | |
| 39 | - if (isHeadless) return; | |
| 40 | - | |
| 41 | - if (callbacks?.onSystemMessage) { | |
| 42 | - callbacks.onSystemMessage(message); | |
| 43 | - } else if (callbacks?.setMessages) { | |
| 44 | - // TUI mode - handled by caller | |
| 45 | - } | |
| 46 | -} | |
| 47 | - | |
| 48 | -/** | |
| 49 | - * Handle successful compaction state updates | |
| 50 | - */ | |
| 51 | -function handleCompactionSuccess( | |
| 52 | - result: any, | |
| 53 | - isHeadless: boolean, | |
| 54 | - callbacks?: AutoCompactionCallbacks, | |
| 55 | -) { | |
| 56 | - if (isHeadless) return; | |
| 57 | - | |
| 58 | - const successMessage = "✓ Chat history auto-compacted successfully."; | |
| 59 | - | |
| 60 | - if (callbacks?.onSystemMessage) { | |
| 61 | - callbacks.onSystemMessage(successMessage); | |
| 62 | - } else if ( | |
| 63 | - callbacks?.setMessages && | |
| 64 | - callbacks?.setChatHistory && | |
| 65 | - callbacks?.setCompactionIndex | |
| 66 | - ) { | |
| 67 | - callbacks.setChatHistory(result.compactedHistory); | |
| 68 | - callbacks.setCompactionIndex(result.compactionIndex); | |
| 69 | - callbacks.setMessages((prev: ChatHistoryItem[]) => [ | |
| 70 | - ...prev, | |
| 71 | - { | |
| 72 | - message: { | |
| 73 | - role: "system", | |
| 74 | - content: successMessage, | |
| 75 | - }, | |
| 76 | - contextItems: [], | |
| 77 | - }, | |
| 78 | - ]); | |
| 79 | - } | |
| 80 | -} | |
| 81 | - | |
| 82 | -/** | |
| 83 | - * Handle compaction error notification | |
| 84 | - */ | |
| 85 | -function handleCompactionError( | |
| 86 | - error: any, | |
| 87 | - isHeadless: boolean, | |
| 88 | - callbacks?: AutoCompactionCallbacks, | |
| 89 | -) { | |
| 90 | - const errorMessage = `Auto-compaction error: ${formatError(error)}`; | |
| 91 | - logger.error(errorMessage); | |
| 92 | - | |
| 93 | - if (isHeadless) return; | |
| 94 | - | |
| 95 | - const warningMessage = `Warning: ${errorMessage}. Continuing without compaction...`; | |
| 96 | - | |
| 97 | - if (callbacks?.onSystemMessage) { | |
| 98 | - callbacks.onSystemMessage(warningMessage); | |
| 99 | - } else if (callbacks?.setMessages) { | |
| 100 | - callbacks.setMessages((prev: ChatHistoryItem[]) => [ | |
| 101 | - ...prev, | |
| 102 | - { | |
| 103 | - message: { | |
| 104 | - role: "system", | |
| 105 | - content: warningMessage, | |
| 106 | - }, | |
| 107 | - contextItems: [], | |
| 108 | - }, | |
| 109 | - ]); | |
| 110 | - } | |
| 111 | -} | |
| 112 | - | |
| 113 | -/** | |
| 114 | - * Unified auto-compaction handler for all modes (streaming, TUI, headless) | |
| 115 | - * @param chatHistory Current chat history | |
| 116 | - * @param model Model configuration | |
| 117 | - * @param llmApi LLM API instance | |
| 118 | - * @param options Configuration options for different usage contexts | |
| 119 | - * @returns Updated chat history and compaction index, or original if no compaction needed | |
| 120 | - */ | |
| 121 | -export async function handleAutoCompaction( | |
| 122 | - chatHistory: ChatHistoryItem[], | |
| 123 | - model: ModelConfig, | |
| 124 | - llmApi: BaseLlmApi, | |
| 125 | - options: AutoCompactionOptions = {}, | |
| 126 | -): Promise<{ | |
| 127 | - chatHistory: ChatHistoryItem[]; | |
| 128 | - compactionIndex: number | null; | |
| 129 | - wasCompacted: boolean; | |
| 130 | -}> { | |
| 131 | - const { isHeadless = false, callbacks } = options; | |
| 132 | - | |
| 133 | - if (!model || !shouldAutoCompact(chatHistory, model)) { | |
| 134 | - return { chatHistory, compactionIndex: null, wasCompacted: false }; | |
| 135 | - } | |
| 136 | - | |
| 137 | - logger.info( | |
| 138 | - `Auto-compaction triggered${isHeadless ? " in headless mode" : ""}`, | |
| 139 | - ); | |
| 140 | - | |
| 141 | - // Notify about compaction start | |
| 142 | - notifyCompactionStart(getAutoCompactMessage(model), isHeadless, callbacks); | |
| 143 | - | |
| 144 | - try { | |
| 145 | - // Compact the history | |
| 146 | - const result = await compactChatHistory( | |
| 147 | - chatHistory, | |
| 148 | - model, | |
| 149 | - llmApi, | |
| 150 | - isHeadless | |
| 151 | - ? undefined | |
| 152 | - : { | |
| 153 | - onStreamContent: callbacks?.onContent, | |
| 154 | - onStreamComplete: () => {}, | |
| 155 | - }, | |
| 156 | - ); | |
| 157 | - | |
| 158 | - // Save the compacted session | |
| 159 | - updateSessionHistory(result.compactedHistory); | |
| 160 | - | |
| 161 | - // Handle success notification | |
| 162 | - handleCompactionSuccess(result, isHeadless, callbacks); | |
| 163 | - | |
| 164 | - return { | |
| 165 | - chatHistory: result.compactedHistory, | |
| 166 | - compactionIndex: result.compactionIndex, | |
| 167 | - wasCompacted: true, | |
| 168 | - }; | |
| 169 | - } catch (error: any) { | |
| 170 | - // Handle error notification | |
| 171 | - handleCompactionError(error, isHeadless, callbacks); | |
| 172 | - | |
| 173 | - // Continue without compaction on error | |
| 174 | - return { chatHistory, compactionIndex: null, wasCompacted: false }; | |
| 175 | - } | |
| 176 | -} |
deleted extensions/cli/src/streamChatResponse.getAllTools.test.ts +0 −171
| @@ -1,171 +0,0 @@ | ||
| 1 | -import { describe, expect, test } from "vitest"; | |
| 2 | - | |
| 3 | -import { | |
| 4 | - getServiceSync, | |
| 5 | - initializeServices, | |
| 6 | - SERVICE_NAMES, | |
| 7 | - serviceContainer, | |
| 8 | -} from "./services/index.js"; | |
| 9 | -import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; | |
| 10 | -import { getAllTools } from "./streamChatResponse.js"; | |
| 11 | - | |
| 12 | -describe("getAllTools - Tool Filtering", () => { | |
| 13 | - beforeEach(() => { | |
| 14 | - // Clean up service container state before each test | |
| 15 | - const services = [ | |
| 16 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 17 | - SERVICE_NAMES.AUTH, | |
| 18 | - SERVICE_NAMES.API_CLIENT, | |
| 19 | - SERVICE_NAMES.CONFIG, | |
| 20 | - SERVICE_NAMES.MODEL, | |
| 21 | - SERVICE_NAMES.MCP, | |
| 22 | - ]; | |
| 23 | - | |
| 24 | - services.forEach((service) => { | |
| 25 | - // Reset service state | |
| 26 | - (serviceContainer as any).services.delete(service); | |
| 27 | - (serviceContainer as any).factories.delete(service); | |
| 28 | - (serviceContainer as any).dependencies.delete(service); | |
| 29 | - }); | |
| 30 | - }); | |
| 31 | - | |
| 32 | - test("should exclude Bash tool in plan mode after service initialization", async () => { | |
| 33 | - // Initialize services in plan mode (simulating `cn -p`) | |
| 34 | - await initializeServices({ | |
| 35 | - headless: true, | |
| 36 | - toolPermissionOverrides: { | |
| 37 | - mode: "plan", | |
| 38 | - }, | |
| 39 | - }); | |
| 40 | - | |
| 41 | - // Verify service is ready | |
| 42 | - const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 43 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 44 | - ); | |
| 45 | - expect(serviceResult.state).toBe("ready"); | |
| 46 | - expect(serviceResult.value?.currentMode).toBe("plan"); | |
| 47 | - | |
| 48 | - // Get available tools - this should include Bash in plan mode | |
| 49 | - const tools = await getAllTools(); | |
| 50 | - const toolNames = tools.map((t) => t.function.name); | |
| 51 | - | |
| 52 | - // Bash should be allowed in plan mode | |
| 53 | - expect(toolNames).toContain("Bash"); | |
| 54 | - | |
| 55 | - // Read-only tools should still be available | |
| 56 | - expect(toolNames).toContain("Read"); | |
| 57 | - expect(toolNames).toContain("List"); | |
| 58 | - expect(toolNames).toContain("Search"); | |
| 59 | - expect(toolNames).toContain("Fetch"); | |
| 60 | - expect(toolNames).toContain("Checklist"); | |
| 61 | - | |
| 62 | - // Write tools should be excluded | |
| 63 | - expect(toolNames).not.toContain("Write"); | |
| 64 | - expect(toolNames).not.toContain("Edit"); | |
| 65 | - }); | |
| 66 | - | |
| 67 | - test("should include Bash tool in normal mode", async () => { | |
| 68 | - // Initialize services in normal mode | |
| 69 | - await initializeServices({ | |
| 70 | - headless: true, | |
| 71 | - toolPermissionOverrides: { | |
| 72 | - mode: "normal", | |
| 73 | - }, | |
| 74 | - }); | |
| 75 | - | |
| 76 | - // Verify service is ready | |
| 77 | - const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 78 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 79 | - ); | |
| 80 | - expect(serviceResult.state).toBe("ready"); | |
| 81 | - expect(serviceResult.value?.currentMode).toBe("normal"); | |
| 82 | - | |
| 83 | - // Get available tools - Bash should be available in normal mode | |
| 84 | - const tools = await getAllTools(); | |
| 85 | - const toolNames = tools.map((t) => t.function.name); | |
| 86 | - | |
| 87 | - // All tools should be available in normal mode | |
| 88 | - expect(toolNames).toContain("Bash"); | |
| 89 | - expect(toolNames).toContain("Read"); | |
| 90 | - expect(toolNames).toContain("Write"); | |
| 91 | - expect(toolNames).toContain("Edit"); | |
| 92 | - }); | |
| 93 | - | |
| 94 | - test("should include all tools in auto mode", async () => { | |
| 95 | - // Initialize services in auto mode | |
| 96 | - await initializeServices({ | |
| 97 | - headless: true, | |
| 98 | - toolPermissionOverrides: { | |
| 99 | - mode: "auto", | |
| 100 | - }, | |
| 101 | - }); | |
| 102 | - | |
| 103 | - // Verify service is ready | |
| 104 | - const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 105 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 106 | - ); | |
| 107 | - expect(serviceResult.state).toBe("ready"); | |
| 108 | - expect(serviceResult.value?.currentMode).toBe("auto"); | |
| 109 | - | |
| 110 | - // Get available tools - all tools should be available in auto mode | |
| 111 | - const tools = await getAllTools(); | |
| 112 | - const toolNames = tools.map((t) => t.function.name); | |
| 113 | - | |
| 114 | - // All tools should be available in auto mode | |
| 115 | - expect(toolNames).toContain("Bash"); | |
| 116 | - expect(toolNames).toContain("Read"); | |
| 117 | - expect(toolNames).toContain("Write"); | |
| 118 | - expect(toolNames).toContain("Edit"); | |
| 119 | - }); | |
| 120 | - | |
| 121 | - test("should respect explicit exclude in normal mode", async () => { | |
| 122 | - // Initialize services in normal mode with Read tool explicitly excluded | |
| 123 | - await initializeServices({ | |
| 124 | - headless: true, | |
| 125 | - toolPermissionOverrides: { | |
| 126 | - mode: "normal", | |
| 127 | - exclude: ["Read"], | |
| 128 | - }, | |
| 129 | - }); | |
| 130 | - | |
| 131 | - const tools = await getAllTools(); | |
| 132 | - const toolNames = tools.map((t) => t.function.name); | |
| 133 | - | |
| 134 | - // Read should be excluded due to explicit exclude | |
| 135 | - expect(toolNames).not.toContain("Read"); | |
| 136 | - | |
| 137 | - // Other tools should still be available in normal mode | |
| 138 | - expect(toolNames).toContain("Bash"); | |
| 139 | - expect(toolNames).toContain("Write"); | |
| 140 | - expect(toolNames).toContain("List"); | |
| 141 | - expect(toolNames).toContain("Search"); | |
| 142 | - }); | |
| 143 | - | |
| 144 | - test("plan mode should override allow flags (regression test for GitHub Actions issue)", async () => { | |
| 145 | - // This test specifically addresses the original issue where plan mode | |
| 146 | - // wasn't properly excluding tools despite being in plan mode | |
| 147 | - await initializeServices({ | |
| 148 | - headless: true, | |
| 149 | - toolPermissionOverrides: { | |
| 150 | - mode: "plan", | |
| 151 | - allow: ["Write", "Edit"], // These should be ignored in plan mode | |
| 152 | - }, | |
| 153 | - }); | |
| 154 | - | |
| 155 | - const tools = await getAllTools(); | |
| 156 | - const toolNames = tools.map((t) => t.function.name); | |
| 157 | - | |
| 158 | - // Plan mode should still exclude write tools despite --allow flags | |
| 159 | - // This tests that plan mode policies have absolute precedence | |
| 160 | - expect(toolNames).not.toContain("Write"); | |
| 161 | - expect(toolNames).not.toContain("Edit"); | |
| 162 | - | |
| 163 | - // Bash should be available in plan mode | |
| 164 | - expect(toolNames).toContain("Bash"); | |
| 165 | - | |
| 166 | - // Read-only tools should be available | |
| 167 | - expect(toolNames).toContain("Read"); | |
| 168 | - expect(toolNames).toContain("List"); | |
| 169 | - expect(toolNames).toContain("Search"); | |
| 170 | - }); | |
| 171 | -}); |
deleted extensions/cli/src/streamChatResponse.helpers.ts +0 −454
| @@ -1,454 +0,0 @@ | ||
| 1 | -// Helper functions extracted from streamChatResponse.ts to reduce file size | |
| 2 | - | |
| 3 | -import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; | |
| 4 | - | |
| 5 | -import { checkToolPermission } from "./permissions/permissionChecker.js"; | |
| 6 | -import { toolPermissionManager } from "./permissions/permissionManager.js"; | |
| 7 | -import { ToolCallRequest } from "./permissions/types.js"; | |
| 8 | -import { StreamCallbacks } from "./streamChatResponse.types.js"; | |
| 9 | -import { telemetryService } from "./telemetry/telemetryService.js"; | |
| 10 | -import { calculateTokenCost } from "./telemetry/utils.js"; | |
| 11 | -import { | |
| 12 | - executeToolCall, | |
| 13 | - getAllBuiltinTools, | |
| 14 | - getAvailableTools, | |
| 15 | - Tool, | |
| 16 | - validateToolCallArgsPresent, | |
| 17 | -} from "./tools/index.js"; | |
| 18 | -import { PreprocessedToolCall, ToolCall } from "./tools/types.js"; | |
| 19 | -import { logger } from "./util/logger.js"; | |
| 20 | - | |
| 21 | -// Helper function to handle permission denied | |
| 22 | -export function handlePermissionDenied( | |
| 23 | - toolCall: PreprocessedToolCall, | |
| 24 | - chatHistoryEntries: ChatCompletionToolMessageParam[], | |
| 25 | - callbacks?: StreamCallbacks, | |
| 26 | -): void { | |
| 27 | - const deniedMessage = `Permission denied by user`; | |
| 28 | - logger.info("Tool call denied", { | |
| 29 | - name: toolCall.name, | |
| 30 | - arguments: toolCall.arguments, | |
| 31 | - }); | |
| 32 | - | |
| 33 | - chatHistoryEntries.push({ | |
| 34 | - role: "tool", | |
| 35 | - tool_call_id: toolCall.id, | |
| 36 | - content: deniedMessage, | |
| 37 | - }); | |
| 38 | - | |
| 39 | - callbacks?.onToolResult?.(deniedMessage, toolCall.name, "canceled"); | |
| 40 | - logger.debug("Tool call rejected - stopping stream"); | |
| 41 | -} | |
| 42 | - | |
| 43 | -// Helper function to handle headless mode permission | |
| 44 | -export function handleHeadlessPermission( | |
| 45 | - toolCall: PreprocessedToolCall, | |
| 46 | -): never { | |
| 47 | - const allBuiltinTools = getAllBuiltinTools(); | |
| 48 | - const tool = allBuiltinTools.find((t) => t.name === toolCall.name); | |
| 49 | - const toolName = tool?.displayName || toolCall.name; | |
| 50 | - | |
| 51 | - console.error( | |
| 52 | - `Error: Tool '${toolName}' requires permission but cn is running in headless mode.`, | |
| 53 | - ); | |
| 54 | - console.error(`If you want to allow this tool, use --allow ${toolName}.`); | |
| 55 | - console.error( | |
| 56 | - `If you don't want the tool to be included, use --exclude ${toolName}.`, | |
| 57 | - ); | |
| 58 | - | |
| 59 | - process.exit(1); | |
| 60 | -} | |
| 61 | - | |
| 62 | -// Helper function to request user permission | |
| 63 | -export async function requestUserPermission( | |
| 64 | - toolCall: PreprocessedToolCall, | |
| 65 | - callbacks?: StreamCallbacks, | |
| 66 | -): Promise<boolean> { | |
| 67 | - if (!callbacks?.onToolPermissionRequest) { | |
| 68 | - return false; | |
| 69 | - } | |
| 70 | - | |
| 71 | - const toolCallRequest: ToolCallRequest = { | |
| 72 | - name: toolCall.name, | |
| 73 | - arguments: toolCall.preprocessResult?.args ?? toolCall.arguments, | |
| 74 | - preview: toolCall.preprocessResult?.preview, | |
| 75 | - }; | |
| 76 | - | |
| 77 | - // Set up listener for permissionRequested event | |
| 78 | - const handlePermissionRequested = (event: { | |
| 79 | - requestId: string; | |
| 80 | - toolCall: ToolCallRequest; | |
| 81 | - }) => { | |
| 82 | - if (event.toolCall.name === toolCall.name) { | |
| 83 | - toolPermissionManager.off( | |
| 84 | - "permissionRequested", | |
| 85 | - handlePermissionRequested, | |
| 86 | - ); | |
| 87 | - // Notify UI about permission request | |
| 88 | - callbacks.onToolPermissionRequest!( | |
| 89 | - event.toolCall.name, | |
| 90 | - event.toolCall.arguments, | |
| 91 | - event.requestId, | |
| 92 | - event.toolCall.preview, | |
| 93 | - ); | |
| 94 | - } | |
| 95 | - }; | |
| 96 | - | |
| 97 | - toolPermissionManager.on("permissionRequested", handlePermissionRequested); | |
| 98 | - | |
| 99 | - // Request permission using the proper API | |
| 100 | - const permissionResult = | |
| 101 | - await toolPermissionManager.requestPermission(toolCallRequest); | |
| 102 | - | |
| 103 | - // Clean up listener in case the condition above was never met | |
| 104 | - // This is a safety net to ensure no listeners are left behind | |
| 105 | - toolPermissionManager.off("permissionRequested", handlePermissionRequested); | |
| 106 | - | |
| 107 | - return permissionResult.approved; | |
| 108 | -} | |
| 109 | - | |
| 110 | -// Helper function to check if tool permission is needed | |
| 111 | -export async function checkToolPermissionApproval( | |
| 112 | - toolCall: PreprocessedToolCall, | |
| 113 | - callbacks?: StreamCallbacks, | |
| 114 | - isHeadless?: boolean, | |
| 115 | -): Promise<boolean> { | |
| 116 | - const permissionCheck = checkToolPermission(toolCall); | |
| 117 | - | |
| 118 | - if (permissionCheck.permission === "allow") { | |
| 119 | - return true; | |
| 120 | - } else if (permissionCheck.permission === "ask") { | |
| 121 | - if (isHeadless) { | |
| 122 | - handleHeadlessPermission(toolCall); | |
| 123 | - } | |
| 124 | - return await requestUserPermission(toolCall, callbacks); | |
| 125 | - } else if (permissionCheck.permission === "exclude") { | |
| 126 | - // This shouldn't happen as excluded tools are filtered out earlier | |
| 127 | - return false; | |
| 128 | - } | |
| 129 | - | |
| 130 | - return false; | |
| 131 | -} | |
| 132 | - | |
| 133 | -// Helper function to track first token time | |
| 134 | -export function trackFirstTokenTime( | |
| 135 | - firstTokenTime: number | null, | |
| 136 | - chunk: any, | |
| 137 | - requestStartTime: number, | |
| 138 | - model: any, | |
| 139 | - tools?: any[], | |
| 140 | -): number | null { | |
| 141 | - if ( | |
| 142 | - firstTokenTime === null && | |
| 143 | - chunk.choices?.[0]?.delta && | |
| 144 | - (chunk.choices[0].delta.content || chunk.choices[0].delta.tool_calls) | |
| 145 | - ) { | |
| 146 | - const tokenTime = Date.now(); | |
| 147 | - telemetryService.recordResponseTime( | |
| 148 | - tokenTime - requestStartTime, | |
| 149 | - model.model, | |
| 150 | - "time_to_first_token", | |
| 151 | - (tools?.length || 0) > 0, | |
| 152 | - ); | |
| 153 | - return tokenTime; | |
| 154 | - } | |
| 155 | - return firstTokenTime; | |
| 156 | -} | |
| 157 | - | |
| 158 | -// Helper function to process content from a chunk | |
| 159 | -export function processChunkContent( | |
| 160 | - content: string, | |
| 161 | - aiResponse: string, | |
| 162 | - callbacks?: StreamCallbacks, | |
| 163 | - isHeadless?: boolean, | |
| 164 | -): string { | |
| 165 | - const updatedResponse = aiResponse + content; | |
| 166 | - | |
| 167 | - if (callbacks?.onContent) { | |
| 168 | - callbacks.onContent(content); | |
| 169 | - } else if (!isHeadless) { | |
| 170 | - process.stdout.write(content); | |
| 171 | - } | |
| 172 | - | |
| 173 | - return updatedResponse; | |
| 174 | -} | |
| 175 | - | |
| 176 | -// Helper function to handle tool call delta | |
| 177 | -export function processToolCallDelta( | |
| 178 | - toolCallDelta: any, | |
| 179 | - toolCallsMap: Map<string, ToolCall>, | |
| 180 | - indexToIdMap: Map<number, string>, | |
| 181 | -): void { | |
| 182 | - let toolCallId: string | undefined; | |
| 183 | - | |
| 184 | - // If we have an ID, use it and map the index | |
| 185 | - if (toolCallDelta.id) { | |
| 186 | - toolCallId = toolCallDelta.id; | |
| 187 | - if (toolCallDelta.index !== undefined && toolCallId) { | |
| 188 | - indexToIdMap.set(toolCallDelta.index, toolCallId); | |
| 189 | - } | |
| 190 | - } else if (toolCallDelta.index !== undefined) { | |
| 191 | - // No ID, but we have an index - look up the ID from our map | |
| 192 | - toolCallId = indexToIdMap.get(toolCallDelta.index); | |
| 193 | - } | |
| 194 | - | |
| 195 | - if (!toolCallId) { | |
| 196 | - logger.warn("Tool call delta without ID or valid index mapping", { | |
| 197 | - toolCallDelta, | |
| 198 | - }); | |
| 199 | - return; | |
| 200 | - } | |
| 201 | - | |
| 202 | - // Create tool call entry if it doesn't exist | |
| 203 | - if (!toolCallsMap.has(toolCallId)) { | |
| 204 | - toolCallsMap.set(toolCallId, { | |
| 205 | - id: toolCallId, | |
| 206 | - name: "", | |
| 207 | - arguments: null, | |
| 208 | - argumentsStr: "", | |
| 209 | - startNotified: false, | |
| 210 | - }); | |
| 211 | - } | |
| 212 | - | |
| 213 | - const toolCall = toolCallsMap.get(toolCallId); | |
| 214 | - if (!toolCall) { | |
| 215 | - logger.warn("Tool call not found in map", { toolCallId }); | |
| 216 | - return; | |
| 217 | - } | |
| 218 | - | |
| 219 | - // Update name | |
| 220 | - if (toolCallDelta.function?.name) { | |
| 221 | - toolCall.name = toolCallDelta.function.name; | |
| 222 | - } | |
| 223 | - | |
| 224 | - // Accumulate arguments | |
| 225 | - if (toolCallDelta.function?.arguments) { | |
| 226 | - toolCall.argumentsStr += toolCallDelta.function.arguments; | |
| 227 | - | |
| 228 | - // Try to parse when we might have complete JSON | |
| 229 | - try { | |
| 230 | - toolCall.arguments = JSON.parse(toolCall.argumentsStr); | |
| 231 | - toolCall.startNotified = true; | |
| 232 | - } catch { | |
| 233 | - // JSON not complete yet, continue | |
| 234 | - } | |
| 235 | - } | |
| 236 | -} | |
| 237 | - | |
| 238 | -// Helper function to record telemetry | |
| 239 | -export function recordStreamTelemetry(options: { | |
| 240 | - requestStartTime: number; | |
| 241 | - responseEndTime: number; | |
| 242 | - inputTokens: number; | |
| 243 | - outputTokens: number; | |
| 244 | - model: any; | |
| 245 | - tools?: any[]; | |
| 246 | -}): number { | |
| 247 | - const { | |
| 248 | - requestStartTime, | |
| 249 | - responseEndTime, | |
| 250 | - inputTokens, | |
| 251 | - outputTokens, | |
| 252 | - model, | |
| 253 | - tools, | |
| 254 | - } = options; | |
| 255 | - const totalDuration = responseEndTime - requestStartTime; | |
| 256 | - const cost = calculateTokenCost(inputTokens, outputTokens, model.model); | |
| 257 | - | |
| 258 | - telemetryService.recordTokenUsage(inputTokens, "input", model.model); | |
| 259 | - telemetryService.recordTokenUsage(outputTokens, "output", model.model); | |
| 260 | - telemetryService.recordCost(cost, model.model); | |
| 261 | - | |
| 262 | - telemetryService.recordResponseTime( | |
| 263 | - totalDuration, | |
| 264 | - model.model, | |
| 265 | - "total_response_time", | |
| 266 | - (tools?.length || 0) > 0, | |
| 267 | - ); | |
| 268 | - | |
| 269 | - telemetryService.logApiRequest({ | |
| 270 | - model: model.model, | |
| 271 | - durationMs: totalDuration, | |
| 272 | - success: true, | |
| 273 | - inputTokens, | |
| 274 | - outputTokens, | |
| 275 | - costUsd: cost, | |
| 276 | - }); | |
| 277 | - | |
| 278 | - return cost; | |
| 279 | -} | |
| 280 | - | |
| 281 | -/** | |
| 282 | - * Processes tool calls by validating and preprocessing them | |
| 283 | - * @param toolCalls - The raw tool calls from the LLM | |
| 284 | - * @param callbacks - Optional callbacks for notifying of events | |
| 285 | - * @returns - Preprocessed tool calls that are ready for execution | |
| 286 | - */ | |
| 287 | -export async function preprocessStreamedToolCalls( | |
| 288 | - toolCalls: ToolCall[], | |
| 289 | - callbacks?: StreamCallbacks, | |
| 290 | -): Promise<{ | |
| 291 | - preprocessedCalls: PreprocessedToolCall[]; | |
| 292 | - errorChatEntries: ChatCompletionToolMessageParam[]; | |
| 293 | -}> { | |
| 294 | - const preprocessedCalls: PreprocessedToolCall[] = []; | |
| 295 | - const errorChatEntries: ChatCompletionToolMessageParam[] = []; | |
| 296 | - | |
| 297 | - // Get all available tools | |
| 298 | - const availableTools: Tool[] = await getAvailableTools(); | |
| 299 | - | |
| 300 | - // Process each tool call | |
| 301 | - for (const toolCall of toolCalls) { | |
| 302 | - const startTime = Date.now(); | |
| 303 | - try { | |
| 304 | - const tool = availableTools.find((t) => t.name === toolCall.name); | |
| 305 | - if (!tool) { | |
| 306 | - throw new Error(`Tool ${toolCall.name} not found`); | |
| 307 | - } | |
| 308 | - | |
| 309 | - validateToolCallArgsPresent(toolCall, tool); | |
| 310 | - | |
| 311 | - const preprocessedCall: PreprocessedToolCall = { | |
| 312 | - ...toolCall, | |
| 313 | - tool, | |
| 314 | - }; | |
| 315 | - | |
| 316 | - if (tool.preprocess) { | |
| 317 | - logger.debug("Preprocessing tool call args", { | |
| 318 | - name: toolCall.name, | |
| 319 | - arguments: toolCall.arguments, | |
| 320 | - }); | |
| 321 | - const preprocessed = await tool.preprocess(toolCall.arguments); | |
| 322 | - preprocessedCall.preprocessResult = preprocessed; | |
| 323 | - } | |
| 324 | - | |
| 325 | - preprocessedCalls.push(preprocessedCall); | |
| 326 | - } catch (error) { | |
| 327 | - // Notify the UI about the tool start, even though it failed | |
| 328 | - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 329 | - | |
| 330 | - const errorMessage = | |
| 331 | - error instanceof Error ? error.message : String(error); | |
| 332 | - | |
| 333 | - logger.error("Invalid tool call", { | |
| 334 | - name: toolCall.name, | |
| 335 | - error: errorMessage, | |
| 336 | - }); | |
| 337 | - | |
| 338 | - const duration = Date.now() - startTime; | |
| 339 | - telemetryService.logToolResult({ | |
| 340 | - toolName: toolCall.name, | |
| 341 | - success: false, | |
| 342 | - durationMs: duration, | |
| 343 | - error: errorMessage, | |
| 344 | - }); | |
| 345 | - | |
| 346 | - // Add error to chat history | |
| 347 | - errorChatEntries.push({ | |
| 348 | - role: "tool", | |
| 349 | - tool_call_id: toolCall.id, | |
| 350 | - content: errorMessage, | |
| 351 | - }); | |
| 352 | - | |
| 353 | - // Notify about the error | |
| 354 | - callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 355 | - } | |
| 356 | - } | |
| 357 | - | |
| 358 | - return { preprocessedCalls, errorChatEntries }; | |
| 359 | -} | |
| 360 | - | |
| 361 | -/** | |
| 362 | - * Executes preprocessed tool calls, handling permissions and results | |
| 363 | - * @param preprocessedCalls - The preprocessed tool calls ready for execution | |
| 364 | - * @param callbacks - Optional callbacks for notifying of events | |
| 365 | - * @returns - Chat history entries with tool results | |
| 366 | - */ | |
| 367 | -export async function executeStreamedToolCalls( | |
| 368 | - preprocessedCalls: PreprocessedToolCall[], | |
| 369 | - callbacks?: StreamCallbacks, | |
| 370 | - isHeadless?: boolean, | |
| 371 | -): Promise<{ | |
| 372 | - hasRejection: boolean; | |
| 373 | - chatHistoryEntries: ChatCompletionToolMessageParam[]; | |
| 374 | -}> { | |
| 375 | - const chatHistoryEntries: ChatCompletionToolMessageParam[] = []; | |
| 376 | - let hasRejection = false; | |
| 377 | - | |
| 378 | - // Execute each preprocessed tool call | |
| 379 | - for (const toolCall of preprocessedCalls) { | |
| 380 | - if (hasRejection) { | |
| 381 | - const cancelledMessage = `Cancelled due to previous tool rejection`; | |
| 382 | - chatHistoryEntries.push({ | |
| 383 | - role: "tool", | |
| 384 | - tool_call_id: toolCall.id, | |
| 385 | - content: cancelledMessage, | |
| 386 | - }); | |
| 387 | - | |
| 388 | - callbacks?.onToolResult?.(cancelledMessage, toolCall.name, "canceled"); | |
| 389 | - continue; | |
| 390 | - } | |
| 391 | - | |
| 392 | - // Handle remaining tool calls in this batch to maintain chat history consistency | |
| 393 | - try { | |
| 394 | - logger.debug("Checking tool permissions", { | |
| 395 | - name: toolCall.name, | |
| 396 | - arguments: toolCall.arguments, | |
| 397 | - }); | |
| 398 | - | |
| 399 | - // Notify tool start - before permission check | |
| 400 | - // This ensures the UI shows the tool call even if it's rejected | |
| 401 | - callbacks?.onToolStart?.(toolCall.name, toolCall.arguments); | |
| 402 | - | |
| 403 | - // Check tool permissions using helper | |
| 404 | - const approved = await checkToolPermissionApproval( | |
| 405 | - toolCall, | |
| 406 | - callbacks, | |
| 407 | - isHeadless, | |
| 408 | - ); | |
| 409 | - | |
| 410 | - if (!approved) { | |
| 411 | - handlePermissionDenied(toolCall, chatHistoryEntries, callbacks); | |
| 412 | - hasRejection = true; | |
| 413 | - continue; | |
| 414 | - } | |
| 415 | - | |
| 416 | - logger.debug("Executing tool", { | |
| 417 | - name: toolCall.name, | |
| 418 | - arguments: toolCall.arguments, | |
| 419 | - }); | |
| 420 | - | |
| 421 | - const toolResult = await executeToolCall(toolCall); | |
| 422 | - | |
| 423 | - chatHistoryEntries.push({ | |
| 424 | - role: "tool", | |
| 425 | - tool_call_id: toolCall.id, | |
| 426 | - content: toolResult, | |
| 427 | - }); | |
| 428 | - | |
| 429 | - callbacks?.onToolResult?.(toolResult, toolCall.name, "done"); | |
| 430 | - } catch (error) { | |
| 431 | - const errorMessage = `Error executing tool ${toolCall.name}: ${ | |
| 432 | - error instanceof Error ? error.message : String(error) | |
| 433 | - }`; | |
| 434 | - | |
| 435 | - logger.error("Tool execution failed", { | |
| 436 | - name: toolCall.name, | |
| 437 | - error: errorMessage, | |
| 438 | - }); | |
| 439 | - | |
| 440 | - chatHistoryEntries.push({ | |
| 441 | - role: "tool", | |
| 442 | - tool_call_id: toolCall.id, | |
| 443 | - content: errorMessage, | |
| 444 | - }); | |
| 445 | - | |
| 446 | - callbacks?.onToolError?.(errorMessage, toolCall.name); | |
| 447 | - } | |
| 448 | - } | |
| 449 | - | |
| 450 | - return { | |
| 451 | - hasRejection, | |
| 452 | - chatHistoryEntries, | |
| 453 | - }; | |
| 454 | -} |
deleted extensions/cli/src/streamChatResponse.modeSwitch.test.ts +0 −170
| @@ -1,170 +0,0 @@ | ||
| 1 | -import { describe, expect, test, vi, beforeEach } from "vitest"; | |
| 2 | - | |
| 3 | -import { | |
| 4 | - serviceContainer, | |
| 5 | - SERVICE_NAMES, | |
| 6 | - initializeServices, | |
| 7 | -} from "./services/index.js"; | |
| 8 | -import { modeService } from "./services/ModeService.js"; | |
| 9 | -import { getAllTools } from "./streamChatResponse.js"; | |
| 10 | - | |
| 11 | -describe("streamChatResponse - Mode Switch During Streaming", () => { | |
| 12 | - beforeEach(async () => { | |
| 13 | - // Clean up service container state before each test | |
| 14 | - const services = [ | |
| 15 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 16 | - SERVICE_NAMES.AUTH, | |
| 17 | - SERVICE_NAMES.API_CLIENT, | |
| 18 | - SERVICE_NAMES.CONFIG, | |
| 19 | - SERVICE_NAMES.MODEL, | |
| 20 | - SERVICE_NAMES.MCP, | |
| 21 | - ]; | |
| 22 | - | |
| 23 | - services.forEach((service) => { | |
| 24 | - (serviceContainer as any).services.delete(service); | |
| 25 | - (serviceContainer as any).factories.delete(service); | |
| 26 | - (serviceContainer as any).dependencies.delete(service); | |
| 27 | - }); | |
| 28 | - | |
| 29 | - // Initialize services in normal mode | |
| 30 | - await initializeServices({ | |
| 31 | - headless: true, | |
| 32 | - toolPermissionOverrides: { | |
| 33 | - mode: "normal", | |
| 34 | - }, | |
| 35 | - }); | |
| 36 | - }); | |
| 37 | - | |
| 38 | - test("should recompute tools on each iteration to handle mode switches", async () => { | |
| 39 | - // Start in normal mode | |
| 40 | - let tools = await getAllTools(); | |
| 41 | - let toolNames = tools.map((t) => t.function.name); | |
| 42 | - | |
| 43 | - // Should include write tools in normal mode | |
| 44 | - expect(toolNames).toContain("Write"); | |
| 45 | - expect(toolNames).toContain("Edit"); | |
| 46 | - | |
| 47 | - // Switch to plan mode (simulating Shift+Tab during streaming) | |
| 48 | - modeService.switchMode("plan"); | |
| 49 | - | |
| 50 | - // Update the service container (this is what UserInput.tsx does) | |
| 51 | - const updatedState = modeService.getToolPermissionService().getState(); | |
| 52 | - serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 53 | - | |
| 54 | - // Recompute tools - should now exclude write tools | |
| 55 | - tools = await getAllTools(); | |
| 56 | - toolNames = tools.map((t) => t.function.name); | |
| 57 | - | |
| 58 | - // Should exclude write tools in plan mode | |
| 59 | - expect(toolNames).not.toContain("Write"); | |
| 60 | - expect(toolNames).not.toContain("Edit"); | |
| 61 | - | |
| 62 | - // Should still include read-only tools | |
| 63 | - expect(toolNames).toContain("Read"); | |
| 64 | - expect(toolNames).toContain("Bash"); | |
| 65 | - expect(toolNames).toContain("List"); | |
| 66 | - }); | |
| 67 | - | |
| 68 | - test("getAllTools reflects current mode immediately", async () => { | |
| 69 | - // Start in normal mode | |
| 70 | - expect(modeService.getCurrentMode()).toBe("normal"); | |
| 71 | - let tools = await getAllTools(); | |
| 72 | - expect(tools.map((t) => t.function.name)).toContain("Write"); | |
| 73 | - | |
| 74 | - // Switch to plan mode | |
| 75 | - modeService.switchMode("plan"); | |
| 76 | - let updatedState = modeService.getToolPermissionService().getState(); | |
| 77 | - serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 78 | - expect(modeService.getCurrentMode()).toBe("plan"); | |
| 79 | - | |
| 80 | - // getAllTools should immediately reflect the new mode | |
| 81 | - tools = await getAllTools(); | |
| 82 | - expect(tools.map((t) => t.function.name)).not.toContain("Write"); | |
| 83 | - | |
| 84 | - // Switch to auto mode | |
| 85 | - modeService.switchMode("auto"); | |
| 86 | - updatedState = modeService.getToolPermissionService().getState(); | |
| 87 | - serviceContainer.set(SERVICE_NAMES.TOOL_PERMISSIONS, updatedState); | |
| 88 | - expect(modeService.getCurrentMode()).toBe("auto"); | |
| 89 | - | |
| 90 | - // getAllTools should immediately reflect auto mode (all tools allowed) | |
| 91 | - tools = await getAllTools(); | |
| 92 | - expect(tools.map((t) => t.function.name)).toContain("Write"); | |
| 93 | - expect(tools.map((t) => t.function.name)).toContain("Edit"); | |
| 94 | - expect(tools.map((t) => t.function.name)).toContain("Read"); | |
| 95 | - }); | |
| 96 | - | |
| 97 | - test("demonstrates the fix: no more stale tool lists", async () => { | |
| 98 | - // This test demonstrates that the fix prevents the original race condition | |
| 99 | - | |
| 100 | - // Mock a multi-turn conversation scenario | |
| 101 | - const mockLlmApi = { | |
| 102 | - chatCompletions: { | |
| 103 | - create: vi.fn().mockImplementation(() => { | |
| 104 | - // Return a mock stream that would trigger multiple iterations | |
| 105 | - return { | |
| 106 | - [Symbol.asyncIterator]: async function* () { | |
| 107 | - // First response - content only | |
| 108 | - yield { | |
| 109 | - choices: [ | |
| 110 | - { | |
| 111 | - delta: { content: "I'll help you with that." }, | |
| 112 | - finish_reason: null, | |
| 113 | - }, | |
| 114 | - ], | |
| 115 | - }; | |
| 116 | - | |
| 117 | - // Second response - indicates tool calls coming | |
| 118 | - yield { | |
| 119 | - choices: [ | |
| 120 | - { | |
| 121 | - delta: { | |
| 122 | - tool_calls: [ | |
| 123 | - { | |
| 124 | - index: 0, | |
| 125 | - id: "call_1", | |
| 126 | - function: { | |
| 127 | - name: "Read", | |
| 128 | - arguments: '{"filepath": "test.txt"}', | |
| 129 | - }, | |
| 130 | - }, | |
| 131 | - ], | |
| 132 | - }, | |
| 133 | - finish_reason: null, | |
| 134 | - }, | |
| 135 | - ], | |
| 136 | - }; | |
| 137 | - | |
| 138 | - // Final response | |
| 139 | - yield { | |
| 140 | - choices: [ | |
| 141 | - { | |
| 142 | - delta: {}, | |
| 143 | - finish_reason: "tool_calls", | |
| 144 | - }, | |
| 145 | - ], | |
| 146 | - }; | |
| 147 | - }, | |
| 148 | - }; | |
| 149 | - }), | |
| 150 | - }, | |
| 151 | - }; | |
| 152 | - | |
| 153 | - const mockModel = { | |
| 154 | - model: "gpt-4", | |
| 155 | - defaultCompletionOptions: {}, | |
| 156 | - }; | |
| 157 | - | |
| 158 | - const abortController = new AbortController(); | |
| 159 | - | |
| 160 | - // Start in normal mode - tools should include Write | |
| 161 | - const initialTools = await getAllTools(); | |
| 162 | - expect(initialTools.map((t) => t.function.name)).toContain("Write"); | |
| 163 | - | |
| 164 | - // During streaming, if mode switches, subsequent iterations should use new tools | |
| 165 | - // This is now handled by recomputing tools on each iteration | |
| 166 | - | |
| 167 | - // The fix ensures that each call to processStreamingResponse gets fresh tools | |
| 168 | - // based on the current mode, preventing the race condition | |
| 169 | - }); | |
| 170 | -}); |
deleted extensions/cli/src/streamChatResponse.test.ts +0 −697
| @@ -1,697 +0,0 @@ | ||
| 1 | -import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | -import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | -import type { ChatHistoryItem } from "core/index.js"; | |
| 4 | -import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs"; | |
| 5 | -import { vi } from "vitest"; | |
| 6 | - | |
| 7 | -import { toolPermissionManager } from "./permissions/permissionManager.js"; | |
| 8 | -import { | |
| 9 | - preprocessStreamedToolCalls, | |
| 10 | - executeStreamedToolCalls, | |
| 11 | -} from "./streamChatResponse.helpers.js"; | |
| 12 | -import { processStreamingResponse } from "./streamChatResponse.js"; | |
| 13 | -import { ToolCall } from "./tools/index.js"; | |
| 14 | -import { readFileTool } from "./tools/readFile.js"; | |
| 15 | -import { searchCodeTool } from "./tools/searchCode.js"; | |
| 16 | -import { PreprocessedToolCall } from "./tools/types.js"; | |
| 17 | -import { writeFileTool } from "./tools/writeFile.js"; | |
| 18 | - | |
| 19 | -// Test the chunk processing logic that was identified as buggy | |
| 20 | -describe("processStreamingResponse - content preservation", () => { | |
| 21 | - // Mock dependencies | |
| 22 | - let mockLlmApi: BaseLlmApi; | |
| 23 | - let mockAbortController: AbortController; | |
| 24 | - let mockModel: ModelConfig; | |
| 25 | - let chunks: ChatCompletionChunk[]; | |
| 26 | - let chatHistory: ChatHistoryItem[]; | |
| 27 | - | |
| 28 | - // Helper to create a content chunk | |
| 29 | - function contentChunk(content: string): ChatCompletionChunk { | |
| 30 | - return { | |
| 31 | - id: "test", | |
| 32 | - object: "chat.completion.chunk", | |
| 33 | - created: Date.now(), | |
| 34 | - model: "test-model", | |
| 35 | - choices: [ | |
| 36 | - { | |
| 37 | - index: 0, | |
| 38 | - delta: { content }, | |
| 39 | - finish_reason: null, | |
| 40 | - }, | |
| 41 | - ], | |
| 42 | - }; | |
| 43 | - } | |
| 44 | - | |
| 45 | - // Helper to create a tool call chunk | |
| 46 | - function toolCallChunk( | |
| 47 | - id: string, | |
| 48 | - name?: string, | |
| 49 | - args?: string, | |
| 50 | - ): ChatCompletionChunk { | |
| 51 | - return { | |
| 52 | - id: "test", | |
| 53 | - object: "chat.completion.chunk", | |
| 54 | - created: Date.now(), | |
| 55 | - model: "test-model", | |
| 56 | - choices: [ | |
| 57 | - { | |
| 58 | - index: 0, | |
| 59 | - delta: { | |
| 60 | - tool_calls: [ | |
| 61 | - { | |
| 62 | - index: 0, | |
| 63 | - id, | |
| 64 | - type: "function", | |
| 65 | - function: { | |
| 66 | - name: name || undefined, | |
| 67 | - arguments: args || undefined, | |
| 68 | - }, | |
| 69 | - }, | |
| 70 | - ], | |
| 71 | - }, | |
| 72 | - finish_reason: null, | |
| 73 | - }, | |
| 74 | - ], | |
| 75 | - }; | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Helper to create a tool call chunk with optional ID | |
| 79 | - function toolCallChunkWithIndex( | |
| 80 | - index: number, | |
| 81 | - id?: string, | |
| 82 | - name?: string, | |
| 83 | - args?: string, | |
| 84 | - ): ChatCompletionChunk { | |
| 85 | - const toolCall: any = { | |
| 86 | - index, | |
| 87 | - type: "function" as const, | |
| 88 | - function: {}, | |
| 89 | - }; | |
| 90 | - | |
| 91 | - if (id) toolCall.id = id; | |
| 92 | - if (name) toolCall.function.name = name; | |
| 93 | - if (args !== undefined) toolCall.function.arguments = args; | |
| 94 | - | |
| 95 | - return { | |
| 96 | - id: "test", | |
| 97 | - object: "chat.completion.chunk" as const, | |
| 98 | - created: Date.now(), | |
| 99 | - model: "test-model", | |
| 100 | - choices: [ | |
| 101 | - { | |
| 102 | - index: 0, | |
| 103 | - delta: { tool_calls: [toolCall] }, | |
| 104 | - finish_reason: null, | |
| 105 | - }, | |
| 106 | - ], | |
| 107 | - }; | |
| 108 | - } | |
| 109 | - | |
| 110 | - beforeEach(() => { | |
| 111 | - // Reset chunks for each test | |
| 112 | - chunks = []; | |
| 113 | - chatHistory = [ | |
| 114 | - { | |
| 115 | - message: { role: "user", content: "Test prompt" }, | |
| 116 | - contextItems: [], | |
| 117 | - }, | |
| 118 | - ]; | |
| 119 | - | |
| 120 | - // Create a mock LLM API that returns our predefined chunks | |
| 121 | - mockLlmApi = { | |
| 122 | - chatCompletionStream: vi.fn().mockImplementation(async function* () { | |
| 123 | - for (const chunk of chunks) { | |
| 124 | - yield chunk; | |
| 125 | - } | |
| 126 | - }), | |
| 127 | - } as unknown as BaseLlmApi; | |
| 128 | - | |
| 129 | - // Mock abort controller | |
| 130 | - mockAbortController = { | |
| 131 | - signal: { aborted: false }, | |
| 132 | - } as unknown as AbortController; | |
| 133 | - | |
| 134 | - // Mock model config | |
| 135 | - mockModel = { | |
| 136 | - model: "test-model", | |
| 137 | - provider: "test-provider", | |
| 138 | - } as unknown as ModelConfig; | |
| 139 | - }); | |
| 140 | - | |
| 141 | - it("content after tool calls is preserved", async () => { | |
| 142 | - chunks = [ | |
| 143 | - contentChunk(""), | |
| 144 | - toolCallChunk("call_123", "Read", '{"filepath": "/README.md"}'), | |
| 145 | - contentChunk(""), | |
| 146 | - contentChunk("I'll read the README file for you."), | |
| 147 | - ]; | |
| 148 | - | |
| 149 | - const result = await processStreamingResponse({ | |
| 150 | - chatHistory, | |
| 151 | - model: mockModel, | |
| 152 | - llmApi: mockLlmApi, | |
| 153 | - abortController: mockAbortController, | |
| 154 | - }); | |
| 155 | - | |
| 156 | - expect(result.content).toBe("I'll read the README file for you."); | |
| 157 | - expect(result.toolCalls.length).toBe(1); | |
| 158 | - | |
| 159 | - // Fixed: finalContent should preserve the content | |
| 160 | - expect(result.finalContent).toBe("I'll read the README file for you."); | |
| 161 | - }); | |
| 162 | - | |
| 163 | - it("content before tool calls is preserved", async () => { | |
| 164 | - chunks = [ | |
| 165 | - contentChunk("Let me search for that. "), | |
| 166 | - toolCallChunk("call_123", "search_code", '{"pattern": "test"}'), | |
| 167 | - ]; | |
| 168 | - | |
| 169 | - const result = await processStreamingResponse({ | |
| 170 | - chatHistory, | |
| 171 | - model: mockModel, | |
| 172 | - llmApi: mockLlmApi, | |
| 173 | - abortController: mockAbortController, | |
| 174 | - }); | |
| 175 | - | |
| 176 | - expect(result.content).toBe("Let me search for that. "); | |
| 177 | - expect(result.toolCalls.length).toBe(1); | |
| 178 | - | |
| 179 | - // Fixed: finalContent preserves content before tool calls | |
| 180 | - expect(result.finalContent).toBe("Let me search for that. "); | |
| 181 | - }); | |
| 182 | - | |
| 183 | - it("handles the exact problematic sequence from the logs", async () => { | |
| 184 | - chunks = [ | |
| 185 | - contentChunk(""), | |
| 186 | - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", "Read", ""), | |
| 187 | - toolCallChunk( | |
| 188 | - "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 189 | - undefined, | |
| 190 | - '{"filepath', | |
| 191 | - ), | |
| 192 | - toolCallChunk( | |
| 193 | - "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 194 | - undefined, | |
| 195 | - '": "/Use', | |
| 196 | - ), | |
| 197 | - toolCallChunk( | |
| 198 | - "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 199 | - undefined, | |
| 200 | - "rs/nate/gh/c", | |
| 201 | - ), | |
| 202 | - toolCallChunk( | |
| 203 | - "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 204 | - undefined, | |
| 205 | - "ontinuede", | |
| 206 | - ), | |
| 207 | - toolCallChunk( | |
| 208 | - "toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", | |
| 209 | - undefined, | |
| 210 | - "v/cli/README", | |
| 211 | - ), | |
| 212 | - toolCallChunk("toolu_vrtx_01Jj9m9VbtwVZwcU6A311g6A", undefined, '.md"}'), | |
| 213 | - contentChunk(""), | |
| 214 | - contentChunk("I'll read the README file for you."), | |
| 215 | - ]; | |
| 216 | - | |
| 217 | - const result = await processStreamingResponse({ | |
| 218 | - chatHistory, | |
| 219 | - model: mockModel, | |
| 220 | - llmApi: mockLlmApi, | |
| 221 | - abortController: mockAbortController, | |
| 222 | - }); | |
| 223 | - | |
| 224 | - expect(result.content).toBe("I'll read the README file for you."); | |
| 225 | - expect(result.toolCalls.length).toBe(1); | |
| 226 | - | |
| 227 | - // Fixed: content is preserved | |
| 228 | - expect(result.finalContent).toBe("I'll read the README file for you."); | |
| 229 | - | |
| 230 | - // Verify the tool call was assembled correctly | |
| 231 | - expect(result.toolCalls[0].name).toBe("Read"); | |
| 232 | - expect(result.toolCalls[0].argumentsStr).toBe( | |
| 233 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 234 | - ); | |
| 235 | - }); | |
| 236 | - | |
| 237 | - it("shows content works fine without tool calls", async () => { | |
| 238 | - chunks = [contentChunk("Hello "), contentChunk("world!")]; | |
| 239 | - | |
| 240 | - const result = await processStreamingResponse({ | |
| 241 | - chatHistory, | |
| 242 | - model: mockModel, | |
| 243 | - llmApi: mockLlmApi, | |
| 244 | - abortController: mockAbortController, | |
| 245 | - }); | |
| 246 | - | |
| 247 | - expect(result.content).toBe("Hello world!"); | |
| 248 | - expect(result.toolCalls.length).toBe(0); | |
| 249 | - | |
| 250 | - // Without tool calls, finalContent is correct | |
| 251 | - expect(result.finalContent).toBe("Hello world!"); | |
| 252 | - }); | |
| 253 | - | |
| 254 | - it("handles provider that only sends tool ID in first chunk then uses index", async () => { | |
| 255 | - chunks = [ | |
| 256 | - contentChunk("I'll read the README.md file for you and then say hello!"), | |
| 257 | - // First chunk has ID | |
| 258 | - toolCallChunkWithIndex( | |
| 259 | - 0, | |
| 260 | - "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", | |
| 261 | - "Read", | |
| 262 | - "", | |
| 263 | - ), | |
| 264 | - // Subsequent chunks only have index, no ID | |
| 265 | - toolCallChunkWithIndex( | |
| 266 | - 0, | |
| 267 | - undefined, | |
| 268 | - undefined, | |
| 269 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 270 | - ), | |
| 271 | - ]; | |
| 272 | - | |
| 273 | - const result = await processStreamingResponse({ | |
| 274 | - chatHistory, | |
| 275 | - model: mockModel, | |
| 276 | - llmApi: mockLlmApi, | |
| 277 | - abortController: mockAbortController, | |
| 278 | - }); | |
| 279 | - | |
| 280 | - // Content is captured correctly | |
| 281 | - expect(result.content).toBe( | |
| 282 | - "I'll read the README.md file for you and then say hello!", | |
| 283 | - ); | |
| 284 | - expect(result.toolCalls.length).toBe(1); | |
| 285 | - | |
| 286 | - // Fixed: finalContent preserves content | |
| 287 | - expect(result.finalContent).toBe( | |
| 288 | - "I'll read the README.md file for you and then say hello!", | |
| 289 | - ); | |
| 290 | - | |
| 291 | - // Tool call arguments are preserved using index mapping | |
| 292 | - expect(result.toolCalls[0].name).toBe("Read"); | |
| 293 | - expect(result.toolCalls[0].argumentsStr).toBe( | |
| 294 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 295 | - ); | |
| 296 | - }); | |
| 297 | - | |
| 298 | - it("handles realistic fragmented arguments from index-based provider", async () => { | |
| 299 | - // Simulate the exact sequence from the user's logs with fragmented JSON | |
| 300 | - chunks = [ | |
| 301 | - contentChunk("I'll read the README.md file for you and then say hello!"), | |
| 302 | - // First chunk has ID | |
| 303 | - toolCallChunkWithIndex( | |
| 304 | - 0, | |
| 305 | - "toolu_vrtx_01ULx6UjdJ7B7bjf5WPHTXGz", | |
| 306 | - "Read", | |
| 307 | - "", | |
| 308 | - ), | |
| 309 | - // Subsequent chunks fragment the JSON arguments | |
| 310 | - toolCallChunkWithIndex(0, undefined, undefined, '{"filepa'), | |
| 311 | - toolCallChunkWithIndex(0, undefined, undefined, 'th"'), | |
| 312 | - toolCallChunkWithIndex(0, undefined, undefined, ": "), | |
| 313 | - toolCallChunkWithIndex(0, undefined, undefined, '"/U'), | |
| 314 | - toolCallChunkWithIndex(0, undefined, undefined, "sers/nate/gh"), | |
| 315 | - toolCallChunkWithIndex(0, undefined, undefined, "/c"), | |
| 316 | - toolCallChunkWithIndex(0, undefined, undefined, "onti"), | |
| 317 | - toolCallChunkWithIndex(0, undefined, undefined, "nuedev/cli"), | |
| 318 | - toolCallChunkWithIndex(0, undefined, undefined, "/READ"), | |
| 319 | - toolCallChunkWithIndex(0, undefined, undefined, "ME.m"), | |
| 320 | - toolCallChunkWithIndex(0, undefined, undefined, 'd"}'), | |
| 321 | - ]; | |
| 322 | - | |
| 323 | - const result = await processStreamingResponse({ | |
| 324 | - chatHistory, | |
| 325 | - model: mockModel, | |
| 326 | - llmApi: mockLlmApi, | |
| 327 | - abortController: mockAbortController, | |
| 328 | - }); | |
| 329 | - | |
| 330 | - // Fixed: Both issues are resolved | |
| 331 | - // 1. Content is preserved | |
| 332 | - expect(result.finalContent).toBe( | |
| 333 | - "I'll read the README.md file for you and then say hello!", | |
| 334 | - ); | |
| 335 | - | |
| 336 | - // 2. Tool call arguments are assembled correctly | |
| 337 | - expect(result.toolCalls[0].name).toBe("Read"); | |
| 338 | - expect(result.toolCalls[0].argumentsStr).toBe( | |
| 339 | - '{"filepath": "/Users/nate/gh/continuedev/cli/README.md"}', | |
| 340 | - ); | |
| 341 | - }); | |
| 342 | - | |
| 343 | - it("handles malformed chunk with empty choices array without crashing", async () => { | |
| 344 | - // This reproduces the exact bug from the logs: | |
| 345 | - // {"chunk":{"choices":[],"usage":{"completion_tokens":96,"prompt_tokens":711,"total_tokens":807,"prompt_tokens_details":{"cached_tokens":3353}},"created":1754927672408,"id":"","model":"claude-sonnet-4-20250514","object":"chat.completion.chunk"}} | |
| 346 | - const malformedChunk: ChatCompletionChunk = { | |
| 347 | - id: "", | |
| 348 | - object: "chat.completion.chunk", | |
| 349 | - created: 1754927672408, | |
| 350 | - model: "claude-sonnet-4-20250514", | |
| 351 | - choices: [], // Empty choices array - this causes the bug | |
| 352 | - usage: { | |
| 353 | - completion_tokens: 96, | |
| 354 | - prompt_tokens: 711, | |
| 355 | - total_tokens: 807, | |
| 356 | - prompt_tokens_details: { | |
| 357 | - cached_tokens: 3353, | |
| 358 | - }, | |
| 359 | - }, | |
| 360 | - }; | |
| 361 | - | |
| 362 | - chunks = [ | |
| 363 | - malformedChunk, // Put malformed chunk first to trigger the bug more clearly | |
| 364 | - contentChunk("Hello "), | |
| 365 | - contentChunk("world!"), | |
| 366 | - ]; | |
| 367 | - | |
| 368 | - // This should not throw an error: "Cannot read properties of undefined (reading 'delta')" | |
| 369 | - let caughtError: any = null; | |
| 370 | - try { | |
| 371 | - await processStreamingResponse({ | |
| 372 | - chatHistory, | |
| 373 | - model: mockModel, | |
| 374 | - llmApi: mockLlmApi, | |
| 375 | - abortController: mockAbortController, | |
| 376 | - }); | |
| 377 | - } catch (error) { | |
| 378 | - caughtError = error; | |
| 379 | - } | |
| 380 | - | |
| 381 | - // Should NOT throw error about reading 'delta' property | |
| 382 | - expect(caughtError).toBeNull(); | |
| 383 | - | |
| 384 | - const result = await processStreamingResponse({ | |
| 385 | - chatHistory, | |
| 386 | - model: mockModel, | |
| 387 | - llmApi: mockLlmApi, | |
| 388 | - abortController: mockAbortController, | |
| 389 | - }); | |
| 390 | - | |
| 391 | - expect(result.content).toBe("Hello world!"); | |
| 392 | - expect(result.toolCalls.length).toBe(0); | |
| 393 | - expect(result.finalContent).toBe("Hello world!"); | |
| 394 | - }); | |
| 395 | -}); | |
| 396 | - | |
| 397 | -// Tests for preprocessStreamedToolCalls function | |
| 398 | -describe.skip("preprocessStreamedToolCalls", () => { | |
| 399 | - // Mock dependencies | |
| 400 | - beforeEach(async () => { | |
| 401 | - // Mock setup would go here but is currently causing issues | |
| 402 | - }); | |
| 403 | - | |
| 404 | - afterEach(() => { | |
| 405 | - vi.restoreAllMocks(); | |
| 406 | - }); | |
| 407 | - | |
| 408 | - it("preprocesses valid tool calls correctly", async () => { | |
| 409 | - const toolCalls: ToolCall[] = [ | |
| 410 | - { | |
| 411 | - id: "call_123", | |
| 412 | - name: "Read", | |
| 413 | - arguments: { filepath: "/path/to/file.txt" }, | |
| 414 | - argumentsStr: '{"filepath": "/path/to/file.txt"}', | |
| 415 | - startNotified: false, | |
| 416 | - }, | |
| 417 | - ]; | |
| 418 | - | |
| 419 | - const callbacks = { | |
| 420 | - onToolStart: vi.fn(), | |
| 421 | - onToolError: vi.fn(), | |
| 422 | - }; | |
| 423 | - | |
| 424 | - const { preprocessedCalls, errorChatEntries } = | |
| 425 | - await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 426 | - | |
| 427 | - // Should have one preprocessed call and no errors | |
| 428 | - expect(preprocessedCalls).toHaveLength(1); | |
| 429 | - expect(errorChatEntries).toHaveLength(0); | |
| 430 | - expect(preprocessedCalls[0].name).toBe("Read"); | |
| 431 | - expect(preprocessedCalls[0].tool).toBeDefined(); | |
| 432 | - expect(preprocessedCalls[0].preprocessResult).toBeDefined(); | |
| 433 | - | |
| 434 | - // Callbacks should not be called for successful preprocessing | |
| 435 | - expect(callbacks.onToolStart).not.toHaveBeenCalled(); | |
| 436 | - expect(callbacks.onToolError).not.toHaveBeenCalled(); | |
| 437 | - }); | |
| 438 | - | |
| 439 | - it("handles tool preprocessing errors correctly", async () => { | |
| 440 | - // Set the spy to throw an error | |
| 441 | - const toolsModule = await import("./tools/index.js"); | |
| 442 | - vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce( | |
| 443 | - () => { | |
| 444 | - throw new Error("Missing required argument"); | |
| 445 | - }, | |
| 446 | - ); | |
| 447 | - | |
| 448 | - const toolCalls: ToolCall[] = [ | |
| 449 | - { | |
| 450 | - id: "call_456", | |
| 451 | - name: "Read", | |
| 452 | - arguments: {}, // Missing required filepath | |
| 453 | - argumentsStr: "{}", | |
| 454 | - startNotified: false, | |
| 455 | - }, | |
| 456 | - ]; | |
| 457 | - | |
| 458 | - const callbacks = { | |
| 459 | - onToolStart: vi.fn(), | |
| 460 | - onToolError: vi.fn(), | |
| 461 | - }; | |
| 462 | - | |
| 463 | - const { preprocessedCalls, errorChatEntries } = | |
| 464 | - await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 465 | - | |
| 466 | - // Should have no preprocessed calls and one error | |
| 467 | - expect(preprocessedCalls).toHaveLength(0); | |
| 468 | - expect(errorChatEntries).toHaveLength(1); | |
| 469 | - expect(errorChatEntries[0].content).toContain("Missing required argument"); | |
| 470 | - | |
| 471 | - // Callbacks should be called for errors | |
| 472 | - expect(callbacks.onToolStart).toHaveBeenCalledWith("Read", {}); | |
| 473 | - expect(callbacks.onToolError).toHaveBeenCalledWith( | |
| 474 | - expect.stringContaining("Missing required argument"), | |
| 475 | - "Read", | |
| 476 | - ); | |
| 477 | - }); | |
| 478 | - | |
| 479 | - it("handles tool not found errors", async () => { | |
| 480 | - const toolCalls: ToolCall[] = [ | |
| 481 | - { | |
| 482 | - id: "call_789", | |
| 483 | - name: "nonexistent_tool", | |
| 484 | - arguments: { some: "arg" }, | |
| 485 | - argumentsStr: '{"some": "arg"}', | |
| 486 | - startNotified: false, | |
| 487 | - }, | |
| 488 | - ]; | |
| 489 | - | |
| 490 | - const { preprocessedCalls, errorChatEntries } = | |
| 491 | - await preprocessStreamedToolCalls(toolCalls); | |
| 492 | - | |
| 493 | - // Should have no preprocessed calls and one error | |
| 494 | - expect(preprocessedCalls).toHaveLength(0); | |
| 495 | - expect(errorChatEntries).toHaveLength(1); | |
| 496 | - expect(errorChatEntries[0].content).toContain( | |
| 497 | - "Tool nonexistent_tool not found", | |
| 498 | - ); | |
| 499 | - }); | |
| 500 | -}); | |
| 501 | - | |
| 502 | -// Tests for executeStreamedToolCalls function | |
| 503 | -describe.skip("executeStreamedToolCalls", () => { | |
| 504 | - beforeEach(() => { | |
| 505 | - // Reset spies | |
| 506 | - vi.spyOn(toolPermissionManager, "requestPermission").mockReset(); | |
| 507 | - vi.spyOn(toolPermissionManager, "on").mockReset(); | |
| 508 | - vi.spyOn(toolPermissionManager, "off").mockReset(); | |
| 509 | - }); | |
| 510 | - | |
| 511 | - it("executes tool calls with allowed permissions", async () => { | |
| 512 | - // Setup spies instead of mocks | |
| 513 | - const permissionsModule = await import("./permissions/index.js"); | |
| 514 | - vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 515 | - permission: "allow", | |
| 516 | - }); | |
| 517 | - | |
| 518 | - const toolsModule = await import("./tools/index.js"); | |
| 519 | - const mockedExecuteToolCall = vi | |
| 520 | - .spyOn(toolsModule, "executeToolCall") | |
| 521 | - .mockResolvedValue("Tool execution successful"); | |
| 522 | - | |
| 523 | - // Create preprocessed tool call | |
| 524 | - const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 525 | - { | |
| 526 | - id: "call_123", | |
| 527 | - name: "Read", | |
| 528 | - arguments: { filepath: "/test.txt" }, | |
| 529 | - argumentsStr: '{"filepath": "/test.txt"}', | |
| 530 | - startNotified: false, | |
| 531 | - tool: readFileTool, | |
| 532 | - }, | |
| 533 | - ]; | |
| 534 | - | |
| 535 | - const callbacks = { | |
| 536 | - onToolStart: vi.fn(), | |
| 537 | - onToolResult: vi.fn(), | |
| 538 | - onToolError: vi.fn(), | |
| 539 | - }; | |
| 540 | - | |
| 541 | - const { chatHistoryEntries } = await executeStreamedToolCalls( | |
| 542 | - preprocessedCalls, | |
| 543 | - callbacks, | |
| 544 | - ); | |
| 545 | - | |
| 546 | - // Verify results | |
| 547 | - expect(chatHistoryEntries).toHaveLength(1); | |
| 548 | - expect(chatHistoryEntries[0].content).toBe("Tool execution successful"); | |
| 549 | - expect(callbacks.onToolStart).toHaveBeenCalledWith("read_file", { | |
| 550 | - filepath: "/test.txt", | |
| 551 | - }); | |
| 552 | - expect(callbacks.onToolResult).toHaveBeenCalledWith( | |
| 553 | - "Tool execution successful", | |
| 554 | - "Read", | |
| 555 | - "done", | |
| 556 | - ); | |
| 557 | - expect(mockedExecuteToolCall).toHaveBeenCalledWith(preprocessedCalls[0]); | |
| 558 | - }); | |
| 559 | - | |
| 560 | - it("handles permission denied correctly", async () => { | |
| 561 | - // Setup permission to ask | |
| 562 | - const permissionsModule = await import("./permissions/index.js"); | |
| 563 | - vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 564 | - permission: "ask", | |
| 565 | - }); | |
| 566 | - | |
| 567 | - // Spy on permission request to be denied | |
| 568 | - vi.spyOn(toolPermissionManager, "requestPermission").mockResolvedValue({ | |
| 569 | - approved: false, | |
| 570 | - }); | |
| 571 | - | |
| 572 | - // Add event listener mock | |
| 573 | - vi.spyOn(toolPermissionManager, "on").mockImplementation( | |
| 574 | - (event: any, callback: any) => { | |
| 575 | - if (event === "permissionRequested") { | |
| 576 | - // Immediately trigger the callback to simulate event | |
| 577 | - callback({ | |
| 578 | - requestId: "req_123", | |
| 579 | - toolCall: { | |
| 580 | - name: "Write", | |
| 581 | - arguments: { | |
| 582 | - filepath: "/test.txt", | |
| 583 | - content: "data", | |
| 584 | - }, | |
| 585 | - }, | |
| 586 | - }); | |
| 587 | - } | |
| 588 | - return toolPermissionManager; | |
| 589 | - }, | |
| 590 | - ); | |
| 591 | - | |
| 592 | - // Create preprocessed tool call | |
| 593 | - const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 594 | - { | |
| 595 | - id: "call_456", | |
| 596 | - name: "Write", | |
| 597 | - arguments: { filepath: "/test.txt", content: "data" }, | |
| 598 | - argumentsStr: '{"filepath": "/test.txt", "content": "data"}', | |
| 599 | - startNotified: false, | |
| 600 | - tool: writeFileTool, | |
| 601 | - }, | |
| 602 | - { | |
| 603 | - id: "call_457", | |
| 604 | - name: "Write", | |
| 605 | - arguments: { filepath: "/test.txt", content: "data" }, | |
| 606 | - argumentsStr: '{"filepath": "/test.txt", "content": "data"}', | |
| 607 | - startNotified: false, | |
| 608 | - tool: writeFileTool, | |
| 609 | - }, | |
| 610 | - ]; | |
| 611 | - | |
| 612 | - const callbacks = { | |
| 613 | - onToolStart: vi.fn(), | |
| 614 | - onToolResult: vi.fn(), | |
| 615 | - onToolPermissionRequest: vi.fn(), | |
| 616 | - }; | |
| 617 | - | |
| 618 | - const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( | |
| 619 | - preprocessedCalls, | |
| 620 | - callbacks, | |
| 621 | - ); | |
| 622 | - | |
| 623 | - // Verify results | |
| 624 | - expect(hasRejection).toEqual(true); | |
| 625 | - expect(chatHistoryEntries).toHaveLength(2); | |
| 626 | - expect(chatHistoryEntries[0].content).toBe("Permission denied by user"); | |
| 627 | - expect(chatHistoryEntries[1].content).toBe( | |
| 628 | - "Cancelled due to previous tool rejection", | |
| 629 | - ); | |
| 630 | - expect(callbacks.onToolStart).toHaveBeenCalledWith("Write", { | |
| 631 | - filepath: "/test.txt", | |
| 632 | - content: "data", | |
| 633 | - }); | |
| 634 | - expect(callbacks.onToolResult).toHaveBeenCalledWith( | |
| 635 | - "Permission denied by user", | |
| 636 | - "Write", | |
| 637 | - "canceled", | |
| 638 | - ); | |
| 639 | - expect(callbacks.onToolPermissionRequest).toHaveBeenCalledWith( | |
| 640 | - "Write", | |
| 641 | - { filepath: "/test.txt", content: "data" }, | |
| 642 | - "req_123", | |
| 643 | - undefined, | |
| 644 | - ); | |
| 645 | - }); | |
| 646 | - | |
| 647 | - it("handles tool execution errors", async () => { | |
| 648 | - // Setup spies | |
| 649 | - const permissionsModule = await import("./permissions/index.js"); | |
| 650 | - vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ | |
| 651 | - permission: "allow", | |
| 652 | - }); | |
| 653 | - | |
| 654 | - const toolsModule = await import("./tools/index.js"); | |
| 655 | - vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue( | |
| 656 | - new Error("Execution failed"), | |
| 657 | - ); | |
| 658 | - | |
| 659 | - // Create preprocessed tool call | |
| 660 | - const preprocessedCalls: PreprocessedToolCall[] = [ | |
| 661 | - { | |
| 662 | - id: "call_789", | |
| 663 | - name: "search_code", | |
| 664 | - arguments: { pattern: "test" }, | |
| 665 | - argumentsStr: '{"pattern": "test"}', | |
| 666 | - startNotified: false, | |
| 667 | - tool: searchCodeTool, | |
| 668 | - }, | |
| 669 | - ]; | |
| 670 | - | |
| 671 | - const callbacks = { | |
| 672 | - onToolStart: vi.fn(), | |
| 673 | - onToolError: vi.fn(), | |
| 674 | - }; | |
| 675 | - | |
| 676 | - const { chatHistoryEntries, hasRejection } = await executeStreamedToolCalls( | |
| 677 | - preprocessedCalls, | |
| 678 | - callbacks, | |
| 679 | - ); | |
| 680 | - | |
| 681 | - // Verify results | |
| 682 | - expect(chatHistoryEntries).toHaveLength(1); | |
| 683 | - expect(chatHistoryEntries[0].content).toContain( | |
| 684 | - "Error executing tool search_code", | |
| 685 | - ); | |
| 686 | - expect(chatHistoryEntries[0].content).toContain("Execution failed"); | |
| 687 | - expect(callbacks.onToolStart).toHaveBeenCalledWith("search_code", { | |
| 688 | - pattern: "test", | |
| 689 | - }); | |
| 690 | - expect(callbacks.onToolError).toHaveBeenCalledWith( | |
| 691 | - expect.stringContaining( | |
| 692 | - "Error executing tool search_code: Execution failed", | |
| 693 | - ), | |
| 694 | - "search_code", | |
| 695 | - ); | |
| 696 | - }); | |
| 697 | -}); |
deleted extensions/cli/src/streamChatResponse.ts +0 −603
| @@ -1,603 +0,0 @@ | ||
| 1 | -import { ModelConfig } from "@continuedev/config-yaml"; | |
| 2 | -import { BaseLlmApi } from "@continuedev/openai-adapters"; | |
| 3 | -import type { ChatHistoryItem, ToolStatus } from "core/index.js"; | |
| 4 | -import * as dotenv from "dotenv"; | |
| 5 | -import type { ChatCompletionTool } from "openai/resources.mjs"; | |
| 6 | - | |
| 7 | -import { | |
| 8 | - convertFromUnifiedHistory, | |
| 9 | - createHistoryItem, | |
| 10 | -} from "./messageConversion.js"; | |
| 11 | -import { filterExcludedTools } from "./permissions/index.js"; | |
| 12 | -import { | |
| 13 | - getServiceSync, | |
| 14 | - MCPServiceState, | |
| 15 | - MCPTool, | |
| 16 | - SERVICE_NAMES, | |
| 17 | -} from "./services/index.js"; | |
| 18 | -import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; | |
| 19 | -import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; | |
| 20 | -import { | |
| 21 | - executeStreamedToolCalls, | |
| 22 | - preprocessStreamedToolCalls, | |
| 23 | - processChunkContent, | |
| 24 | - processToolCallDelta, | |
| 25 | - recordStreamTelemetry, | |
| 26 | - trackFirstTokenTime, | |
| 27 | -} from "./streamChatResponse.helpers.js"; | |
| 28 | -import { | |
| 29 | - getDefaultCompletionOptions, | |
| 30 | - StreamCallbacks, | |
| 31 | -} from "./streamChatResponse.types.js"; | |
| 32 | -import { telemetryService } from "./telemetry/telemetryService.js"; | |
| 33 | -import { getAllBuiltinTools, ToolCall } from "./tools/index.js"; | |
| 34 | -import { | |
| 35 | - chatCompletionStreamWithBackoff, | |
| 36 | - withExponentialBackoff, | |
| 37 | -} from "./util/exponentialBackoff.js"; | |
| 38 | -import { logger } from "./util/logger.js"; | |
| 39 | - | |
| 40 | -dotenv.config(); | |
| 41 | - | |
| 42 | -function updateFinalResponse( | |
| 43 | - content: string, | |
| 44 | - shouldContinue: boolean, | |
| 45 | - isHeadless: boolean, | |
| 46 | - currentFinalResponse: string, | |
| 47 | -): string { | |
| 48 | - if (!shouldContinue) { | |
| 49 | - return content; | |
| 50 | - } else if (isHeadless && content) { | |
| 51 | - return content; | |
| 52 | - } | |
| 53 | - return currentFinalResponse; | |
| 54 | -} | |
| 55 | - | |
| 56 | -function handleContentDisplay( | |
| 57 | - content: string, | |
| 58 | - callbacks: StreamCallbacks | undefined, | |
| 59 | - isHeadless: boolean, | |
| 60 | -): void { | |
| 61 | - // Add newline after content if needed | |
| 62 | - if (!callbacks?.onContent && !isHeadless && content) { | |
| 63 | - logger.info(""); | |
| 64 | - } | |
| 65 | - | |
| 66 | - // Notify content complete | |
| 67 | - if (content && callbacks?.onContentComplete) { | |
| 68 | - callbacks.onContentComplete(content); | |
| 69 | - } | |
| 70 | -} | |
| 71 | - | |
| 72 | -async function handleToolCalls( | |
| 73 | - toolCalls: ToolCall[], | |
| 74 | - chatHistory: ChatHistoryItem[], | |
| 75 | - content: string, | |
| 76 | - callbacks: StreamCallbacks | undefined, | |
| 77 | - isHeadless: boolean, | |
| 78 | -): Promise<boolean> { | |
| 79 | - if (toolCalls.length === 0) { | |
| 80 | - if (content) { | |
| 81 | - chatHistory.push( | |
| 82 | - createHistoryItem({ | |
| 83 | - role: "assistant", | |
| 84 | - content, | |
| 85 | - }), | |
| 86 | - ); | |
| 87 | - } | |
| 88 | - return false; | |
| 89 | - } | |
| 90 | - | |
| 91 | - // Create tool call states for the ChatHistoryItem | |
| 92 | - const toolCallStates = toolCalls.map((tc) => ({ | |
| 93 | - toolCallId: tc.id, | |
| 94 | - toolCall: { | |
| 95 | - id: tc.id, | |
| 96 | - type: "function" as const, | |
| 97 | - function: { | |
| 98 | - name: tc.name, | |
| 99 | - arguments: JSON.stringify(tc.arguments), | |
| 100 | - }, | |
| 101 | - }, | |
| 102 | - status: "generated" as ToolStatus, | |
| 103 | - parsedArgs: tc.arguments, | |
| 104 | - })); | |
| 105 | - | |
| 106 | - // Create assistant message with tool calls | |
| 107 | - const assistantMessage = { | |
| 108 | - role: "assistant" as const, | |
| 109 | - content: content || "", | |
| 110 | - toolCalls: toolCalls.map((tc) => ({ | |
| 111 | - id: tc.id, | |
| 112 | - type: "function" as const, | |
| 113 | - function: { | |
| 114 | - name: tc.name, | |
| 115 | - arguments: JSON.stringify(tc.arguments), | |
| 116 | - }, | |
| 117 | - })), | |
| 118 | - }; | |
| 119 | - | |
| 120 | - chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); | |
| 121 | - | |
| 122 | - // First preprocess the tool calls | |
| 123 | - const { preprocessedCalls, errorChatEntries } = | |
| 124 | - await preprocessStreamedToolCalls(toolCalls, callbacks); | |
| 125 | - | |
| 126 | - // Add any preprocessing errors to chat history | |
| 127 | - // Convert error entries from OpenAI format to ChatHistoryItem format | |
| 128 | - errorChatEntries.forEach((errorEntry) => { | |
| 129 | - chatHistory.push( | |
| 130 | - createHistoryItem({ | |
| 131 | - role: "assistant", | |
| 132 | - content: errorEntry.content || "", | |
| 133 | - }), | |
| 134 | - ); | |
| 135 | - }); | |
| 136 | - | |
| 137 | - // Execute the valid preprocessed tool calls | |
| 138 | - const { chatHistoryEntries: toolResults, hasRejection } = | |
| 139 | - await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless); | |
| 140 | - | |
| 141 | - if (isHeadless && hasRejection) { | |
| 142 | - logger.debug( | |
| 143 | - "Tool call rejected in headless mode - returning current content", | |
| 144 | - ); | |
| 145 | - return true; // Signal early return needed | |
| 146 | - } | |
| 147 | - | |
| 148 | - // Convert tool results from OpenAI format to ChatHistoryItem format | |
| 149 | - // and add them to the chat history | |
| 150 | - toolResults.forEach((toolResult) => { | |
| 151 | - // Find the corresponding tool call state to update | |
| 152 | - const lastAssistantIndex = chatHistory.findLastIndex( | |
| 153 | - (item) => item.message.role === "assistant" && item.toolCallStates, | |
| 154 | - ); | |
| 155 | - | |
| 156 | - if ( | |
| 157 | - lastAssistantIndex >= 0 && | |
| 158 | - chatHistory[lastAssistantIndex].toolCallStates | |
| 159 | - ) { | |
| 160 | - const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( | |
| 161 | - (ts) => ts.toolCallId === toolResult.tool_call_id, | |
| 162 | - ); | |
| 163 | - | |
| 164 | - if (toolState) { | |
| 165 | - toolState.status = hasRejection ? "canceled" : "done"; | |
| 166 | - toolState.output = [ | |
| 167 | - { | |
| 168 | - content: | |
| 169 | - typeof toolResult.content === "string" ? toolResult.content : "", | |
| 170 | - name: `Tool Result`, | |
| 171 | - description: "Tool execution result", | |
| 172 | - }, | |
| 173 | - ]; | |
| 174 | - } | |
| 175 | - } | |
| 176 | - }); | |
| 177 | - return false; | |
| 178 | -} | |
| 179 | - | |
| 180 | -export async function getAllTools() { | |
| 181 | - // Get all available tool names | |
| 182 | - const allBuiltinTools = getAllBuiltinTools(); | |
| 183 | - const builtinToolNames = allBuiltinTools.map((tool) => tool.name); | |
| 184 | - | |
| 185 | - let mcpTools: MCPTool[] = []; | |
| 186 | - let mcpToolNames: string[] = []; | |
| 187 | - const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP); | |
| 188 | - if (mcpServiceResult.state === "ready") { | |
| 189 | - mcpTools = mcpServiceResult?.value?.tools ?? []; | |
| 190 | - mcpToolNames = mcpTools.map((t) => t.name); | |
| 191 | - } else { | |
| 192 | - // MCP is lazy | |
| 193 | - // throw new Error("MCP Service not initialized"); | |
| 194 | - } | |
| 195 | - | |
| 196 | - const allToolNames = [...builtinToolNames, ...mcpToolNames]; | |
| 197 | - | |
| 198 | - // Check if the ToolPermissionService is ready | |
| 199 | - const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>( | |
| 200 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 201 | - ); | |
| 202 | - | |
| 203 | - let allowedToolNames: string[]; | |
| 204 | - if ( | |
| 205 | - permissionsServiceResult.state === "ready" && | |
| 206 | - permissionsServiceResult.value | |
| 207 | - ) { | |
| 208 | - // Filter out excluded tools based on permissions | |
| 209 | - allowedToolNames = filterExcludedTools( | |
| 210 | - allToolNames, | |
| 211 | - permissionsServiceResult.value.permissions, | |
| 212 | - ); | |
| 213 | - } else { | |
| 214 | - // Service not ready - this is a critical error since tools should only be | |
| 215 | - // requested after services are properly initialized | |
| 216 | - logger.error( | |
| 217 | - "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", | |
| 218 | - ); | |
| 219 | - throw new Error( | |
| 220 | - "ToolPermissionService not initialized. Services must be initialized before requesting tools.", | |
| 221 | - ); | |
| 222 | - } | |
| 223 | - | |
| 224 | - const allowedToolNamesSet = new Set(allowedToolNames); | |
| 225 | - | |
| 226 | - // Filter builtin tools | |
| 227 | - const allowedBuiltinTools = allBuiltinTools.filter((tool) => | |
| 228 | - allowedToolNamesSet.has(tool.name), | |
| 229 | - ); | |
| 230 | - | |
| 231 | - const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ | |
| 232 | - type: "function" as const, | |
| 233 | - function: { | |
| 234 | - name: tool.name, | |
| 235 | - description: tool.description, | |
| 236 | - parameters: { | |
| 237 | - type: "object", | |
| 238 | - properties: Object.fromEntries( | |
| 239 | - Object.entries(tool.parameters).map(([key, param]) => [ | |
| 240 | - key, | |
| 241 | - { | |
| 242 | - type: param.type, | |
| 243 | - description: param.description, | |
| 244 | - items: param.items, | |
| 245 | - }, | |
| 246 | - ]), | |
| 247 | - ), | |
| 248 | - required: Object.entries(tool.parameters) | |
| 249 | - .filter(([_, param]) => param.required) | |
| 250 | - .map(([key, _]) => key), | |
| 251 | - }, | |
| 252 | - }, | |
| 253 | - })); | |
| 254 | - | |
| 255 | - // Add filtered MCP tools | |
| 256 | - const allowedMcpTools = mcpTools.filter((tool) => | |
| 257 | - allowedToolNamesSet.has(tool.name), | |
| 258 | - ); | |
| 259 | - | |
| 260 | - allTools.push( | |
| 261 | - ...allowedMcpTools.map((tool) => ({ | |
| 262 | - type: "function" as const, | |
| 263 | - function: { | |
| 264 | - name: tool.name, | |
| 265 | - description: tool.description, | |
| 266 | - parameters: tool.inputSchema, | |
| 267 | - }, | |
| 268 | - })), | |
| 269 | - ); | |
| 270 | - | |
| 271 | - return allTools; | |
| 272 | -} | |
| 273 | - | |
| 274 | -// Helper function to process a single chunk | |
| 275 | -interface ProcessChunkOptions { | |
| 276 | - chunk: any; | |
| 277 | - aiResponse: string; | |
| 278 | - toolCallsMap: Map<string, ToolCall>; | |
| 279 | - indexToIdMap: Map<number, string>; | |
| 280 | - callbacks?: StreamCallbacks; | |
| 281 | - isHeadless?: boolean; | |
| 282 | -} | |
| 283 | - | |
| 284 | -function processChunk(options: ProcessChunkOptions): { | |
| 285 | - aiResponse: string; | |
| 286 | - shouldContinue: boolean; | |
| 287 | -} { | |
| 288 | - const { | |
| 289 | - chunk, | |
| 290 | - aiResponse, | |
| 291 | - toolCallsMap, | |
| 292 | - indexToIdMap, | |
| 293 | - callbacks, | |
| 294 | - isHeadless, | |
| 295 | - } = options; | |
| 296 | - // Safety check: ensure chunk has the expected structure | |
| 297 | - if (!chunk.choices || !chunk.choices[0]) { | |
| 298 | - return { aiResponse, shouldContinue: true }; | |
| 299 | - } | |
| 300 | - | |
| 301 | - const choice = chunk.choices[0]; | |
| 302 | - if (!choice.delta) { | |
| 303 | - return { aiResponse, shouldContinue: true }; | |
| 304 | - } | |
| 305 | - | |
| 306 | - let updatedResponse = aiResponse; | |
| 307 | - | |
| 308 | - // Handle content streaming | |
| 309 | - if (choice.delta.content) { | |
| 310 | - updatedResponse = processChunkContent( | |
| 311 | - choice.delta.content, | |
| 312 | - aiResponse, | |
| 313 | - callbacks, | |
| 314 | - isHeadless, | |
| 315 | - ); | |
| 316 | - } | |
| 317 | - | |
| 318 | - // Handle tool calls | |
| 319 | - if (choice.delta.tool_calls) { | |
| 320 | - for (const toolCallDelta of choice.delta.tool_calls) { | |
| 321 | - processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap); | |
| 322 | - } | |
| 323 | - } | |
| 324 | - | |
| 325 | - return { aiResponse: updatedResponse, shouldContinue: true }; | |
| 326 | -} | |
| 327 | - | |
| 328 | -interface ProcessStreamingResponseOptions { | |
| 329 | - chatHistory: ChatHistoryItem[]; | |
| 330 | - model: ModelConfig; | |
| 331 | - llmApi: BaseLlmApi; | |
| 332 | - abortController: AbortController; | |
| 333 | - callbacks?: StreamCallbacks; | |
| 334 | - isHeadless?: boolean; | |
| 335 | - tools?: ChatCompletionTool[]; | |
| 336 | -} | |
| 337 | - | |
| 338 | -// Process a single streaming response and return whether we need to continue | |
| 339 | -export async function processStreamingResponse( | |
| 340 | - options: ProcessStreamingResponseOptions, | |
| 341 | -): Promise<{ | |
| 342 | - content: string; | |
| 343 | - finalContent: string; // Added field for final content only | |
| 344 | - toolCalls: ToolCall[]; | |
| 345 | - shouldContinue: boolean; | |
| 346 | -}> { | |
| 347 | - const { | |
| 348 | - chatHistory, | |
| 349 | - model, | |
| 350 | - llmApi, | |
| 351 | - abortController, | |
| 352 | - callbacks, | |
| 353 | - isHeadless, | |
| 354 | - tools, | |
| 355 | - } = options; | |
| 356 | - const openaiChatHistory = convertFromUnifiedHistory(chatHistory); | |
| 357 | - const requestStartTime = Date.now(); | |
| 358 | - | |
| 359 | - const streamFactory = async (retryAbortSignal: AbortSignal) => { | |
| 360 | - logger.debug("Creating chat completion stream", { | |
| 361 | - model, | |
| 362 | - messageCount: chatHistory.length, | |
| 363 | - toolCount: tools?.length || 0, | |
| 364 | - }); | |
| 365 | - return await chatCompletionStreamWithBackoff( | |
| 366 | - llmApi, | |
| 367 | - { | |
| 368 | - model: model.model, | |
| 369 | - messages: openaiChatHistory, | |
| 370 | - stream: true, | |
| 371 | - tools, | |
| 372 | - ...getDefaultCompletionOptions(model.defaultCompletionOptions), | |
| 373 | - }, | |
| 374 | - retryAbortSignal, | |
| 375 | - ); | |
| 376 | - }; | |
| 377 | - | |
| 378 | - let aiResponse = ""; | |
| 379 | - let finalContent = ""; | |
| 380 | - const toolCallsMap = new Map<string, ToolCall>(); | |
| 381 | - const indexToIdMap = new Map<number, string>(); // Track index to ID mapping | |
| 382 | - let firstTokenTime: number | null = null; | |
| 383 | - let inputTokens = 0; | |
| 384 | - let outputTokens = 0; | |
| 385 | - | |
| 386 | - try { | |
| 387 | - const streamWithBackoff = withExponentialBackoff( | |
| 388 | - streamFactory, | |
| 389 | - abortController.signal, | |
| 390 | - ); | |
| 391 | - | |
| 392 | - let chunkCount = 0; | |
| 393 | - for await (const chunk of streamWithBackoff) { | |
| 394 | - chunkCount++; | |
| 395 | - | |
| 396 | - logger.debug("Received chunk", { chunkCount, chunk }); | |
| 397 | - | |
| 398 | - // Track token usage if available | |
| 399 | - if (chunk.usage) { | |
| 400 | - inputTokens = chunk.usage.prompt_tokens || 0; | |
| 401 | - outputTokens = chunk.usage.completion_tokens || 0; | |
| 402 | - } | |
| 403 | - | |
| 404 | - // Check if we should abort | |
| 405 | - if (abortController?.signal.aborted) { | |
| 406 | - logger.debug("Stream aborted"); | |
| 407 | - break; | |
| 408 | - } | |
| 409 | - | |
| 410 | - // Track first token time | |
| 411 | - firstTokenTime = trackFirstTokenTime( | |
| 412 | - firstTokenTime, | |
| 413 | - chunk, | |
| 414 | - requestStartTime, | |
| 415 | - model, | |
| 416 | - tools, | |
| 417 | - ); | |
| 418 | - | |
| 419 | - const result = processChunk({ | |
| 420 | - chunk, | |
| 421 | - aiResponse, | |
| 422 | - toolCallsMap, | |
| 423 | - indexToIdMap, | |
| 424 | - callbacks, | |
| 425 | - isHeadless, | |
| 426 | - }); | |
| 427 | - aiResponse = result.aiResponse; | |
| 428 | - if (!result.shouldContinue) break; | |
| 429 | - } | |
| 430 | - | |
| 431 | - const responseEndTime = Date.now(); | |
| 432 | - const cost = recordStreamTelemetry({ | |
| 433 | - requestStartTime, | |
| 434 | - responseEndTime, | |
| 435 | - inputTokens, | |
| 436 | - outputTokens, | |
| 437 | - model, | |
| 438 | - tools, | |
| 439 | - }); | |
| 440 | - const totalDuration = responseEndTime - requestStartTime; | |
| 441 | - | |
| 442 | - logger.debug("Stream complete", { | |
| 443 | - chunkCount, | |
| 444 | - responseLength: aiResponse.length, | |
| 445 | - toolCallsCount: toolCallsMap.size, | |
| 446 | - inputTokens, | |
| 447 | - outputTokens, | |
| 448 | - cost, | |
| 449 | - duration: totalDuration, | |
| 450 | - }); | |
| 451 | - } catch (error: any) { | |
| 452 | - const errorDuration = Date.now() - requestStartTime; | |
| 453 | - | |
| 454 | - // Log failed API request | |
| 455 | - telemetryService.logApiRequest({ | |
| 456 | - model: model.model, | |
| 457 | - durationMs: errorDuration, | |
| 458 | - success: false, | |
| 459 | - error: error.message || String(error), | |
| 460 | - }); | |
| 461 | - | |
| 462 | - if (error.name === "AbortError" || abortController?.signal.aborted) { | |
| 463 | - logger.debug("Stream aborted by user"); | |
| 464 | - return { | |
| 465 | - content: aiResponse, | |
| 466 | - finalContent: aiResponse, | |
| 467 | - toolCalls: [], | |
| 468 | - shouldContinue: false, | |
| 469 | - }; | |
| 470 | - } | |
| 471 | - throw error; | |
| 472 | - } | |
| 473 | - | |
| 474 | - const toolCalls = Array.from(toolCallsMap.values()); | |
| 475 | - | |
| 476 | - // Validate tool calls have complete arguments | |
| 477 | - const validToolCalls = toolCalls.filter((tc) => { | |
| 478 | - if (!tc.arguments || !tc.name) { | |
| 479 | - logger.error("Incomplete tool call", { | |
| 480 | - id: tc.id, | |
| 481 | - name: tc.name, | |
| 482 | - hasArguments: !!tc.arguments, | |
| 483 | - argumentsStr: tc.argumentsStr, | |
| 484 | - }); | |
| 485 | - return false; | |
| 486 | - } | |
| 487 | - return true; | |
| 488 | - }); | |
| 489 | - | |
| 490 | - // Always preserve the content - it should be displayed regardless of tool calls | |
| 491 | - finalContent = aiResponse; | |
| 492 | - | |
| 493 | - return { | |
| 494 | - content: aiResponse, | |
| 495 | - finalContent: finalContent, | |
| 496 | - toolCalls: validToolCalls, | |
| 497 | - shouldContinue: validToolCalls.length > 0, | |
| 498 | - }; | |
| 499 | -} | |
| 500 | - | |
| 501 | -// Main function that handles the conversation loop | |
| 502 | -export async function streamChatResponse( | |
| 503 | - chatHistory: ChatHistoryItem[], | |
| 504 | - model: ModelConfig, | |
| 505 | - llmApi: BaseLlmApi, | |
| 506 | - abortController: AbortController, | |
| 507 | - callbacks?: StreamCallbacks, | |
| 508 | -) { | |
| 509 | - logger.debug("streamChatResponse called", { | |
| 510 | - model, | |
| 511 | - historyLength: chatHistory.length, | |
| 512 | - hasCallbacks: !!callbacks, | |
| 513 | - }); | |
| 514 | - | |
| 515 | - const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 516 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 517 | - ); | |
| 518 | - const isHeadless = serviceResult.value?.isHeadless ?? false; | |
| 519 | - | |
| 520 | - let fullResponse = ""; | |
| 521 | - let finalResponse = ""; | |
| 522 | - | |
| 523 | - while (true) { | |
| 524 | - logger.debug("Starting conversation iteration"); | |
| 525 | - | |
| 526 | - // Recompute tools on each iteration to handle mode changes during streaming | |
| 527 | - const tools = await getAllTools(); | |
| 528 | - | |
| 529 | - logger.debug("Tools prepared", { | |
| 530 | - toolCount: tools.length, | |
| 531 | - toolNames: tools.map((t) => t.function.name), | |
| 532 | - }); | |
| 533 | - | |
| 534 | - // Get response from LLM | |
| 535 | - const { content, toolCalls, shouldContinue } = | |
| 536 | - await processStreamingResponse({ | |
| 537 | - chatHistory, | |
| 538 | - model, | |
| 539 | - llmApi, | |
| 540 | - abortController, | |
| 541 | - callbacks, | |
| 542 | - isHeadless, | |
| 543 | - tools, | |
| 544 | - }); | |
| 545 | - | |
| 546 | - fullResponse += content; | |
| 547 | - | |
| 548 | - // Update final response based on mode | |
| 549 | - finalResponse = updateFinalResponse( | |
| 550 | - content, | |
| 551 | - shouldContinue, | |
| 552 | - isHeadless, | |
| 553 | - finalResponse, | |
| 554 | - ); | |
| 555 | - | |
| 556 | - // Handle content display | |
| 557 | - handleContentDisplay(content, callbacks, isHeadless); | |
| 558 | - | |
| 559 | - // Handle tool calls and check for early return | |
| 560 | - const shouldReturn = await handleToolCalls( | |
| 561 | - toolCalls, | |
| 562 | - chatHistory, | |
| 563 | - content, | |
| 564 | - callbacks, | |
| 565 | - isHeadless, | |
| 566 | - ); | |
| 567 | - | |
| 568 | - if (shouldReturn) { | |
| 569 | - return finalResponse || content || fullResponse; | |
| 570 | - } | |
| 571 | - | |
| 572 | - // Check for auto-compaction after tool execution | |
| 573 | - if (shouldContinue) { | |
| 574 | - const { wasCompacted, chatHistory: updatedChatHistory } = | |
| 575 | - await handleAutoCompaction(chatHistory, model, llmApi, { | |
| 576 | - isHeadless, | |
| 577 | - callbacks: { | |
| 578 | - onSystemMessage: callbacks?.onSystemMessage, | |
| 579 | - onContent: callbacks?.onContent, | |
| 580 | - }, | |
| 581 | - }); | |
| 582 | - | |
| 583 | - // Only update chat history if compaction actually occurred | |
| 584 | - if (wasCompacted) { | |
| 585 | - chatHistory = [...updatedChatHistory]; | |
| 586 | - } | |
| 587 | - } | |
| 588 | - | |
| 589 | - // Check if we should continue | |
| 590 | - if (!shouldContinue) { | |
| 591 | - break; | |
| 592 | - } | |
| 593 | - } | |
| 594 | - | |
| 595 | - logger.debug("streamChatResponse complete", { | |
| 596 | - totalResponseLength: fullResponse.length, | |
| 597 | - totalMessages: chatHistory.length, | |
| 598 | - }); | |
| 599 | - | |
| 600 | - // For headless mode, we return only the final response | |
| 601 | - // Otherwise, return the full response | |
| 602 | - return isHeadless ? finalResponse : fullResponse; | |
| 603 | -} |
deleted extensions/cli/src/streamChatResponse.types.ts +0 −33
| @@ -1,33 +0,0 @@ | ||
| 1 | -import { CompletionOptions } from "@continuedev/config-yaml"; | |
| 2 | -import type { ToolStatus } from "core/index.js"; | |
| 3 | -import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; | |
| 4 | - | |
| 5 | -import { ToolCallPreview } from "./tools/types.js"; | |
| 6 | - | |
| 7 | -export interface StreamCallbacks { | |
| 8 | - onContent?: (content: string) => void; | |
| 9 | - onContentComplete?: (content: string) => void; | |
| 10 | - onToolStart?: (toolName: string, toolArgs?: any) => void; | |
| 11 | - onToolResult?: (result: string, toolName: string, status: ToolStatus) => void; | |
| 12 | - onToolError?: (error: string, toolName?: string) => void; | |
| 13 | - onToolPermissionRequest?: ( | |
| 14 | - toolName: string, | |
| 15 | - toolArgs: any, | |
| 16 | - requestId: string, | |
| 17 | - preview?: ToolCallPreview[], | |
| 18 | - ) => void; | |
| 19 | - onSystemMessage?: (message: string) => void; | |
| 20 | -} | |
| 21 | - | |
| 22 | -export function getDefaultCompletionOptions( | |
| 23 | - opts?: CompletionOptions, | |
| 24 | -): Partial<ChatCompletionCreateParamsStreaming> { | |
| 25 | - if (!opts) return {}; | |
| 26 | - return { | |
| 27 | - max_tokens: opts.maxTokens, | |
| 28 | - temperature: opts.temperature, | |
| 29 | - frequency_penalty: opts.frequencyPenalty, | |
| 30 | - presence_penalty: opts.presencePenalty, | |
| 31 | - top_p: opts.topP, | |
| 32 | - }; | |
| 33 | -} |
modified extensions/cli/src/systemMessage.test.ts +8 −6
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | .mockImplementation((spec: string) => Promise.resolve(spec)), |
| 19 | 19 | })); |
| 20 | 20 | |
| 21 | +const PLAN_MODE_STRING = "You are operating in _Plan Mode_"; | |
| 22 | + | |
| 21 | 23 | describe("constructSystemMessage", () => { |
| 22 | 24 | it("should return base system message with rules when additionalRules is provided", async () => { |
| 23 | 25 | const rules = ["These are the rules for the assistant."]; |
| @@ -167,7 +169,7 @@ | ||
| 167 | 169 | ); |
| 168 | 170 | |
| 169 | 171 | expect(result).toContain("You are an agent in the Continue CLI"); |
| 170 | - expect(result).toContain("PLAN MODE: You are operating in plan mode"); | |
| 172 | + expect(result).toContain(PLAN_MODE_STRING); | |
| 171 | 173 | expect(result).toContain( |
| 172 | 174 | "which means that your goal is to help the user investigate their ideas", |
| 173 | 175 | ); |
| @@ -187,7 +189,7 @@ | ||
| 187 | 189 | ); |
| 188 | 190 | |
| 189 | 191 | expect(result).toContain("You are an agent in the Continue CLI"); |
| 190 | - expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); | |
| 192 | + expect(result).not.toContain(PLAN_MODE_STRING); | |
| 191 | 193 | expect(result).not.toContain( |
| 192 | 194 | "which means that your goal is to help the user investigate their ideas", |
| 193 | 195 | ); |
| @@ -197,7 +199,7 @@ | ||
| 197 | 199 | const result = await constructSystemMessage(); |
| 198 | 200 | |
| 199 | 201 | expect(result).toContain("You are an agent in the Continue CLI"); |
| 200 | - expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); | |
| 202 | + expect(result).not.toContain(PLAN_MODE_STRING); | |
| 201 | 203 | expect(result).not.toContain( |
| 202 | 204 | "which means that your goal is to help the user investigate their ideas", |
| 203 | 205 | ); |
| @@ -211,7 +213,7 @@ | ||
| 211 | 213 | "plan", |
| 212 | 214 | ); |
| 213 | 215 | |
| 214 | - expect(result).toContain("PLAN MODE: You are operating in plan mode"); | |
| 216 | + expect(result).toContain(PLAN_MODE_STRING); | |
| 215 | 217 | expect(result).toContain("read-only tools"); |
| 216 | 218 | expect(result).toContain("write / delete / create files"); |
| 217 | 219 | }); |
| @@ -225,7 +227,7 @@ | ||
| 225 | 227 | ); |
| 226 | 228 | |
| 227 | 229 | expect(result).toContain("IMPORTANT: You are running in headless mode"); |
| 228 | - expect(result).toContain("PLAN MODE: You are operating in plan mode"); | |
| 230 | + expect(result).toContain(PLAN_MODE_STRING); | |
| 229 | 231 | expect(result).toContain( |
| 230 | 232 | "which means that your goal is to help the user investigate their ideas", |
| 231 | 233 | ); |
| @@ -242,7 +244,7 @@ | ||
| 242 | 244 | expect(result).toContain( |
| 243 | 245 | "IMPORTANT: You are operating in JSON output mode", |
| 244 | 246 | ); |
| 245 | - expect(result).toContain("PLAN MODE: You are operating in plan mode"); | |
| 247 | + expect(result).toContain(PLAN_MODE_STRING); | |
| 246 | 248 | expect(result).toContain( |
| 247 | 249 | "which means that your goal is to help the user investigate their ideas", |
| 248 | 250 | ); |
modified extensions/cli/src/systemMessage.ts +6 −7
| @@ -172,6 +172,12 @@ | ||
| 172 | 172 | // Construct the comprehensive system message |
| 173 | 173 | let systemMessage = baseSystemMessage; |
| 174 | 174 | |
| 175 | + // Add plan mode specific instructions if in plan mode | |
| 176 | + if (currentMode === "plan") { | |
| 177 | + systemMessage += | |
| 178 | + '\n<context name="planMode">You are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.</context>\n'; | |
| 179 | + } | |
| 180 | + | |
| 175 | 181 | // In headless mode, add instructions to be concise and only provide final answers |
| 176 | 182 | if (headless) { |
| 177 | 183 | systemMessage += ` |
| @@ -191,13 +197,6 @@ | ||
| 191 | 197 | }`; |
| 192 | 198 | } |
| 193 | 199 | |
| 194 | - // Add plan mode specific instructions if in plan mode | |
| 195 | - if (currentMode === "plan") { | |
| 196 | - systemMessage += ` | |
| 197 | - | |
| 198 | -PLAN MODE: You are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.`; | |
| 199 | - } | |
| 200 | - | |
| 201 | 200 | // Add rules section if we have any rules or agent content |
| 202 | 201 | if (agentContent || processedRules.length > 0) { |
| 203 | 202 | systemMessage += '\n\n<context name="userRules">'; |
added extensions/cli/src/tools/ToolCallTitle.tsx +50 −0
| @@ -0,0 +1,50 @@ | ||
| 1 | +import { Text } from "ink"; | |
| 2 | +import React from "react"; | |
| 3 | + | |
| 4 | +import { formatToolArgument } from "./formatters.js"; | |
| 5 | + | |
| 6 | +import { getToolDisplayName } from "./index.js"; | |
| 7 | + | |
| 8 | +/** | |
| 9 | + * Formats a tool call with its arguments for display | |
| 10 | + * @param toolName The name of the tool | |
| 11 | + * @param args The tool arguments | |
| 12 | + * @returns A React node with bolded tool name like "<b>ToolName</b>(arg)" or just "<b>ToolName</b>" if no args | |
| 13 | + */ | |
| 14 | +export function ToolCallTitle(props: { toolName: string; args?: any }) { | |
| 15 | + const { toolName, args } = props; | |
| 16 | + | |
| 17 | + const displayName = getToolDisplayName(toolName); | |
| 18 | + | |
| 19 | + if (!args || Object.keys(args).length === 0) { | |
| 20 | + return <Text bold>{displayName}</Text>; | |
| 21 | + } | |
| 22 | + | |
| 23 | + // Get the first argument value if it's a simple one | |
| 24 | + let formattedValue = ""; | |
| 25 | + const [key, value] = Object.entries(args)[0]; | |
| 26 | + if ( | |
| 27 | + key.toLowerCase().includes("path") || | |
| 28 | + typeof value === "number" || | |
| 29 | + typeof value === "boolean" | |
| 30 | + ) { | |
| 31 | + formattedValue = formatToolArgument(value); | |
| 32 | + } else if (typeof value === "string") { | |
| 33 | + const valueLines = value.split("\n"); | |
| 34 | + if (valueLines.length === 1) { | |
| 35 | + formattedValue = formatToolArgument(value); | |
| 36 | + } else { | |
| 37 | + // For multi-line strings, show first line with ellipsis | |
| 38 | + const firstLine = valueLines[0].trim(); | |
| 39 | + formattedValue = firstLine | |
| 40 | + ? `${formatToolArgument(firstLine)}...` | |
| 41 | + : "..."; | |
| 42 | + } | |
| 43 | + } | |
| 44 | + | |
| 45 | + return ( | |
| 46 | + <Text> | |
| 47 | + <Text bold>{displayName}</Text>({formattedValue}) | |
| 48 | + </Text> | |
| 49 | + ); | |
| 50 | +} |
deleted extensions/cli/src/tools/formatters.test.ts +0 −100
| @@ -1,100 +0,0 @@ | ||
| 1 | -import { vi } from "vitest"; | |
| 2 | - | |
| 3 | -import { formatToolArgument } from "./formatters.js"; | |
| 4 | - | |
| 5 | -import { formatToolCall } from "./index.js"; | |
| 6 | - | |
| 7 | -describe("formatToolCall", () => { | |
| 8 | - beforeEach(() => { | |
| 9 | - // Mock process.cwd to return a consistent value | |
| 10 | - vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); | |
| 11 | - }); | |
| 12 | - | |
| 13 | - afterEach(() => { | |
| 14 | - vi.restoreAllMocks(); | |
| 15 | - }); | |
| 16 | - | |
| 17 | - it("should format tool name without arguments", () => { | |
| 18 | - expect(formatToolCall("Write")).toBe("Write"); | |
| 19 | - expect(formatToolCall("Read", {})).toBe("Read"); | |
| 20 | - expect(formatToolCall("non_existent_tool", null)).toBe("non_existent_tool"); | |
| 21 | - }); | |
| 22 | - | |
| 23 | - it("should format tool name with relative path argument", () => { | |
| 24 | - expect(formatToolCall("Write", { filepath: "README.md" })).toBe( | |
| 25 | - "Write(README.md)", | |
| 26 | - ); | |
| 27 | - expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe( | |
| 28 | - "Read(src/index.ts)", | |
| 29 | - ); | |
| 30 | - }); | |
| 31 | - | |
| 32 | - it("should convert absolute paths to relative paths", () => { | |
| 33 | - expect( | |
| 34 | - formatToolCall("Write", { | |
| 35 | - filepath: "/Users/test/project/README.md", | |
| 36 | - }), | |
| 37 | - ).toBe("Write(README.md)"); | |
| 38 | - | |
| 39 | - expect( | |
| 40 | - formatToolCall("Read", { | |
| 41 | - filepath: "/Users/test/project/src/components/App.tsx", | |
| 42 | - }), | |
| 43 | - ).toBe("Read(src/components/App.tsx)"); | |
| 44 | - }); | |
| 45 | - | |
| 46 | - it("should handle absolute paths outside the project", () => { | |
| 47 | - expect(formatToolCall("Write", { filepath: "/Users/other/file.txt" })).toBe( | |
| 48 | - "Write(../../other/file.txt)", | |
| 49 | - ); | |
| 50 | - }); | |
| 51 | - | |
| 52 | - it("should handle non-path arguments", () => { | |
| 53 | - expect(formatToolCall("Search", { pattern: "TODO" })).toBe("Search(TODO)"); | |
| 54 | - expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)"); | |
| 55 | - }); | |
| 56 | - | |
| 57 | - it("should use first argument when multiple are provided", () => { | |
| 58 | - expect( | |
| 59 | - formatToolCall("Write", { | |
| 60 | - filepath: "test.txt", | |
| 61 | - content: "Hello world", | |
| 62 | - }), | |
| 63 | - ).toBe("Write(test.txt)"); | |
| 64 | - }); | |
| 65 | -}); | |
| 66 | - | |
| 67 | -describe("formatToolArgument", () => { | |
| 68 | - beforeEach(() => { | |
| 69 | - vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); | |
| 70 | - }); | |
| 71 | - | |
| 72 | - afterEach(() => { | |
| 73 | - vi.restoreAllMocks(); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - it("should return empty string for null/undefined", () => { | |
| 77 | - expect(formatToolArgument(null)).toBe(""); | |
| 78 | - expect(formatToolArgument(undefined)).toBe(""); | |
| 79 | - }); | |
| 80 | - | |
| 81 | - it("should convert absolute paths to relative", () => { | |
| 82 | - expect(formatToolArgument("/Users/test/project/README.md")).toBe( | |
| 83 | - "README.md", | |
| 84 | - ); | |
| 85 | - expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( | |
| 86 | - "src/index.ts", | |
| 87 | - ); | |
| 88 | - }); | |
| 89 | - | |
| 90 | - it("should preserve relative paths", () => { | |
| 91 | - expect(formatToolArgument("README.md")).toBe("README.md"); | |
| 92 | - expect(formatToolArgument("./src/index.ts")).toBe("./src/index.ts"); | |
| 93 | - }); | |
| 94 | - | |
| 95 | - it("should handle non-string values", () => { | |
| 96 | - expect(formatToolArgument(123)).toBe("123"); | |
| 97 | - expect(formatToolArgument(true)).toBe("true"); | |
| 98 | - expect(formatToolArgument({ key: "value" })).toBe("[object Object]"); | |
| 99 | - }); | |
| 100 | -}); |
modified extensions/cli/src/tools/index.test.ts +1 −1
| @@ -1,4 +1,4 @@ | ||
| 1 | -import { getToolDisplayName, extractToolCalls } from "./index.js"; | |
| 1 | +import { extractToolCalls, getToolDisplayName } from "./index.js"; | |
| 2 | 2 | |
| 3 | 3 | describe("tools/index utilities", () => { |
| 4 | 4 | describe("getToolDisplayName", () => { |
deleted extensions/cli/src/tools/index.ts +0 −236
| @@ -1,236 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - getServiceSync, | |
| 3 | - MCPServiceState, | |
| 4 | - SERVICE_NAMES, | |
| 5 | - serviceContainer, | |
| 6 | -} from "../services/index.js"; | |
| 7 | -import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; | |
| 8 | -import { telemetryService } from "../telemetry/telemetryService.js"; | |
| 9 | -import { logger } from "../util/logger.js"; | |
| 10 | - | |
| 11 | -import { editTool } from "./edit.js"; | |
| 12 | -import { exitTool } from "./exit.js"; | |
| 13 | -import { fetchTool } from "./fetch.js"; | |
| 14 | -import { formatToolArgument } from "./formatters.js"; | |
| 15 | -import { listFilesTool } from "./listFiles.js"; | |
| 16 | -import { multiEditTool } from "./multiEdit.js"; | |
| 17 | -import { readFileTool } from "./readFile.js"; | |
| 18 | -import { runTerminalCommandTool } from "./runTerminalCommand.js"; | |
| 19 | -import { searchCodeTool } from "./searchCode.js"; | |
| 20 | -import { | |
| 21 | - type Tool, | |
| 22 | - type ToolCall, | |
| 23 | - type ToolParameters, | |
| 24 | - PreprocessedToolCall, | |
| 25 | -} from "./types.js"; | |
| 26 | -import { writeChecklistTool } from "./writeChecklist.js"; | |
| 27 | -import { writeFileTool } from "./writeFile.js"; | |
| 28 | - | |
| 29 | -export type { Tool, ToolCall, ToolParameters }; | |
| 30 | - | |
| 31 | -// Base tools that are always available | |
| 32 | -const BASE_BUILTIN_TOOLS: Tool[] = [ | |
| 33 | - readFileTool, | |
| 34 | - editTool, | |
| 35 | - multiEditTool, | |
| 36 | - writeFileTool, | |
| 37 | - // searchAndReplaceInFileTool, | |
| 38 | - listFilesTool, | |
| 39 | - searchCodeTool, | |
| 40 | - runTerminalCommandTool, | |
| 41 | - fetchTool, | |
| 42 | - writeChecklistTool, | |
| 43 | -]; | |
| 44 | - | |
| 45 | -// Export BUILTIN_TOOLS as the base set of tools | |
| 46 | -// Dynamic tools (like exit tool in headless mode) are added separately | |
| 47 | -export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; | |
| 48 | - | |
| 49 | -// Get dynamic tools based on current state | |
| 50 | -function getDynamicTools(): Tool[] { | |
| 51 | - const dynamicTools: Tool[] = []; | |
| 52 | - | |
| 53 | - // Add headless-specific tools if in headless mode | |
| 54 | - try { | |
| 55 | - const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 56 | - SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 57 | - ); | |
| 58 | - const isHeadless = serviceResult.value?.isHeadless ?? false; | |
| 59 | - if (isHeadless) { | |
| 60 | - dynamicTools.push(exitTool); | |
| 61 | - } | |
| 62 | - } catch { | |
| 63 | - // Service not ready yet, no dynamic tools | |
| 64 | - } | |
| 65 | - | |
| 66 | - return dynamicTools; | |
| 67 | -} | |
| 68 | - | |
| 69 | -// Get all builtin tools including dynamic ones | |
| 70 | -export function getAllBuiltinTools(): Tool[] { | |
| 71 | - return [...BUILTIN_TOOLS, ...getDynamicTools()]; | |
| 72 | -} | |
| 73 | - | |
| 74 | -export function getToolDisplayName(toolName: string): string { | |
| 75 | - const allTools = getAllBuiltinTools(); | |
| 76 | - const tool = allTools.find((t) => t.name === toolName); | |
| 77 | - return tool?.displayName || toolName; | |
| 78 | -} | |
| 79 | - | |
| 80 | -export function extractToolCalls( | |
| 81 | - response: string, | |
| 82 | -): Array<{ name: string; arguments: Record<string, any> }> { | |
| 83 | - const toolCallRegex = /<tool>([\s\S]*?)<\/tool>/g; | |
| 84 | - const matches = [...response.matchAll(toolCallRegex)]; | |
| 85 | - | |
| 86 | - const toolCalls = []; | |
| 87 | - | |
| 88 | - for (const match of matches) { | |
| 89 | - try { | |
| 90 | - const toolCallJson = JSON.parse(match[1]); | |
| 91 | - if (toolCallJson.name && toolCallJson.arguments) { | |
| 92 | - toolCalls.push({ | |
| 93 | - name: toolCallJson.name, | |
| 94 | - arguments: toolCallJson.arguments, | |
| 95 | - }); | |
| 96 | - } | |
| 97 | - } catch { | |
| 98 | - logger.error("Failed to parse tool call:", { toolCall: match[1] }); | |
| 99 | - } | |
| 100 | - } | |
| 101 | - | |
| 102 | - return toolCalls; | |
| 103 | -} | |
| 104 | - | |
| 105 | -function convertInputSchemaToParameters(inputSchema: any): ToolParameters { | |
| 106 | - const parameters: Record< | |
| 107 | - string, | |
| 108 | - { type: string; description: string; required: boolean } | |
| 109 | - > = {}; | |
| 110 | - for (const [key, value] of Object.entries(inputSchema.properties)) { | |
| 111 | - const val = value as any; | |
| 112 | - parameters[key] = { | |
| 113 | - type: val.type, | |
| 114 | - description: val.description || "", | |
| 115 | - required: inputSchema.required?.includes(key) || false, | |
| 116 | - }; | |
| 117 | - } | |
| 118 | - return parameters; | |
| 119 | -} | |
| 120 | - | |
| 121 | -export async function getAvailableTools() { | |
| 122 | - // Load MCP tools | |
| 123 | - const mcpState = await serviceContainer.get<MCPServiceState>( | |
| 124 | - SERVICE_NAMES.MCP, | |
| 125 | - ); | |
| 126 | - const tools = mcpState.tools ?? []; | |
| 127 | - const mcpTools: Tool[] = | |
| 128 | - tools.map((t) => ({ | |
| 129 | - name: t.name, | |
| 130 | - displayName: t.name.replace("mcp__", "").replace("ide__", ""), | |
| 131 | - description: t.description ?? "", | |
| 132 | - parameters: convertInputSchemaToParameters(t.inputSchema), | |
| 133 | - readonly: undefined, // MCP tools don't have readonly property | |
| 134 | - isBuiltIn: false, | |
| 135 | - run: async (args: any) => { | |
| 136 | - const result = await mcpState.mcpService?.runTool(t.name, args); | |
| 137 | - return JSON.stringify(result?.content) ?? ""; | |
| 138 | - }, | |
| 139 | - })) || []; | |
| 140 | - | |
| 141 | - const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; | |
| 142 | - return allTools; | |
| 143 | -} | |
| 144 | - | |
| 145 | -export async function executeToolCall( | |
| 146 | - toolCall: PreprocessedToolCall, | |
| 147 | -): Promise<string> { | |
| 148 | - const startTime = Date.now(); | |
| 149 | - | |
| 150 | - try { | |
| 151 | - logger.debug("Executing tool", { | |
| 152 | - toolName: toolCall.name, | |
| 153 | - arguments: toolCall.arguments, | |
| 154 | - }); | |
| 155 | - | |
| 156 | - // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args | |
| 157 | - // Preprocessed arg names may be different | |
| 158 | - const result = await toolCall.tool.run( | |
| 159 | - toolCall.preprocessResult?.args ?? toolCall.arguments, | |
| 160 | - ); | |
| 161 | - const duration = Date.now() - startTime; | |
| 162 | - | |
| 163 | - telemetryService.logToolResult({ | |
| 164 | - toolName: toolCall.name, | |
| 165 | - success: true, | |
| 166 | - durationMs: duration, | |
| 167 | - toolParameters: JSON.stringify(toolCall.arguments), | |
| 168 | - }); | |
| 169 | - | |
| 170 | - logger.debug("Tool execution completed", { | |
| 171 | - toolName: toolCall.name, | |
| 172 | - resultLength: result?.length || 0, | |
| 173 | - }); | |
| 174 | - | |
| 175 | - return result; | |
| 176 | - } catch (error) { | |
| 177 | - const duration = Date.now() - startTime; | |
| 178 | - const errorMessage = error instanceof Error ? error.message : String(error); | |
| 179 | - | |
| 180 | - telemetryService.logToolResult({ | |
| 181 | - toolName: toolCall.name, | |
| 182 | - success: false, | |
| 183 | - durationMs: duration, | |
| 184 | - error: errorMessage, | |
| 185 | - toolParameters: JSON.stringify(toolCall.arguments), | |
| 186 | - }); | |
| 187 | - | |
| 188 | - return `Error executing tool "${toolCall.name}": ${errorMessage}`; | |
| 189 | - } | |
| 190 | -} | |
| 191 | - | |
| 192 | -export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { | |
| 193 | - for (const [paramName, paramDef] of Object.entries(tool.parameters)) { | |
| 194 | - if ( | |
| 195 | - paramDef.required && | |
| 196 | - (toolCall.arguments[paramName] === undefined || | |
| 197 | - toolCall.arguments[paramName] === null) | |
| 198 | - ) { | |
| 199 | - throw new Error( | |
| 200 | - `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, | |
| 201 | - ); | |
| 202 | - } | |
| 203 | - } | |
| 204 | -} | |
| 205 | - | |
| 206 | -/** | |
| 207 | - * Formats a tool call with its arguments for display | |
| 208 | - * @param toolName The name of the tool | |
| 209 | - * @param args The tool arguments | |
| 210 | - * @returns A formatted string like "ToolName(arg)" or just "ToolName" if no args | |
| 211 | - */ | |
| 212 | -export function formatToolCall(toolName: string, args?: any): string { | |
| 213 | - const displayName = getToolDisplayName(toolName); | |
| 214 | - | |
| 215 | - if (!args || Object.keys(args).length === 0) { | |
| 216 | - return displayName; | |
| 217 | - } | |
| 218 | - | |
| 219 | - // Get the first argument value if it's a simple one | |
| 220 | - let formattedValue = ""; | |
| 221 | - const [key, value] = Object.entries(args)[0]; | |
| 222 | - if ( | |
| 223 | - key.toLowerCase().includes("path") || | |
| 224 | - typeof value === "number" || | |
| 225 | - typeof value === "boolean" | |
| 226 | - ) { | |
| 227 | - formattedValue = formatToolArgument(value); | |
| 228 | - } else if (typeof value === "string") { | |
| 229 | - const valueLines = value.split("\n"); | |
| 230 | - if (valueLines.length === 1) { | |
| 231 | - formattedValue = formatToolArgument(value); | |
| 232 | - } | |
| 233 | - } | |
| 234 | - | |
| 235 | - return `${displayName}(${formattedValue})`; | |
| 236 | -} |
added extensions/cli/src/tools/index.tsx +204 −0
| @@ -0,0 +1,204 @@ | ||
| 1 | +// @ts-ignore | |
| 2 | +import { | |
| 3 | + getServiceSync, | |
| 4 | + MCPServiceState, | |
| 5 | + SERVICE_NAMES, | |
| 6 | + serviceContainer, | |
| 7 | +} from "../services/index.js"; | |
| 8 | +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; | |
| 9 | +import { telemetryService } from "../telemetry/telemetryService.js"; | |
| 10 | +import { logger } from "../util/logger.js"; | |
| 11 | + | |
| 12 | +import { editTool } from "./edit.js"; | |
| 13 | +import { exitTool } from "./exit.js"; | |
| 14 | +import { fetchTool } from "./fetch.js"; | |
| 15 | +import { listFilesTool } from "./listFiles.js"; | |
| 16 | +import { multiEditTool } from "./multiEdit.js"; | |
| 17 | +import { readFileTool } from "./readFile.js"; | |
| 18 | +import { runTerminalCommandTool } from "./runTerminalCommand.js"; | |
| 19 | +import { searchCodeTool } from "./searchCode.js"; | |
| 20 | +import { | |
| 21 | + type Tool, | |
| 22 | + type ToolCall, | |
| 23 | + type ToolParameters, | |
| 24 | + PreprocessedToolCall, | |
| 25 | +} from "./types.js"; | |
| 26 | +import { writeChecklistTool } from "./writeChecklist.js"; | |
| 27 | +import { writeFileTool } from "./writeFile.js"; | |
| 28 | + | |
| 29 | +export type { Tool, ToolCall, ToolParameters }; | |
| 30 | + | |
| 31 | +// Base tools that are always available | |
| 32 | +const BASE_BUILTIN_TOOLS: Tool[] = [ | |
| 33 | + readFileTool, | |
| 34 | + editTool, | |
| 35 | + multiEditTool, | |
| 36 | + writeFileTool, | |
| 37 | + // searchAndReplaceInFileTool, | |
| 38 | + listFilesTool, | |
| 39 | + searchCodeTool, | |
| 40 | + runTerminalCommandTool, | |
| 41 | + fetchTool, | |
| 42 | + writeChecklistTool, | |
| 43 | +]; | |
| 44 | + | |
| 45 | +// Export BUILTIN_TOOLS as the base set of tools | |
| 46 | +// Dynamic tools (like exit tool in headless mode) are added separately | |
| 47 | +export const BUILTIN_TOOLS: Tool[] = BASE_BUILTIN_TOOLS; | |
| 48 | + | |
| 49 | +// Get dynamic tools based on current state | |
| 50 | +function getDynamicTools(): Tool[] { | |
| 51 | + const dynamicTools: Tool[] = []; | |
| 52 | + | |
| 53 | + // Add headless-specific tools if in headless mode | |
| 54 | + try { | |
| 55 | + const serviceResult = getServiceSync<ToolPermissionServiceState>( | |
| 56 | + SERVICE_NAMES.TOOL_PERMISSIONS, | |
| 57 | + ); | |
| 58 | + const isHeadless = serviceResult.value?.isHeadless ?? false; | |
| 59 | + if (isHeadless) { | |
| 60 | + dynamicTools.push(exitTool); | |
| 61 | + } | |
| 62 | + } catch { | |
| 63 | + // Service not ready yet, no dynamic tools | |
| 64 | + } | |
| 65 | + | |
| 66 | + return dynamicTools; | |
| 67 | +} | |
| 68 | + | |
| 69 | +// Get all builtin tools including dynamic ones | |
| 70 | +export function getAllBuiltinTools(): Tool[] { | |
| 71 | + return [...BUILTIN_TOOLS, ...getDynamicTools()]; | |
| 72 | +} | |
| 73 | + | |
| 74 | +export function getToolDisplayName(toolName: string): string { | |
| 75 | + const allTools = getAllBuiltinTools(); | |
| 76 | + const tool = allTools.find((t) => t.name === toolName); | |
| 77 | + return tool?.displayName || toolName; | |
| 78 | +} | |
| 79 | + | |
| 80 | +export function extractToolCalls( | |
| 81 | + response: string, | |
| 82 | +): Array<{ name: string; arguments: Record<string, any> }> { | |
| 83 | + const toolCallRegex = /<tool>([\s\S]*?)<\/tool>/g; | |
| 84 | + const matches = [...response.matchAll(toolCallRegex)]; | |
| 85 | + | |
| 86 | + const toolCalls = []; | |
| 87 | + | |
| 88 | + for (const match of matches) { | |
| 89 | + try { | |
| 90 | + const toolCallJson = JSON.parse(match[1]); | |
| 91 | + if (toolCallJson.name && toolCallJson.arguments) { | |
| 92 | + toolCalls.push({ | |
| 93 | + name: toolCallJson.name, | |
| 94 | + arguments: toolCallJson.arguments, | |
| 95 | + }); | |
| 96 | + } | |
| 97 | + } catch { | |
| 98 | + logger.error("Failed to parse tool call:", { toolCall: match[1] }); | |
| 99 | + } | |
| 100 | + } | |
| 101 | + | |
| 102 | + return toolCalls; | |
| 103 | +} | |
| 104 | + | |
| 105 | +function convertInputSchemaToParameters(inputSchema: any): ToolParameters { | |
| 106 | + const parameters: Record< | |
| 107 | + string, | |
| 108 | + { type: string; description: string; required: boolean } | |
| 109 | + > = {}; | |
| 110 | + for (const [key, value] of Object.entries(inputSchema.properties)) { | |
| 111 | + const val = value as any; | |
| 112 | + parameters[key] = { | |
| 113 | + type: val.type, | |
| 114 | + description: val.description || "", | |
| 115 | + required: inputSchema.required?.includes(key) || false, | |
| 116 | + }; | |
| 117 | + } | |
| 118 | + return parameters; | |
| 119 | +} | |
| 120 | + | |
| 121 | +export async function getAvailableTools() { | |
| 122 | + // Load MCP tools | |
| 123 | + const mcpState = await serviceContainer.get<MCPServiceState>( | |
| 124 | + SERVICE_NAMES.MCP, | |
| 125 | + ); | |
| 126 | + const tools = mcpState.tools ?? []; | |
| 127 | + const mcpTools: Tool[] = | |
| 128 | + tools.map((t) => ({ | |
| 129 | + name: t.name, | |
| 130 | + displayName: t.name.replace("mcp__", "").replace("ide__", ""), | |
| 131 | + description: t.description ?? "", | |
| 132 | + parameters: convertInputSchemaToParameters(t.inputSchema), | |
| 133 | + readonly: undefined, // MCP tools don't have readonly property | |
| 134 | + isBuiltIn: false, | |
| 135 | + run: async (args: any) => { | |
| 136 | + const result = await mcpState.mcpService?.runTool(t.name, args); | |
| 137 | + return JSON.stringify(result?.content) ?? ""; | |
| 138 | + }, | |
| 139 | + })) || []; | |
| 140 | + | |
| 141 | + const allTools: Tool[] = [...getAllBuiltinTools(), ...mcpTools]; | |
| 142 | + return allTools; | |
| 143 | +} | |
| 144 | + | |
| 145 | +export async function executeToolCall( | |
| 146 | + toolCall: PreprocessedToolCall, | |
| 147 | +): Promise<string> { | |
| 148 | + const startTime = Date.now(); | |
| 149 | + | |
| 150 | + try { | |
| 151 | + logger.debug("Executing tool", { | |
| 152 | + toolName: toolCall.name, | |
| 153 | + arguments: toolCall.arguments, | |
| 154 | + }); | |
| 155 | + | |
| 156 | + // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args | |
| 157 | + // Preprocessed arg names may be different | |
| 158 | + const result = await toolCall.tool.run( | |
| 159 | + toolCall.preprocessResult?.args ?? toolCall.arguments, | |
| 160 | + ); | |
| 161 | + const duration = Date.now() - startTime; | |
| 162 | + | |
| 163 | + telemetryService.logToolResult({ | |
| 164 | + toolName: toolCall.name, | |
| 165 | + success: true, | |
| 166 | + durationMs: duration, | |
| 167 | + toolParameters: JSON.stringify(toolCall.arguments), | |
| 168 | + }); | |
| 169 | + | |
| 170 | + logger.debug("Tool execution completed", { | |
| 171 | + toolName: toolCall.name, | |
| 172 | + resultLength: result?.length || 0, | |
| 173 | + }); | |
| 174 | + | |
| 175 | + return result; | |
| 176 | + } catch (error) { | |
| 177 | + const duration = Date.now() - startTime; | |
| 178 | + const errorMessage = error instanceof Error ? error.message : String(error); | |
| 179 | + | |
| 180 | + telemetryService.logToolResult({ | |
| 181 | + toolName: toolCall.name, | |
| 182 | + success: false, | |
| 183 | + durationMs: duration, | |
| 184 | + error: errorMessage, | |
| 185 | + toolParameters: JSON.stringify(toolCall.arguments), | |
| 186 | + }); | |
| 187 | + | |
| 188 | + return `Error executing tool "${toolCall.name}": ${errorMessage}`; | |
| 189 | + } | |
| 190 | +} | |
| 191 | + | |
| 192 | +export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { | |
| 193 | + for (const [paramName, paramDef] of Object.entries(tool.parameters)) { | |
| 194 | + if ( | |
| 195 | + paramDef.required && | |
| 196 | + (toolCall.arguments[paramName] === undefined || | |
| 197 | + toolCall.arguments[paramName] === null) | |
| 198 | + ) { | |
| 199 | + throw new Error( | |
| 200 | + `Required parameter "${paramName}" missing for tool "${toolCall.name}"`, | |
| 201 | + ); | |
| 202 | + } | |
| 203 | + } | |
| 204 | +} |
modified extensions/cli/src/ui/IntroMessage.tsx +5 −0
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | import { Box, Text } from "ink"; |
| 3 | 3 | import React, { useMemo } from "react"; |
| 4 | 4 | |
| 5 | +import { getDisplayableAsciiArt } from "../asciiArt.js"; | |
| 5 | 6 | import { MCPService } from "../services/MCPService.js"; |
| 6 | 7 | import { isModelCapable } from "../utils/modelCapability.js"; |
| 7 | 8 | |
| @@ -41,6 +42,10 @@ | ||
| 41 | 42 | |
| 42 | 43 | return ( |
| 43 | 44 | <Box flexDirection="column" paddingX={1} paddingY={1}> |
| 45 | + {/* ASCII Art */} | |
| 46 | + <Text>{getDisplayableAsciiArt()}</Text> | |
| 47 | + <Text> </Text> | |
| 48 | + | |
| 44 | 49 | {/* Agent name */} |
| 45 | 50 | {config && ( |
| 46 | 51 | <Text color="blue"> |
modified extensions/cli/src/ui/TUIChat.tsx +1 −1
| @@ -231,7 +231,7 @@ | ||
| 231 | 231 | const { handleConfigSelect, handleModelSelect } = useSelectors( |
| 232 | 232 | configPath, |
| 233 | 233 | setChatHistory, |
| 234 | - resetChatHistory, | |
| 234 | + handleClear, | |
| 235 | 235 | ); |
| 236 | 236 | |
| 237 | 237 | // Session selection handler |
modified extensions/cli/src/ui/ToolResultSummary.tsx +1 −1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | import { Box, Text } from "ink"; |
| 4 | 4 | import React from "react"; |
| 5 | 5 | |
| 6 | -import { getToolDisplayName } from "../tools/index.js"; | |
| 6 | +import { getToolDisplayName } from "src/tools/index.js"; | |
| 7 | 7 | |
| 8 | 8 | import { ColoredDiff } from "./ColoredDiff.js"; |
| 9 | 9 | import { ChecklistDisplay } from "./components/ChecklistDisplay.js"; |
modified extensions/cli/src/ui/UserInput.tsx +21 −0
| @@ -386,6 +386,27 @@ | ||
| 386 | 386 | |
| 387 | 387 | const handleEnterKey = (key: any): boolean => { |
| 388 | 388 | if (key.return && !key.shift) { |
| 389 | + // Check for backslash continuation | |
| 390 | + const beforeCursor = textBuffer.text.slice(0, cursorPosition); | |
| 391 | + const trimmedBeforeCursor = beforeCursor.trimEnd(); | |
| 392 | + | |
| 393 | + if (trimmedBeforeCursor.endsWith("\\")) { | |
| 394 | + // Handle backslash continuation: remove the trailing "\" and add newline | |
| 395 | + const beforeBackslash = trimmedBeforeCursor.slice(0, -1); | |
| 396 | + const afterCursor = textBuffer.text.slice(cursorPosition); | |
| 397 | + const newText = beforeBackslash + "\n" + afterCursor; | |
| 398 | + const newCursorPos = beforeBackslash.length + 1; | |
| 399 | + | |
| 400 | + textBuffer.setText(newText); | |
| 401 | + textBuffer.setCursor(newCursorPos); | |
| 402 | + setInputText(newText); | |
| 403 | + setCursorPosition(newCursorPos); | |
| 404 | + updateSlashCommandState(newText, newCursorPos); | |
| 405 | + updateFileSearchState(newText, newCursorPos); | |
| 406 | + return true; | |
| 407 | + } | |
| 408 | + | |
| 409 | + // Normal Enter behavior - submit if there's content | |
| 389 | 410 | if (textBuffer.text.trim() && !isWaitingForResponse) { |
| 390 | 411 | // Expand all paste blocks before submitting |
| 391 | 412 | textBuffer.expandAllPasteBlocks(); |
modified extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +2 −1
| @@ -2,9 +2,10 @@ | ||
| 2 | 2 | import React from "react"; |
| 3 | 3 | import { afterEach, beforeEach, describe, expect, it } from "vitest"; |
| 4 | 4 | |
| 5 | +import { getAllTools } from "src/stream/handleToolCalls.js"; | |
| 6 | + | |
| 5 | 7 | import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; |
| 6 | 8 | import { modeService } from "../../services/ModeService.js"; |
| 7 | -import { getAllTools } from "../../streamChatResponse.js"; | |
| 8 | 9 | import { createUITestContext } from "../../test-helpers/ui-test-context.js"; |
| 9 | 10 | import { AppRoot } from "../AppRoot.js"; |
| 10 | 11 |
modified extensions/cli/src/ui/components/MemoizedMessage.tsx +3 −2
| @@ -1,8 +1,9 @@ | ||
| 1 | 1 | import { Box, Text } from "ink"; |
| 2 | 2 | import React, { memo } from "react"; |
| 3 | 3 | |
| 4 | +import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; | |
| 5 | + | |
| 4 | 6 | import type { ChatHistoryItem } from "../../../../../core/index.js"; |
| 5 | -import { formatToolCall } from "../../tools/index.js"; | |
| 6 | 7 | import { MarkdownRenderer } from "../MarkdownRenderer.js"; |
| 7 | 8 | import { ToolResultSummary } from "../ToolResultSummary.js"; |
| 8 | 9 | |
| @@ -92,7 +93,7 @@ | ||
| 92 | 93 | </Text> |
| 93 | 94 | <Text color="white"> |
| 94 | 95 | {" "} |
| 95 | - {formatToolCall(toolName, toolArgs)} | |
| 96 | + <ToolCallTitle toolName={toolName} args={toolArgs} /> | |
| 96 | 97 | </Text> |
| 97 | 98 | </Box> |
| 98 | 99 |
modified extensions/cli/src/ui/components/ToolPermissionSelector.tsx +3 −4
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | import { Box, Text, useInput } from "ink"; |
| 2 | 2 | import React, { useState } from "react"; |
| 3 | 3 | |
| 4 | -import { formatToolCall } from "../../tools/index.js"; | |
| 4 | +import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; | |
| 5 | + | |
| 5 | 6 | import { ToolCallPreview } from "../../tools/types.js"; |
| 6 | 7 | |
| 7 | 8 | import { ToolPreview } from "./ToolPreview.js"; |
| @@ -101,8 +102,6 @@ | ||
| 101 | 102 | } |
| 102 | 103 | }); |
| 103 | 104 | |
| 104 | - const toolCallDisplay = formatToolCall(toolName, toolArgs); | |
| 105 | - | |
| 106 | 105 | return ( |
| 107 | 106 | <Box |
| 108 | 107 | flexDirection="column" |
| @@ -111,7 +110,7 @@ | ||
| 111 | 110 | borderColor="magenta" |
| 112 | 111 | > |
| 113 | 112 | <Text color="magenta" bold> |
| 114 | - {toolCallDisplay} | |
| 113 | + <ToolCallTitle toolName={toolName} args={toolArgs} /> | |
| 115 | 114 | </Text> |
| 116 | 115 | |
| 117 | 116 | {/* Show preview of what the tool will do */} |
modified extensions/cli/src/ui/hooks/useChat.clear.test.ts +28 −1
| @@ -1,16 +1,27 @@ | ||
| 1 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 1 | 2 | import { ChatCompletionMessageParam } from "openai/resources.mjs"; |
| 2 | 3 | import { beforeEach, describe, expect, it, vi } from "vitest"; |
| 3 | 4 | |
| 4 | -import { convertToUnifiedHistory } from "../../messageConversion.js"; | |
| 5 | +import { startNewSession } from "../../session.js"; | |
| 5 | 6 | |
| 6 | 7 | import { processSlashCommandResult } from "./useChat.helpers.js"; |
| 7 | 8 | |
| 9 | +// Mock the session module | |
| 10 | +vi.mock("../../session.js", () => ({ | |
| 11 | + loadSession: vi.fn(), | |
| 12 | + updateSessionHistory: vi.fn(), | |
| 13 | + startNewSession: vi.fn(), | |
| 14 | +})); | |
| 15 | + | |
| 8 | 16 | describe("useChat clear command", () => { |
| 9 | 17 | let mockSetChatHistory: ReturnType<typeof vi.fn>; |
| 10 | 18 | let mockExit: ReturnType<typeof vi.fn>; |
| 11 | 19 | let mockOnClear: ReturnType<typeof vi.fn>; |
| 12 | 20 | |
| 13 | 21 | beforeEach(() => { |
| 22 | + // Clear all mocks to prevent call history leaking between tests | |
| 23 | + vi.clearAllMocks(); | |
| 24 | + | |
| 14 | 25 | mockSetChatHistory = vi.fn(); |
| 15 | 26 | mockExit = vi.fn(); |
| 16 | 27 | mockOnClear = vi.fn(); |
| @@ -41,6 +52,11 @@ | ||
| 41 | 52 | // Verify that onClear was called |
| 42 | 53 | expect(mockOnClear).toHaveBeenCalledOnce(); |
| 43 | 54 | |
| 55 | + // Verify that a new session was started with the system message | |
| 56 | + expect(startNewSession).toHaveBeenCalledWith([ | |
| 57 | + chatHistory[0], // The system message ChatHistoryItem | |
| 58 | + ]); | |
| 59 | + | |
| 44 | 60 | // Verify that chat history was reset (keeping only system message) |
| 45 | 61 | expect(mockSetChatHistory).toHaveBeenCalledWith([ |
| 46 | 62 | chatHistory[0], // The system message ChatHistoryItem |
| @@ -81,6 +97,11 @@ | ||
| 81 | 97 | }); |
| 82 | 98 | }).not.toThrow(); |
| 83 | 99 | |
| 100 | + // Verify that a new session was started with the system message | |
| 101 | + expect(startNewSession).toHaveBeenCalledWith([ | |
| 102 | + chatHistory[0], // The system message ChatHistoryItem | |
| 103 | + ]); | |
| 104 | + | |
| 84 | 105 | // Verify that history is still reset |
| 85 | 106 | expect(mockSetChatHistory).toHaveBeenCalledWith([ |
| 86 | 107 | chatHistory[0], // The system message ChatHistoryItem |
| @@ -111,6 +132,9 @@ | ||
| 111 | 132 | onClear: mockOnClear, |
| 112 | 133 | }); |
| 113 | 134 | |
| 135 | + // Verify that a new session was started with the system message | |
| 136 | + expect(startNewSession).toHaveBeenCalledWith([systemHistoryItem]); | |
| 137 | + | |
| 114 | 138 | // Should keep only the system message |
| 115 | 139 | expect(mockSetChatHistory).toHaveBeenCalledWith([systemHistoryItem]); |
| 116 | 140 | expect(mockOnClear).toHaveBeenCalledOnce(); |
| @@ -130,6 +154,9 @@ | ||
| 130 | 154 | onClear: mockOnClear, |
| 131 | 155 | }); |
| 132 | 156 | |
| 157 | + // Verify that a new session was started with empty history | |
| 158 | + expect(startNewSession).toHaveBeenCalledWith([]); | |
| 159 | + | |
| 133 | 160 | // Should set empty history when no system message exists |
| 134 | 161 | expect(mockSetChatHistory).toHaveBeenCalledWith([]); |
| 135 | 162 | expect(mockOnClear).toHaveBeenCalledOnce(); |
modified extensions/cli/src/ui/hooks/useChat.helpers.ts +52 −9
| @@ -4,9 +4,13 @@ | ||
| 4 | 4 | import { getLastNPathParts } from "core/util/uri.js"; |
| 5 | 5 | import { v4 as uuidv4 } from "uuid"; |
| 6 | 6 | |
| 7 | -import { initializeChatHistory } from "../../commands/chat.js"; | |
| 8 | 7 | import { compactChatHistory } from "../../compaction.js"; |
| 9 | -import { loadSession, updateSessionHistory } from "../../session.js"; | |
| 8 | +import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; | |
| 9 | +import { | |
| 10 | + loadSession, | |
| 11 | + updateSessionHistory, | |
| 12 | + startNewSession, | |
| 13 | +} from "../../session.js"; | |
| 10 | 14 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 11 | 15 | import { telemetryService } from "../../telemetry/telemetryService.js"; |
| 12 | 16 | import { formatError } from "../../util/formatError.js"; |
| @@ -16,11 +20,11 @@ | ||
| 16 | 20 | import { SlashCommandResult } from "./useChat.types.js"; |
| 17 | 21 | |
| 18 | 22 | /** |
| 19 | - * Initialize chat history with proper system message | |
| 23 | + * Initialize chat history | |
| 20 | 24 | */ |
| 21 | 25 | export async function initChatHistory( |
| 22 | 26 | resume?: boolean, |
| 23 | - additionalRules?: string[], | |
| 27 | + _additionalRules?: string[], | |
| 24 | 28 | ): Promise<ChatHistoryItem[]> { |
| 25 | 29 | if (resume) { |
| 26 | 30 | const savedSession = loadSession(); |
| @@ -29,11 +33,8 @@ | ||
| 29 | 33 | } |
| 30 | 34 | } |
| 31 | 35 | |
| 32 | - const history = await initializeChatHistory({ | |
| 33 | - resume, | |
| 34 | - rule: additionalRules, | |
| 35 | - }); | |
| 36 | - return history; | |
| 36 | + // Start with empty history - system message will be injected when needed | |
| 37 | + return []; | |
| 37 | 38 | } |
| 38 | 39 | |
| 39 | 40 | /** |
| @@ -177,6 +178,10 @@ | ||
| 177 | 178 | (item) => item.message.role === "system", |
| 178 | 179 | ); |
| 179 | 180 | const newHistory = systemMessage ? [systemMessage] : []; |
| 181 | + | |
| 182 | + // Start a new session with a new sessionId | |
| 183 | + startNewSession(newHistory); | |
| 184 | + | |
| 180 | 185 | setChatHistory(newHistory); |
| 181 | 186 | |
| 182 | 187 | // Reset intro message state to show it again after clearing |
| @@ -407,3 +412,41 @@ | ||
| 407 | 412 | }; |
| 408 | 413 | } |
| 409 | 414 | } |
| 415 | + | |
| 416 | +/** | |
| 417 | + * Generate a title for the session based on the first assistant response | |
| 418 | + */ | |
| 419 | +export async function generateSessionTitle( | |
| 420 | + assistantResponse: string, | |
| 421 | + llmApi: any, | |
| 422 | + model: any, | |
| 423 | + currentSessionTitle?: string, | |
| 424 | +): Promise<string | undefined> { | |
| 425 | + // Only generate title for untitled sessions | |
| 426 | + if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) { | |
| 427 | + return undefined; | |
| 428 | + } | |
| 429 | + | |
| 430 | + if (!assistantResponse || !llmApi || !model) { | |
| 431 | + return undefined; | |
| 432 | + } | |
| 433 | + | |
| 434 | + try { | |
| 435 | + const { ChatDescriber } = await import("core/util/chatDescriber.js"); | |
| 436 | + const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( | |
| 437 | + llmApi, | |
| 438 | + model, | |
| 439 | + assistantResponse, | |
| 440 | + ); | |
| 441 | + | |
| 442 | + logger.debug("Generated session title", { | |
| 443 | + original: currentSessionTitle, | |
| 444 | + generated: generatedTitle, | |
| 445 | + }); | |
| 446 | + | |
| 447 | + return generatedTitle; | |
| 448 | + } catch (error) { | |
| 449 | + logger.error("Failed to generate session title:", error); | |
| 450 | + return undefined; | |
| 451 | + } | |
| 452 | +} |
modified extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +1 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import type { ChatHistoryItem } from "core/index.js"; |
| 2 | +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; | |
| 2 | 3 | |
| 3 | -import { convertToUnifiedHistory } from "../../messageConversion.js"; | |
| 4 | 4 | import { posthogService } from "../../telemetry/posthogService.js"; |
| 5 | 5 | import { logger } from "../../util/logger.js"; |
| 6 | 6 |
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +26 −3
| @@ -1,8 +1,14 @@ | ||
| 1 | 1 | import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; |
| 2 | 2 | |
| 3 | +import { getCurrentSession, updateSessionTitle } from "../../session.js"; | |
| 4 | + | |
| 5 | +import { generateSessionTitle } from "./useChat.helpers.js"; | |
| 6 | + | |
| 3 | 7 | interface CreateStreamCallbacksOptions { |
| 4 | 8 | setChatHistory: React.Dispatch<React.SetStateAction<ChatHistoryItem[]>>; |
| 5 | 9 | setActivePermissionRequest: React.Dispatch<React.SetStateAction<any>>; |
| 10 | + llmApi?: any; | |
| 11 | + model?: any; | |
| 6 | 12 | } |
| 7 | 13 | |
| 8 | 14 | /** |
| @@ -11,12 +17,12 @@ | ||
| 11 | 17 | export function createStreamCallbacks( |
| 12 | 18 | options: CreateStreamCallbacksOptions, |
| 13 | 19 | ): any { |
| 14 | - const { setChatHistory, setActivePermissionRequest } = options; | |
| 20 | + const { setChatHistory, setActivePermissionRequest, llmApi, model } = options; | |
| 15 | 21 | |
| 16 | 22 | return { |
| 17 | 23 | onContent: (_: string) => {}, |
| 18 | 24 | |
| 19 | - onContentComplete: (content: string) => { | |
| 25 | + onContentComplete: async (content: string) => { | |
| 20 | 26 | setChatHistory((prev) => [ |
| 21 | 27 | ...prev, |
| 22 | 28 | { |
| @@ -28,6 +34,21 @@ | ||
| 28 | 34 | }, |
| 29 | 35 | }, |
| 30 | 36 | ]); |
| 37 | + | |
| 38 | + // Generate session title after first assistant response | |
| 39 | + if (content && llmApi && model) { | |
| 40 | + const currentSession = getCurrentSession(); | |
| 41 | + const generatedTitle = await generateSessionTitle( | |
| 42 | + content, | |
| 43 | + llmApi, | |
| 44 | + model, | |
| 45 | + currentSession.title, | |
| 46 | + ); | |
| 47 | + | |
| 48 | + if (generatedTitle) { | |
| 49 | + updateSessionTitle(generatedTitle); | |
| 50 | + } | |
| 51 | + } | |
| 31 | 52 | }, |
| 32 | 53 | |
| 33 | 54 | onToolStart: (toolName: string, toolArgs?: any) => { |
| @@ -198,7 +219,9 @@ | ||
| 198 | 219 | currentCompactionIndex, |
| 199 | 220 | }: ExecuteStreamingOptions): Promise<void> { |
| 200 | 221 | const { getHistoryForLLM } = await import("../../compaction.js"); |
| 201 | - const { streamChatResponse } = await import("../../streamChatResponse.js"); | |
| 222 | + const { streamChatResponse } = await import( | |
| 223 | + "../../stream/streamChatResponse.js" | |
| 224 | + ); | |
| 202 | 225 | |
| 203 | 226 | if (model && llmApi) { |
| 204 | 227 | if ( |
modified extensions/cli/src/ui/hooks/useChat.ts +2 −0
| @@ -203,6 +203,8 @@ | ||
| 203 | 203 | const streamCallbacks = createStreamCallbacks({ |
| 204 | 204 | setChatHistory, |
| 205 | 205 | setActivePermissionRequest, |
| 206 | + llmApi, | |
| 207 | + model, | |
| 206 | 208 | }); |
| 207 | 209 | |
| 208 | 210 | // Execute streaming chat response |
modified extensions/cli/src/ui/hooks/useConfigSelector.ts +3 −13
| @@ -20,14 +20,14 @@ | ||
| 20 | 20 | content: string; |
| 21 | 21 | messageType: "system"; |
| 22 | 22 | }) => void; |
| 23 | - onChatReset: () => void; | |
| 23 | + handleClear: () => void; | |
| 24 | 24 | } |
| 25 | 25 | |
| 26 | 26 | const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); |
| 27 | 27 | |
| 28 | 28 | export function useConfigSelector({ |
| 29 | 29 | onMessage, |
| 30 | - onChatReset, | |
| 30 | + handleClear, | |
| 31 | 31 | }: UseConfigSelectorProps) { |
| 32 | 32 | const { closeCurrentScreen } = useNavigation(); |
| 33 | 33 | |
| @@ -98,12 +98,6 @@ | ||
| 98 | 98 | // Only config path is changing, no organization switch needed |
| 99 | 99 | await services.config.updateConfigPath(targetConfigPath); |
| 100 | 100 | } else { |
| 101 | - onMessage({ | |
| 102 | - role: "system", | |
| 103 | - content: `Switching to organization for ${config.name}...`, | |
| 104 | - messageType: "system" as const, | |
| 105 | - }); | |
| 106 | - | |
| 107 | 101 | // Switch organization first |
| 108 | 102 | await services.auth.switchOrganization(config.organizationId ?? null); |
| 109 | 103 | |
| @@ -112,11 +106,7 @@ | ||
| 112 | 106 | await services.config.updateConfigPath(targetConfigPath); |
| 113 | 107 | } |
| 114 | 108 | |
| 115 | - // Reset chat history | |
| 116 | - onChatReset(); | |
| 117 | - | |
| 118 | - // Clear the screen completely | |
| 119 | - process.stdout.write("\x1b[2J\x1b[H"); | |
| 109 | + handleClear(); | |
| 120 | 110 | |
| 121 | 111 | // Show success message |
| 122 | 112 | onMessage({ |
modified extensions/cli/src/ui/hooks/useTUIChatHooks.ts +2 −2
| @@ -98,7 +98,7 @@ | ||
| 98 | 98 | export function useSelectors( |
| 99 | 99 | configPath: string | undefined, |
| 100 | 100 | setChatHistory: React.Dispatch<React.SetStateAction<any[]>>, |
| 101 | - resetChatHistory: () => void, | |
| 101 | + handleClear: () => void, | |
| 102 | 102 | ): { |
| 103 | 103 | handleConfigSelect: (config: ConfigOption) => Promise<void>; |
| 104 | 104 | handleModelSelect: (model: ModelOption) => Promise<void>; |
| @@ -115,7 +115,7 @@ | ||
| 115 | 115 | }, |
| 116 | 116 | ]); |
| 117 | 117 | }, |
| 118 | - onChatReset: resetChatHistory, | |
| 118 | + handleClear, | |
| 119 | 119 | }); |
| 120 | 120 | |
| 121 | 121 | const { handleModelSelect } = useModelSelector({ |
modified extensions/cli/vitest.setup.ts +3 −0
| @@ -19,6 +19,9 @@ | ||
| 19 | 19 | ), |
| 20 | 20 | })); |
| 21 | 21 | |
| 22 | +// Mock environment for tests | |
| 23 | +process.env.CONTINUE_GLOBAL_DIR = "/tmp/continue-test"; | |
| 24 | + | |
| 22 | 25 | // Set up global afterEach hook to clear all timers and reset console |
| 23 | 26 | afterEach(() => { |
| 24 | 27 | // Clear vitest timers |
modified package-lock.json +1 −1
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | { |
| 2 | - "name": "continue", | |
| 2 | + "name": "wt-generate-message-titles-in-cli", | |
| 3 | 3 | "lockfileVersion": 3, |
| 4 | 4 | "requires": true, |
| 5 | 5 | "packages": { |