| 71 | * @returns The parsed DetectionModeTemplate, or null if not found or invalid. |
| 72 | */ |
| 73 | export function extractDetectionModeTemplate(text: string): DetectionModeTemplate | null { |
| 74 | // Use \s* to handle any whitespace (spaces, newlines, tabs) around the content |
| 75 | const detectionModeRegex = /&&&\s*([\s\S]*?)\s*&&&/; |
| 76 | const match = text.match(detectionModeRegex); |
| 77 | |
| 78 | if (!match || !match[1]) { |
| 79 | return null; |
| 80 | } |
| 81 | |
| 82 | try { |
| 83 | const parsed = JSON.parse(match[1].trim()); |
| 84 | |
| 85 | // Validate the structure |
| 86 | if (!parsed.categories || !Array.isArray(parsed.categories) || parsed.categories.length < 2) { |
| 87 | console.error('Detection mode template must have at least 2 categories'); |
| 88 | return null; |
| 89 | } |
| 90 | |
| 91 | if (!parsed.categorization || typeof parsed.categorization !== 'object') { |
| 92 | console.error('Detection mode template must have a categorization object'); |
| 93 | return null; |
| 94 | } |
| 95 | |
| 96 | // Validate all categories are strings |
| 97 | if (!parsed.categories.every((cat: unknown) => typeof cat === 'string')) { |
| 98 | console.error('All categories must be strings'); |
| 99 | return null; |
| 100 | } |
| 101 | |
| 102 | // Validate all categorization values are arrays of numbers |
| 103 | for (const [key, value] of Object.entries(parsed.categorization)) { |
| 104 | if (!Array.isArray(value) || !value.every((v: unknown) => typeof v === 'number')) { |
| 105 | console.error(`Categorization for "${key}" must be an array of numbers`); |
| 106 | return null; |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | return { |
| 111 | categories: parsed.categories, |
| 112 | categorization: parsed.categorization |
| 113 | }; |
| 114 | } catch (error) { |
| 115 | console.error('Failed to parse detection mode template JSON:', error); |
| 116 | return null; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Parses a raw agent configuration string into a structured agent object and code. |