Elffuss BraidHub

kikocis/continue public

fix: types, imports, and formatting
Changesetb2066c2304f5884b579e800799b7641d4949da1a74a28800d88ebcae20a12938
AuthorNate <sestinj@gmail.com> · 2025-08-27 21:32 -07:00
CommitterNate <sestinj@gmail.com> · 2025-08-27 21:32 -07:00
Parentsfa9f869489e5

Browse the files at this changeset

32 files changed

modified core/util/chatDescriber.ts +7 −30
@@ -5,6 +5,7 @@
55 import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
66 import type { IMessenger } from "../protocol/messenger";
77 import { renderChatMessage } from "./messageContent";
8+import { convertFromUnifiedHistory } from "./messageConversion";
89
910 export class ChatDescriber {
1011 static maxTokens = 12;
@@ -71,32 +72,12 @@
7172 };
7273
7374 // Convert to OpenAI format - use a simple fallback to avoid import issues
74- let openaiMessages;
75- let defaultOptions = {};
76-
77- try {
78- // Try to import CLI dependencies dynamically
79- const { convertFromUnifiedHistory } = await import(
80- "../../extensions/cli/src/messageConversion.js"
81- );
82- const { getDefaultCompletionOptions } = await import(
83- "../../extensions/cli/src/streamChatResponse.types.js"
84- );
85-
86- openaiMessages = convertFromUnifiedHistory([
87- {
88- message: chatMessage,
89- contextItems: [],
90- },
91- ]);
92- defaultOptions = getDefaultCompletionOptions(
93- modelConfig.defaultCompletionOptions,
94- );
95- } catch {
96- // Fallback: use direct OpenAI format if imports fail
97- openaiMessages = [chatMessage];
98- defaultOptions = {};
99- }
75+ const openaiMessages = convertFromUnifiedHistory([
76+ {
77+ message: chatMessage,
78+ contextItems: [],
79+ },
80+ ]);
10081
10182 // Set up completion options for non-streaming
10283 const completionOptions = {
@@ -104,10 +85,6 @@
10485 messages: openaiMessages,
10586 max_tokens: ChatDescriber.maxTokens,
10687 stream: false as const,
107- temperature: (defaultOptions as any)?.temperature,
108- frequency_penalty: (defaultOptions as any)?.frequency_penalty,
109- presence_penalty: (defaultOptions as any)?.presence_penalty,
110- top_p: (defaultOptions as any)?.top_p,
11188 };
11289
11390 // Call the LLM
added core/util/messageConversion.ts +396 −0
@@ -0,0 +1,396 @@
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+ 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: ToolCallState) => 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: ContextItemWithId) =>
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+ * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
346+ * @param historyItems - The chat history items
347+ * @param systemMessage - The system message to inject at the beginning
348+ */
349+export function convertFromUnifiedHistoryWithSystemMessage(
350+ historyItems: ChatHistoryItem[],
351+ systemMessage: string,
352+): ChatCompletionMessageParam[] {
353+ const messages: ChatCompletionMessageParam[] = [];
354+
355+ // Inject system message at the beginning
356+ messages.push({
357+ role: "system",
358+ content: systemMessage,
359+ });
360+
361+ // Convert the rest of the history
362+ const convertedMessages = convertFromUnifiedHistory(historyItems);
363+ messages.push(...convertedMessages);
364+
365+ return messages;
366+}
367+
368+/**
369+ * Extract tool call information from a ChatHistoryItem
370+ */
371+export function extractToolCallInfo(historyItem: ChatHistoryItem): {
372+ hasToolCalls: boolean;
373+ toolCalls?: ToolCall[];
374+ toolStates?: ToolCallState[];
375+} {
376+ const hasToolCalls = !!(
377+ historyItem.toolCallStates && historyItem.toolCallStates.length > 0
378+ );
379+
380+ return {
381+ hasToolCalls,
382+ toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
383+ toolStates: historyItem.toolCallStates,
384+ };
385+}
386+
387+/**
388+ * Helper to safely parse JSON
389+ */
390+function tryParseJson(str: string): any {
391+ try {
392+ return JSON.parse(str);
393+ } catch {
394+ return str;
395+ }
396+}
modified extensions/cli/src/commands/chat.ts +2 −2
@@ -22,7 +22,7 @@
2222 updateSessionHistory,
2323 updateSessionTitle,
2424 } from "../session.js";
25-import { streamChatResponse } from "../streamChatResponse.js";
25+import { streamChatResponse } from "../stream/streamChatResponse.js";
2626 import { posthogService } from "../telemetry/posthogService.js";
2727 import { telemetryService } from "../telemetry/telemetryService.js";
2828 import { startTUIChat } from "../ui/index.js";
@@ -157,7 +157,7 @@
157157 format?: "json",
158158 ): Promise<number | null> {
159159 const { handleAutoCompaction: coreAutoCompaction } = await import(
160- "../streamChatResponse.autoCompaction.js"
160+ "../stream/streamChatResponse.autoCompaction.js"
161161 );
162162
163163 // Custom callbacks for headless mode console output
modified extensions/cli/src/commands/serve.helpers.ts +2 −2
@@ -5,8 +5,8 @@
55 ToolStatus,
66 } from "core/index.js";
77
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";
1010
1111 // Modified version of streamChatResponse that supports interruption
1212 export async function streamChatResponseWithInterruption(
modified extensions/cli/src/commands/serve.ts +1 −1
@@ -3,11 +3,11 @@
33
44 import chalk from "chalk";
55 import type { ChatHistoryItem } from "core/index.js";
6+import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
67 import express, { Request, Response } from "express";
78
89 import { getAssistantSlug } from "../auth/workos.js";
910 import { processCommandFlags } from "../flags/flagProcessor.js";
10-import { convertFromUnifiedHistory } from "../messageConversion.js";
1111 import { toolPermissionManager } from "../permissions/permissionManager.js";
1212 import {
1313 getService,
modified extensions/cli/src/compaction.infiniteLoop.test.ts +3 −3
@@ -1,10 +1,10 @@
11 import { ModelConfig } from "@continuedev/config-yaml";
22 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";
45
56 import { compactChatHistory } from "./compaction.js";
6-import { convertToUnifiedHistory } from "./messageConversion.js";
7-import { streamChatResponse } from "./streamChatResponse.js";
7+import { streamChatResponse } from "./stream/streamChatResponse.js";
88
99 // Mock the dependencies
1010 vi.mock("./streamChatResponse.js", () => ({
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";
23
34 import { pruneLastMessage } from "./compaction.js";
4-import { convertToUnifiedHistory } from "./messageConversion.js";
55 import { logger } from "./util/logger.js";
66
77 describe("pruneLastMessage", () => {
modified extensions/cli/src/compaction.test.ts +2 −2
@@ -1,6 +1,7 @@
11 import { ModelConfig } from "@continuedev/config-yaml";
22 import { BaseLlmApi } from "@continuedev/openai-adapters";
33 import type { ChatHistoryItem } from "core/index.js";
4+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
45 import { describe, expect, it, vi } from "vitest";
56
67 import {
@@ -8,8 +9,7 @@
89 findCompactionIndex,
910 getHistoryForLLM,
1011 } from "./compaction.js";
11-import { convertToUnifiedHistory } from "./messageConversion.js";
12-import { streamChatResponse } from "./streamChatResponse.js";
12+import { streamChatResponse } from "./stream/streamChatResponse.js";
1313
1414 // Mock the streamChatResponse function
1515 vi.mock("./streamChatResponse.js", () => ({
modified extensions/cli/src/compaction.ts +2 −2
@@ -2,8 +2,8 @@
22 import { BaseLlmApi } from "@continuedev/openai-adapters";
33 import type { ChatHistoryItem } from "core/index.js";
44
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";
77 import { logger } from "./util/logger.js";
88 import {
99 countChatHistoryTokens,
modified extensions/cli/src/messageConversion.test.ts +1 −2
@@ -1,6 +1,5 @@
11 import type { ChatHistoryItem } from "core/index.js";
2-
3-import { convertFromUnifiedHistory } from "./messageConversion.js";
2+import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
43
54 describe("convertFromUnifiedHistory", () => {
65 it("should expand contextItems into user message content", () => {
deleted extensions/cli/src/messageConversion.ts +0 −396
@@ -1,396 +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- * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message
346- * @param historyItems - The chat history items
347- * @param systemMessage - The system message to inject at the beginning
348- */
349-export function convertFromUnifiedHistoryWithSystemMessage(
350- historyItems: ChatHistoryItem[],
351- systemMessage: string,
352-): ChatCompletionMessageParam[] {
353- const messages: ChatCompletionMessageParam[] = [];
354-
355- // Inject system message at the beginning
356- messages.push({
357- role: "system",
358- content: systemMessage,
359- });
360-
361- // Convert the rest of the history
362- const convertedMessages = convertFromUnifiedHistory(historyItems);
363- messages.push(...convertedMessages);
364-
365- return messages;
366-}
367-
368-/**
369- * Extract tool call information from a ChatHistoryItem
370- */
371-export function extractToolCallInfo(historyItem: ChatHistoryItem): {
372- hasToolCalls: boolean;
373- toolCalls?: ToolCall[];
374- toolStates?: ToolCallState[];
375-} {
376- const hasToolCalls = !!(
377- historyItem.toolCallStates && historyItem.toolCallStates.length > 0
378- );
379-
380- return {
381- hasToolCalls,
382- toolCalls: historyItem.toolCallStates?.map((ts: any) => ts.toolCall),
383- toolStates: historyItem.toolCallStates,
384- };
385-}
386-
387-/**
388- * Helper to safely parse JSON
389- */
390-function tryParseJson(str: string): any {
391- try {
392- return JSON.parse(str);
393- } catch {
394- return str;
395- }
396-}
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 +246 −0
@@ -0,0 +1,246 @@
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+ 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+});
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- executeStreamedToolCalls,
10- preprocessStreamedToolCalls,
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 −612
@@ -1,612 +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 { stripImages } from "core/util/messageContent.js";
5-import * as dotenv from "dotenv";
6-import type { ChatCompletionTool } from "openai/resources.mjs";
7-
8-import {
9- convertFromUnifiedHistoryWithSystemMessage,
10- createHistoryItem,
11-} from "./messageConversion.js";
12-import { filterExcludedTools } from "./permissions/index.js";
13-import {
14- getServiceSync,
15- MCPServiceState,
16- MCPTool,
17- SERVICE_NAMES,
18-} from "./services/index.js";
19-import { systemMessageService } from "./services/SystemMessageService.js";
20-import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
21-import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
22-import {
23- executeStreamedToolCalls,
24- preprocessStreamedToolCalls,
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-import { telemetryService } from "./telemetry/telemetryService.js";
35-import { getAllBuiltinTools, ToolCall } from "./tools/index.js";
36-import {
37- chatCompletionStreamWithBackoff,
38- withExponentialBackoff,
39-} from "./util/exponentialBackoff.js";
40-import { logger } from "./util/logger.js";
41-
42-dotenv.config();
43-
44-function updateFinalResponse(
45- content: string,
46- shouldContinue: boolean,
47- isHeadless: boolean,
48- currentFinalResponse: string,
49-): string {
50- if (!shouldContinue) {
51- return content;
52- } else if (isHeadless && content) {
53- return content;
54- }
55- return currentFinalResponse;
56-}
57-
58-function handleContentDisplay(
59- content: string,
60- callbacks: StreamCallbacks | undefined,
61- isHeadless: boolean,
62-): void {
63- // Add newline after content if needed
64- if (!callbacks?.onContent && !isHeadless && content) {
65- logger.info("");
66- }
67-
68- // Notify content complete
69- if (content && callbacks?.onContentComplete) {
70- callbacks.onContentComplete(content);
71- }
72-}
73-
74-async function handleToolCalls(
75- toolCalls: ToolCall[],
76- chatHistory: ChatHistoryItem[],
77- content: string,
78- callbacks: StreamCallbacks | undefined,
79- isHeadless: boolean,
80-): Promise<boolean> {
81- if (toolCalls.length === 0) {
82- if (content) {
83- chatHistory.push(
84- createHistoryItem({
85- role: "assistant",
86- content,
87- }),
88- );
89- }
90- return false;
91- }
92-
93- // Create tool call states for the ChatHistoryItem
94- const toolCallStates = toolCalls.map((tc) => ({
95- toolCallId: tc.id,
96- toolCall: {
97- id: tc.id,
98- type: "function" as const,
99- function: {
100- name: tc.name,
101- arguments: JSON.stringify(tc.arguments),
102- },
103- },
104- status: "generated" as ToolStatus,
105- parsedArgs: tc.arguments,
106- }));
107-
108- // Create assistant message with tool calls
109- const assistantMessage = {
110- role: "assistant" as const,
111- content: content || "",
112- toolCalls: toolCalls.map((tc) => ({
113- id: tc.id,
114- type: "function" as const,
115- function: {
116- name: tc.name,
117- arguments: JSON.stringify(tc.arguments),
118- },
119- })),
120- };
121-
122- chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
123-
124- // First preprocess the tool calls
125- const { preprocessedCalls, errorChatEntries } =
126- await preprocessStreamedToolCalls(toolCalls, callbacks);
127-
128- // Add any preprocessing errors to chat history
129- // Convert error entries from OpenAI format to ChatHistoryItem format
130- errorChatEntries.forEach((errorEntry) => {
131- chatHistory.push(
132- createHistoryItem({
133- role: "tool",
134- content: stripImages(errorEntry.content) || "",
135- toolCallId: errorEntry.tool_call_id,
136- }),
137- );
138- });
139-
140- // Execute the valid preprocessed tool calls
141- const { chatHistoryEntries: toolResults, hasRejection } =
142- await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
143-
144- if (isHeadless && hasRejection) {
145- logger.debug(
146- "Tool call rejected in headless mode - returning current content",
147- );
148- return true; // Signal early return needed
149- }
150-
151- // Convert tool results from OpenAI format to ChatHistoryItem format
152- // and add them to the chat history
153- toolResults.forEach((toolResult) => {
154- // Find the corresponding tool call state to update
155- const lastAssistantIndex = chatHistory.findLastIndex(
156- (item) => item.message.role === "assistant" && item.toolCallStates,
157- );
158-
159- if (
160- lastAssistantIndex >= 0 &&
161- chatHistory[lastAssistantIndex].toolCallStates
162- ) {
163- const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
164- (ts) => ts.toolCallId === toolResult.tool_call_id,
165- );
166-
167- if (toolState) {
168- toolState.status = hasRejection ? "canceled" : "done";
169- toolState.output = [
170- {
171- content:
172- typeof toolResult.content === "string" ? toolResult.content : "",
173- name: `Tool Result`,
174- description: "Tool execution result",
175- },
176- ];
177- }
178- }
179- });
180- return false;
181-}
182-
183-export async function getAllTools() {
184- // Get all available tool names
185- const allBuiltinTools = getAllBuiltinTools();
186- const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
187-
188- let mcpTools: MCPTool[] = [];
189- let mcpToolNames: string[] = [];
190- const mcpServiceResult = getServiceSync<MCPServiceState>(SERVICE_NAMES.MCP);
191- if (mcpServiceResult.state === "ready") {
192- mcpTools = mcpServiceResult?.value?.tools ?? [];
193- mcpToolNames = mcpTools.map((t) => t.name);
194- } else {
195- // MCP is lazy
196- // throw new Error("MCP Service not initialized");
197- }
198-
199- const allToolNames = [...builtinToolNames, ...mcpToolNames];
200-
201- // Check if the ToolPermissionService is ready
202- const permissionsServiceResult = getServiceSync<ToolPermissionServiceState>(
203- SERVICE_NAMES.TOOL_PERMISSIONS,
204- );
205-
206- let allowedToolNames: string[];
207- if (
208- permissionsServiceResult.state === "ready" &&
209- permissionsServiceResult.value
210- ) {
211- // Filter out excluded tools based on permissions
212- allowedToolNames = filterExcludedTools(
213- allToolNames,
214- permissionsServiceResult.value.permissions,
215- );
216- } else {
217- // Service not ready - this is a critical error since tools should only be
218- // requested after services are properly initialized
219- logger.error(
220- "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
221- );
222- throw new Error(
223- "ToolPermissionService not initialized. Services must be initialized before requesting tools.",
224- );
225- }
226-
227- const allowedToolNamesSet = new Set(allowedToolNames);
228-
229- // Filter builtin tools
230- const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
231- allowedToolNamesSet.has(tool.name),
232- );
233-
234- const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
235- type: "function" as const,
236- function: {
237- name: tool.name,
238- description: tool.description,
239- parameters: {
240- type: "object",
241- properties: Object.fromEntries(
242- Object.entries(tool.parameters).map(([key, param]) => [
243- key,
244- {
245- type: param.type,
246- description: param.description,
247- items: param.items,
248- },
249- ]),
250- ),
251- required: Object.entries(tool.parameters)
252- .filter(([_, param]) => param.required)
253- .map(([key, _]) => key),
254- },
255- },
256- }));
257-
258- // Add filtered MCP tools
259- const allowedMcpTools = mcpTools.filter((tool) =>
260- allowedToolNamesSet.has(tool.name),
261- );
262-
263- allTools.push(
264- ...allowedMcpTools.map((tool) => ({
265- type: "function" as const,
266- function: {
267- name: tool.name,
268- description: tool.description,
269- parameters: tool.inputSchema,
270- },
271- })),
272- );
273-
274- return allTools;
275-}
276-
277-// Helper function to process a single chunk
278-interface ProcessChunkOptions {
279- chunk: any;
280- aiResponse: string;
281- toolCallsMap: Map<string, ToolCall>;
282- indexToIdMap: Map<number, string>;
283- callbacks?: StreamCallbacks;
284- isHeadless?: boolean;
285-}
286-
287-function processChunk(options: ProcessChunkOptions): {
288- aiResponse: string;
289- shouldContinue: boolean;
290-} {
291- const {
292- chunk,
293- aiResponse,
294- toolCallsMap,
295- indexToIdMap,
296- callbacks,
297- isHeadless,
298- } = options;
299- // Safety check: ensure chunk has the expected structure
300- if (!chunk.choices || !chunk.choices[0]) {
301- return { aiResponse, shouldContinue: true };
302- }
303-
304- const choice = chunk.choices[0];
305- if (!choice.delta) {
306- return { aiResponse, shouldContinue: true };
307- }
308-
309- let updatedResponse = aiResponse;
310-
311- // Handle content streaming
312- if (choice.delta.content) {
313- updatedResponse = processChunkContent(
314- choice.delta.content,
315- aiResponse,
316- callbacks,
317- isHeadless,
318- );
319- }
320-
321- // Handle tool calls
322- if (choice.delta.tool_calls) {
323- for (const toolCallDelta of choice.delta.tool_calls) {
324- processToolCallDelta(toolCallDelta, toolCallsMap, indexToIdMap);
325- }
326- }
327-
328- return { aiResponse: updatedResponse, shouldContinue: true };
329-}
330-
331-interface ProcessStreamingResponseOptions {
332- chatHistory: ChatHistoryItem[];
333- model: ModelConfig;
334- llmApi: BaseLlmApi;
335- abortController: AbortController;
336- callbacks?: StreamCallbacks;
337- isHeadless?: boolean;
338- tools?: ChatCompletionTool[];
339-}
340-
341-// Process a single streaming response and return whether we need to continue
342-export async function processStreamingResponse(
343- options: ProcessStreamingResponseOptions,
344-): Promise<{
345- content: string;
346- finalContent: string; // Added field for final content only
347- toolCalls: ToolCall[];
348- shouldContinue: boolean;
349-}> {
350- const {
351- chatHistory,
352- model,
353- llmApi,
354- abortController,
355- callbacks,
356- isHeadless,
357- tools,
358- } = options;
359-
360- // Get fresh system message and inject it
361- const systemMessage = await systemMessageService.getSystemMessage();
362- const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
363- chatHistory,
364- systemMessage,
365- );
366- const requestStartTime = Date.now();
367-
368- const streamFactory = async (retryAbortSignal: AbortSignal) => {
369- logger.debug("Creating chat completion stream", {
370- model,
371- messageCount: chatHistory.length,
372- toolCount: tools?.length || 0,
373- });
374- return await chatCompletionStreamWithBackoff(
375- llmApi,
376- {
377- model: model.model,
378- messages: openaiChatHistory,
379- stream: true,
380- tools,
381- ...getDefaultCompletionOptions(model.defaultCompletionOptions),
382- },
383- retryAbortSignal,
384- );
385- };
386-
387- let aiResponse = "";
388- let finalContent = "";
389- const toolCallsMap = new Map<string, ToolCall>();
390- const indexToIdMap = new Map<number, string>(); // Track index to ID mapping
391- let firstTokenTime: number | null = null;
392- let inputTokens = 0;
393- let outputTokens = 0;
394-
395- try {
396- const streamWithBackoff = withExponentialBackoff(
397- streamFactory,
398- abortController.signal,
399- );
400-
401- let chunkCount = 0;
402- for await (const chunk of streamWithBackoff) {
403- chunkCount++;
404-
405- logger.debug("Received chunk", { chunkCount, chunk });
406-
407- // Track token usage if available
408- if (chunk.usage) {
409- inputTokens = chunk.usage.prompt_tokens || 0;
410- outputTokens = chunk.usage.completion_tokens || 0;
411- }
412-
413- // Check if we should abort
414- if (abortController?.signal.aborted) {
415- logger.debug("Stream aborted");
416- break;
417- }
418-
419- // Track first token time
420- firstTokenTime = trackFirstTokenTime(
421- firstTokenTime,
422- chunk,
423- requestStartTime,
424- model,
425- tools,
426- );
427-
428- const result = processChunk({
429- chunk,
430- aiResponse,
431- toolCallsMap,
432- indexToIdMap,
433- callbacks,
434- isHeadless,
435- });
436- aiResponse = result.aiResponse;
437- if (!result.shouldContinue) break;
438- }
439-
440- const responseEndTime = Date.now();
441- const cost = recordStreamTelemetry({
442- requestStartTime,
443- responseEndTime,
444- inputTokens,
445- outputTokens,
446- model,
447- tools,
448- });
449- const totalDuration = responseEndTime - requestStartTime;
450-
451- logger.debug("Stream complete", {
452- chunkCount,
453- responseLength: aiResponse.length,
454- toolCallsCount: toolCallsMap.size,
455- inputTokens,
456- outputTokens,
457- cost,
458- duration: totalDuration,
459- });
460- } catch (error: any) {
461- const errorDuration = Date.now() - requestStartTime;
462-
463- // Log failed API request
464- telemetryService.logApiRequest({
465- model: model.model,
466- durationMs: errorDuration,
467- success: false,
468- error: error.message || String(error),
469- });
470-
471- if (error.name === "AbortError" || abortController?.signal.aborted) {
472- logger.debug("Stream aborted by user");
473- return {
474- content: aiResponse,
475- finalContent: aiResponse,
476- toolCalls: [],
477- shouldContinue: false,
478- };
479- }
480- throw error;
481- }
482-
483- const toolCalls = Array.from(toolCallsMap.values());
484-
485- // Validate tool calls have complete arguments
486- const validToolCalls = toolCalls.filter((tc) => {
487- if (!tc.arguments || !tc.name) {
488- logger.error("Incomplete tool call", {
489- id: tc.id,
490- name: tc.name,
491- hasArguments: !!tc.arguments,
492- argumentsStr: tc.argumentsStr,
493- });
494- return false;
495- }
496- return true;
497- });
498-
499- // Always preserve the content - it should be displayed regardless of tool calls
500- finalContent = aiResponse;
501-
502- return {
503- content: aiResponse,
504- finalContent: finalContent,
505- toolCalls: validToolCalls,
506- shouldContinue: validToolCalls.length > 0,
507- };
508-}
509-
510-// Main function that handles the conversation loop
511-export async function streamChatResponse(
512- chatHistory: ChatHistoryItem[],
513- model: ModelConfig,
514- llmApi: BaseLlmApi,
515- abortController: AbortController,
516- callbacks?: StreamCallbacks,
517-) {
518- logger.debug("streamChatResponse called", {
519- model,
520- historyLength: chatHistory.length,
521- hasCallbacks: !!callbacks,
522- });
523-
524- const serviceResult = getServiceSync<ToolPermissionServiceState>(
525- SERVICE_NAMES.TOOL_PERMISSIONS,
526- );
527- const isHeadless = serviceResult.value?.isHeadless ?? false;
528-
529- let fullResponse = "";
530- let finalResponse = "";
531-
532- while (true) {
533- logger.debug("Starting conversation iteration");
534-
535- // Recompute tools on each iteration to handle mode changes during streaming
536- const tools = await getAllTools();
537-
538- logger.debug("Tools prepared", {
539- toolCount: tools.length,
540- toolNames: tools.map((t) => t.function.name),
541- });
542-
543- // Get response from LLM
544- const { content, toolCalls, shouldContinue } =
545- await processStreamingResponse({
546- chatHistory,
547- model,
548- llmApi,
549- abortController,
550- callbacks,
551- isHeadless,
552- tools,
553- });
554-
555- fullResponse += content;
556-
557- // Update final response based on mode
558- finalResponse = updateFinalResponse(
559- content,
560- shouldContinue,
561- isHeadless,
562- finalResponse,
563- );
564-
565- // Handle content display
566- handleContentDisplay(content, callbacks, isHeadless);
567-
568- // Handle tool calls and check for early return
569- const shouldReturn = await handleToolCalls(
570- toolCalls,
571- chatHistory,
572- content,
573- callbacks,
574- isHeadless,
575- );
576-
577- if (shouldReturn) {
578- return finalResponse || content || fullResponse;
579- }
580-
581- // Check for auto-compaction after tool execution
582- if (shouldContinue) {
583- const { wasCompacted, chatHistory: updatedChatHistory } =
584- await handleAutoCompaction(chatHistory, model, llmApi, {
585- isHeadless,
586- callbacks: {
587- onSystemMessage: callbacks?.onSystemMessage,
588- onContent: callbacks?.onContent,
589- },
590- });
591-
592- // Only update chat history if compaction actually occurred
593- if (wasCompacted) {
594- chatHistory = [...updatedChatHistory];
595- }
596- }
597-
598- // Check if we should continue
599- if (!shouldContinue) {
600- break;
601- }
602- }
603-
604- logger.debug("streamChatResponse complete", {
605- totalResponseLength: fullResponse.length,
606- totalMessages: chatHistory.length,
607- });
608-
609- // For headless mode, we return only the final response
610- // Otherwise, return the full response
611- return isHeadless ? finalResponse : fullResponse;
612-}
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/ui/__tests__/TUIChat.planModeBug.test.tsx +2 −1
@@ -2,9 +2,10 @@
22 import React from "react";
33 import { afterEach, beforeEach, describe, expect, it } from "vitest";
44
5+import { getAllTools } from "src/stream/handleToolCalls.js";
6+
57 import { SERVICE_NAMES, serviceContainer } from "../../services/index.js";
68 import { modeService } from "../../services/ModeService.js";
7-import { getAllTools } from "../../streamChatResponse.js";
89 import { createUITestContext } from "../../test-helpers/ui-test-context.js";
910 import { AppRoot } from "../AppRoot.js";
1011
modified extensions/cli/src/ui/hooks/useChat.clear.test.ts +1 −1
@@ -1,7 +1,7 @@
1+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
12 import { ChatCompletionMessageParam } from "openai/resources.mjs";
23 import { beforeEach, describe, expect, it, vi } from "vitest";
34
4-import { convertToUnifiedHistory } from "../../messageConversion.js";
55 import { startNewSession } from "../../session.js";
66
77 import { processSlashCommandResult } from "./useChat.helpers.js";
modified extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +1 −1
@@ -1,6 +1,6 @@
11 import type { ChatHistoryItem } from "core/index.js";
2+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
23
3-import { convertToUnifiedHistory } from "../../messageConversion.js";
44 import { posthogService } from "../../telemetry/posthogService.js";
55 import { logger } from "../../util/logger.js";
66
modified extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +3 −1
@@ -219,7 +219,9 @@
219219 currentCompactionIndex,
220220 }: ExecuteStreamingOptions): Promise<void> {
221221 const { getHistoryForLLM } = await import("../../compaction.js");
222- const { streamChatResponse } = await import("../../streamChatResponse.js");
222+ const { streamChatResponse } = await import(
223+ "../../stream/streamChatResponse.js"
224+ );
223225
224226 if (model && llmApi) {
225227 if (