Elffuss BraidHub

kikocis/continue public

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