diff --git a/.continue/assistants/cli-assistant.yaml b/.continue/assistants/cli-assistant.yaml index 838a59c19..168731625 100644 --- a/.continue/assistants/cli-assistant.yaml +++ b/.continue/assistants/cli-assistant.yaml @@ -1,4 +1,4 @@ -name: CLI Assistant +name: CLI Agent version: 0.0.1 schema: v1 diff --git a/.continue/rules/continue-sdk-cli-and-hub-context.yaml b/.continue/rules/continue-sdk-cli-and-hub-context.yaml index d8d56b7cb..3041db0be 100644 --- a/.continue/rules/continue-sdk-cli-and-hub-context.yaml +++ b/.continue/rules/continue-sdk-cli-and-hub-context.yaml @@ -13,9 +13,9 @@ rules: - Continue SDK: Experimental package in early development, subject to breaking changes - - Continue Hub: Registry for custom AI code assistants + - Continue Hub: Registry for custom AI code agent - - Hub functionality: Manages assistant building blocks (models, rules, + - Hub functionality: Manages agent building blocks (models, rules, context providers, prompts, docs, etc.) - Governance: Allows central configuration for organizations diff --git a/.github/workflows/pr-description.yml.disabled b/.github/workflows/pr-description.yml.disabled index 24e87c4dd..9cdd544b6 100644 --- a/.github/workflows/pr-description.yml.disabled +++ b/.github/workflows/pr-description.yml.disabled @@ -53,7 +53,7 @@ jobs: - name: Analyze PR with Continue id: analyze run: | - continue-cli -p --assistant "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt + continue-cli -p --config "starter/nextjs-assistant" "$(cat prompt.txt)" > analysis.txt echo "analysis_file=analysis.txt" >> $GITHUB_OUTPUT env: ## TODO: This needs to be set on the repo diff --git a/.vscode/launch.json b/.vscode/launch.json index 5b8b7d2e1..c42cd04c7 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -25,7 +25,7 @@ "type": "node", "request": "launch", "program": "${workspaceFolder}/src/index.ts", - "args": ["--config", "nate/default-assistant"], + "args": [], "env": { "NODE_ENV": "development" }, diff --git a/README.md b/README.md index 0bf21c118..c68cf5e9c 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,6 @@ cn --resume ## Command Line Options - `-p`: Run in headless mode (no TUI) -- `--config `: Specify assistant configuration path +- `--config `: Specify agent configuration path - `--resume`: Resume the last session for this terminal - ``: Optional prompt to start with - diff --git a/src/asciiArt.ts b/src/asciiArt.ts index d83a7a20f..305cf75c5 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -1,9 +1,20 @@ +import chalk from "chalk"; + +const b = chalk.bold.magenta; +const d = chalk.dim; + export const CONTINUE_ASCII_ART = ` - _________ _ _____________ ____ ______ - / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ -/ /__/ /_/ / / / / _/ // / /_/ / _/ -\\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ + ${b("_____")}${d("____ ")}${b("_ __")}${d("___________ ____ ______")} + ${b("/ ___/")}${d(" __ \\")}${b("/ |/ /")}${d("_ __/ _/ |/ / / / / __/")} +${b("/ /__")}${d("/ /_/ ")}${b("/ /")}${d(" / / _/ // / /_/ / _/ ")} +${b("\\___/")}${d("\\____")}${b("/_/|_/")}${d(" /_/ /___/_/|_/\\____/___/")} `; +// export const CONTINUE_ASCII_ART = ` +// _________ _ _____________ ____ ______ +// / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ +// / /__/ /_/ / / / / _/ // / /_/ / _/ +// \\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ +// `; export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ -31,7 +42,7 @@ export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ - @@@@@@@@@@@@ + CONTINUE @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ diff --git a/src/auth/workos.ts b/src/auth/workos.ts index ed3222815..f02cb2636 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -427,13 +427,13 @@ export async function login(): Promise { } try { - console.info(chalk.cyan("\nStarting authentication with Continue...")); + console.info(chalk.white("\nSigning in with Continue...")); // Request device authorization const deviceAuth = await requestDeviceAuthorization(); console.info( - chalk.yellow( + chalk.white( `Your authentication code: ${chalk.bold(deviceAuth.user_code)}` ) ); @@ -450,7 +450,7 @@ export async function login(): Promise { console.info(chalk.yellow("Unable to open browser automatically")); } - console.info(chalk.cyan("\nWaiting for confirmation...")); + console.info(chalk.dim("\nWaiting for confirmation...")); // Poll for token const authConfig = await pollForDeviceToken( @@ -459,7 +459,7 @@ export async function login(): Promise { deviceAuth.expires_in ); - console.info(chalk.green("\nAuthentication successful!")); + console.info(chalk.white("āœ… Success!")); return authConfig; } catch (error: any) { diff --git a/src/commands/chat.ts b/src/commands/chat.ts index 32a745738..6fd931102 100644 --- a/src/commands/chat.ts +++ b/src/commands/chat.ts @@ -1,6 +1,7 @@ import chalk from "chalk"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import * as readlineSync from "readline-sync"; +import { CONTINUE_ASCII_ART } from "../asciiArt.js"; import { ensureOrganization, loadAuthConfig } from "../auth/workos.js"; import { introMessage } from "../intro.js"; import { configureLogger } from "../logger.js"; @@ -23,6 +24,9 @@ async function initializeChat(options: ChatOptions) { const authConfig = loadAuthConfig(); // Use onboarding flow for initialization + if (!options.headless) { + console.log(chalk.white(CONTINUE_ASCII_ART)); + } const result = await initializeWithOnboarding(authConfig, options.config); // Ensure organization is selected if authenticated @@ -86,7 +90,10 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { // If no session loaded or not resuming, initialize with system message if (chatHistory.length === 0) { const rulesSystemMessage = ""; // TODO //assistant.systemMessage; - const systemMessage = constructSystemMessage(rulesSystemMessage, options.rule); + const systemMessage = constructSystemMessage( + rulesSystemMessage, + options.rule + ); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } @@ -144,4 +151,4 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { logger.error(chalk.red(`Fatal error: ${formatError(error)}`)); process.exit(1); } -} \ No newline at end of file +} diff --git a/src/commands/commands.ts b/src/commands/commands.ts new file mode 100644 index 000000000..918bb631a --- /dev/null +++ b/src/commands/commands.ts @@ -0,0 +1,91 @@ +import { type AssistantConfig } from "@continuedev/sdk"; + +export interface SlashCommand { + name: string; + description: string; + category: "system" | "assistant"; +} + +export interface SystemCommand extends SlashCommand { + category: "system"; + requiresMultipleOrgs?: boolean; +} + +// Central definition of all system slash commands +export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ + { + name: "help", + description: "Show help message", + category: "system", + }, + { + name: "clear", + description: "Clear the chat history", + category: "system", + }, + { + name: "exit", + description: "Exit the chat", + category: "system", + }, + { + name: "login", + description: "Authenticate with your account", + category: "system", + }, + { + name: "logout", + description: "Sign out of your current session", + category: "system", + }, + { + name: "whoami", + description: "Check who you're currently logged in as", + category: "system", + }, + { + name: "org", + description: "Switch organization", + category: "system", + requiresMultipleOrgs: true, + }, + { + name: "config", + description: "Switch configuration", + category: "system", + }, +]; + +/** + * Get all available slash commands including system commands and assistant prompts + */ +export function getAllSlashCommands( + assistant: AssistantConfig +): SlashCommand[] { + // Filter system commands based on requirements + const systemCommands = SYSTEM_SLASH_COMMANDS; + // Get assistant prompt commands + const assistantCommands: SlashCommand[] = + assistant.prompts?.map((prompt) => ({ + name: prompt?.name || "", + description: prompt?.description || "", + category: "assistant" as const, + })) || []; + + return [...systemCommands, ...assistantCommands]; +} + +/** + * Get assistant prompt commands only + */ +export function getAssistantSlashCommands( + assistant: AssistantConfig +): SlashCommand[] { + return ( + assistant.prompts?.map((prompt) => ({ + name: prompt?.name || "", + description: prompt?.description || "", + category: "assistant" as const, + })) || [] + ); +} diff --git a/src/config.ts b/src/config.ts index 1553d9807..564902a74 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,6 @@ import { AssistantUnrolled, + ModelConfig, RegistryClient, unrollAssistant, } from "@continuedev/config-yaml"; @@ -13,6 +14,7 @@ import { DefaultApi, DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; +import chalk from "chalk"; import { dirname } from "node:path"; import { AuthConfig, @@ -27,7 +29,7 @@ import { MCPService } from "./mcp.js"; export function getLlmApi( assistant: AssistantUnrolled, authConfig: AuthConfig -): [BaseLlmApi, string] { +): [BaseLlmApi, ModelConfig] { const model = assistant.models?.find((model) => model?.roles?.includes("chat") ); @@ -71,7 +73,7 @@ export function getLlmApi( ); } - return [llmApi, model.model]; + return [llmApi, model]; } async function loadConfigYaml( @@ -97,9 +99,15 @@ async function loadConfigYaml( } ); - if (unrollResult.errors?.length || !unrollResult.config) { - const errorDetails = unrollResult.errors?.join("\n") ?? "Unknown error"; + const errorDetails = unrollResult.errors; + if (!unrollResult.config) { throw new Error(`Failed to load config file:\n${errorDetails}`); + } else if (errorDetails?.length) { + const warnings = + errorDetails?.length > 1 + ? errorDetails.map((d) => `\n- ${d.message}`) + : errorDetails[0].message; + console.warn(chalk.dim(`Warning: ${warnings}`)); } return unrollResult.config; @@ -179,12 +187,10 @@ export async function initialize( ): Promise<{ config: AssistantUnrolled; llmApi: BaseLlmApi; - model: string; + model: ModelConfig; mcpService: MCPService; }> { - const accessToken = getAccessToken(authConfig); const organizationId = getOrganizationId(authConfig); - const config = await loadConfig(authConfig, configPath, organizationId); const [llmApi, model] = getLlmApi(config, authConfig); const mcpService = await MCPService.create(config); diff --git a/src/intro.ts b/src/intro.ts index 02c011c14..fa55d43ff 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -1,9 +1,8 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; -import { CONTINUE_ASCII_ART } from "./asciiArt.js"; +import { getAllSlashCommands } from "./commands/commands.js"; import { MCPService } from "./mcp.js"; -import { getAllTools } from "./streamChatResponse.js"; export function loadSystemMessage( assistant: AssistantConfig @@ -14,43 +13,42 @@ export function loadSystemMessage( .join("\n"); } -export function introMessage( +export async function introMessage( config: AssistantUnrolled, - modelName: string, + model: ModelConfig, mcpService: MCPService ) { const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - console.info(chalk.cyan(CONTINUE_ASCII_ART)); + // Get all slash commands from central definition + const allCommands = getAllSlashCommands(config); - console.info(`\n${chalk.bold.blue(`Agent: ${config.name}\n`)}`); - console.info(`${chalk.yellow("Model:")} ${modelName.split("/").pop()}\n`); + console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); + console.info(`${chalk.blue("Model:")} ${model.name.split("/").pop()}\n`); - console.info(chalk.yellow("Tools:")); - getAllTools().forEach((tool) => { + // console.info(chalk.blue("Tools:")); + // BUILTIN_TOOLS.forEach((tool) => { + // console.info( + // `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.description ?? "")}` + // ); + // }); + // console.info(""); + + console.info(chalk.blue("Slash commands:")); + + // Display all commands from central definition + for (const command of allCommands) { console.info( - `- ${chalk.green(tool.function.name)}: ${tool.function.description ?? ""}` + `- ${chalk.white("/" + command.name)}: ${chalk.dim(command.description)}` ); - }); - console.info(""); - - console.info(chalk.yellow("Slash commands:")); - console.info(`- ${chalk.green("/exit")}: Exit the chat`); - console.info(`- ${chalk.green("/clear")}: Clear the chat history`); - console.info(`- ${chalk.green("/help")}: Show help message`); - console.info(`- ${chalk.green("/login")}: Authenticate with your account`); - console.info(`- ${chalk.green("/logout")}: Sign out of your current session`); - console.info( - `- ${chalk.green("/whoami")}: Check who you're currently logged in as` - ); - console.info(`- ${chalk.green("/org")}: Switch organization`); - console.info(`- ${chalk.green("/config")}: Switch configuration`); - for (const prompt of config.prompts ?? []) { - console.info(`- /${prompt?.name}: ${prompt?.description}`); } + + // Display MCP prompts separately since they're not part of our central definition for (const prompt of mcpPrompts) { - console.info(`- /${prompt.name}: ${prompt.description}`); + console.info( + `- ${chalk.white("/" + prompt.name)}: ${chalk.dim(prompt.description)}` + ); } console.info(""); diff --git a/src/onboarding.ts b/src/onboarding.ts index 70d9bc2e2..86b2dccb3 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import chalk from "chalk"; import * as fs from "fs"; @@ -14,7 +14,7 @@ const CONFIG_PATH = path.join(os.homedir(), ".continue", "config.yaml"); export interface OnboardingResult { config: AssistantUnrolled; llmApi: BaseLlmApi; - model: string; + model: ModelConfig; mcpService: MCPService; wasOnboarded: boolean; } @@ -103,41 +103,35 @@ export async function runOnboardingFlow( configPath: string | undefined, authConfig: AuthConfig ): Promise { - console.log(chalk.cyan("\nšŸš€ Welcome to Continue CLI!")); - // Step 1: Check if --config flag is provided if (configPath) { const result = await initialize(authConfig, configPath); return { ...result, wasOnboarded: false }; } - // Step 2: Present user with two options (no longer auto-load config.yaml) - console.log(chalk.yellow("Choose how you'd like to set up your agent:")); - console.log(chalk.white("1. Log in with Continue")); - console.log(chalk.white("2. Enter your Anthropic API key")); + // Step 2: Present user with two options + console.log(chalk.yellow("How do you want to get started?")); + console.log(chalk.white("1. ā© Log in with Continue")); + console.log(chalk.white("2. šŸ”‘ Enter your Anthropic API key")); - const choice = readlineSync.question( - chalk.green("\nSelect option (1 or 2): ") - ); + const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { + limit: ["1", "2", ""], + limitMessage: chalk.dim("Please enter 1 or 2"), + }); - if (choice === "1") { - console.log(chalk.cyan("\nšŸ” Logging in with Continue...")); - try { - const newAuthConfig = await login(); + if (choice === "1" || choice === "") { + const newAuthConfig = await login(); - const result = await initialize(newAuthConfig, undefined); - return { ...result, wasOnboarded: true }; - } catch (error) { - console.error( - chalk.red("āŒ Login failed. Please try again or use option 2.") - ); - throw error; - } + const result = await initialize(newAuthConfig, undefined); + return { ...result, wasOnboarded: true }; } else if (choice === "2") { - console.log(chalk.cyan("\nšŸ”‘ Setting up with Anthropic API key...")); const apiKey = readlineSync.question( - chalk.green("Enter your Anthropic API key: "), + chalk.white("\nEnter your Anthropic API key: "), { + limit: /^sk-ant-.+$/, // Must start with "sk-ant-" and have additional characters + limitMessage: chalk.dim( + "Please enter a valid Anthropic key that starts with 'sk-ant'" + ), hideEchoBack: true, } ); diff --git a/src/slashCommands.ts b/src/slashCommands.ts index a978b513c..40fb81541 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -7,6 +7,7 @@ import { login, logout, } from "./auth/workos.js"; +import { getAllSlashCommands } from "./commands/commands.js"; export async function handleSlashCommands( input: string, @@ -25,19 +26,10 @@ export async function handleSlashCommands( const [command, ...args] = input.slice(1).split(" "); switch (command) { case "help": + const allCommands = getAllSlashCommands(assistant); const helpMessage = [ "Available commands:", - "/help - Show this help message", - "/clear - Clear the chat history", - "/exit - Exit the chat", - "/login - Authenticate with your account", - "/logout - Sign out of your current session", - "/whoami - Check who you're currently logged in as", - "/org - Switch organization", - "/config - Switch configuration", - ...(assistant.prompts?.map( - (prompt) => `/${prompt?.name} - ${prompt?.description}` - ) ?? []), + ...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`), ].join("\n"); return { output: helpMessage }; case "clear": @@ -58,7 +50,7 @@ export async function handleSlashCommands( } else { console.info(chalk.green(`\nLogged in successfully`)); } - + // Reload everything after successful login if (onReload) { await onReload(); @@ -112,4 +104,4 @@ export async function handleSlashCommands( } } return null; -} \ No newline at end of file +} diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index fb097076b..f16d9e0ad 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -1,7 +1,9 @@ +import { CompletionOptions, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import chalk from "chalk"; import * as dotenv from "dotenv"; import type { + ChatCompletionCreateParamsStreaming, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, @@ -10,19 +12,22 @@ import { parseArgs } from "./args.js"; import { MCPService } from "./mcp.js"; import { executeToolCall } from "./tools.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; -import { chatCompletionStreamWithBackoff, withExponentialBackoff } from "./util/exponentialBackoff.js"; +import { + chatCompletionStreamWithBackoff, + withExponentialBackoff, +} from "./util/exponentialBackoff.js"; import logger from "./util/logger.js"; dotenv.config(); export function getAllTools() { const args = parseArgs(); - + // If no-tools mode is enabled, return empty array if (args.noTools) { return []; } - + const allTools: ChatCompletionTool[] = BUILTIN_TOOLS.map((tool) => ({ type: "function" as const, function: { @@ -59,8 +64,6 @@ export function getAllTools() { return allTools; } -type TODO = any; - export interface StreamCallbacks { onContent?: (content: string) => void; onContentComplete?: (content: string) => void; @@ -69,199 +72,264 @@ export interface StreamCallbacks { onToolError?: (error: string, toolName?: string) => void; } -// Define a function to handle streaming responses with tool calling +interface ToolCall { + id: string; + name: string; + arguments: any; + argumentsStr: string; + startNotified: boolean; +} + +function getDefaultCompletionOptions( + opts?: CompletionOptions +): Partial { + if (!opts) return {}; + return { + max_tokens: opts.maxTokens, + temperature: opts.temperature, + frequency_penalty: opts.frequencyPenalty, + presence_penalty: opts.presencePenalty, + top_p: opts.topP, + }; +} + +// Process a single streaming response and return whether we need to continue +async function processStreamingResponse( + chatHistory: ChatCompletionMessageParam[], + model: ModelConfig, + llmApi: BaseLlmApi, + abortController: AbortController, + callbacks?: StreamCallbacks, + isHeadless?: boolean, + tools?: ChatCompletionTool[] +): Promise<{ + content: string; + toolCalls: ToolCall[]; + shouldContinue: boolean; +}> { + const streamFactory = async () => { + logger.debug("Creating chat completion stream", { + model, + messageCount: chatHistory.length, + toolCount: tools?.length || 0, + }); + return await chatCompletionStreamWithBackoff( + llmApi, + { + model: model.model, + messages: chatHistory, + stream: true, + tools, + ...getDefaultCompletionOptions(model.defaultCompletionOptions), + }, + abortController.signal + ); + }; + + let aiResponse = ""; + const toolCallsMap = new Map(); + + try { + const streamWithBackoff = withExponentialBackoff( + streamFactory, + abortController.signal + ); + + let chunkCount = 0; + for await (const chunk of streamWithBackoff) { + chunkCount++; + + logger.debug("Received chunk", { chunkCount, chunk }); + + // Check if we should abort + if (abortController?.signal.aborted) { + logger.debug("Stream aborted"); + break; + } + + // Handle regular content + if (chunk.choices[0].delta.content) { + const content = chunk.choices[0].delta.content; + if (callbacks?.onContent) { + callbacks.onContent(content); + } else if (!isHeadless) { + process.stdout.write(chalk.white(content)); + } + aiResponse += content; + } + + // Handle tool calls + if (chunk.choices[0].delta.tool_calls) { + for (const toolCallDelta of chunk.choices[0].delta.tool_calls) { + // Get or create tool call + if (toolCallDelta.id) { + if (!toolCallsMap.has(toolCallDelta.id)) { + toolCallsMap.set(toolCallDelta.id, { + id: toolCallDelta.id, + name: "", + arguments: null, + argumentsStr: "", + startNotified: false, + }); + } + } + + const toolCall = toolCallsMap.get(toolCallDelta.id || ""); + if (!toolCall) continue; + + // Update name + if (toolCallDelta.function?.name) { + toolCall.name = toolCallDelta.function.name; + } + + // Accumulate arguments + if (toolCallDelta.function?.arguments) { + toolCall.argumentsStr += toolCallDelta.function.arguments; + + // Try to parse when we might have complete JSON + try { + toolCall.arguments = JSON.parse(toolCall.argumentsStr); + + // Notify on first successful parse + if (!toolCall.startNotified && toolCall.name) { + toolCall.startNotified = true; + if (callbacks?.onToolStart) { + callbacks.onToolStart(toolCall.name, toolCall.arguments); + } else if (!isHeadless) { + process.stdout.write( + `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold( + toolCall.name + )}${chalk.yellow("]")}` + ); + } + } + } catch (e) { + // JSON not complete yet, continue + } + } + } + } + } + + logger.debug("Stream complete", { + chunkCount, + responseLength: aiResponse.length, + toolCallsCount: toolCallsMap.size, + }); + } catch (error: any) { + if (error.name === "AbortError" || abortController?.signal.aborted) { + logger.debug("Stream aborted by user"); + return { content: aiResponse, toolCalls: [], shouldContinue: false }; + } + throw error; + } + + const toolCalls = Array.from(toolCallsMap.values()); + + // Validate tool calls have complete arguments + const validToolCalls = toolCalls.filter((tc) => { + if (!tc.arguments || !tc.name) { + logger.error("Incomplete tool call", { + id: tc.id, + name: tc.name, + hasArguments: !!tc.arguments, + argumentsStr: tc.argumentsStr, + }); + return false; + } + return true; + }); + + return { + content: aiResponse, + toolCalls: validToolCalls, + shouldContinue: validToolCalls.length > 0, + }; +} + +// Main function that handles the conversation loop export async function streamChatResponse( chatHistory: ChatCompletionMessageParam[], - model: string, + model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, callbacks?: StreamCallbacks ) { + logger.debug("streamChatResponse called", { + model, + historyLength: chatHistory.length, + hasCallbacks: !!callbacks, + }); + const args = parseArgs(); const isHeadless = args.isHeadless; - // Prepare tools for the API call - const toolsForRequest = getAllTools(); + const tools = getAllTools(); + + logger.debug("Tools prepared", { + toolCount: tools.length, + toolNames: tools.map((t) => t.function.name), + }); let fullResponse = ""; - let currentToolCalls: TODO[] = []; - let shouldContinueConversation = true; - while (shouldContinueConversation) { - logger.debug('Starting new conversation iteration', { hasToolCalls: currentToolCalls.length > 0 }); - // Factory function to create the stream generator - const streamFactory = async () => { - logger.debug('Creating chat completion stream', { model, messageCount: chatHistory.length, toolCount: toolsForRequest.length }); - return await chatCompletionStreamWithBackoff( + while (true) { + logger.debug("Starting conversation iteration"); + + // Get response from LLM + const { content, toolCalls, shouldContinue } = + await processStreamingResponse( + chatHistory, + model, llmApi, - { - model, - messages: chatHistory, - stream: true, - tools: toolsForRequest, - }, - abortController.signal - ); - }; - - let aiResponse = ""; - currentToolCalls = []; - let currentToolCallId = ""; - let toolArguments = ""; - - try { - // Use the exponential backoff wrapper for the entire stream - const streamWithBackoff = withExponentialBackoff( - streamFactory, - abortController.signal + abortController, + callbacks, + isHeadless, + tools ); - for await (const chunk of streamWithBackoff) { - logger.debug('Received stream chunk', { hasContent: !!chunk.choices[0].delta.content, hasToolCalls: !!chunk.choices[0].delta.tool_calls }); - // Check if we should abort - if (abortController?.signal.aborted) { - break; - } + fullResponse += content; - // Handle regular content - if (chunk.choices[0].delta.content) { - const content = chunk.choices[0].delta.content; - if (callbacks?.onContent) { - callbacks.onContent(content); - } else if (!isHeadless) { - process.stdout.write(chalk.white(content)); - } - aiResponse += content; - fullResponse += content; - } - - // Handle tool calls - if (chunk.choices[0].delta.tool_calls) { - for (const toolCallDelta of chunk.choices[0].delta.tool_calls) { - // Initialize a new tool call if we get an index and id - if (toolCallDelta.index !== undefined && toolCallDelta.id) { - if (!currentToolCalls[toolCallDelta.index]) { - currentToolCalls[toolCallDelta.index] = { - id: toolCallDelta.id, - name: "", - arguments: {}, - startNotified: false, - }; - } - currentToolCallId = toolCallDelta.id; - } - - // Add function name if present - if (toolCallDelta.function?.name) { - const toolCall = currentToolCalls.find( - (tc) => tc.id === currentToolCallId - ); - if (toolCall) { - if (!toolCall.name) { - toolCall.name = toolCallDelta.function.name; - toolCall.startNotified = false; - } - } - } - - // Collect function arguments - if (toolCallDelta.function?.arguments) { - const toolCall = currentToolCalls.find( - (tc) => tc.id === currentToolCallId - ); - if (toolCall) { - // Accumulate arguments as string to later parse as JSON - toolArguments += toolCallDelta.function.arguments; - - try { - // Try to parse complete JSON - const parsed = JSON.parse(toolArguments); - toolCall.arguments = parsed; - - // Notify start if we haven't already and have both name and args - if (toolCall.name && !toolCall.startNotified) { - toolCall.startNotified = true; - if (callbacks?.onToolStart) { - callbacks.onToolStart(toolCall.name, toolCall.arguments); - } else if (!isHeadless) { - process.stdout.write( - `\n${chalk.yellow("[Using tool:")} ${chalk.yellow.bold( - toolCall.name - )}${chalk.yellow("]")}` - ); - } - } - } catch (e) { - // Not complete JSON yet, continue collecting - } - } - } - } - } - } - } catch (error: any) { - // Handle AbortError gracefully - this is expected when user cancels - if (error.name === 'AbortError' || abortController?.signal.aborted) { - // Stream was aborted, this is expected behavior - return fullResponse; - } - // For other errors, re-throw them - logger.error( - chalk.red("Error in streamChatResponse:"), - error - ); - throw error; + // Add newline after content if needed + if (!callbacks?.onContent && !isHeadless && content) { + logger.info(""); } - if (!callbacks?.onContent && !isHeadless) { - logger.info(""); // Add a newline after the response + // Notify content complete + if (content && callbacks?.onContentComplete) { + callbacks.onContentComplete(content); } - // Notify that content is complete if we have content and are about to process tool calls - if ( - aiResponse.trim() && - currentToolCalls.length > 0 && - callbacks?.onContentComplete - ) { - callbacks.onContentComplete(aiResponse); - } - - // Add the assistant's response to chat history if there's content or tool calls - if (currentToolCalls.length > 0) { - const toolCalls: ChatCompletionMessageToolCall[] = currentToolCalls.map( - (tc) => ({ + // Add assistant message to history + if (toolCalls.length > 0) { + const toolCallsForHistory: ChatCompletionMessageToolCall[] = + toolCalls.map((tc) => ({ id: tc.id, type: "function", function: { name: tc.name, arguments: JSON.stringify(tc.arguments), }, - }) - ); + })); + chatHistory.push({ role: "assistant", - content: aiResponse, - tool_calls: toolCalls, + content: content || null, + tool_calls: toolCallsForHistory, }); - } else if (aiResponse.trim()) { - // Only add assistant response if there's actual content - chatHistory.push({ role: "assistant", content: aiResponse }); - // Also notify content complete for standalone messages - if (callbacks?.onContentComplete) { - callbacks.onContentComplete(aiResponse); - } - } - // If we have tool calls, execute them - if (currentToolCalls.length > 0) { - for (const toolCall of currentToolCalls) { + // Execute tool calls + for (const toolCall of toolCalls) { try { - // Execute the tool + logger.debug("Executing tool", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + const toolResult = await executeToolCall({ name: toolCall.name, arguments: toolCall.arguments, }); - // Add tool result to chat history chatHistory.push({ role: "tool", tool_call_id: toolCall.id, @@ -277,30 +345,45 @@ export async function streamChatResponse( const errorMessage = `Error executing tool ${toolCall.name}: ${ error instanceof Error ? error.message : String(error) }`; + + logger.error("Tool execution failed", { + name: toolCall.name, + error: errorMessage, + }); + chatHistory.push({ role: "tool", tool_call_id: toolCall.id, content: errorMessage, }); + if (callbacks?.onToolError) { callbacks.onToolError(errorMessage, toolCall.name); } else if (!isHeadless) { console.info( `${chalk.red("[Tool error:")} ${chalk.red( errorMessage - )}${chalk.red(")")}` + )}${chalk.red("]")}` ); } } } + } else if (content) { + // Just content, no tools + chatHistory.push({ role: "assistant", content }); + } - // Continue the conversation with the tool results - shouldContinueConversation = true; - } else { - // No more tool calls, end the conversation - shouldContinueConversation = false; + // Check if we should continue + if (!shouldContinue) { + logger.debug("Conversation complete - no more tool calls"); + break; } } + logger.debug("streamChatResponse complete", { + totalResponseLength: fullResponse.length, + totalMessages: chatHistory.length, + }); + return fullResponse; -} \ No newline at end of file +} diff --git a/src/tools/fetch.ts b/src/tools/fetch.ts index d2a7c897c..f075feca8 100644 --- a/src/tools/fetch.ts +++ b/src/tools/fetch.ts @@ -1,5 +1,5 @@ -import { Tool } from "./types.js"; import TurndownService from "turndown"; +import { Tool } from "./types.js"; const turndownService = new TurndownService({ headingStyle: "atx", @@ -31,7 +31,7 @@ turndownService.addRule("pre", { export const fetchTool: Tool = { name: "fetch", - displayName: "Fetch URL", + displayName: "Fetch", description: "Fetches content from a URL and converts it to markdown format", parameters: { url: { @@ -64,7 +64,8 @@ export const fetchTool: Tool = { signal: controller.signal, headers: { "User-Agent": "Continue-CLI/1.0 (https://continue.dev)", - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + Accept: + "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Cache-Control": "no-cache", @@ -78,7 +79,7 @@ export const fetchTool: Tool = { } const contentType = response.headers.get("content-type") || ""; - + // Handle different content types if (contentType.includes("application/json")) { const json = await response.json(); @@ -96,10 +97,10 @@ export const fetchTool: Tool = { // Process HTML content const html = await response.text(); - + // Convert HTML to markdown const markdown = turndownService.turndown(html); - + // Clean up the markdown const cleanedMarkdown = markdown .replace(/\n\s*\n\s*\n/g, "\n\n") // Remove excessive newlines @@ -108,7 +109,6 @@ export const fetchTool: Tool = { .replace(/\\\]/g, "]"); return `# Content from ${url}\n\n${cleanedMarkdown}`; - } catch (error) { if (error instanceof TypeError && error.message.includes("fetch")) { return `Error: Failed to fetch URL "${url}". Please check the URL and try again.`; @@ -119,4 +119,4 @@ export const fetchTool: Tool = { return `Error: ${error instanceof Error ? error.message : String(error)}`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/index.ts b/src/tools/index.ts index 37b5bd2a5..b4990df2a 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -1,5 +1,6 @@ import { parseArgs } from "../args.js"; import { MCPService } from "../mcp.js"; +import logger from "../util/logger.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; @@ -7,9 +8,7 @@ import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; import { searchCodeTool } from "./searchCode.js"; import { type Tool, type ToolParameters } from "./types.js"; -import { viewDiffTool } from "./viewDiff.js"; import { writeFileTool } from "./writeFile.js"; -import logger from "../util/logger.js"; export type { Tool, ToolParameters }; @@ -17,7 +16,6 @@ const ALL_BUILTIN_TOOLS: Tool[] = [ readFileTool, writeFileTool, listFilesTool, - viewDiffTool, searchCodeTool, runTerminalCommandTool, fetchTool, @@ -165,9 +163,15 @@ export async function executeToolCall(toolCall: { } try { - logger.debug('Executing tool', { toolName: toolCall.name, arguments: toolCall.arguments }); + logger.debug("Executing tool", { + toolName: toolCall.name, + arguments: toolCall.arguments, + }); const result = await tool.run(toolCall.arguments); - logger.debug('Tool execution completed', { toolName: toolCall.name, resultLength: result?.length || 0 }); + logger.debug("Tool execution completed", { + toolName: toolCall.name, + resultLength: result?.length || 0, + }); return result; } catch (error) { return `Error executing tool "${toolCall.name}": ${ diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index b4161c6cc..2462a0207 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -1,10 +1,10 @@ -import { Tool } from "./types.js"; import { exec } from "child_process"; +import { Tool } from "./types.js"; export const runTerminalCommandTool: Tool = { name: "run_terminal_command", - displayName: "Terminal", - description: "Executes a terminal command and returns the output.", + displayName: "Bash", + description: "Executes a terminal command and returns the output", parameters: { command: { type: "string", @@ -28,4 +28,4 @@ export const runTerminalCommandTool: Tool = { }); }); }, -}; \ No newline at end of file +}; diff --git a/src/ui/LoadingAnimation.tsx b/src/ui/LoadingAnimation.tsx index d955de134..4debfe1a3 100644 --- a/src/ui/LoadingAnimation.tsx +++ b/src/ui/LoadingAnimation.tsx @@ -150,7 +150,7 @@ interface LoadingAnimationProps { const LoadingAnimation: React.FC = ({ visible = true, - color = "blue", + color = "magenta", }) => { const [currentIndex, setCurrentIndex] = useState(0); const animationChars = diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 089b28987..a62ccd8c3 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,72 +1,27 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text } from "ink"; import React, { useEffect, useState } from "react"; -import { hasMultipleOrganizations } from "../auth/workos.js"; +import { + getAllSlashCommands, + type SlashCommand, +} from "../commands/commands.js"; interface SlashCommandUIProps { assistant: AssistantConfig; filter: string; selectedIndex: number; - onSelect: (command: string) => void; -} - -interface SlashCommand { - name: string; - description: string; - category: "system" | "assistant"; } const SlashCommandUI: React.FC = ({ assistant, filter, selectedIndex, - onSelect, }) => { - const [hasMultipleOrgs, setHasMultipleOrgs] = useState(false); + const [allCommands, setAllCommands] = useState([]); useEffect(() => { - hasMultipleOrganizations().then(setHasMultipleOrgs); - }, []); - - // Get all available slash commands - const getSlashCommands = (): SlashCommand[] => { - const systemCommands: SlashCommand[] = [ - { name: "help", description: "Show help message", category: "system" }, - { name: "clear", description: "Clear the chat history", category: "system" }, - { name: "exit", description: "Exit the chat", category: "system" }, - { - name: "login", - description: "Authenticate with your account", - category: "system", - }, - { - name: "logout", - description: "Sign out of your current session", - category: "system", - }, - { - name: "whoami", - description: "Check who you're currently logged in as", - category: "system", - }, - ...(hasMultipleOrgs ? [{ - name: "org", - description: "Switch organization", - category: "system" as const, - }] : []), - ]; - - const assistantCommands: SlashCommand[] = - assistant.prompts?.map((prompt) => ({ - name: prompt?.name || "", - description: prompt?.description || "", - category: "assistant" as const, - })) || []; - - return [...systemCommands, ...assistantCommands]; - }; - - const allCommands = getSlashCommands(); + setAllCommands(getAllSlashCommands(assistant)); + }, [assistant]); // Filter commands based on the current filter const filteredCommands = allCommands diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index ea84a3734..1a8709c87 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { Box, Text } from "ink"; import React, { useState } from "react"; @@ -13,11 +13,12 @@ import { useMessageRenderer } from "./hooks/useMessageRenderer.js"; import { useOrganizationSelector } from "./hooks/useOrganizationSelector.js"; import LoadingAnimation from "./LoadingAnimation.js"; import OrganizationSelector from "./OrganizationSelector.js"; +import Timer from "./Timer.js"; import UserInput from "./UserInput.js"; interface TUIChatProps { config: AssistantUnrolled; - model: string; + model: ModelConfig; llmApi: BaseLlmApi; mcpService: MCPService; configPath?: string; @@ -100,6 +101,7 @@ const TUIChat: React.FC = ({ messages, setMessages, isWaitingForResponse, + responseStartTime, inputMode, handleUserMessage, handleInterrupt, @@ -168,10 +170,12 @@ const TUIChat: React.FC = ({ {/* Fixed bottom section */} {/* Status */} - {isWaitingForResponse && ( + {isWaitingForResponse && responseStartTime && ( - esc to interrupt + ( + + • esc to interrupt ) )} @@ -234,4 +238,4 @@ const TUIChat: React.FC = ({ ); }; -export default TUIChat; \ No newline at end of file +export default TUIChat; diff --git a/src/ui/Timer.tsx b/src/ui/Timer.tsx new file mode 100644 index 000000000..32fc2e090 --- /dev/null +++ b/src/ui/Timer.tsx @@ -0,0 +1,25 @@ +import { Text } from "ink"; +import React, { useEffect, useState } from "react"; + +interface TimerProps { + startTime: number; + color?: string; +} + +const Timer: React.FC = ({ startTime, color = "gray" }) => { + const [elapsed, setElapsed] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + const now = Date.now(); + const elapsedSeconds = Math.floor((now - startTime) / 1000); + setElapsed(elapsedSeconds); + }, 1000); // Update every 1000ms for efficient display + + return () => clearInterval(interval); + }, [startTime]); + + return {elapsed}s; +}; + +export default Timer; \ No newline at end of file diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index ae965edaa..7204ce830 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -91,14 +91,31 @@ const UserInput: React.FC = ({ // Only show slash commands if slash is the very first character if (text.trimStart().startsWith("/")) { const trimmedText = text.trimStart(); - const beforeCursor = trimmedText.slice(0, cursor - (text.length - trimmedText.length)); - + const beforeCursor = trimmedText.slice( + 0, + cursor - (text.length - trimmedText.length) + ); + // Only show if cursor is after the slash and before any whitespace if (beforeCursor.length > 0 && beforeCursor.startsWith("/")) { const afterSlash = beforeCursor.slice(1); - + if (!afterSlash.includes(" ") && !afterSlash.includes("\n")) { - // We're in a slash command context + // We're in a slash command context - check if it's a complete command + const allCommands = getSlashCommands(); + const exactMatch = allCommands.find(cmd => cmd.name === afterSlash); + + // Hide selector if we have an exact match and there's more content after the cursor + if (exactMatch) { + const restOfText = text.slice(cursor); + // If there's a space immediately after cursor, or we're at end of line/text, hide selector + if (restOfText.startsWith(" ") || restOfText === "" || restOfText.startsWith("\n")) { + setShowSlashCommands(false); + return; + } + } + + // Show selector for partial matches setShowSlashCommands(true); setSlashCommandFilter(afterSlash); setSelectedCommandIndex(0); @@ -488,7 +505,6 @@ const UserInput: React.FC = ({ assistant={assistant} filter={slashCommandFilter} selectedIndex={selectedCommandIndex} - onSelect={selectSlashCommand} /> )} @@ -505,4 +521,4 @@ const UserInput: React.FC = ({ ); }; -export default UserInput; +export default UserInput; \ No newline at end of file diff --git a/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/src/ui/__tests__/TUIChat.slashCommands.test.tsx index d01ea6247..f00cb9aa1 100644 --- a/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -11,7 +11,7 @@ describe("TUIChat - Slash Commands Tests", () => { stdin.write("/log"); // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, 100)); const frame = lastFrame(); @@ -38,4 +38,89 @@ describe("TUIChat - Slash Commands Tests", () => { // Should autocomplete to /login (first matching command) expect(frameAfterTab).toContain("/login "); }); + + it("hides slash command selector when complete command is typed", async () => { + const { lastFrame, stdin } = render(); + + // Type /cle to show partial command dropdown + stdin.write("/cle"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const framePartial = lastFrame(); + + // Should show the slash command dropdown for partial match + expect(framePartial).toContain("/clear"); + expect(framePartial).toContain("Clear the chat history"); + + // Type the rest to complete the command /clear + stdin.write("ar"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the slash command dropdown anymore since we have a complete command + expect(frameComplete).not.toContain("Clear the chat history"); + expect(frameComplete).not.toContain( + "Use ↑/↓ to navigate, Enter to select, Tab to complete" + ); + + // But should still show the input with /clear + expect(frameComplete).toContain("/clear"); + }); + + it("shows slash command selector again if typing continues past complete command", async () => { + const { lastFrame, stdin } = render(); + + // Type complete command /clear + stdin.write("/clear"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the dropdown for complete command + expect(frameComplete).not.toContain("Clear the chat history"); + + // Type more characters to make it not match any command + stdin.write("xyz"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameInvalid = lastFrame(); + + // Should show "No matching commands found" since /clearxyz doesn't match anything + expect(frameInvalid).toContain("No matching commands found"); + }); + + it("hides slash command selector when space is typed after complete command", async () => { + const { lastFrame, stdin } = render(); + + // Type complete command /help + stdin.write("/help"); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameComplete = lastFrame(); + + // Should NOT show the dropdown for complete command + expect(frameComplete).not.toContain("Show help message"); + + // Type a space after the complete command + stdin.write(" "); + + await new Promise((resolve) => setTimeout(resolve, 50)); + + const frameWithSpace = lastFrame(); + + // Should still NOT show the dropdown after space + expect(frameWithSpace).not.toContain("Show help message"); + expect(frameWithSpace).not.toContain( + "Use ↑/↓ to navigate, Enter to select, Tab to complete" + ); + + // But should show the input with /help + expect(frameWithSpace).toContain("/help "); + }); }); diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 03700dec5..4af1575b8 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; @@ -19,7 +19,7 @@ import { DisplayMessage } from "../types.js"; interface UseChatProps { assistant: AssistantUnrolled; - model: string; + model: ModelConfig; llmApi: BaseLlmApi; initialPrompt?: string; resume?: boolean; @@ -57,7 +57,10 @@ export function useChat({ if (history.length === 0) { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); + const systemMessage = constructSystemMessage( + rulesSystemMessage, + additionalRules + ); if (systemMessage) { history.push({ role: "system", content: systemMessage }); } @@ -83,6 +86,9 @@ export function useChat({ }); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); + const [responseStartTime, setResponseStartTime] = useState( + null + ); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); @@ -110,7 +116,12 @@ export function useChat({ } // Handle slash commands - const commandResult = await handleSlashCommands(message, assistant, onLoginPrompt, onReload); + const commandResult = await handleSlashCommands( + message, + assistant, + onLoginPrompt, + onReload + ); if (commandResult) { if (commandResult.exit) { exit(); @@ -185,8 +196,12 @@ export function useChat({ const controller = new AbortController(); setAbortController(controller); setIsWaitingForResponse(true); + setResponseStartTime(Date.now()); setInputMode(false); - logger.debug('Starting chat response stream', { messageLength: message.length, historyLength: newHistory.length }); + logger.debug("Starting chat response stream", { + messageLength: message.length, + historyLength: newHistory.length, + }); try { let currentStreamingMessage: DisplayMessage | null = null; @@ -312,12 +327,14 @@ export function useChat({ // Update the chat history with the complete conversation after streaming setChatHistory(finalHistory); - logger.debug('Chat history updated', { finalHistoryLength: finalHistory.length }); - + logger.debug("Chat history updated", { + finalHistoryLength: finalHistory.length, + }); + // Save the updated history to session - logger.debug('Saving session', { historyLength: finalHistory.length }); + logger.debug("Saving session", { historyLength: finalHistory.length }); saveSession(finalHistory); - logger.debug('Session saved'); + logger.debug("Session saved"); } catch (error: any) { const errorMessage = `Error: ${formatError(error)}`; setMessages((prev) => [ @@ -331,6 +348,7 @@ export function useChat({ } finally { setAbortController(null); setIsWaitingForResponse(false); + setResponseStartTime(null); setInputMode(true); } }; @@ -355,7 +373,10 @@ export function useChat({ const resetChatHistory = () => { const rulesSystemMessage = ""; - const systemMessage = constructSystemMessage(rulesSystemMessage, additionalRules); + const systemMessage = constructSystemMessage( + rulesSystemMessage, + additionalRules + ); const newHistory = systemMessage ? [{ role: "system" as const, content: systemMessage }] : []; @@ -369,6 +390,7 @@ export function useChat({ chatHistory, setChatHistory, isWaitingForResponse, + responseStartTime, inputMode, attachedFiles, handleUserMessage, @@ -376,4 +398,4 @@ export function useChat({ handleFileAttached, resetChatHistory, }; -} \ No newline at end of file +} diff --git a/src/ui/hooks/useConfigSelector.ts b/src/ui/hooks/useConfigSelector.ts index 592928e48..6e54837b8 100644 --- a/src/ui/hooks/useConfigSelector.ts +++ b/src/ui/hooks/useConfigSelector.ts @@ -1,13 +1,13 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { useState } from "react"; import { exec } from "child_process"; +import * as os from "os"; +import * as path from "path"; +import { useState } from "react"; import { loadAuthConfig, updateAssistantSlug } from "../../auth/workos.js"; import { initialize } from "../../config.js"; import { introMessage } from "../../intro.js"; import { MCPService } from "../../mcp.js"; -import * as path from "path"; -import * as os from "os"; interface ConfigOption { id: string; @@ -20,7 +20,7 @@ interface UseConfigSelectorProps { configPath?: string; onAssistantChange: ( assistant: AssistantUnrolled, - model: string, + model: ModelConfig, llmApi: BaseLlmApi, mcpService: MCPService ) => void; @@ -48,7 +48,7 @@ export function useConfigSelector({ if (config.type === "create") { // Open the web browser to create new assistant const url = "https://hub.continue.dev/new?type=assistant"; - + try { let command: string; if (process.platform === "darwin") { @@ -58,13 +58,13 @@ export function useConfigSelector({ } else { command = `xdg-open "${url}"`; } - + exec(command, (error) => { if (error) { console.error("Failed to open browser:", error); } }); - + onMessage({ role: "system", content: `Opening ${url} in your browser to create a new assistant...`, @@ -152,4 +152,4 @@ export function useConfigSelector({ handleConfigCancel, showConfigSelectorUI, }; -} \ No newline at end of file +} diff --git a/src/ui/hooks/useMessageRenderer.tsx b/src/ui/hooks/useMessageRenderer.tsx index 00d3d5623..66e8a06f8 100644 --- a/src/ui/hooks/useMessageRenderer.tsx +++ b/src/ui/hooks/useMessageRenderer.tsx @@ -58,7 +58,7 @@ export function useMessageRenderer() { return ( - ā— + ā— {isUser ? ( {message.content} diff --git a/src/ui/hooks/useOrganizationSelector.ts b/src/ui/hooks/useOrganizationSelector.ts index 06b50e27c..a767faa1f 100644 --- a/src/ui/hooks/useOrganizationSelector.ts +++ b/src/ui/hooks/useOrganizationSelector.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useState } from "react"; import { @@ -14,7 +14,7 @@ interface UseOrganizationSelectorProps { configPath?: string; onAssistantChange: ( assistant: AssistantUnrolled, - model: string, + model: ModelConfig, llmApi: BaseLlmApi, mcpService: MCPService ) => void; diff --git a/src/ui/index.ts b/src/ui/index.ts index ea540841f..f18a09a7f 100644 --- a/src/ui/index.ts +++ b/src/ui/index.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { render } from "ink"; import React from "react"; @@ -11,7 +11,7 @@ export { default as MarkdownRenderer } from "./MarkdownRenderer.js"; export async function startTUIChat( config: AssistantUnrolled, llmApi: BaseLlmApi, - model: string, + model: ModelConfig, mcpService: MCPService, initialPrompt?: string, resume?: boolean, @@ -42,4 +42,4 @@ export async function startTUIChat( }); return { unmount }; -} \ No newline at end of file +}