Elffuss BraidHub

kikocis/continue public

ea05c35331da · 43.2 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 {
7 openedFilesLruCache,
8 prevFilepaths,
9} from "./autocomplete/util/openedFilesLruCache";
10import { ConfigHandler } from "./config/ConfigHandler";
11import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
12import { addModel, deleteModel } from "./config/util";
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 { EditAggregator } from "./nextEdit/context/aggregateEdits";
22import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
23import { callTool } from "./tools/callTool";
24import { ChatDescriber } from "./util/chatDescriber";
25import { compactConversation } from "./util/conversationCompaction";
26import { GlobalContext } from "./util/GlobalContext";
27import historyManager from "./util/history";
28import { editConfigFile, migrateV1DevDataFiles } from "./util/paths";
29import { Telemetry } from "./util/posthog";
30import {
31 isProcessBackgrounded,
32 markProcessAsBackgrounded,
33} from "./util/processTerminalBackgroundStates";
34import { getSymbolsForManyFiles } from "./util/treeSitter";
35import { TTS } from "./util/tts";
36
37import {
38 CompleteOnboardingPayload,
39 ContextItemId,
40 ContextItemWithId,
41 IdeSettings,
42 ModelDescription,
43 Position,
44 RangeInFile,
45 ToolCall,
46 type ContextItem,
47 type IDE,
48} from ".";
49
50import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
51import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
52import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
53import { createNewAssistantFile } from "./config/createNewAssistantFile";
54import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
55import { CodebaseRulesCache } from "./config/markdown/loadCodebaseRules";
56import {
57 setupLocalConfig,
58 setupProviderConfig,
59 setupQuickstartConfig,
60} from "./config/onboarding";
61import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
62import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
63import { performAuth, removeMCPAuth } from "./context/mcp/MCPOauth";
64import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
65import { ApplyAbortManager } from "./edit/applyAbortManager";
66import { streamDiffLines } from "./edit/streamDiffLines";
67import { shouldIgnore } from "./indexing/shouldIgnore";
68import { walkDirCache } from "./indexing/walkDir";
69import { LLMLogger } from "./llm/logger";
70import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
71import { llmStreamChat } from "./llm/streamChat";
72import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
73import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
74import { PrefetchQueue } from "./nextEdit/NextEditPrefetchQueue";
75import { NextEditProvider } from "./nextEdit/NextEditProvider";
76import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
77import { OnboardingModes } from "./protocol/core";
78import type { IMessenger, Message } from "./protocol/messenger";
79import { Logger } from "./util/Logger.js";
80import { getUriPathBasename } from "./util/uri";
81
82const hasRulesFiles = (uris: string[]): boolean => {
83 for (const uri of uris) {
84 const filename = getUriPathBasename(uri);
85 if (filename === RULES_MARKDOWN_FILENAME) {
86 return true;
87 }
88 }
89 return false;
90};
91
92export class Core {
93 configHandler: ConfigHandler;
94 codeBaseIndexer: CodebaseIndexer;
95 completionProvider: CompletionProvider;
96 nextEditProvider: NextEditProvider;
97 private docsService: DocsService;
98 private globalContext = new GlobalContext();
99 llmLogger = new LLMLogger();
100
101 private messageAbortControllers = new Map<string, AbortController>();
102 private addMessageAbortController(id: string): AbortController {
103 const controller = new AbortController();
104 this.messageAbortControllers.set(id, controller);
105 controller.signal.addEventListener("abort", () => {
106 this.messageAbortControllers.delete(id);
107 });
108 return controller;
109 }
110 private abortById(messageId: string) {
111 this.messageAbortControllers.get(messageId)?.abort();
112 }
113
114 invoke<T extends keyof ToCoreProtocol>(
115 messageType: T,
116 data: ToCoreProtocol[T][0],
117 ): ToCoreProtocol[T][1] {
118 return this.messenger.invoke(messageType, data);
119 }
120
121 send<T extends keyof FromCoreProtocol>(
122 messageType: T,
123 data: FromCoreProtocol[T][0],
124 messageId?: string,
125 ): string {
126 return this.messenger.send(messageType, data, messageId);
127 }
128
129 // TODO: It shouldn't actually need an IDE type, because this can happen
130 // through the messenger (it does in the case of any non-VS Code IDEs already)
131 constructor(
132 private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
133 private readonly ide: IDE,
134 ) {
135 try {
136 // Ensure .continue directory is created
137 migrateV1DevDataFiles();
138
139 const ideInfoPromise = messenger.request("getIdeInfo", undefined);
140 const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
141 const initialSessionInfoPromise = messenger.request(
142 "getControlPlaneSessionInfo",
143 {
144 silent: true,
145 useOnboarding: false,
146 },
147 );
148
149 this.configHandler = new ConfigHandler(
150 this.ide,
151 this.llmLogger,
152 initialSessionInfoPromise,
153 );
154
155 this.docsService = DocsService.createSingleton(
156 this.configHandler,
157 this.ide,
158 this.messenger,
159 );
160
161 MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
162 void this.configHandler.reloadConfig("MCP Connections refreshed");
163
164 // Refresh @mention dropdown submenu items for MCP providers
165 const mcpManager = MCPManagerSingleton.getInstance();
166 const mcpProviderNames = Array.from(mcpManager.connections.keys()).map(
167 (mcpId) => `mcp-${mcpId}`,
168 );
169
170 if (mcpProviderNames.length > 0) {
171 this.messenger.send("refreshSubmenuItems", {
172 providers: mcpProviderNames,
173 });
174 }
175 };
176
177 this.configHandler.onConfigUpdate((result) => {
178 void (async () => {
179 const serializedResult =
180 await this.configHandler.getSerializedConfig();
181 this.messenger.send("configUpdate", {
182 result: serializedResult,
183 profileId:
184 this.configHandler.currentProfile?.profileDescription.id || null,
185 organizations: this.configHandler.getSerializedOrgs(),
186 selectedOrgId: this.configHandler.currentOrg?.id ?? null,
187 });
188
189 // update additional submenu context providers registered via VSCode API
190 const additionalProviders =
191 this.configHandler.getAdditionalSubmenuContextProviders();
192 if (additionalProviders.length > 0) {
193 this.messenger.send("refreshSubmenuItems", {
194 providers: additionalProviders,
195 });
196 }
197 })();
198 });
199
200 this.codeBaseIndexer = new CodebaseIndexer(
201 this.configHandler,
202 this.ide,
203 this.messenger,
204 this.globalContext.get("indexingPaused"),
205 );
206
207 // Dev Data Logger
208 const dataLogger = DataLogger.getInstance();
209 dataLogger.core = this;
210 dataLogger.ideInfoPromise = ideInfoPromise;
211 dataLogger.ideSettingsPromise = ideSettingsPromise;
212
213 void ideSettingsPromise.then((ideSettings) => {
214 // Index on initialization
215 void this.ide.getWorkspaceDirs().then(async (dirs) => {
216 // Respect pauseCodebaseIndexOnStart user settings
217 if (ideSettings.pauseCodebaseIndexOnStart) {
218 this.codeBaseIndexer.paused = true;
219 void this.messenger.request("indexProgress", {
220 progress: 0,
221 desc: "Initial Indexing Skipped",
222 status: "paused",
223 });
224 return;
225 }
226
227 void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
228 });
229 });
230
231 const getLlm = async () => {
232 const { config } = await this.configHandler.loadConfig();
233 if (!config) {
234 return undefined;
235 }
236 return config.selectedModelByRole.autocomplete ?? undefined;
237 };
238 this.completionProvider = new CompletionProvider(
239 this.configHandler,
240 ide,
241 getLlm,
242 (e) => {},
243 (..._) => Promise.resolve([]),
244 );
245
246 const codebaseRulesCache = CodebaseRulesCache.getInstance();
247 void codebaseRulesCache
248 .refresh(ide)
249 .catch((e) =>
250 Logger.error("Failed to initialize colocated rules cache"),
251 )
252 .then(() => {
253 void this.configHandler.reloadConfig(
254 "Initial codebase rules post-walkdir/load reload",
255 );
256 });
257 this.nextEditProvider = NextEditProvider.initialize(
258 this.configHandler,
259 ide,
260 getLlm,
261 (e) => {},
262 (..._) => Promise.resolve([]),
263 "fineTuned",
264 );
265
266 this.registerMessageHandlers(ideSettingsPromise);
267 } catch (error) {
268 Logger.error(error);
269 throw error; // Re-throw to prevent partially initialized core
270 }
271 }
272
273 /* eslint-disable max-lines-per-function */
274 private registerMessageHandlers(ideSettingsPromise: Promise<IdeSettings>) {
275 const on = this.messenger.on.bind(this.messenger);
276
277 // Note, VsCode's in-process messenger doesn't do anything with this
278 // It will only show for jetbrains
279 this.messenger.onError((message, err) => {
280 void Telemetry.capture("core_messenger_error", {
281 message: err.message,
282 stack: err.stack,
283 });
284
285 // just to prevent duplicate error messages in jetbrains (same logic in webview protocol)
286 if (
287 ["llm/streamChat", "chatDescriber/describe"].includes(
288 message.messageType,
289 )
290 ) {
291 return;
292 } else {
293 void this.ide.showToast("error", err.message);
294 }
295 });
296
297 on("abort", (msg) => {
298 this.abortById(msg.data ?? msg.messageId);
299 });
300
301 on("ping", (msg) => {
302 if (msg.data !== "ping") {
303 throw new Error("ping message incorrect");
304 }
305 return "pong";
306 });
307
308 // History
309 on("history/list", (msg) => {
310 return historyManager.list(msg.data);
311 });
312
313 on("history/delete", (msg) => {
314 historyManager.delete(msg.data.id);
315 });
316
317 on("history/load", (msg) => {
318 return historyManager.load(msg.data.id);
319 });
320
321 on("history/save", (msg) => {
322 historyManager.save(msg.data);
323 });
324
325 on("history/clear", (msg) => {
326 historyManager.clearAll();
327 });
328
329 on("devdata/log", async (msg) => {
330 void DataLogger.getInstance().logDevData(msg.data);
331 });
332
333 on("config/addModel", (msg) => {
334 const model = msg.data.model;
335 addModel(model, msg.data.role);
336 void this.configHandler.reloadConfig(
337 "Model added (config/addModel message)",
338 );
339 });
340
341 on("config/deleteModel", (msg) => {
342 deleteModel(msg.data.title);
343 void this.configHandler.reloadConfig(
344 "Model removed (config/deleteModel message)",
345 );
346 });
347
348 on("config/newPromptFile", async (msg) => {
349 const { config } = await this.configHandler.loadConfig();
350 await createNewPromptFileV2(this.ide, config?.experimental?.promptPath);
351 await this.configHandler.reloadConfig(
352 "Prompt file created (config/newPromptFile message)",
353 );
354 });
355
356 on("config/newAssistantFile", async (msg) => {
357 await createNewAssistantFile(this.ide, undefined);
358 await this.configHandler.reloadConfig(
359 "Assistant file created (config/newAssistantFile message)",
360 );
361 });
362
363 on("config/addLocalWorkspaceBlock", async (msg) => {
364 await createNewWorkspaceBlockFile(this.ide, msg.data.blockType);
365 await this.configHandler.reloadConfig(
366 "Local block created (config/addLocalWorkspaceBlock message)",
367 );
368 });
369
370 on("config/openProfile", async (msg) => {
371 await this.configHandler.openConfigProfile(
372 msg.data.profileId,
373 msg.data?.element,
374 );
375 });
376
377 on("config/ideSettingsUpdate", async (msg) => {
378 await this.configHandler.updateIdeSettings(msg.data);
379 });
380
381 on("config/refreshProfiles", async (msg) => {
382 // User force reloading will retrigger colocated rules
383 const codebaseRulesCache = CodebaseRulesCache.getInstance();
384 await codebaseRulesCache.refresh(this.ide);
385
386 const { selectOrgId, selectProfileId, reason } = msg.data ?? {};
387 await this.configHandler.refreshAll(reason);
388 if (selectOrgId) {
389 await this.configHandler.setSelectedOrgId(selectOrgId, selectProfileId);
390 } else if (selectProfileId) {
391 await this.configHandler.setSelectedProfileId(selectProfileId);
392 }
393 });
394
395 on("config/updateSharedConfig", async (msg) => {
396 const newSharedConfig = this.globalContext.updateSharedConfig(msg.data);
397 await this.configHandler.reloadConfig(
398 "Shared config update (config/updateSharedConfig message)",
399 );
400 return newSharedConfig;
401 });
402
403 on("config/updateSelectedModel", async (msg) => {
404 const newSelectedModels = this.globalContext.updateSelectedModel(
405 msg.data.profileId,
406 msg.data.role,
407 msg.data.title,
408 );
409 await this.configHandler.reloadConfig(
410 "Selected model update (config/updateSelectedModel message)",
411 );
412 return newSelectedModels;
413 });
414
415 on("controlPlane/openUrl", async (msg) => {
416 const env = await getControlPlaneEnv(this.ide.getIdeSettings());
417 const urlPath = msg.data.path.startsWith("/")
418 ? msg.data.path.slice(1)
419 : msg.data.path;
420 let url = `${env.APP_URL}${urlPath}`;
421 if (msg.data.orgSlug) {
422 url += `?org=${msg.data.orgSlug}`;
423 }
424 await this.messenger.request("openUrl", url);
425 });
426
427 on("controlPlane/getEnvironment", async (msg) => {
428 return await getControlPlaneEnv(this.ide.getIdeSettings());
429 });
430
431 on("controlPlane/getFreeTrialStatus", async (msg) => {
432 return this.configHandler.controlPlaneClient.getFreeTrialStatus();
433 });
434
435 on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => {
436 return this.configHandler.controlPlaneClient.getModelsAddOnCheckoutUrl(
437 msg.data.vsCodeUriScheme,
438 );
439 });
440
441 on("mcp/reloadServer", async (msg) => {
442 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
443 });
444 on("mcp/getPrompt", async (msg) => {
445 const { serverName, promptName, args } = msg.data;
446 const prompt = await MCPManagerSingleton.getInstance().getPrompt(
447 serverName,
448 promptName,
449 args,
450 );
451 const stringifiedPrompt = stringifyMcpPrompt(prompt);
452 return {
453 prompt: stringifiedPrompt,
454 description: prompt.description,
455 };
456 });
457 on("mcp/startAuthentication", async (msg) => {
458 await new Promise((resolve) => setTimeout(resolve, 5000));
459 MCPManagerSingleton.getInstance().setStatus(msg.data, "authenticating");
460 const status = await performAuth(msg.data, this.ide);
461 if (status === "AUTHORIZED") {
462 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
463 }
464 });
465 on("mcp/removeAuthentication", async (msg) => {
466 removeMCPAuth(msg.data, this.ide);
467 await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
468 });
469
470 // Context providers
471 on("context/addDocs", async (msg) => {
472 void this.docsService.indexAndAdd(msg.data);
473 });
474
475 on("context/removeDocs", async (msg) => {
476 await this.docsService.delete(msg.data.startUrl);
477 });
478
479 on("context/indexDocs", async (msg) => {
480 await this.docsService.syncDocsWithPrompt(msg.data.reIndex);
481 });
482
483 on("context/loadSubmenuItems", async (msg) => {
484 const { config } = await this.configHandler.loadConfig();
485 if (!config) {
486 return [];
487 }
488
489 try {
490 const items = await config.contextProviders
491 ?.find((provider) => provider.description.title === msg.data.title)
492 ?.loadSubmenuItems({
493 config,
494 ide: this.ide,
495 fetch: (url, init) =>
496 fetchwithRequestOptions(url, init, config.requestOptions),
497 });
498 return items || [];
499 } catch (e) {
500 Logger.error(e);
501 return [];
502 }
503 });
504
505 on("context/getContextItems", this.getContextItems.bind(this));
506
507 on("context/getSymbolsForFiles", async (msg) => {
508 const { uris } = msg.data;
509 return await getSymbolsForManyFiles(uris, this.ide);
510 });
511
512 on("config/getSerializedProfileInfo", async (msg) => {
513 return {
514 result: await this.configHandler.getSerializedConfig(),
515 profileId:
516 this.configHandler.currentProfile?.profileDescription.id ?? null,
517 organizations: this.configHandler.getSerializedOrgs(),
518 selectedOrgId: this.configHandler.currentOrg?.id ?? null,
519 };
520 });
521
522 on("llm/streamChat", (msg) => {
523 const abortController = this.addMessageAbortController(msg.messageId);
524 return llmStreamChat(
525 this.configHandler,
526 abortController,
527 msg,
528 this.ide,
529 this.messenger,
530 );
531 });
532
533 on("llm/complete", async (msg) => {
534 const { config } = await this.configHandler.loadConfig();
535 const model = config?.selectedModelByRole.chat;
536 if (!model) {
537 throw new Error("No chat model selected");
538 }
539 const abortController = this.addMessageAbortController(msg.messageId);
540
541 const completion = await model.complete(
542 msg.data.prompt,
543 abortController.signal,
544 msg.data.completionOptions,
545 );
546 return completion;
547 });
548 on("llm/listModels", this.handleListModels.bind(this));
549
550 on("llm/compileChat", async (msg) => {
551 const { messages, options } = msg.data;
552 const model = (await this.configHandler.loadConfig()).config
553 ?.selectedModelByRole.chat;
554
555 if (!model) {
556 throw new Error("No chat model selected");
557 }
558
559 return model.compileChatMessages(messages, options);
560 });
561
562 // Provide messenger to utils so they can interact with GUI + state
563 TTS.messenger = this.messenger;
564 ChatDescriber.messenger = this.messenger;
565
566 on("tts/kill", async () => {
567 void TTS.kill();
568 });
569
570 on("chatDescriber/describe", async (msg) => {
571 const currentModel = (await this.configHandler.loadConfig()).config
572 ?.selectedModelByRole.chat;
573
574 if (!currentModel) {
575 throw new Error("No chat model selected");
576 }
577
578 return await ChatDescriber.describe(currentModel, {}, msg.data.text);
579 });
580
581 on("conversation/compact", async (msg) => {
582 const currentModel = (await this.configHandler.loadConfig()).config
583 ?.selectedModelByRole.chat;
584
585 if (!currentModel) {
586 throw new Error("No chat model selected");
587 }
588
589 try {
590 await compactConversation({
591 sessionId: msg.data.sessionId,
592 index: msg.data.index,
593 historyManager,
594 currentModel,
595 });
596 return undefined;
597 } catch (error) {
598 Logger.error(`Error compacting conversation: ${error}`);
599 return undefined;
600 }
601 });
602
603 // Autocomplete
604 on("autocomplete/complete", async (msg) => {
605 const outcome =
606 await this.completionProvider.provideInlineCompletionItems(
607 msg.data,
608 undefined,
609 );
610 return outcome ? [outcome.completion] : [];
611 });
612 on("autocomplete/accept", async (msg) => {
613 this.completionProvider.accept(msg.data.completionId);
614 });
615 on("autocomplete/cancel", async (msg) => {
616 this.completionProvider.cancel();
617 });
618
619 // Next Edit
620 on("nextEdit/predict", async (msg) => {
621 const outcome = await this.nextEditProvider.provideInlineCompletionItems(
622 msg.data.input,
623 undefined,
624 {
625 withChain: msg.data.options?.withChain ?? false,
626 usingFullFileDiff: msg.data.options?.usingFullFileDiff ?? true,
627 },
628 );
629 return outcome;
630 // ? [outcome.completion, outcome.originalEditableRange]
631 });
632 on("nextEdit/accept", async (msg) => {
633 console.log("nextEdit/accept");
634 this.nextEditProvider.accept(msg.data.completionId);
635 });
636 on("nextEdit/reject", async (msg) => {
637 console.log("nextEdit/reject");
638 this.nextEditProvider.reject(msg.data.completionId);
639 });
640 on("nextEdit/startChain", async (msg) => {
641 console.log("nextEdit/startChain");
642 NextEditProvider.getInstance().startChain();
643 return;
644 });
645
646 on("nextEdit/deleteChain", async (msg) => {
647 console.log("nextEdit/deleteChain");
648 await NextEditProvider.getInstance().deleteChain();
649 return;
650 });
651
652 on("nextEdit/isChainAlive", async (msg) => {
653 console.log("nextEdit/isChainAlive");
654 return NextEditProvider.getInstance().chainExists();
655 });
656
657 on("nextEdit/queue/getProcessedCount", async (msg) => {
658 console.log("nextEdit/queue/getProcessedCount");
659 const queue = PrefetchQueue.getInstance();
660 console.log(queue.processedCount);
661 return queue.processedCount;
662 });
663
664 on("nextEdit/queue/dequeueProcessed", async (msg) => {
665 console.log("nextEdit/queue/dequeueProcessed");
666 const queue = PrefetchQueue.getInstance();
667 return queue.dequeueProcessed() || null;
668 });
669
670 // NOTE: This is not used unless prefetch is used.
671 // At this point this is not used because I opted to rely on the model to return multiple diffs than to use prefetching.
672 on("nextEdit/queue/processOne", async (msg) => {
673 console.log("nextEdit/queue/processOne");
674 const { ctx, recentlyVisitedRanges, recentlyEditedRanges } = msg.data;
675 const queue = PrefetchQueue.getInstance();
676
677 await queue.process({
678 ...ctx,
679 recentlyVisitedRanges,
680 recentlyEditedRanges,
681 });
682 return;
683 });
684
685 on("nextEdit/queue/clear", async (msg) => {
686 console.log("nextEdit/queue/clear");
687 const queue = PrefetchQueue.getInstance();
688 queue.clear();
689 return;
690 });
691
692 on("nextEdit/queue/abort", async (msg) => {
693 console.log("nextEdit/queue/abort");
694 const queue = PrefetchQueue.getInstance();
695 queue.abort();
696 return;
697 });
698
699 on("streamDiffLines", async (msg) => {
700 const { config } = await this.configHandler.loadConfig();
701 if (!config) {
702 throw new Error("Failed to load config");
703 }
704
705 const { data } = msg;
706
707 // Title can be an edit, chat, or apply model
708 // Fall back to chat
709 const llm =
710 config.modelsByRole.edit.find((m) => m.title === data.modelTitle) ??
711 config.modelsByRole.apply.find((m) => m.title === data.modelTitle) ??
712 config.modelsByRole.chat.find((m) => m.title === data.modelTitle) ??
713 config.selectedModelByRole.chat;
714
715 if (!llm) {
716 throw new Error("No model selected");
717 }
718
719 const abortManager = ApplyAbortManager.getInstance();
720 const abortController = abortManager.get(
721 data.fileUri ?? "current-file-stream",
722 ); // not super important since currently cancelling apply will cancel all streams it's one file at a time
723
724 return streamDiffLines({
725 highlighted: data.highlighted,
726 prefix: data.prefix,
727 suffix: data.suffix,
728 llm,
729 // rules included for edit, NOT apply
730 rulesToInclude: data.includeRulesInSystemMessage
731 ? config.rules
732 : undefined,
733 input: data.input,
734 language: data.language,
735 overridePrompt: undefined,
736 abortController,
737 });
738 });
739
740 on("cancelApply", async (msg) => {
741 const abortManager = ApplyAbortManager.getInstance();
742 abortManager.clear(); // for now abort all streams
743 });
744
745 on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
746
747 on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this));
748
749 on("stats/getTokensPerDay", async (msg) => {
750 const rows = await DevDataSqliteDb.getTokensPerDay();
751 return rows;
752 });
753 on("stats/getTokensPerModel", async (msg) => {
754 const rows = await DevDataSqliteDb.getTokensPerModel();
755 return rows;
756 });
757
758 on("index/forceReIndex", async ({ data }) => {
759 const { config } = await this.configHandler.loadConfig();
760 if (!config || config.disableIndexing) {
761 return; // TODO silent in case of commands?
762 }
763 walkDirCache.invalidate();
764 if (data?.shouldClearIndexes) {
765 await this.codeBaseIndexer.clearIndexes();
766 }
767
768 const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
769 await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
770 });
771 on("index/setPaused", (msg) => {
772 this.globalContext.update("indexingPaused", msg.data);
773 // Update using the new setter instead of token
774 this.codeBaseIndexer.paused = msg.data;
775 });
776 on("index/indexingProgressBarInitialized", async (msg) => {
777 // Triggered when progress bar is initialized.
778 // If a non-default state has been stored, update the indexing display to that state
779 const currentState = this.codeBaseIndexer.currentIndexingState;
780
781 if (currentState.status !== "loading") {
782 void this.messenger.request("indexProgress", currentState);
783 }
784 });
785
786 // File changes - TODO - remove remaining logic for these from IDEs where possible
787 on("files/changed", this.handleFilesChanged.bind(this));
788 const refreshIfNotIgnored = async (uris: string[]) => {
789 const toRefresh: string[] = [];
790 for (const uri of uris) {
791 const ignore = await shouldIgnore(uri, this.ide);
792 if (!ignore) {
793 toRefresh.push(uri);
794 }
795 }
796 if (toRefresh.length > 0) {
797 this.messenger.send("refreshSubmenuItems", {
798 providers: ["file"],
799 });
800 const { config } = await this.configHandler.loadConfig();
801 if (config && !config.disableIndexing) {
802 await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
803 }
804 }
805 };
806
807 on("files/created", async ({ data }) => {
808 if (data?.uris?.length) {
809 walkDirCache.invalidate();
810 void refreshIfNotIgnored(data.uris);
811
812 if (hasRulesFiles(data.uris)) {
813 const rulesCache = CodebaseRulesCache.getInstance();
814 await Promise.all(
815 data.uris.map((uri) => rulesCache.update(this.ide, uri)),
816 );
817 await this.configHandler.reloadConfig("Rules file created");
818 }
819 // If it's a local assistant being created, we want to reload all assistants so it shows up in the list
820 let localAssistantCreated = false;
821 for (const uri of data.uris) {
822 if (isLocalDefinitionFile(uri)) {
823 localAssistantCreated = true;
824 }
825 }
826 if (localAssistantCreated) {
827 await this.configHandler.refreshAll("Local assistant file created");
828 }
829 }
830 });
831
832 on("files/deleted", async ({ data }) => {
833 if (data?.uris?.length) {
834 walkDirCache.invalidate();
835 void refreshIfNotIgnored(data.uris);
836
837 if (hasRulesFiles(data.uris)) {
838 const rulesCache = CodebaseRulesCache.getInstance();
839 data.uris.forEach((uri) => rulesCache.remove(uri));
840 await this.configHandler.reloadConfig("Codebase rule file deleted");
841 }
842 }
843 });
844
845 on("files/closed", async ({ data }) => {
846 console.log("deleteChain called from files/closed");
847 await NextEditProvider.getInstance().deleteChain();
848
849 try {
850 const fileUris = await this.ide.getOpenFiles();
851 if (fileUris) {
852 const filepaths = fileUris.map((uri) => uri.toString());
853
854 if (!prevFilepaths.filepaths.length) {
855 prevFilepaths.filepaths = filepaths;
856 }
857
858 // If there is a removal, including if the number of tabs is the same (which can happen with temp tabs)
859 if (filepaths.length <= prevFilepaths.filepaths.length) {
860 // Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs)
861 for (const [key, _] of openedFilesLruCache.entriesDescending()) {
862 if (!filepaths.includes(key)) {
863 openedFilesLruCache.delete(key);
864 }
865 }
866 }
867 prevFilepaths.filepaths = filepaths;
868 }
869 } catch (e) {
870 Logger.error(
871 `didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
872 );
873 }
874
875 if (data.uris) {
876 this.messenger.send("didCloseFiles", {
877 uris: data.uris,
878 });
879 }
880 });
881
882 on("files/opened", async ({ data: { uris } }) => {
883 if (uris) {
884 for (const filepath of uris) {
885 try {
886 const ignore = await shouldIgnore(filepath, this.ide);
887 if (!ignore) {
888 // Set the active file as most recently used (need to force recency update by deleting and re-adding)
889 if (openedFilesLruCache.has(filepath)) {
890 openedFilesLruCache.delete(filepath);
891 }
892 openedFilesLruCache.set(filepath, filepath);
893 }
894 } catch (e) {
895 Logger.error(
896 `files/opened: failed to update openedFiles cache for ${filepath}`,
897 );
898 }
899 }
900 }
901 });
902
903 on("files/smallEdit", async ({ data }) => {
904 const EDIT_AGGREGATION_OPTIONS = {
905 deltaT: 1.0,
906 deltaL: 5,
907 maxEdits: 500,
908 maxDuration: 120.0,
909 contextSize: 5,
910 };
911
912 EditAggregator.getInstance(
913 EDIT_AGGREGATION_OPTIONS,
914 (
915 beforeAfterdiff: BeforeAfterDiff,
916 cursorPosBeforeEdit: Position,
917 cursorPosAfterPrevEdit: Position,
918 ) => {
919 void processSmallEdit(
920 beforeAfterdiff,
921 cursorPosBeforeEdit,
922 cursorPosAfterPrevEdit,
923 data.configHandler,
924 data.getDefsFromLspFunction,
925 this.ide,
926 );
927 },
928 );
929
930 const workspaceDir =
931 data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
932
933 // Store the latest context data
934 const instance = EditAggregator.getInstance();
935 (instance as any).latestContextData = {
936 configHandler: data.configHandler,
937 getDefsFromLspFunction: data.getDefsFromLspFunction,
938 recentlyEditedRanges: data.recentlyEditedRanges,
939 recentlyVisitedRanges: data.recentlyVisitedRanges,
940 workspaceDir: workspaceDir,
941 };
942
943 // queueMicrotask prevents blocking the UI thread during typing
944 queueMicrotask(() => {
945 void EditAggregator.getInstance().processEdits(data.actions);
946 });
947 });
948
949 // Docs, etc. indexing
950 on("indexing/reindex", async (msg) => {
951 if (msg.data.type === "docs") {
952 void this.docsService.reindexDoc(msg.data.id);
953 }
954 });
955 on("indexing/abort", async (msg) => {
956 if (msg.data.type === "docs") {
957 this.docsService.abort(msg.data.id);
958 }
959 });
960 on("indexing/setPaused", async (msg) => {
961 if (msg.data.type === "docs") {
962 }
963 });
964 on("docs/initStatuses", async (msg) => {
965 void this.docsService.initStatuses();
966 });
967 on("docs/getDetails", async (msg) => {
968 return await this.docsService.getDetails(msg.data.startUrl);
969 });
970 on("docs/getIndexedPages", async (msg) => {
971 const pages = await this.docsService.getIndexedPages(msg.data.startUrl);
972 return Array.from(pages);
973 });
974
975 on("didChangeSelectedProfile", async (msg) => {
976 if (msg.data.id) {
977 await this.configHandler.setSelectedProfileId(msg.data.id);
978 }
979 });
980
981 on("didChangeSelectedOrg", async (msg) => {
982 if (msg.data.id) {
983 await this.configHandler.setSelectedOrgId(
984 msg.data.id,
985 msg.data.profileId || undefined,
986 );
987 }
988 });
989
990 on("didChangeControlPlaneSessionInfo", async (msg) => {
991 this.messenger.send("sessionUpdate", {
992 sessionInfo: msg.data.sessionInfo,
993 });
994 await this.configHandler.updateControlPlaneSessionInfo(
995 msg.data.sessionInfo,
996 );
997 });
998
999 on("auth/getAuthUrl", async (msg) => {
1000 const url = await getAuthUrlForTokenPage(
1001 ideSettingsPromise,
1002 msg.data.useOnboarding,
1003 );
1004 return { url };
1005 });
1006
1007 on("tools/call", async ({ data: { toolCall } }) =>
1008 this.handleToolCall(toolCall),
1009 );
1010
1011 on(
1012 "tools/evaluatePolicy",
1013 async ({ data: { toolName, basePolicy, args } }) => {
1014 const { config } = await this.configHandler.loadConfig();
1015 if (!config) {
1016 throw new Error("Config not loaded");
1017 }
1018
1019 const tool = config.tools.find((t) => t.function.name === toolName);
1020 if (!tool) {
1021 // Tool not found, return base policy
1022 return { policy: basePolicy };
1023 }
1024
1025 // Extract display value for specific tools
1026 let displayValue: string | undefined;
1027 if (toolName === "runTerminalCommand" && args.command) {
1028 displayValue = args.command as string;
1029 }
1030
1031 // If tool has evaluateToolCallPolicy function, use it
1032 if (tool.evaluateToolCallPolicy) {
1033 const evaluatedPolicy = tool.evaluateToolCallPolicy(basePolicy, args);
1034 return { policy: evaluatedPolicy, displayValue };
1035 }
1036
1037 // Otherwise return base policy unchanged
1038 return { policy: basePolicy, displayValue };
1039 },
1040 );
1041
1042 on("isItemTooBig", async ({ data: { item } }) => {
1043 return this.isItemTooBig(item);
1044 });
1045
1046 // Process state handlers
1047 on("process/markAsBackgrounded", async ({ data: { toolCallId } }) => {
1048 markProcessAsBackgrounded(toolCallId);
1049 });
1050
1051 on(
1052 "process/isBackgrounded",
1053 async ({ data: { toolCallId }, messageId }) => {
1054 const isBackgrounded = isProcessBackgrounded(toolCallId);
1055 return isBackgrounded; // Return true to indicate the message was handled successfully
1056 },
1057 );
1058
1059 on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
1060 const isValid = setMdmLicenseKey(licenseKey);
1061 return isValid;
1062 });
1063 }
1064
1065 private async handleToolCall(toolCall: ToolCall) {
1066 const { config } = await this.configHandler.loadConfig();
1067 if (!config) {
1068 throw new Error("Config not loaded");
1069 }
1070
1071 const tool = config.tools.find(
1072 (t) => t.function.name === toolCall.function.name,
1073 );
1074
1075 if (!tool) {
1076 throw new Error(`Tool ${toolCall.function.name} not found`);
1077 }
1078
1079 if (!config.selectedModelByRole.chat) {
1080 throw new Error("No chat model selected");
1081 }
1082
1083 // Define a callback for streaming output updates
1084 const onPartialOutput = (params: {
1085 toolCallId: string;
1086 contextItems: ContextItem[];
1087 }) => {
1088 this.messenger.send("toolCallPartialOutput", params);
1089 };
1090
1091 const result = await callTool(tool, toolCall, {
1092 config,
1093 ide: this.ide,
1094 llm: config.selectedModelByRole.chat,
1095 fetch: (url, init) =>
1096 fetchwithRequestOptions(url, init, config.requestOptions),
1097 tool,
1098 toolCallId: toolCall.id,
1099 onPartialOutput,
1100 codeBaseIndexer: this.codeBaseIndexer,
1101 });
1102
1103 return result;
1104 }
1105
1106 private async isItemTooBig(item: ContextItemWithId) {
1107 const { config } = await this.configHandler.loadConfig();
1108 if (!config) {
1109 return false;
1110 }
1111
1112 const llm = config?.selectedModelByRole.chat;
1113 if (!llm) {
1114 throw new Error("No chat model selected");
1115 }
1116
1117 const tokens = countTokens(item.content, llm.model);
1118
1119 if (tokens > llm.contextLength - llm.completionOptions!.maxTokens!) {
1120 return true;
1121 }
1122
1123 return false;
1124 }
1125
1126 private handleAddAutocompleteModel(
1127 msg: Message<{
1128 model: ModelDescription;
1129 }>,
1130 ) {
1131 const model = msg.data.model;
1132 editConfigFile(
1133 (config) => {
1134 return {
1135 ...config,
1136 tabAutocompleteModel: model,
1137 };
1138 },
1139 (config) => ({
1140 ...config,
1141 models: [
1142 ...(config.models ?? []),
1143 {
1144 name: model.title,
1145 provider: model.provider,
1146 model: model.model,
1147 apiKey: model.apiKey,
1148 roles: ["autocomplete"],
1149 apiBase: model.apiBase,
1150 },
1151 ],
1152 }),
1153 );
1154 void this.configHandler.reloadConfig("Autocomplete model added");
1155 }
1156
1157 private async handleFilesChanged({
1158 data,
1159 }: Message<{
1160 uris?: string[];
1161 }>): Promise<void> {
1162 if (data?.uris?.length) {
1163 const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
1164 diffCache.invalidate();
1165 walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
1166 for (const uri of data.uris) {
1167 const currentProfileUri =
1168 this.configHandler.currentProfile?.profileDescription.uri ?? "";
1169
1170 if (URI.equal(uri, currentProfileUri)) {
1171 // Trigger a toast notification to provide UI feedback that config has been updated
1172 const showToast =
1173 this.globalContext.get("showConfigUpdateToast") ?? true;
1174 if (showToast) {
1175 const selection = await this.ide.showToast(
1176 "info",
1177 "Config updated",
1178 "Don't show again",
1179 );
1180 if (selection === "Don't show again") {
1181 this.globalContext.update("showConfigUpdateToast", false);
1182 }
1183 }
1184 await this.configHandler.reloadConfig(
1185 "Current profile config file updated",
1186 );
1187 continue;
1188 }
1189
1190 if (
1191 uri.endsWith(".continuerc.json") ||
1192 uri.endsWith(".prompt") ||
1193 uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
1194 (uri.includes(".continue") &&
1195 (uri.endsWith(".yaml") || uri.endsWith("yml"))) ||
1196 BLOCK_TYPES.some((blockType) =>
1197 uri.includes(`.continue/${blockType}`),
1198 )
1199 ) {
1200 await this.configHandler.reloadConfig(
1201 "Config-related file updated: continuerc, prompt, local block, etc",
1202 );
1203 } else if (uri.endsWith(RULES_MARKDOWN_FILENAME)) {
1204 try {
1205 const codebaseRulesCache = CodebaseRulesCache.getInstance();
1206 void codebaseRulesCache.update(this.ide, uri).then(() => {
1207 void this.configHandler.reloadConfig("Codebase rule update");
1208 });
1209 } catch (e) {
1210 Logger.error(`Failed to update codebase rule: ${e}`);
1211 }
1212 } else if (
1213 uri.endsWith(".continueignore") ||
1214 uri.endsWith(".gitignore")
1215 ) {
1216 // Reindex the workspaces
1217 this.invoke("index/forceReIndex", {
1218 shouldClearIndexes: true,
1219 });
1220 } else {
1221 const { config } = await this.configHandler.loadConfig();
1222 if (config && !config.disableIndexing) {
1223 // Reindex the file
1224 const ignore = await shouldIgnore(uri, this.ide);
1225 if (!ignore) {
1226 await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
1227 }
1228 }
1229 }
1230 }
1231 }
1232 }
1233
1234 private async handleListModels(msg: Message<{ title: string }>) {
1235 const { config } = await this.configHandler.loadConfig();
1236 if (!config) {
1237 return [];
1238 }
1239
1240 const model =
1241 config.modelsByRole.chat.find(
1242 (model) => model.title === msg.data.title,
1243 ) ??
1244 config.modelsByRole.chat.find((model) =>
1245 model.title?.startsWith(msg.data.title),
1246 );
1247
1248 try {
1249 if (model) {
1250 return await model.listModels();
1251 } else {
1252 if (msg.data.title === "Ollama") {
1253 const models = await new Ollama({ model: "" }).listModels();
1254 return models;
1255 } else {
1256 return undefined;
1257 }
1258 }
1259 } catch (e) {
1260 console.debug(`Error listing Ollama models: ${e}`);
1261 return undefined;
1262 }
1263 }
1264
1265 private async handleCompleteOnboarding(
1266 msg: Message<CompleteOnboardingPayload>,
1267 ) {
1268 const { mode, provider, apiKey } = msg.data;
1269
1270 let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
1271
1272 switch (mode) {
1273 case OnboardingModes.LOCAL:
1274 editConfigYamlCallback = setupLocalConfig;
1275 break;
1276
1277 case OnboardingModes.API_KEY:
1278 if (provider && apiKey) {
1279 editConfigYamlCallback = (config: ConfigYaml) =>
1280 setupProviderConfig(config, provider, apiKey);
1281 } else {
1282 editConfigYamlCallback = setupQuickstartConfig;
1283 }
1284 break;
1285
1286 default:
1287 Logger.error(`Invalid mode: ${mode}`);
1288 editConfigYamlCallback = (config) => config;
1289 }
1290
1291 editConfigFile((c) => c, editConfigYamlCallback);
1292
1293 void this.configHandler.reloadConfig("Onboarding completed");
1294 }
1295
1296 private getContextItems = async (
1297 msg: Message<{
1298 name: string;
1299 query: string;
1300 fullInput: string;
1301 selectedCode: RangeInFile[];
1302 isInAgentMode: boolean;
1303 }>,
1304 ) => {
1305 const { config } = await this.configHandler.loadConfig();
1306 if (!config) {
1307 return [];
1308 }
1309
1310 const { name, query, fullInput, selectedCode } = msg.data;
1311
1312 const llm = (await this.configHandler.loadConfig()).config
1313 ?.selectedModelByRole.chat;
1314
1315 if (!llm) {
1316 throw new Error("No chat model selected");
1317 }
1318
1319 const provider = config.contextProviders?.find(
1320 (provider) => provider.description.title === name,
1321 );
1322 if (!provider) {
1323 return [];
1324 }
1325
1326 try {
1327 void Telemetry.capture("context_provider_get_context_items", {
1328 name: provider.description.title,
1329 });
1330
1331 const items = await provider.getContextItems(query, {
1332 config,
1333 llm,
1334 embeddingsProvider: config.selectedModelByRole.embed,
1335 fullInput,
1336 ide: this.ide,
1337 selectedCode,
1338 reranker: config.selectedModelByRole.rerank,
1339 fetch: (url, init) =>
1340 fetchwithRequestOptions(url, init, config.requestOptions),
1341 isInAgentMode: msg.data.isInAgentMode,
1342 });
1343
1344 void Telemetry.capture(
1345 "useContextProvider",
1346 {
1347 name: provider.description.title,
1348 },
1349 true,
1350 );
1351
1352 return items.map((item) => {
1353 const id: ContextItemId = {
1354 providerTitle: provider.description.title,
1355 itemId: uuidv4(),
1356 };
1357
1358 return { ...item, id };
1359 });
1360 } catch (e) {
1361 let knownError = false;
1362
1363 if (e instanceof Error) {
1364 // After removing transformers JS embeddings provider from jetbrains
1365 // Should no longer see this error
1366 // if (e.message.toLowerCase().includes("embeddings provider")) {
1367 // knownError = true;
1368 // const toastOption = "See Docs";
1369 // void this.ide
1370 // .showToast(
1371 // "error",
1372 // `Set up an embeddings model to use @${name}`,
1373 // toastOption,
1374 // )
1375 // .then((userSelection) => {
1376 // if (userSelection === toastOption) {
1377 // void this.ide.openUrl(
1378 // "https://docs.continue.dev/customize/model-roles/embeddings",
1379 // );
1380 // }
1381 // });
1382 // }
1383 }
1384 if (!knownError) {
1385 void this.ide.showToast(
1386 "error",
1387 `Error getting context items from ${name}: ${e}`,
1388 );
1389 }
1390 return [];
1391 }
1392 };
1393}