Elffuss BraidHub

kikocis/continue public

95c91a48de4e · 27.7 KiBRawPermalink
1import { execSync } from "child_process";
2import * as fs from "fs";
3import os from "os";
4import path from "path";
5
6import {
7 ConfigResult,
8 ConfigValidationError,
9 ModelRole,
10} from "@continuedev/config-yaml";
11import * as JSONC from "comment-json";
12import * as tar from "tar";
13
14import {
15 BrowserSerializedContinueConfig,
16 Config,
17 ContextProviderWithParams,
18 ContinueConfig,
19 ContinueRcJson,
20 CustomContextProvider,
21 EmbeddingsProviderDescription,
22 IContextProvider,
23 IDE,
24 IdeInfo,
25 IdeSettings,
26 IdeType,
27 ILLM,
28 ILLMLogger,
29 LLMOptions,
30 ModelDescription,
31 RerankerDescription,
32 SerializedContinueConfig,
33 SlashCommand,
34} from "..";
35import {
36 slashCommandFromDescription,
37 slashFromCustomCommand,
38} from "../commands/index";
39import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
40import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
41import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
42import CustomContextProviderClass from "../context/providers/CustomContextProvider";
43import FileContextProvider from "../context/providers/FileContextProvider";
44import { contextProviderClassFromName } from "../context/providers/index";
45import { useHub } from "../control-plane/env";
46import { BaseLLM } from "../llm";
47import { LLMClasses, llmFromDescription } from "../llm/llms";
48import CustomLLMClass from "../llm/llms/CustomLLM";
49import FreeTrial from "../llm/llms/FreeTrial";
50import { LLMReranker } from "../llm/llms/llm";
51import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
52import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
53import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
54import { allTools } from "../tools";
55import { copyOf } from "../util";
56import { GlobalContext } from "../util/GlobalContext";
57import mergeJson from "../util/merge";
58import {
59 DEFAULT_CONFIG_TS_CONTENTS,
60 getConfigJsonPath,
61 getConfigJsonPathForRemote,
62 getConfigJsPath,
63 getConfigJsPathForRemote,
64 getConfigTsPath,
65 getContinueDotEnv,
66 getEsbuildBinaryPath,
67} from "../util/paths";
68import { localPathToUri } from "../util/pathToUri";
69
70import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
71import {
72 getModelByRole,
73 isSupportedLanceDbCpuTargetForLinux,
74 serializePromptTemplates,
75} from "./util";
76import { validateConfig } from "./validation.js";
77
78export function resolveSerializedConfig(
79 filepath: string,
80): SerializedContinueConfig {
81 let content = fs.readFileSync(filepath, "utf8");
82 const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
83 if (config.env && Array.isArray(config.env)) {
84 const env = {
85 ...process.env,
86 ...getContinueDotEnv(),
87 };
88
89 config.env.forEach((envVar) => {
90 if (envVar in env) {
91 content = (content as any).replaceAll(
92 new RegExp(`"${envVar}"`, "g"),
93 `"${env[envVar]}"`,
94 );
95 }
96 });
97 }
98
99 return JSONC.parse(content) as unknown as SerializedContinueConfig;
100}
101
102const configMergeKeys = {
103 models: (a: any, b: any) => a.title === b.title,
104 contextProviders: (a: any, b: any) => {
105 // If not HTTP providers, use the name only
106 if (a.name !== "http" || b.name !== "http") {
107 return a.name === b.name;
108 }
109 // For HTTP providers, consider them different if they have different URLs
110 return a.name === b.name && a.params?.url === b.params?.url;
111 },
112 slashCommands: (a: any, b: any) => a.name === b.name,
113 customCommands: (a: any, b: any) => a.name === b.name,
114};
115
116function loadSerializedConfig(
117 workspaceConfigs: ContinueRcJson[],
118 ideSettings: IdeSettings,
119 ideType: IdeType,
120 overrideConfigJson: SerializedContinueConfig | undefined,
121 ide: IDE,
122): ConfigResult<SerializedContinueConfig> {
123 let config: SerializedContinueConfig = overrideConfigJson!;
124 if (!config) {
125 try {
126 config = resolveSerializedConfig(getConfigJsonPath());
127 } catch (e) {
128 throw new Error(`Failed to parse config.json: ${e}`);
129 }
130 }
131
132 const errors = validateConfig(config);
133
134 if (errors?.some((error) => error.fatal)) {
135 return {
136 errors,
137 config: undefined,
138 configLoadInterrupted: true,
139 };
140 }
141
142 if (config.allowAnonymousTelemetry === undefined) {
143 config.allowAnonymousTelemetry = true;
144 }
145
146 if (ideSettings.remoteConfigServerUrl) {
147 try {
148 const remoteConfigJson = resolveSerializedConfig(
149 getConfigJsonPathForRemote(ideSettings.remoteConfigServerUrl),
150 );
151 config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
152 } catch (e) {
153 console.warn("Error loading remote config: ", e);
154 }
155 }
156
157 for (const workspaceConfig of workspaceConfigs) {
158 config = mergeJson(
159 config,
160 workspaceConfig,
161 workspaceConfig.mergeBehavior,
162 configMergeKeys,
163 );
164 }
165
166 if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
167 config.disableIndexing = true;
168 }
169
170 return { config, errors, configLoadInterrupted: false };
171}
172
173async function serializedToIntermediateConfig(
174 initial: SerializedContinueConfig,
175 ide: IDE,
176): Promise<Config> {
177 // DEPRECATED - load custom slash commands
178 const slashCommands: SlashCommand[] = [];
179 for (const command of initial.slashCommands || []) {
180 const newCommand = slashCommandFromDescription(command);
181 if (newCommand) {
182 slashCommands.push(newCommand);
183 }
184 }
185 for (const command of initial.customCommands || []) {
186 slashCommands.push(slashFromCustomCommand(command));
187 }
188
189 // DEPRECATED - load slash commands from v1 prompt files
190 // NOTE: still checking the v1 default .prompts folder for slash commands
191 const promptFiles = await getAllPromptFiles(
192 ide,
193 initial.experimental?.promptPath,
194 true,
195 );
196
197 for (const file of promptFiles) {
198 const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
199 if (slashCommand) {
200 slashCommands.push(slashCommand);
201 }
202 }
203
204 const config: Config = {
205 ...initial,
206 slashCommands,
207 contextProviders: initial.contextProviders || [],
208 };
209
210 return config;
211}
212
213// Merge request options set for entire config with model specific options
214function applyRequestOptionsToModels(
215 models: BaseLLM[],
216 config: Config,
217 roles: ModelRole[] | undefined = undefined,
218) {
219 // Prepare models
220 for (const model of models) {
221 model.requestOptions = {
222 ...model.requestOptions,
223 ...config.requestOptions,
224 };
225 if (roles !== undefined) {
226 model.roles = model.roles ?? roles;
227 }
228 }
229}
230
231export function isContextProviderWithParams(
232 contextProvider: CustomContextProvider | ContextProviderWithParams,
233): contextProvider is ContextProviderWithParams {
234 return (contextProvider as ContextProviderWithParams).name !== undefined;
235}
236
237/** Only difference between intermediate and final configs is the `models` array */
238async function intermediateToFinalConfig({
239 config,
240 ide,
241 ideSettings,
242 ideInfo,
243 uniqueId,
244 llmLogger,
245 workOsAccessToken,
246 loadPromptFiles = true,
247 allowFreeTrial = true,
248}: {
249 config: Config;
250 ide: IDE;
251 ideSettings: IdeSettings;
252 ideInfo: IdeInfo;
253 uniqueId: string;
254 llmLogger: ILLMLogger;
255 workOsAccessToken: string | undefined;
256 loadPromptFiles?: boolean;
257 allowFreeTrial?: boolean;
258}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
259 const errors: ConfigValidationError[] = [];
260
261 // Auto-detect models
262 let models: BaseLLM[] = [];
263 await Promise.all(
264 config.models.map(async (desc) => {
265 if ("title" in desc) {
266 const llm = await llmFromDescription(
267 desc,
268 ide.readFile.bind(ide),
269 uniqueId,
270 ideSettings,
271 llmLogger,
272 config.completionOptions,
273 );
274 if (!llm) {
275 return;
276 }
277
278 if (llm.model === "AUTODETECT") {
279 try {
280 const modelNames = await llm.listModels();
281 const detectedModels = await Promise.all(
282 modelNames.map(async (modelName) => {
283 return await llmFromDescription(
284 {
285 ...desc,
286 model: modelName,
287 title: modelName,
288 },
289 ide.readFile.bind(ide),
290 uniqueId,
291 ideSettings,
292 llmLogger,
293 copyOf(config.completionOptions),
294 );
295 }),
296 );
297 models.push(
298 ...(detectedModels.filter(
299 (x) => typeof x !== "undefined",
300 ) as BaseLLM[]),
301 );
302 } catch (e) {
303 console.warn("Error listing models: ", e);
304 }
305 } else {
306 models.push(llm);
307 }
308 } else {
309 const llm = new CustomLLMClass({
310 ...desc,
311 options: { ...desc.options, logger: llmLogger } as any,
312 });
313 if (llm.model === "AUTODETECT") {
314 try {
315 const modelNames = await llm.listModels();
316 const models = modelNames.map(
317 (modelName) =>
318 new CustomLLMClass({
319 ...desc,
320 options: {
321 ...desc.options,
322 model: modelName,
323 logger: llmLogger,
324 },
325 }),
326 );
327
328 models.push(...models);
329 } catch (e) {
330 console.warn("Error listing models: ", e);
331 }
332 } else {
333 models.push(llm);
334 }
335 }
336 }),
337 );
338
339 applyRequestOptionsToModels(models, config, [
340 "chat",
341 "apply",
342 "edit",
343 "summarize",
344 ]); // Default to chat role if not specified
345
346 if (allowFreeTrial) {
347 // Obtain auth token (iff free trial being used)
348 const freeTrialModels = models.filter(
349 (model) => model.providerName === "free-trial",
350 );
351 if (freeTrialModels.length > 0) {
352 const ghAuthToken = await ide.getGitHubAuthToken({});
353 for (const model of freeTrialModels) {
354 (model as FreeTrial).setupGhAuthToken(ghAuthToken);
355 }
356 }
357 } else {
358 // Remove free trial models
359 models = models.filter((model) => model.providerName !== "free-trial");
360 }
361
362 // Tab autocomplete model
363 let tabAutocompleteModels: BaseLLM[] = [];
364 if (config.tabAutocompleteModel) {
365 tabAutocompleteModels = (
366 await Promise.all(
367 (Array.isArray(config.tabAutocompleteModel)
368 ? config.tabAutocompleteModel
369 : [config.tabAutocompleteModel]
370 ).map(async (desc) => {
371 if ("title" in desc) {
372 const llm = await llmFromDescription(
373 desc,
374 ide.readFile.bind(ide),
375 uniqueId,
376 ideSettings,
377 llmLogger,
378 config.completionOptions,
379 );
380
381 if (llm?.providerName === "free-trial") {
382 if (!allowFreeTrial) {
383 // This shouldn't happen
384 throw new Error("Free trial cannot be used with control plane");
385 }
386 const ghAuthToken = await ide.getGitHubAuthToken({});
387 (llm as FreeTrial).setupGhAuthToken(ghAuthToken);
388 }
389 return llm;
390 } else {
391 return new CustomLLMClass(desc);
392 }
393 }),
394 )
395 ).filter((x) => x !== undefined) as BaseLLM[];
396 }
397
398 applyRequestOptionsToModels(tabAutocompleteModels, config);
399
400 // These context providers are always included, regardless of what, if anything,
401 // the user has configured in config.json
402
403 const codebaseContextParams =
404 (
405 (config.contextProviders || [])
406 .filter(isContextProviderWithParams)
407 .find((cp) => cp.name === "codebase") as
408 | ContextProviderWithParams
409 | undefined
410 )?.params || {};
411
412 const DEFAULT_CONTEXT_PROVIDERS = [
413 new FileContextProvider({}),
414 // Add codebase provider if indexing is enabled
415 ...(!config.disableIndexing
416 ? [new CodebaseContextProvider(codebaseContextParams)]
417 : []),
418 ];
419
420 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
421 ({ description: { title } }) => title,
422 );
423
424 // Context providers
425 const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS;
426
427 for (const provider of config.contextProviders || []) {
428 if (isContextProviderWithParams(provider)) {
429 const cls = contextProviderClassFromName(provider.name) as any;
430 if (!cls) {
431 if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) {
432 console.warn(`Unknown context provider ${provider.name}`);
433 }
434
435 continue;
436 }
437 const instance: IContextProvider = new cls(provider.params);
438
439 // Handle continue-proxy
440 if (instance.description.title === "continue-proxy") {
441 (instance as ContinueProxyContextProvider).workOsAccessToken =
442 workOsAccessToken;
443 }
444
445 contextProviders.push(instance);
446 } else {
447 contextProviders.push(new CustomContextProviderClass(provider));
448 }
449 }
450
451 // Embeddings Provider
452 function getEmbeddingsILLM(
453 embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
454 ): ILLM | null {
455 if (embedConfig) {
456 // config.ts-injected ILLM
457 if ("providerName" in embedConfig) {
458 return embedConfig;
459 }
460 const { provider, ...options } = embedConfig;
461 if (provider === "transformers.js") {
462 return new TransformersJsEmbeddingsProvider();
463 } else {
464 const cls = LLMClasses.find((c) => c.providerName === provider);
465 if (cls) {
466 const llmOptions: LLMOptions = {
467 model: options.model ?? "UNSPECIFIED",
468 ...options,
469 };
470 return new cls(llmOptions);
471 } else {
472 errors.push({
473 fatal: false,
474 message: `Embeddings provider ${provider} not found`,
475 });
476 }
477 }
478 }
479 if (ideInfo.ideType === "vscode") {
480 return new TransformersJsEmbeddingsProvider();
481 }
482 return null;
483 }
484 const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
485
486 // Reranker
487 function getRerankingILLM(
488 rerankingConfig: ILLM | RerankerDescription | undefined,
489 ): ILLM | null {
490 if (!rerankingConfig) {
491 return null;
492 }
493 // config.ts-injected ILLM
494 if ("providerName" in rerankingConfig) {
495 return rerankingConfig;
496 }
497 const { name, params } = config.reranker as RerankerDescription;
498
499 if (name === "llm") {
500 const llm = models.find((model) => model.title === params?.modelTitle);
501 if (!llm) {
502 errors.push({
503 fatal: false,
504 message: `Unknown reranking model ${params?.modelTitle}`,
505 });
506 return null;
507 } else {
508 return new LLMReranker(llm);
509 }
510 } else {
511 const cls = LLMClasses.find((c) => c.providerName === name);
512 if (cls) {
513 const llmOptions: LLMOptions = {
514 model: params?.model ?? "UNSPECIFIED",
515 ...params,
516 };
517 return new cls(llmOptions);
518 } else {
519 errors.push({
520 fatal: false,
521 message: `Unknown reranking provider ${name}`,
522 });
523 }
524 }
525 return null;
526 }
527 const newReranker = getRerankingILLM(config.reranker);
528
529 const continueConfig: ContinueConfig = {
530 ...config,
531 contextProviders,
532 tools: [...allTools],
533 mcpServerStatuses: [],
534 slashCommands: config.slashCommands ?? [],
535 modelsByRole: {
536 chat: models,
537 edit: models,
538 apply: models,
539 summarize: models,
540 autocomplete: [...tabAutocompleteModels],
541 embed: newEmbedder ? [newEmbedder] : [],
542 rerank: newReranker ? [newReranker] : [],
543 },
544 selectedModelByRole: {
545 chat: null, // Not implemented (uses GUI defaultModel)
546 edit: null,
547 apply: null,
548 embed: newEmbedder ?? null,
549 autocomplete: null,
550 rerank: newReranker ?? null,
551 summarize: null, // Not implemented
552 },
553 rules: [],
554 };
555
556 if (config.systemMessage) {
557 continueConfig.rules.unshift({
558 rule: config.systemMessage,
559 source: "json-systemMessage",
560 });
561 }
562
563 // Trigger MCP server refreshes (Config is reloaded again once connected!)
564 const mcpManager = MCPManagerSingleton.getInstance();
565 mcpManager.setConnections(
566 (config.experimental?.modelContextProtocolServers ?? []).map(
567 (server, index) => ({
568 id: `continue-mcp-server-${index + 1}`,
569 name: `MCP Server`,
570 ...server,
571 }),
572 ),
573 false,
574 );
575
576 // Handle experimental modelRole config values for apply and edit
577 const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
578 if (inlineEditModel) {
579 const match = continueConfig.modelsByRole.chat.find(
580 (m) => m.title === inlineEditModel,
581 );
582 if (match) {
583 continueConfig.selectedModelByRole.edit = match;
584 continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
585 } else {
586 errors.push({
587 fatal: false,
588 message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
589 });
590 }
591 }
592
593 const applyBlockModel = getModelByRole(
594 continueConfig,
595 "applyCodeBlock",
596 )?.title;
597 if (applyBlockModel) {
598 const match = continueConfig.modelsByRole.chat.find(
599 (m) => m.title === applyBlockModel,
600 );
601 if (match) {
602 continueConfig.selectedModelByRole.apply = match;
603 continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
604 } else {
605 errors.push({
606 fatal: false,
607 message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
608 });
609 }
610 }
611
612 // Add transformers JS to the embed models list if not already added
613 if (
614 ideInfo.ideType === "vscode" &&
615 !continueConfig.modelsByRole.embed.find(
616 (m) => m.providerName === "transformers.js",
617 )
618 ) {
619 continueConfig.modelsByRole.embed.push(
620 new TransformersJsEmbeddingsProvider(),
621 );
622 }
623
624 return { config: continueConfig, errors };
625}
626
627function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
628 return {
629 provider: llm.providerName,
630 model: llm.model,
631 title: llm.title ?? llm.model,
632 apiKey: llm.apiKey,
633 apiBase: llm.apiBase,
634 contextLength: llm.contextLength,
635 template: llm.template,
636 completionOptions: llm.completionOptions,
637 baseAgentSystemMessage: llm.baseAgentSystemMessage,
638 baseChatSystemMessage: llm.baseChatSystemMessage,
639 requestOptions: llm.requestOptions,
640 promptTemplates: serializePromptTemplates(llm.promptTemplates),
641 capabilities: llm.capabilities,
642 roles: llm.roles,
643 configurationStatus: llm.getConfigurationStatus(),
644 };
645}
646
647async function finalToBrowserConfig(
648 final: ContinueConfig,
649 ide: IDE,
650): Promise<BrowserSerializedContinueConfig> {
651 return {
652 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
653 completionOptions: final.completionOptions,
654 slashCommands: final.slashCommands?.map(
655 ({ run, ...slashCommandDescription }) => slashCommandDescription,
656 ),
657 contextProviders: final.contextProviders?.map((c) => c.description),
658 disableIndexing: final.disableIndexing,
659 disableSessionTitles: final.disableSessionTitles,
660 userToken: final.userToken,
661 ui: final.ui,
662 experimental: final.experimental,
663 rules: final.rules,
664 docs: final.docs,
665 tools: final.tools,
666 mcpServerStatuses: final.mcpServerStatuses,
667 tabAutocompleteOptions: final.tabAutocompleteOptions,
668 usePlatform: await useHub(ide.getIdeSettings()),
669 modelsByRole: Object.fromEntries(
670 Object.entries(final.modelsByRole).map(([k, v]) => [
671 k,
672 v.map(llmToSerializedModelDescription),
673 ]),
674 ) as Record<ModelRole, ModelDescription[]>, // TODO better types here
675 selectedModelByRole: Object.fromEntries(
676 Object.entries(final.selectedModelByRole).map(([k, v]) => [
677 k,
678 v ? llmToSerializedModelDescription(v) : null,
679 ]),
680 ) as Record<ModelRole, ModelDescription | null>, // TODO better types here
681 // data not included here because client doesn't need
682 };
683}
684
685function escapeSpacesInPath(p: string): string {
686 return p.replace(/ /g, "\\ ");
687}
688
689async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) {
690 // JetBrains is currently the only IDE that we've reached the plugin size limit and
691 // therefore need to install esbuild manually to reduce the size
692 if (ideType !== "jetbrains") {
693 return;
694 }
695
696 const globalContext = new GlobalContext();
697 if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) {
698 return;
699 }
700
701 const esbuildPath = getEsbuildBinaryPath();
702
703 if (fs.existsSync(esbuildPath)) {
704 return;
705 }
706
707 console.debug("No esbuild binary detected");
708
709 const shouldInstall = await promptEsbuildInstallation(ide);
710
711 if (shouldInstall) {
712 await downloadAndInstallEsbuild(ide);
713 }
714}
715
716async function promptEsbuildInstallation(ide: IDE): Promise<boolean> {
717 const installMsg = "Install esbuild";
718 const dismissMsg = "Dismiss";
719
720 const res = await ide.showToast(
721 "warning",
722 "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?",
723 dismissMsg,
724 installMsg,
725 );
726
727 if (res === dismissMsg) {
728 const globalContext = new GlobalContext();
729 globalContext.update("hasDismissedConfigTsNoticeJetBrains", true);
730 return false;
731 }
732
733 return res === installMsg;
734}
735
736/**
737 * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build
738 */
739async function downloadAndInstallEsbuild(ide: IDE) {
740 const esbuildPath = getEsbuildBinaryPath();
741 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-"));
742
743 try {
744 const target = `${os.platform()}-${os.arch()}`;
745 const version = "0.19.11";
746 const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`;
747 const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`);
748
749 console.debug(`Downloading esbuild from: ${url}`);
750 execSync(`curl -fo "${tgzPath}" "${url}"`);
751
752 console.debug(`Extracting tgz file to: ${tempDir}`);
753 await tar.x({
754 file: tgzPath,
755 cwd: tempDir,
756 strip: 2, // Remove the top two levels of directories
757 });
758
759 // Ensure the destination directory exists
760 const destDir = path.dirname(esbuildPath);
761 if (!fs.existsSync(destDir)) {
762 fs.mkdirSync(destDir, { recursive: true });
763 }
764
765 // Move the file
766 const extractedBinaryPath = path.join(tempDir, "esbuild");
767 fs.renameSync(extractedBinaryPath, esbuildPath);
768
769 // Ensure the binary is executable (not needed on Windows)
770 if (os.platform() !== "win32") {
771 fs.chmodSync(esbuildPath, 0o755);
772 }
773
774 // Clean up
775 fs.unlinkSync(tgzPath);
776 fs.rmSync(tempDir, { recursive: true });
777
778 await ide.showToast(
779 "info",
780 `'esbuild' successfully installed to ${esbuildPath}`,
781 );
782 } catch (error) {
783 console.error("Error downloading or saving esbuild binary:", error);
784 throw error;
785 }
786}
787
788async function tryBuildConfigTs() {
789 try {
790 if (process.env.IS_BINARY === "true") {
791 await buildConfigTsWithBinary();
792 } else {
793 await buildConfigTsWithNodeModule();
794 }
795 } catch (e) {
796 console.log(
797 `Build error. Please check your ~/.continue/config.ts file: ${e}`,
798 );
799 }
800}
801
802async function buildConfigTsWithBinary() {
803 const cmd = [
804 escapeSpacesInPath(getEsbuildBinaryPath()),
805 escapeSpacesInPath(getConfigTsPath()),
806 "--bundle",
807 `--outfile=${escapeSpacesInPath(getConfigJsPath())}`,
808 "--platform=node",
809 "--format=cjs",
810 "--sourcemap",
811 "--external:fetch",
812 "--external:fs",
813 "--external:path",
814 "--external:os",
815 "--external:child_process",
816 ].join(" ");
817
818 execSync(cmd);
819}
820
821async function buildConfigTsWithNodeModule() {
822 const { build } = await import("esbuild");
823
824 await build({
825 entryPoints: [getConfigTsPath()],
826 bundle: true,
827 platform: "node",
828 format: "cjs",
829 outfile: getConfigJsPath(),
830 external: ["fetch", "fs", "path", "os", "child_process"],
831 sourcemap: true,
832 });
833}
834
835function readConfigJs(): string | undefined {
836 const configJsPath = getConfigJsPath();
837
838 if (!fs.existsSync(configJsPath)) {
839 return undefined;
840 }
841
842 return fs.readFileSync(configJsPath, "utf8");
843}
844
845async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
846 const configTsPath = getConfigTsPath();
847
848 if (!fs.existsSync(configTsPath)) {
849 return;
850 }
851
852 const currentContent = fs.readFileSync(configTsPath, "utf8");
853
854 // If the user hasn't modified the default config.ts, don't bother building
855 if (currentContent.trim() === DEFAULT_CONFIG_TS_CONTENTS.trim()) {
856 return;
857 }
858
859 await handleEsbuildInstallation(ide, ideType);
860 await tryBuildConfigTs();
861
862 return readConfigJs();
863}
864
865async function loadContinueConfigFromJson(
866 ide: IDE,
867 workspaceConfigs: ContinueRcJson[],
868 ideSettings: IdeSettings,
869 ideInfo: IdeInfo,
870 uniqueId: string,
871 llmLogger: ILLMLogger,
872 workOsAccessToken: string | undefined,
873 overrideConfigJson: SerializedContinueConfig | undefined,
874): Promise<ConfigResult<ContinueConfig>> {
875 // Serialized config
876 let {
877 config: serialized,
878 errors,
879 configLoadInterrupted,
880 } = loadSerializedConfig(
881 workspaceConfigs,
882 ideSettings,
883 ideInfo.ideType,
884 overrideConfigJson,
885 ide,
886 );
887
888 if (!serialized || configLoadInterrupted) {
889 return { errors, config: undefined, configLoadInterrupted: true };
890 }
891
892 // Apply shared config
893 // TODO: override several of these values with user/org shared config
894 const sharedConfig = new GlobalContext().getSharedConfig();
895 const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
896
897 // Convert serialized to intermediate config
898 let intermediate = await serializedToIntermediateConfig(withShared, ide);
899
900 // Apply config.ts to modify intermediate config
901 const configJsContents = await buildConfigTsandReadConfigJs(
902 ide,
903 ideInfo.ideType,
904 );
905 if (configJsContents) {
906 try {
907 // Try config.ts first
908 const configJsPath = getConfigJsPath();
909 let module: any;
910
911 try {
912 module = await import(configJsPath);
913 } catch (e) {
914 console.log(e);
915 console.log(
916 "Could not load config.ts as absolute path, retrying as file url ...",
917 );
918 try {
919 module = await import(localPathToUri(configJsPath));
920 } catch (e) {
921 throw new Error("Could not load config.ts as file url either", {
922 cause: e,
923 });
924 }
925 }
926
927 if (typeof require !== "undefined") {
928 delete require.cache[require.resolve(configJsPath)];
929 }
930 if (!module.modifyConfig) {
931 throw new Error("config.ts does not export a modifyConfig function.");
932 }
933 intermediate = module.modifyConfig(intermediate);
934 } catch (e) {
935 console.log("Error loading config.ts: ", e);
936 }
937 }
938
939 // Apply remote config.js to modify intermediate config
940 if (ideSettings.remoteConfigServerUrl) {
941 try {
942 const configJsPathForRemote = getConfigJsPathForRemote(
943 ideSettings.remoteConfigServerUrl,
944 );
945 const module = await import(configJsPathForRemote);
946 if (typeof require !== "undefined") {
947 delete require.cache[require.resolve(configJsPathForRemote)];
948 }
949 if (!module.modifyConfig) {
950 throw new Error("config.ts does not export a modifyConfig function.");
951 }
952 intermediate = module.modifyConfig(intermediate);
953 } catch (e) {
954 console.log("Error loading remotely set config.js: ", e);
955 }
956 }
957
958 // Convert to final config format
959 const { config: finalConfig, errors: finalErrors } =
960 await intermediateToFinalConfig({
961 config: intermediate,
962 ide,
963 ideSettings,
964 ideInfo,
965 uniqueId,
966 llmLogger,
967 workOsAccessToken,
968 });
969 return {
970 config: finalConfig,
971 errors: [...(errors ?? []), ...finalErrors],
972 configLoadInterrupted: false,
973 };
974}
975
976export {
977 finalToBrowserConfig,
978 intermediateToFinalConfig,
979 loadContinueConfigFromJson,
980 type BrowserSerializedContinueConfig,
981};