caxton 0.1.4

A secure WebAssembly runtime for multi-agent systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
# 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

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `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:

| Endpoint | Rate Limit | Burst |
|----------|------------|-------|
| 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