Elffuss BraidHub

kikocis/continue public

d691089ac9f7 · 14.3 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 { baseToolDefinitions } 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 },
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 currentUserSlug: "",
138 onPremProxyUrl: null,
139 orgScopeId,
140 platformClient: new LocalPlatformClient(
141 orgScopeId,
142 controlPlaneClient,
143 ide,
144 ),
145 renderSecrets: true,
146 injectBlocks: allLocalBlocks,
147 asConfigResult: true,
148 },
149 );
150 config = unrollResult.config;
151 if (unrollResult.errors) {
152 errors.push(...unrollResult.errors);
153 }
154 }
155
156 if (config) {
157 isAssistantUnrolledNonNullable(config)
158 ? errors.push(...validateConfigYaml(config))
159 : errors.push({
160 fatal: true,
161 message: "Assistant includes blocks that don't exist",
162 });
163 }
164
165 if (errors?.some((error) => error.fatal)) {
166 return {
167 errors,
168 config: undefined,
169 configLoadInterrupted: true,
170 };
171 }
172
173 // Set defaults if undefined (this lets us keep config.json uncluttered for new users)
174 return {
175 config,
176 errors,
177 configLoadInterrupted: false,
178 };
179}
180
181async function configYamlToContinueConfig(options: {
182 config: AssistantUnrolled;
183 ide: IDE;
184 ideSettings: IdeSettings;
185 ideInfo: IdeInfo;
186 uniqueId: string;
187 llmLogger: ILLMLogger;
188 workOsAccessToken: string | undefined;
189}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
190 let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
191
192 const localErrors: ConfigValidationError[] = [];
193
194 const continueConfig: ContinueConfig = {
195 slashCommands: [],
196 tools: [...baseToolDefinitions],
197 mcpServerStatuses: [],
198 contextProviders: [],
199 modelsByRole: {
200 chat: [],
201 edit: [],
202 apply: [],
203 embed: [],
204 autocomplete: [],
205 rerank: [],
206 summarize: [],
207 },
208 selectedModelByRole: {
209 chat: null,
210 edit: null, // not currently used
211 apply: null,
212 embed: null,
213 autocomplete: null,
214 rerank: null,
215 summarize: null,
216 },
217 rules: [],
218 };
219
220 // Right now, if there are any missing packages in the config, then we will just throw an error
221 if (!isAssistantUnrolledNonNullable(config)) {
222 return {
223 config: continueConfig,
224 errors: [
225 {
226 message: "Found missing blocks in config.yaml",
227 fatal: true,
228 },
229 ],
230 };
231 }
232
233 for (const rule of config.rules ?? []) {
234 continueConfig.rules.push(convertYamlRuleToContinueRule(rule));
235 }
236
237 continueConfig.data = config.data;
238 continueConfig.docs = config.docs?.map((doc) => ({
239 title: doc.name,
240 startUrl: doc.startUrl,
241 rootUrl: doc.rootUrl,
242 faviconUrl: doc.faviconUrl,
243 }));
244
245 config.mcpServers?.forEach((mcpServer) => {
246 const mcpArgVariables =
247 mcpServer.args?.filter((arg) => TEMPLATE_VAR_REGEX.test(arg)) ?? [];
248
249 if (mcpArgVariables.length === 0) {
250 return;
251 }
252
253 localErrors.push({
254 fatal: false,
255 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.`,
256 });
257 });
258
259 continueConfig.experimental = {
260 modelContextProtocolServers: config.mcpServers?.map(
261 convertYamlMcpToContinueMcp,
262 ),
263 };
264
265 // Prompt files -
266 try {
267 const promptFiles = await getAllPromptFiles(ide, undefined, true);
268
269 promptFiles.forEach((file) => {
270 try {
271 const slashCommand = slashCommandFromPromptFileV1(
272 file.path,
273 file.content,
274 );
275 if (slashCommand) {
276 continueConfig.slashCommands?.push(slashCommand);
277 }
278 } catch (e) {
279 localErrors.push({
280 fatal: false,
281 message: `Failed to convert prompt file ${file.path} to slash command: ${e instanceof Error ? e.message : e}`,
282 });
283 }
284 });
285 } catch (e) {
286 localErrors.push({
287 fatal: false,
288 message: `Error loading local prompt files: ${e instanceof Error ? e.message : e}`,
289 });
290 }
291
292 config.prompts?.forEach((prompt) => {
293 try {
294 const slashCommand = slashFromCustomCommand(prompt);
295 continueConfig.slashCommands?.push(slashCommand);
296 } catch (e) {
297 localErrors.push({
298 message: `Error loading prompt ${prompt.name}: ${e instanceof Error ? e.message : e}`,
299 fatal: false,
300 });
301 }
302 });
303
304 // Models
305 let warnAboutFreeTrial = false;
306 const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
307 for (const model of config.models ?? []) {
308 model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
309
310 if (model.provider === "free-trial") {
311 warnAboutFreeTrial = true;
312 }
313 try {
314 const llms = await llmsFromModelConfig({
315 model,
316 ide,
317 uniqueId,
318 ideSettings,
319 llmLogger,
320 config: continueConfig,
321 });
322
323 if (model.roles?.includes("chat")) {
324 continueConfig.modelsByRole.chat.push(...llms);
325 }
326
327 if (model.roles?.includes("summarize")) {
328 continueConfig.modelsByRole.summarize.push(...llms);
329 }
330
331 if (model.roles?.includes("apply")) {
332 continueConfig.modelsByRole.apply.push(...llms);
333 }
334
335 if (model.roles?.includes("edit")) {
336 continueConfig.modelsByRole.edit.push(...llms);
337 }
338
339 if (model.roles?.includes("autocomplete")) {
340 continueConfig.modelsByRole.autocomplete.push(...llms);
341 }
342
343 if (model.roles?.includes("embed")) {
344 const { provider } = model;
345 if (provider === "transformers.js") {
346 if (ideInfo.ideType === "vscode") {
347 continueConfig.modelsByRole.embed.push(
348 new TransformersJsEmbeddingsProvider(),
349 );
350 } else {
351 localErrors.push({
352 fatal: false,
353 message: `Transformers.js embeddings provider not supported in this IDE.`,
354 });
355 }
356 } else {
357 continueConfig.modelsByRole.embed.push(...llms);
358 }
359 }
360
361 if (model.roles?.includes("rerank")) {
362 continueConfig.modelsByRole.rerank.push(...llms);
363 }
364 } catch (e) {
365 localErrors.push({
366 fatal: false,
367 message: `Failed to load model:\nName: ${model.name}\nModel: ${model.model}\nProvider: ${model.provider}\n${e instanceof Error ? e.message : e}`,
368 });
369 }
370 }
371
372 // Add transformers js to the embed models in vs code if not already added
373 if (
374 ideInfo.ideType === "vscode" &&
375 !continueConfig.modelsByRole.embed.find(
376 (m) => m.providerName === "transformers.js",
377 )
378 ) {
379 continueConfig.modelsByRole.embed.push(
380 new TransformersJsEmbeddingsProvider(),
381 );
382 }
383
384 if (warnAboutFreeTrial) {
385 localErrors.push({
386 fatal: false,
387 message:
388 "Model provider 'free-trial' is no longer supported, will be ignored.",
389 });
390 }
391
392 // Context providers
393 const codebaseContextParams: IContextProvider[] =
394 (config.context || []).find((cp) => cp.provider === "codebase")?.params ||
395 {};
396 const DEFAULT_CONTEXT_PROVIDERS = [
397 new FileContextProvider({}),
398 new CodebaseContextProvider(codebaseContextParams),
399 ];
400
401 const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
402 ({ description: { title } }) => title,
403 );
404
405 continueConfig.contextProviders = (config.context
406 ?.map((context) => {
407 const cls = contextProviderClassFromName(context.provider) as any;
408 if (!cls) {
409 if (!DEFAULT_CONTEXT_PROVIDERS_TITLES.includes(context.provider)) {
410 localErrors.push({
411 fatal: false,
412 message: `Unknown context provider ${context.provider}`,
413 });
414 }
415 return undefined;
416 }
417 const instance: IContextProvider = new cls({
418 name: context.name,
419 ...context.params,
420 });
421 return instance;
422 })
423 .filter((p) => !!p) ?? []) as IContextProvider[];
424 continueConfig.contextProviders.push(...DEFAULT_CONTEXT_PROVIDERS);
425
426 if (
427 continueConfig.docs?.length &&
428 !continueConfig.contextProviders?.some(
429 (cp) => cp.description.title === "docs",
430 )
431 ) {
432 continueConfig.contextProviders.push(new DocsContextProvider({}));
433 }
434
435 // Trigger MCP server refreshes (Config is reloaded again once connected!)
436 const mcpManager = MCPManagerSingleton.getInstance();
437 mcpManager.setConnections(
438 (config.mcpServers ?? []).map((server) => ({
439 id: server.name,
440 name: server.name,
441 transport: {
442 type: "stdio",
443 args: [],
444 ...(server as any), // TODO: fix the types on mcpServers in config-yaml
445 },
446 timeout: server.connectionTimeout,
447 })),
448 false,
449 );
450
451 return { config: continueConfig, errors: localErrors };
452}
453
454export async function loadContinueConfigFromYaml(options: {
455 ide: IDE;
456 ideSettings: IdeSettings;
457 ideInfo: IdeInfo;
458 uniqueId: string;
459 llmLogger: ILLMLogger;
460 workOsAccessToken: string | undefined;
461 overrideConfigYaml: AssistantUnrolled | undefined;
462 controlPlaneClient: ControlPlaneClient;
463 orgScopeId: string | null;
464 packageIdentifier: PackageIdentifier;
465}): Promise<ConfigResult<ContinueConfig>> {
466 const {
467 ide,
468 ideSettings,
469 ideInfo,
470 uniqueId,
471 llmLogger,
472 workOsAccessToken,
473 overrideConfigYaml,
474 controlPlaneClient,
475 orgScopeId,
476 packageIdentifier,
477 } = options;
478
479 const configYamlResult = await loadConfigYaml({
480 overrideConfigYaml,
481 controlPlaneClient,
482 orgScopeId,
483 ideSettings,
484 ide,
485 packageIdentifier,
486 });
487
488 if (!configYamlResult.config || configYamlResult.configLoadInterrupted) {
489 return {
490 errors: configYamlResult.errors,
491 config: undefined,
492 configLoadInterrupted: true,
493 };
494 }
495
496 const { config: continueConfig, errors: localErrors } =
497 await configYamlToContinueConfig({
498 config: configYamlResult.config,
499 ide,
500 ideSettings,
501 ideInfo,
502 uniqueId,
503 llmLogger,
504 workOsAccessToken,
505 });
506
507 // Apply shared config
508 // TODO: override several of these values with user/org shared config
509 // Don't try catch this - has security implications and failure should be fatal
510 const sharedConfig = new GlobalContext().getSharedConfig();
511 const withShared = modifyAnyConfigWithSharedConfig(
512 continueConfig,
513 sharedConfig,
514 );
515 if (withShared.allowAnonymousTelemetry === undefined) {
516 withShared.allowAnonymousTelemetry = true;
517 }
518
519 return {
520 config: withShared,
521 errors: [...(configYamlResult.errors ?? []), ...localErrors],
522 configLoadInterrupted: false,
523 };
524}