Merge branch 'dev' into nate/jetbrains-tooltip

This commit is contained in:
Test 2024-08-23 09:55:34 -07:00
commit 860eb77798
69 changed files with 2146 additions and 1080 deletions

View file

@ -2,7 +2,7 @@
# Running the publishPlugin task requires all following secrets to be provided: PUBLISH_TOKEN, PRIVATE_KEY, PRIVATE_KEY_PASSWORD, CERTIFICATE_CHAIN.
# See https://plugins.jetbrains.com/docs/intellij/plugin-signing.html for more information.
name: Release
name: JetBrains Release
on:
release:

View file

@ -1,14 +1,27 @@
name: Publish Extension
on:
push:
tags:
- "v0.8.*-vscode"
branches:
- main
release:
types: [released]
jobs:
check_release_name:
runs-on: ubuntu-latest
outputs:
should_run: ${{ steps.check.outputs.should_run }}
steps:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.8.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
strategy:
matrix:
include:

View file

@ -1,14 +1,27 @@
name: Publish Preview Extension
on:
push:
tags:
- "v0.9.*-vscode"
branches:
- dev
release:
types: [prereleased]
jobs:
check_release_name:
runs-on: ubuntu-latest
outputs:
should_run: ${{ steps.check.outputs.should_run }}
steps:
- id: check
working-directory: .
run: |
if [[ "${{ github.event.release.tag_name }}" == v0.9.*-vscode ]]; then
echo "should_run=true" >> $GITHUB_OUTPUT
else
echo "should_run=false" >> $GITHUB_OUTPUT
fi
build:
needs: check_release_name
if: needs.check_release_name.outputs.should_run == 'true'
strategy:
matrix:
include:
@ -99,12 +112,12 @@ jobs:
npm ci
npm i vectordb
- name: Run core tests
run: |
cd core
npm run test
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# - name: Run core tests
# run: |
# cd core
# npm run test
# env:
# OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
# 2.5. Pre package
- name: Set var for environment info

2
.gitignore vendored
View file

@ -165,7 +165,5 @@ Icon?
.continue
# Sandbox env default file
extensions/vscode/manual-testing-sandbox/example.ts
.prompts/

9
.vscode/tasks.json vendored
View file

@ -45,8 +45,6 @@
}
]
},
// Tsc currently errors out due to testing setup issues, will be resolved in a different PR
// This will be useful for preventing debugging if there are compile errors
{
"label": "vscode-extension:tsc",
"type": "npm",
@ -164,6 +162,13 @@
"options": {
"cwd": "docs"
}
},
{
"label": "clean",
"type": "shell",
"command": "node",
"args": ["${workspaceFolder}/scripts/uninstall.js"],
"problemMatcher": []
}
]
}

View file

@ -49,6 +49,7 @@
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.10",
"@continuedev/llm-info": "^1.0.1",
"@crawlee/playwright": "^3.11.1",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
"@typescript-eslint/eslint-plugin": "^7.8.0",
@ -57,11 +58,11 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
"dotenv": "^16.4.5",
"extract-zip": "^2.0.1",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"handlebars": "^4.7.8",
@ -81,6 +82,7 @@
"openai": "^4.20.1",
"p-limit": "^6.1.0",
"pg": "^8.11.3",
"playwright": "^1.46.1",
"posthog-node": "^3.6.3",
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",

View file

@ -33,8 +33,8 @@ const stableCodeFimTemplate: AutocompleteTemplate = {
"<fim_prefix>",
"<fim_suffix>",
"<fim_middle>",
"<|endoftext|>",
"<file_sep>",
"<|endoftext|>",
"</fim_middle>",
"</code>",
],
@ -134,8 +134,8 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
"<fim_prefix>",
"<fim_suffix>",
"<fim_middle>",
"<|endoftext|>",
"<file_sep>",
"<|endoftext|>",
],
},
};

View file

@ -355,9 +355,11 @@ async function intermediateToFinalConfig(
// These context providers are always included, regardless of what, if anything,
// the user has configured in config.json
const codebaseContextParams = ((config.contextProviders || []).filter(isContextProviderWithParams).find(cp => cp.name === "codebase") as ContextProviderWithParams | undefined)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(

View file

@ -10,6 +10,7 @@ import {
import ContinueProxyEmbeddingsProvider from "../../indexing/embeddings/ContinueProxyEmbeddingsProvider.js";
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy.js";
import { Telemetry } from "../../util/posthog.js";
import { TTS } from "../../util/tts.js";
import { loadFullConfigNode } from "../load.js";
export default async function doLoadConfig(
@ -51,6 +52,9 @@ export default async function doLoadConfig(
ideInfo,
);
// TODO: pass config to pre-load non-system TTS models
await TTS.setup();
if (newConfig.analytics) {
await TeamAnalytics.setup(
newConfig.analytics as any, // TODO: Need to get rid of index.d.ts once and for all

View file

@ -26,7 +26,9 @@ import historyManager from "./util/history";
import type { IMessenger, Message } from "./util/messenger";
import { editConfigJson } from "./util/paths";
import { Telemetry } from "./util/posthog";
import { TTS } from "./util/tts";
import { streamDiffLines } from "./util/verticalEdit";
import DocsCrawler from "./indexing/docs/DocsCrawler";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>
@ -167,6 +169,12 @@ export class Core {
(..._) => Promise.resolve([]),
);
try {
DocsCrawler.verifyOrInstallChromium();
} catch (err) {
console.debug(`Failed to install Chromium: ${err}`);
}
const on = this.messenger.on.bind(this.messenger);
this.messenger.onError((err) => {
@ -360,6 +368,13 @@ export class Core {
abortedMessageIds: Set<string>,
msg: Message<ToCoreProtocol["llm/streamChat"][0]>,
) {
const config = await configHandler.loadConfig();
// Stop TTS on new StreamChat
if(config.experimental?.readResponseTTS) {
TTS.kill();
}
const model = await configHandler.llmFromTitle(msg.data.title);
const gen = model.streamChat(
msg.data.messages,
@ -384,6 +399,10 @@ export class Core {
next = await gen.next();
}
if(config.experimental?.readResponseTTS && "completion" in next.value) {
TTS.read(next.value?.completion);
}
return { done: true, content: next.value };
}
@ -458,6 +477,13 @@ export class Core {
}
});
// Provide messenger to TTS so it can set GUI active / inactive state
TTS.messenger = this.messenger;
on("tts/kill", async () => {
TTS.kill();
});
async function* runNodeJsSlashCommand(
configHandler: ConfigHandler,
abortedMessageIds: Set<string>,

23
core/index.d.ts vendored
View file

@ -344,19 +344,23 @@ export interface LLMOptions {
apiVersion?: string;
apiType?: string;
// GCP Options
// AWS options
profile?: string;
modelArn?: string;
// AWS and GCP Options
region?: string;
// GCP Options
projectId?: string;
capabilities?: ModelCapability;
// WatsonX options
// IBM watsonx options
watsonxUrl?: string;
watsonxApiKey?: string;
watsonxZenApiKeyBase64?: string; // Required if using watsonx software with ZenApiKey auth
watsonxUsername?: string;
watsonxPassword?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
@ -590,6 +594,7 @@ type ModelProvider =
| "ollama"
| "huggingface-tgi"
| "huggingface-inference-api"
| "kindo"
| "llama.cpp"
| "replicate"
| "text-gen-webui"
@ -598,6 +603,7 @@ type ModelProvider =
| "gemini"
| "mistral"
| "bedrock"
| "bedrockimport"
| "sagemaker"
| "deepinfra"
| "flowise"
@ -892,6 +898,11 @@ interface ExperimentalConfig {
* function and class declarations.
*/
quickActions?: QuickActionConfig[];
/**
* Automatically read LLM chat responses aloud using system TTS models
*/
readResponseTTS?: boolean;
}
interface AnalyticsConfig {

View file

@ -183,18 +183,20 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
for (let i = 0; i < results.del.length; i++) {
const del = results.del[i];
const snippetToDelete = await db.get(
const snippets = await db.all(
"SELECT id FROM code_snippets WHERE path = ? AND cacheKey = ?",
[del.path, del.cacheKey],
);
await db.run("DELETE FROM code_snippets WHERE id = ?", [
snippetToDelete.id,
]);
if (snippets) {
const snippetIds = snippets.map((row) => row.id).join(",");
await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [
snippetToDelete.id,
]);
await db.run(`DELETE FROM code_snippets WHERE id IN (${snippetIds})`);
await db.run(
`DELETE FROM code_snippets_tags WHERE snippetId IN (${snippetIds})`,
);
}
markComplete([del], IndexResultType.Delete);
}
@ -202,36 +204,61 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
// Add tag
for (let i = 0; i < results.addTag.length; i++) {
const addTag = results.addTag[i];
let snippets: (ChunkWithoutID & { title: string })[] = [];
try {
snippets = await this.getSnippetsInFile(
addTag.path,
await this.ide.readFile(addTag.path),
);
} catch (e) {
// If can't parse, assume malformatted code
console.error(`Error parsing ${addTag.path}:`, e);
}
await db.run(
`
REPLACE INTO code_snippets_tags (tag, snippetId)
SELECT ?, (
SELECT id
FROM code_snippets
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, addTag.cacheKey, addTag.path],
);
for (const snippet of snippets) {
const { lastID } = await db.run(
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
[
addTag.path,
addTag.cacheKey,
snippet.content,
snippet.title,
snippet.startLine,
snippet.endLine,
],
);
await db.run(
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[lastID, tagString],
);
}
markComplete([results.addTag[i]], IndexResultType.AddTag);
}
// Remove tag
for (let i = 0; i < results.removeTag.length; i++) {
const item = results.removeTag[i];
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (
SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?
)
`,
[tagString, item.cacheKey, item.path],
const removeTag = results.removeTag[i];
const snippets = await db.get(
`SELECT id FROM code_snippets
WHERE cacheKey = ? AND path = ?`,
[removeTag.cacheKey, removeTag.path],
);
if (snippets) {
const snippetIds = snippets.map((row: any) => row.id).join(",");
await db.run(
`
DELETE FROM code_snippets_tags
WHERE tag = ?
AND snippetId IN (${snippetIds})
`,
[tagString],
);
}
markComplete([results.removeTag[i]], IndexResultType.RemoveTag);
}
}

View file

@ -1,8 +1,8 @@
import { jest } from "@jest/globals";
import {
insertMockChunks,
updateIndexAndAwaitGenerator,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
@ -25,7 +25,7 @@ describe("FullTextSearchCodebaseIndex", () => {
index = new FullTextSearchCodebaseIndex();
});
it("should update the index and maintain expected database state", async () => {
it.skip("should update the index and maintain expected database state", async () => {
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;

View file

@ -1,11 +1,11 @@
import { jest } from "@jest/globals";
import lance from "vectordb";
import { testIde, testConfigHandler } from "../test/util/fixtures";
import { testConfigHandler, testIde } from "../test/util/fixtures";
import {
testContinueServerClient,
mockTag,
updateIndexAndAwaitGenerator,
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
@ -48,7 +48,7 @@ describe("ChunkCodebaseIndex", () => {
* - We cannot open either the 'dev' or 'main' tag tables ubtil after we
* can assume they've been created through `updateIndexAndAwaitGenerator`
*/
it("should update the index and maintain expected database state", async () => {
it.skip("should update the index and maintain expected database state", async () => {
const mainTag = mockTag;
const mainTagTableName = index.tableNameForTag(mainTag);

View file

@ -1,9 +1,5 @@
import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";
import { testIde } from "../../test/util/fixtures";
import { addToTestDir } from "../../test/util/testDir";
import { jest } from "@jest/globals";
import { testIde } from "../../test/util/fixtures";
import {
mockFileContents,
mockFilename,
@ -11,6 +7,10 @@ import {
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../../test/util/indexing";
import { addToTestDir } from "../../test/util/testDir";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";
import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex";
jest.useFakeTimers();
@ -41,7 +41,7 @@ describe("ChunkCodebaseIndex", () => {
db = await SqliteDb.get();
});
it("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => {
it.skip("should update the index and maintain expected database state, following the same processing order of results as the update method", async () => {
const mockMarkComplete = jest
.fn()
.mockImplementation(() => Promise.resolve()) as any;

View file

@ -0,0 +1,130 @@
import DocsCrawler, { type PageData } from "./DocsCrawler";
import preIndexedDocs from "./preIndexedDocs";
// Temporary workaround until we have better caching of Chromium
// download between test runs
const TIMEOUT = 1_000_000;
// Skipped until we have a better way to cache Chromium installs
// between tests and in CI
describe.skip("crawl", () => {
describe("GitHub repositories", () => {
const repoUrl =
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling";
let crawlResults: PageData[];
beforeAll(async () => {
const docsCrawler = new DocsCrawler(new URL(repoUrl));
crawlResults = [];
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
}, TIMEOUT);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.content.includes("Test body")).toBe(true);
expect(doc?.content.includes("Test H2 Header")).toBe(true);
});
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
describe.only("Non-Github repository sites", () => {
it(
"succeeds in crawling a list of common sites",
async () => {
const TEST_SITES = [
"https://docs.nestjs.com/",
"https://docs.nestjs.com/",
"https://go.dev/doc/",
"https://clickhouse.com/docs",
"https://www.tensorflow.org/api_docs",
"https://www.rust-lang.org/learn",
"https://docs.anthropic.com/en/docs",
];
const NUM_PAGES_TO_CRAWL = 10;
for (const site of TEST_SITES) {
const crawlResults: PageData[] = [];
const docsCrawler = new DocsCrawler(
new URL(site),
NUM_PAGES_TO_CRAWL,
);
for await (const page of docsCrawler.crawl()) {
crawlResults.push(page);
}
// `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee
// an exact number of pages to crawl since it runs in parallel
expect(crawlResults.length).toBeGreaterThanOrEqual(
NUM_PAGES_TO_CRAWL,
);
}
},
TIMEOUT,
);
});
describe("Pre-indexed Docs", () => {
const results: { [url: string]: boolean } = {};
let totalTests = 0;
let passedTests = 0;
Object.keys(preIndexedDocs).forEach((url) => {
test(
`Crawl test for ${url}`,
async () => {
totalTests++;
let pageFound = false;
try {
const docsCrawler = new DocsCrawler(new URL(url), 1);
for await (const page of docsCrawler.crawl()) {
if (page.url === url) {
pageFound = true;
break;
}
}
} catch (error) {
console.error(`Error crawling ${url}:`, error);
}
results[url] = pageFound;
if (pageFound) {
passedTests++;
console.log(`✅ ${url}`);
} else {
console.log(`❌ ${url}`);
}
expect(pageFound).toBe(true);
},
TIMEOUT,
);
});
});
});

View file

@ -0,0 +1,248 @@
import { Octokit } from "@octokit/rest";
import * as fs from "fs";
import { URL } from "node:url";
import { Page } from "puppeteer";
import { getChromiumPath, getContinueUtilsPath } from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
export type PageData = {
url: string;
path: string;
content: string;
};
export default class DocsCrawler {
LINK_GROUP_SIZE = 2; // Controls parallelization of crawler
GITHUB_HOST = "github.com";
static MAX_REQUESTS_PER_CRAWL = 1000;
markdownRegex = new RegExp(/\.(md|mdx)$/);
octokit = new Octokit({
auth: undefined,
});
static PCR_CONFIG = {
downloadPath: getContinueUtilsPath(),
};
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number = DocsCrawler.MAX_REQUESTS_PER_CRAWL,
) {}
static verifyOrInstallChromium() {
if (!fs.existsSync(getChromiumPath())) {
PCR(DocsCrawler.PCR_CONFIG);
}
}
async *crawl(): AsyncGenerator<PageData> {
if (this.startUrl.host === this.GITHUB_HOST) {
yield* this.crawlGithubRepo();
} else {
yield* this.crawlSite();
}
}
private async getGithubRepoDefaultBranch(
owner: string,
repo: string,
): Promise<string> {
const repoInfo = await this.octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
private async getGitHubRepoPaths(
owner: string,
repo: string,
branch: string,
) {
const tree = await this.octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
return paths;
}
private async getGithubRepoFileContent(
path: string,
owner: string,
repo: string,
) {
try {
const response = await this.octokit.repos.getContent({
owner,
repo,
path,
headers: {
Accept: "application/vnd.github.raw+json",
},
});
return response.data as unknown as string;
} catch (error) {
console.debug("Error fetching file contents:", error);
return null;
}
}
private async *crawlGithubRepo() {
console.debug(`Crawling GitHub repo: ${this.startUrl.toString()}`);
const urlStr = this.startUrl.toString();
const [_, owner, repo] = this.startUrl.pathname.split("/");
const branch = await this.getGithubRepoDefaultBranch(owner, repo);
const paths = await this.getGitHubRepoPaths(owner, repo, branch);
for await (const path of paths) {
const content = await this.getGithubRepoFileContent(path, owner, repo);
yield {
path,
url: urlStr,
content: content ?? "",
};
}
}
private stripHashFromUrl(urlStr: string) {
try {
let url = new URL(urlStr);
url.hash = "";
return url;
} catch (err) {
return null;
}
}
private isValidHostAndPath(newUrl: URL, curUrl: URL) {
return (
newUrl.pathname.startsWith(curUrl.pathname) && newUrl.host === curUrl.host
);
}
private async getLinksFromPage(page: Page, curUrl: URL) {
const links = await page.$$eval("a", (links) => links.map((a) => a.href));
// This additional step is due to issues getting the URL module to work
// in an $$eval command
const cleanedLinks = links
.map(this.stripHashFromUrl)
.filter(
(newUrl) =>
newUrl !== null &&
this.isValidHostAndPath(newUrl, curUrl) &&
newUrl !== curUrl,
)
.map((newUrl) => (newUrl as URL).href);
const dedupedLinks = Array.from(new Set(cleanedLinks));
return dedupedLinks;
}
private async getLinkGroupsFromPage(page: Page, curUrl: URL) {
const links = await this.getLinksFromPage(page, curUrl);
const groups = links.reduce((acc, link, i) => {
const groupIndex = Math.floor(i / this.LINK_GROUP_SIZE);
if (!acc[groupIndex]) {
acc.push([]);
}
acc[groupIndex].push(link);
return acc;
}, [] as string[][]);
return groups;
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
curRequestCount: number = 0,
): AsyncGenerator<PageData> {
if (curRequestCount >= this.maxRequestsPerCrawl) {
console.warn("Max requests per crawl reached. Stopping crawler.");
return;
}
if (visitedLinks.has(curUrl.toString())) {
return;
}
console.debug(`Crawling page: ${curUrl.toString()}`);
await page.goto(curUrl.toString());
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
const requestCount = curRequestCount + 1;
visitedLinks.add(curUrl.toString());
yield {
path: curUrl.pathname,
url: curUrl.toString(),
content: htmlContent,
};
for (const linkGroup of linkGroups) {
for (const link of linkGroup) {
yield* this.crawlSitePages(
page,
new URL(link),
visitedLinks,
requestCount,
);
}
}
}
private async *crawlSite(): AsyncGenerator<PageData> {
console.debug(`Crawling site repo: ${this.startUrl}`);
const stats = await PCR(DocsCrawler.PCR_CONFIG);
const browser = await stats.puppeteer.launch({
args: [
"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
],
executablePath: stats.executablePath,
});
const page = await browser.newPage();
try {
yield* this.crawlSitePages(page, this.startUrl);
} catch (e) {
console.debug("Error getting links: ", e);
} finally {
await browser.close();
}
}
}

View file

@ -1,8 +1,8 @@
import { open, type Database } from "sqlite";
import sqlite3 from "sqlite3";
import lancedb, { Connection } from "vectordb";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import DocsContextProvider from "../../context/providers/DocsContextProvider.js";
import { ConfigHandler } from "../../config/ConfigHandler";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import {
Chunk,
ContinueConfig,
@ -10,27 +10,27 @@ import {
IDE,
IndexingProgressUpdate,
SiteIndexingConfig,
} from "../../index.js";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol/index.js";
import { GlobalContext } from "../../util/GlobalContext.js";
import { IMessenger } from "../../util/messenger.js";
} from "../..";
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
import {
editConfigJson,
getDocsSqlitePath,
getLanceDbPath,
} from "../../util/paths.js";
import { Telemetry } from "../../util/posthog.js";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider.js";
import { Article, chunkArticle, pageToArticle } from "./article.js";
import { crawlPage } from "./crawl.js";
import { runLanceMigrations, runSqliteMigrations } from "./migrations.js";
} from "../../util/paths";
import { Telemetry } from "../../util/posthog";
import TransformersJsEmbeddingsProvider from "../embeddings/TransformersJsEmbeddingsProvider";
import { Article, chunkArticle, pageToArticle } from "./article";
import DocsCrawler from "./DocsCrawler";
import { runLanceMigrations, runSqliteMigrations } from "./migrations";
import {
downloadFromS3,
getS3Filename,
S3Buckets,
SiteIndexingResults,
} from "./preIndexed.js";
import preIndexedDocs from "./preIndexedDocs.js";
} from "./preIndexed";
import preIndexedDocs from "./preIndexedDocs";
// Purposefully lowercase because lancedb converts
export interface LanceDbDocsRow {
@ -112,8 +112,8 @@ export default class DocsService {
}
/*
* Currently, we generate and host embeddings for pre-indexed docs using transformers.js.
* However, we don't ship transformers.js with the JetBrains extension.
* Currently, we generate and host embeddings for pre-indexed docs using transformers.
* However, we don't ship transformers with the JetBrains extension.
* So, we only include pre-indexed docs in the submenu for non-JetBrains IDEs.
*/
async canUsePreindexedDocs() {
@ -202,11 +202,10 @@ export default class DocsService {
let processedPages = 0;
let maxKnownPages = 1;
const docsCrawler = new DocsCrawler(new URL(startUrl));
// Crawl pages and retrieve info as articles
for await (const page of crawlPage(
new URL(startUrl),
siteIndexingConfig.maxDepth,
)) {
for await (const page of docsCrawler.crawl()) {
processedPages++;
const article = pageToArticle(page);
@ -279,6 +278,8 @@ export default class DocsService {
status: "failed",
};
this.docsIndexingQueue.delete(startUrl);
return;
}
@ -291,8 +292,8 @@ export default class DocsService {
status: "indexing",
};
// Clear old index if re-indexing.
if (reIndex) {
// Delete indexed docs if re-indexing
if (reIndex && await this.has(startUrl.toString())) {
console.log("Deleting old embeddings");
await this.delete(startUrl);
}
@ -521,8 +522,9 @@ export default class DocsService {
private async getLanceTableNameFromEmbeddingsProvider(
isPreIndexedDoc: boolean,
) {
const embeddingsProvider =
await this.getEmbeddingsProvider(isPreIndexedDoc);
const embeddingsProvider = await this.getEmbeddingsProvider(
isPreIndexedDoc,
);
const embeddingsProviderId = this.removeInvalidLanceTableNameChars(
embeddingsProvider.id,
);

View file

@ -1,8 +1,8 @@
import { Readability } from "@mozilla/readability";
import { JSDOM } from "jsdom";
import { Chunk } from "../../index.js";
import { cleanFragment, cleanHeader } from "../chunk/markdown.js";
import { PageData } from "./crawl.js";
import { Chunk } from "../../";
import { cleanFragment, cleanHeader } from "../chunk/markdown";
import { type PageData } from "./DocsCrawler";
export type ArticleComponent = {
title: string;
@ -148,7 +148,7 @@ export function stringToArticle(
export function pageToArticle(page: PageData): Article | undefined {
try {
return stringToArticle(page.url, page.html, page.path);
return stringToArticle(page.url, page.content, page.path);
} catch (err) {
console.error("Error converting URL to article components", err);
return undefined;

View file

@ -1,103 +0,0 @@
import { crawlPage, PageData } from "../../indexing/docs/crawl";
describe("crawlPage - GitHub repository", () => {
const repoUrl = new URL(
"https://github.com/Patrick-Erichsen/test-github-repo-for-crawling",
);
const maxDepth = 3;
let crawlResults: PageData[];
beforeAll(async () => {
crawlResults = [];
for await (const page of crawlPage(repoUrl, maxDepth)) {
crawlResults.push(page);
}
}, 30000);
test("finds expected markdown files", async () => {
expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe(
true,
);
expect(
crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")),
).toBe(true);
});
test("html includes the correct content", async () => {
const doc = crawlResults.find((page) =>
page.path.endsWith("docs-depth-1.md"),
);
expect(doc?.html.includes("Test body")).toBe(true);
expect(doc?.html.includes("Test H2 Header")).toBe(true);
});
// This test is currently failing, `maxDepth` does not appear to be followed right now
test.todo(
"ignores files past the max depth",
// , () => {
// expect(
// crawlResults.some((page) => page.path.includes("docs-depth-3")),
// ).toBe(false);
// }
);
test("ignores non-markdown files, e.g. `test.js` at the root", async () => {
expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe(
false,
);
});
});
async function testSite(url: string, expectedPaths: string[]) {
test(`crawlPage - ${url}`, async () => {
const crawlResults: PageData[] = [];
for await (const page of crawlPage(new URL(url))) {
crawlResults.push(page);
}
console.log(crawlResults.map((page) => page.path));
// Check if all expected paths are found
for (const expectedPath of expectedPaths) {
expect(
crawlResults.some((page) => page.path.endsWith(expectedPath)),
).toBe(true);
}
});
}
const SITES: { [rootUrl: string]: string[] } = {
"https://docs.continue.dev": [
"intro",
"quickstart",
"features/tab-autocomplete",
"reference/Model%20Providers/mistral",
],
// Failing
// "https://docs.nestjs.com/": ["first-steps"],
// Taking too much time
// "https://go.dev/doc/": ["install", "tutorial/getting-started", "comment"],
// Taking too much time
// "https://clickhouse.com/docs": [
// "intro",
// "getting-started/quick-start",
// "migrations/bigquery/migrating-to-clickhouse-cloud",
// ],
// Taking too much time
// "https://www.tensorflow.org/api_docs": ["python/tf/Variable"],
// "https://www.rust-lang.org/learn": []
// Taking too long
// "https://docs.anthropic.com/en/docs": [
// "welcome",
// "quickstart",
// "build-with-claude/prompt-engineering/prompt-generator",
// ],
};
describe.only("crawlPage should return expected subpages for common sites", () => {
for (const [rootUrl, expectedPaths] of Object.entries(SITES)) {
testSite(rootUrl, expectedPaths);
}
});

View file

@ -1,212 +0,0 @@
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
import { URL } from "node:url";
const IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
const markdownRegex = new RegExp(/\.(md|mdx)$/);
async function getDefaultBranch(owner: string, repo: string): Promise<string> {
const octokit = new Octokit({ auth: undefined });
const repoInfo = await octokit.repos.get({
owner,
repo,
});
return repoInfo.data.default_branch;
}
async function crawlGithubRepo(baseUrl: URL) {
const octokit = new Octokit({
auth: undefined,
});
const [_, owner, repo] = baseUrl.pathname.split("/");
const branch = await getDefaultBranch(owner, repo);
console.log("Github repo detected. Crawling", branch, "branch");
const tree = await octokit.request(
"GET /repos/{owner}/{repo}/git/trees/{tree_sha}",
{
owner,
repo,
tree_sha: branch,
headers: {
"X-GitHub-Api-Version": "2022-11-28",
},
recursive: "true",
},
);
const paths = tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && markdownRegex.test(file.path ?? ""),
)
.map((file: any) => baseUrl.pathname + "/tree/main/" + file.path);
return paths;
}
async function getLinksFromUrl(url: string, path: string) {
const baseUrl = new URL(url);
const location = new URL(path, url);
let response;
try {
response = await fetch(location.toString());
} catch (error: unknown) {
if (error instanceof Error && error.message.includes("maximum redirect")) {
console.error("Maximum redirect reached for: ", location.toString());
return {
html: "",
links: [],
};
}
console.error(error);
return {
html: "",
links: [],
};
}
const html = await response.text();
let links: string[] = [];
if (url.includes("github.com")) {
return {
html,
links,
};
}
const $ = cheerio.load(html);
$("a").each((_, element) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, url);
if (
parsedUrl.hostname === baseUrl.hostname
// parsedUrl.pathname.startsWith(baseUrl.pathname)
) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return {
html,
links,
};
}
function splitUrl(url: URL) {
const baseUrl = `${url.protocol}//${url.hostname}${
url.port ? ":" + url.port : ""
}`;
const basePath = url.pathname;
return {
baseUrl,
basePath,
};
}
export type PageData = {
url: string;
path: string;
html: string;
};
export async function* crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`Starting crawl from: ${url.toString()} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = splitUrl(url);
let paths: { path: string; depth: number }[] = [{ path: basePath, depth: 0 }];
if (url.hostname === "github.com") {
const githubLinks = await crawlGithubRepo(url);
const githubLinkObjects = githubLinks.map((link) => ({
path: link,
depth: 0,
}));
paths = [...paths, ...githubLinkObjects];
}
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
); // Adjust for depth tracking
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
// Check depth
yield {
url: url.toString(),
path,
html,
};
}
// Ensure we only add links if within depth limit
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 }); // Increment depth for new paths
}
}
}
}
} catch (e) {
if (e instanceof TypeError) {
console.warn("Error while crawling page: ", e); // Likely an invalid url, continue with process
} else {
console.error("Error while crawling page: ", e);
}
}
index += batch.length; // Proceed to next batch
}
console.log("Crawl completed");
}

View file

@ -1,4 +1,4 @@
import { SiteIndexingConfig } from "../../index.js";
import { SiteIndexingConfig } from "../../";
const preIndexedDocs: Record<
SiteIndexingConfig["startUrl"],

View file

@ -1,8 +1,7 @@
// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055
import { TextEncoder, TextDecoder } from "util";
import fetch, { Request, Response } from "node-fetch";
import { jest } from "@jest/globals";
import fs from "fs";
import fetch, { Request, Response } from "node-fetch";
import { TextDecoder, TextEncoder } from "util";
if (process.env.DEBUG === "jest") {
jest.setTimeout(5 * 60 * 1000);
@ -16,16 +15,17 @@ globalThis.Response = Response;
globalThis.TextEncoder = TextEncoder;
globalThis.TextDecoder = TextDecoder;
globalThis.beforeAll(() => {
// We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
}
});
// Trying to delete this when for some reason SQLite is still in use causes tests to fail
// globalThis.beforeAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });
globalThis.afterAll(() => {
// We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
}
});
// globalThis.afterAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });

View file

@ -111,15 +111,12 @@ export abstract class BaseLLM implements ILLM {
accountId?: string;
aiGatewaySlug?: string;
// For WatsonX only.
// For IBM watsonx only.
watsonxUrl?: string;
watsonxApiKey?: string;
watsonxZenApiKeyBase64?: string = "YOUR_WATSONX_ZENAPIKEY"; // Required if using watsonx software with ZenApiKey auth
watsonxUsername?: string;
watsonxPassword?: string;
watsonxCreds?: string;
watsonxProjectId?: string;
watsonxStopToken?: string;
watsonxApiVersion?: string;
private _llmOptions: LLMOptions;
@ -173,13 +170,13 @@ export abstract class BaseLLM implements ILLM {
this.apiKey = options.apiKey;
this.aiGatewaySlug = options.aiGatewaySlug;
this.apiBase = options.apiBase;
// for watsonx only
this.watsonxUrl = options.watsonxUrl;
this.watsonxApiKey = options.watsonxApiKey;
this.watsonxCreds = options.watsonxCreds;
this.watsonxProjectId = options.watsonxProjectId;
this.watsonxUsername = options.watsonxUsername;
this.watsonxPassword = options.watsonxPassword;
this.watsonxStopToken = options.watsonxStopToken;
this.watsonxApiVersion = options.watsonxApiVersion;
if (this.apiBase && !this.apiBase.endsWith("/")) {
this.apiBase = `${this.apiBase}/`;

View file

@ -14,19 +14,24 @@ import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
class Bedrock extends BaseLLM {
private static PROFILE_NAME: string = "bedrock";
static providerName: ModelProvider = "bedrock";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
contextLength: 200_000
};
profile?: string | undefined;
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
}
protected async *_streamComplete(
@ -124,11 +129,11 @@ class Bedrock extends BaseLLM {
private async _getCredentials() {
try {
return await fromIni({
profile: Bedrock.PROFILE_NAME,
profile: this.profile,
})();
} catch (e) {
console.warn(
`AWS profile with name ${Bedrock.PROFILE_NAME} not found in ~/.aws/credentials, using default profile`,
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}

View file

@ -0,0 +1,96 @@
import {
BedrockRuntimeClient,
InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { fromIni } from "@aws-sdk/credential-providers";
import {
CompletionOptions,
LLMOptions,
ModelProvider,
} from "../../index.js";
import { BaseLLM } from "../index.js";
class BedrockImport extends BaseLLM {
static providerName: ModelProvider = "bedrockimport";
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1"
};
// the BedRock imported custom model ARN
modelArn?: string | undefined;
profile?: string | undefined;
constructor(options: LLMOptions) {
super(options);
if (!options.apiBase) {
this.apiBase = `https://bedrock-runtime.${options.region}.amazonaws.com`;
}
if (options.modelArn) {
this.modelArn = options.modelArn;
}
if (options.profile) {
this.profile = options.profile;
} else {
this.profile = "bedrock";
}
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions,
): AsyncGenerator<string> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,
credentials: {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken || "",
},
});
const input = this._generateInvokeModelCommandInput(prompt, options);
const command = new InvokeModelWithResponseStreamCommand(input);
const response = await client.send(command);
if (response.body) {
for await (const item of response.body) {
const chunk = JSON.parse(new TextDecoder().decode(item.chunk?.bytes));
if (chunk.outputs[0].text) {
yield chunk.outputs[0].text;
}
}
}
}
private _generateInvokeModelCommandInput(
prompt: string,
options: CompletionOptions,
): any {
const payload = {
prompt: prompt
};
return {
body: JSON.stringify(payload),
modelId: this.modelArn,
accept: "application/json",
contentType: "application/json"
};
}
private async _getCredentials() {
try {
return await
fromIni({
profile: this.profile
})();
} catch (e) {
console.warn(
`AWS profile with name ${this.profile} not found in ~/.aws/credentials, using default profile`,
);
return await fromIni()();
}
}
}
export default BedrockImport;

16
core/llm/llms/Kindo.ts Normal file
View file

@ -0,0 +1,16 @@
import { LLMOptions, ModelProvider } from "../..";
import OpenAI from "./OpenAI";
class Kindo extends OpenAI {
static providerName: ModelProvider = "kindo";
static defaultOptions: Partial<LLMOptions> = {
apiBase: "https://llm.kindo.ai/v1",
requestOptions: {
headers: {
"kindo-token-transaction-type": "CONTINUE"
}
}
};
}
export default Kindo;

View file

@ -6,6 +6,7 @@ import {
} from "../../index.js";
import { stripImages } from "../images.js";
import { BaseLLM } from "../index.js";
import { streamResponse } from "../stream.js";
const watsonxConfig = {
accessToken: {
expiration: 0,
@ -19,14 +20,14 @@ class WatsonX extends BaseLLM {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (
this.watsonxUrl !== null &&
this.watsonxUrl!.includes("cloud.ibm.com")
this.watsonxUrl?.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(
`https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxApiKey}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
`https://iam.cloud.ibm.com/identity/token?apikey=${this.watsonxCreds}&grant_type=urn:ibm:params:oauth:grant-type:apikey`,
{
method: "POST",
headers: {
@ -43,17 +44,16 @@ class WatsonX extends BaseLLM {
} else {
// watsonx Software
if (
this.watsonxZenApiKeyBase64 &&
this.watsonxZenApiKeyBase64 !== "YOUR_WATSONX_ZENAPIKEY"
!this.watsonxCreds?.includes(":")
) {
// Using ZenApiKey auth
return {
token: this.watsonxZenApiKeyBase64,
expiration: -1,
};
// Using ZenApiKey auth
return {
token: this.watsonxCreds ?? "",
expiration: -1,
};
} else {
// Using username/password auth
const userPass = this.watsonxCreds?.split(":");
const wxToken = await (
await fetch(`${this.watsonxUrl}/icp4d-api/v1/authorize`, {
method: "POST",
@ -62,8 +62,8 @@ class WatsonX extends BaseLLM {
Accept: "application/json",
},
body: JSON.stringify({
username: this.watsonxUsername,
password: this.watsonxPassword,
username: userPass[0],
password: userPass[1],
}),
})
).json();
@ -185,9 +185,9 @@ class WatsonX extends BaseLLM {
const stopToken =
this.watsonxStopToken ??
(options.model.includes("granite") ? "<|im_end|>" : undefined);
var streamResponse = await fetch(
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=2023-05-29`,
(options.model?.includes("granite") ? "<|im_end|>" : undefined);
var response = await this.fetch(
`${this.watsonxUrl}/ml/v1/text/generation_stream?version=${this.watsonxApiVersion}`,
{
method: "POST",
headers: {
@ -207,30 +207,22 @@ class WatsonX extends BaseLLM {
repetition_penalty: 1,
},
model_id: options.model,
project_id: this.watsonxProjectId,
project_id: this.watsonxProjectId
}),
},
);
if (!streamResponse.ok || streamResponse.body === null) {
if (!response.ok || response.body === null) {
throw new Error(
"Something went wrong. No response received, check your connection",
);
} else {
const reader = streamResponse.body.getReader();
while (true) {
const chunk = await reader.read();
if (chunk.done) {
break;
}
// Decode the stream
const textResponseMsg = new TextDecoder().decode(chunk.value);
const lines = textResponseMsg.split(/\r?\n/);
for await (const value of streamResponse(response)) {
const lines = value.split("\n");
let generatedChunk = "";
let generatedTextIndex = undefined;
lines.forEach((el) => {
lines.forEach((el: string) => {
// console.log(`${el}`);
if (el.startsWith("id:")) {
generatedTextIndex = parseInt(el.replace(/^id:\s+/, ""));

View file

@ -11,6 +11,7 @@ import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Azure from "./Azure";
import Bedrock from "./Bedrock";
import BedrockImport from "./BedrockImport";
import Cloudflare from "./Cloudflare";
import Cohere from "./Cohere";
import DeepInfra from "./DeepInfra";
@ -22,6 +23,7 @@ import Gemini from "./Gemini";
import Groq from "./Groq";
import HuggingFaceInferenceAPI from "./HuggingFaceInferenceAPI";
import HuggingFaceTGI from "./HuggingFaceTGI";
import Kindo from "./Kindo";
import LMStudio from "./LMStudio";
import LlamaCpp from "./LlamaCpp";
import Llamafile from "./Llamafile";
@ -49,11 +51,13 @@ const LLMs = [
Together,
HuggingFaceTGI,
HuggingFaceInferenceAPI,
Kindo,
LlamaCpp,
OpenAI,
LMStudio,
Mistral,
Bedrock,
BedrockImport,
SageMaker,
DeepInfra,
Flowise,

823
core/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,7 @@
"version": "1.0.13",
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand",
"build:npm": "tsc -p ./tsconfig.npm.json",
"lint": "eslint . --ext ts",
"lint:fix": "eslint . --ext ts --fix"
@ -51,7 +51,6 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
@ -76,6 +75,8 @@
"p-limit": "^6.1.0",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
@ -92,9 +93,6 @@
"yaml": "^2.4.2",
"zod": "^3.23.8"
},
"puppeteer": {
"chromium_revision": "119.0.6045.105"
},
"engine-strict": true,
"engines": {
"node": ">=20.11.0"

View file

@ -128,6 +128,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
undefined,
{ model: string; promptTokens: number; generatedTokens: number }[],
];
"tts/kill": [undefined, void];
"index/setPaused": [boolean, void];
"index/forceReIndex": [
undefined | { dir?: string; shouldClearIndexes?: boolean },

View file

@ -31,6 +31,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
setInactive: [undefined, void];
setTTSActive: [boolean, void];
submitMessage: [{ message: any }, void]; // any -> JSONContent from TipTap
updateSubmenuItems: [
{ provider: string; submenuItems: ContextSubmenuItem[] },

View file

@ -30,6 +30,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
"autocomplete/cancel",
"autocomplete/accept",
"command/run",
"tts/kill",
"llm/complete",
"llm/streamComplete",
"llm/streamChat",
@ -57,4 +58,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
"refreshSubmenuItems",
"isContinueInputFocused",
"didChangeAvailableProfiles",
"setTTSActive",
];

View file

@ -13,4 +13,5 @@ export type ToWebviewFromIdeOrCoreProtocol = {
},
void,
];
setTTSActive: [boolean, void];
};

View file

@ -0,0 +1,131 @@
import { PersistedSessionInfo } from "../..";
import historyManager from "../../util/history";
import { getSessionFilePath } from "../../util/paths";
import { v4 as uuidv4 } from "uuid";
const sessionId = uuidv4();
const testSession: PersistedSessionInfo = {
history: [],
title: `${sessionId} title`,
workspaceDirectory: "workspaceDir",
sessionId: sessionId,
};
describe("No sessions have been created", () => {
const testSessionId = "invalid";
const testSessionPath = getSessionFilePath(testSessionId);
test("Listing all sessions returns empty list", () => {
const sessions = historyManager.list({});
expect(sessions).toEqual([]);
});
test("Deleting session throws error", () => {
expect(() => {
historyManager.delete(testSessionId);
}).toThrow(`Session file ${testSessionPath} does not exist`);
});
test("Loading session returns default session", () => {
const session = historyManager.load(testSessionId);
expect(session).toEqual({
history: [],
title: "Failed to load session",
workspaceDirectory: "",
sessionId: testSessionId,
});
});
});
describe("Full session lifecycle", () => {
test("Creating and listing a session", () => {
// save and list
historyManager.save(testSession);
const sessions = historyManager.list({});
const sessionExists = sessions.some((session) => session?.sessionId === testSession.sessionId);
expect(sessionExists).toBe(true);
});
test("Loading session by ID returns correct object", () => {
const retrievedSession = historyManager.load(testSession.sessionId);
expect(retrievedSession).toEqual(testSession);
});
test("Saving session with new title updates session", () => {
const modifiedSession = { ...testSession };
modifiedSession.title = `Edited: ${testSession.title}`;
historyManager.save(modifiedSession);
const session = historyManager.load(testSession.sessionId);
expect(session.title).toBe(modifiedSession.title);
});
test("Deleting session", () => {
historyManager.delete(testSession.sessionId);
const sessions = historyManager.list({});
const sessionWasDeleted = sessions.every(
(session) => session?.sessionId !== testSession.sessionId,
);
expect(sessionWasDeleted).toEqual(true);
});
});
describe("Many sessions created", () => {
test("Create 100 sessions and list all", () => {
for (let i = 0; i < 100; i++) {
historyManager.save({
history: [],
title: `${i}`,
workspaceDirectory: "workspaceDir",
sessionId: `${i}`,
});
}
const sessions = historyManager.list({});
expect(sessions.length).toBe(100);
});
test("List 10 sessions, offest by 10", () => {
const limit = 10;
const offset = 10;
const sessions = historyManager.list({ offset: offset, limit: limit });
const sessionIds = Array.from({ length: limit }, (_, i) => (i + offset).toString());
const isSessionIdInList = (sessionId: string) =>
sessions.some((session) => session.sessionId === sessionId);
expect(sessionIds.every(isSessionIdInList)).toBe(true);
});
test("List 25 sessions, with no offset", () => {
const limit = 25;
const sessions = historyManager.list({ limit: limit });
const sessionIds = Array.from({ length: limit }, (_, i) => i.toString());
const isSessionIdInList = (sessionId: string) =>
sessions.some((session) => session.sessionId === sessionId);
expect(sessionIds.every(isSessionIdInList)).toBe(true);
});
test("List sessions offset by 75", () => {
const offset = 75;
const sessions = historyManager.list({ offset: offset });
const sessionIds = Array.from({ length: sessions.length - offset }, (_, i) =>
(i + offset).toString(),
);
const isSessionIdInList = (sessionId: string) =>
sessions.some((session) => session.sessionId === sessionId);
expect(sessionIds.every(isSessionIdInList)).toBe(true);
});
test("Delete all sessions", () => {
let sessions = historyManager.list({});
for (let session of sessions) {
historyManager.delete(session.sessionId);
}
sessions = historyManager.list({});
expect(sessions.length).toBe(0);
});
});

View file

@ -8,9 +8,22 @@ import Types from "../config/types.js";
import { IdeType, SerializedContinueConfig } from "../index.js";
dotenv.config();
const CONTINUE_GLOBAL_DIR =
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
export function getChromiumPath(): string {
return path.join(getContinueUtilsPath(), ".chromium-browser-snapshots");
}
export function getContinueUtilsPath(): string {
const utilsPath = path.join(getContinueGlobalPath(), ".utils");
if (!fs.existsSync(utilsPath)) {
fs.mkdirSync(utilsPath);
}
return utilsPath;
}
export function getContinueGlobalPath(): string {
// This is ~/.continue on mac/linux
const continuePath = CONTINUE_GLOBAL_DIR;

117
core/util/tts.ts Normal file
View file

@ -0,0 +1,117 @@
import os from "node:os";
import { exec, ChildProcess } from "child_process";
import type { IMessenger } from "./messenger";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
// The amount of time before a process is declared
// a zombie after executing .kill()
const ttsKillTimeout: number = 5000;
/**
* Removes code blocks from a message.
*
* Return modified message text.
*/
function removeCodeBlocks(msgText: string): string {
const codeBlockRegex = /```[\s\S]*?```/g;
// Remove code blocks from the message text
const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, "");
return textWithoutCodeBlocks.trim();
}
/**
* Cleans a message text to safely be used in 'exec' context on host.
*
* Return modified message text.
*/
function sanitizeMessageForTTS(message: string): string {
message = removeCodeBlocks(message);
// Remove or replace problematic characters
message = message
.replace(/"/g, "")
.replace(/`/g, "")
.replace(/\$/g, "")
.replace(/\\/g, "")
.replace(/[&|;()<>]/g, "");
message = message.trim().replace(/\s+/g, " ");
return message;
}
export class TTS {
static os: string | undefined = undefined;
static handle: ChildProcess | undefined = undefined;
static messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>;
static async read(message: string) {
message = sanitizeMessageForTTS(message);
try {
// Kill any active TTS processes
await TTS.kill();
} catch (e) {
console.warn("Error killing TTS process: ", e);
return;
}
switch (TTS.os) {
case "darwin":
TTS.handle = exec(`say "${message}"`);
break;
case "win32":
// Replace single quotes on windows
TTS.handle = exec(
`powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('${message.replace(
/'/g,
"''",
)}')"`,
);
break;
case "linux":
TTS.handle = exec(`espeak "${message}"`);
break;
default:
console.log(
"Text-to-speech is not supported on this operating system.",
);
return;
}
TTS.messenger.request("setTTSActive", true);
TTS.handle?.once("exit", () => {
TTS.messenger.request("setTTSActive", false);
});
}
static async kill(): Promise<void> {
return new Promise<void>((resolve, reject) => {
// Only kill a TTS process if it's still running
if (TTS.handle && TTS.handle.exitCode === null) {
// Use a timeout in case of zombie processes
let killTimeout: NodeJS.Timeout = setTimeout(() => {
reject(`Unable to kill TTS process: ${TTS.handle?.pid}`);
}, ttsKillTimeout);
// Resolve our promise once the program has exited
TTS.handle.once("exit", () => {
clearTimeout(killTimeout);
TTS.handle = undefined;
resolve();
});
TTS.handle.kill();
} else {
resolve();
}
});
}
static async setup() {
TTS.os = os.platform();
}
}

View file

@ -5,7 +5,7 @@ Prompt files provide a convenient way to standardize common patterns and share a
## Quick start
:::tip[Prompt library]
To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-example). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts!
To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-examples). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts!
:::
Below is a quick example of setting up a prompt file to write unit tests using Jest.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 858 KiB

View file

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

View file

@ -0,0 +1,28 @@
# AWS Bedrock Custom Imported Models
To setup Bedrock using custom imported models, add the following to your `config.json` file:
```json title="~/.continue/config.json"
{
"models": [
{
"title": "AWS Bedrock deepseek-coder-6.7b-instruct",
"provider": "bedrockimport",
"model": "deepseek-coder-6.7b-instruct",
"modelArn": "arn:aws:bedrock:us-west-2:XXXXX:imported-model/XXXXXX",
"region": "us-west-2",
"profile": "bedrock"
}
]
}
```
Authentication will be through temporary or long-term credentials in
~/.aws/credentials under a configured profile (e.g. "bedrock").
```title="~/.aws/credentials
[bedrock]
aws_access_key_id = abcdefg
aws_secret_access_key = hijklmno
aws_session_token = pqrstuvwxyz # Optional: means short term creds.
```

View file

@ -0,0 +1,42 @@
# Kindo
Kindo offers centralized control over your organization's AI operations, ensuring data protection and compliance with internal policies while supporting various commercial and open-source models. To get started, sign up [here](https://app.kindo.ai/), create your API key on the [API keys page](https://app.kindo.ai/settings/api), and choose a model from the list of supported models in the [plugins tab](https://app.kindo.ai/plugins).
## Config Example
```json title="~/.continue/config.json"
{
"models": [
{
"title": "Claude 3.5 Sonnet",
"provider": "kindo",
"model": "claude-3-5-sonnet-20240620",
"apiKey": "<KINDO_API_KEY>"
}
]
}
```
## Tab Autocomplete Config Example
```json title="~/.continue/config.json"
{
"tabAutocompleteModel": [
{
"title": "WhiteRabbitNeo",
"provider": "kindo",
"model": "/models/WhiteRabbitNeo-33B-DeepSeekCoder",
"apiKey": "<KINDO_API_KEY>"
},
{
"title": "DeepSeek",
"provider": "kindo",
"model": "deepseek-ai/deepseek-coder-33b-instruct",
"apiKey": "<KINDO_API_KEY>"
}
]
}
```
## Security
To update your organization's model access, adjust the controls in [security settings](https://app.kindo.ai/security-settings).

View file

@ -1,15 +1,38 @@
# Watsonx
# IBM watsonx
Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.
watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.
## Setup
To access the Watsonx models, create an instance in the [IBM cloud](https://cloud.ibm.com) which supports watsonx studio. Then to create a project refer [this](https://www.ibm.com/docs/en/watsonx/saas?topic=projects-creating-project).
Accessing watsonx models can be done either through watsonx SaaS on IBM Cloud or using a dedicated watsonx.ai Software instance.
You can set it up in two different ways :
1. **Using API** : Create Your IBM cloud API key by referring [this](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key).
2. **Using Credentials** : Use your Username and Password to authenticate
### watsonx.ai SaaS - IBM Cloud
To get started with watsonx SaaS, visit the [registration page](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx). If you do not have an existing IBM Cloud account, you can sign up for a free trial.
To authenticate to watsonx.ai SaaS with Continue, you will need to create a project and [setup an API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key). Then, in continue:
- Set **watsonx URL** to your watsonx SaaS endpoint, e.g. `https://us-south.ml.cloud.ibm.com` for US South region.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx API Key.
### watsonx.ai Software
To authenticate to your watsonx.ai Software instance with Continue, you can use either `username/password` or `ZenApiKey` method:
1. *Option 1* (Recommended): using `ZenApiKey` authentication:
- Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Zen API Key. To generate it:
1. Log in to the CPD web client.
2. From the toolbar, click your avatar.
3. Click **Profile and settings**.
4. Click **API key** > **Generate new key**.
5. Click **Generate**.
6. Click **Copy** and save your key somewhere safe. You cannot recover this key if you lose it.
7. Generate your ZenApiKey by running the following command in your preferred terminal: `echo "<username>:<apikey>" | base64`, replacing `<username>` with your CPD username and `<apikey>` with the API Key you just created.
2. *Option 2*: using `username/password` authentication:
- Set **watsonx URL** to your watsonx software endpoint, e.g. `https://cpd-watsonx.apps.example.com`.
- Set **watsonx Project ID** to your watsonx project ID.
- Set **watsonx API Key** to your watsonx Username and Password using `username:password` as format.
## Usage
![usage-gif](../Model%20Providers/assets/Watsonx1.gif)
![usage-gif](../Model%20Providers/assets/watsonx1.gif)

View file

@ -46,7 +46,7 @@ You can run a model on your local computer using:
- [TensorRT-LLM](https://github.com/NVIDIA/trt-llm-as-openai-windows?tab=readme-ov-file#examples) (OpenAI compatible server)
- [IPEX-LLM](../reference/Model%20Providers/ipex_llm.md) (Local LLM on Intel GPU)
- [Msty](../reference/Model%20Providers/msty.md)
- [Watsonx](../reference/Model%20Providers/watsonx.md)
- [IBM watsonx](../reference/Model%20Providers/watsonx.md)
- [Nvidia NIMS](../reference/Model%20Providers/openai.md) (OpenAI compatible server)
### Remote
@ -63,6 +63,7 @@ You can deploy a model in your [AWS](https://github.com/continuedev/deploy-os-co
You can access both open-source and commercial LLMs via:
- [OpenRouter](../reference/Model%20Providers/openrouter.md)
- [Kindo](../reference/Model%20Providers/kindo.md)
### Open-source models

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"bedrockimport",
"sagemaker",
"together",
"ollama",
@ -198,6 +199,7 @@
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -216,7 +218,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)."
],
"type": "string"
@ -1231,13 +1233,7 @@
"watsonxApiKey": {
"type": "string"
},
"watsonxZenApiKeyBase64": {
"type": "string"
},
"watsonxUsername": {
"type": "string"
},
"watsonxPassword": {
"watsonxApiVersion": {
"type": "string"
},
"watsonxProjectId": {
@ -2405,6 +2401,11 @@
}
}
},
"readResponseTTS": {
"type": "boolean",
"default": true,
"description": "Automatically read LLM chat responses aloud using system TTS models"
},
"promptPath": {
"type": "string"
},

View file

@ -31,6 +31,7 @@ import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.DumbAware
@ -44,6 +45,8 @@ import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.content.ContentManagerUtil
import com.intellij.util.concurrency.annotations.RequiresEdt
import kotlinx.coroutines.*
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
@ -605,8 +608,10 @@ class IdeProtocolClient (
respond(currentFile)
}
"getPinnedFiles" -> {
val openFiles = visibleFiles()
respond(openFiles)
ApplicationManager.getApplication().invokeLater {
val pinnedFiles = pinnedFiles()
respond(pinnedFiles)
}
}
"insertAtCursor" -> {
val msg = data as Map<String, String>;
@ -940,6 +945,14 @@ class IdeProtocolClient (
return fileEditorManager.openFiles.toList().map { it.path }
}
@RequiresEdt
private fun pinnedFiles(): List<String> {
val fileEditorManager = FileEditorManager.getInstance(project) as? FileEditorManagerImpl ?: return listOf()
val openFiles = fileEditorManager.openFiles.map { it.path }.toList()
val pinnedFiles = fileEditorManager.windows.flatMap { window -> window.files.filter { window.isFilePinned(it) } }.map { it.path }.toSet()
return openFiles.intersect(pinnedFiles).toList()
}
private fun currentFile(): String? {
val fileEditorManager = FileEditorManager.getInstance(project)
val editor = fileEditorManager.selectedTextEditor

View file

@ -47,7 +47,7 @@ fun makeTextArea(): JTextArea {
background = GetTheme().getSecondaryDark()
maximumSize = Dimension(400, Short.MAX_VALUE.toInt())
margin = JBUI.insets(8)
font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
}
textArea.putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
@ -262,7 +262,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = Font("Arial", Font.PLAIN, 11)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
isOpaque = false
isEditable = false
@ -317,7 +317,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
isEditable = true
background = defaultBackground
foreground = Color(128, 128, 128, 200)
font = Font("Arial", Font.PLAIN, 11)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
isOpaque = false
isEditable = false
@ -354,7 +354,7 @@ class CustomPanel(layout: MigLayout, project: Project, modelTitles: List<String>
private val subPanelC: JPanel = JPanel(MigLayout("insets 0, fillx")).apply {
val leftLabel = JLabel("Enter follow-up instructions").apply {
foreground = Color(128, 128, 128, 200)
font = Font("Arial", Font.PLAIN, 11)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
}
val leftButton = CustomButton("${getAltKeyLabel()}⇧N") { onReject() }.apply {
@ -447,7 +447,7 @@ class CustomButton(text: String, onClick: () -> Unit) : JLabel(text, CENTER) {
})
// verticalAlignment = CENTER
font = Font("Arial", Font.PLAIN, 11)
font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, 11)
border = EmptyBorder(2, 4, 2, 4)
}
override fun paintComponent(g: Graphics) {
@ -479,7 +479,7 @@ class CustomTextArea(rows: Int, columns: Int) : JXTextArea("") {
// Draw placeholder
if (text.isEmpty()) {
g.color = Color(128, 128, 128, 255)
g.font = Font("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.font = UIUtil.getFontWithFallback("Arial", Font.PLAIN, MAIN_FONT_SIZE)
g.drawString("Enter instructions to edit highlighted code", 8, 20)
}

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"bedrockimport",
"sagemaker",
"together",
"ollama",
@ -198,6 +199,7 @@
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -216,7 +218,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)."
],
"type": "string"
@ -1231,13 +1233,7 @@
"watsonxApiKey": {
"type": "string"
},
"watsonxZenApiKeyBase64": {
"type": "string"
},
"watsonxUsername": {
"type": "string"
},
"watsonxPassword": {
"watsonxApiVersion": {
"type": "string"
},
"watsonxProjectId": {
@ -2405,6 +2401,11 @@
}
}
},
"readResponseTTS": {
"type": "boolean",
"default": true,
"description": "Automatically read LLM chat responses aloud using system TTS models"
},
"promptPath": {
"type": "string"
},

View file

@ -171,6 +171,7 @@
"anthropic",
"cohere",
"bedrock",
"bedrockimport",
"sagemaker",
"together",
"ollama",
@ -198,6 +199,7 @@
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -216,7 +218,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)."
],
"type": "string"
@ -1231,13 +1233,7 @@
"watsonxApiKey": {
"type": "string"
},
"watsonxZenApiKeyBase64": {
"type": "string"
},
"watsonxUsername": {
"type": "string"
},
"watsonxPassword": {
"watsonxApiVersion": {
"type": "string"
},
"watsonxProjectId": {
@ -2405,6 +2401,11 @@
}
}
},
"readResponseTTS": {
"type": "boolean",
"default": true,
"description": "Automatically read LLM chat responses aloud using system TTS models"
},
"promptPath": {
"type": "string"
},

View file

@ -174,6 +174,7 @@
"anthropic",
"cohere",
"bedrock",
"bedrockimport",
"sagemaker",
"together",
"ollama",
@ -201,6 +202,7 @@
"### Anthropic\nTo get started with Anthropic models, you first need to sign up for the open beta [here](https://claude.ai/login) to obtain an API key.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/anthropicllm)",
"### Cohere\nTo use Cohere, visit the [Cohere dashboard](https://dashboard.cohere.com/api-keys) to create an API key.\n\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/cohere)",
"### Bedrock\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Bedrock Imported Models\nTo get started with Bedrock you need to sign up on AWS [here](https://aws.amazon.com/bedrock/claude/)",
"### Sagemaker\nSagemaker is AWS' machine learning platform.",
"### Together\nTogether is a hosted service that provides extremely fast streaming of open-source language models. To get started with Together:\n1. Obtain an API key from [here](https://together.ai)\n2. Paste below\n3. Select a model preset\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/togetherllm)",
"### Ollama\nTo get started with Ollama, follow these steps:\n1. Download from [ollama.ai](https://ollama.ai/) and open the application\n2. Open a terminal and run `ollama run <MODEL_NAME>`. Example model names are `codellama:7b-instruct` or `llama2:7b-text`. You can find the full list [here](https://ollama.ai/library).\n3. Make sure that the model name used in step 2 is the same as the one in config.json (e.g. `model=\"codellama:7b-instruct\"`)\n4. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://docs.continue.dev/reference/Model%20Providers/ollama)",
@ -219,7 +221,7 @@
"### Deepseek\n Deepseek's API provides the best pricing for their state-of-the-art Deepseek Coder models. To get started, obtain an API key from [their console](https://platform.deepseek.com/api_keys)",
"### Azure OpenAI\n Azure OpenAI lets you securely run OpenAI's models on Azure. To get started, follow the steps [here](https://docs.continue.dev/reference/Model%20Providers/azure)",
"### Msty\nMsty is the simplest way to get started with online or local LLMs on all desktop platforms - Windows, Mac, and Linux. No fussing around, one-click and you are up and running. To get started, follow these steps:\n1. Download from [Msty.app](https://msty.app/), open the application, and click 'Setup Local AI'.\n2. Go to the Local AI Module page and download a model of your choice.\n3. Once the model has finished downloading, you can start asking questions through Continue.\n> [Reference](https://continue.dev/docs/reference/Model%20Providers/Msty)",
"### Watsonx\nWatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### IBM watsonx\nwatsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.",
"### OpenRouter\nOpenRouter offers a single API to access almost any language model. To get started, obtain an API key from [their console](https://openrouter.ai/settings/keys)."
],
"type": "string"
@ -2700,6 +2702,11 @@
}
}
},
"readResponseTTS": {
"type": "boolean",
"default": true,
"description": "Automatically read LLM chat responses aloud using system TTS models"
},
"promptPath": {
"type": "string"
},

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "0.9.197",
"version": "0.9.199",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "0.9.197",
"version": "0.9.199",
"license": "Apache-2.0",
"dependencies": {
"@electron/rebuild": "^3.2.10",
@ -108,7 +108,6 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
@ -133,6 +132,8 @@
"p-limit": "^6.1.0",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.197",
"version": "0.9.199",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"

View file

@ -247,6 +247,7 @@ const exe = os === "win32" ? ".exe" : "";
"../../../core/llm/llamaTokenizer.mjs",
"../../../core/llm/tiktokenWorkerPool.mjs",
];
for (const f of filesToCopy) {
fs.copyFileSync(
path.join(__dirname, f),
@ -460,6 +461,7 @@ const exe = os === "win32" ? ".exe" : "";
"@vscode/ripgrep",
"workerpool",
];
fs.mkdirSync("out/node_modules", { recursive: true });
await Promise.all(
@ -507,8 +509,8 @@ const exe = os === "win32" ? ".exe" : "";
os === "darwin"
? "libonnxruntime.1.14.0.dylib"
: os === "linux"
? "libonnxruntime.so.1.14.0"
: "onnxruntime.dll"
? "libonnxruntime.so.1.14.0"
: "onnxruntime.dll"
}`,
"builtin-themes/dark_modern.json",
@ -547,8 +549,8 @@ const exe = os === "win32" ? ".exe" : "";
target === "win32-arm64"
? "esbuild.exe"
: target === "win32-x64"
? "win32-x64/esbuild.exe"
: `${target}/bin/esbuild`
? "win32-x64/esbuild.exe"
: `${target}/bin/esbuild`
}`,
`out/node_modules/@lancedb/vectordb-${
os === "win32"

View file

@ -74,12 +74,12 @@ export async function getContextProviderQuickPickVal(
const val = await new Promise<string>((resolve) => {
quickPick.onDidAccept(async () => {
const selectedItems = Array.from(quickPick.selectedItems);
const context = await getContextProvidersString(
selectedItems,
config,
ide,
);
resolve(context);
getContextProvidersString(selectedItems, config, ide)
.then(resolve)
.catch((e) => {
console.warn(`Fail to get context providers: ${e}`);
resolve("");
});
});
});

65
gui/package-lock.json generated
View file

@ -101,7 +101,6 @@
"adf-to-md": "^1.1.0",
"async-mutex": "^0.5.0",
"axios": "^1.6.7",
"cheerio": "^1.0.0-rc.12",
"commander": "^12.0.0",
"comment-json": "^4.2.3",
"dbinfoz": "^0.1.4",
@ -126,6 +125,8 @@
"p-limit": "^6.1.0",
"pg": "^8.11.3",
"posthog-node": "^3.6.3",
"puppeteer": "^22.4.0",
"puppeteer-chromium-resolver": "^23.0.0",
"quick-lru": "^7.0.0",
"replicate": "^0.26.0",
"request": "^2.88.2",
@ -6312,40 +6313,6 @@
"node": ">=10"
}
},
"../core/node_modules/cheerio": {
"version": "1.0.0-rc.12",
"license": "MIT",
"dependencies": {
"cheerio-select": "^2.1.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1",
"htmlparser2": "^8.0.1",
"parse5": "^7.0.0",
"parse5-htmlparser2-tree-adapter": "^7.0.0"
},
"engines": {
"node": ">= 6"
},
"funding": {
"url": "https://github.com/cheeriojs/cheerio?sponsor=1"
}
},
"../core/node_modules/cheerio-select": {
"version": "2.1.0",
"license": "BSD-2-Clause",
"dependencies": {
"boolbase": "^1.0.0",
"css-select": "^5.1.0",
"css-what": "^6.1.0",
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1"
},
"funding": {
"url": "https://github.com/sponsors/fb55"
}
},
"../core/node_modules/chownr": {
"version": "2.0.0",
"license": "ISC",
@ -8312,23 +8279,6 @@
"dev": true,
"license": "MIT"
},
"../core/node_modules/htmlparser2": {
"version": "8.0.2",
"funding": [
"https://github.com/fb55/htmlparser2?sponsor=1",
{
"type": "github",
"url": "https://github.com/sponsors/fb55"
}
],
"license": "MIT",
"dependencies": {
"domelementtype": "^2.3.0",
"domhandler": "^5.0.3",
"domutils": "^3.0.1",
"entities": "^4.4.0"
}
},
"../core/node_modules/http-cache-semantics": {
"version": "4.1.1",
"license": "BSD-2-Clause",
@ -10574,17 +10524,6 @@
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"../core/node_modules/parse5-htmlparser2-tree-adapter": {
"version": "7.0.0",
"license": "MIT",
"dependencies": {
"domhandler": "^5.0.2",
"parse5": "^7.0.0"
},
"funding": {
"url": "https://github.com/inikulin/parse5?sponsor=1"
}
},
"../core/node_modules/path-exists": {
"version": "4.0.0",
"license": "MIT",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 215 KiB

After

Width:  |  Height:  |  Size: 35 KiB

View file

@ -174,62 +174,61 @@ function ProfileSwitcher(props: {}) {
return (
<>
{controlServerBetaEnabled &&
profiles.some((profile) => profile.id !== "local") && (
<StyledListbox
value={"GPT-4"}
onChange={(id: string) => {
ideMessenger.request("didChangeSelectedProfile", { id });
}}
>
<div className="relative">
<StyledListboxButton>
<div>{selectedProfile()?.title}</div>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon
className="h-4 w-4 text-gray-400"
aria-hidden="true"
/>
</div>
</StyledListboxButton>
{topDiv &&
ReactDOM.createPortal(
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<StyledListboxOptions>
{profiles.map((option, idx) => (
<ListBoxOption
selected={option.id === selectedProfileId}
option={option}
idx={idx}
key={idx}
showDelete={profiles.length > 1}
/>
))}
<div
className="px-2 py-1"
style={{
color: lightGray,
fontSize: getFontSize() - 2,
}}
>
{profiles.length === 0 ? (
<i>No workspaces found</i>
) : (
"Select workspace"
)}
</div>
</StyledListboxOptions>
</Transition>,
topDiv,
)}
</div>
</StyledListbox>
)}
{controlServerBetaEnabled && session?.account?.id && (
<StyledListbox
value={"GPT-4"}
onChange={(id: string) => {
ideMessenger.request("didChangeSelectedProfile", { id });
}}
>
<div className="relative">
<StyledListboxButton>
<div>{selectedProfile()?.title}</div>
<div className="pointer-events-none flex items-center">
<ChevronUpDownIcon
className="h-4 w-4 text-gray-400"
aria-hidden="true"
/>
</div>
</StyledListboxButton>
{topDiv &&
ReactDOM.createPortal(
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<StyledListboxOptions>
{profiles.map((option, idx) => (
<ListBoxOption
selected={option.id === selectedProfileId}
option={option}
idx={idx}
key={idx}
showDelete={profiles.length > 1}
/>
))}
<div
className="px-2 py-1"
style={{
color: lightGray,
fontSize: getFontSize() - 2,
}}
>
{profiles.length === 0 ? (
<i>No workspaces found</i>
) : (
"Select workspace"
)}
</div>
</StyledListboxOptions>
</Transition>,
topDiv,
)}
</div>
</StyledListbox>
)}
{/* Settings button (either opens config.json or /settings page in control plane) */}
<HeaderButtonWithText

View file

@ -7,8 +7,6 @@ import { Button, HelperText, Input, lightGray } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { setShowDialog } from "../../redux/slices/uiStateSlice";
const DEFAULT_MAX_DEPTH = 3;
function AddDocsDialog() {
const posthog = usePostHog();
const dispatch = useDispatch();
@ -17,9 +15,7 @@ function AddDocsDialog() {
const [title, setTitle] = useState("");
const [startUrl, setStartUrl] = useState("");
const [rootUrl, setRootUrl] = useState("");
const [faviconUrl, setFaviconUrl] = useState("");
const [maxDepth, setMaxDepth] = useState<number | string>("");
const [isOpen, setIsOpen] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
@ -39,18 +35,14 @@ function AddDocsDialog() {
const siteIndexingConfig: SiteIndexingConfig = {
startUrl,
rootUrl,
title,
maxDepth: typeof maxDepth === "string" ? DEFAULT_MAX_DEPTH : maxDepth,
faviconUrl: new URL("/favicon.ico", startUrl).toString(),
faviconUrl,
};
ideMessenger.post("context/addDocs", siteIndexingConfig);
setTitle("");
setStartUrl("");
setRootUrl("");
setMaxDepth("");
setFaviconUrl("");
dispatch(setShowDialog(false));
@ -126,22 +118,6 @@ function AddDocsDialog() {
{isOpen && (
<div className="pt-2">
<label>
Root URL [Optional]
<Input
type="url"
placeholder="Root URL"
value={rootUrl}
onChange={(e) => {
setRootUrl(e.target.value);
}}
/>
<HelperText>
Limits the crawler to pages within the same domain and path as
the Root URL
</HelperText>
</label>
<label>
Favicon URL [Optional]
<Input
@ -157,29 +133,6 @@ function AddDocsDialog() {
`/favicon.ico` path from the Start URL
</HelperText>
</label>
<label>
Max Depth [Optional]
<Input
type="text"
inputMode="numeric"
placeholder={`Default: ${DEFAULT_MAX_DEPTH}`}
title="The maximum search tree depth - where your input url is the root node"
value={maxDepth}
onChange={(e) => {
const value = e.target.value;
if (value == "") {
setMaxDepth("");
} else if (!isNaN(+value) && Number(value) > 0) {
setMaxDepth(Number(value));
}
}}
/>
<HelperText>
Limits the maximum search tree depth of the crawler - 3 by
default
</HelperText>
</label>
</div>
)}

View file

@ -192,7 +192,12 @@ const TooltipStyles = {
};
export function StyledTooltip(props: any) {
return <Tooltip {...props} style={TooltipStyles} />;
const combinedStyles = {
...TooltipStyles,
...props.style, // Merge any additional styles passed via props
};
return <Tooltip {...props} style={combinedStyles} />;
}
export const TextArea = styled.textarea`

View file

@ -56,6 +56,7 @@ import {
getSlashCommandDropdownOptions,
} from "./getSuggestion";
import { ComboBoxItem } from "./types";
import { debounce } from "lodash";
const InputBoxDiv = styled.div`
resize: none;
@ -473,6 +474,31 @@ function TipTapEditor(props: TipTapEditorProps) {
},
});
const [shouldHideToolbar, setShouldHideToolbar] = useState(false);
const debouncedShouldHideToolbar = debounce((value) => {
setShouldHideToolbar(value);
}, 200);
useEffect(() => {
if (editor) {
const handleFocus = () => {
debouncedShouldHideToolbar(false);
}
const handleBlur = () => {
debouncedShouldHideToolbar(true);
};
editor.on('focus', handleFocus);
editor.on('blur', handleBlur);
return () => {
editor.off('focus', handleFocus);
editor.off('blur', handleBlur);
};
}
}, [editor]);
const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
useEffect(() => {
@ -831,7 +857,7 @@ function TipTapEditor(props: TipTapEditorProps) {
/>
<InputToolbar
showNoContext={optionKeyHeld}
hidden={!(editorFocusedRef.current || props.isMainInput)}
hidden={shouldHideToolbar && !props.isMainInput}
onAddContextItem={() => {
if (editor.getText().endsWith("@")) {
} else {

View file

@ -7,6 +7,7 @@ import { setVscMachineId } from "../redux/slices/configSlice";
import {
addContextItemsAtIndex,
setConfig,
setTTSActive,
setInactive,
setSelectedProfileId,
} from "../redux/slices/stateSlice";
@ -81,6 +82,10 @@ function useSetup(dispatch: Dispatch<any>) {
dispatch(setInactive());
});
useWebviewListener("setTTSActive", async (status) => {
dispatch(setTTSActive(status));
});
useWebviewListener("setColors", async (colors) => {
Object.keys(colors).forEach((key) => {
document.body.style.setProperty(key, colors[key]);

View file

@ -1,6 +1,6 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import _ from "lodash";
import React, { useCallback, useContext, useEffect, useState } from "react";
import { useCallback, useContext, useEffect, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
@ -14,7 +14,6 @@ import {
import StyledMarkdownPreview from "../../components/markdown/StyledMarkdownPreview";
import ModelCard from "../../components/modelSelection/ModelCard";
import ModelProviderTag from "../../components/modelSelection/ModelProviderTag";
import Toggle from "../../components/modelSelection/Toggle";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useNavigationListener } from "../../hooks/useNavigationListener";
import { setDefaultModel } from "../../redux/slices/stateSlice";
@ -65,35 +64,12 @@ function ConfigureProvider() {
undefined,
);
// different authentication flow is required for watsonx. This state helps to determine which flow to use for authentication
const [watsonxAuthenticate, setWatsonxAuthenticate] = React.useState(true);
useEffect(() => {
if (providerName) {
setModelInfo(providers[providerName]);
}
}, [providerName]);
const handleContinue = () => {
if (!modelInfo) return;
let formParams: any = {};
for (const d of modelInfo.collectInputFor || []) {
const val = formMethods.watch(d.key);
if (val === "" || val === undefined || val === null) continue;
formParams = updatedObj(formParams, {
[d.key]: d.inputType === "text" ? val : parseFloat(val),
});
}
const model = {
...formParams,
provider: modelInfo.provider,
};
ideMessenger.post("config/addModel", { model });
dispatch(setDefaultModel({ title: model.title, force: true }));
navigate("/");
};
const disableModelCards = useCallback(() => {
return (
modelInfo?.collectInputFor?.some((d) => {
@ -106,17 +82,6 @@ function ConfigureProvider() {
);
}, [modelInfo, formMethods]);
const enablecardsForApikey = useCallback(() => {
return modelInfo?.collectInputFor
?.filter((d) => d.isWatsonxAuthenticatedByApiKey)
.some((d) => !formMethods.watch(d.key));
}, [modelInfo, formMethods]);
const enablecardsForCredentials = useCallback(() => {
return modelInfo?.collectInputFor
?.filter((d) => d.isWatsonxAuthenticatedByCredentials)
.some((d) => !formMethods.watch(d.key));
}, [modelInfo, formMethods]);
return (
<FormProvider {...formMethods}>
<div className="overflow-y-scroll">
@ -161,112 +126,31 @@ function ConfigureProvider() {
/>
<br />
{/* The Watsonx Authentication coukd be done by two different ways
1 ==> Using Api key
2 ==> Using Credentials */}
{providerName === "watsonx" ? (
{(modelInfo?.collectInputFor?.filter((d) => d.required).length || 0) >
0 && (
<>
<div className="col-span-full py-4">
<Toggle
selected={watsonxAuthenticate}
optionOne={"Authenticate by API key"}
optionTwo={"Authenticate by crendentials"}
onClick={() => {
setWatsonxAuthenticate((prev) => !prev);
}}
></Toggle>
</div>
{watsonxAuthenticate ? (
<>
{(modelInfo?.collectInputFor?.filter((d) => d.required)
.length || 0) > 0 && (
<>
<h3 className="mb-2">Enter required parameters</h3>
<h3 className="mb-2">Enter required parameters</h3>
{modelInfo?.collectInputFor
.filter((d) => d.isWatsonxAuthenticatedByApiKey)
.map((d, idx) => (
<div key={idx} className="mb-2">
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
placeholder={d.placeholder}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: false,
})}
/>
</div>
))}
</>
)}
</>
) : (
<>
{(modelInfo?.collectInputFor?.filter((d) => d.required)
.length || 0) > 0 && (
<>
<h3 className="mb-2">Enter required parameters</h3>
{modelInfo?.collectInputFor
.filter((d) => d.isWatsonxAuthenticatedByCredentials)
.map((d, idx) => (
<div key={idx} className="mb-2">
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
placeholder={d.placeholder}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: true,
})}
/>
</div>
))}
</>
)}
</>
)}
</>
) : (
<>
{(modelInfo?.collectInputFor?.filter((d) => d.required).length ||
0) > 0 && (
<>
<h3 className="mb-2">Enter required parameters</h3>
{modelInfo?.collectInputFor
?.filter((d) => d.required)
.map((d, idx) => (
<div key={idx} className="mb-2">
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
placeholder={d.placeholder}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: true,
})}
/>
</div>
))}
</>
)}
{modelInfo?.collectInputFor
?.filter((d) => d.required)
.map((d, idx) => (
<div key={idx} className="mb-2">
<label htmlFor={d.key}>{d.label}</label>
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
step={d.step}
{...formMethods.register(d.key, {
required: true,
})}
/>
</div>
))}
</>
)}
@ -276,9 +160,8 @@ function ConfigureProvider() {
<summary className="mb-2 cursor-pointer">
<b>Advanced (optional)</b>
</summary>
{modelInfo?.collectInputFor?.map((d, idx) => {
// Check the attribute is only for Watson X
if (d.isWatsonxAttribute) return null;
if (d.required) return null;
return (
<div key={idx}>
@ -287,7 +170,7 @@ function ConfigureProvider() {
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
placeholder={d.placeholder}
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
max={d.max}
@ -309,11 +192,7 @@ function ConfigureProvider() {
return (
<ModelCard
key={idx}
disabled={
disableModelCards() &&
enablecardsForApikey() &&
enablecardsForCredentials()
}
disabled={disableModelCards()}
title={pkg.title}
description={pkg.description}
tags={pkg.tags}
@ -321,12 +200,7 @@ function ConfigureProvider() {
icon={pkg.icon || modelInfo.icon}
dimensions={pkg.dimensions}
onClick={(e, dimensionChoices) => {
if (
disableModelCards() &&
enablecardsForApikey() &&
enablecardsForCredentials()
)
return;
if (disableModelCards()) return;
let formParams: any = {};
for (const d of modelInfo.collectInputFor || []) {
const val = formMethods.watch(d.key);

View file

@ -722,7 +722,7 @@ export const models: { [key: string]: ModelPackage } = {
isOpenSource: false,
},
graniteChat: {
title: "Watsonx - Granite Chat",
title: "watsonx - Granite Chat",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
@ -735,38 +735,38 @@ export const models: { [key: string]: ModelPackage } = {
isOpenSource: false,
},
graniteCode: {
title: "Watsonx - Granite Code",
title: "watsonx - Granite Code 20b",
description:
"The Granite model series is a family of IBM-trained, dense decoder-only models, which are particularly well-suited for generative tasks.",
params: {
model: "ibm/granite-20b-code-instruct",
contextLength: 20_000,
title: "Granite Code"
title: "watsonx - Granite Code 20b"
},
providerOptions: ["watsonx"],
icon: "Watsonx.png",
icon: "watsonx.png",
isOpenSource: false,
},
MistralLarge: {
title: "Watsonx - Mistral",
title: "watsonx - Mistral Large",
description:
"Mistral Large, the most advanced Large Language Model (LLM) developed by Mistral Al, is an exceptionally powerful model.",
params: {
model: "mistralai/mistral-large",
contextLength: 20_000,
title: "Watsonx - Mistral",
title: "watsonx - Mistral Large",
},
providerOptions: ["watsonx"],
icon: "mistral.png",
isOpenSource: false,
},
MetaLlama3: {
title: "Meta Llama 3",
title: "watsonx - Llama 3.1",
description:
"Llama 3 is an auto-regressive language model that uses an optimized transformer architecture.",
params: {
title: "Meta-llama3-8b",
model: "meta-llama/llama-3-8b-instruct",
title: "watsonx - Llama 3.1 8b",
model: "meta-llama/llama-3-1-8b-instruct",
contextLength: 20_000,
},
icon: "meta.png",
@ -776,12 +776,12 @@ export const models: { [key: string]: ModelPackage } = {
description: "The number of parameters in the model",
options: {
"8b": {
model: "meta-llama/llama-3-8b-instruct",
title: "Meta-llama3-8b",
model: "meta-llama/llama-3-1-8b-instruct",
title: "watsonx - Llama 3.1 8b",
},
"70b": {
model: "meta-llama/llama-3-70b-instruct",
title: "Meta-llama3-70b",
model: "meta-llama/llama-3-1-70b-instruct",
title: "watsonx - Llama 3.1 70b",
},
},
},

View file

@ -19,11 +19,6 @@ export interface InputDescriptor {
required?: boolean;
description?: string;
[key: string]: any;
// the following are used only for Watsonx provider
// these attributes are used to determine whether the input is used in Api Authentication or Credentials section
isWatsonxAuthenticatedByApiKey?: boolean;
isWatsonxAuthenticatedByCredentials?: boolean;
isWatsonxAttribute?: boolean;
}
export interface ProviderInfo {
@ -481,69 +476,57 @@ After it's up and running, you can start using Continue.`,
],
},
watsonx: {
title: "Watsonx",
title: "IBM watsonx",
provider: "watsonx",
refPage: "watsonX",
description:
"Explore foundation models from IBM and other third-parties depending on your use case.",
longDescription: `Watsonx, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.`,
longDescription: `**watsonx**, developed by IBM, offers a variety of pre-trained AI foundation models that can be used for natural language processing (NLP), computer vision, and speech recognition tasks.
To get started, [register](https://dataplatform.cloud.ibm.com/registration/stepone?context=wx) on watsonx SaaS, create your first project and setup an [API key](https://www.ibm.com/docs/en/mas-cd/continuous-delivery?topic=cli-creating-your-cloud-api-key).`,
collectInputFor: [
{
inputType: "text",
key: "watsonxUrl",
label: "Watsonx URL",
placeholder: "http://<region>.dataplatform.cloud.ibm.com",
required: true,
isWatsonxAuthenticatedByApiKey: true,
isWatsonxAuthenticatedByCredentials: true,
},
{
inputType: "text",
key: "watsonxApiKey",
label: "Watsonx API Key",
placeholder: "Enter your API key",
required: true,
isWatsonxAuthenticatedByApiKey: true,
label: "watsonx URL",
placeholder: "e.g. http://us-south.dataplatform.cloud.ibm.com",
required: true
},
{
inputType: "text",
key: "watsonxProjectId",
label: "Watsonx Project Id",
placeholder: "Enter your project Id",
required: true,
isWatsonxAuthenticatedByApiKey: true,
isWatsonxAuthenticatedByCredentials: true,
label: "watsonx Project ID",
placeholder: "Enter your project ID",
required: true
},
{
inputType: "text",
key: "watsonxUsername",
label: "Watsonx Username",
placeholder: "Enter your Username",
required: true,
isWatsonxAuthenticatedByCredentials: true,
key: "watsonxCreds",
label: "watsonx API key",
placeholder: "Enter your API key (SaaS) or ZenApiKey (Software)",
required: true
},
{
inputType: "text",
key: "watsonxPassword",
label: "Watsonx Password",
placeholder: "Enter your password",
required: true,
isWatsonxAuthenticatedByCredentials: true,
},
{
inputType: "text",
key: "title",
label: "Model name",
placeholder: "Granite 13B Chat v2",
isWatsonxAttribute: true,
},
{
inputType: "text",
key: "model",
label: "Model Id",
placeholder: "ibm/granite-13b-chat-v2",
isWatsonxAttribute: true,
key: "watsonxApiVersion",
label: "watsonx API version",
placeholder: "Enter the API Version",
defaultValue: "2023-05-29"
},
// {
// inputType: "text",
// key: "title",
// label: "Model name",
// placeholder: "Granite 13B Chat v2",
// isWatsonxAttribute: true,
// },
// {
// inputType: "text",
// key: "model",
// label: "Model Id",
// placeholder: "ibm/granite-13b-chat-v2",
// isWatsonxAttribute: true,
// },
{
inputType: "text",
key: "watsonxStopToken",
@ -553,7 +536,7 @@ After it's up and running, you can start using Continue.`,
...completionParamsInputsConfigs,
],
icon: "Watsonx.png",
icon: "watsonx.png",
tags: [ModelProviderTags.RequiresApiKey],
packages: [
models.graniteCode,

View file

@ -163,6 +163,7 @@ function GUI() {
const defaultModel = useSelector(defaultModelSelector);
const ttsActive = useSelector((state: RootState) => state.state.ttsActive);
const active = useSelector((state: RootState) => state.state.active);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
@ -517,6 +518,16 @@ function GUI() {
trackVisibility={active}
/>
</TopGuiDiv>
{ttsActive && (
<StopButton
className="mt-2 mb-4"
onClick={() => {
ideMessenger.post("tts/kill", undefined);
}}
>
■ Stop TTS
</StopButton>
)}
{active && (
<StopButton
className="mt-auto mb-4"

View file

@ -23,13 +23,20 @@ import useHistory from "../hooks/useHistory";
import { useNavigationListener } from "../hooks/useNavigationListener";
import { getFontSize } from "../util";
const SearchBarContainer = styled.div`
display: flex;
max-width: 500px;
padding: 0 8px 0 8px;
margin: 0 auto;
align-items: center;
justify-content: center;
`;
const SearchBar = styled.input`
padding: 4px 8px;
border-radius: ${defaultBorderRadius};
border: 0.5px solid #888;
outline: none;
width: 90vw;
max-width: 500px;
margin: 8px auto;
display: block;
background-color: ${vscInputBackground};
@ -60,14 +67,15 @@ const parseDate = (date: string): Date => {
};
const SectionHeader = styled.tr`
display: flex;
user-select: none;
padding: 4px;
padding-left: 16px;
padding-right: 16px;
background-color: ${vscInputBackground};
width: 100%;
font-weight: bold;
text-align: center;
align-items: center;
justify-content: center;
margin: 0;
position: sticky;
height: 1.5em;
@ -150,16 +158,19 @@ function TableRow({
</div>
<div style={{ color: "#9ca3af" }}>
{date.toLocaleString("en-US", {
year: "2-digit",
month: "2-digit",
day: "2-digit",
hour: "numeric",
minute: "2-digit",
hour12: true,
})}
{" | "}
{lastPartOfPath(session.workspaceDirectory || "")}
{!hovered && (
<span className="inline-block float-right">
{date.toLocaleString("en-US", {
year: "2-digit",
month: "2-digit",
day: "2-digit",
hour: "numeric",
minute: "2-digit",
hour12: true,
})}
</span>
)}
</div>
</TdDiv>
@ -214,7 +225,8 @@ function History() {
);
};
const [filteringByWorkspace, setFilteringByWorkspace] = useState(false);
const searchInputRef = React.useRef<HTMLInputElement>(null);
const stickyHistoryHeaderRef = React.useRef<HTMLDivElement>(null);
const [headerHeight, setHeaderHeight] = useState(0);
@ -247,8 +259,12 @@ function History() {
}, []);
useEffect(() => {
// When searchTerm is empty only show sessions from the current workspace
let filteringByWorkspace = searchTerm === "";
// When the searchTerm is wildcard (asterisk) then show ALL sessions, otherwise use minisearch to search for user input
const sessionIds = minisearch
.search(searchTerm, {
.search(searchTerm === "*" ? "" : searchTerm, {
fuzzy: 0.1,
})
.map((result) => result.id);
@ -267,7 +283,11 @@ function History() {
})
// Filter by search term
.filter((session) => {
return searchTerm === "" || sessionIds.includes(session.sessionId);
return (
searchTerm === "*" ||
filteringByWorkspace ||
sessionIds.includes(session.sessionId)
);
})
.sort(
(a, b) =>
@ -275,7 +295,7 @@ function History() {
parseDate(a.dateCreated).getTime(),
),
);
}, [filteringByWorkspace, sessions, searchTerm, minisearch]);
}, [sessions, searchTerm, minisearch]);
useEffect(() => {
setHeaderHeight(stickyHistoryHeaderRef.current?.clientHeight || 100);
@ -319,11 +339,34 @@ function History() {
</div>
<div>
<SearchBar
placeholder="Search past sessions"
type="text"
onChange={(e) => setSearchTerm(e.target.value)}
/>
<SearchBarContainer className="space-x-2">
<SearchBar
className="flex-1 w-full"
ref={searchInputRef}
placeholder="Search past sessions"
type="text"
onChange={(e) => setSearchTerm(e.target.value)}
/>
<span
className="block text-center px-2 py-1.5 rounded-md w-12 mx-1 my-2 select-none cursor-pointer"
style={{
fontSize: "11px",
backgroundColor:
searchTerm !== "" ? vscInputBackground : vscBadgeBackground,
}}
onClick={() => {
if (searchInputRef.current.value === "") {
searchInputRef.current.value = "*";
setSearchTerm("*");
} else {
searchInputRef.current.value = "";
setSearchTerm("");
}
}}
>
{searchTerm === "" ? "Show All" : "Clear"}
</span>
</SearchBarContainer>
{filteredAndSortedSessions.length === 0 && (
<div className="text-center m-4">

View file

@ -98,6 +98,7 @@ fn bubble_sort<T: Ord>(values: &mut[T]) {
type State = {
history: ChatHistory;
contextItems: ContextItemWithId[];
ttsActive: boolean;
active: boolean;
config: BrowserSerializedContinueConfig;
title: string;
@ -110,6 +111,7 @@ type State = {
const initialState: State = {
history: [],
contextItems: [],
ttsActive: false,
active: false,
config: {
slashCommands: [
@ -168,6 +170,9 @@ export const stateSlice = createSlice({
? lastHistory.promptLogs.concat(payload)
: payload;
},
setTTSActive: (state, { payload }: PayloadAction<boolean>) => {
state.ttsActive = payload;
},
setActive: (state) => {
state.active = true;
},
@ -510,6 +515,7 @@ export const {
setDefaultModel,
setConfig,
addPromptCompletionPair,
setTTSActive,
setActive,
setEditingContextItemAtIndex,
initNewActiveMessage,

View file

@ -7,6 +7,8 @@ set -e
echo "Installing Core extension dependencies..."
pushd core
## This flag is set because we pull down Chromium at runtime
export PUPPETEER_SKIP_DOWNLOAD='true'
npm install
npm link