diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts
index 4c23de69e..9c5c5c96b 100644
--- a/core/util/chatDescriber.ts
+++ b/core/util/chatDescriber.ts
@@ -5,6 +5,7 @@ import { removeCodeBlocksAndTrim, removeQuotesAndEscapes } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "../protocol/messenger";
import { renderChatMessage } from "./messageContent";
+import { convertFromUnifiedHistory } from "./messageConversion";
export class ChatDescriber {
static maxTokens = 12;
@@ -71,32 +72,12 @@ export class ChatDescriber {
};
// Convert to OpenAI format - use a simple fallback to avoid import issues
- let openaiMessages;
- let defaultOptions = {};
-
- try {
- // Try to import CLI dependencies dynamically
- const { convertFromUnifiedHistory } = await import(
- "../../extensions/cli/src/messageConversion.js"
- );
- const { getDefaultCompletionOptions } = await import(
- "../../extensions/cli/src/streamChatResponse.types.js"
- );
-
- openaiMessages = convertFromUnifiedHistory([
- {
- message: chatMessage,
- contextItems: [],
- },
- ]);
- defaultOptions = getDefaultCompletionOptions(
- modelConfig.defaultCompletionOptions,
- );
- } catch {
- // Fallback: use direct OpenAI format if imports fail
- openaiMessages = [chatMessage];
- defaultOptions = {};
- }
+ const openaiMessages = convertFromUnifiedHistory([
+ {
+ message: chatMessage,
+ contextItems: [],
+ },
+ ]);
// Set up completion options for non-streaming
const completionOptions = {
@@ -104,10 +85,6 @@ export class ChatDescriber {
messages: openaiMessages,
max_tokens: ChatDescriber.maxTokens,
stream: false as const,
- temperature: (defaultOptions as any)?.temperature,
- frequency_penalty: (defaultOptions as any)?.frequency_penalty,
- presence_penalty: (defaultOptions as any)?.presence_penalty,
- top_p: (defaultOptions as any)?.top_p,
};
// Call the LLM
diff --git a/extensions/cli/src/messageConversion.ts b/core/util/messageConversion.ts
similarity index 98%
rename from extensions/cli/src/messageConversion.ts
rename to core/util/messageConversion.ts
index d182f5425..cc561cb84 100644
--- a/extensions/cli/src/messageConversion.ts
+++ b/core/util/messageConversion.ts
@@ -5,6 +5,7 @@
* format and the unified ChatHistoryItem format from the core package.
*/
+import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import type {
AssistantChatMessage,
ChatHistoryItem,
@@ -14,8 +15,7 @@ import type {
ToolCall,
ToolCallState,
ToolStatus,
-} from "core/index.js";
-import type { ChatCompletionMessageParam } from "openai/resources.mjs";
+} from "../index.js";
/**
* Convert ChatCompletionMessageParam to ChatMessage
@@ -230,7 +230,7 @@ function handleToolResult(
if (!historyItems[lastAssistantIndex].toolCallStates) return;
const toolState = historyItems[lastAssistantIndex].toolCallStates?.find(
- (ts) => ts.toolCallId === unifiedMessage.toolCallId,
+ (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId,
);
if (toolState) {
@@ -311,7 +311,7 @@ export function convertFromUnifiedHistory(
) {
const contextContent = item.contextItems
.map(
- (contextItem) =>
+ (contextItem: ContextItemWithId) =>
`\n${contextItem.content}\n\n\n`,
)
.join("");
diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts
index 44ebc9cff..c62b656c4 100644
--- a/extensions/cli/src/commands/chat.ts
+++ b/extensions/cli/src/commands/chat.ts
@@ -22,7 +22,7 @@ import {
updateSessionHistory,
updateSessionTitle,
} from "../session.js";
-import { streamChatResponse } from "../streamChatResponse.js";
+import { streamChatResponse } from "../stream/streamChatResponse.js";
import { posthogService } from "../telemetry/posthogService.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { startTUIChat } from "../ui/index.js";
@@ -157,7 +157,7 @@ async function handleAutoCompaction(
format?: "json",
): Promise {
const { handleAutoCompaction: coreAutoCompaction } = await import(
- "../streamChatResponse.autoCompaction.js"
+ "../stream/streamChatResponse.autoCompaction.js"
);
// Custom callbacks for headless mode console output
diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts
index 7180955c3..01cc1e032 100644
--- a/extensions/cli/src/commands/serve.helpers.ts
+++ b/extensions/cli/src/commands/serve.helpers.ts
@@ -5,8 +5,8 @@ import type {
ToolStatus,
} from "core/index.js";
-import { streamChatResponse } from "../streamChatResponse.js";
-import { StreamCallbacks } from "../streamChatResponse.types.js";
+import { streamChatResponse } from "../stream/streamChatResponse.js";
+import { StreamCallbacks } from "../stream/streamChatResponse.types.js";
// Modified version of streamChatResponse that supports interruption
export async function streamChatResponseWithInterruption(
diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts
index 97c06cda0..2a07017af 100644
--- a/extensions/cli/src/commands/serve.ts
+++ b/extensions/cli/src/commands/serve.ts
@@ -3,11 +3,11 @@ import { promisify } from "util";
import chalk from "chalk";
import type { ChatHistoryItem } from "core/index.js";
+import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
import express, { Request, Response } from "express";
import { getAssistantSlug } from "../auth/workos.js";
import { processCommandFlags } from "../flags/flagProcessor.js";
-import { convertFromUnifiedHistory } from "../messageConversion.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import {
getService,
diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts
index a153cfb28..14ac4d862 100644
--- a/extensions/cli/src/compaction.infiniteLoop.test.ts
+++ b/extensions/cli/src/compaction.infiniteLoop.test.ts
@@ -1,10 +1,10 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
-import { describe, it, expect, vi } from "vitest";
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
+import { describe, expect, it, vi } from "vitest";
import { compactChatHistory } from "./compaction.js";
-import { convertToUnifiedHistory } from "./messageConversion.js";
-import { streamChatResponse } from "./streamChatResponse.js";
+import { streamChatResponse } from "./stream/streamChatResponse.js";
// Mock the dependencies
vi.mock("./streamChatResponse.js", () => ({
diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts
index 1152837e8..a9ed83da4 100644
--- a/extensions/cli/src/compaction.pruneLastMessage.test.ts
+++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect } from "vitest";
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
+import { describe, expect, it } from "vitest";
import { pruneLastMessage } from "./compaction.js";
-import { convertToUnifiedHistory } from "./messageConversion.js";
import { logger } from "./util/logger.js";
describe("pruneLastMessage", () => {
diff --git a/extensions/cli/src/compaction.test.ts b/extensions/cli/src/compaction.test.ts
index e23424c67..394d26893 100644
--- a/extensions/cli/src/compaction.test.ts
+++ b/extensions/cli/src/compaction.test.ts
@@ -1,6 +1,7 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatHistoryItem } from "core/index.js";
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
import { describe, expect, it, vi } from "vitest";
import {
@@ -8,8 +9,7 @@ import {
findCompactionIndex,
getHistoryForLLM,
} from "./compaction.js";
-import { convertToUnifiedHistory } from "./messageConversion.js";
-import { streamChatResponse } from "./streamChatResponse.js";
+import { streamChatResponse } from "./stream/streamChatResponse.js";
// Mock the streamChatResponse function
vi.mock("./streamChatResponse.js", () => ({
diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts
index 29d7e3f70..3edbe0260 100644
--- a/extensions/cli/src/compaction.ts
+++ b/extensions/cli/src/compaction.ts
@@ -2,8 +2,8 @@ import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatHistoryItem } from "core/index.js";
-import { streamChatResponse } from "./streamChatResponse.js";
-import { StreamCallbacks } from "./streamChatResponse.types.js";
+import { streamChatResponse } from "./stream/streamChatResponse.js";
+import { StreamCallbacks } from "./stream/streamChatResponse.types.js";
import { logger } from "./util/logger.js";
import {
countChatHistoryTokens,
diff --git a/extensions/cli/src/messageConversion.test.ts b/extensions/cli/src/messageConversion.test.ts
index 3a4903294..45e7de2c2 100644
--- a/extensions/cli/src/messageConversion.test.ts
+++ b/extensions/cli/src/messageConversion.test.ts
@@ -1,6 +1,5 @@
import type { ChatHistoryItem } from "core/index.js";
-
-import { convertFromUnifiedHistory } from "./messageConversion.js";
+import { convertFromUnifiedHistory } from "core/util/messageConversion.js";
describe("convertFromUnifiedHistory", () => {
it("should expand contextItems into user message content", () => {
diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts
new file mode 100644
index 000000000..aa37a25d7
--- /dev/null
+++ b/extensions/cli/src/stream/handleToolCalls.ts
@@ -0,0 +1,224 @@
+import type { ChatHistoryItem, ToolStatus } from "core/index.js";
+import { stripImages } from "core/util/messageContent.js";
+import { createHistoryItem } from "core/util/messageConversion.js";
+import type { ChatCompletionTool } from "openai/resources.mjs";
+
+import { filterExcludedTools } from "../permissions/index.js";
+import {
+ getServiceSync,
+ MCPServiceState,
+ MCPTool,
+ SERVICE_NAMES,
+} from "../services/index.js";
+import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
+import { getAllBuiltinTools, ToolCall } from "../tools/index.js";
+import { logger } from "../util/logger.js";
+
+import {
+ executeStreamedToolCalls,
+ preprocessStreamedToolCalls,
+} from "./streamChatResponse.helpers.js";
+import { StreamCallbacks } from "./streamChatResponse.types.js";
+
+export async function handleToolCalls(
+ toolCalls: ToolCall[],
+ chatHistory: ChatHistoryItem[],
+ content: string,
+ callbacks: StreamCallbacks | undefined,
+ isHeadless: boolean,
+): Promise {
+ if (toolCalls.length === 0) {
+ if (content) {
+ chatHistory.push(
+ createHistoryItem({
+ role: "assistant",
+ content,
+ }),
+ );
+ }
+ return false;
+ }
+
+ // Create tool call states for the ChatHistoryItem
+ const toolCallStates = toolCalls.map((tc) => ({
+ toolCallId: tc.id,
+ toolCall: {
+ id: tc.id,
+ type: "function" as const,
+ function: {
+ name: tc.name,
+ arguments: JSON.stringify(tc.arguments),
+ },
+ },
+ status: "generated" as ToolStatus,
+ parsedArgs: tc.arguments,
+ }));
+
+ // Create assistant message with tool calls
+ const assistantMessage = {
+ role: "assistant" as const,
+ content: content || "",
+ toolCalls: toolCalls.map((tc) => ({
+ id: tc.id,
+ type: "function" as const,
+ function: {
+ name: tc.name,
+ arguments: JSON.stringify(tc.arguments),
+ },
+ })),
+ };
+
+ chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
+
+ // First preprocess the tool calls
+ const { preprocessedCalls, errorChatEntries } =
+ await preprocessStreamedToolCalls(toolCalls, callbacks);
+
+ // Add any preprocessing errors to chat history
+ // Convert error entries from OpenAI format to ChatHistoryItem format
+ errorChatEntries.forEach((errorEntry) => {
+ chatHistory.push(
+ createHistoryItem({
+ role: "tool",
+ content: stripImages(errorEntry.content) || "",
+ toolCallId: errorEntry.tool_call_id,
+ }),
+ );
+ });
+
+ // Execute the valid preprocessed tool calls
+ const { chatHistoryEntries: toolResults, hasRejection } =
+ await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
+
+ if (isHeadless && hasRejection) {
+ logger.debug(
+ "Tool call rejected in headless mode - returning current content",
+ );
+ return true; // Signal early return needed
+ }
+
+ // Convert tool results from OpenAI format to ChatHistoryItem format
+ // and add them to the chat history
+ toolResults.forEach((toolResult) => {
+ // Find the corresponding tool call state to update
+ const lastAssistantIndex = chatHistory.findLastIndex(
+ (item) => item.message.role === "assistant" && item.toolCallStates,
+ );
+
+ if (
+ lastAssistantIndex >= 0 &&
+ chatHistory[lastAssistantIndex].toolCallStates
+ ) {
+ const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
+ (ts) => ts.toolCallId === toolResult.tool_call_id,
+ );
+
+ if (toolState) {
+ toolState.status = hasRejection ? "canceled" : "done";
+ toolState.output = [
+ {
+ content:
+ typeof toolResult.content === "string" ? toolResult.content : "",
+ name: `Tool Result`,
+ description: "Tool execution result",
+ },
+ ];
+ }
+ }
+ });
+ return false;
+}
+
+export async function getAllTools() {
+ // Get all available tool names
+ const allBuiltinTools = getAllBuiltinTools();
+ const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
+
+ let mcpTools: MCPTool[] = [];
+ let mcpToolNames: string[] = [];
+ const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP);
+ if (mcpServiceResult.state === "ready") {
+ mcpTools = mcpServiceResult?.value?.tools ?? [];
+ mcpToolNames = mcpTools.map((t) => t.name);
+ } else {
+ // MCP is lazy
+ // throw new Error("MCP Service not initialized");
+ }
+
+ const allToolNames = [...builtinToolNames, ...mcpToolNames];
+
+ // Check if the ToolPermissionService is ready
+ const permissionsServiceResult = getServiceSync(
+ SERVICE_NAMES.TOOL_PERMISSIONS,
+ );
+
+ let allowedToolNames: string[];
+ if (
+ permissionsServiceResult.state === "ready" &&
+ permissionsServiceResult.value
+ ) {
+ // Filter out excluded tools based on permissions
+ allowedToolNames = filterExcludedTools(
+ allToolNames,
+ permissionsServiceResult.value.permissions,
+ );
+ } else {
+ // Service not ready - this is a critical error since tools should only be
+ // requested after services are properly initialized
+ logger.error(
+ "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
+ );
+ throw new Error(
+ "ToolPermissionService not initialized. Services must be initialized before requesting tools.",
+ );
+ }
+
+ const allowedToolNamesSet = new Set(allowedToolNames);
+
+ // Filter builtin tools
+ const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
+ allowedToolNamesSet.has(tool.name),
+ );
+
+ const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
+ type: "function" as const,
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: {
+ type: "object",
+ properties: Object.fromEntries(
+ Object.entries(tool.parameters).map(([key, param]) => [
+ key,
+ {
+ type: param.type,
+ description: param.description,
+ items: param.items,
+ },
+ ]),
+ ),
+ required: Object.entries(tool.parameters)
+ .filter(([_, param]) => param.required)
+ .map(([key, _]) => key),
+ },
+ },
+ }));
+
+ // Add filtered MCP tools
+ const allowedMcpTools = mcpTools.filter((tool) =>
+ allowedToolNamesSet.has(tool.name),
+ );
+
+ allTools.push(
+ ...allowedMcpTools.map((tool) => ({
+ type: "function" as const,
+ function: {
+ name: tool.name,
+ description: tool.description,
+ parameters: tool.inputSchema,
+ },
+ })),
+ );
+
+ return allTools;
+}
diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
similarity index 91%
rename from extensions/cli/src/streamChatResponse.autoCompaction.test.ts
rename to extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
index b154ea5e1..b3f550e1d 100644
--- a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts
+++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts
@@ -1,7 +1,7 @@
import type { ChatHistoryItem } from "core/index.js";
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { convertToUnifiedHistory } from "./messageConversion.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
// Mock dependencies
@@ -69,7 +69,7 @@ describe("handleAutoCompaction", () => {
});
it("should return original history when auto-compaction is not needed", async () => {
- const { shouldAutoCompact } = await import("./util/tokenizer.js");
+ const { shouldAutoCompact } = await import("../util/tokenizer.js");
vi.mocked(shouldAutoCompact).mockReturnValue(false);
const result = await handleAutoCompaction(
@@ -90,10 +90,10 @@ describe("handleAutoCompaction", () => {
it("should perform auto-compaction when context limit is approaching", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import(
- "./util/tokenizer.js"
+ "../util/tokenizer.js"
);
- const { compactChatHistory } = await import("./compaction.js");
- const { updateSessionHistory } = await import("./session.js");
+ const { compactChatHistory } = await import("../compaction.js");
+ const { updateSessionHistory } = await import("../session.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
@@ -157,10 +157,10 @@ describe("handleAutoCompaction", () => {
it("should handle compaction errors gracefully", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import(
- "./util/tokenizer.js"
+ "../util/tokenizer.js"
);
- const { compactChatHistory } = await import("./compaction.js");
- const { logger } = await import("./util/logger.js");
+ const { compactChatHistory } = await import("../compaction.js");
+ const { logger } = await import("../util/logger.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
@@ -200,9 +200,9 @@ describe("handleAutoCompaction", () => {
it("should not call system message callback in headless mode", async () => {
const { shouldAutoCompact, getAutoCompactMessage } = await import(
- "./util/tokenizer.js"
+ "../util/tokenizer.js"
);
- const { compactChatHistory } = await import("./compaction.js");
+ const { compactChatHistory } = await import("../compaction.js");
vi.mocked(shouldAutoCompact).mockReturnValue(true);
vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting...");
diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
similarity index 94%
rename from extensions/cli/src/streamChatResponse.autoCompaction.ts
rename to extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
index 9d66bb0bc..4e55a2cd5 100644
--- a/extensions/cli/src/streamChatResponse.autoCompaction.ts
+++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts
@@ -3,11 +3,11 @@ import { BaseLlmApi } from "@continuedev/openai-adapters";
import type { ChatHistoryItem } from "core/index.js";
import React from "react";
-import { compactChatHistory } from "./compaction.js";
-import { updateSessionHistory } from "./session.js";
-import { formatError } from "./util/formatError.js";
-import { logger } from "./util/logger.js";
-import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js";
+import { compactChatHistory } from "../compaction.js";
+import { updateSessionHistory } from "../session.js";
+import { formatError } from "../util/formatError.js";
+import { logger } from "../util/logger.js";
+import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js";
interface AutoCompactionCallbacks {
// For streaming mode
diff --git a/extensions/cli/src/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts
similarity index 97%
rename from extensions/cli/src/streamChatResponse.getAllTools.test.ts
rename to extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts
index d71f75023..8d8eb68a3 100644
--- a/extensions/cli/src/streamChatResponse.getAllTools.test.ts
+++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts
@@ -5,8 +5,9 @@ import {
initializeServices,
SERVICE_NAMES,
serviceContainer,
-} from "./services/index.js";
-import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
+} from "../services/index.js";
+import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
+
import { getAllTools } from "./streamChatResponse.js";
describe("getAllTools - Tool Filtering", () => {
diff --git a/extensions/cli/src/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts
similarity index 96%
rename from extensions/cli/src/streamChatResponse.helpers.ts
rename to extensions/cli/src/stream/streamChatResponse.helpers.ts
index 4a90aedca..4ac0a9e88 100644
--- a/extensions/cli/src/streamChatResponse.helpers.ts
+++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts
@@ -2,21 +2,22 @@
import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs";
-import { checkToolPermission } from "./permissions/permissionChecker.js";
-import { toolPermissionManager } from "./permissions/permissionManager.js";
-import { ToolCallRequest } from "./permissions/types.js";
-import { StreamCallbacks } from "./streamChatResponse.types.js";
-import { telemetryService } from "./telemetry/telemetryService.js";
-import { calculateTokenCost } from "./telemetry/utils.js";
+import { checkToolPermission } from "../permissions/permissionChecker.js";
+import { toolPermissionManager } from "../permissions/permissionManager.js";
+import { ToolCallRequest } from "../permissions/types.js";
+import { telemetryService } from "../telemetry/telemetryService.js";
+import { calculateTokenCost } from "../telemetry/utils.js";
import {
executeToolCall,
getAllBuiltinTools,
getAvailableTools,
Tool,
validateToolCallArgsPresent,
-} from "./tools/index.js";
-import { PreprocessedToolCall, ToolCall } from "./tools/types.js";
-import { logger } from "./util/logger.js";
+} from "../tools/index.js";
+import { PreprocessedToolCall, ToolCall } from "../tools/types.js";
+import { logger } from "../util/logger.js";
+
+import { StreamCallbacks } from "./streamChatResponse.types.js";
// Helper function to handle permission denied
export function handlePermissionDenied(
diff --git a/extensions/cli/src/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts
similarity index 96%
rename from extensions/cli/src/streamChatResponse.modeSwitch.test.ts
rename to extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts
index d662e1744..f5a9e74bd 100644
--- a/extensions/cli/src/streamChatResponse.modeSwitch.test.ts
+++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts
@@ -1,12 +1,13 @@
-import { describe, expect, test, vi, beforeEach } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import {
- serviceContainer,
SERVICE_NAMES,
initializeServices,
-} from "./services/index.js";
-import { modeService } from "./services/ModeService.js";
-import { getAllTools } from "./streamChatResponse.js";
+ serviceContainer,
+} from "../services/index.js";
+import { modeService } from "../services/ModeService.js";
+
+import { getAllTools } from "./handleToolCalls.js";
describe("streamChatResponse - Mode Switch During Streaming", () => {
beforeEach(async () => {
diff --git a/extensions/cli/src/streamChatResponse.test.ts b/extensions/cli/src/stream/streamChatResponse.test.ts
similarity index 96%
rename from extensions/cli/src/streamChatResponse.test.ts
rename to extensions/cli/src/stream/streamChatResponse.test.ts
index 56fb42a23..05fd1a6cf 100644
--- a/extensions/cli/src/streamChatResponse.test.ts
+++ b/extensions/cli/src/stream/streamChatResponse.test.ts
@@ -4,17 +4,18 @@ import type { ChatHistoryItem } from "core/index.js";
import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs";
import { vi } from "vitest";
-import { toolPermissionManager } from "./permissions/permissionManager.js";
+import { toolPermissionManager } from "../permissions/permissionManager.js";
+import { ToolCall } from "../tools/index.js";
+import { readFileTool } from "../tools/readFile.js";
+import { searchCodeTool } from "../tools/searchCode.js";
+import { PreprocessedToolCall } from "../tools/types.js";
+import { writeFileTool } from "../tools/writeFile.js";
+
import {
executeStreamedToolCalls,
preprocessStreamedToolCalls,
} from "./streamChatResponse.helpers.js";
import { processStreamingResponse } from "./streamChatResponse.js";
-import { ToolCall } from "./tools/index.js";
-import { readFileTool } from "./tools/readFile.js";
-import { searchCodeTool } from "./tools/searchCode.js";
-import { PreprocessedToolCall } from "./tools/types.js";
-import { writeFileTool } from "./tools/writeFile.js";
// Test the chunk processing logic that was identified as buggy
describe("processStreamingResponse - content preservation", () => {
@@ -438,7 +439,7 @@ describe.skip("preprocessStreamedToolCalls", () => {
it("handles tool preprocessing errors correctly", async () => {
// Set the spy to throw an error
- const toolsModule = await import("./tools/index.js");
+ const toolsModule = await import("../tools/index.js");
vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce(
() => {
throw new Error("Missing required argument");
@@ -510,12 +511,12 @@ describe.skip("executeStreamedToolCalls", () => {
it("executes tool calls with allowed permissions", async () => {
// Setup spies instead of mocks
- const permissionsModule = await import("./permissions/index.js");
+ const permissionsModule = await import("../permissions/index.js");
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
permission: "allow",
});
- const toolsModule = await import("./tools/index.js");
+ const toolsModule = await import("../tools/index.js");
const mockedExecuteToolCall = vi
.spyOn(toolsModule, "executeToolCall")
.mockResolvedValue("Tool execution successful");
@@ -559,7 +560,7 @@ describe.skip("executeStreamedToolCalls", () => {
it("handles permission denied correctly", async () => {
// Setup permission to ask
- const permissionsModule = await import("./permissions/index.js");
+ const permissionsModule = await import("../permissions/index.js");
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
permission: "ask",
});
@@ -646,12 +647,12 @@ describe.skip("executeStreamedToolCalls", () => {
it("handles tool execution errors", async () => {
// Setup spies
- const permissionsModule = await import("./permissions/index.js");
+ const permissionsModule = await import("../permissions/index.js");
vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({
permission: "allow",
});
- const toolsModule = await import("./tools/index.js");
+ const toolsModule = await import("../tools/index.js");
vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue(
new Error("Execution failed"),
);
diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts
similarity index 58%
rename from extensions/cli/src/streamChatResponse.ts
rename to extensions/cli/src/stream/streamChatResponse.ts
index 290c3bb07..0f5f5edd5 100644
--- a/extensions/cli/src/streamChatResponse.ts
+++ b/extensions/cli/src/stream/streamChatResponse.ts
@@ -1,27 +1,27 @@
import { ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
-import type { ChatHistoryItem, ToolStatus } from "core/index.js";
-import { stripImages } from "core/util/messageContent.js";
+import type { ChatHistoryItem } from "core/index.js";
+import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js";
import * as dotenv from "dotenv";
-import type { ChatCompletionTool } from "openai/resources.mjs";
+import type {
+ ChatCompletionMessageParam,
+ ChatCompletionTool,
+} from "openai/resources.mjs";
+import { getServiceSync, SERVICE_NAMES } from "../services/index.js";
+import { systemMessageService } from "../services/SystemMessageService.js";
+import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js";
+import { telemetryService } from "../telemetry/telemetryService.js";
+import { ToolCall } from "../tools/index.js";
import {
- convertFromUnifiedHistoryWithSystemMessage,
- createHistoryItem,
-} from "./messageConversion.js";
-import { filterExcludedTools } from "./permissions/index.js";
-import {
- getServiceSync,
- MCPServiceState,
- MCPTool,
- SERVICE_NAMES,
-} from "./services/index.js";
-import { systemMessageService } from "./services/SystemMessageService.js";
-import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js";
+ chatCompletionStreamWithBackoff,
+ withExponentialBackoff,
+} from "../util/exponentialBackoff.js";
+import { logger } from "../util/logger.js";
+
+import { getAllTools, handleToolCalls } from "./handleToolCalls.js";
import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js";
import {
- executeStreamedToolCalls,
- preprocessStreamedToolCalls,
processChunkContent,
processToolCallDelta,
recordStreamTelemetry,
@@ -31,13 +31,6 @@ import {
getDefaultCompletionOptions,
StreamCallbacks,
} from "./streamChatResponse.types.js";
-import { telemetryService } from "./telemetry/telemetryService.js";
-import { getAllBuiltinTools, ToolCall } from "./tools/index.js";
-import {
- chatCompletionStreamWithBackoff,
- withExponentialBackoff,
-} from "./util/exponentialBackoff.js";
-import { logger } from "./util/logger.js";
dotenv.config();
@@ -71,209 +64,6 @@ function handleContentDisplay(
}
}
-async function handleToolCalls(
- toolCalls: ToolCall[],
- chatHistory: ChatHistoryItem[],
- content: string,
- callbacks: StreamCallbacks | undefined,
- isHeadless: boolean,
-): Promise {
- if (toolCalls.length === 0) {
- if (content) {
- chatHistory.push(
- createHistoryItem({
- role: "assistant",
- content,
- }),
- );
- }
- return false;
- }
-
- // Create tool call states for the ChatHistoryItem
- const toolCallStates = toolCalls.map((tc) => ({
- toolCallId: tc.id,
- toolCall: {
- id: tc.id,
- type: "function" as const,
- function: {
- name: tc.name,
- arguments: JSON.stringify(tc.arguments),
- },
- },
- status: "generated" as ToolStatus,
- parsedArgs: tc.arguments,
- }));
-
- // Create assistant message with tool calls
- const assistantMessage = {
- role: "assistant" as const,
- content: content || "",
- toolCalls: toolCalls.map((tc) => ({
- id: tc.id,
- type: "function" as const,
- function: {
- name: tc.name,
- arguments: JSON.stringify(tc.arguments),
- },
- })),
- };
-
- chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates));
-
- // First preprocess the tool calls
- const { preprocessedCalls, errorChatEntries } =
- await preprocessStreamedToolCalls(toolCalls, callbacks);
-
- // Add any preprocessing errors to chat history
- // Convert error entries from OpenAI format to ChatHistoryItem format
- errorChatEntries.forEach((errorEntry) => {
- chatHistory.push(
- createHistoryItem({
- role: "tool",
- content: stripImages(errorEntry.content) || "",
- toolCallId: errorEntry.tool_call_id,
- }),
- );
- });
-
- // Execute the valid preprocessed tool calls
- const { chatHistoryEntries: toolResults, hasRejection } =
- await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless);
-
- if (isHeadless && hasRejection) {
- logger.debug(
- "Tool call rejected in headless mode - returning current content",
- );
- return true; // Signal early return needed
- }
-
- // Convert tool results from OpenAI format to ChatHistoryItem format
- // and add them to the chat history
- toolResults.forEach((toolResult) => {
- // Find the corresponding tool call state to update
- const lastAssistantIndex = chatHistory.findLastIndex(
- (item) => item.message.role === "assistant" && item.toolCallStates,
- );
-
- if (
- lastAssistantIndex >= 0 &&
- chatHistory[lastAssistantIndex].toolCallStates
- ) {
- const toolState = chatHistory[lastAssistantIndex].toolCallStates.find(
- (ts) => ts.toolCallId === toolResult.tool_call_id,
- );
-
- if (toolState) {
- toolState.status = hasRejection ? "canceled" : "done";
- toolState.output = [
- {
- content:
- typeof toolResult.content === "string" ? toolResult.content : "",
- name: `Tool Result`,
- description: "Tool execution result",
- },
- ];
- }
- }
- });
- return false;
-}
-
-export async function getAllTools() {
- // Get all available tool names
- const allBuiltinTools = getAllBuiltinTools();
- const builtinToolNames = allBuiltinTools.map((tool) => tool.name);
-
- let mcpTools: MCPTool[] = [];
- let mcpToolNames: string[] = [];
- const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP);
- if (mcpServiceResult.state === "ready") {
- mcpTools = mcpServiceResult?.value?.tools ?? [];
- mcpToolNames = mcpTools.map((t) => t.name);
- } else {
- // MCP is lazy
- // throw new Error("MCP Service not initialized");
- }
-
- const allToolNames = [...builtinToolNames, ...mcpToolNames];
-
- // Check if the ToolPermissionService is ready
- const permissionsServiceResult = getServiceSync(
- SERVICE_NAMES.TOOL_PERMISSIONS,
- );
-
- let allowedToolNames: string[];
- if (
- permissionsServiceResult.state === "ready" &&
- permissionsServiceResult.value
- ) {
- // Filter out excluded tools based on permissions
- allowedToolNames = filterExcludedTools(
- allToolNames,
- permissionsServiceResult.value.permissions,
- );
- } else {
- // Service not ready - this is a critical error since tools should only be
- // requested after services are properly initialized
- logger.error(
- "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue",
- );
- throw new Error(
- "ToolPermissionService not initialized. Services must be initialized before requesting tools.",
- );
- }
-
- const allowedToolNamesSet = new Set(allowedToolNames);
-
- // Filter builtin tools
- const allowedBuiltinTools = allBuiltinTools.filter((tool) =>
- allowedToolNamesSet.has(tool.name),
- );
-
- const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({
- type: "function" as const,
- function: {
- name: tool.name,
- description: tool.description,
- parameters: {
- type: "object",
- properties: Object.fromEntries(
- Object.entries(tool.parameters).map(([key, param]) => [
- key,
- {
- type: param.type,
- description: param.description,
- items: param.items,
- },
- ]),
- ),
- required: Object.entries(tool.parameters)
- .filter(([_, param]) => param.required)
- .map(([key, _]) => key),
- },
- },
- }));
-
- // Add filtered MCP tools
- const allowedMcpTools = mcpTools.filter((tool) =>
- allowedToolNamesSet.has(tool.name),
- );
-
- allTools.push(
- ...allowedMcpTools.map((tool) => ({
- type: "function" as const,
- function: {
- name: tool.name,
- description: tool.description,
- parameters: tool.inputSchema,
- },
- })),
- );
-
- return allTools;
-}
-
// Helper function to process a single chunk
interface ProcessChunkOptions {
chunk: any;
@@ -362,7 +152,7 @@ export async function processStreamingResponse(
const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage(
chatHistory,
systemMessage,
- );
+ ) as ChatCompletionMessageParam[];
const requestStartTime = Date.now();
const streamFactory = async (retryAbortSignal: AbortSignal) => {
@@ -610,3 +400,4 @@ export async function streamChatResponse(
// Otherwise, return the full response
return isHeadless ? finalResponse : fullResponse;
}
+export { getAllTools };
diff --git a/extensions/cli/src/streamChatResponse.types.ts b/extensions/cli/src/stream/streamChatResponse.types.ts
similarity index 95%
rename from extensions/cli/src/streamChatResponse.types.ts
rename to extensions/cli/src/stream/streamChatResponse.types.ts
index b219849fb..405505eee 100644
--- a/extensions/cli/src/streamChatResponse.types.ts
+++ b/extensions/cli/src/stream/streamChatResponse.types.ts
@@ -2,7 +2,7 @@ import { CompletionOptions } from "@continuedev/config-yaml";
import type { ToolStatus } from "core/index.js";
import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs";
-import { ToolCallPreview } from "./tools/types.js";
+import { ToolCallPreview } from "../tools/types.js";
export interface StreamCallbacks {
onContent?: (content: string) => void;
diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx
index 8dc12557a..77b8161ba 100644
--- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx
+++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx
@@ -2,9 +2,10 @@ import { render } from "ink-testing-library";
import React from "react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { getAllTools } from "src/stream/handleToolCalls.js";
+
import { SERVICE_NAMES, serviceContainer } from "../../services/index.js";
import { modeService } from "../../services/ModeService.js";
-import { getAllTools } from "../../streamChatResponse.js";
import { createUITestContext } from "../../test-helpers/ui-test-context.js";
import { AppRoot } from "../AppRoot.js";
diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts
index fe8c2ed8d..70a88a973 100644
--- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts
+++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts
@@ -1,7 +1,7 @@
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
import { ChatCompletionMessageParam } from "openai/resources.mjs";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { convertToUnifiedHistory } from "../../messageConversion.js";
import { startNewSession } from "../../session.js";
import { processSlashCommandResult } from "./useChat.helpers.js";
diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
index 13553cbe0..6997a4c4b 100644
--- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
+++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts
@@ -1,6 +1,6 @@
import type { ChatHistoryItem } from "core/index.js";
+import { convertToUnifiedHistory } from "core/util/messageConversion.js";
-import { convertToUnifiedHistory } from "../../messageConversion.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { logger } from "../../util/logger.js";
diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts
index d6d1ecc4b..d8b15aab3 100644
--- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts
+++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts
@@ -219,7 +219,9 @@ export async function executeStreaming({
currentCompactionIndex,
}: ExecuteStreamingOptions): Promise {
const { getHistoryForLLM } = await import("../../compaction.js");
- const { streamChatResponse } = await import("../../streamChatResponse.js");
+ const { streamChatResponse } = await import(
+ "../../stream/streamChatResponse.js"
+ );
if (model && llmApi) {
if (