use serde_json::Value;
pub(crate) fn agent_from_payload(payload: &Value) -> Option<String> {
super::mcp_node::str_field(payload, "agent")
}
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn wants_card(payload: &Value) -> bool {
match payload.get("card") {
Some(Value::Bool(on)) => *on,
Some(Value::String(text)) => text.trim().eq_ignore_ascii_case("true"),
_ => false,
}
}
const NAVIGATION_KEYS: &[&str] = &["routeToCardId", "toCardId", "nextCardId"];
pub const CARD_SUBMIT_MARKER: &str = "a2aCardSubmit";
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn answer_from_payload(payload: &Value) -> Option<Value> {
let mut map = payload.get("answer")?.as_object()?.clone();
if !map.contains_key("nextCardId") {
return None;
}
for key in NAVIGATION_KEYS {
map.remove(*key);
}
map.remove(CARD_SUBMIT_MARKER);
map.retain(|_, value| !matches!(value, Value::Null) && value.as_str() != Some(""));
(!map.is_empty()).then_some(Value::Object(map))
}
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn card_submit_target(payload: &Value) -> Option<String> {
super::mcp_node::str_field(payload, "card_submit_to")
}
#[cfg_attr(not(feature = "agentic-worker"), allow(dead_code))]
pub(crate) fn retarget_card_submits(card: &mut Value, node_id: &str) -> bool {
let mut changed = false;
match card {
Value::Object(map) => {
if map.get("type").and_then(Value::as_str) == Some("Action.Submit") {
let data = map
.entry("data")
.or_insert_with(|| Value::Object(Default::default()));
if !data.is_object() {
*data = Value::Object(Default::default());
}
if let Some(data) = data.as_object_mut() {
for key in NAVIGATION_KEYS {
data.remove(*key);
}
data.insert("nextCardId".to_string(), Value::String(node_id.to_string()));
data.insert(CARD_SUBMIT_MARKER.to_string(), Value::Bool(true));
changed = true;
}
}
for value in map.values_mut() {
changed |= retarget_card_submits(value, node_id);
}
}
Value::Array(items) => {
for item in items {
changed |= retarget_card_submits(item, node_id);
}
}
_ => {}
}
changed
}
pub(crate) fn agent_from_ref(reference: &str) -> Option<String> {
let id = reference.strip_prefix("a2a:").unwrap_or(reference).trim();
(!id.is_empty()).then(|| id.to_string())
}
#[cfg(feature = "agentic-worker")]
pub mod aw {
use std::sync::Arc;
use chrono::Utc;
use greentic_aw_runtime::TenantContext;
use greentic_aw_runtime::a2a_source::{
A2aCallOptions, A2aContinuations, A2aToolSource, CONTINUATION_IDLE_TTL_SECS,
call_error_value,
};
use greentic_types::{StateKey, TenantCtx};
use serde_json::Value;
use crate::pack::PackRuntime;
use crate::storage::DynStateStore;
pub const CONTINUATION_PREFIX: &str = "runner-a2a";
fn continuation_key(flow_id: &str, session_id: &str) -> StateKey {
StateKey::new(format!("continuations/{flow_id}/{session_id}"))
}
pub(crate) fn source_for_pack(
pack: &Arc<PackRuntime>,
tenant: &str,
secrets: Option<crate::secrets::DynSecretsManager>,
unit: Option<&str>,
) -> Option<Arc<A2aToolSource>> {
crate::runner::a2a_pack_source::a2a_source_from_packs(
std::slice::from_ref(pack),
tenant,
secrets,
unit,
)
}
fn load_continuations(
store: Option<&DynStateStore>,
state_ctx: Option<&TenantCtx>,
flow_id: &str,
session_id: Option<&str>,
) -> A2aContinuations {
let (Some(store), Some(ctx), Some(session)) = (store, state_ctx, session_id) else {
return A2aContinuations::default();
};
let key = continuation_key(flow_id, session);
let stored = match store.get_json(ctx, CONTINUATION_PREFIX, &key, None) {
Ok(value) => value,
Err(error) => {
tracing::warn!(
%error,
"a2a node could not read its continuation state; this call starts a fresh remote context"
);
return A2aContinuations::default();
}
};
let Some(stored) = stored else {
return A2aContinuations::default();
};
serde_json::from_value(stored).unwrap_or_else(|error| {
tracing::warn!(
%error,
"a2a node could not decode its continuation state; this call starts a fresh remote context"
);
A2aContinuations::default()
})
}
fn save_continuations(
store: Option<&DynStateStore>,
state_ctx: Option<&TenantCtx>,
flow_id: &str,
session_id: Option<&str>,
continuations: &A2aContinuations,
) {
let (Some(store), Some(ctx), Some(session)) = (store, state_ctx, session_id) else {
return;
};
let value = match serde_json::to_value(continuations) {
Ok(value) => value,
Err(error) => {
tracing::warn!(%error, "a2a node could not serialise its continuation state");
return;
}
};
let ttl = u32::try_from(CONTINUATION_IDLE_TTL_SECS).ok();
if let Err(error) = store.set_json(
ctx,
CONTINUATION_PREFIX,
&continuation_key(flow_id, session),
None,
&value,
ttl,
) {
tracing::warn!(
%error,
"a2a node could not persist its continuation state; the next call to this agent \
will start a fresh remote context"
);
}
}
pub struct A2aCall<'a> {
pub source: Option<&'a Arc<A2aToolSource>>,
pub store: Option<&'a DynStateStore>,
pub state_ctx: Option<&'a TenantCtx>,
pub flow_id: &'a str,
pub session_id: Option<&'a str>,
pub tenant: &'a str,
pub env: &'a str,
pub pack_id: &'a str,
pub want_card: bool,
pub answer: Option<Value>,
pub card_submit_to: Option<&'a str>,
}
pub async fn invoke(call: A2aCall<'_>, agent_id: &str, message: &Value) -> Value {
let Some(source) = call.source else {
return call_error_value(
agent_id,
&format!(
"a2a is not available to this flow: pack '{}' declares no agents \
(no assets/a2a-routes.json, or GREENTIC_AW_A2A=0)",
call.pack_id
),
);
};
let catalog = source.catalog().await;
let tenant_ctx = TenantContext::new(call.tenant, call.env);
let mut continuations =
load_continuations(call.store, call.state_ctx, call.flow_id, call.session_id);
let before = continuations.clone();
let result = catalog
.dispatch_in_conversation_with(
agent_id,
message,
&tenant_ctx,
&mut continuations,
Utc::now(),
A2aCallOptions {
want_card: call.want_card,
answer: call.answer.clone(),
},
)
.await;
let mut result = result;
if let (Some(node_id), Some(card)) = (call.card_submit_to, result.get_mut("card")) {
super::retarget_card_submits(card, node_id);
}
if continuations != before {
save_continuations(
call.store,
call.state_ctx,
call.flow_id,
call.session_id,
&continuations,
);
}
if let Some(error) = result.get("error") {
let status = result
.get("status")
.and_then(serde_json::Value::as_str)
.unwrap_or("error");
tracing::warn!(
tenant = call.tenant,
agent = agent_id,
status,
error = %error,
"a2a node did not get an answer"
);
}
result
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn the_continuation_namespace_is_not_the_one_flow_authors_write_to() {
assert_ne!(CONTINUATION_PREFIX, crate::storage::state::STATE_PREFIX);
}
#[test]
fn the_key_is_per_session_so_two_sessions_never_share_a_remote_context() {
assert_ne!(
continuation_key("support", "demo:web:c1:u1").as_str(),
continuation_key("support", "demo:web:c2:u1").as_str()
);
}
#[test]
fn the_key_is_per_flow_so_two_flows_in_one_session_never_share_a_remote_context() {
assert_ne!(
continuation_key("support", "demo:web:c1:u1").as_str(),
continuation_key("billing", "demo:web:c1:u1").as_str()
);
}
#[test]
fn a_flow_id_can_never_contain_the_separator_that_ends_its_segment() {
use std::str::FromStr;
assert!(greentic_types::FlowId::from_str("a/b").is_err());
assert!(greentic_types::FlowId::from_str("support.v2_1-a").is_ok());
}
#[test]
fn without_a_session_there_is_no_continuation_and_nothing_is_stored() {
let empty = load_continuations(None, None, "support", None);
assert!(empty.is_empty());
save_continuations(None, None, "support", None, &empty);
}
}
}
#[cfg(test)]
mod wants_card_tests {
use super::wants_card;
use serde_json::json;
#[test]
fn only_an_explicit_card_true_opts_in() {
assert!(wants_card(&json!({"card": true})));
assert!(wants_card(&json!({"card": "true"})));
assert!(wants_card(&json!({"card": " TRUE "})));
assert!(!wants_card(&json!({"card": false})));
assert!(!wants_card(&json!({"card": "yes"})));
assert!(!wants_card(&json!({"agent": "a"})));
assert!(!wants_card(&json!(null)));
}
#[test]
fn an_answer_drops_the_routers_navigation_keys_and_empty_values() {
use super::answer_from_payload;
let payload = json!({"answer": {
"email": "a@b.co", "notes": "", "gone": null,
"nextCardId": "ask_x", "routeToCardId": "y", "action": "submit",
"a2aCardSubmit": true
}});
assert_eq!(
answer_from_payload(&payload),
Some(json!({"email": "a@b.co", "action": "submit"}))
);
assert_eq!(
answer_from_payload(&json!({"answer": {"nextCardId": "x"}})),
None
);
assert_eq!(answer_from_payload(&json!({"answer": "text"})), None);
assert_eq!(answer_from_payload(&json!({})), None);
}
#[test]
fn every_submit_action_in_a_remote_card_is_pointed_back_at_the_asking_node() {
use super::retarget_card_submits;
let mut card = json!({
"type": "AdaptiveCard",
"body": [{"type": "Input.Text", "id": "email"}],
"actions": [
{"type": "Action.Submit", "title": "Go",
"data": {"action": "go", "nextCardId": "remote_node", "toCardId": "z"}},
{"type": "Action.Submit", "title": "Bare"},
{"type": "Action.OpenUrl", "url": "https://x"}
]
});
assert!(retarget_card_submits(&mut card, "ask_signup"));
assert_eq!(
card["actions"][0]["data"],
json!({"action": "go", "nextCardId": "ask_signup", "a2aCardSubmit": true})
);
assert_eq!(
card["actions"][1]["data"],
json!({"nextCardId": "ask_signup", "a2aCardSubmit": true})
);
assert!(card["actions"][2].get("data").is_none());
let mut plain = json!({"type": "AdaptiveCard", "body": []});
assert!(!retarget_card_submits(&mut plain, "n"));
}
}