Elffuss BraidHub

kikocis/continue public

3ecf862e2425 · 13.9 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 } as any, // TODO: Fix the mcpServers types in config-yaml (discriminated union)
73 timeout: server.connectionTimeout,
74 };
75}
76
77async function loadConfigYaml(options: {
78 overrideConfigYaml: AssistantUnrolled | undefined;
79 controlPlaneClient: ControlPlaneClient;
80 orgScopeId: string | null;
81 ideSettings: IdeSettings;
82 ide: IDE;
83 packageIdentifier: PackageIdentifier;
84}): Promise<ConfigResult<AssistantUnrolled>> {
85 const {
86 overrideConfigYaml,
87 controlPlaneClient,
88 orgScopeId,
89 ideSettings,
90 ide,
91 packageIdentifier,
92 } = options;
93
94 // Add local .continue blocks
95 const allLocalBlocks: PackageIdentifier[] = [];
96 for (const blockType of BLOCK_TYPES) {
97 const localBlocks = await getAllDotContinueDefinitionFiles(
98 ide,
99 { includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
100 blockType,
101 );
102 allLocalBlocks.push(
103 ...localBlocks.map((b) => ({
104 uriType: "file" as const,
105 filePath: b.path,
106 })),
107 );
108 }
109
110 const rootPath =
111 packageIdentifier.uriType === "file"
112 ? dirname(getCleanUriPath(packageIdentifier.filePath))
113 : undefined;
114
115 // logger.info(
116 // `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
117 // );
118
119 const errors: ConfigValidationError[] = [];
120
121 let config: AssistantUnrolled | undefined;
122
123 if (overrideConfigYaml) {
124 config = overrideConfigYaml;
125 } else {
126 // This is how we allow use of blocks locally
127 const unrollResult = await unrollAssistant(
128 packageIdentifier,
129 new RegistryClient({
130 accessToken: await controlPlaneClient.getAccessToken(),
131 apiBase: getControlPlaneEnvSync(ideSettings.continueTestEnvironment)
132 .CONTROL_PLANE_URL,
133 rootPath,
134 }),
135 {
136 renderSecrets: true,
137 currentUserSlug: "",
138 onPremProxyUrl: null,
139 orgScopeId,
140 platformClient: new LocalPlatformClient(
141 orgScopeId,
142 controlPlaneClient,
143 ide,
144 ),
145 injectBlocks: allLocalBlocks,
146 },
147 );
148 config = unrollResult.config;
149 if (unrollResult.errors) {
150 errors.push(...unrollResult.errors);
151 }
152 }
153
154 if (config && isAssistantUnrolledNonNullable(config)) {
155 errors.push(...validateConfigYaml(config));
156 }
157
158 if (errors?.some((error) => error.fatal)) {
159 return {
160 errors,
161 config: undefined,
162 configLoadInterrupted: true,
163 };
164 }
165
166 // Set defaults if undefined (this lets us keep config.json uncluttered for new users)
167 return {
168 config,
169 errors,
170 configLoadInterrupted: false,
171 };
172}
173
174async function configYamlToContinueConfig(options: {
175 config: AssistantUnrolled;
176 ide: IDE;
177 ideSettings: IdeSettings;
178 ideInfo: IdeInfo;
179 uniqueId: string;
180 llmLogger: ILLMLogger;
181 workOsAccessToken: string | undefined;
182}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
183 let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
184
185 const localErrors: ConfigValidationError[] = [];
186
187 const continueConfig: ContinueConfig = {
188 slashCommands: [],
189 tools: await getToolsForIde(ide),
190 mcpServerStatuses: [],
191 contextProviders: [],
192 modelsByRole: {
193 chat: [],
194 edit: [],
195 apply: [],
196 embed: [],
197 autocomplete: [],
198 rerank: [],
199 summarize: [],
200 },
201 selectedModelByRole: {
202 chat: null,
203 edit: null, // not currently used
204 apply: null,
205 embed: null,
206 autocomplete: null,
207 rerank: null,
208 summarize: null,
209 },
210 rules: [],
211 };
212
213 // Right now, if there are any missing packages in the config, then we will just throw an error
214 if (!isAssistantUnrolledNonNullable(config)) {
215 return {
216 config: continueConfig,
217 errors: [
218 {
219 message:
220 "Failed to load config due to missing blocks, see which blocks are missing below",
221 fatal: true,
222 },
223 ],
224 };
225 }
226
227 for (const rule of config.rules ?? []) {
228 continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
229 }
230
231 continueConfig.data = config.data;
232 continueConfig.docs = config.docs?.map((doc) => ({
233 title: doc.name,
234 startUrl: doc.startUrl,
235 rootUrl: doc.rootUrl,
236 faviconUrl: doc.faviconUrl,
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 // Context providers
387 const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
388
389 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
390 ({ description: { title } }) => title,
391 );
392
393 continueConfig.contextProviders = (config.context
394 ?.map((context) => {
395 const cls = contextProviderClassFromName(context.provider) as any;
396 if (!cls) {
397 if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
398 localErrors.push({
399 fatal: false,
400 message: `Unknown context provider ${context.provider}`,
401 });
402 }
403 return undefined;
404 }
405 const instance: IContextProvider = new cls({
406 name: context.name,
407 ...context.params,
408 });
409 return instance;
410 })
411 .filter((p) => !!p) ?? []) as IContextProvider[];
412 continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
413
414 if (
415 continueConfig.docs?.length &&
416 !continueConfig.contextProviders?.some(
417 (cp) => cp.description.title === "docs",
418 )
419 ) {
420 continueConfig.contextProviders.push(new DocsContextProvider({}));
421 }
422
423 // Trigger MCP server refreshes (Config is reloaded again once connected!)
424 const mcpManager = MCPManagerSingleton.getInstance();
425 mcpManager.setConnections(
426 (config.mcpServers ?? []).map((server) => ({
427 id: server.name,
428 name: server.name,
429 transport: {
430 type: "stdio",
431 args: [],
432 ...(server as any), // TODO: fix the types on mcpServers in config-yaml
433 },
434 timeout: server.connectionTimeout,
435 })),
436 false,
437 );
438
439 return { config: continueConfig, errors: localErrors };
440}
441
442export async function loadContinueConfigFromYaml(options: {
443 ide: IDE;
444 ideSettings: IdeSettings;
445 ideInfo: IdeInfo;
446 uniqueId: string;
447 llmLogger: ILLMLogger;
448 workOsAccessToken: string | undefined;
449 overrideConfigYaml: AssistantUnrolled | undefined;
450 controlPlaneClient: ControlPlaneClient;
451 orgScopeId: string | null;
452 packageIdentifier: PackageIdentifier;
453}): Promise<ConfigResult<ContinueConfig>> {
454 const {
455 ide,
456 ideSettings,
457 ideInfo,
458 uniqueId,
459 llmLogger,
460 workOsAccessToken,
461 overrideConfigYaml,
462 controlPlaneClient,
463 orgScopeId,
464 packageIdentifier,
465 } = options;
466
467 const configYamlResult = await loadConfigYaml({
468 overrideConfigYaml,
469 controlPlaneClient,
470 orgScopeId,
471 ideSettings,
472 ide,
473 packageIdentifier,
474 });
475
476 if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
477 return {
478 errors: configYamlResult.errors,
479 config: undefined,
480 configLoadInterrupted: true,
481 };
482 }
483
484 const { config: continueConfig, errors: localErrors } =
485 await configYamlToContinueConfig({
486 config: configYamlResult.config,
487 ide,
488 ideSettings,
489 ideInfo,
490 uniqueId,
491 llmLogger,
492 workOsAccessToken,
493 });
494
495 // Apply shared config
496 // TODO: override several of these values with user/org shared config
497 // Don't try catch this - has security implications and failure should be fatal
498 const sharedConfig = new GlobalContext().getSharedConfig();
499 const withShared = modifyAnyConfigWithSharedConfig(
500 continueConfig,
501 sharedConfig,
502 );
503 if (withShared.allowAnonymousTelemetry === undefined) {
504 withShared.allowAnonymousTelemetry = true;
505 }
506
507 return {
508 config: withShared,
509 errors: [...(configYamlResult.errors ?? []), ...localErrors],
510 configLoadInterrupted: false,
511 };
512}