Elffuss BraidHub

kikocis/continue public

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