+ 👋 Thanks for using Continue. We are always trying to improve
+ and love hearing from users. If you're interested in speaking,
+ enter your name and email. We won't use this information for
+ anything other than reaching out.
+
+
+
+
+ 👋 Thanks for using Continue. We are always trying to improve
+ and love hearing from users. If you're interested in speaking,
+ enter your name and email. We won't use this information for
+ anything other than reaching out.
+
+
+
+
+ Continue now uses a .json config file. We hope that this takes the
+ guesswork out of setting up.
+
+
+
+ Your configuration should have been automatically migrated, but we
+ recommend double-checking that everything looks correct.
+
+
+
+ For a summary of what changed and examples of config.json,
+ please see the{" "}
+
+ migration walkthrough
+
+ , and if you have any questions please reach out to us on{" "}
+
+ Discord
+
+ .
+
+
+
+ Note: If you are running the server manually and have not updated the
+ server, this message does not apply.
+
+
+ {
+ navigate("/");
+ }}
+ disabled={false}
+ />
+
+ Continue now uses a .json config file. We hope that this takes the
+ guesswork out of setting up.
+
+
+
+ Your configuration should have been automatically migrated, but we
+ recommend double-checking that everything looks correct.
+
+
+
+ For a summary of what changed and examples of config.json,
+ please see the{" "}
+
+ migration walkthrough
+
+ , and if you have any questions please reach out to us on{" "}
+
+ Discord
+
+ .
+
+
+
+ Note: If you are running the server manually and have not updated the
+ server, this message does not apply.
+
+
+ {/* ... existing code ... */}
+
+ Continue now uses a .json config file. We hope that this takes the
+ guesswork out of setting up.
+
+
+-
++
+ Your configuration should have been automatically migrated, but we
+ recommend double-checking that everything looks correct.
+
+
+-
++
+ For a summary of what changed and examples of config.json,
+ please see the{" "}
+
+ migration walkthrough
+
+ , and if you have any questions please reach out to us on{" "}
+
+ Discord
+
+ .
+
+
+-
++
+ Note: If you are running the server manually and have not updated the
+ server, this message does not apply.
+
+
+ {
+ navigate("/");
+ }}
+ disabled={false}
+ />
+
+ );
+}
+
+export default MigrationPage;
\ No newline at end of file
diff --git a/core/edit/lazy/test-examples/no-lazy-single-class.js.diff b/core/edit/lazy/test-examples/no-lazy-single-class.js.diff
new file mode 100644
index 000000000..bb561271d
--- /dev/null
+++ b/core/edit/lazy/test-examples/no-lazy-single-class.js.diff
@@ -0,0 +1,30 @@
+class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+
+ reset() {
+ this.result = 0;
+ return this;
+ }
+}
+---
+
+ reset() {
+ this.result = 1;
+ return this;
+ }
+
+---
+
+class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+
+ reset() {
+- this.result = 0;
++ this.result = 1;
+ return this;
+ }
+}
\ No newline at end of file
diff --git a/core/edit/lazy/test-examples/no-lazy.js.diff b/core/edit/lazy/test-examples/no-lazy.js.diff
new file mode 100644
index 000000000..c5195628f
--- /dev/null
+++ b/core/edit/lazy/test-examples/no-lazy.js.diff
@@ -0,0 +1,34 @@
+class Hello {
+ hello() {
+ return "Hello World";
+ }
+}
+
+class Goodbye {
+ goodbye() {
+ return "Goodbye World";
+ }
+}
+
+---
+
+class Goodbye {
+ goodbye() {
+ return "Au revoir le monde";
+ }
+}
+
+---
+
+class Hello {
+ hello() {
+ return "Hello World";
+ }
+}
+
+class Goodbye {
+ goodbye() {
+- return "Goodbye World";
++ return "Au revoir le monde";
+ }
+}
\ No newline at end of file
diff --git a/core/edit/lazy/test-examples/rust-calc-exp.rs.diff b/core/edit/lazy/test-examples/rust-calc-exp.rs.diff
new file mode 100644
index 000000000..21ab8bd10
--- /dev/null
+++ b/core/edit/lazy/test-examples/rust-calc-exp.rs.diff
@@ -0,0 +1,126 @@
+use std::io;
+
+fn main() {
+ println!("Welcome to the Calculator!");
+
+ loop {
+ println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
+ let operator = read_input();
+
+ if operator == "q" {
+ break;
+ }
+
+ println!("Please enter the first number:");
+ let num1 = read_input().parse::().unwrap();
+
+ println!("Please enter the second number:");
+ let num2 = read_input().parse::().unwrap();
+
+ let result = match operator.as_str() {
+ "+" => num1 + num2,
+ "-" => num1 - num2,
+ "*" => num1 * num2,
+ "/" => num1 / num2,
+ _ => {
+ println!("Invalid operator. Please try again.");
+ continue;
+ }
+ };
+
+ println!("Result: {}", result);
+ }
+}
+
+fn read_input() -> String {
+ let mut input = String::new();
+ io::stdin()
+ .read_line(&mut input)
+ .expect("Failed to read input");
+ input.trim().to_string()
+}
+
+---
+
+use std::io;
+
+fn main() {
+ println!("Welcome to the Calculator!");
+
+ loop {
+ println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:");
+ let operator = read_input();
+
+ if operator == "q" {
+ break;
+ }
+
+ println!("Please enter the first number:");
+ let num1 = read_input().parse::().unwrap();
+
+ println!("Please enter the second number:");
+ let num2 = read_input().parse::().unwrap();
+
+ let result = match operator.as_str() {
+ "+" => num1 + num2,
+ "-" => num1 - num2,
+ "*" => num1 * num2,
+ "/" => num1 / num2,
+ "^" => num1.powf(num2),
+ _ => {
+ println!("Invalid operator. Please try again.");
+ continue;
+ }
+ };
+
+ println!("Result: {}", result);
+ }
+}
+
+// ... existing code ...
+
+---
+
+use std::io;
+
+fn main() {
+ println!("Welcome to the Calculator!");
+
+ loop {
+- println!("Please enter an operator (+, -, *, /) or 'q' to quit:");
++ println!("Please enter an operator (+, -, *, /, ^) or 'q' to quit:");
+ let operator = read_input();
+
+ if operator == "q" {
+ break;
+ }
+
+ println!("Please enter the first number:");
+ let num1 = read_input().parse::().unwrap();
+
+ println!("Please enter the second number:");
+ let num2 = read_input().parse::().unwrap();
+
+ let result = match operator.as_str() {
+ "+" => num1 + num2,
+ "-" => num1 - num2,
+ "*" => num1 * num2,
+ "/" => num1 / num2,
++ "^" => num1.powf(num2),
+ _ => {
+ println!("Invalid operator. Please try again.");
+ continue;
+ }
+ };
+
+ println!("Result: {}", result);
+ }
+}
+
+fn read_input() -> String {
+ let mut input = String::new();
+ io::stdin()
+ .read_line(&mut input)
+ .expect("Failed to read input");
+ input.trim().to_string()
+}
\ No newline at end of file
diff --git a/core/edit/lazy/test-examples/top-level-same.js.diff b/core/edit/lazy/test-examples/top-level-same.js.diff
new file mode 100644
index 000000000..97b65a51c
--- /dev/null
+++ b/core/edit/lazy/test-examples/top-level-same.js.diff
@@ -0,0 +1,64 @@
+class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+}
+
+class Subtract extends Calculator {
+ sub(num1, num2) {
+ this.result = num1 - num2;
+ return this.result;
+ }
+}
+
+class Add extends Calculator {
+ add(num1, num2) {
+ this.result = num1 + num2;
+ return this.result;
+ }
+}
+
+---
+
+// ... existing code ...
+
+class Subtract extends Calculator {
+ sub(num1, num2) {
+ this.result = num1 - num2;
+
+ if (this.result < 0) {
+ throw new Error("Result cannot be negative");
+ }
+
+ return this.result;
+ }
+}
+
+// ... existing code ...
+
+---
+
+class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+}
+
+class Subtract extends Calculator {
+ sub(num1, num2) {
+ this.result = num1 - num2;
++
++ if (this.result < 0) {
++ throw new Error("Result cannot be negative");
++ }
++
+ return this.result;
+ }
+}
+
+class Add extends Calculator {
+ add(num1, num2) {
+ this.result = num1 + num2;
+ return this.result;
+ }
+}
\ No newline at end of file
diff --git a/core/util/verticalEdit.ts b/core/edit/streamDiffLines.ts
similarity index 97%
rename from core/util/verticalEdit.ts
rename to core/edit/streamDiffLines.ts
index 34a17ebd4..cad33b3a2 100644
--- a/core/util/verticalEdit.ts
+++ b/core/edit/streamDiffLines.ts
@@ -5,7 +5,7 @@ import {
filterLeadingAndTrailingNewLineInsertion,
skipLines,
stopAtLines,
-} from "../autocomplete/lineStream.js";
+} from "../autocomplete/streamTransforms/lineStream.js";
import { streamDiff } from "../diff/streamDiff.js";
import { streamLines } from "../diff/util.js";
import {
@@ -15,7 +15,7 @@ import {
LLMFullCompletionOptions,
} from "../index.js";
import { gptEditPrompt } from "../llm/templates/edit.js";
-import { Telemetry } from "./posthog.js";
+import { Telemetry } from "../util/posthog.js";
function constructPrompt(
prefix: string,
diff --git a/core/index.d.ts b/core/index.d.ts
index 0c7c9b521..c1c8ddc04 100644
--- a/core/index.d.ts
+++ b/core/index.d.ts
@@ -70,6 +70,7 @@ export interface ILLM extends LLMOptions {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
+ cacheBehavior?: CacheBehavior;
engine?: string;
apiVersion?: string;
@@ -271,6 +272,13 @@ export interface ContextItemId {
itemId: string;
}
+export type ContextItemUriTypes = "file" | "url";
+
+export interface ContextItemUri {
+ type: ContextItemUriTypes;
+ value: string;
+}
+
export interface ContextItem {
content: string;
name: string;
@@ -278,16 +286,11 @@ export interface ContextItem {
editing?: boolean;
editable?: boolean;
icon?: string;
+ uri?: ContextItemUri;
}
-export interface ContextItemWithId {
- content: string;
- name: string;
- description: string;
+export interface ContextItemWithId extends ContextItem {
id: ContextItemId;
- editing?: boolean;
- editable?: boolean;
- icon?: string;
}
export interface InputModifiers {
@@ -340,6 +343,7 @@ export interface LLMOptions {
apiKey?: string;
aiGatewaySlug?: string;
apiBase?: string;
+ cacheBehavior?: CacheBehavior;
useLegacyCompletionsEndpoint?: boolean;
@@ -369,8 +373,6 @@ export interface LLMOptions {
watsonxStopToken?: string;
watsonxApiVersion?: string;
watsonxFullUrl?: string;
-
- cacheSystemMessage?: boolean;
}
type RequireAtLeastOne = Pick<
T,
@@ -578,6 +580,7 @@ type ContextProviderName =
| "gitlab-mr"
| "os"
| "currentFile"
+ | "greptile"
| "outline"
| "continue-proxy"
| "highlights"
@@ -691,6 +694,8 @@ export type ModelName =
| "deepseek-7b"
| "deepseek-33b"
| "neural-chat-7b"
+ | "gemma-7b-it"
+ | "gemma2-9b-it"
// Anthropic
| "claude-3-5-sonnet-20240620"
| "claude-3-opus-20240229"
@@ -725,6 +730,11 @@ export interface RequestOptions {
clientCertificate?: ClientCertificateOptions;
}
+export interface CacheBehavior {
+ cacheSystemMessage?: boolean;
+ cacheConversation?: boolean;
+}
+
export interface ClientCertificateOptions {
cert: string;
key: string;
@@ -787,6 +797,7 @@ export interface ModelDescription {
requestOptions?: RequestOptions;
promptTemplates?: { [key: string]: string };
capabilities?: ModelCapability;
+ cacheBehavior?: CacheBehavior;
}
export type EmbeddingsProviderName =
@@ -871,6 +882,7 @@ export interface TabAutocompleteOptions {
recentLinePrefixMatchMinLength: number;
disableInFiles?: string[];
useImports?: boolean;
+ useRootPathContext?: boolean;
}
export interface ContinueUIConfig {
diff --git a/core/indexing/CodeSnippetsIndex.ts b/core/indexing/CodeSnippetsIndex.ts
index f567a48d2..a8b41cafe 100644
--- a/core/indexing/CodeSnippetsIndex.ts
+++ b/core/indexing/CodeSnippetsIndex.ts
@@ -341,6 +341,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
name: row.title,
description: getLastNPathParts(row.path, 2),
content: `\`\`\`${getBasename(row.path)}\n${row.content}\n\`\`\``,
+ uri: {
+ type: "file",
+ value: row.path,
+ },
};
}
@@ -383,20 +387,18 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
const query = `
- SELECT path, signature
- FROM code_snippets
- WHERE path LIKE ${placeholders}
- ORDER BY path
- LIMIT ? OFFSET ?
-`;
+ SELECT DISTINCT path, signature
+ FROM code_snippets
+ WHERE path LIKE ${placeholders}
+ ORDER BY path, signature
+ LIMIT ? OFFSET ?
+ `;
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
- const validRows = rows.filter((row) => row.path && row.signature !== null);
-
const groupedByPath: { [path: string]: string[] } = {};
- for (const { path, signature } of validRows) {
+ for (const { path, signature } of rows) {
if (!groupedByPath[path]) {
groupedByPath[path] = [];
}
diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts
index bc53539f4..6eca76268 100644
--- a/core/indexing/CodebaseIndexer.ts
+++ b/core/indexing/CodebaseIndexer.ts
@@ -249,10 +249,11 @@ export class CodebaseIndexer {
}
}
yield {
- progress: 100,
+ progress: 1,
desc: "Indexing Complete",
status: "done",
};
+ this.logProgress(beginTime, 0, 1);
}
private handleErrorAndGetProgressUpdate(
@@ -303,9 +304,9 @@ export class CodebaseIndexer {
const seconds = Math.round(timeTaken / 1000);
const progressPercentage = (progress * 100).toFixed(1);
const filesPerSec = (completedFileCount / seconds).toFixed(2);
- console.debug(
- `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
- );
+ // console.debug(
+ // `Indexing: ${progressPercentage}% complete, elapsed time: ${seconds}s, ${filesPerSec} file/sec`,
+ // );
}
private async *yieldUpdateAndPause(): AsyncGenerator {
diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts
index aea21e3cf..70d6ead29 100644
--- a/core/indexing/docs/DocsCrawler.ts
+++ b/core/indexing/docs/DocsCrawler.ts
@@ -411,7 +411,7 @@ class ChromiumCrawler {
for (const link of linkGroup) {
enqueuedLinkCount++;
- console.log({ enqueuedLinkCount, url: this.startUrl });
+ console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts
index 79e6dc86f..30e205c3b 100644
--- a/core/indexing/docs/DocsService.ts
+++ b/core/indexing/docs/DocsService.ts
@@ -1,8 +1,6 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
-import { ConfigHandler } from "../../config/ConfigHandler";
-import DocsContextProvider from "../../context/providers/DocsContextProvider";
import {
Chunk,
ContinueConfig,
@@ -11,6 +9,9 @@ import {
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../..";
+import { ConfigHandler } from "../../config/ConfigHandler";
+import { addContextProvider } from "../../config/util";
+import DocsContextProvider from "../../context/providers/DocsContextProvider";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
@@ -31,7 +32,7 @@ import {
SiteIndexingResults,
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
-import { addContextProvider } from "../../config/util";
+import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@@ -154,7 +155,10 @@ export default class DocsService {
params: {},
});
- this.ide.showToast("info", "Successfuly added docs context provider");
+ await this.ide.showToast(
+ "info",
+ "Successfuly added docs context provider",
+ );
}
return res === actionMsg;
@@ -177,7 +181,7 @@ export default class DocsService {
while (!(await generator.next()).done) {}
}
- this.ide.showToast("info", "Docs indexing completed");
+ await this.ide.showToast("info", "Docs indexing completed");
}
async list() {
@@ -250,6 +254,10 @@ export default class DocsService {
}
}
+ void Telemetry.capture("docs_pages_crawled", {
+ count: processedPages,
+ });
+
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
@@ -317,7 +325,7 @@ export default class DocsService {
await this.delete(startUrl);
}
- const favicon = await this.fetchFavicon(siteIndexingConfig);
+ const favicon = await fetchFavicon(new URL(siteIndexingConfig.startUrl));
await this.add({
siteIndexingConfig,
@@ -456,14 +464,14 @@ export default class DocsService {
for (const doc of newDocs) {
console.log(`Indexing new doc: ${doc.startUrl}`);
- Telemetry.capture("add_docs_config", { url: doc.startUrl });
+ void Telemetry.capture("add_docs_config", { url: doc.startUrl });
const generator = this.indexAndAdd(doc);
while (!(await generator.next()).done) {}
}
for (const doc of deletedDocs) {
- console.log(`Deleting doc: ${doc.startUrl}`);
+ // console.debug(`Deleting doc: ${doc.startUrl}`);
await this.delete(doc.startUrl);
}
@@ -691,7 +699,12 @@ export default class DocsService {
const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
const startUrl = new URL(siteEmbeddings.url).toString();
- const favicon = await this.fetchFavicon(preIndexedDocs[startUrl]);
+
+ const faviconUrl = preIndexedDocs[startUrl].faviconUrl;
+ const favicon =
+ typeof faviconUrl === "string"
+ ? await getFaviconBase64(faviconUrl)
+ : undefined;
await this.add({
favicon,
@@ -704,30 +717,6 @@ export default class DocsService {
});
}
- private async fetchFavicon(siteIndexingConfig: SiteIndexingConfig) {
- const faviconUrl =
- siteIndexingConfig.faviconUrl ??
- new URL("/favicon.ico", siteIndexingConfig.startUrl);
-
- try {
- const response = await fetch(faviconUrl);
- const arrayBuffer = await response.arrayBuffer();
- const base64 = btoa(
- new Uint8Array(arrayBuffer).reduce(
- (data, byte) => data + String.fromCharCode(byte),
- "",
- ),
- );
- const mimeType = response.headers.get("content-type") || "image/x-icon";
-
- return `data:${mimeType};base64,${base64}`;
- } catch {
- console.error(`Failed to fetch favicon: ${faviconUrl}`);
- }
-
- return undefined;
- }
-
private async shouldReindexDocsOnNewEmbeddingsProvider(
curEmbeddingsProviderId: EmbeddingsProvider["id"],
): Promise {
diff --git a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts
index aa9e8bd41..bf3bcac88 100644
--- a/core/indexing/embeddings/BedrockEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/BedrockEmbeddingsProvider.ts
@@ -78,7 +78,8 @@ class BedrockEmbeddingsProvider extends BaseEmbeddingsProvider {
try {
return await
fromIni({
- profile: this.profile
+ profile: this.profile,
+ ignoreCache: true
})();
} catch (e) {
console.warn(
diff --git a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts
index c02685af7..811a4fb0f 100644
--- a/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts
+++ b/core/indexing/embeddings/ContinueProxyEmbeddingsProvider.ts
@@ -1,24 +1,16 @@
-import { CONTROL_PLANE_URL } from "../../control-plane/client.js";
-import { EmbeddingsProviderName, EmbedOptions } from "../../index.js";
+import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
+import { EmbeddingsProviderName } from "../../index.js";
import OpenAIEmbeddingsProvider from "./OpenAIEmbeddingsProvider.js";
class ContinueProxyEmbeddingsProvider extends OpenAIEmbeddingsProvider {
static providerName: EmbeddingsProviderName = "continue-proxy";
- static defaultOptions: Partial | undefined = {
- apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(),
- };
- private _workOsAccessToken: string | undefined = undefined;
-
- get workOsAccessToken(): string | undefined {
- return this._workOsAccessToken;
- }
-
- set workOsAccessToken(value: string | undefined) {
- if (this._workOsAccessToken !== value) {
- this._workOsAccessToken = value;
- this.options.apiKey = value;
- }
+ set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
+ this.options.apiKey = value.workOsAccessToken;
+ this.options.apiBase = new URL(
+ "openai/v1",
+ value.controlPlaneProxyUrl,
+ ).toString();
}
}
diff --git a/core/llm/autodetect.ts b/core/llm/autodetect.ts
index 523bcb028..31eccfc8f 100644
--- a/core/llm/autodetect.ts
+++ b/core/llm/autodetect.ts
@@ -58,6 +58,7 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"bedrock",
"sagemaker",
"continue-proxy",
+ "openrouter",
];
const MODEL_SUPPORTS_IMAGES: string[] = [
@@ -73,15 +74,18 @@ const MODEL_SUPPORTS_IMAGES: string[] = [
"sonnet",
"opus",
"haiku",
+ "pixtral",
];
function modelSupportsImages(
provider: ModelProvider,
model: string,
title: string | undefined,
- capabilities: ModelCapability | undefined
+ capabilities: ModelCapability | undefined,
): boolean {
- if (capabilities?.uploadImage !== undefined) {return capabilities.uploadImage;}
+ if (capabilities?.uploadImage !== undefined) {
+ return capabilities.uploadImage;
+ }
if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) {
return false;
}
diff --git a/core/llm/constants.ts b/core/llm/constants.ts
index cc1866d4b..52265d509 100644
--- a/core/llm/constants.ts
+++ b/core/llm/constants.ts
@@ -1,5 +1,5 @@
-const DEFAULT_MAX_TOKENS = 1024;
-const DEFAULT_CONTEXT_LENGTH = 4096;
+const DEFAULT_MAX_TOKENS = 2048;
+const DEFAULT_CONTEXT_LENGTH = 8096;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {
diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts
index aaf23563e..13d538be8 100644
--- a/core/llm/constructMessages.ts
+++ b/core/llm/constructMessages.ts
@@ -1,8 +1,91 @@
import { ChatHistory, ChatMessage, MessagePart } from "../index.js";
-export function constructMessages(history: ChatHistory): ChatMessage[] {
+const SYSTEM_MESSAGE = `When generating new code:
+
+1. Always produce a single code block.
+2. Never separate the code into multiple code blocks.
+3. Only include the code that is being added.
+4. Replace existing code with a "lazy" comment like this: "// ... existing code ..."
+5. The "lazy" comment must always be a valid comment in the current context (e.g. "" for HTML, "// ... existing code ..." for JavaScript, "{/* ... existing code */}" for TSX, etc.)
+6. You must always provide 1-2 lines of context above and below a "lazy" comment
+7. If the user submits a code block that contains a filename in the language specifier, always include the filename in any code block you generate based on that file. The filename should be on the same line as the language specifier in your code block.
+
+Example 1:
+Input:
+\`\`\`test.js
+import addition from "addition"
+
+class Calculator {
+ constructor() {
+ this.result = 0;
+ }
+
+ add(number) {
+ this.result += number;
+ return this;
+ }
+}
+\`\`\`
+User request: Add a subtract method
+
+Output:
+\`\`\`javascript test.js
+// ... existing code ...
+import subtraction from "subtraction"
+
+class Calculator {
+ // ... existing code ...
+
+ subtract(number) {
+ this.result -= number;
+ return this;
+ }
+}
+\`\`\`
+
+Example 2:
+Input:
+\`\`\`javascript test.js (6-9)
+function helloWorld() {}
+\`\`\`
+
+Output:
+\`\`\`javascript test.js
+function helloWorld() {
+ // New code here
+}
+\`\`\`
+
+Always follow these guidelines when generating code responses.`;
+
+function hasCodeBlockWithFilename(content: ChatMessage["content"]): boolean {
+ const contentStr = typeof content === "string" ? content : content[0].text;
+
+ if (!contentStr) {
+ return false;
+ }
+
+ const codeBlockRegex = /```[\w\W]*?\.[\w\W]*/;
+ return codeBlockRegex.test(contentStr);
+}
+
+export function constructMessages(
+ history: ChatHistory,
+ model: string,
+): ChatMessage[] {
const msgs = [];
+ // Only using this system message with Sonnet right now
+ if (
+ // hasCodeBlockWithFilename(history[0].message.content) &&
+ model.includes("sonnet")
+ ) {
+ msgs.push({
+ role: "system" as const,
+ content: SYSTEM_MESSAGE,
+ });
+ }
+
for (let i = 0; i < history.length; i++) {
const historyItem = history[i];
diff --git a/core/llm/countTokens.ts b/core/llm/countTokens.ts
index 06cd4a3bb..0fbadf68b 100644
--- a/core/llm/countTokens.ts
+++ b/core/llm/countTokens.ts
@@ -332,7 +332,9 @@ function compileChatMessages(
systemMessage: string | undefined = undefined,
): ChatMessage[] {
const msgsCopy = msgs
- ? msgs.map((msg) => ({ ...msg })).filter((msg) => msg.content !== "")
+ ? msgs
+ .map((msg) => ({ ...msg }))
+ .filter((msg) => msg.content !== "" && msg.role !== "system")
: [];
if (prompt) {
@@ -343,10 +345,24 @@ function compileChatMessages(
msgsCopy.push(promptMsg);
}
- if (systemMessage && systemMessage.trim() !== "") {
+ if (
+ (systemMessage && systemMessage.trim() !== "") ||
+ msgs?.[0].role === "system"
+ ) {
+ let content = "";
+ if (msgs?.[0].role === "system") {
+ content = stripImages(msgs?.[0].content);
+ }
+ if (systemMessage && systemMessage.trim() !== "") {
+ const shouldAddNewLines = content !== "";
+ if (shouldAddNewLines) {
+ content += "\n\n";
+ }
+ content += systemMessage;
+ }
const systemChatMsg: ChatMessage = {
role: "system",
- content: systemMessage,
+ content,
};
// Insert as second to last
// Later moved to top, but want second-priority to last user message
diff --git a/core/llm/index.ts b/core/llm/index.ts
index 9a1ddaf46..53c984b43 100644
--- a/core/llm/index.ts
+++ b/core/llm/index.ts
@@ -1,6 +1,7 @@
import { findLlmInfo } from "@continuedev/llm-info";
import Handlebars from "handlebars";
import {
+ CacheBehavior,
ChatMessage,
ChatMessageRole,
CompletionOptions,
@@ -102,6 +103,7 @@ export abstract class BaseLLM implements ILLM {
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
+ cacheBehavior?: CacheBehavior;
capabilities?: ModelCapability;
engine?: string;
@@ -120,8 +122,6 @@ export abstract class BaseLLM implements ILLM {
watsonxApiVersion?: string;
watsonxFullUrl?: string;
- cacheSystemMessage?: boolean;
-
private _llmOptions: LLMOptions;
constructor(_options: LLMOptions) {
@@ -135,6 +135,7 @@ export abstract class BaseLLM implements ILLM {
};
this.model = options.model;
+ // Use @continuedev/llm-info package to autodetect certain parameters
const llmInfo = findLlmInfo(this.model);
const templateType =
@@ -149,7 +150,16 @@ export abstract class BaseLLM implements ILLM {
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
- maxTokens: options.completionOptions?.maxTokens ?? DEFAULT_MAX_TOKENS,
+ maxTokens:
+ options.completionOptions?.maxTokens ??
+ (llmInfo?.maxCompletionTokens
+ ? Math.min(
+ llmInfo.maxCompletionTokens,
+ // Even if the model has a large maxTokens, we don't want to use that every time,
+ // because it takes away from the context length
+ this.contextLength / 4,
+ )
+ : DEFAULT_MAX_TOKENS),
};
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
@@ -174,6 +184,7 @@ export abstract class BaseLLM implements ILLM {
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
+ this.cacheBehavior = options.cacheBehavior;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
@@ -183,8 +194,6 @@ export abstract class BaseLLM implements ILLM {
this.watsonxApiVersion = options.watsonxApiVersion;
this.watsonxFullUrl = options.watsonxFullUrl;
- this.cacheSystemMessage = options.cacheSystemMessage;
-
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;
}
@@ -252,16 +261,29 @@ export abstract class BaseLLM implements ILLM {
prompt: string,
completionOptions: CompletionOptions,
): string {
- const dict = { contextLength: this.contextLength, ...completionOptions };
- const settings = Object.entries(dict)
- .map(([key, value]) => `${key}: ${value}`)
- .join("\n");
- return `Settings:
-${settings}
+ const completionOptionsLog = JSON.stringify(
+ {
+ contextLength: this.contextLength,
+ ...completionOptions,
+ },
+ null,
+ 2,
+ );
-############################################
+ let requestOptionsLog = "";
+ if (this.requestOptions) {
+ requestOptionsLog = JSON.stringify(this.requestOptions, null, 2);
+ }
-${prompt}`;
+ return (
+ "##### Completion options #####\n" +
+ completionOptionsLog +
+ (requestOptionsLog
+ ? "\n\n##### Request options #####\n" + requestOptionsLog
+ : "") +
+ "\n\n##### Prompt #####\n" +
+ prompt
+ );
}
private _logTokensGenerated(
@@ -271,7 +293,8 @@ ${prompt}`;
) {
let promptTokens = this.countTokens(prompt);
let generatedTokens = this.countTokens(completion);
- Telemetry.capture(
+
+ void Telemetry.capture(
"tokens_generated",
{
model: model,
@@ -281,12 +304,14 @@ ${prompt}`;
},
true,
);
- DevDataSqliteDb.logTokensGenerated(
+
+ void DevDataSqliteDb.logTokensGenerated(
model,
this.providerName,
promptTokens,
generatedTokens,
);
+
logDevData("tokens_generated", {
model: model,
provider: this.providerName,
@@ -332,11 +357,11 @@ ${prompt}`;
) {
if (resp.url.includes("codestral.mistral.ai")) {
throw new Error(
- `You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting "apiBase" to "https://api.mistral.ai/v1" in config.json.`,
+ "You are using a Mistral API key, which is not compatible with the Codestral API. Please either obtain a Codestral API key, or use the Mistral API by setting 'apiBase' to 'https://api.mistral.ai/v1' in config.json.",
);
} else {
throw new Error(
- `You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting "apiBase" to "https://codestral.mistral.ai/v1" in config.json.`,
+ "You are using a Codestral API key, which is not compatible with the Mistral API. Please either obtain a Mistral API key, or use the the Codestral API by setting 'apiBase' to 'https://codestral.mistral.ai/v1' in config.json.",
);
}
}
@@ -404,7 +429,7 @@ ${prompt}`;
return formatted;
}
- async *_streamFim(
+ protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
@@ -532,6 +557,7 @@ ${prompt}`;
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, prompt, completion);
+
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
@@ -594,6 +620,7 @@ ${prompt}`;
}
this._logTokensGenerated(completionOptions.model, prompt, completion);
+
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
diff --git a/core/llm/llms/Anthropic.ts b/core/llm/llms/Anthropic.ts
index 320dd9798..f2182d851 100644
--- a/core/llm/llms/Anthropic.ts
+++ b/core/llm/llms/Anthropic.ts
@@ -35,17 +35,40 @@ class Anthropic extends BaseLLM {
}
private _convertMessages(msgs: ChatMessage[]): any[] {
- const messages = msgs
- .filter((m) => m.role !== "system")
- .map((message) => {
+ const filteredmessages = msgs.filter((m) => m.role !== "system")
+ const lastTwoUserMsgIndices = filteredmessages
+ .map((msg, index) => (msg.role === "user" ? index : -1))
+ .filter((index) => index !== -1).slice(-2);
+
+ const messages = filteredmessages.map((message, filteredMsgIdx) => {
+ // Add cache_control parameter to the last two user messages
+ // The second-to-last because it retrieves potentially already cached contents,
+ // The last one because we want it cached for later retrieval.
+ // See: https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
+ const addCaching = this.cacheBehavior?.cacheConversation && lastTwoUserMsgIndices.includes(filteredMsgIdx);
+
if (typeof message.content === "string") {
- return message;
+ var chatMessage = {
+ ...message,
+ content: [{
+ type: "text",
+ text: message.content,
+ ...(addCaching? { cache_control: { type: "ephemeral" } } : {})
+ }]
+ };
+ return chatMessage;
}
+
return {
...message,
- content: message.content.map((part) => {
+ content: message.content.map((part, contentIdx) => {
if (part.type === "text") {
- return part;
+ const newpart = {
+ ...part,
+ // If multiple text parts, only add cache_control to the last one
+ ...((addCaching && contentIdx == message.content.length - 1) ? { cache_control: { type: "ephemeral" } } : {})
+ };
+ return newpart;
}
return {
type: "image",
@@ -75,8 +98,10 @@ class Anthropic extends BaseLLM {
messages: ChatMessage[],
options: CompletionOptions,
): AsyncGenerator {
- const shouldCacheSystemMessage =
- !!this.systemMessage && !!this.cacheSystemMessage;
+ const shouldCacheSystemMessage = !!this.systemMessage && this.cacheBehavior?.cacheSystemMessage;
+ const systemMessage: string = stripImages(
+ messages.filter((m) => m.role === "system")[0]?.content,
+ );
const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
@@ -85,7 +110,7 @@ class Anthropic extends BaseLLM {
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
- ...(shouldCacheSystemMessage
+ ...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
},
@@ -100,7 +125,7 @@ class Anthropic extends BaseLLM {
cache_control: { type: "ephemeral" },
},
]
- : this.systemMessage,
+ : systemMessage,
}),
});
@@ -111,6 +136,7 @@ class Anthropic extends BaseLLM {
}
for await (const value of streamSse(response)) {
+ if (value.type == "message_start") console.log(value);
if (value.delta?.text) {
yield { role: "assistant", content: value.delta.text };
}
diff --git a/core/llm/llms/Azure.ts b/core/llm/llms/Azure.ts
index ce20b4ecc..be7d1c18c 100644
--- a/core/llm/llms/Azure.ts
+++ b/core/llm/llms/Azure.ts
@@ -1,8 +1,18 @@
-import { ModelProvider } from "../../index.js";
+import { LLMOptions, ModelProvider } from "../../index.js";
import OpenAI from "./OpenAI.js";
class Azure extends OpenAI {
static providerName: ModelProvider = "azure";
+
+ static defaultOptions: Partial = {
+ apiVersion: "2024-02-15-preview",
+ apiType: "azure",
+ };
+
+ constructor(options: LLMOptions) {
+ super(options);
+ this.engine = options.model;
+ }
}
export default Azure;
diff --git a/core/llm/llms/Bedrock.ts b/core/llm/llms/Bedrock.ts
index db2603c03..485b87015 100644
--- a/core/llm/llms/Bedrock.ts
+++ b/core/llm/llms/Bedrock.ts
@@ -153,6 +153,7 @@ class Bedrock extends BaseLLM {
try {
return await fromIni({
profile: this.profile,
+ ignoreCache: true
})();
} catch (e) {
console.warn(
diff --git a/core/llm/llms/BedrockImport.ts b/core/llm/llms/BedrockImport.ts
index f53d4b15e..a265c7679 100644
--- a/core/llm/llms/BedrockImport.ts
+++ b/core/llm/llms/BedrockImport.ts
@@ -82,7 +82,8 @@ class BedrockImport extends BaseLLM {
try {
return await
fromIni({
- profile: this.profile
+ profile: this.profile,
+ ignoreCache: true
})();
} catch (e) {
console.warn(
diff --git a/core/llm/llms/Groq.ts b/core/llm/llms/Groq.ts
index 7115bcc32..bc05263c9 100644
--- a/core/llm/llms/Groq.ts
+++ b/core/llm/llms/Groq.ts
@@ -12,6 +12,7 @@ class Groq extends OpenAI {
"llama2-70b": "llama2-70b-4096",
"mistral-8x7b": "mixtral-8x7b-32768",
gemma: "gemma-7b-it",
+ gemma2: "gemma2-9b-it",
"llama3-8b": "llama3-8b-8192",
"llama3-70b": "llama3-70b-8192",
"llama3.1-8b": "llama-3.1-8b-instant",
diff --git a/core/llm/llms/HuggingFaceTGI.ts b/core/llm/llms/HuggingFaceTGI.ts
index 947e15e6f..9636dbc63 100644
--- a/core/llm/llms/HuggingFaceTGI.ts
+++ b/core/llm/llms/HuggingFaceTGI.ts
@@ -3,6 +3,7 @@ import { BaseLLM } from "../index.js";
import { streamSse } from "../stream.js";
class HuggingFaceTGI extends BaseLLM {
+ private static MAX_STOP_TOKENS = 4;
static providerName: ModelProvider = "huggingface-tgi";
static defaultOptions: Partial = {
apiBase: "http://localhost:8080/",
@@ -36,7 +37,10 @@ class HuggingFaceTGI extends BaseLLM {
top_k: options.topK,
presence_penalty: options.presencePenalty,
frequency_penalty: options.frequencyPenalty,
- stop: options.stop,
+ stop: options.stop?.slice(
+ 0,
+ this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS,
+ ),
};
return finalOptions;
diff --git a/core/llm/llms/Ollama.ts b/core/llm/llms/Ollama.ts
index f830b7f0f..3b16d0456 100644
--- a/core/llm/llms/Ollama.ts
+++ b/core/llm/llms/Ollama.ts
@@ -61,7 +61,7 @@ class Ollama extends BaseLLM {
this.completionOptions.stop.push(JSON.parse(value));
} catch (e) {
console.warn(
- "Error parsing stop parameter value \"{value}: ${e}",
+ 'Error parsing stop parameter value "{value}: ${e}',
);
}
break;
@@ -132,11 +132,13 @@ class Ollama extends BaseLLM {
private _convertArgs(
options: CompletionOptions,
prompt: string | ChatMessage[],
+ suffix?: string,
) {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: options.keepAlive ?? 60 * 30, // 30 minutes
+ suffix,
options: {
temperature: options.temperature,
top_p: options.topP,
@@ -248,6 +250,50 @@ class Ollama extends BaseLLM {
}
}
+ supportsFim(): boolean {
+ return true;
+ }
+
+ protected async *_streamFim(
+ prefix: string,
+ suffix: string,
+ options: CompletionOptions,
+ ): AsyncGenerator {
+ const response = await this.fetch(this.getEndpoint("api/generate"), {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${this.apiKey}`,
+ },
+ body: JSON.stringify(this._convertArgs(options, prefix, suffix)),
+ });
+
+ 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 ("response" in j) {
+ yield j.response;
+ } else if ("error" in j) {
+ throw new Error(j.error);
+ }
+ } catch (e) {
+ throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);
+ }
+ }
+ }
+ }
+ }
+
async listModels(): Promise {
const response = await this.fetch(
// localhost was causing fetch failed in pkg binary only for this Ollama endpoint
diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts
index e37b43799..9366a7954 100644
--- a/core/llm/llms/OpenAI.ts
+++ b/core/llm/llms/OpenAI.ts
@@ -264,7 +264,7 @@ class OpenAI extends BaseLLM {
}
}
- async *_streamFim(
+ protected async *_streamFim(
prefix: string,
suffix: string,
options: CompletionOptions,
diff --git a/core/llm/llms/WatsonX.ts b/core/llm/llms/WatsonX.ts
index f7ea473e0..d9b61a3f1 100644
--- a/core/llm/llms/WatsonX.ts
+++ b/core/llm/llms/WatsonX.ts
@@ -20,8 +20,8 @@ class WatsonX extends BaseLLM {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
-
if (
+ this.watsonxFullUrl?.includes("cloud.ibm.com") ||
this.watsonxUrl?.includes("cloud.ibm.com")
) {
// watsonx SaaS
@@ -43,14 +43,12 @@ class WatsonX extends BaseLLM {
};
} else {
// watsonx Software
- if (
- !this.watsonxCreds?.includes(":")
- ) {
- // Using ZenApiKey auth
- return {
- token: this.watsonxCreds ?? "",
- expiration: -1,
- };
+ if (!this.watsonxCreds?.includes(":")) {
+ // Using ZenApiKey auth
+ return {
+ token: this.watsonxCreds ?? "",
+ expiration: -1,
+ };
} else {
// Using username/password auth
const userPass = this.watsonxCreds?.split(":");
@@ -85,7 +83,10 @@ class WatsonX extends BaseLLM {
}
getWatsonxEndpoint(): string {
- return this.watsonxFullUrl ?? `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`;
+ return (
+ this.watsonxFullUrl ??
+ `${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`
+ );
}
static providerName: ModelProvider = "watsonx";
@@ -132,9 +133,8 @@ class WatsonX extends BaseLLM {
protected _getHeaders() {
return {
"Content-Type": "application/json",
- Authorization: `${
- watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
- } ${watsonxConfig.accessToken.token}`,
+ Authorization: `${watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
+ } ${watsonxConfig.accessToken.token}`,
};
}
@@ -178,8 +178,7 @@ class WatsonX extends BaseLLM {
watsonxConfig.accessToken = await this.getBearerToken();
} else {
console.log(
- `Reusing token (expires in ${
- (watsonxConfig.accessToken.expiration - now) / 60
+ `Reusing token (expires in ${(watsonxConfig.accessToken.expiration - now) / 60
} mins)`,
);
}
@@ -191,31 +190,37 @@ class WatsonX extends BaseLLM {
this.watsonxStopToken ??
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
const url = this.getWatsonxEndpoint();
- var response = await this.fetch(
- url,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `${
- watsonxConfig.accessToken.expiration === -1 ? "ZenApiKey" : "Bearer"
- } ${watsonxConfig.accessToken.token}`,
- },
- body: JSON.stringify({
- input: messages[messages.length - 1].content,
- parameters: {
- decoding_method: "greedy",
- max_new_tokens: options.maxTokens ?? 1024,
- min_new_tokens: 1,
- stop_sequences: stopToken ? [stopToken] : [],
- include_stop_sequence: false,
- repetition_penalty: 1,
- },
- model_id: options.model,
- project_id: this.watsonxProjectId
- }),
- },
- );
+ const headers = this._getHeaders();
+
+ const parameters: any = {
+ decoding_method: "greedy",
+ max_new_tokens: options.maxTokens ?? 1024,
+ min_new_tokens: 1,
+ stop_sequences: stopToken ? [stopToken] : [],
+ include_stop_sequence: false,
+ repetition_penalty: 1,
+ };
+ if (!!options.temperature) {
+ parameters.decoding_method = "sample";
+ parameters.temperature = options.temperature;
+ parameters.top_p = options.topP || 1.0;
+ parameters.top_k = options.topK;
+ }
+
+ const payload: any = {
+ input: messages[messages.length - 1].content,
+ parameters: parameters,
+ };
+ if (!this.watsonxFullUrl) {
+ payload.model_id = options.model;
+ payload.project_id = this.watsonxProjectId;
+ }
+
+ var response = await this.fetch(url, {
+ method: "POST",
+ headers: headers,
+ body: JSON.stringify(payload),
+ });
if (!response.ok || response.body === null) {
throw new Error(
@@ -223,7 +228,6 @@ class WatsonX extends BaseLLM {
);
} else {
for await (const value of streamResponse(response)) {
-
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts
index 2b894f418..dedae7795 100644
--- a/core/llm/llms/index.ts
+++ b/core/llm/llms/index.ts
@@ -6,7 +6,6 @@ import {
ModelDescription,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/renderTemplatedString";
-import { DEFAULT_MAX_TOKENS } from "../constants";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Azure from "./Azure";
@@ -112,8 +111,7 @@ export async function llmFromDescription(
model: (desc.model || cls.defaultOptions?.model) ?? "codellama-7b",
maxTokens:
finalCompletionOptions.maxTokens ??
- cls.defaultOptions?.completionOptions?.maxTokens ??
- DEFAULT_MAX_TOKENS,
+ cls.defaultOptions?.completionOptions?.maxTokens,
},
systemMessage,
writeLog,
diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts
index 63712c993..e91e92e06 100644
--- a/core/llm/llms/stubs/ContinueProxy.ts
+++ b/core/llm/llms/stubs/ContinueProxy.ts
@@ -1,23 +1,15 @@
-import { CONTROL_PLANE_URL } from "../../../control-plane/client.js";
+import { ControlPlaneProxyInfo } from "../../../control-plane/analytics/IAnalyticsProvider.js";
import type { LLMOptions, ModelProvider } from "../../../index.js";
import OpenAI from "../OpenAI.js";
class ContinueProxy extends OpenAI {
- private _workOsAccessToken: string | undefined = undefined;
-
- get workOsAccessToken(): string | undefined {
- return this._workOsAccessToken;
+ set controlPlaneProxyInfo(value: ControlPlaneProxyInfo) {
+ this.apiKey = value.workOsAccessToken;
+ this.apiBase = new URL("openai/v1/", value.controlPlaneProxyUrl).toString();
}
- set workOsAccessToken(value: string | undefined) {
- if (this._workOsAccessToken !== value) {
- this._workOsAccessToken = value;
- this.apiKey = value;
- }
- }
static providerName: ModelProvider = "continue-proxy";
static defaultOptions: Partial = {
- apiBase: new URL("/model-proxy/v1", CONTROL_PLANE_URL).toString(),
useLegacyCompletionsEndpoint: false,
};
diff --git a/core/package-lock.json b/core/package-lock.json
index a3332dc01..fe1e4c48d 100644
--- a/core/package-lock.json
+++ b/core/package-lock.json
@@ -13,7 +13,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
- "@continuedev/llm-info": "^1.0.1",
+ "@continuedev/llm-info": "^1.0.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@@ -25,7 +25,8 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
- "dbinfoz": "^0.1.4",
+ "dbinfoz": "^0.11.0",
+ "diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
@@ -38,6 +39,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
+ "lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
@@ -69,6 +71,7 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
+ "@types/diff": "^5.2.2",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
@@ -1340,6 +1343,15 @@
"node": ">=6.9.0"
}
},
+ "node_modules/@babel/helper-compilation-targets/node_modules/lru-cache": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
+ "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
+ "dev": true,
+ "dependencies": {
+ "yallist": "^3.0.2"
+ }
+ },
"node_modules/@babel/helper-compilation-targets/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
@@ -3128,9 +3140,9 @@
}
},
"node_modules/@continuedev/llm-info": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.1.tgz",
- "integrity": "sha512-fmRXuOSwJ9ogBPSDduoedHF3WVg1rge3o8SRRg1hkUagRnxwZqtQj1sS5SjQyAqjQv6VPMGPDEtD77Za/hc4Jg=="
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@continuedev/llm-info/-/llm-info-1.0.2.tgz",
+ "integrity": "sha512-B5VFcZlwlwQg6htbIjCjj3z/pj3I929BzgWowiLzxYC40ag+v3e/hM9EDGWCEdNIT+PDMchAwS67iNB+WhE7qg=="
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.17.19",
@@ -4756,6 +4768,12 @@
"integrity": "sha512-n7RlEEJ+4x4TS7ZQddTmNSxP+zziEG0TNsMfiRIxcIVXt71ENJ9ojeXmGO3wPoTdn7pJcU2xc3CJYMktNT6DPg==",
"peer": true
},
+ "node_modules/@types/diff": {
+ "version": "5.2.2",
+ "resolved": "https://registry.npmjs.org/@types/diff/-/diff-5.2.2.tgz",
+ "integrity": "sha512-qVqLpd49rmJA2nZzLVsmfS/aiiBpfVE95dHhPVwG0NmSBAt+riPxnj53wq2oBq5m4Q2RF1IWFEUpnZTgrQZfEQ==",
+ "dev": true
+ },
"node_modules/@types/follow-redirects": {
"version": "1.14.4",
"resolved": "https://registry.npmjs.org/@types/follow-redirects/-/follow-redirects-1.14.4.tgz",
@@ -6748,9 +6766,9 @@
}
},
"node_modules/dbinfoz": {
- "version": "0.1.4",
- "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.1.4.tgz",
- "integrity": "sha512-MB56+xS571ip7qoXqxdnOUtXebbWaqoZN+S++W51SQYJRSjQFGEIPucNmxgeQlBGJ1vM4mQNV47wzV6fcrezZg==",
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/dbinfoz/-/dbinfoz-0.11.0.tgz",
+ "integrity": "sha512-l7REBd9pwTBI6PWSk/dx+zCpSE2tiJdSKfApeoOajnSgyMJgkwGfhpPO2mV76MLQeKPaSm0mMKxmoqd38SaHmw==",
"dependencies": {
"mysql2": "^3.9.1",
"pg": "^8.11.3",
@@ -6922,6 +6940,14 @@
"resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1312386.tgz",
"integrity": "sha512-DPnhUXvmvKT2dFA/j7B+riVLUt9Q6RKJlcppojL5CoRywJJKLDYnRlw0gTFKfgDPHP5E04UoB71SxoJlVZy8FA=="
},
+ "node_modules/diff": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz",
+ "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==",
+ "engines": {
+ "node": ">=0.3.1"
+ }
+ },
"node_modules/diff-sequences": {
"version": "29.6.3",
"resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz",
@@ -10465,12 +10491,11 @@
"integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q=="
},
"node_modules/lru-cache": {
- "version": "5.1.1",
- "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
- "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==",
- "dev": true,
- "dependencies": {
- "yallist": "^3.0.2"
+ "version": "10.2.2",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.2.2.tgz",
+ "integrity": "sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==",
+ "engines": {
+ "node": "14 || >=16.14"
}
},
"node_modules/mac-ca": {
diff --git a/core/package.json b/core/package.json
index f261f7078..b04da182b 100644
--- a/core/package.json
+++ b/core/package.json
@@ -15,6 +15,7 @@
"@babel/preset-env": "^7.24.7",
"@biomejs/biome": "1.6.4",
"@google/generative-ai": "^0.11.4",
+ "@types/diff": "^5.2.2",
"@types/follow-redirects": "^1.14.4",
"@types/jest": "^29.5.12",
"@types/jquery": "^3.5.29",
@@ -42,7 +43,7 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
- "@continuedev/llm-info": "^1.0.1",
+ "@continuedev/llm-info": "^1.0.2",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@@ -54,7 +55,8 @@
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
- "dbinfoz": "^0.1.4",
+ "dbinfoz": "^0.11.0",
+ "diff": "^7.0.0",
"dotenv": "^16.4.5",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
@@ -67,6 +69,7 @@
"jsdom": "^24.0.0",
"launchdarkly-node-client-sdk": "^3.2.0",
"llm-code-highlighter": "^0.0.14",
+ "lru-cache": "^10.2.2",
"mac-ca": "^3.1.0",
"node-fetch": "^3.3.2",
"node-html-markdown": "^1.3.0",
diff --git a/core/protocol/core.ts b/core/protocol/core.ts
index 73f55946c..d5920ca81 100644
--- a/core/protocol/core.ts
+++ b/core/protocol/core.ts
@@ -1,5 +1,3 @@
-import type { AutocompleteInput } from "../autocomplete/completionProvider";
-import { ProfileDescription } from "../config/ConfigHandler";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@@ -10,12 +8,15 @@ import type {
LLMFullCompletionOptions,
MessageContent,
ModelDescription,
+ ModelRoles,
PersistedSessionInfo,
RangeInFile,
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "../";
+import type { AutocompleteInput } from "../autocomplete/completionProvider";
+import { ProfileDescription } from "../config/ConfigHandler";
export type ProtocolGeneratorType = AsyncGenerator<{
done?: boolean;
@@ -50,7 +51,10 @@ export type ToCoreFromIdeOrWebviewProtocol = {
"devdata/log": [{ tableName: string; data: any }, void];
"config/addOpenAiKey": [string, void];
"config/addModel": [
- { model: SerializedContinueConfig["models"][number] },
+ {
+ model: SerializedContinueConfig["models"][number];
+ role?: keyof ModelRoles;
+ },
void,
];
"config/newPromptFile": [undefined, void];
diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts
index 33a1ae2a9..774da7ee5 100644
--- a/core/protocol/ideWebview.ts
+++ b/core/protocol/ideWebview.ts
@@ -15,7 +15,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
},
];
openUrl: [string, void];
- applyToCurrentFile: [{ text: string }, void];
+ applyToCurrentFile: [{ text: string; streamId: string }, void];
showTutorial: [undefined, void];
showFile: [{ filepath: string }, void];
openConfigJson: [undefined, void];
@@ -26,9 +26,17 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
insertAtCursor: [{ text: string }, void];
copyText: [{ text: string }, void];
"jetbrains/editorInsetHeight": [{ height: number }, void];
+ "vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
+ acceptDiff: [{ filepath: string }, void];
+ rejectDiff: [{ filepath: string }, void];
};
+export interface ApplyState {
+ streamId: string;
+ status: "streaming" | "done" | "closed";
+}
+
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
setTTSActive: [boolean, void];
@@ -61,4 +69,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setupLocalConfig: [undefined, void];
incrementFtc: [undefined, void];
openOnboardingCard: [undefined, void];
+ applyCodeFromChat: [undefined, void];
+ updateApplyState: [ApplyState, void];
};
diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts
new file mode 100644
index 000000000..5f3c6a4be
--- /dev/null
+++ b/core/test/util/dedentAndGetCommonWhitespace.test.ts
@@ -0,0 +1,76 @@
+// File generated by Continue
+import { dedentAndGetCommonWhitespace } from "../../util";
+
+describe("dedentAndGetCommonWhitespace", () => {
+ let originalString: string;
+
+ beforeEach(() => {
+ // Setup any global variables or states if needed
+ originalString = " line1\n line2\n line3";
+ });
+
+ afterEach(() => {
+ // Tear down any changes to global variables or states if needed
+ originalString = "";
+ });
+
+ test("should dedent and return common whitespace for a simple case", () => {
+ const input = " line1\n line2\n line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["line1\nline2\nline3", " "]);
+ });
+
+ test("should handle empty string", () => {
+ const input = "";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["", ""]);
+ });
+
+ test("should handle string with only whitespace", () => {
+ const input = " ";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["", ""]);
+ });
+
+ test("should handle string with mixed whitespace and content", () => {
+ const input = " line1\n line2\n line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual([" line1\nline2\n line3", " "]);
+ });
+
+ test("should handle string with no common leading whitespace", () => {
+ const input = "line1\n line2\n line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual([input, ""]);
+ });
+
+ test("should handle string with empty lines", () => {
+ const input = " line1\n\n line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["line1\n\nline3", " "]);
+ });
+
+ test("should handle string with only empty lines", () => {
+ const input = "\n\n";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["\n\n", ""]);
+ });
+
+ test("should handle string with tabs as whitespace", () => {
+ const input = "\tline1\n\tline2\n\tline3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["line1\nline2\nline3", "\t"]);
+ });
+
+ test("should handle string with mixed tabs and spaces", () => {
+ const input = "\t line1\n\t line2\n\t line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual(["line1\nline2\nline3", "\t "]);
+ });
+
+ test("should handle string with different leading whitespace lengths", () => {
+ const input = " line1\n line2\n line3";
+ const output = dedentAndGetCommonWhitespace(input);
+ expect(output).toEqual([" line1\nline2\n line3", " "]);
+ });
+});
diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts
new file mode 100644
index 000000000..ba72b4520
--- /dev/null
+++ b/core/test/util/getLastNPathParts.test.ts
@@ -0,0 +1,51 @@
+// File generated by Continue
+import { getLastNPathParts } from "../../util";
+
+describe("getLastNPathParts", () => {
+ const SEP_REGEX = /[\\/]+/;
+
+ beforeAll(() => {
+ // Setup code if needed
+ });
+
+ afterAll(() => {
+ // Teardown code if needed
+ });
+
+ test("returns the last N parts of a filepath with forward slashes", () => {
+ const filepath = "home/user/documents/project/file.txt";
+ expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
+ });
+
+ test("returns the last N parts of a filepath with backward slashes", () => {
+ const filepath = "C:\\home\\user\\documents\\project\\file.txt";
+ expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
+ });
+
+ test("returns the last part if N is 1", () => {
+ const filepath = "/home/user/documents/project/file.txt";
+ expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
+ });
+
+ test("returns the entire path if N is greater than the number of parts", () => {
+ const filepath = "home/user/documents/project/file.txt";
+ expect(getLastNPathParts(filepath, 10)).toBe(
+ "home/user/documents/project/file.txt",
+ );
+ });
+
+ test("returns an empty string if N is 0", () => {
+ const filepath = "home/user/documents/project/file.txt";
+ expect(getLastNPathParts(filepath, 0)).toBe("");
+ });
+
+ test("handles paths with mixed forward and backward slashes", () => {
+ const filepath = "home\\user/documents\\project/file.txt";
+ expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
+ });
+
+ test("handles edge case with empty filepath", () => {
+ const filepath = "";
+ expect(getLastNPathParts(filepath, 2)).toBe("");
+ });
+});
diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts
new file mode 100644
index 000000000..da10cdf90
--- /dev/null
+++ b/core/test/util/lcs.test.ts
@@ -0,0 +1,40 @@
+// This file is generated by Continue
+import { longestCommonSubsequence } from "../../util/lcs";
+
+describe("longestCommonSubsequence", () => {
+ beforeAll(() => {
+ // Setup if needed
+ });
+
+ afterAll(() => {
+ // Teardown if needed
+ });
+
+ test("should return the longest common subsequence for non-empty strings", () => {
+ expect(longestCommonSubsequence("abcde", "ace")).toBe("ace");
+ expect(longestCommonSubsequence("abc", "abc")).toBe("abc");
+ expect(longestCommonSubsequence("abc", "def")).toBe("");
+ });
+
+ test("should handle cases where one or both strings are empty", () => {
+ expect(longestCommonSubsequence("", "abc")).toBe("");
+ expect(longestCommonSubsequence("abc", "")).toBe("");
+ expect(longestCommonSubsequence("", "")).toBe("");
+ });
+
+ test("should handle cases with no common subsequence", () => {
+ expect(longestCommonSubsequence("abc", "def")).toBe("");
+ expect(longestCommonSubsequence("xyz", "abc")).toBe("");
+ });
+
+ test("should handle cases with special characters", () => {
+ expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$");
+ expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe("");
+ });
+
+ test("should handle long strings efficiently", () => {
+ const str1 = "a".repeat(1000) + "b".repeat(1000);
+ const str2 = "a".repeat(1000) + "c".repeat(1000);
+ expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000));
+ });
+});
diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts
new file mode 100644
index 000000000..a39a5bc30
--- /dev/null
+++ b/core/test/util/merge.test.ts
@@ -0,0 +1,100 @@
+// File generated by Continue
+import { mergeJson } from "../../util/merge";
+
+describe("mergeJson", () => {
+ it("should merge two simple JSON objects", () => {
+ const first = { a: 1, b: 2 };
+ const second = { b: 3, c: 4 };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 1, b: 3, c: 4 });
+ });
+
+ it('should overwrite values when mergeBehavior is "overwrite"', () => {
+ const first = { a: 1, b: 2 };
+ const second = { b: 3, c: 4 };
+ const result = mergeJson(first, second, "overwrite");
+ expect(result).toEqual({ a: 1, b: 3, c: 4 });
+ });
+
+ it("should merge nested objects", () => {
+ const first = { a: { b: 1 } };
+ const second = { a: { c: 2 } };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: { b: 1, c: 2 } });
+ });
+
+ it("should merge arrays without mergeKeys", () => {
+ const first = { a: [1, 2] };
+ const second = { a: [3, 4] };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: [1, 2, 3, 4] });
+ });
+
+ it("should merge arrays with mergeKeys", () => {
+ const first = {
+ a: [
+ { id: 1, value: "first" },
+ { id: 2, value: "second" },
+ ],
+ };
+ const second = {
+ a: [
+ { id: 2, value: "updated" },
+ { id: 3, value: "third" },
+ ],
+ };
+ const mergeKeys = {
+ a: (item1: any, item2: any) => item1.id === item2.id,
+ };
+ const result = mergeJson(first, second, undefined, mergeKeys);
+ expect(result).toEqual({
+ a: [
+ { id: 1, value: "first" },
+ { id: 2, value: "updated" },
+ { id: 3, value: "third" },
+ ],
+ });
+ });
+
+ it("should handle non-object values correctly", () => {
+ const first = { a: 1, b: "string", c: true };
+ const second = { a: 2, b: "new string", c: false };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 2, b: "new string", c: false });
+ });
+
+ it("should handle null and undefined values correctly", () => {
+ const first = { a: 1, b: null };
+ const second = { b: 2, c: undefined };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 1, b: 2, c: undefined });
+ });
+
+ it("should handle empty objects", () => {
+ const first = {};
+ const second = { a: 1 };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 1 });
+ });
+
+ it("should handle empty second object", () => {
+ const first = { a: 1 };
+ const second = {};
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 1 });
+ });
+
+ it("should handle errors gracefully", () => {
+ const first = { a: 1 };
+ const second = { b: () => {} }; // Functions are not serializable in JSON
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: 1, b: expect.any(Function) });
+ });
+
+ it("should merge deeply nested objects", () => {
+ const first = { a: { b: { c: 1 } } };
+ const second = { a: { b: { d: 2 } } };
+ const result = mergeJson(first, second);
+ expect(result).toEqual({ a: { b: { c: 1, d: 2 } } });
+ });
+});
diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts
new file mode 100644
index 000000000..e0a4df67a
--- /dev/null
+++ b/core/test/util/ranges/getRangeInString.test.ts
@@ -0,0 +1,105 @@
+// This file is generated by Continue
+
+import { getRangeInString } from "../../../util/ranges";
+
+describe.skip("getRangeInString", () => {
+ let content: string;
+
+ beforeEach(() => {
+ content = `Line 1
+Line 2
+Line 3
+Line 4
+Line 5`;
+ });
+
+ afterEach(() => {
+ content = "";
+ });
+
+ test("should return substring within the same line", () => {
+ const range = {
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 4 },
+ };
+ expect(getRangeInString(content, range)).toBe("Line");
+ });
+
+ test("should return substring spanning multiple lines", () => {
+ const range = {
+ start: { line: 1, character: 2 },
+ end: { line: 3, character: 3 },
+ };
+ const expected = `ne 2
+Line 3
+Line 4`;
+ expect(getRangeInString(content, range)).toBe(expected);
+ });
+
+ test("should handle range that starts and ends at the same character", () => {
+ const range = {
+ start: { line: 2, character: 0 },
+ end: { line: 2, character: 0 },
+ };
+ expect(getRangeInString(content, range)).toBe("L");
+ });
+
+ test("should handle range that spans entire content", () => {
+ const range = {
+ start: { line: 0, character: 0 },
+ end: { line: 4, character: 5 },
+ };
+ expect(getRangeInString(content, range)).toBe(content);
+ });
+
+ test("should handle range that spans to the end of the last line", () => {
+ const range = {
+ start: { line: 3, character: 2 },
+ end: { line: 4, character: 5 },
+ };
+ const expected = `ne 4
+Line 5`;
+ expect(getRangeInString(content, range)).toBe(expected);
+ });
+
+ test("should handle empty content", () => {
+ content = "";
+ const range = {
+ start: { line: 0, character: 0 },
+ end: { line: 0, character: 0 },
+ };
+ expect(getRangeInString(content, range)).toBe("");
+ });
+
+ test("should handle invalid range (start line > end line)", () => {
+ const range = {
+ start: { line: 3, character: 0 },
+ end: { line: 2, character: 0 },
+ };
+ expect(getRangeInString(content, range)).toBe("");
+ });
+
+ test("should handle invalid range (start character > end character on same line)", () => {
+ const range = {
+ start: { line: 1, character: 5 },
+ end: { line: 1, character: 2 },
+ };
+ expect(getRangeInString(content, range)).toBe("");
+ });
+
+ test("should handle range that starts and ends at the same line but different characters", () => {
+ const range = {
+ start: { line: 1, character: 2 },
+ end: { line: 1, character: 6 },
+ };
+ expect(getRangeInString(content, range)).toBe("ne 2");
+ });
+
+ test("should handle range that starts and ends at the same line and same characters", () => {
+ const range = {
+ start: { line: 1, character: 2 },
+ end: { line: 1, character: 2 },
+ };
+ expect(getRangeInString(content, range)).toBe("n");
+ });
+});
diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts
new file mode 100644
index 000000000..397dbc1a8
--- /dev/null
+++ b/core/test/util/ranges/intersection.test.ts
@@ -0,0 +1,123 @@
+// This file is generated by Continue
+
+import { intersection } from "../../../util/ranges";
+
+interface Position {
+ line: number;
+ character: number;
+}
+
+interface Range {
+ start: Position;
+ end: Position;
+}
+
+describe("intersection", () => {
+ let rangeA: Range;
+ let rangeB: Range;
+
+ beforeEach(() => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 3, character: 5 },
+ };
+
+ rangeB = {
+ start: { line: 2, character: 2 },
+ end: { line: 4, character: 0 },
+ };
+ });
+
+ test("returns correct intersection for overlapping ranges", () => {
+ const result = intersection(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 2, character: 2 },
+ end: { line: 3, character: 5 },
+ });
+ });
+
+ test("returns null for non-overlapping ranges", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 2, character: 0 },
+ };
+
+ rangeB = {
+ start: { line: 3, character: 0 },
+ end: { line: 4, character: 0 },
+ };
+
+ const result = intersection(rangeA, rangeB);
+ expect(result).toBeNull();
+ });
+
+ // TODO
+ test.skip("returns correct intersection for single line overlap", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 5 },
+ };
+
+ rangeB = {
+ start: { line: 1, character: 3 },
+ end: { line: 2, character: 0 },
+ };
+
+ const result = intersection(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 1, character: 3 },
+ end: { line: 1, character: 5 },
+ });
+ });
+
+ test("returns null for single line non-overlapping ranges", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 2 },
+ };
+
+ rangeB = {
+ start: { line: 1, character: 3 },
+ end: { line: 1, character: 5 },
+ };
+
+ const result = intersection(rangeA, rangeB);
+ expect(result).toBeNull();
+ });
+
+ test("returns correct intersection when one range is fully within another", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 4, character: 5 },
+ };
+
+ rangeB = {
+ start: { line: 2, character: 2 },
+ end: { line: 3, character: 3 },
+ };
+
+ const result = intersection(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 2, character: 2 },
+ end: { line: 3, character: 3 },
+ });
+ });
+
+ test("returns correct intersection when ranges touch at the edge", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 2, character: 0 },
+ };
+
+ rangeB = {
+ start: { line: 2, character: 0 },
+ end: { line: 3, character: 0 },
+ };
+
+ const result = intersection(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 2, character: 0 },
+ end: { line: 2, character: 0 },
+ });
+ });
+});
diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts
new file mode 100644
index 000000000..0468df1cd
--- /dev/null
+++ b/core/test/util/ranges/maxMinPosition.test.ts
@@ -0,0 +1,70 @@
+import { maxPosition, minPosition } from "../../../util/ranges";
+
+// This file is generated by Continue
+interface Position {
+ line: number;
+ character: number;
+}
+
+describe("Position comparison functions", () => {
+ let pos1: Position;
+ let pos2: Position;
+ let pos3: Position;
+ let pos4: Position;
+
+ beforeAll(() => {
+ // Setup: Initializing positions
+ pos1 = { line: 1, character: 5 };
+ pos2 = { line: 2, character: 3 };
+ pos3 = { line: 1, character: 7 };
+ pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
+ });
+
+ describe("maxPosition", () => {
+ it("should return the position with the greater line number", () => {
+ expect(maxPosition(pos1, pos2)).toEqual(pos2);
+ });
+
+ it("should return the position with the greater character number when lines are equal", () => {
+ expect(maxPosition(pos1, pos3)).toEqual(pos3);
+ });
+
+ it("should return the first position when both positions are equal", () => {
+ expect(maxPosition(pos2, pos4)).toEqual(pos2);
+ });
+
+ it("should handle positions with negative line numbers", () => {
+ const posNegative = { line: -1, character: 0 };
+ expect(maxPosition(posNegative, pos1)).toEqual(pos1);
+ });
+
+ it("should handle positions with negative character numbers", () => {
+ const posNegativeChar = { line: 1, character: -1 };
+ expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
+ });
+ });
+
+ describe("minPosition", () => {
+ it("should return the position with the lesser line number", () => {
+ expect(minPosition(pos1, pos2)).toEqual(pos1);
+ });
+
+ it("should return the position with the lesser character number when lines are equal", () => {
+ expect(minPosition(pos1, pos3)).toEqual(pos1);
+ });
+
+ it("should return the first position when both positions are equal", () => {
+ expect(minPosition(pos2, pos4)).toEqual(pos2);
+ });
+
+ it("should handle positions with negative line numbers", () => {
+ const posNegative = { line: -1, character: 0 };
+ expect(minPosition(posNegative, pos1)).toEqual(posNegative);
+ });
+
+ it("should handle positions with negative character numbers", () => {
+ const posNegativeChar = { line: 1, character: -1 };
+ expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
+ });
+ });
+});
diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts
new file mode 100644
index 000000000..9d06a97b4
--- /dev/null
+++ b/core/test/util/ranges/union.test.ts
@@ -0,0 +1,92 @@
+import { union } from "../../../util/ranges";
+
+// This file is generated by Continue
+interface Position {
+ line: number;
+ character: number;
+}
+
+interface Range {
+ start: Position;
+ end: Position;
+}
+
+describe("union", () => {
+ let rangeA: Range;
+ let rangeB: Range;
+
+ beforeEach(() => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 3, character: 5 },
+ };
+
+ rangeB = {
+ start: { line: 2, character: 3 },
+ end: { line: 4, character: 2 },
+ };
+ });
+
+ test("should return the union of two overlapping ranges", () => {
+ const result = union(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 1, character: 0 },
+ end: { line: 4, character: 2 },
+ });
+ });
+
+ test("should return the union when ranges are identical", () => {
+ const result = union(rangeA, rangeA);
+ expect(result).toEqual(rangeA);
+ });
+
+ test("should return the union when ranges do not overlap but are adjacent", () => {
+ rangeB = {
+ start: { line: 3, character: 5 },
+ end: { line: 4, character: 2 },
+ };
+ const result = union(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 1, character: 0 },
+ end: { line: 4, character: 2 },
+ });
+ });
+
+ test("should return the union when one range is completely within the other", () => {
+ rangeB = {
+ start: { line: 2, character: 1 },
+ end: { line: 2, character: 4 },
+ };
+ const result = union(rangeA, rangeB);
+ expect(result).toEqual(rangeA);
+ });
+
+ test("should return the union when ranges do not overlap and are not adjacent", () => {
+ rangeB = {
+ start: { line: 4, character: 3 },
+ end: { line: 5, character: 1 },
+ };
+ const result = union(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 1, character: 0 },
+ end: { line: 5, character: 1 },
+ });
+ });
+
+ // TODO
+ test.skip("should handle edge case where start and end lines are the same", () => {
+ rangeA = {
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 5 },
+ };
+ rangeB = {
+ start: { line: 1, character: 3 },
+ end: { line: 1, character: 7 },
+ };
+ const result = union(rangeA, rangeB);
+ expect(result).toEqual({
+ start: { line: 1, character: 0 },
+ end: { line: 1, character: 7 },
+ });
+ });
+});
diff --git a/core/util/fetchFavicon.ts b/core/util/fetchFavicon.ts
new file mode 100644
index 000000000..8b1c8616a
--- /dev/null
+++ b/core/util/fetchFavicon.ts
@@ -0,0 +1,65 @@
+import { JSDOM } from "jsdom";
+
+export async function findFaviconPath(url: URL): Promise {
+ const baseUrl = `${url.protocol}//${url.hostname}`;
+
+ try {
+ const response = await fetch(baseUrl);
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const html = await response.text();
+ const dom = new JSDOM(html);
+ const document = dom.window.document;
+
+ // Look for favicon in tags
+ const linkTags = document.querySelectorAll('link[rel*="icon"]');
+
+ for (const link of linkTags) {
+ const href = link.getAttribute("href");
+ if (href) {
+ return new URL(href, baseUrl).toString();
+ }
+ }
+ } catch (error) {
+ console.debug(`Failed to fetch favicon for ${baseUrl}: ${error}`);
+ }
+
+ console.debug(`Failed to find favicon for ${baseUrl}`);
+ return undefined;
+}
+
+export async function getFaviconBase64(
+ faviconUrl: string,
+): Promise {
+ try {
+ const response = await fetch(faviconUrl);
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const arrayBuffer = await response.arrayBuffer();
+ const base64 = btoa(
+ new Uint8Array(arrayBuffer).reduce(
+ (data, byte) => data + String.fromCharCode(byte),
+ "",
+ ),
+ );
+ const mimeType = response.headers.get("content-type") || "image/x-icon";
+
+ return `data:${mimeType};base64,${base64}`;
+ } catch (error) {
+ console.debug(`Failed to fetch favicon from ${faviconUrl}: ${error}`);
+ return undefined;
+ }
+}
+
+export async function fetchFavicon(url: URL): Promise {
+ const faviconPath = await findFaviconPath(url);
+ if (faviconPath) {
+ return getFaviconBase64(faviconPath);
+ }
+ return undefined;
+}
diff --git a/core/util/generateRepoMap.ts b/core/util/generateRepoMap.ts
new file mode 100644
index 000000000..785a62c41
--- /dev/null
+++ b/core/util/generateRepoMap.ts
@@ -0,0 +1,213 @@
+import fs from "node:fs";
+import path from "node:path";
+import { IDE, ILLM } from "..";
+import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
+import { walkDirAsync } from "../indexing/walkDir";
+import { pruneLinesFromTop } from "../llm/countTokens";
+import { getRepoMapFilePath } from "./paths";
+
+export interface RepoMapOptions {
+ includeSignatures?: boolean;
+ dirs?: string[];
+}
+
+class RepoMapGenerator {
+ private llm: ILLM;
+ private ide: IDE;
+ private options: RepoMapOptions;
+ private maxRepoMapTokens: number;
+
+ private repoMapPath: string = getRepoMapFilePath();
+ private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath);
+ private contentTokens: number = 0;
+ private repoMapDirs: string[] = [];
+ private allPathsInDirs: Set = new Set();
+ private pathsInDirsWithSnippets: Set = new Set();
+
+ private BATCH_SIZE = 100;
+ private REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5;
+ private PREAMBLE =
+ "Below is a repository map. \n" +
+ "For each file in the codebase, " +
+ "this map contains the name of the file, and the signature for any " +
+ "classes, methods, or functions in the file.\n\n";
+
+ constructor(llm: ILLM, ide: IDE, options: RepoMapOptions) {
+ this.llm = llm;
+ this.ide = ide;
+ this.options = options;
+ this.maxRepoMapTokens =
+ llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
+ }
+
+ async generate(): Promise {
+ this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs());
+ this.allPathsInDirs = await this.getAllPathsInDirs();
+
+ await this.initializeWriteStream();
+ await this.processPathsAndSignatures();
+
+ this.writeStream.end();
+ this.logRepoMapGeneration();
+
+ return fs.readFileSync(this.repoMapPath, "utf8");
+ }
+
+ private async initializeWriteStream(): Promise {
+ await this.writeToStream(this.PREAMBLE);
+ this.contentTokens += this.llm.countTokens(this.PREAMBLE);
+ }
+
+ private async getAllPathsInDirs(): Promise> {
+ const paths = new Set();
+
+ for (const dir of this.repoMapDirs) {
+ for await (const filepath of walkDirAsync(dir, this.ide)) {
+ paths.add(filepath.replace(dir, "").slice(1));
+ }
+ }
+
+ return paths;
+ }
+
+ private async processPathsAndSignatures(): Promise {
+ let offset = 0;
+ while (true) {
+ const { groupedByPath, hasMore } =
+ await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
+ this.repoMapDirs,
+ offset,
+ this.BATCH_SIZE,
+ );
+ await this.processBatch(groupedByPath);
+ if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
+ break;
+ }
+ offset += this.BATCH_SIZE;
+ }
+ await this.writeRemainingPaths();
+ }
+
+ private async processBatch(
+ groupedByPath: Record,
+ ): Promise {
+ for (const [absolutePath, signatures] of Object.entries(groupedByPath)) {
+ const content = await this.processFile(absolutePath, signatures);
+
+ if (content) {
+ await this.writeToStream(content);
+ }
+ }
+ }
+
+ private async processFile(
+ absolutePath: string,
+ signatures: string[],
+ ): Promise {
+ const workspaceDir =
+ this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || "";
+ const relativePath = path.relative(workspaceDir, absolutePath);
+
+ let fileContent: string;
+
+ try {
+ fileContent = await fs.promises.readFile(absolutePath, "utf8");
+ } catch (err) {
+ console.error(
+ "Failed to read file:\n" +
+ ` Path: ${absolutePath}\n` +
+ ` Error: ${err instanceof Error ? err.message : String(err)}`,
+ );
+
+ return;
+ }
+
+ const filteredSignatures = signatures.filter(
+ (signature) => signature.trim() !== fileContent.trim(),
+ );
+
+ if (filteredSignatures.length > 0) {
+ this.pathsInDirsWithSnippets.add(relativePath);
+ }
+
+ return this.generateContentForPath(relativePath, filteredSignatures);
+ }
+
+ private generateContentForPath(
+ relativePath: string,
+ signatures: string[],
+ ): string {
+ if (this.options.includeSignatures === false) {
+ return `${relativePath}\n`;
+ }
+
+ let content = `${relativePath}:\n`;
+
+ for (const signature of signatures.slice(0, -1)) {
+ content += `${this.indentMultilineString(signature)}\n\t...\n`;
+ }
+
+ content += `${this.indentMultilineString(
+ signatures[signatures.length - 1],
+ )}\n\n`;
+
+ return content;
+ }
+
+ private async writeToStream(content: string): Promise {
+ const tokens = this.llm.countTokens(content);
+
+ if (this.contentTokens + tokens > this.maxRepoMapTokens) {
+ content = pruneLinesFromTop(
+ content,
+ this.maxRepoMapTokens - this.contentTokens,
+ this.llm.model,
+ );
+ }
+
+ this.contentTokens += this.llm.countTokens(content);
+
+ await new Promise((resolve) => this.writeStream.write(content, resolve));
+ }
+
+ private async writeRemainingPaths(): Promise {
+ const pathsWithoutSnippets = new Set(
+ [...this.allPathsInDirs].filter(
+ (x) => !this.pathsInDirsWithSnippets.has(x),
+ ),
+ );
+
+ if (pathsWithoutSnippets.size > 0) {
+ await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n"));
+ }
+ }
+
+ private logRepoMapGeneration(): void {
+ console.debug(
+ `Generated repo map for ${this.repoMapDirs.join(", ")} at ${
+ this.repoMapPath
+ }`,
+ );
+ if (this.contentTokens >= this.maxRepoMapTokens) {
+ console.debug(
+ "Full repo map was unable to be generated due to context window limitations",
+ );
+ }
+ }
+
+ private indentMultilineString(str: string) {
+ return str
+ .split("\n")
+ .map((line: any) => "\t" + line)
+ .join("\n");
+ }
+}
+
+export default async function generateRepoMap(
+ llm: ILLM,
+ ide: IDE,
+ options: RepoMapOptions,
+): Promise {
+ const generator = new RepoMapGenerator(llm, ide, options);
+ return generator.generate();
+}
diff --git a/core/util/parameters.ts b/core/util/parameters.ts
index b413a869e..88c7d38a6 100644
--- a/core/util/parameters.ts
+++ b/core/util/parameters.ts
@@ -20,6 +20,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = {
recentLinePrefixMatchMinLength: 7,
disableInFiles: undefined,
useImports: true,
+ useRootPathContext: true,
};
export const COUNT_COMPLETION_REJECTED_AFTER = 10_000;
diff --git a/core/util/repoMap.ts b/core/util/repoMap.ts
deleted file mode 100644
index 6c0a73e1f..000000000
--- a/core/util/repoMap.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import fs from "node:fs";
-import path from "node:path";
-import { IDE, ILLM } from "..";
-import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
-import { walkDirAsync } from "../indexing/walkDir";
-import { pruneLinesFromTop } from "../llm/countTokens";
-import { getRepoMapFilePath } from "./paths";
-
-const repoMapPreamble =
- "Below is a repository map. \n" +
- "For each file in the codebase, " +
- "this map contains the name of the file, and the signature for any " +
- "classes, methods, or functions in the file.\n\n";
-
-// The max percent of the context window we will take
-const REPO_MAX_CONTEXT_LENGTH_RATIO = 0.5;
-
-function indentMultilineString(str: string) {
- return str
- .split("\n")
- .map((line: any) => "\t" + line)
- .join("\n");
-}
-
-export interface RepoMapOptions {
- signatures?: boolean;
- dirs?: string[];
-}
-
-async function generateRepoMap(llm: ILLM, ide: IDE, options?: RepoMapOptions) {
- const repoMapPath = getRepoMapFilePath();
- const dirs = options?.dirs ?? (await ide.getWorkspaceDirs());
- const maxRepoMapTokens = llm.contextLength * REPO_MAX_CONTEXT_LENGTH_RATIO;
-
- const pathsWithoutSnippets = new Set();
- for (const dir of dirs) {
- for await (const filepath of walkDirAsync(dir, ide)) {
- pathsWithoutSnippets.add(filepath.replace(dir, "").slice(1));
- }
- }
-
- if (fs.existsSync(repoMapPath)) {
- console.debug(`Overwriting existing repo map at ${repoMapPath}`);
- }
-
- const writeStream = fs.createWriteStream(repoMapPath);
- await new Promise((resolve) => writeStream.write(repoMapPreamble, resolve));
-
- let curTokens = llm.countTokens(repoMapPreamble);
- let offset = 0;
- const batchSize = 100;
-
- while (true) {
- const { groupedByPath, hasMore } =
- await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
- dirs,
- offset,
- batchSize,
- );
-
- let content = "";
-
- for (const [absolutePath, signatures] of Object.entries(groupedByPath)) {
- const workspaceDir =
- dirs.find((dir) => absolutePath.startsWith(dir)) || "";
-
- const relativePath = path.relative(workspaceDir, absolutePath);
-
- pathsWithoutSnippets.delete(relativePath);
-
- if (options?.signatures !== false) {
- content += `${relativePath}:\n`;
- for (const signature of signatures.slice(0, -1)) {
- content += `${indentMultilineString(signature)}\n\t...\n`;
- }
- if (signatures.length > 0) {
- // Don't add the trailing ellipsis for the last entry
- content += `${indentMultilineString(
- signatures[signatures.length - 1],
- )}\n\n`;
- }
- } else {
- // No signatures mode
- content += `${relativePath}\n`;
- }
- }
-
- const contentTokens = llm.countTokens(content);
-
- if (curTokens + contentTokens >= maxRepoMapTokens) {
- // Fit what we can, then stop
- const prunedContent = pruneLinesFromTop(
- content,
- maxRepoMapTokens - curTokens,
- llm.model,
- );
- await new Promise((resolve) => writeStream.write(prunedContent, resolve));
- break;
- } else {
- await new Promise((resolve) => writeStream.write(content, resolve));
- }
-
- curTokens += contentTokens;
-
- if (!hasMore) {
- break;
- }
-
- offset += batchSize;
- }
-
- const content = Array.from(pathsWithoutSnippets).join("\n");
- if (content.length > 0) {
- await new Promise((resolve) => writeStream.write(content, resolve));
- }
-
- writeStream.end();
- console.debug(`Generated repo map at ${repoMapPath}`);
-
- if (curTokens >= maxRepoMapTokens) {
- console.debug(
- "Full repo map was unable to be genereated due to context window limitations",
- );
- }
-
- const repoMap = fs.readFileSync(repoMapPath, "utf8");
-
- return repoMap;
-}
-
-export default generateRepoMap;
diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts
index 204e2e3df..08cfe64d1 100644
--- a/core/util/treeSitter.ts
+++ b/core/util/treeSitter.ts
@@ -45,6 +45,7 @@ export const supportedLanguages: { [key: string]: string } = {
mjs: "javascript",
cjs: "javascript",
py: "python",
+ ipynb: "python",
pyw: "python",
pyi: "python",
el: "elisp",
@@ -128,6 +129,11 @@ export async function getLanguageForFile(
export enum TSQueryType {
CodeSnippets = "code-snippet-queries",
Imports = "import-queries",
+ // Used in RootPathContextService.ts
+ FunctionDeclaration = "root-path-context-queries/function_declaration",
+ MethodDefinition = "root-path-context-queries/method_definition",
+ FunctionDefinition = "root-path-context-queries/function_definition",
+ MethodDeclaration = "root-path-context-queries/method_declaration",
}
export async function getQueryForFile(
diff --git a/docs/docs/chat/context-selection.md b/docs/docs/chat/context-selection.md
index 2e2e7aa3d..ebdb41185 100644
--- a/docs/docs/chat/context-selection.md
+++ b/docs/docs/chat/context-selection.md
@@ -19,27 +19,27 @@ You can include the currently open file as context by pressing `cmd/ctrl + opt +
## Specific file
-You can include a specific file in your current workspace as context by typing [`@files`](../customize/context-providers.md#files) and selecting the file.
+You can include a specific file in your current workspace as context by typing [`@Files`](../customize/context-providers.md#files) and selecting the file.
## Specific folder
-You can include a folder in your current workspace as context by typing [`@directory`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected directory.
+You can include a folder in your current workspace as context by typing [`@Folder`](../customize/context-providers.md#folders) and selecting the directory. It [works like `@Codebase`](../customize/deep-dives/codebase.md) but only includes the files in the selected folder.
## Entire codebase
-You can include your entire codebase as context by typing [`@codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @codebase works [here](../customize/deep-dives/codebase.md).
+You can include your entire codebase as context by typing [`@Codebase`](../customize/context-providers.md#codebase-retrieval). You can learn about how @Codebase works [here](../customize/deep-dives/codebase.md).
## Documentation site
-You can include a documentation site as context by typing [`@docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @docs works [here](../customize/deep-dives/docs.md).
+You can include a documentation site as context by typing [`@Docs`](../customize/context-providers.md#documentation) and selecting the documentation site. You can learn about how @Docs works [here](../customize/deep-dives/docs.md).
## Terminal contents
-You can include the contents of the terminal in your IDE as context by typing [`@terminal`](../customize/context-providers.md#terminal).
+You can include the contents of the terminal in your IDE as context by typing [`@Terminal`](../customize/context-providers.md#terminal).
## Git diff
-You can include all of the changes you've made to your current branch by typing [`@diff`](../customize/context-providers.md#git-diff).
+You can include all of the changes you've made to your current branch by typing [`@Git Diff`](../customize/context-providers.md#git-diff).
## Other context
diff --git a/docs/docs/chat/how-it-works.md b/docs/docs/chat/how-it-works.md
index 7d0d382a5..b5e8aaece 100644
--- a/docs/docs/chat/how-it-works.md
+++ b/docs/docs/chat/how-it-works.md
@@ -11,4 +11,4 @@ The model response is then streamed directly back to the sidebar. Each code sect
If you would like to view the exact prompt that is sent to the model during Chat, you can [view this in the prompt logs](troubleshooting.md#llm-prompt-logs).
-You can learn more about how `@codebase` works [here](../customize/deep-dives/codebase.md) and `@docs` [here](../customize/deep-dives/docs.md).
+You can learn more about how `@Codebase` works [here](../customize/deep-dives/codebase.md) and `@Docs` [here](../customize/deep-dives/docs.md).
diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md
index a91720213..943d5e7ac 100644
--- a/docs/docs/chat/how-to-customize.md
+++ b/docs/docs/chat/how-to-customize.md
@@ -7,7 +7,7 @@ sidebar_position: 5
There are a number of different ways to customize Chat
-- You can configure [`@codebase`](../customize/deep-dives/codebase.md)
+- You can configure [`@Codebase`](../customize/deep-dives/codebase.md)
- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md)
-- You can configure [`@docs`](../customize/deep-dives/docs.md)
+- You can configure [`@Docs`](../customize/deep-dives/docs.md)
- You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.md)
diff --git a/docs/docs/chat/how-to-use-it.md b/docs/docs/chat/how-to-use-it.md
index 37e8384ab..509702b4f 100644
--- a/docs/docs/chat/how-to-use-it.md
+++ b/docs/docs/chat/how-to-use-it.md
@@ -10,7 +10,7 @@ sidebar_position: 1
## How to use it
-Chat makes it easy to ask for help from an LLM without needing to leave the IDE. You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you want you want, then you can send follow up messages to clarify and adjust its approach until the task is completed.
+Chat makes it easy to ask for help from an LLM without needing to leave the IDE. You send it a task, including any relevant information, and it replies with the text / code most likely to complete the task. If it does not give you what you want, then you can send follow up messages to clarify and adjust its approach until the task is completed.
Chat is best used to understand and iterate on code or as a replacement for search engine queries.
@@ -28,7 +28,7 @@ If there is information from the codebase, documentation, IDE, or other tools th
## Apply generated code to your file
-When the LLM replies with code, you can hover over the top right of the code block and select “Apply to current file” to update the existing code in the editor to this new version.
+When the LLM replies with edits to a file, you can click the “Apply” button. This will update the existing code in the editor to reflect the suggested changes.
## Start a fresh session for a new task
@@ -36,4 +36,4 @@ Once you complete a task and want to start a new one, press `cmd/ctrl + L` (VS C
## Switch between different models
-If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’`
\ No newline at end of file
+If you have configured multiple models, you can switch between models using the dropdown or by pressing `cmd/ctrl + ’`
diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md
index 23979bf94..2b3224543 100644
--- a/docs/docs/customize/context-providers.md
+++ b/docs/docs/customize/context-providers.md
@@ -6,164 +6,259 @@ keywords: [context, "@", provider, LLM]
Context Providers allow you to type '@' and see a dropdown of content that can all be fed to the LLM as context. Every context provider is a plugin, which means if you want to reference some source of information that you don't see here, you can request (or build!) a new context provider.
-As an example, say you are working on solving a new GitHub Issue. You type '@issue' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.
+As an example, say you are working on solving a new GitHub Issue. You type '@Isse' and select the one you are working on. Continue can now see the issue title and contents. You also know that the issue is related to the files 'readme.md' and 'helloNested.py', so you type '@readme' and '@hello' to find and select them. Now these 3 "Context Items" are displayed inline with the rest of your input.

## Built-in Context Providers
-To use any of the built-in context providers, open `~/.continue/config.json` and add it to the `contextProviders` list.
+To use any of the built-in context providers, open `config.json` and add it to the `contextProviders` list.
-### Files
+### `@File`
-Type '@file' to reference any file in your current workspace.
+Reference any file in your current workspace.
-```json
-{ "name": "file" }
-```
-
-### Code
-
-Type '@code' to reference specific functions or classes from throughout your project.
-
-```json
-{ "name": "code" }
-```
-
-### Git Diff
-
-Type '@diff' to reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
-
-```json
-{ "name": "diff" }
-```
-
-### Terminal
-
-Type '@terminal' to reference the contents of your IDE's terminal.
-
-```json
-{ "name": "terminal" }
-```
-
-### Documentation
-
-Type `@docs` to index and retrieve snippets from any documentation site.
-
-```json
-{ "name": "docs" }
-```
-
-To learn more, visit `[@docs](customize/deep-dives/docs.md)`.
-
-### Open Files
-
-Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
-
-```json
-{ "name": "open", "params": { "onlyPinned": true } }
-```
-
-### Codebase Retrieval
-
-Type '@codebase' to automatically retrieve the most relevant snippets from your codebase. Read more about indexing and retrieval [here](customize/deep-dives/codebase.md).
-
-```json
-{ "name": "codebase" }
-```
-
-### Folders
-
-Type '@folder' to use the same retrieval mechanism as '@codebase', but only on a single folder.
-
-```json
-{ "name": "folder" }
-```
-
-### Exact Search
-
-Type '@search' to reference the results of codebase search, just like the results you would get from VS Code search. This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
-
-```json
-{ "name": "search" }
-```
-
-### URL
-
-Type '@url' and input a URL, then Continue will convert it to a markdown document to pass to the model.
-
-```json
-{ "name": "url" }
-```
-
-### File Tree
-
-Type '@tree' to reference the structure of your current workspace. The LLM will be able to see the nested directory structure of your project.
-
-```json
-{ "name": "tree" }
-```
-
-### Google
-
-Type '@google' to reference the results of a Google search. For example, type "@google python tutorial" if you want to search and discuss ways of learning Python.
-
-```json
+```json title="config.json"
{
- "name": "google",
- "params": { "serperApiKey": "" }
+ "contextProviders": [
+ {
+ "name": "file"
+ }
+ ]
}
```
+### `@Code`
+
+Reference specific functions or classes from throughout your project.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "code"
+ }
+ ]
+}
+```
+
+### `@Git Diff`
+
+Reference all of the changes you've made to your current branch. This is useful if you want to summarize what you've done or ask for a general review of your work before committing.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "diff"
+ }
+ ]
+}
+```
+
+### `@Terminal`
+
+Reference the contents of your IDE's terminal.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "terminal"
+ }
+ ]
+}
+```
+
+### `@Docs`
+
+Reference the contents from any documentation site.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "docs"
+ }
+ ]
+}
+```
+
+Note that this will only enable the `@Docs` context provider.
+
+To use it, you need to add a documentation site to your `config.json`. See the [docs](../customize/deep-dives/docs.md) page for more information.
+
+### `@Open`
+
+Reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "open",
+ "params": {
+ "onlyPinned": true
+ }
+ }
+ ]
+}
+```
+
+### `@Codebase`
+
+Reference the most relevant snippets from your codebase.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "codebase"
+ }
+ ]
+}
+```
+
+Read more about indexing and retrieval [here](../customize/deep-dives/codebase.md).
+
+### `@Folder`
+
+Uses the same retrieval mechanism as `@Codebase`, but only on a single folder.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "folder"
+ }
+ ]
+}
+```
+
+### `@Search`
+
+Reference the results of codebase search, just like the results you would get from VS Code search.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "search"
+ }
+ ]
+}
+```
+
+This context provider is powered by [ripgrep](https://github.com/BurntSushi/ripgrep).
+
+### `@Url`
+
+Reference the markdown converted contents of a given URL.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "url"
+ }
+ ]
+}
+```
+
+### `@Tree`
+
+Reference the structure of your current workspace.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "tree"
+ }
+ ]
+}
+```
+
+### `@Google`
+
+Reference the results of a Google search.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "google",
+ "params": {
+ "serperApiKey": ""
+ }
+ }
+ ]
+}
+```
+
+For example, type "@Google python tutorial" if you want to search and discuss ways of learning Python.
+
Note: You can get an API key for free at [serper.dev](https://serper.dev).
-### GitHub Issues
+### `@Isse`
-Type '@issue' to reference the conversation in a GitHub issue. Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited:
+Reference the conversation in a GitHub issue.
-```json
+```json title="config.json"
{
- "name": "issue",
- "params": {
- "repos": [
- {
- "owner": "continuedev",
- "repo": "continue"
+ "contextProviders": [
+ {
+ "name": "issue",
+ "params": {
+ "repos": [
+ {
+ "owner": "continuedev",
+ "repo": "continue"
+ }
+ ],
+ "githubToken": "ghp_xxx"
}
- ],
- "githubToken": "ghp_xxx"
- }
+ }
+ ]
}
```
-### GitLab Merge Request
+Make sure to include your own [GitHub personal access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token) to avoid being rate-limited.
-Type `@gitlab-mr` to reference an open MR for this branch on GitLab.
+### `@Gitlab Merge Request`
-#### Configuration
+Reference an open MR for this branch on GitLab.
-You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope. then add the following to your configuration:
-
-```json
+```json title="config.json"
{
- "name": "gitlab-mr",
- "params": {
- "token": "..."
- }
+ "contextProviders": [
+ {
+ "name": "gitlab-mr",
+ "params": {
+ "token": "..."
+ }
+ }
+ ]
}
```
+You will need to create a [personal access token](https://docs.gitlab.com/ee/user/profile/personal_access_tokens.html) with the `read_api` scope.
+
#### Using Self-Hosted GitLab
You can specify the domain to communicate with by setting the `domain` parameter in your configurtion. By default this is set to `gitlab.com`.
-```json
+```json title="config.json"
{
- "name": "gitlab-mr",
- "params": {
- "token": "...",
- "domain": "gitlab.example.com"
- }
+ "contextProviders": [
+ {
+ "name": "gitlab-mr",
+ "params": {
+ "token": "...",
+ "domain": "gitlab.example.com"
+ }
+ }
+ ]
}
```
@@ -171,31 +266,43 @@ You can specify the domain to communicate with by setting the `domain` parameter
If you select some code to be edited, you can have the context provider filter out comments for other files. To enable this feature, set `filterComments` to `true`.
-### Jira Issues
+### `@Jira`
-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), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email.
+Reference the conversation in a Jira issue.
-```json
+```json title="config.json"
{
- "name": "jira",
- "params": {
- "domain": "company.atlassian.net",
- "token ": "ATATT..."
- }
+ "contextProviders": [
+ {
+ "name": "jira",
+ "params": {
+ "domain": "company.atlassian.net",
+ "token ": "ATATT..."
+ }
+ }
+ ]
}
```
+Make sure to include your own [Atlassian API Token](https://id.atlassian.com/manage-profile/security/api-tokens), or use your `email` and `token`, with token set to your password for basic authentication. If you use your own Atlassian API Token, don't configure your email.
+
#### Jira Datacenter Support
This context provider supports both Jira API version 2 and 3. It will use version 3 by default since
that's what the cloud version uses, but if you have the datacenter version of Jira, you'll need
to set the API Version to 2 using the `apiVersion` property.
-```json
- "params": {
- "apiVersion": "2",
- ...
- }
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "jira",
+ "params": {
+ "apiVersion": "2"
+ }
+ }
+ ]
+}
```
#### Issue Query
@@ -208,117 +315,175 @@ assignee = currentUser() AND resolution = Unresolved order by updated DESC
You can override this query by setting the `issueQuery` parameter.
-
+### `@Postgres`
-
-
-### 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
+### `@Database`
+
+Reference table schemas from Sqlite, Postgres, and MySQL databases.
+
+```json title="config.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"
- }
+ "contextProviders": [
+ {
+ "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"
+ }
+ }
+ ]
}
- ]
- }
+ }
+ ]
}
```
-### Debugger: Local Variables
+Each connection should include a unique name, the `connection_type`, and the necessary connection parameters specific to each database type.
-Type `@locals` to reference the contents of the local variables with top n level (defaulting to 3) of call stack for that thread. A dropdown will appear, allowing you to select a specific thread to see the local variables in that thread.
+Available connection types:
-```json
+- `postgres`
+- `mysql`
+- `sqlite`
+
+### `@Locals`
+
+Reference the contents of the local variables in the debugger.
+
+```json title="config.json"
{
- "name": "locals",
- "params": {
- "stackDepth": 3
- }
+ "contextProviders": [
+ {
+ "name": "locals",
+ "params": {
+ "stackDepth": 3
+ }
+ }
+ ]
}
```
-### Repository map
+Uses the top _n_ levels (defaulting to 3) of the call stack for that thread.
-Provides an overview of all files and the call signatures of top-level classes, functions, and methods. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
+### `@Repository Map`
+
+Reference the outline of your codebase.
+
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "repo-map"
+ }
+ ]
+}
+```
+
+Provides a list of files and the call signatures of top-level classes, functions, and methods in those files. This helps the model better understand how a particular piece of code relates to the rest of the codebase.
+
+In the submenu that appears, you can select either `Entire codebase`, or specify a subfolder to generate the repostiory map from.
This context provider is inpsired by [Aider's repository map](https://aider.chat/2023/10/22/repomap.html).
-```json
+### `@Operating System`
+
+Reference the architecture and platform of your current operating system.
+
+```json title="config.json"
{
- "name": "repo-map"
+ "contextProviders": [
+ {
+ "name": "os"
+ }
+ ]
}
```
-### Operating System
+### `@HTTP`
-Type `@os` to reference the architecture and platform of your current operating system.
+The HttpContextProvider makes a POST request to the url passed in the configuration. The server must return 200 OK with a ContextItem object or an array of ContextItems.
-```json
-{ "name": "os" }
+```json title="config.json"
+{
+ "contextProviders": [
+ {
+ "name": "http",
+ "params": {
+ "url": "https://api.example.com/v1/users",
+ }
+ }
+ ]
+}
+```
+
+The receiving URL should expect to receive the following parameters:
+```json title="POST parameters"
+{
+ query: string,
+ fullInput: string
+}
+```
+
+The response 200 OK should be a JSON object with the following structure:
+```json title="Response"
+[
+ {
+ "name": "",
+ "description": "",
+ "content": ""
+ }
+]
+
+// OR
+{
+ "name": "",
+ "description": "",
+ "content": ""
+}
```
### 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.
+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 Context Provider.
diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md
index 3fd00ef02..49c2de949 100644
--- a/docs/docs/customize/deep-dives/autocomplete.md
+++ b/docs/docs/customize/deep-dives/autocomplete.md
@@ -32,7 +32,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 (note that it is not inside the models array):
-```json title=~/.continue/config.json
+```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
@@ -73,7 +73,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
### Full example
-```json title=~/.continue/config.json
+```json title="config.json"
{
"tabAutocompleteModel": {
"title": "Tab Autocomplete Model",
@@ -119,7 +119,7 @@ To ensure that you receive multi-line completions, you can set `"multilineComple
Yes, in VS Code, if you don't want to be shown suggestions automatically you can:
-1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disabe automatic suggestions
+1. Set `"editor.inlineSuggest.enabled": false` in VS Code settings to disable automatic suggestions
2. Open "Keyboard Shortcuts" (cmd/ctrl+k, cmd/ctrl+s) and search for `editor.action.inlineSuggest.trigger`
3. Click the "+" icon to add a new keybinding
4. Press the key combination you want to use to trigger suggestions (e.g. `ctrl+space`)
diff --git a/docs/docs/customize/deep-dives/codebase.md b/docs/docs/customize/deep-dives/codebase.md
index 8d5fef254..0d70f9b53 100644
--- a/docs/docs/customize/deep-dives/codebase.md
+++ b/docs/docs/customize/deep-dives/codebase.md
@@ -3,11 +3,11 @@ description: Talk to your codebase
keywords: [talk, embeddings, reranker, codebase, experimental]
---
-# @codebase
+# @Codebase
Continue indexes your codebase so that it can later automatically pull in the most relevant context from throughout your workspace. This is done via a combination of embeddings-based retrieval and keyword search. By default, all embeddings are calculated locally with `all-MiniLM-L6-v2` and stored locally in `~/.continue/index`.
-Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@codebase` or `@folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
+Currently, the codebase retrieval feature is available as the "codebase" and "folder" context providers. You can use them by typing `@Codebase` or `@Folder` in the input box, and then asking a question. The contents of the input box will be compared with the embeddings from the rest of the codebase (or folder) to determine relevant files.
Here are some common use cases where it can be useful:
@@ -19,10 +19,10 @@ Here are some common use cases where it can be useful:
- "Generate a new React component with a date picker, using the same patterns as existing components"
- "Write a draft of a CLI application for this project using Python's argparse"
- "Implement the `foo` method in the `bar` class, following the patterns seen in other subclasses of `baz`.
-- Use `@folder` to ask questions about a specific folder, increasing the likelihood of relevant results
+- Use `@Folder` to ask questions about a specific folder, increasing the likelihood of relevant results
- "What is the main purpose of this folder?"
- "How do we use VS Code's CodeLens API?"
- - Or any of the above examples, but with `@folder` instead of `@codebase`
+ - Or any of the above examples, but with `@Folder` instead of `@Codebase`
Here are use cases where it is not useful:
@@ -70,3 +70,7 @@ Continue respects `.gitignore` files in order to determine which files should no
If you want to see exactly what files Continue has indexed, the metadata is stored in `~/.continue/index/index.sqlite`. You can use a tool like [DB Browser for SQLite](https://sqlitebrowser.org/) to view the `tag_catalog` table within this file.
If you need to force a refresh of the index, reload the VS Code window with `cmd/ctrl + shift + p` + "Reload Window".
+
+## Repository map
+
+Models in the Claude 3, Llama 3.1, Gemini 1.5, and GPT-4o families will automatically use a [repository map](../context-providers.md#repository-map) during codebsae retrieval, which allows the model to understand the structure of your codebase and use it to answer questions. Currently, the repository map only contains the filepaths in the codebase.
diff --git a/docs/docs/customize/deep-dives/docs.md b/docs/docs/customize/deep-dives/docs.md
index 7ae6b329b..bc8968528 100644
--- a/docs/docs/customize/deep-dives/docs.md
+++ b/docs/docs/customize/deep-dives/docs.md
@@ -4,31 +4,32 @@ keywords: [documentation, indexing, context provider, embeddings, docs]
toc_max_heading_level: 5
---
-# @docs
+# @Docs
-The [`@docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
+The [`@Docs` context provider](http://localhost:3000/customization/context-providers#documentation) allows you to interact with your documentation directly within Continue. This feature enables you to index any static site or GitHub markdown pages, making it easier to access and utilize your documentation while coding.
-## Enabling the `@docs` context provider
+## Enabling the `@Docs` context provider
-To enable the `@docs` context provider, you need to add it to the list of context providers in your `config.json` file.
+To enable the `@Docs` context provider, you need to add it to the list of context providers in your `config.json` file.
```json
{
- "contextProviders": [
- { "name": "docs" }
- ...
- ]
+ "contextProviders": [
+ {
+ "name": "docs"
+ }
+ ]
}
```
## How It Works
-The `@docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content.
+The `@Docs` context provider works by crawling specified documentation sites, generating embeddings, and storing them locally for you. This process allows for quick and efficient access to your documentation content.
1. We crawl the specified documentation site
2. Generate embeddings for the content
3. Store the embeddings locally on your machine
-4. Provide access to the indexed content through the `@docs` context provider
+4. Provide access to the indexed content through the `@Docs` context provider
## Pre-indexed Documentation Sites
@@ -36,11 +37,11 @@ We offer a selection of pre-indexed documentation sites for popular frameworks a
## Indexing Your Own Documentation
-### Through the `@docs` Context Provider
+### Through the `@Docs` Context Provider
-To add a single documentation site, we recommend using the `@docs` context provider.
+To add a single documentation site, we recommend using the `@Docs` context provider.
-1. Type `@docs` in the chat panel, hit enter
+1. Type `@Docs` in the chat panel, hit enter
2. Type "add" and select the "Add Docs" option
3. Enter the required information into the dialog
@@ -50,7 +51,7 @@ Indexing will begin upon submission.
To add multiple documentation sites, we recommend adding them in bulk to your `config.json` file. Indexing will kick off upon file save.
-The configuration schema is as follows:
+The [configuration schema for docs](https://github.com/continuedev/continue/blob/v0.9.212-vscode/extensions/vscode/config_schema.json#L1943-L1973) is as follows:
```json
"docs": [
@@ -74,7 +75,7 @@ By default, we use a lighter weight tool to crawl documentation sites that canno
If you want to crawl a site that is dynamically generated, or you get an error while attempting to crawl a site, you can enable the experimental `useChromiumForDocsCrawling` feature in your `config.json`. This will download and install Chromium to `~/.continue/.utils`.
-```json title=config.json
+```json title="config.json"
"experimental": {
"useChromiumForDocsCrawling": true
}
diff --git a/docs/docs/customize/model-providers/top-level/anthropic.md b/docs/docs/customize/model-providers/top-level/anthropic.md
index ebc156413..c4bb24a4c 100644
--- a/docs/docs/customize/model-providers/top-level/anthropic.md
+++ b/docs/docs/customize/model-providers/top-level/anthropic.md
@@ -48,14 +48,17 @@ Anthropic currently does not offer any reranking models.
Anthropic supports [prompt caching with Claude](https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching).
-Currently, we only allow caching of the system message. To enable this feature, update your your model configuration with `"cacheSystemMessage": true`:
+To enable caching of the system message and the turn-by-turn conversation, update your your model configuration as following:
```json
{
"models": [
{
// Enable prompt caching
- "cacheSystemMessage": true,
+ "cacheBehavior": {
+ "cacheSystemMessage": true,
+ "cacheConversation": true
+ },
"title": "Anthropic",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20240620",
diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md
index 8e98c9186..8ecac28e6 100644
--- a/docs/docs/customize/model-types/autocomplete.md
+++ b/docs/docs/customize/model-types/autocomplete.md
@@ -7,10 +7,10 @@ sidebar_position: 1
An "autocomplete model" is an LLM that is trained on a special format called fill-in-the-middle (FIM). This format is designed to be given the prefix and suffix of a code file and predict what goes between. This task is very specific, which on one hand means that the models can be smaller (even a 3B parameter model can perform well). On the other hand, this means that Chat models, though larger, will perform poorly.
-In Continue, these models are used to display inline [Autocomplete](../../chat/how-to-use-it.md) suggestions as you type.
+In Continue, these models are used to display inline [Autocomplete](../../autocomplete/how-to-use-it.md) suggestions as you type.
## Recommended Autocomplete models
-If you have the ability to use any model, we recommend [Codestral](../model-providers/top-level/mistral.md) from Mistral.
+If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model).
-If you want to run a model locally, we recommend [Starcoder2-3B] with [Ollama]../model-providers/top-level/ollama.md).
+If you want to run a model locally, we recommend `Starcoder2-3B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model).
diff --git a/docs/docs/customize/model-types/embeddings.md b/docs/docs/customize/model-types/embeddings.md
index 2960dcbfd..c32468967 100644
--- a/docs/docs/customize/model-types/embeddings.md
+++ b/docs/docs/customize/model-types/embeddings.md
@@ -7,7 +7,7 @@ sidebar_position: 3
An "embeddings model" is trained to convert a piece of text into a vector, which can later be rapidly compared to other vectors to determine similarity between the pieces of text. Embeddings models are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
-In Continue, embeddings are generated during indexing and then used by [@codebase](../deep-dives/codebase.md) to perform similarity search over your codebase.
+In Continue, embeddings are generated during indexing and then used by [@Codebase](../deep-dives/codebase.md) to perform similarity search over your codebase.
## Recommended embedding models
diff --git a/docs/docs/customize/model-types/reranking.md b/docs/docs/customize/model-types/reranking.md
index af6c99932..5f3fd77a3 100644
--- a/docs/docs/customize/model-types/reranking.md
+++ b/docs/docs/customize/model-types/reranking.md
@@ -7,7 +7,7 @@ sidebar_position: 4
A "reranking model" is trained to take two pieces of text (often a user question and a document) and return a relevancy score between 0 and 1, estimating how useful the document will be in answering the question. Rerankers are typically much smaller than LLMs, and will be extremely fast and cheap in comparison.
-In Continue, reranking is used by [@codebase](../deep-dives/codebase.md) in order to select the most relevant code snippets after vector search.
+In Continue, reranking is used by [@Codebase](../deep-dives/codebase.md) in order to select the most relevant code snippets after vector search.
## Recommended reranking models
diff --git a/docs/docs/customize/slash-commands.md b/docs/docs/customize/slash-commands.md
index 6379b6db5..702d00c7c 100644
--- a/docs/docs/customize/slash-commands.md
+++ b/docs/docs/customize/slash-commands.md
@@ -10,108 +10,144 @@ Slash commands are shortcuts that can be activated by typing '/' and selecting f
## Built-in Slash Commands
-To use any of the built-in slash commands, open `~/.continue/config.json` and add it to the `slashCommands` list.
+To use any of the built-in slash commands, open `config.json` and add it to the `slashCommands` list.
-### `/edit`
+### `/Edit`
-Select code with ctrl/cmd + L (VS Code) or ctrl/cmd + J (JetBrains), and then type "/edit", followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor.
+Select code with `ctrl/cmd + L` (VS Code) or `ctrl/cmd + J` (JetBrains), and then type `/Edit`, followed by instructions for the edit. Continue will stream the changes into a side-by-side diff editor.
-```json
+```json title="config.json"
{
- "name": "edit",
- "description": "Edit highlighted code"
+ "slashCommands": [
+ {
+ "name": "edit",
+ "description": "Edit highlighted code"
+ }
+ ]
}
```
-### `/comment`
+### `/Comment`
-Comment works just like /edit, except it will automatically prompt the LLM to comment the code.
+Comment works just like `/Edit`, except it will automatically prompt the LLM to comment the code.
-```json
+```json title="config.json"
{
- "name": "comment",
- "description": "Write comments for the highlighted code"
+ "slashCommands": [
+ {
+ "name": "comment",
+ "description": "Write comments for the highlighted code"
+ }
+ ]
}
```
-### `/share`
+### `/Share`
-Type "/share" to generate a shareable markdown transcript of your current chat history.
+Generate a shareable markdown transcript of your current chat history.
-```json
+```json title="config.json"
{
- "name": "share",
- "description": "Export the current chat session to markdown",
- "params": { "outputDir": "~/.continue/session-transcripts" }
+ "slashCommands": [
+ {
+ "name": "share",
+ "description": "Export the current chat session to markdown",
+ "params": { "outputDir": "~/.continue/session-transcripts" }
+ }
+ ]
}
```
Use the `outputDir` parameter to specify where you want to the markdown file to be saved.
-### `/cmd`
+### `/Cmd`
Generate a shell command from natural language and (only in VS Code) automatically paste it into the terminal.
-```json
+```json title="config.json"
{
- "name": "cmd",
- "description": "Generate a shell command"
+ "slashCommands": [
+ {
+ "name": "cmd",
+ "description": "Generate a shell command"
+ }
+ ]
}
```
-### `/commit`
+### `/Commit`
Shows the LLM your current git diff and asks it to generate a commit message.
-```json
+```json title="config.json"
{
- "name": "commit",
- "description": "Generate a commit message for the current changes"
+ "slashCommands": [
+ {
+ "name": "commit",
+ "description": "Generate a commit message for the current changes"
+ }
+ ]
}
```
-### `/http`
+### `/Http`
Write a custom slash command at your own HTTP endpoint. Set 'url' in the params object for the endpoint you have setup. The endpoint should return a sequence of string updates, which will be streamed to the Continue sidebar. See our basic [FastAPI example](https://github.com/continuedev/continue/blob/74002369a5e435735b83278fb965e004ae38a97d/core/context/providers/context_provider_server.py#L34-L45) for reference.
-```json
+```json title="config.json"
{
- "name": "http",
- "description": "Does something custom",
- "params": { "url": "" }
+ "slashCommands": [
+ {
+ "name": "http",
+ "description": "Does something custom",
+ "params": { "url": "" }
+ }
+ ]
}
```
-### `/issue`
+### `/Issue`
Describe the issue you'd like to generate, and Continue will turn into a well-formatted title and body, then give you a link to the draft so you can submit. Make sure to set the URL of the repository you want to generate issues for.
-```json
+```json title="config.json"
{
- "name": "issue",
- "description": "Generate a link to a drafted GitHub issue",
- "params": { "repositoryUrl": "https://github.com/continuedev/continue" }
+ "slashCommands": [
+ {
+ "name": "issue",
+ "description": "Generate a link to a drafted GitHub issue",
+ "params": { "repositoryUrl": "https://github.com/continuedev/continue" }
+ }
+ ]
}
```
-### `/so`
+### `/So`
The StackOverflow slash command will automatically pull results from StackOverflow to answer your question, quoting links along with its answer.
-```json
+```json title="config.json"
{
- "name": "so",
- "description": "Reference StackOverflow to answer the question"
+ "slashCommands": [
+ {
+ "name": "so",
+ "description": "Reference StackOverflow to answer the question"
+ }
+ ]
}
```
-### `/onboard`
+### `/Onboard`
The Onboard slash command helps to familiarize yourself with a new project by analyzing the project structure, READMEs, and dependency files. It identifies key folders, explains their purpose, and highlights popular packages used. Additionally, it offers insights into the project's architecture.
-```json
+```json title="config.json"
{
- "name": "onboard",
- "description": "Familiarize yourself with the codebase"
+ "slashCommands": [
+ {
+ "name": "onboard",
+ "description": "Familiarize yourself with the codebase"
+ }
+ ]
}
```
diff --git a/docs/docs/customize/tutorials/custom-code-rag.md b/docs/docs/customize/tutorials/custom-code-rag.md
index 6793a8277..208180a58 100644
--- a/docs/docs/customize/tutorials/custom-code-rag.md
+++ b/docs/docs/customize/tutorials/custom-code-rag.md
@@ -1,6 +1,6 @@
# Custom code RAG
-While Continue comes with [@codebase](../deep-dives/codebase.md) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this.
+While Continue comes with [@Codebase](../deep-dives/codebase.md) out of the box, you might wish to set up your own vector database and build a custom retrieval-augmented generation (RAG) system. This can allow you to access code that is not available locally, to index code a single time across all users, or to include custom logic. In this guide, we'll walk you through the steps it takes to build this.
## Step 1: Choose an embeddings model
diff --git a/docs/docs/troubleshooting.md b/docs/docs/troubleshooting.md
index 8852cf3f4..d3933f6f9 100644
--- a/docs/docs/troubleshooting.md
+++ b/docs/docs/troubleshooting.md
@@ -122,6 +122,10 @@ If you are having persistent errors with indexing, our recommendation is to rebu
This can be accomplished using the following command: `Continue: Rebuild codebase index`.
+### Android Studio - "Nothing to show" in Chat
+
+This can be fixed by selecting `Actions > Choose Boot runtime for the IDE` then selecting the latest version, and then restarting Android Studio. [See this thread](https://github.com/continuedev/continue/issues/2280#issuecomment-2365231567) for details.
+
## Still having trouble?
You can also join our Discord community [here](https://discord.gg/vapESyrFmJ) for additional support and discussions. Alternatively, you can create a GitHub issue [here](https://github.com/continuedev/continue/issues/new?assignees=&labels=bug&projects=&template=bug-report-%F0%9F%90%9B.md&title=), providing details of your problem, and we'll be able to help you out more quickly.
diff --git a/docs/package.json b/docs/package.json
index 644b1d7f4..423c60bde 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -5,7 +5,7 @@
"private": true,
"scripts": {
"docusaurus": "docusaurus",
- "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec 'docusaurus start'",
+ "start": "nodemon --watch sidebars.js --watch docusaurus.config.js --exec \"docusaurus start\"",
"build": "docusaurus build",
"build:netlify": "docusaurus build --out-dir build/docs",
"swizzle": "docusaurus swizzle",
diff --git a/docs/sidebars.js b/docs/sidebars.js
index 196a6c832..755d7f720 100644
--- a/docs/sidebars.js
+++ b/docs/sidebars.js
@@ -8,10 +8,6 @@ const sidebars = {
type: "category",
label: "Getting started",
collapsed: false,
- link: {
- type: "doc",
- id: "getting-started/install",
- },
items: [
{
type: "autogenerated",
@@ -22,10 +18,6 @@ const sidebars = {
{
type: "category",
label: "Chat",
- link: {
- type: "doc",
- id: "chat/how-to-use-it",
- },
items: [
{
type: "autogenerated",
@@ -36,10 +28,6 @@ const sidebars = {
{
type: "category",
label: "Autocomplete",
- link: {
- type: "doc",
- id: "autocomplete/how-to-use-it",
- },
items: [
{
type: "autogenerated",
@@ -50,10 +38,6 @@ const sidebars = {
{
type: "category",
label: "Edit",
- link: {
- type: "doc",
- id: "edit/how-to-use-it",
- },
items: [
{
type: "autogenerated",
@@ -64,10 +48,6 @@ const sidebars = {
{
type: "category",
label: "Actions",
- link: {
- type: "doc",
- id: "actions/how-to-use-it",
- },
items: [
{
type: "autogenerated",
diff --git a/docs/static/schemas/config.json b/docs/static/schemas/config.json
index 911278ebb..3f340f6ce 100644
--- a/docs/static/schemas/config.json
+++ b/docs/static/schemas/config.json
@@ -609,9 +609,7 @@
"llama3.1-70b",
"llama3.1-405b",
"gpt-3.5-turbo",
- "phind-codellama-34b",
"gemini-pro",
- "mistral-8x7b",
"claude-3-5-sonnet-20240620",
"claude-3-haiku-20240307",
"AUTODETECT"
@@ -701,8 +699,17 @@
},
"then": {
"properties": {
- "cacheSystemMessage": {
- "type": "boolean"
+ "cacheBehavior": {
+ "title": "Caching Behavior",
+ "description": "Options for the prompt caching",
+ "properties": {
+ "cacheSystemMessage": {
+ "type": "boolean"
+ },
+ "cacheConversation": {
+ "type": "boolean"
+ }
+ }
},
"model": {
"anyOf": [
@@ -798,8 +805,14 @@
},
"then": {
"properties": {
- "cacheSystemMessage": {
- "type": "boolean"
+ "cacheBehavior": {
+ "title": "Caching Behavior",
+ "description": "Options for the prompt caching",
+ "properties": {
+ "cacheSystemMessage": {
+ "type": "boolean"
+ }
+ }
},
"model": {
"enum": [
@@ -1019,8 +1032,17 @@
},
"then": {
"properties": {
- "cacheSystemMessage": {
- "type": "boolean"
+ "cacheBehavior": {
+ "title": "Caching Behavior",
+ "description": "Options for the prompt caching",
+ "properties": {
+ "cacheSystemMessage": {
+ "type": "boolean"
+ },
+ "cacheConversation": {
+ "type": "boolean"
+ }
+ }
},
"model": {
"enum": ["deepseek-chat", "deepseek-coder"]
@@ -1044,6 +1066,7 @@
"llama2-70b",
"mistral-8x7b",
"gemma",
+ "gemma2",
"llama3-8b",
"llama3-70b",
"llama3.1-8b",
@@ -1529,7 +1552,8 @@
"url",
"database",
"os",
- "repo-map"
+ "repo-map",
+ "greptile"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@@ -1553,7 +1577,8 @@
"Reference the contents of a page at a URL",
"Reference table schemas",
"Operating system and CPU Information",
- "Map of files in the repository with important code highlights"
+ "Map of files in the repository with important code highlights",
+ "Query your greptile index of the current repo"
],
"type": "string"
},
@@ -1931,6 +1956,36 @@
},
"required": ["host", "port", "user", "password", "database"]
}
+ },
+ {
+ "if": {
+ "properties": {
+ "name": {
+ "enum": ["greptile"]
+ }
+ }
+ },
+ "then": {
+ "properties": {
+ "params": {
+ "properties": {
+ "GithubToken": {
+ "title": "GithubToken",
+ "description": "Your github access token",
+ "default": "",
+ "type": "string"
+ },
+ "GreptileToken": {
+ "title": "GreptileToken",
+ "description": "Your greptile access token",
+ "default": "",
+ "type": "string"
+ }
+ }
+ }
+ },
+ "required": ["GreptileToken", "GithubToken"]
+ }
}
],
"required": ["name"]
@@ -2114,6 +2169,13 @@
"minimum": 128,
"exclusiveMaximum": 2147483647
},
+ "maxBatchSize": {
+ "title": "Maximum Batch Size",
+ "description": "The maximum number of chunks that can be sent to the embeddings provider in a single request",
+ "type": "integer",
+ "minimum": 1,
+ "exclusiveMaximum": 2147483647
+ },
"region": {
"title": "Region",
"description": "The region where the model is hosted",
diff --git a/extensions/intellij/.run/Run Verifications.run.xml b/extensions/intellij/.run/Run Verifications.run.xml
index 3a8d68859..35b018168 100644
--- a/extensions/intellij/.run/Run Verifications.run.xml
+++ b/extensions/intellij/.run/Run Verifications.run.xml
@@ -3,7 +3,7 @@
-
+