use serde_json::Value;
pub(crate) fn agent_from_payload(payload: &Value) -> Option<String> {
super::mcp_node::str_field(payload, "agent")
}
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::{
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 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(
agent_id,
message,
&tenant_ctx,
&mut continuations,
Utc::now(),
)
.await;
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);
}
}
}