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 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 }} 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..9941e2bc2 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1093,7 +1093,10 @@ export interface Tool { faviconUrl?: string; group: string; originalFunctionName?: string; - systemMessageDescription?: string; + systemMessageDescription?: { + prefix: string; + exampleArgs?: Array<[string, string | number]>; + }; defaultToolPolicy?: ToolPolicy; } @@ -1138,6 +1141,7 @@ export interface BaseCompletionOptions { export interface ModelCapability { uploadImage?: boolean; tools?: boolean; + nextEdit?: boolean; } export interface ModelDescription { diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 571a7a700..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, @@ -173,6 +174,34 @@ function isProviderHandlesTemplatingOrNoTemplateTypeRequired( ); } +// NOTE: When updating this list, +// update core/nextEdit/templating/NextEditPromptEngine.ts as well. +const MODEL_SUPPORTS_NEXT_EDIT: string[] = [ + NEXT_EDIT_MODELS.MERCURY_CODER_NEXTEDIT, + NEXT_EDIT_MODELS.MODEL_1, +]; + +function modelSupportsNextEdit( + capabilities: ModelCapability | undefined, + model: string, + title: string | 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, }; diff --git a/core/llm/autodetect.vitest.ts b/core/llm/autodetect.vitest.ts index e9d7180ae..01d48aacc 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,137 @@ 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", () => { + expect( + modelSupportsNextEdit( + { + nextEdit: true, + }, + "any-model", + "Any Title", + ), + ).toBe(true); + }); + + it("should return false when capabilities.nextEdit is 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. + 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(undefined, "Mercury-Coder-Nextedit", undefined), + ).toBe(true); + }); + + it("should return true for model-1", () => { + expect(modelSupportsNextEdit(undefined, "model-1", undefined)).toBe(true); + }); + + it("should return true when model contains supported model name as substring", () => { + expect( + modelSupportsNextEdit( + undefined, + "provider/mercury-coder-nextedit-v2", + undefined, + ), + ).toBe(true); + }); + + it("should return true when title contains supported model name", () => { + expect( + modelSupportsNextEdit( + undefined, + "some-model", + "This is mercury-coder-nextedit model", + ), + ).toBe(true); + }); + + it("should return true when title contains model-1", () => { + expect( + 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( + { + nextEdit: true, + }, + "gpt-4", + "GPT-4 Model", + ), + ).toBe(true); + }); + + it("should return false for unsupported models", () => { + 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); + }); + + it("should return false when model and title do not contain supported names", () => { + expect( + modelSupportsNextEdit(undefined, "claude-3", "Claude 3 Sonnet"), + ).toBe(false); + }); + }); + + describe("edge cases", () => { + it("should handle empty strings", () => { + expect(modelSupportsNextEdit(undefined, "", "")).toBe(false); + }); + + it("should handle undefined title gracefully", () => { + expect( + modelSupportsNextEdit(undefined, "mercury-coder-nextedit", undefined), + ).toBe(true); + }); + + it("should handle case sensitivity correctly", () => { + expect( + modelSupportsNextEdit(undefined, "MERCURY-CODER-NEXTEDIT", "MODEL-1"), + ).toBe(true); + }); + + it("should handle capabilities with other properties", () => { + expect( + modelSupportsNextEdit( + { + nextEdit: true, + uploadImage: false, + }, + "unsupported-model", + undefined, + ), + ).toBe(true); + }); + }); +}); 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, 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} `; 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 2876ba346..e96318697 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -54,26 +54,28 @@ 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; } // LGAI EXAONE models expose an OpenAI-compatible API with tool // calling support when served via frameworks like vLLM - if (model.toLowerCase().includes("exaone")) { + if (lower.includes("exaone")) { 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; } diff --git a/core/nextEdit/NextEditProvider.ts b/core/nextEdit/NextEditProvider.ts index 0b97c4491..ade13b4c3 100644 --- a/core/nextEdit/NextEditProvider.ts +++ b/core/nextEdit/NextEditProvider.ts @@ -30,6 +30,7 @@ import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js"; import { HelperVars } from "../autocomplete/util/HelperVars.js"; import { AutocompleteInput } from "../autocomplete/util/types.js"; import { myersDiff } from "../diff/myers.js"; +import { modelSupportsNextEdit } from "../llm/autodetect.js"; import { countTokens } from "../llm/countTokens.js"; import { localPathOrUriToPath } from "../util/pathToUri.js"; import { replaceEscapedCharacters } from "../util/text.js"; @@ -341,6 +342,14 @@ export class NextEditProvider { return { token, startTime, helper: 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.capabilities, llm.model, llm.title)) { + console.error(`${llm.model} is not capable of next edit.`); + return { token, startTime, helper: undefined }; + } + if (llm.promptTemplates?.autocomplete) { options.template = llm.promptTemplates.autocomplete as string; } diff --git a/core/nextEdit/templating/NextEditPromptEngine.ts b/core/nextEdit/templating/NextEditPromptEngine.ts index 24f16e681..29e958b18 100644 --- a/core/nextEdit/templating/NextEditPromptEngine.ts +++ b/core/nextEdit/templating/NextEditPromptEngine.ts @@ -30,15 +30,11 @@ import { insertCursorToken, insertEditableRegionTokensWithStaticRange, } from "./utils"; +import { NEXT_EDIT_MODELS } from "../../llm/constants"; type TemplateRenderer = (vars: TemplateVars) => string; -export type NextEditModelName = - | "mercury-coder-nextedit" - | "model-1" - | "this field is not used"; - -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.`, }, @@ -46,13 +42,10 @@ 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( - modelName: NextEditModelName, + modelName: NEXT_EDIT_MODELS, ): TemplateRenderer { let template = NEXT_EDIT_MODEL_TEMPLATES[modelName]; if (!template) { @@ -70,18 +63,7 @@ export async function renderPrompt( helper: HelperVars, ctx: any, ): 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, - }; - } + 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)) { @@ -91,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.`, diff --git a/core/nextEdit/templating/NextEditPromptEngine.vitest.ts b/core/nextEdit/templating/NextEditPromptEngine.vitest.ts index 03ffd26e8..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,25 +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, - fileContents: "function test() {\n const a = 1;\n return a;\n}", - pos: { line: 1, character: 12 } as Position, - lang: { name: "typescript" }, - } as HelperVars; - testHelper = { - modelName: "this field is not used" 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" }, @@ -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.", @@ -209,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" }, 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; } diff --git a/core/tools/definitions/codebaseTool.ts b/core/tools/definitions/codebaseTool.ts index f7806bc30..3334034cc 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", @@ -28,9 +27,10 @@ export const codebaseTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 e0ba8ee9a..8f651a601 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", @@ -32,12 +31,11 @@ export const createNewFileTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 3ab63f6a4..7dcb8cd51 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')"; @@ -61,9 +60,8 @@ export const createRuleBlock: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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} @@ -72,7 +70,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", @@ -85,5 +83,5 @@ For example:`, ["globs", "**/*.js"], ["alwaysApply", "false"], ], - ), + }, }; diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 33ac93e38..86250bc57 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 { @@ -41,19 +40,18 @@ export const editFileTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 5deedc9c7..07a76a991 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", @@ -27,9 +26,8 @@ export const fetchUrlContentTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 4d4c01c4f..5e710c04b 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", @@ -27,9 +26,8 @@ export const globSearchTool: Tool = { }, }, defaultToolPolicy: "allowedWithoutPermission", - 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 b3017cbd5..cc4f9c49c 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", @@ -28,9 +27,8 @@ export const grepSearchTool: Tool = { }, }, defaultToolPolicy: "allowedWithoutPermission", - 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 7e66300fe..86d9581af 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", @@ -32,12 +31,11 @@ export const lsTool: Tool = { }, }, defaultToolPolicy: "allowedWithoutPermission", - 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 995dbcd1a..e05241611 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", @@ -21,10 +20,8 @@ export const readCurrentlyOpenFileTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 eae37f603..2fc606883 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,10 +26,9 @@ export const readFileTool: Tool = { }, }, }, + 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"]], + }, defaultToolPolicy: "allowedWithoutPermission", - 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"]], - ), }; diff --git a/core/tools/definitions/requestRule.ts b/core/tools/definitions/requestRule.ts index b90c4d7df..30443506c 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,10 +59,9 @@ export const requestRuleTool: GetTool = ({ rules }) => ({ }, }, }, + systemMessageDescription: { + prefix: getRequestRuleSystemMessageDescription(rules), + exampleArgs: [["name", "rule_name"]], + }, defaultToolPolicy: "disabled", - systemMessageDescription: createSystemMessageExampleCall( - BuiltInToolNames.RequestRule, - getRequestRuleSystemMessageDescription(rules), - [["name", "rule_name"]], - ), }); diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index dea965f5b..b2dc74316 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 @@ -57,12 +56,11 @@ export const runTerminalCommandTool: Tool = { }, }, defaultToolPolicy: "allowedWithPermission", - 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 cdb0d127c..696d0e756 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; @@ -90,16 +89,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 filepath (relative to the root of the workspace) and 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 filepath (relative to the root of the workspace) and 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", @@ -109,6 +107,6 @@ ${SEARCH_AND_REPLACE_RULES} ]`, ], ], - ), + }, defaultToolPolicy: "allowedWithPermission", }; diff --git a/core/tools/definitions/searchWeb.ts b/core/tools/definitions/searchWeb.ts index 5d66e83e8..aa1555e15 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", @@ -27,9 +26,8 @@ export const searchWebTool: Tool = { }, }, defaultToolPolicy: "allowedWithoutPermission", - 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 ceaa241ec..14d6176f2 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,10 +19,8 @@ export const viewDiffTool: Tool = { properties: {}, }, }, + 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.`, + }, defaultToolPolicy: "allowedWithoutPermission", - 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.`, - [], - ), }; diff --git a/core/tools/definitions/viewRepoMap.ts b/core/tools/definitions/viewRepoMap.ts index 147ce132f..0d1d94046 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,10 +19,8 @@ export const viewRepoMapTool: Tool = { properties: {}, }, }, + 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.`, + }, defaultToolPolicy: "allowedWithPermission", - 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.`, - [], - ), }; diff --git a/core/tools/definitions/viewSubdirectory.ts b/core/tools/definitions/viewSubdirectory.ts index 0d45e922b..4ef686445 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,10 +25,9 @@ export const viewSubdirectoryTool: Tool = { }, }, }, + 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"]], + }, defaultToolPolicy: "allowedWithPermission", - 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"]], - ), }; 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/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/docs/customize/deep-dives/configuration.mdx b/docs/customize/deep-dives/configuration.mdx index c3aa770b9..666d3f27b 100644 --- a/docs/customize/deep-dives/configuration.mdx +++ b/docs/customize/deep-dives/configuration.mdx @@ -60,6 +60,11 @@ Example `config.ts` must export a `modifyConfig` function, like: + + The `slashCommands` array shown below is deprecated. For creating custom slash + commands, use [prompt files](./slash-commands) instead. + + ```ts title="config.ts" export function modifyConfig(config: Config): Config { config.slashCommands?.push({ @@ -82,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 81579d3ed..f62725f54 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -9,7 +9,14 @@ 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 + the deprecated `config.json` approach. The methods described below provide + better flexibility and are the actively maintained ways to add custom + commands. + ## Prompts @@ -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). ### MCP Server prompts diff --git a/docs/reference/json-reference.mdx b/docs/reference/json-reference.mdx index 7d6f40568..319b91e38 100644 --- a/docs/reference/json-reference.mdx +++ b/docs/reference/json-reference.mdx @@ -1,12 +1,18 @@ --- -title: "config.json Reference" +title: "config.json Reference (Deprecated)" +description: "Legacy configuration reference for config.json - use config.yaml instead" +noindex: true --- - - We recently introduced a new configuration format, `config.yaml`, to replace - `config.json`. See the `config.yaml` reference and migration guide - [here](/reference). - + + **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 + +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). @@ -468,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. @@ -529,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` 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/extensions/vscode/package.json b/extensions/vscode/package.json index 77b05c381..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.73", + "version": "1.1.75", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 6c32adedc..3861edcb7 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -43,9 +43,10 @@ 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 { 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, { @@ -202,8 +203,13 @@ export class VsCodeExtension { async ({ config: newConfig, configLoadInterrupted }) => { const autocompleteModel = newConfig?.selectedModelByRole.autocomplete; if ( - autocompleteModel && - isModelCapableOfNextEdit(autocompleteModel.model) + (autocompleteModel && + modelSupportsNextEdit( + autocompleteModel.capabilities, + autocompleteModel.model, + autocompleteModel.title, + )) || + isNextEditTest() ) { // Set up next edit window manager only for Continue team members await setupNextEditWindowManager(context); 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, ); 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 ( -
+
{ // 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.`, }, ); diff --git a/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx b/gui/src/components/mainInput/Lump/sections/PromptsSection.tsx index 10fb767b3..ce7721d8c 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 (
> = { 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/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index ae2839926..ca99d8fdd 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -80,7 +80,7 @@ export function ToolCallDiv({ if (shouldShowGroupedUI) { return ( -
+
( -
+
{renderToolCall(toolCallState)}
)); 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..e2f645858 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -25,9 +25,11 @@ 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"; +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 +37,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 +54,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) => { @@ -147,6 +154,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 = {}; @@ -169,10 +179,15 @@ export const streamNormalInput = createAsyncThunk< const baseSystemMessage = getBaseSystemMessage( state.session.mode, selectedChatModel, + activeTools, ); - const systemMessage = useSystemTools - ? addSystemMessageToolsToSystemMessage(baseSystemMessage, activeTools) + const systemMessage = systemToolsFramework + ? addSystemMessageToolsToSystemMessage( + systemToolsFramework, + baseSystemMessage, + activeTools, + ) : baseSystemMessage; const withoutMessageIds = state.session.history.map((item) => { @@ -185,7 +200,7 @@ export const streamNormalInput = createAsyncThunk< systemMessage, state.config.config.rules, state.ui.ruleSettings, - !useNativeTools, + systemToolsFramework, ); // TODO parallel tool calls will cause issues with this @@ -233,8 +248,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(); @@ -289,11 +304,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 +323,6 @@ export const streamNormalInput = createAsyncThunk< dispatch(setInactive()); } - await handleToolCallExecution(dispatch, getState); + await handleToolCallExecution(dispatch, getState, activeTools); }, ); 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, 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; } 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 = { 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; 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;