Elffuss BraidHub

kikocis/continue public

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