routa-server 0.15.1

Routa.js HTTP Server — axum adapter on top of routa-core
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
//! A2A Protocol API
//!
//! /api/a2a/sessions - List active sessions
//! /api/a2a/rpc     - JSON-RPC endpoint + SSE stream
//! /api/a2a/card    - Agent card discovery

use axum::{
    extract::{Path, Query, State},
    response::sse::{Event, KeepAlive, Sse},
    routing::get,
    Json, Router,
};
use chrono::Utc;
use routa_core::models::task::{Task, TaskStatus};
use serde::Deserialize;
use std::convert::Infallible;
use std::time::Duration;
use tokio_stream::StreamExt as _;

use crate::error::ServerError;
use crate::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/sessions", get(list_sessions))
        .route("/rpc", get(rpc_sse).post(rpc_handler))
        .route("/card", get(agent_card))
        .route("/message", axum::routing::post(send_message))
        .route("/tasks", get(list_tasks))
        .route("/tasks/{id}", get(get_task).post(update_task))
}

// ─── /api/a2a/sessions ────────────────────────────────────────────────

async fn list_sessions(
    State(state): State<AppState>,
) -> Result<Json<serde_json::Value>, ServerError> {
    let sessions = state.acp_manager.list_sessions().await;

    let a2a_sessions: Vec<serde_json::Value> = sessions
        .iter()
        .map(|s| {
            serde_json::json!({
                "id": s.session_id,
                "agentName": format!("routa-{}-{}", s.provider.as_deref().unwrap_or("agent"), &s.session_id[..8.min(s.session_id.len())]),
                "provider": s.provider.as_deref().unwrap_or("unknown"),
                "status": "connected",
                "capabilities": [
                    "initialize", "method_list",
                    "session/new", "session/prompt", "session/cancel", "session/load",
                    "list_agents", "create_agent", "delegate_task", "message_agent"
                ],
                "rpcUrl": format!("/api/a2a/rpc?sessionId={}", s.session_id),
                "eventStreamUrl": format!("/api/a2a/rpc?sessionId={}", s.session_id),
                "createdAt": s.created_at,
            })
        })
        .collect();

    Ok(Json(serde_json::json!({
        "sessions": a2a_sessions,
        "count": a2a_sessions.len(),
    })))
}

// ─── /api/a2a/card ────────────────────────────────────────────────────

async fn agent_card() -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "name": "Routa Multi-Agent Coordinator",
        "description": "Multi-agent coordination platform with ACP and MCP support",
        "protocolVersion": "0.3.0",
        "version": "0.1.0",
        "url": "/api/a2a/rpc",
        "skills": [
            {
                "id": "coordination",
                "name": "Agent Coordination",
                "description": "Create, delegate tasks to, and coordinate multiple AI agents",
                "tags": ["coordination", "multi-agent", "orchestration"],
            },
            {
                "id": "acp-proxy",
                "name": "ACP Session Proxy",
                "description": "Proxy access to backend ACP agent sessions",
                "tags": ["acp", "session", "proxy"],
            }
        ],
        "capabilities": { "pushNotifications": true },
        "defaultInputModes": ["text"],
        "defaultOutputModes": ["text"],
        "additionalInterfaces": [{
            "url": "/api/a2a/rpc",
            "transport": "JSONRPC",
        }],
    }))
}

// ─── /api/a2a/rpc POST ───────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct RpcQuery {
    session_id: Option<String>,
}

async fn rpc_handler(
    State(state): State<AppState>,
    Query(query): Query<RpcQuery>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, ServerError> {
    let method = body.get("method").and_then(|m| m.as_str()).unwrap_or("");
    let id = body.get("id").cloned().unwrap_or(serde_json::json!(null));
    let params = body.get("params").cloned().unwrap_or_default();

    let result =
        match method {
            "method_list" => serde_json::json!({
                "methods": [
                    "SendMessage", "GetTask", "ListTasks", "CancelTask",
                    "method_list", "initialize",
                    "session/new", "session/prompt", "session/cancel", "session/load",
                    "list_agents", "create_agent", "delegate_task", "message_agent",
                ]
            }),

            "initialize" => serde_json::json!({
                "protocolVersion": "0.3.0",
                "agentInfo": { "name": "routa-a2a-bridge", "version": "0.1.0" },
                "capabilities": { "sessions": true, "coordination": true, "tasks": true },
            }),

            "SendMessage" => {
                let workspace_id = params
                    .get("metadata")
                    .and_then(|value| value.get("workspaceId"))
                    .and_then(|value| value.as_str())
                    .unwrap_or("default")
                    .to_string();
                let prompt = extract_a2a_prompt(&params)?;
                let task_id = uuid::Uuid::new_v4().to_string();
                let context_id = params
                    .get("message")
                    .and_then(|value| value.get("contextId"))
                    .and_then(|value| value.as_str())
                    .map(ToOwned::to_owned)
                    .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
                let title = prompt
                    .lines()
                    .find(|line| !line.trim().is_empty())
                    .map(|line| truncate_text(line.trim(), 80))
                    .filter(|line| !line.is_empty())
                    .unwrap_or_else(|| "A2A task".to_string());

                let task = Task::new(
                    task_id.clone(),
                    title,
                    prompt,
                    workspace_id,
                    Some(context_id.clone()),
                    None,
                    None,
                    None,
                    None,
                    None,
                    None,
                );
                state.task_store.save(&task).await?;

                let state_clone = state.clone();
                let task_id_clone = task_id.clone();
                tokio::spawn(async move {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                    let _ = state_clone
                        .task_store
                        .update_status(&task_id_clone, &TaskStatus::Completed)
                        .await;
                });

                build_a2a_task_payload(&task, "submitted", Some(Utc::now().to_rfc3339()))
            }

            "GetTask" => {
                let task_id = params
                    .get("id")
                    .and_then(|value| value.as_str())
                    .ok_or_else(|| ServerError::BadRequest("Missing task id".into()))?;
                let task =
                    state.task_store.get(task_id).await?.ok_or_else(|| {
                        ServerError::NotFound(format!("Task {} not found", task_id))
                    })?;
                build_a2a_task_payload(
                    &task,
                    map_task_status_to_a2a_state(&task.status),
                    Some(task.updated_at.to_rfc3339()),
                )
            }

            "ListTasks" => {
                let workspace_id = params
                    .get("workspaceId")
                    .and_then(|value| value.as_str())
                    .unwrap_or("default");
                let tasks = state.task_store.list_by_workspace(workspace_id).await?;
                serde_json::json!({
                    "tasks": tasks
                        .iter()
                        .map(|task| {
                            build_a2a_task_payload(
                                task,
                                map_task_status_to_a2a_state(&task.status),
                                Some(task.updated_at.to_rfc3339()),
                            )["task"].clone()
                        })
                        .collect::<Vec<_>>()
                })
            }

            "CancelTask" => {
                let task_id = params
                    .get("id")
                    .and_then(|value| value.as_str())
                    .ok_or_else(|| ServerError::BadRequest("Missing task id".into()))?;
                state
                    .task_store
                    .update_status(task_id, &TaskStatus::Cancelled)
                    .await?;
                let task =
                    state.task_store.get(task_id).await?.ok_or_else(|| {
                        ServerError::NotFound(format!("Task {} not found", task_id))
                    })?;
                build_a2a_task_payload(&task, "canceled", Some(task.updated_at.to_rfc3339()))
            }

            "list_agents" => {
                let workspace_id = params
                    .get("workspaceId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("default");
                let agents = state.agent_store.list_by_workspace(workspace_id).await?;
                serde_json::json!({ "agents": agents })
            }

            "create_agent" => {
                let name = params
                    .get("name")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| ServerError::BadRequest("Missing name".into()))?;
                let role = params
                    .get("role")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| ServerError::BadRequest("Missing role".into()))?;
                let workspace_id = params
                    .get("workspaceId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("default");

                let agent_role = crate::models::agent::AgentRole::from_str(role)
                    .ok_or_else(|| ServerError::BadRequest(format!("Invalid role: {}", role)))?;

                let agent = crate::models::agent::Agent::new(
                    uuid::Uuid::new_v4().to_string(),
                    name.to_string(),
                    agent_role,
                    workspace_id.to_string(),
                    None,
                    None,
                    None,
                );
                state.agent_store.save(&agent).await?;
                serde_json::json!({ "success": true, "agentId": agent.id })
            }

            "delegate_task" | "message_agent" => {
                // Acknowledge and return stub
                serde_json::json!({
                    "status": "forwarded",
                    "sessionId": query.session_id,
                    "method": method,
                    "message": "Request forwarded to backend session",
                })
            }

            _ => {
                return Ok(Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "error": { "code": -32601, "message": format!("Unknown method: {}", method) }
                })));
            }
        };

    Ok(Json(serde_json::json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": result,
    })))
}

// ─── /api/a2a/rpc GET (SSE) ──────────────────────────────────────────

async fn rpc_sse(
    Query(query): Query<RpcQuery>,
) -> Result<Sse<impl tokio_stream::Stream<Item = Result<Event, Infallible>>>, axum::http::StatusCode>
{
    let session_id = match query.session_id {
        Some(id) => id,
        None => return Err(axum::http::StatusCode::BAD_REQUEST),
    };

    let connected_event = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "notification",
        "params": {
            "type": "connected",
            "sessionId": session_id,
            "message": "A2A event stream connected",
        }
    });

    let initial = tokio_stream::once(Ok::<_, Infallible>(
        Event::default().data(connected_event.to_string()),
    ));

    let heartbeat = tokio_stream::wrappers::IntervalStream::new(tokio::time::interval(
        std::time::Duration::from_secs(30),
    ))
    .map(|_| Ok(Event::default().comment("keep-alive")));

    let stream = initial.chain(heartbeat);

    Ok(Sse::new(stream).keep_alive(KeepAlive::default()))
}

// ─── /api/a2a/message ────────────────────────────────────────────────

/// POST /api/a2a/message — Send a message via the A2A protocol
async fn send_message(Json(body): Json<serde_json::Value>) -> Json<serde_json::Value> {
    let method = body
        .get("method")
        .and_then(|v| v.as_str())
        .unwrap_or("sendMessage");

    let session_id = body
        .get("params")
        .and_then(|p| p.get("sessionId"))
        .and_then(|v| v.as_str())
        .unwrap_or("default");

    Json(serde_json::json!({
        "jsonrpc": "2.0",
        "id": body.get("id"),
        "result": {
            "status": "accepted",
            "method": method,
            "sessionId": session_id,
        }
    }))
}

// ─── /api/a2a/tasks ──────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct TasksQuery {
    session_id: Option<String>,
    workspace_id: Option<String>,
}

/// GET /api/a2a/tasks — List A2A tasks (mapped from Routa tasks)
async fn list_tasks(
    State(state): State<AppState>,
    Query(q): Query<TasksQuery>,
) -> Result<Json<serde_json::Value>, ServerError> {
    let tasks = if let Some(session_id) = &q.session_id {
        state.task_store.list_by_session(session_id).await?
    } else {
        let ws = q.workspace_id.as_deref().unwrap_or("default");
        state.task_store.list_by_workspace(ws).await?
    };
    Ok(Json(serde_json::json!({ "tasks": tasks })))
}

/// GET /api/a2a/tasks/{id} — Get an A2A task by ID
async fn get_task(
    State(state): State<AppState>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, ServerError> {
    state
        .task_store
        .get(&id)
        .await?
        .map(|t| Json(serde_json::json!(t)))
        .ok_or_else(|| ServerError::NotFound(format!("Task {} not found", id)))
}

/// POST /api/a2a/tasks/{id} — Update / respond to an A2A task
async fn update_task(
    State(state): State<AppState>,
    Path(id): Path<String>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, ServerError> {
    if let Some(status) = body.get("status").and_then(|v| v.as_str()) {
        let task_status = crate::models::task::TaskStatus::from_str(status)
            .ok_or_else(|| ServerError::BadRequest(format!("Invalid status: {}", status)))?;
        state.task_store.update_status(&id, &task_status).await?;
        Ok(Json(
            serde_json::json!({ "updated": true, "id": id, "status": status }),
        ))
    } else {
        Ok(Json(
            serde_json::json!({ "updated": false, "id": id, "message": "No status change requested" }),
        ))
    }
}

fn extract_a2a_prompt(params: &serde_json::Value) -> Result<String, ServerError> {
    let parts = params
        .get("message")
        .and_then(|value| value.get("parts"))
        .and_then(|value| value.as_array())
        .ok_or_else(|| ServerError::BadRequest("Missing message parts".into()))?;
    let prompt = parts
        .iter()
        .filter_map(|part| part.get("text").and_then(|value| value.as_str()))
        .map(str::trim)
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("\n");
    if prompt.is_empty() {
        return Err(ServerError::BadRequest(
            "A2A message must contain at least one text part".into(),
        ));
    }
    Ok(prompt)
}

fn truncate_text(text: &str, max_len: usize) -> String {
    if text.chars().count() <= max_len {
        return text.to_string();
    }
    text.chars().take(max_len).collect()
}

fn map_task_status_to_a2a_state(status: &TaskStatus) -> &'static str {
    match status {
        TaskStatus::Completed => "completed",
        TaskStatus::Cancelled => "canceled",
        TaskStatus::Blocked | TaskStatus::NeedsFix => "failed",
        TaskStatus::Pending => "submitted",
        TaskStatus::InProgress | TaskStatus::ReviewRequired => "working",
    }
}

fn build_a2a_task_payload(
    task: &Task,
    state: &str,
    timestamp: Option<String>,
) -> serde_json::Value {
    let timestamp = timestamp.unwrap_or_else(|| Utc::now().to_rfc3339());
    serde_json::json!({
        "task": {
            "id": task.id,
            "contextId": task.session_id,
            "status": {
                "state": state,
                "timestamp": timestamp,
            },
            "history": [{
                "messageId": format!("msg-{}", task.id),
                "role": "user",
                "parts": [{ "text": task.objective }],
                "contextId": task.session_id,
                "taskId": task.id,
            }],
            "artifacts": [],
            "metadata": {
                "workspaceId": task.workspace_id,
                "columnId": task.column_id,
            }
        }
    })
}