Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions tool/generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
21 changes: 14 additions & 7 deletions tool/generator/bin/skills.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -14,11 +15,14 @@ import 'package:skills/src/commands/validate_skill_command.dart';

const String version = '0.1.0';

void main(List<String> arguments) async {
Future<void> main(List<String> arguments) async {
final httpClient = http.Client();

final runner =
CommandRunner<void>('skills', 'A sample command-line application.')
CommandRunner<void>(
'skills',
'CLI tool for generating, updating, and validating Agent Skills.',
)
..addCommand(GenerateSkillCommand(httpClient: httpClient))
..addCommand(UpdateSkillCommand(httpClient: httpClient))
..addCommand(ValidateSkillCommand(httpClient: httpClient))
Expand All @@ -36,14 +40,15 @@ void main(List<String> arguments) async {
help: 'Show additional command output.',
);

StreamSubscription<LogRecord>? logSubscription;
try {
final results = runner.parse(arguments);
if (results.flag('version')) {
stdout.writeln('skills version: $version');
return;
}

_configureLogging(results.flag('verbose'));
logSubscription = _configureLogging(results.flag('verbose'));

if (results.flag('verbose')) {
Logger.root.fine('All arguments: ${results.arguments}');
Expand All @@ -52,20 +57,22 @@ void main(List<String> 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<LogRecord> _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);
}
Expand Down
80 changes: 63 additions & 17 deletions tool/generator/lib/src/commands/base_skill_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -23,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',
Expand All @@ -53,26 +66,45 @@ 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 model = argResults?['model'] as String?;
final gemini = GeminiService(
apiKey: apiKey,
httpClient: httpClient,
model: model,
);
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;
}

int thinkingBudget;
final model = argResults?['model'] as String?;
final thinkingLevel = argResults?['thinking-level'] as String?;
final GeminiService gemini;
try {
thinkingBudget = int.parse(argResults!['thinking-budget'] as String);
} on FormatException {
logger.warning(
'Invalid thinking-budget: ${argResults!['thinking-budget']}. Skipping.',
);
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;
}

Expand All @@ -87,12 +119,26 @@ 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<void> runSkill(
SkillParams skill,
GeminiService gemini,
Directory outputDir,
int thinkingBudget, {
int? thinkingBudget, {
Directory? configDir,
});
}
50 changes: 41 additions & 9 deletions tool/generator/lib/src/commands/base_yaml_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -43,14 +44,38 @@ abstract class BaseYamlCommand extends Command<void> {
}

final yamlContent = file.readAsStringSync();
final yamlList = loadYaml(yamlContent) as YamlList;
final skills = yamlList
.map(
(e) => SkillParams.fromJson(
jsonDecode(jsonEncode(e)) as Map<String, dynamic>,
),
)
.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 = <SkillParams>[];
for (var i = 0; i < yamlList.length; i++) {
final item = yamlList[i];
if (item is! Map<Object?, Object?>) {
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
Expand All @@ -74,6 +99,13 @@ abstract class BaseYamlCommand extends Command<void> {
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<void> runWithSkills(
List<SkillParams> skills,
Expand Down
21 changes: 9 additions & 12 deletions tool/generator/lib/src/commands/generate_skill_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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.
Expand All @@ -26,14 +26,14 @@ 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<void> runSkill(
SkillParams skill,
GeminiService gemini,
Directory outputDir,
int thinkingBudget, {
int? thinkingBudget, {
Directory? configDir,
}) async {
logger.info('Generating skill: ${skill.name}...');
Expand All @@ -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(
Expand Down Expand Up @@ -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}');
}
Expand Down
Loading
Loading