Elffuss BraidHub

kikocis/continue public

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