Content
# Kablewy Agent Starter - Cloudflare Workers
A production-ready **A2A Protocol v0.3.0** compliant agent with real-time WebSocket support, Kablewy MCP integration, and modern web dashboard.
## Features
### Core Capabilities
- ✅ **A2A Protocol v0.3.0 Compliant** - Full implementation with agent discovery, message handling, and task management
- ✅ **Real-time WebSocket Support** - Instant updates without polling via Durable Objects
- ✅ **Push Notifications** - Webhook notifications for task state changes (A2A spec compliant)
- ✅ **Server-Sent Events (SSE)** - Streaming updates for long-running tasks
- ✅ **Kablewy MCP Integration** - Optional AI-powered responses via Kablewy's context infrastructure
- ✅ **Modern Web Dashboard** - Beautiful Lit-based SPA with real-time updates
- ✅ **Cloudflare Workers Ready** - Optimized for edge deployment with Durable Objects
- ✅ **Comprehensive Testing** - 64+ tests covering protocol compliance, security, and functionality
- ✅ **Production Security** - Authentication, CORS handling, input validation ready
### Dashboard Features
- 📊 **Dashboard** - Real-time stats with WebSocket updates
- 💬 **Messages** - Instant chat with connected agents
- 📋 **Tasks** - Live task progress tracking
- 🤖 **Agents** - Connect and manage remote A2A agents
- ⚙️ **Settings** - Beautiful tabbed interface with connection testing
- 🔌 **Connection Status** - Real-time WebSocket connection indicator
## Quick Start
### 1. Clone and Install
```bash
git clone <your-repo>
cd kablewy-agent-starter-cf
npm install
```
### 2. Build Frontend Assets
```bash
npm run build
```
### 3. Run Locally
```bash
npm run dev
# Visit http://localhost:8787
# WebSocket connects automatically for real-time updates
```
### 4. Run Tests
```bash
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:security # Security tests only
npm run test:frontend # Frontend integration tests
```
### 5. Deploy to Cloudflare
```bash
npm run deploy
```
## Real-time Architecture
### Durable Objects Implementation
This starter uses Cloudflare Durable Objects for real-time state management:
- **WebSocket support** - Bidirectional real-time communication
- **Multiple clients** - All connected browsers stay in sync
- **Instant updates** - No polling, immediate state propagation
- **Auto-reconnection** - Handles network interruptions gracefully
### WebSocket Connection Flow
1. Frontend connects to `/ws` endpoint
2. Worker forwards to AgentSession Durable Object
3. Durable Object accepts WebSocket connection
4. Real-time bidirectional communication established
5. All state changes broadcast to connected clients
## Configuration
### Environment Secrets
Set these via `wrangler secret put`:
```bash
# Required for Kablewy MCP features (optional)
wrangler secret put KABLEWY_API_KEY
wrangler secret put KABLEWY_ORG_ID
wrangler secret put KABLEWY_USER_ID
wrangler secret put KABLEWY_BASE_URL
# Optional authentication for A2A endpoint
wrangler secret put A2A_AUTH_SECRET
```
### Durable Objects Configuration
Automatically configured in `wrangler.toml`:
```toml
[[durable_objects.bindings]]
name = "AGENT_SESSION"
class_name = "AgentSession"
[[migrations]]
tag = "v1"
new_classes = ["AgentSession"]
```
## API Endpoints
### A2A Protocol Endpoints
- `GET /.well-known/agent.json` - Agent discovery endpoint
- `POST /a2a/v1` - JSON-RPC 2.0 message endpoint
- `GET /ws` - WebSocket endpoint for real-time communication
- `GET /stream` - Server-Sent Events endpoint
### A2A Methods
- `message/send` - Send message to agent
- `tasks/get` - Retrieve task status
- `tasks/cancel` - Cancel a task
- `tasks/pushNotificationConfig/set` - Configure webhooks
- `tasks/pushNotificationConfig/get` - Get webhook config
### Support Endpoints
- `GET /health` - Health check
- `GET /api/agent-info` - Agent information
- `GET /api/tasks` - List all tasks
- `GET /` - Web dashboard
## Frontend Dashboard
### Technology Stack
- **Lit 3.3** - Web Components with reactive properties
- **WebSocket Client** - Real-time state synchronization
- **@lit-labs/router** - SPA routing with HTML5 History API
- **@lit/context** - Cross-component state management
- **Tailwind CSS** - Utility-first styling (via CDN)
- **Vite** - Fast build system with code splitting
### Real-time Features
- **Connection Status Indicator** - Shows WebSocket connection state
- **Auto-reconnection** - Exponential backoff on disconnection
- **Message Queueing** - Queues messages when offline
- **State Synchronization** - All tabs stay in sync
- **LocalStorage Fallback** - Works offline
### Key Components
#### WebSocket Client (`websocket-client.js`)
- Handles WebSocket connection lifecycle
- Auto-reconnection with exponential backoff
- Message queueing when disconnected
- Ping/pong keepalive
#### State Management (`simple-a2a-context-ws.js`)
- Event-driven updates via WebSocket
- Automatic state synchronization
- LocalStorage persistence
- Real-time connection status
#### Connection Status (`connection-status.js`)
- Visual connection indicator
- Connection details dropdown
- Reconnect button
- Session information
## Push Notifications (A2A Spec)
Configure webhook notifications for task state changes:
```javascript
// Configure webhook
POST /notifications/config
{
"webhookUrl": "https://your-webhook.com/notify",
"events": ["task.completed", "task.failed"],
"auth": {
"type": "bearer",
"credentials": "your-token"
}
}
```
Supported events:
- `task.created`
- `task.started`
- `task.completed`
- `task.failed`
- `task.cancelled`
- `task.input_required`
- `task.auth_required`
## Server-Sent Events (SSE)
Stream real-time updates for specific tasks:
```javascript
// Connect to SSE stream
const eventSource = new EventSource('/stream?taskId=task_123');
eventSource.onmessage = (event) => {
const update = JSON.parse(event.data);
console.log('Task update:', update);
};
```
## Project Structure
```
src/
├── index.ts # Main worker entry
├── durable-objects/
│ └── AgentSession.ts # Durable Object for real-time state
├── a2a/
│ ├── core.ts # Legacy KV-based handler
│ └── core-durable.ts # Durable Objects handler
├── services/
│ ├── KablewyMCPClient.ts # Kablewy MCP integration
│ └── AgentSessionService.ts # Durable Object service
├── types/ # TypeScript definitions
└── frontend/
├── app-root.js # Main app shell
├── services/
│ └── websocket-client.js # WebSocket client
├── simple-a2a-context-ws.js # Real-time state
├── components/
│ └── connection-status.js # Connection indicator
└── pages/ # Dashboard pages
public/
├── index.html # App entry point
├── manifest.json # PWA manifest
└── assets/
└── favicon/ # Kablewy branding
test/
├── basic.spec.ts # Core functionality
├── security-validation.spec.ts # Security tests
├── task-lifecycle.spec.ts # Task management
└── frontend-integration.spec.ts # UI tests
```
## Development Commands
```bash
# Development
npm run dev # Start dev server with WebSocket support
npm run build # Build frontend with Vite
# Testing
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Coverage report
# Deployment
npm run deploy # Deploy to Cloudflare Workers
npm run cf-typegen # Generate TypeScript types
```
## Testing WebSocket Connection
1. Start development server:
```bash
npm run dev
```
2. Open browser to http://localhost:8787
3. Check connection status:
- Look for green indicator in header
- Click for connection details
- Check browser console for WebSocket logs
4. Test real-time updates:
- Open multiple tabs
- Create a task in one tab
- See it appear instantly in other tabs
## Troubleshooting
### WebSocket Connection Issues
**"WebSocket connection failed"**
- Check browser console for specific error
- Verify Durable Object is configured in wrangler.toml
- Ensure `npm run build` was run before `npm run dev`
**"Connection indicator shows disconnected"**
- Click the indicator for details
- Use "Reconnect" button if available
- Check browser console for WebSocket errors
**Real-time updates not working**
- Verify WebSocket is connected (green indicator)
- Check browser console for errors
- Ensure you're using the WebSocket state manager
### Common Issues
**"Durable Object not found"**
- Deploy once to create: `npm run deploy`
- Check wrangler.toml has Durable Object binding
**Frontend not updating**
- Run `npm run build` before `npm run dev`
- Clear browser cache
- Check WebSocket connection status
**Kablewy MCP features not working**
- Verify API credentials are set
- Check secrets with `wrangler secret list`
- MCP features fallback gracefully when unavailable
## Performance Optimizations
- **WebSocket Connection Pooling** - Single connection for all state
- **Message Batching** - Queued messages sent together
- **Automatic Cleanup** - Old tasks cleaned via alarms
- **Code Splitting** - Routes load on-demand
- **Edge Deployment** - Global distribution via Cloudflare
## Security Features
- **Authentication** - Optional bearer token validation
- **CORS** - Configurable cross-origin policies
- **Input Validation** - Comprehensive request validation
- **WebSocket Security** - Connection authentication
- **Content Security** - XSS protection via Lit templates
## Contributing
1. Fork the repository
2. Create a feature branch
3. Run tests: `npm test`
4. Ensure linting passes
5. Submit a pull request
## License
® Kablewy, LLC. All Rights Reserved
## Support
- **Issues**: Report bugs via GitHub Issues
- **Discussions**: Use GitHub Discussions for questions
- **Documentation**: See `/CLAUDE.md` for AI assistant context
## Acknowledgments
- Built with [Cloudflare Workers](https://workers.cloudflare.com) and [Durable Objects](https://developers.cloudflare.com/workers/learning/using-durable-objects/)
- Implements [A2A Protocol](https://github.com/a2aproject/A2A) v0.3.0
- Powered by [Kablewy MCP](https://kablewy.com) (optional)
- UI components with [Lit](https://lit.dev)
- Styling with [Tailwind CSS](https://tailwindcss.com)