miyabi-a2a 0.1.2

Agent-to-Agent (A2A) task storage and communication for Miyabi
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
# Miyabi A2A Dashboard - API Reference

**Version**: 1.0.0
**Base URL**: `http://localhost:3001`
**Last Updated**: 2025-10-22

---

## ๐Ÿ“‹ Table of Contents

1. [Authentication]#authentication
2. [Error Handling]#error-handling
3. [Task Management]#task-management
4. [Error Recovery]#error-recovery
5. [WebSocket API]#websocket-api
6. [Type Definitions]#type-definitions

---

## ๐Ÿ” Authentication

**Current Status**: No authentication required (Development mode)

**Production Recommendation**: Implement one of the following:
- API Key authentication via `X-API-Key` header
- OAuth 2.0 / JWT tokens
- GitHub App authentication

---

## โŒ Error Handling

### Error Response Format

All API errors follow this structured format:

```typescript
interface ErrorResponse {
  status: number;         // HTTP status code (400-599)
  error_code: string;     // Machine-readable error code
  message: string;        // Human-readable error message
  details?: string;       // Optional additional context
  request_id?: string;    // Optional request tracing ID
  timestamp: string;      // ISO 8601 timestamp
}
```

### Example Error Response

```json
{
  "status": 404,
  "error_code": "TASK_NOT_FOUND",
  "message": "Task 123 does not exist",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

### Standard Error Codes

| Error Code | HTTP Status | Description |
|------------|-------------|-------------|
| `INVALID_TASK_ID` | 400 | Task ID format is invalid (must be integer) |
| `TASK_NOT_FOUND` | 404 | Task does not exist in storage |
| `INVALID_TASK_STATE` | 409 | Task state doesn't allow requested operation |
| `MAX_RETRIES_EXCEEDED` | 429 | Task has reached maximum retry limit (3) |
| `STORAGE_ERROR` | 500 | Backend storage operation failed |
| `STORAGE_UPDATE_ERROR` | 500 | Failed to update task in storage |

---

## ๐Ÿ“‹ Task Management

### List Tasks

Get a list of all tasks with optional filtering.

**Endpoint**: `GET /api/tasks`

**Query Parameters**:
- `status` (optional): Filter by task status (`submitted`, `working`, `completed`, `failed`, `cancelled`)
- `limit` (optional): Maximum number of results (default: 50, max: 100)

**Request**:
```bash
curl http://localhost:3001/api/tasks?status=failed&limit=10
```

**Response** (200 OK):
```json
{
  "tasks": [
    {
      "id": 123,
      "title": "Generate code for user authentication",
      "description": "Implement JWT-based auth",
      "status": "failed",
      "task_type": "codegen",
      "agent": "codegen-agent",
      "priority": 3,
      "retry_count": 2,
      "created_at": "2025-10-22T04:00:00Z",
      "updated_at": "2025-10-22T04:30:00Z",
      "issue_url": "https://github.com/owner/repo/issues/123"
    }
  ]
}
```

### Get Task by ID

Retrieve a specific task by its ID.

**Endpoint**: `GET /api/tasks/{task_id}`

**Path Parameters**:
- `task_id` (required): Task ID (integer)

**Request**:
```bash
curl http://localhost:3001/api/tasks/123
```

**Response** (200 OK):
```json
{
  "id": 123,
  "title": "Generate code for user authentication",
  "description": "Implement JWT-based auth",
  "status": "failed",
  "task_type": "codegen",
  "agent": "codegen-agent",
  "context_id": null,
  "priority": 3,
  "retry_count": 2,
  "created_at": "2025-10-22T04:00:00Z",
  "updated_at": "2025-10-22T04:30:00Z",
  "issue_url": "https://github.com/owner/repo/issues/123"
}
```

**Response** (404 Not Found):
```json
{
  "status": 404,
  "error_code": "TASK_NOT_FOUND",
  "message": "Task 999 does not exist",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

---

## ๐Ÿ”„ Error Recovery

### Retry Task

Retry a failed task with exponential backoff.

**Endpoint**: `POST /api/tasks/{task_id}/retry`

**Path Parameters**:
- `task_id` (required): Task ID to retry

**Request Body**:
```typescript
interface TaskRetryRequest {
  reason?: string;  // Optional reason for retry
}
```

**Request Example**:
```bash
curl -X POST http://localhost:3001/api/tasks/123/retry \
  -H "Content-Type: application/json" \
  -d '{
    "reason": "Network timeout - retrying with increased timeout"
  }'
```

**Response** (200 OK):
```json
{
  "task_id": "123",
  "status": "submitted",
  "message": "Task 123 has been queued for retry",
  "retry_count": 2
}
```

**Response** (400 Bad Request - Invalid Task ID):
```json
{
  "status": 400,
  "error_code": "INVALID_TASK_ID",
  "message": "Invalid task ID format",
  "details": "Task ID 'abc' must be a valid integer: invalid digit found in string",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

**Response** (404 Not Found):
```json
{
  "status": 404,
  "error_code": "TASK_NOT_FOUND",
  "message": "Task 999 does not exist",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

**Response** (409 Conflict - Invalid State):
```json
{
  "status": 409,
  "error_code": "INVALID_TASK_STATE",
  "message": "Task must be in failed state to retry",
  "details": "Current task status: Completed",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

**Response** (429 Too Many Requests):
```json
{
  "status": 429,
  "error_code": "MAX_RETRIES_EXCEEDED",
  "message": "Maximum retry limit of 3 attempts reached",
  "details": "Current retry count: 3/3",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

**Response** (500 Internal Server Error):
```json
{
  "status": 500,
  "error_code": "STORAGE_UPDATE_ERROR",
  "message": "Failed to update task status",
  "details": "Storage update error for task 123: Connection timeout",
  "timestamp": "2025-10-22T04:30:00Z"
}
```

**Retry Logic**:
1. Validates task exists
2. Checks task is in `Failed` state
3. Checks retry count < 3
4. Increments `retry_count`
5. Updates task status to `Submitted`
6. Calculates exponential backoff delay
7. Broadcasts `TaskRetry` event via WebSocket

**Exponential Backoff**:
- Attempt 1: 10 seconds
- Attempt 2: 20 seconds
- Attempt 3: 40 seconds
- Formula: `10 * 2^(retry_count - 1)`

### Cancel Task

Cancel a running or queued task.

**Endpoint**: `POST /api/tasks/{task_id}/cancel`

**Path Parameters**:
- `task_id` (required): Task ID to cancel

**Request Body**: None

**Request Example**:
```bash
curl -X POST http://localhost:3001/api/tasks/456/cancel \
  -H "Content-Type: application/json"
```

**Response** (200 OK):
```json
{
  "task_id": "456",
  "status": "cancelled",
  "message": "Task 456 has been cancelled"
}
```

**Response** (400 Bad Request - Invalid Task ID):
```json
{
  "status": 400,
  "error_code": "INVALID_TASK_ID",
  "message": "Invalid task ID format",
  "details": "Task ID 'invalid' must be a valid integer: invalid digit found in string",
  "timestamp": "2025-10-22T04:35:00Z"
}
```

**Response** (404 Not Found):
```json
{
  "status": 404,
  "error_code": "TASK_NOT_FOUND",
  "message": "Task 999 does not exist",
  "timestamp": "2025-10-22T04:35:00Z"
}
```

**Response** (409 Conflict - Invalid State):
```json
{
  "status": 409,
  "error_code": "INVALID_TASK_STATE",
  "message": "Task must be in Submitted or Working state to cancel",
  "details": "Current task status: Failed. Only Submitted or Working tasks can be cancelled.",
  "timestamp": "2025-10-22T04:35:00Z"
}
```

**Response** (500 Internal Server Error):
```json
{
  "status": 500,
  "error_code": "STORAGE_UPDATE_ERROR",
  "message": "Failed to update task status",
  "details": "Storage update error for task 456: Network error",
  "timestamp": "2025-10-22T04:35:00Z"
}
```

**Cancel Logic**:
1. Validates task exists
2. Checks task is in `Submitted` or `Working` state
3. Updates task status to `Cancelled`
4. Updates task description with cancellation timestamp
5. Broadcasts `TaskCancel` event via WebSocket

**Cancellable States**:
- โœ… `Submitted`: Queued but not started
- โœ… `Working`: Currently executing
- โŒ `Failed`: Already failed
- โŒ `Completed`: Already completed
- โŒ `Cancelled`: Already cancelled

---

## ๐Ÿ”Œ WebSocket API

### Connection

**Endpoint**: `ws://localhost:3001/ws`

**Protocol**: WebSocket (RFC 6455)

**Connection Example** (JavaScript):
```javascript
const ws = new WebSocket('ws://localhost:3001/ws');

ws.onopen = () => {
  console.log('WebSocket connected');
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('WebSocket closed');
};
```

### Message Format

All WebSocket messages are JSON objects with a `type` field:

```typescript
type DashboardUpdate =
  | { type: 'agents'; agents: Agent[] }
  | { type: 'systemstatus'; status: SystemStatus }
  | { type: 'error'; error: ErrorInfo }
  | { type: 'taskretry'; event: TaskRetryEvent }
  | { type: 'taskcancel'; event: TaskCancelEvent }
  | { type: 'ping' };
```

### Message Types

#### Agents Update

Sent periodically (every 10 seconds) or when agent state changes.

```json
{
  "type": "agents",
  "agents": [
    {
      "id": 1,
      "name": "ใ—ใใ‚‹ใ‚“",
      "role": "Coordinator",
      "category": "coding",
      "status": "active",
      "tasks": 5,
      "color": "leader",
      "description": "ใ‚ฟใ‚นใ‚ฏ็ตฑๆ‹ฌใƒปDAGๅˆ†่งฃ"
    }
  ]
}
```

#### System Status Update

Sent periodically (every 10 seconds) or when system metrics change.

```json
{
  "type": "systemstatus",
  "status": {
    "status": "operational",
    "active_agents": 7,
    "total_agents": 21,
    "active_tasks": 12,
    "queued_tasks": 5,
    "task_throughput": 3.5,
    "avg_completion_time": 45.2
  }
}
```

#### Error Event

Sent when an error occurs in the system.

```json
{
  "type": "error",
  "error": {
    "id": "error-1729576200123",
    "task_id": "123",
    "agent_id": "1",
    "agent_name": "CodeGen Agent",
    "message": "Failed to generate code: Timeout",
    "stack_trace": "Error: Timeout\n  at ...",
    "timestamp": "2025-10-22T04:30:00Z",
    "severity": "critical",
    "is_retryable": true
  }
}
```

#### Task Retry Event โœจ NEW

Sent when a task is retried.

```json
{
  "type": "taskretry",
  "event": {
    "task_id": "123",
    "retry_count": 2,
    "reason": "Network timeout - retrying",
    "next_retry_at": "2025-10-22T04:40:00Z",
    "timestamp": "2025-10-22T04:39:50Z"
  }
}
```

#### Task Cancel Event โœจ NEW

Sent when a task is cancelled.

```json
{
  "type": "taskcancel",
  "event": {
    "task_id": "456",
    "reason": "Task cancelled by user at 2025-10-22 04:35:00",
    "timestamp": "2025-10-22T04:35:00Z"
  }
}
```

#### Ping

Heartbeat message to keep connection alive.

```json
{
  "type": "ping"
}
```

### Connection Lifecycle

1. **Initial Connection**: Client connects to `ws://localhost:3001/ws`
2. **Initial Data**: Server sends current `agents` and `systemstatus`
3. **Periodic Updates**: Server sends updates every 10 seconds
4. **Event-Driven**: Server broadcasts events (retry, cancel, error) immediately
5. **Reconnection**: Client should implement exponential backoff reconnection (3-second interval recommended)

---

## ๐Ÿ“ Type Definitions

### Task

```typescript
interface Task {
  id: number;
  title: string;
  description: string;
  status: TaskStatus;
  task_type: TaskType;
  agent: string | null;
  context_id: string | null;
  priority: number;  // 1-10
  retry_count: number;
  created_at: string;  // ISO 8601
  updated_at: string;  // ISO 8601
  issue_url: string;
}

type TaskStatus = 'submitted' | 'working' | 'completed' | 'failed' | 'cancelled';

type TaskType = 'codegen' | 'review' | 'testing' | 'deployment' | 'documentation' | 'analysis';
```

### Agent

```typescript
interface Agent {
  id: number;
  name: string;
  role: string;
  category: 'coding' | 'business';
  status: 'active' | 'working' | 'idle' | 'error';
  tasks: number;
  color: 'leader' | 'executor' | 'analyst' | 'support';
  description: string;
}
```

### System Status

```typescript
interface SystemStatus {
  status: string;  // 'operational', 'degraded', 'down'
  active_agents: number;
  total_agents: number;
  active_tasks: number;
  queued_tasks: number;
  task_throughput: number;  // tasks per hour
  avg_completion_time: number;  // seconds
}
```

### Error Info

```typescript
interface ErrorInfo {
  id: string;
  task_id?: string;
  agent_id?: string;
  agent_name?: string;
  message: string;
  stack_trace?: string;
  timestamp: string;  // ISO 8601
  severity: 'critical' | 'high' | 'medium' | 'low';
  is_retryable: boolean;
}
```

### Task Retry Event

```typescript
interface TaskRetryEvent {
  task_id: string;
  retry_count: number;
  reason?: string;
  next_retry_at?: string;  // ISO 8601
  timestamp: string;  // ISO 8601
}
```

### Task Cancel Event

```typescript
interface TaskCancelEvent {
  task_id: string;
  reason: string;
  timestamp: string;  // ISO 8601
}
```

### Task Retry Request

```typescript
interface TaskRetryRequest {
  reason?: string;
}
```

### Task Retry Response

```typescript
interface TaskRetryResponse {
  task_id: string;
  status: string;  // 'submitted'
  message: string;
  retry_count: number;
}
```

### Task Cancel Response

```typescript
interface TaskCancelResponse {
  task_id: string;
  status: string;  // 'cancelled'
  message: string;
}
```

### Error Response

```typescript
interface ErrorResponse {
  status: number;
  error_code: string;
  message: string;
  details?: string;
  request_id?: string;
  timestamp: string;  // ISO 8601
}
```

---

## ๐Ÿ“Š Rate Limits

**Current Status**: No rate limiting (Development mode)

**Production Recommendation**:
- Rate limit per IP: 100 requests per minute
- WebSocket connections per IP: 5 concurrent connections
- Retry operations per task: 3 attempts per hour

---

## ๐Ÿ” Security Headers

**Current Status**: Basic CORS enabled

**Production Recommendation**:
```
Access-Control-Allow-Origin: https://your-domain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
```

---

## ๐Ÿ“š Examples

### Complete Retry Flow

```bash
# 1. Get failed task
curl http://localhost:3001/api/tasks/123

# 2. Retry task
curl -X POST http://localhost:3001/api/tasks/123/retry \
  -H "Content-Type: application/json" \
  -d '{"reason": "Timeout - retrying"}'

# 3. Verify task status changed
curl http://localhost:3001/api/tasks/123

# 4. WebSocket receives TaskRetry event
# {
#   "type": "taskretry",
#   "event": {
#     "task_id": "123",
#     "retry_count": 1,
#     "reason": "Timeout - retrying",
#     "next_retry_at": "2025-10-22T04:40:00Z",
#     "timestamp": "2025-10-22T04:39:50Z"
#   }
# }
```

### Complete Cancel Flow

```bash
# 1. Get running task
curl http://localhost:3001/api/tasks/456

# 2. Cancel task
curl -X POST http://localhost:3001/api/tasks/456/cancel \
  -H "Content-Type: application/json"

# 3. Verify task status changed
curl http://localhost:3001/api/tasks/456

# 4. WebSocket receives TaskCancel event
# {
#   "type": "taskcancel",
#   "event": {
#     "task_id": "456",
#     "reason": "Task cancelled by user at 2025-10-22 04:35:00",
#     "timestamp": "2025-10-22T04:35:00Z"
#   }
# }
```

---

**API Reference Version**: 1.0.0
**Last Updated**: 2025-10-22
**Maintained by**: Claude Code (AI Assistant)