From 8699786d5a630ddedd02752171b9d750cd6e4c0d Mon Sep 17 00:00:00 2001 From: Gaurav Bhambhani <113461154+GauravVBhambhani@users.noreply.github.com> Date: Thu, 20 Mar 2025 16:15:43 -0400 Subject: [PATCH 01/54] Decorate all active edit ranges If a user selects multiple chunks of code with cmd-I, only the most recent chunk of code is decorated as a selection. This commit addresses that problem by changing setDecorations to addDecorations, and carefully tracking which ranges are currently active in the EditDecorationManager. Additionally, overlapping or adjacent ranges are now merged seamlessly to prevent redundant highlights. --- extensions/vscode/src/commands.ts | 2 +- .../src/quickEdit/EditDecorationManager.ts | 46 +++++++++++++++++-- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index de8f5cd1e..04239ecbf 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -569,7 +569,7 @@ const getCommandsMap: ( const range = args?.range ?? new vscode.Range(startFromCharZero, endAtCharLast); - editDecorationManager.setDecoration(editor, range); + editDecorationManager.addDecorations(editor, [range]); const rangeInFileWithContents = getRangeInFileWithContents(true, range); diff --git a/extensions/vscode/src/quickEdit/EditDecorationManager.ts b/extensions/vscode/src/quickEdit/EditDecorationManager.ts index 544287483..18991ac49 100644 --- a/extensions/vscode/src/quickEdit/EditDecorationManager.ts +++ b/extensions/vscode/src/quickEdit/EditDecorationManager.ts @@ -2,6 +2,7 @@ import vscode from "vscode"; class EditDecorationManager { private _lastEditor: vscode.TextEditor | undefined; private decorationType: vscode.TextEditorDecorationType; + private activeRangesMap: Map = new Map(); // Store unique active ranges constructor(context: vscode.ExtensionContext) { this.decorationType = vscode.window.createTextEditorDecorationType({ @@ -23,18 +24,55 @@ class EditDecorationManager { ); } - setDecoration(editor: vscode.TextEditor, range: vscode.Range) { - if (this._lastEditor) { - this._lastEditor.setDecorations(this.decorationType, []); + // Converts each range to a unique string for storing in the map + private rangeToString(range: vscode.Range): string { + return `(${range.start.line},${range.start.character})-(${range.end.line},${range.end.character})`; + } + + // Checks if two ranges are adjacent or overlapping + private rangesCoincide(range1: vscode.Range, range2: vscode.Range): boolean { + return range1.start.isEqual(range2.start) + || range1.end.isEqual(range2.start) + || range2.end.isEqual(range1.start) + || !!range1.intersection(range2); + } + + // Merges new range with existing ranges in the map + private mergeNewRange(newRange: vscode.Range): void { + let mergedRange = newRange; + const rangesToPrune: string[] = []; + + for (const [key, existingRange] of this.activeRangesMap.entries()) { + if (!this.rangesCoincide(mergedRange, existingRange)) continue; + mergedRange = mergedRange.union(existingRange); + rangesToPrune.push(key); + } + + for (const key of rangesToPrune) this.activeRangesMap.delete(key); + this.activeRangesMap.set(this.rangeToString(mergedRange), mergedRange); + } + + // Adds a new decoration to the editor and merges it with existing ranges + addDecorations(editor: vscode.TextEditor, ranges: vscode.Range[]): void { + if (this._lastEditor?.document !== editor.document) { + this.clear(); // Clear previous decorations if editor has changed } - editor.setDecorations(this.decorationType, [range]); this._lastEditor = editor; + + for (const range of ranges) this.mergeNewRange(range); + + const activeRanges = Array.from(this.activeRangesMap.values()); + if (activeRanges.length === 0) return; // No ranges to highlight + + // Update active ranges and apply decorations + editor.setDecorations(this.decorationType, activeRanges); this.updateInEditMode(true); } clear() { if (this._lastEditor) { this._lastEditor.setDecorations(this.decorationType, []); + this.activeRangesMap.clear(); this._lastEditor = undefined; this.updateInEditMode(false); } From 0c829fd99d0e898c1afdc90a0957c907dcb7f4e2 Mon Sep 17 00:00:00 2001 From: liuk Date: Sat, 22 Mar 2025 02:29:55 +0800 Subject: [PATCH 02/54] feat: Improve ProtocolClient initialization and GUI loading - Introduce `onProtocolClientInitialized` to handle client initialization events. - Use `Delegates.observable` for `ideProtocolClient` to trigger listeners on changes. - Ensure URL loading is deferred until protocol client is initialized. --- .../services/ContinuePluginService.kt | 26 +++++++++++++++++-- .../toolWindow/ContinueBrowser.kt | 20 +++++++------- 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index cf1005596..6ebb8f41f 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -1,6 +1,5 @@ package com.github.continuedev.continueintellijextension.services -import IntelliJIDE import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager import com.github.continuedev.continueintellijextension.`continue`.DiffManager @@ -13,12 +12,16 @@ import com.intellij.openapi.project.DumbAware import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel +import kotlin.properties.Delegates @Service(Service.Level.PROJECT) class ContinuePluginService : Disposable, DumbAware { private val coroutineScope = CoroutineScope(Dispatchers.Main) var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null - var ideProtocolClient: IdeProtocolClient? = null + var listener: (() -> Unit)? = null + var ideProtocolClient: IdeProtocolClient? by Delegates.observable(null) { _, _, _ -> + synchronized(this) { listener?.also { listener = null }?.invoke() } + } var coreMessengerManager: CoreMessengerManager? = null val coreMessenger: CoreMessenger? get() = coreMessengerManager?.coreMessenger @@ -41,4 +44,23 @@ class ContinuePluginService : Disposable, DumbAware { ) { continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId) } + + /** + * Add a listener for protocolClient initialization. + * Currently, only one needs to be processed. If there are more than one, + * we can use an array to add listeners to ensure that the message is processed. + */ + fun onProtocolClientInitialized(listener: () -> Unit) { + if (ideProtocolClient == null) { + synchronized(this) { + if (ideProtocolClient == null) { + this.listener = listener + } else { + listener() + } + } + } else { + listener() + } + } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt index 8cb700f15..43a468cf7 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/toolWindow/ContinueBrowser.kt @@ -1,7 +1,6 @@ package com.github.continuedev.continueintellijextension.toolWindow import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable -import com.github.continuedev.continueintellijextension.constants.MessageTypes import com.github.continuedev.continueintellijextension.constants.MessageTypes.Companion.PASS_THROUGH_TO_CORE import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings @@ -10,11 +9,11 @@ import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.ui.jcef.* import com.intellij.ui.jcef.JBCefClient.Properties +import com.intellij.util.application import org.cef.CefApp import org.cef.browser.CefBrowser import org.cef.handler.CefLoadHandlerAdapter @@ -30,8 +29,10 @@ class ContinueBrowser(val project: Project, url: String) { val browser: JBCefBrowser + val continuePluginService: ContinuePluginService = project.getService(ContinuePluginService::class.java) + init { - val isOSREnabled = ServiceManager.getService(ContinueExtensionSettings::class.java).continueState.enableOSR + val isOSREnabled = application.getService(ContinueExtensionSettings::class.java).continueState.enableOSR this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(isOSREnabled).build().apply { // To avoid using System.setProperty to affect other plugins, @@ -42,7 +43,6 @@ class ContinueBrowser(val project: Project, url: String) { } registerAppSchemeHandler() - browser.loadURL(url) Disposer.register(ContinuePluginDisposable.getInstance(project), browser) // Listen for events sent from browser @@ -55,11 +55,6 @@ class ContinueBrowser(val project: Project, url: String) { val data = json.get("data") val messageId = json.get("messageId")?.asString - val continuePluginService = ServiceManager.getService( - project, - ContinuePluginService::class.java - ) - val respond = fun(data: Any?) { sendToWebview(messageType, data, messageId ?: uuid()) } @@ -101,6 +96,13 @@ class ContinueBrowser(val project: Project, url: String) { } }, browser.cefBrowser) + // Load the url only after the protocolClient is initialized, + // otherwise some messages will be lost, which are some configurations when the page is loaded. + // Moreover, we should add LoadHandler before loading the url. + continuePluginService.onProtocolClientInitialized { + browser.loadURL(url) + } + } fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) { From 115d069e62067858b10179bd0b2ec7144c771c32 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 9 Apr 2025 10:06:20 -0700 Subject: [PATCH 03/54] token-counts --- core/llm/constants.ts | 22 ------------- core/llm/countTokens.ts | 30 +++++++++-------- core/llm/index.ts | 40 +++++++---------------- packages/llm-info/src/providers/openai.ts | 6 ++++ 4 files changed, 33 insertions(+), 65 deletions(-) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 333c79e70..1eb81569e 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -7,38 +7,16 @@ const DEFAULT_ARGS = { temperature: DEFAULT_TEMPERATURE, }; -const GPT_4_CTX_LEN = 128_000; - -const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0613": 4096, - "gpt-3.5-turbo-16k": 16_384, - "gpt-35-turbo-16k": 16_384, - "gpt-35-turbo-0613": 4096, - "gpt-35-turbo": 4096, - "gpt-4": 4096, - "gpt-4-32k": 32_000, - "gpt-4-turbo-preview": 32_000, - "gpt-4o": GPT_4_CTX_LEN, - "gpt-4o-mini": GPT_4_CTX_LEN, - "gpt-4-vision": GPT_4_CTX_LEN, - "gpt-4-0125-preview": GPT_4_CTX_LEN, - "gpt-4-1106-preview": GPT_4_CTX_LEN, -}; - -const TOKEN_BUFFER_FOR_SAFETY = 350; const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) const DEFAULT_MAX_BATCH_SIZE = 64; export { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, PROXY_URL, - TOKEN_BUFFER_FOR_SAFETY, }; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 2fc01f9b8..0fae50656 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -4,6 +4,7 @@ import { ChatMessage, MessageContent, MessagePart, + Tool, UserChatMessage, } from "../index.js"; @@ -15,7 +16,6 @@ import { LlamaAsyncEncoder, } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; -import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; import { isRuleActive } from "./rules/isRuleActive.js"; import { extractPathsFromCodeBlocks } from "./utils/extractPathsFromCodeBlocks.js"; @@ -220,6 +220,8 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } +const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; + function pruneRawPromptFromTop( modelName: string, contextLength: number, @@ -227,20 +229,20 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; return pruneStringFromTop(modelName, maxTokens, prompt); } -function pruneRawPromptFromBottom( - modelName: string, - contextLength: number, - prompt: string, - tokensForCompletion: number, -): string { - const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; - return pruneStringFromBottom(modelName, maxTokens, prompt); -} +// function pruneRawPromptFromBottom( +// modelName: string, +// contextLength: number, +// prompt: string, +// tokensForCompletion: number, +// ): string { +// const maxTokens = +// contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; +// return pruneStringFromBottom(modelName, maxTokens, prompt); +// } function summarize(message: ChatMessage): string { return `${renderChatMessage(message).substring(0, 100)}...`; @@ -514,7 +516,7 @@ function compileChatMessages({ maxTokens, supportsImages, prompt, - functions, + tools, systemMessage, rules, }: { @@ -524,7 +526,7 @@ function compileChatMessages({ maxTokens: number; supportsImages: boolean; prompt: string | undefined; - functions: any[] | undefined; + tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { diff --git a/core/llm/index.ts b/core/llm/index.ts index 7544b5292..0c79c6974 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -40,7 +40,6 @@ import { modelSupportsImages, } from "./autodetect.js"; import { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, @@ -278,33 +277,6 @@ export abstract class BaseLLM implements ILLM { return Promise.resolve([]); } - private _compileChatMessages( - options: CompletionOptions, - messages: ChatMessage[], - functions?: any[], - ) { - let contextLength = this.contextLength; - if ( - options.model !== this.model && - options.model in CONTEXT_LENGTH_FOR_MODEL - ) { - contextLength = - CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; - } - - return compileChatMessages({ - modelName: options.model, - msgs: messages, - contextLength, - maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, - supportsImages: this.supportsImages(), - prompt: undefined, - functions, - systemMessage: this.systemMessage, - rules: this.rules ?? [], - }); - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -913,7 +885,17 @@ export abstract class BaseLLM implements ILLM { completionOptions = this._modifyCompletionOptions(completionOptions); - const messages = this._compileChatMessages(completionOptions, _messages); + const messages = compileChatMessages({ + modelName: completionOptions.model, + msgs: _messages, + contextLength: this.contextLength, + maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + prompt: undefined, + tools: options.tools, + systemMessage: this.systemMessage, + rules: this.rules ?? [], + }); const prompt = this.templateMessages ? this.templateMessages(messages) diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index b96461e4b..a15dd3089 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -8,6 +8,12 @@ export const OpenAi: ModelProvider = { contextLength: 16385, maxCompletionTokens: 4096, }, + { + model: "gpt-3.5-turbo-0613", + displayName: "GPT-3.5 Turbo", + contextLength: 16385, + maxCompletionTokens: 4096, + }, { model: "gpt-3.5-turbo-16k", displayName: "GPT-3.5 Turbo 16K", From 57441dad6696eeb6d4bd6d769aec06e389367a53 Mon Sep 17 00:00:00 2001 From: YUAN Date: Sun, 13 Apr 2025 00:17:54 +0800 Subject: [PATCH 04/54] fix: models and mode are not synced --- .../components/modelSelection/ModelSelect.tsx | 43 ++++++++++++------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/gui/src/components/modelSelection/ModelSelect.tsx b/gui/src/components/modelSelection/ModelSelect.tsx index 8191af54b..885864d10 100644 --- a/gui/src/components/modelSelection/ModelSelect.tsx +++ b/gui/src/components/modelSelection/ModelSelect.tsx @@ -12,7 +12,9 @@ import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; import AddModelForm from "../../forms/AddModelForm"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { selectSelectedChatModel } from "../../redux/slices/configSlice"; +import { + selectIsInEditMode, +} from "../../redux/slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { updateSelectedModelByRole } from "../../redux/thunks"; import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util"; @@ -120,10 +122,23 @@ function ModelOption({ function ModelSelect() { const dispatch = useAppDispatch(); - const selectedChatModel = useAppSelector(selectSelectedChatModel); - const allChatModels = useAppSelector( - (state) => state.config.config.modelsByRole.chat, - ); + + const isInEditMode = useAppSelector(selectIsInEditMode); + const config = useAppSelector((state) => state.config.config); + + let selectedModel = null; + let allModels = null; + if (isInEditMode) { + allModels = config.modelsByRole.edit; + selectedModel = config.selectedModelByRole.edit; + } + if (!selectedModel) { + selectedModel = config.selectedModelByRole.chat; + } + if (!allModels || allModels.length === 0) { + allModels = config.modelsByRole.chat; + } + const buttonRef = useRef(null); const [options, setOptions] = useState([]); const [sortedOptions, setSortedOptions] = useState([]); @@ -141,9 +156,7 @@ function ModelSelect() { useEffect(() => { setOptions( - allChatModels - .filter((m) => !m.roles || m.roles.includes("chat")) - .map((model) => { + allModels.map((model) => { return { value: model.title, title: modelSelectTitle(model), @@ -151,7 +164,7 @@ function ModelSelect() { }; }), ); - }, [allChatModels]); + }, [isInEditMode, config]); useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { @@ -162,7 +175,7 @@ function ModelSelect() { const direction = event.shiftKey ? -1 : 1; const currentIndex = options.findIndex( - (option) => option.value === selectedChatModel?.title, + (option) => option.value === selectedModel?.title, ); let nextIndex = (currentIndex + 1 * direction) % options.length; if (nextIndex < 0) nextIndex = options.length - 1; @@ -182,7 +195,7 @@ function ModelSelect() { return () => { window.removeEventListener("keydown", handleKeyDown); }; - }, [options, selectedChatModel]); + }, [options, selectedModel]); function onClickAddModel(e: MouseEvent) { e.stopPropagation(); @@ -207,11 +220,11 @@ function ModelSelect() { return ( { - if (val === selectedChatModel?.title) return; + if (val === selectedModel?.title) return; dispatch( updateSelectedModelByRole({ selectedProfile, - role: "chat", + role: isInEditMode ? "edit" : "chat", modelTitle: val, }), ); @@ -224,7 +237,7 @@ function ModelSelect() { className="h-[18px] gap-1 border-none text-gray-400" > - {modelSelectTitle(selectedChatModel) || "Select model"} + {modelSelectTitle(selectedModel) || "Select model"} ))} From 4e0ac878f7b66bc741a6bc3fb60e180aadcde4f1 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Sun, 13 Apr 2025 19:43:53 -0700 Subject: [PATCH 05/54] BROKEN - tools updates --- core/.eslintrc.json | 2 +- core/core.ts | 22 +-- core/llm/countTokens.ts | 275 ++++++++++++++++------------ core/llm/index.ts | 1 - core/tools/builtIn.ts | 2 + core/tools/callTool.ts | 73 +++++--- core/tools/toolError.ts | 14 ++ extensions/vscode/package-lock.json | 6 +- gui/src/redux/thunks/callTool.ts | 12 +- 9 files changed, 230 insertions(+), 177 deletions(-) create mode 100644 core/tools/toolError.ts diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 4790b5c45..517558d32 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -13,7 +13,7 @@ "@typescript-eslint/semi": "off", "eqeqeq": "error", "complexity": ["error", { "max": 38 }], - "max-lines-per-function": ["error", { "max": 485 }], + "max-lines-per-function": ["error", { "max": 520 }], "max-statements": ["error", { "max": 114 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], diff --git a/core/core.ts b/core/core.ts index e929a863b..43bfb8cd5 100644 --- a/core/core.ts +++ b/core/core.ts @@ -683,23 +683,13 @@ export class Core { const llm = await this.configHandler.llmFromTitle(selectedModelTitle); - const contextItems = await callTool( + const contextItems = await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - }, - ); - - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } + }); return { contextItems }; }); diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index 0fae50656..d3a5f152c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -151,6 +151,51 @@ export function flattenMessages(msgs: ChatMessage[]): ChatMessage[] { return flattened; } +// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 +function countToolsTokens(tools: Tool[], modelName: string): number { + const count = (value: string) => + encodingForModel(modelName).encode(value).length; + + let numTokens = 12; + + for (const tool of tools) { + let functionTokens = count(tool.function.name); + if (tool.function.description) { + functionTokens += count(tool.function.description); + } + const props = tool.function.parameters?.properties; + if (props) { + for (const key in props) { + functionTokens += count(key); + const fields = props[key]; + if (fields) { + const fieldType = fields["type"]; + const fieldDesc = fields["description"]; + const fieldEnum = fields["enum"]; + if (fieldType && typeof fieldType === "string") { + functionTokens += 2; + functionTokens += count(fieldType); + } + if (fieldDesc && typeof fieldDesc === "string") { + functionTokens += 2; + functionTokens += count(fieldDesc); + } + if (fieldEnum && Array.isArray(fieldEnum)) { + functionTokens -= 3; + for (const e of fieldEnum) { + functionTokens += 3; + functionTokens += typeof e === "string" ? count(e) : 5; + } + } + } + } + } + numTokens += functionTokens; + } + + return numTokens + 12; +} + function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -158,8 +203,38 @@ function countChatMessageTokens( // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb // every message follows <|im_start|>{role/name}\n{content}<|end|>\n - const TOKENS_PER_MESSAGE: number = 4; - return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; + const BASE_TOKENS = 4; + const TOOL_CALL_EXTRA_TOKENS = 10; + const TOOL_OUTPUT_EXTRA_TOKENS = 10; + let tokens = BASE_TOKENS; + + if (chatMessage.content) { + tokens += countTokens(chatMessage.content, modelName); + } + + if ("toolCalls" in chatMessage && chatMessage.toolCalls) { + for (const call of chatMessage.toolCalls) { + tokens += TOOL_CALL_EXTRA_TOKENS; + tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this + } + } + + if (chatMessage.role === "thinking") { + if (chatMessage.redactedThinking) { + tokens += countTokens(chatMessage.redactedThinking, modelName); + } + if (chatMessage.signature) { + tokens += countTokens(chatMessage.signature, modelName); + } + } + + if (chatMessage.role === "tool") { + tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety + if (chatMessage.toolCallId) { + tokens += countTokens(chatMessage.toolCallId, modelName); + } + } + return tokens; } function pruneLinesFromTop( @@ -220,7 +295,14 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } -const MAX_TOKEN_BUFFER_FOR_SAFETY = 3000; +const MAX_TOKEN_SAFETY_BUFFER = 1000; +const TOKEN_BUFFER_PROPORTION = 0.07; +function getTokenBufferSafety(contextLength: number) { + return Math.min( + MAX_TOKEN_SAFETY_BUFFER, + contextLength * TOKEN_BUFFER_PROPORTION, + ); +} function pruneRawPromptFromTop( modelName: string, @@ -229,7 +311,7 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - Math.max(MAX_TOKEN_BUFFER_FOR_SAFETY, contextLength*; + contextLength - tokensForCompletion - getTokenBufferSafety(contextLength); return pruneStringFromTop(modelName, maxTokens, prompt); } @@ -245,128 +327,97 @@ function pruneRawPromptFromTop( // } function summarize(message: ChatMessage): string { - return `${renderChatMessage(message).substring(0, 100)}...`; + return `(Truncated message): ${renderChatMessage(message).substring(0, 100)}...`; } function pruneChatHistory( modelName: string, chatHistory: ChatMessage[], - contextLength: number, - tokensForCompletion: number, + inputTokensAvailable: number, ): ChatMessage[] { - let totalTokens = - tokensForCompletion + - chatHistory.reduce((acc, message) => { - return acc + countChatMessageTokens(modelName, message); - }, 0); - - // 0. Prune any messages that take up more than 1/3 of the context length - const zippedMessagesAndTokens: [ChatMessage, number][] = []; - - // Zipped ChatMessage with its token counts - chatHistory.forEach((message) => { - const zippedItem: [ChatMessage, number] = [ - message, - countTokens(message.content, modelName), - ]; - zippedMessagesAndTokens.push(zippedItem); + let currentTokens = 0; + const messagesWithTokens = chatHistory.map((message) => { + const tokens = countChatMessageTokens(modelName, message); + currentTokens += tokens; + return { + ...message, + tokens, + }; }); - const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( - ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, - ); + const sysMessage = messagesWithTokens.find((msg) => msg.role === "system"); + const sysMessageTokens = sysMessage?.tokens ?? 0; - zippedLongerThanOneThird.sort( - ( - [_messageA, tokensA]: [ChatMessage, number], - [_messageB, tokensB]: [ChatMessage, number], - ) => { - return tokensB - tokensA; - }, - ); + const lastUserMessage = messagesWithTokens.at(-1); + // if (lastMessage?.role === "user") + // General strategy: + // Walk from the oldest messages forward to last 5, removing while still above token limit + // Once at the last 5, attempt to summarize if summarizable + // Then, double check no latent tool responses that don't have their preceding calls + // Until under token count - const longerThanOneThird = zippedLongerThanOneThird.map( - ([message, _token]: [ChatMessage, number]) => message, - ); - const distanceFromThird = zippedLongerThanOneThird.map( - ([_message, token]: [ChatMessage, number]) => token - contextLength / 3, - ); - - for (let i = 0; i < longerThanOneThird.length; i++) { - // Prune line-by-line from the top - const message = longerThanOneThird[i]; - const content = renderChatMessage(message); - const deltaNeeded = totalTokens - contextLength; - const delta = Math.min(deltaNeeded, distanceFromThird[i]); - message.content = pruneStringFromTop( - modelName, - countTokens(message.content, modelName) - delta, - content, - ); - totalTokens -= delta; + // 1. Remove entire messages until the last 5 + while ( + messagesWithTokens.length > 5 && + currentTokens > inputTokensAvailable + ) { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } - // 1. Replace beyond last 5 messages with summary - let i = 0; - while (totalTokens > contextLength && i < chatHistory.length - 5) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message), modelName); - message.content = summarize(message); - i++; - } - - // 2. Remove entire messages until the last 5 - while (chatHistory.length > 5 && totalTokens > contextLength) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + // At this point make sure no latent tool response without corresponding call + while (messagesWithTokens[0]?.role === "tool") { + const message = messagesWithTokens.shift()!; + currentTokens -= message.tokens; } // 3. Truncate message in the last 5, except last 1 - i = 0; + let i = 0; while ( - totalTokens > contextLength && - chatHistory.length > 0 && - i < chatHistory.length - 1 + totalTokens > inputTokensAvailable && + messagesWithTokens.length > 0 && + i < messagesWithTokens.length - 1 ) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens[i]; + totalTokens -= message.tokens; totalTokens += countTokens(summarize(message), modelName); message.content = summarize(message); i++; } // 4. Remove entire messages in the last 5, except last 1 - while (totalTokens > contextLength && chatHistory.length > 1) { + while (totalTokens > inputTokensAvailable && messagesWithTokens.length > 1) { // If tool call/response detected prune both (can't have response with no call) // TODO prune lines from tool response before pruning both messages if ( - chatHistory.length > 2 && - messageHasToolCalls(chatHistory[0]) && - chatHistory[1].role === "tool" + messagesWithTokens.length > 2 && + messageHasToolCalls(messagesWithTokens[0]) && + messagesWithTokens[1].role === "tool" ) { - const firstMessage = chatHistory.shift()!; - const secondMessage = chatHistory.shift()!; - totalTokens -= countTokens(firstMessage.content, modelName); - totalTokens -= countTokens(secondMessage.content, modelName); + const firstMessage = messagesWithTokens.shift()!; + const secondMessage = messagesWithTokens.shift()!; + totalTokens -= firstMessage.tokens; + totalTokens -= secondMessage.tokens; } else { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); + const message = messagesWithTokens.shift()!; + totalTokens -= message.tokens; } } - // 5. Truncate last message - if (totalTokens > contextLength && chatHistory.length > 0) { - const message = chatHistory[0]; - message.content = pruneRawPromptFromTop( - modelName, - contextLength, - renderChatMessage(message), - tokensForCompletion, + if (currentTokens > inputTokensAvailable) { + throw new Error( + "Unable to prune chat history to fit into model's context window", ); - totalTokens = contextLength; } - return chatHistory; + + if (messagesWithTokens.length === 0) { + throw new Error("Error processing chat history"); + } + + return messagesWithTokens.map((msg) => { + const { tokens, ...rest } = msg; + return rest; + }); } function messageIsEmpty(message: ChatMessage): boolean { @@ -515,7 +566,6 @@ function compileChatMessages({ contextLength, maxTokens, supportsImages, - prompt, tools, systemMessage, rules, @@ -525,11 +575,22 @@ function compileChatMessages({ contextLength: number; maxTokens: number; supportsImages: boolean; - prompt: string | undefined; tools: Tool[] | undefined; systemMessage: string | undefined; rules: Rule[]; }): ChatMessage[] { + let toolTokens = 0; + if (tools) { + toolTokens = countToolsTokens(tools, modelName); + } + + const safetyBuffer = getTokenBufferSafety(contextLength); + if (toolTokens + maxTokens + safetyBuffer >= contextLength) { + throw new Error( + `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response.${toolTokens ? toolTokens + "tools tokens included in the request may also cause this issue" : ""}`, + ); + } + let msgsCopy = msgs ? msgs .map((msg) => ({ ...msg })) @@ -538,14 +599,6 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - if (prompt) { - const promptMsg: ChatMessage = { - role: "user", - content: prompt, - }; - msgsCopy.push(promptMsg); - } - const lastUserMessage = getLastUserMessage(msgsCopy); msgsCopy = addSystemMessage({ @@ -560,19 +613,6 @@ function compileChatMessages({ originalMessages: msgs, }); - let functionTokens = 0; - if (functions) { - for (const func of functions) { - functionTokens += countTokens(JSON.stringify(func), modelName); - } - } - - if (maxTokens + functionTokens + TOKEN_BUFFER_FOR_SAFETY >= contextLength) { - throw new Error( - `maxTokens (${maxTokens}) is too close to contextLength (${contextLength}), which doesn't leave room for response. Try increasing the contextLength parameter of the model in your config.json.`, - ); - } - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -586,8 +626,7 @@ function compileChatMessages({ const history = pruneChatHistory( modelName, msgsCopy, - contextLength, - functionTokens + maxTokens + TOKEN_BUFFER_FOR_SAFETY, + contextLength - toolTokens - maxTokens - safetyBuffer, ); if (history.length >= 2 && history[history.length - 2].role === "system") { diff --git a/core/llm/index.ts b/core/llm/index.ts index 0c79c6974..c53653aed 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -891,7 +891,6 @@ export abstract class BaseLLM implements ILLM { contextLength: this.contextLength, maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, supportsImages: this.supportsImages(), - prompt: undefined, tools: options.tools, systemMessage: this.systemMessage, rules: this.rules ?? [], diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 7cff1c70e..7afd88615 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -16,3 +16,5 @@ export enum BuiltInToolNames { } export const BUILT_IN_GROUP_NAME = "Built-In"; + +export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index 28a8f8c30..524fbaf47 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -12,6 +12,7 @@ import { readFileImpl } from "./implementations/readFile"; import { runTerminalCommandImpl } from "./implementations/runTerminalCommand"; import { searchWebImpl } from "./implementations/searchWeb"; import { viewDiffImpl } from "./implementations/viewDiff"; +import { toolErrorContextItem } from "./toolError"; async function callHttpTool( url: string, @@ -129,38 +130,54 @@ async function callToolFromUri( } } +// Handles calls for core/non-client tools +// Returns an error context item if the tool call fails export async function callTool( tool: Tool, - args: any, + callArgs: string, extras: ToolExtras, ): Promise { + const args = JSON.parse(callArgs || "{}"); const uri = tool.uri ?? tool.function.name; - - switch (uri) { - case BuiltInToolNames.ReadFile: - return await readFileImpl(args, extras); - // Note: Custom GUI handling for edit - case BuiltInToolNames.CreateNewFile: - return await createNewFileImpl(args, extras); - case BuiltInToolNames.GrepSearch: - return await grepSearchImpl(args, extras); - case BuiltInToolNames.FileGlobSearch: - return await fileGlobSearchImpl(args, extras); - case BuiltInToolNames.RunTerminalCommand: - return await runTerminalCommandImpl(args, extras); - case BuiltInToolNames.SearchWeb: - return await searchWebImpl(args, extras); - case BuiltInToolNames.ViewDiff: - return await viewDiffImpl(args, extras); - case BuiltInToolNames.LSTool: - return await lsToolImpl(args, extras); - case BuiltInToolNames.ReadCurrentlyOpenFile: - return await readCurrentlyOpenFileImpl(args, extras); - // case BuiltInToolNames.ViewRepoMap: - // return await viewRepoMapImpl(args, extras); - // case BuiltInToolNames.ViewSubdirectory: - // return await viewSubdirectoryImpl(args, extras); - default: - return await callToolFromUri(uri, args, extras); + try { + let contextItems: ContextItem[] = []; + switch (uri) { + case BuiltInToolNames.ReadFile: + contextItems = await readFileImpl(args, extras); + case BuiltInToolNames.CreateNewFile: + contextItems = await createNewFileImpl(args, extras); + case BuiltInToolNames.GrepSearch: + contextItems = await grepSearchImpl(args, extras); + case BuiltInToolNames.FileGlobSearch: + contextItems = await fileGlobSearchImpl(args, extras); + case BuiltInToolNames.RunTerminalCommand: + contextItems = await runTerminalCommandImpl(args, extras); + case BuiltInToolNames.SearchWeb: + contextItems = await searchWebImpl(args, extras); + case BuiltInToolNames.ViewDiff: + contextItems = await viewDiffImpl(args, extras); + case BuiltInToolNames.LSTool: + contextItems = await lsToolImpl(args, extras); + case BuiltInToolNames.ReadCurrentlyOpenFile: + contextItems = await readCurrentlyOpenFileImpl(args, extras); + // case BuiltInToolNames.ViewRepoMap: + // contextItems = await viewRepoMapImpl(args, extras); + // case BuiltInToolNames.ViewSubdirectory: + // contextItems = await viewSubdirectoryImpl(args, extras); + default: + contextItems = await callToolFromUri(uri, args, extras); + } + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return contextItems; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return [toolErrorContextItem(uri, errorMessage)]; } } diff --git a/core/tools/toolError.ts b/core/tools/toolError.ts new file mode 100644 index 000000000..5cffc25d5 --- /dev/null +++ b/core/tools/toolError.ts @@ -0,0 +1,14 @@ +import { ContextItem } from ".."; + +export const toolErrorContextItem = ( + functionName: string, + errorMessage: string, +): ContextItem => { + return { + icon: "problems", + name: "Tool Call Error", + description: "Tool Call Failed", + content: `${functionName} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }; +}; diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 108520e49..19b4e5384 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.21", + "version": "1.1.22", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -106,7 +106,7 @@ "@aws-sdk/client-sagemaker-runtime": "^3.777.0", "@aws-sdk/credential-providers": "^3.778.0", "@continuedev/config-types": "^1.0.13", - "@continuedev/config-yaml": "^1.0.71", + "@continuedev/config-yaml": "^1.0.77", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", "@continuedev/openai-adapters": "^1.0.18", diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts index bf15e7ae8..d75fa5897 100644 --- a/gui/src/redux/thunks/callTool.ts +++ b/gui/src/redux/thunks/callTool.ts @@ -58,7 +58,7 @@ export const callTool = createAsyncThunk( toolCallState.toolCallId, ); } catch (e) { - errorMessage = "Failed to call edit tool"; + errorMessage = `Failed to call ${toolCallState.toolCall.function.name} tool`; if (e instanceof Error) { errorMessage = e.message; } @@ -92,15 +92,7 @@ export const callTool = createAsyncThunk( const wrapped = await dispatch( streamResponseAfterToolCall({ toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - icon: "problems", - name: "Tool Call Error", - description: "Tool Call Failed", - content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, - hidden: false, - }, - ], + toolOutput: [], }), ); unwrapResult(wrapped); From a0d9d6307fa05b2b70fbf98b0e3db2da2ca8d691 Mon Sep 17 00:00:00 2001 From: WEC Date: Mon, 14 Apr 2025 20:07:03 +0800 Subject: [PATCH 06/54] fix:recently edited files change ignore bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit function shouldIgnore return promise,if dont await,nothing can set in recentlyEditedFilesCache --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index 68aa605ac..14c45727c 100644 --- a/core/core.ts +++ b/core/core.ts @@ -642,7 +642,7 @@ export class Core { on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { try { - const ignore = shouldIgnore(filepath, this.ide); + const ignore = await shouldIgnore(filepath, this.ide); if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } From 8bb18fd2ee4a0fb81b2f24903e47fb1b0beade36 Mon Sep 17 00:00:00 2001 From: Muli Yulzary <8338082+muliyul@users.noreply.github.com> Date: Mon, 14 Apr 2025 19:02:39 +0300 Subject: [PATCH 07/54] feat: support o3/o4 as agents --- core/llm/toolSupport.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 3d0d72cc8..64b604e6d 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -31,6 +31,14 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + azure: (model) => { + if ( + model.toLowerCase().startsWith("gpt-4") || + model.toLowerCase().startsWith("o3") + ) { + return true; + return false; + } openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( From 4d7fbc0a0e9f12048e33ba42cef5212a10d350a6 Mon Sep 17 00:00:00 2001 From: Muli Yulzary <8338082+muliyul@users.noreply.github.com> Date: Mon, 14 Apr 2025 19:04:30 +0300 Subject: [PATCH 08/54] fix formatting --- core/llm/toolSupport.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 64b604e6d..74ad78d46 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -35,9 +35,8 @@ export const PROVIDER_TOOL_SUPPORT: Record< if ( model.toLowerCase().startsWith("gpt-4") || model.toLowerCase().startsWith("o3") - ) { - return true; - return false; + ) return true; + return false; } openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling From 7557bf2e2bd3eb9263ee4a46a9756b15dea5d0e7 Mon Sep 17 00:00:00 2001 From: Muli Yulzary Date: Mon, 14 Apr 2025 22:22:17 +0300 Subject: [PATCH 09/54] formating --- core/llm/toolSupport.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 74ad78d46..46abd83c0 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -36,8 +36,8 @@ export const PROVIDER_TOOL_SUPPORT: Record< model.toLowerCase().startsWith("gpt-4") || model.toLowerCase().startsWith("o3") ) return true; - return false; - } + return false; + }, openai: (model) => { // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( From 608ca07dfbab6300f235ffe41ecfc2ee11798bac Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 15 Apr 2025 18:39:30 +0530 Subject: [PATCH 10/54] add prompt template for autocomplete --- core/autocomplete/CompletionProvider.ts | 5 +++++ core/index.d.ts | 4 ++-- packages/config-yaml/src/schemas/models.ts | 1 + 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index b56d153dc..9753ab57a 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -122,6 +122,7 @@ export class CompletionProvider { private async _getAutocompleteOptions() { const { config } = await this.configHandler.loadConfig(); + // console.log('debug1 the config was', config?.selectedModelByRole.autocomplete, config.) const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, ...config?.tabAutocompleteOptions, @@ -154,6 +155,10 @@ export class CompletionProvider { return undefined; } + if (llm.promptTemplates?.autocomplete) { + options.template = llm.promptTemplates.autocomplete as string; + } + const helper = await HelperVars.create( input, options, diff --git a/core/index.d.ts b/core/index.d.ts index 30a977717..2774d9403 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,4 @@ -import { DataDestination, ModelRole, Rule } from "@continuedev/config-yaml"; +import { DataDestination, ModelRole, PromptTemplates, Rule } from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; @@ -566,7 +566,7 @@ export interface LLMOptions { completionOptions?: CompletionOptions; requestOptions?: RequestOptions; template?: TemplateType; - promptTemplates?: Record; + promptTemplates?: Partial>; templateMessages?: (messages: ChatMessage[]) => string; logger?: ILLMLogger; llmRequestHook?: (model: string, prompt: string) => any; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 2334b4c7c..01b66228d 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -65,6 +65,7 @@ export type ChatOptions = z.infer; const promptTemplatesSchema = z.object({ apply: z.string().optional(), edit: z.string().optional(), + autocomplete: z.string().optional() }); export type PromptTemplates = z.infer; From b0e676b5dd15878ccd616e24e2c7c48df802c684 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Tue, 15 Apr 2025 18:55:25 +0530 Subject: [PATCH 11/54] update corresponding docs --- core/autocomplete/CompletionProvider.ts | 2 ++ .../customize/model-roles/autocomplete.md | 21 +++++++++++++++++++ docs/docs/reference.md | 2 +- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 9753ab57a..389c45495 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -186,6 +186,8 @@ export class CompletionProvider { helper, }); + console.log('debug1 the prompt was->', prompt) + // Completion let completion: string | undefined = ""; diff --git a/docs/docs/customize/model-roles/autocomplete.md b/docs/docs/customize/model-roles/autocomplete.md index 9641d5dcb..194656ab0 100644 --- a/docs/docs/customize/model-roles/autocomplete.md +++ b/docs/docs/customize/model-roles/autocomplete.md @@ -12,3 +12,24 @@ In Continue, autocomplete models are used to display inline [Autocomplete](../.. ## Recommended Autocomplete models Visit the [Autocomplete Deep Dive](../deep-dives/autocomplete.mdx) for recommended models and more details. + +## Prompt templating + +You can customize the prompt template used when autocomplete happens by setting the `promptTemplates.autocomplete` property in your model configuration. Continue uses [Handlebars syntax](https://handlebarsjs.com/guide/) for templating. + +Available variables for the apply template: + +- `{{{prefix}}}` - the code before your cursor +- `{{{suffix}}}` - the code after your cursor +- `{{{filename}}}` - the name of the file your cursor currently is +- `{{{reponame}}}` - the name of the folder where the codebase is +- `{{{language}}}` - the name of the programming language in full (ex. Typescript) + +Example: + +```yaml +models: + - name: My Custom Autocomplete Template + provider: ollama + model: qwen2.5-coder:1.5b +``` \ No newline at end of file diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 6269a1bb7..ac90b8269 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -145,7 +145,7 @@ The `models` section defines the language models used in your configuration. Mod - `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating) and [`apply`](./customize/model-roles/apply.mdx#prompt-templating). +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating) - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: From 31cb0e657df9dfd22d02760ee1cea8df42aa5b64 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Wed, 16 Apr 2025 16:27:16 +0530 Subject: [PATCH 12/54] show not allowed cursor when enter button is disabled --- gui/src/components/mainInput/InputToolbar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index f243f5ac4..a58090bfd 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -65,7 +65,7 @@ const EnterButton = styled.button<{ isPrimary?: boolean }>` cursor: pointer; :disabled { - cursor: wait; + cursor: not-allowed; } `; From 3fe57c13aa3b834d8f9125b0108ed6913d1e728a Mon Sep 17 00:00:00 2001 From: Keerthana Panyam Date: Wed, 16 Apr 2025 13:04:45 -0400 Subject: [PATCH 13/54] edit prompt hint text ellipsized by default the edit prompt hint text was too long to fit into the default side bar width. This is shorter (35 characters compared to 55), and the format is consistent with the hint text. --- gui/src/components/mainInput/ContinueInputBox.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 14777acb6..1bcbb3c8c 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -100,7 +100,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) { const historyKey = props.isEditMode ? "edit" : "chat"; const placeholder = props.isEditMode - ? "Describe how to modify the code - use '#' to add files" + ? "Describe changes, '#' to add files" : undefined; const toolbarOptions: ToolbarOptions = props.isEditMode From 4ede36e3b5abf17be6b4741be4eda89ad9c768df Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 17 Apr 2025 04:58:20 +0000 Subject: [PATCH 14/54] build(deps): bump http-proxy-middleware from 2.0.7 to 2.0.9 in /docs Bumps [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware) from 2.0.7 to 2.0.9. - [Release notes](https://github.com/chimurai/http-proxy-middleware/releases) - [Changelog](https://github.com/chimurai/http-proxy-middleware/blob/v2.0.9/CHANGELOG.md) - [Commits](https://github.com/chimurai/http-proxy-middleware/compare/v2.0.7...v2.0.9) --- updated-dependencies: - dependency-name: http-proxy-middleware dependency-version: 2.0.9 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- docs/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/package-lock.json b/docs/package-lock.json index deb0071b8..38e005c4e 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -9521,9 +9521,9 @@ } }, "node_modules/http-proxy-middleware": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz", - "integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz", + "integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==", "license": "MIT", "dependencies": { "@types/http-proxy": "^1.17.8", From e0a432ed363f9697791560ed7ad267d29c652f67 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 17 Apr 2025 11:05:00 +0530 Subject: [PATCH 15/54] refactor AddFileCombobox to update selectedFiles based on codeToEdit changes --- gui/src/components/CodeToEditCard/AddFileCombobox.tsx | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index d096f90a2..da77492ae 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -39,6 +39,17 @@ export default function AddFileCombobox({ } }, []); + useEffect(() => { + // update selectedFiles showing only the files that are in codeToEdit + setSelectedFiles( + (prevSelectedFiles) => + prevSelectedFiles.filter( + (file) => + codeToEdit.findIndex((code) => code.filepath === file.id) !== -1, + ), + ); + }, [codeToEdit]); + const filteredFiles = query === "" ? remainingFiles From 3d243045d03e8d4688bc84ec23147747bcdbb95d Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 17 Apr 2025 11:24:11 +0530 Subject: [PATCH 16/54] reset query state after file selection in AddFileCombobox --- gui/src/components/CodeToEditCard/AddFileCombobox.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx index d096f90a2..f801ac9c7 100644 --- a/gui/src/components/CodeToEditCard/AddFileCombobox.tsx +++ b/gui/src/components/CodeToEditCard/AddFileCombobox.tsx @@ -55,12 +55,14 @@ export default function AddFileCombobox({ setSelectedFiles(files); void onSelect(files.map((file) => file.id)); buttonRef.current?.click(); + setQuery(""); }} > {({ open }) => (
{ if (!open) { From d59a331a1fe57f0519804dee7b477507d3380590 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Sat, 19 Apr 2025 14:31:15 +0530 Subject: [PATCH 17/54] explicitly specify that `uses` blocks are pulled from hub.continue.dev --- docs/docs/reference.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 22bc742ab..9df2e889e 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b ### Using Blocks -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization. +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev. Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. From a0dc7ab7c139a68a3542578c0b9529d9295355bf Mon Sep 17 00:00:00 2001 From: erweixin <2991552132@qq.com> Date: Mon, 21 Apr 2025 18:14:18 +0800 Subject: [PATCH 18/54] style: set whitespace-nowrap on dropdown items --- gui/src/components/mainInput/AtMentionDropdown/index.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index 9d5a10bec..d8c7d5316 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -515,7 +515,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { ) : ( )} - {item.title} + {item.title} {" "}
{ ); }) ) : ( - No results + No results )} )} From 1db5144b28a66fe37a808a78415498460f3e4240 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Tue, 22 Apr 2025 02:01:03 +0800 Subject: [PATCH 19/54] Update Node.js LTS to v20.19.0 Node.js v20 entered Maintenance LTS six months ago. Update the version from 20.11.0 (released over a year ago) to 20.19.0, the latest LTS release from last month. This ensures the project leverages recent Node.js improvements, including security updates, and stays on a supported LTS track. --- .node-version | 2 +- .nvmrc | 2 +- CONTRIBUTING.md | 2 +- binary/package-lock.json | 2 +- core/package-lock.json | 2 +- core/package.json | 2 +- core/vendor/package.json | 2 +- docs/package-lock.json | 2 +- docs/package.json | 2 +- extensions/intellij/CONTRIBUTING.md | 2 +- extensions/vscode/package-lock.json | 4 ++-- extensions/vscode/package.json | 2 +- gui/package-lock.json | 4 ++-- gui/package.json | 2 +- 14 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.node-version b/.node-version index 18c284172..829e9737e 100644 --- a/.node-version +++ b/.node-version @@ -1 +1 @@ -20.11.0 \ No newline at end of file +20.19.0 \ No newline at end of file diff --git a/.nvmrc b/.nvmrc index df9385826..3bf34c276 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v20.11.0 \ No newline at end of file +v20.19.0 \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce9686a8b..5b730190a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -102,7 +102,7 @@ We welcome contributions from developers of all experience levels - from first-t #### Pre-requisites -You should have Node.js version 20.11.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project: +You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project: ```bash nvm use diff --git a/binary/package-lock.json b/binary/package-lock.json index 5c2324e82..7320d18fc 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -140,7 +140,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/core/package-lock.json b/core/package-lock.json index 2536f0d29..b08d2f718 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -105,7 +105,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../../../../../documents/code/continuedev/continue/packages/config-yaml": { diff --git a/core/package.json b/core/package.json index 296b8834a..ef8141c4a 100644 --- a/core/package.json +++ b/core/package.json @@ -111,6 +111,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/core/vendor/package.json b/core/vendor/package.json index 856c71f2d..a31c4dfaa 100644 --- a/core/vendor/package.json +++ b/core/vendor/package.json @@ -13,6 +13,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/docs/package-lock.json b/docs/package-lock.json index deb0071b8..9faaeb13a 100644 --- a/docs/package-lock.json +++ b/docs/package-lock.json @@ -23,7 +23,7 @@ "nodemon": "^3.1.4" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@algolia/autocomplete-core": { diff --git a/docs/package.json b/docs/package.json index 8dac6fa86..8f6ad8c95 100644 --- a/docs/package.json +++ b/docs/package.json @@ -44,6 +44,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } diff --git a/extensions/intellij/CONTRIBUTING.md b/extensions/intellij/CONTRIBUTING.md index 26f80ee42..145ea59bf 100644 --- a/extensions/intellij/CONTRIBUTING.md +++ b/extensions/intellij/CONTRIBUTING.md @@ -52,7 +52,7 @@ notes below). ### Node.js Requirements -This project requires Node.js version 20.11.0 (LTS) or higher. You have two options for installation: +This project requires Node.js version 20.19.0 (LTS) or higher. You have two options for installation: 1. Download and install directly from [nodejs.org](https://nodejs.org/en/download). 2. If you're using NVM (Node Version Manager), set the correct Node.js version for this project by running `nvm use` in diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 4917b02cc..39853e2d4 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -93,7 +93,7 @@ "vscode-extension-tester": "^8.10.0" }, "engines": { - "node": ">=20.11.0", + "node": ">=20.19.0", "vscode": "^1.70.0" } }, @@ -198,7 +198,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "node_modules/@75lb/deep-merge": { diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index e3065f1b7..9f83a3494 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -24,7 +24,7 @@ "publisher": "Continue", "engines": { "vscode": "^1.70.0", - "node": ">=20.11.0" + "node": ">=20.19.0" }, "engine-strict": true, "galleryBanner": { diff --git a/gui/package-lock.json b/gui/package-lock.json index c65e604e6..c96d38311 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -97,7 +97,7 @@ "vitest": "^2.1.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../core": { @@ -201,7 +201,7 @@ "typescript": "^5.6.3" }, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } }, "../packages/config-yaml": { diff --git a/gui/package.json b/gui/package.json index 714f58da7..dad5f5d16 100644 --- a/gui/package.json +++ b/gui/package.json @@ -106,6 +106,6 @@ }, "engine-strict": true, "engines": { - "node": ">=20.11.0" + "node": ">=20.19.0" } } From afaabbbcbb5461723d904cee3777b4e46a32c7c2 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 11:12:58 -0700 Subject: [PATCH 20/54] remove system prompt from apply --- core/edit/streamDiffLines.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 1f5c8ffc0..8092d7ab8 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -123,11 +123,13 @@ export async function* streamDiffLines({ if (systemMessage) { if (typeof prompt === "string") { + // Removed system prompt because it was causing it to be used for Apply + // We should bring it back only for Edit prompt = [ - { - role: "system", - content: systemMessage, - }, + // { + // role: "system", + // content: systemMessage, + // }, { role: "user", content: prompt, @@ -138,10 +140,10 @@ export async function* streamDiffLines({ if (curSysMsg) { curSysMsg.content = systemMessage + "\n\n" + curSysMsg.content; } else { - prompt.unshift({ - role: "system", - content: systemMessage, - }); + // prompt.unshift({ + // role: "system", + // content: systemMessage, + // }); } } } From e636b8ad7a7540aea6951a6b3057e27913a008ff Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 11:13:06 -0700 Subject: [PATCH 21/54] relace support prediction --- core/llm/llms/Relace.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/llm/llms/Relace.ts b/core/llm/llms/Relace.ts index d65a94dc1..cc4dedf2d 100644 --- a/core/llm/llms/Relace.ts +++ b/core/llm/llms/Relace.ts @@ -11,6 +11,10 @@ export class Relace extends OpenAI { }; protected useOpenAIAdapterFor: (LlmApiRequestType | "*")[] = ["*"]; + protected supportsPrediction(model: string): boolean { + return true; + } + getConfigurationStatus() { if (!this.apiKey) { return LLMConfigurationStatuses.MISSING_API_KEY; From f8ee8141e09ea9be880363fdb34eb9309775f31f Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 11:35:26 -0700 Subject: [PATCH 22/54] again support prediction --- core/llm/llms/OpenAI.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 6ac50795a..51453d974 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -102,7 +102,12 @@ class OpenAI extends BaseLLM { } protected supportsPrediction(model: string): boolean { - const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; + const SUPPORTED_MODELS = [ + "gpt-4o-mini", + "gpt-4o", + "mistral-large", + "Fast-Apply", + ]; return SUPPORTED_MODELS.some((m) => model.includes(m)); } From 4f35ca0482a43e0dcdacdbe2094ff87864379f42 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 11:40:56 -0700 Subject: [PATCH 23/54] adjust system message --- core/llm/constructMessages.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index b58a18c9f..950ad2cbe 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -20,9 +20,9 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ When addressing code modification requests, present a concise code snippet that emphasizes only the necessary changes and uses abbreviated placeholders for - unmodified sections. For instance: + unmodified sections. For example: - \`\`\`typescript /path/to/file + \`\`\`language /path/to/file // ... rest of code here ... {{ modified code here }} @@ -34,6 +34,22 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ // ... rest of code here ... \`\`\` + In existing files, you should always restate the function or class that the snippet belongs to: + + \`\`\`language /path/to/file + // ... rest of code here ... + + function exampleFunction() { + // ... rest of code here ... + + {{ modified code here }} + + // ... rest of code here ... + } + + // ... rest of code here ... + \`\`\` + Since users have access to their complete file, they prefer reading only the relevant modifications. It's perfectly acceptable to omit unmodified portions at the beginning, middle, or end of files using these "lazy" comments. Only From a4cc558cf593d7b2044747cd1984ac2fcc34dd0e Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 12:09:14 -0700 Subject: [PATCH 24/54] diff cleaning logic --- core/diff/myers.test.ts | 12 ++++++++++++ core/diff/myers.ts | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/core/diff/myers.test.ts b/core/diff/myers.test.ts index 4148424a6..0683e5a96 100644 --- a/core/diff/myers.test.ts +++ b/core/diff/myers.test.ts @@ -41,4 +41,16 @@ describe("Test myers diff function", () => { { type: "same", line: "C" }, ]); }); + + test("should ignore single-line whitespace-only differences", () => { + const linesA = "A\n B\nC\n"; + const linesB = "A\nB\nC"; + + const diffLines = myersDiff(linesA, linesB); + expect(diffLines).toEqual([ + { type: "same", line: "A" }, + { type: "same", line: " B" }, + { type: "same", line: "C" }, + ]); + }); }); diff --git a/core/diff/myers.ts b/core/diff/myers.ts index 7dcb1f67c..0b5d23730 100644 --- a/core/diff/myers.ts +++ b/core/diff/myers.ts @@ -30,8 +30,21 @@ export function myersDiff(oldContent: string, newContent: string): DiffLine[] { const theirFormat = diffLines(oldContent, newContent, { ignoreNewlineAtEof: true, }); - const ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines); + let ourFormat = theirFormat.flatMap(convertMyersChangeToDiffLines); + // Combine consecutive old/new pairs that are identical after trimming + for (let i = 0; i < ourFormat.length - 1; i++) { + if ( + ourFormat[i]?.type === "old" && + ourFormat[i + 1]?.type === "new" && + ourFormat[i].line.trim() === ourFormat[i + 1].line.trim() + ) { + ourFormat[i] = { type: "same", line: ourFormat[i].line }; + ourFormat.splice(i + 1, 1); + } + } + + // Remove trailing empty old lines while ( ourFormat.length > 0 && ourFormat[ourFormat.length - 1].type === "old" && From 60063fd64e1d5f7f405fdaac4ae2bd77d7e6b4ae Mon Sep 17 00:00:00 2001 From: bright-ren Date: Tue, 22 Apr 2025 09:09:31 +0800 Subject: [PATCH 25/54] fix Inline edit panel can not select edit models --- .../continueintellijextension/editor/InlineEditAction.kt | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt index fd910308d..9565b3d1b 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/editor/InlineEditAction.kt @@ -133,8 +133,9 @@ fun openInlineEdit(project: Project?, editor: Editor) { val content = (response as Map)["content"] as Map val result = content["result"] as Map val config = result["config"] as Map - val models = config["models"] as List> - modelTitles.addAll(models.map { it["title"] as String }) + val models = config["modelsByRole"] as Map + val editModels = models["edit"] as List> + modelTitles.addAll(editModels.map { it["title"] as String }) } // This is a hacky way to not complicate getting model titles with coroutines From 1d1f978b709a79f111d62432d2043ebb1ba13b1c Mon Sep 17 00:00:00 2001 From: bright-ren Date: Tue, 22 Apr 2025 09:26:53 +0800 Subject: [PATCH 26/54] fix function.arguments empty issue when use tools call with Qwen2.5 vllm --- core/llm/openaiTypeConverters.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/openaiTypeConverters.ts b/core/llm/openaiTypeConverters.ts index 8e0acef56..a3a6ad895 100644 --- a/core/llm/openaiTypeConverters.ts +++ b/core/llm/openaiTypeConverters.ts @@ -51,7 +51,7 @@ export function toChatMessage( type: toolCall.type!, function: { name: toolCall.function?.name!, - arguments: toolCall.function?.arguments!, + arguments: toolCall.function?.arguments! || "{}", }, })); } From baefa9251c752335bbe4083160baa1b317ab022b Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 21 Apr 2025 21:20:17 -0700 Subject: [PATCH 27/54] fix tail configuration --- extensions/intellij/.run/IDE Logs.run.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/intellij/.run/IDE Logs.run.xml b/extensions/intellij/.run/IDE Logs.run.xml index 2743ca662..fcded8fe0 100644 --- a/extensions/intellij/.run/IDE Logs.run.xml +++ b/extensions/intellij/.run/IDE Logs.run.xml @@ -1,6 +1,6 @@ -