Elffuss BraidHub

kikocis/continue public

e8ee99375f3e · 14.0 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 { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
29import DocsContextProvider from "../../context/providers/DocsContextProvider";
30import FileContextProvider from "../../context/providers/FileContextProvider";
31import { contextProviderClassFromName } from "../../context/providers/index";
32import { ControlPlaneClient } from "../../control-plane/client";
33import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
34import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
35import { GlobalContext } from "../../util/GlobalContext";
36import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
37
38import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
39import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
40import { getControlPlaneEnvSync } from "../../control-plane/env";
41import { getToolsForIde } from "../../tools";
42import { getCleanUriPath } from "../../util/uri";
43import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
44import { LocalPlatformClient } from "./LocalPlatformClient";
45import { llmsFromModelConfig } from "./models";
46
47function convertYamlRuleToContinueRule(rule: Rule): RuleWithSource {
48 if (typeof rule === "string") {
49 return {
50 rule: rule,
51 source: "rules-block",
52 };
53 } else {
54 return {
55 source: "rules-block",
56 rule: rule.rule,
57 globs: rule.globs,
58 name: rule.name,
59 };
60 }
61}
62
63function convertYamlMcpToContinueMcp(
64 server: MCPServer,
65): ExperimentalMCPOptions {
66 return {
67 transport: {
68 type: "stdio",
69 command: server.command,
70 args: server.args ?? [],
71 env: server.env,
72 cwd: server.cwd,
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 = slashCommandFromPromptFile(
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 = convertPromptBlockToSlashCommand(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 DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
389
390 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
391 ({ description: { title } }) => title,
392 );
393
394 continueConfig.contextProviders = (config.context
395 ?.map((context) => {
396 const cls = contextProviderClassFromName(context.provider) as any;
397 if (!cls) {
398 if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
399 localErrors.push({
400 fatal: false,
401 message: `Unknown context provider ${context.provider}`,
402 });
403 }
404 return undefined;
405 }
406 const instance: IContextProvider = new cls({
407 name: context.name,
408 ...context.params,
409 });
410 return instance;
411 })
412 .filter((p) => !!p) ?? []) as IContextProvider[];
413 continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
414
415 if (
416 continueConfig.docs?.length &&
417 !continueConfig.contextProviders?.some(
418 (cp) => cp.description.title === "docs",
419 )
420 ) {
421 continueConfig.contextProviders.push(new DocsContextProvider({}));
422 }
423
424 // Trigger MCP server refreshes (Config is reloaded again once connected!)
425 const mcpManager = MCPManagerSingleton.getInstance();
426 mcpManager.setConnections(
427 (config.mcpServers ?? []).map((server) => ({
428 id: server.name,
429 name: server.name,
430 transport: {
431 type: "stdio",
432 args: [],
433 ...(server as any), // TODO: fix the types on mcpServers in config-yaml
434 },
435 timeout: server.connectionTimeout,
436 })),
437 false,
438 );
439
440 return { config: continueConfig, errors: localErrors };
441}
442
443export async function loadContinueConfigFromYaml(options: {
444 ide: IDE;
445 ideSettings: IdeSettings;
446 ideInfo: IdeInfo;
447 uniqueId: string;
448 llmLogger: ILLMLogger;
449 workOsAccessToken: string | undefined;
450 overrideConfigYaml: AssistantUnrolled | undefined;
451 controlPlaneClient: ControlPlaneClient;
452 orgScopeId: string | null;
453 packageIdentifier: PackageIdentifier;
454}): Promise<ConfigResult<ContinueConfig>> {
455 const {
456 ide,
457 ideSettings,
458 ideInfo,
459 uniqueId,
460 llmLogger,
461 workOsAccessToken,
462 overrideConfigYaml,
463 controlPlaneClient,
464 orgScopeId,
465 packageIdentifier,
466 } = options;
467
468 const configYamlResult = await loadConfigYaml({
469 overrideConfigYaml,
470 controlPlaneClient,
471 orgScopeId,
472 ideSettings,
473 ide,
474 packageIdentifier,
475 });
476
477 if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
478 return {
479 errors: configYamlResult.errors,
480 config: undefined,
481 configLoadInterrupted: true,
482 };
483 }
484
485 const { config: continueConfig, errors: localErrors } =
486 await configYamlToContinueConfig({
487 config: configYamlResult.config,
488 ide,
489 ideSettings,
490 ideInfo,
491 uniqueId,
492 llmLogger,
493 workOsAccessToken,
494 });
495
496 // Apply shared config
497 // TODO: override several of these values with user/org shared config
498 // Don't try catch this - has security implications and failure should be fatal
499 const sharedConfig = new GlobalContext().getSharedConfig();
500 const withShared = modifyAnyConfigWithSharedConfig(
501 continueConfig,
502 sharedConfig,
503 );
504 if (withShared.allowAnonymousTelemetry === undefined) {
505 withShared.allowAnonymousTelemetry = true;
506 }
507
508 return {
509 config: withShared,
510 errors: [...(configYamlResult.errors ?? []), ...localErrors],
511 configLoadInterrupted: false,
512 };
513}