use greentic_a2a::message::TaskState;
use serde_json::{Value, json};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum A2aOutcome {
Answered { text: String, card: Option<Value> },
InputRequired {
question: Option<String>,
card: Option<Value>,
},
Working {
state: TaskState,
detail: Option<String>,
},
Ended {
state: TaskState,
detail: Option<String>,
},
}
fn state_token(state: TaskState) -> &'static str {
match state {
TaskState::Unspecified => "unspecified",
TaskState::Submitted => "submitted",
TaskState::Working => "working",
TaskState::Completed => "completed",
TaskState::Failed => "failed",
TaskState::Canceled => "canceled",
TaskState::InputRequired => "input_required",
TaskState::Rejected => "rejected",
TaskState::AuthRequired => "auth_required",
}
}
fn ended_sentence(agent_id: &str, state: TaskState, detail: Option<&str>) -> String {
let what = match state {
TaskState::Failed => "failed",
TaskState::Canceled => "was canceled",
TaskState::Rejected => "rejected the request",
TaskState::AuthRequired => {
"requires authentication this worker cannot supply in-conversation"
}
_ => "ended in a state this client does not understand",
};
match detail {
Some(text) if !text.trim().is_empty() => {
format!("a2a agent {agent_id} {what}: {}", text.trim())
}
_ => format!("a2a agent {agent_id} {what}"),
}
}
impl A2aOutcome {
pub(super) fn to_value(&self, agent_id: &str) -> Value {
match self {
Self::Answered { text, card } => with_card(
json!({
"status": "completed",
"agent": agent_id,
"reply": text,
}),
card,
),
Self::InputRequired { question, card } => with_card(
json!({
"status": "input_required",
"agent": agent_id,
"question": question.clone().unwrap_or_else(|| format!(
"a2a agent {agent_id} needs more information but did not say what"
)),
"next_step": format!(
"The remote agent {agent_id} is waiting and has NOT answered yet. \
Ask the user for what it needs, then call this tool again with \
their answer; the same remote task continues."
),
}),
card,
),
Self::Working { state, detail } => json!({
"status": "working",
"agent": agent_id,
"state": state_token(*state),
"detail": detail.clone().unwrap_or_else(|| format!(
"a2a agent {agent_id} accepted the request and has not answered yet"
)),
"next_step": format!(
"There is no answer yet. Do not report this as the agent's answer. \
Call this tool again later to ask {agent_id} for progress."
),
}),
Self::Ended { state, detail } => json!({
"status": "failed",
"agent": agent_id,
"state": state_token(*state),
"error": ended_sentence(agent_id, *state, detail.as_deref()),
}),
}
}
}
fn with_card(mut value: Value, card: &Option<Value>) -> Value {
if let (Some(card), Some(map)) = (card, value.as_object_mut()) {
map.insert("card".to_string(), card.clone());
}
value
}
pub fn call_error_value(agent_id: &str, reason: &str) -> Value {
json!({
"status": "error",
"agent": agent_id,
"error": reason,
})
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
fn all_outcomes() -> Vec<A2aOutcome> {
vec![
A2aOutcome::Answered {
text: "an omelette".into(),
card: None,
},
A2aOutcome::InputRequired {
question: Some("Which city?".into()),
card: None,
},
A2aOutcome::InputRequired {
question: None,
card: None,
},
A2aOutcome::Working {
state: TaskState::Working,
detail: None,
},
A2aOutcome::Working {
state: TaskState::Submitted,
detail: Some("queued".into()),
},
A2aOutcome::Ended {
state: TaskState::Failed,
detail: Some("upstream timeout".into()),
},
A2aOutcome::Ended {
state: TaskState::Canceled,
detail: None,
},
A2aOutcome::Ended {
state: TaskState::Rejected,
detail: None,
},
A2aOutcome::Ended {
state: TaskState::AuthRequired,
detail: None,
},
A2aOutcome::Ended {
state: TaskState::Unspecified,
detail: None,
},
]
}
#[test]
fn only_a_completed_outcome_carries_a_reply() {
for outcome in all_outcomes() {
let value = outcome.to_value("recipe");
let has_reply = value.get("reply").is_some();
let completed = value["status"] == "completed";
assert_eq!(
has_reply, completed,
"`reply` must appear exactly when status is completed; got {value}"
);
}
}
#[test]
fn a_failure_carries_an_error_and_never_reads_as_an_answer() {
for state in [
TaskState::Failed,
TaskState::Canceled,
TaskState::Rejected,
TaskState::AuthRequired,
TaskState::Unspecified,
] {
let value = A2aOutcome::Ended {
state,
detail: None,
}
.to_value("recipe");
assert_eq!(value["status"], "failed", "{state:?}");
assert_eq!(value["state"], state_token(state));
assert!(
value["error"]
.as_str()
.is_some_and(|e| e.contains("recipe"))
);
assert!(value.get("reply").is_none());
}
}
#[test]
fn auth_required_names_authentication_rather_than_a_generic_failure() {
let value = A2aOutcome::Ended {
state: TaskState::AuthRequired,
detail: None,
}
.to_value("recipe");
assert_eq!(value["state"], "auth_required");
let error = value["error"].as_str().unwrap();
assert!(error.contains("authentication"), "got: {error}");
}
#[test]
fn input_required_surfaces_the_question_and_says_the_agent_is_waiting() {
let value = A2aOutcome::InputRequired {
question: Some("Which city?".into()),
card: None,
}
.to_value("travel");
assert_eq!(value["status"], "input_required");
assert_eq!(value["question"], "Which city?");
let next = value["next_step"].as_str().unwrap();
assert!(next.contains("waiting") && next.contains("call this tool again"));
}
#[test]
fn input_required_with_no_question_still_says_the_agent_is_waiting() {
let value = A2aOutcome::InputRequired {
question: None,
card: None,
}
.to_value("travel");
assert_eq!(value["status"], "input_required");
assert!(
value["question"]
.as_str()
.is_some_and(|q| q.contains("travel")),
"got: {value}"
);
}
#[test]
fn a_working_task_is_not_an_error_and_not_an_answer() {
let value = A2aOutcome::Working {
state: TaskState::Working,
detail: None,
}
.to_value("recipe");
assert_eq!(value["status"], "working");
assert!(value.get("reply").is_none());
assert!(value.get("error").is_none(), "nothing has gone wrong");
}
#[test]
fn a_call_that_never_reached_the_agent_is_error_not_failed() {
let value = call_error_value("recipe", "card unreachable");
assert_eq!(value["status"], "error");
assert_eq!(value["agent"], "recipe");
assert_eq!(value["error"], "card unreachable");
assert!(value.get("reply").is_none());
}
#[test]
fn every_status_token_is_stable_snake_case() {
for state in [
TaskState::Unspecified,
TaskState::Submitted,
TaskState::Working,
TaskState::Completed,
TaskState::Failed,
TaskState::Canceled,
TaskState::InputRequired,
TaskState::Rejected,
TaskState::AuthRequired,
] {
let token = state_token(state);
assert!(
token.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
"{token}"
);
}
}
#[test]
fn a_card_rides_beside_the_text_and_is_absent_when_there_is_none() {
let card = json!({"type": "AdaptiveCard", "body": []});
let with = A2aOutcome::Answered {
text: "hi".into(),
card: Some(card.clone()),
}
.to_value("a");
assert_eq!(with["card"], card);
assert_eq!(with["reply"], "hi");
let asking = A2aOutcome::InputRequired {
question: Some("q".into()),
card: Some(card.clone()),
}
.to_value("a");
assert_eq!(asking["card"], card);
assert!(asking.get("reply").is_none());
let without = A2aOutcome::Answered {
text: "hi".into(),
card: None,
}
.to_value("a");
assert!(without.get("card").is_none(), "no key, not null");
}
}