Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:00:18 +08:00
commit 765529cd13
69 changed files with 18291 additions and 0 deletions

210
commands/new-sdk-app.md Normal file
View File

@@ -0,0 +1,210 @@
---
description: Create and setup a new Claude Agent SDK application (Python)
argument-hint: [project-name]
---
You are tasked with helping the user create a new Claude Agent SDK application using Python. Follow these steps carefully:
## Reference Documentation
Before starting, use the **claude-agent-sdk skill** to ensure you follow SDK best practices:
```bash
# Load the skill to access patterns and examples
/skill claude-agent-sdk
```
The skill provides:
- SDK templates (assets/sdk-template.py)
- Official examples (examples/)
- Best practices and patterns (references/)
- Validation checklist (assets/sdk-validation-checklist.md)
Also reference the official documentation:
- Python SDK reference: <https://docs.claude.com/en/api/agent-sdk/python>
**IMPORTANT**: Always check for and use the latest SDK version (targeting >= 0.1.6).
## Gather Requirements
IMPORTANT: Ask these questions one at a time. Wait for the user's response before asking the next question. This makes it easier for the user to respond.
Ask the questions in this order (skip any that the user has already provided via arguments):
1. **Project name** (ask first): "What would you like to name your project?"
- If $ARGUMENTS is provided, use that as the project name and skip this question
- Wait for response before continuing
2. **Agent type** (ask second, but skip if #1 was sufficiently detailed): "What kind of agent are you building? Some examples:
- Coding agent (SRE, security review, code review)
- Orchestrator with subagents (multi-agent workflows)
- Business agent (customer support, content creation)
- Custom agent (describe your use case)"
- Wait for response before continuing
3. **Starting point** (ask third): "Would you like:
- A minimal query() example for simple tasks
- A ClaudeSDKClient example for multi-turn conversations
- An orchestrator with subagents
- Start from the SDK template (assets/sdk-template.py)"
- Wait for response before continuing
4. **Project structure** (ask fourth): "What project structure would you prefer:
- Single-file uv script (self-contained with `# /// script` header)
- Standard Python project with pyproject.toml"
- Wait for response before continuing
After all questions are answered, proceed to create the setup plan.
## Setup Plan
Based on the user's answers, create a plan that includes:
1. **Project initialization**:
- Create project directory (if it doesn't exist)
- **For uv scripts**: Create single Python file with `# /// script` header including `claude-agent-sdk` dependency
- **For standard projects**:
- Initialize with `pyproject.toml`
- Add `claude-agent-sdk` to dependencies
- Configure Python version requirements (>= 3.8)
2. **Check for Latest Versions**:
- BEFORE installing, check PyPI for the latest version: <https://pypi.org/project/claude-agent-sdk/>
- Inform the user which version you're using (targeting >= 0.1.6)
3. **SDK Installation**:
- **For uv scripts**: Dependencies specified in script header, no separate installation needed
- **For standard projects**:
- Install with `pip install claude-agent-sdk` or add to pyproject.toml
- After installation, verify with `pip show claude-agent-sdk`
4. **Create starter files**:
Based on user's choice:
- **query() example**: Simple one-shot task (no conversation memory)
- **ClaudeSDKClient example**: Multi-turn conversation with context
- **Orchestrator**: Main orchestrator with programmatically registered subagents
- **SDK template**: Copy from `assets/sdk-template.py` and customize
All files should include:
- Proper imports (`claude_agent_sdk`, `anyio`)
- SDK best practices (system_prompt, allowed_tools, permission_mode)
- Error handling
- Clear comments explaining each part
5. **Authentication setup**:
- Explain that the SDK uses local Claude Code authentication
- No `.env` files needed when running with Claude Code
- If running standalone, API key can be set via environment variable
6. **Optional: Create .claude directory structure**:
- Offer to create `.claude/agents/` directory for subagent definitions
- Provide example agent markdown files if building an orchestrator
## Implementation
After gathering requirements and getting user confirmation on the plan:
1. Check for latest SDK version on PyPI
2. Execute the setup steps
3. Create all necessary files based on project structure choice:
- **Uv script**: Single file with proper script header
- **Standard project**: pyproject.toml + source files
4. Install dependencies if standard project (uv scripts handle deps automatically)
5. Verify installed versions and inform the user
6. Create a working example based on their starting point:
- Use patterns from the claude-agent-sdk skill
- Reference examples from `examples/` directory
- Follow SDK best practices
7. Add helpful comments explaining SDK concepts:
- What `ClaudeAgentOptions` does
- Why `system_prompt="claude_code"` for orchestrators
- Tool restrictions and permission modes
- Async runtime choice (anyio vs asyncio)
8. **VERIFY THE CODE WORKS BEFORE FINISHING**:
- Verify imports are correct
- Check for syntax errors
- Validate SDK patterns match documentation
- Ensure agent names match if using orchestrator
- **DO NOT consider the setup complete until the code verifies successfully**
## Verification
After all files are created and dependencies are installed, launch the **agent-sdk-verifier-py** agent to validate that the Agent SDK application is properly configured and ready for use:
1. Use the Task tool to launch the `agent-sdk-verifier-py` subagent
2. The agent will check:
- SDK installation and configuration
- Proper imports and SDK patterns
- query() vs ClaudeSDKClient usage
- Orchestrator requirements (system_prompt, Task tool, agent registration)
- Permission and security settings
- Best practices adherence
3. Review the verification report and address any issues before completing setup
## Getting Started Guide
Once setup is complete and verified, provide the user with:
1. **Next steps**:
- **For uv scripts**: Run with `uv run <script-name>.py` (automatically handles dependencies)
- **For standard projects**:
- Activate virtual environment if needed
- Run with `python main.py` or `python src/main.py`
- Authentication uses local Claude Code session (no API key setup needed)
2. **Useful resources**:
- Python SDK reference: <https://docs.claude.com/en/api/agent-sdk/python>
- claude-agent-sdk skill: `/skill claude-agent-sdk` for patterns and examples
- Key concepts to explore:
- System prompts (preset vs custom)
- Permissions (permission_mode and callbacks)
- Tools (allowed_tools restrictions)
- MCP servers (custom tools)
- Subagents (programmatic registration)
3. **Common next steps**:
- Customize the system prompt for your use case
- Add custom tools via SDK MCP servers (see `examples/mcp_calculator.py`)
- Configure permission callbacks for fine-grained control
- Create and register subagents programmatically
- Review examples in the skill: `examples/hooks.py`, `examples/streaming_mode.py`
- Validate changes with `assets/sdk-validation-checklist.md`
## Important Notes
- **ALWAYS USE LATEST SDK VERSION**: Check PyPI for the latest version (targeting >= 0.1.6)
- **VERIFY CODE WORKS BEFORE FINISHING**:
- Verify imports are correct
- Check syntax
- Validate SDK patterns (query() vs ClaudeSDKClient, system_prompt, tools)
- Ensure agent names match if using orchestrator
- Launch agent-sdk-verifier-py for comprehensive validation
- Do NOT consider the task complete until verification passes
- **USE THE CLAUDE-AGENT-SDK SKILL**: Reference patterns and examples from the skill
- **FOLLOW SDK BEST PRACTICES**:
- Use `system_prompt="claude_code"` for orchestrators
- Register agents programmatically via `agents={}`
- Include `"Task"` in orchestrator's allowed_tools
- Choose appropriate runtime (anyio.run or asyncio.run)
- Restrict tools to minimum needed per agent
- Always check if directories/files already exist before creating them
- Ensure all code examples are functional and include proper error handling
- Use patterns compatible with the latest SDK version
- Make the experience interactive and educational
- **ASK QUESTIONS ONE AT A TIME** - Do not ask multiple questions in a single response
Begin by asking the FIRST requirement question only. Wait for the user's answer before proceeding to the next question.

316
commands/review-sdk-app.md Normal file
View File

@@ -0,0 +1,316 @@
---
description: Review and validate a Claude Agent SDK application against best practices
argument-hint: [path-to-app]
---
# Review Claude Agent SDK Application
You are tasked with reviewing a Claude Agent SDK (Python) application to ensure
it follows SDK best practices and official documentation patterns. Follow these
steps carefully:
## Reference Documentation
Before starting, load the **claude-agent-sdk skill** to access patterns, examples, and the validation checklist:
```bash
# Load the skill for comprehensive SDK knowledge
/skill claude-agent-sdk
```
The skill provides:
- **Validation checklist**: `assets/sdk-validation-checklist.md` (comprehensive review guide)
- **SDK patterns**: `SKILL.md` and `references/` (official best practices)
- **Working examples**: `examples/` (reference implementations)
- **Template**: `assets/sdk-template.py` (ideal structure)
## Review Approach
You have TWO options for reviewing SDK applications:
### Option 1: Automated Validation (Recommended)
Launch the **agent-sdk-verifier-py** subagent for comprehensive automated review:
```bash
# The subagent will:
# - Read all application files
# - Check SDK patterns and configuration
# - Validate against official documentation
# - Provide detailed report with specific issues and recommendations
```
**Best for:**
- Quick validation
- New applications
- Pre-deployment checks
- Comprehensive coverage
### Option 2: Manual Guided Review
Follow the validation checklist step-by-step with guided assistance.
**Best for:**
- Learning SDK patterns
- Understanding specific issues
- Deep dive into SDK concepts
- Educational reviews
## Gather Information
Ask the user (if not provided via $ARGUMENTS):
1. **Application path**: "What is the path to your SDK application?"
- If $ARGUMENTS is provided, use that as the application path
- Wait for response before continuing
2. **Review type**: "Would you like:
- Automated validation (launch agent-sdk-verifier)
- Manual guided review (step-by-step checklist)
- Both (automated first, then deep dive on issues)"
- Wait for response before continuing
## Automated Validation Flow
If user chooses automated validation:
1. **Launch verifier agent**:
- Use Task tool to launch `agent-sdk-verifier` subagent
- Provide the application path to the agent
- Wait for verification report
2. **Review the report**:
- **Overall Status**: PASS | PASS WITH WARNINGS | FAIL
- **Critical Issues**: Must be fixed before deployment
- **Warnings**: Suboptimal patterns or improvements
- **Passed Checks**: Correctly configured elements
- **Recommendations**: Specific improvements with references
3. **Address issues**:
- For each critical issue: explain the problem and provide fix
- For warnings: explain why the recommendation matters
- Reference specific skill documentation for context
4. **Re-validate if changes made**:
- After fixes, offer to re-run validation
- Ensure all critical issues are resolved
## Manual Guided Review Flow
If user chooses manual review, systematically work through the validation
checklist (`assets/sdk-validation-checklist.md`):
### Section 1: Imports & Dependencies
Read the application files and check:
- [ ] Async runtime import (anyio or asyncio)
- [ ] Claude SDK imports are accurate
- [ ] UV script headers (if single-file script)
**Ask user**: "Found any issues with imports? (Y/N)"
If yes, explain the issue and show correct pattern from skill examples.
### Section 2: Async Runtime
Check:
- [ ] Runtime execution (`anyio.run()` or `asyncio.run()`)
- [ ] Async/await patterns are correct
- [ ] Context managers for ClaudeSDKClient
**Ask user**: "Found any issues with async patterns? (Y/N)"
### Section 3: query() vs ClaudeSDKClient Choice
Check:
- [ ] Correct approach for use case
- [ ] Not using hooks/custom tools with query()
**Ask user**: "Is the query()/ClaudeSDKClient choice appropriate? (Y/N)"
If no, explain when to use each approach (reference SKILL.md lines 29-44).
### Section 4: Orchestrator Configuration (if applicable)
Check:
- [ ] System prompt is `"claude_code"` for orchestrators
- [ ] Task tool is included in allowed_tools
- [ ] Agents are registered programmatically
**Ask user**: "Found any orchestrator configuration issues? (Y/N)"
### Section 5: Agent Definitions (if applicable)
Check:
- [ ] Agent structure is correct (description, prompt, tools, model)
- [ ] Agent names match between definition and usage
- [ ] Tools are restricted to minimum needed
**Ask user**: "Found any agent definition issues? (Y/N)"
### Section 6: Permission Control
Check:
- [ ] Permission strategy is appropriate
- [ ] Permission mode is valid
- [ ] Permission callback (if used) is correct
**Ask user**: "Found any permission issues? (Y/N)"
### Section 7: Hooks (if used)
Check:
- [ ] Hooks ONLY used with ClaudeSDKClient
- [ ] Hook types are supported (not using SessionStart, etc.)
- [ ] Hook signature is correct
- [ ] Hook output structure is valid
**Ask user**: "Found any hook issues? (Y/N)"
### Section 8: ClaudeSDKClient Usage (if applicable)
Check:
- [ ] Context manager pattern is used
- [ ] Query → receive_response flow
- [ ] Interrupts (if used) are correct
**Ask user**: "Found any ClaudeSDKClient usage issues? (Y/N)"
### Section 9: Message Handling
Check:
- [ ] Message types are checked correctly
- [ ] TextBlock extraction is correct
- [ ] ResultMessage handling
**Ask user**: "Found any message handling issues? (Y/N)"
### Section 10: Error Handling
Check:
- [ ] API key validation (if running standalone)
- [ ] Safe dictionary access
- [ ] Async exception handling
**Ask user**: "Found any error handling issues? (Y/N)"
### Section 11: Settings & Configuration
Check:
- [ ] setting_sources is configured appropriately
- [ ] Model selection is appropriate
- [ ] Budget limits (if needed)
**Ask user**: "Found any configuration issues? (Y/N)"
### Section 12: Best Practices
Check:
- [ ] Follows DRY principle
- [ ] Clear comments and documentation
- [ ] Type hints are used
- [ ] No anti-patterns
**Ask user**: "Found any best practice violations? (Y/N)"
### Manual Review Summary
After completing all sections, provide:
```markdown
## Validation Summary
### ✅ Passed Checks:
- [List of passed checks]
### ❌ Issues Found:
- [List of issues with severity: CRITICAL | WARNING | INFO]
### 🔧 Fixes Required:
1. [Specific fix with file:line reference and code example]
2. [Specific fix with file:line reference and code example]
### 📊 Overall Assessment:
- **SDK Pattern Adherence**: [High/Medium/Low]
- **Production Ready**: [Yes/No/With Fixes]
- **Recommended Next Steps**: [Specific actions]
```
## Providing Fixes
For each issue identified:
1. **Explain the problem**:
- Why it's an issue
- What SDK pattern is being violated
- Reference to skill documentation
2. **Show the correct pattern**:
- Code example from skill examples or template
- Explain why this pattern is preferred
- Link to relevant skill reference
3. **Provide specific fix**:
- Exact code change needed
- File and line reference
- Before/after comparison if helpful
## Follow-up Actions
After review:
1. **Offer to implement fixes**:
- "Would you like me to implement these fixes?"
- If yes, make changes and re-validate
2. **Suggest re-validation**:
- "Would you like to run automated validation to confirm fixes?"
- Launch agent-sdk-verifier-py if requested
3. **Recommend next steps**:
- Additional features to consider
- Testing recommendations
- Deployment considerations
## Important Notes
- **USE THE VALIDATION CHECKLIST**: `assets/sdk-validation-checklist.md` is your comprehensive guide
- **REFERENCE SKILL DOCUMENTATION**: Always link to specific skill files for context
- **SHOW WORKING EXAMPLES**: Use examples from `examples/` directory
- **BE SPECIFIC**: Provide file:line references and exact code changes
- **EXPLAIN WHY**: Don't just identify issues, explain the SDK reasoning
- **PRIORITIZE ISSUES**: CRITICAL (breaks functionality) > WARNING (suboptimal) > INFO (nice to have)
- **VERIFY FIXES**: Re-validate after making changes
- **USE AGENT-SDK-VERIFIER-PY**: Leverage automated validation for comprehensive coverage
## Key SDK Patterns to Verify
Always check these common issues:
1. **Orchestrator missing system_prompt**: Must use `"claude_code"`
2. **Orchestrator missing Task tool**: Cannot delegate without it
3. **Agent name mismatches**: Definition name must match usage
4. **Hooks with query()**: Not supported, use ClaudeSDKClient
5. **Custom tools with query()**: Not supported, use ClaudeSDKClient
6. **Excessive tool permissions**: Restrict to minimum needed
7. **Missing agent registration**: Use `agents={}` parameter
8. **Wrong async runtime call**: Use `anyio.run()` or `asyncio.run()`
9. **Missing context manager**: ClaudeSDKClient requires `async with`
10. **Unsafe dictionary access**: Use `.get()` for optional fields
Begin by asking about the application path (if not provided) and review type preference.