From b4978bf30ae33e931694525d760ee850765f0d48 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 13 Jul 2025 21:48:58 -0700 Subject: [PATCH 1/4] AGENTS.md support --- src/index.ts | 4 +++- src/systemMessage.ts | 30 ++++++++++++++++++++++++++++++ src/ui/TUIChat.tsx | 6 ++++-- 3 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 src/systemMessage.ts diff --git a/src/index.ts b/src/index.ts index f74dff493..f46fbd18f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ import { configureLogger } from "./logger.js"; import { MCPService } from "./mcp.js"; import { handleSlashCommands } from "./slashCommands.js"; import { streamChatResponse } from "./streamChatResponse.js"; +import { constructSystemMessage } from "./systemMessage.js"; import { startTUIChat } from "./ui/index.js"; // Parse command line arguments @@ -92,7 +93,8 @@ async function chat() { // Rules const chatHistory: ChatCompletionMessageParam[] = []; - const systemMessage = assistant.systemMessage; + const baseSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(baseSystemMessage); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } diff --git a/src/systemMessage.ts b/src/systemMessage.ts new file mode 100644 index 000000000..6fe1556f5 --- /dev/null +++ b/src/systemMessage.ts @@ -0,0 +1,30 @@ +import * as fs from "fs"; +import * as path from "path"; + +/** + * Load and append agent configuration content to the system message if it exists + * @param baseSystemMessage - The base system message from the assistant + * @returns The enhanced system message with agent configuration content if available + */ +export function constructSystemMessage(baseSystemMessage: string): string { + const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; + + try { + for (const fileName of agentFiles) { + const filePath = path.join(process.cwd(), fileName); + + if (fs.existsSync(filePath)) { + const fileContent = fs.readFileSync(filePath, "utf-8"); + + // Append file content to the base system message + const separator = baseSystemMessage ? "\n\n" : ""; + return `${baseSystemMessage}${separator}# Repository Context from ${fileName}\n\n${fileContent}`; + } + } + } catch (error) { + // If there's any error reading the file, just return the base system message + console.warn("Warning: Could not read agent configuration file:", error); + } + + return baseSystemMessage; +} diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 60d579dd2..fcc7fc04f 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -4,6 +4,7 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import React, { useEffect, useState } from "react"; import { handleSlashCommands } from "../slashCommands.js"; import { StreamCallbacks, streamChatResponse } from "../streamChatResponse.js"; +import { constructSystemMessage } from "../systemMessage.js"; import { getToolDisplayName } from "../tools.js"; import LoadingAnimation from "./LoadingAnimation.js"; import ToolResultSummary from "./ToolResultSummary.js"; @@ -32,7 +33,8 @@ const TUIChat: React.FC = ({ const [chatHistory, setChatHistory] = useState( () => { const history: ChatCompletionMessageParam[] = []; - const systemMessage = assistant.systemMessage; + const baseSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(baseSystemMessage); if (systemMessage) { history.push({ role: "system", content: systemMessage }); } @@ -317,4 +319,4 @@ const TUIChat: React.FC = ({ ); }; -export default TUIChat; \ No newline at end of file +export default TUIChat; From 25a67cf947f786d4cdc36c60e36e303a4e466c87 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 13 Jul 2025 22:16:21 -0700 Subject: [PATCH 2/4] feat: base system message --- src/index.ts | 4 +- src/systemMessage.ts | 114 ++++++++++++++++++++++++++++++++++++++----- src/ui/TUIChat.tsx | 4 +- 3 files changed, 107 insertions(+), 15 deletions(-) diff --git a/src/index.ts b/src/index.ts index f46fbd18f..61e4a40b4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -93,8 +93,8 @@ async function chat() { // Rules const chatHistory: ChatCompletionMessageParam[] = []; - const baseSystemMessage = assistant.systemMessage; - const systemMessage = constructSystemMessage(baseSystemMessage); + const rulesSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(rulesSystemMessage); if (systemMessage) { chatHistory.push({ role: "system", content: systemMessage }); } diff --git a/src/systemMessage.ts b/src/systemMessage.ts index 6fe1556f5..db3e66ea4 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -1,30 +1,122 @@ +import { execSync } from "child_process"; import * as fs from "fs"; import * as path from "path"; /** - * Load and append agent configuration content to the system message if it exists - * @param baseSystemMessage - The base system message from the assistant - * @returns The enhanced system message with agent configuration content if available + * Check if current directory is a git repository */ -export function constructSystemMessage(baseSystemMessage: string): string { +function isGitRepo(): boolean { + try { + execSync("git rev-parse --is-inside-work-tree", { stdio: "ignore" }); + return true; + } catch { + return false; + } +} + +/** + * Get basic directory structure + */ +function getDirectoryStructure(): string { + try { + const result = execSync( + 'find . -type f -name "*.ts" -o -name "*.js" -o -name "*.json" -o -name "*.md" | head -20', + { + encoding: "utf-8", + cwd: process.cwd(), + } + ); + return result.trim() || "No structure available"; + } catch { + return "Directory structure not available"; + } +} + +/** + * Get git status + */ +function getGitStatus(): string { + try { + if (!isGitRepo()) { + return "Not a git repository"; + } + const result = execSync("git status --porcelain", { + encoding: "utf-8", + cwd: process.cwd(), + }); + return result.trim() || "Working tree clean"; + } catch { + return "Git status not available"; + } +} + +const baseSystemMessage = `You are an agent in the Continue CLI. Given the user's prompt, you should use the tools available to you to answer the user's question. + +Notes: +1. IMPORTANT: You should be concise, direct, and to the point, since your responses will be displayed on a command line interface. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is .", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". +2. When relevant, share file names and code snippets relevant to the query +3. Any file paths you return in your final response MUST be absolute. DO NOT use relative paths. +Here is useful information about the environment you are running in: + +Working directory: ${process.cwd()} +Is directory a git repo: ${isGitRepo()} +Platform: ${process.platform} +Today's date: ${new Date().toISOString().split("T")[0]} + + +As you answer the user's questions, you can use the following context: + +Below is a snapshot of this project's file structure at the start of the conversation. This snapshot will NOT update during the conversation. It skips over .gitignore patterns. + +${getDirectoryStructure()} + +This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation. +${getGitStatus()} +`; + +/** + * Load and construct a comprehensive system message with base message and rules section + * @param rulesSystemMessage - The rules system message from the assistant + * @returns The comprehensive system message with base message and rules section + */ +export function constructSystemMessage(rulesSystemMessage: string): string { const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"]; + let agentContent = ""; + try { for (const fileName of agentFiles) { const filePath = path.join(process.cwd(), fileName); if (fs.existsSync(filePath)) { - const fileContent = fs.readFileSync(filePath, "utf-8"); - - // Append file content to the base system message - const separator = baseSystemMessage ? "\n\n" : ""; - return `${baseSystemMessage}${separator}# Repository Context from ${fileName}\n\n${fileContent}`; + agentContent = fs.readFileSync(filePath, "utf-8"); + break; // Use the first found agent file } } } catch (error) { - // If there's any error reading the file, just return the base system message + // If there's any error reading the file, continue without agent content console.warn("Warning: Could not read agent configuration file:", error); } - return baseSystemMessage; + // Construct the comprehensive system message + let systemMessage = baseSystemMessage; + + // Add rules section if we have either rules or agent content + if (rulesSystemMessage || agentContent) { + systemMessage += '\n\n'; + + if (rulesSystemMessage) { + systemMessage += `\n${rulesSystemMessage}`; + } + + if (agentContent) { + const separator = rulesSystemMessage ? "\n\n" : "\n"; + systemMessage += `${separator}${agentContent}`; + } + + systemMessage += "\n"; + } + + console.log("SYS: ", systemMessage); + return systemMessage; } diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index fcc7fc04f..f1ec8d6f0 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -33,8 +33,8 @@ const TUIChat: React.FC = ({ const [chatHistory, setChatHistory] = useState( () => { const history: ChatCompletionMessageParam[] = []; - const baseSystemMessage = assistant.systemMessage; - const systemMessage = constructSystemMessage(baseSystemMessage); + const rulesSystemMessage = assistant.systemMessage; + const systemMessage = constructSystemMessage(rulesSystemMessage); if (systemMessage) { history.push({ role: "system", content: systemMessage }); } From eb59dcc76a5bf16d4da2e4f2c7dc87765e8382b3 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 13 Jul 2025 22:29:32 -0700 Subject: [PATCH 3/4] fix: use ignore-walk for sys msg --- package-lock.json | 130 +++++++++++++++++++++++++++++++++++++------ package.json | 3 + src/systemMessage.ts | 34 ++++++++--- 3 files changed, 143 insertions(+), 24 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8cf183c14..3ea880e57 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@continuedev/cli", - "version": "0.0.17", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/cli", - "version": "0.0.17", + "version": "1.0.1", "license": "Apache-2.0", "dependencies": { "@continuedev/openai-adapters": "^1.0.18", @@ -18,7 +18,9 @@ "chalk": "^5.4.1", "diff": "^7.0.0", "dotenv": "^16.5.0", + "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "minimatch": "^10.0.3", "open": "^10.1.0", "react": "^19.1.0", "readline-sync": "^1.4.10", @@ -33,6 +35,7 @@ "@semantic-release/github": "^11.0.3", "@semantic-release/npm": "^12.0.2", "@types/diff": "^7.0.2", + "@types/ignore-walk": "^4.0.3", "@types/jest": "^29.5.14", "@types/readline-sync": "^1.4.8", "@types/uuid": "^9.0.8", @@ -1237,6 +1240,25 @@ "node": ">=18" } }, + "node_modules/@isaacs/balanced-match": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", + "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@isaacs/brace-expansion": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", + "integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", + "dependencies": { + "@isaacs/balanced-match": "^4.0.1" + }, + "engines": { + "node": "20 || >=22" + } + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -2744,6 +2766,15 @@ "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", "license": "MIT" }, + "node_modules/@types/ignore-walk": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/ignore-walk/-/ignore-walk-4.0.3.tgz", + "integrity": "sha512-6V7wDsk0nz8LtRC7qeC0GfXadFLT4FdCtVbXhxoIGRdkn2kLr20iMLupRGiBhlZ79WWWqaObIdR3nkXfUrBPdQ==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -3342,7 +3373,6 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, "license": "MIT" }, "node_modules/base64-js": { @@ -3400,11 +3430,10 @@ "license": "MIT" }, "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, - "license": "MIT", "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -3985,8 +4014,7 @@ "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" + "dev": true }, "node_modules/config-chain": { "version": "1.1.13", @@ -5630,6 +5658,18 @@ "node": ">= 6" } }, + "node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/globals": { "version": "11.12.0", "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", @@ -5930,6 +5970,39 @@ "node": ">= 4" } }, + "node_modules/ignore-walk": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/ignore-walk/-/ignore-walk-7.0.0.tgz", + "integrity": "sha512-T4gbf83A4NH95zvhVYZc+qWocBBGlpzUXLPGurJggw/WIOwicfXJChLDP/iBZnN5WqROSu5Bm3hhle4z8a8YGQ==", + "dependencies": { + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/ignore-walk/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/ignore-walk/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", @@ -6652,6 +6725,18 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/jake/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/java-properties": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/java-properties/-/java-properties-1.0.2.tgz", @@ -8202,16 +8287,17 @@ } }, "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz", + "integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==", "dependencies": { - "brace-expansion": "^1.1.7" + "@isaacs/brace-expansion": "^5.0.0" }, "engines": { - "node": "*" + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/minimist": { @@ -13188,6 +13274,18 @@ "node": ">=8" } }, + "node_modules/test-exclude/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", diff --git a/package.json b/package.json index b0091c855..9c30e85ef 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,9 @@ "chalk": "^5.4.1", "diff": "^7.0.0", "dotenv": "^16.5.0", + "ignore-walk": "^7.0.0", "ink": "^6.0.1", + "minimatch": "^10.0.3", "open": "^10.1.0", "react": "^19.1.0", "readline-sync": "^1.4.10", @@ -52,6 +54,7 @@ "@semantic-release/github": "^11.0.3", "@semantic-release/npm": "^12.0.2", "@types/diff": "^7.0.2", + "@types/ignore-walk": "^4.0.3", "@types/jest": "^29.5.14", "@types/readline-sync": "^1.4.8", "@types/uuid": "^9.0.8", diff --git a/src/systemMessage.ts b/src/systemMessage.ts index db3e66ea4..9e6f013f5 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -1,6 +1,9 @@ import { execSync } from "child_process"; import * as fs from "fs"; +import pkg from "ignore-walk"; +import { Minimatch } from "minimatch"; import * as path from "path"; +const { WalkerSync } = pkg; /** * Check if current directory is a git repository @@ -19,14 +22,29 @@ function isGitRepo(): boolean { */ function getDirectoryStructure(): string { try { - const result = execSync( - 'find . -type f -name "*.ts" -o -name "*.js" -o -name "*.json" -o -name "*.md" | head -20', - { - encoding: "utf-8", - cwd: process.cwd(), - } - ); - return result.trim() || "No structure available"; + const walker = new WalkerSync({ + path: process.cwd(), + includeEmpty: false, + follow: false, + ignoreFiles: [".gitignore", ".continueignore", ".customignore"], + }); + + (walker.ignoreRules as any)[".customignore"] = [ + new Minimatch(".git/*", { + matchBase: true, + dot: true, + flipNegate: true, + nocase: true, + }), + ]; + + const files = walker.start().result as string[]; + + const filteredFiles = files + .slice(0, 100) + .map((file: string) => `./${file}`); + + return filteredFiles.join("\n") || "No structure available"; } catch { return "Directory structure not available"; } From b822b938f110af2de2c040f45cd3fca770d9a4a7 Mon Sep 17 00:00:00 2001 From: Nate Date: Sun, 13 Jul 2025 23:04:07 -0700 Subject: [PATCH 4/4] fix: improve streaming message handling and API endpoint --- src/auth/workos.ts | 2 +- src/streamChatResponse.ts | 10 ++++++ src/systemMessage.ts | 3 +- src/ui/TUIChat.tsx | 70 +++++++++++++++++++++++---------------- 4 files changed, 53 insertions(+), 32 deletions(-) diff --git a/src/auth/workos.ts b/src/auth/workos.ts index 91b32733e..e99183f14 100644 --- a/src/auth/workos.ts +++ b/src/auth/workos.ts @@ -132,7 +132,7 @@ function getAuthUrlForTokenPage(useOnboarding: boolean = false): string { */ async function refreshToken(refreshToken: string): Promise { try { - const response = await axios.post(`${env.apiBase}auth/refresh`, { + const response = await axios.post(`${env.apiBase}/auth/refresh`, { refreshToken, }); diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 3ac1e5649..9526e0701 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -52,6 +52,7 @@ type TODO = any; export interface StreamCallbacks { onContent?: (content: string) => void; + onContentComplete?: (content: string) => void; onToolStart?: (toolName: string, toolArgs?: any) => void; onToolResult?: (result: string, toolName: string) => void; onToolError?: (error: string, toolName?: string) => void; @@ -187,6 +188,11 @@ export async function streamChatResponse( console.info(); // Add a newline after the response } + // 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( @@ -207,6 +213,10 @@ export async function streamChatResponse( } 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 diff --git a/src/systemMessage.ts b/src/systemMessage.ts index 9e6f013f5..ae13dda8a 100644 --- a/src/systemMessage.ts +++ b/src/systemMessage.ts @@ -135,6 +135,5 @@ export function constructSystemMessage(rulesSystemMessage: string): string { systemMessage += "\n"; } - console.log("SYS: ", systemMessage); return systemMessage; -} +} \ No newline at end of file diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index f1ec8d6f0..25db23d85 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -89,7 +89,8 @@ const TUIChat: React.FC = ({ role: "user", content: message, }; - setChatHistory((prev) => [...prev, newUserMessage]); + const newHistory = [...chatHistory, newUserMessage]; + setChatHistory(newHistory); setMessages((prev) => [...prev, { role: "user", content: message }]); // Start streaming response @@ -98,29 +99,45 @@ const TUIChat: React.FC = ({ setIsWaitingForResponse(true); setInputMode(false); - // Add placeholder for streaming message - setMessages((prev) => [ - ...prev, - { role: "assistant", content: "", isStreaming: true }, - ]); - try { - const newHistory = [...chatHistory, newUserMessage]; - let assistantResponse = ""; + let currentStreamingMessage: DisplayMessage | null = null; // Create callbacks to handle streaming updates const streamCallbacks: StreamCallbacks = { onContent: (content: string) => { - assistantResponse += content; setMessages((prev) => { const newMessages = [...prev]; - const lastMessage = newMessages[newMessages.length - 1]; - if (lastMessage.isStreaming) { - lastMessage.content += content; + + // Find or create current streaming message + if (!currentStreamingMessage) { + currentStreamingMessage = { role: "assistant", content: "", isStreaming: true }; + newMessages.push(currentStreamingMessage); } + + // Update the streaming message + const streamingIndex = newMessages.indexOf(currentStreamingMessage); + if (streamingIndex >= 0) { + newMessages[streamingIndex].content += content; + } + return newMessages; }); }, + onContentComplete: (content: string) => { + // Finalize the current streaming message + if (currentStreamingMessage) { + setMessages((prev) => { + const newMessages = [...prev]; + const streamingIndex = newMessages.indexOf(currentStreamingMessage!); + if (streamingIndex >= 0) { + newMessages[streamingIndex].isStreaming = false; + newMessages[streamingIndex].content = content; + } + return newMessages; + }); + currentStreamingMessage = null; + } + }, onToolStart: (toolName: string, toolArgs?: any) => { const formatToolCall = (name: string, args: any) => { const displayName = getToolDisplayName(name); @@ -182,22 +199,17 @@ const TUIChat: React.FC = ({ controller ); - // Finalize the assistant message - const finalAssistantMessage: ChatCompletionMessageParam = { - role: "assistant", - content: assistantResponse, - }; - setChatHistory((prev) => [...prev, finalAssistantMessage]); - - // Update messages to remove streaming flag - setMessages((prev) => { - const newMessages = [...prev]; - const lastMessage = newMessages[newMessages.length - 1]; - if (lastMessage.isStreaming) { - lastMessage.isStreaming = false; - } - return newMessages; - }); + // Finalize any remaining streaming message + if (currentStreamingMessage) { + setMessages((prev) => { + const newMessages = [...prev]; + const streamingIndex = newMessages.indexOf(currentStreamingMessage!); + if (streamingIndex >= 0) { + newMessages[streamingIndex].isStreaming = false; + } + return newMessages; + }); + } } catch (error: any) { const errorMessage = `Error: ${error.message}`; setMessages((prev) => [