scripts/init_skill.py
scripts/init_skill.pyBrowse 3 files
2,928 tokens
13,193 bytes
Token encoding: o200k_base
Snapshot 229ffef
← Back to SKILL.md
1#!/usr/bin/env python32"""Skill Initializer - Creates a new skill from template.3 4Usage:5 init_skill.py <skill-name> --path <path>6 7Examples:8 init_skill.py my-new-skill --path skills/public9 init_skill.py my-api-helper --path skills/private10 init_skill.py custom-skill --path /custom/location11 12For deepagents CLI:13 init_skill.py my-skill --path "${DEEPAGENTS_HOME:-$HOME/.deepagents}/agent/skills"14"""15 16import sys17from pathlib import Path18 19MAX_SKILL_NAME_LENGTH = 6420 21SKILL_TEMPLATE = """---22name: {skill_name}23description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]24---25 26# {skill_title}27 28## Overview29 30[TODO: 1-2 sentences explaining what this skill enables]31 32## Structuring This Skill33 34[TODO: Choose the structure that best fits this skill's purpose. Common patterns:35 36**1. Workflow-Based** (best for sequential processes)37- Works well when there are clear step-by-step procedures38- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"39- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...40 41**2. Task-Based** (best for tool collections)42- Works well when the skill offers different operations/capabilities43- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"44- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...45 46**3. Reference/Guidelines** (best for standards or specifications)47- Works well for brand guidelines, coding standards, or requirements48- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"49- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...50 51**4. Capabilities-Based** (best for integrated systems)52- Works well when the skill provides multiple interrelated features53- Example: Product Management with "Core Capabilities" → numbered capability list54- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...55 56Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).57 58Delete this entire "Structuring This Skill" section when done - it's just guidance.]59 60## [TODO: Replace with the first main section based on chosen structure]61 62[TODO: Add content here. See examples in existing skills:63- Code samples for technical skills64- Decision trees for complex workflows65- Concrete examples with realistic user requests66- References to scripts/templates/references as needed]67 68## Resources69 70This skill includes example resource directories that demonstrate how to organize different types of bundled resources:71 72### scripts/73Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.74 75**Examples from other skills:**76- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation77- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing78 79**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.80 81**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.82 83### references/84Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.85 86**Examples from other skills:**87- Product management: `communication.md`, `context_building.md` - detailed workflow guides88- BigQuery: API reference documentation and query examples89- Finance: Schema documentation, company policies90 91**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.92 93### assets/94Files not intended to be loaded into context, but rather used within the output Claude produces.95 96**Examples from other skills:**97- Brand styling: PowerPoint template files (.pptx), logo files98- Frontend builder: HTML/React boilerplate project directories99- Typography: Font files (.ttf, .woff2)100 101**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.102 103---104 105**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.106""" # noqa: E501107 108EXAMPLE_SCRIPT = '''#!/usr/bin/env python3109"""110Example helper script for {skill_name}111 112This is a placeholder script that can be executed directly.113Replace with actual implementation or delete if not needed.114 115Example real scripts from other skills:116- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields117- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images118"""119 120def main():121 print("This is an example script for {skill_name}")122 # TODO: Add actual script logic here123 # This could be data processing, file conversion, API calls, etc.124 125if __name__ == "__main__":126 main()127'''128 129EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}130 131This is a placeholder for detailed reference documentation.132Replace with actual reference content or delete if not needed.133 134Example real reference docs from other skills:135- product-management/references/communication.md - Comprehensive guide for status updates136- product-management/references/context_building.md - Deep-dive on gathering context137- bigquery/references/ - API references and query examples138 139## When Reference Docs Are Useful140 141Reference docs are ideal for:142- Comprehensive API documentation143- Detailed workflow guides144- Complex multi-step processes145- Information too lengthy for main SKILL.md146- Content that's only needed for specific use cases147 148## Structure Suggestions149 150### API Reference Example151- Overview152- Authentication153- Endpoints with examples154- Error codes155- Rate limits156 157### Workflow Guide Example158- Prerequisites159- Step-by-step instructions160- Common patterns161- Troubleshooting162- Best practices163""" # noqa: E501164 165EXAMPLE_ASSET = """# Example Asset File166 167This placeholder represents where asset files would be stored.168Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.169 170Asset files are NOT intended to be loaded into context, but rather used within171the output Claude produces.172 173Example asset files from other skills:174- Brand guidelines: logo.png, slides_template.pptx175- Frontend builder: hello-world/ directory with HTML/React boilerplate176- Typography: custom-font.ttf, font-family.woff2177- Data: sample_data.csv, test_dataset.json178 179## Common Asset Types180 181- Templates: .pptx, .docx, boilerplate directories182- Images: .png, .jpg, .svg, .gif183- Fonts: .ttf, .otf, .woff, .woff2184- Boilerplate code: Project directories, starter files185- Icons: .ico, .svg186- Data files: .csv, .json, .xml, .yaml187 188Note: This is a text placeholder. Actual assets can be any file type.189""" # noqa: E501190 191 192def _validate_name(name: str) -> tuple[bool, str]:193 """Validate skill name per Agent Skills spec.194 195 Requirements (https://agentskills.io/specification):196 - 1-64 characters197 - Unicode lowercase alphanumeric and hyphens only198 - Cannot start or end with hyphen199 - No consecutive hyphens200 201 Unicode lowercase alphanumeric means any character where202 `c.isalpha() and c.islower()` or `c.isdigit()` returns `True`.203 204 Args:205 name: The skill name to validate.206 207 Returns:208 Tuple of (is_valid, error_message). If valid, error_message is empty.209 """210 if not name or not name.strip():211 return False, "cannot be empty"212 if len(name) > MAX_SKILL_NAME_LENGTH:213 return False, "cannot exceed 64 characters"214 if name.startswith("-") or name.endswith("-") or "--" in name:215 return False, "must be lowercase alphanumeric with single hyphens only"216 for c in name:217 if c == "-":218 continue219 if (c.isalpha() and c.islower()) or c.isdigit():220 continue221 return False, "must be lowercase alphanumeric with single hyphens only"222 return True, ""223 224 225def title_case_skill_name(skill_name):226 """Convert hyphenated skill name to Title Case for display.227 228 Returns:229 Skill name with each word capitalized.230 """231 return " ".join(word.capitalize() for word in skill_name.split("-"))232 233 234def init_skill(skill_name, path):235 """Initialize a new skill directory with template SKILL.md.236 237 Args:238 skill_name: Name of the skill239 path: Path where the skill directory should be created240 241 Returns:242 Path to created skill directory, or None if error243 """244 is_valid, error_msg = _validate_name(skill_name)245 if not is_valid:246 print(f"Error: Invalid skill name: {error_msg}")247 print(248 "Skill names must be lowercase alphanumeric with hyphens only.\n"249 "Examples: web-research, code-review, data-analysis"250 )251 return None252 253 # Determine skill directory path254 skill_dir = Path(path).resolve() / skill_name255 256 # Check if directory already exists257 if skill_dir.exists():258 print(f"Error: Skill directory already exists: {skill_dir}")259 return None260 261 # Create skill directory262 try:263 skill_dir.mkdir(parents=True, exist_ok=False)264 print(f"Created skill directory: {skill_dir}")265 except Exception as e:266 print(f"Error creating directory: {e}")267 return None268 269 # Create SKILL.md from template270 skill_title = title_case_skill_name(skill_name)271 skill_content = SKILL_TEMPLATE.format(272 skill_name=skill_name, skill_title=skill_title273 )274 275 skill_md_path = skill_dir / "SKILL.md"276 try:277 skill_md_path.write_text(skill_content)278 print("Created SKILL.md")279 except Exception as e:280 print(f"Error creating SKILL.md: {e}")281 return None282 283 # Create resource directories with example files284 try:285 # Create scripts/ directory with example script286 scripts_dir = skill_dir / "scripts"287 scripts_dir.mkdir(exist_ok=True)288 example_script = scripts_dir / "example.py"289 example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))290 example_script.chmod(0o755)291 print("Created scripts/example.py")292 293 # Create references/ directory with example reference doc294 references_dir = skill_dir / "references"295 references_dir.mkdir(exist_ok=True)296 example_reference = references_dir / "api_reference.md"297 example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))298 print("Created references/api_reference.md")299 300 # Create assets/ directory with example asset placeholder301 assets_dir = skill_dir / "assets"302 assets_dir.mkdir(exist_ok=True)303 example_asset = assets_dir / "example_asset.txt"304 example_asset.write_text(EXAMPLE_ASSET)305 print("Created assets/example_asset.txt")306 except Exception as e:307 print(f"Error creating resource directories: {e}")308 return None309 310 # Print next steps311 print(f"\nSkill '{skill_name}' initialized successfully at {skill_dir}")312 print("\nNext steps:")313 print("1. Edit SKILL.md to complete the TODO items and update the description")314 print(315 "2. Customize or delete the example files in scripts/, references/, and assets/"316 )317 print("3. Run the validator when ready to check the skill structure")318 319 return skill_dir320 321 322def main():323 """Main entry point for the skill initialization script."""324 if len(sys.argv) < 4 or sys.argv[2] != "--path":325 print("Usage: init_skill.py <skill-name> --path <path>")326 print("\nSkill name requirements:")327 print(" - Hyphen-case identifier (e.g., 'data-analyzer')")328 print(" - Lowercase letters, digits, and hyphens only")329 print(" - Max 64 characters")330 print(" - Must match directory name exactly")331 print("\nExamples:")332 print(" init_skill.py my-new-skill --path skills/public")333 print(" init_skill.py my-api-helper --path skills/private")334 print(" init_skill.py custom-skill --path /custom/location")335 print("\nFor deepagents CLI:")336 skills_dir = "${DEEPAGENTS_HOME:-$HOME/.deepagents}/agent/skills"337 print(f' init_skill.py my-skill --path "{skills_dir}"')338 sys.exit(1)339 340 skill_name = sys.argv[1]341 path = sys.argv[3]342 343 # Early validation for fast feedback344 is_valid, error_msg = _validate_name(skill_name)345 if not is_valid:346 print(f"Error: Invalid skill name '{skill_name}': {error_msg}")347 print("\nSkill name requirements:")348 print(" - Lowercase letters, digits, and hyphens only")349 print(" - Cannot start or end with hyphen")350 print(" - No consecutive hyphens")351 print(" - Max 64 characters")352 sys.exit(1)353 354 print(f"Initializing skill: {skill_name}")355 print(f" Location: {path}")356 print()357 358 result = init_skill(skill_name, path)359 360 if result:361 sys.exit(0)362 else:363 sys.exit(1)364 365 366if __name__ == "__main__":367 main()368 Referenced from SKILL.md
SKILL.mdView in source ↗
Source excerpt starting at line 283.SKILL.mdView in source ↗283```bash284scripts/init_skill.py <skill-name> --path <output-directory>285```
Source excerpt starting at line 290.SKILL.mdView in source ↗290# User skills (default)291scripts/init_skill.py <skill-name> --path "${DEEPAGENTS_HOME:-$HOME/.deepagents}/agent/skills"
Source excerpt starting at line 293.293# Project skills294scripts/init_skill.py <skill-name> --path .deepagents/skills295```