Elffuss BraidHub

kikocis/continue public

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