Elffuss BraidHub

kikocis/continue public

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