marona 5.5.0

Marona Agents, MCP server and App authoring, B2A, D2A, realtime and A2A
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//! Brain2Agent 1.0 sessions, semantic intent and encoded-feedback exchange.
//!
//! The interface service owns signal decoding and feedback encoding. B2A carries
//! their open-ended semantic messages to native Marona endpoints. Preserve a
//! constructed message unchanged when retrying; do not generate a new ID.

use std::{collections::BTreeSet, sync::Arc};

use reqwest::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use time::{format_description::well_known::Rfc3339, OffsetDateTime};
use uuid::Uuid;

use crate::{core::Core, Agent, AgentTool, Error, Result};

pub const B2A_PROTOCOL_VERSION: &str = "1.0";
#[path = "b2a_content.rs"]
pub(crate) mod content;

/// An arbitrary semantic intent produced by a decoder, with optional evidence.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct B2AIntent {
    pub content: Value,
    pub media_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decoder: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<Value>,
}

impl B2AIntent {
    pub fn new(content: impl Into<Value>) -> Result<Self> {
        let content = content.into();
        let value = Self {
            media_type: if content.is_string() {
                "text/plain"
            } else {
                "application/json"
            }
            .into(),
            content,
            confidence: None,
            decoder: None,
            provenance: None,
        };
        value.validate()?;
        Ok(value)
    }

    pub fn with_confidence(mut self, confidence: f64) -> Result<Self> {
        self.confidence = Some(confidence);
        self.validate()?;
        Ok(self)
    }

    pub fn validate(&self) -> Result<()> {
        if !self.content.is_object()
            && !self
                .content
                .as_str()
                .is_some_and(|value| !value.trim().is_empty())
        {
            return invalid("intent content must be a JSON object or nonempty string");
        }
        if !["application/json", "text/plain"].contains(&self.media_type.as_str()) {
            return invalid("intent media_type must be application/json or text/plain");
        }
        if self.media_type == "text/plain" && !self.content.is_string() {
            return invalid("text/plain intent content must be a string");
        }
        if self
            .confidence
            .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))
        {
            return invalid("confidence must be finite and between 0 and 1");
        }
        for (name, value) in [("decoder", &self.decoder), ("provenance", &self.provenance)] {
            if value.as_ref().is_some_and(|value| !value.is_object()) {
                return invalid(&format!("{name} must be a JSON object"));
            }
        }
        Ok(())
    }
}

/// A stable envelope for idempotent retries. Incoming sequence starts at one.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct B2AMessage {
    pub protocol: String,
    pub version: String,
    pub message_id: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub session_id: String,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub sequence: u64,
    #[serde(rename = "type")]
    pub message_type: String,
    pub timestamp: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
    #[serde(default = "default_source")]
    pub source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<Value>,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
    pub payload: Value,
}

fn is_zero(value: &u64) -> bool {
    *value == 0
}
fn default_source() -> String {
    "neural_decoder".into()
}

impl B2AMessage {
    pub fn new(
        session_id: impl Into<String>,
        sequence: u64,
        message_type: impl Into<String>,
        payload: Value,
    ) -> Result<Self> {
        let value = Self {
            protocol: "b2a".into(),
            version: "0.1".into(),
            message_id: Uuid::new_v4().to_string(),
            session_id: session_id.into(),
            sequence,
            message_type: message_type.into(),
            timestamp: OffsetDateTime::now_utc()
                .format(&Rfc3339)
                .map_err(|error| Error::Validation(error.to_string()))?,
            expires_at: None,
            source: default_source(),
            stream: None,
            extra: Map::new(),
            payload,
        };
        value.validate()?;
        Ok(value)
    }

    pub fn multimodal(source: &str, content: Vec<Value>) -> Result<Self> {
        Self::from_value(
            json!({"protocol":"b2a","version":"1.0","type":"message","source":source,
            "message_id":Uuid::new_v4().to_string(),"timestamp":OffsetDateTime::now_utc().format(&Rfc3339).map_err(|e| Error::Validation(e.to_string()))?,
            "payload":{"content":content}}),
        )
    }
    pub fn from_value(value: Value) -> Result<Self> {
        if value["type"] == "message"
            && [
                "protocol",
                "version",
                "source",
                "message_id",
                "timestamp",
                "payload",
            ]
            .iter()
            .any(|key| value.get(key).is_none())
        {
            return invalid("Missing canonical message fields");
        }
        let message: Self =
            serde_json::from_value(value).map_err(|e| Error::Validation(e.to_string()))?;
        message.validate()?;
        Ok(message)
    }
    pub fn bind(
        mut self,
        session_id: &str,
        sequence: u64,
        context_revision: u64,
        execute: bool,
    ) -> Result<Self> {
        self.session_id = session_id.into();
        self.sequence = sequence;
        self.payload["context_revision"] = json!(context_revision);
        self.payload["execute"] = json!(execute);
        self.validate()?;
        Ok(self)
    }
    /// Build an intent envelope. `execute` never bypasses runtime approval gates.
    pub fn intent(
        session_id: impl Into<String>,
        sequence: u64,
        intent: B2AIntent,
        context_revision: u64,
        execute: bool,
    ) -> Result<Self> {
        intent.validate()?;
        Self::new(
            session_id,
            sequence,
            "intent.submit",
            json!({
                "intent": intent,
                "context_revision": context_revision,
                "execute": execute,
            }),
        )
    }

    /// Continue the same conversation in response to a question.
    pub fn clarification(
        session_id: impl Into<String>,
        sequence: u64,
        intent: B2AIntent,
        context_revision: u64,
        execute: bool,
    ) -> Result<Self> {
        let mut message = Self::intent(session_id, sequence, intent, context_revision, execute)?;
        message.message_type = "intent.clarify".into();
        Ok(message)
    }

    pub fn validate(&self) -> Result<()> {
        if self.protocol != "b2a" || !["0.1", "1.0"].contains(&self.version.as_str()) {
            return invalid("this client supports B2A versions 0.1 and 1.0");
        }
        nonempty(&self.message_id, "message_id")?;

        nonempty(&self.message_type, "type")?;
        if self.session_id.is_empty() != (self.sequence == 0) {
            return invalid("sequence must be at least one");
        }
        if !self.payload.is_object() {
            return invalid("payload must be a JSON object");
        }
        validate_timestamp(&self.timestamp)?;
        if let Some(expires_at) = &self.expires_at {
            validate_timestamp(expires_at)?;
        }
        if self.message_type == "message" {
            content::validate(
                &serde_json::to_value(self).map_err(|e| Error::Validation(e.to_string()))?,
            )?;
        }
        if ["intent.submit", "intent.clarify"].contains(&self.message_type.as_str()) {
            let intent = self
                .payload
                .get("intent")
                .ok_or_else(|| Error::Validation("B2A intent payload is missing intent".into()))?;
            let intent: B2AIntent = serde_json::from_value(intent.clone())
                .map_err(|error| Error::Validation(format!("invalid B2A intent: {error}")))?;
            intent.validate()?;
            if self
                .payload
                .get("context_revision")
                .is_some_and(|value| value.as_u64().is_none())
            {
                return invalid("context_revision must be a nonnegative integer");
            }
            if self
                .payload
                .get("execute")
                .is_some_and(|value| !value.is_boolean())
            {
                return invalid("execute must be a boolean");
            }
        }
        Ok(())
    }
}

/// Session creation requires explicit consent and declared interface capabilities.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AOpenSession {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversation_id: Option<String>,
    pub protocol_version: String,
    pub user_id: String,
    pub device_id: String,
    pub consent: Value,
    pub capabilities: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent: Option<Value>,
    pub context: Value,
    pub ttl_seconds: u64,
}

impl B2AOpenSession {
    pub fn new(
        user_id: impl Into<String>,
        device_id: impl Into<String>,
        consent: Value,
        capabilities: Value,
    ) -> Self {
        Self {
            protocol_version: "0.1".into(),
            conversation_id: None,
            user_id: user_id.into(),
            device_id: device_id.into(),
            consent,
            capabilities,
            agent: None,
            context: json!({}),
            ttl_seconds: 3600,
        }
    }

    /// Serialize server-executable Agent settings, graph and governed Hub scope.
    /// SDK callbacks, local functions and SDK-managed peers cannot run remotely.
    pub fn with_agent(mut self, agent: &Agent) -> Result<Self> {
        self.agent = Some(b2a_agent_config(agent)?);
        Ok(self)
    }

    fn validate(&self) -> Result<()> {
        if !["0.1", "1.0"].contains(&self.protocol_version.as_str()) {
            return invalid("this client supports B2A versions 0.1 and 1.0");
        }
        nonempty(&self.user_id, "user_id")?;
        nonempty(&self.device_id, "device_id")?;
        if self.ttl_seconds == 0 {
            return invalid("ttl_seconds must be greater than zero");
        }
        for (name, value) in [
            ("consent", &self.consent),
            ("capabilities", &self.capabilities),
            ("context", &self.context),
        ] {
            if !value.is_object() {
                return invalid(&format!("{name} must be a JSON object"));
            }
        }
        if self.agent.as_ref().is_some_and(|value| !value.is_object()) {
            return invalid("agent must be a JSON object");
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2ASession {
    pub protocol: String,
    pub version: String,
    pub session_id: String,
    pub state: String,
    pub user_id: String,
    pub device_id: String,
    pub capabilities: Value,
    pub consent: Value,
    pub context: Value,
    pub context_revision: u64,
    pub next_sequence: u64,
    pub expires_at: String,
    pub created_at: String,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEvent {
    pub protocol: String,
    pub version: String,
    pub event_id: String,
    pub session_id: String,
    pub sequence: u64,
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(default)]
    pub correlation_id: Option<String>,
    pub timestamp: String,
    pub payload: Value,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AAcknowledgment {
    pub message_id: String,
    pub status: String,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AExchange {
    pub protocol: String,
    pub version: String,
    pub session_id: String,
    pub ack: B2AAcknowledgment,
    pub events: Vec<B2AEvent>,
    pub session: B2ASession,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct B2AEventPage {
    pub protocol: String,
    pub version: String,
    pub session_id: String,
    pub events: Vec<B2AEvent>,
    pub next_cursor: u64,
    pub has_more: bool,
    #[serde(flatten)]
    pub extra: Map<String, Value>,
}

pub type B2AEventStream = std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<Value>> + Send>>;

/// Native B2A client. All requests retain the Marona project's authentication,
/// timeout, custom HTTP client, headers and response-size limit.
#[derive(Clone, Debug)]
pub struct B2AClient {
    pub(crate) core: Arc<Core>,
}

impl B2AClient {
    pub async fn capabilities(&self) -> Result<Value> {
        self.core
            .json(
                &self.core.runtime_url,
                Method::GET,
                "/runtime/b2a/capabilities",
                None,
            )
            .await
    }

    pub async fn open_session(&self, request: B2AOpenSession) -> Result<B2ASession> {
        request.validate()?;
        let body =
            serde_json::to_value(request).map_err(|error| Error::Validation(error.to_string()))?;
        self.core
            .json(
                &self.core.runtime_url,
                Method::POST,
                "/runtime/b2a/sessions",
                Some(&body),
            )
            .await
    }

    pub async fn get_session(&self, session_id: &str) -> Result<B2ASession> {
        self.core
            .json(
                &self.core.runtime_url,
                Method::GET,
                &session_path(session_id)?,
                None,
            )
            .await
    }

    pub async fn close_session(&self, session_id: &str) -> Result<B2ASession> {
        self.core
            .json(
                &self.core.runtime_url,
                Method::DELETE,
                &session_path(session_id)?,
                None,
            )
            .await
    }

    pub async fn send_message(
        &self,
        session_id: &str,
        message: &B2AMessage,
    ) -> Result<B2AExchange> {
        message.validate()?;
        if session_id != message.session_id {
            return invalid("envelope session_id does not match the requested session");
        }
        let body =
            serde_json::to_value(message).map_err(|error| Error::Validation(error.to_string()))?;
        self.core
            .json(
                &self.core.runtime_url,
                Method::POST,
                &format!("{}/messages", session_path(session_id)?),
                Some(&body),
            )
            .await
    }

    /// Authenticated live progress, followed by the durable exchange. No automatic replay.
    pub async fn stream_message(
        &self,
        session_id: &str,
        message: &B2AMessage,
    ) -> Result<B2AEventStream> {
        use futures_util::StreamExt;
        message.validate()?;
        if message.session_id != session_id {
            return invalid("B2A stream session mismatch");
        }
        let response = self
            .core
            .stream_client
            .post(format!(
                "{}{}/messages/stream",
                self.core.runtime_url,
                session_path(session_id)?
            ))
            .headers(self.core.headers.clone())
            .bearer_auth(self.core.require_api_key()?)
            .header("Accept", "text/event-stream")
            .json(message)
            .send()
            .await?;
        if !response.status().is_success() {
            let status = response.status();
            let body = self.core.response_body(response).await?;
            return Err(Error::api(status, serde_json::from_slice(&body).ok()));
        }
        self.core.check_response(&response)?;
        let core = self.core.clone();
        let id = session_id.to_owned();
        let mid = message.message_id.clone();
        Ok(Box::pin(async_stream::try_stream! {
            let mut source = response.bytes_stream();
            let mut buffer = Vec::new();
            let mut received = 0;
            while let Some(chunk) = source.next().await {
                let chunk = chunk?;
                received = core.response_size(received, chunk.len())?;
                buffer.extend_from_slice(&chunk);
                while let Some(end) = buffer.iter().position(|b| *b == b'\n') {
                    let line: Vec<u8> = buffer.drain(..=end).collect();
                    if !line.starts_with(b"data:") {continue;}
                    let event: Value = serde_json::from_slice(&line[5..]).map_err(|_| Error::Protocol("Invalid B2A stream JSON".into()))?;
                    if event["session_id"] != id || event["correlation_id"] != mid { Err(Error::Protocol("B2A stream identity mismatch".into()))?; }
                    if event["type"] == "exchange.completed" {
                        let exchange = &event["exchange"];
                        if exchange["protocol"] != "b2a" || !matches!(exchange["version"].as_str(), Some("0.1" | "1.0")) || exchange["session_id"] != id || exchange["session"]["session_id"] != id || exchange["ack"]["message_id"] != mid || !matches!(exchange["ack"]["status"].as_str(), Some("accepted" | "duplicate" | "processing")) {
                            Err(Error::Protocol("Invalid B2A exchange acknowledgment".into()))?;
                        }
                    }
                    yield event;
                }
                if buffer.len() > 1_048_576 { Err(Error::Protocol("B2A stream frame exceeds size limit".into()))?; }
            }
            if buffer.iter().any(|b| !b.is_ascii_whitespace()) { Err(Error::Protocol("Incomplete B2A stream frame".into()))?; }
        }))
    }

    pub async fn events(&self, session_id: &str, after: u64, limit: u32) -> Result<B2AEventPage> {
        if limit == 0 {
            return invalid("event page limit must be greater than zero");
        }
        self.core
            .json(
                &self.core.runtime_url,
                Method::GET,
                &format!(
                    "{}/events?after={after}&limit={limit}",
                    session_path(session_id)?
                ),
                None,
            )
            .await
    }
}

fn session_path(id: &str) -> Result<String> {
    nonempty(id, "session_id")?;
    let encoded: String = url::form_urlencoded::byte_serialize(id.as_bytes()).collect();
    Ok(format!("/runtime/b2a/sessions/{encoded}"))
}

fn nonempty(value: &str, name: &str) -> Result<()> {
    if value.trim().is_empty() {
        invalid(&format!("{name} must be nonempty"))
    } else {
        Ok(())
    }
}

fn validate_timestamp(value: &str) -> Result<()> {
    OffsetDateTime::parse(value, &Rfc3339)
        .map(|_| ())
        .map_err(|_| Error::Validation("B2A timestamps must use RFC3339 with a timezone".into()))
}

fn invalid<T>(message: &str) -> Result<T> {
    Err(Error::Validation(format!("B2A {message}")))
}

/// Convert an Agent into the subset that native B2A can execute remotely.
pub fn b2a_agent_config(agent: &Agent) -> Result<Value> {
    crate::agent::validate_graph(agent)?;
    let mut apps = BTreeSet::new();
    let mut skills = BTreeSet::new();
    let mut all_apps = false;
    let mut seen = BTreeSet::new();

    fn visit(
        agent: &Agent,
        seen: &mut BTreeSet<String>,
        apps: &mut BTreeSet<String>,
        skills: &mut BTreeSet<String>,
        all_apps: &mut bool,
    ) -> Result<()> {
        if !seen.insert(agent.name.clone()) {
            return Ok(());
        }
        if agent.hooks.is_some()
            || agent.instruction_provider.is_some()
            || !agent.input_guardrails.is_empty()
            || !agent.output_guardrails.is_empty()
            || !agent.peers.is_empty()
        {
            return invalid("native sessions cannot execute SDK callbacks, guardrails, dynamic instructions or SDK A2A peers");
        }
        if let Some(connection) = &agent.hub_tools {
            *all_apps |= connection.unscoped;
            if let Some(values) = connection.b2a_scope.get("apps").and_then(Value::as_array) {
                apps.extend(values.iter().filter_map(Value::as_str).map(str::to_owned));
            }
            if let Some(values) = connection.b2a_scope.get("skills").and_then(Value::as_array) {
                skills.extend(values.iter().filter_map(Value::as_str).map(str::to_owned));
            }
        }
        for tool in &agent.tools {
            match tool {
                AgentTool::Function(_) => {
                    return invalid(
                        "native sessions require server-hosted tools, not local functions",
                    )
                }
                AgentTool::Delegation { agent, .. } => visit(agent, seen, apps, skills, all_apps)?,
            }
        }
        for handoff in &agent.handoffs {
            if handoff.input_filter.is_some() {
                return invalid("native sessions cannot execute local handoff input filters");
            }
            visit(&handoff.agent, seen, apps, skills, all_apps)?;
        }
        Ok(())
    }

    visit(agent, &mut seen, &mut apps, &mut skills, &mut all_apps)?;
    let mut result = json!({
        "name": agent.name,
        "instructions": agent.instructions,
        "model": agent.model,
        "tool_choice": agent.tool_choice,
        "tools_enabled": agent.hub_tools.is_some() || !agent.tools.is_empty() || !agent.handoffs.is_empty(),
        "max_turns": agent.max_turns,
        "model_settings": agent.model_settings,
        "multi_agent": crate::agent::graph_value(agent),
        "connection_scope": {"all_apps": all_apps, "apps": apps, "skills": skills},
        "output": crate::agent::output_request(agent),
    });
    if let Some(routing) = &agent.routing {
        result["routing"] = json!(routing);
    }
    if let Some(capabilities) = agent.metadata.get("_marona_protocol_capabilities") {
        result["protocol_capabilities"] = capabilities.clone();
    }
    Ok(result)
}