Elffuss BraidHub

kikocis/continue public

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