| 1 | import * as YAML from "yaml"; |
| 2 | import { PlatformClient, Registry } from "../interfaces/index.js"; |
| 3 | import { encodeSecretLocation } from "../interfaces/SecretResult.js"; |
| 4 | import { |
| 5 | decodeFQSN, |
| 6 | decodePackageIdentifier, |
| 7 | encodeFQSN, |
| 8 | FQSN, |
| 9 | PackageIdentifier, |
| 10 | } from "../interfaces/slugs.js"; |
| 11 | import { |
| 12 | AssistantUnrolled, |
| 13 | assistantUnrolledSchema, |
| 14 | Block, |
| 15 | blockSchema, |
| 16 | ConfigYaml, |
| 17 | configYamlSchema, |
| 18 | Rule, |
| 19 | } from "../schemas/index.js"; |
| 20 | import { |
| 21 | packageIdentifierToShorthandSlug, |
| 22 | useProxyForUnrenderedSecrets, |
| 23 | } from "./clientRender.js"; |
| 24 | import { getBlockType } from "./getBlockType.js"; |
| 25 | |
| 26 | export function parseConfigYaml(configYaml: string): ConfigYaml { |
| 27 | try { |
| 28 | const parsed = YAML.parse(configYaml); |
| 29 | const result = configYamlSchema.safeParse(parsed); |
| 30 | if (result.success) { |
| 31 | return result.data; |
| 32 | } |
| 33 | throw new Error( |
| 34 | result.error.errors |
| 35 | .map((e) => `${e.path.join(".")}: ${e.message}`) |
| 36 | .join(""), |
| 37 | ); |
| 38 | } catch (e) { |
| 39 | console.log("Failed to parse rolled assistant:", configYaml); |
| 40 | throw new Error( |
| 41 | `Failed to parse assistant:\n${e instanceof Error ? e.message : e}`, |
| 42 | ); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | export function parseAssistantUnrolled(configYaml: string): AssistantUnrolled { |
| 47 | try { |
| 48 | const parsed = YAML.parse(configYaml); |
| 49 | const result = assistantUnrolledSchema.parse(parsed); |
| 50 | return result; |
| 51 | } catch (e: any) { |
| 52 | throw new Error( |
| 53 | `Failed to parse unrolled assistant: ${e.message}\n\n${configYaml}`, |
| 54 | ); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | export function parseBlock(configYaml: string): Block { |
| 59 | try { |
| 60 | const parsed = YAML.parse(configYaml); |
| 61 | const result = blockSchema.parse(parsed); |
| 62 | return result; |
| 63 | } catch (e: any) { |
| 64 | throw new Error(`Failed to parse block: ${e.message}`); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | export const TEMPLATE_VAR_REGEX = /\${{[\s]*([^}\s]+)[\s]*}}/g; |
| 69 | |
| 70 | export function getTemplateVariables(templatedYaml: string): string[] { |
| 71 | const variables = new Set<string>(); |
| 72 | const matches = templatedYaml.matchAll(TEMPLATE_VAR_REGEX); |
| 73 | for (const match of matches) { |
| 74 | variables.add(match[1]); |
| 75 | } |
| 76 | return Array.from(variables); |
| 77 | } |
| 78 | |
| 79 | export function fillTemplateVariables( |
| 80 | templatedYaml: string, |
| 81 | data: { [key: string]: string }, |
| 82 | ): string { |
| 83 | return templatedYaml.replace(TEMPLATE_VAR_REGEX, (match, variableName) => { |
| 84 | // Inject data |
| 85 | if (variableName in data) { |
| 86 | return data[variableName]; |
| 87 | } |
| 88 | // If variable doesn't exist, return the original expression |
| 89 | return match; |
| 90 | }); |
| 91 | } |
| 92 | |
| 93 | export interface TemplateData { |
| 94 | inputs: Record<string, string> | undefined; |
| 95 | secrets: Record<string, string> | undefined; |
| 96 | continue: {}; |
| 97 | } |
| 98 | |
| 99 | function flattenTemplateData( |
| 100 | templateData: TemplateData, |
| 101 | ): Record<string, string> { |
| 102 | const flattened: Record<string, string> = {}; |
| 103 | |
| 104 | if (templateData.inputs) { |
| 105 | for (const [key, value] of Object.entries(templateData.inputs)) { |
| 106 | flattened[`inputs.${key}`] = value; |
| 107 | } |
| 108 | } |
| 109 | if (templateData.secrets) { |
| 110 | for (const [key, value] of Object.entries(templateData.secrets)) { |
| 111 | flattened[`secrets.${key}`] = value; |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | return flattened; |
| 116 | } |
| 117 | |
| 118 | function secretToFQSNMap( |
| 119 | secretNames: string[], |
| 120 | parentPackages: PackageIdentifier[], |
| 121 | ): Record<string, string> { |
| 122 | const map: Record<string, string> = {}; |
| 123 | for (const secret of secretNames) { |
| 124 | const parentSlugs = parentPackages.map(packageIdentifierToShorthandSlug); |
| 125 | const parts = [...parentSlugs, secret]; |
| 126 | const fqsn = parts.join("/"); |
| 127 | map[secret] = `\${{ secrets.${fqsn} }}`; |
| 128 | } |
| 129 | |
| 130 | return map; |
| 131 | } |
| 132 | |
| 133 | function extractFQSNMap( |
| 134 | rawContent: string, |
| 135 | parentPackages: PackageIdentifier[], |
| 136 | ): Record<string, string> { |
| 137 | const templateVars = getTemplateVariables(rawContent); |
| 138 | const secrets = templateVars |
| 139 | .filter((v) => v.startsWith("secrets.")) |
| 140 | .map((v) => v.replace("secrets.", "")); |
| 141 | |
| 142 | return secretToFQSNMap(secrets, parentPackages); |
| 143 | } |
| 144 | |
| 145 | /** |
| 146 | * All template vars are already FQSNs, here we just resolve them to either locations or values |
| 147 | */ |
| 148 | async function extractRenderedSecretsMap( |
| 149 | rawContent: string, |
| 150 | platformClient: PlatformClient, |
| 151 | alwaysUseProxy: boolean = false, |
| 152 | ): Promise<Record<string, string>> { |
| 153 | // Get all template variables |
| 154 | const templateVars = getTemplateVariables(rawContent); |
| 155 | const secrets = templateVars |
| 156 | .filter((v) => v.startsWith("secrets.")) |
| 157 | .map((v) => v.replace("secrets.", "")); |
| 158 | |
| 159 | const fqsns: FQSN[] = secrets.map(decodeFQSN); |
| 160 | |
| 161 | // FQSN -> SecretResult |
| 162 | const secretResults = await platformClient.resolveFQSNs(fqsns); |
| 163 | |
| 164 | const map: Record<string, string> = {}; |
| 165 | for (const secretResult of secretResults) { |
| 166 | if (!secretResult) { |
| 167 | continue; |
| 168 | } |
| 169 | |
| 170 | // User secrets are rendered |
| 171 | if ("value" in secretResult && !alwaysUseProxy) { |
| 172 | map[encodeFQSN(secretResult.fqsn)] = secretResult.value; |
| 173 | } else { |
| 174 | // Other secrets are rendered as secret locations and then converted to proxy types later |
| 175 | map[encodeFQSN(secretResult.fqsn)] = |
| 176 | `\${{ secrets.${encodeSecretLocation(secretResult.secretLocation)} }}`; |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | return map; |
| 181 | } |
| 182 | |
| 183 | export interface BaseUnrollAssistantOptions { |
| 184 | renderSecrets: boolean; |
| 185 | injectBlocks?: PackageIdentifier[]; |
| 186 | } |
| 187 | |
| 188 | export interface DoNotRenderSecretsUnrollAssistantOptions |
| 189 | extends BaseUnrollAssistantOptions { |
| 190 | renderSecrets: false; |
| 191 | } |
| 192 | |
| 193 | export interface RenderSecretsUnrollAssistantOptions |
| 194 | extends BaseUnrollAssistantOptions { |
| 195 | renderSecrets: true; |
| 196 | orgScopeId: string | null; |
| 197 | currentUserSlug: string; |
| 198 | platformClient: PlatformClient; |
| 199 | onPremProxyUrl: string | null; |
| 200 | alwaysUseProxy?: boolean; |
| 201 | } |
| 202 | |
| 203 | export type UnrollAssistantOptions = |
| 204 | | DoNotRenderSecretsUnrollAssistantOptions |
| 205 | | RenderSecretsUnrollAssistantOptions; |
| 206 | |
| 207 | export async function unrollAssistant( |
| 208 | id: PackageIdentifier, |
| 209 | registry: Registry, |
| 210 | options: UnrollAssistantOptions, |
| 211 | ): Promise<AssistantUnrolled> { |
| 212 | // Request the content from the registry |
| 213 | const rawContent = await registry.getContent(id); |
| 214 | return unrollAssistantFromContent(id, rawContent, registry, options); |
| 215 | } |
| 216 | |
| 217 | function renderTemplateData( |
| 218 | rawYaml: string, |
| 219 | templateData: Partial<TemplateData>, |
| 220 | ): string { |
| 221 | const fullTemplateData: TemplateData = { |
| 222 | inputs: {}, |
| 223 | secrets: {}, |
| 224 | continue: {}, |
| 225 | ...templateData, |
| 226 | }; |
| 227 | const templatedYaml = fillTemplateVariables( |
| 228 | rawYaml, |
| 229 | flattenTemplateData(fullTemplateData), |
| 230 | ); |
| 231 | return templatedYaml; |
| 232 | } |
| 233 | |
| 234 | export async function unrollAssistantFromContent( |
| 235 | id: PackageIdentifier, |
| 236 | rawYaml: string, |
| 237 | registry: Registry, |
| 238 | options: UnrollAssistantOptions, |
| 239 | ): Promise<AssistantUnrolled> { |
| 240 | // Parse string to Zod-validated YAML |
| 241 | let parsedYaml = parseConfigYaml(rawYaml); |
| 242 | |
| 243 | // Unroll blocks and convert their secrets to FQSNs |
| 244 | const unrolledAssistant = await unrollBlocks( |
| 245 | parsedYaml, |
| 246 | registry, |
| 247 | options.injectBlocks, |
| 248 | ); |
| 249 | |
| 250 | // Back to a string so we can fill in template variables |
| 251 | const rawUnrolledYaml = YAML.stringify(unrolledAssistant); |
| 252 | |
| 253 | // Convert all of the template variables to FQSNs |
| 254 | // Secrets from the block will have the assistant slug prepended to the FQSN |
| 255 | const templatedYaml = renderTemplateData(rawUnrolledYaml, { |
| 256 | secrets: extractFQSNMap(rawUnrolledYaml, [id]), |
| 257 | }); |
| 258 | |
| 259 | if (!options.renderSecrets) { |
| 260 | return parseAssistantUnrolled(templatedYaml); |
| 261 | } |
| 262 | |
| 263 | // Render secret values/locations for client |
| 264 | const secrets = await extractRenderedSecretsMap( |
| 265 | templatedYaml, |
| 266 | options.platformClient, |
| 267 | options.alwaysUseProxy, |
| 268 | ); |
| 269 | const renderedYaml = renderTemplateData(templatedYaml, { |
| 270 | secrets, |
| 271 | }); |
| 272 | |
| 273 | // Parse again and replace models with proxy versions where secrets weren't rendered |
| 274 | const finalConfig = useProxyForUnrenderedSecrets( |
| 275 | parseAssistantUnrolled(renderedYaml), |
| 276 | id, |
| 277 | options.orgScopeId, |
| 278 | options.onPremProxyUrl, |
| 279 | ); |
| 280 | return finalConfig; |
| 281 | } |
| 282 | |
| 283 | export async function unrollBlocks( |
| 284 | assistant: ConfigYaml, |
| 285 | registry: Registry, |
| 286 | injectBlocks: PackageIdentifier[] | undefined, |
| 287 | ): Promise<AssistantUnrolled> { |
| 288 | const unrolledAssistant: AssistantUnrolled = { |
| 289 | name: assistant.name, |
| 290 | version: assistant.version, |
| 291 | }; |
| 292 | |
| 293 | const sections: (keyof Omit< |
| 294 | ConfigYaml, |
| 295 | "name" | "version" | "rules" | "schema" | "metadata" |
| 296 | >)[] = ["models", "context", "data", "mcpServers", "prompts", "docs"]; |
| 297 | |
| 298 | // For each section, replace "uses/with" blocks with the real thing |
| 299 | for (const section of sections) { |
| 300 | if (assistant[section]) { |
| 301 | const sectionBlocks: any[] = []; |
| 302 | |
| 303 | for (const unrolledBlock of assistant[section]) { |
| 304 | // "uses/with" block |
| 305 | if ("uses" in unrolledBlock) { |
| 306 | try { |
| 307 | const blockConfigYaml = await resolveBlock( |
| 308 | decodePackageIdentifier(unrolledBlock.uses), |
| 309 | unrolledBlock.with, |
| 310 | registry, |
| 311 | ); |
| 312 | const block = blockConfigYaml[section]?.[0]; |
| 313 | if (block) { |
| 314 | sectionBlocks.push( |
| 315 | mergeOverrides(block, unrolledBlock.override ?? {}), |
| 316 | ); |
| 317 | } |
| 318 | } catch (err) { |
| 319 | console.error( |
| 320 | `Failed to unroll block ${unrolledBlock.uses}: ${(err as Error).message}`, |
| 321 | ); |
| 322 | sectionBlocks.push(null); |
| 323 | } |
| 324 | } else { |
| 325 | // Normal block |
| 326 | sectionBlocks.push(unrolledBlock); |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | unrolledAssistant[section] = sectionBlocks; |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | // Rules are a bit different because they can be strings, so handle separately |
| 335 | if (assistant.rules) { |
| 336 | const rules: (Rule | null)[] = []; |
| 337 | for (const rule of assistant.rules) { |
| 338 | if (typeof rule === "string" || !("uses" in rule)) { |
| 339 | rules.push(rule); |
| 340 | } else if ("uses" in rule) { |
| 341 | try { |
| 342 | const blockConfigYaml = await resolveBlock( |
| 343 | decodePackageIdentifier(rule.uses), |
| 344 | rule.with, |
| 345 | registry, |
| 346 | ); |
| 347 | const block = blockConfigYaml.rules?.[0]; |
| 348 | if (block) { |
| 349 | rules.push(block); |
| 350 | } |
| 351 | } catch (err) { |
| 352 | console.error( |
| 353 | `Failed to unroll block ${rule.uses}: ${(err as Error).message}`, |
| 354 | ); |
| 355 | rules.push(null); |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | unrolledAssistant.rules = rules; |
| 361 | } |
| 362 | |
| 363 | // Add injected blocks |
| 364 | for (const injectBlock of injectBlocks ?? []) { |
| 365 | try { |
| 366 | const blockConfigYaml = await registry.getContent(injectBlock); |
| 367 | const parsedBlock = parseConfigYaml(blockConfigYaml); |
| 368 | const blockType = getBlockType(parsedBlock); |
| 369 | const resolvedBlock = await resolveBlock( |
| 370 | injectBlock, |
| 371 | undefined, |
| 372 | registry, |
| 373 | ); |
| 374 | |
| 375 | if (blockType) { |
| 376 | if (!unrolledAssistant[blockType]) { |
| 377 | unrolledAssistant[blockType] = []; |
| 378 | } |
| 379 | unrolledAssistant[blockType]?.push( |
| 380 | ...(resolvedBlock[blockType] as any), |
| 381 | ); |
| 382 | } |
| 383 | } catch (err) { |
| 384 | console.error( |
| 385 | `Failed to unroll block ${injectBlock}: ${(err as Error).message}`, |
| 386 | ); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | return unrolledAssistant; |
| 391 | } |
| 392 | |
| 393 | export async function resolveBlock( |
| 394 | id: PackageIdentifier, |
| 395 | inputs: Record<string, string> | undefined, |
| 396 | registry: Registry, |
| 397 | ): Promise<AssistantUnrolled> { |
| 398 | // Retrieve block raw yaml |
| 399 | const rawYaml = await registry.getContent(id); |
| 400 | |
| 401 | if (rawYaml === undefined) { |
| 402 | throw new Error(`Block ${packageIdentifierToShorthandSlug(id)} not found`); |
| 403 | } |
| 404 | |
| 405 | // 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) |
| 406 | const renderedInputs = inputsToFQSNs(inputs || {}, id); |
| 407 | |
| 408 | // Render template variables |
| 409 | const templatedYaml = renderTemplateData(rawYaml, { |
| 410 | inputs: renderedInputs, |
| 411 | secrets: extractFQSNMap(rawYaml, [id]), |
| 412 | }); |
| 413 | |
| 414 | const parsedYaml = parseBlock(templatedYaml); |
| 415 | return parsedYaml; |
| 416 | } |
| 417 | |
| 418 | function inputsToFQSNs( |
| 419 | inputs: Record<string, string>, |
| 420 | blockIdentifier: PackageIdentifier, |
| 421 | ): Record<string, string> { |
| 422 | const renderedInputs: Record<string, string> = {}; |
| 423 | for (const [key, value] of Object.entries(inputs)) { |
| 424 | renderedInputs[key] = renderTemplateData(value, { |
| 425 | secrets: extractFQSNMap(value, [blockIdentifier]), |
| 426 | }); |
| 427 | } |
| 428 | return renderedInputs; |
| 429 | } |
| 430 | |
| 431 | export function mergeOverrides<T extends Record<string, any>>( |
| 432 | block: T, |
| 433 | overrides: Partial<T>, |
| 434 | ): T { |
| 435 | for (const key in overrides) { |
| 436 | if (overrides.hasOwnProperty(key)) { |
| 437 | block[key] = overrides[key]!; |
| 438 | } |
| 439 | } |
| 440 | return block; |
| 441 | } |