fix: types, imports, and formatting
This commit is contained in:
parent
d1c4e64580
commit
626a3c66a0
23 changed files with 324 additions and 326 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
`<context name="${contextItem.name}">\n${contextItem.content}\n</context>\n\n`,
|
||||
)
|
||||
.join("");
|
||||
|
|
@ -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<number | null> {
|
||||
const { handleAutoCompaction: coreAutoCompaction } = await import(
|
||||
"../streamChatResponse.autoCompaction.js"
|
||||
"../stream/streamChatResponse.autoCompaction.js"
|
||||
);
|
||||
|
||||
// Custom callbacks for headless mode console output
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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", () => ({
|
||||
|
|
|
|||
|
|
@ -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", () => {
|
||||
|
|
|
|||
|
|
@ -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", () => ({
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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", () => {
|
||||
|
|
|
|||
224
extensions/cli/src/stream/handleToolCalls.ts
Normal file
224
extensions/cli/src/stream/handleToolCalls.ts
Normal file
|
|
@ -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<boolean> {
|
||||
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<MCPServiceState>(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<ToolPermissionServiceState>(
|
||||
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;
|
||||
}
|
||||
|
|
@ -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...");
|
||||
|
|
@ -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
|
||||
|
|
@ -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", () => {
|
||||
|
|
@ -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(
|
||||
|
|
@ -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 () => {
|
||||
|
|
@ -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"),
|
||||
);
|
||||
|
|
@ -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<boolean> {
|
||||
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<MCPServiceState>(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<ToolPermissionServiceState>(
|
||||
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 };
|
||||
|
|
@ -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;
|
||||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
|
|
@ -219,7 +219,9 @@ export async function executeStreaming({
|
|||
currentCompactionIndex,
|
||||
}: ExecuteStreamingOptions): Promise<void> {
|
||||
const { getHistoryForLLM } = await import("../../compaction.js");
|
||||
const { streamChatResponse } = await import("../../streamChatResponse.js");
|
||||
const { streamChatResponse } = await import(
|
||||
"../../stream/streamChatResponse.js"
|
||||
);
|
||||
|
||||
if (model && llmApi) {
|
||||
if (
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue