| 1 | import { parseDocument } from "yaml"; |
| 2 | |
| 3 | export interface ModelConfig { |
| 4 | uses: string; |
| 5 | with: { |
| 6 | ANTHROPIC_API_KEY: string; |
| 7 | }; |
| 8 | } |
| 9 | |
| 10 | export interface ConfigStructure { |
| 11 | name: string; |
| 12 | version: string; |
| 13 | schema: string; |
| 14 | models: ModelConfig[]; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Updates or adds an Anthropic Claude model configuration in a YAML string while preserving comments and formatting. |
| 19 | * This is a pure function that takes a YAML string and returns a modified YAML string. |
| 20 | * |
| 21 | * @param yamlContent - The original YAML content as a string (can be empty) |
| 22 | * @param apiKey - The Anthropic API key to set |
| 23 | * @returns The updated YAML content as a string with comments preserved |
| 24 | */ |
| 25 | export function updateAnthropicModelInYaml( |
| 26 | yamlContent: string, |
| 27 | apiKey: string, |
| 28 | ): string { |
| 29 | const newModel: ModelConfig = { |
| 30 | uses: "anthropic/claude-4-sonnet", |
| 31 | with: { |
| 32 | ANTHROPIC_API_KEY: apiKey, |
| 33 | }, |
| 34 | }; |
| 35 | |
| 36 | try { |
| 37 | const doc = parseDocument(yamlContent); |
| 38 | |
| 39 | // If document is empty or has no content, create a new config |
| 40 | if (!doc.contents || doc.contents === null) { |
| 41 | const defaultConfig: ConfigStructure = { |
| 42 | name: "Local Config", |
| 43 | version: "1.0.0", |
| 44 | schema: "v1", |
| 45 | models: [newModel], |
| 46 | }; |
| 47 | |
| 48 | const newDoc = parseDocument(""); |
| 49 | Object.keys(defaultConfig).forEach((key) => |
| 50 | newDoc.set(key, (defaultConfig as any)[key]), |
| 51 | ); |
| 52 | return newDoc.toString(); |
| 53 | } |
| 54 | |
| 55 | // Convert to JS, filter models, and recreate |
| 56 | const config = doc.toJS() as any; |
| 57 | |
| 58 | // Make sure models array exists |
| 59 | if (!config.models) { |
| 60 | config.models = []; |
| 61 | } |
| 62 | |
| 63 | // Filter out existing anthropic models |
| 64 | config.models = config.models.filter( |
| 65 | (model: any) => !model || model.uses !== "anthropic/claude-4-sonnet", |
| 66 | ); |
| 67 | |
| 68 | // Add the new anthropic model |
| 69 | config.models.push(newModel); |
| 70 | |
| 71 | // Update the models array while preserving comments and structure |
| 72 | doc.set("models", config.models); |
| 73 | |
| 74 | return doc.toString(); |
| 75 | } catch { |
| 76 | // If parsing fails completely, create a new config |
| 77 | const defaultConfig: ConfigStructure = { |
| 78 | name: "Local Config", |
| 79 | version: "1.0.0", |
| 80 | schema: "v1", |
| 81 | models: [newModel], |
| 82 | }; |
| 83 | |
| 84 | const doc = parseDocument(""); |
| 85 | Object.keys(defaultConfig).forEach((key) => |
| 86 | doc.set(key, (defaultConfig as any)[key]), |
| 87 | ); |
| 88 | return doc.toString(); |
| 89 | } |
| 90 | } |