From bb8bac27ae105256313e8e48decaa8c1155eb83c Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 19:58:22 -0700 Subject: [PATCH 01/18] onboarding polish --- .vscode/launch.json | 2 +- src/auth/workos.ts | 8 ++++---- src/commands/chat.ts | 11 +++++++++-- src/config.ts | 2 -- src/intro.ts | 3 --- src/onboarding.ts | 42 +++++++++++------------------------------- 6 files changed, 25 insertions(+), 43 deletions(-) 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/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/config.ts b/src/config.ts index 1553d9807..1b85541a7 100644 --- a/src/config.ts +++ b/src/config.ts @@ -182,9 +182,7 @@ export async function initialize( model: string; 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..253da2496 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -1,7 +1,6 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; -import { CONTINUE_ASCII_ART } from "./asciiArt.js"; import { MCPService } from "./mcp.js"; import { getAllTools } from "./streamChatResponse.js"; @@ -22,8 +21,6 @@ export function introMessage( const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - console.info(chalk.cyan(CONTINUE_ASCII_ART)); - console.info(`\n${chalk.bold.blue(`Agent: ${config.name}\n`)}`); console.info(`${chalk.yellow("Model:")} ${modelName.split("/").pop()}\n`); diff --git a/src/onboarding.ts b/src/onboarding.ts index 7bd54ad60..b8600e825 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -103,45 +103,25 @@ 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: Check if user has ~/.continue/config.yaml with acceptable model - if (await checkHasAcceptableModel(CONFIG_PATH)) { - console.log(chalk.blue(`āœ“ Using existing ${CONFIG_PATH}`)); - const result = await initialize(authConfig, CONFIG_PATH); + // 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.yellow("\nEnter choice (1): ")); + + if (choice === "1" || choice === "") { + const newAuthConfig = await login(); + + const result = await initialize(newAuthConfig, undefined); return { ...result, wasOnboarded: true }; - } - - // Step 3: Present user with two options - 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")); - - const choice = readlineSync.question( - chalk.green("\nSelect option (1 or 2): ") - ); - - if (choice === "1") { - console.log(chalk.cyan("\nšŸ” Logging in with Continue...")); - try { - 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; - } } 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: "), { From e00729073e932ba6eabea0cc9cce3241998a1c9c Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:10:40 -0700 Subject: [PATCH 02/18] update tools --- src/intro.ts | 6 +++--- src/tools/fetch.ts | 16 ++++++++-------- src/tools/index.ts | 14 +++++++++----- src/tools/runTerminalCommand.ts | 8 ++++---- 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/src/intro.ts b/src/intro.ts index 253da2496..76c33c68a 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -2,7 +2,7 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; import { MCPService } from "./mcp.js"; -import { getAllTools } from "./streamChatResponse.js"; +import { BUILTIN_TOOLS } from "./tools/index.js"; export function loadSystemMessage( assistant: AssistantConfig @@ -25,9 +25,9 @@ export function introMessage( console.info(`${chalk.yellow("Model:")} ${modelName.split("/").pop()}\n`); console.info(chalk.yellow("Tools:")); - getAllTools().forEach((tool) => { + BUILTIN_TOOLS.forEach((tool) => { console.info( - `- ${chalk.green(tool.function.name)}: ${tool.function.description ?? ""}` + `- ${chalk.green(tool.displayName)}: ${tool.description ?? ""}` ); }); console.info(""); 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 +}; From 6e4b4bb264b63c9dfaf3b316ff0885e0c0cf87c4 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:21:49 -0700 Subject: [PATCH 03/18] add guiderails to onboarding --- src/onboarding.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/onboarding.ts b/src/onboarding.ts index b8600e825..514c59e49 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -114,7 +114,10 @@ export async function runOnboardingFlow( console.log(chalk.white("1. ā© Log in with Continue")); console.log(chalk.white("2. šŸ”‘ Enter your Anthropic API key")); - const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): ")); + const choice = readlineSync.question(chalk.yellow("\nEnter choice (1): "), { + limit: ["1", "2", ""], + limitMessage: chalk.dim("Please enter 1 or 2"), + }); if (choice === "1" || choice === "") { const newAuthConfig = await login(); @@ -123,9 +126,12 @@ export async function runOnboardingFlow( return { ...result, wasOnboarded: true }; } else if (choice === "2") { const apiKey = readlineSync.question( - chalk.green("Enter your Anthropic API key: "), + chalk.white("\nEnter your Anthropic API key: "), { - hideEchoBack: true, + 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'" + ), } ); From ff1d11386282fa5760faa76f86edcc15852803ee Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:35:07 -0700 Subject: [PATCH 04/18] warnings on config load --- src/config.ts | 11 +++++++++-- src/onboarding.ts | 1 + 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/config.ts b/src/config.ts index 1b85541a7..000be0058 100644 --- a/src/config.ts +++ b/src/config.ts @@ -13,6 +13,7 @@ import { DefaultApi, DefaultApiInterface, } from "@continuedev/sdk/dist/api/dist/index.js"; +import chalk from "chalk"; import { dirname } from "node:path"; import { AuthConfig, @@ -97,9 +98,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; diff --git a/src/onboarding.ts b/src/onboarding.ts index 514c59e49..8ca687549 100644 --- a/src/onboarding.ts +++ b/src/onboarding.ts @@ -132,6 +132,7 @@ export async function runOnboardingFlow( limitMessage: chalk.dim( "Please enter a valid Anthropic key that starts with 'sk-ant'" ), + hideEchoBack: true, } ); From a937a121512aff1ba12135285aa235ae58e259fc Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:37:44 -0700 Subject: [PATCH 05/18] fewer colors --- src/intro.ts | 38 +++++++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/src/intro.ts b/src/intro.ts index 76c33c68a..41a8b3818 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -27,27 +27,43 @@ export function introMessage( console.info(chalk.yellow("Tools:")); BUILTIN_TOOLS.forEach((tool) => { console.info( - `- ${chalk.green(tool.displayName)}: ${tool.description ?? ""}` + `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.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.white("/exit")}: ${chalk.dim("Exit the chat")}`); console.info( - `- ${chalk.green("/whoami")}: Check who you're currently logged in as` + `- ${chalk.white("/clear")}: ${chalk.dim("Clear the chat history")}` + ); + console.info(`- ${chalk.white("/help")}: ${chalk.dim("Show help message")}`); + console.info( + `- ${chalk.white("/login")}: ${chalk.dim("Authenticate with your account")}` + ); + console.info( + `- ${chalk.white("/logout")}: ${chalk.dim( + "Sign out of your current session" + )}` + ); + console.info( + `- ${chalk.white("/whoami")}: ${chalk.dim( + "Check who you're currently logged in as" + )}` + ); + console.info(`- ${chalk.white("/org")}: ${chalk.dim("Switch organization")}`); + console.info( + `- ${chalk.white("/config")}: ${chalk.dim("Switch configuration")}` ); - 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}`); + console.info( + `- ${chalk.white("/" + prompt?.name)}: ${chalk.dim(prompt?.description)}` + ); } for (const prompt of mcpPrompts) { - console.info(`- /${prompt.name}: ${prompt.description}`); + console.info( + `- ${chalk.white("/" + prompt.name)}: ${chalk.dim(prompt.description)}` + ); } console.info(""); From 2a78edf88cac57d91f16dae7c3ab03a523629bf1 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:46:59 -0700 Subject: [PATCH 06/18] attempt different ascii art --- src/asciiArt.ts | 23 ++++++++++++++++------- src/intro.ts | 8 ++++---- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/asciiArt.ts b/src/asciiArt.ts index d83a7a20f..5d2b1a19e 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -1,9 +1,18 @@ -export const CONTINUE_ASCII_ART = ` - _________ _ _____________ ____ ______ - / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ -/ /__/ /_/ / / / / _/ // / /_/ / _/ -\\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ -`; +import chalk from "chalk"; + +const b = chalk.bold.white; +export const CONTINUE_ASCII_ART = chalk.dim(` + ${b("_____")}____ ${b("_ __")}___________ ____ ______ + ${b("/ ___/")} __ \\${b("/ |/ /")}_ __/ _/ |/ / / / / __/ +${b("/ /__")}/ /_/ ${b("/ /")} / / _/ // / /_/ / _/ +${b("\\___/")}\\____${b("/_/|_/")} /_/ /___/_/|_/\\____/___/ +`); +// export const CONTINUE_ASCII_ART = ` +// _________ _ _____________ ____ ______ +// / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ +// / /__/ /_/ / / / / _/ // / /_/ / _/ +// \\___/\\____/_/|_/ /_/ /___/_/|_/\\____/___/ +// `; export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ -31,7 +40,7 @@ export const CONTINUE_LOGO_ASCII_ART = ` @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ - @@@@@@@@@@@@ + CONTINUE @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@ @@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ diff --git a/src/intro.ts b/src/intro.ts index 41a8b3818..89bfbdbf5 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -21,10 +21,10 @@ export function introMessage( const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - 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:")} ${modelName.split("/").pop()}\n`); - console.info(chalk.yellow("Tools:")); + console.info(chalk.blue("Tools:")); BUILTIN_TOOLS.forEach((tool) => { console.info( `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.description ?? "")}` @@ -32,7 +32,7 @@ export function introMessage( }); console.info(""); - console.info(chalk.yellow("Slash commands:")); + console.info(chalk.blue("Slash commands:")); console.info(`- ${chalk.white("/exit")}: ${chalk.dim("Exit the chat")}`); console.info( `- ${chalk.white("/clear")}: ${chalk.dim("Clear the chat history")}` From db675f26367ad9b52f195980c97adc4b927f7cd9 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 20:56:52 -0700 Subject: [PATCH 07/18] rename to agent in a few places --- .continue/assistants/cli-assistant.yaml | 2 +- .../rules/continue-sdk-cli-and-hub-context.yaml | 4 ++-- .github/workflows/pr-description.yml.disabled | 2 +- README.md | 3 +-- src/asciiArt.ts | 16 +++++++++------- 5 files changed, 14 insertions(+), 13 deletions(-) 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/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 5d2b1a19e..305cf75c5 100644 --- a/src/asciiArt.ts +++ b/src/asciiArt.ts @@ -1,12 +1,14 @@ import chalk from "chalk"; -const b = chalk.bold.white; -export const CONTINUE_ASCII_ART = chalk.dim(` - ${b("_____")}____ ${b("_ __")}___________ ____ ______ - ${b("/ ___/")} __ \\${b("/ |/ /")}_ __/ _/ |/ / / / / __/ -${b("/ /__")}/ /_/ ${b("/ /")} / / _/ // / /_/ / _/ -${b("\\___/")}\\____${b("/_/|_/")} /_/ /___/_/|_/\\____/___/ -`); +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 = ` // _________ _ _____________ ____ ______ // / ___/ __ \\/ |/ /_ __/ _/ |/ / / / / __/ From 7eb1e007eb3a1b9f94f8451007590c4746de4684 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:14:28 -0700 Subject: [PATCH 08/18] refactor slash commands --- src/commands/commands.ts | 101 ++++++++++++++++++++++++++++++++++++++ src/intro.ts | 38 +++++--------- src/slashCommands.ts | 14 ++---- src/ui/SlashCommandUI.tsx | 56 ++------------------- 4 files changed, 121 insertions(+), 88 deletions(-) create mode 100644 src/commands/commands.ts diff --git a/src/commands/commands.ts b/src/commands/commands.ts new file mode 100644 index 000000000..458434493 --- /dev/null +++ b/src/commands/commands.ts @@ -0,0 +1,101 @@ +import { type AssistantConfig } from "@continuedev/sdk"; +import { hasMultipleOrganizations } from "../auth/workos.js"; + +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 async function getAllSlashCommands(assistant: AssistantConfig): Promise { + const hasMultipleOrgs = await hasMultipleOrganizations(); + + // Filter system commands based on requirements + const systemCommands = SYSTEM_SLASH_COMMANDS.filter(command => + !command.requiresMultipleOrgs || hasMultipleOrgs + ); + + // 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 system slash commands only + */ +export async function getSystemSlashCommands(): Promise { + const hasMultipleOrgs = await hasMultipleOrganizations(); + + return SYSTEM_SLASH_COMMANDS.filter(command => + !command.requiresMultipleOrgs || hasMultipleOrgs + ); +} + +/** + * 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, + })) || []; +} \ No newline at end of file diff --git a/src/intro.ts b/src/intro.ts index 89bfbdbf5..525a9327c 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -3,6 +3,7 @@ import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; import { MCPService } from "./mcp.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; +import { getAllSlashCommands } from "./commands/commands.js"; export function loadSystemMessage( assistant: AssistantConfig @@ -13,13 +14,16 @@ export function loadSystemMessage( .join("\n"); } -export function introMessage( +export async function introMessage( config: AssistantUnrolled, modelName: string, mcpService: MCPService ) { const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; + + // Get all slash commands from central definition + const allCommands = await getAllSlashCommands(config); console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); console.info(`${chalk.blue("Model:")} ${modelName.split("/").pop()}\n`); @@ -33,33 +37,15 @@ export function introMessage( console.info(""); console.info(chalk.blue("Slash commands:")); - console.info(`- ${chalk.white("/exit")}: ${chalk.dim("Exit the chat")}`); - console.info( - `- ${chalk.white("/clear")}: ${chalk.dim("Clear the chat history")}` - ); - console.info(`- ${chalk.white("/help")}: ${chalk.dim("Show help message")}`); - console.info( - `- ${chalk.white("/login")}: ${chalk.dim("Authenticate with your account")}` - ); - console.info( - `- ${chalk.white("/logout")}: ${chalk.dim( - "Sign out of your current session" - )}` - ); - console.info( - `- ${chalk.white("/whoami")}: ${chalk.dim( - "Check who you're currently logged in as" - )}` - ); - console.info(`- ${chalk.white("/org")}: ${chalk.dim("Switch organization")}`); - console.info( - `- ${chalk.white("/config")}: ${chalk.dim("Switch configuration")}` - ); - for (const prompt of config.prompts ?? []) { + + // Display all commands from central definition + for (const command of allCommands) { console.info( - `- ${chalk.white("/" + prompt?.name)}: ${chalk.dim(prompt?.description)}` + `- ${chalk.white("/" + command.name)}: ${chalk.dim(command.description)}` ); } + + // Display MCP prompts separately since they're not part of our central definition for (const prompt of mcpPrompts) { console.info( `- ${chalk.white("/" + prompt.name)}: ${chalk.dim(prompt.description)}` @@ -78,4 +64,4 @@ export function introMessage( }); } console.info(""); -} +} \ No newline at end of file diff --git a/src/slashCommands.ts b/src/slashCommands.ts index a978b513c..ae238a8ee 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 = await 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": diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index 089b28987..d9b518fc1 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,7 +1,7 @@ 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; @@ -10,63 +10,17 @@ interface SlashCommandUIProps { 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(); + getAllSlashCommands(assistant).then(setAllCommands); + }, [assistant]); // Filter commands based on the current filter const filteredCommands = allCommands @@ -113,4 +67,4 @@ const SlashCommandUI: React.FC = ({ ); }; -export default SlashCommandUI; +export default SlashCommandUI; \ No newline at end of file From ddd320172097d58aae874592391d598c618f8cca Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:14:35 -0700 Subject: [PATCH 09/18] always show org slash command --- src/commands/commands.ts | 58 ++++++++++++++++----------------------- src/intro.ts | 12 ++++---- src/slashCommands.ts | 8 +++--- src/ui/SlashCommandUI.tsx | 9 ++++-- 4 files changed, 40 insertions(+), 47 deletions(-) diff --git a/src/commands/commands.ts b/src/commands/commands.ts index 458434493..918bb631a 100644 --- a/src/commands/commands.ts +++ b/src/commands/commands.ts @@ -1,5 +1,4 @@ import { type AssistantConfig } from "@continuedev/sdk"; -import { hasMultipleOrganizations } from "../auth/workos.js"; export interface SlashCommand { name: string; @@ -20,13 +19,13 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ category: "system", }, { - name: "clear", + name: "clear", description: "Clear the chat history", category: "system", }, { name: "exit", - description: "Exit the chat", + description: "Exit the chat", category: "system", }, { @@ -35,7 +34,7 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ category: "system", }, { - name: "logout", + name: "logout", description: "Sign out of your current session", category: "system", }, @@ -60,42 +59,33 @@ export const SYSTEM_SLASH_COMMANDS: SystemCommand[] = [ /** * Get all available slash commands including system commands and assistant prompts */ -export async function getAllSlashCommands(assistant: AssistantConfig): Promise { - const hasMultipleOrgs = await hasMultipleOrganizations(); - +export function getAllSlashCommands( + assistant: AssistantConfig +): SlashCommand[] { // Filter system commands based on requirements - const systemCommands = SYSTEM_SLASH_COMMANDS.filter(command => - !command.requiresMultipleOrgs || hasMultipleOrgs - ); - + 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, - })) || []; + const assistantCommands: SlashCommand[] = + assistant.prompts?.map((prompt) => ({ + name: prompt?.name || "", + description: prompt?.description || "", + category: "assistant" as const, + })) || []; return [...systemCommands, ...assistantCommands]; } -/** - * Get system slash commands only - */ -export async function getSystemSlashCommands(): Promise { - const hasMultipleOrgs = await hasMultipleOrganizations(); - - return SYSTEM_SLASH_COMMANDS.filter(command => - !command.requiresMultipleOrgs || hasMultipleOrgs - ); -} - /** * 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, - })) || []; -} \ No newline at end of file +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/intro.ts b/src/intro.ts index 525a9327c..cc8c331fc 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -1,9 +1,9 @@ import { AssistantUnrolled } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; +import { getAllSlashCommands } from "./commands/commands.js"; import { MCPService } from "./mcp.js"; import { BUILTIN_TOOLS } from "./tools/index.js"; -import { getAllSlashCommands } from "./commands/commands.js"; export function loadSystemMessage( assistant: AssistantConfig @@ -21,9 +21,9 @@ export async function introMessage( ) { const mcpTools = mcpService.getTools() ?? []; const mcpPrompts = mcpService.getPrompts() ?? []; - + // Get all slash commands from central definition - const allCommands = await getAllSlashCommands(config); + const allCommands = getAllSlashCommands(config); console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); console.info(`${chalk.blue("Model:")} ${modelName.split("/").pop()}\n`); @@ -37,14 +37,14 @@ export async function introMessage( console.info(""); console.info(chalk.blue("Slash commands:")); - + // Display all commands from central definition for (const command of allCommands) { console.info( `- ${chalk.white("/" + command.name)}: ${chalk.dim(command.description)}` ); } - + // Display MCP prompts separately since they're not part of our central definition for (const prompt of mcpPrompts) { console.info( @@ -64,4 +64,4 @@ export async function introMessage( }); } console.info(""); -} \ No newline at end of file +} diff --git a/src/slashCommands.ts b/src/slashCommands.ts index ae238a8ee..40fb81541 100644 --- a/src/slashCommands.ts +++ b/src/slashCommands.ts @@ -26,10 +26,10 @@ export async function handleSlashCommands( const [command, ...args] = input.slice(1).split(" "); switch (command) { case "help": - const allCommands = await getAllSlashCommands(assistant); + const allCommands = getAllSlashCommands(assistant); const helpMessage = [ "Available commands:", - ...allCommands.map(cmd => `/${cmd.name} - ${cmd.description}`) + ...allCommands.map((cmd) => `/${cmd.name} - ${cmd.description}`), ].join("\n"); return { output: helpMessage }; case "clear": @@ -50,7 +50,7 @@ export async function handleSlashCommands( } else { console.info(chalk.green(`\nLogged in successfully`)); } - + // Reload everything after successful login if (onReload) { await onReload(); @@ -104,4 +104,4 @@ export async function handleSlashCommands( } } return null; -} \ No newline at end of file +} diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index d9b518fc1..c940c9133 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -1,7 +1,10 @@ import { type AssistantConfig } from "@continuedev/sdk"; import { Box, Text } from "ink"; import React, { useEffect, useState } from "react"; -import { getAllSlashCommands, type SlashCommand } from "../commands/commands.js"; +import { + getAllSlashCommands, + type SlashCommand, +} from "../commands/commands.js"; interface SlashCommandUIProps { assistant: AssistantConfig; @@ -19,7 +22,7 @@ const SlashCommandUI: React.FC = ({ const [allCommands, setAllCommands] = useState([]); useEffect(() => { - getAllSlashCommands(assistant).then(setAllCommands); + setAllCommands(getAllSlashCommands(assistant)); }, [assistant]); // Filter commands based on the current filter @@ -67,4 +70,4 @@ const SlashCommandUI: React.FC = ({ ); }; -export default SlashCommandUI; \ No newline at end of file +export default SlashCommandUI; From 67bf34b3344044793fb9d2806fa3c6f228c2bb24 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:17:53 -0700 Subject: [PATCH 10/18] dead code --- src/ui/SlashCommandUI.tsx | 2 -- src/ui/UserInput.tsx | 10 ++++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ui/SlashCommandUI.tsx b/src/ui/SlashCommandUI.tsx index c940c9133..a62ccd8c3 100644 --- a/src/ui/SlashCommandUI.tsx +++ b/src/ui/SlashCommandUI.tsx @@ -10,14 +10,12 @@ interface SlashCommandUIProps { assistant: AssistantConfig; filter: string; selectedIndex: number; - onSelect: (command: string) => void; } const SlashCommandUI: React.FC = ({ assistant, filter, selectedIndex, - onSelect, }) => { const [allCommands, setAllCommands] = useState([]); diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index ae965edaa..8f6b39622 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -91,12 +91,15 @@ 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 setShowSlashCommands(true); @@ -488,7 +491,6 @@ const UserInput: React.FC = ({ assistant={assistant} filter={slashCommandFilter} selectedIndex={selectedCommandIndex} - onSelect={selectSlashCommand} /> )} From 458c5d54766f45b2521796facf14011a0e5ed1fa Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:22:15 -0700 Subject: [PATCH 11/18] magenta loader --- src/ui/LoadingAnimation.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 = From c9919d90eb6448658cd1c5b3d7dd7290ca36c0b2 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:34:52 -0700 Subject: [PATCH 12/18] don't print tools --- src/intro.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/intro.ts b/src/intro.ts index cc8c331fc..87933761d 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -3,7 +3,6 @@ import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; import { getAllSlashCommands } from "./commands/commands.js"; import { MCPService } from "./mcp.js"; -import { BUILTIN_TOOLS } from "./tools/index.js"; export function loadSystemMessage( assistant: AssistantConfig @@ -28,13 +27,13 @@ export async function introMessage( console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); console.info(`${chalk.blue("Model:")} ${modelName.split("/").pop()}\n`); - 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("Tools:")); + // BUILTIN_TOOLS.forEach((tool) => { + // console.info( + // `- ${chalk.white(tool.displayName)}: ${chalk.dim(tool.description ?? "")}` + // ); + // }); + // console.info(""); console.info(chalk.blue("Slash commands:")); From 0a4acdacb3087ae33a78b4c312acacc397e20a74 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:40:20 -0700 Subject: [PATCH 13/18] lots of debug logs --- src/streamChatResponse.ts | 104 ++++++++++++++++++++++++---- src/ui/hooks/useMessageRenderer.tsx | 2 +- 2 files changed, 93 insertions(+), 13 deletions(-) diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index fb097076b..ab5ac11ef 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -10,19 +10,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: { @@ -77,20 +80,38 @@ export async function streamChatResponse( 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(); + logger.debug("Tools prepared", { + toolCount: toolsForRequest.length, + toolNames: toolsForRequest.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 }); + logger.debug("Starting new conversation iteration", { + iterationNumber: + chatHistory.filter((m) => m.role === "assistant").length + 1, + hasToolCalls: currentToolCalls.length > 0, + previousToolCount: currentToolCalls.length, + }); // Factory function to create the stream generator const streamFactory = async () => { - logger.debug('Creating chat completion stream', { model, messageCount: chatHistory.length, toolCount: toolsForRequest.length }); + logger.debug("Creating chat completion stream", { + model, + messageCount: chatHistory.length, + toolCount: toolsForRequest.length, + }); return await chatCompletionStreamWithBackoff( llmApi, { @@ -107,6 +128,7 @@ export async function streamChatResponse( currentToolCalls = []; let currentToolCallId = ""; let toolArguments = ""; + logger.debug("Initialized iteration variables"); try { // Use the exponential backoff wrapper for the entire stream @@ -115,10 +137,19 @@ export async function streamChatResponse( abortController.signal ); + let chunkCount = 0; for await (const chunk of streamWithBackoff) { - logger.debug('Received stream chunk', { hasContent: !!chunk.choices[0].delta.content, hasToolCalls: !!chunk.choices[0].delta.tool_calls }); + chunkCount++; + logger.debug("Received stream chunk", { + chunkNumber: chunkCount, + hasContent: !!chunk.choices[0].delta.content, + contentLength: chunk.choices[0].delta.content?.length || 0, + hasToolCalls: !!chunk.choices[0].delta.tool_calls, + toolCallCount: chunk.choices[0].delta.tool_calls?.length || 0, + }); // Check if we should abort if (abortController?.signal.aborted) { + logger.debug("Stream aborted"); break; } @@ -140,6 +171,10 @@ export async function streamChatResponse( // Initialize a new tool call if we get an index and id if (toolCallDelta.index !== undefined && toolCallDelta.id) { if (!currentToolCalls[toolCallDelta.index]) { + logger.debug("Initializing new tool call", { + index: toolCallDelta.index, + id: toolCallDelta.id, + }); currentToolCalls[toolCallDelta.index] = { id: toolCallDelta.id, name: "", @@ -157,6 +192,10 @@ export async function streamChatResponse( ); if (toolCall) { if (!toolCall.name) { + logger.debug("Setting tool name", { + toolId: currentToolCallId, + name: toolCallDelta.function.name, + }); toolCall.name = toolCallDelta.function.name; toolCall.startNotified = false; } @@ -176,6 +215,10 @@ export async function streamChatResponse( // Try to parse complete JSON const parsed = JSON.parse(toolArguments); toolCall.arguments = parsed; + logger.debug("Successfully parsed tool arguments", { + toolName: toolCall.name, + argumentKeys: Object.keys(parsed), + }); // Notify start if we haven't already and have both name and args if (toolCall.name && !toolCall.startNotified) { @@ -192,23 +235,29 @@ export async function streamChatResponse( } } catch (e) { // Not complete JSON yet, continue collecting + logger.debug("Tool arguments not yet complete JSON", { + arguments: toolArguments, + }); } } } } } } + logger.debug("Stream iteration complete", { + totalChunks: chunkCount, + responseLength: aiResponse.length, + toolCallsCollected: currentToolCalls.length, + }); } catch (error: any) { // Handle AbortError gracefully - this is expected when user cancels - if (error.name === 'AbortError' || abortController?.signal.aborted) { + if (error.name === "AbortError" || abortController?.signal.aborted) { + logger.debug("Stream aborted by user"); // Stream was aborted, this is expected behavior return fullResponse; } // For other errors, re-throw them - logger.error( - chalk.red("Error in streamChatResponse:"), - error - ); + logger.error(chalk.red("Error in streamChatResponse:"), error); throw error; } @@ -227,6 +276,11 @@ export async function streamChatResponse( // Add the assistant's response to chat history if there's content or tool calls if (currentToolCalls.length > 0) { + logger.debug("Adding assistant response with tool calls", { + toolCount: currentToolCalls.length, + toolNames: currentToolCalls.map((tc) => tc.name), + hasContent: !!aiResponse.trim(), + }); const toolCalls: ChatCompletionMessageToolCall[] = currentToolCalls.map( (tc) => ({ id: tc.id, @@ -244,22 +298,38 @@ export async function streamChatResponse( }); } else if (aiResponse.trim()) { // Only add assistant response if there's actual content + logger.debug("Adding assistant response without tool calls", { + contentLength: aiResponse.length, + }); chatHistory.push({ role: "assistant", content: aiResponse }); // Also notify content complete for standalone messages if (callbacks?.onContentComplete) { callbacks.onContentComplete(aiResponse); } + } else { + logger.debug("No content or tool calls to add to history"); } // If we have tool calls, execute them if (currentToolCalls.length > 0) { + logger.debug("Executing tool calls", { + count: currentToolCalls.length, + }); for (const toolCall of currentToolCalls) { try { + logger.debug("Executing tool", { + name: toolCall.name, + arguments: toolCall.arguments, + }); // Execute the tool const toolResult = await executeToolCall({ name: toolCall.name, arguments: toolCall.arguments, }); + logger.debug("Tool execution complete", { + name: toolCall.name, + resultLength: toolResult.length, + }); // Add tool result to chat history chatHistory.push({ @@ -277,6 +347,10 @@ export async function streamChatResponse( const errorMessage = `Error executing tool ${toolCall.name}: ${ error instanceof Error ? error.message : String(error) }`; + logger.debug("Tool execution failed", { + name: toolCall.name, + error: errorMessage, + }); chatHistory.push({ role: "tool", tool_call_id: toolCall.id, @@ -296,11 +370,17 @@ export async function streamChatResponse( // Continue the conversation with the tool results shouldContinueConversation = true; + logger.debug("Continuing conversation after tool execution"); } else { // No more tool calls, end the conversation shouldContinueConversation = false; + logger.debug("Ending conversation - no more tool calls"); } } + logger.debug("streamChatResponse complete", { + totalResponseLength: fullResponse.length, + totalMessages: chatHistory.length, + }); return fullResponse; -} \ 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} From 443c08bb83fca5339e007901cb8feb9f7f23f280 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 21:47:56 -0700 Subject: [PATCH 14/18] timer --- src/ui/TUIChat.tsx | 10 +++++++--- src/ui/Timer.tsx | 25 +++++++++++++++++++++++++ src/ui/hooks/useChat.ts | 4 ++++ 3 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 src/ui/Timer.tsx diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index ea84a3734..c82f63c97 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -13,6 +13,7 @@ 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 { @@ -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..33f540cea --- /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); + }, 100); // Update every 100ms for smooth display + + return () => clearInterval(interval); + }, [startTime]); + + return {elapsed}s; +}; + +export default Timer; \ No newline at end of file diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 03700dec5..9909a6fd1 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -83,6 +83,7 @@ export function useChat({ }); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); + const [responseStartTime, setResponseStartTime] = useState(null); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); @@ -185,6 +186,7 @@ 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 }); @@ -331,6 +333,7 @@ export function useChat({ } finally { setAbortController(null); setIsWaitingForResponse(false); + setResponseStartTime(null); setInputMode(true); } }; @@ -369,6 +372,7 @@ export function useChat({ chatHistory, setChatHistory, isWaitingForResponse, + responseStartTime, inputMode, attachedFiles, handleUserMessage, From db7c99cc2e058fc310b752fee2f6d22a77770867 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 22:24:56 -0700 Subject: [PATCH 15/18] refactor streamChatResponse --- src/streamChatResponse.ts | 433 ++++++++++++++++++-------------------- src/ui/TUIChat.tsx | 2 +- 2 files changed, 211 insertions(+), 224 deletions(-) diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index ab5ac11ef..4ba405d5b 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -62,8 +62,6 @@ export function getAllTools() { return allTools; } -type TODO = any; - export interface StreamCallbacks { onContent?: (content: string) => void; onContentComplete?: (content: string) => void; @@ -72,7 +70,168 @@ 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; +} + +// Process a single streaming response and return whether we need to continue +async function processStreamingResponse( + chatHistory: ChatCompletionMessageParam[], + model: string, + 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, + messages: chatHistory, + stream: true, + tools, + }, + 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, @@ -85,253 +244,76 @@ export async function streamChatResponse( 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: toolsForRequest.length, - toolNames: toolsForRequest.map((t) => t.function.name), + 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", { - iterationNumber: - chatHistory.filter((m) => m.role === "assistant").length + 1, - hasToolCalls: currentToolCalls.length > 0, - previousToolCount: currentToolCalls.length, - }); - // Factory function to create the stream generator - const streamFactory = async () => { - logger.debug("Creating chat completion stream", { + while (true) { + logger.debug("Starting conversation iteration"); + + // Get response from LLM + const { content, toolCalls, shouldContinue } = + await processStreamingResponse( + chatHistory, model, - messageCount: chatHistory.length, - toolCount: toolsForRequest.length, - }); - return await chatCompletionStreamWithBackoff( llmApi, - { - model, - messages: chatHistory, - stream: true, - tools: toolsForRequest, - }, - abortController.signal - ); - }; - - let aiResponse = ""; - currentToolCalls = []; - let currentToolCallId = ""; - let toolArguments = ""; - logger.debug("Initialized iteration variables"); - - try { - // Use the exponential backoff wrapper for the entire stream - const streamWithBackoff = withExponentialBackoff( - streamFactory, - abortController.signal + abortController, + callbacks, + isHeadless, + tools ); - let chunkCount = 0; - for await (const chunk of streamWithBackoff) { - chunkCount++; - logger.debug("Received stream chunk", { - chunkNumber: chunkCount, - hasContent: !!chunk.choices[0].delta.content, - contentLength: chunk.choices[0].delta.content?.length || 0, - hasToolCalls: !!chunk.choices[0].delta.tool_calls, - toolCallCount: chunk.choices[0].delta.tool_calls?.length || 0, - }); - // Check if we should abort - if (abortController?.signal.aborted) { - logger.debug("Stream 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]) { - logger.debug("Initializing new tool call", { - index: toolCallDelta.index, - id: toolCallDelta.id, - }); - 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) { - logger.debug("Setting tool name", { - toolId: currentToolCallId, - name: toolCallDelta.function.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; - logger.debug("Successfully parsed tool arguments", { - toolName: toolCall.name, - argumentKeys: Object.keys(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 - logger.debug("Tool arguments not yet complete JSON", { - arguments: toolArguments, - }); - } - } - } - } - } - } - logger.debug("Stream iteration complete", { - totalChunks: chunkCount, - responseLength: aiResponse.length, - toolCallsCollected: currentToolCalls.length, - }); - } catch (error: any) { - // Handle AbortError gracefully - this is expected when user cancels - if (error.name === "AbortError" || abortController?.signal.aborted) { - logger.debug("Stream aborted by user"); - // 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) { - logger.debug("Adding assistant response with tool calls", { - toolCount: currentToolCalls.length, - toolNames: currentToolCalls.map((tc) => tc.name), - hasContent: !!aiResponse.trim(), - }); - 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 - logger.debug("Adding assistant response without tool calls", { - contentLength: aiResponse.length, - }); - chatHistory.push({ role: "assistant", content: aiResponse }); - // Also notify content complete for standalone messages - if (callbacks?.onContentComplete) { - callbacks.onContentComplete(aiResponse); - } - } else { - logger.debug("No content or tool calls to add to history"); - } - // If we have tool calls, execute them - if (currentToolCalls.length > 0) { - logger.debug("Executing tool calls", { - count: currentToolCalls.length, - }); - for (const toolCall of currentToolCalls) { + // Execute tool calls + for (const toolCall of toolCalls) { try { logger.debug("Executing tool", { name: toolCall.name, arguments: toolCall.arguments, }); - // Execute the tool + const toolResult = await executeToolCall({ name: toolCall.name, arguments: toolCall.arguments, }); - logger.debug("Tool execution complete", { - name: toolCall.name, - resultLength: toolResult.length, - }); - // Add tool result to chat history chatHistory.push({ role: "tool", tool_call_id: toolCall.id, @@ -347,34 +329,38 @@ export async function streamChatResponse( const errorMessage = `Error executing tool ${toolCall.name}: ${ error instanceof Error ? error.message : String(error) }`; - logger.debug("Tool execution failed", { + + 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; - logger.debug("Continuing conversation after tool execution"); - } else { - // No more tool calls, end the conversation - shouldContinueConversation = false; - logger.debug("Ending conversation - no more tool calls"); + // Check if we should continue + if (!shouldContinue) { + logger.debug("Conversation complete - no more tool calls"); + break; } } @@ -382,5 +368,6 @@ export async function streamChatResponse( totalResponseLength: fullResponse.length, totalMessages: chatHistory.length, }); + return fullResponse; } diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index c82f63c97..30002dac5 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -175,7 +175,7 @@ const TUIChat: React.FC = ({ ( - • esc to interrupt ) + • esc to interrupt ) )} From 889d19e44881832e66974ba81aa4ba14d6e25a26 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 22:45:09 -0700 Subject: [PATCH 16/18] fix: pass defaultCompletionOptions --- src/config.ts | 7 +++-- src/intro.ts | 6 ++-- src/onboarding.ts | 4 +-- src/streamChatResponse.ts | 22 +++++++++++-- src/ui/TUIChat.tsx | 4 +-- src/ui/hooks/useChat.ts | 42 ++++++++++++++++++------- src/ui/hooks/useConfigSelector.ts | 18 +++++------ src/ui/hooks/useOrganizationSelector.ts | 4 +-- src/ui/index.ts | 6 ++-- 9 files changed, 74 insertions(+), 39 deletions(-) diff --git a/src/config.ts b/src/config.ts index 000be0058..564902a74 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,5 +1,6 @@ import { AssistantUnrolled, + ModelConfig, RegistryClient, unrollAssistant, } from "@continuedev/config-yaml"; @@ -28,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") ); @@ -72,7 +73,7 @@ export function getLlmApi( ); } - return [llmApi, model.model]; + return [llmApi, model]; } async function loadConfigYaml( @@ -186,7 +187,7 @@ export async function initialize( ): Promise<{ config: AssistantUnrolled; llmApi: BaseLlmApi; - model: string; + model: ModelConfig; mcpService: MCPService; }> { const organizationId = getOrganizationId(authConfig); diff --git a/src/intro.ts b/src/intro.ts index 87933761d..fa55d43ff 100644 --- a/src/intro.ts +++ b/src/intro.ts @@ -1,4 +1,4 @@ -import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { type AssistantConfig } from "@continuedev/sdk"; import chalk from "chalk"; import { getAllSlashCommands } from "./commands/commands.js"; @@ -15,7 +15,7 @@ export function loadSystemMessage( export async function introMessage( config: AssistantUnrolled, - modelName: string, + model: ModelConfig, mcpService: MCPService ) { const mcpTools = mcpService.getTools() ?? []; @@ -25,7 +25,7 @@ export async function introMessage( const allCommands = getAllSlashCommands(config); console.info(`\n${chalk.bold.yellow(`Agent: ${config.name}\n`)}`); - console.info(`${chalk.blue("Model:")} ${modelName.split("/").pop()}\n`); + console.info(`${chalk.blue("Model:")} ${model.name.split("/").pop()}\n`); // console.info(chalk.blue("Tools:")); // BUILTIN_TOOLS.forEach((tool) => { diff --git a/src/onboarding.ts b/src/onboarding.ts index 8ca687549..cf6667a3e 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; } diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 4ba405d5b..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, @@ -78,10 +80,23 @@ interface ToolCall { 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: string, + model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, callbacks?: StreamCallbacks, @@ -101,10 +116,11 @@ async function processStreamingResponse( return await chatCompletionStreamWithBackoff( llmApi, { - model, + model: model.model, messages: chatHistory, stream: true, tools, + ...getDefaultCompletionOptions(model.defaultCompletionOptions), }, abortController.signal ); @@ -234,7 +250,7 @@ async function processStreamingResponse( // Main function that handles the conversation loop export async function streamChatResponse( chatHistory: ChatCompletionMessageParam[], - model: string, + model: ModelConfig, llmApi: BaseLlmApi, abortController: AbortController, callbacks?: StreamCallbacks diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 30002dac5..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"; @@ -18,7 +18,7 @@ import UserInput from "./UserInput.js"; interface TUIChatProps { config: AssistantUnrolled; - model: string; + model: ModelConfig; llmApi: BaseLlmApi; mcpService: MCPService; configPath?: string; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 9909a6fd1..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,7 +86,9 @@ export function useChat({ }); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); - const [responseStartTime, setResponseStartTime] = useState(null); + const [responseStartTime, setResponseStartTime] = useState( + null + ); const [inputMode, setInputMode] = useState(true); const [abortController, setAbortController] = useState(null); @@ -111,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(); @@ -188,7 +198,10 @@ export function useChat({ 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; @@ -314,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) => [ @@ -358,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 }] : []; @@ -380,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/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 +} From 387427273cb719320e2b8b3140e83ecbfb6f98d5 Mon Sep 17 00:00:00 2001 From: Nate Date: Sat, 19 Jul 2025 22:53:21 -0700 Subject: [PATCH 17/18] fix slash commands bug + test --- src/ui/UserInput.tsx | 18 +++- .../__tests__/TUIChat.slashCommands.test.tsx | 87 ++++++++++++++++++- 2 files changed, 102 insertions(+), 3 deletions(-) diff --git a/src/ui/UserInput.tsx b/src/ui/UserInput.tsx index 8f6b39622..7204ce830 100644 --- a/src/ui/UserInput.tsx +++ b/src/ui/UserInput.tsx @@ -101,7 +101,21 @@ const UserInput: React.FC = ({ 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); @@ -507,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 "); + }); }); From 85ba9fd49e1764bfcfb1eae22a7bbab964281e64 Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Sat, 19 Jul 2025 22:55:25 -0700 Subject: [PATCH 18/18] Update src/ui/Timer.tsx Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- src/ui/Timer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ui/Timer.tsx b/src/ui/Timer.tsx index 33f540cea..32fc2e090 100644 --- a/src/ui/Timer.tsx +++ b/src/ui/Timer.tsx @@ -14,7 +14,7 @@ const Timer: React.FC = ({ startTime, color = "gray" }) => { const now = Date.now(); const elapsedSeconds = Math.floor((now - startTime) / 1000); setElapsed(elapsedSeconds); - }, 100); // Update every 100ms for smooth display + }, 1000); // Update every 1000ms for efficient display return () => clearInterval(interval); }, [startTime]);