Elffuss BraidHub

kikocis/continue public

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