Elffuss BraidHub

kikocis/continue public

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