Elffuss BraidHub

kikocis/continue public

22e692d80113 · 28.1 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 envSecretLocations: llm.envSecretLocations,
655 };
656}
657
658async function finalToBrowserConfig(
659 final: ContinueConfig,
660 ide: IDE,
661): Promise<BrowserSerializedContinueConfig> {
662 return {
663 allowAnonymousTelemetry: final.allowAnonymousTelemetry,
664 completionOptions: final.completionOptions,
665 slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
666 ...rest,
667 isLegacy: !!run,
668 })),
669 contextProviders: final.contextProviders?.map((c) => c.description),
670 disableIndexing: final.disableIndexing,
671 disableSessionTitles: final.disableSessionTitles,
672 userToken: final.userToken,
673 ui: final.ui,
674 experimental: final.experimental,
675 rules: final.rules,
676 docs: final.docs,
677 tools: final.tools,
678 mcpServerStatuses: final.mcpServerStatuses,
679 tabAutocompleteOptions: final.tabAutocompleteOptions,
680 usePlatform: await useHub(ide.getIdeSettings()),
681 modelsByRole: Object.fromEntries(
682 Object.entries(final.modelsByRole).map(([k, v]) => [
683 k,
684 v.map(llmToSerializedModelDescription),
685 ]),
686 ) as Record<ModelRole, ModelDescription[]>, // TODO better types here
687 selectedModelByRole: Object.fromEntries(
688 Object.entries(final.selectedModelByRole).map(([k, v]) => [
689 k,
690 v ? llmToSerializedModelDescription(v) : null,
691 ]),
692 ) as Record<ModelRole, ModelDescription | null>, // TODO better types here
693 // data not included here because client doesn't need
694 };
695}
696
697function escapeSpacesInPath(p: string): string {
698 return p.replace(/ /g, "\\ ");
699}
700
701async function handleEsbuildInstallation(ide: IDE, ideType: IdeType) {
702 // JetBrains is currently the only IDE that we've reached the plugin size limit and
703 // therefore need to install esbuild manually to reduce the size
704 if (ideType !== "jetbrains") {
705 return;
706 }
707
708 const globalContext = new GlobalContext();
709 if (globalContext.get("hasDismissedConfigTsNoticeJetBrains")) {
710 return;
711 }
712
713 const esbuildPath = getEsbuildBinaryPath();
714
715 if (fs.existsSync(esbuildPath)) {
716 return;
717 }
718
719 console.debug("No esbuild binary detected");
720
721 const shouldInstall = await promptEsbuildInstallation(ide);
722
723 if (shouldInstall) {
724 await downloadAndInstallEsbuild(ide);
725 }
726}
727
728async function promptEsbuildInstallation(ide: IDE): Promise<boolean> {
729 const installMsg = "Install esbuild";
730 const dismissMsg = "Dismiss";
731
732 const res = await ide.showToast(
733 "warning",
734 "You're using a custom 'config.ts' file, which requires 'esbuild' to be installed. Would you like to install it now?",
735 dismissMsg,
736 installMsg,
737 );
738
739 if (res === dismissMsg) {
740 const globalContext = new GlobalContext();
741 globalContext.update("hasDismissedConfigTsNoticeJetBrains", true);
742 return false;
743 }
744
745 return res === installMsg;
746}
747
748/**
749 * The download logic is adapted from here: https://esbuild.github.io/getting-started/#download-a-build
750 */
751async function downloadAndInstallEsbuild(ide: IDE) {
752 const esbuildPath = getEsbuildBinaryPath();
753 const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "esbuild-"));
754
755 try {
756 const target = `${os.platform()}-${os.arch()}`;
757 const version = "0.19.11";
758 const url = `https://registry.npmjs.org/@esbuild/${target}/-/${target}-${version}.tgz`;
759 const tgzPath = path.join(tempDir, `esbuild-${version}.tgz`);
760
761 console.debug(`Downloading esbuild from: ${url}`);
762 execSync(`curl -fo "${tgzPath}" "${url}"`);
763
764 console.debug(`Extracting tgz file to: ${tempDir}`);
765 await tar.x({
766 file: tgzPath,
767 cwd: tempDir,
768 strip: 2, // Remove the top two levels of directories
769 });
770
771 // Ensure the destination directory exists
772 const destDir = path.dirname(esbuildPath);
773 if (!fs.existsSync(destDir)) {
774 fs.mkdirSync(destDir, { recursive: true });
775 }
776
777 // Move the file
778 const extractedBinaryPath = path.join(tempDir, "esbuild");
779 fs.renameSync(extractedBinaryPath, esbuildPath);
780
781 // Ensure the binary is executable (not needed on Windows)
782 if (os.platform() !== "win32") {
783 fs.chmodSync(esbuildPath, 0o755);
784 }
785
786 // Clean up
787 fs.unlinkSync(tgzPath);
788 fs.rmSync(tempDir, { recursive: true });
789
790 await ide.showToast(
791 "info",
792 `'esbuild' successfully installed to ${esbuildPath}`,
793 );
794 } catch (error) {
795 console.error("Error downloading or saving esbuild binary:", error);
796 throw error;
797 }
798}
799
800async function tryBuildConfigTs() {
801 try {
802 if (process.env.IS_BINARY === "true") {
803 await buildConfigTsWithBinary();
804 } else {
805 await buildConfigTsWithNodeModule();
806 }
807 } catch (e) {
808 console.log(
809 `Build error. Please check your ~/.continue/config.ts file: ${e}`,
810 );
811 }
812}
813
814async function buildConfigTsWithBinary() {
815 const cmd = [
816 escapeSpacesInPath(getEsbuildBinaryPath()),
817 escapeSpacesInPath(getConfigTsPath()),
818 "--bundle",
819 `--outfile=${escapeSpacesInPath(getConfigJsPath())}`,
820 "--platform=node",
821 "--format=cjs",
822 "--sourcemap",
823 "--external:fetch",
824 "--external:fs",
825 "--external:path",
826 "--external:os",
827 "--external:child_process",
828 ].join(" ");
829
830 execSync(cmd);
831}
832
833async function buildConfigTsWithNodeModule() {
834 const { build } = await import("esbuild");
835
836 await build({
837 entryPoints: [getConfigTsPath()],
838 bundle: true,
839 platform: "node",
840 format: "cjs",
841 outfile: getConfigJsPath(),
842 external: ["fetch", "fs", "path", "os", "child_process"],
843 sourcemap: true,
844 });
845}
846
847function readConfigJs(): string | undefined {
848 const configJsPath = getConfigJsPath();
849
850 if (!fs.existsSync(configJsPath)) {
851 return undefined;
852 }
853
854 return fs.readFileSync(configJsPath, "utf8");
855}
856
857async function buildConfigTsandReadConfigJs(ide: IDE, ideType: IdeType) {
858 const configTsPath = getConfigTsPath();
859
860 if (!fs.existsSync(configTsPath)) {
861 return;
862 }
863
864 const currentContent = fs.readFileSync(configTsPath, "utf8");
865
866 // If the user hasn't modified the default config.ts, don't bother building
867 if (currentContent.trim() === DEFAULT_CONFIG_TS_CONTENTS.trim()) {
868 return;
869 }
870
871 await handleEsbuildInstallation(ide, ideType);
872 await tryBuildConfigTs();
873
874 return readConfigJs();
875}
876
877async function loadContinueConfigFromJson(
878 ide: IDE,
879 workspaceConfigs: ContinueRcJson[],
880 ideSettings: IdeSettings,
881 ideInfo: IdeInfo,
882 uniqueId: string,
883 llmLogger: ILLMLogger,
884 workOsAccessToken: string | undefined,
885 overrideConfigJson: SerializedContinueConfig | undefined,
886): Promise<ConfigResult<ContinueConfig>> {
887 // Serialized config
888 let {
889 config: serialized,
890 errors,
891 configLoadInterrupted,
892 } = loadSerializedConfig(
893 workspaceConfigs,
894 ideSettings,
895 ideInfo.ideType,
896 overrideConfigJson,
897 ide,
898 );
899
900 if (!serialized || configLoadInterrupted) {
901 return { errors, config: undefined, configLoadInterrupted: true };
902 }
903
904 // Apply shared config
905 // TODO: override several of these values with user/org shared config
906 const sharedConfig = new GlobalContext().getSharedConfig();
907 const withShared = modifyAnyConfigWithSharedConfig(serialized, sharedConfig);
908
909 // Convert serialized to intermediate config
910 let intermediate = await serializedToIntermediateConfig(withShared, ide);
911
912 // Apply config.ts to modify intermediate config
913 const configJsContents = await buildConfigTsandReadConfigJs(
914 ide,
915 ideInfo.ideType,
916 );
917 if (configJsContents) {
918 try {
919 // Try config.ts first
920 const configJsPath = getConfigJsPath();
921 let module: any;
922
923 try {
924 module = await import(configJsPath);
925 } catch (e) {
926 console.log(e);
927 console.log(
928 "Could not load config.ts as absolute path, retrying as file url ...",
929 );
930 try {
931 module = await import(localPathToUri(configJsPath));
932 } catch (e) {
933 throw new Error("Could not load config.ts as file url either", {
934 cause: e,
935 });
936 }
937 }
938
939 if (typeof require !== "undefined") {
940 delete require.cache[require.resolve(configJsPath)];
941 }
942 if (!module.modifyConfig) {
943 throw new Error("config.ts does not export a modifyConfig function.");
944 }
945 intermediate = module.modifyConfig(intermediate);
946 } catch (e) {
947 console.log("Error loading config.ts: ", e);
948 }
949 }
950
951 // Apply remote config.js to modify intermediate config
952 if (ideSettings.remoteConfigServerUrl) {
953 try {
954 const configJsPathForRemote = getConfigJsPathForRemote(
955 ideSettings.remoteConfigServerUrl,
956 );
957 const module = await import(configJsPathForRemote);
958 if (typeof require !== "undefined") {
959 delete require.cache[require.resolve(configJsPathForRemote)];
960 }
961 if (!module.modifyConfig) {
962 throw new Error("config.ts does not export a modifyConfig function.");
963 }
964 intermediate = module.modifyConfig(intermediate);
965 } catch (e) {
966 console.log("Error loading remotely set config.js: ", e);
967 }
968 }
969
970 // Convert to final config format
971 const { config: finalConfig, errors: finalErrors } =
972 await intermediateToFinalConfig({
973 config: intermediate,
974 ide,
975 ideSettings,
976 ideInfo,
977 uniqueId,
978 llmLogger,
979 workOsAccessToken,
980 });
981 return {
982 config: finalConfig,
983 errors: [...(errors ?? []), ...finalErrors],
984 configLoadInterrupted: false,
985 };
986}
987
988export {
989 finalToBrowserConfig,
990 loadContinueConfigFromJson,
991 type BrowserSerializedContinueConfig,
992};