car-a2a 0.6.0

Bridge between Common Agent Runtime and the Linux Foundation Agent2Agent (A2A) v1.0 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
//! Translation layer between A2A messages/tasks and CAR IR.
//!
//! Two directions:
//!
//! 1. **A2A → CAR.** Inbound `message/send` carries a `Message` whose
//!    `parts` may include a structured `data` part naming a tool and
//!    parameters. We compile that into an `ActionProposal` of one
//!    `ToolCall` action. Free-text parts pass through as proposal
//!    `context` so a downstream planner can pick them up.
//!
//! 2. **CAR → A2A.** A `ProposalResult` becomes a list of `Artifact`s
//!    — one per `ActionResult`. Each artifact carries the action's
//!    output as a `data` part plus a short text part summarising the
//!    outcome.
//!
//! Lifecycle mapping:
//!
//! | A2A `TaskState` | CAR signal |
//! |-----------------|-----------|
//! | `SUBMITTED` | Task created, proposal queued |
//! | `WORKING`   | `Runtime::execute` in flight |
//! | `COMPLETED` | `ProposalResult::all_succeeded() == true` |
//! | `FAILED`    | At least one `ActionStatus::Failed`/`Rejected` |
//! | `CANCELED`  | Caller invoked `tasks/cancel` |

use car_ir::{Action, ActionProposal, ActionResult, ActionStatus, ActionType, ProposalResult};
use chrono::Utc;
use std::collections::HashMap;

use crate::types::{Artifact, DataPart, Message, Part, Task, TaskState, TaskStatus, TextPart};

#[derive(Debug, thiserror::Error)]
pub enum ProposalBuildError {
    #[error("message contained no actionable content (no tool data part, no text)")]
    Empty,
    #[error("`data.parameters` must be a JSON object")]
    BadParameters,
}

/// Compile an A2A `Message` into a CAR `ActionProposal`.
///
/// Recognised structured form (the easy path — peer agent already
/// knows the tool name):
///
/// ```json
/// {
///   "kind": "data",
///   "data": {
///     "tool": "fs.read",
///     "parameters": { "path": "/tmp/x" }
///   }
/// }
/// ```
///
/// Falls back to `Empty` if neither a `data.tool` nor any text part is
/// present. When only text is present, the caller can still build a
/// proposal externally (e.g. via `car-active-planner`); this function
/// returns an empty proposal whose `context` carries the text so the
/// planner has something to chew on.
pub fn message_to_proposal(message: &Message) -> Result<ActionProposal, ProposalBuildError> {
    let mut actions = Vec::new();
    let mut context: HashMap<String, serde_json::Value> = HashMap::new();
    let mut text_blobs: Vec<String> = Vec::new();

    for part in &message.parts {
        match part {
            Part::Text(t) => text_blobs.push(t.text.clone()),
            Part::Data(d) => {
                if let Some(obj) = d.data.as_object() {
                    if let Some(tool) = obj.get("tool").and_then(|v| v.as_str()) {
                        let params_value = obj.get("parameters").cloned().unwrap_or_else(|| {
                            serde_json::Value::Object(serde_json::Map::new())
                        });
                        let params_obj = match params_value {
                            serde_json::Value::Object(map) => map,
                            _ => return Err(ProposalBuildError::BadParameters),
                        };
                        let parameters: HashMap<String, serde_json::Value> =
                            params_obj.into_iter().collect();
                        actions.push(Action {
                            id: short_id(),
                            action_type: ActionType::ToolCall,
                            tool: Some(tool.to_string()),
                            parameters,
                            preconditions: Vec::new(),
                            expected_effects: HashMap::new(),
                            state_dependencies: Vec::new(),
                            idempotent: false,
                            max_retries: 3,
                            failure_behavior: car_ir::FailureBehavior::Abort,
                            timeout_ms: None,
                            metadata: HashMap::new(),
                        });
                    } else {
                        // Stash anonymous data under a stable key so the
                        // planner can see it.
                        context.insert("a2a_data".into(), d.data.clone());
                    }
                }
            }
            Part::File(f) => {
                context.insert(
                    "a2a_file".into(),
                    serde_json::to_value(&f.file).unwrap_or(serde_json::Value::Null),
                );
            }
        }
    }

    if !text_blobs.is_empty() {
        context.insert(
            "a2a_text".into(),
            serde_json::Value::String(text_blobs.join("\n")),
        );
    }

    if actions.is_empty() && context.is_empty() {
        return Err(ProposalBuildError::Empty);
    }

    let mut ctx_with_origin = context;
    ctx_with_origin.insert(
        "a2a_message_id".into(),
        serde_json::Value::String(message.message_id.clone()),
    );

    Ok(ActionProposal {
        id: short_id(),
        source: "a2a".into(),
        actions,
        timestamp: Utc::now(),
        context: ctx_with_origin,
    })
}

/// Convert a CAR `ProposalResult` into A2A artifacts — one per action
/// outcome.
pub fn action_results_to_artifacts(result: &ProposalResult) -> Vec<Artifact> {
    result
        .results
        .iter()
        .map(|r| action_result_to_artifact(r))
        .collect()
}

fn action_result_to_artifact(result: &ActionResult) -> Artifact {
    let summary = match result.status {
        ActionStatus::Succeeded => "succeeded".to_string(),
        ActionStatus::Failed => format!(
            "failed: {}",
            result.error.as_deref().unwrap_or("(no detail)")
        ),
        ActionStatus::Rejected => format!(
            "rejected: {}",
            result.error.as_deref().unwrap_or("(no detail)")
        ),
        ActionStatus::Skipped => "skipped".to_string(),
        ActionStatus::Executing => "executing".to_string(),
        ActionStatus::Validated => "validated".to_string(),
        ActionStatus::Proposed => "proposed".to_string(),
    };

    let mut parts: Vec<Part> = vec![Part::Text(TextPart {
        text: format!("action {}: {}", result.action_id, summary),
        metadata: HashMap::new(),
    })];

    if let Some(out) = &result.output {
        parts.push(Part::Data(DataPart {
            data: out.clone(),
            metadata: HashMap::new(),
        }));
    }

    Artifact {
        artifact_id: format!("art-{}", result.action_id),
        name: format!("action.{}", result.action_id),
        description: result.error.clone(),
        parts,
        metadata: HashMap::new(),
    }
}

/// Map a `ProposalResult` to a terminal A2A `TaskState`.
///
/// Rules (priority order):
///
/// - Empty `results` ⇒ `Completed`. A text-only message yields a
///   proposal with no actions, the runtime executes a no-op, and the
///   honest answer is "acknowledged" — not "failed".
/// - Any action `Skipped` with the engine's `CANCELED_PREFIX` error
///   ⇒ `Canceled`. This is what `Runtime::execute_with_cancel` emits
///   when its token trips at a level boundary; without recognising
///   it here the bridge would misreport cancelled tasks as
///   `Completed`. The store's terminal-state guard masks this for
///   peer-initiated `tasks/cancel` (which flips state to `Canceled`
///   before the executor's late `update_state` arrives), but
///   engine-initiated cancels (cost-budget, timeouts) skip that
///   path — they need this branch to land correctly.
/// - Any `Rejected` action ⇒ `Rejected`.
/// - Any `Failed` action ⇒ `Failed`.
/// - Otherwise ⇒ `Completed`.
pub fn a2a_state_for(result: &ProposalResult) -> TaskState {
    if result.results.is_empty() {
        return TaskState::Completed;
    }
    let mut any_canceled = false;
    let mut any_rejected = false;
    let mut any_failed = false;
    for r in &result.results {
        match r.status {
            ActionStatus::Rejected => any_rejected = true,
            ActionStatus::Failed => any_failed = true,
            ActionStatus::Skipped
                if r.error
                    .as_deref()
                    .is_some_and(|e| e.starts_with(car_engine::CANCELED_PREFIX)) =>
            {
                any_canceled = true;
            }
            _ => {}
        }
    }
    if any_canceled {
        TaskState::Canceled
    } else if any_rejected {
        TaskState::Rejected
    } else if any_failed {
        TaskState::Failed
    } else {
        TaskState::Completed
    }
}

/// Bundle a status update into a complete `Task` payload. Used by the
/// store when emitting state transitions.
pub fn task_with_status(
    task_id: String,
    context_id: String,
    state: TaskState,
    history: Vec<Message>,
    artifacts: Vec<Artifact>,
) -> Task {
    Task {
        id: task_id,
        context_id,
        status: TaskStatus {
            state,
            message: None,
            timestamp: Utc::now(),
        },
        history,
        artifacts,
        metadata: HashMap::new(),
    }
}

/// Short UUID used to mint task ids, message ids, etc. Exposed so the
/// dispatcher and other modules don't each maintain their own copy.
pub fn short_id() -> String {
    uuid::Uuid::new_v4().simple().to_string()[..12].to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{DataPart, Message, MessageRole, Part, TextPart};
    use serde_json::json;

    #[test]
    fn structured_data_part_compiles_to_tool_call() {
        let msg = Message {
            message_id: "m1".into(),
            role: MessageRole::User,
            parts: vec![Part::Data(DataPart {
                data: json!({
                    "tool": "fs.read",
                    "parameters": { "path": "/tmp/x" }
                }),
                metadata: HashMap::new(),
            })],
            task_id: None,
            context_id: None,
            metadata: HashMap::new(),
        };
        let proposal = message_to_proposal(&msg).expect("compile");
        assert_eq!(proposal.actions.len(), 1);
        let action = &proposal.actions[0];
        assert_eq!(action.action_type, ActionType::ToolCall);
        assert_eq!(action.tool.as_deref(), Some("fs.read"));
        assert_eq!(action.parameters.get("path"), Some(&json!("/tmp/x")));
        assert_eq!(proposal.source, "a2a");
        assert_eq!(
            proposal.context.get("a2a_message_id"),
            Some(&json!("m1"))
        );
    }

    #[test]
    fn text_only_message_yields_context_proposal() {
        let msg = Message {
            message_id: "m2".into(),
            role: MessageRole::User,
            parts: vec![Part::Text(TextPart {
                text: "summarise this".into(),
                metadata: HashMap::new(),
            })],
            task_id: None,
            context_id: None,
            metadata: HashMap::new(),
        };
        let proposal = message_to_proposal(&msg).expect("compile");
        assert!(proposal.actions.is_empty());
        assert_eq!(
            proposal.context.get("a2a_text"),
            Some(&json!("summarise this"))
        );
    }

    #[test]
    fn empty_message_errors() {
        let msg = Message {
            message_id: "m3".into(),
            role: MessageRole::User,
            parts: vec![],
            task_id: None,
            context_id: None,
            metadata: HashMap::new(),
        };
        assert!(matches!(
            message_to_proposal(&msg),
            Err(ProposalBuildError::Empty)
        ));
    }

    #[test]
    fn proposal_result_round_trips_to_artifacts() {
        let pr = ProposalResult {
            proposal_id: "p1".into(),
            results: vec![
                ActionResult {
                    action_id: "a1".into(),
                    status: ActionStatus::Succeeded,
                    output: Some(json!({"result": 42})),
                    error: None,
                    state_changes: HashMap::new(),
                    duration_ms: Some(12.0),
                    timestamp: Utc::now(),
                },
                ActionResult {
                    action_id: "a2".into(),
                    status: ActionStatus::Failed,
                    output: None,
                    error: Some("boom".into()),
                    state_changes: HashMap::new(),
                    duration_ms: Some(3.0),
                    timestamp: Utc::now(),
                },
            ],
            cost: car_ir::CostSummary::default(),
        };
        let arts = action_results_to_artifacts(&pr);
        assert_eq!(arts.len(), 2);
        assert_eq!(arts[0].name, "action.a1");
        assert_eq!(arts[1].description.as_deref(), Some("boom"));
        assert_eq!(a2a_state_for(&pr), TaskState::Failed);
    }

    #[test]
    fn empty_proposal_result_is_completed() {
        let pr = ProposalResult {
            proposal_id: "p-empty".into(),
            results: vec![],
            cost: car_ir::CostSummary::default(),
        };
        assert_eq!(a2a_state_for(&pr), TaskState::Completed);
    }

    #[test]
    fn skipped_with_canceled_prefix_maps_to_canceled_state() {
        // Engine emits Skipped("canceled: ...") when its cancellation
        // token trips at a level boundary. The bridge must recognise
        // this prefix and return TaskState::Canceled — otherwise
        // engine-initiated cancels (cost budget, future timeouts)
        // silently report as Completed.
        let pr = ProposalResult {
            proposal_id: "p-cancel".into(),
            results: vec![
                ActionResult {
                    action_id: "a1".into(),
                    status: ActionStatus::Succeeded,
                    output: None,
                    error: None,
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
                ActionResult {
                    action_id: "a2".into(),
                    status: ActionStatus::Skipped,
                    output: None,
                    error: Some(format!(
                        "{}{}",
                        car_engine::CANCELED_PREFIX,
                        "cancellation requested by caller"
                    )),
                    state_changes: HashMap::new(),
                    duration_ms: None,
                    timestamp: Utc::now(),
                },
            ],
            cost: car_ir::CostSummary::default(),
        };
        assert_eq!(a2a_state_for(&pr), TaskState::Canceled);
    }

    #[test]
    fn rejected_action_yields_rejected_state() {
        let pr = ProposalResult {
            proposal_id: "p-rej".into(),
            results: vec![ActionResult {
                action_id: "a1".into(),
                status: ActionStatus::Rejected,
                output: None,
                error: Some("policy denied".into()),
                state_changes: HashMap::new(),
                duration_ms: None,
                timestamp: Utc::now(),
            }],
            cost: car_ir::CostSummary::default(),
        };
        assert_eq!(a2a_state_for(&pr), TaskState::Rejected);
    }
}