Skip to content
Open
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
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
38 changes: 26 additions & 12 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 Down Expand Up @@ -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,
Expand All @@ -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<void> runSkill(
SkillParams skill,
Expand Down
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
19 changes: 8 additions & 11 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,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<void> runSkill(
Expand Down Expand Up @@ -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
26 changes: 14 additions & 12 deletions tool/generator/lib/src/commands/update_readme_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -65,11 +76,7 @@ class UpdateReadmeCommand extends BaseYamlCommand {

// Parse existing example prompts from the README if they exist
final existingPrompts = <String, String>{};
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) {
Expand Down Expand Up @@ -112,20 +119,15 @@ 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) {
// Find the end of the line with the header
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,
);

Expand Down
23 changes: 10 additions & 13 deletions tool/generator/lib/src/commands/update_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 update skills from a configuration file, preserving existing content.
Expand Down Expand Up @@ -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;
}
Expand All @@ -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(
Expand All @@ -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}');
}
Expand Down
Loading
Loading