//! Device2Agent: capability-based device messages, actions and persistent sessions.
use crate::{Agent, AgentProtocol, Error, Input, ProtocolSession, Result, RunEvent, RunResult};
use async_trait::async_trait;
use futures_util::{Stream, StreamExt};
use reqwest::{redirect::Policy, Method};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
pin::Pin,
sync::Arc,
time::Duration,
};
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use tokio::sync::{mpsc, oneshot};
pub const D2A_PROTOCOL_VERSION: &str = "1.0";
pub type D2AMessageStream = Pin<Box<dyn Stream<Item = Result<D2AMessage>> + Send>>;
fn invalid(message: impl Into<String>) -> Error {
Error::Validation(message.into())
}
fn nonempty(value: &str) -> bool {
!value.trim().is_empty() && value.len() <= 256
}
fn timestamp() -> String {
OffsetDateTime::now_utc()
.format(&Rfc3339)
.expect("valid clock")
}
/// One canonical envelope is used in both directions. Content is never an implicit command.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct D2AMessage {
pub protocol: String,
pub version: String,
#[serde(rename = "type")]
pub message_type: String,
pub source: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
pub message_id: String,
pub timestamp: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sequence: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub correlation_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_at: Option<String>,
pub payload: Value,
#[serde(flatten)]
pub extra: serde_json::Map<String, Value>,
}
impl D2AMessage {
/// Construct the shared envelope from a source and an explicit payload.
pub fn from_payload(source: impl Into<String>, payload: Value) -> Result<Self> {
let mut result = Self::new(source, "coordination", vec![])?;
result.payload = payload;
result.validate()?;
Ok(result)
}
pub fn new(source: impl Into<String>, kind: &str, content: Vec<Value>) -> Result<Self> {
let result = Self {
protocol: "d2a".into(),
version: "1.0".into(),
message_type: "message".into(),
source: source.into(),
target: None,
message_id: uuid::Uuid::new_v4().to_string(),
timestamp: timestamp(),
session_id: None,
sequence: None,
correlation_id: None,
expires_at: None,
payload: json!({"kind":kind,"content":content}),
extra: serde_json::Map::new(),
};
result.validate()?;
Ok(result)
}
pub fn observation(source: impl Into<String>, content: Vec<Value>) -> Result<Self> {
Self::new(source, "data", content)
}
pub fn action(
target: impl Into<String>,
capability: impl Into<String>,
arguments: Value,
) -> Result<Self> {
let mut message = Self::new(
"agent",
"coordination",
vec![json!({"type":"control","data":arguments})],
)?;
message.target = Some(target.into());
message.payload = json!({"kind":"action","content":message.payload["content"],"action_id":uuid::Uuid::new_v4().to_string(),"capability":capability.into(),"arguments":arguments});
message.validate()?;
Ok(message)
}
pub fn feedback(action: &Self, status: &str, result: Value) -> Result<Self> {
let mut message = Self::new(
action.target.as_deref().unwrap_or("device"),
"coordination",
vec![json!({"type":"control","data":{"status":status,"result":result}})],
)?;
message.target = Some(action.source.clone());
message.correlation_id = action
.correlation_id
.clone()
.or_else(|| Some(action.message_id.clone()));
message.payload["kind"] = json!("feedback");
message.payload["action_id"] = action.payload["action_id"].clone();
message.payload["status"] = json!(status);
message.payload["result"] = result;
message.validate()?;
Ok(message)
}
pub fn from_value(value: Value) -> Result<Self> {
for key in [
"target",
"session_id",
"sequence",
"correlation_id",
"expires_at",
] {
if value.get(key).is_some_and(Value::is_null) {
return Err(invalid("Optional D2A fields cannot be null"));
}
}
let result: Self = serde_json::from_value(value).map_err(|e| invalid(e.to_string()))?;
result.validate()?;
Ok(result)
}
pub fn to_value(&self) -> Value {
serde_json::to_value(self).expect("message is JSON")
}
pub fn validate(&self) -> Result<()> {
if self.protocol != "d2a"
|| self.version != "1.0"
|| self.message_type != "message"
|| !nonempty(&self.source)
|| !nonempty(&self.message_id)
|| self.target.as_ref().is_some_and(|v| !nonempty(v))
{
return Err(invalid("Invalid D2A envelope"));
}
OffsetDateTime::parse(&self.timestamp, &Rfc3339)
.map_err(|_| invalid("Invalid D2A timestamp"))?;
if self.session_id.is_some() != self.sequence.is_some()
|| self.session_id.as_ref().is_some_and(|v| !nonempty(v))
|| self.correlation_id.as_ref().is_some_and(|v| !nonempty(v))
{
return Err(invalid(
"Session/sequence must be paired and identities nonempty",
));
}
if self.extra.keys().any(|key| key != "stream") {
return Err(invalid("Unknown D2A envelope property"));
}
if let Some(stream) = self.extra.get("stream") {
if !stream["id"].as_str().is_some_and(nonempty)
|| stream["index"].as_u64().is_none()
|| !stream["final"].is_boolean()
|| stream
.get("mode")
.is_some_and(|v| v != "snapshot" && v != "delta")
{
return Err(invalid("Invalid D2A stream metadata"));
}
}
if self.sequence == Some(0) {
return Err(invalid("D2A sequence must be positive"));
}
if let Some(expires) = &self.expires_at {
OffsetDateTime::parse(expires, &Rfc3339).map_err(|_| invalid("Invalid D2A expiry"))?;
}
let kind = self.payload["kind"].as_str().unwrap_or("");
if ![
"data",
"observation",
"state",
"action",
"feedback",
"coordination",
]
.contains(&kind)
{
return Err(invalid("Invalid D2A message kind"));
}
for item in self.payload["content"].as_array().into_iter().flatten() {
if let Some(uri) = item.get("uri") {
if !uri
.as_str()
.is_some_and(|v| url::Url::parse(v).is_ok_and(|url| url.scheme() == "https"))
{
return Err(invalid(
"D2A resources require HTTPS; resolve private resources in the provider",
));
}
}
}
let mut validation = self.to_value();
validation["source"] = json!("device");
if self.payload["content"]
.as_array()
.is_some_and(Vec::is_empty)
&& ["action", "feedback", "coordination"].contains(&kind)
{
validation["payload"]["content"] = json!([{"type":"protocol:metadata","data":{}}]);
}
crate::b2a::content::validate(&validation)?;
if kind == "action"
&& (self.source != "agent"
|| self.target.is_none()
|| !self.payload["action_id"].as_str().is_some_and(nonempty)
|| !self.payload["capability"].as_str().is_some_and(nonempty)
|| !self.payload["arguments"].is_object())
{
return Err(invalid("Invalid D2A action"));
}
if kind == "feedback"
&& (self.payload.get("result").is_none()
|| !self.payload["action_id"].as_str().is_some_and(nonempty)
|| ![
"accepted",
"executing",
"succeeded",
"rejected",
"failed",
"cancelled",
"expired",
"unknown",
]
.contains(&self.payload["status"].as_str().unwrap_or("")))
{
return Err(invalid("Invalid D2A feedback"));
}
Ok(())
}
fn expired(&self) -> bool {
self.expires_at
.as_ref()
.and_then(|v| OffsetDateTime::parse(v, &Rfc3339).ok())
.is_some_and(|v| v <= OffsetDateTime::now_utc())
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ACapability {
pub name: String,
pub input_schema: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output_schema: Option<Value>,
#[serde(default)]
pub requires_approval: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ADeviceDescriptor {
pub id: String,
pub kind: String,
pub capabilities: Vec<D2ACapability>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub state: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revision: Option<Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct D2ADiscovery {
pub devices: Vec<D2ADeviceDescriptor>,
}
impl D2ADiscovery {
pub fn validate(&self) -> Result<()> {
if self.devices.len() > 1024 {
return Err(invalid("Discovery supports at most 1024 devices"));
}
let mut ids = HashSet::new();
for device in &self.devices {
if !nonempty(&device.id) || !nonempty(&device.kind) || !ids.insert(&device.id) {
return Err(invalid("Device IDs must be unique and nonempty"));
}
let mut names = HashSet::new();
for capability in &device.capabilities {
if !nonempty(&capability.name) || !names.insert(&capability.name) {
return Err(invalid("Capability names must be unique per device"));
}
validate_schema(&capability.input_schema)?;
if let Some(schema) = &capability.output_schema {
validate_schema(schema)?;
}
}
}
Ok(())
}
}
fn validate_schema(schema: &Value) -> Result<()> {
if !schema.is_object() {
return Err(invalid("Capability schema must be an object"));
}
fn remote(value: &Value) -> bool {
match value {
Value::Object(m) => m.iter().any(|(k, v)| {
(["$ref", "$dynamicRef", "$recursiveRef"].contains(&k.as_str())
&& !v.as_str().is_some_and(|r| r.starts_with('#')))
|| remote(v)
}),
Value::Array(a) => a.iter().any(remote),
_ => false,
}
}
if remote(schema) {
return Err(invalid("Device schemas must not fetch remote references"));
}
jsonschema::validator_for(schema).map_err(|_| invalid("Invalid device JSON schema"))?;
Ok(())
}
/// Implement this interface for native vendor SDKs, MQTT, ROS 2 or any other device bus.
#[async_trait]
pub trait D2AProvider: Send + Sync {
async fn discover(&self) -> Result<D2ADiscovery>;
async fn events(&self, session_id: &str, cursor: Option<&str>) -> Result<D2AMessageStream>;
async fn execute(&self, message: &D2AMessage) -> Result<D2AMessage>;
async fn get_action(&self, action_id: &str) -> Result<D2AMessage>;
async fn cancel(&self, action_id: &str) -> Result<D2AMessage>;
}
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct D2APolicy {
pub allow_actions: bool,
pub allowed_devices: Vec<String>,
pub allowed_capabilities: Vec<String>,
}
#[derive(Clone)]
pub struct D2A {
pub provider: Arc<dyn D2AProvider>,
pub policy: D2APolicy,
pub context: Value,
}
impl D2A {
pub fn new(provider: impl D2AProvider + 'static) -> Self {
Self {
provider: Arc::new(provider),
policy: D2APolicy::default(),
context: json!({}),
}
}
pub fn with_policy(mut self, policy: D2APolicy) -> Self {
self.policy = policy;
self
}
async fn open(
&self,
agent: &Agent,
user_id: &str,
session_id: &str,
live: bool,
) -> Result<D2ASession> {
if !nonempty(user_id) || !nonempty(session_id) || !self.context.is_object() {
return Err(invalid(
"D2A requires user and application session identity",
));
}
let discovery = self.provider.discover().await?;
discovery.validate()?;
let core = agent.marona.b2a.core.clone();
let capabilities: Value = core
.json(
&core.runtime_url,
Method::GET,
"/runtime/d2a/capabilities",
None,
)
.await?;
if !capabilities["transports"]
.as_array()
.is_some_and(|v| v.contains(&json!("http-sse")))
{
return Err(invalid("Runtime does not support D2A realtime streaming"));
}
let snapshot:Value=core.json(&core.runtime_url,Method::POST,"/runtime/d2a/sessions",Some(&json!({"protocol_version":"1.0","user_id":user_id,"session_id":session_id,"agent":crate::b2a_agent_config(agent)?,"devices":discovery.devices,"context":self.context,"policy":self.policy}))).await?;
let id = snapshot["session_id"]
.as_str()
.filter(|v| nonempty(v))
.ok_or_else(|| invalid("Missing D2A session identity"))?
.to_owned();
if snapshot["protocol"] != "d2a"
|| snapshot["version"] != "1.0"
|| snapshot["state"] != "active"
|| snapshot["user_id"] != user_id
{
return Err(invalid("Invalid D2A session response"));
}
let provider_events = if live {
match self.provider.events(session_id, None).await {
Ok(s) => Some(s),
Err(error) => {
let _: Result<Value> = core
.json(
&core.runtime_url,
Method::DELETE,
&format!("/runtime/d2a/sessions/{id}"),
None,
)
.await;
return Err(error);
}
}
} else {
None
};
let (commands, rx) = mpsc::channel(32);
let (events, out) = mpsc::channel(128);
let worker = D2AWorker {
core,
config: self.clone(),
discovery,
snapshot,
agent: agent.clone(),
application_id: session_id.into(),
events,
actions: HashMap::new(),
requests: HashMap::new(),
approved: HashSet::new(),
seen: HashSet::new(),
};
let task = tokio::spawn(worker.run(rx, provider_events));
Ok(D2ASession {
session_id: session_id.into(),
protocol_session_id: id,
commands,
events: out,
task: Some(task),
last_result: None,
closed: false,
})
}
}
#[async_trait]
impl AgentProtocol for D2A {
fn name(&self) -> &str {
"d2a"
}
async fn capabilities(&self) -> Result<Value> {
let devices = self.provider.discover().await?;
devices.validate()?;
Ok(json!({"devices":devices.devices,"policy":self.policy}))
}
async fn connect(
&self,
agent: &Agent,
user_id: &str,
session_id: &str,
) -> Result<Box<dyn ProtocolSession>> {
Ok(Box::new(self.open(agent, user_id, session_id, true).await?))
}
async fn run(
&self,
agent: &Agent,
input: Input,
user_id: &str,
session_id: &str,
) -> Result<RunResult> {
let Input::Message(input) = input else {
return Err(invalid("D2A input must be a canonical message"));
};
let mut session = self.open(agent, user_id, session_id, false).await?;
let outcome = async {
session.send(&input).await?;
while let Some(event) = session.next_event().await? {
if event.event_type == "exchange.completed" {
if let Some(status) = event.data.get("action_status").and_then(Value::as_str) {
if status != "succeeded" {
return Err(Error::Protocol(format!("D2A action outcome: {status}")));
}
}
return session
.last_result
.clone()
.ok_or_else(|| invalid("D2A exchange did not produce agent output"));
}
}
Err(invalid("D2A closed before completion"))
}
.await;
let close = session.close().await;
match outcome {
Ok(result) => {
close?;
Ok(result)
}
Err(e) => Err(e),
}
}
}
#[derive(Clone, Debug)]
pub struct D2AEvent {
pub event_type: String,
pub data: Value,
pub message: Option<D2AMessage>,
pub output: Value,
}
enum D2ACommand {
Reconcile(String, bool, oneshot::Sender<Result<D2AMessage>>),
Approve(String, bool, oneshot::Sender<Result<()>>),
Send(Value, oneshot::Sender<Result<()>>),
Close(oneshot::Sender<Result<()>>),
}
struct D2AItem {
event: RunEvent,
result: Option<RunResult>,
}
pub struct D2ASession {
pub session_id: String,
pub protocol_session_id: String,
commands: mpsc::Sender<D2ACommand>,
events: mpsc::Receiver<Result<D2AItem>>,
task: Option<tokio::task::JoinHandle<Result<()>>>,
last_result: Option<RunResult>,
closed: bool,
}
impl D2ASession {
pub async fn get_action(&mut self, action_id: &str) -> Result<D2AMessage> {
self.reconcile(action_id, false).await
}
pub async fn cancel(&mut self, action_id: &str) -> Result<D2AMessage> {
self.reconcile(action_id, true).await
}
async fn reconcile(&mut self, action_id: &str, cancel: bool) -> Result<D2AMessage> {
if !nonempty(action_id) || self.closed {
return Err(invalid("Active session and action ID required"));
}
let (tx, rx) = oneshot::channel();
self.commands
.send(D2ACommand::Reconcile(action_id.into(), cancel, tx))
.await
.map_err(|_| invalid("D2A session stopped"))?;
rx.await.map_err(|_| invalid("D2A session stopped"))?
}
pub async fn approve_action(&mut self, action_id: &str, approved: bool) -> Result<()> {
if !nonempty(action_id) || self.closed {
return Err(invalid("Active session and action ID required"));
}
let (tx, rx) = oneshot::channel();
self.commands
.send(D2ACommand::Approve(action_id.into(), approved, tx))
.await
.map_err(|_| invalid("D2A session stopped"))?;
rx.await.map_err(|_| invalid("D2A session stopped"))?
}
pub async fn send_message(&mut self, message: &D2AMessage) -> Result<()> {
self.send(&message.to_value()).await
}
async fn request(&mut self, input: &Value) -> Result<()> {
if self.closed {
return Err(invalid("D2A session is closed"));
}
D2AMessage::from_value(input.clone())?;
let (tx, rx) = oneshot::channel();
self.commands
.send(D2ACommand::Send(input.clone(), tx))
.await
.map_err(|_| invalid("D2A session stopped"))?;
rx.await.map_err(|_| invalid("D2A session stopped"))?
}
fn consume(&mut self, item: Result<D2AItem>) -> Result<RunEvent> {
let item = item?;
if item.event.event_type == "exchange.started" {
self.last_result = None;
}
if item.result.is_some() {
self.last_result = item.result;
}
Ok(item.event)
}
}
#[async_trait]
impl ProtocolSession for D2ASession {
fn supports_feedback(&self) -> bool {
true
}
fn supports_delivery(&self) -> bool {
true
}
fn result(&self) -> Option<RunResult> {
self.last_result.clone()
}
async fn send(&mut self, input: &Value) -> Result<()> {
self.request(input).await
}
async fn deliver(&mut self, input: &Value) -> Result<()> {
self.request(input).await
}
async fn deliver_feedback(&mut self, original: &Value) -> Result<()> {
let mut message = D2AMessage::new(
"agent",
"coordination",
original["payload"]["content"]
.as_array()
.cloned()
.unwrap_or_default(),
)?;
message.correlation_id = original["correlation_id"]
.as_str()
.or_else(|| original["message_id"].as_str())
.map(str::to_owned);
message.payload["execute"] = json!(false);
message.payload["source_protocol"] = original["protocol"].clone();
message.payload["feedback"] = original["payload"].clone();
self.request(&message.to_value()).await
}
async fn next_event(&mut self) -> Result<Option<RunEvent>> {
match self.events.recv().await {
Some(item) => Ok(Some(self.consume(item)?)),
None => Ok(None),
}
}
async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
match self.events.try_recv() {
Ok(item) => Ok(Some(self.consume(item)?)),
Err(mpsc::error::TryRecvError::Empty) => Ok(None),
Err(_) => Ok(None),
}
}
async fn close(&mut self) -> Result<()> {
if self.closed {
return Ok(());
}
self.closed = true;
let (tx, rx) = oneshot::channel();
let closing = self.commands.send(D2ACommand::Close(tx));
tokio::pin!(closing);
let sent = loop {
tokio::select! {sent=&mut closing=>break sent,_=self.events.recv()=>{}}
};
// Drain bounded events while the worker finishes; otherwise a full queue could block close.
let result = if sent.is_ok() {
tokio::select! {value=rx=>value.unwrap_or(Ok(())),_ = async {while self.events.recv().await.is_some(){}}=>Ok(())}
} else {
Ok(())
};
let cleanup = if let Some(task) = self.task.take() {
task.await
.map_err(|_| invalid("D2A session task stopped unexpectedly"))?
} else {
Ok(())
};
result?;
cleanup
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
impl Drop for D2ASession {
fn drop(&mut self) {
if let Some(task) = self.task.take() {
task.abort();
}
}
}
struct D2AWorker {
core: Arc<crate::core::Core>,
config: D2A,
discovery: D2ADiscovery,
snapshot: Value,
agent: Agent,
application_id: String,
events: mpsc::Sender<Result<D2AItem>>,
actions: HashMap<String, D2AMessage>,
requests: HashMap<String, Value>,
approved: HashSet<String>,
seen: HashSet<String>,
}
impl D2AWorker {
fn path(&self, suffix: &str) -> String {
format!(
"/runtime/d2a/sessions/{}{suffix}",
self.snapshot["session_id"].as_str().unwrap_or("")
)
}
async fn emit(&self, kind: &str, data: Value, result: Option<RunResult>) -> Result<()> {
let output = result
.as_ref()
.map(|r| r.output.clone())
.unwrap_or(Value::Null);
self.events
.send(Ok(D2AItem {
event: RunEvent {
event_type: kind.into(),
delta: None,
output,
data: data.as_object().cloned().unwrap_or_default(),
},
result,
}))
.await
.map_err(|_| invalid("D2A receiver closed"))
}
async fn run(
mut self,
mut commands: mpsc::Receiver<D2ACommand>,
mut provider_events: Option<D2AMessageStream>,
) -> Result<()> {
loop {
tokio::select! {
command=commands.recv()=>{match command {Some(D2ACommand::Send(input,reply))=>{let _=reply.send(Ok(()));if let Err(error)=self.exchange(input).await {let _=self.events.send(Err(error)).await;break;}},Some(D2ACommand::Approve(id,approved,reply))=>{let _=reply.send(Ok(()));if let Err(error)=self.approve(&id,approved).await{let _=self.events.send(Err(error)).await;break;}},Some(D2ACommand::Reconcile(id,cancel,reply))=>{let result=self.reconcile(&id,cancel).await;let _=reply.send(result);},Some(D2ACommand::Close(reply))=>{let result=self.close().await;let _=reply.send(result);return Ok(());},None=>break}},
next=async {match &mut provider_events {Some(stream)=>stream.next().await,None=>std::future::pending().await}}=>{
match next {Some(Ok(message))=>{if let Err(error)=self.ingest(message).await {let _=self.events.send(Err(error)).await;break;}},Some(Err(error))=>{let _=self.events.send(Err(error)).await;break;},None=>{provider_events=None;let _=self.emit("provider.disconnected",json!({"protocol":"d2a"}),None).await;}}
}
}
}
self.close().await
}
async fn reconcile(&mut self, id: &str, cancel: bool) -> Result<D2AMessage> {
if !self.requests.contains_key(id) {
return Err(invalid("No reserved device action"));
}
let message = if cancel {
self.config.provider.cancel(id).await?
} else {
self.config.provider.get_action(id).await?
};
self.ingest(message.clone()).await?;
Ok(message)
}
async fn ingest(&mut self, message: D2AMessage) -> Result<()> {
message.validate()?;
let device = self
.discovery
.devices
.iter()
.find(|d| d.id == message.source)
.ok_or_else(|| invalid("Provider event source was not discovered"))?;
if message.source == "agent"
|| !["data", "observation", "state", "feedback"]
.contains(&message.payload["kind"].as_str().unwrap_or(""))
|| [
"routes",
"approved",
"coordination",
"source_protocol",
"route_id",
"hops",
]
.iter()
.any(|key| message.payload.get(key).is_some())
{
return Err(invalid(
"Provider events cannot request actions or protocol coordination",
));
}
if message.payload["kind"] == "feedback" {
let id = message.payload["action_id"].as_str().unwrap_or("");
let request = self
.requests
.get(id)
.ok_or_else(|| invalid("Provider feedback has no reserved action"))?;
if request["target"] != message.source {
return Err(invalid("Provider feedback source mismatch"));
}
let cap = device
.capabilities
.iter()
.find(|c| c.name == request["capability"])
.ok_or_else(|| invalid("Feedback capability not advertised"))?;
if message.payload["status"] == "succeeded" {
if let Some(schema) = &cap.output_schema {
if !jsonschema::validator_for(schema)
.map_err(|_| invalid("Invalid output schema"))?
.is_valid(&message.payload["result"])
{
return Err(invalid("Device result does not match capability schema"));
}
}
}
if let Some(previous) = self.actions.get(id) {
let status = previous.payload["status"].as_str().unwrap_or("unknown");
if !["accepted", "executing", "unknown"].contains(&status)
&& previous.payload["status"] != message.payload["status"]
{
return Err(invalid("Terminal device outcome cannot change"));
}
}
self.actions.insert(id.into(), message.clone());
}
self.exchange(message.to_value()).await
}
async fn close(&self) -> Result<()> {
let _: Value = self
.core
.json(&self.core.runtime_url, Method::DELETE, &self.path(""), None)
.await?;
Ok(())
}
fn bind(&self, mut message: D2AMessage) -> Result<D2AMessage> {
message.session_id = self.snapshot["session_id"].as_str().map(str::to_owned);
if ["feedback", "coordination"].contains(&message.payload["kind"].as_str().unwrap_or("")) {
message.payload["execute"] = json!(false);
}
message.sequence = self.snapshot["next_sequence"].as_u64();
if message.sequence.is_none() {
return Err(invalid("Invalid D2A sequence state"));
}
message.validate()?;
Ok(message)
}
async fn exchange(&mut self, input: Value) -> Result<()> {
let message = self.bind(D2AMessage::from_value(input)?)?;
if message.expired() {
return Err(invalid("D2A message expired"));
}
self.emit(
"exchange.started",
json!({"message_id":message.message_id,"protocol":"d2a"}),
None,
)
.await?;
let response = self
.core
.stream_client
.post(format!(
"{}{}",
self.core.runtime_url,
self.path("/messages/stream")
))
.headers(self.core.headers.clone())
.bearer_auth(self.core.require_api_key()?)
.json(&message)
.send()
.await?;
self.core.check_response(&response)?;
let mut stream = json_events(response);
let mut completed = None;
let mut pending = Vec::new();
while let Some(event) = stream.next().await {
let event = event?;
match event["type"].as_str() {
Some("message") => {
let output = D2AMessage::from_value(event["message"].clone())?;
self.check_identity(&output)?;
if output.extra.get("stream").and_then(|v| v.get("final"))
== Some(&json!(false))
{
self.emit(
"message",
json!({"message":output,"protocol":"d2a","source":output.source}),
None,
)
.await?;
continue;
}
pending.push(output);
}
Some("protocol.route") => {
self.emit("protocol.route", event["data"].clone(), None)
.await?;
}
Some("exchange.completed") => {
completed = Some(event["exchange"].clone());
}
Some("stream.failed") => {
return Err(Error::Protocol(
"D2A stream failed; no action was replayed".into(),
))
}
_ => {}
}
}
let exchange =
completed.ok_or_else(|| invalid("D2A stream ended before exchange completion"))?;
if exchange["session_id"] != self.snapshot["session_id"]
|| exchange["ack"]["message_id"] != message.message_id
{
return Err(invalid("D2A exchange correlation mismatch"));
}
self.process(exchange, pending).await
}
async fn approve(&mut self, id: &str, approved: bool) -> Result<()> {
let encoded = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
let exchange: Value = self
.core
.json(
&self.core.runtime_url,
Method::POST,
&self.path(&format!("/actions/{encoded}/approve")),
Some(&json!({"approved":approved})),
)
.await?;
if approved {
self.approved.insert(id.into());
}
let result = self.process(exchange, Vec::new()).await;
self.approved.remove(id);
result
}
async fn process(&mut self, exchange: Value, mut pending: Vec<D2AMessage>) -> Result<()> {
if exchange["session_id"] != self.snapshot["session_id"]
|| exchange["session"]["session_id"] != self.snapshot["session_id"]
|| exchange["session"]["state"] != "active"
{
return Err(invalid("Invalid D2A exchange snapshot"));
}
let mut result = None;
let mut action_status: Option<String> = None;
self.snapshot = exchange["session"].clone();
for event in exchange["events"].as_array().into_iter().flatten() {
if event["type"] == "protocol.route" {
self.emit("protocol.route", event["data"].clone(), None)
.await?;
} else {
let item = D2AMessage::from_value(event.clone())?;
self.check_identity(&item)?;
pending.push(item);
}
}
for output in pending {
if !self.seen.insert(output.message_id.clone()) {
continue;
}
if self.seen.len() > 4096 {
return Err(invalid(
"D2A event history capacity reached; open a new session",
));
}
if output.payload["status"] == "failed" && output.payload.get("error").is_some() {
action_status = Some("failed".into());
}
if output.payload["status"] == "approval_required" {
action_status = Some("approval_required".into());
}
if output.payload["kind"] == "feedback" {
let status = output.payload["status"].as_str().unwrap_or("unknown");
if action_status.is_none() || action_status.as_deref() == Some("succeeded") {
action_status = Some(status.into());
}
self.emit(
"feedback",
json!({"message":output,"source":output.source}),
None,
)
.await?;
}
if output.payload["response"].is_object() {
result = crate::b2a_runner::completed_result(
&self.agent,
&json!({"status":"completed","response":output.payload["response"]}),
&self.application_id,
)
.await?;
}
self.emit(
"message",
json!({"message":output,"protocol":"d2a","source":output.source}),
result.clone(),
)
.await?;
for route in output.payload["routes"].as_array().into_iter().flatten() {
self.emit("protocol.route", route.clone(), None).await?;
}
if output.source == "agent" && output.payload["kind"] == "action" {
let feedback = self.execute(&output).await?;
if action_status.is_none() || action_status.as_deref() == Some("succeeded") {
action_status = feedback.payload["status"].as_str().map(str::to_owned);
}
let feedback = self.bind(feedback)?;
let mut body = feedback.to_value();
body["payload"]["execute"] = json!(false);
let saved: Value = self
.core
.json(
&self.core.runtime_url,
Method::POST,
&self.path("/messages"),
Some(&body),
)
.await?;
if saved["session_id"] != self.snapshot["session_id"]
|| saved["ack"]["message_id"] != feedback.message_id
{
return Err(invalid("D2A feedback correlation mismatch"));
}
self.snapshot = saved["session"].clone();
self.emit(
"feedback",
json!({"message":feedback,"protocol":"d2a","source":feedback.source}),
None,
)
.await?;
}
}
self.emit(
"exchange.completed",
json!({"exchange":exchange,"protocol":"d2a","action_status":action_status}),
result,
)
.await?;
Ok(())
}
fn check_identity(&self, message: &D2AMessage) -> Result<()> {
if message.session_id.as_deref() != self.snapshot["session_id"].as_str() {
return Err(invalid("D2A event session mismatch"));
}
Ok(())
}
async fn execute(&mut self, action: &D2AMessage) -> Result<D2AMessage> {
let id = action.payload["action_id"]
.as_str()
.ok_or_else(|| invalid("Missing action ID"))?
.to_owned();
let identity = json!({"target":action.target,"capability":action.payload["capability"],"arguments":action.payload["arguments"],"expected_revision":action.payload["expected_revision"]});
if self.requests.get(&id).is_some_and(|v| v != &identity) {
return Err(invalid("Action ID reused for different request"));
}
if let Some(previous) = self.actions.get(&id) {
return Ok(previous.clone());
}
if self.actions.len() >= 10000 {
return Err(invalid(
"Action history capacity reached; open a new session",
));
}
let feedback = match self.authorize(action) {
Err(reason) => D2AMessage::feedback(
action,
if action.expired() {
"expired"
} else {
"rejected"
},
json!({"reason":reason.to_string()}),
)?,
Ok(capability) => {
self.requests.insert(id.clone(), identity);
// Reserve before I/O. Never replay a physical action after an uncertain transport outcome.
self.actions.insert(
id.clone(),
D2AMessage::feedback(
action,
"unknown",
json!({"reason":"Execution outcome is not confirmed"}),
)?,
);
let received = match self.config.provider.execute(action).await {
Ok(value) => Ok(value),
Err(_) => self.config.provider.get_action(&id).await,
};
match received {
Ok(value) => {
value.validate()?;
if [
"routes",
"coordination",
"approved",
"source_protocol",
"route_id",
"hops",
]
.iter()
.any(|key| value.payload.get(key).is_some())
{
return Err(invalid(
"Provider feedback cannot supply coordination or approval metadata",
));
}
if value.payload["kind"] != "feedback"
|| value.payload["action_id"] != id
|| value.source != action.target.clone().unwrap_or_default()
{
return Err(invalid("Device feedback identity mismatch"));
}
if value.payload["status"] == "succeeded" {
if let Some(schema) = capability.output_schema {
let validator = jsonschema::validator_for(&schema)
.map_err(|_| invalid("Invalid output schema"))?;
if !validator.is_valid(&value.payload["result"]) {
return Err(invalid(
"Device result does not match capability schema",
));
}
}
}
value
}
Err(_) => self.actions[&id].clone(),
}
}
};
// Retain IDs for the entire session. Fail closed rather than evict execution history.
if self.actions.len() >= 10000 && !self.actions.contains_key(&id) {
return Err(invalid(
"D2A action history capacity reached; open a new session",
));
}
self.actions.insert(id, feedback.clone());
Ok(feedback)
}
fn authorize(&self, action: &D2AMessage) -> Result<D2ACapability> {
if action.expired() {
return Err(invalid("Action expired"));
}
if !self.config.policy.allow_actions {
return Err(Error::PermissionRequired("D2A actions are disabled".into()));
}
let device = self
.discovery
.devices
.iter()
.find(|v| Some(v.id.as_str()) == action.target.as_deref())
.ok_or_else(|| invalid("Action target was not discovered"))?;
let name = action.payload["capability"].as_str().unwrap_or("");
let capability = device
.capabilities
.iter()
.find(|v| v.name == name)
.ok_or_else(|| invalid("Undeclared device capability"))?;
if (!self.config.policy.allowed_devices.is_empty()
&& !self.config.policy.allowed_devices.contains(&device.id))
|| (!self.config.policy.allowed_capabilities.is_empty()
&& !self
.config
.policy
.allowed_capabilities
.contains(&capability.name))
{
return Err(Error::PermissionRequired(
"Action is outside the allowlist".into(),
));
}
if capability.requires_approval
&& !self
.approved
.contains(action.payload["action_id"].as_str().unwrap_or(""))
{
return Err(Error::ApprovalRequired(
"Device capability requires separate approval".into(),
));
}
if let Some(expected) = action.payload.get("expected_revision") {
if device.revision.as_ref() != Some(expected) {
return Err(invalid("Device state revision changed"));
}
}
let schema = jsonschema::validator_for(&capability.input_schema)
.map_err(|_| invalid("Invalid input schema"))?;
if !schema.is_valid(&action.payload["arguments"]) {
return Err(invalid("Action arguments do not match capability schema"));
}
Ok(capability.clone())
}
}
/// HTTP/SSE device gateway. MCP command tools may share a separately configured SSE event URL.
#[derive(Clone)]
pub struct D2ADevice {
url: String,
client: reqwest::Client,
transport: D2ATransport,
event_url: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum D2ATransport {
Http,
Mcp,
}
impl D2ADevice {
pub fn new(url: impl Into<String>, token: impl Into<String>) -> Result<Self> {
Self::with_transport(url, token, D2ATransport::Http, None)
}
pub fn with_transport(
url: impl Into<String>,
token: impl Into<String>,
transport: D2ATransport,
event_url: Option<String>,
) -> Result<Self> {
let url = url.into().trim_end_matches('/').to_owned();
let token = token.into();
if token.trim().is_empty() {
return Err(invalid("Device credential is required"));
}
validate_gateway_url(&url)?;
if let Some(value) = &event_url {
validate_gateway_url(value)?;
}
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
.map_err(|_| invalid("Invalid provider credential"))?,
);
headers.insert(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json, text/event-stream"),
);
Ok(Self {
url,
transport,
event_url,
client: reqwest::Client::builder()
.default_headers(headers)
.redirect(Policy::none())
.connect_timeout(Duration::from_secs(15))
.read_timeout(Duration::from_secs(60))
.build()?,
})
}
async fn call(
&self,
method: Method,
path: &str,
operation: &str,
body: Option<Value>,
) -> Result<Value> {
if self.transport == D2ATransport::Http {
let mut request = self.client.request(method, format!("{}{path}", self.url));
if let Some(body) = body {
request = request.json(&body);
}
let response = request.send().await?;
if !response.status().is_success() {
return Err(invalid(format!(
"Device gateway request failed ({})",
response.status()
)));
}
return bounded_json(response).await;
}
let response=self.client.post(&self.url).json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"marona","version":env!("CARGO_PKG_VERSION")}}})).send().await?;
let mut headers = reqwest::header::HeaderMap::new();
if let Some(id) = response.headers().get("mcp-session-id") {
headers.insert("mcp-session-id", id.clone());
}
let initialized = crate::b2a_codec::rpc(response, 1).await?;
let version = initialized["protocolVersion"]
.as_str()
.ok_or_else(|| invalid("Missing MCP protocol version"))?;
if !["2025-11-25", "2025-06-18", "2025-03-26"].contains(&version) {
return Err(invalid("Unsupported MCP protocol version"));
}
headers.insert(
"MCP-Protocol-Version",
reqwest::header::HeaderValue::from_str(version)
.map_err(|_| invalid("Invalid MCP version"))?,
);
let outcome=async {let ready=self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})).send().await?;if !ready.status().is_success(){return Err(invalid("MCP initialization rejected"));}let response=self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":operation,"arguments":body.unwrap_or_else(||json!({}))}})).send().await?;let result=crate::b2a_codec::rpc(response,2).await?;if result["isError"]==true{return Err(invalid("D2A MCP tool failed"));}let value=result.get("structuredContent").ok_or_else(||invalid("D2A MCP requires structuredContent"))?;Ok(value.get("data").filter(|_|value["success"]==true).unwrap_or(value).clone())}.await;
if headers.contains_key("mcp-session-id") {
let _ = self
.client
.delete(&self.url)
.headers(headers)
.timeout(Duration::from_secs(2))
.send()
.await;
}
outcome
}
}
fn validate_gateway_url(value: &str) -> Result<()> {
let url = url::Url::parse(value).map_err(|_| invalid("Invalid device gateway URL"))?;
let local = matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
if !(url.scheme() == "https" || url.scheme() == "http" && local)
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
|| url.query().is_some()
{
return Err(invalid(
"Device gateways require HTTPS except loopback development",
));
}
Ok(())
}
#[async_trait]
impl D2AProvider for D2ADevice {
async fn discover(&self) -> Result<D2ADiscovery> {
let result: D2ADiscovery = serde_json::from_value(
self.call(Method::GET, "/v1/devices", "discover", None)
.await?,
)
.map_err(|_| invalid("Invalid device discovery"))?;
result.validate()?;
Ok(result)
}
async fn events(&self, session_id: &str, cursor: Option<&str>) -> Result<D2AMessageStream> {
let endpoint=match (&self.event_url,self.transport){(Some(url),_)=>url.clone(),(None,D2ATransport::Http)=>format!("{}/v1/events",self.url),_=>return Err(invalid("MCP request tools require an explicit persistent event URL or native streaming provider"))};
let mut query = vec![("session_id", session_id)];
if let Some(cursor) = cursor {
query.push(("cursor", cursor));
}
let response = self.client.get(endpoint).query(&query).send().await?;
if !response.status().is_success() {
return Err(invalid("Device event stream rejected"));
}
let mut stream = json_events(response);
Ok(Box::pin(
async_stream::try_stream! {while let Some(value)=stream.next().await{let value=value?;yield D2AMessage::from_value(value.get("message").unwrap_or(&value).clone())?;}},
))
}
async fn execute(&self, message: &D2AMessage) -> Result<D2AMessage> {
D2AMessage::from_value(
self.call(
Method::POST,
"/v1/actions",
"execute",
Some(if self.transport == D2ATransport::Mcp {
json!({"message":message})
} else {
message.to_value()
}),
)
.await?,
)
}
async fn get_action(&self, id: &str) -> Result<D2AMessage> {
if !nonempty(id) {
return Err(invalid("Action ID is required"));
}
let id_path = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
D2AMessage::from_value(
self.call(
Method::GET,
&format!("/v1/actions/{id_path}"),
"get_action",
Some(json!({"action_id":id})),
)
.await?,
)
}
async fn cancel(&self, id: &str) -> Result<D2AMessage> {
if !nonempty(id) {
return Err(invalid("Action ID is required"));
}
let id_path = url::form_urlencoded::byte_serialize(id.as_bytes()).collect::<String>();
D2AMessage::from_value(
self.call(
Method::POST,
&format!("/v1/actions/{id_path}/cancel"),
"cancel",
Some(json!({"action_id":id})),
)
.await?,
)
}
}
async fn bounded_json(response: reqwest::Response) -> Result<Value> {
let mut body = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if body.len() + chunk.len() > 2_097_152 {
return Err(invalid("Device response exceeds 2 MiB"));
}
body.extend_from_slice(&chunk);
}
serde_json::from_slice(&body).map_err(|_| invalid("Invalid device JSON response"))
}
fn json_events(response: reqwest::Response) -> Pin<Box<dyn Stream<Item = Result<Value>> + Send>> {
Box::pin(
async_stream::try_stream! {let mut bytes=response.bytes_stream();let mut buffer=Vec::new();let mut data=Vec::new();while let Some(chunk)=bytes.next().await{buffer.extend_from_slice(&chunk?);if buffer.len()+data.len()>1_048_576{Err(invalid("D2A event exceeds 1 MiB"))?;}while let Some(end)=buffer.iter().position(|b|*b==b'\n'){let mut line:Vec<u8>=buffer.drain(..=end).collect();line.pop();if line.last()==Some(&b'\r'){line.pop();}if line.is_empty(){if !data.is_empty(){let event:Value=serde_json::from_slice(&data).map_err(|_|invalid("Invalid D2A SSE JSON"))?;data.clear();yield event;}}else if line.starts_with(b"data:"){if !data.is_empty(){data.push(b'\n');}let value=&line[5..];data.extend_from_slice(value.strip_prefix(b" ").unwrap_or(value));}}}if !buffer.is_empty()||!data.is_empty(){Err(invalid("D2A SSE ended mid-event"))?;}},
)
}
/// Compatibility spelling for applications using a device gateway.
pub type D2AGateway = D2ADevice;