Elffuss BraidHub

kikocis/continue public

deff15df45d1 · 33.5 KiBRawPermalink
1import { fetchwithRequestOptions } from "@continuedev/fetch";
2import * as URI from "uri-js";
3import { v4 as uuidv4 } from "uuid";
4
5import { CompletionProvider } from "./autocomplete/CompletionProvider";
6import { ConfigHandler } from "./config/ConfigHandler";
7import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
8import { addModel, deleteModel } from "./config/util";
9import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
10import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
11import { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
12import { ContinueServerClient } from "./continueServer/stubs/client";
13import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
14import { getControlPlaneEnv } from "./control-plane/env";
15import { DevDataSqliteDb } from "./data/devdataSqlite";
16import { DataLogger } from "./data/log";
17import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
18import DocsService from "./indexing/docs/DocsService";
19import { countTokens } from "./llm/countTokens";
20import Ollama from "./llm/llms/Ollama";
21import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
22import { callTool } from "./tools/callTool";
23import { ChatDescriber } from "./util/chatDescriber";
24import { clipboardCache } from "./util/clipboardCache";
25import { GlobalContext } from "./util/GlobalContext";
26import historyManager from "./util/history";
27import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
28import { Telemetry } from "./util/posthog";
29import {
30 isProcessBackgrounded,
31 markProcessAsBackgrounded,
32} from "./util/processTerminalBackgroundStates";
33import { getSymbolsForManyFiles } from "./util/treeSitter";
34import { TTS } from "./util/tts";
35
36import {
37 ContextItemWithId,
38 IdeSettings,
39 ModelDescription,
40 RangeInFile,
41 type ContextItem,
42 type ContextItemId,
43 type IDE,
44 type IndexingProgressUpdate,
45} from ".";
46
47import { ConfigYaml } from "@continuedev/config-yaml";
48import { isLocalAssistantFile } from "./config/loadLocalAssistants";
49import {
50 setupBestConfig,
51 setupLocalConfig,
52 setupQuickstartConfig,
53} from "./config/onboarding";
54import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
55import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
56import { streamDiffLines } from "./edit/streamDiffLines";
57import { shouldIgnore } from "./indexing/shouldIgnore";
58import { walkDirCache } from "./indexing/walkDir";
59import { LLMError } from "./llm";
60import { LLMLogger } from "./llm/logger";
61import { llmStreamChat } from "./llm/streamChat";
62import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
63import type { IMessenger, Message } from "./protocol/messenger";
64import { StreamAbortManager } from "./util/abortManager";
65
66export class Core {
67 configHandler: ConfigHandler;
68 codebaseIndexerPromise: Promise<CodebaseIndexer>;
69 completionProvider: CompletionProvider;
70 continueServerClientPromise: Promise<ContinueServerClient>;
71 codebaseIndexingState: IndexingProgressUpdate;
72 private docsService: DocsService;
73 private globalContext = new GlobalContext();
74 llmLogger = new LLMLogger();
75
76 private readonly indexingPauseToken = new PauseToken(
77 this.globalContext.get("indexingPaused") === true,
78 );
79
80 private messageAbortControllers = new Map<string, AbortController>();
81 private addMessageAbortController(id: string): AbortController {
82 const controller = new AbortController();
83 this.messageAbortControllers.set(id, controller);
84 controller.signal.addEventListener("abort", () => {
85 this.messageAbortControllers.delete(id);
86 });
87 return controller;
88 }
89 private abortById(messageId: string) {
90 this.messageAbortControllers.get(messageId)?.abort();
91 }
92
93 invoke<T extends keyof ToCoreProtocol>(
94 messageType: T,
95 data: ToCoreProtocol[T][0],
96 ): ToCoreProtocol[T][1] {
97 return this.messenger.invoke(messageType, data);
98 }
99
100 send<T extends keyof FromCoreProtocol>(
101 messageType: T,
102 data: FromCoreProtocol[T][0],
103 messageId?: string,
104 ): string {
105 return this.messenger.send(messageType, data, messageId);
106 }
107
108 // TODO: It shouldn't actually need an IDE type, because this can happen
109 // through the messenger (it does in the case of any non-VS Code IDEs already)
110 constructor(
111 private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
112 private readonly ide: IDE,
113 ) {
114 // Ensure .continue directory is created
115 migrateV1DevDataFiles();
116
117 this.codebaseIndexingState = {
118 status: "loading",
119 desc: "loading",
120 progress: 0,
121 };
122
123 const ideInfoPromise = messenger.request("getIdeInfo", undefined);
124 const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
125 const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
126 silent: true,
127 useOnboarding: false,
128 });
129
130 this.configHandler = new ConfigHandler(
131 this.ide,
132 ideSettingsPromise,
133 this.llmLogger,
134 sessionInfoPromise,
135 );
136
137 this.docsService = DocsService.createSingleton(
138 this.configHandler,
139 this.ide,
140 this.messenger,
141 );
142
143 MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
144 await this.configHandler.reloadConfig();
145 };
146
147 this.configHandler.onConfigUpdate(async (result) => {
148 const serializedResult = await this.configHandler.getSerializedConfig();
149 this.messenger.send("configUpdate", {
150 result: serializedResult,
151 profileId:
152 this.configHandler.currentProfile?.profileDescription.id || null,
153 organizations: this.configHandler.getSerializedOrgs(),
154 selectedOrgId: this.configHandler.currentOrg.id,
155 });
156
157 // update additional submenu context providers registered via VSCode API
158 const additionalProviders =
159 this.configHandler.getAdditionalSubmenuContextProviders();
160 if (additionalProviders.length > 0) {
161 this.messenger.send("refreshSubmenuItems", {
162 providers: additionalProviders,
163 });
164 }
165 });
166
167 // Dev Data Logger
168 const dataLogger = DataLogger.getInstance();
169 dataLogger.core = this;
170 dataLogger.ideInfoPromise = ideInfoPromise;
171 dataLogger.ideSettingsPromise = ideSettingsPromise;
172
173 // Codebase Indexer and ContinueServerClient depend on IdeSettings
174 let codebaseIndexerResolve: (_: any) => void | undefined;
175 this.codebaseIndexerPromise = new Promise(
176 async (resolve) => (codebaseIndexerResolve = resolve),
177 );
178
179 let continueServerClientResolve: (_: any) => void | undefined;
180 this.continueServerClientPromise = new Promise(
181 (resolve) => (continueServerClientResolve = resolve),
182 );
183
184 void ideSettingsPromise.then((ideSettings) => {
185 const continueServerClient = new ContinueServerClient(
186 ideSettings.remoteConfigServerUrl,
187 ideSettings.userToken,
188 );
189 continueServerClientResolve(continueServerClient);
190
191 codebaseIndexerResolve(
192 new CodebaseIndexer(
193 this.configHandler,
194 this.ide,
195 this.indexingPauseToken,
196 continueServerClient,
197 ),
198 );
199
200 // Index on initialization
201 void this.ide.getWorkspaceDirs().then(async (dirs) => {
202 // Respect pauseCodebaseIndexOnStart user settings
203 if (ideSettings.pauseCodebaseIndexOnStart) {
204 this.indexingPauseToken.paused = true;
205 void this.messenger.request("indexProgress", {
206 progress: 0,
207 desc: "Initial Indexing Skipped",
208 status: "paused",
209 });
210 return;
211 }
212
213 void this.refreshCodebaseIndex(dirs);
214 });
215 });
216
217 const getLlm = async () => {
218 const { config } = await this.configHandler.loadConfig();
219 if (!config) {
220 return undefined;
221 }
222 return config.selectedModelByRole.autocomplete ?? undefined;
223 };
224 this.completionProvider = new CompletionProvider(
225 this.configHandler,
226 ide,
227 getLlm,
228 (e) => {},
229 (..._) => Promise.resolve([]),
230 );
231
232 this.registerMessageHandlers(ideSettingsPromise);
233 }
234
235 /* eslint-disable max-lines-per-function */
236 private registerMessageHandlers(ideSettingsPromise: Promise<IdeSettings>) {
237 const on = this.messenger.on.bind(this.messenger);
238
239 // Note, VsCode's in-process messenger doesn't do anything with this
240 // It will only show for jetbrains
241 this.messenger.onError((message, err) => {
242 void Telemetry.capture("core_messenger_error", {
243 message: err.message,
244 stack: err.stack,
245 });
246
247 // just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
248 if (
249 ["llm/streamChat", "chatDescriber/describe"].includes(
250 message.messageType,
251 )
252 ) {
253 return;
254 } else {
255 void this.ide.showToast("error", err.message);
256 }
257 });
258
259 on("abort", (msg) => {
260 this.abortById(msg.data ?? msg.messageId);
261 });
262
263 on("ping", (msg) => {
264 if (msg.data !== "ping") {
265 throw new Error("ping message incorrect");
266 }
267 return "pong";
268 });
269
270 // History
271 on("history/list", (msg) => {
272 return historyManager.list(msg.data);
273 });
274
275 on("history/delete", (msg) => {
276 historyManager.delete(msg.data.id);
277 });
278
279 on("history/load", (msg) => {
280 return historyManager.load(msg.data.id);
281 });
282
283 on("history/save", (msg) => {
284 historyManager.save(msg.data);
285 });
286
287 on("history/clear", (msg) => {
288 historyManager.clearAll();
289 });
290
291 on("devdata/log", async (msg) => {
292 void DataLogger.getInstance().logDevData(msg.data);
293 });
294
295 on("config/addModel", (msg) => {
296 const model = msg.data.model;
297 addModel(model, msg.data.role);
298 void this.configHandler.reloadConfig();
299 });
300
301 on("config/deleteModel", (msg) => {
302 deleteModel(msg.data.title);
303 void this.configHandler.reloadConfig();
304 });
305
306 on("config/newPromptFile", async (msg) => {
307 const { config } = await this.configHandler.loadConfig();
308 await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
309 await this.configHandler.reloadConfig();
310 });
311
312 on("config/addLocalWorkspaceBlock", async (msg) => {
313 await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
314 await this.configHandler.reloadConfig();
315 });
316
317 on("config/openProfile", async (msg) => {
318 await this.configHandler.openConfigProfile(msg.data.profileId);
319 });
320
321 on("config/reload", async (msg) => {
322 void this.configHandler.reloadConfig();
323 return await this.configHandler.getSerializedConfig();
324 });
325
326 on("config/ideSettingsUpdate", async (msg) => {
327 await this.configHandler.updateIdeSettings(msg.data);
328 });
329
330 on("config/refreshProfiles", async (msg) => {
331 const { selectOrgId, selectProfileId } = msg.data ?? {};
332 await this.configHandler.refreshAll();
333 if (selectOrgId) {
334 await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
335 } else if (selectProfileId) {
336 await this.configHandler.setSelectedProfileId(selectProfileId);
337 }
338 });
339
340 on("config/updateSharedConfig", async (msg) => {
341 const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
342 await this.configHandler.reloadConfig();
343 return newSharedConfig;
344 });
345
346 on("config/updateSelectedModel", async (msg) => {
347 const newSelectedModels = this.globalContext.updateSelectedModel(
348 msg.data.profileId,
349 msg.data.role,
350 msg.data.title,
351 );
352 await this.configHandler.reloadConfig();
353 return newSelectedModels;
354 });
355
356 on("controlPlane/openUrl", async (msg) => {
357 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
358 let url = `${env.APP_URL}${msg.data.path}`;
359 if (msg.data.orgSlug) {
360 url += `?org=${msg.data.orgSlug}`;
361 }
362 await this.messenger.request("openUrl", url);
363 });
364
365 on("mcp/reloadServer", async (msg) => {
366 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
367 });
368 // Context providers
369 on("context/addDocs", async (msg) => {
370 void this.docsService.indexAndAdd(msg.data);
371 });
372
373 on("context/removeDocs", async (msg) => {
374 await this.docsService.delete(msg.data.startUrl);
375 });
376
377 on("context/indexDocs", async (msg) => {
378 await this.docsService.syncDocsWithPrompt(msg.data.reIndex);
379 });
380
381 on("context/loadSubmenuItems", async (msg) => {
382 const { config } = await this.configHandler.loadConfig();
383 if (!config) {
384 return [];
385 }
386
387 try {
388 const items = await config.contextProviders
389 ?.find((provider) => provider.description.title === msg.data.title)
390 ?.loadSubmenuItems({
391 config,
392 ide: this.ide,
393 fetch: (url, init) =>
394 fetchwithRequestOptions(url, init, config.requestOptions),
395 });
396 return items || [];
397 } catch (e) {
398 console.error(e);
399 return [];
400 }
401 });
402
403 on("context/getContextItems", this.getContextItems.bind(this));
404
405 on("context/getSymbolsForFiles", async (msg) => {
406 const { uris } = msg.data;
407 return await getSymbolsForManyFiles(uris, this.ide);
408 });
409
410 on("config/getSerializedProfileInfo", async (msg) => {
411 return {
412 result: await this.configHandler.getSerializedConfig(),
413 profileId:
414 this.configHandler.currentProfile?.profileDescription.id ?? null,
415 organizations: this.configHandler.getSerializedOrgs(),
416 selectedOrgId: this.configHandler.currentOrg.id,
417 };
418 });
419
420 on("clipboardCache/add", (msg) => {
421 const added = clipboardCache.add(uuidv4(), msg.data.content);
422 if (added) {
423 this.messenger.send("refreshSubmenuItems", {
424 providers: ["clipboard"],
425 });
426 }
427 });
428
429 on("llm/streamChat", (msg) => {
430 const abortController = this.addMessageAbortController(msg.messageId);
431 return llmStreamChat(
432 this.configHandler,
433 abortController,
434 msg,
435 this.ide,
436 this.messenger,
437 );
438 });
439
440 on("llm/complete", async (msg) => {
441 const { config } = await this.configHandler.loadConfig();
442 const model = config?.selectedModelByRole.chat;
443 if (!model) {
444 throw new Error("No chat model selected");
445 }
446 const abortController = this.addMessageAbortController(msg.messageId);
447
448 const completion = await model.complete(
449 msg.data.prompt,
450 abortController.signal,
451 msg.data.completionOptions,
452 );
453 return completion;
454 });
455 on("llm/listModels", this.handleListModels.bind(this));
456
457 // Provide messenger to utils so they can interact with GUI + state
458 TTS.messenger = this.messenger;
459 ChatDescriber.messenger = this.messenger;
460
461 on("tts/kill", async () => {
462 void TTS.kill();
463 });
464
465 on("chatDescriber/describe", async (msg) => {
466 const currentModel = (await this.configHandler.loadConfig()).config
467 ?.selectedModelByRole.chat;
468
469 if (!currentModel) {
470 throw new Error("No chat model selected");
471 }
472
473 return await ChatDescriber.describe(currentModel, {}, msg.data.text);
474 });
475
476 // Autocomplete
477 on("autocomplete/complete", async (msg) => {
478 const outcome =
479 await this.completionProvider.provideInlineCompletionItems(
480 msg.data,
481 undefined,
482 );
483 return outcome ? [outcome.completion] : [];
484 });
485 on("autocomplete/accept", async (msg) => {
486 this.completionProvider.accept(msg.data.completionId);
487 });
488 on("autocomplete/cancel", async (msg) => {
489 this.completionProvider.cancel();
490 });
491
492 on("streamDiffLines", async (msg) => {
493 const { config } = await this.configHandler.loadConfig();
494 if (!config) {
495 throw new Error("Failed to load config");
496 }
497
498 const { data } = msg;
499
500 // Title can be an edit, chat, or apply model
501 // Fall back to chat
502 const llm =
503 config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
504 config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
505 config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
506 config.selectedModelByRole.chat;
507
508 if (!llm) {
509 throw new Error("No model selected");
510 }
511
512 return streamDiffLines({
513 highlighted: data.highlighted,
514 prefix: data.prefix,
515 suffix: data.suffix,
516 llm,
517 // rules included for edit, NOT apply
518 rulesToInclude: data.includeRulesInSystemMessage
519 ? config.rules
520 : undefined,
521 input: data.input,
522 language: data.language,
523 onlyOneInsertion: false,
524 overridePrompt: undefined,
525 abortControllerId: data.fileUri ?? "current-file-stream", // not super important since currently cancelling apply will cancel all streams it's one file at a time
526 });
527 });
528
529 on("cancelApply", async (msg) => {
530 const abortManager = StreamAbortManager.getInstance();
531 abortManager.clear();
532 });
533
534 on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
535
536 on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this));
537
538 on("stats/getTokensPerDay", async (msg) => {
539 const rows = await DevDataSqliteDb.getTokensPerDay();
540 return rows;
541 });
542 on("stats/getTokensPerModel", async (msg) => {
543 const rows = await DevDataSqliteDb.getTokensPerModel();
544 return rows;
545 });
546
547 on("index/forceReIndex", async ({ data }) => {
548 const { config } = await this.configHandler.loadConfig();
549 if (!config || config.disableIndexing) {
550 return; // TODO silent in case of commands?
551 }
552 walkDirCache.invalidate();
553 if (data?.shouldClearIndexes) {
554 const codebaseIndexer = await this.codebaseIndexerPromise;
555 await codebaseIndexer.clearIndexes();
556 }
557
558 const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
559 await this.refreshCodebaseIndex(dirs);
560 });
561 on("index/setPaused", (msg) => {
562 this.globalContext.update("indexingPaused", msg.data);
563 this.indexingPauseToken.paused = msg.data;
564 });
565 on("index/indexingProgressBarInitialized", async (msg) => {
566 // Triggered when progress bar is initialized.
567 // If a non-default state has been stored, update the indexing display to that state
568 if (this.codebaseIndexingState.status !== "loading") {
569 void this.messenger.request(
570 "indexProgress",
571 this.codebaseIndexingState,
572 );
573 }
574 });
575
576 // File changes - TODO - remove remaining logic for these from IDEs where possible
577 on("files/changed", this.handleFilesChanged.bind(this));
578 const refreshIfNotIgnored = async (uris: string[]) => {
579 const toRefresh: string[] = [];
580 for (const uri of uris) {
581 const ignore = await shouldIgnore(uri, this.ide);
582 if (!ignore) {
583 toRefresh.push(uri);
584 }
585 }
586 if (toRefresh.length > 0) {
587 this.messenger.send("refreshSubmenuItems", {
588 providers: ["file"],
589 });
590 const { config } = await this.configHandler.loadConfig();
591 if (config && !config.disableIndexing) {
592 await this.refreshCodebaseIndexFiles(toRefresh);
593 }
594 }
595 };
596
597 on("files/created", async ({ data }) => {
598 if (data?.uris?.length) {
599 walkDirCache.invalidate();
600 void refreshIfNotIgnored(data.uris);
601
602 // If it's a local assistant being created, we want to reload all assistants so it shows up in the list
603 let localAssistantCreated = false;
604 for (const uri of data.uris) {
605 if (isLocalAssistantFile(uri)) {
606 localAssistantCreated = true;
607 }
608 }
609 if (localAssistantCreated) {
610 await this.configHandler.refreshAll();
611 }
612 }
613 });
614
615 on("files/deleted", async ({ data }) => {
616 if (data?.uris?.length) {
617 walkDirCache.invalidate();
618 void refreshIfNotIgnored(data.uris);
619 }
620 });
621
622 on("files/closed", async ({ data }) => {
623 if (data.uris) {
624 this.messenger.send("didCloseFiles", {
625 uris: data.uris,
626 });
627 }
628 });
629
630 on("files/opened", async () => {});
631
632 // Docs, etc. indexing
633 on("indexing/reindex", async (msg) => {
634 if (msg.data.type === "docs") {
635 void this.docsService.reindexDoc(msg.data.id);
636 }
637 });
638 on("indexing/abort", async (msg) => {
639 if (msg.data.type === "docs") {
640 this.docsService.abort(msg.data.id);
641 }
642 });
643 on("indexing/setPaused", async (msg) => {
644 if (msg.data.type === "docs") {
645 }
646 });
647 on("docs/initStatuses", async (msg) => {
648 void this.docsService.initStatuses();
649 });
650 on("docs/getDetails", async (msg) => {
651 return await this.docsService.getDetails(msg.data.startUrl);
652 });
653
654 on("didChangeSelectedProfile", async (msg) => {
655 if (msg.data.id) {
656 await this.configHandler.setSelectedProfileId(msg.data.id);
657 }
658 });
659
660 on("didChangeSelectedOrg", async (msg) => {
661 if (msg.data.id) {
662 await this.configHandler.setSelectedOrgId(
663 msg.data.id,
664 msg.data.profileId || undefined,
665 );
666 }
667 });
668
669 on("didChangeControlPlaneSessionInfo", async (msg) => {
670 this.messenger.send("sessionUpdate", {
671 sessionInfo: msg.data.sessionInfo,
672 });
673 await this.configHandler.updateControlPlaneSessionInfo(
674 msg.data.sessionInfo,
675 );
676 });
677
678 on("auth/getAuthUrl", async (msg) => {
679 const url = await getAuthUrlForTokenPage(
680 ideSettingsPromise,
681 msg.data.useOnboarding,
682 );
683 return { url };
684 });
685
686 on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
687 try {
688 const ignore = await shouldIgnore(filepath, this.ide);
689 if (!ignore) {
690 recentlyEditedFilesCache.set(filepath, filepath);
691 }
692 } catch (e) {
693 console.error(
694 `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
695 );
696 }
697 });
698
699 on("tools/call", async ({ data: { toolCall } }) => {
700 const { config } = await this.configHandler.loadConfig();
701 if (!config) {
702 throw new Error("Config not loaded");
703 }
704
705 const tool = config.tools.find(
706 (t) => t.function.name === toolCall.function.name,
707 );
708
709 if (!tool) {
710 throw new Error(`Tool ${toolCall.function.name} not found`);
711 }
712
713 if (!config.selectedModelByRole.chat) {
714 throw new Error("No chat model selected");
715 }
716
717 // Define a callback for streaming output updates
718 const onPartialOutput = (params: {
719 toolCallId: string;
720 contextItems: ContextItem[];
721 }) => {
722 this.messenger.send("toolCallPartialOutput", params);
723 };
724
725 return await callTool(tool, toolCall.function.arguments, {
726 ide: this.ide,
727 llm: config.selectedModelByRole.chat,
728 fetch: (url, init) =>
729 fetchwithRequestOptions(url, init, config.requestOptions),
730 tool,
731 toolCallId: toolCall.id,
732 onPartialOutput,
733 });
734 });
735
736 on("isItemTooBig", async ({ data: { item } }) => {
737 return this.isItemTooBig(item);
738 });
739
740 // Process state handlers
741 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
742 markProcessAsBackgrounded(toolCallId);
743 });
744
745 on(
746 "process/isBackgrounded",
747 async ({ data: { toolCallId }, messageId }) => {
748 const isBackgrounded = isProcessBackgrounded(toolCallId);
749 return isBackgrounded; // Return true to indicate the message was handled successfully
750 },
751 );
752 }
753
754 private async isItemTooBig(item: ContextItemWithId) {
755 const { config } = await this.configHandler.loadConfig();
756 if (!config) {
757 return false;
758 }
759
760 const llm = config?.selectedModelByRole.chat;
761 if (!llm) {
762 throw new Error("No chat model selected");
763 }
764
765 const tokens = countTokens(item.content, llm.model);
766
767 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
768 return true;
769 }
770
771 return false;
772 }
773
774 private handleAddAutocompleteModel(
775 msg: Message<{
776 model: ModelDescription;
777 }>,
778 ) {
779 const model = msg.data.model;
780 editConfigFile(
781 (config) => {
782 return {
783 ...config,
784 tabAutocompleteModel: model,
785 };
786 },
787 (config) => ({
788 ...config,
789 models: [
790 ...(config.models ?? []),
791 {
792 name: model.title,
793 provider: model.provider,
794 model: model.model,
795 apiKey: model.apiKey,
796 roles: ["autocomplete"],
797 apiBase: model.apiBase,
798 },
799 ],
800 }),
801 );
802 void this.configHandler.reloadConfig();
803 }
804
805 private async handleFilesChanged({
806 data,
807 }: Message<{
808 uris?: string[];
809 }>) {
810 if (data?.uris?.length) {
811 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
812 for (const uri of data.uris) {
813 const currentProfileUri =
814 this.configHandler.currentProfile?.profileDescription.uri ?? "";
815
816 if (URI.equal(uri, currentProfileUri)) {
817 // Trigger a toast notification to provide UI feedback that config has been updated
818 const showToast =
819 this.globalContext.get("showConfigUpdateToast") ?? true;
820 if (showToast) {
821 const selection = await this.ide.showToast(
822 "info",
823 "Config updated",
824 "Don't show again",
825 );
826 if (selection === "Don't show again") {
827 this.globalContext.update("showConfigUpdateToast", false);
828 }
829 }
830 await this.configHandler.reloadConfig();
831 continue;
832 }
833
834 if (
835 uri.endsWith(".continuerc.json") ||
836 uri.endsWith(".prompt") ||
837 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
838 (uri.includes(".continue") && uri.endsWith(".yaml"))
839 ) {
840 await this.configHandler.reloadConfig();
841 } else if (
842 uri.endsWith(".continueignore") ||
843 uri.endsWith(".gitignore")
844 ) {
845 // Reindex the workspaces
846 this.invoke("index/forceReIndex", {
847 shouldClearIndexes: true,
848 });
849 } else {
850 const { config } = await this.configHandler.loadConfig();
851 if (config && !config.disableIndexing) {
852 // Reindex the file
853 const ignore = await shouldIgnore(uri, this.ide);
854 if (!ignore) {
855 await this.refreshCodebaseIndexFiles([uri]);
856 }
857 }
858 }
859 }
860 }
861 }
862
863 private async handleListModels(msg: Message<{ title: string }>) {
864 const { config } = await this.configHandler.loadConfig();
865 if (!config) {
866 return [];
867 }
868
869 const model =
870 config.modelsByRole.chat.find(
871 (model) => model.title === msg.data.title,
872 ) ??
873 config.modelsByRole.chat.find((model) =>
874 model.title?.startsWith(msg.data.title),
875 );
876
877 try {
878 if (model) {
879 return await model.listModels();
880 } else {
881 if (msg.data.title === "Ollama") {
882 const models = await new Ollama({ model: "" }).listModels();
883 return models;
884 } else {
885 return undefined;
886 }
887 }
888 } catch (e) {
889 console.debug(`Error listing Ollama models: ${e}`);
890 return undefined;
891 }
892 }
893
894 private async handleCompleteOnboarding(msg: Message<{ mode: string }>) {
895 const mode = msg.data.mode;
896
897 if (mode === "Custom") {
898 return;
899 }
900
901 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
902
903 switch (mode) {
904 case "Local":
905 editConfigYamlCallback = setupLocalConfig;
906 break;
907
908 case "Quickstart":
909 editConfigYamlCallback = setupQuickstartConfig;
910 break;
911
912 case "Best":
913 editConfigYamlCallback = setupBestConfig;
914 break;
915
916 default:
917 console.error(`Invalid mode: ${mode}`);
918 editConfigYamlCallback = (config) => config;
919 }
920
921 editConfigFile((c) => c, editConfigYamlCallback);
922
923 void this.configHandler.reloadConfig();
924 }
925
926 private getContextItems = async (
927 msg: Message<{
928 name: string;
929 query: string;
930 fullInput: string;
931 selectedCode: RangeInFile[];
932 }>,
933 ) => {
934 const { config } = await this.configHandler.loadConfig();
935 if (!config) {
936 return [];
937 }
938
939 const { name, query, fullInput, selectedCode } = msg.data;
940
941 const llm = (await this.configHandler.loadConfig()).config
942 ?.selectedModelByRole.chat;
943
944 if (!llm) {
945 throw new Error("No chat model selected");
946 }
947
948 const provider =
949 config.contextProviders?.find(
950 (provider) => provider.description.title === name,
951 ) ??
952 [
953 // user doesn't need these in their config.json for the shortcuts to work
954 // option+enter
955 new CurrentFileContextProvider({}),
956 // cmd+enter
957 new CodebaseContextProvider({}),
958 ].find((provider) => provider.description.title === name);
959 if (!provider) {
960 return [];
961 }
962
963 try {
964 const id: ContextItemId = {
965 providerTitle: provider.description.title,
966 itemId: uuidv4(),
967 };
968
969 const items = await provider.getContextItems(query, {
970 config,
971 llm,
972 embeddingsProvider: config.selectedModelByRole.embed,
973 fullInput,
974 ide: this.ide,
975 selectedCode,
976 reranker: config.selectedModelByRole.rerank,
977 fetch: (url, init) =>
978 fetchwithRequestOptions(url, init, config.requestOptions),
979 });
980
981 void Telemetry.capture(
982 "useContextProvider",
983 {
984 name: provider.description.title,
985 },
986 true,
987 );
988
989 return items.map((item) => ({
990 ...item,
991 id,
992 }));
993 } catch (e) {
994 let knownError = false;
995
996 if (e instanceof Error) {
997 // After removing transformers JS embeddings provider from jetbrains
998 // Should no longer see this error
999 // if (e.message.toLowerCase().includes("embeddings provider")) {
1000 // knownError = true;
1001 // const toastOption = "See Docs";
1002 // void this.ide
1003 // .showToast(
1004 // "error",
1005 // `Set up an embeddings model to use @${name}`,
1006 // toastOption,
1007 // )
1008 // .then((userSelection) => {
1009 // if (userSelection === toastOption) {
1010 // void this.ide.openUrl(
1011 // "https://docs.continue.dev/customize/model-roles/embeddings",
1012 // );
1013 // }
1014 // });
1015 // }
1016 }
1017 if (!knownError) {
1018 void this.ide.showToast(
1019 "error",
1020 `Error getting context items from ${name}: ${e}`,
1021 );
1022 }
1023 return [];
1024 }
1025 };
1026
1027 private indexingCancellationController: AbortController | undefined;
1028 private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
1029 console.debug(
1030 "Indexing failed with error: ",
1031 update.desc,
1032 update.debugInfo,
1033 );
1034 void Telemetry.capture(
1035 "indexing_error",
1036 {
1037 error: update.desc,
1038 stack: update.debugInfo,
1039 },
1040 false,
1041 );
1042 }
1043
1044 private async refreshCodebaseIndex(paths: string[]) {
1045 if (this.indexingCancellationController) {
1046 this.indexingCancellationController.abort();
1047 }
1048 this.indexingCancellationController = new AbortController();
1049 try {
1050 for await (const update of (
1051 await this.codebaseIndexerPromise
1052 ).refreshDirs(paths, this.indexingCancellationController.signal)) {
1053 let updateToSend = { ...update };
1054
1055 void this.messenger.request("indexProgress", updateToSend);
1056 this.codebaseIndexingState = updateToSend;
1057
1058 if (update.status === "failed") {
1059 void this.sendIndexingErrorTelemetry(update);
1060 }
1061 }
1062 } catch (e: any) {
1063 console.log(`Failed refreshing codebase index directories : ${e}`);
1064 this.handleIndexingError(e);
1065 }
1066
1067 this.messenger.send("refreshSubmenuItems", {
1068 providers: "dependsOnIndexing",
1069 });
1070 this.indexingCancellationController = undefined;
1071 }
1072
1073 private async refreshCodebaseIndexFiles(files: string[]) {
1074 // Can be cancelled by codebase index but not vice versa
1075 if (
1076 this.indexingCancellationController &&
1077 !this.indexingCancellationController.signal.aborted
1078 ) {
1079 return;
1080 }
1081 this.indexingCancellationController = new AbortController();
1082 try {
1083 for await (const update of (
1084 await this.codebaseIndexerPromise
1085 ).refreshFiles(files)) {
1086 let updateToSend = { ...update };
1087
1088 void this.messenger.request("indexProgress", updateToSend);
1089 this.codebaseIndexingState = updateToSend;
1090
1091 if (update.status === "failed") {
1092 void this.sendIndexingErrorTelemetry(update);
1093 }
1094 }
1095 } catch (e: any) {
1096 console.log(`Failed refreshing codebase index files : ${e}`);
1097 this.handleIndexingError(e);
1098 }
1099
1100 this.messenger.send("refreshSubmenuItems", {
1101 providers: "dependsOnIndexing",
1102 });
1103 this.indexingCancellationController = undefined;
1104 }
1105
1106 // private
1107 handleIndexingError(e: any) {
1108 if (e instanceof LLMError) {
1109 // Need to report this specific error to the IDE for special handling
1110 void this.messenger.request("reportError", e);
1111 }
1112 // broadcast indexing error
1113 let updateToSend: IndexingProgressUpdate = {
1114 progress: 0,
1115 status: "failed",
1116 desc: e.message,
1117 };
1118 void this.messenger.request("indexProgress", updateToSend);
1119 this.codebaseIndexingState = updateToSend;
1120 void this.sendIndexingErrorTelemetry(updateToSend);
1121 }
1122}