turul-a2a 0.1.17

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
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
//! JSON-RPC 2.0 dispatch layer.
//!
//! Routes JSON-RPC method calls to the same core handler functions used by HTTP routes.
//! Method names match `turul_a2a_types::wire::jsonrpc` constants (PascalCase, A2A v1.0).
//!
//! A2A v0.3 compatibility: method name normalization is delegated to
//! `compat_v03::normalize_jsonrpc_method` — see that module for details.
//!
//! Streaming methods (`SendStreamingMessage`, `SubscribeToTask`) return SSE responses
//! with each event wrapped in a JSON-RPC response envelope.

use std::sync::Arc;
use std::time::Duration;

use axum::Json;
use axum::extract::State;
use axum::response::IntoResponse;
use axum::response::sse::{Event, KeepAlive, Sse};
use serde_json::{Value, json};
use tokio::sync::broadcast;
use tokio_stream::wrappers::ReceiverStream;

use turul_a2a_types::wire::jsonrpc as methods;
use turul_a2a_types::{Message, Task, TaskState, TaskStatus};

use crate::error::A2aError;
use crate::router::AppState;
use crate::storage::A2aEventStore;
use crate::streaming::{self, StreamEvent, replay};

/// JSON-RPC 2.0 dispatch handler.
///
/// POST /jsonrpc — accepts JSON-RPC 2.0 requests and dispatches to core handlers.
pub async fn jsonrpc_dispatch_handler(
    State(state): State<AppState>,
    axum::Extension(ctx): axum::Extension<crate::middleware::RequestContext>,
    headers: axum::http::HeaderMap,
    body: String,
) -> axum::response::Response {
    let owner = ctx.identity.owner().to_string();
    let claims = ctx.identity.claims().cloned();
    // 1. Parse JSON
    let value: Value = match serde_json::from_str(&body) {
        Ok(v) => v,
        Err(_) => {
            return Json(jsonrpc_error(Value::Null, -32700, "Parse error", None)).into_response();
        }
    };

    // 2. Validate JSON-RPC 2.0 envelope
    let jsonrpc = value.get("jsonrpc").and_then(|v| v.as_str());
    if jsonrpc != Some("2.0") {
        let id = value.get("id").cloned().unwrap_or(Value::Null);
        return Json(jsonrpc_error(
            id,
            -32600,
            "Invalid Request: missing or wrong jsonrpc version",
            None,
        ))
        .into_response();
    }

    let raw_method = match value.get("method").and_then(|v| v.as_str()) {
        Some(m) => m,
        None => {
            let id = value.get("id").cloned().unwrap_or(Value::Null);
            return Json(jsonrpc_error(
                id,
                -32600,
                "Invalid Request: missing method",
                None,
            ))
            .into_response();
        }
    };

    // Method resolution: canonical v1.0 pass-through, or v0.3 compat normalization
    #[cfg(feature = "compat-v03")]
    let method = {
        let mode = crate::compat_v03::detect_compat_mode(raw_method, &headers);
        if mode == crate::compat_v03::CompatMode::V03 {
            let normalized = crate::compat_v03::maybe_normalize_method(raw_method, mode);
            tracing::info!(
                raw_method = %raw_method,
                normalized_method = %normalized,
                "A2A v0.3 compatibility mode activated"
            );
            normalized
        } else {
            raw_method.to_string()
        }
    };
    #[cfg(not(feature = "compat-v03"))]
    let method = raw_method.to_string();

    // 3. Check if this is a notification (no "id" field = notification, must not reply)
    let is_notification = !value.as_object().is_some_and(|o| o.contains_key("id"));
    let id = value.get("id").cloned().unwrap_or(Value::Null);

    // Reject explicit `id: null`. Notifications are signalled by the absence
    // of the `id` key, not by `id: null`. Aligning with that reading lets the
    // server use a String|Number id type internally with no Null variant.
    // The rejection response carries `id: null` per JSON-RPC 2.0 §5.1
    // (id MUST be Null when the request id cannot be detected/used).
    if !is_notification && id.is_null() {
        return Json(jsonrpc_error(
            Value::Null,
            -32600,
            "Invalid Request: id must be a string or number",
            None,
        ))
        .into_response();
    }

    // 4. Validate params: must be object, null, or absent. Arrays/scalars are -32602.
    #[cfg_attr(not(feature = "compat-v03"), allow(unused_mut))]
    let mut params = match value.get("params") {
        None => json!({}),
        Some(Value::Null) => json!({}),
        Some(Value::Object(_)) => value.get("params").cloned().unwrap(),
        Some(_) => {
            if is_notification {
                return axum::http::StatusCode::NO_CONTENT.into_response();
            }
            return Json(jsonrpc_error(
                id,
                -32602,
                "Invalid params: params must be an object",
                None,
            ))
            .into_response();
        }
    };

    // A2A v0.3 compat: normalize params (role enums, part formats) before dispatch
    #[cfg(feature = "compat-v03")]
    {
        let mode = crate::compat_v03::detect_compat_mode(raw_method, &headers);
        crate::compat_v03::maybe_normalize_params(&mut params, mode);
    }

    // 5. Extract tenant from params
    let tenant = params
        .get("tenant")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();

    // 6. Streaming methods return SSE directly (bypass normal dispatch)
    if method == methods::SEND_STREAMING_MESSAGE || method == methods::SUBSCRIBE_TO_TASK {
        if is_notification {
            return axum::http::StatusCode::NO_CONTENT.into_response();
        }

        // Extract Last-Event-ID from HTTP header (Turul extension for JSON-RPC resume).
        // The proto SubscribeToTaskRequest has no cursor field, but since JSON-RPC
        // streaming runs over HTTP, clients MAY send this header for resumable replay.
        let last_event_id = headers
            .get("Last-Event-ID")
            .or_else(|| headers.get("last-event-id"))
            .and_then(|v| v.to_str().ok())
            .map(String::from);

        return match dispatch_streaming(
            state,
            &method,
            &tenant,
            &owner,
            claims,
            params,
            id.clone(),
            last_event_id.as_deref(),
        )
        .await
        {
            Ok(response) => response,
            Err(e) => Json(e.to_jsonrpc_error(Some(&id))).into_response(),
        };
    }

    // 7. Non-streaming dispatch.
    //
    // Notifications run dispatch for side effects, then drop the response.
    if is_notification {
        let _ = dispatch(state, &method, &tenant, &owner, claims, params).await;
        return axum::http::StatusCode::NO_CONTENT.into_response();
    }

    // Route known non-streaming methods through turul-rpc when the id and
    // params are representable as turul-rpc types. Unknown methods, exotic
    // numeric ids (non-i64), and any other edge cases fall back to the
    // legacy direct path so wire behavior stays unchanged.
    let representable_id = match &id {
        Value::String(s) => Some(turul_rpc::RequestId::String(s.clone())),
        Value::Number(n) => n.as_i64().map(turul_rpc::RequestId::Number),
        _ => None,
    };
    let method_is_known_non_streaming = matches!(
        method.as_str(),
        methods::SEND_MESSAGE
            | methods::GET_TASK
            | methods::LIST_TASKS
            | methods::CANCEL_TASK
            | methods::GET_EXTENDED_AGENT_CARD
            | methods::CREATE_TASK_PUSH_NOTIFICATION_CONFIG
            | methods::GET_TASK_PUSH_NOTIFICATION_CONFIG
            | methods::LIST_TASK_PUSH_NOTIFICATION_CONFIGS
            | methods::DELETE_TASK_PUSH_NOTIFICATION_CONFIG
    );

    if let (Some(rid), true) = (representable_id, method_is_known_non_streaming) {
        let params_obj: std::collections::HashMap<String, Value> = match &params {
            Value::Object(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
            _ => std::collections::HashMap::new(),
        };
        let request = turul_rpc::JsonRpcRequest::new(
            rid,
            method.clone(),
            Some(turul_rpc::RequestParams::Object(params_obj)),
        );
        let mut session_ctx = turul_rpc::SessionContext {
            session_id: String::new(),
            metadata: std::collections::HashMap::new(),
            broadcaster: None,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .unwrap_or(0),
            extensions: std::collections::HashMap::new(),
        };
        session_ctx
            .extensions
            .insert("tenant".to_string(), Value::String(tenant.clone()));
        session_ctx
            .extensions
            .insert("owner".to_string(), Value::String(owner.clone()));
        if let Some(c) = claims.clone() {
            session_ctx.extensions.insert("claims".to_string(), c);
        }

        let mut dispatcher = turul_rpc::JsonRpcDispatcher::<A2aError>::new();
        dispatcher.set_default_handler(A2aJsonRpcHandler {
            state: state.clone(),
        });
        let msg = dispatcher
            .handle_request_with_context(request, session_ctx)
            .await;

        #[cfg_attr(not(feature = "compat-v03"), allow(unused_mut))]
        let mut response = serde_json::to_value(&msg)
            .expect("JsonRpcMessage serialization is infallible for in-memory values");
        #[cfg(feature = "compat-v03")]
        {
            let mode = crate::compat_v03::detect_compat_mode(raw_method, &headers);
            crate::compat_v03::maybe_normalize_response(&mut response, mode);
        }
        return Json(response).into_response();
    }

    // Fallback: direct dispatch for unknown methods and non-i64 numeric ids.
    let result = dispatch(state, &method, &tenant, &owner, claims, params).await;

    match result {
        Ok(value) => {
            #[cfg_attr(not(feature = "compat-v03"), allow(unused_mut))]
            let mut response = jsonrpc_success(id, value);
            #[cfg(feature = "compat-v03")]
            {
                let mode = crate::compat_v03::detect_compat_mode(raw_method, &headers);
                crate::compat_v03::maybe_normalize_response(&mut response, mode);
            }
            Json(response).into_response()
        }
        Err(ref e) if matches!(e, A2aError::InvalidRequest { message } if message == "Method not found") => {
            Json(jsonrpc_error(id, -32601, "Method not found", None)).into_response()
        }
        Err(e) => Json(e.to_jsonrpc_error(Some(&id))).into_response(),
    }
}

/// Adapter from turul-rpc's typed handler trait into A2A's existing dispatch
/// table. The outer handler (`jsonrpc_dispatch_handler`) guarantees by
/// construction that `method` is a known non-streaming A2A method, that
/// `params` is `RequestParams::Object`, and that `session_context` carries
/// tenant/owner/claims under those keys.
struct A2aJsonRpcHandler {
    state: AppState,
}

#[async_trait::async_trait]
impl turul_rpc::JsonRpcHandler for A2aJsonRpcHandler {
    type Error = A2aError;

    async fn handle(
        &self,
        method: &str,
        params: Option<turul_rpc::RequestParams>,
        session_context: Option<turul_rpc::SessionContext>,
    ) -> Result<Value, Self::Error> {
        let ctx = session_context.expect("outer A2A handler always populates SessionContext");
        let tenant = ctx
            .extensions
            .get("tenant")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let owner = ctx
            .extensions
            .get("owner")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let claims = ctx.extensions.get("claims").cloned();

        let params_value = match params {
            Some(turul_rpc::RequestParams::Object(map)) => Value::Object(map.into_iter().collect()),
            _ => json!({}),
        };

        dispatch(
            self.state.clone(),
            method,
            &tenant,
            &owner,
            claims,
            params_value,
        )
        .await
    }
}

async fn dispatch(
    state: AppState,
    method: &str,
    tenant: &str,
    owner: &str,
    claims: Option<serde_json::Value>,
    params: Value,
) -> Result<Value, A2aError> {
    match method {
        methods::SEND_MESSAGE => dispatch_send_message(state, tenant, owner, claims, params).await,
        methods::GET_TASK => dispatch_get_task(state, tenant, owner, params).await,
        methods::LIST_TASKS => dispatch_list_tasks(state, tenant, owner, params).await,
        methods::CANCEL_TASK => dispatch_cancel_task(state, tenant, owner, params).await,
        methods::GET_EXTENDED_AGENT_CARD => dispatch_get_extended_agent_card(state).await,
        methods::CREATE_TASK_PUSH_NOTIFICATION_CONFIG => {
            dispatch_create_push_config(state, tenant, owner, params).await
        }
        methods::GET_TASK_PUSH_NOTIFICATION_CONFIG => {
            dispatch_get_push_config(state, tenant, owner, params).await
        }
        methods::LIST_TASK_PUSH_NOTIFICATION_CONFIGS => {
            dispatch_list_push_configs(state, tenant, owner, params).await
        }
        methods::DELETE_TASK_PUSH_NOTIFICATION_CONFIG => {
            dispatch_delete_push_config(state, tenant, owner, params).await
        }
        // Streaming methods handled before dispatch() is called
        methods::SEND_STREAMING_MESSAGE | methods::SUBSCRIBE_TO_TASK => Err(A2aError::Internal(
            "Streaming methods should not reach dispatch()".into(),
        )),
        _ => Err(method_not_found(method)),
    }
}

// =========================================================
// JSON-RPC streaming dispatch
// =========================================================

#[allow(clippy::too_many_arguments)] // dispatch glue: all args are request-derived
async fn dispatch_streaming(
    state: AppState,
    method: &str,
    tenant: &str,
    owner: &str,
    claims: Option<serde_json::Value>,
    params: Value,
    request_id: Value,
    last_event_id: Option<&str>,
) -> Result<axum::response::Response, A2aError> {
    match method {
        methods::SEND_STREAMING_MESSAGE => {
            dispatch_send_streaming_message(state, tenant, owner, claims, params, request_id).await
        }
        methods::SUBSCRIBE_TO_TASK => {
            dispatch_subscribe_to_task(state, tenant, owner, params, request_id, last_event_id)
                .await
        }
        _ => Err(A2aError::Internal("Unknown streaming method".into())),
    }
}

async fn dispatch_send_streaming_message(
    state: AppState,
    tenant: &str,
    owner: &str,
    claims: Option<serde_json::Value>,
    params: Value,
    request_id: Value,
) -> Result<axum::response::Response, A2aError> {
    // Parse the SendMessageRequest from params
    let request: turul_a2a_proto::SendMessageRequest =
        serde_json::from_value(params).map_err(|e| A2aError::InvalidRequest {
            message: format!("Invalid params: {e}"),
        })?;

    let proto_message = request.message.ok_or(A2aError::InvalidRequest {
        message: "message field is required".into(),
    })?;

    let message = Message::try_from(proto_message).map_err(|e| A2aError::InvalidRequest {
        message: format!("Invalid message: {e}"),
    })?;

    let task_id = uuid::Uuid::now_v7().to_string();
    let context_id = if message.as_proto().context_id.is_empty() {
        uuid::Uuid::now_v7().to_string()
    } else {
        message.as_proto().context_id.clone()
    };

    // Subscribe to wake-ups BEFORE creating the task
    let wake_rx = state.event_broker.subscribe(&task_id).await;

    // Atomic: create task + SUBMITTED event
    let mut task =
        Task::new(&task_id, TaskStatus::new(TaskState::Submitted)).with_context_id(&context_id);
    task.append_message(message.clone());

    let submitted_event = StreamEvent::StatusUpdate {
        status_update: streaming::StatusUpdatePayload {
            task_id: task_id.clone(),
            context_id: context_id.clone(),
            status: serde_json::to_value(TaskStatus::new(TaskState::Submitted)).unwrap_or_default(),
        },
    };

    state
        .atomic_store
        .create_task_with_events(tenant, owner, task, vec![submitted_event])
        .await
        .map_err(A2aError::from)?;
    state.event_broker.notify(&task_id).await;

    // SUBMITTED → WORKING via CAS so subscribers see WORKING before
    // the executor begins emitting.
    let working_event = StreamEvent::StatusUpdate {
        status_update: streaming::StatusUpdatePayload {
            task_id: task_id.clone(),
            context_id: context_id.clone(),
            status: serde_json::to_value(TaskStatus::new(TaskState::Working)).unwrap_or_default(),
        },
    };
    state
        .atomic_store
        .update_task_status_with_events(
            tenant,
            &task_id,
            owner,
            TaskStatus::new(TaskState::Working),
            vec![working_event],
        )
        .await
        .map_err(A2aError::from)?;
    state.event_broker.notify(&task_id).await;

    // Spawn the executor on a tracked handle. Streaming transport does
    // not block on yielded_rx.
    let spawn_deps = crate::server::spawn::SpawnDeps {
        executor: state.executor.clone(),
        task_storage: state.task_storage.clone(),
        atomic_store: state.atomic_store.clone(),
        event_broker: state.event_broker.clone(),
        in_flight: state.in_flight.clone(),
        push_dispatcher: state.push_dispatcher.clone(),
    };
    let scope = crate::server::spawn::SpawnScope {
        tenant: tenant.to_string(),
        owner: owner.to_string(),
        task_id: task_id.clone(),
        context_id: context_id.clone(),
        message: message.clone(),
        claims,
    };
    let _spawn = crate::server::spawn::spawn_tracked_executor(spawn_deps, scope)?;

    Ok(make_jsonrpc_sse_response(
        request_id,
        state.event_store,
        tenant.to_string(),
        task_id,
        0,
        wake_rx,
        None,
    ))
}

async fn dispatch_subscribe_to_task(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
    request_id: Value,
    last_event_id: Option<&str>,
) -> Result<axum::response::Response, A2aError> {
    let task_id = params
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: id".into(),
        })?
        .to_string();

    // Verify task exists and caller owns it
    let task = state
        .task_storage
        .get_task(tenant, &task_id, owner, None)
        .await
        .map_err(A2aError::from)?
        .ok_or_else(|| A2aError::TaskNotFound {
            task_id: task_id.clone(),
        })?;

    // Spec §3.1.6: terminal tasks return UnsupportedOperationError
    if let Some(status) = task.status() {
        if let Ok(s) = status.state() {
            if s.is_terminal() {
                return Err(A2aError::UnsupportedOperation {
                    message: format!("Task {task_id} is already in terminal state {s:?}"),
                });
            }
        }
    }

    // Parse Last-Event-ID for replay (Turul extension — proto has no cursor field)
    let after_sequence = last_event_id
        .and_then(replay::parse_last_event_id)
        .filter(|parsed| parsed.task_id == task_id)
        .map(|parsed| parsed.sequence)
        .unwrap_or(0);

    // Spec §3.1.6: first event is Task snapshot (when not reconnecting)
    let initial_task = if after_sequence == 0 {
        Some(task)
    } else {
        None
    };

    let wake_rx = state.event_broker.subscribe(&task_id).await;

    Ok(make_jsonrpc_sse_response(
        request_id,
        state.event_store,
        tenant.to_string(),
        task_id,
        after_sequence,
        wake_rx,
        initial_task,
    ))
}

// =========================================================
// JSON-RPC SSE response builder
// =========================================================

/// Polling interval for cross-instance subscribers.
const JSONRPC_STORE_POLL_INTERVAL: Duration = Duration::from_secs(2);

/// Build an SSE response with JSON-RPC envelopes around each event.
///
/// Each SSE `data:` line is: `{"jsonrpc":"2.0","result":{event},"id":request_id}`
fn make_jsonrpc_sse_response(
    request_id: Value,
    event_store: Arc<dyn A2aEventStore>,
    tenant: String,
    task_id: String,
    after_sequence: u64,
    wake_rx: broadcast::Receiver<()>,
    initial_task: Option<Task>,
) -> axum::response::Response {
    let (tx, rx) = tokio::sync::mpsc::channel::<Result<Event, std::convert::Infallible>>(64);

    tokio::spawn(async move {
        // Spec §3.1.6: emit Task object as first event (when not reconnecting)
        if let Some(task) = initial_task {
            let task_json = json!({"task": serde_json::to_value(&task).unwrap_or_default()});
            let envelope = json!({
                "jsonrpc": "2.0",
                "result": task_json,
                "id": request_id,
            });
            let sse_event = Event::default()
                .id(replay::format_event_id(&task_id, 0))
                .data(serde_json::to_string(&envelope).unwrap_or_default());
            if tx.send(Ok(sse_event)).await.is_err() {
                return;
            }
        }

        let mut last_seq = after_sequence;
        let mut wake_rx = wake_rx;

        loop {
            let events = match event_store
                .get_events_after(&tenant, &task_id, last_seq)
                .await
            {
                Ok(e) => e,
                Err(_) => break,
            };

            let mut saw_terminal = false;
            for (seq, event) in events {
                last_seq = seq;
                let event_id = replay::format_event_id(&task_id, seq);
                let event_json = serde_json::to_value(&event).unwrap_or_default();
                let envelope = json!({
                    "jsonrpc": "2.0",
                    "result": event_json,
                    "id": request_id,
                });
                let sse_event = Event::default()
                    .id(event_id)
                    .data(serde_json::to_string(&envelope).unwrap_or_default());
                if tx.send(Ok(sse_event)).await.is_err() {
                    return;
                }
                if event.is_terminal() {
                    saw_terminal = true;
                }
            }

            if saw_terminal {
                break;
            }

            tokio::select! {
                result = wake_rx.recv() => {
                    match result {
                        Ok(()) => {}
                        Err(broadcast::error::RecvError::Closed) => break,
                        Err(broadcast::error::RecvError::Lagged(_)) => {}
                    }
                }
                _ = tokio::time::sleep(JSONRPC_STORE_POLL_INTERVAL) => {}
            }
        }
    });

    let stream = ReceiverStream::new(rx);
    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

fn method_not_found(_method: &str) -> A2aError {
    // Return a special error that maps to -32601
    A2aError::InvalidRequest {
        message: "Method not found".into(),
    }
}

// =========================================================
// Per-method dispatch — deserialize params, call core, serialize result
// =========================================================

async fn dispatch_send_message(
    state: AppState,
    tenant: &str,
    owner: &str,
    claims: Option<serde_json::Value>,
    params: Value,
) -> Result<Value, A2aError> {
    let body = serde_json::to_string(&params).map_err(|e| A2aError::InvalidRequest {
        message: format!("Invalid params: {e}"),
    })?;
    // Reuse the core handler, which returns Json<Value> with SendMessageResponse shape
    let Json(response) =
        crate::router::core_send_message(state, tenant, owner, claims, body).await?;
    Ok(response)
}

async fn dispatch_get_task(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let id = params
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: id".into(),
        })?
        .to_string();

    let history_length = params
        .get("historyLength")
        .and_then(|v| v.as_i64())
        .map(|v| v as i32);

    let Json(response) =
        crate::router::core_get_task(state, tenant, owner, &id, history_length).await?;
    Ok(response)
}

async fn dispatch_list_tasks(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let query = crate::router::ListTasksQuery {
        context_id: params
            .get("contextId")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
        status: params
            .get("status")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
        page_size: params
            .get("pageSize")
            .and_then(|v| v.as_i64())
            .map(|v| v as i32),
        page_token: params
            .get("pageToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
        history_length: params
            .get("historyLength")
            .and_then(|v| v.as_i64())
            .map(|v| v as i32),
        include_artifacts: params.get("includeArtifacts").and_then(|v| v.as_bool()),
    };

    let Json(response) = crate::router::core_list_tasks(state, tenant, owner, &query).await?;
    Ok(response)
}

async fn dispatch_cancel_task(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let id = params
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: id".into(),
        })?
        .to_string();

    let Json(response) = crate::router::core_cancel_task(state, tenant, owner, &id).await?;
    Ok(response)
}

async fn dispatch_get_extended_agent_card(state: AppState) -> Result<Value, A2aError> {
    match state.executor.extended_agent_card(None) {
        Some(card) => Ok(serde_json::to_value(card).unwrap_or_default()),
        None => Err(A2aError::ExtendedAgentCardNotConfigured),
    }
}

async fn dispatch_create_push_config(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let task_id = params
        .get("taskId")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: taskId".into(),
        })?
        .to_string();

    let body = serde_json::to_string(&params).map_err(|e| A2aError::InvalidRequest {
        message: format!("Invalid params: {e}"),
    })?;

    let Json(response) =
        crate::router::core_create_push_config(state, tenant, owner, &task_id, body).await?;
    Ok(response)
}

async fn dispatch_get_push_config(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let task_id = params
        .get("taskId")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: taskId".into(),
        })?
        .to_string();
    let id = params
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: id".into(),
        })?
        .to_string();

    let Json(response) =
        crate::router::core_get_push_config(state, tenant, owner, &task_id, &id).await?;
    Ok(response)
}

async fn dispatch_list_push_configs(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let task_id = params
        .get("taskId")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: taskId".into(),
        })?
        .to_string();

    let query = crate::router::PushConfigQuery {
        page_size: params
            .get("pageSize")
            .and_then(|v| v.as_i64())
            .map(|v| v as i32),
        page_token: params
            .get("pageToken")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string()),
    };

    let Json(response) =
        crate::router::core_list_push_configs(state, tenant, owner, &task_id, &query).await?;
    Ok(response)
}

async fn dispatch_delete_push_config(
    state: AppState,
    tenant: &str,
    owner: &str,
    params: Value,
) -> Result<Value, A2aError> {
    let task_id = params
        .get("taskId")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: taskId".into(),
        })?
        .to_string();
    let id = params
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or(A2aError::InvalidRequest {
            message: "Missing required field: id".into(),
        })?
        .to_string();

    let Json(response) =
        crate::router::core_delete_push_config(state, tenant, owner, &task_id, &id).await?;
    Ok(response)
}

// =========================================================
// JSON-RPC response builders
// =========================================================

fn jsonrpc_success(id: Value, result: Value) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": result,
    })
}

fn jsonrpc_error(id: Value, code: i32, message: &str, data: Option<Value>) -> Value {
    let mut error = json!({
        "code": code,
        "message": message,
    });
    if let Some(d) = data {
        error["data"] = d;
    }
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": error,
    })
}