Elffuss BraidHub

kikocis/continue public

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