Elffuss BraidHub

kikocis/continue public

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