diff --git a/.claude/.claude-plugin/plugin.json b/.claude/.claude-plugin/plugin.json new file mode 100644 index 0000000..059a8c9 --- /dev/null +++ b/.claude/.claude-plugin/plugin.json @@ -0,0 +1,35 @@ +{ + "name": "copilotkit-expert", + "version": "1.0.0", + "description": "CopilotKit Expert Plugin - Specialized agent for CopilotKit, AG-UI, and AI framework integrations", + "author": { + "name": "BLOG-CANVAS-COPILOTkit Team" + }, + "license": "MIT", + "engines": { + "claudeCode": ">=1.0.0" + }, + "dependencies": { + "copilotkit": ">=1.5.20", + "langraph": ">=0.1.0", + "langchain": ">=0.1.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/alchimie-di-circe/BLOG-CANVAS-COPILOTkit", + "directory": ".claude" + }, + "keywords": [ + "claude-code", + "copilotkit", + "ag-ui", + "langgraph", + "langchain", + "anthropic", + "openai", + "ai-agents", + "coagents", + "mcp", + "plugin" + ] +} diff --git a/.claude/COPILOTKIT_PLUGIN.md b/.claude/COPILOTKIT_PLUGIN.md new file mode 100644 index 0000000..df58c14 --- /dev/null +++ b/.claude/COPILOTKIT_PLUGIN.md @@ -0,0 +1,419 @@ +# CopilotKit Expert Plugin for Claude Code + +A comprehensive, reusable plugin that transforms Claude Code into a CopilotKit expert with deep knowledge of CoAgents, AG-UI, and AI framework integrations. + +## 🎯 What This Plugin Provides + +### Expert AI Agent +A specialized **CopilotKit Expert Agent** with expertise in: +- CopilotKit framework (v1.5.20+) +- AG-UI integration +- LangGraph orchestration +- LangChain patterns +- Anthropic Claude SDK +- OpenAI integration +- Human-in-the-loop workflows +- State management and streaming + +### MCP Integration +Direct access to **CopilotKit VIBE CODING MCP** for: +- Real-time official documentation +- Code examples from CopilotKit repos +- Best practices and patterns +- Version-specific guidance + +### Slash Commands +Quick-access commands for common tasks: +- `/copilotkit-docs` - Search and fetch CopilotKit documentation +- `/copilotkit-integrate` - Guide for integrating CopilotKit features +- `/copilotkit-debug` - Debug CopilotKit issues (state sync, streaming, interrupts) + +### Knowledge Base +Comprehensive patterns and best practices guide: +- Core patterns (CoAgent setup, state management) +- Streaming patterns (content generation, progress indicators) +- Human-in-the-loop workflows (approval patterns, interrupts) +- Framework integrations (LangGraph, LangChain, Anthropic) +- AG-UI patterns (auto-form generation) +- Performance optimization +- Error handling + +## πŸ“¦ Installation + +### In This Repository + +The plugin is already installed! It's in `.claude/` with: + +``` +.claude/ +β”œβ”€β”€ skills/ +β”‚ └── copilotkit-expert.md # Main expert agent +β”œβ”€β”€ commands/ +β”‚ β”œβ”€β”€ copilotkit-docs.md # Documentation search +β”‚ β”œβ”€β”€ copilotkit-integrate.md # Integration guide +β”‚ └── copilotkit-debug.md # Debugging helper +β”œβ”€β”€ copilotkit-patterns.md # Patterns & best practices +└── COPILOTKIT_PLUGIN.md # This file +``` + +### In Other Repositories (Reusable) + +To use this plugin in other projects: + +#### Option 1: Copy Files + +```bash +# From this repo, copy the plugin files +cp -r .claude/skills/copilotkit-expert.md /path/to/other/repo/.claude/skills/ +cp -r .claude/commands/copilotkit-*.md /path/to/other/repo/.claude/commands/ +cp .claude/copilotkit-patterns.md /path/to/other/repo/.claude/ +``` + +#### Option 2: Git Submodule + +```bash +cd /path/to/other/repo +git submodule add .claude/modules/copilotkit-plugin +ln -s .claude/modules/copilotkit-plugin/skills/copilotkit-expert.md .claude/skills/ +ln -s .claude/modules/copilotkit-plugin/commands/copilotkit-*.md .claude/commands/ +``` + +#### Option 3: npm Package (Future) + +```bash +npx create-claude-plugin copilotkit-expert +``` + +### MCP Server Setup + +Configure the CopilotKit VIBE CODING MCP: + +```bash +claude mcp add --transport sse copilotkit-mcp https://mcp.copilotkit.ai/sse +``` + +Verify it's active: + +```bash +claude mcp list +# Should show: copilotkit-mcp (https://mcp.copilotkit.ai/sse) +``` + +## πŸš€ Usage + +### Activating the Expert Agent + +The CopilotKit Expert is available as a **skill** in Claude Code. Activate it when you need CopilotKit expertise: + +``` +User: I need help implementing a human-in-the-loop workflow with CopilotKit + +Claude: I'll activate the CopilotKit Expert skill to help you with this. + [Loads copilotkit-expert skill] + + [Provides expert guidance on interrupts, state management, etc.] +``` + +Or explicitly request it: + +``` +User: Use the copilotkit-expert skill to help me debug state synchronization +``` + +### Using Slash Commands + +#### Search Documentation + +``` +/copilotkit-docs + +# Then specify what you want to search: +> How do I use useCoAgentStateRender? +``` + +#### Integrate a Feature + +``` +/copilotkit-integrate + +# Then describe the feature: +> I want to add a progress indicator that shows real-time agent status +``` + +#### Debug Issues + +``` +/copilotkit-debug + +# Then describe the problem: +> My frontend isn't receiving state updates from the agent +``` + +### Accessing Patterns Guide + +The patterns guide is available at `.claude/copilotkit-patterns.md`. Reference it for: +- Complete code examples +- Best practices +- Common patterns +- Framework integration examples + +## 🧠 How the Expert Agent Works + +### Knowledge Sources + +1. **Built-in Expertise**: Pre-trained knowledge of CopilotKit patterns +2. **MCP Access**: Real-time docs from https://mcp.copilotkit.ai/sse +3. **Patterns Guide**: Local knowledge base at `.claude/copilotkit-patterns.md` +4. **Project Context**: Understands your current project structure + +### Capabilities + +#### Code Generation +```typescript +// The agent can generate complete, working code like: +import { useCoAgent, useCoAgentStateRender } from "@copilotkit/react-core"; + +export function MyCoAgent() { + const { state, setState } = useCoAgent({ + name: "my_agent", + initialState: { /* ... */ } + }); + + useCoAgentStateRender({ + name: "my_agent", + render: ({ state }) => { + // Custom rendering logic + } + }); + + return /* UI */; +} +``` + +#### Architecture Guidance +- Recommends appropriate frameworks for your use case +- Explains trade-offs between different approaches +- Provides state management strategies +- Suggests performance optimizations + +#### Debugging +- Diagnoses state synchronization issues +- Identifies streaming problems +- Fixes interrupt/approval workflows +- Resolves type mismatches + +#### Best Practices +- Enforces CopilotKit patterns +- Ensures type safety +- Optimizes for performance +- Handles errors gracefully + +## πŸ“š Examples + +### Example 1: Creating a CoAgent + +``` +User: Help me create a CoAgent that generates research reports + +CopilotKit Expert: +I'll help you create a research report CoAgent. Here's the complete implementation: + +[Backend - state.py] +... (provides complete Python code) + +[Backend - graph.py] +... (provides LangGraph setup) + +[Frontend - components/ResearchAgent.tsx] +... (provides React component) + +This pattern uses: +- State synchronization via copilotkit_emit_state() +- Streaming content updates +- Human-in-the-loop approval workflow +- Progress indicators + +Try it by: +1. Start agent: cd agent && langgraph up +2. Start frontend: cd frontend && pnpm dev +3. Test the workflow end-to-end +``` + +### Example 2: Debugging State Sync + +``` +User: My state updates aren't showing in the frontend + +CopilotKit Expert: +Let me help debug this state synchronization issue. + +First, let's verify: +1. Is copilotkit_emit_state() called after state changes? + [Checks agent code] + +2. Does the state schema match TypeScript types? + [Compares state.py vs types.ts] + +3. Is the CopilotKit provider configured correctly? + [Checks layout.tsx] + +I found the issue: [explains specific problem] + +Here's the fix: [provides corrected code] + +After applying this fix, you should see state updates in real-time. +``` + +### Example 3: Adding AG-UI + +``` +User: How do I add AG-UI to generate forms from my Pydantic models? + +CopilotKit Expert: +AG-UI can automatically generate forms from Pydantic models. Here's how: + +[Step 1: Define Pydantic Model] +... (shows Python code) + +[Step 2: Install AG-UI] +... (shows npm command) + +[Step 3: Create Form Component] +... (shows React component with AG-UI) + +[Step 4: Integrate with CoAgent] +... (shows integration code) + +This will generate a fully functional form with: +- Automatic field types +- Validation from Pydantic +- Submit handling +- Error display +``` + +## 🎨 Customization + +### Extending the Expert + +Add your own patterns to `.claude/copilotkit-patterns.md`: + +```markdown +## My Custom Pattern + +### Use Case +Describe when to use this pattern + +### Implementation +```code examples``` + +### Best Practices +- Tip 1 +- Tip 2 +``` + +### Adding Commands + +Create new slash commands in `.claude/commands/`: + +```markdown +--- +description: My custom CopilotKit command +--- + +Command instructions here... +``` + +### Configuring MCP + +Add additional MCP servers for extended capabilities: + +```bash +claude mcp add --transport stdio my-custom-mcp /path/to/server +``` + +## πŸ”§ Troubleshooting + +### MCP Not Connected + +```bash +# Check MCP status +claude mcp list + +# Reconnect if needed +claude mcp remove copilotkit-mcp +claude mcp add --transport sse copilotkit-mcp https://mcp.copilotkit.ai/sse +``` + +### Skill Not Loading + +Verify file locations: +```bash +ls -la .claude/skills/copilotkit-expert.md +ls -la .claude/commands/copilotkit-*.md +``` + +### Commands Not Appearing + +Ensure frontmatter is correct: +```markdown +--- +description: Brief description here +--- +``` + +## 🌐 Using Across Projects + +### Cloud Repositories + +Works seamlessly in cloud environments (GitHub Codespaces, etc.): +1. Clone your repo with the plugin +2. Claude Code automatically detects `.claude/` config +3. MCP connection works via SSE (no local setup needed) + +### Local Development + +Same setup process: +1. Install Claude Code CLI +2. Copy plugin files to `.claude/` +3. Configure MCP server +4. Start using immediately + +### Team Sharing + +Share the plugin with your team: +1. Commit `.claude/` directory to git +2. Team members get the plugin automatically +3. Everyone has the same CopilotKit expertise + +## πŸ“– Resources + +### Official Documentation +- [CopilotKit Docs](https://docs.copilotkit.ai/) +- [CoAgents Guide](https://docs.copilotkit.ai/coagents) +- [LangGraph Docs](https://langchain-ai.github.io/langgraph/) +- [Claude Code Docs](https://docs.claude.com/en/docs/claude-code) + +### Plugin Files +- **Expert Agent**: `.claude/skills/copilotkit-expert.md` +- **Patterns Guide**: `.claude/copilotkit-patterns.md` +- **Commands**: `.claude/commands/copilotkit-*.md` + +### Support +- [CopilotKit Discord](https://discord.gg/copilotkit) +- [GitHub Issues](https://github.com/CopilotKit/CopilotKit/issues) +- [Claude Code GitHub](https://github.com/anthropics/claude-code) + +## 🚒 Version + +- **Plugin Version**: 1.0.0 +- **CopilotKit Compatibility**: v1.5.20+ +- **Claude Code**: Latest +- **Last Updated**: 2025-11-15 + +## πŸ“ License + +This plugin is part of the BLOG-CANVAS-COPILOTkit project. Reusable across projects. + +--- + +**Ready to become a CopilotKit expert? Activate the skill or use a slash command to get started!** diff --git a/.claude/MCP_SETUP.md b/.claude/MCP_SETUP.md new file mode 100644 index 0000000..10df044 --- /dev/null +++ b/.claude/MCP_SETUP.md @@ -0,0 +1,267 @@ +# CopilotKit VIBE CODING MCP Setup + +This guide helps you set up the CopilotKit VIBE CODING MCP server for the CopilotKit Expert Plugin. + +## What is VIBE CODING MCP? + +The **VIBE CODING MCP** is CopilotKit's official Model Context Protocol server that provides: +- Real-time access to CopilotKit documentation +- Official code examples from CopilotKit repositories +- API references and best practices +- Version-specific guidance + +## Setup Instructions + +### Method 1: Using Claude CLI (Recommended) + +Run this command in your terminal: + +```bash +claude mcp add --transport sse copilotkit-mcp https://mcp.copilotkit.ai/sse +``` + +This will: +1. Add the CopilotKit MCP server to your Claude configuration +2. Configure it to use Server-Sent Events (SSE) transport +3. Make it available to all Claude Code sessions + +### Method 2: Manual Configuration + +If the CLI command doesn't work, manually configure the MCP: + +1. **Locate your Claude config file**: + - Linux/Mac: `~/.config/claude/config.json` + - Windows: `%APPDATA%\claude\config.json` + +2. **Add the MCP server**: + +```json +{ + "mcpServers": { + "copilotkit-mcp": { + "url": "https://mcp.copilotkit.ai/sse", + "transport": "sse" + } + } +} +``` + +3. **Restart Claude Code** to apply changes. + +### Method 3: Environment Variable + +Set an environment variable to configure the MCP: + +```bash +export CLAUDE_MCP_COPILOTKIT_URL="https://mcp.copilotkit.ai/sse" +``` + +Add this to your `~/.bashrc`, `~/.zshrc`, or equivalent. + +## Verification + +To verify the MCP is configured correctly: + +### Using Claude CLI + +```bash +claude mcp list +``` + +You should see: +``` +copilotkit-mcp (https://mcp.copilotkit.ai/sse) [sse] +``` + +### Testing in Claude Code + +Ask Claude a CopilotKit question: + +``` +You: What is the latest version of CopilotKit? + +Claude (should use MCP to fetch current info): +The latest version of CopilotKit is [version from MCP]... +``` + +## Troubleshooting + +### Issue: MCP server not connecting + +**Possible causes:** +1. Network/firewall blocking the URL +2. Incorrect URL or transport type +3. Claude config not reloaded + +**Solutions:** + +1. **Check network connectivity**: +```bash +curl -I https://mcp.copilotkit.ai/sse +``` + +Should return HTTP 200 OK. + +2. **Verify transport type**: +The transport MUST be `sse` (Server-Sent Events), not `stdio`. + +3. **Restart Claude Code**: +Close and reopen Claude Code after configuration changes. + +### Issue: MCP server not showing in list + +**Solution:** + +1. Check config file syntax (valid JSON) +2. Ensure proper permissions on config file +3. Try removing and re-adding: + +```bash +claude mcp remove copilotkit-mcp +claude mcp add --transport sse copilotkit-mcp https://mcp.copilotkit.ai/sse +``` + +### Issue: Plugin works but MCP not used + +**Note:** The CopilotKit Expert Plugin works even WITHOUT MCP connection! + +- **With MCP**: Gets latest docs, real-time API info +- **Without MCP**: Uses built-in knowledge (still very capable) + +The MCP enhances the plugin but is not required. + +## MCP Capabilities + +Once configured, the MCP provides: + +### 1. Documentation Search +``` +/copilotkit-docs + +> Search for "useCoAgent hook" +``` + +The MCP fetches the latest official documentation. + +### 2. Code Examples +``` +"Show me the official example of CoAgent state synchronization" +``` + +The MCP retrieves examples from CopilotKit's GitHub repos. + +### 3. API References +``` +"What are all the parameters for CopilotKitProvider?" +``` + +The MCP provides current API signatures. + +### 4. Version Information +``` +"What changed in CopilotKit v1.5.20?" +``` + +The MCP accesses version-specific changelogs. + +## Using the MCP + +### Implicit Usage + +The CopilotKit Expert Plugin automatically uses the MCP when: +- You ask documentation questions +- You request code examples +- You search for API references +- You use `/copilotkit-docs` command + +### Explicit Usage + +You can explicitly request MCP usage: + +``` +"Use the VIBE CODING MCP to get the latest docs for useCoAgentStateRender" +``` + +## Alternative: Manual Documentation Access + +If you can't configure the MCP, you can still: + +1. **Reference built-in patterns**: + - See `.claude/copilotkit-patterns.md` + - Contains extensive examples and patterns + +2. **Browse official docs manually**: + - https://docs.copilotkit.ai/ + - Copy/paste relevant sections to Claude + +3. **Use the expert agent**: + - Still has deep CopilotKit knowledge + - Can answer most questions without MCP + +## Cloud vs Local + +### Cloud (GitHub Codespaces, etc.) + +MCP works seamlessly in cloud environments: +- SSE transport works over HTTP +- No local setup required +- Same command to configure + +### Local Development + +Works the same way: +- SSE transport is firewall-friendly +- No special network configuration +- Automatic reconnection + +## Security & Privacy + +The VIBE CODING MCP: +- βœ… Is official from CopilotKit +- βœ… Uses HTTPS (secure) +- βœ… Only fetches public documentation +- βœ… Doesn't send your code to the server +- βœ… Read-only access (no mutations) + +Your code and private data never leave your environment. + +## Additional MCP Servers + +You can add other MCP servers alongside CopilotKit: + +```bash +# Add filesystem access +claude mcp add --transport stdio filesystem npx -y @modelcontextprotocol/server-filesystem + +# Add web search +claude mcp add --transport stdio brave-search npx -y @modelcontextprotocol/server-brave-search +``` + +All MCP servers work together and enhance Claude Code capabilities. + +## Support + +If you have issues with the VIBE CODING MCP: + +1. **CopilotKit Discord**: https://discord.gg/copilotkit +2. **CopilotKit GitHub Issues**: https://github.com/CopilotKit/CopilotKit/issues +3. **Claude Code Issues**: https://github.com/anthropics/claude-code/issues + +## Summary + +**To set up the MCP:** +```bash +claude mcp add --transport sse copilotkit-mcp https://mcp.copilotkit.ai/sse +``` + +**To verify:** +```bash +claude mcp list +``` + +**To use:** +Just ask CopilotKit questions! The MCP activates automatically. + +--- + +**The CopilotKit Expert Plugin works with or without MCP, but MCP provides the best experience!** diff --git a/.claude/PLUGIN_COMPLIANCE.md b/.claude/PLUGIN_COMPLIANCE.md new file mode 100644 index 0000000..f064f79 --- /dev/null +++ b/.claude/PLUGIN_COMPLIANCE.md @@ -0,0 +1,159 @@ +# Plugin Structure Compliance + +## Overview + +This plugin now follows the official **Anthropic Claude Code plugin standards (2025)** for marketplace-ready distribution. + +## Official Structure Implemented + +``` +.claude/ +β”œβ”€β”€ .claude-plugin/ +β”‚ └── plugin.json # Official plugin metadata (NEW) +β”œβ”€β”€ commands/ # Slash commands +β”‚ β”œβ”€β”€ copilotkit-docs.md +β”‚ β”œβ”€β”€ copilotkit-integrate.md +β”‚ └── copilotkit-debug.md +β”œβ”€β”€ skills/ # Agent skills +β”‚ └── copilotkit-expert.md +β”œβ”€β”€ COPILOTKIT_PLUGIN.md # Main documentation +β”œβ”€β”€ MCP_SETUP.md # MCP configuration guide +β”œβ”€β”€ QUICKSTART.md # Quick start guide +β”œβ”€β”€ copilotkit-patterns.md # Best practices +β”œβ”€β”€ install-plugin.sh # Installer script +└── plugin-manifest.json # Legacy manifest (kept for compatibility) +``` + +## Changes Made + +### 1. Added `.claude-plugin/plugin.json` + +This is the **official** plugin manifest format required by Anthropic Claude Code for: +- Plugin marketplace distribution +- Version management +- Dependency tracking +- Installation via `claude plugin install` + +The file follows the official schema: +```json +{ + "name": "copilotkit-expert", + "version": "1.0.0", + "description": "...", + "author": { "name": "..." }, + "license": "MIT", + "engines": { "claudeCode": ">=1.0.0" }, + "dependencies": { ... }, + "repository": { ... }, + "keywords": [ ... ] +} +``` + +### 2. Updated `install-plugin.sh` + +- Added `.claude-plugin/plugin.json` to installation files +- Creates `.claude-plugin/` directory during installation +- Hardened with `set -u` and `set -o pipefail` +- Improved path handling to prevent manipulation +- Resolved absolute paths before operations + +### 3. Security Enhancements + +The plugin now includes: +- **Environment variable validation** in API route (route.ts) +- **URL allowlisting** to prevent SSRF attacks +- **Prompt injection protection** in section_writer.py +- **Shell script hardening** with proper error handling + +## Marketplace Compatibility + +This plugin is now ready for: + +1. **Local Distribution**: Copy `.claude/` directory to other projects +2. **Git-based Distribution**: Clone repo and reference `.claude/` path +3. **Official Marketplace**: Publishable to Claude Code marketplace + +## Installation Methods + +### Method 1: Direct Copy +```bash +cp -r .claude /path/to/target/project/ +``` + +### Method 2: Using Installer +```bash +.claude/install-plugin.sh install /path/to/target/project +``` + +### Method 3: Export as Package +```bash +.claude/install-plugin.sh export /tmp/copilotkit-plugin +cd /tmp/copilotkit-plugin +./install.sh install /path/to/target/project +``` + +### Method 4: From Git (Future) +```bash +# When added to a marketplace +claude plugin install copilotkit-expert@marketplace-name +``` + +## Version Compatibility + +### Frontend +- `@copilotkit/react-core`: 1.5.20 +- `@copilotkit/react-ui`: 1.5.20 +- `@copilotkit/runtime`: 1.5.20 + +### Agent +- `copilotkit`: 0.1.70 (compatible with frontend 1.5.20) +- `langgraph-cli`: 0.1.71 + +**Status**: βœ… Versions are aligned and compatible + +## Security Compliance + +### API Route (route.ts) +- βœ… Environment variable validation +- βœ… Fail-closed approach for missing configs +- βœ… URL validation and SSRF prevention +- βœ… Strict localhost checking for local mode + +### Shell Script (install-plugin.sh) +- βœ… `set -u` to catch unset variables +- βœ… `set -o pipefail` for pipeline error handling +- βœ… Absolute path resolution +- βœ… Proper variable quoting + +### Prompt Injection (section_writer.py) +- βœ… User input sanitization +- βœ… Length truncation (max 2000 chars) +- βœ… Removal of special tokens +- βœ… Safe message extraction + +## References + +- [Anthropic Claude Code Plugin Docs](https://code.claude.com/docs/en/plugins) +- [Plugin Marketplace Guide](https://code.claude.com/docs/en/plugin-marketplaces) +- [Official Plugin Schema](https://code.claude.com/docs/en/plugins/schema) + +## Testing + +To verify the plugin structure: +```bash +.claude/install-plugin.sh verify +``` + +## Future Enhancements + +- [ ] Create marketplace.json for multi-plugin distribution +- [ ] Add plugin versioning and update mechanism +- [ ] Implement plugin health checks +- [ ] Add automated testing for plugin installation +- [ ] Create GitHub Action for plugin packaging + +--- + +**Last Updated**: 2025-11-15 +**Plugin Version**: 1.0.0 +**Compliant With**: Anthropic Claude Code Standards 2025 diff --git a/.claude/QUICKSTART.md b/.claude/QUICKSTART.md new file mode 100644 index 0000000..e09add9 --- /dev/null +++ b/.claude/QUICKSTART.md @@ -0,0 +1,455 @@ +# CopilotKit Plugin - Quick Start Guide + +Get started with the CopilotKit Expert Plugin in under 5 minutes! + +## 🎯 What You'll Learn + +- How to use the CopilotKit Expert skill +- How to use CopilotKit slash commands +- Common workflows and examples +- How to leverage the MCP integration + +## ⚑ Quick Examples + +### Example 1: Getting Help with CopilotKit + +**Scenario**: You want to understand how `useCoAgentStateRender` works. + +``` +You: How do I use useCoAgentStateRender to show real-time agent state? + +Claude (activates copilotkit-expert skill): +useCoAgentStateRender is a hook that lets you render UI based on agent state changes. + +Here's a complete example: + +[Provides detailed TypeScript code with explanations] + +The key points are: +1. It subscribes to state updates from your CoAgent +2. You provide a render function that returns JSX +3. The component re-renders automatically when state changes +4. Great for progress indicators, approval UIs, etc. + +In this project, you can see it used in: +- frontend/src/components/structure-proposal-viewer.tsx +- frontend/src/components/progress.tsx +``` + +**Alternative using slash command**: +``` +You: /copilotkit-docs + +Claude: What CopilotKit documentation would you like to explore? + +You: useCoAgentStateRender hook + +Claude (uses MCP to fetch official docs): +[Fetches and displays official documentation with examples] +``` + +### Example 2: Implementing a New Feature + +**Scenario**: Add a progress indicator to your CoAgent. + +``` +You: I want to add a progress indicator that shows which step my agent is on + +Claude (activates copilotkit-expert skill): +I'll help you add a progress indicator with real-time updates. + +Backend (agent/state.py): +--- +[Provides Python code to add progress tracking to state] + +Backend (agent/graph.py): +--- +[Shows how to emit progress updates] + +Frontend (components/ProgressIndicator.tsx): +--- +[Complete React component with useCoAgentStateRender] + +Implementation Steps: +1. Update state schema with progress field +2. Emit state after each step in the agent +3. Create progress component in frontend +4. Add component to your layout + +Test it by: +1. Start agent and frontend +2. Trigger a workflow +3. Watch the progress indicator update in real-time +``` + +**Alternative using slash command**: +``` +You: /copilotkit-integrate + +Claude: What CopilotKit feature would you like to integrate? + +You: A progress indicator showing agent steps + +Claude: +[Provides detailed integration guide with checklist] +[Shows exactly what files to modify] +[Includes testing steps] +``` + +### Example 3: Debugging State Synchronization + +**Scenario**: Your frontend isn't receiving agent state updates. + +``` +You: My frontend isn't showing agent state updates. The state seems stuck. + +Claude (activates copilotkit-expert skill): +Let me help debug this state synchronization issue. + +I'll check the common causes: + +1. State Emission (Backend) + βœ… Checking if copilotkit_emit_state() is called... + [Analyzes agent code] + +2. State Schema Matching + βœ… Comparing Python state vs TypeScript types... + [Compares state.py and types.ts] + +3. Provider Configuration + βœ… Checking CopilotKitProvider setup... + [Reviews layout.tsx] + +Found the issue: +In agent/graph.py:156, you're updating state but not emitting it. + +Fix: +[Shows exact code change needed] + +After this fix, your frontend will receive state updates immediately. +``` + +**Alternative using slash command**: +``` +You: /copilotkit-debug + +Claude: What CopilotKit issue are you experiencing? + +You: State not syncing to frontend + +Claude: +[Runs diagnostic workflow] +[Identifies specific problem] +[Provides fix with explanation] +[Shows verification steps] +``` + +### Example 4: Learning About AG-UI + +**Scenario**: You want to auto-generate forms from Pydantic models. + +``` +You: How do I use AG-UI to generate forms from my Pydantic agent models? + +Claude (activates copilotkit-expert skill): +AG-UI automatically generates beautiful forms from Pydantic models. Here's how: + +Step 1: Define Your Pydantic Model +--- +[Shows Python Pydantic model with Field descriptions] + +Step 2: Install AG-UI +--- +[Shows npm install command] + +Step 3: Create the Form Component +--- +[Complete React component using AG-UI] + +Step 4: Integrate with CoAgent +--- +[Shows how to connect form to agent state] + +The result: +- Automatic field types from Pydantic +- Built-in validation +- Professional styling +- Submit handling +- Error display + +You can customize: +- Field layouts +- Validation messages +- Styling/theming +- Submit behavior +``` + +### Example 5: Multi-Framework Integration + +**Scenario**: Use LangGraph + Anthropic SDK + CopilotKit together. + +``` +You: How do I integrate Claude's streaming with my LangGraph CoAgent? + +Claude (activates copilotkit-expert skill): +Great question! You can combine LangGraph orchestration with Claude's +streaming capabilities. Here's the pattern: + +Architecture: +1. LangGraph manages the workflow +2. Anthropic SDK handles Claude streaming +3. CopilotKit synchronizes state to frontend + +Implementation: +--- +[Shows complete Python code integrating all three] + +Key Points: +1. Create async streaming node in LangGraph +2. Use Anthropic's async streaming client +3. Emit state on each chunk for real-time updates +4. Handle errors gracefully + +Frontend: +--- +[Shows React component to display streaming content] + +This pattern gives you: +βœ… Structured workflow (LangGraph) +βœ… Streaming responses (Anthropic) +βœ… Real-time UI updates (CopilotKit) +``` + +## πŸ› οΈ Common Workflows + +### Workflow 1: Starting a New CoAgent + +1. **Ask for architecture guidance**: + ``` + "I want to create a CoAgent that [describe functionality]" + ``` + +2. **Get complete implementation**: + - Backend state schema (Python) + - LangGraph workflow + - Frontend hooks and components + - Testing instructions + +3. **Implement step-by-step**: + - Follow provided code examples + - Test as you go + - Iterate with feedback + +### Workflow 2: Adding a Feature + +1. **Use the integration command**: + ``` + /copilotkit-integrate + ``` + +2. **Describe the feature**: + ``` + "Add user approval workflow for generated sections" + ``` + +3. **Follow the checklist**: + - Backend changes + - Frontend changes + - Integration testing + +### Workflow 3: Debugging Issues + +1. **Use the debug command**: + ``` + /copilotkit-debug + ``` + +2. **Describe the problem**: + ``` + "Interrupts aren't triggering in my agent" + ``` + +3. **Apply suggested fixes**: + - Review diagnostics + - Implement fixes + - Verify solution + +### Workflow 4: Learning Patterns + +1. **Search documentation**: + ``` + /copilotkit-docs + ``` + +2. **Or ask directly**: + ``` + "Show me best practices for state management in CopilotKit" + ``` + +3. **Reference patterns guide**: + - Check `.claude/copilotkit-patterns.md` + - Find relevant pattern + - Adapt to your use case + +## πŸ“– Understanding the Plugin Components + +### The Expert Agent (Skill) +- **File**: `.claude/skills/copilotkit-expert.md` +- **When it activates**: Automatically when you ask CopilotKit questions +- **What it knows**: CopilotKit, AG-UI, LangGraph, LangChain, Anthropic, OpenAI +- **What it does**: Provides code, explains patterns, debugs issues + +### Slash Commands +- **`/copilotkit-docs`**: Fetch official documentation via MCP +- **`/copilotkit-integrate`**: Step-by-step integration guide +- **`/copilotkit-debug`**: Diagnostic and debugging workflow + +### Patterns Guide +- **File**: `.claude/copilotkit-patterns.md` +- **Contains**: Complete code examples, best practices, anti-patterns +- **Use when**: You need reference implementations + +### MCP Integration +- **Server**: CopilotKit VIBE CODING MCP +- **URL**: https://mcp.copilotkit.ai/sse +- **Provides**: Real-time official docs, code examples, API references + +## πŸŽ“ Learning Path + +### Beginner +1. Use `/copilotkit-docs` to explore basic concepts +2. Ask "How do I create a basic CoAgent?" +3. Review patterns guide for simple examples +4. Build your first CoAgent with guidance + +### Intermediate +1. Ask about state management patterns +2. Learn human-in-the-loop workflows +3. Implement streaming content +4. Use `/copilotkit-integrate` for new features + +### Advanced +1. Explore multi-framework integrations +2. Learn AG-UI auto-generation +3. Optimize performance +4. Build complex multi-agent systems + +## πŸ’‘ Pro Tips + +### Tip 1: Be Specific +``` +❌ "How does CopilotKit work?" +βœ… "How do I emit state from my LangGraph agent to update the frontend?" +``` + +### Tip 2: Use the Right Tool +- **Quick docs lookup** β†’ `/copilotkit-docs` +- **Feature implementation** β†’ `/copilotkit-integrate` +- **Debugging** β†’ `/copilotkit-debug` +- **Complex questions** β†’ Just ask (expert agent activates) + +### Tip 3: Reference Existing Code +``` +"How can I modify frontend/src/components/documents-view.tsx to add +a new streaming section viewer?" +``` + +The expert understands your project structure and can give targeted advice. + +### Tip 4: Ask for Comparisons +``` +"What's the difference between useCoAgent and useCoAgentStateRender?" +"When should I use interrupt() vs regular state emission?" +``` + +### Tip 5: Request Complete Examples +``` +"Show me a complete example of a CoAgent with: +- State synchronization +- Streaming content +- User approval workflow +- Error handling" +``` + +## πŸš€ Your First 5 Minutes + +Try this right now: + +``` +You: /copilotkit-docs + +Claude: What CopilotKit documentation would you like to explore? + +You: CoAgent basics + +Claude: [Fetches and explains CoAgent concepts with examples] +``` + +Then: + +``` +You: Show me how the research agent in this project uses CoAgents + +Claude: [Analyzes agent/graph.py and explains the implementation] +``` + +Finally: + +``` +You: /copilotkit-integrate + +Claude: What CopilotKit feature would you like to integrate? + +You: I want to add a "save draft" feature that stores partial research + +Claude: [Provides complete implementation plan] +``` + +## πŸ“š Next Steps + +1. **Explore the patterns guide**: Open `.claude/copilotkit-patterns.md` +2. **Read plugin docs**: Check `.claude/COPILOTKIT_PLUGIN.md` +3. **Try examples**: Implement one of the examples above +4. **Ask questions**: The expert is always available! + +## ❓ FAQ + +**Q: When should I use a slash command vs asking directly?** + +A: Use slash commands for structured workflows (integration, debugging). + Ask directly for explanations, examples, and general questions. + +**Q: Can the expert help with other frameworks besides CopilotKit?** + +A: Yes! It knows LangGraph, LangChain, Anthropic SDK, OpenAI, and can + help integrate them with CopilotKit. + +**Q: Does the MCP need to be connected?** + +A: The expert works without MCP, but MCP provides access to the latest + official documentation and examples. + +**Q: Can I use this plugin in other projects?** + +A: Absolutely! Copy `.claude/skills/copilotkit-expert.md`, the commands, + and patterns guide to any project. + +**Q: How do I know if the expert agent is activated?** + +A: Claude will use its knowledge of CopilotKit to answer your questions. + The quality and depth of CopilotKit-specific answers indicate activation. + +## πŸŽ‰ Ready to Go! + +You now know how to: +- βœ… Use the CopilotKit Expert skill +- βœ… Run slash commands +- βœ… Debug issues +- βœ… Integrate features +- βœ… Learn patterns + +**Start building amazing CoAgents!** πŸš€ + +--- + +*Need more help? Just ask! The CopilotKit Expert is here to help you succeed.* diff --git a/.claude/README.md b/.claude/README.md new file mode 100644 index 0000000..f09e379 --- /dev/null +++ b/.claude/README.md @@ -0,0 +1,203 @@ +# Claude Code Configuration + +This directory contains Claude Code customizations for the BLOG-CANVAS-COPILOTkit project. + +## Structure + +``` +.claude/ +β”œβ”€β”€ commands/ # Custom slash commands +β”‚ β”œβ”€β”€ start-dev.md # Start full dev environment +β”‚ β”œβ”€β”€ check-health.md # Health check all services +β”‚ β”œβ”€β”€ add-feature.md # Feature addition guide +β”‚ β”œβ”€β”€ debug-agent.md # Agent debugging workflow +β”‚ β”œβ”€β”€ update-deps.md # Dependency update guide +β”‚ β”œβ”€β”€ copilotkit-docs.md # CopilotKit documentation search +β”‚ β”œβ”€β”€ copilotkit-integrate.md # CopilotKit integration guide +β”‚ └── copilotkit-debug.md # CopilotKit debugging helper +β”œβ”€β”€ skills/ # Custom skills +β”‚ └── copilotkit-expert.md # CopilotKit Expert Agent +β”œβ”€β”€ copilotkit-patterns.md # CopilotKit patterns & best practices +β”œβ”€β”€ COPILOTKIT_PLUGIN.md # CopilotKit plugin documentation +└── README.md # This file +``` + +## Available Slash Commands + +### `/start-dev` +Starts the complete development environment: +- LangGraph agent server +- CopilotKit tunnel +- Frontend dev server + +**Usage**: `/start-dev` + +### `/check-health` +Performs comprehensive health check: +- Service status (agent, frontend) +- Environment configuration +- Dependencies +- API connectivity +- Port availability + +**Usage**: `/check-health` + +### `/add-feature` +Interactive guide for adding new features: +- Analyzes feature requirements +- Provides implementation plan +- Guides through frontend/agent/full-stack changes +- Includes testing checklist + +**Usage**: `/add-feature` then describe your feature + +### `/debug-agent` +Debug LangGraph agent issues: +- Analyzes agent logs +- Checks configuration +- Tests state and tools +- Reviews system prompts +- Suggests fixes for common issues + +**Usage**: `/debug-agent` + +### `/update-deps` +Safely update project dependencies: +- Checks current versions +- Shows available updates +- Provides update strategy +- Runs update process +- Verifies functionality + +**Usage**: `/update-deps` + +### `/copilotkit-docs` +Search and fetch CopilotKit documentation using VIBE CODING MCP: +- Search official docs +- Get code examples +- Access latest API references +- Version-specific guidance + +**Usage**: `/copilotkit-docs` then specify what to search for + +### `/copilotkit-integrate` +Guide for integrating CopilotKit features: +- Plans frontend/backend integration +- Provides implementation checklist +- Shows code examples +- Tests integration + +**Usage**: `/copilotkit-integrate` then describe the feature + +### `/copilotkit-debug` +Debug CopilotKit integration issues: +- State synchronization problems +- Streaming content issues +- Interrupt/approval workflows +- Type mismatches +- Performance issues + +**Usage**: `/copilotkit-debug` then describe the issue + +## Available Skills + +### `copilotkit-expert` +Specialized AI agent expert in CopilotKit framework: +- Deep knowledge of CoAgents, AG-UI, and integrations +- Supports LangGraph, LangChain, Anthropic SDK, OpenAI +- Provides complete working examples +- Debugging and optimization guidance +- Access to VIBE CODING MCP for real-time docs + +**Activation**: The skill activates automatically when CopilotKit topics are discussed, or request it explicitly. + +**See**: [COPILOTKIT_PLUGIN.md](./COPILOTKIT_PLUGIN.md) for full documentation + +## πŸš€ CopilotKit Plugin + +This project includes a comprehensive **CopilotKit Expert Plugin** that provides: +- **Expert Agent**: Specialized in CopilotKit, AG-UI, and AI frameworks +- **MCP Integration**: Real-time access to official CopilotKit docs +- **Slash Commands**: Quick access to docs, integration, and debugging +- **Patterns Guide**: Complete reference of best practices + +### Quick Start with CopilotKit Plugin + +1. **Use Slash Commands**: + ``` + /copilotkit-docs + /copilotkit-integrate + /copilotkit-debug + ``` + +2. **Activate Expert Agent**: Just ask CopilotKit questions + ``` + "How do I implement human-in-the-loop with CopilotKit?" + ``` + +3. **Reference Patterns**: Check `copilotkit-patterns.md` for examples + +**Full Plugin Documentation**: [COPILOTKIT_PLUGIN.md](./COPILOTKIT_PLUGIN.md) + +## Creating Custom Commands + +To create a new slash command: + +1. Create a new `.md` file in `.claude/commands/` +2. Add frontmatter with description: + ```markdown + --- + description: Brief description of what this command does + --- + + Command prompt content here... + ``` +3. The command name will be the filename (e.g., `my-command.md` β†’ `/my-command`) + +## Creating Custom Skills + +Skills are reusable, specialized agents that can be invoked during conversations. + +To create a skill: + +1. Create a new `.md` file in `.claude/skills/` +2. Add frontmatter with description +3. Define the skill's capabilities and workflow + +Skills are invoked differently than commands - they run as specialized sub-agents. + +## Project Context + +Claude Code has access to: +- Full codebase (frontend + agent) +- `CLAUDE.md` - comprehensive project documentation +- Git history and status +- Environment files (.env.example) + +For best results: +- Use specific commands for specific tasks +- Refer to CLAUDE.md for architecture details +- Check health before debugging +- Use start-dev for quick setup + +## Tips for Working with Claude Code + +1. **Use slash commands proactively**: Commands like `/check-health` can prevent issues +2. **Leverage context**: Claude understands the full project structure +3. **Iterate incrementally**: Use `/add-feature` to plan before implementing +4. **Debug systematically**: `/debug-agent` follows a logical debugging flow +5. **Keep deps updated**: Regular `/update-deps` prevents drift + +## Resources + +### Project Documentation +- [Project README](../README.md) +- [Project Documentation (CLAUDE.md)](../CLAUDE.md) +- [CopilotKit Plugin Documentation](./COPILOTKIT_PLUGIN.md) +- [CopilotKit Patterns & Best Practices](./copilotkit-patterns.md) + +### Official Documentation +- [Claude Code Documentation](https://docs.claude.com/en/docs/claude-code) +- [CopilotKit Docs](https://docs.copilotkit.ai/) +- [LangGraph Docs](https://langchain-ai.github.io/langgraph/) +- [Anthropic Claude Docs](https://docs.anthropic.com/) diff --git a/.claude/commands/add-feature.md b/.claude/commands/add-feature.md new file mode 100644 index 0000000..f5d8622 --- /dev/null +++ b/.claude/commands/add-feature.md @@ -0,0 +1,66 @@ +--- +description: Guide for adding a new feature to the application +--- + +Guide the user through adding a new feature to BLOG-CANVAS-COPILOTkit. + +## Feature Addition Workflow: + +Ask the user to describe the feature they want to add. Then, based on the feature type, follow the appropriate path: + +### For Frontend Features (UI/UX): + +1. **Analyze requirements**: + - Determine which components need changes + - Identify new components needed + - Consider state management implications + +2. **Implementation plan**: + - Create/modify components in `frontend/src/components/` + - Update types in `frontend/src/lib/types/` + - Add any new hooks in `frontend/src/lib/hooks/` + - Update routing in `frontend/src/app/` if needed + +3. **Integration**: + - Integrate with CopilotKit hooks if AI-related + - Update context providers if state changes + - Add shadcn/ui components if needed + +### For Agent Features (Backend/AI): + +1. **Analyze requirements**: + - Determine if new tools are needed + - Consider state schema changes + - Plan LangGraph workflow modifications + +2. **Implementation plan**: + - Add new tools in `agent/tools/` + - Update `agent/state.py` if state changes + - Modify `agent/graph.py` for new nodes/edges + - Update system prompt in `agent/graph.py` + +3. **Integration**: + - Register new tools in ResearchAgent + - Update CopilotKit state emission + - Add corresponding frontend handling + +### For Full-Stack Features: + +Follow both Frontend and Agent paths, ensuring: +- State synchronization between agent and frontend +- Type consistency across TypeScript and Python +- Proper error handling on both sides + +### Testing Checklist: + +- [ ] Feature works in local development +- [ ] No console errors in frontend +- [ ] Agent logs show expected behavior +- [ ] State updates correctly +- [ ] UI is responsive and accessible +- [ ] Error cases are handled + +After implementation, ask if the user wants to: +- Add tests +- Update documentation (CLAUDE.md) +- Create a custom slash command for this feature diff --git a/.claude/commands/check-health.md b/.claude/commands/check-health.md new file mode 100644 index 0000000..1575069 --- /dev/null +++ b/.claude/commands/check-health.md @@ -0,0 +1,48 @@ +--- +description: Check health status of all services (agent, frontend, APIs) +--- + +Perform a comprehensive health check of the BLOG-CANVAS-COPILOTkit application. + +## Health Checks: + +1. **Agent Service**: + - Check if langgraph process is running + - Test connectivity to http://localhost:8123 (or configured port) + - Verify agent responds to health check + +2. **Frontend Service**: + - Check if Next.js dev server is running + - Test connectivity to http://localhost:3000 (or configured port) + - Verify frontend can reach backend + +3. **Environment Configuration**: + - Verify agent/.env has all required keys: + - OPENAI_API_KEY + - TAVILY_API_KEY + - LANGSMITH_API_KEY + - Verify frontend/.env has all required keys: + - OPENAI_API_KEY + - LANGSMITH_API_KEY + - NEXT_PUBLIC_COPILOT_CLOUD_API_KEY + - Check for any missing or placeholder values + +4. **Dependencies**: + - Check if `frontend/node_modules` exists + - Check if `agent/` has required Python packages installed + - List any missing dependencies + +5. **API Connectivity** (if possible): + - Test OpenAI API key validity (optional) + - Test Tavily API key validity (optional) + - Note: Only test if we can do so without making expensive calls + +6. **Port Availability**: + - Check if ports 8123 (agent), 3000 (frontend) are in use + - Identify what's using them + +Provide a summary report with: +- βœ… Green checks for healthy services +- ⚠️ Warnings for potential issues +- ❌ Red flags for critical problems +- Actionable recommendations to fix issues diff --git a/.claude/commands/copilotkit-debug.md b/.claude/commands/copilotkit-debug.md new file mode 100644 index 0000000..3d30cc5 --- /dev/null +++ b/.claude/commands/copilotkit-debug.md @@ -0,0 +1,259 @@ +--- +description: Debug CopilotKit integration issues (state sync, streaming, interrupts) +--- + +Debug CopilotKit-related issues in the BLOG-CANVAS-COPILOTkit project. + +## Debugging Workflow + +### Step 1: Identify the Issue +Ask the user about the problem: +- State not syncing between agent and frontend? +- Streaming content not working? +- Interrupts not triggering? +- CoAgent not responding? +- Type mismatches? +- Performance issues? + +### Step 2: Gather Information + +Run diagnostic checks: + +**Check Agent Status:** +```bash +cd agent +langgraph status # or check http://localhost:8123 +``` + +**Check Frontend Console:** +- Open browser DevTools +- Check for CopilotKit errors +- Verify state updates in React DevTools + +**Check Logs:** +- Agent logs from LangGraph server +- Frontend console logs +- Network tab for API calls + +### Step 3: Common Issues & Solutions + +#### Issue: State Not Syncing + +**Symptoms:** +- Frontend doesn't receive state updates +- State shows as undefined/null +- Stale state in UI + +**Debug Steps:** +1. Verify `copilotkit_emit_state()` is called in agent +2. Check state schema matches between Python and TypeScript +3. Verify CopilotKitProvider is properly configured +4. Check network requests in DevTools + +**Common Fixes:** +```python +# Ensure state emission after updates +await copilotkit_emit_state(state) +``` + +```typescript +// Verify provider setup + + {children} + +``` + +#### Issue: Streaming Not Working + +**Symptoms:** +- Content doesn't update in real-time +- Loading indicators stuck +- Partial content not showing + +**Debug Steps:** +1. Check if agent emits intermediate states +2. Verify streaming hook setup +3. Check for proper state key paths +4. Verify generator functions are async + +**Common Fixes:** +```python +# Emit state during processing, not just at the end +for item in items: + state["current_item"] = item + await copilotkit_emit_state(state) + process(item) +``` + +```typescript +// Ensure streaming hook is properly configured +const { content } = useStreamingContent({ + stateKey: "sections", + contentKey: "content" +}); +``` + +#### Issue: Interrupts Not Triggering + +**Symptoms:** +- Agent doesn't wait for user approval +- Review UI doesn't appear +- Workflow skips approval step + +**Debug Steps:** +1. Verify `interrupt()` is called in agent +2. Check interrupt identifier is unique +3. Verify frontend has approval UI +4. Check if checkpoint is properly configured + +**Common Fixes:** +```python +# Ensure interrupt is properly called +async def review_node(state): + await copilotkit_emit_state(state) + interrupt("awaiting_approval") # Must be called + return state +``` + +```typescript +// Ensure UI handles the interrupt state +useCoAgentStateRender({ + name: "research_agent", + render: ({ state }) => { + if (state.proposal && !state.outline) { + return ; + } + return null; + } +}); +``` + +#### Issue: Type Mismatches + +**Symptoms:** +- TypeScript errors in frontend +- Python validation errors +- Data shape inconsistencies + +**Debug Steps:** +1. Compare state definitions (state.py vs types.ts) +2. Check for missing fields or wrong types +3. Verify JSON serialization/deserialization +4. Check for optional vs required fields + +**Common Fixes:** +```python +# state.py - Ensure proper typing +class ResearchState(CopilotKitState): + title: str = "" # Default value + sections: list[dict] = [] # Proper list type +``` + +```typescript +// types.ts - Match Python schema +interface ResearchState { + title: string; + sections: Array<{/* ... */}>; +} +``` + +#### Issue: CoAgent Not Responding + +**Symptoms:** +- Chat messages don't trigger agent +- No response from backend +- Timeout errors + +**Debug Steps:** +1. Check agent server is running (port 8123) +2. Verify tunnel is active +3. Check API route configuration +4. Verify API keys are set +5. Check for agent errors in logs + +**Common Fixes:** +```bash +# Restart agent server +cd agent +langgraph up + +# Restart tunnel in new terminal +npx copilotkit@latest dev --port 8123 +``` + +```typescript +// Verify API route +// frontend/src/app/api/copilotkit/route.ts +export const POST = async (req: Request) => { + return new CopilotRuntime({ + url: process.env.AGENT_URL || "http://localhost:8123" + }).response(req); +}; +``` + +### Step 4: Advanced Debugging + +#### Enable Verbose Logging + +**Agent:** +```python +import logging +logging.basicConfig(level=logging.DEBUG) +``` + +**Frontend:** +```typescript +// Add console.log in useEffect +useEffect(() => { + console.log("State updated:", state); +}, [state]); +``` + +#### Check LangSmith Traces +1. Open LangSmith dashboard +2. Find the trace for your request +3. Examine each node execution +4. Check input/output at each step + +#### Network Analysis +1. Open DevTools Network tab +2. Filter by "copilotkit" +3. Examine request/response payloads +4. Check for errors or timeouts + +### Step 5: Performance Issues + +If experiencing slowness: +1. Check token usage in LangSmith +2. Verify streaming is enabled +3. Check for unnecessary state emissions +4. Optimize tool execution +5. Consider caching strategies + +### Verification Checklist + +After fixing, verify: +- [ ] State syncs correctly +- [ ] Streaming works smoothly +- [ ] Interrupts trigger appropriately +- [ ] No console errors +- [ ] Types are consistent +- [ ] Performance is acceptable +- [ ] Error handling works + +## Quick Diagnostic Commands + +```bash +# Check agent health +curl http://localhost:8123/health + +# Check running processes +ps aux | grep langgraph +ps aux | grep copilotkit + +# Check environment variables +cd frontend && cat .env +cd agent && cat .env +``` + +**What CopilotKit issue are you experiencing?** diff --git a/.claude/commands/copilotkit-docs.md b/.claude/commands/copilotkit-docs.md new file mode 100644 index 0000000..62c73e7 --- /dev/null +++ b/.claude/commands/copilotkit-docs.md @@ -0,0 +1,47 @@ +--- +description: Search and fetch CopilotKit documentation using VIBE CODING MCP +--- + +You have access to the **CopilotKit VIBE CODING MCP** server which provides real-time access to official CopilotKit documentation. + +## Your Task + +Ask the user what CopilotKit topic they want to learn about or search for. Then: + +1. **Use the MCP tools** to search/fetch the relevant documentation +2. **Summarize the key points** from the documentation +3. **Provide code examples** if available +4. **Explain how it applies** to the current project (if relevant) + +## Common Topics + +- CoAgents and human-in-the-loop patterns +- React hooks (useCopilotAction, useCoAgent, useCoAgentStateRender, etc.) +- Backend integration (Python SDK, LangGraph integration) +- State management and synchronization +- Streaming content patterns +- AG-UI integration +- Tool creation and binding +- Deployment strategies +- Version migration guides + +## Example Workflow + +1. User asks: "How do I use useCoAgentStateRender?" +2. You use MCP to fetch official docs for that hook +3. You provide: + - Purpose and use case + - API signature + - Working code example + - Integration with this project + - Common pitfalls + +## Tips + +- Always fetch the latest documentation via MCP +- Provide complete, working examples +- Explain the "why" behind the pattern +- Reference existing code in this project when applicable +- Mention version-specific considerations + +**What CopilotKit documentation would you like to explore?** diff --git a/.claude/commands/copilotkit-integrate.md b/.claude/commands/copilotkit-integrate.md new file mode 100644 index 0000000..1a43583 --- /dev/null +++ b/.claude/commands/copilotkit-integrate.md @@ -0,0 +1,131 @@ +--- +description: Guide for integrating CopilotKit features into the project +--- + +Help the user integrate a new CopilotKit feature into the BLOG-CANVAS-COPILOTkit project. + +## Integration Workflow + +### Step 1: Understand the Feature +Ask the user what they want to integrate: +- New CoAgent functionality? +- Additional hooks or actions? +- AG-UI components? +- State management enhancement? +- New streaming pattern? + +### Step 2: Analyze Current Architecture +Review the existing implementation: +- Check `frontend/src/app/api/copilotkit/route.ts` +- Review agent state in `agent/state.py` +- Examine existing hooks in `frontend/src/lib/hooks/` +- Check current CoAgent setup + +### Step 3: Plan the Integration + +#### For Frontend Features: +1. Identify which components need updates +2. Determine new hooks needed +3. Plan state synchronization +4. Consider UX/UI implications + +#### For Agent Features: +1. Determine if new tools are needed +2. Plan state schema changes +3. Design LangGraph workflow modifications +4. Consider interrupt/approval patterns + +#### For Full-Stack Features: +1. Design state schema (Python + TypeScript) +2. Plan backend tools and nodes +3. Design frontend UI and hooks +4. Ensure bidirectional sync + +### Step 4: Implementation Checklist + +**Backend (`/agent`):** +- [ ] Update `state.py` with new state fields +- [ ] Create new tools in `tools/` if needed +- [ ] Modify `graph.py` for new nodes/edges +- [ ] Add `copilotkit_emit_state()` calls +- [ ] Update system prompts if needed + +**Frontend (`/frontend`):** +- [ ] Update types in `src/lib/types/` +- [ ] Create/modify components in `src/components/` +- [ ] Add hooks in `src/lib/hooks/` +- [ ] Update CopilotKit provider if needed +- [ ] Add UI for new features + +**Integration:** +- [ ] Test state synchronization +- [ ] Verify streaming works +- [ ] Test error handling +- [ ] Check interrupt patterns (if applicable) +- [ ] Update documentation + +### Step 5: Testing + +1. Start the agent: `cd agent && langgraph up` +2. Start the tunnel: `npx copilotkit@latest dev --port 8123` +3. Start frontend: `cd frontend && pnpm dev` +4. Test the feature end-to-end + +### CopilotKit Integration Patterns + +#### Adding a New Action +```typescript +// Frontend +useCopilotAction({ + name: "my_action", + description: "Action description", + parameters: [/* ... */], + handler: async ({ param }) => { + // Handle action + } +}); +``` + +#### Adding a New Tool (Agent) +```python +# Backend +@tool +async def my_tool(query: str) -> str: + """Tool description.""" + result = await perform_action(query) + await copilotkit_emit_state({"status": "updated"}) + return result +``` + +#### Adding State Synchronization +```python +# state.py +class ResearchState(CopilotKitState): + my_new_field: str = "" +``` + +```typescript +// types.ts +interface ResearchState { + myNewField: string; +} +``` + +### Common Integrations + +1. **Add a new approval workflow**: Use interrupt + useCoAgentStateRender +2. **Add streaming content**: Use copilotkit_emit_state + useStreamingContent +3. **Add a new tool**: Create in agent/tools/, bind in graph.py +4. **Add AG-UI**: Create Pydantic models, integrate with CoAgent +5. **Add progress indicators**: Emit state logs, render in Progress component + +### Best Practices + +- Keep state schemas in sync (Python ↔ TypeScript) +- Always emit state after significant changes +- Use interrupts for user approval +- Provide clear progress indicators +- Handle errors gracefully on both sides +- Test state sync thoroughly + +**What CopilotKit feature would you like to integrate?** diff --git a/.claude/commands/debug-agent.md b/.claude/commands/debug-agent.md new file mode 100644 index 0000000..9ed8deb --- /dev/null +++ b/.claude/commands/debug-agent.md @@ -0,0 +1,45 @@ +--- +description: Debug issues with the LangGraph agent +--- + +Debug and troubleshoot issues with the LangGraph agent. + +## Debugging Workflow: + +1. **Check agent logs**: + - Look for recent agent output + - Identify error messages or stack traces + - Note which node/tool failed + +2. **Verify configuration**: + - Check `agent/config.py` for correct model setup + - Verify `agent/.env` has valid API keys + - Ensure `agent/langgraph.json` is correct + +3. **Test agent state**: + - Check if state is being properly updated + - Verify state schema in `agent/state.py` + - Look for state serialization issues + +4. **Inspect tool execution**: + - Check which tool is causing issues + - Test tool independently if possible + - Verify tool inputs match expected schema + +5. **Review system prompt**: + - Check if system prompt is properly constructed + - Verify state context is included + - Ensure instructions are clear + +6. **Common issues**: + - **Tool not found**: Check if tool is registered in `self.tools` + - **State update fails**: Verify state schema matches + - **LLM doesn't call tools**: Review system prompt and tool descriptions + - **Interrupt not working**: Check `process_feedback_node` implementation + - **Tavily API errors**: Verify API key and rate limits + +7. **LangSmith debugging**: + - Suggest checking LangSmith trace for execution flow + - Provide LangSmith URL if available + +Provide specific recommendations based on the error pattern identified. diff --git a/.claude/commands/start-dev.md b/.claude/commands/start-dev.md new file mode 100644 index 0000000..a33e2ba --- /dev/null +++ b/.claude/commands/start-dev.md @@ -0,0 +1,38 @@ +--- +description: Start the complete development environment (agent + frontend + tunnel) +--- + +Start the complete development environment for the BLOG-CANVAS-COPILOTkit project. + +## Steps: + +1. **Check environment files**: + - Verify `agent/.env` exists with required keys (OPENAI_API_KEY, TAVILY_API_KEY, LANGSMITH_API_KEY) + - Verify `frontend/.env` exists with required keys (OPENAI_API_KEY, LANGSMITH_API_KEY, NEXT_PUBLIC_COPILOT_CLOUD_API_KEY) + - If missing, list what's needed + +2. **Start the LangGraph agent**: + - Navigate to `agent/` + - Run `langgraph up` in background + - Note the agent URL (typically http://localhost:8123) + - Wait for successful startup confirmation + +3. **Create tunnel to agent**: + - Run `npx copilotkit@latest dev --port 8123` in background + - Note the tunnel URL + +4. **Install frontend dependencies** (if needed): + - Navigate to `frontend/` + - Run `pnpm install` if node_modules is missing or package.json changed + +5. **Start frontend**: + - Navigate to `frontend/` + - Run `pnpm run dev` in background + - Note the frontend URL (typically http://localhost:3000) + +6. **Provide summary**: + - List all running services with their URLs + - Provide instructions to access the app + - Note any errors encountered + +IMPORTANT: Run services in background so user can continue working. Monitor output for errors. diff --git a/.claude/commands/update-deps.md b/.claude/commands/update-deps.md new file mode 100644 index 0000000..505260b --- /dev/null +++ b/.claude/commands/update-deps.md @@ -0,0 +1,73 @@ +--- +description: Update project dependencies (frontend and agent) +--- + +Update dependencies for both frontend and agent, safely and systematically. + +## Dependency Update Process: + +### Frontend Dependencies: + +1. **Check current versions**: + - Navigate to `frontend/` + - Show current package.json versions for major packages: + - Next.js + - React + - CopilotKit packages + - TypeScript + - Tailwind CSS + +2. **Check for updates**: + - Run `pnpm outdated` to see available updates + - Highlight major vs minor vs patch updates + +3. **Update strategy**: + - **Patch updates**: Generally safe, run `pnpm update` + - **Minor updates**: Review changelogs, update selectively + - **Major updates**: Careful review required, especially for: + - Next.js (check migration guides) + - React (breaking changes) + - CopilotKit (API changes) + +4. **Update process**: + - Create backup of package.json and pnpm-lock.yaml + - Update packages + - Run `pnpm install` + - Test build: `pnpm run build` + - Test dev server: `pnpm run dev` + +### Agent Dependencies: + +1. **Check current versions**: + - Navigate to `agent/` + - Show current requirements.txt versions for major packages: + - langchain + - langgraph + - copilotkit + - tavily-python + - langchain-openai + +2. **Check for updates**: + - Run `pip list --outdated` for packages in requirements.txt + +3. **Update strategy**: + - **Pin versions**: Note that langgraph-cli is pinned (0.1.71) + - **langchain-core**: Note version constraint (~=0.3.15) + - **Major updates**: Review changelogs for breaking changes + +4. **Update process**: + - Create backup of requirements.txt + - Update versions in requirements.txt + - Run `pip install -r requirements.txt` + - Test agent: `langgraph up` + +### Post-Update Verification: + +- [ ] Frontend builds without errors +- [ ] Frontend dev server starts +- [ ] Agent starts successfully +- [ ] Full workflow works (search β†’ outline β†’ approve β†’ write) +- [ ] No console/log errors +- [ ] CopilotKit integration still works + +Provide a summary of what was updated and any breaking changes to watch for. diff --git a/.claude/copilotkit-patterns.md b/.claude/copilotkit-patterns.md new file mode 100644 index 0000000..a204982 --- /dev/null +++ b/.claude/copilotkit-patterns.md @@ -0,0 +1,716 @@ +# CopilotKit Patterns & Best Practices + +A comprehensive guide to common CopilotKit patterns and best practices for building CoAgents with human-in-the-loop workflows. + +## Table of Contents + +1. [Core Patterns](#core-patterns) +2. [State Management](#state-management) +3. [Streaming Patterns](#streaming-patterns) +4. [Human-in-the-Loop](#human-in-the-loop) +5. [Framework Integrations](#framework-integrations) +6. [AG-UI Patterns](#ag-ui-patterns) +7. [Performance Optimization](#performance-optimization) +8. [Error Handling](#error-handling) + +--- + +## Core Patterns + +### 1. Basic CoAgent Setup + +#### Backend (LangGraph + CopilotKit) + +```python +# state.py +from copilotkit import CopilotKitState +from typing import Annotated +from langgraph.graph import StateGraph, MessagesState + +class MyAgentState(CopilotKitState, MessagesState): + """Agent state with CopilotKit integration.""" + title: str = "" + content: str = "" + status: str = "idle" + +# graph.py +from langgraph.graph import StateGraph, END +from copilotkit import copilotkit_emit_state, copilotkit_exit + +async def process_node(state: MyAgentState): + """Process node with state emission.""" + # Do work + state["status"] = "processing" + await copilotkit_emit_state(state) + + # More work + result = await perform_task(state) + state["content"] = result + state["status"] = "complete" + + await copilotkit_emit_state(state) + return state + +# Build graph +graph = StateGraph(MyAgentState) +graph.add_node("process", process_node) +graph.set_entry_point("process") +graph.add_edge("process", END) + +agent = graph.compile() +``` + +#### Frontend (React + CopilotKit) + +```typescript +// app/layout.tsx +import { CopilotKit } from "@copilotkit/react-core"; + +export default function RootLayout({ children }) { + return ( + + {children} + + ); +} + +// app/api/copilotkit/route.ts +import { CopilotRuntime, LangGraphAgent } from "@copilotkit/runtime"; + +export const POST = async (req: Request) => { + const runtime = new CopilotRuntime({ + agents: [ + new LangGraphAgent({ + name: "my_agent", + url: process.env.AGENT_URL || "http://localhost:8123", + }), + ], + }); + + return runtime.response(req); +}; + +// components/MyComponent.tsx +import { useCoAgent, useCoAgentStateRender } from "@copilotkit/react-core"; + +export function MyComponent() { + const { state, setState } = useCoAgent({ + name: "my_agent", + initialState: { + title: "", + content: "", + status: "idle", + }, + }); + + return ( +
+

{state.title}

+

{state.content}

+

Status: {state.status}

+
+ ); +} +``` + +--- + +## State Management + +### 1. Bidirectional State Sync + +**Key Principle**: Keep state schemas in sync between Python and TypeScript. + +#### Python State Schema + +```python +from copilotkit import CopilotKitState +from typing import Optional, List +from pydantic import BaseModel + +class Section(BaseModel): + """Section model.""" + title: str + content: str + status: str = "pending" + +class ResearchState(CopilotKitState): + """Research state.""" + title: str = "" + sections: List[Section] = [] + current_section: Optional[int] = None + + # Always emit after changes + async def update_section(self, index: int, content: str): + self.sections[index].content = content + self.sections[index].status = "complete" + await copilotkit_emit_state(self) +``` + +#### TypeScript State Schema + +```typescript +// types.ts +interface Section { + title: string; + content: string; + status: "pending" | "complete"; +} + +interface ResearchState { + title: string; + sections: Section[]; + currentSection: number | null; +} + +// Use the schema +const { state } = useCoAgent({ + name: "research_agent", + initialState: { + title: "", + sections: [], + currentSection: null, + }, +}); +``` + +### 2. State Update Patterns + +```python +# βœ… GOOD: Emit state after each significant update +async def write_section(state: ResearchState, index: int): + state["sections"][index]["status"] = "writing" + await copilotkit_emit_state(state) + + content = await generate_content() + state["sections"][index]["content"] = content + state["sections"][index]["status"] = "complete" + await copilotkit_emit_state(state) + + return state + +# ❌ BAD: Only emit at the end (no progress updates) +async def write_section_bad(state: ResearchState, index: int): + state["sections"][index]["status"] = "writing" + content = await generate_content() + state["sections"][index]["content"] = content + state["sections"][index]["status"] = "complete" + await copilotkit_emit_state(state) # Too late! + return state +``` + +--- + +## Streaming Patterns + +### 1. Streaming Content Generation + +#### Backend: Emit State Incrementally + +```python +async def generate_long_content(state: MyState): + """Generate content with streaming updates.""" + state["content"] = "" + state["status"] = "generating" + await copilotkit_emit_state(state) + + chunks = [] + async for chunk in llm.astream(prompt): + chunks.append(chunk) + state["content"] = "".join(chunks) + await copilotkit_emit_state(state) + + state["status"] = "complete" + await copilotkit_emit_state(state) + return state +``` + +#### Frontend: Use Streaming Hook + +```typescript +import { useStreamingContent } from "@/lib/hooks/useStreamingContent"; + +export function ContentViewer() { + const { content, isStreaming } = useStreamingContent({ + stateKey: "content", + agentName: "my_agent", + }); + + return ( +
+
{content}
+ {isStreaming && } +
+ ); +} +``` + +### 2. Progress Indicators + +```python +# Backend: Emit logs for progress +async def multi_step_process(state: MyState): + state["logs"] = [] + + state["logs"].append({ + "message": "Starting research...", + "level": "info" + }) + await copilotkit_emit_state(state) + + # Step 1 + await step_one() + state["logs"].append({ + "message": "Research complete. Analyzing results...", + "level": "info" + }) + await copilotkit_emit_state(state) + + # Step 2 + await step_two() + state["logs"].append({ + "message": "Analysis complete!", + "level": "success" + }) + await copilotkit_emit_state(state) + + return state +``` + +```typescript +// Frontend: Render progress +import { useCoAgentStateRender } from "@copilotkit/react-core"; + +export function ProgressViewer() { + useCoAgentStateRender({ + name: "my_agent", + render: ({ state }) => ( +
+ {state.logs?.map((log, i) => ( +
+ {log.message} +
+ ))} +
+ ), + }); + + return null; +} +``` + +--- + +## Human-in-the-Loop + +### 1. Approval Workflow Pattern + +#### Backend: Interrupt for Approval + +```python +from langgraph.types import interrupt + +async def propose_outline(state: ResearchState): + """Generate outline and wait for approval.""" + # Generate proposal + outline = await generate_outline(state["title"]) + state["proposal"] = outline + state["status"] = "awaiting_approval" + + # Emit state so frontend can show proposal + await copilotkit_emit_state(state) + + # Interrupt and wait for user feedback + feedback = interrupt("outline_approval") + + # Process feedback + if feedback.get("approved"): + state["outline"] = state["proposal"] + state["status"] = "approved" + else: + state["status"] = "rejected" + state["feedback"] = feedback.get("comments", "") + + state["proposal"] = None + await copilotkit_emit_state(state) + return state +``` + +#### Frontend: Approval UI + +```typescript +import { useCoAgentStateRender } from "@copilotkit/react-core"; +import { useCopilotAction } from "@copilotkit/react-core"; + +export function ApprovalUI() { + // Send approval back to agent + useCopilotAction({ + name: "approve_outline", + description: "Approve or reject the proposed outline", + parameters: [ + { + name: "approved", + type: "boolean", + description: "Whether the outline is approved", + }, + { + name: "comments", + type: "string", + description: "Feedback comments", + required: false, + }, + ], + handler: async ({ approved, comments }) => { + // This will resume the agent with the feedback + return { approved, comments }; + }, + }); + + // Render proposal when available + useCoAgentStateRender({ + name: "research_agent", + render: ({ state }) => { + if (state.status === "awaiting_approval" && state.proposal) { + return ; + } + return null; + }, + }); + + return null; +} + +function ProposalViewer({ proposal }) { + const [comments, setComments] = useState(""); + + return ( +
+

Outline Proposal

+
{/* Render outline */}
+ +