From 8a8a87889ec4ccf051c1771eb6995b850802e47a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 3 Mar 2024 20:22:08 -0500 Subject: [PATCH 01/24] =?UTF-8?q?=F0=9F=9A=A7=20WIP=20on=20indexing=20for?= =?UTF-8?q?=20code=20context=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/CodeSnippetsIndex.ts | 104 +++++++++++++++++ core/tag-qry/tree-sitter-c-tags.scm | 9 ++ core/tag-qry/tree-sitter-c_sharp-tags.scm | 46 ++++++++ core/tag-qry/tree-sitter-cpp-tags.scm | 15 +++ core/tag-qry/tree-sitter-elisp-tags.scm | 8 ++ core/tag-qry/tree-sitter-elixir-tags.scm | 54 +++++++++ core/tag-qry/tree-sitter-elm-tags.scm | 19 +++ core/tag-qry/tree-sitter-go-tags.scm | 30 +++++ core/tag-qry/tree-sitter-java-tags.scm | 20 ++++ core/tag-qry/tree-sitter-javascript-tags.scm | 88 ++++++++++++++ core/tag-qry/tree-sitter-ocaml-tags.scm | 116 +++++++++++++++++++ core/tag-qry/tree-sitter-php-tags.scm | 26 +++++ core/tag-qry/tree-sitter-python-tags.scm | 12 ++ core/tag-qry/tree-sitter-ql-tags.scm | 26 +++++ core/tag-qry/tree-sitter-ruby-tags.scm | 64 ++++++++++ core/tag-qry/tree-sitter-rust-tags.scm | 60 ++++++++++ core/tag-qry/tree-sitter-typescript-tags.scm | 23 ++++ core/util/treeSitter.ts | 19 ++- 18 files changed, 737 insertions(+), 2 deletions(-) create mode 100644 core/indexing/CodeSnippetsIndex.ts create mode 100644 core/tag-qry/tree-sitter-c-tags.scm create mode 100644 core/tag-qry/tree-sitter-c_sharp-tags.scm create mode 100644 core/tag-qry/tree-sitter-cpp-tags.scm create mode 100644 core/tag-qry/tree-sitter-elisp-tags.scm create mode 100644 core/tag-qry/tree-sitter-elixir-tags.scm create mode 100644 core/tag-qry/tree-sitter-elm-tags.scm create mode 100644 core/tag-qry/tree-sitter-go-tags.scm create mode 100644 core/tag-qry/tree-sitter-java-tags.scm create mode 100644 core/tag-qry/tree-sitter-javascript-tags.scm create mode 100644 core/tag-qry/tree-sitter-ocaml-tags.scm create mode 100644 core/tag-qry/tree-sitter-php-tags.scm create mode 100644 core/tag-qry/tree-sitter-python-tags.scm create mode 100644 core/tag-qry/tree-sitter-ql-tags.scm create mode 100644 core/tag-qry/tree-sitter-ruby-tags.scm create mode 100644 core/tag-qry/tree-sitter-rust-tags.scm create mode 100644 core/tag-qry/tree-sitter-typescript-tags.scm diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts new file mode 100644 index 000000000..55bddb88c --- /dev/null +++ b/core/indexing/CodeSnippetsIndex.ts @@ -0,0 +1,104 @@ +import fs from "fs"; +import path from "path"; +import { ChunkWithoutID, IDE, IndexingProgressUpdate } from ".."; +import { + getLanguageForFile, + getParserForFile, + supportedLanguages, +} from "../util/treeSitter"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { + CodebaseIndex, + IndexResultType, + IndexTag, + 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, + startLine INTEGER NOT NULL, + endLine INTEGER NOT NULL + )`); + } + + private getQuerySource(filepath: string) { + const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""]; + const sourcePath = path.join( + __dirname, + "..", + "tag-qry", + `tree-sitter-${fullLangName}-tags.scm`, + ); + return fs.readFileSync(sourcePath).toString(); + } + + async getSnippetsInFile( + filepath: string, + contents: string, + ): Promise { + const lang = await getLanguageForFile(filepath); + const parser = await getParserForFile(filepath); + const ast = parser.parse(contents); + const query = lang?.query(this.getQuerySource(filepath)); + const matches = query?.matches(ast.rootNode); + + return ( + matches?.flatMap((match) => { + const nodes = match.captures.map((capture) => capture.node); + const results = nodes.map((node) => ({ + 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); + + 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) { + await db.run( + `INSERT INTO code_snippets (path, cacheKey, content, startLine, endLine) VALUES (?, ?, ?, ?, ?)`, + [ + compute.path, + compute.cacheKey, + snippet.content, + snippet.startLine, + snippet.endLine, + ], + ); + } + + yield { + desc: `Indexing ${compute.path}`, + progress: i / results.compute.length, + }; + markComplete([compute], IndexResultType.Compute); + } + } +} 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/treeSitter.ts b/core/util/treeSitter.ts index 3e82e0811..f0e9814b3 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 } = { @@ -71,6 +72,21 @@ 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 { const extension = path.extname(filepath).slice(1); if (!supportedLanguages[extension]) { @@ -89,8 +105,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; From d4e9fd2a819de8ed85d13226ca6e2e125ab92c9e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sun, 3 Mar 2024 22:38:20 -0500 Subject: [PATCH 02/24] =?UTF-8?q?=F0=9F=9A=A7=20WIP=20on=20auth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/src/activation/activate.ts | 12 ++++ extensions/vscode/src/activation/auth.ts | 62 ++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 extensions/vscode/src/activation/auth.ts diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 3de6b77be..558096b14 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -7,6 +7,7 @@ import { VsCodeExtension } from "../extension/vscodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; import { getExtensionUri } from "../util/vscode"; +import { ManualTokenAuthProvider } from "./auth"; import { setupInlineTips } from "./inlineTips"; export async function showTutorial() { @@ -67,6 +68,17 @@ function showRefactorMigrationMessage( } export async function activateExtension(context: vscode.ExtensionContext) { + const authProvider = vscode.authentication.registerAuthenticationProvider( + "manualToken", + "Continue Manual Token", + new ManualTokenAuthProvider(() => { + return new vscode.Disposable(() => {}); + }, context), + ); + const session = await vscode.authentication.getSession("manualToken", [], { + createIfNone: true, + }); + // Add necessary files getTsConfigPath(); 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), + ); + } +} From fa8d6fc36a7ba9b57f16cf45b9cf6d5bd81a89dd Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 9 Mar 2024 13:54:19 -0800 Subject: [PATCH 03/24] =?UTF-8?q?=F0=9F=9A=A7=20full=20draft=20of=20code?= =?UTF-8?q?=20context=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/retrieval.ts | 3 +- core/context/providers/CodeContextProvider.ts | 44 +++++++ core/context/providers/index.ts | 2 + core/context/retrieval.ts | 4 +- core/index.d.ts | 31 +++-- core/indexing/CodeSnippetsIndex.ts | 104 +++++++++++++++- core/indexing/FullTextSearch.ts | 3 +- core/indexing/LanceDbIndex.ts | 8 +- core/indexing/README.md | 30 +++++ core/indexing/chunk/ChunkCodebaseIndex.ts | 15 ++- core/indexing/indexCodebase.ts | 6 +- core/indexing/refreshIndex.ts | 3 +- core/indexing/types.ts | 8 +- core/util/filesystem.ts | 6 +- core/util/messageIde.ts | 5 +- core/web/webviewProtocol.ts | 3 + extensions/vscode/src/ideProtocol.ts | 25 +++- .../vscode/tag-qry/tree-sitter-c-tags.scm | 9 ++ .../tag-qry/tree-sitter-c_sharp-tags.scm | 46 +++++++ .../vscode/tag-qry/tree-sitter-cpp-tags.scm | 15 +++ .../vscode/tag-qry/tree-sitter-elisp-tags.scm | 8 ++ .../tag-qry/tree-sitter-elixir-tags.scm | 54 ++++++++ .../vscode/tag-qry/tree-sitter-elm-tags.scm | 19 +++ .../vscode/tag-qry/tree-sitter-go-tags.scm | 30 +++++ .../vscode/tag-qry/tree-sitter-java-tags.scm | 20 +++ .../tag-qry/tree-sitter-javascript-tags.scm | 88 +++++++++++++ .../vscode/tag-qry/tree-sitter-ocaml-tags.scm | 116 ++++++++++++++++++ .../vscode/tag-qry/tree-sitter-php-tags.scm | 26 ++++ .../tag-qry/tree-sitter-python-tags.scm | 12 ++ .../vscode/tag-qry/tree-sitter-ql-tags.scm | 26 ++++ .../vscode/tag-qry/tree-sitter-ruby-tags.scm | 64 ++++++++++ .../vscode/tag-qry/tree-sitter-rust-tags.scm | 60 +++++++++ .../tag-qry/tree-sitter-typescript-tags.scm | 23 ++++ extensions/vscode/yarn.lock | 5 + 34 files changed, 878 insertions(+), 43 deletions(-) create mode 100644 core/context/providers/CodeContextProvider.ts create mode 100644 core/indexing/README.md create mode 100644 extensions/vscode/tag-qry/tree-sitter-c-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-c_sharp-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-cpp-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-elisp-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-elixir-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-elm-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-go-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-java-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-javascript-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-ocaml-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-php-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-python-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-ql-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-ruby-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-rust-tags.scm create mode 100644 extensions/vscode/tag-qry/tree-sitter-typescript-tags.scm 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/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 17f83467f..53f0a48ef 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -16,7 +16,7 @@ declare global { postIntellijMessage?: ( messageType: string, data: any, - messageIde: string + messageIde: string, ) => void; } } @@ -73,17 +73,17 @@ export interface ILLM extends LLMOptions { streamComplete( prompt: string, - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): AsyncGenerator; streamChat( messages: ChatMessage[], - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): AsyncGenerator; chat( messages: ChatMessage[], - options?: LLMFullCompletionOptions + options?: LLMFullCompletionOptions, ): Promise; countTokens(text: string): number; @@ -123,10 +123,10 @@ export interface CustomContextProvider { type?: ContextProviderType; getContextItems( query: string, - extras: ContextProviderExtras + extras: ContextProviderExtras, ): Promise; loadSubmenuItems?: ( - args: LoadSubmenuItemsArgs + args: LoadSubmenuItemsArgs, ) => Promise; } @@ -141,7 +141,7 @@ export interface IContextProvider { getContextItems( query: string, - extras: ContextProviderExtras + extras: ContextProviderExtras, ): Promise; loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise; @@ -287,15 +287,15 @@ export interface CustomLLMWithOptionals { streamCompletion?: ( prompt: string, options: CompletionOptions, - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; streamChat?: ( messages: ChatMessage[], options: CompletionOptions, - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => AsyncGenerator; listModels?: ( - fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise + fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise, ) => Promise; } @@ -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; @@ -349,12 +355,12 @@ export interface IDE { showLines( filepath: string, startLine: number, - endLine: number + endLine: number, ): Promise; showDiff( filepath: string, newContents: string, - stepIndex: number + stepIndex: number, ): Promise; getOpenFiles(): Promise; getPinnedFiles(): 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 diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 55bddb88c..26edbc432 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -1,16 +1,23 @@ import fs from "fs"; import path from "path"; -import { ChunkWithoutID, IDE, IndexingProgressUpdate } from ".."; +import { + ChunkWithoutID, + ContextItem, + ContextSubmenuItem, + IDE, + IndexTag, + IndexingProgressUpdate, +} from ".."; +import { getBasename } from "../util"; import { getLanguageForFile, getParserForFile, supportedLanguages, } from "../util/treeSitter"; -import { DatabaseConnection, SqliteDb } from "./refreshIndex"; +import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex"; import { CodebaseIndex, IndexResultType, - IndexTag, MarkCompleteCallback, RefreshIndexResults, } from "./types"; @@ -29,6 +36,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { 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) { @@ -39,6 +53,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { "tag-qry", `tree-sitter-${fullLangName}-tags.scm`, ); + if (!fs.existsSync(sourcePath)) { + return ""; + } return fs.readFileSync(sourcePath).toString(); } @@ -72,6 +89,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { ): 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]; @@ -82,7 +100,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add snippets to sqlite for (const snippet of snippets) { - await db.run( + const { lastID } = await db.run( `INSERT INTO code_snippets (path, cacheKey, content, startLine, endLine) VALUES (?, ?, ?, ?, ?)`, [ compute.path, @@ -92,6 +110,11 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { snippet.endLine, ], ); + + await db.run( + `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, + [lastID, tagString], + ); } yield { @@ -100,5 +123,78 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { }; 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_snippet_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: getBasename(row.path), + description: getBasename(row.path, 2), + content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, + }; + } + + static async getAll(tag: IndexTag): Promise { + const db = await SqliteDb.get(); + const rows = await db.all( + `SELECT * + FROM code_snippets cs + JOIN code_snippets_tags cst ON cs.id = cst.snippetId + WHERE cst.tag = ?; + `, + [tagToString(tag)], + ); + + return rows.map((row) => ({ + title: getBasename(row.path), + description: getBasename(row.path, 2), + id: row.id.toString(), + })); } } 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/indexCodebase.ts b/core/indexing/indexCodebase.ts index 03597e99e..a812e802b 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; 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/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/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/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 8ac6e8207..3114e3bd9 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,26 @@ 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.race([ + Promise.all(workspaceDirs.map((dir) => this.getBranch(dir))), + new Promise((resolve) => { + setTimeout(() => { + resolve(["NONE"]); + }, 500); + }), + ])) as string[]; + + 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/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/yarn.lock b/extensions/vscode/yarn.lock index c82bcdb44..21f1b3e6c 100644 --- a/extensions/vscode/yarn.lock +++ b/extensions/vscode/yarn.lock @@ -696,6 +696,11 @@ resolved "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz" integrity sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg== +"@lancedb/vectordb-darwin-arm64@*": + version "0.4.12" + resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.12.tgz" + integrity sha512-38/rkJRlWXkPWXuj9onzvbrhnIWcIUQjgEp5G9v5ixPosBowm7A4j8e2Q8CJMsVSNcVX2JLqwWVldiWegZFuYw== + "@lancedb/vectordb-darwin-arm64@0.4.10": version "0.4.10" resolved "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.10.tgz" From 283c7ebcaddc40dd50b924cd3341a326db22ea18 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 9 Mar 2024 16:24:52 -0800 Subject: [PATCH 04/24] =?UTF-8?q?=F0=9F=9A=B8=20add=20titles=20to=20code?= =?UTF-8?q?=20context=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/CodeSnippetsIndex.ts | 52 ++++++++++++-------- core/util/treeSitter.ts | 6 --- extensions/vscode/src/ideProtocol.ts | 11 ++--- gui/src/components/mainInput/MentionList.tsx | 6 ++- 4 files changed, 39 insertions(+), 36 deletions(-) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 26edbc432..737c3c058 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -33,6 +33,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { path TEXT NOT NULL, cacheKey TEXT NOT NULL, content TEXT NOT NULL, + title TEXT NOT NULL, startLine INTEGER NOT NULL, endLine INTEGER NOT NULL )`); @@ -42,7 +43,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { tag TEXT NOT NULL, snippetId INTEGER NOT NULL, FOREIGN KEY (snippetId) REFERENCES code_snippets (id) - )`); + )`); } private getQuerySource(filepath: string) { @@ -62,8 +63,11 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { async getSnippetsInFile( filepath: string, contents: string, - ): Promise { + ): Promise<(ChunkWithoutID & { title: string })[]> { const lang = await getLanguageForFile(filepath); + if (!lang) { + return []; + } const parser = await getParserForFile(filepath); const ast = parser.parse(contents); const query = lang?.query(this.getQuerySource(filepath)); @@ -71,12 +75,14 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { return ( matches?.flatMap((match) => { - const nodes = match.captures.map((capture) => capture.node); - const results = nodes.map((node) => ({ + 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; }) ?? [] ); @@ -101,11 +107,12 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { // Add snippets to sqlite for (const snippet of snippets) { const { lastID } = await db.run( - `INSERT INTO code_snippets (path, cacheKey, content, startLine, endLine) VALUES (?, ?, ?, ?, ?)`, + `INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)`, [ compute.path, compute.cacheKey, snippet.content, + snippet.title, snippet.startLine, snippet.endLine, ], @@ -174,7 +181,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const row = await db.get(`SELECT * FROM code_snippets WHERE id = ?`, [id]); return { - name: getBasename(row.path), + name: row.title, description: getBasename(row.path, 2), content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``, }; @@ -182,19 +189,24 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { static async getAll(tag: IndexTag): Promise { const db = await SqliteDb.get(); - const rows = await db.all( - `SELECT * - FROM code_snippets cs - JOIN code_snippets_tags cst ON cs.id = cst.snippetId - WHERE cst.tag = ?; - `, - [tagToString(tag)], - ); + try { + const rows = await db.all( + `SELECT * + FROM code_snippets cs + JOIN code_snippets_tags cst ON cs.id = cst.snippetId + WHERE cst.tag = ?; + `, + [tagToString(tag)], + ); - return rows.map((row) => ({ - title: getBasename(row.path), - description: getBasename(row.path, 2), - id: row.id.toString(), - })); + 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/util/treeSitter.ts b/core/util/treeSitter.ts index f0e9814b3..4116d5440 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -90,12 +90,6 @@ export async function getLanguageForFile( const extension = path.extname(filepath).slice(1); if (!supportedLanguages[extension]) { - console.warn( - "Unable to load language for file", - extension, - "from path: ", - filepath, - ); return undefined; } diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 3114e3bd9..ea8edcc1d 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -22,14 +22,9 @@ class VsCodeIde implements IDE { async getTags(artifactId: string): Promise { const workspaceDirs = await this.getWorkspaceDirs(); - const branches = (await Promise.race([ - Promise.all(workspaceDirs.map((dir) => this.getBranch(dir))), - new Promise((resolve) => { - setTimeout(() => { - resolve(["NONE"]); - }, 500); - }), - ])) as string[]; + const branches = await Promise.all( + workspaceDirs.map((dir) => this.getBranch(dir)), + ); const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({ directory, diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 4695b874d..524019e30 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 @@ -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", From f6633fd157aa7ef284fdfb542408a5fef237f5f0 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 9 Mar 2024 20:15:44 -0800 Subject: [PATCH 05/24] =?UTF-8?q?=F0=9F=8E=A8=20more=20minimal=20tree-sitt?= =?UTF-8?q?er=20queries=20for=20code=20ctx=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/CodeSnippetsIndex.ts | 3 ++- core/package-lock.json | 11 ++++++++ core/util/treeSitter.ts | 1 + core/yarn.lock | 5 ++++ .../tree-sitter-c-tags.scm | 9 +++++++ .../tree-sitter-c_sharp-tags.scm | 23 ++++++++++++++++ .../tree-sitter-cpp-tags.scm | 7 +++++ .../tree-sitter-elisp-tags.scm | 6 +++++ .../tree-sitter-elixir-tags.scm | 26 +++++++++++++++++++ .../tree-sitter-go-tags.scm | 20 ++++++++++++++ .../tree-sitter-java-tags.scm | 8 ++++++ .../tree-sitter-javascript-tags.scm | 8 ++++++ .../tree-sitter-ocaml-tags.scm | 12 +++++++++ .../tree-sitter-php-tags.scm | 8 ++++++ .../tree-sitter-python-tags.scm | 5 ++++ .../tree-sitter-ql-tags.scm | 26 +++++++++++++++++++ .../tree-sitter-ruby-tags.scm | 0 .../tree-sitter-rust-tags.scm | 8 ++++++ .../tree-sitter-typescript-tags.scm | 11 ++++++++ 19 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-c_sharp-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-cpp-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elisp-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-elixir-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-go-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-java-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-javascript-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ocaml-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-php-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-python-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ql-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-ruby-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-rust-tags.scm create mode 100644 extensions/vscode/tree-sitter/code-snippet-queries/tree-sitter-typescript-tags.scm diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 737c3c058..6afb8a8d7 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -51,7 +51,8 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const sourcePath = path.join( __dirname, "..", - "tag-qry", + "tree-sitter", + "code-snippet-queries", `tree-sitter-${fullLangName}-tags.scm`, ); if (!fs.existsSync(sourcePath)) { diff --git a/core/package-lock.json b/core/package-lock.json index a55a26357..a753efdb0 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" } }, @@ -9825,6 +9826,16 @@ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", "license": "MIT" }, + "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.6", "resolved": "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.6.tgz", diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 4116d5440..87da23d6b 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -87,6 +87,7 @@ export async function getLanguageForFile( filepath: string, ): Promise { try { + await Parser.init(); const extension = path.extname(filepath).slice(1); if (!supportedLanguages[extension]) { diff --git a/core/yarn.lock b/core/yarn.lock index 40d96bb4c..7da17351f 100644 --- a/core/yarn.lock +++ b/core/yarn.lock @@ -5492,6 +5492,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.6" resolved "https://registry.npmjs.org/tree-sitter-wasms/-/tree-sitter-wasms-0.1.6.tgz" 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 From 6391d243b0a66f0eaeeb4d34241a2dc8706ae45b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Sat, 9 Mar 2024 20:30:10 -0800 Subject: [PATCH 06/24] =?UTF-8?q?=F0=9F=A5=85=20catch=20parser=20failure?= =?UTF-8?q?=20when=20indexing=20codebase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/CodeSnippetsIndex.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 6afb8a8d7..7694e6cc4 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -70,6 +70,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { 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); From a3501ba555a1c31593e1fe8c90382b2c87ef6533 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 11 Mar 2024 16:58:07 -0700 Subject: [PATCH 07/24] =?UTF-8?q?=F0=9F=92=9A=20on:=20[]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/main.yaml | 5 +---- .github/workflows/preview.yaml | 5 +---- extensions/vscode/package.json | 2 +- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index 277b5f50f..a08a9a753 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -1,9 +1,6 @@ name: Publish Extension -on: - push: - branches: - - main +on: [] jobs: build: diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index 14d5da38e..57d7b7422 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -1,9 +1,6 @@ name: Publish Preview Extension -on: - push: - branches: - - preview +on: [] jobs: build: 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", From 22a3068248780d0e044ea7b40598e2aeca7d1ad1 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 11 Mar 2024 17:01:25 -0700 Subject: [PATCH 08/24] =?UTF-8?q?=F0=9F=94=A5=20remove=20GitHub=20Actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/main.yaml | 208 --------------------------------- .github/workflows/preview.yaml | 195 ------------------------------- 2 files changed, 403 deletions(-) delete mode 100644 .github/workflows/main.yaml delete mode 100644 .github/workflows/preview.yaml diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml deleted file mode 100644 index a08a9a753..000000000 --- a/.github/workflows/main.yaml +++ /dev/null @@ -1,208 +0,0 @@ -name: Publish Extension - -on: [] - -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 57d7b7422..000000000 --- a/.github/workflows/preview.yaml +++ /dev/null @@ -1,195 +0,0 @@ -name: Publish Preview Extension - -on: [] - -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 }} From 09372e1e3438fa694f3cf9896b466366749b0d66 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 11 Mar 2024 17:55:36 -0700 Subject: [PATCH 09/24] =?UTF-8?q?=F0=9F=92=9A=20catch=20error=20removing?= =?UTF-8?q?=20unused=20binaries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/scripts/prepackage.js | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) 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"); From 3a75dbfe60575d2f4216e915997d7ed35c6a235e Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 11 Mar 2024 20:16:01 -0700 Subject: [PATCH 10/24] =?UTF-8?q?=F0=9F=A4=A1=20add=20remote=20config=20st?= =?UTF-8?q?ubs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 10 +- extensions/vscode/src/activation/activate.ts | 12 -- .../vscode/src/extension/vscodeExtension.ts | 14 +- extensions/vscode/src/stubs/activation.ts | 1 + extensions/vscode/src/stubs/auth.ts | 3 + extensions/vscode/src/util/remoteConfig.ts | 131 ------------------ 6 files changed, 15 insertions(+), 156 deletions(-) create mode 100644 extensions/vscode/src/stubs/activation.ts create mode 100644 extensions/vscode/src/stubs/auth.ts delete mode 100644 extensions/vscode/src/util/remoteConfig.ts diff --git a/core/config/load.ts b/core/config/load.ts index f911b9932..d0df1aa06 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]}"`, + ); + } }); } diff --git a/extensions/vscode/src/activation/activate.ts b/extensions/vscode/src/activation/activate.ts index 558096b14..3de6b77be 100644 --- a/extensions/vscode/src/activation/activate.ts +++ b/extensions/vscode/src/activation/activate.ts @@ -7,7 +7,6 @@ import { VsCodeExtension } from "../extension/vscodeExtension"; import registerQuickFixProvider from "../lang-server/codeActions"; import { getExtensionVersion } from "../util/util"; import { getExtensionUri } from "../util/vscode"; -import { ManualTokenAuthProvider } from "./auth"; import { setupInlineTips } from "./inlineTips"; export async function showTutorial() { @@ -68,17 +67,6 @@ function showRefactorMigrationMessage( } export async function activateExtension(context: vscode.ExtensionContext) { - const authProvider = vscode.authentication.registerAuthenticationProvider( - "manualToken", - "Continue Manual Token", - new ManualTokenAuthProvider(() => { - return new vscode.Disposable(() => {}); - }, context), - ); - const session = await vscode.authentication.getSession("manualToken", [], { - createIfNone: true, - }); - // Add necessary files getTsConfigPath(); 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/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}`); - } - } -} From 36f62daa660fe3b142bd4e366436288af74bd11b Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Mon, 11 Mar 2024 20:42:25 -0700 Subject: [PATCH 11/24] =?UTF-8?q?=F0=9F=90=9B=20use=20same=20starcoder=20t?= =?UTF-8?q?emplate=20for=20starcoder2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/autocomplete/templates.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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") || From 0c6f8d9605855b86d6a634ffa3b39a71dec4eab5 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Mar 2024 00:40:12 -0700 Subject: [PATCH 12/24] =?UTF-8?q?=F0=9F=8E=A8=20use=20new=20URL=20everywhe?= =?UTF-8?q?re=20instead=20of=20strings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../embeddings/OllamaEmbeddingsProvider.ts | 4 ++-- .../embeddings/OpenAIEmbeddingsProvider.ts | 9 ++------ core/llm/index.ts | 4 ++-- core/llm/llms/Anthropic.ts | 4 ++-- core/llm/llms/DeepInfra.ts | 2 +- core/llm/llms/GooglePalm.ts | 12 +++++++--- core/llm/llms/HuggingFaceTGI.ts | 19 ++++++++------- core/llm/llms/LMStudio.ts | 2 +- core/llm/llms/LlamaCpp.ts | 4 ++-- core/llm/llms/Mistral.ts | 2 +- core/llm/llms/Ollama.ts | 2 +- core/llm/llms/OpenAI.ts | 23 +++++++++---------- core/llm/llms/TextGenWebUI.ts | 2 +- core/llm/llms/Together.ts | 2 +- docs/docs/walkthroughs/codellama.md | 2 +- gui/src/util/modelData.ts | 4 ++-- 16 files changed, 50 insertions(+), 47 deletions(-) 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/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..4e02a16cf 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", }; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index e3c50c5c5..ea9dad075 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) { @@ -95,22 +95,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); } } @@ -134,7 +133,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", @@ -184,7 +183,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", @@ -202,7 +201,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/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/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, ], From 7a01d29b1bde7e44272d5d0edb373ef2a28ce56a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Mar 2024 01:17:06 -0700 Subject: [PATCH 13/24] =?UTF-8?q?=E2=9C=A8=20polish=20code=20context=20pro?= =?UTF-8?q?vider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/config/load.ts | 38 ++++---------------- core/index.d.ts | 4 ++- core/indexing/CodeSnippetsIndex.ts | 4 +-- docs/docs/customization/context-providers.md | 10 +++++- extensions/vscode/config_schema.json | 6 ++-- 5 files changed, 24 insertions(+), 38 deletions(-) diff --git a/core/config/load.ts b/core/config/load.ts index d0df1aa06..e30980b4b 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -88,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: {}, }, ]; @@ -126,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/index.d.ts b/core/index.d.ts index 475fa60f5..18f88a2cd 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -426,7 +426,9 @@ type ContextProviderName = | "folder" | "jira" | "postgres" - | "database"; + | "database" + | "code" + | "docs"; type TemplateType = | "llama2" diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts index 7694e6cc4..c1ab1c68d 100644 --- a/core/indexing/CodeSnippetsIndex.ts +++ b/core/indexing/CodeSnippetsIndex.ts @@ -155,7 +155,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { for (const snippet of snippetsWithPath) { await db.run( - `INSERT INTO code_snippet_tags (snippetId, tag) VALUES (?, ?)`, + `INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`, [snippet.id, tagString], ); } @@ -195,7 +195,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex { const db = await SqliteDb.get(); try { const rows = await db.all( - `SELECT * + `SELECT cs.id, cs.path, cs.title FROM code_snippets cs JOIN code_snippets_tags cst ON cs.id = cst.snippetId WHERE cst.tag = ?; 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/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index f41430f78..13e77c8c7 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1045,7 +1045,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1065,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" }, From c717bed0da1d35840269dc1e6f1e3c8b0e6083c2 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Mar 2024 13:27:27 -0700 Subject: [PATCH 14/24] =?UTF-8?q?=F0=9F=92=84=20file=20icons=20for=20code?= =?UTF-8?q?=20context=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/static/schemas/config.json | 10 ++++++++-- .../intellij/src/main/resources/config_schema.json | 10 ++++++++-- extensions/vscode/config_schema.json | 4 ++++ extensions/vscode/continue_rc_schema.json | 10 ++++++++-- gui/src/components/mainInput/MentionList.tsx | 10 +++++++--- 5 files changed, 35 insertions(+), 9 deletions(-) diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index f41430f78..62102a4e8 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -1045,7 +1045,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1065,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 +1261,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..62102a4e8 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -1045,7 +1045,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1064,7 +1065,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 +1261,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 13e77c8c7..62102a4e8 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -1261,6 +1261,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..556310fc0 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -1161,7 +1161,8 @@ "tree", "highlights", "outline", - "postgres" + "postgres", + "code" ], "markdownEnumDescriptions": [ "Reference the contents of the current changes as given by `git diff`", @@ -1180,7 +1181,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 +1412,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/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index 524019e30..a8528f224 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -283,6 +283,10 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { }, })); + const showFileIconForItem = (item: ComboBoxItem) => { + return ["file", "code"].includes(item.type); + }; + return ( {querySubmenuItem ? ( @@ -324,14 +328,14 @@ const MentionList = forwardRef((props: MentionListProps, ref) => { >
- {item.type === "file" && ( + {showFileIconForItem(item) && ( )} - {item.type !== "file" && ( + {!showFileIconForItem(item) && ( <> From 572916ebbfa2ca27782737fc16f8bb2402c1d344 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Tue, 12 Mar 2024 23:24:56 -0700 Subject: [PATCH 15/24] =?UTF-8?q?=F0=9F=90=9B=20fix=20error=20listing=20Ol?= =?UTF-8?q?lama=20tags=20in=20JetBrains?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/llms/Ollama.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts index 4e02a16cf..1c0c77561 100644 --- a/core/llm/llms/Ollama.ts +++ b/core/llm/llms/Ollama.ts @@ -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); } From 88a254a8b07bce1a237f01300ff1600413520532 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 13 Mar 2024 00:57:27 -0700 Subject: [PATCH 16/24] =?UTF-8?q?=F0=9F=90=9B=20fix=20token=20counting=20b?= =?UTF-8?q?ug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/countTokens.ts | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) 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 From c72ab598fed74b61a30857591645a75b498835dc Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 13 Mar 2024 09:08:01 -0700 Subject: [PATCH 17/24] =?UTF-8?q?=F0=9F=9A=B8=20allow=20arbitrary=20model?= =?UTF-8?q?=20with=20openai=20provider?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extensions/vscode/config_schema.json | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 62102a4e8..7734d7cef 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -352,15 +352,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" + } ] } } From debe14423472588294d9ad7eb8163ff755e5cf5a Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 13 Mar 2024 13:07:57 -0700 Subject: [PATCH 18/24] =?UTF-8?q?=F0=9F=9A=B8=20show=20indexing=20progress?= =?UTF-8?q?=20immediately?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/indexing/indexCodebase.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/indexing/indexCodebase.ts b/core/indexing/indexCodebase.ts index a812e802b..645affa6a 100644 --- a/core/indexing/indexCodebase.ts +++ b/core/indexing/indexCodebase.ts @@ -59,7 +59,7 @@ export class CodebaseIndexer { let completedDirs = 0; yield { - progress: 0, + progress: 0.01, desc: "Starting indexing...", }; From bb838f15468314ce3504e702cfb6894bc0edc208 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Wed, 13 Mar 2024 13:08:07 -0700 Subject: [PATCH 19/24] =?UTF-8?q?=F0=9F=8E=A8=20update=20config=20json=20s?= =?UTF-8?q?chemas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/static/schemas/config.json | 25 ++++++++++++------- .../src/main/resources/config_schema.json | 25 ++++++++++++------- extensions/vscode/continue_rc_schema.json | 25 ++++++++++++------- 3 files changed, 48 insertions(+), 27 deletions(-) diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json index 62102a4e8..7734d7cef 100644 --- a/docs/static/schemas/config.json +++ b/docs/static/schemas/config.json @@ -352,15 +352,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" + } ] } } diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 62102a4e8..7734d7cef 100644 --- a/extensions/intellij/src/main/resources/config_schema.json +++ b/extensions/intellij/src/main/resources/config_schema.json @@ -352,15 +352,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" + } ] } } diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 556310fc0..996045153 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -380,15 +380,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" + } ] } } From cd24ecf686071e8a2257d875eb0e76b9bcb8a1ba Mon Sep 17 00:00:00 2001 From: Jason Jacobs Date: Thu, 14 Mar 2024 13:20:47 -0700 Subject: [PATCH 20/24] Changing the subMenuTitle in the context provider has led to an inability to add new documentation sources. (#959) --- gui/src/components/mainInput/MentionList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/mainInput/MentionList.tsx b/gui/src/components/mainInput/MentionList.tsx index a8528f224..2b4de321a 100644 --- a/gui/src/components/mainInput/MentionList.tsx +++ b/gui/src/components/mainInput/MentionList.tsx @@ -175,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", From caa7aa9459b997e564a087193094083919115397 Mon Sep 17 00:00:00 2001 From: Riccardo Schirone <562321+ret2libc@users.noreply.github.com> Date: Thu, 14 Mar 2024 21:23:16 +0100 Subject: [PATCH 21/24] Add autocomplete support for Solidity (#964) --- core/autocomplete/languages.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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, }; From 9c290e9db8a105729ea7d0eaa2dcccbd736094ae Mon Sep 17 00:00:00 2001 From: Jason Jacobs Date: Thu, 14 Mar 2024 13:24:12 -0700 Subject: [PATCH 22/24] Refactor DB (#960) * Refactor table creation and SQLite connection initialization. Previously, attempts to create the 'docs' table were made on every interaction with it. Now, table creation is attempted only upon the first interaction. Additionally, the SQLite connection is now initialized just once, enhancing performance. * no longer need createDocsTable * library no longer used --- core/indexing/docs/db.ts | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) 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; } From ebff85795ff32a277b7a568b34a06b63342f7098 Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Thu, 14 Mar 2024 18:29:02 -0700 Subject: [PATCH 23/24] =?UTF-8?q?=F0=9F=92=A1=20add=20note=20about=20Jan?= =?UTF-8?q?=20stop=20words?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/llm/llms/OpenAI.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index ea9dad075..0894b1ab8 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -71,6 +71,7 @@ class OpenAI extends BaseLLM { top_p: options.topP, frequency_penalty: options.frequencyPenalty, presence_penalty: options.presencePenalty, + // Jan doesn't truncate and will throw an error stop: this.apiBase?.includes(":1337") ? options.stop?.slice(0, 4) : options.stop, From 5164676197ae73b211005c1d20c4a4e97a5d6cde Mon Sep 17 00:00:00 2001 From: Nate Sesti Date: Fri, 15 Mar 2024 09:57:50 -0700 Subject: [PATCH 24/24] =?UTF-8?q?=E2=9C=A8=20gemma=20chat=20template?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/index.d.ts | 3 ++- core/llm/autodetect.ts | 9 +++++++++ core/llm/templates/chat.ts | 19 +++++++++++++++++++ core/llm/templates/edit.ts | 14 ++++++++++++++ docs/static/schemas/config.json | 5 ++++- .../src/main/resources/config_schema.json | 5 ++++- extensions/vscode/config_schema.json | 5 ++++- extensions/vscode/continue_rc_schema.json | 5 ++++- 8 files changed, 60 insertions(+), 5 deletions(-) diff --git a/core/index.d.ts b/core/index.d.ts index 18f88a2cd..abb337154 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -444,7 +444,8 @@ type TemplateType = | "xwin-coder" | "neural-chat" | "codellama-70b" - | "llava"; + | "llava" + | "gemma"; type ModelProvider = | "openai" 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/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/docs/static/schemas/config.json b/docs/static/schemas/config.json index 7734d7cef..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" }, diff --git a/extensions/intellij/src/main/resources/config_schema.json b/extensions/intellij/src/main/resources/config_schema.json index 7734d7cef..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" }, diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index 7734d7cef..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" }, diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 996045153..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" },