Merge branch 'dev' into fix-minisearch-exception
This commit is contained in:
commit
add02fb005
258 changed files with 26415 additions and 6790 deletions
8
.changes/extensions/intellij/0.0.53.md
Normal file
8
.changes/extensions/intellij/0.0.53.md
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
## 0.0.53 - 2024-07-10
|
||||
### Added
|
||||
* Support for .prompt files
|
||||
* New onboarding experience
|
||||
### Fixed
|
||||
* Indexing fixes from VS Code versions merged into IntelliJ
|
||||
* Improved codebase indexing reliability and testing
|
||||
* Fixes for autocomplete text positioning and timing
|
||||
6
.changes/extensions/intellij/0.0.54.md
Normal file
6
.changes/extensions/intellij/0.0.54.md
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
## 0.0.54 - 2024-07-13
|
||||
### Added
|
||||
* Partial autocomplete acceptance
|
||||
* Autocomplete status bar spinner
|
||||
### Fixed
|
||||
* Fixed duplicate completion bug and others
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
## 0.8.40 - 2024-07-02
|
||||
### Added
|
||||
* Support for Gemini 1.5 Pro
|
||||
* Link to code in the sidebar when using codebase retrieval
|
||||
* Smoother onboarding experience
|
||||
* .prompt files, a way of saving and sharing slash commands
|
||||
* Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
|
||||
* Support for comments in config.json
|
||||
* Specify multiple autocomplete models and switch between them
|
||||
* Improved bracket matching strategy reduces noisy completions
|
||||
### Fixed
|
||||
* Numerous reliability upgrades to codebase indexing
|
||||
16
.changes/extensions/vscode/0.8.42.md
Normal file
16
.changes/extensions/vscode/0.8.42.md
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
## 0.8.42 - 2024-07-02
|
||||
|
||||
### Added
|
||||
|
||||
- Support for Gemini 1.5 Pro
|
||||
- Link to code in the sidebar when using codebase retrieval
|
||||
- Smoother onboarding experience
|
||||
- .prompt files, a way of saving and sharing slash commands
|
||||
- Support for Claude 3.5 Sonnet, Deepseek Coder v2, and other new models
|
||||
- Support for comments in config.json
|
||||
- Specify multiple autocomplete models and switch between them
|
||||
- Improved bracket matching strategy reduces noisy completions
|
||||
|
||||
### Fixed
|
||||
|
||||
- Numerous reliability upgrades to codebase indexing
|
||||
4
.changes/extensions/vscode/0.8.43.md
Normal file
4
.changes/extensions/vscode/0.8.43.md
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
## 0.8.43 - 2024-07-08
|
||||
### Added
|
||||
* Improved indexing reliability and testing
|
||||
* Quick Actions: use CodeLens to quickly take common actions like adding docstrings
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
## v0.1.104 - 2023-12-25
|
||||
|
||||
### Added
|
||||
|
||||
- Continuous and faster syncing of codebase index
|
||||
|
||||
### Removed
|
||||
|
||||
- No longer using Continue Python server
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
## v0.1.99 - 2023-11-19
|
||||
|
||||
### Changed
|
||||
|
||||
- migrated to .json config file format
|
||||
4
.changes/unreleased/Added-20240726-153514.yaml
Normal file
4
.changes/unreleased/Added-20240726-153514.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: Support for Llama 3.1 and gpt-4o-mini
|
||||
time: 2024-07-26T15:35:14.411895-07:00
|
||||
4
.changes/unreleased/Changed-20240726-153458.yaml
Normal file
4
.changes/unreleased/Changed-20240726-153458.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Significant improvements to indexing performance
|
||||
time: 2024-07-26T15:34:58.457908-07:00
|
||||
5
.changes/unreleased/Changed-20240726-153542.yaml
Normal file
5
.changes/unreleased/Changed-20240726-153542.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
project: extensions/vscode
|
||||
kind: Changed
|
||||
body: Improved @codebase quality by more accurately searching over file names and
|
||||
paths
|
||||
time: 2024-07-26T15:35:42.390496-07:00
|
||||
14
.github/workflows/main.yaml
vendored
14
.github/workflows/main.yaml
vendored
|
|
@ -125,13 +125,13 @@ jobs:
|
|||
|
||||
# 4. 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'
|
||||
# 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: |
|
||||
|
|
|
|||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -166,4 +166,6 @@ Icon?
|
|||
.continue
|
||||
|
||||
# Sandbox env default file
|
||||
extensions/vscode/manual-testing-sandbox/example.ts
|
||||
extensions/vscode/manual-testing-sandbox/example.ts
|
||||
|
||||
.prompts/
|
||||
|
|
@ -1,2 +1,3 @@
|
|||
extensions/vscode/continue_rc_schema.json
|
||||
**/.continueignore
|
||||
**/.continueignore
|
||||
CHANGELOG.md
|
||||
|
|
@ -1,20 +0,0 @@
|
|||
temperature: 0.5
|
||||
maxTokens: 4096
|
||||
name: jest
|
||||
description: Write Jest unit tests
|
||||
---
|
||||
<system>
|
||||
You are an expert programmer
|
||||
</system>
|
||||
|
||||
{{{ input }}}
|
||||
|
||||
Write unit tests for the above selected code, following each of these instructions:
|
||||
- Use `jest`
|
||||
- Properly set up and tear down
|
||||
- Include important edge cases
|
||||
- The tests should be complete and sophisticated
|
||||
- Give the tests just as chat output, don't edit any file
|
||||
- Don't explain how to set up `jest`
|
||||
- Write a single code block, making sure to label with the language being used (e.g. "```typscript")
|
||||
- Do not under any circumstances mock any functions or modules
|
||||
33
.vscode/launch.json
vendored
33
.vscode/launch.json
vendored
|
|
@ -22,7 +22,6 @@
|
|||
"CONTINUE_GLOBAL_DIR": "${workspaceFolder}/binary/.continue"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "Debug Jest Tests",
|
||||
"type": "node",
|
||||
|
|
@ -35,6 +34,7 @@
|
|||
"--config",
|
||||
"${workspaceRoot}/core/jest.config.js"
|
||||
],
|
||||
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
},
|
||||
|
|
@ -68,7 +68,10 @@
|
|||
"${workspaceFolder}/extensions/vscode/out/extension.js",
|
||||
"/Users/natesesti/.continue/config.ts"
|
||||
],
|
||||
"preLaunchTask": "vscode-extension:build"
|
||||
"preLaunchTask": "vscode-extension:build",
|
||||
"env": {
|
||||
// "CONTROL_PLANE_ENV": "local"
|
||||
}
|
||||
},
|
||||
// Has to be run after starting the server (separately or using the compound configuration)
|
||||
{
|
||||
|
|
@ -110,7 +113,31 @@
|
|||
],
|
||||
"cwd": "${workspaceRoot}/core",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen"
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"env": {
|
||||
"NODE_OPTIONS": "--experimental-vm-modules",
|
||||
"CI": "true",
|
||||
"DEBUG": "jest"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "[openai-adapters] Jest Test Debugger, Current Open File",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"runtimeArgs": [
|
||||
"--inspect-brk",
|
||||
"${workspaceRoot}/packages/openai-adapters/node_modules/jest/bin/jest.js",
|
||||
"--runInBand",
|
||||
"--config",
|
||||
"${workspaceRoot}/packages/openai-adapters/jest.config.mjs",
|
||||
"${relativeFile}"
|
||||
],
|
||||
"cwd": "${workspaceRoot}/packages/openai-adapters",
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
"env": {
|
||||
"NODE_OPTIONS": "--experimental-vm-modules"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
15
.vscode/settings.json
vendored
15
.vscode/settings.json
vendored
|
|
@ -7,10 +7,15 @@
|
|||
"python.testing.unittestEnabled": false,
|
||||
"python.testing.pytestEnabled": true,
|
||||
"terminal.integrated.defaultProfile.linux": "bash",
|
||||
"terminal.integrated.profiles.linux": {
|
||||
"bash": {
|
||||
"path": "bash",
|
||||
"args": ["-l"]
|
||||
}
|
||||
"terminal.integrated.profiles.linux": {
|
||||
"bash": {
|
||||
"path": "bash",
|
||||
"args": ["-l"]
|
||||
}
|
||||
},
|
||||
"search.exclude": {
|
||||
"**/binary": true,
|
||||
"**/core/vendor/**": true,
|
||||
"**/gui/dist": true
|
||||
}
|
||||
}
|
||||
|
|
|
|||
73
CODE_OF_CONDUCT.md
Normal file
73
CODE_OF_CONDUCT.md
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, gender identity and expression, level of experience,
|
||||
education, socio-economic status, nationality, personal appearance, race,
|
||||
religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at hi@continue.dev. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
|
@ -158,11 +158,18 @@ async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
|
|||
);
|
||||
});
|
||||
|
||||
fs.copyFileSync(
|
||||
path.join(__dirname, "../core/vendor/tree-sitter.wasm"),
|
||||
path.join(__dirname, "out/tree-sitter.wasm"),
|
||||
);
|
||||
console.log("[info] Copied tree-sitter wasms");
|
||||
const filesToCopy = [
|
||||
"../core/vendor/tree-sitter.wasm",
|
||||
"../core/llm/llamaTokenizerWorkerPool.mjs",
|
||||
"../core/llm/llamaTokenizer.mjs",
|
||||
];
|
||||
for (const f of filesToCopy) {
|
||||
fs.copyFileSync(
|
||||
path.join(__dirname, f),
|
||||
path.join(__dirname, "out", path.basename(f)),
|
||||
);
|
||||
console.log(`[info] Copied ${path.basename(f)}`);
|
||||
}
|
||||
|
||||
console.log("[info] Cleaning up artifacts from previous builds...");
|
||||
|
||||
|
|
|
|||
9
binary/package-lock.json
generated
9
binary/package-lock.json
generated
|
|
@ -44,9 +44,9 @@
|
|||
"version": "1.0.13",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.574.0",
|
||||
"@aws-sdk/credential-providers": "^3.596.0",
|
||||
"@continuedev/config-types": "^1.0.6",
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.620.1",
|
||||
"@aws-sdk/credential-providers": "^3.620.1",
|
||||
"@continuedev/config-types": "^1.0.10",
|
||||
"@continuedev/llm-info": "^1.0.1",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.0.2",
|
||||
|
|
@ -82,6 +82,7 @@
|
|||
"openai": "^4.20.1",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.3",
|
||||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"socket.io-client": "^4.7.3",
|
||||
|
|
@ -93,6 +94,7 @@
|
|||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
|
|
@ -104,6 +106,7 @@
|
|||
"@types/jest": "^29.5.12",
|
||||
"@types/jquery": "^3.5.29",
|
||||
"@types/mustache": "^4.2.5",
|
||||
"@types/request": "^2.48.12",
|
||||
"@types/uuid": "^9.0.7",
|
||||
"esbuild": "0.17.19",
|
||||
"eslint": "^8",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
{
|
||||
"name": "binary",
|
||||
"version": "1.0.0",
|
||||
"author": "Continue Dev, Inc",
|
||||
"description": "",
|
||||
"main": "out/index.js",
|
||||
"bin": "out/index.js",
|
||||
|
|
@ -26,7 +27,6 @@
|
|||
"build:dev": "tsc",
|
||||
"esbuild": "node build.js --esbuild-only"
|
||||
},
|
||||
"author": "",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "1.6.4",
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
"module": "commonjs",
|
||||
"target": "ES2020",
|
||||
"outDir": "out",
|
||||
"lib": ["ES2020", "dom", "es6", "es5", "dom.iterable", "scripthost"],
|
||||
"lib": ["ES2021", "dom", "es6", "es5", "dom.iterable", "scripthost"],
|
||||
"sourceMap": true,
|
||||
"rootDirs": ["src", "../core"],
|
||||
"allowJs": true,
|
||||
|
|
|
|||
26
biome.json
26
biome.json
|
|
@ -1,26 +0,0 @@
|
|||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"suspicious": {
|
||||
"noExplicitAny": "off",
|
||||
"noConfusingVoidType": "off"
|
||||
},
|
||||
"style": {
|
||||
"noUselessElse": "off",
|
||||
"noNonNullAssertion": "off"
|
||||
},
|
||||
"complexity": {
|
||||
"noForEach": "off"
|
||||
}
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space"
|
||||
}
|
||||
}
|
||||
|
|
@ -8,7 +8,6 @@
|
|||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"quotes": ["warn", "double", {}],
|
||||
"import/extensions": ["error", "ignorePackages"],
|
||||
"@typescript-eslint/naming-convention": "warn",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
"curly": "warn",
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import { IDE } from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { PrecalculatedLruCache } from "../util/LruCache";
|
||||
import { IDE } from "../index.js";
|
||||
import { RangeInFileWithContents } from "../commands/util.js";
|
||||
import { PrecalculatedLruCache } from "../util/LruCache.js";
|
||||
import {
|
||||
TSQueryType,
|
||||
getParserForFile,
|
||||
getQueryForFile,
|
||||
} from "../util/treeSitter";
|
||||
} from "../util/treeSitter.js";
|
||||
|
||||
interface FileInfo {
|
||||
imports: { [key: string]: RangeInFileWithContents[] };
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { IDE, Location } from "..";
|
||||
import { LANGUAGES } from "./languages";
|
||||
import { getSymbolsForSnippet } from "./ranking";
|
||||
import { IDE, Location } from "../index.js";
|
||||
import { LANGUAGES } from "./languages.js";
|
||||
import { getSymbolsForSnippet } from "./ranking.js";
|
||||
|
||||
interface FileInfo {
|
||||
filepath: string;
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ import AutocompleteLruCache from "./cache.js";
|
|||
import {
|
||||
noFirstCharNewline,
|
||||
onlyWhitespaceAfterEndOfLine,
|
||||
stopAtStopTokens,
|
||||
} from "./charStream.js";
|
||||
import {
|
||||
constructAutocompletePrompt,
|
||||
|
|
@ -51,6 +52,7 @@ import { getTemplateForModel } from "./templates.js";
|
|||
import { GeneratorReuseManager } from "./util.js";
|
||||
// @prettier-ignore
|
||||
import Handlebars from "handlebars";
|
||||
import { getConfigJsonPath } from "../util/paths.js";
|
||||
|
||||
export interface AutocompleteInput {
|
||||
completionId: string;
|
||||
|
|
@ -248,6 +250,11 @@ export class CompletionProvider {
|
|||
...config.tabAutocompleteOptions,
|
||||
};
|
||||
|
||||
// Check whether we're in the continue config.json file
|
||||
if (input.filepath === getConfigJsonPath()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
if (options.disableInFiles) {
|
||||
// Relative path needed for `ignore`
|
||||
|
|
@ -265,7 +272,8 @@ export class CompletionProvider {
|
|||
filepath = getBasename(filepath);
|
||||
}
|
||||
|
||||
const pattern = ignore().add(options.disableInFiles);
|
||||
// @ts-ignore
|
||||
const pattern = ignore.default().add(options.disableInFiles);
|
||||
if (pattern.ignores(filepath)) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -455,7 +463,7 @@ export class CompletionProvider {
|
|||
) {
|
||||
shownGptClaudeWarning = true;
|
||||
throw new Error(
|
||||
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/walkthroughs/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
|
||||
`Warning: ${llm.model} is not trained for tab-autocomplete, and will result in low-quality suggestions. See the docs to learn more about why: https://docs.continue.dev/features/tab-autocomplete#i-want-better-completions-should-i-use-gpt-4`,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -585,7 +593,14 @@ export class CompletionProvider {
|
|||
});
|
||||
} else {
|
||||
// Let the template function format snippets
|
||||
prompt = template(prefix, suffix, filepath, reponame, snippets);
|
||||
prompt = template(
|
||||
prefix,
|
||||
suffix,
|
||||
filepath,
|
||||
reponame,
|
||||
lang.name,
|
||||
snippets,
|
||||
);
|
||||
}
|
||||
|
||||
// Completion
|
||||
|
|
@ -662,6 +677,7 @@ export class CompletionProvider {
|
|||
lang.endOfLine,
|
||||
fullStop,
|
||||
);
|
||||
charGenerator = stopAtStopTokens(charGenerator, stop);
|
||||
charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket(
|
||||
charGenerator,
|
||||
prefix,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import type { LineFilter } from "./lineStream";
|
||||
import type { LineFilter } from "./lineStream.js";
|
||||
|
||||
export interface AutocompleteLanguageInfo {
|
||||
name: string;
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { ILLM } from "..";
|
||||
import { longestCommonSubsequence } from "../util/lcs";
|
||||
import { lineIsRepeated } from "./lineStream";
|
||||
import type { ILLM } from "../index.js";
|
||||
import { longestCommonSubsequence } from "../util/lcs.js";
|
||||
import { lineIsRepeated } from "./lineStream.js";
|
||||
|
||||
function rewritesLineAbove(completion: string, prefix: string): boolean {
|
||||
const lineAbove = prefix
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ interface AutocompleteTemplate {
|
|||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
) => string);
|
||||
completionOptions?: Partial<CompletionOptions>;
|
||||
|
|
@ -78,6 +79,7 @@ const codestralMultifileFimTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
return `[SUFFIX]${suffix}[PREFIX]${prefix}`;
|
||||
|
|
@ -109,6 +111,7 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filename: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
const otherFiles =
|
||||
|
|
@ -155,9 +158,40 @@ const deepseekFimTemplate: AutocompleteTemplate = {
|
|||
},
|
||||
};
|
||||
|
||||
const deepseekFimTemplateWrongPipeChar: AutocompleteTemplate = {
|
||||
template: "<|fim▁begin|>{{{prefix}}}<|fim▁hole|>{{{suffix}}}<|fim▁end|>",
|
||||
completionOptions: { stop: ["<|fim▁begin|>", "<|fim▁hole|>", "<|fim▁end|>"] },
|
||||
// https://github.com/THUDM/CodeGeeX4/blob/main/guides/Infilling_guideline.md
|
||||
const codegeexFimTemplate: AutocompleteTemplate = {
|
||||
template: (
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
filepath: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
): string => {
|
||||
const relativePaths = shortestRelativePaths([
|
||||
...snippets.map((snippet) => snippet.filepath),
|
||||
filepath,
|
||||
]);
|
||||
const baseTemplate = `###PATH:${relativePaths[relativePaths.length - 1]}\n###LANGUAGE:${language}\n###MODE:BLOCK\n<|code_suffix|>${suffix}<|code_prefix|>${prefix}<|code_middle|>`;
|
||||
if (snippets.length == 0) {
|
||||
return `<|user|>\n${baseTemplate}<|assistant|>\n`;
|
||||
}
|
||||
const references = `###REFERENCE:\n${snippets
|
||||
.map((snippet, i) => `###PATH:${relativePaths[i]}\n${snippet.contents}\n`)
|
||||
.join("###REFERENCE:\n")}`;
|
||||
const prompt = `<|user|>\n${references}\n${baseTemplate}<|assistant|>\n`;
|
||||
return prompt;
|
||||
},
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<|user|>",
|
||||
"<|code_suffix|>",
|
||||
"<|code_prefix|>",
|
||||
"<|code_middle|>",
|
||||
"<|assistant|>",
|
||||
"<|endoftext|>",
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const gptAutocompleteTemplate: AutocompleteTemplate = {
|
||||
|
|
@ -175,6 +209,7 @@ const holeFillerTemplate: AutocompleteTemplate = {
|
|||
suffix: string,
|
||||
filename: string,
|
||||
reponame: string,
|
||||
language: string,
|
||||
snippets: AutocompleteSnippet[],
|
||||
) => {
|
||||
// From https://github.com/VictorTaelin/AI-scripts
|
||||
|
|
@ -307,6 +342,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
|
|||
return deepseekFimTemplate;
|
||||
}
|
||||
|
||||
if (lowerCaseModel.includes("codegeex")) {
|
||||
return codegeexFimTemplate;
|
||||
}
|
||||
|
||||
if (
|
||||
lowerCaseModel.includes("gpt") ||
|
||||
lowerCaseModel.includes("davinci-002") ||
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space"
|
||||
}
|
||||
}
|
||||
|
|
@ -3,7 +3,7 @@ import {
|
|||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
} from "../index.js";
|
||||
import { stripImages } from "../llm/countTokens.js";
|
||||
import { stripImages } from "../llm/images.js";
|
||||
import { renderTemplatedString } from "../llm/llms/index.js";
|
||||
import SlashCommands from "./slash/index.js";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
const CommitMessageCommand: SlashCommand = {
|
||||
name: "commit",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import { removeQuotesAndEscapes } from "../../util/index.js";
|
||||
|
||||
const PROMPT = (
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import {
|
|||
} from "../../autocomplete/lineStream.js";
|
||||
import { streamLines } from "../../diff/util.js";
|
||||
import { ContextItemWithId, ILLM, SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
import {
|
||||
dedentAndGetCommonWhitespace,
|
||||
getMarkdownLanguageTagForFile,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { ChatMessage, SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
const prompt = `
|
||||
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { homedir } from "node:os";
|
|||
import path from "path";
|
||||
import { languageForFilepath } from "../../autocomplete/constructPrompt.js";
|
||||
import { SlashCommand } from "../../index.js";
|
||||
import { stripImages } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
|
||||
function getOffsetDatetime(date: Date): Date {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { constants } from "../../deploy/constants.js";
|
||||
import { ChatMessageRole, FetchFunction, SlashCommand } from "../../index.js";
|
||||
import { pruneStringFromBottom, stripImages } from "../../llm/countTokens.js";
|
||||
import { pruneStringFromBottom } from "../../llm/countTokens.js";
|
||||
import { stripImages } from "../../llm/images.js";
|
||||
|
||||
const PROMPT = (
|
||||
input: string,
|
||||
|
|
|
|||
|
|
@ -105,6 +105,37 @@ export class ConfigHandler {
|
|||
private profiles: ProfileLifecycleManager[];
|
||||
private selectedProfileId: string;
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
controlPlaneClient,
|
||||
writeLog,
|
||||
);
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
|
||||
this.selectedProfileId = localProfileLoader.profileId;
|
||||
|
||||
// Always load local profile immediately in case control plane doesn't load
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
|
||||
// Load control plane profiles
|
||||
this.fetchControlPlaneProfiles();
|
||||
}
|
||||
|
||||
// This will be the local profile
|
||||
private get fallbackProfile() {
|
||||
return this.profiles[0];
|
||||
|
|
@ -163,40 +194,10 @@ export class ConfigHandler {
|
|||
});
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
private readonly writeLog: (text: string) => Promise<void>,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.ideSettingsPromise = ideSettingsPromise;
|
||||
this.writeLog = writeLog;
|
||||
|
||||
// Set local profile as default
|
||||
const localProfileLoader = new LocalProfileLoader(
|
||||
ide,
|
||||
ideSettingsPromise,
|
||||
writeLog,
|
||||
);
|
||||
this.profiles = [new ProfileLifecycleManager(localProfileLoader)];
|
||||
this.selectedProfileId = localProfileLoader.profileId;
|
||||
|
||||
// Always load local profile immediately in case control plane doesn't load
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
|
||||
// Load control plane profiles
|
||||
this.fetchControlPlaneProfiles();
|
||||
}
|
||||
|
||||
async setSelectedProfile(profileId: string) {
|
||||
this.selectedProfileId = profileId;
|
||||
const newConfig = await this.loadConfig();
|
||||
this.notifyConfigListerners(newConfig);
|
||||
this.notifyConfigListeners(newConfig);
|
||||
const selectedProfiles =
|
||||
this.globalContext.get("lastSelectedProfileForWorkspace") ?? {};
|
||||
selectedProfiles[await this.getWorkspaceId()] = profileId;
|
||||
|
|
@ -240,7 +241,7 @@ export class ConfigHandler {
|
|||
}
|
||||
}
|
||||
|
||||
private notifyConfigListerners(newConfig: ContinueConfig) {
|
||||
private notifyConfigListeners(newConfig: ContinueConfig) {
|
||||
// Notify listeners that config changed
|
||||
for (const listener of this.updateListeners) {
|
||||
listener(newConfig);
|
||||
|
|
@ -256,7 +257,7 @@ export class ConfigHandler {
|
|||
// TODO: this isn't right, there are two different senses in which you want to "reload"
|
||||
const newConfig = await this.currentProfile.reloadConfig();
|
||||
this.inactiveProfiles.forEach((profile) => profile.clearConfig());
|
||||
this.notifyConfigListerners(newConfig);
|
||||
this.notifyConfigListeners(newConfig);
|
||||
}
|
||||
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
|
|
|
|||
|
|
@ -32,39 +32,21 @@ export const FREE_TRIAL_MODELS: ModelDescription[] = [
|
|||
},
|
||||
];
|
||||
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
models: [],
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder2 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder2:3b",
|
||||
},
|
||||
};
|
||||
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
|
||||
{ name: "code", params: {} },
|
||||
{ name: "docs", params: {} },
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "terminal", params: {} },
|
||||
{ name: "problems", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
];
|
||||
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
models: FREE_TRIAL_MODELS,
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder2 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder2:3b",
|
||||
},
|
||||
};
|
||||
export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
];
|
||||
|
||||
export const defaultSlashCommandsVscode: SlashCommandDescription[] = [
|
||||
{
|
||||
|
|
@ -108,18 +90,40 @@ export const defaultSlashCommandsJetBrains = [
|
|||
},
|
||||
];
|
||||
|
||||
export const defaultContextProvidersVsCode: ContextProviderWithParams[] = [
|
||||
{ name: "code", params: {} },
|
||||
{ name: "docs", params: {} },
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "terminal", params: {} },
|
||||
{ name: "problems", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
];
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
models: [],
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder2 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder2:3b",
|
||||
},
|
||||
contextProviders: defaultContextProvidersVsCode,
|
||||
slashCommands: defaultSlashCommandsVscode,
|
||||
};
|
||||
|
||||
export const defaultContextProvidersJetBrains: ContextProviderWithParams[] = [
|
||||
{ name: "diff", params: {} },
|
||||
{ name: "folder", params: {} },
|
||||
{ name: "codebase", params: {} },
|
||||
];
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
models: FREE_TRIAL_MODELS,
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder2 3b",
|
||||
provider: "ollama",
|
||||
model: "starcoder2:3b",
|
||||
},
|
||||
contextProviders: defaultContextProvidersJetBrains,
|
||||
slashCommands: defaultSlashCommandsJetBrains,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ import CustomLLMClass from "../llm/llms/CustomLLM.js";
|
|||
import FreeTrial from "../llm/llms/FreeTrial.js";
|
||||
import { llmFromDescription } from "../llm/llms/index.js";
|
||||
|
||||
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
|
||||
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider.js";
|
||||
import { fetchwithRequestOptions } from "../util/fetchWithOptions.js";
|
||||
import { copyOf } from "../util/index.js";
|
||||
import mergeJson from "../util/merge.js";
|
||||
|
|
@ -59,8 +61,7 @@ import {
|
|||
getPromptFiles,
|
||||
slashCommandFromPromptFile,
|
||||
} from "./promptFile.js";
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
import { execSync } from "child_process";
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
|
||||
|
|
@ -94,13 +95,16 @@ function loadSerializedConfig(
|
|||
workspaceConfigs: ContinueRcJson[],
|
||||
ideSettings: IdeSettings,
|
||||
ideType: IdeType,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): SerializedContinueConfig {
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config: SerializedContinueConfig;
|
||||
try {
|
||||
config = resolveSerializedConfig(configPath);
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to parse config.json: ${e}`);
|
||||
let config: SerializedContinueConfig = overrideConfigJson!;
|
||||
if (!config) {
|
||||
try {
|
||||
config = resolveSerializedConfig(configPath);
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to parse config.json: ${e}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.allowAnonymousTelemetry === undefined) {
|
||||
|
|
@ -210,6 +214,7 @@ async function intermediateToFinalConfig(
|
|||
ideSettings: IdeSettings,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
allowFreeTrial: boolean = true,
|
||||
): Promise<ContinueConfig> {
|
||||
// Auto-detect models
|
||||
|
|
@ -347,16 +352,39 @@ async function intermediateToFinalConfig(
|
|||
).filter((x) => x !== undefined) as BaseLLM[];
|
||||
}
|
||||
|
||||
// These context providers are always included, regardless of what, if anything,
|
||||
// the user has configured in config.json
|
||||
const DEFAULT_CONTEXT_PROVIDERS = [
|
||||
new FileContextProvider({}),
|
||||
new CodebaseContextProvider({}),
|
||||
];
|
||||
|
||||
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
|
||||
({ description: { title } }) => title,
|
||||
);
|
||||
|
||||
// Context providers
|
||||
const contextProviders: IContextProvider[] = [new FileContextProvider({})];
|
||||
const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS;
|
||||
|
||||
for (const provider of config.contextProviders || []) {
|
||||
if (isContextProviderWithParams(provider)) {
|
||||
const cls = contextProviderClassFromName(provider.name) as any;
|
||||
if (!cls) {
|
||||
console.warn(`Unknown context provider ${provider.name}`);
|
||||
if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) {
|
||||
console.warn(`Unknown context provider ${provider.name}`);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
contextProviders.push(new cls(provider.params));
|
||||
const instance: IContextProvider = new cls(provider.params);
|
||||
|
||||
// Handle continue-proxy
|
||||
if (instance.description.title === "continue-proxy") {
|
||||
(instance as ContinueProxyContextProvider).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
contextProviders.push(instance);
|
||||
} else {
|
||||
contextProviders.push(new CustomContextProviderClass(provider));
|
||||
}
|
||||
|
|
@ -435,6 +463,7 @@ function finalToBrowserConfig(
|
|||
systemMessage: m.systemMessage,
|
||||
requestOptions: m.requestOptions,
|
||||
promptTemplates: m.promptTemplates as any,
|
||||
capabilities: m.capabilities,
|
||||
})),
|
||||
systemMessage: final.systemMessage,
|
||||
completionOptions: final.completionOptions,
|
||||
|
|
@ -504,7 +533,7 @@ async function buildConfigTs() {
|
|||
);
|
||||
} else {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
const esbuild = await import("esbuild");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
|
|
@ -536,9 +565,16 @@ async function loadFullConfigNode(
|
|||
ideType: IdeType,
|
||||
uniqueId: string,
|
||||
writeLog: (log: string) => Promise<void>,
|
||||
workOsAccessToken: string | undefined,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
): Promise<ContinueConfig> {
|
||||
// Serialized config
|
||||
let serialized = loadSerializedConfig(workspaceConfigs, ideSettings, ideType);
|
||||
let serialized = loadSerializedConfig(
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
ideType,
|
||||
overrideConfigJson,
|
||||
);
|
||||
|
||||
// Convert serialized to intermediate config
|
||||
let intermediate = await serializedToIntermediateConfig(serialized, ide);
|
||||
|
|
@ -549,7 +585,7 @@ async function loadFullConfigNode(
|
|||
try {
|
||||
// Try config.ts first
|
||||
const configJsPath = getConfigJsPath();
|
||||
const module = await require(configJsPath);
|
||||
const module = await import(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
|
|
@ -566,7 +602,7 @@ async function loadFullConfigNode(
|
|||
const configJsPathForRemote = getConfigJsPathForRemote(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
);
|
||||
const module = await require(configJsPathForRemote);
|
||||
const module = await import(configJsPathForRemote);
|
||||
delete require.cache[require.resolve(configJsPathForRemote)];
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
|
|
@ -584,6 +620,7 @@ async function loadFullConfigNode(
|
|||
ideSettings,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
);
|
||||
return finalConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,13 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import {
|
||||
ContinueConfig,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import {
|
||||
defaultContextProvidersJetBrains,
|
||||
defaultContextProvidersVsCode,
|
||||
defaultSlashCommandsJetBrains,
|
||||
defaultSlashCommandsVscode,
|
||||
} from "../default";
|
||||
import {
|
||||
intermediateToFinalConfig,
|
||||
serializedToIntermediateConfig,
|
||||
} from "../load";
|
||||
import { IProfileLoader } from "./IProfileLoader";
|
||||
} from "../../index.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
|
||||
export default class ControlPlaneProfileLoader implements IProfileLoader {
|
||||
private static RELOAD_INTERVAL = 1000 * 60 * 15; // every 15 minutes
|
||||
|
|
@ -49,58 +37,20 @@ export default class ControlPlaneProfileLoader implements IProfileLoader {
|
|||
}
|
||||
|
||||
async doLoadConfig(): Promise<ContinueConfig> {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const settings =
|
||||
this.workspaceSettings ??
|
||||
((await this.controlPlaneClient.getSettingsForWorkspace(
|
||||
this.profileId,
|
||||
)) as any);
|
||||
|
||||
// First construct a SerializedContinueConfig from the ControlPlaneSettings (TODO)
|
||||
const serializedConfig: SerializedContinueConfig = settings;
|
||||
|
||||
serializedConfig.contextProviders ??=
|
||||
ideInfo.ideType === "vscode"
|
||||
? defaultContextProvidersVsCode
|
||||
: defaultContextProvidersJetBrains;
|
||||
serializedConfig.slashCommands ??=
|
||||
ideInfo.ideType === "vscode"
|
||||
? defaultSlashCommandsVscode
|
||||
: defaultSlashCommandsJetBrains;
|
||||
|
||||
const intermediateConfig = await serializedToIntermediateConfig(
|
||||
serializedConfig,
|
||||
return doLoadConfig(
|
||||
this.ide,
|
||||
);
|
||||
|
||||
const uniqueId = await this.ide.getUniqueId();
|
||||
const finalConfig = await intermediateToFinalConfig(
|
||||
intermediateConfig,
|
||||
this.ide,
|
||||
await this.ideSettingsPromise,
|
||||
uniqueId,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
serializedConfig,
|
||||
);
|
||||
|
||||
// Set up team analytics/telemetry
|
||||
await Telemetry.setup(true, uniqueId, ideInfo.extensionVersion);
|
||||
await TeamAnalytics.setup(
|
||||
settings.analytics,
|
||||
uniqueId,
|
||||
ideInfo.extensionVersion,
|
||||
);
|
||||
|
||||
[
|
||||
...finalConfig.models,
|
||||
...(finalConfig.tabAutocompleteModels ?? []),
|
||||
].forEach(async (model) => {
|
||||
if (model.providerName === "continue-proxy") {
|
||||
const accessToken = await this.controlPlaneClient.getAccessToken();
|
||||
(model as ContinueProxy).workOsAccessToken = accessToken;
|
||||
}
|
||||
});
|
||||
|
||||
return finalConfig;
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// ProfileHandlers manage the loading of a config, allowing us to abstract over different ways of getting to a ContinueConfig
|
||||
|
||||
import { ContinueConfig } from "../..";
|
||||
import { ContinueConfig } from "../../index.js";
|
||||
|
||||
// After we have the ContinueConfig, the ConfigHandler takes care of everything else (loading models, lifecycle, etc.)
|
||||
export interface IProfileLoader {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ContinueConfig, ContinueRcJson, IDE, IdeSettings } from "../..";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { loadFullConfigNode } from "../load";
|
||||
import { IProfileLoader } from "./IProfileLoader";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { ContinueConfig, IDE, IdeSettings } from "../../index.js";
|
||||
import doLoadConfig from "./doLoadConfig.js";
|
||||
import { IProfileLoader } from "./IProfileLoader.js";
|
||||
|
||||
export default class LocalProfileLoader implements IProfileLoader {
|
||||
static ID = "local";
|
||||
|
|
@ -11,42 +11,18 @@ export default class LocalProfileLoader implements IProfileLoader {
|
|||
constructor(
|
||||
private ide: IDE,
|
||||
private ideSettingsPromise: Promise<IdeSettings>,
|
||||
// private controlPlaneClient: ControlPlaneClient,
|
||||
private controlPlaneClient: ControlPlaneClient,
|
||||
private writeLog: (message: string) => Promise<void>,
|
||||
) {}
|
||||
|
||||
async doLoadConfig(): Promise<ContinueConfig> {
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
workspaceConfigs = await this.ide.getWorkspaceConfigs();
|
||||
} catch (e) {
|
||||
console.warn("Failed to load workspace configs");
|
||||
}
|
||||
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const uniqueId = await this.ide.getUniqueId();
|
||||
const ideSettings = await this.ideSettingsPromise;
|
||||
|
||||
const newConfig = await loadFullConfigNode(
|
||||
return doLoadConfig(
|
||||
this.ide,
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
ideInfo.ideType,
|
||||
uniqueId,
|
||||
this.ideSettingsPromise,
|
||||
this.controlPlaneClient,
|
||||
this.writeLog,
|
||||
undefined,
|
||||
);
|
||||
newConfig.allowAnonymousTelemetry =
|
||||
newConfig.allowAnonymousTelemetry &&
|
||||
(await this.ide.isTelemetryEnabled());
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
newConfig.allowAnonymousTelemetry ?? true,
|
||||
await this.ide.getUniqueId(),
|
||||
ideInfo.extensionVersion,
|
||||
);
|
||||
|
||||
return newConfig;
|
||||
}
|
||||
|
||||
setIsActive(isActive: boolean): void {}
|
||||
|
|
|
|||
82
core/config/profile/doLoadConfig.ts
Normal file
82
core/config/profile/doLoadConfig.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
import { ContinueProxyReranker } from "../../context/rerankers/ContinueProxyReranker.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import {
|
||||
ContinueRcJson,
|
||||
IDE,
|
||||
IdeSettings,
|
||||
SerializedContinueConfig,
|
||||
} from "../../index.js";
|
||||
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
import { loadFullConfigNode } from "../load.js";
|
||||
|
||||
export default async function doLoadConfig(
|
||||
ide: IDE,
|
||||
ideSettingsPromise: Promise<IdeSettings>,
|
||||
controlPlaneClient: ControlPlaneClient,
|
||||
writeLog: (message: string) => Promise<void>,
|
||||
overrideConfigJson: SerializedContinueConfig | undefined,
|
||||
) {
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
workspaceConfigs = await ide.getWorkspaceConfigs();
|
||||
} catch (e) {
|
||||
console.warn("Failed to load workspace configs");
|
||||
}
|
||||
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
const uniqueId = await ide.getUniqueId();
|
||||
const ideSettings = await ideSettingsPromise;
|
||||
const workOsAccessToken = await controlPlaneClient.getAccessToken();
|
||||
|
||||
const newConfig = await loadFullConfigNode(
|
||||
ide,
|
||||
workspaceConfigs,
|
||||
ideSettings,
|
||||
ideInfo.ideType,
|
||||
uniqueId,
|
||||
writeLog,
|
||||
workOsAccessToken,
|
||||
overrideConfigJson,
|
||||
);
|
||||
newConfig.allowAnonymousTelemetry =
|
||||
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
newConfig.allowAnonymousTelemetry ?? true,
|
||||
await ide.getUniqueId(),
|
||||
ideInfo.extensionVersion,
|
||||
);
|
||||
|
||||
if (newConfig.analytics) {
|
||||
await TeamAnalytics.setup(
|
||||
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all
|
||||
uniqueId,
|
||||
ideInfo.extensionVersion,
|
||||
);
|
||||
}
|
||||
|
||||
[...newConfig.models, ...(newConfig.tabAutocompleteModels ?? [])].forEach(
|
||||
async (model) => {
|
||||
if (model.providerName === "continue-proxy") {
|
||||
(model as ContinueProxy).workOsAccessToken = workOsAccessToken;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (newConfig.embeddingsProvider?.providerName === "continue-proxy") {
|
||||
(
|
||||
newConfig.embeddingsProvider as ContinueProxyEmbeddingsProvider
|
||||
).workOsAccessToken = workOsAccessToken;
|
||||
}
|
||||
|
||||
if (newConfig.reranker?.name === "continue-proxy") {
|
||||
(newConfig.reranker as ContinueProxyReranker).workOsAccessToken =
|
||||
workOsAccessToken;
|
||||
}
|
||||
|
||||
return newConfig;
|
||||
}
|
||||
|
|
@ -3,9 +3,9 @@ import path from "path";
|
|||
import * as YAML from "yaml";
|
||||
import type { IDE, SlashCommand } from "..";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { stripImages } from "../llm/countTokens.js";
|
||||
import { renderTemplatedString } from "../llm/llms/index.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../llm/llms/index";
|
||||
import { getBasename } from "../util/index";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
|
|
@ -34,7 +34,7 @@ export async function getPromptFiles(
|
|||
const DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
# Continue will automatically create a slash command for each prompt in the .prompts folder
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/walkthroughs/prompt-files
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
|
||||
temperature: 0.0
|
||||
---
|
||||
{{{ diff }}}
|
||||
|
|
@ -133,6 +133,7 @@ export function slashCommandFromPromptFile(
|
|||
provider.description.title,
|
||||
async (context: any) => {
|
||||
const items = await provider.getContextItems(context, {
|
||||
config,
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
fetch,
|
||||
fullInput: userInput,
|
||||
|
|
|
|||
76
core/context/providers/ContinueProxyContextProvider.ts
Normal file
76
core/context/providers/ContinueProxyContextProvider.ts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../../index.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
|
||||
class ContinueProxyContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "continue-proxy",
|
||||
displayTitle: "Continue Proxy",
|
||||
description: "Retrieve a context item from a Continue for Teams add-on",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
workOsAccessToken: string | undefined = undefined;
|
||||
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
title:
|
||||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
ContinueProxyContextProvider.description.description,
|
||||
type: this.options.type || ContinueProxyContextProvider.description.type,
|
||||
};
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const response = await args.fetch(
|
||||
new URL(`/proxy/context/${this.options.id}/list`, CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.workOsAccessToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
const data = await response.json();
|
||||
return data.items;
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const response = await extras.fetch(
|
||||
new URL(`/proxy/context/${this.options.id}/retrieve`, CONTROL_PLANE_URL),
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.workOsAccessToken}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query: query || "",
|
||||
fullInput: extras.fullInput,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
const items: any = await response.json();
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
export default ContinueProxyContextProvider;
|
||||
|
|
@ -30,7 +30,7 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
|
||||
const [connectionName, table] = query.split(".");
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
const { getDatabaseAdapter } = await import("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
if (connection.name === connectionName) {
|
||||
|
|
@ -87,7 +87,7 @@ class DatabaseContextProvider extends BaseContextProvider {
|
|||
return contextItems;
|
||||
}
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
const { getDatabaseAdapter } = await import("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
const adapter = getDatabaseAdapter(
|
||||
|
|
|
|||
|
|
@ -4,18 +4,16 @@ import {
|
|||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
EmbeddingsProvider,
|
||||
LoadSubmenuItemsArgs,
|
||||
Reranker,
|
||||
} from "../../index.js";
|
||||
import { DocsService } from "../../indexing/docs/DocsService.js";
|
||||
import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
import { BaseContextProvider } from "../index.js";
|
||||
} from "../..";
|
||||
import DocsService from "../../indexing/docs/DocsService";
|
||||
import preIndexedDocs from "../../indexing/docs/preIndexedDocs";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { BaseContextProvider } from "../";
|
||||
|
||||
class DocsContextProvider extends BaseContextProvider {
|
||||
static DEFAULT_N_RETRIEVE = 30;
|
||||
static DEFAULT_N_FINAL = 15;
|
||||
static nRetrieve = 30;
|
||||
static nFinal = 15;
|
||||
static description: ContextProviderDescription = {
|
||||
title: "docs",
|
||||
displayTitle: "Docs",
|
||||
|
|
@ -23,11 +21,8 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
type: "submenu",
|
||||
};
|
||||
|
||||
private docsService: DocsService;
|
||||
|
||||
constructor(options: any) {
|
||||
super(options);
|
||||
this.docsService = DocsService.getInstance();
|
||||
}
|
||||
|
||||
private async _rerankChunks(
|
||||
|
|
@ -46,14 +41,14 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
chunksCopy = chunksCopy.splice(
|
||||
0,
|
||||
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
|
||||
this.options?.nFinal ?? DocsContextProvider.nFinal,
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn(`Failed to rerank docs results: ${e}`);
|
||||
|
||||
chunksCopy = chunksCopy.splice(
|
||||
0,
|
||||
this.options?.nFinal ?? DocsContextProvider.DEFAULT_N_FINAL,
|
||||
this.options?.nFinal ?? DocsContextProvider.nFinal,
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -84,14 +79,15 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const ideInfo = await extras.ide.getIdeInfo();
|
||||
const isJetBrains = ideInfo.ideType === "jetbrains";
|
||||
const docsService = DocsService.getSingleton();
|
||||
|
||||
if (!docsService) {
|
||||
console.error(`${DocsService.name} has not been initialized`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const isJetBrainsAndPreIndexedDocsProvider =
|
||||
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
|
||||
ideInfo,
|
||||
extras.embeddingsProvider.id,
|
||||
);
|
||||
await docsService.isJetBrainsAndPreIndexedDocsProvider();
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
extras.ide.errorPopup(
|
||||
|
|
@ -106,29 +102,26 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
|
||||
const preIndexedDoc = preIndexedDocs[query];
|
||||
|
||||
let embeddingsProvider: EmbeddingsProvider;
|
||||
|
||||
if (!!preIndexedDoc && !isJetBrains) {
|
||||
// Pre-indexed docs should be filtered out in `loadSubmenuItems`,
|
||||
// for JetBrains users, but we sanity check that here
|
||||
if (!!preIndexedDoc) {
|
||||
Telemetry.capture("docs_pre_indexed_doc_used", {
|
||||
doc: preIndexedDoc["title"],
|
||||
});
|
||||
|
||||
embeddingsProvider = DocsService.preIndexedDocsEmbeddingsProvider;
|
||||
} else {
|
||||
embeddingsProvider = extras.embeddingsProvider;
|
||||
}
|
||||
|
||||
const embeddingsProvider = await docsService.getEmbeddingsProvider(
|
||||
!!preIndexedDoc,
|
||||
);
|
||||
|
||||
const [vector] = await embeddingsProvider.embed([extras.fullInput]);
|
||||
|
||||
let chunks = await this.docsService.retrieve(
|
||||
let chunks = await docsService.retrieveChunks(
|
||||
query,
|
||||
vector,
|
||||
this.options?.nRetrieve ?? DocsContextProvider.DEFAULT_N_RETRIEVE,
|
||||
embeddingsProvider.id,
|
||||
this.options?.nRetrieve ?? DocsContextProvider.nRetrieve,
|
||||
);
|
||||
|
||||
const favicon = await docsService.getFavicon(query);
|
||||
|
||||
if (extras.reranker) {
|
||||
chunks = await this._rerankChunks(
|
||||
chunks,
|
||||
|
|
@ -140,6 +133,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
return [
|
||||
...chunks
|
||||
.map((chunk) => ({
|
||||
icon: favicon,
|
||||
name: chunk.filepath.includes("/tree/main") // For display of GitHub files
|
||||
? chunk.filepath
|
||||
.split("/")
|
||||
|
|
@ -157,7 +151,10 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
name: "Instructions",
|
||||
description: "Instructions",
|
||||
content:
|
||||
"Use the above documentation to answer the following question. You should not reference anything outside of what is shown, unless it is a commonly known concept. Reference URLs whenever possible using markdown formatting. If there isn't enough information to answer the question, suggest where the user might look to learn more.",
|
||||
"Use the above documentation to answer the following question. You should not reference " +
|
||||
"anything outside of what is shown, unless it is a commonly known concept. Reference URLs " +
|
||||
"whenever possible using markdown formatting. If there isn't enough information to answer " +
|
||||
"the question, suggest where the user might look to learn more.",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
|
@ -165,15 +162,19 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const ideInfo = await args.ide.getIdeInfo();
|
||||
const isJetBrains = ideInfo.ideType === "jetbrains";
|
||||
const configSites = this.options?.sites || [];
|
||||
const docsService = DocsService.getSingleton();
|
||||
|
||||
if (!docsService) {
|
||||
console.error(`${DocsService.name} has not been initialized`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const docs = (await docsService.list()) ?? [];
|
||||
const canUsePreindexedDocs = await docsService.canUsePreindexedDocs();
|
||||
|
||||
const submenuItemsMap = new Map<string, ContextSubmenuItem>();
|
||||
|
||||
if (!isJetBrains) {
|
||||
// Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
|
||||
// However, we don't ship transformers.js with the JetBrains extension.
|
||||
// So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
|
||||
if (canUsePreindexedDocs) {
|
||||
for (const { startUrl, title } of Object.values(preIndexedDocs)) {
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
|
|
@ -186,25 +187,18 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
}
|
||||
}
|
||||
|
||||
for (const { title, baseUrl } of await this.docsService.list()) {
|
||||
submenuItemsMap.set(baseUrl, {
|
||||
title,
|
||||
id: baseUrl,
|
||||
description: new URL(baseUrl).hostname,
|
||||
});
|
||||
}
|
||||
|
||||
for (const { startUrl, title } of configSites) {
|
||||
for (const { startUrl, title, favicon } of docs) {
|
||||
submenuItemsMap.set(startUrl, {
|
||||
title,
|
||||
id: startUrl,
|
||||
description: new URL(startUrl).hostname,
|
||||
icon: favicon,
|
||||
});
|
||||
}
|
||||
|
||||
const submenuItems = Array.from(submenuItemsMap.values());
|
||||
|
||||
if (!isJetBrains) {
|
||||
if (canUsePreindexedDocs) {
|
||||
return this._sortByPreIndexedDocs(submenuItems);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { RequestOptions } from "../../../index.js";
|
||||
const { convert: adf2md } = require("adf-to-md");
|
||||
|
||||
// @ts-ignore
|
||||
import adf2md from "adf-to-md";
|
||||
interface JiraClientOptions {
|
||||
domain: string;
|
||||
username: string;
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@ class PostgresContextProvider extends BaseContextProvider {
|
|||
static DEFAULT_SAMPLE_ROWS = 3;
|
||||
|
||||
private async getPool() {
|
||||
const pg = await require("pg");
|
||||
// @ts-ignore
|
||||
const pg = await import("pg");
|
||||
|
||||
return new pg.Pool({
|
||||
host: this.options.host,
|
||||
port: this.options.port,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { ContextProviderName } from "../../index.js";
|
|||
import { BaseContextProvider } from "../index.js";
|
||||
import CodeContextProvider from "./CodeContextProvider.js";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider.js";
|
||||
import ContinueProxyContextProvider from "./ContinueProxyContextProvider.js";
|
||||
import CurrentFileContextProvider from "./CurrentFileContextProvider.js";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider.js";
|
||||
import DiffContextProvider from "./DiffContextProvider.js";
|
||||
|
|
@ -40,7 +41,6 @@ const Providers: (typeof BaseContextProvider)[] = [
|
|||
HttpContextProvider,
|
||||
SearchContextProvider,
|
||||
OSContextProvider,
|
||||
CodebaseContextProvider,
|
||||
ProblemsContextProvider,
|
||||
FolderContextProvider,
|
||||
DocsContextProvider,
|
||||
|
|
@ -51,6 +51,7 @@ const Providers: (typeof BaseContextProvider)[] = [
|
|||
CodeContextProvider,
|
||||
CurrentFileContextProvider,
|
||||
URLContextProvider,
|
||||
ContinueProxyContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
46
core/context/rerankers/ContinueProxyReranker.ts
Normal file
46
core/context/rerankers/ContinueProxyReranker.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import fetch from "node-fetch";
|
||||
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
|
||||
import { Chunk, Reranker } from "../../index.js";
|
||||
|
||||
export class ContinueProxyReranker implements Reranker {
|
||||
name = "continue-proxy";
|
||||
|
||||
private _workOsAccessToken: string | undefined = undefined;
|
||||
|
||||
get workOsAccessToken(): string | undefined {
|
||||
return this._workOsAccessToken;
|
||||
}
|
||||
|
||||
set workOsAccessToken(value: string | undefined) {
|
||||
if (this._workOsAccessToken !== value) {
|
||||
this._workOsAccessToken = value;
|
||||
this.params.apiKey = value!;
|
||||
}
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly params: {
|
||||
apiKey: string;
|
||||
model?: string;
|
||||
},
|
||||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
const url = new URL("/model-proxy/v1/rerank", CONTROL_PLANE_URL);
|
||||
const resp = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${this.params.apiKey}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
query,
|
||||
documents: chunks.map((chunk) => chunk.content),
|
||||
model: this.params.model,
|
||||
}),
|
||||
});
|
||||
const data: any = await resp.json();
|
||||
const results = data.data.sort((a: any, b: any) => a.index - b.index);
|
||||
return results.map((result: any) => result.relevance_score);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +1,16 @@
|
|||
import { RerankerName } from "../../index.js";
|
||||
import { CohereReranker } from "./cohere.js";
|
||||
import { ContinueProxyReranker } from "./ContinueProxyReranker.js";
|
||||
import { FreeTrialReranker } from "./freeTrial.js";
|
||||
import { LLMReranker } from "./llm.js";
|
||||
import { HuggingFaceTEIReranker } from "./tei.js";
|
||||
import { VoyageReranker } from "./voyage.js";
|
||||
import {HuggingFaceTEIReranker} from "./tei.js"
|
||||
|
||||
export const AllRerankers: { [key in RerankerName]: any } = {
|
||||
cohere: CohereReranker,
|
||||
llm: LLMReranker,
|
||||
voyage: VoyageReranker,
|
||||
"free-trial": FreeTrialReranker,
|
||||
"huggingface-tei": HuggingFaceTEIReranker
|
||||
"huggingface-tei": HuggingFaceTEIReranker,
|
||||
"continue-proxy": ContinueProxyReranker,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ export class VoyageReranker implements Reranker {
|
|||
) {}
|
||||
|
||||
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
|
||||
if (!query || chunks.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const resp = await fetch("https://api.voyageai.com/v1/rerank", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
|
|||
|
|
@ -4,9 +4,12 @@ import {
|
|||
EmbeddingsProvider,
|
||||
IDE,
|
||||
Reranker,
|
||||
} from "../../..";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
|
||||
import { retrieveFts } from "../fullTextSearch";
|
||||
} from "../../../index.js";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk.js";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex.js";
|
||||
import { MAX_CHUNK_SIZE } from "../../../llm/constants.js";
|
||||
import { retrieveFts } from "../fullTextSearch.js";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
|
||||
|
||||
export interface RetrievalPipelineOptions {
|
||||
ide: IDE;
|
||||
|
|
@ -32,6 +35,43 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
);
|
||||
}
|
||||
|
||||
protected async retrieveAndChunkRecentlyEditedFiles(
|
||||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
const recentlyEditedFilesSlice = Array.from(
|
||||
recentlyEditedFilesCache.keys(),
|
||||
).slice(0, n);
|
||||
|
||||
// If the number of recently edited files is less than the retrieval limit,
|
||||
// include additional open files. This is useful in the case where a user
|
||||
// has many tabs open and reloads their IDE. They now have 0 recently edited files,
|
||||
// but many open tabs that represent what they were working on prior to reload.
|
||||
if (recentlyEditedFilesSlice.length < n) {
|
||||
const openFiles = await this.options.ide.getOpenFiles();
|
||||
recentlyEditedFilesSlice.push(
|
||||
...openFiles.slice(0, n - recentlyEditedFilesSlice.length),
|
||||
);
|
||||
}
|
||||
|
||||
const chunks: Chunk[] = [];
|
||||
|
||||
for (const filepath of recentlyEditedFilesSlice) {
|
||||
const contents = await this.options.ide.readFile(filepath);
|
||||
const fileChunks = chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize: MAX_CHUNK_SIZE,
|
||||
digest: filepath,
|
||||
});
|
||||
|
||||
for await (const chunk of fileChunks) {
|
||||
chunks.push(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
protected async retrieveFts(input: string, n: number): Promise<Chunk[]> {
|
||||
return retrieveFts(
|
||||
input,
|
||||
|
|
|
|||
|
|
@ -1,26 +1,38 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { deduplicateChunks } from "../util";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline";
|
||||
import { Chunk } from "../../../index.js";
|
||||
import { deduplicateChunks } from "../util.js";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
|
||||
|
||||
export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
async run(): Promise<Chunk[]> {
|
||||
const { input } = this.options;
|
||||
const { input, nFinal } = this.options;
|
||||
|
||||
// We give 1/4 weight to recently edited files, 1/4 to full text search,
|
||||
// and the remaining 1/2 to embeddings
|
||||
const recentlyEditedNFinal = nFinal * 0.25;
|
||||
const ftsNFinal = nFinal * 0.25;
|
||||
const embeddingsNFinal = nFinal - recentlyEditedNFinal - ftsNFinal;
|
||||
|
||||
// Get all retrieval results
|
||||
const retrievalResults: Chunk[] = [];
|
||||
|
||||
// Full-text search
|
||||
const ftsResults = await this.retrieveFts(input, this.options.nFinal / 2);
|
||||
retrievalResults.push(...ftsResults);
|
||||
const ftsChunks = await this.retrieveFts(input, ftsNFinal);
|
||||
|
||||
// Embeddings
|
||||
const embeddingResults = await this.retrieveEmbeddings(
|
||||
const embeddingsChunks = await this.retrieveEmbeddings(
|
||||
input,
|
||||
this.options.nFinal / 2,
|
||||
embeddingsNFinal,
|
||||
);
|
||||
retrievalResults.push(...embeddingResults);
|
||||
|
||||
const finalResults: Chunk[] = deduplicateChunks(retrievalResults);
|
||||
return finalResults;
|
||||
const recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
|
||||
|
||||
retrievalResults.push(
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
);
|
||||
|
||||
const deduplicatedRetrievalResults: Chunk[] =
|
||||
deduplicateChunks(retrievalResults);
|
||||
|
||||
return deduplicatedRetrievalResults;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,30 @@
|
|||
import { Chunk } from "../../..";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
|
||||
import { deduplicateChunks } from "../util";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline";
|
||||
import { Chunk } from "../../../index.js";
|
||||
import { RETRIEVAL_PARAMS } from "../../../util/parameters.js";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache.js";
|
||||
import { deduplicateChunks } from "../util.js";
|
||||
import BaseRetrievalPipeline from "./BaseRetrievalPipeline.js";
|
||||
|
||||
export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
||||
private async _retrieveInitial(): Promise<Chunk[]> {
|
||||
const { input, nRetrieve } = this.options;
|
||||
|
||||
// Get all retrieval results
|
||||
const retrievalResults: Chunk[] = [];
|
||||
|
||||
// Full-text search
|
||||
const ftsResults = await this.retrieveFts(input, nRetrieve / 2);
|
||||
retrievalResults.push(...ftsResults);
|
||||
const ftsChunks = await this.retrieveFts(input, nRetrieve);
|
||||
const embeddingsChunks = await this.retrieveEmbeddings(input, nRetrieve);
|
||||
const recentlyEditedFilesChunks =
|
||||
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
|
||||
|
||||
// Embeddings
|
||||
const embeddingResults = await this.retrieveEmbeddings(input, nRetrieve);
|
||||
retrievalResults.push(
|
||||
...embeddingResults.slice(0, nRetrieve - ftsResults.length),
|
||||
...recentlyEditedFilesChunks,
|
||||
...ftsChunks,
|
||||
...embeddingsChunks,
|
||||
);
|
||||
|
||||
const results: Chunk[] = deduplicateChunks(retrievalResults);
|
||||
return results;
|
||||
const deduplicatedRetrievalResults: Chunk[] =
|
||||
deduplicateChunks(retrievalResults);
|
||||
|
||||
return deduplicatedRetrievalResults;
|
||||
}
|
||||
|
||||
private async _rerank(input: string, chunks: Chunk[]): Promise<Chunk[]> {
|
||||
|
|
@ -74,12 +77,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
}
|
||||
|
||||
async run(): Promise<Chunk[]> {
|
||||
// Retrieve initial results
|
||||
let results = await this._retrieveInitial();
|
||||
|
||||
// Rerank
|
||||
const { input } = this.options;
|
||||
results = await this._rerank(input, results);
|
||||
const intialResults = await this._retrieveInitial();
|
||||
const rankedResults = await this._rerank(this.options.input, intialResults);
|
||||
|
||||
// // // Expand top reranked results
|
||||
// const expanded = await this._expandRankedResults(results);
|
||||
|
|
@ -93,7 +92,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
|
|||
|
||||
// TODO: stitch together results
|
||||
|
||||
return results;
|
||||
return rankedResults;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
15
core/context/retrieval/recentlyEditedFilesCache.ts
Normal file
15
core/context/retrieval/recentlyEditedFilesCache.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import QuickLRU from "quick-lru";
|
||||
import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js";
|
||||
|
||||
// The cache key and value are both a filepath string
|
||||
export type RecentlyEditedFilesCacheKeyAndValue =
|
||||
ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"];
|
||||
|
||||
const MAX_NUM_RECENTLY_EDITED_FILES = 100;
|
||||
|
||||
export const recentlyEditedFilesCache = new QuickLRU<
|
||||
RecentlyEditedFilesCacheKeyAndValue,
|
||||
RecentlyEditedFilesCacheKeyAndValue
|
||||
>({
|
||||
maxSize: MAX_NUM_RECENTLY_EDITED_FILES,
|
||||
});
|
||||
|
|
@ -3,7 +3,7 @@ import {
|
|||
ContextItem,
|
||||
ContextProviderExtras,
|
||||
} from "../../index.js";
|
||||
|
||||
import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js";
|
||||
import { getRelativePath } from "../../util/index.js";
|
||||
import { RetrievalPipelineOptions } from "./pipelines/BaseRetrievalPipeline.js";
|
||||
import NoRerankerRetrievalPipeline from "./pipelines/NoRerankerRetrievalPipeline.js";
|
||||
|
|
@ -19,24 +19,20 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
}
|
||||
|
||||
// transformers.js not supported in JetBrains IDEs right now
|
||||
if (
|
||||
extras.embeddingsProvider.id === "all-MiniLM-L6-v2" &&
|
||||
(await extras.ide.getIdeInfo()).ideType === "jetbrains"
|
||||
) {
|
||||
|
||||
const isJetBrainsAndTransformersJs =
|
||||
extras.embeddingsProvider.id === TransformersJsEmbeddingsProvider.model &&
|
||||
(await extras.ide.getIdeInfo()).ideType === "jetbrains";
|
||||
|
||||
if (isJetBrainsAndTransformersJs) {
|
||||
throw new Error(
|
||||
"The transformers.js context provider is not currently supported in JetBrains. For now, you can use Ollama to set up local embeddings, or use our 'free-trial' embeddings provider. See here to learn more: https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
|
||||
"The 'transformers.js' context provider is not currently supported in JetBrains. " +
|
||||
"For now, you can use Ollama to set up local embeddings, or use our 'free-trial' " +
|
||||
"embeddings provider. See here to learn more: " +
|
||||
"https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
|
||||
);
|
||||
}
|
||||
|
||||
// Fill half of the context length, up to a max of 100 snippets
|
||||
const contextLength = extras.llm.contextLength;
|
||||
const tokensPerSnippet = 512;
|
||||
const nFinal =
|
||||
options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2);
|
||||
const useReranking = extras.reranker !== undefined;
|
||||
const nRetrieve =
|
||||
useReranking === false ? nFinal : options?.nRetrieve || 2 * nFinal;
|
||||
|
||||
// Get tags to retrieve for
|
||||
const workspaceDirs = await extras.ide.getWorkspaceDirs();
|
||||
|
||||
|
|
@ -44,6 +40,14 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
throw new Error("No workspace directories found");
|
||||
}
|
||||
|
||||
// Fill half of the context length, up to a max of 100 snippets
|
||||
const contextLength = extras.llm.contextLength;
|
||||
const tokensPerSnippet = 512;
|
||||
const nFinal =
|
||||
options?.nFinal ?? Math.min(50, contextLength / tokensPerSnippet / 2);
|
||||
const useReranking = !!extras.reranker;
|
||||
const nRetrieve = useReranking ? options?.nRetrieve || 2 * nFinal : nFinal;
|
||||
|
||||
const branches = (await Promise.race([
|
||||
Promise.all(workspaceDirs.map((dir) => extras.ide.getBranch(dir))),
|
||||
new Promise((resolve) => {
|
||||
|
|
@ -52,6 +56,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
}, 500);
|
||||
}),
|
||||
])) as string[];
|
||||
|
||||
const tags: BranchAndDir[] = workspaceDirs.map((directory, i) => ({
|
||||
directory,
|
||||
branch: branches[i],
|
||||
|
|
@ -60,6 +65,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
const pipelineType = useReranking
|
||||
? RerankerRetrievalPipeline
|
||||
: NoRerankerRetrievalPipeline;
|
||||
|
||||
const pipelineOptions: RetrievalPipelineOptions = {
|
||||
nFinal,
|
||||
nRetrieve,
|
||||
|
|
@ -70,6 +76,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
ide: extras.ide,
|
||||
input: extras.fullInput,
|
||||
};
|
||||
|
||||
const pipeline = new pipelineType(pipelineOptions);
|
||||
const results = await pipeline.run();
|
||||
|
||||
|
|
@ -81,7 +88,9 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
|
||||
return [
|
||||
...results.map((r) => {
|
||||
const name = `${getRelativePath(r.filepath, workspaceDirs)} (${r.startLine}-${r.endLine})`;
|
||||
const name = `${getRelativePath(r.filepath, workspaceDirs)} (${
|
||||
r.startLine
|
||||
}-${r.endLine})`;
|
||||
const description = `${r.filepath} (${r.startLine}-${r.endLine})`;
|
||||
return {
|
||||
name,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Chunk } from "../..";
|
||||
import { deduplicateArray } from "../../util";
|
||||
import { Chunk } from "../../index.js";
|
||||
import { deduplicateArray } from "../../util/index.js";
|
||||
|
||||
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
|
||||
return deduplicateArray(chunks, (a, b) => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { constants, getTimestamp } from "../../deploy/constants";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { constants, getTimestamp } from "../../deploy/constants.js";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
|
||||
export async function getHeaders() {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import os from "node:os";
|
||||
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider";
|
||||
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider";
|
||||
import ContinueProxyAnalyticsProvider from "./analytics/ContinueProxyAnalyticsProvider.js";
|
||||
import { IAnalyticsProvider } from "./analytics/IAnalyticsProvider.js";
|
||||
import LogStashAnalyticsProvider from "./analytics/LogStashAnalyticsProvider.js";
|
||||
import PostHogAnalyticsProvider from "./analytics/PostHogAnalyticsProvider.js";
|
||||
|
||||
function createAnalyticsProvider(
|
||||
config: Analytics,
|
||||
|
|
@ -10,6 +12,10 @@ function createAnalyticsProvider(
|
|||
switch (config.provider) {
|
||||
case "posthog":
|
||||
return new PostHogAnalyticsProvider();
|
||||
case "logstash":
|
||||
return new LogStashAnalyticsProvider();
|
||||
case "continue-proxy":
|
||||
return new ContinueProxyAnalyticsProvider();
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,32 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import fetch from "node-fetch";
|
||||
import { CONTROL_PLANE_URL } from "../client.js";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class ContinueProxyAnalyticsProvider
|
||||
implements IAnalyticsProvider
|
||||
{
|
||||
uniqueId?: string;
|
||||
addOnId?: string;
|
||||
|
||||
async capture(
|
||||
event: string,
|
||||
properties: { [key: string]: any },
|
||||
): Promise<void> {
|
||||
fetch(new URL(`/proxy/analytics/${this.addOnId}`, CONTROL_PLANE_URL), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
event,
|
||||
properties,
|
||||
uniqueId: this.uniqueId,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
this.uniqueId = uniqueId;
|
||||
this.addOnId = config.url?.split("/").slice(-1)[0];
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {}
|
||||
}
|
||||
|
|
@ -1,17 +0,0 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider";
|
||||
|
||||
export default class ElasticAnalyticsProvider implements IAnalyticsProvider {
|
||||
async capture(
|
||||
event: string,
|
||||
properties: { [key: string]: any },
|
||||
): Promise<void> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {}
|
||||
}
|
||||
42
core/control-plane/analytics/LogStashAnalyticsProvider.ts
Normal file
42
core/control-plane/analytics/LogStashAnalyticsProvider.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import net from "node:net";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class LogStashAnalyticsProvider implements IAnalyticsProvider {
|
||||
private host?: string;
|
||||
private port?: number;
|
||||
private uniqueId?: string;
|
||||
|
||||
async capture(
|
||||
event: string,
|
||||
properties: { [key: string]: any },
|
||||
): Promise<void> {
|
||||
if (this.host === undefined || this.port === undefined) {
|
||||
console.warn("LogStashAnalyticsProvider not set up yet.");
|
||||
}
|
||||
|
||||
const payload = {
|
||||
event,
|
||||
properties,
|
||||
uniqueId: this.uniqueId,
|
||||
};
|
||||
const client = new net.Socket();
|
||||
|
||||
client.connect(this.port!, this.host!, () => {
|
||||
client.write(JSON.stringify(payload));
|
||||
client.end();
|
||||
});
|
||||
}
|
||||
|
||||
async setup(config: Analytics, uniqueId: string): Promise<void> {
|
||||
if (!config.url) {
|
||||
throw new Error("Missing url in analytics config");
|
||||
}
|
||||
const url = new URL(config.url);
|
||||
this.host = url.hostname;
|
||||
this.port = parseInt(url.port);
|
||||
this.uniqueId = uniqueId;
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {}
|
||||
}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { Analytics } from "@continuedev/config-types";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider";
|
||||
import { IAnalyticsProvider } from "./IAnalyticsProvider.js";
|
||||
|
||||
export default class PostHogAnalyticsProvider implements IAnalyticsProvider {
|
||||
client?: any;
|
||||
|
|
|
|||
20
core/control-plane/auth/index.ts
Normal file
20
core/control-plane/auth/index.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
const CLIENT_ID = "client_01J0FW6XN8N2XJAECF7NE0Y65J";
|
||||
// const CLIENT_ID = "client_01J0FW6XCPMJMQ3CG51RB4HBZQ"; // Staging
|
||||
|
||||
export async function getAuthUrlForTokenPage(): Promise<string> {
|
||||
const url = new URL("https://api.workos.com/user_management/authorize");
|
||||
const params = {
|
||||
response_type: "code",
|
||||
client_id: CLIENT_ID,
|
||||
redirect_uri: "https://app.continue.dev/tokens/callback",
|
||||
// redirect_uri: "http://localhost:3000/tokens/callback",
|
||||
state: uuidv4(),
|
||||
provider: "authkit",
|
||||
};
|
||||
Object.keys(params).forEach((key) =>
|
||||
url.searchParams.append(key, params[key as keyof typeof params]),
|
||||
);
|
||||
return url.toString();
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { ConfigJson } from "@continuedev/config-types";
|
||||
import fetch, { RequestInit, Response } from "node-fetch";
|
||||
import { ModelDescription } from "..";
|
||||
import { ModelDescription } from "../index.js";
|
||||
|
||||
export interface ControlPlaneSessionInfo {
|
||||
accessToken: string;
|
||||
|
|
@ -18,9 +18,10 @@ export interface ControlPlaneWorkspace {
|
|||
|
||||
export interface ControlPlaneModelDescription extends ModelDescription {}
|
||||
|
||||
// export const CONTROL_PLANE_URL = "http://localhost:3001";
|
||||
export const CONTROL_PLANE_URL =
|
||||
"https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
|
||||
process.env.CONTROL_PLANE_ENV === "local"
|
||||
? "http://localhost:3001"
|
||||
: "https://control-plane-api-service-i3dqylpbqa-uc.a.run.app";
|
||||
|
||||
export class ControlPlaneClient {
|
||||
private static URL = CONTROL_PLANE_URL;
|
||||
|
|
@ -72,10 +73,14 @@ export class ControlPlaneClient {
|
|||
return [];
|
||||
}
|
||||
|
||||
const resp = await this.request(`/workspaces`, {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
try {
|
||||
const resp = await this.request(`/workspaces`, {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as any;
|
||||
} catch (e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getSettingsForWorkspace(workspaceId: string): Promise<ConfigJson> {
|
||||
|
|
|
|||
241
core/core.ts
241
core/core.ts
|
|
@ -1,37 +1,32 @@
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
import type {
|
||||
ContextItemId,
|
||||
EmbeddingsProvider,
|
||||
IDE,
|
||||
IndexingProgressUpdate,
|
||||
SiteIndexingConfig,
|
||||
} from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider.js";
|
||||
import { ConfigHandler } from "./config/ConfigHandler.js";
|
||||
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
|
||||
import { CompletionProvider } from "./autocomplete/completionProvider";
|
||||
import { ConfigHandler } from "./config/ConfigHandler";
|
||||
import {
|
||||
setupApiKeysMode,
|
||||
setupFreeTrialMode,
|
||||
setupLocalAfterFreeTrial,
|
||||
setupLocalMode,
|
||||
} from "./config/onboarding.js";
|
||||
import { createNewPromptFile } from "./config/promptFile.js";
|
||||
import { addModel, addOpenAIKey, deleteModel } from "./config/util.js";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client.js";
|
||||
import { ControlPlaneClient } from "./control-plane/client.js";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer.js";
|
||||
import { DocsService } from "./indexing/docs/DocsService.js";
|
||||
import TransformersJsEmbeddingsProvider from "./indexing/embeddings/TransformersJsEmbeddingsProvider.js";
|
||||
import Ollama from "./llm/llms/Ollama.js";
|
||||
} from "./config/onboarding";
|
||||
import { createNewPromptFile } from "./config/promptFile";
|
||||
import { addModel, addOpenAIKey, deleteModel } from "./config/util";
|
||||
import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { ControlPlaneClient } from "./control-plane/client";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import DocsService, { docsServiceSingleton } from "./indexing/docs/DocsService";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { GlobalContext } from "./util/GlobalContext.js";
|
||||
import { logDevData } from "./util/devdata.js";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite.js";
|
||||
import { fetchwithRequestOptions } from "./util/fetchWithOptions.js";
|
||||
import historyManager from "./util/history.js";
|
||||
import { GlobalContext } from "./util/GlobalContext";
|
||||
import { logDevData } from "./util/devdata";
|
||||
import { DevDataSqliteDb } from "./util/devdataSqlite";
|
||||
import { fetchwithRequestOptions } from "./util/fetchWithOptions";
|
||||
import historyManager from "./util/history";
|
||||
import type { IMessenger, Message } from "./util/messenger";
|
||||
import { editConfigJson } from "./util/paths.js";
|
||||
import { Telemetry } from "./util/posthog.js";
|
||||
import { streamDiffLines } from "./util/verticalEdit.js";
|
||||
import { editConfigJson } from "./util/paths";
|
||||
import { Telemetry } from "./util/posthog";
|
||||
import { streamDiffLines } from "./util/verticalEdit";
|
||||
|
||||
export class Core {
|
||||
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
|
||||
|
|
@ -41,8 +36,9 @@ export class Core {
|
|||
continueServerClientPromise: Promise<ContinueServerClient>;
|
||||
indexingState: IndexingProgressUpdate;
|
||||
controlPlaneClient: ControlPlaneClient;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
private docsService = DocsService.getInstance();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
);
|
||||
|
|
@ -97,20 +93,16 @@ export class Core {
|
|||
this.controlPlaneClient,
|
||||
);
|
||||
|
||||
this.docsService = DocsService.createSingleton(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.messenger,
|
||||
);
|
||||
|
||||
this.configHandler.onConfigUpdate(
|
||||
(() => this.messenger.send("configUpdate", undefined)).bind(this),
|
||||
);
|
||||
|
||||
this.configHandler.onConfigUpdate(async ({ embeddingsProvider }) => {
|
||||
if (
|
||||
await this.shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
embeddingsProvider.id,
|
||||
)
|
||||
) {
|
||||
await this.reindexDocsOnNewEmbeddingsProvider(embeddingsProvider);
|
||||
}
|
||||
});
|
||||
|
||||
this.configHandler.onDidChangeAvailableProfiles((profiles) =>
|
||||
this.messenger.send("didChangeAvailableProfiles", { profiles }),
|
||||
);
|
||||
|
|
@ -143,16 +135,19 @@ export class Core {
|
|||
);
|
||||
|
||||
// Index on initialization
|
||||
this.ide
|
||||
.getWorkspaceDirs()
|
||||
.then((dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
return;
|
||||
}
|
||||
this.ide.getWorkspaceDirs().then(async (dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
await this.messenger.request("indexProgress", {
|
||||
progress: 100,
|
||||
desc: "Initial Indexing Skipped",
|
||||
status: "paused",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
this.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
});
|
||||
|
||||
const getLlm = async () => {
|
||||
|
|
@ -205,12 +200,15 @@ export class Core {
|
|||
on("history/list", (msg) => {
|
||||
return historyManager.list(msg.data);
|
||||
});
|
||||
|
||||
on("history/delete", (msg) => {
|
||||
historyManager.delete(msg.data.id);
|
||||
});
|
||||
|
||||
on("history/load", (msg) => {
|
||||
return historyManager.load(msg.data.id);
|
||||
});
|
||||
|
||||
on("history/save", (msg) => {
|
||||
historyManager.save(msg.data);
|
||||
});
|
||||
|
|
@ -226,14 +224,17 @@ export class Core {
|
|||
addModel(model);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/addOpenAiKey", (msg) => {
|
||||
addOpenAIKey(msg.data);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/deleteModel", (msg) => {
|
||||
deleteModel(msg.data.title);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/newPromptFile", async (msg) => {
|
||||
createNewPromptFile(
|
||||
this.ide,
|
||||
|
|
@ -241,10 +242,12 @@ export class Core {
|
|||
);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
|
||||
on("config/reload", (msg) => {
|
||||
this.configHandler.reloadConfig();
|
||||
return this.configHandler.getSerializedConfig();
|
||||
});
|
||||
|
||||
on("config/ideSettingsUpdate", (msg) => {
|
||||
this.configHandler.updateIdeSettings(msg.data);
|
||||
});
|
||||
|
|
@ -254,47 +257,46 @@ export class Core {
|
|||
|
||||
// Context providers
|
||||
on("context/addDocs", async (msg) => {
|
||||
await this.getEmbeddingsProviderAndIndexDoc(msg.data);
|
||||
let hasFailed = false;
|
||||
|
||||
this.ide.infoPopup(`Successfully indexed ${msg.data.title}`);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
for await (const result of this.docsService.indexAndAdd(msg.data)) {
|
||||
if (result.status === "failed") {
|
||||
hasFailed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasFailed) {
|
||||
this.ide.infoPopup(`Failed to index ${msg.data.startUrl}`);
|
||||
} else {
|
||||
this.ide.infoPopup(`Successfully indexed ${msg.data.startUrl}`);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
});
|
||||
|
||||
on("context/removeDocs", async (msg) => {
|
||||
const baseUrl = msg.data.baseUrl;
|
||||
await this.docsService.delete(baseUrl);
|
||||
await this.docsService.delete(msg.data.startUrl);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
});
|
||||
|
||||
on("context/indexDocs", async (msg) => {
|
||||
const config = await this.config();
|
||||
const provider: any = config.contextProviders?.find(
|
||||
(provider) => provider.description.title === "docs",
|
||||
);
|
||||
|
||||
if (!provider) {
|
||||
this.ide.infoPopup("No docs in configuration");
|
||||
return;
|
||||
}
|
||||
|
||||
const siteIndexingOptions: SiteIndexingConfig[] = ((mProvider) =>
|
||||
mProvider?.options?.sites || [])({ ...provider });
|
||||
|
||||
for (const site of siteIndexingOptions) {
|
||||
await this.getEmbeddingsProviderAndIndexDoc(site, msg.data.reIndex);
|
||||
}
|
||||
|
||||
this.ide.infoPopup("Docs indexing completed");
|
||||
await this.docsService.indexAllDocs(msg.data.reIndex);
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
});
|
||||
|
||||
on("context/loadSubmenuItems", async (msg) => {
|
||||
const config = await this.config();
|
||||
const items = await config.contextProviders
|
||||
?.find((provider) => provider.description.title === msg.data.title)
|
||||
?.loadSubmenuItems({
|
||||
config,
|
||||
ide: this.ide,
|
||||
fetch: (url, init) =>
|
||||
fetchwithRequestOptions(url, init, config.requestOptions),
|
||||
});
|
||||
return items || [];
|
||||
});
|
||||
|
||||
on("context/getContextItems", async (msg) => {
|
||||
const { name, query, fullInput, selectedCode } = msg.data;
|
||||
const config = await this.config();
|
||||
|
|
@ -311,7 +313,9 @@ export class Core {
|
|||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
|
||||
const items = await provider.getContextItems(query, {
|
||||
config,
|
||||
llm,
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
fullInput,
|
||||
|
|
@ -647,10 +651,19 @@ export class Core {
|
|||
|
||||
on("didChangeSelectedProfile", (msg) => {
|
||||
this.configHandler.setSelectedProfile(msg.data.id);
|
||||
this.configHandler.reloadConfig();
|
||||
});
|
||||
on("didChangeControlPlaneSessionInfo", async (msg) => {
|
||||
this.configHandler.updateControlPlaneSessionInfo(msg.data.sessionInfo);
|
||||
});
|
||||
on("auth/getAuthUrl", async (msg) => {
|
||||
const url = await getAuthUrlForTokenPage();
|
||||
return { url };
|
||||
});
|
||||
|
||||
on("didChangeActiveTextEditor", ({ data: { filepath } }) => {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
});
|
||||
}
|
||||
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
|
|
@ -670,94 +683,4 @@ export class Core {
|
|||
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
|
||||
private async shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
curEmbeddingsProviderId: EmbeddingsProvider["id"],
|
||||
): Promise<boolean> {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
const isJetBrainsAndPreIndexedDocsProvider =
|
||||
this.docsService.isJetBrainsAndPreIndexedDocsProvider(
|
||||
ideInfo,
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
this.ide.errorPopup(
|
||||
`${DocsService.preIndexedDocsEmbeddingsProvider.id} cannot be used as an embeddings provider with JetBrains. Please select a different embeddings provider.`,
|
||||
);
|
||||
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastEmbeddingsProviderId = this.globalContext.get(
|
||||
"curEmbeddingsProviderId",
|
||||
);
|
||||
|
||||
if (!lastEmbeddingsProviderId) {
|
||||
// If it's the first time we're setting the `curEmbeddingsProviderId`
|
||||
// global state, we don't need to reindex docs
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return lastEmbeddingsProviderId !== curEmbeddingsProviderId;
|
||||
}
|
||||
|
||||
private async getEmbeddingsProviderAndIndexDoc(
|
||||
site: SiteIndexingConfig,
|
||||
reIndex: boolean = false,
|
||||
): Promise<void> {
|
||||
const config = await this.config();
|
||||
const { embeddingsProvider } = config;
|
||||
|
||||
for await (const update of this.docsService.indexAndAdd(
|
||||
site,
|
||||
embeddingsProvider,
|
||||
reIndex,
|
||||
)) {
|
||||
// Temporary disabled posting progress updates to the UI due to
|
||||
// possible collision with code indexing progress updates.
|
||||
// this.messenger.request("indexProgress", update);
|
||||
// this.indexingState = update;
|
||||
}
|
||||
}
|
||||
|
||||
private async reindexDocsOnNewEmbeddingsProvider(
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
) {
|
||||
const docs = await this.docsService.list();
|
||||
|
||||
if (docs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.ide.infoPopup("Reindexing docs with new embeddings provider");
|
||||
|
||||
for (const { title, baseUrl } of docs) {
|
||||
await this.docsService.delete(baseUrl);
|
||||
|
||||
const generator = this.docsService.indexAndAdd(
|
||||
{ title, startUrl: baseUrl, rootUrl: baseUrl },
|
||||
embeddingsProvider,
|
||||
);
|
||||
|
||||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
// Important that this only is invoked after we have successfully
|
||||
// cleared and reindex the docs so that the table cannot end up in an
|
||||
// invalid state.
|
||||
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
|
||||
|
||||
this.ide.infoPopup("Completed reindexing of all docs");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { distance } from "fastest-levenshtein";
|
||||
import { ChatMessage } from "../index.js";
|
||||
import { stripImages } from "../llm/countTokens.js";
|
||||
import { stripImages } from "../llm/images.js";
|
||||
|
||||
export type LineStream = AsyncGenerator<string>;
|
||||
|
||||
|
|
|
|||
54
core/index.d.ts
vendored
54
core/index.d.ts
vendored
|
|
@ -127,6 +127,7 @@ export interface ContextProviderDescription {
|
|||
export type FetchFunction = (url: string | URL, init?: any) => Promise<any>;
|
||||
|
||||
export interface ContextProviderExtras {
|
||||
config: ContinueConfig;
|
||||
fullInput: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
reranker: Reranker | undefined;
|
||||
|
|
@ -137,6 +138,7 @@ export interface ContextProviderExtras {
|
|||
}
|
||||
|
||||
export interface LoadSubmenuItemsArgs {
|
||||
config: ContinueConfig;
|
||||
ide: IDE;
|
||||
fetch: FetchFunction;
|
||||
}
|
||||
|
|
@ -160,21 +162,21 @@ export interface ContextSubmenuItem {
|
|||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
iconUrl?: string;
|
||||
icon?: string;
|
||||
metadata?: any;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl: string;
|
||||
title: string;
|
||||
startUrl: string;
|
||||
rootUrl?: string;
|
||||
maxDepth?: number;
|
||||
faviconUrl?: string;
|
||||
}
|
||||
|
||||
export interface SiteIndexingConfig {
|
||||
startUrl: string;
|
||||
rootUrl: string;
|
||||
rootUrl?: string;
|
||||
title: string;
|
||||
maxDepth?: number;
|
||||
}
|
||||
|
|
@ -268,6 +270,7 @@ export interface ContextItem {
|
|||
description: string;
|
||||
editing?: boolean;
|
||||
editable?: boolean;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface ContextItemWithId {
|
||||
|
|
@ -277,6 +280,7 @@ export interface ContextItemWithId {
|
|||
id: ContextItemId;
|
||||
editing?: boolean;
|
||||
editable?: boolean;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface InputModifiers {
|
||||
|
|
@ -338,6 +342,15 @@ export interface LLMOptions {
|
|||
// GCP Options
|
||||
region?: string;
|
||||
projectId?: string;
|
||||
capabilities?: ModelCapability;
|
||||
|
||||
// WatsonX options
|
||||
watsonxUrl?: string;
|
||||
watsonxApiKey?: string;
|
||||
watsonxZenApiKeyBase64?:string// Required if using watsonx software with ZenApiKey auth
|
||||
watsonxUsername?:string;
|
||||
watsonxPassword?:string;
|
||||
watsonxProjectId?: string;
|
||||
}
|
||||
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
|
||||
T,
|
||||
|
|
@ -422,8 +435,8 @@ export interface IdeSettings {
|
|||
remoteConfigSyncPeriod: number;
|
||||
userToken: string;
|
||||
enableControlServerBeta: boolean;
|
||||
pauseCodebaseIndexOnStart: boolean
|
||||
enableDebugLogs: boolean
|
||||
pauseCodebaseIndexOnStart: boolean;
|
||||
enableDebugLogs: boolean;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
|
|
@ -589,7 +602,8 @@ type ModelProvider =
|
|||
| "deepseek"
|
||||
| "azure"
|
||||
| "openai-aiohttp"
|
||||
| "msty";
|
||||
| "msty"
|
||||
| "watsonx";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
|
|
@ -717,6 +731,10 @@ interface BaseCompletionOptions {
|
|||
stream?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelCapability {
|
||||
uploadImage?: boolean;
|
||||
}
|
||||
|
||||
export interface ModelDescription {
|
||||
title: string;
|
||||
provider: ModelProvider;
|
||||
|
|
@ -729,6 +747,7 @@ export interface ModelDescription {
|
|||
systemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
promptTemplates?: { [key: string]: string };
|
||||
capabilities?: ModelCapability;
|
||||
}
|
||||
|
||||
export type EmbeddingsProviderName =
|
||||
|
|
@ -738,7 +757,9 @@ export type EmbeddingsProviderName =
|
|||
| "openai"
|
||||
| "cohere"
|
||||
| "free-trial"
|
||||
| "gemini";
|
||||
| "gemini"
|
||||
| "continue-proxy"
|
||||
| "deepinfra";
|
||||
|
||||
export interface EmbedOptions {
|
||||
apiBase?: string;
|
||||
|
|
@ -757,6 +778,7 @@ export interface EmbeddingsProviderDescription extends EmbedOptions {
|
|||
|
||||
export interface EmbeddingsProvider {
|
||||
id: string;
|
||||
providerName: EmbeddingsProviderName;
|
||||
maxChunkSize: number;
|
||||
embed(chunks: string[]): Promise<number[][]>;
|
||||
}
|
||||
|
|
@ -766,7 +788,8 @@ export type RerankerName =
|
|||
| "voyage"
|
||||
| "llm"
|
||||
| "free-trial"
|
||||
| "huggingface-tei";
|
||||
| "huggingface-tei"
|
||||
| "continue-proxy";
|
||||
|
||||
export interface RerankerDescription {
|
||||
name: RerankerName;
|
||||
|
|
@ -858,6 +881,12 @@ interface ExperimentalConfig {
|
|||
quickActions?: QuickActionConfig[];
|
||||
}
|
||||
|
||||
interface AnalyticsConfig {
|
||||
type: string;
|
||||
url?: string;
|
||||
clientKey?: string;
|
||||
}
|
||||
|
||||
// config.json
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
|
|
@ -878,6 +907,8 @@ export interface SerializedContinueConfig {
|
|||
ui?: ContinueUIConfig;
|
||||
reranker?: RerankerDescription;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
}
|
||||
|
||||
export type ConfigMergeType = "merge" | "overwrite";
|
||||
|
|
@ -928,6 +959,8 @@ export interface Config {
|
|||
reranker?: RerankerDescription | Reranker;
|
||||
/** Experimental configuration */
|
||||
experimental?: ExperimentalConfig;
|
||||
/** Analytics configuration */
|
||||
analytics?: AnalyticsConfig;
|
||||
}
|
||||
|
||||
// in the actual Continue source code
|
||||
|
|
@ -948,6 +981,8 @@ export interface ContinueConfig {
|
|||
ui?: ContinueUIConfig;
|
||||
reranker?: Reranker;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
docs?: SiteIndexingConfig[];
|
||||
}
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
|
|
@ -965,4 +1000,5 @@ export interface BrowserSerializedContinueConfig {
|
|||
ui?: ContinueUIConfig;
|
||||
reranker?: RerankerDescription;
|
||||
experimental?: ExperimentalConfig;
|
||||
analytics?: AnalyticsConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,6 +50,40 @@ export class CodebaseIndexer {
|
|||
return indexes;
|
||||
}
|
||||
|
||||
public async refreshFile(file: string): Promise<void> {
|
||||
if (this.pauseToken.paused) {
|
||||
// NOTE: by returning here, there is a chance that while paused a file is modified and
|
||||
// then after unpausing the file is not reindexed
|
||||
return;
|
||||
}
|
||||
const workspaceDir = await this.getWorkspaceDir(file);
|
||||
if (!workspaceDir) {
|
||||
return;
|
||||
}
|
||||
const branch = await this.ide.getBranch(workspaceDir);
|
||||
const repoName = await this.ide.getRepoName(workspaceDir);
|
||||
const stats = await this.ide.getLastModified([file]);
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
for (const codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory: workspaceDir,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
const [results, lastUpdated, markComplete] = await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath),
|
||||
repoName,
|
||||
);
|
||||
for await (const _ of codebaseIndex.update(tag, results, markComplete, repoName)) {
|
||||
lastUpdated.forEach((lastUpdated, path) => {
|
||||
markComplete([lastUpdated], IndexResultType.UpdateLastUpdated);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[],
|
||||
abortSignal: AbortSignal,
|
||||
|
|
@ -206,4 +240,14 @@ export class CodebaseIndexer {
|
|||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async getWorkspaceDir(filepath: string): Promise<string | undefined> {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
if (filepath.startsWith(workspaceDir)) {
|
||||
return workspaceDir;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,9 +62,17 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
"lancedb_sqlite_artifact_id_column",
|
||||
async () => {
|
||||
try {
|
||||
await db.exec(
|
||||
"ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'",
|
||||
const pragma = await db.all("PRAGMA table_info(lance_db_cache)");
|
||||
|
||||
const hasArtifactIdCol = pragma.some(
|
||||
(pragma) => pragma.name === "artifact_id",
|
||||
);
|
||||
|
||||
if (!hasArtifactIdCol) {
|
||||
await db.exec(
|
||||
"ALTER TABLE lance_db_cache ADD COLUMN artifact_id TEXT NOT NULL DEFAULT 'UNDEFINED'",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
resolve(undefined);
|
||||
}
|
||||
|
|
@ -96,12 +104,12 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
|
||||
let hasEmptyChunks = false;
|
||||
|
||||
for await (const chunk of chunkDocument(
|
||||
items[i].path,
|
||||
content,
|
||||
this.embeddingsProvider.maxChunkSize,
|
||||
items[i].cacheKey,
|
||||
)) {
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath: items[i].path,
|
||||
contents: content,
|
||||
maxChunkSize: this.embeddingsProvider.maxChunkSize,
|
||||
digest: items[i].cacheKey,
|
||||
})) {
|
||||
if (chunk.content.length == 0) {
|
||||
hasEmptyChunks = true;
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ The indexing process does the following:
|
|||
|
||||
## Existing `CodebaseIndex`es
|
||||
|
||||
All indexes must be returned by `getIndexesToBuild` in [`indexCodebase.ts`](./indexCodebase.ts) if they are to be used.
|
||||
All indexes must be returned by `getIndexesToBuild` in [`CodebaseIndexer.ts`](./CodebaseIndexer.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
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
constructor(
|
||||
private readonly readFile: (filepath: string) => Promise<string>,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
private readonly maxChunkSize: number
|
||||
private readonly maxChunkSize: number,
|
||||
) {
|
||||
this.readFile = readFile;
|
||||
}
|
||||
|
|
@ -105,31 +105,15 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
const item = results.compute[i];
|
||||
|
||||
// Insert chunks
|
||||
for await (const chunk of chunkDocument(
|
||||
item.path,
|
||||
contents[i],
|
||||
this.maxChunkSize,
|
||||
item.cacheKey,
|
||||
)) {
|
||||
handleChunk(chunk);
|
||||
}
|
||||
|
||||
accumulatedProgress =
|
||||
(i / results.compute.length) * (1 - progressReservedForTagging);
|
||||
yield {
|
||||
progress: accumulatedProgress,
|
||||
desc: `Chunking ${getBasename(item.path)}`,
|
||||
status: "indexing",
|
||||
};
|
||||
markComplete([item], IndexResultType.Compute);
|
||||
// Insert chunks
|
||||
for await (const chunk of chunkDocument(
|
||||
item.path,
|
||||
contents[i],
|
||||
this.maxChunkSize,
|
||||
item.cacheKey,
|
||||
)) {
|
||||
handleChunk(chunk);
|
||||
if (contents.length) {
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath: item.path,
|
||||
contents: contents[i],
|
||||
maxChunkSize: this.maxChunkSize,
|
||||
digest: item.cacheKey,
|
||||
})) {
|
||||
await handleChunk(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
accumulatedProgress =
|
||||
|
|
@ -150,13 +134,15 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
|
|||
const item = results.addTag[i];
|
||||
|
||||
// Insert chunks
|
||||
for await (const chunk of chunkDocument(
|
||||
item.path,
|
||||
addContents[i],
|
||||
this.maxChunkSize,
|
||||
item.cacheKey,
|
||||
)) {
|
||||
handleChunk(chunk);
|
||||
if (contents.length) {
|
||||
for await (const chunk of chunkDocument({
|
||||
filepath: item.path,
|
||||
contents: contents[i],
|
||||
maxChunkSize: this.maxChunkSize,
|
||||
digest: item.cacheKey,
|
||||
})) {
|
||||
handleChunk(chunk);
|
||||
}
|
||||
}
|
||||
|
||||
markComplete([item], IndexResultType.AddTag);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import { ChunkWithoutID } from "../../index.js";
|
||||
import { countTokens } from "../../llm/countTokens.js";
|
||||
import { countTokensAsync } from "../../llm/countTokens.js";
|
||||
|
||||
export function* basicChunker(
|
||||
export async function* basicChunker(
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
): Generator<ChunkWithoutID> {
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (contents.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -14,18 +14,24 @@ export function* basicChunker(
|
|||
let startLine = 0;
|
||||
let currLine = 0;
|
||||
|
||||
for (const line of contents.split("\n")) {
|
||||
const lineTokens = countTokens(line);
|
||||
if (chunkTokens + lineTokens > maxChunkSize - 5) {
|
||||
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
|
||||
return {
|
||||
line: l,
|
||||
tokenCount: await countTokensAsync(l),
|
||||
};
|
||||
}));
|
||||
|
||||
for (const lt of lineTokens) {
|
||||
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
|
||||
yield { content: chunkContent, startLine, endLine: currLine - 1 };
|
||||
chunkContent = "";
|
||||
chunkTokens = 0;
|
||||
startLine = currLine;
|
||||
}
|
||||
|
||||
if (lineTokens < maxChunkSize) {
|
||||
chunkContent += `${line}\n`;
|
||||
chunkTokens += lineTokens + 1;
|
||||
if (lt.tokenCount < maxChunkSize) {
|
||||
chunkContent += `${lt.line}\n`;
|
||||
chunkTokens += lt.tokenCount + 1;
|
||||
}
|
||||
|
||||
currLine++;
|
||||
|
|
|
|||
|
|
@ -1,9 +1,16 @@
|
|||
import { Chunk, ChunkWithoutID } from "../../index.js";
|
||||
import { countTokens } from "../../llm/countTokens.js";
|
||||
import { countTokens, countTokensAsync } from "../../llm/countTokens.js";
|
||||
import { supportedLanguages } from "../../util/treeSitter.js";
|
||||
import { basicChunker } from "./basic.js";
|
||||
import { codeChunker } from "./code.js";
|
||||
|
||||
export type ChunkDocumentParam = {
|
||||
filepath: string;
|
||||
contents: string;
|
||||
maxChunkSize: number;
|
||||
digest: string;
|
||||
};
|
||||
|
||||
async function* chunkDocumentWithoutId(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
|
|
@ -30,32 +37,41 @@ async function* chunkDocumentWithoutId(
|
|||
yield* basicChunker(contents, maxChunkSize);
|
||||
}
|
||||
|
||||
export async function* chunkDocument(
|
||||
filepath: string,
|
||||
contents: string,
|
||||
maxChunkSize: number,
|
||||
digest: string,
|
||||
): AsyncGenerator<Chunk> {
|
||||
export async function* chunkDocument({
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
digest,
|
||||
}: ChunkDocumentParam): AsyncGenerator<Chunk> {
|
||||
let index = 0;
|
||||
const chunkPromises: Promise<Chunk | undefined>[] = [];
|
||||
for await (const chunkWithoutId of chunkDocumentWithoutId(
|
||||
filepath,
|
||||
contents,
|
||||
maxChunkSize,
|
||||
)) {
|
||||
if (countTokens(chunkWithoutId.content) > maxChunkSize) {
|
||||
console.warn(
|
||||
`Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
chunkPromises.push(new Promise(async (resolve) => {
|
||||
if (await countTokensAsync(chunkWithoutId.content) > maxChunkSize) {
|
||||
console.warn(
|
||||
`Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
filepath,
|
||||
countTokens(chunkWithoutId.content),
|
||||
);
|
||||
return resolve(undefined);
|
||||
}
|
||||
resolve({
|
||||
...chunkWithoutId,
|
||||
digest,
|
||||
index,
|
||||
filepath,
|
||||
countTokens(chunkWithoutId.content),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
yield {
|
||||
...chunkWithoutId,
|
||||
digest,
|
||||
index,
|
||||
filepath,
|
||||
};
|
||||
});
|
||||
}));
|
||||
index++;
|
||||
}
|
||||
for await (const chunk of chunkPromises) {
|
||||
if (!chunk) {
|
||||
continue;
|
||||
}
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { SyntaxNode } from "web-tree-sitter";
|
||||
import { ChunkWithoutID } from "../../index.js";
|
||||
import { countTokens } from "../../llm/countTokens.js";
|
||||
import { countTokensAsync } from "../../llm/countTokens.js";
|
||||
import { getParserForFile } from "../../util/treeSitter.js";
|
||||
|
||||
function collapsedReplacement(node: SyntaxNode): string {
|
||||
|
|
@ -22,14 +22,14 @@ function firstChild(
|
|||
return node.children.find((child) => child.type === grammarName) || null;
|
||||
}
|
||||
|
||||
function collapseChildren(
|
||||
async function collapseChildren(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
blockTypes: string[],
|
||||
collapseTypes: string[],
|
||||
collapseBlockTypes: string[],
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
): Promise<string> {
|
||||
code = code.slice(0, node.endIndex);
|
||||
const block = firstChild(node, blockTypes);
|
||||
const collapsedChildren = [];
|
||||
|
|
@ -58,7 +58,7 @@ function collapseChildren(
|
|||
code = code.slice(node.startIndex);
|
||||
let removedChild = false;
|
||||
while (
|
||||
countTokens(code.trim()) > maxChunkSize &&
|
||||
(await countTokensAsync(code.trim())) > maxChunkSize &&
|
||||
collapsedChildren.length > 0
|
||||
) {
|
||||
removedChild = true;
|
||||
|
|
@ -106,11 +106,11 @@ export const FUNCTION_DECLARATION_NODE_TYPEs = [
|
|||
"method_declaration",
|
||||
];
|
||||
|
||||
function constructClassDefinitionChunk(
|
||||
async function constructClassDefinitionChunk(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
): Promise<string> {
|
||||
return collapseChildren(
|
||||
node,
|
||||
code,
|
||||
|
|
@ -121,11 +121,11 @@ function constructClassDefinitionChunk(
|
|||
);
|
||||
}
|
||||
|
||||
function constructFunctionDefinitionChunk(
|
||||
async function constructFunctionDefinitionChunk(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
): string {
|
||||
): Promise<string> {
|
||||
const bodyNode = node.children[node.children.length - 1];
|
||||
const funcText =
|
||||
code.slice(node.startIndex, bodyNode.startIndex) +
|
||||
|
|
@ -153,7 +153,7 @@ const collapsedNodeConstructors: {
|
|||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
) => string;
|
||||
) => Promise<string>;
|
||||
} = {
|
||||
// Classes, structs, etc
|
||||
class_definition: constructClassDefinitionChunk,
|
||||
|
|
@ -163,39 +163,61 @@ const collapsedNodeConstructors: {
|
|||
function_definition: constructFunctionDefinitionChunk,
|
||||
function_declaration: constructFunctionDefinitionChunk,
|
||||
function_item: constructFunctionDefinitionChunk,
|
||||
// Methods
|
||||
method_declaration: constructFunctionDefinitionChunk,
|
||||
// Properties
|
||||
};
|
||||
|
||||
function* getSmartCollapsedChunks(
|
||||
async function maybeYieldChunk(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
root = true,
|
||||
): Generator<ChunkWithoutID> {
|
||||
): Promise<ChunkWithoutID | undefined> {
|
||||
// Keep entire text if not over size
|
||||
if (
|
||||
(root || node.type in collapsedNodeConstructors) &&
|
||||
countTokens(node.text) < maxChunkSize
|
||||
) {
|
||||
yield {
|
||||
content: node.text,
|
||||
startLine: node.startPosition.row,
|
||||
endLine: node.endPosition.row,
|
||||
};
|
||||
if (root || node.type in collapsedNodeConstructors) {
|
||||
const tokenCount = await countTokensAsync(node.text);
|
||||
if (tokenCount < maxChunkSize) {
|
||||
return {
|
||||
content: node.text,
|
||||
startLine: node.startPosition.row,
|
||||
endLine: node.endPosition.row,
|
||||
};
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function* getSmartCollapsedChunks(
|
||||
node: SyntaxNode,
|
||||
code: string,
|
||||
maxChunkSize: number,
|
||||
root = true,
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
const chunk = await maybeYieldChunk(node, code, maxChunkSize, root);
|
||||
if (chunk) {
|
||||
yield chunk;
|
||||
return;
|
||||
}
|
||||
|
||||
// If a collapsed form is defined, use that
|
||||
if (node.type in collapsedNodeConstructors) {
|
||||
yield {
|
||||
content: collapsedNodeConstructors[node.type](node, code, maxChunkSize),
|
||||
content: await collapsedNodeConstructors[node.type](
|
||||
node,
|
||||
code,
|
||||
maxChunkSize,
|
||||
),
|
||||
startLine: node.startPosition.row,
|
||||
endLine: node.endPosition.row,
|
||||
};
|
||||
}
|
||||
|
||||
// Recurse (because even if collapsed version was shown, want to show the children in full somewhere)
|
||||
for (const child of node.children) {
|
||||
yield* getSmartCollapsedChunks(child, code, maxChunkSize, false);
|
||||
const generators = node.children.map((child) =>
|
||||
getSmartCollapsedChunks(child, code, maxChunkSize, false),
|
||||
);
|
||||
for (const generator of generators) {
|
||||
yield* generator;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ export async function* markdownChunker(
|
|||
if (hLevel > 4) {
|
||||
const header = findHeader(content.split("\n"));
|
||||
|
||||
for (const chunk of basicChunker(content, maxChunkSize)) {
|
||||
for await (const chunk of basicChunker(content, maxChunkSize)) {
|
||||
yield {
|
||||
...chunk,
|
||||
otherMetadata: {
|
||||
|
|
|
|||
|
|
@ -1,23 +1,41 @@
|
|||
import { open, type Database } from "sqlite";
|
||||
import sqlite3 from "sqlite3";
|
||||
import {
|
||||
Chunk,
|
||||
ContinueConfig,
|
||||
EmbeddingsProvider,
|
||||
IdeInfo,
|
||||
IDE,
|
||||
IndexingProgressUpdate,
|
||||
SiteIndexingConfig,
|
||||
} from "../../index.js";
|
||||
import { getDocsSqlitePath, getLanceDbPath } from "../../util/paths.js";
|
||||
import {
|
||||
editConfigJson,
|
||||
getDocsSqlitePath,
|
||||
getLanceDbPath,
|
||||
} from "../../util/paths.js";
|
||||
import { Article, chunkArticle, pageToArticle } from "./article.js";
|
||||
import { crawlPage } from "./crawl.js";
|
||||
import { downloadFromS3, SiteIndexingResults } from "./preIndexed.js";
|
||||
import {
|
||||
downloadFromS3,
|
||||
getS3Filename,
|
||||
S3Buckets,
|
||||
SiteIndexingResults,
|
||||
} from "./preIndexed.js";
|
||||
import preIndexedDocs from "./preIndexedDocs.js";
|
||||
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
|
||||
import { ConfigHandler } from "../../config/ConfigHandler.js";
|
||||
import lancedb, { Connection } from "vectordb";
|
||||
import { GlobalContext } from "../../util/GlobalContext.js";
|
||||
import DocsContextProvider from "../../context/providers/DocsContextProvider.js";
|
||||
import { open, type Database } from "sqlite";
|
||||
import sqlite3 from "sqlite3";
|
||||
import { Telemetry } from "../../util/posthog.js";
|
||||
import { runSqliteMigrations, runLanceMigrations } from "./migrations.js";
|
||||
import { IMessenger } from "../../util/messenger.js";
|
||||
import { ToCoreProtocol, FromCoreProtocol } from "../../protocol/index.js";
|
||||
|
||||
// Purposefully lowercase because lancedb converts
|
||||
interface LanceDbDocsRow {
|
||||
export interface LanceDbDocsRow {
|
||||
title: string;
|
||||
baseurl: string;
|
||||
starturl: string;
|
||||
// Chunk
|
||||
content: string;
|
||||
path: string;
|
||||
|
|
@ -27,200 +45,142 @@ interface LanceDbDocsRow {
|
|||
[key: string]: any;
|
||||
}
|
||||
|
||||
export class DocsService {
|
||||
private static instance: DocsService;
|
||||
private static DOCS_TABLE_NAME = "docs";
|
||||
public static preIndexedDocsEmbeddingsProvider =
|
||||
new TransformersJsEmbeddingsProvider();
|
||||
private _sqliteTable: Database | undefined;
|
||||
private docsIndexingQueue: Set<string> = new Set();
|
||||
export interface SqliteDocsRow {
|
||||
title: string;
|
||||
startUrl: string;
|
||||
favicon: string;
|
||||
}
|
||||
|
||||
public static getInstance(): DocsService {
|
||||
if (!DocsService.instance) {
|
||||
DocsService.instance = new DocsService();
|
||||
}
|
||||
export type AddParams = {
|
||||
siteIndexingConfig: SiteIndexingConfig;
|
||||
chunks: Chunk[];
|
||||
embeddings: number[][];
|
||||
favicon?: string;
|
||||
};
|
||||
|
||||
export default class DocsService {
|
||||
static lanceTableName = "docs";
|
||||
static sqlitebTableName = "docs";
|
||||
static preIndexedDocsEmbeddingsProvider =
|
||||
new TransformersJsEmbeddingsProvider();
|
||||
|
||||
private static instance?: DocsService;
|
||||
public isInitialized: Promise<void>;
|
||||
public isSyncing: boolean = false;
|
||||
|
||||
private docsIndexingQueue = new Set<string>();
|
||||
private globalContext = new GlobalContext();
|
||||
private lanceTableNamesSet = new Set<string>();
|
||||
|
||||
private config!: ContinueConfig;
|
||||
private sqliteDb?: Database;
|
||||
|
||||
// If we are instantiating a new DocsService from `getContextItems()`,
|
||||
// we have access to the direct config object.
|
||||
// When instantiating the DocsService from core, we have access
|
||||
// to a ConfigHandler instance.
|
||||
constructor(
|
||||
configOrHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
) {
|
||||
this.isInitialized = this.init(configOrHandler);
|
||||
}
|
||||
|
||||
static getSingleton() {
|
||||
return DocsService.instance;
|
||||
}
|
||||
|
||||
private async getSqliteTable() {
|
||||
if (!this._sqliteTable) {
|
||||
this._sqliteTable = await open({
|
||||
filename: getDocsSqlitePath(),
|
||||
driver: sqlite3.Database,
|
||||
});
|
||||
|
||||
this._sqliteTable.exec(`CREATE TABLE IF NOT EXISTS docs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title STRING NOT NULL,
|
||||
baseUrl STRING NOT NULL UNIQUE
|
||||
)`);
|
||||
}
|
||||
|
||||
return this._sqliteTable;
|
||||
}
|
||||
|
||||
private async getLanceDb() {
|
||||
const lancedb = await import("vectordb");
|
||||
const lance = await lancedb.connect(getLanceDbPath());
|
||||
return lance;
|
||||
}
|
||||
|
||||
async retrieve(
|
||||
baseUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number,
|
||||
embeddingsProviderId: string,
|
||||
nested = false,
|
||||
): Promise<Chunk[]> {
|
||||
const lance = await this.getLanceDb();
|
||||
const tableNames = await lance.tableNames();
|
||||
const preIndexedDoc = preIndexedDocs[baseUrl];
|
||||
const isPreIndexedDoc = !!preIndexedDoc;
|
||||
let shouldDownloadPreIndexedDoc =
|
||||
!tableNames.includes(DocsService.DOCS_TABLE_NAME) && isPreIndexedDoc;
|
||||
|
||||
const downloadAndRetrievePreIndexedDoc = async (
|
||||
preIndexedDoc: SiteIndexingConfig,
|
||||
) => {
|
||||
await this.downloadAndAddPreIndexedDocs(
|
||||
embeddingsProviderId,
|
||||
preIndexedDoc.title,
|
||||
);
|
||||
|
||||
return await this.retrieve(
|
||||
baseUrl,
|
||||
vector,
|
||||
nRetrieve,
|
||||
embeddingsProviderId,
|
||||
true,
|
||||
);
|
||||
};
|
||||
|
||||
if (shouldDownloadPreIndexedDoc) {
|
||||
return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!);
|
||||
}
|
||||
|
||||
const table = await lance.openTable(DocsService.DOCS_TABLE_NAME);
|
||||
|
||||
let docs: LanceDbDocsRow[] = await table
|
||||
.search(vector)
|
||||
.limit(nRetrieve)
|
||||
.where(`baseurl = '${baseUrl}'`)
|
||||
.execute();
|
||||
|
||||
docs = docs.filter((doc) => doc.baseurl === baseUrl);
|
||||
|
||||
shouldDownloadPreIndexedDoc =
|
||||
(!docs || docs.length === 0) && !nested && isPreIndexedDoc;
|
||||
|
||||
if (shouldDownloadPreIndexedDoc) {
|
||||
return await downloadAndRetrievePreIndexedDoc(preIndexedDoc!);
|
||||
}
|
||||
|
||||
return docs.map((doc) => ({
|
||||
digest: doc.path,
|
||||
filepath: doc.path,
|
||||
startLine: doc.startline,
|
||||
endLine: doc.endline,
|
||||
index: 0,
|
||||
content: doc.content,
|
||||
otherMetadata: {
|
||||
title: doc.title,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
private async add(
|
||||
title: string,
|
||||
baseUrl: URL,
|
||||
chunks: Chunk[],
|
||||
embeddings: number[][],
|
||||
static createSingleton(
|
||||
configOrHandler: ConfigHandler,
|
||||
ide: IDE,
|
||||
messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
) {
|
||||
const data: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
|
||||
title: chunk.otherMetadata?.title || title,
|
||||
baseurl: baseUrl.toString(),
|
||||
content: chunk.content,
|
||||
path: chunk.filepath,
|
||||
startline: chunk.startLine,
|
||||
endline: chunk.endLine,
|
||||
vector: embeddings[i],
|
||||
}));
|
||||
|
||||
const lance = await this.getLanceDb();
|
||||
const tableNames = await lance.tableNames();
|
||||
if (!tableNames.includes(DocsService.DOCS_TABLE_NAME)) {
|
||||
await lance.createTable(DocsService.DOCS_TABLE_NAME, data);
|
||||
} else {
|
||||
const table = await lance.openTable(DocsService.DOCS_TABLE_NAME);
|
||||
await table.add(data);
|
||||
}
|
||||
|
||||
// Only after add it to SQLite
|
||||
const db = await this.getSqliteTable();
|
||||
await db.run(
|
||||
"INSERT INTO docs (title, baseUrl) VALUES (?, ?)",
|
||||
title,
|
||||
baseUrl.toString(),
|
||||
);
|
||||
const docsService = new DocsService(configOrHandler, ide, messenger);
|
||||
DocsService.instance = docsService;
|
||||
return docsService;
|
||||
}
|
||||
|
||||
async list(): Promise<{ title: string; baseUrl: string }[]> {
|
||||
const db = await this.getSqliteTable();
|
||||
const docs = db.all("SELECT title, baseUrl FROM docs");
|
||||
async isJetBrainsAndPreIndexedDocsProvider(): Promise<boolean> {
|
||||
const isJetBrains = await this.isJetBrains();
|
||||
|
||||
const isPreIndexedDocsProvider =
|
||||
this.config.embeddingsProvider.id ===
|
||||
DocsService.preIndexedDocsEmbeddingsProvider.id;
|
||||
|
||||
return isJetBrains && isPreIndexedDocsProvider;
|
||||
}
|
||||
|
||||
/*
|
||||
* Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
|
||||
* However, we don't ship transformers.js with the JetBrains extension.
|
||||
* So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
|
||||
*/
|
||||
async canUsePreindexedDocs() {
|
||||
const isJetBrains = await this.isJetBrains();
|
||||
return !isJetBrains;
|
||||
}
|
||||
|
||||
async delete(startUrl: string) {
|
||||
await this.deleteFromLance(startUrl);
|
||||
await this.deleteFromSqlite(startUrl);
|
||||
this.deleteFromConfig(startUrl);
|
||||
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async has(startUrl: string): Promise<Promise<boolean>> {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
const title = await db.get(
|
||||
`SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
|
||||
startUrl,
|
||||
);
|
||||
|
||||
return !!title;
|
||||
}
|
||||
|
||||
async indexAllDocs(reIndex: boolean = false) {
|
||||
if (!this.hasDocsContextProvider()) {
|
||||
this.ide.infoPopup(
|
||||
"No 'docs' provider configured under 'contextProviders' in config.json",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const docs = await this.list();
|
||||
|
||||
for (const doc of docs) {
|
||||
const generator = this.indexAndAdd(doc, reIndex);
|
||||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
this.ide.infoPopup("Docs indexing completed");
|
||||
}
|
||||
|
||||
async list() {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
const docs = await db.all<SqliteDocsRow[]>(
|
||||
`SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}`,
|
||||
);
|
||||
|
||||
return docs;
|
||||
}
|
||||
|
||||
async delete(baseUrl: string) {
|
||||
const db = await this.getSqliteTable();
|
||||
await db.run("DELETE FROM docs WHERE baseUrl = ?", baseUrl);
|
||||
const lance = await this.getLanceDb();
|
||||
const tableNames = await lance.tableNames();
|
||||
if (tableNames.includes(DocsService.DOCS_TABLE_NAME)) {
|
||||
const table = await lance.openTable(DocsService.DOCS_TABLE_NAME);
|
||||
await table.delete(`baseurl = '${baseUrl}'`);
|
||||
}
|
||||
}
|
||||
|
||||
async has(baseUrl: string) {
|
||||
const db = await this.getSqliteTable();
|
||||
const doc = await db.get(
|
||||
"SELECT title FROM docs WHERE baseUrl =?",
|
||||
baseUrl,
|
||||
);
|
||||
return !!doc;
|
||||
}
|
||||
|
||||
private async downloadAndAddPreIndexedDocs(
|
||||
embeddingsProviderId: string,
|
||||
title: string,
|
||||
) {
|
||||
const data = await downloadFromS3(
|
||||
"continue-indexed-docs",
|
||||
`${embeddingsProviderId}/${title}`,
|
||||
"us-west-1",
|
||||
);
|
||||
const results = JSON.parse(data) as SiteIndexingResults;
|
||||
await this.add(
|
||||
results.title,
|
||||
new URL(results.url),
|
||||
results.chunks,
|
||||
results.chunks.map((c) => c.embedding),
|
||||
);
|
||||
}
|
||||
|
||||
async *indexAndAdd(
|
||||
siteIndexingConfig: SiteIndexingConfig,
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
reIndex: boolean = false,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const startUrl = new URL(siteIndexingConfig.startUrl.toString());
|
||||
const { startUrl } = siteIndexingConfig;
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider();
|
||||
|
||||
if (this.docsIndexingQueue.has(startUrl.toString())) {
|
||||
if (this.docsIndexingQueue.has(startUrl)) {
|
||||
console.log("Already in queue");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!reIndex && (await this.has(startUrl.toString()))) {
|
||||
if (!reIndex && (await this.has(startUrl))) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Already indexed",
|
||||
|
|
@ -230,7 +190,7 @@ export class DocsService {
|
|||
}
|
||||
|
||||
// Mark the site as currently being indexed
|
||||
this.docsIndexingQueue.add(startUrl.toString());
|
||||
this.docsIndexingQueue.add(startUrl);
|
||||
|
||||
yield {
|
||||
progress: 0,
|
||||
|
|
@ -243,12 +203,18 @@ export class DocsService {
|
|||
let maxKnownPages = 1;
|
||||
|
||||
// Crawl pages and retrieve info as articles
|
||||
for await (const page of crawlPage(startUrl, siteIndexingConfig.maxDepth)) {
|
||||
for await (const page of crawlPage(
|
||||
new URL(startUrl),
|
||||
siteIndexingConfig.maxDepth,
|
||||
)) {
|
||||
processedPages++;
|
||||
|
||||
const article = pageToArticle(page);
|
||||
|
||||
if (!article) {
|
||||
continue;
|
||||
}
|
||||
|
||||
articles.push(article);
|
||||
|
||||
// Use a heuristic approach for progress calculation
|
||||
|
|
@ -281,14 +247,19 @@ export class DocsService {
|
|||
};
|
||||
|
||||
try {
|
||||
const subpathEmbeddings = await embeddingsProvider.embed(
|
||||
chunkArticle(article, embeddingsProvider.maxChunkSize).map(
|
||||
(chunk) => {
|
||||
chunks.push(chunk);
|
||||
const chunkedArticle = chunkArticle(
|
||||
article,
|
||||
embeddingsProvider.maxChunkSize,
|
||||
);
|
||||
|
||||
return chunk.content;
|
||||
},
|
||||
),
|
||||
const chunkedArticleContents = chunkedArticle.map(
|
||||
(chunk) => chunk.content,
|
||||
);
|
||||
|
||||
chunks.push(...chunkedArticle);
|
||||
|
||||
const subpathEmbeddings = await embeddingsProvider.embed(
|
||||
chunkedArticleContents,
|
||||
);
|
||||
|
||||
embeddings.push(...subpathEmbeddings);
|
||||
|
|
@ -297,8 +268,23 @@ export class DocsService {
|
|||
}
|
||||
}
|
||||
|
||||
if (embeddings.length === 0) {
|
||||
console.error(
|
||||
`No embeddings were created for site: ${siteIndexingConfig.startUrl}\n Num chunks: ${chunks.length}`,
|
||||
);
|
||||
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: `No embeddings were created for site: ${siteIndexingConfig.startUrl}`,
|
||||
status: "failed",
|
||||
};
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Add docs to databases
|
||||
console.log("Adding ", embeddings.length, " embeddings to db");
|
||||
console.log(`Adding ${embeddings.length} embeddings to db`);
|
||||
|
||||
yield {
|
||||
progress: 0.5,
|
||||
desc: `Adding ${embeddings.length} embeddings to db`,
|
||||
|
|
@ -308,27 +294,503 @@ export class DocsService {
|
|||
// Clear old index if re-indexing.
|
||||
if (reIndex) {
|
||||
console.log("Deleting old embeddings");
|
||||
await this.delete(startUrl.toString());
|
||||
await this.delete(startUrl);
|
||||
}
|
||||
|
||||
await this.add(siteIndexingConfig.title, startUrl, chunks, embeddings);
|
||||
this.docsIndexingQueue.delete(startUrl.toString());
|
||||
const favicon = await this.fetchFavicon(siteIndexingConfig);
|
||||
|
||||
await this.add({
|
||||
siteIndexingConfig,
|
||||
chunks,
|
||||
embeddings,
|
||||
favicon,
|
||||
});
|
||||
|
||||
this.docsIndexingQueue.delete(startUrl);
|
||||
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Done",
|
||||
status: "done",
|
||||
};
|
||||
|
||||
console.log(`Successfully indexed: ${siteIndexingConfig.startUrl}`);
|
||||
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
}
|
||||
}
|
||||
|
||||
public isJetBrainsAndPreIndexedDocsProvider(
|
||||
ideInfo: IdeInfo,
|
||||
embeddingsProviderId: EmbeddingsProvider["id"],
|
||||
): boolean {
|
||||
const isJetBrains = ideInfo.ideType === "jetbrains";
|
||||
const isPreIndexedDocsProvider =
|
||||
embeddingsProviderId === DocsService.preIndexedDocsEmbeddingsProvider.id;
|
||||
async retrieveChunks(
|
||||
startUrl: string,
|
||||
vector: number[],
|
||||
nRetrieve: number,
|
||||
isRetry: boolean = false,
|
||||
): Promise<Chunk[]> {
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
initializationVector: vector,
|
||||
isPreIndexedDoc: !!preIndexedDocs[startUrl],
|
||||
});
|
||||
|
||||
return isJetBrains && isPreIndexedDocsProvider;
|
||||
const docs: LanceDbDocsRow[] = await table
|
||||
.search(vector)
|
||||
.limit(nRetrieve)
|
||||
.where(`starturl = '${startUrl}'`)
|
||||
.execute();
|
||||
|
||||
const hasIndexedDoc = await this.hasIndexedDoc(startUrl);
|
||||
|
||||
if (!hasIndexedDoc && docs.length === 0) {
|
||||
const preIndexedDoc = preIndexedDocs[startUrl];
|
||||
|
||||
if (isRetry || !preIndexedDoc) {
|
||||
return [];
|
||||
}
|
||||
|
||||
await this.fetchAndAddPreIndexedDocEmbeddings(preIndexedDoc.title);
|
||||
return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
|
||||
}
|
||||
|
||||
return docs.map((doc) => ({
|
||||
digest: doc.path,
|
||||
filepath: doc.path,
|
||||
startLine: doc.startline,
|
||||
endLine: doc.endline,
|
||||
index: 0,
|
||||
content: doc.content,
|
||||
otherMetadata: {
|
||||
title: doc.title,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
async getEmbeddingsProvider(isPreIndexedDoc: boolean = false) {
|
||||
const canUsePreindexedDocs = await this.canUsePreindexedDocs();
|
||||
|
||||
if (isPreIndexedDoc && canUsePreindexedDocs) {
|
||||
return DocsService.preIndexedDocsEmbeddingsProvider;
|
||||
}
|
||||
|
||||
return this.config.embeddingsProvider;
|
||||
}
|
||||
|
||||
async getFavicon(startUrl: string) {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
const { favicon } = await db.get(
|
||||
`SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
|
||||
startUrl,
|
||||
);
|
||||
|
||||
return favicon;
|
||||
}
|
||||
|
||||
/**
|
||||
* A ConfigHandler is passed to the DocsService in `core` when
|
||||
* we don't yet have access to the config object. This handler
|
||||
* is used to set up a single instance of the DocsService that
|
||||
* subscribes to config updates, e.g. to trigger re-indexing
|
||||
* on a new embeddings provider.
|
||||
*/
|
||||
private async init(configHandler: ConfigHandler) {
|
||||
if (configHandler instanceof ConfigHandler) {
|
||||
this.config = await configHandler.loadConfig();
|
||||
} else {
|
||||
this.config = configHandler;
|
||||
}
|
||||
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider();
|
||||
|
||||
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
|
||||
|
||||
configHandler.onConfigUpdate(async (newConfig) => {
|
||||
const oldConfig = this.config;
|
||||
|
||||
// Need to update class property for config at the beginning of this callback
|
||||
// to ensure downstream methods have access to the latest config.
|
||||
this.config = newConfig;
|
||||
|
||||
if (oldConfig.docs !== newConfig.docs) {
|
||||
await this.syncConfigAndSqlite();
|
||||
}
|
||||
|
||||
const shouldReindex = await this.shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
newConfig.embeddingsProvider.id,
|
||||
);
|
||||
|
||||
if (shouldReindex) {
|
||||
await this.reindexDocsOnNewEmbeddingsProvider(
|
||||
newConfig.embeddingsProvider,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async syncConfigAndSqlite() {
|
||||
this.isSyncing = true;
|
||||
|
||||
const sqliteDocs = await this.list();
|
||||
const sqliteDocStartUrls = sqliteDocs.map((doc) => doc.startUrl) || [];
|
||||
|
||||
const configDocs = this.config.docs || [];
|
||||
const configDocStartUrls =
|
||||
this.config.docs?.map((doc) => doc.startUrl) || [];
|
||||
|
||||
const newDocs = configDocs.filter(
|
||||
(doc) => !sqliteDocStartUrls.includes(doc.startUrl),
|
||||
);
|
||||
const deletedDocs = sqliteDocs.filter(
|
||||
(doc) =>
|
||||
!configDocStartUrls.includes(doc.startUrl) &&
|
||||
!preIndexedDocs[doc.startUrl],
|
||||
);
|
||||
|
||||
for (const doc of newDocs) {
|
||||
console.log(`Indexing new doc: ${doc.startUrl}`);
|
||||
Telemetry.capture("add_docs_config", { url: doc.startUrl });
|
||||
|
||||
const generator = this.indexAndAdd(doc);
|
||||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
for (const doc of deletedDocs) {
|
||||
console.log(`Deleting doc: ${doc.startUrl}`);
|
||||
await this.delete(doc.startUrl);
|
||||
}
|
||||
|
||||
this.isSyncing = false;
|
||||
}
|
||||
|
||||
private hasDocsContextProvider() {
|
||||
return !!this.config.contextProviders?.some(
|
||||
(provider) =>
|
||||
provider.description.title === DocsContextProvider.description.title,
|
||||
);
|
||||
}
|
||||
|
||||
private async getOrCreateSqliteDb() {
|
||||
if (!this.sqliteDb) {
|
||||
const db = await open({
|
||||
filename: getDocsSqlitePath(),
|
||||
driver: sqlite3.Database,
|
||||
});
|
||||
|
||||
await runSqliteMigrations(db);
|
||||
|
||||
db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
title STRING NOT NULL,
|
||||
startUrl STRING NOT NULL UNIQUE,
|
||||
favicon STRING
|
||||
)`);
|
||||
|
||||
this.sqliteDb = db;
|
||||
}
|
||||
|
||||
return this.sqliteDb;
|
||||
}
|
||||
|
||||
private async createLanceDocsTable(
|
||||
connection: Connection,
|
||||
initializationVector: number[],
|
||||
tableName: string,
|
||||
) {
|
||||
const mockRowTitle = "mockRowTitle";
|
||||
const mockRow: LanceDbDocsRow[] = [
|
||||
{
|
||||
title: mockRowTitle,
|
||||
vector: initializationVector,
|
||||
starturl: "",
|
||||
content: "",
|
||||
path: "",
|
||||
startline: 0,
|
||||
endline: 0,
|
||||
},
|
||||
];
|
||||
|
||||
const table = await connection.createTable(tableName, mockRow);
|
||||
|
||||
await runLanceMigrations(table);
|
||||
|
||||
await table.delete(`title = '${mockRowTitle}'`);
|
||||
}
|
||||
|
||||
private removeInvalidLanceTableNameChars(tableName: string) {
|
||||
return tableName.replace(/:/g, "");
|
||||
}
|
||||
|
||||
private async getLanceTableNameFromEmbeddingsProvider(
|
||||
isPreIndexedDoc: boolean,
|
||||
) {
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(
|
||||
isPreIndexedDoc,
|
||||
);
|
||||
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
|
||||
embeddingsProvider.id,
|
||||
);
|
||||
const tableName = `${DocsService.lanceTableName}${embeddingsProviderId}`;
|
||||
|
||||
return tableName;
|
||||
}
|
||||
|
||||
private async getOrCreateLanceTable({
|
||||
initializationVector,
|
||||
isPreIndexedDoc,
|
||||
}: {
|
||||
initializationVector: number[];
|
||||
isPreIndexedDoc?: boolean;
|
||||
}) {
|
||||
const conn = await lancedb.connect(getLanceDbPath());
|
||||
const tableNames = await conn.tableNames();
|
||||
const tableNameFromEmbeddingsProvider =
|
||||
await this.getLanceTableNameFromEmbeddingsProvider(!!isPreIndexedDoc);
|
||||
|
||||
if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
|
||||
if (initializationVector) {
|
||||
await this.createLanceDocsTable(
|
||||
conn,
|
||||
initializationVector,
|
||||
tableNameFromEmbeddingsProvider,
|
||||
);
|
||||
} else {
|
||||
console.trace(
|
||||
"No existing Lance DB docs table was found and no initialization " +
|
||||
"vector was passed to create one",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const table = await conn.openTable(tableNameFromEmbeddingsProvider);
|
||||
|
||||
this.lanceTableNamesSet.add(tableNameFromEmbeddingsProvider);
|
||||
|
||||
return table;
|
||||
}
|
||||
|
||||
private async isJetBrains() {
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
return ideInfo.ideType === "jetbrains";
|
||||
}
|
||||
|
||||
private async hasIndexedDoc(startUrl: string) {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
const docs = await db.all(
|
||||
`SELECT startUrl FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
|
||||
startUrl,
|
||||
);
|
||||
|
||||
return docs.length > 0;
|
||||
}
|
||||
|
||||
private async addToLance({
|
||||
chunks,
|
||||
siteIndexingConfig,
|
||||
embeddings,
|
||||
}: AddParams) {
|
||||
const sampleVector = embeddings[0];
|
||||
const isPreIndexedDoc = !!preIndexedDocs[siteIndexingConfig.startUrl];
|
||||
const table = await this.getOrCreateLanceTable({
|
||||
isPreIndexedDoc,
|
||||
initializationVector: sampleVector,
|
||||
});
|
||||
|
||||
const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
|
||||
vector: embeddings[i],
|
||||
starturl: siteIndexingConfig.startUrl,
|
||||
title: chunk.otherMetadata?.title || siteIndexingConfig.title,
|
||||
content: chunk.content,
|
||||
path: chunk.filepath,
|
||||
startline: chunk.startLine,
|
||||
endline: chunk.endLine,
|
||||
}));
|
||||
|
||||
await table.add(rows);
|
||||
}
|
||||
|
||||
private async addToSqlite({
|
||||
siteIndexingConfig: { title, startUrl },
|
||||
favicon,
|
||||
}: AddParams) {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
await db.run(
|
||||
`INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon) VALUES (?, ?, ?)`,
|
||||
title,
|
||||
startUrl,
|
||||
favicon,
|
||||
);
|
||||
}
|
||||
|
||||
private addToConfig({ siteIndexingConfig }: AddParams) {
|
||||
// Handles the case where a user has manually added the doc to config.json
|
||||
// so it already exists in the file
|
||||
const doesDocExist = this.config.docs?.some(
|
||||
(doc) => doc.startUrl === siteIndexingConfig.startUrl,
|
||||
);
|
||||
|
||||
if (!doesDocExist) {
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: [...(config.docs ?? []), siteIndexingConfig],
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private async add(params: AddParams) {
|
||||
await this.addToLance(params);
|
||||
await this.addToSqlite(params);
|
||||
|
||||
const isPreIndexedDoc =
|
||||
!!preIndexedDocs[params.siteIndexingConfig.startUrl];
|
||||
|
||||
if (!isPreIndexedDoc) {
|
||||
this.addToConfig(params);
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteFromLance(startUrl: string) {
|
||||
for (const tableName of this.lanceTableNamesSet) {
|
||||
const conn = await lancedb.connect(getLanceDbPath());
|
||||
const table = await conn.openTable(tableName);
|
||||
await table.delete(`starturl = '${startUrl}'`);
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteFromSqlite(startUrl: string) {
|
||||
const db = await this.getOrCreateSqliteDb();
|
||||
await db.run(
|
||||
`DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ?`,
|
||||
startUrl,
|
||||
);
|
||||
}
|
||||
|
||||
deleteFromConfig(startUrl: string) {
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
|
||||
}));
|
||||
}
|
||||
|
||||
private async fetchAndAddPreIndexedDocEmbeddings(title: string) {
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(true);
|
||||
|
||||
const data = await downloadFromS3(
|
||||
S3Buckets.continueIndexedDocs,
|
||||
getS3Filename(embeddingsProvider.id, title),
|
||||
);
|
||||
|
||||
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
|
||||
const startUrl = new URL(siteEmbeddings.url).toString();
|
||||
const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]);
|
||||
|
||||
await this.add({
|
||||
favicon,
|
||||
siteIndexingConfig: {
|
||||
startUrl,
|
||||
title: siteEmbeddings.title,
|
||||
},
|
||||
chunks: siteEmbeddings.chunks,
|
||||
embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
|
||||
});
|
||||
}
|
||||
|
||||
private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) {
|
||||
const faviconUrl =
|
||||
siteIndexingConfig.faviconUrl ??
|
||||
new URL("/favicon.ico", siteIndexingConfig.startUrl);
|
||||
|
||||
try {
|
||||
const response = await fetch(faviconUrl);
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const base64 = btoa(
|
||||
new Uint8Array(arrayBuffer).reduce(
|
||||
(data, byte) => data + String.fromCharCode(byte),
|
||||
"",
|
||||
),
|
||||
);
|
||||
const mimeType = response.headers.get("content-type") || "image/x-icon";
|
||||
|
||||
return `data:${mimeType};base64,${base64}`;
|
||||
} catch {
|
||||
console.error(`Failed to fetch favicon: ${faviconUrl}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private async shouldReindexDocsOnNewEmbeddingsProvider(
|
||||
curEmbeddingsProviderId: EmbeddingsProvider["id"],
|
||||
): Promise<boolean> {
|
||||
const isJetBrainsAndPreIndexedDocsProvider =
|
||||
await this.isJetBrainsAndPreIndexedDocsProvider();
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
this.ide.errorPopup(
|
||||
"The 'transformers.js' embeddings provider currently cannot be used to index " +
|
||||
"documentation in JetBrains. To enable documentation indexing, you can use " +
|
||||
"any of the other providers described in the docs: " +
|
||||
"https://docs.continue.dev/walkthroughs/codebase-embeddings#embeddings-providers",
|
||||
);
|
||||
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
const lastEmbeddingsProviderId = this.globalContext.get(
|
||||
"curEmbeddingsProviderId",
|
||||
);
|
||||
|
||||
if (!lastEmbeddingsProviderId) {
|
||||
// If it's the first time we're setting the `curEmbeddingsProviderId`
|
||||
// global state, we don't need to reindex docs
|
||||
this.globalContext.update(
|
||||
"curEmbeddingsProviderId",
|
||||
curEmbeddingsProviderId,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return lastEmbeddingsProviderId !== curEmbeddingsProviderId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Currently this deletes re-crawls + re-indexes all docs.
|
||||
* A more optimal solution in the future will be to create
|
||||
* a per-embeddings-provider table for docs.
|
||||
*/
|
||||
private async reindexDocsOnNewEmbeddingsProvider(
|
||||
embeddingsProvider: EmbeddingsProvider,
|
||||
) {
|
||||
// We use config as our source of truth here since it contains additional information
|
||||
// needed for re-crawling such as `faviconUrl` and `maxDepth`.
|
||||
const { docs } = this.config;
|
||||
|
||||
if (!docs || docs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`Reindexing docs with new embeddings provider: ${embeddingsProvider.id}`,
|
||||
);
|
||||
|
||||
for (const doc of docs) {
|
||||
await this.delete(doc.startUrl);
|
||||
|
||||
const generator = this.indexAndAdd(doc);
|
||||
|
||||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
// Important that this only is invoked after we have successfully
|
||||
// cleared and reindex the docs so that the table cannot end up in an
|
||||
// invalid state.
|
||||
this.globalContext.update("curEmbeddingsProviderId", embeddingsProvider.id);
|
||||
|
||||
console.log("Completed reindexing of all docs");
|
||||
}
|
||||
}
|
||||
|
||||
export const docsServiceSingleton = DocsService.getSingleton();
|
||||
|
|
|
|||
|
|
@ -118,7 +118,6 @@ function extractTitlesAndBodies(html: string): ArticleComponent[] {
|
|||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function stringToArticle(
|
||||
url: string,
|
||||
html: string,
|
||||
|
|
|
|||
70
core/indexing/docs/migrations.ts
Normal file
70
core/indexing/docs/migrations.ts
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { Table } from "vectordb";
|
||||
import { editConfigJson, migrate } from "../../util/paths.js";
|
||||
import { type Database } from "sqlite";
|
||||
import DocsService, { SqliteDocsRow } from "./DocsService.js";
|
||||
|
||||
export async function runLanceMigrations(table: Table) {
|
||||
await new Promise((resolve) =>
|
||||
migrate(
|
||||
"rename_baseurl_column_for_lance_docs",
|
||||
async () => {
|
||||
try {
|
||||
const schema = await table.schema;
|
||||
|
||||
if (schema.fields.some((field: any) => field.name === "baseurl")) {
|
||||
await table.alterColumns([{ path: "baseurl", rename: "starturl" }]);
|
||||
}
|
||||
} finally {
|
||||
resolve(undefined);
|
||||
}
|
||||
},
|
||||
() => resolve(undefined),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function runSqliteMigrations(db: Database) {
|
||||
await new Promise((resolve) => {
|
||||
migrate(
|
||||
"sqlite_modify_docs_columns_and_copy_to_config",
|
||||
async () => {
|
||||
try {
|
||||
const pragma = await db.all(
|
||||
`PRAGMA table_info(${DocsService.sqlitebTableName})`,
|
||||
);
|
||||
|
||||
const hasFaviconCol = pragma.some(
|
||||
(pragma) => pragma.name === "favicon",
|
||||
);
|
||||
const hasBaseUrlCol = pragma.some(
|
||||
(pragma) => pragma.name === "baseUrl",
|
||||
);
|
||||
|
||||
if (!hasFaviconCol) {
|
||||
await db.exec(
|
||||
`ALTER TABLE ${DocsService.sqlitebTableName} ADD COLUMN favicon BLOB`,
|
||||
);
|
||||
}
|
||||
|
||||
if (hasBaseUrlCol) {
|
||||
await db.exec(
|
||||
`ALTER TABLE ${DocsService.sqlitebTableName} RENAME COLUMN baseUrl TO startUrl`,
|
||||
);
|
||||
}
|
||||
|
||||
const sqliteDocs = await db.all<
|
||||
Array<Pick<SqliteDocsRow, "title" | "startUrl">>
|
||||
>(`SELECT title, startUrl FROM ${DocsService.sqlitebTableName}`);
|
||||
|
||||
editConfigJson((config) => ({
|
||||
...config,
|
||||
docs: [...(config.docs || []), ...sqliteDocs],
|
||||
}));
|
||||
} finally {
|
||||
resolve(undefined);
|
||||
}
|
||||
},
|
||||
() => resolve(undefined),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,17 +1,28 @@
|
|||
import { Chunk } from "../../index.js";
|
||||
import { Chunk } from "../../";
|
||||
import request from "request";
|
||||
|
||||
const request = require("request");
|
||||
export function getS3Filename(
|
||||
embeddingsProviderId: string,
|
||||
title: string,
|
||||
): string {
|
||||
return `${embeddingsProviderId}/${title}`;
|
||||
}
|
||||
|
||||
export enum S3Buckets {
|
||||
continueIndexedDocs = "continue-indexed-docs",
|
||||
}
|
||||
|
||||
const AWS_REGION = "us-west-1";
|
||||
|
||||
export async function downloadFromS3(
|
||||
bucket: string,
|
||||
fileName: string,
|
||||
region: string,
|
||||
): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
let data = "";
|
||||
|
||||
const download = request({
|
||||
url: `https://${bucket}.s3.${region}.amazonaws.com/${fileName}`,
|
||||
url: `https://${bucket}.s3.${AWS_REGION}.amazonaws.com/${fileName}`,
|
||||
});
|
||||
download.on("response", (response: any) => {
|
||||
if (response.statusCode !== 200) {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import {
|
||||
EmbedOptions,
|
||||
EmbeddingsProvider,
|
||||
EmbeddingsProviderName,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
|
||||
|
|
@ -17,6 +18,11 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
|
|||
static maxBatchSize: IBaseEmbeddingsProvider["maxBatchSize"];
|
||||
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"];
|
||||
|
||||
static providerName: EmbeddingsProviderName;
|
||||
get providerName(): EmbeddingsProviderName {
|
||||
return (this.constructor as typeof BaseEmbeddingsProvider).providerName;
|
||||
}
|
||||
|
||||
options: IBaseEmbeddingsProvider["options"];
|
||||
fetch: IBaseEmbeddingsProvider["fetch"];
|
||||
id: IBaseEmbeddingsProvider["id"];
|
||||
|
|
@ -38,6 +44,8 @@ abstract class BaseEmbeddingsProvider implements IBaseEmbeddingsProvider {
|
|||
this.id = `${this.constructor.name}::${this.options.model}`;
|
||||
}
|
||||
}
|
||||
defaultOptions?: EmbedOptions | undefined;
|
||||
maxBatchSize?: number | undefined;
|
||||
|
||||
abstract embed(chunks: string[]): Promise<number[][]>;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
import { Response } from "node-fetch";
|
||||
import { EmbedOptions } from "../../index.js";
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class CohereEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static maxBatchSize = 96;
|
||||
|
||||
static providerName: EmbeddingsProviderName = "cohere";
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "https://api.cohere.ai/v1/",
|
||||
model: "embed-english-v3.0",
|
||||
|
|
|
|||
25
core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts
Normal file
25
core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
|
||||
|
||||
class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "continue-proxy";
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(),
|
||||
};
|
||||
|
||||
private _workOsAccessToken: string | undefined = undefined;
|
||||
|
||||
get workOsAccessToken(): string | undefined {
|
||||
return this._workOsAccessToken;
|
||||
}
|
||||
|
||||
set workOsAccessToken(value: string | undefined) {
|
||||
if (this._workOsAccessToken !== value) {
|
||||
this._workOsAccessToken = value;
|
||||
this.options.apiKey = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default ContinueProxyEmbeddingsProvider;
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { EmbedOptions } from "../../index.js";
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class DeepInfraEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "deepinfra";
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
model: "sentence-transformers/all-MiniLM-L6-v2",
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,11 +1,16 @@
|
|||
import { Response } from "node-fetch";
|
||||
import { getHeaders } from "../../continueServer/stubs/headers.js";
|
||||
import { constants } from "../../deploy/constants.js";
|
||||
import { EmbedOptions, FetchFunction } from "../../index.js";
|
||||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "free-trial";
|
||||
static maxBatchSize = 128;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
import { Response } from "node-fetch";
|
||||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider, {
|
||||
IBaseEmbeddingsProvider,
|
||||
} from "./BaseEmbeddingsProvider.js";
|
||||
import {
|
||||
EmbedContentRequest,
|
||||
EmbedContentResponse,
|
||||
} from "@google/generative-ai";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
/**
|
||||
* [View the Gemini Text Embedding docs.](https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding)
|
||||
*/
|
||||
class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "gemini";
|
||||
static maxBatchSize = 2048;
|
||||
|
||||
static defaultOptions = {
|
||||
|
|
@ -20,26 +16,26 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
};
|
||||
|
||||
get urlPath(): string {
|
||||
return `${this.options.model}:embedContent`;
|
||||
return `${this.options.model}:batchEmbedContents`;
|
||||
}
|
||||
|
||||
async getSingleBatchEmbedding(batch: string[]) {
|
||||
const body: EmbedContentRequest = {
|
||||
// Batch embed endpoint: https://ai.google.dev/api/embeddings?authuser=1#EmbedContentRequest
|
||||
const requests = batch.map((text) => ({
|
||||
model: this.options.model,
|
||||
content: {
|
||||
/**
|
||||
* Listed as optional in the [docs](https://ai.google.dev/api/rest/v1/Content)
|
||||
* but is required in the interface.
|
||||
*/
|
||||
role: "user",
|
||||
parts: batch.map((part) => ({ text: part })),
|
||||
parts: [{ text }],
|
||||
},
|
||||
};
|
||||
}));
|
||||
|
||||
const fetchWithBackoff = () =>
|
||||
withExponentialBackoff<Response>(() =>
|
||||
this.fetch(new URL(this.urlPath, this.options.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify({
|
||||
requests,
|
||||
}),
|
||||
headers: {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
"x-goog-api-key": this.options.apiKey,
|
||||
|
|
@ -55,17 +51,18 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
throw new Error(await resp.text());
|
||||
}
|
||||
|
||||
const data = (await resp.json()) as EmbedContentResponse;
|
||||
const data = (await resp.json()) as any;
|
||||
|
||||
return data.embedding.values;
|
||||
return data.embeddings.map((embedding: any) => embedding.values);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
const batches = GeminiEmbeddingsProvider.getBatchedChunks(chunks);
|
||||
|
||||
return await Promise.all(
|
||||
const results = await Promise.all(
|
||||
batches.map((batch) => this.getSingleBatchEmbedding(batch)),
|
||||
);
|
||||
return results.flat();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import fetch, { Response } from "node-fetch";
|
||||
import { EmbedOptions, FetchFunction } from "../..";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
||||
import { Response } from "node-fetch";
|
||||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
private maxBatchSize = 32;
|
||||
static providerName: EmbeddingsProviderName = "huggingface-tei";
|
||||
maxBatchSize = 32;
|
||||
|
||||
static defaultOptions: Partial<EmbedOptions> | undefined = {
|
||||
apiBase: "http://localhost:8080",
|
||||
|
|
@ -17,7 +22,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
if (!this.options.apiBase?.endsWith("/")) {
|
||||
this.options.apiBase += "/";
|
||||
}
|
||||
this.doInfoRequest().then(response => {
|
||||
this.doInfoRequest().then((response) => {
|
||||
this.options.model = response.model_id;
|
||||
this.maxBatchSize = response.max_client_batch_size;
|
||||
});
|
||||
|
|
@ -26,7 +31,9 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
async embed(chunks: string[]) {
|
||||
const promises = [];
|
||||
for (let i = 0; i < chunks.length; i += this.maxBatchSize) {
|
||||
promises.push(this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)));
|
||||
promises.push(
|
||||
this.doEmbedRequest(chunks.slice(i, i + this.maxBatchSize)),
|
||||
);
|
||||
}
|
||||
const results = await Promise.all(promises);
|
||||
return results.flat();
|
||||
|
|
@ -37,11 +44,11 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
|||
this.fetch(new URL("embed", this.options.apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: batch
|
||||
inputs: batch,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!resp.ok) {
|
||||
|
|
@ -75,9 +82,9 @@ class TEIEmbedError extends Error {
|
|||
}
|
||||
|
||||
type TEIEmbedErrorResponse = {
|
||||
error: string
|
||||
error_type: string
|
||||
}
|
||||
error: string;
|
||||
error_type: string;
|
||||
};
|
||||
|
||||
type TEIInfoResponse = {
|
||||
model_id: string;
|
||||
|
|
@ -86,7 +93,7 @@ type TEIInfoResponse = {
|
|||
model_type: {
|
||||
embedding: {
|
||||
pooling: string;
|
||||
}
|
||||
};
|
||||
};
|
||||
max_concurrent_requests: number;
|
||||
max_input_length: number;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { EmbedOptions, FetchFunction } from "../../index.js";
|
||||
import {
|
||||
EmbeddingsProviderName,
|
||||
EmbedOptions,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider, {
|
||||
IBaseEmbeddingsProvider,
|
||||
|
|
@ -10,12 +14,21 @@ async function embedOne(
|
|||
customFetch: FetchFunction,
|
||||
) {
|
||||
const embedding = await withExponentialBackoff<number[]>(async () => {
|
||||
const resp = await customFetch(new URL("api/embeddings", options.apiBase), {
|
||||
let apiBase = options.apiBase!;
|
||||
|
||||
if (!apiBase.endsWith("/")) {
|
||||
apiBase += "/";
|
||||
}
|
||||
|
||||
const resp = await customFetch(new URL("api/embeddings", apiBase), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
prompt: chunk,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
|
|
@ -35,6 +48,7 @@ async function embedOne(
|
|||
}
|
||||
|
||||
class OllamaEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "ollama";
|
||||
static defaultOptions: IBaseEmbeddingsProvider["defaultOptions"] = {
|
||||
apiBase: "http://localhost:11434/",
|
||||
model: "nomic-embed-text",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import { Response } from "node-fetch";
|
||||
import { EmbedOptions } from "../../index.js";
|
||||
import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
|
||||
import { withExponentialBackoff } from "../../util/withExponentialBackoff.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
|
||||
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "openai";
|
||||
// https://platform.openai.com/docs/api-reference/embeddings/create is 2048
|
||||
// but Voyage is 128
|
||||
static maxBatchSize = 128;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import path from "path";
|
||||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
// @ts-ignore
|
||||
// prettier-ignore
|
||||
import { type PipelineType } from "../../vendor/modules/@xenova/transformers/src/transformers.js";
|
||||
|
|
@ -37,13 +38,23 @@ class EmbeddingsPipeline {
|
|||
}
|
||||
|
||||
export class TransformersJsEmbeddingsProvider extends BaseEmbeddingsProvider {
|
||||
static providerName: EmbeddingsProviderName = "transformers.js";
|
||||
static maxGroupSize: number = 4;
|
||||
static model: string = "all-MiniLM-L6-v2";
|
||||
static mockVector: number[] = Array.from({ length: 384 }).fill(2) as number[];
|
||||
|
||||
constructor() {
|
||||
super({ model: "all-MiniLM-L6-v2" }, () => Promise.resolve(null));
|
||||
super({ model: TransformersJsEmbeddingsProvider.model }, () =>
|
||||
Promise.resolve(null),
|
||||
);
|
||||
}
|
||||
|
||||
async embed(chunks: string[]) {
|
||||
// Workaround to ignore testing issues in Jest
|
||||
if (process.env.NODE_ENV === "test") {
|
||||
return chunks.map(() => TransformersJsEmbeddingsProvider.mockVector);
|
||||
}
|
||||
|
||||
const extractor = await EmbeddingsPipeline.getInstance();
|
||||
|
||||
if (!extractor) {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,14 @@
|
|||
import { EmbeddingsProviderName } from "../../index.js";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider.js";
|
||||
import CohereEmbeddingsProvider from "./CohereEmbeddingsProvider.js";
|
||||
import ContinueProxyEmbeddingsProvider from "./ContinueProxyEmbeddingsProvider.js";
|
||||
import DeepInfraEmbeddingsProvider from "./DeepInfraEmbeddingsProvider.js";
|
||||
import FreeTrialEmbeddingsProvider from "./FreeTrialEmbeddingsProvider.js";
|
||||
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
|
||||
import HuggingFaceTEIEmbeddingsProvider from "./HuggingFaceTEIEmbeddingsProvider.js";
|
||||
import OllamaEmbeddingsProvider from "./OllamaEmbeddingsProvider.js";
|
||||
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
|
||||
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider.js";
|
||||
import GeminiEmbeddingsProvider from "./GeminiEmbeddingsProvider.js";
|
||||
|
||||
type EmbeddingsProviderConstructor = new (
|
||||
...args: any[]
|
||||
|
|
@ -26,4 +28,6 @@ export const allEmbeddingsProviders: Record<
|
|||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
|
||||
gemini: GeminiEmbeddingsProvider,
|
||||
"continue-proxy": ContinueProxyEmbeddingsProvider,
|
||||
deepinfra: DeepInfraEmbeddingsProvider,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -67,33 +67,35 @@ export const DEFAULT_IGNORE_FILETYPES = [
|
|||
".csv",
|
||||
// "*.prompt", // can be incredibly confusing for the LLM to have another set of instructions injected into the prompt
|
||||
];
|
||||
|
||||
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
|
||||
export const DEFAULT_IGNORE_DIRS = [
|
||||
".git",
|
||||
".svn",
|
||||
".vscode",
|
||||
".idea",
|
||||
".vs",
|
||||
"venv",
|
||||
".venv",
|
||||
"env",
|
||||
".env",
|
||||
"node_modules",
|
||||
"dist",
|
||||
"build",
|
||||
"target",
|
||||
"out",
|
||||
"bin",
|
||||
".pytest_cache",
|
||||
".vscode-test",
|
||||
".continue",
|
||||
"__pycache__",
|
||||
"site-packages",
|
||||
".gradle",
|
||||
".cache",
|
||||
"gems",
|
||||
"vendor",
|
||||
".git/",
|
||||
".svn/",
|
||||
".vscode/",
|
||||
".idea/",
|
||||
".vs/",
|
||||
"venv/",
|
||||
".venv/",
|
||||
"env/",
|
||||
".env/",
|
||||
"node_modules/",
|
||||
"dist/",
|
||||
"build/",
|
||||
"target/",
|
||||
"out/",
|
||||
"bin/",
|
||||
".pytest_cache/",
|
||||
".vscode-test/",
|
||||
".continue/",
|
||||
"__pycache__/",
|
||||
"site-packages/",
|
||||
".gradle/",
|
||||
".cache/",
|
||||
"gems/",
|
||||
"vendor/",
|
||||
];
|
||||
|
||||
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
|
||||
|
||||
export const DEFAULT_IGNORE =
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ enum AddRemoveResultType {
|
|||
UpdateNewVersion = "updateNewVersion",
|
||||
UpdateOldVersion = "updateOldVersion",
|
||||
UpdateLastUpdated = "updateLastUpdated",
|
||||
Compute = "compute"
|
||||
Compute = "compute",
|
||||
}
|
||||
|
||||
async function getAddRemoveForTag(
|
||||
|
|
@ -451,7 +451,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
|
|||
tag: IndexTag,
|
||||
): Promise<void> {
|
||||
await this.db.run(
|
||||
"INSERT INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
|
||||
"REPLACE INTO global_cache (cacheKey, dir, branch, artifactId) VALUES (?, ?, ?, ?)",
|
||||
cacheKey,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
|
|
|
|||
|
|
@ -1,17 +1,15 @@
|
|||
import { EventEmitter } from "events";
|
||||
import { Minimatch } from "minimatch";
|
||||
import path from "node:path";
|
||||
import { FileType, IDE } from "../index.js";
|
||||
import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES } from "./ignore.js";
|
||||
import { FileType, IDE } from "../index.d.js";
|
||||
import ignore, { Ignore } from "ignore";
|
||||
import {
|
||||
DEFAULT_IGNORE_DIRS,
|
||||
DEFAULT_IGNORE_FILETYPES,
|
||||
defaultIgnoreDir,
|
||||
defaultIgnoreFile,
|
||||
} from "./ignore.js";
|
||||
|
||||
export interface WalkerOptions {
|
||||
isSymbolicLink?: boolean;
|
||||
path?: string;
|
||||
ignoreFiles?: string[];
|
||||
parent?: Walker | null;
|
||||
includeEmpty?: boolean;
|
||||
follow?: boolean;
|
||||
exact?: boolean;
|
||||
onlyDirs?: boolean;
|
||||
returnRelativePaths?: boolean;
|
||||
additionalIgnoreRules?: string[];
|
||||
|
|
@ -19,314 +17,148 @@ export interface WalkerOptions {
|
|||
|
||||
type Entry = [string, FileType];
|
||||
|
||||
class Walker extends EventEmitter {
|
||||
isSymbolicLink: boolean;
|
||||
path: string;
|
||||
basename: string;
|
||||
ignoreFiles: string[];
|
||||
ignoreRules: { [key: string]: Minimatch[] };
|
||||
parent: Walker | null;
|
||||
includeEmpty: boolean;
|
||||
root: string;
|
||||
follow: boolean;
|
||||
result: Set<string>;
|
||||
entries: Entry[] | null;
|
||||
sawError: boolean;
|
||||
exact: boolean | undefined;
|
||||
onlyDirs: boolean | undefined;
|
||||
constructor(opts: WalkerOptions = {}, protected readonly ide: IDE) {
|
||||
super(opts as any);
|
||||
this.isSymbolicLink = opts.isSymbolicLink || false;
|
||||
this.path = opts.path || process.cwd();
|
||||
this.basename = path.basename(this.path);
|
||||
this.ignoreFiles = [...(opts.ignoreFiles || [".ignore"]), ".defaultignore"];
|
||||
this.ignoreRules = {};
|
||||
this.parent = opts.parent || null;
|
||||
this.includeEmpty = !!opts.includeEmpty;
|
||||
this.root = this.parent ? this.parent.root : this.path;
|
||||
this.follow = !!opts.follow;
|
||||
this.result = this.parent ? this.parent.result : new Set();
|
||||
this.entries = null;
|
||||
this.sawError = false;
|
||||
this.exact = opts.exact;
|
||||
this.onlyDirs = opts.onlyDirs;
|
||||
// helper struct used for the DFS walk
|
||||
type WalkableEntry = {
|
||||
relPath: string;
|
||||
absPath: string;
|
||||
type: FileType;
|
||||
entry: Entry;
|
||||
};
|
||||
|
||||
if (opts.additionalIgnoreRules) {
|
||||
this.addIgnoreRules(opts.additionalIgnoreRules);
|
||||
}
|
||||
// helper struct used for the DFS walk
|
||||
type WalkContext = {
|
||||
walkableEntry: WalkableEntry;
|
||||
ignore: Ignore;
|
||||
};
|
||||
|
||||
class DFSWalker {
|
||||
private readonly path: string;
|
||||
private readonly ide: IDE;
|
||||
private readonly options: WalkerOptions;
|
||||
private readonly ignoreFileNames: Set<string>;
|
||||
|
||||
constructor(path: string, ide: IDE, options: WalkerOptions) {
|
||||
this.path = path;
|
||||
this.ide = ide;
|
||||
this.options = options;
|
||||
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
|
||||
}
|
||||
|
||||
sort(a: string, b: string): number {
|
||||
return a.localeCompare(b, "en");
|
||||
}
|
||||
|
||||
emit(ev: string, data: any): boolean {
|
||||
let ret = false;
|
||||
|
||||
if (!(this.sawError && ev === "error")) {
|
||||
if (ev === "error") {
|
||||
this.sawError = true;
|
||||
} else if (ev === "done" && !this.parent) {
|
||||
data = (Array.from(data) as any)
|
||||
.map((e: string) => (/^@/.test(e) ? `./${e}` : e))
|
||||
.sort(this.sort);
|
||||
this.result = new Set(data);
|
||||
}
|
||||
|
||||
if (ev === "error" && this.parent) {
|
||||
ret = this.parent.emit("error", data);
|
||||
} else {
|
||||
ret = super.emit(ev, data);
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
async *start() {
|
||||
try {
|
||||
const entries = await this.ide.listDir(this.path);
|
||||
|
||||
for await (const result of this.onReadDir(entries)) {
|
||||
yield result;
|
||||
}
|
||||
} catch (err) {
|
||||
this.emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
isIgnoreFile(e: Entry): boolean {
|
||||
const p = e[0];
|
||||
return p !== "." && p !== ".." && this.ignoreFiles.indexOf(p) !== -1;
|
||||
}
|
||||
|
||||
async *onReadDir(entries: Entry[]) {
|
||||
this.entries = entries;
|
||||
|
||||
if (entries.length === 0) {
|
||||
if (this.includeEmpty) {
|
||||
this.result.add(this.path.slice(this.root.length + 1));
|
||||
}
|
||||
this.emit("done", this.result);
|
||||
yield this.result;
|
||||
} else {
|
||||
const hasIg = this.entries.some((e) => this.isIgnoreFile(e));
|
||||
|
||||
if (hasIg) {
|
||||
await this.addIgnoreFiles();
|
||||
}
|
||||
|
||||
yield* this.filterEntries();
|
||||
}
|
||||
}
|
||||
|
||||
async addIgnoreFiles() {
|
||||
const newIg = this.entries!.filter((e) => this.isIgnoreFile(e));
|
||||
await Promise.all(newIg.map((e) => this.addIgnoreFile(e)));
|
||||
}
|
||||
|
||||
async addIgnoreFile(fileEntry: Entry) {
|
||||
const ig = path.resolve(this.path, fileEntry[0]);
|
||||
|
||||
try {
|
||||
const file = await this.ide.readFile(ig);
|
||||
this.onReadIgnoreFile(fileEntry, file);
|
||||
} catch (err) {
|
||||
this.emit("error", err);
|
||||
}
|
||||
}
|
||||
|
||||
onReadIgnoreFile(file: Entry, data: string): void {
|
||||
const mmopt = {
|
||||
matchBase: true,
|
||||
dot: true,
|
||||
flipNegate: true,
|
||||
nocase: true,
|
||||
// walk is a depth-first search implementation
|
||||
public async *walk(): AsyncGenerator<string> {
|
||||
const root: WalkContext = {
|
||||
walkableEntry: {
|
||||
relPath: "",
|
||||
absPath: this.path,
|
||||
type: 2 as FileType.Directory,
|
||||
entry: ["", 2 as FileType.Directory],
|
||||
},
|
||||
ignore: ignore().add(defaultIgnoreDir).add(defaultIgnoreFile),
|
||||
};
|
||||
|
||||
const rules = data
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !/^#|^$/.test(line.trim()))
|
||||
.map((rule) => {
|
||||
return new Minimatch(rule.trim(), mmopt);
|
||||
});
|
||||
|
||||
this.ignoreRules[file[0]] = rules;
|
||||
}
|
||||
|
||||
addIgnoreRules(rules: string[]) {
|
||||
const mmopt = {
|
||||
matchBase: true,
|
||||
dot: true,
|
||||
flipNegate: true,
|
||||
nocase: true,
|
||||
};
|
||||
|
||||
const minimatchRules = rules
|
||||
.filter((line) => !/^#|^$/.test(line.trim()))
|
||||
.map((rule) => {
|
||||
return new Minimatch(rule.trim(), mmopt);
|
||||
});
|
||||
|
||||
this.ignoreRules[".defaultignore"] = minimatchRules;
|
||||
}
|
||||
|
||||
async *filterEntries() {
|
||||
const filtered = (await Promise.all(
|
||||
this.entries!.map(async (entry) => {
|
||||
const passFile = await this.filterEntry(entry[0]);
|
||||
const passDir = await this.filterEntry(entry[0], true);
|
||||
return passFile || passDir ? [entry, passFile, passDir] : false;
|
||||
}),
|
||||
).then((entries) => entries.filter((e) => e))) as [
|
||||
Entry,
|
||||
boolean,
|
||||
boolean,
|
||||
][];
|
||||
let entryCount = filtered.length;
|
||||
if (entryCount === 0) {
|
||||
this.emit("done", this.result);
|
||||
yield this.result;
|
||||
} else {
|
||||
const then = () => {
|
||||
if (--entryCount === 0) {
|
||||
// Otherwise in onlyDirs mode, nothing would be returned
|
||||
if (this.onlyDirs && this.path !== this.root) {
|
||||
this.result.add(this.path.slice(this.root.length + 1));
|
||||
}
|
||||
this.emit("done", this.result);
|
||||
}
|
||||
};
|
||||
|
||||
for (const [entry, file, dir] of filtered) {
|
||||
for await (const statResult of this.stat(entry, file, dir, then)) {
|
||||
yield statResult;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
entryIsDirectory(entry: Entry) {
|
||||
const Directory = 2 as FileType.Directory;
|
||||
return entry[1] === Directory;
|
||||
}
|
||||
|
||||
entryIsSymlink(entry: Entry) {
|
||||
const Directory = 64 as FileType.SymbolicLink;
|
||||
return entry[1] === Directory;
|
||||
}
|
||||
|
||||
async *onstat(entry: Entry, file: boolean, dir: boolean, then: () => void) {
|
||||
const abs = this.path + "/" + entry[0];
|
||||
const isSymbolicLink = this.entryIsSymlink(entry);
|
||||
if (!this.entryIsDirectory(entry)) {
|
||||
if (file && !this.onlyDirs) {
|
||||
this.result.add(abs.slice(this.root.length + 1));
|
||||
}
|
||||
then();
|
||||
yield this.result;
|
||||
} else {
|
||||
if (dir) {
|
||||
yield* this.walker(
|
||||
entry[0],
|
||||
{ isSymbolicLink, exact: await this.filterEntry(entry[0] + "/") },
|
||||
then,
|
||||
);
|
||||
} else {
|
||||
then();
|
||||
yield this.result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async *stat(
|
||||
entry: Entry,
|
||||
file: boolean,
|
||||
dir: boolean,
|
||||
then: () => void,
|
||||
): any {
|
||||
yield* this.onstat(entry, file, dir, then);
|
||||
}
|
||||
|
||||
walkerOpt(entry: string, opts: Partial<WalkerOptions>): WalkerOptions {
|
||||
return {
|
||||
path: this.path + "/" + entry,
|
||||
parent: this,
|
||||
ignoreFiles: this.ignoreFiles,
|
||||
follow: this.follow,
|
||||
includeEmpty: this.includeEmpty,
|
||||
onlyDirs: this.onlyDirs,
|
||||
...opts,
|
||||
};
|
||||
}
|
||||
|
||||
async *walker(entry: string, opts: Partial<WalkerOptions>, then: () => void) {
|
||||
const walker = new Walker(this.walkerOpt(entry, opts), this.ide);
|
||||
|
||||
walker.on("done", then);
|
||||
yield* walker.start();
|
||||
}
|
||||
|
||||
async filterEntry(
|
||||
entry: string,
|
||||
partial?: boolean,
|
||||
entryBasename?: string,
|
||||
): Promise<boolean> {
|
||||
let included = true;
|
||||
|
||||
if (this.parent && this.parent.filterEntry) {
|
||||
const parentEntry = this.basename + "/" + entry;
|
||||
const parentBasename = entryBasename || entry;
|
||||
included = await this.parent.filterEntry(
|
||||
parentEntry,
|
||||
partial,
|
||||
parentBasename,
|
||||
const stack = [root];
|
||||
for (let cur = stack.pop(); cur; cur = stack.pop()) {
|
||||
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
|
||||
const ignore = await this.getIgnoreToApplyInDir(
|
||||
cur.ignore,
|
||||
walkableEntries,
|
||||
);
|
||||
if (!included && !this.exact) {
|
||||
for (const w of walkableEntries) {
|
||||
if (!this.shouldInclude(w, ignore)) {
|
||||
continue;
|
||||
}
|
||||
if (this.entryIsDirectory(w.entry)) {
|
||||
stack.push({
|
||||
walkableEntry: w,
|
||||
ignore: ignore,
|
||||
});
|
||||
if (this.options.onlyDirs) {
|
||||
// when onlyDirs is enabled the walker will only return directory names
|
||||
yield w.relPath;
|
||||
}
|
||||
} else {
|
||||
yield w.relPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async listDirForWalking(
|
||||
walkableEntry: WalkableEntry,
|
||||
): Promise<WalkableEntry[]> {
|
||||
const entries = await this.ide.listDir(walkableEntry.absPath);
|
||||
return entries.map((e) => {
|
||||
return {
|
||||
relPath: path.join(walkableEntry.relPath, e[0]),
|
||||
absPath: path.join(walkableEntry.absPath, e[0]),
|
||||
type: e[1],
|
||||
entry: e,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private async getIgnoreToApplyInDir(
|
||||
parentIgnore: Ignore,
|
||||
walkableEntries: WalkableEntry[],
|
||||
): Promise<Ignore> {
|
||||
const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries);
|
||||
if (ignoreFilesInDir.length === 0) {
|
||||
return parentIgnore;
|
||||
}
|
||||
const patterns = ignoreFilesInDir.map(c => {
|
||||
return c.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => !/^#|^$/.test(l));
|
||||
}).flat();
|
||||
return ignore().add(parentIgnore).add(patterns);
|
||||
}
|
||||
|
||||
private async loadIgnoreFiles(
|
||||
entries: WalkableEntry[],
|
||||
): Promise<string[]> {
|
||||
const ignoreEntries = entries.filter((w) => this.isIgnoreFile(w.entry));
|
||||
const promises = ignoreEntries.map(async (w) => {
|
||||
return await this.ide.readFile(w.absPath);
|
||||
});
|
||||
return Promise.all(promises);
|
||||
}
|
||||
|
||||
private isIgnoreFile(e: Entry): boolean {
|
||||
const p = e[0];
|
||||
return this.ignoreFileNames.has(p);
|
||||
}
|
||||
|
||||
private shouldInclude(
|
||||
walkableEntry: WalkableEntry,
|
||||
ignore: Ignore,
|
||||
) {
|
||||
if (this.entryIsSymlink(walkableEntry.entry)) {
|
||||
// If called from the root, a symlink either links to a real file in this repository,
|
||||
// and therefore will be walked OR it linksto something outside of the repository and
|
||||
// we do not want to index it
|
||||
return false;
|
||||
}
|
||||
let relPath = walkableEntry.relPath;
|
||||
if (this.entryIsDirectory(walkableEntry.entry)) {
|
||||
relPath = `${relPath}/`;
|
||||
} else {
|
||||
if (this.options.onlyDirs) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return !ignore.ignores(relPath);
|
||||
}
|
||||
|
||||
for (const f of this.ignoreFiles) {
|
||||
if (this.ignoreRules[f]) {
|
||||
for (const rule of this.ignoreRules[f]) {
|
||||
if (rule.negate !== included) {
|
||||
const isRelativeRule =
|
||||
entryBasename &&
|
||||
rule.globParts.some(
|
||||
(part) => part.length <= (part.slice(-1)[0] ? 1 : 2),
|
||||
);
|
||||
private entryIsDirectory(entry: Entry) {
|
||||
return entry[1] === (2 as FileType.Directory);
|
||||
}
|
||||
|
||||
const match =
|
||||
rule.match("/" + entry) ||
|
||||
rule.match(entry) ||
|
||||
(!!partial &&
|
||||
(rule.match("/" + entry + "/") ||
|
||||
rule.match(entry + "/") ||
|
||||
(rule.negate &&
|
||||
(rule.match("/" + entry, true) ||
|
||||
rule.match(entry, true))) ||
|
||||
(isRelativeRule &&
|
||||
(rule.match("/" + entryBasename + "/") ||
|
||||
rule.match(entryBasename + "/") ||
|
||||
(rule.negate &&
|
||||
(rule.match("/" + entryBasename, true) ||
|
||||
rule.match(entryBasename, true)))))));
|
||||
|
||||
if (match) {
|
||||
included = rule.negate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return included;
|
||||
private entryIsSymlink(entry: Entry) {
|
||||
return entry[1] === (64 as FileType.SymbolicLink);
|
||||
}
|
||||
}
|
||||
|
||||
const defaultOptions: WalkerOptions = {
|
||||
ignoreFiles: [".gitignore", ".continueignore"],
|
||||
onlyDirs: false,
|
||||
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
|
||||
};
|
||||
|
||||
|
|
@ -337,39 +169,16 @@ export async function walkDir(
|
|||
): Promise<string[]> {
|
||||
let entries: string[] = [];
|
||||
const options = { ...defaultOptions, ..._options };
|
||||
|
||||
const walker = new Walker(
|
||||
{
|
||||
path,
|
||||
ignoreFiles: options.ignoreFiles,
|
||||
onlyDirs: options.onlyDirs,
|
||||
follow: true,
|
||||
includeEmpty: false,
|
||||
additionalIgnoreRules: options.additionalIgnoreRules,
|
||||
},
|
||||
ide,
|
||||
);
|
||||
|
||||
try {
|
||||
for await (const walkedEntries of walker.start()) {
|
||||
entries = [...walkedEntries];
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Error walking directories: ${err}`);
|
||||
throw err;
|
||||
const dfsWalker = new DFSWalker(path, ide, options);
|
||||
let relativePaths: string[] = [];
|
||||
for await (const e of dfsWalker.walk()) {
|
||||
relativePaths.push(e);
|
||||
}
|
||||
|
||||
const relativePaths = entries || [];
|
||||
|
||||
if (options?.returnRelativePaths) {
|
||||
return relativePaths;
|
||||
}
|
||||
|
||||
const pathSep = await ide.pathSep();
|
||||
const prefix = options.returnRelativePaths ? "" : path + pathSep;
|
||||
|
||||
if (pathSep === "/") {
|
||||
return relativePaths.map((p) => path + pathSep + p);
|
||||
return relativePaths.map((p) => prefix + p);
|
||||
}
|
||||
|
||||
return relativePaths.map((p) => path + pathSep + p.split("/").join(pathSep));
|
||||
return relativePaths.map((p) => prefix + p.split("/").join(pathSep));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,13 @@
|
|||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
process.env.NODE_OPTIONS = "--experimental-vm-modules";
|
||||
|
||||
export default {
|
||||
transform: {
|
||||
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
|
||||
"^.+\\.(ts|js)$": ["ts-jest", { useESM: true, useIsolatedModules: true }],
|
||||
},
|
||||
|
||||
moduleNameMapper: {
|
||||
"(.+)\\.js": "$1",
|
||||
"^(\\.{1,2}/.*)\\.js$": "$1",
|
||||
"^uuid$": "uuid", // https://stackoverflow.com/a/73626360
|
||||
},
|
||||
extensionsToTreatAsEsm: [".ts"],
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
|
|
@ -20,4 +18,5 @@ export default {
|
|||
__filename: path.resolve(fileURLToPath(import.meta.url)),
|
||||
},
|
||||
globalSetup: "<rootDir>/jest.global-setup.ts",
|
||||
setupFilesAfterEnv: ["<rootDir>/jest.setup-after-env.ts"],
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
// jest.global-setup.js
|
||||
import path from "path";
|
||||
|
||||
export default async function () {
|
||||
|
|
|
|||
16
core/jest.setup-after-env.ts
Normal file
16
core/jest.setup-after-env.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055
|
||||
import { TextEncoder, TextDecoder } from "util";
|
||||
import fetch, { Request, Response } from "node-fetch";
|
||||
import { jest } from "@jest/globals";
|
||||
|
||||
if (process.env.DEBUG === "jest") {
|
||||
jest.setTimeout(5 * 60 * 1000);
|
||||
}
|
||||
|
||||
const globalThis = global as any;
|
||||
|
||||
globalThis.fetch = fetch;
|
||||
globalThis.Request = Request;
|
||||
globalThis.Response = Response;
|
||||
globalThis.TextEncoder = TextEncoder;
|
||||
globalThis.TextDecoder = TextDecoder;
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue