Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 27.2 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 { getToolsForIde } 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 },
286 ide.readFile.bind(ide),
287 getUriFromPath,
288 uniqueId,
289 ideSettings,
290 llmLogger,
291 copyOf(config.completionOptions),
292 );
293 }),
294 );
295 models.push(
296 ...(detectedModels.filter(
297 (x) => typeof x !== "undefined",
298 ) as BaseLLM[]),
299 );
300 } catch (e) {
301 console.warn("Error listing models: ", e);
302 }
303 } else {
304 models.push(llm);
305 }
306 } else {
307 const llm = new CustomLLMClass({
308 ...desc,
309 options: { ...desc.options, logger: llmLogger } as any,
310 });
311 if (llm.model === "AUTODETECT") {
312 try {
313 const modelNames = await llm.listModels();
314 const models = modelNames.map(
315 (modelName) =>
316 new CustomLLMClass({
317 ...desc,
318 options: {
319 ...desc.options,
320 model: modelName,
321 logger: llmLogger,
322 },
323 }),
324 );
325
326 models.push(...models);
327 } catch (e) {
328 console.warn("Error listing models: ", e);
329 }
330 } else {
331 models.push(llm);
332 }
333 }
334 }),
335 );
336
337 applyRequestOptionsToModels(models, config, [
338 "chat",
339 "apply",
340 "edit",
341 "summarize",
342 ]); // Default to chat role if not specified
343
344 // Free trial provider will be completely ignored
345 let warnAboutFreeTrial = false;
346 models = models.filter((model) => model.providerName !== "free-trial");
347 if (models.filter((m) => m.providerName === "free-trial").length) {
348 warnAboutFreeTrial = true;
349 }
350
351 // Tab autocomplete model
352 const tabAutocompleteModels: BaseLLM[] = [];
353 if (config.tabAutocompleteModel) {
354 const autocompleteConfigs = Array.isArray(config.tabAutocompleteModel)
355 ? config.tabAutocompleteModel
356 : [config.tabAutocompleteModel];
357
358 await Promise.all(
359 autocompleteConfigs.map(async (desc) => {
360 if ("title" in desc) {
361 const llm = await llmFromDescription(
362 desc,
363 ide.readFile.bind(ide),
364 getUriFromPath,
365 uniqueId,
366 ideSettings,
367 llmLogger,
368 config.completionOptions,
369 );
370 if (llm) {
371 if (llm.providerName === "free-trial") {
372 warnAboutFreeTrial = true;
373 } else {
374 tabAutocompleteModels.push(llm);
375 }
376 }
377 } else {
378 tabAutocompleteModels.push(new CustomLLMClass(desc));
379 }
380 }),
381 );
382 }
383
384 applyRequestOptionsToModels(tabAutocompleteModels, config);
385
386 // Load context providers
387 const { providers: contextProviders, errors: contextErrors } =
388 loadConfigContextProviders(
389 config.contextProviders
390 ?.filter((cp) => isContextProviderWithParams(cp))
391 .map((cp) => ({
392 provider: (cp as ContextProviderWithParams).name,
393 params: (cp as ContextProviderWithParams).params,
394 })),
395 !!config.docs?.length,
396 ideInfo.ideType,
397 );
398
399 for (const cp of config.contextProviders ?? []) {
400 if (!isContextProviderWithParams(cp)) {
401 contextProviders.push(new CustomContextProviderClass(cp));
402 }
403 }
404 errors.push(...contextErrors);
405
406 // Embeddings Provider
407 function getEmbeddingsILLM(
408 embedConfig: EmbeddingsProviderDescription | ILLM | undefined,
409 ): ILLM | null {
410 if (embedConfig) {
411 // config.ts-injected ILLM
412 if ("providerName" in embedConfig) {
413 return embedConfig;
414 }
415 const { provider, ...options } = embedConfig;
416 if (provider === "transformers.js" || provider === "free-trial") {
417 if (provider === "free-trial") {
418 warnAboutFreeTrial = true;
419 }
420 return new TransformersJsEmbeddingsProvider();
421 } else {
422 const cls = LLMClasses.find((c) => c.providerName === provider);
423 if (cls) {
424 const llmOptions: LLMOptions = {
425 model: options.model ?? "UNSPECIFIED",
426 ...options,
427 };
428 return new cls(llmOptions);
429 } else {
430 errors.push({
431 fatal: false,
432 message: `Embeddings provider ${provider} not found`,
433 });
434 }
435 }
436 }
437 if (ideInfo.ideType === "vscode") {
438 return new TransformersJsEmbeddingsProvider();
439 }
440 return null;
441 }
442 const newEmbedder = getEmbeddingsILLM(config.embeddingsProvider);
443
444 // Reranker
445 function getRerankingILLM(
446 rerankingConfig: ILLM | RerankerDescription | undefined,
447 ): ILLM | null {
448 if (!rerankingConfig) {
449 return null;
450 }
451 // config.ts-injected ILLM
452 if ("providerName" in rerankingConfig) {
453 return rerankingConfig;
454 }
455 const { name, params } = config.reranker as RerankerDescription;
456 if (name === "free-trial") {
457 warnAboutFreeTrial = true;
458 return null;
459 }
460 if (name === "llm") {
461 const llm = models.find((model) => model.title === params?.modelTitle);
462 if (!llm) {
463 errors.push({
464 fatal: false,
465 message: `Unknown reranking model ${params?.modelTitle}`,
466 });
467 return null;
468 } else {
469 return new LLMReranker(llm);
470 }
471 } else {
472 const cls = LLMClasses.find((c) => c.providerName === name);
473 if (cls) {
474 const llmOptions: LLMOptions = {
475 model: params?.model ?? "UNSPECIFIED",
476 ...params,
477 };
478 return new cls(llmOptions);
479 } else {
480 errors.push({
481 fatal: false,
482 message: `Unknown reranking provider ${name}`,
483 });
484 }
485 }
486 return null;
487 }
488 const newReranker = getRerankingILLM(config.reranker);
489
490 if (warnAboutFreeTrial) {
491 errors.push({
492 fatal: false,
493 message:
494 "Model provider 'free-trial' is no longer supported, will be ignored",
495 });
496 }
497
498 const continueConfig: ContinueConfig = {
499 ...config,
500 contextProviders,
501 tools: await getToolsForIde(ide),
502 mcpServerStatuses: [],
503 slashCommands: [],
504 modelsByRole: {
505 chat: models,
506 edit: models,
507 apply: models,
508 summarize: models,
509 autocomplete: [...tabAutocompleteModels],
510 embed: newEmbedder ? [newEmbedder] : [],
511 rerank: newReranker ? [newReranker] : [],
512 },
513 selectedModelByRole: {
514 chat: null, // Not implemented (uses GUI defaultModel)
515 edit: null,
516 apply: null,
517 embed: newEmbedder ?? null,
518 autocomplete: null,
519 rerank: newReranker ?? null,
520 summarize: null, // Not implemented
521 },
522 rules: [],
523 };
524
525 for (const cmd of config.slashCommands ?? []) {
526 if ("source" in cmd) {
527 continueConfig.slashCommands.push(cmd);
528 } else {
529 continueConfig.slashCommands.push({
530 ...cmd,
531 source: "config-ts-slash-command",
532 });
533 }
534 }
535
536 if (config.systemMessage) {
537 continueConfig.rules.unshift({
538 rule: config.systemMessage,
539 source: "json-systemMessage",
540 });
541 }
542
543 // Trigger MCP server refreshes (Config is reloaded again once connected!)
544 const mcpManager = MCPManagerSingleton.getInstance();
545 mcpManager.setConnections(
546 (config.experimental?.modelContextProtocolServers ?? []).map(
547 (server, index) => ({
548 id: `continue-mcp-server-${index + 1}`,
549 name: `MCP Server`,
550 ...server,
551 }),
552 ),
553 false,
554 );
555
556 // Handle experimental modelRole config values for apply and edit
557 const inlineEditModel = getModelByRole(continueConfig, "inlineEdit")?.title;
558 if (inlineEditModel) {
559 const match = continueConfig.modelsByRole.chat.find(
560 (m) => m.title === inlineEditModel,
561 );
562 if (match) {
563 continueConfig.selectedModelByRole.edit = match;
564 continueConfig.modelsByRole.edit = [match]; // The only option if inlineEdit role is set
565 } else {
566 errors.push({
567 fatal: false,
568 message: `experimental.modelRoles.inlineEdit model title ${inlineEditModel} not found in models array`,
569 });
570 }
571 }
572
573 const applyBlockModel = getModelByRole(
574 continueConfig,
575 "applyCodeBlock",
576 )?.title;
577 if (applyBlockModel) {
578 const match = continueConfig.modelsByRole.chat.find(
579 (m) => m.title === applyBlockModel,
580 );
581 if (match) {
582 continueConfig.selectedModelByRole.apply = match;
583 continueConfig.modelsByRole.apply = [match]; // The only option if applyCodeBlock role is set
584 } else {
585 errors.push({
586 fatal: false,
587 message: `experimental.modelRoles.applyCodeBlock model title ${inlineEditModel} not found in models array`,
588 });
589 }
590 }
591
592 // Add transformers JS to the embed models list if not already added
593 if (
594 ideInfo.ideType === "vscode" &&
595 !continueConfig.modelsByRole.embed.find(
596 (m) => m.providerName === "transformers.js",
597 )
598 ) {
599 continueConfig.modelsByRole.embed.push(
600 new TransformersJsEmbeddingsProvider(),
601 );
602 }
603
604 return { config: continueConfig, errors };
605}
606
607function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
608 return {
609 provider: llm.providerName,
610 underlyingProviderName: llm.underlyingProviderName,
611 model: llm.model,
612 title: llm.title ?? llm.model,
613 apiKey: llm.apiKey,
614 apiBase: llm.apiBase,
615 contextLength: llm.contextLength,
616 template: llm.template,
617 completionOptions: llm.completionOptions,
618 baseAgentSystemMessage: llm.baseAgentSystemMessage,
619 basePlanSystemMessage: llm.basePlanSystemMessage,
620 baseChatSystemMessage: llm.baseChatSystemMessage,
621 requestOptions: llm.requestOptions,
622 promptTemplates: serializePromptTemplates(llm.promptTemplates),
623 capabilities: llm.capabilities,
624 roles: llm.roles,
625 configurationStatus: llm.getConfigurationStatus(),
626 apiKeyLocation: llm.apiKeyLocation,
627 envSecretLocations: llm.envSecretLocations,
628 sourceFile: llm.sourceFile,
629 };
630}
631
632async function finalToBrowserConfig(
633 final: ContinueConfig,
634 ide: IDE,
635): Promise<BrowserSerializedContinueConfig> {
636 return {
637 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
638 completionOptions: final.completionOptions,
639 slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
640 ...rest,
641 isLegacy: !!run,
642 })),
643 contextProviders: final.contextProviders?.map((c) => c.description),
644 disableIndexing: final.disableIndexing,
645 disableSessionTitles: final.disableSessionTitles,
646 userToken: final.userToken,
647 ui: final.ui,
648 experimental: final.experimental,
649 rules: final.rules,
650 docs: final.docs,
651 tools: final.tools,
652 mcpServerStatuses: final.mcpServerStatuses,
653 tabAutocompleteOptions: final.tabAutocompleteOptions,
654 usePlatform: await useHub(ide.getIdeSettings()),
655 modelsByRole: Object.fromEntries(
656 Object.entries(final.modelsByRole).map(([k, v]) => [
657 k,
658 v.map(llmToSerializedModelDescription),
659 ]),
660 ) as Record<ModelRole, ModelDescription[]>, // TODO better types here
661 selectedModelByRole: Object.fromEntries(
662 Object.entries(final.selectedModelByRole).map(([k, v]) => [
663 k,
664 v ? llmToSerializedModelDescription(v) : null,
665 ]),
666 ) as Record<ModelRole, ModelDescription | null>, // TODO better types here
667 // data not included here because client doesn't need
668 };
669}
670
671function escapeSpacesInPath(p: string): string {
672 return p.replace(/ /g, "\\ ");
673}
674
675async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) {
676 // JetBrains is currently the only IDE that we've reached the plugin size limit and
677 // therefore need to install esbuild manually to reduce the size
678 if (ideType !== "jetbrains") {
679 return;
680 }
681
682 const globalContext = new GlobalContext();
683 if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) {
684 return;
685 }
686
687 const esbuildPath = getEsbuildBinaryPath();
688
689 if (fs.existsSync(esbuildPath)) {
690 return;
691 }
692
693 console.debug("No esbuild binary detected");
694
695 const shouldInstall = await promptEsbuildInstallation(ide);
696
697 if (shouldInstall) {
698 await downloadAndInstallEsbuild(ide);
699 }
700}
701
702async function promptEsbuildInstallation(ide: IDE): Promise<boolean> {
703 const installMsg = "Install esbuild";
704 const dismissMsg = "Dismiss";
705
706 const res = await ide.showToast(
707 "warning",
708 "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?",
709 dismissMsg,
710 installMsg,
711 );
712
713 if (res === dismissMsg) {
714 const globalContext = new GlobalContext();
715 globalContext.update("hasDismissedConfigTsNoticeJetBrains", true);
716 return false;
717 }
718
719 return res === installMsg;
720}
721
722/**
723 * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build
724 */
725async function downloadAndInstallEsbuild(ide: IDE) {
726 const esbuildPath = getEsbuildBinaryPath();
727 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-"));
728
729 try {
730 const target = `${os.platform()}-${os.arch()}`;
731 const version = "0.19.11";
732 const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`;
733 const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`);
734
735 console.debug(`Downloading esbuild from: ${url}`);
736 execSync(`curl -fo "${tgzPath}" "${url}"`);
737
738 console.debug(`Extracting tgz file to: ${tempDir}`);
739 await tar.x({
740 file: tgzPath,
741 cwd: tempDir,
742 strip: 2, // Remove the top two levels of directories
743 });
744
745 // Ensure the destination directory exists
746 const destDir = path.dirname(esbuildPath);
747 if (!fs.existsSync(destDir)) {
748 fs.mkdirSync(destDir, { recursive: true });
749 }
750
751 // Move the file
752 const extractedBinaryPath = path.join(tempDir, "esbuild");
753 fs.renameSync(extractedBinaryPath, esbuildPath);
754
755 // Ensure the binary is executable (not needed on Windows)
756 if (os.platform() !== "win32") {
757 fs.chmodSync(esbuildPath, 0o755);
758 }
759
760 // Clean up
761 fs.unlinkSync(tgzPath);
762 fs.rmSync(tempDir, { recursive: true });
763
764 await ide.showToast(
765 "info",
766 `'esbuild' successfully installed to ${esbuildPath}`,
767 );
768 } catch (error) {
769 console.error("Error downloading or saving esbuild binary:", error);
770 throw error;
771 }
772}
773
774async function tryBuildConfigTs() {
775 try {
776 if (process.env.IS_BINARY === "true") {
777 await buildConfigTsWithBinary();
778 } else {
779 await buildConfigTsWithNodeModule();
780 }
781 } catch (e) {
782 console.log(
783 `Build error. Please check your ~/.continue/config.ts file: ${e}`,
784 );
785 }
786}
787
788async function buildConfigTsWithBinary() {
789 const cmd = [
790 escapeSpacesInPath(getEsbuildBinaryPath()),
791 escapeSpacesInPath(getConfigTsPath()),
792 "--bundle",
793 `--outfile=${escapeSpacesInPath(getConfigJsPath())}`,
794 "--platform=node",
795 "--format=cjs",
796 "--sourcemap",
797 "--external:fetch",
798 "--external:fs",
799 "--external:path",
800 "--external:os",
801 "--external:child_process",
802 ].join(" ");
803
804 execSync(cmd);
805}
806
807async function buildConfigTsWithNodeModule() {
808 const { build } = await import("esbuild");
809
810 await build({
811 entryPoints: [getConfigTsPath()],
812 bundle: true,
813 platform: "node",
814 format: "cjs",
815 outfile: getConfigJsPath(),
816 external: ["fetch", "fs", "path", "os", "child_process"],
817 sourcemap: true,
818 });
819}
820
821function readConfigJs(): string | undefined {
822 const configJsPath = getConfigJsPath();
823
824 if (!fs.existsSync(configJsPath)) {
825 return undefined;
826 }
827
828 return fs.readFileSync(configJsPath, "utf8");
829}
830
831async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
832 const configTsPath = getConfigTsPath();
833
834 if (!fs.existsSync(configTsPath)) {
835 return;
836 }
837
838 const currentContent = fs.readFileSync(configTsPath, "utf8");
839
840 // If the user hasn't modified the default config.ts, don't bother building
841 if (currentContent.trim() === DEFAULT_CONFIG_TS_CONTENTS.trim()) {
842 return;
843 }
844
845 await handleEsbuildInstallation(ide, ideType);
846 await tryBuildConfigTs();
847
848 return readConfigJs();
849}
850
851async function loadContinueConfigFromJson(
852 ide: IDE,
853 ideSettings: IdeSettings,
854 ideInfo: IdeInfo,
855 uniqueId: string,
856 llmLogger: ILLMLogger,
857 workOsAccessToken: string | undefined,
858 overrideConfigJson: SerializedContinueConfig | undefined,
859): Promise<ConfigResult<ContinueConfig>> {
860 const workspaceConfigs = await getWorkspaceRcConfigs(ide);
861 // Serialized config
862 let {
863 config: serialized,
864 errors,
865 configLoadInterrupted,
866 } = loadSerializedConfig(
867 workspaceConfigs,
868 ideSettings,
869 ideInfo.ideType,
870 overrideConfigJson,
871 ide,
872 );
873
874 if (!serialized || configLoadInterrupted) {
875 return { errors, config: undefined, configLoadInterrupted: true };
876 }
877
878 // Apply shared config
879 // TODO: override several of these values with user/org shared config
880 const sharedConfig = new GlobalContext().getSharedConfig();
881 const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
882
883 // Convert serialized to intermediate config
884 let intermediate = await serializedToIntermediateConfig(withShared, ide);
885
886 // Apply config.ts to modify intermediate config
887 const configJsContents = await buildConfigTsandReadConfigJs(
888 ide,
889 ideInfo.ideType,
890 );
891 if (configJsContents) {
892 try {
893 // Try config.ts first
894 const configJsPath = getConfigJsPath();
895 let module: any;
896
897 try {
898 module = await import(configJsPath);
899 } catch (e) {
900 console.log(e);
901 console.log(
902 "Could not load config.ts as absolute path, retrying as file url ...",
903 );
904 try {
905 module = await import(localPathToUri(configJsPath));
906 } catch (e) {
907 throw new Error("Could not load config.ts as file url either", {
908 cause: e,
909 });
910 }
911 }
912
913 if (typeof require !== "undefined") {
914 delete require.cache[require.resolve(configJsPath)];
915 }
916 if (!module.modifyConfig) {
917 throw new Error("config.ts does not export a modifyConfig function.");
918 }
919 intermediate = module.modifyConfig(intermediate);
920 } catch (e) {
921 console.log("Error loading config.ts: ", e);
922 }
923 }
924
925 // Apply remote config.js to modify intermediate config
926 if (ideSettings.remoteConfigServerUrl) {
927 try {
928 const configJsPathForRemote = getConfigJsPathForRemote(
929 ideSettings.remoteConfigServerUrl,
930 );
931 const module = await import(configJsPathForRemote);
932 if (typeof require !== "undefined") {
933 delete require.cache[require.resolve(configJsPathForRemote)];
934 }
935 if (!module.modifyConfig) {
936 throw new Error("config.ts does not export a modifyConfig function.");
937 }
938 intermediate = module.modifyConfig(intermediate);
939 } catch (e) {
940 console.log("Error loading remotely set config.js: ", e);
941 }
942 }
943
944 // Convert to final config format
945 const { config: finalConfig, errors: finalErrors } =
946 await intermediateToFinalConfig({
947 config: intermediate,
948 ide,
949 ideSettings,
950 ideInfo,
951 uniqueId,
952 llmLogger,
953 workOsAccessToken,
954 });
955 return {
956 config: finalConfig,
957 errors: [...(errors ?? []), ...finalErrors],
958 configLoadInterrupted: false,
959 };
960}
961
962export {
963 finalToBrowserConfig,
964 loadContinueConfigFromJson,
965 type BrowserSerializedContinueConfig,
966};