diff --git a/.continue/rules/typescript-enum-usage.md b/.continue/rules/typescript-enum-usage.md new file mode 100644 index 000000000..34728c1d5 --- /dev/null +++ b/.continue/rules/typescript-enum-usage.md @@ -0,0 +1,6 @@ +--- +globs: "**/*.{ts,tsx}" +alwaysApply: false +--- + +Use enums instead of simple string unions when possible in TypeScript code diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 2497e28dc..348566cd8 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -8,9 +8,9 @@ - [] The relevant docs, if any, have been updated or created - [] The relevant tests, if any, have been updated or created -## Screenshots +## Screen recording or screenshot -[ For visual changes, include screenshots. Screen recordings are particularly helpful, and appreciated! ] +[ When applicable, please include a short screen recording or screenshot - this makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example. ] ## Tests diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index 36eebc970..a88dad8c0 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -572,6 +572,43 @@ jobs: cd packages/config-yaml npm test + openai-adapters-tests: + needs: install-openai-adapters + 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: node_modules + key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }} + + - uses: actions/cache@v4 + id: openai-adapters-cache + with: + path: packages/openai-adapters/node_modules + key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }} + + - name: Run openai-adapters tests + run: | + cd packages/openai-adapters + npm test + env: + IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} + vscode-get-test-file-matrix: runs-on: ubuntu-latest needs: [install-root, install-vscode, install-config-yaml] @@ -613,6 +650,9 @@ jobs: echo "test_file_matrix<> $GITHUB_OUTPUT echo "$FILES" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT + env: + # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 + GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - name: Debug Outputs run: | @@ -1068,6 +1108,7 @@ jobs: - config-yaml-checks - install-config-yaml - install-openai-adapters + - openai-adapters-tests steps: - name: Decide whether the needed jobs succeeded or failed diff --git a/.github/workflows/release-config-yaml.yml b/.github/workflows/release-config-yaml.yml index f0d220ed0..fea1c31d4 100644 --- a/.github/workflows/release-config-yaml.yml +++ b/.github/workflows/release-config-yaml.yml @@ -6,6 +6,13 @@ on: - main paths: - "packages/config-yaml/**" + - ".github/workflows/release-config-yaml.yml" + - ".github/workflows/reusable-release.yml" + +permissions: + contents: write + issues: write + pull-requests: write jobs: release: @@ -16,3 +23,12 @@ jobs: secrets: SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} diff --git a/.github/workflows/release-fetch.yml b/.github/workflows/release-fetch.yml index 2fa1124bc..fb4636a21 100644 --- a/.github/workflows/release-fetch.yml +++ b/.github/workflows/release-fetch.yml @@ -6,6 +6,13 @@ on: - main paths: - "packages/fetch/**" + - ".github/workflows/release-fetch.yml" + - ".github/workflows/reusable-release.yml" + +permissions: + contents: write + issues: write + pull-requests: write jobs: release: @@ -16,3 +23,12 @@ jobs: secrets: SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} diff --git a/.github/workflows/release-llm-info.yml b/.github/workflows/release-llm-info.yml index 1b1c044dc..7a94eba59 100644 --- a/.github/workflows/release-llm-info.yml +++ b/.github/workflows/release-llm-info.yml @@ -16,3 +16,11 @@ jobs: secrets: SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} \ No newline at end of file diff --git a/.github/workflows/release-openai-adapters.yml b/.github/workflows/release-openai-adapters.yml index ce7f4fda8..e2a6b0622 100644 --- a/.github/workflows/release-openai-adapters.yml +++ b/.github/workflows/release-openai-adapters.yml @@ -6,6 +6,13 @@ on: - main paths: - "packages/openai-adapters/**" + - ".github/workflows/release-openai-adapters.yml" + - ".github/workflows/reusable-release.yml" + +permissions: + contents: write + issues: write + pull-requests: write jobs: release: @@ -16,3 +23,12 @@ jobs: secrets: SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} diff --git a/.github/workflows/reusable-release.yml b/.github/workflows/reusable-release.yml index 7de9d7320..80d135e29 100644 --- a/.github/workflows/reusable-release.yml +++ b/.github/workflows/reusable-release.yml @@ -14,6 +14,24 @@ on: required: true SEMANTIC_RELEASE_NPM_TOKEN: required: true + OPENAI_API_KEY: + required: false + ANTHROPIC_API_KEY: + required: false + GEMINI_API_KEY: + required: false + MISTRAL_API_KEY: + required: false + AZURE_OPENAI_API_KEY: + required: false + AZURE_FOUNDRY_CODESTRAL_API_KEY: + required: false + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: + required: false + AZURE_OPENAI_GPT41_API_KEY: + required: false + VOYAGE_API_KEY: + required: false permissions: contents: write @@ -46,10 +64,20 @@ jobs: - name: Run tests run: npm test + env: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }} + MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }} + AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }} + AZURE_FOUNDRY_CODESTRAL_API_KEY: ${{ secrets.AZURE_FOUNDRY_CODESTRAL_API_KEY }} + AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }} + AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }} + VOYAGE_API_KEY: ${{ secrets.VOYAGE_API_KEY }} - name: Release env: GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }} NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }} - run: npx semantic-release \ No newline at end of file + run: npx semantic-release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6d89e4655..9824071c1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -192,6 +192,7 @@ To keep the Continue codebase clean and maintainable, we expect the following fr - Keep changes focused. Multiple unrelated fixes should be opened as separate PRs - Write or update tests for new functionality - Update relevant documentation in the `docs` folder +- **For new features**: Include a short screen recording or screenshot demonstrating the new functionality. This makes it much easier for us as contributors to review and understand your changes. See [this PR](https://github.com/continuedev/continue/pull/6455) as a good example - Open a PR against the `main` branch. Make sure to fill in the PR template ### Formatting diff --git a/core/.eslintrc.json b/core/.eslintrc.json index 08948b866..7b4563436 100644 --- a/core/.eslintrc.json +++ b/core/.eslintrc.json @@ -19,5 +19,13 @@ "max-depth": ["error", { "max": 6 }], "max-nested-callbacks": ["error", { "max": 4 }], "max-params": ["error", { "max": 8 }] - } + }, + "overrides": [ + { + "files": ["**/*.vitest.ts"], + "rules": { + "max-lines-per-function": "off" + } + } + ] } diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index e6111a508..0d974e317 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -10,7 +10,7 @@ import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { postprocessCompletion } from "./postprocessing/index.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { getAllSnippets } from "./snippets/index.js"; +import { getAllSnippetsWithoutRace } from "./snippets/index.js"; import { renderPrompt } from "./templating/index.js"; import { GetLspDefinitionsFunction } from "./types.js"; import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; @@ -121,6 +121,12 @@ export class CompletionProvider { ...config?.tabAutocompleteOptions, ...llm.autocompleteOptions, }; + + // Enable static contextualization if defined. + if (config?.experimental?.enableStaticContextualization) { + options.experimental_enableStaticContextualization = true; + } + return options; } @@ -171,7 +177,7 @@ export class CompletionProvider { } const [snippetPayload, workspaceDirs] = await Promise.all([ - getAllSnippets({ + getAllSnippetsWithoutRace({ helper, ide: this.ide, getDefinitionsFromLsp: this.getDefinitionsFromLsp, @@ -258,6 +264,10 @@ export class CompletionProvider { ...helper.options, }; + if (options.experimental_enableStaticContextualization) { + outcome.enabledStaticContextualization = true; + } + ////////// // Save to cache diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index f521d292a..e7e9e60a4 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -2,16 +2,19 @@ import { IDE } from "../.."; import { AutocompleteCodeSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./root-path-context/RootPathContextService"; +import { StaticContextService } from "./static-context/StaticContextService"; export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; + private staticContextService: StaticContextService; constructor(private readonly ide: IDE) { this.importDefinitionsService = new ImportDefinitionsService(this.ide); @@ -19,6 +22,7 @@ export class ContextRetrievalService { this.importDefinitionsService, this.ide, ); + this.staticContextService = new StaticContextService(this.ide); } public async getSnippetsFromImportDefinitions( @@ -71,6 +75,12 @@ export class ContextRetrievalService { ); } + public async getStaticContextSnippets( + helper: HelperVars, + ): Promise { + return this.staticContextService.getContext(helper); + } + /** * Initialize the import definitions cache for a file. * This is normally done automatically when the active text editor changes, diff --git a/core/autocomplete/context/static-context/StaticContextService.ts b/core/autocomplete/context/static-context/StaticContextService.ts new file mode 100644 index 000000000..b955a38ff --- /dev/null +++ b/core/autocomplete/context/static-context/StaticContextService.ts @@ -0,0 +1,888 @@ +import * as fs from "fs/promises"; +import path from "path"; +import { pathToFileURL } from "url"; +import Parser from "web-tree-sitter"; +import { IDE, Position } from "../../.."; +import { localPathOrUriToPath } from "../../../util/pathToUri"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import { + AutocompleteSnippetType, + AutocompleteStaticSnippet, +} from "../../snippets/types"; +import { getAst } from "../../util/ast"; +import { HelperVars } from "../../util/HelperVars"; +import { + extractFunctionTypeFromDecl, + extractTopLevelDecls, + findEnclosingTypeDeclaration, + unwrapToBaseType, +} from "./tree-sitter-utils"; +import { + HoleContext, + RelevantHeaders, + RelevantTypes, + StaticContext, + TypeSpanAndSourceFile, + TypeSpanAndSourceFileAndAst, +} from "./types"; + +export class StaticContextService { + private readonly ide: IDE; + + constructor(ide: IDE) { + this.ide = ide; + } + + public logAutocompleteStaticSnippet( + ctx: StaticContext, + label = "Static Snippet", + ) { + console.log(`=== ${label} ===`); + console.log("Hole Type:", ctx.holeType); + + console.log(`\nRelevant Types (${ctx.relevantTypes.size} files):`); + ctx.relevantTypes.forEach((types, filepath) => { + console.log(` 📁 ${filepath}`); + types.forEach((type) => console.log(` • ${type}`)); + }); + + console.log(`\nRelevant Headers (${ctx.relevantHeaders.size} files):`); + ctx.relevantHeaders.forEach((headers, filepath) => { + console.log(` 📁 ${filepath}`); + headers.forEach((header) => console.log(` • ${header}`)); + }); + } + + public static formatAutocompleteStaticSnippet(ctx: StaticContext): string { + let output = `AutocompleteStaticSnippet:\n`; + output += ` holeType: ${ctx.holeType}\n`; + + output += ` relevantTypes:\n`; + if (ctx.relevantTypes.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantTypes.forEach((types, filepath) => { + output += ` ${filepath}: [${types.join(", ")}]\n`; + }); + } + + output += ` relevantHeaders:\n`; + if (ctx.relevantHeaders.size === 0) { + output += ` (none)\n`; + } else { + ctx.relevantHeaders.forEach((headers, filepath) => { + output += ` ${filepath}: [${headers.join(", ")}]\n`; + }); + } + + return output; + } + + public async getContext( + helper: HelperVars, + ): Promise { + const start = Date.now(); + const tsFiles = await this.getTypeScriptFilesFromWorkspaces( + helper.workspaceUris, + ); + // Get the three contexts holeContext, relevantTypes, relevantHeaders. + const holeContext = await this.getHoleContext( + helper.fileContents, + helper.filepath, + helper.pos, + ); + + const relevantTypes = await this.extractRelevantTypes( + holeContext.fullHoverResult, + holeContext.functionName, + holeContext.range.start.line, + holeContext.source, + new Map(), + ); + + // if (this.language === "typescript") { + // repo = getAllTSFiles(this.repoPath); + // } else if (this.language === "ocaml") { + // repo = getAllOCamlFiles(this.repoPath); + // } + // + + const relevantHeaders = await this.extractRelevantHeaders( + tsFiles, + relevantTypes, + holeContext.functionTypeSpan, + helper.pos, + holeContext.returnTypeIsAny, + ); + + const relevantTypesToReturn: Map = new Map< + string, + string[] + >(); + relevantTypes.forEach(({ typeSpan: v, sourceFile: src }, _) => { + if (relevantTypesToReturn.has(src)) { + const updated = relevantTypesToReturn.get(src)!; + updated.push(v); + relevantTypesToReturn.set(src, updated); + } else { + relevantTypesToReturn.set(src, [v]); + } + }); + + const relevantHeadersToReturn: Map = new Map< + string, + string[] + >(); + relevantHeaders.forEach(({ typeSpan: v, sourceFile: src }) => { + if (relevantHeadersToReturn.has(src)) { + const updated = relevantHeadersToReturn.get(src)!; + if (!updated.includes(v)) { + updated.push(v); + } + relevantHeadersToReturn.set(src, updated); + } else { + relevantHeadersToReturn.set(src, [v]); + } + }); + + const ctx = { + holeType: holeContext.functionTypeSpan, + relevantTypes: relevantTypesToReturn, + relevantHeaders: relevantHeadersToReturn, + }; + const end = Date.now(); + + this.logAutocompleteStaticSnippet(ctx); + + // console.log(end - start); + + const snippets: AutocompleteStaticSnippet[] = []; + + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(holeContext.source)).toString(), + content: holeContext.fullHoverResult, + }); + + for (const [filepath, typs] of ctx.relevantTypes.entries()) { + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: typs.join("\n"), + }); + } + + for (const [filepath, headers] of ctx.relevantHeaders.entries()) { + snippets.push({ + type: AutocompleteSnippetType.Static, + filepath: pathToFileURL(path.resolve(filepath)).toString(), + content: headers.join("\n"), + }); + } + + return snippets; + } + + private async getHoleContext( + sketchFileContent: string, + sketchFilePath: string, + cursorPosition: Position, + ): Promise { + // We need to inject the hole @ to trigger a treesitter error node. + sketchFilePath = localPathOrUriToPath(sketchFilePath); + // const sketchFileContent = await fs.readFile(sketchFilePath, "utf8"); + const injectedContent = this.insertAtPosition( + sketchFileContent, + cursorPosition, + "@;", + ); + + // The hole's position is cursorPosition. + + // Use treesitter to parse. + const ast = await getAst(sketchFilePath, injectedContent); + if (!ast) { + throw new Error("failed to get ast"); + } + const language = getFullLanguageName(sketchFilePath); + const query = await getQueryForFile( + sketchFilePath, + `static-context-queries/hole-queries/${language}.scm`, + ); + if (!query) { + throw new Error( + `getHoleContext: failed to get query for file ${sketchFilePath} and language ${language}`, + ); + } + + const captures = query.captures(ast.rootNode); + const res: HoleContext = { + fullHoverResult: "", + functionName: "", + functionTypeSpan: "", + returnTypeIsAny: false, + range: { + start: { line: 0, character: 0 }, + end: { line: 0, character: 0 }, + }, + source: `file://${sketchFilePath}`, + }; + let paramsTypes = ""; + for (const c of captures) { + const { name, node } = c; + // console.log(`${name} →`, node.text, node.startPosition, node.endPosition); + + switch (name) { + case "function.decl": { + res.fullHoverResult = node.text; + break; + } + case "function.name": { + res.functionName = node.text; + break; + } + case "function.params": { + paramsTypes = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + break; + } + case "function.type": { + res.functionTypeSpan = node.text; + res.range = { + start: { + line: node.startPosition.row, + character: node.startPosition.column, + }, + end: { + line: node.endPosition.row, + character: node.endPosition.column, + }, + }; + break; + } + } + } + + if (res.functionTypeSpan === "") { + res.functionTypeSpan = `${paramsTypes} => any`; + res.returnTypeIsAny = true; + } + + return res; + } + + private async extractRelevantTypes( + declText: string, + typeName: string, + startLine: number, + currentFile: string, + foundContents: Map, // uri -> contents + ): Promise { + const foundSoFar = new Map(); // identifier -> [full hover result, source] + + await this.extractRelevantTypesHelper( + declText, + typeName, + startLine, + foundSoFar, + currentFile, + foundContents, + ); + + return foundSoFar; + } + + private async extractRelevantTypesHelper( + declText: string, + typeName: string, + startLine: number, + foundSoFar: Map, // identifier -> [full hover result, source] + currentFile: string, + foundContents: Map, // uri -> contents + ) { + if (!foundSoFar.has(typeName)) { + const ast = await getAst(currentFile, declText); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + foundSoFar.set(typeName, { + typeSpan: declText, + sourceFile: currentFile.slice(7), + ast: ast, + }); + + const language = getFullLanguageName(currentFile); + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-types-queries/${language}-extract-identifiers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + + const identifiers = query.captures(ast.rootNode); + + for (const { name, node } of identifiers) { + if (foundSoFar.has(node.text)) continue; + + try { + const typeDefinitionResult = await this.ide.gotoTypeDefinition({ + filepath: currentFile, + position: { + character: node.startPosition.column, + line: startLine + node.startPosition.row, + }, + }); + + if (typeDefinitionResult.length > 0) { + const tdLocation = typeDefinitionResult[0]; + + let content = ""; + + if (foundContents.has(tdLocation.filepath)) { + content = foundContents.get(tdLocation.filepath)!; + } else { + content = await fs.readFile( + localPathOrUriToPath(tdLocation.filepath), + "utf8", + ); + foundContents.set(tdLocation.filepath, content); + } + + const ast = await getAst(tdLocation.filepath, content); + if (!ast) { + throw new Error( + `failed to get ast for file ${tdLocation.filepath}`, + ); + } + const decl = findEnclosingTypeDeclaration( + content, + tdLocation.range.start.line, + tdLocation.range.start.character, + ast, + ); + if (!decl) { + // throw new Error(`failed to get decl for file ${tdLocation.uri}`); + console.error( + `failed to get decl for file ${tdLocation.filepath}`, + ); + } + + if (decl) { + await this.extractRelevantTypesHelper( + decl.fullText, + node.text, + tdLocation.range.start.line, + foundSoFar, + tdLocation.filepath, + foundContents, + ); + } else { + // console.log("decl not found"); + } + } else { + // console.log("td not found"); + } + } catch (err) { + console.log(err); + } + } + } + } + + private async extractRelevantHeaders( + sources: string[], + relevantTypes: Map, + holeType: string, + cursorPosition: Position, + returnTypeIsAny: boolean, + ): Promise { + const relevantContext = new Set(); + if (returnTypeIsAny) return relevantContext; + // NOTE: This is necessary because TypeScript sucks. + // There is no way to compare objects by value, + // so sets of objects starts to accumulate tons of duplicates. + const relevantContextMap = new Map(); + const foundNormalForms = new Map(); + + const targetTypes = await this.generateTargetTypes(relevantTypes, holeType); + + for (const source of sources) { + const topLevelDecls = await extractTopLevelDecls(source); + for (const tld of topLevelDecls) { + // pattern 0 is let/const, 1 is var, 2 is fun + // if (!seenDecls.has(JSON.stringify()) { + const originalDeclText = + tld.pattern === 2 + ? tld.captures.find((d) => d.name === "top.fn.decl")!.node.text + : tld.captures.find((d) => d.name === "top.var.decl")!.node.text; + + if (tld.pattern === 2) { + // build a type span + // TODO: this fails sometimes with Cannot read properties of undefined (reading 'text') + // most likely due to my scm query and how I'm not attaching param name along with param type + let funcType = ""; + try { + funcType = extractFunctionTypeFromDecl(tld); + } catch (err) { + // Most likely is the case that there is no explicit return type annotation. + const sigHelp = await this.ide.getSignatureHelp({ + filepath: source, + position: cursorPosition, + }); + if (!sigHelp) continue; + funcType = sigHelp.signatures[0].label; + + // TODO: This only works for TypeScript. + function convertToArrowType(signature: string): string { + // Handle various function declaration formats. + const patterns = [ + // Standard: functionName(params): returnType. + /^(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + // With generics: functionName(params): returnType. + /^(\w+)\s*<[^>]*>\s*\((.*?)\)\s*:\s*(.+)$/, + // With modifiers: export function functionName(params): returnType. + /^(?:export\s+)?(?:function\s+)?(\w+)\s*\((.*?)\)\s*:\s*(.+)$/, + ]; + + for (const pattern of patterns) { + const match = signature.match(pattern); + if (match) { + const [, , parameters, returnType] = match; + return `(${parameters}) => ${returnType}`; + } + } + + return signature; + } + + funcType = convertToArrowType(funcType); + } + const wrapped = `type __TMP = ${funcType};`; + + const ast = await getAst("file.ts", wrapped); + if (!ast) { + throw new Error(`failed to generate ast for ${wrapped}`); + } + + // console.log(ast.rootNode); + const alias = ast.rootNode.namedChild(0); + // console.log(alias); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error( + "extractRelevantHeaders: Failed to parse type alias", + ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + + await this.extractRelevantHeadersHelper( + originalDeclText, + baseNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } else { + const varTypNode = tld.captures.find( + (d) => d.name === "top.var.type", + )!.node; + await this.extractRelevantHeadersHelper( + originalDeclText, + varTypNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + + for (const v of relevantContextMap.values()) { + relevantContext.add(v); + } + + return relevantContext; + } + + private async extractRelevantHeadersHelper( + originalDeclText: string, + node: Parser.SyntaxNode, + targetTypes: Set, + relevantTypes: Map, + relevantContext: Set, + relevantContextMap: Map, + foundNormalForms: Map, + source: string, + ) { + for (const typ of targetTypes) { + if ( + await this.isTypeEquivalent(node, typ, relevantTypes, foundNormalForms) + ) { + const ctx = { typeSpan: originalDeclText, sourceFile: source }; + relevantContextMap.set(JSON.stringify(ctx), ctx); + } + + if (node.type === "function_type") { + const retTypeNode = node.namedChildren.find( + (c) => c && c.type === "return_type", + ); + if (retTypeNode) { + await this.extractRelevantHeadersHelper( + originalDeclText, + retTypeNode, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } else if (node.type === "tuple_type") { + for (const c of node.namedChildren) { + await this.extractRelevantHeadersHelper( + originalDeclText, + c!, + targetTypes, + relevantTypes, + relevantContext, + relevantContextMap, + foundNormalForms, + source, + ); + } + } + } + } + + private async generateTargetTypes( + relevantTypes: Map, + holeType: string, + ) { + const targetTypes = new Set(); + // const ast = relevantTypes.get(holeIdentifier)!.ast; + const ast = await getAst("file.ts", `type T = ${holeType};`); + if (!ast) { + throw new Error(`failed to generate ast for ${holeType}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + throw new Error("generateTargetTypes: Failed to parse type alias"); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + targetTypes.add(baseNode); + await this.generateTargetTypesHelper( + relevantTypes, + holeType, + targetTypes, + baseNode, + ); + + return targetTypes; + } + + private async generateTargetTypesHelper( + relevantTypes: Map, + currType: string, + targetTypes: Set, + node: Parser.SyntaxNode | null, + ): Promise { + if (!node) return; + + if (node.type === "function_type") { + const returnType = node.childForFieldName("return_type"); + if (returnType) { + targetTypes.add(returnType); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + returnType, + ); + } + } + + if (node.type === "tuple_type") { + for (const child of node.namedChildren) { + if (child) { + targetTypes.add(child); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + child, + ); + } + } + } + + if (relevantTypes.has(node.text)) { + // const ast = relevantTypes.get(node.text)!.ast; + const typeSpan = relevantTypes.get(node.text)?.typeSpan; + + // const ast = await getAst("file.ts", `type T = ${typeSpan}`); + const ast = await getAst("file.ts", typeSpan!); + if (!ast) { + throw new Error(`failed to generate ast for ${typeSpan}`); + } + + const alias = ast.rootNode.namedChild(0); + if (!alias || alias.type !== "type_alias_declaration") { + console.error("generateTargetTypesHelper: Failed to parse type alias"); + return; + // throw new Error( + // "generateTargetTypesHelper: Failed to parse type alias", + // ); + } + + const valueNode = alias.childForFieldName("value"); + if (!valueNode) throw new Error("No type value found"); + + const baseNode = unwrapToBaseType(valueNode); + await this.generateTargetTypesHelper( + relevantTypes, + currType, + targetTypes, + baseNode, + ); + } + + // if (node.type === "type_identifier" || node.type === "predefined_type") { + // return [node.text]; + // } + + return; + } + + private async isTypeEquivalent( + node: Parser.SyntaxNode, + typ: Parser.SyntaxNode, + relevantTypes: Map, + foundNormalForms: Map, + ): Promise { + if (!node || !typ) { + return false; + } + let normT1 = ""; + let normT2 = ""; + if (foundNormalForms.has(node.text)) { + // console.log("found t1", true) + normT1 = foundNormalForms.get(node.text)!; + } else { + // console.log("not found t1", false) + normT1 = await this.normalize(node, relevantTypes); + foundNormalForms.set(node.text, normT1); + } + if (foundNormalForms.has(typ.text)) { + // console.log("found t2", true) + normT2 = foundNormalForms.get(typ.text)!; + } else { + // console.log("not found t2", false) + normT2 = await this.normalize(typ, relevantTypes); + foundNormalForms.set(typ.text, normT2); + } + // const normT1 = foundNormalForms.has(t1) ? foundNormalForms.get(t1) : this.normalize2(t1, relevantTypes); + // const normT2 = foundNormalForms.has(t2) ? foundNormalForms.get(t2) : this.normalize2(t2, relevantTypes); + // console.log(`normal forms: ${normT1} {}{} ${normT2}`) + return normT1 === normT2; + } + + private async normalize( + node: Parser.SyntaxNode, + relevantTypes: Map, + ): Promise { + if (!node) return ""; + + switch (node.type) { + case "function_type": { + const params = node.child(0); // formal_parameters + const returnType = + node.childForFieldName("type") || node.namedChildren[1]; // function_type → parameters, =>, return + + const paramTypes = + params?.namedChildren + .map((param) => + this.normalize( + param!.childForFieldName("type")! || + param!.namedChildren.at(-1), + relevantTypes, + ), + ) + .join(", ") || ""; + + const ret = this.normalize(returnType!, relevantTypes); + return `(${paramTypes}) => ${ret}`; + } + + case "tuple_type": { + const elements = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return `[${elements.join(", ")}]`; + } + + case "union_type": { + const parts = node.namedChildren.map((c) => + this.normalize(c!, relevantTypes), + ); + return parts.join(" | "); + } + + case "type_identifier": { + const alias = relevantTypes.get(node.text); + if (!alias) return node.text; + + // Parse the alias's type span + const wrapped = `type __TMP = ${alias};`; + const tree = await getAst("file.ts", wrapped); + const valueNode = tree!.rootNode + .descendantsOfType("type_alias_declaration")[0] + ?.childForFieldName("value"); + + return this.normalize(valueNode!, relevantTypes); + } + + case "predefined_type": + case "number": + case "string": + return node.text; + + default: + // Fallback for types like array, etc. + return node.text; + } + } + + private insertAtPosition = ( + contents: string, + cursorPosition: { line: number; character: number }, + insertText: string, + ): string => { + const lines = contents.split(/\r?\n/); // Handle both LF and CRLF line endings + const { line, character } = cursorPosition; + + if (line < 0 || line >= lines.length) { + throw new Error("Invalid line number"); + } + + const targetLine = lines[line]; + if (character < 0 || character > targetLine.length) { + throw new Error("Invalid character index"); + } + + // Insert the text + lines[line] = + targetLine.slice(0, character) + insertText + targetLine.slice(character); + + return lines.join("\n"); // Reconstruct the file + }; + + private async getTypeScriptFilesFromWorkspaces( + workspaceUris: string[], + ): Promise { + const tsExtensions = [".ts"]; + const allTsFiles: string[] = []; + + for (const workspaceUri of workspaceUris) { + try { + // Convert URI to file path + const folderPath = workspaceUri.startsWith("file://") + ? new URL(workspaceUri).pathname + : workspaceUri; + + const tsFiles = await this.scanDirectoryForTypeScriptFiles( + folderPath, + tsExtensions, + ); + allTsFiles.push(...tsFiles); + } catch (error) { + console.error(`Error scanning workspace ${workspaceUri}:`, error); + } + } + + return allTsFiles; + } + + private async scanDirectoryForTypeScriptFiles( + dirPath: string, + tsExtensions: string[], + ): Promise { + const tsFiles: string[] = []; + + const shouldSkipDirectory = (dirName: string): boolean => { + const skipDirs = [ + "node_modules", + ".git", + ".vscode", + "dist", + "build", + "out", + ".next", + "coverage", + ".nyc_output", + "tmp", + "temp", + ".cache", + ]; + + return skipDirs.includes(dirName) || dirName.startsWith("."); + }; + + async function scanRecursively(currentPath: string): Promise { + try { + const entries = await fs.readdir(currentPath, { + withFileTypes: true, + }); + + for (const entry of entries) { + const fullPath = localPathOrUriToPath( + path.join(currentPath, entry.name), + ); + + if (entry.isDirectory()) { + // Skip common directories that typically don't contain source files + if (!shouldSkipDirectory(entry.name)) { + await scanRecursively(fullPath); + } + } else if (entry.isFile()) { + const extension = path.extname(entry.name).toLowerCase(); + if (tsExtensions.includes(extension)) { + tsFiles.push(fullPath); + } + } + } + } catch (error) { + console.error(`Error reading directory ${currentPath}:`, error); + } + } + + await scanRecursively(dirPath); + return tsFiles; + } +} diff --git a/core/autocomplete/context/static-context/tree-sitter-utils.ts b/core/autocomplete/context/static-context/tree-sitter-utils.ts new file mode 100644 index 000000000..6e751f547 --- /dev/null +++ b/core/autocomplete/context/static-context/tree-sitter-utils.ts @@ -0,0 +1,222 @@ +import * as fs from "fs/promises"; +import Parser from "web-tree-sitter"; +import { getFullLanguageName, getQueryForFile } from "../../../util/treeSitter"; +import { getAst } from "../../util/ast"; + +export interface TypeDeclarationResult { + name: string; + fullText: string; + startLine: number; + startColumn: number; + endLine: number; + endColumn: number; + kind: string; +} + +export function findEnclosingTypeDeclaration( + sourceCode: string, + cursorLine: number, + cursorColumn: number, + ast: Parser.Tree, +): TypeDeclarationResult | null { + const point = { row: cursorLine, column: cursorColumn }; + let node = ast.rootNode.descendantForPosition(point); + + while ( + node && + ![ + "type_alias_declaration", + "interface_declaration", + "enum_declaration", + ].includes(node.type) + ) { + if (!node.parent) return null; + node = node.parent; + } + + if (!node) return null; + + const nameNode = node.childForFieldName("name"); + const name = nameNode?.text ?? ""; + const fullText = sourceCode.slice(node.startIndex, node.endIndex); + + return { + name, + fullText, + startLine: node.startPosition.row, + startColumn: node.startPosition.column, + endLine: node.endPosition.row, + endColumn: node.endPosition.column, + kind: node.type, + }; +} + +export async function extractTopLevelDecls( + currentFile: string, + givenParser?: Parser, +) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + return query.matches(ast.rootNode); +} + +export async function extractTopLevelDeclsWithFormatting( + currentFile: string, + givenParser?: Parser, +) { + const ast = await getAst(currentFile, await fs.readFile(currentFile, "utf8")); + if (!ast) { + throw new Error(`failed to get ast for file ${currentFile}`); + } + let language; + if (givenParser) { + language = givenParser.getLanguage(); + } else { + language = getFullLanguageName(currentFile); + } + + const query = await getQueryForFile( + currentFile, + `static-context-queries/relevant-headers-queries/${language}-get-toplevel-headers.scm`, + ); + if (!query) { + throw new Error( + `failed to get query for file ${currentFile} and language ${language}`, + ); + } + const matches = query.matches(ast.rootNode); + + const results = []; + + for (const match of matches) { + const item: { + declaration: string; + nodeType: string; + name: string; + declaredType: string; + returnType?: string; + } = { + declaration: "", + nodeType: "", + name: "", + declaredType: "", + }; + + for (const { name, node } of match.captures) { + if (name === "top.var.decl") { + item.nodeType = "variable"; + item.declaration = node.text; + + // Attempt to get the declared type (e.g., const x: string = ...) + const typeNode = node.descendantsOfType("type_annotation")[0]; + if (typeNode) { + item.declaredType = typeNode.text.replace(/^:\s*/, ""); + } + } else if (name === "top.var.name" || name === "top.fn.name") { + item.name = node.text; + } else if (name === "top.fn.decl") { + item.nodeType = "function"; + item.declaration = node.text; + + // Get the return type (e.g., function foo(): string) + const returnTypeNode = node.childForFieldName("return_type"); + if (returnTypeNode) { + item.returnType = returnTypeNode.text.replace(/^:\s*/, ""); + } + + // Get declaredType if needed (TypeScript style) + const nameNode = node.childForFieldName("name"); + if (nameNode && nameNode.nextSibling?.type === "type_annotation") { + item.declaredType = nameNode.nextSibling.text.replace(/^:\s*/, ""); + } + } + } + + if (item.name && item.declaration) { + results.push(item); + } + } + + return results; +} + +export function extractFunctionTypeFromDecl(match: Parser.QueryMatch): string { + let paramsNode: Parser.SyntaxNode | undefined = undefined; + let returnNode: Parser.SyntaxNode | undefined = undefined; + + for (const capture of match.captures) { + if (capture.name === "top.fn.param.type") { + paramsNode = capture.node; + } else if (capture.name === "top.fn.type") { + returnNode = capture.node; + } + } + + if (!paramsNode) { + console.error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: paramsNode ${paramsNode} not found`, + ); + } + + if (!returnNode) { + console.error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); + throw new Error( + `extractFunctionTypeFromDecl: returnNode ${returnNode} not found`, + ); + } + + return `(${paramsNode!.text}) => ${returnNode!.text}`; +} + +export function unwrapToBaseType(node: Parser.SyntaxNode): Parser.SyntaxNode { + if ( + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(node.type) + ) { + return node; + } + + for (const child of node.namedChildren) { + const unwrapped = unwrapToBaseType(child!); + if ( + unwrapped !== child || + [ + "function_type", + "tuple_type", + "type_identifier", + "predefined_type", + ].includes(unwrapped.type) + ) { + return unwrapped; + } + } + + return node; +} diff --git a/core/autocomplete/context/static-context/types.ts b/core/autocomplete/context/static-context/types.ts new file mode 100644 index 000000000..1aa8b473d --- /dev/null +++ b/core/autocomplete/context/static-context/types.ts @@ -0,0 +1,33 @@ +import { Tree } from "web-tree-sitter"; +import { Range } from "../../.."; + +export interface TypeSpanAndSourceFile { + typeSpan: string; + sourceFile: string; +} + +export interface TypeSpanAndSourceFileAndAst extends TypeSpanAndSourceFile { + ast: Tree; +} + +export interface HoleContext { + fullHoverResult: string; + functionName: string; + functionTypeSpan: string; + returnTypeIsAny: boolean; + range: Range; + source: string; +} + +export type RelevantTypes = Map; +export type RelevantHeaders = Set; + +export type Filepath = string; +export type RelevantType = string; +export type RelevantHeader = string; + +export interface StaticContext { + holeType: string; + relevantTypes: Map; + relevantHeaders: Map; +} diff --git a/core/autocomplete/snippets/getAllSnippets.ts b/core/autocomplete/snippets/getAllSnippets.ts index 702356198..079127abc 100644 --- a/core/autocomplete/snippets/getAllSnippets.ts +++ b/core/autocomplete/snippets/getAllSnippets.ts @@ -11,6 +11,7 @@ import { AutocompleteCodeSnippet, AutocompleteDiffSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "./types"; const IDE_SNIPPETS_ENABLED = false; // ideSnippets is not used, so it's temporarily disabled @@ -24,6 +25,7 @@ export interface SnippetPayload { diffSnippets: AutocompleteDiffSnippet[]; clipboardSnippets: AutocompleteClipboardSnippet[]; recentlyOpenedFileSnippets: AutocompleteCodeSnippet[]; + staticSnippet: AutocompleteStaticSnippet[]; } function racePromise(promise: Promise, timeout = 100): Promise { @@ -185,6 +187,7 @@ export const getAllSnippets = async ({ diffSnippets, clipboardSnippets, recentlyOpenedFileSnippets, + staticSnippet, ] = await Promise.all([ racePromise(contextRetrievalService.getRootPathSnippets(helper)), racePromise( @@ -196,6 +199,9 @@ export const getAllSnippets = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, racePromise(getClipboardSnippets(ide)), racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete + helper.options.experimental_enableStaticContextualization + ? racePromise(contextRetrievalService.getStaticContextSnippets(helper)) + : [], ]); return { @@ -207,6 +213,7 @@ export const getAllSnippets = async ({ clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, recentlyOpenedFileSnippets, + staticSnippet, }; }; @@ -231,6 +238,7 @@ export const getAllSnippetsWithoutRace = async ({ diffSnippets, clipboardSnippets, recentlyOpenedFileSnippets, + staticSnippet, ] = await Promise.all([ contextRetrievalService.getRootPathSnippets(helper), contextRetrievalService.getSnippetsFromImportDefinitions(helper), @@ -240,6 +248,9 @@ export const getAllSnippetsWithoutRace = async ({ [], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882, getClipboardSnippets(ide), getSnippetsFromRecentlyOpenedFiles(helper, ide), + helper.options.experimental_enableStaticContextualization + ? contextRetrievalService.getStaticContextSnippets(helper) + : [], ]); return { @@ -251,5 +262,6 @@ export const getAllSnippetsWithoutRace = async ({ clipboardSnippets, recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges, recentlyOpenedFileSnippets, + staticSnippet, }; }; diff --git a/core/autocomplete/snippets/types.ts b/core/autocomplete/snippets/types.ts index e43b59862..be820609b 100644 --- a/core/autocomplete/snippets/types.ts +++ b/core/autocomplete/snippets/types.ts @@ -2,6 +2,7 @@ export enum AutocompleteSnippetType { Code = "code", Diff = "diff", Clipboard = "clipboard", + Static = "static", } interface BaseAutocompleteSnippet { @@ -23,7 +24,13 @@ export interface AutocompleteClipboardSnippet extends BaseAutocompleteSnippet { copiedAt: string; } +export interface AutocompleteStaticSnippet extends BaseAutocompleteSnippet { + type: AutocompleteSnippetType.Static; + filepath: string; +} + export type AutocompleteSnippet = | AutocompleteCodeSnippet | AutocompleteDiffSnippet - | AutocompleteClipboardSnippet; + | AutocompleteClipboardSnippet + | AutocompleteStaticSnippet; diff --git a/core/autocomplete/templating/filtering.ts b/core/autocomplete/templating/filtering.ts index 2abb98c7d..94fe312e2 100644 --- a/core/autocomplete/templating/filtering.ts +++ b/core/autocomplete/templating/filtering.ts @@ -4,6 +4,7 @@ import { AutocompleteCodeSnippet, AutocompleteSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; import { formatOpenedFilesContext } from "./formatOpenedFilesContext"; @@ -32,9 +33,9 @@ const shuffleArray = (array: T[]): T[] => { }; function filterSnippetsAlreadyInCaretWindow( - snippets: AutocompleteCodeSnippet[], + snippets: (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[], caretWindow: string, -): AutocompleteCodeSnippet[] { +): (AutocompleteCodeSnippet | AutocompleteStaticSnippet)[] { return snippets.filter( (s) => s.content.trim() !== "" && !caretWindow.includes(s.content.trim()), ); @@ -52,7 +53,11 @@ export const getSnippets = ( recentlyOpenedFiles: payload.recentlyOpenedFileSnippets, base: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), @@ -107,7 +112,11 @@ export const getSnippets = ( defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override snippets: shuffleArray( filterSnippetsAlreadyInCaretWindow( - [...payload.rootPathSnippets, ...payload.importDefinitionSnippets], + [ + ...payload.rootPathSnippets, + ...payload.importDefinitionSnippets, + ...payload.staticSnippet, + ], helper.prunedCaretWindow, ), ), diff --git a/core/autocomplete/templating/formatting.ts b/core/autocomplete/templating/formatting.ts index 2a91ad438..583873c2d 100644 --- a/core/autocomplete/templating/formatting.ts +++ b/core/autocomplete/templating/formatting.ts @@ -5,6 +5,7 @@ import { AutocompleteDiffSnippet, AutocompleteSnippet, AutocompleteSnippetType, + AutocompleteStaticSnippet, } from "../snippets/types"; import { HelperVars } from "../util/HelperVars"; @@ -51,6 +52,12 @@ const formatDiffSnippet = ( return snippet; }; +const formatStaticSnippet = ( + snippet: AutocompleteStaticSnippet, +): AutocompleteStaticSnippet => { + return snippet; +}; + const commentifySnippet = ( helper: HelperVars, snippet: AutocompleteSnippet, @@ -81,6 +88,8 @@ export const formatSnippets = ( return formatDiffSnippet(snippet); case AutocompleteSnippetType.Clipboard: return formatClipboardSnippet(snippet, workspaceDirs); + case AutocompleteSnippetType.Static: + return formatStaticSnippet(snippet); } }) .map((item) => { diff --git a/core/autocomplete/util/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts index 2e4d19844..58b3d2d0d 100644 --- a/core/autocomplete/util/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -105,24 +105,27 @@ export class AutocompleteLoggingService { }); const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: getUriFileExtension(restOfOutcome.filepath), - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - numLines: restOfOutcome.numLines, - }, - true, - ); + const toLog = { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: getUriFileExtension(restOfOutcome.filepath), + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + numLines: restOfOutcome.numLines, + }; + + outcome.enabledStaticContextualization + ? void Telemetry.capture("autocomplete", { + ...toLog, + enabledStaticContextualization: true, + }) + : void Telemetry.capture("autocomplete", toLog); } } diff --git a/core/autocomplete/util/types.ts b/core/autocomplete/util/types.ts index bd385fb47..4f669fc63 100644 --- a/core/autocomplete/util/types.ts +++ b/core/autocomplete/util/types.ts @@ -42,4 +42,5 @@ export interface AutocompleteOutcome extends TabAutocompleteOptions { completionId: string; uniqueId: string; timestamp: string; + enabledStaticContextualization?: boolean; } diff --git a/core/commands/slash/customSlashCommand.ts b/core/commands/slash/customSlashCommand.ts index c27a41f4c..9526cbca8 100644 --- a/core/commands/slash/customSlashCommand.ts +++ b/core/commands/slash/customSlashCommand.ts @@ -11,5 +11,6 @@ export function convertCustomCommandToSlashCommand( description: customCommand.description ?? "", prompt: customCommand.prompt, source: "json-custom-command", + promptFile: customCommand.sourceFile, // TODO refactor promptFile to align with sourceFile }; } diff --git a/core/commands/slash/promptBlockSlashCommand.ts b/core/commands/slash/promptBlockSlashCommand.ts index 00530b8bd..4f3446a21 100644 --- a/core/commands/slash/promptBlockSlashCommand.ts +++ b/core/commands/slash/promptBlockSlashCommand.ts @@ -9,5 +9,6 @@ export function convertPromptBlockToSlashCommand( description: prompt.description ?? "", prompt: prompt.prompt, source: "yaml-prompt-block", + promptFile: prompt.sourceFile, // Align with the sourceFile property }; } diff --git a/core/config/ConfigHandler.ts b/core/config/ConfigHandler.ts index a50e72c24..1ca09b1e2 100644 --- a/core/config/ConfigHandler.ts +++ b/core/config/ConfigHandler.ts @@ -522,7 +522,10 @@ export class ConfigHandler { return config; } - async openConfigProfile(profileId?: string) { + async openConfigProfile( + profileId?: string, + element?: { sourceFile?: string }, + ) { let openProfileId = profileId || this.currentProfile?.profileDescription.id; if (!openProfileId) { return; @@ -530,8 +533,10 @@ export class ConfigHandler { const profile = this.currentOrg.profiles.find( (p) => p.profileDescription.id === openProfileId, ); + if (profile?.profileDescription.profileType === "local") { - await this.ide.openFile(profile.profileDescription.uri); + const configFile = element?.sourceFile ?? profile.profileDescription.uri; + await this.ide.openFile(configFile); } else { const env = await getControlPlaneEnv(this.ide.getIdeSettings()); await this.ide.openUrl(`${env.APP_URL}${openProfileId}`); diff --git a/core/config/load.ts b/core/config/load.ts index a5da010f9..5206bb8bb 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -652,6 +652,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription { configurationStatus: llm.getConfigurationStatus(), apiKeyLocation: llm.apiKeyLocation, envSecretLocations: llm.envSecretLocations, + sourceFile: llm.sourceFile, }; } diff --git a/core/config/sharedConfig.ts b/core/config/sharedConfig.ts index c720f4272..568a30af8 100644 --- a/core/config/sharedConfig.ts +++ b/core/config/sharedConfig.ts @@ -22,6 +22,7 @@ export const sharedConfigSchema = z optInNextEditFeature: z.boolean(), enableExperimentalTools: z.boolean(), codebaseToolCallingOnly: z.boolean(), + enableStaticContextualization: z.boolean(), // `ui` in `ContinueConfig` showSessionTabs: z.boolean(), @@ -188,6 +189,10 @@ export function modifyAnyConfigWithSharedConfig< configCopy.experimental.codebaseToolCallingOnly = sharedConfig.codebaseToolCallingOnly; } + if (sharedConfig.enableStaticContextualization !== undefined) { + configCopy.experimental.enableStaticContextualization = + sharedConfig.enableStaticContextualization; + } return configCopy; } diff --git a/core/config/yaml/loadYaml.ts b/core/config/yaml/loadYaml.ts index 04c19b326..b1682e751 100644 --- a/core/config/yaml/loadYaml.ts +++ b/core/config/yaml/loadYaml.ts @@ -56,6 +56,7 @@ function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource { rule: rule.rule, globs: rule.globs, name: rule.name, + ruleFile: rule.sourceFile, }; } } @@ -235,8 +236,8 @@ async function configYamlToContinueConfig(options: { startUrl: doc.startUrl, rootUrl: doc.rootUrl, faviconUrl: doc.faviconUrl, - maxDepth: doc.maxDepth, useLocalCrawling: doc.useLocalCrawling, + sourceFile: doc.sourceFile, })); config.mcpServers?.forEach((mcpServer) => { @@ -429,6 +430,7 @@ async function configYamlToContinueConfig(options: { (config.mcpServers ?? []).map((server) => ({ id: server.name, name: server.name, + sourceFile: server.sourceFile, transport: { type: "stdio", args: [], diff --git a/core/core.ts b/core/core.ts index a3fe4cab5..d8275b8ff 100644 --- a/core/core.ts +++ b/core/core.ts @@ -349,7 +349,10 @@ export class Core { }); on("config/openProfile", async (msg) => { - await this.configHandler.openConfigProfile(msg.data.profileId); + await this.configHandler.openConfigProfile( + msg.data.profileId, + msg.data?.element, + ); }); on("config/reload", async (msg) => { diff --git a/core/index.d.ts b/core/index.d.ts index 924a224b9..f9fdc34cf 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -237,6 +237,7 @@ export interface SiteIndexingConfig { maxDepth?: number; faviconUrl?: string; useLocalCrawling?: boolean; + sourceFile?: string; } export interface DocsIndexingDetails { @@ -369,10 +370,32 @@ export interface ThinkingChatMessage { toolCalls?: ToolCallDelta[]; } +/** + * This is meant to be equivalent to the OpenAI [usage object](https://platform.openai.com/docs/api-reference/chat/object#chat/object-usage) + * but potentially with additional information that is needed for other providers. + */ +export interface Usage { + completionTokens: number; + promptTokens: number; + promptTokensDetails?: { + cachedTokens?: number; + /** This an Anthropic-specific property */ + cacheWriteTokens?: number; + audioTokens?: number; + }; + completionTokensDetails?: { + acceptedPredictionTokens?: number; + reasoningTokens?: number; + rejectedPredictionTokens?: number; + audioTokens?: number; + }; +} + export interface AssistantChatMessage { role: "assistant"; content: MessageContent; toolCalls?: ToolCallDelta[]; + usage?: Usage; } export interface SystemChatMessage { @@ -491,12 +514,14 @@ export interface LLMInteractionStartChat extends LLMInteractionBase { kind: "startChat"; messages: ChatMessage[]; options: CompletionOptions; + provider: string; } export interface LLMInteractionStartComplete extends LLMInteractionBase { kind: "startComplete"; prompt: string; options: CompletionOptions; + provider: string; } export interface LLMInteractionStartFim extends LLMInteractionBase { @@ -504,6 +529,7 @@ export interface LLMInteractionStartFim extends LLMInteractionBase { prefix: string; suffix: string; options: CompletionOptions; + provider: string; } export interface LLMInteractionChunk extends LLMInteractionBase { @@ -520,6 +546,7 @@ export interface LLMInteractionEnd extends LLMInteractionBase { promptTokens: number; generatedTokens: number; thinkingTokens: number; + usage: Usage | undefined; } export interface LLMInteractionSuccess extends LLMInteractionEnd { @@ -634,6 +661,8 @@ export interface LLMOptions { deploymentId?: string; env?: Record; + + sourceFile?: string; } type RequireAtLeastOne = Pick< @@ -845,6 +874,8 @@ export interface IDE { // LSP gotoDefinition(location: Location): Promise; + gotoTypeDefinition(location: Location): Promise; // TODO: add to jetbrains + getSignatureHelp(location: Location): Promise; // TODO: add to jetbrains // Callbacks onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void; @@ -1009,6 +1040,7 @@ export interface CustomCommand { name: string; prompt: string; description?: string; + sourceFile?: string; } export interface Prediction { @@ -1126,6 +1158,8 @@ export interface ModelDescription { capabilities?: ModelCapability; roles?: ModelRole[]; configurationStatus?: LLMConfigurationStatuses; + + sourceFile?: string; } export interface JSONEmbedOptions { @@ -1183,6 +1217,7 @@ export interface TabAutocompleteOptions { experimental_includeRecentlyVisitedRanges: boolean | number; experimental_includeRecentlyEditedRanges: boolean | number; experimental_includeDiff: boolean | number; + experimental_enableStaticContextualization: boolean; } export interface StdioOptions { @@ -1280,6 +1315,7 @@ export interface MCPServerStatus extends MCPOptions { tools: MCPTool[]; resources: MCPResource[]; resourceTemplates: MCPResourceTemplate[]; + sourceFile?: string; } export interface ContinueUIConfig { @@ -1382,6 +1418,68 @@ export interface RangeInFileWithNextEditInfo { export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents; +/** + * Signature help represents the signature of something + * callable. There can be multiple signatures but only one + * active and only one active parameter. + */ +export class SignatureHelp { + /** + * One or more signatures. + */ + signatures: SignatureInformation[]; + + /** + * The active signature. + */ + activeSignature: number; + + /** + * The active parameter of the active signature. + */ + activeParameter: number; +} + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +export class SignatureInformation { + /** + * The label of this signature. Will be shown in + * the UI. + */ + label: string; + + /** + * The parameters of this signature. + */ + parameters: ParameterInformation[]; + + /** + * The index of the active parameter. + * + * If provided, this is used in place of {@linkcode SignatureHelp.activeParameter}. + */ + activeParameter?: number; +} + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +export class ParameterInformation { + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * {@link SignatureInformation.label signature label}. *Note*: A label of type string must be + * a substring of its containing signature information's {@link SignatureInformation.label label}. + */ + label: string | [number, number]; +} + /** * Represents the configuration for a quick action in the Code Lens. * Quick actions are custom commands that can be added to function and class declarations. @@ -1452,6 +1550,12 @@ export interface ExperimentalConfig { * instead of embeddings, FTS, recently edited files, etc. */ codebaseToolCallingOnly?: boolean; + + /** + * If enabled, static contextualization will be used to + * gather context for the model where necessary. + */ + enableStaticContextualization?: boolean; } export interface AnalyticsConfig { @@ -1686,23 +1790,12 @@ export interface CompleteOnboardingPayload { apiKey?: string; } -export type PruningStatus = "deleted-last-input" | "pruned" | "not-pruned"; - export interface CompiledMessagesResult { compiledChatMessages: ChatMessage[]; - pruningStatus: PruningStatus; + didPrune: boolean; + contextPercentage: number; } export interface MessageOption { precompiled: boolean; } - -export type WarningMessageLevel = "warning" | "fatal"; - -export type WarningCategory = "exceeded-context-length" | "deleted-last-input"; - -export interface WarningMessage { - message: string; - level: WarningMessageLevel; - category: WarningCategory; -} diff --git a/core/indexing/docs/crawlers/DocsCrawler.test.ts b/core/indexing/docs/crawlers/DocsCrawler.test.ts index 96c6dc24d..d72d774ca 100644 --- a/core/indexing/docs/crawlers/DocsCrawler.test.ts +++ b/core/indexing/docs/crawlers/DocsCrawler.test.ts @@ -53,7 +53,7 @@ describe("DocsCrawler", () => { }; } - describe("GitHub Crawler", () => { + describe.skip("GitHub Crawler", () => { const repoUrl = "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index add0b983b..852638d1c 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -5,7 +5,6 @@ import { CompiledMessagesResult, MessageContent, MessagePart, - PruningStatus, Tool, } from "../index.js"; import { autodetectTemplateType } from "./autodetect.js"; @@ -363,9 +362,6 @@ function getTokenCountingBufferSafety(contextLength: number) { } const MIN_RESPONSE_TOKENS = 1000; -function getMinResponseTokens(maxTokens: number) { - return Math.min(MIN_RESPONSE_TOKENS, maxTokens); -} function pruneRawPromptFromTop( modelName: string, @@ -425,6 +421,8 @@ function compileChatMessages({ supportsImages: boolean; tools?: Tool[]; }): CompiledMessagesResult { + let didPrune = false; + let msgsCopy: ChatMessage[] = msgs.map((m) => ({ ...m })); // If images not supported, convert MessagePart[] to string @@ -446,22 +444,15 @@ function compileChatMessages({ msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy); - while (msgsCopy.length > 1) { - if (isUserOrToolMsg(msgsCopy.at(-1))) { - break; - } - msgsCopy.pop(); + // Extract the tool sequence from the end of the message array + const toolSequence = extractToolSequence(msgsCopy); + + // Count tokens for all messages in the tool sequence + let lastMessagesTokens = 0; + for (const msg of toolSequence) { + lastMessagesTokens += countChatMessageTokens(modelName, msg); } - // // Extract the tool sequence from the end of the message array - // const toolSequence = extractToolSequence(msgsCopy); - - // // Count tokens for all messages in the tool sequence - // let lastMessagesTokens = 0; - // for (const msg of toolSequence) { - // lastMessagesTokens += countChatMessageTokens(modelName, msg); - // } - // System message let systemMsgTokens = 0; if (systemMsg) { @@ -475,7 +466,7 @@ function compileChatMessages({ } const countingSafetyBuffer = getTokenCountingBufferSafety(contextLength); - const minOutputTokens = getMinResponseTokens(maxTokens); + const minOutputTokens = Math.min(MIN_RESPONSE_TOKENS, maxTokens); let inputTokensAvailable = contextLength; @@ -486,19 +477,19 @@ function compileChatMessages({ // Non-negotiable messages inputTokensAvailable -= toolTokens; inputTokensAvailable -= systemMsgTokens; - // inputTokensAvailable -= lastMessagesTokens; + 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} - - max output tokens: ${maxTokens}`, + 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} + - max output tokens: ${maxTokens}`, ); } @@ -513,12 +504,10 @@ function compileChatMessages({ }; }); - let pruningStatus: PruningStatus = "not-pruned"; - while (historyWithTokens.length > 0 && currentTotal > inputTokensAvailable) { const message = historyWithTokens.shift()!; currentTotal -= message.tokens; - pruningStatus = "pruned"; + didPrune = true; // At this point make sure no latent tool response without corresponding call while (historyWithTokens[0]?.role === "tool") { @@ -527,18 +516,24 @@ function compileChatMessages({ } } - if (historyWithTokens.length === 0) { - pruningStatus = "deleted-last-input"; - } - // Now reassemble const reassembled: ChatMessage[] = []; if (systemMsg) { reassembled.push(systemMsg); } reassembled.push(...historyWithTokens.map(({ tokens, ...rest }) => rest)); + reassembled.push(...toolSequence); - return { compiledChatMessages: reassembled, pruningStatus }; + const inputTokens = + currentTotal + systemMsgTokens + toolTokens + lastMessagesTokens; + const availableTokens = + contextLength - countingSafetyBuffer - minOutputTokens; + const contextPercentage = inputTokens / availableTokens; + return { + compiledChatMessages: reassembled, + didPrune, + contextPercentage, + }; } export { diff --git a/core/llm/index.ts b/core/llm/index.ts index 9a727d1a4..0df366bbf 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -28,6 +28,7 @@ import { RequestOptions, TabAutocompleteOptions, TemplateType, + Usage, } from "../index.js"; import mergeJson from "../util/merge.js"; import { renderChatMessage } from "../util/messageContent.js"; @@ -186,6 +187,9 @@ export abstract class BaseLLM implements ILLM { maxEmbeddingChunkSize: number; maxEmbeddingBatchSize: number; + //URI to local block defining this LLM + sourceFile?: string; + private _llmOptions: LLMOptions; protected openaiAdapter?: BaseLlmApi; @@ -289,6 +293,7 @@ export abstract class BaseLLM implements ILLM { this.embeddingId = `${this.constructor.name}::${this.model}::${this.maxEmbeddingChunkSize}`; this.autocompleteOptions = options.autocompleteOptions; + this.sourceFile = options.sourceFile; } getConfigurationStatus() { @@ -327,6 +332,7 @@ export abstract class BaseLLM implements ILLM { completion: string, thinking: string | undefined, interaction: ILLMInteractionLog | undefined, + usage: Usage | undefined, error?: any, ): InteractionStatus { let promptTokens = this.countTokens(prompt); @@ -368,6 +374,7 @@ export abstract class BaseLLM implements ILLM { promptTokens, generatedTokens, thinkingTokens, + usage, }); return "cancelled"; } else { @@ -379,6 +386,7 @@ export abstract class BaseLLM implements ILLM { promptTokens, generatedTokens, thinkingTokens, + usage, }); return "error"; } @@ -388,6 +396,7 @@ export abstract class BaseLLM implements ILLM { promptTokens, generatedTokens, thinkingTokens, + usage, }); return "success"; } @@ -574,6 +583,7 @@ export abstract class BaseLLM implements ILLM { prefix, suffix, options: completionOptions, + provider: this.providerName, }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, fimLog); @@ -622,6 +632,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, ); } catch (e) { status = this._logEnd( @@ -630,6 +641,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, e, ); throw e; @@ -641,6 +653,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, "cancel", ); } @@ -681,6 +694,7 @@ export abstract class BaseLLM implements ILLM { kind: "startComplete", prompt, options: completionOptions, + provider: this.providerName, }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -736,6 +750,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, ); } catch (e) { status = this._logEnd( @@ -744,6 +759,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, e, ); throw e; @@ -755,6 +771,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, "cancel", ); } @@ -796,6 +813,7 @@ export abstract class BaseLLM implements ILLM { kind: "startComplete", prompt: prompt, options: completionOptions, + provider: this.providerName, }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -829,6 +847,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, ); } catch (e) { status = this._logEnd( @@ -837,6 +856,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, e, ); throw e; @@ -848,6 +868,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + undefined, "cancel", ); } @@ -923,7 +944,7 @@ export abstract class BaseLLM implements ILLM { let messages = _messages; // If not precompiled, compile the chat messages - if (!messageOptions || messageOptions.precompiled === false) { + if (!messageOptions?.precompiled) { const { compiledChatMessages } = compileChatMessages({ modelName: completionOptions.model, msgs: _messages, @@ -944,6 +965,7 @@ export abstract class BaseLLM implements ILLM { kind: "startChat", messages, options: completionOptions, + provider: this.providerName, }); if (this.llmRequestHook) { this.llmRequestHook(completionOptions.model, prompt); @@ -952,6 +974,7 @@ export abstract class BaseLLM implements ILLM { let thinking = ""; let completion = ""; + let usage: Usage | undefined = undefined; try { if (this.templateMessages) { @@ -1018,6 +1041,11 @@ export abstract class BaseLLM implements ILLM { kind: "message", message: chunk, }); + + if (chunk.role === "assistant" && chunk.usage) { + usage = chunk.usage; + } + yield chunk; } } @@ -1028,6 +1056,7 @@ export abstract class BaseLLM implements ILLM { completion, thinking, interaction, + usage, ); } catch (e) { status = this._logEnd( @@ -1036,6 +1065,7 @@ export abstract class BaseLLM implements ILLM { completion, thinking, interaction, + usage, e, ); throw e; @@ -1047,6 +1077,7 @@ export abstract class BaseLLM implements ILLM { completion, undefined, interaction, + usage, "cancel", ); } diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index ff0f78c06..98a6f14f1 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -1,5 +1,10 @@ import { streamSse } from "@continuedev/fetch"; -import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; +import { + ChatMessage, + CompletionOptions, + LLMOptions, + Usage, +} from "../../index.js"; import { safeParseToolCallArgs } from "../../tools/parseArgs.js"; import { renderChatMessage, stripImages } from "../../util/messageContent.js"; import { BaseLLM } from "../index.js"; @@ -234,15 +239,49 @@ class Anthropic extends BaseLLM { if (options.stream === false) { const data = await response.json(); - yield { role: "assistant", content: data.content[0].text }; + const cost = data.usage + ? { + inputTokens: data.usage.input_tokens, + outputTokens: data.usage.output_tokens, + totalTokens: data.usage.input_tokens + data.usage.output_tokens, + } + : {}; + yield { + role: "assistant", + content: data.content[0].text, + ...(Object.keys(cost).length > 0 ? { cost } : {}), + }; return; } let lastToolUseId: string | undefined; let lastToolUseName: string | undefined; + let usage: Usage = { + promptTokens: 0, + completionTokens: 0, + promptTokensDetails: { + cachedTokens: 0, + cacheWriteTokens: 0, + }, + }; + for await (const value of streamSse(response)) { // https://docs.anthropic.com/en/api/messages-streaming#event-types switch (value.type) { + case "message_start": + // Capture initial usage information + usage.promptTokens = value.message.usage.input_tokens; + usage.promptTokensDetails!.cachedTokens = + value.message.usage.cache_read_input_tokens; + usage.promptTokensDetails!.cacheWriteTokens = + value.message.usage.cache_creation_input_tokens; + break; + case "message_delta": + // Update usage information during streaming + if (value.usage) { + usage.completionTokens = value.usage.output_tokens; + } + break; case "content_block_start": if (value.content_block.type === "tool_use") { lastToolUseId = value.content_block.id; @@ -250,7 +289,6 @@ class Anthropic extends BaseLLM { } // handle redacted thinking if (value.content_block.type === "redacted_thinking") { - console.log("redacted thinking", value.content_block.data); yield { role: "thinking", content: "", @@ -303,6 +341,12 @@ class Anthropic extends BaseLLM { break; } } + + yield { + role: "assistant", + content: "", + usage, + }; } } diff --git a/core/llm/llms/Anthropic.vitest.ts b/core/llm/llms/Anthropic.vitest.ts new file mode 100644 index 000000000..5c623b05e --- /dev/null +++ b/core/llm/llms/Anthropic.vitest.ts @@ -0,0 +1,495 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../index.js"; +import Anthropic from "./Anthropic.js"; + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +describe("Anthropic", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("streamChat should send a valid request", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "hello" }], + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + test("chat should send a valid request", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "hello" }], + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + test("streamComplete should send a valid request", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "streamComplete", + params: ["Complete this: Hello", new AbortController().signal], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "Complete this: Hello" }], + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + test("complete should send a valid request", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "complete", + params: ["Complete this: Hello", new AbortController().signal], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "Complete this: Hello" }], + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": " world!"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + describe("Different configurations", () => { + test("should handle system message", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "streamChat", + params: [ + [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Hello!" }, + ], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "Hello!" }], + }, + ], + system: "You are a helpful assistant.", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello! How can I help you today?"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + test("should handle tool calls", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + const tools = [ + { + type: "function" as const, + function: { + name: "get_weather", + description: "Get the current weather", + parameters: { + type: "object", + properties: { + location: { type: "string" }, + }, + required: ["location"], + }, + }, + }, + ]; + + await runLlmTest({ + llm: anthropic, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "What's the weather in New York?" }], + new AbortController().signal, + { tools }, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 8192, + stream: true, + messages: [ + { + role: "user", + content: [ + { type: "text", text: "What's the weather in New York?" }, + ], + }, + ], + tools: [ + { + name: "get_weather", + description: "Get the current weather", + input_schema: { + type: "object", + properties: { + location: { type: "string" }, + }, + required: ["location"], + }, + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_start", "content_block": {"type": "tool_use", "id": "toolu_123", "name": "get_weather"}}', + '{"type": "content_block_delta", "delta": {"type": "input_json_delta", "partial_json": "{\\"location\\": \\"New York\\""}}', + '{"type": "content_block_stop"}', + ], + }); + }); + + test("should handle custom max tokens", async () => { + const anthropic = new Anthropic({ + apiKey: "test-api-key", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await runLlmTest({ + llm: anthropic, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + { maxTokens: 1000 }, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "anthropic-version": "2023-06-01", + "x-api-key": "test-api-key", + }, + body: { + model: "claude-3-5-sonnet-latest", + max_tokens: 1000, + stream: true, + messages: [ + { + role: "user", + content: [{ type: "text", text: "hello" }], + }, + ], + system: "", + }, + }, + mockStream: [ + '{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hello!"}}', + '{"type": "content_block_stop"}', + ], + }); + }); + }); + + describe("Error handling", () => { + test("should throw error when API key is missing", async () => { + const anthropic = new Anthropic({ + apiKey: "", + model: "claude-3-5-sonnet-latest", + apiBase: "https://api.anthropic.com/v1/", + }); + + await expect( + runLlmTest({ + llm: anthropic, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.anthropic.com/v1/messages", + method: "POST", + }, + }), + ).rejects.toThrow( + "Request not sent. You have an Anthropic model configured in your config.json, but the API key is not set.", + ); + }); + }); +}); diff --git a/core/llm/llms/Docker.ts b/core/llm/llms/Docker.ts index 3860a9b9e..a79a9b368 100644 --- a/core/llm/llms/Docker.ts +++ b/core/llm/llms/Docker.ts @@ -17,7 +17,7 @@ import OpenAI from "./OpenAI.js"; class Docker extends OpenAI implements ModelInstaller { static providerName = "docker"; static defaultOptions: Partial = { - apiBase: "http://localhost:12434/engines/v1", + apiBase: "http://localhost:12434/engines/v1/", model: "gemma3-4B-F4", // Default model }; diff --git a/core/llm/llms/Fireworks.ts b/core/llm/llms/Fireworks.ts index 558cc77a9..9008eedb1 100644 --- a/core/llm/llms/Fireworks.ts +++ b/core/llm/llms/Fireworks.ts @@ -5,7 +5,7 @@ import OpenAI from "./OpenAI.js"; class Fireworks extends OpenAI { static providerName = "fireworks"; static defaultOptions: Partial = { - apiBase: "https://api.fireworks.ai/inference/v1", + apiBase: "https://api.fireworks.ai/inference/v1/", }; private static modelConversion: { [key: string]: string } = { diff --git a/core/llm/llms/Fireworks.vitest.ts b/core/llm/llms/Fireworks.vitest.ts new file mode 100644 index 000000000..716aa0b03 --- /dev/null +++ b/core/llm/llms/Fireworks.vitest.ts @@ -0,0 +1,12 @@ +import Fireworks from "./Fireworks.js"; +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; + +createOpenAISubclassTests(Fireworks, { + providerName: "fireworks", + defaultApiBase: "https://api.fireworks.ai/inference/v1/", + modelConversions: { + "starcoder-7b": "accounts/fireworks/models/starcoder-7b", + }, + modelConversionContent: + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", +}); diff --git a/core/llm/llms/Groq.vitest.ts b/core/llm/llms/Groq.vitest.ts new file mode 100644 index 000000000..a5a0ad1a3 --- /dev/null +++ b/core/llm/llms/Groq.vitest.ts @@ -0,0 +1,12 @@ +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; +import Groq from "./Groq.js"; + +createOpenAISubclassTests(Groq, { + providerName: "groq", + defaultApiBase: "https://api.groq.com/openai/v1/", + modelConversions: { + "mistral-8x7b": "mixtral-8x7b-32768", + "llama3-8b": "llama3-8b-8192", + "llama3-70b": "llama3-70b-8192", + }, +}); diff --git a/core/llm/llms/Kindo.ts b/core/llm/llms/Kindo.ts index 88df3c2fd..e728a0035 100644 --- a/core/llm/llms/Kindo.ts +++ b/core/llm/llms/Kindo.ts @@ -5,7 +5,7 @@ import OpenAI from "./OpenAI"; class Kindo extends OpenAI { static providerName = "kindo"; static defaultOptions: Partial = { - apiBase: "https://llm.kindo.ai/v1", + apiBase: "https://llm.kindo.ai/v1/", requestOptions: { headers: { "kindo-token-transaction-type": "CONTINUE", diff --git a/core/llm/llms/NCompass.ts b/core/llm/llms/NCompass.ts index 87ee69732..aaed5e1ad 100644 --- a/core/llm/llms/NCompass.ts +++ b/core/llm/llms/NCompass.ts @@ -6,9 +6,9 @@ import OpenAI from "./OpenAI.js"; class NCompass extends OpenAI { static providerName = "ncompass"; static defaultOptions: Partial = { - apiBase: "https://api.ncompass.tech/v1", + apiBase: "https://api.ncompass.tech/v1/", }; - static embeddingsApiEndpoint: "https://api.gcp.ncompass.tech/v1/embeddings"; + static embeddingsApiEndpoint = "https://api.gcp.ncompass.tech/v1/embeddings"; private static modelConversion: { [key: string]: string } = { "qwen2.5-coder-7b": "Qwen/Qwen2.5-Coder-7B-Instruct", diff --git a/core/llm/llms/OpenAI-compatible-core.vitest.ts b/core/llm/llms/OpenAI-compatible-core.vitest.ts new file mode 100644 index 000000000..23d076d07 --- /dev/null +++ b/core/llm/llms/OpenAI-compatible-core.vitest.ts @@ -0,0 +1,294 @@ +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; + +// Import core OpenAI-compatible providers +import OpenAI from "./OpenAI.js"; +import Groq from "./Groq.js"; +import Fireworks from "./Fireworks.js"; +import Together from "./Together.js"; +import Deepseek from "./Deepseek.js"; +import OpenRouter from "./OpenRouter.js"; +import xAI from "./xAI.js"; +import Mistral from "./Mistral.js"; +import LMStudio from "./LMStudio.js"; +import Cerebras from "./Cerebras.js"; +import DeepInfra from "./DeepInfra.js"; +import Nvidia from "./Nvidia.js"; + +// Base OpenAI tests +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../index.js"; + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + // Disable OpenAI adapter to use our custom fetch mock + (llm as any).useOpenAIAdapterFor = []; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +describe("OpenAI", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("streamChat should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); +}); + +// Core OpenAI-compatible providers +createOpenAISubclassTests(Groq, { + providerName: "groq", + defaultApiBase: "https://api.groq.com/openai/v1/", + modelConversions: { + "mistral-8x7b": "mistral-8x7b", + "llama3-8b": "llama3-8b-8192", + }, + modelConversionContent: "[INST] hello [/INST]", + modelConversionMaxTokens: 4096, +}); + +createOpenAISubclassTests(Fireworks, { + providerName: "fireworks", + defaultApiBase: "https://api.fireworks.ai/inference/v1/", + modelConversions: { + "starcoder-7b": "starcoder-7b", + }, + modelConversionContent: + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", +}); + +createOpenAISubclassTests(Together, { + providerName: "together", + defaultApiBase: "https://api.together.xyz/v1/", + modelConversions: { + "codellama-7b": "codellama-7b", + "llama3-8b": "meta-llama/Llama-3-8b-chat-hf", + }, + modelConversionContent: "hello", + customStreamCompleteEndpoint: "completions", +}); + +createOpenAISubclassTests(Deepseek, { + providerName: "deepseek", + defaultApiBase: "https://api.deepseek.com/", +}); + +createOpenAISubclassTests(OpenRouter, { + providerName: "openrouter", + defaultApiBase: "https://openrouter.ai/api/v1/", +}); + +createOpenAISubclassTests(xAI, { + providerName: "xAI", + defaultApiBase: "https://api.x.ai/v1/", + modelConversions: { + "grok-beta": "grok-beta", + }, + modelConversionContent: "hello", +}); + +createOpenAISubclassTests(Mistral, { + providerName: "mistral", + defaultApiBase: "https://api.mistral.ai/v1/", + modelConversions: { + "mistral-7b": "mistral-7b", + "mistral-8x7b": "open-mixtral-8x7b", + }, + modelConversionContent: "hello", +}); + +createOpenAISubclassTests(LMStudio, { + providerName: "lmstudio", + defaultApiBase: "http://localhost:1234/v1/", +}); + +createOpenAISubclassTests(Cerebras, { + providerName: "cerebras", + defaultApiBase: "https://api.cerebras.ai/v1/", + modelConversions: { + "llama3.1-8b": "llama3.1-8b", + "llama3.1-70b": "llama3.1-70b", + }, + modelConversionContent: + "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n", +}); + +createOpenAISubclassTests(DeepInfra, { + providerName: "deepinfra", + defaultApiBase: "https://api.deepinfra.com/v1/openai/", + customEmbeddingsUrl: + "https://api.deepinfra.com/v1/inference/text-embedding-ada-002", + customEmbeddingsHeaders: { + Authorization: "bearer test-api-key", + }, + customEmbeddingsBody: { + inputs: ["Hello", "World"], + }, +}); + +createOpenAISubclassTests(Nvidia, { + providerName: "nvidia", + defaultApiBase: "https://integrate.api.nvidia.com/v1/", + customEmbeddingsHeaders: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + }, + customEmbeddingsBody: { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + input_type: "passage", + truncate: "END", + }, +}); diff --git a/core/llm/llms/OpenAI-compatible.vitest.ts b/core/llm/llms/OpenAI-compatible.vitest.ts new file mode 100644 index 000000000..2ec8de109 --- /dev/null +++ b/core/llm/llms/OpenAI-compatible.vitest.ts @@ -0,0 +1,453 @@ +import { createOpenAISubclassTests } from "./test-utils/openai-test-utils.js"; + +// Import all OpenAI-compatible providers +import OpenAI from "./OpenAI.js"; +import Groq from "./Groq.js"; +import Fireworks from "./Fireworks.js"; +import Together from "./Together.js"; +import Deepseek from "./Deepseek.js"; +import OpenRouter from "./OpenRouter.js"; +import xAI from "./xAI.js"; +import Mistral from "./Mistral.js"; +import LMStudio from "./LMStudio.js"; +import Cerebras from "./Cerebras.js"; +import DeepInfra from "./DeepInfra.js"; +import Nvidia from "./Nvidia.js"; +import SambaNova from "./SambaNova.js"; +import Scaleway from "./Scaleway.js"; +import Venice from "./Venice.js"; +import Moonshot from "./Moonshot.js"; +import Novita from "./Novita.js"; +import SiliconFlow from "./SiliconFlow.js"; +import Kindo from "./Kindo.js"; +import Azure from "./Azure.js"; +import Inception from "./Inception.js"; +import Docker from "./Docker.js"; +import Voyage from "./Voyage.js"; +import Vllm from "./Vllm.js"; +import TextGenWebUI from "./TextGenWebUI.js"; +// import Relace from "./Relace.js"; // Skip - causing import issues +import FunctionNetwork from "./FunctionNetwork.js"; +import NCompass from "./NCompass.js"; +import LlamaStack from "./LlamaStack.js"; +import Nebius from "./Nebius.js"; +import OVHcloud from "./OVHcloud.js"; + +// Base OpenAI tests +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../index.js"; + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + // Disable OpenAI adapter to use our custom fetch mock + (llm as any).useOpenAIAdapterFor = []; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +describe("OpenAI", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("streamChat should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("should handle embeddings", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "text-embedding-ada-002", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "embed", + params: [["Hello", "World"]], + expectedRequest: { + url: "https://api.openai.com/v1/embeddings", + method: "POST", + headers: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + "api-key": "test-api-key", + }, + body: { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + }, + }, + mockResponse: { + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], + }, + }); + }); +}); + +// OpenAI-compatible providers +createOpenAISubclassTests(Groq, { + providerName: "groq", + defaultApiBase: "https://api.groq.com/openai/v1/", + modelConversions: { + "mistral-8x7b": "mixtral-8x7b-32768", + "llama3-8b": "llama3-8b-8192", + "llama3-70b": "llama3-70b-8192", + }, + modelConversionContent: "[INST] hello [/INST]", + modelConversionMaxTokens: 4096, +}); + +createOpenAISubclassTests(Fireworks, { + providerName: "fireworks", + defaultApiBase: "https://api.fireworks.ai/inference/v1/", + modelConversions: { + "starcoder-7b": "accounts/fireworks/models/starcoder-7b", + }, + modelConversionContent: + "<|im_start|>user\nhello<|im_end|>\n<|im_start|>assistant\n", +}); + +createOpenAISubclassTests(Together, { + providerName: "together", + defaultApiBase: "https://api.together.xyz/v1/", + modelConversions: { + "codellama-7b": "codellama-7b", + "llama3-8b": "meta-llama/Llama-3-8b-chat-hf", + "mistral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1", + }, + modelConversionContent: "hello", + customStreamCompleteEndpoint: "completions", +}); + +createOpenAISubclassTests(Deepseek, { + providerName: "deepseek", + defaultApiBase: "https://api.deepseek.com/", +}); + +createOpenAISubclassTests(OpenRouter, { + providerName: "openrouter", + defaultApiBase: "https://openrouter.ai/api/v1/", +}); + +createOpenAISubclassTests(xAI, { + providerName: "xAI", + defaultApiBase: "https://api.x.ai/v1/", + modelConversions: { + "grok-beta": "grok-beta", + }, + modelConversionContent: "hello", +}); + +createOpenAISubclassTests(Mistral, { + providerName: "mistral", + defaultApiBase: "https://api.mistral.ai/v1/", + modelConversions: { + "mistral-7b": "mistral-7b", + "mistral-8x7b": "open-mixtral-8x7b", + }, + modelConversionContent: "hello", +}); + +createOpenAISubclassTests(LMStudio, { + providerName: "lmstudio", + defaultApiBase: "http://localhost:1234/v1/", +}); + +createOpenAISubclassTests(Cerebras, { + providerName: "cerebras", + defaultApiBase: "https://api.cerebras.ai/v1/", + modelConversions: { + "llama3.1-8b": "llama3.1-8b", + "llama3.1-70b": "llama3.1-70b", + }, + modelConversionContent: + "<|start_header_id|>user<|end_header_id|>\nhello<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n", +}); + +createOpenAISubclassTests(DeepInfra, { + providerName: "deepinfra", + defaultApiBase: "https://api.deepinfra.com/v1/openai/", + customEmbeddingsUrl: + "https://api.deepinfra.com/v1/inference/text-embedding-ada-002", + customEmbeddingsHeaders: { + Authorization: "bearer test-api-key", + }, + customEmbeddingsBody: { + inputs: ["Hello", "World"], + }, +}); + +createOpenAISubclassTests(Nvidia, { + providerName: "nvidia", + defaultApiBase: "https://integrate.api.nvidia.com/v1/", + customEmbeddingsHeaders: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + }, + customEmbeddingsBody: { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + input_type: "passage", + truncate: "END", + }, +}); + +createOpenAISubclassTests(SambaNova, { + providerName: "sambanova", + defaultApiBase: "https://api.sambanova.ai/v1/", +}); + +createOpenAISubclassTests(Scaleway, { + providerName: "scaleway", + defaultApiBase: "https://api.scaleway.ai/v1/", +}); + +createOpenAISubclassTests(Venice, { + providerName: "venice", + defaultApiBase: "https://api.venice.ai/api/v1/", +}); + +createOpenAISubclassTests(Moonshot, { + providerName: "moonshot", + defaultApiBase: "https://api.moonshot.cn/v1/", +}); + +createOpenAISubclassTests(Novita, { + providerName: "novita", + defaultApiBase: "https://api.novita.ai/v3/openai/", + customStreamCompleteEndpoint: "completions", +}); + +createOpenAISubclassTests(SiliconFlow, { + providerName: "siliconflow", + defaultApiBase: "https://api.siliconflow.cn/v1/", +}); + +createOpenAISubclassTests(Kindo, { + providerName: "kindo", + defaultApiBase: "https://llm.kindo.ai/v1/", +}); + +createOpenAISubclassTests(Azure, { + providerName: "azure", +}); + +createOpenAISubclassTests(Inception, { + providerName: "inception", + defaultApiBase: "https://api.inceptionlabs.ai/v1/", + customBodyOptions: { + temperature: 0.0, + presence_penalty: 1.5, + stop: ["<|endoftext|>"], + }, +}); + +createOpenAISubclassTests(Docker, { + providerName: "docker", + defaultApiBase: "http://localhost:12434/engines/v1/", +}); + +createOpenAISubclassTests(Voyage, { + providerName: "voyage", + defaultApiBase: "https://api.voyageai.com/v1/", +}); + +createOpenAISubclassTests(Vllm, { + providerName: "vllm", + defaultApiBase: "https://api.openai.com/v1/", +}); + +createOpenAISubclassTests(TextGenWebUI, { + providerName: "text-gen-webui", + defaultApiBase: "http://localhost:5000/v1/", +}); + +createOpenAISubclassTests(FunctionNetwork, { + providerName: "function-network", + defaultApiBase: "https://api.function.network/v1/", + customEmbeddingsHeaders: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + }, +}); + +createOpenAISubclassTests(NCompass, { + providerName: "ncompass", + defaultApiBase: "https://api.ncompass.tech/v1/", + customEmbeddingsUrl: "https://api.gcp.ncompass.tech/v1/embeddings", + customEmbeddingsHeaders: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + }, + customEmbeddingsBody: { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + }, +}); + +createOpenAISubclassTests(LlamaStack, { + providerName: "llamastack", + defaultApiBase: "http://localhost:8321/v1/openai/v1/", +}); + +createOpenAISubclassTests(Nebius, { + providerName: "nebius", + defaultApiBase: "https://api.studio.nebius.ai/v1/", +}); + +createOpenAISubclassTests(OVHcloud, { + providerName: "ovhcloud", + defaultApiBase: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/", +}); diff --git a/core/llm/llms/OpenAI.vitest.ts b/core/llm/llms/OpenAI.vitest.ts new file mode 100644 index 000000000..d48bbd403 --- /dev/null +++ b/core/llm/llms/OpenAI.vitest.ts @@ -0,0 +1,427 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../index.js"; +import OpenAI from "./OpenAI.js"; + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + // Disable OpenAI adapter to use our custom fetch mock + (llm as any).useOpenAIAdapterFor = []; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +describe("OpenAI", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("streamChat should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("chat should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("streamComplete should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "streamComplete", + params: ["Hello", new AbortController().signal], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "Hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("complete should send a valid request", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "complete", + params: ["Hello", new AbortController().signal], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "Hello" }], + stream: true, + max_tokens: 2048, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("should handle O1 models correctly", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "o1-preview", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + { maxTokens: 100 }, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "o1-preview", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_completion_tokens: 100, + }, + }, + mockStream: [{ choices: [{ delta: { content: "Hello world" } }] }], + }); + }); + + test("should handle tools", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + const tools = [ + { + type: "function" as const, + function: { + name: "test_function", + description: "Test function", + parameters: { type: "object", properties: {} }, + }, + }, + ]; + + await runLlmTest({ + llm: openai, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + { tools }, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + tools: [ + { + type: "function", + function: { + name: "test_function", + description: "Test function", + parameters: { type: "object", properties: {} }, + }, + }, + ], + }, + }, + mockStream: [{ choices: [{ delta: { content: "I'll help you" } }] }], + }); + }); + + test("should handle custom max tokens", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + { maxTokens: 500 }, + ], + expectedRequest: { + url: "https://api.openai.com/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 500, + }, + }, + mockStream: [{ choices: [{ delta: { content: "Hello" } }] }], + }); + }); + + test("should handle embeddings", async () => { + const openai = new OpenAI({ + apiKey: "test-api-key", + model: "text-embedding-ada-002", + apiBase: "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: openai, + methodToTest: "embed", + params: [["Hello", "World"]], + expectedRequest: { + url: "https://api.openai.com/v1/embeddings", + method: "POST", + headers: { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + "api-key": "test-api-key", + }, + body: { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + }, + }, + mockResponse: { + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], + }, + }); + }); +}); diff --git a/core/llm/llms/Venice.ts b/core/llm/llms/Venice.ts index 174b4a3de..537338d4e 100644 --- a/core/llm/llms/Venice.ts +++ b/core/llm/llms/Venice.ts @@ -6,7 +6,7 @@ import OpenAI from "./OpenAI"; class Venice extends OpenAI { static providerName = "venice"; static defaultOptions: Partial = { - apiBase: "https://api.venice.ai/api/v1", + apiBase: "https://api.venice.ai/api/v1/", }; protected _convertArgs( diff --git a/core/llm/llms/llmTestHarness.ts b/core/llm/llms/llmTestHarness.ts new file mode 100644 index 000000000..0e309ed53 --- /dev/null +++ b/core/llm/llms/llmTestHarness.ts @@ -0,0 +1,93 @@ +import { expect, jest } from "@jest/globals"; +import { ILLM } from "../../index.js"; + +export interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: string[]; // array of string chunks for SSE +} + +export async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = jest.fn(); + + if (mockStream) { + const encoder = new TextEncoder(); + let streamIndex = 0; + mockFetch.mockResolvedValue( + new Response( + new ReadableStream({ + start(controller) { + mockStream.forEach((chunk) => { + controller.enqueue(new TextEncoder().encode(chunk)); + }); + controller.close(); + }, + }), + { + headers: { + "Content-Type": "text/event-stream", + }, + }, + ), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { + "Content-Type": "application/json", + }, + }), + ); + } + + // @ts-ignore + llm.fetch = mockFetch; + + // @ts-ignore + if (typeof llm[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + // @ts-ignore + const result = await llm[methodToTest](...params); + + if (mockStream) { + // Consume the stream to ensure it's processed correctly + for await (const _ of result) { + } + } + + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual(expectedRequest.headers); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} diff --git a/core/llm/llms/stubs/ContinueProxy.vitest.ts b/core/llm/llms/stubs/ContinueProxy.vitest.ts new file mode 100644 index 000000000..20bed0ec1 --- /dev/null +++ b/core/llm/llms/stubs/ContinueProxy.vitest.ts @@ -0,0 +1,758 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../../index.js"; +import ContinueProxy from "./ContinueProxy.js"; + +vi.mock("@continuedev/config-yaml", async (importOriginal) => { + const mod = (await importOriginal()) as any; + return { + ...mod, + parseProxyModelName: vi.fn(() => ({ + provider: "test-provider", + model: "test-model", + ownerSlug: "test-owner", + packageSlug: "test-package", + })), + }; +}); + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +describe("ContinueProxy", () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("rerank should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "rerank", + params: [ + "test query", + [{ content: "document1" }, { content: "document2" }], + ], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/rerank", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + }, + body: { + query: "test query", + documents: ["document1", "document2"], + model: "test-model", + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [ + { index: 0, relevance_score: 0.9 }, + { index: 1, relevance_score: 0.1 }, + ], + }, + }); + }); + + test("streamChat should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "streamChat", + params: [[{ role: "user", content: "hello" }]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: [{ role: "user", content: "hello" }], + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": "response"}}]}', + "[DONE]", + ], + }); + }); + + test("chat should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "chat", + params: [[{ role: "user", content: "hello" }]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: [{ role: "user", content: "hello" }], + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": "Hello! How can I help you today?"}}]}', + "[DONE]", + ], + }); + }); + + test("streamComplete should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "streamComplete", + params: ["Complete this: Hello"], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: [{ role: "user", content: "Complete this: Hello" }], + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": " world!"}}]}', + "[DONE]", + ], + }); + }); + + test("complete should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "complete", + params: ["Complete this: Hello"], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: [{ role: "user", content: "Complete this: Hello" }], + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": " world!"}}]}', + "[DONE]", + ], + }); + }); + + test("streamFim should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "streamFim", + params: ["function test() {\n ", "\n}"], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/fim/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "x-api-key": "test-api-key", + Authorization: "Bearer test-api-key", + }, + body: { + model: "test-model", + prompt: "function test() {\n ", + suffix: "\n}", + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": "console.log("Hello");"}}]}', + "[DONE]", + ], + }); + }); + + test("embed should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "embed", + params: [["text to embed", "another text"]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + input: ["text to embed", "another text"], + model: "test-model", + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [{ embedding: [0.1, 0.2, 0.3] }, { embedding: [0.4, 0.5, 0.6] }], + }, + }); + }); + + test("listModels should send a valid request", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "listModels", + params: [], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/models", + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + }, + mockResponse: { + data: [{ id: "gpt-4" }, { id: "gpt-3.5-turbo" }], + }, + }); + }); + + describe("Different provider configurations", () => { + test("should handle on-prem proxy URL", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + onPremProxyUrl: "https://my-proxy.company.com/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "rerank", + params: [ + "test query", + [{ content: "document1" }, { content: "document2" }], + ], + expectedRequest: { + url: "https://my-proxy.company.com/model-proxy/v1/rerank", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + }, + body: { + query: "test query", + documents: ["document1", "document2"], + model: "test-model", + continueProperties: { + apiBase: undefined, + apiKeyLocation: undefined, + env: undefined, + envSecretLocations: undefined, + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [ + { index: 0, relevance_score: 0.9 }, + { index: 1, relevance_score: 0.1 }, + ], + }, + }); + }); + + test("should handle environment variables", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + env: { + CUSTOM_VAR: "custom-value", + ANOTHER_VAR: "another-value", + }, + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "streamChat", + params: [[{ role: "user", content: "hello" }]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: [{ role: "user", content: "hello" }], + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + env: { + CUSTOM_VAR: "custom-value", + ANOTHER_VAR: "another-value", + }, + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": "response"}}]}', + "[DONE]", + ], + }); + }); + + test("should handle API key location", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + apiKeyLocation: "env:OPENAI_API_KEY", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "embed", + params: [["test text"]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + input: ["test text"], + model: "test-model", + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + apiKeyLocation: "env:OPENAI_API_KEY", + env: undefined, + envSecretLocations: undefined, + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [{ embedding: [0.1, 0.2, 0.3] }], + }, + }); + }); + + test("should handle env secret locations", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + envSecretLocations: { + AZURE_API_KEY: "env:AZURE_API_KEY", + AZURE_ENDPOINT: "env:AZURE_ENDPOINT", + }, + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "streamFim", + params: ["const x = ", ";"], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/fim/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Accept: "application/json", + "x-api-key": "test-api-key", + Authorization: "Bearer test-api-key", + }, + body: { + model: "test-model", + prompt: "const x = ", + suffix: ";", + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + envSecretLocations: { + AZURE_API_KEY: "env:AZURE_API_KEY", + AZURE_ENDPOINT: "env:AZURE_ENDPOINT", + }, + orgScopeId: null, + }, + }, + }, + mockStream: ['{"choices": [{"delta": {"content": "42"}}]}', "[DONE]"], + }); + }); + + test("should handle organization scope ID", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: "org_12345", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "listModels", + params: [], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/models", + method: "GET", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + }, + mockResponse: { + data: [{ id: "gpt-4" }], + }, + }); + }); + }); + + describe("Edge cases", () => { + test("should handle empty chunks array for rerank", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "rerank", + params: ["test query", []], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/rerank", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + }, + body: { + query: "test query", + documents: [], + model: "test-model", + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + apiKeyLocation: undefined, + env: undefined, + envSecretLocations: undefined, + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [], + }, + }); + }); + + test("should handle complex chat messages", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + const complexMessages = [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "Hello!" }, + { role: "assistant", content: "Hi there! How can I help you today?" }, + { role: "user", content: "What's the weather like?" }, + ]; + + await runLlmTest({ + llm: proxy, + methodToTest: "streamChat", + params: [complexMessages], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/chat/completions", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + "x-continue-unique-id": "NOT_UNIQUE", + }, + body: { + model: "test-model", + messages: complexMessages, + max_tokens: 4096, + stream: true, + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + orgScopeId: null, + }, + }, + }, + mockStream: [ + '{"choices": [{"delta": {"content": "I don\'t have access to current weather data."}}]}', + "[DONE]", + ], + }); + }); + + test("should handle single embedding chunk", async () => { + const proxy = new ContinueProxy({ + apiKey: "test-api-key", + model: "test-model", + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + }); + + await runLlmTest({ + llm: proxy, + methodToTest: "embed", + params: [["single text"]], + expectedRequest: { + url: "https://proxy.continue.dev/model-proxy/v1/embeddings", + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + input: ["single text"], + model: "test-model", + continueProperties: { + apiBase: "https://proxy.continue.dev/model-proxy/v1/", + apiKeyLocation: undefined, + env: undefined, + envSecretLocations: undefined, + orgScopeId: null, + }, + }, + }, + mockResponse: { + data: [{ embedding: [0.1, 0.2, 0.3] }], + }, + }); + }); + }); +}); diff --git a/core/llm/llms/test-utils/openai-test-utils.ts b/core/llm/llms/test-utils/openai-test-utils.ts new file mode 100644 index 000000000..4c9c3fbdb --- /dev/null +++ b/core/llm/llms/test-utils/openai-test-utils.ts @@ -0,0 +1,375 @@ +import { afterEach, describe, expect, test, vi } from "vitest"; +import { ILLM } from "../../../index.js"; +import OpenAI from "../OpenAI.js"; + +interface LlmTestCase { + llm: ILLM; + methodToTest: keyof ILLM; + params: any[]; + expectedRequest: { + url: string; + method: string; + headers?: Record; + body?: Record; + }; + mockResponse?: any; + mockStream?: any[]; +} + +function createMockStream(mockStream: any[]) { + const encoder = new TextEncoder(); + return new ReadableStream({ + start(controller) { + for (const chunk of mockStream) { + controller.enqueue( + encoder.encode( + `data: ${ + typeof chunk === "string" ? chunk : JSON.stringify(chunk) + }\n\n`, + ), + ); + } + controller.close(); + }, + }); +} + +function setupMockFetch(mockResponse?: any, mockStream?: any[]) { + const mockFetch = vi.fn(); + + if (mockStream) { + const stream = createMockStream(mockStream); + mockFetch.mockResolvedValue( + new Response(stream, { + headers: { + "Content-Type": "text/event-stream", + }, + }), + ); + } else { + mockFetch.mockResolvedValue( + new Response(JSON.stringify(mockResponse), { + headers: { "Content-Type": "application/json" }, + }), + ); + } + + return mockFetch; +} + +function setupReadableStreamPolyfill() { + // This can be removed if https://github.com/nodejs/undici/issues/2888 is resolved + // @ts-ignore + const originalFrom = ReadableStream.from; + // @ts-ignore + ReadableStream.from = (body) => { + if (body?.source) { + return body; + } + return originalFrom(body); + }; +} + +async function executeLlmMethod( + llm: ILLM, + methodToTest: keyof ILLM, + params: any[], +) { + if (typeof (llm as any)[methodToTest] !== "function") { + throw new Error( + `Method ${String(methodToTest)} does not exist on the LLM instance.`, + ); + } + + const result = await (llm as any)[methodToTest](...params); + if (result?.next) { + for await (const _ of result) { + } + } +} + +function assertFetchCall(mockFetch: any, expectedRequest: any) { + expect(mockFetch).toHaveBeenCalledTimes(1); + const [url, options] = mockFetch.mock.calls[0]; + + expect(url.toString()).toBe(expectedRequest.url); + expect(options.method).toBe(expectedRequest.method); + + if (expectedRequest.headers) { + expect(options.headers).toEqual( + expect.objectContaining(expectedRequest.headers), + ); + } + + if (expectedRequest.body) { + const actualBody = JSON.parse(options.body as string); + expect(actualBody).toEqual(expectedRequest.body); + } +} + +async function runLlmTest(testCase: LlmTestCase) { + const { + llm, + methodToTest, + params, + expectedRequest, + mockResponse, + mockStream, + } = testCase; + + const mockFetch = setupMockFetch(mockResponse, mockStream); + setupReadableStreamPolyfill(); + + (llm as any).fetch = mockFetch; + + // Disable OpenAI adapter to use our custom fetch mock + (llm as any).useOpenAIAdapterFor = []; + + await executeLlmMethod(llm, methodToTest, params); + assertFetchCall(mockFetch, expectedRequest); +} + +export interface OpenAISubclassConfig { + providerName: string; + defaultApiBase?: string; + modelConversions?: { [key: string]: string }; + customOptions?: any; + modelConversionContent?: string; + modelConversionMaxTokens?: number; + customStreamCompleteEndpoint?: string; + customEmbeddingsUrl?: string; + customEmbeddingsHeaders?: { [key: string]: string }; + customEmbeddingsBody?: any; + customBodyOptions?: any; +} + +function getExpectedUrl( + config: OpenAISubclassConfig, + endpoint: string, + model: string = "gpt-4", +) { + let baseUrl = config.defaultApiBase || "https://api.openai.com/v1/"; + if (config.providerName === "azure") { + return `${baseUrl}openai/deployments/${model}/${endpoint}?api-version=2023-07-01-preview`; + } else if (config.providerName === "ncompass") { + return `${baseUrl}${endpoint}`; + } + return `${baseUrl}${endpoint}`; +} + +export const createOpenAISubclassTests = ( + ProviderClass: typeof OpenAI, + config: OpenAISubclassConfig, +) => { + describe(config.providerName, () => { + afterEach(() => { + vi.clearAllMocks(); + }); + + test("should have correct provider name", () => { + expect(ProviderClass.providerName).toBe(config.providerName); + }); + + if (config.defaultApiBase) { + test("should have correct default API base", () => { + expect(ProviderClass.defaultOptions?.apiBase).toBe( + config.defaultApiBase, + ); + }); + } + + test("streamChat should send a valid request", async () => { + const provider = new ProviderClass({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: provider, + methodToTest: "streamChat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: getExpectedUrl(config, "chat/completions"), + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + ...config.customBodyOptions, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("chat should send a valid request", async () => { + const provider = new ProviderClass({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: provider, + methodToTest: "chat", + params: [ + [{ role: "user", content: "hello" }], + new AbortController().signal, + ], + expectedRequest: { + url: getExpectedUrl(config, "chat/completions"), + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "hello" }], + stream: true, + max_tokens: 2048, + ...config.customBodyOptions, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("streamComplete should send a valid request", async () => { + const provider = new ProviderClass({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: provider, + methodToTest: "streamComplete", + params: ["Hello", new AbortController().signal], + expectedRequest: { + url: getExpectedUrl( + config, + config.customStreamCompleteEndpoint || "chat/completions", + ), + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: + config.customStreamCompleteEndpoint === "completions" + ? { + model: "gpt-4", + prompt: "Hello", + stream: true, + max_tokens: 2048, + ...config.customBodyOptions, + } + : { + model: "gpt-4", + messages: [{ role: "user", content: "Hello" }], + stream: true, + max_tokens: 2048, + ...config.customBodyOptions, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("complete should send a valid request", async () => { + const provider = new ProviderClass({ + apiKey: "test-api-key", + model: "gpt-4", + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", + }); + + await runLlmTest({ + llm: provider, + methodToTest: "complete", + params: ["Hello", new AbortController().signal], + expectedRequest: { + url: getExpectedUrl(config, "chat/completions"), + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-api-key", + "api-key": "test-api-key", + }, + body: { + model: "gpt-4", + messages: [{ role: "user", content: "Hello" }], + stream: true, + max_tokens: 2048, + ...config.customBodyOptions, + }, + }, + mockStream: [ + { choices: [{ delta: { content: "Hello" } }] }, + { choices: [{ delta: { content: " world" } }] }, + ], + }); + }); + + test("should handle embeddings", async () => { + const provider = new ProviderClass({ + apiKey: "test-api-key", + model: "text-embedding-ada-002", + apiBase: config.defaultApiBase || "https://api.openai.com/v1/", + }); + + // Skip test if provider doesn't support embeddings (e.g., ncompass with undefined endpoint) + if (config.providerName === "ncompass" && !config.customEmbeddingsUrl) { + return; + } + + await runLlmTest({ + llm: provider, + methodToTest: "embed", + params: [["Hello", "World"]], + expectedRequest: { + url: + config.customEmbeddingsUrl || + `${config.defaultApiBase || "https://api.openai.com/v1/"}embeddings`, + method: "POST", + headers: config.customEmbeddingsHeaders || { + Authorization: "Bearer test-api-key", + "Content-Type": "application/json", + "api-key": "test-api-key", + }, + body: config.customEmbeddingsBody || { + input: ["Hello", "World"], + model: "text-embedding-ada-002", + }, + }, + mockResponse: { + data: [ + { embedding: [0.1, 0.2, 0.3] }, + { embedding: [0.4, 0.5, 0.6] }, + ], + }, + }); + }); + }); +}; diff --git a/core/llm/logFormatter.test.ts b/core/llm/logFormatter.test.ts index 80aa92068..380d5995b 100644 --- a/core/llm/logFormatter.test.ts +++ b/core/llm/logFormatter.test.ts @@ -44,6 +44,7 @@ describe("LLMLogFormatter", () => { content: "You are a helpful assistant", }, ], + provider: "watsonx", }); logger._logItem({ interactionId: "1", @@ -79,6 +80,7 @@ describe("LLMLogFormatter", () => { promptTokens: 10, generatedTokens: 20, thinkingTokens: 0, + usage: undefined, }); expect(output.getText()).toBe( @@ -113,6 +115,7 @@ describe("LLMLogFormatter", () => { model: "granite3.2-dense:8b", }, prompt: "A horse is a horse", + provider: "watsonx", }); logger._logItem({ interactionId: "1", @@ -149,6 +152,7 @@ describe("LLMLogFormatter", () => { }, prefix: "A\nB", suffix: "D\nE", + provider: "watsonx", }); logger._logItem({ interactionId: "1", @@ -225,6 +229,7 @@ describe("LLMLogFormatter", () => { promptTokens: 10, generatedTokens: 20, thinkingTokens: 0, + usage: undefined, }); logger._logItem({ interactionId: "3", diff --git a/core/llm/utils/calculateRequestCost.ts b/core/llm/utils/calculateRequestCost.ts new file mode 100644 index 000000000..d8706c29e --- /dev/null +++ b/core/llm/utils/calculateRequestCost.ts @@ -0,0 +1,181 @@ +import { Usage } from "../.."; + +export interface CostBreakdown { + cost: number; + breakdown: string; +} + +function calculateAnthropicCost( + model: string, + usage: Usage, +): CostBreakdown | null { + // Normalize model name to handle various formats + const normalizedModel = model.toLowerCase(); + + // Define pricing per million tokens (MTok) + const pricing: Record< + string, + { input: number; output: number; cacheWrite: number; cacheRead: number } + > = { + // Claude Opus 4 (most intelligent model) + "claude-3-opus": { + input: 15, + output: 75, + cacheWrite: 18.75, + cacheRead: 1.5, + }, + "claude-3-opus-20240229": { + input: 15, + output: 75, + cacheWrite: 18.75, + cacheRead: 1.5, + }, + + // Claude Sonnet 4 (optimal balance) + "claude-3-5-sonnet": { + input: 3, + output: 15, + cacheWrite: 3.75, + cacheRead: 0.3, + }, + "claude-3-5-sonnet-20241022": { + input: 3, + output: 15, + cacheWrite: 3.75, + cacheRead: 0.3, + }, + "claude-3-5-sonnet-20240620": { + input: 3, + output: 15, + cacheWrite: 3.75, + cacheRead: 0.3, + }, + + // Claude Haiku 3.5 (fastest, most cost-effective) + "claude-3-5-haiku": { + input: 0.8, + output: 4, + cacheWrite: 1, + cacheRead: 0.08, + }, + "claude-3-5-haiku-20241022": { + input: 0.8, + output: 4, + cacheWrite: 1, + cacheRead: 0.08, + }, + + // Legacy Claude 3 Haiku + "claude-3-haiku": { + input: 0.25, + output: 1.25, + cacheWrite: 0.3, + cacheRead: 0.03, + }, + "claude-3-haiku-20240307": { + input: 0.25, + output: 1.25, + cacheWrite: 0.3, + cacheRead: 0.03, + }, + }; + + // Find matching pricing model + let modelPricing = pricing[normalizedModel]; + + // If exact match not found, try to find by partial match + if (!modelPricing) { + for (const [key, value] of Object.entries(pricing)) { + if (normalizedModel.includes(key) || key.includes(normalizedModel)) { + modelPricing = value; + break; + } + } + } + + // If still no match, try common patterns + if (!modelPricing) { + if (normalizedModel.includes("opus")) { + modelPricing = pricing["claude-3-opus"]; + } else if (normalizedModel.includes("sonnet")) { + modelPricing = pricing["claude-3-5-sonnet"]; + } else if (normalizedModel.includes("haiku")) { + modelPricing = pricing["claude-3-5-haiku"]; + } + } + + if (!modelPricing) { + return null; // Unknown model + } + + // Calculate costs + const inputCost = (usage.promptTokens / 1_000_000) * modelPricing.input; + const outputCost = (usage.completionTokens / 1_000_000) * modelPricing.output; + + // Build breakdown components + const breakdownParts: string[] = []; + + // Input tokens breakdown + if (usage.promptTokens > 0) { + breakdownParts.push( + `Input: ${usage.promptTokens.toLocaleString()} tokens × $${modelPricing.input}/MTok = $${inputCost.toFixed(6)}`, + ); + } + + // Output tokens breakdown + if (usage.completionTokens > 0) { + breakdownParts.push( + `Output: ${usage.completionTokens.toLocaleString()} tokens × $${modelPricing.output}/MTok = $${outputCost.toFixed(6)}`, + ); + } + + // Handle prompt caching costs if available + let cacheCost = 0; + if (usage.promptTokensDetails) { + const { cachedTokens, cacheWriteTokens } = usage.promptTokensDetails; + + if (cacheWriteTokens && cacheWriteTokens > 0) { + const cacheWriteCost = + (cacheWriteTokens / 1_000_000) * modelPricing.cacheWrite; + cacheCost += cacheWriteCost; + breakdownParts.push( + `Cache Write: ${cacheWriteTokens.toLocaleString()} tokens × $${modelPricing.cacheWrite}/MTok = $${cacheWriteCost.toFixed(6)}`, + ); + } + + if (cachedTokens && cachedTokens > 0) { + const cacheReadCost = (cachedTokens / 1_000_000) * modelPricing.cacheRead; + cacheCost += cacheReadCost; + breakdownParts.push( + `Cache Read: ${cachedTokens.toLocaleString()} tokens × $${modelPricing.cacheRead}/MTok = $${cacheReadCost.toFixed(6)}`, + ); + } + } + + const totalCost = inputCost + outputCost + cacheCost; + + // Build final breakdown string + let breakdown = `Model: ${model}\n`; + breakdown += breakdownParts.join("\n"); + if (breakdownParts.length > 1) { + breakdown += `\nTotal: $${totalCost.toFixed(6)}`; + } + + return { + cost: totalCost, + breakdown, + }; +} + +export function calculateRequestCost( + provider: string, + model: string, + usage: Usage, +): CostBreakdown | null { + switch (provider) { + case "anthropic": + return calculateAnthropicCost(model, usage); + default: + return null; + } +} diff --git a/core/package-lock.json b/core/package-lock.json index 7f869503f..d2afa4b76 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -190,7 +190,8 @@ "@types/json-schema": "^7.0.15", "cross-env": "^7.0.3", "ts-jest": "^29.2.3", - "ts-node": "^10.9.2" + "ts-node": "^10.9.2", + "vitest": "^1.6.1" } }, "node_modules/@75lb/deep-merge": { diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 251922696..743556d15 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -102,7 +102,10 @@ export type ToCoreFromIdeOrWebviewProtocol = { ), void, ]; - "config/openProfile": [{ profileId: string | undefined }, void]; + "config/openProfile": [ + { profileId: string | undefined; element?: { sourceFile?: string } }, + void, + ]; "config/updateSharedConfig": [SharedConfigSchema, SharedConfigSchema]; "config/updateSelectedModel": [ { diff --git a/core/protocol/ide.ts b/core/protocol/ide.ts index ba4cf4f88..c67b8c94a 100644 --- a/core/protocol/ide.ts +++ b/core/protocol/ide.ts @@ -10,6 +10,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../"; @@ -82,6 +83,8 @@ export type ToIdeFromWebviewOrCoreProtocol = { getFileStats: [{ files: string[] }, FileStatsMap]; gotoDefinition: [{ location: Location }, RangeInFile[]]; + gotoTypeDefinition: [{ location: Location }, RangeInFile[]]; + getSignatureHelp: [{ location: Location }, SignatureHelp | null]; getControlPlaneSessionInfo: [ { silent: boolean; useOnboarding: boolean }, diff --git a/core/protocol/messenger/messageIde.ts b/core/protocol/messenger/messageIde.ts index 30d9b8177..2365117c0 100644 --- a/core/protocol/messenger/messageIde.ts +++ b/core/protocol/messenger/messageIde.ts @@ -13,6 +13,7 @@ import type { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "../.."; @@ -45,6 +46,14 @@ export class MessageIde implements IDE { return this.request("gotoDefinition", { location }); } + async gotoTypeDefinition(location: Location): Promise { + return this.request("gotoTypeDefinition", { location }); + } + + async getSignatureHelp(location: Location): Promise { + return this.request("getSignatureHelp", { location }); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { this.on("didChangeActiveTextEditor", (data) => callback(data.filepath)); } diff --git a/core/tools/definitions/createRuleBlock.ts b/core/tools/definitions/createRuleBlock.ts index 92aecb158..8f19c5955 100644 --- a/core/tools/definitions/createRuleBlock.ts +++ b/core/tools/definitions/createRuleBlock.ts @@ -16,7 +16,7 @@ export const createRuleBlock: Tool = { 'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.\n\nRule Types:\n- Always: Include only "rule" (always included in model context)\n- Auto Attached: Include "rule", "globs", and/or "regex" (included when files match patterns)\n- Agent Requested: Include "rule" and "description" (AI decides when to apply based on description)\n- Manual: Include only "rule" (only included when explicitly mentioned using @ruleName)', parameters: { type: "object", - required: ["name", "rule", "description"], + required: ["name", "rule"], properties: { name: { type: "string", diff --git a/core/tools/definitions/ls.ts b/core/tools/definitions/ls.ts index 979f9450b..71f4e5cf9 100644 --- a/core/tools/definitions/ls.ts +++ b/core/tools/definitions/ls.ts @@ -16,12 +16,11 @@ export const lsTool: Tool = { description: "List files and folders in a given directory", parameters: { type: "object", - required: ["dirPath", "recursive"], properties: { dirPath: { type: "string", description: - "The directory path relative to the root of the project. Always use forward slash paths like '/'. rather than e.g. '.'", + "The directory path relative to the root of the project. Use forward slash paths like '/'. rather than e.g. '.'", }, recursive: { type: "boolean", diff --git a/core/tools/definitions/runTerminalCommand.ts b/core/tools/definitions/runTerminalCommand.ts index f9ddd4f9a..fe5e032de 100644 --- a/core/tools/definitions/runTerminalCommand.ts +++ b/core/tools/definitions/runTerminalCommand.ts @@ -20,7 +20,7 @@ export function getPreferredShell(): string { } } -export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform} and ${os.arch} and shell ${getPreferredShell()}.`; +export const PLATFORM_INFO = `Choose terminal commands and scripts optimized for ${os.platform()} and ${os.arch()} and shell ${getPreferredShell()}.`; export const runTerminalCommandTool: Tool = { type: "function", diff --git a/core/tools/implementations/codebaseTool.ts b/core/tools/implementations/codebaseTool.ts index fe4f77ace..4af0579bf 100644 --- a/core/tools/implementations/codebaseTool.ts +++ b/core/tools/implementations/codebaseTool.ts @@ -1,22 +1,15 @@ import { ToolImpl } from "."; import { RangeInFile } from "../.."; import { retrieveContextItemsFromEmbeddings } from "../../context/retrieval/retrieval"; +import { getStringArg } from "../parseArgs"; export const codebaseToolImpl: ToolImpl = async (args, extras) => { - if (!args.query || args.query.trim() === "") { - return [ - { - name: "Error", - description: "Codebase search error", - content: "Query parameter is required and cannot be empty.", - }, - ]; - } + const query = getStringArg(args, "query"); try { const contextExtras = { config: extras.config, - fullInput: args.query, + fullInput: query, embeddingsProvider: extras.config.selectedModelByRole.embed, reranker: extras.config.selectedModelByRole.rerank, llm: extras.llm, @@ -39,7 +32,7 @@ export const codebaseToolImpl: ToolImpl = async (args, extras) => { { name: "No Results", description: "Codebase search", - content: `No relevant code found for query: "${args.query}". This could mean: + content: `No relevant code found for query: "${query}". This could mean: - The codebase hasn't been indexed yet - No code matches the search criteria - Embeddings provider is not configured diff --git a/core/tools/implementations/createNewFile.ts b/core/tools/implementations/createNewFile.ts index 5b18f03d3..0677e7dcd 100644 --- a/core/tools/implementations/createNewFile.ts +++ b/core/tools/implementations/createNewFile.ts @@ -2,20 +2,24 @@ import { inferResolvedUriFromRelativePath } from "../../util/ideUtils"; import { ToolImpl } from "."; import { getCleanUriPath, getUriPathBasename } from "../../util/uri"; +import { getStringArg } from "../parseArgs"; export const createNewFileImpl: ToolImpl = async (args, extras) => { + const filepath = getStringArg(args, "filepath"); + const contents = getStringArg(args, "contents", true); + const resolvedFileUri = await inferResolvedUriFromRelativePath( - args.filepath, + filepath, extras.ide, ); if (resolvedFileUri) { const exists = await extras.ide.fileExists(resolvedFileUri); if (exists) { throw new Error( - `File ${args.filepath} already exists. Use the edit tool to edit this file`, + `File ${filepath} already exists. Use the edit tool to edit this file`, ); } - await extras.ide.writeFile(resolvedFileUri, args.contents); + await extras.ide.writeFile(resolvedFileUri, contents); await extras.ide.openFile(resolvedFileUri); await extras.ide.saveFile(resolvedFileUri); if (extras.codeBaseIndexer) { diff --git a/core/tools/implementations/createRuleBlock.ts b/core/tools/implementations/createRuleBlock.ts index e433c233d..8e8ebcf90 100644 --- a/core/tools/implementations/createRuleBlock.ts +++ b/core/tools/implementations/createRuleBlock.ts @@ -2,6 +2,11 @@ import { createRuleMarkdown } from "@continuedev/config-yaml"; import { ToolImpl } from "."; import { RuleWithSource } from "../.."; import { createRuleFilePath } from "../../config/markdown/utils"; +import { + getBooleanArg, + getOptionalStringArg, + getStringArg, +} from "../parseArgs"; export type CreateRuleBlockArgs = Pick< Required, @@ -9,11 +14,21 @@ export type CreateRuleBlockArgs = Pick< > & Pick; -export const createRuleBlockImpl: ToolImpl = async ( - { name, rule, ...otherArgs }: CreateRuleBlockArgs, - extras, -) => { - const fileContent = createRuleMarkdown(name, rule, otherArgs); +export const createRuleBlockImpl: ToolImpl = async (args, extras) => { + const name = getStringArg(args, "name"); + const rule = getStringArg(args, "rule"); + + const description = getOptionalStringArg(args, "description"); + const regex = getOptionalStringArg(args, "regex"); + const globs = getOptionalStringArg(args, "globs"); + const alwaysApply = getBooleanArg(args, "alwaysApply", false); + + const fileContent = createRuleMarkdown(name, rule, { + alwaysApply, + description, + globs, + regex, + }); const [localContinueDir] = await extras.ide.getWorkspaceDirs(); const ruleFilePath = createRuleFilePath(localContinueDir, name); @@ -24,7 +39,7 @@ export const createRuleBlockImpl: ToolImpl = async ( return [ { name: "New Rule Block", - description: otherArgs.description || "", + description: description || "", uri: { type: "file", value: ruleFilePath, diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts index 16259780a..95b5b216b 100644 --- a/core/tools/implementations/fetchUrlContent.ts +++ b/core/tools/implementations/fetchUrlContent.ts @@ -1,10 +1,13 @@ import { ToolImpl } from "."; import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +import { getStringArg } from "../parseArgs"; const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { - const contextItems = await getUrlContextItems(args.url, extras.fetch); + const url = getStringArg(args, "url"); + + const contextItems = await getUrlContextItems(url, extras.fetch); // Track truncated content const truncatedUrls: string[] = []; @@ -12,7 +15,7 @@ export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { // Check and truncate each context item const processedItems = contextItems.map((item) => { if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) { - truncatedUrls.push(args.url); + truncatedUrls.push(url); return { ...item, content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT), diff --git a/core/tools/implementations/globSearch.ts b/core/tools/implementations/globSearch.ts index 1e551d9e2..04a105556 100644 --- a/core/tools/implementations/globSearch.ts +++ b/core/tools/implementations/globSearch.ts @@ -1,10 +1,13 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; +import { getStringArg } from "../parseArgs"; const MAX_AGENT_GLOB_RESULTS = 100; + export const fileGlobSearchImpl: ToolImpl = async (args, extras) => { + const pattern = getStringArg(args, "pattern"); const results = await extras.ide.getFileResults( - args.pattern, + pattern, MAX_AGENT_GLOB_RESULTS, ); const contextItems: ContextItem[] = [ diff --git a/core/tools/implementations/grepSearch.ts b/core/tools/implementations/grepSearch.ts index b13839669..b75c21891 100644 --- a/core/tools/implementations/grepSearch.ts +++ b/core/tools/implementations/grepSearch.ts @@ -1,6 +1,7 @@ import { ToolImpl } from "."; import { ContextItem } from "../.."; import { formatGrepSearchResults } from "../../util/grepSearch"; +import { getStringArg } from "../parseArgs"; const DEFAULT_GREP_SEARCH_RESULTS_LIMIT = 100; const DEFAULT_GREP_SEARCH_CHAR_LIMIT = 5000; // ~1000 tokens, will keep truncation simply for now @@ -41,8 +42,10 @@ function splitGrepResultsByFile(content: string): ContextItem[] { } export const grepSearchImpl: ToolImpl = async (args, extras) => { + const query = getStringArg(args, "query"); + const results = await extras.ide.getSearchResults( - args.query, + query, DEFAULT_GREP_SEARCH_RESULTS_LIMIT, ); const { formatted, numResults, truncated } = formatGrepSearchResults( @@ -63,7 +66,7 @@ export const grepSearchImpl: ToolImpl = async (args, extras) => { let contextItems: ContextItem[] = []; - const splitByFile: boolean = args.splitByFile || false; + const splitByFile: boolean = args?.splitByFile || false; if (splitByFile) { contextItems = splitGrepResultsByFile(formatted); } else { diff --git a/core/tools/implementations/readFile.ts b/core/tools/implementations/readFile.ts index 4736d0b4c..a026d0f47 100644 --- a/core/tools/implementations/readFile.ts +++ b/core/tools/implementations/readFile.ts @@ -2,28 +2,28 @@ import { resolveRelativePathInDir } from "../../util/ideUtils"; import { getUriPathBasename } from "../../util/uri"; import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; import { throwIfFileExceedsHalfOfContext } from "./readFileLimit"; export const readFileImpl: ToolImpl = async (args, extras) => { - const firstUriMatch = await resolveRelativePathInDir( - args.filepath, - extras.ide, - ); + const filepath = getStringArg(args, "filepath"); + + const firstUriMatch = await resolveRelativePathInDir(filepath, extras.ide); if (!firstUriMatch) { - throw new Error(`Could not find file ${args.filepath}`); + throw new Error(`Could not find file ${filepath}`); } const content = await extras.ide.readFile(firstUriMatch); await throwIfFileExceedsHalfOfContext( - args.filepath, + filepath, content, extras.config.selectedModelByRole.chat, ); return [ { - name: getUriPathBasename(args.filepath), - description: args.filepath, + name: getUriPathBasename(firstUriMatch), + description: filepath, content, uri: { type: "file", diff --git a/core/tools/implementations/requestRule.ts b/core/tools/implementations/requestRule.ts index a8801f344..61467e429 100644 --- a/core/tools/implementations/requestRule.ts +++ b/core/tools/implementations/requestRule.ts @@ -1,13 +1,14 @@ import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; export const requestRuleImpl: ToolImpl = async (args, extras) => { + const name = getStringArg(args, "name"); + // Find the rule by name in the config - const rule = extras.config.rules.find((r) => r.name === args.name); + const rule = extras.config.rules.find((r) => r.name === name); if (!rule || !rule.ruleFile) { - throw new Error( - `Rule with name "${args.name}" not found or has no file path`, - ); + throw new Error(`Rule with name "${name}" not found or has no file path`); } return [ diff --git a/core/tools/implementations/runTerminalCommand.ts b/core/tools/implementations/runTerminalCommand.ts index 3336a1006..201d76358 100644 --- a/core/tools/implementations/runTerminalCommand.ts +++ b/core/tools/implementations/runTerminalCommand.ts @@ -24,6 +24,7 @@ import { isProcessBackgrounded, removeBackgroundedProcess, } from "../../util/processTerminalBackgroundStates"; +import { getBooleanArg, getStringArg } from "../parseArgs"; const asyncExec = util.promisify(childProcess.exec); @@ -50,8 +51,11 @@ const ENABLED_FOR_REMOTES = [ ]; export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { + const command = getStringArg(args, "command"); // Default to waiting for completion if not specified - const waitForCompletion = args.waitForCompletion !== false; + const waitForCompletion = + getBooleanArg(args, "waitForCompletion", false) ?? true; + const ideInfo = await extras.ide.getIdeInfo(); const toolCallId = extras.toolCallId || ""; @@ -84,7 +88,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { } // Use spawn with color environment - const childProc = childProcess.spawn(args.command, { + const childProc = childProcess.spawn(command, { cwd, shell: true, env: getColorEnv(), // Add enhanced environment for colors @@ -229,7 +233,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // Standard execution, waiting for completion try { // Use color environment for exec as well - const output = await asyncExec(args.command, { + const output = await asyncExec(command, { cwd, env: getColorEnv(), }); @@ -258,7 +262,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // but don't attach any listeners other than error try { // Use spawn with color environment - const childProc = childProcess.spawn(args.command, { + const childProc = childProcess.spawn(command, { cwd, shell: true, env: getColorEnv(), // Add color environment @@ -309,7 +313,7 @@ export const runTerminalCommandImpl: ToolImpl = async (args, extras) => { // For remote environments, just run the command // Note: waitForCompletion is not supported in remote environments yet - await extras.ide.runCommand(args.command); + await extras.ide.runCommand(command); return [ { name: "Terminal", diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts index c7b64feb3..3d331ebfd 100644 --- a/core/tools/implementations/searchWeb.ts +++ b/core/tools/implementations/searchWeb.ts @@ -1,10 +1,13 @@ import { ToolImpl } from "."; import { fetchSearchResults } from "../../context/providers/WebContextProvider"; +import { getStringArg } from "../parseArgs"; const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; export const searchWebImpl: ToolImpl = async (args, extras) => { - const webResults = await fetchSearchResults(args.query, 5, extras.fetch); + const query = getStringArg(args, "query"); + + const webResults = await fetchSearchResults(query, 5, extras.fetch); // Track truncated results const truncatedResults: string[] = []; diff --git a/core/tools/implementations/viewSubdirectory.ts b/core/tools/implementations/viewSubdirectory.ts index c62887dc5..b7897aae8 100644 --- a/core/tools/implementations/viewSubdirectory.ts +++ b/core/tools/implementations/viewSubdirectory.ts @@ -2,9 +2,11 @@ import generateRepoMap from "../../util/generateRepoMap"; import { resolveRelativePathInDir } from "../../util/ideUtils"; import { ToolImpl } from "."; +import { getStringArg } from "../parseArgs"; export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => { - const { directory_path } = args; + const directory_path = getStringArg(args, "directory_path"); + const uri = await resolveRelativePathInDir(directory_path, extras.ide); if (!uri) { diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 8ee794eb5..1e7709ddc 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -12,3 +12,52 @@ export function safeParseToolCallArgs( return {}; } } + +export function getStringArg( + args: any, + argName: string, + allowEmpty = false, +): string { + if (!args || !(argName in args) || typeof args[argName] !== "string") { + throw new Error( + `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty"}. (type string)`, + ); + } + if (!allowEmpty && !args[argName].trim()) { + throw new Error(`Argument ${argName} must not be empty`); + } + return args[argName]; +} + +export function getOptionalStringArg( + args: any, + argName: string, + allowEmpty = false, +) { + if (typeof args?.[argName] === "undefined") { + return undefined; + } + return getStringArg(args, argName, allowEmpty); +} + +export function getBooleanArg(args: any, argName: string, required = false) { + if (!args || !(argName in args)) { + if (required) { + throw new Error(`Argument \`${argName}\` is required (type boolean)`); + } else { + return undefined; + } + } + if (typeof args[argName] === "string") { + if (args[argName].toLowerCase() === "false") { + return false; + } + if (args[argName].toLowerCase() === "true") { + return true; + } + } + if (typeof args[argName] !== "boolean") { + throw new Error(`Argument \`${argName}\` must be a boolean true or false`); + } + return args[argName]; +} diff --git a/core/tools/parseArgs.vitest.ts b/core/tools/parseArgs.vitest.ts new file mode 100644 index 000000000..b501191f0 --- /dev/null +++ b/core/tools/parseArgs.vitest.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from "vitest"; +import { ToolCallDelta } from ".."; +import { + getBooleanArg, + getOptionalStringArg, + getStringArg, + safeParseToolCallArgs, +} from "./parseArgs"; + +describe("safeParseToolCallArgs", () => { + it("should parse valid JSON arguments", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: '{"name": "test", "value": 123}', + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({ name: "test", value: 123 }); + }); + + it("should parse valid JSON arguments with whitespace", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: ' {"name": "test", "value": 123} ', + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({ name: "test", value: 123 }); + }); + + it("should return empty object for invalid JSON", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: '{"name": "test", value: 123', // Invalid JSON + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); + + it("should return empty object when arguments is empty", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: "", + }, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); + + it("should return empty object when arguments is null or undefined", () => { + const toolCall1: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: null as any, + }, + }; + + const toolCall2: ToolCallDelta = { + id: "1", + function: { + name: "testFunction", + arguments: undefined, + }, + }; + + expect(safeParseToolCallArgs(toolCall1)).toEqual({}); + expect(safeParseToolCallArgs(toolCall2)).toEqual({}); + }); + + it("should handle case when function is undefined", () => { + const toolCall: ToolCallDelta = { + id: "1", + function: undefined, + }; + + const result = safeParseToolCallArgs(toolCall); + expect(result).toEqual({}); + }); +}); + +describe("getStringArg", () => { + it("should return string argument when valid", () => { + const args = { name: "test" }; + const result = getStringArg(args, "name"); + expect(result).toBe("test"); + }); + + it("should throw error when argument is missing", () => { + const args = { otherArg: "test" }; + expect(() => getStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is not a string", () => { + const args = { name: 123 }; + expect(() => getStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is empty and empty not allowed", () => { + const args = { name: "" }; + expect(() => getStringArg(args, "name")).toThrowError( + "Argument name must not be empty", + ); + + const argsWithSpace = { name: " " }; + expect(() => getStringArg(argsWithSpace, "name")).toThrowError( + "Argument name must not be empty", + ); + }); + + it("should accept empty string when allowEmpty is true", () => { + const args = { name: "" }; + const result = getStringArg(args, "name", true); + expect(result).toBe(""); + + const argsWithSpace = { name: " " }; + const resultWithSpace = getStringArg(argsWithSpace, "name", true); + expect(resultWithSpace).toBe(" "); + }); + + it("should handle null or undefined args", () => { + expect(() => getStringArg(null, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + expect(() => getStringArg(undefined, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); +}); + +describe("getOptionalStringArg", () => { + it("should return undefined when argument is not provided", () => { + const args = { otherArg: "test" }; + const result = getOptionalStringArg(args, "name"); + expect(result).toBeUndefined(); + }); + + it("should return string argument when valid", () => { + const args = { name: "test" }; + const result = getOptionalStringArg(args, "name"); + expect(result).toBe("test"); + }); + + it("should throw error when argument is not a string", () => { + const args = { name: 123 }; + expect(() => getOptionalStringArg(args, "name")).toThrowError( + "`name` argument is required and must not be empty. (type string)", + ); + }); + + it("should throw error when argument is empty and empty not allowed", () => { + const args = { name: "" }; + expect(() => getOptionalStringArg(args, "name")).toThrowError( + "Argument name must not be empty", + ); + }); + + it("should accept empty string when allowEmpty is true", () => { + const args = { name: "" }; + const result = getOptionalStringArg(args, "name", true); + expect(result).toBe(""); + }); + + it("should handle null or undefined args", () => { + expect(getOptionalStringArg(null, "name")).toBeUndefined(); + expect(getOptionalStringArg(undefined, "name")).toBeUndefined(); + }); +}); + +describe("getBooleanArg", () => { + it("should return boolean argument when valid", () => { + const argsTrue = { flag: true }; + const argsFalse = { flag: false }; + + expect(getBooleanArg(argsTrue, "flag")).toBe(true); + expect(getBooleanArg(argsFalse, "flag")).toBe(false); + }); + + it("should return undefined when argument is not provided and not required", () => { + const args = { otherArg: true }; + const result = getBooleanArg(args, "flag"); + expect(result).toBeUndefined(); + }); + + it("should throw error when argument is not provided and required", () => { + const args = { otherArg: true }; + expect(() => getBooleanArg(args, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + }); + + it('should handle string "true" and "false" values', () => { + const argsStringTrue = { flag: "true" }; + const argsStringFalse = { flag: "false" }; + const argsStringTrueUppercase = { flag: "TRUE" }; + const argsStringFalseUppercase = { flag: "FALSE" }; + + expect(getBooleanArg(argsStringTrue, "flag")).toBe(true); + expect(getBooleanArg(argsStringFalse, "flag")).toBe(false); + expect(getBooleanArg(argsStringTrueUppercase, "flag")).toBe(true); + expect(getBooleanArg(argsStringFalseUppercase, "flag")).toBe(false); + }); + + it("should throw error when argument is not a boolean or valid boolean string", () => { + const argsNumber = { flag: 1 }; + const argsInvalidString = { flag: "yes" }; + const argsObject = { flag: {} }; + + expect(() => getBooleanArg(argsNumber, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + expect(() => getBooleanArg(argsInvalidString, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + expect(() => getBooleanArg(argsObject, "flag")).toThrowError( + "Argument `flag` must be a boolean true or false", + ); + }); + + it("should handle null or undefined args", () => { + expect(getBooleanArg(null, "flag")).toBeUndefined(); + expect(getBooleanArg(undefined, "flag")).toBeUndefined(); + + expect(() => getBooleanArg(null, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + expect(() => getBooleanArg(undefined, "flag", true)).toThrowError( + "Argument `flag` is required (type boolean)", + ); + }); +}); diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 1926f578d..72c66740f 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -13,6 +13,7 @@ import { Problem, Range, RangeInFile, + SignatureHelp, TerminalOptions, Thread, ToastType, @@ -44,6 +45,14 @@ class FileSystemIde implements IDE { return Promise.resolve([]); } + gotoTypeDefinition(location: Location): Promise { + return Promise.resolve([]); + } + + getSignatureHelp(location: Location): Promise { + return Promise.resolve(null); + } + onDidChangeActiveTextEditor(callback: (fileUri: string) => void): void { return; } diff --git a/core/util/parameters.ts b/core/util/parameters.ts index cadbe9a47..147c3979a 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -24,6 +24,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { experimental_includeRecentlyVisitedRanges: true, experimental_includeRecentlyEditedRanges: true, experimental_includeDiff: true, + experimental_enableStaticContextualization: false, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/docs/customize/context/codebase.mdx b/docs/customize/context/codebase.mdx index 674167045..5cad74c59 100644 --- a/docs/customize/context/codebase.mdx +++ b/docs/customize/context/codebase.mdx @@ -94,4 +94,4 @@ If you need to force a refresh of the index, reload the VS Code window with diff --git a/docs/customize/custom-providers.mdx b/docs/customize/custom-providers.mdx index 3fb3b6591..78d518e99 100644 --- a/docs/customize/custom-providers.mdx +++ b/docs/customize/custom-providers.mdx @@ -143,7 +143,10 @@ Reference the contents of all of your open files. Set `onlyPinned` to `true` to config.yaml ``` -context: - provider: open params: onlyPinned: true +context: + - provider: open + params: + onlyPinned: true ``` config.json @@ -164,7 +167,10 @@ Optionally, set `n` to limit the number of results returned (default 6). config.yaml ``` -context: - provider: web params: n: 5 +context: + - provider: web + params: + n: 5 ``` config.json @@ -183,7 +189,8 @@ Reference the most relevant snippets from your codebase. config.yaml ``` -context: - provider: codebase +context: + - provider: codebase ``` config.json @@ -223,7 +230,10 @@ Reference the results of codebase search, just like the results you would get fr config.yaml ``` -context: - provider: search params: maxResults: 100 # optional, defaults to 200 +context: + - provider: search + params: + maxResults: 100 # optional, defaults to 200 ``` config.json @@ -244,7 +254,8 @@ Reference the markdown converted contents of a given URL. config.yaml ``` -context: - provider: url +context: + - provider: url ``` config.json @@ -263,7 +274,8 @@ Reference recent clipboard items config.yaml ``` -context: - provider: clipboard +context: + - provider: clipboard ``` config.json @@ -282,7 +294,8 @@ Reference the structure of your current workspace. config.yaml ``` -context: - provider: tree +context: + - provider: tree ``` config.json @@ -301,7 +314,8 @@ Get Problems from the current file. config.yaml ``` -context: - provider: problems +context: + - provider: problems ``` config.json @@ -320,7 +334,10 @@ Reference the contents of the local variables in the debugger. Currently only av config.yaml ``` -context: - provider: debugger params: stackDepth: 3 +context: + - provider: debugger + params: + stackDepth: 3 ``` config.json @@ -343,7 +360,10 @@ Reference the outline of your codebase. By default, signatures are included alon config.yaml ``` -context: - provider: repo-map params: includeSignatures: false # default true +context: + - provider: repo-map + params: + includeSignatures: false # default true ``` config.json @@ -368,7 +388,8 @@ Reference the architecture and platform of your current operating system. config.yaml ``` -context: - provider: os +context: + - provider: os ``` config.json @@ -387,7 +408,13 @@ The [Model Context Protocol](https://modelcontextprotocol.io/introduction) is a config.yaml ``` -mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db +mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db ``` config.json @@ -420,7 +447,13 @@ Reference the conversation in a GitHub issue. config.yaml ``` -context: - provider: issue params: repos: - owner: continuedev repo: continue githubToken: ghp_xxx +context: + - provider: issue + params: + repos: + - owner: continuedev + repo: continue + githubToken: ghp_xxx ``` config.json @@ -451,7 +484,29 @@ Reference table schemas from Sqlite, Postgres, MSSQL, and MySQL databases. config.yaml ``` -context: - provider: database params: connections: - name: examplePostgres connection_type: postgres connection: user: username host: localhost database: exampleDB password: yourPassword port: 5432 - name: exampleMssql connection_type: mssql connection: user: username server: localhost database: exampleDB password: yourPassword - name: exampleSqlite connection_type: sqlite connection: filename: /path/to/your/sqlite/database.db +context: + - provider: database + params: + connections: + - name: examplePostgres + connection_type: postgres + connection: + user: username + host: localhost + database: exampleDB + password: yourPassword + port: 5432 + - name: exampleMssql + connection_type: mssql + connection: + user: username + server: localhost + database: exampleDB + password: yourPassword + - name: exampleSqlite + connection_type: sqlite + connection: + filename: /path/to/your/sqlite/database.db ``` config.json @@ -514,7 +569,16 @@ Reference the schema of a table, and some sample rows config.yaml ``` -context: - provider: postgres params: host: localhost port: 5436 user: myuser password: catsarecool database: animals schema: public sampleRows: 3 +context: + - provider: postgres + params: + host: localhost + port: 5436 + user: myuser + password: catsarecool + database: animals + schema: public + sampleRows: 3 ``` config.json @@ -554,7 +618,10 @@ Reference the results of a Google search. config.yaml ``` -context: - provider: google params: serperApiKey: +context: + - provider: google + params: + serperApiKey: ``` config.json @@ -584,7 +651,10 @@ Reference an open MR for this branch on GitLab. config.yaml ``` -context: - provider: gitlab-mr params: token: "..." +context: + - provider: gitlab-mr + params: + token: "..." ``` config.json @@ -605,7 +675,11 @@ You can specify the domain to communicate with by setting the `domain` parameter config.yaml ``` -context: - provider: gitlab-mr params: token: "..." domain: "gitlab.example.com" +context: + - provider: gitlab-mr + params: + token: "..." + domain: "gitlab.example.com" ``` config.json @@ -635,7 +709,11 @@ Reference the conversation in a Jira issue. config.yaml ``` -context: - provider: jira params: domain: company.atlassian.net token: ATATT... +context: + - provider: jira + params: + domain: company.atlassian.net + token: ATATT... ``` config.json @@ -663,7 +741,10 @@ This context provider supports both Jira API version 2 and 3. It will use versio config.yaml ``` -context: - provider: jira params: apiVersion: "2" +context: + - provider: jira + params: + apiVersion: "2" ``` config.json @@ -696,7 +777,16 @@ Reference the messages in a Discord channel. config.yaml ``` -context: - provider: discord params: discordKey: "bot token" guildId: "1234567890" channels: - id: "123456" name: "example-channel" - id: "678901" name: "example-channel-2" +context: + - provider: discord + params: + discordKey: "bot token" + guildId: "1234567890" + channels: + - id: "123456" + name: "example-channel" + - id: "678901" + name: "example-channel-2" ``` config.json @@ -731,7 +821,10 @@ The HttpContextProvider makes a POST request to the url passed in the configurat config.yaml ``` -context: - provider: http params: url: "https://api.example.com/v1/users" +context: + - provider: http + params: + url: "https://api.example.com/v1/users" ``` config.json @@ -770,7 +863,11 @@ Reference specific git commit metadata and diff or all of the recent commits. config.yaml ``` -context: - provider: commit params: Depth: 50 LastXCommitsDepth: 10 +context: + - provider: commit + params: + Depth: 50 + LastXCommitsDepth: 10 ``` config.json @@ -795,7 +892,11 @@ Query a [Greptile](https://www.greptile.com/) index of the current repo/branch. config.yaml ``` -context: - provider: greptile params: greptileToken: "..." githubToken: "..." +context: + - provider: greptile + params: + greptileToken: "..." + githubToken: "..." ``` config.json diff --git a/docs/customize/deep-dives/slash-commands.mdx b/docs/customize/deep-dives/slash-commands.mdx index 7057575bd..81579d3ed 100644 --- a/docs/customize/deep-dives/slash-commands.mdx +++ b/docs/customize/deep-dives/slash-commands.mdx @@ -15,7 +15,7 @@ Slash commands can be combined with additional instructions, including [context ### Assistant prompt blocks -The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types.md#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx). +The easiest way to add a slash command is by adding [`prompt` blocks](../../hub/blocks/block-types#prompts) to your assistant, which show up as slash commands in [Chat](../../features/chat/how-it-works.mdx). ### Prompt files diff --git a/docs/customize/model-providers/top-level/azure.mdx b/docs/customize/model-providers/top-level/azure.mdx index 26392fe1b..c91404df9 100644 --- a/docs/customize/model-providers/top-level/azure.mdx +++ b/docs/customize/model-providers/top-level/azure.mdx @@ -48,7 +48,13 @@ We recommend configuring **GPT-4o** as your chat model. ## Autocomplete model -We recommend configuring **Codestral** as your autocomplete model. If you use Azure AI Foundry to deploy Codestral: +We recommend configuring **Codestral** as your autocomplete model. + + +**Note:** Azure AI Foundry does not provide the FIM (Fill-in-Middle) endpoint required for autocomplete functionality. To use Codestral for autocomplete, deploy it through **Azure Machine Learning Studio** instead, which provides the necessary `/v1/fim/completions` endpoint. + + +If you use Azure Machine Learning Studio to deploy Codestral: diff --git a/docs/customize/model-providers/top-level/bedrock.mdx b/docs/customize/model-providers/top-level/bedrock.mdx index 7c959fae4..93ed96648 100644 --- a/docs/customize/model-providers/top-level/bedrock.mdx +++ b/docs/customize/model-providers/top-level/bedrock.mdx @@ -186,6 +186,41 @@ aws_secret_access_key = hijklmno aws_session_token = pqrstuvwxyz # Optional: means short term creds. ``` +You can also use an AWS `accessKeyId` and `secretAccessKey` for authentication instead of a local credentials profile. + + + + ```yaml title="config.yaml" + models: + - name: Claude 3.7 Sonnet + provider: bedrock + model: us.anthropic.claude-3-7-sonnet-20250219-v1:0 + env: + region: us-east-1 + accessKeyId: ${{ secrets.AWS_ACCESS_KEY_ID }} # can also enter key inline here for local assistants + secretAccessKey: ${{ secrets.AWS_SECRET_ACCESS_KEY }} # can also enter key inline here for local assistants + roles: + - chat + ``` + + + ```json title="config.json" + { + "models": [ + { + "title": "Claude 3.7 Sonnet", + "provider": "bedrock", + "model": "us.anthropic.claude-3-7-sonnet-20250219-v1:0", + "region": "us-east-1", + "accessKeyId": "[YOUR_ACCESS_KEY_ID]", + "secretAccessKey": "[YOUR_SECRET_ACCESS_KEY]" + } + ] + } + ``` + + + ## Custom Imported Models To setup Bedrock using custom imported models, add the following to your config file: diff --git a/docs/customize/model-roles/embeddings.mdx b/docs/customize/model-roles/embeddings.mdx index c82f3d355..feb7f675d 100644 --- a/docs/customize/model-roles/embeddings.mdx +++ b/docs/customize/model-roles/embeddings.mdx @@ -21,7 +21,7 @@ You can add `embed` to a model's `roles` to specify that it can be used to embed If you have the ability to use any model, we recommend `voyage-code-3`, which is listed below along with the rest of the options for embeddings models. -If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama.mdx#embeddings-model). +If you want to generate embeddings locally, we recommend using `nomic-embed-text` with [Ollama](../model-providers/top-level/ollama#embeddings-model). ### Voyage AI @@ -57,7 +57,7 @@ After obtaining an API key from [here](https://www.voyageai.com/), you can confi ### Ollama -See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instructions on how to use Ollama for embeddings. +See [here](../model-providers/top-level/ollama#embeddings-model) for instructions on how to use Ollama for embeddings. ### Transformers.js (currently VS Code only) @@ -118,36 +118,36 @@ See [here](../model-providers/top-level/ollama.mdx#embeddings-model) for instruc ### OpenAI -See [here](../model-providers/top-level/openai.mdx#embeddings-model) for instructions on how to use OpenAI for embeddings. +See [here](../model-providers/top-level/openai#embeddings-model) for instructions on how to use OpenAI for embeddings. ### Cohere -See [here](../model-providers/more/cohere.mdx#embeddings-model) for instructions on how to use Cohere for embeddings. +See [here](../model-providers/more/cohere#embeddings-model) for instructions on how to use Cohere for embeddings. ### Gemini -See [here](../model-providers/top-level/gemini.mdx#embeddings-model) for instructions on how to use Gemini for embeddings. +See [here](../model-providers/top-level/gemini#embeddings-model) for instructions on how to use Gemini for embeddings. ### Vertex -See [here](../model-providers/top-level/vertexai.mdx#embeddings-model) for instructions on how to use Vertex for embeddings. +See [here](../model-providers/top-level/vertexai#embeddings-model) for instructions on how to use Vertex for embeddings. ### Mistral -See [here](../model-providers/top-level/mistral.mdx#embeddings-model) for instructions on how to use Mistral for embeddings. +See [here](../model-providers/top-level/mistral#embeddings-model) for instructions on how to use Mistral for embeddings. ### NVIDIA -See [here](../model-providers/more/nvidia.mdx#embeddings-model) for instructions on how to use NVIDIA for embeddings. +See [here](../model-providers/more/nvidia#embeddings-model) for instructions on how to use NVIDIA for embeddings. ### Bedrock -See [here](../model-providers/top-level/bedrock.mdx#embeddings-model) for instructions on how to use Bedrock for embeddings. +See [here](../model-providers/top-level/bedrock#embeddings-model) for instructions on how to use Bedrock for embeddings. ### WatsonX -See [here](../model-providers/more/watsonx.mdx#embeddings-model) for instructions on how to use WatsonX for embeddings. +See [here](../model-providers/more/watsonx#embeddings-model) for instructions on how to use WatsonX for embeddings. ### LMStudio -See [here](../model-providers/more/lmstudio.mdx#embeddings-model) for instructions on how to use LMStudio for embeddings. +See [here](../model-providers/more/lmstudio#embeddings-model) for instructions on how to use LMStudio for embeddings. diff --git a/docs/docs.json b/docs/docs.json index 86657b4b8..ec993cdb7 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -65,6 +65,7 @@ "pages": [ "features/agent/quick-start", "features/agent/how-it-works", + "features/agent/plan-mode", "features/agent/model-setup", "features/agent/how-to-customize", "features/agent/context-selection" diff --git a/docs/features/agent/how-it-works.mdx b/docs/features/agent/how-it-works.mdx index 0b5e884f4..eaca170b7 100644 --- a/docs/features/agent/how-it-works.mdx +++ b/docs/features/agent/how-it-works.mdx @@ -17,22 +17,37 @@ The following handshake describes how Agent uses tools: 6. The model responds, potentially with another tool call and step 2 begins again - In [Chat mode](/features/chat/quick-start), tools are **not** included in the - request to the model. + Tool availability varies by mode: + - **Chat mode**: No tools included + - **Plan mode**: Only read-only tools included + - **Agent mode**: All tools included ## Built-in tools -Continue includes several built-in tools which provide the model access to IDE functionality: +Continue includes several built-in tools which provide the model access to IDE functionality. -- **Read file** (`read_file`): read the contents of a file within the project -- **Read currently open file** (`read_currently_open_file`): read the contents of the currently open file -- **Create new file** (`create_new_file`): Create a new file within the project, with path and contents specified by the model -- **Exact search** (`exact_search`): perform a `ripgrep` search within the project -- **Glob search** (`file_glob_search`): perform a glob search on files in the project. Currently limits to 100 output and warns the Agent if limit reached. -- **Run terminal command** (`run_terminal_command`): run a terminal command from the workspace root -- **Search web** (`search_web`): Perform a web search to get top results -- **View diff** (`view_diff`): View the current working git diff -- **View repo map** (`view_repo_map`): request a copy of the repository map—same as the [Repo Map Context Provider](/customize/custom-providers#repository-map) -- **View subdirectory** (`view_subdirectory`): request a copy of a repo map for a specific directory within the project -- **Create Rule Block** (`create_rule_block`): creates a new rule block in `.continue/rules` based on the contents of the conversation +### Plan mode tools (read-only) + +In Plan mode, only these read-only tools are available: +- **Read file** (`read_file`) +- **Read currently open file** (`read_currently_open_file`) +- **List directory** (`ls`) +- **Glob search** (`glob_search`) +- **Grep search** (`grep_search`) +- **Fetch URL content** (`fetch_url_content`) +- **Search web** (`search_web`) +- **View diff** (`view_diff`) +- **View repo map** (`view_repo_map`) +- **View subdirectory** (`view_subdirectory`) +- **Codebase tool** (`codebase_tool`) + +### Agent mode tools (all tools) + +In Agent mode, all tools are available including the read-only tools above plus: + +- **Create new file** (`create_new_file`): Create a new file within the project +- **Edit file** (`edit_file`): Make changes to existing files +- **Run terminal command** (`run_terminal_command`): Run commands from the workspace root +- **Create Rule Block** (`create_rule_block`): Create a new rule block in `.continue/rules` +- All other write/execute tools for modifying the codebase diff --git a/docs/features/agent/plan-mode.mdx b/docs/features/agent/plan-mode.mdx new file mode 100644 index 000000000..104b73d37 --- /dev/null +++ b/docs/features/agent/plan-mode.mdx @@ -0,0 +1,49 @@ +--- +title: "Plan Mode" +description: "Explore and understand code safely with read-only tools" +--- + +## What is Plan mode? + +Plan mode is a restricted environment that provides read-only access to your codebase. It's designed for safe exploration, understanding code, and planning changes without making any modifications. + +![Plan mode in action](/images/plan-mode.gif) + +### Key features + +- **Read-only tools**: Access files, search, and analyze without risk +- **Safe exploration**: Perfect for understanding unfamiliar codebases +- **Planning focus**: Develop implementation strategies before execution +- **MCP support**: Works with all MCP tools alongside built-in read-only tools + +### How it works + +Plan mode filters the available tools to only include read-only operations. This means you can: +- Read any file in your project +- Search through code with grep and glob patterns +- View repository structure and diffs +- Fetch web content for additional context +- Use all MCP tools + +But you cannot: +- Create, edit, or delete files +- Run terminal commands +- Make any system changes + +### Getting started + +Select "Plan" from the mode selector below the chat input, or use `Cmd/Ctrl + .` to cycle through modes. + +![Plan mode selector](/images/plan-mode-selector.png) + +For detailed information about tools and usage, see the [Agent documentation](/features/agent/how-it-works), which covers both Agent and Plan modes. + +### Common workflow + +1. **Start in Plan mode** to explore and understand +2. **Develop your approach** with the model's help +3. **Switch to Agent mode** when ready to implement + + + Plan mode shares the same interface and context features as Chat and Agent modes. You can use `@` context providers and highlight code just like in other modes. + \ No newline at end of file diff --git a/docs/features/agent/quick-start.mdx b/docs/features/agent/quick-start.mdx index a2c3434c2..91f2e6297 100644 --- a/docs/features/agent/quick-start.mdx +++ b/docs/features/agent/quick-start.mdx @@ -6,18 +6,39 @@ title: "Quick Start" Agent equips the Chat model with the tools needed to handle a wide range of coding tasks, allowing the model to make decisions and save you the work of manually finding context and performing actions. +### When to use each mode + +- **Plan mode**: Use when you want to explore code, understand systems, or plan changes without making modifications. Perfect for: + - Understanding unfamiliar codebases + - Planning complex refactors + - Debugging and investigation + - Creating implementation strategies + +- **Agent mode**: Use when you're ready to make changes. Ideal for: + - Implementing features + - Fixing bugs + - Running tests and commands + - Executing plans developed in Plan mode + ### Use Agent -You can switch to `Agent` in the mode selector below the chat input box. +You can switch to `Agent` in the mode selector below the chat input box. The mode selector offers three options: +- **Chat**: No tools available, pure conversation +- **Plan**: Read-only tools for safe exploration and planning +- **Agent**: All tools available for making changes ![How to select agent mode](/images/mode-select-agent.png) - If Agent is disabled with a `Not Supported` message, the selected model or + If Agent or Plan is disabled with a `Not Supported` message, the selected model or provider doesn't support tools, or Continue doesn't yet support tools with it. See [Model Blocks](/customization/models) for more information. + + Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between modes. + + ### Chat with Agent Agent lives within the same interface as [Chat](/features/chat/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context). diff --git a/docs/features/chat/model-setup.mdx b/docs/features/chat/model-setup.mdx index bd7238e5f..c1ebd019a 100644 --- a/docs/features/chat/model-setup.mdx +++ b/docs/features/chat/model-setup.mdx @@ -25,6 +25,13 @@ These models have varying tool calling and reasoning capabilities. 3. Add `GEMINI_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) 4. Click `Reload config` in the assistant selector in the Continue IDE extension +[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI + +1. Get your API key from [Together AI](https://api.together.ai) +2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub +3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) +4. Click `Reload config` in the assistant selector in the Continue IDE extension + [o3](https://hub.continue.dev/openai/o3) from OpenAI 1. Get your API key from [OpenAI](https://platform.openai.com) @@ -46,10 +53,10 @@ These models have varying tool calling and reasoning capabilities. 3. Add `MISTRAL_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) 4. Click `Reload config` in the assistant selector in the Continue IDE extension -[Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) from Moonshot AI +[DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) from DeepSeek -1. Get your API key from [TogetherAI](https://api.together.ai) -2. Add [Kimi K2](hub.continue.dev/togetherai/kimi-k2-instruct) to your assistant on Continue Hub +1. Get your API key from [Together AI](https://api.together.ai) +2. Add [DeepSeek-V3](https://hub.continue.dev/togetherai/deepseek-v3) to your assistant on Continue Hub 3. Add `TOGETHER_API_KEY` as a [User Secret](https://docs.continue.dev/hub/secrets/secret-types#user-secrets) on Continue Hub [here](https://hub.continue.dev/settings/secrets) 4. Click `Reload config` in the assistant selector in the Continue IDE extension @@ -59,6 +66,18 @@ These models can be run on your computer if you have enough VRAM. Their limited tool calling and reasoning capabilities will make it challenging to use Agent mode. +[Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) + +1. Add [Qwen2.5-Coder 32B](https://hub.continue.dev/ollama/qwen2.5-coder-32b) to your assistant on Continue Hub +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) +3. Click `Reload config` in the assistant selector in the Continue IDE extension + +[Devstral Small 27B](https://hub.continue.dev/ollama/devstral) + +1. Add [Devstral Small](https://hub.continue.dev/ollama/devstral) to your assistant on Continue Hub +2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) +3. Click `Reload config` in the assistant selector in the Continue IDE extension + [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) from Qwen 1. Add [Qwen2.5-Coder 7B](https://hub.continue.dev/ollama/qwen2.5-coder-7b) to your assistant on Continue Hub @@ -71,10 +90,4 @@ Their limited tool calling and reasoning capabilities will make it challenging t 2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) 3. Click `Reload config` in the assistant selector in the Continue IDE extension -[Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) from Meta - -1. Add [Llama 3.1 8B](https://hub.continue.dev/ollama/llama3.1-8b) to your assistant on Continue Hub -2. Run the model with [Ollama](https://docs.continue.dev/guides/ollama-guide#using-ollama-with-continue-a-developers-guide) -3. Click `Reload config` in the assistant selector in the Continue IDE extension - For more detailed setup instructions, see [here](/getting-started/install#setup-your-first-model) diff --git a/docs/features/edit/context-selection.mdx b/docs/features/edit/context-selection.mdx index a7c3459c9..0cbff11c5 100644 --- a/docs/features/edit/context-selection.mdx +++ b/docs/features/edit/context-selection.mdx @@ -4,8 +4,4 @@ The input you provide is included in the prompt. ## Code to Edit -The **entire contents** of each file (the current file for Jetbrains inline Edit, the `Code to Edit` item for VS Code Edit mode) are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. - -## Context Providers - -In VS Code Edit mode, you can use `@` to add context using [Context Providers](/customize/custom-providers), similar to [Chat](/features/chat/context-selection). Some context providers may be disabled in Edit mode. +The **entire contents** of the current file are included in the prompt for context. The model will only attempt to edit the highlighted/specified ranges. diff --git a/docs/features/edit/how-to-customize.mdx b/docs/features/edit/how-to-customize.mdx index 1375d7b9d..74f06a549 100644 --- a/docs/features/edit/how-to-customize.mdx +++ b/docs/features/edit/how-to-customize.mdx @@ -6,4 +6,6 @@ You can configure particular models from your Assistant to be used for Edit and 2. Click the cube icon to expand the "Models" section 3. Use the dropdowns to select models for Edit and Apply +![Edit model selection](/images/edit-model.png) + Learn more about the [Edit role](/customize/model-roles/edit) and [Apply role](/customize/model-roles/apply). diff --git a/docs/features/edit/quick-start.mdx b/docs/features/edit/quick-start.mdx index 087ac5e15..aa2d9b5d4 100644 --- a/docs/features/edit/quick-start.mdx +++ b/docs/features/edit/quick-start.mdx @@ -14,7 +14,7 @@ Edit is recommended for small, targeted changes, such as ## Highlight code and activate -Highlight the block of code you would like to modify and press `cmd/ctrl` + `i` to active Edit mode. You can also enter Edit mode by pressing `cmd/ctrl` + `i` with no code highlighted, which will default to editing the current file. +Highlight the block of code you would like to modify and press `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to activate Edit mode. You can also press `Cmd/Ctrl+I` with no code highlighted, which will default to inserting code at the current cursor location. ## Describe code changes @@ -24,23 +24,12 @@ Describe the changes you would like the model to make to your highlighted code. Proposed changes appear as inline diffs within your highlighted text. -You can navigate through each proposed change, accepting or rejecting them using `cmd/ctrl` + `opt` + `y` (to accept) or `cmd/ctrl` + `opt` + `n` (to reject). +You can navigate through each proposed change, accepting or rejecting them using `Cmd+Opt+Y` (Mac) or `Ctrl+Alt+Y` (Windows/Linux) to accept, or `Cmd+Opt+N` (Mac) or `Ctrl+Alt+N` (Windows/Linux) to reject. -You can also accept or reject all changes at once using `cmd/ctrl` + `shift` + `enter` (to accept) or `cmd/ctrl` + `shift` + `delete/backspace` (to reject). +You can also accept or reject all changes at once using `Cmd+Shift+Enter` (Mac) or `Ctrl+Shift+Enter` (Windows/Linux) to accept, or `Cmd+Shift+Delete` (Mac) or `Ctrl+Shift+Backspace` (Windows/Linux) to reject. -If you want to request a new suggestion for the same highlighted code section, you can use `cmd/ctrl` + `i` to re-prompt the model. +If you want to request a new suggestion for the same highlighted code section, you can use `Cmd+I` (Mac) or `Ctrl+I` (Windows/Linux) to re-prompt the model. -## VS Code - -In VS Code, Edit is implemented in the extension sidebar with a similar interface to [Chat](/features/chat/how-it-works), and you can also enter Edit mode by using the Mode Selector below the main Chat input to select `Edit`. - -![edit mode selected](/images/features/edit/images/select-edit-mode-75c8f01861ebe03177986a5b7f21f746.png) - -You can also reject and accept diffs using the `Reject All` and `Accept All` buttons that show up in the Chat when diffs are present (see examples below). - -### Adding Code to Edit - -Along with adding highlighted code, you can also manually add files to edit using the `Add file` combobox or by clicking the dropdown and selecting `Add all open files` to add all files that are currently open in the editor. ## Jetbrains diff --git a/docs/features/plan/how-it-works.mdx b/docs/features/plan/how-it-works.mdx new file mode 100644 index 000000000..c19bb2080 --- /dev/null +++ b/docs/features/plan/how-it-works.mdx @@ -0,0 +1,112 @@ +--- +title: "How Plan Works" +description: "Plan mode provides a restricted environment with read-only tools, enabling safe exploration and planning without making changes to your codebase." +--- + +## Understanding Plan mode + +Plan mode is designed to help you understand code and construct plans before making changes. It sits between Chat mode (no tools) and Agent mode (all tools), providing a middle ground where you can explore and analyze without risk. + +### The key difference: Read-only tools + +While Agent mode has access to all tools including those that modify files, Plan mode restricts access to only read-only tools. This ensures that: + +- No files are created, modified, or deleted +- No commands are executed that could change system state +- All exploration is safe and non-destructive +- You can confidently investigate without unintended consequences + +## How Plan mode works + +When you select Plan mode: + +1. Continue sends a special system message instructing the model to focus on understanding and planning +2. The tool list is filtered to include only read-only tools +3. The model can use these tools to explore and analyze your codebase +4. When you're ready to implement changes, you switch to Agent mode + +### Available tools in Plan mode + +Plan mode includes these read-only built-in tools: + +- **Read file** (`read_file`): Read the contents of any file in the project +- **Read currently open file** (`read_currently_open_file`): Read the contents of the currently open file +- **List directory** (`ls`): List files and directories +- **Glob search** (`glob_search`): Search for files matching a pattern +- **Grep search** (`grep_search`): Search file contents using regex patterns +- **Fetch URL content** (`fetch_url_content`): Retrieve content from web URLs +- **Search web** (`search_web`): Perform web searches for additional context +- **View diff** (`view_diff`): View the current git diff +- **View repo map** (`view_repo_map`): Get an overview of the repository structure +- **View subdirectory** (`view_subdirectory`): Get a detailed view of a specific directory +- **Codebase tool** (`codebase_tool`): Advanced codebase analysis capabilities + +### MCP tools support + +In addition to built-in read-only tools, Plan mode also supports all MCP (Model Context Protocol) tools. This allows integration with external services that provide additional context or analysis capabilities without modifying your local environment. + + + While Plan mode restricts built-in tools to read-only operations, MCP tools are not filtered by Continue. Some MCP tools may have write capabilities that could modify your system or external services. Always verify what actions your MCP tools can perform before using them in Plan mode. + + +## The planning workflow + +A typical Plan mode workflow follows these steps: + +1. **Exploration**: Use read-only tools to understand the current state +2. **Analysis**: Identify what needs to change and potential impacts +3. **Planning**: Develop a detailed plan for implementation +4. **Verification**: Review the plan and ensure it addresses all requirements +5. **Execution**: Switch to Agent mode to implement the plan + +### Example: Planning a refactor + +``` +User: Help me plan a refactor to extract the authentication logic into a separate module + +Plan mode: +1. Reads relevant files to understand current structure +2. Analyzes dependencies and usage patterns +3. Identifies all places that need updates +4. Creates a step-by-step refactoring plan +5. Suggests: "Switch to Agent mode to implement this plan" +``` + +## System message and behavior + +Plan mode uses a dedicated system message that: + +- Instructs the model to focus on understanding and planning +- Emphasizes using only read-only tools +- Reminds the model to suggest switching to Agent mode for implementation +- Encourages thorough analysis before suggesting changes + + + The system message can be customized per model. See [How to + Customize](/features/plan/how-to-customize) for details or see it [directly in + the + code](https://github.com/continuedev/continue/blob/main/core/llm/defaultSystemMessages.ts). + + +## When to use Plan mode vs other modes + +### Use Plan mode when: + +- Exploring unfamiliar codebases +- Planning complex refactors or features +- Debugging and understanding issues +- Reviewing code architecture +- Creating implementation strategies + +### Use Chat mode when: + +- Having discussions without needing file access +- Asking general programming questions +- Getting explanations without exploring code + +### Use Agent mode when: + +- Ready to implement changes +- Need to create or modify files +- Want to run commands or tests +- Implementing a plan developed in Plan mode diff --git a/docs/features/plan/quick-start.mdx b/docs/features/plan/quick-start.mdx new file mode 100644 index 000000000..03a969c4b --- /dev/null +++ b/docs/features/plan/quick-start.mdx @@ -0,0 +1,60 @@ +--- +title: "Quick Start" +--- + +## How to use it + +Plan mode provides a safe environment for understanding and constructing plans without making changes. It equips the Chat model with read-only tools, allowing you to explore, analyze, and plan modifications before executing them. + +### Use Plan + +You can switch to `Plan` in the mode selector below the chat input box. + +![How to select plan mode](/images/mode-select-plan.png) + + + If Plan is disabled with a `Not Supported` message, the selected model or + provider doesn't support tools. See [Model Setup](/features/plan/model-setup) + for more information. + + +### Chat with Plan + +Plan mode lives within the same interface as [Chat](/features/chat/how-it-works) and [Agent](/features/agent/how-it-works), so the same [input](/features/chat/quick-start#1-start-a-conversation) is used to send messages and you can still use the same manual methods of providing context, such as [`@` context providers](/features/chat/quick-start#3-use--for-additional-context) or adding [highlighted code from the editor](/features/chat/quick-start#2-include-code-context). + +#### What makes Plan different + +Unlike Agent mode, Plan mode: +- Only uses read-only tools (file reading, searching, analysis) +- Cannot modify, create, or delete files +- Focuses on understanding and planning rather than execution +- Provides a safe environment for exploration + +### Common use cases + +Plan mode is ideal for: +- **Code exploration**: Understanding how a codebase works +- **Planning refactors**: Analyzing impact before making changes +- **Debugging**: Investigating issues without modifying code +- **Architecture review**: Understanding system design and dependencies +- **Pre-implementation planning**: Thinking through changes before executing + +### Example workflow + +1. **Start in Plan mode** to explore and understand the task +2. **Develop a plan** with the model's help +3. **Switch to Agent mode** when ready to implement changes + +For example, you might say: + +> Help me understand how the authentication system works and plan improvements to add OAuth support + +Plan mode will analyze the existing code, understand the current implementation, and help you create a detailed plan—all without making any changes. + +## Switching to execution + +When you're ready to implement your plan, simply switch to Agent mode using the mode selector or keyboard shortcut (`Cmd/Ctrl + .`). The conversation context carries over, so Agent mode can immediately start implementing the plan you developed. + + + Use the keyboard shortcut `Cmd/Ctrl + .` to quickly cycle between Chat, Plan, and Agent modes. + \ No newline at end of file diff --git a/docs/getting-started/overview.mdx b/docs/getting-started/overview.mdx index c0e0aabd8..d3b6b3269 100644 --- a/docs/getting-started/overview.mdx +++ b/docs/getting-started/overview.mdx @@ -27,7 +27,7 @@ description: "To quickly understand what you can do with Continue, check out eac [Edit](/features/edit/quick-start) is a convenient way to modify code without leaving your current file -![edit](/images/edit-d522442f88e715924b4c9f4c83900e3a.gif) +![edit](/images/edit.gif) Learn more about [Edit](/features/edit/quick-start) @@ -43,4 +43,14 @@ description: "To quickly understand what you can do with Continue, check out eac Learn more about [Agent](/features/agent/quick-start) + + +[Plan](/features/agent/plan-mode) provides a safe environment with read-only tools for exploring code and planning changes + +![plan](/images/plan-mode.gif) + + + Learn more about [Plan](/features/agent/plan-mode) + + diff --git a/docs/guides/custom-code-rag.mdx b/docs/guides/custom-code-rag.mdx index be5c9e50e..24e4ff91f 100644 --- a/docs/guides/custom-code-rag.mdx +++ b/docs/guides/custom-code-rag.mdx @@ -79,7 +79,13 @@ After you've set up your server, you can configure Continue to use it by adding config.yaml ``` -context: - provider: http params: url: https://myserver.com/retrieve name: http description: Custom HTTP Context Provider displayTitle: My Custom Context +context: + - provider: http + params: + url: https://myserver.com/retrieve + name: http + description: Custom HTTP Context Provider + displayTitle: My Custom Context ``` config.json diff --git a/docs/guides/how-to-self-host-a-model.mdx b/docs/guides/how-to-self-host-a-model.mdx index 1a76ebf1c..ddad69551 100644 --- a/docs/guides/how-to-self-host-a-model.mdx +++ b/docs/guides/how-to-self-host-a-model.mdx @@ -25,7 +25,11 @@ Basic authentication can be done with any provider using the `apiKey` field: config.yaml ``` -models: - name: Ollama provider: ollama model: llama2-7b apiKey: +models: + - name: Ollama + provider: ollama + model: llama2-7b + apiKey: ``` config.json @@ -53,7 +57,13 @@ If you need to send custom headers for authentication, you may use the `requestO config.yaml ``` -models: - name: Ollama provider: ollama model: llama2-7b requestOptions: headers: X-Auth-Token: xxx +models: + - name: Ollama + provider: ollama + model: llama2-7b + requestOptions: + headers: + X-Auth-Token: xxx ``` config.json @@ -79,7 +89,15 @@ Similarly if your model requires a Certificate for authentication, you may use t config.yaml ``` -models: - name: Ollama provider: ollama model: llama2-7b requestOptions: clientCertificate: cert: C:\tempollama.pem key: C:\tempollama.key passphrase: c0nt!nu3 +models: + - name: Ollama + provider: ollama + model: llama2-7b + requestOptions: + clientCertificate: + cert: C:\tempollama.pem + key: C:\tempollama.key + passphrase: c0nt!nu3 ``` config.json diff --git a/docs/guides/llama3.1.mdx b/docs/guides/llama3.1.mdx index 87af279fd..a79644343 100644 --- a/docs/guides/llama3.1.mdx +++ b/docs/guides/llama3.1.mdx @@ -21,7 +21,10 @@ Ollama is the fastest way to get up and running with local language models. We r config.yaml ``` -models: - name: Llama 3.1 8b provider: ollama model: llama3.1-8b +models: + - name: Llama 3.1 8b + provider: ollama + model: llama3.1-8b ``` config.json @@ -53,7 +56,11 @@ Groq provides the fastest available inference for open-source language models, i config.yaml ``` -models: - name: Llama 3.3 70b Versatile provider: groq model: llama-3.3-70b-versatile apiKey: +models: + - name: Llama 3.3 70b Versatile + provider: groq + model: llama-3.3-70b-versatile + apiKey: ``` config.json @@ -85,7 +92,11 @@ Together AI provides fast and reliable inference of open-source models. You'll b config.yaml ``` -models: - name: Llama 3.1 405b provider: together model: llama3.1-405b apiKey: +models: + - name: Llama 3.1 405b + provider: together + model: llama3.1-405b + apiKey: ``` config.json @@ -116,7 +127,11 @@ Replicate makes it easy to host and run open-source AI with an API. config.yaml ``` -models: - name: Llama 3.1 405b provider: replicate model: llama3.1-405b apiKey: +models: + - name: Llama 3.1 405b + provider: replicate + model: llama3.1-405b + apiKey: ``` config.json @@ -148,7 +163,11 @@ SambaNova Cloud provides world record Llama3.1 70B/405B serving. config.yaml ``` -models: - name: SambaNova Llama 3.1 405B provider: sambanova model: llama3.1-405b apiKey: +models: + - name: SambaNova Llama 3.1 405B + provider: sambanova + model: llama3.1-405b + apiKey: ``` config.json @@ -180,7 +199,11 @@ Cerebras Inference uses specialized silicon to provides fast inference for the L config.yaml ``` -models: - name: Cerebras Llama 3.1 70B provider: cerebras model: llama3.1-70b apiKey: +models: + - name: Cerebras Llama 3.1 70B + provider: cerebras + model: llama3.1-70b + apiKey: ``` config.json diff --git a/docs/guides/ollama-guide.mdx b/docs/guides/ollama-guide.mdx index caba3c63d..768160137 100644 --- a/docs/guides/ollama-guide.mdx +++ b/docs/guides/ollama-guide.mdx @@ -19,7 +19,14 @@ Before getting started, ensure your system meets these requirements: Choose the installation method for your operating system: ``` -# macOSbrew install ollama# Linuxcurl -fsSL https://ollama.ai/install.sh | sh# Windows# Download from ollama.ai +# macOS +brew install ollama + +# Linux +curl -fsSL https://ollama.ai/install.sh | sh + +# Windows +# Download from ollama.ai ``` ### Step 2: Download Models @@ -27,7 +34,10 @@ Choose the installation method for your operating system: After installing Ollama, download the models you want to use. Here are some popular options: ``` -# Popular models for developmentollama pull llama2ollama pull codellamaollama pull mistral +# Popular models for development +ollama pull llama2 +ollama pull codellama +ollama pull mistral ``` ## Configuration diff --git a/docs/guides/set-up-codestral.mdx b/docs/guides/set-up-codestral.mdx index 2da33a6f6..06c7c01ca 100644 --- a/docs/guides/set-up-codestral.mdx +++ b/docs/guides/set-up-codestral.mdx @@ -18,7 +18,15 @@ title: "How to Set Up Codestral" config.yaml ``` -models: - name: Codestral provider: mistral model: codestral-latest apiKey: apiBase: https://codestral.mistral.ai/v1 roles: - chat - autocomplete +models: + - name: Codestral + provider: mistral + model: codestral-latest + apiKey: + apiBase: https://codestral.mistral.ai/v1 + roles: + - chat + - autocomplete ``` config.json diff --git a/docs/images/edit-model.png b/docs/images/edit-model.png new file mode 100644 index 000000000..f68864956 Binary files /dev/null and b/docs/images/edit-model.png differ diff --git a/docs/images/edit.gif b/docs/images/edit.gif index a1629930c..7f7cd0b15 100644 Binary files a/docs/images/edit.gif and b/docs/images/edit.gif differ diff --git a/docs/images/plan-mode-compressed.gif b/docs/images/plan-mode-compressed.gif new file mode 100644 index 000000000..c3e9d2512 Binary files /dev/null and b/docs/images/plan-mode-compressed.gif differ diff --git a/docs/images/plan-mode-selector.png b/docs/images/plan-mode-selector.png new file mode 100644 index 000000000..b8c4fe232 Binary files /dev/null and b/docs/images/plan-mode-selector.png differ diff --git a/docs/images/plan-mode.gif b/docs/images/plan-mode.gif new file mode 100644 index 000000000..bdfc589fe Binary files /dev/null and b/docs/images/plan-mode.gif differ diff --git a/docs/reference.mdx b/docs/reference.mdx index 9a9381622..670100f24 100644 --- a/docs/reference.mdx +++ b/docs/reference.mdx @@ -61,7 +61,7 @@ Blocks: - `.continue/models` - for models - `.continue/prompts` - for prompts - `.continue/context` - for context providers -- `.continue/docs` - for docs~~~~ +- `.continue/docs` - for docs - `.continue/data` - for data - `.continue/mcpServers` - for MCP Servers @@ -357,8 +357,6 @@ List of documentation sites to index. - `name` (**required**): Name of the documentation site, displayed in dropdowns, etc. - `startUrl` (**required**): Start page for crawling - usually root or intro page for docs - -- `maxDepth`: Maximum link depth for crawling. Default `4` - `favicon`: URL for site favicon (default is `/favicon.ico` from `startUrl`). - `useLocalCrawling`: Skip the default crawler and only crawl using a local crawler. @@ -507,7 +505,6 @@ context: params: startUrl: https://docs.example.com/introduction rootUrl: https://docs.example.com - maxDepth: 3 mcpServers: - name: DevServer command: npm diff --git a/docs/reference/continue-mcp.mdx b/docs/reference/continue-mcp.mdx index 6045d0ff1..bd7d7d3cf 100644 --- a/docs/reference/continue-mcp.mdx +++ b/docs/reference/continue-mcp.mdx @@ -4,54 +4,25 @@ description: Set up an MCP server to search Continue documentation keywords: [mcp, documentation, search, mintlify, reference] --- -The continue-docs MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. This is powered by Mintlify's MCP server generation. +The Continue Documentation MCP Server allows you to search and retrieve information from the Continue documentation directly within your agent conversations. -## Installation +## Set up -### Step 1: Install the MCP Server - -Run the following command to install the continue-docs MCP server: - -```bash -npx mint-mcp add docs.continue.dev -``` - -When prompted, select "All" from the selection menu: - -![mintlify cli selection tree](/images/mintlify-cli-selection-tree.png) - -This command will: - -- Download and install the MCP server locally -- Set up the search tool for Continue documentation -- Create the necessary configuration files - - -Take note of the installation path displayed after running the command above. You'll need to replace in the configuration below with your actual installation path. - -It will look like this: `/path/to/user/.mcp/docs.continue.dev/src/index.js` - - - -### Step 2: Configure Continue +### Configure Continue 1. Create a folder called `.continue/mcpServers` at the top level of your workspace 2. Add a file called `continue-docs-mcp.yaml` to this folder 3. Write the following contents and save: -````yaml title=".continue/mcpServers/continue-docs-mcp.yaml" ```yaml title=".continue/mcpServers/continue-docs-mcp.yaml" name: Continue Documentation MCP version: 0.0.1 schema: v1 mcpServers: - - name: Continue Docs Search - command: node - args: - - "/path/to/user/.mcp/docs.continue.dev/src/index.js" -```` + - uses: continuedev/continue-docs-mcp +``` -### Step 3: Enable Agent Mode +### Enable Agent Mode MCP servers only work in agent mode. Make sure to switch to agent mode in Continue before testing. @@ -62,77 +33,28 @@ Once configured, you can use the MCP server to search Continue documentation: ### Model Configuration Help ``` -Search for model setup instructions in the Continue docs +How do I add Claude 4 Sonnet as a model from Bedrock in Continue? ``` ### Context Providers ``` -Find documentation about context providers and how to configure them +What context providers are available in Continue? ``` -### Autocomplete Setup +### Customization ``` -How do I configure autocomplete in Continue? +How do I add custom rules to my assistant in Continue? ``` -### Slash Commands - -``` -Search for information about custom slash commands -``` - -### Troubleshooting - -``` -Find troubleshooting information for Continue extension issues -``` - -## Test Plan - -Use this test plan to verify your MCP server is working correctly: - -### Prerequisites - -- Continue extension is installed and running -- Agent mode is enabled -- MCP server configuration file exists in `.continue/mcpServers/` - -### Test Cases - -#### 1. Basic Documentation Search - -- **Query**: "Search the Continue docs for information about model setup" -- **Expected**: Returns structured information about configuring models -- **Pass/Fail**: ☐ - -#### 2. Context Provider Documentation - -- **Query**: "Find documentation about context providers in Continue" -- **Expected**: Returns information about available context providers -- **Pass/Fail**: ☐ - -#### 3. Feature-Specific Search - -- **Query**: "How do I configure autocomplete in Continue?" -- **Expected**: Returns autocomplete setup instructions -- **Pass/Fail**: ☐ - -#### 4. MCP Documentation Search - -- **Query**: "Search for MCP server setup instructions" -- **Expected**: Returns MCP configuration information -- **Pass/Fail**: ☐ - ## Troubleshooting ### MCP Server Not Loading -1. **Check configuration**: Ensure your YAML configuration uses the npx command approach -2. **Verify installation**: Run `npx mint-mcp add continue-docs` to confirm the server can be accessed -3. **Check agent mode**: MCP servers only work in agent mode -4. **Restart Continue**: Try restarting the Continue extension +1. **Check configuration**: Ensure your YAML configuration uses the correct `uses` field with `continuedev/continue-docs-mcp` +2. **Check agent mode**: MCP servers only work in agent mode +3. **Restart Continue**: Try restarting the Continue extension ### No Search Results @@ -140,20 +62,6 @@ Use this test plan to verify your MCP server is working correctly: 2. **Check query format**: Try rephrasing your search query 3. **Test with known topics**: Search for well-documented features like "model configuration" -### Permission Issues - -If you encounter permission errors, ensure npx has proper permissions: - -```bash -npm config get prefix -``` - -## Advanced Configuration - -### Using Environment Variables - -You can configure the MCP server with environment variables: - ## Related Documentation - [MCP Overview](/customize/deep-dives/mcp) diff --git a/docs/reference/yaml-migration.mdx b/docs/reference/yaml-migration.mdx index fcff3c644..1e585b0a0 100644 --- a/docs/reference/yaml-migration.mdx +++ b/docs/reference/yaml-migration.mdx @@ -88,7 +88,48 @@ config.json config.yaml ``` -models: - name: GPT-4 provider: openai model: gpt-4 apiKey: defaultCompletionOptions: temperature: 0.5 maxTokens: 2000 roles: - chat - edit - name: My Voyage Reranker provider: voyage apiKey: roles: - rerank - name: My Starcoder provider: ollama model: starcoder2:3b roles: - autocomplete - name: My Ada Embedder provider: openai apiKey: roles: - embed embedOptions: - maxChunkSize: 256 - maxBatchSize: 5 - name: Ollama Autodetect provider: ollama model: AUTODETECT - name: My Open AI Compatible Model - Apply provider: openai model: my-openai-compatible-model apiBase: http://3.3.3.3/v1 requestOptions: headers: X-Auth-Token: roles: - chat - apply +models: + - name: GPT-4 + provider: openai + model: gpt-4 + apiKey: + defaultCompletionOptions: + temperature: 0.5 + maxTokens: 2000 + roles: + - chat + - edit + - name: My Voyage Reranker + provider: voyage + apiKey: + roles: + - rerank + - name: My Starcoder + provider: ollama + model: starcoder2:3b + roles: + - autocomplete + - name: My Ada Embedder + provider: openai + apiKey: + roles: + - embed + embedOptions: + - maxChunkSize: 256 + - maxBatchSize: 5 + - name: Ollama Autodetect + provider: ollama + model: AUTODETECT + - name: My Open AI Compatible Model - Apply + provider: openai + model: my-openai-compatible-model + apiBase: http://3.3.3.3/v1 + requestOptions: + headers: + X-Auth-Token: + roles: + - chat + - apply ``` Note that the `repoMapFileSelection` experimental model role has been deprecated and is only available in `config.json`. @@ -119,7 +160,13 @@ config.json config.yaml ``` -context: - provider: docs - provider: codebase params: nRetrieve: 30 nFinal: 3 - provider: diff +context: + - provider: docs + - provider: codebase + params: + nRetrieve: 30 + nFinal: 3 + - provider: diff ``` ### System Message @@ -139,7 +186,8 @@ config.json config.yaml ``` -rules: - Always give concise responses +rules: + - Always give concise responses ``` ### Prompts @@ -167,7 +215,17 @@ config.json config.yaml ``` -prompts: - name: check description: Check for mistakes in my code prompt: | Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: - Syntax errors - Logic errors - Security vulnerabilities - Performance issues - Anything else that looks wrong Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found. +prompts: + - name: check + description: Check for mistakes in my code + prompt: | + Please read the highlighted code and check for any mistakes. You should look for the following, and be extremely vigilant: + - Syntax errors + - Logic errors + - Security vulnerabilities + - Performance issues + - Anything else that looks wrong + Once you find an error, please explain it as clearly as possible, but without using extra words. For example, instead of saying 'I think there is a syntax error on line 5', you should say 'Syntax error on line 5'. Give your answer as one bullet point per mistake found. ``` ### Documentation @@ -192,7 +250,11 @@ config.json config.yaml ``` -docs: - name: nest.js startUrl: https://docs.nestjs.com/ - name: My site startUrl: https://mysite.com/docs/ +docs: + - name: nest.js + startUrl: https://docs.nestjs.com/ + - name: My site + startUrl: https://mysite.com/docs/ ``` ### MCP Servers @@ -231,7 +293,15 @@ config.json config.yaml ``` -mcpServers: - name: My MCP Server command: uvx args: - mcp-server-sqlite - --db-path - /Users/NAME/test.db env: KEY: +mcpServers: + - name: My MCP Server + command: uvx + args: + - mcp-server-sqlite + - --db-path + - /Users/NAME/test.db + env: + KEY: ``` --- diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx index afafbc5f9..60f197442 100644 --- a/docs/troubleshooting.mdx +++ b/docs/troubleshooting.mdx @@ -92,7 +92,11 @@ If you're seeing a `fetch failed` error and your network requires custom certifi config.yaml ``` -models: - name: My Model ... requestOptions: caBundlePath: /path/to/cert.pem +models: + - name: My Model + ... + requestOptions: + caBundlePath: /path/to/cert.pem ``` config.json diff --git a/extensions/intellij/build.gradle.kts b/extensions/intellij/build.gradle.kts index fb85ded90..8dc8ce738 100644 --- a/extensions/intellij/build.gradle.kts +++ b/extensions/intellij/build.gradle.kts @@ -9,6 +9,8 @@ fun Sync.prepareSandbox() { } val remoteRobotVersion = "0.11.23" +val isEap get() = environment("RELEASE_CHANNEL").orNull == "eap" +val pluginVersion = properties("pluginVersion").get() plugins { id("java") @@ -22,21 +24,14 @@ plugins { } group = properties("pluginGroup").get() +version = if (isEap) "$pluginVersion-eap" else pluginVersion -version = properties("pluginVersion").get() - -// Configure project's dependencies repositories { mavenCentral() maven { url = uri("https://packages.jetbrains.team/maven/p/ij/intellij-dependencies") } } -// Dependencies are managed with Gradle version catalog - read more: -// https://docs.gradle.org/current/userguide/platforms.html#sub:version-catalog dependencies { - implementation("com.squareup.okhttp3:okhttp:4.12.0") { - exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib") - } implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32") implementation("com.posthog.java:posthog:1.+") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0") @@ -48,22 +43,6 @@ dependencies { testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0") testImplementation("com.automation-remarks:video-recorder-junit5:2.0") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") - - - // Exclude vulnerable Log4j from all dependencies - configurations.all { - resolutionStrategy { - eachDependency { - if (requested.group == "log4j" && requested.name == "log4j") { - useTarget("org.slf4j:log4j-over-slf4j:1.7.36") - } - } - } - } - - // Add Log4j 2.x explicitly - implementation("org.apache.logging.log4j:log4j-core:2.20.0") - implementation("org.apache.logging.log4j:log4j-api:2.20.0") testImplementation(kotlin("test")) } @@ -105,7 +84,7 @@ koverReport { defaults { xml { onCheck = true } } } tasks { downloadRobotServerPlugin { - version.set(remoteRobotVersion) + version = remoteRobotVersion } prepareSandbox { @@ -120,13 +99,14 @@ tasks { prepareSandbox() } - wrapper { gradleVersion = properties("gradleVersion").get() } + wrapper { + gradleVersion = properties("gradleVersion").get() + } patchPluginXml { - version.set(properties("pluginVersion")) - sinceBuild.set(properties("pluginSinceBuild")) - untilBuild.set(properties("pluginUntilBuild")) - pluginDescription.set( + sinceBuild = properties("pluginSinceBuild") + untilBuild = properties("pluginUntilBuild") + pluginDescription = providers.fileContents(layout.projectDirectory.file("README.md")).asText.map { val start = "" val end = "" @@ -140,7 +120,6 @@ tasks { subList(indexOf(start) + 1, indexOf(end)).joinToString("\n").let(::markdownToHTML) } } - ) } // Configure UI tests plugin @@ -167,7 +146,7 @@ tasks { // See ContinueExtensionSettingsService.kt for more info. // Currently commented out however since test fail in CI with this version // intellij { -// version.set("2024.1") +// version = "2024.1" // } } @@ -178,17 +157,10 @@ tasks { } publishPlugin { - // dependsOn("patchChangelog") token = environment("PUBLISH_TOKEN") - // The pluginVersion is based on the SemVer (https://semver.org) and supports pre-release - // labels, like 2.1.7-alpha.3 - // Specify pre-release label to publish the plugin in a custom Release Channel automatically. - // Read more: - // https://plugins.jetbrains.com/docs/intellij/deployment.html#specifying-a-release-channel - channels.set(listOf(environment("RELEASE_CHANNEL").getOrElse("eap"))) - // We always hide the stable releases until a few days of EAP have proven them stable - // hidden = environment("RELEASE_CHANNEL").map { it == "stable" }.getOrElse(false) + val channel = if (isEap) "eap" else "default" + channels = listOf(channel) } runIde { diff --git a/extensions/intellij/gradle.properties b/extensions/intellij/gradle.properties index 36cde4116..a1c5d01c1 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.29 +pluginVersion=1.0.30 # 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/auth/ContinueAuthService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt index 13ceaf810..4538b8771 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/auth/ContinueAuthService.kt @@ -1,5 +1,6 @@ package com.github.continuedev.continueintellijextension.auth +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.google.gson.Gson @@ -10,24 +11,22 @@ import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.remoteServer.util.CloudConfigurationUtil.createCredentialAttributes +import com.intellij.util.io.HttpRequests import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import okhttp3.MediaType.Companion.toMediaType -import okhttp3.OkHttpClient -import okhttp3.Request -import okhttp3.RequestBody.Companion.toRequestBody -import java.net.URL +import kotlin.time.Duration.Companion.minutes @Service class ContinueAuthService { private val coroutineScope = CoroutineScope(Dispatchers.IO) + private val log = Logger.getInstance(ContinueAuthService::class.java) companion object { - fun getInstance(): ContinueAuthService = service() private const val CREDENTIALS_USER = "ContinueAuthUser" private const val ACCESS_TOKEN_KEY = "ContinueAccessToken" private const val REFRESH_TOKEN_KEY = "ContinueRefreshToken" @@ -77,73 +76,47 @@ class ContinueAuthService { } private fun updateRefreshToken(token: String) { - // Launch a coroutine to call the suspend function - coroutineScope.launch { - try { - val response = refreshToken(token) - val accessToken = response["accessToken"] as? String - val refreshToken = response["refreshToken"] as? String - val user = response["user"] as? Map<*, *> - val firstName = user?.get("firstName") as? String - val lastName = user?.get("lastName") as? String - val label = "$firstName $lastName" - val id = user?.get("id") as? String - val email = user?.get("email") as? String + try { + val response = refreshToken(token) + val accountLabel = "${response.user.firstName} ${response.user.lastName}" - // Persist the session info - setRefreshToken(refreshToken!!) - val sessionInfo = - ControlPlaneSessionInfo(accessToken!!, ControlPlaneSessionInfo.Account(email!!, label)) - setControlPlaneSessionInfo(sessionInfo) + // Persist the session info + setRefreshToken(response.refreshToken) + val account = ControlPlaneSessionInfo.Account(response.user.email, accountLabel) + val sessionInfo = ControlPlaneSessionInfo(response.accessToken, account) + setControlPlaneSessionInfo(sessionInfo) - // Notify listeners - ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) - .handleUpdatedSessionInfo(sessionInfo) - - } catch (e: Exception) { - // Handle any exceptions - println("Exception while refreshing token: ${e.message}") - } + // Notify listeners + ApplicationManager.getApplication().messageBus.syncPublisher(AuthListener.TOPIC) + .handleUpdatedSessionInfo(sessionInfo) + } catch (e: Exception) { + service().report(e, "Exception while refreshing token ${e.message}") } } private fun setupRefreshTokenInterval() { - // Launch a coroutine to refresh the token every 30 minutes coroutineScope.launch { while (true) { val refreshToken = getRefreshToken() if (refreshToken != null) { updateRefreshToken(refreshToken) } - - kotlinx.coroutines.delay(15 * 60 * 1000) // 15 minutes in milliseconds + log.info("Token refreshed, retrying in 15 minutes") + delay(15.minutes) } } } - private suspend fun refreshToken(refreshToken: String) = withContext(Dispatchers.IO) { - val client = OkHttpClient() - val url = URL(getControlPlaneUrl()).toURI().resolve("/auth/refresh").toURL() - val jsonBody = mapOf("refreshToken" to refreshToken) - val jsonString = Gson().toJson(jsonBody) - val requestBody = jsonString.toRequestBody("application/json".toMediaType()) - - val request = Request.Builder() - .url(url) - .post(requestBody) - .header("Content-Type", "application/json") - .build() - - val response = client.newCall(request).execute() - - val responseBody = response.body?.string() + private fun refreshToken(refreshToken: String): RefreshTokenResponse { val gson = Gson() - val responseMap = gson.fromJson(responseBody, Map::class.java) - - responseMap + val jsonBody = gson.toJson(mapOf("refreshToken" to refreshToken)) + val url = getControlPlaneUrl() + "/auth/refresh" + val response = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE) + .connect { connection -> connection.write(jsonBody.toByteArray()) } + .toString() + return gson.fromJson(response, RefreshTokenResponse::class.java) } - private fun openSignInPage(project: Project, useOnboarding: Boolean): String? { var authUrl: String? = null val coreMessenger = project.service().coreMessenger @@ -256,6 +229,17 @@ class ContinueAuthService { setAccountLabel(info.account.label) } + private data class RefreshTokenResponse( + val accessToken: String, + val refreshToken: String, + val user: User, + ) { + data class User( + val firstName: String, + val lastName: String, + val email: String + ) + } } // Data class to represent the ControlPlaneSessionInfo diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index 8ccb07838..1c0ab242a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -7,9 +7,11 @@ import com.github.continuedev.continueintellijextension.`continue`.process.Conti import com.github.continuedev.continueintellijextension.services.ContinuePluginService import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson +import com.google.gson.JsonSyntaxException import com.intellij.openapi.components.service +import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project -import kotlinx.coroutines.* +import kotlinx.coroutines.CoroutineScope class CoreMessenger( private val project: Project, @@ -20,6 +22,7 @@ class CoreMessenger( private val gson = Gson() private val responseListeners = mutableMapOf Unit>() private val process = startContinueProcess() + private val log = Logger.getInstance(CoreMessenger::class.java) fun request(messageType: String, data: Any?, messageId: String?, onResponse: (Any?) -> Unit) { val id = messageId ?: uuid() @@ -38,13 +41,13 @@ class CoreMessenger( } private fun handleMessage(json: String) { - val responseMap = gson.fromJson(json, Map::class.java) + val responseMap = tryToParse(json) ?: return val messageId = responseMap["messageId"].toString() val messageType = responseMap["messageType"].toString() val data = responseMap["data"] // IDE listeners - if (MessageTypes.IDE_MESSAGE_TYPES.contains(messageType)) { + if (messageType in MessageTypes.IDE_MESSAGE_TYPES) { ideProtocolClient.handleMessage(json) { data -> val message = gson.toJson(mapOf("messageId" to messageId, "messageType" to messageType, "data" to data)) process.write(message) @@ -52,8 +55,9 @@ class CoreMessenger( } // Forward to webview - if (MessageTypes.PASS_THROUGH_TO_WEBVIEW.contains(messageType)) { + if (messageType in MessageTypes.PASS_THROUGH_TO_WEBVIEW) { val continuePluginService = project.service() + // todo: is this a bug below (messageType = ID)? verify continuePluginService.sendToWebview(messageType, responseMap["data"], messageType) } @@ -68,6 +72,15 @@ class CoreMessenger( } } + // todo: map<*, *> = code smell + private fun tryToParse(json: String): Map<*, *>? = + try { + gson.fromJson(json, Map::class.java) + } catch (_: JsonSyntaxException) { + log.warn("Invalid message JSON: $json") // example: NODE_ENV undefined + null + } + fun killSubProcess() { process.close() } 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 08a5e8d18..66ea992a4 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 @@ -8,12 +8,13 @@ import com.github.continuedev.continueintellijextension.editor.DiffStreamService import com.github.continuedev.continueintellijextension.editor.EditorUtils import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.github.continuedev.continueintellijextension.protocol.* -import com.github.continuedev.continueintellijextension.services.* -import com.github.continuedev.continueintellijextension.utils.* +import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings +import com.github.continuedev.continueintellijextension.services.ContinuePluginService +import com.github.continuedev.continueintellijextension.utils.getMachineUniqueID +import com.github.continuedev.continueintellijextension.utils.uuid import com.google.gson.Gson import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.command.WriteCommandAction -import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.components.service import com.intellij.openapi.editor.SelectionModel import com.intellij.openapi.fileEditor.FileEditorManager @@ -21,7 +22,10 @@ import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.wm.ToolWindowManager -import kotlinx.coroutines.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch import java.awt.Toolkit import java.awt.datatransfer.StringSelection @@ -323,7 +327,11 @@ class IdeProtocolClient( } "runCommand" -> { - // Running commands not yet supported in JetBrains + val params = Gson().fromJson( + dataElement.toString(), + RunCommandParams::class.java + ) + ide.runCommand(params.command, params.options) respond(null) } 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 d6980afb8..2f1889fb4 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 @@ -1,4 +1,3 @@ - package com.github.continuedev.continueintellijextension.`continue` import com.github.continuedev.continueintellijextension.* @@ -27,12 +26,14 @@ import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.guessProjectDir -import com.intellij.openapi.util.IconLoader import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFileManager +import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiDocumentManager import com.intellij.testFramework.LightVirtualFile import kotlinx.coroutines.* +import org.jetbrains.plugins.terminal.ShellTerminalWidget +import org.jetbrains.plugins.terminal.TerminalView import java.awt.Toolkit import java.awt.datatransfer.DataFlavor import java.io.BufferedReader @@ -54,7 +55,7 @@ class IntelliJIDE( init { try { val os = getOS() - + if (os == OS.LINUX || os == OS.MAC) { val file = File(ripgrep) if (!file.canExecute()) { @@ -135,7 +136,33 @@ class IntelliJIDE( } override suspend fun getTerminalContents(): String { - return "" + return withContext(Dispatchers.EDT) { + try { + val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal") + + val terminalView = TerminalView.getInstance(project) + // Find the first terminal widget selected, whatever its state, running command or not. + val widget = terminalView.getWidgets().filterIsInstance().firstOrNull { + toolWindow?.getContentManager()?.getContent(it)?.isSelected ?: false + } + + if (widget != null) { + val textBuffer = widget.terminalTextBuffer + val stringBuilder = StringBuilder() + // Iterate through all lines in the buffer (history + screen) + for (i in 0 until textBuffer.historyLinesCount + textBuffer.screenLinesCount) { + stringBuilder.append(textBuffer.getLine(i).text).append('\n') + } + stringBuilder.toString() + } else { + "" // Return empty if no terminal is available + } + } catch (e: Exception) { + println("Error getting terminal contents: ${e.message}") + e.printStackTrace() + "" // Return empty on error + } + } } override suspend fun getDebugLocals(threadIndex: Int): String { @@ -220,8 +247,65 @@ class IntelliJIDE( } } - override suspend fun runCommand(command: String) { - throw NotImplementedError("runCommand not implemented in IntelliJ") + override suspend fun runCommand(command: String, options: TerminalOptions?) { + val terminalOptions = + options ?: TerminalOptions(reuseTerminal = true, terminalName = null, waitForCompletion = false) + + ApplicationManager.getApplication().invokeLater { + try { + val toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal") + toolWindow?.activate({ + try { + val terminalView = TerminalView.getInstance(project) + var widget: ShellTerminalWidget? = null + + // 1. Handle reuseTerminal option + if (terminalOptions.reuseTerminal == true && terminalView.getWidgets().isNotEmpty()) { + // 2. Find by terminalName if provided + if (terminalOptions.terminalName != null) { + widget = terminalView.getWidgets().filterIsInstance() + .firstOrNull { + toolWindow.contentManager.getContent(it).tabName == terminalOptions.terminalName + && !it.hasRunningCommands() + } + } else { + // 3. Find active terminal, or fall back to the first one + widget = terminalView.getWidgets().filterIsInstance() + .firstOrNull { toolWindow.contentManager.getContent(it).isSelected } + ?: terminalView.getWidgets().filterIsInstance().firstOrNull { + !it.hasRunningCommands() + } + } + } + + // 4. Create a new terminal if needed + if (widget == null) { + widget = terminalView.createLocalShellWidget( + project.basePath, + terminalOptions.terminalName, + true + ) + } else { + // Ensure the found widget is visible + val content = toolWindow.contentManager.getContent(widget) + if (content != null) { + toolWindow.contentManager.setSelectedContent(content, true) + } + } + + // 5. Show and send text + widget.ttyConnector?.write(command) + + } catch (e: Exception) { + println("Error during terminal widget handling: ${e.message}") + e.printStackTrace() + } + }, true) + } catch (e: Exception) { + println("Error activating terminal tool window: ${e.message}") + e.printStackTrace() + } + } } override suspend fun saveFile(filepath: String) { @@ -343,7 +427,7 @@ class IntelliJIDE( } val command = GeneralCommandLine(commandArgs) - + command.setWorkDirectory(project.basePath) val results = ExecUtil.execAndGetOutput(command).stdout return results.split("\n") @@ -357,11 +441,12 @@ class IntelliJIDE( throw NotImplementedError("Ripgrep not supported, this workspace is remote") } } + override suspend fun getSearchResults(query: String, maxResults: Int?): String { val ideInfo = this.getIdeInfo() if (ideInfo.remoteName == "local") { try { - val commandArgs = mutableListOf( + val commandArgs = mutableListOf( ripgrep, "-i", "--ignore-file", @@ -372,20 +457,20 @@ class IntelliJIDE( "2", "--heading" ) - + // Conditionally add maxResults flag if (maxResults != null) { commandArgs.add("-m") commandArgs.add(maxResults.toString()) } - + // Add the search query and path commandArgs.add("-e") commandArgs.add(query) commandArgs.add(".") val command = GeneralCommandLine(commandArgs) - + command.setWorkDirectory(project.basePath) return ExecUtil.execAndGetOutput(command).stdout } catch (exception: Exception) { @@ -594,6 +679,14 @@ class IntelliJIDE( throw NotImplementedError("gotoDefinition not implemented yet") } + override suspend fun gotoTypeDefinition(location: Location): List { + throw NotImplementedError("gotoTypeDefinition not implemented yet") + } + + override suspend fun getSignatureHelp(location: Location): SignatureHelp? { + throw NotImplementedError("getSignatureHelp not implemented yet") + } + override fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) { throw NotImplementedError("onDidChangeActiveTextEditor not implemented yet") } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt index bf377e675..bc199b35a 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/protocol/ide.kt @@ -1,6 +1,7 @@ package com.github.continuedev.continueintellijextension.protocol -import com.github.continuedev.continueintellijextension.* +import com.github.continuedev.continueintellijextension.Range +import com.github.continuedev.continueintellijextension.TerminalOptions data class GetControlPlaneSessionInfoParams(val silent: Boolean, val useOnboarding: Boolean) @@ -59,4 +60,6 @@ data class GetGitRootPathParams(val dir: String) data class ListDirParams(val dir: String) -data class GetFileStatsParams(val files: List) \ No newline at end of file +data class GetFileStatsParams(val files: List) + +data class RunCommandParams(val command: String, val options: TerminalOptions?) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt index 4e4117985..057a87593 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinueExtensionSettingsService.kt @@ -1,25 +1,25 @@ package com.github.continuedev.continueintellijextension.services -import com.github.continuedev.continueintellijextension.constants.getConfigJsPath import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath -import com.intellij.execution.target.value.constant +import com.github.continuedev.continueintellijextension.error.ContinueErrorService import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.components.* +import com.intellij.openapi.components.PersistentStateComponent +import com.intellij.openapi.components.State +import com.intellij.openapi.components.Storage +import com.intellij.openapi.components.service import com.intellij.openapi.options.Configurable import com.intellij.openapi.project.DumbAware -import com.intellij.openapi.util.SystemInfo import com.intellij.util.concurrency.AppExecutorUtil +import com.intellij.util.io.HttpRequests import com.intellij.util.messages.Topic -import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json -import okhttp3.OkHttpClient -import okhttp3.Request import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.io.File import java.io.IOException +import java.net.URL import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import javax.swing.* @@ -72,11 +72,10 @@ class ContinueSettingsComponent : DumbAware { } } -@Serializable -class ContinueRemoteConfigSyncResponse { - var configJson: String? = null - var configJs: String? = null -} +data class ContinueRemoteConfigSyncResponse( + var configJson: String?, + var configJs: String? +) @State( name = "com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings", @@ -117,50 +116,23 @@ open class ContinueExtensionSettings : PersistentStateComponent - if (!response.isSuccessful) throw IOException("Unexpected code $response") - - response.body?.string()?.let { responseBody -> - try { - configResponse = - Json.decodeFromString(responseBody) - } catch (e: Exception) { - e.printStackTrace() - return - } - } - } + val url = "$baseUrl/sync" + val responseBody = HttpRequests.post(url, HttpRequests.JSON_CONTENT_TYPE) + .tuner { connection -> + if (token != null) + connection.addRequestProperty("Authorization", "Bearer $token") + }.readString() + val response = Json.decodeFromString(responseBody) + val file = File(getConfigJsonPath(URL(url).host)) + response.configJs.let { file.writeText(it!!) } + response.configJson.let { file.writeText(it!!) } } catch (e: IOException) { - e.printStackTrace() - return - } - - if (configResponse?.configJson?.isNotEmpty()!!) { - val file = File(getConfigJsonPath(request.url.host)) - file.writeText(configResponse!!.configJson!!) - } - - if (configResponse?.configJs?.isNotEmpty()!!) { - val file = File(getConfigJsPath(request.url.host)) - file.writeText(configResponse!!.configJs!!) + service().report(e, "Unexpected exception during remote config sync") } } } @@ -174,7 +146,7 @@ open class ContinueExtensionSettings : PersistentStateComponent, + + /** + * The active signature. + */ + val activeSignature: Int, + + /** + * The active parameter of the active signature. + */ + val activeParameter: Int +) + +/** + * Represents the signature of something callable. A signature + * can have a label, like a function-name, a doc-comment, and + * a set of parameters. + */ +data class SignatureInformation( + /** + * The label of this signature. Will be shown in + * the UI. + */ + val label: String, + + /** + * The parameters of this signature. + */ + val parameters: List, + + /** + * The index of the active parameter. + * + * If provided, this is used in place of [SignatureHelp.activeParameter]. + */ + val activeParameter: Int? = null +) + +/** + * Represents a parameter of a callable-signature. A parameter can + * have a label and a doc-comment. + */ +data class ParameterInformation( + /** + * The label of this signature. + * + * Either a string or inclusive start and exclusive end offsets within its containing + * [SignatureInformation.label] signature label. *Note*: A label of type string must be + * a substring of its containing signature information's [SignatureInformation.label] label. + */ + val label: String // Note: Kotlin doesn't have union types, so this represents the string case +) + data class ControlPlaneSessionInfo( val accessToken: String, val account: Account @@ -91,6 +153,11 @@ data class ContinueRcJson( val mergeBehavior: ConfigMergeType ) +data class TerminalOptions( + val reuseTerminal: Boolean?, + val terminalName: String?, + val waitForCompletion: Boolean? +) interface IDE { suspend fun getIdeInfo(): IdeInfo @@ -134,7 +201,7 @@ interface IDE { suspend fun openUrl(url: String) - suspend fun runCommand(command: String) + suspend fun runCommand(command: String, options: TerminalOptions?) suspend fun saveFile(filepath: String) @@ -192,6 +259,8 @@ interface IDE { // LSP suspend fun gotoDefinition(location: Location): List + suspend fun gotoTypeDefinition(location: Location): List + suspend fun getSignatureHelp(location: Location): SignatureHelp? // Callbacks fun onDidChangeActiveTextEditor(callback: (filepath: String) -> Unit) @@ -253,4 +322,4 @@ data class ShowFilePayload( sealed class FimResult { data class FimEdit(val fimText: String) : FimResult() object NotFimEdit : FimResult() -} \ No newline at end of file +} diff --git a/extensions/intellij/src/main/resources/META-INF/plugin.xml b/extensions/intellij/src/main/resources/META-INF/plugin.xml index 951338698..15a0dd864 100644 --- a/extensions/intellij/src/main/resources/META-INF/plugin.xml +++ b/extensions/intellij/src/main/resources/META-INF/plugin.xml @@ -7,6 +7,7 @@ GitHub]]> com.intellij.modules.platform + org.jetbrains.plugins.terminal diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index a47f507d1..a813e7b95 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.65", + "version": "1.1.66", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" diff --git a/extensions/vscode/src/VsCodeIde.ts b/extensions/vscode/src/VsCodeIde.ts index f620cd457..a8ce254ad 100644 --- a/extensions/vscode/src/VsCodeIde.ts +++ b/extensions/vscode/src/VsCodeIde.ts @@ -6,7 +6,10 @@ import { EXTENSION_NAME } from "core/control-plane/env"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import { executeGotoProvider } from "./autocomplete/lsp"; +import { + executeGotoProvider, + executeSignatureHelpProvider, +} from "./autocomplete/lsp"; import { Repository } from "./otherExtensions/git"; import { SecretStorage } from "./stubs/SecretStorage"; import { VsCodeIdeUtils } from "./util/ideUtils"; @@ -24,6 +27,7 @@ import type { Location, Problem, RangeInFile, + SignatureHelp, TerminalOptions, Thread, } from "core"; @@ -87,6 +91,28 @@ class VsCodeIde implements IDE { return result; } + async gotoTypeDefinition(location: Location): Promise { + const result = await executeGotoProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeTypeDefinitionProvider", + }); + + return result; + } + + async getSignatureHelp(location: Location): Promise { + const result = await executeSignatureHelpProvider({ + uri: vscode.Uri.parse(location.filepath), + line: location.position.line, + character: location.position.character, + name: "vscode.executeSignatureHelpProvider", + }); + + return result; + } + onDidChangeActiveTextEditor(callback: (uri: string) => void): void { vscode.window.onDidChangeActiveTextEditor((editor) => { if (editor) { diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index a6900291a..c3d5c11a4 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -13,7 +13,13 @@ import { intersection } from "core/util/ranges"; import * as URI from "uri-js"; import * as vscode from "vscode"; -import type { IDE, Range, RangeInFile, RangeInFileWithContents } from "core"; +import type { + IDE, + Range, + RangeInFile, + RangeInFileWithContents, + SignatureHelp, +} from "core"; import type Parser from "web-tree-sitter"; type GotoProviderName = @@ -23,6 +29,8 @@ type GotoProviderName = | "vscode.executeImplementationProvider" | "vscode.executeReferenceProvider"; +type SignatureHelpProviderName = "vscode.executeSignatureHelpProvider"; + interface GotoInput { uri: vscode.Uri; line: number; @@ -33,8 +41,19 @@ function gotoInputKey(input: GotoInput) { return `${input.name}${input.uri.toString()}${input.line}${input.character}`; } +interface SignatureHelpInput { + uri: vscode.Uri; + line: number; + character: number; + name: SignatureHelpProviderName; +} +function signatureHelpKey(input: SignatureHelpInput) { + return `${input.name}${input.uri.toString()}${input.line}${input.character}`; +} + const MAX_CACHE_SIZE = 500; const gotoCache = new Map(); +const signatureHelpCache = new Map(); export async function executeGotoProvider( input: GotoInput, @@ -382,3 +401,36 @@ export const getDefinitionsFromLsp: GetLspDefinitionsFunction = async ( return []; } }; + +export async function executeSignatureHelpProvider( + input: SignatureHelpInput, +): Promise { + const cacheKey = signatureHelpKey(input); + const cached = signatureHelpCache.get(cacheKey); + if (cached) { + return cached; + } + + try { + const definitions = (await vscode.commands.executeCommand( + input.name, + input.uri, + new vscode.Position(input.line, input.character), + )) as SignatureHelp; + + // Add to cache + if (signatureHelpCache.size >= MAX_CACHE_SIZE) { + // Remove the oldest item from the cache + const oldestKey = signatureHelpCache.keys().next().value; + if (oldestKey) { + signatureHelpCache.delete(oldestKey); + } + } + signatureHelpCache.set(cacheKey, definitions); + + return definitions; + } catch (e) { + console.warn(`Error executing ${input.name}:`, e); + return null; + } +} diff --git a/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm new file mode 100644 index 000000000..02de34466 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/hole-queries/typescript.scm @@ -0,0 +1,59 @@ +;; Capture the variable/function name +(variable_declarator + name: (identifier) @function.name + type: (type_annotation + (function_type) @function.type)) + +;; Capture the full parameter list +(function_type + parameters: (formal_parameters) @function.params) + +;; Capture the type identifiers used in the parameters +(formal_parameters + (required_parameter + type: (type_annotation + (type_identifier) @param.type)) + (required_parameter + type: (type_annotation + (type_identifier) @param.type))) + +;; Capture the return type of the function +(function_type + return_type: (type_identifier) @return.type) + +;; Capture any parse errors (e.g., the `@`) +(ERROR) @error.node + +;; Capture the entire function declaration line +(lexical_declaration) @function.decl + +;; Matches import declarations like: import { A, B } from "module"; +(import_statement + (import_clause + (named_imports + (import_specifier + name: (identifier) @import.name))) + source: (string) @import.source) + +;; Capture standalone function declarations +(function_declaration + name: (identifier) @function.name) @function.decl + +;; Capture the function signature including parameters and return type +(function_declaration + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) + +;; For function expressions or arrow functions +(function_type + parameters: (formal_parameters) @function.params) @function.decl + +;; For arrow functions +(arrow_function + parameters: (formal_parameters) @function.params) @function.decl + +;; For function signatures without a body (like in your example) +(function_signature + name: (identifier) @function.name + parameters: (formal_parameters) @function.params + return_type: (type_annotation)? @function.type) @function.decl diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm new file mode 100644 index 000000000..02b0bda77 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-headers-queries/typescript-get-toplevel-headers.scm @@ -0,0 +1,22 @@ +;; Match top-level `var`, `let`, or `const` declarations +(lexical_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +(variable_declaration + (variable_declarator + name: (identifier) @top.var.name + type: (type_annotation + (_) @top.var.type))) @top.var.decl + +;; Match function declarations +(function_declaration + name: (identifier) @top.fn.name + parameters: (formal_parameters + (required_parameter + pattern: (identifier) @top.fn.param.name + type: (type_annotation (_) @top.fn.param.type)))* + + return_type: (type_annotation (_) @top.fn.type)?) @top.fn.decl diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm new file mode 100644 index 000000000..b5051cb77 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-extract-identifiers.scm @@ -0,0 +1,10 @@ +;; Capture the type alias name (left-hand side) +; (type_alias_declaration +; name: (type_identifier) @type.name) + +;; Capture all identifiers on the right-hand side (value), recursively +; (type_alias_declaration +; value: (_) @type.value) + +;; Match all identifiers inside the type value — deeply nested +(type_identifier) @type.identifier diff --git a/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm new file mode 100644 index 000000000..b26180e05 --- /dev/null +++ b/extensions/vscode/tree-sitter/static-context-queries/relevant-types-queries/typescript-find-typedecl-given-typeidentifier.scm @@ -0,0 +1,11 @@ +(type_alias_declaration + name: (type_identifier) @type.identifier + value: (_) @type.value) + +(interface_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) + +(enum_declaration + name: (type_identifier) @type.identifier + body: (_) @type.value) diff --git a/gui/src/components/History/HistoryTableRow.tsx b/gui/src/components/History/HistoryTableRow.tsx index 65c99233c..0143b1488 100644 --- a/gui/src/components/History/HistoryTableRow.tsx +++ b/gui/src/components/History/HistoryTableRow.tsx @@ -79,7 +79,7 @@ export function HistoryTableRow({ navigate("/"); }} > -
+ {editing ? (
*/}
-
+ {hovered && !editing && ( -
+ { @@ -136,7 +136,7 @@ export function HistoryTableRow({ > -
+ )} ); diff --git a/gui/src/components/StepContainer/ConversationSummary.tsx b/gui/src/components/StepContainer/ConversationSummary.tsx index 78c3043f9..6980ba5f7 100644 --- a/gui/src/components/StepContainer/ConversationSummary.tsx +++ b/gui/src/components/StepContainer/ConversationSummary.tsx @@ -1,9 +1,12 @@ import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/solid"; +import { TrashIcon } from "@heroicons/react/24/outline"; import { ChatHistoryItem } from "core"; import { useState } from "react"; import { AnimatedEllipsis } from "../"; import { useAppSelector } from "../../redux/hooks"; import StyledMarkdownPreview from "../StyledMarkdownPreview"; +import { useDeleteCompaction } from "../../util/compactConversation"; +import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip"; interface ConversationSummaryProps { item: ChatHistoryItem; @@ -15,6 +18,7 @@ export default function ConversationSummary(props: ConversationSummaryProps) { const isLoading = useAppSelector( (state) => state.session.compactionLoading[props.index] || false, ); + const deleteCompaction = useDeleteCompaction(); if (!props.item.conversationSummary && !isLoading) { return null; @@ -47,7 +51,16 @@ export default function ConversationSummary(props: ConversationSummaryProps) { ) : ( )} - Conversation Summary + Conversation Summary + { + e.stopPropagation(); + deleteCompaction(props.index); + }} + > + + {open && ( <> diff --git a/gui/src/components/StepContainer/ResponseActions.tsx b/gui/src/components/StepContainer/ResponseActions.tsx index 96cb1bab1..068432792 100644 --- a/gui/src/components/StepContainer/ResponseActions.tsx +++ b/gui/src/components/StepContainer/ResponseActions.tsx @@ -7,13 +7,11 @@ import { import { ChatHistoryItem } from "core"; import { modelSupportsTools } from "core/llm/autodetect"; import { renderChatMessage } from "core/util/messageContent"; -import { useContext, useMemo } from "react"; -import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useMemo } from "react"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; -import { setCompactionLoading } from "../../redux/slices/sessionSlice"; import { setDialogMessage, setShowDialog } from "../../redux/slices/uiSlice"; -import { loadSession } from "../../redux/thunks/session"; +import { useCompactConversation } from "../../util/compactConversation"; import { FeedbackButtons } from "../FeedbackButtons"; import { GenerateRuleDialog } from "../GenerateRuleDialog"; import { CopyIconButton } from "../gui/CopyIconButton"; @@ -37,49 +35,56 @@ export default function ResponseActions({ isLast, }: ResponseActionsProps) { const dispatch = useAppDispatch(); - const ideMessenger = useContext(IdeMessengerContext); - const currentSessionId = useAppSelector((state) => state.session.id); const selectedModel = useAppSelector(selectSelectedChatModel); + const contextPercentage = useAppSelector( + (state) => state.session.contextPercentage, + ); + const isPruned = useAppSelector((state) => state.session.isPruned); const ruleGenerationSupported = useMemo(() => { return selectedModel && modelSupportsTools(selectedModel); }, [selectedModel]); + const percent = Math.round((contextPercentage ?? 0) * 100); + const buttonColorClass = + isLast && (isPruned || percent > 80) + ? "text-warning" + : "text-description-muted"; + + const showLabel = isLast && (isPruned || percent >= 60); + + const compactConversation = useCompactConversation(); + const onGenerateRule = () => { dispatch(setShowDialog(true)); dispatch(setDialogMessage()); }; - const onCompactConversation = async () => { - if (!currentSessionId) { - return; - } - - try { - // Set loading state - dispatch(setCompactionLoading({ index, loading: true })); - - await ideMessenger.request("conversation/compact", { - index, - sessionId: currentSessionId, - }); - - // Reload the current session to refresh the conversation state - dispatch( - loadSession({ - sessionId: currentSessionId, - saveCurrentSession: false, - }), - ); - } catch (error) { - console.error("Error compacting conversation:", error); - } finally { - // Clear loading state - dispatch(setCompactionLoading({ index, loading: false })); - } - }; - return (
+ compactConversation(index)} + > +
+ + {showLabel && ( + + Compact conversation + + )} +
+
+ {isLast && ruleGenerationSupported && ( )} - - - - state.session.history[props.index + 1], ); - const warningMessage = useAppSelector( - (state) => state.session.warningMessage, - ); const uiConfig = useAppSelector(selectUIConfig); // Calculate dimming and indicator state based on latest summary index diff --git a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx index da0e439c0..4d6aa97bd 100644 --- a/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx +++ b/gui/src/components/StyledMarkdownPreview/StepContainerPreToolbar/RunInTerminalButton.tsx @@ -2,7 +2,6 @@ import { CommandLineIcon } from "@heroicons/react/24/outline"; import { useContext } from "react"; import { lightGray, vscForeground } from "../.."; import { IdeMessengerContext } from "../../../context/IdeMessenger"; -import { isJetBrains } from "../../../util"; import { extractCommand } from "../utils/commandExtractor"; interface RunInTerminalButtonProps { @@ -12,11 +11,6 @@ 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; - } - function runInTerminal() { // Extract just the command line const extractedCommand = extractCommand(command); diff --git a/gui/src/components/console/Details.tsx b/gui/src/components/console/Details.tsx index fd0545763..915ad9b26 100644 --- a/gui/src/components/console/Details.tsx +++ b/gui/src/components/console/Details.tsx @@ -117,6 +117,11 @@ export default function Details({ interaction }: DetailsProps) { format={(v: number) => v.toFixed(1)} >
+ {/* {summary.costBreakdown && ( +
+            {summary.costBreakdown.breakdown}
+          
+ )} */}
(undefined); + const [showTotalUsage, setShowTotalUsage] = useState(false); const interaction = selectedId ? llmLog.interactions.get(selectedId) @@ -16,14 +18,46 @@ export default function Layout() {
Loading...
) : (
- { - setSelectedId(interactionId); - }} - > - {interaction && ( -
+
+ {/*
+ +
*/} +
+ { + setSelectedId(interactionId); + }} + > + {interaction && ( +
+ )} +
+
+ + {/* Full-screen popover for TotalUsage */} + {showTotalUsage && ( +
+
+ {/* Close button */} + + + {/* Content container with scroll */} +
+ +
+
+
)}
); diff --git a/gui/src/components/console/Message.tsx b/gui/src/components/console/Message.tsx index 8c5c35bc6..b15ca3e4a 100644 --- a/gui/src/components/console/Message.tsx +++ b/gui/src/components/console/Message.tsx @@ -48,7 +48,9 @@ export function renderMessage(message: ChatMessage, includeRole: boolean) { {includeRole ? renderMessageRole(message.role) : ""} {message.toolCalls ? message.toolCalls.map((toolCall) => ( -
Tool call: {JSON.stringify(toolCall, undefined, 2)}
+
+                  Tool call: {JSON.stringify(toolCall, undefined, 2)}
+                
)) : ""} {renderMessageContent(message)} diff --git a/gui/src/components/console/TotalUsage.tsx b/gui/src/components/console/TotalUsage.tsx new file mode 100644 index 000000000..f5a9819cc --- /dev/null +++ b/gui/src/components/console/TotalUsage.tsx @@ -0,0 +1,362 @@ +import { calculateRequestCost } from "core/llm/utils/calculateRequestCost"; +import React, { useMemo, useState } from "react"; +import { LLMLog } from "../../hooks/useLLMLog"; +import useTotalUsage from "../../hooks/useTotalUsage"; + +interface TotalUsageProps { + llmLog: LLMLog; +} + +const StatCard: React.FC<{ label: string; value: number; color?: string }> = ({ + label, + value, + color = "var(--vscode-foreground)", +}) => ( +
+
+ {label} +
+
+ {value.toLocaleString()} +
+
+); + +const CostChart: React.FC<{ llmLog: LLMLog }> = ({ llmLog }) => { + const chartData = useMemo(() => { + let cumulativeCost = 0; + const dataPoints: { interaction: number; cost: number }[] = []; + + llmLog.order.forEach((id, index) => { + const interaction = llmLog.interactions.get(id); + + // Calculate cost for this interaction if we have the necessary data + if ( + interaction?.end?.usage && + interaction.start?.provider && + interaction.start?.options?.model + ) { + const costBreakdown = calculateRequestCost( + interaction.start.provider, + interaction.start.options.model, + interaction.end.usage, + ); + if (costBreakdown) { + cumulativeCost += costBreakdown.cost; + } + } + + dataPoints.push({ interaction: index + 1, cost: cumulativeCost }); + }); + + return dataPoints; + }, [llmLog.order, llmLog.interactions]); + + if (chartData.length === 0 || chartData[chartData.length - 1].cost === 0) { + return null; + } + + const maxCost = Math.max(...chartData.map((d) => d.cost)); + const maxInteraction = chartData.length; + const chartWidth = 400; + const chartHeight = 200; + const padding = 40; + + const xScale = (interaction: number) => + ((interaction - 1) / (maxInteraction - 1)) * (chartWidth - 2 * padding) + + padding; + + const yScale = (cost: number) => + chartHeight - padding - (cost / maxCost) * (chartHeight - 2 * padding); + + const pathData = chartData + .map( + (d, i) => + `${i === 0 ? "M" : "L"} ${xScale(d.interaction)} ${yScale(d.cost)}`, + ) + .join(" "); + + return ( +
+

+ Cumulative Cost Over Interactions +

+
+ + {/* Grid lines */} + + + + + + + + {/* Chart area background */} + + + {/* Cost line */} + + + {/* Data points */} + {chartData.map((d, i) => ( + + ))} + + {/* Y-axis labels */} + {[0, 0.25, 0.5, 0.75, 1].map((ratio) => { + const cost = maxCost * ratio; + const y = yScale(cost); + return ( + + + + ${cost.toFixed(4)} + + + ); + })} + + {/* X-axis labels */} + {[0, 0.25, 0.5, 0.75, 1].map((ratio) => { + const interaction = Math.round(1 + ratio * (maxInteraction - 1)); + const x = xScale(interaction); + return ( + + + + {interaction} + + + ); + })} + + {/* Axis labels */} + + Interaction Number + + + Cumulative Cost ($) + + +
+
+ ); +}; + +const TotalUsage: React.FC = ({ llmLog }) => { + const totalUsage = useTotalUsage(llmLog); + const [showCostBreakdown, setShowCostBreakdown] = useState(false); + + return ( +
+
+

+ Total Usage Summary +

+
+ {totalUsage.totalCost > 0 && ( + + )} +
+ {totalUsage.totalInteractions} interactions +
+
+
+ + {showCostBreakdown && totalUsage.costBreakdowns.length > 0 && ( +
+

+ Cost Breakdown +

+
+ {totalUsage.costBreakdowns.map((breakdown, index) => ( +
+
+                  {breakdown.breakdown}
+                
+
+ ))} +
+
+ )} + +
+ + + + +
+ + {totalUsage.totalCost > 0 && ( + <> + +
+
+
+ Total Cost +
+
+ ${totalUsage.totalCost.toFixed(6)} +
+
+ {totalUsage.costBreakdowns.length} cost calculations +
+
+
+ + )} + + {totalUsage.totalCacheWriteTokens > 0 && ( +
+ +
+
+ Cache Hit Rate:{" "} + {totalUsage.totalPromptTokens > 0 + ? ( + (totalUsage.totalCachedTokens / + totalUsage.totalPromptTokens) * + 100 + ).toFixed(1) + : "0"} + % +
+
+
+ )} + +
+
+
+ {totalUsage.totalSuccessfulInteractions} +
+
+ Success +
+
+
+
+ {totalUsage.totalErrorInteractions} +
+
+ Error +
+
+
+
+ {totalUsage.totalCancelledInteractions} +
+
+ Cancelled +
+
+
+
+ ); +}; + +export default TotalUsage; diff --git a/gui/src/components/mainInput/ContextStatus.tsx b/gui/src/components/mainInput/ContextStatus.tsx new file mode 100644 index 000000000..7a97c2768 --- /dev/null +++ b/gui/src/components/mainInput/ContextStatus.tsx @@ -0,0 +1,84 @@ +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { saveCurrentSession } from "../../redux/thunks/session"; +import { useCompactConversation } from "../../util/compactConversation"; +import { ToolTip } from "../gui/Tooltip"; + +const ContextStatus = () => { + const dispatch = useAppDispatch(); + const contextPercentage = useAppSelector( + (state) => state.session.contextPercentage, + ); + const history = useAppSelector((state) => state.session.history); + const percent = Math.round((contextPercentage ?? 0) * 100); + const isPruned = useAppSelector((state) => state.session.isPruned); + + const compactConversation = useCompactConversation(); + if (!isPruned && percent < 60) { + return null; + } + + const barColorClass = isPruned ? "bg-error" : "bg-description"; + + return ( +
+ +
+ + {`${percent}% of context filled.`} + + {isPruned && ( + + {`Oldest messages are being removed.`} + + )} + {history.length > 0 && ( +
+
+ compactConversation(history.length - 1)} + > + Compact conversation + + {"\n"} + { + dispatch( + saveCurrentSession({ + openNewSession: true, + generateTitle: false, + }), + ); + }} + > + Start a new session + +
+
+ )} +
+
+
+
+
+
+ ); +}; + +export default ContextStatus; diff --git a/gui/src/components/mainInput/ContinueInputBox.tsx b/gui/src/components/mainInput/ContinueInputBox.tsx index d95a0a118..c731b761b 100644 --- a/gui/src/components/mainInput/ContinueInputBox.tsx +++ b/gui/src/components/mainInput/ContinueInputBox.tsx @@ -10,9 +10,6 @@ import { GradientBorder } from "./GradientBorder"; import { ToolbarOptions } from "./InputToolbar"; import { Lump } from "./Lump"; import { TipTapEditor } from "./TipTapEditor"; -import WarningMessageBox from "./WarningMessageBox"; -import EditConfigAction from "./WarningMessageBox/Actions/EditConfigAction"; -import NewSessionAction from "./WarningMessageBox/Actions/NewSessionAction"; interface ContinueInputBoxProps { isLastUserInput: boolean; @@ -43,9 +40,6 @@ const EDIT_DISALLOWED_CONTEXT_PROVIDERS = [ function ContinueInputBox(props: ContinueInputBoxProps) { const isStreaming = useAppSelector((state) => state.session.isStreaming); - const warningMessage = useAppSelector( - (state) => state.session.warningMessage, - ); const availableSlashCommands = useAppSelector( selectSlashCommandComboBoxInputs, ); @@ -125,19 +119,6 @@ function ContinueInputBox(props: ContinueInputBoxProps) { />
)} - {props.isLastUserInput && - warningMessage && - (warningMessage.category === "exceeded-context-length" ? ( - - ) : ( - - ))} ); } diff --git a/gui/src/components/mainInput/InlineErrorMessage.tsx b/gui/src/components/mainInput/InlineErrorMessage.tsx new file mode 100644 index 000000000..d23fc7813 --- /dev/null +++ b/gui/src/components/mainInput/InlineErrorMessage.tsx @@ -0,0 +1,48 @@ +import { useContext } from "react"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppDispatch, useAppSelector } from "../../redux/hooks"; +import { setInlineErrorMessage } from "../../redux/slices/sessionSlice"; + +export type InlineErrorMessageType = "out-of-context"; + +export default function InlineErrorMessage() { + const dispatch = useAppDispatch(); + const ideMessenger = useContext(IdeMessengerContext); + const inlineErrorMessage = useAppSelector( + (state) => state.session.inlineErrorMessage, + ); + if (inlineErrorMessage === "out-of-context") { + return ( +
+

+ {`Message exceeds context limit.`} +

+
+
{ + ideMessenger.post("config/openProfile", { + profileId: undefined, + }); + }} + > + Open config + Config +
+ | + { + dispatch(setInlineErrorMessage(undefined)); + }} + > + Hide + +
+
+ ); + } + return null; +} diff --git a/gui/src/components/mainInput/InputToolbar.tsx b/gui/src/components/mainInput/InputToolbar.tsx index 4967c9d90..9be9f25d9 100644 --- a/gui/src/components/mainInput/InputToolbar.tsx +++ b/gui/src/components/mainInput/InputToolbar.tsx @@ -19,6 +19,7 @@ import ModelSelect from "../modelSelection/ModelSelect"; import { ModeSelect } from "../ModeSelect"; import { Button } from "../ui"; import { useFontSize } from "../ui/font"; +import ContextStatus from "./ContextStatus"; import HoverItem from "./InputToolbar/HoverItem"; export interface ToolbarOptions { @@ -170,6 +171,7 @@ function InputToolbar(props: InputToolbarProps) { fontSize: tinyFont, }} > + {!isInEdit && } {!props.toolbarOptions?.hideUseCodebase && !isInEdit && (