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