Elffuss BraidHub

kikocis/continue public

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