Merge branch 'preview' into nate/no-more-undici

This commit is contained in:
Nate Sesti 2024-02-01 00:35:35 -08:00
commit dbab612c81
115 changed files with 6892 additions and 2400 deletions

View file

@ -0,0 +1,8 @@
## v0.8.2 - 2024-01-23
### Added
* Add codellama and gemini to free trial, using new server
* Local codebase syncing and embeddings using LanceDB
* Improved VS Code theme matching
### Changed
* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
* Context providers now run from the extension side (in Node.js instead of browser javascript)

View file

@ -1,4 +0,0 @@
project: extensions/vscode
kind: Added
body: Add codellama and gemini to free trial, using new server
time: 2024-01-11T19:42:46.155127-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Image support
time: 2024-01-24T22:29:04.193864-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Full-text search index for retrieval
time: 2024-01-29T21:05:50.216548-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: Docs context provider
time: 2024-01-30T12:31:43.521306-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Added
body: CodeLlama-70b support
time: 2024-01-30T13:03:32.287428-08:00

View file

@ -0,0 +1,4 @@
project: extensions/vscode
kind: Fixed
body: Fixed proxy setting in config.json
time: 2024-01-30T13:03:15.8294-08:00

View file

@ -26,10 +26,6 @@ newlines:
envPrefix: CHANGIE_
projects:
- label: server
key: server
changelog: server/CHANGELOG.md
- label: extensions/intellij
key: extensions/intellij
changelog: extensions/intellij/CHANGELOG.md

View file

@ -1,2 +1,3 @@
**/*.run.xml
archive/**/*
archive/**/*
extensions/vscode/models/**/*

5
.gitignore vendored
View file

@ -149,4 +149,7 @@ codeql
**/**/build
continue_server.build
continue_server.dist
continue_server.dist
Icon
Icon?

3
.vscode/tasks.json vendored
View file

@ -102,8 +102,9 @@
{
"label": "install-all-dependencies",
"type": "shell",
"windows": { "command": "./install-dependencies.ps1" },
"command": "./install-dependencies.sh",
"problemMatcher": [] // Empty so users are not promted to select progress reporting
"problemMatcher": [] // Empty so users are not prompted to select progress reporting
},
//
// Start the React App for debugging with Vite

View file

@ -11,6 +11,7 @@
- [Environment Setup](#environment-setup)
- [Writing Slash Commands](#writing-slash-commands)
- [Writing Context Providers](#writing-context-providers)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
@ -56,7 +57,7 @@ Continue is continuously improving, but a feature isn't complete until it is ref
VS Code is assumed for development as Continue is primarily a VS Code tool at the moment. Most of the setup and running is automated through VS Code tasks and launch configurations.
Pre-requisite: you will need `cargo` the rust package manager installed ([get it on rust-lang.org](https://www.rust-lang.org/tools/install)).
<!-- Pre-requisite: you will need `cargo` the rust package manager installed ([get it on rust-lang.org](https://www.rust-lang.org/tools/install)). -->
1. Clone and open in VS Code the Continue repo `https://github.com/continuedev/continue`
@ -82,11 +83,47 @@ Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esb
### Writing Slash Commands
A Step can be used as a custom slash command, or called otherwise in a `Policy`. See the [steps README](./server/continuedev/plugins/steps/README.md) to learn how to write a Step.
The slash command interface, defined in [core/index.d.ts](./core/index.d.ts), requires you to define a `name` (the text that will be typed to invoke the command), a `description` (the text that will be shown in the slash command menu), and a `run` function that will be called when the command is invoked. The `run` function is an async generator that yields the content to be displayed in the chat. The `run` function is passed a `ContinueSDK` object that can be used to interact with the IDE, call the LLM, and see the chat history, among a few other utilities.
```ts
export interface SlashCommand {
name: string;
description: string;
params?: { [key: string]: any };
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
```
There are many example of slash commands in [core/commands/slash](./core/commands/slash) that we recommend borrowing from. Once you've created your new `SlashCommand` in this folder, also be sure to complete the following:
- Add your command to the array in [core/commands/slash/index.ts](./core/commands/slash/index.ts)
- Add your command to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what commands are available for your provider when they are editing `config.json`. If there are any parameters that your command accepts, you should also follow existing examples in adding them to the JSON Schema.
### Writing Context Providers
A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The simplest way to create a `ContextProvider` is to implement the `provide_context_items` method. You can find a great example of this in [GitHubIssuesContextProvider](./server/continuedev/plugins/context_providers/github.py), which allows you to search GitHub Issues in a repo.
A `ContextProvider` is a Continue plugin that lets type '@' to quickly select documents as context for the language model. The `IContextProvider` interface is defined in [`core/index.d.ts`](./core/index.d.ts), but all built-in context providers extend [`BaseContextProvider`](./core/context/index.ts).
Before defining your context provider, determine which "type" you want to create. The `"query"` type will show a small text input when selected, giving the user the chance to enter something like a Google search query for the [`GoogleContextProvider`](./core/context/providers/GoogleContextProvider.ts). The `"submenu"` type will open up a submenu of items that can be searched through and selected. Examples are the [`GitHubIssuesContextProvider`](./core/context/providers/GitHubIssuesContextProvider.ts) and the [`DocsContextProvider`](./core/context/providers/DocsContextProvider.ts). The `"normal"` type will just immediately add the context item. Examples include the [`DiffContextProvider`](./core/context/providers/DiffContextProvider.ts) and the [`OpenFilesContextProvider`](./core/context/providers/OpenFilesContextProvider.ts).
After you've written your context provider, make sure to complete the following:
- Add it to the array of context providers in [core/context/providers/index.ts](./core/context/providers/index.ts)
- Add it to the `ContextProviderName` type in [core/index.d.ts](./core/index.d.ts)
- Add it to the list in [`config_schema.json`](./extensions/vscode/config_schema.json). If there are any parameters that your context provider accepts, you should also follow existing examples in adding them to the JSON Schema.
### Adding an LLM Provider
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
- `providerName` - the identifier for your provider
- At least one of `_streamComplete` or `_streamChat` - This is the function that makes the request to the API and returns the streamed response. You only need to implement one because Continue can automatically convert between "chat" and "raw completion".
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/index.ts](./core/llm/index.ts).
4. Add the necessary JSON Schema types to [`config_schema.json`](./extensions/vscode/config_schema.json). This makes sure that Intellisense shows users what options are available for your provider when they are editing `config.json`.
5. Add a documentation page for your provider in [`docs/docs/reference/Model Providers`](./docs/docs/reference/Model%20Providers). This should show an example of configuring your provider in `config.json` and explain what options are available.
### Adding Models

View file

@ -11,13 +11,13 @@
<div align="center">
<a target="_blank" href="https://opensource.org/licenses/Apache-2.0" style="background:none">
<img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 36px;" />
<img src="https://img.shields.io/badge/License-Apache_2.0-blue.svg" style="height: 22px;" />
</a>
<a target="_blank" href="https://continue.dev/docs" style="background:none">
<img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 36px;" />
<img src="https://img.shields.io/badge/continue_docs-%23BE1B55" style="height: 22px;" />
</a>
<a target="_blank" href="https://discord.gg/vapESyrFmJ" style="background:none">
<img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 36px;" />
<img src="https://img.shields.io/badge/discord-join-continue.svg?labelColor=191937&color=6F6FF7&logo=discord" style="height: 22px;" />
</a>
<p></p>
@ -66,4 +66,4 @@ Check out the [contribution ideas board](https://github.com/orgs/continuedev/pro
## License
[Apache 2.0 © 2023 Continue Dev, Inc.](./LICENSE)
[Apache 2.0 © 2023 Continue Dev, Inc.](./LICENSE)

View file

@ -1,19 +1,40 @@
import { SlashCommand } from "../..";
import { streamLines } from "../../diff/util";
import { removeQuotesAndEscapes } from "../../util";
const GenerateTerminalCommand: SlashCommand = {
name: "cmd",
description: "Generate a shell command",
run: async function* ({ ide, llm, input }) {
let cmd =
await llm.complete(`The user has made a request to run a shell command. Their description of what it should do is:
const gen =
llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
"${input}"
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested.`);
cmd = removeQuotesAndEscapes(cmd.trim())
.replace("\n", "")
.replace("\r", "");
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`);
const lines = streamLines(gen);
let cmd = "";
for await (const line of lines) {
console.log(line);
if (line.startsWith("```") && line.endsWith("```")) {
cmd = line.split(" ").slice(1).join(" ").slice(0, -3);
break;
}
if (
line.startsWith(">") ||
line.startsWith("``") ||
line.startsWith("\\begin{") ||
line.trim() === ""
) {
continue;
}
cmd = removeQuotesAndEscapes(line.trim());
break;
}
await ide.runCommand(cmd);
yield `Generated shell command: ${cmd}`;
},

View file

@ -29,12 +29,13 @@ const DraftIssueCommand: SlashCommand = {
yield "This command requires a repository URL to be set in the config file.";
return;
}
const title = await llm.complete(
let title = await llm.complete(
`Generate a title for the GitHub issue requested in this user input: '${input}'. Use no more than 20 words and output nothing other than the title. Do not surround it with quotes. The title is: `,
{ maxTokens: 20 }
);
yield removeQuotesAndEscapes(title) + "\n\n";
title = removeQuotesAndEscapes(title.trim()) + "\n\n";
yield title;
let body = "";
const messages: ChatMessage[] = [

View file

@ -206,10 +206,15 @@ const EditSlashCommand: SlashCommand = {
name: "edit",
description: "Edit selected code",
run: async function* ({ ide, llm, input, history, contextItems, params }) {
const contextItemToEdit = contextItems.find(
let contextItemToEdit = contextItems.find(
(item: ContextItemWithId) =>
item.editing && item.id.providerTitle === "code"
);
if (!contextItemToEdit) {
contextItemToEdit = contextItems.find(
(item: ContextItemWithId) => item.id.providerTitle === "code"
);
}
if (!contextItemToEdit) {
yield "Select (highlight and press `cmd+shift+M` (MacOS) / `ctrl+shift+M` (Windows)) the code that you want to edit first";

View file

@ -15,10 +15,10 @@ export function contextItemToRangeInFileWithContents(
const lines = item.name.split("(")[1].split(")")[0].split("-");
const rif: RangeInFileWithContents = {
filepath: item.description,
filepath: item.description.split(" (")[0],
range: {
start: {
line: parseInt(lines[0]) - 1,
line: parseInt(lines[0]),
character: 0,
},
end: {

View file

@ -8,20 +8,20 @@ const defaultConfig: SerializedContinueConfig = {
model: "gpt-4",
},
{
title: "GPT-3.5-Turbo (Free Trial)",
title: "GPT-4 Vision (Free Trial)",
provider: "free-trial",
model: "gpt-3.5-turbo",
},
{
title: "Phind CodeLlama (Free Trial)",
provider: "free-trial",
model: "phind-codellama-34b",
model: "gpt-4-vision-preview",
},
{
title: "Gemini Pro (Free Trial)",
provider: "free-trial",
model: "gemini-pro",
},
{
title: "Codellama 70b (Free Trial)",
provider: "free-trial",
model: "codellama-70b",
},
],
slashCommands: [
{

View file

@ -4,7 +4,6 @@ import {
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
import { retrieveContextItemsFromEmbeddings } from "../retrieval";
class CodebaseContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -18,6 +17,7 @@ class CodebaseContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const { retrieveContextItemsFromEmbeddings } = await import("../retrieval");
return retrieveContextItemsFromEmbeddings(extras, this.options, undefined);
}
async load(): Promise<void> {}

View file

@ -36,13 +36,15 @@ class DocsContextProvider extends BaseContextProvider {
return [
...chunks
.map((chunk) => ({
name: chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/"), // chunk.otherMetadata?.title || chunk.filepath,
name: chunk.filepath.includes("/tree/main") // For display of GitHub files
? chunk.filepath
.split("/")
.slice(1)
.join("/")
.split("/tree/main/")
.slice(1)
.join("/")
: chunk.otherMetadata?.title || chunk.filepath,
description: new URL(chunk.filepath, query).toString(),
content: chunk.content,
}))

View file

@ -75,9 +75,9 @@ class FileTreeContextProvider extends BaseContextProvider {
}
currentTree.files.push(parts.pop()!);
trees.push(formatFileTree(subDirTree));
}
trees.push(formatFileTree(subDirTree));
}
return [

View file

@ -7,7 +7,6 @@ import {
LoadSubmenuItemsArgs,
} from "../..";
import { getBasename, getLastNPathParts } from "../../util";
import { retrieveContextItemsFromEmbeddings } from "../retrieval";
class FolderContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
@ -21,6 +20,7 @@ class FolderContextProvider extends BaseContextProvider {
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const { retrieveContextItemsFromEmbeddings } = await import("../retrieval");
return retrieveContextItemsFromEmbeddings(extras, this.options, query);
}
async loadSubmenuItems(

View file

@ -1,10 +1,8 @@
import {
Chunk,
ContextItem,
ContextProviderExtras,
ILLM,
ModelProvider,
} from "..";
import { Chunk, ContextItem, ContextProviderExtras, ILLM } from "..";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch";
import { ChunkCodebaseIndex } from "../indexing/chunk/ChunkCodebaseIndex";
import { IndexTag } from "../indexing/types";
import { llmCanGenerateInParallel } from "../llm";
import { getBasename } from "../util";
const RERANK_PROMPT = (
@ -47,28 +45,6 @@ ${document}
Relevant:
`;
const PARALLEL_PROVIDERS: ModelProvider[] = [
"anthropic",
"bedrock",
"deepinfra",
"gemini",
"google-palm",
"huggingface-inference-api",
"huggingface-tgi",
"mistral",
"free-trial",
"replicate",
"together",
];
function llmCanGenerateInParallel(llm: ILLM): boolean {
if (llm.providerName === "openai") {
return llm.model.includes("gpt");
}
return PARALLEL_PROVIDERS.includes(llm.providerName);
}
async function scoreChunk(
chunk: Chunk,
llm: ILLM,
@ -133,24 +109,66 @@ export async function retrieveContextItemsFromEmbeddings(
return [];
}
const nRetrieve = options?.nRetrieve || 20;
const nFinal = options?.nFinal || 8;
const nFinal = options?.nFinal || 10;
const useReranking =
llmCanGenerateInParallel(extras.llm) &&
(options?.useReranking === undefined ? false : options?.useReranking);
const nRetrieve = useReranking === false ? nFinal : options?.nRetrieve || 20;
// Similarity search
let results = await extras.ide.retrieveChunks(
const ftsIndex = new FullTextSearchCodebaseIndex();
const workspaceDirs = await extras.ide.getWorkspaceDirs();
const branches = await Promise.all(
workspaceDirs.map((dir) => extras.ide.getBranch(dir))
);
const tags: IndexTag[] = workspaceDirs.map((directory, i) => ({
directory,
branch: branches[i],
artifactId: ChunkCodebaseIndex.artifactId,
}));
let ftsResults = await ftsIndex.retrieve(
tags,
extras.fullInput.trim().split(" ").join(" OR "),
nRetrieve / 2,
filterDirectory,
undefined
);
let vecResults = await extras.ide.retrieveChunks(
extras.fullInput,
useReranking === false ? nFinal : nRetrieve,
nRetrieve,
filterDirectory
);
// Now combine these (de-duplicate) and re-rank
let results = [...ftsResults];
for (const vecResult of vecResults) {
if (results.length >= nRetrieve) {
break;
}
if (
!ftsResults.find(
(r) =>
r.filepath === vecResult.filepath &&
r.startLine === vecResult.startLine &&
r.endLine === vecResult.endLine
)
) {
results.push(vecResult);
}
}
// Re-ranking
if (useReranking) {
results = await rerank(results, extras.llm, extras.fullInput, nFinal);
}
if (results.length === 0) {
throw new Error(
"Warning: No results found for @codebase context provider."
);
}
return [
...results.map((r) => {
const name = `${getBasename(r.filepath)} (${r.startLine}-${r.endLine})`;

View file

@ -28,6 +28,13 @@ class FileSystemIde implements IDE {
getTerminalContents(): Promise<string> {
return Promise.resolve("");
}
showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return Promise.resolve();
}
listWorkspaceContents(): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readdir("/tmp/continue", (err, files) => {
@ -94,6 +101,10 @@ class FileSystemIde implements IDE {
return Promise.resolve();
}
getBranch(dir: string): Promise<string> {
return Promise.resolve("");
}
async verticalDiffUpdate(
filepath: string,
startLine: number,

View file

@ -30,6 +30,14 @@ export class ExtensionIde implements IDE {
return await r("getWorkspaceDirs");
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
return await r("showLines", { filepath, startLine, endLine });
}
async listFolders(): Promise<string[]> {
return await r("listFolders");
}
@ -112,6 +120,10 @@ export class ExtensionIde implements IDE {
return r("sendChunkForFile", { chunk, embedding, tags });
}
async getBranch(dir: string): Promise<string> {
return r("getBranch", { dir });
}
retrieveChunks(
text: string,
n: number,

14
core/index.d.ts vendored
View file

@ -300,6 +300,11 @@ export interface IDE {
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
@ -316,6 +321,7 @@ export interface IDE {
getSearchResults(query: string): Promise<string>;
subprocess(command: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
// Embeddings
/**
@ -397,7 +403,9 @@ type TemplateType =
| "openchat"
| "deepseek"
| "xwin-coder"
| "neural-chat";
| "neural-chat"
| "codellama-70b"
| "llava";
type ModelProvider =
| "openai"
@ -426,7 +434,8 @@ export type ModelName =
| "gpt-4"
| "gpt-3.5-turbo-0613"
| "gpt-4-32k"
| "gpt-4-1106-preview"
| "gpt-4-0125-preview"
| "gpt-4-vision-preview"
// Open Source
| "mistral-7b"
| "mistral-8x7b"
@ -435,6 +444,7 @@ export type ModelName =
| "codellama-7b"
| "codellama-13b"
| "codellama-34b"
| "codellama-70b"
| "phi2"
| "phind-codellama-34b"
| "wizardcoder-7b"

View file

@ -0,0 +1,135 @@
import { Chunk, IndexingProgressUpdate } from "..";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
MarkCompleteCallback,
RefreshIndexResults,
} from "./types";
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
artifactId: string = "sqliteFts";
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(
path,
content,
tokenize = 'trigram'
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS fts_metadata (
id INTEGER PRIMARY KEY,
path TEXT NOT NULL,
cacheKey TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id),
FOREIGN KEY (id) REFERENCES fts (rowid)
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
for (let i = 0; i < results.compute.length; i++) {
const item = results.compute[i];
// Insert chunks
const chunks = await db.all(
`SELECT * FROM chunks WHERE path = ? AND cacheKey = ?`,
[item.path, item.cacheKey]
);
for (let chunk of chunks) {
const { lastID } = await db.run(
`INSERT INTO fts (path, content) VALUES (?, ?)`,
[item.path, chunk.content]
);
await db.run(
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)`,
[lastID, item.path, item.cacheKey, chunk.id]
);
}
yield {
progress: i / results.compute.length,
desc: `Indexing ${item.path}`,
};
markComplete([item], IndexResultType.Compute);
}
// Add tag
for (const item of results.addTag) {
markComplete([item], IndexResultType.AddTag);
}
// Remove tag
for (const item of results.removeTag) {
markComplete([item], IndexResultType.RemoveTag);
}
// Delete
for (const item of results.del) {
const { lastID } = await db.run(
`DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?`,
[item.path, item.cacheKey]
);
await db.run(`DELETE FROM fts WHERE rowid = ?`, [lastID]);
markComplete([item], IndexResultType.Delete);
}
}
async retrieve(
tags: IndexTag[],
text: string,
n: number,
directory: string | undefined,
filterPaths: string[] | undefined
): Promise<Chunk[]> {
const db = await SqliteDb.get();
const tagStrings = tags.map(tagToString);
const results = await db.all(
`SELECT fts_metadata.chunkId, fts_metadata.path, fts.content, rank
FROM fts
JOIN fts_metadata ON fts.rowid = fts_metadata.id
JOIN chunk_tags ON fts_metadata.chunkId = chunk_tags.chunkId
WHERE fts MATCH '${text.replace(
/\?/g,
""
)}' AND chunk_tags.tag IN (${tagStrings.map(() => "?").join(",")})
${
filterPaths
? `AND fts_metadata.path IN (${filterPaths
.map(() => "?")
.join(",")})`
: ""
}
ORDER BY rank
LIMIT ?`,
[...tagStrings, ...(filterPaths || []), n]
);
const chunks = await db.all(
`SELECT * FROM chunks WHERE id IN (${results.map(() => "?").join(",")})`,
results.map((result) => result.chunkId)
);
return chunks.map((chunk) => {
return {
filepath: chunk.path,
index: chunk.index,
startLine: chunk.startLine,
endLine: chunk.endLine,
content: chunk.content,
digest: chunk.cacheKey,
};
});
}
}

View file

@ -6,7 +6,7 @@ import { MAX_CHUNK_SIZE } from "../llm/constants";
import { getBasename } from "../util";
import { getLanceDbPath } from "../util/paths";
import { chunkDocument } from "./chunk/chunk";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
CodebaseIndex,
IndexResultType,
@ -15,10 +15,6 @@ import {
RefreshIndexResults,
} from "./types";
export function tagToString(tag: IndexTag): string {
return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
}
// LanceDB converts to lowercase, so names must all be lowercase
interface LanceDbRow {
uuid: string;
@ -283,7 +279,7 @@ export class LanceDbIndex implements CodebaseIndex {
}
allResults = allResults
.sort((a, b) => b._distance - a._distance)
.sort((a, b) => a._distance - b._distance)
.slice(0, n);
const sqliteDb = await SqliteDb.get();

View file

@ -0,0 +1,127 @@
import { IndexingProgressUpdate } from "../..";
import { MAX_CHUNK_SIZE } from "../../llm/constants";
import { getBasename } from "../../util";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex";
import {
CodebaseIndex,
IndexResultType,
IndexTag,
MarkCompleteCallback,
RefreshIndexResults,
} from "../types";
import { chunkDocument } from "./chunk";
export class ChunkCodebaseIndex implements CodebaseIndex {
static artifactId: string = "chunks";
artifactId: string = ChunkCodebaseIndex.artifactId;
readFile: (filepath: string) => Promise<string>;
constructor(readFile: (filepath: string) => Promise<string>) {
this.readFile = readFile;
}
private async _createTables(db: DatabaseConnection) {
await db.exec(`CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cacheKey TEXT NOT NULL,
path TEXT NOT NULL,
idx INTEGER NOT NULL,
startLine INTEGER NOT NULL,
endLine INTEGER NOT NULL,
content TEXT NOT NULL
)`);
await db.exec(`CREATE TABLE IF NOT EXISTS chunk_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tag TEXT NOT NULL,
chunkId INTEGER NOT NULL,
FOREIGN KEY (chunkId) REFERENCES chunks (id)
)`);
}
async *update(
tag: IndexTag,
results: RefreshIndexResults,
markComplete: MarkCompleteCallback
): AsyncGenerator<IndexingProgressUpdate, any, unknown> {
const db = await SqliteDb.get();
await this._createTables(db);
const tagString = tagToString(tag);
// Compute chunks for new files
const contents = await Promise.all(
results.compute.map(({ path }) => this.readFile(path))
);
for (let i = 0; i < results.compute.length; i++) {
const item = results.compute[i];
// Insert chunks
for await (let chunk of chunkDocument(
item.path,
contents[i],
MAX_CHUNK_SIZE,
item.cacheKey
)) {
const { lastID } = await db.run(
`INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`,
[
chunk.digest,
chunk.filepath,
chunk.index,
chunk.startLine,
chunk.endLine,
chunk.content,
]
);
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
lastID,
tagString,
]);
}
yield {
progress: i / results.compute.length,
desc: `Chunking ${getBasename(item.path)}`,
};
markComplete([item], IndexResultType.Compute);
}
// Add tag
for (const item of results.addTag) {
const chunksWithPath = await db.all(
`SELECT * FROM chunks WHERE cacheKey = ?`,
[item.cacheKey]
);
for (const chunk of chunksWithPath) {
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
chunk.id,
tagString,
]);
}
markComplete([item], IndexResultType.AddTag);
}
// Remove tag
for (const item of results.removeTag) {
await db.run(`DELETE FROM chunk_tags WHERE tag = ?`, [tagString]);
markComplete([item], IndexResultType.RemoveTag);
}
// Delete
for (const item of results.del) {
const deleted = await db.run(`DELETE FROM chunks WHERE cacheKey = ?`, [
item.cacheKey,
]);
// Delete from chunk_tags
await db.run(`DELETE FROM chunk_tags WHERE chunkId = ?`, [
deleted.lastID,
]);
markComplete([item], IndexResultType.Delete);
}
}
}

View file

@ -58,14 +58,29 @@ export async function* markdownChunker(
hLevel: number
): AsyncGenerator<ChunkWithoutID> {
if (countTokens(content, "gpt-4") <= maxChunkSize) {
const header = findHeader(content.split("\n"));
yield {
content,
startLine: 0,
endLine: content.split("\n").length,
otherMetadata: {
fragment: cleanFragment(header),
title: cleanHeader(header),
},
};
return;
} else if (hLevel > 4) {
yield* basicChunker(content, maxChunkSize);
const header = findHeader(content.split("\n"));
for (const chunk of basicChunker(content, maxChunkSize)) {
yield {
...chunk,
otherMetadata: {
fragment: cleanFragment(header),
title: cleanHeader(header),
},
};
}
return;
}

View file

@ -43,11 +43,16 @@ function shouldFilterPath(pathname: string, baseUrl: URL): boolean {
return false;
}
async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
async function* crawlLinks(
path: string,
baseUrl: URL,
visited: Set<string>
): AsyncGenerator<number> {
if (visited.has(path) || shouldFilterPath(path, baseUrl)) {
return;
}
visited.add(path);
yield visited.size;
const response = await fetch(new URL(path, baseUrl));
const text = await response.text();
@ -71,8 +76,12 @@ async function crawlLinks(path: string, baseUrl: URL, visited: Set<string>) {
});
await Promise.all(
children.map((child) => crawlLinks(child, baseUrl, visited))
children.map(async (child) => {
for await (const _ of crawlLinks(child, baseUrl, visited)) {
}
})
);
yield visited.size;
}
async function crawlGithubRepo(baseUrl: URL) {
@ -116,25 +125,44 @@ async function crawlGithubRepo(baseUrl: URL) {
return paths;
}
export async function crawlSubpages(baseUrl: URL) {
export async function* crawlSubpages(
baseUrl: URL
): AsyncGenerator<number, string[]> {
// Special case for GitHub repos
if (baseUrl.hostname === "github.com") {
return crawlGithubRepo(baseUrl);
}
// First, check if the parent of the path redirects to the same page
const parentUrl = new URL(baseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
const response = await fetch(parentUrl);
let useParent = response.url === baseUrl.toString();
if (baseUrl.pathname.endsWith("/")) {
baseUrl.pathname = baseUrl.pathname.slice(0, -1);
}
let realBaseUrl = new URL(baseUrl);
while (true) {
let parentUrl = new URL(realBaseUrl);
parentUrl.pathname = parentUrl.pathname.split("/").slice(0, -1).join("/");
if (
parentUrl.pathname === realBaseUrl.pathname ||
parentUrl.pathname === ""
) {
break;
}
const response = await fetch(parentUrl);
const redirected = response.url.toString() === baseUrl.toString() + "/";
if (!redirected) {
break;
}
realBaseUrl = parentUrl;
}
const visited = new Set<string>();
await crawlLinks(
(useParent ? parentUrl.pathname : baseUrl.pathname) || "/",
baseUrl,
for await (const count of crawlLinks(
realBaseUrl.pathname || "/",
realBaseUrl,
visited
);
)) {
yield count;
}
return [...visited];
}

View file

@ -22,7 +22,7 @@ async function createDocsTable(db: Database<sqlite3.Database>) {
db.exec(`CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title STRING NOT NULL,
baseUrl STRING NOT NULL
baseUrl STRING NOT NULL UNIQUE
)`);
}

View file

@ -16,7 +16,7 @@ export async function* indexDocs(
embeddingsProvider: EmbeddingsProvider
): AsyncGenerator<IndexingProgressUpdate> {
const existingDocs = await listDocs();
if (existingDocs.find((doc) => doc.title === title)) {
if (existingDocs.find((doc) => doc.baseUrl === baseUrl.toString())) {
yield {
progress: 1,
desc: "Already indexed",
@ -29,8 +29,23 @@ export async function* indexDocs(
desc: "Finding subpages",
};
let subpaths = await crawlSubpages(baseUrl);
console.log("Found subpaths", subpaths);
const subpathGenerator = crawlSubpages(baseUrl);
let { value, done } = await subpathGenerator.next();
while (true) {
if (done) {
break;
}
yield {
progress: 0,
desc: `Finding subpages (${value})`,
};
const next = await subpathGenerator.next();
value = next.value;
done = next.done;
}
let subpaths = value as string[];
const chunks: Chunk[] = [];
const embeddings: number[][] = [];
@ -53,7 +68,7 @@ export async function* indexDocs(
for (let i = 0; i < subpaths.length; i++) {
const subpath = subpaths[i];
yield {
progress: 1 / (subpaths.length + 1),
progress: Math.max(1, Math.floor(100 / (subpaths.length + 1))),
desc: `${subpath}`,
};
@ -75,6 +90,7 @@ export async function* indexDocs(
(chunk.otherMetadata?.fragment
? `#${chunk.otherMetadata.fragment}`
: ""),
otherMetadata: chunk.otherMetadata,
index,
digest: subpath,
});

View file

@ -4,7 +4,7 @@ import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
static defaultOptions: Partial<EmbedOptions> | undefined = {
apiBase: "https://api.openai.com",
model: "text-embedding-ada-002",
model: "text-embedding-3-large",
};
get id(): string {
@ -16,13 +16,10 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
if (apiBase?.endsWith("/")) {
apiBase = apiBase.slice(0, -1);
}
if (apiBase?.endsWith("/v1")) {
apiBase = apiBase.slice(0, -3);
}
return await Promise.all(
chunks.map(async (chunk) => {
const resp = await fetch(`${apiBase}/v1/embeddings`, {
const resp = await fetch(`${apiBase}/embeddings`, {
method: "POST",
body: JSON.stringify({
input: chunk,

View file

@ -15,6 +15,10 @@ import {
export type DatabaseConnection = Database<sqlite3.Database>;
export function tagToString(tag: IndexTag): string {
return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
}
export class SqliteDb {
static db: DatabaseConnection | null = null;

View file

@ -17,6 +17,8 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
"gpt-35-turbo": 4096,
"gpt-4-32k": 32_768,
"gpt-4-1106-preview": 128_000,
"gpt-4-vision": 128_000,
"gpt-4-0125-preview": 128_000,
};
const TOKEN_BUFFER_FOR_SAFETY = 350;

View file

@ -6,10 +6,12 @@ import {
LLMFullCompletionOptions,
LLMOptions,
LLMReturnValue,
ModelName,
ModelProvider,
RequestOptions,
TemplateType,
} from "..";
import mergeJson from "../util/merge";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
@ -24,8 +26,10 @@ import {
import {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
llama2TemplateMessages,
llavaTemplateMessages,
neuralChatTemplateMessages,
openchatTemplateMessages,
phi2TemplateMessages,
@ -36,6 +40,7 @@ import {
} from "./templates/chat";
import {
alpacaEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
deepseekEditPrompt,
mistralEditPrompt,
@ -47,14 +52,21 @@ import {
xWinCoderEditPrompt,
zephyrEditPrompt,
} from "./templates/edit";
import CompletionOptionsForModels from "./templates/options";
const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
"lmstudio",
"openai",
"ollama",
"together",
];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = ["openai", "ollama"];
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
"openai",
"ollama",
"google-palm",
"free-trial",
];
export function modelSupportsImages(
provider: ModelProvider,
@ -63,19 +75,53 @@ export function modelSupportsImages(
if (!PROVIDER_SUPPORTS_IMAGES.includes(provider)) {
return false;
}
if (model.includes("llava")) {
return true;
}
if (["gpt-4-vision-preview"].includes(model)) {
return true;
}
if (
model === "gemini-ultra" &&
(provider === "google-palm" || provider === "free-trial")
) {
return true;
}
return false;
}
const PARALLEL_PROVIDERS: ModelProvider[] = [
"anthropic",
"bedrock",
"deepinfra",
"gemini",
"google-palm",
"huggingface-inference-api",
"huggingface-tgi",
"mistral",
"free-trial",
"replicate",
"together",
];
export function llmCanGenerateInParallel(llm: ILLM): boolean {
if (llm.providerName === "openai") {
return llm.model.includes("gpt");
}
return PARALLEL_PROVIDERS.includes(llm.providerName);
}
function autodetectTemplateType(model: string): TemplateType | undefined {
const lower = model.toLowerCase();
if (lower.includes("codellama") && lower.includes("70b")) {
return "codellama-70b";
}
if (
lower.includes("gpt") ||
lower.includes("chat-bison") ||
@ -85,6 +131,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
return undefined;
}
if (lower.includes("llava")) {
return "llava";
}
if (lower.includes("xwin")) {
return "xwin-coder";
}
@ -163,6 +213,8 @@ function autodetectTemplateFunction(
openchat: openchatTemplateMessages,
"xwin-coder": xWinCoderTemplateMessages,
"neural-chat": neuralChatTemplateMessages,
llava: llavaTemplateMessages,
"codellama-70b": codeLlama70bTemplateMessages,
none: null,
};
@ -203,6 +255,8 @@ function autodetectPromptTemplates(
editTemplate = xWinCoderEditPrompt;
} else if (templateType === "neural-chat") {
editTemplate = neuralChatEditPrompt;
} else if (templateType === "codellama-70b") {
editTemplate = codeLlama70bEditPrompt;
} else if (templateType) {
editTemplate = simplestEditPrompt;
}
@ -273,6 +327,12 @@ export abstract class BaseLLM implements ILLM {
model: options.model || "gpt-4",
maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS,
};
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
this.completionOptions,
CompletionOptionsForModels[options.model as ModelName] || {}
);
}
this.requestOptions = options.requestOptions;
this.promptTemplates = {
...autodetectPromptTemplates(options.model, templateType),
@ -355,11 +415,11 @@ export abstract class BaseLLM implements ILLM {
.map(([key, value]) => `${key}: ${value}`)
.join("\n");
return `Settings:
${settings}
${settings}
############################################
############################################
${prompt}`;
${prompt}`;
}
private _logTokensGenerated(model: string, completion: string) {
@ -404,10 +464,10 @@ export abstract class BaseLLM implements ILLM {
delete options.log;
delete options.raw;
const completionOptions: CompletionOptions = {
...this.completionOptions,
...options,
};
const completionOptions: CompletionOptions = mergeJson(
this.completionOptions,
options
);
return { completionOptions, log, raw };
}
@ -455,6 +515,10 @@ export abstract class BaseLLM implements ILLM {
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return { prompt, completion };
}
@ -485,6 +549,10 @@ export abstract class BaseLLM implements ILLM {
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return completion;
}
@ -543,6 +611,10 @@ export abstract class BaseLLM implements ILLM {
}
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return { prompt, completion };
}

View file

@ -3,7 +3,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../..";
import { streamResponse } from "../stream";
// const SERVER_URL = "http://localhost:3000";
const SERVER_URL = "https://node-proxy-server-l6vsfbzhba-uw.a.run.app";
const SERVER_URL = "https://node-proxy-server-blue-l6vsfbzhba-uw.a.run.app";
class FreeTrial extends BaseLLM {
static providerName: ModelProvider = "free-trial";
@ -47,6 +47,24 @@ class FreeTrial extends BaseLLM {
}
}
protected _convertMessage(message: ChatMessage) {
if (typeof message.content === "string") {
return message;
}
const parts = message.content.map((part) => {
return {
type: part.type,
text: part.text,
image_url: { ...part.imageUrl, detail: "low" },
};
});
return {
...message,
content: parts,
};
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
@ -57,7 +75,7 @@ class FreeTrial extends BaseLLM {
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({
messages,
messages: messages.map(this._convertMessage),
...args,
}),
});

View file

@ -3,6 +3,7 @@ import {
ChatMessage,
CompletionOptions,
LLMOptions,
MessagePart,
ModelProvider,
} from "../..";
import { stripImages } from "../countTokens";
@ -42,6 +43,19 @@ class GooglePalm extends BaseLLM {
}
}
private _continuePartToGeminiPart(part: MessagePart) {
return part.type === "text"
? {
text: part.text,
}
: {
inlineData: {
mimeType: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
private async *streamChatGemini(
messages: ChatMessage[],
options: CompletionOptions
@ -51,7 +65,10 @@ class GooglePalm extends BaseLLM {
contents: messages.map((msg) => {
return {
role: msg.role === "assistant" ? "model" : "user",
parts: [{ text: msg.content }],
parts:
typeof msg.content === "string"
? [{ text: msg.content }]
: msg.content.map(this._continuePartToGeminiPart),
};
}),
};

View file

@ -67,6 +67,7 @@ class Ollama extends BaseLLM {
"codellama-7b": "codellama:7b",
"codellama-13b": "codellama:13b",
"codellama-34b": "codellama:34b",
"codellama-70b": "codellama:70b",
"phi-2": "phi:2.7b",
"phind-codellama-34b": "phind-codellama:34b-v2",
"wizardcoder-7b": "wizardcoder:7b-python",
@ -103,6 +104,7 @@ class Ollama extends BaseLLM {
const finalOptions: any = {
model: this._getModel(),
raw: true,
keep_alive: 60 * 30, // 30 minutes
options: {
temperature: options.temperature,
top_p: options.topP,

View file

@ -24,7 +24,7 @@ const NON_CHAT_MODELS = [
class OpenAI extends BaseLLM {
static providerName: ModelProvider = "openai";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.openai.com",
apiBase: "https://api.openai.com/v1",
};
protected _convertMessage(message: ChatMessage) {
@ -87,9 +87,7 @@ class OpenAI extends BaseLLM {
if (url.endsWith("/")) {
url = url.slice(0, -1);
}
if (!url.endsWith("/v1") && !url.includes("api.perplexity.ai")) {
url += "/v1";
}
return url + "/completions";
}
}
@ -110,6 +108,10 @@ class OpenAI extends BaseLLM {
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
const args: any = this._convertArgs(options, []);
args.prompt = prompt;
delete args.messages;
const response = await this.fetch(this._getCompletionUrl(), {
method: "POST",
headers: {
@ -118,16 +120,7 @@ class OpenAI extends BaseLLM {
"api-key": this.apiKey || "", // For Azure
},
body: JSON.stringify({
...{
prompt,
model: options.model,
max_tokens: options.maxTokens,
temperature: options.temperature,
top_p: options.topP,
frequency_penalty: options.frequencyPenalty,
presence_penalty: options.presencePenalty,
stop: options.stop,
},
...args,
stream: true,
}),
});
@ -153,10 +146,6 @@ class OpenAI extends BaseLLM {
url = url.slice(0, -1);
}
if (!url.includes("/v1") && !url.includes("api.perplexity.ai")) {
// includes instead of endsWith becuase DeepInfra uses /v1/openai/chat/completions
url += "/v1";
}
return url + "/chat/completions";
}
}
@ -178,6 +167,15 @@ class OpenAI extends BaseLLM {
return;
}
let body = {
...this._convertArgs(options, messages),
stream: true,
};
// Empty messages cause an error in LM Studio
body.messages = body.messages.map((m) => ({
...m,
content: m.content === "" ? " " : m.content,
})) as any;
const response = await this.fetch(this._getChatUrl(), {
method: "POST",
headers: {
@ -185,10 +183,7 @@ class OpenAI extends BaseLLM {
Authorization: `Bearer ${this.apiKey}`,
"api-key": this.apiKey || "", // For Azure
},
body: JSON.stringify({
...this._convertArgs(options, messages),
stream: true,
}),
body: JSON.stringify(body),
});
for await (const value of streamSse(response)) {

View file

@ -1,17 +1,23 @@
import { BaseLLM } from "..";
import { CompletionOptions, LLMOptions, ModelProvider } from "../..";
import { streamSse } from "../stream";
import {
ChatMessage,
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../..";
class Together extends BaseLLM {
import OpenAI from "./OpenAI";
class Together extends OpenAI {
static providerName: ModelProvider = "together";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://api.together.xyz",
apiBase: "https://api.together.xyz/v1",
};
private static MODEL_IDS: { [name: string]: string } = {
"codellama-7b": "togethercomputer/CodeLlama-7b-Instruct",
"codellama-13b": "togethercomputer/CodeLlama-13b-Instruct",
"codellama-34b": "togethercomputer/CodeLlama-34b-Instruct",
"codellama-70b": "codellama/CodeLlama-70b-Instruct-hf",
"llama2-7b": "togethercomputer/llama-2-7b-chat",
"llama2-13b": "togethercomputer/llama-2-13b-chat",
"llama2-70b": "togethercomputer/llama-2-70b-chat",
@ -24,17 +30,9 @@ class Together extends BaseLLM {
return Together.MODEL_IDS[model] || this.model;
}
private _convertArgs(options: CompletionOptions, prompt: string) {
const finalOptions = {
prompt,
model: this._getModelName(options.model),
temperature: options.temperature,
top_p: options.topP,
top_k: options.topK,
max_tokens: options.maxTokens,
repetition_penalty: options.frequencyPenalty,
};
protected _convertArgs(options: any, messages: ChatMessage[]) {
const finalOptions = super._convertArgs(options, messages);
finalOptions.model = this._getModelName(options.model);
return finalOptions;
}
@ -42,22 +40,8 @@ class Together extends BaseLLM {
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
const response = await this.fetch(`${this.apiBase}/inference`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
...this._convertArgs(options, prompt),
stream_tokens: true,
}),
});
for await (const value of streamSse(response)) {
if (value.choices) {
yield value.choices[0].text;
}
for await (const chunk of this._legacystreamComplete(prompt, options)) {
yield chunk;
}
}
}

View file

@ -69,6 +69,26 @@ function anthropicTemplateMessages(messages: ChatMessage[]): string {
return prompt;
}
function llavaTemplateMessages(msgs: ChatMessage[]): string {
`A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.
USER: <image>{prompt}
ASSISTANT:`;
let prompt =
"A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.";
for (const msg of msgs) {
prompt += msg.role === "user" ? "USER: <image>" : "ASSISTANT: ";
prompt += msg.content;
prompt += "\n";
}
prompt += "ASSISTANT: ";
return prompt;
}
function zephyrTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "";
@ -244,11 +264,29 @@ function neuralChatTemplateMessages(msgs: ChatMessage[]): string {
return prompt;
}
/**
'<s>Source: system\n\n System prompt <step> Source: user\n\n First user query <step> Source: assistant\n\n Model response to first query <step> Source: user\n\n Second user query <step> Source: assistant\nDestination: user\n\n '
*/
function codeLlama70bTemplateMessages(msgs: ChatMessage[]): string {
let prompt = "<s>";
for (const msg of msgs) {
prompt += `Source: ${msg.role}\n\n ${stripImages(msg.content).trim()}`;
prompt += " <step> ";
}
prompt += "Source: assistant\nDestination: user\n\n";
return prompt;
}
export {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
llama2TemplateMessages,
llavaTemplateMessages,
neuralChatTemplateMessages,
openchatTemplateMessages,
phi2TemplateMessages,

View file

@ -138,18 +138,25 @@ Sure! Here's the code you requested:
\`\`\`{{{language}}}
`;
const codeLlama70bEditPrompt = `<s>Source: system\n\n You are an expert programmer and write code on the first attempt without any errors or fillers. <step> Source: user\n\n Rewrite the code to satisfy this request: "{{{userInput}}}"
\`\`\`{{{language}}}
{{{codeToEdit}}}
\`\`\` <step> Source: assistant\nDestination: user\n\n `;
export {
alpacaEditPrompt,
codeLlama70bEditPrompt,
codellamaEditPrompt,
codellamaInfillEditPrompt,
deepseekEditPrompt,
gptEditPrompt,
mistralEditPrompt,
neuralChatEditPrompt,
openchatEditPrompt,
phindEditPrompt,
simplestEditPrompt,
simplifiedEditPrompt,
xWinCoderEditPrompt,
zephyrEditPrompt,
neuralChatEditPrompt,
};

View file

@ -0,0 +1,11 @@
import { CompletionOptions, ModelName } from "../..";
const CompletionOptionsForModels: {
[key in ModelName]?: Partial<CompletionOptions>;
} = {
"codellama-70b": {
stop: ["Source: assistant"],
},
};
export default CompletionOptionsForModels;

View file

@ -16,13 +16,17 @@ export function removeQuotesAndEscapes(output: string): string {
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
if (
while (
(output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
) {
output = output.slice(1, -1);
}
while (output.startsWith("`") && output.endsWith("`")) {
output = output.slice(1, -1);
}
return output;
}
@ -131,6 +135,10 @@ export function getMarkdownLanguageTagForFile(filepath: string): string {
return "python";
case "js":
return "javascript";
case "jsx":
return "jsx";
case "tsx":
return "tsx";
case "ts":
return "typescript";
case "java":

36
core/util/merge.ts Normal file
View file

@ -0,0 +1,36 @@
type JsonObject = { [key: string]: any };
export function mergeJson(first: JsonObject, second: JsonObject): any {
try {
for (var key in second) {
let secondValue = second[key];
if (!(key in first)) {
// New value
first[key] = secondValue;
continue;
}
const firstValue = first[key];
if (Array.isArray(secondValue)) {
// Array
first[key] = [...firstValue, ...secondValue];
} else if (typeof secondValue === "object") {
// Object
first[key] = mergeJson(firstValue, secondValue);
} else {
// Other (boolean, number, string)
first[key] = secondValue;
}
}
return first;
} catch (e) {
console.error("Error merging JSON", e, first, second);
return {
...first,
...second,
};
}
}
export default mergeJson;

View file

@ -32,6 +32,14 @@ Type '@terminal' to reference the contents of your IDE's terminal.
{ "name": "terminal" }
```
### Documentation
Type `@docs` to index and retrieve snippets from any documentation site. You can add any site by selecting "Add Docs" in the dropdown, then entering the root URL of the documentation site and a title to remember it by. After the site has been indexed, you can type `@docs`, select your documentation from the dropdown, and Continue will use similarity search to automatically find important sections when answering your question.
```json
{ "name": "docs" }
```
### Open Files
Type '@open' to reference the contents of all of your open files. Set `onlyPinned` to `true` to only reference pinned files.
@ -129,7 +137,11 @@ interface CustomContextProvider {
}
```
As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database.
As an example, let's say you have a set of internal documents that have been indexed in a vector database. You've set up a simple REST API that allows internal users to query and get back relevant snippets. This context provider will send the query to this server and return the results from the vector database. The return type of `getContextItems` _must_ be an array of objects that have all of the following properties:
- `name`: The name of the context item, which will be displayed as a title
- `description`: A longer description of the context item
- `content`: The actual content of the context item, which will be fed to the LLM as context
```typescript title="~/.continue/config.ts"
const RagContextProvider: CustomContextProvider = {
@ -172,6 +184,83 @@ export function modifyConfig(config: Config): Config {
No modification in `config.json` is necessary.
### Custom Context Providers with Submenu or Query
There are 3 types of context providers: "normal", "query", and "submenu". The "normal" type is the default, and is what we've seen so far.
The **"query"** type is used when you want to display a text box to the user, and then use the contents of that text box to generate the context items. Built-in examples include ["search"](#exact-search) and ["google"](#google). This text is what gets passed to the "query" argument in `getContextItems`. To implement a "query" context provider, simply set `"type": "query"` in your custom context provider object.
The **"submenu"** type is used when you want to display a list of searchable items in the dropdown. Built-in examples include ["issue"](#github-issues) and ["folder"](#folders). To implement a "submenu" context provider, set `"type": "submenu"` and implement the `loadSubmenuItems` and `getContextItems` functions. Here is an example that shows a list of all README files in the current workspace:
```typescript title="~/.continue/config.ts"
const ReadMeContextProvider: CustomContextProvider = {
title: "readme",
displayTitle: "README",
description: "Reference README.md files in your workspace",
type: "submenu",
getContextItems: async (
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> => {
// 'query' is the filepath of the README selected from the dropdown
const content = await extras.ide.readFile(query);
return [
{
name: getFolder(query),
description: getFolderAndBasename(query),
content,
},
];
},
loadSubmenuItems: async (
args: LoadSubmenuItemsArgs
): Promise<ContextSubmenuItem[]> => {
// Filter all workspace files for READMEs
const allFiles = await args.ide.listWorkspaceContents();
const readmes = allFiles.filter((filepath) =>
filepath.endsWith("README.md")
);
// Return the items that will be shown in the dropdown
return readmes.map((filepath) => {
return {
id: filepath,
title: getFolder(filepath),
description: getFolderAndBasename(filepath),
};
});
},
};
export function modifyConfig(config: Config): Config {
if (!config.contextProviders) {
config.contextProviders = [];
}
config.contextProviders.push(ReadMeContextProvider);
return config;
}
function getFolder(path: string): string {
return path.split(/[\/\\]/g).slice(-2)[0];
}
function getFolderAndBasename(path: string): string {
return path
.split(/[\/\\]/g)
.slice(-2)
.join("/");
}
```
The flow of information in the above example is as follows:
1. The user types `@readme` and selects it from the dropdown, now displaying the submenu where they can search for any item returned by `loadSubmenuItems`.
2. The user selects one of the READMEs in the submenu, enters the rest of their input, and presses enter.
3. The `id` of the chosen `ContextSubmenuItem` is passed to `getContextItems` as the `query` argument. In this case it is the filepath of the README.
4. The `getContextItems` function can then use the `query` to retrieve the full contents of the README and format the content before returning the context item which will be included in the prompt.
### Importing outside modules
> Context providers run in a NodeJS environment, but for the time being the `modifyConfig` function will be called both from NodeJS _and_ the browser. This means that if you are importing packages requiring NodeJS, you should dynamically import them inside of the context provider (e.g. `const moduleA = await import('./moduleA');`).
@ -185,9 +274,11 @@ Continue will use [esbuild](https://esbuild.github.io/) to bundle your `config.t
- `title`: An identifier for the context provider
- `displayTitle` (optional): The title displayed in the dropdown
- `description` (optional): The longer description displayed in the dropdown when hovered
- `type` (optional): The type of context provider. Options are "normal", "query", and "submenu". Defaults to "normal".
- `getContextItems`: A function that returns the documents to include in the prompt. It should return a list of `ContextItem`s, and is given access to the following arguments:
- `extras.fullInput`: A string representing the user's full input to the text box. This can be used for example to generate an embedding to compare against a set of other embedded documents
- `extras.embeddingsProvider`: The embeddings provider has an `embed` function that will convert text (such as `fullInput`) to an embedding
- `extras.llm`: The current default LLM, which you can use to make completion requests
- `extras.ide`: An instance of the `IDE` class, which lets you gather various sources of information from the IDE, including the contents of the terminal, the list of open files, or any warnings in the currently open file.
- `query`: (not currently used) A string representing the query
- `loadSubmenuItems` (optional): A function that returns a list of `ContextSubmenuItem`s to display in a submenu. It is given access to an `IDE`, the same that is passed to `getContextItems`.

View file

@ -9,12 +9,12 @@ Once you're ready to use your own API key or a different model / provider, press
If you are unsure what model or provider to use, here is a rule of thumb:
- Use GPT-4 via OpenAI if you want the best possible model overall right now
- Use X via Together if you want the best open-source model right now
- Use X via Ollama if you want to run a model locally on Mac or Linux
- Use X via LM Studio if you want to run a model locally on Windows
- Use Phind CodeLlama or Mixtral 8x7B via Together if you want the best open-source model right now
- Use CodeLlama via Ollama if you want to run a model locally on Mac or Linux
- Use CodeLlama via LM Studio if you want to run a model locally on Windows
Learn more:
- [Select a provider](select-provider.md)
- [Select a model](select-model.md)
- [Configuration](configuration.md)
- [Configuration](configuration.md)

View file

@ -17,6 +17,7 @@ The default models available in the GUI:
- [Code Llama-Instruct-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [Code Llama-Instruct-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [Code Llama-Instruct-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [Code Llama-Instruct-70B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#1-code-llama)
- [WizardCoder-7B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder)
- [WizardCoder-13B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder)
- [WizardCoder-34B](https://github.com/continuedev/what-llm-to-use/blob/main/README.md#2-wizardcoder)

View file

@ -3,7 +3,7 @@ import JSONSchemaViewer from "@theme/JSONSchemaViewer";
# Configuration Options
The following shows the JSON Schema definition for `config.json`:
The following shows the JSON Schema definition for `config.json`. You can also define a partial `config.json` object in a file called `.continuerc.json` at the root of your workspace. This will be [applied on top of](https://github.com/continuedev/continue/blob/74c1eb5e25c517c575f72d26227d31d5d2ea18ed/extensions/vscode/src/ideProtocol.ts#L165-L173) any configuration from `config.json`.
<JSONSchemaViewer
schema={Schema}

View file

@ -18,6 +18,27 @@ To solve many problems, the first step is reading the logs to find the relevant
4. Select the `Console` tab
5. Read the console logs
## Configure Certificates
If you're seeing a `fetch failed` error and your network requires custom certificates, you will need to configure them in `config.json`. In each of the objects in the `"models"` array, add `requestOptions.caBundlePath` like this:
```json
{
"models": [
{
"title": "My Model",
...
"requestOptions": {
"caBundlePath": "/path/to/cert.pem"
}
}
],
...
}
```
You may also set `requestOptions.caBundlePath` to an array of paths to multiple certificates.
## Download a Newer Version
If you are using an older version of the Continue extension, particularly one which depends on the separate Python server, we would recommend downloading the latest version of the extension, as we are constantly making bug fixes and are likely to have solved any major issues.

View file

@ -8,15 +8,30 @@ keywords: [talk, embeddings, codebase, experimental]
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`.
<!-- ## How to use codebase retrieval -->
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:
Here are some common use cases where it can be useful:
### Asking high-level codebase questions
- Asking high-level questions about your codebase
- "How do I add a new endpoint to the server?"
- "Do we use VS Code's CodeLens feature anywhere?"
- "Is there any code written already to convert HTML to markdown?"
- Generate code using existing samples as reference
- "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
- "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`
- -->
Here are use cases where it is not useful:
- When you need the LLM to see _literally every_ file in your codebase
- "Find everywhere where the `foo` function is called"
- "Review our codebase and find any spelling mistakes"
- Refactoring
- "Add a new parameter to the `bar` function and update usages"
## Configuration
@ -121,3 +136,5 @@ export function modifyConfig(config: Config): Config {
## Customizing which files are indexed
Continue respects `.gitignore` files in order to determine which files should not be indexed. If you'd like to exclude additional files, you can add them to a `.continueignore` file, which follows the exact same rules as `.gitignore`.
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 `tags_catalog` table within this file.

View file

@ -172,7 +172,8 @@
"deepseek",
"openchat",
"xwin-coder",
"neural-chat"
"neural-chat",
"codellama-70b"
],
"type": "string"
},
@ -334,7 +335,7 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview"
"gpt-4-0125-preview"
]
}
}
@ -386,7 +387,8 @@
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"mistral-medium"
"gpt-4-vision-preview",
"codellama-70b"
]
}
}
@ -417,7 +419,8 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
"gpt-4-vision-preview",
"mistral-7b",
"mistral-8x7b",
"llama2-7b",
@ -425,6 +428,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -502,6 +506,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b"
]
},
@ -557,6 +562,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -596,6 +602,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phi-2",
"phind-codellama-34b",
"wizardcoder-7b",
@ -762,7 +769,8 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
"gpt-4-vision-preview",
"mistral-7b",
"mistral-8x7b",
"llama2-7b",
@ -770,6 +778,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -959,7 +968,9 @@
"codebase",
"problems",
"folder",
"issue"
"issue",
"docs",
"tree"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@ -972,7 +983,9 @@
"Reference all linting errors and warnings in the currently open file",
"Include important files from a folder in the prompt, as determined by similarity search",
"Reference GitHub issues from a repository",
"Retrieve important pages from a documentation website, as determined by similarity search"
"Retrieve important pages from a documentation website, as determined by similarity search",
"Index and retrieve the contents of any documentation site, using embeddings to find important snippets",
"Display a file tree of the current workspace"
],
"type": "string"
},

View file

@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@ -7,17 +7,6 @@
<title>Continue</title>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" href="/assets/index.css" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Lexend:wght@300&display=swap"
rel="stylesheet"
/>
<link
href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div id="root"></div>

View file

@ -8,7 +8,21 @@ and is generated by [Changie](https://github.com/miniscruff/changie).
Pre-release Changes
### Added
* Image support
* Full-text search index for retrieval
* Docs context provider
* CodeLlama-70b support
### Fixed
* Fixed proxy setting in config.json
## v0.8.2 - 2024-01-23
### Added
* Add codellama and gemini to free trial, using new server
* Local codebase syncing and embeddings using LanceDB
* Improved VS Code theme matching
### Changed
* Updates to packaging to download native modules for current platform (lancedb, sqlite, onnxruntime, tree-sitter wasms)
* Context providers now run from the extension side (in Node.js instead of browser javascript)
## v0.8.1 - 2024-01-08

View file

@ -4,7 +4,6 @@ This is the Continue VS Code Extension. Its primary jobs are
1. Implement the IDE side of the Continue IDE protocol, allowing a Continue server to interact natively in an IDE. This happens in `src/continueIdeClient.ts`.
2. Open the Continue React app in a side panel. The React app's source code lives in the `gui` directory. The panel is opened by the `continue.openContinueGUI` command, as defined in `src/commands.ts`.
3. Run a Continue server in the background, which connects to both the IDE protocol and the React app. The server is launched in `src/activation/environmentSetup.ts` by calling Python code that lives in `server/` (unless extension settings define a server URL other than localhost:65432, in which case the extension will just connect to that).
# How to run the extension
@ -12,7 +11,7 @@ See [Environment Setup](../CONTRIBUTING.md#environment-setup)
# How to run and debug tests
After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run `npm run test` in the command line or the `Server + Tests (VSCode)` launch configuration in VS Code to debug tests + server.
After following the setup in [Environment Setup](../CONTRIBUTING.md#environment-setup) you can run the `Extension (VSCode)` launch configuration in VS Code.
## Notes

View file

@ -172,7 +172,8 @@
"deepseek",
"openchat",
"xwin-coder",
"neural-chat"
"neural-chat",
"codellama-70b"
],
"type": "string"
},
@ -334,7 +335,7 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview"
"gpt-4-0125-preview"
]
}
}
@ -386,7 +387,8 @@
"gpt-4",
"phind-codellama-34b",
"gemini-pro",
"mistral-medium"
"gpt-4-vision-preview",
"codellama-70b"
]
}
}
@ -417,7 +419,8 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
"gpt-4-vision-preview",
"mistral-7b",
"mistral-8x7b",
"llama2-7b",
@ -425,6 +428,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -502,6 +506,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b"
]
},
@ -557,6 +562,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -596,6 +602,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phi-2",
"phind-codellama-34b",
"wizardcoder-7b",
@ -762,7 +769,8 @@
"gpt-4",
"gpt-3.5-turbo-0613",
"gpt-4-32k",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
"gpt-4-vision-preview",
"mistral-7b",
"mistral-8x7b",
"llama2-7b",
@ -770,6 +778,7 @@
"codellama-7b",
"codellama-13b",
"codellama-34b",
"codellama-70b",
"phind-codellama-34b",
"wizardcoder-7b",
"wizardcoder-13b",
@ -959,7 +968,9 @@
"codebase",
"problems",
"folder",
"issue"
"issue",
"docs",
"tree"
],
"markdownEnumDescriptions": [
"Reference the contents of the current changes as given by `git diff`",
@ -972,7 +983,9 @@
"Reference all linting errors and warnings in the currently open file",
"Include important files from a folder in the prompt, as determined by similarity search",
"Reference GitHub issues from a repository",
"Retrieve important pages from a documentation website, as determined by similarity search"
"Retrieve important pages from a documentation website, as determined by similarity search",
"Index and retrieve the contents of any documentation site, using embeddings to find important snippets",
"Display a file tree of the current workspace"
],
"type": "string"
},

View file

@ -1,93 +0,0 @@
Copyright 2018 The Lexend Project Authors (https://github.com/googlefonts/lexend), with Reserved Font Name “RevReading Lexend”.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View file

@ -1,71 +0,0 @@
Lexend Variable Font
====================
This download contains Lexend as both a variable font and static fonts.
Lexend is a variable font with this axis:
wght
This means all the styles are contained in a single file:
Lexend-VariableFont_wght.ttf
If your app fully supports variable fonts, you can now pick intermediate styles
that aren’t available as static fonts. Not all apps support variable fonts, and
in those cases you can use the static font files for Lexend:
static/Lexend-Thin.ttf
static/Lexend-ExtraLight.ttf
static/Lexend-Light.ttf
static/Lexend-Regular.ttf
static/Lexend-Medium.ttf
static/Lexend-SemiBold.ttf
static/Lexend-Bold.ttf
static/Lexend-ExtraBold.ttf
static/Lexend-Black.ttf
Get started
-----------
1. Install the font files you want to use
2. Use your app's font picker to view the font family and all the
available styles
Learn more about variable fonts
-------------------------------
https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts
https://variablefonts.typenetwork.com
https://medium.com/variable-fonts
In desktop apps
https://theblog.adobe.com/can-variable-fonts-illustrator-cc
https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts
Online
https://developers.google.com/fonts/docs/getting_started
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide
https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts
Installing fonts
MacOS: https://support.apple.com/en-us/HT201749
Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux
Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows
Android Apps
https://developers.google.com/fonts/docs/android
https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts
License
-------
Please read the full license text (OFL.txt) to understand the permissions,
restrictions and requirements for usage, redistribution, and modification.
You can use them in your products & projects – print or digital,
commercial or otherwise.
This isn't legal advice, please consider consulting a lawyer and see the full
license for all details.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 MiB

After

Width:  |  Height:  |  Size: 10 MiB

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.29",
"version": "0.9.42",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.29",
"version": "0.9.42",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -1,7 +1,7 @@
{
"name": "continue",
"icon": "media/icon.png",
"version": "0.9.29",
"version": "0.9.42",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -73,90 +73,108 @@
{
"command": "continue.acceptDiff",
"category": "Continue",
"title": "Accept Diff"
"title": "Accept Diff",
"group": "Continue"
},
{
"command": "continue.rejectDiff",
"category": "Continue",
"title": "Reject Diff"
"title": "Reject Diff",
"group": "Continue",
"icon": "$(stop)"
},
{
"command": "continue.quickEdit",
"category": "Continue",
"title": "Quick Edit"
"title": "Quick Edit",
"group": "Continue"
},
{
"command": "continue.toggleAuxiliaryBar",
"category": "Continue",
"title": "Toggle Right Sidebar"
"title": "Toggle Right Sidebar",
"group": "Continue"
},
{
"command": "continue.focusContinueInput",
"category": "Continue",
"title": "Add Highlighted Code to Context"
"title": "Add Highlighted Code to Context",
"group": "Continue"
},
{
"command": "continue.focusContinueInputWithoutClear",
"category": "Continue",
"title": "Add Highlighted Code to Context"
"title": "Add Highlighted Code to Context",
"group": "Continue"
},
{
"command": "continue.debugTerminal",
"category": "Continue",
"title": "Debug Terminal"
"title": "Debug Terminal",
"group": "Continue"
},
{
"command": "continue.toggleFullScreen",
"category": "Continue",
"title": "Toggle Full Screen",
"icon": "$(fullscreen)"
"icon": "$(fullscreen)",
"group": "Continue"
},
{
"command": "continue.shareSession",
"category": "Continue",
"title": "Share Session"
"title": "Share Session",
"group": "Continue"
},
{
"command": "continue.selectFilesAsContext",
"category": "Continue",
"title": "Continue: Select Files as Context"
"title": "Continue: Select Files as Context",
"group": "Continue"
},
{
"command": "continue.newSession",
"category": "Continue",
"title": "New Session",
"icon": "$(add)"
"icon": "$(add)",
"group": "Continue"
},
{
"command": "continue.viewHistory",
"category": "Continue",
"title": "View History",
"icon": "$(history)"
"icon": "$(history)",
"group": "Continue"
},
{
"command": "continue.writeCommentsForCode",
"category": "Continue",
"title": "Write Comments for this Code"
"title": "Write Comments for this Code",
"group": "Continue"
},
{
"command": "continue.writeDocstringForCode",
"category": "Continue",
"title": "Write a Docstring for this Code"
"title": "Write a Docstring for this Code",
"group": "Continue"
},
{
"command": "continue.fixCode",
"category": "Continue",
"title": "Fix this Code"
"title": "Fix this Code",
"group": "Continue"
},
{
"command": "continue.optimizeCode",
"category": "Continue",
"title": "Optimize this Code"
"title": "Optimize this Code",
"group": "Continue"
},
{
"command": "continue.fixGrammar",
"category": "Continue",
"title": "Fix Grammar / Spelling"
"title": "Fix Grammar / Spelling",
"group": "Continue"
}
],
"keybindings": [
@ -209,6 +227,29 @@
}
],
"menus": {
"commandPalette": [
{
"command": "continue.quickEdit"
},
{
"command": "continue.toggleAuxiliaryBar"
},
{
"command": "continue.focusContinueInput"
},
{
"command": "continue.focusContinueInputWithoutClear"
},
{
"command": "continue.debugTerminal"
},
{
"command": "continue.toggleFullScreen"
},
{
"command": "continue.newSession"
}
],
"webview/context": [
{
"command": "continue.shareSession",
@ -218,7 +259,14 @@
"editor/context": [
{
"submenu": "continue.continueSubMenu",
"group": "1_debug@1"
"group": "0_acontinue"
}
],
"editor/title/run": [
{
"command": "continue.rejectDiff",
"group": "Continue",
"when": "continue.streamingDiff"
}
],
"continue.continueSubMenu": [

View file

@ -124,6 +124,7 @@ if (args[2] === "--target") {
target = `${os}-${arch}`;
console.log("Detected target: ", target);
}
fs.mkdirSync("bin", { recursive: true });
// onnxruntime-node
await new Promise((resolve, reject) => {

View file

@ -17,14 +17,27 @@ export let extensionContext: vscode.ExtensionContext | undefined = undefined;
export let ideProtocolClient: IdeProtocolClient;
export let windowId: string = v4();
async function openTutorial(context: vscode.ExtensionContext) {
export async function showTutorial() {
const tutorialPath = path.join(
getExtensionUri().fsPath,
"continue_tutorial.py"
);
// Ensure keyboard shortcuts match OS
if (process.platform !== "darwin") {
let tutorialContent = fs.readFileSync(tutorialPath, "utf8");
tutorialContent = tutorialContent.replace("⌘", "^");
fs.writeFileSync(tutorialPath, tutorialContent);
}
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(tutorialPath)
);
await vscode.window.showTextDocument(doc);
}
async function openTutorialFirstTime(context: vscode.ExtensionContext) {
if (context.globalState.get<boolean>("continue.tutorialShown") !== true) {
const doc = await vscode.workspace.openTextDocument(
vscode.Uri.file(
path.join(getExtensionUri().fsPath, "continue_tutorial.py")
)
);
await vscode.window.showTextDocument(doc);
await showTutorial();
context.globalState.update("continue.tutorialShown", true);
}
}
@ -69,7 +82,7 @@ export async function activateExtension(context: vscode.ExtensionContext) {
registerAllCodeLensProviders(context);
registerAllCommands(context);
registerQuickFixProvider();
await openTutorial(context);
await openTutorialFirstTime(context);
setupInlineTips(context);
showRefactorMigrationMessage();
@ -132,6 +145,8 @@ export async function activateExtension(context: vscode.ExtensionContext) {
fontColor: "#fff",
};
themeJson.fileNames[".continueignore"] = "_f_continue";
themeJson.fileNames[".continuerc.json"] = "_f_continue";
themeJson.fileNames["config.json"] = "_f_continue";
fs.writeFileSync(themePath, JSON.stringify(themeJson));
found = true;
break;

View file

@ -13,6 +13,11 @@ const inlineTipDecoration = vscode.window.createTextEditorDecorationType({
function handleSelectionChange(e: vscode.TextEditorSelectionChangeEvent) {
const selection = e.selections[0];
const editor = e.textEditor;
if (editor.document.uri.toString().startsWith("output:")) {
return;
}
if (
selection.isEmpty ||
vscode.workspace
@ -69,6 +74,10 @@ export function setupInlineTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor?.document.getText() === "") {
if (editor.document.uri.toString().startsWith("output:")) {
return;
}
editor.setDecorations(emptyFileTooltipDecoration, [
{
range: new vscode.Range(
@ -83,6 +92,9 @@ export function setupInlineTips(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument((e) => {
if (e.document.uri.toString().startsWith("vscode://inline-chat")) {
return;
}
if (e.document.getText() === "") {
vscode.window.visibleTextEditors.forEach((editor) => {
editor.setDecorations(emptyFileTooltipDecoration, [

View file

@ -190,7 +190,7 @@ const commandsMap: { [command: string]: (...args: any) => any } = {
await vscode.window.showTextDocument(uri);
},
"continue.debugTerminal": async () => {
const terminalContents = await ideProtocolClient.getTerminalContents(2);
const terminalContents = await ideProtocolClient.getTerminalContents(1);
vscode.commands.executeCommand("continue.continueGUIView.focus");
debugPanelWebview?.postMessage({
type: "userInput",

View file

@ -233,9 +233,9 @@ class IdeProtocolClient {
panel.webview.html = getSidebarContent(panel, "/monaco", edits);
}
openFile(filepath: string) {
openFile(filepath: string, range?: vscode.Range) {
// vscode has a builtin open/get open files
openEditorAndRevealRange(filepath, undefined, vscode.ViewColumn.One);
return openEditorAndRevealRange(filepath, range, vscode.ViewColumn.One);
}
async fileExists(filepath: string): Promise<boolean> {
@ -354,7 +354,20 @@ class IdeProtocolClient {
}
const allFiles: string[] = [];
for await (const file of traverseDirectory(directory, [])) {
const gitRoot = await this.getGitRoot(directory);
let onlyThisDirectory = undefined;
if (gitRoot) {
onlyThisDirectory = directory.slice(gitRoot.length).split(path.sep);
if (onlyThisDirectory[0] === "") {
onlyThisDirectory.shift();
}
}
for await (const file of traverseDirectory(
gitRoot || directory,
[],
true,
onlyThisDirectory
)) {
allFiles.push(file);
}
return allFiles;
@ -455,6 +468,11 @@ class IdeProtocolClient {
return repo;
}
async getGitRoot(forDirectory: string): Promise<string | undefined> {
const repo = await this.getRepo(vscode.Uri.file(forDirectory));
return repo?.rootUri?.fsPath;
}
async getBranch(forDirectory: vscode.Uri) {
let repo = await this.getRepo(forDirectory);
if (repo?.state?.HEAD?.name === undefined) {

View file

@ -2,12 +2,19 @@ import { ContextItemId, DiffLine, FileEdit, ModelDescription } from "core";
import { indexDocs } from "core/indexing/docs";
import TransformersJsEmbeddingsProvider from "core/indexing/embeddings/TransformersJsEmbeddingsProvider";
import { editConfigJson, getConfigJsonPath } from "core/util/paths";
import * as fs from "fs";
import { readFileSync, writeFileSync } from "fs";
import * as path from "path";
import * as io from "socket.io-client";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { ideProtocolClient, windowId } from "./activation/activate";
import {
ideProtocolClient,
showTutorial,
windowId,
} from "./activation/activate";
import { getContinueServerUrl } from "./bridge";
import { streamEdit } from "./diff/verticalPerLine/manager";
import historyManager from "./history";
import { VsCodeIde } from "./ideProtocol";
import { configHandler, llmFromTitle } from "./loadConfig";
@ -214,25 +221,6 @@ export function getSidebarContent(
});
break;
}
case "showLines": {
ideProtocolClient.highlightCode(
{
filepath: data.filepath,
range: {
start: {
line: data.start,
character: 0,
},
end: {
line: data.end,
character: 0,
},
},
},
"#00ff0022"
);
break;
}
case "toggleDevTools": {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
vscode.commands.executeCommand("continue.viewLogs");
@ -431,6 +419,11 @@ export function getSidebarContent(
respond(await ide.getProblems(data.message.filepath));
break;
}
case "getBranch": {
const { dir } = data.message;
respond(await ide.getBranch(dir));
break;
}
case "getOpenFiles": {
respond(await ide.getOpenFiles());
break;
@ -439,6 +432,11 @@ export function getSidebarContent(
respond(await ide.getPinnedFiles());
break;
}
case "showLines": {
const { filepath, startLine, endLine } = data.message;
respond(await ide.showLines(filepath, startLine, endLine));
break;
}
// Other
case "errorPopup": {
vscode.window
@ -694,7 +692,7 @@ export function getSidebarContent(
embeddingsProvider
)) {
progress.report({
increment: update.progress * 100,
increment: update.progress,
message: update.desc,
});
}
@ -702,26 +700,104 @@ export function getSidebarContent(
vscode.window.showInformationMessage(
`🎉 Successfully indexed ${title}`
);
debugPanelWebview?.postMessage({
type: "refreshSubmenuItems",
});
}
);
break;
}
case "applyToCurrentFile": {
// Select the entire current file
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage(
"No active editor to apply edits to"
);
break;
}
const document = editor.document;
const start = new vscode.Position(0, 0);
const end = new vscode.Position(
document.lineCount - 1,
document.lineAt(document.lineCount - 1).text.length
);
editor.selection = new vscode.Selection(start, end);
streamEdit(
`The following code was suggested as an edit:\n\`\`\`\n${data.text}\n\`\`\`\nPlease apply it to the previous code.`
);
break;
}
case "showTutorial": {
showTutorial();
break;
}
}
} catch (e) {
} catch (e: any) {
let message = `Continue error: ${e.message}`;
if (e.cause) {
if (e.cause.name === "ConnectTimeoutError") {
message = `Connection timed out. If you expect it to take a long time to connect, you can increase the timeout in config.json by setting "requestOptions": { "timeout": 10000 }. You can find the full config reference here: https://continue.dev/docs/reference/config`;
} else if (e.cause.code === "ECONNREFUSED") {
message = `Connection was refused. This likely means that there is no server running at the specified URL. If you are running your own server you may need to set the "apiBase" parameter in config.json. For example, you can set up an OpenAI-compatible server like here: https://continue.dev/docs/reference/Model%20Providers/openai#openai-compatible-servers--apis`;
} else {
message = `The request failed with "${e.cause.name}": ${e.cause.message}. If you're having trouble setting up Continue, please see the troubleshooting guide for help.`;
}
}
vscode.window
.showErrorMessage(
`Error handling message from Continue side panel: ${e}`,
"Show Logs"
)
.showErrorMessage(message, "Show Logs", "Troubleshooting")
.then((selection) => {
if (selection === "Show Logs") {
vscode.commands.executeCommand("workbench.action.toggleDevTools");
} else if (selection === "Troubleshooting") {
vscode.env.openExternal(
vscode.Uri.parse("https://continue.dev/docs/troubleshooting")
);
}
});
respond({ done: true, data: {} });
}
});
let currentTheme = undefined;
let colorThemeName = "dark-plus";
const tokenColorMap: any = {};
try {
// Pass color theme to webview for syntax highlighting
const colorTheme = vscode.workspace
.getConfiguration("workbench")
.get("colorTheme");
for (let i = vscode.extensions.all.length - 1; i >= 0; i--) {
if (currentTheme) {
break;
}
const extension = vscode.extensions.all[i];
if (extension.packageJSON?.contributes?.themes?.length > 0) {
for (const theme of extension.packageJSON.contributes.themes) {
if (theme.label === colorTheme) {
const themePath = path.join(extension.extensionPath, theme.path);
currentTheme = fs.readFileSync(themePath).toString();
break;
}
}
}
}
// Strip comments from theme
currentTheme = currentTheme
?.split("\n")
.filter((line) => {
return !line.trim().startsWith("//");
})
.join("\n");
} catch (e) {
console.log("Error adding .continueignore file icon: ", e);
}
return `<!DOCTYPE html>
<html lang="en">
<head>
@ -730,11 +806,6 @@ export function getSidebarContent(
<script>const vscode = acquireVsCodeApi();</script>
<link href="${styleMainUri}" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lexend:wght@300&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
<title>Continue</title>
</head>
<body>
@ -747,6 +818,8 @@ export function getSidebarContent(
<script>window.vscMachineId = "${getUniqueId()}"</script>
<script>window.vscMediaUrl = "${vscMediaUrl}"</script>
<script>window.ide = "vscode"</script>
<script>window.fullColorTheme = ${currentTheme}</script>
<script>window.colorThemeName = "${colorThemeName}"</script>
<script>window.workspacePaths = ${JSON.stringify(
vscode.workspace.workspaceFolders?.map(
(folder) => folder.uri.fsPath

View file

@ -342,12 +342,18 @@ async function recordAcceptReject(accepted: boolean, diffInfo: DiffInfo) {
);
}
export async function acceptDiffCommand(newFilepath?: string) {
export async function acceptDiffCommand(newFilepath?: string | vscode.Uri) {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalPerLineDiffManager.clearForFilepath(newFilepath, true);
await diffManager.acceptDiff(newFilepath);
}
export async function rejectDiffCommand(newFilepath?: string) {
export async function rejectDiffCommand(newFilepath?: string | vscode.Uri) {
if (newFilepath instanceof vscode.Uri) {
newFilepath = newFilepath.fsPath;
}
verticalPerLineDiffManager.clearForFilepath(newFilepath, false);
await diffManager.rejectDiff(newFilepath);
}

View file

@ -108,14 +108,28 @@ export async function streamEdit(input: string) {
editor.selection.active
);
await diffHandler.run(
streamDiffLines(
rangeContent,
llm,
input,
getMarkdownLanguageTagForFile(filepath)
)
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
true
);
try {
await diffHandler.run(
streamDiffLines(
rangeContent,
llm,
input,
getMarkdownLanguageTagForFile(filepath)
)
);
} finally {
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
false
);
}
}
}

View file

@ -8,7 +8,6 @@ import { getUniqueId } from "./util/vscode";
let client: any = undefined;
export async function capture(args: any) {
console.log("Capturing posthog event: ", args);
if (!client) {
const { PostHog } = await import("posthog-node");
client = new PostHog("phc_JS6XFROuNbhJtVCEdTSYk6gl5ArRrTNMpCcguAXlSPs", {

View file

@ -27,11 +27,11 @@ import {
} from "core/config/load";
import { LanceDbIndex } from "core/indexing/LanceDbIndex";
import { IndexTag } from "core/indexing/types";
import mergeJson from "core/util/merge";
import { verticalPerLineDiffManager } from "./diff/verticalPerLine/manager";
import { configHandler } from "./loadConfig";
import mergeJson from "./util/merge";
import { traverseDirectory } from "./util/traverseDirectory";
import { getExtensionUri } from "./util/vscode";
import { getExtensionUri, openEditorAndRevealRange } from "./util/vscode";
async function buildConfigTs(browser: boolean) {
if (!fs.existsSync(getConfigTsPath())) {
@ -243,7 +243,7 @@ class VsCodeIde implements IDE {
}
async getTerminalContents(): Promise<string> {
return await ideProtocolClient.getTerminalContents(2);
return await ideProtocolClient.getTerminalContents(1);
}
async listWorkspaceContents(directory?: string): Promise<string[]> {
@ -295,6 +295,26 @@ class VsCodeIde implements IDE {
ideProtocolClient.openFile(path);
}
async showLines(
filepath: string,
startLine: number,
endLine: number
): Promise<void> {
const range = new vscode.Range(
new vscode.Position(startLine, 0),
new vscode.Position(endLine, 0)
);
openEditorAndRevealRange(filepath, range).then(() => {
ideProtocolClient.highlightCode(
{
filepath,
range,
},
"#fff1"
);
});
}
async runCommand(command: string): Promise<void> {
await ideProtocolClient.runCommand(command);
}
@ -416,6 +436,10 @@ class VsCodeIde implements IDE {
});
}
async getBranch(dir: string): Promise<string> {
return ideProtocolClient.getBranch(vscode.Uri.file(dir));
}
async getFilesToEmbed(
providerId: string
): Promise<[string, string, string][]> {

View file

@ -2,10 +2,15 @@ import { ContinueConfig, IDE, ILLM } from "core";
import { https } from "follow-redirects";
import * as fs from "fs";
import fetch from "node-fetch";
import * as vscode from "vscode";
import { webviewRequest } from "./debugPanel";
import { VsCodeIde, loadFullConfigNode } from "./ideProtocol";
const tls = require("tls");
const outputChannel = vscode.window.createOutputChannel(
"Continue - LLM Prompt/Completion"
);
class VsCodeConfigHandler {
savedConfig: ContinueConfig | undefined;
@ -72,18 +77,42 @@ export async function llmFromTitle(title?: string): Promise<ILLM> {
keepAliveMsecs: timeout,
});
llm._fetch = (input, init) => {
llm._fetch = async (input, init) => {
const headers: { [key: string]: string } =
llm!.requestOptions?.headers || {};
for (const [key, value] of Object.entries(init?.headers || {})) {
headers[key] = value as string;
}
return fetch(input, {
const resp = await fetch(input, {
...init,
headers,
agent,
});
if (!resp.ok) {
let text = await resp.text();
if (resp.status === 404 && !resp.url.includes("/v1")) {
text =
"This may mean that you forgot to add '/v1' to the end of your 'apiBase' in config.json.";
}
throw new Error(
`HTTP ${resp.status} ${resp.statusText} from ${resp.url}\n\n${text}`
);
}
return resp;
};
llm.writeLog = async (log: string) => {
outputChannel.appendLine(
"=========================================================================="
);
outputChannel.appendLine(
"=========================================================================="
);
outputChannel.append(log);
};
return llm;

View file

@ -1,4 +1,6 @@
import { FullTextSearchCodebaseIndex } from "core/indexing/FullTextSearch";
import { LanceDbIndex } from "core/indexing/LanceDbIndex";
import { ChunkCodebaseIndex } from "core/indexing/chunk/ChunkCodebaseIndex";
import { getComputeDeleteAddRemove } from "core/indexing/refreshIndex";
import { CodebaseIndex, IndexTag, LastModifiedMap } from "core/indexing/types";
import * as vscode from "vscode";
@ -23,11 +25,14 @@ const vscodeGetStats = async (
};
async function getIndexesToBuild(): Promise<CodebaseIndex[]> {
const indexes = [];
const ide = new VsCodeIde();
const config = await configHandler.loadConfig(ide);
indexes.push(new LanceDbIndex(config.embeddingsProvider, ide.readFile));
const indexes = [
new ChunkCodebaseIndex(ide.readFile), // Chunking must come first
new LanceDbIndex(config.embeddingsProvider, ide.readFile),
new FullTextSearchCodebaseIndex(),
];
return indexes;
}
@ -37,6 +42,11 @@ export async function vsCodeIndexCodebase(workspaceDirs: string[]) {
debugPanelWebview?.postMessage({ type: "indexProgress", progress, desc });
};
const config = await configHandler.loadConfig(new VsCodeIde());
if (config.disableIndexing) {
return;
}
const indexesToBuild = await getIndexesToBuild();
let completedDirs = 0;
@ -57,12 +67,10 @@ export async function vsCodeIndexCodebase(workspaceDirs: string[]) {
};
const [results, markComplete] = await getComputeDeleteAddRemove(
tag,
stats,
{ ...stats },
(filepath) => ideProtocolClient.readFile(filepath)
);
// console.log("RESULTS: ", results);
for await (let { progress, desc } of codebaseIndex.update(
tag,
results,

View file

@ -1,27 +0,0 @@
type JsonObject = { [key: string]: any };
function mergeJson(first: JsonObject, second: JsonObject): any {
for (var key in second) {
let secondValue = second[key];
if (!(key in first)) {
// New value
first[key] = secondValue;
}
const firstValue = first[key];
if (Array.isArray(secondValue)) {
// Array
first[key] = [...firstValue, ...secondValue];
} else if (typeof secondValue === "object") {
// Object
first[key] = mergeJson(firstValue, secondValue);
} else {
// Other (boolean, number, string)
first[key] = secondValue;
}
}
return first;
}
export default mergeJson;

View file

@ -95,7 +95,8 @@ function splitGlob(glob: string): [string | undefined, string, boolean] {
export async function* traverseDirectory(
directory: string,
gitIgnorePatterns: string[],
returnFiles: boolean = true
returnFiles: boolean = true,
onlyThisDirectory?: string[]
): AsyncGenerator<string> {
const nodes = await vscode.workspace.fs.readDirectory(
uriFromFilePath(directory)
@ -119,7 +120,9 @@ export async function* traverseDirectory(
);
const contents = new TextDecoder().decode(bytes);
ignorePatterns.push(
...contents.split("\n").filter((p) => p.trim() !== "")
...contents
.split("\n")
.filter((p) => p.trim() !== "" && p[0] !== "#")
);
} else {
files.push(name);
@ -133,12 +136,21 @@ export async function* traverseDirectory(
}
}
const allIgnorePatterns = [...gitIgnorePatterns, ...ignorePatterns];
const allIgnorePatterns = [...gitIgnorePatterns, ...ignorePatterns].map(
(pattern) => {
if (!pattern.slice(0, -1).includes("/")) {
return "**/" + pattern;
}
return pattern;
}
);
const ig = ignore().add(allIgnorePatterns);
for (const node of returnFiles ? files : dirs) {
if (!ig.ignores(node)) {
yield path.join(directory, node);
if (!onlyThisDirectory) {
for (const node of returnFiles ? files : dirs) {
if (!ig.ignores(node)) {
yield path.join(directory, node);
}
}
}
@ -147,7 +159,7 @@ export async function* traverseDirectory(
for (const ignorePattern of allIgnorePatterns) {
const [first, rest, leadingWildcard] = splitGlob(ignorePattern);
if (leadingWildcard) {
wildcardPatterns.push("**/" + rest);
wildcardPatterns.push("**/" + first + (rest ? "/" + rest : ""));
}
if (first) {
if (subDirIgnorePatterns[first] === undefined) {
@ -157,10 +169,14 @@ export async function* traverseDirectory(
}
}
const entries = Object.entries(subDirIgnorePatterns);
for (const dir of dirs) {
// Skip everything except onlyThisDirectory
if (onlyThisDirectory && onlyThisDirectory[0] !== dir) {
continue;
}
// Recurse if not ignored
if (!ig.ignores(dir)) {
if (!(ig.ignores(dir + "/") || ig.ignores(dir))) {
// For patterns who can potentially match items of this subdir, strip the subdir from the start
const keepPatterns = [...wildcardPatterns];
for (const [startPattern, subDirPatterns] of entries) {
@ -171,7 +187,10 @@ export async function* traverseDirectory(
for await (const file of traverseDirectory(
path.join(directory, dir),
keepPatterns,
returnFiles
returnFiles,
onlyThisDirectory && onlyThisDirectory.length > 1
? onlyThisDirectory.slice(1)
: undefined
)) {
yield file;
}

5403
gui/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -13,6 +13,7 @@
"@heroicons/react": "^2.0.18",
"@monaco-editor/react": "^4.6.0",
"@reduxjs/toolkit": "^1.9.3",
"@shikijs/rehype": "^1.0.0-beta.0",
"@tiptap/extension-dropcursor": "^2.1.16",
"@tiptap/extension-image": "^2.1.16",
"@tiptap/extension-mention": "^2.1.13",
@ -22,7 +23,6 @@
"@tiptap/starter-kit": "^2.1.13",
"@tiptap/suggestion": "^2.1.13",
"@types/vscode-webview": "^1.57.1",
"@uiw/react-markdown-preview": "^4.1.13",
"core": "file:../core",
"dompurify": "^3.0.6",
"downshift": "^7.6.0",
@ -34,17 +34,24 @@
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.11",
"react-hook-form": "^7.47.0",
"react-markdown": "^9.0.1",
"react-redux": "^8.0.5",
"react-remark": "^2.1.0",
"react-router-dom": "^6.14.2",
"react-switch": "^7.0.0",
"react-syntax-highlighter": "^15.5.0",
"react-tooltip": "^5.18.0",
"redux-persist": "^6.0.0",
"redux-persist-transform-filter": "^0.0.22",
"rehype-shikiji": "^0.10.2",
"rehype-wrap-all": "^1.1.0",
"remark-shiki-twoslash": "^3.1.3",
"seti-file-icons": "^0.0.8",
"shikiji": "^0.10.2",
"socket.io-client": "^4.7.2",
"styled-components": "^5.3.6",
"tippy.js": "^6.3.7",
"unist-util-visit": "^5.0.0",
"uuid": "^9.0.1",
"vscode-webview": "^1.0.1-beta.1"
},

View file

@ -66,19 +66,28 @@ const router = createMemoryRouter([
},
]);
export const SubmenuContextProvidersContext = createContext<
(providerTitle: string | undefined, query: string) => ContextSubmenuItem[]
>(() => []);
export const SubmenuContextProvidersContext = createContext<{
getSubmenuContextItems: (
providerTitle: string | undefined,
query: string
) => ContextSubmenuItem[];
addItem: (providerTitle: string, item: ContextSubmenuItem) => void;
}>({
getSubmenuContextItems: () => [],
addItem: () => {},
});
function App() {
const dispatch = useDispatch();
useSetup(dispatch);
const { getSubmenuContextItems } = useSubmenuContextProviders();
const submenuContextProvidersMethods = useSubmenuContextProviders();
return (
<SubmenuContextProvidersContext.Provider value={getSubmenuContextItems}>
<SubmenuContextProvidersContext.Provider
value={submenuContextProvidersMethods}
>
<RouterProvider router={router} />
</SubmenuContextProvidersContext.Provider>
);

View file

@ -1,9 +1,10 @@
import { postToIde } from "core/ide/messaging";
import React, { useLayoutEffect } from "react";
import { usePostHog } from "posthog-js/react";
import React, { useContext, useLayoutEffect } from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { Button, Input } from "..";
import useSubmenuContextProviders from "../../hooks/useSubmenuContextProviders";
import { SubmenuContextProvidersContext } from "../../App";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
const GridDiv = styled.div`
@ -19,14 +20,17 @@ function AddDocsDialog() {
const [urlValid, setUrlValid] = React.useState(false);
const dispatch = useDispatch();
const { addItem } = useSubmenuContextProviders();
const { addItem } = useContext(SubmenuContextProvidersContext);
const ref = React.useRef<HTMLInputElement>(null);
const posthog = usePostHog();
useLayoutEffect(() => {
if (ref.current) {
ref.current.focus();
}
setTimeout(() => {
if (ref.current) {
ref.current.focus();
}
}, 100);
}, [ref]);
return (
@ -63,6 +67,7 @@ function AddDocsDialog() {
title: docsTitle,
description: new URL(docsUrl).hostname,
});
posthog.capture("add_docs", { url: docsUrl });
}}
>
Done

View file

@ -1,5 +1,5 @@
import React, { isValidElement, useEffect } from "react";
import { ReactMarkdown } from "react-markdown/lib/react-markdown";
import ReactMarkdown from "react-markdown";
import styled from "styled-components";
import {
VSC_BACKGROUND_VAR,

View file

@ -17,6 +17,8 @@ export const VSC_QUICK_INPUT_BACKGROUND_VAR = "--vscode-quickInput-background";
export const VSC_INPUT_BORDER_VAR = "--vscode-input-border";
export const VSC_INPUT_BORDER_FOCUS_VAR = "--vscode-focusBorder";
export const VSC_BADGE_BACKGROUND_VAR = "--vscode-badge-background";
export const VSC_BADGE_FOREGROUND_VAR = "--vscode-badge-foreground";
export const VSC_SIDEBAR_BORDER_VAR = "--vscode-sideBar-border";
export const VSC_THEME_COLOR_VARS = [
VSC_INPUT_BACKGROUND_VAR,
@ -31,6 +33,8 @@ export const VSC_THEME_COLOR_VARS = [
VSC_INPUT_BORDER_VAR,
VSC_INPUT_BORDER_FOCUS_VAR,
VSC_BADGE_BACKGROUND_VAR,
VSC_SIDEBAR_BORDER_VAR,
VSC_BADGE_FOREGROUND_VAR,
];
export const defaultBorderRadius = "5px";
@ -49,6 +53,8 @@ export const vscListActiveForeground = `var(${VSC_LIST_ACTIVE_FOREGROUND_VAR}, $
export const vscInputBorder = `var(${VSC_INPUT_BORDER_VAR}, ${lightGray})`;
export const vscInputBorderFocus = `var(${VSC_INPUT_BORDER_FOCUS_VAR}, ${lightGray})`;
export const vscBadgeBackground = `var(${VSC_BADGE_BACKGROUND_VAR}, #1bbe84)`;
export const vscBadgeForeground = `var(${VSC_BADGE_FOREGROUND_VAR}, #fff)`;
export const vscSidebarBorder = `var(${VSC_SIDEBAR_BORDER_VAR}, transparent)`;
if (typeof document !== "undefined") {
for (const colorVar of VSC_THEME_COLOR_VARS) {
@ -74,7 +80,6 @@ export function parseColorForHex(colorVar: string): string {
colorVar
);
if (value.startsWith("#")) {
console.log("value", value);
return value.slice(0, 7);
}
@ -89,7 +94,6 @@ export function parseColorForHex(colorVar: string): string {
.map((x) => x.toString(16))
.map((x) => (x.length === 1 ? "0" + x : x))
.join("");
console.log(hex, value);
return hex;
}
@ -113,11 +117,13 @@ export const Button = styled.button`
export const StyledTooltip = styled(Tooltip)`
font-size: 12px;
background-color: rgb(60 60 60);
background-color: ${vscEditorBackground};
color: ${vscForeground};
border-radius: ${defaultBorderRadius};
padding: 6px;
padding-left: 12px;
padding-right: 12px;
box-shadow: 0 0 3px 0 ${vscForeground};
padding: 4px;
padding-left: 8px;
padding-right: 8px;
z-index: 1000;
max-width: 80vw;

View file

@ -1,5 +1,6 @@
import { ChevronDownIcon, ChevronUpIcon } from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import { contextItemToRangeInFileWithContents } from "core/commands/util";
import { ExtensionIde } from "core/ide";
import React from "react";
import styled from "styled-components";
@ -46,8 +47,11 @@ const ContextItemsPeek = (props: ContextItemsPeekProps) => {
contextItem.description.startsWith("/") ||
contextItem.description.startsWith("\\")
) {
new ExtensionIde().openFile(
contextItem.description.split(" ").shift() || ""
const rif = contextItemToRangeInFileWithContents(contextItem);
new ExtensionIde().showLines(
rif.filepath,
rif.range.start.line,
rif.range.end.line
);
} else {
new ExtensionIde().showVirtualFile(contextItem.name, contextItem.content);

View file

@ -1,10 +1,7 @@
import styled from "styled-components";
import { Button, vscBackground } from "..";
import { PlayIcon, StopIcon } from "@heroicons/react/24/outline";
import { useSelector } from "react-redux";
import { RootStore } from "../../redux/store";
import { useEffect, useState } from "react";
import { getPlatform } from "../../util";
import styled from "styled-components";
import { Button } from "..";
const StyledButton = styled(Button)<{
color?: string | null;
@ -72,7 +69,7 @@ function ContinueButton(props: {
color={buttonColor as any}
hidden={props.hidden}
style={{ fontSize: "10px" }}
className="m-auto press-start-2p"
className="m-auto"
onClick={props.disabled ? undefined : props.onClick}
isDisabled={props.disabled}
>

View file

@ -3,7 +3,14 @@ import { PhotoIcon as SolidPhotoIcon } from "@heroicons/react/24/solid";
import { useRef, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, vscInputBackground } from "..";
import {
defaultBorderRadius,
lightGray,
vscBadgeBackground,
vscBadgeForeground,
vscForeground,
vscInputBackground,
} from "..";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
const StyledDiv = styled.div<{ hidden?: boolean }>`
@ -36,11 +43,11 @@ const EnterButton = styled.div<{ offFocus: boolean }>`
background-color: ${(props) =>
props.offFocus ? undefined : lightGray + "33"};
border-radius: ${defaultBorderRadius};
color: #fff8;
color: ${vscForeground};
&:hover {
background-color: #cf313199;
color: white;
background-color: ${vscBadgeBackground};
color: ${vscBadgeForeground};
}
cursor: pointer;
@ -79,7 +86,7 @@ function InputToolbar(props: InputToolbarProps) {
>
+ Add Context
</span>
{false && defaultModel?.supportsImages() && (
{defaultModel?.supportsImages() && (
<span
className="ml-1.5 mt-0.5"
onMouseLeave={() => setFileSelectHovered(false)}
@ -120,7 +127,7 @@ function InputToolbar(props: InputToolbarProps) {
</span>
<span
style={{
color: props.usingCodebase ? "#fff8" : lightGray,
color: props.usingCodebase ? vscBadgeBackground : lightGray,
backgroundColor: props.usingCodebase ? lightGray + "33" : undefined,
borderRadius: defaultBorderRadius,
padding: "2px 4px",

View file

@ -1,5 +1,4 @@
import Document from "@tiptap/extension-document";
import Dropcursor from "@tiptap/extension-dropcursor";
import History from "@tiptap/extension-history";
import Image from "@tiptap/extension-image";
import Paragraph from "@tiptap/extension-paragraph";
@ -14,6 +13,7 @@ import styled from "styled-components";
import {
defaultBorderRadius,
lightGray,
vscBadgeBackground,
vscForeground,
vscInputBackground,
vscInputBorder,
@ -53,6 +53,7 @@ const InputBoxDiv = styled.div`
&:focus {
outline: none;
border: 0.5px solid ${vscInputBorderFocus};
}
@ -63,6 +64,34 @@ const InputBoxDiv = styled.div`
position: relative;
`;
const HoverDiv = styled.div`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0.5;
background-color: ${vscBadgeBackground};
color: ${vscForeground};
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
`;
const HoverTextDiv = styled.div`
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
color: ${vscForeground};
z-index: 100;
display: flex;
align-items: center;
justify-content: center;
`;
function getDataUrlForFile(file: File, img): string {
const targetWidth = 512;
const targetHeight = 512;
@ -94,7 +123,7 @@ interface TipTapEditorProps {
function TipTapEditor(props: TipTapEditorProps) {
const dispatch = useDispatch();
const getSubmenuContextItems = useContext(SubmenuContextProvidersContext);
const { getSubmenuContextItems } = useContext(SubmenuContextProvidersContext);
const historyLength = useSelector(
(store: RootStore) => store.state.history.length
@ -158,7 +187,14 @@ function TipTapEditor(props: TipTapEditorProps) {
let filesize = file.size / 1024 / 1024; // filesize in MB
// check image type and size
if (
(file.type === "image/jpeg" || file.type === "image/png") &&
[
"image/jpeg",
"image/jpg",
"image/png",
"image/gif",
"image/svg",
"image/webp",
].includes(file.type) &&
filesize < 10
) {
// check dimensions
@ -190,7 +226,6 @@ function TipTapEditor(props: TipTapEditorProps) {
Document,
History,
Image,
Dropcursor,
Placeholder.configure({
placeholder: () =>
historyLengthRef.current === 0
@ -265,32 +300,6 @@ function TipTapEditor(props: TipTapEditorProps) {
class: "outline-none -mt-1 overflow-hidden",
style: "font-size: 14px;",
},
handleDrop: function (view, event, slice, moved) {
if (
!moved &&
event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files[0]
) {
let file = event.dataTransfer.files[0];
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = view.state;
const coordinates = view.posAtCoords({
left: event.clientX,
top: event.clientY,
});
const node = schema.nodes.image.create({ src: dataUrl });
const transaction = view.state.tr.insert(
Math.max(0, coordinates.pos - 1),
[node]
);
return view.dispatch(transaction);
});
return true;
}
return false;
},
},
content: props.editorState || "",
onUpdate: ({ editor, transaction }) => {
@ -428,12 +437,63 @@ function TipTapEditor(props: TipTapEditorProps) {
};
}, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
const [showDragOverMsg, setShowDragOverMsg] = useState(false);
useEffect(() => {
const overListener = (event: DragEvent) => {
if (event.shiftKey) return;
setShowDragOverMsg(true);
};
window.addEventListener("dragover", overListener);
const leaveListener = (event: DragEvent) => {
if (event.shiftKey) {
setShowDragOverMsg(false);
} else {
setTimeout(() => setShowDragOverMsg(false), 2000);
}
};
window.addEventListener("dragleave", leaveListener);
return () => {
window.removeEventListener("dragover", overListener);
window.removeEventListener("dragleave", leaveListener);
};
}, []);
return (
<InputBoxDiv
className="cursor-text"
onClick={() => {
editor && editor.commands.focus();
}}
onDragOver={(event) => {
event.preventDefault();
setShowDragOverMsg(true);
}}
onDragLeave={(e) => {
if (e.relatedTarget === null) {
if (e.shiftKey) {
setShowDragOverMsg(false);
} else {
setTimeout(() => setShowDragOverMsg(false), 2000);
}
}
}}
onDragEnter={() => {
setShowDragOverMsg(true);
}}
onDrop={(event) => {
setShowDragOverMsg(false);
let file = event.dataTransfer.files[0];
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = editor.state;
const node = schema.nodes.image.create({ src: dataUrl });
const tr = editor.state.tr.insert(0, node);
editor.view.dispatch(tr);
});
event.preventDefault();
}}
>
<EditorContent
editor={editor}
@ -465,10 +525,19 @@ function TipTapEditor(props: TipTapEditorProps) {
handleImageFile(file).then(([img, dataUrl]) => {
const { schema } = editor.state;
const node = schema.nodes.image.create({ src: dataUrl });
editor.state.tr.insert(0, node);
editor.commands.command(({ tr }) => {
tr.insert(0, node);
return true;
});
});
}}
/>
{showDragOverMsg && (
<>
<HoverDiv></HoverDiv>
<HoverTextDiv>Hold ⇧ to drop image</HoverTextDiv>
</>
)}
</InputBoxDiv>
);
}

View file

@ -38,6 +38,7 @@ function getSuggestion(
interactive: true,
trigger: "manual",
placement: "bottom-start",
maxWidth: `${window.innerWidth - 24}px`,
});
onOpen();

View file

@ -132,15 +132,25 @@ async function resolveEditorContent(
}
if (slashCommand) {
let firstTextIndex = parts.findIndex((part) => part.type === "text");
parts[
firstTextIndex
].text = `${slashCommand} ${parts[firstTextIndex].text}`;
let lastTextIndex = findLastIndex(parts, (part) => part.type === "text");
parts[lastTextIndex].text = `${slashCommand} ${parts[lastTextIndex].text}`;
}
return [contextItems, parts];
}
function findLastIndex<T>(
array: T[],
predicate: (value: T, index: number, obj: T[]) => boolean
): number {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i], i, array)) {
return i;
}
}
return -1; // if no element satisfies the predicate
}
function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] {
let text = "";
const contextItems = [];

View file

@ -0,0 +1,77 @@
import {
CheckIcon,
ClipboardIcon,
PlayIcon,
} from "@heroicons/react/24/outline";
import { postToIde } from "core/ide/messaging";
import { useState } from "react";
import styled from "styled-components";
import { vscEditorBackground } from "..";
import HeaderButtonWithText from "../HeaderButtonWithText";
const TopDiv = styled.div`
position: sticky;
top: 0;
left: 100%;
height: 0;
width: 0;
overflow: visible;
`;
const SecondDiv = styled.div`
position: absolute;
top: -6px;
right: -6px;
display: flex;
gap: 4px;
`;
interface CodeBlockToolBarProps {
text: string;
}
function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const [copied, setCopied] = useState(false);
const [applying, setApplying] = useState(false);
return (
<TopDiv>
<SecondDiv>
<HeaderButtonWithText
text={applying ? "Applying..." : "Apply to current file"}
disabled={applying}
style={{ backgroundColor: vscEditorBackground }}
onClick={(e) => {
if (applying) return;
postToIde("applyToCurrentFile", { text: props.text });
setApplying(true);
setTimeout(() => setApplying(false), 2000);
}}
>
{applying ? (
<CheckIcon className="w-5 h-5 text-green-500" />
) : (
<PlayIcon className="w-5 h-5" />
)}
</HeaderButtonWithText>
<HeaderButtonWithText
text={copied ? "Copied!" : "Copy"}
style={{ backgroundColor: vscEditorBackground }}
onClick={(e) => {
navigator.clipboard.writeText(props.text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}}
>
{copied ? (
<CheckIcon className="w-5 h-5 text-green-500" />
) : (
<ClipboardIcon className="w-5 h-5" />
)}
</HeaderButtonWithText>
</SecondDiv>
</TopDiv>
);
}
export default CodeBlockToolBar;

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