# API Reference
Complete API documentation for Caxton management and control.
## API Overview
Caxton provides both gRPC and REST APIs for management operations. The gRPC API is the primary interface, with REST available as a gateway.
### Base URLs
- **gRPC**: `localhost:50051` (default)
- **REST**: `http://localhost:8080/api/v1`
- **WebSocket**: `ws://localhost:8080/ws`
### Authentication
Include authentication token in requests:
```bash
# REST
curl -H "X-Caxton-Token: your-token" http://localhost:8080/api/v1/agents
# gRPC
grpcurl -H "authorization: Bearer your-token" localhost:50051 caxton.v1.AgentService/ListAgents
```
## Agent Management API
### Deploy Agent
Deploy a new WebAssembly agent with comprehensive lifecycle management.
#### REST
```bash
POST /api/v1/agents
# Request
curl -X POST http://localhost:8080/api/v1/agents \
-H "Content-Type: multipart/form-data" \
-F "wasm=@agent.wasm" \
-F "config={\"name\":\"my-agent\",\"strategy\":\"immediate\",\"resources\":{\"memory\":\"50MB\",\"cpu\":\"100000\"}}"
# Response
{
"agent_id": "agent_123",
"name": "my-agent",
"status": "running",
"deployed_at": "2024-01-15T10:30:00Z",
"version": "1.0.0",
"deployment_id": "deploy_456",
"lifecycle_state": "running",
"resource_limits": {
"memory": "50MB",
"cpu_fuel": 100000
}
}
```
#### Deployment Strategies
Available deployment strategies:
- **`immediate`**: Replace agent instantly (brief interruption)
- **`rolling`**: Gradual replacement with configurable batch size
- **`blue_green`**: Deploy to parallel environment, switch traffic
- **`canary`**: Deploy to subset, gradually increase traffic
### Hot Reload Agent
Update an existing agent without downtime:
```bash
PUT /api/v1/agents/{agent_id}/reload
# Request
curl -X PUT http://localhost:8080/api/v1/agents/agent_123/reload \
-H "Content-Type: multipart/form-data" \
-F "wasm=@agent-v2.wasm" \
-F "config={\"strategy\":\"graceful\",\"traffic_split\":10}"
# Response
{
"hot_reload_id": "reload_789",
"status": "in_progress",
"from_version": "1.0.0",
"to_version": "2.0.0",
"strategy": "graceful",
"started_at": "2024-01-15T10:45:00Z"
}
```
### Agent Lifecycle States
Agents progress through defined states:
- **`unloaded`**: Not present in system
- **`loaded`**: WASM module loaded, not executing
- **`running`**: Actively processing messages
- **`draining`**: Finishing current work before shutdown
- **`stopped`**: Cleanly shut down
- **`failed`**: Encountered error and terminated
#### gRPC
```protobuf
service AgentService {
rpc DeployAgent(DeployAgentRequest) returns (DeployAgentResponse);
}
message DeployAgentRequest {
bytes wasm_module = 1;
AgentConfig config = 2;
}
message AgentConfig {
string name = 1;
ResourceLimits resources = 2;
map<string, string> environment = 3;
repeated string capabilities = 4;
}
message DeployAgentResponse {
string agent_id = 1;
AgentStatus status = 2;
google.protobuf.Timestamp deployed_at = 3;
}
```
### List Agents
Get a list of all deployed agents.
#### REST
```bash
GET /api/v1/agents?status=running&limit=10&offset=0
# Response
{
"agents": [
{
"agent_id": "agent_123",
"name": "my-agent",
"status": "running",
"created_at": "2024-01-15T10:30:00Z",
"resources": {
"memory_used": "25MB",
"cpu_usage": 0.15
}
}
],
"total": 42,
"next_offset": 10
}
```
#### gRPC
```protobuf
message ListAgentsRequest {
AgentStatus status_filter = 1;
int32 limit = 2;
int32 offset = 3;
}
message ListAgentsResponse {
repeated Agent agents = 1;
int32 total = 2;
}
```
### Get Agent Details
Retrieve detailed information about a specific agent.
#### REST
```bash
GET /api/v1/agents/{agent_id}
# Response
{
"agent_id": "agent_123",
"name": "my-agent",
"status": "running",
"version": "1.0.0",
"deployment": {
"strategy": "direct",
"deployed_at": "2024-01-15T10:30:00Z",
"deployed_by": "user@example.com"
},
"resources": {
"limits": {
"memory": "50MB",
"cpu": "100m"
},
"usage": {
"memory": "25MB",
"cpu": "50m"
}
},
"metrics": {
"messages_processed": 1542,
"messages_failed": 3,
"average_latency_ms": 12.5,
"uptime_seconds": 3600
}
}
```
### Update Agent
Update an agent's configuration or code.
#### REST
```bash
PUT /api/v1/agents/{agent_id}
# Request
{
"wasm_module": "base64_encoded_wasm", // Optional
"config": { // Optional
"resources": {
"memory": "100MB"
}
},
"strategy": "blue_green"
}
# Response
{
"agent_id": "agent_123",
"status": "updating",
"deployment_id": "deploy_456"
}
```
### Stop Agent
Stop a running agent gracefully.
#### REST
```bash
POST /api/v1/agents/{agent_id}/stop
# Request
{
"grace_period_seconds": 30,
"drain_messages": true
}
# Response
{
"agent_id": "agent_123",
"status": "draining",
"estimated_completion": "2024-01-15T10:31:00Z"
}
```
### Remove Agent
Remove an agent from the system.
#### REST
```bash
DELETE /api/v1/agents/{agent_id}
# Response
{
"agent_id": "agent_123",
"status": "removed",
"removed_at": "2024-01-15T10:35:00Z"
}
```
## Message API
### Send Message
Send a FIPA message to an agent.
#### REST
```bash
POST /api/v1/messages
# Request
{
"performative": "request",
"sender": "client_001",
"receiver": "agent_123",
"content": {
"action": "process",
"data": {"key": "value"}
},
"conversation_id": "conv_789",
"reply_with": "msg_001"
}
# Response
{
"message_id": "msg_abc123",
"status": "delivered",
"delivered_at": "2024-01-15T10:30:00.123Z"
}
```
#### gRPC
```protobuf
service MessageService {
rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
rpc SendMessageAndWait(SendMessageRequest) returns (MessageReply);
}
message SendMessageRequest {
FipaMessage message = 1;
DeliveryOptions options = 2;
}
message FipaMessage {
string performative = 1;
string sender = 2;
string receiver = 3;
google.protobuf.Struct content = 4;
string conversation_id = 5;
string reply_with = 6;
string in_reply_to = 7;
string ontology = 8;
string language = 9;
}
```
### Subscribe to Messages
Subscribe to message streams via WebSocket.
#### WebSocket
```javascript
// Connect to WebSocket
const ws = new WebSocket('ws://localhost:8080/ws');
// Subscribe to agent messages
ws.send(JSON.stringify({
type: 'subscribe',
filter: {
agents: ['agent_123', 'agent_456'],
performatives: ['inform', 'request']
}
}));
// Receive messages
ws.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received:', message);
};
```
### Query Message History
Retrieve historical messages.
#### REST
```bash
GET /api/v1/messages?conversation_id=conv_789&limit=50
# Response
{
"messages": [
{
"message_id": "msg_001",
"performative": "request",
"sender": "agent_123",
"receiver": "agent_456",
"content": {...},
"timestamp": "2024-01-15T10:30:00Z"
}
],
"total": 150,
"next_cursor": "cursor_abc"
}
```
## Task API
### Create Task
Create a task for distribution among agents.
#### REST
```bash
POST /api/v1/tasks
# Request
{
"name": "process_data",
"description": "Process customer data batch",
"data": {...},
"protocol": "contract_net",
"participants": ["agent_1", "agent_2", "agent_3"],
"timeout_seconds": 300,
"requirements": {
"capabilities": ["data_processing"],
"min_performance_score": 0.8
}
}
# Response
{
"task_id": "task_999",
"status": "created",
"created_at": "2024-01-15T10:30:00Z"
}
```
### Distribute Task
Distribute a task using Contract Net Protocol.
#### REST
```bash
POST /api/v1/tasks/{task_id}/distribute
# Request
{
"strategy": "best_bid",
"max_wait_seconds": 30
}
# Response
{
"task_id": "task_999",
"status": "distributed",
"assigned_to": "agent_456",
"proposals_received": 3,
"winning_bid": {
"agent_id": "agent_456",
"estimated_time": 45,
"confidence": 0.95
}
}
```
### Get Task Status
Check the status of a task.
#### REST
```bash
GET /api/v1/tasks/{task_id}
# Response
{
"task_id": "task_999",
"status": "in_progress",
"assigned_to": "agent_456",
"progress": 0.65,
"started_at": "2024-01-15T10:31:00Z",
"estimated_completion": "2024-01-15T10:32:00Z",
"subtasks": [
{
"id": "subtask_001",
"status": "completed"
},
{
"id": "subtask_002",
"status": "in_progress"
}
]
}
```
## Deployment API
### Create Deployment
Create a new deployment with specific strategy.
#### REST
```bash
POST /api/v1/deployments
# Request
{
"agent_id": "agent_123",
"wasm_module": "base64_encoded_wasm",
"version": "2.0.0",
"strategy": {
"type": "canary",
"stages": [
{"percentage": 10, "duration": "5m"},
{"percentage": 50, "duration": "10m"},
{"percentage": 100, "duration": "0"}
],
"rollback_on_error": true,
"error_threshold": 0.05
}
}
# Response
{
"deployment_id": "deploy_888",
"status": "initializing",
"created_at": "2024-01-15T10:30:00Z"
}
```
### Monitor Deployment
Monitor deployment progress.
#### REST
```bash
GET /api/v1/deployments/{deployment_id}
# Response
{
"deployment_id": "deploy_888",
"status": "in_progress",
"current_stage": 2,
"current_percentage": 50,
"metrics": {
"success_rate": 0.98,
"error_count": 5,
"latency_p99": 125.5
},
"stages": [
{
"stage": 1,
"percentage": 10,
"status": "completed",
"completed_at": "2024-01-15T10:35:00Z"
},
{
"stage": 2,
"percentage": 50,
"status": "in_progress",
"started_at": "2024-01-15T10:35:00Z"
}
]
}
```
### Rollback Deployment
Rollback a deployment to previous version.
#### REST
```bash
POST /api/v1/deployments/{deployment_id}/rollback
# Request
{
"reason": "High error rate detected"
}
# Response
{
"deployment_id": "deploy_888",
"status": "rolling_back",
"rollback_to_version": "1.0.0",
"estimated_completion": "2024-01-15T10:37:00Z"
}
```
## Metrics API
### Get System Metrics
Retrieve system-wide metrics.
#### REST
```bash
GET /api/v1/metrics/system
# Response
{
"timestamp": "2024-01-15T10:30:00Z",
"agents": {
"total": 42,
"running": 40,
"failed": 2
},
"messages": {
"total_processed": 1000000,
"rate_per_second": 1500,
"queue_size": 250
},
"resources": {
"cpu_usage_percent": 45.2,
"memory_used_mb": 2048,
"memory_available_mb": 6144,
"disk_used_gb": 10.5
},
"performance": {
"message_latency_p50": 10.5,
"message_latency_p99": 125.3,
"agent_spawn_time_ms": 85.2
}
}
```
### Get Agent Metrics
Get metrics for a specific agent.
#### REST
```bash
GET /api/v1/metrics/agents/{agent_id}?period=1h
# Response
{
"agent_id": "agent_123",
"period": "1h",
"metrics": {
"messages_processed": 5432,
"messages_failed": 12,
"average_latency_ms": 15.3,
"cpu_usage": {
"average": 0.25,
"peak": 0.85
},
"memory_usage": {
"average_mb": 32,
"peak_mb": 48
},
"errors": [
{
"timestamp": "2024-01-15T10:15:00Z",
"error": "timeout",
"count": 3
}
]
}
}
```
## WebSocket Events
Real-time event streaming via WebSocket.
### Event Types
```javascript
// Agent lifecycle events
{
"type": "agent.deployed",
"agent_id": "agent_123",
"timestamp": "2024-01-15T10:30:00Z"
}
// Message events
{
"type": "message.sent",
"message_id": "msg_456",
"from": "agent_123",
"to": "agent_456",
"performative": "inform"
}
// Task events
{
"type": "task.completed",
"task_id": "task_999",
"agent_id": "agent_456",
"result": "success"
}
// System events
{
"type": "system.alert",
"severity": "warning",
"message": "High memory usage detected",
"details": {
"memory_percent": 85
}
}
```
### Subscription Management
```javascript
// Subscribe to specific event types
ws.send(JSON.stringify({
type: 'subscribe',
events: ['agent.*', 'task.completed'],
filters: {
agent_ids: ['agent_123']
}
}));
// Unsubscribe
ws.send(JSON.stringify({
type: 'unsubscribe',
subscription_id: 'sub_123'
}));
```
## Error Responses
All APIs use consistent error responses:
```json
{
"error": {
"code": "AGENT_NOT_FOUND",
"message": "Agent with ID 'agent_999' not found",
"details": {
"agent_id": "agent_999",
"searched_at": "2024-01-15T10:30:00Z"
},
"trace_id": "trace_abc123"
}
}
```
### Error Codes
| `AGENT_NOT_FOUND` | 404 | Agent does not exist |
| `AGENT_ALREADY_EXISTS` | 409 | Agent name already in use |
| `INVALID_WASM` | 400 | Invalid WebAssembly module |
| `RESOURCE_LIMIT_EXCEEDED` | 429 | Resource limits exceeded |
| `DEPLOYMENT_FAILED` | 500 | Deployment operation failed |
| `MESSAGE_DELIVERY_FAILED` | 500 | Message could not be delivered |
| `UNAUTHORIZED` | 401 | Authentication required |
| `FORBIDDEN` | 403 | Operation not permitted |
| `RATE_LIMITED` | 429 | Rate limit exceeded |
| `INTERNAL_ERROR` | 500 | Internal server error |
## SDK Examples
### JavaScript/TypeScript
```typescript
import { CaxtonClient } from '@caxton/sdk';
const client = new CaxtonClient({
endpoint: 'http://localhost:8080',
apiKey: 'your-api-key'
});
// Deploy an agent
const agent = await client.deployAgent({
wasmModule: fs.readFileSync('agent.wasm'),
config: {
name: 'my-agent',
resources: {
memory: '50MB'
}
}
});
// Send a message
const response = await client.sendMessage({
performative: 'request',
receiver: agent.id,
content: { action: 'process' }
});
// Subscribe to events
client.on('agent.failed', (event) => {
console.log('Agent failed:', event);
});
```
### Python
```python
from caxton import CaxtonClient
client = CaxtonClient(
endpoint='http://localhost:8080',
api_key='your-api-key'
)
# Deploy an agent
with open('agent.wasm', 'rb') as f:
agent = client.deploy_agent(
wasm_module=f.read(),
config={
'name': 'my-agent',
'resources': {'memory': '50MB'}
}
)
# Send and wait for reply
reply = client.send_message_and_wait(
performative='request',
receiver=agent.id,
content={'action': 'process'},
timeout=30
)
# Query metrics
metrics = client.get_agent_metrics(
agent_id=agent.id,
period='1h'
)
```
### Go
```go
package main
import (
"github.com/caxton/caxton-go"
)
func main() {
client := caxton.NewClient(
caxton.WithEndpoint("localhost:50051"),
caxton.WithAPIKey("your-api-key"),
)
// Deploy agent
agent, err := client.DeployAgent(ctx, &caxton.DeployRequest{
WasmModule: wasmBytes,
Config: &caxton.AgentConfig{
Name: "my-agent",
Resources: &caxton.Resources{
Memory: "50MB",
},
},
})
// Send message
resp, err := client.SendMessage(ctx, &caxton.Message{
Performative: "request",
Receiver: agent.ID,
Content: map[string]interface{}{
"action": "process",
},
})
}
```
## Rate Limiting
API rate limits per endpoint:
| Agent deployment | 10/min | 20 |
| Message sending | 1000/sec | 2000 |
| Metrics queries | 100/min | 200 |
| System operations | 50/min | 100 |
Rate limit headers:
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 950
X-RateLimit-Reset: 1642248000
```
## Next Steps
- [Message Protocols](message-protocols.md) - FIPA protocol details
- [Building Agents](building-agents.md) - Agent development guide
- [WebAssembly Integration](wasm-integration.md) - WASM specifics
- [Testing Guide](testing.md) - Testing strategies