turul-a2a 0.2.8

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
//! `A2aService` implementation — gRPC transport adapter.
//!
//! Every RPC dispatches into the same `core_*` function that HTTP and
//! JSON-RPC call. The adapter does only:
//!   1. tenant + owner extraction (metadata → fallback to proto → fallback "")
//!   2. serialize incoming proto to JSON for the core body argument
//!   3. deserialize core JSON response back to the proto response type
//!   4. map `A2aError` via [`crate::grpc::error::a2a_to_status`]
//!
//! The two streaming RPCs encode the shared core stream in
//! [`crate::grpc::streaming`].

use std::pin::Pin;

use async_trait::async_trait;
use futures::Stream;
use tonic::{Request, Response, Status};
use turul_a2a_proto as pb;

use crate::grpc::error::a2a_to_status;
use crate::middleware::context::RequestContext;
use crate::router::{self, AppState, ListTasksQuery, PushConfigQuery};

/// Metadata key the adapter reads to scope a request to a tenant.
/// — ASCII, lowercase per HTTP/2 header canonicalisation.
pub const TENANT_METADATA: &str = "x-tenant-id";

/// gRPC service implementing `lf.a2a.v1.A2AService` by forwarding each
/// RPC into the shared core handler layer.
pub struct GrpcService {
    pub(crate) state: AppState,
}

impl GrpcService {
    pub fn new(state: AppState) -> Self {
        Self { state }
    }
}

/// Pull the tenant ID for this request. Precedence (normative):
///   1. Proto `tenant` field on the request, when non-empty.
///   2. `x-tenant-id` ASCII metadata, when the proto field is empty.
///   3. Empty string (= DEFAULT_TENANT, matches the HTTP default route).
///
/// When both are set and differ, the proto field wins — the metadata is
/// ignored rather than raising an error. Every A2AService request proto
/// carries `tenant` explicitly, and HTTP/JSON-RPC also bind tenant via
/// explicit wire fields (URL path / JSON-RPC param).
pub(crate) fn tenant_from<T>(req: &Request<T>, proto_tenant: &str) -> String {
    if !proto_tenant.is_empty() {
        return proto_tenant.to_string();
    }
    if let Some(val) = req.metadata().get(TENANT_METADATA)
        && let Ok(s) = val.to_str()
        && !s.is_empty()
    {
        return s.to_string();
    }
    String::new()
}

/// Pull the caller's owner identity from the request extensions.
///
/// When the `A2aAuthLayer` is wired (next commit), it injects a
/// [`RequestContext`] into `http::Request::extensions_mut()`; tonic
/// surfaces those same extensions to the service impl. When no layer is
/// configured (bare test harness, compile-only checks) the owner falls
/// back to `"anonymous"` — identical to the HTTP path's behaviour.
fn owner_from<T>(req: &Request<T>) -> String {
    req.extensions()
        .get::<RequestContext>()
        .map(|ctx| ctx.identity.owner().to_string())
        .unwrap_or_else(|| "anonymous".to_string())
}

/// The caller's auth claims, as the HTTP handlers pass them to the
/// executor (`ExecutionContext::claims`).
fn claims_from<T>(req: &Request<T>) -> Option<serde_json::Value> {
    req.extensions()
        .get::<RequestContext>()
        .and_then(|ctx| ctx.identity.claims().cloned())
}

/// Convert a serde_json::Error at the adapter boundary into a
/// `tonic::Status`. Adapter-layer JSON failures are internal: the core
/// handler produced a Value it was meant to produce, and we failed to
/// decode it into the proto response type — that is a framework bug,
/// not an A2A error.
fn internal_from_json(err: serde_json::Error) -> Status {
    Status::internal(format!("grpc adapter: proto/json mismatch: {err}"))
}

/// Parse the `a2a-extensions` gRPC metadata key, validate against the
/// agent card's advertised extensions, and return the negotiated set
/// for echo on the response trailers. Mirrors the HTTP path's
/// [`crate::router::negotiate_profile_extensions`].
fn negotiate_profile_extensions_grpc(
    state: &AppState,
    metadata: &tonic::metadata::MetadataMap,
) -> Result<std::collections::HashSet<String>, crate::error::A2aError> {
    let raw = metadata
        .get(crate::profile_dispatch::A2A_EXTENSIONS_HEADER)
        .and_then(|v| v.to_str().ok());
    let activated = crate::profile_dispatch::parse_a2a_extensions(raw);
    let card = state.executor.agent_card();
    let advertised: &[turul_a2a_proto::AgentExtension] = card
        .capabilities
        .as_ref()
        .map(|c| c.extensions.as_slice())
        .unwrap_or(&[]);
    crate::profile_dispatch::validate_activation(&activated, advertised)
}

/// Attach the `a2a-extensions` echo metadata to a gRPC response.
/// Metadata is set on initial response metadata (not trailers) so the
/// client observes it before the first streaming frame.
fn attach_extension_echo_grpc<T>(
    response: &mut Response<T>,
    echoed: &std::collections::HashSet<String>,
) {
    if let Some(value) = crate::profile_dispatch::response_header_value(echoed)
        && let Ok(metadata_value) = tonic::metadata::MetadataValue::try_from(value.as_str())
    {
        response.metadata_mut().insert(
            crate::profile_dispatch::A2A_EXTENSIONS_HEADER,
            metadata_value,
        );
    }
}

/// Boxed stream type used by both streaming RPCs. Keeps the `A2aService`
/// associated types stable between the placeholder implementations here
/// and the real streaming module that lands in the next commit.
pub type BoxedStreamResponseStream =
    Pin<Box<dyn Stream<Item = Result<pb::StreamResponse, Status>> + Send + 'static>>;

#[async_trait]
impl pb::grpc::A2aService for GrpcService {
    // --- SendMessage ----------------------------------------------------

    async fn send_message(
        &self,
        request: Request<pb::SendMessageRequest>,
    ) -> Result<Response<pb::SendMessageResponse>, Status> {
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let echoed = negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;

        // core_send_message wants the JSON body the HTTP handler would have
        // received — serialize the proto request back to JSON to reuse the
        // existing input path (including `configuration.returnImmediately`).
        let body = serde_json::to_string(request.get_ref()).map_err(internal_from_json)?;
        crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)
            .map_err(a2a_to_status)?;

        let claims = claims_from(&request);
        let value =
            router::core_send_message(self.state.clone(), &tenant, &owner, claims, &echoed, body)
                .await
                .map_err(a2a_to_status)?
                .0;

        let response: pb::SendMessageResponse =
            serde_json::from_value(value).map_err(internal_from_json)?;
        let mut wrapped = Response::new(response);
        attach_extension_echo_grpc(&mut wrapped, &echoed);
        Ok(wrapped)
    }

    // --- GetTask --------------------------------------------------------

    async fn get_task(
        &self,
        request: Request<pb::GetTaskRequest>,
    ) -> Result<Response<pb::Task>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().id.clone();
        let history_length = request.get_ref().history_length;

        let value = router::core_get_task(
            self.state.clone(),
            &tenant,
            &owner,
            &task_id,
            history_length,
        )
        .await
        .map_err(a2a_to_status)?
        .0;

        let task: pb::Task = serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(task))
    }

    // --- ListTasks ------------------------------------------------------

    async fn list_tasks(
        &self,
        request: Request<pb::ListTasksRequest>,
    ) -> Result<Response<pb::ListTasksResponse>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let req = request.get_ref();
        let tenant = tenant_from(&request, &req.tenant);

        let query = ListTasksQuery::from_proto(req).map_err(a2a_to_status)?;

        let value = router::core_list_tasks(self.state.clone(), &tenant, &owner, &query)
            .await
            .map_err(a2a_to_status)?
            .0;

        let response: pb::ListTasksResponse =
            serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(response))
    }

    // --- CancelTask -----------------------------------------------------

    async fn cancel_task(
        &self,
        request: Request<pb::CancelTaskRequest>,
    ) -> Result<Response<pb::Task>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().id.clone();

        let value = router::core_cancel_task(self.state.clone(), &tenant, &owner, &task_id)
            .await
            .map_err(a2a_to_status)?
            .0;

        let task: pb::Task = serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(task))
    }

    // --- Push config CRUD ----------------------------------------------

    async fn create_task_push_notification_config(
        &self,
        request: Request<pb::TaskPushNotificationConfig>,
    ) -> Result<Response<pb::TaskPushNotificationConfig>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().task_id.clone();
        if task_id.is_empty() {
            return Err(a2a_to_status(crate::error::A2aError::InvalidRequest {
                message: "push config task_id is required".into(),
            }));
        }
        let body = serde_json::to_string(request.get_ref()).map_err(internal_from_json)?;

        let value =
            router::core_create_push_config(self.state.clone(), &tenant, &owner, &task_id, body)
                .await
                .map_err(a2a_to_status)?
                .0;

        let config: pb::TaskPushNotificationConfig =
            serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(config))
    }

    async fn get_task_push_notification_config(
        &self,
        request: Request<pb::GetTaskPushNotificationConfigRequest>,
    ) -> Result<Response<pb::TaskPushNotificationConfig>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().task_id.clone();
        let config_id = request.get_ref().id.clone();

        let value =
            router::core_get_push_config(self.state.clone(), &tenant, &owner, &task_id, &config_id)
                .await
                .map_err(a2a_to_status)?
                .0;

        let config: pb::TaskPushNotificationConfig =
            serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(config))
    }

    async fn list_task_push_notification_configs(
        &self,
        request: Request<pb::ListTaskPushNotificationConfigsRequest>,
    ) -> Result<Response<pb::ListTaskPushNotificationConfigsResponse>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let req = request.get_ref();
        let tenant = tenant_from(&request, &req.tenant);
        let task_id = req.task_id.clone();

        let query = PushConfigQuery {
            page_size: Some(req.page_size).filter(|n| *n > 0),
            page_token: Some(req.page_token.clone()).filter(|s| !s.is_empty()),
        };

        let value =
            router::core_list_push_configs(self.state.clone(), &tenant, &owner, &task_id, &query)
                .await
                .map_err(a2a_to_status)?
                .0;

        // core returns {"configs": [...], "nextPageToken": "..."} — reshape
        // into the proto response (which uses `configs` + `next_page_token`
        // / camelCase via pbjson).
        let response: pb::ListTaskPushNotificationConfigsResponse =
            serde_json::from_value(value).map_err(internal_from_json)?;
        Ok(Response::new(response))
    }

    async fn delete_task_push_notification_config(
        &self,
        request: Request<pb::DeleteTaskPushNotificationConfigRequest>,
    ) -> Result<Response<pb::pbjson_types::Empty>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().task_id.clone();
        let config_id = request.get_ref().id.clone();

        let _ = router::core_delete_push_config(
            self.state.clone(),
            &tenant,
            &owner,
            &task_id,
            &config_id,
        )
        .await
        .map_err(a2a_to_status)?;

        Ok(Response::new(pb::pbjson_types::Empty {}))
    }

    // --- GetExtendedAgentCard ------------------------------------------

    async fn get_extended_agent_card(
        &self,
        request: Request<pb::GetExtendedAgentCardRequest>,
    ) -> Result<Response<pb::AgentCard>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let claims = request
            .extensions()
            .get::<RequestContext>()
            .and_then(|ctx| ctx.identity.claims());
        router::core_get_extended_agent_card(&self.state, claims)
            .map(Response::new)
            .map_err(a2a_to_status)
    }

    // --- Streaming RPCs -------------------------------------------------

    type SendStreamingMessageStream = BoxedStreamResponseStream;

    async fn send_streaming_message(
        &self,
        request: Request<pb::SendMessageRequest>,
    ) -> Result<Response<Self::SendStreamingMessageStream>, Status> {
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let echoed = negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let body = serde_json::to_string(request.get_ref()).map_err(internal_from_json)?;
        crate::profile_dispatch::check_skill_invocation_body(&echoed, &body)
            .map_err(a2a_to_status)?;

        let claims = claims_from(&request);
        let stream = crate::grpc::streaming::handle_send_streaming_message(
            self.state.clone(),
            tenant,
            owner,
            claims,
            &echoed,
            body,
        )
        .await?;
        let mut wrapped = Response::new(stream);
        attach_extension_echo_grpc(&mut wrapped, &echoed);
        Ok(wrapped)
    }

    type SubscribeToTaskStream = BoxedStreamResponseStream;

    async fn subscribe_to_task(
        &self,
        request: Request<pb::SubscribeToTaskRequest>,
    ) -> Result<Response<Self::SubscribeToTaskStream>, Status> {
        negotiate_profile_extensions_grpc(&self.state, request.metadata())
            .map_err(a2a_to_status)?;
        let owner = owner_from(&request);
        let tenant = tenant_from(&request, &request.get_ref().tenant);
        let task_id = request.get_ref().id.clone();

        let stream = crate::grpc::streaming::handle_subscribe_to_task(
            self.state.clone(),
            tenant,
            owner,
            task_id,
        )
        .await?;
        Ok(Response::new(stream))
    }
}

#[cfg(test)]
mod tests {
    //! Unit tests for adapter-local helpers. Full end-to-end gRPC
    //! integration tests (later commits in IMPLEMENTATION-PLAN-grpc.md)
    //! cover the request paths end-to-end; these tests pin the
    //! precedence rules the integration harness assumes.

    use super::*;

    fn make_request<T>(value: T, metadata_tenant: Option<&str>) -> Request<T> {
        let mut req = Request::new(value);
        if let Some(t) = metadata_tenant {
            req.metadata_mut().insert(
                TENANT_METADATA,
                tonic::metadata::MetadataValue::try_from(t).expect("ascii metadata"),
            );
        }
        req
    }

    // proto wins over metadata.

    #[test]
    fn proto_tenant_wins_over_metadata() {
        let req = make_request((), Some("tenant-from-metadata"));
        assert_eq!(tenant_from(&req, "tenant-from-proto"), "tenant-from-proto");
    }

    #[test]
    fn metadata_fallback_when_proto_empty() {
        let req = make_request((), Some("tenant-from-metadata"));
        assert_eq!(tenant_from(&req, ""), "tenant-from-metadata");
    }

    #[test]
    fn empty_when_neither_set() {
        let req = make_request((), None);
        assert_eq!(tenant_from(&req, ""), "");
    }

    #[test]
    fn metadata_ignored_when_proto_non_empty_even_on_conflict() {
        // The conflict case: proto and metadata disagree. Contract: proto
        // wins, metadata silently ignored (no error). Covers the
        // "accidentally addressing two tenants" scenario; the three cases
        // above plus this one are the complete decision matrix.
        let req = make_request((), Some("tenant-B"));
        assert_eq!(tenant_from(&req, "tenant-A"), "tenant-A");
    }

    #[test]
    fn empty_proto_and_empty_metadata_yields_empty() {
        // Edge case: both set but both empty. Expected: empty string
        // (default tenant). Proves we don't fall through when the
        // metadata header is present but blank.
        let req = make_request((), Some(""));
        assert_eq!(tenant_from(&req, ""), "");
    }
}