Elffuss BraidHub

kikocis/continue public

2ff6e1c400a1 · 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 };
644}
645
646async function finalToBrowserConfig(
647 final: ContinueConfig,
648 ide: IDE,
649): Promise<BrowserSerializedContinueConfig> {
650 return {
651 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
652 completionOptions: final.completionOptions,
653 slashCommands: final.slashCommands?.map(
654 ({ run, ...slashCommandDescription }) => slashCommandDescription,
655 ),
656 contextProviders: final.contextProviders?.map((c) => c.description),
657 disableIndexing: final.disableIndexing,
658 disableSessionTitles: final.disableSessionTitles,
659 userToken: final.userToken,
660 ui: final.ui,
661 experimental: final.experimental,
662 rules: final.rules,
663 docs: final.docs,
664 tools: final.tools,
665 mcpServerStatuses: final.mcpServerStatuses,
666 tabAutocompleteOptions: final.tabAutocompleteOptions,
667 usePlatform: await useHub(ide.getIdeSettings()),
668 modelsByRole: Object.fromEntries(
669 Object.entries(final.modelsByRole).map(([k, v]) => [
670 k,
671 v.map(llmToSerializedModelDescription),
672 ]),
673 ) as Record<ModelRole, ModelDescription[]>, // TODO better types here
674 selectedModelByRole: Object.fromEntries(
675 Object.entries(final.selectedModelByRole).map(([k, v]) => [
676 k,
677 v ? llmToSerializedModelDescription(v) : null,
678 ]),
679 ) as Record<ModelRole, ModelDescription | null>, // TODO better types here
680 // data not included here because client doesn't need
681 };
682}
683
684function escapeSpacesInPath(p: string): string {
685 return p.replace(/ /g, "\\ ");
686}
687
688async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) {
689 // JetBrains is currently the only IDE that we've reached the plugin size limit and
690 // therefore need to install esbuild manually to reduce the size
691 if (ideType !== "jetbrains") {
692 return;
693 }
694
695 const globalContext = new GlobalContext();
696 if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) {
697 return;
698 }
699
700 const esbuildPath = getEsbuildBinaryPath();
701
702 if (fs.existsSync(esbuildPath)) {
703 return;
704 }
705
706 console.debug("No esbuild binary detected");
707
708 const shouldInstall = await promptEsbuildInstallation(ide);
709
710 if (shouldInstall) {
711 await downloadAndInstallEsbuild(ide);
712 }
713}
714
715async function promptEsbuildInstallation(ide: IDE): Promise<boolean> {
716 const installMsg = "Install esbuild";
717 const dismissMsg = "Dismiss";
718
719 const res = await ide.showToast(
720 "warning",
721 "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?",
722 dismissMsg,
723 installMsg,
724 );
725
726 if (res === dismissMsg) {
727 const globalContext = new GlobalContext();
728 globalContext.update("hasDismissedConfigTsNoticeJetBrains", true);
729 return false;
730 }
731
732 return res === installMsg;
733}
734
735/**
736 * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build
737 */
738async function downloadAndInstallEsbuild(ide: IDE) {
739 const esbuildPath = getEsbuildBinaryPath();
740 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-"));
741
742 try {
743 const target = `${os.platform()}-${os.arch()}`;
744 const version = "0.19.11";
745 const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`;
746 const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`);
747
748 console.debug(`Downloading esbuild from: ${url}`);
749 execSync(`curl -fo "${tgzPath}" "${url}"`);
750
751 console.debug(`Extracting tgz file to: ${tempDir}`);
752 await tar.x({
753 file: tgzPath,
754 cwd: tempDir,
755 strip: 2, // Remove the top two levels of directories
756 });
757
758 // Ensure the destination directory exists
759 const destDir = path.dirname(esbuildPath);
760 if (!fs.existsSync(destDir)) {
761 fs.mkdirSync(destDir, { recursive: true });
762 }
763
764 // Move the file
765 const extractedBinaryPath = path.join(tempDir, "esbuild");
766 fs.renameSync(extractedBinaryPath, esbuildPath);
767
768 // Ensure the binary is executable (not needed on Windows)
769 if (os.platform() !== "win32") {
770 fs.chmodSync(esbuildPath, 0o755);
771 }
772
773 // Clean up
774 fs.unlinkSync(tgzPath);
775 fs.rmSync(tempDir, { recursive: true });
776
777 await ide.showToast(
778 "info",
779 `'esbuild' successfully installed to ${esbuildPath}`,
780 );
781 } catch (error) {
782 console.error("Error downloading or saving esbuild binary:", error);
783 throw error;
784 }
785}
786
787async function tryBuildConfigTs() {
788 try {
789 if (process.env.IS_BINARY === "true") {
790 await buildConfigTsWithBinary();
791 } else {
792 await buildConfigTsWithNodeModule();
793 }
794 } catch (e) {
795 console.log(
796 `Build error. Please check your ~/.continue/config.ts file: ${e}`,
797 );
798 }
799}
800
801async function buildConfigTsWithBinary() {
802 const cmd = [
803 escapeSpacesInPath(getEsbuildBinaryPath()),
804 escapeSpacesInPath(getConfigTsPath()),
805 "--bundle",
806 `--outfile=${escapeSpacesInPath(getConfigJsPath())}`,
807 "--platform=node",
808 "--format=cjs",
809 "--sourcemap",
810 "--external:fetch",
811 "--external:fs",
812 "--external:path",
813 "--external:os",
814 "--external:child_process",
815 ].join(" ");
816
817 execSync(cmd);
818}
819
820async function buildConfigTsWithNodeModule() {
821 const { build } = await import("esbuild");
822
823 await build({
824 entryPoints: [getConfigTsPath()],
825 bundle: true,
826 platform: "node",
827 format: "cjs",
828 outfile: getConfigJsPath(),
829 external: ["fetch", "fs", "path", "os", "child_process"],
830 sourcemap: true,
831 });
832}
833
834function readConfigJs(): string | undefined {
835 const configJsPath = getConfigJsPath();
836
837 if (!fs.existsSync(configJsPath)) {
838 return undefined;
839 }
840
841 return fs.readFileSync(configJsPath, "utf8");
842}
843
844async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
845 const configTsPath = getConfigTsPath();
846
847 if (!fs.existsSync(configTsPath)) {
848 return;
849 }
850
851 const currentContent = fs.readFileSync(configTsPath, "utf8");
852
853 // If the user hasn't modified the default config.ts, don't bother building
854 if (currentContent.trim() === DEFAULT_CONFIG_TS_CONTENTS.trim()) {
855 return;
856 }
857
858 await handleEsbuildInstallation(ide, ideType);
859 await tryBuildConfigTs();
860
861 return readConfigJs();
862}
863
864async function loadContinueConfigFromJson(
865 ide: IDE,
866 workspaceConfigs: ContinueRcJson[],
867 ideSettings: IdeSettings,
868 ideInfo: IdeInfo,
869 uniqueId: string,
870 llmLogger: ILLMLogger,
871 workOsAccessToken: string | undefined,
872 overrideConfigJson: SerializedContinueConfig | undefined,
873): Promise<ConfigResult<ContinueConfig>> {
874 // Serialized config
875 let {
876 config: serialized,
877 errors,
878 configLoadInterrupted,
879 } = loadSerializedConfig(
880 workspaceConfigs,
881 ideSettings,
882 ideInfo.ideType,
883 overrideConfigJson,
884 ide,
885 );
886
887 if (!serialized || configLoadInterrupted) {
888 return { errors, config: undefined, configLoadInterrupted: true };
889 }
890
891 // Apply shared config
892 // TODO: override several of these values with user/org shared config
893 const sharedConfig = new GlobalContext().getSharedConfig();
894 const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
895
896 // Convert serialized to intermediate config
897 let intermediate = await serializedToIntermediateConfig(withShared, ide);
898
899 // Apply config.ts to modify intermediate config
900 const configJsContents = await buildConfigTsandReadConfigJs(
901 ide,
902 ideInfo.ideType,
903 );
904 if (configJsContents) {
905 try {
906 // Try config.ts first
907 const configJsPath = getConfigJsPath();
908 let module: any;
909
910 try {
911 module = await import(configJsPath);
912 } catch (e) {
913 console.log(e);
914 console.log(
915 "Could not load config.ts as absolute path, retrying as file url ...",
916 );
917 try {
918 module = await import(localPathToUri(configJsPath));
919 } catch (e) {
920 throw new Error("Could not load config.ts as file url either", {
921 cause: e,
922 });
923 }
924 }
925
926 if (typeof require !== "undefined") {
927 delete require.cache[require.resolve(configJsPath)];
928 }
929 if (!module.modifyConfig) {
930 throw new Error("config.ts does not export a modifyConfig function.");
931 }
932 intermediate = module.modifyConfig(intermediate);
933 } catch (e) {
934 console.log("Error loading config.ts: ", e);
935 }
936 }
937
938 // Apply remote config.js to modify intermediate config
939 if (ideSettings.remoteConfigServerUrl) {
940 try {
941 const configJsPathForRemote = getConfigJsPathForRemote(
942 ideSettings.remoteConfigServerUrl,
943 );
944 const module = await import(configJsPathForRemote);
945 if (typeof require !== "undefined") {
946 delete require.cache[require.resolve(configJsPathForRemote)];
947 }
948 if (!module.modifyConfig) {
949 throw new Error("config.ts does not export a modifyConfig function.");
950 }
951 intermediate = module.modifyConfig(intermediate);
952 } catch (e) {
953 console.log("Error loading remotely set config.js: ", e);
954 }
955 }
956
957 // Convert to final config format
958 const { config: finalConfig, errors: finalErrors } =
959 await intermediateToFinalConfig({
960 config: intermediate,
961 ide,
962 ideSettings,
963 ideInfo,
964 uniqueId,
965 llmLogger,
966 workOsAccessToken,
967 });
968 return {
969 config: finalConfig,
970 errors: [...(errors ?? []), ...finalErrors],
971 configLoadInterrupted: false,
972 };
973}
974
975export {
976 finalToBrowserConfig,
977 intermediateToFinalConfig,
978 loadContinueConfigFromJson,
979 type BrowserSerializedContinueConfig,
980};