Merge remote-tracking branch 'upstream/preview' into fix-search-context-provider
This commit is contained in:
commit
2b14fbd0a6
182 changed files with 31262 additions and 6652 deletions
12
.vscode/launch.json
vendored
12
.vscode/launch.json
vendored
|
|
@ -5,6 +5,18 @@
|
|||
"version": "0.2.0",
|
||||
"compounds": [],
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Core Binary",
|
||||
"skipFiles": ["<node_internals>/**"],
|
||||
"program": "${workspaceFolder}/pkg/out/index.js",
|
||||
"preLaunchTask": "pkg:esbuild",
|
||||
"outFiles": ["${workspaceFolder}/pkg/out/**/*.js"],
|
||||
"sourceMaps": true,
|
||||
"smartStep": true,
|
||||
"internalConsoleOptions": "openOnSessionStart"
|
||||
},
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
|
|
|
|||
12
.vscode/tasks.json
vendored
12
.vscode/tasks.json
vendored
|
|
@ -136,6 +136,18 @@
|
|||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
//
|
||||
// esbuild for the core binary
|
||||
{
|
||||
"label": "pkg:esbuild",
|
||||
"type": "shell",
|
||||
"command": "npm",
|
||||
"args": ["run", "esbuild"],
|
||||
"problemMatcher": [],
|
||||
"options": {
|
||||
"cwd": "pkg"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@
|
|||
|
||||
</div>
|
||||
|
||||
## Task, not tab, auto-complete
|
||||
## Task and tab autocomplete
|
||||
|
||||
### Answer coding questions
|
||||
|
||||
|
|
@ -52,6 +52,12 @@ Open a blank file and let Continue start new Python scripts, React components, e
|
|||
- “/edit implement a c++ shortest path algo in a concise way”
|
||||
- “/edit create a docker compose file with php and mysql server"
|
||||
|
||||
### And much more!
|
||||
|
||||
- Try out [experimental support for local tab autocomplete](https://continue.dev/docs/walkthroughs/tab-autocomplete) in VS Code
|
||||
- Use [built-in context providers](https://continue.dev/docs/customization/context-providers#built-in-context-providers) or create your own [custom context providers](https://continue.dev/docs/customization/context-providers#building-your-own-context-provider)
|
||||
- Use [built-in slash commands](https://arc.net/l/quote/zbhwfjmp) or create your own [custom slash commands](https://continue.dev/docs/customization/slash-commands#custom-slash-commands)
|
||||
|
||||
## Getting Started
|
||||
|
||||
#### Download for [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)
|
||||
|
|
|
|||
|
|
@ -29,11 +29,10 @@ function formatExternalSnippet(
|
|||
return lines.join("\n");
|
||||
}
|
||||
|
||||
async function getTreePathAtCursor(
|
||||
async function getAst(
|
||||
filepath: string,
|
||||
fileContents: string,
|
||||
cursorIndex: number
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
fileContents: string
|
||||
): Promise<Parser.Tree | undefined> {
|
||||
const parser = await getParserForFile(filepath);
|
||||
|
||||
if (!parser) {
|
||||
|
|
@ -41,6 +40,13 @@ async function getTreePathAtCursor(
|
|||
}
|
||||
|
||||
const ast = parser.parse(fileContents);
|
||||
return ast;
|
||||
}
|
||||
|
||||
async function getTreePathAtCursor(
|
||||
ast: Parser.Tree,
|
||||
cursorIndex: number
|
||||
): Promise<Parser.SyntaxNode[] | undefined> {
|
||||
const path = [ast.rootNode];
|
||||
while (path[path.length - 1].childCount > 0) {
|
||||
let foundChild = false;
|
||||
|
|
@ -65,6 +71,35 @@ export interface AutocompleteSnippet {
|
|||
content: string;
|
||||
}
|
||||
|
||||
const BLOCK_TYPES = ["body", "statement_block"];
|
||||
|
||||
function shouldCompleteMultiline(
|
||||
treePath: Parser.SyntaxNode[],
|
||||
cursorLine: number
|
||||
): boolean {
|
||||
// If at the base of the file, do multiline
|
||||
if (treePath.length === 1) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If at the first line of an otherwise empty funtion body, do multiline
|
||||
for (let i = treePath.length - 1; i >= 0; i--) {
|
||||
const node = treePath[i];
|
||||
if (
|
||||
BLOCK_TYPES.includes(node.type) &&
|
||||
Math.abs(node.startPosition.row - cursorLine) <= 1
|
||||
) {
|
||||
let text = node.text;
|
||||
text = text.slice(text.indexOf("{") + 1);
|
||||
text = text.slice(0, text.lastIndexOf("}"));
|
||||
text = text.trim();
|
||||
return text.split("\n").length === 1;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function constructAutocompletePrompt(
|
||||
filepath: string,
|
||||
fullPrefix: string,
|
||||
|
|
@ -76,24 +111,32 @@ export async function constructAutocompletePrompt(
|
|||
line: number,
|
||||
character: number
|
||||
) => Promise<AutocompleteSnippet | undefined>,
|
||||
options: TabAutocompleteOptions
|
||||
): Promise<{ prefix: string; suffix: string; useFim: boolean }> {
|
||||
options: TabAutocompleteOptions,
|
||||
modelName: string
|
||||
): Promise<{
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
useFim: boolean;
|
||||
completeMultiline: boolean;
|
||||
}> {
|
||||
// Find external snippets
|
||||
const snippets: AutocompleteSnippet[] = [];
|
||||
|
||||
let treePath;
|
||||
let treePath: Parser.SyntaxNode[] | undefined;
|
||||
try {
|
||||
treePath = await getTreePathAtCursor(
|
||||
filepath,
|
||||
fullPrefix + fullSuffix,
|
||||
fullPrefix.length
|
||||
);
|
||||
const ast = await getAst(filepath, fullPrefix + fullSuffix);
|
||||
if (!ast) {
|
||||
throw new Error(`AST undefined for ${filepath}`);
|
||||
}
|
||||
|
||||
treePath = await getTreePathAtCursor(ast, fullPrefix.length);
|
||||
} catch (e) {
|
||||
console.error("Failed to parse AST", e);
|
||||
}
|
||||
|
||||
// Get function def when inside call expression
|
||||
let completeMultiline = false;
|
||||
if (treePath) {
|
||||
// Get function def when inside call expression
|
||||
let callExpression = undefined;
|
||||
for (let node of treePath.reverse()) {
|
||||
if (node.type === "call_expression") {
|
||||
|
|
@ -111,6 +154,10 @@ export async function constructAutocompletePrompt(
|
|||
snippets.push(definition);
|
||||
}
|
||||
}
|
||||
|
||||
// Use AST to determine whether to complete multiline
|
||||
let cursorLine = fullPrefix.split("\n").length - 1;
|
||||
completeMultiline = shouldCompleteMultiline(treePath, cursorLine);
|
||||
}
|
||||
|
||||
// Construct basic prefix / suffix
|
||||
|
|
@ -121,17 +168,17 @@ export async function constructAutocompletePrompt(
|
|||
.join("\n");
|
||||
const maxPrefixTokens =
|
||||
options.maxPromptTokens * options.prefixPercentage -
|
||||
countTokens(formattedSnippets, "gpt-4");
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens);
|
||||
countTokens(formattedSnippets, modelName);
|
||||
let prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName);
|
||||
if (formattedSnippets.length > 0) {
|
||||
prefix = formattedSnippets + "\n" + prefix;
|
||||
}
|
||||
|
||||
const maxSuffixTokens = Math.min(
|
||||
options.maxPromptTokens - countTokens(prefix, "gpt-4"),
|
||||
options.maxPromptTokens - countTokens(prefix, modelName),
|
||||
options.maxSuffixPercentage * options.maxPromptTokens
|
||||
);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens);
|
||||
let suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName);
|
||||
|
||||
return { prefix, suffix, useFim: true };
|
||||
return { prefix, suffix, useFim: true, completeMultiline };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,24 +4,186 @@ export interface AutocompleteLanguageInfo {
|
|||
endOfLine: string[];
|
||||
}
|
||||
|
||||
// TypeScript
|
||||
export const Typescript = {
|
||||
stopWords: ["function", "class", "module", "export "],
|
||||
stopWords: ["function", "class", "module", "export"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Python
|
||||
export const Python = {
|
||||
stopWords: ["def", "class"],
|
||||
comment: "#",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Java
|
||||
export const Java = {
|
||||
stopWords: ["class", "function"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// C++
|
||||
export const Cpp = {
|
||||
stopWords: ["class", "namespace", "template"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// C#
|
||||
export const CSharp = {
|
||||
stopWords: ["class", "namespace", "void"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// C
|
||||
export const C = {
|
||||
stopWords: ["if", "else", "while", "for", "switch", "case"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Scala
|
||||
export const Scala = {
|
||||
stopWords: ["def", "val", "var", "class", "object", "trait"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Go
|
||||
export const Go = {
|
||||
stopWords: ["func", "package", "import", "type"],
|
||||
comment: "//",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Rust
|
||||
export const Rust = {
|
||||
stopWords: ["fn", "mod", "pub", "struct", "enum", "trait"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Haskell
|
||||
export const Haskell = {
|
||||
stopWords: [
|
||||
"data",
|
||||
"type",
|
||||
"newtype",
|
||||
"class",
|
||||
"instance",
|
||||
"let",
|
||||
"in",
|
||||
"where",
|
||||
],
|
||||
comment: "--",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// PHP
|
||||
export const PHP = {
|
||||
stopWords: ["function", "class", "namespace", "use"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Ruby on Rails
|
||||
export const RubyOnRails = {
|
||||
stopWords: ["def", "class", "module"],
|
||||
comment: "#",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Swift
|
||||
export const Swift = {
|
||||
stopWords: ["func", "class", "struct", "import"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Kotlin
|
||||
export const Kotlin = {
|
||||
stopWords: ["fun", "class", "package", "import"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// Ruby
|
||||
export const Ruby = {
|
||||
stopWords: ["class", "module", "def"],
|
||||
comment: "#",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Clojure
|
||||
export const Clojure = {
|
||||
stopWords: ["def", "fn", "let", "do", "if", "defn", "ns", "defmacro"],
|
||||
comment: ";",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Julia
|
||||
export const Julia = {
|
||||
stopWords: [
|
||||
"function",
|
||||
"macro",
|
||||
"if",
|
||||
"else",
|
||||
"elseif",
|
||||
"while",
|
||||
"for",
|
||||
"begin",
|
||||
"end",
|
||||
"module",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
// F#
|
||||
export const FSharp = {
|
||||
stopWords: [
|
||||
"let",
|
||||
"type",
|
||||
"module",
|
||||
"namespace",
|
||||
"open",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"match",
|
||||
"with",
|
||||
],
|
||||
comment: "//",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// R
|
||||
export const R = {
|
||||
stopWords: [
|
||||
"function",
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"repeat",
|
||||
"library",
|
||||
"require",
|
||||
],
|
||||
comment: "#",
|
||||
endOfLine: [],
|
||||
};
|
||||
|
||||
// Dart
|
||||
export const Dart = {
|
||||
stopWords: ["class", "import", "void", "enum"],
|
||||
comment: "//",
|
||||
endOfLine: [";"],
|
||||
};
|
||||
|
||||
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
||||
ts: Typescript,
|
||||
js: Typescript,
|
||||
|
|
@ -30,4 +192,31 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
|
|||
py: Python,
|
||||
pyi: Python,
|
||||
java: Java,
|
||||
cpp: Cpp,
|
||||
cxx: Cpp,
|
||||
h: Cpp,
|
||||
hpp: Cpp,
|
||||
cs: CSharp,
|
||||
c: C,
|
||||
scala: Scala,
|
||||
sc: Scala,
|
||||
go: Go,
|
||||
rs: Rust,
|
||||
hs: Haskell,
|
||||
php: PHP,
|
||||
rb: Ruby,
|
||||
rails: RubyOnRails,
|
||||
swift: Swift,
|
||||
kt: Kotlin,
|
||||
clj: Clojure,
|
||||
cljs: Clojure,
|
||||
cljc: Clojure,
|
||||
jl: Julia,
|
||||
fs: FSharp,
|
||||
fsi: FSharp,
|
||||
fsx: FSharp,
|
||||
fsscript: FSharp,
|
||||
r: R,
|
||||
R: R,
|
||||
dart: Dart,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
|
|||
|
||||
const codeLlamaFimTemplate: AutocompleteTemplate = {
|
||||
template: "<PRE> {{{prefix}}} <SUF>{{{suffix}}} <MID>",
|
||||
completionOptions: { stop: ["<PRE>", "<SUF>", "<MID>"] },
|
||||
completionOptions: { stop: ["<PRE>", "<SUF>", "<MID>", "<EOT>"] },
|
||||
};
|
||||
|
||||
// https://huggingface.co/deepseek-ai/deepseek-coder-1.3b-base
|
||||
|
|
|
|||
|
|
@ -428,7 +428,7 @@ const EditSlashCommand: SlashCommand = {
|
|||
}
|
||||
|
||||
let messages = history;
|
||||
messages.push({ role: "user", content: prompt });
|
||||
messages[messages.length - 1] = { role: "user", content: prompt };
|
||||
|
||||
let linesOfPrefixCopied = 0;
|
||||
let lines = [];
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import EditSlashCommand from "./edit";
|
|||
import HttpSlashCommand from "./http";
|
||||
import ShareSlashCommand from "./share";
|
||||
import StackOverflowSlashCommand from "./stackOverflow";
|
||||
import VerticalEditSlashCommand from "./verticalEdit";
|
||||
|
||||
export default [
|
||||
DraftIssueCommand,
|
||||
|
|
@ -17,5 +16,4 @@ export default [
|
|||
CommentSlashCommand,
|
||||
HttpSlashCommand,
|
||||
CommitMessageCommand,
|
||||
VerticalEditSlashCommand,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { SerializedContinueConfig } from "..";
|
||||
|
||||
const defaultConfig: SerializedContinueConfig = {
|
||||
export const defaultConfig: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4",
|
||||
},
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
|
|
@ -34,7 +34,7 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Download and share this session",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
{
|
||||
name: "cmd",
|
||||
|
|
@ -61,4 +61,55 @@ const defaultConfig: SerializedContinueConfig = {
|
|||
],
|
||||
};
|
||||
|
||||
export default defaultConfig;
|
||||
export const defaultConfigJetBrains: SerializedContinueConfig = {
|
||||
models: [
|
||||
{
|
||||
title: "GPT-4 Vision (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-4-vision-preview",
|
||||
},
|
||||
{
|
||||
title: "GPT-3.5-Turbo (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
title: "Gemini Pro (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "gemini-pro",
|
||||
},
|
||||
{
|
||||
title: "Codellama 70b (Free Trial)",
|
||||
provider: "free-trial",
|
||||
model: "codellama-70b",
|
||||
},
|
||||
],
|
||||
slashCommands: [
|
||||
{
|
||||
name: "edit",
|
||||
description: "Edit selected code",
|
||||
},
|
||||
{
|
||||
name: "comment",
|
||||
description: "Write comments for the selected code",
|
||||
},
|
||||
{
|
||||
name: "share",
|
||||
description: "Export this session as markdown",
|
||||
},
|
||||
],
|
||||
customCommands: [
|
||||
{
|
||||
name: "test",
|
||||
prompt:
|
||||
"Write a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
|
||||
description: "Write unit tests for highlighted code",
|
||||
},
|
||||
],
|
||||
contextProviders: [
|
||||
{
|
||||
name: "open",
|
||||
params: {},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
196
core/config/handler.ts
Normal file
196
core/config/handler.ts
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
import { http, https } from "follow-redirects";
|
||||
import * as fs from "fs";
|
||||
import { HttpProxyAgent } from "http-proxy-agent";
|
||||
import { HttpsProxyAgent } from "https-proxy-agent";
|
||||
import fetch from "node-fetch";
|
||||
import { ContinueConfig, ContinueRcJson, IDE, ILLM } from "..";
|
||||
import { Telemetry } from "../util/posthog";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
finalToBrowserConfig,
|
||||
loadFullConfigNode,
|
||||
} from "./load";
|
||||
const tls = require("tls");
|
||||
export class ConfigHandler {
|
||||
private savedConfig: ContinueConfig | undefined;
|
||||
private savedBrowserConfig?: BrowserSerializedContinueConfig;
|
||||
|
||||
private readonly ide: IDE;
|
||||
private readonly remoteConfigServerUrl: URL | undefined;
|
||||
private readonly writeLog: (text: string) => void;
|
||||
constructor(
|
||||
ide: IDE,
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
writeLog: (text: string) => void
|
||||
) {
|
||||
this.ide = ide;
|
||||
this.remoteConfigServerUrl = remoteConfigServerUrl;
|
||||
this.writeLog = writeLog;
|
||||
try {
|
||||
this.loadConfig();
|
||||
} catch (e) {
|
||||
console.error("Failed to load config: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
reloadConfig() {
|
||||
this.savedConfig = undefined;
|
||||
this.savedBrowserConfig = undefined;
|
||||
this.loadConfig();
|
||||
}
|
||||
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
if (!this.savedBrowserConfig) {
|
||||
this.savedConfig = await this.loadConfig();
|
||||
this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig);
|
||||
}
|
||||
return this.savedBrowserConfig;
|
||||
}
|
||||
|
||||
async loadConfig(): Promise<ContinueConfig> {
|
||||
try {
|
||||
if (this.savedConfig) {
|
||||
return this.savedConfig;
|
||||
}
|
||||
|
||||
let workspaceConfigs: ContinueRcJson[] = [];
|
||||
try {
|
||||
workspaceConfigs = await this.ide.getWorkspaceConfigs();
|
||||
} catch (e) {
|
||||
console.warn("Failed to load workspace configs");
|
||||
}
|
||||
|
||||
const ideInfo = await this.ide.getIdeInfo();
|
||||
this.savedConfig = await loadFullConfigNode(
|
||||
this.ide.readFile,
|
||||
workspaceConfigs,
|
||||
this.remoteConfigServerUrl,
|
||||
ideInfo.ideType
|
||||
);
|
||||
this.savedConfig.allowAnonymousTelemetry =
|
||||
this.savedConfig.allowAnonymousTelemetry &&
|
||||
(await this.ide.isTelemetryEnabled());
|
||||
|
||||
// Setup telemetry only after (and if) we know it is enabled
|
||||
await Telemetry.setup(
|
||||
this.savedConfig.allowAnonymousTelemetry ?? true,
|
||||
await this.ide.getUniqueId()
|
||||
);
|
||||
|
||||
return this.savedConfig;
|
||||
} catch (e: any) {
|
||||
console.error("Failed to loadConfig: ", e.message);
|
||||
throw new Error("Failed to loadConfig: " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
setupLlm(llm: ILLM): ILLM {
|
||||
const TIMEOUT = 7200; // 7200 seconds = 2 hours
|
||||
// Since we know this is happening in Node.js, we can add requestOptions through a custom agent
|
||||
const ca = [...tls.rootCertificates];
|
||||
const customCerts =
|
||||
typeof llm.requestOptions?.caBundlePath === "string"
|
||||
? [llm.requestOptions?.caBundlePath]
|
||||
: llm.requestOptions?.caBundlePath;
|
||||
if (customCerts) {
|
||||
ca.push(
|
||||
...customCerts.map((customCert) => fs.readFileSync(customCert, "utf8"))
|
||||
);
|
||||
}
|
||||
|
||||
let timeout = (llm.requestOptions?.timeout || TIMEOUT) * 1000; // measured in ms
|
||||
|
||||
const agentOptions = {
|
||||
ca,
|
||||
rejectUnauthorized: llm.requestOptions?.verifySsl,
|
||||
timeout,
|
||||
sessionTimeout: timeout,
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: timeout,
|
||||
};
|
||||
|
||||
const proxy = llm.requestOptions?.proxy;
|
||||
|
||||
llm._fetch = async (input, init) => {
|
||||
// Create agent
|
||||
const protocol = new URL(input).protocol === "https:" ? https : http;
|
||||
const agent = proxy
|
||||
? new URL(input).protocol === "https:"
|
||||
? new HttpsProxyAgent(proxy, agentOptions)
|
||||
: new HttpProxyAgent(proxy, agentOptions)
|
||||
: new protocol.Agent(agentOptions);
|
||||
|
||||
const headers: { [key: string]: string } =
|
||||
llm!.requestOptions?.headers || {};
|
||||
for (const [key, value] of Object.entries(init?.headers || {})) {
|
||||
headers[key] = value as string;
|
||||
}
|
||||
|
||||
// Replace localhost with 127.0.0.1
|
||||
input = new URL(input);
|
||||
if (input.hostname === "localhost") {
|
||||
input.hostname = "127.0.0.1";
|
||||
}
|
||||
|
||||
let updatedBody: string | undefined = undefined;
|
||||
try {
|
||||
if (
|
||||
llm.requestOptions?.extraBodyProperties &&
|
||||
typeof init.body === "string"
|
||||
) {
|
||||
const parsedBody = JSON.parse(init.body);
|
||||
updatedBody = JSON.stringify({
|
||||
...parsedBody,
|
||||
...llm.requestOptions.extraBodyProperties,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.log("Unable to parse HTTP request body: ", e);
|
||||
}
|
||||
|
||||
const resp = await fetch(input, {
|
||||
...init,
|
||||
body: updatedBody ?? init.body,
|
||||
headers,
|
||||
agent,
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
let text = await resp.text();
|
||||
if (resp.status === 404 && !resp.url.includes("/v1")) {
|
||||
if (text.includes("try pulling it first")) {
|
||||
const model = JSON.parse(text).error.split(" ")[1].slice(1, -1);
|
||||
text = `The model "${model}" was not found. To download it, run \`ollama run ${model}\`.`;
|
||||
} else if (text.includes("/api/chat")) {
|
||||
text =
|
||||
"The /api/chat endpoint was not found. This may mean that you are using an older version of Ollama that does not support /api/chat. Upgrading to the latest version will solve the issue.";
|
||||
} else {
|
||||
text =
|
||||
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`
|
||||
);
|
||||
}
|
||||
|
||||
return resp;
|
||||
};
|
||||
|
||||
llm.writeLog = async (log: string) => {
|
||||
this.writeLog(log);
|
||||
};
|
||||
return llm;
|
||||
}
|
||||
|
||||
async llmFromTitle(title?: string): Promise<ILLM> {
|
||||
const config = await this.loadConfig();
|
||||
const model =
|
||||
config.models.find((m) => m.title === title) || config.models[0];
|
||||
if (!model) {
|
||||
throw new Error("No model found");
|
||||
}
|
||||
|
||||
return this.setupLlm(model);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import {
|
||||
BaseCompletionOptions,
|
||||
BrowserSerializedContinueConfig,
|
||||
Config,
|
||||
ContextProviderDescription,
|
||||
ContextProviderWithParams,
|
||||
ContinueConfig,
|
||||
ContinueRcJson,
|
||||
|
|
@ -10,12 +10,11 @@ import {
|
|||
CustomLLM,
|
||||
EmbeddingsProviderDescription,
|
||||
IContextProvider,
|
||||
IdeType,
|
||||
ModelDescription,
|
||||
SerializedContinueConfig,
|
||||
SlashCommand,
|
||||
SlashCommandDescription,
|
||||
} from "..";
|
||||
|
||||
import {
|
||||
slashCommandFromDescription,
|
||||
slashFromCustomCommand,
|
||||
|
|
@ -31,32 +30,46 @@ import CustomLLMClass from "../llm/llms/CustomLLM";
|
|||
import mergeJson from "../util/merge";
|
||||
import {
|
||||
getConfigJsPath,
|
||||
getConfigJsPathForRemote,
|
||||
getConfigJsonPath,
|
||||
getConfigJsonPathForRemote,
|
||||
getConfigTsPath,
|
||||
getContinueDotEnv,
|
||||
migrate,
|
||||
} from "../util/paths";
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
|
||||
let content = fs.readFileSync(filepath, "utf8");
|
||||
let config = JSON.parse(content) as SerializedContinueConfig;
|
||||
if (config.env && Array.isArray(config.env)) {
|
||||
const env = {
|
||||
...process.env,
|
||||
...getContinueDotEnv(),
|
||||
};
|
||||
|
||||
config.env.forEach((envVar) => {
|
||||
content = content.replaceAll(
|
||||
new RegExp(`"${envVar}"`, "g"),
|
||||
`"${env[envVar]}"`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return JSON.parse(content);
|
||||
}
|
||||
|
||||
function loadSerializedConfig(
|
||||
workspaceConfigs: ContinueRcJson[]
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType
|
||||
): SerializedContinueConfig {
|
||||
const configPath = getConfigJsonPath();
|
||||
let contents = fs.readFileSync(configPath, "utf8");
|
||||
let config = JSON.parse(contents) as SerializedContinueConfig;
|
||||
const configPath = getConfigJsonPath(ideType);
|
||||
let config = resolveSerializedConfig(configPath);
|
||||
if (config.allowAnonymousTelemetry === undefined) {
|
||||
config.allowAnonymousTelemetry = true;
|
||||
}
|
||||
|
||||
// Migrate to camelCase - replace all instances of "snake_case" with "camelCase"
|
||||
migrate("camelCaseConfig", () => {
|
||||
contents = contents
|
||||
.replace(/(_\w)/g, function (m) {
|
||||
return m[1].toUpperCase();
|
||||
})
|
||||
.replace("openai-aiohttp", "openai");
|
||||
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
|
||||
migrate("codebaseContextProvider", () => {
|
||||
if (
|
||||
!config.contextProviders?.filter((cp) => cp.name === "codebase")?.length
|
||||
|
|
@ -111,10 +124,12 @@ function loadSerializedConfig(
|
|||
fs.writeFileSync(configPath, JSON.stringify(config, undefined, 2), "utf8");
|
||||
});
|
||||
|
||||
migrate("renameFreeTrialProvider", () => {
|
||||
contents = contents.replace(/openai-free-trial/g, "free-trial");
|
||||
fs.writeFileSync(configPath, contents, "utf8");
|
||||
});
|
||||
if (remoteConfigServerUrl) {
|
||||
const remoteConfigJson = resolveSerializedConfig(
|
||||
getConfigJsonPathForRemote(remoteConfigServerUrl)
|
||||
);
|
||||
config = mergeJson(config, remoteConfigJson, "merge");
|
||||
}
|
||||
|
||||
for (const workspaceConfig of workspaceConfigs) {
|
||||
config = mergeJson(config, workspaceConfig, workspaceConfig.mergeBehavior);
|
||||
|
|
@ -275,19 +290,6 @@ async function intermediateToFinalConfig(
|
|||
};
|
||||
}
|
||||
|
||||
interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
|
||||
function finalToBrowserConfig(
|
||||
final: ContinueConfig
|
||||
): BrowserSerializedContinueConfig {
|
||||
|
|
@ -321,49 +323,101 @@ function finalToBrowserConfig(
|
|||
};
|
||||
}
|
||||
|
||||
async function buildConfigTs(browser: boolean) {
|
||||
function getTarget() {
|
||||
const os =
|
||||
{
|
||||
aix: "linux",
|
||||
darwin: "darwin",
|
||||
freebsd: "linux",
|
||||
linux: "linux",
|
||||
openbsd: "linux",
|
||||
sunos: "linux",
|
||||
win32: "win32",
|
||||
}[process.platform as string] ?? "linux";
|
||||
const arch = {
|
||||
arm: "arm64",
|
||||
arm64: "arm64",
|
||||
ia32: "x64",
|
||||
loong64: "arm64",
|
||||
mips: "arm64",
|
||||
mipsel: "arm64",
|
||||
ppc: "x64",
|
||||
ppc64: "x64",
|
||||
riscv64: "arm64",
|
||||
s390: "x64",
|
||||
s390x: "x64",
|
||||
x64: "x64",
|
||||
}[process.arch];
|
||||
|
||||
return `${os}-${arch}`;
|
||||
}
|
||||
|
||||
function escapeSpacesInPath(p: string): string {
|
||||
return p.replace(/ /g, "\\ ");
|
||||
}
|
||||
|
||||
async function buildConfigTs() {
|
||||
if (!fs.existsSync(getConfigTsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
if (process.env.IS_BINARY === "true") {
|
||||
execSync(
|
||||
escapeSpacesInPath(path.dirname(process.execPath)) +
|
||||
`/esbuild${
|
||||
getTarget().startsWith("win32") ? ".exe" : ""
|
||||
} ${escapeSpacesInPath(
|
||||
getConfigTsPath()
|
||||
)} --bundle --outfile=${escapeSpacesInPath(
|
||||
getConfigJsPath()
|
||||
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`
|
||||
);
|
||||
} else {
|
||||
// Dynamic import esbuild so potentially disastrous errors can be caught
|
||||
const esbuild = require("esbuild");
|
||||
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: browser ? "browser" : "node",
|
||||
format: browser ? "esm" : "cjs",
|
||||
outfile: getConfigJsPath(!browser),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
await esbuild.build({
|
||||
entryPoints: [getConfigTsPath()],
|
||||
bundle: true,
|
||||
platform: "node",
|
||||
format: "cjs",
|
||||
outfile: getConfigJsPath(),
|
||||
external: ["fetch", "fs", "path", "os", "child_process"],
|
||||
sourcemap: true,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
console.log(
|
||||
"Build error. Please check your ~/.continue/config.ts file: " + e
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!fs.existsSync(getConfigJsPath(!browser))) {
|
||||
if (!fs.existsSync(getConfigJsPath())) {
|
||||
return undefined;
|
||||
}
|
||||
return fs.readFileSync(getConfigJsPath(!browser), "utf8");
|
||||
return fs.readFileSync(getConfigJsPath(), "utf8");
|
||||
}
|
||||
|
||||
async function loadFullConfigNode(
|
||||
readFile: (filepath: string) => Promise<string>,
|
||||
workspaceConfigs: ContinueRcJson[]
|
||||
workspaceConfigs: ContinueRcJson[],
|
||||
remoteConfigServerUrl: URL | undefined,
|
||||
ideType: IdeType
|
||||
): Promise<ContinueConfig> {
|
||||
let serialized = loadSerializedConfig(workspaceConfigs);
|
||||
let serialized = loadSerializedConfig(
|
||||
workspaceConfigs,
|
||||
remoteConfigServerUrl,
|
||||
ideType
|
||||
);
|
||||
let intermediate = serializedToIntermediateConfig(serialized);
|
||||
|
||||
const configJsContents = await buildConfigTs(false);
|
||||
const configJsContents = await buildConfigTs();
|
||||
if (configJsContents) {
|
||||
try {
|
||||
// Try config.ts first
|
||||
const configJsPath = getConfigJsPath(true);
|
||||
const configJsPath = getConfigJsPath();
|
||||
const module = await require(configJsPath);
|
||||
delete require.cache[require.resolve(configJsPath)];
|
||||
if (!module.modifyConfig) {
|
||||
|
|
@ -374,6 +428,24 @@ async function loadFullConfigNode(
|
|||
console.log("Error loading config.ts: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Remote config.js
|
||||
if (remoteConfigServerUrl) {
|
||||
try {
|
||||
const configJsPathForRemote = getConfigJsPathForRemote(
|
||||
remoteConfigServerUrl
|
||||
);
|
||||
const module = await require(configJsPathForRemote);
|
||||
delete require.cache[require.resolve(configJsPathForRemote)];
|
||||
if (!module.modifyConfig) {
|
||||
throw new Error("config.ts does not export a modifyConfig function.");
|
||||
}
|
||||
intermediate = module.modifyConfig(intermediate);
|
||||
} catch (e) {
|
||||
console.log("Error loading remotely set config.js: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
const finalConfig = await intermediateToFinalConfig(intermediate, readFile);
|
||||
return finalConfig;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,28 @@
|
|||
const Types = `
|
||||
declare global {
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
windowId: string;
|
||||
serverUrl: string;
|
||||
vscMachineId: string;
|
||||
vscMediaUrl: string;
|
||||
fullColorTheme?: {
|
||||
rules?: {
|
||||
token?: string;
|
||||
foreground?: string;
|
||||
}[];
|
||||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChunkWithoutID {
|
||||
content: string;
|
||||
startLine: number;
|
||||
|
|
@ -68,6 +91,8 @@ declare global {
|
|||
countTokens(text: string): number;
|
||||
|
||||
supportsImages(): boolean;
|
||||
|
||||
listModels(): Promise<string[]>;
|
||||
}
|
||||
|
||||
export type ContextProviderType = "normal" | "query" | "submenu";
|
||||
|
|
@ -76,6 +101,7 @@ declare global {
|
|||
title: string;
|
||||
displayTitle: string;
|
||||
description: string;
|
||||
renderInlineAs?: string;
|
||||
type: ContextProviderType;
|
||||
}
|
||||
|
||||
|
|
@ -95,6 +121,7 @@ declare global {
|
|||
title: string;
|
||||
displayTitle?: string;
|
||||
description?: string;
|
||||
renderInlineAs?: string;
|
||||
type?: ContextProviderType;
|
||||
getContextItems(
|
||||
query: string,
|
||||
|
|
@ -264,6 +291,9 @@ declare global {
|
|||
options: CompletionOptions,
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
) => AsyncGenerator<string>;
|
||||
listModels?: (
|
||||
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>
|
||||
) => Promise<string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -287,14 +317,24 @@ declare global {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<SerializedContinueConfig>;
|
||||
getConfigJsUrl(): Promise<string | undefined>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -302,38 +342,24 @@ declare global {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void>;
|
||||
showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -346,6 +372,8 @@ declare global {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -399,7 +427,9 @@ declare global {
|
|||
| "openchat"
|
||||
| "deepseek"
|
||||
| "xwin-coder"
|
||||
| "neural-chat";
|
||||
| "neural-chat"
|
||||
| "codellama-70b"
|
||||
| "llava";
|
||||
|
||||
type ModelProvider =
|
||||
| "openai"
|
||||
|
|
@ -422,6 +452,7 @@ declare global {
|
|||
| "flowise";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
// OpenAI
|
||||
| "gpt-3.5-turbo"
|
||||
| "gpt-3.5-turbo-16k"
|
||||
|
|
@ -429,6 +460,7 @@ declare global {
|
|||
| "gpt-3.5-turbo-0613"
|
||||
| "gpt-4-32k"
|
||||
| "gpt-4-turbo-preview"
|
||||
| "gpt-4-vision-preview"
|
||||
// Open Source
|
||||
| "mistral-7b"
|
||||
| "mistral-8x7b"
|
||||
|
|
@ -437,6 +469,7 @@ declare global {
|
|||
| "codellama-7b"
|
||||
| "codellama-13b"
|
||||
| "codellama-34b"
|
||||
| "codellama-70b"
|
||||
| "phi2"
|
||||
| "phind-codellama-34b"
|
||||
| "wizardcoder-7b"
|
||||
|
|
@ -444,7 +477,6 @@ declare global {
|
|||
| "wizardcoder-34b"
|
||||
| "zephyr-7b"
|
||||
| "codeup-13b"
|
||||
| "deepseek-1b"
|
||||
| "deepseek-7b"
|
||||
| "deepseek-33b"
|
||||
| "neural-chat-7b"
|
||||
|
|
@ -457,7 +489,12 @@ declare global {
|
|||
// Mistral
|
||||
| "mistral-tiny"
|
||||
| "mistral-small"
|
||||
| "mistral-medium";
|
||||
| "mistral-medium"
|
||||
// Tab autocomplete
|
||||
| "deepseek-1b"
|
||||
| "starcoder-1b"
|
||||
| "starcoder-3b"
|
||||
| "stable-code-3b";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
|
|
@ -465,6 +502,7 @@ declare global {
|
|||
caBundlePath?: string | string[];
|
||||
proxy?: string;
|
||||
headers?: { [key: string]: string };
|
||||
extraBodyProperties?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface StepWithParams {
|
||||
|
|
@ -532,6 +570,17 @@ declare global {
|
|||
embed(chunks: string[]): Promise<number[][]>;
|
||||
}
|
||||
|
||||
export interface TabAutocompleteOptions {
|
||||
useCopyBuffer: boolean;
|
||||
useSuffix: boolean;
|
||||
maxPromptTokens: number;
|
||||
debounceDelay: number;
|
||||
maxSuffixPercentage: number;
|
||||
prefixPercentage: number;
|
||||
template?: string;
|
||||
disableMultiLineCompletions?: boolean;
|
||||
}
|
||||
|
||||
export interface SerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
|
|
@ -544,8 +593,16 @@ declare global {
|
|||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: EmbeddingsProviderDescription;
|
||||
tabAutocompleteModel?: ModelDescription;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export type ConfigMergeType = "merge" | "overwrite";
|
||||
|
||||
export type ContinueRcJson = Partial<SerializedContinueConfig> & {
|
||||
mergeBehavior: ConfigMergeType;
|
||||
};
|
||||
|
||||
export interface Config {
|
||||
/** If set to true, Continue will collect anonymous usage data to improve the product. If set to false, we will collect nothing. Read here to learn more: https://continue.dev/docs/telemetry */
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
|
|
@ -572,6 +629,10 @@ declare global {
|
|||
userToken?: string;
|
||||
/** The provider used to calculate embeddings. If left empty, Continue will use transformers.js to calculate the embeddings with all-MiniLM-L6-v2 */
|
||||
embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider;
|
||||
/** The model that Continue will use for tab autocompletions. */
|
||||
tabAutocompleteModel?: CustomLLM | ModelDescription;
|
||||
/** Options for tab autocomplete */
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export interface ContinueConfig {
|
||||
|
|
@ -585,8 +646,22 @@ declare global {
|
|||
disableIndexing?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider: EmbeddingsProvider;
|
||||
tabAutocompleteModel?: ILLM;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
||||
|
|
|
|||
38
core/config/util.ts
Normal file
38
core/config/util.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { ModelDescription } from "..";
|
||||
import { editConfigJson, getConfigJsonPath } from "../util/paths";
|
||||
|
||||
export function addModel(model: ModelDescription) {
|
||||
const config = readFileSync(getConfigJsonPath(), "utf8");
|
||||
const configJson = JSON.parse(config);
|
||||
configJson.models.push(model);
|
||||
const newConfigString = JSON.stringify(
|
||||
configJson,
|
||||
(key, value) => {
|
||||
return value === null ? undefined : value;
|
||||
},
|
||||
2
|
||||
);
|
||||
writeFileSync(getConfigJsonPath(), newConfigString);
|
||||
return newConfigString;
|
||||
}
|
||||
|
||||
export function addOpenAIKey(key: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.map((m: ModelDescription) => {
|
||||
if (m.provider === "free-trial") {
|
||||
m.apiKey = key;
|
||||
m.provider = "openai";
|
||||
}
|
||||
return m;
|
||||
});
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
||||
export function deleteModel(title: string) {
|
||||
editConfigJson((config) => {
|
||||
config.models = config.models.filter((m: any) => m.title !== title);
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
|
@ -6,7 +6,7 @@ import {
|
|||
} from "../..";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getFileOutlineHighlights } from "llm-code-highlighter/dist/index.continue";
|
||||
import { getOutlines } from "llm-code-highlighter/dist/index.continue";
|
||||
|
||||
class CodeOutlineContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
|
|
@ -32,7 +32,7 @@ class CodeOutlineContextProvider extends BaseContextProvider {
|
|||
};
|
||||
})
|
||||
);
|
||||
const outlines = await getFileOutlineHighlights(
|
||||
const outlines = await getOutlines(
|
||||
allFiles
|
||||
.filter((file) => file.content.length > 0)
|
||||
.map((file) => {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ class CodebaseContextProvider extends BaseContextProvider {
|
|||
displayTitle: "Codebase",
|
||||
description: "Automatically find relevant files",
|
||||
type: "normal",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ class CustomContextProviderClass implements IContextProvider {
|
|||
displayTitle: this.custom.displayTitle || this.custom.title,
|
||||
description: this.custom.description || "",
|
||||
type: this.custom.type || "normal",
|
||||
renderInlineAs: this.custom.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
112
core/context/providers/DatabaseContextProvider.ts
Normal file
112
core/context/providers/DatabaseContextProvider.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
LoadSubmenuItemsArgs,
|
||||
ContextSubmenuItem,
|
||||
} from "../..";
|
||||
|
||||
class DatabaseContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "database",
|
||||
displayTitle: "Database",
|
||||
description: "Table schemas",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
): Promise<ContextItem[]> {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) { return contextItems; }
|
||||
|
||||
let [connectionName, table] = query.split('.');
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
if(connection.name == connectionName) {
|
||||
const adapter = getDatabaseAdapter(connection.connection_type, connection.connection);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(connection.connection.database);
|
||||
|
||||
if(table === 'all') {
|
||||
let prompt = `Schema for all tables on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-all-tables-schemas`,
|
||||
description: `Schema for all tables.`,
|
||||
content: prompt
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
} else {
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
tables.forEach(tableName => {
|
||||
if(table === tableName) {
|
||||
let prompt = `Schema for ${tableName} on ${connection.connection_type} is `;
|
||||
prompt += JSON.stringify(tablesAndSchemas[tableName]);
|
||||
|
||||
let contextItem = {
|
||||
name: `${connectionName}-${tableName}-schema`,
|
||||
description: `${tableName} Schema`,
|
||||
content: prompt
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const connections = this.options?.connections;
|
||||
|
||||
if (connections === null) { return contextItems; }
|
||||
|
||||
const getDatabaseAdapter = await require("dbinfoz");
|
||||
|
||||
for (const connection of connections) {
|
||||
let adapter = getDatabaseAdapter(connection.connection_type, connection.connection);
|
||||
const tablesAndSchemas = await adapter.getAllTablesAndSchemas(connection.connection.database);
|
||||
const tables = Object.keys(tablesAndSchemas);
|
||||
|
||||
let contextItem = {
|
||||
id: `${connection.name}.all`,
|
||||
title: `${connection.name} all table schemas`,
|
||||
description: ``
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
|
||||
tables.forEach(tableName => {
|
||||
let contextItem = {
|
||||
id: `${connection.name}.${tableName}`,
|
||||
title: `${connection.name}.${tableName} schema`,
|
||||
description: ``
|
||||
}
|
||||
|
||||
contextItems.push(contextItem);
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
}
|
||||
}
|
||||
|
||||
export default DatabaseContextProvider;
|
||||
|
||||
134
core/context/providers/JiraIssuesContextProvider.ts
Normal file
134
core/context/providers/JiraIssuesContextProvider.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
import type { AxiosInstance } from "axios";
|
||||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
} from "../..";
|
||||
const { convert } = require("adf-to-md");
|
||||
|
||||
interface JiraComment {
|
||||
id: string;
|
||||
created: string;
|
||||
updated: string;
|
||||
author: {
|
||||
emailAddress: string;
|
||||
displayName: string;
|
||||
};
|
||||
body: object;
|
||||
}
|
||||
|
||||
interface JiraIssue {
|
||||
id: string;
|
||||
key: string;
|
||||
fields: {
|
||||
summary: string;
|
||||
description: object;
|
||||
comment: {
|
||||
total: number;
|
||||
comments: Array<JiraComment>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface QueryResults {
|
||||
issues: JiraIssue[];
|
||||
}
|
||||
|
||||
class JiraIssuesContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "jira",
|
||||
displayTitle: "Jira Issues",
|
||||
description: "Reference Jira issues",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
private async createApi(): Promise<AxiosInstance> {
|
||||
const { default: Axios } = await import("axios");
|
||||
|
||||
return Axios.create({
|
||||
baseURL: `https://${this.options.domain}/rest/api/3/`,
|
||||
auth: {
|
||||
username: this.options.email,
|
||||
password: this.options.token,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras
|
||||
): Promise<ContextItem[]> {
|
||||
const issueId = query;
|
||||
|
||||
const api = await this.createApi();
|
||||
|
||||
const issue = await api
|
||||
.get<JiraIssue>(`/issue/${issueId}`, {
|
||||
params: {
|
||||
fields: "description,comment,summary",
|
||||
},
|
||||
})
|
||||
.then((result) => result.data);
|
||||
|
||||
const parts = [
|
||||
`# Jira Issue ${issue.key}: ${issue.fields.summary}`,
|
||||
"## Description",
|
||||
issue.fields.description
|
||||
? convert(issue.fields.description).result
|
||||
: "No description",
|
||||
];
|
||||
|
||||
if (issue.fields.comment.comments.length > 0) {
|
||||
parts.push("## Comments");
|
||||
|
||||
parts.push(
|
||||
...issue.fields.comment.comments.map((comment) => {
|
||||
const commentText = convert(comment.body).result;
|
||||
|
||||
return `### ${comment.author.displayName} on ${comment.created}\n\n${commentText}`;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
const content = parts.join("\n\n");
|
||||
|
||||
return [
|
||||
{
|
||||
name: `${issue.key}: ${issue.fields.summary}`,
|
||||
content,
|
||||
description: issue.key,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const api = await this.createApi();
|
||||
|
||||
try {
|
||||
const results = await api.get<QueryResults>("/search", {
|
||||
params: {
|
||||
jql:
|
||||
this.options.issueQuery ??
|
||||
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
|
||||
fields: "summary",
|
||||
},
|
||||
});
|
||||
|
||||
return results.data.issues.map((issue) => ({
|
||||
id: issue.id,
|
||||
title: `${issue.key}: ${issue.fields.summary}`,
|
||||
description: "",
|
||||
}));
|
||||
} catch (ex) {
|
||||
console.error(`Unable to get jira tickets: ${ex}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default JiraIssuesContextProvider;
|
||||
146
core/context/providers/PostgresContextProvider.ts
Normal file
146
core/context/providers/PostgresContextProvider.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
LoadSubmenuItemsArgs,
|
||||
ContextSubmenuItem,
|
||||
} from "../..";
|
||||
|
||||
class PostgresContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "postgres",
|
||||
displayTitle: "PostgreSQL",
|
||||
description: "Retrieve PostgreSQL table schema and sample rows",
|
||||
type: "submenu",
|
||||
};
|
||||
|
||||
static ALL_TABLES = "__all_tables";
|
||||
static DEFAULT_SAMPLE_ROWS = 3;
|
||||
|
||||
constructor(options: {
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
password: string;
|
||||
database: string;
|
||||
schema?: string;
|
||||
sampleRows?: number;
|
||||
}) {
|
||||
super(options);
|
||||
}
|
||||
|
||||
private async getPool() {
|
||||
const pg = await require("pg");
|
||||
return new pg.Pool({
|
||||
host: this.options.host,
|
||||
port: this.options.port,
|
||||
user: this.options.user,
|
||||
password: this.options.password,
|
||||
database: this.options.database,
|
||||
});
|
||||
}
|
||||
|
||||
private async getTableNames(pool: any): Promise<string[]> {
|
||||
const schema = this.options.schema ?? "public";
|
||||
var tablesInfoQuery = `
|
||||
SELECT table_schema, table_name
|
||||
FROM information_schema.tables`;
|
||||
if (schema != null) {
|
||||
tablesInfoQuery += ` WHERE table_schema = '${schema}'`;
|
||||
}
|
||||
const { rows: tablesInfo } = await pool.query(tablesInfoQuery);
|
||||
return tablesInfo.map(
|
||||
(tableInfo: any) => `${tableInfo.table_schema}.${tableInfo.table_name}`
|
||||
);
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string = "",
|
||||
_: ContextProviderExtras = {} as ContextProviderExtras
|
||||
): Promise<ContextItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextItem[] = [];
|
||||
|
||||
const tableNames = [];
|
||||
if (query === PostgresContextProvider.ALL_TABLES) {
|
||||
tableNames.push(...(await this.getTableNames(pool)));
|
||||
} else {
|
||||
tableNames.push(query);
|
||||
}
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
// Get the table schema
|
||||
if (!tableName.includes(".")) {
|
||||
throw new Error(
|
||||
`Table name must be in format schema.table_name, got ${tableName}`
|
||||
);
|
||||
}
|
||||
var schemaQuery = `
|
||||
SELECT column_name, data_type, character_maximum_length
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE table_schema = '${tableName.split(".")[0]}'
|
||||
AND table_name = '${tableName.split(".")[1]}'`;
|
||||
console.log("schemaQuery", schemaQuery);
|
||||
const { rows: tableSchema } = await pool.query(schemaQuery);
|
||||
|
||||
// Get the sample rows
|
||||
const sampleRows =
|
||||
this.options.sampleRows ??
|
||||
PostgresContextProvider.DEFAULT_SAMPLE_ROWS;
|
||||
const { rows: sampleRowResults } = await pool.query(`
|
||||
SELECT *
|
||||
FROM ${tableName}
|
||||
LIMIT ${sampleRows}`);
|
||||
|
||||
// Create prompt from the table schema and sample rows
|
||||
var prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`;
|
||||
prompt += `${JSON.stringify(tableSchema, null, 2)}\n\n`;
|
||||
prompt += `Sample rows: ${JSON.stringify(sampleRowResults, null, 2)}`;
|
||||
|
||||
contextItems.push({
|
||||
name: `${this.options.database}-${tableName}-schema-and-sample-rows`,
|
||||
description: `Schema and sample rows for table ${tableName}`,
|
||||
content: prompt,
|
||||
});
|
||||
}
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
} finally {
|
||||
}
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
_: LoadSubmenuItemsArgs
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
const pool = await this.getPool();
|
||||
|
||||
try {
|
||||
const contextItems: ContextSubmenuItem[] = [];
|
||||
const tableNames = await this.getTableNames(pool);
|
||||
|
||||
for (const tableName of tableNames) {
|
||||
contextItems.push({
|
||||
id: tableName,
|
||||
title: tableName,
|
||||
description: `Schema from ${tableName} and ${this.options.sampleRows} sample rows.`,
|
||||
});
|
||||
}
|
||||
contextItems.push({
|
||||
id: PostgresContextProvider.ALL_TABLES,
|
||||
title: "All tables",
|
||||
description: `Schema from all tables and ${this.options.sampleRows} sample rows each.`,
|
||||
});
|
||||
|
||||
return contextItems;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to query PostgreSQL database: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default PostgresContextProvider;
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import { ContextProviderName } from "../..";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import CodeHighlightsContextProvider from "./CodeHighlightsContextProvider";
|
||||
import CodeOutlineContextProvider from "./CodeOutlineContextProvider";
|
||||
import CodebaseContextProvider from "./CodebaseContextProvider";
|
||||
import DatabaseContextProvider from "./DatabaseContextProvider";
|
||||
import DiffContextProvider from "./DiffContextProvider";
|
||||
import DocsContextProvider from "./DocsContextProvider";
|
||||
import FileTreeContextProvider from "./FileTreeContextProvider";
|
||||
|
|
@ -10,7 +11,9 @@ import FolderContextProvider from "./FolderContextProvider";
|
|||
import GitHubIssuesContextProvider from "./GitHubIssuesContextProvider";
|
||||
import GoogleContextProvider from "./GoogleContextProvider";
|
||||
import HttpContextProvider from "./HttpContextProvider";
|
||||
import JiraIssuesContextProvider from "./JiraIssuesContextProvider";
|
||||
import OpenFilesContextProvider from "./OpenFilesContextProvider";
|
||||
import PostgresContextProvider from "./PostgresContextProvider";
|
||||
import ProblemsContextProvider from "./ProblemsContextProvider";
|
||||
import SearchContextProvider from "./SearchContextProvider";
|
||||
import TerminalContextProvider from "./TerminalContextProvider";
|
||||
|
|
@ -32,6 +35,9 @@ const Providers: (typeof BaseContextProvider)[] = [
|
|||
DocsContextProvider,
|
||||
CodeHighlightsContextProvider,
|
||||
CodeOutlineContextProvider,
|
||||
JiraIssuesContextProvider,
|
||||
PostgresContextProvider,
|
||||
DatabaseContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
|
||||
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
|
||||
import { LanceDbIndex } from "../indexing/LanceDbIndex";
|
||||
import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex";
|
||||
import { IndexTag } from "../indexing/types";
|
||||
import { llmCanGenerateInParallel } from "../llm/autodetect";
|
||||
|
|
@ -137,7 +138,7 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
if (extras.fullInput.trim() !== "") {
|
||||
ftsResults = await ftsIndex.retrieve(
|
||||
tags,
|
||||
extras.fullInput.trim().split(" ").join(" OR "),
|
||||
extras.fullInput.trim().split(" ").map(element => `"${element}"`).join(" OR "),
|
||||
nRetrieve / 2,
|
||||
filterDirectory,
|
||||
undefined
|
||||
|
|
@ -147,7 +148,11 @@ export async function retrieveContextItemsFromEmbeddings(
|
|||
console.warn("Error retrieving from FTS:", e);
|
||||
}
|
||||
|
||||
let vecResults = await extras.ide.retrieveChunks(
|
||||
const lanceDbIndex = new LanceDbIndex(extras.embeddingsProvider, (path) =>
|
||||
extras.ide.readFile(path)
|
||||
);
|
||||
let vecResults = await lanceDbIndex.retrieve(
|
||||
tags,
|
||||
extras.fullInput,
|
||||
nRetrieve,
|
||||
filterDirectory
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export async function* streamDiff(
|
|||
oldLines: string[],
|
||||
newLines: LineStream
|
||||
): AsyncGenerator<DiffLine> {
|
||||
oldLines = [...oldLines]; // be careful
|
||||
const mutatedOldLines = [...oldLines]; // be careful
|
||||
let seenIndentationMistake = false;
|
||||
|
||||
let newLineResult = await newLines.next();
|
||||
|
|
|
|||
|
|
@ -1,131 +0,0 @@
|
|||
import { Chunk, DiffLine, Problem } from "..";
|
||||
import { BrowserSerializedContinueConfig } from "../config/load";
|
||||
import { IDE } from "../index";
|
||||
|
||||
import { ideRequest } from "./messaging";
|
||||
async function r(messageType: string, options: any = {}) {
|
||||
return await ideRequest(messageType, options);
|
||||
}
|
||||
export class ExtensionIde implements IDE {
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
return await r("getSerializedConfig");
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
return await r("getDiff");
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
return await r("getTerminalContents");
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
return await r("listWorkspaceContents");
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return await r("getWorkspaceDirs");
|
||||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void> {
|
||||
return await r("showLines", { filepath, startLine, endLine });
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await r("listFolders");
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await r("getContinueDir");
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await r("writeFile", { path, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await r("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await r("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await r("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await r("saveFile", { filepath });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await r("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await r("showDiff", { filepath, newContents, stepIndex });
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
await r("diffLine", { filepath, startLine, endLine, diffLine });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return r("getOpenFiles");
|
||||
}
|
||||
|
||||
getPinnedFiles(): Promise<string[]> {
|
||||
return r("getPinnedFiles");
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return r("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
return r("getProblems", { filepath });
|
||||
}
|
||||
|
||||
subprocess(command: string): Promise<[string, string]> {
|
||||
return r("subprocess", { command });
|
||||
}
|
||||
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
|
||||
return r("getFilesToEmbed", { providerId });
|
||||
}
|
||||
|
||||
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {
|
||||
return r("sendChunkForFile", { chunk, embedding, tags });
|
||||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return r("getBranch", { dir });
|
||||
}
|
||||
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
return r("retrieveChunks", { text, n, directory });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
// import "vscode-webview";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { ChatMessage, LLMFullCompletionOptions, LLMReturnValue } from "..";
|
||||
interface vscode {
|
||||
postMessage(message: any): vscode;
|
||||
}
|
||||
|
||||
declare const vscode: any;
|
||||
|
||||
function _postToIde(type: string, data: any) {
|
||||
if (typeof vscode === "undefined") {
|
||||
if (localStorage.getItem("ide") === "jetbrains") {
|
||||
if (window.postIntellijMessage === undefined) {
|
||||
console.log(
|
||||
"Unable to send message: postIntellijMessage is undefined. ",
|
||||
type,
|
||||
data
|
||||
);
|
||||
throw new Error("postIntellijMessage is undefined");
|
||||
}
|
||||
window.postIntellijMessage?.(type, data);
|
||||
return;
|
||||
} else {
|
||||
console.log("Unable to send message: vscode is undefined. ", type, data);
|
||||
return;
|
||||
}
|
||||
}
|
||||
vscode.postMessage({
|
||||
type,
|
||||
...data,
|
||||
});
|
||||
}
|
||||
|
||||
export function postToIde(type: string, data: any, attempt: number = 0) {
|
||||
try {
|
||||
_postToIde(type, data);
|
||||
} catch (error) {
|
||||
if (attempt < 5) {
|
||||
console.log(`Attempt ${attempt} failed. Retrying...`);
|
||||
setTimeout(
|
||||
() => postToIde(type, data, attempt + 1),
|
||||
Math.pow(2, attempt) * 1000
|
||||
);
|
||||
} else {
|
||||
console.error("Max attempts reached. Message could not be sent.", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function ideRequest(type: string, message: any): Promise<any> {
|
||||
// message, messageId, and type are passed back and forth
|
||||
const messageId = uuidv4();
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
window.removeEventListener("message", handler);
|
||||
resolve(event.data.message);
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
});
|
||||
}
|
||||
|
||||
export async function* ideStreamRequest(
|
||||
type: string,
|
||||
message: any,
|
||||
cancelToken?: AbortSignal
|
||||
): AsyncGenerator<any, any> {
|
||||
const messageId = uuidv4();
|
||||
|
||||
postToIde(type, { message, messageId });
|
||||
|
||||
let buffer = "";
|
||||
let index = 0;
|
||||
let done = false;
|
||||
let returnVal = undefined;
|
||||
|
||||
const handler = (event: any) => {
|
||||
if (event.data.messageId === messageId) {
|
||||
if (event.data.message.done) {
|
||||
window.removeEventListener("message", handler);
|
||||
done = true;
|
||||
returnVal = event.data.message.data;
|
||||
} else {
|
||||
buffer += event.data.message.content || "";
|
||||
}
|
||||
}
|
||||
};
|
||||
window.addEventListener("message", handler);
|
||||
|
||||
cancelToken?.addEventListener("abort", () => {
|
||||
postToIde("abort", { messageId });
|
||||
});
|
||||
|
||||
while (!done) {
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
} else {
|
||||
yield undefined;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
if (buffer.length > index) {
|
||||
const chunk = buffer.slice(index);
|
||||
index = buffer.length;
|
||||
yield chunk;
|
||||
}
|
||||
|
||||
return returnVal;
|
||||
}
|
||||
|
||||
export async function* llmStreamChat(
|
||||
modelTitle: string,
|
||||
cancelToken: AbortSignal | undefined,
|
||||
messages: ChatMessage[],
|
||||
options: LLMFullCompletionOptions = {}
|
||||
): AsyncGenerator<ChatMessage, LLMReturnValue> {
|
||||
const gen = ideStreamRequest(
|
||||
"llmStreamChat",
|
||||
{
|
||||
messages,
|
||||
title: modelTitle,
|
||||
completionOptions: options,
|
||||
},
|
||||
cancelToken
|
||||
);
|
||||
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (next.value) {
|
||||
yield { role: "user", content: next.value };
|
||||
}
|
||||
next = await gen.next();
|
||||
}
|
||||
return { prompt: next.value?.prompt, completion: next.value?.completion };
|
||||
}
|
||||
70
core/index.d.ts
vendored
70
core/index.d.ts
vendored
|
|
@ -1,5 +1,3 @@
|
|||
import { BrowserSerializedContinueConfig } from "./config/load";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ide?: "vscode";
|
||||
|
|
@ -15,7 +13,11 @@ declare global {
|
|||
};
|
||||
colorThemeName?: string;
|
||||
workspacePaths?: string[];
|
||||
postIntellijMessage?: (type: string, data: any) => void;
|
||||
postIntellijMessage?: (
|
||||
messageType: string,
|
||||
data: any,
|
||||
messageIde: string
|
||||
) => void;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -97,6 +99,7 @@ export interface ContextProviderDescription {
|
|||
title: string;
|
||||
displayTitle: string;
|
||||
description: string;
|
||||
renderInlineAs?: string;
|
||||
type: ContextProviderType;
|
||||
}
|
||||
|
||||
|
|
@ -116,6 +119,7 @@ export interface CustomContextProvider {
|
|||
title: string;
|
||||
displayTitle?: string;
|
||||
description?: string;
|
||||
renderInlineAs?: string;
|
||||
type?: ContextProviderType;
|
||||
getContextItems(
|
||||
query: string,
|
||||
|
|
@ -311,13 +315,24 @@ export class Problem {
|
|||
message: string;
|
||||
}
|
||||
|
||||
export type IdeType = "vscode" | "jetbrains";
|
||||
export interface IdeInfo {
|
||||
ideType: IdeType;
|
||||
name: string;
|
||||
version: string;
|
||||
remoteName: string;
|
||||
}
|
||||
|
||||
export interface IDE {
|
||||
getSerializedConfig(): Promise<BrowserSerializedContinueConfig>;
|
||||
getIdeInfo(): Promise<IdeInfo>;
|
||||
getDiff(): Promise<string>;
|
||||
isTelemetryEnabled(): Promise<boolean>;
|
||||
getUniqueId(): Promise<string>;
|
||||
getTerminalContents(): Promise<string>;
|
||||
listWorkspaceContents(directory?: string): Promise<string[]>;
|
||||
listFolders(): Promise<string[]>;
|
||||
getWorkspaceDirs(): Promise<string[]>;
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
|
||||
writeFile(path: string, contents: string): Promise<void>;
|
||||
showVirtualFile(title: string, contents: string): Promise<void>;
|
||||
getContinueDir(): Promise<string>;
|
||||
|
|
@ -325,6 +340,7 @@ export interface IDE {
|
|||
runCommand(command: string): Promise<void>;
|
||||
saveFile(filepath: string): Promise<void>;
|
||||
readFile(filepath: string): Promise<string>;
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string>;
|
||||
showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
|
|
@ -335,34 +351,13 @@ export interface IDE {
|
|||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void>;
|
||||
verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
): Promise<void>;
|
||||
getOpenFiles(): Promise<string[]>;
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
subprocess(command: string): Promise<[string, string]>;
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]>;
|
||||
getBranch(dir: string): Promise<string>;
|
||||
|
||||
// Embeddings
|
||||
/**
|
||||
* Returns list of [tag, filepath, hash of contents] that need to be embedded
|
||||
*/
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]>;
|
||||
sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
): void;
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]>;
|
||||
getStats(directory: string): Promise<{ [path: string]: number }>;
|
||||
}
|
||||
|
||||
// Slash Commands
|
||||
|
|
@ -375,6 +370,8 @@ export interface ContinueSDK {
|
|||
input: string;
|
||||
params?: { [key: string]: any } | undefined;
|
||||
contextItems: ContextItemWithId[];
|
||||
selectedCode: RangeInFile[];
|
||||
config: ContinueConfig;
|
||||
}
|
||||
|
||||
export interface SlashCommand {
|
||||
|
|
@ -414,7 +411,10 @@ type ContextProviderName =
|
|||
| "http"
|
||||
| "codebase"
|
||||
| "problems"
|
||||
| "folder";
|
||||
| "folder"
|
||||
| "jira"
|
||||
| "postgres"
|
||||
| "database";
|
||||
|
||||
type TemplateType =
|
||||
| "llama2"
|
||||
|
|
@ -503,6 +503,7 @@ export interface RequestOptions {
|
|||
caBundlePath?: string | string[];
|
||||
proxy?: string;
|
||||
headers?: { [key: string]: string };
|
||||
extraBodyProperties?: { [key: string]: any };
|
||||
}
|
||||
|
||||
export interface StepWithParams {
|
||||
|
|
@ -537,6 +538,7 @@ interface BaseCompletionOptions {
|
|||
mirostat?: number;
|
||||
stop?: string[];
|
||||
maxTokens?: number;
|
||||
numThreads?: number;
|
||||
}
|
||||
|
||||
export interface ModelDescription {
|
||||
|
|
@ -582,6 +584,7 @@ export interface TabAutocompleteOptions {
|
|||
}
|
||||
|
||||
export interface SerializedContinueConfig {
|
||||
env?: string[];
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
|
|
@ -649,3 +652,16 @@ export interface ContinueConfig {
|
|||
tabAutocompleteModel?: ILLM;
|
||||
tabAutocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
}
|
||||
|
||||
export interface BrowserSerializedContinueConfig {
|
||||
allowAnonymousTelemetry?: boolean;
|
||||
models: ModelDescription[];
|
||||
systemMessage?: string;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
slashCommands?: SlashCommandDescription[];
|
||||
contextProviders?: ContextProviderDescription[];
|
||||
disableIndexing?: boolean;
|
||||
disableSessionTitles?: boolean;
|
||||
userToken?: string;
|
||||
embeddingsProvider?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ export function* basicChunker(
|
|||
let currLine = 0;
|
||||
|
||||
for (const line of contents.split("\n")) {
|
||||
const lineTokens = countTokens(line, "gpt-4");
|
||||
const lineTokens = countTokens(line);
|
||||
if (chunkTokens + lineTokens > maxChunkSize - 5) {
|
||||
yield { content: chunkContent, startLine, endLine: currLine - 1 };
|
||||
chunkContent = "";
|
||||
|
|
|
|||
|
|
@ -43,11 +43,11 @@ export async function* chunkDocument(
|
|||
contents,
|
||||
maxChunkSize
|
||||
)) {
|
||||
if (countTokens(chunkWithoutId.content, "gpt-4") > MAX_CHUNK_SIZE) {
|
||||
if (countTokens(chunkWithoutId.content) > MAX_CHUNK_SIZE) {
|
||||
console.warn(
|
||||
`Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
filepath,
|
||||
countTokens(chunkWithoutId.content, "gpt-4")
|
||||
countTokens(chunkWithoutId.content)
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -59,10 +59,7 @@ function collapseChildren(
|
|||
}
|
||||
code = code.slice(node.startIndex);
|
||||
let removedChild = false;
|
||||
while (
|
||||
countTokens(code, "gpt-4") > maxChunkSize &&
|
||||
collapsedChildren.length > 0
|
||||
) {
|
||||
while (countTokens(code) > maxChunkSize && collapsedChildren.length > 0) {
|
||||
removedChild = true;
|
||||
// Remove children starting at the end - TODO: Add multiple chunks so no children are missing
|
||||
const childCode = collapsedChildren.pop()!;
|
||||
|
|
@ -169,7 +166,7 @@ function* getSmartCollapsedChunks(
|
|||
// Keep entire text if not over size
|
||||
if (
|
||||
(root || node.type in collapsedNodeConstructors) &&
|
||||
countTokens(node.text, "gpt-4") < maxChunkSize
|
||||
countTokens(node.text) < maxChunkSize
|
||||
) {
|
||||
yield {
|
||||
content: node.text,
|
||||
|
|
|
|||
|
|
@ -57,7 +57,7 @@ export async function* markdownChunker(
|
|||
maxChunkSize: number,
|
||||
hLevel: number
|
||||
): AsyncGenerator<ChunkWithoutID> {
|
||||
if (countTokens(content, "gpt-4") <= maxChunkSize) {
|
||||
if (countTokens(content) <= maxChunkSize) {
|
||||
const header = findHeader(content.split("\n"));
|
||||
yield {
|
||||
content,
|
||||
|
|
@ -122,8 +122,7 @@ export async function* markdownChunker(
|
|||
for (const section of sections) {
|
||||
for await (const chunk of markdownChunker(
|
||||
section.content,
|
||||
maxChunkSize -
|
||||
(section.header ? countTokens(section.header, "gpt-4") : 0),
|
||||
maxChunkSize - (section.header ? countTokens(section.header) : 0),
|
||||
hLevel + 1
|
||||
)) {
|
||||
yield {
|
||||
|
|
|
|||
|
|
@ -4,13 +4,14 @@ import {
|
|||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers";
|
||||
|
||||
import path from "path";
|
||||
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = `${__dirname}/../models`;
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
|
|
|
|||
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
59
core/indexing/embeddings/TransformersJsWorkerThread.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import path from "path";
|
||||
import {
|
||||
env,
|
||||
pipeline,
|
||||
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
|
||||
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
|
||||
const { parentPort } = require("worker_threads");
|
||||
|
||||
env.allowLocalModels = true;
|
||||
env.allowRemoteModels = false;
|
||||
if (typeof window === "undefined") {
|
||||
// The embeddings provider should just never be called in the browser
|
||||
env.localModelPath = path.join(__dirname, "..", "models");
|
||||
}
|
||||
|
||||
class EmbeddingsPipeline {
|
||||
static task = "feature-extraction";
|
||||
static model = TransformersJsEmbeddingsProvider.ModelName;
|
||||
static instance = null;
|
||||
|
||||
static async getInstance() {
|
||||
if (this.instance === null) {
|
||||
this.instance = await pipeline(this.task, this.model);
|
||||
}
|
||||
|
||||
return this.instance;
|
||||
}
|
||||
}
|
||||
|
||||
parentPort.on("message", async (chunks) => {
|
||||
try {
|
||||
const extractor = await EmbeddingsPipeline.getInstance();
|
||||
|
||||
if (!extractor) {
|
||||
throw new Error("TransformerJS embeddings pipeline is not initialized");
|
||||
}
|
||||
|
||||
let outputs = [];
|
||||
for (
|
||||
let i = 0;
|
||||
i < chunks.length;
|
||||
i += TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
) {
|
||||
let chunkGroup = chunks.slice(
|
||||
i,
|
||||
i + TransformersJsEmbeddingsProvider.MaxGroupSize
|
||||
);
|
||||
let output = await extractor(chunkGroup, {
|
||||
pooling: "mean",
|
||||
normalize: true,
|
||||
});
|
||||
outputs.push(...output.tolist());
|
||||
}
|
||||
|
||||
parentPort.postMessage(outputs);
|
||||
} catch (error) {
|
||||
parentPort.postMessage({ error: error.message });
|
||||
}
|
||||
});
|
||||
94
core/indexing/indexCodebase.ts
Normal file
94
core/indexing/indexCodebase.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { IDE, IndexingProgressUpdate } from "..";
|
||||
import { ConfigHandler } from "../config/handler";
|
||||
import { FullTextSearchCodebaseIndex } from "./FullTextSearch";
|
||||
import { LanceDbIndex } from "./LanceDbIndex";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
|
||||
import { getComputeDeleteAddRemove } from "./refreshIndex";
|
||||
import { CodebaseIndex, IndexTag } from "./types";
|
||||
|
||||
export class CodebaseIndexer {
|
||||
configHandler: ConfigHandler;
|
||||
ide: IDE;
|
||||
constructor(configHandler: ConfigHandler, ide: IDE) {
|
||||
this.configHandler = configHandler;
|
||||
this.ide = ide;
|
||||
}
|
||||
|
||||
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 LanceDbIndex(
|
||||
config.embeddingsProvider,
|
||||
this.ide.readFile.bind(this.ide)
|
||||
),
|
||||
new FullTextSearchCodebaseIndex(),
|
||||
];
|
||||
|
||||
return indexes;
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[]
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const config = await this.configHandler.loadConfig();
|
||||
if (config.disableIndexing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
|
||||
let completedDirs = 0;
|
||||
|
||||
for (let directory of workspaceDirs) {
|
||||
const stats = await this.ide.getStats(directory);
|
||||
const branch = await this.ide.getBranch(directory);
|
||||
let completedIndexes = 0;
|
||||
|
||||
try {
|
||||
for (let codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
const [results, markComplete] = await getComputeDeleteAddRemove(
|
||||
tag,
|
||||
{ ...stats },
|
||||
(filepath) => this.ide.readFile(filepath)
|
||||
);
|
||||
|
||||
for await (let { progress, desc } of codebaseIndex.update(
|
||||
tag,
|
||||
results,
|
||||
markComplete
|
||||
)) {
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs +
|
||||
(completedIndexes + progress) / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc,
|
||||
};
|
||||
}
|
||||
completedIndexes++;
|
||||
yield {
|
||||
progress:
|
||||
(completedDirs + completedIndexes / indexesToBuild.length) /
|
||||
workspaceDirs.length,
|
||||
desc: "Completed indexing " + codebaseIndex.artifactId,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Error refreshing index: ", e);
|
||||
}
|
||||
|
||||
completedDirs++;
|
||||
yield {
|
||||
progress: completedDirs / workspaceDirs.length,
|
||||
desc: "Indexing Complete",
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -165,12 +165,14 @@ async function getAddRemoveForTag(
|
|||
case AddRemoveResultType.Remove:
|
||||
await db.run(
|
||||
`DELETE FROM tag_catalog WHERE
|
||||
path IN (?) AND
|
||||
cacheKey = ? AND
|
||||
path = ? AND
|
||||
dir = ? AND
|
||||
branch = ? AND
|
||||
artifactId = ?
|
||||
`,
|
||||
remove.map((r) => `'${r.path}'`).join(", "),
|
||||
cacheKey,
|
||||
path,
|
||||
tag.directory,
|
||||
tag.branch,
|
||||
tag.artifactId
|
||||
|
|
|
|||
|
|
@ -1,16 +1,29 @@
|
|||
import { encodingForModel as _encodingForModel, Tiktoken } from "js-tiktoken";
|
||||
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
|
||||
// @ts-ignore
|
||||
import llamaTokenizer from "llama-tokenizer-js";
|
||||
import { ChatMessage, MessageContent, MessagePart } from "..";
|
||||
import { autodetectTemplateType } from "./autodetect";
|
||||
import { TOKEN_BUFFER_FOR_SAFETY } from "./constants";
|
||||
|
||||
let encoding: Tiktoken | null = null;
|
||||
interface Encoding {
|
||||
encode: Tiktoken["encode"];
|
||||
decode: Tiktoken["decode"];
|
||||
}
|
||||
|
||||
function encodingForModel(modelName: string): Tiktoken {
|
||||
if (encoding) {
|
||||
return encoding;
|
||||
let gptEncoding: Encoding | null = null;
|
||||
|
||||
function encodingForModel(modelName: string): Encoding {
|
||||
const modelType = autodetectTemplateType(modelName);
|
||||
|
||||
if (!modelType || modelType === "none") {
|
||||
if (!gptEncoding) {
|
||||
gptEncoding = _encodingForModel("gpt-4");
|
||||
}
|
||||
|
||||
return gptEncoding;
|
||||
}
|
||||
|
||||
encoding = _encodingForModel("gpt-4");
|
||||
return encoding;
|
||||
return llamaTokenizer;
|
||||
}
|
||||
|
||||
function countImageTokens(content: MessagePart): number {
|
||||
|
|
@ -21,7 +34,11 @@ function countImageTokens(content: MessagePart): number {
|
|||
}
|
||||
}
|
||||
|
||||
function countTokens(content: MessageContent, modelName: string): number {
|
||||
function countTokens(
|
||||
content: MessageContent,
|
||||
// defaults to llama2 because the tokenizer tends to produce more tokens
|
||||
modelName: string = "llama2"
|
||||
): number {
|
||||
const encoding = encodingForModel(modelName);
|
||||
if (Array.isArray(content)) {
|
||||
return content.reduce((acc, part) => {
|
||||
|
|
@ -72,21 +89,29 @@ function countChatMessageTokens(
|
|||
return countTokens(chatMessage.content, modelName) + TOKENS_PER_MESSAGE;
|
||||
}
|
||||
|
||||
function pruneLinesFromTop(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromTop(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.shift()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.shift()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function pruneLinesFromBottom(prompt: string, maxTokens: number): string {
|
||||
let totalTokens = countTokens(prompt, "gpt-4");
|
||||
function pruneLinesFromBottom(
|
||||
prompt: string,
|
||||
maxTokens: number,
|
||||
modelName: string
|
||||
): string {
|
||||
let totalTokens = countTokens(prompt, modelName);
|
||||
const lines = prompt.split("\n");
|
||||
while (totalTokens > maxTokens && lines.length > 0) {
|
||||
totalTokens -= countTokens(lines.pop()!, "gpt-4");
|
||||
totalTokens -= countTokens(lines.pop()!, modelName);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ class Gemini extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiUrl = `https://${this.region}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/us-central1/publishers/google/models/gemini-pro:streamGenerateContent`;
|
||||
const apiUrl = `https://${this.region}-aiplatform.googleapis.com/v1/projects/${this.projectId}/locations/${this.region}/publishers/google/models/gemini-pro:streamGenerateContent`;
|
||||
const body = {
|
||||
contents: messages.map((msg) => {
|
||||
return {
|
||||
|
|
@ -60,8 +60,12 @@ class Gemini extends BaseLLM {
|
|||
if (data[0]?.error) {
|
||||
throw new Error(data[0].error.message);
|
||||
}
|
||||
yield data[0]?.candidates?.[0]?.content?.parts?.[0]?.text || "";
|
||||
}
|
||||
let combinedText = '';
|
||||
for (const entry of data || []) {
|
||||
combinedText += entry?.candidates?.[0]?.content?.parts?.[0]?.text || '';
|
||||
}
|
||||
|
||||
yield { role: "assistant", content: combinedText.trim() }; }
|
||||
}
|
||||
|
||||
export default Gemini;
|
||||
|
|
|
|||
|
|
@ -13,7 +13,8 @@ class GooglePalm extends BaseLLM {
|
|||
static providerName: ModelProvider = "google-palm";
|
||||
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
model: "chat-bison-001",
|
||||
model: "gemini-pro",
|
||||
apiBase: "https://generativelanguage.googleapis.com",
|
||||
};
|
||||
|
||||
protected async *_streamComplete(
|
||||
|
|
@ -28,16 +29,37 @@ class GooglePalm extends BaseLLM {
|
|||
}
|
||||
}
|
||||
|
||||
private removeSystemMessage(messages: ChatMessage[]) {
|
||||
const msgs = [...messages];
|
||||
|
||||
if (msgs[0]?.role === "system") {
|
||||
let sysMsg = msgs.shift()!.content;
|
||||
// @ts-ignore
|
||||
if (msgs[0]?.role === "user") {
|
||||
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
|
||||
}
|
||||
}
|
||||
|
||||
return msgs;
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
let convertedMsgs = this.removeSystemMessage(messages);
|
||||
if (options.model.includes("gemini")) {
|
||||
for await (const message of this.streamChatGemini(messages, options)) {
|
||||
for await (const message of this.streamChatGemini(
|
||||
convertedMsgs,
|
||||
options
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
} else {
|
||||
for await (const message of this.streamChatBison(messages, options)) {
|
||||
for await (const message of this.streamChatBison(
|
||||
convertedMsgs,
|
||||
options
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
}
|
||||
|
|
@ -60,7 +82,7 @@ class GooglePalm extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const apiURL = `https://generativelanguage.googleapis.com/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`;
|
||||
const apiURL = `${this.apiBase}/v1/models/${options.model}:streamGenerateContent?key=${this.apiKey}`;
|
||||
const body = {
|
||||
contents: messages.map((msg) => {
|
||||
return {
|
||||
|
|
@ -135,7 +157,7 @@ class GooglePalm extends BaseLLM {
|
|||
msgList.push({ content: message.content });
|
||||
}
|
||||
|
||||
const apiURL = `https://generativelanguage.googleapis.com/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`;
|
||||
const apiURL = `${this.apiBase}/v1beta2/models/${options.model}:generateMessage?key=${this.apiKey}`;
|
||||
const body = { prompt: { messages: msgList } };
|
||||
const response = await this.fetch(apiURL, {
|
||||
method: "POST",
|
||||
|
|
|
|||
|
|
@ -1,34 +1,50 @@
|
|||
import { BaseLLM } from "..";
|
||||
import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
|
||||
import { CompletionOptions, ModelProvider } from "../..";
|
||||
import { streamSse } from "../stream";
|
||||
|
||||
class HuggingFaceInferenceAPI extends BaseLLM {
|
||||
static providerName: ModelProvider = "huggingface-inference-api";
|
||||
|
||||
private _convertArgs(options: CompletionOptions, prompt: string) {
|
||||
const finalOptions = {};
|
||||
|
||||
return finalOptions;
|
||||
}
|
||||
|
||||
protected async _complete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
): Promise<string> {
|
||||
throw new Error("Method not implemented.");
|
||||
private _convertArgs(options: CompletionOptions) {
|
||||
return {
|
||||
max_new_tokens: options.maxTokens ?? 1024,
|
||||
temperature: options.temperature,
|
||||
top_k: options.topK,
|
||||
top_p: options.topP,
|
||||
};
|
||||
}
|
||||
|
||||
protected async *_streamComplete(
|
||||
prompt: string,
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<string> {
|
||||
throw new Error("Method not implemented.");
|
||||
}
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please add the `apiBase` field in your config.json."
|
||||
);
|
||||
}
|
||||
|
||||
protected async *_streamChat(
|
||||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
throw new Error("Method not implemented.");
|
||||
const response = await this.fetch(this.apiBase, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
inputs: prompt,
|
||||
stream: true,
|
||||
parameters: this._convertArgs(options),
|
||||
}),
|
||||
});
|
||||
for await (const chunk of streamSse(response)) {
|
||||
let text = chunk?.token?.text ?? "";
|
||||
if (text.endsWith("</s>")) {
|
||||
yield text.slice(0, -5);
|
||||
} else {
|
||||
yield text;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import * as ollama from "ollama";
|
||||
import { BaseLLM } from "..";
|
||||
import {
|
||||
ChatMessage,
|
||||
|
|
@ -26,40 +25,44 @@ class Ollama extends BaseLLM {
|
|||
method: "POST",
|
||||
headers: {},
|
||||
body: JSON.stringify({ name: this._getModel() }),
|
||||
}).then(async (response) => {
|
||||
if (response.status !== 200) {
|
||||
console.warn(
|
||||
"Error calling Ollama /api/show endpoint: ",
|
||||
await response.text()
|
||||
);
|
||||
return;
|
||||
}
|
||||
const body = await response.json();
|
||||
if (body.parameters) {
|
||||
const params = [];
|
||||
for (let line of body.parameters.split("\n")) {
|
||||
let parts = line.split(" ");
|
||||
if (parts.length < 2) {
|
||||
continue;
|
||||
}
|
||||
let key = parts[0];
|
||||
let value = parts[parts.length - 1];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength = parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
if (!this.completionOptions.stop) {
|
||||
this.completionOptions.stop = [];
|
||||
}
|
||||
this.completionOptions.stop.push(value);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
})
|
||||
.then(async (response) => {
|
||||
if (response.status !== 200) {
|
||||
console.warn(
|
||||
"Error calling Ollama /api/show endpoint: ",
|
||||
await response.text()
|
||||
);
|
||||
return;
|
||||
}
|
||||
const body = await response.json();
|
||||
if (body.parameters) {
|
||||
const params = [];
|
||||
for (let line of body.parameters.split("\n")) {
|
||||
let parts = line.split(" ");
|
||||
if (parts.length < 2) {
|
||||
continue;
|
||||
}
|
||||
let key = parts[0];
|
||||
let value = parts[parts.length - 1];
|
||||
switch (key) {
|
||||
case "num_ctx":
|
||||
this.contextLength = parseInt(value);
|
||||
break;
|
||||
case "stop":
|
||||
if (!this.completionOptions.stop) {
|
||||
this.completionOptions.stop = [];
|
||||
}
|
||||
this.completionOptions.stop.push(value);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
console.warn(`Error calling Ollama /api/show endpoint: ${e}`);
|
||||
});
|
||||
}
|
||||
|
||||
private _getModel() {
|
||||
|
|
@ -121,6 +124,7 @@ class Ollama extends BaseLLM {
|
|||
stop: options.stop,
|
||||
num_ctx: this.contextLength,
|
||||
mirostat: options.mirostat,
|
||||
num_thread: options.numThreads,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -176,34 +180,40 @@ class Ollama extends BaseLLM {
|
|||
messages: ChatMessage[],
|
||||
options: CompletionOptions
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
const client = new ollama.Ollama({
|
||||
host: this.apiBase,
|
||||
|
||||
fetch: (input, config) => {
|
||||
return fetch(input, {
|
||||
...config,
|
||||
headers: {
|
||||
...(config?.headers || {}),
|
||||
...(this.requestOptions?.headers || {})
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
const response = await client.chat({
|
||||
...this._convertArgs(options, messages),
|
||||
stream: true,
|
||||
const response = await this.fetch(`${this.apiBase}/api/chat`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(this._convertArgs(options, messages)),
|
||||
});
|
||||
|
||||
try {
|
||||
for await (const chunk of response) {
|
||||
if (!chunk?.message?.content) continue;
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: chunk.message.content,
|
||||
};
|
||||
let buffer = "";
|
||||
for await (const value of streamResponse(response)) {
|
||||
// Append the received chunk to the buffer
|
||||
buffer += value;
|
||||
// Split the buffer into individual JSON chunks
|
||||
const chunks = buffer.split("\n");
|
||||
buffer = chunks.pop() ?? "";
|
||||
|
||||
for (let i = 0; i < chunks.length; i++) {
|
||||
const chunk = chunks[i];
|
||||
if (chunk.trim() !== "") {
|
||||
try {
|
||||
const j = JSON.parse(chunk);
|
||||
if (j.message?.content) {
|
||||
yield {
|
||||
role: "assistant",
|
||||
content: j.message.content,
|
||||
};
|
||||
} else if (j.error) {
|
||||
throw new Error(j.error);
|
||||
}
|
||||
} catch (e) {
|
||||
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
client.abort();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,15 @@
|
|||
import { ChatMessage } from "../..";
|
||||
import { stripImages } from "../countTokens";
|
||||
|
||||
/**
|
||||
* @description Template for LLAMA2 messages:
|
||||
*
|
||||
* <s>[INST] <<SYS>>
|
||||
* {{ system_prompt }}
|
||||
* <</SYS>>
|
||||
*
|
||||
* {{ user_msg_1 }} [/INST] {{ model_answer_1 }} </s><s>[INST] {{ user_msg_2 }} [/INST] {{ model_answer_2 }} </s><s>[INST] {{ user_msg_3 }} [/INST]
|
||||
*/
|
||||
function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
||||
if (msgs.length === 0) {
|
||||
return "";
|
||||
|
|
@ -21,14 +30,9 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
|||
}
|
||||
|
||||
if (hasSystem) {
|
||||
const systemMessage = `
|
||||
<<SYS>>
|
||||
${msgs[0].content}
|
||||
<</SYS>>
|
||||
|
||||
`;
|
||||
const systemMessage = `<<SYS>>\n ${msgs[0].content}\n<</SYS>>\n\n`;
|
||||
if (msgs.length > 1) {
|
||||
prompt += `[INST] ${systemMessage}${msgs[1].content} [/INST]`;
|
||||
prompt += `<s>[INST] ${systemMessage} ${msgs[1].content} [/INST]`;
|
||||
} else {
|
||||
prompt += `[INST] ${systemMessage} [/INST]`;
|
||||
return prompt;
|
||||
|
|
@ -39,7 +43,7 @@ function llama2TemplateMessages(msgs: ChatMessage[]): string {
|
|||
if (msgs[i].role === "user") {
|
||||
prompt += `[INST] ${msgs[i].content} [/INST]`;
|
||||
} else {
|
||||
prompt += msgs[i].content + " ";
|
||||
prompt += msgs[i].content + "</s>\n<s>";
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -126,6 +130,9 @@ function templateAlpacaMessages(msgs: ChatMessage[]): string {
|
|||
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) {
|
||||
|
|
|
|||
2405
core/package-lock.json
generated
2405
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -8,6 +8,7 @@
|
|||
"author": "Nate Sesti and Ty Dunn",
|
||||
"license": "Apache-2.0",
|
||||
"devDependencies": {
|
||||
"@types/follow-redirects": "^1.14.4",
|
||||
"@types/handlebars": "^4.1.0",
|
||||
"@types/jest": "^29.5.11",
|
||||
"@types/jquery": "^3.5.29",
|
||||
|
|
@ -21,16 +22,24 @@
|
|||
"@octokit/rest": "^20.0.2",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@xenova/transformers": "^2.14.0",
|
||||
"adf-to-md": "^1.1.0",
|
||||
"axios": "^1.6.7",
|
||||
"cheerio": "^1.0.0-rc.12",
|
||||
"commander": "^12.0.0",
|
||||
"dotenv": "^16.3.1",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"follow-redirects": "^1.15.5",
|
||||
"handlebars": "^4.7.8",
|
||||
"http-proxy-agent": "^7.0.1",
|
||||
"https-proxy-agent": "^7.0.3",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"llm-code-highlighter": "^0.0.9",
|
||||
"llm-code-highlighter": "^0.0.13",
|
||||
"llama-tokenizer-js": "^1.1.3",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-html-markdown": "^1.3.0",
|
||||
"ollama": "^0.4.6",
|
||||
"openai": "^4.20.1",
|
||||
"pg": "^8.11.3",
|
||||
"posthog-node": "^3.6.2",
|
||||
"replicate": "^0.26.0",
|
||||
"socket.io-client": "^4.7.3",
|
||||
|
|
|
|||
98
core/protocol.ts
Normal file
98
core/protocol.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
ChatMessage,
|
||||
ContextItemWithId,
|
||||
ContextSubmenuItem,
|
||||
LLMFullCompletionOptions,
|
||||
MessageContent,
|
||||
PersistedSessionInfo,
|
||||
RangeInFile,
|
||||
SerializedContinueConfig,
|
||||
SessionInfo,
|
||||
} from ".";
|
||||
|
||||
export type ProtocolGeneratorType<T> = AsyncGenerator<{
|
||||
done?: boolean;
|
||||
content: T;
|
||||
}>;
|
||||
|
||||
export type Protocol = {
|
||||
// New
|
||||
"update/modelChange": [string, void];
|
||||
// Special
|
||||
ping: [string, string];
|
||||
abort: [undefined, void];
|
||||
|
||||
// History
|
||||
"history/list": [undefined, SessionInfo[]];
|
||||
"history/delete": [{ id: string }, void];
|
||||
"history/load": [{ id: string }, PersistedSessionInfo];
|
||||
"history/save": [PersistedSessionInfo, void];
|
||||
"devdata/log": [{ tableName: string; data: any }, void];
|
||||
"config/addOpenAiKey": [string, void];
|
||||
"config/addModel": [
|
||||
{ model: SerializedContinueConfig["models"][number] },
|
||||
void,
|
||||
];
|
||||
"config/getBrowserSerialized": [
|
||||
undefined,
|
||||
Promise<BrowserSerializedContinueConfig>,
|
||||
];
|
||||
"config/deleteModel": [{ title: string }, void];
|
||||
"config/reload": [undefined, Promise<BrowserSerializedContinueConfig>];
|
||||
"context/getContextItems": [
|
||||
{
|
||||
name: string;
|
||||
query: string;
|
||||
fullInput: string;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
Promise<ContextItemWithId[]>,
|
||||
];
|
||||
"context/loadSubmenuItems": [
|
||||
{ title: string },
|
||||
Promise<ContextSubmenuItem[]>,
|
||||
];
|
||||
"context/addDocs": [{ title: string; url: string }, void];
|
||||
"autocomplete/complete": [
|
||||
{ filepath: string; line: number; column: number },
|
||||
string[],
|
||||
];
|
||||
"command/run": [
|
||||
{
|
||||
input: string;
|
||||
history: ChatMessage[];
|
||||
modelTitle: string;
|
||||
slashCommandName: string;
|
||||
contextItems: ContextItemWithId[];
|
||||
params: any;
|
||||
historyIndex: number;
|
||||
selectedCode: RangeInFile[];
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
];
|
||||
"llm/complete": [
|
||||
{
|
||||
prompt: string;
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
string,
|
||||
];
|
||||
"llm/streamComplete": [
|
||||
{
|
||||
prompt: string;
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<string>,
|
||||
];
|
||||
"llm/streamChat": [
|
||||
{
|
||||
messages: ChatMessage[];
|
||||
completionOptions: LLMFullCompletionOptions;
|
||||
title: string;
|
||||
},
|
||||
ProtocolGeneratorType<MessageContent>,
|
||||
];
|
||||
};
|
||||
|
|
@ -1,6 +1,18 @@
|
|||
import { streamDiff } from "../diff/streamDiff";
|
||||
|
||||
const oldCode = [
|
||||
`A
|
||||
B`,
|
||||
`A
|
||||
B
|
||||
C`,
|
||||
`A
|
||||
B
|
||||
C
|
||||
A
|
||||
B
|
||||
B
|
||||
A`,
|
||||
`function mergeSortAlgorithm() {
|
||||
// TODO: implement
|
||||
}`,
|
||||
|
|
@ -10,6 +22,19 @@ const oldCode = [
|
|||
];
|
||||
|
||||
const newCode = [
|
||||
`C
|
||||
D`,
|
||||
`D
|
||||
E
|
||||
C
|
||||
F
|
||||
C`,
|
||||
`C
|
||||
B
|
||||
A
|
||||
B
|
||||
A
|
||||
C`,
|
||||
`function mergeSortAlgorithm(arr: number[]): number[] {
|
||||
if (arr.length <= 1) {
|
||||
return arr;
|
||||
|
|
@ -113,7 +138,11 @@ describe("streamDiff", () => {
|
|||
// Check that there are no red lines immediately following green (they should always be above)
|
||||
for (let i = 1; i < diff.length; i++) {
|
||||
if (diff[i].type === "old" && diff[i - 1].type === "new") {
|
||||
throw new Error("Found red immediately after green line");
|
||||
throw new Error(
|
||||
`Found red '${diff[i].line}' immediately after green line '${
|
||||
diff[i - 1].line
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@ import * as dotenv from "dotenv";
|
|||
import { ContinueSDK } from "..";
|
||||
import EditSlashCommand, { getPromptParts } from "../commands/slash/edit";
|
||||
import { contextItemToRangeInFileWithContents } from "../commands/util";
|
||||
import FileSystemIde from "../ide/filesystem";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
import Ollama from "../llm/llms/Ollama";
|
||||
import { dedentAndGetCommonWhitespace } from "../util";
|
||||
import FileSystemIde from "../util/filesystem";
|
||||
|
||||
jest.setTimeout(100_000);
|
||||
|
||||
|
|
@ -62,6 +62,8 @@ describe("/edit slash command", () => {
|
|||
history: [],
|
||||
input: "implement this function",
|
||||
contextItems: [TEST_CONTEXT_ITEM],
|
||||
selectedCode: [],
|
||||
config: {} as any,
|
||||
};
|
||||
|
||||
let total = "";
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext"],
|
||||
"lib": ["DOM", "DOM.Iterable", "ESNext", "ES2021"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": false,
|
||||
|
|
@ -18,5 +18,5 @@
|
|||
"noEmitOnError": false,
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
"include": ["./**/*.ts", "indexing/embeddings/TransformersJsWorkerThread.js"]
|
||||
}
|
||||
|
|
|
|||
8
core/util/devdata.ts
Normal file
8
core/util/devdata.ts
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import { writeFileSync } from "fs";
|
||||
import { getDevDataFilePath } from "./paths";
|
||||
|
||||
export function logDevData(tableName: string, data: any) {
|
||||
const filepath: string = getDevDataFilePath(tableName);
|
||||
const jsonLine = JSON.stringify(data);
|
||||
writeFileSync(filepath, `${jsonLine}\n`, { flag: "a" });
|
||||
}
|
||||
|
|
@ -1,12 +1,30 @@
|
|||
import * as fs from "fs";
|
||||
import { DiffLine, IDE, Problem } from "..";
|
||||
import { BrowserSerializedContinueConfig } from "../config/load";
|
||||
import { Chunk } from "../index";
|
||||
import { getContinueGlobalPath } from "../util/paths";
|
||||
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
|
||||
import { getContinueGlobalPath } from "./paths";
|
||||
|
||||
class FileSystemIde implements IDE {
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
throw new Error("Not implemented");
|
||||
getIdeInfo(): Promise<IdeInfo> {
|
||||
return Promise.resolve({
|
||||
ideType: "vscode",
|
||||
name: "na",
|
||||
version: "0.1",
|
||||
remoteName: "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([]);
|
||||
}
|
||||
|
||||
getDiff(): Promise<string> {
|
||||
|
|
@ -92,15 +110,6 @@ class FileSystemIde implements IDE {
|
|||
return Promise.resolve("");
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
|
@ -120,20 +129,6 @@ class FileSystemIde implements IDE {
|
|||
async subprocess(command: string): Promise<[string, string]> {
|
||||
return ["", ""];
|
||||
}
|
||||
|
||||
getFilesToEmbed(providerId: string): Promise<[string, string, string][]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
|
||||
sendEmbeddingForChunk(chunk: Chunk, embedding: number[], tags: string[]) {}
|
||||
|
||||
retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
}
|
||||
|
||||
export default FileSystemIde;
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { PersistedSessionInfo, SessionInfo } from "core";
|
||||
import { getSessionFilePath, getSessionsListPath } from "core/util/paths";
|
||||
import * as fs from "fs";
|
||||
import { PersistedSessionInfo, SessionInfo } from "..";
|
||||
import { getSessionFilePath, getSessionsListPath } from "./paths";
|
||||
|
||||
class HistoryManager {
|
||||
list(): PersistedSessionInfo[] {
|
||||
list(): SessionInfo[] {
|
||||
const filepath = getSessionsListPath();
|
||||
if (!fs.existsSync(filepath)) {
|
||||
return [];
|
||||
121
core/util/messageIde.ts
Normal file
121
core/util/messageIde.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "..";
|
||||
|
||||
export class MessageIde implements IDE {
|
||||
constructor(
|
||||
private readonly request: (messageType: string, data: any) => Promise<any>
|
||||
) {}
|
||||
getIdeInfo(): Promise<IdeInfo> {
|
||||
return this.request("getIdeInfo", undefined);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
getUniqueId(): Promise<string> {
|
||||
return this.request("getUniqueId", undefined);
|
||||
}
|
||||
|
||||
getWorkspaceConfigs(): Promise<ContinueRcJson[]> {
|
||||
return this.request("getWorkspaceConfigs", undefined);
|
||||
}
|
||||
|
||||
async getDiff() {
|
||||
return await this.request("getDiff", undefined);
|
||||
}
|
||||
|
||||
async getTerminalContents() {
|
||||
return await this.request("getTerminalContents", undefined);
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
return await this.request("listWorkspaceContents", undefined);
|
||||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return await this.request("getWorkspaceDirs", undefined);
|
||||
}
|
||||
|
||||
async showLines(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number
|
||||
): Promise<void> {
|
||||
return await this.request("showLines", { filepath, startLine, endLine });
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
return await this.request("listFolders", undefined);
|
||||
}
|
||||
|
||||
_continueDir: string | null = null;
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
if (this._continueDir) {
|
||||
return this._continueDir;
|
||||
}
|
||||
const dir = await this.request("getContinueDir", undefined);
|
||||
this._continueDir = dir;
|
||||
return dir;
|
||||
}
|
||||
|
||||
async writeFile(path: string, contents: string): Promise<void> {
|
||||
await this.request("writeFile", { path, contents });
|
||||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
await this.request("showVirtualFile", { name: title, content: contents });
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
await this.request("openFile", { path });
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await this.request("runCommand", { command });
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await this.request("saveFile", { filepath });
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await this.request("readFile", { filepath });
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await this.request("showDiff", { filepath, newContents, stepIndex });
|
||||
}
|
||||
|
||||
getOpenFiles(): Promise<string[]> {
|
||||
return this.request("getOpenFiles", undefined);
|
||||
}
|
||||
|
||||
getPinnedFiles(): Promise<string[]> {
|
||||
return this.request("getPinnedFiles", undefined);
|
||||
}
|
||||
|
||||
getSearchResults(query: string): Promise<string> {
|
||||
return this.request("getSearchResults", { query });
|
||||
}
|
||||
|
||||
getProblems(filepath?: string | undefined): Promise<Problem[]> {
|
||||
return this.request("getProblems", { filepath });
|
||||
}
|
||||
|
||||
subprocess(command: string): Promise<[string, string]> {
|
||||
return this.request("subprocess", { command });
|
||||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return this.request("getBranch", { dir });
|
||||
}
|
||||
}
|
||||
5
core/util/messenger.ts
Normal file
5
core/util/messenger.ts
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export interface Message<T = any> {
|
||||
messageType: string;
|
||||
messageId: string;
|
||||
data: T;
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
import dotenv from "dotenv";
|
||||
import * as fs from "fs";
|
||||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import { SerializedContinueConfig } from "..";
|
||||
import defaultConfig from "../config/default";
|
||||
import { IdeType, SerializedContinueConfig } from "..";
|
||||
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
|
||||
import Types from "../config/types";
|
||||
|
||||
export function getContinueGlobalPath(): string {
|
||||
|
|
@ -42,10 +43,14 @@ export function getSessionsListPath(): string {
|
|||
return filepath;
|
||||
}
|
||||
|
||||
export function getConfigJsonPath(): string {
|
||||
export function getConfigJsonPath(ideType: IdeType = "vscode"): string {
|
||||
const p = path.join(getContinueGlobalPath(), "config.json");
|
||||
if (!fs.existsSync(p)) {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
|
||||
if (ideType === "jetbrains") {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfigJetBrains, null, 2));
|
||||
} else {
|
||||
fs.writeFileSync(p, JSON.stringify(defaultConfig, null, 2));
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
|
@ -86,13 +91,9 @@ export function getConfigTsPath(): string {
|
|||
return p;
|
||||
}
|
||||
|
||||
export function getConfigJsPath(node: boolean): string {
|
||||
export function getConfigJsPath(): string {
|
||||
// Do not create automatically
|
||||
return path.join(
|
||||
getContinueGlobalPath(),
|
||||
"out",
|
||||
`config${node ? ".node" : ""}.js`
|
||||
);
|
||||
return path.join(getContinueGlobalPath(), "out", "config.js");
|
||||
}
|
||||
|
||||
export function getTsConfigPath(): string {
|
||||
|
|
@ -183,3 +184,43 @@ export function getTabAutocompleteCacheSqlitePath(): string {
|
|||
export function getDocsSqlitePath(): string {
|
||||
return path.join(getIndexFolderPath(), "docs.sqlite");
|
||||
}
|
||||
|
||||
export function getRemoteConfigsFolderPath(): string {
|
||||
const dir = path.join(getContinueGlobalPath(), ".configs");
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function getPathToRemoteConfig(remoteConfigServerUrl: URL): string {
|
||||
const dir = path.join(
|
||||
getRemoteConfigsFolderPath(),
|
||||
remoteConfigServerUrl.hostname
|
||||
);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function getConfigJsonPathForRemote(remoteConfigServerUrl: URL): string {
|
||||
return path.join(getPathToRemoteConfig(remoteConfigServerUrl), "config.json");
|
||||
}
|
||||
|
||||
export function getConfigJsPathForRemote(remoteConfigServerUrl: URL): string {
|
||||
return path.join(getPathToRemoteConfig(remoteConfigServerUrl), "config.js");
|
||||
}
|
||||
|
||||
export function getContinueDotEnv(): { [key: string]: string } {
|
||||
const filepath = path.join(getContinueGlobalPath(), ".env");
|
||||
if (fs.existsSync(filepath)) {
|
||||
return dotenv.parse(fs.readFileSync(filepath));
|
||||
} else {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function getCoreLogsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), "core.log");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,14 +19,18 @@ export class Telemetry {
|
|||
if (!allow) {
|
||||
Telemetry.client = undefined;
|
||||
} else {
|
||||
if (!Telemetry.client) {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
Telemetry.client = new PostHog(
|
||||
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
|
||||
{
|
||||
host: "https://app.posthog.com",
|
||||
}
|
||||
);
|
||||
try {
|
||||
if (!Telemetry.client) {
|
||||
const { PostHog } = await import("posthog-node");
|
||||
Telemetry.client = new PostHog(
|
||||
"phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs",
|
||||
{
|
||||
host: "https://app.posthog.com",
|
||||
}
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(`Failed to setup telemetry: ${e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,16 @@
|
|||
import { ContextItemWithId, DiffLine, ILLM, SlashCommand } from "../..";
|
||||
import { DiffLine, ILLM } from "..";
|
||||
import {
|
||||
filterCodeBlockLines,
|
||||
filterEnglishLinesAtEnd,
|
||||
filterEnglishLinesAtStart,
|
||||
filterLeadingAndTrailingNewLineInsertion,
|
||||
fixCodeLlamaFirstLineIndentation,
|
||||
} from "../../autocomplete/lineStream";
|
||||
import { streamDiff } from "../../diff/streamDiff";
|
||||
import { streamLines } from "../../diff/util";
|
||||
import { stripImages } from "../../llm/countTokens";
|
||||
import { gptEditPrompt } from "../../llm/templates/edit";
|
||||
import {
|
||||
dedentAndGetCommonWhitespace,
|
||||
getMarkdownLanguageTagForFile,
|
||||
renderPromptTemplate,
|
||||
} from "../../util";
|
||||
import {
|
||||
RangeInFileWithContents,
|
||||
contextItemToRangeInFileWithContents,
|
||||
} from "../util";
|
||||
} from "../autocomplete/lineStream";
|
||||
import { streamDiff } from "../diff/streamDiff";
|
||||
import { streamLines } from "../diff/util";
|
||||
import { stripImages } from "../llm/countTokens";
|
||||
import { gptEditPrompt } from "../llm/templates/edit";
|
||||
import { dedentAndGetCommonWhitespace, renderPromptTemplate } from "../util";
|
||||
|
||||
function constructPrompt(
|
||||
codeToEdit: string,
|
||||
|
|
@ -87,38 +79,3 @@ export async function* streamDiffLines(
|
|||
yield diffLine;
|
||||
}
|
||||
}
|
||||
|
||||
const VerticalEditSlashCommand: SlashCommand = {
|
||||
name: "verticalEdit",
|
||||
description: "Edit selected code with vertical diff",
|
||||
run: async function* ({ ide, llm, input, contextItems }) {
|
||||
const contextItemToEdit = contextItems.find(
|
||||
(item: ContextItemWithId) =>
|
||||
item.editing && item.id.providerTitle === "code"
|
||||
);
|
||||
|
||||
if (!contextItemToEdit) {
|
||||
yield "Highlight the code that you want to edit first";
|
||||
return;
|
||||
}
|
||||
|
||||
const rif: RangeInFileWithContents =
|
||||
contextItemToRangeInFileWithContents(contextItemToEdit);
|
||||
const startLine = rif.range.start.line;
|
||||
const endLine = rif.range.end.line;
|
||||
const filepath = rif.filepath;
|
||||
|
||||
const diffLineGenerator = streamDiffLines(
|
||||
rif.contents,
|
||||
llm,
|
||||
input,
|
||||
getMarkdownLanguageTagForFile(rif.filepath)
|
||||
);
|
||||
|
||||
for await (const diffLine of diffLineGenerator) {
|
||||
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default VerticalEditSlashCommand;
|
||||
2
core/vendor/package-lock.json
generated
vendored
2
core/vendor/package-lock.json
generated
vendored
|
|
@ -7,7 +7,7 @@
|
|||
"": {
|
||||
"name": "vendor",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@xenova/transformers": "^2.14.0"
|
||||
}
|
||||
|
|
|
|||
2
core/vendor/package.json
vendored
2
core/vendor/package.json
vendored
|
|
@ -7,7 +7,7 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@xenova/transformers": "^2.14.0"
|
||||
}
|
||||
|
|
|
|||
102
core/web/webviewProtocol.ts
Normal file
102
core/web/webviewProtocol.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import {
|
||||
ContextItemWithId,
|
||||
ContinueRcJson,
|
||||
DiffLine,
|
||||
Problem,
|
||||
Range,
|
||||
} from "..";
|
||||
import { RangeInFileWithContents } from "../commands/util";
|
||||
import { Protocol } from "../protocol";
|
||||
|
||||
export type IdeProtocol = {
|
||||
listWorkspaceContents: [undefined, string[]];
|
||||
getWorkspaceDirs: [undefined, string[]];
|
||||
listFolders: [undefined, string[]];
|
||||
writeFile: [{ path: string; contents: string }, void];
|
||||
showVirtualFile: [{ name: string; content: string }, void];
|
||||
getContinueDir: [undefined, string];
|
||||
openFile: [{ path: string }, void];
|
||||
runCommand: [{ command: string }, void];
|
||||
getSearchResults: [{ query: string }, string];
|
||||
subprocess: [{ command: string }, [string, string]];
|
||||
saveFile: [{ filepath: string }, void];
|
||||
readFile: [{ filepath: string }, string];
|
||||
showDiff: [
|
||||
{ filepath: string; newContents: string; stepIndex: number },
|
||||
void,
|
||||
];
|
||||
diffLine: [
|
||||
{
|
||||
diffLine: DiffLine;
|
||||
filepath: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
},
|
||||
void,
|
||||
];
|
||||
getProblems: [{ filepath: string }, Problem[]];
|
||||
getBranch: [{ dir: string }, string];
|
||||
getOpenFiles: [undefined, string[]];
|
||||
getPinnedFiles: [undefined, string[]];
|
||||
showLines: [{ filepath: string; startLine: number; endLine: number }, void];
|
||||
readRangeInFile: [{ filepath: string; range: Range }, string];
|
||||
getDiff: [undefined, string];
|
||||
getWorkspaceConfigs: [undefined, ContinueRcJson[]];
|
||||
getTerminalContents: [undefined, string];
|
||||
isTelemetryEnabled: [undefined, boolean];
|
||||
getUniqueId: [undefined, string];
|
||||
};
|
||||
|
||||
export type WebviewProtocol = Protocol &
|
||||
IdeProtocol & {
|
||||
onLoad: [
|
||||
undefined,
|
||||
{
|
||||
windowId: string;
|
||||
serverUrl: string;
|
||||
workspacePaths: string[];
|
||||
vscMachineId: string;
|
||||
vscMediaUrl: string;
|
||||
},
|
||||
];
|
||||
|
||||
errorPopup: [{ message: string }, void];
|
||||
openUrl: [string, void];
|
||||
applyToCurrentFile: [{ text: string }, void];
|
||||
showTutorial: [undefined, void];
|
||||
showFile: [{ filepath: string }, void];
|
||||
openConfigJson: [undefined, void];
|
||||
|
||||
toggleDevTools: [undefined, void];
|
||||
reloadWindow: [undefined, void];
|
||||
focusEditor: [undefined, void];
|
||||
toggleFullScreen: [undefined, void];
|
||||
};
|
||||
|
||||
export type ReverseWebviewProtocol = {
|
||||
setInactive: [undefined, void];
|
||||
configUpdate: [undefined, void];
|
||||
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
|
||||
addContextItem: [
|
||||
{
|
||||
historyIndex: number;
|
||||
item: ContextItemWithId;
|
||||
},
|
||||
void,
|
||||
];
|
||||
getDefaultModelTitle: [undefined, string];
|
||||
newSessionWithPrompt: [{ prompt: string }, void];
|
||||
userInput: [{ input: string }, void];
|
||||
focusContinueInput: [undefined, void];
|
||||
focusContinueInputWithoutClear: [undefined, void];
|
||||
focusContinueInputWithNewSession: [undefined, void];
|
||||
highlightedCode: [{ rangeInFileWithContents: RangeInFileWithContents }, void];
|
||||
addModel: [undefined, void];
|
||||
openSettings: [undefined, void];
|
||||
viewHistory: [undefined, void];
|
||||
indexProgress: [{ progress: number; desc: string }, void];
|
||||
newSession: [undefined, void];
|
||||
refreshSubmenuItems: [undefined, void];
|
||||
setTheme: [{ theme: any }, void];
|
||||
setColors: [{ [key: string]: string }, void];
|
||||
};
|
||||
1373
core/yarn.lock
1373
core/yarn.lock
File diff suppressed because it is too large
Load diff
|
|
@ -112,6 +112,31 @@ Type '@issue' to reference the conversation in a GitHub issue. Make sure to incl
|
|||
}
|
||||
```
|
||||
|
||||
### Jira Issues
|
||||
|
||||
Type '@jira' to reference the conversation in a Jira issue. Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens).
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "issue",
|
||||
"params": {
|
||||
"domain": "company.atlassian.net",
|
||||
"email": "someone@somewhere.com",
|
||||
"token ": "ATATT..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Issue Query
|
||||
|
||||
By default, the following query will be used to find issues:
|
||||
|
||||
```jql
|
||||
assignee = currentUser() AND resolution = Unresolved order by updated DESC
|
||||
```
|
||||
|
||||
You can override this query by setting the `issueQuery` parameter.
|
||||
|
||||
### Code Outline
|
||||
|
||||
Type '@outline' to reference the outline of all currently open files. The outline of a files consists of only the function and class definitions in the file. Supported file extensions are '.js', '.mjs', '.go', '.c', '.cc', '.cs', '.cpp', '.el', '.ex', '.elm', '.java', '.ml', '.php', '.ql', '.rb', '.rs', '.ts'
|
||||
|
|
@ -128,6 +153,63 @@ Type '@highlights' to reference the 'highlights' from all currently open files.
|
|||
{ "name": "highlights" }
|
||||
```
|
||||
|
||||
### PostgreSQL
|
||||
|
||||
Type `@postgres` to reference the schema of a table, and some sample rows. A dropdown will appear, allowing you to select a specific table, or all tables.
|
||||
|
||||
The only required settings are those for creating the database connection: `host`, `port`, `user`, `password`, and `database`.
|
||||
|
||||
By default, the `schema` filter is set to `public`, and the `sampleRows` is set to 3. You may unset the schema if you want to include tables from all schemas.
|
||||
|
||||
[Here is a short demo.](https://github.com/continuedev/continue/pull/859)
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "postgres",
|
||||
"params": {
|
||||
"host": "localhost",
|
||||
"port": 5436,
|
||||
"user": "myuser",
|
||||
"password": "catsarecool",
|
||||
"database": "animals",
|
||||
"schema": "public",
|
||||
"sampleRows": 3
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Database Tables
|
||||
|
||||
Type `@database` to reference table schemas you can use the drop-down or start typeing table names based off of your configuration. Configuration supports multiple databases, allowing you to specify various connection details for PostgreSQL, MySQL, SQLite. Each connection should include a unique name, the connection_type (e.g., postgres, sqlite), and the necessary connection parameters specific to each database type.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "database",
|
||||
"params": {
|
||||
"connections": [
|
||||
{
|
||||
"name": "examplePostgres",
|
||||
"connection_type": "postgres",
|
||||
"connection": {
|
||||
"user": "username",
|
||||
"host": "localhost",
|
||||
"database": "exampleDB",
|
||||
"password": "yourPassword",
|
||||
"port": 5432
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "exampleSqlite",
|
||||
"connection_type": "sqlite",
|
||||
"connection": {
|
||||
"filename": "/path/to/your/sqlite/database.db"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Requesting Context Providers
|
||||
|
||||
Not seeing what you want? Create an issue [here](https://github.com/continuedev/continue/issues/new?assignees=TyDunn&labels=enhancement&projects=&template=feature-request-%F0%9F%92%AA.md&title=) to request a new ContextProvider.
|
||||
|
|
|
|||
|
|
@ -6,15 +6,14 @@ When you first install Continue, you can try it out for free using a proxy serve
|
|||
|
||||
Once you're ready to use your own API key or a different model / provider, press the `+` button in the bottom left to add a new model to your `config.json`.
|
||||
|
||||
If you are unsure what model or provider to use, here is a rule of thumb:
|
||||
If you are unsure what model or provider to use, here is our current rule of thumb:
|
||||
|
||||
- Use GPT-4 via OpenAI if you want the best possible model overall right now
|
||||
- Use Phind CodeLlama or Mixtral 8x7B via Together if you want the best open-source model right now
|
||||
- Use CodeLlama via Ollama if you want to run a model locally on Mac or Linux
|
||||
- Use CodeLlama via LM Studio if you want to run a model locally on Windows
|
||||
- Use GPT-4 via OpenAI if you want the best possible model overall
|
||||
- Use DeepSeek Coder 33B via the Together API if you want the best open-source model
|
||||
- Use DeepSeek Coder 6.7B with Ollama if you want to run a model locally
|
||||
|
||||
Learn more:
|
||||
|
||||
- [Select a provider](select-provider.md)
|
||||
- [Select a model](select-model.md)
|
||||
- [Configuration](configuration.md)
|
||||
- [Configuration](configuration.md)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# HuggingFaceInferenceAPI
|
||||
# HuggingFace Inference Endpoints
|
||||
|
||||
Hugging Face Inference API is a great option for newly released language models. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this:
|
||||
Hugging Face Inference Endpoints are an easy way to setup instances of open-source language models on any cloud. Sign up for an account and add billing [here](https://huggingface.co/settings/billing), access the Inference Endpoints [here](https://ui.endpoints.huggingface.co), click on “New endpoint”, and fill out the form (e.g. select a model like [WizardCoder-Python-34B-V1.0](https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0)), and then deploy your model by clicking “Create Endpoint”. Change `~/.continue/config.json` to look like this:
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
|
|
|
|||
|
|
@ -8,10 +8,21 @@
|
|||
{
|
||||
"title": "Ollama",
|
||||
"provider": "ollama",
|
||||
"model": "llama2-7b"
|
||||
"model": "llama2-7b",
|
||||
"completionOptions": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Completion Options
|
||||
|
||||
In addition to the model type, you can also configure some of the parameters that Ollama uses to run the model.
|
||||
|
||||
- temperature: options.temperature - This is a parameter that controls the randomness of the generated text. Higher values result in more creative but potentially less coherent outputs, while lower values lead to more predictable and focused outputs.
|
||||
- top_p: options.topP - This sets a threshold (between 0 and 1) to control how diverse the predicted tokens should be. The model generates tokens that are likely according to their probability distribution, but also considers the top-k most probable tokens.
|
||||
- top_k: options.topK - This parameter limits the number of unique tokens to consider when generating the next token in the sequence. Higher values increase the variety of generated sequences, while lower values lead to more focused outputs.
|
||||
- num_predict: options.maxTokens - This determines the maximum number of tokens (words or characters) to generate for the given input prompt.
|
||||
- num_thread: options.numThreads - This is the multi-threading configuration option that controls how many threads the model uses for parallel processing. Higher values may lead to faster generation times but could also increase memory usage and complexity. Set this to one or two lower than the number of threads your CPU can handle to leave some for your GUI when running the model locally.
|
||||
|
||||
[View the source](https://github.com/continuedev/continue/blob/main/core/llm/llms/Ollama.ts)
|
||||
|
|
|
|||
|
|
@ -96,13 +96,42 @@ We also support other methods of generating embeddings, which can be configured
|
|||
|
||||
### OpenAI
|
||||
|
||||
OpenAI's [ada-002 embeddings](https://platform.openai.com/docs/guides/embeddings) are high dimensional embeddings that give great performance on both text and code.
|
||||
OpenAI's [embeddings](https://platform.openai.com/docs/guides/embeddings) are high dimensional embeddings that give great performance on both text and code.
|
||||
|
||||
Configuration for text-embedding-3-small Model
|
||||
The text-embedding-3-small model offers an outstanding balance between performance and efficiency, suitable for a versatile range of applications.
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "openai",
|
||||
"model": "text-embedding-ada-002", // optional, defaults to "text-embedding-ada-002"
|
||||
"model": "text-embedding-3-small",
|
||||
"apiBase": "<your custom OpenAI-compatible endpoint>" // optional, defaults to OpenAI's API
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Configuration for text-embedding-3-large Model
|
||||
For those requiring the highest level of embedding detail and precision, the text-embedding-3-large model is the better choice.
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "openai",
|
||||
"model": "text-embedding-3-large",
|
||||
"apiBase": "<your custom OpenAI-compatible endpoint>" // optional, defaults to OpenAI's API
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Legacy Model Configuration
|
||||
For certain scenarios, you may still find the text-embedding-ada-002 model relevant. Below is the configuration example:
|
||||
|
||||
```json title="~/.continue/config.json"
|
||||
{
|
||||
"embeddingsProvider": {
|
||||
"provider": "openai",
|
||||
"model": "text-embedding-ada-002",
|
||||
"apiBase": "<your custom OpenAI-compatible endpoint>" // optional, defaults to OpenAI's API
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ Once it has been downloaded, you should begin to see completions in VS Code.
|
|||
|
||||
All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote Ollama instance you would edit your `config.json` like this:
|
||||
|
||||
```json
|
||||
```json title=~/.continue/config.json
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
|
|
@ -50,6 +50,24 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number)
|
||||
- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String)
|
||||
|
||||
### Full example
|
||||
|
||||
```json title=~/.continue/config.json
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "deepseek-coder:1.3b-base",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
"tabAutocompleteOptions": {
|
||||
"useCopyBuffer": false,
|
||||
"maxPromptTokens": 400,
|
||||
"prefixPercentage": 0.5
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### I'm not seeing any completions
|
||||
|
|
|
|||
230
docs/static/schemas/config.json
vendored
230
docs/static/schemas/config.json
vendored
|
|
@ -49,6 +49,11 @@
|
|||
"description": "The maximum number of tokens to generate.",
|
||||
"default": 600,
|
||||
"type": "integer"
|
||||
},
|
||||
"numThreads": {
|
||||
"title": "Number of threads",
|
||||
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -71,8 +76,15 @@
|
|||
"title": "Ca Bundle Path",
|
||||
"description": "Path to a custom CA bundle to use when making the HTTP request",
|
||||
"anyOf": [
|
||||
{ "type": "string" },
|
||||
{ "type": "array", "items": { "type": "string" } }
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"proxy": {
|
||||
|
|
@ -87,6 +99,11 @@
|
|||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"extraBodyProperties": {
|
||||
"title": "Extra Body Properties",
|
||||
"description": "This object will be merged with the body when making the HTTP requests",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -216,7 +233,8 @@
|
|||
"verifySsl": null,
|
||||
"caBundlePath": null,
|
||||
"proxy": null,
|
||||
"headers": null
|
||||
"headers": null,
|
||||
"extraBodyProperties": null
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
|
|
@ -285,7 +303,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": ["huggingface-tgi"]
|
||||
"enum": ["huggingface-tgi", "huggingface-inference-api"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -365,7 +383,9 @@
|
|||
"llama2-13b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)."
|
||||
|
|
@ -445,10 +465,15 @@
|
|||
"stable-code-3b",
|
||||
"starcoder-1b",
|
||||
"starcoder-3b",
|
||||
"mistral-tiny",
|
||||
"mistral-small",
|
||||
"mistral-medium",
|
||||
"AUTODETECT"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -467,8 +492,12 @@
|
|||
"properties": {
|
||||
"model": {
|
||||
"anyOf": [
|
||||
{ "enum": ["claude-2", "claude-instant-1"] },
|
||||
{ "type": "string" }
|
||||
{
|
||||
"enum": ["claude-2", "claude-instant-1"]
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -517,7 +546,9 @@
|
|||
"phind-codellama-34b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)."
|
||||
}
|
||||
|
|
@ -585,7 +616,9 @@
|
|||
"starcoder-3b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -630,7 +663,9 @@
|
|||
"AUTODETECT"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)."
|
||||
}
|
||||
|
|
@ -813,7 +848,9 @@
|
|||
"starcoder-3b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -878,7 +915,9 @@
|
|||
"Generate a commit message for the current changes"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
|
|
@ -989,7 +1028,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1007,11 +1047,14 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"params": {
|
||||
|
|
@ -1112,6 +1155,102 @@
|
|||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["database"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": ["postgres", "mysql", "sqlite"]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["name", "type", "connection"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["connections"]
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["jira"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"domain": {
|
||||
"type": "string",
|
||||
"description": "Your Jira domain, for example company.atlassian.net."
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"description": "The email that you log into Jira with"
|
||||
},
|
||||
"token": {
|
||||
"type": "string",
|
||||
"description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens"
|
||||
},
|
||||
"issueQuery": {
|
||||
"type": "string",
|
||||
"description": "Customize the query used to find Jira issues"
|
||||
}
|
||||
},
|
||||
"required": ["domain", "email", "token"]
|
||||
}
|
||||
},
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -1169,6 +1308,65 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["postgres"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": ["name"]
|
||||
|
|
|
|||
3
extensions/intellij/.gitignore
vendored
3
extensions/intellij/.gitignore
vendored
|
|
@ -1 +1,2 @@
|
|||
src/main/resources/webview
|
||||
src/main/resources/webview
|
||||
src/main/resources/bin
|
||||
|
|
@ -79,6 +79,12 @@ koverReport {
|
|||
}
|
||||
|
||||
tasks {
|
||||
prepareSandbox {
|
||||
from("../../pkg/bin") {
|
||||
into("${intellij.pluginName.get()}/core/")
|
||||
}
|
||||
}
|
||||
|
||||
wrapper {
|
||||
gradleVersion = properties("gradleVersion").get()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.27
|
||||
pluginVersion = 0.0.33
|
||||
|
||||
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
|
||||
pluginSinceBuild = 223
|
||||
|
|
|
|||
|
|
@ -4,13 +4,11 @@ import com.github.continuedev.continueintellijextension.services.ContinuePluginS
|
|||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.actionSystem.AnAction
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
|
||||
import com.intellij.openapi.components.ServiceManager
|
||||
import com.intellij.openapi.ui.DialogWrapper
|
||||
import com.intellij.openapi.ui.Messages
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import java.awt.Dimension
|
||||
import java.awt.GridLayout
|
||||
import javax.swing.*
|
||||
import javax.swing.event.DocumentEvent
|
||||
import javax.swing.event.DocumentListener
|
||||
|
|
@ -130,7 +128,7 @@ class QuickTextEntryAction : AnAction() {
|
|||
}
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
|
||||
continuePluginService.sendToWebview("focusContinueInput", null)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -179,7 +177,7 @@ class FocusContinueInputWithoutClearAction : AnAction() {
|
|||
|
||||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithoutClear")))
|
||||
continuePluginService.sendToWebview("focusContinueInputWithoutClear", null)
|
||||
|
||||
continuePluginService.ideProtocolClient?.sendHighlightedCode()
|
||||
}
|
||||
|
|
@ -202,7 +200,7 @@ class FocusContinueInputAction : AnAction() {
|
|||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInput")))
|
||||
continuePluginService.sendToWebview("focusContinueInput", null)
|
||||
|
||||
continuePluginService.ideProtocolClient?.sendHighlightedCode()
|
||||
}
|
||||
|
|
@ -225,7 +223,7 @@ class NewContinueSessionAction : AnAction() {
|
|||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "focusContinueInputWithNewSession")))
|
||||
continuePluginService.sendToWebview("focusContinueInputWithNewSession", null)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -239,6 +237,6 @@ class ViewHistoryAction : AnAction() {
|
|||
|
||||
val continuePluginService = pluginServiceFromActionEvent(e) ?: return
|
||||
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(mutableMapOf("type" to "viewHistory")))
|
||||
continuePluginService.sendToWebview("viewHistory", null)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,9 +1,7 @@
|
|||
package com.github.continuedev.continueintellijextension.activities
|
||||
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.github.continuedev.continueintellijextension.`continue`.startProxyServer
|
||||
import com.github.continuedev.continueintellijextension.`continue`.DefaultTextSelectionStrategy
|
||||
import com.github.continuedev.continueintellijextension.`continue`.IdeProtocolClient
|
||||
import com.github.continuedev.continueintellijextension.`continue`.*
|
||||
import com.github.continuedev.continueintellijextension.listeners.ContinuePluginSelectionListener
|
||||
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
|
|
@ -30,7 +28,9 @@ import java.nio.charset.StandardCharsets
|
|||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import javax.swing.*
|
||||
|
||||
import com.intellij.openapi.application.PathManager;
|
||||
import com.intellij.ide.plugins.PluginManager
|
||||
import com.intellij.openapi.extensions.PluginId
|
||||
|
||||
class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
|
||||
private var panel: JPanel? = null
|
||||
|
|
@ -78,6 +78,28 @@ class WelcomeDialogWrapper(val project: Project) : DialogWrapper(true) {
|
|||
}
|
||||
}
|
||||
|
||||
fun showTutorial(project: Project) {
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: continue_tutorial.py")
|
||||
}
|
||||
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
|
||||
content = content.replace("⌘", "⌃")
|
||||
}
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
|
||||
File(filepath).writeText(content)
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
|
||||
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (virtualFile != null) {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.IO)
|
||||
|
||||
|
|
@ -121,6 +143,8 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
ContinuePluginService::class.java
|
||||
)
|
||||
|
||||
val theme = GetTheme().getTheme()
|
||||
|
||||
val defaultStrategy = DefaultTextSelectionStrategy()
|
||||
|
||||
coroutineScope.launch {
|
||||
|
|
@ -129,24 +153,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
if (!settings.continueState.shownWelcomeDialog) {
|
||||
settings.continueState.shownWelcomeDialog = true
|
||||
// Open continue_tutorial.py
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("continue_tutorial.py").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: continue_tutorial.py")
|
||||
}
|
||||
var content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
if (!System.getProperty("os.name").toLowerCase().contains("mac")) {
|
||||
content = content.replace("⌘", "⌃")
|
||||
}
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "continue_tutorial.py").toString()
|
||||
File(filepath).writeText(content)
|
||||
val virtualFile = LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
|
||||
if (virtualFile != null) {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
FileEditorManager.getInstance(project).openFile(virtualFile, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
showTutorial(project)
|
||||
|
||||
// Show the welcome dialog
|
||||
// withContext(Dispatchers.Main) {
|
||||
|
|
@ -156,17 +163,17 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
// settings.continueState.shownWelcomeDialog = true
|
||||
}
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val ideProtocolClient = IdeProtocolClient(
|
||||
val ideProtocolClient = IdeProtocolClient(
|
||||
continuePluginService,
|
||||
defaultStrategy,
|
||||
coroutineScope,
|
||||
project.basePath,
|
||||
project
|
||||
)
|
||||
)
|
||||
|
||||
continuePluginService.ideProtocolClient = ideProtocolClient
|
||||
continuePluginService.ideProtocolClient = ideProtocolClient
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val listener =
|
||||
ContinuePluginSelectionListener(
|
||||
ideProtocolClient,
|
||||
|
|
@ -193,6 +200,34 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
GlobalScope.async(Dispatchers.IO) {
|
||||
val myPluginId = "com.github.continuedev.continueintellijextension"
|
||||
val pluginDescriptor = PluginManager.getPlugin(PluginId.getId(myPluginId))
|
||||
|
||||
if (pluginDescriptor == null) {
|
||||
throw Exception("Plugin not found")
|
||||
}
|
||||
val pluginPath = pluginDescriptor.pluginPath
|
||||
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 osArch = System.getProperty("os.arch").toLowerCase()
|
||||
val arch = when {
|
||||
osArch.contains("aarch64") || (osArch.contains("arm") && osArch.contains("64")) -> "arm64"
|
||||
osArch.contains("amd64") || osArch.contains("x86_64") -> "x64"
|
||||
else -> "x64"
|
||||
}
|
||||
val target = "$os-$arch"
|
||||
|
||||
val continueCorePath = Paths.get(pluginPath.toString(), "core", target, "pkg").toString()
|
||||
|
||||
val coreMessenger = CoreMessenger(continueCorePath, ideProtocolClient);
|
||||
continuePluginService.coreMessenger = coreMessenger
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,48 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.activities.ContinuePluginStartupActivity
|
||||
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.util.io.StreamUtil
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import com.jetbrains.jsonSchema.extension.JsonSchemaFileProvider
|
||||
import com.jetbrains.jsonSchema.extension.JsonSchemaProviderFactory
|
||||
import com.jetbrains.jsonSchema.extension.SchemaType
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.nio.file.Paths
|
||||
|
||||
class ConfigJsonSchemaProviderFactory : JsonSchemaProviderFactory {
|
||||
override fun getProviders(project: Project): MutableList<JsonSchemaFileProvider> {
|
||||
return mutableListOf(ConfigJsonSchemaFileProvider())
|
||||
}
|
||||
}
|
||||
|
||||
class ConfigJsonSchemaFileProvider : JsonSchemaFileProvider {
|
||||
override fun isAvailable(file: VirtualFile): Boolean {
|
||||
return file.name == "config.json"
|
||||
}
|
||||
|
||||
override fun getName(): String {
|
||||
return "config.json"
|
||||
}
|
||||
|
||||
override fun getSchemaFile(): VirtualFile? {
|
||||
ContinuePluginStartupActivity::class.java.getClassLoader().getResourceAsStream("config_schema.json").use { `is` ->
|
||||
if (`is` == null) {
|
||||
throw IOException("Resource not found: config_schema.json")
|
||||
}
|
||||
val content = StreamUtil.readText(`is`, StandardCharsets.UTF_8)
|
||||
val filepath = Paths.get(getContinueGlobalPath(), "config_schema.json").toString()
|
||||
File(filepath).writeText(content)
|
||||
return LocalFileSystem.getInstance().findFileByPath(filepath)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getSchemaType(): SchemaType {
|
||||
return SchemaType.embeddedSchema
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,179 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
|
||||
import java.io.*
|
||||
|
||||
import com.google.gson.Gson
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.nio.file.attribute.PosixFilePermission
|
||||
|
||||
class CoreMessenger(continueCorePath: String, ideProtocolClient: IdeProtocolClient) {
|
||||
private val writer: OutputStreamWriter
|
||||
private val reader: BufferedReader
|
||||
private val process: Process
|
||||
private val gson = Gson()
|
||||
private val responseListeners = mutableMapOf<String, (String) -> Unit>()
|
||||
private val ideProtocolClient = ideProtocolClient
|
||||
|
||||
private fun write(message: String) {
|
||||
writer.write(message + "\r\n")
|
||||
writer.flush()
|
||||
}
|
||||
|
||||
private fun close() {
|
||||
writer.close()
|
||||
reader.close()
|
||||
val exitCode = process.waitFor()
|
||||
println("Subprocess exited with code: $exitCode")
|
||||
}
|
||||
|
||||
fun request(messageType: String, data: Any?, messageId: String?, onResponse: (String) -> Unit) {
|
||||
val id = messageId ?: uuid()
|
||||
val message = gson.toJson(mapOf(
|
||||
"messageId" to id,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
))
|
||||
responseListeners[id] = onResponse
|
||||
write(message)
|
||||
}
|
||||
|
||||
private fun handleMessage(json: String) {
|
||||
val responseMap = gson.fromJson(json, Map::class.java)
|
||||
val messageId = responseMap["messageId"].toString()
|
||||
val messageType = responseMap["messageType"].toString()
|
||||
val data = gson.toJson(responseMap["data"])
|
||||
|
||||
// IDE listeners
|
||||
if (ideMessageTypes.contains(messageType)) {
|
||||
ideProtocolClient.handleMessage(json) { data ->
|
||||
val message = gson.toJson(mapOf(
|
||||
"messageId" to messageId,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
))
|
||||
write(message)
|
||||
};
|
||||
}
|
||||
|
||||
// Responses for messageId
|
||||
responseListeners[messageId]?.let { listener ->
|
||||
listener(data)
|
||||
if (generatorTypes.contains(messageType)) {
|
||||
val parsedData = gson.fromJson(data, Map::class.java)
|
||||
val done = parsedData["done"] as Boolean?
|
||||
if (done == true) {
|
||||
responseListeners.remove(messageId)
|
||||
} else {}
|
||||
} else {
|
||||
responseListeners.remove(messageId)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private val generatorTypes = listOf(
|
||||
"llm/streamComplete",
|
||||
"llm/streamChat",
|
||||
"command/run"
|
||||
)
|
||||
|
||||
private val ideMessageTypes = listOf(
|
||||
"readRangeInFile",
|
||||
"isTelemetryEnabled",
|
||||
"getUniqueId",
|
||||
"getWorkspaceConfigs",
|
||||
"getDiff",
|
||||
"getTerminalContents",
|
||||
"listWorkspaceContents",
|
||||
"getWorkspaceDirs",
|
||||
"showLines",
|
||||
"listFolders",
|
||||
"getContinueDir",
|
||||
"writeFile",
|
||||
"showVirtualFile",
|
||||
"openFile",
|
||||
"runCommand",
|
||||
"saveFile",
|
||||
"readFile",
|
||||
"showDiff",
|
||||
"getOpenFiles",
|
||||
"getPinnedFiles",
|
||||
"getSearchResults",
|
||||
"getProblems",
|
||||
"subprocess",
|
||||
"getBranch",
|
||||
"getIdeInfo"
|
||||
)
|
||||
|
||||
private fun setPermissions(destination: String) {
|
||||
val osName = System.getProperty("os.name").toLowerCase()
|
||||
if (osName.contains("mac") || osName.contains("darwin")) {
|
||||
ProcessBuilder(
|
||||
"xattr",
|
||||
"-dr",
|
||||
"com.apple.quarantine",
|
||||
destination
|
||||
).start()
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
} else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
|
||||
setFilePermissions(destination, "rwxr-xr-x")
|
||||
}
|
||||
}
|
||||
|
||||
private fun setFilePermissions(path: String, posixPermissions: String) {
|
||||
val perms = HashSet<PosixFilePermission>()
|
||||
if (posixPermissions.contains("r")) perms.add(PosixFilePermission.OWNER_READ)
|
||||
if (posixPermissions.contains("w")) perms.add(PosixFilePermission.OWNER_WRITE)
|
||||
if (posixPermissions.contains("x")) perms.add(PosixFilePermission.OWNER_EXECUTE)
|
||||
Files.setPosixFilePermissions(Paths.get(path), perms)
|
||||
}
|
||||
|
||||
init {
|
||||
// Set proper permissions
|
||||
setPermissions(continueCorePath)
|
||||
|
||||
// Start the subprocess
|
||||
val processBuilder = ProcessBuilder(continueCorePath)
|
||||
process = processBuilder.start()
|
||||
|
||||
val outputStream = process.outputStream
|
||||
val inputStream = process.inputStream
|
||||
|
||||
writer = OutputStreamWriter(outputStream)
|
||||
reader = BufferedReader(InputStreamReader(inputStream))
|
||||
|
||||
process.onExit().thenRun {
|
||||
val err = process.errorStream.bufferedReader().readText()
|
||||
ideProtocolClient.showMessage("Core process exited with output: $err")
|
||||
}
|
||||
|
||||
Thread {
|
||||
try {
|
||||
while (true) {
|
||||
val line = reader.readLine()
|
||||
if (line != null && line.isNotEmpty()) {
|
||||
handleMessage(line)
|
||||
} else {
|
||||
Thread.sleep(100)
|
||||
}
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
} finally {
|
||||
try {
|
||||
reader.close()
|
||||
writer.close()
|
||||
outputStream.close()
|
||||
inputStream.close()
|
||||
process.destroy()
|
||||
} catch (e: IOException) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
}.start()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
import com.intellij.codeInsight.template.impl.TemplateColors
|
||||
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
|
||||
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 kotlin.math.max
|
||||
import kotlin.math.min
|
||||
|
||||
|
||||
class GetTheme {
|
||||
fun getTheme(): Map<String, String> {
|
||||
val globalScheme = EditorColorsManager.getInstance().globalScheme
|
||||
val defaultBackground = globalScheme.defaultBackground
|
||||
val defaultForeground = globalScheme.defaultForeground
|
||||
val highlight = globalScheme.getColor(EditorColors.MODIFIED_TAB_ICON_COLOR) ?: defaultForeground
|
||||
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
|
||||
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
|
||||
val highlightHex = String.format("#%02x%02x%02x", highlight.red, highlight.green, highlight.blue)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
|
||||
|
||||
return mapOf(
|
||||
"--vscode-editor-foreground" to defaultForegroundHex,
|
||||
"--vscode-sideBar-background" to defaultBackgroundHex,
|
||||
"--vscode-input-background" to secondaryDarkHex,
|
||||
"--vscode-editor-background" to defaultBackgroundHex,
|
||||
"--vscode-button-background" to defaultBackgroundHex,
|
||||
"--vscode-list-activeSelectionBackground" to defaultBackgroundHex,
|
||||
"--vscode-focusBorder" to highlightHex,
|
||||
"--vscode-quickInputList-focusForeground" to defaultForegroundHex,
|
||||
"--vscode-quickInput-background" to secondaryDarkHex,
|
||||
"--vscode-input-border" to "#80808080",
|
||||
"--vscode-badge-background" to highlightHex,
|
||||
"--vscode-badge-foreground" to defaultForegroundHex,
|
||||
"--vscode-sideBar-border" to "#80808080"
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -1,28 +1,19 @@
|
|||
package com.github.continuedev.continueintellijextension.`continue`
|
||||
|
||||
import com.github.continuedev.continueintellijextension.*
|
||||
import com.github.continuedev.continueintellijextension.constants.*
|
||||
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.GsonBuilder
|
||||
import com.google.gson.JsonObject
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.intellij.execution.ExecutionManager
|
||||
import com.intellij.execution.process.ProcessAdapter
|
||||
import com.intellij.execution.process.ProcessEvent
|
||||
import com.intellij.execution.ui.RunContentDescriptor
|
||||
import com.intellij.openapi.Disposable
|
||||
import com.intellij.openapi.actionSystem.AnActionEvent
|
||||
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.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.fileEditor.TextEditor
|
||||
import com.intellij.openapi.project.DumbAware
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.project.ProjectManagerListener
|
||||
import com.intellij.openapi.ui.MessageType
|
||||
import com.intellij.openapi.ui.popup.Balloon
|
||||
import com.intellij.openapi.ui.popup.JBPopupFactory
|
||||
|
|
@ -32,15 +23,10 @@ import com.intellij.openapi.wm.WindowManager
|
|||
import com.intellij.testFramework.LightVirtualFile
|
||||
import com.intellij.ui.awt.RelativePoint
|
||||
import kotlinx.coroutines.*
|
||||
import net.minidev.json.JSONObject
|
||||
import org.jetbrains.annotations.NotNull
|
||||
import java.io.*
|
||||
import java.net.NetworkInterface
|
||||
import java.nio.charset.Charset
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.util.*
|
||||
import kotlin.coroutines.ContinuationInterceptor
|
||||
|
||||
|
||||
fun uuid(): String {
|
||||
|
|
@ -103,7 +89,7 @@ class AsyncFileSaveListener : AsyncFileListener {
|
|||
}
|
||||
override fun prepareChange(events: MutableList<out VFileEvent>): AsyncFileListener.ChangeApplier? {
|
||||
for (event in events) {
|
||||
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts")) {
|
||||
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(".continue\\config.json") || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json")) {
|
||||
return object : AsyncFileListener.ChangeApplier {
|
||||
override fun afterVfsChange() {
|
||||
val config = readConfigJson()
|
||||
|
|
@ -137,35 +123,21 @@ class IdeProtocolClient (
|
|||
|
||||
private fun send(messageType: String, data: Any?, messageId: String? = null) {
|
||||
val id = messageId ?: uuid()
|
||||
val message = IdeMessage(
|
||||
messageType,
|
||||
id,
|
||||
data
|
||||
)
|
||||
val json = Gson().toJson(message)
|
||||
continuePluginService.dispatchCustomEvent(json)
|
||||
continuePluginService.sendToWebview(messageType, data, id)
|
||||
}
|
||||
|
||||
fun handleWebsocketMessage(text: String) {
|
||||
fun handleMessage(text: String, respond: (Any?) -> Unit) {
|
||||
coroutineScope.launch(Dispatchers.IO) {
|
||||
val parsedMessage: Map<String, Any> = Gson().fromJson(
|
||||
text,
|
||||
object : TypeToken<Map<String, Any>>() {}.type
|
||||
)
|
||||
val messageType = parsedMessage["type"] as? String
|
||||
val messageType = parsedMessage["messageType"] as? String
|
||||
if (messageType == null) {
|
||||
println("Recieved message without type: $text")
|
||||
return@launch
|
||||
}
|
||||
val data = parsedMessage["data"] as Map<*, *>
|
||||
|
||||
fun respond(responseData: Any?) {
|
||||
if (data["messageId"] == null) {
|
||||
println("Recieved message without messageId: $text")
|
||||
return
|
||||
}
|
||||
send(messageType, responseData ?: emptyMap<String, String>(), data["messageId"] as String);
|
||||
}
|
||||
val data = parsedMessage["data"]
|
||||
|
||||
val historyManager = HistoryManager()
|
||||
|
||||
|
|
@ -175,7 +147,7 @@ class IdeProtocolClient (
|
|||
mapOf("uniqueId" to uniqueId())
|
||||
)
|
||||
|
||||
"ide" -> {
|
||||
"getIdeInfo" -> {
|
||||
val applicationInfo = ApplicationInfo.getInstance()
|
||||
val ideName: String = applicationInfo.fullApplicationName
|
||||
val ideVersion = applicationInfo.fullVersion
|
||||
|
|
@ -187,14 +159,19 @@ class IdeProtocolClient (
|
|||
remoteName = "ssh"
|
||||
}
|
||||
respond(mapOf(
|
||||
"ideType" to "jetbrains",
|
||||
"name" to ideName,
|
||||
"version" to ideVersion,
|
||||
"remoteName" to remoteName
|
||||
))
|
||||
}
|
||||
|
||||
"getUniqueId" -> {
|
||||
respond(uniqueId())
|
||||
}
|
||||
|
||||
"showDiff" -> {
|
||||
val data = data["message"] as Map<String, Any>
|
||||
val data = data as Map<String, Any>
|
||||
diffManager.showDiff(
|
||||
data["filepath"] as String,
|
||||
data["newContents"] as String,
|
||||
|
|
@ -204,10 +181,31 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
"readFile" -> {
|
||||
val msg = readFile((data["message"] as Map<String, String>)["filepath"] as String)
|
||||
val msg = readFile((data as Map<String, String>)["filepath"] as String)
|
||||
respond(msg)
|
||||
}
|
||||
|
||||
"isTelemetryEnabled" -> {
|
||||
respond(true)
|
||||
}
|
||||
|
||||
"readRangeInFile" -> {
|
||||
val fullContents = readFile((data as Map<String, String>)["filepath"] as String)
|
||||
val range = data["range"] as Map<String, Any>
|
||||
val start = range["start"] as Map<String, Any>
|
||||
val end = range["end"] as Map<String, Any>
|
||||
val startLine = start["line"] as Int
|
||||
val startCharacter = start["character"] as Int
|
||||
val endLine = end["line"] as Int
|
||||
val endCharacter = end["character"] as Int
|
||||
|
||||
val firstLine = fullContents.split("\n")[startLine].slice(startCharacter until fullContents.split("\n")[startLine].length)
|
||||
val lastLine = fullContents.split("\n")[endLine].slice(0 until endCharacter)
|
||||
val between = fullContents.split("\n").slice(startLine + 1 until endLine).joinToString("\n")
|
||||
|
||||
respond(firstLine + "\n" + between + "\n" + lastLine)
|
||||
}
|
||||
|
||||
"listWorkspaceContents" -> {
|
||||
respond(listDirectoryContents(null))
|
||||
}
|
||||
|
|
@ -216,6 +214,10 @@ class IdeProtocolClient (
|
|||
respond(workspaceDirectories())
|
||||
}
|
||||
|
||||
"getWorkspaceConfigs" -> {
|
||||
respond(emptyList<String>())
|
||||
}
|
||||
|
||||
"getTerminalContents" -> {
|
||||
respond(
|
||||
mapOf("contents" to "Terminal cannot be accessed in JetBrains IDE")
|
||||
|
|
@ -229,10 +231,11 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
"saveFile" -> {
|
||||
saveFile((data["message"] as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
|
||||
saveFile((data as Map<String, String>)["filepath"] ?: throw Exception("No filepath provided"))
|
||||
respond(null)
|
||||
}
|
||||
"showVirtualFile" -> {
|
||||
val data = data as Map<String, Any>
|
||||
showVirtualFile(
|
||||
data["name"] as String,
|
||||
data["contents"] as String
|
||||
|
|
@ -242,10 +245,11 @@ class IdeProtocolClient (
|
|||
|
||||
"connected" -> {}
|
||||
"showMessage" -> {
|
||||
showMessage(data["message"] as String)
|
||||
showMessage(data as String)
|
||||
respond(null)
|
||||
}
|
||||
"setFileOpen" -> {
|
||||
val data = data as Map<String, Any>
|
||||
setFileOpen(
|
||||
data["filepath"] as String,
|
||||
data["open"] as Boolean
|
||||
|
|
@ -253,8 +257,27 @@ class IdeProtocolClient (
|
|||
respond(null)
|
||||
}
|
||||
|
||||
"showLines" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val filepath = data["filepath"] as String
|
||||
val startLine = data["startLine"] as Int
|
||||
val endLine = data["endLine"] as Int
|
||||
highlightCode(
|
||||
RangeInFile(
|
||||
filepath,
|
||||
Range(
|
||||
Position(startLine, 0),
|
||||
Position(endLine, 0)
|
||||
)
|
||||
),
|
||||
data["color"] as String
|
||||
)
|
||||
respond(null)
|
||||
}
|
||||
|
||||
"highlightCode" -> {
|
||||
val gson = Gson()
|
||||
val data = data as Map<String, Any>
|
||||
val json = gson.toJson(data["rangeInFile"])
|
||||
val type = object : TypeToken<RangeInFile>() {}.type
|
||||
val rangeInFile =
|
||||
|
|
@ -265,16 +288,6 @@ class IdeProtocolClient (
|
|||
|
||||
"setSuggestionsLocked" -> {}
|
||||
"getSessionId" -> {}
|
||||
"highlightedCode" -> {
|
||||
val rifWithContents = getHighlightedCode()
|
||||
val rifs: MutableList<RangeInFile> = mutableListOf()
|
||||
if (rifWithContents != null) {
|
||||
val rif = RangeInFile(rifWithContents.filepath, rifWithContents.range)
|
||||
rifs += rif
|
||||
}
|
||||
respond(mapOf("highlightedCode" to rifs))
|
||||
}
|
||||
|
||||
|
||||
// NEW //
|
||||
"getDiff" -> {
|
||||
|
|
@ -295,29 +308,6 @@ class IdeProtocolClient (
|
|||
|
||||
respond(output.toString());
|
||||
}
|
||||
"getSerializedConfig" -> {
|
||||
val configPath = getConfigJsonPath()
|
||||
var config = File(configPath).readText()
|
||||
|
||||
migrate("camelCaseConfig") {
|
||||
if (config.contains("_")) {
|
||||
config = config
|
||||
.replace(Regex("(_\\w)")) { it.value[1].uppercase() }
|
||||
.replace("openai-aiohttp", "openai")
|
||||
// Rewrite to config.json
|
||||
File(configPath).writeText(config)
|
||||
}
|
||||
}
|
||||
|
||||
migrate("renameFreeTrialProvider") {
|
||||
config = config.replace("openai-free-trial", "free-trial");
|
||||
File(configPath).writeText(config)
|
||||
}
|
||||
|
||||
val mapType = object : TypeToken<Map<String, Any>>() {}.type
|
||||
val parsed: Map<String, Any> = Gson().fromJson(config, mapType)
|
||||
respond(parsed)
|
||||
}
|
||||
"getConfigJsUrl" -> {
|
||||
// Calculate a data URL for the config.js file
|
||||
val configJsPath = getConfigJsPath()
|
||||
|
|
@ -326,7 +316,7 @@ class IdeProtocolClient (
|
|||
respond(configJsDataUrl)
|
||||
}
|
||||
"writeFile" -> {
|
||||
val msg = data["message"] as Map<String, String>;
|
||||
val msg = data as Map<String, String>;
|
||||
val file = File(msg["path"])
|
||||
file.writeText(msg["contents"] as String)
|
||||
respond(null);
|
||||
|
|
@ -335,7 +325,7 @@ class IdeProtocolClient (
|
|||
respond(getContinueGlobalPath())
|
||||
}
|
||||
"openFile" -> {
|
||||
setFileOpen((data["message"] as Map<String, Any>)["path"] as String)
|
||||
setFileOpen((data as Map<String, Any>)["path"] as String)
|
||||
respond(null)
|
||||
}
|
||||
"runCommand" -> {
|
||||
|
|
@ -343,7 +333,14 @@ class IdeProtocolClient (
|
|||
// Running commands not yet supported in JetBrains
|
||||
}
|
||||
"errorPopup" -> {
|
||||
showMessage(data["message"] as String)
|
||||
val data = data as Map<String, Any>
|
||||
val message = data["message"] as String
|
||||
showMessage(message)
|
||||
respond(null)
|
||||
}
|
||||
|
||||
"listFolders" -> {
|
||||
respond(null)
|
||||
}
|
||||
|
||||
// History
|
||||
|
|
@ -351,15 +348,15 @@ class IdeProtocolClient (
|
|||
respond(historyManager.list());
|
||||
}
|
||||
"saveSession" -> {
|
||||
historyManager.save(data["message"] as PersistedSessionInfo);
|
||||
historyManager.save(data as PersistedSessionInfo);
|
||||
respond(null);
|
||||
}
|
||||
"deleteSession" -> {
|
||||
historyManager.delete(data["message"] as String);
|
||||
historyManager.delete(data as String);
|
||||
respond(null);
|
||||
}
|
||||
"loadSession" -> {
|
||||
val session = historyManager.load(data["message"] as String)
|
||||
val session = historyManager.load(data as String)
|
||||
respond(session)
|
||||
}
|
||||
"getSearchResults" -> {
|
||||
|
|
@ -371,7 +368,12 @@ class IdeProtocolClient (
|
|||
val openFiles = visibleFiles()
|
||||
respond(openFiles)
|
||||
}
|
||||
"getPinnedFiles" -> {
|
||||
val openFiles = visibleFiles()
|
||||
respond(openFiles)
|
||||
}
|
||||
"logDevData" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val filename = data["tableName"] as String
|
||||
val jsonLine = data["data"]
|
||||
val filepath = getDevDataFilepath(filename)
|
||||
|
|
@ -379,6 +381,7 @@ class IdeProtocolClient (
|
|||
File(filepath).appendText(contents)
|
||||
}
|
||||
"addModel" -> {
|
||||
val data = data as Map<String, Any>
|
||||
val model = data["model"] as Map<String, Any>
|
||||
val updatedConfig = editConfigJson {
|
||||
val models = it["models"] as MutableList<Map<String, Any>>
|
||||
|
|
@ -392,7 +395,7 @@ class IdeProtocolClient (
|
|||
"deleteModel" -> {
|
||||
val configJson = editConfigJson { config ->
|
||||
var models: MutableList<Map<String, Any>> = config["models"] as MutableList<Map<String, Any>>
|
||||
|
||||
val data = data as Map<String, Any>
|
||||
val model = data["title"] as String
|
||||
models = models.filter { it["title"] != model }.toMutableList()
|
||||
config["models"] = models
|
||||
|
|
@ -402,6 +405,7 @@ class IdeProtocolClient (
|
|||
}
|
||||
"addOpenAIKey" -> {
|
||||
val updatedConfig = editConfigJson { config ->
|
||||
val data = data as Map<String, Any>
|
||||
val key = data["key"] as String
|
||||
var models = config["models"] as MutableList<MutableMap<String, Any>>
|
||||
models = models.map {
|
||||
|
|
@ -432,12 +436,8 @@ class IdeProtocolClient (
|
|||
}
|
||||
|
||||
fun configUpdate(config: Map<String, Any>) {
|
||||
val data = mapOf(
|
||||
"type" to "configUpdate",
|
||||
"config" to config
|
||||
)
|
||||
val json = Gson().toJson(data)
|
||||
continuePluginService.dispatchCustomEvent(json)
|
||||
continuePluginService.coreMessenger?.request("config/reload", null, null) { _ -> }
|
||||
continuePluginService.sendToWebview("configUpdate", config)
|
||||
}
|
||||
|
||||
private fun editConfigJson(callback: (config: MutableMap<String, Any>) -> Map<String, Any>): Map<String, Any> {
|
||||
|
|
@ -581,20 +581,17 @@ class IdeProtocolClient (
|
|||
// edit
|
||||
// ))
|
||||
|
||||
continuePluginService.dispatchCustomEvent(
|
||||
Gson().toJson(mapOf(
|
||||
"type" to "highlightedCode",
|
||||
continuePluginService.sendToWebview(
|
||||
"highlightedCode",
|
||||
mapOf(
|
||||
"rangeInFileWithContents" to rif,
|
||||
"edit" to edit
|
||||
)))
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fun sendMainUserInput(input: String) {
|
||||
val data = mapOf(
|
||||
"type" to "userInput",
|
||||
"input" to input,
|
||||
)
|
||||
continuePluginService.dispatchCustomEvent(Gson().toJson(data))
|
||||
continuePluginService.sendToWebview("userInput", mapOf("input" to input))
|
||||
}
|
||||
|
||||
fun sendAcceptRejectDiff(accepted: Boolean, stepIndex: Int) {
|
||||
|
|
@ -712,7 +709,7 @@ class IdeProtocolClient (
|
|||
return fileEditorManager.openFiles.toList().map { it.path }
|
||||
}
|
||||
|
||||
private fun showMessage(msg: String) {
|
||||
fun showMessage(msg: String) {
|
||||
val statusBar = WindowManager.getInstance().getStatusBar(project)
|
||||
|
||||
JBPopupFactory.getInstance()
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ class CustomResourceHandler : CefResourceHandler, DumbAware {
|
|||
): Boolean {
|
||||
val url = cefRequest.url
|
||||
return if (url != null) {
|
||||
val pathToResource = url.replace("http://continue", "webview/")
|
||||
val pathToResource = url.replace("http://continue", "webview/").replace("http://localhost:5173", "webview/")
|
||||
val newUrl = javaClass.classLoader.getResource(pathToResource)
|
||||
state = OpenedConnection(newUrl?.openConnection())
|
||||
currentUrl = url
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
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.ContinuePluginToolWindowFactory
|
||||
import com.google.gson.Gson
|
||||
import com.intellij.openapi.Disposable
|
||||
|
|
@ -20,7 +22,8 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
|
|||
var continuePluginWindow: ContinuePluginToolWindowFactory.ContinuePluginWindow? = null
|
||||
|
||||
var ideProtocolClient: IdeProtocolClient? = null
|
||||
var workspacePaths: Array<String>? = null
|
||||
var coreMessenger: CoreMessenger? = null
|
||||
var worksapcePaths: Array<String>? = null
|
||||
var windowId: String = UUID.randomUUID().toString()
|
||||
|
||||
override fun dispose() {
|
||||
|
|
@ -33,10 +36,19 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware {
|
|||
}
|
||||
}
|
||||
|
||||
fun dispatchCustomEvent(
|
||||
data: String
|
||||
fun sendToWebview(
|
||||
messageType: String,
|
||||
data: Any?,
|
||||
messageId: String = uuid()
|
||||
) {
|
||||
val jsCode = buildJavaScript(data)
|
||||
val jsonData = Gson().toJson(
|
||||
mapOf(
|
||||
"messageId" to messageId,
|
||||
"messageType" to messageType,
|
||||
"data" to data
|
||||
)
|
||||
)
|
||||
val jsCode = buildJavaScript(jsonData)
|
||||
|
||||
try {
|
||||
continuePluginWindow?.webView?.executeJavaScriptAsync(jsCode)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,8 @@
|
|||
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`.Position
|
||||
import com.github.continuedev.continueintellijextension.`continue`.Range
|
||||
import com.github.continuedev.continueintellijextension.`continue`.RangeInFile
|
||||
import com.github.continuedev.continueintellijextension.`continue`.getMachineUniqueID
|
||||
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
|
||||
|
|
@ -55,12 +53,34 @@ 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.osr.enabled", "false")
|
||||
}
|
||||
|
||||
val webView: JBCefBrowser by lazy {
|
||||
val browser = JBCefBrowser()
|
||||
val browser = JBCefBrowser.createBuilder().setOffScreenRendering(false).build()
|
||||
browser.jbCefClient.setProperty(
|
||||
JBCefClient.Properties.JS_QUERY_POOL_SIZE,
|
||||
JS_QUERY_POOL_SIZE
|
||||
|
|
@ -68,6 +88,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
registerAppSchemeHandler()
|
||||
|
||||
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 continuePluginService = ServiceManager.getService(
|
||||
|
|
@ -81,58 +103,46 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
myJSQueryOpenInBrowser.addHandler { msg: String? ->
|
||||
val parser = JsonParser()
|
||||
val json: JsonObject = parser.parse(msg).asJsonObject
|
||||
val type = json.get("type").asString
|
||||
val data = json.get("data").asJsonObject
|
||||
val messageType = json.get("messageType").asString
|
||||
val data = json.get("data")
|
||||
val messageId = json.get("messageId")?.asString
|
||||
|
||||
val ide = continuePluginService.ideProtocolClient;
|
||||
|
||||
when (type) {
|
||||
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 globalScheme = EditorColorsManager.getInstance().globalScheme
|
||||
val defaultBackground = globalScheme.defaultBackground
|
||||
val defaultForeground = globalScheme.defaultForeground
|
||||
val defaultBackgroundHex = String.format("#%02x%02x%02x", defaultBackground.red, defaultBackground.green, defaultBackground.blue)
|
||||
val defaultForegroundHex = String.format("#%02x%02x%02x", defaultForeground.red, defaultForeground.green, defaultForeground.blue)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
val secondaryDarkHex = String.format("#%02x%02x%02x", adjustedRed, adjustedGreen, adjustedBlue)
|
||||
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-foreground\", \"$defaultForegroundHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-sideBar-background\", \"$defaultBackgroundHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-input-background\", \"$secondaryDarkHex\");")
|
||||
browser.executeJavaScriptAsync("document.body.style.setProperty(\"--vscode-editor-background\", \"$defaultBackgroundHex\");")
|
||||
val colors = GetTheme().getTheme();
|
||||
continuePluginService.sendToWebview("setColors", colors)
|
||||
|
||||
val jsonData = mutableMapOf(
|
||||
"type" to "onLoad",
|
||||
"windowId" to continuePluginService.windowId,
|
||||
"workspacePaths" to continuePluginService.workspacePaths,
|
||||
"vscMachineId" to getMachineUniqueID(),
|
||||
"vscMediaUrl" to "http://continue",
|
||||
)
|
||||
val jsonString = Gson().toJson(jsonData)
|
||||
browser.executeJavaScriptAsync("""window.postMessage($jsonString, "*");""")
|
||||
respond(jsonData)
|
||||
}
|
||||
|
||||
}
|
||||
"showLines" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.highlightCode(RangeInFile(
|
||||
data.get("filepath").asString,
|
||||
Range(Position(
|
||||
|
|
@ -145,10 +155,15 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
|
||||
),"#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" -> {}
|
||||
|
|
@ -156,6 +171,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
ide?.setFileOpen(getConfigJsonPath())
|
||||
}
|
||||
"readRangeInFile" -> {
|
||||
val data = data.asJsonObject
|
||||
ide?.readRangeInFile(RangeInFile(
|
||||
data.get("filepath").asString,
|
||||
Range(Position(
|
||||
|
|
@ -172,7 +188,7 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
// IDE //
|
||||
else -> {
|
||||
if (msg != null) {
|
||||
ide?.handleWebsocketMessage(msg)
|
||||
ide?.handleMessage(msg, respond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -201,8 +217,8 @@ class ContinuePluginToolWindowFactory : ToolWindowFactory, DumbAware {
|
|||
|
||||
fun executeJavaScript(browser: CefBrowser?, myJSQueryOpenInBrowser: JBCefJSQuery) {
|
||||
// Execute JavaScript - you might want to handle potential exceptions here
|
||||
val script = """window.postIntellijMessage = function(type, data) {
|
||||
const msg = JSON.stringify({type, data});
|
||||
val script = """window.postIntellijMessage = function(messageType, data, messageId) {
|
||||
const msg = JSON.stringify({messageType, data, messageId});
|
||||
${myJSQueryOpenInBrowser.inject("msg")}
|
||||
}""".trimIndent()
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,10 @@
|
|||
<depends>com.intellij.modules.platform</depends>
|
||||
<idea-version since-build="223.0"/>
|
||||
|
||||
<extensions defaultExtensionNs="JavaScript.JsonSchema">
|
||||
<ProviderFactory implementation="com.github.continuedev.continueintellijextension.continue.ConfigJsonSchemaProviderFactory"/>
|
||||
</extensions>
|
||||
|
||||
<extensions defaultExtensionNs="com.intellij">
|
||||
<toolWindow id="Continue" anchor="right" icon="/tool-window-icon.png"
|
||||
factoryClass="com.github.continuedev.continueintellijextension.toolWindow.ContinuePluginToolWindowFactory"/>
|
||||
|
|
|
|||
1449
extensions/intellij/src/main/resources/config_schema.json
Normal file
1449
extensions/intellij/src/main/resources/config_schema.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,2 +1,3 @@
|
|||
media
|
||||
textmate-syntaxes
|
||||
**/*.tmLanguage
|
||||
textmate-syntaxes
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@
|
|||
"description": "The maximum number of tokens to generate.",
|
||||
"default": 600,
|
||||
"type": "integer"
|
||||
},
|
||||
"numThreads": {
|
||||
"title": "Number of threads",
|
||||
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -71,8 +76,15 @@
|
|||
"title": "Ca Bundle Path",
|
||||
"description": "Path to a custom CA bundle to use when making the HTTP request",
|
||||
"anyOf": [
|
||||
{ "type": "string" },
|
||||
{ "type": "array", "items": { "type": "string" } }
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"proxy": {
|
||||
|
|
@ -87,6 +99,11 @@
|
|||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"extraBodyProperties": {
|
||||
"title": "Extra Body Properties",
|
||||
"description": "This object will be merged with the body when making the HTTP requests",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -216,7 +233,8 @@
|
|||
"verifySsl": null,
|
||||
"caBundlePath": null,
|
||||
"proxy": null,
|
||||
"headers": null
|
||||
"headers": null,
|
||||
"extraBodyProperties": null
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
|
|
@ -285,7 +303,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": ["huggingface-tgi"]
|
||||
"enum": ["huggingface-tgi", "huggingface-inference-api"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -365,7 +383,9 @@
|
|||
"llama2-13b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"markdownDescription": "Select a pre-defined option, or find an exact model ID from Replicate [here](https://replicate.com/collections/streaming-language-models)."
|
||||
|
|
@ -445,10 +465,15 @@
|
|||
"stable-code-3b",
|
||||
"starcoder-1b",
|
||||
"starcoder-3b",
|
||||
"mistral-tiny",
|
||||
"mistral-small",
|
||||
"mistral-medium",
|
||||
"AUTODETECT"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -467,8 +492,12 @@
|
|||
"properties": {
|
||||
"model": {
|
||||
"anyOf": [
|
||||
{ "enum": ["claude-2", "claude-instant-1"] },
|
||||
{ "type": "string" }
|
||||
{
|
||||
"enum": ["claude-2", "claude-instant-1"]
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -517,7 +546,9 @@
|
|||
"phind-codellama-34b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"markdownDescription": "Select a pre-defined option, or find an exact model string from Together AI [here](https://docs.together.ai/docs/inference-models)."
|
||||
}
|
||||
|
|
@ -585,7 +616,9 @@
|
|||
"starcoder-3b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -630,7 +663,9 @@
|
|||
"AUTODETECT"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
],
|
||||
"markdownDescription": "Select a pre-defined option, or find the exact model tag for an Ollama model [here](https://ollama.ai/library)."
|
||||
}
|
||||
|
|
@ -813,7 +848,9 @@
|
|||
"starcoder-3b"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -878,7 +915,9 @@
|
|||
"Generate a commit message for the current changes"
|
||||
]
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"description": {
|
||||
|
|
@ -989,7 +1028,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1007,11 +1047,14 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
{ "type": "string" }
|
||||
{
|
||||
"type": "string"
|
||||
}
|
||||
]
|
||||
},
|
||||
"params": {
|
||||
|
|
@ -1112,6 +1155,102 @@
|
|||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["database"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": ["postgres", "mysql", "sqlite"]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["name", "type", "connection"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["connections"]
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["jira"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"domain": {
|
||||
"type": "string",
|
||||
"description": "Your Jira domain, for example company.atlassian.net."
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"description": "The email that you log into Jira with"
|
||||
},
|
||||
"token": {
|
||||
"type": "string",
|
||||
"description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens"
|
||||
},
|
||||
"issueQuery": {
|
||||
"type": "string",
|
||||
"description": "Customize the query used to find Jira issues"
|
||||
}
|
||||
},
|
||||
"required": ["domain", "email", "token"]
|
||||
}
|
||||
},
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
|
|
@ -1169,6 +1308,65 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["postgres"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": ["name"]
|
||||
|
|
|
|||
|
|
@ -49,6 +49,11 @@
|
|||
"description": "The maximum number of tokens to generate.",
|
||||
"default": 600,
|
||||
"type": "integer"
|
||||
},
|
||||
"numThreads": {
|
||||
"title": "Number of threads",
|
||||
"description": "The number of threads used in the generation process. Only available for Ollama (this is the num_thread parameter)",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -94,6 +99,11 @@
|
|||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"extraBodyProperties": {
|
||||
"title": "Extra Body Properties",
|
||||
"description": "This object will be merged with the body when making the HTTP requests",
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -223,7 +233,8 @@
|
|||
"verifySsl": null,
|
||||
"caBundlePath": null,
|
||||
"proxy": null,
|
||||
"headers": null
|
||||
"headers": null,
|
||||
"extraBodyProperties": null
|
||||
},
|
||||
"allOf": [
|
||||
{
|
||||
|
|
@ -234,10 +245,7 @@
|
|||
"apiType": {
|
||||
"title": "Api Type",
|
||||
"markdownDescription": "OpenAI API type, either `openai` or `azure`",
|
||||
"enum": [
|
||||
"openai",
|
||||
"azure"
|
||||
]
|
||||
"enum": ["openai", "azure"]
|
||||
},
|
||||
"apiVersion": {
|
||||
"title": "Api Version",
|
||||
|
|
@ -250,11 +258,7 @@
|
|||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"title",
|
||||
"provider",
|
||||
"model"
|
||||
],
|
||||
"required": ["title", "provider", "model"],
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
|
|
@ -264,9 +268,7 @@
|
|||
}
|
||||
},
|
||||
"not": {
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
|
|
@ -291,47 +293,33 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"apiKey"
|
||||
]
|
||||
"required": ["apiKey"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"huggingface-tgi"
|
||||
]
|
||||
"enum": ["huggingface-tgi", "huggingface-inference-api"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"apiBase"
|
||||
]
|
||||
"required": ["apiBase"]
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"openai"
|
||||
]
|
||||
"enum": ["openai"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -351,14 +339,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"openai"
|
||||
]
|
||||
"enum": ["openai"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -381,14 +365,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"replicate"
|
||||
]
|
||||
"enum": ["replicate"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -416,14 +396,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"free-trial"
|
||||
]
|
||||
"enum": ["free-trial"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -445,9 +421,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"openai"
|
||||
]
|
||||
"enum": ["openai"]
|
||||
},
|
||||
"apiType": {
|
||||
"not": {
|
||||
|
|
@ -455,9 +429,7 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -493,6 +465,9 @@
|
|||
"stable-code-3b",
|
||||
"starcoder-1b",
|
||||
"starcoder-3b",
|
||||
"mistral-tiny",
|
||||
"mistral-small",
|
||||
"mistral-medium",
|
||||
"AUTODETECT"
|
||||
]
|
||||
},
|
||||
|
|
@ -508,24 +483,17 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"anthropic"
|
||||
]
|
||||
"enum": ["anthropic"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"model": {
|
||||
"anyOf": [
|
||||
{
|
||||
"enum": [
|
||||
"claude-2",
|
||||
"claude-instant-1"
|
||||
]
|
||||
"enum": ["claude-2", "claude-instant-1"]
|
||||
},
|
||||
{
|
||||
"type": "string"
|
||||
|
|
@ -539,22 +507,15 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"google-palm"
|
||||
]
|
||||
"enum": ["google-palm"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"model": {
|
||||
"enum": [
|
||||
"chat-bison-001",
|
||||
"gemini-pro"
|
||||
]
|
||||
"enum": ["chat-bison-001", "gemini-pro"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -563,14 +524,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"together"
|
||||
]
|
||||
"enum": ["together"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -602,14 +559,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"deepinfra"
|
||||
]
|
||||
"enum": ["deepinfra"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -632,9 +585,7 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -677,14 +628,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"ollama"
|
||||
]
|
||||
"enum": ["ollama"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -729,23 +676,15 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"mistral"
|
||||
]
|
||||
"enum": ["mistral"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"model": {
|
||||
"enum": [
|
||||
"mistral-tiny",
|
||||
"mistral-small",
|
||||
"mistral-medium"
|
||||
]
|
||||
"enum": ["mistral-tiny", "mistral-small", "mistral-medium"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -757,30 +696,20 @@
|
|||
"const": "azure"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"apiType"
|
||||
]
|
||||
"required": ["apiType"]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"engine",
|
||||
"apiVersion",
|
||||
"apiBase"
|
||||
]
|
||||
"required": ["engine", "apiVersion", "apiBase"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"openai"
|
||||
]
|
||||
"enum": ["openai"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -797,9 +726,7 @@
|
|||
"const": "llamafile"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -813,14 +740,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"text-gen-webui"
|
||||
]
|
||||
"enum": ["text-gen-webui"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -834,14 +757,10 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"flowise"
|
||||
]
|
||||
"enum": ["flowise"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
|
|
@ -868,10 +787,7 @@
|
|||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"value"
|
||||
]
|
||||
"required": ["key", "value"]
|
||||
}
|
||||
},
|
||||
"additionalFlowiseConfiguration": {
|
||||
|
|
@ -890,10 +806,7 @@
|
|||
"description": "Configuration Property value"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"key",
|
||||
"value"
|
||||
]
|
||||
"required": ["key", "value"]
|
||||
}
|
||||
},
|
||||
"model": {
|
||||
|
|
@ -970,9 +883,7 @@
|
|||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"default"
|
||||
]
|
||||
"required": ["default"]
|
||||
},
|
||||
"SlashCommand": {
|
||||
"title": "SlashCommand",
|
||||
|
|
@ -1029,9 +940,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"issue"
|
||||
]
|
||||
"enum": ["issue"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1044,23 +953,17 @@
|
|||
"description": "Enter the URL of the GitHub repository for which you want to generate the issue."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"repositoryUrl"
|
||||
]
|
||||
"required": ["repositoryUrl"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"params"
|
||||
]
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"edit"
|
||||
]
|
||||
"enum": ["edit"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1082,10 +985,7 @@
|
|||
}
|
||||
}
|
||||
],
|
||||
"required": [
|
||||
"name",
|
||||
"description"
|
||||
]
|
||||
"required": ["name", "description"]
|
||||
},
|
||||
"CustomCommand": {
|
||||
"title": "CustomCommand",
|
||||
|
|
@ -1104,11 +1004,7 @@
|
|||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"prompt",
|
||||
"description"
|
||||
]
|
||||
"required": ["name", "prompt", "description"]
|
||||
},
|
||||
"ContextProviderWithParams": {
|
||||
"title": "ContextProviderWithParams",
|
||||
|
|
@ -1132,7 +1028,8 @@
|
|||
"docs",
|
||||
"tree",
|
||||
"highlights",
|
||||
"outline"
|
||||
"outline",
|
||||
"postgres"
|
||||
],
|
||||
"markdownEnumDescriptions": [
|
||||
"Reference the contents of the current changes as given by `git diff`",
|
||||
|
|
@ -1150,7 +1047,8 @@
|
|||
"Display a file tree of the current workspace",
|
||||
"Include a repo map showing important code objects",
|
||||
"Displays important snippets of code from the currently open files",
|
||||
"Displays definition lines from the currently open files"
|
||||
"Displays definition lines from the currently open files",
|
||||
"References Postgres table schema and sample rows"
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -1170,9 +1068,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"google"
|
||||
]
|
||||
"enum": ["google"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1185,23 +1081,17 @@
|
|||
"description": "Your API key for https://serper.dev in order to get Google search results"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"serperApiKey"
|
||||
]
|
||||
"required": ["serperApiKey"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"params"
|
||||
]
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"open"
|
||||
]
|
||||
"enum": ["open"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1223,9 +1113,7 @@
|
|||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"issue"
|
||||
]
|
||||
"enum": ["issue"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1254,37 +1142,120 @@
|
|||
"type": {
|
||||
"type": "string",
|
||||
"description": "The type of issues to search for",
|
||||
"enum": [
|
||||
"open",
|
||||
"closed",
|
||||
"all"
|
||||
]
|
||||
"enum": ["open", "closed", "all"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"owner",
|
||||
"repo"
|
||||
]
|
||||
"required": ["owner", "repo"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"repos"
|
||||
]
|
||||
"required": ["repos"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"params"
|
||||
]
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"http"
|
||||
]
|
||||
"enum": ["database"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"connections": {
|
||||
"type": "array",
|
||||
"description": "A list of database connections",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "A unique name for this database connection"
|
||||
},
|
||||
"connection_type": {
|
||||
"type": "string",
|
||||
"description": "The type of database (e.g., 'postgres', 'mysql')",
|
||||
"enum": ["postgres", "mysql", "sqlite"]
|
||||
},
|
||||
"connection": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"user": {
|
||||
"type": "string",
|
||||
"description": "The database user name"
|
||||
},
|
||||
"host": {
|
||||
"type": "string",
|
||||
"description": "The host address of the database server"
|
||||
},
|
||||
"database": {
|
||||
"type": "string",
|
||||
"description": "The name of the database to connect to"
|
||||
},
|
||||
"password": {
|
||||
"type": "string",
|
||||
"description": "The password for the database user"
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "The port number to connect to at the host"
|
||||
},
|
||||
"filename": {
|
||||
"type": "string",
|
||||
"description": "File location for simple file DB's"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
},
|
||||
"required": ["name", "type", "connection"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["connections"]
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["jira"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"domain": {
|
||||
"type": "string",
|
||||
"description": "Your Jira domain, for example company.atlassian.net."
|
||||
},
|
||||
"email": {
|
||||
"type": "string",
|
||||
"description": "The email that you log into Jira with"
|
||||
},
|
||||
"token": {
|
||||
"type": "string",
|
||||
"description": "Your atlassian API token from https://id.atlassian.com/manage-profile/security/api-tokens"
|
||||
},
|
||||
"issueQuery": {
|
||||
"type": "string",
|
||||
"description": "Customize the query used to find Jira issues"
|
||||
}
|
||||
},
|
||||
"required": ["domain", "email", "token"]
|
||||
}
|
||||
},
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["http"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1297,24 +1268,17 @@
|
|||
"description": "The HTTP endpoint of your context provider server."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"url"
|
||||
]
|
||||
"required": ["url"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"params"
|
||||
]
|
||||
"required": ["params"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": [
|
||||
"codebase",
|
||||
"folder"
|
||||
]
|
||||
"enum": ["codebase", "folder"]
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -1344,11 +1308,68 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"name": {
|
||||
"enum": ["postgres"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"then": {
|
||||
"properties": {
|
||||
"params": {
|
||||
"properties": {
|
||||
"host": {
|
||||
"title": "Host",
|
||||
"description": "Database host",
|
||||
"default": "localhost",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"description": "Database port",
|
||||
"default": 5432,
|
||||
"type": "integer"
|
||||
},
|
||||
"user": {
|
||||
"title": "User",
|
||||
"description": "Database user",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"password": {
|
||||
"title": "Password",
|
||||
"description": "Database password",
|
||||
"type": "string"
|
||||
},
|
||||
"database": {
|
||||
"title": "Database",
|
||||
"description": "Database name",
|
||||
"default": "postgres",
|
||||
"type": "string"
|
||||
},
|
||||
"schema": {
|
||||
"title": "Schema",
|
||||
"description": "Database schema",
|
||||
"default": "public",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleRows": {
|
||||
"title": "Sample Rows",
|
||||
"description": "Number of rows to sample from the database",
|
||||
"default": 3,
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": ["host", "port", "user", "password", "database"]
|
||||
}
|
||||
}
|
||||
],
|
||||
"required": [
|
||||
"name"
|
||||
]
|
||||
"required": ["name"]
|
||||
},
|
||||
"SerializedContinueConfig": {
|
||||
"title": "config.json",
|
||||
|
|
@ -1466,11 +1487,7 @@
|
|||
"type": "object",
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"transformers.js",
|
||||
"ollama",
|
||||
"openai"
|
||||
]
|
||||
"enum": ["transformers.js", "ollama", "openai"]
|
||||
},
|
||||
"model": {
|
||||
"type": "string"
|
||||
|
|
@ -1482,27 +1499,19 @@
|
|||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
],
|
||||
"required": ["provider"],
|
||||
"allOf": [
|
||||
{
|
||||
"if": {
|
||||
"properties": {
|
||||
"provider": {
|
||||
"enum": [
|
||||
"ollama"
|
||||
]
|
||||
"enum": ["ollama"]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"provider"
|
||||
]
|
||||
"required": ["provider"]
|
||||
},
|
||||
"then": {
|
||||
"required": [
|
||||
"model"
|
||||
]
|
||||
"required": ["model"]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
|
@ -1558,10 +1567,7 @@
|
|||
},
|
||||
"mergeBehavior": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"merge",
|
||||
"overwrite"
|
||||
],
|
||||
"enum": ["merge", "overwrite"],
|
||||
"default": "merge",
|
||||
"title": "Merge behavior",
|
||||
"markdownDescription": "If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json."
|
||||
|
|
@ -1569,4 +1575,4 @@
|
|||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +1,18 @@
|
|||
"""
|
||||
Welcome to Continue!
|
||||
|
||||
_________ _____ _____
|
||||
__ ____/______ _______ __ /____(_)_______ ____ _______
|
||||
_ / _ __ \__ __ \_ __/__ / __ __ \_ / / /_ _ \
|
||||
/ /___ / /_/ /_ / / // /_ _ / _ / / // /_/ / / __/
|
||||
\____/ \____/ /_/ /_/ \__/ /_/ /_/ /_/ \__,_/ \___/
|
||||
|
||||
This is a 2 minute tutorial.
|
||||
|
||||
It will walk you through the basic features:
|
||||
1. Ask a question
|
||||
2. Edit code
|
||||
3. Debug
|
||||
Welcome to Continue! This is a 2 minute tutorial.
|
||||
|
||||
You can either
|
||||
- follow the instructions on your own, or
|
||||
- follow along by clicking the gray CodeLens buttons above the lines, in order, starting with "Begin Section"
|
||||
"""
|
||||
|
||||
# region —————————————————————————— Part 1: Ask a question about code [⌘ M] ——————————————————————————
|
||||
# region —————————————————————————— Part 1: Ask a question about code [⌘ L] ——————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Highlight the function below"""
|
||||
|
|
@ -34,14 +27,14 @@ def mysterious_function(x):
|
|||
return x
|
||||
|
||||
|
||||
"""Step 2: Use the keyboard shortcut [⌘ M] to
|
||||
"""Step 2: Use the keyboard shortcut [⌘ L] to
|
||||
select the code and toggle the Continue input box"""
|
||||
|
||||
"""Step 3: Ask a question and press Enter"""
|
||||
|
||||
# endregion
|
||||
|
||||
# region ————————————————————————————————— Part 2: Edit code [⌘ ⇧ L] —————————————————————————————————
|
||||
# region ————————————————————————————————— Part 2: Edit code [⌘ I] —————————————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Highlight this code"""
|
||||
|
|
@ -60,7 +53,7 @@ def mysterious_function(x):
|
|||
return x
|
||||
|
||||
|
||||
"""Step 2: Use the keyboard shortcut [⌘ ⇧ L] to edit"""
|
||||
"""Step 2: Use the keyboard shortcut [⌘ I] to edit"""
|
||||
|
||||
"""Step 3: Type "<your edit request>" and press Enter"""
|
||||
|
||||
|
|
@ -72,7 +65,7 @@ accept [⌘ ⇧ ⏎] or reject [⌘ ⇧ ⌫] the edit"""
|
|||
# region ———————————————————————————— Part 3: Debug automatically [⌘ ⇧ R] ————————————————————————————
|
||||
|
||||
|
||||
"""Step 1: Run this Python file"""
|
||||
"""Step 1: Run this Python file (it should error!)"""
|
||||
|
||||
|
||||
def print_sum(list_to_print):
|
||||
|
|
|
|||
|
|
@ -1,17 +1,27 @@
|
|||
# 👋 Welcome to Continue
|
||||
|
||||
## 🔑 Most important shortcuts
|
||||
|
||||
> If you've been using Continue, these have changed
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>L</kbd> = Select code
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Select code for follow-up
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>I</kbd> = Quick edit
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal
|
||||
|
||||
## ❗️ Before you get started
|
||||
|
||||
Continue is currently in the left sidebar, but we recommend moving it to the right. This way it won't cover your file explorer. You can move it back at any time.
|
||||
|
||||

|
||||
|
||||
## 🔑 Most important shortcuts
|
||||
## ⚡️ Setting up tab autocomplete
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>M</kbd> = Select code
|
||||
1. Download [Ollama](https://ollama.ai)
|
||||
2. Download starcoder:3b by running `ollama run starcoder:3b` in the terminal
|
||||
3. Click the `Continue` button in the status bar (bottom right of the VS Code window) to enable autocomplete
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>M</kbd> = Select code for follow-up
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> = Quick edit
|
||||
|
||||
<kbd>Cmd/Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>R</kbd> = Automatically debug terminal
|
||||

|
||||
|
|
|
|||
14409
extensions/vscode/package-lock.json
generated
14409
extensions/vscode/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"icon": "media/icon.png",
|
||||
"version": "0.9.63",
|
||||
"version": "0.9.72",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/continuedev/continue"
|
||||
|
|
@ -65,7 +65,22 @@
|
|||
"continue.enableTabAutocomplete": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"markdownDescription": "Enable Continue's experimental tab autocomplete feature. Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://continue.dev/docs/walkthroughs/tab-autocomplete)"
|
||||
"markdownDescription": "Enable Continue's experimental tab autocomplete feature (pre-release only). Read our walkthrough to learn about configuration and how to share feedback: [continue.dev › Walkthrough: Tab Autocomplete](https://continue.dev/docs/walkthroughs/tab-autocomplete)"
|
||||
},
|
||||
"continue.remoteConfigServerUrl": {
|
||||
"type": "string",
|
||||
"default": null,
|
||||
"markdownDescription": "If your team is set up to use shared configuration, enter the server URL here and your user token below to enable automatic syncing."
|
||||
},
|
||||
"continue.userToken": {
|
||||
"type": "string",
|
||||
"default": null,
|
||||
"markdownDescription": "If your team is set up to use shared configuration, enter your user token here and your server URL above to enable automatic syncing."
|
||||
},
|
||||
"continue.remoteConfigSyncPeriod": {
|
||||
"type": "number",
|
||||
"default": 60,
|
||||
"description": "The period of time in minutes between automatic syncs."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -180,13 +195,13 @@
|
|||
"keybindings": [
|
||||
{
|
||||
"command": "continue.focusContinueInput",
|
||||
"mac": "cmd+m",
|
||||
"key": "ctrl+m"
|
||||
"mac": "cmd+l",
|
||||
"key": "ctrl+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.focusContinueInputWithoutClear",
|
||||
"mac": "cmd+shift+m",
|
||||
"key": "ctrl+shift+m"
|
||||
"mac": "cmd+shift+l",
|
||||
"key": "ctrl+shift+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.acceptDiff",
|
||||
|
|
@ -206,13 +221,13 @@
|
|||
},
|
||||
{
|
||||
"command": "continue.quickEdit",
|
||||
"mac": "cmd+shift+l",
|
||||
"key": "ctrl+shift+l"
|
||||
"mac": "cmd+i",
|
||||
"key": "ctrl+i"
|
||||
},
|
||||
{
|
||||
"command": "continue.toggleAuxiliaryBar",
|
||||
"mac": "alt+cmd+m",
|
||||
"key": "alt+ctrl+m"
|
||||
"mac": "alt+cmd+l",
|
||||
"key": "alt+ctrl+l"
|
||||
},
|
||||
{
|
||||
"command": "continue.debugTerminal",
|
||||
|
|
@ -461,6 +476,7 @@
|
|||
"axios": "^1.2.5",
|
||||
"core": "file:../../core",
|
||||
"cors": "^2.8.5",
|
||||
"dbinfoz": "^0.1.4",
|
||||
"downshift": "^7.6.0",
|
||||
"express": "^4.18.2",
|
||||
"fkill": "^8.1.0",
|
||||
|
|
|
|||
|
|
@ -13,11 +13,22 @@ if (args[2] === "--target") {
|
|||
(async () => {
|
||||
console.log("[info] Packaging extension for target ", target);
|
||||
|
||||
// Copy config_schema.json to config.json in docs
|
||||
// Copy config_schema.json to config.json in docs and intellij
|
||||
fs.copyFileSync(
|
||||
"config_schema.json",
|
||||
path.join("..", "..", "docs", "static", "schemas", "config.json")
|
||||
);
|
||||
fs.copyFileSync(
|
||||
"config_schema.json",
|
||||
path.join(
|
||||
"..",
|
||||
"intellij",
|
||||
"src",
|
||||
"main",
|
||||
"resources",
|
||||
"config_schema.json"
|
||||
)
|
||||
);
|
||||
// Modify and copy for .continuerc.json
|
||||
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
|
||||
schema.definitions.SerializedContinueConfig.properties.mergeBehavior = {
|
||||
|
|
@ -77,11 +88,19 @@ if (args[2] === "--target") {
|
|||
});
|
||||
});
|
||||
|
||||
// Put back index.html
|
||||
if (fs.existsSync(indexHtmlPath)) {
|
||||
fs.rmSync(indexHtmlPath, {});
|
||||
}
|
||||
fs.copyFileSync("tmp_index.html", indexHtmlPath);
|
||||
fs.unlinkSync("tmp_index.html");
|
||||
|
||||
// Copy over other misc. files
|
||||
fs.copyFileSync(
|
||||
"../extensions/vscode/gui/onigasm.wasm",
|
||||
path.join(intellijExtensionWebviewPath, "onigasm.wasm")
|
||||
);
|
||||
|
||||
console.log("[info] Copied gui build to Intellij extension");
|
||||
|
||||
// Then copy over the dist folder to the VSCode extension //
|
||||
|
|
|
|||
|
|
@ -2,26 +2,13 @@ import { getTsConfigPath, migrate } from "core/util/paths";
|
|||
import { Telemetry } from "core/util/posthog";
|
||||
import * as fs from "fs";
|
||||
import path from "path";
|
||||
import { v4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import { registerAllCommands } from "../commands";
|
||||
import IdeProtocolClient from "../continueIdeClient";
|
||||
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
|
||||
import { VsCodeExtension } from "../extension/vscodeExtension";
|
||||
import registerQuickFixProvider from "../lang-server/codeActions";
|
||||
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
|
||||
import {
|
||||
ContinueCompletionProvider,
|
||||
setupStatusBar,
|
||||
} from "../lang-server/completionProvider";
|
||||
import { vsCodeIndexCodebase } from "../util/indexCodebase";
|
||||
import { getExtensionVersion } from "../util/util";
|
||||
import { getExtensionUri } from "../util/vscode";
|
||||
import { setupInlineTips } from "./inlineTips";
|
||||
|
||||
export let extensionContext: vscode.ExtensionContext | undefined = undefined;
|
||||
export let ideProtocolClient: IdeProtocolClient;
|
||||
export let windowId: string = v4();
|
||||
|
||||
export async function showTutorial() {
|
||||
const tutorialPath = path.join(
|
||||
getExtensionUri().fsPath,
|
||||
|
|
@ -47,7 +34,9 @@ async function openTutorialFirstTime(context: vscode.ExtensionContext) {
|
|||
}
|
||||
}
|
||||
|
||||
function showRefactorMigrationMessage() {
|
||||
function showRefactorMigrationMessage(
|
||||
extensionContext: vscode.ExtensionContext
|
||||
) {
|
||||
// Only if the vscode setting continue.manuallyRunningSserver is true
|
||||
const manuallyRunningServer =
|
||||
vscode.workspace
|
||||
|
|
@ -81,47 +70,15 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
// Add necessary files
|
||||
getTsConfigPath();
|
||||
|
||||
extensionContext = context;
|
||||
|
||||
// Register commands and providers
|
||||
registerAllCodeLensProviders(context);
|
||||
registerAllCommands(context);
|
||||
registerQuickFixProvider();
|
||||
await openTutorialFirstTime(context);
|
||||
setupInlineTips(context);
|
||||
showRefactorMigrationMessage();
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get<boolean>("enableTabAutocomplete");
|
||||
showRefactorMigrationMessage(context);
|
||||
|
||||
// Register inline completion provider (odd versions are pre-release)
|
||||
if (parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !== 0) {
|
||||
setupStatusBar(enabled);
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerInlineCompletionItemProvider(
|
||||
[{ pattern: "**" }],
|
||||
new ContinueCompletionProvider()
|
||||
)
|
||||
);
|
||||
}
|
||||
const vscodeExtension = new VsCodeExtension(context);
|
||||
|
||||
ideProtocolClient = new IdeProtocolClient(context);
|
||||
|
||||
// Register Continue GUI as sidebar webview, and beginning a new session
|
||||
const provider = new ContinueGUIWebviewViewProvider();
|
||||
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
"continue.continueGUIView",
|
||||
provider,
|
||||
{
|
||||
webviewOptions: { retainContextWhenHidden: true },
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
vsCodeIndexCodebase(ideProtocolClient.getWorkspaceDirectories());
|
||||
|
||||
migrate("showWelcome", () => {
|
||||
migrate("showWelcome_1", () => {
|
||||
vscode.commands.executeCommand(
|
||||
"markdown.showPreview",
|
||||
vscode.Uri.file(
|
||||
|
|
@ -130,25 +87,6 @@ export async function activateExtension(context: vscode.ExtensionContext) {
|
|||
);
|
||||
});
|
||||
|
||||
// (async () => {
|
||||
// const defaultDocsPages = [
|
||||
// ["Socket.IO", "https://python-socketio.readthedocs.io/en/stable"],
|
||||
// // ["Flask", "https://flask.palletsprojects.com/en/2.0.x/"],
|
||||
// ];
|
||||
|
||||
// const config = await configHandler.loadConfig(new VsCodeIde());
|
||||
|
||||
// defaultDocsPages.forEach(async ([title, url]) => {
|
||||
// for await (const update of indexDocs(
|
||||
// title,
|
||||
// new URL(url),
|
||||
// config.embeddingsProvider
|
||||
// )) {
|
||||
// console.log(update.progress, update.desc);
|
||||
// }
|
||||
// });
|
||||
// })();
|
||||
|
||||
// Load Continue configuration
|
||||
if (!context.globalState.get("hasBeenInstalled")) {
|
||||
context.globalState.update("hasBeenInstalled", true);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { getMetaKeyLabel } from "../util/util";
|
|||
|
||||
const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
|
||||
after: {
|
||||
contentText: `${getMetaKeyLabel()} M to select code, ${getMetaKeyLabel()} ⇧ L to edit`,
|
||||
contentText: `${getMetaKeyLabel()} L to select code, ${getMetaKeyLabel()} I to edit`,
|
||||
color: "#888",
|
||||
margin: "0 0 0 6em",
|
||||
fontWeight: "bold",
|
||||
|
|
@ -31,7 +31,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
|
|||
const line = Math.max(0, selection.start.line - 1);
|
||||
|
||||
const hoverMarkdown = new vscode.MarkdownString(
|
||||
`Use ${getMetaKeyLabel()} M to select code, or ${getMetaKeyLabel()} ⇧ L to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
|
||||
`Use ${getMetaKeyLabel()} L to select code, or ${getMetaKeyLabel()} I to edit highlighted code. Click [here](command:continue.hideInlineTip) if you don't want to see these inline suggestions.`
|
||||
);
|
||||
hoverMarkdown.isTrusted = true;
|
||||
hoverMarkdown.supportHtml = true;
|
||||
|
|
@ -49,7 +49,7 @@ function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
|
|||
const emptyFileTooltipDecoration = vscode.window.createTextEditorDecorationType(
|
||||
{
|
||||
after: {
|
||||
contentText: `Use ${getMetaKeyLabel()} ⇧ L to generate code`,
|
||||
contentText: `Use ${getMetaKeyLabel()} I to generate code`,
|
||||
color: "#888",
|
||||
margin: "2em 0 0 0",
|
||||
fontStyle: "italic",
|
||||
|
|
|
|||
|
|
@ -3,19 +3,26 @@ import * as os from "os";
|
|||
import * as path from "path";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { extensionContext, ideProtocolClient } from "./activation/activate";
|
||||
import { debugPanelWebview, getSidebarContent } from "./debugPanel";
|
||||
import { acceptDiffCommand, rejectDiffCommand } from "./diff/horizontal";
|
||||
import {
|
||||
editorToVerticalDiffCodeLens,
|
||||
streamEdit,
|
||||
verticalPerLineDiffManager,
|
||||
} from "./diff/verticalPerLine/manager";
|
||||
import { VsCodeIde } from "./ideProtocol";
|
||||
import { IDE } from "core";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { logDevData } from "core/util/devdata";
|
||||
import { ContinueGUIWebviewViewProvider } from "./debugPanel";
|
||||
import { DiffManager } from "./diff/horizontal";
|
||||
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
|
||||
import { AutocompleteOutcome } from "./lang-server/completionProvider";
|
||||
import { configHandler, llmFromTitle } from "./loadConfig";
|
||||
import { VsCodeWebviewProtocol } from "./webviewProtocol";
|
||||
|
||||
function addHighlightedCodeToContext(edit: boolean) {
|
||||
function getFullScreenTab() {
|
||||
const tabs = vscode.window.tabGroups.all.flatMap((tabGroup) => tabGroup.tabs);
|
||||
return tabs.find(
|
||||
(tab) => (tab.input as any).viewType?.endsWith("continue.continueGUIView")
|
||||
);
|
||||
}
|
||||
|
||||
function addHighlightedCodeToContext(
|
||||
edit: boolean,
|
||||
webviewProtocol: VsCodeWebviewProtocol | undefined
|
||||
) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (editor) {
|
||||
const selection = editor.selection;
|
||||
|
|
@ -37,22 +44,28 @@ function addHighlightedCodeToContext(edit: boolean) {
|
|||
},
|
||||
};
|
||||
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "highlightedCode",
|
||||
webviewProtocol?.request("highlightedCode", {
|
||||
rangeInFileWithContents,
|
||||
edit,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) {
|
||||
async function addEntireFileToContext(
|
||||
filepath: vscode.Uri,
|
||||
edit: boolean,
|
||||
webviewProtocol: VsCodeWebviewProtocol | undefined
|
||||
) {
|
||||
// If a directory, add all files in the directory
|
||||
const stat = await vscode.workspace.fs.stat(filepath);
|
||||
if (stat.type === vscode.FileType.Directory) {
|
||||
const files = await vscode.workspace.fs.readDirectory(filepath);
|
||||
for (const [filename, type] of files) {
|
||||
if (type === vscode.FileType.File) {
|
||||
addEntireFileToContext(vscode.Uri.joinPath(filepath, filename), edit);
|
||||
addEntireFileToContext(
|
||||
vscode.Uri.joinPath(filepath, filename),
|
||||
edit,
|
||||
webviewProtocol
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
|
|
@ -75,79 +88,74 @@ async function addEntireFileToContext(filepath: vscode.Uri, edit: boolean) {
|
|||
},
|
||||
};
|
||||
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "highlightedCode",
|
||||
webviewProtocol?.request("highlightedCode", {
|
||||
rangeInFileWithContents,
|
||||
edit,
|
||||
});
|
||||
}
|
||||
|
||||
function acceptRejectVerticalDiffBlock(
|
||||
accept: boolean,
|
||||
filepath?: string,
|
||||
index?: number
|
||||
) {
|
||||
if (!filepath) {
|
||||
const activeEditor = vscode.window.activeTextEditor;
|
||||
if (!activeEditor) {
|
||||
return;
|
||||
}
|
||||
filepath = activeEditor.document.uri.fsPath;
|
||||
}
|
||||
|
||||
if (typeof index === "undefined") {
|
||||
index = 0;
|
||||
}
|
||||
|
||||
let blocks = editorToVerticalDiffCodeLens.get(filepath);
|
||||
const block = blocks?.[index];
|
||||
if (!blocks || !block) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handler = verticalPerLineDiffManager.getHandlerForFile(filepath);
|
||||
if (!handler) {
|
||||
return;
|
||||
}
|
||||
|
||||
// CodeLens object removed from editorToVerticalDiffCodeLens here
|
||||
handler.acceptRejectBlock(accept, block.start, block.numGreen, block.numRed);
|
||||
}
|
||||
|
||||
// Copy everything over from extension.ts
|
||||
const commandsMap: { [command: string]: (...args: any) => any } = {
|
||||
"continue.acceptDiff": acceptDiffCommand,
|
||||
"continue.rejectDiff": rejectDiffCommand,
|
||||
const commandsMap: (
|
||||
ide: IDE,
|
||||
extensionContext: vscode.ExtensionContext,
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
configHandler: ConfigHandler,
|
||||
diffManager: DiffManager,
|
||||
verticalDiffManager: VerticalPerLineDiffManager
|
||||
) => { [command: string]: (...args: any) => any } = (
|
||||
ide,
|
||||
extensionContext,
|
||||
sidebar,
|
||||
configHandler,
|
||||
diffManager,
|
||||
verticalDiffManager
|
||||
) => ({
|
||||
"continue.acceptDiff": async (newFilepath?: string | vscode.Uri) => {
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
verticalDiffManager.clearForFilepath(newFilepath, true);
|
||||
await diffManager.acceptDiff(newFilepath);
|
||||
},
|
||||
"continue.rejectDiff": async (newFilepath?: string | vscode.Uri) => {
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
verticalDiffManager.clearForFilepath(newFilepath, false);
|
||||
await diffManager.rejectDiff(newFilepath);
|
||||
},
|
||||
"continue.acceptVerticalDiffBlock": (filepath?: string, index?: number) => {
|
||||
acceptRejectVerticalDiffBlock(true, filepath, index);
|
||||
verticalDiffManager.acceptRejectVerticalDiffBlock(true, filepath, index);
|
||||
},
|
||||
"continue.rejectVerticalDiffBlock": (filepath?: string, index?: number) => {
|
||||
acceptRejectVerticalDiffBlock(false, filepath, index);
|
||||
verticalDiffManager.acceptRejectVerticalDiffBlock(false, filepath, index);
|
||||
},
|
||||
"continue.quickFix": async (message: string, code: string, edit: boolean) => {
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "newSessionWithPrompt",
|
||||
sidebar.webviewProtocol?.request("newSessionWithPrompt", {
|
||||
prompt: `${
|
||||
edit ? "/edit " : ""
|
||||
}${code}\n\nHow do I fix this problem in the above code?: ${message}`,
|
||||
});
|
||||
|
||||
if (!edit) {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
}
|
||||
},
|
||||
"continue.focusContinueInput": async () => {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "focusContinueInput",
|
||||
});
|
||||
addHighlightedCodeToContext(false);
|
||||
if (!getFullScreenTab()) {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
}
|
||||
sidebar.webviewProtocol?.request("focusContinueInput", undefined);
|
||||
addHighlightedCodeToContext(false, sidebar.webviewProtocol);
|
||||
},
|
||||
"continue.focusContinueInputWithoutClear": async () => {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "focusContinueInputWithoutClear",
|
||||
});
|
||||
addHighlightedCodeToContext(true);
|
||||
if (!getFullScreenTab()) {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
}
|
||||
sidebar.webviewProtocol?.request(
|
||||
"focusContinueInputWithoutClear",
|
||||
undefined
|
||||
);
|
||||
addHighlightedCodeToContext(true, sidebar.webviewProtocol);
|
||||
},
|
||||
"continue.toggleAuxiliaryBar": () => {
|
||||
vscode.commands.executeCommand("workbench.action.toggleAuxiliaryBar");
|
||||
|
|
@ -167,7 +175,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
}
|
||||
|
||||
if (text.length > 0) {
|
||||
await streamEdit(text);
|
||||
await verticalDiffManager.streamEdit(text);
|
||||
} else {
|
||||
// Pick context first
|
||||
const quickPickItems: Promise<vscode.QuickPickItem[]> = configHandler
|
||||
|
|
@ -201,7 +209,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
title: "Continue Quick Edit",
|
||||
});
|
||||
if (text) {
|
||||
const llm = await llmFromTitle();
|
||||
const llm = await configHandler.llmFromTitle();
|
||||
const config = await configHandler.loadConfig();
|
||||
const context = (
|
||||
await Promise.all(
|
||||
|
|
@ -216,7 +224,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
|
||||
return provider.getContextItems("", {
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
ide: new VsCodeIde(),
|
||||
ide,
|
||||
llm,
|
||||
fullInput: text || "",
|
||||
selectedCode: [],
|
||||
|
|
@ -230,25 +238,29 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
"\n\n---\n\n" +
|
||||
text;
|
||||
|
||||
await streamEdit(text);
|
||||
await verticalDiffManager.streamEdit(text);
|
||||
}
|
||||
}
|
||||
},
|
||||
"continue.writeCommentsForCode": async () => {
|
||||
await streamEdit("Write comments for this code");
|
||||
await verticalDiffManager.streamEdit(
|
||||
"Write comments for this code. Do not change anything about the code itself."
|
||||
);
|
||||
},
|
||||
"continue.writeDocstringForCode": async () => {
|
||||
await streamEdit("Write a docstring for this code");
|
||||
await verticalDiffManager.streamEdit(
|
||||
"Write a docstring for this code. Do not change anything about the code itself."
|
||||
);
|
||||
},
|
||||
"continue.fixCode": async () => {
|
||||
await streamEdit("Fix this code");
|
||||
await verticalDiffManager.streamEdit("Fix this code");
|
||||
},
|
||||
"continue.optimizeCode": async () => {
|
||||
await streamEdit("Optimize this code");
|
||||
await verticalDiffManager.streamEdit("Optimize this code");
|
||||
},
|
||||
"continue.fixGrammar": async () => {
|
||||
await streamEdit(
|
||||
"If there are any grammar or spelling mistakes in this writing, fix them"
|
||||
await verticalDiffManager.streamEdit(
|
||||
"If there are any grammar or spelling mistakes in this writing, fix them. Do not make other large changes to the writing."
|
||||
);
|
||||
},
|
||||
"continue.viewLogs": async () => {
|
||||
|
|
@ -264,11 +276,10 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
await vscode.window.showTextDocument(uri);
|
||||
},
|
||||
"continue.debugTerminal": async () => {
|
||||
const terminalContents = await ideProtocolClient.getTerminalContents(1);
|
||||
const terminalContents = await ide.getTerminalContents();
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "userInput",
|
||||
input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents}`,
|
||||
sidebar.webviewProtocol?.request("userInput", {
|
||||
input: `I got the following error, can you please help explain how to fix it?\n\n${terminalContents.trim()}`,
|
||||
});
|
||||
},
|
||||
"continue.hideInlineTip": () => {
|
||||
|
|
@ -280,21 +291,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
// Commands without keyboard shortcuts
|
||||
"continue.addModel": () => {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "addModel",
|
||||
});
|
||||
sidebar.webviewProtocol?.request("addModel", undefined);
|
||||
},
|
||||
"continue.openSettingsUI": () => {
|
||||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "openSettings",
|
||||
});
|
||||
sidebar.webviewProtocol?.request("openSettings", undefined);
|
||||
},
|
||||
"continue.sendMainUserInput": (text: string) => {
|
||||
ideProtocolClient.sendMainUserInput(text);
|
||||
sidebar.sendMainUserInput(text);
|
||||
},
|
||||
"continue.shareSession": () => {
|
||||
ideProtocolClient.sendMainUserInput("/share");
|
||||
sidebar.sendMainUserInput("/share");
|
||||
},
|
||||
"continue.selectRange": (startLine: number, endLine: number) => {
|
||||
if (!vscode.window.activeTextEditor) {
|
||||
|
|
@ -319,27 +326,17 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
});
|
||||
},
|
||||
"continue.sendToTerminal": (text: string) => {
|
||||
ideProtocolClient.runCommand(text);
|
||||
ide.runCommand(text);
|
||||
},
|
||||
"continue.newSession": () => {
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "newSession",
|
||||
});
|
||||
sidebar.webviewProtocol?.request("newSession", undefined);
|
||||
},
|
||||
"continue.viewHistory": () => {
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "viewHistory",
|
||||
});
|
||||
sidebar.webviewProtocol?.request("viewHistory", undefined);
|
||||
},
|
||||
"continue.toggleFullScreen": () => {
|
||||
// Check if full screen is already open by checking open tabs
|
||||
const tabs = vscode.window.tabGroups.all.flatMap(
|
||||
(tabGroup) => tabGroup.tabs
|
||||
);
|
||||
|
||||
const fullScreenTab = tabs.find(
|
||||
(tab) => (tab.input as any).viewType?.endsWith("continue.continueGUIView")
|
||||
);
|
||||
const fullScreenTab = getFullScreenTab();
|
||||
|
||||
// Check if the active editor is the Continue GUI View
|
||||
if (fullScreenTab && fullScreenTab.isActive) {
|
||||
|
|
@ -364,7 +361,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
return;
|
||||
}
|
||||
|
||||
// Close the sidebars
|
||||
// Close the sidebar.webviews
|
||||
// vscode.commands.executeCommand("workbench.action.closeSidebar");
|
||||
vscode.commands.executeCommand("workbench.action.closeAuxiliaryBar");
|
||||
// vscode.commands.executeCommand("workbench.action.toggleZenMode");
|
||||
|
|
@ -373,9 +370,12 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
"Continue",
|
||||
vscode.ViewColumn.One
|
||||
);
|
||||
panel.webview.html = getSidebarContent(
|
||||
panel.webview.html = sidebar.getSidebarContent(
|
||||
extensionContext,
|
||||
panel,
|
||||
ide,
|
||||
configHandler,
|
||||
verticalDiffManager,
|
||||
undefined,
|
||||
undefined,
|
||||
true
|
||||
|
|
@ -388,7 +388,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
vscode.commands.executeCommand("continue.continueGUIView.focus");
|
||||
|
||||
for (const uri of uris) {
|
||||
addEntireFileToContext(uri, false);
|
||||
addEntireFileToContext(uri, false, sidebar.webviewProtocol);
|
||||
}
|
||||
},
|
||||
"continue.updateAllReferences": (filepath: vscode.Uri) => {
|
||||
|
|
@ -398,7 +398,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
return;
|
||||
}
|
||||
const position = editor.selection.active;
|
||||
ideProtocolClient.sendMainUserInput(
|
||||
sidebar.sendMainUserInput(
|
||||
`/references ${filepath.fsPath} ${position.line} ${position.character}`
|
||||
);
|
||||
},
|
||||
|
|
@ -408,7 +408,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
) => {
|
||||
clearTimeout(logRejectionTimeout);
|
||||
outcome.accepted = true;
|
||||
ideProtocolClient.logDevData("autocomplete", outcome);
|
||||
logDevData("autocomplete", outcome);
|
||||
},
|
||||
"continue.toggleTabAutocompleteEnabled": () => {
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
|
|
@ -419,10 +419,27 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
|
|||
vscode.ConfigurationTarget.Global
|
||||
);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export function registerAllCommands(context: vscode.ExtensionContext) {
|
||||
for (const [command, callback] of Object.entries(commandsMap)) {
|
||||
export function registerAllCommands(
|
||||
context: vscode.ExtensionContext,
|
||||
ide: IDE,
|
||||
extensionContext: vscode.ExtensionContext,
|
||||
sidebar: ContinueGUIWebviewViewProvider,
|
||||
configHandler: ConfigHandler,
|
||||
diffManager: DiffManager,
|
||||
verticalDiffManager: VerticalPerLineDiffManager
|
||||
) {
|
||||
for (const [command, callback] of Object.entries(
|
||||
commandsMap(
|
||||
ide,
|
||||
extensionContext,
|
||||
sidebar,
|
||||
configHandler,
|
||||
diffManager,
|
||||
verticalDiffManager
|
||||
)
|
||||
)) {
|
||||
context.subscriptions.push(
|
||||
vscode.commands.registerCommand(command, callback)
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,707 +1,118 @@
|
|||
import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core";
|
||||
import { indexDocs } from "core/indexing/docs";
|
||||
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
|
||||
import { editConfigJson, getConfigJsonPath } from "core/util/paths";
|
||||
import { readFileSync, writeFileSync } from "fs";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { FileEdit, IDE } from "core";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import * as vscode from "vscode";
|
||||
import {
|
||||
extensionContext,
|
||||
ideProtocolClient,
|
||||
showTutorial,
|
||||
windowId,
|
||||
} from "./activation/activate";
|
||||
import { streamEdit } from "./diff/verticalPerLine/manager";
|
||||
import historyManager from "./history";
|
||||
import { VsCodeIde } from "./ideProtocol";
|
||||
import { configHandler, llmFromTitle } from "./loadConfig";
|
||||
import { VerticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
|
||||
import { getTheme } from "./util/getTheme";
|
||||
import { getExtensionUri, getNonce, getUniqueId } from "./util/vscode";
|
||||
import { VsCodeWebviewProtocol } from "./webviewProtocol";
|
||||
|
||||
export let debugPanelWebview: vscode.Webview | undefined;
|
||||
export class ContinueGUIWebviewViewProvider
|
||||
implements vscode.WebviewViewProvider
|
||||
{
|
||||
public static readonly viewType = "continue.continueGUIView";
|
||||
public webviewProtocol: VsCodeWebviewProtocol;
|
||||
|
||||
export async function webviewRequest(
|
||||
messageType: string,
|
||||
data: any = {}
|
||||
): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!debugPanelWebview) {
|
||||
resolve(undefined);
|
||||
resolveWebviewView(
|
||||
webviewView: vscode.WebviewView,
|
||||
_context: vscode.WebviewViewResolveContext,
|
||||
_token: vscode.CancellationToken
|
||||
): void | Thenable<void> {
|
||||
this._webview = webviewView.webview;
|
||||
webviewView.webview.html = this.getSidebarContent(
|
||||
this.extensionContext,
|
||||
webviewView,
|
||||
this.ide,
|
||||
this.configHandler,
|
||||
this.verticalDiffManager
|
||||
);
|
||||
}
|
||||
|
||||
private _webview?: vscode.Webview;
|
||||
|
||||
get webview() {
|
||||
return this._webview;
|
||||
}
|
||||
|
||||
sendMainUserInput(input: string) {
|
||||
this.webview?.postMessage({
|
||||
type: "userInput",
|
||||
input,
|
||||
});
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly windowId: string,
|
||||
private readonly extensionContext: vscode.ExtensionContext,
|
||||
private readonly verticalDiffManager: VerticalPerLineDiffManager
|
||||
) {
|
||||
this.webviewProtocol = new VsCodeWebviewProtocol(
|
||||
ide,
|
||||
configHandler,
|
||||
verticalDiffManager
|
||||
);
|
||||
}
|
||||
|
||||
getSidebarContent(
|
||||
context: vscode.ExtensionContext | undefined,
|
||||
panel: vscode.WebviewPanel | vscode.WebviewView,
|
||||
ide: IDE,
|
||||
configHandler: ConfigHandler,
|
||||
verticalDiffManager: VerticalPerLineDiffManager,
|
||||
page: string | undefined = undefined,
|
||||
edits: FileEdit[] | undefined = undefined,
|
||||
isFullScreen: boolean = false
|
||||
): string {
|
||||
let extensionUri = getExtensionUri();
|
||||
let scriptUri: string;
|
||||
let styleMainUri: string;
|
||||
let vscMediaUrl: string = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui"))
|
||||
.toString();
|
||||
|
||||
const inDevelopmentMode =
|
||||
context?.extensionMode === vscode.ExtensionMode.Development;
|
||||
if (!inDevelopmentMode) {
|
||||
scriptUri = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js"))
|
||||
.toString();
|
||||
styleMainUri = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css"))
|
||||
.toString();
|
||||
} else {
|
||||
scriptUri = "http://localhost:5173/src/main.tsx";
|
||||
styleMainUri = "http://localhost:5173/src/index.css";
|
||||
}
|
||||
|
||||
const listener = debugPanelWebview?.onDidReceiveMessage((data) => {
|
||||
if (data.type === messageType) {
|
||||
resolve(data);
|
||||
listener?.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
debugPanelWebview?.postMessage({ type: messageType, data });
|
||||
|
||||
setTimeout(() => {
|
||||
reject("Error communciating with Continue side panel: timed out");
|
||||
listener?.dispose();
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
|
||||
const abortedMessageIds: Set<string> = new Set();
|
||||
|
||||
export function getSidebarContent(
|
||||
context: vscode.ExtensionContext | undefined,
|
||||
panel: vscode.WebviewPanel | vscode.WebviewView,
|
||||
page: string | undefined = undefined,
|
||||
edits: FileEdit[] | undefined = undefined,
|
||||
isFullScreen: boolean = false
|
||||
): string {
|
||||
if (!isFullScreen) {
|
||||
debugPanelWebview = panel.webview;
|
||||
panel.onDidDispose(() => {
|
||||
debugPanelWebview = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
let extensionUri = getExtensionUri();
|
||||
let scriptUri: string;
|
||||
let styleMainUri: string;
|
||||
let vscMediaUrl: string = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui"))
|
||||
.toString();
|
||||
|
||||
const inDevelopmentMode =
|
||||
context?.extensionMode === vscode.ExtensionMode.Development;
|
||||
if (!inDevelopmentMode) {
|
||||
scriptUri = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.js"))
|
||||
.toString();
|
||||
styleMainUri = panel.webview
|
||||
.asWebviewUri(vscode.Uri.joinPath(extensionUri, "gui/assets/index.css"))
|
||||
.toString();
|
||||
} else {
|
||||
scriptUri = "http://localhost:5173/src/main.tsx";
|
||||
styleMainUri = "http://localhost:5173/src/index.css";
|
||||
}
|
||||
|
||||
panel.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [
|
||||
vscode.Uri.joinPath(extensionUri, "gui"),
|
||||
vscode.Uri.joinPath(extensionUri, "assets"),
|
||||
],
|
||||
enableCommandUris: true,
|
||||
portMapping: [
|
||||
{
|
||||
webviewPort: 65433,
|
||||
extensionHostPort: 65433,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const nonce = getNonce();
|
||||
|
||||
panel.webview.onDidReceiveMessage(async (data) => {
|
||||
const ide = new VsCodeIde();
|
||||
const respond = (message: any) => {
|
||||
panel.webview.postMessage({
|
||||
type: data.type,
|
||||
messageId: data.messageId,
|
||||
message: message,
|
||||
});
|
||||
panel.webview.options = {
|
||||
enableScripts: true,
|
||||
localResourceRoots: [
|
||||
vscode.Uri.joinPath(extensionUri, "gui"),
|
||||
vscode.Uri.joinPath(extensionUri, "assets"),
|
||||
],
|
||||
enableCommandUris: true,
|
||||
portMapping: [
|
||||
{
|
||||
webviewPort: 65433,
|
||||
extensionHostPort: 65433,
|
||||
},
|
||||
],
|
||||
};
|
||||
try {
|
||||
switch (data.type) {
|
||||
case "abort": {
|
||||
abortedMessageIds.add(data.messageId);
|
||||
break;
|
||||
}
|
||||
case "showFile": {
|
||||
ideProtocolClient.openFile(data.filepath);
|
||||
break;
|
||||
}
|
||||
case "openConfigJson": {
|
||||
ideProtocolClient.openFile(getConfigJsonPath());
|
||||
break;
|
||||
}
|
||||
case "readRangeInFile": {
|
||||
vscode.workspace.openTextDocument(data.filepath).then((document) => {
|
||||
let start = new vscode.Position(0, 0);
|
||||
let end = new vscode.Position(5, 0);
|
||||
let range = new vscode.Range(start, end);
|
||||
|
||||
let contents = document.getText(range);
|
||||
panel.webview.postMessage({
|
||||
type: "readRangeInFile",
|
||||
messageId: data.messageId,
|
||||
contents,
|
||||
});
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "toggleDevTools": {
|
||||
vscode.commands.executeCommand("workbench.action.toggleDevTools");
|
||||
vscode.commands.executeCommand("continue.viewLogs");
|
||||
break;
|
||||
}
|
||||
case "reloadWindow": {
|
||||
vscode.commands.executeCommand("workbench.action.reloadWindow");
|
||||
break;
|
||||
}
|
||||
case "focusEditor": {
|
||||
vscode.commands.executeCommand(
|
||||
"workbench.action.focusActiveEditorGroup"
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "toggleFullScreen": {
|
||||
vscode.commands.executeCommand("continue.toggleFullScreen");
|
||||
break;
|
||||
}
|
||||
case "withProgress": {
|
||||
// This message allows withProgress to be used in the webview
|
||||
if (data.done) {
|
||||
// Will be caught in the listener created below
|
||||
break;
|
||||
}
|
||||
let title = data.title;
|
||||
vscode.window.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Notification,
|
||||
title,
|
||||
cancellable: false,
|
||||
},
|
||||
async () => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let listener = panel.webview.onDidReceiveMessage(
|
||||
async (data) => {
|
||||
if (
|
||||
data.type === "withProgress" &&
|
||||
data.done &&
|
||||
data.title === title
|
||||
) {
|
||||
listener.dispose();
|
||||
resolve();
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
const nonce = getNonce();
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// IDE
|
||||
case "getDiff": {
|
||||
respond(await ide.getDiff());
|
||||
break;
|
||||
}
|
||||
case "getSerializedConfig": {
|
||||
respond(await ide.getSerializedConfig());
|
||||
break;
|
||||
}
|
||||
case "getTerminalContents": {
|
||||
respond(await ide.getTerminalContents());
|
||||
break;
|
||||
}
|
||||
case "listWorkspaceContents": {
|
||||
respond(await ide.listWorkspaceContents());
|
||||
break;
|
||||
}
|
||||
case "getWorkspaceDirs": {
|
||||
respond(await ide.getWorkspaceDirs());
|
||||
break;
|
||||
}
|
||||
case "listFolders": {
|
||||
respond(await ide.listFolders());
|
||||
break;
|
||||
}
|
||||
case "writeFile": {
|
||||
respond(
|
||||
await ide.writeFile(data.message.path, data.message.contents)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "showVirtualFile": {
|
||||
respond(
|
||||
await ide.showVirtualFile(data.message.name, data.message.content)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "getContinueDir": {
|
||||
respond(await ide.getContinueDir());
|
||||
break;
|
||||
}
|
||||
case "openFile": {
|
||||
respond(await ide.openFile(data.message.path));
|
||||
break;
|
||||
}
|
||||
case "runCommand": {
|
||||
respond(await ide.runCommand(data.message.command));
|
||||
break;
|
||||
}
|
||||
case "getSearchResults": {
|
||||
respond(await ide.getSearchResults(data.message.query));
|
||||
break;
|
||||
}
|
||||
case "subprocess": {
|
||||
respond(await ide.subprocess(data.message.command));
|
||||
break;
|
||||
}
|
||||
case "getFilesToEmbed": {
|
||||
let filesToEmbed = await ide.getFilesToEmbed(data.message.providerId);
|
||||
respond(filesToEmbed);
|
||||
break;
|
||||
}
|
||||
case "sendChunkForFile": {
|
||||
respond(
|
||||
await ide.sendEmbeddingForChunk(
|
||||
data.message.chunk,
|
||||
data.message.embedding,
|
||||
data.message.tags
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "retrieveChunks": {
|
||||
respond(
|
||||
await ide.retrieveChunks(
|
||||
data.message.text,
|
||||
data.message.n,
|
||||
data.message.directory
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
// History
|
||||
case "history": {
|
||||
respond(historyManager.list());
|
||||
break;
|
||||
}
|
||||
case "saveSession": {
|
||||
historyManager.save(data.message);
|
||||
respond({});
|
||||
break;
|
||||
}
|
||||
case "deleteSession": {
|
||||
historyManager.delete(data.message);
|
||||
respond({});
|
||||
break;
|
||||
}
|
||||
case "loadSession": {
|
||||
respond(historyManager.load(data.message));
|
||||
break;
|
||||
}
|
||||
case "saveFile": {
|
||||
respond(await ide.saveFile(data.message.filepath));
|
||||
break;
|
||||
}
|
||||
case "readFile": {
|
||||
respond(await ide.readFile(data.message.filepath));
|
||||
break;
|
||||
}
|
||||
case "showDiff": {
|
||||
respond(
|
||||
await ide.showDiff(
|
||||
data.message.filepath,
|
||||
data.message.newContents,
|
||||
data.message.stepIndex
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "diffLine": {
|
||||
const {
|
||||
diffLine,
|
||||
filepath,
|
||||
startLine,
|
||||
endLine,
|
||||
}: {
|
||||
diffLine: DiffLine;
|
||||
filepath: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
} = data.message;
|
||||
|
||||
respond(
|
||||
await ide.verticalDiffUpdate(filepath, startLine, endLine, diffLine)
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "getProblems": {
|
||||
respond(await ide.getProblems(data.message.filepath));
|
||||
break;
|
||||
}
|
||||
case "getBranch": {
|
||||
const { dir } = data.message;
|
||||
respond(await ide.getBranch(dir));
|
||||
break;
|
||||
}
|
||||
case "getOpenFiles": {
|
||||
respond(await ide.getOpenFiles());
|
||||
break;
|
||||
}
|
||||
case "getPinnedFiles": {
|
||||
respond(await ide.getPinnedFiles());
|
||||
break;
|
||||
}
|
||||
case "showLines": {
|
||||
const { filepath, startLine, endLine } = data.message;
|
||||
respond(await ide.showLines(filepath, startLine, endLine));
|
||||
break;
|
||||
}
|
||||
// Other
|
||||
case "errorPopup": {
|
||||
vscode.window
|
||||
.showErrorMessage(data.message, "Show Logs")
|
||||
.then((selection) => {
|
||||
if (selection === "Show Logs") {
|
||||
vscode.commands.executeCommand(
|
||||
"workbench.action.toggleDevTools"
|
||||
);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "logDevData": {
|
||||
ideProtocolClient.logDevData(data.tableName, data.data);
|
||||
break;
|
||||
}
|
||||
case "addModel": {
|
||||
const model = data.model;
|
||||
const config = readFileSync(getConfigJsonPath(), "utf8");
|
||||
const configJson = JSON.parse(config);
|
||||
configJson.models.push(model);
|
||||
const newConfigString = JSON.stringify(
|
||||
configJson,
|
||||
(key, value) => {
|
||||
return value === null ? undefined : value;
|
||||
},
|
||||
2
|
||||
);
|
||||
writeFileSync(getConfigJsonPath(), newConfigString);
|
||||
configHandler.reloadConfig();
|
||||
ideProtocolClient.openFile(getConfigJsonPath());
|
||||
|
||||
// Find the range where it was added and highlight
|
||||
let lines = newConfigString.split("\n");
|
||||
let startLine;
|
||||
let endLine;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
let line = lines[i];
|
||||
|
||||
if (!startLine) {
|
||||
if (line.trim() === `"title": "${data.model.title}",`) {
|
||||
startLine = i - 1;
|
||||
}
|
||||
} else {
|
||||
if (line.startsWith(" }")) {
|
||||
endLine = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startLine && endLine) {
|
||||
ideProtocolClient.highlightCode(
|
||||
{
|
||||
filepath: getConfigJsonPath(),
|
||||
range: {
|
||||
start: { character: 0, line: startLine },
|
||||
end: { character: 0, line: endLine },
|
||||
},
|
||||
},
|
||||
"#fff1"
|
||||
);
|
||||
}
|
||||
vscode.window.showInformationMessage(
|
||||
"🎉 Your model has been successfully added to config.json. You can use this file to further edit its configuration."
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "deleteModel": {
|
||||
const configJson = editConfigJson((config) => {
|
||||
config.models = config.models.filter(
|
||||
(m: any) => m.title !== data.title
|
||||
);
|
||||
return config;
|
||||
});
|
||||
configHandler.reloadConfig();
|
||||
break;
|
||||
}
|
||||
case "addOpenAIKey": {
|
||||
const configJson = editConfigJson((config) => {
|
||||
config.models = config.models.map((m: ModelDescription) => {
|
||||
if (m.provider === "free-trial") {
|
||||
m.apiKey = data.key;
|
||||
m.provider = "openai";
|
||||
}
|
||||
return m;
|
||||
});
|
||||
return config;
|
||||
});
|
||||
configHandler.reloadConfig();
|
||||
break;
|
||||
}
|
||||
case "llmStreamComplete": {
|
||||
const model = await llmFromTitle(data.message.title);
|
||||
const gen = model.streamComplete(
|
||||
data.message.prompt,
|
||||
data.message.completionOptions
|
||||
);
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (abortedMessageIds.has(data.messageId)) {
|
||||
abortedMessageIds.delete(data.messageId);
|
||||
next = await gen.return({ completion: "", prompt: "" });
|
||||
break;
|
||||
}
|
||||
respond({ content: next.value });
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
respond({ done: true, data: next.value });
|
||||
break;
|
||||
}
|
||||
case "llmStreamChat": {
|
||||
const model = await llmFromTitle(data.message.title);
|
||||
const gen = model.streamChat(
|
||||
data.message.messages,
|
||||
data.message.completionOptions
|
||||
);
|
||||
let next = await gen.next();
|
||||
while (!next.done) {
|
||||
if (abortedMessageIds.has(data.messageId)) {
|
||||
abortedMessageIds.delete(data.messageId);
|
||||
next = await gen.return({ completion: "", prompt: "" });
|
||||
break;
|
||||
}
|
||||
respond({ content: next.value.content });
|
||||
next = await gen.next();
|
||||
}
|
||||
|
||||
respond({ done: true, data: next.value });
|
||||
break;
|
||||
}
|
||||
case "llmComplete": {
|
||||
const model = await llmFromTitle(data.message.title);
|
||||
const completion = await model.complete(
|
||||
data.message.prompt,
|
||||
data.message.completionOptions
|
||||
);
|
||||
respond({ content: completion });
|
||||
break;
|
||||
}
|
||||
case "runNodeJsSlashCommand": {
|
||||
const {
|
||||
input,
|
||||
history,
|
||||
modelTitle,
|
||||
slashCommandName,
|
||||
contextItems,
|
||||
params,
|
||||
historyIndex,
|
||||
} = data.message;
|
||||
|
||||
const config = await configHandler.loadConfig();
|
||||
const llm = await llmFromTitle(modelTitle);
|
||||
const slashCommand = config.slashCommands?.find(
|
||||
(sc) => sc.name === slashCommandName
|
||||
);
|
||||
if (!slashCommand) {
|
||||
throw new Error(`Unknown slash command ${slashCommandName}`);
|
||||
}
|
||||
|
||||
for await (const update of slashCommand.run({
|
||||
input,
|
||||
history,
|
||||
llm,
|
||||
contextItems,
|
||||
params,
|
||||
ide,
|
||||
addContextItem: (item) => {
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "addContextItem",
|
||||
message: { item, historyIndex },
|
||||
});
|
||||
},
|
||||
})) {
|
||||
if (abortedMessageIds.has(data.messageId)) {
|
||||
abortedMessageIds.delete(data.messageId);
|
||||
break;
|
||||
}
|
||||
respond({ content: update });
|
||||
}
|
||||
respond({ done: true });
|
||||
break;
|
||||
}
|
||||
case "loadSubmenuItems": {
|
||||
const { title } = data.message;
|
||||
const config = await configHandler.loadConfig();
|
||||
const provider = config.contextProviders?.find(
|
||||
(p) => p.description.title === title
|
||||
);
|
||||
if (!provider) {
|
||||
vscode.window.showErrorMessage(
|
||||
`Unknown provider ${title}. Existing providers: ${config.contextProviders
|
||||
?.map((p) => p.description.title)
|
||||
.join(", ")}`
|
||||
);
|
||||
respond({ items: [] });
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const items = await provider.loadSubmenuItems({ ide });
|
||||
respond({ items });
|
||||
} catch (e) {
|
||||
vscode.window.showErrorMessage(
|
||||
`Error loading submenu items from ${title}: ${e}`
|
||||
);
|
||||
respond({ items: [] });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "getContextItems": {
|
||||
const { name, query, fullInput, selectedCode } = data.message;
|
||||
const config = await configHandler.loadConfig();
|
||||
const llm = await llmFromTitle();
|
||||
const provider = config.contextProviders?.find(
|
||||
(p) => p.description.title === name
|
||||
);
|
||||
if (!provider) {
|
||||
vscode.window.showErrorMessage(
|
||||
`Unknown provider ${name}. Existing providers: ${config.contextProviders
|
||||
?.map((p) => p.description.title)
|
||||
.join(", ")}`
|
||||
);
|
||||
respond({ items: [] });
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
const id: ContextItemId = {
|
||||
providerTitle: provider.description.title,
|
||||
itemId: uuidv4(),
|
||||
};
|
||||
const items = await provider.getContextItems(query, {
|
||||
llm,
|
||||
embeddingsProvider: config.embeddingsProvider,
|
||||
fullInput,
|
||||
ide,
|
||||
selectedCode,
|
||||
});
|
||||
respond({ items: items.map((item) => ({ ...item, id })) });
|
||||
} catch (e) {
|
||||
vscode.window.showErrorMessage(
|
||||
`Error getting context items from ${name}: ${e}`
|
||||
);
|
||||
respond({ items: [] });
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "addDocs": {
|
||||
const { url, title } = data;
|
||||
const embeddingsProvider = new TransformersJsEmbeddingsProvider();
|
||||
vscode.window.withProgress(
|
||||
{
|
||||
location: vscode.ProgressLocation.Notification,
|
||||
title: `Indexing ${title}`,
|
||||
cancellable: false,
|
||||
},
|
||||
async (progress) => {
|
||||
for await (const update of indexDocs(
|
||||
title,
|
||||
new URL(url),
|
||||
embeddingsProvider
|
||||
)) {
|
||||
progress.report({
|
||||
increment: update.progress,
|
||||
message: update.desc,
|
||||
});
|
||||
}
|
||||
|
||||
vscode.window.showInformationMessage(
|
||||
`🎉 Successfully indexed ${title}`
|
||||
);
|
||||
|
||||
debugPanelWebview?.postMessage({
|
||||
type: "refreshSubmenuItems",
|
||||
});
|
||||
}
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "applyToCurrentFile": {
|
||||
// Select the entire current file
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) {
|
||||
vscode.window.showErrorMessage(
|
||||
"No active editor to apply edits to"
|
||||
);
|
||||
break;
|
||||
}
|
||||
const document = editor.document;
|
||||
|
||||
if (document.getText().trim() === "") {
|
||||
editor.edit((editBuilder) => {
|
||||
editBuilder.insert(document.positionAt(0), data.text);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const start = new vscode.Position(0, 0);
|
||||
const end = new vscode.Position(
|
||||
document.lineCount - 1,
|
||||
document.lineAt(document.lineCount - 1).text.length
|
||||
);
|
||||
editor.selection = new vscode.Selection(start, end);
|
||||
|
||||
streamEdit(
|
||||
`The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "showTutorial": {
|
||||
showTutorial();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
let message = `Continue error: ${e.message}`;
|
||||
if (e.cause) {
|
||||
if (e.cause.name === "ConnectTimeoutError") {
|
||||
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`;
|
||||
} else if (e.cause.code === "ECONNREFUSED") {
|
||||
message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`;
|
||||
} else {
|
||||
message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`;
|
||||
}
|
||||
const currentTheme = getTheme();
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
if (e.affectsConfiguration("workbench.colorTheme")) {
|
||||
// Send new theme to GUI to update embedded Monaco themes
|
||||
this.webviewProtocol?.request("setTheme", { theme: getTheme() });
|
||||
}
|
||||
});
|
||||
|
||||
vscode.window
|
||||
.showErrorMessage(message, "Show Logs", "Troubleshooting")
|
||||
.then((selection) => {
|
||||
if (selection === "Show Logs") {
|
||||
vscode.commands.executeCommand("workbench.action.toggleDevTools");
|
||||
} else if (selection === "Troubleshooting") {
|
||||
vscode.env.openExternal(
|
||||
vscode.Uri.parse("https://continue.dev/docs/troubleshooting")
|
||||
);
|
||||
}
|
||||
});
|
||||
respond({ done: true, data: {} });
|
||||
}
|
||||
});
|
||||
this.webviewProtocol.webview = panel.webview;
|
||||
|
||||
const currentTheme = getTheme();
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
if (e.affectsConfiguration("workbench.colorTheme")) {
|
||||
// Send new theme to GUI to update embedded Monaco themes
|
||||
debugPanelWebview?.postMessage({ type: "setTheme", theme: getTheme() });
|
||||
}
|
||||
});
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
|
|
@ -729,7 +140,7 @@ export function getSidebarContent(
|
|||
<script type="module" nonce="${nonce}" src="${scriptUri}"></script>
|
||||
|
||||
<script>localStorage.setItem("ide", "vscode")</script>
|
||||
<script>window.windowId = "${windowId}"</script>
|
||||
<script>window.windowId = "${this.windowId}"</script>
|
||||
<script>window.vscMachineId = "${getUniqueId()}"</script>
|
||||
<script>window.vscMediaUrl = "${vscMediaUrl}"</script>
|
||||
<script>window.ide = "vscode"</script>
|
||||
|
|
@ -750,18 +161,5 @@ export function getSidebarContent(
|
|||
${page ? `<script>window.location.pathname = "${page}"</script>` : ""}
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export class ContinueGUIWebviewViewProvider
|
||||
implements vscode.WebviewViewProvider
|
||||
{
|
||||
public static readonly viewType = "continue.continueGUIView";
|
||||
|
||||
resolveWebviewView(
|
||||
webviewView: vscode.WebviewView,
|
||||
_context: vscode.WebviewViewResolveContext,
|
||||
_token: vscode.CancellationToken
|
||||
): void | Thenable<void> {
|
||||
webviewView.webview.html = getSidebarContent(extensionContext, webviewView);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,11 +3,9 @@ import * as fs from "fs";
|
|||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { extensionContext } from "../activation/activate";
|
||||
import { debugPanelWebview } from "../debugPanel";
|
||||
import { getMetaKeyLabel, getPlatform } from "../util/util";
|
||||
import { uriFromFilePath } from "../util/vscode";
|
||||
import { verticalPerLineDiffManager } from "./verticalPerLine/manager";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
interface DiffInfo {
|
||||
originalFilepath: string;
|
||||
|
|
@ -32,7 +30,7 @@ export const DIFF_DIRECTORY = path
|
|||
.join(os.homedir(), ".continue", "diffs")
|
||||
.replace(/^C:/, "c:");
|
||||
|
||||
class DiffManager {
|
||||
export class DiffManager {
|
||||
// Create a temporary file in the global .continue directory which displays the updated version
|
||||
// Doing this because virtual files are read-only
|
||||
private diffs: Map<string, DiffInfo> = new Map();
|
||||
|
|
@ -50,7 +48,9 @@ class DiffManager {
|
|||
}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
webviewProtocol: VsCodeWebviewProtocol | undefined;
|
||||
|
||||
constructor(private readonly extensionContext: vscode.ExtensionContext) {
|
||||
this.setupDirectory();
|
||||
|
||||
// Listen for file closes, and if it's a diff file, clean up
|
||||
|
|
@ -115,7 +115,7 @@ class DiffManager {
|
|||
.update("codeLens", true, vscode.ConfigurationTarget.Global);
|
||||
|
||||
if (
|
||||
extensionContext?.globalState.get<boolean>(
|
||||
this.extensionContext.globalState.get<boolean>(
|
||||
"continue.showDiffInfoMessage"
|
||||
) !== false
|
||||
) {
|
||||
|
|
@ -128,7 +128,7 @@ class DiffManager {
|
|||
.then((selection) => {
|
||||
if (selection === "Don't show again") {
|
||||
// Get the global state
|
||||
extensionContext?.globalState.update(
|
||||
this.extensionContext.globalState.update(
|
||||
"continue.showDiffInfoMessage",
|
||||
false
|
||||
);
|
||||
|
|
@ -289,7 +289,7 @@ class DiffManager {
|
|||
}
|
||||
|
||||
// Stop the step at step_index in case it is still streaming
|
||||
debugPanelWebview?.postMessage({ type: "setInactive" });
|
||||
this.webviewProtocol?.request("setInactive", undefined);
|
||||
|
||||
vscode.workspace.textDocuments
|
||||
.find((doc) => doc.uri.fsPath === newFilepath)
|
||||
|
|
@ -302,8 +302,6 @@ class DiffManager {
|
|||
}
|
||||
}
|
||||
|
||||
export const diffManager = new DiffManager();
|
||||
|
||||
async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
|
||||
const devDataDir = devDataPath();
|
||||
const suggestionsPath = path.join(devDataDir, "suggestions.json");
|
||||
|
|
@ -333,19 +331,3 @@ async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
|
|||
JSON.stringify(suggestions, null, 4)
|
||||
);
|
||||
}
|
||||
|
||||
export async function acceptDiffCommand(newFilepath?: string | vscode.Uri) {
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
verticalPerLineDiffManager.clearForFilepath(newFilepath, true);
|
||||
await diffManager.acceptDiff(newFilepath);
|
||||
}
|
||||
|
||||
export async function rejectDiffCommand(newFilepath?: string | vscode.Uri) {
|
||||
if (newFilepath instanceof vscode.Uri) {
|
||||
newFilepath = newFilepath.fsPath;
|
||||
}
|
||||
verticalPerLineDiffManager.clearForFilepath(newFilepath, false);
|
||||
await diffManager.rejectDiff(newFilepath);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,10 +7,7 @@ import {
|
|||
indexDecorationType,
|
||||
redDecorationType,
|
||||
} from "./decorations";
|
||||
import {
|
||||
editorToVerticalDiffCodeLens,
|
||||
verticalPerLineDiffManager,
|
||||
} from "./manager";
|
||||
import { VerticalDiffCodeLens } from "./manager";
|
||||
|
||||
export class VerticalPerLineDiffHandler {
|
||||
private editor: vscode.TextEditor;
|
||||
|
|
@ -33,6 +30,14 @@ export class VerticalPerLineDiffHandler {
|
|||
startLine: number,
|
||||
endLine: number,
|
||||
editor: vscode.TextEditor,
|
||||
private readonly editorToVerticalDiffCodeLens: Map<
|
||||
string,
|
||||
VerticalDiffCodeLens[]
|
||||
>,
|
||||
private readonly clearForFilepath: (
|
||||
filepath: string | undefined,
|
||||
accept: boolean
|
||||
) => void,
|
||||
input?: string
|
||||
) {
|
||||
this.currentLineIndex = startLine;
|
||||
|
|
@ -71,13 +76,13 @@ export class VerticalPerLineDiffHandler {
|
|||
}
|
||||
|
||||
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
|
||||
const blocks = editorToVerticalDiffCodeLens.get(this.filepath) || [];
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(this.filepath) || [];
|
||||
blocks.push({
|
||||
start: this.currentLineIndex - this.insertedInCurrentBlock,
|
||||
numRed: this.deletionBuffer.length,
|
||||
numGreen: this.insertedInCurrentBlock,
|
||||
});
|
||||
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
|
||||
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
|
||||
}
|
||||
|
||||
if (this.deletionBuffer.length === 0) {
|
||||
|
|
@ -188,7 +193,7 @@ export class VerticalPerLineDiffHandler {
|
|||
this.greenDecorationManager.clear();
|
||||
this.clearIndexLineDecorations();
|
||||
|
||||
editorToVerticalDiffCodeLens.delete(this.filepath);
|
||||
this.editorToVerticalDiffCodeLens.delete(this.filepath);
|
||||
|
||||
this.editor.edit((editBuilder) => {
|
||||
for (const range of rangesToDelete) {
|
||||
|
|
@ -251,7 +256,7 @@ export class VerticalPerLineDiffHandler {
|
|||
// }
|
||||
// });
|
||||
} catch (e) {
|
||||
verticalPerLineDiffManager.clearForFilepath(this.filepath, false);
|
||||
this.clearForFilepath(this.filepath, false);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
|
@ -288,7 +293,7 @@ export class VerticalPerLineDiffHandler {
|
|||
|
||||
// Shift the codelens objects
|
||||
const blocks =
|
||||
editorToVerticalDiffCodeLens
|
||||
this.editorToVerticalDiffCodeLens
|
||||
.get(this.filepath)
|
||||
?.filter((x) => x.start !== startLine)
|
||||
.map((x) => {
|
||||
|
|
@ -297,6 +302,6 @@ export class VerticalPerLineDiffHandler {
|
|||
}
|
||||
return x;
|
||||
}) || [];
|
||||
editorToVerticalDiffCodeLens.set(this.filepath, blocks);
|
||||
this.editorToVerticalDiffCodeLens.set(this.filepath, blocks);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,23 @@
|
|||
import { streamDiffLines } from "core/commands/slash/verticalEdit";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { getMarkdownLanguageTagForFile } from "core/util";
|
||||
import { streamDiffLines } from "core/util/verticalEdit";
|
||||
import * as vscode from "vscode";
|
||||
import { llmFromTitle } from "../../loadConfig";
|
||||
import { VerticalPerLineDiffHandler } from "./handler";
|
||||
|
||||
class VerticalPerLineDiffManager {
|
||||
export interface VerticalDiffCodeLens {
|
||||
start: number;
|
||||
numRed: number;
|
||||
numGreen: number;
|
||||
}
|
||||
|
||||
export class VerticalPerLineDiffManager {
|
||||
private filepathToEditorMap: Map<string, VerticalPerLineDiffHandler> =
|
||||
new Map();
|
||||
|
||||
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> = new Map();
|
||||
|
||||
constructor(private readonly configHandler: ConfigHandler) {}
|
||||
|
||||
createVerticalPerLineDiffHandler(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
|
|
@ -24,6 +34,8 @@ class VerticalPerLineDiffManager {
|
|||
startLine,
|
||||
endLine,
|
||||
editor,
|
||||
this.editorToVerticalDiffCodeLens,
|
||||
this.clearForFilepath,
|
||||
input
|
||||
);
|
||||
this.filepathToEditorMap.set(filepath, handler);
|
||||
|
|
@ -46,7 +58,9 @@ class VerticalPerLineDiffManager {
|
|||
const handler = new VerticalPerLineDiffHandler(
|
||||
startLine,
|
||||
endLine,
|
||||
editor
|
||||
editor,
|
||||
this.editorToVerticalDiffCodeLens,
|
||||
this.clearForFilepath
|
||||
);
|
||||
this.filepathToEditorMap.set(filepath, handler);
|
||||
return handler;
|
||||
|
|
@ -75,78 +89,113 @@ class VerticalPerLineDiffManager {
|
|||
this.filepathToEditorMap.delete(filepath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const verticalPerLineDiffManager = new VerticalPerLineDiffManager();
|
||||
acceptRejectVerticalDiffBlock(
|
||||
accept: boolean,
|
||||
filepath?: string,
|
||||
index?: number
|
||||
) {
|
||||
if (!filepath) {
|
||||
const activeEditor = vscode.window.activeTextEditor;
|
||||
if (!activeEditor) {
|
||||
return;
|
||||
}
|
||||
filepath = activeEditor.document.uri.fsPath;
|
||||
}
|
||||
|
||||
export async function streamEdit(input: string) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) {
|
||||
return;
|
||||
if (typeof index === "undefined") {
|
||||
index = 0;
|
||||
}
|
||||
|
||||
let blocks = this.editorToVerticalDiffCodeLens.get(filepath);
|
||||
const block = blocks?.[index];
|
||||
if (!blocks || !block) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handler = this.getHandlerForFile(filepath);
|
||||
if (!handler) {
|
||||
return;
|
||||
}
|
||||
|
||||
// CodeLens object removed from editorToVerticalDiffCodeLens here
|
||||
handler.acceptRejectBlock(
|
||||
accept,
|
||||
block.start,
|
||||
block.numGreen,
|
||||
block.numRed
|
||||
);
|
||||
}
|
||||
|
||||
const filepath = editor.document.uri.fsPath;
|
||||
const startLine = editor.selection.start.line;
|
||||
const endLine = editor.selection.end.line;
|
||||
async streamEdit(input: string) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingHandler =
|
||||
verticalPerLineDiffManager.getHandlerForFile(filepath);
|
||||
existingHandler?.clear(false);
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 200);
|
||||
});
|
||||
const diffHandler =
|
||||
verticalPerLineDiffManager.createVerticalPerLineDiffHandler(
|
||||
const filepath = editor.document.uri.fsPath;
|
||||
const startLine = editor.selection.start.line;
|
||||
const endLine = editor.selection.end.line;
|
||||
|
||||
const existingHandler = this.getHandlerForFile(filepath);
|
||||
existingHandler?.clear(false);
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 200);
|
||||
});
|
||||
const diffHandler = this.createVerticalPerLineDiffHandler(
|
||||
filepath,
|
||||
existingHandler?.range.start.line ?? startLine,
|
||||
existingHandler?.range.end.line ?? endLine,
|
||||
input
|
||||
);
|
||||
if (!diffHandler) {
|
||||
return;
|
||||
}
|
||||
if (!diffHandler) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedRange =
|
||||
existingHandler?.range ??
|
||||
new vscode.Range(
|
||||
editor.selection.start.with(undefined, 0),
|
||||
editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER)
|
||||
const selectedRange =
|
||||
existingHandler?.range ??
|
||||
new vscode.Range(
|
||||
editor.selection.start.with(undefined, 0),
|
||||
editor.selection.end.with(undefined, Number.MAX_SAFE_INTEGER)
|
||||
);
|
||||
const rangeContent = editor.document.getText(selectedRange);
|
||||
const llm = await this.configHandler.llmFromTitle();
|
||||
|
||||
// Unselect the range
|
||||
editor.selection = new vscode.Selection(
|
||||
editor.selection.active,
|
||||
editor.selection.active
|
||||
);
|
||||
const rangeContent = editor.document.getText(selectedRange);
|
||||
const llm = await llmFromTitle();
|
||||
|
||||
// Unselect the range
|
||||
editor.selection = new vscode.Selection(
|
||||
editor.selection.active,
|
||||
editor.selection.active
|
||||
);
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.streamingDiff",
|
||||
true
|
||||
);
|
||||
|
||||
vscode.commands.executeCommand("setContext", "continue.streamingDiff", true);
|
||||
|
||||
if (existingHandler?.input) {
|
||||
if (existingHandler.input.startsWith("Original request: ")) {
|
||||
existingHandler.input = existingHandler.input.substring(
|
||||
"Original request: ".length
|
||||
if (existingHandler?.input) {
|
||||
if (existingHandler.input.startsWith("Original request: ")) {
|
||||
existingHandler.input = existingHandler.input.substring(
|
||||
"Original request: ".length
|
||||
);
|
||||
}
|
||||
input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`;
|
||||
}
|
||||
try {
|
||||
await diffHandler.run(
|
||||
streamDiffLines(
|
||||
rangeContent,
|
||||
llm,
|
||||
input,
|
||||
getMarkdownLanguageTagForFile(filepath)
|
||||
)
|
||||
);
|
||||
} finally {
|
||||
vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"continue.streamingDiff",
|
||||
false
|
||||
);
|
||||
}
|
||||
input = `Original request: ${existingHandler.input}\nUpdated request: ${input}`;
|
||||
}
|
||||
|
||||
await diffHandler.run(
|
||||
streamDiffLines(
|
||||
rangeContent,
|
||||
llm,
|
||||
input,
|
||||
getMarkdownLanguageTagForFile(filepath)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export interface VerticalDiffCodeLens {
|
||||
start: number;
|
||||
numRed: number;
|
||||
numGreen: number;
|
||||
}
|
||||
|
||||
export const editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]> =
|
||||
new Map();
|
||||
|
|
|
|||
0
extensions/vscode/src/extension/autocomplete.ts
Normal file
0
extensions/vscode/src/extension/autocomplete.ts
Normal file
0
extensions/vscode/src/extension/indexing.ts
Normal file
0
extensions/vscode/src/extension/indexing.ts
Normal file
214
extensions/vscode/src/extension/vscodeExtension.ts
Normal file
214
extensions/vscode/src/extension/vscodeExtension.ts
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
import { ConfigHandler } from "core/config/handler";
|
||||
import { CodebaseIndexer } from "core/indexing/indexCodebase";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import { registerAllCommands } from "../commands";
|
||||
import { ContinueGUIWebviewViewProvider } from "../debugPanel";
|
||||
import { DiffManager } from "../diff/horizontal";
|
||||
import { VerticalPerLineDiffManager } from "../diff/verticalPerLine/manager";
|
||||
import { VsCodeIde } from "../ideProtocol";
|
||||
import { registerAllCodeLensProviders } from "../lang-server/codeLens";
|
||||
import {
|
||||
ContinueCompletionProvider,
|
||||
setupStatusBar,
|
||||
} from "../lang-server/completionProvider";
|
||||
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { RemoteConfigSync } from "../util/remoteConfig";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
export class VsCodeExtension {
|
||||
private configHandler: ConfigHandler;
|
||||
private extensionContext: vscode.ExtensionContext;
|
||||
private ide: VsCodeIde;
|
||||
private tabAutocompleteModel: TabAutocompleteModel;
|
||||
private sidebar: ContinueGUIWebviewViewProvider;
|
||||
private windowId: string;
|
||||
private indexer: CodebaseIndexer;
|
||||
private diffManager: DiffManager;
|
||||
private verticalDiffManager: VerticalPerLineDiffManager;
|
||||
private webviewProtocol: VsCodeWebviewProtocol;
|
||||
|
||||
constructor(context: vscode.ExtensionContext) {
|
||||
this.diffManager = new DiffManager(context);
|
||||
this.ide = new VsCodeIde(this.diffManager);
|
||||
const remoteUrl = vscode.workspace
|
||||
.getConfiguration("continue")
|
||||
.get<string | undefined>("remoteConfigServerUrl", undefined);
|
||||
|
||||
// Config Handler with output channel
|
||||
const outputChannel = vscode.window.createOutputChannel(
|
||||
"Continue - LLM Prompt/Completion"
|
||||
);
|
||||
this.configHandler = new ConfigHandler(
|
||||
this.ide,
|
||||
remoteUrl === undefined || remoteUrl === ""
|
||||
? undefined
|
||||
: new URL(remoteUrl),
|
||||
async (log: string) => {
|
||||
outputChannel.appendLine(
|
||||
"=========================================================================="
|
||||
);
|
||||
outputChannel.appendLine(
|
||||
"=========================================================================="
|
||||
);
|
||||
outputChannel.append(log);
|
||||
}
|
||||
);
|
||||
|
||||
this.configHandler.reloadConfig();
|
||||
this.verticalDiffManager = new VerticalPerLineDiffManager(
|
||||
this.configHandler
|
||||
);
|
||||
this.extensionContext = context;
|
||||
this.tabAutocompleteModel = new TabAutocompleteModel(this.configHandler);
|
||||
this.windowId = uuidv4();
|
||||
this.sidebar = new ContinueGUIWebviewViewProvider(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.windowId,
|
||||
this.extensionContext,
|
||||
this.verticalDiffManager
|
||||
);
|
||||
try {
|
||||
const configSync = new RemoteConfigSync(
|
||||
this.configHandler.reloadConfig.bind(this.configHandler)
|
||||
);
|
||||
configSync.setup();
|
||||
} catch (e) {
|
||||
console.warn(`Failed to sync remote config: ${e}`);
|
||||
}
|
||||
|
||||
// Sidebar
|
||||
context.subscriptions.push(
|
||||
vscode.window.registerWebviewViewProvider(
|
||||
"continue.continueGUIView",
|
||||
this.sidebar,
|
||||
{
|
||||
webviewOptions: { retainContextWhenHidden: true },
|
||||
}
|
||||
)
|
||||
);
|
||||
this.webviewProtocol = this.sidebar.webviewProtocol;
|
||||
|
||||
this.diffManager.webviewProtocol = this.webviewProtocol;
|
||||
this.indexer = new CodebaseIndexer(this.configHandler, this.ide);
|
||||
|
||||
// CodeLens
|
||||
registerAllCodeLensProviders(
|
||||
context,
|
||||
this.diffManager,
|
||||
this.verticalDiffManager.editorToVerticalDiffCodeLens
|
||||
);
|
||||
|
||||
// Tab autocomplete
|
||||
const config = vscode.workspace.getConfiguration("continue");
|
||||
const enabled = config.get<boolean>("enableTabAutocomplete");
|
||||
|
||||
// Register inline completion provider (odd versions are pre-release)
|
||||
if (
|
||||
parseInt(context.extension.packageJSON.version.split(".")[1]) % 2 !==
|
||||
0
|
||||
) {
|
||||
setupStatusBar(enabled);
|
||||
context.subscriptions.push(
|
||||
vscode.languages.registerInlineCompletionItemProvider(
|
||||
[{ pattern: "**" }],
|
||||
new ContinueCompletionProvider(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.tabAutocompleteModel
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Commands
|
||||
registerAllCommands(
|
||||
context,
|
||||
this.ide,
|
||||
context,
|
||||
this.sidebar,
|
||||
this.configHandler,
|
||||
this.diffManager,
|
||||
this.verticalDiffManager
|
||||
);
|
||||
|
||||
// Indexing
|
||||
this.ide.getWorkspaceDirs().then((dirs) => this.refreshCodebaseIndex(dirs));
|
||||
|
||||
// Listen for file saving
|
||||
vscode.workspace.onDidSaveTextDocument((event) => {
|
||||
const filepath = event.uri.fsPath;
|
||||
|
||||
if (
|
||||
filepath.endsWith(".continue/config.json") ||
|
||||
filepath.endsWith(".continue\\config.json") ||
|
||||
filepath.endsWith(".continue/config.ts") ||
|
||||
filepath.endsWith(".continue\\config.ts") ||
|
||||
filepath.endsWith(".continuerc.json")
|
||||
) {
|
||||
this.configHandler.reloadConfig();
|
||||
this.tabAutocompleteModel.clearLlm();
|
||||
} else if (
|
||||
filepath.endsWith(".continueignore") ||
|
||||
filepath.endsWith(".gitignore")
|
||||
) {
|
||||
// Update embeddings! (TODO)
|
||||
}
|
||||
});
|
||||
|
||||
// Refresh index when branch is changed
|
||||
this.ide.getWorkspaceDirs().then((dirs) =>
|
||||
dirs.forEach(async (dir) => {
|
||||
const repo = await this.ide.getRepo(vscode.Uri.file(dir));
|
||||
if (repo) {
|
||||
repo.state.onDidChange(() => {
|
||||
// args passed to this callback are always undefined, so keep track of previous branch
|
||||
const currentBranch = repo?.state?.HEAD?.name;
|
||||
if (currentBranch) {
|
||||
if (this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]) {
|
||||
if (
|
||||
currentBranch !== this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir]
|
||||
) {
|
||||
// Trigger refresh of index only in this directory
|
||||
this.refreshCodebaseIndex([dir]);
|
||||
}
|
||||
}
|
||||
|
||||
this.PREVIOUS_BRANCH_FOR_WORKSPACE_DIR[dir] = currentBranch;
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Register a content provider for the readonly virtual documents
|
||||
const documentContentProvider = new (class
|
||||
implements vscode.TextDocumentContentProvider
|
||||
{
|
||||
// emitter and its event
|
||||
onDidChangeEmitter = new vscode.EventEmitter<vscode.Uri>();
|
||||
onDidChange = this.onDidChangeEmitter.event;
|
||||
|
||||
provideTextDocumentContent(uri: vscode.Uri): string {
|
||||
return uri.query;
|
||||
}
|
||||
})();
|
||||
context.subscriptions.push(
|
||||
vscode.workspace.registerTextDocumentContentProvider(
|
||||
VsCodeExtension.continueVirtualDocumentScheme,
|
||||
documentContentProvider
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
static continueVirtualDocumentScheme = "continue";
|
||||
|
||||
private PREVIOUS_BRANCH_FOR_WORKSPACE_DIR: { [dir: string]: string } = {};
|
||||
|
||||
private async refreshCodebaseIndex(dirs: string[]) {
|
||||
for await (const update of this.indexer.refresh(dirs)) {
|
||||
this.webviewProtocol.request("indexProgress", update);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -2,48 +2,105 @@ import { exec } from "child_process";
|
|||
import { getContinueGlobalPath } from "core/util/paths";
|
||||
import * as path from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { ideProtocolClient } from "./activation/activate";
|
||||
|
||||
import * as child_process from "child_process";
|
||||
import { Chunk, DiffLine, IDE, Problem } from "core";
|
||||
import {
|
||||
BrowserSerializedContinueConfig,
|
||||
finalToBrowserConfig,
|
||||
} from "core/config/load";
|
||||
import { LanceDbIndex } from "core/indexing/LanceDbIndex";
|
||||
import { IndexTag } from "core/indexing/types";
|
||||
import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
|
||||
import { configHandler } from "./loadConfig";
|
||||
import { ContinueRcJson, IDE, IdeInfo, Problem, Range } from "core";
|
||||
import { DiffManager } from "./diff/horizontal";
|
||||
import { VsCodeIdeUtils } from "./util/ideUtils";
|
||||
import { traverseDirectory } from "./util/traverseDirectory";
|
||||
import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
|
||||
|
||||
class VsCodeIde implements IDE {
|
||||
async getSerializedConfig(): Promise<BrowserSerializedContinueConfig> {
|
||||
const config = await configHandler.loadConfig();
|
||||
return finalToBrowserConfig(config);
|
||||
ideUtils: VsCodeIdeUtils;
|
||||
|
||||
constructor(private readonly diffManager: DiffManager) {
|
||||
this.ideUtils = new VsCodeIdeUtils();
|
||||
}
|
||||
getIdeInfo(): Promise<IdeInfo> {
|
||||
return Promise.resolve({
|
||||
ideType: "vscode",
|
||||
name: vscode.env.appName,
|
||||
version: vscode.version,
|
||||
remoteName: vscode.env.remoteName || "local",
|
||||
});
|
||||
}
|
||||
readRangeInFile(filepath: string, range: Range): Promise<string> {
|
||||
return this.ideUtils.readRangeInFile(
|
||||
filepath,
|
||||
new vscode.Range(
|
||||
new vscode.Position(range.start.line, range.start.character),
|
||||
new vscode.Position(range.end.line, range.end.character)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async getStats(directory: string): Promise<{ [path: string]: number }> {
|
||||
const files = await this.listWorkspaceContents(directory);
|
||||
const pathToLastModified: { [path: string]: number } = {};
|
||||
await Promise.all(
|
||||
files.map(async (file) => {
|
||||
let stat = await vscode.workspace.fs.stat(vscode.Uri.file(file));
|
||||
pathToLastModified[file] = stat.mtime;
|
||||
})
|
||||
);
|
||||
|
||||
return pathToLastModified;
|
||||
}
|
||||
|
||||
async getRepo(dir: vscode.Uri): Promise<any> {
|
||||
return this.ideUtils.getRepo(dir);
|
||||
}
|
||||
|
||||
async isTelemetryEnabled(): Promise<boolean> {
|
||||
return (
|
||||
(await vscode.workspace
|
||||
.getConfiguration("continue")
|
||||
.get("telemetryEnabled")) ?? true
|
||||
);
|
||||
}
|
||||
getUniqueId(): Promise<string> {
|
||||
return Promise.resolve(vscode.env.machineId);
|
||||
}
|
||||
|
||||
async getDiff(): Promise<string> {
|
||||
return await ideProtocolClient.getDiff();
|
||||
return await this.ideUtils.getDiff();
|
||||
}
|
||||
|
||||
async getTerminalContents(): Promise<string> {
|
||||
return await ideProtocolClient.getTerminalContents(1);
|
||||
return await this.ideUtils.getTerminalContents(1);
|
||||
}
|
||||
|
||||
async listWorkspaceContents(directory?: string): Promise<string[]> {
|
||||
if (directory) {
|
||||
return await ideProtocolClient.getDirectoryContents(directory, true);
|
||||
return await this.ideUtils.getDirectoryContents(directory, true);
|
||||
} else {
|
||||
const contents = await Promise.all(
|
||||
ideProtocolClient
|
||||
this.ideUtils
|
||||
.getWorkspaceDirectories()
|
||||
.map((dir) => ideProtocolClient.getDirectoryContents(dir, true))
|
||||
.map((dir) => this.ideUtils.getDirectoryContents(dir, true))
|
||||
);
|
||||
return contents.flat();
|
||||
}
|
||||
}
|
||||
|
||||
async getWorkspaceConfigs() {
|
||||
const workspaceDirs =
|
||||
vscode.workspace.workspaceFolders?.map((folder) => folder.uri) || [];
|
||||
const configs: ContinueRcJson[] = [];
|
||||
for (const workspaceDir of workspaceDirs) {
|
||||
const files = await vscode.workspace.fs.readDirectory(workspaceDir);
|
||||
for (const [filename, type] of files) {
|
||||
if (type === vscode.FileType.File && filename === ".continuerc.json") {
|
||||
const contents = await this.ideUtils.readFile(
|
||||
vscode.Uri.joinPath(workspaceDir, filename).fsPath
|
||||
);
|
||||
configs.push(JSON.parse(contents));
|
||||
}
|
||||
}
|
||||
}
|
||||
return configs;
|
||||
}
|
||||
|
||||
async listFolders(): Promise<string[]> {
|
||||
const allDirs: string[] = [];
|
||||
|
||||
|
|
@ -63,7 +120,7 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
|
||||
async getWorkspaceDirs(): Promise<string[]> {
|
||||
return ideProtocolClient.getWorkspaceDirectories();
|
||||
return this.ideUtils.getWorkspaceDirectories();
|
||||
}
|
||||
|
||||
async getContinueDir(): Promise<string> {
|
||||
|
|
@ -78,11 +135,11 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
|
||||
async showVirtualFile(title: string, contents: string): Promise<void> {
|
||||
ideProtocolClient.showVirtualFile(title, contents);
|
||||
this.ideUtils.showVirtualFile(title, contents);
|
||||
}
|
||||
|
||||
async openFile(path: string): Promise<void> {
|
||||
ideProtocolClient.openFile(path);
|
||||
this.ideUtils.openFile(path);
|
||||
}
|
||||
|
||||
async showLines(
|
||||
|
|
@ -95,53 +152,44 @@ class VsCodeIde implements IDE {
|
|||
new vscode.Position(endLine, 0)
|
||||
);
|
||||
openEditorAndRevealRange(filepath, range).then(() => {
|
||||
ideProtocolClient.highlightCode(
|
||||
{
|
||||
filepath,
|
||||
range,
|
||||
},
|
||||
"#fff1"
|
||||
);
|
||||
// TODO: Highlight lines
|
||||
// this.ideUtils.highlightCode(
|
||||
// {
|
||||
// filepath,
|
||||
// range,
|
||||
// },
|
||||
// "#fff1"
|
||||
// );
|
||||
});
|
||||
}
|
||||
|
||||
async runCommand(command: string): Promise<void> {
|
||||
await ideProtocolClient.runCommand(command);
|
||||
if (vscode.window.terminals.length) {
|
||||
vscode.window.terminals[0].show();
|
||||
vscode.window.terminals[0].sendText(command, false);
|
||||
} else {
|
||||
const terminal = vscode.window.createTerminal();
|
||||
terminal.show();
|
||||
terminal.sendText(command, false);
|
||||
}
|
||||
}
|
||||
|
||||
async saveFile(filepath: string): Promise<void> {
|
||||
await ideProtocolClient.saveFile(filepath);
|
||||
await this.ideUtils.saveFile(filepath);
|
||||
}
|
||||
async readFile(filepath: string): Promise<string> {
|
||||
return await ideProtocolClient.readFile(filepath);
|
||||
return await this.ideUtils.readFile(filepath);
|
||||
}
|
||||
async showDiff(
|
||||
filepath: string,
|
||||
newContents: string,
|
||||
stepIndex: number
|
||||
): Promise<void> {
|
||||
await ideProtocolClient.showDiff(filepath, newContents, stepIndex);
|
||||
}
|
||||
|
||||
async verticalDiffUpdate(
|
||||
filepath: string,
|
||||
startLine: number,
|
||||
endLine: number,
|
||||
diffLine: DiffLine
|
||||
) {
|
||||
const diffHandler =
|
||||
verticalPerLineDiffManager.getOrCreateVerticalPerLineDiffHandler(
|
||||
filepath,
|
||||
startLine,
|
||||
endLine
|
||||
);
|
||||
if (diffHandler) {
|
||||
await diffHandler.handleDiffLine(diffLine);
|
||||
}
|
||||
await this.diffManager.writeDiff(filepath, newContents, stepIndex);
|
||||
}
|
||||
|
||||
async getOpenFiles(): Promise<string[]> {
|
||||
return await ideProtocolClient.getOpenFiles();
|
||||
return await this.ideUtils.getOpenFiles();
|
||||
}
|
||||
|
||||
async getPinnedFiles(): Promise<string[]> {
|
||||
|
|
@ -229,48 +277,7 @@ class VsCodeIde implements IDE {
|
|||
}
|
||||
|
||||
async getBranch(dir: string): Promise<string> {
|
||||
return ideProtocolClient.getBranch(vscode.Uri.file(dir));
|
||||
}
|
||||
|
||||
async getFilesToEmbed(
|
||||
providerId: string
|
||||
): Promise<[string, string, string][]> {
|
||||
return [];
|
||||
}
|
||||
|
||||
async sendEmbeddingForChunk(
|
||||
chunk: Chunk,
|
||||
embedding: number[],
|
||||
tags: string[]
|
||||
) {}
|
||||
|
||||
async retrieveChunks(
|
||||
text: string,
|
||||
n: number,
|
||||
directory: string | undefined
|
||||
): Promise<Chunk[]> {
|
||||
const embeddingsProvider = (await configHandler.loadConfig())
|
||||
.embeddingsProvider;
|
||||
if (!embeddingsProvider) {
|
||||
return [];
|
||||
}
|
||||
const lanceDbIndex = new LanceDbIndex(embeddingsProvider, (path) =>
|
||||
ideProtocolClient.readFile(path)
|
||||
);
|
||||
|
||||
const tags = await Promise.all(
|
||||
(await this.getWorkspaceDirs()).map(async (dir) => {
|
||||
let branch = await ideProtocolClient.getBranch(vscode.Uri.file(dir));
|
||||
let tag: IndexTag = {
|
||||
directory: dir,
|
||||
branch,
|
||||
artifactId: lanceDbIndex.artifactId,
|
||||
};
|
||||
return tag;
|
||||
})
|
||||
);
|
||||
let chunks = await lanceDbIndex.retrieve(tags, text, n, directory);
|
||||
return chunks as any[];
|
||||
return this.ideUtils.getBranch(vscode.Uri.file(dir));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
import { IDE } from "core";
|
||||
import { AutocompleteSnippet } from "core/autocomplete/constructPrompt";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
export class AutocompletePromptBuilder {
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
async getDefinition(
|
||||
uri: string,
|
||||
line: number,
|
||||
character: number
|
||||
): Promise<AutocompleteSnippet | undefined> {
|
||||
const definitions = (await vscode.commands.executeCommand(
|
||||
"vscode.executeDefinitionProvider",
|
||||
vscode.Uri.parse(uri),
|
||||
new vscode.Position(line, character)
|
||||
)) as any;
|
||||
|
||||
if (definitions[0]?.targetRange) {
|
||||
return {
|
||||
filepath: uri,
|
||||
content: await this.ide.readRangeInFile(
|
||||
definitions[0].targetUri.fsPath,
|
||||
definitions[0].targetRange
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,26 @@
|
|||
import * as os from "os";
|
||||
import * as path from "path";
|
||||
import * as vscode from "vscode";
|
||||
import { DIFF_DIRECTORY, diffManager } from "../diff/horizontal";
|
||||
import { editorToVerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
|
||||
import { DIFF_DIRECTORY, DiffManager } from "../diff/horizontal";
|
||||
import { VerticalDiffCodeLens } from "../diff/verticalPerLine/manager";
|
||||
import { editorSuggestionsLocked, editorToSuggestions } from "../suggestions";
|
||||
import { getMetaKeyLabel } from "../util/util";
|
||||
import { getExtensionUri } from "../util/vscode";
|
||||
|
||||
class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
|
||||
constructor(
|
||||
private readonly editorToVerticalDiffCodeLens: Map<
|
||||
string,
|
||||
VerticalDiffCodeLens[]
|
||||
>
|
||||
) {}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken
|
||||
): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
|
||||
const filepath = document.uri.fsPath;
|
||||
const blocks = editorToVerticalDiffCodeLens.get(filepath);
|
||||
const blocks = this.editorToVerticalDiffCodeLens.get(filepath);
|
||||
if (!blocks) {
|
||||
return [];
|
||||
}
|
||||
|
|
@ -28,12 +35,12 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
|
|||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Accept ✅",
|
||||
title: "Accept",
|
||||
command: "continue.acceptVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Reject ❌",
|
||||
title: "Reject",
|
||||
command: "continue.rejectVerticalDiffBlock",
|
||||
arguments: [filepath, i],
|
||||
})
|
||||
|
|
@ -41,7 +48,7 @@ class VerticalPerLineCodeLensProvider implements vscode.CodeLensProvider {
|
|||
if (codeLenses.length === 2) {
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}⇧L to retry)`,
|
||||
title: `(${getMetaKeyLabel()}⇧↩/${getMetaKeyLabel()}⇧⌫ to accept/reject all, ${getMetaKeyLabel()}I to retry)`,
|
||||
command: "",
|
||||
})
|
||||
);
|
||||
|
|
@ -71,12 +78,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
|
|||
);
|
||||
codeLenses.push(
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Accept ✅",
|
||||
title: "Accept",
|
||||
command: "continue.acceptSuggestion",
|
||||
arguments: [suggestion],
|
||||
}),
|
||||
new vscode.CodeLens(range, {
|
||||
title: "Reject ❌",
|
||||
title: "Reject",
|
||||
command: "continue.rejectSuggestion",
|
||||
arguments: [suggestion],
|
||||
})
|
||||
|
|
@ -96,6 +103,12 @@ class SuggestionsCodeLensProvider implements vscode.CodeLensProvider {
|
|||
}
|
||||
|
||||
class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
|
||||
diffManager: DiffManager;
|
||||
|
||||
constructor(diffManager: DiffManager) {
|
||||
this.diffManager = diffManager;
|
||||
}
|
||||
|
||||
public provideCodeLenses(
|
||||
document: vscode.TextDocument,
|
||||
_: vscode.CancellationToken
|
||||
|
|
@ -103,7 +116,7 @@ class DiffViewerCodeLensProvider implements vscode.CodeLensProvider {
|
|||
if (path.dirname(document.uri.fsPath) === DIFF_DIRECTORY) {
|
||||
const codeLenses: vscode.CodeLens[] = [];
|
||||
let range = new vscode.Range(0, 0, 1, 0);
|
||||
const diffInfo = diffManager.diffAtNewFilepath(document.uri.fsPath);
|
||||
const diffInfo = this.diffManager.diffAtNewFilepath(document.uri.fsPath);
|
||||
if (diffInfo) {
|
||||
range = diffInfo.range;
|
||||
}
|
||||
|
|
@ -284,7 +297,7 @@ class TutorialCodeLensProvider implements vscode.CodeLensProvider {
|
|||
new vscode.CodeLens(range, {
|
||||
title: "Highlight the function",
|
||||
command: "continue.selectRange",
|
||||
arguments: [lineOf11 + 1, lineOf11 + 8],
|
||||
arguments: [lineOf11 + 3, lineOf11 + 11],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
@ -334,7 +347,11 @@ let suggestionsCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
|||
let configPyCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
let tutorialCodeLensDisposable: vscode.Disposable | undefined = undefined;
|
||||
|
||||
export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
|
||||
export function registerAllCodeLensProviders(
|
||||
context: vscode.ExtensionContext,
|
||||
diffManager: DiffManager,
|
||||
editorToVerticalDiffCodeLens: Map<string, VerticalDiffCodeLens[]>
|
||||
) {
|
||||
if (verticalPerLineCodeLensProvider) {
|
||||
verticalPerLineCodeLensProvider.dispose();
|
||||
}
|
||||
|
|
@ -353,7 +370,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
|
|||
|
||||
verticalPerLineCodeLensProvider = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new VerticalPerLineCodeLensProvider()
|
||||
new VerticalPerLineCodeLensProvider(editorToVerticalDiffCodeLens)
|
||||
);
|
||||
suggestionsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
|
|
@ -361,7 +378,7 @@ export function registerAllCodeLensProviders(context: vscode.ExtensionContext) {
|
|||
);
|
||||
diffsCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
new DiffViewerCodeLensProvider()
|
||||
new DiffViewerCodeLensProvider(diffManager)
|
||||
);
|
||||
configPyCodeLensDisposable = vscode.languages.registerCodeLensProvider(
|
||||
"*",
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
import { TabAutocompleteOptions } from "core";
|
||||
import { IDE, TabAutocompleteOptions } from "core";
|
||||
import { AutocompleteLruCache } from "core/autocomplete/cache";
|
||||
import { onlyWhitespaceAfterEndOfLine } from "core/autocomplete/charStream";
|
||||
import {
|
||||
AutocompleteSnippet,
|
||||
constructAutocompletePrompt,
|
||||
languageForFilepath,
|
||||
} from "core/autocomplete/constructPrompt";
|
||||
|
|
@ -12,13 +11,15 @@ import {
|
|||
} from "core/autocomplete/lineStream";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "core/autocomplete/parameters";
|
||||
import { getTemplateForModel } from "core/autocomplete/templates";
|
||||
import { ConfigHandler } from "core/config/handler";
|
||||
import { streamLines } from "core/diff/util";
|
||||
import OpenAI from "core/llm/llms/OpenAI";
|
||||
import { logDevData } from "core/util/devdata";
|
||||
import Handlebars from "handlebars";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import * as vscode from "vscode";
|
||||
import { ideProtocolClient } from "../activation/activate";
|
||||
import { TabAutocompleteModel, configHandler } from "../loadConfig";
|
||||
import { TabAutocompleteModel } from "../util/loadAutocompleteModel";
|
||||
import { AutocompletePromptBuilder } from "./autocompletePromptBuilder";
|
||||
|
||||
const statusBarItemText = (enabled: boolean | undefined) =>
|
||||
enabled ? "$(check) Continue" : "$(circle-slash) Continue";
|
||||
|
|
@ -70,30 +71,6 @@ export function setupStatusBar(
|
|||
});
|
||||
}
|
||||
|
||||
async function getDefinition(
|
||||
uri: string,
|
||||
line: number,
|
||||
character: number
|
||||
): Promise<AutocompleteSnippet | undefined> {
|
||||
const definitions = (await vscode.commands.executeCommand(
|
||||
"vscode.executeDefinitionProvider",
|
||||
vscode.Uri.parse(uri),
|
||||
new vscode.Position(line, character)
|
||||
)) as any;
|
||||
|
||||
if (definitions[0]?.targetRange) {
|
||||
return {
|
||||
filepath: uri,
|
||||
content: await ideProtocolClient.readRangeInFile(
|
||||
definitions[0].targetUri.fsPath,
|
||||
definitions[0].targetRange
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface AutocompleteOutcome {
|
||||
accepted?: boolean;
|
||||
time: number;
|
||||
|
|
@ -234,157 +211,6 @@ class GeneratorReuseManager {
|
|||
}
|
||||
}
|
||||
|
||||
async function getTabCompletion(
|
||||
document: vscode.TextDocument,
|
||||
pos: vscode.Position,
|
||||
token: vscode.CancellationToken,
|
||||
options: TabAutocompleteOptions
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Filter
|
||||
const lang = languageForFilepath(document.fileName);
|
||||
const line = document.lineAt(pos).text;
|
||||
for (const endOfLine of lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Model
|
||||
const llm = await TabAutocompleteModel.get();
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
}
|
||||
if (!llm) return;
|
||||
|
||||
// Prompt
|
||||
const fullPrefix = document.getText(
|
||||
new vscode.Range(new vscode.Position(0, 0), pos)
|
||||
);
|
||||
const fullSuffix = document.getText(
|
||||
new vscode.Range(
|
||||
pos,
|
||||
new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER)
|
||||
)
|
||||
);
|
||||
const lineBelowCursor = document.lineAt(
|
||||
Math.min(pos.line + 1, document.lineCount - 1)
|
||||
).text;
|
||||
const clipboardText = await vscode.env.clipboard.readText();
|
||||
const { prefix, suffix } = await constructAutocompletePrompt(
|
||||
document.uri.toString(),
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
clipboardText,
|
||||
lang,
|
||||
getDefinition,
|
||||
options
|
||||
);
|
||||
|
||||
const { template, completionOptions } = options.template
|
||||
? { template: options.template, completionOptions: {} }
|
||||
: getTemplateForModel(llm.model);
|
||||
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
const prompt = compiledTemplate({ prefix, suffix });
|
||||
|
||||
// Completion
|
||||
let completion = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = await cache.get(prompt);
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
setupStatusBar(true, true);
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
let stop = [
|
||||
...(completionOptions?.stop || []),
|
||||
"\n\n",
|
||||
"```",
|
||||
...lang.stopWords,
|
||||
];
|
||||
if (options.disableMultiLineCompletions) {
|
||||
stop.unshift("\n");
|
||||
}
|
||||
let generator = GeneratorReuseManager.getGenerator(prefix, () =>
|
||||
llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
temperature: 0,
|
||||
raw: true,
|
||||
stop,
|
||||
})
|
||||
);
|
||||
|
||||
// LLM
|
||||
let cancelled = false;
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.isCancellationRequested) {
|
||||
stopStatusBarLoading();
|
||||
cancelled = true;
|
||||
return undefined;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
const gen2 = onlyWhitespaceAfterEndOfLine(
|
||||
generatorWithCancellation(),
|
||||
lang.endOfLine
|
||||
);
|
||||
const lineGenerator = streamWithNewLines(streamLines(gen2));
|
||||
const finalGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor);
|
||||
for await (const update of finalGenerator) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Don't return empty
|
||||
if (completion.trim().length <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Post-processing
|
||||
completion = completion.trimEnd();
|
||||
}
|
||||
|
||||
const time = Date.now() - startTime;
|
||||
return {
|
||||
time,
|
||||
completion,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
};
|
||||
} catch (e: any) {
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (!ContinueCompletionProvider.errorsShown.has(e.message)) {
|
||||
ContinueCompletionProvider.errorsShown.add(e.message);
|
||||
vscode.window.showErrorMessage(e.message, "Documentation").then((val) => {
|
||||
if (val === "Documentation") {
|
||||
vscode.env.openExternal(
|
||||
vscode.Uri.parse(
|
||||
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export class ContinueCompletionProvider
|
||||
implements vscode.InlineCompletionItemProvider
|
||||
{
|
||||
|
|
@ -394,6 +220,174 @@ export class ContinueCompletionProvider
|
|||
|
||||
public static errorsShown: Set<string> = new Set();
|
||||
|
||||
private readonly promptBuilder: AutocompletePromptBuilder;
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly tabAutocompleteModel: TabAutocompleteModel
|
||||
) {
|
||||
this.promptBuilder = new AutocompletePromptBuilder(ide);
|
||||
}
|
||||
|
||||
async getTabCompletion(
|
||||
document: vscode.TextDocument,
|
||||
pos: vscode.Position,
|
||||
token: vscode.CancellationToken,
|
||||
options: TabAutocompleteOptions
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
const startTime = Date.now();
|
||||
|
||||
// Filter
|
||||
const lang = languageForFilepath(document.fileName);
|
||||
const line = document.lineAt(pos).text;
|
||||
for (const endOfLine of lang.endOfLine) {
|
||||
if (line.endsWith(endOfLine) && pos.character >= endOfLine.length) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Model
|
||||
const llm = await this.tabAutocompleteModel.get();
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
}
|
||||
if (!llm) return;
|
||||
|
||||
// Prompt
|
||||
const fullPrefix = document.getText(
|
||||
new vscode.Range(new vscode.Position(0, 0), pos)
|
||||
);
|
||||
const fullSuffix = document.getText(
|
||||
new vscode.Range(
|
||||
pos,
|
||||
new vscode.Position(document.lineCount, Number.MAX_SAFE_INTEGER)
|
||||
)
|
||||
);
|
||||
const lineBelowCursor = document.lineAt(
|
||||
Math.min(pos.line + 1, document.lineCount - 1)
|
||||
).text;
|
||||
const clipboardText = await vscode.env.clipboard.readText();
|
||||
const { prefix, suffix, completeMultiline } =
|
||||
await constructAutocompletePrompt(
|
||||
document.uri.toString(),
|
||||
fullPrefix,
|
||||
fullSuffix,
|
||||
clipboardText,
|
||||
lang,
|
||||
this.promptBuilder.getDefinition.bind(this.promptBuilder),
|
||||
options,
|
||||
llm.model
|
||||
);
|
||||
|
||||
const { template, completionOptions } = options.template
|
||||
? { template: options.template, completionOptions: {} }
|
||||
: getTemplateForModel(llm.model);
|
||||
|
||||
const compiledTemplate = Handlebars.compile(template);
|
||||
const prompt = compiledTemplate({ prefix, suffix });
|
||||
|
||||
// Completion
|
||||
let completion = "";
|
||||
|
||||
const cache = await autocompleteCache;
|
||||
const cachedCompletion = await cache.get(prompt);
|
||||
let cacheHit = false;
|
||||
if (cachedCompletion) {
|
||||
// Cache
|
||||
cacheHit = true;
|
||||
completion = cachedCompletion;
|
||||
} else {
|
||||
setupStatusBar(true, true);
|
||||
|
||||
// Try to reuse pending requests if what the user typed matches start of completion
|
||||
let stop = [
|
||||
...(completionOptions?.stop || []),
|
||||
"\n\n",
|
||||
"```",
|
||||
...lang.stopWords,
|
||||
];
|
||||
if (options.disableMultiLineCompletions || !completeMultiline) {
|
||||
stop.unshift("\n");
|
||||
}
|
||||
let generator = GeneratorReuseManager.getGenerator(prefix, () =>
|
||||
llm.streamComplete(prompt, {
|
||||
...completionOptions,
|
||||
temperature: 0,
|
||||
raw: true,
|
||||
stop,
|
||||
})
|
||||
);
|
||||
|
||||
// LLM
|
||||
let cancelled = false;
|
||||
const generatorWithCancellation = async function* () {
|
||||
for await (const update of generator) {
|
||||
if (token.isCancellationRequested) {
|
||||
stopStatusBarLoading();
|
||||
cancelled = true;
|
||||
return undefined;
|
||||
}
|
||||
yield update;
|
||||
}
|
||||
};
|
||||
const gen2 = onlyWhitespaceAfterEndOfLine(
|
||||
generatorWithCancellation(),
|
||||
lang.endOfLine
|
||||
);
|
||||
const lineGenerator = streamWithNewLines(streamLines(gen2));
|
||||
const finalGenerator = stopAtSimilarLine(
|
||||
lineGenerator,
|
||||
lineBelowCursor
|
||||
);
|
||||
for await (const update of finalGenerator) {
|
||||
completion += update;
|
||||
}
|
||||
|
||||
if (cancelled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Don't return empty
|
||||
if (completion.trim().length <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Post-processing
|
||||
completion = completion.trimEnd();
|
||||
}
|
||||
|
||||
const time = Date.now() - startTime;
|
||||
return {
|
||||
time,
|
||||
completion,
|
||||
prompt,
|
||||
modelProvider: llm.providerName,
|
||||
modelName: llm.model,
|
||||
completionOptions,
|
||||
cacheHit,
|
||||
};
|
||||
} catch (e: any) {
|
||||
console.warn("Error generating autocompletion: ", e);
|
||||
if (!ContinueCompletionProvider.errorsShown.has(e.message)) {
|
||||
ContinueCompletionProvider.errorsShown.add(e.message);
|
||||
vscode.window
|
||||
.showErrorMessage(e.message, "Documentation")
|
||||
.then((val) => {
|
||||
if (val === "Documentation") {
|
||||
vscode.env.openExternal(
|
||||
vscode.Uri.parse(
|
||||
"https://continue.dev/docs/walkthroughs/tab-autocomplete"
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async provideInlineCompletionItems(
|
||||
document: vscode.TextDocument,
|
||||
position: vscode.Position,
|
||||
|
|
@ -405,7 +399,7 @@ export class ContinueCompletionProvider
|
|||
const uuid = uuidv4();
|
||||
ContinueCompletionProvider.lastUUID = uuid;
|
||||
|
||||
const config = await configHandler.loadConfig();
|
||||
const config = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...config.tabAutocompleteOptions,
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
|
|
@ -437,7 +431,7 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
try {
|
||||
const outcome = await getTabCompletion(
|
||||
const outcome = await this.getTabCompletion(
|
||||
document,
|
||||
position,
|
||||
token,
|
||||
|
|
@ -459,7 +453,7 @@ export class ContinueCompletionProvider
|
|||
const logRejectionTimeout = setTimeout(() => {
|
||||
// Wait 10 seconds, then assume it wasn't accepted
|
||||
outcome.accepted = false;
|
||||
ideProtocolClient.logDevData("autocomplete", outcome);
|
||||
logDevData("autocomplete", outcome);
|
||||
}, 10_000);
|
||||
|
||||
return [
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue