Elffuss BraidHub

kikocis/continue public

99fe51849b68 · 40.6 KiBRawPermalink
1import { ConfigResult } from "@continuedev/config-yaml";
2import { open, type Database } from "sqlite";
3import sqlite3 from "sqlite3";
4
5import {
6 Chunk,
7 ContinueConfig,
8 DocsIndexingDetails,
9 IDE,
10 IdeInfo,
11 ILLM,
12 IndexingStatus,
13 SiteIndexingConfig,
14} from "../..";
15import { ConfigHandler } from "../../config/ConfigHandler";
16import { isSupportedLanceDbCpuTargetForLinux } from "../../config/util";
17import DocsContextProvider from "../../context/providers/DocsContextProvider";
18import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
19import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
20import { IMessenger } from "../../protocol/messenger";
21import { fetchFavicon } from "../../util/fetchFavicon";
22import { GlobalContext } from "../../util/GlobalContext";
23import {
24 editConfigFile,
25 getDocsSqlitePath,
26 getLanceDbPath,
27} from "../../util/paths";
28import { Telemetry } from "../../util/posthog";
29
30import {
31 ArticleWithChunks,
32 htmlPageToArticleWithChunks,
33 markdownPageToArticleWithChunks,
34} from "./article";
35import DocsCrawler, { DocsCrawlerType, PageData } from "./crawlers/DocsCrawler";
36import { runLanceMigrations, runSqliteMigrations } from "./migrations";
37
38import type * as LanceType from "vectordb";
39import { LLMError } from "../../llm";
40import { DocsCache, SiteIndexingResults } from "./DocsCache";
41
42// Purposefully lowercase because lancedb converts
43export interface LanceDbDocsRow {
44 title: string;
45 starturl: string;
46 // Chunk
47 content: string;
48 path: string;
49 startline: number;
50 endline: number;
51 vector: number[];
52 [key: string]: any;
53}
54
55export interface SqliteDocsRow {
56 title: string;
57 startUrl: string;
58 favicon: string;
59}
60
61export type AddParams = {
62 siteIndexingConfig: SiteIndexingConfig;
63 chunks: Chunk[];
64 embeddings: number[][];
65 favicon?: string;
66};
67
68const markFailedInGlobalContext = (siteIndexingConfig: SiteIndexingConfig) => {
69 const globalContext = new GlobalContext();
70 const failedDocs = globalContext.get("failedDocs") ?? [];
71 const newFailedDocs = failedDocs.filter(
72 (d) => !docConfigsAreEqual(siteIndexingConfig, d),
73 );
74 newFailedDocs.push(siteIndexingConfig);
75 globalContext.update("failedDocs", newFailedDocs);
76};
77
78const removeFromFailedGlobalContext = (
79 siteIndexingConfig: SiteIndexingConfig,
80) => {
81 const globalContext = new GlobalContext();
82 const failedDocs = globalContext.get("failedDocs") ?? [];
83 const newFailedDocs = failedDocs.filter(
84 (d) => !docConfigsAreEqual(siteIndexingConfig, d),
85 );
86 globalContext.update("failedDocs", newFailedDocs);
87};
88
89const hasIndexingFailed = (siteIndexingConfig: SiteIndexingConfig) => {
90 const globalContext = new GlobalContext();
91 const failedDocs = globalContext.get("failedDocs") ?? [];
92 return failedDocs.find((d) => docConfigsAreEqual(siteIndexingConfig, d));
93};
94
95export function embedModelsAreEqual(
96 llm1: ILLM | null | undefined,
97 llm2: ILLM | null | undefined,
98): boolean {
99 return (
100 llm1?.underlyingProviderName === llm2?.underlyingProviderName &&
101 llm1?.title === llm2?.title &&
102 llm1?.maxEmbeddingChunkSize === llm2?.maxEmbeddingChunkSize
103 );
104}
105
106const docConfigsAreEqual = (
107 siteConfig1: SiteIndexingConfig,
108 siteConfig2: SiteIndexingConfig,
109) => {
110 return (
111 siteConfig1.faviconUrl === siteConfig2.faviconUrl &&
112 siteConfig1.title === siteConfig2.title &&
113 docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2)
114 );
115};
116
117const docConfigsAreEqualExceptTitleAndFavicon = (
118 siteConfig1: SiteIndexingConfig,
119 siteConfig2: SiteIndexingConfig,
120) => {
121 return (
122 siteConfig1.startUrl === siteConfig2.startUrl &&
123 siteConfig1.maxDepth === siteConfig2.maxDepth &&
124 siteConfig1.useLocalCrawling === siteConfig2.useLocalCrawling
125 );
126};
127
128const siteIndexingConfigsAreEqual = (
129 siteConfig1: SiteIndexingConfig,
130 siteConfig2: SiteIndexingConfig,
131 contConfig1: ContinueConfig | undefined,
132 contConfig2: ContinueConfig,
133) => {
134 return (
135 docConfigsAreEqual(siteConfig1, siteConfig2) &&
136 embedModelsAreEqual(
137 contConfig1?.selectedModelByRole.embed,
138 contConfig2.selectedModelByRole.embed,
139 )
140 );
141};
142
143const siteIndexingConfigsAreEqualExceptTitleAndFavicon = (
144 siteConfig1: SiteIndexingConfig,
145 siteConfig2: SiteIndexingConfig,
146 contConfig1: ContinueConfig | undefined,
147 contConfig2: ContinueConfig,
148) => {
149 return (
150 docConfigsAreEqualExceptTitleAndFavicon(siteConfig1, siteConfig2) &&
151 embedModelsAreEqual(
152 contConfig1?.selectedModelByRole.embed,
153 contConfig2.selectedModelByRole.embed,
154 )
155 );
156};
157
158/*
159 General process:
160 - On config update:
161 - Reindex ALL docs if embeddings provider has changed
162 - Otherwise, reindex docs with CHANGED URL/DEPTH
163 - And update docs with CHANGED TITLE/FAVICON
164 - Also, messages to core can trigger:
165 - delete
166 - reindex all
167 - add/index one
168*/
169export default class DocsService {
170 private static lance: typeof LanceType | null = null;
171 static lanceTableName = "docs";
172 static sqlitebTableName = "docs";
173
174 static defaultEmbeddingsProvider = new TransformersJsEmbeddingsProvider();
175
176 public isInitialized: Promise<void>;
177 public isSyncing: boolean = false;
178
179 private docsIndexingQueue = new Set<string>();
180 private lanceTableNamesSet = new Set<string>();
181
182 private config!: ContinueConfig;
183 private sqliteDb?: Database;
184
185 private ideInfoPromise: Promise<IdeInfo>;
186 private githubToken?: string;
187
188 constructor(
189 configHandler: ConfigHandler,
190 private readonly ide: IDE,
191 private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
192 ) {
193 this.ideInfoPromise = this.ide.getIdeInfo();
194 this.isInitialized = this.init(configHandler);
195 }
196
197 setGithubToken(token: string) {
198 this.githubToken = token;
199 }
200
201 private async initLanceDb() {
202 if (!isSupportedLanceDbCpuTargetForLinux()) {
203 return null;
204 }
205
206 try {
207 if (!DocsService.lance) {
208 DocsService.lance = await import("vectordb");
209 }
210 return DocsService.lance;
211 } catch (err) {
212 console.error("Failed to load LanceDB:", err);
213 return null;
214 }
215 }
216
217 // Singleton pattern: only one service globally
218 private static instance?: DocsService;
219 static createSingleton(
220 configHandler: ConfigHandler,
221 ide: IDE,
222 messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
223 ) {
224 const docsService = new DocsService(configHandler, ide, messenger);
225 DocsService.instance = docsService;
226 return docsService;
227 }
228
229 static getSingleton() {
230 return DocsService.instance;
231 }
232
233 // Initialization - load config and attach config listener
234 private async init(configHandler: ConfigHandler) {
235 const result = await configHandler.loadConfig();
236 await this.handleConfigUpdate(result);
237 configHandler.onConfigUpdate(
238 this.handleConfigUpdate.bind(this) as (arg: any) => void,
239 );
240 }
241
242 readonly statuses: Map<string, IndexingStatus> = new Map();
243
244 handleStatusUpdate(update: IndexingStatus) {
245 this.statuses.set(update.id, update);
246 this.messenger?.send("indexing/statusUpdate", update);
247 }
248
249 // A way for gui to retrieve initial statuses
250 async initStatuses(): Promise<void> {
251 if (!this.config?.docs) {
252 return;
253 }
254 const metadata = await this.listMetadata();
255
256 this.config.docs?.forEach((doc) => {
257 if (!doc.startUrl) {
258 console.error("Invalid config docs entry, no start url", doc.title);
259 return;
260 }
261
262 const currentStatus = this.statuses.get(doc.startUrl);
263 if (currentStatus) {
264 this.handleStatusUpdate(currentStatus);
265 return;
266 }
267
268 const sharedStatus: Omit<
269 IndexingStatus,
270 "progress" | "description" | "status"
271 > = {
272 type: "docs",
273 id: doc.startUrl,
274 isReindexing: false,
275 title: doc.title,
276 debugInfo: `max depth: ${doc.maxDepth}`,
277 icon: doc.faviconUrl,
278 url: doc.startUrl,
279 };
280 if (this.config.selectedModelByRole.embed) {
281 sharedStatus.embeddingsProviderId =
282 this.config.selectedModelByRole.embed.embeddingId;
283 }
284 const indexedStatus: IndexingStatus = metadata.find(
285 (meta) => meta.startUrl === doc.startUrl,
286 )
287 ? {
288 ...sharedStatus,
289 progress: 0,
290 description: "Pending",
291 status: "pending",
292 }
293 : {
294 ...sharedStatus,
295 progress: 1,
296 description: "Complete",
297 status: "complete",
298 };
299 this.handleStatusUpdate(indexedStatus);
300 });
301 }
302
303 abort(startUrl: string) {
304 if (this.docsIndexingQueue.has(startUrl)) {
305 const status = this.statuses.get(startUrl);
306 if (status) {
307 this.handleStatusUpdate({
308 ...status,
309 status: "aborted",
310 progress: 0,
311 description: "Canceled",
312 });
313 }
314 this.docsIndexingQueue.delete(startUrl);
315 }
316 }
317
318 // Used to check periodically during indexing if should cancel indexing
319 shouldCancel(startUrl: string, startedWithEmbedder: string) {
320 // Check if aborted
321 const isAborted = this.statuses.get(startUrl)?.status === "aborted";
322 if (isAborted) {
323 return true;
324 }
325
326 // Handle embeddings provider change mid-indexing
327 if (
328 this.config.selectedModelByRole.embed?.embeddingId !== startedWithEmbedder
329 ) {
330 this.abort(startUrl);
331 return true;
332 }
333 return false;
334 }
335
336 // Determine if transformers.js embeddings are supported in this environment
337 async canUseTransformersEmbeddings() {
338 const ideInfo = await this.ideInfoPromise;
339 if (ideInfo.ideType === "jetbrains") {
340 return false;
341 }
342 return true;
343 }
344
345 // Get the appropriate embeddings provider
346 async getEmbeddingsProvider() {
347 // First check if there's a config selected embeddings provider
348 if (this.config.selectedModelByRole.embed) {
349 return {
350 provider: this.config.selectedModelByRole.embed,
351 };
352 }
353
354 // Fall back to transformers if supported
355 const canUseTransformers = await this.canUseTransformersEmbeddings();
356 if (canUseTransformers) {
357 return {
358 provider: DocsService.defaultEmbeddingsProvider,
359 };
360 }
361
362 // No provider available
363 return {
364 provider: undefined,
365 };
366 }
367
368 private async handleConfigUpdate({
369 config: newConfig,
370 }: ConfigResult<ContinueConfig>) {
371 if (newConfig) {
372 const oldConfig = this.config;
373 this.config = newConfig; // IMPORTANT - need to set up top, other methods below use this without passing it in
374
375 // No point in indexing if no docs context provider
376 const hasDocsContextProvider = this.hasDocsContextProvider();
377 if (!hasDocsContextProvider) {
378 return;
379 }
380
381 // Skip docs indexing if not supported
382 // No warning message here because would show on ANY config update
383 if (!this.config.selectedModelByRole.embed) {
384 return;
385 }
386
387 await this.syncDocs(oldConfig, newConfig, false);
388 }
389 }
390
391 async syncDocsWithPrompt(reIndex: boolean = false) {
392 await this.syncDocs(undefined, this.config, reIndex);
393
394 void this.ide.showToast("info", "Docs indexing completed");
395 }
396
397 // Returns true if startUrl has been indexed with current embeddingsProvider
398 async hasMetadata(startUrl: string): Promise<boolean> {
399 if (!this.config.selectedModelByRole.embed) {
400 return false;
401 }
402 const db = await this.getOrCreateSqliteDb();
403 const title = await db.get(
404 `SELECT title FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
405 startUrl,
406 this.config.selectedModelByRole.embed.embeddingId,
407 );
408
409 return !!title;
410 }
411
412 async listMetadata() {
413 const embeddingsProvider = this.config.selectedModelByRole.embed;
414 if (!embeddingsProvider) {
415 return [];
416 }
417 const db = await this.getOrCreateSqliteDb();
418 const docs = await db.all<SqliteDocsRow[]>(
419 `SELECT title, startUrl, favicon FROM ${DocsService.sqlitebTableName}
420 WHERE embeddingsProviderId = ?`,
421 embeddingsProvider.embeddingId,
422 );
423
424 return docs;
425 }
426
427 async reindexDoc(startUrl: string) {
428 const docConfig = this.config.docs?.find(
429 (doc) => doc.startUrl === startUrl,
430 );
431 if (docConfig) {
432 await this.indexAndAdd(docConfig, true);
433 }
434 }
435
436 /**
437 * Attempt to load document embeddings from cache
438 * @returns true if cache was successfully loaded, false otherwise
439 */
440 private async tryLoadFromCache(
441 startUrl: string,
442 embeddingId: string,
443 siteIndexingConfig: SiteIndexingConfig,
444 ): Promise<boolean> {
445 try {
446 // Set a initial status when retrieving cache
447 this.handleStatusUpdate({
448 type: "docs",
449 id: startUrl,
450 embeddingsProviderId: embeddingId,
451 isReindexing: false,
452 title: siteIndexingConfig.title,
453 debugInfo: "Loaded from cache",
454 icon: siteIndexingConfig.faviconUrl,
455 url: startUrl,
456 progress: 0,
457 description: "Try to retrieve cache",
458 status: "indexing",
459 });
460
461 const cacheHit = await this.tryFetchFromCache(startUrl, embeddingId);
462
463 if (cacheHit) {
464 console.log(`Successfully loaded cached embeddings for ${startUrl}`);
465 // Update status to complete
466 this.handleStatusUpdate({
467 type: "docs",
468 id: startUrl,
469 embeddingsProviderId: embeddingId,
470 isReindexing: false,
471 title: siteIndexingConfig.title,
472 debugInfo: "Loaded from cache",
473 icon: siteIndexingConfig.faviconUrl,
474 url: startUrl,
475 progress: 1,
476 description: "Complete",
477 status: "complete",
478 });
479
480 return true;
481 }
482 } catch (e) {
483 console.log(`Error trying to fetch from cache: ${e}`);
484 // Continue with regular indexing
485 }
486
487 return false;
488 }
489
490 // eslint-disable-next-line max-statements
491 async indexAndAdd(
492 siteIndexingConfig: SiteIndexingConfig,
493 forceReindex: boolean = false,
494 ): Promise<void> {
495 const { startUrl, useLocalCrawling, maxDepth, faviconUrl } =
496 siteIndexingConfig;
497
498 // First, if indexing is already in process, don't attempt
499 // This queue is necessary because indexAndAdd is invoked circularly by config edits
500 // TODO shouldn't really be a gap between adding and checking in queue but probably fine
501 if (this.docsIndexingQueue.has(startUrl)) {
502 return;
503 }
504
505 const { provider } = await this.getEmbeddingsProvider();
506 if (!provider) {
507 console.warn("@docs indexAndAdd: no embeddings provider found");
508 return;
509 }
510
511 // Try to fetch from cache first before crawling
512 if (!forceReindex) {
513 const cacheLoaded = await this.tryLoadFromCache(
514 startUrl,
515 provider.embeddingId,
516 siteIndexingConfig,
517 );
518
519 if (cacheLoaded) {
520 return;
521 }
522 }
523
524 const startedWithEmbedder = provider.embeddingId;
525
526 // Check if doc has been successfully indexed with the given embedder
527 const indexExists = await this.hasMetadata(startUrl);
528
529 // Build status update - most of it is fixed values
530 const fixedStatus: Omit<
531 IndexingStatus,
532 "progress" | "description" | "status"
533 > = {
534 type: "docs",
535 id: siteIndexingConfig.startUrl,
536 embeddingsProviderId: provider.embeddingId,
537 isReindexing: forceReindex && indexExists,
538 title: siteIndexingConfig.title,
539 debugInfo: `max depth: ${siteIndexingConfig.maxDepth}`,
540 icon: siteIndexingConfig.faviconUrl,
541 url: siteIndexingConfig.startUrl,
542 };
543
544 // If not force-reindexing and has failed with same config, don't reattempt
545 if (!forceReindex) {
546 if (hasIndexingFailed(siteIndexingConfig)) {
547 console.log(
548 `Not reattempting to index ${siteIndexingConfig.startUrl}, has already failed with same config`,
549 );
550 this.handleStatusUpdate({
551 ...fixedStatus,
552 description: "Failed",
553 status: "failed",
554 progress: 1,
555 });
556 return;
557 }
558 }
559
560 if (indexExists && !forceReindex) {
561 this.handleStatusUpdate({
562 ...fixedStatus,
563 progress: 1,
564 description: "Complete",
565 status: "complete",
566 debugInfo: "Already indexed",
567 });
568 return;
569 }
570
571 // Do a test run on the embedder
572 // This particular failure will not mark as a failed config in global context
573 // Since SiteIndexingConfig is likely to be valid
574 try {
575 await provider.embed(["continue-test-run"]);
576 } catch (e) {
577 if (e instanceof LLMError) {
578 // Report the error to the IDE
579 await this.messenger?.request("reportError", e);
580 }
581 this.handleStatusUpdate({
582 ...fixedStatus,
583 description: `Failed to test embeddings connection. ${e}`,
584 status: "failed",
585 progress: 1,
586 });
587 console.error("Failed to test embeddings connection", e);
588 return;
589 }
590
591 try {
592 this.docsIndexingQueue.add(startUrl);
593
594 // Clear current indexes if reIndexing
595 if (indexExists && forceReindex) {
596 await this.deleteIndexes(startUrl);
597 }
598
599 this.addToConfig(siteIndexingConfig);
600
601 this.handleStatusUpdate({
602 ...fixedStatus,
603 status: "indexing",
604 description: "Finding subpages",
605 progress: 0,
606 });
607
608 // Crawl pages to get page data
609 const pages: PageData[] = [];
610 let processedPages = 0;
611 let estimatedProgress = 0;
612 let done = false;
613 let usedCrawler: DocsCrawlerType | undefined = undefined;
614
615 const docsCrawler = new DocsCrawler(
616 this.ide,
617 this.config,
618 maxDepth,
619 undefined,
620 useLocalCrawling,
621 this.githubToken,
622 );
623 const crawlerGen = docsCrawler.crawl(new URL(startUrl));
624
625 while (!done) {
626 const result = await crawlerGen.next();
627 if (result.done) {
628 done = true;
629 usedCrawler = result.value;
630 } else {
631 const page = result.value;
632 estimatedProgress += 1 / 2 ** (processedPages + 1);
633
634 // NOTE - during "indexing" phase, check if aborted before each status update
635 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
636 return;
637 }
638 this.handleStatusUpdate({
639 ...fixedStatus,
640 description: `Finding subpages (${page.path})`,
641 status: "indexing",
642 progress:
643 0.15 * estimatedProgress +
644 Math.min(0.35, (0.35 * processedPages) / 500),
645 // For the first 50%, 15% is sum of series 1/(2^n) and the other 35% is based on number of files/ 500 max
646 });
647
648 pages.push(page);
649
650 processedPages++;
651
652 // Locks down GUI if no sleeping
653 // Wait proportional to how many docs are indexing
654 const toWait = 100 * this.docsIndexingQueue.size + 50;
655 await new Promise((resolve) => setTimeout(resolve, toWait));
656 }
657 }
658
659 void Telemetry.capture("docs_pages_crawled", {
660 count: processedPages,
661 });
662
663 // Chunk pages based on which crawler was used
664 const articles: ArticleWithChunks[] = [];
665 const chunks: Chunk[] = [];
666 const articleChunker =
667 usedCrawler === "github"
668 ? markdownPageToArticleWithChunks
669 : htmlPageToArticleWithChunks;
670 for (const page of pages) {
671 const articleWithChunks = await articleChunker(
672 page,
673 provider.maxEmbeddingChunkSize,
674 );
675 if (articleWithChunks) {
676 articles.push(articleWithChunks);
677 }
678 const toWait = 20 * this.docsIndexingQueue.size + 10;
679 await new Promise((resolve) => setTimeout(resolve, toWait));
680 }
681
682 // const chunks: Chunk[] = [];
683 const embeddings: number[][] = [];
684
685 // Create embeddings of retrieved articles
686 for (let i = 0; i < articles.length; i++) {
687 const article = articles[i];
688
689 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
690 return;
691 }
692 this.handleStatusUpdate({
693 ...fixedStatus,
694 status: "indexing",
695 description: `Creating Embeddings: ${article.article.subpath}`,
696 progress: 0.5 + 0.3 * (i / articles.length), // 50% -> 80%
697 });
698
699 try {
700 const subpathEmbeddings =
701 article.chunks.length > 0
702 ? await provider.embed(article.chunks.map((c) => c.content))
703 : [];
704 chunks.push(...article.chunks);
705 embeddings.push(...subpathEmbeddings);
706 const toWait = 100 * this.docsIndexingQueue.size + 50;
707 await new Promise((resolve) => setTimeout(resolve, toWait));
708 } catch (e) {
709 console.warn("Error embedding article chunks: ", e);
710 }
711 }
712
713 if (embeddings.length === 0) {
714 console.error(
715 `No embeddings were created for site: ${startUrl}\n Num chunks: ${chunks.length}`,
716 );
717
718 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
719 return;
720 }
721 this.handleStatusUpdate({
722 ...fixedStatus,
723 description: `No embeddings were created for site: ${startUrl}`,
724 status: "failed",
725 progress: 1,
726 });
727
728 // void this.ide.showToast("info", `Failed to index ${startUrl}`);
729 markFailedInGlobalContext(siteIndexingConfig);
730 return;
731 }
732
733 // Add docs to databases
734 console.log(`Adding ${embeddings.length} embeddings to db`);
735
736 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
737 return;
738 }
739 this.handleStatusUpdate({
740 ...fixedStatus,
741 description: "Deleting old embeddings from the db",
742 status: "indexing",
743 progress: 0.8,
744 });
745
746 // Delete indexed docs if re-indexing
747 if (forceReindex && indexExists) {
748 console.log("Deleting old embeddings");
749 await this.deleteIndexes(startUrl);
750 }
751
752 const favicon =
753 faviconUrl ||
754 (await fetchFavicon(new URL(siteIndexingConfig.startUrl)));
755
756 if (this.shouldCancel(startUrl, startedWithEmbedder)) {
757 return;
758 }
759 this.handleStatusUpdate({
760 ...fixedStatus,
761 description: `Adding ${embeddings.length} embeddings to db`,
762 status: "indexing",
763 progress: 0.85,
764 });
765
766 await this.add({
767 siteIndexingConfig,
768 chunks,
769 embeddings,
770 favicon,
771 });
772
773 this.handleStatusUpdate({
774 ...fixedStatus,
775 description: "Complete",
776 status: "complete",
777 progress: 1,
778 });
779
780 // Only show notificaitons if the user manually re-indexed, otherwise
781 // they are too noisy, especially when switching embeddings providers
782 // and we automatically re-index all docs
783 if (forceReindex) {
784 void this.ide.showToast("info", `Successfully indexed ${startUrl}`);
785 }
786
787 removeFromFailedGlobalContext(siteIndexingConfig);
788 } catch (e) {
789 console.error(
790 `Error indexing docs at: ${siteIndexingConfig.startUrl}`,
791 e,
792 );
793 let description = `Error indexing docs at: ${siteIndexingConfig.startUrl}`;
794 if (e instanceof Error) {
795 if (
796 e.message.includes("github.com") &&
797 e.message.includes("rate limit")
798 ) {
799 description = "Github rate limit exceeded"; // This text is used verbatim elsewhere
800 }
801 }
802 this.handleStatusUpdate({
803 ...fixedStatus,
804 description,
805 status: "failed",
806 progress: 1,
807 });
808 markFailedInGlobalContext(siteIndexingConfig);
809 } finally {
810 this.docsIndexingQueue.delete(startUrl);
811 }
812 }
813
814 /**
815 * Try to fetch embeddings from the S3 cache for any document URL
816 * @param startUrl The URL of the documentation site
817 * @param embeddingsProviderId The ID of the embeddings provider
818 * @returns True if cache hit and successfully loaded, false otherwise
819 */
820 private async tryFetchFromCache(
821 startUrl: string,
822 embeddingId: string,
823 ): Promise<boolean> {
824 try {
825 const data = await DocsCache.getDocsCacheForUrl(embeddingId, startUrl);
826
827 // Parse the cached data
828 const siteEmbeddings = JSON.parse(data) as SiteIndexingResults;
829
830 // Try to get a favicon for the site
831 const favicon =
832 this.statuses.get(startUrl)?.icon ||
833 (await fetchFavicon(new URL(startUrl)));
834
835 // Always try to make the title match what users set in the config
836 const title =
837 this.statuses.get(startUrl)?.title ||
838 siteEmbeddings.title ||
839 new URL(startUrl).hostname;
840
841 // Add the cached embeddings to our database
842 await this.add({
843 favicon,
844 siteIndexingConfig: {
845 startUrl,
846 title,
847 },
848 chunks: siteEmbeddings.chunks,
849 embeddings: siteEmbeddings.chunks.map((c) => c.embedding),
850 });
851
852 return true;
853 } catch (e) {
854 // Cache miss or error - silently fail
855 console.log(`Cache miss for ${startUrl} with provider ${embeddingId}`);
856 return false;
857 }
858 }
859
860 // Retrieve docs embeds based on user input
861 async retrieveChunksFromQuery(
862 query: string,
863 startUrl: string,
864 nRetrieve: number,
865 ) {
866 const { provider } = await this.getEmbeddingsProvider();
867
868 if (!provider) {
869 void this.ide.showToast(
870 "error",
871 "Set up an embeddings model to use the @docs context provider. See: " +
872 "https://docs.continue.dev/customize/model-roles/embeddings",
873 );
874 return [];
875 }
876
877 // Try to get embeddings for the query
878 const [vector] = await provider.embed([query]);
879
880 // Retrieve chunks using the query vector
881 return await this.retrieveChunks(startUrl, vector, nRetrieve);
882 }
883
884 private lanceDBRowToChunk(row: LanceDbDocsRow): Chunk {
885 return {
886 digest: row.path,
887 filepath: row.path,
888 startLine: row.startline,
889 endLine: row.endline,
890 index: 0,
891 content: row.content,
892 otherMetadata: {
893 title: row.title,
894 },
895 };
896 }
897 async getDetails(startUrl: string): Promise<DocsIndexingDetails> {
898 const db = await this.getOrCreateSqliteDb();
899
900 try {
901 const { provider } = await this.getEmbeddingsProvider();
902
903 if (!provider) {
904 throw new Error("No embeddings model set");
905 }
906
907 const result = await db.get(
908 `SELECT startUrl, title, favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
909 startUrl,
910 provider.embeddingId,
911 );
912
913 if (!result) {
914 throw new Error(`${startUrl} not found in sqlite`);
915 }
916 const siteIndexingConfig: SiteIndexingConfig = {
917 startUrl,
918 faviconUrl: result.favicon,
919 title: result.title,
920 };
921
922 const table = await this.getOrCreateLanceTable({
923 initializationVector: [],
924 startUrl,
925 });
926 const rows = (await table
927 .filter(`starturl = '${startUrl}'`)
928 .limit(1000)
929 .execute()) as LanceDbDocsRow[];
930
931 return {
932 startUrl,
933 config: siteIndexingConfig,
934 indexingStatus: this.statuses.get(startUrl),
935 chunks: rows.map(this.lanceDBRowToChunk),
936 };
937 } catch (e) {
938 console.warn("Error getting details", e);
939 throw e;
940 }
941 }
942 // This function attempts to retrieve chunks by vector similarity
943 // It will also attempt to fetch from cache if no results are found
944 async retrieveChunks(
945 startUrl: string,
946 vector: number[],
947 nRetrieve: number,
948 isRetry: boolean = false,
949 ): Promise<Chunk[]> {
950 // Get the appropriate embeddings provider
951 const { provider } = await this.getEmbeddingsProvider();
952 if (!provider) {
953 return [];
954 }
955
956 // Lance doesn't have an embeddingsprovider column, instead it includes it in the table name
957 const table = await this.getOrCreateLanceTable({
958 initializationVector: vector,
959 startUrl,
960 });
961
962 let docs: LanceDbDocsRow[] = [];
963 try {
964 docs = await table
965 .search(vector)
966 .limit(nRetrieve)
967 .where(`starturl = '${startUrl}'`)
968 .execute();
969 } catch (e: any) {
970 console.warn("Error retrieving chunks from LanceDB", e);
971 }
972
973 // If no docs are found and this isn't a retry, try fetching from cache
974 if (docs.length === 0 && !isRetry) {
975 try {
976 // Try to fetch the document from the S3 cache
977 const cacheHit = await this.tryFetchFromCache(
978 startUrl,
979 provider.embeddingId,
980 );
981
982 if (cacheHit) {
983 // If cache hit, refresh the submenu items for docs
984 this.messenger?.send("refreshSubmenuItems", {
985 providers: ["docs"],
986 });
987 // If cache hit, retry the search once
988 return await this.retrieveChunks(startUrl, vector, nRetrieve, true);
989 }
990 } catch (e) {
991 console.warn("Error trying to fetch from cache:", e);
992 }
993 }
994
995 return docs.map(this.lanceDBRowToChunk);
996 }
997
998 // SQLITE DB
999 private async getOrCreateSqliteDb() {
1000 if (!this.sqliteDb) {
1001 const db = await open({
1002 filename: getDocsSqlitePath(),
1003 driver: sqlite3.Database,
1004 });
1005
1006 await db.exec("PRAGMA busy_timeout = 3000;");
1007
1008 // First create the table if it doesn't exist
1009 await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
1010 id INTEGER PRIMARY KEY AUTOINCREMENT,
1011 title STRING NOT NULL,
1012 startUrl STRING NOT NULL,
1013 favicon STRING,
1014 embeddingsProviderId STRING
1015 )`);
1016
1017 await runSqliteMigrations(db);
1018
1019 this.sqliteDb = db;
1020 }
1021
1022 return this.sqliteDb;
1023 }
1024
1025 async getFavicon(startUrl: string) {
1026 if (!this.config.selectedModelByRole.embed) {
1027 console.warn(
1028 "Attempting to get favicon without embeddings provider specified",
1029 );
1030 return;
1031 }
1032 const db = await this.getOrCreateSqliteDb();
1033 const result = await db.get(
1034 `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
1035 startUrl,
1036 this.config.selectedModelByRole.embed.embeddingId,
1037 );
1038
1039 if (!result) {
1040 return;
1041 }
1042 return result.favicon;
1043 }
1044
1045 /**
1046 * Sync with no embeddings provider change
1047 */
1048 private async syncDocs(
1049 oldConfig: ContinueConfig | undefined,
1050 newConfig: ContinueConfig,
1051 forceReindex: boolean,
1052 ) {
1053 try {
1054 this.isSyncing = true;
1055
1056 // Otherwise sync the index based on config changes
1057 const oldConfigDocs = oldConfig?.docs || [];
1058 const newConfigDocs = newConfig.docs || [];
1059
1060 // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
1061 const currentlyIndexedDocs = await this.listMetadata();
1062 const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
1063
1064 // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
1065 // Anything found in new config that isn't in sqlite should be added/indexed
1066 const addedDocs: SiteIndexingConfig[] = [];
1067 const changedDocs: SiteIndexingConfig[] = [];
1068 for (const doc of newConfigDocs) {
1069 const currentIndexedDoc = currentStartUrls.includes(doc.startUrl);
1070
1071 if (currentIndexedDoc) {
1072 const oldConfigDoc = oldConfigDocs.find(
1073 (d) => d.startUrl === doc.startUrl,
1074 );
1075
1076 // TODO: Changes to the docs config made while Continue isn't running won't be caught
1077 if (
1078 oldConfigDoc &&
1079 !siteIndexingConfigsAreEqual(
1080 oldConfigDoc,
1081 doc,
1082 oldConfig,
1083 newConfig,
1084 )
1085 ) {
1086 // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
1087 if (
1088 siteIndexingConfigsAreEqualExceptTitleAndFavicon(
1089 oldConfigDoc,
1090 doc,
1091 oldConfig,
1092 newConfig,
1093 )
1094 ) {
1095 await this.updateMetadataInSqlite(doc);
1096 } else {
1097 changedDocs.push(doc);
1098 }
1099 } else {
1100 if (forceReindex) {
1101 changedDocs.push(doc);
1102 } else {
1103 // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
1104 // We only update title and faviconUrl here
1105 await this.updateMetadataInSqlite(doc);
1106 // if get's here, not changed, no update needed, mark as complete
1107 this.handleStatusUpdate({
1108 type: "docs",
1109 id: doc.startUrl,
1110 embeddingsProviderId:
1111 this.config.selectedModelByRole.embed?.embeddingId,
1112 isReindexing: false,
1113 title: doc.title,
1114 debugInfo: "Config sync: not changed",
1115 icon: doc.faviconUrl,
1116 url: doc.startUrl,
1117 progress: 1,
1118 description: "Complete",
1119 status: "complete",
1120 });
1121 }
1122 }
1123 } else {
1124 addedDocs.push(doc);
1125 void Telemetry.capture("add_docs_config", { url: doc.startUrl });
1126 }
1127 }
1128
1129 await Promise.allSettled([
1130 ...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
1131 ...addedDocs.map((doc) => this.indexAndAdd(doc)),
1132 ]);
1133 } catch (e) {
1134 console.error("Error syncing docs index on config update", e);
1135 } finally {
1136 this.isSyncing = false;
1137 // Refresh the submenu items for docs
1138 this.messenger?.send("refreshSubmenuItems", {
1139 providers: ["docs"],
1140 });
1141 }
1142 }
1143
1144 private hasDocsContextProvider() {
1145 return !!this.config.contextProviders?.some(
1146 (provider) =>
1147 provider.description.title === DocsContextProvider.description.title,
1148 );
1149 }
1150
1151 // Lance DB Initialization
1152 private async createLanceDocsTable(
1153 connection: LanceType.Connection,
1154 initializationVector: number[],
1155 tableName: string,
1156 ) {
1157 const mockRowTitle = "mockRowTitle";
1158 const mockRow: LanceDbDocsRow[] = [
1159 {
1160 title: mockRowTitle,
1161 vector: initializationVector,
1162 starturl: "",
1163 content: "",
1164 path: "",
1165 startline: 0,
1166 endline: 0,
1167 },
1168 ];
1169
1170 const table = await connection.createTable(tableName, mockRow);
1171
1172 await runLanceMigrations(table);
1173
1174 await table.delete(`title = '${mockRowTitle}'`);
1175 }
1176
1177 /**
1178 * From Lance: Table names can only contain alphanumeric characters,
1179 * underscores, hyphens, and periods
1180 */
1181 private sanitizeLanceTableName(name: string) {
1182 return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
1183 }
1184
1185 private async getLanceTableName(embeddingsProvider: ILLM) {
1186 const tableName = this.sanitizeLanceTableName(
1187 `${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
1188 );
1189
1190 return tableName;
1191 }
1192
1193 private async getOrCreateLanceTable({
1194 initializationVector,
1195 startUrl,
1196 }: {
1197 initializationVector: number[];
1198 startUrl: string;
1199 }) {
1200 const lance = await this.initLanceDb();
1201 if (!lance) {
1202 throw new Error("LanceDB not available on this platform");
1203 }
1204
1205 const conn = await lance.connect(getLanceDbPath());
1206 const tableNames = await conn.tableNames();
1207 const { provider } = await this.getEmbeddingsProvider();
1208
1209 if (!provider) {
1210 throw new Error(
1211 "Could not retrieve @docs Lance Table: no embeddings provider specified",
1212 );
1213 }
1214
1215 const tableNameFromEmbeddingsProvider =
1216 await this.getLanceTableName(provider);
1217
1218 if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
1219 if (initializationVector) {
1220 await this.createLanceDocsTable(
1221 conn,
1222 initializationVector,
1223 tableNameFromEmbeddingsProvider,
1224 );
1225 } else {
1226 console.trace(
1227 "No existing Lance DB docs table was found and no initialization " +
1228 "vector was passed to create one",
1229 );
1230 }
1231 }
1232
1233 const table = await conn.openTable(tableNameFromEmbeddingsProvider);
1234
1235 this.lanceTableNamesSet.add(tableNameFromEmbeddingsProvider);
1236
1237 return table;
1238 }
1239
1240 // Methods for adding individual docs
1241 private async addToLance({
1242 chunks,
1243 siteIndexingConfig,
1244 embeddings,
1245 }: AddParams) {
1246 const sampleVector = embeddings[0];
1247 const { startUrl } = siteIndexingConfig;
1248
1249 const table = await this.getOrCreateLanceTable({
1250 startUrl,
1251 initializationVector: sampleVector,
1252 });
1253
1254 const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
1255 vector: embeddings[i],
1256 starturl: startUrl,
1257 title: chunk.otherMetadata?.title || siteIndexingConfig.title,
1258 content: chunk.content,
1259 path: chunk.filepath,
1260 startline: chunk.startLine,
1261 endline: chunk.endLine,
1262 }));
1263
1264 await table.add(rows);
1265 }
1266
1267 private async addMetadataToSqlite({
1268 siteIndexingConfig: { title, startUrl },
1269 favicon,
1270 }: AddParams) {
1271 if (!this.config.selectedModelByRole.embed) {
1272 console.warn(
1273 `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1274 );
1275 return;
1276 }
1277 const db = await this.getOrCreateSqliteDb();
1278 await db.run(
1279 `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
1280 title,
1281 startUrl,
1282 favicon,
1283 this.config.selectedModelByRole.embed.embeddingId,
1284 );
1285 }
1286
1287 private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
1288 const { startUrl, title, faviconUrl } = siteIndexingConfig;
1289 const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
1290 if (!this.config.selectedModelByRole.embed) {
1291 console.warn(
1292 `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1293 );
1294 return;
1295 }
1296
1297 const db = await this.getOrCreateSqliteDb();
1298
1299 await db.run(
1300 `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
1301 title,
1302 favicon,
1303 startUrl,
1304 this.config.selectedModelByRole.embed.embeddingId,
1305 );
1306 }
1307
1308 private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
1309 // Handles the case where a user has manually added the doc to config.json
1310 // so it already exists in the file
1311 const doesEquivalentDocExist = this.config.docs?.some((doc) =>
1312 docConfigsAreEqual(doc, siteIndexingConfig),
1313 );
1314
1315 if (!doesEquivalentDocExist) {
1316 editConfigFile(
1317 (config) => ({
1318 ...config,
1319 docs: [
1320 ...(config.docs?.filter(
1321 (doc) => doc.startUrl !== siteIndexingConfig.startUrl,
1322 ) ?? []),
1323 siteIndexingConfig,
1324 ],
1325 }),
1326 (config) => ({
1327 ...config,
1328 docs: [
1329 ...(config.docs?.filter(
1330 (doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl,
1331 ) ?? []),
1332 {
1333 name: siteIndexingConfig.title,
1334 faviconUrl: siteIndexingConfig.faviconUrl,
1335 startUrl: siteIndexingConfig.startUrl,
1336 },
1337 ],
1338 }),
1339 );
1340 }
1341 }
1342
1343 private async add(params: AddParams) {
1344 await this.addToLance(params);
1345 await this.addMetadataToSqlite(params);
1346 }
1347
1348 // Delete methods
1349 private async deleteEmbeddingsFromLance(startUrl: string) {
1350 const lance = await this.initLanceDb();
1351 if (!lance) {
1352 return;
1353 }
1354
1355 for (const tableName of this.lanceTableNamesSet) {
1356 const conn = await lance.connect(getLanceDbPath());
1357 const table = await conn.openTable(tableName);
1358 await table.delete(`starturl = '${startUrl}'`);
1359 }
1360 }
1361
1362 private async deleteMetadataFromSqlite(startUrl: string) {
1363 if (!this.config.selectedModelByRole.embed) {
1364 console.warn(
1365 `Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
1366 );
1367 return;
1368 }
1369 const db = await this.getOrCreateSqliteDb();
1370
1371 await db.run(
1372 `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
1373 startUrl,
1374 this.config.selectedModelByRole.embed.embeddingId,
1375 );
1376 }
1377
1378 private deleteFromConfig(startUrl: string) {
1379 const doesDocExist = this.config.docs?.some(
1380 (doc) => doc.startUrl === startUrl,
1381 );
1382 if (doesDocExist) {
1383 editConfigFile(
1384 (config) => ({
1385 ...config,
1386 docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
1387 }),
1388 (config) => ({
1389 ...config,
1390 docs:
1391 config.docs?.filter(
1392 (doc) => "startUrl" in doc && doc.startUrl !== startUrl,
1393 ) || [],
1394 }),
1395 );
1396 }
1397 }
1398
1399 private async deleteIndexes(startUrl: string) {
1400 await this.deleteEmbeddingsFromLance(startUrl);
1401 await this.deleteMetadataFromSqlite(startUrl);
1402 }
1403
1404 async delete(startUrl: string) {
1405 this.docsIndexingQueue.delete(startUrl);
1406 this.abort(startUrl);
1407 await this.deleteIndexes(startUrl);
1408 this.deleteFromConfig(startUrl);
1409 this.messenger?.send("refreshSubmenuItems", {
1410 providers: ["docs"],
1411 });
1412 this.statuses.delete(startUrl);
1413 }
1414}