diff --git a/tool/generator/lib/src/services/gemini_service.dart b/tool/generator/lib/src/services/gemini_service.dart index 83fed1f..995977d 100644 --- a/tool/generator/lib/src/services/gemini_service.dart +++ b/tool/generator/lib/src/services/gemini_service.dart @@ -9,6 +9,7 @@ import 'package:http/http.dart' as http; import 'package:logging/logging.dart'; import 'package:meta/meta.dart'; import 'package:retry/retry.dart'; +import 'package:yaml/yaml.dart'; import 'prompts.dart'; import 'skill_instructions.dart'; @@ -21,6 +22,7 @@ class GeminiService { http.Client? httpClient, String? model, }) : _model = model ?? defaultModel, + _ownsClient = httpClient == null, _client = _ApiKeyClient(httpClient ?? http.Client(), apiKey); /// Default temperature for legacy models. @@ -88,10 +90,49 @@ class GeminiService { ), ]; + static final RegExp _leadingCodeFenceRegExp = RegExp( + r'^\s*(`{3,})[^\r\n`]*\r?\n', + ); + static final RegExp _yamlFenceLineRegExp = RegExp( + r'^---[ \t]*$', + multiLine: true, + ); + static final RegExp _markdownPrefixStartRegExp = RegExp( + r'^(?:[-#>*+_~`]|\d+\.)', + ); + static final RegExp _leadingBlankLineRegExp = RegExp( + r'^[ \t]*\r?\n[ \t]*\r?\n', + ); + static final RegExp _trailingBlankLineRegExp = RegExp( + r'\r?\n[ \t]*\r?\n[ \t]*$', + ); + static final RegExp _yamlFrontmatterKeyRegExp = RegExp( + r'^[a-z][a-zA-Z0-9_-]*$', + ); + static const Set _knownFrontmatterKeys = { + 'name', + 'description', + 'metadata', + 'license', + 'compatibility', + 'allowed-tools', + }; + final String _model; + final bool _ownsClient; final http.Client _client; final Logger _logger = Logger('GeminiService'); + /// Closes the underlying HTTP client if it was created internally by this + /// [GeminiService]. + /// + /// Does not close an external `httpClient` passed into the constructor. + void close() { + if (_ownsClient) { + _client.close(); + } + } + /// Generates the content for a skill based on raw markdown input. Future generateSkillContent( String rawMarkdown, @@ -116,23 +157,16 @@ class GeminiService { try { const r = RetryOptions(maxAttempts: 3); - final response = await r.retry(() async { + final cleanedBody = await r.retry(() async { final res = await service.generateContent(request); - final text = res.candidates.first.content?.parts - .where((part) => !part.thought) - .map((part) => part.text) - .where((text) => text != null) - .join('\n'); - - if (text == null || text.isEmpty) { - throw const FormatException('Empty response from Gemini'); + final text = _extractVerifiedText(res); + final cleaned = cleanContent(text); + if (cleaned == null || cleaned.trim().isEmpty) { + throw const FormatException('Empty markdown body from Gemini'); } - - return text; + return cleaned; }, onRetry: (e) => _logger.warning('Retrying Gemini generation: $e')); - final content = response; - final frontmatter = '''--- name: $skillName @@ -143,7 +177,7 @@ metadata: --- '''; - return frontmatter + (cleanContent(content) ?? ''); + return frontmatter + cleanedBody; } on Object catch (e) { _logger.severe('Gemini generation failed: $e'); return null; @@ -179,23 +213,16 @@ metadata: try { const r = RetryOptions(maxAttempts: 3); - final response = await r.retry(() async { + final cleanedBody = await r.retry(() async { final res = await service.generateContent(request); - final text = res.candidates.first.content?.parts - .where((part) => !part.thought) - .map((part) => part.text) - .where((text) => text != null) - .join('\n'); - - if (text == null || text.isEmpty) { - throw const FormatException('Empty response from Gemini'); + final text = _extractVerifiedText(res); + final cleaned = cleanContent(text); + if (cleaned == null || cleaned.trim().isEmpty) { + throw const FormatException('Empty markdown body from Gemini'); } - - return text; + return cleaned; }, onRetry: (e) => _logger.warning('Retrying Gemini generation: $e')); - final content = response; - final frontmatter = '''--- name: $skillName @@ -206,14 +233,14 @@ metadata: --- '''; - return frontmatter + (cleanContent(content) ?? ''); + return frontmatter + cleanedBody; } on Object catch (e) { _logger.severe('Gemini update failed: $e'); return null; } } - /// Validates an existing skill + /// Validates an existing skill. Future validateExistingSkillContent( String markdown, String skillName, @@ -246,17 +273,7 @@ metadata: const r = RetryOptions(maxAttempts: 3); final response = await r.retry(() async { final res = await service.generateContent(request); - final text = res.candidates.first.content?.parts - .where((part) => !part.thought) - .map((part) => part.text) - .where((text) => text != null) - .join('\n'); - - if (text == null || text.isEmpty) { - throw const FormatException('Empty response from Gemini'); - } - - return text; + return _extractVerifiedText(res); }, onRetry: (e) => _logger.warning('Retrying Gemini validation: $e')); return response; @@ -266,40 +283,140 @@ metadata: } } - /// Cleans the generated content by removing markdown code blocks and frontmatter. + String _extractVerifiedText(GenerateContentResponse res) { + if (res.candidates.isEmpty) { + throw FormatException( + 'No candidates returned from Gemini ' + '(blockReason: ${res.promptFeedback?.blockReason}).', + ); + } + final candidate = res.candidates.first; + final finishReason = candidate.finishReason; + if (finishReason != Candidate_FinishReason.stop && + finishReason != Candidate_FinishReason.finishReasonUnspecified) { + throw FormatException( + 'Incomplete Gemini response (finishReason: $finishReason).', + ); + } + final text = candidate.content?.parts + .where((part) => !part.thought) + .map((part) => part.text) + .where((text) => text != null) + .join('\n'); + + if (text == null || text.trim().isEmpty) { + throw const FormatException('Empty response from Gemini'); + } + return text; + } + + /// Cleans the generated content by removing outer markdown code fences and + /// leading YAML frontmatter while preserving horizontal rules (`---`) inside + /// the markdown body. @visibleForTesting String? cleanContent(String? content) { if (content == null) return null; var cleaned = content; - final startMatch = RegExp( - r'^\s*```[a-zA-Z]*\s*\n', - caseSensitive: false, - ).firstMatch(cleaned); + final startMatch = _leadingCodeFenceRegExp.firstMatch(cleaned); if (startMatch != null) { + final fence = startMatch.group(1)!; cleaned = cleaned.substring(startMatch.end); - // Remove the last triple backticks if they exist - cleaned = cleaned.replaceAll(RegExp(r'\n```\s*$'), ''); + final trailingFenceRegExp = RegExp( + '(?:^|\\r?\\n)[ \\t]*${RegExp.escape(fence)}\\s*\$', + ); + cleaned = cleaned.replaceFirst(trailingFenceRegExp, ''); } - final yamlStartIndex = cleaned.indexOf('---'); - if (yamlStartIndex == 0) { - // Possible frontmatter, skip it - final end = cleaned.indexOf('---', 3); - if (end != -1) { - cleaned = cleaned.substring(end + 3).trim(); - } - } else if (yamlStartIndex > 0) { - // Maybe noise before frontmatter, try to strip it if it looks like frontmatter - final end = cleaned.indexOf('---', yamlStartIndex + 3); - if (end != -1) { - cleaned = cleaned.substring(end + 3).trim(); - } - } + cleaned = _stripLeadingFrontmatter(cleaned); // Ensure one trailing newline return '${cleaned.trim()}\n'; } + String _stripLeadingFrontmatter(String input) { + final firstFence = _yamlFenceLineRegExp.firstMatch(input); + if (firstFence == null) { + return input; + } + + final prefix = input.substring(0, firstFence.start).trim(); + // Allow frontmatter only at the start of the response or immediately after + // a single-line conversational lead-in ending with ':' (e.g. "Here is the + // content:"). Reject multi-line prefixes and Markdown block starters + // (headings, blockquotes, lists, emphasis, or code fences). + if (prefix.isNotEmpty && + (prefix.contains('\n') || + prefix.contains('\r') || + !prefix.endsWith(':') || + _markdownPrefixStartRegExp.hasMatch(prefix))) { + return input; + } + + final remainder = input.substring(firstFence.end); + final secondFence = _yamlFenceLineRegExp.firstMatch(remainder); + if (secondFence == null) { + return input; + } + + final rawCandidate = remainder.substring(0, secondFence.start); + // YAML frontmatter never starts with a blank line after `---`, whereas + // Markdown horizontal rules (`---`) and Setext H2 sections do. + if (_leadingBlankLineRegExp.hasMatch(rawCandidate)) { + return input; + } + + final hasTrailingBlankLine = _trailingBlankLineRegExp.hasMatch( + rawCandidate, + ); + if (hasTrailingBlankLine && prefix.isNotEmpty) { + return input; + } + + final bodyAfterFence = remainder.substring(secondFence.end).trim(); + final candidateYaml = rawCandidate.trim(); + if (candidateYaml.isEmpty) { + return prefix.isEmpty ? bodyAfterFence : input; + } + + if (!_isValidFrontmatterBlock( + candidateYaml, + allowNullDocument: prefix.isEmpty && bodyAfterFence.isNotEmpty, + requireKnownKey: prefix.isNotEmpty || hasTrailingBlankLine, + )) { + return input; + } + + return bodyAfterFence; + } + + bool _isValidFrontmatterBlock( + String candidateYaml, { + required bool allowNullDocument, + required bool requireKnownKey, + }) { + try { + final parsed = loadYaml(candidateYaml); + if (parsed == null) { + return allowNullDocument; + } + if (parsed is! YamlMap || parsed.isEmpty) { + return false; + } + final hasValidKeys = parsed.keys.every( + (key) => key is String && _yamlFrontmatterKeyRegExp.hasMatch(key), + ); + if (!hasValidKeys) { + return false; + } + if (requireKnownKey) { + return parsed.keys.any(_knownFrontmatterKeys.contains); + } + return true; + } on YamlException { + return false; + } + } + GenerateContentRequest _createRequest( String prompt, { String? systemInstruction, @@ -345,4 +462,9 @@ class _ApiKeyClient extends http.BaseClient { request.headers['x-goog-api-key'] = _apiKey; return _inner.send(request); } + + @override + void close() { + _inner.close(); + } } diff --git a/tool/generator/test/services/gemini_service_test.dart b/tool/generator/test/services/gemini_service_test.dart index d49c640..6a4daa8 100644 --- a/tool/generator/test/services/gemini_service_test.dart +++ b/tool/generator/test/services/gemini_service_test.dart @@ -17,8 +17,9 @@ void main() { setUp(() { service = GeminiService( apiKey: 'test-api-key', - httpClient: http.Client(), + httpClient: MockClient((_) async => http.Response('', 500)), ); + addTearDown(service.close); }); group('cleanContent', () { @@ -40,6 +41,32 @@ Some content expect(service.cleanContent(content), expected); }); + test( + 'removes 4-backtick outer fences while preserving nested 3-backtick blocks', + () { + const content = ''' +````markdown +# Title +```dart +void main() {} +``` +```` +'''; + const expected = ''' +# Title +```dart +void main() {} +``` +'''; + expect(service.cleanContent(content), expected); + }, + ); + + test('strips empty outer code fences completely', () { + expect(service.cleanContent('```markdown\n```'), '\n'); + expect(service.cleanContent('````markdown\n\n````'), '\n'); + }); + test('removes markdown code blocks with other languages', () { const content = ''' ```text @@ -83,11 +110,11 @@ Some content expect(service.cleanContent(content), expected); }); - test('strips possible frontmatter after some noise', () { + test('strips possible frontmatter after conversational lead-in', () { const content = ''' Here is the content: --- -key: value +name: value --- # Title Some content @@ -99,6 +126,43 @@ Some content expect(service.cleanContent(content), expected); }); + test( + 'strips frontmatter with camelCase keys and block scalars ending in blank line', + () { + const content = ''' +--- +name: flutter-layout +examplePrompt: Build a responsive layout +description: | + Multi-line description. + +--- +# Flutter Layout +Body content. +'''; + const expected = ''' +# Flutter Layout +Body content. +'''; + expect(service.cleanContent(content), expected); + }, + ); + + test( + 'preserves colon-terminated prose followed by non-frontmatter key:', + () { + const content = ''' +Shortcut mapping: +--- +key: Ctrl+Shift+P +command: Reload +--- +# Body +'''; + expect(service.cleanContent(content), content); + }, + ); + test('preserves internal code blocks', () { const content = ''' # Title @@ -145,6 +209,7 @@ print('hello'); '''; expect(service.cleanContent(content), expected); }); + test('removes markdown code blocks with leading whitespace', () { const content = ''' ```markdown @@ -189,6 +254,300 @@ Some content '''; expect(service.cleanContent(content), expected); }); + + test( + 'preserves markdown body containing multiple horizontal rules (---)', + () { + const content = ''' +# Building CLI Apps + +Introductory paragraph. + +--- + +## Section 1 + +Details for section 1. + +--- + +## Section 2 + +Details for section 2. +'''; + expect(service.cleanContent(content), content); + }, + ); + + test( + 'preserves embedded YAML frontmatter inside code blocks after heading', + () { + const content = ''' +# Authoring Skills + +Example frontmatter: + +```yaml +--- +name: example-skill +description: Example description +--- +``` +'''; + expect(service.cleanContent(content), content); + }, + ); + + test( + 'preserves horizontal rules even without top H1 if section has subheadings', + () { + const content = ''' +Introductory note without H1. + +--- + +## Subheading + +Body text. + +--- + +Footer text. +'''; + expect(service.cleanContent(content), content); + }, + ); + + test( + 'preserves callout and numbered section between --- rules before first # heading', + () { + const content = ''' +> **Note:** Run all commands from the repository root. + +--- + +1. Configure `pubspec.yaml`. +2. Run `dart pub get`. + +--- + +# CLI Usage +Details here. +'''; + expect(service.cleanContent(content), content); + }, + ); + + test('preserves Setext H2 headings underlined with ---', () { + const content = ''' +Overview +--- + +Note: Run from root. +--- + +Details. +'''; + expect(service.cleanContent(content), content); + }); + + test( + 'preserves colon-terminated ATX headings and Setext H2 headings before --- rules', + () { + const atxHeading = ''' +# Prerequisites: + +--- + +Note: Run from root. + +--- + +# Steps +Details. +'''; + expect(service.cleanContent(atxHeading), atxHeading); + + const setextHeading = ''' +Prerequisites: +--- +Note: Run from root. +--- + +Details. +'''; + expect(service.cleanContent(setextHeading), setextHeading); + }, + ); + + test('strips YAML frontmatter containing # YAML comments', () { + const content = ''' +--- +# Skill metadata +name: flutter-layout +description: Build responsive layouts +--- +# Flutter Layout +Body content. +'''; + const expected = ''' +# Flutter Layout +Body content. +'''; + expect(service.cleanContent(content), expected); + }); + + test( + 'strips empty and comment-only frontmatter blocks at start of response', + () { + const emptyFrontmatter = ''' +--- +--- +# Title +Body content. +'''; + const commentOnlyFrontmatter = ''' +--- +# Placeholder comment +--- +# Title +Body content. +'''; + const expected = ''' +# Title +Body content. +'''; + expect(service.cleanContent(emptyFrontmatter), expected); + expect(service.cleanContent(commentOnlyFrontmatter), expected); + }, + ); + + test('preserves content when --- frontmatter is unclosed', () { + const content = ''' +--- +name: flutter-layout +# Flutter Layout +Body content. +'''; + expect(service.cleanContent(content), content); + }); + + test('handles CRLF line endings in code fences and frontmatter', () { + const content = + '```markdown\r\n---\r\nname: test\r\n---\r\n# Title\r\nBody\r\n```\r\n'; + expect(service.cleanContent(content), '# Title\r\nBody\n'); + }); + }); + + group('response validation and client lifecycle', () { + test( + 'rejects frontmatter-only, empty-fence, truncated finishReason, and empty candidates', + () async { + var callCount = 0; + final responses = >[ + // 1. Frontmatter-only response (empty body after cleaning) -> retry + { + 'candidates': [ + { + 'finishReason': 'STOP', + 'content': { + 'parts': [ + {'text': '---\nname: stub\n---'}, + ], + }, + }, + ], + }, + // 2. Truncated MAX_TOKENS response -> retry + { + 'candidates': [ + { + 'finishReason': 'MAX_TOKENS', + 'content': { + 'parts': [ + {'text': '# Partial body cut mid-sent'}, + ], + }, + }, + ], + }, + // 3. Complete valid response -> succeeds on 3rd attempt + { + 'candidates': [ + { + 'finishReason': 'STOP', + 'content': { + 'parts': [ + {'text': '# Valid Skill\nComplete body.'}, + ], + }, + }, + ], + }, + ]; + + final mockClient = MockClient((_) async { + final payload = responses[callCount++]; + return http.Response(jsonEncode(payload), 200); + }); + + final gemini = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + ); + + final result = await gemini.generateSkillContent( + 'Raw', + 'test-skill', + 'Desc', + ); + expect(callCount, 3); + expect(result, contains('# Valid Skill\nComplete body.')); + }, + ); + + test( + 'returns null when candidates list is empty across retries', + () async { + final mockClient = MockClient((_) async { + return http.Response( + jsonEncode({ + 'candidates': [], + 'promptFeedback': {'blockReason': 'SAFETY'}, + }), + 200, + ); + }); + + final gemini = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + ); + final result = await gemini.updateSkillContent( + 'Existing', + 'Raw', + 'test-skill', + 'Desc', + ); + expect(result, isNull); + }, + ); + + test( + 'close() closes internally owned client but preserves injected client', + () { + var injectedClosed = false; + final injectedClient = _TrackingClient( + onClose: () => injectedClosed = true, + ); + + GeminiService(apiKey: 'k', httpClient: injectedClient).close(); + expect(injectedClosed, isFalse); + + final ownedService = GeminiService(apiKey: 'k'); + expect(ownedService.close, returnsNormally); + }, + ); }); group('generateSkillContent front matter', () { @@ -396,3 +755,18 @@ Some content }); }); } + +class _TrackingClient extends http.BaseClient { + _TrackingClient({required this.onClose}); + + final void Function() onClose; + + @override + Future send(http.BaseRequest request) => + throw UnimplementedError(); + + @override + void close() { + onClose(); + } +}