klieo-a2a 3.4.0

Durable A2A v1.0 protocol layer atop klieo-bus traits.
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
//! JSON-RPC 2.0 envelope + A2A method enum + standard A2A headers.
//!
//! Wire format mirrors the A2A v1.0 spec §9 ("JSON-RPC Surface"). See
//! <https://a2a-protocol.org/latest/specification/>.

use crate::error::A2aError;
use serde::{Deserialize, Serialize};

/// JSON-RPC 2.0 error codes used across A2A transports.
///
/// Centralised here so the NATS server (`server.rs`), HTTP transport
/// (`http.rs`), and error-mapping impl (`error.rs`) all read from one
/// source of truth rather than carrying local integer literals.
pub mod codes {
    /// JSON-RPC 2.0 -32700: parse error.
    pub const PARSE_ERROR: i32 = -32700;
    /// JSON-RPC 2.0 -32600: invalid request.
    pub const INVALID_REQUEST: i32 = -32600;
    /// JSON-RPC 2.0 -32601: method not found.
    pub const METHOD_NOT_FOUND: i32 = -32601;
    /// JSON-RPC 2.0 -32602: invalid params.
    pub const INVALID_PARAMS: i32 = -32602;
    /// Server-defined -32000: generic internal error.
    pub const SERVER_ERROR: i32 = -32000;
    /// klieo-a2a -32001: authentication required.
    pub const UNAUTHENTICATED: i32 = -32001;
    /// Klieo-specific: resume requested with a cursor older than the
    /// oldest retained event in the buffer.
    pub const RESUME_BUFFER_EXPIRED: i32 = -32010;
    /// Stream leader (originating replica running the invoke) died
    /// or never claimed leadership. Follower observed an orphaned
    /// resume buffer + wrote a terminal frame so the client sees
    /// clean termination + can retry. ADR-020.
    pub const LEADER_DIED: i32 = -32099;
}

/// JSON-RPC 2.0 request envelope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    /// Always `"2.0"`.
    pub jsonrpc: String,
    /// Request id (number, string, or null).
    pub id: serde_json::Value,
    /// One of the 11 [`A2aMethod`] variants.
    pub method: String,
    /// Method-specific params payload.
    #[serde(default)]
    pub params: serde_json::Value,
}

/// JSON-RPC 2.0 response envelope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcResponse {
    /// Always `"2.0"`.
    pub jsonrpc: String,
    /// Mirrors the request id.
    pub id: serde_json::Value,
    /// Successful result (mutually exclusive with `error`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// Error payload (mutually exclusive with `result`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
}

/// JSON-RPC 2.0 error payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcError {
    /// Numeric code (negative for server errors).
    pub code: i32,
    /// Human-readable message.
    pub message: String,
    /// Optional structured detail.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// The 11 method names from A2A v1.0 spec §9.4.
///
/// # Wire form
///
/// The upstream A2A v1.0 spec **renamed every JSON-RPC method from its
/// v0.3.x slash-form to CamelCase** (`message/send` → `SendMessage`,
/// `tasks/get` → `GetTask`, …; see `docs/whats-new-v1.md` in
/// `a2aproject/A2A`). CamelCase is therefore the CURRENT canonical wire
/// form — [`Self::wire_name`] returns it, and that is the only form
/// `klieo-a2a` ever emits.
///
/// [`Self::from_str`] additionally ACCEPTS the legacy v0.3.x slash-form
/// name for every method that had one (`ListTasks` is new in v1.0 and
/// has no legacy name), dispatching it to the identical [`A2aMethod`]
/// variant as its CamelCase successor. This is spec-sanctioned
/// backward compatibility (§A.2 "Server Implementations MAY: Accept
/// both legacy and current request message forms"), not a deviation
/// from spec — it lets `klieo-a2a` interoperate with peers still on
/// pre-1.0 SDKs without maintaining two dispatch tables.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum A2aMethod {
    /// §9.4.1.
    SendMessage,
    /// §9.4.2.
    SendStreamingMessage,
    /// §9.4.3.
    GetTask,
    /// §9.4.4.
    ListTasks,
    /// §9.4.5.
    CancelTask,
    /// §9.4.6.
    SubscribeToTask,
    /// §9.4.7.
    CreateTaskPushNotificationConfig,
    /// §9.4.8.
    GetTaskPushNotificationConfig,
    /// §9.4.9.
    ListTaskPushNotificationConfigs,
    /// §9.4.10.
    DeleteTaskPushNotificationConfig,
    /// §9.4.11.
    GetExtendedAgentCard,
}

impl A2aMethod {
    /// Parse a JSON-RPC `method` string. Accepts both the current
    /// CamelCase wire form and the legacy A2A v0.3.x slash-form alias
    /// (see the type docs). Unknown method names return
    /// [`A2aError::MethodNotFound`].
    #[allow(clippy::should_implement_trait)] // Inherent fn matches the plan; trait `FromStr` would change error type.
    pub fn from_str(s: &str) -> Result<Self, A2aError> {
        Ok(match s {
            "SendMessage" | "message/send" => Self::SendMessage,
            "SendStreamingMessage" | "message/stream" => Self::SendStreamingMessage,
            "GetTask" | "tasks/get" => Self::GetTask,
            // No legacy alias: ListTasks is new in A2A v1.0.
            "ListTasks" => Self::ListTasks,
            "CancelTask" | "tasks/cancel" => Self::CancelTask,
            "SubscribeToTask" | "tasks/resubscribe" => Self::SubscribeToTask,
            "CreateTaskPushNotificationConfig" | "tasks/pushNotificationConfig/set" => {
                Self::CreateTaskPushNotificationConfig
            }
            "GetTaskPushNotificationConfig" | "tasks/pushNotificationConfig/get" => {
                Self::GetTaskPushNotificationConfig
            }
            "ListTaskPushNotificationConfigs" | "tasks/pushNotificationConfig/list" => {
                Self::ListTaskPushNotificationConfigs
            }
            "DeleteTaskPushNotificationConfig" | "tasks/pushNotificationConfig/delete" => {
                Self::DeleteTaskPushNotificationConfig
            }
            "GetExtendedAgentCard" | "agent/getAuthenticatedExtendedCard" => {
                Self::GetExtendedAgentCard
            }
            other => return Err(A2aError::MethodNotFound(other.to_string())),
        })
    }

    /// The current canonical wire form — CamelCase, per the A2A v1.0
    /// rename (see type docs). This is the only form `klieo-a2a` ever
    /// emits; callers that need to normalise a caller-supplied alias
    /// before passing it to a scope-based [`klieo_auth_common::Authenticator`]
    /// should use this rather than echoing the raw request string, so a
    /// legacy-alias request is authorized under the same identity as its
    /// current-form equivalent.
    pub fn wire_name(&self) -> &'static str {
        match self {
            Self::SendMessage => "SendMessage",
            Self::SendStreamingMessage => "SendStreamingMessage",
            Self::GetTask => "GetTask",
            Self::ListTasks => "ListTasks",
            Self::CancelTask => "CancelTask",
            Self::SubscribeToTask => "SubscribeToTask",
            Self::CreateTaskPushNotificationConfig => "CreateTaskPushNotificationConfig",
            Self::GetTaskPushNotificationConfig => "GetTaskPushNotificationConfig",
            Self::ListTaskPushNotificationConfigs => "ListTaskPushNotificationConfigs",
            Self::DeleteTaskPushNotificationConfig => "DeleteTaskPushNotificationConfig",
            Self::GetExtendedAgentCard => "GetExtendedAgentCard",
        }
    }
}

/// Standard A2A headers extracted from a transport-layer header bag.
///
/// Header names match A2A v1.0 spec §8 ("Headers"). Defaults for
/// missing headers: `a2a_version = "1.0"`, everything else `None` /
/// empty.
#[derive(Debug, Clone)]
pub struct A2aHeaders {
    /// `Authorization` header (full value, including scheme).
    pub authorization: Option<String>,
    /// `Content-Type` header.
    pub content_type: Option<String>,
    /// `A2A-Version` — defaults to `"1.0"` when absent.
    pub a2a_version: String,
    /// `A2A-Extensions` — comma-split, trimmed.
    pub a2a_extensions: Vec<String>,
}

impl klieo_auth_common::Headers for A2aHeaders {
    /// Case-insensitive lookup over the four decoded A2A header slots.
    /// Returns `None` for header names outside the known A2A set —
    /// authenticators that need a richer header surface should keep
    /// hold of the raw [`klieo_core::Headers`] bag.
    fn get(&self, name: &str) -> Option<&str> {
        match name.to_ascii_lowercase().as_str() {
            "authorization" => self.authorization.as_deref(),
            "content-type" => self.content_type.as_deref(),
            "a2a-version" => Some(self.a2a_version.as_str()),
            _ => None,
        }
    }
}

impl A2aHeaders {
    /// Decode the four standard A2A headers from a [`klieo_core::Headers`]
    /// map. Missing headers fall back to defaults.
    ///
    /// HTTP header names are case-insensitive (RFC 7230 §3.2). The
    /// upstream [`klieo_core::Headers`] is a plain `HashMap<String,
    /// String>` so we perform the case-fold lookup here — axum's
    /// `HeaderMap` iterator emits lowercase names, while NATS callers
    /// historically use title case (`Authorization`).
    pub fn decode_from(headers: &klieo_core::Headers) -> Self {
        let get = |k: &str| {
            headers
                .iter()
                .find_map(|(name, value)| name.eq_ignore_ascii_case(k).then(|| value.clone()))
        };
        Self {
            authorization: get("Authorization"),
            content_type: get("Content-Type"),
            a2a_version: get("A2A-Version").unwrap_or_else(|| "1.0".to_string()),
            a2a_extensions: get("A2A-Extensions")
                .map(|v| {
                    v.split(',')
                        .map(|s| s.trim().to_string())
                        .filter(|s| !s.is_empty())
                        .collect()
                })
                .unwrap_or_default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn envelope_request_round_trips() {
        let req = JsonRpcRequest {
            jsonrpc: "2.0".into(),
            id: json!(42),
            method: "SendMessage".into(),
            params: json!({"message": {"messageId": "m-1", "role": "user", "parts": []}}),
        };
        let v = serde_json::to_value(&req).unwrap();
        let back: JsonRpcRequest = serde_json::from_value(v).unwrap();
        assert_eq!(back.method, "SendMessage");
        assert_eq!(back.id, json!(42));
    }

    #[test]
    fn method_send_message_parses() {
        let m = A2aMethod::from_str("SendMessage").unwrap();
        assert_eq!(m, A2aMethod::SendMessage);
    }

    #[test]
    fn legacy_slash_form_aliases_parse_to_the_same_variant_as_current_camel_case() {
        let pairs: [(&str, &str, A2aMethod); 10] = [
            ("message/send", "SendMessage", A2aMethod::SendMessage),
            (
                "message/stream",
                "SendStreamingMessage",
                A2aMethod::SendStreamingMessage,
            ),
            ("tasks/get", "GetTask", A2aMethod::GetTask),
            ("tasks/cancel", "CancelTask", A2aMethod::CancelTask),
            (
                "tasks/resubscribe",
                "SubscribeToTask",
                A2aMethod::SubscribeToTask,
            ),
            (
                "tasks/pushNotificationConfig/set",
                "CreateTaskPushNotificationConfig",
                A2aMethod::CreateTaskPushNotificationConfig,
            ),
            (
                "tasks/pushNotificationConfig/get",
                "GetTaskPushNotificationConfig",
                A2aMethod::GetTaskPushNotificationConfig,
            ),
            (
                "tasks/pushNotificationConfig/list",
                "ListTaskPushNotificationConfigs",
                A2aMethod::ListTaskPushNotificationConfigs,
            ),
            (
                "tasks/pushNotificationConfig/delete",
                "DeleteTaskPushNotificationConfig",
                A2aMethod::DeleteTaskPushNotificationConfig,
            ),
            (
                "agent/getAuthenticatedExtendedCard",
                "GetExtendedAgentCard",
                A2aMethod::GetExtendedAgentCard,
            ),
        ];
        for (legacy, current, expected) in pairs {
            let via_legacy = A2aMethod::from_str(legacy)
                .unwrap_or_else(|e| panic!("legacy `{legacy}` failed to parse: {e}"));
            let via_current = A2aMethod::from_str(current)
                .unwrap_or_else(|e| panic!("current `{current}` failed to parse: {e}"));
            assert_eq!(via_legacy, expected, "legacy `{legacy}`");
            assert_eq!(via_current, expected, "current `{current}`");
        }
    }

    #[test]
    fn list_tasks_has_no_legacy_alias() {
        // ListTasks is new in v1.0 — the v0.3.x slash-form namespace
        // (`tasks/list`) was never defined for it.
        assert!(A2aMethod::from_str("tasks/list").is_err());
    }

    #[test]
    fn wire_name_returns_current_camel_case_form_for_every_variant() {
        let variants = [
            (A2aMethod::SendMessage, "SendMessage"),
            (A2aMethod::SendStreamingMessage, "SendStreamingMessage"),
            (A2aMethod::GetTask, "GetTask"),
            (A2aMethod::ListTasks, "ListTasks"),
            (A2aMethod::CancelTask, "CancelTask"),
            (A2aMethod::SubscribeToTask, "SubscribeToTask"),
            (
                A2aMethod::CreateTaskPushNotificationConfig,
                "CreateTaskPushNotificationConfig",
            ),
            (
                A2aMethod::GetTaskPushNotificationConfig,
                "GetTaskPushNotificationConfig",
            ),
            (
                A2aMethod::ListTaskPushNotificationConfigs,
                "ListTaskPushNotificationConfigs",
            ),
            (
                A2aMethod::DeleteTaskPushNotificationConfig,
                "DeleteTaskPushNotificationConfig",
            ),
            (A2aMethod::GetExtendedAgentCard, "GetExtendedAgentCard"),
        ];
        for (variant, expected) in variants {
            assert_eq!(variant.wire_name(), expected);
        }
    }

    #[test]
    fn wire_name_round_trips_through_from_str() {
        for method in [
            A2aMethod::SendMessage,
            A2aMethod::SendStreamingMessage,
            A2aMethod::GetTask,
            A2aMethod::ListTasks,
            A2aMethod::CancelTask,
            A2aMethod::SubscribeToTask,
            A2aMethod::CreateTaskPushNotificationConfig,
            A2aMethod::GetTaskPushNotificationConfig,
            A2aMethod::ListTaskPushNotificationConfigs,
            A2aMethod::DeleteTaskPushNotificationConfig,
            A2aMethod::GetExtendedAgentCard,
        ] {
            assert_eq!(A2aMethod::from_str(method.wire_name()).unwrap(), method);
        }
    }

    #[test]
    fn unknown_method_returns_method_not_found() {
        let err = A2aMethod::from_str("Frobnicate").unwrap_err();
        assert!(matches!(err, crate::error::A2aError::MethodNotFound(_)));
    }

    #[test]
    fn headers_decode_with_all_four_fields() {
        let mut h = klieo_core::Headers::new();
        h.insert("Authorization".into(), "Bearer abc".into());
        h.insert("Content-Type".into(), "application/json".into());
        h.insert("A2A-Version".into(), "1.0".into());
        h.insert("A2A-Extensions".into(), "ext1,ext2".into());
        let decoded = A2aHeaders::decode_from(&h);
        assert_eq!(decoded.authorization.as_deref(), Some("Bearer abc"));
        assert_eq!(decoded.a2a_version, "1.0");
        assert_eq!(
            decoded.a2a_extensions,
            vec!["ext1".to_string(), "ext2".to_string()]
        );
    }

    #[test]
    fn missing_version_defaults_to_one_zero() {
        let h = klieo_core::Headers::new();
        let decoded = A2aHeaders::decode_from(&h);
        assert_eq!(decoded.a2a_version, "1.0");
    }
}