diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml deleted file mode 100644 index 277b5f50f..000000000 --- a/.github/workflows/main.yaml +++ /dev/null @@ -1,211 +0,0 @@ -name: Publish Extension - -on: - push: - branches: - - main - -jobs: - build: - strategy: - matrix: - include: - - os: windows-latest - platform: win32 - arch: x64 - npm_config_arch: x64 - - os: windows-latest - platform: win32 - arch: arm64 - npm_config_arch: arm - - os: ubuntu-latest - platform: linux - arch: x64 - npm_config_arch: x64 - - os: ubuntu-latest - platform: linux - arch: arm64 - npm_config_arch: arm64 - - os: ubuntu-latest - platform: linux - arch: armhf - npm_config_arch: arm - - os: ubuntu-latest - platform: alpine - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: arm64 - npm_config_arch: arm64 - runs-on: ${{ matrix.os }} - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - - name: Make sure version isn't odd - run: | - cd extensions/vscode - node versionCheck.js - - # 2. Install npm dependencies - - name: Use Node.js 19.0.0 - uses: actions/setup-node@v4 - with: - node-version: 19.0.0 - - - name: Cache extension node_modules - uses: actions/cache@v3 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Install global Dependencies - run: | - npm install -g cargo-cp-artifact - - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Install gui Dependencies - run: | - cd gui - npm ci --legacy-peer-deps - - - name: Install Core Dependencies - run: | - cd core - npm ci --legacy-peer-deps - - # 2.5. Pre package - - name: Make the out/node_modules directory - run: | - cd extensions/vscode - mkdir out - cd out - mkdir node_modules - - - name: Set var for environment info - shell: pwsh - run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV - - - name: Prepackage the extension - run: | - cd extensions/vscode - npm run prepackage -- --target ${{ env.target }} - - # 3. Run tests for the extension - - # - name: Install Xvfb for Linux and run tests - # run: | - # sudo apt-get install -y xvfb # Install Xvfb - # Xvfb :99 & # Start Xvfb - # export DISPLAY=:99 # Export the display number to the environment - # cd extensions/vscode - # npm run test - # if: matrix.os == 'ubuntu-latest' - - # - name: Run extension tests - # run: | - # cd extensions/vscode - # npm run test - # if: matrix.os != 'ubuntu-latest' - - # 4. Package the extension - - name: Re-install esbuild - run: | - cd extensions/vscode - npm install -f esbuild - - - name: Package the extension - run: cd extensions/vscode && npx vsce package --target ${{ env.target }} - - # 5. Upload the .vsix as an artifact - - uses: actions/upload-artifact@v2 - with: - name: ${{ env.target }} - path: "extensions/vscode/*.vsix" - - publish: - runs-on: ubuntu-latest - needs: - - build - permissions: - contents: write - steps: - # 0. Setup git - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - - - name: Pull latest changes - run: git pull origin main - - # 1. Download the artifacts - - uses: actions/download-artifact@v3 - - # 2. Publish the extension to VS Code Marketplace - - name: Publish to VS Code Marketplace - run: | - cd extensions/vscode - npx vsce publish --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix - env: - VSCE_PAT: ${{ secrets.VSCE_TOKEN }} - - # 3. Publish the extension to Open VSX Registry - - name: Publish (Open VSX Registry) - run: | - cd extensions/vscode - npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix - - # 4. Update the package.json version and push changes - - name: Update version in package.json - run: | - cd extensions/vscode - npm version patch - - - name: Commit changes - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - git commit -am "💚 Update package.json version [skip ci]" - - - name: Push changes - uses: ad-m/github-push-action@master - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ github.ref }} - - # 5 Send to Discord Webhook - - name: Discord Commits - uses: Sniddl/discord-commits@1.7 - with: - webhook: ${{ secrets.DISCORD_WEBHOOK }} - template: "avatar-with-link" - include-extras: true diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml deleted file mode 100644 index 14d5da38e..000000000 --- a/.github/workflows/preview.yaml +++ /dev/null @@ -1,198 +0,0 @@ -name: Publish Preview Extension - -on: - push: - branches: - - preview - -jobs: - build: - strategy: - matrix: - include: - - os: windows-latest - platform: win32 - arch: x64 - npm_config_arch: x64 - - os: windows-latest - platform: win32 - arch: arm64 - npm_config_arch: arm - - os: ubuntu-latest - platform: linux - arch: x64 - npm_config_arch: x64 - - os: ubuntu-latest - platform: linux - arch: arm64 - npm_config_arch: arm64 - - os: ubuntu-latest - platform: linux - arch: armhf - npm_config_arch: arm - - os: ubuntu-latest - platform: alpine - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: x64 - npm_config_arch: x64 - - os: macos-latest - platform: darwin - arch: arm64 - npm_config_arch: arm64 - runs-on: ${{ matrix.os }} - steps: - # 1. Check-out repository - - name: Check-out repository - uses: actions/checkout@v4 - - # 2. Install npm dependencies - - name: Use Node.js 19.0.0 - uses: actions/setup-node@v4 - with: - node-version: 19.0.0 - - - name: Cache extension node_modules - uses: actions/cache@v3 - with: - path: extensions/vscode/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }} - - - name: Cache core node_modules - uses: actions/cache@v3 - with: - path: core/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }} - - - name: Cache gui node_modules - uses: actions/cache@v3 - with: - path: gui/node_modules - key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }} - - - name: Install global Dependencies - run: | - npm install -g cargo-cp-artifact - - - name: Install extension Dependencies - run: | - cd extensions/vscode - npm ci - env: - # https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333 - GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }} - - - name: Install gui Dependencies - run: | - cd gui - npm ci --legacy-peer-deps - - - name: Install Core Dependencies - run: | - cd core - npm ci --legacy-peer-deps - - # 2.5. Pre package - - name: Make the out/node_modules directory - run: | - cd extensions/vscode - mkdir out - cd out - mkdir node_modules - - - name: Set var for environment info - shell: pwsh - run: echo "target=${{ matrix.platform }}-${{ matrix.arch }}" >> $env:GITHUB_ENV - - - name: Prepackage the extension - run: | - cd extensions/vscode - npm run prepackage -- --target ${{ env.target }} - - # 3. Run tests for the extension - - # - name: Install Xvfb for Linux and run tests - # run: | - # sudo apt-get install -y xvfb # Install Xvfb - # Xvfb :99 & # Start Xvfb - # export DISPLAY=:99 # Export the display number to the environment - # cd extensions/vscode - # npm run test - # if: matrix.os == 'ubuntu-latest' - - # - name: Run extension tests - # run: | - # cd extensions/vscode - # npm run test - # if: matrix.os != 'ubuntu-latest' - - # 4. Package the extension - - name: Re-install esbuild - run: | - cd extensions/vscode - npm install -f esbuild - - - name: Package the extension - run: cd extensions/vscode && npx vsce package --pre-release --target ${{ env.target }} - - # 5. Upload the .vsix as an artifact - - uses: actions/upload-artifact@v2 - with: - name: ${{ env.target }} - path: "extensions/vscode/*.vsix" - - publish: - runs-on: ubuntu-latest - needs: - - build - permissions: - contents: write - steps: - # 0. Setup git - - name: Checkout - uses: actions/checkout@v4 - - - name: Set up Git - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - - - name: Pull latest changes - run: git pull origin preview - - # 1. Download the artifacts - - uses: actions/download-artifact@v3 - - # 2. Publish the extension to VS Code Marketplace - - name: Publish to VS Code Marketplace - run: | - cd extensions/vscode - npx vsce publish --pre-release --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix - env: - VSCE_PAT: ${{ secrets.VSCE_TOKEN }} - - # 3. Publish the extension to Open VSX Registry - - name: Publish (Open VSX Registry) - run: | - cd extensions/vscode - npx ovsx publish --pre-release -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../alpine-x64/*.vsix ../../darwin-arm64/*.vsix ../../darwin-x64/*.vsix ../../linux-arm64/*.vsix ../../linux-armhf/*.vsix ../../linux-x64/*.vsix ../../win32-x64/*.vsix ../../win32-arm64/*.vsix - - # 4. Update the package.json version and push changes - - name: Update version in package.json - run: | - cd extensions/vscode - npm version patch - - - name: Commit changes - run: | - git config --local user.email "action@github.com" - git config --local user.name "GitHub Action" - git commit -am "💚 Update package.json version [skip ci]" - - - name: Push changes - uses: ad-m/github-push-action@master - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - branch: ${{ github.ref }} diff --git a/core/autocomplete/languages.ts b/core/autocomplete/languages.ts index 865f7b09d..1f9e7dac2 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/languages.ts @@ -184,6 +184,28 @@ export const Dart = { endOfLine: [";"], }; +// Solidity +export const Solidity = { + stopWords: [ + "contract", + "event", + "modifier", + "function", + "constructor", + "for", + "require", + "emit", + "interface", + "error", + "library", + "struct", + "enum", + "type", + ], + comment: "//", + endOfLine: [";"], +}; + export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, @@ -219,4 +241,5 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { r: R, R: R, dart: Dart, + sol: Solidity, }; diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/retrieval.ts index 00272d377..0f6349508 100644 --- a/core/autocomplete/retrieval.ts +++ b/core/autocomplete/retrieval.ts @@ -1,6 +1,5 @@ -import { Chunk } from ".."; +import { Chunk, IndexTag } from ".."; import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; -import { IndexTag } from "../indexing/types"; export async function fullTextRetrieve( prefix: string, diff --git a/core/autocomplete/templates.ts b/core/autocomplete/templates.ts index 51d28c5dc..c153badd7 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/templates.ts @@ -91,9 +91,9 @@ The last line is incomplete, and you should provide the rest of that line. If th export function getTemplateForModel(model: string): AutocompleteTemplate { const lowerCaseModel = model.toLowerCase(); - if (lowerCaseModel.includes("starcoder2")) { - return starcoder2FimTemplate; - } + // if (lowerCaseModel.includes("starcoder2")) { + // return starcoder2FimTemplate; + // } if ( lowerCaseModel.includes("starcoder") || diff --git a/core/config/load.ts b/core/config/load.ts index f911b9932..e30980b4b 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -51,10 +51,12 @@ function resolveSerializedConfig(filepath: string): SerializedContinueConfig { }; config.env.forEach((envVar) => { - content = content.replaceAll( - new RegExp(`"${envVar}"`, "g"), - `"${env[envVar]}"`, - ); + if (envVar in env) { + content = content.replaceAll( + new RegExp(`"${envVar}"`, "g"), + `"${env[envVar]}"`, + ); + } }); } @@ -86,36 +88,12 @@ function loadSerializedConfig( config.allowAnonymousTelemetry = true; } - migrate("codebaseContextProvider", () => { - if ( - !config.contextProviders?.filter((cp) => cp.name === "codebase")?.length - ) { + migrate("codeContextProvider", () => { + if (!config.contextProviders?.filter((cp) => cp.name === "code")?.length) { config.contextProviders = [ ...(config.contextProviders || []), { - name: "codebase", - params: {}, - }, - ]; - } - - if (!config.embeddingsProvider) { - config.embeddingsProvider = { - provider: "transformers.js", - }; - } - - fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8"); - }); - - migrate("problemsContextProvider", () => { - if ( - !config.contextProviders?.filter((cp) => cp.name === "problems")?.length - ) { - config.contextProviders = [ - ...(config.contextProviders || []), - { - name: "problems", + name: "code", params: {}, }, ]; @@ -124,14 +102,12 @@ function loadSerializedConfig( fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8"); }); - migrate("foldersContextProvider", () => { - if ( - !config.contextProviders?.filter((cp) => cp.name === "folder")?.length - ) { + migrate("docsContextProvider1", () => { + if (!config.contextProviders?.filter((cp) => cp.name === "docs")?.length) { config.contextProviders = [ ...(config.contextProviders || []), { - name: "folder", + name: "docs", params: {}, }, ]; diff --git a/core/context/providers/CodeContextProvider.ts b/core/context/providers/CodeContextProvider.ts new file mode 100644 index 000000000..89bf9b026 --- /dev/null +++ b/core/context/providers/CodeContextProvider.ts @@ -0,0 +1,44 @@ +import { BaseContextProvider } from ".."; +import { + ContextItem, + ContextProviderDescription, + ContextProviderExtras, + ContextSubmenuItem, + LoadSubmenuItemsArgs, +} from "../.."; +import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex"; + +class CodeContextProvider extends BaseContextProvider { + static description: ContextProviderDescription = { + title: "code", + displayTitle: "Code", + description: "Type to search", + type: "submenu", + }; + + async getContextItems( + query: string, + extras: ContextProviderExtras, + ): Promise { + // Assume the query is the id as returned by loadSubmenuItems + return [await CodeSnippetsCodebaseIndex.getForId(parseInt(query, 10))]; + } + + async loadSubmenuItems( + args: LoadSubmenuItemsArgs, + ): Promise { + const tags = await args.ide.getTags("codeSnippets"); + const snippets = await Promise.all( + tags.map((tag) => CodeSnippetsCodebaseIndex.getAll(tag)), + ); + + const submenuItems: ContextSubmenuItem[] = []; + for (const snippetList of snippets) { + submenuItems.push(...snippetList); + } + + return submenuItems; + } +} + +export default CodeContextProvider; diff --git a/core/context/providers/index.ts b/core/context/providers/index.ts index 072f453fe..978c8e94c 100644 --- a/core/context/providers/index.ts +++ b/core/context/providers/index.ts @@ -1,5 +1,6 @@ import { BaseContextProvider } from ".."; import { ContextProviderName } from "../.."; +import CodeContextProvider from "./CodeContextProvider"; import CodebaseContextProvider from "./CodebaseContextProvider"; import DatabaseContextProvider from "./DatabaseContextProvider"; import DiffContextProvider from "./DiffContextProvider"; @@ -36,6 +37,7 @@ const Providers: (typeof BaseContextProvider)[] = [ JiraIssuesContextProvider, PostgresContextProvider, DatabaseContextProvider, + CodeContextProvider, ]; export function contextProviderClassFromName( diff --git a/core/context/retrieval.ts b/core/context/retrieval.ts index 4d218696e..6dc1a8071 100644 --- a/core/context/retrieval.ts +++ b/core/context/retrieval.ts @@ -1,7 +1,7 @@ -import { Chunk, ContextItem, ContextProviderExtras, ILLM } from ".."; +import { Chunk, ContextItem, ContextProviderExtras, ILLM, IndexTag } from ".."; import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch"; import { LanceDbIndex } from "../indexing/LanceDbIndex"; -import { IndexTag } from "../indexing/types"; + import { llmCanGenerateInParallel } from "../llm/autodetect"; import { getBasename } from "../util"; diff --git a/core/index.d.ts b/core/index.d.ts index 7c8f76098..abb337154 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -328,6 +328,12 @@ export interface IdeInfo { remoteName: string; } +export interface IndexTag { + directory: string; + branch: string; + artifactId: string; +} + export interface IDE { getIdeInfo(): Promise; getDiff(): Promise; @@ -363,6 +369,7 @@ export interface IDE { getProblems(filepath?: string | undefined): Promise; getBranch(dir: string): Promise; getStats(directory: string): Promise<{ [path: string]: number }>; + getTags(artifactId: string): Promise; } // Slash Commands @@ -419,7 +426,9 @@ type ContextProviderName = | "folder" | "jira" | "postgres" - | "database"; + | "database" + | "code" + | "docs"; type TemplateType = | "llama2" @@ -435,7 +444,8 @@ type TemplateType = | "xwin-coder" | "neural-chat" | "codellama-70b" - | "llava"; + | "llava" + | "gemma"; type ModelProvider = | "openai" diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts new file mode 100644 index 000000000..c1ab1c68d --- /dev/null +++ b/core/indexing/CodeSnippetsIndex.ts @@ -0,0 +1,216 @@ +import fs from "fs"; +import path from "path"; +import { + ChunkWithoutID, + ContextItem, + ContextSubmenuItem, + IDE, + IndexTag, + IndexingProgressUpdate, +} from ".."; +import { getBasename } from "../util"; +import { + getLanguageForFile, + getParserForFile, + supportedLanguages, +} from "../util/treeSitter"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; +import { + CodebaseIndex, + IndexResultType, + MarkCompleteCallback, + RefreshIndexResults, +} from "./types"; + +export class CodeSnippetsCodebaseIndex implements CodebaseIndex { + artifactId = "codeSnippets"; + + constructor(private readonly ide: IDE) {} + + private async _createTables(db: DatabaseConnection) { + await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets ( + id INTEGER PRIMARY KEY, + path TEXT NOT NULL, + cacheKey TEXT NOT NULL, + content TEXT NOT NULL, + title TEXT NOT NULL, + startLine INTEGER NOT NULL, + endLine INTEGER NOT NULL + )`); + + await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets_tags ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tag TEXT NOT NULL, + snippetId INTEGER NOT NULL, + FOREIGN KEY (snippetId) REFERENCES code_snippets (id) + )`); + } + + private getQuerySource(filepath: string) { + const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""]; + const sourcePath = path.join( + __dirname, + "..", + "tree-sitter", + "code-snippet-queries", + `tree-sitter-${fullLangName}-tags.scm`, + ); + if (!fs.existsSync(sourcePath)) { + return ""; + } + return fs.readFileSync(sourcePath).toString(); + } + + async getSnippetsInFile( + filepath: string, + contents: string, + ): Promise<(ChunkWithoutID & { title: string })[]> { + const lang = await getLanguageForFile(filepath); + if (!lang) { + return []; + } + const parser = await getParserForFile(filepath); + if (!parser) { + return []; + } + const ast = parser.parse(contents); + const query = lang?.query(this.getQuerySource(filepath)); + const matches = query?.matches(ast.rootNode); + + return ( + matches?.flatMap((match) => { + const node = match.captures[0].node; + const title = match.captures[1].node.text; + const results = { + title, + content: node.text, + startLine: node.startPosition.row, + endLine: node.endPosition.row, + }; + return results; + }) ?? [] + ); + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: MarkCompleteCallback, + ): AsyncGenerator { + const db = await SqliteDb.get(); + await this._createTables(db); + const tagString = tagToString(tag); + + for (let i = 0; i < results.compute.length; i++) { + const compute = results.compute[i]; + const snippets = await this.getSnippetsInFile( + compute.path, + await this.ide.readFile(compute.path), + ); + + // Add snippets to sqlite + for (const snippet of snippets) { + const { lastID } = await db.run( + `INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)`, + [ + compute.path, + compute.cacheKey, + snippet.content, + snippet.title, + snippet.startLine, + snippet.endLine, + ], + ); + + await db.run( + `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, + [lastID, tagString], + ); + } + + yield { + desc: `Indexing ${compute.path}`, + progress: i / results.compute.length, + }; + markComplete([compute], IndexResultType.Compute); + } + + for (let i = 0; i < results.del.length; i++) { + const del = results.del[i]; + const deleted = await db.run( + `DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?`, + [del.path, del.cacheKey], + ); + await db.run(`DELETE FROM code_snippets_tags WHERE snippetId = ?`, [ + deleted.lastID, + ]); + markComplete([del], IndexResultType.Delete); + } + + for (let i = 0; i < results.addTag.length; i++) { + const snippetsWithPath = await db.all( + `SELECT * FROM code_snippets WHERE cacheKey = ?`, + [results.addTag[i].cacheKey], + ); + + for (const snippet of snippetsWithPath) { + await db.run( + `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, + [snippet.id, tagString], + ); + } + + markComplete([results.addTag[i]], IndexResultType.AddTag); + } + + for (let i = 0; i < results.removeTag.length; i++) { + const item = results.removeTag[i]; + await db.run( + ` + DELETE FROM code_snippets_tags + WHERE tag = ? + AND snippetId IN ( + SELECT id FROM code_snippets + WHERE cacheKey = ? AND path = ? + ) + `, + [tagString, item.cacheKey, item.path], + ); + markComplete([results.removeTag[i]], IndexResultType.RemoveTag); + } + } + + static async getForId(id: number): Promise { + const db = await SqliteDb.get(); + const row = await db.get(`SELECT * FROM code_snippets WHERE id = ?`, [id]); + + return { + name: row.title, + description: getBasename(row.path, 2), + content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, + }; + } + + static async getAll(tag: IndexTag): Promise { + const db = await SqliteDb.get(); + try { + const rows = await db.all( + `SELECT cs.id, cs.path, cs.title + FROM code_snippets cs + JOIN code_snippets_tags cst ON cs.id = cst.snippetId + WHERE cst.tag = ?; + `, + [tagToString(tag)], + ); + + return rows.map((row) => ({ + title: row.title, + description: getBasename(row.path, 2), + id: row.id.toString(), + })); + } catch (e) { + console.warn("Error getting all code snippets: ", e); + return []; + } + } +} diff --git a/core/indexing/FullTextSearch.ts b/core/indexing/FullTextSearch.ts index c4bd785f2..883b73a51 100644 --- a/core/indexing/FullTextSearch.ts +++ b/core/indexing/FullTextSearch.ts @@ -1,9 +1,8 @@ -import { Chunk, IndexingProgressUpdate } from ".."; +import { Chunk, IndexTag, IndexingProgressUpdate } from ".."; import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, - IndexTag, MarkCompleteCallback, RefreshIndexResults, } from "./types"; diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 1a63cc7c0..4029f7543 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,6 +1,11 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error import { v4 as uuidv4 } from "uuid"; -import { Chunk, EmbeddingsProvider, IndexingProgressUpdate } from ".."; +import { + Chunk, + EmbeddingsProvider, + IndexTag, + IndexingProgressUpdate, +} from ".."; import { MAX_CHUNK_SIZE } from "../llm/constants"; import { getBasename } from "../util"; import { getLanceDbPath } from "../util/paths"; @@ -9,7 +14,6 @@ import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, - IndexTag, PathAndCacheKey, RefreshIndexResults, } from "./types"; diff --git a/core/indexing/README.md b/core/indexing/README.md new file mode 100644 index 000000000..401f281f7 --- /dev/null +++ b/core/indexing/README.md @@ -0,0 +1,30 @@ +# Indexing + +Continue uses a tagging system along with content addressing to ensure that nothing needs to be indexed twice. When you change branches, Continue will only re-index the files that are newly modified and that we don't already have a copy of. This system can be used across many different "artifacts" just by implementing the `CodebaseIndex` class. + +_artifact_: something that is generated by indexing and then saved to be used later (e.g. emeddings, full-text search index, or a table of top-level code snippets in each file) + +_cacheKey_: a key that determines whether two files can be considered the same to avoid re-indexing (always hash of file contents at this point) + +_`CodebaseIndex`_: a class that makes it easy to use the indexing system to help you generate a new artifact + +The indexing process does the following: + +1. Check the modified timestamps of all files in the repo (this may seem extreme, but checking timestamps is significantly faster than actually reading a file. Git does the same thing.) +2. Compare these to a "catalog" (stored in SQLite) of the last time that we indexed each of these files to get a list of files to "add" or "remove". If the file exists in the repo but not in the catalog, then we must "add" the file. If it exists in the catalog but not the repo, we must "remove" the file. If it exists in both and was modified after last indexed, then we must update the file. In this case we also add it to the "add" list. +3. For each file to "add", check whether it was indexed on another branch. Here we use a SQLite table that acts as a cache for indexed files. If we find an entry in this table for a file with the same cacheKey, then we only need to add a tag to this entry for the current branch ("addTag"). Otherwise, we must "compute" the artifact. +4. For each file in "remove", check whether it was indexed on another branch. If we find only one entry with the same cacheKey (presumably this should be the entry for the current branch, or something has gone wrong), then this entry should be removed and there will be no more branches that need the artifact, so we want to "delete" it. If there is more than one tag on this artifact, then we should just remove the tag for this branch ("removeTag"). +5. After having calculated these four lists of files ("compute", "delete", "addTag", "removeTag"), we pass them to the `CodebaseIndex` so that it can update whatever index-specific storage it might have. Many of them use SQLite and/or LanceDB. The `CodebaseIndex` implements a method called "update" that accepts the four lists and yields progress updates as it iterates over the lists. These progress updates are used to officially mark a file as having been indexed, so that if the extension is closed mid-indexing we don't falsely record progress. + +## Existing `CodebaseIndex`es + +All indexes must be returned by `getIndexesToBuild` in [`indexCodebase.ts`](./indexCodebase.ts) if they are to be used. + +`CodeSnippetsCodebaseIndex`: uses tree-sitter queries to get a list of functions, classes, and other top-level code objects in each file +`FullTextSearchCodebaseIndex`: creates a full-text search index using SQLite FTS5 +`ChunkCodebaseIndex`: chunks files recursively by code structure, for use in other embeddings providers like `LanceDbCodebaseIndex` +`LanceDbCodebaseIndex`: calculates embeddings for each chunk and adds them to the LanceDB vector database, with metadata going into SQLite + +## Known problems: + +- `FullTextSearchCodebaseIndex` doesn't differentiate between tags (branch, repo), so results may come from any branch/repo. LanceDB does this by creating separate tables for each tag (see `tableNameForTag`). The chunk index does this with a second table diff --git a/core/indexing/chunk/ChunkCodebaseIndex.ts b/core/indexing/chunk/ChunkCodebaseIndex.ts index ab485a04a..d52f57b7e 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.ts @@ -1,11 +1,10 @@ -import { IndexingProgressUpdate } from "../.."; +import { IndexTag, IndexingProgressUpdate } from "../.."; import { MAX_CHUNK_SIZE } from "../../llm/constants"; import { getBasename } from "../../util"; import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex"; import { CodebaseIndex, IndexResultType, - IndexTag, MarkCompleteCallback, RefreshIndexResults, } from "../types"; @@ -106,7 +105,17 @@ export class ChunkCodebaseIndex implements CodebaseIndex { // Remove tag for (const item of results.removeTag) { - await db.run(`DELETE FROM chunk_tags WHERE tag = ?`, [tagString]); + await db.run( + ` + DELETE FROM chunk_tags + WHERE tag = ? + AND chunkId IN ( + SELECT id FROM chunks + WHERE cacheKey = ? AND path = ? + ) + `, + [tagString, item.cacheKey, item.path], + ); markComplete([item], IndexResultType.RemoveTag); } diff --git a/core/indexing/docs/db.ts b/core/indexing/docs/db.ts index a59c1c934..73651452e 100644 --- a/core/indexing/docs/db.ts +++ b/core/indexing/docs/db.ts @@ -2,7 +2,6 @@ import { Database, open } from "sqlite"; import sqlite3 from "sqlite3"; import { Chunk } from "../.."; import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths"; -import { SqliteDb } from "../refreshIndex"; import { downloadPreIndexedDocs } from "./preIndexed"; import { default as configs } from "./preIndexedDocs"; @@ -21,12 +20,23 @@ interface LanceDbDocsRow { [key: string]: any; } -async function createDocsTable(db: Database) { - db.exec(`CREATE TABLE IF NOT EXISTS docs ( +let dbDocs:Database; + +async function getDBDocs() { + if (!dbDocs) { + dbDocs = await open({ + filename: getDocsSqlitePath(), + driver: sqlite3.Database, + }); + + dbDocs.exec(`CREATE TABLE IF NOT EXISTS docs ( id INTEGER PRIMARY KEY AUTOINCREMENT, title STRING NOT NULL, baseUrl STRING NOT NULL UNIQUE )`); + } + + return dbDocs; } export async function retrieveDocs( @@ -37,8 +47,7 @@ export async function retrieveDocs( nested: boolean = false, ): Promise { const lancedb = await import("vectordb"); - const db = await SqliteDb.get(); - await createDocsTable(db); + const db = await getDBDocs(); const lance = await lancedb.connect(getLanceDbPath()); const downloadDocs = async () => { @@ -116,11 +125,7 @@ export async function addDocs( } // Only after add it to SQLite - const db = await open({ - filename: getDocsSqlitePath(), - driver: sqlite3.Database, - }); - await createDocsTable(db); + const db = await getDBDocs(); await db.run( `INSERT INTO docs (title, baseUrl) VALUES (?, ?)`, title, @@ -131,11 +136,7 @@ export async function addDocs( export async function listDocs(): Promise< { title: string; baseUrl: string }[] > { - const db = await open({ - filename: getDocsSqlitePath(), - driver: sqlite3.Database, - }); - await createDocsTable(db); - const docs = await db.all(`SELECT title, baseUrl FROM docs`); + const db = await getDBDocs(); + const docs = db.all(`SELECT title, baseUrl FROM docs`); return docs; } diff --git a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts index e95ddad4f..3393cc111 100644 --- a/core/indexing/embeddings/OllamaEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OllamaEmbeddingsProvider.ts @@ -2,7 +2,7 @@ import { EmbedOptions } from "../.."; import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider"; async function embedOne(chunk: string, options: EmbedOptions) { - const resp = await fetch(`${options.apiBase}/api/embeddings`, { + const resp = await fetch(new URL("api/embeddings", options.apiBase), { method: "POST", body: JSON.stringify({ model: options.model, @@ -19,7 +19,7 @@ async function embedOne(chunk: string, options: EmbedOptions) { class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: Partial | undefined = { - apiBase: "http://localhost:11434", + apiBase: "http://localhost:11434/", }; get id(): string { diff --git a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts index 1d806d865..0710da682 100644 --- a/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts +++ b/core/indexing/embeddings/OpenAIEmbeddingsProvider.ts @@ -4,7 +4,7 @@ import { fetchWithExponentialBackoff } from "./util"; class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { static defaultOptions: Partial | undefined = { - apiBase: "https://api.openai.com/v1", + apiBase: "https://api.openai.com/v1/", model: "text-embedding-3-small", }; @@ -13,15 +13,10 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider { } async embed(chunks: string[]) { - let apiBase = this.options.apiBase; - if (apiBase?.endsWith("/")) { - apiBase = apiBase.slice(0, -1); - } - return await Promise.all( chunks.map(async (chunk) => { const resp = await fetchWithExponentialBackoff( - `${apiBase}/embeddings`, + new URL("embeddings", this.options.apiBase).toString(), { method: "POST", body: JSON.stringify({ diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts index 03597e99e..645affa6a 100644 --- a/core/indexing/indexCodebase.ts +++ b/core/indexing/indexCodebase.ts @@ -1,10 +1,11 @@ -import { IDE, IndexingProgressUpdate } from ".."; +import { IDE, IndexTag, IndexingProgressUpdate } from ".."; import { ConfigHandler } from "../config/handler"; +import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex"; import { FullTextSearchCodebaseIndex } from "./FullTextSearch"; import { LanceDbIndex } from "./LanceDbIndex"; import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex"; import { getComputeDeleteAddRemove } from "./refreshIndex"; -import { CodebaseIndex, IndexTag } from "./types"; +import { CodebaseIndex } from "./types"; export class PauseToken { constructor(private _paused: boolean) {} @@ -39,6 +40,7 @@ export class CodebaseIndexer { this.ide.readFile.bind(this.ide), ), new FullTextSearchCodebaseIndex(), + new CodeSnippetsCodebaseIndex(this.ide), ]; return indexes; @@ -57,7 +59,7 @@ export class CodebaseIndexer { let completedDirs = 0; yield { - progress: 0, + progress: 0.01, desc: "Starting indexing...", }; diff --git a/core/indexing/refreshIndex.ts b/core/indexing/refreshIndex.ts index c908bc7bd..03bf7f7fa 100644 --- a/core/indexing/refreshIndex.ts +++ b/core/indexing/refreshIndex.ts @@ -2,12 +2,11 @@ import crypto from "crypto"; import * as fs from "fs"; import { Database, open } from "sqlite"; import sqlite3 from "sqlite3"; -import { IndexingProgressUpdate } from ".."; +import { IndexTag, IndexingProgressUpdate } from ".."; import { getIndexSqlitePath } from "../util/paths"; import { CodebaseIndex, IndexResultType, - IndexTag, LastModifiedMap, MarkCompleteCallback, PathAndCacheKey, diff --git a/core/indexing/types.ts b/core/indexing/types.ts index e62897238..64df4a618 100644 --- a/core/indexing/types.ts +++ b/core/indexing/types.ts @@ -1,4 +1,4 @@ -import { IndexingProgressUpdate } from ".."; +import { IndexTag, IndexingProgressUpdate } from ".."; export enum IndexResultType { Compute = "compute", @@ -26,12 +26,6 @@ export type PathAndCacheKey = { cacheKey: string; }; -export interface IndexTag { - directory: string; - branch: string; - artifactId: string; -} - export type RefreshIndexResults = { compute: PathAndCacheKey[]; del: PathAndCacheKey[]; diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts index c4821aed8..a29ababf8 100644 --- a/core/llm/autodetect.ts +++ b/core/llm/autodetect.ts @@ -4,6 +4,7 @@ import { chatmlTemplateMessages, codeLlama70bTemplateMessages, deepseekTemplateMessages, + gemmaTemplateMessage, llama2TemplateMessages, llavaTemplateMessages, neuralChatTemplateMessages, @@ -20,6 +21,7 @@ import { codeLlama70bEditPrompt, codellamaEditPrompt, deepseekEditPrompt, + gemmaEditPrompt, mistralEditPrompt, neuralChatEditPrompt, openchatEditPrompt, @@ -129,6 +131,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined { return "chatml"; } + if (lower.includes("gemma")) { + return "gemma"; + } + if (lower.includes("phi2")) { return "phi2"; } @@ -201,6 +207,7 @@ function autodetectTemplateFunction( "neural-chat": neuralChatTemplateMessages, llava: llavaTemplateMessages, "codellama-70b": codeLlama70bTemplateMessages, + gemma: gemmaTemplateMessage, none: null, }; @@ -245,6 +252,8 @@ function autodetectPromptTemplates( editTemplate = codeLlama70bEditPrompt; } else if (templateType === "anthropic") { editTemplate = claudeEditPrompt; + } else if (templateType === "gemma") { + editTemplate = gemmaEditPrompt; } else if (templateType) { editTemplate = simplestEditPrompt; } diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts index ae9244d57..4274c3a55 100644 --- a/core/llm/countTokens.ts +++ b/core/llm/countTokens.ts @@ -205,19 +205,15 @@ function pruneChatHistory( for (let i = 0; i < longerThanOneThird.length; i++) { // Prune line-by-line from the top const message = longerThanOneThird[i]; - let lines = stripImages(message.content).split("\n"); - let tokensRemoved = 0; - while ( - tokensRemoved < distanceFromThird[i] && - totalTokens > contextLength && - lines.length > 0 - ) { - const delta = countTokens("\n" + lines.shift()!, modelName); - tokensRemoved += delta; - totalTokens -= delta; - } - - message.content = lines.join("\n"); + let content = stripImages(message.content); + const deltaNeeded = totalTokens - contextLength; + const delta = Math.min(deltaNeeded, distanceFromThird[i]); + message.content = pruneStringFromTop( + modelName, + countTokens(message.content, modelName) - delta, + content, + ); + totalTokens -= delta; } // 1. Replace beyond last 5 messages with summary diff --git a/core/llm/index.ts b/core/llm/index.ts index 1fcf8c2aa..e6df8e2ba 100644 --- a/core/llm/index.ts +++ b/core/llm/index.ts @@ -113,8 +113,8 @@ export abstract class BaseLLM implements ILLM { this.llmRequestHook = options.llmRequestHook; this.apiKey = options.apiKey; this.apiBase = options.apiBase; - if (this.apiBase?.endsWith("/")) { - this.apiBase = this.apiBase.slice(0, -1); + if (this.apiBase && !this.apiBase.endsWith("/")) { + this.apiBase = this.apiBase + "/"; } this.engine = options.engine; diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts index e64d58d89..8bb642648 100644 --- a/core/llm/llms/Anthropic.ts +++ b/core/llm/llms/Anthropic.ts @@ -16,7 +16,7 @@ class Anthropic extends BaseLLM { model: "claude-3-opus-20240229", maxTokens: 4096, }, - apiBase: "https://api.anthropic.com/v1", + apiBase: "https://api.anthropic.com/v1/", }; constructor(options: LLMOptions) { @@ -69,7 +69,7 @@ class Anthropic extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const response = await this.fetch(this.apiBase + "/messages", { + const response = await this.fetch(new URL("messages", this.apiBase), { method: "POST", headers: { "Content-Type": "application/json", diff --git a/core/llm/llms/DeepInfra.ts b/core/llm/llms/DeepInfra.ts index a3723afb6..1a6952cfa 100644 --- a/core/llm/llms/DeepInfra.ts +++ b/core/llm/llms/DeepInfra.ts @@ -4,7 +4,7 @@ import OpenAI from "./OpenAI"; class DeepInfra extends OpenAI { static providerName: ModelProvider = "deepinfra"; static defaultOptions: Partial = { - apiBase: "https://api.deepinfra.com/v1/openai", + apiBase: "https://api.deepinfra.com/v1/openai/", }; } diff --git a/core/llm/llms/GooglePalm.ts b/core/llm/llms/GooglePalm.ts index 3c62a49ca..780eeac19 100644 --- a/core/llm/llms/GooglePalm.ts +++ b/core/llm/llms/GooglePalm.ts @@ -14,7 +14,7 @@ class GooglePalm extends BaseLLM { static defaultOptions: Partial = { model: "gemini-pro", - apiBase: "https://generativelanguage.googleapis.com", + apiBase: "https://generativelanguage.googleapis.com/", }; protected async *_streamComplete( @@ -82,7 +82,10 @@ class GooglePalm extends BaseLLM { messages: ChatMessage[], options: CompletionOptions, ): AsyncGenerator { - const apiURL = `${this.apiBase}/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`; + const apiURL = new URL( + `v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`, + this.apiBase, + ); const body = { contents: messages.map((msg) => { return { @@ -157,7 +160,10 @@ class GooglePalm extends BaseLLM { msgList.push({ content: message.content }); } - const apiURL = `${this.apiBase}/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`; + const apiURL = new URL( + `v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`, + this.apiBase, + ); const body = { prompt: { messages: msgList } }; const response = await this.fetch(apiURL, { method: "POST", diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts index a4893b8eb..f7f759e1e 100644 --- a/core/llm/llms/HuggingFaceTGI.ts +++ b/core/llm/llms/HuggingFaceTGI.ts @@ -5,13 +5,13 @@ import { streamSse } from "../stream"; class HuggingFaceTGI extends BaseLLM { static providerName: ModelProvider = "huggingface-tgi"; static defaultOptions: Partial = { - apiBase: "http://localhost:8080", + apiBase: "http://localhost:8080/", }; constructor(options: LLMOptions) { super(options); - this.fetch(`${this.apiBase}/info`, { + this.fetch(new URL("info", this.apiBase), { method: "GET", }).then(async (response) => { if (response.status !== 200) { @@ -48,13 +48,16 @@ class HuggingFaceTGI extends BaseLLM { ): AsyncGenerator { const args = this._convertArgs(options, prompt); - const response = await this.fetch(`${this.apiBase}/generate_stream`, { - method: "POST", - headers: { - "Content-Type": "application/json", + const response = await this.fetch( + new URL("generate_stream", this.apiBase), + { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ inputs: prompt, parameters: args }), }, - body: JSON.stringify({ inputs: prompt, parameters: args }), - }); + ); for await (const value of streamSse(response)) { yield value.token.text; diff --git a/core/llm/llms/LMStudio.ts b/core/llm/llms/LMStudio.ts index 4279abaf1..5a63701e1 100644 --- a/core/llm/llms/LMStudio.ts +++ b/core/llm/llms/LMStudio.ts @@ -4,7 +4,7 @@ import OpenAI from "./OpenAI"; class LMStudio extends OpenAI { static providerName: ModelProvider = "lmstudio"; static defaultOptions: Partial = { - apiBase: "http://localhost:1234/v1", + apiBase: "http://localhost:1234/v1/", }; } diff --git a/core/llm/llms/LlamaCpp.ts b/core/llm/llms/LlamaCpp.ts index eb947af11..9c5349619 100644 --- a/core/llm/llms/LlamaCpp.ts +++ b/core/llm/llms/LlamaCpp.ts @@ -5,7 +5,7 @@ import { streamSse } from "../stream"; class LlamaCpp extends BaseLLM { static providerName: ModelProvider = "llama.cpp"; static defaultOptions: Partial = { - apiBase: "http://127.0.0.1:8080", + apiBase: "http://127.0.0.1:8080/", }; private _convertArgs(options: CompletionOptions, prompt: string) { @@ -30,7 +30,7 @@ class LlamaCpp extends BaseLLM { ...this.requestOptions?.headers, }; - const resp = await this.fetch(`${this.apiBase}/completion`, { + const resp = await this.fetch(new URL("completion", this.apiBase), { method: "POST", headers, body: JSON.stringify({ diff --git a/core/llm/llms/Mistral.ts b/core/llm/llms/Mistral.ts index 385eda897..03a2b3a07 100644 --- a/core/llm/llms/Mistral.ts +++ b/core/llm/llms/Mistral.ts @@ -4,7 +4,7 @@ import OpenAI from "./OpenAI"; class Mistral extends OpenAI { static providerName: ModelProvider = "mistral"; static defaultOptions: Partial = { - apiBase: "https://api.mistral.ai/v1", + apiBase: "https://api.mistral.ai/v1/", model: "mistral-small", }; } diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 8d88c1535..1c0c77561 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -11,7 +11,7 @@ import { streamResponse } from "../stream"; class Ollama extends BaseLLM { static providerName: ModelProvider = "ollama"; static defaultOptions: Partial = { - apiBase: "http://localhost:11434", + apiBase: "http://localhost:11434/", model: "codellama-7b", }; @@ -218,9 +218,13 @@ class Ollama extends BaseLLM { } async listModels(): Promise { - const response = await this.fetch(new URL("api/tags", this.apiBase), { - method: "GET", - }); + const response = await this.fetch( + // localhost was causing fetch failed in pkg binary only for this Ollama endpoint + new URL("api/tags", this.apiBase?.replace("localhost", "127.0.0.1")), + { + method: "GET", + }, + ); const data = await response.json(); return data.models.map((model: any) => model.name); } diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index a151e9737..05a6c5c5d 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -41,7 +41,7 @@ class OpenAI extends BaseLLM { static providerName: ModelProvider = "openai"; static defaultOptions: Partial = { - apiBase: "https://api.openai.com/v1", + apiBase: "https://api.openai.com/v1/", }; protected _convertMessage(message: ChatMessage) { @@ -72,6 +72,7 @@ class OpenAI extends BaseLLM { frequency_penalty: options.frequencyPenalty, presence_penalty: options.presencePenalty, stop: + // Jan + Azure OpenAI don't truncate and will throw an error this.apiBase?.includes(":1337") || this.apiType === "azure" ? options.stop?.slice(0, 4) : options.stop, @@ -96,22 +97,21 @@ class OpenAI extends BaseLLM { } private _getEndpoint( - endpoint: "/chat/completions" | "/completions" | "/models", + endpoint: "chat/completions" | "completions" | "models", ) { if (this.apiType === "azure") { - return `${this.apiBase}/openai/deployments/${this.engine}${endpoint}?api-version=${this.apiVersion}`; + return new URL( + `openai/deployments/${this.engine}${endpoint}?api-version=${this.apiVersion}`, + this.apiBase, + ); } else { - let url = this.apiBase; - if (!url) { + if (!this.apiBase) { throw new Error( "No API base URL provided. Please set the 'apiBase' option in config.json", ); } - if (url.endsWith("/")) { - url = url.slice(0, -1); - } - return url + endpoint; + return new URL(endpoint, this.apiBase); } } @@ -135,7 +135,7 @@ class OpenAI extends BaseLLM { args.prompt = prompt; delete args.messages; - const response = await this.fetch(this._getEndpoint("/completions"), { + const response = await this.fetch(this._getEndpoint("completions"), { method: "POST", headers: { "Content-Type": "application/json", @@ -185,7 +185,7 @@ class OpenAI extends BaseLLM { ...m, content: m.content === "" ? " " : m.content, })) as any; - const response = await this.fetch(this._getEndpoint("/chat/completions"), { + const response = await this.fetch(this._getEndpoint("chat/completions"), { method: "POST", headers: { "Content-Type": "application/json", @@ -203,7 +203,7 @@ class OpenAI extends BaseLLM { } async listModels(): Promise { - const response = await this.fetch(this._getEndpoint("/models"), { + const response = await this.fetch(this._getEndpoint("models"), { method: "GET", headers: { Authorization: `Bearer ${this.apiKey}`, diff --git a/core/llm/llms/TextGenWebUI.ts b/core/llm/llms/TextGenWebUI.ts index 2482df838..ce7e65ebd 100644 --- a/core/llm/llms/TextGenWebUI.ts +++ b/core/llm/llms/TextGenWebUI.ts @@ -4,7 +4,7 @@ import OpenAI from "./OpenAI"; class TextGenWebUI extends OpenAI { static providerName: ModelProvider = "text-gen-webui"; static defaultOptions: Partial = { - apiBase: "http://localhost:5000/v1", + apiBase: "http://localhost:5000/v1/", }; } diff --git a/core/llm/llms/Together.ts b/core/llm/llms/Together.ts index 1b2aa29bd..62ce21e83 100644 --- a/core/llm/llms/Together.ts +++ b/core/llm/llms/Together.ts @@ -10,7 +10,7 @@ import OpenAI from "./OpenAI"; class Together extends OpenAI { static providerName: ModelProvider = "together"; static defaultOptions: Partial = { - apiBase: "https://api.together.xyz/v1", + apiBase: "https://api.together.xyz/v1/", }; private static MODEL_IDS: { [name: string]: string } = { diff --git a/core/llm/templates/chat.ts b/core/llm/templates/chat.ts index 67d5a04f5..8f004abb8 100644 --- a/core/llm/templates/chat.ts +++ b/core/llm/templates/chat.ts @@ -287,11 +287,30 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string { return prompt; } +/** + user + What is Cramer's Rule? + model + */ + +function gemmaTemplateMessage(msgs: ChatMessage[]): string { + let prompt = ""; + for (const msg of msgs) { + prompt += `${ + msg.role === "assistant" ? "model" : "user" + }\n${stripImages(msg.content).trim()}\n`; + } + + prompt += "model\n"; + return prompt; +} + export { anthropicTemplateMessages, chatmlTemplateMessages, codeLlama70bTemplateMessages, deepseekTemplateMessages, + gemmaTemplateMessage, llama2TemplateMessages, llavaTemplateMessages, neuralChatTemplateMessages, diff --git a/core/llm/templates/edit.ts b/core/llm/templates/edit.ts index e6383fa21..abe914f74 100644 --- a/core/llm/templates/edit.ts +++ b/core/llm/templates/edit.ts @@ -171,6 +171,19 @@ Output only a code block with the rewritten code: \`\`\`${otherData.language}`, }, ]; + +const gemmaEditPrompt = `user +You are an expert programmer and write code on the first attempt without any errors or fillers. Rewrite the code to satisfy this request: "{{{userInput}}}" + +\`\`\`{{{language}}} +{{{codeToEdit}}} +\`\`\` +model +Sure! Here's the code you requested: + +\`\`\`{{{language}}} +`; + export { alpacaEditPrompt, claudeEditPrompt, @@ -178,6 +191,7 @@ export { codellamaEditPrompt, codellamaInfillEditPrompt, deepseekEditPrompt, + gemmaEditPrompt, gptEditPrompt, mistralEditPrompt, neuralChatEditPrompt, diff --git a/core/package-lock.json b/core/package-lock.json index 4570869b7..5670ffd72 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -55,6 +55,7 @@ "@types/uuid": "^9.0.7", "esbuild": "^0.19.11", "jest": "^29.7.0", + "tree-sitter-cli": "^0.21.0", "ts-jest": "^29.1.1" } }, @@ -9391,6 +9392,16 @@ "node": ">=18" } }, + "node_modules/tree-sitter-cli": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.21.0.tgz", + "integrity": "sha512-wA7wT5724fNQW82XDH6zT6ZcYonjrAKLCHHuhLsPcAKULrhp3rNuMvlgBdB5FUBvmjHNhtTZF/qpHenMoRJPBw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "tree-sitter": "cli.js" + } + }, "node_modules/tree-sitter-wasms": { "version": "0.1.7", "resolved": "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.7.tgz", diff --git a/core/tag-qry/tree-sitter-c-tags.scm b/core/tag-qry/tree-sitter-c-tags.scm new file mode 100644 index 000000000..1035aa224 --- /dev/null +++ b/core/tag-qry/tree-sitter-c-tags.scm @@ -0,0 +1,9 @@ +(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class + +(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class + +(function_declarator declarator: (identifier) @name.definition.function) @definition.function + +(type_definition declarator: (type_identifier) @name.definition.type) @definition.type + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type diff --git a/core/tag-qry/tree-sitter-c_sharp-tags.scm b/core/tag-qry/tree-sitter-c_sharp-tags.scm new file mode 100644 index 000000000..58e9199a4 --- /dev/null +++ b/core/tag-qry/tree-sitter-c_sharp-tags.scm @@ -0,0 +1,46 @@ +(class_declaration + name: (identifier) @name.definition.class + ) @definition.class + +(class_declaration + bases: (base_list (_) @name.reference.class) + ) @reference.class + +(interface_declaration + name: (identifier) @name.definition.interface + ) @definition.interface + +(interface_declaration + bases: (base_list (_) @name.reference.interface) + ) @reference.interface + +(method_declaration + name: (identifier) @name.definition.method + ) @definition.method + +(object_creation_expression + type: (identifier) @name.reference.class + ) @reference.class + +(type_parameter_constraints_clause + target: (identifier) @name.reference.class + ) @reference.class + +(type_constraint + type: (identifier) @name.reference.class + ) @reference.class + +(variable_declaration + type: (identifier) @name.reference.class + ) @reference.class + +(invocation_expression + function: + (member_access_expression + name: (identifier) @name.reference.send + ) +) @reference.send + +(namespace_declaration + name: (identifier) @name.definition.module +) @definition.module diff --git a/core/tag-qry/tree-sitter-cpp-tags.scm b/core/tag-qry/tree-sitter-cpp-tags.scm new file mode 100644 index 000000000..7a7ad0b99 --- /dev/null +++ b/core/tag-qry/tree-sitter-cpp-tags.scm @@ -0,0 +1,15 @@ +(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class + +(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class + +(function_declarator declarator: (identifier) @name.definition.function) @definition.function + +(function_declarator declarator: (field_identifier) @name.definition.function) @definition.function + +(function_declarator declarator: (qualified_identifier scope: (namespace_identifier) @scope name: (identifier) @name.definition.method)) @definition.method + +(type_definition declarator: (type_identifier) @name.definition.type) @definition.type + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type + +(class_specifier name: (type_identifier) @name.definition.class) @definition.class diff --git a/core/tag-qry/tree-sitter-elisp-tags.scm b/core/tag-qry/tree-sitter-elisp-tags.scm new file mode 100644 index 000000000..743c8d8a8 --- /dev/null +++ b/core/tag-qry/tree-sitter-elisp-tags.scm @@ -0,0 +1,8 @@ +;; defun/defsubst +(function_definition name: (symbol) @name.definition.function) @definition.function + +;; Treat macros as function definitions for the sake of TAGS. +(macro_definition name: (symbol) @name.definition.function) @definition.function + +;; Match function calls +(list (symbol) @name.reference.function) @reference.function diff --git a/core/tag-qry/tree-sitter-elixir-tags.scm b/core/tag-qry/tree-sitter-elixir-tags.scm new file mode 100644 index 000000000..9eb39d95d --- /dev/null +++ b/core/tag-qry/tree-sitter-elixir-tags.scm @@ -0,0 +1,54 @@ +; Definitions + +; * modules and protocols +(call + target: (identifier) @ignore + (arguments (alias) @name.definition.module) + (#match? @ignore "^(defmodule|defprotocol)$")) @definition.module + +; * functions/macros +(call + target: (identifier) @ignore + (arguments + [ + ; zero-arity functions with no parentheses + (identifier) @name.definition.function + ; regular function clause + (call target: (identifier) @name.definition.function) + ; function clause with a guard clause + (binary_operator + left: (call target: (identifier) @name.definition.function) + operator: "when") + ]) + (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @definition.function + +; References + +; ignore calls to kernel/special-forms keywords +(call + target: (identifier) @ignore + (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp|defmodule|defprotocol|defimpl|defstruct|defexception|defoverridable|alias|case|cond|else|for|if|import|quote|raise|receive|require|reraise|super|throw|try|unless|unquote|unquote_splicing|use|with)$")) + +; ignore module attributes +(unary_operator + operator: "@" + operand: (call + target: (identifier) @ignore)) + +; * function call +(call + target: [ + ; local + (identifier) @name.reference.call + ; remote + (dot + right: (identifier) @name.reference.call) + ]) @reference.call + +; * pipe into function call +(binary_operator + operator: "|>" + right: (identifier) @name.reference.call) @reference.call + +; * modules +(alias) @name.reference.module @reference.module diff --git a/core/tag-qry/tree-sitter-elm-tags.scm b/core/tag-qry/tree-sitter-elm-tags.scm new file mode 100644 index 000000000..ad15d5e67 --- /dev/null +++ b/core/tag-qry/tree-sitter-elm-tags.scm @@ -0,0 +1,19 @@ +(value_declaration (function_declaration_left (lower_case_identifier) @name.definition.function)) @definition.function + +(function_call_expr (value_expr (value_qid) @name.reference.function)) @reference.function +(exposed_value (lower_case_identifier) @name.reference.function)) @reference.function +(type_annotation ((lower_case_identifier) @name.reference.function) (colon)) @reference.function + +(type_declaration ((upper_case_identifier) @name.definition.type) ) @definition.type + +(type_ref (upper_case_qid (upper_case_identifier) @name.reference.type)) @reference.type +(exposed_type (upper_case_identifier) @name.reference.type)) @reference.type + +(type_declaration (union_variant (upper_case_identifier) @name.definition.union)) @definition.union + +(value_expr (upper_case_qid (upper_case_identifier) @name.reference.union)) @reference.union + + +(module_declaration + (upper_case_qid (upper_case_identifier)) @name.definition.module +) @definition.module diff --git a/core/tag-qry/tree-sitter-go-tags.scm b/core/tag-qry/tree-sitter-go-tags.scm new file mode 100644 index 000000000..a32d03aa7 --- /dev/null +++ b/core/tag-qry/tree-sitter-go-tags.scm @@ -0,0 +1,30 @@ +( + (comment)* @doc + . + (function_declaration + name: (identifier) @name.definition.function) @definition.function + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (method_declaration + name: (field_identifier) @name.definition.method) @definition.method + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.method) +) + +(call_expression + function: [ + (identifier) @name.reference.call + (parenthesized_expression (identifier) @name.reference.call) + (selector_expression field: (field_identifier) @name.reference.call) + (parenthesized_expression (selector_expression field: (field_identifier) @name.reference.call)) + ]) @reference.call + +(type_spec + name: (type_identifier) @name.definition.type) @definition.type + +(type_identifier) @name.reference.type @reference.type diff --git a/core/tag-qry/tree-sitter-java-tags.scm b/core/tag-qry/tree-sitter-java-tags.scm new file mode 100644 index 000000000..3b7290d46 --- /dev/null +++ b/core/tag-qry/tree-sitter-java-tags.scm @@ -0,0 +1,20 @@ +(class_declaration + name: (identifier) @name.definition.class) @definition.class + +(method_declaration + name: (identifier) @name.definition.method) @definition.method + +(method_invocation + name: (identifier) @name.reference.call + arguments: (argument_list) @reference.call) + +(interface_declaration + name: (identifier) @name.definition.interface) @definition.interface + +(type_list + (type_identifier) @name.reference.implementation) @reference.implementation + +(object_creation_expression + type: (type_identifier) @name.reference.class) @reference.class + +(superclass (type_identifier) @name.reference.class) @reference.class diff --git a/core/tag-qry/tree-sitter-javascript-tags.scm b/core/tag-qry/tree-sitter-javascript-tags.scm new file mode 100644 index 000000000..3bc55c5c5 --- /dev/null +++ b/core/tag-qry/tree-sitter-javascript-tags.scm @@ -0,0 +1,88 @@ +( + (comment)* @doc + . + (method_definition + name: (property_identifier) @name.definition.method) @definition.method + (#not-eq? @name.definition.method "constructor") + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.method) +) + +( + (comment)* @doc + . + [ + (class + name: (_) @name.definition.class) + (class_declaration + name: (_) @name.definition.class) + ] @definition.class + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.class) +) + +( + (comment)* @doc + . + [ + (function + name: (identifier) @name.definition.function) + (function_declaration + name: (identifier) @name.definition.function) + (generator_function + name: (identifier) @name.definition.function) + (generator_function_declaration + name: (identifier) @name.definition.function) + ] @definition.function + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (lexical_declaration + (variable_declarator + name: (identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function) + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (variable_declaration + (variable_declarator + name: (identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function) + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +(assignment_expression + left: [ + (identifier) @name.definition.function + (member_expression + property: (property_identifier) @name.definition.function) + ] + right: [(arrow_function) (function)] +) @definition.function + +(pair + key: (property_identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function + +( + (call_expression + function: (identifier) @name.reference.call) @reference.call + (#not-match? @name.reference.call "^(require)$") +) + +(call_expression + function: (member_expression + property: (property_identifier) @name.reference.call) + arguments: (_) @reference.call) + +(new_expression + constructor: (_) @name.reference.class) @reference.class diff --git a/core/tag-qry/tree-sitter-ocaml-tags.scm b/core/tag-qry/tree-sitter-ocaml-tags.scm new file mode 100644 index 000000000..1799f8acf --- /dev/null +++ b/core/tag-qry/tree-sitter-ocaml-tags.scm @@ -0,0 +1,116 @@ +; Modules +;-------- + +( + (comment)? @doc . + (module_definition (module_binding (module_name) @name.definition.module) @definition.module) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(module_path (module_name) @name.reference.module) @reference.module + +; Modules types +;-------------- + +( + (comment)? @doc . + (module_type_definition (module_type_name) @name.definition.interface) @definition.interface + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(module_type_path (module_type_name) @name.reference.implementation) @reference.implementation + +; Functions +;---------- + +( + (comment)? @doc . + (value_definition + [ + (let_binding + pattern: (value_name) @name.definition.function + (parameter)) + (let_binding + pattern: (value_name) @name.definition.function + body: [(fun_expression) (function_expression)]) + ] @definition.function + ) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +( + (comment)? @doc . + (external (value_name) @name.definition.function) @definition.function + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(application_expression + function: (value_path (value_name) @name.reference.call)) @reference.call + +(infix_expression + left: (value_path (value_name) @name.reference.call) + (infix_operator) @reference.call + (#eq? @reference.call "@@")) + +(infix_expression + (infix_operator) @reference.call + right: (value_path (value_name) @name.reference.call) + (#eq? @reference.call "|>")) + +; Operator +;--------- + +( + (comment)? @doc . + (value_definition + (let_binding + pattern: (parenthesized_operator [ + (prefix_operator) + (infix_operator) + (hash_operator) + (indexing_operator) + (let_operator) + (and_operator) + (match_operator) + ] @name.definition.function)) @definition.function) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +[ + (prefix_operator) + (sign_operator) + (infix_operator) + (hash_operator) + (indexing_operator) + (let_operator) + (and_operator) + (match_operator) +] @name.reference.call @reference.call + +; Classes +;-------- + +( + (comment)? @doc . + [ + (class_definition (class_binding (class_name) @name.definition.class) @definition.class) + (class_type_definition (class_type_binding (class_type_name) @name.definition.class) @definition.class) + ] + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +[ + (class_path (class_name) @name.reference.class) + (class_type_path (class_type_name) @name.reference.class) +] @reference.class + +; Methods +;-------- + +( + (comment)? @doc . + (method_definition (method_name) @name.definition.method) @definition.method + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(method_invocation (method_name) @name.reference.call) @reference.call diff --git a/core/tag-qry/tree-sitter-php-tags.scm b/core/tag-qry/tree-sitter-php-tags.scm new file mode 100644 index 000000000..61c86fcbe --- /dev/null +++ b/core/tag-qry/tree-sitter-php-tags.scm @@ -0,0 +1,26 @@ +(class_declaration + name: (name) @name.definition.class) @definition.class + +(function_definition + name: (name) @name.definition.function) @definition.function + +(method_declaration + name: (name) @name.definition.function) @definition.function + +(object_creation_expression + [ + (qualified_name (name) @name.reference.class) + (variable_name (name) @name.reference.class) + ]) @reference.class + +(function_call_expression + function: [ + (qualified_name (name) @name.reference.call) + (variable_name (name)) @name.reference.call + ]) @reference.call + +(scoped_call_expression + name: (name) @name.reference.call) @reference.call + +(member_call_expression + name: (name) @name.reference.call) @reference.call diff --git a/core/tag-qry/tree-sitter-python-tags.scm b/core/tag-qry/tree-sitter-python-tags.scm new file mode 100644 index 000000000..3be5bed9f --- /dev/null +++ b/core/tag-qry/tree-sitter-python-tags.scm @@ -0,0 +1,12 @@ +(class_definition + name: (identifier) @name.definition.class) @definition.class + +(function_definition + name: (identifier) @name.definition.function) @definition.function + +(call + function: [ + (identifier) @name.reference.call + (attribute + attribute: (identifier) @name.reference.call) + ]) @reference.call diff --git a/core/tag-qry/tree-sitter-ql-tags.scm b/core/tag-qry/tree-sitter-ql-tags.scm new file mode 100644 index 000000000..3164aa25a --- /dev/null +++ b/core/tag-qry/tree-sitter-ql-tags.scm @@ -0,0 +1,26 @@ +(classlessPredicate + name: (predicateName) @name.definition.function) @definition.function + +(memberPredicate + name: (predicateName) @name.definition.method) @definition.method + +(aritylessPredicateExpr + name: (literalId) @name.reference.call) @reference.call + +(module + name: (moduleName) @name.definition.module) @definition.module + +(dataclass + name: (className) @name.definition.class) @definition.class + +(datatype + name: (className) @name.definition.class) @definition.class + +(datatypeBranch + name: (className) @name.definition.class) @definition.class + +(qualifiedRhs + name: (predicateName) @name.reference.call) @reference.call + +(typeExpr + name: (className) @name.reference.type) @reference.type diff --git a/core/tag-qry/tree-sitter-ruby-tags.scm b/core/tag-qry/tree-sitter-ruby-tags.scm new file mode 100644 index 000000000..79e71d2d6 --- /dev/null +++ b/core/tag-qry/tree-sitter-ruby-tags.scm @@ -0,0 +1,64 @@ +; Method definitions + +( + (comment)* @doc + . + [ + (method + name: (_) @name.definition.method) @definition.method + (singleton_method + name: (_) @name.definition.method) @definition.method + ] + (#strip! @doc "^#\\s*") + (#select-adjacent! @doc @definition.method) +) + +(alias + name: (_) @name.definition.method) @definition.method + +(setter + (identifier) @ignore) + +; Class definitions + +( + (comment)* @doc + . + [ + (class + name: [ + (constant) @name.definition.class + (scope_resolution + name: (_) @name.definition.class) + ]) @definition.class + (singleton_class + value: [ + (constant) @name.definition.class + (scope_resolution + name: (_) @name.definition.class) + ]) @definition.class + ] + (#strip! @doc "^#\\s*") + (#select-adjacent! @doc @definition.class) +) + +; Module definitions + +( + (module + name: [ + (constant) @name.definition.module + (scope_resolution + name: (_) @name.definition.module) + ]) @definition.module +) + +; Calls + +(call method: (identifier) @name.reference.call) @reference.call + +( + [(identifier) (constant)] @name.reference.call @reference.call + (#is-not? local) + (#not-match? @name.reference.call "^(lambda|load|require|require_relative|__FILE__|__LINE__)$") +) diff --git a/core/tag-qry/tree-sitter-rust-tags.scm b/core/tag-qry/tree-sitter-rust-tags.scm new file mode 100644 index 000000000..dadfa7acb --- /dev/null +++ b/core/tag-qry/tree-sitter-rust-tags.scm @@ -0,0 +1,60 @@ +; ADT definitions + +(struct_item + name: (type_identifier) @name.definition.class) @definition.class + +(enum_item + name: (type_identifier) @name.definition.class) @definition.class + +(union_item + name: (type_identifier) @name.definition.class) @definition.class + +; type aliases + +(type_item + name: (type_identifier) @name.definition.class) @definition.class + +; method definitions + +(declaration_list + (function_item + name: (identifier) @name.definition.method)) @definition.method + +; function definitions + +(function_item + name: (identifier) @name.definition.function) @definition.function + +; trait definitions +(trait_item + name: (type_identifier) @name.definition.interface) @definition.interface + +; module definitions +(mod_item + name: (identifier) @name.definition.module) @definition.module + +; macro definitions + +(macro_definition + name: (identifier) @name.definition.macro) @definition.macro + +; references + +(call_expression + function: (identifier) @name.reference.call) @reference.call + +(call_expression + function: (field_expression + field: (field_identifier) @name.reference.call)) @reference.call + +(macro_invocation + macro: (identifier) @name.reference.call) @reference.call + +; implementations + +(impl_item + trait: (type_identifier) @name.reference.implementation) @reference.implementation + +(impl_item + type: (type_identifier) @name.reference.implementation + !trait) @reference.implementation diff --git a/core/tag-qry/tree-sitter-typescript-tags.scm b/core/tag-qry/tree-sitter-typescript-tags.scm new file mode 100644 index 000000000..b1ab874dd --- /dev/null +++ b/core/tag-qry/tree-sitter-typescript-tags.scm @@ -0,0 +1,23 @@ +(function_signature + name: (identifier) @name.definition.function) @definition.function + +(method_signature + name: (property_identifier) @name.definition.method) @definition.method + +(abstract_method_signature + name: (property_identifier) @name.definition.method) @definition.method + +(abstract_class_declaration + name: (type_identifier) @name.definition.class) @definition.class + +(module + name: (identifier) @name.definition.module) @definition.module + +(interface_declaration + name: (type_identifier) @name.definition.interface) @definition.interface + +(type_annotation + (type_identifier) @name.reference.type) @reference.type + +(new_expression + constructor: (identifier) @name.reference.class) @reference.class diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 3f54e21b9..f93aa8f80 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -1,8 +1,12 @@ import * as fs from "fs"; -import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from ".."; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from ".."; + import { getContinueGlobalPath } from "./paths"; class FileSystemIde implements IDE { + getTags(artifactId: string): Promise { + return Promise.resolve([]); + } getIdeInfo(): Promise { return Promise.resolve({ ideType: "vscode", diff --git a/core/util/messageIde.ts b/core/util/messageIde.ts index 14e4c2e1d..6677f0508 100644 --- a/core/util/messageIde.ts +++ b/core/util/messageIde.ts @@ -1,9 +1,12 @@ -import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from ".."; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from ".."; export class MessageIde implements IDE { constructor( private readonly request: (messageType: string, data: any) => Promise, ) {} + getTags(artifactId: string): Promise { + return this.request("getTags", artifactId); + } getIdeInfo(): Promise { return this.request("getIdeInfo", undefined); } diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 00deb5071..a308cacb3 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -1,4 +1,5 @@ import * as path from "path"; +import { Language } from "web-tree-sitter"; const Parser = require("web-tree-sitter"); export const supportedLanguages: { [key: string]: string } = { @@ -74,15 +75,25 @@ export async function getParserForFile(filepath: string) { try { await Parser.init(); const parser = new Parser(); + + const language = await getLanguageForFile(filepath); + parser.setLanguage(language); + + return parser; + } catch (e) { + console.error("Unable to load language for file", filepath, e); + return undefined; + } +} + +export async function getLanguageForFile( + filepath: string, +): Promise { + try { + await Parser.init(); const extension = path.extname(filepath).slice(1); if (!supportedLanguages[extension]) { - console.warn( - "Unable to load language for file", - extension, - "from path: ", - filepath, - ); return undefined; } @@ -92,8 +103,7 @@ export async function getParserForFile(filepath: string) { `tree-sitter-${supportedLanguages[extension]}.wasm`, ); const language = await Parser.Language.load(wasmPath); - parser.setLanguage(language); - return parser; + return language; } catch (e) { console.error("Unable to load language for file", filepath, e); return undefined; diff --git a/core/web/webviewProtocol.ts b/core/web/webviewProtocol.ts index 248fe468f..220ed8be6 100644 --- a/core/web/webviewProtocol.ts +++ b/core/web/webviewProtocol.ts @@ -2,10 +2,12 @@ import { ContextItemWithId, ContinueRcJson, DiffLine, + IndexTag, Problem, Range, } from ".."; import { RangeInFileWithContents } from "../commands/util"; + import { Protocol } from "../protocol"; export type IdeProtocol = { @@ -45,6 +47,7 @@ export type IdeProtocol = { getTerminalContents: [undefined, string]; isTelemetryEnabled: [undefined, boolean]; getUniqueId: [undefined, string]; + getTags: [string, IndexTag[]]; }; export type WebviewProtocol = Protocol & diff --git a/core/yarn.lock b/core/yarn.lock index 6db13ef49..33b36ba9a 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -5512,6 +5512,11 @@ tr46@~0.0.3: resolved "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz" integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw== +tree-sitter-cli@^0.21.0: + version "0.21.0" + resolved "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.21.0.tgz" + integrity sha512-wA7wT5724fNQW82XDH6zT6ZcYonjrAKLCHHuhLsPcAKULrhp3rNuMvlgBdB5FUBvmjHNhtTZF/qpHenMoRJPBw== + tree-sitter-wasms@^0.1.6: version "0.1.7" resolved "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.7.tgz" diff --git a/docs/docs/customization/context-providers.md b/docs/docs/customization/context-providers.md index d3985be04..3328f2fbb 100644 --- a/docs/docs/customization/context-providers.md +++ b/docs/docs/customization/context-providers.md @@ -16,6 +16,14 @@ As an example, say you are working on solving a new GitHub Issue. You type '@iss To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list. +### Code + +Type '@code' to reference specific functions or classes from throughout your project. + +`````json +{ "name": "code" } +``` + ### Git Diff Type '@diff' to reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing. @@ -145,7 +153,7 @@ By default, the following query will be used to find issues: ```jql assignee = currentUser() AND resolution = Unresolved order by updated DESC -```` +````` You can override this query by setting the `issueQuery` parameter. diff --git a/docs/docs/walkthroughs/codellama.md b/docs/docs/walkthroughs/codellama.md index 961788cc6..9ee122234 100644 --- a/docs/docs/walkthroughs/codellama.md +++ b/docs/docs/walkthroughs/codellama.md @@ -78,7 +78,7 @@ If you haven't already installed Continue, you can do that [here](https://market "title": "Code Llama", "provider": "openai", "model": "codellama-7b", - "apiBase": "http://localhost:8000/v1" + "apiBase": "http://localhost:8000/v1/" } ] } diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index f41430f78..14fa444e1 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -187,6 +187,7 @@ "llama2", "alpaca", "zephyr", + "phi2", "phind", "anthropic", "chatml", @@ -195,7 +196,9 @@ "openchat", "xwin-coder", "neural-chat", - "codellama-70b" + "codellama-70b", + "llava", + "gemma" ], "type": "string" }, @@ -352,15 +355,22 @@ "then": { "properties": { "model": { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "AUTODETECT" + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "AUTODETECT" + ] + }, + { + "type": "string" + } ] } } @@ -1045,7 +1055,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1075,8 @@ "Include a repo map showing important code objects", "Displays important snippets of code from the currently open files", "Displays definition lines from the currently open files", - "References Postgres table schema and sample rows" + "References Postgres table schema and sample rows", + "Reference specific functions and classes from throughout your codebase" ], "type": "string" }, @@ -1259,6 +1271,10 @@ "issueQuery": { "type": "string", "description": "Customize the query used to find Jira issues" + }, + "apiVersion": { + "type": "integer", + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." } }, "required": ["domain", "email", "token"] diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index f41430f78..14fa444e1 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -187,6 +187,7 @@ "llama2", "alpaca", "zephyr", + "phi2", "phind", "anthropic", "chatml", @@ -195,7 +196,9 @@ "openchat", "xwin-coder", "neural-chat", - "codellama-70b" + "codellama-70b", + "llava", + "gemma" ], "type": "string" }, @@ -352,15 +355,22 @@ "then": { "properties": { "model": { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "AUTODETECT" + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "AUTODETECT" + ] + }, + { + "type": "string" + } ] } } @@ -1045,7 +1055,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1075,8 @@ "Include a repo map showing important code objects", "Displays important snippets of code from the currently open files", "Displays definition lines from the currently open files", - "References Postgres table schema and sample rows" + "References Postgres table schema and sample rows", + "Reference specific functions and classes from throughout your codebase" ], "type": "string" }, @@ -1259,6 +1271,10 @@ "issueQuery": { "type": "string", "description": "Customize the query used to find Jira issues" + }, + "apiVersion": { + "type": "integer", + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." } }, "required": ["domain", "email", "token"] diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f41430f78..14fa444e1 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -187,6 +187,7 @@ "llama2", "alpaca", "zephyr", + "phi2", "phind", "anthropic", "chatml", @@ -195,7 +196,9 @@ "openchat", "xwin-coder", "neural-chat", - "codellama-70b" + "codellama-70b", + "llava", + "gemma" ], "type": "string" }, @@ -352,15 +355,22 @@ "then": { "properties": { "model": { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "AUTODETECT" + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "AUTODETECT" + ] + }, + { + "type": "string" + } ] } } @@ -1045,7 +1055,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1075,8 @@ "Include a repo map showing important code objects", "Displays important snippets of code from the currently open files", "Displays definition lines from the currently open files", - "References Postgres table schema and sample rows" + "References Postgres table schema and sample rows", + "Reference specific functions and classes from throughout your codebase" ], "type": "string" }, @@ -1259,6 +1271,10 @@ "issueQuery": { "type": "string", "description": "Customize the query used to find Jira issues" + }, + "apiVersion": { + "type": "integer", + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." } }, "required": ["domain", "email", "token"] diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 3a96843fd..e21a1c0fb 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -187,6 +187,7 @@ "llama2", "alpaca", "zephyr", + "phi2", "phind", "anthropic", "chatml", @@ -195,7 +196,9 @@ "openchat", "xwin-coder", "neural-chat", - "codellama-70b" + "codellama-70b", + "llava", + "gemma" ], "type": "string" }, @@ -380,15 +383,22 @@ "then": { "properties": { "model": { - "enum": [ - "gpt-3.5-turbo", - "gpt-3.5-turbo-16k", - "gpt-4", - "gpt-3.5-turbo-0613", - "gpt-4-32k", - "gpt-4-0125-preview", - "gpt-4-turbo-preview", - "AUTODETECT" + "anyOf": [ + { + "enum": [ + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-4", + "gpt-3.5-turbo-0613", + "gpt-4-32k", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "AUTODETECT" + ] + }, + { + "type": "string" + } ] } } @@ -1161,7 +1171,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1180,7 +1191,8 @@ "Include a repo map showing important code objects", "Displays important snippets of code from the currently open files", "Displays definition lines from the currently open files", - "References Postgres table schema and sample rows" + "References Postgres table schema and sample rows", + "Reference specific functions and classes from throughout your codebase" ], "type": "string" }, @@ -1410,6 +1422,10 @@ "issueQuery": { "type": "string", "description": "Customize the query used to find Jira issues" + }, + "apiVersion": { + "type": "integer", + "markdownDescription": "This context provider supports both Jira API version 2 and 3. It will use version 3 by default since that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need to set the API Version to 2 using the `apiVersion` property." } }, "required": [ diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 936655a81..b932feff0 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -17,7 +17,7 @@ "homepage": "https://continue.dev", "qna": "https://github.com/continuedev/continue/issues/new/choose", "license": "Apache-2.0", - "displayName": "Continue - CodeLlama, GPT-4, and more", + "displayName": "Continue - Claude, CodeLlama, GPT-4, and more", "pricing": "Free", "description": "Open-source autopilot for software development - bring the power of ChatGPT to your IDE", "publisher": "Continue", diff --git a/extensions/vscode/scripts/prepackage.js b/extensions/vscode/scripts/prepackage.js index 2d409ca9d..1b8758fce 100644 --- a/extensions/vscode/scripts/prepackage.js +++ b/extensions/vscode/scripts/prepackage.js @@ -171,14 +171,18 @@ if (args[2] === "--target") { }); if (target) { // If building for production, only need the binaries for current platform - if (!target.startsWith("darwin")) { - rimrafSync(path.join(__dirname, "../bin/napi-v3/darwin")); - } - if (!target.startsWith("linux")) { - rimrafSync(path.join(__dirname, "../bin/napi-v3/linux")); - } - if (!target.startsWith("win")) { - rimrafSync(path.join(__dirname, "../bin/napi-v3/win32")); + try { + if (!target.startsWith("darwin")) { + rimrafSync(path.join(__dirname, "../bin/napi-v3/darwin")); + } + if (!target.startsWith("linux")) { + rimrafSync(path.join(__dirname, "../bin/napi-v3/linux")); + } + if (!target.startsWith("win")) { + rimrafSync(path.join(__dirname, "../bin/napi-v3/win32")); + } + } catch (e) { + console.warn("[info] Error removing unused binaries", e); } } console.log("[info] Copied onnxruntime-node"); diff --git a/extensions/vscode/src/activation/auth.ts b/extensions/vscode/src/activation/auth.ts new file mode 100644 index 000000000..f90985d96 --- /dev/null +++ b/extensions/vscode/src/activation/auth.ts @@ -0,0 +1,62 @@ +import { v4 as uuidv4 } from "uuid"; +import * as vscode from "vscode"; + +export async function setupAuth() { + const session = await vscode.authentication.getSession("github", [], { + createIfNone: true, + }); + return session; +} + +export class ManualTokenAuthProvider implements vscode.AuthenticationProvider { + constructor( + public onDidChangeSessions: vscode.Event, + private readonly context: vscode.ExtensionContext, + ) {} + + getSessions( + scopes?: readonly string[] | undefined, + ): Thenable { + const sessions = this.context.globalState.get< + vscode.AuthenticationSession[] + >("continue.manualTokenSessions"); + return Promise.resolve( + sessions?.filter((session) => { + if (!scopes) { + return true; + } + return !scopes.some((scope) => session.scopes.indexOf(scope) === -1); + }) ?? [], + ); + } + async createSession( + scopes: readonly string[], + ): Promise { + const token = await vscode.window.showInputBox({ + prompt: "Enter your Continue user token", + ignoreFocusOut: true, + }); + + if (!token) { + throw new Error("User canceled"); + } + + const session: vscode.AuthenticationSession = { + id: uuidv4(), + accessToken: token, + account: { + id: token, + label: token, + }, + scopes: [], + }; + return session; + } + removeSession(sessionId: string): Thenable { + return this.context.globalState.update( + "continue.manualTokenSessions", + (sessions: vscode.AuthenticationSession[] | undefined) => + sessions?.filter((session) => session.id !== sessionId), + ); + } +} diff --git a/extensions/vscode/src/extension/vscodeExtension.ts b/extensions/vscode/src/extension/vscodeExtension.ts index d06a3bc5a..36f8cafc4 100644 --- a/extensions/vscode/src/extension/vscodeExtension.ts +++ b/extensions/vscode/src/extension/vscodeExtension.ts @@ -11,8 +11,8 @@ import { DiffManager } from "../diff/horizontal"; import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager"; import { VsCodeIde } from "../ideProtocol"; import { registerAllCodeLensProviders } from "../lang-server/codeLens"; +import { setupRemoteConfigSync } from "../stubs/activation"; import { TabAutocompleteModel } from "../util/loadAutocompleteModel"; -import { RemoteConfigSync } from "../util/remoteConfig"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; export class VsCodeExtension { @@ -78,14 +78,10 @@ export class VsCodeExtension { this.extensionContext, this.verticalDiffManager, ); - try { - const configSync = new RemoteConfigSync( - this.configHandler.reloadConfig.bind(this.configHandler), - ); - configSync.setup(); - } catch (e) { - console.warn(`Failed to sync remote config: ${e}`); - } + + setupRemoteConfigSync( + this.configHandler.reloadConfig.bind(this.configHandler), + ); // Sidebar context.subscriptions.push( diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 8ac6e8207..ea8edcc1d 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -1,10 +1,9 @@ +import * as child_process from "child_process"; import { exec } from "child_process"; +import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range } from "core"; import { getContinueGlobalPath } from "core/util/paths"; import * as path from "path"; import * as vscode from "vscode"; - -import * as child_process from "child_process"; -import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "core"; import { DiffManager } from "./diff/horizontal"; import { VsCodeIdeUtils } from "./util/ideUtils"; import { traverseDirectory } from "./util/traverseDirectory"; @@ -20,6 +19,21 @@ class VsCodeIde implements IDE { constructor(private readonly diffManager: DiffManager) { this.ideUtils = new VsCodeIdeUtils(); } + async getTags(artifactId: string): Promise { + const workspaceDirs = await this.getWorkspaceDirs(); + + const branches = await Promise.all( + workspaceDirs.map((dir) => this.getBranch(dir)), + ); + + const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({ + directory, + branch: branches[i], + artifactId, + })); + + return tags; + } getIdeInfo(): Promise { return Promise.resolve({ ideType: "vscode", diff --git a/extensions/vscode/src/stubs/activation.ts b/extensions/vscode/src/stubs/activation.ts new file mode 100644 index 000000000..3e4ae2635 --- /dev/null +++ b/extensions/vscode/src/stubs/activation.ts @@ -0,0 +1 @@ +export async function setupRemoteConfigSync(reloadConfig: () => void) {} diff --git a/extensions/vscode/src/stubs/auth.ts b/extensions/vscode/src/stubs/auth.ts new file mode 100644 index 000000000..70de9e24b --- /dev/null +++ b/extensions/vscode/src/stubs/auth.ts @@ -0,0 +1,3 @@ +export async function getUserToken(): Promise { + return Promise.resolve(""); +} diff --git a/extensions/vscode/src/util/remoteConfig.ts b/extensions/vscode/src/util/remoteConfig.ts deleted file mode 100644 index 294277484..000000000 --- a/extensions/vscode/src/util/remoteConfig.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { - getConfigJsPathForRemote, - getConfigJsonPathForRemote, -} from "core/util/paths"; -import * as fs from "fs"; -import * as vscode from "vscode"; - -export class RemoteConfigSync { - private userToken: string | null; - private remoteConfigServerUrl: string | null; - private remoteConfigSyncPeriod: number; - - private syncInterval: NodeJS.Timer | undefined = undefined; - - constructor(private triggerReloadConfig: () => void) { - const { userToken, remoteConfigServerUrl, remoteConfigSyncPeriod } = - this.loadVsCodeSettings(); - this.userToken = userToken; - this.remoteConfigServerUrl = remoteConfigServerUrl; - this.remoteConfigSyncPeriod = remoteConfigSyncPeriod; - - // Listen for changes to VS Code settings, then trigger a refresh - vscode.workspace.onDidChangeConfiguration((event) => { - if (event.affectsConfiguration("continue")) { - const { userToken, remoteConfigServerUrl, remoteConfigSyncPeriod } = - this.loadVsCodeSettings(); - if ( - userToken !== this.userToken || - remoteConfigServerUrl !== this.remoteConfigServerUrl || - remoteConfigSyncPeriod !== this.remoteConfigSyncPeriod - ) { - this.userToken = userToken; - this.remoteConfigServerUrl = remoteConfigServerUrl; - this.remoteConfigSyncPeriod = remoteConfigSyncPeriod; - - this.setInterval(); - } - } - }); - } - - private loadVsCodeSettings() { - const settings = vscode.workspace.getConfiguration("continue"); - const userToken = settings.get("userToken", null); - const remoteConfigServerUrl = settings.get( - "remoteConfigServerUrl", - null, - ); - const remoteConfigSyncPeriod = settings.get( - "remoteConfigSyncPeriod", - 60, - ); - - return { - userToken, - remoteConfigServerUrl, - remoteConfigSyncPeriod, - }; - } - - async setup() { - if ( - this.userToken === null || - this.remoteConfigServerUrl === null || - this.remoteConfigServerUrl.trim() === "" - ) { - return; - } - if (!URL.canParse(this.remoteConfigServerUrl)) { - vscode.window.showErrorMessage( - "The value set for 'remoteConfigServerUrl' is not valid: ", - this.remoteConfigServerUrl, - ); - return; - } - - // Sync once - await this.sync(this.userToken, new URL(this.remoteConfigServerUrl)); - - // Set timer to sync at user-defined interval - this.setInterval(); - } - - private setInterval() { - if (this.syncInterval !== undefined) { - clearInterval(this.syncInterval); - } - this.syncInterval = setInterval( - () => { - if (!this.userToken || !this.remoteConfigServerUrl) return; - this.sync(this.userToken, new URL(this.remoteConfigServerUrl)); - }, - this.remoteConfigSyncPeriod * 1000 * 60, - ); - } - - async sync(userToken: string, remoteConfigServerUrl: URL) { - try { - const response = await fetch( - new URL("sync", remoteConfigServerUrl).href, - { - method: "GET", - headers: { - Authorization: `Bearer ${userToken}`, - }, - }, - ); - - if (!response.ok) { - vscode.window.showErrorMessage( - `Failed to sync remote config (HTTP ${response.status}): ${response.statusText}`, - ); - return; - } - - const { configJson, configJs } = await response.json(); - - fs.writeFileSync( - getConfigJsonPathForRemote(remoteConfigServerUrl), - configJson, - ); - fs.writeFileSync( - getConfigJsPathForRemote(remoteConfigServerUrl), - configJs, - ); - this.triggerReloadConfig(); - } catch (e) { - vscode.window.showErrorMessage(`Failed to sync remote config: ${e}`); - } - } -} diff --git a/extensions/vscode/tag-qry/tree-sitter-c-tags.scm b/extensions/vscode/tag-qry/tree-sitter-c-tags.scm new file mode 100644 index 000000000..1035aa224 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-c-tags.scm @@ -0,0 +1,9 @@ +(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class + +(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class + +(function_declarator declarator: (identifier) @name.definition.function) @definition.function + +(type_definition declarator: (type_identifier) @name.definition.type) @definition.type + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type diff --git a/extensions/vscode/tag-qry/tree-sitter-c_sharp-tags.scm b/extensions/vscode/tag-qry/tree-sitter-c_sharp-tags.scm new file mode 100644 index 000000000..58e9199a4 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-c_sharp-tags.scm @@ -0,0 +1,46 @@ +(class_declaration + name: (identifier) @name.definition.class + ) @definition.class + +(class_declaration + bases: (base_list (_) @name.reference.class) + ) @reference.class + +(interface_declaration + name: (identifier) @name.definition.interface + ) @definition.interface + +(interface_declaration + bases: (base_list (_) @name.reference.interface) + ) @reference.interface + +(method_declaration + name: (identifier) @name.definition.method + ) @definition.method + +(object_creation_expression + type: (identifier) @name.reference.class + ) @reference.class + +(type_parameter_constraints_clause + target: (identifier) @name.reference.class + ) @reference.class + +(type_constraint + type: (identifier) @name.reference.class + ) @reference.class + +(variable_declaration + type: (identifier) @name.reference.class + ) @reference.class + +(invocation_expression + function: + (member_access_expression + name: (identifier) @name.reference.send + ) +) @reference.send + +(namespace_declaration + name: (identifier) @name.definition.module +) @definition.module diff --git a/extensions/vscode/tag-qry/tree-sitter-cpp-tags.scm b/extensions/vscode/tag-qry/tree-sitter-cpp-tags.scm new file mode 100644 index 000000000..7a7ad0b99 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-cpp-tags.scm @@ -0,0 +1,15 @@ +(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class + +(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class + +(function_declarator declarator: (identifier) @name.definition.function) @definition.function + +(function_declarator declarator: (field_identifier) @name.definition.function) @definition.function + +(function_declarator declarator: (qualified_identifier scope: (namespace_identifier) @scope name: (identifier) @name.definition.method)) @definition.method + +(type_definition declarator: (type_identifier) @name.definition.type) @definition.type + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type + +(class_specifier name: (type_identifier) @name.definition.class) @definition.class diff --git a/extensions/vscode/tag-qry/tree-sitter-elisp-tags.scm b/extensions/vscode/tag-qry/tree-sitter-elisp-tags.scm new file mode 100644 index 000000000..743c8d8a8 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-elisp-tags.scm @@ -0,0 +1,8 @@ +;; defun/defsubst +(function_definition name: (symbol) @name.definition.function) @definition.function + +;; Treat macros as function definitions for the sake of TAGS. +(macro_definition name: (symbol) @name.definition.function) @definition.function + +;; Match function calls +(list (symbol) @name.reference.function) @reference.function diff --git a/extensions/vscode/tag-qry/tree-sitter-elixir-tags.scm b/extensions/vscode/tag-qry/tree-sitter-elixir-tags.scm new file mode 100644 index 000000000..9eb39d95d --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-elixir-tags.scm @@ -0,0 +1,54 @@ +; Definitions + +; * modules and protocols +(call + target: (identifier) @ignore + (arguments (alias) @name.definition.module) + (#match? @ignore "^(defmodule|defprotocol)$")) @definition.module + +; * functions/macros +(call + target: (identifier) @ignore + (arguments + [ + ; zero-arity functions with no parentheses + (identifier) @name.definition.function + ; regular function clause + (call target: (identifier) @name.definition.function) + ; function clause with a guard clause + (binary_operator + left: (call target: (identifier) @name.definition.function) + operator: "when") + ]) + (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @definition.function + +; References + +; ignore calls to kernel/special-forms keywords +(call + target: (identifier) @ignore + (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp|defmodule|defprotocol|defimpl|defstruct|defexception|defoverridable|alias|case|cond|else|for|if|import|quote|raise|receive|require|reraise|super|throw|try|unless|unquote|unquote_splicing|use|with)$")) + +; ignore module attributes +(unary_operator + operator: "@" + operand: (call + target: (identifier) @ignore)) + +; * function call +(call + target: [ + ; local + (identifier) @name.reference.call + ; remote + (dot + right: (identifier) @name.reference.call) + ]) @reference.call + +; * pipe into function call +(binary_operator + operator: "|>" + right: (identifier) @name.reference.call) @reference.call + +; * modules +(alias) @name.reference.module @reference.module diff --git a/extensions/vscode/tag-qry/tree-sitter-elm-tags.scm b/extensions/vscode/tag-qry/tree-sitter-elm-tags.scm new file mode 100644 index 000000000..ad15d5e67 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-elm-tags.scm @@ -0,0 +1,19 @@ +(value_declaration (function_declaration_left (lower_case_identifier) @name.definition.function)) @definition.function + +(function_call_expr (value_expr (value_qid) @name.reference.function)) @reference.function +(exposed_value (lower_case_identifier) @name.reference.function)) @reference.function +(type_annotation ((lower_case_identifier) @name.reference.function) (colon)) @reference.function + +(type_declaration ((upper_case_identifier) @name.definition.type) ) @definition.type + +(type_ref (upper_case_qid (upper_case_identifier) @name.reference.type)) @reference.type +(exposed_type (upper_case_identifier) @name.reference.type)) @reference.type + +(type_declaration (union_variant (upper_case_identifier) @name.definition.union)) @definition.union + +(value_expr (upper_case_qid (upper_case_identifier) @name.reference.union)) @reference.union + + +(module_declaration + (upper_case_qid (upper_case_identifier)) @name.definition.module +) @definition.module diff --git a/extensions/vscode/tag-qry/tree-sitter-go-tags.scm b/extensions/vscode/tag-qry/tree-sitter-go-tags.scm new file mode 100644 index 000000000..a32d03aa7 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-go-tags.scm @@ -0,0 +1,30 @@ +( + (comment)* @doc + . + (function_declaration + name: (identifier) @name.definition.function) @definition.function + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (method_declaration + name: (field_identifier) @name.definition.method) @definition.method + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.method) +) + +(call_expression + function: [ + (identifier) @name.reference.call + (parenthesized_expression (identifier) @name.reference.call) + (selector_expression field: (field_identifier) @name.reference.call) + (parenthesized_expression (selector_expression field: (field_identifier) @name.reference.call)) + ]) @reference.call + +(type_spec + name: (type_identifier) @name.definition.type) @definition.type + +(type_identifier) @name.reference.type @reference.type diff --git a/extensions/vscode/tag-qry/tree-sitter-java-tags.scm b/extensions/vscode/tag-qry/tree-sitter-java-tags.scm new file mode 100644 index 000000000..3b7290d46 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-java-tags.scm @@ -0,0 +1,20 @@ +(class_declaration + name: (identifier) @name.definition.class) @definition.class + +(method_declaration + name: (identifier) @name.definition.method) @definition.method + +(method_invocation + name: (identifier) @name.reference.call + arguments: (argument_list) @reference.call) + +(interface_declaration + name: (identifier) @name.definition.interface) @definition.interface + +(type_list + (type_identifier) @name.reference.implementation) @reference.implementation + +(object_creation_expression + type: (type_identifier) @name.reference.class) @reference.class + +(superclass (type_identifier) @name.reference.class) @reference.class diff --git a/extensions/vscode/tag-qry/tree-sitter-javascript-tags.scm b/extensions/vscode/tag-qry/tree-sitter-javascript-tags.scm new file mode 100644 index 000000000..3bc55c5c5 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-javascript-tags.scm @@ -0,0 +1,88 @@ +( + (comment)* @doc + . + (method_definition + name: (property_identifier) @name.definition.method) @definition.method + (#not-eq? @name.definition.method "constructor") + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.method) +) + +( + (comment)* @doc + . + [ + (class + name: (_) @name.definition.class) + (class_declaration + name: (_) @name.definition.class) + ] @definition.class + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.class) +) + +( + (comment)* @doc + . + [ + (function + name: (identifier) @name.definition.function) + (function_declaration + name: (identifier) @name.definition.function) + (generator_function + name: (identifier) @name.definition.function) + (generator_function_declaration + name: (identifier) @name.definition.function) + ] @definition.function + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (lexical_declaration + (variable_declarator + name: (identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function) + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (variable_declaration + (variable_declarator + name: (identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function) + (#strip! @doc "^[\\s\\*/]+|^[\\s\\*/]$") + (#select-adjacent! @doc @definition.function) +) + +(assignment_expression + left: [ + (identifier) @name.definition.function + (member_expression + property: (property_identifier) @name.definition.function) + ] + right: [(arrow_function) (function)] +) @definition.function + +(pair + key: (property_identifier) @name.definition.function + value: [(arrow_function) (function)]) @definition.function + +( + (call_expression + function: (identifier) @name.reference.call) @reference.call + (#not-match? @name.reference.call "^(require)$") +) + +(call_expression + function: (member_expression + property: (property_identifier) @name.reference.call) + arguments: (_) @reference.call) + +(new_expression + constructor: (_) @name.reference.class) @reference.class diff --git a/extensions/vscode/tag-qry/tree-sitter-ocaml-tags.scm b/extensions/vscode/tag-qry/tree-sitter-ocaml-tags.scm new file mode 100644 index 000000000..1799f8acf --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-ocaml-tags.scm @@ -0,0 +1,116 @@ +; Modules +;-------- + +( + (comment)? @doc . + (module_definition (module_binding (module_name) @name.definition.module) @definition.module) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(module_path (module_name) @name.reference.module) @reference.module + +; Modules types +;-------------- + +( + (comment)? @doc . + (module_type_definition (module_type_name) @name.definition.interface) @definition.interface + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(module_type_path (module_type_name) @name.reference.implementation) @reference.implementation + +; Functions +;---------- + +( + (comment)? @doc . + (value_definition + [ + (let_binding + pattern: (value_name) @name.definition.function + (parameter)) + (let_binding + pattern: (value_name) @name.definition.function + body: [(fun_expression) (function_expression)]) + ] @definition.function + ) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +( + (comment)? @doc . + (external (value_name) @name.definition.function) @definition.function + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(application_expression + function: (value_path (value_name) @name.reference.call)) @reference.call + +(infix_expression + left: (value_path (value_name) @name.reference.call) + (infix_operator) @reference.call + (#eq? @reference.call "@@")) + +(infix_expression + (infix_operator) @reference.call + right: (value_path (value_name) @name.reference.call) + (#eq? @reference.call "|>")) + +; Operator +;--------- + +( + (comment)? @doc . + (value_definition + (let_binding + pattern: (parenthesized_operator [ + (prefix_operator) + (infix_operator) + (hash_operator) + (indexing_operator) + (let_operator) + (and_operator) + (match_operator) + ] @name.definition.function)) @definition.function) + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +[ + (prefix_operator) + (sign_operator) + (infix_operator) + (hash_operator) + (indexing_operator) + (let_operator) + (and_operator) + (match_operator) +] @name.reference.call @reference.call + +; Classes +;-------- + +( + (comment)? @doc . + [ + (class_definition (class_binding (class_name) @name.definition.class) @definition.class) + (class_type_definition (class_type_binding (class_type_name) @name.definition.class) @definition.class) + ] + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +[ + (class_path (class_name) @name.reference.class) + (class_type_path (class_type_name) @name.reference.class) +] @reference.class + +; Methods +;-------- + +( + (comment)? @doc . + (method_definition (method_name) @name.definition.method) @definition.method + (#strip! @doc "^\\(\\*\\*?\\s*|\\s\\*\\)$") +) + +(method_invocation (method_name) @name.reference.call) @reference.call diff --git a/extensions/vscode/tag-qry/tree-sitter-php-tags.scm b/extensions/vscode/tag-qry/tree-sitter-php-tags.scm new file mode 100644 index 000000000..61c86fcbe --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-php-tags.scm @@ -0,0 +1,26 @@ +(class_declaration + name: (name) @name.definition.class) @definition.class + +(function_definition + name: (name) @name.definition.function) @definition.function + +(method_declaration + name: (name) @name.definition.function) @definition.function + +(object_creation_expression + [ + (qualified_name (name) @name.reference.class) + (variable_name (name) @name.reference.class) + ]) @reference.class + +(function_call_expression + function: [ + (qualified_name (name) @name.reference.call) + (variable_name (name)) @name.reference.call + ]) @reference.call + +(scoped_call_expression + name: (name) @name.reference.call) @reference.call + +(member_call_expression + name: (name) @name.reference.call) @reference.call diff --git a/extensions/vscode/tag-qry/tree-sitter-python-tags.scm b/extensions/vscode/tag-qry/tree-sitter-python-tags.scm new file mode 100644 index 000000000..3be5bed9f --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-python-tags.scm @@ -0,0 +1,12 @@ +(class_definition + name: (identifier) @name.definition.class) @definition.class + +(function_definition + name: (identifier) @name.definition.function) @definition.function + +(call + function: [ + (identifier) @name.reference.call + (attribute + attribute: (identifier) @name.reference.call) + ]) @reference.call diff --git a/extensions/vscode/tag-qry/tree-sitter-ql-tags.scm b/extensions/vscode/tag-qry/tree-sitter-ql-tags.scm new file mode 100644 index 000000000..3164aa25a --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-ql-tags.scm @@ -0,0 +1,26 @@ +(classlessPredicate + name: (predicateName) @name.definition.function) @definition.function + +(memberPredicate + name: (predicateName) @name.definition.method) @definition.method + +(aritylessPredicateExpr + name: (literalId) @name.reference.call) @reference.call + +(module + name: (moduleName) @name.definition.module) @definition.module + +(dataclass + name: (className) @name.definition.class) @definition.class + +(datatype + name: (className) @name.definition.class) @definition.class + +(datatypeBranch + name: (className) @name.definition.class) @definition.class + +(qualifiedRhs + name: (predicateName) @name.reference.call) @reference.call + +(typeExpr + name: (className) @name.reference.type) @reference.type diff --git a/extensions/vscode/tag-qry/tree-sitter-ruby-tags.scm b/extensions/vscode/tag-qry/tree-sitter-ruby-tags.scm new file mode 100644 index 000000000..79e71d2d6 --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-ruby-tags.scm @@ -0,0 +1,64 @@ +; Method definitions + +( + (comment)* @doc + . + [ + (method + name: (_) @name.definition.method) @definition.method + (singleton_method + name: (_) @name.definition.method) @definition.method + ] + (#strip! @doc "^#\\s*") + (#select-adjacent! @doc @definition.method) +) + +(alias + name: (_) @name.definition.method) @definition.method + +(setter + (identifier) @ignore) + +; Class definitions + +( + (comment)* @doc + . + [ + (class + name: [ + (constant) @name.definition.class + (scope_resolution + name: (_) @name.definition.class) + ]) @definition.class + (singleton_class + value: [ + (constant) @name.definition.class + (scope_resolution + name: (_) @name.definition.class) + ]) @definition.class + ] + (#strip! @doc "^#\\s*") + (#select-adjacent! @doc @definition.class) +) + +; Module definitions + +( + (module + name: [ + (constant) @name.definition.module + (scope_resolution + name: (_) @name.definition.module) + ]) @definition.module +) + +; Calls + +(call method: (identifier) @name.reference.call) @reference.call + +( + [(identifier) (constant)] @name.reference.call @reference.call + (#is-not? local) + (#not-match? @name.reference.call "^(lambda|load|require|require_relative|__FILE__|__LINE__)$") +) diff --git a/extensions/vscode/tag-qry/tree-sitter-rust-tags.scm b/extensions/vscode/tag-qry/tree-sitter-rust-tags.scm new file mode 100644 index 000000000..dadfa7acb --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-rust-tags.scm @@ -0,0 +1,60 @@ +; ADT definitions + +(struct_item + name: (type_identifier) @name.definition.class) @definition.class + +(enum_item + name: (type_identifier) @name.definition.class) @definition.class + +(union_item + name: (type_identifier) @name.definition.class) @definition.class + +; type aliases + +(type_item + name: (type_identifier) @name.definition.class) @definition.class + +; method definitions + +(declaration_list + (function_item + name: (identifier) @name.definition.method)) @definition.method + +; function definitions + +(function_item + name: (identifier) @name.definition.function) @definition.function + +; trait definitions +(trait_item + name: (type_identifier) @name.definition.interface) @definition.interface + +; module definitions +(mod_item + name: (identifier) @name.definition.module) @definition.module + +; macro definitions + +(macro_definition + name: (identifier) @name.definition.macro) @definition.macro + +; references + +(call_expression + function: (identifier) @name.reference.call) @reference.call + +(call_expression + function: (field_expression + field: (field_identifier) @name.reference.call)) @reference.call + +(macro_invocation + macro: (identifier) @name.reference.call) @reference.call + +; implementations + +(impl_item + trait: (type_identifier) @name.reference.implementation) @reference.implementation + +(impl_item + type: (type_identifier) @name.reference.implementation + !trait) @reference.implementation diff --git a/extensions/vscode/tag-qry/tree-sitter-typescript-tags.scm b/extensions/vscode/tag-qry/tree-sitter-typescript-tags.scm new file mode 100644 index 000000000..b1ab874dd --- /dev/null +++ b/extensions/vscode/tag-qry/tree-sitter-typescript-tags.scm @@ -0,0 +1,23 @@ +(function_signature + name: (identifier) @name.definition.function) @definition.function + +(method_signature + name: (property_identifier) @name.definition.method) @definition.method + +(abstract_method_signature + name: (property_identifier) @name.definition.method) @definition.method + +(abstract_class_declaration + name: (type_identifier) @name.definition.class) @definition.class + +(module + name: (identifier) @name.definition.module) @definition.module + +(interface_declaration + name: (type_identifier) @name.definition.interface) @definition.interface + +(type_annotation + (type_identifier) @name.reference.type) @reference.type + +(new_expression + constructor: (identifier) @name.reference.class) @reference.class diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm new file mode 100644 index 000000000..bb343911e --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm @@ -0,0 +1,9 @@ +(function_definition declarator: (function_declarator (identifier) @name)) @definition.function + +(struct_specifier name: (type_identifier) @name.definition.class body:(_)) @definition.class + +(declaration type: (union_specifier name: (type_identifier) @name.definition.class)) @definition.class + +(type_definition declarator: (type_identifier) @name ) @body + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm new file mode 100644 index 000000000..d3334b9bd --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm @@ -0,0 +1,23 @@ +(class_declaration + name: (identifier) @name.definition.class + ) @definition.class + +(class_declaration + bases: (base_list (_) @name.reference.class) + ) @reference.class + +(interface_declaration + name: (identifier) @name.definition.interface + ) @definition.interface + +(interface_declaration + bases: (base_list (_) @name.reference.interface) + ) @reference.interface + +(method_declaration + name: (identifier) @name.definition.method + ) @definition.method + +(namespace_declaration + name: (identifier) @name.definition.module +) @definition.module diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm new file mode 100644 index 000000000..ed2154aca --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm @@ -0,0 +1,7 @@ +(function_definition declarator: (function_declarator) @name.definition.function) @definition.function + +(type_definition declarator: (type_identifier) @name.definition.type) @definition.type + +(enum_specifier name: (type_identifier) @name.definition.type) @definition.type + +(class_specifier name: (type_identifier) @name.definition.class) @definition.class diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm new file mode 100644 index 000000000..0c9bc51e9 --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm @@ -0,0 +1,6 @@ +;; defun/defsubst +(function_definition name: (symbol) @name.definition.function) @definition.function + +;; Treat macros as function definitions for the sake of TAGS. +(macro_definition name: (symbol) @name.definition.function) @definition.function + diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm new file mode 100644 index 000000000..e43215bb3 --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm @@ -0,0 +1,26 @@ +; Definitions + +; * modules and protocols +(call + target: (identifier) @ignore + (arguments (alias) @name.definition.module) + (#match? @ignore "^(defmodule|defprotocol)$")) @definition.module + +; * functions/macros +(call + target: (identifier) @ignore + (arguments + [ + ; zero-arity functions with no parentheses + (identifier) @name.definition.function + ; regular function clause + (call target: (identifier) @name.definition.function) + ; function clause with a guard clause + (binary_operator + left: (call target: (identifier) @name.definition.function) + operator: "when") + ]) + (#match? @ignore "^(def|defp|defdelegate|defguard|defguardp|defmacro|defmacrop|defn|defnp)$")) @definition.function + +; * modules +(alias) @name.reference.module @reference.module diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm new file mode 100644 index 000000000..9d2af874d --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm @@ -0,0 +1,20 @@ +( + (comment)* @doc + . + (function_declaration + name: (identifier) @name.definition.function) @definition.function + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.function) +) + +( + (comment)* @doc + . + (method_declaration + name: (field_identifier) @name.definition.method) @definition.method + (#strip! @doc "^//\\s*") + (#set-adjacent! @doc @definition.method) +) + +(type_spec + name: (type_identifier) @name.definition.type) @definition.type \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm new file mode 100644 index 000000000..593a75fc6 --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm @@ -0,0 +1,8 @@ +(class_declaration + name: (identifier) @name.definition.class) @definition.class + +(method_declaration + name: (identifier) @name.definition.method) @definition.method + +(interface_declaration + name: (identifier) @name.definition.interface) @definition.interface \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm new file mode 100644 index 000000000..7be9458f4 --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm @@ -0,0 +1,8 @@ +(class_declaration + name: (_) @name) @body + +(function_declaration + name: (_) @name) @body + +(method_definition + name: (_) @name) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm new file mode 100644 index 000000000..9bc034d8e --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm @@ -0,0 +1,12 @@ +(value_definition + (let_binding + pattern: (_) @name) +) @body + +(module_type_definition + name: (_) @name) @body + +(class_definition + (class_binding + name: (_) @name) +) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm new file mode 100644 index 000000000..c95663f3c --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm @@ -0,0 +1,8 @@ +(class_declaration + name: (name) @name) @body + +(function_definition + name: (name) @name) @body + +(method_declaration + name: (name) @name) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm new file mode 100644 index 000000000..04289704f --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm @@ -0,0 +1,5 @@ +(class_definition + name: (_) @name) @body + +(function_definition + name: (_) @name) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm new file mode 100644 index 000000000..3164aa25a --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm @@ -0,0 +1,26 @@ +(classlessPredicate + name: (predicateName) @name.definition.function) @definition.function + +(memberPredicate + name: (predicateName) @name.definition.method) @definition.method + +(aritylessPredicateExpr + name: (literalId) @name.reference.call) @reference.call + +(module + name: (moduleName) @name.definition.module) @definition.module + +(dataclass + name: (className) @name.definition.class) @definition.class + +(datatype + name: (className) @name.definition.class) @definition.class + +(datatypeBranch + name: (className) @name.definition.class) @definition.class + +(qualifiedRhs + name: (predicateName) @name.reference.call) @reference.call + +(typeExpr + name: (className) @name.reference.type) @reference.type diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ruby-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ruby-tags.scm new file mode 100644 index 000000000..e69de29bb diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm new file mode 100644 index 000000000..e4125cabf --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm @@ -0,0 +1,8 @@ +(function_item + name: (_) @name) @body + +(struct_item + name: (_) @name) @body + +(impl_item + type: (_) @name) @body \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm new file mode 100644 index 000000000..c56cf4fba --- /dev/null +++ b/extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm @@ -0,0 +1,11 @@ +(class_declaration + name: (_) @name) @body + +(function_declaration + name: (_) @name) @body + +(method_definition + name: (_) @name) @body + +(interface_declaration + name: (_) @name) @body \ No newline at end of file diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 4695b874d..2b4de321a 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -5,6 +5,7 @@ import { BeakerIcon, BookOpenIcon, ChevronDoubleRightIcon, + CodeBracketIcon, Cog6ToothIcon, CommandLineIcon, ExclamationCircleIcon, @@ -47,6 +48,7 @@ import { ComboBoxItem } from "./types"; const ICONS_FOR_DROPDOWN: { [key: string]: any } = { file: FolderIcon, + code: CodeBracketIcon, terminal: CommandLineIcon, diff: PlusIcon, search: MagnifyingGlassIcon, @@ -163,7 +165,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { const [selectedIndex, setSelectedIndex] = useState(0); const [subMenuTitle, setSubMenuTitle] = useState( - undefined + undefined, ); const [querySubmenuItem, setQuerySubmenuItem] = useState< ComboBoxItem | undefined @@ -173,7 +175,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { useEffect(() => { const items = [...props.items]; - if (subMenuTitle === "Search documentation") { + if (subMenuTitle === "Type to search docs") { items.push({ title: "Add Docs", type: "action", @@ -186,7 +188,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { const text = tr.doc.textBetween(0, tr.selection.from); const start = text.lastIndexOf("@"); props.editor.view.dispatch( - tr.delete(start, tr.selection.from).scrollIntoView() + tr.delete(start, tr.selection.from).scrollIntoView(), ); }, description: "Add a new documentation source", @@ -281,6 +283,10 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { }, })); + const showFileIconForItem = (item: ComboBoxItem) => { + return ["file", "code"].includes(item.type); + }; + return ( {querySubmenuItem ? ( @@ -322,14 +328,14 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { >
- {item.type === "file" && ( + {showFileIconForItem(item) && ( )} - {item.type !== "file" && ( + {!showFileIconForItem(item) && ( <> diff --git a/gui/src/util/modelData.ts b/gui/src/util/modelData.ts index ff782f86a..adab0715a 100644 --- a/gui/src/util/modelData.ts +++ b/gui/src/util/modelData.ts @@ -808,7 +808,7 @@ export const PROVIDER_INFO: { [key: string]: ModelInfo } = { icon: "lmstudio.png", tags: [ModelProviderTag["Local"], ModelProviderTag["Open-Source"]], params: { - apiBase: "http://localhost:1234/v1", + apiBase: "http://localhost:1234/v1/", }, packages: [ { @@ -899,7 +899,7 @@ After it's up and running, you can start using Continue.`, collectInputFor: [ { ...apiBaseInput, - defaultValue: "http://localhost:8000/v1", + defaultValue: "http://localhost:8000/v1/", }, ...completionParamsInputs, ],