| 1 | import * as YAML from "yaml"; |
| 2 | import { ZodError } from "zod"; |
| 3 | import { PlatformClient, Registry } from "../interfaces/index.js"; |
| 4 | import { encodeSecretLocation } from "../interfaces/SecretResult.js"; |
| 5 | import { |
| 6 | decodeFQSN, |
| 7 | decodePackageIdentifier, |
| 8 | encodeFQSN, |
| 9 | FQSN, |
| 10 | PackageIdentifier, |
| 11 | } from "../interfaces/slugs.js"; |
| 12 | import { markdownToRule } from "../markdown/index.js"; |
| 13 | import { |
| 14 | AssistantUnrolled, |
| 15 | assistantUnrolledSchema, |
| 16 | Block, |
| 17 | blockSchema, |
| 18 | ConfigYaml, |
| 19 | configYamlSchema, |
| 20 | Rule, |
| 21 | } from "../schemas/index.js"; |
| 22 | import { ConfigResult, ConfigValidationError } from "../validation.js"; |
| 23 | import { |
| 24 | packageIdentifierToShorthandSlug, |
| 25 | useProxyForUnrenderedSecrets, |
| 26 | } from "./clientRender.js"; |
| 27 | import { getBlockType } from "./getBlockType.js"; |
| 28 | |
| 29 | export 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 | |
| 58 | export 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 | |
| 71 | export 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 | |
| 81 | export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; |
| 82 | |
| 83 | export 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 | |
| 92 | export 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 | |
| 106 | export interface TemplateData { |
| 107 | inputs: Record<string, string> | undefined; |
| 108 | secrets: Record<string, string> | undefined; |
| 109 | continue: {}; |
| 110 | } |
| 111 | |
| 112 | function 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 | |
| 131 | function 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 | |
| 146 | function 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 | */ |
| 161 | async 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 | |
| 196 | export interface BaseUnrollAssistantOptions { |
| 197 | renderSecrets: boolean; |
| 198 | injectBlocks?: PackageIdentifier[]; |
| 199 | } |
| 200 | |
| 201 | export interface DoNotRenderSecretsUnrollAssistantOptions |
| 202 | extends BaseUnrollAssistantOptions { |
| 203 | renderSecrets: false; |
| 204 | } |
| 205 | |
| 206 | export 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 | |
| 216 | export type UnrollAssistantOptions = |
| 217 | | DoNotRenderSecretsUnrollAssistantOptions |
| 218 | | RenderSecretsUnrollAssistantOptions; |
| 219 | |
| 220 | export 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 | |
| 233 | function 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 | |
| 250 | export 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 | |
| 308 | export 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 | // For each section, replace "uses/with" blocks with the real thing |
| 326 | for (const section of sections) { |
| 327 | if (assistant[section]) { |
| 328 | const sectionBlocks: any[] = []; |
| 329 | |
| 330 | for (const unrolledBlock of assistant[section]) { |
| 331 | // "uses/with" block |
| 332 | if ("uses" in unrolledBlock) { |
| 333 | try { |
| 334 | const blockConfigYaml = await resolveBlock( |
| 335 | decodePackageIdentifier(unrolledBlock.uses), |
| 336 | unrolledBlock.with, |
| 337 | registry, |
| 338 | ); |
| 339 | const block = blockConfigYaml[section]?.[0]; |
| 340 | if (block) { |
| 341 | sectionBlocks.push( |
| 342 | mergeOverrides(block, unrolledBlock.override ?? {}), |
| 343 | ); |
| 344 | } |
| 345 | } catch (err) { |
| 346 | let msg = ""; |
| 347 | if ( |
| 348 | typeof unrolledBlock.uses !== "string" && |
| 349 | "filePath" in unrolledBlock.uses |
| 350 | ) { |
| 351 | msg = `${(err as Error).message}.\n> ${unrolledBlock.uses.filePath}`; |
| 352 | } else { |
| 353 | msg = `${(err as Error).message}.\n> ${JSON.stringify(unrolledBlock.uses)}`; |
| 354 | } |
| 355 | |
| 356 | errors.push({ |
| 357 | fatal: false, |
| 358 | message: msg, |
| 359 | }); |
| 360 | |
| 361 | console.error( |
| 362 | `Failed to unroll block ${JSON.stringify(unrolledBlock.uses)}: ${(err as Error).message}`, |
| 363 | ); |
| 364 | sectionBlocks.push(null); |
| 365 | } |
| 366 | } else { |
| 367 | // Normal block |
| 368 | sectionBlocks.push(unrolledBlock); |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | unrolledAssistant[section] = sectionBlocks; |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | // Rules are a bit different because they can be strings, so handle separately |
| 377 | if (assistant.rules) { |
| 378 | const rules: (Rule | null)[] = []; |
| 379 | for (const rule of assistant.rules) { |
| 380 | if (typeof rule === "string" || !("uses" in rule)) { |
| 381 | rules.push(rule); |
| 382 | } else if ("uses" in rule) { |
| 383 | try { |
| 384 | const blockConfigYaml = await resolveBlock( |
| 385 | decodePackageIdentifier(rule.uses), |
| 386 | rule.with, |
| 387 | registry, |
| 388 | ); |
| 389 | const block = blockConfigYaml.rules?.[0]; |
| 390 | if (block) { |
| 391 | rules.push(block); |
| 392 | } |
| 393 | } catch (err) { |
| 394 | errors.push({ |
| 395 | fatal: false, |
| 396 | message: `${(err as Error).message}:\n${rule.uses}`, |
| 397 | }); |
| 398 | |
| 399 | console.error( |
| 400 | `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, |
| 401 | ); |
| 402 | rules.push(null); |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | unrolledAssistant.rules = rules; |
| 408 | } |
| 409 | |
| 410 | // Add injected blocks |
| 411 | for (const injectBlock of injectBlocks ?? []) { |
| 412 | try { |
| 413 | const blockConfigYaml = await registry.getContent(injectBlock); |
| 414 | const parsedBlock = parseMarkdownRuleOrConfigYaml( |
| 415 | blockConfigYaml, |
| 416 | injectBlock, |
| 417 | ); |
| 418 | const blockType = getBlockType(parsedBlock); |
| 419 | const resolvedBlock = await resolveBlock( |
| 420 | injectBlock, |
| 421 | undefined, |
| 422 | registry, |
| 423 | ); |
| 424 | |
| 425 | if (blockType) { |
| 426 | if (!unrolledAssistant[blockType]) { |
| 427 | unrolledAssistant[blockType] = []; |
| 428 | } |
| 429 | unrolledAssistant[blockType]?.push( |
| 430 | ...(resolvedBlock[blockType] as any), |
| 431 | ); |
| 432 | } |
| 433 | } catch (err) { |
| 434 | let msg = ""; |
| 435 | if (injectBlock.uriType === "file") { |
| 436 | msg = `${(err as Error).message}.\n> ${injectBlock.filePath}`; |
| 437 | } else { |
| 438 | msg = `${(err as Error).message}.\n> ${injectBlock.fullSlug}`; |
| 439 | } |
| 440 | errors.push({ |
| 441 | fatal: false, |
| 442 | message: msg, |
| 443 | }); |
| 444 | |
| 445 | console.error( |
| 446 | `Failed to unroll block ${JSON.stringify(injectBlock)}: ${(err as Error).message}`, |
| 447 | ); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | const configResult: ConfigResult<AssistantUnrolled> = { |
| 452 | config: undefined, |
| 453 | errors: undefined, |
| 454 | configLoadInterrupted: false, |
| 455 | }; |
| 456 | configResult.config = unrolledAssistant; |
| 457 | if (errors.length > 0) { |
| 458 | configResult.errors = errors; |
| 459 | } |
| 460 | return configResult; |
| 461 | } |
| 462 | |
| 463 | export async function resolveBlock( |
| 464 | id: PackageIdentifier, |
| 465 | inputs: Record<string, string> | undefined, |
| 466 | registry: Registry, |
| 467 | ): Promise<AssistantUnrolled> { |
| 468 | // Retrieve block raw yaml |
| 469 | const rawYaml = await registry.getContent(id); |
| 470 | |
| 471 | if (rawYaml === undefined) { |
| 472 | throw new Error(`Block ${packageIdentifierToShorthandSlug(id)} not found`); |
| 473 | } |
| 474 | |
| 475 | // 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) |
| 476 | const renderedInputs = inputsToFQSNs(inputs || {}, id); |
| 477 | |
| 478 | // Render template variables |
| 479 | const templatedYaml = renderTemplateData(rawYaml, { |
| 480 | inputs: renderedInputs, |
| 481 | secrets: extractFQSNMap(rawYaml, [id]), |
| 482 | }); |
| 483 | |
| 484 | return parseMarkdownRuleOrAssistantUnrolled(templatedYaml, id); |
| 485 | } |
| 486 | |
| 487 | function parseMarkdownRuleOrAssistantUnrolled( |
| 488 | content: string, |
| 489 | id: PackageIdentifier, |
| 490 | ): AssistantUnrolled { |
| 491 | // Try to parse as YAML first, then as markdown rule if that fails |
| 492 | let parsedYaml: AssistantUnrolled; |
| 493 | try { |
| 494 | parsedYaml = parseBlock(content); |
| 495 | } catch (yamlError) { |
| 496 | // If YAML parsing fails, try parsing as markdown rule |
| 497 | try { |
| 498 | const rule = markdownToRule(content, id); |
| 499 | // Convert the rule object to the expected format |
| 500 | parsedYaml = { |
| 501 | name: rule.name, |
| 502 | version: "1.0.0", |
| 503 | rules: [rule], |
| 504 | }; |
| 505 | } catch (markdownError) { |
| 506 | // If both fail, throw the original YAML error |
| 507 | throw yamlError; |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | return parsedYaml; |
| 512 | } |
| 513 | |
| 514 | function parseMarkdownRuleOrConfigYaml( |
| 515 | content: string, |
| 516 | id: PackageIdentifier, |
| 517 | ): ConfigYaml { |
| 518 | // Try to parse as YAML first, then as markdown rule if that fails |
| 519 | let parsedYaml: ConfigYaml; |
| 520 | try { |
| 521 | parsedYaml = parseConfigYaml(content); |
| 522 | } catch (yamlError) { |
| 523 | // If YAML parsing fails, try parsing as markdown rule |
| 524 | try { |
| 525 | const rule = markdownToRule(content, id); |
| 526 | // Convert the rule object to the expected format |
| 527 | parsedYaml = { |
| 528 | name: rule.name, |
| 529 | version: "1.0.0", |
| 530 | rules: [rule], |
| 531 | }; |
| 532 | } catch (markdownError) { |
| 533 | // If both fail, throw the original YAML error |
| 534 | throw yamlError; |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | return parsedYaml; |
| 539 | } |
| 540 | |
| 541 | function inputsToFQSNs( |
| 542 | inputs: Record<string, string>, |
| 543 | blockIdentifier: PackageIdentifier, |
| 544 | ): Record<string, string> { |
| 545 | const renderedInputs: Record<string, string> = {}; |
| 546 | for (const [key, value] of Object.entries(inputs)) { |
| 547 | renderedInputs[key] = renderTemplateData(value, { |
| 548 | secrets: extractFQSNMap(value, [blockIdentifier]), |
| 549 | }); |
| 550 | } |
| 551 | return renderedInputs; |
| 552 | } |
| 553 | |
| 554 | export function mergeOverrides<T extends Record<string, any>>( |
| 555 | block: T, |
| 556 | overrides: Partial<T>, |
| 557 | ): T { |
| 558 | for (const key in overrides) { |
| 559 | if (overrides.hasOwnProperty(key)) { |
| 560 | block[key] = overrides[key]!; |
| 561 | } |
| 562 | } |
| 563 | return block; |
| 564 | } |
| 565 | |
| 566 | function formatZodError(error: any): string { |
| 567 | if (error.errors && Array.isArray(error.errors)) { |
| 568 | return error.errors |
| 569 | .map((e: any) => { |
| 570 | const path = e.path.length > 0 ? `${e.path.join(".")}: ` : ""; |
| 571 | return `${path}${e.message}`; |
| 572 | }) |
| 573 | .join(", "); |
| 574 | } |
| 575 | return error.message || "Validation failed"; |
| 576 | } |