use crate::{B2AIntent, B2AMessage, Error, Result};
use reqwest::{
header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE},
redirect::Policy,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::time::Duration;
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum B2ADecodeStatus {
Decoded,
Abstain,
PoorSignal,
CalibrationRequired,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2ADecodeResult {
pub status: B2ADecodeStatus,
pub intent: Option<B2AIntent>,
#[serde(default)]
pub message: Option<B2AMessage>,
pub provenance: Value,
pub uncertainty: Value,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEncodedFeedback {
pub feedback_id: String,
pub profile: String,
pub media_type: String,
pub content: Value,
pub provenance: Value,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum B2ACodecTransport {
#[default]
Http,
Mcp,
}
#[derive(Clone, Debug)]
pub struct B2ACodecOptions {
pub transport: B2ACodecTransport,
pub timeout: Duration,
pub decode_tool: String,
pub encode_tool: String,
pub decode_path: String,
pub encode_path: String,
pub allow_simulation: bool,
}
impl Default for B2ACodecOptions {
fn default() -> Self {
Self {
transport: B2ACodecTransport::Http,
timeout: Duration::from_secs(60),
decode_tool: "decode".into(),
encode_tool: "encode".into(),
decode_path: "/v1/decode".into(),
encode_path: "/v1/encode".into(),
allow_simulation: false,
}
}
}
#[derive(Clone)]
pub struct B2ACodec {
url: String,
client: reqwest::Client,
options: B2ACodecOptions,
}
impl B2ACodec {
pub fn new(url: &str, token: &str) -> Result<Self> {
Self::with_options(url, token, B2ACodecOptions::default())
}
pub fn with_options(url: &str, token: &str, options: B2ACodecOptions) -> Result<Self> {
let parsed = url::Url::parse(url).map_err(|_| bad("Invalid codec URL"))?;
if !["http", "https"].contains(&parsed.scheme())
|| parsed.host_str().is_none()
|| !parsed.username().is_empty()
|| parsed.password().is_some()
|| parsed.query().is_some()
|| parsed.fragment().is_some()
{
return Err(bad("Invalid codec endpoint"));
}
if parsed.scheme() == "http"
&& !["localhost", "127.0.0.1", "[::1]", "::1"]
.contains(&parsed.host_str().unwrap_or(""))
{
return Err(bad("Remote codec endpoints require HTTPS"));
}
for text in [token, &options.decode_tool, &options.encode_tool] {
nonempty(text)?;
}
for path in [&options.decode_path, &options.encode_path] {
if !path.starts_with('/') || path.starts_with("//") || path.contains(['?', '#', '\\']) {
return Err(bad("Invalid codec path"));
}
}
if options.timeout.is_zero() {
return Err(bad("Codec timeout must be positive"));
}
let mut headers = HeaderMap::new();
let mut auth = HeaderValue::from_str(&format!("Bearer {token}"))
.map_err(|_| bad("Invalid neural credential"))?;
auth.set_sensitive(true);
headers.insert(AUTHORIZATION, auth);
headers.insert(
ACCEPT,
HeaderValue::from_static("application/json, text/event-stream"),
);
let client = reqwest::Client::builder()
.default_headers(headers)
.redirect(Policy::none())
.timeout(options.timeout)
.build()?;
Ok(Self {
url: parsed.as_str().trim_end_matches('/').into(),
client,
options,
})
}
pub async fn decode(&self, signal: &Value, consent: bool) -> Result<B2ADecodeResult> {
require_consent(consent)?;
object(Some(signal))?;
let data = self
.call("decode", json!({"signal":signal,"consent":true}))
.await?;
let status: B2ADecodeStatus =
serde_json::from_value(data.get("status").cloned().unwrap_or(Value::Null))
.map_err(|_| bad("Invalid decoder status"))?;
let provenance = self.provenance(data.get("provenance"))?;
let uncertainty = Value::Object(object(data.get("uncertainty"))?);
if let Some(message) = data.get("message").filter(|v| !v.is_null()) {
if status != B2ADecodeStatus::Decoded {
return Err(bad("An abstaining decoder cannot return a message"));
}
let mut body = serde_json::to_value(B2AMessage::from_value(message.clone())?)
.map_err(|e| bad(&e.to_string()))?;
body["payload"]["provenance"] = provenance.clone();
body["payload"]["uncertainty"] = uncertainty.clone();
for block in body["payload"]["content"].as_array_mut().unwrap() {
if block["uri"].as_str().is_some_and(|v| v.starts_with("b2a:")) {
let resource = self
.call("read_resource", json!({"uri":block["uri"],"consent":true}))
.await?;
if resource["type"] != block["type"]
|| resource["mime_type"] != block["mime_type"]
|| resource["uri"]
.as_str()
.is_some_and(|v| v.starts_with("b2a:"))
{
return Err(bad("Resource resolution must preserve type/MIME and return inline data or HTTPS"));
}
let target = block.as_object_mut().unwrap();
if resource.get("data").is_some() {
target.remove("uri");
}
target.extend(resource.as_object().unwrap().clone());
}
}
return Ok(B2ADecodeResult {
status,
intent: None,
message: Some(B2AMessage::from_value(body)?),
provenance,
uncertainty,
});
}
let content = data.get("intent").cloned().unwrap_or(Value::Null);
let intent = if status == B2ADecodeStatus::Decoded {
if content.as_object().is_some_and(Map::is_empty) {
return Err(bad("Decoder returned empty intent"));
}
let mut intent = B2AIntent::new(content)?;
if let Some(confidence) = data.get("confidence").filter(|v| !v.is_null()) {
intent = intent.with_confidence(
confidence
.as_f64()
.ok_or_else(|| bad("Invalid decoder confidence"))?,
)?;
}
let mut metadata = object(Some(&provenance))?;
metadata.insert("uncertainty".into(), uncertainty.clone());
if let Some(id) = signal.get("signal_id").filter(|v| !v.is_null()) {
metadata.insert("signal_id".into(), json!(text(Some(id))?));
}
let mut decoder = Map::new();
for (key, source) in [("id", "backend"), ("version", "version")] {
if let Some(value) = provenance.get(source).filter(|v| !v.is_null()) {
decoder.insert(key.into(), json!(text(Some(value))?));
}
}
if !decoder.is_empty() {
intent.decoder = Some(Value::Object(decoder));
}
intent.provenance = Some(Value::Object(metadata));
intent.validate()?;
Some(intent)
} else {
if !content.is_null() {
return Err(bad("Abstaining decoder returned actionable intent"));
}
None
};
Ok(B2ADecodeResult {
status,
intent,
message: None,
provenance,
uncertainty,
})
}
pub async fn encode(
&self,
response: &Value,
profile: &str,
consent: bool,
) -> Result<B2AEncodedFeedback> {
self.encode_with(
response,
profile,
consent,
&json!({}),
&["application/json"],
)
.await
}
pub async fn encode_with(
&self,
response: &Value,
profile: &str,
consent: bool,
context: &Value,
media_types: &[&str],
) -> Result<B2AEncodedFeedback> {
require_consent(consent)?;
nonempty(profile)?;
object(Some(response))?;
object(Some(context))?;
if media_types.is_empty() {
return Err(bad("At least one output media type is required"));
}
for media in media_types {
nonempty(media)?;
}
let data = self.call("encode", json!({"request":{"response":response,"profile":profile,"context":context},"consent":true})).await?;
let media_type = text(data.get("media_type"))?;
if data.get("profile").and_then(Value::as_str) != Some(profile)
|| !media_types.contains(&media_type.as_str())
{
return Err(bad("Encoder output does not match interface capabilities"));
}
Ok(B2AEncodedFeedback {
feedback_id: text(data.get("feedback_id"))?,
profile: profile.into(),
media_type,
content: Value::Object(object(Some(data.get("content").unwrap_or(&Value::Null)))?),
provenance: self.provenance(data.get("provenance"))?,
})
}
fn provenance(&self, value: Option<&Value>) -> Result<Value> {
let provenance = object(value)?;
let flag = match provenance.get("simulation") {
None => false,
Some(Value::Bool(v)) => *v,
_ => return Err(bad("Invalid neural provenance")),
};
if flag && !self.options.allow_simulation {
return Err(bad("Neural output failed provenance validation"));
}
Ok(Value::Object(provenance))
}
async fn call(&self, operation: &str, arguments: Value) -> Result<Value> {
tokio::time::timeout(self.options.timeout, self.exchange(operation, arguments))
.await
.map_err(|_| {
Error::Timeout(self.options.timeout.as_millis().min(u64::MAX as u128) as u64)
})?
}
async fn exchange(&self, operation: &str, arguments: Value) -> Result<Value> {
if self.options.transport == B2ACodecTransport::Http {
let path = if operation == "read_resource" {
"/v1/resources/read"
} else if operation == "decode" {
&self.options.decode_path
} else {
&self.options.encode_path
};
let response = self
.client
.post(format!("{}{path}", self.url))
.json(&arguments)
.send()
.await?;
success(&response)?;
let value: Value = response.json().await?;
object(Some(&value))?;
return Ok(value);
}
let mut headers = HeaderMap::new();
let initialization = 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?;
success(&initialization)?;
if let Some(value) = initialization.headers().get("mcp-session-id") {
headers.insert("mcp-session-id", value.clone());
}
let result = async {
let initialized = rpc(initialization, 1).await?;
let version = text(initialized.get("protocolVersion"))?;
if !["2025-11-25", "2025-06-18", "2025-03-26"].contains(&version.as_str()) { return Err(bad("Unsupported MCP protocol version")); }
headers.insert("MCP-Protocol-Version", HeaderValue::from_str(&version).map_err(|_| bad("Invalid MCP version"))?);
let response = self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","method":"notifications/initialized"})).send().await?;
success(&response)?; drop(response);
let tool = if operation == "read_resource" { "read_resource" } else if operation == "decode" { &self.options.decode_tool } else { &self.options.encode_tool };
let response = self.client.post(&self.url).headers(headers.clone()).json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":tool,"arguments":arguments}})).send().await?;
success(&response)?; let result = rpc(response, 2).await?;
let structured = result.get("structuredContent").ok_or_else(|| bad("Missing MCP structured result"))?;
if result.get("isError") == Some(&Value::Bool(true)) || structured.get("success") != Some(&Value::Bool(true)) { return Err(bad("Neural MCP tool failed")); }
let data = structured.get("data").ok_or_else(|| bad("Missing neural result"))?; object(Some(data))?; Ok(data.clone())
}.await;
if headers.contains_key("mcp-session-id") {
let _ = self
.client
.delete(&self.url)
.headers(headers)
.timeout(Duration::from_secs(1))
.send()
.await;
}
result
}
}
fn bad(message: &str) -> Error {
Error::Validation(message.into())
}
fn nonempty(value: &str) -> Result<()> {
if value.trim().is_empty() {
Err(bad("Expected nonempty codec text"))
} else {
Ok(())
}
}
fn text(value: Option<&Value>) -> Result<String> {
let text = value
.and_then(Value::as_str)
.ok_or_else(|| bad("Expected codec text"))?;
nonempty(text)?;
Ok(text.into())
}
fn object(value: Option<&Value>) -> Result<Map<String, Value>> {
match value {
None => Ok(Map::new()),
Some(Value::Object(v)) => Ok(v.clone()),
_ => Err(bad("Expected codec JSON object")),
}
}
fn require_consent(value: bool) -> Result<()> {
if value {
Ok(())
} else {
Err(bad("Neural processing requires explicit consent"))
}
}
fn success(response: &reqwest::Response) -> Result<()> {
if response.status().is_success() {
Ok(())
} else {
Err(bad(&format!(
"Neural service returned HTTP {}",
response.status().as_u16()
)))
}
}
fn rpc_value(value: Value, id: u64) -> Result<Option<Value>> {
object(Some(&value))?;
if value.get("id").and_then(Value::as_u64) != Some(id) {
return Ok(None);
}
if value.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || value.get("error").is_some() {
return Err(bad("Neural MCP request failed"));
}
let result = value
.get("result")
.ok_or_else(|| bad("Missing MCP result"))?;
object(Some(result))?;
Ok(Some(result.clone()))
}
pub(crate) async fn rpc(mut response: reqwest::Response, id: u64) -> Result<Value> {
if !response
.headers()
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.contains("text/event-stream")
{
return rpc_value(response.json().await?, id)?
.ok_or_else(|| bad("MCP response ID mismatch"));
}
let mut buffer = Vec::new();
let mut data = Vec::new();
let mut size = 0usize;
while let Some(chunk) = response.chunk().await? {
size += chunk.len();
if size > 2_097_152 {
return Err(bad("MCP response exceeds size limit"));
}
buffer.extend_from_slice(&chunk);
while let Some(position) = buffer.iter().position(|v| *v == b'\n') {
let line: Vec<u8> = buffer.drain(..=position).collect();
let line = std::str::from_utf8(&line)
.map_err(|_| bad("Invalid MCP UTF-8"))?
.trim_end_matches(['\r', '\n']);
if line.is_empty() {
let payload = data.join("\n");
if !payload.trim().is_empty() {
let value =
serde_json::from_str(&payload).map_err(|_| bad("Invalid MCP JSON"))?;
if let Some(result) = rpc_value(value, id)? {
return Ok(result);
}
}
data.clear();
} else if let Some(value) = line.strip_prefix("data:") {
data.push(value.strip_prefix(' ').unwrap_or(value).to_owned());
}
}
}
Err(bad("MCP stream ended without a matching response"))
}