From c43822c23a2e795ab08b29780b2c5819db9df358 Mon Sep 17 00:00:00 2001 From: Jaime Wren Date: Wed, 18 Nov 2026 17:31:13 -0800 Subject: [PATCH 1/4] generator: Centralize text metrics, YAML checks, and CLI exit codes Skill commands duplicated RegExp word, line, and 1.3x token counts, validate-skill read and parsed YAML configs twice via JSON round-trips, and logged SEVERE errors exited 0 while exit() skipped client cleanup. Extract shared RegExpMatchCount and StringMetrics extensions into text_metrics.dart, validate and construct SkillParams in a single YAML pass, allow --dry-run without GEMINI_API_KEY, and set exitCode on SEVERE and UsageException paths so finally always closes httpClient. Refs: https://github.com/flutter/agent-plugins/pull/267 (Gemini 4 generator follow-up) Tested: dart format, dart analyze --fatal-infos --fatal-warnings, dart test (126 passed) --- tool/generator/bin/skills.dart | 21 ++- .../lib/src/commands/base_skill_command.dart | 38 ++++-- .../lib/src/commands/base_yaml_command.dart | 50 +++++-- .../src/commands/generate_skill_command.dart | 19 ++- .../src/commands/update_readme_command.dart | 26 ++-- .../src/commands/update_skill_command.dart | 23 ++-- .../src/commands/validate_skill_command.dart | 92 ++++--------- .../lib/src/models/skill_params.dart | 55 +++++++- .../generator/lib/src/utils/text_metrics.dart | 68 ++++++++++ .../commands/base_skill_command_test.dart | 127 ++++++++++++++++-- .../commands/validate_skills_input_test.dart | 25 +++- .../test/models/skill_params_test.dart | 56 ++++++++ tool/generator/test/skills_cli_test.dart | 47 +++++++ tool/generator/test/update_skills_test.dart | 2 +- .../test/utils/text_metrics_test.dart | 116 ++++++++++++++++ 15 files changed, 615 insertions(+), 150 deletions(-) create mode 100644 tool/generator/lib/src/utils/text_metrics.dart create mode 100644 tool/generator/test/skills_cli_test.dart create mode 100644 tool/generator/test/utils/text_metrics_test.dart diff --git a/tool/generator/bin/skills.dart b/tool/generator/bin/skills.dart index 6475eb21..3c11c0f5 100644 --- a/tool/generator/bin/skills.dart +++ b/tool/generator/bin/skills.dart @@ -2,6 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'dart:async'; import 'dart:io'; import 'package:args/command_runner.dart'; @@ -14,11 +15,14 @@ import 'package:skills/src/commands/validate_skill_command.dart'; const String version = '0.1.0'; -void main(List arguments) async { +Future main(List arguments) async { final httpClient = http.Client(); final runner = - CommandRunner('skills', 'A sample command-line application.') + CommandRunner( + 'skills', + 'CLI tool for generating, updating, and validating Agent Skills.', + ) ..addCommand(GenerateSkillCommand(httpClient: httpClient)) ..addCommand(UpdateSkillCommand(httpClient: httpClient)) ..addCommand(ValidateSkillCommand(httpClient: httpClient)) @@ -36,6 +40,7 @@ void main(List arguments) async { help: 'Show additional command output.', ); + StreamSubscription? logSubscription; try { final results = runner.parse(arguments); if (results.flag('version')) { @@ -43,7 +48,7 @@ void main(List arguments) async { return; } - _configureLogging(results.flag('verbose')); + logSubscription = _configureLogging(results.flag('verbose')); if (results.flag('verbose')) { Logger.root.fine('All arguments: ${results.arguments}'); @@ -52,20 +57,22 @@ void main(List arguments) async { await runner.run(arguments); } on UsageException catch (e) { stderr.writeln(e); - exit(64); + exitCode = 64; } on Exception catch (e) { stderr.writeln('An error occurred: $e'); - exit(1); + exitCode = 1; } finally { + await logSubscription?.cancel(); httpClient.close(); } } -void _configureLogging(bool verbose) { +StreamSubscription _configureLogging(bool verbose) { Logger.root.level = verbose ? Level.ALL : Level.INFO; - Logger.root.onRecord.listen((record) { + return Logger.root.onRecord.listen((record) { if (record.level >= Level.SEVERE) { stderr.writeln(record.message); + exitCode = 1; } else { stdout.writeln(record.message); } diff --git a/tool/generator/lib/src/commands/base_skill_command.dart b/tool/generator/lib/src/commands/base_skill_command.dart index 9f37850e..5531f3cf 100644 --- a/tool/generator/lib/src/commands/base_skill_command.dart +++ b/tool/generator/lib/src/commands/base_skill_command.dart @@ -5,9 +5,11 @@ import 'dart:io'; import 'package:http/http.dart' as http; +import 'package:meta/meta.dart'; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; +import '../utils/text_metrics.dart'; import 'base_yaml_command.dart'; /// Base command for skill operations requiring AI generation. @@ -53,29 +55,27 @@ abstract class BaseSkillCommand extends BaseYamlCommand { Directory outputDir, { Directory? configDir, }) async { + final dryRun = argResults?['dry-run'] as bool? ?? false; final apiKey = (environment ?? Platform.environment)['GEMINI_API_KEY']; - if (apiKey == null) { + if (!dryRun && (apiKey == null || apiKey.trim().isEmpty)) { logger.severe('GEMINI_API_KEY environment variable not set.'); return; } + final rawBudget = argResults!['thinking-budget'] as String; + final thinkingBudget = int.tryParse(rawBudget); + if (thinkingBudget == null || thinkingBudget < 0) { + logger.severe('Invalid thinking-budget: $rawBudget. Skipping.'); + return; + } + final model = argResults?['model'] as String?; final gemini = GeminiService( - apiKey: apiKey, + apiKey: (apiKey != null && apiKey.trim().isNotEmpty) ? apiKey : 'dry-run', httpClient: httpClient, model: model, ); - int thinkingBudget; - try { - thinkingBudget = int.parse(argResults!['thinking-budget'] as String); - } on FormatException { - logger.warning( - 'Invalid thinking-budget: ${argResults!['thinking-budget']}. Skipping.', - ); - return; - } - for (final skill in skills) { await runSkill( skill, @@ -87,6 +87,20 @@ abstract class BaseSkillCommand extends BaseYamlCommand { } } + /// Logs a warning when [content] exceeds [maxRecommendedSkillLines] lines per + /// the Agent Skills standard. + @protected + void warnIfExceedsLineLimit(String content, {required String prefix}) { + final lines = content.lineCount; + if (lines > maxRecommendedSkillLines) { + logger.warning( + ' $prefix has $lines lines. ' + 'The Agent Skills standard (https://agentskills.io) recommends keeping ' + 'SKILL.md under $maxRecommendedSkillLines lines.', + ); + } + } + /// Executes the command for a specific skill. Future runSkill( SkillParams skill, diff --git a/tool/generator/lib/src/commands/base_yaml_command.dart b/tool/generator/lib/src/commands/base_yaml_command.dart index 1b89d605..280a534a 100644 --- a/tool/generator/lib/src/commands/base_yaml_command.dart +++ b/tool/generator/lib/src/commands/base_yaml_command.dart @@ -2,11 +2,12 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:args/command_runner.dart'; import 'package:logging/logging.dart'; +import 'package:meta/meta.dart'; +import 'package:path/path.dart' as p; import 'package:yaml/yaml.dart'; import '../models/skill_params.dart'; @@ -43,14 +44,38 @@ abstract class BaseYamlCommand extends Command { } final yamlContent = file.readAsStringSync(); - final yamlList = loadYaml(yamlContent) as YamlList; - final skills = yamlList - .map( - (e) => SkillParams.fromJson( - jsonDecode(jsonEncode(e)) as Map, - ), - ) - .toList(); + final YamlList yamlList; + try { + final decoded = loadYaml(yamlContent); + if (decoded is! YamlList) { + logger.severe('Invalid configuration: Root must be a YAML list.'); + return; + } + yamlList = decoded; + } on YamlException catch (e) { + logger.severe('Invalid YAML syntax in $inputFile: $e'); + return; + } + + if (!validateYamlList(yamlList, p.basename(file.path))) { + logger.severe('Configuration validation failed.'); + return; + } + + final skills = []; + for (var i = 0; i < yamlList.length; i++) { + final item = yamlList[i]; + if (item is! Map) { + logger.severe('Invalid configuration: Item $i is not a Map.'); + return; + } + try { + skills.add(SkillParams.fromYamlMap(item)); + } on FormatException catch (e) { + logger.severe('Invalid configuration at item $i: ${e.message}'); + return; + } + } final skillFilter = argResults?['skill'] as String?; final targetSkills = skillFilter != null @@ -74,6 +99,13 @@ abstract class BaseYamlCommand extends Command { await runWithSkills(targetSkills, outDir, configDir: file.parent); } + /// Validates the raw [yamlList] before converting entries to [SkillParams]. + /// + /// Subclasses such as `ValidateSkillCommand` can override this method to + /// perform schema checks without reading or parsing the YAML file twice. + @protected + bool validateYamlList(YamlList yamlList, String fileName) => true; + /// Executes the command with the parsed and filtered list of skills. Future runWithSkills( List skills, diff --git a/tool/generator/lib/src/commands/generate_skill_command.dart b/tool/generator/lib/src/commands/generate_skill_command.dart index 827600c3..927d25e4 100644 --- a/tool/generator/lib/src/commands/generate_skill_command.dart +++ b/tool/generator/lib/src/commands/generate_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -11,6 +10,7 @@ import 'package:path/path.dart' as p; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to generate skills from a configuration file. @@ -26,7 +26,7 @@ class GenerateSkillCommand extends BaseSkillCommand { String get name => 'generate-skill'; @override - String get description => 'Generates skills from using yaml configuration.'; + String get description => 'Generates skills from a YAML configuration file.'; @override Future runSkill( @@ -55,8 +55,8 @@ class GenerateSkillCommand extends BaseSkillCommand { final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final words = RegExp(r'\S+').allMatches(combinedMarkdown).length; - final approxTokens = (words * 1.3).round(); + final words = combinedMarkdown.wordCount; + final approxTokens = combinedMarkdown.approximateTokenCount; logger ..info(' [DRY RUN] Would generate skill: ${skill.name}') ..info( @@ -86,13 +86,10 @@ class GenerateSkillCommand extends BaseSkillCommand { ' Generated ${p.join(outputDir.path, skill.name, 'SKILL.md')}', ); - final lineCount = const LineSplitter().convert(generatedContent).length; - if (lineCount > 500) { - logger.warning( - ' Warning: Generated SKILL.md has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + generatedContent, + prefix: 'Warning: Generated SKILL.md', + ); } else { logger.severe(' Failed to generate content for ${skill.name}'); } diff --git a/tool/generator/lib/src/commands/update_readme_command.dart b/tool/generator/lib/src/commands/update_readme_command.dart index f5d36250..5991653e 100644 --- a/tool/generator/lib/src/commands/update_readme_command.dart +++ b/tool/generator/lib/src/commands/update_readme_command.dart @@ -21,6 +21,17 @@ class UpdateReadmeCommand extends BaseYamlCommand { ); } + static final RegExp _tableLineRegExp = RegExp( + r'^\| \[([^\]]+)\]\([^)]+\) \| [^|]+ \| ([^|]+) \|', + multiLine: true, + ); + static final RegExp _sectionHeaderRegExp = RegExp( + '^## (Available Skills|List of Skills|Skills List|Skill Index)', + caseSensitive: false, + multiLine: true, + ); + static final RegExp _nextSectionRegExp = RegExp(r'\n##\s'); + @override String get name => 'update-readme'; @@ -65,11 +76,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { // Parse existing example prompts from the README if they exist final existingPrompts = {}; - final tableLineRegex = RegExp( - r'^\| \[([^\]]+)\]\([^)]+\) \| [^|]+ \| ([^|]+) \|', - multiLine: true, - ); - for (final match in tableLineRegex.allMatches(content)) { + for (final match in _tableLineRegExp.allMatches(content)) { final skillName = match.group(1)!; final prompt = match.group(2)!.trim(); if (prompt.isNotEmpty) { @@ -112,12 +119,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { final newTable = buffer.toString(); // Find where to insert the table - final sectionRegex = RegExp( - '^## (Available Skills|List of Skills|Skills List|Skill Index)', - caseSensitive: false, - multiLine: true, - ); - final match = sectionRegex.firstMatch(content); + final match = _sectionHeaderRegExp.firstMatch(content); String updatedContent; if (match != null) { @@ -125,7 +127,7 @@ class UpdateReadmeCommand extends BaseYamlCommand { final headerEnd = content.indexOf('\n', match.start); // Find the next section header or end of file final nextSectionIndex = content.indexOf( - RegExp(r'\n##\s', multiLine: true), + _nextSectionRegExp, headerEnd + 1, ); diff --git a/tool/generator/lib/src/commands/update_skill_command.dart b/tool/generator/lib/src/commands/update_skill_command.dart index 23129cd3..0c88bc88 100644 --- a/tool/generator/lib/src/commands/update_skill_command.dart +++ b/tool/generator/lib/src/commands/update_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -11,6 +10,7 @@ import 'package:path/path.dart' as p; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to update skills from a configuration file, preserving existing content. @@ -42,7 +42,7 @@ class UpdateSkillCommand extends BaseSkillCommand { final skillFile = File(p.join(outputDir.path, skill.name, 'SKILL.md')); if (!skillFile.existsSync()) { logger.severe( - ' Skill file not found at ${skillFile.path}. Cannot update an non-existent skill.', + ' Skill file not found at ${skillFile.path}. Cannot update a non-existent skill.', ); return; } @@ -66,10 +66,10 @@ class UpdateSkillCommand extends BaseSkillCommand { final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final origWords = RegExp(r'\S+').allMatches(existingContent).length; - final origTokens = (origWords * 1.3).round(); - final rawWords = RegExp(r'\S+').allMatches(combinedMarkdown).length; - final rawTokens = (rawWords * 1.3).round(); + final origWords = existingContent.wordCount; + final origTokens = existingContent.approximateTokenCount; + final rawWords = combinedMarkdown.wordCount; + final rawTokens = combinedMarkdown.approximateTokenCount; logger ..info(' [DRY RUN] Would update skill: ${skill.name}') ..info( @@ -93,13 +93,10 @@ class UpdateSkillCommand extends BaseSkillCommand { ' Updated ${p.join(outputDir.path, skill.name, 'SKILL.md')}', ); - final lineCount = const LineSplitter().convert(generatedContent).length; - if (lineCount > 500) { - logger.warning( - ' Warning: Updated SKILL.md has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + generatedContent, + prefix: 'Warning: Updated SKILL.md', + ); } else { logger.severe(' Failed to update content for ${skill.name}'); } diff --git a/tool/generator/lib/src/commands/validate_skill_command.dart b/tool/generator/lib/src/commands/validate_skill_command.dart index 31885181..3e6fa2f1 100644 --- a/tool/generator/lib/src/commands/validate_skill_command.dart +++ b/tool/generator/lib/src/commands/validate_skill_command.dart @@ -2,7 +2,6 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. -import 'dart:convert'; import 'dart:io'; import 'package:logging/logging.dart'; @@ -12,6 +11,7 @@ import 'package:yaml/yaml.dart'; import '../models/skill_params.dart'; import '../services/gemini_service.dart'; import '../services/resource_fetcher_service.dart'; +import '../utils/text_metrics.dart'; import 'base_skill_command.dart'; /// Command to validate skills by re-generating and comparing with existing skills. @@ -24,6 +24,11 @@ class ValidateSkillCommand extends BaseSkillCommand { this.validationDir, }) : super(logger: Logger('ValidateSkillCommand')); + static final RegExp _kebabCaseRegExp = RegExp(r'^[a-z0-9]+(-[a-z0-9]+)*$'); + static final RegExp _lastModifiedRegExp = RegExp('last_modified: (.*)'); + static final RegExp _modelRegExp = RegExp('model: (.*)'); + static final RegExp _gradeRegExp = RegExp(r'Grade:\s*(\d+)'); + /// The directory to output validation reports. final Directory? validationDir; @@ -32,51 +37,16 @@ class ValidateSkillCommand extends BaseSkillCommand { @override String get description => - 'Validates skills using existing skill files and yaml configuration.'; + 'Validates skills using existing skill files and YAML configuration.'; @override - Future run() async { - final inputFile = argResults!.rest.isNotEmpty - ? argResults!.rest.first - : 'resources/flutter_skills.yaml'; - - final file = File(inputFile); - if (!file.existsSync()) { - logger.severe('Configuration file not found: $inputFile'); - return; - } - - final yamlContent = file.readAsStringSync(); - YamlList yamlList; - try { - final decoded = loadYaml(yamlContent); - if (decoded is! YamlList) { - logger.severe('Invalid configuration: Root must be a YAML list.'); - return; - } - yamlList = decoded; - } on Object catch (e) { - logger.severe('Invalid YAML syntax in $inputFile: $e'); - return; - } - - final isValid = _validateYamlStructure(yamlList, p.basename(file.path)); - if (!isValid) { - logger.severe('Configuration validation failed.'); - return; - } - - await super.run(); - } - - bool _validateYamlStructure(YamlList yamlList, String fileName) { + bool validateYamlList(YamlList yamlList, String fileName) { if (yamlList.isEmpty) { logger.severe('Configuration list must not be empty.'); return false; } var isValid = true; - final kabobCase = RegExp(r'^[a-z0-9]+(-[a-z0-9]+)*$'); for (var i = 0; i < yamlList.length; i++) { final item = yamlList[i]; @@ -103,10 +73,10 @@ class ValidateSkillCommand extends BaseSkillCommand { } else if (rawDescription is! String) { logger.severe('Skill "$name" field "description" must be a string.'); isValid = false; - } else if (rawDescription.length > 1024) { + } else if (rawDescription.length > maxSkillDescriptionLength) { logger.warning( - 'Skill "$name" description exceeds 1024 characters (${rawDescription.length} chars). ' - 'The Agent Skills standard (https://agentskills.io) limits descriptions to 1024 characters.', + 'Skill "$name" description exceeds $maxSkillDescriptionLength characters (${rawDescription.length} chars). ' + 'The Agent Skills standard (https://agentskills.io) limits descriptions to $maxSkillDescriptionLength characters.', ); } @@ -120,8 +90,13 @@ class ValidateSkillCommand extends BaseSkillCommand { isValid = false; } + if (item['examplePrompt'] != null && item['examplePrompt'] is! String) { + logger.severe('Skill "$name" field "examplePrompt" must be a string.'); + isValid = false; + } + if (rawName is String) { - if (!kabobCase.hasMatch(name)) { + if (!_kebabCaseRegExp.hasMatch(name)) { logger.severe( 'Skill name "$name" must be kabob-case (e.g. abc-def).', ); @@ -228,37 +203,26 @@ class ValidateSkillCommand extends BaseSkillCommand { } // Check file length per agentskills.io recommendation (< 500 lines) - final lineCount = const LineSplitter() - .convert(existingSkillFileContent) - .length; - if (lineCount > 500) { - logger.warning( - ' Validation Warning: ${existingSkillFile.path} has $lineCount lines. ' - 'The Agent Skills standard (https://agentskills.io) recommends keeping SKILL.md under 500 lines.', - ); - } + warnIfExceedsLineLimit( + existingSkillFileContent, + prefix: 'Validation Warning: ${existingSkillFile.path}', + ); // Extract metadata from existing content final generationDate = - RegExp( - 'last_modified: (.*)', - ).firstMatch(existingSkillFileContent)?.group(1) ?? + _lastModifiedRegExp.firstMatch(existingSkillFileContent)?.group(1) ?? 'Unknown'; final modelName = - RegExp( - 'model: (.*)', - ).firstMatch(existingSkillFileContent)?.group(1) ?? + _modelRegExp.firstMatch(existingSkillFileContent)?.group(1) ?? 'Unknown'; // Compare final dryRun = argResults?['dry-run'] as bool? ?? false; if (dryRun) { - final existWords = RegExp( - r'\S+', - ).allMatches(existingSkillFileContent).length; - final existTokens = (existWords * 1.3).round(); - final rawWords = RegExp(r'\S+').allMatches(markdown).length; - final rawTokens = (rawWords * 1.3).round(); + final existWords = existingSkillFileContent.wordCount; + final existTokens = existingSkillFileContent.approximateTokenCount; + final rawWords = markdown.wordCount; + final rawTokens = markdown.approximateTokenCount; logger ..info(' [DRY RUN] Would validate skill: ${skill.name}') ..info( @@ -288,7 +252,7 @@ class ValidateSkillCommand extends BaseSkillCommand { File(p.join(valDir.path, 'validation.md')).writeAsStringSync(result); // Extract and log the grade - final gradeMatch = RegExp(r'Grade:\s*(\d+)').firstMatch(result); + final gradeMatch = _gradeRegExp.firstMatch(result); final grade = gradeMatch?.group(1); logger.info( diff --git a/tool/generator/lib/src/models/skill_params.dart b/tool/generator/lib/src/models/skill_params.dart index e2d833a2..64f165e0 100644 --- a/tool/generator/lib/src/models/skill_params.dart +++ b/tool/generator/lib/src/models/skill_params.dart @@ -14,13 +14,56 @@ class SkillParams { }); /// Creates a [SkillParams] instance from a JSON map. - factory SkillParams.fromJson(Map json) { + factory SkillParams.fromJson(Map json) => + SkillParams.fromYamlMap(json); + + /// Creates a [SkillParams] instance from a decoded YAML or JSON map. + /// + /// Throws a [FormatException] if required fields are missing or have invalid + /// types. + factory SkillParams.fromYamlMap(Map map) { + final name = map['name']; + if (name is! String || name.trim().isEmpty) { + throw const FormatException('Skill "name" must be a non-empty string.'); + } + final description = map['description']; + if (description is! String) { + throw FormatException( + 'Skill "$name" field "description" must be a string.', + ); + } + final rawResources = map['resources']; + if (rawResources is! List) { + throw FormatException('Skill "$name" field "resources" must be a list.'); + } + final resources = []; + for (final resource in rawResources) { + if (resource is! String) { + throw FormatException( + 'Skill "$name" resource entries must be strings.', + ); + } + resources.add(resource); + } + final instructions = map['instructions']; + if (instructions != null && instructions is! String) { + throw FormatException( + 'Skill "$name" field "instructions" must be a string.', + ); + } + final examplePrompt = map['examplePrompt']; + if (examplePrompt != null && examplePrompt is! String) { + throw FormatException( + 'Skill "$name" field "examplePrompt" must be a string.', + ); + } + return SkillParams( - name: json['name'] as String, - description: json['description'] as String, - resources: (json['resources'] as List).cast(), - instructions: json['instructions'] as String?, - examplePrompt: json['examplePrompt'] as String?, + name: name, + description: description, + resources: List.unmodifiable(resources), + instructions: instructions as String?, + examplePrompt: examplePrompt as String?, ); } diff --git a/tool/generator/lib/src/utils/text_metrics.dart b/tool/generator/lib/src/utils/text_metrics.dart new file mode 100644 index 00000000..ea0b5935 --- /dev/null +++ b/tool/generator/lib/src/utils/text_metrics.dart @@ -0,0 +1,68 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +/// Recommended maximum line count for a `SKILL.md` file per the Agent Skills +/// standard (https://agentskills.io). +const int maxRecommendedSkillLines = 500; + +/// Maximum `description` length in characters per the Agent Skills standard +/// (https://agentskills.io). +const int maxSkillDescriptionLength = 1024; + +/// Approximate ratio of LLM tokens per whitespace-delimited word. +/// +/// Subword tokenizers used by Gemini (SentencePiece/BPE) average roughly +/// 4 characters per token, or 100 tokens per 60–80 English words (~0.75 words +/// per token, whose reciprocal is ~1.33 tokens per word). We use `1.3` as a +/// fast offline dry-run heuristic without making network calls to `countTokens`. +/// +/// See: https://ai.google.dev/gemini-api/docs/tokens +const double tokensPerWordEstimate = 1.3; + +final RegExp _nonWhitespaceWordRegExp = RegExp(r'\S+'); + +/// Extension methods on [RegExp] for match counting without allocating +/// intermediate substring lists. +extension RegExpMatchCount on RegExp { + /// Returns the number of non-overlapping matches of this pattern in [input] + /// without allocating intermediate substring lists. + int countMatches(String input) => allMatches(input).length; +} + +/// Extension methods on [String] for document size and token estimation. +extension StringMetrics on String { + /// Number of whitespace-delimited words in this string. + int get wordCount => _nonWhitespaceWordRegExp.countMatches(this); + + /// Approximate LLM token count using [tokensPerWordEstimate] (~1.3 tokens + /// per whitespace-delimited word). + int get approximateTokenCount => (wordCount * tokensPerWordEstimate).round(); + + /// Number of lines in this string without allocating intermediate substrings. + /// + /// Matches `LineSplitter` semantics for `\n`, `\r`, and `\r\n`, ignoring a + /// single trailing line terminator at the end of the string. + int get lineCount { + if (isEmpty) return 0; + var lines = 0; + for (var i = 0; i < length; i++) { + final unit = codeUnitAt(i); + if (unit == 0x0D) { + lines++; + if (i + 1 < length && codeUnitAt(i + 1) == 0x0A) { + i++; + } + if (i == length - 1) { + return lines; + } + } else if (unit == 0x0A) { + lines++; + if (i == length - 1) { + return lines; + } + } + } + return lines + 1; + } +} diff --git a/tool/generator/test/commands/base_skill_command_test.dart b/tool/generator/test/commands/base_skill_command_test.dart index 48edfbf4..c84cf4d1 100644 --- a/tool/generator/test/commands/base_skill_command_test.dart +++ b/tool/generator/test/commands/base_skill_command_test.dart @@ -18,6 +18,8 @@ class _TestSkillCommand extends BaseSkillCommand { _TestSkillCommand({required super.httpClient, super.environment}) : super(logger: Logger('_TestSkillCommand')); + int runSkillCalls = 0; + @override String get name => 'test-command'; @@ -31,7 +33,9 @@ class _TestSkillCommand extends BaseSkillCommand { Directory outputDir, int thinkingBudget, { Directory? configDir, - }) async {} + }) async { + runSkillCalls++; + } } void main() { @@ -40,6 +44,7 @@ void main() { late Directory tempDir; late MockClient mockClient; final logs = []; + final records = []; setUp(() async { tempDir = await Directory.systemTemp.createTemp( @@ -50,13 +55,19 @@ void main() { ..addCommand(_TestSkillCommand(httpClient: mockClient)); Logger.root.level = Level.INFO; - Logger.root.onRecord.listen((record) => logs.add(record.message)); + final sub = Logger.root.onRecord.listen((record) { + logs.add(record.message); + records.add(record); + }); + addTearDown(sub.cancel); logs.clear(); + records.clear(); }); tearDown(() async { await tempDir.delete(recursive: true); logs.clear(); + records.clear(); }); test('logs severe error when configuration file not found', () async { @@ -68,6 +79,38 @@ void main() { expect(logs, contains('Configuration file not found: $path')); }); + test( + 'logs severe error when YAML syntax or item schema is invalid', + () async { + final invalidYamlFile = File(p.join(tempDir.path, 'invalid.yaml')); + await invalidYamlFile.writeAsString(': invalid: [yaml'); + await runner.run(['test-command', invalidYamlFile.path]); + expect(logs, contains(contains('Invalid YAML syntax in'))); + + logs.clear(); + final nonMapItemFile = File(p.join(tempDir.path, 'non_map.yaml')); + await nonMapItemFile.writeAsString(jsonEncode([123])); + await runner.run(['test-command', nonMapItemFile.path]); + expect(logs, contains('Invalid configuration: Item 0 is not a Map.')); + + logs.clear(); + final badMapItemFile = File(p.join(tempDir.path, 'bad_map.yaml')); + await badMapItemFile.writeAsString( + jsonEncode([ + {'name': 'foo', 'description': 123, 'resources': []}, + ]), + ); + await runner.run(['test-command', badMapItemFile.path]); + expect( + logs, + contains( + 'Invalid configuration at item 0: ' + 'Skill "foo" field "description" must be a string.', + ), + ); + }, + ); + test('logs warning when no skills match the --skill filter', () async { final configFile = File(p.join(tempDir.path, 'config.yaml')); await configFile.writeAsString( @@ -103,7 +146,52 @@ void main() { expect(logs, contains('No skills found in configuration file.')); }); - test('logs severe error when GEMINI_API_KEY is not set', () async { + test( + 'logs severe error when GEMINI_API_KEY is missing or blank unless --dry-run', + () async { + final configFile = File(p.join(tempDir.path, 'config.yaml')); + await configFile.writeAsString( + jsonEncode(>[ + { + 'name': 'existent-skill', + 'description': 'desc', + 'resources': [], + }, + ]), + ); + + final missingKeyCommand = _TestSkillCommand( + httpClient: mockClient, + environment: {}, + ); + runner = CommandRunner('skills', 'Test runner') + ..addCommand(missingKeyCommand); + await runner.run(['test-command', configFile.path]); + expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + expect(missingKeyCommand.runSkillCalls, 0); + + logs.clear(); + await runner.run(['test-command', '--dry-run', configFile.path]); + expect( + logs, + isNot(contains('GEMINI_API_KEY environment variable not set.')), + ); + expect(missingKeyCommand.runSkillCalls, 1); + + logs.clear(); + final blankKeyCommand = _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': ' '}, + ); + runner = CommandRunner('skills', 'Test runner') + ..addCommand(blankKeyCommand); + await runner.run(['test-command', configFile.path]); + expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + expect(blankKeyCommand.runSkillCalls, 0); + }, + ); + + test('logs severe error when --thinking-budget is invalid', () async { final configFile = File(p.join(tempDir.path, 'config.yaml')); await configFile.writeAsString( jsonEncode(>[ @@ -115,17 +203,28 @@ void main() { ]), ); - // Override environment parameter to simulate missing api key - runner = CommandRunner( - 'skills', - 'Test runner', - )..addCommand(_TestSkillCommand(httpClient: mockClient, environment: {})); - - await IOOverrides.runZoned(() async { - await runner.run(['test-command', configFile.path]); - }, getCurrentDirectory: () => tempDir); - - expect(logs, contains('GEMINI_API_KEY environment variable not set.')); + runner = CommandRunner('skills', 'Test runner') + ..addCommand( + _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': 'test-key'}, + ), + ); + + await runner.run([ + 'test-command', + configFile.path, + '--thinking-budget', + '-1', + ]); + expect( + records.any( + (r) => + r.level == Level.SEVERE && + r.message.contains('Invalid thinking-budget: -1. Skipping.'), + ), + isTrue, + ); }); test('defines model option defaulting to GeminiService.defaultModel', () { diff --git a/tool/generator/test/commands/validate_skills_input_test.dart b/tool/generator/test/commands/validate_skills_input_test.dart index b287e6bd..9badf97e 100644 --- a/tool/generator/test/commands/validate_skills_input_test.dart +++ b/tool/generator/test/commands/validate_skills_input_test.dart @@ -27,9 +27,10 @@ void main() { mockClient = MockClient((request) async => http.Response('', 200)); Logger.root.level = Level.INFO; - Logger.root.onRecord.listen((record) { + final sub = Logger.root.onRecord.listen((record) { logs.add(record.message); }); + addTearDown(sub.cancel); logs.clear(); }); @@ -225,6 +226,7 @@ void main() { await runValidation('flutter_skills.yaml', content1); expect(logs, contains('Item 0 field "name" must be a string.')); + expect(logs, contains('Configuration validation failed.')); logs.clear(); final content2 = jsonEncode([ @@ -240,6 +242,7 @@ void main() { logs, contains('Skill "flutter-skill" field "description" must be a string.'), ); + expect(logs, contains('Configuration validation failed.')); logs.clear(); final content3 = jsonEncode([ @@ -258,6 +261,26 @@ void main() { 'Skill "flutter-skill" field "instructions" must be a string.', ), ); + expect(logs, contains('Configuration validation failed.')); + + logs.clear(); + final content4 = jsonEncode([ + { + 'name': 'flutter-skill', + 'description': 'A Flutter skill description', + 'resources': ['https://example.com'], + 'examplePrompt': 123, // int, should be string + }, + ]); + + await runValidation('flutter_skills.yaml', content4); + expect( + logs, + contains( + 'Skill "flutter-skill" field "examplePrompt" must be a string.', + ), + ); + expect(logs, contains('Configuration validation failed.')); }); }); } diff --git a/tool/generator/test/models/skill_params_test.dart b/tool/generator/test/models/skill_params_test.dart index b0293775..40cb9253 100644 --- a/tool/generator/test/models/skill_params_test.dart +++ b/tool/generator/test/models/skill_params_test.dart @@ -33,5 +33,61 @@ void main() { expect(skill.resources, ['http://example.com']); expect(skill.instructions, 'Do not hallucinate.'); }); + + test('fromYamlMap parses untyped YAML maps including examplePrompt', () { + final yamlMap = { + 'name': 'yaml-skill', + 'description': 'YAML Description', + 'resources': ['https://example.com/doc'], + 'instructions': 'Keep under 500 lines.', + 'examplePrompt': 'Build a responsive layout.', + }; + final skill = SkillParams.fromYamlMap(yamlMap); + expect(skill.name, 'yaml-skill'); + expect(skill.description, 'YAML Description'); + expect(skill.resources, ['https://example.com/doc']); + expect(skill.instructions, 'Keep under 500 lines.'); + expect(skill.examplePrompt, 'Build a responsive layout.'); + }); + + test('fromYamlMap throws FormatException on invalid field types', () { + expect( + () => SkillParams.fromYamlMap({}), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 123, + 'resources': ['https://example.com'], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 'desc', + 'resources': [123], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': ' ', + 'description': 'desc', + 'resources': ['https://example.com'], + }), + throwsFormatException, + ); + expect( + () => SkillParams.fromYamlMap({ + 'name': 'foo', + 'description': 'desc', + 'resources': ['https://example.com'], + 'examplePrompt': 456, + }), + throwsFormatException, + ); + }); }); } diff --git a/tool/generator/test/skills_cli_test.dart b/tool/generator/test/skills_cli_test.dart new file mode 100644 index 00000000..6fb5e47e --- /dev/null +++ b/tool/generator/test/skills_cli_test.dart @@ -0,0 +1,47 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:test/test.dart'; + +import '../bin/skills.dart' as cli; + +void main() { + group('skills CLI entrypoint', () { + late Directory tempDir; + + setUp(() async { + exitCode = 0; + tempDir = await Directory.systemTemp.createTemp('skills_cli_test'); + }); + + tearDown(() async { + exitCode = 0; + await tempDir.delete(recursive: true); + }); + + test('exits 0 for --version and warning-only runs', () async { + await cli.main(['--version']); + expect(exitCode, 0); + + final emptyConfig = File(p.join(tempDir.path, 'empty.yaml')) + ..writeAsStringSync('[]'); + await cli.main(['generate-skill', emptyConfig.path]); + expect(exitCode, 0); + }); + + test('sets exitCode = 64 on UsageException', () async { + await cli.main(['--unknown-flag']); + expect(exitCode, 64); + }); + + test('sets exitCode = 1 when a SEVERE error is logged', () async { + final missingPath = p.join(tempDir.path, 'does_not_exist.yaml'); + await cli.main(['generate-skill', missingPath]); + expect(exitCode, 1); + }); + }); +} diff --git a/tool/generator/test/update_skills_test.dart b/tool/generator/test/update_skills_test.dart index 4c9680e4..5ab2080f 100644 --- a/tool/generator/test/update_skills_test.dart +++ b/tool/generator/test/update_skills_test.dart @@ -131,7 +131,7 @@ void main() { await runner.run(['update-skill', inputYamlFile.path]); expect(logs, contains(contains('Skill file not found at'))); - expect(logs, contains(contains('Cannot update an non-existent skill.'))); + expect(logs, contains(contains('Cannot update a non-existent skill.'))); }); test( diff --git a/tool/generator/test/utils/text_metrics_test.dart b/tool/generator/test/utils/text_metrics_test.dart new file mode 100644 index 00000000..0094c5b8 --- /dev/null +++ b/tool/generator/test/utils/text_metrics_test.dart @@ -0,0 +1,116 @@ +// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +import 'dart:convert'; + +import 'package:skills/src/utils/text_metrics.dart'; +import 'package:test/test.dart'; + +void main() { + group('Agent Skills standard constants', () { + test('exposes expected Agent Skills limits and token ratio', () { + expect(maxRecommendedSkillLines, 500); + expect(maxSkillDescriptionLength, 1024); + expect(tokensPerWordEstimate, 1.3); + }); + }); + + group('RegExpMatchCount', () { + test('returns 0 when input is empty or has no matches', () { + final digits = RegExp(r'\d+'); + expect(digits.countMatches(''), 0); + expect(digits.countMatches('no numbers here'), 0); + }); + + test('counts non-overlapping matches across single and multiple lines', () { + final digits = RegExp(r'\d+'); + expect(digits.countMatches('1 22 333\n4444'), 4); + + final headings = RegExp(r'^#+\s+', multiLine: true); + expect(headings.countMatches('# Title\nBody\n## Section 1\n### Sub'), 3); + }); + }); + + group('StringMetrics', () { + group('wordCount', () { + test('returns 0 for empty and whitespace-only strings', () { + expect(''.wordCount, 0); + expect(' '.wordCount, 0); + expect('\t\n\r\n '.wordCount, 0); + }); + + test('counts single and multiple whitespace-delimited words', () { + expect('hello'.wordCount, 1); + expect(' hello world '.wordCount, 2); + expect('one\ttwo\nthree\r\nfour'.wordCount, 4); + }); + + test('counts markdown tokens and punctuation-attached words', () { + const markdown = '# Heading\n\n- `code_symbol`: value (v1.2.3)'; + // Tokens: #, Heading, -, `code_symbol`:, value, (v1.2.3) + expect(markdown.wordCount, 6); + }); + }); + + group('approximateTokenCount', () { + test('returns 0 for empty and whitespace-only strings', () { + expect(''.approximateTokenCount, 0); + expect(' \n\t '.approximateTokenCount, 0); + }); + + test('multiplies wordCount by 1.3 and rounds to nearest integer', () { + // 1 * 1.3 = 1.3 -> 1 + expect('one'.approximateTokenCount, 1); + // 2 * 1.3 = 2.6 -> 3 + expect('one two'.approximateTokenCount, 3); + // 4 * 1.3 = 5.2 -> 5 + expect('one two three four'.approximateTokenCount, 5); + // 7 * 1.3 = 9.1 -> 9 + expect('a b c d e f g'.approximateTokenCount, 9); + // 8 * 1.3 = 10.4 -> 10 + expect('a b c d e f g h'.approximateTokenCount, 10); + // 10 * 1.3 = 13.0 -> 13 + expect('a b c d e f g h i j'.approximateTokenCount, 13); + }); + }); + + group('lineCount', () { + test('returns 0 for empty string', () { + expect(''.lineCount, 0); + }); + + test('counts single and multi-line LF, CR, and CRLF strings', () { + expect('single line'.lineCount, 1); + expect('line 1\nline 2\nline 3'.lineCount, 3); + expect('line 1\rline 2\rline 3'.lineCount, 3); + expect('line 1\r\nline 2\r\nline 3'.lineCount, 3); + }); + + test('matches LineSplitter across trailing newline edge cases', () { + const samples = [ + '', + '\n', + '\r', + '\r\n', + '\n\n', + '\r\n\r\n', + 'a', + 'a\n', + 'a\r', + 'a\r\n', + 'line 1\nline 2\n', + 'line 1\nline 2\n\n', + 'line 1\rline 2\r\nline 3\n', + ]; + for (final sample in samples) { + expect( + sample.lineCount, + const LineSplitter().convert(sample).length, + reason: 'Mismatch for ${jsonEncode(sample)}', + ); + } + }); + }); + }); +} From d32e75adeb4bfb9cad0ab84e7f21c40bbf6329e4 Mon Sep 17 00:00:00 2001 From: Jaime Wren Date: Wed, 18 Nov 2026 18:11:26 -0800 Subject: [PATCH 2/4] generator: Reject duplicate skill names in validateYamlList Duplicate skill names in YAML configuration files previously passed validation silently, causing subsequent commands to overwrite earlier SKILL.md files or emit duplicate README table rows. Track seen skill names in ValidateSkillCommand.validateYamlList and log a SEVERE error whenever a duplicate name appears. Refs: https://github.com/flutter/agent-plugins/pull/267 (Gemini 4 generator follow-up) Tested: dart format, dart analyze --fatal-infos --fatal-warnings, dart test (127 passed) --- .../src/commands/validate_skill_command.dart | 6 +++++ .../commands/validate_skills_input_test.dart | 24 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/tool/generator/lib/src/commands/validate_skill_command.dart b/tool/generator/lib/src/commands/validate_skill_command.dart index 3e6fa2f1..ce0aa179 100644 --- a/tool/generator/lib/src/commands/validate_skill_command.dart +++ b/tool/generator/lib/src/commands/validate_skill_command.dart @@ -47,6 +47,7 @@ class ValidateSkillCommand extends BaseSkillCommand { } var isValid = true; + final seenNames = {}; for (var i = 0; i < yamlList.length; i++) { final item = yamlList[i]; @@ -96,6 +97,11 @@ class ValidateSkillCommand extends BaseSkillCommand { } if (rawName is String) { + if (!seenNames.add(name)) { + logger.severe('Duplicate skill name "$name" in $fileName.'); + isValid = false; + } + if (!_kebabCaseRegExp.hasMatch(name)) { logger.severe( 'Skill name "$name" must be kabob-case (e.g. abc-def).', diff --git a/tool/generator/test/commands/validate_skills_input_test.dart b/tool/generator/test/commands/validate_skills_input_test.dart index 9badf97e..ff9b0605 100644 --- a/tool/generator/test/commands/validate_skills_input_test.dart +++ b/tool/generator/test/commands/validate_skills_input_test.dart @@ -282,5 +282,29 @@ void main() { ); expect(logs, contains('Configuration validation failed.')); }); + + test('fails when configuration contains duplicate skill names', () async { + final content = jsonEncode([ + { + 'name': 'flutter-duplicate-skill', + 'description': 'First skill description', + 'resources': ['https://example.com/first'], + }, + { + 'name': 'flutter-duplicate-skill', + 'description': 'Second skill description', + 'resources': ['https://example.com/second'], + }, + ]); + + await runValidation('flutter_skills.yaml', content); + expect( + logs, + contains( + 'Duplicate skill name "flutter-duplicate-skill" in flutter_skills.yaml.', + ), + ); + expect(logs, contains('Configuration validation failed.')); + }); }); } From b25220dbabde1678d0da5966279e4ea97824b58e Mon Sep 17 00:00:00 2001 From: Jaime Wren Date: Wed, 18 Nov 2026 17:34:59 -0800 Subject: [PATCH 3/4] generator: Fix frontmatter stripping, truncation, and client close Naive indexOf('---') stripping truncated Markdown horizontal rules, while MAX_TOKENS or frontmatter-only responses bypassed retry checks and overwrote SKILL.md with incomplete or body-less output. Parse leading YAML frontmatter via package:yaml (including camelCase keys and block scalars), strip 3+/4-backtick outer fences, reject non-STOP finishReason and empty cleaned bodies inside retry loops, and add close() to release internally owned HTTP clients. Refs: https://github.com/flutter/agent-plugins/pull/267 (Gemini 4 generator follow-up) Tested: dart format, dart analyze --fatal-infos --fatal-warnings, dart test (125 passed) --- .../lib/src/services/gemini_service.dart | 244 ++++++++--- .../test/services/gemini_service_test.dart | 380 +++++++++++++++++- 2 files changed, 560 insertions(+), 64 deletions(-) diff --git a/tool/generator/lib/src/services/gemini_service.dart b/tool/generator/lib/src/services/gemini_service.dart index 83fed1ff..995977dd 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 d49c6401..6a4daa80 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(); + } +} From 59349e0e16761f56c99468455e2f71f3aaf97f86 Mon Sep 17 00:00:00 2001 From: Jaime Wren Date: Wed, 18 Nov 2026 17:41:34 -0800 Subject: [PATCH 4/4] generator: Default to Gemini 4 Carbon and add --thinking-level Gemini 4 Carbon succeeds Argon as Google's strongest reasoning model at the same token cost, while bare --model IDs 404ed against v1beta and incompatible thinking parameters failed only after 3 HTTP retries. Set defaultModel to models/gemini-4-carbon alongside Neon, Argon, and Hydrogen constants, normalize bare model IDs, omit temperature on Gemini 3/4, and add --thinking-level with upfront model-compatibility validation across Gemini 4, Gemini 3, legacy, and tuned models. Refs: https://github.com/flutter/agent-plugins/pull/267 (Gemini 4 generator follow-up) Tested: dart format, dart analyze --fatal-infos --fatal-warnings, dart test (149 passed) --- tool/generator/README.md | 27 +- .../lib/src/commands/base_skill_command.dart | 60 ++- .../src/commands/generate_skill_command.dart | 2 +- .../src/commands/update_skill_command.dart | 2 +- .../src/commands/validate_skill_command.dart | 2 +- .../lib/src/services/gemini_service.dart | 377 ++++++++++++---- .../commands/base_skill_command_test.dart | 194 ++++++-- tool/generator/test/generate_skills_test.dart | 79 +++- .../test/services/gemini_service_test.dart | 418 ++++++++++++++++-- 9 files changed, 979 insertions(+), 182 deletions(-) diff --git a/tool/generator/README.md b/tool/generator/README.md index 60458a52..35127763 100644 --- a/tool/generator/README.md +++ b/tool/generator/README.md @@ -9,7 +9,7 @@ The Skills CLI simplifies the process of creating "Agent Skills" from external d ## Prerequisite -This tool requires the `GEMINI_API_KEY` environment variable to be set. +This tool requires the `GEMINI_API_KEY` environment variable to be set (except when running with `--dry-run`). ## Commands @@ -31,10 +31,11 @@ dart run skills generate-skill [options] [config_file] **Options:** * `--skill`: Filter to generate only the specified skill by name. -* `--directory` (`-d`): The directory to output the generated skill folder. Defaults to `../skills/`. -* `--model`: The Gemini model to use for generation. Defaults to `models/gemini-4-argon`. -* `--thinking-budget`: The token budget for the model to "think" before generating content. Defaults to 4096. -* `--dry-run`: Performs a dry run, showing what would be generated and token count without writing files. +* `--directory` (`-d`): The directory to output the generated skill folder. Defaults to `skills/`. +* `--model`: The Gemini model to use for generation (e.g., `models/gemini-4-carbon`, `models/gemini-4-neon`, `models/gemini-4-argon`, `models/gemini-4-hydrogen`). Defaults to `models/gemini-4-carbon`. +* `--thinking-level`: Reasoning depth for Gemini 3 and Gemini 4 models (`low`, `medium`, `high` on Carbon/Argon; `+xhigh` on Neon/Hydrogen; `+minimal` on Gemini 3 Flash-Lite). Defaults to the model default. +* `--thinking-budget`: Legacy token budget for model thinking on earlier models (`-1` for dynamic, `0` to disable where supported, or a positive token count; legacy default: `4096`). +* `--dry-run` (`-n`): Performs a dry run, showing what would be generated and estimated token count without writing files. **Example:** Generate all skills defined in resources/flutter_skills.yaml to the skills/ directory: @@ -63,9 +64,11 @@ dart run skills update-skill [options] [config_file] **Options:** * `--skill`: Filter to update only the specified skill by name. -* `--directory` (`-d`): The directory to search for skills. Defaults to `../skills/`. -* `--model`: The Gemini model to use for generation. Defaults to `models/gemini-4-argon`. -* `--thinking-budget`: The token budget for the model to "think" before generating content. Defaults to 4096. +* `--directory` (`-d`): The directory to search for skills. Defaults to `skills/`. +* `--model`: The Gemini model to use for generation (e.g., `models/gemini-4-carbon`, `models/gemini-4-neon`, `models/gemini-4-argon`, `models/gemini-4-hydrogen`). Defaults to `models/gemini-4-carbon`. +* `--thinking-level`: Reasoning depth for Gemini 3 and Gemini 4 models (`low`, `medium`, `high` on Carbon/Argon; `+xhigh` on Neon/Hydrogen; `+minimal` on Gemini 3 Flash-Lite). Defaults to the model default. +* `--thinking-budget`: Legacy token budget for model thinking on earlier models (`-1` for dynamic, `0` to disable where supported, or a positive token count; legacy default: `4096`). +* `--dry-run` (`-n`): Performs a dry run, showing original and raw content sizes without writing files. **Example:** Update all skills defined in resources/flutter_skills.yaml: @@ -94,9 +97,11 @@ dart run skills validate-skill [options] [config_file] **Options:** * `--skill`: Validate only the specified skill by name. -* `--directory` (`-d`): The directory containing the generated skills to validate. Defaults to `../skills/`. -* `--model`: The Gemini model to use for generation. Defaults to `models/gemini-4-argon`. -* `--thinking-budget`: The token budget for the model to "think" before generating content. Defaults to 4096. +* `--directory` (`-d`): The directory containing the generated skills to validate. Defaults to `skills/`. +* `--model`: The Gemini model to use for generation (e.g., `models/gemini-4-carbon`, `models/gemini-4-neon`, `models/gemini-4-argon`, `models/gemini-4-hydrogen`). Defaults to `models/gemini-4-carbon`. +* `--thinking-level`: Reasoning depth for Gemini 3 and Gemini 4 models (`low`, `medium`, `high` on Carbon/Argon; `+xhigh` on Neon/Hydrogen; `+minimal` on Gemini 3 Flash-Lite). Defaults to the model default. +* `--thinking-budget`: Legacy token budget for model thinking on earlier models (`-1` for dynamic, `0` to disable where supported, or a positive token count; legacy default: `4096`). +* `--dry-run` (`-n`): Performs a dry run, showing existing and fetched content sizes without writing files. **Example:** Validate skills in the default 'skills' directory: diff --git a/tool/generator/lib/src/commands/base_skill_command.dart b/tool/generator/lib/src/commands/base_skill_command.dart index 5531f3cf..9a018d20 100644 --- a/tool/generator/lib/src/commands/base_skill_command.dart +++ b/tool/generator/lib/src/commands/base_skill_command.dart @@ -25,14 +25,25 @@ abstract class BaseSkillCommand extends BaseYamlCommand { ..addOption( 'model', help: - 'The Gemini model to use for generation. Defaults to ${GeminiService.defaultModel}.', + 'The Gemini model to use for generation ' + '(e.g., ${GeminiService.knownModels.join(', ')}). ' + 'Defaults to ${GeminiService.defaultModel}.', defaultsTo: GeminiService.defaultModel, ) + ..addOption( + 'thinking-level', + allowed: GeminiService.supportedThinkingLevels, + help: + 'Reasoning depth for Gemini 3 and Gemini 4 models ' + '(low, medium, high on Carbon/Argon; +xhigh on Neon/Hydrogen; ' + '+minimal on Gemini 3 Flash-Lite). Defaults to the model default.', + ) ..addOption( 'thinking-budget', help: - 'The token budget for the model to "think". Defaults to ${GeminiService.defaultThinkingBudget} (recommended for technical documentation).', - defaultsTo: GeminiService.defaultThinkingBudget.toString(), + 'Legacy token budget for model thinking (-1 for dynamic, 0 to disable ' + 'where supported, or positive token count; legacy default: ' + '${GeminiService.defaultThinkingBudget}).', ) ..addFlag( 'dry-run', @@ -62,19 +73,40 @@ abstract class BaseSkillCommand extends BaseYamlCommand { return; } - final rawBudget = argResults!['thinking-budget'] as String; - final thinkingBudget = int.tryParse(rawBudget); - if (thinkingBudget == null || thinkingBudget < 0) { - logger.severe('Invalid thinking-budget: $rawBudget. Skipping.'); - return; + if (argResults!.wasParsed('thinking-level') && + argResults!.wasParsed('thinking-budget')) { + usageException( + 'Cannot specify both --thinking-level and --thinking-budget.', + ); + } + + int? thinkingBudget; + final rawBudget = argResults?['thinking-budget'] as String?; + if (rawBudget != null) { + final parsed = int.tryParse(rawBudget); + if (parsed == null || parsed < -1) { + logger.severe('Invalid thinking-budget: $rawBudget. Skipping.'); + return; + } + thinkingBudget = parsed; } final model = argResults?['model'] as String?; - final gemini = GeminiService( - apiKey: (apiKey != null && apiKey.trim().isNotEmpty) ? apiKey : 'dry-run', - httpClient: httpClient, - model: model, - ); + final thinkingLevel = argResults?['thinking-level'] as String?; + final GeminiService gemini; + try { + gemini = GeminiService( + apiKey: (apiKey != null && apiKey.trim().isNotEmpty) + ? apiKey + : 'dry-run', + httpClient: httpClient, + model: model, + thinkingLevel: thinkingLevel, + )..validateThinkingBudget(thinkingBudget); + } on FormatException catch (e) { + logger.severe('Invalid model or thinking configuration: ${e.message}'); + return; + } for (final skill in skills) { await runSkill( @@ -106,7 +138,7 @@ abstract class BaseSkillCommand extends BaseYamlCommand { SkillParams skill, GeminiService gemini, Directory outputDir, - int thinkingBudget, { + int? thinkingBudget, { Directory? configDir, }); } diff --git a/tool/generator/lib/src/commands/generate_skill_command.dart b/tool/generator/lib/src/commands/generate_skill_command.dart index 927d25e4..2f752bbc 100644 --- a/tool/generator/lib/src/commands/generate_skill_command.dart +++ b/tool/generator/lib/src/commands/generate_skill_command.dart @@ -33,7 +33,7 @@ class GenerateSkillCommand extends BaseSkillCommand { SkillParams skill, GeminiService gemini, Directory outputDir, - int thinkingBudget, { + int? thinkingBudget, { Directory? configDir, }) async { logger.info('Generating skill: ${skill.name}...'); diff --git a/tool/generator/lib/src/commands/update_skill_command.dart b/tool/generator/lib/src/commands/update_skill_command.dart index 0c88bc88..84b05739 100644 --- a/tool/generator/lib/src/commands/update_skill_command.dart +++ b/tool/generator/lib/src/commands/update_skill_command.dart @@ -34,7 +34,7 @@ class UpdateSkillCommand extends BaseSkillCommand { SkillParams skill, GeminiService gemini, Directory outputDir, - int thinkingBudget, { + int? thinkingBudget, { Directory? configDir, }) async { logger.info('Updating skill: ${skill.name}...'); diff --git a/tool/generator/lib/src/commands/validate_skill_command.dart b/tool/generator/lib/src/commands/validate_skill_command.dart index ce0aa179..9a167800 100644 --- a/tool/generator/lib/src/commands/validate_skill_command.dart +++ b/tool/generator/lib/src/commands/validate_skill_command.dart @@ -161,7 +161,7 @@ class ValidateSkillCommand extends BaseSkillCommand { SkillParams skill, GeminiService gemini, Directory outputDir, - int thinkingBudget, { + int? thinkingBudget, { Directory? configDir, }) async { logger.info('Validating skill: ${skill.name}...'); diff --git a/tool/generator/lib/src/services/gemini_service.dart b/tool/generator/lib/src/services/gemini_service.dart index 995977dd..8ee46a49 100644 --- a/tool/generator/lib/src/services/gemini_service.dart +++ b/tool/generator/lib/src/services/gemini_service.dart @@ -2,6 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'dart:convert'; import 'dart:io' as io; import 'package:google_cloud_ai_generativelanguage_v1beta/generativelanguage.dart'; @@ -17,57 +18,119 @@ import 'skill_instructions.dart'; /// Service for interacting with the Gemini API to generate and validate skills. class GeminiService { /// Creates a new [GeminiService]. - GeminiService({ + /// + /// Throws a [FormatException] if [model] is empty or if [thinkingLevel] is + /// invalid or incompatible with [model]. + factory GeminiService({ required String apiKey, http.Client? httpClient, String? model, - }) : _model = model ?? defaultModel, - _ownsClient = httpClient == null, - _client = _ApiKeyClient(httpClient ?? http.Client(), apiKey); + String? thinkingLevel, + }) { + final normalizedModel = normalizeModelName(model ?? defaultModel); + final normalizedLevel = _resolveThinkingLevel( + model: normalizedModel, + thinkingLevel: thinkingLevel, + ); + return GeminiService._( + model: normalizedModel, + thinkingLevel: normalizedLevel, + ownsClient: httpClient == null, + client: _ApiKeyClient( + httpClient ?? http.Client(), + apiKey, + thinkingLevel: normalizedLevel?.toUpperCase(), + ), + ); + } + + GeminiService._({ + required String model, + required String? thinkingLevel, + required bool ownsClient, + required http.Client client, + }) : _model = model, + _thinkingLevel = thinkingLevel, + _ownsClient = ownsClient, + _client = client; + + /// Gemini 4 Carbon (`models/gemini-4-carbon`): strongest frontier reasoning + /// model built for complex software engineering, verification, and + /// source-grounded synthesis. + static const String gemini4CarbonModel = 'models/gemini-4-carbon'; + + /// Gemini 4 Neon (`models/gemini-4-neon`): balanced Gemini 4 frontier model + /// sitting between Carbon and Hydrogen with faster end-to-end completion than + /// Carbon and deeper reasoning than Hydrogen. + static const String gemini4NeonModel = 'models/gemini-4-neon'; + + /// Gemini 4 Argon (`models/gemini-4-argon`): predecessor Gemini 4 reasoning + /// model supporting `low`, `medium`, and `high` thinking levels. + static const String gemini4ArgonModel = 'models/gemini-4-argon'; + + /// Gemini 4 Hydrogen (`models/gemini-4-hydrogen`): fast, cost-efficient + /// general-purpose Gemini 4 model (also available on the free tier). + static const String gemini4HydrogenModel = 'models/gemini-4-hydrogen'; + + /// Known Gemini model identifiers supported out of the box. + static const List knownModels = [ + gemini4CarbonModel, + gemini4NeonModel, + gemini4ArgonModel, + gemini4HydrogenModel, + ]; - /// Default temperature for legacy models. + /// Default temperature for legacy Gemini 1.x / 2.x models. /// - /// Note: For Gemini 4 models (such as `gemini-4-argon`), sampling parameters - /// such as temperature, top_p, and top_k should be omitted, as the model - /// optimizes its own reasoning path and setting them can degrade performance - /// or is ignored by the API. + /// Note: For Gemini 3 and Gemini 4 models, sampling parameters such as + /// `temperature`, `top_p`, and `top_k` should be omitted, as these models + /// optimize their own reasoning paths and custom sampling parameters are + /// ignored or rejected by the API. /// - /// See: https://ai.google.dev/gemini-api/docs/latest-model#migrate-to-gemini-4-argon + /// See: https://ai.google.dev/gemini-api/docs/whats-new-gemini-4-carbon#migrate-to-gemini-4-carbon static const double defaultTemperature = 0.2; /// The default model to use for generation. /// - /// Defaults to Gemini 4 Argon (`models/gemini-4-argon`), Google's flagship - /// model for software engineering, deep reasoning, and autonomous agents, - /// featuring a 1M unified context window. + /// Defaults to [gemini4CarbonModel] (`models/gemini-4-carbon`), Google's + /// strongest frontier reasoning model for software engineering and dense + /// technical synthesis, featuring a 1M unified context window. /// /// See: - /// - https://ai.google.dev/gemini-api/docs/models/gemini-4-argon - /// - https://ai.google.dev/gemini-api/docs/latest-model - static const String defaultModel = 'models/gemini-4-argon'; + /// - https://ai.google.dev/gemini-api/docs/models/gemini-4-carbon + /// - https://ai.google.dev/gemini-api/docs/choosing-a-model + static const String defaultModel = gemini4CarbonModel; - /// The default token budget for thinking. + /// The default token budget for thinking on Gemini 2.5 models that use + /// `thinkingBudget` instead of `thinkingLevel`. /// - /// Gemini 4 Argon engages in dynamic reasoning by default (using thinking - /// levels: low, medium, high). When communicating via GenerativeLanguage API, - /// thinking budget controls reasoning depth. + /// Gemini 3 and Gemini 4 models engage in dynamic reasoning by default + /// (`medium` on Carbon/Argon, `high` on Neon/Hydrogen) controlled via + /// `thinkingLevel` (`minimal`, `low`, `medium`, `high`, `xhigh`). /// - /// See: - /// - https://ai.google.dev/gemini-api/docs/thinking - /// - https://ai.google.dev/gemini-api/docs/latest-model#understanding-thinking-levels + /// See: https://ai.google.dev/gemini-api/docs/thinking static const int defaultThinkingBudget = 4096; + /// Allowed `thinking_level` values across Gemini 3 and Gemini 4 models. + static const List supportedThinkingLevels = [ + 'minimal', + 'low', + 'medium', + 'high', + 'xhigh', + ]; + /// The default max output tokens for generation. /// - /// For Gemini 4 Argon (and thinking models), thinking tokens and response - /// tokens share the same output budget and context window. In synchronous - /// mode, Gemini 4 Argon supports a maximum output limit of 65,536 tokens. - /// Setting a limit lower than 32K (such as 8192) can cause reasoning to be - /// truncated. + /// For Gemini 4 models (and thinking models), thinking tokens and response + /// tokens share the same output budget and 1M unified context window. + /// Synchronous interactions default to a 65,536-token limit (note that direct + /// non-streaming REST hops on Carbon and Argon return up to 32,768 tokens per + /// hop without continuation). /// /// See: - /// - https://ai.google.dev/gemini-api/docs/models/gemini-4-argon - /// - https://ai.google.dev/gemini-api/docs/latest-model#setting-output-token-limits + /// - https://ai.google.dev/gemini-api/docs/thinking#token-limits + /// - https://ai.google.dev/gemini-api/docs/long-decode static const int defaultMaxOutputLimit = 65536; /// The default safety settings to use for generation. @@ -118,11 +181,125 @@ class GeminiService { 'allowed-tools', }; + /// Normalizes a Gemini [model] identifier so it includes the `'models/'` + /// (or `'tunedModels/'`) resource prefix required by the Generative Language + /// REST endpoint (`/v1beta/{model}:generateContent`). + /// + /// Throws a [FormatException] if the model slug is empty. + static String normalizeModelName(String model) { + final trimmed = model.trim(); + final String prefix; + final String slug; + if (trimmed.startsWith('models/')) { + prefix = 'models/'; + slug = trimmed.substring('models/'.length).trim(); + } else if (trimmed.startsWith('tunedModels/')) { + prefix = 'tunedModels/'; + slug = trimmed.substring('tunedModels/'.length).trim(); + } else { + prefix = 'models/'; + slug = trimmed; + } + + if (slug.isEmpty) { + throw FormatException('Model identifier must not be empty: "$model"'); + } + return '$prefix$slug'; + } + + static String? _resolveThinkingLevel({ + required String model, + required String? thinkingLevel, + }) { + if (thinkingLevel == null) return null; + final normalized = thinkingLevel.trim().toLowerCase(); + if (normalized.isEmpty || !supportedThinkingLevels.contains(normalized)) { + throw FormatException( + 'Unsupported thinking level "$thinkingLevel". Allowed values: ' + '${supportedThinkingLevels.join(', ')}.', + ); + } + if (model.startsWith('tunedModels/')) { + throw FormatException( + 'Thinking level "$normalized" is not supported by tuned model $model.', + ); + } + if (model.startsWith('models/gemini-1') || + model.startsWith('models/gemini-2')) { + throw FormatException( + 'Thinking level "$normalized" is not supported by $model; ' + 'use --thinking-budget instead.', + ); + } + if (normalized == 'minimal' && + (model.startsWith('models/gemini-4') || + model.startsWith('models/gemini-3.8-flash') || + model.startsWith('models/gemini-3.1-pro') || + model.startsWith('models/gemini-3-pro'))) { + throw FormatException( + 'Thinking level "minimal" is not supported by $model.', + ); + } + if (normalized == 'medium' && model.startsWith('models/gemini-3-pro')) { + throw FormatException( + 'Thinking level "medium" is not supported by $model.', + ); + } + if (normalized == 'xhigh' && + (model.startsWith(gemini4CarbonModel) || + model.startsWith(gemini4ArgonModel) || + model.startsWith('models/gemini-3'))) { + throw FormatException( + 'Thinking level "xhigh" is not supported by $model.', + ); + } + return normalized; + } + final String _model; + final String? _thinkingLevel; final bool _ownsClient; final http.Client _client; final Logger _logger = Logger('GeminiService'); + bool get _isModernThinkingModel => + _model.startsWith('models/gemini-4') || + _model.startsWith('models/gemini-3'); + + bool get _isTunedModel => _model.startsWith('tunedModels/'); + + bool get _supportsThinkingBudget => + !_isTunedModel && + !_model.startsWith('models/gemini-1') && + !_model.startsWith('models/gemini-2.0'); + + /// Validates that [thinkingBudget] is compatible with this service's model. + /// + /// Throws a [FormatException] if [thinkingBudget] is less than `-1`, if a + /// non-zero budget is passed for a non-thinking model, or if `0` is passed + /// for a model where thinking cannot be disabled. + void validateThinkingBudget(int? thinkingBudget) { + if (thinkingBudget == null) return; + if (thinkingBudget < -1) { + throw FormatException( + 'thinkingBudget must be >= -1 (got $thinkingBudget).', + ); + } + if (!_supportsThinkingBudget && thinkingBudget != 0) { + throw FormatException( + 'Thinking budget $thinkingBudget is not supported by $_model ' + '(only 0 to omit thinkingConfig is allowed).', + ); + } + if (thinkingBudget == 0 && + (_model.startsWith('models/gemini-4') || + _model.startsWith('models/gemini-2.5-pro'))) { + throw FormatException( + 'Thinking cannot be disabled (thinkingBudget: 0) on $_model.', + ); + } + } + /// Closes the underlying HTTP client if it was created internally by this /// [GeminiService]. /// @@ -133,26 +310,42 @@ class GeminiService { } } + String _formatThinkingSummary(int? thinkingBudget) { + if (_thinkingLevel != null) { + return 'Thinking Level: $_thinkingLevel'; + } + if (thinkingBudget != null) { + return !_supportsThinkingBudget + ? 'Thinking: none' + : 'Thinking Budget: $thinkingBudget'; + } + if (_isModernThinkingModel) { + return 'Thinking Level: default'; + } + if (!_supportsThinkingBudget) { + return 'Thinking: none'; + } + return 'Thinking Budget: $defaultThinkingBudget'; + } + /// Generates the content for a skill based on raw markdown input. Future generateSkillContent( String rawMarkdown, String skillName, String description, { String? instructions, - int thinkingBudget = defaultThinkingBudget, + int? thinkingBudget, }) async { - final service = GenerativeService(client: _client); - final lastModified = io.HttpDate.format(DateTime.now()); - final prompt = Prompts.createSkillPrompt(rawMarkdown, instructions); - final request = _createRequest( - prompt, + Prompts.createSkillPrompt(rawMarkdown, instructions), systemInstruction: skillInstructions, thinkingBudget: thinkingBudget, ); + final service = GenerativeService(client: _client); + final lastModified = io.HttpDate.format(DateTime.now()); _logger.info( - ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, Thinking Budget: $thinkingBudget', + ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, ${_formatThinkingSummary(thinkingBudget)}', ); try { @@ -191,24 +384,18 @@ metadata: String skillName, String description, { String? instructions, - int thinkingBudget = defaultThinkingBudget, + int? thinkingBudget, }) async { - final service = GenerativeService(client: _client); - final lastModified = io.HttpDate.format(DateTime.now()); - final prompt = Prompts.updateSkillPrompt( - existingContent, - rawMarkdown, - instructions, - ); - final request = _createRequest( - prompt, + Prompts.updateSkillPrompt(existingContent, rawMarkdown, instructions), systemInstruction: skillInstructions, thinkingBudget: thinkingBudget, ); + final service = GenerativeService(client: _client); + final lastModified = io.HttpDate.format(DateTime.now()); _logger.info( - ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, Thinking Budget: $thinkingBudget', + ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, ${_formatThinkingSummary(thinkingBudget)}', ); try { @@ -248,25 +435,23 @@ metadata: String generationDate, String modelName, String currentSkillContent, { - int thinkingBudget = defaultThinkingBudget, + int? thinkingBudget, }) async { - final service = GenerativeService(client: _client); - final validationPrompt = Prompts.validateExistingSkillContentPrompt( - markdown, - instructions, - generationDate, - modelName, - currentSkillContent, - ); - final request = _createRequest( - validationPrompt, + Prompts.validateExistingSkillContentPrompt( + markdown, + instructions, + generationDate, + modelName, + currentSkillContent, + ), systemInstruction: skillInstructions, thinkingBudget: thinkingBudget, ); + final service = GenerativeService(client: _client); _logger.info( - ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, Thinking Budget: $thinkingBudget', + ' Model: $_model, Max Output Tokens: $defaultMaxOutputLimit, ${_formatThinkingSummary(thinkingBudget)}', ); try { @@ -420,12 +605,37 @@ metadata: GenerateContentRequest _createRequest( String prompt, { String? systemInstruction, - int thinkingBudget = defaultThinkingBudget, + int? thinkingBudget, }) { - // For Gemini 4 thinking models, sampling parameters (temperature, top_p, - // top_k) should be omitted per Google best practices. - final isGemini4 = - _model.startsWith('models/gemini-4') || _model.startsWith('gemini-4'); + validateThinkingBudget(thinkingBudget); + + final ThinkingConfig? resolvedThinkingConfig; + if (_thinkingLevel != null) { + resolvedThinkingConfig = ThinkingConfig(includeThoughts: true); + } else if (thinkingBudget != null) { + if (!_supportsThinkingBudget) { + resolvedThinkingConfig = null; + } else if (thinkingBudget > 0 || thinkingBudget == -1) { + resolvedThinkingConfig = ThinkingConfig( + includeThoughts: true, + thinkingBudget: thinkingBudget, + ); + } else { + resolvedThinkingConfig = ThinkingConfig( + includeThoughts: false, + thinkingBudget: 0, + ); + } + } else if (_isModernThinkingModel) { + resolvedThinkingConfig = ThinkingConfig(includeThoughts: true); + } else if (!_supportsThinkingBudget) { + resolvedThinkingConfig = null; + } else { + resolvedThinkingConfig = ThinkingConfig( + includeThoughts: true, + thinkingBudget: defaultThinkingBudget, + ); + } return GenerateContentRequest( model: _model, @@ -437,14 +647,9 @@ metadata: ], // See [GenerationConfig] in package:google_cloud_ai_generativelanguage_v1beta generationConfig: GenerationConfig( - temperature: isGemini4 ? null : defaultTemperature, + temperature: _isModernThinkingModel ? null : defaultTemperature, maxOutputTokens: defaultMaxOutputLimit, - thinkingConfig: thinkingBudget > 0 - ? ThinkingConfig( - includeThoughts: true, - thinkingBudget: thinkingBudget, - ) - : null, + thinkingConfig: resolvedThinkingConfig, ), safetySettings: defaultSafetySettings, ); @@ -452,14 +657,38 @@ metadata: } class _ApiKeyClient extends http.BaseClient { - _ApiKeyClient(this._inner, this._apiKey); + _ApiKeyClient(this._inner, this._apiKey, {this.thinkingLevel}); final http.Client _inner; final String _apiKey; + final String? thinkingLevel; @override - Future send(http.BaseRequest request) { + Future send(http.BaseRequest request) async { request.headers['x-goog-api-key'] = _apiKey; + final path = request.url.path; + final isGenerateEndpoint = + path.endsWith(':generateContent') || + path.endsWith(':streamGenerateContent'); + if (thinkingLevel != null && + isGenerateEndpoint && + request is http.Request && + request.body.isNotEmpty) { + final decoded = jsonDecode(request.body); + if (decoded is Map) { + final genConfig = + (decoded['generationConfig'] as Map?) ?? + {}; + final thinkingConfig = + ((genConfig['thinkingConfig'] as Map?) ?? + {}) + ..remove('thinkingBudget') + ..['thinkingLevel'] = thinkingLevel; + genConfig['thinkingConfig'] = thinkingConfig; + decoded['generationConfig'] = genConfig; + request.body = jsonEncode(decoded); + } + } return _inner.send(request); } diff --git a/tool/generator/test/commands/base_skill_command_test.dart b/tool/generator/test/commands/base_skill_command_test.dart index c84cf4d1..4ca14f0d 100644 --- a/tool/generator/test/commands/base_skill_command_test.dart +++ b/tool/generator/test/commands/base_skill_command_test.dart @@ -18,7 +18,7 @@ class _TestSkillCommand extends BaseSkillCommand { _TestSkillCommand({required super.httpClient, super.environment}) : super(logger: Logger('_TestSkillCommand')); - int runSkillCalls = 0; + final List recordedThinkingBudgets = []; @override String get name => 'test-command'; @@ -31,10 +31,10 @@ class _TestSkillCommand extends BaseSkillCommand { SkillParams skill, GeminiService gemini, Directory outputDir, - int thinkingBudget, { + int? thinkingBudget, { Directory? configDir, }) async { - runSkillCalls++; + recordedThinkingBudgets.add(thinkingBudget); } } @@ -168,7 +168,7 @@ void main() { ..addCommand(missingKeyCommand); await runner.run(['test-command', configFile.path]); expect(logs, contains('GEMINI_API_KEY environment variable not set.')); - expect(missingKeyCommand.runSkillCalls, 0); + expect(missingKeyCommand.recordedThinkingBudgets, isEmpty); logs.clear(); await runner.run(['test-command', '--dry-run', configFile.path]); @@ -176,7 +176,7 @@ void main() { logs, isNot(contains('GEMINI_API_KEY environment variable not set.')), ); - expect(missingKeyCommand.runSkillCalls, 1); + expect(missingKeyCommand.recordedThinkingBudgets, [null]); logs.clear(); final blankKeyCommand = _TestSkillCommand( @@ -187,53 +187,161 @@ void main() { ..addCommand(blankKeyCommand); await runner.run(['test-command', configFile.path]); expect(logs, contains('GEMINI_API_KEY environment variable not set.')); - expect(blankKeyCommand.runSkillCalls, 0); + expect(blankKeyCommand.recordedThinkingBudgets, isEmpty); }, ); - test('logs severe error when --thinking-budget is invalid', () async { - final configFile = File(p.join(tempDir.path, 'config.yaml')); - await configFile.writeAsString( - jsonEncode(>[ - { - 'name': 'existent-skill', - 'description': 'desc', - 'resources': [], - }, - ]), - ); - - runner = CommandRunner('skills', 'Test runner') - ..addCommand( - _TestSkillCommand( - httpClient: mockClient, - environment: {'GEMINI_API_KEY': 'test-key'}, - ), - ); - - await runner.run([ - 'test-command', - configFile.path, - '--thinking-budget', - '-1', - ]); - expect( - records.any( - (r) => - r.level == Level.SEVERE && - r.message.contains('Invalid thinking-budget: -1. Skipping.'), - ), - isTrue, - ); - }); - - test('defines model option defaulting to GeminiService.defaultModel', () { + test('defines model and thinking-level options with expected defaults', () { final command = _TestSkillCommand(httpClient: mockClient); expect(command.argParser.options.containsKey('model'), isTrue); expect( command.argParser.options['model']!.defaultsTo, GeminiService.defaultModel, ); + for (final knownModel in GeminiService.knownModels) { + expect(command.argParser.options['model']!.help, contains(knownModel)); + } + expect(command.argParser.options.containsKey('thinking-level'), isTrue); + expect( + command.argParser.options['thinking-level']!.allowed, + GeminiService.supportedThinkingLevels, + ); + expect(command.argParser.options['thinking-budget']!.defaultsTo, isNull); }); + + test( + 'throws UsageException when both --thinking-level and --thinking-budget are passed', + () async { + final configFile = File(p.join(tempDir.path, 'config.yaml')); + await configFile.writeAsString( + jsonEncode(>[ + { + 'name': 'existent-skill', + 'description': 'desc', + 'resources': [], + }, + ]), + ); + + runner = CommandRunner('skills', 'Test runner') + ..addCommand( + _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': 'test-key'}, + ), + ); + + expect( + () => runner.run([ + 'test-command', + configFile.path, + '--thinking-level', + 'high', + '--thinking-budget', + '4096', + ]), + throwsA(isA()), + ); + }, + ); + + test( + 'logs severe error on invalid model, thinking-level, or thinking-budget combinations', + () async { + final configFile = File(p.join(tempDir.path, 'config.yaml')); + await configFile.writeAsString( + jsonEncode(>[ + { + 'name': 'existent-skill', + 'description': 'desc', + 'resources': [], + }, + ]), + ); + + final command = _TestSkillCommand( + httpClient: mockClient, + environment: {'GEMINI_API_KEY': 'test-key'}, + ); + runner = CommandRunner('skills', 'Test runner') + ..addCommand(command); + + await runner.run(['test-command', configFile.path, '--model', '']); + expect( + logs, + contains(contains('Invalid model or thinking configuration')), + ); + + records.clear(); + await runner.run([ + 'test-command', + configFile.path, + '--model', + 'gemini-4-carbon', + '--thinking-level', + 'xhigh', + ]); + expect( + records.any( + (r) => + r.level == Level.SEVERE && + r.message.contains('Invalid model or thinking configuration'), + ), + isTrue, + ); + + records.clear(); + await runner.run([ + 'test-command', + configFile.path, + '--model', + 'gemini-4-carbon', + '--thinking-budget', + '0', + ]); + expect( + records.any( + (r) => + r.level == Level.SEVERE && + r.message.contains('Invalid model or thinking configuration'), + ), + isTrue, + ); + + records.clear(); + await runner.run([ + 'test-command', + configFile.path, + '--thinking-budget', + '-2', + ]); + expect( + records.any( + (r) => + r.level == Level.SEVERE && + r.message.contains('Invalid thinking-budget: -2. Skipping.'), + ), + isTrue, + ); + + await runner.run([ + 'test-command', + configFile.path, + '--model', + 'gemini-2.5-flash', + '--thinking-budget', + '-1', + ]); + await runner.run([ + 'test-command', + configFile.path, + '--model', + 'gemini-2.5-flash', + '--thinking-budget', + '0', + ]); + expect(command.recordedThinkingBudgets, [-1, 0]); + }, + ); }); } diff --git a/tool/generator/test/generate_skills_test.dart b/tool/generator/test/generate_skills_test.dart index 65216a73..ca4ade55 100644 --- a/tool/generator/test/generate_skills_test.dart +++ b/tool/generator/test/generate_skills_test.dart @@ -246,7 +246,7 @@ void main() { logs, contains( contains( - 'Model: models/gemini-4-argon, Max Output Tokens: 65536, Thinking Budget: 4000', + 'Model: models/gemini-4-carbon, Max Output Tokens: 65536, Thinking Budget: 4000', ), ), ); @@ -260,6 +260,83 @@ void main() { ); }); + test('accepts --thinking-level option', () async { + final skillsDir = Directory(p.join(tempDir.path, 'skills_output_level')); + await skillsDir.create(); + + final configFile = File(p.join(tempDir.path, 'config_level.yaml')); + final inputData = [ + { + 'name': 'level_test', + 'description': 'Thinking level test description', + 'resources': ['https://example.com/level'], + }, + ]; + configFile.writeAsStringSync(jsonEncode(inputData)); + + final logs = []; + final sub = Logger.root.onRecord.listen((record) { + logs.add(record.message); + }); + addTearDown(sub.cancel); + + late Map capturedBody; + final mockClient = MockClient((request) async { + final url = request.url.toString(); + if (url == 'https://example.com/level') { + return http.Response('Level Content', 200); + } + if (url.contains('generativelanguage')) { + capturedBody = jsonDecode(request.body) as Map; + return http.Response( + jsonEncode({ + 'candidates': [ + { + 'content': { + 'parts': [ + {'text': 'Generated Level Content'}, + ], + }, + }, + ], + }), + 200, + ); + } + return http.Response('Error', 500); + }); + + final command = GenerateSkillCommand( + environment: {'GEMINI_API_KEY': 'test-key'}, + httpClient: mockClient, + outputDir: skillsDir, + ); + runner.addCommand(command); + + await runner.run([ + 'generate-skill', + configFile.path, + '--directory', + skillsDir.path, + '--thinking-level', + 'high', + ]); + + expect( + logs, + contains( + contains( + 'Model: models/gemini-4-carbon, Max Output Tokens: 65536, Thinking Level: high', + ), + ), + ); + final genConfig = + capturedBody['generationConfig'] as Map; + final thinkingConfig = + genConfig['thinkingConfig'] as Map; + expect(thinkingConfig['thinkingLevel'], equals('HIGH')); + }); + test('accepts custom --model option', () async { final skillsDir = Directory(p.join(tempDir.path, 'skills_output_model')); await skillsDir.create(); diff --git a/tool/generator/test/services/gemini_service_test.dart b/tool/generator/test/services/gemini_service_test.dart index 6a4daa80..d6dd0631 100644 --- a/tool/generator/test/services/gemini_service_test.dart +++ b/tool/generator/test/services/gemini_service_test.dart @@ -647,12 +647,198 @@ Body content. }); }); - group('Gemini 4 request parameters', () { + group('model constants, normalization, and thinking compatibility', () { + test('exposes expected Gemini 4 model constants and Carbon default', () { + expect(GeminiService.gemini4CarbonModel, 'models/gemini-4-carbon'); + expect(GeminiService.gemini4NeonModel, 'models/gemini-4-neon'); + expect(GeminiService.gemini4ArgonModel, 'models/gemini-4-argon'); + expect(GeminiService.gemini4HydrogenModel, 'models/gemini-4-hydrogen'); + expect(GeminiService.defaultModel, GeminiService.gemini4CarbonModel); + expect(GeminiService.knownModels, [ + GeminiService.gemini4CarbonModel, + GeminiService.gemini4NeonModel, + GeminiService.gemini4ArgonModel, + GeminiService.gemini4HydrogenModel, + ]); + expect(GeminiService.supportedThinkingLevels, [ + 'minimal', + 'low', + 'medium', + 'high', + 'xhigh', + ]); + }); + + test('normalizeModelName prepends models/ and rejects empty slugs', () { + expect( + GeminiService.normalizeModelName('gemini-4-carbon'), + 'models/gemini-4-carbon', + ); + expect( + GeminiService.normalizeModelName(' gemini-4-neon '), + 'models/gemini-4-neon', + ); + expect( + GeminiService.normalizeModelName('models/gemini-4-argon'), + 'models/gemini-4-argon', + ); + expect( + GeminiService.normalizeModelName('tunedModels/custom-123'), + 'tunedModels/custom-123', + ); + expect( + () => GeminiService.normalizeModelName(''), + throwsFormatException, + ); + expect( + () => GeminiService.normalizeModelName(' '), + throwsFormatException, + ); + expect( + () => GeminiService.normalizeModelName('models/'), + throwsFormatException, + ); + expect( + () => GeminiService.normalizeModelName('tunedModels/ '), + throwsFormatException, + ); + }); + + test('validates model-specific thinkingLevel compatibility', () { + final noopClient = MockClient((_) async => http.Response('', 500)); + + // xhigh is valid on Neon and Hydrogen, rejected on Carbon, Argon, Gemini 3. + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: GeminiService.gemini4NeonModel, + thinkingLevel: 'xhigh', + ), + returnsNormally, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: GeminiService.gemini4HydrogenModel, + thinkingLevel: 'xhigh', + ), + returnsNormally, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: GeminiService.gemini4CarbonModel, + thinkingLevel: 'xhigh', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: GeminiService.gemini4ArgonModel, + thinkingLevel: 'xhigh', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-3.5-flash-lite', + thinkingLevel: 'xhigh', + ), + throwsFormatException, + ); + + // minimal is valid on Gemini 3.5 Flash-Lite, rejected on Gemini 4, 3.8 Flash, and 3 Pro. + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-3.5-flash-lite', + thinkingLevel: 'minimal', + ), + returnsNormally, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: GeminiService.gemini4CarbonModel, + thinkingLevel: 'minimal', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-3.8-flash', + thinkingLevel: 'minimal', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-3.1-pro-preview', + thinkingLevel: 'minimal', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-3-pro-preview', + thinkingLevel: 'medium', + ), + throwsFormatException, + ); + + // Rejects thinkingLevel on legacy 1.x / 2.x and tunedModels. + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'gemini-2.5-pro', + thinkingLevel: 'medium', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + model: 'tunedModels/custom-123', + thinkingLevel: 'high', + ), + throwsFormatException, + ); + expect( + () => GeminiService( + apiKey: 'k', + httpClient: noopClient, + thinkingLevel: 'ultra', + ), + throwsFormatException, + ); + }); + }); + + group('Gemini 3, Gemini 4, and legacy request parameters', () { test( - 'omits temperature for models starting with models/gemini-4', + 'omits temperature and thinkingBudget by default for Gemini 4 Carbon', () async { + late Uri capturedUrl; late Map capturedBody; final mockClient = MockClient((request) async { + capturedUrl = request.url; capturedBody = jsonDecode(request.body) as Map; return http.Response( jsonEncode({ @@ -673,19 +859,85 @@ Body content. final gemini = GeminiService( apiKey: 'test-key', httpClient: mockClient, - model: 'models/gemini-4-argon', ); await gemini.generateSkillContent('raw', 'name', 'desc'); + expect( + capturedUrl.path, + '/v1beta/models/gemini-4-carbon:generateContent', + ); final genConfig = capturedBody['generationConfig'] as Map; expect(genConfig.containsKey('temperature'), isFalse); + final thinkingConfig = + genConfig['thinkingConfig'] as Map; + expect(thinkingConfig['includeThoughts'], isTrue); + expect(thinkingConfig.containsKey('thinkingBudget'), isFalse); + }, + ); + + test( + 'normalizes bare gemini-4 model IDs and omits temperature for Gemini 3 and 4', + () async { + late Uri capturedUrl; + late Map capturedBody; + final mockClient = MockClient((request) async { + capturedUrl = request.url; + capturedBody = jsonDecode(request.body) as Map; + return http.Response( + jsonEncode({ + 'candidates': [ + { + 'content': { + 'parts': [ + {'text': 'Generated content'}, + ], + }, + }, + ], + }), + 200, + ); + }); + + final neonService = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + model: 'gemini-4-neon', + ); + final result = await neonService.generateSkillContent( + 'raw', + 'name', + 'desc', + ); + expect( + capturedUrl.path, + '/v1beta/models/gemini-4-neon:generateContent', + ); + expect(result, contains('model: models/gemini-4-neon')); + expect( + (capturedBody['generationConfig'] as Map) + .containsKey('temperature'), + isFalse, + ); + + final gemini3Service = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + model: 'models/gemini-3.1-pro-preview', + ); + await gemini3Service.generateSkillContent('raw', 'name', 'desc'); + expect( + (capturedBody['generationConfig'] as Map) + .containsKey('temperature'), + isFalse, + ); }, ); test( - 'omits temperature for models starting with gemini-4 without prefix', + 'injects thinkingLevel and omits thinkingBudget when thinkingLevel is specified', () async { late Map capturedBody; final mockClient = MockClient((request) async { @@ -709,49 +961,143 @@ Body content. final gemini = GeminiService( apiKey: 'test-key', httpClient: mockClient, - model: 'gemini-4-argon', + model: GeminiService.gemini4NeonModel, + thinkingLevel: 'xhigh', ); - await gemini.generateSkillContent('raw', 'name', 'desc'); + await gemini.generateSkillContent( + 'raw', + 'name', + 'desc', + thinkingBudget: 4096, + ); final genConfig = capturedBody['generationConfig'] as Map; - expect(genConfig.containsKey('temperature'), isFalse); + final thinkingConfig = + genConfig['thinkingConfig'] as Map; + expect(thinkingConfig['thinkingLevel'], equals('XHIGH')); + expect(thinkingConfig['includeThoughts'], isTrue); + expect(thinkingConfig.containsKey('thinkingBudget'), isFalse); }, ); - test('includes temperature for non-gemini-4 models', () async { - late Map capturedBody; - final mockClient = MockClient((request) async { - capturedBody = jsonDecode(request.body) as Map; - return http.Response( - jsonEncode({ - 'candidates': [ - { - 'content': { - 'parts': [ - {'text': 'Generated content'}, - ], + test( + 'handles thinkingBudget across Gemini 2.5, non-thinking legacy, and tuned models', + () async { + late Map capturedBody; + final mockClient = MockClient((request) async { + capturedBody = jsonDecode(request.body) as Map; + return http.Response( + jsonEncode({ + 'candidates': [ + { + 'content': { + 'parts': [ + {'text': 'Generated content'}, + ], + }, }, - }, - ], - }), - 200, - ); - }); - - final gemini = GeminiService( - apiKey: 'test-key', - httpClient: mockClient, - model: 'models/gemini-3.1-pro-preview', - ); + ], + }), + 200, + ); + }); - await gemini.generateSkillContent('raw', 'name', 'desc'); + // Gemini 2.5 Flash supports disabling thinking (0) and dynamic (-1). + final flash25 = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + model: 'models/gemini-2.5-flash', + ); + await flash25.generateSkillContent('raw', 'name', 'desc'); + final defaultGenConfig = + capturedBody['generationConfig'] as Map; + expect(defaultGenConfig['temperature'], equals(0.2)); + expect( + (defaultGenConfig['thinkingConfig'] + as Map)['thinkingBudget'], + equals(4096), + ); - final genConfig = - capturedBody['generationConfig'] as Map; - expect(genConfig['temperature'], equals(0.2)); - }); + await flash25.generateSkillContent( + 'raw', + 'name', + 'desc', + thinkingBudget: 0, + ); + final zeroConfig = + (capturedBody['generationConfig'] + as Map)['thinkingConfig'] + as Map; + expect(zeroConfig['includeThoughts'], isFalse); + expect(zeroConfig['thinkingBudget'], equals(0)); + + await flash25.generateSkillContent( + 'raw', + 'name', + 'desc', + thinkingBudget: -1, + ); + final dynamicConfig = + (capturedBody['generationConfig'] + as Map)['thinkingConfig'] + as Map; + expect(dynamicConfig['includeThoughts'], isTrue); + expect(dynamicConfig['thinkingBudget'], equals(-1)); + + // Gemini 4 Carbon and 2.5 Pro cannot disable thinking (0). + final carbon = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + ); + expect(() => carbon.validateThinkingBudget(0), throwsFormatException); + final pro25 = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + model: 'models/gemini-2.5-pro', + ); + expect(() => pro25.validateThinkingBudget(0), throwsFormatException); + expect(() => pro25.validateThinkingBudget(-2), throwsFormatException); + + // Non-thinking models (gemini-2.0, gemini-1.5, tunedModels) omit thinkingConfig + // by default and when thinkingBudget == 0, and reject non-zero budgets. + for (final modelId in [ + 'models/gemini-2.0-flash', + 'models/gemini-1.5-pro', + 'tunedModels/custom-123', + ]) { + final nonThinking = GeminiService( + apiKey: 'test-key', + httpClient: mockClient, + model: modelId, + ); + await nonThinking.generateSkillContent('raw', 'name', 'desc'); + expect( + (capturedBody['generationConfig'] as Map) + .containsKey('thinkingConfig'), + isFalse, + reason: 'Default request for $modelId must omit thinkingConfig', + ); + await nonThinking.generateSkillContent( + 'raw', + 'name', + 'desc', + thinkingBudget: 0, + ); + expect( + (capturedBody['generationConfig'] as Map) + .containsKey('thinkingConfig'), + isFalse, + reason: 'thinkingBudget: 0 on $modelId must omit thinkingConfig', + ); + expect( + () => nonThinking.validateThinkingBudget(4096), + throwsFormatException, + ); + } + }, + ); }); }); }