Elffuss BraidHub

kikocis/continue public

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