a2a-rs 0.5.0

Rust implementation of the Agent-to-Agent (A2A) Protocol
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
use crate::domain::error::A2AError;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

#[cfg(feature = "tracing")]
use tracing::instrument;

#[cfg(feature = "tracing")]
use crate::measure_duration;

use super::message::{Artifact, Message};

// Re-export generated types
pub use crate::domain::generated::{Task, TaskPushNotificationConfig, TaskState, TaskStatus};

#[allow(non_upper_case_globals)]
impl TaskState {
    pub const Submitted: Self = Self::TASK_STATE_SUBMITTED;
    pub const Working: Self = Self::TASK_STATE_WORKING;
    pub const InputRequired: Self = Self::TASK_STATE_INPUT_REQUIRED;
    pub const Completed: Self = Self::TASK_STATE_COMPLETED;
    pub const Canceled: Self = Self::TASK_STATE_CANCELED;
    pub const Failed: Self = Self::TASK_STATE_FAILED;
    pub const Rejected: Self = Self::TASK_STATE_REJECTED;
    pub const AuthRequired: Self = Self::TASK_STATE_AUTH_REQUIRED;
    pub const Unknown: Self = Self::TASK_STATE_UNSPECIFIED;

    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::TASK_STATE_COMPLETED
                | Self::TASK_STATE_FAILED
                | Self::TASK_STATE_CANCELED
                | Self::TASK_STATE_REJECTED
        )
    }

    /// The spec's *interrupted* states: the agent has stopped and is waiting on
    /// the caller. Not terminal — the task resumes once the caller supplies what
    /// it asked for — but a caller polling for progress should stop here too.
    pub fn is_interrupted(&self) -> bool {
        matches!(
            self,
            Self::TASK_STATE_INPUT_REQUIRED | Self::TASK_STATE_AUTH_REQUIRED
        )
    }

    /// Whether the task has stopped and will not advance on its own — terminal,
    /// or interrupted waiting on the caller.
    ///
    /// This is the spec's own stopping condition for a blocking `SendMessage`:
    /// `return_immediately = false` obliges the server to wait for a terminal
    /// **or** interrupted state (`spec/a2a.proto:155`). It is also where a
    /// subscription ends, and where a polling client stops. Those three had
    /// each spelled the condition out separately.
    pub fn is_settled(&self) -> bool {
        self.is_terminal() || self.is_interrupted()
    }

    /// Whether a client may still cancel a task in this state.
    ///
    /// Everything that has not finished: queued (`SUBMITTED`), running
    /// (`WORKING`), and the interrupted states — cancelling an `INPUT_REQUIRED`
    /// task is exactly how a client says "never mind". Only the terminal states
    /// refuse, because there is nothing left to stop.
    ///
    /// Defined here rather than in each storage adapter so the rule has one
    /// home: a state added later is cancelable unless it is declared terminal,
    /// which is the safe direction to be wrong in — the alternative strands a
    /// task no client can get rid of.
    pub fn is_cancelable(&self) -> bool {
        !self.is_terminal()
    }
}

/// When a `SendMessage` call should return.
///
/// The A2A default is the **waiting** one, which is easy to get backwards:
/// `SendMessageConfiguration.return_immediately` is a proto3 `bool` and so
/// defaults to `false`, and `false` obliges the server to wait until the task
/// settles before returning (`spec/a2a.proto:155`). A conformant client that
/// sends no configuration at all — which is what the official SDKs do — is
/// therefore promised a settled task, not an acknowledgement.
///
/// Modelled as an enum rather than the wire's bare `bool` because
/// `send_message(…, false)` at a call site reads as "don't" with no way to tell
/// *what* is being declined, and the polarity is already the trap here.
///
/// Lives in the domain because both directions need it: the server decodes it
/// from the request, and the client `Transport` port sets it on the way out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SendCompletion {
    /// Wait until the task reaches a terminal or interrupted state. The spec
    /// default, and what a client that sent no configuration is owed.
    #[default]
    WhenSettled,
    /// Return as soon as the message is accepted, even if the agent is still
    /// working (`return_immediately = true`).
    ///
    /// What a caller doing its own follow-up wants: it keeps *its* deadline in
    /// charge instead of inheriting the server's.
    WhenCreated,
}

impl SendCompletion {
    /// The wire spelling. Note the inversion — this is why the enum exists.
    #[inline]
    pub fn return_immediately(self) -> bool {
        matches!(self, Self::WhenCreated)
    }
}

pub trait TaskStateExt {
    fn is_terminal(&self) -> bool;
    fn is_interrupted(&self) -> bool;
    fn is_settled(&self) -> bool;
    fn is_cancelable(&self) -> bool;
}

/// An unrecognized state is treated as non-terminal, and therefore cancelable:
/// a peer speaking a newer protocol may have states this build does not know,
/// and refusing to cancel one would leave the client no way out at all.
impl TaskStateExt for ::buffa::EnumValue<TaskState> {
    fn is_terminal(&self) -> bool {
        match self {
            ::buffa::EnumValue::Known(state) => state.is_terminal(),
            _ => false,
        }
    }

    fn is_interrupted(&self) -> bool {
        match self {
            ::buffa::EnumValue::Known(state) => state.is_interrupted(),
            _ => false,
        }
    }

    /// An unrecognized state is *not* settled: a caller waiting on it should
    /// keep waiting rather than report a task finished on the strength of a
    /// state this build cannot read.
    fn is_settled(&self) -> bool {
        self.is_terminal() || self.is_interrupted()
    }

    fn is_cancelable(&self) -> bool {
        !self.is_terminal()
    }
}

impl TaskStatus {
    pub fn new(state: TaskState, message: Option<Message>) -> Self {
        let timestamp = chrono::Utc::now();
        let seconds = timestamp.timestamp();
        let nanos = timestamp.timestamp_subsec_nanos() as i32;

        Self {
            state: ::buffa::EnumValue::from(state),
            message: message.into(),
            timestamp: ::buffa::MessageField::some(::buffa_types::google::protobuf::Timestamp {
                seconds,
                nanos,
                ..Default::default()
            }),
            ..Default::default()
        }
    }

    pub fn timestamp_utc(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        self.timestamp.as_option().and_then(|t| {
            chrono::DateTime::<chrono::Utc>::from_timestamp(t.seconds, t.nanos as u32)
        })
    }
}

/// Parameters for identifying a task by ID.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskIdParams {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Parameters for querying a task with optional history constraints.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskQueryParams {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "historyLength")]
    pub history_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Configuration options for sending messages including output modes and notifications.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageSendConfiguration {
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "acceptedOutputModes"
    )]
    pub accepted_output_modes: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "historyLength")]
    pub history_length: Option<u32>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "pushNotificationConfig"
    )]
    pub push_notification_config: Option<TaskPushNotificationConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocking: Option<bool>,
}

/// Parameters for sending a message with optional configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageSendParams {
    pub message: Message,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub configuration: Option<MessageSendConfiguration>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Parameters for sending a task (legacy)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskSendParams {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none", rename = "sessionId")]
    pub session_id: Option<String>,
    pub message: Message,
    #[serde(skip_serializing_if = "Option::is_none", rename = "pushNotification")]
    pub push_notification: Option<TaskPushNotificationConfig>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "historyLength")]
    pub history_length: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Parameters for listing tasks with filtering and pagination.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListTasksParams {
    #[serde(skip_serializing_if = "Option::is_none", rename = "contextId")]
    pub context_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<TaskState>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "pageSize")]
    pub page_size: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "pageToken")]
    pub page_token: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "historyLength")]
    pub history_length: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none", rename = "includeArtifacts")]
    pub include_artifacts: Option<bool>,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "statusTimestampAfter"
    )]
    pub status_timestamp_after: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Result object for tasks/list method.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListTasksResult {
    pub tasks: Vec<Task>,
    #[serde(rename = "totalSize")]
    pub total_size: i32,
    #[serde(rename = "pageSize")]
    pub page_size: i32,
    #[serde(rename = "nextPageToken")]
    pub next_page_token: String,
}

/// Parameters for getting a specific push notification config.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GetTaskPushNotificationConfigParams {
    pub id: String,
    #[serde(
        skip_serializing_if = "Option::is_none",
        rename = "pushNotificationConfigId"
    )]
    pub push_notification_config_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Parameters for listing all push notification configs for a task.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListTaskPushNotificationConfigsParams {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

/// Parameters for deleting a push notification config.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteTaskPushNotificationConfigParams {
    pub id: String,
    #[serde(rename = "pushNotificationConfigId")]
    pub push_notification_config_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Map<String, Value>>,
}

pub struct TaskBuilder {
    id: String,
    context_id: String,
    status: Option<TaskStatus>,
    artifacts: Vec<Artifact>,
    history: Vec<Message>,
    metadata: Option<::buffa_types::google::protobuf::Struct>,
}

impl TaskBuilder {
    pub fn new() -> Self {
        Self {
            id: String::new(),
            context_id: String::new(),
            status: None,
            artifacts: Vec::new(),
            history: Vec::new(),
            metadata: None,
        }
    }

    pub fn id(mut self, id: String) -> Self {
        self.id = id;
        self
    }

    pub fn context_id(mut self, context_id: String) -> Self {
        self.context_id = context_id;
        self
    }

    pub fn status(mut self, status: TaskStatus) -> Self {
        self.status = Some(status);
        self
    }

    pub fn artifacts(mut self, artifacts: Vec<Artifact>) -> Self {
        self.artifacts = artifacts;
        self
    }

    pub fn history(mut self, history: Vec<Message>) -> Self {
        self.history = history;
        self
    }

    pub fn metadata(mut self, metadata: ::buffa_types::google::protobuf::Struct) -> Self {
        self.metadata = Some(metadata);
        self
    }

    pub fn build(self) -> Task {
        Task {
            id: self.id,
            context_id: self.context_id,
            status: self
                .status
                .unwrap_or_else(|| TaskStatus::new(TaskState::TASK_STATE_SUBMITTED, None))
                .into(),
            artifacts: self.artifacts,
            history: self.history,
            metadata: self.metadata.into(),
            ..Default::default()
        }
    }
}

impl Default for TaskBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Task {
    pub fn builder() -> TaskBuilder {
        TaskBuilder::new()
    }

    /// Create a new task with the given ID in the submitted state
    pub fn new(id: String, context_id: String) -> Self {
        Self {
            id,
            context_id,
            status: ::buffa::MessageField::some(TaskStatus::new(
                TaskState::TASK_STATE_SUBMITTED,
                None,
            )),
            artifacts: Vec::new(),
            history: Vec::new(),
            metadata: ::buffa::MessageField::none(),
            ..Default::default()
        }
    }

    /// Create a new task with the given ID and context ID in the submitted state
    pub fn with_context(id: String, context_id: String) -> Self {
        Self::new(id, context_id)
    }

    /// Update the task status
    #[cfg_attr(feature = "tracing", instrument(skip(self, message), fields(
        task.id = %self.id,
        task.old_state = ?self.status.as_option().map(|s| &s.state),
        task.new_state = ?state,
        task.has_message = message.is_some()
    )))]
    pub fn update_status(&mut self, state: TaskState, message: Option<Message>) {
        #[cfg(feature = "tracing")]
        tracing::info!("Updating task status");

        self.status = ::buffa::MessageField::some(TaskStatus::new(state, message.clone()));

        if let Some(msg) = message {
            self.history.push(msg);
        }

        #[cfg(feature = "tracing")]
        tracing::info!("Task status updated successfully");
    }

    /// Get a copy of this task with history limited to the specified length
    #[cfg_attr(feature = "tracing", instrument(skip(self), fields(
        task.id = %self.id,
        history.current_size = self.history.len(),
        history.requested_limit = ?history_length
    )))]
    pub fn with_limited_history(&self, history_length: Option<u32>) -> Self {
        if history_length.is_none() {
            #[cfg(feature = "tracing")]
            tracing::debug!("No history truncation needed");
            return self.clone();
        }

        #[cfg(feature = "tracing")]
        let _span = tracing::Span::current();

        let limit: usize = history_length.unwrap().try_into().unwrap_or(usize::MAX);

        #[cfg(feature = "tracing")]
        let mut task_copy = measure_duration!(_span, "operation.duration_ms", { self.clone() });

        #[cfg(not(feature = "tracing"))]
        let mut task_copy = self.clone();

        if limit == 0 {
            #[cfg(feature = "tracing")]
            tracing::debug!("Removing all history (limit = 0)");
            task_copy.history.clear();
        } else if task_copy.history.len() > limit {
            let items_to_skip = task_copy.history.len() - limit;
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "Truncating history from {} to {} items (removing {} oldest)",
                self.history.len(),
                limit,
                items_to_skip
            );
            task_copy.history = task_copy
                .history
                .iter()
                .skip(items_to_skip)
                .cloned()
                .collect();
        }

        task_copy
    }

    /// Add an artifact to the task
    #[cfg_attr(feature = "tracing", instrument(skip(self, artifact), fields(
        task.id = %self.id,
        artifact.id = %artifact.artifact_id,
        artifacts.count = self.artifacts.len()
    )))]
    pub fn add_artifact(&mut self, artifact: Artifact) {
        self.artifacts.push(artifact);
    }

    /// Validate a task (useful after building with builder)
    #[cfg_attr(feature = "tracing", instrument(skip(self), fields(
        task.id = %self.id,
        task.state = ?self.status.as_option().map(|s| &s.state),
        history.size = self.history.len()
    )))]
    pub fn validate(&self) -> Result<(), A2AError> {
        #[cfg(feature = "tracing")]
        tracing::debug!("Validating task");

        let mut message_ids = std::collections::HashSet::new();
        for (_index, message) in self.history.iter().enumerate() {
            #[cfg(feature = "tracing")]
            tracing::trace!("Validating message {} in history", _index);

            if !message_ids.insert(&message.message_id) {
                #[cfg(feature = "tracing")]
                tracing::error!("Duplicate message ID found: {}", message.message_id);
                return Err(A2AError::InvalidParams(format!(
                    "Duplicate message ID in history: {}",
                    message.message_id
                )));
            }
            message.validate()?;
        }

        if let Some(status) = self.status.as_option()
            && let Some(msg) = status.message.as_option()
        {
            #[cfg(feature = "tracing")]
            tracing::trace!("Validating status message");
            msg.validate()?;
        }

        #[cfg(feature = "tracing")]
        tracing::debug!("Task validation successful");
        Ok(())
    }
}

/// A task paired with its storage version — the optimistic-concurrency token.
///
/// The version is a monotonic counter the storage adapter bumps on every
/// successful mutation of the task. A caller reads a task and its version, then
/// passes that version back on a conditional update
/// ([`AsyncTaskVersioning::update_status_checked`](crate::port::AsyncTaskVersioning::update_status_checked));
/// if another writer advanced the task in between, the update fails with
/// [`A2AError::VersionConflict`](crate::domain::A2AError::VersionConflict) instead
/// of silently clobbering it.
#[derive(Debug, Clone, PartialEq)]
pub struct VersionedTask {
    /// The task at this version.
    pub task: Task,
    /// The storage version this snapshot was read or written at.
    pub version: u64,
}

impl VersionedTask {
    /// Pair a task with a version.
    pub fn new(task: Task, version: u64) -> Self {
        Self { task, version }
    }
}

#[cfg(test)]
mod state_predicate_tests {
    use super::*;

    /// Every state is classified exactly once, so a state added to the proto
    /// cannot slip through unclassified — the failure mode being a task that
    /// nothing will cancel and no client can be rid of.
    #[test]
    fn every_state_is_either_terminal_or_cancelable() {
        let all = [
            TaskState::TASK_STATE_UNSPECIFIED,
            TaskState::TASK_STATE_SUBMITTED,
            TaskState::TASK_STATE_WORKING,
            TaskState::TASK_STATE_COMPLETED,
            TaskState::TASK_STATE_FAILED,
            TaskState::TASK_STATE_CANCELED,
            TaskState::TASK_STATE_INPUT_REQUIRED,
            TaskState::TASK_STATE_REJECTED,
            TaskState::TASK_STATE_AUTH_REQUIRED,
        ];
        for state in all {
            assert_ne!(
                state.is_terminal(),
                state.is_cancelable(),
                "{state:?} must be exactly one of terminal / cancelable"
            );
        }
    }

    /// The states that had been refused: queued work, and work stopped waiting
    /// on the caller. Cancelling those is the whole point of cancel.
    #[test]
    fn unfinished_work_can_be_canceled() {
        assert!(TaskState::Submitted.is_cancelable());
        assert!(TaskState::Working.is_cancelable());
        assert!(TaskState::InputRequired.is_cancelable());
        assert!(TaskState::AuthRequired.is_cancelable());
    }

    #[test]
    fn finished_work_cannot_be_canceled() {
        assert!(!TaskState::Completed.is_cancelable());
        assert!(!TaskState::Failed.is_cancelable());
        assert!(!TaskState::Canceled.is_cancelable());
        assert!(!TaskState::Rejected.is_cancelable());
    }

    /// A state this build does not recognize leaves the client a way out
    /// rather than stranding the task.
    #[test]
    fn an_unrecognized_state_is_cancelable() {
        let unknown: ::buffa::EnumValue<TaskState> = ::buffa::EnumValue::Unknown(99);
        assert!(!unknown.is_terminal());
        assert!(unknown.is_cancelable());
    }
}