Merge branch 'dev' into nate/cmd-i-sidebar-v2

This commit is contained in:
Nate 2024-11-02 00:20:21 -07:00
commit c353271a36
14 changed files with 549 additions and 7126 deletions

11
.vscode/tasks.json vendored
View file

@ -5,11 +5,11 @@
{
"label": "vscode-extension:build",
"dependsOn": [
// To detect compile errors and output extensions.js
// To detect compile errors
"vscode-extension:tsc",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// To bundle the code the same way we do for publishing
// // To bundle the code the same way we do for publishing
"vscode-extension:esbuild",
// Start the React app that is used in the extension
"gui:dev"
@ -21,10 +21,7 @@
},
{
"label": "vscode-extension:esbuild",
"dependsOn": [
"vscode-extension:continue-ui:build",
"vscode-extension:tsc"
],
"dependsOn": ["vscode-extension:continue-ui:build"],
"type": "npm",
"script": "esbuild-watch",
"path": "extensions/vscode",
@ -44,7 +41,7 @@
"background": {
"activeOnStart": true,
"beginsPattern": ">",
"endsPattern": ">"
"endsPattern": "node scripts/esbuild.js --sourcemap --watch"
}
}
]

View file

@ -156,12 +156,17 @@ export class JiraClient {
},
);
if (response.status !== 200) {
if (response.status === 500) {
const text = await response.text();
console.warn(
"Unable to get jira tickets. Response code from API is",
response.status,
"Unable to get Jira tickets. You may need to set 'apiVersion': 2 in your config.json. See full documentation here: https://docs.continue.dev/customize/context-providers#jira-datacenter-support\n\n",
text,
);
return Promise.resolve([]);
} else if (response.status !== 200) {
const text = await response.text();
console.warn("Unable to get Jira tickets: ", text);
return Promise.resolve([]);
}
const data = (await response.json()) as any;

View file

@ -1,18 +1,11 @@
import { Octokit } from "@octokit/rest";
import * as cheerio from "cheerio";
import * as fs from "fs";
import fetch from "node-fetch";
import { URL } from "node:url";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../..";
import CheerioCrawler from "./crawlers/CheerioCrawler";
import { ChromiumCrawler, ChromiumInstaller } from "./crawlers/ChromiumCrawler";
import { DefaultCrawler } from "./crawlers/DefaultCrawler";
import GitHubCrawler from "./crawlers/GitHubCrawler";
export type PageData = {
url: string;
@ -45,7 +38,17 @@ class DocsCrawler {
): AsyncGenerator<PageData> {
if (startUrl.host === this.GITHUB_HOST) {
yield* new GitHubCrawler(startUrl).crawl();
} else if (this.shouldUseChromium()) {
return;
}
try {
yield* new DefaultCrawler(startUrl).crawl();
return;
} catch (e) {
console.error("Default crawler failed, trying backup: ", e);
}
if (this.shouldUseChromium()) {
yield* new ChromiumCrawler(startUrl, maxRequestsPerCrawl).crawl();
} else {
let didCrawlSinglePage = false;
@ -83,471 +86,6 @@ class DocsCrawler {
}
}
class GitHubCrawler {
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
private octokit = new Octokit({ auth: undefined });
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${
(this.constructor as any).name
}] 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 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",
},
);
return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
}
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;
}
}
}
class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`[${
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
this.getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
);
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
}
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });
}
}
}
}
} catch (e) {
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
private async 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(
`[${
(this.constructor as any).name
}] Maximum redirect reached for: ${location.toString()}`,
);
return { html: "", links: [] };
}
console.error(error);
return { html: "", links: [] };
}
if (!response.ok) {
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((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, location);
if (parsedUrl.hostname === baseUrl.hostname) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return { html, links };
}
private splitUrl(url: URL) {
const baseUrl = new URL('/', url).href;
const basePath = url.pathname;
return { baseUrl, basePath };
}
}
class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private curCrawlCount = 0;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumInstaller.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);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*
* https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
this.curCrawlCount++;
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
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));
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;
}
}
class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
await this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}
export default DocsCrawler;
export {
CheerioCrawler,

View file

@ -0,0 +1,146 @@
import * as cheerio from "cheerio";
import { URL } from "node:url";
import { PageData } from "../DocsCrawler";
export default class CheerioCrawler {
private readonly IGNORE_PATHS_ENDING_IN = [
"favicon.ico",
"robots.txt",
".rst.txt",
"genindex",
"py-modindex",
"search.html",
"search",
"genindex.html",
"changelog",
"changelog.html",
];
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
async *crawl(): AsyncGenerator<PageData> {
yield* this.crawlPage(this.startUrl);
}
private async *crawlPage(
url: URL,
maxDepth: number = 3,
): AsyncGenerator<PageData> {
console.log(
`[${
(this.constructor as any).name
}] Starting crawl from: ${url} - Max Depth: ${maxDepth}`,
);
const { baseUrl, basePath } = this.splitUrl(url);
let paths: { path: string; depth: number }[] = [
{ path: basePath, depth: 0 },
];
let index = 0;
while (index < paths.length) {
const batch = paths.slice(index, index + 50);
try {
const promises = batch.map(({ path, depth }) =>
this.getLinksFromUrl(baseUrl, path).then((links) => ({
links,
path,
depth,
})),
);
const results = await Promise.all(promises);
for (const {
links: { html, links: linksArray },
path,
depth,
} of results) {
if (html !== "" && depth <= maxDepth) {
yield { url: url.toString(), path, content: html };
}
if (depth < maxDepth) {
for (let link of linksArray) {
if (!paths.some((p) => p.path === link)) {
paths.push({ path: link, depth: depth + 1 });
}
}
}
}
} catch (e) {
console.debug("Error while crawling page: ", e);
}
index += batch.length;
}
console.log("Crawl completed");
}
private async 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(
`[${
(this.constructor as any).name
}] Maximum redirect reached for: ${location.toString()}`,
);
return { html: "", links: [] };
}
console.error(error);
return { html: "", links: [] };
}
if (!response.ok) {
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((_: any, element: any) => {
const href = $(element).attr("href");
if (!href) {
return;
}
const parsedUrl = new URL(href, location);
if (parsedUrl.hostname === baseUrl.hostname) {
links.push(parsedUrl.pathname);
}
});
links = [...new Set(links)].filter((link) => {
return (
!link.includes("#") &&
!this.IGNORE_PATHS_ENDING_IN.some((ending) => link.endsWith(ending))
);
});
return { html, links };
}
private splitUrl(url: URL) {
const baseUrl = new URL("/", url).href;
const basePath = url.pathname;
return { baseUrl, basePath };
}
}

View file

@ -0,0 +1,260 @@
import * as fs from "fs";
import { URL } from "node:url";
import { Handler, HTTPResponse, Page } from "puppeteer";
import {
editConfigJson,
getChromiumPath,
getContinueUtilsPath,
} from "../../../util/paths";
// @ts-ignore
// @prettier-ignore
import PCR from "puppeteer-chromium-resolver";
import { ContinueConfig, IDE } from "../../..";
import { PageData } from "../DocsCrawler";
export class ChromiumCrawler {
private readonly LINK_GROUP_SIZE = 2;
private curCrawlCount = 0;
constructor(
private readonly startUrl: URL,
private readonly maxRequestsPerCrawl: number,
) {}
static setUseChromiumForDocsCrawling(useChromiumForDocsCrawling: boolean) {
editConfigJson((config) => ({
...config,
experimental: {
...config.experimental,
useChromiumForDocsCrawling,
},
}));
}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${(this.constructor as any).name}] Crawling site: ${this.startUrl}`,
);
const stats = await PCR(ChromiumInstaller.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);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
} finally {
await browser.close();
}
}
/**
* We need to handle redirects manually, otherwise there are race conditions.
*
* https://github.com/puppeteer/puppeteer/issues/3323#issuecomment-2332333573
*/
private async gotoPageAndHandleRedirects(page: Page, url: string) {
const MAX_PAGE_WAIT_MS = 5000;
await page.goto(url, {
timeout: 0,
waitUntil: "networkidle2",
});
let responseEventOccurred = false;
const responseHandler: Handler<HTTPResponse> = (event) =>
(responseEventOccurred = true);
const responseWatcher = new Promise<void>(function (resolve, reject) {
setTimeout(() => {
if (!responseEventOccurred) {
resolve();
} else {
setTimeout(() => resolve(), MAX_PAGE_WAIT_MS);
}
}, 500);
});
page.on("response", responseHandler);
await Promise.race([responseWatcher, page.waitForNavigation()]);
}
private async *crawlSitePages(
page: Page,
curUrl: URL,
visitedLinks: Set<string> = new Set(),
): AsyncGenerator<PageData> {
const urlStr = curUrl.toString();
if (visitedLinks.has(urlStr)) {
return;
}
await this.gotoPageAndHandleRedirects(page, urlStr);
const htmlContent = await page.content();
const linkGroups = await this.getLinkGroupsFromPage(page, curUrl);
this.curCrawlCount++;
visitedLinks.add(urlStr);
yield {
path: curUrl.pathname,
url: urlStr,
content: htmlContent,
};
for (const linkGroup of linkGroups) {
let enqueuedLinkCount = this.curCrawlCount;
for (const link of linkGroup) {
enqueuedLinkCount++;
console.log({ enqueuedLinkCount, url: this.startUrl.toString() });
if (enqueuedLinkCount <= this.maxRequestsPerCrawl) {
yield* this.crawlSitePages(page, new URL(link), visitedLinks);
}
}
}
}
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));
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;
}
}
export class ChromiumInstaller {
static PCR_CONFIG = { downloadPath: getContinueUtilsPath() };
constructor(
private readonly ide: IDE,
private readonly config: ContinueConfig,
) {
if (this.shouldInstallOnStartup()) {
console.log("Installing Chromium");
void this.install();
}
}
isInstalled() {
return fs.existsSync(getChromiumPath());
}
shouldInstallOnStartup() {
return (
!this.isInstalled() &&
this.config.experimental?.useChromiumForDocsCrawling
);
}
shouldProposeUseChromiumOnCrawlFailure() {
const { experimental } = this.config;
return (
experimental?.useChromiumForDocsCrawling === undefined ||
experimental.useChromiumForDocsCrawling
);
}
async proposeAndAttemptInstall(site: string) {
const userAcceptedInstall = await this.proposeInstall(site);
if (userAcceptedInstall) {
const didInstall = await this.install();
return didInstall;
}
}
async install() {
try {
await PCR(ChromiumInstaller.PCR_CONFIG);
ChromiumCrawler.setUseChromiumForDocsCrawling(true);
return true;
} catch (error) {
console.debug("Error installing Chromium : ", error);
console.debug(
"Setting 'useChromiumForDocsCrawling' to 'false' in config.json",
);
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
await this.ide.showToast("error", "Failed to install Chromium");
return false;
}
}
private async proposeInstall(site: string) {
const msg =
`Unable to crawl documentation site: ${site}\n` +
"We recommend installing Chromium. " +
"Download progress can be viewed in the developer console.";
const actionMsg = "Install Chromium";
const res = await this.ide.showToast("warning", msg, actionMsg);
return res === actionMsg;
}
}

View file

@ -0,0 +1,27 @@
import { URL } from "node:url";
import { getHeaders } from "../../../continueServer/stubs/headers";
import { TRIAL_PROXY_URL } from "../../../control-plane/client";
import { PageData } from "../DocsCrawler";
export class DefaultCrawler {
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
const resp = await fetch(new URL("crawl", TRIAL_PROXY_URL).toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
...(await getHeaders()),
},
body: JSON.stringify({ startUrl: this.startUrl.toString() }),
});
if (!resp.ok) {
const text = await resp.text();
throw new Error(`Failed to crawl site: ${text}`);
}
const json = (await resp.json()) as PageData[];
for (const pageData of json) {
yield pageData;
}
}
}

View file

@ -0,0 +1,80 @@
import { Octokit } from "@octokit/rest";
import { URL } from "node:url";
import { PageData } from "../DocsCrawler";
class GitHubCrawler {
private readonly markdownRegex = new RegExp(/\.(md|mdx)$/);
private octokit = new Octokit({ auth: undefined });
constructor(private readonly startUrl: URL) {}
async *crawl(): AsyncGenerator<PageData> {
console.debug(
`[${
(this.constructor as any).name
}] 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 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",
},
);
return tree.data.tree
.filter(
(file: any) =>
file.type === "blob" && this.markdownRegex.test(file.path ?? ""),
)
.map((file: any) => file.path);
}
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;
}
}
}
export default GitHubCrawler;

View file

@ -1,2 +1,4 @@
src/main/resources/webview
src/main/resources/bin
src/main/resources/bin
src/main/resources/config_schema.json
src/main/resources/continue_rc_schema.json

File diff suppressed because it is too large Load diff

View file

@ -14,4 +14,6 @@ gui/*
!gui/onigasm.wasm
.devcontainer
.github
.github
continue_rc_schema.json

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

@ -2,17 +2,12 @@ import type { ILLM } from "core";
import { ConfigHandler } from "core/config/ConfigHandler";
import Ollama from "core/llm/llms/Ollama";
import { GlobalContext } from "core/util/GlobalContext";
import * as vscode from "vscode";
export class TabAutocompleteModel {
private _llm: ILLM | undefined;
private defaultTag = "starcoder2:3b";
private defaultTagName = "Starcoder2 3b";
private globalContext: GlobalContext = new GlobalContext();
private shownOllamaWarning = false;
private shownDeepseekWarning = false;
constructor(private configHandler: ConfigHandler) {}
clearLlm() {
@ -27,49 +22,9 @@ export class TabAutocompleteModel {
try {
const models = await llm.listModels();
if (!models.includes(this.defaultTag)) {
if (!this.shownDeepseekWarning) {
vscode.window
.showWarningMessage(
`Your local Ollama instance doesn't yet have ${this.defaultTagName}. To download this model, run \`ollama run ${this.defaultTag}\` (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs`,
"Documentation",
"Copy Command",
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (value === "Copy Command") {
vscode.env.clipboard.writeText(`ollama run ${this.defaultTag}`);
}
});
this.shownDeepseekWarning = true;
}
return undefined;
}
} catch (e) {
if (!this.shownOllamaWarning) {
vscode.window
.showWarningMessage(
"Continue failed to connect to Ollama, which is used by default for tab-autocomplete. If you haven't downloaded it yet, you can do so at https://ollama.ai (recommended). If you'd like to use a custom model for tab autocomplete, learn more in the docs",
"Download Ollama",
"Documentation",
)
.then((value) => {
if (value === "Documentation") {
vscode.env.openExternal(
vscode.Uri.parse(
"https://docs.continue.dev/features/tab-autocomplete",
),
);
} else if (value === "Download Ollama") {
vscode.env.openExternal(vscode.Uri.parse("https://ollama.ai"));
}
});
this.shownOllamaWarning = true;
}
return undefined;
}