diff --git a/docs/skills.mdx b/docs/skills.mdx index 5fec95c7d..6c2b90a11 100644 --- a/docs/skills.mdx +++ b/docs/skills.mdx @@ -7,7 +7,13 @@ Think of Stac Skills as expert assistants that know Stac inside and out. They he ## Installation -Install all Stac skills with one command: +Install all Stac skills natively with the Stac CLI: + +```bash +stac skills add +``` + +Alternatively, you can install them using `npx`: ```bash npx skills add https://github.com/StacDev/stac diff --git a/packages/stac_cli/bin/stac_cli.dart b/packages/stac_cli/bin/stac_cli.dart index aabbf704c..ea89ae57a 100644 --- a/packages/stac_cli/bin/stac_cli.dart +++ b/packages/stac_cli/bin/stac_cli.dart @@ -9,6 +9,7 @@ import 'package:stac_cli/src/commands/build_command.dart'; import 'package:stac_cli/src/commands/deploy_command.dart'; import 'package:stac_cli/src/commands/init_command.dart'; import 'package:stac_cli/src/commands/project_command.dart'; +import 'package:stac_cli/src/commands/skills_command.dart'; import 'package:stac_cli/src/commands/upgrade_command.dart'; import 'package:stac_cli/src/config/env.dart'; import 'package:stac_cli/src/exceptions/stac_exception.dart'; @@ -67,6 +68,7 @@ void main(List arguments) async { ..addCommand(ProjectCommand()) ..addCommand(BuildCommand()) ..addCommand(DeployCommand()) + ..addCommand(SkillsCommand()) ..addCommand(UpgradeCommand()); // Add global flags diff --git a/packages/stac_cli/lib/src/commands/init_command.dart b/packages/stac_cli/lib/src/commands/init_command.dart index 3b40a19e6..8a17a1135 100644 --- a/packages/stac_cli/lib/src/commands/init_command.dart +++ b/packages/stac_cli/lib/src/commands/init_command.dart @@ -8,6 +8,7 @@ import '../services/project_service.dart'; import '../utils/console_logger.dart'; import '../utils/file_utils.dart'; import 'base_command.dart'; +import 'skills/add_command.dart'; /// Command for initializing a Stac project from cloud projects class InitCommand extends BaseCommand { @@ -84,6 +85,24 @@ class InitCommand extends BaseCommand { // Create default_stac_options.dart configuration file await _createStacConfigFile(targetDir, project); + // Ask to install skills + final shouldInstallSkills = Confirm( + prompt: 'Install Stac agent skills? (Recommended for AI-assisted development)', + defaultValue: true, + ).interact(); + if (shouldInstallSkills) { + ConsoleLogger.info('Installing skills...'); + final skillsExitCode = await AddCommand( + targetDirectory: targetDir, + ).execute(); + if (skillsExitCode != 0) { + ConsoleLogger.warning( + 'Skills installation encountered an issue. ' + 'You can retry later with: stac skills add', + ); + } + } + ConsoleLogger.success('✓ Project initialized successfully!'); ConsoleLogger.info('Next steps:'); ConsoleLogger.info(' 1. Add your Stac widgets definitions to /stac'); diff --git a/packages/stac_cli/lib/src/commands/skills/add_command.dart b/packages/stac_cli/lib/src/commands/skills/add_command.dart new file mode 100644 index 000000000..fe899b7b2 --- /dev/null +++ b/packages/stac_cli/lib/src/commands/skills/add_command.dart @@ -0,0 +1,249 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive_io.dart'; +import 'package:dio/dio.dart'; +import 'package:path/path.dart' as path; + +import '../../utils/console_logger.dart'; +import '../base_command.dart'; + +/// Command to add Stac AI agent skills +class AddCommand extends BaseCommand { + @override + String get name => 'add'; + + @override + String get description => 'Add Stac AI agent skills to your project'; + + @override + bool get requiresAuth => false; + + /// Optional target directory; defaults to [Directory.current]. + final String? targetDirectory; + + AddCommand({this.targetDirectory}); + + @override + Future execute() async { + String repoUrl = 'https://github.com/StacDev/stac'; + + if (argResults?.rest.isNotEmpty == true) { + repoUrl = argResults!.rest.first; + } + + if (!repoUrl.contains('github.com')) { + ConsoleLogger.error('Currently only github.com URLs are supported.'); + return 1; + } + + // Extract owner/repo + final uri = Uri.parse(repoUrl); + final segments = uri.pathSegments; + if (segments.length < 2) { + ConsoleLogger.error('Invalid GitHub URL format.'); + return 1; + } + + final owner = segments[0]; + final repo = segments[1].replaceAll('.git', ''); + + final zipUrl = 'https://github.com/$owner/$repo/archive/HEAD.zip'; + + ConsoleLogger.info('Fetching skills from $repoUrl...'); + + final tempDir = await Directory.systemTemp.createTemp('stac_skills_'); + try { + final dio = Dio(); + final zipFile = File(path.join(tempDir.path, 'repo.zip')); + + await dio.download(zipUrl, zipFile.path); + + // Extract ZIP + final archive = ZipDecoder().decodeBytes(zipFile.readAsBytesSync()); + final extractDir = Directory(path.join(tempDir.path, 'extracted')); + extractArchiveToDisk(archive, extractDir.path); + + // Find skills/catalog.json + // The extracted folder usually has a root folder named - + final rootDirs = extractDir.listSync().whereType().toList(); + if (rootDirs.isEmpty) { + ConsoleLogger.error('Empty repository archive.'); + return 1; + } + + final repoRoot = rootDirs.first; + ConsoleLogger.info('Extracted root: ${repoRoot.path}'); + + final catalogFile = File( + path.join(repoRoot.path, 'skills', 'catalog.json'), + ); + ConsoleLogger.info('Looking for catalog at: ${catalogFile.path}'); + + if (!await catalogFile.exists()) { + ConsoleLogger.error('skills/catalog.json not found in repository.'); + + ConsoleLogger.info('Contents of extracted:'); + for (var e in extractDir.listSync(recursive: true)) { + ConsoleLogger.info(e.path); + } + + return 1; + } + + // Parse catalog.json + final catalogContent = await catalogFile.readAsString(); + final List catalog = jsonDecode(catalogContent); + + final installDir = targetDirectory ?? Directory.current.path; + final targetAgentsDir = Directory( + path.join(installDir, '.agents', 'skills'), + ); + if (!await targetAgentsDir.exists()) { + await targetAgentsDir.create(recursive: true); + } + + // Canonical boundary paths for security checks + final repoRootCanonical = path.canonicalize(repoRoot.path); + final targetCanonical = path.canonicalize(targetAgentsDir.path); + + int installedCount = 0; + for (final skill in catalog) { + if (skill is! Map) { + ConsoleLogger.warning('Skipping invalid catalog entry (not a map): $skill'); + continue; + } + final skillName = skill['name']; + final skillPath = skill['path']; + + if (skillName is! String || skillPath is! String) { + ConsoleLogger.warning('Skipping invalid catalog entry: $skill'); + continue; + } + + // Guard against path-traversal in catalog entries + if (containsPathTraversal(skillName) || + containsPathTraversal(skillPath)) { + ConsoleLogger.warning( + 'Skipping skill with suspicious name/path: $skillName / $skillPath', + ); + continue; + } + + final sourceSkillDir = Directory( + path.join(repoRoot.path, skillPath), + ); + + // Ensure the resolved source is still inside the repo root + final sourceCanonical = path.canonicalize(sourceSkillDir.path); + if (!path.equals(repoRootCanonical, sourceCanonical) && + !path.isWithin(repoRootCanonical, sourceCanonical)) { + ConsoleLogger.warning( + 'Skill path $skillPath escapes repo root. Skipping.', + ); + continue; + } + + if (!await sourceSkillDir.exists()) { + ConsoleLogger.warning( + 'Skill directory $skillPath not found, skipping.', + ); + continue; + } + + final targetSkillDir = Directory( + path.join(targetAgentsDir.path, skillName), + ); + + // Ensure the resolved target is still inside .agents/skills + final targetSkillCanonical = path.canonicalize(targetSkillDir.path); + if (!path.equals(targetCanonical, targetSkillCanonical) && + !path.isWithin(targetCanonical, targetSkillCanonical)) { + ConsoleLogger.warning( + 'Skill name $skillName escapes target directory. Skipping.', + ); + continue; + } + + if (await targetSkillDir.exists()) { + await targetSkillDir.delete(recursive: true); + } + await targetSkillDir.create(recursive: true); + + // Copy directory contents + await _copyDirectory( + sourceSkillDir, + targetSkillDir, + sourceCanonical, + targetSkillCanonical, + ); + ConsoleLogger.success('✓ $skillName (copied)'); + installedCount++; + } + + ConsoleLogger.success( + 'Installed $installedCount skills to .agents/skills', + ); + return 0; + } catch (e) { + ConsoleLogger.error('Failed to install skills: $e'); + return 1; + } finally { + // Always clean up temp files regardless of success or failure + if (await tempDir.exists()) { + await tempDir.delete(recursive: true); + } + } + } + + /// Returns true if a name or path segment contains traversal patterns. + bool containsPathTraversal(String value) { + return value.contains('..') || + path.isAbsolute(value) || + value.contains(r'\'); + } + + Future _copyDirectory( + Directory source, + Directory destination, + String sourceRootCanonical, + String destinationRootCanonical, + ) async { + await for (var entity in source.list(recursive: false, followLinks: false)) { + if (entity is Link) { + ConsoleLogger.warning('Skipping symlink: ${entity.path}'); + continue; + } + + final entityCanonical = path.canonicalize(entity.path); + // Ensure the source entity is within the allowed source root + if (!path.equals(sourceRootCanonical, entityCanonical) && + !path.isWithin(sourceRootCanonical, entityCanonical)) { + ConsoleLogger.warning('Skipping out-of-bounds source entity: ${entity.path}'); + continue; + } + + final targetPath = path.join(destination.path, path.basename(entity.path)); + final targetCanonical = path.canonicalize(targetPath); + // Ensure the destination path is within the allowed target root + if (!path.equals(destinationRootCanonical, targetCanonical) && + !path.isWithin(destinationRootCanonical, targetCanonical)) { + ConsoleLogger.warning('Skipping out-of-bounds destination path: $targetPath'); + continue; + } + + if (entity is Directory) { + final newDirectory = Directory(targetPath); + await newDirectory.create(recursive: true); + await _copyDirectory( + entity, + newDirectory, + sourceRootCanonical, + destinationRootCanonical, + ); + } else if (entity is File) { + await entity.copy(targetPath); + } + } + } +} diff --git a/packages/stac_cli/lib/src/commands/skills_command.dart b/packages/stac_cli/lib/src/commands/skills_command.dart new file mode 100644 index 000000000..caabefbfa --- /dev/null +++ b/packages/stac_cli/lib/src/commands/skills_command.dart @@ -0,0 +1,15 @@ +import 'package:args/command_runner.dart'; +import 'skills/add_command.dart'; + +/// Command for managing Stac AI agent skills +class SkillsCommand extends Command { + @override + String get name => 'skills'; + + @override + String get description => 'Manage Stac AI agent skills'; + + SkillsCommand() { + addSubcommand(AddCommand()); + } +} diff --git a/packages/stac_cli/pubspec.lock b/packages/stac_cli/pubspec.lock index 4fe9fd6bf..a4d3c1c47 100644 --- a/packages/stac_cli/pubspec.lock +++ b/packages/stac_cli/pubspec.lock @@ -17,6 +17,14 @@ packages: url: "https://pub.dev" source: hosted version: "10.0.1" + archive: + dependency: "direct main" + description: + name: archive + sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff + url: "https://pub.dev" + source: hosted + version: "4.0.9" args: dependency: "direct main" description: @@ -101,10 +109,10 @@ packages: dependency: transitive description: name: characters - sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 url: "https://pub.dev" source: hosted - version: "1.4.1" + version: "1.4.0" checked_yaml: dependency: transitive description: @@ -241,6 +249,11 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.1" + flutter: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" frontend_server_client: dependency: transitive description: @@ -353,6 +366,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" meta: dependency: transitive description: @@ -401,6 +422,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.2" + posix: + dependency: transitive + description: + name: posix + sha256: "185ef7606574f789b40f289c233efa52e96dead518aed988e040a10737febb07" + url: "https://pub.dev" + source: hosted + version: "6.5.0" pub_semver: dependency: transitive description: @@ -449,6 +478,11 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" source_gen: dependency: transitive description: @@ -492,16 +526,18 @@ packages: stac_core: dependency: "direct main" description: - path: "../stac_core" - relative: true - source: path + name: stac_core + sha256: "855767538be98fb2021ee4d58a85af66e0f40c6317eab94e5a08654c09ce49c0" + url: "https://pub.dev" + source: hosted version: "1.5.0" stac_logger: - dependency: "direct overridden" + dependency: transitive description: - path: "../stac_logger" - relative: true - source: path + name: stac_logger + sha256: bc3c1cc486d59d2378c1e18bfd9bfa078be564b58d4ae2b3898633c05a02df26 + url: "https://pub.dev" + source: hosted version: "1.1.0" stack_trace: dependency: transitive @@ -583,6 +619,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" vm_service: dependency: transitive description: @@ -649,3 +693,4 @@ packages: version: "3.1.3" sdks: dart: ">=3.10.0 <4.0.0" + flutter: ">=1.17.0" diff --git a/packages/stac_cli/pubspec.yaml b/packages/stac_cli/pubspec.yaml index 89c523dde..1e17fb04a 100644 --- a/packages/stac_cli/pubspec.yaml +++ b/packages/stac_cli/pubspec.yaml @@ -18,6 +18,7 @@ dependencies: json_annotation: ^4.11.0 dotenv: ^4.2.0 cryptography: ^2.9.0 + archive: ^4.0.9 # Executables that can be run globally executables: diff --git a/packages/stac_cli/test/commands/cli_commands_test.dart b/packages/stac_cli/test/commands/cli_commands_test.dart new file mode 100644 index 000000000..b410d1d11 --- /dev/null +++ b/packages/stac_cli/test/commands/cli_commands_test.dart @@ -0,0 +1,141 @@ +import 'dart:io'; +import 'package:test/test.dart'; +import 'package:args/command_runner.dart'; +import 'package:path/path.dart' as path; +import 'package:stac_cli/src/commands/build_command.dart'; +import 'package:stac_cli/src/commands/init_command.dart'; +import 'package:stac_cli/src/commands/deploy_command.dart'; +import 'package:stac_cli/src/commands/skills_command.dart'; +import 'package:stac_cli/src/commands/skills/add_command.dart'; +import 'package:stac_cli/src/config/env.dart'; + +/// Test suite for verifying core Stac CLI commands. +void main() { + group('CLI Commands', () { + late CommandRunner runner; + + setUp(() { + // Initialize environment with mock values to satisfy required checks in services. + // This allows testing command configuration without needing real API keys. + configureEnvironment({ + 'STAC_BASE_API_URL': 'https://api.test.stac.dev', + 'STAC_GOOGLE_CLIENT_ID': 'test-client-id', + 'STAC_FIREBASE_API_KEY': 'test-api-key', + }); + + runner = CommandRunner('stac', 'Stac CLI test runner'); + runner.addCommand(BuildCommand()); + runner.addCommand(InitCommand()); + runner.addCommand(DeployCommand()); + runner.addCommand(SkillsCommand()); + }); + + tearDown(() { + configureEnvironment({}); + }); + + test('build command has correct name and description', () { + final command = runner.commands['build']; + expect(command, isNotNull, reason: 'BuildCommand should be registered'); + expect(command!.name, equals('build')); + expect(command.description, isNotEmpty); + }); + + test('init command has correct name and description', () { + final command = runner.commands['init']; + expect(command, isNotNull, reason: 'InitCommand should be registered'); + expect(command!.name, equals('init')); + expect(command.description, isNotEmpty); + }); + + test('deploy command has correct name and description', () { + final command = runner.commands['deploy']; + expect(command, isNotNull, reason: 'DeployCommand should be registered'); + expect(command!.name, equals('deploy')); + expect(command.description, isNotEmpty); + }); + + test('skills command has correct name and description', () { + final command = runner.commands['skills']; + expect(command, isNotNull, reason: 'SkillsCommand should be registered'); + expect(command!.name, equals('skills')); + expect(command.description, isNotEmpty); + }); + + test('skills add subcommand is registered', () { + final command = runner.commands['skills']; + expect(command, isNotNull, reason: 'SkillsCommand should be registered'); + expect(command, isA(), + reason: 'skills command should be a SkillsCommand'); + final skillsCommand = command as SkillsCommand; + expect(skillsCommand.subcommands['add'], isNotNull, + reason: 'AddCommand should be registered as a subcommand of skills'); + expect(skillsCommand.subcommands['add']!.name, equals('add')); + expect(skillsCommand.subcommands['add']!.description, isNotEmpty); + }); + }); + + group('AddCommand', () { + late CommandRunner runner; + + setUp(() { + runner = CommandRunner('stac', 'Stac CLI test runner') + ..addCommand(SkillsCommand()); + }); + + test('has correct name and description', () { + final cmd = AddCommand(); + expect(cmd.name, equals('add')); + expect(cmd.description, isNotEmpty); + }); + + test('does not require auth', () { + final cmd = AddCommand(); + expect(cmd.requiresAuth, isFalse); + }); + + test('path traversal check detects unsafe paths', () { + final cmd = TestAddCommand(); + expect(cmd.testContainsPathTraversal('safe-skill-name'), isFalse); + expect(cmd.testContainsPathTraversal('../unsafe'), isTrue); + expect(cmd.testContainsPathTraversal('/absolute/path'), isTrue); + expect(cmd.testContainsPathTraversal(r'unsafe\backslash'), isTrue); + expect(cmd.testContainsPathTraversal('..'), isTrue); + }); + + test('temp directory is cleaned up in finally block when execution fails/throws', () async { + // Get initial set of stac_skills_ temp directories + final beforeDirs = Directory.systemTemp + .listSync() + .where((entity) => + entity is Directory && + path.basename(entity.path).startsWith('stac_skills_')) + .map((entity) => entity.path) + .toSet(); + + // We run the command via the runner with a valid-looking but nonexistent GitHub URL so it fails/throws during download + final exitCode = await runner.run([ + 'skills', + 'add', + 'https://github.com/nonexistent-stac-owner/nonexistent-stac-repo' + ]); + expect(exitCode, equals(1)); + + // Get final set of stac_skills_ temp directories + final afterDirs = Directory.systemTemp + .listSync() + .where((entity) => + entity is Directory && + path.basename(entity.path).startsWith('stac_skills_')) + .map((entity) => entity.path) + .toSet(); + + // The temporary directories list should be clean (meaning the created directory was deleted in finally) + expect(afterDirs, equals(beforeDirs)); + }); + }); +} + +class TestAddCommand extends AddCommand { + bool testContainsPathTraversal(String value) => containsPathTraversal(value); +} diff --git a/packages/stac_cli/test/utils/file_utils_test.dart b/packages/stac_cli/test/utils/file_utils_test.dart new file mode 100644 index 000000000..b7d005e2b --- /dev/null +++ b/packages/stac_cli/test/utils/file_utils_test.dart @@ -0,0 +1,70 @@ +import 'dart:io'; +import 'package:test/test.dart'; +import 'package:stac_cli/src/utils/file_utils.dart'; +import 'package:path/path.dart' as path; + +/// Test suite for Stac CLI file utility operations. +void main() { + group('FileUtils', () { + // Basic verification of environment-dependent directory getters. + test('homeDirectory returns a non-empty string on this OS and points to an existing directory', () async { + final home = FileUtils.homeDirectory; + expect(home, isNotEmpty); + final dir = Directory(home); + expect(await dir.exists(), isTrue, reason: 'Home directory must exist'); + final stat = await dir.stat(); + expect(stat.type, equals(FileSystemEntityType.directory), reason: 'Home directory path must be a directory'); + }); + + test('configDirectory path is generated and points to a valid directory', () async { + final config = FileUtils.configDirectory; + expect(config, isNotEmpty); + + final dir = Directory(config); + final originallyExisted = await dir.exists(); + + // Ensure config directory exists (creating it if necessary) + await FileUtils.ensureConfigDirectory(); + + expect(await dir.exists(), isTrue, reason: 'Config directory must exist after ensuring'); + final stat = await dir.stat(); + expect(stat.type, equals(FileSystemEntityType.directory), reason: 'Config directory path must be a directory'); + + // Clean up the created config directory if it didn't exist before the test + if (!originallyExisted && await dir.exists()) { + try { + await dir.delete(recursive: true); + } catch (_) {} + } + }); + + // Integrated test for file system operations using a temporary directory. + test('integrated file operations: create, read, and delete', () async { + // Setup a clean temporary sandbox for this test. + final tempDir = Directory.systemTemp.createTempSync('stac_cli_test'); + final filePath = path.join(tempDir.path, 'test_file.txt'); + + try { + // 1. Initial State: file should not exist. + expect(await FileUtils.fileExists(filePath), isFalse); + + // 2. Write Operation: create file with content. + await FileUtils.writeFile(filePath, 'hello world'); + expect(await FileUtils.fileExists(filePath), isTrue); + + // 3. Read Operation: verify content matches. + final content = await FileUtils.readFile(filePath); + expect(content, equals('hello world')); + + // 4. Delete Operation: cleanup file. + await FileUtils.deleteFile(filePath); + expect(await FileUtils.fileExists(filePath), isFalse); + } finally { + // Always cleanup the temporary directory logic even if tests fail. + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + } + }); + }); +}