turul-a2a 0.1.4

A2A Protocol v1.0 server framework
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
//! Handler integration tests — exercise handlers through HTTP via storage.
//!
//! Tests cover exact response envelopes, ErrorInfo on error paths,
//! owner/tenant scoping, historyLength, pagination, and push config CRUD.

use std::collections::HashMap;
use std::sync::Arc;

use axum::body::Body;
use http::Request;
use http_body_util::BodyExt;
use tower::ServiceExt;

use turul_a2a::error::A2aError;
use turul_a2a::executor::AgentExecutor;
use turul_a2a::router::{AppState, build_router};
use turul_a2a::storage::InMemoryA2aStorage;
use turul_a2a_types::{Message, Task};

/// Test executor that transitions task to Working then Completed.
struct CompletingExecutor;

#[async_trait::async_trait]
impl AgentExecutor for CompletingExecutor {
    async fn execute(
        &self,
        task: &mut Task,
        _message: &Message,
        _ctx: &turul_a2a::executor::ExecutionContext,
    ) -> Result<(), A2aError> {
        // Move to Working, then Completed
        let mut proto = task.as_proto().clone();
        proto.status = Some(turul_a2a_proto::TaskStatus {
            state: turul_a2a_proto::TaskState::Completed.into(),
            message: None,
            timestamp: None,
        });
        proto.artifacts.push(turul_a2a_proto::Artifact {
            artifact_id: "result-1".into(),
            name: "Result".into(),
            description: String::new(),
            parts: vec![turul_a2a_proto::Part {
                content: Some(turul_a2a_proto::part::Content::Text("done".into())),
                metadata: None,
                filename: String::new(),
                media_type: String::new(),
            }],
            metadata: None,
            extensions: vec![],
        });
        *task = Task::try_from(proto).unwrap();
        Ok(())
    }

    fn agent_card(&self) -> turul_a2a_proto::AgentCard {
        test_agent_card()
    }
}

fn test_agent_card() -> turul_a2a_proto::AgentCard {
    turul_a2a_proto::AgentCard {
        name: "Test Agent".into(),
        description: "A test agent".into(),
        supported_interfaces: vec![turul_a2a_proto::AgentInterface {
            url: "http://localhost:3000".into(),
            protocol_binding: "JSONRPC".into(),
            tenant: String::new(),
            protocol_version: "1.0".into(),
        }],
        provider: None,
        version: "1.0.0".into(),
        documentation_url: None,
        capabilities: Some(turul_a2a_proto::AgentCapabilities {
            streaming: Some(false),
            push_notifications: Some(true),
            extensions: vec![],
            extended_agent_card: Some(false),
        }),
        security_schemes: HashMap::new(),
        security_requirements: vec![],
        default_input_modes: vec!["text/plain".into()],
        default_output_modes: vec!["text/plain".into()],
        skills: vec![],
        signatures: vec![],
        icon_url: None,
    }
}

fn test_state() -> AppState {
    let s = InMemoryA2aStorage::new();
    AppState {
        executor: Arc::new(CompletingExecutor),
        task_storage: Arc::new(s.clone()),
        push_storage: Arc::new(s.clone()),
        event_store: std::sync::Arc::new(s.clone()),
        atomic_store: std::sync::Arc::new(s),
        event_broker: turul_a2a::streaming::TaskEventBroker::new(),
        middleware_stack: std::sync::Arc::new(turul_a2a::middleware::MiddlewareStack::new(vec![])),
        runtime_config: turul_a2a::server::RuntimeConfig::default(),
        in_flight: std::sync::Arc::new(turul_a2a::server::in_flight::InFlightRegistry::new()),
        cancellation_supervisor: std::sync::Arc::new(turul_a2a::storage::InMemoryA2aStorage::new()),
        push_delivery_store: None,
        push_dispatcher: None,
    }
}

async fn json_response(router: axum::Router, req: Request<Body>) -> (u16, serde_json::Value) {
    let resp = router.oneshot(req).await.unwrap();
    let status = resp.status().as_u16();
    let body = resp.into_body().collect().await.unwrap().to_bytes();
    let json = serde_json::from_slice(&body).unwrap_or_default();
    (status, json)
}

fn send_message_json(message_id: &str, text: &str) -> String {
    serde_json::json!({
        "message": {
            "messageId": message_id,
            "role": "ROLE_USER",
            "parts": [{"text": text}]
        }
    })
    .to_string()
}

// =========================================================
// SendMessage — response envelope is SendMessageResponse
// =========================================================

#[tokio::test]
async fn send_message_returns_send_message_response_with_task() {
    let router = build_router(test_state());
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-1", "hello")))
        .unwrap();

    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);

    // SendMessageResponse has oneof: task or message
    // Our executor completes the task, so we expect "task" variant
    assert!(
        body.get("task").is_some() || body.get("message").is_some(),
        "SendMessageResponse must have 'task' or 'message' field, got: {body}"
    );

    if let Some(task) = body.get("task") {
        assert!(task.get("id").is_some(), "Task must have id");
        assert!(task.get("status").is_some(), "Task must have status");
    }
}

#[tokio::test]
async fn send_message_tenant_prefixed_works() {
    let router = build_router(test_state());
    let req = Request::post("/acme/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-t", "hello tenant")))
        .unwrap();

    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert!(
        body.get("task").is_some() || body.get("message").is_some(),
        "Tenant-prefixed SendMessage must return valid response"
    );
}

// =========================================================
// GetTask — returns Task with correct fields
// =========================================================

#[tokio::test]
async fn get_task_returns_task_after_send() {
    let state = test_state();
    let router = build_router(state.clone());

    // First: send a message to create a task
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-g1", "create task")))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Then: get the task
    let router = build_router(state);
    let req = Request::get(format!("/tasks/{task_id}"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(body["id"].as_str().unwrap(), task_id);
    assert!(body.get("status").is_some());
}

#[tokio::test]
async fn get_task_nonexistent_returns_404_with_error_info() {
    let router = build_router(test_state());
    let req = Request::get("/tasks/nonexistent-id")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();

    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 404);

    // Must have ErrorInfo
    let details = body["error"]["details"].as_array().unwrap();
    assert!(!details.is_empty());
    assert_eq!(
        details[0]["@type"],
        "type.googleapis.com/google.rpc.ErrorInfo"
    );
    assert_eq!(details[0]["reason"], "TASK_NOT_FOUND");
    assert_eq!(details[0]["domain"], "a2a-protocol.org");
}

#[tokio::test]
async fn get_task_history_length_zero_omits_history() {
    let state = test_state();

    // Create task via send
    let router = build_router(state.clone());
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-hl", "with history")))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Get with historyLength=0
    let router = build_router(state);
    let req = Request::get(format!("/tasks/{task_id}?historyLength=0"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    // History should be empty or absent (proto3 omits empty repeated)
    let history = body.get("history");
    assert!(
        history.is_none() || history.unwrap().as_array().is_none_or(|a| a.is_empty()),
        "historyLength=0 should omit history"
    );
}

// =========================================================
// CancelTask — 409 on terminal, 200 on cancelable
// =========================================================

#[tokio::test]
async fn cancel_completed_task_returns_409_with_error_info() {
    let state = test_state();

    // Create and complete a task
    let router = build_router(state.clone());
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-c", "complete me")))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Cancel the completed task
    let router = build_router(state);
    let req = Request::post(format!("/tasks/{task_id}:cancel"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 409);

    let details = body["error"]["details"].as_array().unwrap();
    assert_eq!(details[0]["reason"], "TASK_NOT_CANCELABLE");
    assert_eq!(details[0]["domain"], "a2a-protocol.org");
}

#[tokio::test]
async fn cancel_nonexistent_task_returns_404_with_error_info() {
    let router = build_router(test_state());
    let req = Request::post("/tasks/no-such-task:cancel")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 404);

    let details = body["error"]["details"].as_array().unwrap();
    assert_eq!(details[0]["reason"], "TASK_NOT_FOUND");
}

// =========================================================
// ListTasks — pagination fields always present
// =========================================================

#[tokio::test]
async fn list_tasks_returns_required_pagination_fields() {
    let router = build_router(test_state());
    let req = Request::get("/tasks")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();

    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);

    // All REQUIRED per proto ListTasksResponse
    assert!(body.get("tasks").is_some(), "must have tasks array");
    assert!(
        body.get("nextPageToken").is_some(),
        "must have nextPageToken"
    );
    assert!(body.get("pageSize").is_some(), "must have pageSize");
    assert!(body.get("totalSize").is_some(), "must have totalSize");
}

#[tokio::test]
async fn list_tasks_empty_result_still_has_all_fields() {
    let router = build_router(test_state());
    let req = Request::get("/tasks")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();

    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(body["tasks"].as_array().unwrap().len(), 0);
    assert_eq!(body["totalSize"], 0);
}

// =========================================================
// Push notification config — CRUD through HTTP
// =========================================================

#[tokio::test]
async fn push_config_crud_through_http() {
    let state = test_state();

    // Create a task first
    let router = build_router(state.clone());
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-pc", "for push")))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Create push config
    let router = build_router(state.clone());
    let config_body = serde_json::json!({
        "taskId": task_id,
        "url": "https://example.com/webhook"
    })
    .to_string();
    let req = Request::post(format!("/tasks/{task_id}/pushNotificationConfigs"))
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(config_body))
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert!(
        !body["id"].as_str().unwrap_or("").is_empty(),
        "config must have server-generated id"
    );
    let config_id = body["id"].as_str().unwrap();

    // Get push config
    let router = build_router(state.clone());
    let req = Request::get(format!(
        "/tasks/{task_id}/pushNotificationConfigs/{config_id}"
    ))
    .header("a2a-version", "1.0")
    .body(Body::empty())
    .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(body["id"].as_str().unwrap(), config_id);

    // List push configs
    let router = build_router(state.clone());
    let req = Request::get(format!("/tasks/{task_id}/pushNotificationConfigs"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert!(body.get("configs").is_some());

    // Delete push config
    let router = build_router(state.clone());
    let req = Request::builder()
        .method("DELETE")
        .uri(format!(
            "/tasks/{task_id}/pushNotificationConfigs/{config_id}"
        ))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(status, 200);

    // Get after delete returns 404
    let router = build_router(state);
    let req = Request::get(format!(
        "/tasks/{task_id}/pushNotificationConfigs/{config_id}"
    ))
    .header("a2a-version", "1.0")
    .body(Body::empty())
    .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(status, 404);
}

// =========================================================
// Agent card discovery — exact paths
// =========================================================

#[tokio::test]
async fn well_known_agent_card_has_all_required_fields() {
    let router = build_router(test_state());
    let req = Request::get("/.well-known/agent-card.json")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert!(body.get("name").is_some());
    assert!(body.get("description").is_some());
    assert!(body.get("version").is_some());
    assert!(body.get("supportedInterfaces").is_some());
    assert!(body.get("capabilities").is_some());
    assert!(body.get("defaultInputModes").is_some());
    assert!(body.get("defaultOutputModes").is_some());
}

// =========================================================
// [P1] Tenant isolation — tenant from path actually scopes data
// =========================================================

#[tokio::test]
async fn tenant_prefixed_send_scopes_to_tenant() {
    let state = test_state();

    // Create task under tenant "acme"
    let router = build_router(state.clone());
    let req = Request::post("/acme/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-ta", "acme task")))
        .unwrap();
    let (status, send_body) = json_response(router, req).await;
    assert_eq!(status, 200);
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Get the task under tenant "acme" — should find it
    let router = build_router(state.clone());
    let req = Request::get(format!("/acme/tasks/{task_id}"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(status, 200, "Task should be visible under its own tenant");

    // Get the same task under default (no tenant) — should NOT find it
    let router = build_router(state.clone());
    let req = Request::get(format!("/tasks/{task_id}"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(
        status, 404,
        "Task should be invisible under different tenant"
    );

    // Get the same task under tenant "other" — should NOT find it
    let router = build_router(state.clone());
    let req = Request::get(format!("/other/tasks/{task_id}"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(status, 404, "Task should be invisible under wrong tenant");

    // List under "acme" should include it
    let router = build_router(state.clone());
    let req = Request::get("/acme/tasks")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(body["totalSize"], 1);

    // List under default should NOT include it
    let router = build_router(state);
    let req = Request::get("/tasks")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    assert_eq!(
        body["totalSize"], 0,
        "Default tenant should not see acme's tasks"
    );
}

#[tokio::test]
async fn tenant_prefixed_cancel_scopes_to_tenant() {
    let state = test_state();

    // Create task under "acme"
    let router = build_router(state.clone());
    let req = Request::post("/acme/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json("m-tc", "cancel me")))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Cancel under wrong tenant — should fail (404)
    let router = build_router(state.clone());
    let req = Request::post(format!("/other/tasks/{task_id}:cancel"))
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, _) = json_response(router, req).await;
    assert_eq!(status, 404, "Cancel under wrong tenant should return 404");
}

// =========================================================
// [P2] ListTasks status filter — actually narrows results
// =========================================================

#[tokio::test]
async fn list_tasks_status_filter_narrows_results() {
    let state = test_state();

    // Create 2 tasks — both will complete (executor completes them)
    for i in 0..2 {
        let router = build_router(state.clone());
        let req = Request::post("/message:send")
            .header("content-type", "application/json")
            .header("a2a-version", "1.0")
            .body(Body::from(send_message_json(&format!("m-sf-{i}"), "task")))
            .unwrap();
        json_response(router, req).await;
    }

    // List all — should see 2
    let router = build_router(state.clone());
    let req = Request::get("/tasks")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (_, body) = json_response(router, req).await;
    assert_eq!(body["totalSize"], 2);

    // List with status=TASK_STATE_COMPLETED — should see 2 (both completed)
    let router = build_router(state.clone());
    let req = Request::get("/tasks?status=TASK_STATE_COMPLETED")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (_, body) = json_response(router, req).await;
    assert_eq!(body["totalSize"], 2, "Both tasks should be completed");

    // List with status=TASK_STATE_WORKING — should see 0
    let router = build_router(state);
    let req = Request::get("/tasks?status=TASK_STATE_WORKING")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (_, body) = json_response(router, req).await;
    assert_eq!(body["totalSize"], 0, "No tasks should be in working state");
}

#[tokio::test]
async fn list_tasks_invalid_status_returns_400() {
    let router = build_router(test_state());
    let req = Request::get("/tasks?status=NOT_A_REAL_STATE")
        .header("a2a-version", "1.0")
        .body(Body::empty())
        .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 400, "Invalid status value should return 400");
    assert!(
        body["error"]["message"]
            .as_str()
            .unwrap_or("")
            .contains("status"),
        "Error message should mention status"
    );
}

// =========================================================
// [P2] Push config list pagination through HTTP
// =========================================================

#[tokio::test]
async fn push_config_list_pagination_through_http() {
    let state = test_state();

    // Create a task
    let router = build_router(state.clone());
    let req = Request::post("/message:send")
        .header("content-type", "application/json")
        .header("a2a-version", "1.0")
        .body(Body::from(send_message_json(
            "m-pcp",
            "for push pagination",
        )))
        .unwrap();
    let (_, send_body) = json_response(router, req).await;
    let task_id = send_body["task"]["id"].as_str().unwrap();

    // Create 5 push configs
    for i in 0..5 {
        let router = build_router(state.clone());
        let config_body = serde_json::json!({
            "taskId": task_id,
            "url": format!("https://example.com/hook-{i}")
        })
        .to_string();
        let req = Request::post(format!("/tasks/{task_id}/pushNotificationConfigs"))
            .header("content-type", "application/json")
            .header("a2a-version", "1.0")
            .body(Body::from(config_body))
            .unwrap();
        let (status, _) = json_response(router, req).await;
        assert_eq!(status, 200);
    }

    // List with pageSize=2 — should paginate
    let router = build_router(state.clone());
    let req = Request::get(format!(
        "/tasks/{task_id}/pushNotificationConfigs?pageSize=2"
    ))
    .header("a2a-version", "1.0")
    .body(Body::empty())
    .unwrap();
    let (status, body) = json_response(router, req).await;
    assert_eq!(status, 200);
    let configs = body["configs"].as_array().unwrap();
    assert!(configs.len() <= 2, "pageSize=2 should return at most 2");
    assert!(
        !body["nextPageToken"].as_str().unwrap_or("").is_empty(),
        "Should have nextPageToken for next page"
    );
}