Elffuss BraidHub

kikocis/continue public

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