Elffuss BraidHub

kikocis/continue public

main · 13.7 KiBRawPermalink
1import {
2 AssistantUnrolled,
3 BLOCK_TYPES,
4 ConfigResult,
5 ConfigValidationError,
6 isAssistantUnrolledNonNullable,
7 mergeConfigYamlRequestOptions,
8 mergeUnrolledAssistants,
9 ModelRole,
10 PackageIdentifier,
11 RegistryClient,
12 TEMPLATE_VAR_REGEX,
13 unrollAssistant,
14 validateConfigYaml,
15} from "@continuedev/config-yaml";
16import { dirname } from "node:path";
17
18import {
19 ContinueConfig,
20 IDE,
21 IdeInfo,
22 IdeSettings,
23 ILLMLogger,
24 InternalMcpOptions,
25} from "../..";
26import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
27import { ControlPlaneClient } from "../../control-plane/client";
28import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
29import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
30import { GlobalContext } from "../../util/GlobalContext";
31import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
32
33import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
34import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
35import { loadJsonMcpConfigs } from "../../context/mcp/json/loadJsonMcpConfigs";
36import { getControlPlaneEnvSync } from "../../control-plane/env";
37import { PolicySingleton } from "../../control-plane/PolicySingleton";
38import { getBaseToolDefinitions } from "../../tools";
39import { getCleanUriPath } from "../../util/uri";
40import { loadConfigContextProviders } from "../loadContextProviders";
41import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
42import { unrollLocalYamlBlocks } from "./loadLocalYamlBlocks";
43import { LocalPlatformClient } from "./LocalPlatformClient";
44import { llmsFromModelConfig } from "./models";
45import {
46 convertYamlMcpConfigToInternalMcpOptions,
47 convertYamlRuleToContinueRule,
48} from "./yamlToContinueConfig";
49
50async function loadConfigYaml(options: {
51 overrideConfigYaml: AssistantUnrolled | undefined;
52 controlPlaneClient: ControlPlaneClient;
53 orgScopeId: string | null;
54 ideSettings: IdeSettings;
55 ide: IDE;
56 packageIdentifier: PackageIdentifier;
57}): Promise<ConfigResult<AssistantUnrolled>> {
58 const {
59 overrideConfigYaml,
60 controlPlaneClient,
61 orgScopeId,
62 ideSettings,
63 ide,
64 packageIdentifier,
65 } = options;
66
67 // Add local .continue blocks
68 const localBlockPromises = BLOCK_TYPES.map(async (blockType) => {
69 const localBlocks = await getAllDotContinueDefinitionFiles(
70 ide,
71 { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
72 blockType,
73 );
74 return localBlocks.map((b) => ({
75 uriType: "file" as const,
76 fileUri: b.path,
77 }));
78 });
79 const localPackageIdentifiers: PackageIdentifier[] = (
80 await Promise.all(localBlockPromises)
81 ).flat();
82
83 // logger.info(
84 // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
85 // );
86
87 // Registry client is only used if local blocks are present, but logic same for hub/local assistants
88 const getRegistryClient = async () => {
89 const rootPath =
90 packageIdentifier.uriType === "file"
91 ? dirname(getCleanUriPath(packageIdentifier.fileUri))
92 : undefined;
93 return new RegistryClient({
94 accessToken: await controlPlaneClient.getAccessToken(),
95 apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
96 .CONTROL_PLANE_URL,
97 rootPath,
98 });
99 };
100
101 const errors: ConfigValidationError[] = [];
102
103 let config: AssistantUnrolled | undefined;
104
105 if (overrideConfigYaml) {
106 config = overrideConfigYaml;
107 if (localPackageIdentifiers.length > 0) {
108 const unrolledLocal = await unrollLocalYamlBlocks(
109 localPackageIdentifiers,
110 ide,
111 await getRegistryClient(),
112 orgScopeId,
113 controlPlaneClient,
114 );
115 if (unrolledLocal.errors) {
116 errors.push(...unrolledLocal.errors);
117 }
118 if (unrolledLocal.config) {
119 config = mergeUnrolledAssistants(config, unrolledLocal.config);
120 }
121 }
122 } else {
123 // This is how we allow use of blocks locally
124 const unrollResult = await unrollAssistant(
125 packageIdentifier,
126 await getRegistryClient(),
127 {
128 renderSecrets: true,
129 currentUserSlug: "",
130 onPremProxyUrl: null,
131 orgScopeId,
132 platformClient: new LocalPlatformClient(
133 orgScopeId,
134 controlPlaneClient,
135 ide,
136 ),
137 injectBlocks: localPackageIdentifiers,
138 },
139 );
140 config = unrollResult.config;
141 if (unrollResult.errors) {
142 errors.push(...unrollResult.errors);
143 }
144 }
145
146 if (config && isAssistantUnrolledNonNullable(config)) {
147 errors.push(...validateConfigYaml(config));
148 }
149
150 if (errors?.some((error) => error.fatal)) {
151 return {
152 errors,
153 config: undefined,
154 configLoadInterrupted: true,
155 };
156 }
157
158 // Set defaults if undefined (this lets us keep config.json uncluttered for new users)
159 return {
160 config,
161 errors,
162 configLoadInterrupted: false,
163 };
164}
165
166export async function configYamlToContinueConfig(options: {
167 config: AssistantUnrolled;
168 ide: IDE;
169 ideInfo: IdeInfo;
170 uniqueId: string;
171 llmLogger: ILLMLogger;
172 workOsAccessToken: string | undefined;
173}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
174 let { config, ide, ideInfo, uniqueId, llmLogger } = options;
175
176 const localErrors: ConfigValidationError[] = [];
177
178 const continueConfig: ContinueConfig = {
179 slashCommands: [],
180 tools: getBaseToolDefinitions(),
181 mcpServerStatuses: [],
182 contextProviders: [],
183 modelsByRole: {
184 chat: [],
185 edit: [],
186 apply: [],
187 embed: [],
188 autocomplete: [],
189 rerank: [],
190 summarize: [],
191 },
192 selectedModelByRole: {
193 chat: null,
194 edit: null, // not currently used
195 apply: null,
196 embed: null,
197 autocomplete: null,
198 rerank: null,
199 summarize: null,
200 },
201 rules: [],
202 requestOptions: { ...config.requestOptions },
203 };
204
205 // Right now, if there are any missing packages in the config, then we will just throw an error
206 if (!isAssistantUnrolledNonNullable(config)) {
207 return {
208 config: continueConfig,
209 errors: [
210 {
211 message:
212 "Failed to load config due to missing blocks, see which blocks are missing below",
213 fatal: true,
214 },
215 ],
216 };
217 }
218
219 for (const rule of config.rules ?? []) {
220 const convertedRule = convertYamlRuleToContinueRule(rule);
221 continueConfig.rules.push(convertedRule);
222 }
223
224 continueConfig.data = config.data?.map((d) => ({
225 ...d,
226 requestOptions: mergeConfigYamlRequestOptions(
227 d.requestOptions,
228 continueConfig.requestOptions,
229 ),
230 }));
231 continueConfig.docs = config.docs?.map((doc) => ({
232 title: doc.name,
233 startUrl: doc.startUrl,
234 rootUrl: doc.rootUrl,
235 faviconUrl: doc.faviconUrl,
236 useLocalCrawling: doc.useLocalCrawling,
237 sourceFile: doc.sourceFile,
238 }));
239
240 config.mcpServers?.forEach((mcpServer) => {
241 if ("args" in mcpServer) {
242 const mcpArgVariables =
243 mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
244
245 if (mcpArgVariables.length === 0) {
246 return;
247 }
248
249 localErrors.push({
250 fatal: false,
251 message: `MCP server "${mcpServer.name}" has unsubstituted variables in args: ${mcpArgVariables.join(", ")}. Please refer to https://docs.continue.dev/hub/secrets/secret-types for managing hub secrets.`,
252 });
253 }
254 });
255
256 // Prompt files -
257 try {
258 const promptFiles = await getAllPromptFiles(ide, undefined, true);
259
260 promptFiles.forEach((file) => {
261 try {
262 const slashCommand = slashCommandFromPromptFile(
263 file.path,
264 file.content,
265 );
266 if (slashCommand) {
267 continueConfig.slashCommands?.push(slashCommand);
268 }
269 } catch (e) {
270 localErrors.push({
271 fatal: false,
272 message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
273 });
274 }
275 });
276 } catch (e) {
277 localErrors.push({
278 fatal: false,
279 message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`,
280 });
281 }
282
283 config.prompts?.forEach((prompt) => {
284 try {
285 const slashCommand = convertPromptBlockToSlashCommand(prompt);
286 continueConfig.slashCommands?.push(slashCommand);
287 } catch (e) {
288 localErrors.push({
289 message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`,
290 fatal: false,
291 });
292 }
293 });
294
295 // Models
296 let warnAboutFreeTrial = false;
297 const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
298 for (const model of config.models ?? []) {
299 model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
300
301 if (model.provider === "free-trial") {
302 warnAboutFreeTrial = true;
303 }
304 try {
305 const llms = await llmsFromModelConfig({
306 model,
307 uniqueId,
308 llmLogger,
309 config: continueConfig,
310 });
311
312 if (model.roles?.includes("chat")) {
313 continueConfig.modelsByRole.chat.push(...llms);
314 }
315
316 if (model.roles?.includes("summarize")) {
317 continueConfig.modelsByRole.summarize.push(...llms);
318 }
319
320 if (model.roles?.includes("apply")) {
321 continueConfig.modelsByRole.apply.push(...llms);
322 }
323
324 if (model.roles?.includes("edit")) {
325 continueConfig.modelsByRole.edit.push(...llms);
326 }
327
328 if (model.roles?.includes("autocomplete")) {
329 continueConfig.modelsByRole.autocomplete.push(...llms);
330 }
331
332 if (model.roles?.includes("embed")) {
333 const { provider } = model;
334 if (provider === "transformers.js") {
335 if (ideInfo.ideType === "vscode") {
336 continueConfig.modelsByRole.embed.push(
337 new TransformersJsEmbeddingsProvider(),
338 );
339 } else {
340 localErrors.push({
341 fatal: false,
342 message: `Transformers.js embeddings provider not supported in this IDE.`,
343 });
344 }
345 } else {
346 continueConfig.modelsByRole.embed.push(...llms);
347 }
348 }
349
350 if (model.roles?.includes("rerank")) {
351 continueConfig.modelsByRole.rerank.push(...llms);
352 }
353 } catch (e) {
354 localErrors.push({
355 fatal: false,
356 message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`,
357 });
358 }
359 }
360
361 // Add transformers js to the embed models in vs code if not already added
362 if (
363 ideInfo.ideType === "vscode" &&
364 !continueConfig.modelsByRole.embed.find(
365 (m) => m.providerName === "transformers.js",
366 )
367 ) {
368 continueConfig.modelsByRole.embed.push(
369 new TransformersJsEmbeddingsProvider(),
370 );
371 }
372
373 if (warnAboutFreeTrial) {
374 localErrors.push({
375 fatal: false,
376 message:
377 "Model provider 'free-trial' is no longer supported, will be ignored.",
378 });
379 }
380
381 const { providers, errors: contextErrors } = loadConfigContextProviders(
382 config.context,
383 !!config.docs?.length,
384 ideInfo.ideType,
385 );
386
387 continueConfig.contextProviders = providers;
388 localErrors.push(...contextErrors);
389
390 // Trigger MCP server refreshes (Config is reloaded again once connected!)
391 const mcpManager = MCPManagerSingleton.getInstance();
392
393 const orgPolicy = PolicySingleton.getInstance().policy;
394 if (orgPolicy?.policy?.allowMcpServers === false) {
395 await mcpManager.shutdown();
396 } else {
397 const mcpOptions: InternalMcpOptions[] = (config.mcpServers ?? []).map(
398 (server) =>
399 convertYamlMcpConfigToInternalMcpOptions(server, config.requestOptions),
400 );
401 const { errors: jsonMcpErrors, mcpServers } = await loadJsonMcpConfigs(
402 ide,
403 true,
404 config.requestOptions,
405 );
406 localErrors.push(...jsonMcpErrors);
407 mcpOptions.push(...mcpServers);
408 mcpManager.setConnections(mcpOptions, false, { ide });
409 }
410
411 return { config: continueConfig, errors: localErrors };
412}
413
414export async function loadContinueConfigFromYaml(options: {
415 ide: IDE;
416 ideSettings: IdeSettings;
417 ideInfo: IdeInfo;
418 uniqueId: string;
419 llmLogger: ILLMLogger;
420 workOsAccessToken: string | undefined;
421 overrideConfigYaml: AssistantUnrolled | undefined;
422 controlPlaneClient: ControlPlaneClient;
423 orgScopeId: string | null;
424 packageIdentifier: PackageIdentifier;
425}): Promise<ConfigResult<ContinueConfig>> {
426 const {
427 ide,
428 ideSettings,
429 ideInfo,
430 uniqueId,
431 llmLogger,
432 workOsAccessToken,
433 overrideConfigYaml,
434 controlPlaneClient,
435 orgScopeId,
436 packageIdentifier,
437 } = options;
438
439 const configYamlResult = await loadConfigYaml({
440 overrideConfigYaml,
441 controlPlaneClient,
442 orgScopeId,
443 ideSettings,
444 ide,
445 packageIdentifier,
446 });
447
448 if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
449 return {
450 errors: configYamlResult.errors,
451 config: undefined,
452 configLoadInterrupted: true,
453 };
454 }
455
456 const { config: continueConfig, errors: localErrors } =
457 await configYamlToContinueConfig({
458 config: configYamlResult.config,
459 ide,
460 ideInfo,
461 uniqueId,
462 llmLogger,
463 workOsAccessToken,
464 });
465
466 // Apply shared config
467 // TODO: override several of these values with user/org shared config
468 // Don't try catch this - has security implications and failure should be fatal
469 const sharedConfig = new GlobalContext().getSharedConfig();
470 const withShared = modifyAnyConfigWithSharedConfig(
471 continueConfig,
472 sharedConfig,
473 );
474 if (withShared.allowAnonymousTelemetry === undefined) {
475 withShared.allowAnonymousTelemetry = true;
476 }
477
478 return {
479 config: withShared,
480 errors: [...(configYamlResult.errors ?? []), ...localErrors],
481 configLoadInterrupted: false,
482 };
483}