vtcode-a2a 0.140.1

Agent2Agent (A2A) Protocol support for VT Code
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
//! A2A Protocol core data types
//!
//! Implements the core data structures as defined in the A2A specification:
//! - Task and TaskStatus for task lifecycle management
//! - Message and Part types for communication
//! - Artifact for task outputs

use chrono::{DateTime, Utc};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};

// ============================================================================
// Task State & Status
// ============================================================================

/// Task lifecycle states as defined in the A2A specification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum TaskState {
    /// Task has been submitted but not yet started
    #[default]
    Submitted,
    /// Task is actively being processed
    Working,
    /// Task requires additional input from the user
    InputRequired,
    /// Task completed successfully
    Completed,
    /// Task failed with an error
    Failed,
    /// Task was canceled by request
    Canceled,
    /// Task was rejected by the agent
    Rejected,
    /// Task requires authentication
    AuthRequired,
    /// Task state is unknown or unrecognized from a remote A2A agent.
    #[serde(other)]
    Unknown,
}

impl TaskState {
    /// Check if this is a terminal state
    fn is_terminal(&self) -> bool {
        matches!(self, TaskState::Completed | TaskState::Failed | TaskState::Canceled | TaskState::Rejected)
    }

    /// Check if the task can be canceled from this state
    fn is_cancelable(&self) -> bool {
        matches!(self, TaskState::Submitted | TaskState::Working | TaskState::InputRequired)
    }
}

/// Task status with state, optional message, and timestamp
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskStatus {
    /// Current lifecycle state
    pub state: TaskState,
    /// Optional message from the agent providing status details
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<Message>,
    /// ISO-8601 timestamp of the status update
    pub(crate) timestamp: DateTime<Utc>,
}

impl TaskStatus {
    /// Create a new task status
    pub(crate) fn new(state: TaskState) -> Self {
        Self { state, message: None, timestamp: Utc::now() }
    }

    /// Create a new task status with a message
    pub(crate) fn with_message(state: TaskState, message: Message) -> Self {
        Self {
            state,
            message: Some(message),
            timestamp: Utc::now(),
        }
    }
}

impl Default for TaskStatus {
    fn default() -> Self {
        Self::new(TaskState::Submitted)
    }
}

// ============================================================================
// Message & Parts
// ============================================================================

/// Role of the message sender
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageRole {
    /// Message from the user/client
    User,
    /// Message from the agent
    Agent,
}

/// A single unit of communication
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Message {
    /// Sender's role
    pub role: MessageRole,
    /// Content of the message
    pub parts: Vec<Part>,
    /// Unique message identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    message_id: Option<String>,
    /// Associated task ID
    #[serde(skip_serializing_if = "Option::is_none")]
    task_id: Option<String>,
    /// Conversation context ID
    #[serde(skip_serializing_if = "Option::is_none")]
    context_id: Option<String>,
    /// List of prior task IDs for context
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    reference_task_ids: Vec<String>,
    /// Custom metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<HashMap<String, serde_json::Value>>,
}

impl Message {
    /// Create a new message
    fn new(role: MessageRole, parts: Vec<Part>) -> Self {
        Self {
            role,
            parts,
            message_id: None,
            task_id: None,
            context_id: None,
            reference_task_ids: Vec::new(),
            metadata: None,
        }
    }

    /// Create a text message from the agent
    pub(crate) fn agent_text(text: impl Into<String>) -> Self {
        Self::new(MessageRole::Agent, vec![Part::text(text)])
    }

    /// Create a text message from the user
    pub fn user_text(text: impl Into<String>) -> Self {
        Self::new(MessageRole::User, vec![Part::text(text)])
    }

    /// Set the message ID
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.message_id = Some(id.into());
        self
    }

    /// Set the task ID
    pub fn with_task_id(mut self, task_id: impl Into<String>) -> Self {
        self.task_id = Some(task_id.into());
        self
    }

    /// Set the context ID
    pub fn with_context_id(mut self, context_id: impl Into<String>) -> Self {
        self.context_id = Some(context_id.into());
        self
    }
}

/// Content part types: text, file, or structured data
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Part {
    /// Plain text content
    #[serde(rename = "text")]
    Text {
        /// The text content
        text: String,
    },
    /// File content (URI or inline bytes)
    #[serde(rename = "file")]
    File {
        /// File content details
        file: FileContent,
    },
    /// Structured JSON data
    #[serde(rename = "data")]
    Data {
        /// The structured data
        data: serde_json::Value,
    },
    /// Catch-all for unknown part types added by the A2A spec.
    #[serde(other)]
    Unknown,
}

impl Part {
    /// Create a text part
    fn text(text: impl Into<String>) -> Self {
        Part::Text { text: text.into() }
    }

    /// Create a file part from URI
    pub fn file_uri(uri: impl Into<String>, mime_type: Option<String>) -> Self {
        Part::File {
            file: FileContent::Uri { uri: uri.into(), mime_type },
        }
    }

    /// Create a file part from inline bytes
    pub fn file_bytes(bytes: Vec<u8>, mime_type: Option<String>, name: Option<String>) -> Self {
        Part::File {
            file: FileContent::Bytes {
                bytes: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes),
                mime_type,
                name,
            },
        }
    }

    /// Create a data part
    fn data(data: serde_json::Value) -> Self {
        Part::Data { data }
    }

    /// Get the text content if this is a text part
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Part::Text { text } => Some(text),
            _ => None,
        }
    }

    /// Returns true if this is an unknown/unsupported part type.
    pub fn is_unknown(&self) -> bool {
        matches!(self, Part::Unknown)
    }
}

/// File content representation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FileContent {
    /// File referenced by URI
    Uri {
        /// The file URI
        uri: String,
        /// Optional MIME type
        #[serde(skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
    },
    /// File with inline base64-encoded bytes
    Bytes {
        /// Base64-encoded file content
        bytes: String,
        /// Optional MIME type
        #[serde(skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
        /// Optional file name
        #[serde(skip_serializing_if = "Option::is_none")]
        name: Option<String>,
    },
}

// ============================================================================
// Artifact
// ============================================================================

/// A tangible output generated by a task
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Artifact {
    /// Unique artifact identifier
    pub id: String,
    /// Human-readable name
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    /// Description of the artifact
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    /// Content parts
    pub parts: Vec<Part>,
    /// Index for ordering multiple artifacts
    #[serde(skip_serializing_if = "Option::is_none")]
    index: Option<u32>,
    /// Custom metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<HashMap<String, serde_json::Value>>,
}

impl Artifact {
    /// Create a new artifact with text content
    pub(crate) fn text(id: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            name: None,
            description: None,
            parts: vec![Part::text(text)],
            index: None,
            metadata: None,
        }
    }

    /// Create a new artifact with file content
    pub fn file(id: impl Into<String>, file: FileContent) -> Self {
        Self {
            id: id.into(),
            name: None,
            description: None,
            parts: vec![Part::File { file }],
            index: None,
            metadata: None,
        }
    }

    /// Add a name to the artifact
    fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Add a description to the artifact
    fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

// ============================================================================
// Task
// ============================================================================

/// Represents a stateful unit of work
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Task {
    /// Unique task identifier
    pub id: String,
    /// Conversational context identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_id: Option<String>,
    /// Current status
    pub status: TaskStatus,
    /// Outputs produced by the agent
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub artifacts: Vec<Artifact>,
    /// Conversation history (if enabled)
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub history: Vec<Message>,
    /// Custom metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    metadata: Option<HashMap<String, serde_json::Value>>,
    /// Type discriminator
    #[serde(default = "default_task_kind")]
    kind: String,
}

fn default_task_kind() -> String {
    "task".to_string()
}

impl Task {
    /// Create a new task with a generated ID
    pub(crate) fn new() -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            context_id: None,
            status: TaskStatus::default(),
            artifacts: Vec::new(),
            history: Vec::new(),
            metadata: None,
            kind: "task".to_string(),
        }
    }

    /// Create a new task with a specific ID
    pub fn with_id(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            context_id: None,
            status: TaskStatus::default(),
            artifacts: Vec::new(),
            history: Vec::new(),
            metadata: None,
            kind: "task".to_string(),
        }
    }

    /// Set the context ID
    pub(crate) fn with_context_id(mut self, context_id: impl Into<String>) -> Self {
        self.context_id = Some(context_id.into());
        self
    }

    /// Get the current state
    pub(crate) fn state(&self) -> TaskState {
        self.status.state
    }

    /// Check if the task is in a terminal state
    pub(crate) fn is_terminal(&self) -> bool {
        self.status.state.is_terminal()
    }

    /// Check if the task can be canceled
    pub(crate) fn is_cancelable(&self) -> bool {
        self.status.state.is_cancelable()
    }

    /// Update the task status
    fn update_status(&mut self, state: TaskState, message: Option<Message>) {
        self.status = match message {
            Some(msg) => TaskStatus::with_message(state, msg),
            None => TaskStatus::new(state),
        };
    }

    /// Add an artifact to the task
    pub fn add_artifact(&mut self, artifact: Artifact) {
        self.artifacts.push(artifact);
    }

    /// Add a message to the history
    pub fn add_message(&mut self, message: Message) {
        self.history.push(message);
    }
}

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

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

    #[test]
    fn test_task_state_terminal() {
        assert!(!TaskState::Submitted.is_terminal());
        assert!(!TaskState::Working.is_terminal());
        assert!(TaskState::Completed.is_terminal());
        assert!(TaskState::Failed.is_terminal());
        assert!(TaskState::Canceled.is_terminal());
    }

    #[test]
    fn test_task_state_cancelable() {
        assert!(TaskState::Submitted.is_cancelable());
        assert!(TaskState::Working.is_cancelable());
        assert!(TaskState::InputRequired.is_cancelable());
        assert!(!TaskState::Completed.is_cancelable());
        assert!(!TaskState::Failed.is_cancelable());
    }

    #[test]
    fn test_message_creation() {
        let msg = Message::agent_text("Hello, world!");
        assert_eq!(msg.role, MessageRole::Agent);
        assert_eq!(msg.parts.len(), 1);
        assert_eq!(msg.parts[0].as_text(), Some("Hello, world!"));
    }

    #[test]
    fn test_task_lifecycle() {
        let mut task = Task::new();
        assert_eq!(task.state(), TaskState::Submitted);
        assert!(!task.is_terminal());
        assert!(task.is_cancelable());

        task.update_status(TaskState::Working, None);
        assert_eq!(task.state(), TaskState::Working);

        task.update_status(TaskState::Completed, Some(Message::agent_text("Task completed")));
        assert!(task.is_terminal());
        assert!(!task.is_cancelable());
    }

    #[test]
    fn test_part_serialization() {
        let text_part = Part::text("Hello");
        let json = serde_json::to_string(&text_part).expect("serialize");
        assert!(json.contains("\"type\":\"text\""));

        let data_part = Part::data(serde_json::json!({"key": "value"}));
        let json = serde_json::to_string(&data_part).expect("serialize");
        assert!(json.contains("\"type\":\"data\""));
    }

    #[test]
    fn test_artifact_creation() {
        let artifact = Artifact::text("art-1", "Generated content")
            .with_name("output.txt")
            .with_description("The generated output file");

        assert_eq!(artifact.id, "art-1");
        assert_eq!(artifact.name, Some("output.txt".to_string()));
        assert_eq!(artifact.parts.len(), 1);
    }
}