From af1b6b1bc4c0ce0e387e63ab674fd8ba79c862e3 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 29 Jul 2025 15:22:55 -0700 Subject: [PATCH 01/33] feat: plug and play system message tool frameworks --- core/index.d.ts | 5 +- core/tools/definitions/codebaseTool.ts | 12 +- core/tools/definitions/createNewFile.ts | 10 +- core/tools/definitions/createRuleBlock.ts | 10 +- core/tools/definitions/editFile.ts | 10 +- core/tools/definitions/fetchUrlContent.ts | 10 +- core/tools/definitions/globSearch.ts | 10 +- core/tools/definitions/grepSearch.ts | 10 +- core/tools/definitions/ls.ts | 10 +- .../definitions/readCurrentlyOpenFile.ts | 9 +- core/tools/definitions/readFile.ts | 10 +- core/tools/definitions/requestRule.ts | 10 +- core/tools/definitions/runTerminalCommand.ts | 10 +- .../definitions/searchAndReplaceInFile.ts | 10 +- core/tools/definitions/searchWeb.ts | 10 +- core/tools/definitions/viewDiff.ts | 9 +- core/tools/definitions/viewRepoMap.ts | 9 +- core/tools/definitions/viewSubdirectory.ts | 10 +- .../buildToolsSystemMessage.ts | 127 +++--------------- .../systemMessageTools/convertSystemTools.ts | 20 +-- .../systemMessageTools/detectToolCallStart.ts | 19 ++- .../interceptSystemToolCalls.ts | 20 +-- .../systemMessageTools/textifySystemTools.ts | 102 -------------- .../buildSystemMessage.vitest.ts} | 47 ++++--- .../detectToolCallStart.vitest.ts | 20 +-- .../toolCodeblocks/index.ts | 120 +++++++++++++++++ .../interceptSystemToolCalls.vitest.ts | 14 +- .../interceptionTests.vitest.ts | 0 .../parseSystemToolCall.ts | 40 ++---- .../parseSystemToolCall.vitest.ts | 46 ++----- core/tools/systemMessageTools/types.ts | 51 +++++++ gui/src/redux/thunks/streamNormalInput.ts | 18 ++- gui/src/redux/util/constructMessages.ts | 6 +- 33 files changed, 379 insertions(+), 445 deletions(-) delete mode 100644 core/tools/systemMessageTools/textifySystemTools.ts rename core/tools/systemMessageTools/{buildToolsSystemMessage.vitest.ts => toolCodeblocks/buildSystemMessage.vitest.ts} (85%) rename core/tools/systemMessageTools/{ => toolCodeblocks}/detectToolCallStart.vitest.ts (76%) create mode 100644 core/tools/systemMessageTools/toolCodeblocks/index.ts rename core/tools/systemMessageTools/{ => toolCodeblocks}/interceptSystemToolCalls.vitest.ts (96%) create mode 100644 core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts rename core/tools/systemMessageTools/{ => toolCodeblocks}/parseSystemToolCall.ts (79%) rename core/tools/systemMessageTools/{ => toolCodeblocks}/parseSystemToolCall.vitest.ts (87%) create mode 100644 core/tools/systemMessageTools/types.ts diff --git a/core/index.d.ts b/core/index.d.ts index f96cc7716..69fa259e3 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1084,7 +1084,10 @@ export interface Tool { faviconUrl?: string; group: string; originalFunctionName?: string; - systemMessageDescription?: string; + systemMessageDescription?: { + prefix: string; + exampleArgs?: Array<[string, string | number]>; + }; } interface ToolChoice { diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts index 0714a230b..71af43508 100644 --- a/core/tools/definitions/codebaseTool.ts +++ b/core/tools/definitions/codebaseTool.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const codebaseTool: Tool = { type: "function", @@ -27,9 +26,10 @@ export const codebaseTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.CodebaseTool, - `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`, - [["query", "How is user authentication handled in this codebase?"]], - ), + systemMessageDescription: { + prefix: `To search the codebase, use the ${BuiltInToolNames.CodebaseTool} tool with a natural language query. For example, to find authentication logic, you might respond with:`, + exampleArgs: [ + ["query", "How is user authentication handled in this codebase?"], + ], + }, }; diff --git a/core/tools/definitions/createNewFile.ts b/core/tools/definitions/createNewFile.ts index 152af5693..e078bd261 100644 --- a/core/tools/definitions/createNewFile.ts +++ b/core/tools/definitions/createNewFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const createNewFileTool: Tool = { type: "function", @@ -31,12 +30,11 @@ export const createNewFileTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.CreateNewFile, - `To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`, - [ + systemMessageDescription: { + prefix: `To create a NEW file, use the ${BuiltInToolNames.CreateNewFile} tool with the relative filepath and new contents. For example, to create a file located at 'path/to/file.txt', you would respond with:`, + exampleArgs: [ ["filepath", "path/to/the_file.txt"], ["contents", "Contents of the file"], ], - ), + }, }; diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index e6bf6689e..ccfd0ec59 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; const NAME_ARG_DESC = "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')"; @@ -60,9 +59,8 @@ export const createRuleBlock: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.CreateRuleBlock, - `Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions. + systemMessageDescription: { + prefix: `Sometimes the user will provide feedback or guidance on your output. If you were not aware of these "rules", consider using the ${BuiltInToolNames.CreateRuleBlock} tool to persist the rule for future interactions. This tool cannot be used to edit existing rules, but you can search in the ".continue/rules" folder and use the edit tool to manage rules. To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call and the following arguments: - name: ${NAME_ARG_DESC} @@ -71,7 +69,7 @@ To create a rule, respond with a ${BuiltInToolNames.CreateRuleBlock} tool call a - globs: ${GLOB_ARG_DESC} - alwaysApply: ${ALWAYS_APPLY_DESC} For example:`, - [ + exampleArgs: [ ["name", "Use PropTypes"], [ "rule", @@ -84,5 +82,5 @@ For example:`, ["globs", "**/*.js"], ["alwaysApply", "false"], ], - ), + }, }; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 59e20c681..b195d9ab0 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { EDIT_CODE_INSTRUCTIONS } from "../../llm/defaultSystemMessages"; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; import { NO_PARALLEL_TOOL_CALLING_INSRUCTION } from "./searchAndReplaceInFile"; export interface EditToolArgs { @@ -40,19 +39,18 @@ export const editFileTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.EditExistingFile, - `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with + systemMessageDescription: { + prefix: `To edit an EXISTING file, use the ${BuiltInToolNames.EditExistingFile} tool with - filepath: the relative filepath to the file. - changes: ${CHANGES_DESCRIPTION} Only use this tool if you already know the contents of the file. Otherwise, use the ${BuiltInToolNames.ReadFile} or ${BuiltInToolNames.ReadCurrentlyOpenFile} tool to read it first. For example:`, - [ + exampleArgs: [ ["filepath", "path/to/the_file.ts"], [ "changes", "// ... existing code ...\nfunction subtract(a: number, b: number): number {\n return a - b;\n}\n// ... rest of code ...", ], ], - ), + }, }; diff --git a/core/tools/definitions/fetchUrlContent.ts b/core/tools/definitions/fetchUrlContent.ts index ae57fc532..543aaa81a 100644 --- a/core/tools/definitions/fetchUrlContent.ts +++ b/core/tools/definitions/fetchUrlContent.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const fetchUrlContentTool: Tool = { type: "function", @@ -26,9 +25,8 @@ export const fetchUrlContentTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.FetchUrlContent, - `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, - [["url", "https://example.com"]], - ), + systemMessageDescription: { + prefix: `To fetch the content of a URL, use the ${BuiltInToolNames.FetchUrlContent} tool. For example, to read the contents of a webpage, you might respond with:`, + exampleArgs: [["url", "https://example.com"]], + }, }; diff --git a/core/tools/definitions/globSearch.ts b/core/tools/definitions/globSearch.ts index e0f195a66..7fd77e0b2 100644 --- a/core/tools/definitions/globSearch.ts +++ b/core/tools/definitions/globSearch.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const globSearchTool: Tool = { type: "function", @@ -26,9 +25,8 @@ export const globSearchTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.FileGlobSearch, - `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, - [["pattern", "*.py"]], - ), + systemMessageDescription: { + prefix: `To return a list of files based on a glob search pattern, use the ${BuiltInToolNames.FileGlobSearch} tool`, + exampleArgs: [["pattern", "*.py"]], + }, }; diff --git a/core/tools/definitions/grepSearch.ts b/core/tools/definitions/grepSearch.ts index e276d5a8f..b322b5259 100644 --- a/core/tools/definitions/grepSearch.ts +++ b/core/tools/definitions/grepSearch.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const grepSearchTool: Tool = { type: "function", @@ -27,9 +26,8 @@ export const grepSearchTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.GrepSearch, - `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, - [["query", ".*main_services.*"]], - ), + systemMessageDescription: { + prefix: `To perform a grep search within the project, call the ${BuiltInToolNames.GrepSearch} tool with the query pattern to match. For example:`, + exampleArgs: [["query", ".*main_services.*"]], + }, }; diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 97d23f4f6..b96f44cde 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const lsTool: Tool = { type: "function", @@ -31,12 +30,11 @@ export const lsTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.LSTool, - `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`, - [ + systemMessageDescription: { + prefix: `To list files and folders in a given directory, call the ${BuiltInToolNames.LSTool} tool with "dirPath" and "recursive". For example:`, + exampleArgs: [ ["dirPath", "path/to/dir"], ["recursive", "false"], ], - ), + }, }; diff --git a/core/tools/definitions/readCurrentlyOpenFile.ts b/core/tools/definitions/readCurrentlyOpenFile.ts index 3f07f816f..df771b870 100644 --- a/core/tools/definitions/readCurrentlyOpenFile.ts +++ b/core/tools/definitions/readCurrentlyOpenFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readCurrentlyOpenFileTool: Tool = { type: "function", @@ -20,10 +19,8 @@ export const readCurrentlyOpenFileTool: Tool = { properties: {}, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ReadCurrentlyOpenFile, - `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. + systemMessageDescription: { + prefix: `To view the user's currently open file, use the ${BuiltInToolNames.ReadCurrentlyOpenFile} tool. If the user is asking about a file and you don't see any code, use this to check the current file`, - [], - ), + }, }; diff --git a/core/tools/definitions/readFile.ts b/core/tools/definitions/readFile.ts index fb13eba05..bf693bb65 100644 --- a/core/tools/definitions/readFile.ts +++ b/core/tools/definitions/readFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const readFileTool: Tool = { type: "function", @@ -27,9 +26,8 @@ export const readFileTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ReadFile, - `To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`, - [["filepath", "path/to/the_file.txt"]], - ), + systemMessageDescription: { + prefix: `To read a file with a known filepath, use the ${BuiltInToolNames.ReadFile} tool. For example, to read a file located at 'path/to/file.txt', you would respond with this:`, + exampleArgs: [["filepath", "path/to/the_file.txt"]], + }, }; diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts index 4e2f1ef61..00bf8bd2c 100644 --- a/core/tools/definitions/requestRule.ts +++ b/core/tools/definitions/requestRule.ts @@ -1,6 +1,5 @@ import { ConfigDependentToolParams, GetTool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface RequestRuleArgs { name: string; @@ -60,9 +59,8 @@ export const requestRuleTool: GetTool = ({ rules }) => ({ }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.RequestRule, - getRequestRuleSystemMessageDescription(rules), - [["name", "rule_name"]], - ), + systemMessageDescription: { + prefix: getRequestRuleSystemMessageDescription(rules), + exampleArgs: [["name", "rule_name"]], + }, }); diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index 8ab379e1b..09275061c 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -1,7 +1,6 @@ import os from "os"; import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; /** * Get the preferred shell for the current platform @@ -56,12 +55,11 @@ export const runTerminalCommandTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.RunTerminalCommand, - `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool + systemMessageDescription: { + prefix: `To run a terminal command, use the ${BuiltInToolNames.RunTerminalCommand} tool ${RUN_COMMAND_NOTES} You can also optionally include the waitForCompletion argument set to false to run the command in the background. For example, to see the git log, you could respond with:`, - [["command", "git log"]], - ), + exampleArgs: [["command", "git log"]], + }, }; diff --git a/core/tools/definitions/searchAndReplaceInFile.ts b/core/tools/definitions/searchAndReplaceInFile.ts index 96dac65da..c43d96153 100644 --- a/core/tools/definitions/searchAndReplaceInFile.ts +++ b/core/tools/definitions/searchAndReplaceInFile.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export interface SearchAndReplaceInFileArgs { filepath: string; @@ -92,16 +91,15 @@ export const searchAndReplaceInFileTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.SearchAndReplaceInFile, - `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. + systemMessageDescription: { + prefix: `To make targeted edits by replacing sections of content in an existing file, use the ${BuiltInToolNames.SearchAndReplaceInFile} tool with a "diffs" argument containing an array of SEARCH/REPLACE blocks that define exact changes to specific parts of the file. Each block should follow this format: ${SEARCH_AND_REPLACE_EXAMPLE_BLOCK} ${SEARCH_AND_REPLACE_RULES} For example, you could respond with:`, - [ + exampleArgs: [ ["filepath", "path/to/file.ts"], [ "diffs", @@ -119,5 +117,5 @@ ${SEARCH_AND_REPLACE_RULES} ]`, ], ], - ), + }, }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index bcaa743a3..0770b121c 100644 --- a/core/tools/definitions/searchWeb.ts +++ b/core/tools/definitions/searchWeb.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const searchWebTool: Tool = { type: "function", @@ -26,9 +25,8 @@ export const searchWebTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.SearchWeb, - `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, - [["query", "What is the current weather in San Francisco?"]], - ), + systemMessageDescription: { + prefix: `To search the web, use the ${BuiltInToolNames.SearchWeb} tool with a natural language query. For example, to search for the current weather, you would respond with:`, + exampleArgs: [["query", "What is the current weather in San Francisco?"]], + }, }; diff --git a/core/tools/definitions/viewDiff.ts b/core/tools/definitions/viewDiff.ts index bf488f171..e8aaa8dd8 100644 --- a/core/tools/definitions/viewDiff.ts +++ b/core/tools/definitions/viewDiff.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewDiffTool: Tool = { type: "function", @@ -20,9 +19,7 @@ export const viewDiffTool: Tool = { properties: {}, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ViewDiff, - `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, - [], - ), + systemMessageDescription: { + prefix: `To view the current git diff, use the ${BuiltInToolNames.ViewDiff} tool. This will show you the changes made in the working directory compared to the last commit.`, + }, }; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index a58584fc1..17f9dac4c 100644 --- a/core/tools/definitions/viewRepoMap.ts +++ b/core/tools/definitions/viewRepoMap.ts @@ -1,7 +1,6 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewRepoMapTool: Tool = { type: "function", @@ -20,9 +19,7 @@ export const viewRepoMapTool: Tool = { properties: {}, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ViewRepoMap, - `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, - [], - ), + systemMessageDescription: { + prefix: `To view the repository map, use the ${BuiltInToolNames.ViewRepoMap} tool. This will provide a visual representation of the project's structure and organization.`, + }, }; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 11c27a775..08a1c83f7 100644 --- a/core/tools/definitions/viewSubdirectory.ts +++ b/core/tools/definitions/viewSubdirectory.ts @@ -1,6 +1,5 @@ import { Tool } from "../.."; import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; -import { createSystemMessageExampleCall } from "../systemMessageTools/buildToolsSystemMessage"; export const viewSubdirectoryTool: Tool = { type: "function", @@ -26,9 +25,8 @@ export const viewSubdirectoryTool: Tool = { }, }, }, - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.ViewSubdirectory, - `To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`, - [["directory_path", "path/to/subdirectory"]], - ), + systemMessageDescription: { + prefix: `To view a map of a specific folder within the project, you can use the ${BuiltInToolNames.ViewSubdirectory} tool. This will provide a visual representation of the folder's structure and organization.`, + exampleArgs: [["directory_path", "path/to/subdirectory"]], + }, }; diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.ts b/core/tools/systemMessageTools/buildToolsSystemMessage.ts index 8536c794f..750e6bb43 100644 --- a/core/tools/systemMessageTools/buildToolsSystemMessage.ts +++ b/core/tools/systemMessageTools/buildToolsSystemMessage.ts @@ -1,91 +1,13 @@ import { Tool } from "../.."; import { closeTag } from "./systemToolUtils"; +import { SystemMessageToolsFramework } from "./types"; export const TOOL_INSTRUCTIONS_TAG = ""; -export const TOOL_DEFINITION_TAG = "TOOL_DEFINITION"; -export const TOOL_DESCRIPTION_TAG = "DESCRIPTION"; -const EXAMPLE_DYNAMIC_TOOL = ` -\`\`\`tool_definition -TOOL_NAME: example_tool -TOOL_ARG: arg_1 (string, required) -Description of the first argument -END_ARG -TOOL_ARG: arg_2 (number, optional) -END_ARG -\`\`\``.trim(); - -const EXAMPLE_DYNAMIC_TOOL_CALL = ` -\`\`\`tool -TOOL_NAME: example_tool -BEGIN_ARG: arg_1 -The value -of arg 1 -END_ARG -BEGIN_ARG: arg_2 -3 -END_ARG -\`\`\``.trim(); - -export function createSystemMessageExampleCall( - name: string, - instructions: string, - args: Array<[string, string]> = [], -) { - let callExample = `\`\`\`tool -TOOL_NAME: ${name}`; - - // Add each argument dynamically - for (const [argName, argValue] of args) { - callExample += ` -BEGIN_ARG: ${argName} -${argValue} -END_ARG`; - } - - callExample += ` -\`\`\``; - - return `${instructions.trim()} -${callExample}`; -} - -function toolToSystemToolDefinition(tool: Tool): string { - let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`; - - if (tool.function.description) { - toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`; - } - - if (tool.function.parameters && "properties" in tool.function.parameters) { - for (const [key, value] of Object.entries( - tool.function.parameters.properties as object, - )) { - const isRequired = tool.function.parameters.required?.includes(key); - const requiredText = isRequired ? "required" : "optional"; - - let argType = "string"; - if ("type" in value) { - argType = value.type; - } - let argDescription = ""; - if ("description" in value) { - argDescription = value.description; - } - - toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`; - if (argDescription) { - toolDefinition += argDescription + "\n"; - } - toolDefinition += `END_ARG\n`; - } - } - - toolDefinition += `\`\`\``; - return toolDefinition.trim(); -} - -export const generateToolsSystemMessage = (tools: Tool[]): string => { +export const generateToolsSystemMessage = ( + tools: Tool[], + framework: SystemMessageToolsFramework, +): string => { if (tools.length === 0) { return ""; } @@ -99,17 +21,17 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { const instructions: string[] = []; instructions.push(TOOL_INSTRUCTIONS_TAG); - instructions.push( - `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User.`, - ); - instructions.push( - `To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`, - ); + instructions.push(framework.systemMessagePrefix); if (withPredefinedMessage.length > 0) { instructions.push(`\nThe following tools are available to you:`); for (const tool of withPredefinedMessage) { - instructions.push(`\n${tool.systemMessageDescription}`); + const definition = framework.createSystemMessageExampleCall( + tool.function.name, + tool.systemMessageDescription!.prefix, + tool.systemMessageDescription!.exampleArgs, + ); + instructions.push(`\n${definition}`); } } @@ -120,7 +42,7 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { for (const tool of tools) { try { - const definition = toolToSystemToolDefinition(tool); + const definition = framework.toolToSystemToolDefinition(tool); instructions.push(`\n${definition}`); } catch (e) { console.error( @@ -131,35 +53,28 @@ export const generateToolsSystemMessage = (tools: Tool[]): string => { } instructions.push(`\nFor example, this tool definition:\n`); - instructions.push(EXAMPLE_DYNAMIC_TOOL); + instructions.push(framework.exampleDynamicToolDefinition); instructions.push("\nCan be called like this:\n"); - instructions.push(EXAMPLE_DYNAMIC_TOOL_CALL); + instructions.push(framework.exampleDynamicToolCall); } - instructions.push( - `\nIf it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions`, - ); - instructions.push( - `Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line.`, - ); - instructions.push( - `Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant.`, - ); - instructions.push( - `You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`, - ); + instructions.push("\n" + framework.systemMessageSuffix); instructions.push(`${closeTag(TOOL_INSTRUCTIONS_TAG)}`); return instructions.join("\n"); }; export function addSystemMessageToolsToSystemMessage( + framework: SystemMessageToolsFramework, baseSystemMessage: string, systemMessageTools: Tool[], ): string { let systemMessage = baseSystemMessage; if (systemMessageTools.length > 0) { - const toolsSystemMessage = generateToolsSystemMessage(systemMessageTools); + const toolsSystemMessage = generateToolsSystemMessage( + systemMessageTools, + framework, + ); systemMessage += `\n\n${toolsSystemMessage}`; } diff --git a/core/tools/systemMessageTools/convertSystemTools.ts b/core/tools/systemMessageTools/convertSystemTools.ts index 4517915d0..5002bfcdd 100644 --- a/core/tools/systemMessageTools/convertSystemTools.ts +++ b/core/tools/systemMessageTools/convertSystemTools.ts @@ -12,22 +12,7 @@ import { CANCELLED_TOOL_CALL_MESSAGE, NO_TOOL_CALL_OUTPUT_MESSAGE, } from "../constants"; -function toolCallStateToSystemToolCall(state: ToolCallState): string { - let parts = ["```tool"]; - parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); - try { - for (const arg in state.parsedArgs) { - parts.push(`BEGIN_ARG: ${arg}`); - parts.push(JSON.stringify(state.parsedArgs[arg])); - parts.push(`END_ARG`); - } - } catch (e) { - console.log("Failed to stringify json args", state.parsedArgs); - } - // TODO - include tool call id for parallel. Confuses dumb models - parts.push("```"); - return parts.join("\n"); -} +import { SystemMessageToolsFramework } from "./types"; function toolCallStateToSystemToolOutput(state: ToolCallState): string { let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; @@ -46,6 +31,7 @@ function toolCallStateToSystemToolOutput(state: ToolCallState): string { export function convertToolCallStatesToSystemCallsAndOutput( originalAssistantMessage: AssistantChatMessage, toolCallStates: ToolCallState[], + framework: SystemMessageToolsFramework, ): { assistantMessage: AssistantChatMessage; userMessage: UserChatMessage; @@ -55,7 +41,7 @@ export function convertToolCallStatesToSystemCallsAndOutput( parts.push( ...toolCallStates.map((state) => ({ type: "text" as const, - text: toolCallStateToSystemToolCall(state), + text: framework.toolCallStateToSystemToolCall(state), })), ); } diff --git a/core/tools/systemMessageTools/detectToolCallStart.ts b/core/tools/systemMessageTools/detectToolCallStart.ts index f99ce03d5..e143411dd 100644 --- a/core/tools/systemMessageTools/detectToolCallStart.ts +++ b/core/tools/systemMessageTools/detectToolCallStart.ts @@ -1,19 +1,16 @@ -let boundaryTypeIndex = 0; +import { SystemMessageToolsFramework } from "./types"; -// Poor models are really bad at following instructions -// Give some leeway in how the initiate -const acceptedToolStarts: [string, string][] = [ - ["```tool\n", "```tool\n"], - ["tool_name:", "```tool\nTOOL_NAME:"], -]; - -export function detectToolCallStart(buffer: string) { +export function detectToolCallStart( + buffer: string, + toolCallFramework: SystemMessageToolsFramework, +) { + const starts = toolCallFramework.acceptedToolCallStarts; let modifiedBuffer = buffer; let isInToolCall = false; let isInPartialStart = false; const lowerCaseBuffer = buffer.toLowerCase(); - for (let i = 0; i < acceptedToolStarts.length; i++) { - const [start, replacement] = acceptedToolStarts[i]; + for (let i = 0; i < starts.length; i++) { + const [start, replacement] = starts[i]; if (lowerCaseBuffer.startsWith(start)) { // for non-standard cases like no ```tool codeblock, etc, replace before adding to buffer, case insensitive if (i !== 0) { diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.ts b/core/tools/systemMessageTools/interceptSystemToolCalls.ts index 31fb562bf..a89fbdcfb 100644 --- a/core/tools/systemMessageTools/interceptSystemToolCalls.ts +++ b/core/tools/systemMessageTools/interceptSystemToolCalls.ts @@ -1,12 +1,12 @@ import { ChatMessage, PromptLog, TextMessagePart } from "../.."; import { normalizeToMessageParts } from "../../util/messageContent"; import { detectToolCallStart } from "./detectToolCallStart"; -import { - getInitialTooLCallParseState, - handleToolCallBuffer, - ToolCallParseState, -} from "./parseSystemToolCall"; import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils"; +import { + getInitialToolCallParseState, + SystemMessageToolsFramework, + ToolCallParseState, +} from "./types"; /* Function to intercept tool calls in markdown code blocks format from a chat message stream @@ -24,6 +24,7 @@ import { createDelta, splitAtCodeblocksAndNewLines } from "./systemToolUtils"; export async function* interceptSystemToolCalls( messageGenerator: AsyncGenerator, abortController: AbortController, + systemToolFramework: SystemMessageToolsFramework, ): AsyncGenerator { let buffer = ""; let parseState: ToolCallParseState | undefined; @@ -70,19 +71,22 @@ export async function* interceptSystemToolCalls( buffer += chunk; if (!parseState) { const { isInPartialStart, isInToolCall, modifiedBuffer } = - detectToolCallStart(buffer); + detectToolCallStart(buffer, systemToolFramework); if (isInPartialStart) { continue; } if (isInToolCall) { - parseState = getInitialTooLCallParseState(); + parseState = getInitialToolCallParseState(); buffer = modifiedBuffer; } } if (parseState && !parseState.done) { - const delta = handleToolCallBuffer(buffer, parseState); + const delta = systemToolFramework.handleToolCallBuffer( + buffer, + parseState, + ); if (delta) { yield [ { diff --git a/core/tools/systemMessageTools/textifySystemTools.ts b/core/tools/systemMessageTools/textifySystemTools.ts deleted file mode 100644 index f654037df..000000000 --- a/core/tools/systemMessageTools/textifySystemTools.ts +++ /dev/null @@ -1,102 +0,0 @@ -import { - AssistantChatMessage, - MessagePart, - ToolCallState, - UserChatMessage, -} from "../.."; -import { - normalizeToMessageParts, - renderContextItems, -} from "../../util/messageContent"; -import { - CANCELLED_TOOL_CALL_MESSAGE, - NO_TOOL_CALL_OUTPUT_MESSAGE, -} from "../constants"; -function toolCallStateToSystemToolCall(state: ToolCallState): string { - let parts = ["```tool"]; - parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); - try { - for (const arg in state.parsedArgs) { - parts.push(`BEGIN_ARG: ${arg}`); - parts.push(JSON.stringify(state.parsedArgs[arg])); - parts.push(`END_ARG`); - } - } catch (e) { - console.log("Failed to stringify json args", state.parsedArgs); - } - // TODO - include tool call id for parallel. Confuses dumb models - parts.push("```"); - return parts.join("\n"); -} - -function toolCallStateToSystemToolOutput(state: ToolCallState): string { - let output = `Tool output for ${state.toolCall.function.name} tool call:\n\n`; - // TODO - include tool call id for parallel. Confuses dumb models - // let output = `Tool output for tool call ${state.toolCallId} (${state.toolCall.function.name}):\n\n`; - if (state.status === "canceled") { - output += CANCELLED_TOOL_CALL_MESSAGE; - } else if (state.output?.length) { - output += renderContextItems(state.output); - } else { - output += NO_TOOL_CALL_OUTPUT_MESSAGE; - } - return output; -} - -export function convertToolCallStatesToSystemCallsAndOutput( - originalAssistantMessage: AssistantChatMessage, - toolCallStates: ToolCallState[], -): { - assistantMessage: AssistantChatMessage; - userMessage: UserChatMessage; -} { - const assistantParts = normalizeToMessageParts(originalAssistantMessage); - if (originalAssistantMessage.toolCalls) { - assistantParts.push( - ...toolCallStates.map((state) => ({ - type: "text" as const, - text: toolCallStateToSystemToolCall(state), - })), - ); - } - - const userParts: MessagePart[] = []; - if (toolCallStates) { - for (const state of toolCallStates) { - userParts.push({ - type: "text", - text: toolCallStateToSystemToolOutput(state), - }); - } - } - if (userParts.length === 0) { - userParts.push({ - type: "text", - text: "No tool output for tool calls", - }); - } - - const nonEmptyAssistantParts = assistantParts.filter( - (p) => p.type !== "text" || !!p.text, - ); - const nonEmptyUserParts = userParts.filter( - (p) => p.type !== "text" || !!p.text, - ); - - // new message with tool calls moved to content - const assistantMessage: AssistantChatMessage = { - ...originalAssistantMessage, - content: nonEmptyAssistantParts, - toolCalls: undefined, // remove tool calls from the assistant message - }; - - const userMessage: UserChatMessage = { - role: "user", - content: nonEmptyUserParts, - }; - - return { - assistantMessage, - userMessage, - }; -} diff --git a/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts similarity index 85% rename from core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts index 70215c477..669d1c103 100644 --- a/core/tools/systemMessageTools/buildToolsSystemMessage.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/buildSystemMessage.vitest.ts @@ -1,12 +1,13 @@ import { describe, expect, it } from "vitest"; -import { Tool } from "../.."; +import { Tool } from "../../.."; import { TOOL_INSTRUCTIONS_TAG, addSystemMessageToolsToSystemMessage, - createSystemMessageExampleCall, generateToolsSystemMessage, -} from "./buildToolsSystemMessage"; -import { closeTag } from "./systemToolUtils"; +} from "../buildToolsSystemMessage"; + +import { SystemMessageToolCodeblocksFramework } from "."; +import { closeTag } from "../systemToolUtils"; const SHARED_TOOL_FIELDS = { displayTitle: "DUD", @@ -15,9 +16,11 @@ const SHARED_TOOL_FIELDS = { type: "function" as const, }; +const framework = new SystemMessageToolCodeblocksFramework(); + describe("createSystemMessageExampleCall", () => { it("creates a system message example call with no args", () => { - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", ); @@ -28,7 +31,7 @@ describe("createSystemMessageExampleCall", () => { }); it("creates a system message example call with args", () => { - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", [ @@ -49,7 +52,7 @@ describe("createSystemMessageExampleCall", () => { it("handles multiline arg values correctly", () => { const multilineValue = "value\nwith\nmultiple\nlines"; - const result = createSystemMessageExampleCall( + const result = framework.createSystemMessageExampleCall( "test_tool", "Use this tool to test things", [["arg1", multilineValue]], @@ -63,7 +66,7 @@ describe("createSystemMessageExampleCall", () => { describe("generateToolsSystemMessage", () => { it("returns empty string for empty tools array", () => { - const result = generateToolsSystemMessage([]); + const result = generateToolsSystemMessage([], framework); expect(result).toBe(""); }); @@ -81,12 +84,14 @@ describe("generateToolsSystemMessage", () => { required: [], }, }, - systemMessageDescription: customDescription, + systemMessageDescription: { + prefix: customDescription, + }, ...SHARED_TOOL_FIELDS, }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check structure rather than exact text expect(result).includes(TOOL_INSTRUCTIONS_TAG); @@ -123,7 +128,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for key elements without requiring exact wording expect(result).includes(`TOOL_NAME: ${toolName}`); @@ -150,7 +155,9 @@ describe("generateToolsSystemMessage", () => { required: [], }, }, - systemMessageDescription: customMsg, + systemMessageDescription: { + prefix: customMsg, + }, ...SHARED_TOOL_FIELDS, }, { @@ -172,7 +179,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for both types of tools expect(result).includes(customMsg); @@ -202,7 +209,7 @@ describe("generateToolsSystemMessage", () => { }, ]; - const result = generateToolsSystemMessage(tools); + const result = generateToolsSystemMessage(tools, framework); // Check for example sections without exact text expect(result).includes("```tool_definition"); @@ -221,7 +228,11 @@ describe("generateToolsSystemMessage", () => { describe("addSystemMessageToolsToSystemMessage", () => { it("returns original system message when no tools are provided", () => { const baseMessage = "This is the base system message"; - const result = addSystemMessageToolsToSystemMessage(baseMessage, []); + const result = addSystemMessageToolsToSystemMessage( + framework, + baseMessage, + [], + ); expect(result).toBe(baseMessage); }); @@ -243,7 +254,11 @@ describe("addSystemMessageToolsToSystemMessage", () => { }, ]; - const result = addSystemMessageToolsToSystemMessage(baseMessage, tools); + const result = addSystemMessageToolsToSystemMessage( + framework, + baseMessage, + tools, + ); expect(result.startsWith(baseMessage)).toBe(true); expect(result).includes(TOOL_INSTRUCTIONS_TAG); diff --git a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts similarity index 76% rename from core/tools/systemMessageTools/detectToolCallStart.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts index 715113475..297c58ec4 100644 --- a/core/tools/systemMessageTools/detectToolCallStart.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/detectToolCallStart.vitest.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from "vitest"; -import { detectToolCallStart } from "./detectToolCallStart"; +import { SystemMessageToolCodeblocksFramework } from "."; +import { detectToolCallStart } from "../detectToolCallStart"; describe("detectToolCallStart", () => { + let framework = new SystemMessageToolCodeblocksFramework(); it("detects standard tool call start", () => { const buffer = "```tool\nTOOL_NAME: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -13,7 +15,7 @@ describe("detectToolCallStart", () => { it("detects tool_name start without codeblock", () => { const buffer = "tool_name: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -22,7 +24,7 @@ describe("detectToolCallStart", () => { it("detects case-insensitive tool call start", () => { const buffer = "```ToOl\nTOOL_NAME: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -31,7 +33,7 @@ describe("detectToolCallStart", () => { it("detects case-insensitive tool_name start", () => { const buffer = "ToOl_NaMe: example_tool"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(true); expect(result.isInPartialStart).toBe(false); @@ -40,7 +42,7 @@ describe("detectToolCallStart", () => { it("identifies partial tool call start", () => { const buffer = "```to"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(true); @@ -49,7 +51,7 @@ describe("detectToolCallStart", () => { it("identifies partial tool_name start", () => { const buffer = "tool_na"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(true); @@ -58,7 +60,7 @@ describe("detectToolCallStart", () => { it("does not detect tool call in unrelated text", () => { const buffer = "This is some regular text."; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(false); @@ -67,7 +69,7 @@ describe("detectToolCallStart", () => { it("does not detect tool call in similar but different markdown block", () => { const buffer = "```javascript\nconst x = 10;"; - const result = detectToolCallStart(buffer); + const result = detectToolCallStart(buffer, framework); expect(result.isInToolCall).toBe(false); expect(result.isInPartialStart).toBe(false); diff --git a/core/tools/systemMessageTools/toolCodeblocks/index.ts b/core/tools/systemMessageTools/toolCodeblocks/index.ts new file mode 100644 index 000000000..97baa19fa --- /dev/null +++ b/core/tools/systemMessageTools/toolCodeblocks/index.ts @@ -0,0 +1,120 @@ +import { Tool, ToolCallState } from "../../.."; +import { SystemMessageToolsFramework } from "../types"; +import { handleToolCallBuffer } from "./parseSystemToolCall"; + +export class SystemMessageToolCodeblocksFramework + implements SystemMessageToolsFramework +{ + // Poor models are really bad at following instructions, alternate starts allowed: + acceptedToolCallStarts: [string, string][] = [ + ["```tool\n", "```tool\n"], + ["tool_name:", "```tool\nTOOL_NAME:"], + ]; + + toolCallStateToSystemToolCall(state: ToolCallState): string { + let parts = ["```tool"]; + parts.push(`TOOL_NAME: ${state.toolCall.function.name}`); + try { + for (const arg in state.parsedArgs) { + parts.push(`BEGIN_ARG: ${arg}`); + parts.push(JSON.stringify(state.parsedArgs[arg])); + parts.push(`END_ARG`); + } + } catch (e) { + console.log("Failed to stringify json args", state.parsedArgs); + } + // TODO - include tool call id for parallel. Confuses dumb models + parts.push("```"); + return parts.join("\n"); + } + + handleToolCallBuffer = handleToolCallBuffer; + + toolToSystemToolDefinition(tool: Tool): string { + let toolDefinition = `\`\`\`tool_definition\nTOOL_NAME: ${tool.function.name}\n`; + + if (tool.function.description) { + toolDefinition += `TOOL_DESCRIPTION:\n${tool.function.description}\n`; + } + + if (tool.function.parameters && "properties" in tool.function.parameters) { + for (const [key, value] of Object.entries( + tool.function.parameters.properties as object, + )) { + const isRequired = tool.function.parameters.required?.includes(key); + const requiredText = isRequired ? "required" : "optional"; + + let argType = "string"; + if ("type" in value) { + argType = value.type; + } + let argDescription = ""; + if ("description" in value) { + argDescription = value.description; + } + + toolDefinition += `TOOL_ARG: ${key} (${argType}, ${requiredText})\n`; + if (argDescription) { + toolDefinition += argDescription + "\n"; + } + toolDefinition += `END_ARG\n`; + } + } + + toolDefinition += `\`\`\``; + return toolDefinition.trim(); + } + + systemMessagePrefix = `You have access to several "tools" that you can use at any time to retrieve information and/or perform tasks for the User. +To use a tool, respond with a tool code block (\`\`\`tool) using the syntax shown in the examples below:`; + + systemMessageSuffix = `If it seems like the User's request could be solved with one of the tools, choose the BEST one for the job based on the user's request and the tool descriptions +Then send the \`\`\`tool codeblock (YOU call the tool, not the user). Always start the codeblock on a new line. +Do not perform actions with/for hypothetical files. Ask the user or use tools to deduce which files are relevant. +You can only call ONE tool at at time. The tool codeblock should be the last thing you say; stop your response after the tool codeblock.`; + + exampleDynamicToolDefinition = ` +\`\`\`tool_definition +TOOL_NAME: example_tool +TOOL_ARG: arg_1 (string, required) +Description of the first argument +END_ARG +TOOL_ARG: arg_2 (number, optional) +END_ARG +\`\`\``.trim(); + + exampleDynamicToolCall = ` +\`\`\`tool +TOOL_NAME: example_tool +BEGIN_ARG: arg_1 +The value +of arg 1 +END_ARG +BEGIN_ARG: arg_2 +3 +END_ARG +\`\`\``.trim(); + + createSystemMessageExampleCall( + toolName: string, + prefix: string, + exampleArgs: Array<[string, string | number]> = [], + ) { + let callExample = `\`\`\`tool +TOOL_NAME: ${toolName}`; + + // Add each argument dynamically + for (const [argName, argValue] of exampleArgs) { + callExample += ` +BEGIN_ARG: ${argName} +${argValue} +END_ARG`; + } + + callExample += ` +\`\`\``; + + return `${prefix.trim()} +${callExample}`; + } +} diff --git a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts similarity index 96% rename from core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts index 756125bd4..a636cc6a9 100644 --- a/core/tools/systemMessageTools/interceptSystemToolCalls.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/interceptSystemToolCalls.vitest.ts @@ -1,9 +1,11 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { AssistantChatMessage, ChatMessage, PromptLog } from "../.."; -import { interceptSystemToolCalls } from "./interceptSystemToolCalls"; +import { SystemMessageToolCodeblocksFramework } from "."; +import { AssistantChatMessage, ChatMessage, PromptLog } from "../../.."; +import { interceptSystemToolCalls } from "../interceptSystemToolCalls"; describe("interceptSystemToolCalls", () => { let abortController: AbortController; + let framework = new SystemMessageToolCodeblocksFramework(); beforeEach(() => { abortController = new AbortController(); @@ -27,6 +29,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); let result = await generator.next(); @@ -64,6 +67,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); const result = await generator.next(); @@ -91,6 +95,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); const result = await generator.next(); @@ -116,6 +121,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // First chunk should be normal text @@ -185,6 +191,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // First chunk should be normal text @@ -249,6 +256,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); let result; @@ -271,6 +279,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // Process the first part @@ -300,6 +309,7 @@ describe("interceptSystemToolCalls", () => { const generator = interceptSystemToolCalls( createAsyncGenerator(messages), abortController, + framework, ); // Skip to number arg end diff --git a/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts new file mode 100644 index 000000000..e69de29bb diff --git a/core/tools/systemMessageTools/parseSystemToolCall.ts b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts similarity index 79% rename from core/tools/systemMessageTools/parseSystemToolCall.ts rename to core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts index 0300654d9..acba31727 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.ts @@ -1,34 +1,12 @@ -import { ToolCallDelta } from "../.."; -import { createDelta, generateOpenAIToolCallId } from "./systemToolUtils"; - -export type ToolCallParseState = { - toolCallId: string; - isOnArgBeginLine: boolean; - currentArgName: string | undefined; - currentArgLines: string[]; - processedArgNames: Set; - currentLineIndex: number; - lineChunks: string[][]; - done: boolean; -}; - -export const getInitialTooLCallParseState = (): ToolCallParseState => ({ - toolCallId: generateOpenAIToolCallId(), - isOnArgBeginLine: false, - currentArgName: undefined, - currentArgLines: [], - currentLineIndex: 0, - processedArgNames: new Set(), - lineChunks: [], - done: false, -}); +import { ToolCallDelta } from "../../.."; +import { createDelta } from "../systemToolUtils"; +import { ToolCallParseState } from "../types"; /* Efficiently applies chunks to a tool call state as they come in Expects chunks to be broken so that new lines and codeblocks are alone For now, this parser collects entire arg before This is because support for JSON booleans is tricky otherwise - */ export function handleToolCallBuffer( chunk: string, @@ -72,14 +50,14 @@ export function handleToolCallBuffer( } return; default: - if (state.isOnArgBeginLine) { + if (state.isWithinArgStart) { if (isNewLine) { const argName = (line.split(/begin_?arg:/i)[1] ?? "").trim(); if (!argName) { throw new Error("Invalid begin arg line"); } state.currentArgName = argName; - state.isOnArgBeginLine = false; + state.isWithinArgStart = false; const argPrefix = state.processedArgNames.size === 0 ? "{" : ","; return createDelta("", `${argPrefix}"${argName}":`, state.toolCallId); } @@ -87,8 +65,8 @@ export function handleToolCallBuffer( if (isNewLine) { const isEndArgTag = line.match(/end_?arg/i); if (isEndArgTag) { - let trimmedValue = state.currentArgLines.join("").trim(); - state.currentArgLines.length = 0; + let trimmedValue = state.currentArgChunks.join("").trim(); + state.currentArgChunks.length = 0; state.processedArgNames.add(state.currentArgName); state.currentArgName = undefined; @@ -120,14 +98,14 @@ export function handleToolCallBuffer( return createDelta("", stringifiedArg, state.toolCallId); } } else { - state.currentArgLines.push(line); + state.currentArgChunks.push(line); } } } else { // Check for entry into arg const isBeginArgLine = line.match(/begin_?arg:/i); if (isBeginArgLine) { - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; } // Check for exit diff --git a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts similarity index 87% rename from core/tools/systemMessageTools/parseSystemToolCall.vitest.ts rename to core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts index 2aeac2ce8..95fae25b6 100644 --- a/core/tools/systemMessageTools/parseSystemToolCall.vitest.ts +++ b/core/tools/systemMessageTools/toolCodeblocks/parseSystemToolCall.vitest.ts @@ -1,32 +1,12 @@ import { beforeEach, describe, expect, it } from "vitest"; -import { - ToolCallParseState, - getInitialTooLCallParseState, - handleToolCallBuffer, -} from "./parseSystemToolCall"; - -describe("getInitialTooLCallParseState", () => { - it("returns a properly initialized parse state", () => { - const state = getInitialTooLCallParseState(); - - expect(state).toEqual({ - isOnArgBeginLine: false, - currentArgName: undefined, - currentArgLines: [], - currentLineIndex: 0, - processedArgNames: new Set(), - lineChunks: [], - done: false, - toolCallId: expect.any(String), - }); - }); -}); +import { getInitialToolCallParseState, ToolCallParseState } from "../types"; +import { handleToolCallBuffer } from "./parseSystemToolCall"; describe("handleToolCallBuffer", () => { let state: ToolCallParseState; beforeEach(() => { - state = getInitialTooLCallParseState(); + state = getInitialToolCallParseState(); }); it("handles the ```tool\ntool_name the name", () => { @@ -88,7 +68,7 @@ describe("handleToolCallBuffer", () => { const result = handleToolCallBuffer("BEGIN_ARG: test_arg", state); expect(result).toBeUndefined(); - expect(state.isOnArgBeginLine).toBe(true); + expect(state.isWithinArgStart).toBe(true); const newLineResult = handleToolCallBuffer("\n", state); @@ -101,7 +81,7 @@ describe("handleToolCallBuffer", () => { id: expect.any(String), }); expect(state.currentArgName).toBe("test_arg"); - expect(state.isOnArgBeginLine).toBe(false); + expect(state.isWithinArgStart).toBe(false); }); it("handles case-insensitive begin arg", () => { @@ -109,7 +89,7 @@ describe("handleToolCallBuffer", () => { const result = handleToolCallBuffer("begin_arg: test_arg", state); expect(result).toBeUndefined(); - expect(state.isOnArgBeginLine).toBe(true); + expect(state.isWithinArgStart).toBe(true); const newLineResult = handleToolCallBuffer("\n", state); @@ -135,13 +115,13 @@ describe("handleToolCallBuffer", () => { const newLineResult2 = handleToolCallBuffer("\n", state); expect(newLineResult2).toBeUndefined(); - expect(state.currentArgLines).toEqual(["line 1\n", "line 2\n"]); + expect(state.currentArgChunks).toEqual(["line 1\n", "line 2\n"]); }); it("ends an argument correctly with string value", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = ["string value"]; + state.currentArgChunks = ["string value"]; const result = handleToolCallBuffer("END_ARG", state); expect(result).toBeUndefined(); @@ -163,7 +143,7 @@ describe("handleToolCallBuffer", () => { it("handles case-insensitive end arg", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = ["string value"]; + state.currentArgChunks = ["string value"]; const result = handleToolCallBuffer("end_arg", state); expect(result).toBeUndefined(); @@ -183,7 +163,7 @@ describe("handleToolCallBuffer", () => { it("attempts to parse JSON values", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = ["123"]; + state.currentArgChunks = ["123"]; handleToolCallBuffer("END_ARG", state); const newLineResult = handleToolCallBuffer("\n", state); @@ -201,7 +181,7 @@ describe("handleToolCallBuffer", () => { it("handles multiple arguments", () => { // Setup first arg state.currentLineIndex = 2; - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; state.lineChunks[2] = ["BEGIN_ARG: first_arg"]; handleToolCallBuffer("\n", state); @@ -213,7 +193,7 @@ describe("handleToolCallBuffer", () => { expect(state.processedArgNames.has("first_arg")).toBe(true); // Setup second arg - state.isOnArgBeginLine = true; + state.isWithinArgStart = true; handleToolCallBuffer("BEGIN_ARG: second_arg", state); handleToolCallBuffer("\n", state); handleToolCallBuffer("value2", state); @@ -270,7 +250,7 @@ describe("handleToolCallBuffer", () => { it("handles JSON array args", () => { state.currentLineIndex = 3; state.currentArgName = "test_arg"; - state.currentArgLines = [ + state.currentArgChunks = [ "[\n", '"------- SEARCH\n', " subtract(number) {\n", diff --git a/core/tools/systemMessageTools/types.ts b/core/tools/systemMessageTools/types.ts new file mode 100644 index 000000000..22496a7d9 --- /dev/null +++ b/core/tools/systemMessageTools/types.ts @@ -0,0 +1,51 @@ +import { Tool, ToolCallDelta, ToolCallState } from "../.."; +import { generateOpenAIToolCallId } from "./systemToolUtils"; + +export interface SystemMessageToolsFramework { + acceptedToolCallStarts: [string, string][]; + + toolCallStateToSystemToolCall(state: ToolCallState): string; + + handleToolCallBuffer( + chunk: string, + state: ToolCallParseState, + ): ToolCallDelta | undefined; + + toolToSystemToolDefinition: (tool: Tool) => string; + + systemMessagePrefix: string; + + systemMessageSuffix: string; + + exampleDynamicToolDefinition: string; + + exampleDynamicToolCall: string; + + createSystemMessageExampleCall( + toolName: string, + prefix: string, + exampleArgs?: Array<[string, string | number]>, + ): string; +} + +export type ToolCallParseState = { + toolCallId: string; + isWithinArgStart: boolean; + currentArgName: string | undefined; + currentArgChunks: string[]; + processedArgNames: Set; + currentLineIndex: number; + lineChunks: string[][]; + done: boolean; +}; + +export const getInitialToolCallParseState = (): ToolCallParseState => ({ + toolCallId: generateOpenAIToolCallId(), + isWithinArgStart: false, + currentArgName: undefined, + currentArgChunks: [], + currentLineIndex: 0, + processedArgNames: new Set(), + lineChunks: [], + done: false, +}); diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index fbff48d23..1bab0f04f 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -24,6 +24,7 @@ import { constructMessages } from "../util/constructMessages"; import { modelSupportsNativeTools } from "core/llm/toolSupport"; import { addSystemMessageToolsToSystemMessage } from "core/tools/systemMessageTools/buildToolsSystemMessage"; import { interceptSystemToolCalls } from "core/tools/systemMessageTools/interceptSystemToolCalls"; +import { SystemMessageToolCodeblocksFramework } from "core/tools/systemMessageTools/toolCodeblocks"; import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; import { callToolById } from "./callToolById"; @@ -146,6 +147,9 @@ export const streamNormalInput = createAsyncThunk< // Use the centralized selector to determine if system message tools should be used const useSystemTools = selectUseSystemMessageTools(state); const useNativeTools = !useSystemTools && supportsNativeTools; + const systemToolsFramework = useSystemTools + ? new SystemMessageToolCodeblocksFramework() + : undefined; // Construct completion options let completionOptions: LLMFullCompletionOptions = {}; @@ -170,8 +174,12 @@ export const streamNormalInput = createAsyncThunk< selectedChatModel, ); - const systemMessage = useSystemTools - ? addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools) + const systemMessage = systemToolsFramework + ? addSystemMessageToolsToSystemMessage( + systemToolsFramework, + baseSystemMessage, + activeTools, + ) : baseSystemMessage; const withoutMessageIds = state.session.history.map((item) => { @@ -184,7 +192,7 @@ export const streamNormalInput = createAsyncThunk< systemMessage, state.config.config.rules, state.ui.ruleSettings, - !useNativeTools, + systemToolsFramework, ); // TODO parallel tool calls will cause issues with this @@ -232,8 +240,8 @@ export const streamNormalInput = createAsyncThunk< }, streamAborter.signal, ); - if (!useNativeTools && activeTools.length > 0) { - gen = interceptSystemToolCalls(gen, streamAborter); + if (systemToolsFramework && activeTools.length > 0) { + gen = interceptSystemToolCalls(gen, streamAborter, systemToolsFramework); } let next = await gen.next(); diff --git a/gui/src/redux/util/constructMessages.ts b/gui/src/redux/util/constructMessages.ts index ac70bdafa..f75eb8b49 100644 --- a/gui/src/redux/util/constructMessages.ts +++ b/gui/src/redux/util/constructMessages.ts @@ -15,6 +15,7 @@ import { NO_TOOL_CALL_OUTPUT_MESSAGE, } from "core/tools/constants"; import { convertToolCallStatesToSystemCallsAndOutput } from "core/tools/systemMessageTools/convertSystemTools"; +import { SystemMessageToolsFramework } from "core/tools/systemMessageTools/types"; import { findLast, findLastIndex } from "core/util/findLast"; import { normalizeToMessageParts, @@ -30,7 +31,7 @@ export function constructMessages( baseSystemMessage: string | undefined, availableRules: RuleWithSource[], rulePolicies: RulePolicies, - useSystemMessageTools?: boolean, + useSystemToolsFramework?: SystemMessageToolsFramework, ): { messages: ChatMessage[]; appliedRules: RuleWithSource[]; @@ -95,11 +96,12 @@ export function constructMessages( }); } else if (item.message.role === "assistant") { // When using system message tools, convert tool calls/states to text content - if (item.toolCallStates?.length && useSystemMessageTools) { + if (item.toolCallStates?.length && useSystemToolsFramework) { const { userMessage, assistantMessage } = convertToolCallStatesToSystemCallsAndOutput( item.message, item.toolCallStates ?? [], + useSystemToolsFramework, ); msgs.push({ message: assistantMessage, From 031179ecf7107e4cbd0ae319415cad80c46ad83a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 29 Jul 2025 15:31:57 -0700 Subject: [PATCH 02/33] fix: remove blank test file --- .../systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts diff --git a/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts b/core/tools/systemMessageTools/toolCodeblocks/interceptionTests.vitest.ts deleted file mode 100644 index e69de29bb..000000000 From b821fb2448f07ae930e1bba7fa505e7d1217a110 Mon Sep 17 00:00:00 2001 From: vldf Date: Wed, 6 Aug 2025 12:19:47 +0300 Subject: [PATCH 03/33] Feat: disable edit prompt action for the init prompt --- .../components/mainInput/Lump/sections/PromptsSection.tsx | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 10fb767b3..beb4b87e7 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -60,6 +60,9 @@ function PromptRow({ } }; + const canEdit = + prompt.promptFile && !prompt.promptFile.startsWith("builtin:"); + return (
Date: Thu, 7 Aug 2025 02:21:01 +0800 Subject: [PATCH 04/33] fix: fix tool execute abnormal when there is no tool policy data in the local cache --- extensions/vscode/e2e/tests/GUI.test.ts | 1 - gui/src/redux/thunks/callToolById.ts | 9 ++++--- gui/src/redux/thunks/streamNormalInput.ts | 33 +++++++++++++++-------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/extensions/vscode/e2e/tests/GUI.test.ts b/extensions/vscode/e2e/tests/GUI.test.ts index 421e17772..589e37ff4 100644 --- a/extensions/vscode/e2e/tests/GUI.test.ts +++ b/extensions/vscode/e2e/tests/GUI.test.ts @@ -287,7 +287,6 @@ describe("GUI Test", () => { }).timeout(DEFAULT_TIMEOUT.MD); it("should render tool call", async () => { - await GUIActions.toggleToolPolicy(view, "view_diff", 0); const [messageInput] = await GUISelectors.getMessageInputFields(view); await messageInput.sendKeys("Hello"); await messageInput.sendKeys(Key.ENTER); diff --git a/gui/src/redux/thunks/callToolById.ts b/gui/src/redux/thunks/callToolById.ts index 468838ec6..32898f30e 100644 --- a/gui/src/redux/thunks/callToolById.ts +++ b/gui/src/redux/thunks/callToolById.ts @@ -14,6 +14,7 @@ import { import { ThunkApiType } from "../store"; import { findToolCallById, logToolUsage } from "../util"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; +import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; export const callToolById = createAsyncThunk< void, @@ -36,9 +37,11 @@ export const callToolById = createAsyncThunk< // Check if this is an auto-approved tool const toolSettings = state.ui.toolSettings; - const isAutoApproved = - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission"; + const toolPolicy = + toolSettings[toolCallState.toolCall.function.name] ?? + toolCallState.tool?.defaultToolPolicy ?? + DEFAULT_TOOL_SETTING; + const isAutoApproved = toolPolicy === "allowedWithoutPermission"; posthog.capture("gui_tool_call_decision", { decision: isAutoApproved ? "auto_accept" : "accept", diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 6e3939a5b..769f4e82e 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -28,6 +28,7 @@ import { interceptSystemToolCalls } from "core/tools/systemMessageTools/intercep import { selectCurrentToolCalls } from "../selectors/selectToolCalls"; import { getBaseSystemMessage } from "../util/getBaseSystemMessage"; import { callToolById } from "./callToolById"; +import { DEFAULT_TOOL_SETTING } from "../slices/uiSlice"; /** * Handles the execution of tool calls that may be automatically accepted. * Sets all tools as generated first, then executes auto-approved tool calls. @@ -35,6 +36,7 @@ import { callToolById } from "./callToolById"; async function handleToolCallExecution( dispatch: AppThunkDispatch, getState: () => RootState, + activeTools: Tool[], ): Promise { const newState = getState(); const toolSettings = newState.ui.toolSettings; @@ -51,11 +53,15 @@ async function handleToolCallExecution( } // Check if ALL tool calls are auto-approved - if not, wait for user approval - const allAutoApproved = toolCallStates.every( - (toolCallState) => - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission", - ); + const allAutoApproved = toolCallStates.every((toolCallState) => { + const toolPolicy = + toolSettings[toolCallState.toolCall.function.name] ?? + activeTools.find( + (tool) => tool.function.name === toolCallState.toolCall.function.name, + )?.defaultToolPolicy ?? + DEFAULT_TOOL_SETTING; + return toolPolicy == "allowedWithoutPermission"; + }); // Set all tools as generated first toolCallStates.forEach((toolCallState) => { @@ -289,11 +295,16 @@ export const streamNormalInput = createAsyncThunk< // Check if ALL generating tool calls are auto-approved const allAutoApproved = generatingToolCalls.length > 0 && - generatingToolCalls.every( - (toolCallState) => - toolSettings[toolCallState.toolCall.function.name] === - "allowedWithoutPermission", - ); + generatingToolCalls.every((toolCallState) => { + const toolPolicy = + toolSettings[toolCallState.toolCall.function.name] ?? + activeTools.find( + (tool) => + tool.function.name === toolCallState.toolCall.function.name, + )?.defaultToolPolicy ?? + DEFAULT_TOOL_SETTING; + return toolPolicy == "allowedWithoutPermission"; + }); // Only set inactive if: // 1. There are no tool calls, OR @@ -303,6 +314,6 @@ export const streamNormalInput = createAsyncThunk< dispatch(setInactive()); } - await handleToolCallExecution(dispatch, getState); + await handleToolCallExecution(dispatch, getState, activeTools); }, ); From 221127e09e6ba50494053b25826969a9e1fb9fe6 Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Wed, 6 Aug 2025 15:04:56 -0700 Subject: [PATCH 05/33] fix: apply code changes requested in the diff Commit generated with [cn](https://docs.continue.dev/guides/cli) --- docs/customize/deep-dives/configuration.mdx | 4 ++++ docs/customize/deep-dives/slash-commands.mdx | 9 ++++++++- docs/reference/json-reference.mdx | 10 +++++++++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx index c3aa770b9..e18056baa 100644 --- a/docs/customize/deep-dives/configuration.mdx +++ b/docs/customize/deep-dives/configuration.mdx @@ -60,6 +60,10 @@ Example `config.ts` must export a `modifyConfig` function, like: + + The `slashCommands` array shown below is deprecated. For creating custom slash commands, use [prompt blocks or prompt files](./slash-commands) instead. + + ```ts title="config.ts" export function modifyConfig(config: Config): Config { config.slashCommands?.push({ diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 81579d3ed..38b22da29 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -11,6 +11,13 @@ Slash commands are shortcuts that can be activated by typing '/' in a chat sessi Slash commands can be combined with additional instructions, including [context providers](../custom-providers.mdx) or highlighted code. + + **Recommended approach**: Use prompt blocks or prompt files to create slash + commands instead of the deprecated `config.json` approach. The methods + described below provide better flexibility and are the actively maintained + ways to add custom commands. + + ## Prompts ### Assistant prompt blocks @@ -21,7 +28,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/ It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. -Learn more about prompt files [here](./prompts.md) +Learn more about prompt files [here](./prompts.mdx). ### MCP Server prompts diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index 7d6f40568..ae2e5cafb 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -1,7 +1,15 @@ --- -title: "config.json Reference" +title: "config.json Reference (Deprecated)" +description: "Legacy configuration reference for config.json - use config.yaml instead" +noindex: true --- + + **This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use: + - [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands + - [config.yaml](/reference) for configuration + + We recently introduced a new configuration format, `config.yaml`, to replace `config.json`. See the `config.yaml` reference and migration guide From 89b07e87854b1bdc5ebae569d525ece614914bac Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Wed, 6 Aug 2025 15:09:55 -0700 Subject: [PATCH 06/33] fix: copy --- docs/customize/deep-dives/configuration.mdx | 5 +++-- docs/customize/deep-dives/slash-commands.mdx | 8 ++++---- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx index e18056baa..666d3f27b 100644 --- a/docs/customize/deep-dives/configuration.mdx +++ b/docs/customize/deep-dives/configuration.mdx @@ -61,7 +61,8 @@ Example `config.ts` must export a `modifyConfig` function, like: - The `slashCommands` array shown below is deprecated. For creating custom slash commands, use [prompt blocks or prompt files](./slash-commands) instead. + The `slashCommands` array shown below is deprecated. For creating custom slash + commands, use [prompt files](./slash-commands) instead. ```ts title="config.ts" @@ -86,4 +87,4 @@ export function modifyConfig(config: Config): Config { }); return config; } -``` \ No newline at end of file +``` diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 38b22da29..5add2fbfa 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -12,10 +12,10 @@ Slash commands are shortcuts that can be activated by typing '/' in a chat sessi Slash commands can be combined with additional instructions, including [context providers](../custom-providers.mdx) or highlighted code. - **Recommended approach**: Use prompt blocks or prompt files to create slash - commands instead of the deprecated `config.json` approach. The methods - described below provide better flexibility and are the actively maintained - ways to add custom commands. + **Recommended approach**: Use prompt files to create slash commands instead of + the deprecated `config.json` approach. The methods described below provide + better flexibility and are the actively maintained ways to add custom + commands. ## Prompts From b8057dc3f28e782a54c6b6849e2e47c7eb81829e Mon Sep 17 00:00:00 2001 From: Brian 'bdougie' Douglas Date: Wed, 6 Aug 2025 15:26:16 -0700 Subject: [PATCH 07/33] fix: links --- docs/customize/deep-dives/slash-commands.mdx | 4 ++-- docs/reference/json-reference.mdx | 16 ++++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 5add2fbfa..f62725f54 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -9,7 +9,7 @@ keywords: [slash command, custom commands, step] Slash commands are shortcuts that can be activated by typing '/' in a chat session (press cmd/ctrl + L (VS Code) or cmd/ctrl + J (JetBrains)), and selecting from the dropdown. ![slash-commands](/images/slash-commands.png) -Slash commands can be combined with additional instructions, including [context providers](../custom-providers.mdx) or highlighted code. +Slash commands can be combined with additional instructions, including [context providers](../custom-providers) or highlighted code. **Recommended approach**: Use prompt files to create slash commands instead of @@ -28,7 +28,7 @@ The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/ It is also possible to write your own slash command by defining a “.prompt file.” Prompt files can be as simple as a text file, but also include templating so that you can refer to files, URLs, highlighted code, and more. -Learn more about prompt files [here](./prompts.mdx). +Learn more about prompt files [here](./prompts). ### MCP Server prompts diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index ae2e5cafb..319b91e38 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -8,13 +8,11 @@ noindex: true **This page documents deprecated functionality.** For creating slash commands and customizing Continue, please use: - [Prompt blocks and prompt files](/customize/deep-dives/slash-commands) for slash commands - [config.yaml](/reference) for configuration - - - We recently introduced a new configuration format, `config.yaml`, to replace - `config.json`. See the `config.yaml` reference and migration guide - [here](/reference). - +See the `config.yaml` reference and migration guide +[here](/reference). + + Below are details for each property that can be set in `config.json`. The config schema code is found in [`extensions/vscode/config_schema.json`](https://github.com/continuedev/continue/blob/main/extensions/vscode/config_schema.json). @@ -476,16 +474,19 @@ Several experimental config parameters are available, as described below: - `defaultContext`: Defines the default context for the LLM. Uses the same format as `contextProviders` but includes an additional `query` property to specify custom query parameters.= - `modelRoles`: + - `inlineEdit`: Model title for inline edits. - `applyCodeBlock`: Model title for applying code blocks. - `repoMapFileSelection`: Model title for repo map selections. - `quickActions`: Array of custom quick actions + - `title` (**required**): Display title for the quick action. - `prompt` (**required**): Prompt for quick action. - `sendToChat`: If `true`, sends result to chat; else inserts in document. Default is `false`. - `contextMenuPrompts`: + - `comment`: Prompt for commenting code. - `docstring`: Prompt for adding docstrings. - `fix`: Prompt for fixing code. @@ -537,15 +538,18 @@ Some deprecated `config.json` settings are no longer stored in config and have b - `disableSessionTitles`/`ui.getChatTitles`: This value will be migrated to the safest merged value (`true` if either are `true`). `getChatTitles` takes precedence if set to false - `tabAutocompleteOptions` + - `useCache`: This value will override during migration. - `disableInFiles`: This value will be migrated to the safest merged value (arrays of file matches merged/deduplicated) - `multilineCompletions`: This value will override during migration. - `experimental` + - `useChromiumForDocsCrawling`: This value will override during migration. - `readResponseTTS`: This value will override during migration. - `ui` - all will override during migration + - `codeBlockToolbarPosition` - `fontSize` - `codeWrap` From c70f5695dc571ef0ed3b4fce7a0218300561fc61 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:49:22 -0700 Subject: [PATCH 08/33] chore: add comments --- core/nextEdit/templating/NextEditPromptEngine.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 1369ebbc6..54e19212d 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -33,6 +33,7 @@ import { type TemplateRenderer = (vars: TemplateVars) => string; +// NOTE: When updating this union, update core/llm/autodetect.ts as well. export type NextEditModelName = | "mercury-coder-nextedit" | "model-1" From f691b90778e700e4644bfb6b63702f3138af6e5b Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:49:47 -0700 Subject: [PATCH 09/33] feat: add next_edit capability --- core/config/yaml/models.ts | 1 + core/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 3f571c3fb..102e4152b 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -68,6 +68,7 @@ async function modelConfigToBaseLLM({ capabilities: { tools: model.capabilities?.includes("tool_use"), uploadImage: model.capabilities?.includes("image_input"), + nextEdit: model.capabilities?.includes("next_edit"), }, autocompleteOptions: model.autocompleteOptions, }; diff --git a/core/index.d.ts b/core/index.d.ts index eacffcb56..3dc7a1f71 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1138,6 +1138,7 @@ export interface BaseCompletionOptions { export interface ModelCapability { uploadImage?: boolean; tools?: boolean; + nextEdit?: boolean; } export interface ModelDescription { From c5c2e2e0f2a3efd1cda6e88b3534f888a927f43d Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:50:29 -0700 Subject: [PATCH 10/33] feat: add a checker function to see if next_edit capability is set, or if the model is one of our supported models --- core/llm/autodetect.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 571a7a700..9d0b72626 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -173,6 +173,35 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( ); } +// NOTE: When updating this list, +// update core/nextEdit/templating/NextEditPromptEngine.ts as well. +const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ + "mercury-coder-nextedit", + "model-1", + "this field is not used", +]; + +function modelSupportsNextEdit( + model: string, + title: string | undefined, + capabilities: ModelCapability | undefined, +): boolean { + if (capabilities?.nextEdit !== undefined) { + return capabilities.nextEdit; + } + + const lower = model.toLowerCase(); + if ( + MODEL_SUPPORTS_NEXT_EDIT.some( + (modelName) => lower.includes(modelName) || title?.includes(modelName), + ) + ) { + return true; + } + + return false; +} + function autodetectTemplateType(model: string): TemplateType | undefined { const lower = model.toLowerCase(); @@ -391,4 +420,5 @@ export { autodetectTemplateType, llmCanGenerateInParallel, modelSupportsImages, + modelSupportsNextEdit, }; From e480bcf9d00a73a09c360bd1e8b22fc311ed59ba Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:50:59 -0700 Subject: [PATCH 11/33] refactor: check if model supports next edit --- core/nextEdit/NextEditProvider.ts | 9 +++++++++ extensions/vscode/src/extension/VsCodeExtension.ts | 12 +++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 1ae21c152..8e37d2547 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -18,6 +18,7 @@ import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebounce import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; +import { modelSupportsNextEdit } from "../llm/autodetect.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; import { @@ -286,6 +287,14 @@ export class NextEditProvider { return undefined; } + // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts. + // For other editors, this check should be done in their respective config reloaders. + // This is left for a final check. + if (!modelSupportsNextEdit(llm.model, llm.title, llm.capabilities)) { + console.error(`${llm.model} is not capable of next edit.`); + return undefined; + } + if (llm.promptTemplates?.autocomplete) { options.template = llm.promptTemplates.autocomplete as string; } diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index a8fcdbb88..898d648a0 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -43,13 +43,14 @@ import { ConfigYamlDocumentLinkProvider } from "./ConfigYamlDocumentLinkProvider import { VsCodeMessenger } from "./VsCodeMessenger"; import { getAst } from "core/autocomplete/util/ast"; +import { modelSupportsNextEdit } from "core/llm/autodetect"; import { DocumentHistoryTracker } from "core/nextEdit/DocumentHistoryTracker"; import { EditableRegionStrategy, getNextEditableRegion, } from "core/nextEdit/NextEditEditableRegionCalculator"; import { NextEditProvider } from "core/nextEdit/NextEditProvider"; -import { isModelCapableOfNextEdit } from "core/nextEdit/utils"; +import { isNextEditTest } from "core/nextEdit/utils"; import { localPathOrUriToPath } from "core/util/pathToUri"; import { JumpManager } from "../activation/JumpManager"; import setupNextEditWindowManager, { @@ -190,8 +191,13 @@ export class VsCodeExtension { async ({ config: newConfig, configLoadInterrupted }) => { const autocompleteModel = newConfig?.selectedModelByRole.autocomplete; if ( - autocompleteModel && - isModelCapableOfNextEdit(autocompleteModel.model) + (autocompleteModel && + modelSupportsNextEdit( + autocompleteModel.model, + autocompleteModel.title, + autocompleteModel.capabilities, + )) || + isNextEditTest() ) { // Set up next edit window manager only for Continue team members await setupNextEditWindowManager(context); From 51ef9a9ec76426f0da65f968cf6c653b6b08cb12 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:51:12 -0700 Subject: [PATCH 12/33] refactor: only handle test environments --- core/nextEdit/utils.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/core/nextEdit/utils.ts b/core/nextEdit/utils.ts index 152e55933..bf1081ebe 100644 --- a/core/nextEdit/utils.ts +++ b/core/nextEdit/utils.ts @@ -1,15 +1,13 @@ -type NextEditModelName = "mercury-coder-nextedit"; +export function isNextEditTest(): boolean { + const enabled = process.env.NEXT_EDIT_TEST_ENABLED; -export function isModelCapableOfNextEdit(modelName: string): boolean { - // In test mode, we can control whether next edit is enabled via environment variable. - if (process.env.NEXT_EDIT_TEST_ENABLED === "false") { + if (enabled === "false") { return false; } - if (process.env.NEXT_EDIT_TEST_ENABLED === "true") { + if (enabled === "true") { return true; } - const supportedModels: NextEditModelName[] = ["mercury-coder-nextedit"]; - return supportedModels.some((supported) => modelName.includes(supported)); + return false; } From 6a31f985b02d595b76f98404359ddb5be0bf9656 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:51:57 -0700 Subject: [PATCH 13/33] feat: add next_edit z.literal --- packages/config-yaml/src/schemas/models.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index 283ec6781..0693675a2 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -36,6 +36,7 @@ export type ModelRole = z.infer; export const modelCapabilitySchema = z.union([ z.literal("tool_use"), z.literal("image_input"), + z.literal("next_edit"), ]); export type ModelCapability = z.infer; From 3c51d54cc2096eaf47bc1b9f59bc0ecb141e874f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 15:59:27 -0700 Subject: [PATCH 14/33] test: add vitest for autodetect next edit --- core/llm/autodetect.vitest.ts | 126 +++++++++++++++++++++++++++++++++- 1 file changed, 124 insertions(+), 2 deletions(-) diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index e9d7180ae..5743a749c 100644 --- a/core/llm/autodetect.vitest.ts +++ b/core/llm/autodetect.vitest.ts @@ -1,5 +1,5 @@ -import { expect, test } from "vitest"; -import { autodetectTemplateType } from "./autodetect"; +import { describe, expect, it, test } from "vitest"; +import { autodetectTemplateType, modelSupportsNextEdit } from "./autodetect"; test("autodetectTemplateType returns 'codellama-70b' for CodeLlama 70B models", () => { expect(autodetectTemplateType("codellama-70b")).toBe("codellama-70b"); @@ -201,3 +201,125 @@ test("autodetectTemplateType handles models with mixed keywords", () => { expect(autodetectTemplateType("gpt-llama")).toBe(undefined); // gpt comes first, returns undefined expect(autodetectTemplateType("claude-llama")).toBe("llama2"); // llama comes first, returns llama2 }); + +describe("modelSupportsNextEdit", () => { + describe("when capabilities.nextEdit is defined", () => { + it("should return true when capabilities.nextEdit is true", () => { + const result = modelSupportsNextEdit("any-model", "Any Title", { + nextEdit: true, + }); + + expect(result).toBe(true); + }); + + it("should return false when capabilities.nextEdit is false", () => { + const result = modelSupportsNextEdit( + "mercury-coder-nextedit", + "Mercury Coder", + { nextEdit: false }, + ); + + expect(result).toBe(false); + }); + + it("should prioritize capabilities over model name matching", () => { + // Even though model name matches, capabilities should take precedence. + const result = modelSupportsNextEdit( + "mercury-coder-nextedit", + "Mercury Coder", + { nextEdit: false }, + ); + + expect(result).toBe(false); + }); + }); + + describe("when capabilities.nextEdit is undefined", () => { + it("should return true for mercury-coder-nextedit model (case insensitive)", () => { + expect( + modelSupportsNextEdit("Mercury-Coder-Nextedit", undefined, undefined), + ).toBe(true); + }); + + it("should return true for model-1", () => { + expect(modelSupportsNextEdit("model-1", undefined, undefined)).toBe(true); + }); + + it("should return true when model contains supported model name as substring", () => { + expect( + modelSupportsNextEdit( + "provider/mercury-coder-nextedit-v2", + undefined, + undefined, + ), + ).toBe(true); + }); + + it("should return true when title contains supported model name", () => { + expect( + modelSupportsNextEdit( + "some-model", + "This is mercury-coder-nextedit model", + undefined, + ), + ).toBe(true); + }); + + it("should return true when title contains model-1", () => { + expect( + modelSupportsNextEdit("some-model", "model-1 deployment", undefined), + ).toBe(true); + }); + + it("should return true for unsupported models that have capabilities explicitly set to true", () => { + expect( + modelSupportsNextEdit("gpt-4", "GPT-4 Model", { + nextEdit: true, + }), + ).toBe(true); + }); + + it("should return false for unsupported models", () => { + expect(modelSupportsNextEdit("gpt-4", "GPT-4 Model", undefined)).toBe( + false, + ); + }); + + it("should return false when model and title are both undefined/null", () => { + expect(modelSupportsNextEdit("", undefined, undefined)).toBe(false); + }); + + it("should return false when model and title do not contain supported names", () => { + expect( + modelSupportsNextEdit("claude-3", "Claude 3 Sonnet", undefined), + ).toBe(false); + }); + }); + + describe("edge cases", () => { + it("should handle empty strings", () => { + expect(modelSupportsNextEdit("", "", undefined)).toBe(false); + }); + + it("should handle undefined title gracefully", () => { + expect( + modelSupportsNextEdit("mercury-coder-nextedit", undefined, undefined), + ).toBe(true); + }); + + it("should handle case sensitivity correctly", () => { + expect( + modelSupportsNextEdit("MERCURY-CODER-NEXTEDIT", "MODEL-1", undefined), + ).toBe(true); + }); + + it("should handle capabilities with other properties", () => { + expect( + modelSupportsNextEdit("unsupported-model", undefined, { + nextEdit: true, + uploadImage: false, + }), + ).toBe(true); + }); + }); +}); From b3da8c7c70ba9f0769bced204a4c94cd7ce015a9 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 16:06:45 -0700 Subject: [PATCH 15/33] refactor: return token, startTime, and helper --- core/nextEdit/NextEditProvider.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 1af6b6fc0..0b549dfde 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -347,7 +347,7 @@ export class NextEditProvider { // This is left for a final check. if (!modelSupportsNextEdit(llm.model, llm.title, llm.capabilities)) { console.error(`${llm.model} is not capable of next edit.`); - return undefined; + return { token, startTime, helper: undefined }; } if (llm.promptTemplates?.autocomplete) { From 793c835f23cfd4248c36675d0b449b0d250e2fe7 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 16:20:43 -0700 Subject: [PATCH 16/33] fix: remove test model for now --- core/llm/autodetect.ts | 1 - .../templating/NextEditPromptEngine.ts | 19 +------------------ 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 9d0b72626..4d59bd667 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -178,7 +178,6 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ "mercury-coder-nextedit", "model-1", - "this field is not used", ]; function modelSupportsNextEdit( diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 59cea94f5..bfab03a73 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -34,10 +34,7 @@ import { type TemplateRenderer = (vars: TemplateVars) => string; // NOTE: When updating this union, update core/llm/autodetect.ts as well. -export type NextEditModelName = - | "mercury-coder-nextedit" - | "model-1" - | "this field is not used"; +export type NextEditModelName = "mercury-coder-nextedit" | "model-1"; const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { @@ -47,9 +44,6 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { template: "### User Edits:\n\n{{{userEdits}}}\n\n### User Excerpts:\n\n```{{{languageShorthand}}}\n{{{userExcerpts}}}```", }, - "this field is not used": { - template: "NEXT_EDIT", - }, }; function templateRendererOfModel( @@ -73,17 +67,6 @@ export async function renderPrompt( ): Promise { let modelName = helper.modelName as NextEditModelName; - if (modelName === "this field is not used") { - return { - prompt: { - role: "user", - content: "NEXT_EDIT", - }, - userEdits: "", - userExcerpts: helper.fileContents, - }; - } - // Validate that the modelName is actually a supported model. if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { // Check if modelName includes any known model name as substring. From 6b51f556a9bed2343951eb8b6cb317ede8b97612 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 16:26:56 -0700 Subject: [PATCH 17/33] fix: remove test llm from prompt engine vitest --- .../templating/NextEditPromptEngine.vitest.ts | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 03ffd26e8..a83f19330 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -41,12 +41,6 @@ describe("NextEditPromptEngine", () => { pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, } as HelperVars; - testHelper = { - modelName: "this field is not used" as NextEditModelName, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; unsupportedHelper = { modelName: "mistral/codestral" as NextEditModelName, fileContents: "function test() {\n const a = 1;\n return a;\n}", @@ -99,16 +93,6 @@ describe("NextEditPromptEngine", () => { expect(result.userExcerpts).toContain(MODEL_1_USER_CURSOR_IS_HERE_TOKEN); }); - it("should handle 'this field is not used' model name", async () => { - const result = await renderPrompt(testHelper, ctx); - - expect(result).toHaveProperty("prompt"); - expect(result.prompt.role).toBe("user"); - expect(result.prompt.content).toBe("NEXT_EDIT"); - expect(result.userEdits).toBe(""); - expect(result.userExcerpts).toBe(testHelper.fileContents); - }); - it("should throw error for unsupported model name", async () => { await expect(renderPrompt(unsupportedHelper, ctx)).rejects.toThrow( "mistral/codestral is not yet supported for next edit.", From 9d279cb620ad1d5851ce3880c15afc1bb82bd59c Mon Sep 17 00:00:00 2001 From: Patrick Erichsen Date: Wed, 6 Aug 2025 18:12:13 -0700 Subject: [PATCH 18/33] Delete .continue/rules/continue-pun.md --- .continue/rules/continue-pun.md | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 .continue/rules/continue-pun.md diff --git a/.continue/rules/continue-pun.md b/.continue/rules/continue-pun.md deleted file mode 100644 index 502e1cfbc..000000000 --- a/.continue/rules/continue-pun.md +++ /dev/null @@ -1,9 +0,0 @@ ---- -name: Add Continue pun easter eggs -description: Adds an easter egg whenever the "continue" keyword -pattern: "continue" ---- - -Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase - -Do not add a comment if the use of "continue" is not in a code continue statement From def9970dbd83aa12f30f8ed539cf2161adb5745a Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 18:23:44 -0700 Subject: [PATCH 19/33] refactor: define next edit model enum to use elsewhere --- core/llm/constants.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/core/llm/constants.ts b/core/llm/constants.ts index b6759663d..5b93048e9 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -19,6 +19,11 @@ export enum LLMConfigurationStatuses { MISSING_ENV_SECRET = "missing-env-secret", } +export enum NEXT_EDIT_MODELS { + MERCURY_CODER_NEXTEDIT = "mercury-coder-nextedit", + MODEL_1 = "model-1", +} + export { DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, From 722bdbf97d7d44890e5a2cac96ec91cd3f3ed83f Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 18:24:17 -0700 Subject: [PATCH 20/33] refactor: use next edit model enum --- core/llm/autodetect.ts | 7 ++++--- core/nextEdit/templating/NextEditPromptEngine.ts | 12 +++++------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 4d59bd667..b2943e316 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -1,4 +1,5 @@ import { ChatMessage, ModelCapability, TemplateType } from "../index.js"; +import { NEXT_EDIT_MODELS } from "./constants.js"; import { anthropicTemplateMessages, @@ -176,14 +177,14 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( // NOTE: When updating this list, // update core/nextEdit/templating/NextEditPromptEngine.ts as well. const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ - "mercury-coder-nextedit", - "model-1", + NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, + NEXT_EDIT_MODELS.MODEL_1, ]; function modelSupportsNextEdit( + capabilities: ModelCapability | undefined, model: string, title: string | undefined, - capabilities: ModelCapability | undefined, ): boolean { if (capabilities?.nextEdit !== undefined) { return capabilities.nextEdit; diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index bfab03a73..29e958b18 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -30,13 +30,11 @@ import { insertCursorToken, insertEditableRegionTokensWithStaticRange, } from "./utils"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; type TemplateRenderer = (vars: TemplateVars) => string; -// NOTE: When updating this union, update core/llm/autodetect.ts as well. -export type NextEditModelName = "mercury-coder-nextedit" | "model-1"; - -const NEXT_EDIT_MODEL_TEMPLATES: Record = { +const NEXT_EDIT_MODEL_TEMPLATES: Record = { "mercury-coder-nextedit": { template: `${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_OPEN}\n{{{recentlyViewedCodeSnippets}}}\n${MERCURY_RECENTLY_VIEWED_CODE_SNIPPETS_CLOSE}\n\n${MERCURY_CURRENT_FILE_CONTENT_OPEN}\n{{{currentFileContent}}}\n${MERCURY_CURRENT_FILE_CONTENT_CLOSE}\n\n${MERCURY_EDIT_DIFF_HISTORY_OPEN}\n{{{editDiffHistory}}}\n${MERCURY_EDIT_DIFF_HISTORY_CLOSE}\n\nThe developer was working on a section of code within the tags \`<|code_to_edit|>\` in the file located at {{{currentFilePath}}}.\nUsing the given \`recently_viewed_code_snippets\`, \`current_file_content\`, \`edit_diff_history\`, and the cursor position marked as \`<|cursor|>\`, please continue the developer's work. Update the \`code_to_edit\` section by predicting and completing the changes they would have made next. Provide the revised code that was between the \`<|code_to_edit|>\` and \`<|/code_to_edit|>\` tags, including the tags themselves.`, }, @@ -47,7 +45,7 @@ const NEXT_EDIT_MODEL_TEMPLATES: Record = { }; function templateRendererOfModel( - modelName: NextEditModelName, + modelName: NEXT_EDIT_MODELS, ): TemplateRenderer { let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; if (!template) { @@ -65,7 +63,7 @@ export async function renderPrompt( helper: HelperVars, ctx: any, ): Promise { - let modelName = helper.modelName as NextEditModelName; + let modelName = helper.modelName as NEXT_EDIT_MODELS; // Validate that the modelName is actually a supported model. if (!Object.keys(NEXT_EDIT_MODEL_TEMPLATES).includes(modelName)) { @@ -75,7 +73,7 @@ export async function renderPrompt( ); if (matchingModel) { - modelName = matchingModel as NextEditModelName; + modelName = matchingModel as NEXT_EDIT_MODELS; } else { throw new Error( `${helper.modelName} is not yet supported for next edit.`, From 2aae07efc37d0847f3de8d3224afcd3d3021a3c5 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 18:24:43 -0700 Subject: [PATCH 21/33] refactor: move capabilities to the top --- core/llm/autodetect.vitest.ts | 86 +++++++++++-------- core/nextEdit/NextEditProvider.ts | 2 +- .../templating/NextEditPromptEngine.vitest.ts | 10 +-- 3 files changed, 55 insertions(+), 43 deletions(-) diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index 5743a749c..01d48aacc 100644 --- a/core/llm/autodetect.vitest.ts +++ b/core/llm/autodetect.vitest.ts @@ -205,51 +205,55 @@ test("autodetectTemplateType handles models with mixed keywords", () => { describe("modelSupportsNextEdit", () => { describe("when capabilities.nextEdit is defined", () => { it("should return true when capabilities.nextEdit is true", () => { - const result = modelSupportsNextEdit("any-model", "Any Title", { - nextEdit: true, - }); - - expect(result).toBe(true); + expect( + modelSupportsNextEdit( + { + nextEdit: true, + }, + "any-model", + "Any Title", + ), + ).toBe(true); }); it("should return false when capabilities.nextEdit is false", () => { - const result = modelSupportsNextEdit( - "mercury-coder-nextedit", - "Mercury Coder", - { nextEdit: false }, - ); - - expect(result).toBe(false); + expect( + modelSupportsNextEdit( + { nextEdit: false }, + "mercury-coder-nextedit", + "Mercury Coder", + ), + ).toBe(false); }); it("should prioritize capabilities over model name matching", () => { // Even though model name matches, capabilities should take precedence. - const result = modelSupportsNextEdit( - "mercury-coder-nextedit", - "Mercury Coder", - { nextEdit: false }, - ); - - expect(result).toBe(false); + expect( + modelSupportsNextEdit( + { nextEdit: false }, + "mercury-coder-nextedit", + "Mercury Coder", + ), + ).toBe(false); }); }); describe("when capabilities.nextEdit is undefined", () => { it("should return true for mercury-coder-nextedit model (case insensitive)", () => { expect( - modelSupportsNextEdit("Mercury-Coder-Nextedit", undefined, undefined), + modelSupportsNextEdit(undefined, "Mercury-Coder-Nextedit", undefined), ).toBe(true); }); it("should return true for model-1", () => { - expect(modelSupportsNextEdit("model-1", undefined, undefined)).toBe(true); + expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true); }); it("should return true when model contains supported model name as substring", () => { expect( modelSupportsNextEdit( - "provider/mercury-coder-nextedit-v2", undefined, + "provider/mercury-coder-nextedit-v2", undefined, ), ).toBe(true); @@ -258,67 +262,75 @@ describe("modelSupportsNextEdit", () => { it("should return true when title contains supported model name", () => { expect( modelSupportsNextEdit( + undefined, "some-model", "This is mercury-coder-nextedit model", - undefined, ), ).toBe(true); }); it("should return true when title contains model-1", () => { expect( - modelSupportsNextEdit("some-model", "model-1 deployment", undefined), + modelSupportsNextEdit(undefined, "some-model", "model-1 deployment"), ).toBe(true); }); it("should return true for unsupported models that have capabilities explicitly set to true", () => { expect( - modelSupportsNextEdit("gpt-4", "GPT-4 Model", { - nextEdit: true, - }), + modelSupportsNextEdit( + { + nextEdit: true, + }, + "gpt-4", + "GPT-4 Model", + ), ).toBe(true); }); it("should return false for unsupported models", () => { - expect(modelSupportsNextEdit("gpt-4", "GPT-4 Model", undefined)).toBe( + expect(modelSupportsNextEdit(undefined, "gpt-4", "GPT-4 Model")).toBe( false, ); }); it("should return false when model and title are both undefined/null", () => { - expect(modelSupportsNextEdit("", undefined, undefined)).toBe(false); + expect(modelSupportsNextEdit(undefined, "", undefined)).toBe(false); }); it("should return false when model and title do not contain supported names", () => { expect( - modelSupportsNextEdit("claude-3", "Claude 3 Sonnet", undefined), + modelSupportsNextEdit(undefined, "claude-3", "Claude 3 Sonnet"), ).toBe(false); }); }); describe("edge cases", () => { it("should handle empty strings", () => { - expect(modelSupportsNextEdit("", "", undefined)).toBe(false); + expect(modelSupportsNextEdit(undefined, "", "")).toBe(false); }); it("should handle undefined title gracefully", () => { expect( - modelSupportsNextEdit("mercury-coder-nextedit", undefined, undefined), + modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined), ).toBe(true); }); it("should handle case sensitivity correctly", () => { expect( - modelSupportsNextEdit("MERCURY-CODER-NEXTEDIT", "MODEL-1", undefined), + modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"), ).toBe(true); }); it("should handle capabilities with other properties", () => { expect( - modelSupportsNextEdit("unsupported-model", undefined, { - nextEdit: true, - uploadImage: false, - }), + modelSupportsNextEdit( + { + nextEdit: true, + uploadImage: false, + }, + "unsupported-model", + undefined, + ), ).toBe(true); }); }); diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b549dfde..ade13b4c3 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -345,7 +345,7 @@ export class NextEditProvider { // In vscode, this check is done in extensions/vscode/src/extension/VsCodeExtension.ts. // For other editors, this check should be done in their respective config reloaders. // This is left for a final check. - if (!modelSupportsNextEdit(llm.model, llm.title, llm.capabilities)) { + if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) { console.error(`${llm.model} is not capable of next edit.`); return { token, startTime, helper: undefined }; } diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index a83f19330..785dd79cc 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts @@ -14,11 +14,11 @@ import { MODEL_1_USER_CURSOR_IS_HERE_TOKEN, } from "../constants"; import { - NextEditModelName, renderDefaultSystemPrompt, renderDefaultUserPrompt, renderPrompt, } from "./NextEditPromptEngine"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; describe("NextEditPromptEngine", () => { describe("renderPrompt", () => { @@ -30,19 +30,19 @@ describe("NextEditPromptEngine", () => { beforeEach(() => { mercuryHelper = { - modelName: "inception/mercury-coder-nextedit" as NextEditModelName, + modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, fileContents: "function test() {\n const a = 1;\n return a;\n}", pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, } as HelperVars; model1Helper = { - modelName: "continuedev/model-1" as NextEditModelName, + modelName: "continuedev/model-1" as NEXT_EDIT_MODELS, fileContents: "function test() {\n const a = 1;\n return a;\n}", pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, } as HelperVars; unsupportedHelper = { - modelName: "mistral/codestral" as NextEditModelName, + modelName: "mistral/codestral" as NEXT_EDIT_MODELS, fileContents: "function test() {\n const a = 1;\n return a;\n}", pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, @@ -193,7 +193,7 @@ describe("NextEditPromptEngine", () => { describe("insertTokens", () => { it("should correctly insert cursor and editable region tokens", () => { const mercuryHelper = { - modelName: "inception/mercury-coder-nextedit" as NextEditModelName, + modelName: "inception/mercury-coder-nextedit" as NEXT_EDIT_MODELS, fileContents: "function test() {\n const a = 1;\n return a;\n}", pos: { line: 1, character: 12 } as Position, lang: { name: "typescript" }, From 6f65295a17e53e7e36b4d3a1fa5f3e451a89a348 Mon Sep 17 00:00:00 2001 From: Jacob Kim Date: Wed, 6 Aug 2025 18:28:00 -0700 Subject: [PATCH 22/33] refactor: move capabilities to the top --- extensions/vscode/src/extension/VsCodeExtension.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 387faf311..3861edcb7 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -205,9 +205,9 @@ export class VsCodeExtension { if ( (autocompleteModel && modelSupportsNextEdit( + autocompleteModel.capabilities, autocompleteModel.model, autocompleteModel.title, - autocompleteModel.capabilities, )) || isNextEditTest() ) { From d4b0609a7a87f5b89ab7a0086901f676b658033a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Aug 2025 20:14:07 -0700 Subject: [PATCH 23/33] fix: tell model no tools are available if they aren't (#7034) * fix: tell model no tools are available if they aren't * fix: prettier * fix: no duplicate warning message for tests * fix: revert main prettier chanages --- gui/src/redux/thunks/streamNormalInput.ts | 1 + .../redux/util/getBaseSystemMessage.test.ts | 73 +++++++++++++++---- gui/src/redux/util/getBaseSystemMessage.ts | 21 +++++- 3 files changed, 75 insertions(+), 20 deletions(-) diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index 13c57da8e..d3f99c64d 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -173,6 +173,7 @@ export const streamNormalInput = createAsyncThunk< const baseSystemMessage = getBaseSystemMessage( state.session.mode, selectedChatModel, + activeTools, ); const systemMessage = systemToolsFramework diff --git a/gui/src/redux/util/getBaseSystemMessage.test.ts b/gui/src/redux/util/getBaseSystemMessage.test.ts index ef2eef559..ed069693a 100644 --- a/gui/src/redux/util/getBaseSystemMessage.test.ts +++ b/gui/src/redux/util/getBaseSystemMessage.test.ts @@ -1,10 +1,10 @@ -import { ModelDescription } from "core"; +import { ModelDescription, Tool } from "core"; import { DEFAULT_AGENT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_PLAN_SYSTEM_MESSAGE, } from "core/llm/defaultSystemMessages"; -import { getBaseSystemMessage } from "./getBaseSystemMessage"; +import { getBaseSystemMessage, NO_TOOL_WARNING } from "./getBaseSystemMessage"; test("getBaseSystemMessage should return the correct system message based on mode", () => { const mockModel = { @@ -13,33 +13,74 @@ test("getBaseSystemMessage should return the correct system message based on mod baseAgentSystemMessage: "Custom Agent System Message", } as ModelDescription; - // Test agent mode with custom message - expect(getBaseSystemMessage("agent", mockModel)).toBe( + const mockTool = { + function: { + name: "testTool", + description: "Test tool", + parameters: {}, + }, + } as Tool; + + // Test agent mode with custom message and tools + expect(getBaseSystemMessage("agent", mockModel, [mockTool])).toBe( "Custom Agent System Message", ); - // Test plan mode with custom message - expect(getBaseSystemMessage("plan", mockModel)).toBe( + // Test plan mode with custom message and tools + expect(getBaseSystemMessage("plan", mockModel, [mockTool])).toBe( "Custom Plan System Message", ); - // Test chat mode with custom message - expect(getBaseSystemMessage("chat", mockModel)).toBe( + // Test chat mode with custom message and tools + expect(getBaseSystemMessage("chat", mockModel, [mockTool])).toBe( "Custom Chat System Message", ); - // Test agent mode with default message - expect(getBaseSystemMessage("agent", {} as ModelDescription)).toBe( - DEFAULT_AGENT_SYSTEM_MESSAGE, - ); + // Test agent mode with default message and tools + expect( + getBaseSystemMessage("agent", {} as ModelDescription, [mockTool]), + ).toBe(DEFAULT_AGENT_SYSTEM_MESSAGE); - // Test plan mode with default message - expect(getBaseSystemMessage("plan", {} as ModelDescription)).toBe( + // Test plan mode with default message and tools + expect(getBaseSystemMessage("plan", {} as ModelDescription, [mockTool])).toBe( DEFAULT_PLAN_SYSTEM_MESSAGE, ); - // Test chat mode with default message - expect(getBaseSystemMessage("chat", {} as ModelDescription)).toBe( + // Test chat mode with default message and tools + expect(getBaseSystemMessage("chat", {} as ModelDescription, [mockTool])).toBe( DEFAULT_CHAT_SYSTEM_MESSAGE, ); }); + +test("getBaseSystemMessage should append no-tools warning for agent/plan modes without tools", () => { + const mockModel = { + baseChatSystemMessage: "Custom Chat System Message", + basePlanSystemMessage: "Custom Plan System Message", + baseAgentSystemMessage: "Custom Agent System Message", + } as ModelDescription; + + // Test agent mode without tools + expect(getBaseSystemMessage("agent", mockModel, [])).toBe( + "Custom Agent System Message" + NO_TOOL_WARNING, + ); + + // Test plan mode without tools + expect(getBaseSystemMessage("plan", mockModel, [])).toBe( + "Custom Plan System Message" + NO_TOOL_WARNING, + ); + + // Test chat mode without tools (should not append warning) + expect(getBaseSystemMessage("chat", mockModel, [])).toBe( + "Custom Chat System Message", + ); + + // Test agent mode with undefined tools + expect(getBaseSystemMessage("agent", mockModel)).toBe( + "Custom Agent System Message" + NO_TOOL_WARNING, + ); + + // Test plan mode with undefined tools + expect(getBaseSystemMessage("plan", mockModel)).toBe( + "Custom Plan System Message" + NO_TOOL_WARNING, + ); +}); diff --git a/gui/src/redux/util/getBaseSystemMessage.ts b/gui/src/redux/util/getBaseSystemMessage.ts index b27d38ff7..c03493b15 100644 --- a/gui/src/redux/util/getBaseSystemMessage.ts +++ b/gui/src/redux/util/getBaseSystemMessage.ts @@ -1,19 +1,32 @@ -import { ModelDescription } from "core"; +import { ModelDescription, Tool } from "core"; import { DEFAULT_AGENT_SYSTEM_MESSAGE, DEFAULT_CHAT_SYSTEM_MESSAGE, DEFAULT_PLAN_SYSTEM_MESSAGE, } from "core/llm/defaultSystemMessages"; +export const NO_TOOL_WARNING = + "\n\nTHE USER HAS NOT PROVIDED ANY TOOLS, DO NOT ATTEMPT TO USE ANY TOOLS. STOP AND LET THE USER KNOW THAT THERE ARE NO TOOLS AVAILABLE. The user can provide tools by enabling them in the Tool Policies section of the notch (wrench icon)"; + export function getBaseSystemMessage( messageMode: string, model: ModelDescription, + activeTools?: Tool[], ): string { + let baseMessage: string; + if (messageMode === "agent") { - return model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; + baseMessage = model.baseAgentSystemMessage ?? DEFAULT_AGENT_SYSTEM_MESSAGE; } else if (messageMode === "plan") { - return model.basePlanSystemMessage ?? DEFAULT_PLAN_SYSTEM_MESSAGE; + baseMessage = model.basePlanSystemMessage ?? DEFAULT_PLAN_SYSTEM_MESSAGE; } else { - return model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; + baseMessage = model.baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE; } + + // Add no-tools warning for agent/plan modes when no tools are available + if (messageMode !== "chat" && (!activeTools || activeTools.length === 0)) { + baseMessage += NO_TOOL_WARNING; + } + + return baseMessage; } From 2513ae78e68cdc2d433e07c686a0178517339667 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Aug 2025 21:08:53 -0700 Subject: [PATCH 24/33] improv: tweak file too big message (#7036) --- gui/src/components/mainInput/AtMentionDropdown/index.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index ac0bcfdba..f9638b37f 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -245,12 +245,14 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { // Trigger warning message ideMessenger.ide.showToast( "warning", - fileSize > 0 ? "File exceeds context length" : "Can't load the file", + fileSize > 0 + ? "File exceeds model's context length" + : "Error loading file", { modal: true, detail: fileSize > 0 - ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model` + ? `'${item.title}' cannot be added because it exceeds the model's allowed context length. File size: ${formatFileSize(fileSize)}` : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, }, ); From 4fd88d3b842b31085ef5d8d6f5427d84b4466d5b Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Wed, 6 Aug 2025 21:19:15 -0700 Subject: [PATCH 25/33] chore: vscode 1.1.74 --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 77b05c381..faf1aa07a 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.73", + "version": "1.1.74", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From d111bc5f3a81df9be92b72bfba1008875785aa67 Mon Sep 17 00:00:00 2001 From: vldf Date: Thu, 7 Aug 2025 11:26:47 +0300 Subject: [PATCH 26/33] Fix: add missing space --- gui/src/components/mainInput/Lump/sections/PromptsSection.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index beb4b87e7..ce7721d8c 100644 --- a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx @@ -81,7 +81,7 @@ function PromptRow({
From aed9153e6ad11861e2f7db27aaa9031522006d93 Mon Sep 17 00:00:00 2001 From: vldf Date: Thu, 7 Aug 2025 13:37:04 +0300 Subject: [PATCH 27/33] Fix: remove redundant `call` word from the default agent system prompt --- core/llm/defaultSystemMessages.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/defaultSystemMessages.ts b/core/llm/defaultSystemMessages.ts index edb5753fb..eebcc8510 100644 --- a/core/llm/defaultSystemMessages.ts +++ b/core/llm/defaultSystemMessages.ts @@ -61,7 +61,7 @@ export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\ You are in agent mode. - If you need to use multiple tools, you can call call multiple read only tools simultaneously. + If you need to use multiple tools, you can call multiple read only tools simultaneously. ${CODEBLOCK_FORMATTING_INSTRUCTIONS} `; From a266903de19567701152d24577c24a406fb663b5 Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 7 Aug 2025 18:55:19 +0530 Subject: [PATCH 28/33] improve: tool call spacing and margins --- .../StyledMarkdownPreview/StepContainerPreToolbar/index.tsx | 2 +- gui/src/pages/gui/ToolCallDiv/index.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index fd5f0150a..4679c232c 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -263,7 +263,7 @@ export function StepContainerPreToolbar({ } return ( -
+
+
( -
+
{renderToolCall(toolCallState)}
)); From e394a9aa95079b45ebff1d4c95a97a1f74d41eec Mon Sep 17 00:00:00 2001 From: uinstinct <61635505+uinstinct@users.noreply.github.com> Date: Thu, 7 Aug 2025 19:42:51 +0530 Subject: [PATCH 29/33] improve: open conversation summary be default --- gui/src/components/StepContainer/ConversationSummary.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gui/src/components/StepContainer/ConversationSummary.tsx b/gui/src/components/StepContainer/ConversationSummary.tsx index 5260da58f..392b757da 100644 --- a/gui/src/components/StepContainer/ConversationSummary.tsx +++ b/gui/src/components/StepContainer/ConversationSummary.tsx @@ -1,12 +1,12 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; import { TrashIcon } from "@heroicons/react/24/outline"; +import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; import { ChatHistoryItem } from "core"; import { useState } from "react"; -import { AnimatedEllipsis } from "../AnimatedEllipsis"; import { useAppSelector } from "../../redux/hooks"; -import StyledMarkdownPreview from "../StyledMarkdownPreview"; import { useDeleteCompaction } from "../../util/compactConversation"; +import { AnimatedEllipsis } from "../AnimatedEllipsis"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; +import StyledMarkdownPreview from "../StyledMarkdownPreview"; interface ConversationSummaryProps { item: ChatHistoryItem; @@ -14,7 +14,7 @@ interface ConversationSummaryProps { } export default function ConversationSummary(props: ConversationSummaryProps) { - const [open, setOpen] = useState(false); + const [open, setOpen] = useState(true); const isLoading = useAppSelector( (state) => state.session.compactionLoading[props.index] || false, ); From bc3375e818acc7f80b987c16ad3a7ace009f40c9 Mon Sep 17 00:00:00 2001 From: Jazzcort Date: Tue, 22 Jul 2025 09:43:02 -0400 Subject: [PATCH 30/33] Fix: Remove duplicate blocks and provide config warnings This patch is to address the following cases that duplicate blocks appear in the UI and confuse users: 1. When users refer to a local block with "- uses", if the block is already in the default directories (e.g. ~/.continue/models or /.continue/models) and users don't override its name attribute, the duplicate block will appear in the UI. 2. When users have duplicate block names among each block type in their assistant config. 3. When the injected blocks have duplicate names with the assistant config for the corresponding block type. The duplicate blocks in the UI is confusing, especially in the model selection. This patch add a blockDuplicationDetector to detect duplication. When a duplication is detected, we remove the duplicate item and push a config error to the result to warn the users that having duplicate names is not the best practice to set up their config. The detecting order: assistant config -> injected blocks To detect duplication, all block types use "name" as the identifier except for rules and context. For rules, if it's an rule object, we use the "name" attribute. Otherwise, we use its string content as the identifier. For context, the "provider" attribute is used as the identifier. The detection only happens under assistant level, which means you can have assistants with duplicate names. --- .../config-yaml/src/__tests__/index.test.ts | 82 +++++++++++++++++-- .../local-files/duplicate-test-assistant.yaml | 39 +++++++++ .../src/__tests__/local-files/mcpServer.yaml | 8 ++ .../src/__tests__/local-files/prompt.yaml | 7 ++ .../src/__tests__/local-files/rules.yaml | 6 ++ .../src/load/blockDuplicationDetector.ts | 76 +++++++++++++++++ packages/config-yaml/src/load/unroll.ts | 35 ++++++-- 7 files changed, 242 insertions(+), 11 deletions(-) create mode 100644 packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/mcpServer.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/prompt.yaml create mode 100644 packages/config-yaml/src/__tests__/local-files/rules.yaml create mode 100644 packages/config-yaml/src/load/blockDuplicationDetector.ts diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index af11cf0c4..5e0a3cdb9 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -93,9 +93,11 @@ describe("E2E Scenarios", () => { const registry: Registry = { getContent: async function (id: PackageIdentifier): Promise { const slug = packageIdentifierToShorthandSlug(id); - return fs - .readFileSync(`./src/__tests__/packages/${slug}.yaml`) - .toString(); + const filePath = + id.uriType === "slug" + ? `./src/__tests__/packages/${slug}.yaml` + : id.filePath; + return fs.readFileSync(filePath).toString(); }, }; @@ -230,7 +232,7 @@ describe("E2E Scenarios", () => { orgScopeId: "test-org", currentUserSlug: "test-user", onPremProxyUrl: null, - // Add an injected block + // Add injected blocks injectBlocks: [ { uriType: "slug", @@ -240,11 +242,16 @@ describe("E2E Scenarios", () => { versionSlug: "latest", }, }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/rules.yaml", + }, ], }, ); const config = unrolledConfig.config; + const errors = unrolledConfig.errors; // The original rules array should have two items expect(config?.rules?.length).toBe(3); // Now 3 with the injected block @@ -255,7 +262,72 @@ describe("E2E Scenarios", () => { ); // Check the injected doc block was added - expect(config?.rules?.[2]).toBe("Be kind"); + expect( + typeof config?.rules?.[2] !== "string" && + config?.rules?.[2]?.rule === "Be humble", + ); + + // Check if we receive one error that is caused by duplicate rules + expect(errors?.length).toBe(1); + expect(errors?.[0].message.includes("Duplicate rules detected")); + }); + + it("duplicate detection should happen in the assistant config first and then the intected blocks", async () => { + const unrolledConfig = await unrollAssistant( + { + uriType: "file", + filePath: "./src/__tests__/local-files/duplicate-test-assistant.yaml", + }, + registry, + { + renderSecrets: true, + platformClient, + orgScopeId: "test-org", + currentUserSlug: "test-user", + onPremProxyUrl: null, + // Add injected blocks + injectBlocks: [ + { + uriType: "file", + filePath: "./src/__tests__/local-files/rules.yaml", + }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/mcpServer.yaml", + }, + { + uriType: "file", + filePath: "./src/__tests__/local-files/prompt.yaml", + }, + ], + }, + ); + + const config = unrolledConfig.config; + const errors = unrolledConfig.errors; + + // Check if all the duplicate blocks get removed + expect(config?.models?.length).toBe(1); + expect(config?.context?.length).toBe(1); + expect(config?.mcpServers?.length).toBe(1); + expect(config?.rules?.length).toBe(1); + expect(config?.prompts?.length).toBe(1); + expect(config?.docs?.length).toBe(1); + + // Check if there are 8 duplication detected + expect(errors?.length).toBe(8); + + // Beginning of the assistant config duplication check + expect( + errors?.[0].message.includes("Duplicate models named gpt-5 detected"), + ).toBe(true); + // Beginning of the injected blocks duplication check + expect(errors?.[4].message.includes("Duplicate rules detected")).toBe(true); + expect( + errors?.[6].message.includes( + "Duplicate mcpServers named Browser search detected", + ), + ).toBe(true); }); it.skip("should prioritize org over user / package secrets", () => {}); diff --git a/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml b/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml new file mode 100644 index 000000000..7f5eca13a --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/duplicate-test-assistant.yaml @@ -0,0 +1,39 @@ +name: Duplicate Test Assistant +version: 0.0.1 +schema: v1 + +docs: + - name: React + startUrl: https://react.dev + - name: React + startUrl: https://react.dev + +rules: + - Be humble + - uses: ./src/__tests__/local-files/rules.yaml + +models: + - name: gpt-5 + provider: openai + model: gpt-5 + apiKey: ${{ secrets.OPENAI_API_KEY }} + roles: + - chat + + - name: gpt-5 + provider: openai + model: gpt-5 + apiKey: ${{ secrets.OPENAI_API_KEY }} + roles: + - chat + +mcpServers: + - uses: ./src/__tests__/local-files/mcpServer.yaml + +prompts: + - uses: ./src/__tests__/local-files/prompt.yaml + - uses: ./src/__tests__/local-files/prompt.yaml + +context: + - provider: doc + - provider: doc diff --git a/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml b/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml new file mode 100644 index 000000000..b6be73016 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/mcpServer.yaml @@ -0,0 +1,8 @@ +name: Local MCP Server +version: 0.0.1 +schema: v1 +mcpServers: + - name: Browser search + command: npx + args: + - "@playwright/mcp@latest" diff --git a/packages/config-yaml/src/__tests__/local-files/prompt.yaml b/packages/config-yaml/src/__tests__/local-files/prompt.yaml new file mode 100644 index 000000000..7ea2c2707 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/prompt.yaml @@ -0,0 +1,7 @@ +name: Local prompt +version: 0.0.1 +schema: v1 +prompts: + - name: duplication test + description: test purpose + prompt: Please check that this prompt should only appear once diff --git a/packages/config-yaml/src/__tests__/local-files/rules.yaml b/packages/config-yaml/src/__tests__/local-files/rules.yaml new file mode 100644 index 000000000..6bfca2423 --- /dev/null +++ b/packages/config-yaml/src/__tests__/local-files/rules.yaml @@ -0,0 +1,6 @@ +name: Rules +version: 0.0.1 +schema: v1 + +rules: + - Be humble diff --git a/packages/config-yaml/src/load/blockDuplicationDetector.ts b/packages/config-yaml/src/load/blockDuplicationDetector.ts new file mode 100644 index 000000000..78e5ce980 --- /dev/null +++ b/packages/config-yaml/src/load/blockDuplicationDetector.ts @@ -0,0 +1,76 @@ +import { BLOCK_TYPES, BlockType } from "./getBlockType.js"; + +export class BlockDuplicationDetector { + private records: Map>; + + constructor() { + this.records = new Map(); + for (const blockType of BLOCK_TYPES) { + this.records.set(blockType, new Set()); + } + } + + private isRuleDuplicated(rule: any): boolean { + if (typeof rule === "string") { + return this.check(rule, "rules"); + } else { + return this.check(rule.name, "rules"); + } + } + + private isContextDuplicated(context: any): boolean { + return this.check(context.provider, "context"); + } + + private isCommonBlockDuplicated(block: any, blockType: BlockType): boolean { + return this.check(block.name, blockType); + } + + private check(identifier: string, blockType: BlockType): boolean { + if (this.records.get(blockType)!.has(identifier)) { + return true; + } else { + this.records.get(blockType)!.add(identifier); + return false; + } + } + + // Check if the name is duplicated within the same blockType + isDuplicated( + block: any, + blockType: BlockType, + injectError?: (errorMsg: string) => void, + ): boolean { + // Not checking any null or undefined object + if (block === null || block === undefined) { + return false; + } + + switch (blockType) { + case "rules": + if (this.isRuleDuplicated(block)) { + injectError?.( + `Duplicate rules${typeof block === "string" ? "" : ` named ${block.name}`} detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + case "context": + if (this.isContextDuplicated(block)) { + injectError?.( + `Duplicate ${block.provider} context providers detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + default: + if (this.isCommonBlockDuplicated(block, blockType)) { + injectError?.( + `Duplicate ${blockType} named ${block.name} detected. The duplicate one has been deleted for preventing unexpected behavior.`, + ); + return true; + } + return false; + } + } +} diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index adbe45324..5225f79aa 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -20,6 +20,7 @@ import { Rule, } from "../schemas/index.js"; import { ConfigResult, ConfigValidationError } from "../validation.js"; +import { BlockDuplicationDetector } from "./blockDuplicationDetector.js"; import { packageIdentifierToShorthandSlug, useProxyForUnrenderedSecrets, @@ -306,6 +307,13 @@ export async function unrollBlocks( ): Promise> { const errors: ConfigValidationError[] = []; + function injectDuplicationError(errorMsg: string) { + errors.push({ + fatal: false, + message: errorMsg, + }); + } + const unrolledAssistant: AssistantUnrolled = { name: assistant.name, version: assistant.version, @@ -484,7 +492,7 @@ export async function unrollBlocks( const injectedResults = await Promise.all(injectedBlockPromises); const injectedErrors: ConfigValidationError[] = []; const injectedBlocks: { - blockType: string; + blockType: BlockType; resolvedBlock: any; source?: string; }[] = []; @@ -521,16 +529,27 @@ export async function unrollBlocks( errors.push(...rulesResult.errors); errors.push(...injectedResult.errors); + const detector = new BlockDuplicationDetector(); + // Assign section results for (const sectionResult of sectionResults) { if (sectionResult.blocks) { - unrolledAssistant[sectionResult.section] = sectionResult.blocks; + unrolledAssistant[sectionResult.section] = sectionResult.blocks.filter( + (block) => + !detector.isDuplicated( + block, + sectionResult.section, + injectDuplicationError, + ), + ); } } // Assign rules result if (rulesResult.rules) { - unrolledAssistant.rules = rulesResult.rules; + unrolledAssistant.rules = rulesResult.rules.filter( + (rule) => !detector.isDuplicated(rule, "rules", injectDuplicationError), + ); } // Add injected blocks @@ -539,16 +558,20 @@ export async function unrollBlocks( resolvedBlock, source, } of injectedResult.injectedBlocks) { - const key = blockType as BlockType; + const key = blockType; if (!unrolledAssistant[key]) { unrolledAssistant[key] = []; } - const blocksWithSourceFiles = injectLocalSourceFile( + + const filteredBlocks = injectLocalSourceFile( key, resolvedBlock, source, + ).filter( + (block: any) => + !detector.isDuplicated(block, blockType, injectDuplicationError), ); - unrolledAssistant[key]?.push(...blocksWithSourceFiles); + unrolledAssistant[key]?.push(...filteredBlocks); } const configResult: ConfigResult = { From ab4bb9c1579b591bffb713b90e7cd207586f4dc2 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 11:56:31 -0700 Subject: [PATCH 31/33] fix: jetbrains release script (#7050) * fix: jetbrains release script - build only option * fix: channel name --- .github/workflows/jetbrains-release.yaml | 117 ++++++++++++++--------- 1 file changed, 73 insertions(+), 44 deletions(-) diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index d2eb53938..72bd84235 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -9,10 +9,18 @@ on: types: [prereleased] workflow_dispatch: inputs: - publish_build: - description: "Whether or not to publish the built extension to the JetBrains marketplace" + build_only: + description: "If true, only build the extension for the given channels, don't publish" required: true - default: false + default: "true" + eap_channel: + description: "If true, build/publish the extension to the EAP channel" + required: true + default: "true" + stable_channel: + description: "If true, build/publish the extension to the Stable channel" + required: true + default: "true" defaults: run: @@ -37,50 +45,50 @@ jobs: echo "should_run=false" >> $GITHUB_OUTPUT fi - bump-version: - runs-on: ubuntu-latest - needs: - - check_release_name - if: github.event_name != 'workflow_dispatch' || github.event.inputs.publish_build == 'true' - permissions: - contents: write - pull-requests: write - steps: - # 0. Setup git - - name: Checkout - uses: actions/checkout@v4 + # bump-version: + # runs-on: ubuntu-latest + # needs: + # - check_release_name + # if: github.event_name != 'workflow_dispatch' || github.event.inputs.eap_channel == 'true' || github.event.inputs.stable_channel == 'true' + # permissions: + # contents: write + # pull-requests: write + # steps: + # # 0. Setup git + # - name: Checkout + # uses: actions/checkout@v4 - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" + # - name: Set up Git + # run: | + # git config --local user.email "action@github.com" + # git config --local user.name "GitHub Action" - - name: Create PR branch - run: | - BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" - git checkout -b $BRANCH_NAME - echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV + # - name: Create PR branch + # run: | + # BRANCH_NAME="chore/bump-jetbrains-version-$(date +%Y%m%d-%H%M%S)" + # git checkout -b $BRANCH_NAME + # echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV - - name: Bump version in gradle.properties - run: | - awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties - rm -rf tmp - NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) - echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV + # - name: Bump version in gradle.properties + # run: | + # awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties + # rm -rf tmp + # NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2) + # echo "NEW_VERSION=$NEW_VERSION" >> $GITHUB_ENV - - name: Create Pull Request - uses: peter-evans/create-pull-request@v7 - with: - token: ${{ secrets.CI_GITHUB_TOKEN }} - commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" - title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" - body: | - Automated PR to bump the JetBrains extension version after successful pre-release publication. + # - name: Create Pull Request + # uses: peter-evans/create-pull-request@v7 + # with: + # token: ${{ secrets.CI_GITHUB_TOKEN }} + # commit-message: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + # title: "chore: bump jetbrains extension version to ${{ env.NEW_VERSION }}" + # body: | + # Automated PR to bump the JetBrains extension version after successful pre-release publication. - - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} - branch: ${{ env.BRANCH_NAME }} - base: main - delete-branch: true + # - Bumped version in extensions/intellij/gradle.properties to ${{ env.NEW_VERSION }} + # branch: ${{ env.BRANCH_NAME }} + # base: main + # delete-branch: true # Prepare and publish the plugin to JetBrains Marketplace repository build: @@ -223,9 +231,30 @@ jobs: # apple-product-id: dev.continue.continue-binary # options: --options runtime --entitlements entitlements.xml + # Build the plugin if not publishing + - name: Build EAP Plugin (no publish) + if: github.event_name != 'release' && github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only == 'true' + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: eap + run: ./gradlew buildPlugin --info --stacktrace + + - name: Build Stable Plugin (no publish) + if: github.event_name != 'release' && github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only == 'true' + env: + PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} + CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} + PRIVATE_KEY: ${{ secrets.JETBRAINS_PRIVATE_KEY }} + PRIVATE_KEY_PASSWORD: ${{ secrets.JETBRAINS_PRIVATE_KEY_PASSWORD }} + RELEASE_CHANNEL: default + run: ./gradlew buildPlugin --info --stacktrace + # Publish the plugin to JetBrains Marketplace - name: Publish EAP Plugin - if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' + if: github.event_name == 'release' || (github.event.inputs.eap_channel == 'true' && github.event.inputs.build_only != 'true') env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} @@ -235,7 +264,7 @@ jobs: run: ./gradlew publishPlugin --info --stacktrace - name: Publish Stable Plugin - if: github.event_name == 'release' || github.event.inputs.publish_build == 'true' + if: github.event_name == 'release' || (github.event.inputs.stable_channel == 'true' && github.event.inputs.build_only != 'true') env: PUBLISH_TOKEN: ${{ secrets.JETBRAINS_PUBLISH_TOKEN }} CERTIFICATE_CHAIN: ${{ secrets.JETBRAINS_CERTIFICATE_CHAIN }} From 01812e598f2e5b3f201c1329388d3133b0c935b7 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 13:36:26 -0700 Subject: [PATCH 32/33] feat: gpt-5 support (#7054) * fix: gpt-5 support * fix: gpt 5 context length * fix: broken test file --- core/llm/llms/OpenAI.test.ts | 32 +++++++++---------- core/llm/llms/OpenAI.ts | 16 +++++----- core/llm/toolSupport.ts | 10 +++--- gui/src/pages/AddNewModel/configs/models.ts | 12 +++++++ .../pages/AddNewModel/configs/providers.ts | 5 +-- packages/llm-info/src/providers/openai.ts | 9 ++++++ packages/openai-adapters/src/apis/OpenAI.ts | 2 +- 7 files changed, 55 insertions(+), 31 deletions(-) diff --git a/core/llm/llms/OpenAI.test.ts b/core/llm/llms/OpenAI.test.ts index 46c8b4e23..8daf93852 100644 --- a/core/llm/llms/OpenAI.test.ts +++ b/core/llm/llms/OpenAI.test.ts @@ -5,30 +5,30 @@ describe("OpenAI", () => { const openai = new OpenAI({ model: "o3-mini", }); - expect(openai.isOSeriesModel("o4-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o3-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o1-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o1")).toBeTruthy(); - expect(openai.isOSeriesModel("o3")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o4-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o3-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o1-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o1")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o3")).toBeTruthy(); // artificially correct samples for future models - expect(openai.isOSeriesModel("o5-mini")).toBeTruthy(); - expect(openai.isOSeriesModel("o6")).toBeTruthy(); - expect(openai.isOSeriesModel("o77")).toBeTruthy(); - expect(openai.isOSeriesModel("o54-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o5-mini")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o6")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o77")).toBeTruthy(); + expect(openai.isOSeriesOrGpt5Model("o54-mini")).toBeTruthy(); }); test("should identify incorrect o-series models", () => { const openai = new OpenAI({ model: "o3-mini", }); - expect(openai.isOSeriesModel("gpt-o4-mini")).toBeFalsy(); - expect(openai.isOSeriesModel("gpt-4.5")).toBeFalsy(); - expect(openai.isOSeriesModel("gpt-4.1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-o4-mini")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-4.5")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("gpt-4.1")).toBeFalsy(); // artificially wrong samples - expect(openai.isOSeriesModel("os1")).toBeFalsy(); - expect(openai.isOSeriesModel("so1")).toBeFalsy(); - expect(openai.isOSeriesModel("ao31")).toBeFalsy(); - expect(openai.isOSeriesModel("1os")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("os1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("so1")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("ao31")).toBeFalsy(); + expect(openai.isOSeriesOrGpt5Model("1os")).toBeFalsy(); }); }); diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index c48349f83..27006aea1 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -36,12 +36,12 @@ function isChatOnlyModel(model: string): boolean { return model.startsWith("gpt") || model.startsWith("o"); } -const formatMessageForO1 = (messages: ChatCompletionMessageParam[]) => { +const formatMessageForO1OrGpt5 = (messages: ChatCompletionMessageParam[]) => { return messages?.map((message: any) => { if (message?.role === "system") { return { ...message, - role: "user", + role: "developer", }; } @@ -77,8 +77,8 @@ class OpenAI extends BaseLLM { return model; } - public isOSeriesModel(model?: string): boolean { - return !!model && !!model.match(/^o[0-9]+/); + public isOSeriesOrGpt5Model(model?: string): boolean { + return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5")); } private isFireworksAiModel(model?: string): boolean { @@ -139,13 +139,13 @@ class OpenAI extends BaseLLM { finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isOSeriesModel(options.model)) { + if (this.isOSeriesOrGpt5Model(options.model)) { // a) use max_completion_tokens instead of max_tokens finalOptions.max_completion_tokens = options.maxTokens; finalOptions.max_tokens = undefined; // b) don't support system message - finalOptions.messages = formatMessageForO1(finalOptions.messages); + finalOptions.messages = formatMessageForO1OrGpt5(finalOptions.messages); } if (options.model === "o1") { @@ -241,13 +241,13 @@ class OpenAI extends BaseLLM { body.stop = body.stop?.slice(0, this.getMaxStopWords()); // OpenAI o1-preview and o1-mini or o3-mini: - if (this.isOSeriesModel(body.model)) { + if (this.isOSeriesOrGpt5Model(body.model)) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; // b) don't support system message - body.messages = formatMessageForO1(body.messages); + body.messages = formatMessageForO1OrGpt5(body.messages); } if (body.model === "o1") { diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 2700361cc..1417d8307 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -54,18 +54,20 @@ export const PROVIDER_TOOL_SUPPORT: Record boolean> = return false; }, openai: (model) => { + const lower = model.toLowerCase(); // https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling if ( - model.toLowerCase().startsWith("gpt-4") || - model.toLowerCase().startsWith("o3") + lower.startsWith("gpt-4") || + lower.startsWith("gpt-5") || + lower.startsWith("o3") ) { return true; } - if (model.toLowerCase().includes("gpt-oss")) { + if (lower.includes("gpt-oss")) { return true; } // https://ai.google.dev/gemma/docs/capabilities/function-calling - if (model.toLowerCase().startsWith("gemma")) { + if (lower.startsWith("gemma")) { return true; } // firworks-ai https://docs.fireworks.ai/guides/function-calling diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index d0857d7db..b5c4bbae5 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -1095,6 +1095,18 @@ export const models: { [key: string]: ModelPackage } = { icon: "cohere.png", isOpenSource: false, }, + gpt5: { + title: "GPT-5", + description: "OpenAI's next-generation, high-intelligence flagship model", + params: { + model: "gpt-5", + contextLength: 400_000, + title: "GPT-5", + }, + providerOptions: ["openai"], + icon: "openai.png", + isOpenSource: false, + }, gpt4turbo: { title: "GPT-4 Turbo", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index d210da9d6..071f96be9 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -52,12 +52,13 @@ export const providers: Partial> = { openai: { title: "OpenAI", provider: "openai", - description: "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model", + description: "Use gpt-5, gpt-4, or any other OpenAI model", longDescription: - "Use gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.", + "Use gpt-5, gpt-4, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.", icon: "openai.png", tags: [ModelProviderTags.RequiresApiKey], packages: [ + models.gpt5, models.gpt4o, models.gpt4omini, models.gpt4turbo, diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index a15dd3089..820559308 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -75,6 +75,15 @@ export const OpenAi: ModelProvider = { contextLength: 128000, maxCompletionTokens: 4096, }, + // gpt-5 + { + model: "gpt-5", + displayName: "GPT-5", + contextLength: 400000, + maxCompletionTokens: 128000, + regex: /gpt-5/, + recommendedFor: ["chat"], + }, // gpt-4o { model: "gpt-4o", diff --git a/packages/openai-adapters/src/apis/OpenAI.ts b/packages/openai-adapters/src/apis/OpenAI.ts index c1e356fa5..714ce67fd 100644 --- a/packages/openai-adapters/src/apis/OpenAI.ts +++ b/packages/openai-adapters/src/apis/OpenAI.ts @@ -38,7 +38,7 @@ export class OpenAIApi implements BaseLlmApi { // o-series models - only apply for official OpenAI API const isOfficialOpenAIAPI = this.apiBase === "https://api.openai.com/v1/"; if (isOfficialOpenAIAPI) { - if (body.model.startsWith("o")) { + if (body.model.startsWith("o") || body.model.includes("gpt-5")) { // a) use max_completion_tokens instead of max_tokens body.max_completion_tokens = body.max_tokens; body.max_tokens = undefined; From c69ed88bf0a7e156bfff6de763cacc881147e352 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Thu, 7 Aug 2025 13:52:41 -0700 Subject: [PATCH 33/33] chore: vscode 1.1.75 --- extensions/vscode/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index faf1aa07a..9d15d1bb6 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "1.1.74", + "version": "1.1.75", "repository": { "type": "git", "url": "https://github.com/continuedev/continue"