Elffuss BraidHub

kikocis/continue public

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