Elffuss BraidHub

kikocis/continue public

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