Elffuss BraidHub

kikocis/continue public

19cfb6ec829a · 20.5 KiBRawPermalink
1import * as YAML from "yaml";
2import { ZodError } from "zod";
3import { PlatformClient, Registry } from "../interfaces/index.js";
4import { encodeSecretLocation } from "../interfaces/SecretResult.js";
5import {
6 decodeFQSN,
7 decodePackageIdentifier,
8 encodeFQSN,
9 FQSN,
10 PackageIdentifier,
11} from "../interfaces/slugs.js";
12import { markdownToRule } from "../markdown/index.js";
13import {
14 AssistantUnrolled,
15 assistantUnrolledSchema,
16 Block,
17 blockSchema,
18 ConfigYaml,
19 configYamlSchema,
20 Rule,
21} from "../schemas/index.js";
22import { ConfigResult, ConfigValidationError } from "../validation.js";
23import { BlockDuplicationDetector } from "./blockDuplicationDetector.js";
24import {
25 packageIdentifierToShorthandSlug,
26 useProxyForUnrenderedSecrets,
27} from "./clientRender.js";
28import { BlockType, getBlockType } from "./getBlockType.js";
29
30export function parseConfigYaml(configYaml: string): ConfigYaml {
31 try {
32 const parsed = YAML.parse(configYaml);
33 const result = configYamlSchema.safeParse(parsed);
34 if (result.success) {
35 return result.data;
36 }
37
38 throw new Error(formatZodError(result.error), {
39 cause: "result.success was false",
40 });
41 } catch (e) {
42 console.error("Failed to parse rolled assistant:", configYaml);
43 if (
44 e instanceof Error &&
45 "cause" in e &&
46 e.cause === "result.success was false"
47 ) {
48 throw new Error(`Failed to parse assistant: ${e.message}`);
49 } else if (e instanceof ZodError) {
50 throw new Error(`Failed to parse assistant: ${formatZodError(e)}`);
51 } else {
52 throw new Error(
53 `Failed to parse assistant: ${e instanceof Error ? e.message : e}`,
54 );
55 }
56 }
57}
58
59export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled {
60 try {
61 const parsed = YAML.parse(configYaml);
62 const result = assistantUnrolledSchema.parse(parsed);
63 return result;
64 } catch (e: any) {
65 console.error(
66 `Failed to parse unrolled assistant: ${e.message}\n\n${configYaml}`,
67 );
68 throw new Error(`Failed to parse unrolled assistant: ${formatZodError(e)}`);
69 }
70}
71
72export function parseBlock(configYaml: string): Block {
73 try {
74 const parsed = YAML.parse(configYaml);
75 const result = blockSchema.parse(parsed);
76 return result;
77 } catch (e: any) {
78 throw new Error(`Failed to parse block: ${formatZodError(e)}`);
79 }
80}
81
82export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g;
83
84export function getTemplateVariables(templatedYaml: string): string[] {
85 const variables = new Set<string>();
86 const matches = templatedYaml.matchAll(TEMPLATE_VAR_REGEX);
87 for (const match of matches) {
88 variables.add(match[1]);
89 }
90 return Array.from(variables);
91}
92
93export function fillTemplateVariables(
94 templatedYaml: string,
95 data: { [key: string]: string },
96): string {
97 return templatedYaml.replace(TEMPLATE_VAR_REGEX, (match, variableName) => {
98 // Inject data
99 if (variableName in data) {
100 return data[variableName];
101 }
102 // If variable doesn't exist, return the original expression
103 return match;
104 });
105}
106
107export interface TemplateData {
108 inputs: Record<string, string> | undefined;
109 secrets: Record<string, string> | undefined;
110 continue: {};
111}
112
113function flattenTemplateData(
114 templateData: TemplateData,
115): Record<string, string> {
116 const flattened: Record<string, string> = {};
117
118 if (templateData.inputs) {
119 for (const [key, value] of Object.entries(templateData.inputs)) {
120 flattened[`inputs.${key}`] = value;
121 }
122 }
123 if (templateData.secrets) {
124 for (const [key, value] of Object.entries(templateData.secrets)) {
125 flattened[`secrets.${key}`] = value;
126 }
127 }
128
129 return flattened;
130}
131
132function secretToFQSNMap(
133 secretNames: string[],
134 parentPackages: PackageIdentifier[],
135): Record<string, string> {
136 const map: Record<string, string> = {};
137 for (const secret of secretNames) {
138 const parentSlugs = parentPackages.map(packageIdentifierToShorthandSlug);
139 const parts = [...parentSlugs, secret];
140 const fqsn = parts.join("/");
141 map[secret] = `\${{ secrets.${fqsn} }}`;
142 }
143
144 return map;
145}
146
147function extractFQSNMap(
148 rawContent: string,
149 parentPackages: PackageIdentifier[],
150): Record<string, string> {
151 const templateVars = getTemplateVariables(rawContent);
152 const secrets = templateVars
153 .filter((v) => v.startsWith("secrets."))
154 .map((v) => v.replace("secrets.", ""));
155
156 return secretToFQSNMap(secrets, parentPackages);
157}
158
159/**
160 * All template vars are already FQSNs, here we just resolve them to either locations or values
161 */
162async function extractRenderedSecretsMap(
163 rawContent: string,
164 platformClient: PlatformClient,
165 alwaysUseProxy: boolean = false,
166): Promise<Record<string, string>> {
167 // Get all template variables
168 const templateVars = getTemplateVariables(rawContent);
169 const secrets = templateVars
170 .filter((v) => v.startsWith("secrets."))
171 .map((v) => v.replace("secrets.", ""));
172
173 const fqsns: FQSN[] = secrets.map(decodeFQSN);
174
175 // FQSN -> SecretResult
176 const secretResults = await platformClient.resolveFQSNs(fqsns);
177
178 const map: Record<string, string> = {};
179 for (const secretResult of secretResults) {
180 if (!secretResult) {
181 continue;
182 }
183
184 // User secrets are rendered
185 if ("value" in secretResult && !alwaysUseProxy) {
186 map[encodeFQSN(secretResult.fqsn)] = secretResult.value;
187 } else {
188 // Other secrets are rendered as secret locations and then converted to proxy types later
189 map[encodeFQSN(secretResult.fqsn)] =
190 `\${{ secrets.${encodeSecretLocation(secretResult.secretLocation)} }}`;
191 }
192 }
193
194 return map;
195}
196
197export interface BaseUnrollAssistantOptions {
198 renderSecrets: boolean;
199 injectBlocks?: PackageIdentifier[];
200}
201
202export interface DoNotRenderSecretsUnrollAssistantOptions
203 extends BaseUnrollAssistantOptions {
204 renderSecrets: false;
205}
206
207export interface RenderSecretsUnrollAssistantOptions
208 extends BaseUnrollAssistantOptions {
209 renderSecrets: true;
210 orgScopeId: string | null;
211 currentUserSlug: string;
212 platformClient: PlatformClient;
213 onPremProxyUrl: string | null;
214 alwaysUseProxy?: boolean;
215}
216
217export type UnrollAssistantOptions =
218 | DoNotRenderSecretsUnrollAssistantOptions
219 | RenderSecretsUnrollAssistantOptions;
220
221export async function unrollAssistant(
222 id: PackageIdentifier,
223 registry: Registry,
224 options: UnrollAssistantOptions,
225): Promise<ConfigResult<AssistantUnrolled>> {
226 // Request the content from the registry
227 const rawContent = await registry.getContent(id);
228
229 const result = unrollAssistantFromContent(id, rawContent, registry, options);
230
231 return result;
232}
233
234function renderTemplateData(
235 rawYaml: string,
236 templateData: Partial<TemplateData>,
237): string {
238 const fullTemplateData: TemplateData = {
239 inputs: {},
240 secrets: {},
241 continue: {},
242 ...templateData,
243 };
244 const templatedYaml = fillTemplateVariables(
245 rawYaml,
246 flattenTemplateData(fullTemplateData),
247 );
248 return templatedYaml;
249}
250
251export async function unrollAssistantFromContent(
252 id: PackageIdentifier,
253 rawYaml: string,
254 registry: Registry,
255 options: UnrollAssistantOptions,
256): Promise<ConfigResult<AssistantUnrolled>> {
257 // Parse string to Zod-validated YAML
258 let parsedYaml = parseMarkdownRuleOrConfigYaml(rawYaml, id);
259
260 // Unroll blocks and convert their secrets to FQSNs
261 const {
262 config: unrolledAssistant,
263 configLoadInterrupted,
264 errors,
265 } = await unrollBlocks(parsedYaml, registry, options.injectBlocks);
266
267 // Back to a string so we can fill in template variables
268 const rawUnrolledYaml = YAML.stringify(unrolledAssistant);
269
270 // Convert all of the template variables to FQSNs
271 // Secrets from the block will have the assistant slug prepended to the FQSN
272 const templatedYaml = renderTemplateData(rawUnrolledYaml, {
273 secrets: extractFQSNMap(rawUnrolledYaml, [id]),
274 });
275
276 if (!options.renderSecrets) {
277 return {
278 config: parseAssistantUnrolled(templatedYaml),
279 errors: [],
280 configLoadInterrupted: false,
281 };
282 }
283
284 // Render secret values/locations for client
285 const secrets = await extractRenderedSecretsMap(
286 templatedYaml,
287 options.platformClient,
288 options.alwaysUseProxy,
289 );
290 const renderedYaml = renderTemplateData(templatedYaml, { secrets });
291
292 // Parse again and replace models with proxy versions where secrets weren't rendered
293 const finalConfig = useProxyForUnrenderedSecrets(
294 parseAssistantUnrolled(renderedYaml),
295 id,
296 options.orgScopeId,
297 options.onPremProxyUrl,
298 );
299
300 return { config: finalConfig, errors, configLoadInterrupted };
301}
302
303export async function unrollBlocks(
304 assistant: ConfigYaml,
305 registry: Registry,
306 injectBlocks: PackageIdentifier[] | undefined,
307): Promise<ConfigResult<AssistantUnrolled>> {
308 const errors: ConfigValidationError[] = [];
309
310 function injectDuplicationError(errorMsg: string) {
311 errors.push({
312 fatal: false,
313 message: errorMsg,
314 });
315 }
316
317 const unrolledAssistant: AssistantUnrolled = {
318 name: assistant.name,
319 version: assistant.version,
320 };
321
322 const sections: (keyof Omit<
323 ConfigYaml,
324 "name" | "version" | "rules" | "schema" | "metadata"
325 >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"];
326
327 // Process all sections in parallel
328 const sectionPromises = sections.map(async (section) => {
329 if (!assistant[section]) {
330 return { section, blocks: null };
331 }
332
333 // Process all blocks in this section in parallel
334 const blockPromises = assistant[section].map(
335 async (unrolledBlock, index) => {
336 // "uses/with" block
337 if ("uses" in unrolledBlock) {
338 try {
339 const blockConfigYaml = await resolveBlock(
340 decodePackageIdentifier(unrolledBlock.uses),
341 unrolledBlock.with,
342 registry,
343 );
344 const block = blockConfigYaml[section]?.[0];
345 if (block) {
346 return {
347 index,
348 block: mergeOverrides(block, unrolledBlock.override ?? {}),
349 error: null,
350 };
351 }
352 return { index, block: null, error: null };
353 } catch (err) {
354 let msg = "";
355 if (
356 typeof unrolledBlock.uses !== "string" &&
357 "filePath" in unrolledBlock.uses
358 ) {
359 msg = `${(err as Error).message}.\n> ${unrolledBlock.uses.filePath}`;
360 } else {
361 msg = `${(err as Error).message}.\n> ${JSON.stringify(unrolledBlock.uses)}`;
362 }
363
364 console.error(
365 `Failed to unroll block ${JSON.stringify(unrolledBlock.uses)}: ${(err as Error).message}`,
366 );
367
368 return {
369 index,
370 block: null,
371 error: { fatal: false, message: msg },
372 };
373 }
374 } else {
375 // Normal block
376 return { index, block: unrolledBlock, error: null };
377 }
378 },
379 );
380
381 const blockResults = await Promise.all(blockPromises);
382
383 // Collect errors and maintain order
384 const sectionBlocks: any[] = [];
385 const sectionErrors: ConfigValidationError[] = [];
386
387 for (const result of blockResults) {
388 if (result.error) {
389 sectionErrors.push(result.error);
390 }
391 sectionBlocks[result.index] = result.block;
392 }
393
394 return { section, blocks: sectionBlocks, errors: sectionErrors };
395 });
396
397 // Process rules in parallel
398 const rulesPromise = assistant.rules
399 ? (async () => {
400 const rulePromises = assistant.rules!.map(async (rule, index) => {
401 if (typeof rule === "string" || !("uses" in rule)) {
402 return { index, rule, error: null };
403 } else if ("uses" in rule) {
404 try {
405 const blockConfigYaml = await resolveBlock(
406 decodePackageIdentifier(rule.uses),
407 rule.with,
408 registry,
409 );
410 const block = blockConfigYaml.rules?.[0];
411 return { index, rule: block || null, error: null };
412 } catch (err) {
413 console.error(
414 `Failed to unroll block ${rule.uses}: ${(err as Error).message}`,
415 );
416
417 return {
418 index,
419 rule: null,
420 error: {
421 fatal: false,
422 message: `${(err as Error).message}:\n${rule.uses}`,
423 },
424 };
425 }
426 }
427 return { index, rule: null, error: null };
428 });
429
430 const ruleResults = await Promise.all(rulePromises);
431
432 const rules: (Rule | null)[] = [];
433 const ruleErrors: ConfigValidationError[] = [];
434
435 for (const result of ruleResults) {
436 if (result.error) {
437 ruleErrors.push(result.error);
438 }
439 rules[result.index] = result.rule;
440 }
441
442 return { rules, errors: ruleErrors };
443 })()
444 : Promise.resolve({ rules: undefined, errors: [] });
445
446 // Process injected blocks in parallel
447 const injectedBlocksPromise = injectBlocks
448 ? (async () => {
449 const injectedBlockPromises = injectBlocks.map(async (injectBlock) => {
450 try {
451 const blockConfigYaml = await registry.getContent(injectBlock);
452 const parsedBlock = parseMarkdownRuleOrConfigYaml(
453 blockConfigYaml,
454 injectBlock,
455 );
456 const blockType = getBlockType(parsedBlock);
457 const resolvedBlock = await resolveBlock(
458 injectBlock,
459 undefined,
460 registry,
461 );
462
463 return {
464 blockType,
465 resolvedBlock,
466 source:
467 injectBlock.uriType === "file"
468 ? injectBlock.filePath
469 : undefined,
470 error: null,
471 };
472 } catch (err) {
473 let msg = "";
474 if (injectBlock.uriType === "file") {
475 msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`;
476 } else {
477 msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`;
478 }
479
480 console.error(
481 `Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`,
482 );
483
484 return {
485 blockType: null,
486 resolvedBlock: null,
487 error: { fatal: false, message: msg },
488 };
489 }
490 });
491
492 const injectedResults = await Promise.all(injectedBlockPromises);
493 const injectedErrors: ConfigValidationError[] = [];
494 const injectedBlocks: {
495 blockType: BlockType;
496 resolvedBlock: any;
497 source?: string;
498 }[] = [];
499
500 for (const result of injectedResults) {
501 if (result.error) {
502 injectedErrors.push(result.error);
503 } else if (result.blockType && result.resolvedBlock) {
504 injectedBlocks.push({
505 blockType: result.blockType,
506 resolvedBlock: result.resolvedBlock,
507 source: result.source,
508 });
509 }
510 }
511
512 return { injectedBlocks, errors: injectedErrors };
513 })()
514 : Promise.resolve({ injectedBlocks: [], errors: [] });
515
516 // Wait for all parallel operations to complete
517 const [sectionResults, rulesResult, injectedResult] = await Promise.all([
518 Promise.all(sectionPromises),
519 rulesPromise,
520 injectedBlocksPromise,
521 ]);
522
523 // Collect all errors
524 for (const sectionResult of sectionResults) {
525 if (sectionResult.errors) {
526 errors.push(...sectionResult.errors);
527 }
528 }
529 errors.push(...rulesResult.errors);
530 errors.push(...injectedResult.errors);
531
532 const detector = new BlockDuplicationDetector();
533
534 // Assign section results
535 for (const sectionResult of sectionResults) {
536 if (sectionResult.blocks) {
537 unrolledAssistant[sectionResult.section] = sectionResult.blocks.filter(
538 (block) =>
539 !detector.isDuplicated(
540 block,
541 sectionResult.section,
542 injectDuplicationError,
543 ),
544 );
545 }
546 }
547
548 // Assign rules result
549 if (rulesResult.rules) {
550 unrolledAssistant.rules = rulesResult.rules.filter(
551 (rule) => !detector.isDuplicated(rule, "rules", injectDuplicationError),
552 );
553 }
554
555 // Add injected blocks
556 for (const {
557 blockType,
558 resolvedBlock,
559 source,
560 } of injectedResult.injectedBlocks) {
561 const key = blockType;
562 if (!unrolledAssistant[key]) {
563 unrolledAssistant[key] = [];
564 }
565
566 const filteredBlocks = injectLocalSourceFile(
567 key,
568 resolvedBlock,
569 source,
570 ).filter(
571 (block: any) =>
572 !detector.isDuplicated(block, blockType, injectDuplicationError),
573 );
574 unrolledAssistant[key]?.push(...filteredBlocks);
575 }
576
577 const configResult: ConfigResult<AssistantUnrolled> = {
578 config: undefined,
579 errors: undefined,
580 configLoadInterrupted: false,
581 };
582 configResult.config = unrolledAssistant;
583 if (errors.length > 0) {
584 configResult.errors = errors;
585 }
586 return configResult;
587}
588
589function injectLocalSourceFile(
590 blockType: BlockType,
591 resolvedBlock: any,
592 source?: string,
593): (any & { source?: string })[] {
594 const blocks: any[] = resolvedBlock[blockType] ?? [];
595 if (source === undefined) {
596 // If no source is provided, return blocks as is
597 return blocks;
598 }
599 if (blockType === "rules") {
600 // For rules, we need to ensure they are wrapped in an object with a `source
601 return blocks.map((block) => {
602 if (typeof block === "string") {
603 const rule = {
604 sourceFile: source,
605 name: block,
606 rule: block,
607 } as Rule;
608 return rule;
609 } else if (typeof block === "object") {
610 block.sourceFile = source;
611 }
612 return block;
613 });
614 }
615 // For other block types, we can directly inject the source file
616 return blocks.map((block) => ({
617 ...block,
618 sourceFile: source,
619 }));
620}
621
622export async function resolveBlock(
623 id: PackageIdentifier,
624 inputs: Record<string, string> | undefined,
625 registry: Registry,
626): Promise<AssistantUnrolled> {
627 // Retrieve block raw yaml
628 const rawYaml = await registry.getContent(id);
629
630 if (rawYaml === undefined) {
631 throw new Error(`Block ${packageIdentifierToShorthandSlug(id)} not found`);
632 }
633
634 // Convert any input secrets to FQSNs (they get FQSNs as if they are in the block. This is so that we know when to use models add-on / free trial secrets)
635 const renderedInputs = inputsToFQSNs(inputs || {}, id);
636
637 // Render template variables
638 const templatedYaml = renderTemplateData(rawYaml, {
639 inputs: renderedInputs,
640 secrets: extractFQSNMap(rawYaml, [id]),
641 });
642
643 return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id);
644}
645
646export function parseMarkdownRuleOrAssistantUnrolled(
647 content: string,
648 id: PackageIdentifier,
649): AssistantUnrolled {
650 return parseYamlOrMarkdownRule<AssistantUnrolled>(content, id, parseBlock);
651}
652
653function parseMarkdownRuleOrConfigYaml(
654 content: string,
655 id: PackageIdentifier,
656): ConfigYaml {
657 return parseYamlOrMarkdownRule<ConfigYaml>(content, id, parseConfigYaml);
658}
659
660function parseYamlOrMarkdownRule<T>(
661 content: string,
662 id: PackageIdentifier,
663 parseYamlFn: (content: string) => T,
664): T {
665 let parsedYaml: T;
666 try {
667 // Try to parse as YAML first, then as markdown rule if that fails
668 parsedYaml = parseYamlFn(content);
669 } catch (yamlError) {
670 if (
671 id.uriType === "file" &&
672 [".yaml", ".yml"].some((ext) => id.filePath.endsWith(ext))
673 ) {
674 throw yamlError;
675 }
676 // If YAML parsing fails, try parsing as markdown rule
677 try {
678 const rule = markdownToRule(content, id);
679 // Convert the rule object to the expected format
680 parsedYaml = { name: rule.name, version: "1.0.0", rules: [rule] } as T;
681 } catch (markdownError) {
682 // If both fail, throw the original YAML error
683 throw yamlError;
684 }
685 }
686 return parsedYaml;
687}
688
689function inputsToFQSNs(
690 inputs: Record<string, string>,
691 blockIdentifier: PackageIdentifier,
692): Record<string, string> {
693 const renderedInputs: Record<string, string> = {};
694 for (const [key, value] of Object.entries(inputs)) {
695 renderedInputs[key] = renderTemplateData(value, {
696 secrets: extractFQSNMap(value, [blockIdentifier]),
697 });
698 }
699 return renderedInputs;
700}
701
702export function mergeOverrides<T extends Record<string, any>>(
703 block: T,
704 overrides: Partial<T>,
705): T {
706 for (const key in overrides) {
707 if (overrides.hasOwnProperty(key)) {
708 block[key] = overrides[key]!;
709 }
710 }
711 return block;
712}
713
714function formatZodError(error: any): string {
715 if (error.errors && Array.isArray(error.errors)) {
716 return error.errors
717 .map((e: any) => {
718 const path = e.path.length > 0 ? `${e.path.join(".")}: ` : "";
719 return `${path}${e.message}`;
720 })
721 .join(", ");
722 }
723 return error.message || "Validation failed";
724}