Elffuss BraidHub

kikocis/continue public

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