Elffuss BraidHub

kikocis/continue public

e841ee848161 · 27.6 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 { LLMReranker } from "../llm/llms/llm";
50import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
51import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
52import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
53import { copyOf } from "../util";
54import { GlobalContext } from "../util/GlobalContext";
55import mergeJson from "../util/merge";
56import {
57 DEFAULT_CONFIG_TS_CONTENTS,
58 getConfigJsonPath,
59 getConfigJsonPathForRemote,
60 getConfigJsPath,
61 getConfigJsPathForRemote,
62 getConfigTsPath,
63 getContinueDotEnv,
64 getEsbuildBinaryPath,
65} from "../util/paths";
66import { localPathToUri } from "../util/pathToUri";
67
68import { baseToolDefinitions } from "../tools";
69import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
70import {
71 getModelByRole,
72 isSupportedLanceDbCpuTargetForLinux,
73 serializePromptTemplates,
74} from "./util";
75import { validateConfig } from "./validation.js";
76
77export function resolveSerializedConfig(
78 filepath: string,
79): SerializedContinueConfig {
80 let content = fs.readFileSync(filepath, "utf8");
81 const config = JSONC.parse(content) as unknown as SerializedContinueConfig;
82 if (config.env && Array.isArray(config.env)) {
83 const env = {
84 ...process.env,
85 ...getContinueDotEnv(),
86 };
87
88 config.env.forEach((envVar) => {
89 if (envVar in env) {
90 content = (content as any).replaceAll(
91 new RegExp(`"${envVar}"`, "g"),
92 `"${env[envVar]}"`,
93 );
94 }
95 });
96 }
97
98 return JSONC.parse(content) as unknown as SerializedContinueConfig;
99}
100
101const configMergeKeys = {
102 models: (a: any, b: any) => a.title === b.title,
103 contextProviders: (a: any, b: any) => {
104 // If not HTTP providers, use the name only
105 if (a.name !== "http" || b.name !== "http") {
106 return a.name === b.name;
107 }
108 // For HTTP providers, consider them different if they have different URLs
109 return a.name === b.name && a.params?.url === b.params?.url;
110 },
111 slashCommands: (a: any, b: any) => a.name === b.name,
112 customCommands: (a: any, b: any) => a.name === b.name,
113};
114
115function loadSerializedConfig(
116 workspaceConfigs: ContinueRcJson[],
117 ideSettings: IdeSettings,
118 ideType: IdeType,
119 overrideConfigJson: SerializedContinueConfig | undefined,
120 ide: IDE,
121): ConfigResult<SerializedContinueConfig> {
122 let config: SerializedContinueConfig = overrideConfigJson!;
123 if (!config) {
124 try {
125 config = resolveSerializedConfig(getConfigJsonPath());
126 } catch (e) {
127 throw new Error(`Failed to parse config.json: ${e}`);
128 }
129 }
130
131 const errors = validateConfig(config);
132
133 if (errors?.some((error) => error.fatal)) {
134 return {
135 errors,
136 config: undefined,
137 configLoadInterrupted: true,
138 };
139 }
140
141 if (config.allowAnonymousTelemetry === undefined) {
142 config.allowAnonymousTelemetry = true;
143 }
144
145 if (ideSettings.remoteConfigServerUrl) {
146 try {
147 const remoteConfigJson = resolveSerializedConfig(
148 getConfigJsonPathForRemote(ideSettings.remoteConfigServerUrl),
149 );
150 config = mergeJson(config, remoteConfigJson, "merge", configMergeKeys);
151 } catch (e) {
152 console.warn("Error loading remote config: ", e);
153 }
154 }
155
156 for (const workspaceConfig of workspaceConfigs) {
157 config = mergeJson(
158 config,
159 workspaceConfig,
160 workspaceConfig.mergeBehavior,
161 configMergeKeys,
162 );
163 }
164
165 if (os.platform() === "linux" && !isSupportedLanceDbCpuTargetForLinux(ide)) {
166 config.disableIndexing = true;
167 }
168
169 return { config, errors, configLoadInterrupted: false };
170}
171
172async function serializedToIntermediateConfig(
173 initial: SerializedContinueConfig,
174 ide: IDE,
175): Promise<Config> {
176 // DEPRECATED - load custom slash commands
177 const slashCommands: SlashCommand[] = [];
178 for (const command of initial.slashCommands || []) {
179 const newCommand = slashCommandFromDescription(command);
180 if (newCommand) {
181 slashCommands.push(newCommand);
182 }
183 }
184 for (const command of initial.customCommands || []) {
185 slashCommands.push(slashFromCustomCommand(command));
186 }
187
188 // DEPRECATED - load slash commands from v1 prompt files
189 // NOTE: still checking the v1 default .prompts folder for slash commands
190 const promptFiles = await getAllPromptFiles(
191 ide,
192 initial.experimental?.promptPath,
193 true,
194 );
195
196 for (const file of promptFiles) {
197 const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
198 if (slashCommand) {
199 slashCommands.push(slashCommand);
200 }
201 }
202
203 const config: Config = {
204 ...initial,
205 slashCommands,
206 contextProviders: initial.contextProviders || [],
207 };
208
209 return config;
210}
211
212// Merge request options set for entire config with model specific options
213function applyRequestOptionsToModels(
214 models: BaseLLM[],
215 config: Config,
216 roles: ModelRole[] | undefined = undefined,
217) {
218 // Prepare models
219 for (const model of models) {
220 model.requestOptions = {
221 ...model.requestOptions,
222 ...config.requestOptions,
223 };
224 if (roles !== undefined) {
225 model.roles = model.roles ?? roles;
226 }
227 }
228}
229
230export function isContextProviderWithParams(
231 contextProvider: CustomContextProvider | ContextProviderWithParams,
232): contextProvider is ContextProviderWithParams {
233 return (contextProvider as ContextProviderWithParams).name !== undefined;
234}
235
236/** Only difference between intermediate and final configs is the `models` array */
237async function intermediateToFinalConfig({
238 config,
239 ide,
240 ideSettings,
241 ideInfo,
242 uniqueId,
243 llmLogger,
244 workOsAccessToken,
245 loadPromptFiles = true,
246}: {
247 config: Config;
248 ide: IDE;
249 ideSettings: IdeSettings;
250 ideInfo: IdeInfo;
251 uniqueId: string;
252 llmLogger: ILLMLogger;
253 workOsAccessToken: string | undefined;
254 loadPromptFiles?: boolean;
255}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
256 const errors: ConfigValidationError[] = [];
257
258 // Auto-detect models
259 let models: BaseLLM[] = [];
260 await Promise.all(
261 config.models.map(async (desc) => {
262 if ("title" in desc) {
263 const llm = await llmFromDescription(
264 desc,
265 ide.readFile.bind(ide),
266 uniqueId,
267 ideSettings,
268 llmLogger,
269 config.completionOptions,
270 );
271 if (!llm) {
272 return;
273 }
274
275 if (llm.model === "AUTODETECT") {
276 try {
277 const modelNames = await llm.listModels();
278 const detectedModels = await Promise.all(
279 modelNames.map(async (modelName) => {
280 return await llmFromDescription(
281 {
282 ...desc,
283 model: modelName,
284 title: modelName,
285 },
286 ide.readFile.bind(ide),
287 uniqueId,
288 ideSettings,
289 llmLogger,
290 copyOf(config.completionOptions),
291 );
292 }),
293 );
294 models.push(
295 ...(detectedModels.filter(
296 (x) => typeof x !== "undefined",
297 ) as BaseLLM[]),
298 );
299 } catch (e) {
300 console.warn("Error listing models: ", e);
301 }
302 } else {
303 models.push(llm);
304 }
305 } else {
306 const llm = new CustomLLMClass({
307 ...desc,
308 options: { ...desc.options, logger: llmLogger } as any,
309 });
310 if (llm.model === "AUTODETECT") {
311 try {
312 const modelNames = await llm.listModels();
313 const models = modelNames.map(
314 (modelName) =>
315 new CustomLLMClass({
316 ...desc,
317 options: {
318 ...desc.options,
319 model: modelName,
320 logger: llmLogger,
321 },
322 }),
323 );
324
325 models.push(...models);
326 } catch (e) {
327 console.warn("Error listing models: ", e);
328 }
329 } else {
330 models.push(llm);
331 }
332 }
333 }),
334 );
335
336 applyRequestOptionsToModels(models, config, [
337 "chat",
338 "apply",
339 "edit",
340 "summarize",
341 ]); // Default to chat role if not specified
342
343 // Free trial provider will be completely ignored
344 let warnAboutFreeTrial = false;
345 models = models.filter((model) => model.providerName !== "free-trial");
346 if (models.filter((m) => m.providerName === "free-trial").length) {
347 warnAboutFreeTrial = true;
348 }
349
350 // Tab autocomplete model
351 const tabAutocompleteModels: BaseLLM[] = [];
352 if (config.tabAutocompleteModel) {
353 const autocompleteConfigs = Array.isArray(config.tabAutocompleteModel)
354 ? config.tabAutocompleteModel
355 : [config.tabAutocompleteModel];
356
357 await Promise.all(
358 autocompleteConfigs.map(async (desc) => {
359 if ("title" in desc) {
360 const llm = await llmFromDescription(
361 desc,
362 ide.readFile.bind(ide),
363 uniqueId,
364 ideSettings,
365 llmLogger,
366 config.completionOptions,
367 );
368 if (llm) {
369 if (llm.providerName === "free-trial") {
370 warnAboutFreeTrial = true;
371 } else {
372 tabAutocompleteModels.push(llm);
373 }
374 }
375 } else {
376 tabAutocompleteModels.push(new CustomLLMClass(desc));
377 }
378 }),
379 );
380 }
381
382 applyRequestOptionsToModels(tabAutocompleteModels, config);
383
384 // These context providers are always included, regardless of what, if anything,
385 // the user has configured in config.json
386
387 const codebaseContextParams =
388 (
389 (config.contextProviders || [])
390 .filter(isContextProviderWithParams)
391 .find((cp) => cp.name === "codebase") as
392 | ContextProviderWithParams
393 | undefined
394 )?.params || {};
395
396 const DEFAULT_CONTEXT_PROVIDERS = [
397 new FileContextProvider({}),
398 // Add codebase provider if indexing is enabled
399 ...(!config.disableIndexing
400 ? [new CodebaseContextProvider(codebaseContextParams)]
401 : []),
402 ];
403
404 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
405 ({ description: { title } }) => title,
406 );
407
408 // Context providers
409 const contextProviders: IContextProvider[] = DEFAULT_CONTEXT_PROVIDERS;
410
411 for (const provider of config.contextProviders || []) {
412 if (isContextProviderWithParams(provider)) {
413 const cls = contextProviderClassFromName(provider.name) as any;
414 if (!cls) {
415 if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(provider.name)) {
416 console.warn(`Unknown context provider ${provider.name}`);
417 }
418
419 continue;
420 }
421 const instance: IContextProvider = new cls(provider.params);
422
423 // Handle continue-proxy
424 if (instance.description.title === "continue-proxy") {
425 (instance as ContinueProxyContextProvider).workOsAccessToken =
426 workOsAccessToken;
427 }
428
429 contextProviders.push(instance);
430 } else {
431 contextProviders.push(new CustomContextProviderClass(provider));
432 }
433 }
434
435 // Embeddings Provider
436 function getEmbeddingsILLM(
437 embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
438 ): ILLM | null {
439 if (embedConfig) {
440 // config.ts-injected ILLM
441 if ("providerName" in embedConfig) {
442 return embedConfig;
443 }
444 const { provider, ...options } = embedConfig;
445 if (provider === "transformers.js" || provider === "free-trial") {
446 if (provider === "free-trial") {
447 warnAboutFreeTrial = true;
448 }
449 return new TransformersJsEmbeddingsProvider();
450 } else {
451 const cls = LLMClasses.find((c) => c.providerName === provider);
452 if (cls) {
453 const llmOptions: LLMOptions = {
454 model: options.model ?? "UNSPECIFIED",
455 ...options,
456 };
457 return new cls(llmOptions);
458 } else {
459 errors.push({
460 fatal: false,
461 message: `Embeddings provider ${provider} not found`,
462 });
463 }
464 }
465 }
466 if (ideInfo.ideType === "vscode") {
467 return new TransformersJsEmbeddingsProvider();
468 }
469 return null;
470 }
471 const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
472
473 // Reranker
474 function getRerankingILLM(
475 rerankingConfig: ILLM | RerankerDescription | undefined,
476 ): ILLM | null {
477 if (!rerankingConfig) {
478 return null;
479 }
480 // config.ts-injected ILLM
481 if ("providerName" in rerankingConfig) {
482 return rerankingConfig;
483 }
484 const { name, params } = config.reranker as RerankerDescription;
485 if (name === "free-trial") {
486 warnAboutFreeTrial = true;
487 return null;
488 }
489 if (name === "llm") {
490 const llm = models.find((model) => model.title === params?.modelTitle);
491 if (!llm) {
492 errors.push({
493 fatal: false,
494 message: `Unknown reranking model ${params?.modelTitle}`,
495 });
496 return null;
497 } else {
498 return new LLMReranker(llm);
499 }
500 } else {
501 const cls = LLMClasses.find((c) => c.providerName === name);
502 if (cls) {
503 const llmOptions: LLMOptions = {
504 model: params?.model ?? "UNSPECIFIED",
505 ...params,
506 };
507 return new cls(llmOptions);
508 } else {
509 errors.push({
510 fatal: false,
511 message: `Unknown reranking provider ${name}`,
512 });
513 }
514 }
515 return null;
516 }
517 const newReranker = getRerankingILLM(config.reranker);
518
519 if (warnAboutFreeTrial) {
520 errors.push({
521 fatal: false,
522 message:
523 "Model provider 'free-trial' is no longer supported, will be ignored",
524 });
525 }
526
527 const continueConfig: ContinueConfig = {
528 ...config,
529 contextProviders,
530 tools: [...baseToolDefinitions],
531 mcpServerStatuses: [],
532 slashCommands: config.slashCommands ?? [],
533 modelsByRole: {
534 chat: models,
535 edit: models,
536 apply: models,
537 summarize: models,
538 autocomplete: [...tabAutocompleteModels],
539 embed: newEmbedder ? [newEmbedder] : [],
540 rerank: newReranker ? [newReranker] : [],
541 },
542 selectedModelByRole: {
543 chat: null, // Not implemented (uses GUI defaultModel)
544 edit: null,
545 apply: null,
546 embed: newEmbedder ?? null,
547 autocomplete: null,
548 rerank: newReranker ?? null,
549 summarize: null, // Not implemented
550 },
551 rules: [],
552 };
553
554 if (config.systemMessage) {
555 continueConfig.rules.unshift({
556 rule: config.systemMessage,
557 source: "json-systemMessage",
558 });
559 }
560
561 // Trigger MCP server refreshes (Config is reloaded again once connected!)
562 const mcpManager = MCPManagerSingleton.getInstance();
563 mcpManager.setConnections(
564 (config.experimental?.modelContextProtocolServers ?? []).map(
565 (server, index) => ({
566 id: `continue-mcp-server-${index + 1}`,
567 name: `MCP Server`,
568 ...server,
569 }),
570 ),
571 false,
572 );
573
574 // Handle experimental modelRole config values for apply and edit
575 const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
576 if (inlineEditModel) {
577 const match = continueConfig.modelsByRole.chat.find(
578 (m) => m.title === inlineEditModel,
579 );
580 if (match) {
581 continueConfig.selectedModelByRole.edit = match;
582 continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
583 } else {
584 errors.push({
585 fatal: false,
586 message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
587 });
588 }
589 }
590
591 const applyBlockModel = getModelByRole(
592 continueConfig,
593 "applyCodeBlock",
594 )?.title;
595 if (applyBlockModel) {
596 const match = continueConfig.modelsByRole.chat.find(
597 (m) => m.title === applyBlockModel,
598 );
599 if (match) {
600 continueConfig.selectedModelByRole.apply = match;
601 continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
602 } else {
603 errors.push({
604 fatal: false,
605 message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
606 });
607 }
608 }
609
610 // Add transformers JS to the embed models list if not already added
611 if (
612 ideInfo.ideType === "vscode" &&
613 !continueConfig.modelsByRole.embed.find(
614 (m) => m.providerName === "transformers.js",
615 )
616 ) {
617 continueConfig.modelsByRole.embed.push(
618 new TransformersJsEmbeddingsProvider(),
619 );
620 }
621
622 return { config: continueConfig, errors };
623}
624
625function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
626 return {
627 provider: llm.providerName,
628 underlyingProviderName: llm.underlyingProviderName,
629 model: llm.model,
630 title: llm.title ?? llm.model,
631 apiKey: llm.apiKey,
632 apiBase: llm.apiBase,
633 contextLength: llm.contextLength,
634 template: llm.template,
635 completionOptions: llm.completionOptions,
636 baseAgentSystemMessage: llm.baseAgentSystemMessage,
637 baseChatSystemMessage: llm.baseChatSystemMessage,
638 requestOptions: llm.requestOptions,
639 promptTemplates: serializePromptTemplates(llm.promptTemplates),
640 capabilities: llm.capabilities,
641 roles: llm.roles,
642 configurationStatus: llm.getConfigurationStatus(),
643 apiKeyLocation: llm.apiKeyLocation,
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};