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
//! Extensible communication protocols and automatic session coordination.
use crate::{Agent, Error, Input, Result, RunEvent, RunResult};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::{
    any::Any,
    collections::{HashMap, HashSet, VecDeque},
    sync::Arc,
    time::Duration,
};
use tokio::sync::{mpsc, oneshot};

#[async_trait]
pub trait ProtocolSession: Send {
    async fn send(&mut self, input: &Value) -> Result<()>;
    async fn next_event(&mut self) -> Result<Option<RunEvent>>;
    async fn close(&mut self) -> Result<()>;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    /// Opt in only when deliver and poll_event implement the coordinated session contract.
    fn supports_delivery(&self) -> bool {
        false
    }
    async fn deliver(&mut self, _message: &Value) -> Result<()> {
        Err(Error::Validation(
            "Protocol does not support canonical delivery".into(),
        ))
    }
    fn supports_feedback(&self) -> bool {
        false
    }
    async fn deliver_feedback(&mut self, _message: &Value) -> Result<()> {
        Err(Error::Validation(
            "Protocol does not support feedback delivery".into(),
        ))
    }
    /// Perform one bounded read, returning None when no event is ready. Must not loop indefinitely.
    async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
        self.next_event().await
    }
    fn result(&self) -> Option<RunResult> {
        None
    }
}
#[async_trait]
pub trait AgentProtocol: Any + Send + Sync {
    fn name(&self) -> &str;
    fn accepts(&self, input: &Value) -> bool {
        input["protocol"].as_str() == Some(self.name())
    }
    async fn capabilities(&self) -> Result<Value> {
        Ok(json!({}))
    }
    async fn connect(
        &self,
        agent: &Agent,
        user_id: &str,
        session_id: &str,
    ) -> Result<Box<dyn ProtocolSession>>;
    async fn run(
        &self,
        agent: &Agent,
        input: Input,
        user_id: &str,
        session_id: &str,
    ) -> Result<RunResult>;
}
pub(crate) fn select(agent: &Agent, name: Option<&str>) -> Result<Option<Arc<dyn AgentProtocol>>> {
    let mut protocols = agent.protocols.clone();
    if let Some(config) = &agent.b2a {
        protocols.push(Arc::new(config.clone()));
    }
    let mut names = HashSet::new();
    for protocol in &protocols {
        if protocol.name().trim().is_empty() || !names.insert(protocol.name().to_owned()) {
            return Err(Error::Validation(
                "Protocols must have nonempty, unique names".into(),
            ));
        }
    }
    if let Some(name) = name {
        return protocols
            .into_iter()
            .find(|p| p.name() == name)
            .map(Some)
            .ok_or_else(|| Error::Validation(format!("No configured protocol named {name}")));
    }
    if protocols.len() > 1 {
        return Ok(Some(Arc::new(Coordinator { protocols })));
    }
    Ok(protocols.into_iter().next())
}
struct Coordinator {
    protocols: Vec<Arc<dyn AgentProtocol>>,
}
#[async_trait]
impl AgentProtocol for Coordinator {
    fn name(&self) -> &str {
        "coordinated"
    }
    async fn connect(
        &self,
        agent: &Agent,
        user_id: &str,
        session_id: &str,
    ) -> Result<Box<dyn ProtocolSession>> {
        Ok(Box::new(
            CoordinatedSession::open(agent, &self.protocols, user_id, session_id).await?,
        ))
    }
    async fn run(
        &self,
        agent: &Agent,
        input: Input,
        user_id: &str,
        session_id: &str,
    ) -> Result<RunResult> {
        let input = serde_json::to_value(input).map_err(|e| Error::Validation(e.to_string()))?;
        let mut session =
            CoordinatedSession::open(agent, &self.protocols, user_id, session_id).await?;
        let outcome = async {
            session.send(&input).await?;
            while let Some(event) = session.next_event().await? {
                if event.event_type == "feedback" {
                    if let Some(message) = event.data.get("message") {
                        if message["payload"]["kind"] == "feedback"
                            && message["payload"]["status"] != "succeeded"
                        {
                            return Err(Error::Protocol(format!(
                                "Protocol action outcome: {}",
                                message["payload"]["status"]
                            )));
                        }
                    }
                }
                if event.event_type == "exchange.completed"
                    && event
                        .data
                        .get("action_status")
                        .and_then(Value::as_str)
                        .is_some_and(|s| s != "succeeded")
                {
                    return Err(Error::Protocol(format!(
                        "Protocol action outcome: {}",
                        event.data["action_status"]
                    )));
                }
                if event.event_type == "protocol.route.failed" {
                    return Err(Error::Protocol(format!(
                        "Protocol route failed: {}",
                        Value::Object(event.data)
                    )));
                }
                if let Some(error) = &session.route_failure {
                    return Err(Error::Protocol(error.clone()));
                }
                if matches!(
                    event.event_type.as_str(),
                    "feedback" | "exchange.completed" | "protocol.route.completed"
                ) && session.pending.is_empty()
                {
                    if let Some(result) = session.result() {
                        return Ok(result);
                    }
                }
            }
            Err(Error::Protocol(
                "Coordinated session closed before completion".into(),
            ))
        }
        .await;
        let closed = session.close().await;
        match outcome {
            Ok(value) => {
                closed?;
                Ok(value)
            }
            Err(error) => Err(error),
        }
    }
}
enum Command {
    Feedback(Value, oneshot::Sender<Result<()>>),
    Send(Value, bool, oneshot::Sender<Result<()>>),
    Close(oneshot::Sender<Result<()>>),
}
struct ChildEvent {
    name: String,
    event: Result<RunEvent>,
    result: Option<RunResult>,
}
/// Handle to an attached protocol; its event stream remains owned by the coordinator.
#[derive(Clone)]
pub struct ProtocolConnection {
    commands: mpsc::Sender<Command>,
}
impl ProtocolConnection {
    pub async fn send(&self, input: &Value) -> Result<()> {
        self.call(input, false).await
    }
    pub async fn deliver_feedback(&self, message: &Value) -> Result<()> {
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(Command::Feedback(message.clone(), tx))
            .await
            .map_err(|_| Error::Protocol("Protocol session stopped".into()))?;
        rx.await
            .map_err(|_| Error::Protocol("Protocol session stopped".into()))?
    }
    pub async fn deliver(&self, message: &Value) -> Result<()> {
        self.call(message, true).await
    }
    async fn call(&self, value: &Value, canonical: bool) -> Result<()> {
        let (tx, rx) = oneshot::channel();
        self.commands
            .send(Command::Send(value.clone(), canonical, tx))
            .await
            .map_err(|_| Error::Protocol("Protocol session stopped".into()))?;
        rx.await
            .map_err(|_| Error::Protocol("Protocol session stopped".into()))?
    }
}
#[derive(Clone)]
struct PendingRoute {
    origin: String,
    target: String,
    route_id: String,
    hops: u64,
}
/// A single bounded event stream for every attached protocol. Routing never broadcasts input.
pub struct CoordinatedSession {
    pub session_id: String,
    children: HashMap<String, ProtocolConnection>,
    configurations: Vec<Arc<dyn AgentProtocol>>,
    tasks: Vec<tokio::task::JoinHandle<()>>,
    events: mpsc::Receiver<ChildEvent>,
    queue: VecDeque<RunEvent>,
    seen: HashSet<String>,
    pending: HashMap<String, PendingRoute>,
    last_result: Option<RunResult>,
    route_failure: Option<String>,
    closed: bool,
}
impl CoordinatedSession {
    async fn open(
        agent: &Agent,
        protocols: &[Arc<dyn AgentProtocol>],
        user_id: &str,
        session_id: &str,
    ) -> Result<Self> {
        let mut configured = agent.clone();
        let mut declarations = Vec::new();
        // Discover before opening any native session. No provider credential is in these declarations.
        for protocol in protocols {
            declarations.push(
                json!({"protocol":protocol.name(),"capabilities":protocol.capabilities().await?}),
            );
        }
        configured
            .metadata
            .insert("_marona_protocol_capabilities".into(), json!(declarations));
        let mut opened = Vec::<(String, Box<dyn ProtocolSession>)>::new();
        for protocol in protocols {
            match protocol.connect(&configured, user_id, session_id).await {
                Ok(mut child) => {
                    if !child.supports_delivery() || !child.supports_feedback() {
                        let _ = child.close().await;
                        for (_, mut previous) in opened {
                            let _ = previous.close().await;
                        }
                        return Err(Error::Validation(format!("Protocol {} must implement canonical delivery and bounded event reads for coordination",protocol.name())));
                    }
                    opened.push((protocol.name().to_owned(), child));
                }
                Err(error) => {
                    for (_, mut previous) in opened {
                        let _ = previous.close().await;
                    }
                    return Err(error);
                }
            }
        }
        let (tx, events) = mpsc::channel(128);
        let mut children = HashMap::new();
        let mut tasks = Vec::new();
        for (name, mut child) in opened {
            let (commands, mut rx) = mpsc::channel(32);
            children.insert(name.clone(), ProtocolConnection { commands });
            let tx = tx.clone();
            tasks.push(tokio::spawn(async move {
                loop {
                    match rx.try_recv() {
                        Ok(Command::Feedback(value, reply)) => {
                            let _ = reply.send(child.deliver_feedback(&value).await);
                        }
                        Ok(Command::Send(value, canonical, reply)) => {
                            let result = if canonical {
                                child.deliver(&value).await
                            } else {
                                child.send(&value).await
                            };
                            let _ = reply.send(result);
                        }
                        Ok(Command::Close(reply)) => {
                            let _ = reply.send(child.close().await);
                            return;
                        }
                        Err(mpsc::error::TryRecvError::Disconnected) => break,
                        Err(mpsc::error::TryRecvError::Empty) => match child.poll_event().await {
                            Ok(Some(event)) => {
                                if tx
                                    .send(ChildEvent {
                                        name: name.clone(),
                                        event: Ok(event),
                                        result: child.result(),
                                    })
                                    .await
                                    .is_err()
                                {
                                    break;
                                }
                            }
                            Ok(None) => tokio::time::sleep(Duration::from_millis(10)).await,
                            Err(error) => {
                                let _ = tx
                                    .send(ChildEvent {
                                        name: name.clone(),
                                        event: Err(error),
                                        result: None,
                                    })
                                    .await;
                                break;
                            }
                        },
                    }
                }
                let _ = child.close().await;
            }));
        }
        Ok(Self {
            session_id: session_id.into(),
            children,
            configurations: protocols.to_vec(),
            tasks,
            events,
            queue: VecDeque::new(),
            seen: HashSet::new(),
            pending: HashMap::new(),
            last_result: None,
            route_failure: None,
            closed: false,
        })
    }
    pub fn protocol(&self, name: &str) -> Result<ProtocolConnection> {
        self.children
            .get(name)
            .cloned()
            .ok_or_else(|| Error::Validation(format!("No attached protocol named {name}")))
    }
    pub async fn send_to(&mut self, input: &Value, protocol: Option<&str>) -> Result<()> {
        let name = if let Some(name) = protocol {
            name.to_owned()
        } else if let Some(name) = input["protocol"].as_str() {
            name.to_owned()
        } else {
            let candidates: Vec<_> = self
                .configurations
                .iter()
                .filter(|p| p.accepts(input))
                .collect();
            if candidates.len() != 1 {
                return Err(Error::Validation(
                    "Input is ambiguous; provide a canonical protocol or explicit selection".into(),
                ));
            }
            candidates[0].name().to_owned()
        };
        self.protocol(&name)?.send(input).await
    }
    pub async fn send_signal(&mut self, signal: &Value) -> Result<()> {
        self.send_to(signal, Some("b2a")).await
    }
    async fn route(&mut self, source: &str, data: &Value) -> Result<()> {
        let route_id = data["route_id"]
            .as_str()
            .filter(|v| !v.is_empty())
            .ok_or_else(|| Error::Validation("Route ID is required".into()))?
            .to_owned();
        if self.seen.contains(&route_id) {
            return Ok(());
        }
        if self.seen.len() >= 4096 {
            return Err(Error::Validation(
                "Protocol route history capacity reached; open a new session".into(),
            ));
        }
        self.seen.insert(route_id.clone());
        let outcome = async {
            let target = data["target_protocol"]
                .as_str()
                .ok_or_else(|| Error::Validation("Missing route target".into()))?;
            let hops=match data.get("hops"){None=>0,Some(v)=>v.as_u64().ok_or_else(||Error::Validation("Malformed route hop count".into()))?};
            let mut visited=match data.get("visited"){None=>Vec::new(),Some(Value::Array(v)) if v.len()<=9 && v.iter().all(|p|p.as_str().is_some_and(|s|!s.is_empty()))=>v.clone(),_=>return Err(Error::Validation("Malformed route lineage".into()))};
            if visited.contains(&json!(target)){return Err(Error::Validation("Protocol route lineage loop".into()));}
            if !visited.contains(&json!(source)){visited.push(json!(source));}visited.push(json!(target));
            if hops >= 8 || target == source {
                return Err(Error::Validation("Protocol route loop or hop limit".into()));
            }
            let mut message = data["message"].clone();
            if message["protocol"] != target
                || message["type"] != "message"
                || message["source"] != "agent"
            {
                return Err(Error::Validation(
                    "Route must contain a canonical agent message for its target".into(),
                ));
            }
            let correlation = data["correlation_id"]
                .as_str()
                .or_else(|| message["message_id"].as_str())
                .ok_or_else(|| Error::Validation("Route correlation is required".into()))?
                .to_owned();
            message["correlation_id"] = json!(correlation);
            message["payload"]["source_protocol"] = json!(source);
            message["payload"]["route_id"] = json!(route_id);
            message["payload"]["hops"] = json!(hops + 1);
            message["payload"]["coordination"]=json!({"route_id":route_id,"origin_protocol":source,"hops":hops+1,"visited":visited});
            let pending = PendingRoute {
                origin: source.into(),
                target:target.into(),
                route_id: route_id.clone(),
                hops: hops + 1,
            };
            let mut identifiers = vec![correlation.clone()];
            if let Some(id) = message["message_id"].as_str() {
                identifiers.push(id.to_owned());
            }
            if let Some(id) = message["payload"]["action_id"].as_str() {
                identifiers.push(id.to_owned());
            }
            for id in identifiers {
                self.pending.insert(id, pending.clone());
            }
            if let Err(error) = self.protocol(target)?.deliver(&message).await {
                self.pending.retain(|_, value| value.route_id != route_id);
                return Err(error);
            }
            Ok(())
        }
        .await;
        if let Err(error) = outcome {
            self.route_failure = Some(error.to_string());
            self.queue.push_back(route_event(
                "protocol.route.failed",
                &route_id,
                source,
                Some(error.to_string()),
            ));
        }
        Ok(())
    }
    async fn handle(&mut self, item: ChildEvent) -> Result<RunEvent> {
        let mut event = item.event?;
        if item.result.is_some() {
            self.last_result = item.result;
        }
        if event.event_type == "protocol.route" {
            self.route(&item.name, &Value::Object(event.data.clone()))
                .await?;
        } else {
            let envelope = event
                .data
                .get("message")
                .cloned()
                .unwrap_or_else(|| Value::Object(event.data.clone()));
            for route in envelope["payload"]["routes"]
                .as_array()
                .into_iter()
                .flatten()
            {
                self.route(&item.name, route).await?;
            }
            if event.event_type == "feedback" || envelope["payload"]["kind"] == "feedback" {
                let identifiers = [
                    envelope["correlation_id"].as_str(),
                    envelope["message_id"].as_str(),
                    envelope["payload"]["action_id"].as_str(),
                ];
                let pending = identifiers
                    .into_iter()
                    .flatten()
                    .find_map(|id| self.pending.get(id).cloned());
                if let Some(pending) = pending {
                    if item.name != pending.target {
                        return Err(Error::Validation(
                            "Protocol feedback came from a different route target".into(),
                        ));
                    }
                    let status = envelope["payload"]["status"]
                        .as_str()
                        .unwrap_or("succeeded");
                    let terminal = !["accepted", "executing"].contains(&status);
                    let outcome = if pending.hops >= 8 {
                        Err(Error::Validation("Protocol feedback hop limit".into()))
                    } else {
                        self.protocol(&pending.origin)?
                            .deliver_feedback(&envelope)
                            .await
                    };
                    if outcome.is_err() || (terminal && status != "succeeded") {
                        self.route_failure = Some(
                            outcome
                                .as_ref()
                                .err()
                                .map(|e| e.to_string())
                                .unwrap_or_else(|| format!("Protocol outcome: {status}")),
                        );
                    }
                    if terminal || outcome.is_err() {
                        self.pending
                            .retain(|_, value| value.route_id != pending.route_id);
                        self.queue.push_back(route_event(
                            if outcome.is_ok() && status == "succeeded" {
                                "protocol.route.completed"
                            } else {
                                "protocol.route.failed"
                            },
                            &pending.route_id,
                            &pending.origin,
                            outcome.err().map(|e| e.to_string()).or_else(|| {
                                if status != "succeeded" {
                                    Some(format!("Protocol outcome: {status}"))
                                } else {
                                    None
                                }
                            }),
                        ));
                    }
                }
            }
        }

        event.data.insert("protocol".into(), json!(item.name));
        if !event.data.contains_key("source") {
            event.data.insert("source".into(), json!(item.name));
        }
        Ok(event)
    }
}
fn route_event(kind: &str, id: &str, target: &str, error: Option<String>) -> RunEvent {
    RunEvent {
        event_type: kind.into(),
        delta: None,
        output: Value::Null,
        data: json!({"route_id":id,"target_protocol":target,"error":error})
            .as_object()
            .unwrap()
            .clone(),
    }
}
#[async_trait]
impl ProtocolSession for CoordinatedSession {
    fn supports_delivery(&self) -> bool {
        true
    }
    fn result(&self) -> Option<RunResult> {
        self.last_result.clone()
    }
    async fn send(&mut self, input: &Value) -> Result<()> {
        self.send_to(input, None).await
    }
    async fn deliver(&mut self, message: &Value) -> Result<()> {
        let name = message["protocol"]
            .as_str()
            .ok_or_else(|| Error::Validation("Missing target protocol".into()))?;
        self.protocol(name)?.deliver(message).await
    }
    async fn next_event(&mut self) -> Result<Option<RunEvent>> {
        if let Some(event) = self.queue.pop_front() {
            return Ok(Some(event));
        }
        match self.events.recv().await {
            Some(item) => Ok(Some(self.handle(item).await?)),
            None => Ok(None),
        }
    }
    async fn poll_event(&mut self) -> Result<Option<RunEvent>> {
        if let Some(event) = self.queue.pop_front() {
            return Ok(Some(event));
        }
        match self.events.try_recv() {
            Ok(item) => Ok(Some(self.handle(item).await?)),
            Err(_) => Ok(None),
        }
    }
    async fn close(&mut self) -> Result<()> {
        if self.closed {
            return Ok(());
        }
        self.closed = true;
        let mut acknowledgements = Vec::new();
        for child in self.children.values() {
            let (tx, rx) = oneshot::channel();
            if child.commands.send(Command::Close(tx)).await.is_ok() {
                acknowledgements.push(rx);
            }
        }
        let closing = async {
            let mut error = None;
            for ack in acknowledgements {
                if let Ok(Err(value)) = ack.await {
                    error.get_or_insert(value);
                }
            }
            match error {
                Some(error) => Err(error),
                None => Ok(()),
            }
        };
        tokio::pin!(closing);
        let result = loop {
            tokio::select! {result=&mut closing=>break result,_=self.events.recv()=>{}}
        };
        for task in self.tasks.drain(..) {
            let _ = task.await;
        }
        result
    }
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}
impl Drop for CoordinatedSession {
    fn drop(&mut self) {
        for task in self.tasks.drain(..) {
            task.abort();
        }
    }
}