Elffuss BraidHub

kikocis/continue public

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