Merge branch 'preview' into patch-1

This commit is contained in:
lmaosweqf1 2024-04-04 10:29:47 +03:00 • committed by GitHub
commit e4d7b16238
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
147 changed files with 5501 additions and 4330 deletions

6
.vscode/launch.json vendored
View file

@ -10,9 +10,9 @@
"request": "launch",
"name": "Core Binary",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/pkg/out/index.js",
"preLaunchTask": "pkg:esbuild",
"outFiles": ["${workspaceFolder}/pkg/out/**/*.js"],
"program": "${workspaceFolder}/binary/out/index.js",
"preLaunchTask": "binary:esbuild",
"outFiles": ["${workspaceFolder}/binary/out/**/*.js"],
"sourceMaps": true,
"smartStep": true,
"internalConsoleOptions": "openOnSessionStart"

6
.vscode/tasks.json vendored
View file

@ -142,17 +142,17 @@
}
}
]
},
},
//
// esbuild for the core binary
{
"label": "pkg:esbuild",
"label": "binary:esbuild",
"type": "shell",
"command": "npm",
"args": ["run", "esbuild"],
"problemMatcher": [],
"options": {
"cwd": "pkg"
"cwd": "binary"
}
}
]

View file

@ -93,7 +93,7 @@ Pre-requisite: You should use the Intellij IDE, which can be downloaded [here](h
> For changes to Typescript code, the binary/gui will currently need to be rebuilt. Changes to Kotlin code can often be hot-reloaded with "Run -> Debugging Actions -> Reload Changed Classes"
Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `pkg` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file.
Continue's JetBrains extension shares much of the code with the VS Code extension by utilizing shared code in the `core` directory and packaging it in a binary in the `binary` directory. The Intellij extension (written in Kotlin) is then able to communicate over stdin/stdout in the [CoreMessenger.kt](./extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt) file.
### Formatting

View file

View file

@ -90,7 +90,7 @@ const targetToLanceDb = {
entryPoints: ["src/index.ts"],
bundle: true,
outfile: esbuildOutputFile,
external: ["esbuild", ...DYNAMIC_IMPORTS],
external: ["esbuild", ...DYNAMIC_IMPORTS, "./xhr-sync-worker.js"],
format: "cjs",
platform: "node",
sourcemap: true,
@ -118,6 +118,7 @@ const targetToLanceDb = {
console.log("[info] Building binaries with pkg...");
for (const target of targets) {
const targetDir = `bin/${target}`;
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[info] Building ${target}...`);
execSync(
`npx pkg --no-bytecode --public-packages "*" --public pkgJson/${target} --out-path ${targetDir}`,
@ -141,6 +142,7 @@ const targetToLanceDb = {
// Download and unzip prebuilt esbuild binary for the target
console.log(`[info] Downloading esbuild for ${target}...`);
// Version is pinned to 0.19.11 in package.json to make sure that they match
execSync(
`curl -o ${targetDir}/esbuild.tgz https://registry.npmjs.org/@esbuild/${target}/-/${target}-0.19.11.tgz`,
);

View file

@ -1,11 +1,11 @@
{
"name": "pkg",
"name": "binary",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pkg",
"name": "binary",
"version": "1.0.0",
"license": "Apache-2.0",
"dependencies": {
@ -19,20 +19,20 @@
"vectordb": "^0.4.10"
},
"bin": {
"pkg": "out/index.js"
"binary": "out/index.js"
},
"devDependencies": {
"@types/follow-redirects": "^1.14.4",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"esbuild": "^0.19.11",
"esbuild": "0.19.11",
"pkg": "^5.8.1",
"typescript": "^5.3.3"
}
},
"../core": {
"name": "@continuedev/core",
"version": "1.0.4",
"version": "1.0.6",
"license": "Apache-2.0",
"dependencies": {
"@mozilla/readability": "^0.5.0",
@ -52,6 +52,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
@ -69,7 +70,7 @@
"sqlite3": "^5.1.7",
"tree-sitter-wasms": "^0.1.6",
"uuid": "^9.0.1",
"vectordb": "^0.4.12",
"vectordb": "0.4.12",
"web-tree-sitter": "^0.21.0"
},
"devDependencies": {
@ -142,9 +143,9 @@
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.23.4",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz",
"integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==",
"version": "7.24.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.24.1.tgz",
"integrity": "sha512-2ofRCjnnA9y+wk8b9IAREroeUP02KHp431N2mhKniy2yKIDKpbrHv9eXwm8cBeWQYcJmzv5qKCu65P47eCF7CQ==",
"dev": true,
"engines": {
"node": ">=6.9.0"
@ -186,9 +187,9 @@
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.12.tgz",
"integrity": "sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.11.tgz",
"integrity": "sha512-FnzU0LyE3ySQk7UntJO4+qIiQgI7KoODnZg5xzXIrFJlKd2P2gwHsHY4927xj9y5PJmJSzULiUCWmv7iWnNa7g==",
"cpu": [
"ppc64"
],
@ -202,9 +203,9 @@
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.12.tgz",
"integrity": "sha512-qg/Lj1mu3CdQlDEEiWrlC4eaPZ1KztwGJ9B6J+/6G+/4ewxJg7gqj8eVYWvao1bXrqGiW2rsBZFSX3q2lcW05w==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.11.tgz",
"integrity": "sha512-5OVapq0ClabvKvQ58Bws8+wkLCV+Rxg7tUVbo9xu034Nm536QTII4YzhaFriQ7rMrorfnFKUsArD2lqKbFY4vw==",
"cpu": [
"arm"
],
@ -218,9 +219,9 @@
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.12.tgz",
"integrity": "sha512-P0UVNGIienjZv3f5zq0DP3Nt2IE/3plFzuaS96vihvD0Hd6H/q4WXUGpCxD/E8YrSXfNyRPbpTq+T8ZQioSuPA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.11.tgz",
"integrity": "sha512-aiu7K/5JnLj//KOnOfEZ0D90obUkRzDMyqd/wNAUQ34m4YUPVhRZpnqKV9uqDGxT7cToSDnIHsGooyIczu9T+Q==",
"cpu": [
"arm64"
],
@ -234,9 +235,9 @@
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.12.tgz",
"integrity": "sha512-3k7ZoUW6Q6YqhdhIaq/WZ7HwBpnFBlW905Fa4s4qWJyiNOgT1dOqDiVAQFwBH7gBRZr17gLrlFCRzF6jFh7Kew==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.11.tgz",
"integrity": "sha512-eccxjlfGw43WYoY9QgB82SgGgDbibcqyDTlk3l3C0jOVHKxrjdc9CTwDUQd0vkvYg5um0OH+GpxYvp39r+IPOg==",
"cpu": [
"x64"
],
@ -250,9 +251,9 @@
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.12.tgz",
"integrity": "sha512-B6IeSgZgtEzGC42jsI+YYu9Z3HKRxp8ZT3cqhvliEHovq8HSX2YX8lNocDn79gCKJXOSaEot9MVYky7AKjCs8g==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.11.tgz",
"integrity": "sha512-ETp87DRWuSt9KdDVkqSoKoLFHYTrkyz2+65fj9nfXsaV3bMhTCjtQfw3y+um88vGRKRiF7erPrh/ZuIdLUIVxQ==",
"cpu": [
"arm64"
],
@ -266,9 +267,9 @@
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.12.tgz",
"integrity": "sha512-hKoVkKzFiToTgn+41qGhsUJXFlIjxI/jSYeZf3ugemDYZldIXIxhvwN6erJGlX4t5h417iFuheZ7l+YVn05N3A==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.11.tgz",
"integrity": "sha512-fkFUiS6IUK9WYUO/+22omwetaSNl5/A8giXvQlcinLIjVkxwTLSktbF5f/kJMftM2MJp9+fXqZ5ezS7+SALp4g==",
"cpu": [
"x64"
],
@ -282,9 +283,9 @@
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.12.tgz",
"integrity": "sha512-4aRvFIXmwAcDBw9AueDQ2YnGmz5L6obe5kmPT8Vd+/+x/JMVKCgdcRwH6APrbpNXsPz+K653Qg8HB/oXvXVukA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.11.tgz",
"integrity": "sha512-lhoSp5K6bxKRNdXUtHoNc5HhbXVCS8V0iZmDvyWvYq9S5WSfTIHU2UGjcGt7UeS6iEYp9eeymIl5mJBn0yiuxA==",
"cpu": [
"arm64"
],
@ -298,9 +299,9 @@
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.12.tgz",
"integrity": "sha512-EYoXZ4d8xtBoVN7CEwWY2IN4ho76xjYXqSXMNccFSx2lgqOG/1TBPW0yPx1bJZk94qu3tX0fycJeeQsKovA8gg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.11.tgz",
"integrity": "sha512-JkUqn44AffGXitVI6/AbQdoYAq0TEullFdqcMY/PCUZ36xJ9ZJRtQabzMA+Vi7r78+25ZIBosLTOKnUXBSi1Kw==",
"cpu": [
"x64"
],
@ -314,9 +315,9 @@
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.12.tgz",
"integrity": "sha512-J5jPms//KhSNv+LO1S1TX1UWp1ucM6N6XuL6ITdKWElCu8wXP72l9MM0zDTzzeikVyqFE6U8YAV9/tFyj0ti+w==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.11.tgz",
"integrity": "sha512-3CRkr9+vCV2XJbjwgzjPtO8T0SZUmRZla+UL1jw+XqHZPkPgZiyWvbDvl9rqAN8Zl7qJF0O/9ycMtjU67HN9/Q==",
"cpu": [
"arm"
],
@ -330,9 +331,9 @@
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.12.tgz",
"integrity": "sha512-EoTjyYyLuVPfdPLsGVVVC8a0p1BFFvtpQDB/YLEhaXyf/5bczaGeN15QkR+O4S5LeJ92Tqotve7i1jn35qwvdA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.11.tgz",
"integrity": "sha512-LneLg3ypEeveBSMuoa0kwMpCGmpu8XQUh+mL8XXwoYZ6Be2qBnVtcDI5azSvh7vioMDhoJFZzp9GWp9IWpYoUg==",
"cpu": [
"arm64"
],
@ -346,9 +347,9 @@
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.12.tgz",
"integrity": "sha512-Thsa42rrP1+UIGaWz47uydHSBOgTUnwBwNq59khgIwktK6x60Hivfbux9iNR0eHCHzOLjLMLfUMLCypBkZXMHA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.11.tgz",
"integrity": "sha512-caHy++CsD8Bgq2V5CodbJjFPEiDPq8JJmBdeyZ8GWVQMjRD0sU548nNdwPNvKjVpamYYVL40AORekgfIubwHoA==",
"cpu": [
"ia32"
],
@ -362,9 +363,9 @@
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.12.tgz",
"integrity": "sha512-LiXdXA0s3IqRRjm6rV6XaWATScKAXjI4R4LoDlvO7+yQqFdlr1Bax62sRwkVvRIrwXxvtYEHHI4dm50jAXkuAA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.11.tgz",
"integrity": "sha512-ppZSSLVpPrwHccvC6nQVZaSHlFsvCQyjnvirnVjbKSHuE5N24Yl8F3UwYUUR1UEPaFObGD2tSvVKbvR+uT1Nrg==",
"cpu": [
"loong64"
],
@ -378,9 +379,9 @@
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.12.tgz",
"integrity": "sha512-fEnAuj5VGTanfJ07ff0gOA6IPsvrVHLVb6Lyd1g2/ed67oU1eFzL0r9WL7ZzscD+/N6i3dWumGE1Un4f7Amf+w==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.11.tgz",
"integrity": "sha512-B5x9j0OgjG+v1dF2DkH34lr+7Gmv0kzX6/V0afF41FkPMMqaQ77pH7CrhWeR22aEeHKaeZVtZ6yFwlxOKPVFyg==",
"cpu": [
"mips64el"
],
@ -394,9 +395,9 @@
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.12.tgz",
"integrity": "sha512-nYJA2/QPimDQOh1rKWedNOe3Gfc8PabU7HT3iXWtNUbRzXS9+vgB0Fjaqr//XNbd82mCxHzik2qotuI89cfixg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.11.tgz",
"integrity": "sha512-MHrZYLeCG8vXblMetWyttkdVRjQlQUb/oMgBNurVEnhj4YWOr4G5lmBfZjHYQHHN0g6yDmCAQRR8MUHldvvRDA==",
"cpu": [
"ppc64"
],
@ -410,9 +411,9 @@
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.12.tgz",
"integrity": "sha512-2MueBrlPQCw5dVJJpQdUYgeqIzDQgw3QtiAHUC4RBz9FXPrskyyU3VI1hw7C0BSKB9OduwSJ79FTCqtGMWqJHg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.11.tgz",
"integrity": "sha512-f3DY++t94uVg141dozDu4CCUkYW+09rWtaWfnb3bqe4w5NqmZd6nPVBm+qbz7WaHZCoqXqHz5p6CM6qv3qnSSQ==",
"cpu": [
"riscv64"
],
@ -426,9 +427,9 @@
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.12.tgz",
"integrity": "sha512-+Pil1Nv3Umes4m3AZKqA2anfhJiVmNCYkPchwFJNEJN5QxmTs1uzyy4TvmDrCRNT2ApwSari7ZIgrPeUx4UZDg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.11.tgz",
"integrity": "sha512-A5xdUoyWJHMMlcSMcPGVLzYzpcY8QP1RtYzX5/bS4dvjBGVxdhuiYyFwp7z74ocV7WDc0n1harxmpq2ePOjI0Q==",
"cpu": [
"s390x"
],
@ -442,9 +443,9 @@
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.12.tgz",
"integrity": "sha512-B71g1QpxfwBvNrfyJdVDexenDIt1CiDN1TIXLbhOw0KhJzE78KIFGX6OJ9MrtC0oOqMWf+0xop4qEU8JrJTwCg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.11.tgz",
"integrity": "sha512-grbyMlVCvJSfxFQUndw5mCtWs5LO1gUlwP4CDi4iJBbVpZcqLVT29FxgGuBJGSzyOxotFG4LoO5X+M1350zmPA==",
"cpu": [
"x64"
],
@ -458,9 +459,9 @@
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.12.tgz",
"integrity": "sha512-3ltjQ7n1owJgFbuC61Oj++XhtzmymoCihNFgT84UAmJnxJfm4sYCiSLTXZtE00VWYpPMYc+ZQmB6xbSdVh0JWA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.11.tgz",
"integrity": "sha512-13jvrQZJc3P230OhU8xgwUnDeuC/9egsjTkXN49b3GcS5BKvJqZn86aGM8W9pd14Kd+u7HuFBMVtrNGhh6fHEQ==",
"cpu": [
"x64"
],
@ -474,9 +475,9 @@
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.12.tgz",
"integrity": "sha512-RbrfTB9SWsr0kWmb9srfF+L933uMDdu9BIzdA7os2t0TXhCRjrQyCeOt6wVxr79CKD4c+p+YhCj31HBkYcXebw==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.11.tgz",
"integrity": "sha512-ysyOGZuTp6SNKPE11INDUeFVVQFrhcNDVUgSQVDzqsqX38DjhPEPATpid04LCoUr2WXhQTEZ8ct/EgJCUDpyNw==",
"cpu": [
"x64"
],
@ -490,9 +491,9 @@
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.12.tgz",
"integrity": "sha512-HKjJwRrW8uWtCQnQOz9qcU3mUZhTUQvi56Q8DPTLLB+DawoiQdjsYq+j+D3s9I8VFtDr+F9CjgXKKC4ss89IeA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.11.tgz",
"integrity": "sha512-Hf+Sad9nVwvtxy4DXCZQqLpgmRTQqyFyhT3bZ4F2XlJCjxGmRFF0Shwn9rzhOYRB61w9VMXUkxlBy56dk9JJiQ==",
"cpu": [
"x64"
],
@ -506,9 +507,9 @@
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.12.tgz",
"integrity": "sha512-URgtR1dJnmGvX864pn1B2YUYNzjmXkuJOIqG2HdU62MVS4EHpU2946OZoTMnRUHklGtJdJZ33QfzdjGACXhn1A==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.11.tgz",
"integrity": "sha512-0P58Sbi0LctOMOQbpEOvOL44Ne0sqbS0XWHMvvrg6NE5jQ1xguCSSw9jQeUk2lfrXYsKDdOe6K+oZiwKPilYPQ==",
"cpu": [
"arm64"
],
@ -522,9 +523,9 @@
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.12.tgz",
"integrity": "sha512-+ZOE6pUkMOJfmxmBZElNOx72NKpIa/HFOMGzu8fqzQJ5kgf6aTGrcJaFsNiVMH4JKpMipyK+7k0n2UXN7a8YKQ==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.11.tgz",
"integrity": "sha512-6YOrWS+sDJDmshdBIQU+Uoyh7pQKrdykdefC1avn76ss5c+RN6gut3LZA4E2cH5xUEp5/cA0+YxRaVtRAb0xBg==",
"cpu": [
"ia32"
],
@ -538,9 +539,9 @@
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.12.tgz",
"integrity": "sha512-T1QyPSDCyMXaO3pzBkF96E8xMkiRYbUEZADd29SyPGabqxMViNoii+NcK7eWJAEoU6RZyEm5lVSIjTmcdoB9HA==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.11.tgz",
"integrity": "sha512-vfkhltrjCAb603XaFhqhAF4LGDi2M4OrCRrFusyQ+iTLQ/o60QQXxc9cZC/FFpihBI9N1Grn6SMKVJ4KP7Fuiw==",
"cpu": [
"x64"
],
@ -602,9 +603,9 @@
}
},
"node_modules/@lancedb/vectordb-darwin-arm64": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.12.tgz",
"integrity": "sha512-38/rkJRlWXkPWXuj9onzvbrhnIWcIUQjgEp5G9v5ixPosBowm7A4j8e2Q8CJMsVSNcVX2JLqwWVldiWegZFuYw==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-arm64/-/vectordb-darwin-arm64-0.4.15.tgz",
"integrity": "sha512-asNVd0ojbExbj/iRCFu/+vpnnGtAHbrn7AjrL1PFeSl1JvsvzeZBBxq+WlM4UfGKfiJhkyBvQwh609OiCP3Snw==",
"cpu": [
"arm64"
],
@ -614,9 +615,9 @@
]
},
"node_modules/@lancedb/vectordb-darwin-x64": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.12.tgz",
"integrity": "sha512-psE48dztyO450hXWdv9Rl9aayM2HQ1uF9wErfC0gKmDUh1N0NdVq2viDuFpZxnmCis/nvGwKlYiYT9OnYNCJ9g==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-darwin-x64/-/vectordb-darwin-x64-0.4.15.tgz",
"integrity": "sha512-tbMGb1P9KXdnoP6dqFnjhUUjGIVzzo2V/Ewc8iktMU1scCVQ7/rEPPvTh9jHuM1r1i+wVTNtKYijIVaHZZPJLA==",
"cpu": [
"x64"
],
@ -626,9 +627,9 @@
]
},
"node_modules/@lancedb/vectordb-linux-arm64-gnu": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.12.tgz",
"integrity": "sha512-xwkgF6MiF5aAdG9JG8v4ke652YxUJrhs9z4OrsEfrENnvsIQd2C5UyKMepVLdvij4BI/XPFRFWXdjPvP7S9rTA==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-arm64-gnu/-/vectordb-linux-arm64-gnu-0.4.15.tgz",
"integrity": "sha512-5oiWvS9Y5mRc2PhaVzu9zoM1UFf77gDgX8IM95U87CZZdPAoREDvnbVhyIZa2SEZccEjLG7tShe+PJsOFWOT/w==",
"cpu": [
"arm64"
],
@ -638,9 +639,9 @@
]
},
"node_modules/@lancedb/vectordb-linux-x64-gnu": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.12.tgz",
"integrity": "sha512-gJqYR0aymrS+C60xc4EQPzmQ5/69XfeFv2ofBvAj7qW+c6BcnoAcfVl+7s1IrcWeGz251sm5cD5Lx4AzJd89dA==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-linux-x64-gnu/-/vectordb-linux-x64-gnu-0.4.15.tgz",
"integrity": "sha512-FjlrV2h97t5aoammRpPSBjws2cWSKYQpzALHm8Af8QjTuvo9J/MD63Fr/D6Sb9Ie2ER3pCiWD1o8UCFndCFtRg==",
"cpu": [
"x64"
],
@ -650,9 +651,9 @@
]
},
"node_modules/@lancedb/vectordb-win32-x64-msvc": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.12.tgz",
"integrity": "sha512-LhCzpyEeBUyO6L2fuVqeP3mW8kYDryyU9PNqcM01m88sZB1Do6AlwiM+GjPRQ0SpzD0LK9oxQqSmJrdcNGqjbw==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/@lancedb/vectordb-win32-x64-msvc/-/vectordb-win32-x64-msvc-0.4.15.tgz",
"integrity": "sha512-o3zlY/FnY426kp2Y7xn4UbD6/Oeg5xqtezYNhhmt44lCmhSlpydx+2m9Fq1OGSDNUCWtrhMhgdHVnGTu2VTa5A==",
"cpu": [
"x64"
],
@ -980,11 +981,11 @@
}
},
"node_modules/axios": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz",
"integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==",
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"dependencies": {
"follow-redirects": "^1.15.4",
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
@ -1270,9 +1271,9 @@
"integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ=="
},
"node_modules/detect-libc": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
"integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==",
"dev": true,
"engines": {
"node": ">=8"
@ -1306,9 +1307,9 @@
}
},
"node_modules/esbuild": {
"version": "0.19.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.12.tgz",
"integrity": "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg==",
"version": "0.19.11",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.11.tgz",
"integrity": "sha512-HJ96Hev2hX/6i5cDVwcqiJBBtuo9+FeIJOtZ9W1kA5M6AMJRHUZlpYZ1/SbEwtO0ioNAW8rUooVpC/WehY2SfA==",
"dev": true,
"hasInstallScript": true,
"bin": {
@ -1318,29 +1319,29 @@
"node": ">=12"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.19.12",
"@esbuild/android-arm": "0.19.12",
"@esbuild/android-arm64": "0.19.12",
"@esbuild/android-x64": "0.19.12",
"@esbuild/darwin-arm64": "0.19.12",
"@esbuild/darwin-x64": "0.19.12",
"@esbuild/freebsd-arm64": "0.19.12",
"@esbuild/freebsd-x64": "0.19.12",
"@esbuild/linux-arm": "0.19.12",
"@esbuild/linux-arm64": "0.19.12",
"@esbuild/linux-ia32": "0.19.12",
"@esbuild/linux-loong64": "0.19.12",
"@esbuild/linux-mips64el": "0.19.12",
"@esbuild/linux-ppc64": "0.19.12",
"@esbuild/linux-riscv64": "0.19.12",
"@esbuild/linux-s390x": "0.19.12",
"@esbuild/linux-x64": "0.19.12",
"@esbuild/netbsd-x64": "0.19.12",
"@esbuild/openbsd-x64": "0.19.12",
"@esbuild/sunos-x64": "0.19.12",
"@esbuild/win32-arm64": "0.19.12",
"@esbuild/win32-ia32": "0.19.12",
"@esbuild/win32-x64": "0.19.12"
"@esbuild/aix-ppc64": "0.19.11",
"@esbuild/android-arm": "0.19.11",
"@esbuild/android-arm64": "0.19.11",
"@esbuild/android-x64": "0.19.11",
"@esbuild/darwin-arm64": "0.19.11",
"@esbuild/darwin-x64": "0.19.11",
"@esbuild/freebsd-arm64": "0.19.11",
"@esbuild/freebsd-x64": "0.19.11",
"@esbuild/linux-arm": "0.19.11",
"@esbuild/linux-arm64": "0.19.11",
"@esbuild/linux-ia32": "0.19.11",
"@esbuild/linux-loong64": "0.19.11",
"@esbuild/linux-mips64el": "0.19.11",
"@esbuild/linux-ppc64": "0.19.11",
"@esbuild/linux-riscv64": "0.19.11",
"@esbuild/linux-s390x": "0.19.11",
"@esbuild/linux-x64": "0.19.11",
"@esbuild/netbsd-x64": "0.19.11",
"@esbuild/openbsd-x64": "0.19.11",
"@esbuild/sunos-x64": "0.19.11",
"@esbuild/win32-arm64": "0.19.11",
"@esbuild/win32-ia32": "0.19.11",
"@esbuild/win32-x64": "0.19.11"
}
},
"node_modules/escalade": {
@ -1881,9 +1882,9 @@
}
},
"node_modules/node-abi": {
"version": "3.56.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.56.0.tgz",
"integrity": "sha512-fZjdhDOeRcaS+rcpve7XuwHBmktS1nS1gzgghwKUQQ8nTy2FdSDr6ZT8k6YhvlJeHmmQMYiT/IH9hfco5zeW2Q==",
"version": "3.57.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.57.0.tgz",
"integrity": "sha512-Dp+A9JWxRaKuHP35H77I4kCKesDy5HUDEmScia2FyncMTOXASMyg251F5PhFoDA5uqBrDDffiLpbqnrZmNXW+g==",
"dev": true,
"dependencies": {
"semver": "^7.3.5"
@ -2510,9 +2511,9 @@
}
},
"node_modules/typescript": {
"version": "5.4.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.2.tgz",
"integrity": "sha512-+2/g0Fds1ERlP6JsakQQDXjZdZMM+rqpamFZJEKh4kwTIn3iDkgKtby0CeNd5ATNZ4Ry1ax15TMx0W2V+miizQ==",
"version": "5.4.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.3.tgz",
"integrity": "sha512-KrPd3PKaCLr78MalgiwJnA25Nm8HAmdwN3mYUYZgG/wizIo9EainNVQI9/yDavtVFRN2h3k8uf3GLHuhDMgEHg==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
@ -2564,9 +2565,9 @@
}
},
"node_modules/vectordb": {
"version": "0.4.12",
"resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.12.tgz",
"integrity": "sha512-H2mFwZ87d3BcuX4yGx5RoW06amRZQ3W5u/FRTNc86rwVINuEEa+Ivsqng1i8hURHXoTDbF/0Y9qwCshySkeznQ==",
"version": "0.4.15",
"resolved": "https://registry.npmjs.org/vectordb/-/vectordb-0.4.15.tgz",
"integrity": "sha512-iROQ92CUGHj+kDUFVCdIk1Wvqg/pGE6WHhBlOorgRXHZwiFjP2SwmcDZeW7c7lH2hXC5Sks8MAGlglPstCpELQ==",
"cpu": [
"x64",
"arm64"
@ -2581,11 +2582,11 @@
"axios": "^1.4.0"
},
"optionalDependencies": {
"@lancedb/vectordb-darwin-arm64": "0.4.12",
"@lancedb/vectordb-darwin-x64": "0.4.12",
"@lancedb/vectordb-linux-arm64-gnu": "0.4.12",
"@lancedb/vectordb-linux-x64-gnu": "0.4.12",
"@lancedb/vectordb-win32-x64-msvc": "0.4.12"
"@lancedb/vectordb-darwin-arm64": "0.4.15",
"@lancedb/vectordb-darwin-x64": "0.4.15",
"@lancedb/vectordb-linux-arm64-gnu": "0.4.15",
"@lancedb/vectordb-linux-x64-gnu": "0.4.15",
"@lancedb/vectordb-win32-x64-msvc": "0.4.15"
},
"peerDependencies": {
"@apache-arrow/ts": "^14.0.2",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "binary",
"version": "1.0.0",
"description": "",
"main": "out/index.js",
@ -32,7 +32,7 @@
"@types/follow-redirects": "^1.14.4",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"esbuild": "^0.19.11",
"esbuild": "0.19.11",
"pkg": "^5.8.1",
"typescript": "^5.3.3"
},

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -1,5 +1,5 @@
{
"name": "pkg",
"name": "continue-binary",
"version": "1.0.0",
"description": "",
"bin": "../../out/index.js",

View file

@ -9,6 +9,7 @@ import { logDevData } from "core/util/devdata";
import historyManager from "core/util/history";
import { Message } from "core/util/messenger";
import { Telemetry } from "core/util/posthog";
import { streamDiffLines } from "core/util/verticalEdit";
import { v4 as uuidv4 } from "uuid";
import { IpcMessenger } from "./messenger";
import { Protocol } from "./protocol";
@ -47,6 +48,8 @@ export class Core {
this.configHandler,
this.ide,
new PauseToken(false),
undefined, // TODO
Promise.resolve(undefined), // TODO
);
const getLlm = async () => {
@ -293,6 +296,36 @@ export class Core {
on("autocomplete/cancel", async (msg) => {
this.completionProvider.cancel();
});
async function* streamDiffLinesGenerator(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,
msg: Message<Protocol["streamDiffLines"][0]>,
) {
const data = msg.data;
const llm = await configHandler.llmFromTitle(msg.data.modelTitle);
for await (const diffLine of streamDiffLines(
data.prefix,
data.highlighted,
data.suffix,
llm,
data.input,
data.language,
)) {
if (abortedMessageIds.has(msg.messageId)) {
abortedMessageIds.delete(msg.messageId);
break;
}
console.log(diffLine);
yield { content: diffLine };
}
return { done: true };
}
on("streamDiffLines", (msg) =>
streamDiffLinesGenerator(this.configHandler, this.abortedMessageIds, msg),
);
}
public invoke<T extends keyof Protocol>(

View file

@ -18,6 +18,7 @@ import {
import { AutocompleteLanguageInfo } from "./languages";
import {
avoidPathLine,
noTopLevelKeywordsMidline,
stopAtLines,
stopAtRepeatingLines,
stopAtSimilarLine,
@ -37,7 +38,7 @@ export interface AutocompleteInput {
clipboardText: string;
}
export interface AutocompleteOutcome {
export interface AutocompleteOutcome extends TabAutocompleteOptions {
accepted?: boolean;
time: number;
prompt: string;
@ -53,7 +54,7 @@ const autocompleteCache = AutocompleteLruCache.get();
function formatExternalSnippet(
filepath: string,
snippet: string,
language: AutocompleteLanguageInfo
language: AutocompleteLanguageInfo,
) {
const comment = language.comment;
const lines = [
@ -78,8 +79,8 @@ export async function getTabCompletion(
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE
) => Promise<AutocompleteSnippet[]>
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
): Promise<AutocompleteOutcome | undefined> {
const startTime = Date.now();
@ -129,7 +130,7 @@ export async function getTabCompletion(
filepath,
fullPrefix + fullSuffix,
fullPrefix.length,
ide
ide,
),
new Promise((resolve) => {
setTimeout(() => resolve([]), 100);
@ -155,7 +156,7 @@ export async function getTabCompletion(
recentlyEditedRanges,
recentlyEditedFiles,
llm.model,
extrasSnippets
extrasSnippets,
);
// Template prompt
@ -172,7 +173,7 @@ export async function getTabCompletion(
// Format snippets as comments and prepend to prefix
const formattedSnippets = snippets
.map((snippet) =>
formatExternalSnippet(snippet.filepath, snippet.contents, lang)
formatExternalSnippet(snippet.filepath, snippet.contents, lang),
)
.join("\n");
if (formattedSnippets.length > 0) {
@ -233,7 +234,7 @@ export async function getTabCompletion(
raw: true,
stop,
}),
multiline
multiline,
);
// LLM
@ -242,22 +243,22 @@ export async function getTabCompletion(
for await (const update of generator) {
if (token.aborted) {
cancelled = true;
return undefined;
return;
}
yield update;
}
};
let chars = generatorWithCancellation();
const gen2 = onlyWhitespaceAfterEndOfLine(
noFirstCharNewline(chars),
lang.endOfLine
);
const lineGenerator = streamWithNewLines(
avoidPathLine(
stopAtRepeatingLines(stopAtLines(streamLines(gen2))),
lang.comment
)
);
let charGenerator = generatorWithCancellation();
charGenerator = noFirstCharNewline(charGenerator);
charGenerator = onlyWhitespaceAfterEndOfLine(charGenerator, lang.endOfLine);
let lineGenerator = streamLines(charGenerator);
lineGenerator = stopAtLines(lineGenerator);
lineGenerator = stopAtRepeatingLines(lineGenerator);
lineGenerator = avoidPathLine(lineGenerator, lang.comment);
lineGenerator = noTopLevelKeywordsMidline(lineGenerator, lang.stopWords);
lineGenerator = streamWithNewLines(lineGenerator);
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
for await (const update of finalGenerator) {
completion += update;
@ -285,6 +286,7 @@ export async function getTabCompletion(
modelName: llm.model,
completionOptions,
cacheHit,
...options,
};
}
@ -302,11 +304,11 @@ export class CompletionProvider {
filepath: string,
contents: string,
cursorIndex: number,
ide: IDE
) => Promise<AutocompleteSnippet[]>
ide: IDE,
) => Promise<AutocompleteSnippet[]>,
) {
this.generatorReuseManager = new GeneratorReuseManager(
this.onError.bind(this)
this.onError.bind(this),
);
}
@ -356,7 +358,7 @@ export class CompletionProvider {
public async provideInlineCompletionItems(
input: AutocompleteInput,
token: AbortSignal | undefined
token: AbortSignal | undefined,
): Promise<AutocompleteOutcome | undefined> {
// Create abort signal if not given
if (!token) {
@ -381,7 +383,7 @@ export class CompletionProvider {
const lastUUID = await new Promise((resolve) =>
setTimeout(() => {
resolve(CompletionProvider.lastUUID);
}, options.debounceDelay)
}, options.debounceDelay),
);
if (uuid !== lastUUID) {
return undefined;
@ -401,7 +403,7 @@ export class CompletionProvider {
// Set temperature (but don't overrride)
if (llm.completionOptions.temperature === undefined) {
llm.completionOptions.temperature = 0.0;
llm.completionOptions.temperature = 0.01;
}
const outcome = await getTabCompletion(
@ -411,7 +413,7 @@ export class CompletionProvider {
this.ide,
this.generatorReuseManager,
input,
this.getDefinitionsFromLsp
this.getDefinitionsFromLsp,
);
const completion = outcome?.completion;
@ -430,12 +432,9 @@ export class CompletionProvider {
const logRejectionTimeout = setTimeout(() => {
// Wait 10 seconds, then assume it wasn't accepted
logDevData("autocomplete", outcome);
const { prompt, completion, ...restOfOutcome } = outcome;
Telemetry.capture("autocomplete", {
accepted: outcome.accepted,
modelName: outcome.modelName,
modelProvider: outcome.modelProvider,
time: outcome.time,
cacheHit: outcome.cacheHit,
...restOfOutcome,
});
this._logRejectionTimeouts.delete(input.completionId);
}, 10_000);

View file

@ -6,7 +6,7 @@ export interface AutocompleteLanguageInfo {
// TypeScript
export const Typescript = {
stopWords: ["function", "class", "module", "export"],
stopWords: ["function", "class", "module", "export", "import"],
comment: "//",
endOfLine: [";"],
};

View file

@ -2,6 +2,22 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "..";
import { LineStream } from "../diff/util";
export async function* noTopLevelKeywordsMidline(
lines: LineStream,
topLevelKeywords: string[],
): LineStream {
for await (const line of lines) {
for (const keyword of topLevelKeywords) {
const indexOf = line.indexOf(keyword + " ");
if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") {
yield line.slice(0, indexOf);
break;
}
}
yield line;
}
}
export async function* avoidPathLine(
stream: LineStream,
comment: string,
@ -54,11 +70,11 @@ export async function* stopAtSimilarLine(
}
}
const LINES_TO_STOP_AT = ["# End of file."];
const LINES_TO_STOP_AT = ["# End of file.", "<STOP EDITING HERE"];
export async function* stopAtLines(stream: LineStream): LineStream {
for await (const line of stream) {
if (LINES_TO_STOP_AT.includes(line)) {
if (LINES_TO_STOP_AT.some((stopAt) => line.trim().includes(stopAt))) {
break;
}
yield line;
@ -69,7 +85,8 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
return (
line.trimStart().startsWith("```") ||
line.trim() === "[CODE]" ||
line.trim() === ""
line.trim() === "" ||
line.trim() === "<START EDITING HERE>"
);
}
@ -142,6 +159,9 @@ export async function* filterEnglishLinesAtStart(lines: LineStream) {
let i = 0;
let wasEnglishFirstLine = false;
for await (let line of lines) {
if (i === 0 && line.trim() === "") {
continue;
}
if (i === 0) {
if (isEnglishFirstLine(line)) {
wasEnglishFirstLine = true;

View file

@ -1,7 +1,7 @@
import { TabAutocompleteOptions } from "..";
export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
useCopyBuffer: true,
useCopyBuffer: false,
useSuffix: true,
maxPromptTokens: 500,
prefixPercentage: 0.85,

View file

@ -79,12 +79,11 @@ const deepseekFimTemplateWrongPipeChar: AutocompleteTemplate = {
};
const gptAutocompleteTemplate: AutocompleteTemplate = {
template: `Your task is to complete the line at the end of this code block:
\`\`\`
{{{prefix}}}
template: `\`\`\`
{{{prefix}}}[BLANK]{{{suffix}}}
\`\`\`
The last line is incomplete, and you should provide the rest of that line. If the line is already complete, just return a new line. Otherwise, DO NOT provide explanation, a code block, or extra whitespace, just the code that should be added to the last line to complete it:`,
Fill in the blank to complete the code block. Your response should include only the code to replace [BLANK], without surrounding backticks.`,
completionOptions: { stop: ["\n"] },
};
@ -113,7 +112,11 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
return deepseekFimTemplate;
}
if (lowerCaseModel.includes("gpt") || lowerCaseModel.includes("davinci-002")) {
if (
lowerCaseModel.includes("gpt") ||
lowerCaseModel.includes("davinci-002") ||
lowerCaseModel.includes("claude")
) {
return gptAutocompleteTemplate;
}

View file

@ -49,8 +49,9 @@ export class ListenableGenerator<T> {
async *tee(): AsyncGenerator<T> {
try {
for (const value of this._buffer) {
yield value;
let i = 0;
while (i < this._buffer.length) {
yield this._buffer[i++];
}
while (!this._isEnded) {
let resolve: (value: any) => void;
@ -58,10 +59,14 @@ export class ListenableGenerator<T> {
resolve = res;
this._listeners.add(resolve!);
});
const value = await promise;
await promise;
this._listeners.delete(resolve!);
yield value;
// Possible timing caused something to slip in between
// timers so we iterate over the buffer
while (i < this._buffer.length) {
yield this._buffer[i++];
}
}
} finally {
// this._listeners.delete(resolve!);

View file

@ -8,7 +8,7 @@ import {
} from "../../autocomplete/lineStream";
import { streamLines } from "../../diff/util";
import { stripImages } from "../../llm/countTokens";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../../util";
import { dedentAndGetCommonWhitespace } from "../../util";
import {
RangeInFileWithContents,
contextItemToRangeInFileWithContents,
@ -446,7 +446,7 @@ const EditSlashCommand: SlashCommand = {
const template = llm.promptTemplates?.edit;
let generator: AsyncGenerator<string>;
if (template) {
let rendered = renderPromptTemplate(
let rendered = llm.renderPromptTemplate(
template,
// typeof template === 'string' ? template : template.prompt,
messages.slice(0, messages.length - 1),

View file

@ -137,7 +137,4 @@ export const defaultConfigJetBrains: SerializedContinueConfig = {
params: {},
},
],
ui: {
codeBlockToolbarPosition: "top",
}
};

View file

@ -90,6 +90,7 @@ export class ConfigHandler {
await Telemetry.setup(
this.savedConfig.allowAnonymousTelemetry ?? true,
await this.ide.getUniqueId(),
ideInfo.extensionVersion,
);
return this.savedConfig;
@ -123,6 +124,10 @@ export class ConfigHandler {
const proxy = llm.requestOptions?.proxy;
llm._fetch = async (input, init) => {
if (agentOptions.rejectUnauthorized === false) {
console.log("SSL verification is disabled");
}
// Create agent
const protocol = new URL(input).protocol === "https:" ? https : http;
const agent = proxy

View file

@ -408,7 +408,6 @@ declare global {
| "open"
| "google"
| "search"
| "url"
| "tree"
| "http"
| "codebase"

View file

@ -1,43 +0,0 @@
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
class URLContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "url",
displayTitle: "URL",
description: "Attach the contents of a web page",
type: "query",
};
async getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]> {
let url = query.trim();
if (!url.startsWith("http")) {
url = "https://" + url;
}
const response = await fetch(url);
const html = await response.text();
const content = html;
const title = url
.replace("https://", "")
.replace("http://", "")
.replace("www.", "");
return [
{
content,
name: title,
description: title,
},
];
}
}
export default URLContextProvider;

View file

@ -8,18 +8,17 @@ import DocsContextProvider from "./DocsContextProvider";
import FileTreeContextProvider from "./FileTreeContextProvider";
import FolderContextProvider from "./FolderContextProvider";
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider";
import GoogleContextProvider from "./GoogleContextProvider";
import HttpContextProvider from "./HttpContextProvider";
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
import LocalsProvider from "./LocalsProvider";
import OSContextProvider from "./OSContextProvider";
import OpenFilesContextProvider from "./OpenFilesContextProvider";
import PostgresContextProvider from "./PostgresContextProvider";
import ProblemsContextProvider from "./ProblemsContextProvider";
import SearchContextProvider from "./SearchContextProvider";
import OSContextProvider from "./OSContextProvider";
import TerminalContextProvider from "./TerminalContextProvider";
import LocalsProvider from "./LocalsProvider";
import URLContextProvider from "./URLContextProvider";
import GitLabMergeRequestContextProvider from "./GitLabMergeRequestContextProvider";
const Providers: (typeof BaseContextProvider)[] = [
DiffContextProvider,
@ -28,7 +27,6 @@ const Providers: (typeof BaseContextProvider)[] = [
GoogleContextProvider,
TerminalContextProvider,
LocalsProvider,
URLContextProvider,
OpenFilesContextProvider,
HttpContextProvider,
SearchContextProvider,

View file

@ -0,0 +1,28 @@
import { Chunk } from "..";
export interface EmbeddingsCacheChunk {
vector: number[];
startLine: number;
endLine: number;
contents: string;
}
interface ArtifactReturnTypes {
chunks: Chunk[];
embeddings: EmbeddingsCacheChunk[];
}
export type ArtifactType = keyof ArtifactReturnTypes;
export interface EmbeddingsCacheResponse<T extends ArtifactType> {
files: { [cacheKey: string]: ArtifactReturnTypes[T] };
}
export interface IContinueServerClient {
getConfig(): Promise<{ configJson: string; configJs: string }>;
getFromIndexCache<T extends ArtifactType>(
keys: string[],
artifactId: T,
repoName: string | undefined,
): Promise<EmbeddingsCacheResponse<T>>;
}

View file

@ -0,0 +1,24 @@
import {
ArtifactType,
EmbeddingsCacheResponse,
IContinueServerClient,
} from "../interface";
export class ContinueServerClient implements IContinueServerClient {
constructor(
private readonly serverUrl: string,
private readonly userToken: Promise<string | undefined>,
) {}
public async getConfig(): Promise<{ configJson: string; configJs: string }> {
throw new Error("Not Implemented");
}
public async getFromIndexCache<T extends ArtifactType>(
keys: string[],
artifactId: T,
repoName: string | undefined,
): Promise<EmbeddingsCacheResponse<T>> {
return { files: {} };
}
}

View file

@ -14,6 +14,8 @@ export async function* streamDiff(
newLines: LineStream,
): AsyncGenerator<DiffLine> {
const mutatedOldLines = [...oldLines]; // be careful
// If one indentation mistake is made, others are likely. So we are more permissive about matching
let seenIndentationMistake = false;
let newLineResult = await newLines.next();

View file

@ -8,16 +8,23 @@ function linesMatchPerfectly(lineA: string, lineB: string): boolean {
return lineA === lineB && lineA !== "";
}
function linesMatch(lineA: string, lineB: string): boolean {
const END_BRACKETS = ["}", "});", "})"];
function linesMatch(
lineA: string,
lineB: string,
linesBetween: number = 0,
): boolean {
// Require a perfect (without padding) match for these lines
// Otherwise they are edit distance 1 from empty lines and other single char lines (e.g. each other)
if (["}", "*"].includes(lineA.trim())) {
if (["}", "*", "});", "})"].includes(lineA.trim())) {
return lineA.trim() === lineB.trim();
}
const d = distance(lineA, lineB);
return (
(d / Math.max(lineA.length, lineB.length) < 0.5 ||
// Should be more unlikely for lines to fuzzy match if they are further away
(d / Math.max(lineA.length, lineB.length) < 0.5 - linesBetween * 0.05 ||
lineA.trim() === lineB.trim()) &&
lineA.trim() !== ""
);
@ -37,10 +44,16 @@ export function matchLine(
return [0, true, newLine.trim()];
}
const isEndBracket = END_BRACKETS.includes(newLine.trim());
for (let i = 0; i < oldLines.length; i++) {
// Don't match end bracket lines if too far away
if (i > 4 && isEndBracket) {
return [-1, false, newLine];
}
if (linesMatchPerfectly(newLine, oldLines[i])) {
return [i, true, newLine];
} else if (linesMatch(newLine, oldLines[i])) {
} else if (linesMatch(newLine, oldLines[i], i)) {
// This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines
if (
newLine.trimStart() === oldLines[i].trimStart() &&

28
core/index.d.ts vendored
View file

@ -43,6 +43,14 @@ export interface LLMReturnValue {
prompt: string;
completion: string;
}
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export interface ILLM extends LLMOptions {
get providerName(): ModelProvider;
@ -90,7 +98,18 @@ export interface ILLM extends LLMOptions {
supportsImages(): boolean;
supportsCompletions(): boolean;
supportsPrefill(): boolean;
listModels(): Promise<string[]>;
renderPromptTemplate(
template: PromptTemplate,
history: ChatMessage[],
otherData: Record<string, string>,
canPutWordsInModelsMouth?: boolean,
): string | ChatMessage[];
}
export type ContextProviderType = "normal" | "query" | "submenu";
@ -243,7 +262,6 @@ export type ChatHistory = ChatHistoryItem[];
// LLM
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
raw?: boolean;
log?: boolean;
model?: string;
@ -331,6 +349,7 @@ export interface IdeInfo {
name: string;
version: string;
remoteName: string;
extensionVersion: string;
}
export interface IndexTag {
@ -381,6 +400,7 @@ export interface IDE {
getBranch(dir: string): Promise<string>;
getStats(directory: string): Promise<{ [path: string]: number }>;
getTags(artifactId: string): Promise<IndexTag[]>;
getRepoName(dir: string): Promise<string | undefined>;
}
// Slash Commands
@ -430,7 +450,6 @@ type ContextProviderName =
| "open"
| "google"
| "search"
| "url"
| "tree"
| "http"
| "codebase"
@ -479,7 +498,8 @@ type ModelProvider =
| "mistral"
| "bedrock"
| "deepinfra"
| "flowise";
| "flowise"
| "groq";
export type ModelName =
| "AUTODETECT"
@ -496,6 +516,7 @@ export type ModelName =
| "mistral-8x7b"
| "llama2-7b"
| "llama2-13b"
| "llama2-70b"
| "codellama-7b"
| "codellama-13b"
| "codellama-34b"
@ -573,6 +594,7 @@ interface BaseCompletionOptions {
maxTokens?: number;
numThreads?: number;
keepAlive?: number;
raw?: boolean;
}
export interface ModelDescription {

View file

@ -96,6 +96,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await CodeSnippetsCodebaseIndex._createTables(db);

View file

@ -31,6 +31,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);

View file

@ -1,11 +1,13 @@
// NOTE: vectordb requirement must be listed in extensions/vscode to avoid error
import { v4 as uuidv4 } from "uuid";
import { Table } from "vectordb";
import {
Chunk,
EmbeddingsProvider,
IndexTag,
IndexingProgressUpdate,
} from "..";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { MAX_CHUNK_SIZE } from "../llm/constants";
import { getBasename } from "../util";
import { getLanceDbPath } from "../util/paths";
@ -34,16 +36,11 @@ export class LanceDbIndex implements CodebaseIndex {
static MAX_CHUNK_SIZE = MAX_CHUNK_SIZE;
embeddingsProvider: EmbeddingsProvider;
readFile: (filepath: string) => Promise<string>;
constructor(
embeddingsProvider: EmbeddingsProvider,
readFile: (filepath: string) => Promise<string>,
) {
this.embeddingsProvider = embeddingsProvider;
this.readFile = readFile;
}
private readonly embeddingsProvider: EmbeddingsProvider,
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: ContinueServerClient,
) {}
private tableNameForTag(tag: IndexTag) {
return tagToString(tag)
@ -136,6 +133,7 @@ export class LanceDbIndex implements CodebaseIndex {
items: PathAndCacheKey[],
resultType: IndexResultType,
) => void,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const lancedb = await import("vectordb");
const tableName = this.tableNameForTag(tag);
@ -145,11 +143,92 @@ export class LanceDbIndex implements CodebaseIndex {
await this.createSqliteCacheTable(sqlite);
// Compute
let table = undefined;
let table: Table<number[]> | undefined = undefined;
let needToCreateTable = true;
const existingTables = await db.tableNames();
let computedRows: LanceDbRow[] = [];
const addComputedLanceDbRows = async (
pathAndCacheKey: PathAndCacheKey,
computedRows: LanceDbRow[],
) => {
// Create table if needed, add computed rows
if (table) {
if (computedRows.length > 0) {
await table.add(computedRows);
}
} else if (existingTables.includes(tableName)) {
table = await db.openTable(tableName);
needToCreateTable = false;
if (computedRows.length > 0) {
await table.add(computedRows);
}
} else if (computedRows.length > 0) {
table = await db.createTable(tableName, computedRows);
needToCreateTable = false;
}
// Mark item complete
markComplete([pathAndCacheKey], IndexResultType.Compute);
};
// Check remote cache
if (this.continueServerClient !== undefined) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
const resp = await this.continueServerClient.getFromIndexCache(
keys,
"embeddings",
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
// Get path for cacheKey
const path = results.compute.find(
(item) => item.cacheKey === cacheKey,
)?.path;
if (!path) {
console.warn(
"Continue server sent a cacheKey that wasn't requested",
cacheKey,
);
continue;
}
// Build LanceDbRow objects
const rows: LanceDbRow[] = [];
for (const chunk of chunks) {
const row = {
path,
cachekey: cacheKey,
uuid: uuidv4(),
vector: chunk.vector,
};
rows.push(row);
await sqlite.run(
"INSERT INTO lance_db_cache (uuid, cacheKey, path, vector, startLine, endLine, contents) VALUES (?, ?, ?, ?, ?, ?, ?)",
row.uuid,
row.cachekey,
row.path,
JSON.stringify(row.vector),
chunk.startLine,
chunk.endLine,
chunk.contents,
);
}
await addComputedLanceDbRows({ cacheKey, path }, rows);
}
// Remove items that don't need to be recomputed
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
} catch (e) {
console.log("Error checking remote cache: ", e);
}
}
let computedRows: LanceDbRow[] = [];
for await (const update of this.computeChunks(results.compute)) {
if (Array.isArray(update)) {
const [progress, row, data, desc] = update;
@ -169,26 +248,8 @@ export class LanceDbIndex implements CodebaseIndex {
yield { progress, desc };
} else {
// Create table if needed, add computed rows
if (table) {
if (computedRows.length > 0) {
await table.add(computedRows);
}
} else if (existingTables.includes(tableName)) {
table = await db.openTable(tableName);
needToCreateTable = false;
if (computedRows.length > 0) {
await table.add(computedRows);
}
} else if (computedRows.length > 0) {
table = await db.createTable(tableName, computedRows);
needToCreateTable = false;
}
await addComputedLanceDbRows(update, computedRows);
computedRows = [];
// Mark item complete
markComplete([update], IndexResultType.Compute);
}
}

View file

@ -1,4 +1,5 @@
import { IndexTag, IndexingProgressUpdate } from "../..";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../..";
import { ContinueServerClient } from "../../continueServer/stubs/client";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { getBasename } from "../../util";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex";
@ -14,8 +15,10 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
static artifactId: string = "chunks";
artifactId: string = ChunkCodebaseIndex.artifactId;
readFile: (filepath: string) => Promise<string>;
constructor(readFile: (filepath: string) => Promise<string>) {
constructor(
private readonly readFile: (filepath: string) => Promise<string>,
private readonly continueServerClient?: ContinueServerClient,
) {
this.readFile = readFile;
}
@ -42,11 +45,54 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
const tagString = tagToString(tag);
async function handleChunk(chunk: Chunk) {
const { lastID } = await db.run(
`INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`,
[
chunk.digest,
chunk.filepath,
chunk.index,
chunk.startLine,
chunk.endLine,
chunk.content,
],
);
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
lastID,
tagString,
]);
}
// Check the remote cache
if (this.continueServerClient !== undefined) {
try {
const keys = results.compute.map(({ cacheKey }) => cacheKey);
const resp = await this.continueServerClient.getFromIndexCache(
keys,
"chunks",
repoName,
);
for (const [cacheKey, chunks] of Object.entries(resp.files)) {
for (const chunk of chunks) {
await handleChunk(chunk);
}
}
results.compute = results.compute.filter(
(item) => !resp.files[item.cacheKey],
);
} catch (e) {
console.error("Failed to fetch from remote cache: ", e);
}
}
// Compute chunks for new files
const contents = await Promise.all(
results.compute.map(({ path }) => this.readFile(path)),
@ -61,22 +107,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
MAX_CHUNK_SIZE,
item.cacheKey,
)) {
const { lastID } = await db.run(
`INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`,
[
chunk.digest,
chunk.filepath,
chunk.index,
chunk.startLine,
chunk.endLine,
chunk.content,
],
);
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
lastID,
tagString,
]);
handleChunk(chunk);
}
yield {

79
core/indexing/ignore.ts Normal file
View file

@ -0,0 +1,79 @@
import ignore from "ignore";
const DEFAULT_IGNORE_FILETYPES = [
"*.DS_Store",
"*-lock.json",
"*.lock",
"*.log",
"*.ttf",
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"*.mp4",
"*.svg",
"*.ico",
"*.pdf",
"*.zip",
"*.gz",
"*.tar",
"*.dmg",
"*.tgz",
"*.rar",
"*.7z",
"*.exe",
"*.dll",
"*.obj",
"*.o",
"*.a",
"*.lib",
"*.so",
"*.dylib",
"*.ncb",
"*.sdf",
"*.woff",
"*.woff2",
"*.eot",
"*.cur",
"*.avi",
"*.mpg",
"*.mpeg",
"*.mov",
"*.mp3",
"*.mp4",
"*.mkv",
"*.mkv",
"*.webm",
"*.jar",
"*.onnx",
"*.parquet",
"*.pqt",
"*.wav",
"*.webp",
"*.db",
"*.sqlite",
"*.wasm",
"*.plist",
];
export const defaultIgnoreFile = ignore().add(DEFAULT_IGNORE_FILETYPES);
const DEFAULT_IGNORE_DIRS = [
".git",
".vscode",
".idea",
".vs",
"venv",
".venv",
"env",
".env",
"node_modules",
"dist",
"build",
"target",
"out",
"bin",
".pytest_cache",
".vscode-test",
".continue",
"__pycache__",
];
export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);

View file

@ -1,5 +1,6 @@
import { IDE, IndexTag, IndexingProgressUpdate } from "..";
import { ConfigHandler } from "../config/handler";
import { ContinueServerClient } from "../continueServer/stubs/client";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
import { LanceDbIndex } from "./LanceDbIndex";
@ -20,24 +21,34 @@ export class PauseToken {
}
export class CodebaseIndexer {
configHandler: ConfigHandler;
ide: IDE;
pauseToken: PauseToken;
constructor(configHandler: ConfigHandler, ide: IDE, pauseToken: PauseToken) {
this.configHandler = configHandler;
this.ide = ide;
this.pauseToken = pauseToken;
private continueServerClient?: ContinueServerClient;
constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly pauseToken: PauseToken,
private readonly continueServerUrl: string | undefined,
private readonly userToken: Promise<string | undefined>,
) {
if (continueServerUrl) {
this.continueServerClient = new ContinueServerClient(
continueServerUrl,
userToken,
);
}
}
private async getIndexesToBuild(): Promise<CodebaseIndex[]> {
const config = await this.configHandler.loadConfig();
const indexes = [
new ChunkCodebaseIndex(this.ide.readFile.bind(this.ide)), // Chunking must come first
new ChunkCodebaseIndex(
this.ide.readFile.bind(this.ide),
this.continueServerClient,
), // Chunking must come first
new LanceDbIndex(
config.embeddingsProvider,
this.ide.readFile.bind(this.ide),
this.continueServerClient,
),
new FullTextSearchCodebaseIndex(),
new CodeSnippetsCodebaseIndex(this.ide),
@ -66,10 +77,12 @@ export class CodebaseIndexer {
for (let directory of workspaceDirs) {
const stats = await this.ide.getStats(directory);
const branch = await this.ide.getBranch(directory);
const repoName = await this.ide.getRepoName(directory);
let completedIndexes = 0;
try {
for (let codebaseIndex of indexesToBuild) {
// TODO: IndexTag type should use repoName rather than directory
const tag: IndexTag = {
directory,
branch,
@ -79,12 +92,14 @@ export class CodebaseIndexer {
tag,
{ ...stats },
(filepath) => this.ide.readFile(filepath),
repoName,
);
for await (let { progress, desc } of codebaseIndex.update(
tag,
results,
markComplete,
repoName,
)) {
// Handle pausing in this loop because it's the only one really taking time
while (this.pauseToken.paused) {

View file

@ -259,6 +259,7 @@ export async function getComputeDeleteAddRemove(
tag: IndexTag,
currentFiles: LastModifiedMap,
readFile: (path: string) => Promise<string>,
repoName: string | undefined,
): Promise<[RefreshIndexResults, MarkCompleteCallback]> {
const [add, remove, markComplete] = await getAddRemoveForTag(
tag,
@ -316,7 +317,12 @@ export async function getComputeDeleteAddRemove(
removeTag: [],
};
results[resultType] = items;
for await (let _ of globalCacheIndex.update(tag, results, () => {})) {
for await (let _ of globalCacheIndex.update(
tag,
results,
() => {},
repoName,
)) {
}
},
];
@ -338,6 +344,7 @@ export class GlobalCacheCodeBaseIndex implements CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
_: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate> {
const add = [...results.compute, ...results.addTag];
const remove = [...results.del, ...results.removeTag];

View file

@ -18,6 +18,7 @@ export interface CodebaseIndex {
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback,
repoName: string | undefined,
): AsyncGenerator<IndexingProgressUpdate>;
}

View file

@ -19,13 +19,13 @@ import {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
deepseekEditPrompt,
gemmaEditPrompt,
gptEditPrompt,
mistralEditPrompt,
neuralChatEditPrompt,
openchatEditPrompt,
osModelsEditPrompt,
phindEditPrompt,
simplifiedEditPrompt,
xWinCoderEditPrompt,
@ -38,6 +38,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"ollama",
"together",
"anthropic",
"bedrock",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
@ -46,6 +47,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"google-palm",
"free-trial",
"anthropic",
"bedrock",
];
function modelSupportsImages(provider: ModelProvider, model: string): boolean {
@ -160,7 +162,7 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return "alpaca";
}
if (lower.includes("mistral")) {
if (lower.includes("mistral") || lower.includes("mixtral")) {
return "llama2";
}
@ -218,6 +220,22 @@ function autodetectTemplateFunction(
return null;
}
const USES_OS_MODELS_EDIT_PROMPT: TemplateType[] = [
"alpaca",
"chatml",
// "codellama-70b", Doesn't respond well to this prompt
"deepseek",
"gemma",
"llama2",
"llava",
"neural-chat",
"openchat",
"phi2",
"phind",
"xwin-coder",
"zephyr",
];
function autodetectPromptTemplates(
model: string,
explicitTemplate: TemplateType | undefined = undefined,
@ -227,7 +245,11 @@ function autodetectPromptTemplates(
let editTemplate = null;
if (templateType === "phind") {
if (templateType && USES_OS_MODELS_EDIT_PROMPT.includes(templateType)) {
// This is overriding basically everything else
// Will probably delete the rest later, but for now it's easy to revert
editTemplate = osModelsEditPrompt;
} else if (templateType === "phind") {
editTemplate = phindEditPrompt;
} else if (templateType === "phi2") {
editTemplate = simplifiedEditPrompt;
@ -237,7 +259,7 @@ function autodetectPromptTemplates(
if (model.includes("mistral")) {
editTemplate = mistralEditPrompt;
} else {
editTemplate = codellamaEditPrompt;
editTemplate = osModelsEditPrompt;
}
} else if (templateType === "alpaca") {
editTemplate = alpacaEditPrompt;

View file

@ -8,6 +8,7 @@ import {
LLMReturnValue,
ModelName,
ModelProvider,
PromptTemplate,
RequestOptions,
TemplateType,
} from "..";
@ -46,6 +47,23 @@ export abstract class BaseLLM implements ILLM {
return modelSupportsImages(this.providerName, this.model);
}
supportsCompletions(): boolean {
if (this.providerName === "openai") {
if (
this.apiBase?.includes("api.groq.com") ||
this.apiBase?.includes(":1337")
) {
// Jan + Groq don't support completions : (
return false;
}
}
return true;
}
supportsPrefill(): boolean {
return ["ollama", "anthropic"].includes(this.providerName);
}
uniqueId: string;
model: string;
@ -237,7 +255,6 @@ ${prompt}`;
const log = options.log ?? true;
const raw = options.raw ?? false;
delete options.log;
delete options.raw;
const completionOptions: CompletionOptions = mergeJson(
this.completionOptions,
@ -443,10 +460,45 @@ ${prompt}`;
};
}
private _shouldRequestDirectly() {
if (typeof window === "undefined") {
return true;
public renderPromptTemplate(
template: PromptTemplate,
history: ChatMessage[],
otherData: Record<string, string>,
canPutWordsInModelsMouth: boolean = false,
): string | ChatMessage[] {
if (typeof template === "string") {
let data: any = {
history: history,
...otherData,
};
if (history.length > 0 && history[0].role == "system") {
data["system_message"] = history.shift()!.content;
}
const compiledTemplate = Handlebars.compile(template);
return compiledTemplate(data);
} else {
const rendered = template(history, {
...otherData,
supportsCompletions: this.supportsCompletions() ? "true" : "false",
supportsPrefill: this.supportsPrefill() ? "true" : "false",
});
if (
typeof rendered !== "string" &&
rendered[rendered.length - 1]?.role === "assistant" &&
!canPutWordsInModelsMouth
) {
// Some providers don't allow you to put words in the model's mouth
// So we have to manually compile the prompt template and use
// raw /completions, not /chat/completions
const templateMessages = autodetectTemplateFunction(
this.model,
this.providerName,
autodetectTemplateType(this.model),
);
return templateMessages(rendered);
}
return rendered;
}
return window?.ide !== "vscode";
}
}

View file

@ -31,7 +31,7 @@ class Anthropic extends BaseLLM {
temperature: options.temperature,
max_tokens: options.maxTokens ?? 2048,
model: options.model === "claude-2" ? "claude-2.1" : options.model,
stop_sequences: options.stop,
stop_sequences: options.stop?.filter((x) => x.trim() !== ""),
};
return finalOptions;

View file

@ -1,35 +1,209 @@
import * as fs from "fs";
import { join as joinPath } from "path";
import { promisify } from "util";
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import { streamSse } from "../stream";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
const aws4 = require("aws4");
const readFile = promisify(fs.readFile);
namespace BedrockCommon {
export enum Method {
Chat = "invoke",
Completion = "invoke-with-response-stream",
}
export const Service: string = "bedrock";
export const AuthAlgo: string = "AWS4-HMAC-SHA256";
export const HashAlgo: string = "sha256";
}
class Bedrock extends BaseLLM {
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {};
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "claude-3-sonnet-20240229",
contextLength: 200_000,
};
constructor(options: LLMOptions) {
super(options);
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
private _convertModelName(model: string): string {
return (
{
"claude-3-sonnet-20240229": "anthropic.claude-3-sonnet-20240229-v1:0",
"claude-3-haiku-20240307": "anthropic.claude-3-haiku-20240307-v1:0",
"claude-2": "anthropic.claude-v2:1",
}[model] ?? model
);
}
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
top_p: options.topP,
temperature: options.temperature,
max_tokens: options.maxTokens ?? 4096,
stop_sequences: options.stop,
};
return finalOptions;
}
private _convertMessages(msgs: ChatMessage[]): any[] {
const messages = msgs
.filter((m) => m.role !== "system")
.map((message) => {
if (typeof message.content === "string") {
return message;
} else {
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
} else {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
}),
};
}
});
return messages;
}
private _parseCredentialsFile(fileContents: string) {
const profiles: { [key: string]: any } = {};
const lines = fileContents.trim().split("\n");
let currentProfile: string | null = null;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith("[") && trimmedLine.endsWith("]")) {
currentProfile = trimmedLine.slice(1, -1);
profiles[currentProfile] = {};
} else if (currentProfile !== null && trimmedLine.includes("=")) {
const [key, value] = trimmedLine.split("=");
const trimmedKey = key.trim();
const trimmedValue = value.trim();
if (trimmedKey === "aws_access_key_id") {
profiles[currentProfile].accessKeyId = trimmedValue;
} else if (trimmedKey === "aws_secret_access_key") {
profiles[currentProfile].secretAccessKey = trimmedValue;
} else if (trimmedKey === "aws_session_token") {
profiles[currentProfile].sessionToken = trimmedValue;
}
}
}
return profiles;
}
private async _fetchWithAwsAuthSigV4(
apiMethod: BedrockCommon.Method,
body: string,
model: string,
): Promise<Response> {
const path = `/model/${model}/${apiMethod}`;
const opts = {
headers: {
accept:
apiMethod === BedrockCommon.Method.Chat
? "application/json"
: "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
path: path,
body: body,
service: "bedrock",
host: new URL(this.apiBase!).host,
region: this.region,
};
let accessKeyId: string, secretAccessKey: string, sessionToken: string;
try {
const data = await readFile(
joinPath(process.env.HOME!, ".aws", "credentials"),
"utf8",
);
const credentials = this._parseCredentialsFile(data);
accessKeyId = credentials.bedrock.accessKeyId;
secretAccessKey = credentials.bedrock.secretAccessKey;
sessionToken = credentials.bedrock.sessionToken || "";
} catch (err) {
console.error("Error reading AWS credentials", err);
return new Response("403");
}
return await this.fetch(new URL(`${this.apiBase}${path}`), {
method: "POST",
headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })[
"headers"
],
body: body,
});
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const response = await this.fetch(
`${this.apiBase}/model/${options.model}/invoke-with-response-stream`,
{
method: "POST",
headers: {
accept: "application/vnd.amazon.eventstream",
"content-type": "application/json",
"x-amzn-bedrock-accept": "*/*",
},
body: JSON.stringify({
inputText: prompt,
}),
},
);
for await (const value of streamSse(response)) {
if (value.chunk) {
yield value.chunk;
}
const messages = [{ role: "user" as const, content: prompt }];
for await (const update of this._streamChat(messages, options)) {
yield stripImages(update.content);
}
// TODO: Couldn't seem to get this stream API working yet. Deferring to _streamChat.
// import { streamSse } from "../stream";
// const response = await this._fetchWithAwsAuthSigV4(BedrockCommon.Method.Completion, JSON.stringify({
// ...this._convertArgs(options),
// max_tokens: undefined, // Delete this key in favor of the correct one for the Completions API.
// max_tokens_to_sample: options.maxTokens,
// prompt: `\n\nHuman: ${prompt}\n\nAssistant:`,
// })
// );
// for await (const value of streamSse(response)) {
// if (value.completion) {
// yield value.completion
// }
// }
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
const response = await this._fetchWithAwsAuthSigV4(
BedrockCommon.Method.Chat,
JSON.stringify({
...this._convertArgs(options),
messages: this._convertMessages(messages),
anthropic_version: "bedrock-2023-05-31", // Fixed, required parameter for Chat API.
}),
this._convertModelName(options.model),
);
yield {
role: "assistant",
content: (await response.json()).content[0].text,
};
}
}

20
core/llm/llms/Groq.ts Normal file
View file

@ -0,0 +1,20 @@
import { LLMOptions, ModelProvider } from "../..";
import OpenAI from "./OpenAI";
class Groq extends OpenAI {
static providerName: ModelProvider = "groq";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.groq.com/openai/v1/",
};
private static modelConversion: { [key: string]: string } = {
"llama2-70b": "llama2-70b-4096",
"mistral-8x7b": "mixtral-8x7b-32768",
gemma: "gemma-7b-it",
};
protected _convertModelName(model: string): string {
return Groq.modelConversion[model] ?? model;
}
}
export default Groq;

View file

@ -65,10 +65,15 @@ class OpenAI extends BaseLLM {
};
}
protected _convertModelName(model: string): string {
return model;
}
protected _convertArgs(options: any, messages: ChatMessage[]) {
const url = new URL(this.apiBase!);
const finalOptions = {
messages: messages.map(this._convertMessage),
model: options.model,
model: this._convertModelName(options.model),
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
@ -76,7 +81,9 @@ class OpenAI extends BaseLLM {
presence_penalty: options.presencePenalty,
stop:
// Jan + Azure OpenAI don't truncate and will throw an error
this.apiBase?.includes(":1337") || this.apiType === "azure"
url.port === "1337" ||
url.host === "api.openai.com" ||
this.apiType === "azure"
? options.stop?.slice(0, 4)
: options.stop,
};
@ -164,8 +171,10 @@ class OpenAI extends BaseLLM {
): AsyncGenerator<ChatMessage> {
if (
!CHAT_ONLY_MODELS.includes(options.model) &&
this.supportsCompletions() &&
(NON_CHAT_MODELS.includes(options.model) ||
this.useLegacyCompletionsEndpoint)
this.useLegacyCompletionsEndpoint ||
options.raw)
) {
for await (const content of this._legacystreamComplete(
stripImages(messages[messages.length - 1]?.content || ""),

View file

@ -14,6 +14,7 @@ import Flowise from "./Flowise";
import FreeTrial from "./FreeTrial";
import Gemini from "./Gemini";
import GooglePalm from "./GooglePalm";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import LMStudio from "./LMStudio";
@ -94,6 +95,7 @@ const LLMs = [
DeepInfra,
OpenAIFreeTrial,
Flowise,
Groq,
];
export async function llmFromDescription(
@ -123,13 +125,13 @@ export async function llmFromDescription(
completionOptions: {
...finalCompletionOptions,
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens: (
maxTokens:
finalCompletionOptions.maxTokens ??
cls.defaultOptions?.completionOptions?.maxTokens
) ?? DEFAULT_MAX_TOKENS,
cls.defaultOptions?.completionOptions?.maxTokens ??
DEFAULT_MAX_TOKENS,
},
systemMessage,
};
};
return new cls(options);
}

View file

@ -1,6 +1,46 @@
import { ChatMessage } from "../..";
import { stripImages } from "../countTokens";
function templateFactory(
systemMessage: (msg: ChatMessage) => string,
userPrompt: string,
assistantPrompt: string,
separator: string,
prefix?: string,
emptySystemMessage?: string,
): (msgs: ChatMessage[]) => string {
return (msgs: ChatMessage[]) => {
let prompt = prefix ?? "";
// Skip assistant messages at the beginning
while (msgs.length > 0 && msgs[0].role === "assistant") {
msgs.shift();
}
if (msgs.length > 0 && msgs[0].role === "system") {
prompt += systemMessage(msgs.shift()!);
} else if (emptySystemMessage) {
prompt += emptySystemMessage;
}
for (let i = 0; i < msgs.length; i++) {
const msg = msgs[i];
prompt += msg.role === "user" ? userPrompt : assistantPrompt;
prompt += msg.content;
if (i < msgs.length - 1) {
prompt += separator;
}
}
if (msgs.length > 0 && msgs[msgs.length - 1].role === "user") {
prompt += separator;
prompt += assistantPrompt;
}
return prompt;
};
}
/**
* @description Template for LLAMA2 messages:
*
@ -43,7 +83,10 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
if (msgs[i].role === "user") {
prompt += `[INST] ${msgs[i].content} [/INST]`;
} else {
prompt += msgs[i].content + "</s>\n<s>";
prompt += msgs[i].content;
if (i < msgs.length - 1) {
prompt += "</s>\n<s>";
}
}
}
@ -73,77 +116,41 @@ function anthropicTemplateMessages(messages: ChatMessage[]): string {
return prompt;
}
function llavaTemplateMessages(msgs: ChatMessage[]): string {
`A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.
`A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: <image>{prompt}
ASSISTANT:`;
const llavaTemplateMessages = templateFactory(
() => "",
"USER: <image>",
"ASSISTANT: ",
"\n",
"A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.",
);
let prompt =
"A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.";
const zephyrTemplateMessages = templateFactory(
(msg) => `<|system|>${msg.content}</s>\n`,
"<|user|>\n",
"<|assistant|>\n",
"</s>\n",
undefined,
"<|system|> </s>\n",
);
for (const msg of msgs) {
prompt += msg.role === "user" ? "USER: <image>" : "ASSISTANT: ";
prompt += msg.content;
const chatmlTemplateMessages = templateFactory(
(msg) => `<|im_start|>${msg.role}\n${msg.content}<|im_end|>\n`,
"<|im_start|>user\n",
"<|im_start|>assistant\n",
"<|im_end|>\n",
);
prompt += "\n";
}
prompt += "ASSISTANT: ";
return prompt;
}
function zephyrTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `<|system|>${msgs[0].content}</s>\n`;
msgs.shift();
} else {
prompt += "<|system|> </s>\n";
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "<|user|>\n" : "<|assistant|>\n";
prompt += `${msg.content}</s>\n`;
}
prompt += "<|assistant|>\n";
return prompt;
}
function chatmlTemplateMessages(messages: ChatMessage[]): string {
let prompt = "";
for (const msg of messages) {
prompt += `<|im_start|>${msg.role}\n${msg.content}<|im_end|>\n`;
}
prompt += "<|im_start|>assistant\n";
return prompt;
}
function templateAlpacaMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `${msgs[0].content}\n\n`;
msgs.shift();
} else {
prompt +=
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n";
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n";
prompt += `${msg.content}\n\n`;
}
prompt += "### Response:\n";
return prompt;
}
const templateAlpacaMessages = templateFactory(
(msg) => `${msg.content}\n\n`,
"### Instruction:\n",
"### Response:\n",
"\n\n",
undefined,
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n",
);
function deepseekTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
@ -163,63 +170,45 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
}
prompt += `${msg.content}`;
prompt += msg.role === "user" ? "\n" : "<|EOT|>\n";
if (i < msgs.length - 1) {
prompt += msg.role === "user" ? "\n" : "<|EOT|>\n";
}
}
return prompt + "### Response:\n";
if (msgs.length > 0 && msgs[msgs.length - 1].role === "user") {
prompt += "\n";
prompt += "### Response:\n";
}
return prompt;
}
// See https://huggingface.co/microsoft/phi-2#qa-format
function phi2TemplateMessages(msgs: ChatMessage[]): string {
const HUMAN_PROMPT = "\n\nInstruct:";
const AI_PROMPT = "\n\nOutput:";
let prompt = "";
const phi2TemplateMessages = templateFactory(
(msg) => `\n\nInstruct: ${msg.content} `,
"\n\nInstruct: ",
"\n\nOutput: ",
" ",
);
for (const msg of msgs) {
prompt += `${
msg.role === "user" || msg.role === "system" ? HUMAN_PROMPT : AI_PROMPT
} ${msg.content} `;
}
prompt += AI_PROMPT;
return prompt;
}
function phindTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `### System Prompt\n${msgs[0].content}\n\n`;
msgs.shift();
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "### User Message\n" : "### Assistant\n";
prompt += `${msg.content}\n`;
}
prompt += "### Assistant\n";
return prompt;
}
const phindTemplateMessages = templateFactory(
(msg) => `### System Prompt\n${msg.content}\n\n`,
"### User Message\n",
"### Assistant\n",
"\n",
);
/**
* OpenChat Template, used by CodeNinja
* GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi<|end_of_turn|>GPT4 Correct User: How are you today?<|end_of_turn|>GPT4 Correct Assistant:
*/
function openchatTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
for (const msg of msgs) {
prompt +=
msg.role === "user" ? "GPT4 Correct User: " : "GPT4 Correct Assistant: ";
prompt += msg.content + "<|end_of_turn|>";
}
prompt += "GPT4 Correct Assistant: ";
return prompt;
}
const openchatTemplateMessages = templateFactory(
() => "",
"GPT4 Correct User: ",
"GPT4 Correct Assistant: ",
"<|end_of_turn|>",
);
/**
* Chat template used by https://huggingface.co/TheBloke/XwinCoder-13B-GPTQ
@ -229,47 +218,25 @@ function openchatTemplateMessages(msgs: ChatMessage[]): string {
<user>: {prompt}
<AI>:
*/
function xWinCoderTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "<system>: ";
if (msgs[0].role === "system") {
prompt += msgs.shift()!.content;
} else {
prompt +=
"You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request.";
}
for (let msg of msgs) {
prompt += "\n";
prompt += msg.role === "user" ? "<user>" : "<AI>";
prompt += ": " + msg.content;
}
prompt += "<AI>: ";
return prompt;
}
const xWinCoderTemplateMessages = templateFactory(
(msg) => `<system>: ${msg.content}`,
"\n<user>: ",
"\n<AI>: ",
"",
undefined,
"<system>: You are an AI coding assistant that helps people with programming. Write a response that appropriately completes the user's request.",
);
/**
* NeuralChat Template
* ### System:\n{system_input}\n### User:\n{user_input}\n### Assistant:\n
*/
function neuralChatTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
if (msgs[0].role === "system") {
prompt += `### System:\n${msgs[0].content}\n`;
msgs.shift();
}
for (const msg of msgs) {
prompt += msg.role === "user" ? "### User:\n" : "### Assistant:\n";
prompt += `${msg.content}\n`;
}
prompt += "### Assistant:\n";
return prompt;
}
const neuralChatTemplateMessages = templateFactory(
(msg) => `### System:\n${msg.content}\n`,
"### User:\n",
"### Assistant:\n",
"\n",
);
/**
'<s>Source: system\n\n System prompt <step> Source: user\n\n First user query <step> Source: assistant\n\n Model response to first query <step> Source: user\n\n Second user query <step> Source: assistant\nDestination: user\n\n '
@ -292,18 +259,12 @@ function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string {
What is Cramer's Rule?<end_of_turn>
<start_of_turn>model
*/
function gemmaTemplateMessage(msgs: ChatMessage[]): string {
let prompt = "";
for (const msg of msgs) {
prompt += `<start_of_turn>${
msg.role === "assistant" ? "model" : "user"
}\n${stripImages(msg.content).trim()}<end_of_turn>\n`;
}
prompt += "<start_of_turn>model\n";
return prompt;
}
const gemmaTemplateMessage = templateFactory(
() => "",
"<start_of_turn>user\n",
"<start_of_turn>model\n",
"<end_of_turn>\n",
);
export {
anthropicTemplateMessages,

View file

@ -1,5 +1,4 @@
import { ChatMessage } from "../..";
import { PromptTemplate } from "../../util";
import { ChatMessage, PromptTemplate } from "../..";
const simplifiedEditPrompt = `Consider the following code:
\`\`\`{{{language}}}
@ -19,27 +18,115 @@ Here is the edit requested:
Here is the code after editing:`;
const gptEditPrompt = `\
\`\`\`{{{language}}}
{{{codeToEdit}}}
const gptEditPrompt: PromptTemplate = (_, otherData) => {
if (otherData?.codeToEdit?.trim().length === 0) {
return `\
\`\`\`${otherData.language}
${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix}
\`\`\`
You are an expert programmer. You will rewrite the above code to do the following:
Given the user's request: "${otherData.userInput}"
{{{userInput}}}
Here is the code that should fill in the [BLANK]:`;
}
Output only a code block with the rewritten code:`;
const paragraphs = [
"The user has requested a section of code in a file to be rewritten.",
];
if (otherData.prefix?.trim().length > 0) {
paragraphs.push(`This is the prefix of the file:
\`\`\`${otherData.language}
${otherData.prefix}
\`\`\``);
}
if (otherData.suffix?.trim().length > 0) {
paragraphs.push(`This is the suffix of the file:
\`\`\`${otherData.language}
${otherData.suffix}
\`\`\``);
}
paragraphs.push(`This is the code to rewrite:
\`\`\`${otherData.language}
${otherData.codeToEdit}
\`\`\`
The user's request is: "${otherData.userInput}"
Here is the rewritten code:`);
return paragraphs.join("\n\n");
};
const codellamaInfillEditPrompt = "{{filePrefix}}<FILL>{{fileSuffix}}";
const codellamaEditPrompt = `\`\`\`{{{language}}}
{{{codeToEdit}}}
\`\`\`
[INST] You are an expert programmer and personal assistant. Your task is to rewrite the above code with these instructions: "{{{userInput}}}"
const START_TAG = "<START EDITING HERE>";
const osModelsEditPrompt: PromptTemplate = (history, otherData) => {
// "No sufix" means either there is no suffix OR
// it's a clean break at end of function or something
// (what we're trying to avoid is just the language model trying to complete the closing brackets of a function or something)
const firstCharOfFirstLine = otherData.suffix?.split("\n")[0]?.[0]?.trim();
const isSuffix =
otherData.suffix?.trim() !== "" &&
// First character of first line is whitespace
// Otherwise we assume it's a clean break
!firstCharOfFirstLine;
const suffixTag = isSuffix ? "<STOP EDITING HERE>" : "";
const suffixExplanation = isSuffix
? ' When you get to "<STOP EDITING HERE>", end your response.'
: "";
Your answer should be given inside of a code block. It should use the same kind of indentation as above.
[/INST] Sure! Here's the rewritten code you requested:
\`\`\`{{{language}}}`;
// If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth
if (
otherData.supportsCompletions !== "true" &&
otherData.supportsPrefill !== "true"
) {
return gptEditPrompt(history, otherData);
}
// Use a different prompt when there's neither prefix nor suffix
if (otherData.prefix?.trim() === "" && otherData.suffix?.trim() === "") {
return [
{
role: "user",
content: `\`\`\`${otherData.language}
${otherData.codeToEdit}
${suffixTag}
\`\`\`
Please rewrite the entire code block above in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation}`,
},
{
role: "assistant",
content: `Sure! Here's the entire rewritten code block:
\`\`\`${otherData.language}
`,
},
];
}
return [
{
role: "user",
content: `\`\`\`${otherData.language}
${otherData.prefix}${START_TAG}
${otherData.codeToEdit}
${suffixTag}
\`\`\`
Please rewrite the entire code block above, editing the portion below "${START_TAG}" in order to satisfy the following request: "${otherData.userInput}".${suffixExplanation}
`,
},
{
role: "assistant",
content: `Sure! Here's the entire code block, including the rewritten portion:
\`\`\`${otherData.language}
${otherData.prefix}${START_TAG}
`,
},
];
};
const mistralEditPrompt = `[INST] You are a helpful code assistant. Your task is to rewrite the following code with these instructions: "{{{userInput}}}"
\`\`\`{{{language}}}
@ -188,7 +275,6 @@ export {
alpacaEditPrompt,
claudeEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
codellamaInfillEditPrompt,
deepseekEditPrompt,
gemmaEditPrompt,
@ -196,6 +282,7 @@ export {
mistralEditPrompt,
neuralChatEditPrompt,
openchatEditPrompt,
osModelsEditPrompt,
phindEditPrompt,
simplestEditPrompt,
simplifiedEditPrompt,

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/core",
"version": "1.0.4",
"version": "1.0.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/core",
"version": "1.0.4",
"version": "1.0.6",
"license": "Apache-2.0",
"dependencies": {
"@mozilla/readability": "^0.5.0",
@ -26,6 +26,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
@ -43,7 +44,7 @@
"sqlite3": "^5.1.7",
"tree-sitter-wasms": "^0.1.6",
"uuid": "^9.0.1",
"vectordb": "^0.4.12",
"vectordb": "0.4.12",
"web-tree-sitter": "^0.21.0"
},
"devDependencies": {
@ -5336,7 +5337,6 @@
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz",
"integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==",
"peer": true,
"engines": {
"node": ">= 4"
}

View file

@ -1,6 +1,6 @@
{
"name": "@continuedev/core",
"version": "1.0.4",
"version": "1.0.6",
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js server. It is written in TypeScript and contains much of the functionality that was previously inside of the legacy Continue Python Server.",
"scripts": {
"test": "jest ./test/diff.test.ts",
@ -37,6 +37,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
@ -54,7 +55,7 @@
"sqlite3": "^5.1.7",
"tree-sitter-wasms": "^0.1.6",
"uuid": "^9.0.1",
"vectordb": "^0.4.12",
"vectordb": "0.4.12",
"web-tree-sitter": "^0.21.0"
},
"puppeteer": {

View file

@ -3,6 +3,7 @@ import {
ChatMessage,
ContextItemWithId,
ContextSubmenuItem,
DiffLine,
LLMFullCompletionOptions,
MessageContent,
PersistedSessionInfo,
@ -97,6 +98,17 @@ export type Protocol = {
},
ProtocolGeneratorType<MessageContent>,
];
streamDiffLines: [
{
prefix: string;
highlighted: string;
suffix: string;
input: string;
language: string | undefined;
modelTitle: string | undefined;
},
ProtocolGeneratorType<DiffLine>,
];
};
export interface IdeSettings {

View file

@ -1,32 +1,51 @@
import * as fs from "fs";
import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from "..";
import {
ContinueRcJson,
IDE,
IdeInfo,
IndexTag,
Problem,
Range,
Thread,
} from "..";
import { getContinueGlobalPath } from "./paths";
class FileSystemIde implements IDE {
getRepoName(dir: string): Promise<string | undefined> {
return Promise.resolve(undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
return Promise.resolve([]);
}
getIdeInfo(): Promise<IdeInfo> {
return Promise.resolve({
ideType: "vscode",
name: "na",
version: "0.1",
remoteName: "na",
extensionVersion: "na",
});
}
readRangeInFile(filepath: string, range: Range): Promise<string> {
return Promise.resolve("");
}
getStats(directory: string): Promise<{ [path: string]: number }> {
return Promise.resolve({});
}
isTelemetryEnabled(): Promise<boolean> {
return Promise.resolve(false);
}
getUniqueId(): Promise<string> {
return Promise.resolve("NOT_UNIQUE");
}
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
return Promise.resolve([]);
}
@ -34,28 +53,34 @@ class FileSystemIde implements IDE {
getDiff(): Promise<string> {
return Promise.resolve("");
}
getTerminalContents(): Promise<string> {
return Promise.resolve("");
}
async getDebugLocals(threadIndex: number): Promise<string> {
return Promise.resolve("");
}
async getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
stackDepth: number,
): Promise<string[]> {
return Promise.resolve([]);
}
async getAvailableThreads(): Promise<Thread[]> {
return Promise.resolve([]);
}
showLines(
filepath: string,
startLine: number,
endLine: number
endLine: number,
): Promise<void> {
return Promise.resolve();
}
listWorkspaceContents(): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir("/tmp/continue", (err, files) => {
@ -66,6 +91,7 @@ class FileSystemIde implements IDE {
});
});
}
getWorkspaceDirs(): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.mkdtemp("/tmp/continue", (err, folder) => {
@ -76,9 +102,11 @@ class FileSystemIde implements IDE {
});
});
}
listFolders(): Promise<string[]> {
return Promise.resolve([]);
}
writeFile(path: string, contents: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.writeFile(path, contents, (err) => {
@ -89,21 +117,27 @@ class FileSystemIde implements IDE {
});
});
}
showVirtualFile(title: string, contents: string): Promise<void> {
return Promise.resolve();
}
getContinueDir(): Promise<string> {
return Promise.resolve(getContinueGlobalPath());
}
openFile(path: string): Promise<void> {
return Promise.resolve();
}
runCommand(command: string): Promise<void> {
return Promise.resolve();
}
saveFile(filepath: string): Promise<void> {
return Promise.resolve();
}
readFile(filepath: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(filepath, "utf8", (err, contents) => {
@ -114,10 +148,11 @@ class FileSystemIde implements IDE {
});
});
}
showDiff(
filepath: string,
newContents: string,
stepIndex: number
stepIndex: number,
): Promise<void> {
return Promise.resolve();
}

View file

@ -1,6 +1,3 @@
import Handlebars from "handlebars";
import { ChatMessage } from "..";
export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
@ -92,34 +89,6 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
return [lines.map((x) => x.replace(lcp, "")).join("\n"), lcp];
}
export type PromptTemplate =
| string
| ((
history: ChatMessage[],
otherData: Record<string, string>,
) => string | ChatMessage[]);
export function renderPromptTemplate(
template: PromptTemplate,
history: ChatMessage[],
otherData: Record<string, string>,
): string | ChatMessage[] {
if (typeof template === "string") {
let data: any = {
history: history,
...otherData,
};
if (history.length > 0 && history[0].role == "system") {
data["system_message"] = history.shift()!.content;
}
const compiledTemplate = Handlebars.compile(template);
return compiledTemplate(data);
} else {
return template(history, otherData);
}
}
export function getBasename(filepath: string, n: number = 1): string {
return filepath.split(/[\\/]/).pop() ?? "";
}

View file

@ -1,27 +1,44 @@
import { ContinueRcJson, IDE, IdeInfo, IndexTag, Problem, Range, Thread } from "..";
import {
ContinueRcJson,
IDE,
IdeInfo,
IndexTag,
Problem,
Range,
Thread,
} from "..";
export class MessageIde implements IDE {
constructor(
private readonly request: (messageType: string, data: any) => Promise<any>
private readonly request: (messageType: string, data: any) => Promise<any>,
) {}
getRepoName(dir: string): Promise<string | undefined> {
return this.request("getRepoName", { dir });
}
getDebugLocals(threadIndex: number): Promise<string> {
return this.request("getDebugLocals", { threadIndex });
}
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number
stackDepth: number,
): Promise<string[]> {
return this.request("getTopLevelCallStackSources", {
threadIndex,
stackDepth,
});
}
getAvailableThreads(): Promise<Thread[]> {
return this.request("getAvailableThreads", undefined);
}
getTags(artifactId: string): Promise<IndexTag[]> {
return this.request("getTags", artifactId);
}
getIdeInfo(): Promise<IdeInfo> {
return this.request("getIdeInfo", undefined);
}
@ -29,9 +46,11 @@ export class MessageIde implements IDE {
readRangeInFile(filepath: string, range: Range): Promise<string> {
return this.request("readRangeInFile", { filepath, range });
}
getStats(directory: string): Promise<{ [path: string]: number }> {
throw new Error("Method not implemented.");
}
isTelemetryEnabled(): Promise<boolean> {
return this.request("isTelemetryEnabled", undefined);
}
@ -63,7 +82,7 @@ export class MessageIde implements IDE {
async showLines(
filepath: string,
startLine: number,
endLine: number
endLine: number,
): Promise<void> {
return await this.request("showLines", { filepath, startLine, endLine });
}
@ -108,7 +127,7 @@ export class MessageIde implements IDE {
async showDiff(
filepath: string,
newContents: string,
stepIndex: number
stepIndex: number,
): Promise<void> {
await this.request("showDiff", { filepath, newContents, stepIndex });
}

View file

@ -1,13 +1,21 @@
import os from "os";
export class Telemetry {
// Set to undefined whenever telemetry is disabled
static client: any = undefined;
static uniqueId: string = "NOT_UNIQUE";
static os: string | undefined = undefined;
static extensionVersion: string | undefined = undefined;
static async capture(event: string, properties: any) {
static async capture(event: string, properties: { [key: string]: any }) {
Telemetry.client?.capture({
distinctId: Telemetry.uniqueId,
event,
properties,
properties: {
...properties,
os: Telemetry.os,
extensionVersion: Telemetry.extensionVersion,
},
});
}
@ -15,8 +23,15 @@ export class Telemetry {
Telemetry.client?.shutdown();
}
static async setup(allow: boolean, uniqueId: string) {
static async setup(
allow: boolean,
uniqueId: string,
extensionVersion: string,
) {
Telemetry.uniqueId = uniqueId;
Telemetry.os = os.platform();
Telemetry.extensionVersion = extensionVersion;
if (!allow) {
Telemetry.client = undefined;
} else {

View file

@ -4,23 +4,27 @@ import {
filterEnglishLinesAtEnd,
filterEnglishLinesAtStart,
filterLeadingAndTrailingNewLineInsertion,
fixCodeLlamaFirstLineIndentation,
stopAtLines,
} from "../autocomplete/lineStream";
import { streamDiff } from "../diff/streamDiff";
import { streamLines } from "../diff/util";
import { gptEditPrompt } from "../llm/templates/edit";
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util";
import { Telemetry } from "./posthog";
function constructPrompt(
codeToEdit: string,
prefix: string,
highlighted: string,
suffix: string,
llm: ILLM,
userInput: string,
language: string | undefined,
): string | ChatMessage[] {
const template = llm.promptTemplates?.edit ?? gptEditPrompt;
return renderPromptTemplate(template, [], {
return llm.renderPromptTemplate(template, [], {
userInput,
codeToEdit,
prefix,
codeToEdit: highlighted,
suffix,
language: language ?? "",
});
}
@ -42,37 +46,62 @@ function modelIsInept(model: string): boolean {
}
export async function* streamDiffLines(
oldCode: string,
prefix: string,
highlighted: string,
suffix: string,
llm: ILLM,
input: string,
language: string | undefined,
): AsyncGenerator<DiffLine> {
Telemetry.capture("inlineEdit", {
model: llm.model,
provider: llm.providerName,
});
// Strip common indentation for the LLM, then add back after generation
const [withoutIndentation, commonIndentation] =
dedentAndGetCommonWhitespace(oldCode);
oldCode = withoutIndentation;
const oldLines = oldCode.split("\n");
const prompt = constructPrompt(oldCode, llm, input, language);
let oldLines =
highlighted.length > 0
? highlighted.split("\n")
: // When highlighted is empty, we need to combine last line of prefix and first line of suffix to determine the line being edited
[(prefix + suffix).split("\n")[prefix.split("\n").length - 1]];
// But if that line is empty, we can assume we are insertion-only
if (oldLines.length === 1 && oldLines[0].trim() === "") {
oldLines = [];
}
const prompt = constructPrompt(
prefix,
highlighted,
suffix,
llm,
input,
language,
);
const inept = modelIsInept(llm.model);
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt)
? llm.streamComplete(prompt, { raw: true })
: llm.streamChat(prompt);
let lines = streamLines(completion);
if (inept) {
lines = filterEnglishLinesAtStart(lines);
}
lines = filterEnglishLinesAtStart(lines);
lines = filterCodeBlockLines(lines);
lines = stopAtLines(lines);
if (inept) {
lines = filterEnglishLinesAtEnd(fixCodeLlamaFirstLineIndentation(lines));
// lines = fixCodeLlamaFirstLineIndentation(lines);
lines = filterEnglishLinesAtEnd(lines);
}
let diffLines = streamDiff(oldLines, lines);
diffLines = addIndentation(diffLines, commonIndentation);
diffLines = filterLeadingAndTrailingNewLineInsertion(diffLines);
if (highlighted.length === 0) {
const line = prefix.split("\n").slice(-1)[0];
const indentation = line.slice(0, line.length - line.trimStart().length);
diffLines = addIndentation(diffLines, indentation);
}
for await (let diffLine of diffLines) {
yield diffLine;

View file

@ -73,6 +73,7 @@ export type WebviewProtocol = Protocol &
errorPopup: [{ message: string }, void];
"index/setPaused": [boolean, void];
"index/forceReIndex": [undefined, void];
openUrl: [string, void];
applyToCurrentFile: [{ text: string }, void];
showTutorial: [undefined, void];
@ -85,6 +86,8 @@ export type WebviewProtocol = Protocol &
toggleFullScreen: [undefined, void];
"stats/getTokensPerDay": [undefined, { day: string; tokens: number }[]];
"stats/getTokensPerModel": [undefined, { model: string; tokens: number }[]];
insertAtCursor: [{ text: string }, void];
"jetbrains/editorInsetHeight": [{ height: number }, void];
};
export type ReverseWebviewProtocol = {
@ -117,4 +120,5 @@ export type ReverseWebviewProtocol = {
refreshSubmenuItems: [undefined, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];
};

View file

@ -3044,7 +3044,7 @@ ieee754@^1.1.13, ieee754@^1.2.1:
resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz"
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==
ignore@^5.2.0:
ignore@^5.2.0, ignore@^5.3.1:
version "5.3.1"
resolved "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz"
integrity sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==
@ -5730,7 +5730,7 @@ v8-to-istanbul@^9.0.1:
"@types/istanbul-lib-coverage" "^2.0.1"
convert-source-map "^2.0.0"
vectordb@^0.4.12:
vectordb@0.4.12:
version "0.4.12"
resolved "https://registry.npmjs.org/vectordb/-/vectordb-0.4.12.tgz"
integrity sha512-H2mFwZ87d3BcuX4yGx5RoW06amRZQ3W5u/FRTNc86rwVINuEEa+Ivsqng1i8hURHXoTDbF/0Y9qwCshySkeznQ==

View file

@ -0,0 +1,26 @@
# AWS Bedrock
To setup Bedrock, add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "Bedrock: Claude 3 Sonnet",
"provider": "bedrock",
"model": "anthropic.claude-3-sonnet-20240229-v1:0",
"region": "us-east-1"
}
]
}
```
Authentication will be through temporary or long-term credentials in
~/.aws/credentials under a profile called "bedrock".
```title="~/.aws/credentials
[bedrock]
aws_access_key_id = abcdefg
aws_secret_access_key = hijklmno
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
```

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -139,12 +140,14 @@
"llamafile",
"mistral",
"deepinfra",
"flowise"
"flowise",
"groq"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +532,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -715,6 +746,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["groq"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["llama2-70b", "mistral-8x7b", "gemma"]
}
}
}
},
{
"if": {
"properties": {
@ -1649,6 +1697,16 @@
}
},
"required": []
},
"ui": {
"type": "object",
"properties": {
"codeBlockToolbarPosition": {
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
}
}
}
}
}

View file

@ -80,7 +80,7 @@ koverReport {
tasks {
prepareSandbox {
from("../../pkg/bin") {
from("../../binary/bin") {
into("${intellij.pluginName.get()}/core/")
}
}

View file

@ -4,7 +4,7 @@ pluginGroup = com.github.continuedev.continueintellijextension
pluginName = continue-intellij-extension
pluginRepositoryUrl = https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion = 0.0.39
pluginVersion = 0.0.40
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild = 223

View file

@ -1,11 +1,15 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.wm.ToolWindowManager
import java.awt.Dimension
@ -25,16 +29,40 @@ fun pluginServiceFromActionEvent(e: AnActionEvent): ContinuePluginService? {
class AcceptDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
acceptHorizontalDiff(e)
acceptVerticalDiff(e)
}
private fun acceptHorizontalDiff(e: AnActionEvent) {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.ideProtocolClient?.diffManager?.acceptDiff(null)
}
private fun acceptVerticalDiff(e: AnActionEvent) {
val project = e.project ?: return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: FileEditorManager.getInstance(project).selectedTextEditor ?: return
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.accept(editor)
}
}
class RejectDiffAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
rejectHorizontalDiff(e)
rejectVerticalDiff(e)
}
private fun rejectHorizontalDiff(e: AnActionEvent) {
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
continuePluginService.ideProtocolClient?.diffManager?.rejectDiff(null)
}
private fun rejectVerticalDiff(e: AnActionEvent) {
val project = e.project ?: return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: FileEditorManager.getInstance(project).selectedTextEditor ?: return
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.reject(editor)
}
}

View file

@ -237,7 +237,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
val corePath = Paths.get(pluginPath.toString(), "core").toString()
val targetPath = Paths.get(corePath, target).toString()
val continueCorePath = Paths.get(targetPath, "pkg" + (if (os == "win32") ".exe" else "")).toString()
val continueCorePath = Paths.get(targetPath, "continue-binary" + (if (os == "win32") ".exe" else "")).toString()
// Copy targetPath / node_sqlite3.node to core / node_sqlite3.node
val nodeSqlite3Path = Paths.get(targetPath, "node_sqlite3.node")

View file

@ -4,11 +4,6 @@ import com.github.continuedev.continueintellijextension.`continue`.uuid
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.application.invokeLater
@ -95,6 +90,13 @@ class AutocompleteService(private val project: Project) {
} else {
editor.inlayModel.addInlineElement(offset, properties, ContinueCustomElementRenderer(editor, text))
}
// val attributes = TextAttributes().apply {
// backgroundColor = JBColor.GREEN
// }
// val key = TextAttributesKey.createTextAttributesKey("CONTINUE_AUTOCOMPLETE")
// key.let { editor.colorsScheme.setAttributes(it, attributes) }
// editor.markupModel.addLineHighlighter(key, editor.caretModel.logicalPosition.line, HighlighterLayer.LAST)
}
}
}

View file

@ -79,7 +79,8 @@ class CoreMessenger(esbuildPath: String, continueCorePath: String, ideProtocolCl
private val generatorTypes = listOf(
"llm/streamComplete",
"llm/streamChat",
"command/run"
"command/run",
"streamDiffLines"
)
private val ideMessageTypes = listOf(

View file

@ -1,6 +1,7 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel
import com.intellij.diff.DiffContentFactory
import com.intellij.diff.DiffManager
import com.intellij.diff.DiffRequestPanel
@ -27,7 +28,7 @@ import javax.swing.JComponent
fun getDiffDirectory(): File {
val homeDirectory = System.getProperty("user.home")
val diffDirPath = Paths.get(homeDirectory).resolve(".continue").resolve("diffs").toString()
val diffDirPath = Paths.get(homeDirectory).resolve(".continue").resolve(".diffs").toString()
val diffDir = File(diffDirPath)
if (!diffDir.exists()) {
diffDir.mkdirs()
@ -174,11 +175,10 @@ class DiffManager(private val project: Project): DumbAware {
override fun createActions(): Array<Action> {
val okAction = getOKAction()
val cmdCtrl = if (System.getProperty("os.name").toLowerCase().contains("mac")) "⌘" else "⌃"
okAction.putValue(Action.NAME, "Accept ($cmdCtrl ⇧ ⏎)")
okAction.putValue(Action.NAME, "Accept (${getAltKeyLabel()} ⇧ Y)")
val cancelAction = getCancelAction()
cancelAction.putValue(Action.NAME, "Reject ($cmdCtrl ⇧ ⌫)")
cancelAction.putValue(Action.NAME, "Reject (${getAltKeyLabel()} ⇧ N)")
return arrayOf(okAction, cancelAction)
}

View file

@ -5,11 +5,40 @@ import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorColorsScheme
import com.intellij.openapi.editor.colors.TextAttributesKey
import java.awt.Color
import kotlin.math.max
import kotlin.math.min
class GetTheme {
fun getSecondaryDark(): Color {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val grayscale = (defaultBackground.red * 0.3 + defaultBackground.green * 0.59 + defaultBackground.blue * 0.11).toInt()
val adjustedRed: Int
val adjustedGreen: Int
val adjustedBlue: Int
val tint: Int = 20
if (grayscale > 128) { // if closer to white
adjustedRed = max(0, defaultBackground.red - tint)
adjustedGreen = max(0, defaultBackground.green - tint)
adjustedBlue = max(0, defaultBackground.blue - tint)
} else { // if closer to black
adjustedRed = min(255, defaultBackground.red + tint)
adjustedGreen = min(255, defaultBackground.green + tint)
adjustedBlue = min(255, defaultBackground.blue + tint)
}
return Color(adjustedRed, adjustedGreen, adjustedBlue)
}
fun getHighlight(): Color {
val globalScheme = EditorColorsManager.getInstance().globalScheme
return globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: globalScheme.defaultForeground
}
fun getTheme(): Map<String, String> {
try {
val globalScheme = EditorColorsManager.getInstance().globalScheme

View file

@ -6,11 +6,13 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
@ -168,11 +170,17 @@ class IdeProtocolClient (
if (sshClient != null || sshTty != null) {
remoteName = "ssh"
}
val pluginId = "com.github.continuedev.continueintellijextension"
val plugin = PluginManagerCore.getPlugin(PluginId.getId(pluginId))
val extensionVersion = plugin?.version ?: "Unknown"
respond(mapOf(
"ideType" to "jetbrains",
"name" to ideName,
"version" to ideVersion,
"remoteName" to remoteName
"remoteName" to remoteName,
"extensionVersion" to extensionVersion
))
}

View file

@ -0,0 +1,19 @@
package com.github.continuedev.continueintellijextension.editor
import com.intellij.openapi.editor.EditorLinePainter
import com.intellij.openapi.editor.LineExtensionInfo
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.JBColor
import java.awt.Color
import java.awt.Font
class ContinueEditorLinePainter : EditorLinePainter() {
override fun getLineExtensions(project: Project, file: VirtualFile, lineNumber: Int): MutableCollection<LineExtensionInfo>? {
return null
// return mutableListOf(LineExtensionInfo("Line $lineNumber", null, EffectType.BOLD_DOTTED_LINE, JBColor.BLUE, Font.PLAIN ))
}
}

View file

@ -0,0 +1,236 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.HighlighterLayer
import com.intellij.openapi.editor.markup.RangeHighlighter
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.ui.JBColor
import java.awt.event.KeyEvent
import javax.swing.JTextArea
import kotlin.math.min
enum class DiffLineType {
SAME, NEW, OLD
}
class DiffStreamHandler(
private val project: Project,
private val editor: Editor,
private val textArea: JTextArea,
private val startLine: Int,
private val endLine: Int,
private val onClose: () -> Unit,
private val onFinish: () -> Unit
) {
private val greenKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x3000FF00.toInt(), 0x3000FF00.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_NEW_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private val currentLineKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x40888888.toInt(), 0x40888888.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private val unfinishedKey = run {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(0x20888888.toInt(), 0x20888888.toInt())
}
val key = TextAttributesKey.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE")
key.let { editor.colorsScheme.setAttributes(it, attributes) }
key
}
private var currentLine = startLine
private var currentLineHighlighter: RangeHighlighter? = null
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
private var changeCount: Int = 0
private var running: Boolean = false
fun setup() {
// Highlight the range with unfinished color
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min(
i, editor.document.lineCount - 1
), HighlighterLayer.FIRST)
unfinishedHighlighters.add(highlighter)
}
}
private fun handleDiffLine(type: DiffLineType, line: String) {
println("DiffStreamHandler: handleDiffLine: $currentLine, $type, $line")
try {
when (type) {
DiffLineType.SAME -> {
currentLine++
}
DiffLineType.NEW -> {
// Insert new line
if (currentLine == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
}
val offset = editor.document.getLineStartOffset(currentLine)
editor.document.insertString(offset, line + "\n")
// Highlight the new line green
editor.markupModel.addLineHighlighter(greenKey, currentLine, HighlighterLayer.LAST)
currentLine++
changeCount++
}
DiffLineType.OLD -> {
// Remove old line
val startOffset = editor.document.getLineStartOffset(currentLine)
val endOffset = editor.document.getLineEndOffset(currentLine) + 1
editor.document.deleteString(startOffset, min(endOffset, editor.document.textLength))
changeCount++
}
}
// Highlight the current line
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
currentLineHighlighter = editor.markupModel.addLineHighlighter(currentLineKey, min(currentLine, editor.document.lineCount - 1), HighlighterLayer.LAST)
// Remove the unfinished highlighter top line
if (type != DiffLineType.OLD) {
if (unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
}
}
} catch (e: Exception) {
println("Error handling diff line: $currentLine, $type, $line, $e.message")
}
}
private fun resetState() {
// Remove all highlighters
editor.markupModel.removeAllHighlighters()
// Undo changes just by using builtin undo
WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project)
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document) ?: return@runWriteCommandAction
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor?
if (undoManager.isUndoAvailable(fileEditor)) {
for (i in 0 until changeCount) {
undoManager.undo(fileEditor)
}
}
// Reset state variables
currentLine = startLine
changeCount = 0
}
}
fun accept() {
// Accept the changes
editor.markupModel.removeAllHighlighters()
onClose()
running = false
}
fun reject() {
// Reject the changes
resetState()
onClose()
running = false
}
fun toggleFocus() {
if (textArea.hasFocus()) {
textArea.transferFocus()
editor.contentComponent.requestFocus()
} else {
textArea.requestFocus()
}
}
fun run(input : String, prefix : String, highlighted : String, suffix : String, modelTitle : String) {
// Undo changes
resetState()
running = true
// Highlight the range with unfinished color
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(unfinishedKey, min(
i, editor.document.lineCount - 1
), HighlighterLayer.FIRST)
unfinishedHighlighters.add(highlighter)
}
// Request diff stream from core
val continuePluginService = ServiceManager.getService(
this.project,
ContinuePluginService::class.java
)
val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
continuePluginService.coreMessenger?.request("streamDiffLines", mapOf(
"input" to input,
"prefix" to prefix,
"highlighted" to highlighted,
"suffix" to suffix,
"language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle
), null) { response ->
if (!running) {
return@request
}
val parsed = Gson().fromJson(response, Map::class.java)
val done = parsed["done"] as? Boolean
if (done == true) {
onFinish()
ApplicationManager.getApplication().invokeLater {
// Clean up highlighters
if (currentLineHighlighter != null) {
editor.markupModel.removeHighlighter(currentLineHighlighter!!)
}
unfinishedHighlighters.forEach { editor.markupModel.removeHighlighter(it) }
// Add ", " to the text area
textArea.document.insertString(textArea.caretPosition, ", ", null)
textArea.requestFocus()
}
return@request
}
val data = parsed["content"] as Map<*, *>
val type = data["type"] as String
val diffLineType = when (type) {
"same" -> DiffLineType.SAME
"new" -> DiffLineType.NEW
"old" -> DiffLineType.OLD
else -> throw Exception("Unknown diff line type: $type")
}
WriteCommandAction.runWriteCommandAction(project) {
handleDiffLine(diffLineType, data["line"] as String)
}
}
}
}

View file

@ -0,0 +1,31 @@
package com.github.continuedev.continueintellijextension.editor
import com.intellij.openapi.components.Service
import com.intellij.openapi.editor.Editor
@Service(Service.Level.PROJECT)
class DiffStreamService {
private val handlers = mutableMapOf<Editor, DiffStreamHandler>()
fun register(handler: DiffStreamHandler, editor: Editor) {
if (handlers.containsKey(editor)) {
handlers[editor]?.reject()
}
handlers[editor] = handler
println("Registered handler for editor")
}
fun reject(editor: Editor) {
handlers[editor]?.reject()
handlers.remove(editor)
}
fun accept(editor: Editor) {
handlers[editor]?.accept()
handlers.remove(editor)
}
fun getHandler(editor: Editor): DiffStreamHandler? {
return handlers[editor]
}
}

View file

@ -0,0 +1,158 @@
package com.github.continuedev.continueintellijextension.editor
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.impl.EditorEmbeddedComponentManager
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.view.FontLayoutService
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.ui.JBUI
import java.awt.Dimension
import java.awt.Font
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import javax.swing.JComponent
import javax.swing.ScrollPaneConstants
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* Copied from com.intellij.util.ui.codereview.diff.EditorComponentInlaysManager
* via https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/EditorComponentInlaysManager.kt
*/
class EditorComponentInlaysManager(val editor: EditorImpl) : Disposable {
private val managedInlays = mutableMapOf<ComponentWrapper, Disposable>()
private val editorWidthWatcher = EditorTextWidthWatcher()
init {
editor.scrollPane.viewport.addComponentListener(editorWidthWatcher)
Disposer.register(this, Disposable {
editor.scrollPane.viewport.removeComponentListener(editorWidthWatcher)
})
EditorUtil.disposeWithEditor(editor, this)
}
@RequiresEdt
fun insertAfter(lineIndex: Int, component: JComponent): Disposable? {
if (Disposer.isDisposed(this)) return null
// Dispose all other inlays
managedInlays.values.forEach(Disposer::dispose)
val wrappedComponent = ComponentWrapper(component)
val offset = editor.document.getLineEndOffset(lineIndex)
return EditorEmbeddedComponentManager.getInstance()
.addComponent(editor, wrappedComponent,
EditorEmbeddedComponentManager.Properties(EditorEmbeddedComponentManager.ResizePolicy.none(),
null,
true,
false,
0,
offset))?.also {
managedInlays[wrappedComponent] = it
Disposer.register(it, Disposable { managedInlays.remove(wrappedComponent) })
}
}
private inner class ComponentWrapper(private val component: JComponent) : JBScrollPane(component) {
init {
isOpaque = false
viewport.isOpaque = false
border = JBUI.Borders.empty()
viewportBorder = JBUI.Borders.empty()
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
verticalScrollBar.preferredSize = Dimension(0, 0)
setViewportView(component)
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent) =
dispatchEvent(ComponentEvent(component, ComponentEvent.COMPONENT_RESIZED))
})
}
override fun getPreferredSize(): Dimension {
return Dimension(editorWidthWatcher.editorTextWidth, component.preferredSize.height)
}
}
override fun dispose() {
managedInlays.values.forEach(Disposer::dispose)
}
private inner class EditorTextWidthWatcher : ComponentAdapter() {
var editorTextWidth: Int = 0
private val maximumEditorTextWidth: Int
private val verticalScrollbarFlipped: Boolean
init {
val metrics = editor.getFontMetrics(Font.PLAIN)
val spaceWidth = FontLayoutService.getInstance().charWidth2D(metrics, ' '.toInt())
// -4 to create some space
maximumEditorTextWidth = ceil(spaceWidth * (editor.settings.getRightMargin(editor.project)) - 4).toInt()
val scrollbarFlip = editor.scrollPane.getClientProperty(JBScrollPane.Flip::class.java)
verticalScrollbarFlipped =
scrollbarFlip == JBScrollPane.Flip.HORIZONTAL || scrollbarFlip == JBScrollPane.Flip.BOTH
}
override fun componentResized(e: ComponentEvent) = updateWidthForAllInlays()
override fun componentHidden(e: ComponentEvent) = updateWidthForAllInlays()
override fun componentShown(e: ComponentEvent) = updateWidthForAllInlays()
private fun updateWidthForAllInlays() {
val newWidth = calcWidth()
if (editorTextWidth == newWidth) return
editorTextWidth = newWidth
managedInlays.keys.forEach {
it.dispatchEvent(ComponentEvent(it, ComponentEvent.COMPONENT_RESIZED))
it.invalidate()
}
}
private fun calcWidth(): Int {
val visibleEditorTextWidth = editor.scrollPane.viewport.width - getVerticalScrollbarWidth() - getGutterTextGap()
return min(max(visibleEditorTextWidth, 0), maximumEditorTextWidth)
}
private fun getVerticalScrollbarWidth(): Int {
val width = editor.scrollPane.verticalScrollBar.width
return if (!verticalScrollbarFlipped) width * 2 else width
}
private fun getGutterTextGap(): Int {
return if (verticalScrollbarFlipped) {
val gutter = (editor as EditorEx).gutterComponentEx
gutter.width - gutter.whitespaceSeparatorOffset
} else 0
}
}
companion object {
val INLAYS_KEY: Key<EditorComponentInlaysManager> = Key.create("EditorComponentInlaysManager")
fun from(editor: Editor): EditorComponentInlaysManager {
return synchronized(editor) {
val manager = editor.getUserData(INLAYS_KEY)
if (manager == null) {
val newManager = EditorComponentInlaysManager(editor as EditorImpl)
editor.putUserData(INLAYS_KEY, newManager)
newManager
} else manager
}
}
}
}

View file

@ -0,0 +1,462 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.`continue`.GetTheme
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.getAltKeyLabel
import com.github.continuedev.continueintellijextension.utils.getMetaKeyLabel
import com.google.gson.Gson
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.TextRange
import com.intellij.ui.JBColor
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.swing.MigLayout
import org.jdesktop.swingx.JXPanel
import org.jdesktop.swingx.JXTextArea
import org.jdesktop.swingx.border.DropShadowBorder
import java.awt.*
import java.awt.event.*
import java.awt.geom.RoundRectangle2D
import javax.swing.*
import javax.swing.border.EmptyBorder
import javax.swing.event.DocumentEvent
import javax.swing.event.DocumentListener
import kotlin.math.max
const val SHADOW_SIZE = 7
const val MAIN_FONT_SIZE = 13
/**
* Adapted from https://github.com/cursive-ide/component-inlay-example/blob/master/src/main/kotlin/inlays/InlineEditAction.kt
*/
class InlineEditAction : AnAction(), DumbAware {
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = true
e.presentation.isVisible = true
}
override fun actionPerformed(e: AnActionEvent) {
if (e.project == null) return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: return
val project = e.getData(PlatformDataKeys.PROJECT) ?: return
val manager = EditorComponentInlaysManager.from(editor)
// Get list of model titles
val continuePluginService = project.service<ContinuePluginService>()
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getBrowserSerialized", null, null) { response ->
val gson = Gson()
val config = gson.fromJson(response, Map::class.java)
val models = config["models"] as List<Map<String, Any>>
modelTitles.addAll(models.map { it["title"] as String })
}
val maxWaitTime = 200
val startTime = System.currentTimeMillis()
while (modelTitles.isEmpty() && System.currentTimeMillis() - startTime < maxWaitTime) {
Thread.sleep(20)
}
// Get highlighted range
val selectionModel = editor.selectionModel
val start = selectionModel.selectionStart
val end = selectionModel.selectionEnd
val prefix = editor.document.getText(TextRange(0, start))
val highlighted = editor.document.getText(TextRange(start, end))
val suffix = editor.document.getText(TextRange(end, editor.document.textLength))
val startLineNum = editor.document.getLineNumber(start)
val endLineNum = editor.document.getLineNumber(end)
val lineNumber = max(0, startLineNum - 1)
// Un-highlight the selected text
selectionModel.removeSelection()
// Get indentation width in pixels
val indentationLineNum = lineNumber + 1
val lineStart = editor.document.getLineStartOffset(indentationLineNum)
val lineEnd = editor.document.getLineEndOffset(indentationLineNum)
val text = editor.document.getText(TextRange(lineStart, lineEnd))
val indentation = text.takeWhile { it == ' ' }.length
val charWidth = editor.contentComponent.getFontMetrics(editor.colorsScheme.getFont(EditorFontType.PLAIN)).charWidth(' ')
val leftInset = indentation * charWidth * 2 / 3
val inlayRef = Ref<Disposable>()
val customPanelRef = Ref<CustomPanel>()
// Create text area, attach key listener
val textArea = makeTextArea()
// Create diff stream handler
val diffStreamHandler = DiffStreamHandler(project, editor, textArea, startLineNum, endLineNum, {
inlayRef.get().dispose()
}, {
customPanelRef.get().finish()
})
val diffStreamService = project.service<DiffStreamService>()
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.setup()
val comboBoxRef = Ref<JComboBox<String>>()
fun onEnter() {
customPanelRef.get().enter()
diffStreamHandler.run(textArea.text, prefix, highlighted, suffix, comboBoxRef.get().selectedItem as String)
}
val panel = makePanel(project, customPanelRef, textArea, inlayRef, comboBoxRef, leftInset, modelTitles, {onEnter()}, {
diffStreamService.reject(editor)
selectionModel.setSelection(start, end)
}, {
diffStreamService.accept(editor)
inlayRef.get().dispose()
}, {
diffStreamService.reject(editor)
inlayRef.get().dispose()
})
val inlay = manager.insertAfter(lineNumber, panel)
panel.revalidate()
inlayRef.set(inlay)
val viewport = (editor as? EditorImpl)?.scrollPane?.viewport
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
// Add key listener to text area
textArea.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ESCAPE) {
diffStreamService.reject(editor)
// Re-highlight the selected text
selectionModel.setSelection(start, end)
} else if (e.keyCode == KeyEvent.VK_ENTER) {
if (e.modifiersEx == KeyEvent.SHIFT_DOWN_MASK) {
textArea.document.insertString(textArea.caretPosition, "\n", null)
} else if (e.modifiersEx == 0) {
onEnter()
e.consume()
}
}
}
})
// Listen for changes to textarea line count
textArea.document.addDocumentListener(object : DocumentListener {
private var lastNumLines: Int = 0
private fun updateSize() {
val numLines = textArea.text.lines().size
if (numLines != lastNumLines) {
lastNumLines = numLines
viewport?.dispatchEvent(ComponentEvent(viewport, ComponentEvent.COMPONENT_RESIZED))
}
}
override fun insertUpdate(e: DocumentEvent?) {
updateSize()
}
override fun removeUpdate(e: DocumentEvent?) {
updateSize()
}
override fun changedUpdate(e: DocumentEvent?) {
updateSize()
}
})
textArea.requestFocus()
}
fun makeTextArea(): JTextArea {
val textArea = CustomTextArea( 2, 40).apply {
lineWrap = true
wrapStyleWord = true
isOpaque = false
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(8)
font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
return textArea
}
fun makePanel(project: Project, customPanelRef: Ref<CustomPanel>, textArea: JTextArea, inlayRef: Ref<Disposable>, comboBoxRef: Ref<JComboBox<String>>, leftInset: Int, modelTitles: List<String>, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel {
val topPanel = ShadowPanel(MigLayout("wrap 1, insets 10 $leftInset 8 8, gap 0!")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
// background = defaultBackground
background = JBColor(0x20888888.toInt(), 0x20888888.toInt())
isOpaque = false
}
val panel = CustomPanel(MigLayout("wrap 1, insets 0, gap 0!, fillx"), project, modelTitles, comboBoxRef, onEnter, onCancel, onAccept, onReject).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
background = defaultBackground
add(textArea, "grow, gap 0!, height 100%")
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
preferredSize = textArea.preferredSize
isOpaque = false
setup()
val shadow = DropShadowBorder()
shadow.shadowColor = JBColor(0xb0b0b0, 0x505050)
shadow.isShowRightShadow = true
shadow.isShowBottomShadow = true
shadow.shadowSize = SHADOW_SIZE
border = shadow
}
customPanelRef.set(panel)
textArea.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
panel.revalidate()
panel.repaint()
}
})
topPanel.add(panel, "grow, gap 0!")
return topPanel
}
}
class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>, comboBoxRef: Ref<JComboBox<String>>, onEnter: () -> Unit, onCancel: () -> Unit, onAccept: () -> Unit, onReject: () -> Unit): JPanel(layout) {
private val subPanelA: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply {
foreground = Color(128, 128, 128, 200)
background = defaultBackground
}
val continueSettingsService = service<ContinueExtensionSettings>()
val dropdown = JComboBox(modelTitles.toTypedArray()).apply {
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = Font("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
isOpaque = false
isEditable = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
renderer = DefaultListCellRenderer().apply {
horizontalAlignment = SwingConstants.RIGHT
}
selectedIndex = continueSettingsService.continueState.lastSelectedInlineEditModel?.let { modelTitles.indexOf(it) } ?: 0
addActionListener {
continueSettingsService.continueState.lastSelectedInlineEditModel = selectedItem as String
}
}
comboBoxRef.set(dropdown)
val rightButton = CustomButton("Submit") { onEnter() }.apply {
// background = GetTheme().getHighlight()
background = JBColor(0xe04573e8.toInt(), 0xe04573e8.toInt())
foreground = JBColor.WHITE
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
border = EmptyBorder(0, 0, 0, 0)
add(dropdown, "align right")
add(rightButton, "align right")
}
border = EmptyBorder(4, 8, 4, 8)
add(leftButton, "align left")
add(rightPanel, "align right")
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelB: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
// Get the global color scheme and default background color
val globalScheme = EditorColorsManager.getInstance().globalScheme
val defaultBackground = globalScheme.defaultBackground
val leftButton = CustomButton("Esc to cancel") { onCancel() }.apply {
foreground = Color(128, 128, 128, 200)
background = defaultBackground
}
val progressBar = JProgressBar()
progressBar.isIndeterminate = true
border = EmptyBorder(4, 8, 4, 8)
add(leftButton, "align left")
add(progressBar, "align right")
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)
}
private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel = JLabel("Enter follow-up instructions").apply {
foreground = Color(128, 128, 128, 200)
font = Font("Arial", Font.PLAIN, 11)
}
val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply {
background = Color(255, 0, 0, 64)
}
val rightButton = CustomButton("${getAltKeyLabel()}⇧Y") { onAccept() }.apply {
background = Color(0, 255, 0, 64)
}
val rightPanel = JPanel(MigLayout("insets 0, fillx")).apply {
isOpaque = false
add(leftButton, "align right")
add(rightButton, "align right")
border = EmptyBorder(0, 0, 0, 0)
}
add(leftLabel, "align left")
add(rightPanel, "align right")
border = EmptyBorder(4, 8, 4, 8)
isOpaque = false
}
fun setup() {
remove(subPanelB)
remove(subPanelC)
add(subPanelA, "grow, gap 0!")
}
fun enter() {
remove(subPanelA)
remove(subPanelC)
add(subPanelB, "grow, gap 0!")
revalidate()
repaint()
}
fun finish() {
remove(subPanelB)
add(subPanelC, "grow, gap 0!")
revalidate()
repaint()
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
// Draw the rounded border
val borderColor = Color(128, 128, 128, 128)
val borderThickness = 1
val borderRadius = 8
g2.color = borderColor
g2.stroke = BasicStroke(borderThickness.toFloat())
g2.drawRoundRect(
borderThickness / 2,
borderThickness / 2,
width - borderThickness - SHADOW_SIZE + 1,
height - borderThickness - SHADOW_SIZE + 1,
borderRadius,
borderRadius
)
super.paintComponent(g)
}
}
class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
private var isHovered = false
init {
isOpaque = false
cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
addMouseListener(object : MouseAdapter() {
override fun mouseEntered(e: MouseEvent?) {
isHovered = true
repaint()
}
override fun mouseExited(e: MouseEvent?) {
isHovered = false
repaint()
}
override fun mouseClicked(e: MouseEvent?) {
onClick()
}
})
// verticalAlignment = CENTER
font = Font("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
}
override fun paintComponent(g: Graphics) {
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val cornerRadius = 8
val rect = Rectangle(0, 0, width, height)
val roundRect = RoundRectangle2D.Float(rect.x.toFloat(), rect.y.toFloat(), rect.width.toFloat(), rect.height.toFloat(), cornerRadius.toFloat(), cornerRadius.toFloat())
if (isHovered) {
g2.color = background.brighter()
} else {
g2.color = background
}
g2.fill(roundRect)
g2.color = foreground
g2.drawString(text, (width / 2 - g.fontMetrics.stringWidth(text) / 2).toFloat(),
(height / 2 + g.fontMetrics.ascent / 2).toFloat())
}
}
class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
init {
setRows(rows)
setColumns(columns)
}
override fun paintComponent(g: Graphics) {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions to edit highlighted code", 8, 20)
}
super.paintComponent(g)
}
}
class ShadowPanel(layout: LayoutManager) : JXPanel(layout) {
override fun getPreferredSize(): Dimension {
val prefSize = super.getPreferredSize()
val insets = getInsets()
prefSize.width += insets.left + insets.right
prefSize.height += insets.top + insets.bottom
return prefSize
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
}
}

View file

@ -0,0 +1,27 @@
package com.github.continuedev.continueintellijextension.editor
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.components.service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAware
class ToggleInlineEditAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.getData(PlatformDataKeys.PROJECT) ?: return
val editor = e.getData(PlatformDataKeys.EDITOR) ?: FileEditorManager.getInstance(project).selectedTextEditor ?: return
val diffService = project.service<DiffStreamService>()
val handler = diffService.getHandler(editor)
if (handler == null) {
val actionId = "continue.inlineEdit"
val action = ActionManager.getInstance().getAction(actionId)
if (action != null) {
e.actionManager.tryToExecute(action, e.inputEvent, null, null, true)
}
} else {
handler.toggleFocus()
}
}
}

View file

@ -62,6 +62,7 @@ class ContinueSettingsComponent: DumbAware {
open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensionSettings.ContinueState> {
class ContinueState {
var lastSelectedInlineEditModel: String? = null
var shownWelcomeDialog: Boolean = false
var remoteConfigServerUrl: String? = null
var remoteConfigSyncPeriod: Int = 60

View file

@ -3,6 +3,7 @@ package com.github.continuedev.continueintellijextension.services
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
import com.github.continuedev.continueintellijextension.`continue`.uuid
import com.github.continuedev.continueintellijextension.toolWindow.ContinueBrowser
import com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory
import com.google.gson.Gson
import com.intellij.openapi.Disposable
@ -41,25 +42,6 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
data: Any?,
messageId: String = uuid()
) {
val jsonData = Gson().toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
)
)
val jsCode = buildJavaScript(jsonData)
try {
continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode)
} catch (error: IllegalStateException) {
println("Webview not initialized yet $error")
}
continuePluginWindow?.browser?.sendToWebview(messageType, data, messageId)
}
private fun buildJavaScript(jsonData: String): String {
return """window.postMessage($jsonData, "*");"""
}
}

View file

@ -0,0 +1,233 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.ui.jcef.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
class ContinueBrowser(val project: Project, url: String, useOsr: Boolean = false) {
private val heightChangeListeners = mutableListOf<(Int) -> Unit>()
fun onHeightChange(listener: (Int) -> Unit) {
heightChangeListeners.add(listener)
}
private val PASS_THROUGH_TO_CORE = listOf(
"abort",
"getContinueDir",
"history/list",
"history/save",
"history/delete",
"history/load",
"devdata/log",
"config/addModel",
"config/deleteModel",
"config/addOpenAIKey",
"llm/streamComplete",
"llm/streamChat",
"llm/complete",
"command/run",
"context/loadSubmenuItems",
"context/getContextItems",
"context/addDocs",
"config/getBrowserSerialized",
)
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
"continue",
CustomSchemeHandlerFactory()
)
}
val browser: JBCefBrowser
init {
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
this.browser = JBCefBrowser.createBuilder().setOffScreenRendering(os == "linux" || useOsr).build()
browser.jbCefClient.setProperty(
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
JS_QUERY_POOL_SIZE
)
registerAppSchemeHandler()
browser.loadURL(url);
Disposer.register(project, browser)
// Listen for events sent from browser
val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!)
myJSQueryOpenInBrowser.addHandler { msg: String? ->
val parser = JsonParser()
val json: JsonObject = parser.parse(msg).asJsonObject
val messageType = json.get("messageType").asString
val data = json.get("data")
val messageId = json.get("messageId")?.asString
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
val ide = continuePluginService.ideProtocolClient;
val respond = fun(data: Any?) {
val jsonData = mutableMapOf(
"messageId" to messageId,
"data" to data,
"messageType" to messageType
)
val jsonString = Gson().toJson(jsonData)
sendToWebview(messageType, data, messageId ?: uuid())
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
return@addHandler null
}
when (messageType) {
"jetbrains/editorInsetHeight" -> {
val height = data.asJsonObject.get("height").asInt
heightChangeListeners.forEach { it(height) }
}
"onLoad" -> {
GlobalScope.launch {
// Set the colors to match Intellij theme
val colors = GetTheme().getTheme();
sendToWebview("setColors", colors)
val jsonData = mutableMapOf(
"windowId" to continuePluginService.windowId,
"workspacePaths" to continuePluginService.workspacePaths,
"vscMachineId" to getMachineUniqueID(),
"vscMediaUrl" to "http://continue",
)
respond(jsonData)
}
}
"showLines" -> {
val data = data.asJsonObject
ide?.highlightCode(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
0
), Position(
data.get("end").asInt,
0
)),
),"#00ff0022")
}
"showTutorial" -> {
showTutorial(project)
}
"showVirtualFile" -> {
val data = data.asJsonObject
ide?.showVirtualFile(data.get("name").asString, data.get("content").asString)
}
"showFile" -> {
val data = data.asJsonObject
ide?.setFileOpen(data.get("filepath").asString)
}
"reloadWindow" -> {}
"openConfigJson" -> {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
val data = data.asJsonObject
ide?.readRangeInFile(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
0
), Position(
data.get("end").asInt + 1,
0
)),
))
}
"focusEditor" -> {}
// IDE //
else -> {
if (msg != null) {
ide?.handleMessage(msg, respond)
}
}
}
null
}
// Listen for the page load event
browser.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() {
override fun onLoadingStateChange(
browser: CefBrowser?,
isLoading: Boolean,
canGoBack: Boolean,
canGoForward: Boolean
) {
if (!isLoading) {
// The page has finished loading
executeJavaScript(browser, myJSQueryOpenInBrowser)
}
}
}, browser.cefBrowser)
}
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
// Execute JavaScript - you might want to handle potential exceptions here
val script = """window.postIntellijMessage = function(messageType, data, messageId) {
const msg = JSON.stringify({messageType, data, messageId});
${myJSQueryOpenInBrowser.inject("msg")}
}""".trimIndent()
browser?.executeJavaScript(script, browser.url, 0)
}
fun sendToWebview(
messageType: String,
data: Any?,
messageId: String = uuid()
) {
val jsonData = Gson().toJson(
mapOf(
"messageId" to messageId,
"messageType" to messageType,
"data" to data
)
)
val jsCode = buildJavaScript(jsonData)
try {
this.browser.executeJavaScriptAsync(jsCode)
} catch (error: IllegalStateException) {
println("Webview not initialized yet $error")
}
}
private fun buildJavaScript(jsonData: String): String {
return """window.postMessage($jsonData, "*");"""
}
}

View file

@ -1,33 +1,16 @@
package com.github.continuedev.continueintellijextension.toolWindow
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.constants.getConfigJsonPath
import com.github.continuedev.continueintellijextension.`continue`.*
import com.github.continuedev.continueintellijextension.factories.CustomSchemeHandlerFactory
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.jcef.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.cef.CefApp
import org.cef.browser.CefBrowser
import org.cef.handler.CefLoadHandlerAdapter
import javax.swing.*
import kotlin.math.max
import kotlin.math.min
const val JS_QUERY_POOL_SIZE = "200"
@ -38,6 +21,13 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
toolWindow.contentManager.addContent(content)
val titleActions = mutableListOf<AnAction>()
createTitleActions(titleActions)
// Add MaximizeToolWindow action
val action = ActionManager.getInstance().getAction("MaximizeToolWindow")
if (action != null) {
titleActions.add(action)
}
toolWindow.setTitleActions(titleActions)
}
@ -53,200 +43,26 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
class ContinuePluginWindow(toolWindow: ToolWindow, project: Project) {
val PASS_THROUGH_TO_CORE = listOf(
"abort",
"getContinueDir",
"history/list",
"history/save",
"history/delete",
"history/load",
"devdata/log",
"config/addModel",
"config/deleteModel",
"config/addOpenAIKey",
"llm/streamComplete",
"llm/streamChat",
"llm/complete",
"command/run",
"context/loadSubmenuItems",
"context/getContextItems",
"context/addDocs",
"config/getBrowserSerialized",
)
init {
System.setProperty("ide.browser.jcef.jsQueryPoolSize", JS_QUERY_POOL_SIZE)
System.setProperty("ide.browser.jcef.contextMenu.devTools.enabled", "true")
}
val webView: JBCefBrowser by lazy {
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> "darwin"
osName.contains("win") -> "win32"
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> "linux"
else -> "linux"
}
val browser = JBCefBrowser.createBuilder().setOffScreenRendering(os == "linux").build()
browser.jbCefClient.setProperty(
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
JS_QUERY_POOL_SIZE
)
registerAppSchemeHandler()
val browser: ContinueBrowser by lazy {
val url = "http://continue/index.html";
// Use to get hot-reloading in local development
if (false) {
browser.loadURL("http://localhost:5173/jetbrains_index.html");
} else {
browser.loadURL("http://continue/index.html")
}
// browser.loadHTML("<html><body><input type='text'/></body></html>")
// browser.loadURL("http://localhost:5173/index.html")
Disposer.register(project, browser)
// val url = "http://localhost:5173/jetbrains_index.html";
val browser = ContinueBrowser(project, url)
val continuePluginService = ServiceManager.getService(
project,
ContinuePluginService::class.java
)
continuePluginService.continuePluginWindow = this
// Listen for events sent from browser
val myJSQueryOpenInBrowser = JBCefJSQuery.create((browser as JBCefBrowserBase?)!!)
myJSQueryOpenInBrowser.addHandler { msg: String? ->
val parser = JsonParser()
val json: JsonObject = parser.parse(msg).asJsonObject
val messageType = json.get("messageType").asString
val data = json.get("data")
val messageId = json.get("messageId")?.asString
val ide = continuePluginService.ideProtocolClient;
val respond = fun(data: Any?) {
val jsonData = mutableMapOf(
"messageId" to messageId,
"data" to data,
"messageType" to messageType
)
val jsonString = Gson().toJson(jsonData)
continuePluginService.sendToWebview(messageType, data, messageId ?: uuid())
}
if (PASS_THROUGH_TO_CORE.contains(messageType)) {
continuePluginService.coreMessenger?.request(messageType, data, messageId, respond)
return@addHandler null
}
when (messageType) {
"onLoad" -> {
GlobalScope.launch {
// Set the colors to match Intellij theme
val colors = GetTheme().getTheme();
continuePluginService.sendToWebview("setColors", colors)
val jsonData = mutableMapOf(
"windowId" to continuePluginService.windowId,
"workspacePaths" to continuePluginService.workspacePaths,
"vscMachineId" to getMachineUniqueID(),
"vscMediaUrl" to "http://continue",
)
respond(jsonData)
}
}
"showLines" -> {
val data = data.asJsonObject
ide?.highlightCode(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
0
), Position(
data.get("end").asInt,
0
)),
),"#00ff0022")
}
"showTutorial" -> {
showTutorial(project)
}
"showVirtualFile" -> {
val data = data.asJsonObject
ide?.showVirtualFile(data.get("name").asString, data.get("content").asString)
}
"showFile" -> {
val data = data.asJsonObject
ide?.setFileOpen(data.get("filepath").asString)
}
"reloadWindow" -> {}
"openConfigJson" -> {
ide?.setFileOpen(getConfigJsonPath())
}
"readRangeInFile" -> {
val data = data.asJsonObject
ide?.readRangeInFile(RangeInFile(
data.get("filepath").asString,
Range(Position(
data.get("start").asInt,
0
), Position(
data.get("end").asInt + 1,
0
)),
))
}
"focusEditor" -> {}
// IDE //
else -> {
if (msg != null) {
ide?.handleMessage(msg, respond)
}
}
}
null
}
// Listen for the page load event
browser.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() {
override fun onLoadingStateChange(
browser: CefBrowser?,
isLoading: Boolean,
canGoBack: Boolean,
canGoForward: Boolean
) {
if (!isLoading) {
// The page has finished loading
executeJavaScript(browser, myJSQueryOpenInBrowser)
}
}
}, browser.cefBrowser)
browser
}
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
// Execute JavaScript - you might want to handle potential exceptions here
val script = """window.postIntellijMessage = function(messageType, data, messageId) {
const msg = JSON.stringify({messageType, data, messageId});
${myJSQueryOpenInBrowser.inject("msg")}
}""".trimIndent()
browser?.executeJavaScript(script, browser.url, 0)
}
val content: JComponent
get() = webView.component
private fun registerAppSchemeHandler() {
CefApp.getInstance().registerSchemeHandlerFactory(
"http",
"continue",
CustomSchemeHandlerFactory()
)
}
get() = browser.browser.component
}
}

View file

@ -0,0 +1,34 @@
package com.github.continuedev.continueintellijextension.utils
import java.awt.Toolkit
import java.awt.event.KeyEvent
enum class Os {
MAC, WINDOWS, LINUX
}
fun getOs(): Os {
val osName = System.getProperty("os.name").toLowerCase()
val os = when {
osName.contains("mac") || osName.contains("darwin") -> Os.MAC
osName.contains("win") -> Os.WINDOWS
osName.contains("nix") || osName.contains("nux") || osName.contains("aix") -> Os.LINUX
else -> Os.LINUX
}
return os
}
fun getMetaKeyLabel(): String {
return when (getOs()) {
Os.MAC -> "⌘"
Os.WINDOWS -> "Ctrl"
Os.LINUX -> "Ctrl"
}
}
fun getAltKeyLabel(): String {
return when (getOs()) {
Os.MAC -> "⌥"
Os.WINDOWS -> "Alt"
Os.LINUX -> "Alt"
}
}

View file

@ -16,6 +16,9 @@
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>
<projectService id="ContinuePluginService"
serviceImplementation="com.github.continuedev.continueintellijextension.services.ContinuePluginService"/>
<projectService
id="DiffStreamService"
serviceImplementation="com.github.continuedev.continueintellijextension.editor.DiffStreamService"/>
</extensions>
<resource-bundle>messages.MyBundle</resource-bundle>
@ -33,21 +36,41 @@
</extensions>
<actions>
<action class="com.github.continuedev.continueintellijextension.editor.InlineEditAction"
id="continue.inlineEdit"
description="Inline Edit"
text="Inline Edit">
<keyboard-shortcut keymap="$default"
first-keystroke="ctrl I"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="meta I"/>
</action>
<action class="com.github.continuedev.continueintellijextension.editor.ToggleInlineEditAction"
id="continue.toggleInlineEdit"
description="Toggle Inline Edit"
text="Toggle Inline Edit">
<keyboard-shortcut keymap="$default"
first-keystroke="ctrl shift I"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="meta shift I"/>
</action>
<action id="continue.acceptDiff"
class="com.github.continuedev.continueintellijextension.actions.AcceptDiffAction"
text="Accept Diff" description="Accept Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="shift ctrl ENTER"/>
first-keystroke="alt shift Y"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="shift meta ENTER"/>
first-keystroke="alt shift Y"/>
</action>
<action id="continue.rejectDiff"
class="com.github.continuedev.continueintellijextension.actions.RejectDiffAction"
text="Reject Diff" description="Reject Diff">
<keyboard-shortcut keymap="$default"
first-keystroke="shift ctrl BACK_SPACE"/>
first-keystroke="alt shift N"/>
<keyboard-shortcut keymap="Mac OS X"
first-keystroke="shift meta BACK_SPACE"/>
first-keystroke="alt shift N"/>
</action>
<action id="continue.quickTextEntry"
class="com.github.continuedev.continueintellijextension.actions.QuickTextEntryAction"

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -139,12 +140,14 @@
"llamafile",
"mistral",
"deepinfra",
"flowise"
"flowise",
"groq"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +532,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -715,6 +746,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["groq"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["llama2-70b", "mistral-8x7b", "gemma"]
}
}
}
},
{
"if": {
"properties": {
@ -1649,6 +1697,16 @@
}
},
"required": []
},
"ui": {
"type": "object",
"properties": {
"codeBlockToolbarPosition": {
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
}
}
}
}
}

View file

@ -39,7 +39,7 @@ select the code and toggle the Continue input box"""
# endregion
# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ J] —————————————————————————————————
# region ————————————————————————————————— Part 2: Edit code [⌘ I] —————————————————————————————————
"""Step 1: Highlight this code"""
@ -54,15 +54,15 @@ def bubble_sort(x):
return x
"""Step 2: Use the keyboard shortcut [⌘ J] to
"""Step 2: Use the keyboard shortcut [⌘ I] to
select the code"""
"""Step 3: Type "/edit <your edit request>" and press Enter"""
# e.g.) /edit optimize this function
# e.g.) /edit write comments
"""Step 3: Type instructions to edit the code and press Enter"""
# e.g.) "optimize this function"
# e.g.) "edit write comments"
"""Step 4: Use keyboard shortcuts to
accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
accept [⌥ ⇧ Y] or reject [⌥ ⇧ N] the edit"""
# endregion

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -139,12 +140,14 @@
"llamafile",
"mistral",
"deepinfra",
"flowise"
"flowise",
"groq"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -529,6 +532,34 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["bedrock"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -715,6 +746,23 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": ["groq"]
}
},
"required": ["provider"]
},
"then": {
"properties": {
"model": {
"enum": ["llama2-70b", "mistral-8x7b", "gemma"]
}
}
}
},
{
"if": {
"properties": {
@ -1649,6 +1697,16 @@
}
},
"required": []
},
"ui": {
"type": "object",
"properties": {
"codeBlockToolbarPosition": {
"enum": ["top", "bottom"],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
}
}
}
}
}

View file

@ -128,6 +128,7 @@
"openai",
"free-trial",
"anthropic",
"bedrock",
"together",
"ollama",
"huggingface-tgi",
@ -139,12 +140,14 @@
"llamafile",
"mistral",
"deepinfra",
"flowise"
"flowise",
"groq"
],
"markdownEnumDescriptions": [
"### OpenAI\nUse gpt-4, gpt-3.5-turbo, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/openai)",
"### Free Trial\nNew users can try out Continue for free using a proxy server that securely makes calls to OpenAI using our API key. If you are ready to use your own API key or have used all 250 free uses, you can enter your API key in config.py where it says `apiKey=\"\"` or select another model provider.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/freetrial)",
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/anthropicllm)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.py (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/ollama)",
"### Huggingface TGI\n\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/huggingfacetgi)",
@ -573,6 +576,38 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"bedrock"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"anyOf": [
{
"enum": [
"claude-3-sonnet-20240229",
"claude-3-haiku-20240307",
"claude-2"
]
},
{
"type": "string"
}
]
}
}
}
},
{
"if": {
"properties": {
@ -788,6 +823,31 @@
}
}
},
{
"if": {
"properties": {
"provider": {
"enum": [
"groq"
]
}
},
"required": [
"provider"
]
},
"then": {
"properties": {
"model": {
"enum": [
"llama2-70b",
"mistral-8x7b",
"gemma"
]
}
}
}
},
{
"if": {
"properties": {
@ -1848,6 +1908,19 @@
},
"required": []
},
"ui": {
"type": "object",
"properties": {
"codeBlockToolbarPosition": {
"enum": [
"top",
"bottom"
],
"default": "top",
"description": "Whether to show the copy and apply code buttons at the top or bottom of code blocks in the sidebar."
}
}
},
"mergeBehavior": {
"type": "string",
"enum": [

View file

@ -6,7 +6,7 @@ const esbuildConfig = {
entryPoints: ["src/extension.ts"],
bundle: true,
outfile: "out/extension.js",
external: ["vscode", "esbuild"],
external: ["vscode", "esbuild", "./xhr-sync-worker.js"],
format: "cjs",
platform: "node",
sourcemap: true,

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.92",
"version": "0.8.22",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.92",
"version": "0.8.22",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -48,7 +48,7 @@
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",
"uuidv4": "^6.2.13",
"vectordb": "^0.4.3",
"vectordb": "0.4.12",
"vscode-languageclient": "^8.0.2",
"ws": "^8.13.0",
"yarn": "^1.22.21"
@ -86,7 +86,7 @@
},
"../../core": {
"name": "@continuedev/core",
"version": "1.0.4",
"version": "1.0.6",
"license": "Apache-2.0",
"dependencies": {
"@mozilla/readability": "^0.5.0",
@ -106,6 +106,7 @@
"handlebars": "^4.7.8",
"http-proxy-agent": "^7.0.1",
"https-proxy-agent": "^7.0.3",
"ignore": "^5.3.1",
"js-tiktoken": "^1.0.8",
"jsdom": "^24.0.0",
"llama-tokenizer-js": "^1.1.3",
@ -123,7 +124,7 @@
"sqlite3": "^5.1.7",
"tree-sitter-wasms": "^0.1.6",
"uuid": "^9.0.1",
"vectordb": "^0.4.12",
"vectordb": "0.4.12",
"web-tree-sitter": "^0.21.0"
},
"devDependencies": {

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.8.22",
"version": "0.9.92",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -100,6 +100,18 @@
"group": "Continue",
"icon": "$(stop)"
},
{
"command": "continue.acceptVerticalDiffBlock",
"category": "Continue",
"title": "Accept Vertical Diff Block",
"group": "Continue"
},
{
"command": "continue.rejectVerticalDiffBlock",
"category": "Continue",
"title": "Reject Vertical Diff Block",
"group": "Continue"
},
{
"command": "continue.quickEdit",
"category": "Continue",
@ -219,7 +231,17 @@
"command": "continue.rejectDiff",
"mac": "cmd+z",
"key": "ctrl+z",
"when": "continue.streamingDiff"
"when": "continue.diffVisible"
},
{
"command": "continue.acceptVerticalDiffBlock",
"mac": "alt+cmd+y",
"key": "alt+ctrl+y"
},
{
"command": "continue.rejectVerticalDiffBlock",
"mac": "alt+cmd+n",
"key": "alt+ctrl+n"
},
{
"command": "continue.quickEdit",
@ -508,7 +530,7 @@
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",
"uuidv4": "^6.2.13",
"vectordb": "^0.4.3",
"vectordb": "0.4.12",
"vscode-languageclient": "^8.0.2",
"ws": "^8.13.0",
"yarn": "^1.22.21"

View file

@ -47,12 +47,12 @@ if (args[2] === "--target") {
}
// Install node_modules //
execSync("npm install");
execSync("npm install --no-save");
console.log("[info] npm install in extensions/vscode completed");
process.chdir("../../gui");
execSync("npm install");
execSync("npm install --no-save");
console.log("[info] npm install in gui completed");
if (ghAction()) {

View file

@ -62,13 +62,20 @@ export class ContinueCompletionProvider
const abortController = new AbortController();
const signal = abortController.signal;
token.onCancellationRequested(() => abortController.abort());
const config = await this.configHandler.loadConfig();
let clipboardText = "";
if (config.tabAutocompleteOptions?.useCopyBuffer === true) {
clipboardText = await vscode.env.clipboard.readText();
}
const input: AutocompleteInput = {
completionId: uuidv4(),
filepath: document.uri.fsPath,
pos: { line: position.line, character: position.character },
recentlyEditedFiles: [],
recentlyEditedRanges: [],
clipboardText: await vscode.env.clipboard.readText(),
clipboardText: clipboardText
};
setupStatusBar(true, true);

View file

@ -6,7 +6,7 @@ const statusBarItemText = (enabled: boolean | undefined) =>
const statusBarItemTooltip = (enabled: boolean | undefined) =>
enabled ? "Tab autocomplete is enabled" : "Click to enable tab autocomplete";
let lastStatusBar: vscode.StatusBarItem | undefined = undefined;
let statusBarItem: vscode.StatusBarItem | undefined = undefined;
let statusBarFalseTimeout: NodeJS.Timeout | undefined = undefined;
export function stopStatusBarLoading() {
@ -24,27 +24,25 @@ export function setupStatusBar(
statusBarFalseTimeout = undefined;
}
const statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
);
// If statusBarItem hasn't been defined yet, create it
if (!statusBarItem) {
statusBarItem = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
);
}
statusBarItem.text = loading
? "$(loading~spin) Continue"
: statusBarItemText(enabled);
statusBarItem.tooltip = statusBarItemTooltip(enabled);
statusBarItem.command = "continue.toggleTabAutocompleteEnabled";
// Swap out with old status bar
if (lastStatusBar) {
lastStatusBar.dispose();
}
statusBarItem.show();
lastStatusBar = statusBarItem;
vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration("continue")) {
const config = vscode.workspace.getConfiguration("continue");
const enabled = config.get<boolean>("enableTabAutocomplete");
statusBarItem.dispose();
setupStatusBar(enabled);
}
});

View file

@ -11,6 +11,7 @@ import { Telemetry } from "core/util/posthog";
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
import { DiffManager } from "./diff/horizontal";
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { getPlatform } from "./util/util";
import { VsCodeWebviewProtocol } from "./webviewProtocol";
function getFullScreenTab() {
@ -164,18 +165,56 @@ const commandsMap: (
"continue.quickEdit": async () => {
const selectionEmpty = vscode.window.activeTextEditor?.selection.isEmpty;
let text = await vscode.window.showInputBox({
const editor = vscode.window.activeTextEditor;
const existingHandler = verticalDiffManager.getHandlerForFile(
editor?.document.uri.fsPath ?? "",
);
const previousInput = existingHandler?.input;
let defaultModelTitle = await sidebar.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
);
const config = await configHandler.loadConfig();
if (!defaultModelTitle) {
defaultModelTitle = config.models[0]?.title!;
}
const quickPickItems =
config.contextProviders
?.filter((provider) => provider.description.type === "normal")
.map((provider) => {
return {
label: provider.description.displayTitle,
description: provider.description.title,
detail: provider.description.description,
};
}) || [];
const addContextMsg = quickPickItems.length
? " (or press enter to add context first)"
: "";
const textInputOptions: vscode.InputBoxOptions = {
placeHolder: selectionEmpty
? "Describe the code you want to generate (or press enter to add context first)"
: "Describe how to edit the highlighted code (or press enter to add context first)",
title: "Continue Quick Edit",
});
? `Type instructions to generate code${addContextMsg}`
: `Describe how to edit the highlighted code${addContextMsg}`,
title: `${getPlatform() === "mac" ? "Cmd" : "Ctrl"}+I`,
prompt: `[${defaultModelTitle}]`,
};
if (previousInput) {
textInputOptions.value = previousInput + ", ";
textInputOptions.valueSelection = [
textInputOptions.value.length,
textInputOptions.value.length,
];
}
let text = await vscode.window.showInputBox(textInputOptions);
if (text === undefined) {
return;
}
if (text.length > 0) {
if (text.length > 0 || quickPickItems.length === 0) {
const modelName = await sidebar.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
@ -183,22 +222,6 @@ const commandsMap: (
await verticalDiffManager.streamEdit(text, modelName);
} else {
// Pick context first
const quickPickItems: Promise<vscode.QuickPickItem[]> = configHandler
.loadConfig()
.then((config) => {
return (
config.contextProviders
?.filter((provider) => provider.description.type === "normal")
.map((provider) => {
return {
label: provider.description.displayTitle,
description: provider.description.title,
detail: provider.description.description,
};
}) || []
);
});
const selectedProviders = await vscode.window.showQuickPick(
quickPickItems,
{
@ -207,12 +230,7 @@ const commandsMap: (
},
);
let text = await vscode.window.showInputBox({
placeHolder: selectionEmpty
? "Describe the code you want to generate (or press enter to add context first)"
: "Describe how to edit the highlighted code (or press enter to add context first)",
title: "Continue Quick Edit",
});
let text = await vscode.window.showInputBox(textInputOptions);
if (text) {
const llm = await configHandler.llmFromTitle();
const config = await configHandler.loadConfig();
@ -243,13 +261,7 @@ const commandsMap: (
"\n\n---\n\n" +
text;
await verticalDiffManager.streamEdit(
text,
await sidebar.webviewProtocol.request(
"getDefaultModelTitle",
undefined,
),
);
await verticalDiffManager.streamEdit(text, defaultModelTitle);
}
}
},
@ -361,13 +373,12 @@ const commandsMap: (
const fullScreenTab = getFullScreenTab();
// Check if the active editor is the Continue GUI View
if (fullScreenTab && fullScreenTab.isActive) {
vscode.commands.executeCommand("workbench.action.closeActiveEditor");
vscode.commands.executeCommand("continue.focusContinueInput");
if (fullScreenTab && fullScreenTab.isActive) { //Full screen open and focused - close it
vscode.commands.executeCommand("workbench.action.closeActiveEditor"); //this will trigger the onDidDispose listener below
return;
}
if (fullScreenTab) {
if (fullScreenTab) { //Full screen open, but not focused - focus it
// Focus the tab
const openOptions = {
preserveFocus: true,
@ -383,15 +394,21 @@ const commandsMap: (
return;
}
//Full screen not open - open it
// Close the sidebar.webviews
// vscode.commands.executeCommand("workbench.action.closeSidebar");
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
// vscode.commands.executeCommand("workbench.action.toggleZenMode");
const panel = vscode.window.createWebviewPanel(
//create the full screen panel
let panel = vscode.window.createWebviewPanel(
"continue.continueGUIView",
"Continue",
vscode.ViewColumn.One,
);
//Add content to the panel
panel.webview.html = sidebar.getSidebarContent(
extensionContext,
panel,
@ -402,6 +419,13 @@ const commandsMap: (
undefined,
true,
);
//When panel closes, reset the webview and focus
panel.onDidDispose(() => {
sidebar.resetWebviewProtocolWebview();
vscode.commands.executeCommand("continue.focusContinueInput");
}, null, extensionContext.subscriptions);
},
"continue.selectFilesAsContext": (
firstUri: vscode.Uri,

View file

@ -33,6 +33,14 @@ export class ContinueGUIWebviewViewProvider
return this._webview;
}
public resetWebviewProtocolWebview(): void {
if (this._webview) {
this.webviewProtocol.webview = this._webview;
} else{
console.warn("no webview found during reset")
}
}
sendMainUserInput(input: string) {
this.webview?.postMessage({
type: "userInput",

Some files were not shown because too many files have changed in this diff Show more