Elffuss BraidHub

kikocis/continue public

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