Elffuss BraidHub

kikocis/continue public

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