Elffuss BraidHub

kikocis/continue public

35c0ed0a3308 · 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 await runSqliteMigrations(db);
972 // First create the table if it doesn't exist
973 await db.exec(`CREATE TABLE IF NOT EXISTS ${DocsService.sqlitebTableName} (
974 id INTEGER PRIMARY KEY AUTOINCREMENT,
975 title STRING NOT NULL,
976 startUrl STRING NOT NULL,
977 favicon STRING,
978 embeddingsProviderId STRING
979 )`);
980
981 this.sqliteDb = db;
982 }
983
984 return this.sqliteDb;
985 }
986
987 async getFavicon(startUrl: string) {
988 if (!this.config.selectedModelByRole.embed) {
989 console.warn(
990 "Attempting to get favicon without embeddings provider specified",
991 );
992 return;
993 }
994 const db = await this.getOrCreateSqliteDb();
995 const result = await db.get(
996 `SELECT favicon FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
997 startUrl,
998 this.config.selectedModelByRole.embed.embeddingId,
999 );
1000
1001 if (!result) {
1002 return;
1003 }
1004 return result.favicon;
1005 }
1006
1007 /**
1008 * Sync with no embeddings provider change
1009 */
1010 private async syncDocs(
1011 oldConfig: ContinueConfig | undefined,
1012 newConfig: ContinueConfig,
1013 forceReindex: boolean,
1014 ) {
1015 try {
1016 this.isSyncing = true;
1017
1018 // Otherwise sync the index based on config changes
1019 const oldConfigDocs = oldConfig?.docs || [];
1020 const newConfigDocs = newConfig.docs || [];
1021
1022 // NOTE since listMetadata filters by embeddings provider id embedding model changes are accounted for here
1023 const currentlyIndexedDocs = await this.listMetadata();
1024 const currentStartUrls = currentlyIndexedDocs.map((doc) => doc.startUrl);
1025
1026 // Anything found in old config, new config, AND sqlite that doesn't match should be reindexed
1027 // Anything found in new config that isn't in sqlite should be added/indexed
1028 const addedDocs: SiteIndexingConfig[] = [];
1029 const changedDocs: SiteIndexingConfig[] = [];
1030 for (const doc of newConfigDocs) {
1031 const currentIndexedDoc = currentStartUrls.includes(doc.startUrl);
1032
1033 if (currentIndexedDoc) {
1034 const oldConfigDoc = oldConfigDocs.find(
1035 (d) => d.startUrl === doc.startUrl,
1036 );
1037
1038 // TODO: Changes to the docs config made while Continue isn't running won't be caught
1039 if (oldConfigDoc && !siteIndexingConfigsAreEqual(oldConfigDoc, doc)) {
1040 // When only the title or faviconUrl changed, Update the sqlite metadate instead of reindexing
1041 if (
1042 siteIndexingConfigsAreEqualExceptTitleAndFavicon(
1043 oldConfigDoc,
1044 doc,
1045 )
1046 ) {
1047 await this.updateMetadataInSqlite(doc);
1048 } else {
1049 changedDocs.push(doc);
1050 }
1051 } else {
1052 if (forceReindex) {
1053 changedDocs.push(doc);
1054 } else {
1055 // This is a temperary fix to catch the changes to the docs config that were made when Continue isn't running
1056 // We only update title and faviconUrl here
1057 await this.updateMetadataInSqlite(doc);
1058 // if get's here, not changed, no update needed, mark as complete
1059 this.handleStatusUpdate({
1060 type: "docs",
1061 id: doc.startUrl,
1062 embeddingsProviderId:
1063 this.config.selectedModelByRole.embed?.embeddingId,
1064 isReindexing: false,
1065 title: doc.title,
1066 debugInfo: "Config sync: not changed",
1067 icon: doc.faviconUrl,
1068 url: doc.startUrl,
1069 progress: 1,
1070 description: "Complete",
1071 status: "complete",
1072 });
1073 }
1074 }
1075 } else {
1076 addedDocs.push(doc);
1077 void Telemetry.capture("add_docs_config", { url: doc.startUrl });
1078 }
1079 }
1080
1081 await Promise.allSettled([
1082 ...changedDocs.map((doc) => this.indexAndAdd(doc, true)),
1083 ...addedDocs.map((doc) => this.indexAndAdd(doc)),
1084 ]);
1085 } catch (e) {
1086 console.error("Error syncing docs index on config update", e);
1087 } finally {
1088 this.isSyncing = false;
1089 // Refresh the submenu items for docs
1090 this.messenger?.send("refreshSubmenuItems", {
1091 providers: ["docs"],
1092 });
1093 }
1094 }
1095
1096 private hasDocsContextProvider() {
1097 return !!this.config.contextProviders?.some(
1098 (provider) =>
1099 provider.description.title === DocsContextProvider.description.title,
1100 );
1101 }
1102
1103 // Lance DB Initialization
1104 private async createLanceDocsTable(
1105 connection: LanceType.Connection,
1106 initializationVector: number[],
1107 tableName: string,
1108 ) {
1109 const mockRowTitle = "mockRowTitle";
1110 const mockRow: LanceDbDocsRow[] = [
1111 {
1112 title: mockRowTitle,
1113 vector: initializationVector,
1114 starturl: "",
1115 content: "",
1116 path: "",
1117 startline: 0,
1118 endline: 0,
1119 },
1120 ];
1121
1122 const table = await connection.createTable(tableName, mockRow);
1123
1124 await runLanceMigrations(table);
1125
1126 await table.delete(`title = '${mockRowTitle}'`);
1127 }
1128
1129 /**
1130 * From Lance: Table names can only contain alphanumeric characters,
1131 * underscores, hyphens, and periods
1132 */
1133 private sanitizeLanceTableName(name: string) {
1134 return name.replace(/[^a-zA-Z0-9_.-]/g, "_");
1135 }
1136
1137 private async getLanceTableName(embeddingsProvider: ILLM) {
1138 const tableName = this.sanitizeLanceTableName(
1139 `${DocsService.lanceTableName}${embeddingsProvider.embeddingId}`,
1140 );
1141
1142 return tableName;
1143 }
1144
1145 private async getOrCreateLanceTable({
1146 initializationVector,
1147 startUrl,
1148 }: {
1149 initializationVector: number[];
1150 startUrl: string;
1151 }) {
1152 const lance = await this.initLanceDb();
1153 if (!lance) {
1154 throw new Error("LanceDB not available on this platform");
1155 }
1156
1157 const conn = await lance.connect(getLanceDbPath());
1158 const tableNames = await conn.tableNames();
1159 const { provider } = await this.getEmbeddingsProvider();
1160
1161 if (!provider) {
1162 throw new Error(
1163 "Could not retrieve @docs Lance Table: no embeddings provider specified",
1164 );
1165 }
1166
1167 const tableNameFromEmbeddingsProvider =
1168 await this.getLanceTableName(provider);
1169
1170 if (!tableNames.includes(tableNameFromEmbeddingsProvider)) {
1171 if (initializationVector) {
1172 await this.createLanceDocsTable(
1173 conn,
1174 initializationVector,
1175 tableNameFromEmbeddingsProvider,
1176 );
1177 } else {
1178 console.trace(
1179 "No existing Lance DB docs table was found and no initialization " +
1180 "vector was passed to create one",
1181 );
1182 }
1183 }
1184
1185 const table = await conn.openTable(tableNameFromEmbeddingsProvider);
1186
1187 this.lanceTableNamesSet.add(tableNameFromEmbeddingsProvider);
1188
1189 return table;
1190 }
1191
1192 // Methods for adding individual docs
1193 private async addToLance({
1194 chunks,
1195 siteIndexingConfig,
1196 embeddings,
1197 }: AddParams) {
1198 const sampleVector = embeddings[0];
1199 const { startUrl } = siteIndexingConfig;
1200
1201 const table = await this.getOrCreateLanceTable({
1202 startUrl,
1203 initializationVector: sampleVector,
1204 });
1205
1206 const rows: LanceDbDocsRow[] = chunks.map((chunk, i) => ({
1207 vector: embeddings[i],
1208 starturl: startUrl,
1209 title: chunk.otherMetadata?.title || siteIndexingConfig.title,
1210 content: chunk.content,
1211 path: chunk.filepath,
1212 startline: chunk.startLine,
1213 endline: chunk.endLine,
1214 }));
1215
1216 await table.add(rows);
1217 }
1218
1219 private async addMetadataToSqlite({
1220 siteIndexingConfig: { title, startUrl },
1221 favicon,
1222 }: AddParams) {
1223 if (!this.config.selectedModelByRole.embed) {
1224 console.warn(
1225 `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1226 );
1227 return;
1228 }
1229 const db = await this.getOrCreateSqliteDb();
1230 await db.run(
1231 `INSERT INTO ${DocsService.sqlitebTableName} (title, startUrl, favicon, embeddingsProviderId) VALUES (?, ?, ?, ?)`,
1232 title,
1233 startUrl,
1234 favicon,
1235 this.config.selectedModelByRole.embed.embeddingId,
1236 );
1237 }
1238
1239 private async updateMetadataInSqlite(siteIndexingConfig: SiteIndexingConfig) {
1240 const { startUrl, title, faviconUrl } = siteIndexingConfig;
1241 const favicon = faviconUrl || (await fetchFavicon(new URL(startUrl)));
1242 if (!this.config.selectedModelByRole.embed) {
1243 console.warn(
1244 `Attempting to add metadata for ${startUrl} without embeddings provider specified`,
1245 );
1246 return;
1247 }
1248
1249 const db = await this.getOrCreateSqliteDb();
1250
1251 await db.run(
1252 `UPDATE ${DocsService.sqlitebTableName} SET title = ?, favicon = ? WHERE startUrl = ? AND embeddingsProviderId = ?`,
1253 title,
1254 favicon,
1255 startUrl,
1256 this.config.selectedModelByRole.embed.embeddingId,
1257 );
1258 }
1259
1260 private addToConfig(siteIndexingConfig: SiteIndexingConfig) {
1261 // Handles the case where a user has manually added the doc to config.json
1262 // so it already exists in the file
1263 const doesEquivalentDocExist = this.config.docs?.some((doc) =>
1264 siteIndexingConfigsAreEqual(doc, siteIndexingConfig),
1265 );
1266
1267 if (!doesEquivalentDocExist) {
1268 editConfigFile(
1269 (config) => ({
1270 ...config,
1271 docs: [
1272 ...(config.docs?.filter(
1273 (doc) => doc.startUrl !== siteIndexingConfig.startUrl,
1274 ) ?? []),
1275 siteIndexingConfig,
1276 ],
1277 }),
1278 (config) => ({
1279 ...config,
1280 docs: [
1281 ...(config.docs?.filter(
1282 (doc) => (doc as any).startUrl !== siteIndexingConfig.startUrl,
1283 ) ?? []),
1284 {
1285 name: siteIndexingConfig.title,
1286 faviconUrl: siteIndexingConfig.faviconUrl,
1287 startUrl: siteIndexingConfig.startUrl,
1288 },
1289 ],
1290 }),
1291 );
1292 }
1293 }
1294
1295 private async add(params: AddParams) {
1296 await this.addToLance(params);
1297 await this.addMetadataToSqlite(params);
1298 }
1299
1300 // Delete methods
1301 private async deleteEmbeddingsFromLance(startUrl: string) {
1302 const lance = await this.initLanceDb();
1303 if (!lance) {
1304 return;
1305 }
1306
1307 for (const tableName of this.lanceTableNamesSet) {
1308 const conn = await lance.connect(getLanceDbPath());
1309 const table = await conn.openTable(tableName);
1310 await table.delete(`starturl = '${startUrl}'`);
1311 }
1312 }
1313
1314 private async deleteMetadataFromSqlite(startUrl: string) {
1315 if (!this.config.selectedModelByRole.embed) {
1316 console.warn(
1317 `Attempting to delete metadata for ${startUrl} without embeddings provider specified`,
1318 );
1319 return;
1320 }
1321 const db = await this.getOrCreateSqliteDb();
1322
1323 await db.run(
1324 `DELETE FROM ${DocsService.sqlitebTableName} WHERE startUrl = ? AND embeddingsProviderId = ?`,
1325 startUrl,
1326 this.config.selectedModelByRole.embed.embeddingId,
1327 );
1328 }
1329
1330 private deleteFromConfig(startUrl: string) {
1331 const doesDocExist = this.config.docs?.some(
1332 (doc) => doc.startUrl === startUrl,
1333 );
1334 if (doesDocExist) {
1335 editConfigFile(
1336 (config) => ({
1337 ...config,
1338 docs: config.docs?.filter((doc) => doc.startUrl !== startUrl) || [],
1339 }),
1340 (config) => ({
1341 ...config,
1342 docs:
1343 config.docs?.filter(
1344 (doc) => "startUrl" in doc && doc.startUrl !== startUrl,
1345 ) || [],
1346 }),
1347 );
1348 }
1349 }
1350
1351 private async deleteIndexes(startUrl: string) {
1352 await this.deleteEmbeddingsFromLance(startUrl);
1353 await this.deleteMetadataFromSqlite(startUrl);
1354 }
1355
1356 async delete(startUrl: string) {
1357 this.docsIndexingQueue.delete(startUrl);
1358 this.abort(startUrl);
1359 await this.deleteIndexes(startUrl);
1360 this.deleteFromConfig(startUrl);
1361 this.messenger?.send("refreshSubmenuItems", {
1362 providers: ["docs"],
1363 });
1364 this.statuses.delete(startUrl);
1365 }
1366}