diff --git a/.github/workflows/jetbrains-release.yaml b/.github/workflows/jetbrains-release.yaml index 629fa97b7..9f20b8131 100644 --- a/.github/workflows/jetbrains-release.yaml +++ b/.github/workflows/jetbrains-release.yaml @@ -481,7 +481,7 @@ jobs: # Run Qodana inspections - name: Qodana - Code Inspection - uses: JetBrains/qodana-action@v2024.3.2 + uses: JetBrains/qodana-action@v2025.1.0 with: cache-default-branch-only: true diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 098bc1b6c..c490373a0 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -1,5 +1,6 @@ name: PR checks +# PR Checks run on all PRs to the main branch and must pass before merging. on: pull_request: branches: @@ -415,6 +416,30 @@ jobs: AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }} + package-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: ".nvmrc" + + - uses: actions/cache@v4 + with: + path: core/node_modules + key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }} + + - name: Install dependencies + run: | + cd packages/config-yaml + npm ci + + - name: Run config-yaml tests + run: | + cd packages/config-yaml + npm test + vscode-get-test-file-matrix: runs-on: ubuntu-latest needs: [install-root, install-vscode, install-config-yaml] @@ -551,7 +576,7 @@ jobs: path: extensions/vscode/e2e/storage vscode-e2e-tests: - name: ${{ matrix.test_file }} (${{ matrix.command }}) + name: ${{ matrix.test_file || 'unknown' }} (${{ matrix.command }}) needs: [ vscode-download-e2e-dependencies, @@ -652,6 +677,27 @@ jobs: name: e2e-failure-screenshots path: extensions/vscode/e2e/storage/screenshots + - name: Sanitize test file name + id: sanitize_filename + if: always() + run: | + FILENAME="${{ matrix.test_file }}" + SANITIZED_FILENAME="${FILENAME//\//-}" # Replace / with - using bash parameter expansion + echo "sanitized_test_file=${SANITIZED_FILENAME}" >> $GITHUB_OUTPUT + + - name: Find e2e log file + if: always() + run: | + echo "Searching for e2e.log file..." + find $GITHUB_WORKSPACE -name "e2e.log" -type f + + - name: Upload e2e logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-logs-${{ steps.sanitize_filename.outputs.sanitized_test_file || 'unknown' }}-${{ matrix.command == 'e2e:ci:run-yaml' && 'yaml' || 'json' }} + path: extensions/vscode/e2e.log + gui-tests: needs: [install-gui, install-core, install-config-yaml] runs-on: ubuntu-latest @@ -820,6 +866,7 @@ jobs: - install-vscode - vscode-checks - core-tests + - package-tests - vscode-get-test-file-matrix - vscode-package-extension - vscode-download-e2e-dependencies diff --git a/.gitignore b/.gitignore index 92cb4b852..2ca914069 100644 --- a/.gitignore +++ b/.gitignore @@ -83,16 +83,6 @@ ipython_config.py # pyenv .python-version -# pipenv -# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. -# However, in case of collaboration, if having platform-specific dependencies or dependencies -# having no cross-platform support, pipenv may install dependencies that don't work, or not -# install all needed dependencies. -#Pipfile.lock - -# PEP 582; used by e.g. github.com/David-OConnor/pyflow -__pypackages__/ - # Celery stuff celerybeat-schedule celerybeat.pid diff --git a/.idea/compiler.xml b/.idea/compiler.xml index b589d56e9..2a7499c2b 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -3,4 +3,7 @@ + + \ No newline at end of file diff --git a/.idea/scopes/Continue.xml b/.idea/scopes/Continue.xml index 3b28a76b1..d5943c932 100644 --- a/.idea/scopes/Continue.xml +++ b/.idea/scopes/Continue.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/binary/package-lock.json b/binary/package-lock.json index 7320d18fc..7f603ec07 100644 --- a/binary/package-lock.json +++ b/binary/package-lock.json @@ -51,7 +51,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.18", + "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -106,6 +106,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" @@ -2086,9 +2087,10 @@ } }, "node_modules/@octokit/endpoint": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz", - "integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==", + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz", + "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", + "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" @@ -2155,12 +2157,13 @@ } }, "node_modules/@octokit/request": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz", - "integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", + "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", + "license": "MIT", "dependencies": { - "@octokit/endpoint": "^9.0.1", - "@octokit/request-error": "^5.1.0", + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" }, @@ -2169,9 +2172,10 @@ } }, "node_modules/@octokit/request-error": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz", - "integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz", + "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", + "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "deprecation": "^2.0.0", diff --git a/core/.eslintrc.json b/core/.eslintrc.json index fbd390fb4..fa760cc0c 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -13,7 +13,7 @@ "@typescript-eslint/semi": "off", "eqeqeq": "error", "complexity": ["error", { "max": 36 }], - "max-lines-per-function": ["error", { "max": 472 }], + "max-lines-per-function": ["error", { "max": 500 }], "max-statements": ["error", { "max": 108 }], "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index c2cf5049b..bf0284cb2 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -103,7 +103,7 @@ export function postprocessCompletion({ } } - if (llm.model.includes("granite")) { + if (llm.model.includes("mercury") || llm.model.includes("granite")) { // Granite tends to repeat the start of the line in the completion output let prefixEnd = prefix.split("\n").pop(); if (prefixEnd) { @@ -123,13 +123,14 @@ export function postprocessCompletion({ // // If completion starts with multiple whitespaces, but the cursor is at the end of the line // // then it should probably be on a new line - // if ( - // (completion.startsWith(" ") || completion.startsWith("\t")) && - // !prefix.endsWith("\n") && - // (suffix.startsWith("\n") || suffix.trim().length === 0) - // ) { - // completion = "\n" + completion; - // } + if ( + llm.model.includes("mercury") && + (completion.startsWith(" ") || completion.startsWith("\t")) && + !prefix.endsWith("\n") && + (suffix.startsWith("\n") || suffix.trim().length === 0) + ) { + completion = "\n" + completion; + } // If prefix ends with space and so does completion, then remove the space from completion diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 2c8b12a31..b304c4058 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -87,9 +87,10 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { snippets, workspaceUris, ): [string, string] => { - - function getFileName(snippet: { uri: string, uniquePath: string }) { - return snippet.uri.startsWith("file://") ? snippet.uniquePath : snippet.uri + function getFileName(snippet: { uri: string; uniquePath: string }) { + return snippet.uri.startsWith("file://") + ? snippet.uniquePath + : snippet.uri; } if (snippets.length === 0) { @@ -135,6 +136,64 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = { }, }; +const mercuryMultifileFimTemplate: AutocompleteTemplate = { + compilePrefixSuffix: ( + prefix, + suffix, + filepath, + reponame, + snippets, + workspaceUris, + ): [string, string] => { + function getFileName(snippet: { uri: string; uniquePath: string }) { + return snippet.uri.startsWith("file://") + ? snippet.uniquePath + : snippet.uri; + } + + // Our current snippet format doesn't work well with mercury. We need to clean this up + snippets = []; + + if (snippets.length === 0) { + if (suffix.trim().length === 0 && prefix.trim().length === 0) { + return [ + `<|file_sep|>${getLastNUriRelativePathParts(workspaceUris, filepath, 2)}\n${prefix}`, + suffix, + ]; + } + return [prefix, suffix]; + } + + const relativePaths = getShortestUniqueRelativeUriPaths( + [ + ...snippets.map((snippet) => + "filepath" in snippet ? snippet.filepath : "file:///Untitled.txt", + ), + filepath, + ], + workspaceUris, + ); + + const otherFiles = snippets + .map((snippet, i) => { + if (snippet.type === AutocompleteSnippetType.Diff) { + return snippet.content; + } + + return `<|file_sep|>${getFileName(relativePaths[i])} \n${snippet.content}`; + }) + .join("\n\n"); + + return [ + `${otherFiles}${otherFiles ? "\n\n" : ""}<|file_sep|>${getFileName(relativePaths[relativePaths.length - 1])}\n<|fim_prefix|>${prefix}`, + suffix, + ]; + }, + template: (prefix: string, suffix: string): string => { + return `${prefix}<|fim_suffix|>${suffix}<|fim_middle|>`; + }, +}; + const codegemmaFimTemplate: AutocompleteTemplate = { template: "<|fim_prefix|>{{{prefix}}}<|fim_suffix|>{{{suffix}}}<|fim_middle|>", @@ -223,8 +282,9 @@ const codegeexFimTemplate: AutocompleteTemplate = { [...snippets.map((snippet) => snippet.filepath), filepath], workspaceUris, ); - const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1] - }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; + const baseTemplate = `###PATH:${ + relativePaths[relativePaths.length - 1] + }\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`; if (snippets.length === 0) { return `<|user|>\n${baseTemplate}<|assistant|>\n`; } @@ -358,6 +418,9 @@ export function getTemplateForModel(model: string): AutocompleteTemplate { // if (lowerCaseModel.includes("starcoder2")) { // return starcoder2FimTemplate; // } + if (lowerCaseModel.includes("mercury")) { + return mercuryMultifileFimTemplate; + } if (lowerCaseModel.includes("qwen") && lowerCaseModel.includes("coder")) { return qwenCoderFimTemplate; diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index 96e676ce6..c830ef10e 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -15,7 +15,12 @@ import { } from "../index.js"; import { GlobalContext } from "../util/GlobalContext.js"; -import { getAllAssistantFiles } from "./loadLocalAssistants.js"; +import { logger } from "../util/logger.js"; +import { + ASSISTANTS, + getAllDotContinueYamlFiles, + LoadAssistantFilesOptions, +} from "./loadLocalAssistants.js"; import LocalProfileLoader from "./profile/LocalProfileLoader.js"; import PlatformProfileLoader from "./profile/PlatformProfileLoader.js"; import { @@ -185,7 +190,11 @@ export class ConfigHandler { private async getNonPersonalHubOrg( org: OrganizationDescription, ): Promise { - const profiles = await this.getHubProfiles(org.id); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: false, + includeWorkspace: true, + }); + const profiles = [...(await this.getHubProfiles(org.id)), ...localProfiles]; return this.rectifyProfilesForOrg(org, profiles); } @@ -196,15 +205,21 @@ export class ConfigHandler { slug: undefined, }; private async getPersonalHubOrg() { - const allLocalProfiles = await this.getAllLocalProfiles(); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: true, + includeWorkspace: true, + }); const hubProfiles = await this.getHubProfiles(null); - const profiles = [...hubProfiles, ...allLocalProfiles]; + const profiles = [...hubProfiles, ...localProfiles]; return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, profiles); } private async getLocalOrg() { - const allLocalProfiles = await this.getAllLocalProfiles(); - return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, allLocalProfiles); + const localProfiles = await this.getLocalProfiles({ + includeGlobal: true, + includeWorkspace: true, + }); + return this.rectifyProfilesForOrg(this.PERSONAL_ORG_DESC, localProfiles); } private async rectifyProfilesForOrg( @@ -251,24 +266,41 @@ export class ConfigHandler { }; } - async getAllLocalProfiles() { + async getLocalProfiles(options: LoadAssistantFilesOptions) { /** * Users can define as many local assistants as they want in a `.continue/assistants` folder */ - const assistantFiles = await getAllAssistantFiles(this.ide); - const profiles = assistantFiles.map((assistant) => { - return new LocalProfileLoader( + const localProfiles: ProfileLifecycleManager[] = []; + + if (options.includeGlobal) { + localProfiles.push(this.globalLocalProfileManager); + } + + if (options.includeWorkspace) { + const assistantFiles = await getAllDotContinueYamlFiles( this.ide, - this.ideSettingsPromise, - this.controlPlaneClient, - this.llmLogger, - assistant, + { + ...options, + includeGlobal: false, // Because the global comes from above + }, + ASSISTANTS, ); - }); - const localAssistantProfiles = profiles.map( - (profile) => new ProfileLifecycleManager(profile, this.ide), - ); - return [this.globalLocalProfileManager, ...localAssistantProfiles]; + const profiles = assistantFiles.map((assistant) => { + return new LocalProfileLoader( + this.ide, + this.ideSettingsPromise, + this.controlPlaneClient, + this.llmLogger, + assistant, + ); + }); + const localAssistantProfiles = profiles.map( + (profile) => new ProfileLifecycleManager(profile, this.ide), + ); + localProfiles.push(...localAssistantProfiles); + } + + return localProfiles; } ////////////////// @@ -421,9 +453,14 @@ export class ConfigHandler { configLoadInterrupted: true, }; } - return await this.currentProfile.loadConfig( + const config = await this.currentProfile.loadConfig( this.additionalContextProviders, ); + + if (config.errors?.length) { + logger.warn("Errors loading config: ", config.errors); + } + return config; } async openConfigProfile(profileId?: string) { diff --git a/core/config/ProfileLifecycleManager.ts b/core/config/ProfileLifecycleManager.ts index d93ab9236..d0b830440 100644 --- a/core/config/ProfileLifecycleManager.ts +++ b/core/config/ProfileLifecycleManager.ts @@ -95,7 +95,10 @@ export class ProfileLifecycleManager { try { result = await this.profileLoader.doLoadConfig(); } catch (e) { - const message = e instanceof Error ? e.message : "Error loading config"; + const message = + e instanceof Error + ? `${e.message}\n${e.stack ? e.stack : ""}` + : "Error loading config"; result = { errors: [ { diff --git a/core/config/load.ts b/core/config/load.ts index 683fd6e4a..c9ab18925 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -486,7 +486,7 @@ async function intermediateToFinalConfig({ const cls = LLMClasses.find((c) => c.providerName === name); if (cls) { const llmOptions: LLMOptions = { - model: params?.model, + model: params?.model ?? "UNSPECIFIED", ...params, }; return new cls(llmOptions); diff --git a/core/config/loadLocalAssistants.ts b/core/config/loadLocalAssistants.ts index 7faa87d5e..18e24f58d 100644 --- a/core/config/loadLocalAssistants.ts +++ b/core/config/loadLocalAssistants.ts @@ -5,11 +5,12 @@ import { DEFAULT_IGNORE_FILETYPES, } from "../indexing/ignore"; import { walkDir } from "../indexing/walkDir"; -import { getGlobalAssistantsPath } from "../util/paths"; +import { getGlobalFolderWithName } from "../util/paths"; import { localPathToUri } from "../util/pathToUri"; import { joinPathsToUri } from "../util/uri"; -export const ASSISTANTS_FOLDER = ".continue/assistants"; +export const ASSISTANTS = "assistants"; +export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`; export function isLocalAssistantFile(uri: string): boolean { if (!uri.endsWith(".yaml") && !uri.endsWith(".yml")) { @@ -20,7 +21,7 @@ export function isLocalAssistantFile(uri: string): boolean { return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`); } -export async function getAssistantFilesFromDir( +export async function listYamlFilesInDir( ide: IDE, dir: string, ): Promise<{ path: string; content: string }[]> { @@ -53,21 +54,56 @@ export async function getAssistantFilesFromDir( } } -export async function getAllAssistantFiles( +export interface LoadAssistantFilesOptions { + includeGlobal: boolean; + includeWorkspace: boolean; +} + +export function getDotContinueSubDirs( ide: IDE, + options: LoadAssistantFilesOptions, + workspaceDirs: string[], + subDirName: string, +): string[] { + let fullDirs: string[] = []; + + // Workspace .continue/ + if (options.includeWorkspace) { + fullDirs = workspaceDirs.map((dir) => + joinPathsToUri(dir, ".continue", subDirName), + ); + } + + // ~/.continue/ + if (options.includeGlobal) { + fullDirs.push(localPathToUri(getGlobalFolderWithName(subDirName))); + } + + return fullDirs; +} + +/** + * This method searches in both ~/.continue and workspace .continue + * for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts + */ +export async function getAllDotContinueYamlFiles( + ide: IDE, + options: LoadAssistantFilesOptions, + subDirName: string, ): Promise<{ path: string; content: string }[]> { const workspaceDirs = await ide.getWorkspaceDirs(); - let assistantFiles: { path: string; content: string }[] = []; - let dirsToCheck = [ASSISTANTS_FOLDER]; - const fullDirs = workspaceDirs - .map((dir) => dirsToCheck.map((d) => joinPathsToUri(dir, d))) - .flat(); + // Get all directories to check for assistant files + const fullDirs = getDotContinueSubDirs( + ide, + options, + workspaceDirs, + subDirName, + ); - fullDirs.push(localPathToUri(getGlobalAssistantsPath())); - - assistantFiles = ( - await Promise.all(fullDirs.map((dir) => getAssistantFilesFromDir(ide, dir))) + // Get all assistant files from the directories + const assistantFiles = ( + await Promise.all(fullDirs.map((dir) => listYamlFilesInDir(ide, dir))) ).flat(); return await Promise.all( diff --git a/core/config/profile/LocalProfileLoader.ts b/core/config/profile/LocalProfileLoader.ts index 5b73a13e6..466243b3f 100644 --- a/core/config/profile/LocalProfileLoader.ts +++ b/core/config/profile/LocalProfileLoader.ts @@ -60,12 +60,14 @@ export default class LocalProfileLoader implements IProfileLoader { ideSettingsPromise: this.ideSettingsPromise, controlPlaneClient: this.controlPlaneClient, llmLogger: this.llmLogger, - overrideConfigJson: undefined, - overrideConfigYaml: undefined, - platformConfigMetadata: undefined, profileId: this.description.id, overrideConfigYamlByPath: this.overrideAssistantFile?.path, orgScopeId: null, + packageIdentifier: { + uriType: "file", + filePath: + this.overrideAssistantFile?.path ?? getPrimaryConfigFilePath(), + }, }); this.description.errors = result.errors; diff --git a/core/config/profile/PlatformProfileLoader.ts b/core/config/profile/PlatformProfileLoader.ts index 66bea1ef2..fd622bdd1 100644 --- a/core/config/profile/PlatformProfileLoader.ts +++ b/core/config/profile/PlatformProfileLoader.ts @@ -142,15 +142,17 @@ export default class PlatformProfileLoader implements IProfileLoader { ideSettingsPromise: this.ideSettingsPromise, controlPlaneClient: this.controlPlaneClient, llmLogger: this.llmLogger, - overrideConfigJson: undefined, overrideConfigYaml: this.configResult.config, - platformConfigMetadata: { - ownerSlug: this.ownerSlug, - packageSlug: this.packageSlug, - }, profileId: this.description.id, - overrideConfigYamlByPath: undefined, orgScopeId: this.orgScopeId, + packageIdentifier: { + uriType: "slug", + fullSlug: { + ownerSlug: this.ownerSlug, + packageSlug: this.packageSlug, + versionSlug: this.versionSlug, + }, + }, }); return { diff --git a/core/config/profile/doLoadConfig.ts b/core/config/profile/doLoadConfig.ts index 922b1af9a..1308ca2a0 100644 --- a/core/config/profile/doLoadConfig.ts +++ b/core/config/profile/doLoadConfig.ts @@ -5,6 +5,7 @@ import { ConfigResult, ConfigValidationError, ModelRole, + PackageIdentifier, } from "@continuedev/config-yaml"; import { @@ -29,37 +30,37 @@ import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths"; import { localPathOrUriToPath } from "../../util/pathToUri"; import { Telemetry } from "../../util/posthog"; import { TTS } from "../../util/tts"; +import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; import { loadContinueConfigFromJson } from "../load"; import { migrateJsonSharedConfig } from "../migrateSharedConfig"; import { rectifySelectedModelsFromGlobalContext } from "../selectedModels"; import { loadContinueConfigFromYaml } from "../yaml/loadYaml"; -import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles"; -import { PlatformConfigMetadata } from "./PlatformProfileLoader"; - -export default async function doLoadConfig({ - ide, - ideSettingsPromise, - controlPlaneClient, - llmLogger, - overrideConfigJson, - overrideConfigYaml, - platformConfigMetadata, - profileId, - overrideConfigYamlByPath, - orgScopeId, -}: { +export default async function doLoadConfig(options: { ide: IDE; ideSettingsPromise: Promise; controlPlaneClient: ControlPlaneClient; llmLogger: ILLMLogger; - overrideConfigJson: SerializedContinueConfig | undefined; - overrideConfigYaml: AssistantUnrolled | undefined; - platformConfigMetadata: PlatformConfigMetadata | undefined; + overrideConfigJson?: SerializedContinueConfig; + overrideConfigYaml?: AssistantUnrolled; profileId: string; - overrideConfigYamlByPath: string | undefined; + overrideConfigYamlByPath?: string; orgScopeId: string | null; + packageIdentifier: PackageIdentifier; }): Promise> { + const { + ide, + ideSettingsPromise, + controlPlaneClient, + llmLogger, + overrideConfigJson, + overrideConfigYaml, + profileId, + overrideConfigYamlByPath, + orgScopeId, + packageIdentifier, + } = options; + const workspaceConfigs = await getWorkspaceConfigs(ide); const ideInfo = await ide.getIdeInfo(); const uniqueId = await ide.getUniqueId(); @@ -89,10 +90,10 @@ export default async function doLoadConfig({ uniqueId, llmLogger, overrideConfigYaml, - platformConfigMetadata, controlPlaneClient, - configYamlPath, orgScopeId, + packageIdentifier, + workOsAccessToken, }); newConfig = result.config; errors = result.errors; @@ -236,13 +237,13 @@ export default async function doLoadConfig({ }; if (newConfig.analytics) { - await TeamAnalytics.setup( - newConfig.analytics, - uniqueId, - ideInfo.extensionVersion, - controlPlaneClient, - controlPlaneProxyInfo, - ); + // await TeamAnalytics.setup( + // newConfig.analytics, + // uniqueId, + // ideInfo.extensionVersion, + // controlPlaneClient, + // controlPlaneProxyInfo, + // ); } else { await TeamAnalytics.shutdown(); } diff --git a/core/config/types.ts b/core/config/types.ts index f168bcbaa..690f17165 100644 --- a/core/config/types.ts +++ b/core/config/types.ts @@ -403,6 +403,7 @@ declare global { | "generated" | "calling" | "done" + | "errored" | "canceled"; // Will exist only on "assistant" messages with tool calls diff --git a/core/config/yaml/LocalPlatformClient.ts b/core/config/yaml/LocalPlatformClient.ts new file mode 100644 index 000000000..3c8cc33bb --- /dev/null +++ b/core/config/yaml/LocalPlatformClient.ts @@ -0,0 +1,106 @@ +import { + FQSN, + PlatformClient, + SecretResult, + SecretType, +} from "@continuedev/config-yaml"; +import * as dotenv from "dotenv"; +import { IDE } from "../.."; +import { ControlPlaneClient } from "../../control-plane/client"; +import { getContinueDotEnv } from "../../util/paths"; +import { joinPathsToUri } from "../../util/uri"; + +export class LocalPlatformClient implements PlatformClient { + constructor( + private orgScopeId: string | null, + private readonly client: ControlPlaneClient, + private readonly ide: IDE, + ) {} + + private async findSecretInEnvFiles( + fqsn: FQSN, + ): Promise { + const secretValue = + this.findSecretInLocalEnvFile(fqsn) ?? + (await this.findSecretInWorkspaceEnvFiles(fqsn)); + + if (secretValue) { + return { + found: true, + fqsn, + value: secretValue, + secretLocation: { + secretName: fqsn.secretName, + secretType: SecretType.LocalEnv, + }, + }; + } + return undefined; + } + + private findSecretInLocalEnvFile(fqsn: FQSN): string | undefined { + try { + const dotEnv = getContinueDotEnv(); + return dotEnv[fqsn.secretName]; + } catch (error) { + console.warn( + `Error reading ~/.continue/.env file: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } + } + + private async findSecretInWorkspaceEnvFiles( + fqsn: FQSN, + ): Promise { + try { + const workspaceDirs = await this.ide.getWorkspaceDirs(); + + for (const folder of workspaceDirs) { + const envFilePath = joinPathsToUri(folder, ".env"); + try { + const fileExists = await this.ide.fileExists(envFilePath); + if (fileExists) { + const envContent = await this.ide.readFile(envFilePath); + const env = dotenv.parse(envContent); + if (fqsn.secretName in env) { + return env[fqsn.secretName]; + } + } + } catch (error) { + console.warn( + `Error reading workspace .env file at ${envFilePath}: ${error instanceof Error ? error.message : String(error)}`, + ); + // Continue to next workspace folder + } + } + + return undefined; + } catch (error) { + console.warn( + `Error searching workspace .env files: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } + } + + async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { + if (fqsns.length === 0) { + return []; + } + + const results = await this.client.resolveFQSNs(fqsns, this.orgScopeId); + + // For any secret that isn't found, look in .env files + for (let i = 0; i < results.length; i++) { + if (!results[i]?.found) { + const secretFromEnv = await this.findSecretInEnvFiles(fqsns[i]); + if (secretFromEnv?.found) { + results[i] = secretFromEnv; + } + } + } + + return results; + } +} diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 1a8e4b17c..85e94bbb2 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -1,20 +1,18 @@ -import fs from "node:fs"; - import { AssistantUnrolled, + BLOCK_TYPES, ConfigResult, ConfigValidationError, - FQSN, isAssistantUnrolledNonNullable, MCPServer, ModelRole, - PlatformClient, + PackageIdentifier, RegistryClient, Rule, - SecretResult, - unrollAssistantFromContent, + unrollAssistant, validateConfigYaml, } from "@continuedev/config-yaml"; +import { dirname } from "node:path"; import { ContinueConfig, @@ -39,29 +37,15 @@ import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandF import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles"; import { allTools } from "../../tools"; import { GlobalContext } from "../../util/GlobalContext"; -import { getConfigYamlPath } from "../../util/paths"; -import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; import { modifyAnyConfigWithSharedConfig } from "../sharedConfig"; import { getControlPlaneEnvSync } from "../../control-plane/env"; +import { logger } from "../../util/logger"; +import { getCleanUriPath } from "../../util/uri"; +import { getAllDotContinueYamlFiles } from "../loadLocalAssistants"; +import { LocalPlatformClient } from "./LocalPlatformClient"; import { llmsFromModelConfig } from "./models"; -export class LocalPlatformClient implements PlatformClient { - constructor( - private orgScopeId: string | null, - private readonly client: ControlPlaneClient, - ) {} - - async resolveFQSNs(fqsns: FQSN[]): Promise<(SecretResult | undefined)[]> { - if (fqsns.length === 0) { - return []; - } - - const response = await this.client.resolveFQSNs(fqsns, this.orgScopeId); - return response; - } -} - function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { if (typeof rule === "string") { return { @@ -72,7 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { return { source: "rules-block", rule: rule.rule, - if: rule.if, + globs: rule.globs, name: rule.name, }; } @@ -91,35 +75,70 @@ function convertYamlMcpToContinueMcp( }; } -async function loadConfigYaml( - rawYaml: string, - overrideConfigYaml: AssistantUnrolled | undefined, - controlPlaneClient: ControlPlaneClient, - orgScopeId: string | null, - ideSettings: IdeSettings, -): Promise> { +async function loadConfigYaml(options: { + overrideConfigYaml: AssistantUnrolled | undefined; + controlPlaneClient: ControlPlaneClient; + orgScopeId: string | null; + ideSettings: IdeSettings; + ide: IDE; + packageIdentifier: PackageIdentifier; +}): Promise> { + const { + overrideConfigYaml, + controlPlaneClient, + orgScopeId, + ideSettings, + ide, + packageIdentifier, + } = options; + + // Add local .continue blocks + const allLocalBlocks: PackageIdentifier[] = []; + for (const blockType of BLOCK_TYPES) { + const localBlocks = await getAllDotContinueYamlFiles( + ide, + { includeGlobal: true, includeWorkspace: true }, + blockType, + ); + allLocalBlocks.push( + ...localBlocks.map((b) => ({ + uriType: "file" as const, + filePath: b.path, + })), + ); + } + + const rootPath = + packageIdentifier.uriType === "file" + ? dirname(getCleanUriPath(packageIdentifier.filePath)) + : undefined; + + logger.info( + `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`, + ); + let config = overrideConfigYaml ?? // This is how we allow use of blocks locally - (await unrollAssistantFromContent( - { - ownerSlug: "", - packageSlug: "", - versionSlug: "", - }, - rawYaml, - new RegistryClient( - await controlPlaneClient.getAccessToken(), - getControlPlaneEnvSync( - ideSettings.continueTestEnvironment, - ).CONTROL_PLANE_URL, - ), + (await unrollAssistant( + packageIdentifier, + new RegistryClient({ + accessToken: await controlPlaneClient.getAccessToken(), + apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment) + .CONTROL_PLANE_URL, + rootPath, + }), { currentUserSlug: "", onPremProxyUrl: null, orgScopeId, - platformClient: new LocalPlatformClient(orgScopeId, controlPlaneClient), + platformClient: new LocalPlatformClient( + orgScopeId, + controlPlaneClient, + ide, + ), renderSecrets: true, + injectBlocks: allLocalBlocks, }, )); @@ -148,25 +167,27 @@ async function loadConfigYaml( }; } -async function configYamlToContinueConfig({ - config, - ide, - ideSettings, - ideInfo, - uniqueId, - llmLogger, - platformConfigMetadata, - allowFreeTrial = true, -}: { +async function configYamlToContinueConfig(options: { config: AssistantUnrolled; ide: IDE; ideSettings: IdeSettings; ideInfo: IdeInfo; uniqueId: string; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; - allowFreeTrial: boolean; + workOsAccessToken: string | undefined; + allowFreeTrial?: boolean; }): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> { + let { + config, + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + allowFreeTrial, + } = options; + allowFreeTrial = allowFreeTrial ?? true; + const localErrors: ConfigValidationError[] = []; const continueConfig: ContinueConfig = { @@ -275,7 +296,6 @@ async function configYamlToContinueConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config: continueConfig, }); @@ -431,44 +451,39 @@ async function configYamlToContinueConfig({ return { config: continueConfig, errors: localErrors }; } -export async function loadContinueConfigFromYaml({ - ide, - ideSettings, - ideInfo, - uniqueId, - llmLogger, - overrideConfigYaml, - platformConfigMetadata, - controlPlaneClient, - configYamlPath, - orgScopeId, -}: { +export async function loadContinueConfigFromYaml(options: { ide: IDE; ideSettings: IdeSettings; ideInfo: IdeInfo; uniqueId: string; llmLogger: ILLMLogger; + workOsAccessToken: string | undefined; overrideConfigYaml: AssistantUnrolled | undefined; - platformConfigMetadata: PlatformConfigMetadata | undefined; controlPlaneClient: ControlPlaneClient; - configYamlPath: string | undefined; orgScopeId: string | null; + packageIdentifier: PackageIdentifier; }): Promise> { - const rawYaml = - overrideConfigYaml === undefined - ? fs.readFileSync( - configYamlPath ?? getConfigYamlPath(ideInfo.ideType), - "utf-8", - ) - : ""; + const { + ide, + ideSettings, + ideInfo, + uniqueId, + llmLogger, + workOsAccessToken, + overrideConfigYaml, + controlPlaneClient, + orgScopeId, + packageIdentifier, + } = options; - const configYamlResult = await loadConfigYaml( - rawYaml, + const configYamlResult = await loadConfigYaml({ overrideConfigYaml, controlPlaneClient, orgScopeId, ideSettings, - ); + ide, + packageIdentifier, + }); if (!configYamlResult.config || configYamlResult.configLoadInterrupted) { return { @@ -486,8 +501,7 @@ export async function loadContinueConfigFromYaml({ ideInfo, uniqueId, llmLogger, - platformConfigMetadata, - allowFreeTrial: true, + workOsAccessToken, }); // Apply shared config diff --git a/core/config/yaml/models.ts b/core/config/yaml/models.ts index 7b5994317..6e15787bc 100644 --- a/core/config/yaml/models.ts +++ b/core/config/yaml/models.ts @@ -9,7 +9,6 @@ import { } from "../.."; import { BaseLLM } from "../../llm"; import { LLMClasses } from "../../llm/llms"; -import { PlatformConfigMetadata } from "../profile/PlatformProfileLoader"; const AUTODETECT = "AUTODETECT"; @@ -32,14 +31,12 @@ async function modelConfigToBaseLLM({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { model: ModelConfig; uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { const cls = getModelClass(model); @@ -63,6 +60,7 @@ async function modelConfigToBaseLLM({ logger: llmLogger, uniqueId, title: model.name, + template: model.promptTemplates?.chatTemplate, promptTemplates: model.promptTemplates, baseChatSystemMessage: model.chatOptions?.baseSystemMessage, capabilities: { @@ -147,7 +145,6 @@ async function autodetectModels({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { llm: BaseLLM; @@ -156,7 +153,6 @@ async function autodetectModels({ uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { try { @@ -177,7 +173,6 @@ async function autodetectModels({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); }), @@ -195,7 +190,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }: { model: ModelConfig; @@ -203,7 +197,6 @@ export async function llmsFromModelConfig({ uniqueId: string; ideSettings: IdeSettings; llmLogger: ILLMLogger; - platformConfigMetadata: PlatformConfigMetadata | undefined; config: ContinueConfig; }): Promise { const baseLlm = await modelConfigToBaseLLM({ @@ -211,7 +204,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); if (!baseLlm) { @@ -226,7 +218,6 @@ export async function llmsFromModelConfig({ uniqueId, ideSettings, llmLogger, - platformConfigMetadata, config, }); return models; diff --git a/core/context/mcp/MCPConnection.ts b/core/context/mcp/MCPConnection.ts index 9abea3e12..dca630cc6 100644 --- a/core/context/mcp/MCPConnection.ts +++ b/core/context/mcp/MCPConnection.ts @@ -14,7 +14,7 @@ import { MCPTool, } from "../.."; -const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds +export const DEFAULT_MCP_TIMEOUT = 20_000; // 10 seconds class MCPConnection { public client: Client; @@ -30,7 +30,7 @@ class MCPConnection { public tools: MCPTool[] = []; public resources: MCPResource[] = []; - constructor(private readonly options: MCPOptions) { + constructor(public options: MCPOptions) { this.transport = this.constructTransport(options); this.client = new Client( @@ -139,7 +139,6 @@ class MCPConnection { this.transport = this.constructTransport(this.options); try { await this.client.connect(this.transport); - await this.client.close(); } catch (error) { // Allow the case where for whatever reason is already connected if ( diff --git a/core/context/mcp/MCPManagerSingleton.ts b/core/context/mcp/MCPManagerSingleton.ts index 2f5031c8c..d0d7c0991 100644 --- a/core/context/mcp/MCPManagerSingleton.ts +++ b/core/context/mcp/MCPManagerSingleton.ts @@ -1,6 +1,11 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { MCPOptions, MCPServerStatus } from "../.."; +import { + MCPOptions, + MCPServerStatus, + StdioOptions, + TransportOptions, +} from "../.."; import MCPConnection from "./MCPConnection"; export class MCPManagerSingleton { @@ -48,7 +53,17 @@ export class MCPManagerSingleton { // Remove any connections that are no longer in config Array.from(this.connections.entries()).forEach(([id, connection]) => { - if (!servers.find((s) => s.id === id)) { + if ( + !servers.find( + // Refresh the connection if TransportOptions changed + (s) => + s.id === id && + this.compareTransportOptions( + connection.options.transport, + s.transport, + ), + ) + ) { refresh = true; connection.abortController.abort(); void connection.client.close(); @@ -61,6 +76,12 @@ export class MCPManagerSingleton { if (!this.connections.has(server.id)) { refresh = true; this.connections.set(server.id, new MCPConnection(server)); + } else { + const conn = this.connections.get(server.id); + if (conn) { + // We need to update it. Some attributes may have changed, such as name, faviconUrl, etc. + conn.options = server; + } } }); @@ -70,6 +91,37 @@ export class MCPManagerSingleton { } } + private compareTransportOptions( + a: TransportOptions, + b: TransportOptions, + ): boolean { + if (a.type !== b.type) { + return false; + } + if (a.type === "stdio" && b.type === "stdio") { + return ( + a.command === b.command && + JSON.stringify(a.args) === JSON.stringify(b.args) && + this.compareEnv(a, b) + ); + } else if (a.type !== "stdio" && b.type !== "stdio") { + return a.url === b.url; + } + return false; + } + + private compareEnv(a: StdioOptions, b: StdioOptions): boolean { + const aEnv = a.env ?? {}; + const bEnv = b.env ?? {}; + const aKeys = Object.keys(aEnv); + const bKeys = Object.keys(bEnv); + + return ( + aKeys.length === bKeys.length && + aKeys.every((key) => aEnv[key] === bEnv[key]) + ); + } + async refreshConnection(serverId: string) { const connection = this.connections.get(serverId); if (!connection) { diff --git a/core/context/providers/HttpContextProvider.ts b/core/context/providers/HttpContextProvider.ts index bcca31177..284c539d4 100644 --- a/core/context/providers/HttpContextProvider.ts +++ b/core/context/providers/HttpContextProvider.ts @@ -1,7 +1,9 @@ +import isLocalhost from "is-localhost-ip"; import { ContextItem, ContextProviderDescription, ContextProviderExtras, + IDE, } from "../../index.js"; import { BaseContextProvider } from "../index.js"; @@ -14,6 +16,19 @@ class HttpContextProvider extends BaseContextProvider { renderInlineAs: "", }; + private async getWorkspacePath(ide: IDE, url: URL) { + try { + const currentFile = await ide.getCurrentFile(); + // `isLocalhost` actually also returns true for other local addresses, not just localhost + return await isLocalhost(url.hostname) ? + (await ide.getWorkspaceDirs()).find(workspaceDirectory => { + return currentFile?.path.startsWith(workspaceDirectory) + }) : undefined + } catch (e) { + return undefined; + } + } + override get description(): ContextProviderDescription { return { title: this.options.title || HttpContextProvider.description.title, @@ -34,7 +49,8 @@ class HttpContextProvider extends BaseContextProvider { query: string, extras: ContextProviderExtras, ): Promise { - const response = await extras.fetch(new URL(this.options.url), { + const parsedUrl = new URL(this.options.url) + const response = await extras.fetch(parsedUrl, { method: "POST", headers: { "Content-Type": "application/json", @@ -44,6 +60,7 @@ class HttpContextProvider extends BaseContextProvider { query: query || "", fullInput: extras.fullInput, options: this.options.options, + workspacePath: await this.getWorkspacePath(extras.ide, parsedUrl), }), }); diff --git a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts index a3dcc0f7e..c59ef7fc8 100644 --- a/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts +++ b/core/context/retrieval/pipelines/BaseRetrievalPipeline.ts @@ -68,7 +68,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { const cleanedTokens = [...tokens].join(" "); const trigrams = nlp.string.ngram(cleanedTokens, 3); - return trigrams; + return trigrams.map(this.escapeFtsQueryString); } private escapeFtsQueryString(query: string): string { @@ -84,9 +84,8 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline { return []; } - const tokensRaw = this.getCleanedTrigrams(args.query).join(" OR "); - const tokens = this.escapeFtsQueryString(tokensRaw); - + const tokens = this.getCleanedTrigrams(args.query).join(" OR "); + return await this.ftsIndex.retrieve({ n, text: tokens, diff --git a/core/core.ts b/core/core.ts index dc43785e6..21208970d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -57,6 +57,7 @@ import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton"; import { streamDiffLines } from "./edit/streamDiffLines"; import { shouldIgnore } from "./indexing/shouldIgnore"; import { walkDirCache } from "./indexing/walkDir"; +import { LLMError } from "./llm"; import { LLMLogger } from "./llm/logger"; import { llmStreamChat } from "./llm/streamChat"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; @@ -682,59 +683,44 @@ export class Core { } }); - on( - "tools/call", - async ({ data: { toolCall, selectedModelTitle }, messageId }) => { - const { config } = await this.configHandler.loadConfig(); - if (!config) { - throw new Error("Config not loaded"); - } + on("tools/call", async ({ data: { toolCall } }) => { + const { config } = await this.configHandler.loadConfig(); + if (!config) { + throw new Error("Config not loaded"); + } - const tool = config.tools.find( - (t) => t.function.name === toolCall.function.name, - ); + const tool = config.tools.find( + (t) => t.function.name === toolCall.function.name, + ); - if (!tool) { - throw new Error(`Tool ${toolCall.function.name} not found`); - } + if (!tool) { + throw new Error(`Tool ${toolCall.function.name} not found`); + } - if (!config.selectedModelByRole.chat) { - throw new Error("No chat model selected"); - } + if (!config.selectedModelByRole.chat) { + throw new Error("No chat model selected"); + } - // Define a callback for streaming output updates - const onPartialOutput = (params: { - toolCallId: string; - contextItems: ContextItem[]; - }) => { - this.messenger.send("toolCallPartialOutput", params); - }; + // Define a callback for streaming output updates + const onPartialOutput = (params: { + toolCallId: string; + contextItems: ContextItem[]; + }) => { + this.messenger.send("toolCallPartialOutput", params); + }; - const contextItems = await callTool( - tool, - JSON.parse(toolCall.function.arguments || "{}"), - { - ide: this.ide, - llm: config.selectedModelByRole.chat, - fetch: (url, init) => - fetchwithRequestOptions(url, init, config.requestOptions), - tool, - toolCallId: toolCall.id, - onPartialOutput, - }, - ); + return await callTool(tool, toolCall.function.arguments, { + ide: this.ide, + llm: config.selectedModelByRole.chat, + fetch: (url, init) => + fetchwithRequestOptions(url, init, config.requestOptions), + tool, + toolCallId: toolCall.id, + onPartialOutput, + }); + }); - if (tool.faviconUrl) { - contextItems.forEach((item) => { - item.icon = tool.faviconUrl; - }); - } - - return { contextItems }; - }, - ); - - on("isItemTooBig", async ({ data: { item, selectedModelTitle } }) => { + on("isItemTooBig", async ({ data: { item } }) => { return this.isItemTooBig(item); }); @@ -754,19 +740,16 @@ export class Core { private async isItemTooBig(item: ContextItemWithId) { const { config } = await this.configHandler.loadConfig(); - if (!config) { return false; } - - const llm = (await this.configHandler.loadConfig()).config - ?.selectedModelByRole.chat; - + + const llm = config?.selectedModelByRole.chat; if (!llm) { throw new Error("No chat model selected"); } - const tokens = countTokens(item.content); + const tokens = countTokens(item.content, llm.model); if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) { return true; @@ -838,7 +821,8 @@ export class Core { if ( uri.endsWith(".continuerc.json") || uri.endsWith(".prompt") || - uri.endsWith(SYSTEM_PROMPT_DOT_FILE) + uri.endsWith(SYSTEM_PROMPT_DOT_FILE) || + (uri.includes(".continue") && uri.endsWith(".yaml")) ) { await this.configHandler.reloadConfig(); } else if ( @@ -932,7 +916,6 @@ export class Core { query: string; fullInput: string; selectedCode: RangeInFile[]; - selectedModelTitle: string; }>, ) => { const { config } = await this.configHandler.loadConfig(); @@ -1050,25 +1033,23 @@ export class Core { this.indexingCancellationController.abort(); } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshDirs( - paths, - this.indexingCancellationController.signal, - )) { - let updateToSend = { ...update }; - // TODO reconsider this status overwrite? - // original goal was to not concern users with edge noncritical errors - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } + try { + for await (const update of (await this.codebaseIndexerPromise).refreshDirs( + paths, + this.indexingCancellationController.signal, + )) { + let updateToSend = { ...update }; - void this.messenger.request("indexProgress", updateToSend); - this.codebaseIndexingState = updateToSend; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; - if (update.status === "failed") { - void this.sendIndexingErrorTelemetry(update); + if (update.status === "failed") { + void this.sendIndexingErrorTelemetry(update); + } } + } catch (e: any) { + console.log(`Failed refreshing codebase index directories : ${e}`); + this.handleIndexingError(e); } this.messenger.send("refreshSubmenuItems", { @@ -1086,22 +1067,22 @@ export class Core { return; } this.indexingCancellationController = new AbortController(); - for await (const update of (await this.codebaseIndexerPromise).refreshFiles( - files, - )) { - let updateToSend = { ...update }; - if (update.status === "failed") { - updateToSend.status = "done"; - updateToSend.desc = "Indexing complete"; - updateToSend.progress = 1.0; - } + try{ + for await (const update of (await this.codebaseIndexerPromise).refreshFiles( + files, + )) { + let updateToSend = { ...update }; - void this.messenger.request("indexProgress", updateToSend); - this.codebaseIndexingState = updateToSend; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; - if (update.status === "failed") { - void this.sendIndexingErrorTelemetry(update); + if (update.status === "failed") { + void this.sendIndexingErrorTelemetry(update); + } } + } catch (e: any) { + console.log(`Failed refreshing codebase index files : ${e}`); + this.handleIndexingError(e); } this.messenger.send("refreshSubmenuItems", { @@ -1111,4 +1092,19 @@ export class Core { } // private + handleIndexingError(e: any) { + if (e instanceof LLMError) { + // Need to report this specific error to the IDE for special handling + this.messenger.request("reportError", e); + } + // broadcast indexing error + let updateToSend: IndexingProgressUpdate = { + progress: 0, + status: "failed", + desc: e.message, + }; + void this.messenger.request("indexProgress", updateToSend); + this.codebaseIndexingState = updateToSend; + void this.sendIndexingErrorTelemetry(updateToSend); + } } diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index 8092d7ab8..f88aeefc0 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -4,6 +4,7 @@ import { ILLM, Prediction, RuleWithSource, + ToolResultChatMessage, UserChatMessage, } from "../"; import { @@ -104,18 +105,18 @@ export async function* streamDiffLines({ // Rules will be included with edit prompt // If any rules are present this will result in using chat instead of legacy completion - const lastUserMessage: UserChatMessage | undefined = + const lastUserMessage = typeof prompt === "string" - ? { + ? ({ role: "user", content: prompt, - } - : (findLast(prompt, (msg) => msg.role === "user") as - | UserChatMessage - | undefined); + } as UserChatMessage) + : (findLast( + prompt, + (msg) => msg.role === "user" || msg.role === "tool", + ) as UserChatMessage | ToolResultChatMessage | undefined); const systemMessage = getSystemMessageWithRules({ - currentModel: llm.model, rules, userMessage: lastUserMessage, baseSystemMessage: undefined, diff --git a/core/index.d.ts b/core/index.d.ts index 2884798c2..e80bb8f32 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -1,4 +1,8 @@ -import { DataDestination, ModelRole, PromptTemplates } from "@continuedev/config-yaml"; +import { + DataDestination, + ModelRole, + PromptTemplates, +} from "@continuedev/config-yaml"; import Parser from "web-tree-sitter"; import { LLMConfigurationStatuses } from "./llm/constants"; import { GetGhTokenArgs } from "./protocol/ide"; @@ -153,6 +157,10 @@ export interface ModelInstaller { signal: AbortSignal, progressReporter?: (task: string, increment: number, total: number) => void, ): Promise; + + isInstallingModel( + modelName: string + ): Promise; } export type ContextProviderType = "normal" | "query" | "submenu"; @@ -428,6 +436,7 @@ export type ToolStatus = | "generating" | "generated" | "calling" + | "errored" | "done" | "canceled"; @@ -1211,6 +1220,7 @@ export type EditStatus = | "done"; export type ApplyStateStatus = + | "not-started" // Apply state created but not necessarily streaming | "streaming" // Changes are being applied to the file | "done" // All changes have been applied, awaiting user to accept/reject | "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed" @@ -1501,7 +1511,7 @@ export interface RuleWithSource { | "rules-block" | "json-systemMessage" | ".continuerules"; - if?: string; + globs?: string | string[]; rule: string; description?: string; ruleFile?: string; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index f0f1cd4bb..0bd1f57b6 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -7,6 +7,8 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js"; import { findUriInDirs, getUriPathBasename } from "../util/uri.js"; +import { LLMError } from "../llm/index.js"; +import { getRootCause } from "../util/errors.js"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js"; @@ -350,6 +352,10 @@ export class CodebaseIndexer { ): IndexingProgressUpdate { console.log("error when indexing: ", err); if (err instanceof Error) { + const cause = getRootCause(err); + if (cause instanceof LLMError) { + throw cause; + } return this.errorToProgressUpdate(err); } return { @@ -361,7 +367,8 @@ export class CodebaseIndexer { } private errorToProgressUpdate(err: Error): IndexingProgressUpdate { - let errMsg: string = `${err}`; + const cause = getRootCause(err); + let errMsg: string = `${cause}`; let shouldClearIndexes = false; // Check if any of the error regexes match diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 0bd7ba93a..cc9eef842 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -36,6 +36,7 @@ import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler"; import { runLanceMigrations, runSqliteMigrations } from "./migrations"; import type * as LanceType from "vectordb"; +import { LLMError } from "../../llm"; import { DocsCache, SiteIndexingResults } from "./DocsCache"; // Purposefully lowercase because lancedb converts @@ -421,6 +422,7 @@ export default class DocsService { return false; } + // eslint-disable-next-line max-statements async indexAndAdd( siteIndexingConfig: SiteIndexingConfig, forceReindex: boolean = false, @@ -506,6 +508,16 @@ export default class DocsService { try { await provider.embed(["continue-test-run"]); } catch (e) { + if (e instanceof LLMError) { + // Report the error to the IDE + this.messenger?.request("reportError", e); + } + this.handleStatusUpdate({ + ...fixedStatus, + description: `Failed to test embeddings connection. ${e}`, + status: "failed", + progress: 1, + }); console.error("Failed to test embeddings connection", e); return; } diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index 05c294f9d..92bf71266 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -95,6 +95,7 @@ const MODEL_SUPPORTS_IMAGES: string[] = [ "pixtral", "llama3.2", "llama-3.2", + "llama4" ]; function modelSupportsTools(modelDescription: ModelDescription) { @@ -175,7 +176,8 @@ function autodetectTemplateType(model: string): TemplateType | undefined { lower.includes("pplx") || lower.includes("gemini") || lower.includes("grok") || - lower.includes("moonshot") + lower.includes("moonshot") || + lower.includes("mercury") ) { return undefined; } diff --git a/core/llm/constants.ts b/core/llm/constants.ts index 8532aa33b..19b067d15 100644 --- a/core/llm/constants.ts +++ b/core/llm/constants.ts @@ -7,26 +7,6 @@ const DEFAULT_ARGS = { temperature: DEFAULT_TEMPERATURE, }; -const GPT_4_CTX_LEN = 128_000; - -const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = { - "gpt-3.5-turbo": 4096, - "gpt-3.5-turbo-0613": 4096, - "gpt-3.5-turbo-16k": 16_384, - "gpt-35-turbo-16k": 16_384, - "gpt-35-turbo-0613": 4096, - "gpt-35-turbo": 4096, - "gpt-4": 4096, - "gpt-4-32k": 32_000, - "gpt-4-turbo-preview": 32_000, - "gpt-4o": GPT_4_CTX_LEN, - "gpt-4o-mini": GPT_4_CTX_LEN, - "gpt-4-vision": GPT_4_CTX_LEN, - "gpt-4-0125-preview": GPT_4_CTX_LEN, - "gpt-4-1106-preview": GPT_4_CTX_LEN, -}; - -const TOKEN_BUFFER_FOR_SAFETY = 350; const PROXY_URL = "http://localhost:65433"; const DEFAULT_MAX_CHUNK_SIZE = 500; // 512 - buffer for safety (in case of differing tokenizers) @@ -38,12 +18,10 @@ export enum LLMConfigurationStatuses { } export { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, DEFAULT_MAX_CHUNK_SIZE, DEFAULT_MAX_TOKENS, PROXY_URL, - TOKEN_BUFFER_FOR_SAFETY, }; diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index 950ad2cbe..11701feb8 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -3,15 +3,16 @@ import { ChatMessage, RuleWithSource, TextMessagePart, + ToolResultChatMessage, UserChatMessage, } from "../"; import { findLast } from "../util/findLast"; import { normalizeToMessageParts } from "../util/messageContent"; -import { messageIsEmpty } from "./messages"; +import { isUserOrToolMsg } from "./messages"; import { getSystemMessageWithRules } from "./rules/getSystemMessageWithRules"; export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL = - "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts#L8"; + "https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts"; export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ @@ -57,14 +58,10 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\ of changes unless the user specifically asks for code only. `; -const CANCELED_TOOL_CALL_MESSAGE = - "This tool call was cancelled by the user. You should clarify next steps, as they don't wish for you to use this tool."; - export function constructMessages( history: ChatHistoryItem[], baseChatSystemMessage: string | undefined, rules: RuleWithSource[], - modelName: string, ): ChatMessage[] { const filteredHistory = history.filter( (item) => item.message.role !== "system", @@ -92,26 +89,22 @@ export function constructMessages( ...historyItem.message, content, }); - } else if (historyItem.toolCallState?.status === "canceled") { - // Canceled tool call - msgs.push({ - ...historyItem.message, - content: CANCELED_TOOL_CALL_MESSAGE, - }); } else { msgs.push(historyItem.message); } } - const userMessage = findLast(msgs, (msg) => msg.role === "user") as + const lastUserMsg = findLast(msgs, isUserOrToolMsg) as | UserChatMessage + | ToolResultChatMessage | undefined; + const systemMessage = getSystemMessageWithRules({ baseSystemMessage: baseChatSystemMessage ?? DEFAULT_CHAT_SYSTEM_MESSAGE, rules, - userMessage, - currentModel: modelName, + userMessage: lastUserMsg, }); + if (systemMessage.trim()) { msgs.unshift({ role: "system", @@ -119,16 +112,6 @@ export function constructMessages( }); } - // We dispatch an empty assistant chat message to the history on submission. Don't send it - const lastMessage = msgs.at(-1); - if ( - lastMessage && - lastMessage.role === "assistant" && - messageIsEmpty(lastMessage) - ) { - msgs.pop(); - } - // Remove the "id" from all of the messages return msgs.map((msg) => { const { id, ...rest } = msg as any; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index fbe532208..218343538 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -1,6 +1,6 @@ import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken"; -import { ChatMessage, MessageContent, MessagePart } from "../index.js"; +import { ChatMessage, MessageContent, MessagePart, Tool } from "../index.js"; import { renderChatMessage } from "../util/messageContent.js"; import { @@ -9,13 +9,13 @@ import { LlamaAsyncEncoder, } from "./asyncEncoder.js"; import { autodetectTemplateType } from "./autodetect.js"; -import { TOKEN_BUFFER_FOR_SAFETY } from "./constants.js"; import llamaTokenizer from "./llamaTokenizer.js"; import { addSpaceToAnyEmptyMessages, chatMessageIsEmpty, flattenMessages, - messageHasToolCalls, + isUserOrToolMsg, + messageHasToolCallId, } from "./messages.js"; interface Encoding { encode: Tiktoken["encode"]; @@ -124,6 +124,51 @@ function countTokens( } } +// https://community.openai.com/t/how-to-calculate-the-tokens-when-using-function-call/266573/10 +function countToolsTokens(tools: Tool[], modelName: string): number { + const count = (value: string) => + encodingForModel(modelName).encode(value).length; + + let numTokens = 12; + + for (const tool of tools) { + let functionTokens = count(tool.function.name); + if (tool.function.description) { + functionTokens += count(tool.function.description); + } + const props = tool.function.parameters?.properties; + if (props) { + for (const key in props) { + functionTokens += count(key); + const fields = props[key]; + if (fields) { + const fieldType = fields["type"]; + const fieldDesc = fields["description"]; + const fieldEnum = fields["enum"]; + if (fieldType && typeof fieldType === "string") { + functionTokens += 2; + functionTokens += count(fieldType); + } + if (fieldDesc && typeof fieldDesc === "string") { + functionTokens += 2; + functionTokens += count(fieldDesc); + } + if (fieldEnum && Array.isArray(fieldEnum)) { + functionTokens -= 3; + for (const e of fieldEnum) { + functionTokens += 3; + functionTokens += typeof e === "string" ? count(e) : 5; + } + } + } + } + } + numTokens += functionTokens; + } + + return numTokens + 12; +} + function countChatMessageTokens( modelName: string, chatMessage: ChatMessage, @@ -131,8 +176,38 @@ function countChatMessageTokens( // Doing simpler, safer version of what is here: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb // every message follows <|im_start|>{role/name}\n{content}<|end|>\n - const TOKENS_PER_MESSAGE: number = 4; - return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE; + const BASE_TOKENS = 4; + const TOOL_CALL_EXTRA_TOKENS = 10; + const TOOL_OUTPUT_EXTRA_TOKENS = 10; + let tokens = BASE_TOKENS; + + if (chatMessage.content) { + tokens += countTokens(chatMessage.content, modelName); + } + + if ("toolCalls" in chatMessage && chatMessage.toolCalls) { + for (const call of chatMessage.toolCalls) { + tokens += TOOL_CALL_EXTRA_TOKENS; + tokens += countTokens(JSON.stringify(call), modelName); // TODO hone this + } + } + + if (chatMessage.role === "thinking") { + if (chatMessage.redactedThinking) { + tokens += countTokens(chatMessage.redactedThinking, modelName); + } + if (chatMessage.signature) { + tokens += countTokens(chatMessage.signature, modelName); + } + } + + if (chatMessage.role === "tool") { + tokens += TOOL_OUTPUT_EXTRA_TOKENS; // safety + if (chatMessage.toolCallId) { + tokens += countTokens(chatMessage.toolCallId, modelName); + } + } + return tokens; } function pruneLinesFromTop( @@ -193,6 +268,20 @@ function pruneStringFromTop( return encoding.decode(tokens.slice(tokens.length - maxTokens)); } +const MAX_TOKEN_SAFETY_BUFFER = 1000; +const TOKEN_SAFETY_PROPORTION = 0.02; +function getTokenCountingBufferSafety(contextLength: number) { + return Math.min( + MAX_TOKEN_SAFETY_BUFFER, + contextLength * TOKEN_SAFETY_PROPORTION, + ); +} + +const MIN_RESPONSE_TOKENS = 1000; +function getMinResponseTokens(maxTokens: number) { + return Math.min(MIN_RESPONSE_TOKENS, maxTokens); +} + function pruneRawPromptFromTop( modelName: string, contextLength: number, @@ -200,184 +289,36 @@ function pruneRawPromptFromTop( tokensForCompletion: number, ): string { const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; + contextLength - + tokensForCompletion - + getTokenCountingBufferSafety(contextLength); return pruneStringFromTop(modelName, maxTokens, prompt); } -function pruneRawPromptFromBottom( - modelName: string, - contextLength: number, - prompt: string, - tokensForCompletion: number, -): string { - const maxTokens = - contextLength - tokensForCompletion - TOKEN_BUFFER_FOR_SAFETY; - return pruneStringFromBottom(modelName, maxTokens, prompt); -} - -function summarize(message: ChatMessage): string { - return `${renderChatMessage(message).substring(0, 100)}...`; -} - -function pruneChatHistory( - modelName: string, - msgs: ChatMessage[], - contextLength: number, - tokensForCompletion: number, -): ChatMessage[] { - // Move system message to 2nd to last to give it priority - const systemMessage = msgs.find((msg) => msg.role === "system"); - const chatHistory: ChatMessage[] = msgs.filter( - (msg) => msg.role !== "system", - ); - if (systemMessage) { - chatHistory.splice(-1, 0, systemMessage); - } - - let totalTokens = - tokensForCompletion + - chatHistory.reduce((acc, message) => { - return acc + countChatMessageTokens(modelName, message); - }, 0); - - // 0. Prune any messages that take up more than 1/3 of the context length - const zippedMessagesAndTokens: [ChatMessage, number][] = []; - - // Zipped ChatMessage with its token counts - chatHistory.forEach((message) => { - const zippedItem: [ChatMessage, number] = [ - message, - countTokens(message.content, modelName), - ]; - zippedMessagesAndTokens.push(zippedItem); - }); - - const zippedLongerThanOneThird = zippedMessagesAndTokens.filter( - ([_message, tokens]: [ChatMessage, number]) => tokens > contextLength / 3, - ); - - zippedLongerThanOneThird.sort( - ( - [_messageA, tokensA]: [ChatMessage, number], - [_messageB, tokensB]: [ChatMessage, number], - ) => { - return tokensB - tokensA; - }, - ); - - const longerThanOneThird = zippedLongerThanOneThird.map( - ([message, _token]: [ChatMessage, number]) => message, - ); - const distanceFromThird = zippedLongerThanOneThird.map( - ([_message, token]: [ChatMessage, number]) => token - contextLength / 3, - ); - - for (let i = 0; i < longerThanOneThird.length; i++) { - // Prune line-by-line from the top - const message = longerThanOneThird[i]; - const content = renderChatMessage(message); - const deltaNeeded = totalTokens - contextLength; - const delta = Math.min(deltaNeeded, distanceFromThird[i]); - message.content = pruneStringFromTop( - modelName, - countTokens(message.content, modelName) - delta, - content, - ); - totalTokens -= delta; - } - - // 1. Replace beyond last 5 messages with summary - let i = 0; - while (totalTokens > contextLength && i < chatHistory.length - 5) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message), modelName); - message.content = summarize(message); - i++; - } - - // 2. Remove entire messages until the last 5 - while (chatHistory.length > 5 && totalTokens > contextLength) { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); - } - - // 3. Truncate message in the last 5, except last 1 - i = 0; - while ( - totalTokens > contextLength && - chatHistory.length > 0 && - i < chatHistory.length - 1 - ) { - const message = chatHistory[i]; - totalTokens -= countTokens(message.content, modelName); - totalTokens += countTokens(summarize(message), modelName); - message.content = summarize(message); - i++; - } - - // 4. Remove entire messages in the last 5, except last 1 - while (totalTokens > contextLength && chatHistory.length > 1) { - // If tool call/response detected prune both (can't have response with no call) - // TODO prune lines from tool response before pruning both messages - if ( - chatHistory.length > 2 && - messageHasToolCalls(chatHistory[0]) && - chatHistory[1].role === "tool" - ) { - const firstMessage = chatHistory.shift()!; - const secondMessage = chatHistory.shift()!; - totalTokens -= countTokens(firstMessage.content, modelName); - totalTokens -= countTokens(secondMessage.content, modelName); - } else { - const message = chatHistory.shift()!; - totalTokens -= countTokens(message.content, modelName); - } - } - - // 5. Truncate last message - if (totalTokens > contextLength && chatHistory.length > 0) { - const message = chatHistory[0]; - message.content = pruneRawPromptFromTop( - modelName, - contextLength, - renderChatMessage(message), - tokensForCompletion, - ); - totalTokens = contextLength; - } - - // put system message back if applicable - if ( - chatHistory.length > 1 && - chatHistory[chatHistory.length - 2].role === "system" - ) { - const movedSystemMessage = chatHistory.splice(-2, 1)[0]; - chatHistory.unshift(movedSystemMessage); - } - - return chatHistory; -} - +/* + Goal: reconcile chat messages with available context length + Guidelines: + - Always keep last user message, system message, and tools + - Never allow tool output without the corresponding tool call + - Remove older messages first +*/ function compileChatMessages({ modelName, msgs, contextLength, maxTokens, supportsImages, + tools, }: { modelName: string; msgs: ChatMessage[]; contextLength: number; maxTokens: number; supportsImages: boolean; + tools?: Tool[]; }): ChatMessage[] { let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); - msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); - - msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - // If images not supported, convert MessagePart[] to string if (!supportsImages) { for (const msg of msgsCopy) { @@ -388,15 +329,118 @@ function compileChatMessages({ } } - const history = pruneChatHistory( - modelName, - msgsCopy, - contextLength, - maxTokens + TOKEN_BUFFER_FOR_SAFETY, - ); + // Extract system message + const systemMsg = msgsCopy.find((msg) => msg.role === "system"); + msgsCopy = msgsCopy.filter((msg) => msg.role !== "system"); - const flattenedHistory = flattenMessages(history); + // Remove any empty messages or non-user/tool trailing messages + msgsCopy = msgsCopy.filter((msg) => !chatMessageIsEmpty(msg)); + msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); + + while (msgsCopy.length > 1) { + if (isUserOrToolMsg(msgsCopy.at(-1))) { + break; + } + msgsCopy.pop(); + } + + const lastUserOrToolMsg = msgsCopy.pop(); + if (!lastUserOrToolMsg || !isUserOrToolMsg(lastUserOrToolMsg)) { + throw new Error("Error parsing chat history: no user/tool message found"); // should never happen + } + + let lastToolCallsMsg: ChatMessage | undefined = undefined; + if (lastUserOrToolMsg.role === "tool") { + lastToolCallsMsg = msgsCopy.pop(); + if (!messageHasToolCallId(lastToolCallsMsg, lastUserOrToolMsg.toolCallId)) { + throw new Error( + `Error parsing chat history: tool call found to match tool output for id ${lastUserOrToolMsg.toolCallId}`, + ); + } + } + + let lastMessagesTokens = countChatMessageTokens(modelName, lastUserOrToolMsg); + if (lastToolCallsMsg) { + lastMessagesTokens += countChatMessageTokens(modelName, lastToolCallsMsg); + } + + // System message + let systemMsgTokens = 0; + if (systemMsg) { + systemMsgTokens = countChatMessageTokens(modelName, systemMsg); + } + + // Tools + let toolTokens = 0; + if (tools) { + toolTokens = countToolsTokens(tools, modelName); + } + + const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); + const minOutputTokens = getMinResponseTokens(maxTokens); + + let inputTokensAvailable = contextLength; + + // Leave space for output/safety + inputTokensAvailable -= countingSafetyBuffer; + inputTokensAvailable -= minOutputTokens; + + // Non-negotiable messages + inputTokensAvailable -= toolTokens; + inputTokensAvailable -= systemMsgTokens; + inputTokensAvailable -= lastMessagesTokens; + + // Make sure there's enough context for the non-excludable items + if (inputTokensAvailable < 0) { + throw new Error( + `Not enough context available to include the system message, last user message, and tools. + There must be at least ${minOutputTokens} tokens remaining for output. + Request had the following token counts: + - contextLength: ${contextLength} + - counting safety buffer: ${countingSafetyBuffer} + - tools: ~${toolTokens} + - system message: ~${systemMsgTokens} + - last user or tool + tool call message tokens: ~${lastMessagesTokens} + - max output tokens: ${maxTokens}`, + ); + } + + // Now remove messages till we're under the limit + let currentTotal = 0; + const historyWithTokens = msgsCopy.map((message) => { + const tokens = countChatMessageTokens(modelName, message); + currentTotal += tokens; + return { + ...message, + tokens, + }; + }); + + while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { + const message = historyWithTokens.shift()!; + currentTotal -= message.tokens; + + // At this point make sure no latent tool response without corresponding call + while (historyWithTokens[0]?.role === "tool") { + const message = historyWithTokens.shift()!; + currentTotal -= message.tokens; + } + } + + // Now reassemble + const reassembled: ChatMessage[] = []; + if (systemMsg) { + reassembled.push(systemMsg); + } + reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); + if (lastToolCallsMsg) { + reassembled.push(lastToolCallsMsg); + } + reassembled.push(lastUserOrToolMsg); + + // Flatten the messages (combines adjacent similar messages) + const flattenedHistory = flattenMessages(reassembled); return flattenedHistory; } @@ -404,7 +448,6 @@ export { compileChatMessages, countTokens, countTokensAsync, - flattenMessages, pruneLinesFromBottom, pruneLinesFromTop, pruneRawPromptFromTop, diff --git a/core/llm/index.ts b/core/llm/index.ts index e3d8004bb..1f7684652 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -40,7 +40,6 @@ import { modelSupportsImages, } from "./autodetect.js"; import { - CONTEXT_LENGTH_FOR_MODEL, DEFAULT_ARGS, DEFAULT_CONTEXT_LENGTH, DEFAULT_MAX_BATCH_SIZE, @@ -72,7 +71,7 @@ export class LLMError extends Error { } export function isModelInstaller(provider: any): provider is ModelInstaller { - return provider && typeof provider.installModel === "function"; + return provider && typeof provider.installModel === "function" && typeof provider.isInstallingModel === "function";; } type InteractionStatus = "in_progress" | "success" | "error" | "cancelled"; @@ -281,28 +280,6 @@ export abstract class BaseLLM implements ILLM { return Promise.resolve([]); } - private _compileChatMessages( - options: CompletionOptions, - messages: ChatMessage[], - ) { - let contextLength = this.contextLength; - if ( - options.model !== this.model && - options.model in CONTEXT_LENGTH_FOR_MODEL - ) { - contextLength = - CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH; - } - - return compileChatMessages({ - modelName: options.model, - msgs: messages, - contextLength, - maxTokens: options.maxTokens ?? DEFAULT_MAX_TOKENS, - supportsImages: this.supportsImages(), - }); - } - private _templatePromptLikeMessages(prompt: string): string { if (!this.templateMessages) { return prompt; @@ -879,7 +856,14 @@ export abstract class BaseLLM implements ILLM { completionOptions = this._modifyCompletionOptions(completionOptions); - const messages = this._compileChatMessages(completionOptions, _messages); + const messages = compileChatMessages({ + modelName: completionOptions.model, + msgs: _messages, + contextLength: this.contextLength, + maxTokens: completionOptions.maxTokens ?? DEFAULT_MAX_TOKENS, + supportsImages: this.supportsImages(), + tools: options.tools, + }); const prompt = this.templateMessages ? this.templateMessages(messages) diff --git a/core/llm/llm.test.ts b/core/llm/llm.test.ts index 2ce2d93b2..d1067a8bc 100644 --- a/core/llm/llm.test.ts +++ b/core/llm/llm.test.ts @@ -226,7 +226,11 @@ describe("LLM", () => { apiKey: process.env.MISTRAL_API_KEY, model: "codestral-latest", }), - { testFim: true, skip: false }, + { + testFim: true, + skip: false, + testToolCall: true, + }, ); testLLM( new Azure({ diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts index d9c3d5c58..131f45b14 100644 --- a/core/llm/llms/Docker.ts +++ b/core/llm/llms/Docker.ts @@ -1,3 +1,4 @@ +import { Mutex } from "async-mutex"; import { spawn } from "child_process"; import { LLMOptions, ModelInstaller } from "../../index.js"; import OpenAI from "./OpenAI.js"; @@ -47,6 +48,9 @@ class Docker extends OpenAI implements ModelInstaller { "deepseek-r1-distill-llama-8B-Q4": "ai/deepseek-r1-distill-llama:8B-Q4_K_M", }; + private static modelsBeingInstalled: Set = new Set(); + private static modelsBeingInstalledMutex = new Mutex(); + constructor(options: LLMOptions) { super(options); @@ -164,6 +168,16 @@ class Docker extends OpenAI implements ModelInstaller { ): Promise { const targetModel = this.modelMap[modelName] || modelName; + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + if (Docker.modelsBeingInstalled.has(modelName)) { + throw new Error(`Model '${modelName}' is already being installed.`); + } + Docker.modelsBeingInstalled.add(modelName); + } finally { + release(); + } + try { // Report starting the installation progressReporter?.(`Installing Docker model ${targetModel}`, 0, 100); @@ -184,12 +198,28 @@ class Docker extends OpenAI implements ModelInstaller { return { success: true, stdout, stderr }; } catch (error) { console.error(`Failed to install Docker model ${targetModel}:`, error); - // Fix: Type check the error before accessing message property +// Fix: Type check the error before accessing message property const errorMessage = error instanceof Error ? error.message : String(error); throw new Error( `Failed to install Docker model ${targetModel}: ${errorMessage}`, ); + } finally { + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + Docker.modelsBeingInstalled.delete(modelName); + } finally { + release(); + } + } + } + + public async isInstallingModel(modelName: string): Promise { + const release = await Docker.modelsBeingInstalledMutex.acquire(); + try { + return Docker.modelsBeingInstalled.has(modelName); + } finally { + release(); } } } diff --git a/core/llm/llms/Inception.ts b/core/llm/llms/Inception.ts index ef204fec1..2d75ca86b 100644 --- a/core/llm/llms/Inception.ts +++ b/core/llm/llms/Inception.ts @@ -18,13 +18,12 @@ import OpenAI from "./OpenAI.js"; class Inception extends OpenAI { static providerName = "inception"; static defaultOptions: Partial = { - apiBase: "https://copenhagen.api.inceptionlabs.ai/v1/", - model: "mercury-editor-small-experimental", + apiBase: "https://api.inceptionlabs.ai/v1/", + model: "mercury-coder-small", completionOptions: { temperature: 0.0, - maxTokens: 150, presencePenalty: 1.5, - stop: ["\n\n", "\n \n", "<|endoftext|>"], + stop: ["<|endoftext|>"], model: "mercury-editor-small-experimental", // Added model to fix TypeScript error }, }; @@ -45,13 +44,13 @@ class Inception extends OpenAI { body: JSON.stringify({ model: options.model, prompt: prefix, - suffix, - max_tokens: options.maxTokens, + suffix: suffix.trim() === "" ? "<|endoftext|>" : suffix, + max_tokens: options.maxTokens ?? 150, // Only want this for /fim, not chat temperature: options.temperature, top_p: options.topP, frequency_penalty: options.frequencyPenalty, presence_penalty: options.presencePenalty, - stop: options.stop, + stop: [...(options.stop ?? []), "\n\n", "\n \n"], stream: true, }), headers: { @@ -62,6 +61,9 @@ class Inception extends OpenAI { signal, }); for await (const chunk of streamSse(resp)) { + if (!chunk.choices[0]) { + continue; + } yield chunk.choices[0].text; } } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 173692de3..9db223b79 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -1,3 +1,4 @@ +import { Mutex } from "async-mutex"; import { JSONSchema7, JSONSchema7Object } from "json-schema"; import { @@ -138,6 +139,9 @@ class Ollama extends BaseLLM implements ModelInstaller { maxEmbeddingBatchSize: 64, }; + private static modelsBeingInstalled: Set = new Set(); + private static modelsBeingInstalledMutex = new Mutex(); + private fimSupported: boolean = false; constructor(options: LLMOptions) { @@ -592,33 +596,62 @@ class Ollama extends BaseLLM implements ModelInstaller { if (!modelInfo) { throw new Error(`'${modelName}' not found in the Ollama registry!`); } - const response = await fetch(this.getEndpoint("api/pull"), { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${this.apiKey}`, - }, - body: JSON.stringify({ name: modelName }), - signal, - }); - const reader = response.body?.getReader(); - //TODO: generate proper progress based on modelInfo size - while (true) { - const { done, value } = (await reader?.read()) || { - done: true, - value: undefined, - }; - if (done) { - break; + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + if (Ollama.modelsBeingInstalled.has(modelName)) { + throw new Error(`Model '${modelName}' is already being installed.`); } + Ollama.modelsBeingInstalled.add(modelName); + } finally { + release(); + } - const chunk = new TextDecoder().decode(value); - const lines = chunk.split("\n").filter(Boolean); - for (const line of lines) { - const data = JSON.parse(line); - progressReporter?.(data.status, data.completed, data.total); + try { + const response = await fetch(this.getEndpoint("api/pull"), { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ name: modelName }), + signal, + }); + + const reader = response.body?.getReader(); + //TODO: generate proper progress based on modelInfo size + while (true) { + const { done, value } = (await reader?.read()) || { + done: true, + value: undefined, + }; + if (done) { + break; + } + + const chunk = new TextDecoder().decode(value); + const lines = chunk.split("\n").filter(Boolean); + for (const line of lines) { + const data = JSON.parse(line); + progressReporter?.(data.status, data.completed, data.total); + } } + } finally { + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + Ollama.modelsBeingInstalled.delete(modelName); + } finally { + release(); + } + } + } + + public async isInstallingModel(modelName: string): Promise { + const release = await Ollama.modelsBeingInstalledMutex.acquire(); + try { + return Ollama.modelsBeingInstalled.has(modelName); + } finally { + release(); } } } diff --git a/core/llm/llms/SambaNova.ts b/core/llm/llms/SambaNova.ts index 4c2599529..db37c9276 100644 --- a/core/llm/llms/SambaNova.ts +++ b/core/llm/llms/SambaNova.ts @@ -9,20 +9,17 @@ class SambaNova extends OpenAI { }; private static MODEL_IDS: { [name: string]: string } = { - "qwen2.5-coder-32b": "Qwen2.5-Coder-32B-Instruct", + "llama4-scout": "Llama-4-Scout-17B-16E-Instruct", + "llama4-maverick": "Llama-4-Maverick-17B-128E-Instruct", "llama3.3-70b": "Meta-Llama-3.3-70B-Instruct", "llama3.1-8b": "Meta-Llama-3.1-8B-Instruct", - "llama3.1-70b": "Meta-Llama-3.1-70B-Instruct", "llama3.1-405b": "Meta-Llama-3.1-405B-Instruct", - "llama3.1-tulu-405b": "Llama-3.1-Tulu-3-405B", "llama3.2-1b": "Meta-Llama-3.2-1B-Instruct", "llama3.2-3b": "Meta-Llama-3.2-3B-Instruct", - "llama3.2-11b": "Llama-3.2-11B-Vision-Instruct", - "llama3.2-90b": "Llama-3.2-90B-Vision-Instruct", - "qwen2.5-72b": "Qwen2.5-72B-Instruct", - "qwq-32b": "QwQ-32B-Preview", + "qwq-32b": "QwQ-32B", "deepseek-r1-distill-llama-70b": "DeepSeek-R1-Distill-Llama-70B", "deepseek-r1": "DeepSeek-R1", + "deepseek-v3": "DeepSeek-V3-0324", }; protected _convertModelName(model: string) { diff --git a/core/llm/messages.test.ts b/core/llm/messages.test.ts index 6f5ba0a4c..3594eb679 100644 --- a/core/llm/messages.test.ts +++ b/core/llm/messages.test.ts @@ -1,5 +1,5 @@ import { ChatMessage } from ".."; -import { flattenMessages } from "./countTokens"; +import { flattenMessages } from "./messages"; describe("flattenMessages", () => { it("should return an empty array when given an empty array", () => { diff --git a/core/llm/messages.ts b/core/llm/messages.ts index d3f7ab477..8a0312766 100644 --- a/core/llm/messages.ts +++ b/core/llm/messages.ts @@ -49,6 +49,31 @@ export function addSpaceToAnyEmptyMessages( }); } +export function isUserOrToolMsg(msg: ChatMessage | undefined): boolean { + if (!msg) { + return false; + } + return msg.role === "user" || msg.role === "tool"; +} + +export function isToolMessageForId( + msg: ChatMessage | undefined, + toolCallId: string, +): boolean { + return !!msg && msg.role === "tool" && msg.toolCallId === toolCallId; +} + +export function messageHasToolCallId( + msg: ChatMessage | undefined, + toolCallId: string, +): boolean { + return ( + !!msg && + msg.role === "assistant" && + !!msg.toolCalls?.find((call) => call.id === toolCallId) + ); +} + export function chatMessageIsEmpty(message: ChatMessage): boolean { switch (message.role) { case "system": diff --git a/core/llm/rules/getSystemMessageWithRules.test.ts b/core/llm/rules/getSystemMessageWithRules.test.ts new file mode 100644 index 000000000..c1a7765ee --- /dev/null +++ b/core/llm/rules/getSystemMessageWithRules.test.ts @@ -0,0 +1,201 @@ +import { RuleWithSource, UserChatMessage } from "../.."; +import { getSystemMessageWithRules } from "./getSystemMessageWithRules"; + +describe("getSystemMessageWithRules", () => { + const baseSystemMessage = "Base system message"; + const tsRule: RuleWithSource = { + name: "TypeScript Rule", + rule: "Follow TypeScript best practices", + globs: "**/*.ts?(x)", + source: "rules-block", + }; + + // Rule without pattern (always active) + const generalRule: RuleWithSource = { + name: "General Rule", + rule: "Always write clear comments", + source: "rules-block", + }; + + // Rule with a different pattern + const pythonRule: RuleWithSource = { + name: "Python Rule", + rule: "Follow PEP 8 guidelines", + globs: "**/*.py", + source: "rules-block", + }; + + it("should not include pattern-matched rules when no file paths are mentioned", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [tsRule], + }); + + expect(result).toBe(baseSystemMessage); + }); + + it("should include general rules (without matches) regardless of file paths", () => { + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage: undefined, + rules: [generalRule], + }); + + expect(result).toBe(`${baseSystemMessage}\n\n${generalRule.rule}`); + }); + + it("should include only matching rules based on file paths", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```tsx Component.tsx\nexport const Component = () =>
Hello
;\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should include TS rule and general rule, but not Python rule + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include multiple matching rules", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```tsx Component.tsx\nexport const Component = () =>
Hello
;\n```\n```python test.py\nprint('hello')\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should include all rules + const expected = `${baseSystemMessage}\n\n${tsRule.rule}\n\n${pythonRule.rule}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should include only general rules when no paths match pattern-specific rules", () => { + const userMessage: UserChatMessage = { + role: "user", + content: "```ruby test.rb\nputs 'hello'\n```", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [tsRule, pythonRule, generalRule], + }); + + // Should only include the general rule + const expected = `${baseSystemMessage}\n\n${generalRule.rule}`; + expect(result).toBe(expected); + }); + + it("should NOT match with comma-separated glob patterns", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```", + }; + + // Rule with comma-separated glob patterns + const commaRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for comma-separated globs", + globs: "src/**/*.ts, tests/**/*.ts", + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [commaRule], + }); + + // With the current implementation, the comma-separated pattern is treated as a single string, + // so it won't match any of the file paths (minimatch doesn't support comma-separated patterns) + expect(result).toBe(baseSystemMessage); + }); + + it("should match with an array of glob patterns", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts tests/example.test.ts\ntest('should work', () => {});\n```\n```ts config/settings.ts\nconst config = {};\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // With our new implementation, the array of patterns should match both src/main.ts and tests/example.test.ts + expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`); + }); + + it("should match only patterns in the array", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts src/main.ts\nconsole.log('hello');\n```\n```ts config/settings.ts\nconst config = {};\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // Should match src/main.ts but not config/settings.ts + expect(result).toBe(`${baseSystemMessage}\n\n${arrayGlobRule.rule}`); + }); + + it("should not match any when no patterns in the array match", () => { + const userMessage: UserChatMessage = { + role: "user", + content: + "```ts config/settings.ts\nconst config = {};\n```\n```ruby test.rb\nputs 'hello'\n```", + }; + + // Rule with an array of glob patterns + const arrayGlobRule: RuleWithSource = { + name: "TypeScript Standards", + rule: "Use TypeScript best practices for array globs", + globs: ["src/**/*.ts", "tests/**/*.ts"], + source: "rules-block", + }; + + const result = getSystemMessageWithRules({ + baseSystemMessage, + userMessage, + rules: [arrayGlobRule], + }); + + // Should not match any file paths + expect(result).toBe(baseSystemMessage); + }); +}); diff --git a/core/llm/rules/getSystemMessageWithRules.ts b/core/llm/rules/getSystemMessageWithRules.ts index 2387145d4..dacd941bb 100644 --- a/core/llm/rules/getSystemMessageWithRules.ts +++ b/core/llm/rules/getSystemMessageWithRules.ts @@ -1,32 +1,52 @@ -import { RuleWithSource, UserChatMessage } from "../.."; +import { minimatch } from "minimatch"; +import { RuleWithSource, ToolResultChatMessage, UserChatMessage } from "../.."; import { renderChatMessage } from "../../util/messageContent"; import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks"; -import { isRuleActive } from "./isRuleActive"; + +/** + * Checks if a path matches any of the provided globs + */ +const matchesGlobs = ( + path: string, + globs: string | string[] | undefined, +): boolean => { + if (!globs) return true; + + if (typeof globs === "string") { + return minimatch(path, globs); + } + + if (Array.isArray(globs)) { + return globs.some((glob) => minimatch(path, glob)); + } + + return false; +}; export const getSystemMessageWithRules = ({ baseSystemMessage, userMessage, rules, - currentModel, }: { baseSystemMessage?: string; - userMessage: UserChatMessage | undefined; + userMessage: UserChatMessage | ToolResultChatMessage | undefined; rules: RuleWithSource[]; - currentModel: string; }) => { const filePathsFromMessage = userMessage ? extractPathsFromCodeBlocks(renderChatMessage(userMessage)) : []; let systemMessage = baseSystemMessage ?? ""; + for (const rule of rules) { - if ( - isRuleActive({ - rule, - activePaths: filePathsFromMessage, - currentModel, - }) - ) { + // A rule is active if it has no globs (applies to all files) + // or if at least one file path matches its globs + const hasNoGlobs = !rule.globs; + const matchesAnyFilePath = filePathsFromMessage.some((path) => + matchesGlobs(path, rule.globs), + ); + + if (hasNoGlobs || matchesAnyFilePath) { systemMessage += `\n\n${rule.rule}`; } } diff --git a/core/llm/rules/isRuleActive.test.ts b/core/llm/rules/isRuleActive.test.ts deleted file mode 100644 index 89e06e148..000000000 --- a/core/llm/rules/isRuleActive.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { RuleWithSource } from "../.."; -import { isRuleActive } from "./isRuleActive"; - -describe("isRuleActive", () => { - const rule: RuleWithSource = { - name: "My Rule", - rule: "Do no harm", - if: '${{ contains(current.model.model, "claude-3-7-sonnet") and glob("*.tsx") }}', - source: "rules-block", - }; - - it("should return false when activePaths is empty", () => { - expect( - isRuleActive({ - rule, - activePaths: [], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); - - it("should return false when no matching paths exist", () => { - expect( - isRuleActive({ - rule, - activePaths: ["test.py", "main.js"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); - - it("should return true when both conditions are met", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.tsx", "main.js"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(true); - }); - - it("should return false when only glob matches but model doesn't", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.tsx"], - currentModel: "gpt-4", - }), - ).toBe(false); - }); - - it("should return false when model matches but glob doesn't", () => { - expect( - isRuleActive({ - rule, - activePaths: ["Component.ts"], - currentModel: "claude-3-7-sonnet", - }), - ).toBe(false); - }); -}); diff --git a/core/llm/rules/isRuleActive.ts b/core/llm/rules/isRuleActive.ts deleted file mode 100644 index 9c80f67ec..000000000 --- a/core/llm/rules/isRuleActive.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { compileExpression } from "filtrex"; -import { minimatch } from "minimatch"; -import { RuleWithSource } from "../.."; - -const TEMPLATE_VAR_REGEX = /^\$\{\{(\s*.*?\s*)\}\}$/; - -const createGlobFunction = (activePaths: string[]) => { - return (pattern: string) => { - const result = activePaths.some((path) => minimatch(path, pattern)); - return result; - }; -}; - -const contains = (str: string, searchStr: string): boolean => { - return str.includes(searchStr); -}; - -const evaluateIf = ({ - condition, - activePaths, - currentModel, -}: { - condition: string; - activePaths: string[]; - currentModel: string; -}) => { - const expression = condition.match(TEMPLATE_VAR_REGEX)?.[1]?.trim(); - if (!expression) { - return true; - } - - try { - const evaluate = compileExpression(expression, { - extraFunctions: { - glob: createGlobFunction(activePaths), - contains, - }, - constants: { - "current.model.model": currentModel, - }, - }); - - return evaluate({}); - } catch (error) { - console.error("Error evaluating rule condition:", error); - return false; - } -}; - -export const isRuleActive = ({ - rule, - activePaths, - currentModel, -}: { - rule: RuleWithSource; - activePaths: string[]; - currentModel: string; -}): boolean => { - if (rule.if) { - return evaluateIf({ condition: rule.if, activePaths, currentModel }); - } - - return true; -}; diff --git a/core/llm/toolSupport.test.ts b/core/llm/toolSupport.test.ts index df18dc876..c92bb93ee 100644 --- a/core/llm/toolSupport.test.ts +++ b/core/llm/toolSupport.test.ts @@ -143,6 +143,36 @@ describe("PROVIDER_TOOL_SUPPORT", () => { }); }); + describe("mistral", () => { + const supportsFn = PROVIDER_TOOL_SUPPORT["mistral"]; + + it("should return true for supported models", () => { + expect(supportsFn("mistral-large-latest")).toBe(true); + expect(supportsFn("mistral-small-latest")).toBe(true); + expect(supportsFn("codestral-latest")).toBe(true); + expect(supportsFn("ministral-8b-latest")).toBe(true); + expect(supportsFn("ministral-3b-latest")).toBe(true); + expect(supportsFn("pixtral-12b-2409")).toBe(true); + expect(supportsFn("pixtral-large-latest")).toBe(true); + expect(supportsFn("open-mistral-nemo")).toBe(true); + }); + + it("should return false for other unsupported models", () => { + expect(supportsFn("mistral-saba-latest")).toBe(false); + expect(supportsFn("mistral-embed")).toBe(false); + expect(supportsFn("mistral-moderation-latest")).toBe(false); + expect(supportsFn("mistral-ocr-latest")).toBe(false); + expect(supportsFn("open-codestral-mamba")).toBe(false); + }); + + it("should handle case insensitivity", () => { + expect(supportsFn("MISTRAL-LARGE-LATEST")).toBe(true); + expect(supportsFn("CODESTRAL-LATEST")).toBe(true); + expect(supportsFn("MINISTRAL-8B-LATEST")).toBe(true); + expect(supportsFn("PIXTRAL-12B-2409")).toBe(true); + }); + }); + describe("ollama", () => { const supportsFn = PROVIDER_TOOL_SUPPORT["ollama"]; diff --git a/core/llm/toolSupport.ts b/core/llm/toolSupport.ts index 46abd83c0..ad5f65b75 100644 --- a/core/llm/toolSupport.ts +++ b/core/llm/toolSupport.ts @@ -79,6 +79,18 @@ export const PROVIDER_TOOL_SUPPORT: Record< return true; } }, + mistral: (model) => { + // https://docs.mistral.ai/capabilities/function_calling/ + return !model.toLowerCase().includes("mamba") && + [ + "codestral", + "mistral-large", + "mistral-small", + "pixtral", + "ministral", + "mistral-nemo" + ].some((part) => model.toLowerCase().includes(part)); + }, // https://ollama.com/search?c=tools ollama: (model) => { let modelName = ""; @@ -125,7 +137,9 @@ export const PROVIDER_TOOL_SUPPORT: Record< sambanova: (model) => { // https://docs.sambanova.ai/cloud/docs/capabilities/function-calling if ( - model.toLowerCase().startsWith("meta-llama-3") + model.toLowerCase().startsWith("meta-llama-3") || + model.toLowerCase().includes("llama-4") || + model.toLowerCase().includes("deepseek") ) { return true; } diff --git a/core/package-lock.json b/core/package-lock.json index b08d2f718..d1cc6a59a 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -16,7 +16,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.18", + "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -39,6 +39,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", + "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", "js-tiktoken": "^1.0.8", "jsdom": "^24.0.0", @@ -71,6 +72,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" @@ -2902,6 +2904,14 @@ "node": ">=14.21.3" } }, + "node_modules/@colors/colors": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz", + "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==", + "engines": { + "node": ">=0.1.90" + } + }, "node_modules/@continuedev/config-types": { "version": "1.0.14", "resolved": "https://registry.npmjs.org/@continuedev/config-types/-/config-types-1.0.14.tgz", @@ -2932,31 +2942,42 @@ "integrity": "sha512-/htL7p4li3zQSwn9bXkI23WRpZNklWTPzRSSG3Fd5gvYW8cizjhlf7OzeDdKxBfi1S0lpqMm0VwHlx3KjMKLpw==" }, "node_modules/@continuedev/openai-adapters": { - "version": "1.0.18", - "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.18.tgz", - "integrity": "sha512-VkYNhW+XKVXnn5FTLCGoJkcejkDWSCUvvIS6WnYusmS1+W5MJBFZQ5q6O/WA17U0UF9Xou81RWfCltYs4fXnyQ==", + "version": "1.0.19", + "resolved": "https://registry.npmjs.org/@continuedev/openai-adapters/-/openai-adapters-1.0.19.tgz", + "integrity": "sha512-9bfgTHPThRZAIn5T/zaWvKhMgVDFgpP3zr9DIkBT5THRNIrbbWd6VrguNEp9ASlX85ohNiXnk+jiC/FfFcH++w==", "dependencies": { "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", "@continuedev/fetch": "^1.0.3", + "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", + "uuid": "^11.1.0", "zod": "^3.24.2" } }, - "node_modules/@continuedev/openai-adapters/node_modules/@continuedev/config-yaml": { - "version": "1.0.86", - "resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.86.tgz", - "integrity": "sha512-X0H1iPunFcqxgTcoS87EvbqNHjfkfidWt8rQ2CU5A8iBzPSDI/jdkok0Bm0MjgzgZuXbR6GxvwMcZcOTiFw1nA==", - "dependencies": { - "@continuedev/config-types": "^1.0.14", - "yaml": "^2.6.1", - "zod": "^3.24.2" - }, + "node_modules/@continuedev/openai-adapters/node_modules/uuid": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", + "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], "bin": { - "config-yaml": "dist/cli.js" + "uuid": "dist/esm/bin/uuid" + } + }, + "node_modules/@dabh/diagnostics": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.3.tgz", + "integrity": "sha512-hrlQOIi7hAfzsMqlGSFyVucrx38O+j6wiGOf//H2ecvIEqYN4ADBSS2iLMh5UFyDunCNniUIPk/q3riFv45xRA==", + "dependencies": { + "colorspace": "1.1.x", + "enabled": "2.0.x", + "kuler": "^2.0.0" } }, "node_modules/@esbuild/darwin-arm64": { @@ -3845,9 +3866,10 @@ } }, "node_modules/@octokit/endpoint": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.5.tgz", - "integrity": "sha512-ekqR4/+PCLkEBF6qgj8WqJfvDq65RH85OAgrtnVp1mSxaXF03u2xW/hUdweGS5654IlC0wkNYC18Z50tSYTAFw==", + "version": "9.0.6", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-9.0.6.tgz", + "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", + "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" @@ -3917,12 +3939,13 @@ } }, "node_modules/@octokit/request": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.0.tgz", - "integrity": "sha512-9Bb014e+m2TgBeEJGEbdplMVWwPmL1FPtggHQRkV+WVsMggPtEkLKPlcVYm/o8xKLkpJ7B+6N8WfQMtDLX2Dpw==", + "version": "8.4.1", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", + "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", + "license": "MIT", "dependencies": { - "@octokit/endpoint": "^9.0.1", - "@octokit/request-error": "^5.1.0", + "@octokit/endpoint": "^9.0.6", + "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" }, @@ -3931,9 +3954,10 @@ } }, "node_modules/@octokit/request-error": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.0.tgz", - "integrity": "sha512-GETXfE05J0+7H2STzekpKObFe765O5dlAKUTLNGeH+x47z7JjXHfsHKo5z21D/o/IOZTUEI6nyWyR+bZVP/n5Q==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-5.1.1.tgz", + "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", + "license": "MIT", "dependencies": { "@octokit/types": "^13.1.0", "deprecation": "^2.0.0", @@ -4983,6 +5007,11 @@ "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", "dev": true }, + "node_modules/@types/triple-beam": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz", + "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==" + }, "node_modules/@types/uuid": { "version": "9.0.8", "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz", @@ -5629,8 +5658,7 @@ "node_modules/async": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", - "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", - "dev": true + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==" }, "node_modules/async-mutex": { "version": "0.5.0", @@ -5852,44 +5880,75 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, "node_modules/bare-events": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.0.tgz", - "integrity": "sha512-/E8dDe9dsbLyh2qrZ64PEPadOQ0F4gbl1sUJOrmph7xOiIxfY8vwab/4bFLh4Y88/Hk/ujKcrQKc+ps0mv873A==", + "version": "2.5.4", + "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.5.4.tgz", + "integrity": "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA==", + "license": "Apache-2.0", "optional": true }, "node_modules/bare-fs": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-2.3.5.tgz", - "integrity": "sha512-SlE9eTxifPDJrT6YgemQ1WGFleevzwY+XAP1Xqgl56HtcrisC2CHCZ2tq6dBpcH2TnNxwUEUGhweo+lrQtYuiw==", + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.1.3.tgz", + "integrity": "sha512-OeEZYIg+2qepaWLyphaOXHAHKo3xkM8y3BeGAvHdMN8GNWvEAU1Yw6rYpGzu/wDDbKxgEjVeVDpgGhDzaeMpjg==", + "license": "Apache-2.0", "optional": true, "dependencies": { - "bare-events": "^2.0.0", - "bare-path": "^2.0.0", - "bare-stream": "^2.0.0" + "bare-events": "^2.5.4", + "bare-path": "^3.0.0", + "bare-stream": "^2.6.4" + }, + "engines": { + "bare": ">=1.16.0" + }, + "peerDependencies": { + "bare-buffer": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + } } }, "node_modules/bare-os": { - "version": "2.4.4", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-2.4.4.tgz", - "integrity": "sha512-z3UiI2yi1mK0sXeRdc4O1Kk8aOa/e+FNWZcTiPB/dfTWyLypuE99LibgRaQki914Jq//yAWylcAt+mknKdixRQ==", - "optional": true + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz", + "integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==", + "license": "Apache-2.0", + "optional": true, + "engines": { + "bare": ">=1.14.0" + } }, "node_modules/bare-path": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-2.1.3.tgz", - "integrity": "sha512-lh/eITfU8hrj9Ru5quUp0Io1kJWIk1bTjzo7JH1P5dWmQ2EL4hFUlfI8FonAhSlgIfhn63p84CDY/x+PisgcXA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz", + "integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==", + "license": "Apache-2.0", "optional": true, "dependencies": { - "bare-os": "^2.1.0" + "bare-os": "^3.0.1" } }, "node_modules/bare-stream": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.4.2.tgz", - "integrity": "sha512-XZ4ln/KV4KT+PXdIWTKjsLY+quqCaEtqqtgGJVPw9AoM73By03ij64YjepK0aQvHSWDb6AfAZwqKaFu68qkrdA==", + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.6.5.tgz", + "integrity": "sha512-jSmxKJNJmHySi6hC42zlZnq00rga4jjxcgNZjY9N5WlOe/iOoGRtdwGsHzQv2RlH2KOYMwGUXhf2zXd32BA9RA==", + "license": "Apache-2.0", "optional": true, "dependencies": { - "streamx": "^2.20.0" + "streamx": "^2.21.0" + }, + "peerDependencies": { + "bare-buffer": "*", + "bare-events": "*" + }, + "peerDependenciesMeta": { + "bare-buffer": { + "optional": true + }, + "bare-events": { + "optional": true + } } }, "node_modules/base64-js": { @@ -6453,6 +6512,37 @@ "color-support": "bin.js" } }, + "node_modules/colorspace": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/colorspace/-/colorspace-1.1.4.tgz", + "integrity": "sha512-BgvKJiuVu1igBUF2kEjRCZXol6wiiGbY5ipL/oVPwm0BL9sIpMIzM8IK7vwuxIIzOXMV3Ey5w+vxhm0rR/TN8w==", + "dependencies": { + "color": "^3.1.3", + "text-hex": "1.0.x" + } + }, + "node_modules/colorspace/node_modules/color": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/color/-/color-3.2.1.tgz", + "integrity": "sha512-aBl7dZI9ENN6fUGC7mWpMTPNHmWUSNan9tuWN6ahh5ZLNk9baLJOnSMlrQkHcrfFgz2/RigjUVAjdx36VcemKA==", + "dependencies": { + "color-convert": "^1.9.3", + "color-string": "^1.6.0" + } + }, + "node_modules/colorspace/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/colorspace/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -7080,9 +7170,9 @@ } }, "node_modules/dotenv": { - "version": "16.4.7", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", - "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz", + "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==", "engines": { "node": ">=12" }, @@ -7173,6 +7263,11 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, + "node_modules/enabled": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz", + "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==" + }, "node_modules/encoding": { "version": "0.1.13", "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", @@ -8075,6 +8170,11 @@ "pend": "~1.2.0" } }, + "node_modules/fecha": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", + "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==" + }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -8201,6 +8301,11 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.2.tgz", "integrity": "sha512-AiwGJM8YcNOaobumgtng+6NHuOqC3A7MixFeDafM3X9cIUM+xUXoS5Vfgf+OihAYe20fxqNM9yPBXJzRtZ/4eA==" }, + "node_modules/fn.name": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz", + "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==" + }, "node_modules/follow-redirects": { "version": "1.15.9", "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz", @@ -9429,6 +9534,15 @@ "integrity": "sha512-z7CMFGNrENq5iFB9Bqo64Xk6Y9sg+epq1myIcdHaGnbMTYOxvzsEtdYqQUylB7LxfkvgrrjP32T6Ywciio9UIQ==", "optional": true }, + "node_modules/is-localhost-ip": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-localhost-ip/-/is-localhost-ip-2.0.0.tgz", + "integrity": "sha512-vlgs2cSgMOfnKU8c1ewgKPyum9rVrjjLLW2HBdL5i0iAJjOs8NY55ZBd/hqUTaYR0EO9CKZd3hVSC2HlIbygTQ==", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/is-map": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", @@ -10937,6 +11051,11 @@ "node": ">=6" } }, + "node_modules/kuler": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz", + "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==" + }, "node_modules/launchdarkly-eventsource": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/launchdarkly-eventsource/-/launchdarkly-eventsource-2.0.3.tgz", @@ -11096,6 +11215,22 @@ "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==" }, + "node_modules/logform": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz", + "integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==", + "dependencies": { + "@colors/colors": "1.6.0", + "@types/triple-beam": "^1.3.2", + "fecha": "^4.2.0", + "ms": "^2.1.1", + "safe-stable-stringify": "^2.3.1", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, "node_modules/long": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", @@ -12103,6 +12238,14 @@ "wrappy": "1" } }, + "node_modules/one-time": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz", + "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==", + "dependencies": { + "fn.name": "1.x.x" + } + }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -12924,9 +13067,10 @@ } }, "node_modules/prebuild-install/node_modules/tar-fs": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", - "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.2.tgz", + "integrity": "sha512-EsaAXwxmx8UB7FRKqeozqEPop69DXcmYwTQwXvyAPF352HJsPdkVhvTaDPYqfNgruveJIJy3TA2l+2zj8LJIJA==", + "license": "MIT", "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", @@ -13746,6 +13890,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -14224,6 +14376,14 @@ "node": ">=8" } }, + "node_modules/stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==", + "engines": { + "node": "*" + } + }, "node_modules/stack-utils": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", @@ -14530,16 +14690,17 @@ } }, "node_modules/tar-fs": { - "version": "3.0.6", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.6.tgz", - "integrity": "sha512-iokBDQQkUyeXhgPYaZxmczGPhnhXZ0CmrqI+MOb/WFGS9DW5wnfrLgtjUJBvz50vQ3qfRwJ62QVoCFu8mPVu5w==", + "version": "3.0.8", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.0.8.tgz", + "integrity": "sha512-ZoROL70jptorGAlgAYiLoBLItEKw/fUxg9BSYK/dF/GAGYFJOJJJMvjPAKDJraCXFwadD456FCuvLWgfhMsPwg==", + "license": "MIT", "dependencies": { "pump": "^3.0.0", "tar-stream": "^3.1.5" }, "optionalDependencies": { - "bare-fs": "^2.1.1", - "bare-path": "^2.1.0" + "bare-fs": "^4.0.1", + "bare-path": "^3.0.0" } }, "node_modules/tar-stream": { @@ -14707,6 +14868,11 @@ "b4a": "^1.6.4" } }, + "node_modules/text-hex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz", + "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==" + }, "node_modules/text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", @@ -14775,6 +14941,14 @@ "tree-sitter-wasms": "^0.1.11" } }, + "node_modules/triple-beam": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz", + "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==", + "engines": { + "node": ">= 14.0.0" + } + }, "node_modules/ts-api-utils": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", @@ -15582,6 +15756,66 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==" }, + "node_modules/winston": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/winston/-/winston-3.17.0.tgz", + "integrity": "sha512-DLiFIXYC5fMPxaRg832S6F5mJYvePtmO5G9v9IgUFPhXm9/GkXarH/TUrBAVzhTCzAj9anE/+GjrgXp/54nOgw==", + "dependencies": { + "@colors/colors": "^1.6.0", + "@dabh/diagnostics": "^2.0.2", + "async": "^3.2.3", + "is-stream": "^2.0.0", + "logform": "^2.7.0", + "one-time": "^1.0.0", + "readable-stream": "^3.4.0", + "safe-stable-stringify": "^2.3.1", + "stack-trace": "0.0.x", + "triple-beam": "^1.3.0", + "winston-transport": "^4.9.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz", + "integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==", + "dependencies": { + "logform": "^2.7.0", + "readable-stream": "^3.6.2", + "triple-beam": "^1.3.0" + }, + "engines": { + "node": ">= 12.0.0" + } + }, + "node_modules/winston-transport/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/winston/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", diff --git a/core/package.json b/core/package.json index ef8141c4a..3b92245c7 100644 --- a/core/package.json +++ b/core/package.json @@ -50,7 +50,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.18", + "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -73,6 +73,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", + "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", "js-tiktoken": "^1.0.8", "jsdom": "^24.0.0", @@ -105,6 +106,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 38a51c098..45a01a976 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -101,7 +101,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { query: string; fullInput: string; selectedCode: RangeInFile[]; - selectedModelTitle: string; }, ContextItemWithId[], ]; @@ -156,7 +155,6 @@ export type ToCoreFromIdeOrWebviewProtocol = { ]; "chatDescriber/describe": [ { - selectedModelTitle: string; text: string; }, string | undefined, @@ -203,15 +201,12 @@ export type ToCoreFromIdeOrWebviewProtocol = { "auth/getAuthUrl": [{ useOnboarding: boolean }, { url: string }]; "tools/call": [ - { toolCall: ToolCall; selectedModelTitle: string }, - { contextItems: ContextItem[] }, + { toolCall: ToolCall }, + { contextItems: ContextItem[]; errorMessage?: string }, ]; "clipboardCache/add": [{ content: string }, void]; "controlPlane/openUrl": [{ path: string; orgSlug: string | undefined }, void]; - isItemTooBig: [ - { item: ContextItemWithId; selectedModelTitle: string | undefined }, - boolean, - ]; + isItemTooBig: [{ item: ContextItemWithId }, boolean]; didChangeControlPlaneSessionInfo: [ { sessionInfo: ControlPlaneSessionInfo | undefined }, void, diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index 96342c4bf..88e7f779c 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -99,6 +99,7 @@ export type ToIdeFromWebviewOrCoreProtocol = { ControlPlaneSessionInfo | undefined, ]; logoutOfControlPlane: [undefined, void]; + reportError:[any, void]; closeSidebar: [undefined, void]; }; diff --git a/core/tools/builtIn.ts b/core/tools/builtIn.ts index 5e269c232..9f70b1a22 100644 --- a/core/tools/builtIn.ts +++ b/core/tools/builtIn.ts @@ -17,3 +17,5 @@ export enum BuiltInToolNames { } export const BUILT_IN_GROUP_NAME = "Built-In"; + +export const CLIENT_TOOLS = [BuiltInToolNames.EditExistingFile]; diff --git a/core/tools/callTool.ts b/core/tools/callTool.ts index c8b36aa90..d8eaf4ffd 100644 --- a/core/tools/callTool.ts +++ b/core/tools/callTool.ts @@ -130,40 +130,72 @@ async function callToolFromUri( } } +// Handles calls for core/non-client tools +// Returns an error context item if the tool call fails +// Note: Edit tool is handled on client export async function callTool( tool: Tool, - args: any, + callArgs: string, extras: ToolExtras, -): Promise { +): Promise<{ + contextItems: ContextItem[]; + errorMessage: string | undefined; +}> { + const args = JSON.parse(callArgs || "{}"); const uri = tool.uri ?? tool.function.name; - - switch (uri) { - case BuiltInToolNames.ReadFile: - return await readFileImpl(args, extras); - // Note: Custom GUI handling for edit - case BuiltInToolNames.CreateNewFile: - return await createNewFileImpl(args, extras); - case BuiltInToolNames.GrepSearch: - return await grepSearchImpl(args, extras); - case BuiltInToolNames.FileGlobSearch: - return await fileGlobSearchImpl(args, extras); - case BuiltInToolNames.RunTerminalCommand: - return await runTerminalCommandImpl(args, extras); - case BuiltInToolNames.SearchWeb: - return await searchWebImpl(args, extras); - case BuiltInToolNames.ViewDiff: - return await viewDiffImpl(args, extras); - case BuiltInToolNames.LSTool: - return await lsToolImpl(args, extras); - case BuiltInToolNames.ReadCurrentlyOpenFile: - return await readCurrentlyOpenFileImpl(args, extras); - case BuiltInToolNames.CreateRuleBlock: - return await createRuleBlockImpl(args, extras); - // case BuiltInToolNames.ViewRepoMap: - // return await viewRepoMapImpl(args, extras); - // case BuiltInToolNames.ViewSubdirectory: - // return await viewSubdirectoryImpl(args, extras); - default: - return await callToolFromUri(uri, args, extras); + try { + let contextItems: ContextItem[] = []; + switch (uri) { + case BuiltInToolNames.ReadFile: + contextItems = await readFileImpl(args, extras); + break; + case BuiltInToolNames.CreateNewFile: + contextItems = await createNewFileImpl(args, extras); + break; + case BuiltInToolNames.GrepSearch: + contextItems = await grepSearchImpl(args, extras); + break; + case BuiltInToolNames.FileGlobSearch: + contextItems = await fileGlobSearchImpl(args, extras); + break; + case BuiltInToolNames.RunTerminalCommand: + contextItems = await runTerminalCommandImpl(args, extras); + break; + case BuiltInToolNames.SearchWeb: + contextItems = await searchWebImpl(args, extras); + break; + case BuiltInToolNames.ViewDiff: + contextItems = await viewDiffImpl(args, extras); + break; + case BuiltInToolNames.LSTool: + contextItems = await lsToolImpl(args, extras); + break; + case BuiltInToolNames.ReadCurrentlyOpenFile: + contextItems = await readCurrentlyOpenFileImpl(args, extras); + break; + case BuiltInToolNames.CreateRuleBlock: + contextItems = await createRuleBlockImpl(args, extras); + break; + default: + contextItems = await callToolFromUri(uri, args, extras); + } + if (tool.faviconUrl) { + contextItems.forEach((item) => { + item.icon = tool.faviconUrl; + }); + } + return { + contextItems, + errorMessage: undefined, + }; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return { + contextItems: [], + errorMessage, + }; } } diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 5c7b69c64..c3a0846f4 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -4,32 +4,35 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export const createRuleBlock: Tool = { type: "function", displayTitle: "Create Rule Block", - wouldLikeTo: 'create a rule block for "{{{ rule_name }}}"', - isCurrently: 'creating a rule block for "{{{ rule_name }}}"', - hasAlready: 'created a rule block for "{{{ rule_name }}}"', + wouldLikeTo: 'create a rule block for "{{{ name }}}"', + isCurrently: 'creating a rule block for "{{{ name }}}"', + hasAlready: 'created a rule block for "{{{ name }}}"', readonly: false, isInstant: true, group: BUILT_IN_GROUP_NAME, function: { name: BuiltInToolNames.CreateRuleBlock, description: - "Creates a persistent rule that applies to all future conversations. " + - "Use for establishing ongoing code standards or preferences (e.g. 'use named exports', 'follow Google docstrings'). " + - "Not for one-time instructions. Rules are stored as YAML in `.continue/rules`.", + "Creates a persistent rule for all future conversations. For establishing code standards or preferences that should be applied consistently.", parameters: { type: "object", - required: ["rule_name", "rule_content"], + required: ["name", "rule"], properties: { - rule_name: { + name: { type: "string", description: "Short, descriptive name summarizing the rule's purpose (e.g. 'React Standards', 'Type Hints')", }, - rule_content: { + rule: { type: "string", description: "Clear, imperative instruction for future code generation (e.g. 'Use named exports', 'Add Python type hints'). Each rule should focus on one specific standard.", }, + globs: { + type: "string", + description: + "Optional file patterns to which this rule applies (e.g. ['**/*.{ts,tsx}'] or ['src/**/*.ts', 'tests/**/*.ts'])", + }, }, }, }, diff --git a/core/tools/definitions/editFile.ts b/core/tools/definitions/editFile.ts index 6ee5cee6b..9e2d60219 100644 --- a/core/tools/definitions/editFile.ts +++ b/core/tools/definitions/editFile.ts @@ -3,7 +3,7 @@ import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "../builtIn"; export interface EditToolArgs { filepath: string; - new_contents: string; + changes: string; } export const editFileTool: Tool = { @@ -20,16 +20,17 @@ export const editFileTool: Tool = { "Use this tool to edit an existing file. If you don't know the contents of the file, read it first.", parameters: { type: "object", - required: ["filepath", "new_contents"], + required: ["filepath", "changes"], properties: { filepath: { type: "string", description: "The path of the file to edit, relative to the root of the workspace.", }, - new_contents: { + changes: { type: "string", - description: "The new file contents", + description: + "Any modifications to the file, showing only needed changes. Do NOT wrap this in a codeblock. Use brief language-appropriate placeholders for large unmodified sections, e.g. '// ... rest of code here ...'", }, }, }, diff --git a/core/tools/implementations/createRuleBlock.test.ts b/core/tools/implementations/createRuleBlock.test.ts new file mode 100644 index 000000000..0491b8e26 --- /dev/null +++ b/core/tools/implementations/createRuleBlock.test.ts @@ -0,0 +1,78 @@ +import * as YAML from "yaml"; +import { createRuleBlockImpl } from "./createRuleBlock"; + +// Mock the extras parameter with necessary functions +const mockIde = { + getWorkspaceDirs: jest.fn().mockResolvedValue(["/"]), + writeFile: jest.fn().mockResolvedValue(undefined), + openFile: jest.fn().mockResolvedValue(undefined), +}; + +const mockExtras = { + ide: mockIde, +}; + +describe("createRuleBlockImpl", () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("should create a basic rule with name and rule content", async () => { + const args = { + name: "Test Rule", + rule: "Always write tests", + }; + + const result = await createRuleBlockImpl(args, mockExtras as any); + + // Verify that writeFile was called with the correct YAML + expect(mockIde.writeFile).toHaveBeenCalled(); + const yamlContent = mockIde.writeFile.mock.calls[0][1]; + const parsedYaml = YAML.parse(yamlContent); + + // Verify the structure of the YAML + expect(parsedYaml).toEqual({ + name: "Test Rule", + version: "0.0.1", + schema: "v1", + rules: [ + { + name: "Test Rule", + rule: "Always write tests", + }, + ], + }); + }); + + it("should create a rule with glob pattern", async () => { + const args = { + name: "TypeScript Rule", + rule: "Use interfaces for object shapes", + globs: "**/*.{ts,tsx}", + }; + + await createRuleBlockImpl(args, mockExtras as any); + + // Verify the YAML structure with globs + const yamlContent = mockIde.writeFile.mock.calls[0][1]; + const parsedYaml = YAML.parse(yamlContent); + expect(parsedYaml.rules[0]).toEqual({ + name: "TypeScript Rule", + rule: "Use interfaces for object shapes", + globs: "**/*.{ts,tsx}", + }); + }); + + it("should create a filename based on sanitized rule name", async () => { + const args = { + name: "Special Ch@racters & Spaces", + rule: "Handle special characters", + }; + + await createRuleBlockImpl(args, mockExtras as any); + + // Check that the filename is sanitized + const fileUri = mockIde.writeFile.mock.calls[0][0]; + expect(fileUri).toContain("special-chracters-spaces.yaml"); + }); +}); diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index 4e37f8818..87702e866 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -4,8 +4,9 @@ import { ToolImpl } from "."; import { joinPathsToUri } from "../../util/uri"; export interface CreateRuleBlockArgs { - rule_name: string; - rule_content: string; + name: string; + rule: string; + globs?: string; } export const createRuleBlockImpl: ToolImpl = async ( @@ -13,22 +14,24 @@ export const createRuleBlockImpl: ToolImpl = async ( extras, ) => { // Sanitize rule name for use in filename (remove special chars, replace spaces with dashes) - const safeRuleName = args.rule_name + const safeRuleName = args.name .toLowerCase() .replace(/[^a-z0-9\s-]/g, "") .replace(/\s+/g, "-"); - const ruleBlock: ConfigYaml = { - name: args.rule_name, - version: "0.0.1", - rules: [ - // This can be either a string or an object with {name, rule} - // Since we want a simple rule, we use the string format - args.rule_content, - ], + const ruleObject = { + name: args.name, + rule: args.rule, + ...(args.globs ? { globs: args.globs.trim() } : {}), + }; + + const ruleBlock: ConfigYaml = { + name: args.name, + version: "0.0.1", + schema: "v1", + rules: [ruleObject], }; - // Convert the rule block to YAML const ruleYaml = YAML.stringify(ruleBlock); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); @@ -44,9 +47,13 @@ export const createRuleBlockImpl: ToolImpl = async ( return [ { - name: "Rule Block Created", - description: `Created ${args.rule_name} rule`, - content: ruleYaml, + name: "New Rule Block", + description: "", // No description throws an error in the GUI + uri: { + type: "file", + value: rulesDirUri, + }, + content: "Rule created successfully", }, ]; }; diff --git a/core/util/errors.ts b/core/util/errors.ts new file mode 100644 index 000000000..02d87b00a --- /dev/null +++ b/core/util/errors.ts @@ -0,0 +1,13 @@ + +/** + * Recursively retrieves the root cause of an error by traversing through its `cause` property. + * + * @param err - The error object to analyze. It can be of any type. + * @returns The root cause of the error, or the original error if no further cause is found. + */ +export function getRootCause(err: any): any { + if (err.cause) { + return getRootCause(err.cause); + } + return err; +} \ No newline at end of file diff --git a/core/util/logger.ts b/core/util/logger.ts new file mode 100644 index 000000000..faaa05a43 --- /dev/null +++ b/core/util/logger.ts @@ -0,0 +1,14 @@ +import winston from "winston"; + +console.log("NODE_ENV", process.env.NODE_ENV); + +export const logger = winston.createLogger({ + level: "info", + format: winston.format.json(), + transports: [ + // Write all logs with importance level of `info` or higher to `info.log` + new winston.transports.File({ filename: "e2e.log", level: "info" }), + // Normal console.log behavior + new winston.transports.Console(), + ], +}); diff --git a/core/util/paths.ts b/core/util/paths.ts index a277d4977..1123b7eda 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -13,8 +13,16 @@ import Types from "../config/types"; dotenv.config(); -const CONTINUE_GLOBAL_DIR = - process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue"); +const CONTINUE_GLOBAL_DIR = (() => { + const configPath = process.env.CONTINUE_GLOBAL_DIR; + if (configPath) { + // Convert relative path to absolute paths based on current working directory + return path.isAbsolute(configPath) + ? configPath + : path.resolve(process.cwd(), configPath); + } + return path.join(os.homedir(), ".continue"); +})(); // export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config { // return config; @@ -376,12 +384,16 @@ export function getPromptLogsPath(): string { return path.join(getLogsDirPath(), "prompt.log"); } +export function getGlobalFolderWithName(name: string): string { + return path.join(getContinueGlobalPath(), name); +} + export function getGlobalPromptsPath(): string { - return path.join(getContinueGlobalPath(), "prompts"); + return getGlobalFolderWithName("prompts"); } export function getGlobalAssistantsPath(): string { - return path.join(getContinueGlobalPath(), "assistants"); + return getGlobalFolderWithName("assistants"); } export function readAllGlobalPromptFiles( diff --git a/docs/docs/agent/model-setup.mdx b/docs/docs/agent/model-setup.mdx index 89e1cdf7e..f0acf6f85 100644 --- a/docs/docs/agent/model-setup.mdx +++ b/docs/docs/agent/model-setup.mdx @@ -15,5 +15,6 @@ Currently the following providers are supported: - [Ollama](../customize/model-providers/top-level/ollama.mdx) - we recommend [Qwen 2.5 Coder 7b](https://hub.continue.dev/ollama/qwen2.5-coder-7b). Also see all Ollama models that support tools [here](https://ollama.com/search?c=tools). - [OpenAI](../customize/model-providers/top-level/openai.mdx) - we recommend [GPT-4o](https://hub.continue.dev/openai/gpt-4o) - [Gemini](../customize/model-providers/top-level/gemini.mdx) - we recommend [Gemini 2.0 Flash](https://hub.continue.dev/google/gemini-2.0-flash) +- [Mistral](../customize/model-providers/top-level/mistral.mdx) - we recommend [Codestral](https://hub.continue.dev/mistral/codestral) The best chat models generally support tool usage. See [recommended chat models](../customize/model-roles/chat.mdx#recommended-chat-models) for more. diff --git a/docs/docs/blocks/context-providers.md b/docs/docs/blocks/context-providers.md new file mode 100644 index 000000000..918ff3961 --- /dev/null +++ b/docs/docs/blocks/context-providers.md @@ -0,0 +1,21 @@ +--- +title: Context Blocks +sidebar_label: Context +description: Determine what internal information your AI assistant can access +keywords: [context, blocks, repositories, integration, knowledge base] +sidebar_position: 2 +--- + +These blocks determine what internal information your AI assistant can access: + +- **Connect to source repositories** and issues, CI/CD systems, wikis, and knowledge bases +- **Determine the scope** of what the AI can "see" when providing assistance +- **Customize** to match your specific development environment +- **Include proprietary code patterns** unique to your organization +- **Integrate data sources** to connect to any internal system with valuable context + +![Context Blocks Overview](/img/context-blocks-overview.png) + +## Learn More + +Learn more about context providers [here](../reference.md#context), and check out [this guide](../customize/tutorials/build-your-own-context-provider.mdx) to creating your own custom context provider. diff --git a/docs/docs/blocks/data.md b/docs/docs/blocks/data.md new file mode 100644 index 000000000..6e38e35e8 --- /dev/null +++ b/docs/docs/blocks/data.md @@ -0,0 +1,20 @@ +--- +title: Data Blocks +sidebar_label: Data +description: Help organizations capture and analyze AI assistant usage data +keywords: [data, blocks, analytics, metrics, storage, compliance] +sidebar_position: 7 +--- + +These help organizations capture and analyze AI assistant usage data: + +- **Analytics Integration**: Export metrics to observability platforms like Splunk or New Relic +- **Cloud Storage**: Store development data in S3/Azure Blob for model fine-tuning and auditing +- **Impact Measurement**: Track acceptance rates and productivity outcomes for ROI calculation +- **Compliance Reporting**: Generate audit trails for security and governance requirements + +![Data Blocks Overview](/img/data-blocks-overview.png) + +## Learn More + +You can read more about development data [here](../customize/deep-dives/development-data.md). Data destinations are configured in the [`data`](../reference.md#data) section of `config.yaml`. diff --git a/docs/docs/blocks/docs.md b/docs/docs/blocks/docs.md new file mode 100644 index 000000000..304a8c474 --- /dev/null +++ b/docs/docs/blocks/docs.md @@ -0,0 +1,19 @@ +--- +title: Docs Blocks +sidebar_label: Docs +description: Bring your documentation directly into the IDE +keywords: [docs, blocks, documentation, guidance, flow] +sidebar_position: 3 +--- + +This is how Continue brings your documentation directly into the IDE: + +- **Provide just-in-time guidance** without context switching +- **Reduce support burden** by making information discoverable +- **Keep developers in flow** by eliminating searches through multiple systems + +![Docs Blocks Overview](/img/docs-blocks-overview.png) + +## Learn More + +Learn more in the [@Docs deep dive](../customize/deep-dives/docs.mdx), and view [`docs`](../reference.md#docs) in the YAML Reference for more details. diff --git a/docs/docs/blocks/mcp.md b/docs/docs/blocks/mcp.md new file mode 100644 index 000000000..7201c4ac1 --- /dev/null +++ b/docs/docs/blocks/mcp.md @@ -0,0 +1,44 @@ +--- +title: MCP Blocks +--- + +title: MCP Blocks +sidebar_label: MCP +description: Model Context Protocol servers provide specialized functionality +keywords: [mcp, blocks, model context protocol, integrations, tools] +sidebar_position: 4 + +--- + +Model Context Protocol servers provide specialized functionality: + +- **Enable integration** with external tools and systems +- **Create extensible interfaces** for custom capabilities +- **Support complex interactions** with your development environment +- **Allow partners** to contribute specialized functionality +- **Connect to databases** to understand schema and data models during development + +![MCP Blocks Overview](/img/mcp-blocks-overview.png) + +## Learn More + +Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details. +description: Model Context Protocol servers provide specialized functionality +keywords: [mcp, blocks, model context protocol, integrations, tools] +sidebar_position: 4 + +--- + +Model Context Protocol servers provide specialized functionality: + +- Enable integration with external tools and systems +- Create extensible interfaces for custom capabilities +- Support more complex interactions with your development environment +- Allow partners to contribute specialized functionality +- Database Connectors: Understand schema and data models during development + +![MCP Blocks Overview](/img/mcp-blocks-overview.png) + +## Learn More + +Learn more in the [MCP deep dive](../customize/deep-dives/mcp.mdx), and view [`mcpServers`](../reference.md#mcpservers) in the YAML Reference for more details. diff --git a/docs/docs/blocks/models.md b/docs/docs/blocks/models.md new file mode 100644 index 000000000..bcf78be02 --- /dev/null +++ b/docs/docs/blocks/models.md @@ -0,0 +1,24 @@ +--- +title: Model Blocks +sidebar_label: Model +description: Foundation of the entire assistant experience offering specialized capabilities +keywords: [model, blocks, chat, edit, apply, autocomplete, embedding, reranker] +sidebar_position: 1 +--- + +These blocks form the foundation of the entire assistant experience, offering different specialized capabilities: + +- **[Chat](../customize/model-roles/chat.mdx)**: Power conversational interactions about code and provide detailed guidance +- **[Edit](../customize/model-roles/edit.mdx)**: Handle complex code transformations and refactoring tasks +- **[Apply](../customize/model-roles/apply.mdx)**: Execute targeted code modifications with high accuracy +- **[Autocomplete](../customize/model-roles/autocomplete.md)**: Provide real-time suggestions as developers type +- **[Embedding](../customize/model-roles/embeddings.mdx)**: Transform code into vector representations for semantic search +- **[Reranker](../customize/model-roles/reranking.mdx)**: Improve search relevance by ordering results based on semantic meaning + +![Model Blocks Overview](/img/model-blocks-overview.png) + +## Learn More + +Continue supports [many model providers](../customize/model-providers), including Anthropic, OpenAI, Gemini, Ollama, Amazon Bedrock, Azure, xAI, DeepSeek, and more. Models can have various roles like `chat`, `edit`, `apply`, `autocomplete`, `embed`, and `rerank`. + +Read more about roles [here](../customize/model-roles/intro.mdx) and view [`models`](../reference.md#models) in the YAML Reference. diff --git a/docs/docs/blocks/prompts.md b/docs/docs/blocks/prompts.md new file mode 100644 index 000000000..07cc9fb53 --- /dev/null +++ b/docs/docs/blocks/prompts.md @@ -0,0 +1,21 @@ +--- +title: Prompt Blocks +sidebar_label: Prompt +description: Specialized instructions that shape how models respond +keywords: [prompts, blocks, instructions, guidance, code review] +sidebar_position: 6 +--- + +These are the specialized instructions that shape how models respond: + +- **Define interaction patterns** for specific tasks or frameworks +- **Encode domain expertise** for particular technologies +- **Ensure consistent guidance** aligned with organizational practices +- **Can be shared and reused** across multiple assistants +- **Act as automated code reviewers** that ensure consistency across teams + +![Prompt Blocks Overview](/img/prompts-blocks-overview.png) + +## Learn More + +Prompt blocks have the same syntax as [prompt files](../customize/deep-dives/prompts.md). The `config.yaml` spec for `prompts` can be found [here](../reference.md#prompts). diff --git a/docs/docs/blocks/rules.md b/docs/docs/blocks/rules.md new file mode 100644 index 000000000..bc1baaf4b --- /dev/null +++ b/docs/docs/blocks/rules.md @@ -0,0 +1,19 @@ +--- +title: Rules Blocks +sidebar_label: Rules +description: Guardrails for your AI coding assistants +keywords: [rules, blocks, standards, practices, guardrails] +sidebar_position: 5 +--- + +Think of these as the guardrails for your AI coding assistants: + +- **Enforce company-specific coding standards** and security practices +- **Implement quality checks** that match your engineering culture +- **Create paved paths** for developers to follow organizational best practices + +![Rules Blocks Overview](/img/rules-blocks-overview.png) + +## Learn More + +Learn more in the [rules deep dive](../customize/deep-dives/rules.md), and view [`rules`](../reference.md#rules) in the YAML Reference for more details. diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index c6c87ae7a..ec30bb46e 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -17,12 +17,14 @@ Hub Assistants can be managed in [the Hub](https://hub.continue.dev). See [Editi Local user-level configuration is stored and can be edited in your home directory in `config.yaml`: -To open `config.yaml`, you can click the "gear" icon in the header of the Continue Chat sidebar to open the settings page, and then click `Open Assistant configuration` to open the file. When editing this file, you can see the available options suggested as you type, or check the reference below. - - `~/.continue/config.yaml` (MacOS / Linux) - `%USERPROFILE%\.continue\config.yaml` (Windows) -When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. +To open this `config.yaml`, you need to open the assistants dropdown in the top-right portion of the chat input. On that dropdown beside the "Local Assistant" option, select the cog icon. It will open the local `config.yaml`. + +![local-config-open-steps](/img/local-config-open-steps.png) + +When editing this file, you can see the available options suggested as you type, or check the reference below. When you save a config file from the IDE, Continue will automatically refresh to take into account your changes. A config file is automatically created the first time you use Continue, and always automatically generated with default values if it doesn't exist. See the full reference for `config.yaml` [here](../../reference.md). diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 94dec8a07..6113a0e33 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -1,5 +1,5 @@ --- -description: Learn how to customize the system prompt with a `.continuerules` file +description: Rules are used to provide instructions to the model for Chat, Edit, and Agent requests. keywords: [rules, .continuerules, system, prompt, message] --- @@ -7,7 +7,7 @@ keywords: [rules, .continuerules, system, prompt, message] Rules are used to provide instructions to the model for [Chat](../../chat/how-to-use-it.md), [Edit](../../edit/how-to-use-it.md), and [Agent](../../agent/how-to-use-it.md) requests. -Rules are **_NOT_** included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). +Rules are not included in most other requests, such as [autocomplete](./autocomplete.mdx) or [apply](../model-roles/apply.mdx). You can view the current rules by clicking the pen icon above the main toolbar: @@ -20,27 +20,36 @@ To form the system message, rules are joined with new lines, in the order they a Rules can be added to an Assistant on the Continue Hub. Explore available rules [here](https://hub.continue.dev/explore/rules), or [create your own](https://hub.continue.dev/new?type=block&blockType=rules) in the Hub. These blocks are defined using the [`config.yaml` syntax](../../reference.md#rules) and can also be created locally. :::info Automatically create local rule blocks -When in Agent mode, you can simply prompt the agent to create a rule for you. +When in Agent mode, you can simply prompt the agent to create a rule for you using the `builtin_create_rule_block` tool if enabled. -For example, you can say "Create a rule for this", and a rule will be created for you in `~/.continue/rules` based on your conversation. +For example, you can say "Create a rule for this", and a rule will be created for you in `.continue/rules` based on your conversation. ::: +### Syntax + Rules blocks can be simple text, or have the following properties: - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule - -Examples: +- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). ```yaml title="config.yaml" rules: + - Always annotate Python functions with their parameter and return types + + - name: TypeScript best practices + rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly. + globs: "**/*.{ts,tsx}" + + - name: TypeScript test patterns + rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking. + globs: + - "src/**/*.test.ts" + - "tests/**/*.ts" + - uses: myprofile/my-mood-setter with: - TONE: consise - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes - - name: Server-side components - rule: When writing Next.js React components, use server-side components where possible instead of client components. + TONE: concise ``` ## Chat System Message diff --git a/docs/docs/customize/model-providers/more/SambaNova.mdx b/docs/docs/customize/model-providers/more/SambaNova.mdx index 3d554006e..58197ae30 100644 --- a/docs/docs/customize/model-providers/more/SambaNova.mdx +++ b/docs/docs/customize/model-providers/more/SambaNova.mdx @@ -9,9 +9,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor ```yaml title="config.yaml" models: - - name: SambaNova Qwen2.5 coder + - name: SambaNova Llama 4 Scout provider: sambanova - model: qwen2.5-coder-32b + model: Llama-4-Scout-17B-16E-Instruct apiKey: ``` @@ -20,9 +20,9 @@ The SambaNova Cloud is a cloud platform for running large AI models with the wor { "models": [ { - "title": "SambaNova Qwen2.5 coder", + "title": "SambaNova Llama 4 Scout", "provider": "sambanova", - "model": "qwen2.5-coder-32b", + "model": "Llama-4-Scout-17B-16E-Instruct", "apiKey": "" } ] diff --git a/docs/docs/customize/model-providers/more/morph.mdx b/docs/docs/customize/model-providers/more/morph.mdx new file mode 100644 index 000000000..710fcccd5 --- /dev/null +++ b/docs/docs/customize/model-providers/more/morph.mdx @@ -0,0 +1,36 @@ +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + +# Morph + +Morph provides a fast apply model that helps you quickly and accurately apply code changes from chat suggestions to your files. It's optimized for speed and precision when integrating generated code into your existing codebase. You can sign up for Morph's generous free tier [here](https://morphllm.com/dashboard). Then, update your configuration file as follows: + + + + ```yaml title="config.yaml" + models: + - uses: morphllm/morph-v0 + with: + MORPH_API_KEY: ${{ secrets.MORPH_API_KEY }} + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Morph Fast Apply", + "provider": "openai", + "model": "morph-v0", + "apiKey": "", + "apiBase": "https://api.morphllm.com/v1/", + "roles": ["apply", "chat"], + "promptTemplates": { + "apply": "{{{ original_code }}}\n{{{ new_code }}}" + } + } + ] + } + ``` + + diff --git a/docs/docs/customize/model-providers/top-level/azure.mdx b/docs/docs/customize/model-providers/top-level/azure.mdx index 2c201d938..8202d5608 100644 --- a/docs/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/docs/customize/model-providers/top-level/azure.mdx @@ -143,7 +143,7 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de models: - name: GPT-4o Azure model: gpt-4o - provider: openai + provider: azure apiBase: https://just-an-example.openai.azure.com apiKey: env: @@ -157,7 +157,7 @@ For example, a Target URI of `https://just-an-example.openai.azure.com/openai/de { "title": "GPT-4o Azure", "model": "gpt-4o", - "provider": "openai", + "provider": "azure", "apiBase": "https://just-an-example.openai.azure.com", "deployment": "gpt-4o-july", "apiVersion": "2023-03-15-preview", diff --git a/docs/docs/customize/model-providers/top-level/inception.mdx b/docs/docs/customize/model-providers/top-level/inception.mdx new file mode 100644 index 000000000..625bfcc10 --- /dev/null +++ b/docs/docs/customize/model-providers/top-level/inception.mdx @@ -0,0 +1,81 @@ +--- +title: Inception +slug: ../inception +--- + +import TabItem from "@theme/TabItem"; +import Tabs from "@theme/Tabs"; + +:::info +You can get an API key from the [Inception Dashboard](https://platform.inceptionlabs.ai/dashboard/api-keys). +::: + +## Chat model + +We recommend configuring **Mercury Coder Small** as your chat model. + + + + ```yaml title="config.yaml" + models: + - uses: inceptionlabs/mercury-coder-small + with: + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Mercury Coder Small", + "provider": "inception", + "model": "mercury-coder-small", + "apiKey": "" + } + ] + } + ``` + + + +## Autocomplete model + +We also recommend configuring **Mercury Coder Small** as your autocomplete model. + + + + ```yaml title="config.yaml" + models: + - uses: inceptionlabs/mercury-coder-small + with: + INCEPTION_API_KEY: ${{ secrets.INCEPTION_API_KEY }} + ``` + + + ```json title="config.json" + { + "tabAutocompleteModel": [ + { + "title": "Mercury Coder Small", + "provider": "inception", + "model": "mercury-coder-small", + "apiKey": "" + } + ] + } + ``` + + + +## Embeddings model + +Inception currently does not offer any embeddings models. + +[Click here](../../model-roles/embeddings.mdx) to see a list of embeddings model providers. + +## Reranking model + +Inception currently does not offer any reranking models. + +[Click here](../../model-roles/reranking.mdx) to see a list of reranking model providers. diff --git a/docs/docs/customize/model-roles/apply.mdx b/docs/docs/customize/model-roles/apply.mdx index 040cdaa2e..6cce4acbc 100644 --- a/docs/docs/customize/model-roles/apply.mdx +++ b/docs/docs/customize/model-roles/apply.mdx @@ -1,18 +1,8 @@ ---- -title: Apply Role -description: Apply model role -keywords: [apply, model, role] -sidebar_position: 4 ---- - -import TabItem from "@theme/TabItem"; -import Tabs from "@theme/Tabs"; - When editing code, Chat and Edit model output often doesn't clearly align with existing code. A model with the `apply` role is used to generate a more precise diff to apply changes to a file. ## Recommended Apply models -We recommend [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can get an API key [here](https://app.relace.ai/settings/api-keys). +We recommend [Morph Fast Apply](https://morphllm.com) or [Relace's Instant Apply model](https://hub.continue.dev/relace/instant-apply) for the fastest Apply experience. You can sign up for Morph's free tier [here](https://morphllm.com/dashboard) or get a Relace API key [here](https://app.relace.ai/settings/api-keys). However, most Chat models can also be used for applying code changes. We recommend smaller/cheaper models for the task, such as Claude 3.5 Haiku. diff --git a/docs/docs/customize/model-roles/chat.mdx b/docs/docs/customize/model-roles/chat.mdx index 781ce37d9..7761114d2 100644 --- a/docs/docs/customize/model-roles/chat.mdx +++ b/docs/docs/customize/model-roles/chat.mdx @@ -18,7 +18,7 @@ In Continue, these models are used for normal [Chat](../../chat/how-to-use-it.md For the best overall Chat experience, you will want to use a 400B+ parameter model or one of the frontier models. -### Claude Sonnet 3.5 from Anthropic +### Claude Sonnet 3.7 from Anthropic Our current top recommendation is Claude 3.7 Sonnet from [Anthropic](../model-providers/top-level/anthropic.mdx). diff --git a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx index 1494680c0..d8bdc39be 100644 --- a/docs/docs/customize/tutorials/build-your-own-context-provider.mdx +++ b/docs/docs/customize/tutorials/build-your-own-context-provider.mdx @@ -47,7 +47,17 @@ Continue can retrieve context from a custom HTTP server that you create and serv Then, create a server that responds to requests as are made from [HttpContextProvider.ts](https://github.com/continuedev/continue/blob/main/core/context/providers/HttpContextProvider.ts). See the `hello` endpoint in [context_provider_server.py](https://github.com/continuedev/continue/blob/main/core/context/providers/context_provider_server.py) for an example that uses FastAPI. -The `"options"` property can be used to send additional parameters to your endpoint, which will be included in the request body. +The `"options"` property can be used to send additional parameters to your endpoint. The full request body has the following shape: + +```typescript +{ + query: string; + fullInput: string; + options: Record; + + workspacePath?: string; // Only provided if the server is local. +} +``` :::info The following methods for creating custom context providers are deprecated. We recommend using HTTP context providers, [MCP Servers](../context-providers.mdx#model-context-protocol), and [Prompts](../deep-dives/prompts.md) where possible. diff --git a/docs/docs/customize/tutorials/llama3.1.mdx b/docs/docs/customize/tutorials/llama3.1.mdx index bb65be947..23d7d38a9 100644 --- a/docs/docs/customize/tutorials/llama3.1.mdx +++ b/docs/docs/customize/tutorials/llama3.1.mdx @@ -153,7 +153,7 @@ Replicate makes it easy to host and run open-source AI with an API. SambaNova Cloud provides world record Llama3.1 70B/405B serving. -1. Create an account [here](https://cloud.sambanova.ai/) +1. Create an account [here](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ) 2. Copy your API key 3. Update your Continue config file like this: diff --git a/docs/docs/json-reference.md b/docs/docs/json-reference.md index 0fa8e2d25..897695b37 100644 --- a/docs/docs/json-reference.md +++ b/docs/docs/json-reference.md @@ -159,6 +159,8 @@ Parameters that control the behavior of text generation and completion settings. - `numThreads`: The number of threads used during the generation process. Available only for Ollama as `num_thread`. - `keepAlive`: For Ollama, this parameter sets the number of seconds to keep the model loaded after the last request, unloading it from memory if inactive (default: `1800` seconds, or 30 minutes). - `useMmap`: For Ollama, this parameter allows the model to be mapped into memory. If disabled can enhance response time on low end devices but will slow down the stream. +- `reasoning`: Enables thinking/reasoning for Anthropic Claude 3.7+ models. +- `reasoningBudgetTokens`: Sets budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. Example diff --git a/docs/docs/reference.md b/docs/docs/reference.md index ca794416a..3b360b7c8 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -32,7 +32,7 @@ Assistants can either explicitly define blocks - see [Properties](#properties) b ### Using Blocks -Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from https://hub.continue.dev. +Hub blocks and assistants are identified with a slug in the format `owner-slug/block-or-assistant-slug`, where an owner can be a user or organization (For example, if you want to use the [OpenAI 4o Model block](https://hub.continue.dev/openai/gpt-4o), your slug would be `openai/gpt-4o`). These blocks are pulled from [https://hub.continue.dev](https://hub.continue.dev). Blocks can be imported into an assistant by adding a `uses` clause under the block type. This can be alongside other `uses` clauses or explicit blocks of that type. @@ -167,7 +167,7 @@ The `models` section defines the language models used in your configuration. Mod - `apiBase`: Can be used to override the default API base that is specified per model - `roles`: An array specifying the roles this model can fulfill, such as `chat`, `autocomplete`, `embed`, `rerank`, `edit`, `apply`, `summarize`. The default value is `[chat, edit, apply, summarize]`. Note that the `summarize` role is not currently used. - `capabilities`: Array of strings denoting model capabilities, which will overwrite Continue's autodetection based on provider and model. Supported capabilities include `tool_use` and `image_input`. -- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [autocomplete](./customize/model-roles/autocomplete.md#prompt-templating) +- `promptTemplates`: Can be used to override the default prompt templates for different model roles. Valid values are `chatTemplate`, [`edit`](./customize/model-roles/edit.mdx#prompt-templating), [`apply`](./customize/model-roles/apply.mdx#prompt-templating) and [`autocomplete`](./customize/model-roles/autocomplete.md#prompt-templating). The `chatTemplate` property must be a valid template name, such as `llama3` or `anthropic`. - `chatOptions`: If the model includes role `chat`, these settings apply for Chat and Agent mode: - `baseSystemMessage`: Can be used to override the default system prompt. - `embedOptions`: If the model includes role `embed`, these settings apply for embeddings: @@ -181,6 +181,8 @@ The `models` section defines the language models used in your configuration. Mod - `topK`: Maximum number of tokens considered at each step. - `stop`: An array of stop tokens that will terminate the completion. - `n`: Number of completions to generate. + - `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models. + - `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models. - `requestOptions`: HTTP request options specific to the model. - `timeout`: Timeout for each request to the language model. - `verifySsl`: Whether to verify SSL certificates for requests. @@ -270,19 +272,25 @@ Explicit rules can either be simple text or an object with the following propert - `name` (**required**): A display name/title for the rule - `rule` (**required**): The text content of the rule - - -Example +- `globs` (optional): When files are provided as context that match this glob pattern, the rule will be included. This can be either a single pattern (e.g., `"**/*.{ts,tsx}"`) or an array of patterns (e.g., `["src/**/*.ts", "tests/**/*.ts"]`). ```yaml title="config.yaml" rules: + - Always annotate Python functions with their parameter and return types + + - name: TypeScript best practices + rule: Always use TypeScript interfaces to define shape of objects. Use type aliases sparingly. + globs: "**/*.{ts,tsx}" + + - name: TypeScript test patterns + rule: In TypeScript tests, use Jest's describe/it pattern and follow best practices for mocking. + globs: + - "src/**/*.test.ts" + - "tests/**/*.ts" + - uses: myprofile/my-mood-setter with: TONE: concise - - Always annotate Python functions with their parameter and return types - - Always write Google style docstrings for functions and classes - - name: Server-side components - rule: When writing Next.js React components, use server-side components where possible instead of client components. ``` --- diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md index 79e142ca9..d53afe6e7 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/model-providers/more/SambaNova.md @@ -1,7 +1,6 @@ # SambaNova Cloud -SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](https://cloud.sambanova.ai/) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。 - +SambaNova 云是一个运行大型 AI 模型的云平台,有 Llama 3.1 70B/405B 性能的世界记录。你可以在 [这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ) 登录,在最初的欢迎屏幕复制你的 API key ,然后在 [模型列表](https://community.sambanova.ai/t/quick-start-guide/104) 任何模型上点击 play 按钮。 ```json title="config.json" { "models": [ diff --git a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md index 877864a15..674b3dcbe 100644 --- a/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md +++ b/docs/i18n/zh-CN/docusaurus-plugin-content-docs/current/customize/tutorials/llama3.1.md @@ -95,7 +95,7 @@ Replicate 让使用 API 托管和运行开源 AI 变得简单。 SambaNova Cloud 提供 Llama3.1 70B/405B 服务的世界记录。 -1. 创建账号 [在这里](https://cloud.sambanova.ai/) +1. 创建账号 [在这里](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup) 2. 复制你的 API key 3. 更新你的 Continue 配置文件像这样: diff --git a/docs/sidebars.js b/docs/sidebars.js index 1a634d163..398514029 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -55,6 +55,16 @@ const sidebars = { }, ], }, + { + type: "category", + label: "Blocks", + items: [ + { + type: "autogenerated", + dirName: "blocks", + }, + ], + }, "telemetry", "troubleshooting", { @@ -68,7 +78,6 @@ const sidebars = { { type: "category", label: "Model providers", - collapsed: false, link: { slug: "/customize/model-providers", type: "generated-index", diff --git a/docs/static/img/context-blocks-overview.png b/docs/static/img/context-blocks-overview.png new file mode 100644 index 000000000..2db89de89 Binary files /dev/null and b/docs/static/img/context-blocks-overview.png differ diff --git a/docs/static/img/data-blocks-overview.png b/docs/static/img/data-blocks-overview.png new file mode 100644 index 000000000..dc7ec288e Binary files /dev/null and b/docs/static/img/data-blocks-overview.png differ diff --git a/docs/static/img/docs-blocks-overview.png b/docs/static/img/docs-blocks-overview.png new file mode 100644 index 000000000..ac7876784 Binary files /dev/null and b/docs/static/img/docs-blocks-overview.png differ diff --git a/docs/static/img/local-config-open-steps.png b/docs/static/img/local-config-open-steps.png new file mode 100644 index 000000000..07b27c976 Binary files /dev/null and b/docs/static/img/local-config-open-steps.png differ diff --git a/docs/static/img/mcp-blocks-overview.png b/docs/static/img/mcp-blocks-overview.png new file mode 100644 index 000000000..0967ee831 Binary files /dev/null and b/docs/static/img/mcp-blocks-overview.png differ diff --git a/docs/static/img/model-blocks-overview.png b/docs/static/img/model-blocks-overview.png new file mode 100644 index 000000000..56e139a29 Binary files /dev/null and b/docs/static/img/model-blocks-overview.png differ diff --git a/docs/static/img/prompts-blocks-overview.png b/docs/static/img/prompts-blocks-overview.png new file mode 100644 index 000000000..109f58654 Binary files /dev/null and b/docs/static/img/prompts-blocks-overview.png differ diff --git a/docs/static/img/rules-blocks-overview.png b/docs/static/img/rules-blocks-overview.png new file mode 100644 index 000000000..7864c8d6b Binary files /dev/null and b/docs/static/img/rules-blocks-overview.png differ diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 4f74ef64d..b6887362b 100644 --- a/extensions/intellij/gradle.properties +++ b/extensions/intellij/gradle.properties @@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension pluginName=continue-intellij-extension pluginRepositoryUrl=https://github.com/continuedev/continue # SemVer format -> https://semver.org -pluginVersion=1.0.14 +pluginVersion=1.0.15 # Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=223 # IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index 677d0bd84..031783597 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -432,6 +432,25 @@ class IdeProtocolClient( } } + "acceptDiff" -> { + val params = Gson().fromJson( + dataElement.toString(), + AcceptDiffParams::class.java + ) + val filepath = params.filepath; + + acceptOrRejectDiff(filepath, true) + } + + "rejectDiff" -> { + val params = Gson().fromJson( + dataElement.toString(), + RejectDiffParams::class.java + ) + val filepath = params.filepath; + acceptOrRejectDiff(filepath, false) + } + "applyToFile" -> { val params = Gson().fromJson( dataElement.toString(), @@ -648,6 +667,29 @@ class IdeProtocolClient( continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid()) } + fun acceptOrRejectDiff(filepath: String, accepted: Boolean) { + val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath) + + if (virtualFile != null) { + ApplicationManager.getApplication().invokeAndWait { + val openedEditor = + FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first() + if (openedEditor != null) { + val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor + + if (editor != null) { + val diffStreamService = project.service() + if (accepted) { + diffStreamService.accept(editor) + } else { + diffStreamService.reject(editor) + } + } + } + } + } + } + fun deleteAtIndex(index: Int) { continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid()) } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt index 41bcc2941..afd3f8b1c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IntelliJIde.kt @@ -42,7 +42,7 @@ class IntelliJIDE( private val project: Project, private val continuePluginService: ContinuePluginService, -) : IDE { + ) : IDE { private val gitService = GitService(project, continuePluginService) @@ -57,6 +57,19 @@ class IntelliJIDE( val os = getOS() ripgrep = Paths.get(pluginPath.toString(), "ripgrep", "bin", "rg" + if (os == OS.WINDOWS) ".exe" else "").toString() + + // Make ripgrep executable if on Unix-like systems + try { + if (os == OS.LINUX || os == OS.MAC) { + val file = File(ripgrep) + if (!file.canExecute()) { + file.setExecutable(true) + } + } + } catch (e: Throwable) { + e.printStackTrace() + } + } /** @@ -179,6 +192,7 @@ class IntelliJIDE( override suspend fun writeFile(path: String, contents: String) { val file = File(URI(path)) + file.parentFile?.mkdirs() file.writeText(contents) } @@ -194,7 +208,13 @@ class IntelliJIDE( } override suspend fun openFile(path: String) { - val file = LocalFileSystem.getInstance().findFileByPath(URI(path).path) + // Convert URI path to absolute file path + val filePath = File(URI(path)).absolutePath + // Find the file using the absolute path + val file = withContext(Dispatchers.IO) { + LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath) + } + file?.let { ApplicationManager.getApplication().invokeLater { FileEditorManager.getInstance(project).openFile(it, true) @@ -311,7 +331,7 @@ class IntelliJIDE( val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { val command = GeneralCommandLine( - ripgrep, + ripgrep, "--files", "--iglob", pattern, @@ -320,37 +340,37 @@ class IntelliJIDE( "--ignore-file", ".gitignore", ) - + command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout return results.split("\n") } else { - throw NotImplementedError("Ripgrep not supported, this workspace is remote") + throw NotImplementedError("Ripgrep not supported, this workspace is remote") - // Leaving in here for ideas - // val projectBasePath = project.basePath ?: return emptyList() - // val scope = GlobalSearchScope.projectScope(project) - // - // // Get all ignore patterns from .continueignore files - // val ignorePatterns = mutableSetOf() - // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> - // VfsUtil.collectChildrenRecursively(root).forEach { file -> - // if (file.name == ".continueignore") { - // file.inputStream.bufferedReader().useLines { lines -> - // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) - // } - // } - // } - // } - // - // return FilenameIndex.getAllFilesByExt(project, "*", scope) - // .filter { file -> - // val relativePath = file.path.removePrefix("$projectBasePath/") - // // Check if file matches pattern and isn't ignored - // PatternUtil.(relativePath, pattern) && - // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } - // } - // .map { it.path.removePrefix("$projectBasePath/") } + // Leaving in here for ideas + // val projectBasePath = project.basePath ?: return emptyList() + // val scope = GlobalSearchScope.projectScope(project) + // + // // Get all ignore patterns from .continueignore files + // val ignorePatterns = mutableSetOf() + // VirtualFileManager.getInstance().findFileByUrl("file://$projectBasePath")?.let { root -> + // VfsUtil.collectChildrenRecursively(root).forEach { file -> + // if (file.name == ".continueignore") { + // file.inputStream.bufferedReader().useLines { lines -> + // ignorePatterns.addAll(lines.filter { it.isNotBlank() && !it.startsWith("#") }) + // } + // } + // } + // } + // + // return FilenameIndex.getAllFilesByExt(project, "*", scope) + // .filter { file -> + // val relativePath = file.path.removePrefix("$projectBasePath/") + // // Check if file matches pattern and isn't ignored + // PatternUtil.(relativePath, pattern) && + // !ignorePatterns.any { PatternUtil.matchesGlob(relativePath, it) } + // } + // .map { it.path.removePrefix("$projectBasePath/") } } } @@ -358,20 +378,20 @@ class IntelliJIDE( val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { val command = GeneralCommandLine( - ripgrep, - "-i", + ripgrep, + "-i", "--ignore-file", ".continueignore", "--ignore-file", - ".gitignore", - "-C", - "2", - "--heading", - "-e", - query, + ".gitignore", + "-C", + "2", + "--heading", + "-e", + query, "." ) - + command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout } else { @@ -415,7 +435,7 @@ class IntelliJIDE( // return searchResults.toString() } } - + override suspend fun subprocess(command: String, cwd: String?): List { val commandList = command.split(" ") diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt index 718755a99..b875f744c 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ideWebview.kt @@ -15,6 +15,16 @@ data class ApplyToFileParams( val toolCallId: String? ) +data class AcceptDiffParams( + val filepath: String, + val streamId: String +) + +data class RejectDiffParams( + val filepath: String, + val streamId: String +) + data class InsertAtCursorParams( val text: String ) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 48f6e2aaa..9ad8b8cb2 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -71,6 +71,16 @@ "title": "Ollama keep_alive", "description": "The number of seconds after no requests are made to unload the model from memory. Defaults to 60*30 = 30min", "type": "integer" + }, + "reasoning": { + "title": "Reasoning", + "description": "Enable thinking/reasoning for Anthropic Claude 3.7+ models", + "type": "boolean" + }, + "reasoningBudgetTokens": { + "title": "Reasoning Budget Tokens", + "description": "Set budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models", + "type": "integer" } } }, @@ -216,7 +226,8 @@ "siliconflow", "function-network", "scaleway", - "relace" + "relace", + "morph" ], "markdownEnumDescriptions": [ "### OpenAI\nUse 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.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/openai)", @@ -250,7 +261,7 @@ "### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)", "### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.", "### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys).", - "### SambaNova\n SambaNova provides fast inference of open-source language models with zero data retention. To get started, obtain an API key in [SambaNova Cloud](https://cloud.sambanova.ai/apis).", + "### SambaNova\n SambaNova provides fast inference of open-source language models with zero data retention. To get started, obtain an API key in [SambaNova Cloud](https://cloud.sambanova.ai/apis?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup ).", "### NVIDIA NIMs\nNVIDIA offers a single API to access almost any language model. To find out more, visit the [LLM APIs Documentation](https://docs.api.nvidia.com/nim/reference/llm-apis).\nFor information specific to getting a key, please check out the [docs here](https://docs.nvidia.com/nim/large-language-models/latest/getting-started.html#option-1-from-api-catalog)", "### vLLM\nvLLM is a highly performant way of hosting LLMs for a team. To get started, follow their [quickstart](https://docs.vllm.ai/en/latest/getting_started/quickstart.html) to set up your server.", "### Cerebras\nCerebras Inference uses specialized silicon to provides superfast inference. To get started, get your API keys from [their console](https://cloud.cerebras.ai/).", @@ -263,7 +274,8 @@ "### SiliconFlow\nTo get started with SiliconFlow, obtain your API key from [SiliconCloud](https://cloud.siliconflow.cn/account/ak). SiliconCloud provides cost-effective GenAI services based on excellent open source basic models.\n> [Models](https://siliconflow.cn/zh-cn/models)", "### Function Network offers private, affordable user-owned AI\nTo get started with Function Network, obtain your API key from [Function Network](https://www.function.network/join-waitlist). Function Network provides a variety of models for chat, completion, and embeddings.", "### Scaleway\n Generative APIs are serverless endpoints for the most popular AI models.\nHosted in European data centers and priced competitively per million tokens used, models served by Scaleway are ideal for users requiring low latency, full data privacy, and 100% compliance with EU AI Act. To get access to the Scaleway Generative APIs, read the [Quickstart guide](https://www.scaleway.com/en/docs/ai-data/generative-apis/quickstart/) and get a [valid API key](https://www.scaleway.com/en/docs/identity-and-access-management/iam/how-to/create-api-keys/).", - "### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys)." + "### Relace\n Relace provides a fast apply model. To get started, obtain an API key from [here](https://app.relace.ai/settings/api-keys).", + "### Morph\nMorph provides a fast apply model. To get started, obtain an API key from [here](https://morphllm.com/dashboard)." ], "type": "string" }, @@ -959,7 +971,8 @@ "gemini-2.0-flash-lite-preview-02-05", "gemini-2.0-flash-lite", "gemini-2.0-flash-exp-image-generation", - "gemini-2.5-pro-exp-03-25" + "gemini-2.5-pro-exp-03-25", + "gemini-2.5-pro-latest" ] } } @@ -1565,6 +1578,7 @@ "gemini-pro", "gemini-1.5-pro-latest", "gemini-1.5-pro", + "gemini-2.5-pro", "gemini-1.5-flash-latest", "gemini-1.5-flash", "mistral-tiny", @@ -1651,20 +1665,17 @@ "anyOf": [ { "enum": [ - "Qwen2.5-Coder-32B-Instruct", + "Llama-4-Scout-17B-16E-Instruct", + "Llama-4-Maverick-17B-128E-Instruct", "Meta-Llama-3.3-70B-Instruct", "Meta-Llama-3.1-8B-Instruct", - "Meta-Llama-3.1-70B-Instruct", "Meta-Llama-3.1-405B-Instruct", - "Llama-3.1-Tulu-3-405B", "Meta-Llama-3.2-1B-Instruct", "Meta-Llama-3.2-3B-Instruct", - "Llama-3.2-11B-Vision-Instruct", - "Llama-3.2-90B-Vision-Instruct", - "Qwen2.5-72B-Instruct", - "QwQ-32B-Preview", + "QwQ-32B", "DeepSeek-R1-Distill-Llama-70B", - "DeepSeek-R1" + "DeepSeek-R1", + "DeepSeek-V3-0324" ] }, { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 17fd744c5..69beb8be7 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "1.1.24", + "version": "1.1.28", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "1.1.24", + "version": "1.1.28", "license": "Apache-2.0", "dependencies": { "@continuedev/fetch": "^1.0.3", @@ -31,7 +31,7 @@ "highlightable": "^1.3.0-beta.0", "http-proxy": "^1.18.1", "http-proxy-agent": "^7.0.0", - "http-proxy-middleware": "^2.0.6", + "http-proxy-middleware": "^2.0.9", "https-proxy-agent": "^7.0.2", "ignore": "^5.3.0", "jsdom": "^24.0.0", @@ -109,7 +109,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.18", + "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -132,6 +132,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", + "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", "js-tiktoken": "^1.0.8", "jsdom": "^24.0.0", @@ -164,6 +165,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" @@ -6900,9 +6902,10 @@ } }, "node_modules/http-proxy-middleware": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.7.tgz", - "integrity": "sha512-fgVY8AV7qU7z/MmXJ/rxwbrtQH4jBQ9m7kp3llF0liB7glmFeVZFBepQb32T3y8n8k2+AEYuMPCpinYW+/CuRA==", + "version": "2.0.9", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.9.tgz", + "integrity": "sha512-c1IyJYLYppU574+YI7R4QyX2ystMtVXZwIdzazUIPIJsHuWNd+mho2j+bKoHftndicGj9yh+xjd+l0yj7VeT1Q==", + "license": "MIT", "dependencies": { "@types/http-proxy": "^1.17.8", "http-proxy": "^1.18.1", diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 9f83a3494..f2f1fb54f 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.24", + "version": "1.1.29", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" @@ -688,7 +688,7 @@ "highlightable": "^1.3.0-beta.0", "http-proxy": "^1.18.1", "http-proxy-agent": "^7.0.0", - "http-proxy-middleware": "^2.0.6", + "http-proxy-middleware": "^2.0.9", "https-proxy-agent": "^7.0.2", "ignore": "^5.3.0", "jsdom": "^24.0.0", diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 05e263117..381d9117a 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -5,11 +5,11 @@ import { type AutocompleteOutcome, } from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; -import { startLocalOllama } from "core/util/ollamaHelper"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; +import { handleLLMError } from "../util/errorHandling"; import { showFreeTrialLoginMessage } from "../util/messages"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; @@ -24,7 +24,6 @@ import { } from "./statusBar"; import type { IDE } from "core"; -import { handleLLMError } from "../util/errorHandling"; interface VsCodeCompletionInput { document: vscode.TextDocument; @@ -34,8 +33,8 @@ interface VsCodeCompletionInput { export class ContinueCompletionProvider implements vscode.InlineCompletionItemProvider { - private onError(e: any) { - if (handleLLMError(e)) { + private async onError(e: any) { + if (await handleLLMError(e)) { return; } let message = e.message; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index 7aad46202..8a5a4ae99 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -795,7 +795,7 @@ const getCommandsMap: ( vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar"); }, "continue.openConfigPage": () => { - vscode.commands.executeCommand("continue.navigateTo", "/config", true); + vscode.commands.executeCommand("continue.navigateTo", "/config", false); }, "continue.selectFilesAsContext": async ( firstUri: vscode.Uri, diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index d0ada4fc4..49de7f758 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -22,6 +22,7 @@ import { getControlPlaneSessionInfo, WorkOsAuthProvider, } from "../stubs/WorkOsAuthProvider"; +import { handleLLMError } from "../util/errorHandling"; import { showTutorial } from "../util/tutorial"; import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; @@ -237,11 +238,11 @@ export class VsCodeMessenger { /** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/ WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => { this.onWebview(messageType, async (msg) => { - return await this.inProcessMessenger.externalRequest( - messageType, - msg.data, - msg.messageId, - ); + return await this.inProcessMessenger.externalRequest( + messageType, + msg.data, + msg.messageId, + ); }); }); @@ -410,5 +411,9 @@ export class VsCodeMessenger { this.onWebviewOrCore("getUniqueId", async (msg) => { return await ide.getUniqueId(); }); + + this.onWebviewOrCore("reportError", async (msg) => { + handleLLMError(msg.data); + }); } } diff --git a/extensions/vscode/src/util/errorHandling.ts b/extensions/vscode/src/util/errorHandling.ts index de68f0ce2..c866e1907 100644 --- a/extensions/vscode/src/util/errorHandling.ts +++ b/extensions/vscode/src/util/errorHandling.ts @@ -1,3 +1,5 @@ +import { ILLM } from "core"; +import { isModelInstaller } from "core/llm"; import * as vscode from "vscode"; function supportSpecialHandling(error: any): boolean { @@ -9,7 +11,7 @@ function supportSpecialHandling(error: any): boolean { * @param error Handles common LLM errors. Currently only handles Ollama-related errors. * @returns true if error is handled, false otherwise */ -export function handleLLMError(error: any): boolean { +export async function handleLLMError(error: any): Promise { if (!supportSpecialHandling(error)) { return false; } @@ -23,6 +25,11 @@ export function handleLLMError(error: any): boolean { } else if (message.includes("ollama run") && error.llm) { //extract model name from error message matching the pattern "ollama run " modelName = message.match(/`ollama run (.*)`/)?.[1]; + const llm = error.llm as ILLM; + if (isModelInstaller(llm) && await llm.isInstallingModel(modelName!)){ + console.log(`${llm.providerName} already installing ${modelName}`); + return false; + } message = `Model "${modelName}" is not found in Ollama. You need to install it.`; options = [`Install Model`]; } diff --git a/extensions/vscode/src/webviewProtocol.ts b/extensions/vscode/src/webviewProtocol.ts index 0d58532ae..a22e3b312 100644 --- a/extensions/vscode/src/webviewProtocol.ts +++ b/extensions/vscode/src/webviewProtocol.ts @@ -87,7 +87,7 @@ export class VsCodeWebviewProtocol respond({ done: true, content: response, status: "success" }); } } catch (e: any) { - if (handleLLMError(e)) { + if (await handleLLMError(e)) { // Respond without an error, so the UI doesn't show the error component respond({ done: true, status: "error" }); } diff --git a/gui/package-lock.json b/gui/package-lock.json index d363f166e..e4a7c0b67 100644 --- a/gui/package-lock.json +++ b/gui/package-lock.json @@ -113,7 +113,7 @@ "@continuedev/config-yaml": "file:../packages/config-yaml", "@continuedev/fetch": "^1.0.4", "@continuedev/llm-info": "^1.0.8", - "@continuedev/openai-adapters": "^1.0.18", + "@continuedev/openai-adapters": "^1.0.19", "@modelcontextprotocol/sdk": "^1.5.0", "@mozilla/readability": "^0.5.0", "@octokit/rest": "^20.1.1", @@ -136,6 +136,7 @@ "http-proxy-agent": "^7.0.1", "https-proxy-agent": "^7.0.3", "ignore": "^5.3.1", + "is-localhost-ip": "^2.0.0", "jinja-js": "0.1.8", "js-tiktoken": "^1.0.8", "jsdom": "^24.0.0", @@ -168,6 +169,7 @@ "web-tree-sitter": "^0.21.0", "win-ca": "^3.5.1", "wink-nlp-utils": "^2.1.0", + "winston": "^3.17.0", "workerpool": "^9.1.3", "yaml": "^2.4.2", "zod": "^3.24.2" @@ -4364,9 +4366,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001662", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001662.tgz", - "integrity": "sha512-sgMUVwLmGseH8ZIrm1d51UbrhqMCH3jvS7gF/M6byuHOnKyLOBL7W8yz5V02OHwgLGA36o/AFhWzzh4uc5aqTA==", + "version": "1.0.30001715", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001715.tgz", + "integrity": "sha512-7ptkFGMm2OAOgvZpwgA4yjQ5SQbrNVGdRjzH0pBdy1Fasvcr+KAeECmbCAECzTuDuoX0FCY8KzUxjf9+9kfZEw==", "funding": [ { "type": "opencollective", @@ -4380,7 +4382,8 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/ccount": { "version": "2.0.1", diff --git a/gui/src/App.tsx b/gui/src/App.tsx index 15082d35b..2f3a94dd8 100644 --- a/gui/src/App.tsx +++ b/gui/src/App.tsx @@ -45,7 +45,7 @@ const router = createMemoryRouter([ Prevents entire app from rerendering continuously with useSetup in App TODO - look into a more redux-esque way to do this */ -function SetupListeners() { +export function SetupListeners() { useSetup(); return <>; } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx index 0c1c8c7d0..17bbc5802 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/ApplyActions.tsx @@ -48,6 +48,14 @@ export function ApplyActions(props: ApplyActionsProps) { ); switch (props.applyState ? props.applyState.status : null) { + case "not-started": + return ( +
+ + Pending + +
+ ); case "streaming": return (
@@ -84,8 +92,8 @@ export function ApplyActions(props: ApplyActionsProps) {
); case "closed": - if (!hasRejected && props.applyState?.numDiffs === 0) { - if (showApplied) { + if (isSuccessful) { + if (showApplied || props.disableManualApply) { return ( Applied @@ -93,9 +101,6 @@ export function ApplyActions(props: ApplyActionsProps) { ); } - if (props.disableManualApply) { - return null; - } return applyButton("Reapply"); } default: diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx index b730b30e5..28e13e5b3 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/GeneratingCodeLoader.tsx @@ -3,22 +3,24 @@ import Spinner from "../../gui/Spinner"; export interface GeneratingCodeLoaderProps { showLineCount: boolean; codeBlockContent: string; + isPending: boolean; } export function GeneratingCodeLoader({ showLineCount, codeBlockContent, + isPending, }: GeneratingCodeLoaderProps) { const numLinesCodeBlock = codeBlockContent.split("\n").length; const linesGeneratedText = numLinesCodeBlock === 1 ? `1 line generated` - : `${numLinesCodeBlock} lines generated`; + : `${numLinesCodeBlock} lines ${isPending ? "pending" : "generated"}`; return ( {showLineCount ? linesGeneratedText : "Generating"} - + {!isPending && } ); } diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index a50c953f4..6154b3452 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -2,6 +2,7 @@ import { CommandLineIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { lightGray, vscForeground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; +import { isJetBrains } from "../../../util"; interface RunInTerminalButtonProps { command: string; @@ -10,16 +11,21 @@ interface RunInTerminalButtonProps { export function RunInTerminalButton({ command }: RunInTerminalButtonProps) { const ideMessenger = useContext(IdeMessengerContext); + if (isJetBrains()) { + // JetBrains plugin doesn't currently have a way to run the command in the terminal for the user + return null; + } + // Extract just the command line (the line after $ or the first line) function extractCommand(cmd: string): string { // If the command contains a $ prompt, extract the line after it - if (cmd.includes('$')) { + if (cmd.includes("$")) { const match = cmd.match(/\$\s*([^\n]+)/); - return match ? match[1].trim() : ''; + return match ? match[1].trim() : ""; } - + // Otherwise, just take the first line - return cmd.split('\n')[0].trim(); + return cmd.split("\n")[0].trim(); } function runInTerminal() { diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx index 202d87972..6b299db18 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/index.tsx @@ -52,7 +52,7 @@ export interface StepContainerPreToolbarProps { codeBlockContent: string; language: string | null; relativeFilepath?: string; - isGeneratingCodeBlock: boolean; + isFinalCodeblock: boolean; codeBlockIndex: number; // To track which codeblock we are applying codeBlockStreamId: string; range?: string; @@ -65,7 +65,7 @@ export function StepContainerPreToolbar({ codeBlockContent, language, relativeFilepath, - isGeneratingCodeBlock, + isFinalCodeblock, codeBlockIndex, codeBlockStreamId, range, @@ -115,6 +115,9 @@ export function StepContainerPreToolbar({ const hasFileExtension = relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath); + const isStreaming = useAppSelector((store) => store.session.isStreaming); + const isGeneratingCodeBlock = isFinalCodeblock && isStreaming; + // If we are creating a file, we already render that in the button // so we don't want to dispaly it twice here const displayFilepath = relativeFilepath ?? appliedFileUri; @@ -204,7 +207,7 @@ export function StepContainerPreToolbar({ setAppliedFileUri(undefined); } - function onClickFilename() { + async function onClickFilename() { if (appliedFileUri) { ideMessenger.post("showFile", { filepath: appliedFileUri, @@ -212,8 +215,13 @@ export function StepContainerPreToolbar({ } if (relativeFilepath) { + const filepath = await inferResolvedUriFromRelativePath( + relativeFilepath, + ideMessenger.ide, + ); + ideMessenger.post("showFile", { - filepath: relativeFilepath, + filepath, }); } } @@ -272,20 +280,23 @@ export function StepContainerPreToolbar({
- {isGeneratingCodeBlock ? ( + {!isGeneratingCodeBlock && ( +
+ + +
+ )} + + {isGeneratingCodeBlock || applyState?.status === "not-started" ? ( ) : ( - <> -
- - -
- - {renderActionButtons()} - + renderActionButtons() )}
diff --git a/gui/src/components/StyledMarkdownPreview/index.tsx b/gui/src/components/StyledMarkdownPreview/index.tsx index 4f6e7f7a2..082fea740 100644 --- a/gui/src/components/StyledMarkdownPreview/index.tsx +++ b/gui/src/components/StyledMarkdownPreview/index.tsx @@ -126,7 +126,7 @@ interface StyledMarkdownPreviewProps { itemIndex?: number; useParentBackgroundColor?: boolean; disableManualApply?: boolean; - singleCodeblockStreamId?: string; + forceStreamId?: string; expandCodeblocks?: boolean; } @@ -195,27 +195,16 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const pastFileInfoRef = useUpdatingRef(pastFileInfo); const isLastItem = useMemo(() => { - return props.itemIndex && props.itemIndex === history.length - 1; + return props.itemIndex === history.length - 1; }, [history.length, props.itemIndex]); const isLastItemRef = useUpdatingRef(isLastItem); - const isStreaming = useAppSelector((store) => store.session.isStreaming); - const isStreamingRef = useUpdatingRef(isStreaming); - - const codeblockState = useRef<{ streamId: string; isGenerating: boolean }[]>( - [], - ); - + const codeblockStreamIds = useRef([]); useEffect(() => { - if (props.singleCodeblockStreamId) { - codeblockState.current = [ - { - streamId: props.singleCodeblockStreamId, - isGenerating: false, - }, - ]; + if (props.forceStreamId) { + codeblockStreamIds.current = [props.forceStreamId]; } - }, [props.singleCodeblockStreamId]); + }, [props.forceStreamId, codeblockStreamIds]); const [reactContent, setMarkdownSource] = useRemark({ remarkPlugins: [ @@ -232,7 +221,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( visit(tree, "code", (node: any) => { if (!node.lang) { - node.lang = "javascript"; + node.lang = ""; } else if (node.lang.includes(".")) { node.lang = node.lang.split(".").slice(-1)[0]; } @@ -307,19 +296,12 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( const language = getLanguageFromClassName(className); - const isGeneratingCodeBlock = - preChildProps["data-islastcodeblock"] && - isLastItemRef.current && - isStreamingRef.current; + const isFinalCodeblock = + preChildProps["data-islastcodeblock"] && isLastItemRef.current; - if (codeblockState.current[codeBlockIndex] === undefined) { - codeblockState.current[codeBlockIndex] = { - streamId: uuidv4(), - isGenerating: isGeneratingCodeBlock, - }; - } else { - codeblockState.current[codeBlockIndex].isGenerating = - isGeneratingCodeBlock; + if (codeblockStreamIds.current[codeBlockIndex] === undefined) { + codeblockStreamIds.current[codeBlockIndex] = + props.forceStreamId ?? uuidv4(); } return ( @@ -328,11 +310,9 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview( codeBlockIndex={codeBlockIndex} language={language} relativeFilepath={relativeFilePath} - isGeneratingCodeBlock={isGeneratingCodeBlock} + isFinalCodeblock={isFinalCodeblock} range={range} - codeBlockStreamId={ - codeblockState.current[codeBlockIndex].streamId - } + codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} expanded={props.expandCodeblocks} disableManualApply={props.disableManualApply} > diff --git a/gui/src/components/dialogs/index.tsx b/gui/src/components/dialogs/index.tsx index c49b47721..5acf040b6 100644 --- a/gui/src/components/dialogs/index.tsx +++ b/gui/src/components/dialogs/index.tsx @@ -6,7 +6,6 @@ import { CloseButton, VSC_BACKGROUND_VAR, defaultBorderRadius, - lightGray, parseColorForHex, vscBackground, vscForeground, @@ -38,7 +37,7 @@ const DialogContainer = styled.div` border-radius: ${defaultBorderRadius}; display: flex; flex-direction: column; - border: 1px solid ${lightGray}; + box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); word-wrap: break-word; `; diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 7f6874aeb..fd174f59c 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -11,9 +11,7 @@ import { useRef, useState, } from "react"; -import { useSelector } from "react-redux"; import { HeaderButton, Input } from ".."; -import { RootState } from "../../redux/store"; import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; import { useAppSelector } from "../../redux/hooks"; diff --git a/gui/src/components/mainInput/AtMentionDropdown/index.tsx b/gui/src/components/mainInput/AtMentionDropdown/index.tsx index d8c7d5316..269e4b042 100644 --- a/gui/src/components/mainInput/AtMentionDropdown/index.tsx +++ b/gui/src/components/mainInput/AtMentionDropdown/index.tsx @@ -25,8 +25,6 @@ import { vscQuickInputBackground, } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { useAppSelector } from "../../../redux/hooks"; -import { selectSelectedChatModel } from "../../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../../redux/slices/uiSlice"; import { fontSize } from "../../../util"; import FileIcon from "../../FileIcon"; @@ -162,8 +160,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { const ideMessenger = useContext(IdeMessengerContext); - const selectedModelTitle = useAppSelector(selectSelectedChatModel); - const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( @@ -191,7 +187,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { query, fullInput: "", selectedCode, - selectedModelTitle: selectedModelTitle?.title ?? "", }, ); @@ -204,7 +199,6 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { // Check if the context item exceeds the context length of the selected model const result = await ideMessenger.request("isItemTooBig", { item, - selectedModelTitle: selectedModelTitle?.title, }); if (result.status === "error") { @@ -251,7 +245,7 @@ const AtMentionDropdown = forwardRef((props: AtMentionDropdownProps, ref) => { modal: true, detail: fileSize > 0 - ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and connot be processed by the model` + ? `'${item.title}' is ${formatFileSize(fileSize)} which exceeds the allowed context length and cannot be processed by the model` : `'${item.title}' could not be loaded. Please check if the file exists and has the correct permissions.`, }, ); diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index 1bcbb3c8c..14d4816f4 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -5,7 +5,7 @@ import styled, { keyframes } from "styled-components"; import { defaultBorderRadius, vscBackground } from ".."; import { useAppSelector } from "../../redux/hooks"; import { selectSlashCommandComboBoxInputs } from "../../redux/selectors"; -import ContextItemsPeek from "./belowMainInput/ContextItemsPeek"; +import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; @@ -114,7 +114,10 @@ function ContinueInputBox(props: ContinueInputBoxProps) { : {}; return ( -
+
{props.isMainInput && } ` - padding-top: 4px; - justify-content: space-between; - gap: 1px; - background-color: ${vscInputBackground}; - align-items: center; - font-size: ${getFontSize() - 2}px; - cursor: ${(props) => (props.isHidden ? "default" : "text")}; - opacity: ${(props) => (props.isHidden ? 0 : 1)}; - pointer-events: ${(props) => (props.isHidden ? "none" : "auto")}; - user-select: none; - - & > * { - flex: 0 0 auto; - } -`; - export interface ToolbarOptions { hideUseCodebase?: boolean; hideImageUpload?: boolean; @@ -73,15 +56,16 @@ function InputToolbar(props: InputToolbarProps) { const hasCodeToEdit = useAppSelector(selectHasCodeToEdit); const toolCallState = useAppSelector(selectCurrentToolCall); const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit; - const activeToolCallStreamId = useAppSelector( - (store) => store.session.activeToolStreamId, + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, ); const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit || toolCallState?.status === "generated" || - !!activeToolCallStreamId; + (currentToolCallApplyState && + currentToolCallApplyState.status !== "closed"); const toolsSupported = defaultModel && modelSupportsTools(defaultModel); @@ -107,8 +91,18 @@ function InputToolbar(props: InputToolbarProps) { }} >
- - + + + + Select Mode + + + + + + Select Model + +
{props.toolbarOptions?.hideImageUpload || (supportsImages && ( @@ -136,8 +130,9 @@ function InputToolbar(props: InputToolbarProps) { fileInputRef.current?.click(); }} /> + - Attach an image + Attach Image @@ -150,7 +145,7 @@ function InputToolbar(props: InputToolbarProps) { /> - Add context (files, docs, urls, etc.) + Attach Context )} @@ -186,7 +181,7 @@ function InputToolbar(props: InputToolbarProps) { {getMetaKeyLabel()}⏎ @codebase - Submit with the codebase as context ({getMetaKeyLabel()}⏎) + Send With Codebase as Context ({getMetaKeyLabel()}⏎) )} @@ -212,6 +207,7 @@ function InputToolbar(props: InputToolbarProps) { )} { @@ -228,6 +224,9 @@ function InputToolbar(props: InputToolbarProps) { ⏎ {props.toolbarOptions?.enterText ?? "Enter"} ⏎ + + Send (⏎) +
diff --git a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx index 2ec82b660..b9b27aa92 100644 --- a/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx +++ b/gui/src/components/mainInput/Lump/BlockSettingsTopToolbar.tsx @@ -9,15 +9,21 @@ import { Squares2X2Icon, WrenchScrewdriverIcon, } from "@heroicons/react/24/outline"; +import { ReactNode } from "react"; import { vscBadgeForeground } from "../.."; import { useAppSelector } from "../../../redux/hooks"; import { fontSize } from "../../../util"; +import { ToolTip } from "../../gui/Tooltip"; import AssistantSelect from "../../modelSelection/platform/AssistantSelect"; import HoverItem from "../InputToolbar/HoverItem"; import { useLump } from "./LumpContext"; +import { ErrorsSectionTooltip } from "./sections/errors/ErrorsSectionTooltip"; +import { McpSectionTooltip } from "./sections/mcp/MCPTooltip"; +import { ToolsSectionTooltip } from "./sections/tool-policies/ToolPoliciesSectionTooltip"; interface BlockSettingsToolbarIcon { - tooltip: string; + title: string; + tooltip: ReactNode; icon: React.ComponentType; itemCount?: number; onClick: () => void; @@ -27,18 +33,39 @@ interface BlockSettingsToolbarIcon { interface Section { id: string; - tooltip: string; + title: string; + tooltip: ReactNode; icon: React.ComponentType; } const sections: Section[] = [ - { id: "models", tooltip: "Models", icon: CubeIcon }, - { id: "rules", tooltip: "Rules", icon: PencilIcon }, - { id: "docs", tooltip: "Docs", icon: BookOpenIcon }, - { id: "prompts", tooltip: "Prompts", icon: ChatBubbleLeftIcon }, - { id: "tools", tooltip: "Tools", icon: WrenchScrewdriverIcon }, - { id: "mcp", tooltip: "MCP", icon: Squares2X2Icon }, - { id: "error", tooltip: "Errors", icon: ExclamationTriangleIcon }, + { id: "models", title: "Models", tooltip: "Models", icon: CubeIcon }, + { id: "rules", title: "Rules", tooltip: "Rules", icon: PencilIcon }, + { id: "docs", title: "Docs", tooltip: "Docs", icon: BookOpenIcon }, + { + id: "prompts", + title: "Prompts", + tooltip: "Prompts", + icon: ChatBubbleLeftIcon, + }, + { + id: "tools", + title: "Tools", + tooltip: , + icon: WrenchScrewdriverIcon, + }, + { + id: "mcp", + title: "MCP", + tooltip: , + icon: Squares2X2Icon, + }, + { + id: "error", + title: "Errors", + tooltip: , + icon: ExclamationTriangleIcon, + }, ]; function BlockSettingsToolbarIcon( @@ -46,53 +73,62 @@ function BlockSettingsToolbarIcon( ) { const isErrorSection = props.sectionId === "error"; + const id = `block-settings-toolbar-icon-${props.sectionId}`; return ( - -
{ - if (e.key === "Enter" || e.key === " ") { - e.preventDefault(); - props.onClick(); - } - }} - className={`${ - props.isSelected - ? isErrorSection - ? "bg-red-600" - : "bg-badge" - : undefined - } relative flex select-none items-center rounded-full px-1 transition-all duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${props.className || ""}`} + + <> + -
-
+ + + + {props.tooltip} + + ); } @@ -126,9 +162,8 @@ export function BlockSettingsTopToolbar() { @@ -142,6 +177,7 @@ export function BlockSettingsTopToolbar() { sectionId={section.id} icon={section.icon} tooltip={section.tooltip} + title={section.title} isSelected={selectedSection === section.id} onClick={() => setSelectedSection( @@ -154,8 +190,13 @@ export function BlockSettingsTopToolbar() {
-
- +
+ + + + Select Assistant + +
); diff --git a/gui/src/components/mainInput/Lump/LumpToolbar.tsx b/gui/src/components/mainInput/Lump/LumpToolbar.tsx index dd91d4e66..f8953cbf7 100644 --- a/gui/src/components/mainInput/Lump/LumpToolbar.tsx +++ b/gui/src/components/mainInput/Lump/LumpToolbar.tsx @@ -5,10 +5,15 @@ import { AnimatedEllipsis } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall"; -import { callTool } from "../../../redux/thunks/callTool"; +import { callCurrentTool } from "../../../redux/thunks/callCurrentTool"; +import { cancelCurrentToolCall } from "../../../redux/thunks/cancelCurrentToolCall"; import { cancelStream } from "../../../redux/thunks/cancelStream"; -import { cancelTool } from "../../../redux/thunks/cancelTool"; -import { getFontSize, getMetaKeyLabel } from "../../../util"; +import { + getAltKeyLabel, + getFontSize, + getMetaKeyLabel, + isJetBrains, +} from "../../../util"; import { EnterButton } from "../InputToolbar/EnterButton"; import { BlockSettingsTopToolbar } from "./BlockSettingsTopToolbar"; @@ -40,21 +45,23 @@ export function LumpToolbar() { const ideMessenger = useContext(IdeMessengerContext); const ttsActive = useAppSelector((state) => state.ui.ttsActive); const isStreaming = useAppSelector((state) => state.session.isStreaming); + const jetbrains = isJetBrains(); const toolCallState = useSelector(selectCurrentToolCall); const handleKeyDown = (event: KeyboardEvent) => { if (toolCallState?.status === "generated") { const metaKey = event.metaKey || event.ctrlKey; + const altKey = event.altKey; if (metaKey && event.key === "Enter") { event.preventDefault(); event.stopPropagation(); - dispatch(callTool()); - } else if (metaKey && event.key === "Backspace") { + dispatch(callCurrentTool()); + } else if ((jetbrains ? altKey : metaKey) && event.key === "Backspace") { event.preventDefault(); event.stopPropagation(); - dispatch(cancelTool()); + dispatch(cancelCurrentToolCall()); } } }; @@ -92,7 +99,8 @@ export function LumpToolbar() { dispatch(cancelStream()); }} > - {getMetaKeyLabel()} ⌫ Cancel + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel ); @@ -101,20 +109,23 @@ export function LumpToolbar() { if (toolCallState?.status === "generated") { return ( - +
+ Pending tool call +
dispatch(cancelTool())} + onClick={() => dispatch(cancelCurrentToolCall())} data-testid="reject-tool-call-button" > - {getMetaKeyLabel()} ⌫ Cancel + {/* JetBrains overrides cmd+backspace, so we have to use another shortcut */} + {jetbrains ? getAltKeyLabel() : getMetaKeyLabel()} ⌫ Cancel dispatch(callTool())} + onClick={() => dispatch(callCurrentTool())} data-testid="accept-tool-call-button" > {getMetaKeyLabel()} ⏎ Continue diff --git a/gui/src/components/mainInput/Lump/index.tsx b/gui/src/components/mainInput/Lump/index.tsx index 32222af65..218c23b68 100644 --- a/gui/src/components/mainInput/Lump/index.tsx +++ b/gui/src/components/mainInput/Lump/index.tsx @@ -37,7 +37,7 @@ export function Lump() { return ( -
+
; -} diff --git a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx index 562d7e50b..77b6c4bd9 100644 --- a/gui/src/components/mainInput/Lump/sections/RulesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/RulesSection.tsx @@ -123,16 +123,16 @@ const RuleCard: React.FC = ({ rule }) => { > {rule.rule} - {rule.if ? ( + {rule.globs ? (
- Applies if + Applies to files - {rule.if.replace(/\${{|}}/g, "")} + {rule.globs}
) : null} @@ -181,7 +181,7 @@ export function RulesSection() { } } // Add a displayed rule for the base system chat message when in chat mode - if (mode === "chat") { + if (mode === "chat" || mode === "agent") { const baseMessage = config.selectedModelByRole.chat?.baseChatSystemMessage; if (baseMessage) { diff --git a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx index 85f72078f..ad07a86d6 100644 --- a/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/SelectedSection.tsx @@ -1,8 +1,8 @@ import { useLump } from "../LumpContext"; import { ContextSection } from "./ContextSection"; import DocsSection from "./docs/DocsSection"; -import { ErrorSection } from "./ErrorSection"; -import { MCPSection } from "./MCPSection"; +import { ErrorSection } from "./errors/ErrorSection"; +import MCPSection from "./mcp/MCPSection"; import { ModelsSection } from "./ModelsSection"; import { PromptsSection } from "./PromptsSection"; import { RulesSection } from "./RulesSection"; diff --git a/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx b/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx similarity index 70% rename from gui/src/components/mainInput/Lump/sections/ErrorSection.tsx rename to gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx index d4d01141c..89a243871 100644 --- a/gui/src/components/mainInput/Lump/sections/ErrorSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/errors/ErrorSection.tsx @@ -2,7 +2,7 @@ import { ExclamationCircleIcon, ExclamationTriangleIcon, } from "@heroicons/react/24/outline"; -import { useAppSelector } from "../../../../redux/hooks"; +import { useAppSelector } from "../../../../../redux/hooks"; export function ErrorSection() { const configError = useAppSelector((state) => state.config.configError); @@ -24,14 +24,11 @@ export function ErrorSection() { }`} > {error.fatal ? ( - + ) : ( - + )} -

- {error.fatal ? "Fatal Error:" : "Warning:"}{" "} - {error.message} -

+

{error.message}

))} diff --git a/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx new file mode 100644 index 000000000..fd2199ede --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/errors/ErrorsSectionTooltip.tsx @@ -0,0 +1,14 @@ +import { useAppSelector } from "../../../../../redux/hooks"; + +export const ErrorsSectionTooltip = () => { + const configError = useAppSelector((store) => store.config.configError); + + const numErrors = configError?.length ?? 0; + const plural = numErrors > 1 ? "s" : ""; + + return ( +
+ {`${numErrors} Config Error${plural}`} +
+ ); +}; diff --git a/gui/src/pages/config/MCPServersPreview.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx similarity index 91% rename from gui/src/pages/config/MCPServersPreview.tsx rename to gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx index f1ca7b5af..07ec23c56 100644 --- a/gui/src/pages/config/MCPServersPreview.tsx +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPSection.tsx @@ -8,14 +8,14 @@ import { } from "@heroicons/react/24/outline"; import { MCPServerStatus } from "core"; import { useContext, useMemo } from "react"; -import { ToolTip } from "../../components/gui/Tooltip"; -import EditBlockButton from "../../components/mainInput/Lump/EditBlockButton"; -import { ExploreBlocksButton } from "../../components/mainInput/Lump/sections/ExploreBlocksButton"; -import { useAuth } from "../../context/Auth"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; -import { useAppDispatch, useAppSelector } from "../../redux/hooks"; -import { updateConfig } from "../../redux/slices/configSlice"; -import { fontSize } from "../../util"; +import { useAuth } from "../../../../../context/Auth"; +import { IdeMessengerContext } from "../../../../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../../../../redux/hooks"; +import { updateConfig } from "../../../../../redux/slices/configSlice"; +import { fontSize } from "../../../../../util"; +import { ToolTip } from "../../../../gui/Tooltip"; +import EditBlockButton from "../../EditBlockButton"; +import { ExploreBlocksButton } from "../ExploreBlocksButton"; interface MCPServerStatusProps { server: MCPServerStatus; @@ -154,7 +154,7 @@ function MCPServerPreview({ server, serverFromYaml }: MCPServerStatusProps) { ); } -function MCPServersPreview() { +function MCPSection() { const servers = useAppSelector( (store) => store.config.config.mcpServerStatuses, ); @@ -186,4 +186,4 @@ function MCPServersPreview() { ); } -export default MCPServersPreview; +export default MCPSection; diff --git a/gui/src/components/mainInput/Lump/sections/mcp/MCPTooltip.tsx b/gui/src/components/mainInput/Lump/sections/mcp/MCPTooltip.tsx new file mode 100644 index 000000000..b06528fdb --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/mcp/MCPTooltip.tsx @@ -0,0 +1,18 @@ +import { useAppSelector } from "../../../../../redux/hooks"; + +export const McpSectionTooltip = () => { + const mcpServers = useAppSelector( + (store) => store.config.config.mcpServerStatuses, + ); + + const numServers = mcpServers.length; + const numActiveServers = mcpServers.filter( + (server) => server.status === "connected", + ).length; + + return ( +
+ {`MCP Servers (${numActiveServers}/${numServers} active)`} +
+ ); +}; diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx index 7ad61abd0..c6e96c16b 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSection.tsx @@ -59,7 +59,7 @@ export const ToolPoliciesSection = () => { size={10} />
-
+
{tools.map((tool) => ( { excluded={toolGroupSettings[groupName] === "exclude"} /> ))} - {toolGroupSettings[groupName] === "exclude" && ( -
- )}
))} diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSectionTooltip.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSectionTooltip.tsx new file mode 100644 index 000000000..7e3334b1a --- /dev/null +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPoliciesSectionTooltip.tsx @@ -0,0 +1,16 @@ +import { useAppSelector } from "../../../../../redux/hooks"; +import { selectActiveTools } from "../../../../../redux/selectors/selectActiveTools"; + +export const ToolsSectionTooltip = () => { + const tools = useAppSelector((store) => store.config.config.tools); + const activeTools = useAppSelector(selectActiveTools); + + const numTools = tools.length; + const numActiveTools = activeTools.length; + + return ( +
+ {`Tools (${numActiveTools}/${numTools} active)`} +
+ ); +}; diff --git a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx index c19c926af..f7b0a97d1 100644 --- a/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx +++ b/gui/src/components/mainInput/Lump/sections/tool-policies/ToolPolicyItem.tsx @@ -1,14 +1,17 @@ -import { InformationCircleIcon } from "@heroicons/react/24/outline"; +import { + ChevronRightIcon, + InformationCircleIcon, +} from "@heroicons/react/24/outline"; import { Tool } from "core"; -import { useEffect } from "react"; +import { useEffect, useMemo, useState } from "react"; import { useDispatch } from "react-redux"; import { useAppSelector } from "../../../../../redux/hooks"; import { addTool, toggleToolSetting, } from "../../../../../redux/slices/uiSlice"; -import { fontSize } from "../../../../../util"; import { ToolTip } from "../../../../gui/Tooltip"; +import { useFontSize } from "../../../../ui/font"; interface ToolDropdownItemProps { tool: Tool; @@ -21,6 +24,7 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { const policy = useAppSelector( (state) => state.ui.toolSettings[props.tool.function.name], ); + const [isExpanded, setIsExpanded] = useState(false); useEffect(() => { if (!policy) { @@ -28,74 +32,133 @@ function ToolPolicyItem(props: ToolDropdownItemProps) { } }, [props.tool.function.name, policy]); + const parameters = useMemo(() => { + if (props.tool.function.parameters?.properties) { + return Object.entries(props.tool.function.parameters.properties).map( + ([name, schema]) => + [name, schema] as [string, { description: string; type: string }], + ); + } + return undefined; + }, [props.tool.function.parameters]); + + const fontSize = useFontSize(-2); + if (!policy) { return null; } return (
{ - dispatch(toggleToolSetting(props.tool.function.name)); - e.stopPropagation(); - e.preventDefault(); + fontSize, }} > -
- {props.duplicatesDetected ? ( - <> -
- +
setIsExpanded((val) => !val)} + > +
- {props.excluded ? ( - Excluded - ) : ( -
- {(policy === "allowedWithPermission" || policy === undefined) && ( - Ask First - )} - {policy === "allowedWithoutPermission" && ( - Automatic - )} - {policy === "disabled" && ( - Excluded + )} + + {props.tool.function.name} + +
+
+
{ + dispatch(toggleToolSetting(props.tool.function.name)); + e.stopPropagation(); + e.preventDefault(); + }} + > + {props.excluded || policy === "disabled" ? ( + <> + Off + + Excluded + + + ) : policy === "allowedWithoutPermission" ? ( + <> + Auto + + Automatic + + + ) : ( + // allowedWithPermission + <> + Ask + + Ask First + + )}
- )} +
+
+ Description: + {props.tool.function.description} + {parameters ? ( + <> + Arguments: + {parameters.map((param) => ( +
+ {param[0]} + {`(${param[1].type}):`} + {param[1].description} +
+ ))} + + ) : null} +
+
); } diff --git a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx index b7f3d724c..a5b89d0f4 100644 --- a/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/components/ExpandableToolbarPreview.tsx @@ -134,7 +134,7 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { useEffect(() => { const resizeObserver = new ResizeObserver(() => { - setContentDims(prevValue => ({ + setContentDims((prevValue) => ({ width: contentRef.current?.scrollWidth ?? prevValue.width, height: contentRef.current?.scrollHeight ?? prevValue.height, })); @@ -156,6 +156,7 @@ export function ExpandableToolbarPreview(props: ExpandableToolbarPreviewProps) { props.isSelected ? vscBadgeBackground : vscCommandCenterInactiveBorder } className="find-widget-skip !my-0" + contentEditable={false} >
- {hidden ? ( - - ) : ( - - )} + {!!props.children && + (hidden ? ( + + ) : ( + + ))} {props.onDelete && (
- {!hidden && ( + {!hidden && !!props.children && ( - + {!content ? null : ( + + )} ); diff --git a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx index 8a1095d80..50db13fcd 100644 --- a/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx +++ b/gui/src/components/mainInput/TipTapEditor/extensions/Prompt/PromptBlockPreview.tsx @@ -42,9 +42,14 @@ export const PromptBlockPreview = ({ onDelete={handleDelete} onTitleClick={handleTitleClick} > -
- {item.content} -
+ {!item.content ? null : ( +
+ {item.content} +
+ )} ); diff --git a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts index ad7858a0a..6ff74eb2c 100644 --- a/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts +++ b/gui/src/components/mainInput/TipTapEditor/utils/resolveEditorContent.ts @@ -33,7 +33,6 @@ interface ResolveEditorContentInput { ideMessenger: IIdeMessenger; defaultContextProviders: DefaultContextProvider[]; availableSlashCommands: SlashCommandDescription[]; - selectedModelTitle: string; dispatch: Dispatch; } @@ -60,7 +59,6 @@ export async function resolveEditorContent({ ideMessenger, defaultContextProviders, availableSlashCommands, - selectedModelTitle, dispatch, }: ResolveEditorContentInput): Promise { const { parts, contextItemAttrs, selectedCode, slashCommandName } = @@ -84,7 +82,6 @@ export async function resolveEditorContent({ defaultContextProviders, parts, selectedCode, - selectedModelTitle, }); if (shouldGatherContext) { @@ -236,7 +233,6 @@ async function gatherContextItems({ defaultContextProviders, parts, selectedCode, - selectedModelTitle, }: { contextItemAttrs: MentionAttrs[]; modifiers: InputModifiers; @@ -244,7 +240,6 @@ async function gatherContextItems({ defaultContextProviders: DefaultContextProvider[]; parts: MessagePart[]; selectedCode: RangeInFile[]; - selectedModelTitle: string; }): Promise { let contextItems: ContextItemWithId[] = []; @@ -255,7 +250,6 @@ async function gatherContextItems({ query: item.query ?? "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { contextItems.push(...result.content); @@ -269,7 +263,6 @@ async function gatherContextItems({ query: "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { @@ -285,7 +278,6 @@ async function gatherContextItems({ query: provider.query ?? "", fullInput: stripImages(parts), selectedCode, - selectedModelTitle, }); if (result.status === "success") { return result.content; diff --git a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx index 5840240c2..7c67463a9 100644 --- a/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx +++ b/gui/src/components/mainInput/belowMainInput/ContextItemsPeek.tsx @@ -18,14 +18,15 @@ interface ContextItemsPeekProps { isCurrentContextPeek: boolean; icon?: ComponentType>; title?: JSX.Element | string; - showWhenNoResults?: boolean; } interface ContextItemsPeekItemProps { contextItem: ContextItemWithId; } -function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { +export function ContextItemsPeekItem({ + contextItem, +}: ContextItemsPeekItemProps) { const ideMessenger = useContext(IdeMessengerContext); const isUrl = contextItem.uri?.type === "url"; @@ -150,12 +151,11 @@ function ContextItemsPeekItem({ contextItem }: ContextItemsPeekItemProps) { ); } -function ContextItemsPeek({ +export function ContextItemsPeek({ contextItems, isCurrentContextPeek, icon, title, - showWhenNoResults, }: ContextItemsPeekProps) { const ctxItems = useMemo(() => { return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; @@ -165,11 +165,7 @@ function ContextItemsPeek({ const indicateIsGathering = isCurrentContextPeek && isGatheringContext; - if ( - !showWhenNoResults && - (!ctxItems || ctxItems.length === 0) && - !indicateIsGathering - ) { + if ((!ctxItems || ctxItems.length === 0) && !indicateIsGathering) { return null; } @@ -198,5 +194,3 @@ function ContextItemsPeek({ ); } - -export default ContextItemsPeek; diff --git a/gui/src/components/modelSelection/ModeSelect.tsx b/gui/src/components/modelSelection/ModeSelect.tsx index 92395f545..b4cb94545 100644 --- a/gui/src/components/modelSelection/ModeSelect.tsx +++ b/gui/src/components/modelSelection/ModeSelect.tsx @@ -8,9 +8,10 @@ import { } from "@heroicons/react/24/outline"; import { MessageModes } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; -import { useEffect, useMemo } from "react"; +import { useEffect, useMemo, useState } from "react"; import styled from "styled-components"; import { lightGray } from ".."; +import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { @@ -41,6 +42,8 @@ function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector(selectCurrentMode); const selectedModel = useAppSelector(selectSelectedChatModel); + const currentSession = useAppSelector((state) => state.session); + const [newSessionInitialized, setNewSessionInitialized] = useState(false); const agentModeSupported = selectedModel && modelSupportsTools(selectedModel); const jetbrains = useMemo(() => { @@ -83,6 +86,16 @@ function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [dispatch, mode, jetbrains]); + useWebviewListener("newSession", async () => { + setNewSessionInitialized(true); + }); + + useEffect(() => { + if (currentSession.history.length > 0) { + setNewSessionInitialized(false); + } + }, [currentSession.history]); + return ( { - const enabledOptions = options.filter((option) => option.apiKey !== ""); - const disabledOptions = options.filter((option) => option.apiKey === ""); + const alphaSort = options.sort((a, b) => a.title.localeCompare(b.title)); + const enabledOptions = alphaSort.filter((option) => option.apiKey !== ""); + const disabledOptions = alphaSort.filter((option) => option.apiKey === ""); const sorted = [...enabledOptions, ...disabledOptions]; diff --git a/gui/src/components/modelSelection/platform/AssistantSelect.tsx b/gui/src/components/modelSelection/platform/AssistantSelect.tsx index f58a4194a..e2d6bc456 100644 --- a/gui/src/components/modelSelection/platform/AssistantSelect.tsx +++ b/gui/src/components/modelSelection/platform/AssistantSelect.tsx @@ -7,7 +7,7 @@ import { ExclamationTriangleIcon, PlusIcon, } from "@heroicons/react/24/outline"; -import { useContext, useEffect, useMemo, useRef } from "react"; +import { useContext, useEffect, useMemo, useRef, useState } from "react"; import { useAuth } from "../../../context/Auth"; import { IdeMessengerContext } from "../../../context/IdeMessenger"; import { @@ -33,8 +33,8 @@ import { import { ProfileDescription } from "core/config/ConfigHandler"; import { useNavigate } from "react-router-dom"; import { vscCommandCenterInactiveBorder } from "../.."; +import { cn } from "../../../util/cn"; import { ROUTES } from "../../../util/navigation"; -import { ToolTip } from "../../gui/Tooltip"; import { useLump } from "../../mainInput/Lump/LumpContext"; import { useFontSize } from "../../ui/font"; import AssistantIcon from "./AssistantIcon"; @@ -113,42 +113,35 @@ const AssistantSelectOption = ({
- {!profile.errors?.length ? ( - isLocalProfile(profile) ? ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - ) : ( - { - e.stopPropagation(); - e.preventDefault(); - handleConfigure(); - }} - /> - ) + {profile.errors && profile.errors?.length > 0 && ( + { + e.preventDefault(); + e.stopPropagation(); + handleClickError(); + }} + /> + )} + {isLocalProfile(profile) ? ( + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> ) : ( - <> - { - e.preventDefault(); - e.stopPropagation(); - handleClickError(); - }} - /> - -
Errors
- {JSON.stringify(profile.errors, null, 2)} -
- + { + e.stopPropagation(); + e.preventDefault(); + handleConfigure(); + }} + /> )}
@@ -165,6 +158,7 @@ export default function AssistantSelect() { const orgs = useAppSelector((store) => store.profiles.organizations); const ideMessenger = useContext(IdeMessengerContext); const { isToolbarExpanded } = useLump(); + const [loading, setLoading] = useState(false) const { profiles, session, login } = useAuth(); const navigate = useNavigate(); @@ -297,13 +291,15 @@ export default function AssistantSelect() { Assistants
{ + onClick={async (e) => { e.stopPropagation(); - refreshProfiles(); + setLoading(true) + await refreshProfiles() + setLoading(false) buttonRef.current?.click(); }} > - +
diff --git a/gui/src/components/ui/Listbox.tsx b/gui/src/components/ui/Listbox.tsx index ed2e077bf..1659a06b6 100644 --- a/gui/src/components/ui/Listbox.tsx +++ b/gui/src/components/ui/Listbox.tsx @@ -53,7 +53,7 @@ const ListboxOptions = React.forwardRef( border: `1px solid ${vscCommandCenterInactiveBorder}`, fontSize, borderRadius: defaultBorderRadius, - zIndex: 1000, + zIndex: 200000, ...props.style, }} /> diff --git a/gui/src/context/Auth.tsx b/gui/src/context/Auth.tsx index 831df7f6a..47e5845f9 100644 --- a/gui/src/context/Auth.tsx +++ b/gui/src/context/Auth.tsx @@ -28,7 +28,7 @@ interface AuthContextType { login: (useOnboarding: boolean) => Promise; selectedProfile: ProfileDescription | null; profiles: ProfileDescription[] | null; - refreshProfiles: () => void; + refreshProfiles: () => Promise; organizations: OrganizationDescription[]; } diff --git a/gui/src/context/IdeMessenger.ts b/gui/src/context/IdeMessenger.tsx similarity index 96% rename from gui/src/context/IdeMessenger.ts rename to gui/src/context/IdeMessenger.tsx index 4d0258efd..e30f39ccf 100644 --- a/gui/src/context/IdeMessenger.ts +++ b/gui/src/context/IdeMessenger.tsx @@ -264,3 +264,14 @@ export class IdeMessenger implements IIdeMessenger { export const IdeMessengerContext = createContext( new IdeMessenger(), ); + +export const IdeMessengerProvider: React.FC<{ + children: React.ReactNode; + messenger?: IIdeMessenger; +}> = ({ children, messenger = new IdeMessenger() }) => { + return ( + + {children} + + ); +}; diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts new file mode 100644 index 000000000..ac40a0a7f --- /dev/null +++ b/gui/src/context/MockIdeMessenger.ts @@ -0,0 +1,122 @@ +import { IDE, PromptLog } from "core"; +import { + FromWebviewProtocol, + ToCoreProtocol, + ToWebviewProtocol, +} from "core/protocol"; +import { MessageIde } from "core/protocol/messenger/messageIde"; +import { + GeneratorReturnType, + GeneratorYieldType, + WebviewSingleProtocolMessage, +} from "core/protocol/util"; +import { ChatMessage } from "../redux/store"; +import { IIdeMessenger } from "./IdeMessenger"; + +async function defaultMockHandleMessage( + messageType: T, + data: FromWebviewProtocol[T][0], +): Promise { + function returnFor( + _: K, + value: FromWebviewProtocol[K][1], + ): FromWebviewProtocol[T][1] { + return value as unknown as FromWebviewProtocol[T][1]; + } + + switch (messageType) { + case "history/list": + return returnFor("history/list", [ + { + title: "Session 1", + sessionId: "session-1", + dateCreated: new Date().toString(), + workspaceDirectory: "/tmp", + }, + ]); + case "getControlPlaneSessionInfo": + return returnFor("getControlPlaneSessionInfo", { + accessToken: "", + account: { + label: "", + id: "", + }, + }); + case "config/getSerializedProfileInfo": + return returnFor("config/getSerializedProfileInfo", { + organizations: [], + profileId: "test-profile", + result: { + config: undefined, + errors: [], + configLoadInterrupted: false, + }, + selectedOrgId: "local", + }); + default: + throw new Error(`Unknown message type ${messageType}`); + } +} + +export class MockIdeMessenger implements IIdeMessenger { + ide: IDE; + + constructor() { + this.ide = new MessageIde( + (messageType, data) => { + throw new Error("Not implemented"); + }, + (messageType, callback) => {}, + ); + } + + async *llmStreamChat( + msg: ToCoreProtocol["llm/streamChat"][0], + cancelToken: AbortSignal, + ): AsyncGenerator { + yield [ + { + role: "assistant", + content: "This is a test", + }, + ]; + + return undefined; + } + + post( + messageType: T, + data: FromWebviewProtocol[T][0], + messageId?: string, + attempt?: number, + ): void {} + + async request( + messageType: T, + data: FromWebviewProtocol[T][0], + ): Promise> { + const content = await defaultMockHandleMessage(messageType, data); + return { + status: "success", + content, + done: true, + }; + } + + respond( + messageType: T, + data: ToWebviewProtocol[T][1], + messageId: string, + ): void {} + + async *streamRequest( + messageType: T, + data: FromWebviewProtocol[T][0], + cancelToken?: AbortSignal, + ): AsyncGenerator< + GeneratorYieldType[], + GeneratorReturnType | undefined + > { + return undefined; + } +} diff --git a/gui/src/hooks/useSetup.ts b/gui/src/hooks/useSetup.ts index e9d9223a8..98ba3c5cf 100644 --- a/gui/src/hooks/useSetup.ts +++ b/gui/src/hooks/useSetup.ts @@ -10,6 +10,7 @@ import { setSelectedProfile, } from "../redux"; import { useAppDispatch, useAppSelector } from "../redux/hooks"; +import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel, setConfigResult, @@ -18,12 +19,11 @@ import { updateIndexingStatus } from "../redux/slices/indexingSlice"; import { acceptToolCall, addContextItemsAtIndex, - setInactive, - setToolCallOutput, updateApplyState, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; import { streamResponseAfterToolCall } from "../redux/thunks"; +import { cancelStream } from "../redux/thunks/cancelStream"; import { refreshSessionMetadata } from "../redux/thunks/session"; import { streamResponseThunk } from "../redux/thunks/streamResponse"; import { updateFileSymbolsFromHistory } from "../redux/thunks/updateFileSymbols"; @@ -50,7 +50,6 @@ function useSetup() { organizations, selectedOrgId, } = result; - if (isInitial && hasDoneInitialConfigLoad.current) { return; } @@ -139,7 +138,7 @@ function useSetup() { // ON LOAD useEffect(() => { // Override persisted state - dispatch(setInactive()); + dispatch(cancelStream()); const jetbrains = isJetBrains(); for (const colorVar of VSC_THEME_COLOR_VARS) { @@ -224,7 +223,7 @@ function useSetup() { ); useWebviewListener("setInactive", async () => { - dispatch(setInactive()); + dispatch(cancelStream()); }); useWebviewListener("setTTSActive", async (status) => { @@ -254,34 +253,39 @@ function useSetup() { dispatch(updateIndexingStatus(data)); }); - const activeToolStreamId = useAppSelector( - (store) => store.session.activeToolStreamId, + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, ); useWebviewListener( "updateApplyState", async (state) => { dispatch(updateApplyState(state)); + + // Handle apply status updates that are associated with current tool call if ( - activeToolStreamId && - state.streamId === activeToolStreamId[0] && - state.status === "closed" + state.status === "closed" && + currentToolCallApplyState && + currentToolCallApplyState.streamId === state.streamId ) { // const output: ContextItem = { // name: "Edit tool output", // content: "Completed edit", // description: "", // }; - dispatch(acceptToolCall()); - dispatch(setToolCallOutput([])); + dispatch( + acceptToolCall({ + toolCallId: currentToolCallApplyState.toolCallId!, + }), + ); + // dispatch(setToolCallOutput([])); dispatch( streamResponseAfterToolCall({ - toolCallId: activeToolStreamId[1], - toolOutput: [], + toolCallId: currentToolCallApplyState.toolCallId!, }), ); } }, - [activeToolStreamId], + [currentToolCallApplyState, history], ); } diff --git a/gui/src/pages/AddNewModel/configs/models.ts b/gui/src/pages/AddNewModel/configs/models.ts index d21a7d66f..1bfb49f7e 100644 --- a/gui/src/pages/AddNewModel/configs/models.ts +++ b/gui/src/pages/AddNewModel/configs/models.ts @@ -929,6 +929,20 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["gemini"], isOpenSource: false, }, + gemini25Pro: { + title: "Gemini 2.5 Pro", + description: + "Google's thinking by default Pro model with up to 64k output context. Best for complex tasks involving reasoning.", + params: { + title: "Gemini 2.5 Pro", + model: "gemini-2.5-pro", + contextLength: 1_048_576, + apiKey: "", + }, + icon: "gemini.png", + providerOptions: ["gemini"], + isOpenSource: false, + }, commandR: { title: "Command R", description: @@ -1565,13 +1579,37 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["siliconflow"], isOpenSource: true, }, + llama4Scout: { + title: "Llama 4 Scout Instruct", + description: "A model from Meta, fine-tuned for chat", + params: { + title: "Llama 4 Scout Instruct", + model: "Llama-4-Scout-17B-16E-Instruct", + contextLength: 16_000, + }, + icon: "meta.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, + llama4Maverick: { + title: "Llama 4 Maverick Instruct", + description: "A model from Meta, fine-tuned for chat", + params: { + title: "Llama 4 Maverick Instruct", + model: "Llama-4-Maverick-17B-128E-Instruct", + contextLength: 16_000, + }, + icon: "meta.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, llama3370BInstruct: { title: "Llama 3.3 70B Instruct", description: "A model from Meta, fine-tuned for chat", params: { title: "Llama 3.3 70B instruct", model: "Meta-Llama-3.3-70B-Instruct", - contextLength: 16_000, + contextLength: 128_000, }, icon: "meta.png", providerOptions: ["sambanova"], @@ -1590,19 +1628,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, - llama3170BInstruct: { - title: "Llama3.1 70B", - description: "A model from Meta, fine-tuned for chat", - refUrl: "", - params: { - title: "Llama 3.1 70B Instruct", - model: "Meta-Llama-3.1-70B-Instruct", - contextLength: 128_000, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, llama31405BInstruct: { title: "Llama3.1 405B", description: "A model from Meta, fine-tuned for chat", @@ -1616,19 +1641,6 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, - llama31Tulu3405B: { - title: "Llama3.1 Tulu 3405B", - description: "A model from Meta, fine-tuned for chat", - refUrl: "", - params: { - title: "Llama 3.1 Tulu 3 405B", - model: "Llama-3.1-Tulu-3-405B", - contextLength: 16_000, - }, - icon: "allenai.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, llama321BInstruct: { title: "Llama3.2 1B", description: "A model from Meta, fine-tuned for chat", @@ -1655,65 +1667,13 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, - llama3211BInstruct: { - title: "Llama3.2 11B", - description: "A model from Meta, fine-tuned for multimodal chat with images", - refUrl: "", - params: { - title: "Llama 3.2 11B Vision Instruct", - model: "Llama-3.2-11B-Vision-Instruct", - contextLength: 4096, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - llama3290BInstruct: { - title: "Llama3.2 90B", - description: "A model from Meta, fine-tuned for multimodal chat with images", - refUrl: "", - params: { - title: "Llama 3.2 90B Vision Instruct", - model: "Llama-3.2-90B-Vision-Instruct", - contextLength: 4096, - }, - icon: "meta.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - qwen25Coder32BInstruct: { - title: "Qwen 2.5 Coder 32B", + qwq32B: { + title: "QwQ 32B", description: - "Qwen 2.5 coder is an auto-regressive language model that uses an optimized transformer architecture, fine-tuned for coding tasks.", + "QwQ-32B is Qwen's latest experimental research model, focusing on improving AI reasoning capabilities.", params: { - title: "Qwen2.5 Coder 32B Instruct", - model: "Qwen2.5-Coder-32B-Instruct", - contextLength: 16_000, - }, - icon: "qwen.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - qwen2572BInstruct: { - title: "Qwen 2.5 72B", - description: - "Qwen 2.5 is an auto-regressive language model that uses an optimized transformer architecture.", - params: { - title: "Qwen2.5 72B Instruct", - model: "Qwen2.5-72B-Instruct", - contextLength: 16_000, - }, - icon: "qwen.png", - providerOptions: ["sambanova"], - isOpenSource: true, - }, - qwq32BPreview: { - title: "QwQ 32B Preview", - description: - "QwQ-32B-Preview is Qwen's latest experimental research model, focusing on improving AI reasoning capabilities.", - params: { - title: "QwQ 32B Preview", - model: "QwQ-32B-Preview", + title: "QwQ 32B", + model: "QwQ-32B", contextLength: 16_000, }, icon: "qwen.png", @@ -1746,6 +1706,19 @@ export const models: { [key: string]: ModelPackage } = { providerOptions: ["sambanova"], isOpenSource: true, }, + deepseekV3: { + title: "DeepSeek V3", + description: + "DeekSeek V3 reasoning model from DeepSeek", + params: { + title: "DeepSeek V3", + model: "DeepSeek-V3-0324", + contextLength: 8192, + }, + icon: "deepseek.png", + providerOptions: ["sambanova"], + isOpenSource: true, + }, AUTODETECT: { title: "Autodetect", description: diff --git a/gui/src/pages/AddNewModel/configs/providers.ts b/gui/src/pages/AddNewModel/configs/providers.ts index 43a3bbe4c..50f23ec73 100644 --- a/gui/src/pages/AddNewModel/configs/providers.ts +++ b/gui/src/pages/AddNewModel/configs/providers.ts @@ -748,7 +748,7 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo refPage: "sambanova", description: "Use SambaNova Cloud for fast inference performance", icon: "sambanova.png", - longDescription: `The SambaNova Cloud is a cloud platform for running large open source AI models with the world record performance and zero data retention. You can sign up [here](https://cloud.sambanova.ai/)`, + longDescription: `The SambaNova Cloud is a cloud platform for running large open source AI models with the world record performance and zero data retention. You can sign up [here](http://cloud.sambanova.ai?utm_source=continue&utm_medium=external&utm_campaign=cloud_signup)`, tags: [ModelProviderTags.RequiresApiKey, ModelProviderTags.OpenSource], params: { apiKey: "", @@ -764,20 +764,17 @@ To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepo ...completionParamsInputsConfigs, ], packages:[ - models.qwen25Coder32BInstruct, + models.llama4Scout, + models.llama4Maverick, models.llama3370BInstruct, models.llama318BInstruct, - models.llama3170BInstruct, models.llama31405BInstruct, - models.llama31Tulu3405B, models.llama321BInstruct, models.llama323BInstruct, - models.llama3211BInstruct, - models.llama3290BInstruct, - models.qwen2572BInstruct, - models.qwq32BPreview, + models.qwq32B, models.deepseekR1DistillLlama70B, models.deepseekR1, + models.deepseekV3 ], apiKeyUrl: "https://cloud.sambanova.ai/apis", }, diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx index 5de74fb3f..fa8e07097 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressBar.tsx @@ -6,7 +6,8 @@ export interface IndexingProgressBarProps { } function IndexingProgressBar({ update }: IndexingProgressBarProps) { - const progressPercentage = getProgressPercentage(update.progress); + // Show 100% red progress bar if indexing failed + const progressPercentage = update.status === "failed" ? 100 : getProgressPercentage(update.progress); return (
diff --git a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx index e7a19f612..33d4818ad 100644 --- a/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx +++ b/gui/src/pages/config/IndexingProgress/IndexingProgressErrorText.tsx @@ -31,7 +31,7 @@ function IndexingProgressErrorText({ update }: IndexingProgressErrorTextProps) { } return ( -
+
{update.desc}
diff --git a/gui/src/pages/config/ModelRoleSelector.tsx b/gui/src/pages/config/ModelRoleSelector.tsx index e3464a6f2..a4606ad89 100644 --- a/gui/src/pages/config/ModelRoleSelector.tsx +++ b/gui/src/pages/config/ModelRoleSelector.tsx @@ -108,7 +108,7 @@ const ModelRoleSelector = ({ style={{ borderRadius: defaultBorderRadius }} className="min-w-40" > - {models.map((option, idx) => { + {[...models].sort((a,b)=>a.title.localeCompare(b.title)).map((option, idx) => { const showMissingApiKeyMsg = option.configurationStatus === LLMConfigurationStatuses.MISSING_API_KEY; diff --git a/gui/src/pages/gui/Chat.test.tsx b/gui/src/pages/gui/Chat.test.tsx new file mode 100644 index 000000000..5339f831b --- /dev/null +++ b/gui/src/pages/gui/Chat.test.tsx @@ -0,0 +1,62 @@ +import { renderWithProviders } from "../../util/test/render"; +import { screen, waitFor } from "@testing-library/dom"; +import { act, fireEvent } from "@testing-library/react"; +import { Chat } from "./Chat"; + +describe("Chat page test", () => { + it("should render input box", async () => { + await renderWithProviders(); + expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument(); + }); + + it("should be able to toggle modes", async () => { + await renderWithProviders(); + expect(screen.getByText("Chat")).toBeInTheDocument(); + + // Simulate cmd+. keyboard shortcut to toggle modes + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + + // Check that it switched to Edit mode + expect(await screen.findByText("Edit")).toBeInTheDocument(); + + act(() => { + document.dispatchEvent( + new KeyboardEvent("keydown", { + key: ".", + metaKey: true, // cmd key on Mac + }), + ); + }); + + // Check that it switched to Agent mode + expect(await screen.findByText("Agent")).toBeInTheDocument(); + }); + + it.skip("should send a message and receive a response", async () => { + const { user, container } = await renderWithProviders(); + const inputBox = await waitFor(() => + container.querySelector(".ProseMirror")!.querySelector("p"), + ); + expect(inputBox).toBeDefined(); + + const sendButton = await screen.findByTestId("submit-input-button"); + + await act(async () => { + // Focus input box + inputBox!.focus(); + + // Type message + await user.type(inputBox!, "Hello, world!"); + + sendButton.click(); + }); + expect(await screen.findByText("Hello, world!")).toBeInTheDocument(); + }); +}); diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 8a76cdbf9..4350ff56d 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -30,7 +30,10 @@ import { IdeMessengerContext } from "../../context/IdeMessenger"; import { useWebviewListener } from "../../hooks/useWebviewListener"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectUseHub } from "../../redux/selectors"; -import { selectCurrentToolCall } from "../../redux/selectors/selectCurrentToolCall"; +import { + selectCurrentToolCall, + selectCurrentToolCallApplyState, +} from "../../redux/selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { submitEdit } from "../../redux/slices/editModeState"; import { @@ -48,7 +51,7 @@ import { cancelStream } from "../../redux/thunks/cancelStream"; import { exitEditMode } from "../../redux/thunks/exitEditMode"; import { loadLastSession } from "../../redux/thunks/session"; import { streamResponseThunk } from "../../redux/thunks/streamResponse"; -import { isMetaEquivalentKeyPressed } from "../../util"; +import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { FREE_TRIAL_LIMIT_REQUESTS, incrementFreeTrialCount, @@ -130,13 +133,14 @@ export function Chat() { const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); + const jetbrains = isJetBrains(); useEffect(() => { // Cmd + Backspace to delete current step const listener = (e: any) => { if ( e.key === "Backspace" && - isMetaEquivalentKeyPressed(e) && + (jetbrains ? e.altKey : isMetaEquivalentKeyPressed(e)) && !e.shiftKey ) { dispatch(cancelStream()); @@ -151,6 +155,10 @@ export function Chat() { const { widget, highlights } = useFindWidget(stepsDivRef); + const currentToolCallApplyState = useAppSelector( + selectCurrentToolCallApplyState, + ); + const sendInput = useCallback( ( editorState: JSONContent, @@ -163,6 +171,14 @@ export function Chat() { "Cannot submit message while awaiting tool confirmation", ); } + if ( + currentToolCallApplyState && + currentToolCallApplyState.status !== "closed" + ) { + return console.error( + "Cannot submit message while awaiting tool call apply", + ); + } if (selectedChatModel?.provider === "free-trial") { const newCount = incrementFreeTrialCount(); @@ -246,7 +262,6 @@ export function Chat() { defaultContextProviders: [], availableSlashCommands: [], dispatch, - selectedModelTitle: selectedChatModel.title, }); const prompt = [ @@ -340,11 +355,8 @@ export function Chat() { inputId={item.message.id} /> - ) : item.message.role === "tool" ? null : // - item.message.role === "assistant" && + ) : item.message.role === "tool" ? null : item.message.role === // /> // toolCallId={item.message.toolCallId} // contextItems={item.contextItems} // @@ -355,6 +367,7 @@ export function Chat() { toolCallState={item.toolCallState!} toolCall={toolCall} output={history[index + 1]?.contextItems} + historyIndex={index} />
); diff --git a/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx b/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx new file mode 100644 index 000000000..3f38623f8 --- /dev/null +++ b/gui/src/pages/gui/ModelsAddOnLimitDialog.tsx @@ -0,0 +1,44 @@ +import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; +import { useContext } from "react"; +import { SecondaryButton } from "../../components"; +import { DiscordIcon } from "../../components/svg/DiscordIcon"; +import { GithubIcon } from "../../components/svg/GithubIcon"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; + +export function ModelsAddOnLimitDialog() { + const ideMessenger = useContext(IdeMessengerContext); + + return ( +
+

Models Add-On Limit Reached

+ +
+ + You have reached the monthly limit for chat requests with the Models + Add-On. This limit exists to avoid abuse, but if this happened from + normal usage we encourage you to contact us on GitHub or Discord + +
+ { + ideMessenger.post("openUrl", GITHUB_LINK); + }} + > + + Github + + { + ideMessenger.post("openUrl", DISCORD_LINK); + }} + > + + Discord + +
+
+
+ ); +} diff --git a/gui/src/pages/gui/StreamError.tsx b/gui/src/pages/gui/StreamError.tsx index 35fe3dc91..d098d2bc4 100644 --- a/gui/src/pages/gui/StreamError.tsx +++ b/gui/src/pages/gui/StreamError.tsx @@ -1,6 +1,9 @@ -import { Cog8ToothIcon } from "@heroicons/react/24/outline"; +import { + ArrowTopRightOnSquareIcon, + Cog8ToothIcon, +} from "@heroicons/react/24/outline"; import { DISCORD_LINK, GITHUB_LINK } from "core/util/constants"; -import { useContext } from "react"; +import { useContext, useMemo } from "react"; import { Button, SecondaryButton } from "../../components"; import { DiscordIcon } from "../../components/svg/DiscordIcon"; import { GithubIcon } from "../../components/svg/GithubIcon"; @@ -13,10 +16,22 @@ import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; import { isLocalProfile } from "../../util"; import { providers } from "../AddNewModel/configs/providers"; +import { ModelsAddOnLimitDialog } from "./ModelsAddOnLimitDialog"; interface StreamErrorProps { error: unknown; } + +function parseErrorMessage(fullErrMsg: string): string { + const msg = fullErrMsg.split("\n\n").slice(1).join("\n\n"); + try { + const parsed = JSON.parse(msg); + return parsed.error ?? parsed.message ?? msg; + } catch (e) { + return msg; + } +} + const StreamErrorDialog = ({ error }: StreamErrorProps) => { const dispatch = useAppDispatch(); const ideMessenger = useContext(IdeMessengerContext); @@ -25,6 +40,11 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { const selectedProfile = useAppSelector(selectSelectedProfile); const { session, refreshProfiles } = useAuth(); + const parsedError = useMemo( + () => parseErrorMessage((error as any)?.message || ""), + [error], + ); + const handleRefreshProfiles = () => { refreshProfiles(); dispatch(setShowDialog(false)); @@ -103,6 +123,12 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { ); + if ( + parsedError === "You have exceeded the chat limit for the Models Add-On." + ) { + return ; + } + let errorContent: React.ReactNode = <>; // Display components for specific errors @@ -206,19 +232,22 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { } return ( -
-

{`${statusCode ? statusCode + " " : ""}Error`}

+
+

{`Error (status code ${statusCode})`}

{message ? ( -
- {message} +
+ + {parsedError} +
{ ideMessenger.post("toggleDevTools", undefined); }} > View Logs +
) : null} @@ -246,16 +275,6 @@ const StreamErrorDialog = ({ error }: StreamErrorProps) => { Discord
-
- -
); diff --git a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx index 7e50b7305..a3e81355b 100644 --- a/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/CreateFile.tsx @@ -4,6 +4,7 @@ import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; interface CreateFileToolCallProps { relativeFilepath: string; fileContents: string; + historyIndex: number; } export function CreateFile(props: CreateFileToolCallProps) { @@ -14,6 +15,7 @@ export function CreateFile(props: CreateFileToolCallProps) { isRenderingInStepContainer disableManualApply source={src} + itemIndex={props.historyIndex} /> ) : null; } diff --git a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx index 304dcb4c7..35b9d1a5f 100644 --- a/gui/src/pages/gui/ToolCallDiv/EditFile.tsx +++ b/gui/src/pages/gui/ToolCallDiv/EditFile.tsx @@ -1,26 +1,40 @@ import { getMarkdownLanguageTagForFile } from "core/util"; -import { useMemo } from "react"; +import { useEffect } from "react"; +import { v4 as uuidv4 } from "uuid"; import AcceptRejectAllButtons from "../../../components/AcceptRejectAllButtons"; import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview"; -import { useAppSelector } from "../../../redux/hooks"; +import { useAppDispatch, useAppSelector } from "../../../redux/hooks"; +import { + selectApplyStateByToolCallId, + updateApplyState, +} from "../../../redux/slices/sessionSlice"; type EditToolCallProps = { relativeFilePath: string; - newContents: string; + changes: string; toolCallId?: string; + historyIndex: number; }; export function EditFile(props: EditToolCallProps) { - const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.newContents ?? ""}\n\`\`\``; + const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes ?? ""}\n\`\`\``; + const dispatch = useAppDispatch(); const isStreaming = useAppSelector((state) => state.session.isStreaming); - const states = useAppSelector((store) => store.session.codeBlockApplyStates); - - const applyState = useMemo(() => { - return states.states.find( - (state) => state.toolCallId && state.toolCallId === props.toolCallId, - ); - }, [states, props.toolCallId]); + const applyState = useAppSelector((state) => + selectApplyStateByToolCallId(state, props.toolCallId), + ); + useEffect(() => { + if (!applyState) { + dispatch( + updateApplyState({ + streamId: uuidv4(), + toolCallId: props.toolCallId, + status: "not-started", + }), + ); + } + }, [applyState, props.toolCallId]); if (!props.relativeFilePath) { return null; @@ -32,8 +46,9 @@ export function EditFile(props: EditToolCallProps) { isRenderingInStepContainer disableManualApply source={src} - singleCodeblockStreamId={applyState?.streamId} + forceStreamId={applyState?.streamId} expandCodeblocks={false} + itemIndex={props.historyIndex} /> {/* TODO better indicator of generation at bottom */} {/* {isStreaming && applyState?.status === "streaming" && ( diff --git a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx index d9906794e..516282d74 100644 --- a/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx +++ b/gui/src/pages/gui/ToolCallDiv/FunctionSpecificToolCallDiv.tsx @@ -7,9 +7,11 @@ import { RunTerminalCommand } from "./RunTerminalCommand"; function FunctionSpecificToolCallDiv({ toolCall, toolCallState, + historyIndex, }: { toolCall: ToolCallDelta; toolCallState: ToolCallState; + historyIndex: number; }) { const args = toolCallState.parsedArgs; @@ -19,14 +21,16 @@ function FunctionSpecificToolCallDiv({ ); case BuiltInToolNames.EditExistingFile: return ( ); case BuiltInToolNames.RunTerminalCommand: diff --git a/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx new file mode 100644 index 000000000..d041943b5 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/SimpleToolCallUI.tsx @@ -0,0 +1,97 @@ +import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; +import { ContextItemWithId, Tool, ToolCallState } from "core"; +import { ComponentType, useMemo, useState } from "react"; +import { ContextItemsPeekItem } from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; +import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; +import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; + +interface SimpleToolCallUIProps { + toolCallState: ToolCallState; + tool: Tool | undefined; + contextItems: ContextItemWithId[]; + icon?: ComponentType>; +} + +export function SimpleToolCallUI({ + contextItems, + icon: Icon, + toolCallState, + tool, +}: SimpleToolCallUIProps) { + const ctxItems = useMemo(() => { + return contextItems?.filter((ctxItem) => !ctxItem.hidden) ?? []; + }, [contextItems]); + + const [open, setOpen] = useState(false); + const [isHovered, setIsHovered] = useState(false); + + const [showingArgs, setShowingArgs] = useState(false); + + const args: [string, any][] = useMemo(() => { + return Object.entries(toolCallState.parsedArgs); + }, [toolCallState.parsedArgs]); + + return ( +
+
+
setOpen((prev) => !prev)} + onMouseEnter={() => setIsHovered(true)} + onMouseLeave={() => setIsHovered(false)} + data-testid="context-items-peek" + > +
+ {Icon && !isHovered && !open ? ( + + ) : ( + <> + + + + )} +
+ + + +
+
+ {args.length > 0 ? ( + + ) : null} +
+
+ +
+ {ctxItems.length ? ( + ctxItems.map((contextItem, idx) => ( + + )) + ) : ( +
+ No tool call output +
+ )} +
+
+ ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx index 0abee8f3f..6f313236d 100644 --- a/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx +++ b/gui/src/pages/gui/ToolCallDiv/ToolCall.tsx @@ -1,99 +1,26 @@ -import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline"; -import { Tool, ToolCallDelta, ToolCallState } from "core"; -import Mustache from "mustache"; -import { ReactNode, useMemo, useState } from "react"; -import { ToolTip } from "../../../components/gui/Tooltip"; -import { useAppSelector } from "../../../redux/hooks"; +import { Tool, ToolCallState } from "core"; +import { useMemo, useState } from "react"; +import { ArgsItems, ArgsToggleIcon } from "./ToolCallArgs"; +import { ToolCallStatusMessage } from "./ToolCallStatusMessage"; interface ToolCallDisplayProps { children: React.ReactNode; icon: React.ReactNode; - toolCall: ToolCallDelta; + tool: Tool | undefined; toolCallState: ToolCallState; } -export function getToolCallStatusMessage( - tool: Tool | undefined, - toolCallState: ToolCallState, -) { - if (!tool) return "Agent tool use"; - - const defaultToolDescription = ( - <> - {tool.displayTitle ?? tool.function.name} tool - - ); - - const futureMessage = tool.wouldLikeTo ? ( - Mustache.render(tool.wouldLikeTo, toolCallState.parsedArgs) - ) : ( - <> - use the {defaultToolDescription} - - ); - - let intro = ""; - let message: ReactNode = ""; - - if ( - toolCallState.status === "done" || - (tool.isInstant && toolCallState.status === "calling") - ) { - intro = ""; - message = tool.hasAlready ? ( - Mustache.render(tool.hasAlready, toolCallState.parsedArgs) - ) : ( - <> - used the {defaultToolDescription} - - ); - } else if (toolCallState.status === "generating") { - intro = "is generating output to"; - message = futureMessage; - } else if (toolCallState.status === "generated") { - intro = "wants to"; - message = futureMessage; - } else if (toolCallState.status === "calling") { - intro = "is"; - message = tool.isCurrently ? ( - Mustache.render(tool.isCurrently, toolCallState.parsedArgs) - ) : ( - <> - calling the {defaultToolDescription} - - ); - } else if (toolCallState.status === "canceled") { - intro = "tried to"; - message = futureMessage; - } - return ( -
- Continue {intro} {message} -
- ); -} - -export function ToolCallDisplay(props: ToolCallDisplayProps) { - const [isExpanded, setIsExpanded] = useState(false); - const availableTools = useAppSelector((state) => state.config.config.tools); - - const tool = useMemo(() => { - return availableTools.find( - (tool) => props.toolCall.function?.name === tool.function.name, - ); - }, [availableTools, props.toolCall]); - - const statusMessage = useMemo(() => { - return getToolCallStatusMessage(tool, props.toolCallState); - }, [props.toolCallState, tool]); +export function ToolCallDisplay({ + tool, + toolCallState, + children, + icon, +}: ToolCallDisplayProps) { + const [argsExpanded, setArgsExpanded] = useState(false); const args: [string, any][] = useMemo(() => { - return Object.entries(props.toolCallState.parsedArgs); - }, [props.toolCallState.parsedArgs]); - - const argsTooltipId = useMemo(() => { - return "args-hover-" + props.toolCallState.toolCallId; - }, [props.toolCallState]); + return Object.entries(toolCallState.parsedArgs); + }, [toolCallState.parsedArgs]); return ( <> @@ -101,54 +28,32 @@ export function ToolCallDisplay(props: ToolCallDisplayProps) {
-
- {props.icon} +
+ {icon}
{tool?.faviconUrl && ( )}
- {statusMessage} +
{!!args.length ? ( -
setIsExpanded(!isExpanded)} - className="ml-2 cursor-pointer hover:opacity-80" - > - {isExpanded ? ( - - ) : ( - - )} -
+ ) : null} - - {isExpanded ? "Hide args" : "Show args"} -
- - {isExpanded && !!args.length && ( -
- {args.map(([key, value]) => ( -
- {key}: - {value.toString()} -
- ))} -
+ {argsExpanded && !!args.length && ( + )}
-
{props.children}
+
{children}
); diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx new file mode 100644 index 000000000..738be01f9 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallArgs.tsx @@ -0,0 +1,64 @@ +import { CodeBracketIcon } from "@heroicons/react/24/outline"; +import { useMemo } from "react"; +import { ToolTip } from "../../../components/gui/Tooltip"; + +interface ArgsToggleIconProps { + isShowing: boolean; + setIsShowing: (val: boolean) => void; + toolCallId: string; +} + +export const ArgsToggleIcon = ({ + isShowing, + setIsShowing, + toolCallId, +}: ArgsToggleIconProps) => { + const argsTooltipId = useMemo(() => { + return "args-hover-" + toolCallId; + }, [toolCallId]); + + return ( + <> +
{ + e.stopPropagation(); + setIsShowing(!isShowing); + }} + className={`cursor-pointer select-none rounded-sm px-1 py-0.5 hover:bg-gray-400/40 hover:opacity-80 ${isShowing ? "bg-gray-400/40" : "bg-transparent"}`} + > + + {/* {`{}`} */} +
+ + {isShowing ? "Hide args" : "Show args"} + + + ); +}; + +interface ArgsItemsProps { + isShowing: boolean; + args: [string, string][]; +} + +export const ArgsItems = ({ args, isShowing }: ArgsItemsProps) => { + if (args.length === 0) { + return null; + } + + if (!isShowing) { + return null; + } + + return ( +
+ {args.map(([key, value]) => ( +
+ {key}: + {value.toString()} +
+ ))} +
+ ); +}; diff --git a/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx new file mode 100644 index 000000000..e4e4c6e42 --- /dev/null +++ b/gui/src/pages/gui/ToolCallDiv/ToolCallStatusMessage.tsx @@ -0,0 +1,72 @@ +import { Tool, ToolCallState } from "core"; +import Mustache from "mustache"; +import { ReactNode } from "react"; + +interface ToolCallStatusMessageProps { + tool: Tool | undefined; + toolCallState: ToolCallState; +} + +export function ToolCallStatusMessage({ + tool, + toolCallState, +}: ToolCallStatusMessageProps) { + if (!tool) return "Agent tool use"; + + const defaultToolDescription = ( + <> + {tool.displayTitle ?? tool.function.name} tool + + ); + + const futureMessage = tool.wouldLikeTo ? ( + Mustache.render(tool.wouldLikeTo, toolCallState.parsedArgs) + ) : ( + <> + use the {defaultToolDescription} + + ); + + let intro = ""; + let message: ReactNode = ""; + + if ( + toolCallState.status === "done" || + (tool.isInstant && toolCallState.status === "calling") + ) { + intro = ""; + message = tool.hasAlready ? ( + Mustache.render(tool.hasAlready, toolCallState.parsedArgs) + ) : ( + <> + used the {defaultToolDescription} + + ); + } else if (toolCallState.status === "generating") { + intro = "is generating output to"; + message = futureMessage; + } else if (toolCallState.status === "generated") { + intro = "wants to"; + message = futureMessage; + } else if (toolCallState.status === "calling") { + intro = "is"; + message = tool.isCurrently ? ( + Mustache.render(tool.isCurrently, toolCallState.parsedArgs) + ) : ( + <> + calling the {defaultToolDescription} + + ); + } else if ( + toolCallState.status === "canceled" || + toolCallState.status === "errored" + ) { + intro = "tried to"; + message = futureMessage; + } + return ( +
+ Continue {intro} {message} +
+ ); +} diff --git a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx b/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx deleted file mode 100644 index 069f839ca..000000000 --- a/gui/src/pages/gui/ToolCallDiv/ToolOutput.tsx +++ /dev/null @@ -1,31 +0,0 @@ -import { ContextItemWithId } from "core"; -import { ComponentType } from "react"; -import ContextItemsPeek from "../../../components/mainInput/belowMainInput/ContextItemsPeek"; - -interface ToolOutputProps { - contextItems: ContextItemWithId[]; - toolCallId: string; - icon?: ComponentType; - title?: JSX.Element | string; -} - -function ToolOutput(props: ToolOutputProps) { - // Terminal has dedicated UI to show the output - if (props.contextItems.some((ci) => ci.name === "Terminal")) { - return null; - } - - return ( -
- -
- ); -} - -export default ToolOutput; diff --git a/gui/src/pages/gui/ToolCallDiv/index.tsx b/gui/src/pages/gui/ToolCallDiv/index.tsx index 06cf74515..39d14cd0a 100644 --- a/gui/src/pages/gui/ToolCallDiv/index.tsx +++ b/gui/src/pages/gui/ToolCallDiv/index.tsx @@ -10,6 +10,7 @@ import { GlobeAltIcon, MagnifyingGlassIcon, MapIcon, + PencilIcon, XMarkIcon, } from "@heroicons/react/24/outline"; import { @@ -24,13 +25,14 @@ import { vscButtonBackground } from "../../../components"; import Spinner from "../../../components/gui/Spinner"; import { useAppSelector } from "../../../redux/hooks"; import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv"; -import { getToolCallStatusMessage, ToolCallDisplay } from "./ToolCall"; -import ToolOutput from "./ToolOutput"; +import { SimpleToolCallUI } from "./SimpleToolCallUI"; +import { ToolCallDisplay } from "./ToolCall"; interface ToolCallDivProps { toolCall: ToolCallDelta; toolCallState: ToolCallState; output?: ContextItemWithId[]; + historyIndex: number; } const toolCallIcons: Record = { @@ -43,23 +45,28 @@ const toolCallIcons: Record = { [BuiltInToolNames.ViewDiff]: CodeBracketIcon, [BuiltInToolNames.ViewRepoMap]: MapIcon, [BuiltInToolNames.ViewSubdirectory]: FolderOpenIcon, + [BuiltInToolNames.CreateRuleBlock]: PencilIcon, + // EditExistingFile = "builtin_edit_existing_file", + // CreateNewFile = "builtin_create_new_file", + // RunTerminalCommand = "builtin_run_terminal_command", }; -export function ToolCallDiv(props: ToolCallDivProps) { - function getIcon(state: ToolStatus) { - switch (state) { - case "generating": - case "calling": - return ; - case "generated": - return ; - case "done": - return ; - case "canceled": - return ; - } +function getStatusIcon(state: ToolStatus) { + switch (state) { + case "generating": + case "calling": + return ; + case "generated": + return ; + case "done": + return ; + case "canceled": + case "errored": + return ; } +} +export function ToolCallDiv(props: ToolCallDivProps) { const availableTools = useAppSelector((state) => state.config.config.tools); const tool = useMemo(() => { return availableTools.find( @@ -67,23 +74,20 @@ export function ToolCallDiv(props: ToolCallDivProps) { ); }, [availableTools, props.toolCall]); - const statusMessage = useMemo(() => { - return getToolCallStatusMessage(tool, props.toolCallState); - }, [props.toolCallState, tool]); - const icon = props.toolCall.function?.name && - toolCallIcons[props.toolCall.function?.name]; - if (icon && props.toolCall.id) { + toolCallIcons[props.toolCall.function.name]; + + if (icon) { return ( -
- +
); @@ -91,13 +95,14 @@ export function ToolCallDiv(props: ToolCallDivProps) { return ( ); diff --git a/gui/src/pages/history/history.test.tsx b/gui/src/pages/history/history.test.tsx index 9a9d2772c..8ab4f2862 100644 --- a/gui/src/pages/history/history.test.tsx +++ b/gui/src/pages/history/history.test.tsx @@ -2,19 +2,21 @@ import { screen } from "@testing-library/dom"; import { renderWithProviders } from "../../util/test/render"; import HistoryPage from "./index"; -const navigateFn = vi.fn(); - -vi.mock("react-router-dom", async () => { - const original = await vi.importActual("react-router-dom"); - return { - ...original, - useNavigate: () => navigateFn, - }; -}); - describe("history Page test", () => { - it("History text is existed after render", () => { - renderWithProviders(); + it("History text is existed after render", async () => { + await renderWithProviders(); expect(screen.getByTestId("history-sessions-note")).toBeInTheDocument(); }); + + it("History shows the first item in the list", async () => { + await renderWithProviders(); + const sessionElement = await screen.findByText( + "Session 1", + {}, + { + timeout: 3000, // There is a 2000ms timeout before the first call to refreshSessionMetadata is called + }, + ); + expect(sessionElement).toBeInTheDocument(); + }); }); diff --git a/gui/src/redux/selectors/index.ts b/gui/src/redux/selectors/index.ts index cca27e6e2..bbfea5364 100644 --- a/gui/src/redux/selectors/index.ts +++ b/gui/src/redux/selectors/index.ts @@ -47,7 +47,5 @@ export const selectUseActiveFile = createSelector( (defaultContext) => defaultContext?.includes("activeFile" as any), ); -export const selectUseHub = createSelector( - [(state: RootState) => state.config.config.usePlatform], - (usePlatform) => usePlatform, -); +export const selectUseHub = (state: RootState) => + state.config.config.usePlatform; diff --git a/gui/src/redux/selectors/selectActiveTools.ts b/gui/src/redux/selectors/selectActiveTools.ts new file mode 100644 index 000000000..bae3426e0 --- /dev/null +++ b/gui/src/redux/selectors/selectActiveTools.ts @@ -0,0 +1,22 @@ +import { createSelector } from "@reduxjs/toolkit"; +import { Tool } from "core"; +import { RootState } from "../store"; + +export const selectActiveTools = createSelector( + [ + (store: RootState) => store.session.mode, + (store: RootState) => store.config.config.tools, + (store: RootState) => store.ui.toolSettings, + (store: RootState) => store.ui.toolGroupSettings, + ], + (mode, tools, policies, groupPolicies): Tool[] => { + if (mode !== "agent") { + return []; + } + return tools.filter( + (tool) => + policies[tool.function.name] !== "disabled" && + groupPolicies[tool.group] !== "exclude", + ); + }, +); diff --git a/gui/src/redux/selectors/selectCurrentToolCall.ts b/gui/src/redux/selectors/selectCurrentToolCall.ts index eb0bf669b..56c3a6cc1 100644 --- a/gui/src/redux/selectors/selectCurrentToolCall.ts +++ b/gui/src/redux/selectors/selectCurrentToolCall.ts @@ -8,3 +8,20 @@ export const selectCurrentToolCall = createSelector( return findCurrentToolCall(history); }, ); + +export const selectCurrentToolCallApplyState = createSelector( + [ + (store: RootState) => store.session.history, + (store: RootState) => store.session.codeBlockApplyStates, + ], + (history, applyStates) => { + const currentToolCall = findCurrentToolCall(history); + if (!currentToolCall) { + return undefined; + } + return applyStates.states.find( + (state) => + state.toolCallId && state.toolCallId === currentToolCall.toolCallId, + ); + }, +); diff --git a/gui/src/redux/slices/sessionSlice.ts b/gui/src/redux/slices/sessionSlice.ts index 7c065a9ae..5f74e0c50 100644 --- a/gui/src/redux/slices/sessionSlice.ts +++ b/gui/src/redux/slices/sessionSlice.ts @@ -21,7 +21,6 @@ import { ToolCallDelta, ToolCallState, } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; import { NEW_SESSION_TITLE } from "core/util/constants"; import { incrementalParseJson } from "core/util/incrementalParseJson"; import { renderChatMessage } from "core/util/messageContent"; @@ -29,7 +28,7 @@ import { findUriInDirs, getUriPathBasename } from "core/util/uri"; import { v4 as uuidv4 } from "uuid"; import { RootState } from "../store"; import { streamResponseThunk } from "../thunks/streamResponse"; -import { findCurrentToolCall } from "../util"; +import { findCurrentToolCall, findToolCall } from "../util"; // We need this to handle reorderings (e.g. a mid-array deletion) of the messages array. // The proper fix is adding a UUID to all chat messages, but this is the temp workaround. @@ -54,7 +53,6 @@ type SessionState = { states: ApplyState[]; curIndex: number; }; - activeToolStreamId?: [string, string]; newestToolbarPreviewForInput: Record; }; @@ -357,7 +355,7 @@ export const sessionSlice = createSlice({ if ( !( toolCallDelta.id && - toolCallDelta.function?.arguments && + toolCallDelta.function?.arguments !== undefined && toolCallDelta.function?.name && toolCallDelta.type ) @@ -368,19 +366,6 @@ export const sessionSlice = createSlice({ ); } - if ( - toolCallDelta.id && - toolCallDelta.function?.name === - BuiltInToolNames.EditExistingFile - ) { - const streamId = uuidv4(); - state.codeBlockApplyStates.states.push({ - streamId, - toolCallId: toolCallDelta.id, - status: "streaming", - }); - state.activeToolStreamId = [streamId, toolCallDelta.id]; - } historyItem.toolCallState = toolCallDeltaToState(toolCallDelta); } state.history.push(historyItem); @@ -624,54 +609,91 @@ export const sessionSlice = createSlice({ clearCodeToEdit: (state) => { state.codeToEdit = []; }, - // Related to currentToolCallState - setToolGenerated: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "generated"; - }, - setToolCallOutput: (state, action: PayloadAction) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.output = action.payload; + // TOOL CALL STATE + setToolGenerated: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "generated"; + } }, updateToolCallOutput: ( state, - action: PayloadAction<{ toolCallId: string; contextItems: ContextItem[] }>, + action: PayloadAction<{ + toolCallId: string; + contextItems: ContextItem[]; + }>, ) => { - // Find the tool call with the given ID and update its output - const { toolCallId, contextItems } = action.payload; - - // Find the history item containing the tool call - const historyItem = state.history.find( - (item) => - item.toolCallState?.toolCallId === toolCallId + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, ); - - if (historyItem && historyItem.toolCallState) { - historyItem.toolCallState.output = contextItems; + if (toolCallState) { + toolCallState.output = action.payload.contextItems; } }, - cancelToolCall: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "canceled"; + cancelToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "canceled"; + } }, - acceptToolCall: (state) => { - state.activeToolStreamId = undefined; - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "done"; + errorToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "errored"; + } }, - setCalling: (state) => { - const toolCallState = findCurrentToolCall(state.history); - if (!toolCallState) return; - - toolCallState.status = "calling"; + acceptToolCall: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "done"; + } + }, + setToolCallCalling: ( + state, + action: PayloadAction<{ + toolCallId: string; + }>, + ) => { + const toolCallState = findToolCall( + state.history, + action.payload.toolCallId, + ); + if (toolCallState) { + toolCallState.status = "calling"; + } }, setMode: (state, action: PayloadAction) => { state.mode = action.payload; @@ -722,9 +744,6 @@ export const sessionSlice = createSlice({ selectHasCodeToEdit: (state) => { return state.codeToEdit.length > 0; }, - selectUseTools: (state) => { - return state.mode === "agent"; - }, }, extraReducers: (builder) => { addPassthroughCases(builder, [streamResponseThunk]); @@ -760,6 +779,16 @@ export const selectApplyStateByStreamId = createSelector( }, ); +export const selectApplyStateByToolCallId = createSelector( + [ + (state: RootState) => state.session.codeBlockApplyStates.states, + (state: RootState, toolCallId?: string) => toolCallId, + ], + (states, toolCallId) => { + return states.find((state) => state.toolCallId === toolCallId); + }, +); + export const { updateFileSymbols, setContextItemsAtIndex, @@ -785,11 +814,11 @@ export const { clearCodeToEdit, addCodeToEdit, removeCodeToEdit, - setCalling, + setToolCallCalling, cancelToolCall, + errorToolCall, acceptToolCall, setToolGenerated, - setToolCallOutput, updateToolCallOutput, setMode, setAllSessionMetadata, @@ -806,7 +835,6 @@ export const { selectCurrentMode, selectIsSingleRangeEditOrInsertion, selectHasCodeToEdit, - selectUseTools, } = sessionSlice.selectors; export default sessionSlice.reducer; diff --git a/gui/src/redux/slices/uiSlice.ts b/gui/src/redux/slices/uiSlice.ts index 7cc964cd6..4105d3319 100644 --- a/gui/src/redux/slices/uiSlice.ts +++ b/gui/src/redux/slices/uiSlice.ts @@ -1,18 +1,21 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { Tool } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; +import { BUILT_IN_GROUP_NAME, BuiltInToolNames } from "core/tools/builtIn"; import { defaultOnboardingCardState, OnboardingCardState, } from "../../components/OnboardingCard"; import { getLocalStorage, LocalStorageKey } from "../../util/localStorage"; -type ToolSetting = +export type ToolPolicy = | "allowedWithPermission" | "allowedWithoutPermission" | "disabled"; -type ToolGroupSetting = "include" | "exclude"; +export type ToolGroupPolicy = "include" | "exclude"; + +export type ToolPolicies = { [toolName: string]: ToolPolicy }; +export type ToolGroupPolicies = { [toolGroupName: string]: ToolGroupPolicy }; type UIState = { showDialog: boolean; @@ -22,12 +25,12 @@ type UIState = { isExploreDialogOpen: boolean; hasDismissedExploreDialog: boolean; shouldAddFileForEditing: boolean; - toolSettings: { [toolName: string]: ToolSetting }; - toolGroupSettings: { [toolGroupName: string]: ToolGroupSetting }; + toolSettings: ToolPolicies; + toolGroupSettings: ToolGroupPolicies; ttsActive: boolean; }; -export const DEFAULT_TOOL_SETTING: ToolSetting = "allowedWithPermission"; +export const DEFAULT_TOOL_SETTING: ToolPolicy = "allowedWithPermission"; export const uiSlice = createSlice({ name: "ui", @@ -55,7 +58,7 @@ export const uiSlice = createSlice({ [BuiltInToolNames.CreateRuleBlock]: "allowedWithPermission", }, toolGroupSettings: { - BUILT_IN_GROUP_NAME: "include", + [BUILT_IN_GROUP_NAME]: "include", }, } as UIState, reducers: { diff --git a/gui/src/redux/store.ts b/gui/src/redux/store.ts index c69e65315..aa7c2bb5c 100644 --- a/gui/src/redux/store.ts +++ b/gui/src/redux/store.ts @@ -1,4 +1,9 @@ -import { combineReducers, configureStore } from "@reduxjs/toolkit"; +import { + combineReducers, + configureStore, + ThunkDispatch, + UnknownAction, +} from "@reduxjs/toolkit"; import { createLogger } from "redux-logger"; import { createMigrate, @@ -104,7 +109,9 @@ const persistedReducer = persistReducer>( rootReducer, ); -export function setupStore() { +export function setupStore(options: { ideMessenger?: IIdeMessenger }) { + const ideMessenger = options.ideMessenger ?? new IdeMessenger(); + const logger = createLogger({ // Customize logger options if needed collapsed: true, // Collapse console groups by default @@ -121,7 +128,7 @@ export function setupStore() { serializableCheck: false, thunk: { extraArgument: { - ideMessenger: new IdeMessenger(), + ideMessenger, }, }, }), @@ -130,12 +137,20 @@ export function setupStore() { }); } +export type ThunkExtrasType = { ideMessenger: IIdeMessenger }; + export type ThunkApiType = { state: RootState; - extra: { ideMessenger: IIdeMessenger }; + extra: ThunkExtrasType; }; -export const store = setupStore(); +export type AppThunkDispatch = ThunkDispatch< + RootState, + ThunkExtrasType, + UnknownAction +>; + +export const store = setupStore({}); export type RootState = ReturnType; diff --git a/gui/src/redux/thunks/callCurrentTool.ts b/gui/src/redux/thunks/callCurrentTool.ts new file mode 100644 index 000000000..f6f408238 --- /dev/null +++ b/gui/src/redux/thunks/callCurrentTool.ts @@ -0,0 +1,137 @@ +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { ContextItem } from "core"; +import { CLIENT_TOOLS } from "core/tools/builtIn"; +import { callClientTool } from "../../util/clientTools/callClientTool"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { selectSelectedChatModel } from "../slices/configSlice"; +import { + acceptToolCall, + errorToolCall, + setToolCallCalling, + updateToolCallOutput, +} from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const callCurrentTool = createAsyncThunk( + "chat/callTool", + async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + const selectedChatModel = selectSelectedChatModel(state); + + if (!selectedChatModel) { + throw new Error("No model selected"); + } + + const { toolCallId } = toolCallState; + + dispatch( + setToolCallCalling({ + toolCallId, + }), + ); + + let output: ContextItem[] | undefined = undefined; + let errorMessage: string | undefined = undefined; + let streamResponse: boolean; + + // IMPORTANT: + // Errors that occur while calling tool call implementations + // Are caught and passed in output as context items + // Errors that occur outside specifically calling the tool + // Should not be caught here - should be handled as normal stream errors + if ( + CLIENT_TOOLS.find( + (toolName) => toolName === toolCallState.toolCall.function.name, + ) + ) { + // Tool is called on client side + const { + output: clientToolOuput, + respondImmediately, + errorMessage: clientToolError, + } = await callClientTool(toolCallState.toolCall, { + dispatch, + ideMessenger: extra.ideMessenger, + streamId: state.session.codeBlockApplyStates.states.find( + (state) => + state.toolCallId && state.toolCallId === toolCallState.toolCallId, + )?.streamId, + getState, + }); + output = clientToolOuput; + errorMessage = clientToolError; + streamResponse = respondImmediately; + } else { + // Tool is called on core side + const result = await extra.ideMessenger.request("tools/call", { + toolCall: toolCallState.toolCall, + }); + if (result.status === "error") { + throw new Error(result.error); + } else { + output = result.content.contextItems; + errorMessage = result.content.errorMessage; + } + streamResponse = true; + } + + if (errorMessage) { + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: [ + { + icon: "problems", + name: "Tool Call Error", + description: "Tool Call Failed", + content: `${toolCallState.toolCall.function.name} failed with the message: ${errorMessage}\n\nPlease try something else or request further instructions.`, + hidden: false, + }, + ], + }), + ); + } else if (output?.length) { + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: output, + }), + ); + } + + if (streamResponse) { + if (errorMessage) { + dispatch( + errorToolCall({ + toolCallId, + }), + ); + } else { + dispatch( + acceptToolCall({ + toolCallId, + }), + ); + } + + // Send to the LLM to continue the conversation + const wrapped = await dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + unwrapResult(wrapped); + } + }, +); diff --git a/gui/src/redux/thunks/callTool.ts b/gui/src/redux/thunks/callTool.ts deleted file mode 100644 index cb875f805..000000000 --- a/gui/src/redux/thunks/callTool.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ContextItem } from "core"; -import { BuiltInToolNames } from "core/tools/builtIn"; -import { EditToolArgs } from "core/tools/definitions/editFile"; -import { resolveRelativePathInDir } from "core/util/ideUtils"; -import { IIdeMessenger } from "../../context/IdeMessenger"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { selectSelectedChatModel } from "../slices/configSlice"; -import { - acceptToolCall, - cancelToolCall, - setCalling, - setToolCallOutput, - updateApplyState, -} from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const callTool = createAsyncThunk( - "chat/callTool", - async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - const selectedChatModel = selectSelectedChatModel(state); - - if (!selectedChatModel) { - throw new Error("No model selected"); - } - - dispatch(setCalling()); - - let errorMessage = ""; - let output: ContextItem[] | undefined = undefined; - - if ( - toolCallState.toolCall.function.name === BuiltInToolNames.EditExistingFile - ) { - const args = JSON.parse( - toolCallState.toolCall.function.arguments || "{}", - ); - try { - if (!state.session.activeToolStreamId) { - throw new Error("Invalid apply state"); - } - await customGuiEditImpl( - args, - extra.ideMessenger, - state.session.activeToolStreamId[0], - toolCallState.toolCallId, - ); - } catch (e) { - errorMessage = "Failed to call edit tool"; - if (e instanceof Error) { - errorMessage = e.message; - } - if (state.session.activeToolStreamId?.[0]) { - dispatch( - updateApplyState({ - streamId: state.session.activeToolStreamId[0], - status: "closed", - toolCallId: toolCallState.toolCallId, - numDiffs: 0, - filepath: args.filepath, - }), - ); - } - } - } else { - const result = await extra.ideMessenger.request("tools/call", { - toolCall: toolCallState.toolCall, - selectedModelTitle: selectedChatModel.title, - }); - if (result.status === "error") { - errorMessage = result.error; - } else { - output = result.content.contextItems; - } - } - - if (errorMessage) { - dispatch(cancelToolCall()); - - const wrapped = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - icon: "problems", - name: "Tool Call Error", - description: "Tool Call Failed", - content: `${toolCallState.toolCall.function.name} failed with the message:\n\n${errorMessage}\n\nPlease try something else or request further instructions.`, - hidden: false, - }, - ], - }), - ); - unwrapResult(wrapped); - } else if (output) { - dispatch(setToolCallOutput(output)); - dispatch(acceptToolCall()); - - // Send to the LLM to continue the conversation - const wrapped = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCall.id, - toolOutput: output, - }), - ); - unwrapResult(wrapped); - } - // okay for a tool to have no output and need some GUI trigger or other to trigger response e.g. edit tool - }, -); - -async function customGuiEditImpl( - args: EditToolArgs, - ideMessenger: IIdeMessenger, - streamId: string, - toolCallId: string, -) { - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - ideMessenger.ide, - ); - if (!firstUriMatch) { - throw new Error(`${args.filepath} does not exist`); - } - const apply = await ideMessenger.request("applyToFile", { - streamId, - text: args.new_contents, - toolCallId, - filepath: firstUriMatch, - }); - if (apply.status === "error") { - throw new Error(apply.error); - } -} diff --git a/gui/src/redux/thunks/cancelCurrentToolCall.ts b/gui/src/redux/thunks/cancelCurrentToolCall.ts new file mode 100644 index 000000000..f90d80ff6 --- /dev/null +++ b/gui/src/redux/thunks/cancelCurrentToolCall.ts @@ -0,0 +1,50 @@ +import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; +import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; +import { cancelToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { ThunkApiType } from "../store"; +import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; + +export const cancelCurrentToolCall = createAsyncThunk< + void, + undefined, + ThunkApiType +>("chat/cancelTool", async (_, { dispatch, extra, getState }) => { + const state = getState(); + const toolCallState = selectCurrentToolCall(state); + + if (!toolCallState) { + return; + } + + if (toolCallState.status !== "generated") { + return; + } + + const { toolCallId } = toolCallState; + dispatch( + cancelToolCall({ + toolCallId, + }), + ); + + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems: [ + { + name: "Tool Cancelled", + description: "Tool Cancelled", + content: + "The tool call was cancelled by the user. Please try something else or request further instructions.", + hidden: true, + }, + ], + }), + ); + const output = await dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + unwrapResult(output); +}); diff --git a/gui/src/redux/thunks/cancelStream.ts b/gui/src/redux/thunks/cancelStream.ts index c7346557c..515a02cfc 100644 --- a/gui/src/redux/thunks/cancelStream.ts +++ b/gui/src/redux/thunks/cancelStream.ts @@ -12,8 +12,9 @@ export const cancelStream = createAsyncThunk( dispatch(setInactive()); dispatch(abortStream()); + // In the case tool calls were being generated, + // Replace them with // If the assistant message is empty, then remove it and the user message, placing the user input in the main text box - // TODO: Waiting until next release dispatch(clearLastEmptyResponse()); }, ); diff --git a/gui/src/redux/thunks/cancelTool.ts b/gui/src/redux/thunks/cancelTool.ts deleted file mode 100644 index d46195674..000000000 --- a/gui/src/redux/thunks/cancelTool.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; -import { cancelToolCall } from "../slices/sessionSlice"; -import { ThunkApiType } from "../store"; -import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; - -export const cancelTool = createAsyncThunk( - "chat/cancelTool", - async (_, { dispatch, extra, getState }) => { - const state = getState(); - const toolCallState = selectCurrentToolCall(state); - - if (!toolCallState) { - return; - } - - if (toolCallState.status !== "generated") { - return; - } - - dispatch(cancelToolCall()); - - const output = await dispatch( - streamResponseAfterToolCall({ - toolCallId: toolCallState.toolCallId, - toolOutput: [ - { - name: "Tool Cancelled", - description: "Tool Cancelled", - content: - "The tool call was cancelled by the user. Please try something else or request further instructions.", - hidden: true, - }, - ], - }), - ); - unwrapResult(output); - }, -); diff --git a/gui/src/redux/thunks/gatherContext.ts b/gui/src/redux/thunks/gatherContext.ts index 2ba244d3f..4b8f00286 100644 --- a/gui/src/redux/thunks/gatherContext.ts +++ b/gui/src/redux/thunks/gatherContext.ts @@ -58,7 +58,6 @@ export const gatherContext = createAsyncThunk< defaultContextProviders, availableSlashCommands: state.config.config.slashCommands, dispatch, - selectedModelTitle: selectedChatModel.title, }); // Automatically use currently open file @@ -72,7 +71,6 @@ export const gatherContext = createAsyncThunk< query: "non-mention-usage", fullInput: "", selectedCode: [], - selectedModelTitle: selectedChatModel.title, }, ); if (currentFileResponse.status === "success") { diff --git a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts index 1b592f549..c3f0a39d0 100644 --- a/gui/src/redux/thunks/moveTerminalProcessToBackground.ts +++ b/gui/src/redux/thunks/moveTerminalProcessToBackground.ts @@ -1,6 +1,10 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { ContextItem } from "core"; -import { abortStream, acceptToolCall, updateToolCallOutput } from "../slices/sessionSlice"; +import { + abortStream, + acceptToolCall, + updateToolCallOutput, +} from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; import { streamResponseAfterToolCall } from "./streamResponseAfterToolCall"; @@ -15,54 +19,64 @@ export const moveTerminalProcessToBackground = createAsyncThunk< void, { toolCallId: string }, ThunkApiType ->("chat/moveTerminalProcessToBackground", async ({ toolCallId }, { dispatch, getState, extra }) => { - // Find the current tool call - const state = getState(); - const toolCalls = state.session.history.filter( - (item) => item.toolCallState?.toolCallId === toolCallId - ); +>( + "chat/moveTerminalProcessToBackground", + async ({ toolCallId }, { dispatch, getState, extra }) => { + // Find the current tool call + const state = getState(); + const toolCalls = state.session.history.filter( + (item) => item.toolCallState?.toolCallId === toolCallId, + ); - if (toolCalls.length === 0) { - console.error("Could not find tool call with ID:", toolCallId); - return; - } - - const toolCall = toolCalls[0].toolCallState; - if (!toolCall) { - console.error("Tool call state is missing"); - return; - } - - const status = "Command moved to background. Further output will be ignored." - - const contextItems: ContextItem[] = [ - { - name: "Terminal", - description: "Terminal command output", - content: "\n" + status, - status: status, + if (toolCalls.length === 0) { + console.error("Could not find tool call with ID:", toolCallId); + return; } - ]; - // Abort any existing stream for this tool call - dispatch(abortStream()); + const toolCall = toolCalls[0].toolCallState; + if (!toolCall) { + console.error("Tool call state is missing"); + return; + } - // Update the tool call output - dispatch(updateToolCallOutput({ - toolCallId, - contextItems - })); + const status = + "Command moved to background. Further output will be ignored."; - // Mark the process as backgrounded so we ignore future events - await extra.ideMessenger.request("process/markAsBackgrounded", { toolCallId }); + const contextItems: ContextItem[] = [ + { + name: "Terminal", + description: "Terminal command output", + content: "\n" + status, + status: status, + }, + ]; - // Mark the tool call as "done" in the UI - // This will set isRunning to false in RunTerminalCommand.tsx - dispatch(acceptToolCall()); + // Abort any existing stream for this tool call + dispatch(abortStream()); - // Trigger an LLM response about the command being moved to background - dispatch(streamResponseAfterToolCall({ - toolCallId, - toolOutput: contextItems - })); -}); \ No newline at end of file + // Update the tool call output + dispatch( + updateToolCallOutput({ + toolCallId, + contextItems, + }), + ); + + // Mark the process as backgrounded so we ignore future events + await extra.ideMessenger.request("process/markAsBackgrounded", { + toolCallId, + }); + + // Mark the tool call as "done" in the UI + // This will set isRunning to false in RunTerminalCommand.tsx + dispatch(acceptToolCall({ toolCallId })); + + // Trigger an LLM response about the command being moved to background + dispatch(updateToolCallOutput({ toolCallId, contextItems })); + dispatch( + streamResponseAfterToolCall({ + toolCallId, + }), + ); + }, +); diff --git a/gui/src/redux/thunks/session.ts b/gui/src/redux/thunks/session.ts index 7572b1fe4..e9c0bffe8 100644 --- a/gui/src/redux/thunks/session.ts +++ b/gui/src/redux/thunks/session.ts @@ -180,7 +180,6 @@ export const saveCurrentSession = createAsyncThunk< "chatDescriber/describe", { text: assistantResponse, - selectedModelTitle: selectedChatModel.title, }, ); if (result.status === "success" && result.content) { diff --git a/gui/src/redux/thunks/streamNormalInput.ts b/gui/src/redux/thunks/streamNormalInput.ts index c8b10dc37..43e431271 100644 --- a/gui/src/redux/thunks/streamNormalInput.ts +++ b/gui/src/redux/thunks/streamNormalInput.ts @@ -1,18 +1,18 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage } from "core"; +import { ChatMessage, LLMFullCompletionOptions } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { ToCoreProtocol } from "core/protocol"; +import { selectActiveTools } from "../selectors/selectActiveTools"; import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall"; import { selectSelectedChatModel } from "../slices/configSlice"; import { abortStream, addPromptCompletionPair, - selectUseTools, setToolGenerated, streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; -import { callTool } from "./callTool"; +import { callCurrentTool } from "./callCurrentTool"; export const streamNormalInput = createAsyncThunk< void, @@ -31,27 +31,24 @@ export const streamNormalInput = createAsyncThunk< const state = getState(); const selectedChatModel = selectSelectedChatModel(state); - const toolSettings = state.ui.toolSettings; - const toolGroupSettings = state.ui.toolGroupSettings; const streamAborter = state.session.streamAborter; - const useTools = selectUseTools(state); if (!selectedChatModel) { throw new Error("Default model not defined"); } - const includeTools = useTools && modelSupportsTools(selectedChatModel); + + let completionOptions: LLMFullCompletionOptions = {}; + const activeTools = selectActiveTools(state); + const toolsSupported = modelSupportsTools(selectedChatModel); + if (toolsSupported && activeTools.length > 0) { + completionOptions = { + tools: activeTools, + }; + } // Send request const gen = extra.ideMessenger.llmStreamChat( { - completionOptions: includeTools - ? { - tools: state.config.config.tools.filter( - (tool) => - toolSettings[tool.function.name] !== "disabled" && - toolGroupSettings[tool.group] !== "exclude", - ), - } - : {}, + completionOptions, title: selectedChatModel.title, messages, legacySlashCommandData, @@ -105,15 +102,21 @@ export const streamNormalInput = createAsyncThunk< } // If it's a tool call that is automatically accepted, we should call it - const toolCallState = selectCurrentToolCall(getState()); + const newState = getState(); + const toolSettings = newState.ui.toolSettings; + const toolCallState = selectCurrentToolCall(newState); if (toolCallState) { - dispatch(setToolGenerated()); + dispatch( + setToolGenerated({ + toolCallId: toolCallState.toolCallId, + }), + ); if ( toolSettings[toolCallState.toolCall.function.name] === "allowedWithoutPermission" ) { - const response = await dispatch(callTool()); + const response = await dispatch(callCurrentTool()); unwrapResult(response); } } diff --git a/gui/src/redux/thunks/streamResponse.ts b/gui/src/redux/thunks/streamResponse.ts index 63b5e6189..dd00b86fb 100644 --- a/gui/src/redux/thunks/streamResponse.ts +++ b/gui/src/redux/thunks/streamResponse.ts @@ -89,7 +89,6 @@ export const streamResponseThunk = createAsyncThunk< [...updatedHistory], selectedChatModel?.baseChatSystemMessage, state.config.config.rules, - selectedChatModel.model, ); posthog.capture("step run", { diff --git a/gui/src/redux/thunks/streamResponseAfterToolCall.ts b/gui/src/redux/thunks/streamResponseAfterToolCall.ts index 5a0083886..7ff0ee47e 100644 --- a/gui/src/redux/thunks/streamResponseAfterToolCall.ts +++ b/gui/src/redux/thunks/streamResponseAfterToolCall.ts @@ -1,5 +1,5 @@ import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit"; -import { ChatMessage, ContextItem } from "core"; +import { ChatMessage } from "core"; import { constructMessages } from "core/llm/constructMessages"; import { renderContextItems } from "core/util/messageContent"; import { selectSelectedChatModel } from "../slices/configSlice"; @@ -9,20 +9,18 @@ import { streamUpdate, } from "../slices/sessionSlice"; import { ThunkApiType } from "../store"; +import { findToolCall } from "../util"; import { resetStateForNewMessage } from "./resetStateForNewMessage"; import { streamNormalInput } from "./streamNormalInput"; import { streamThunkWrapper } from "./streamThunkWrapper"; export const streamResponseAfterToolCall = createAsyncThunk< void, - { - toolCallId: string; - toolOutput: ContextItem[]; - }, + { toolCallId: string }, ThunkApiType >( "chat/streamAfterToolCall", - async ({ toolCallId, toolOutput }, { dispatch, getState }) => { + async ({ toolCallId }, { dispatch, getState }) => { await dispatch( streamThunkWrapper(async () => { const state = getState(); @@ -33,6 +31,14 @@ export const streamResponseAfterToolCall = createAsyncThunk< throw new Error("No model selected"); } + const toolCallState = findToolCall(state.session.history, toolCallId); + + if (!toolCallState) { + throw new Error("Tool call not found"); + } + + const toolOutput = toolCallState.output ?? []; + resetStateForNewMessage(); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -63,7 +69,6 @@ export const streamResponseAfterToolCall = createAsyncThunk< [...updatedHistory], selectedChatModel?.baseChatSystemMessage, state.config.config.rules, - selectedChatModel.model, ); unwrapResult(await dispatch(streamNormalInput({ messages }))); diff --git a/gui/src/redux/thunks/streamThunkWrapper.tsx b/gui/src/redux/thunks/streamThunkWrapper.tsx index 7bd5a82f9..149782416 100644 --- a/gui/src/redux/thunks/streamThunkWrapper.tsx +++ b/gui/src/redux/thunks/streamThunkWrapper.tsx @@ -1,8 +1,9 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import StreamErrorDialog from "../../pages/gui/StreamError"; -import { clearLastEmptyResponse, setInactive } from "../slices/sessionSlice"; +import { setInactive } from "../slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../slices/uiSlice"; import { ThunkApiType } from "../store"; +import { cancelStream } from "./cancelStream"; import { saveCurrentSession } from "./session"; export const streamThunkWrapper = createAsyncThunk< @@ -12,14 +13,8 @@ export const streamThunkWrapper = createAsyncThunk< >("chat/streamWrapper", async (runStream, { dispatch, extra, getState }) => { try { await runStream(); - } catch (e: unknown) { - dispatch(clearLastEmptyResponse()); - dispatch(setDialogMessage()); - dispatch(setShowDialog(true)); - } finally { - dispatch(setInactive()); const state = getState(); - if (state.session.mode === "chat") { + if (state.session.mode === "chat" || state.session.mode === "agent") { await dispatch( saveCurrentSession({ openNewSession: false, @@ -27,5 +22,10 @@ export const streamThunkWrapper = createAsyncThunk< }), ); } + dispatch(setInactive()); + } catch (e) { + dispatch(cancelStream()); + dispatch(setDialogMessage()); + dispatch(setShowDialog(true)); } }); diff --git a/gui/src/redux/util/index.ts b/gui/src/redux/util/index.ts index 7c21c69bd..eab18ae60 100644 --- a/gui/src/redux/util/index.ts +++ b/gui/src/redux/util/index.ts @@ -2,7 +2,16 @@ import { ToolCallState } from "core"; import { RootState } from "../store"; export function findCurrentToolCall( - state: RootState["session"]["history"], + chatHistory: RootState["session"]["history"], ): ToolCallState | undefined { - return state[state.length - 1]?.toolCallState; + return chatHistory[chatHistory.length - 1]?.toolCallState; +} + +export function findToolCall( + chatHistory: RootState["session"]["history"], + toolCallId: string, +): ToolCallState | undefined { + return chatHistory.find( + (item) => item.toolCallState?.toolCallId === toolCallId, + )?.toolCallState; } diff --git a/gui/src/util/clientTools/callClientTool.ts b/gui/src/util/clientTools/callClientTool.ts new file mode 100644 index 000000000..65f11fbf6 --- /dev/null +++ b/gui/src/util/clientTools/callClientTool.ts @@ -0,0 +1,58 @@ +import { ContextItem, ToolCall } from "core"; +import { BuiltInToolNames } from "core/tools/builtIn"; +import { IIdeMessenger } from "../../context/IdeMessenger"; +import { AppThunkDispatch, RootState } from "../../redux/store"; +import { editToolImpl } from "./editImpl"; + +export interface ClientToolExtras { + getState: () => RootState; + dispatch: AppThunkDispatch; + ideMessenger: IIdeMessenger; + streamId?: string; +} + +export interface ClientToolOutput { + output: ContextItem[] | undefined; + respondImmediately: boolean; +} + +export interface ClientToolResult extends ClientToolOutput { + errorMessage: string | undefined; +} + +export type ClientToolImpl = ( + args: any, + toolCallId: string, + extras: ClientToolExtras, +) => Promise; + +export async function callClientTool( + toolCall: ToolCall, + extras: ClientToolExtras, +): Promise { + const args = JSON.parse(toolCall.function.arguments || "{}"); + try { + let output: ClientToolOutput; + switch (toolCall.function.name) { + case BuiltInToolNames.EditExistingFile: + output = await editToolImpl(args, toolCall.id, extras); + break; + default: + throw new Error(`Invalid client tool name ${toolCall.function.name}`); + } + return { + ...output, + errorMessage: undefined, + }; + } catch (e) { + let errorMessage = `${e}`; + if (e instanceof Error) { + errorMessage = e.message; + } + return { + respondImmediately: true, + errorMessage, + output: undefined, + }; + } +} diff --git a/gui/src/util/clientTools/editImpl.ts b/gui/src/util/clientTools/editImpl.ts new file mode 100644 index 000000000..d1f80f25a --- /dev/null +++ b/gui/src/util/clientTools/editImpl.ts @@ -0,0 +1,33 @@ +import { resolveRelativePathInDir } from "core/util/ideUtils"; +import { ClientToolImpl } from "./callClientTool"; + +export const editToolImpl: ClientToolImpl = async ( + args, + toolCallId, + extras, +) => { + if (!extras.streamId) { + throw new Error("Invalid apply state"); + } + const firstUriMatch = await resolveRelativePathInDir( + args.filepath, + extras.ideMessenger.ide, + ); + if (!firstUriMatch) { + throw new Error(`${args.filepath} does not exist`); + } + const apply = await extras.ideMessenger.request("applyToFile", { + streamId: extras.streamId, + text: args.changes, + toolCallId, + filepath: firstUriMatch, + }); + if (apply.status === "error") { + throw new Error(apply.error); + } + + return { + respondImmediately: false, + output: undefined, // No immediate output. + }; +}; diff --git a/gui/src/util/test/render.tsx b/gui/src/util/test/render.tsx index 95f1cbd2d..2b9ae5b29 100644 --- a/gui/src/util/test/render.tsx +++ b/gui/src/util/test/render.tsx @@ -1,11 +1,17 @@ -import type { RenderOptions } from "@testing-library/react"; +import type { RenderOptions, RenderResult } from "@testing-library/react"; import { render } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { PropsWithChildren } from "react"; import { Provider } from "react-redux"; import { MemoryRouter, RouterProps } from "react-router-dom"; import { AuthProvider } from "../../context/Auth"; +import { IdeMessengerProvider } from "../../context/IdeMessenger"; +import { MockIdeMessenger } from "../../context/MockIdeMessenger"; import { setupStore } from "../../redux/store"; +import { SetupListeners } from "../../App"; +import { act } from "@testing-library/react"; +import { LumpProvider } from "../../components/mainInput/Lump/LumpContext"; +import { MainEditorProvider } from "../../components/mainInput/TipTapEditor"; // As a basic setup, import your same slice reducers // This type interface extends the default options for render from RTL, as well @@ -15,13 +21,26 @@ type ExtendedRenderOptions = Omit & { routerProps?: RouterProps; }; -export function renderWithProviders( +function setupMocks() { + global.ResizeObserver = vi.fn().mockImplementation(() => ({ + observe: vi.fn(), + unobserve: vi.fn(), + disconnect: vi.fn(), + })); +} + +export async function renderWithProviders( ui: React.ReactElement, extendedRenderOptions: ExtendedRenderOptions = {}, ) { + setupMocks(); + const ideMessenger = new MockIdeMessenger(); + const { // Automatically create a store instance if no store was passed in - store = setupStore(), + store = setupStore({ + ideMessenger, + }), routerProps = {}, ...renderOptions } = extendedRenderOptions; @@ -30,16 +49,30 @@ export function renderWithProviders( const Wrapper = ({ children }: PropsWithChildren) => ( - - {children} - + + + + + + {children} + + + + + + ); + let rendered: RenderResult; + await act(async () => { + rendered = render(ui, { wrapper: Wrapper, ...renderOptions }); + }); + // Return an object with the store and all of RTL's query functions return { user, store, - ...render(ui, { wrapper: Wrapper, ...renderOptions }), + ...rendered!, }; } diff --git a/packages/config-yaml/src/__tests__/index.test.ts b/packages/config-yaml/src/__tests__/index.test.ts index 0c8f120d7..95f7bf331 100644 --- a/packages/config-yaml/src/__tests__/index.test.ts +++ b/packages/config-yaml/src/__tests__/index.test.ts @@ -2,7 +2,8 @@ import * as fs from "fs"; import { decodeSecretLocation, FQSN, - FullSlug, + PackageIdentifier, + packageIdentifierToShorthandSlug, PlatformClient, PlatformSecretStore, Registry, @@ -90,18 +91,24 @@ describe("E2E Scenarios", () => { }; const registry: Registry = { - getContent: async function (fullSlug: FullSlug): Promise { + getContent: async function (id: PackageIdentifier): Promise { + const slug = packageIdentifierToShorthandSlug(id); return fs - .readFileSync( - `./src/__tests__/packages/${fullSlug.ownerSlug}/${fullSlug.packageSlug}.yaml`, - ) + .readFileSync(`./src/__tests__/packages/${slug}.yaml`) .toString(); }, }; it("should unroll assistant with a single block that doesn't exist", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant-with-non-existing-block", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant-with-non-existing-block", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -117,7 +124,14 @@ describe("E2E Scenarios", () => { it("should correctly unroll assistant", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -195,7 +209,14 @@ describe("E2E Scenarios", () => { it("should correctly unroll assistant with injected blocks", async () => { const unrolledConfig = await unrollAssistant( - "test-org/assistant", + { + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "assistant", + versionSlug: "latest", + }, + }, registry, { renderSecrets: true, @@ -206,16 +227,19 @@ describe("E2E Scenarios", () => { // Add an injected block injectBlocks: [ { - ownerSlug: "test-org", - packageSlug: "docs", - versionSlug: "latest", + uriType: "slug", + fullSlug: { + ownerSlug: "test-org", + packageSlug: "rules", + versionSlug: "latest", + }, }, ], }, ); - // The original docs array should have one item - expect(unrolledConfig.docs?.length).toBe(2); // Now 2 with the injected block + // The original rules array should have two items + expect(unrolledConfig.rules?.length).toBe(3); // Now 3 with the injected block // Check the original doc is still there expect(unrolledConfig.docs?.[0]?.startUrl).toBe( @@ -223,9 +247,7 @@ describe("E2E Scenarios", () => { ); // Check the injected doc block was added - expect(unrolledConfig.docs?.[1]?.startUrl).toBe( - "https://docs.python.org/release/3.13.1", - ); + expect(unrolledConfig.rules?.[2]).toBe("Be kind"); }); it.skip("should prioritize org over user / package secrets", () => {}); diff --git a/packages/config-yaml/src/interfaces/SecretResult.ts b/packages/config-yaml/src/interfaces/SecretResult.ts index 5c626c3d0..b89e12e59 100644 --- a/packages/config-yaml/src/interfaces/SecretResult.ts +++ b/packages/config-yaml/src/interfaces/SecretResult.ts @@ -7,6 +7,7 @@ export enum SecretType { NotFound = "not_found", ModelsAddOn = "models_add_on", FreeTrial = "free_trial", + LocalEnv = "local_env", } export interface OrgSecretLocation { @@ -39,6 +40,11 @@ export interface FreeTrialSecretLocation { secretName: string; } +export interface LocalEnvSecretLocation { + secretType: SecretType.LocalEnv; + secretName: string; +} + /** * If not found in user/package/org secrets, then there's a chance it's in * - the on-prem proxy @@ -56,7 +62,8 @@ export type SecretLocation = | UserSecretLocation | NotFoundSecretLocation | ModelsAddOnSecretLocation - | FreeTrialSecretLocation; + | FreeTrialSecretLocation + | LocalEnvSecretLocation; export function encodeSecretLocation(secretLocation: SecretLocation): string { if (secretLocation.secretType === SecretType.Organization) { @@ -71,6 +78,8 @@ export function encodeSecretLocation(secretLocation: SecretLocation): string { return `${SecretType.ModelsAddOn}:${encodePackageSlug(secretLocation.blockSlug)}/${secretLocation.secretName}`; } else if (secretLocation.secretType === SecretType.FreeTrial) { return `${SecretType.FreeTrial}:${encodePackageSlug(secretLocation.blockSlug)}/${secretLocation.secretName}`; + } else if (secretLocation.secretType === SecretType.LocalEnv) { + return `${SecretType.LocalEnv}:${secretLocation.secretName}`; } else { throw new Error(`Invalid secret type: ${secretLocation}`); } @@ -123,6 +132,11 @@ export function decodeSecretLocation(secretLocation: string): SecretLocation { packageSlug: parts[1], }, }; + case SecretType.LocalEnv: + return { + secretType: SecretType.LocalEnv, + secretName, + }; default: throw new Error(`Invalid secret type: ${secretType}`); } @@ -140,7 +154,8 @@ export interface FoundSecretResult { | OrgSecretLocation | PackageSecretLocation | ModelsAddOnSecretLocation - | FreeTrialSecretLocation; + | FreeTrialSecretLocation + | LocalEnvSecretLocation; fqsn: FQSN; } diff --git a/packages/config-yaml/src/interfaces/index.ts b/packages/config-yaml/src/interfaces/index.ts index a3f32e93a..dd6377230 100644 --- a/packages/config-yaml/src/interfaces/index.ts +++ b/packages/config-yaml/src/interfaces/index.ts @@ -1,11 +1,16 @@ import { SecretLocation, SecretResult, SecretType } from "./SecretResult.js"; -import { FQSN, FullSlug, PackageSlug, packageSlugsEqual } from "./slugs.js"; +import { + FQSN, + PackageIdentifier, + PackageSlug, + packageSlugsEqual, +} from "./slugs.js"; /** * A registry stores the content of packages */ export interface Registry { - getContent(fullSlug: FullSlug): Promise; + getContent(fullSlug: PackageIdentifier): Promise; } export type SecretNamesMap = Map; diff --git a/packages/config-yaml/src/interfaces/slugs.test.ts b/packages/config-yaml/src/interfaces/slugs.test.ts index cab57e5d2..e07e6f700 100644 --- a/packages/config-yaml/src/interfaces/slugs.test.ts +++ b/packages/config-yaml/src/interfaces/slugs.test.ts @@ -1,9 +1,11 @@ import { decodeFQSN, decodeFullSlug, + decodePackageIdentifier, decodePackageSlug, encodeFQSN, encodeFullSlug, + encodePackageIdentifier, encodePackageSlug, VirtualTags, } from "./slugs.js"; @@ -80,3 +82,80 @@ describe("PackageSlug", () => { ); }); }); + +describe("PackageIdentifier", () => { + it("should encode/decode slug-based package identifier", () => { + const testIdentifier = { + uriType: "slug" as const, + fullSlug: { + ownerSlug: "test-owner", + packageSlug: "test-package", + versionSlug: "2.1.0", + }, + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("test-owner/test-package@2.1.0"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should encode/decode slug-based package identifier without version", () => { + const encoded = "test-owner/test-package"; + const decoded = decodePackageIdentifier(encoded); + + expect(decoded).toEqual({ + uriType: "slug", + fullSlug: { + ownerSlug: "test-owner", + packageSlug: "test-package", + versionSlug: VirtualTags.Latest, + }, + }); + }); + + it("should encode/decode file-based package identifier with relative path", () => { + const testIdentifier = { + uriType: "file" as const, + filePath: "./path/to/package.yaml", + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("./path/to/package.yaml"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should encode/decode file-based package identifier with absolute path", () => { + const testIdentifier = { + uriType: "file" as const, + filePath: "/absolute/path/to/package.yaml", + }; + const encoded = encodePackageIdentifier(testIdentifier); + expect(encoded).toBe("/absolute/path/to/package.yaml"); + + const decoded = decodePackageIdentifier(encoded); + expect(decoded).toEqual(testIdentifier); + }); + + it("should decode file-based package identifier with file:// protocol", () => { + const encoded = "file:///path/to/package.yaml"; + const decoded = decodePackageIdentifier(encoded); + + expect(decoded).toEqual({ + uriType: "file" as const, + filePath: "/path/to/package.yaml", + }); + }); + + it("should throw error for unknown URI type", () => { + const invalidIdentifier = { + uriType: "invalid", + data: "something", + }; + + expect(() => encodePackageIdentifier(invalidIdentifier as any)).toThrow( + "Unknown URI type: invalid", + ); + }); +}); diff --git a/packages/config-yaml/src/interfaces/slugs.ts b/packages/config-yaml/src/interfaces/slugs.ts index dd225aa10..5d1f9885f 100644 --- a/packages/config-yaml/src/interfaces/slugs.ts +++ b/packages/config-yaml/src/interfaces/slugs.ts @@ -2,10 +2,65 @@ export interface PackageSlug { ownerSlug: string; packageSlug: string; } + export interface FullSlug extends PackageSlug { versionSlug: string; } +// Identifier roughly equals URI, except that we want to provide shorthand for slugs and filepaths +// Later it is possible to allow URIs as well since they can be uniquely parsed +interface BasePackageIdentifier { + uriType: "file" | "slug"; +} + +interface FullSlugIdentifier extends BasePackageIdentifier { + uriType: "slug"; + fullSlug: FullSlug; +} + +interface FileIdentifier extends BasePackageIdentifier { + uriType: "file"; + filePath: string; +} + +export type PackageIdentifier = FullSlugIdentifier | FileIdentifier; + +export function encodePackageIdentifier(identifier: PackageIdentifier): string { + switch (identifier.uriType) { + case "slug": + return encodeFullSlug(identifier.fullSlug); + case "file": + // For file paths, just return the path directly without a prefix + return identifier.filePath; + default: + throw new Error(`Unknown URI type: ${(identifier as any).uriType}`); + } +} + +export function decodePackageIdentifier(identifier: string): PackageIdentifier { + // Shorthand: if it starts with . or /, then it's a path + if (identifier.startsWith(".") || identifier.startsWith("/")) { + return { + uriType: "file", + filePath: identifier, + }; + } + // Keep support for explicit file:// protocol + else if (identifier.startsWith("file://")) { + return { + uriType: "file", + filePath: identifier.substring(7), + }; + } + // Otherwise, it's a slug + else { + return { + uriType: "slug", + fullSlug: decodeFullSlug(identifier), + }; + } +} + export enum VirtualTags { Latest = "latest", } diff --git a/packages/config-yaml/src/load/clientRender.ts b/packages/config-yaml/src/load/clientRender.ts index ffc62f0fc..18a0aebd0 100644 --- a/packages/config-yaml/src/load/clientRender.ts +++ b/packages/config-yaml/src/load/clientRender.ts @@ -9,7 +9,7 @@ import { decodeFQSN, encodeFQSN, FQSN, - PackageSlug, + PackageIdentifier, } from "../interfaces/slugs.js"; import { AssistantUnrolled } from "../schemas/index.js"; import { @@ -19,7 +19,7 @@ import { } from "./unroll.js"; export async function renderSecrets( - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, unrolledConfigContent: string, clientSecretStore: SecretStore, orgScopeId: string | null, // The "scope" that the user is logged in with @@ -72,7 +72,7 @@ export async function renderSecrets( // 7. We update any of the items with the proxy version if there are un-rendered secrets const finalConfig = useProxyForUnrenderedSecrets( parsedYaml, - packageSlug, + packageIdentifier, orgScopeId, onPremProxyUrl, ); @@ -103,17 +103,28 @@ export function getUnrenderedSecretLocation( return undefined; } +export function packageIdentifierToShorthandSlug( + id: PackageIdentifier, +): string { + switch (id.uriType) { + case "slug": + return `${id.fullSlug.ownerSlug}/${id.fullSlug.packageSlug}`; + case "file": + return "/"; + } +} + function getContinueProxyModelName( - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, provider: string, model: string, ): string { - return `${packageSlug.ownerSlug}/${packageSlug.packageSlug}/${provider}/${model}`; + return `${packageIdentifierToShorthandSlug(packageIdentifier)}/${provider}/${model}`; } export function useProxyForUnrenderedSecrets( config: AssistantUnrolled, - packageSlug: PackageSlug, + packageIdentifier: PackageIdentifier, orgScopeId: string | null, onPremProxyUrl: string | null, ): AssistantUnrolled { @@ -128,7 +139,7 @@ export function useProxyForUnrenderedSecrets( name: config.models[i]?.name ?? "", provider: "continue-proxy", model: getContinueProxyModelName( - packageSlug, + packageIdentifier, config.models[i]?.provider ?? "", config.models[i]?.model ?? "", ), diff --git a/packages/config-yaml/src/load/getBlockType.ts b/packages/config-yaml/src/load/getBlockType.ts index a2cf56062..c46de0bd4 100644 --- a/packages/config-yaml/src/load/getBlockType.ts +++ b/packages/config-yaml/src/load/getBlockType.ts @@ -1,13 +1,17 @@ +import { z } from "zod"; import { ConfigYaml } from "../schemas/index.js"; -export type BlockType = - | "models" - | "context" - | "docs" - | "mcpServers" - | "data" - | "rules" - | "prompts"; +export const BLOCK_TYPES = [ + "models", + "context", + "data", + "mcpServers", + "rules", + "prompts", + "docs", +] as const; +export type BlockType = (typeof BLOCK_TYPES)[number]; +export const blockTypeSchema = z.enum(BLOCK_TYPES); export function getBlockType(block: ConfigYaml): BlockType | undefined { if (block.context?.length) { diff --git a/packages/config-yaml/src/load/unroll.ts b/packages/config-yaml/src/load/unroll.ts index e0e440bb0..0b5003473 100644 --- a/packages/config-yaml/src/load/unroll.ts +++ b/packages/config-yaml/src/load/unroll.ts @@ -3,12 +3,10 @@ import { PlatformClient, Registry } from "../interfaces/index.js"; import { encodeSecretLocation } from "../interfaces/SecretResult.js"; import { decodeFQSN, - decodeFullSlug, + decodePackageIdentifier, encodeFQSN, - encodePackageSlug, FQSN, - FullSlug, - PackageSlug, + PackageIdentifier, } from "../interfaces/slugs.js"; import { AssistantUnrolled, @@ -19,7 +17,10 @@ import { configYamlSchema, Rule, } from "../schemas/index.js"; -import { useProxyForUnrenderedSecrets } from "./clientRender.js"; +import { + packageIdentifierToShorthandSlug, + useProxyForUnrenderedSecrets, +} from "./clientRender.js"; import { getBlockType } from "./getBlockType.js"; export function parseConfigYaml(configYaml: string): ConfigYaml { @@ -116,11 +117,11 @@ function flattenTemplateData( function secretToFQSNMap( secretNames: string[], - parentPackages: PackageSlug[], + parentPackages: PackageIdentifier[], ): Record { const map: Record = {}; for (const secret of secretNames) { - const parentSlugs = parentPackages.map(encodePackageSlug); + const parentSlugs = parentPackages.map(packageIdentifierToShorthandSlug); const parts = [...parentSlugs, secret]; const fqsn = parts.join("/"); map[secret] = `\${{ secrets.${fqsn} }}`; @@ -131,7 +132,7 @@ function secretToFQSNMap( function extractFQSNMap( rawContent: string, - parentPackages: PackageSlug[], + parentPackages: PackageIdentifier[], ): Record { const templateVars = getTemplateVariables(rawContent); const secrets = templateVars @@ -181,7 +182,7 @@ async function extractRenderedSecretsMap( export interface BaseUnrollAssistantOptions { renderSecrets: boolean; - injectBlocks?: FullSlug[]; + injectBlocks?: PackageIdentifier[]; } export interface DoNotRenderSecretsUnrollAssistantOptions @@ -204,20 +205,13 @@ export type UnrollAssistantOptions = | RenderSecretsUnrollAssistantOptions; export async function unrollAssistant( - fullSlug: string, + id: PackageIdentifier, registry: Registry, options: UnrollAssistantOptions, ): Promise { - const assistantSlug = decodeFullSlug(fullSlug); - // Request the content from the registry - const rawContent = await registry.getContent(assistantSlug); - return unrollAssistantFromContent( - assistantSlug, - rawContent, - registry, - options, - ); + const rawContent = await registry.getContent(id); + return unrollAssistantFromContent(id, rawContent, registry, options); } function renderTemplateData( @@ -238,7 +232,7 @@ function renderTemplateData( } export async function unrollAssistantFromContent( - assistantSlug: FullSlug, + id: PackageIdentifier, rawYaml: string, registry: Registry, options: UnrollAssistantOptions, @@ -259,7 +253,7 @@ export async function unrollAssistantFromContent( // Convert all of the template variables to FQSNs // Secrets from the block will have the assistant slug prepended to the FQSN const templatedYaml = renderTemplateData(rawUnrolledYaml, { - secrets: extractFQSNMap(rawUnrolledYaml, [assistantSlug]), + secrets: extractFQSNMap(rawUnrolledYaml, [id]), }); if (!options.renderSecrets) { @@ -279,7 +273,7 @@ export async function unrollAssistantFromContent( // Parse again and replace models with proxy versions where secrets weren't rendered const finalConfig = useProxyForUnrenderedSecrets( parseAssistantUnrolled(renderedYaml), - assistantSlug, + id, options.orgScopeId, options.onPremProxyUrl, ); @@ -289,7 +283,7 @@ export async function unrollAssistantFromContent( export async function unrollBlocks( assistant: ConfigYaml, registry: Registry, - injectBlocks: FullSlug[] | undefined, + injectBlocks: PackageIdentifier[] | undefined, ): Promise { const unrolledAssistant: AssistantUnrolled = { name: assistant.name, @@ -311,7 +305,7 @@ export async function unrollBlocks( if ("uses" in unrolledBlock) { try { const blockConfigYaml = await resolveBlock( - decodeFullSlug(unrolledBlock.uses), + decodePackageIdentifier(unrolledBlock.uses), unrolledBlock.with, registry, ); @@ -346,7 +340,7 @@ export async function unrollBlocks( } else if ("uses" in rule) { try { const blockConfigYaml = await resolveBlock( - decodeFullSlug(rule.uses), + decodePackageIdentifier(rule.uses), rule.with, registry, ); @@ -397,26 +391,24 @@ export async function unrollBlocks( } export async function resolveBlock( - fullSlug: FullSlug, + id: PackageIdentifier, inputs: Record | undefined, registry: Registry, ): Promise { // Retrieve block raw yaml - const rawYaml = await registry.getContent(fullSlug); + const rawYaml = await registry.getContent(id); if (rawYaml === undefined) { - throw new Error( - `Block ${fullSlug.ownerSlug}/${fullSlug.packageSlug} not found`, - ); + throw new Error(`Block ${packageIdentifierToShorthandSlug(id)} not found`); } // Convert any input secrets to FQSNs (they get FQSNs as if they are in the block. This is so that we know when to use models add-on / free trial secrets) - const renderedInputs = inputsToFQSNs(inputs || {}, fullSlug); + const renderedInputs = inputsToFQSNs(inputs || {}, id); // Render template variables const templatedYaml = renderTemplateData(rawYaml, { inputs: renderedInputs, - secrets: extractFQSNMap(rawYaml, [fullSlug]), + secrets: extractFQSNMap(rawYaml, [id]), }); const parsedYaml = parseBlock(templatedYaml); @@ -425,12 +417,12 @@ export async function resolveBlock( function inputsToFQSNs( inputs: Record, - blockSlug: PackageSlug, + blockIdentifier: PackageIdentifier, ): Record { const renderedInputs: Record = {}; for (const [key, value] of Object.entries(inputs)) { renderedInputs[key] = renderTemplateData(value, { - secrets: extractFQSNMap(value, [blockSlug]), + secrets: extractFQSNMap(value, [blockIdentifier]), }); } return renderedInputs; diff --git a/packages/config-yaml/src/registryClient.test.ts b/packages/config-yaml/src/registryClient.test.ts new file mode 100644 index 000000000..d820579ab --- /dev/null +++ b/packages/config-yaml/src/registryClient.test.ts @@ -0,0 +1,209 @@ +import * as fs from "node:fs"; +import * as http from "node:http"; +import { AddressInfo } from "node:net"; +import * as os from "node:os"; +import * as path from "node:path"; +import { PackageIdentifier } from "./interfaces/slugs.js"; +import { RegistryClient } from "./registryClient.js"; + +describe("RegistryClient", () => { + // Create a temp directory for test files + let tempDir: string; + // Setup a test server + let server: http.Server; + let apiBaseUrl: string; + beforeAll(async () => { + // Create a temporary directory for test files + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "registry-client-test-")); + + // Create a simple HTTP server for API testing + server = http.createServer((req, res) => { + if (req.url?.startsWith("/registry/v1/")) { + const authHeader = req.headers.authorization; + const data = { + content: authHeader + ? `auth content for ${req.url}` + : `content for ${req.url}`, + }; + + res.writeHead(200, { "Content-Type": "application/json" }); + res.end(JSON.stringify(data)); + } else { + res.writeHead(404); + res.end(); + } + }); + + // Start server on a random port + await new Promise((resolve) => { + server.listen(0, "localhost", () => resolve()); + }); + + const address = server.address() as AddressInfo; + apiBaseUrl = `http://localhost:${address.port}`; + }); + + afterAll(async () => { + // Clean up temp directory + fs.rmSync(tempDir, { recursive: true, force: true }); + + // Close the test server + await new Promise((resolve) => { + server.close(() => resolve()); + }); + }); + + describe("constructor", () => { + it("should use default apiBase if not provided", () => { + const client = new RegistryClient(); + expect((client as any).apiBase).toBe("https://api.continue.dev/"); + }); + + it("should append trailing slash to apiBase if missing", () => { + const client = new RegistryClient({ apiBase: "https://example.com" }); + expect((client as any).apiBase).toBe("https://example.com/"); + }); + + it("should keep trailing slash if apiBase already has one", () => { + const client = new RegistryClient({ apiBase: "https://example.com/" }); + expect((client as any).apiBase).toBe("https://example.com/"); + }); + + it("should store the accessToken if provided", () => { + const client = new RegistryClient({ accessToken: "test-token" }); + expect((client as any).accessToken).toBe("test-token"); + }); + + it("should store the rootPath if provided", () => { + const client = new RegistryClient({ rootPath: "/test-path" }); + expect((client as any).rootPath).toBe("/test-path"); + }); + }); + + describe("getContent", () => { + let testFilePath: string; + + beforeEach(() => { + // Create a test file for each test + testFilePath = path.join(tempDir, "test-file.yaml"); + fs.writeFileSync(testFilePath, "file content", "utf8"); + }); + + it("should get content from file path for file uriType", async () => { + const client = new RegistryClient(); + + const id: PackageIdentifier = { + uriType: "file", + filePath: testFilePath, + }; + + const result = await client.getContent(id); + expect(result).toBe("file content"); + }); + + it("should get content from slug for slug uriType", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + }); + + const id: PackageIdentifier = { + uriType: "slug", + fullSlug: { + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }, + }; + + const result = await client.getContent(id); + expect(result).toBe("content for /registry/v1/owner/package/1.0.0"); + }); + + it("should throw error for unknown uriType", async () => { + const client = new RegistryClient(); + + const id = { + uriType: "unknown", + } as any; + + await expect(client.getContent(id)).rejects.toThrow( + "Unknown package identifier type: unknown", + ); + }); + }); + + describe("getContentFromFilePath", () => { + let absoluteFilePath: string; + let relativeFilePath: string; + + beforeEach(() => { + // Create test files + absoluteFilePath = path.join(tempDir, "absolute-path.yaml"); + fs.writeFileSync(absoluteFilePath, "absolute file content", "utf8"); + + // Create a subdirectory and file in the temp directory + const subDir = path.join(tempDir, "sub"); + fs.mkdirSync(subDir, { recursive: true }); + relativeFilePath = "sub/relative-path.yaml"; + fs.writeFileSync( + path.join(tempDir, relativeFilePath), + "relative file content", + "utf8", + ); + }); + + it("should read from absolute path directly", () => { + const client = new RegistryClient(); + + const result = (client as any).getContentFromFilePath(absoluteFilePath); + + expect(result).toBe("absolute file content"); + }); + + it("should use rootPath for relative paths when provided", () => { + const client = new RegistryClient({ rootPath: tempDir }); + + const result = (client as any).getContentFromFilePath(relativeFilePath); + + expect(result).toBe("relative file content"); + }); + + it("should throw error for relative path without rootPath", () => { + const client = new RegistryClient(); + + expect(() => { + (client as any).getContentFromFilePath("relative/path.yaml"); + }).toThrow("No rootPath provided for relative file path"); + }); + }); + + describe("getContentFromSlug", () => { + it("should fetch content from API without auth token", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + }); + const result = await (client as any).getContentFromSlug({ + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }); + + expect(result).toBe("content for /registry/v1/owner/package/1.0.0"); + }); + + it("should include auth token in request when provided", async () => { + const client = new RegistryClient({ + apiBase: apiBaseUrl, + accessToken: "test-token", + }); + + const result = await (client as any).getContentFromSlug({ + ownerSlug: "owner", + packageSlug: "package", + versionSlug: "1.0.0", + }); + + expect(result).toBe("auth content for /registry/v1/owner/package/1.0.0"); + }); + }); +}); diff --git a/packages/config-yaml/src/registryClient.ts b/packages/config-yaml/src/registryClient.ts index d6d3f28fc..73ca9fefd 100644 --- a/packages/config-yaml/src/registryClient.ts +++ b/packages/config-yaml/src/registryClient.ts @@ -1,16 +1,58 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; import { Registry } from "./interfaces/index.js"; -import { FullSlug } from "./interfaces/slugs.js"; +import { FullSlug, PackageIdentifier } from "./interfaces/slugs.js"; + +interface RegistryClientOptions { + accessToken?: string; + apiBase?: string; + rootPath?: string; +} export class RegistryClient implements Registry { - constructor( - private readonly accessToken?: string, - private readonly apiBase: string = "https://api.continue.dev/", - ) { + private readonly accessToken?: string; + private readonly apiBase: string; + private readonly rootPath?: string; + + constructor(options: RegistryClientOptions = {}) { + this.accessToken = options.accessToken; + this.apiBase = options.apiBase ?? "https://api.continue.dev/"; + this.rootPath = options.rootPath; if (!this.apiBase.endsWith("/")) { this.apiBase += "/"; } } - async getContent(fullSlug: FullSlug): Promise { + + async getContent(id: PackageIdentifier): Promise { + switch (id.uriType) { + case "file": + return this.getContentFromFilePath(id.filePath); + case "slug": + return this.getContentFromSlug(id.fullSlug); + default: + throw new Error( + `Unknown package identifier type: ${(id as any).uriType}`, + ); + } + } + + private getContentFromFilePath(filepath: string): string { + if (filepath.startsWith("file://")) { + const pathWithoutProtocol = filepath.slice(7); + + // For Windows file:///C:/path/to/file, we need to handle it properly + // On other systems, we might have file:///path/to/file + return fs.readFileSync(decodeURIComponent(pathWithoutProtocol), "utf8"); + } else if (path.isAbsolute(filepath)) { + return fs.readFileSync(filepath, "utf8"); + } else if (this.rootPath) { + return fs.readFileSync(path.join(this.rootPath, filepath), "utf8"); + } else { + throw new Error("No rootPath provided for relative file path"); + } + } + + private async getContentFromSlug(fullSlug: FullSlug): Promise { const response = await fetch( `${this.apiBase}registry/v1/${fullSlug.ownerSlug}/${fullSlug.packageSlug}/${fullSlug.versionSlug}`, { diff --git a/packages/config-yaml/src/schemas/index.ts b/packages/config-yaml/src/schemas/index.ts index 1de41838c..7f8d55531 100644 --- a/packages/config-yaml/src/schemas/index.ts +++ b/packages/config-yaml/src/schemas/index.ts @@ -35,16 +35,15 @@ const docSchema = z.object({ }); export type DocsConfig = z.infer; - const ruleObjectSchema = z.object({ name: z.string(), rule: z.string(), - if: z.string().optional(), + globs: z.union([z.string(), z.array(z.string())]).optional(), }); - const ruleSchema = z.union([z.string(), ruleObjectSchema]); export type Rule = z.infer; +export type RuleObject = z.infer; const defaultUsesSchema = z.string(); @@ -168,3 +167,59 @@ export const blockSchema = baseConfigYamlSchema.and( ); export type Block = z.infer; + +export const continueCommandSchema = z.object({ + name: z.string(), + description: z.string().optional(), + prompt: z.string(), + placeholders: z.array(z.string()).optional(), + context: z.string().optional(), + contextWindowSize: z.number().optional(), + model: z.string().optional(), + systemMessage: z.string().optional(), + slashCommand: z.string().optional(), + hideFromCommandPalette: z.boolean().optional(), + hideFromSlashCommands: z.boolean().optional(), + mode: z.enum(["insert", "replace", "diff"]).optional(), + addEnhancedContext: z.boolean().optional(), +}); + +export const languageMarkerSchema = z.object({ + language: z.string(), + markers: z.array(z.string()), +}); + +export const sidebarSchema = z.object({ + enabled: z.boolean().optional(), + defaultOpen: z.boolean().optional(), + defaultWidth: z.number().optional(), + showButtonsThreshold: z.number().optional(), +}); + +const toolSchema = z.object({ + name: z.string(), + description: z.string(), + defaultIcon: z.string().optional(), +}); + +export const autoindentExtensionsSchema = z.array(z.string()); + +export const configSchema = z.object({ + models: z.array(modelSchema).optional(), + defaultModel: z.string().optional(), + defaultRecentMessages: z.number().optional(), + commands: z.array(continueCommandSchema).optional(), + tools: z.array(toolSchema).optional(), + contextProviders: z.array(z.any()).optional(), + langMarkers: z.array(languageMarkerSchema).optional(), + sidebar: sidebarSchema.optional(), + tabAutocompleteModel: z.string().optional(), + rules: z.array(ruleObjectSchema).optional(), + doneWithBannerForever: z.boolean().optional(), + autoindentExtensions: autoindentExtensionsSchema.optional(), + proxy: z.string().optional(), + api_base: z.string().optional(), + api_key: z.string().optional(), +}); + +export type Config = z.infer; diff --git a/packages/config-yaml/src/schemas/models.ts b/packages/config-yaml/src/schemas/models.ts index f56ae96db..1d2d075f4 100644 --- a/packages/config-yaml/src/schemas/models.ts +++ b/packages/config-yaml/src/schemas/models.ts @@ -47,9 +47,17 @@ export const completionOptionsSchema = z.object({ topK: z.number().optional(), stop: z.array(z.string()).optional(), n: z.number().optional(), + reasoning: z.boolean().optional(), + reasoningBudgetTokens: z.number().optional(), }); export type CompletionOptions = z.infer; +export const cacheBehaviorSchema = z.object({ + cacheSystemMessage: z.boolean().optional(), + cacheConversation: z.boolean().optional(), +}) +export type CacheBehavior = z.infer; + export const embedOptionsSchema = z.object({ maxChunkSize: z.number().optional(), maxBatchSize: z.number().optional(), @@ -61,9 +69,30 @@ export const chatOptionsSchema = z.object({ }); export type ChatOptions = z.infer; +const templateSchema = z.enum([ + "llama2", + "alpaca", + "zephyr", + "phi2", + "phind", + "anthropic", + "chatml", + "none", + "openchat", + "deepseek", + "xwin-coder", + "neural-chat", + "codellama-70b", + "llava", + "gemma", + "granite", + "llama3", +]); + /** Prompt templates use Handlebars syntax */ const promptTemplatesSchema = z.object({ apply: z.string().optional(), + chatTemplate: templateSchema.optional(), edit: z.string().optional(), autocomplete: z.string().optional() }); @@ -77,6 +106,7 @@ const baseModelFields = { roles: modelRolesSchema.array().optional(), capabilities: modelCapabilitySchema.array().optional(), defaultCompletionOptions: completionOptionsSchema.optional(), + cacheBehavior: cacheBehaviorSchema.optional(), requestOptions: requestOptionsSchema.optional(), embedOptions: embedOptionsSchema.optional(), chatOptions: chatOptionsSchema.optional(), diff --git a/packages/llm-info/src/providers/openai.ts b/packages/llm-info/src/providers/openai.ts index b96461e4b..a15dd3089 100644 --- a/packages/llm-info/src/providers/openai.ts +++ b/packages/llm-info/src/providers/openai.ts @@ -8,6 +8,12 @@ export const OpenAi: ModelProvider = { contextLength: 16385, maxCompletionTokens: 4096, }, + { + model: "gpt-3.5-turbo-0613", + displayName: "GPT-3.5 Turbo", + contextLength: 16385, + maxCompletionTokens: 4096, + }, { model: "gpt-3.5-turbo-16k", displayName: "GPT-3.5 Turbo 16K", diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 08d52d3b9..c069bf45e 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -1,18 +1,19 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.18", + "version": "1.0.21", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@continuedev/openai-adapters", - "version": "1.0.18", + "version": "1.0.21", "license": "Apache-2.0", "dependencies": { "@azure/openai": "^1.0.0-beta.12", "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", "@continuedev/fetch": "^1.0.3", + "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", @@ -21,6 +22,7 @@ }, "devDependencies": { "@types/follow-redirects": "^1.14.4", + "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", "ts-jest": "^29.2.3", @@ -166,7 +168,6 @@ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.24.7.tgz", "integrity": "sha512-BcYH1CVJBO9tvyIZ2jVeXgSIMvGZ2FDRvDdOIVQyuklNKSsx+eppDEBq/g47Ayw+RqNFE+URvOShmf+f/qwAlA==", "dev": true, - "peer": true, "dependencies": { "@babel/highlight": "^7.24.7", "picocolors": "^1.0.0" @@ -321,7 +322,6 @@ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.24.7.tgz", "integrity": "sha512-rR+PBcQ1SMQDDyF6X0wxtG8QyLCgUB0eRAGguqRLfkCA87l7yAP7ehq8SNj96OOGTO8OBV70KhuFYcIkHXOg0w==", "dev": true, - "peer": true, "engines": { "node": ">=6.9.0" } @@ -355,7 +355,6 @@ "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.24.7.tgz", "integrity": "sha512-EStJpq4OuY8xYfhGVXngigBJRWxftKX9ksiGDnmlY3o7B/V7KIAc9X4oiK87uPJSc/vs5L869bem5fhZa8caZw==", "dev": true, - "peer": true, "dependencies": { "@babel/helper-validator-identifier": "^7.24.7", "chalk": "^2.4.2", @@ -371,7 +370,6 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", "dev": true, - "peer": true, "dependencies": { "color-convert": "^1.9.0" }, @@ -384,7 +382,6 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", "dev": true, - "peer": true, "dependencies": { "ansi-styles": "^3.2.1", "escape-string-regexp": "^1.0.5", @@ -399,7 +396,6 @@ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", "dev": true, - "peer": true, "dependencies": { "color-name": "1.1.3" } @@ -408,15 +404,13 @@ "version": "1.1.3", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true, - "peer": true + "dev": true }, "node_modules/@babel/highlight/node_modules/escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", "dev": true, - "peer": true, "engines": { "node": ">=0.8.0" } @@ -426,7 +420,6 @@ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", "dev": true, - "peer": true, "engines": { "node": ">=4" } @@ -436,7 +429,6 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", "dev": true, - "peer": true, "dependencies": { "has-flag": "^3.0.0" }, @@ -885,7 +877,6 @@ "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", "dev": true, - "peer": true, "dependencies": { "jest-get-type": "^29.6.3" }, @@ -1263,6 +1254,16 @@ "@types/istanbul-lib-report": "*" } }, + "node_modules/@types/jest": { + "version": "29.5.14", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", + "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", + "dev": true, + "dependencies": { + "expect": "^29.0.0", + "pretty-format": "^29.0.0" + } + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -1290,8 +1291,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, - "peer": true + "dev": true }, "node_modules/@types/yargs": { "version": "17.0.32", @@ -1581,7 +1581,6 @@ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, - "peer": true, "dependencies": { "fill-range": "^7.1.1" }, @@ -1961,11 +1960,21 @@ "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", "dev": true, - "peer": true, "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/dotenv": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.5.0.tgz", + "integrity": "sha512-m/C+AwOAr9/W1UOIZUo232ejMNnJAJtYQjUbHoNTBNTJSvqzzDh7vnrei3o3r3m9blf6ZoDkvcw0VmozNRFJxg==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, "node_modules/ejs": { "version": "3.1.10", "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", @@ -2033,7 +2042,6 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -2099,7 +2107,6 @@ "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", "dev": true, - "peer": true, "dependencies": { "@jest/expect-utils": "^29.7.0", "jest-get-type": "^29.6.3", @@ -2184,7 +2191,6 @@ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, - "peer": true, "dependencies": { "to-regex-range": "^5.0.1" }, @@ -2555,7 +2561,6 @@ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true, - "peer": true, "engines": { "node": ">=0.12.0" } @@ -2840,7 +2845,6 @@ "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", "dev": true, - "peer": true, "dependencies": { "chalk": "^4.0.0", "diff-sequences": "^29.6.3", @@ -2904,7 +2908,6 @@ "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", "dev": true, - "peer": true, "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } @@ -2954,7 +2957,6 @@ "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", "dev": true, - "peer": true, "dependencies": { "chalk": "^4.0.0", "jest-diff": "^29.7.0", @@ -2970,7 +2972,6 @@ "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", "dev": true, - "peer": true, "dependencies": { "@babel/code-frame": "^7.12.13", "@jest/types": "^29.6.3", @@ -3280,8 +3281,7 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "peer": true + "dev": true }, "node_modules/js-yaml": { "version": "3.14.1", @@ -3447,7 +3447,6 @@ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.7.tgz", "integrity": "sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==", "dev": true, - "peer": true, "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" @@ -3765,8 +3764,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.1.tgz", "integrity": "sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==", - "dev": true, - "peer": true + "dev": true }, "node_modules/picomatch": { "version": "2.3.1", @@ -3808,7 +3806,6 @@ "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", "dev": true, - "peer": true, "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", @@ -3823,7 +3820,6 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, - "peer": true, "engines": { "node": ">=10" }, @@ -3866,8 +3862,7 @@ "version": "18.3.1", "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "peer": true + "dev": true }, "node_modules/require-directory": { "version": "2.1.1", @@ -3980,7 +3975,6 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, - "peer": true, "engines": { "node": ">=8" } @@ -4018,7 +4012,6 @@ "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", "dev": true, - "peer": true, "dependencies": { "escape-string-regexp": "^2.0.0" }, @@ -4163,7 +4156,6 @@ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, - "peer": true, "dependencies": { "is-number": "^7.0.0" }, diff --git a/packages/openai-adapters/package.json b/packages/openai-adapters/package.json index 82ba2509b..766b93eb5 100644 --- a/packages/openai-adapters/package.json +++ b/packages/openai-adapters/package.json @@ -1,6 +1,6 @@ { "name": "@continuedev/openai-adapters", - "version": "1.0.18", + "version": "1.0.21", "description": "", "main": "dist/index.js", "types": "dist/index.d.ts", @@ -16,6 +16,7 @@ "@continuedev/config-types": "^1.0.5", "@continuedev/config-yaml": "^1.0.51", "@continuedev/fetch": "^1.0.3", + "dotenv": "^16.5.0", "json-schema": "^0.4.0", "node-fetch": "^3.3.2", "openai": "^4.76.0", @@ -24,6 +25,7 @@ }, "devDependencies": { "@types/follow-redirects": "^1.14.4", + "@types/jest": "^29.5.14", "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", "ts-jest": "^29.2.3", diff --git a/packages/openai-adapters/src/apis/Anthropic.ts b/packages/openai-adapters/src/apis/Anthropic.ts index 04b0fbce9..871b35acc 100644 --- a/packages/openai-adapters/src/apis/Anthropic.ts +++ b/packages/openai-adapters/src/apis/Anthropic.ts @@ -37,11 +37,23 @@ export class AnthropicApi implements BaseLlmApi { stop = [oaiBody.stop]; } + const systemMessage = oaiBody.messages.find( + (msg) => msg.role === "system", + )?.content; + const anthropicBody = { messages: this._convertMessages( oaiBody.messages.filter((msg) => msg.role !== "system"), ), - system: oaiBody.messages.find((msg) => msg.role === "system")?.content, + system: systemMessage + ? [ + { + type: "text", + text: systemMessage, + cache_control: { type: "ephemeral" }, + }, + ] + : systemMessage, top_p: oaiBody.top_p, temperature: oaiBody.temperature, max_tokens: oaiBody.max_tokens ?? 4096, // max_tokens is required diff --git a/packages/openai-adapters/src/apis/Inception.ts b/packages/openai-adapters/src/apis/Inception.ts new file mode 100644 index 000000000..35d585bb8 --- /dev/null +++ b/packages/openai-adapters/src/apis/Inception.ts @@ -0,0 +1,58 @@ +import { streamSse } from "@continuedev/fetch"; +import { ChatCompletionChunk, Model } from "openai/resources/index"; +import { InceptionConfig } from "../types.js"; +import { chatChunk, customFetch } from "../util.js"; +import { OpenAIApi } from "./OpenAI.js"; +import { FimCreateParamsStreaming } from "./base.js"; + +export class InceptionApi extends OpenAIApi { + apiBase: string = "https://api.inceptionlabs.ai/v1/"; + constructor(config: InceptionConfig) { + super({ + ...config, + provider: "openai", + }); + } + + async *fimStream( + body: FimCreateParamsStreaming, + signal: AbortSignal, + ): AsyncGenerator { + const endpoint = new URL("completions", this.apiBase); + const resp = await customFetch(this.config.requestOptions)(endpoint, { + method: "POST", + body: JSON.stringify({ + model: body.model, + prompt: body.prompt, + suffix: body.suffix.trim() === "" ? "<|endoftext|>" : body.suffix, + max_tokens: body.max_tokens ?? 150, // Only want this for /fim, not chat + temperature: body.temperature, + top_p: body.top_p, + frequency_penalty: body.frequency_penalty, + presence_penalty: body.presence_penalty, + stop: [...(body.stop ?? []), "\n\n", "\n \n"], + stream: true, + }), + headers: { + "Content-Type": "application/json", + Accept: "application/json", + Authorization: `Bearer ${this.config.apiKey}`, + }, + signal, + }); + for await (const chunk of streamSse(resp as any)) { + if (!chunk.choices[0]) { + continue; + } + yield chatChunk({ + content: chunk.choices[0].text, + finish_reason: null, + model: body.model, + }); + } + } + + list(): Promise { + throw new Error("Method not implemented."); + } +} diff --git a/packages/openai-adapters/src/index.ts b/packages/openai-adapters/src/index.ts index 05e43fc20..8cda78931 100644 --- a/packages/openai-adapters/src/index.ts +++ b/packages/openai-adapters/src/index.ts @@ -6,6 +6,7 @@ import { BaseLlmApi } from "./apis/base.js"; import { CohereApi } from "./apis/Cohere.js"; import { DeepSeekApi } from "./apis/DeepSeek.js"; import { GeminiApi } from "./apis/Gemini.js"; +import { InceptionApi } from "./apis/Inception.js"; import { JinaApi } from "./apis/Jina.js"; import { MockApi } from "./apis/Mock.js"; import { MoonshotApi } from "./apis/Moonshot.js"; @@ -45,6 +46,8 @@ export function constructLlmApi(config: LLMConfig): BaseLlmApi | undefined { return new MoonshotApi(config); case "relace": return new RelaceApi(config); + case "inception": + return new InceptionApi(config); case "x-ai": return openAICompatible("https://api.x.ai/v1/", config); case "voyage": diff --git a/packages/openai-adapters/src/types.ts b/packages/openai-adapters/src/types.ts index 04f0b0c12..93edcc99b 100644 --- a/packages/openai-adapters/src/types.ts +++ b/packages/openai-adapters/src/types.ts @@ -103,6 +103,11 @@ export const JinaConfigSchema = OpenAIConfigSchema.extend({ }); export type JinaConfig = z.infer; +export const InceptionConfigSchema = OpenAIConfigSchema.extend({ + provider: z.literal("inception"), +}); +export type InceptionConfig = z.infer; + // Discriminated union export const LLMConfigSchema = z.discriminatedUnion("provider", [ OpenAIConfigSchema, @@ -114,5 +119,6 @@ export const LLMConfigSchema = z.discriminatedUnion("provider", [ AnthropicConfigSchema, JinaConfigSchema, MockConfigSchema, + InceptionConfigSchema, ]); export type LLMConfig = z.infer;