Elffuss BraidHub

kikocis/continue public

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