Elffuss BraidHub

kikocis/continue public

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