Skip to main content

universal_exports/liaison/
mod.rs

1//! Liaison: A2A 1.0 at AI6's boundary, as the wire format of Cables.
2//!
3//! A peer's A2A message becomes a Cable to one AI6 Agent or an Operation's role, submitted to the
4//! Cable relay as the peer's configured principal: the same records, grants, compartments, quotas,
5//! TTL, deduplication and audit as any Cable. The addressee's reply is a Cable reply, read back as
6//! the A2A answer. Nothing else is kept: an A2A Task is the peer's Cable (its ID is the Cable's),
7//! its context the Cable conversation, and its state the Cable's delivery. Nothing is placed or
8//! scheduled. A thread stays with the Run that first took it ([`CableSendRequest::with_affinity`]).
9//!
10//! A peer arrives on a proven agentic-peer link ([`LinkListener`]) or on the gateway's
11//! HTTP JSON-RPC binding (`/v1/a2a`), signed in as its principal. Cables to `a2a:<peer>` leave as
12//! A2A the other way.
13
14mod http;
15mod link;
16mod metadata;
17mod outbound;
18#[cfg(test)]
19mod tests;
20
21pub(crate) use http::routes;
22pub use link::LinkListener;
23
24use std::collections::{BTreeMap, BTreeSet};
25use std::fmt;
26use std::str::FromStr;
27use std::sync::Arc;
28use std::time::{Duration, SystemTime, UNIX_EPOCH};
29
30use ai6::directorates::registry::cables::{
31    Cable, CableAuditRecord, CableDelivery, CableEndpoint, CablePrincipal, CableRelay,
32    CableRelayError, CableScope, CableSendRequest, CableState, CableTarget,
33};
34pub use ai6::directorates::registry::cables::{LIAISON_PREFIX, LIAISON_STATION};
35use ai6::directorates::registry::store::AuditRecord;
36use ai6::{Authorizer, Limit, Person, RegistryBackend};
37use coqui_a2a::error::{A2aError, ErrorKind};
38use coqui_a2a::model::{
39    AgentCapabilities, AgentCard, AgentSkill, Artifact, CancelTaskRequest, GetTaskRequest,
40    ListTasksRequest, ListTasksResponse, Message, Part, Role, SendMessageRequest,
41    SendMessageResponse, StreamResponse, SubscribeToTaskRequest, Task, TaskArtifactUpdateEvent,
42    TaskState, TaskStatus, TaskStatusUpdateEvent,
43};
44use coqui_a2a::{Agent, Caller, Events};
45
46use crate::Gateway;
47use metadata::Members;
48
49/// Where an addressee's Cable is said to wait: in the Registry, for any Station of its Agent.
50const ADDRESSEE_STATION: &str = "registry";
51
52/// The message metadata member that names an addressee.
53pub const ADDRESSEE_MEMBER: &str = "addressee";
54
55/// Why Liaison could not be set up.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct LiaisonError(String);
58
59impl LiaisonError {
60    fn new(message: impl Into<String>) -> Self {
61        Self(message.into())
62    }
63}
64
65impl fmt::Display for LiaisonError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(&self.0)
68    }
69}
70
71impl std::error::Error for LiaisonError {}
72
73/// What a peer may write to.
74#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
75pub enum Addressee {
76    /// One Agent of one Operation: `agent:<operation>/<agent>`.
77    Agent {
78        /// The Operation.
79        operation: String,
80        /// The Agent's codename.
81        agent: String,
82    },
83    /// The Agent the roster selects for a role in one Operation: `role:<operation>/<role>`.
84    Role {
85        /// The Operation.
86        operation: String,
87        /// The role.
88        role: String,
89    },
90}
91
92impl Addressee {
93    /// Its Operation.
94    pub fn operation(&self) -> &str {
95        match self {
96            Self::Agent { operation, .. } | Self::Role { operation, .. } => operation,
97        }
98    }
99}
100
101impl fmt::Display for Addressee {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::Agent { operation, agent } => write!(f, "agent:{operation}/{agent}"),
105            Self::Role { operation, role } => write!(f, "role:{operation}/{role}"),
106        }
107    }
108}
109
110impl FromStr for Addressee {
111    type Err = LiaisonError;
112
113    fn from_str(text: &str) -> Result<Self, Self::Err> {
114        let refused = || {
115            LiaisonError::new(format!(
116                "{text:?} is not agent:<operation>/<agent> or role:<operation>/<role>"
117            ))
118        };
119        let (kind, rest) = text.split_once(':').ok_or_else(refused)?;
120        let (operation, name) = rest.split_once('/').ok_or_else(refused)?;
121        let valid = ai6::directorates::section_00::assistant::valid_identity;
122        if !valid(operation) || !valid(name) {
123            return Err(refused());
124        }
125        let (operation, name) = (operation.to_owned(), name.to_owned());
126        match kind {
127            "agent" => Ok(Self::Agent {
128                operation,
129                agent: name,
130            }),
131            "role" => Ok(Self::Role {
132                operation,
133                role: name,
134            }),
135            _ => Err(refused()),
136        }
137    }
138}
139
140/// One paired peer.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct LiaisonPeer {
143    /// Its configured name.
144    pub name: String,
145    /// Its peer id, `sha256:<hex>` of its link key; `None` for a peer that only signs in over
146    /// HTTP.
147    pub id: Option<String>,
148    /// The subject it acts as (`person:<id>`, `account:<name>`, `group:<name>`); over HTTP, the
149    /// person signed in as this subject is this peer.
150    pub principal: String,
151    /// What it may write to.
152    pub addressees: Vec<Addressee>,
153    /// Whether its link grants it `a2a/1`.
154    pub a2a: bool,
155    /// Where Liaison dials it to carry Cables sent to it, when it holds no link open itself.
156    pub url: Option<url::Url>,
157}
158
159impl LiaisonPeer {
160    /// The sender its Cables carry: `a2a:<name>`.
161    pub fn sender(&self) -> String {
162        format!("{LIAISON_PREFIX}{}", self.name)
163    }
164
165    /// Whether `person` is this peer's principal.
166    fn is(&self, person: &Person) -> bool {
167        let Ok(subject) = self.principal.parse::<ai6::Subject>() else {
168            return false;
169        };
170        match subject.kind() {
171            "person" => person.id == subject.value(),
172            "account" => person.name == subject.value(),
173            "group" => person.groups.iter().any(|group| group == subject.value()),
174            _ => false,
175        }
176    }
177}
178
179/// What Liaison serves and to whom.
180#[derive(Debug, Clone)]
181pub struct LiaisonConfig {
182    /// The paired peers, by name.
183    pub peers: BTreeMap<String, LiaisonPeer>,
184    /// How often a waiting operation looks for a reply, and the outbound side for Cables.
185    pub poll: Duration,
186    /// Links served at once.
187    pub max_links: Limit,
188    /// Whether a `ws://` listener or dial may go beyond loopback.
189    pub plain_beyond_loopback: bool,
190    /// How often a running stream's grant is asked about again.
191    pub recheck: Duration,
192}
193
194impl Default for LiaisonConfig {
195    fn default() -> Self {
196        Self {
197            peers: BTreeMap::new(),
198            poll: Duration::from_secs(1),
199            max_links: Limit::at(64),
200            plain_beyond_loopback: false,
201            recheck: Duration::from_secs(1),
202        }
203    }
204}
205
206impl LiaisonConfig {
207    /// Adds a peer.
208    #[must_use]
209    pub fn with_peer(mut self, peer: LiaisonPeer) -> Self {
210        self.peers.insert(peer.name.clone(), peer);
211        self
212    }
213
214    /// Reads `[unex.liaison]`.
215    ///
216    /// # Errors
217    ///
218    /// A peer's name, id, principal, addressee or url is not valid, or a duration is negative.
219    pub fn from_settings(settings: &ai6::bootstrap::LiaisonSettings) -> Result<Self, LiaisonError> {
220        let mut config = Self::default();
221        if let Some(poll) = settings.poll {
222            config.poll = Duration::try_from_secs_f64(poll).map_err(|_| {
223                LiaisonError::new("[unex.liaison] poll must be seconds, not negative")
224            })?;
225        }
226        if let Some(most) = settings.max_links {
227            config.max_links = Limit::at(most);
228        }
229        config.plain_beyond_loopback = settings.plain_beyond_loopback.unwrap_or(false);
230        for (name, peer) in &settings.peer {
231            let at = |what: &str| LiaisonError::new(format!("[unex.liaison.peer.{name}] {what}"));
232            if !ai6::directorates::section_00::assistant::valid_identity(name) {
233                return Err(at("the name must be letters, digits, - and _"));
234            }
235            if peer
236                .id
237                .as_ref()
238                .is_some_and(|id| !id.starts_with("sha256:"))
239            {
240                return Err(at("id must be the peer's sha256:<hex>"));
241            }
242            let principal = peer
243                .principal
244                .clone()
245                .filter(|principal| principal.parse::<ai6::Subject>().is_ok())
246                .ok_or_else(|| {
247                    at("principal must be person:<id>, account:<name> or group:<name>")
248                })?;
249            let addressees = peer
250                .addressees
251                .iter()
252                .map(|addressee| {
253                    addressee
254                        .parse()
255                        .map_err(|error| at(&format!("addressees: {error}")))
256                })
257                .collect::<Result<Vec<_>, _>>()?;
258            let url = peer
259                .url
260                .as_deref()
261                .map(|url| {
262                    url::Url::parse(url)
263                        .ok()
264                        .filter(|url| matches!(url.scheme(), "ws" | "wss"))
265                        .ok_or_else(|| at("url must be ws:// or wss://"))
266                })
267                .transpose()?;
268            if url.is_some() && peer.id.is_none() {
269                return Err(at(
270                    "a peer Liaison dials needs its id, which its proof must show",
271                ));
272            }
273            config = config.with_peer(LiaisonPeer {
274                name: name.clone(),
275                id: peer.id.clone(),
276                principal,
277                addressees,
278                a2a: peer.a2a.unwrap_or(true),
279                url,
280            });
281        }
282        Ok(config)
283    }
284}
285
286/// Who is calling: a configured peer, and what proved it (its key on a link, its sign-in over
287/// HTTP). The proof goes on its Cables.
288#[derive(Debug, Clone)]
289pub(crate) struct Calling<'a> {
290    pub(crate) peer: &'a LiaisonPeer,
291    pub(crate) proof: String,
292}
293
294/// Liaison's A2A agent: what a peer reaches, over a link or over HTTP. It keeps nothing of its
295/// own: every answer is read from the Registry.
296#[derive(Clone)]
297pub struct Liaison {
298    inner: Arc<Inner>,
299}
300
301struct Inner {
302    gateway: Gateway,
303    config: Arc<LiaisonConfig>,
304}
305
306impl fmt::Debug for Liaison {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        f.debug_struct("Liaison")
309            .field("peers", &self.inner.config.peers.len())
310            .finish_non_exhaustive()
311    }
312}
313
314/// A Task as the Registry holds it: the peer's Cable and the replies to it.
315struct Exchange {
316    cable: Cable,
317    replies: Vec<CableDelivery>,
318    state: TaskState,
319    reason: Option<&'static str>,
320}
321
322/// Something an operation asks, between waits, whether its caller is still there.
323pub(crate) type Open = Arc<dyn Fn() -> bool + Send + Sync>;
324
325impl Liaison {
326    /// Serves `config`'s peers through `gateway`: its Registry, configuration provider, Directory
327    /// and authorizer. Without them every message is refused.
328    pub fn new(gateway: Gateway, config: LiaisonConfig) -> Self {
329        Self::shared(gateway, Arc::new(config))
330    }
331
332    pub(crate) fn shared(gateway: Gateway, config: Arc<LiaisonConfig>) -> Self {
333        Self {
334            inner: Arc::new(Inner { gateway, config }),
335        }
336    }
337
338    /// The peer the link proved, by its key; a key nobody configured never gets this far.
339    fn peer_by_id(&self, id: &str) -> Option<&LiaisonPeer> {
340        self.inner
341            .config
342            .peers
343            .values()
344            .find(|peer| peer.id.as_deref() == Some(id))
345    }
346
347    /// The peer whose principal `person` is, for a caller signed in over HTTP.
348    pub(crate) fn peer_for(&self, person: &Person) -> Option<&LiaisonPeer> {
349        self.inner
350            .config
351            .peers
352            .values()
353            .find(|peer| peer.is(person))
354    }
355
356    fn calling<'a>(&'a self, caller: &Caller<'_>) -> Result<Calling<'a>, A2aError> {
357        let peer = self
358            .peer_by_id(caller.peer)
359            .ok_or_else(|| A2aError::standard(ErrorKind::PermissionDenied))?;
360        Ok(Calling {
361            peer,
362            proof: caller.peer.to_owned(),
363        })
364    }
365
366    fn registry(&self) -> Result<Arc<dyn RegistryBackend>, A2aError> {
367        self.inner
368            .gateway
369            .registry
370            .clone()
371            .ok_or_else(|| unavailable("the Registry"))
372    }
373
374    fn snapshot(&self) -> Result<ai6::ConfigSnapshot, A2aError> {
375        self.inner
376            .gateway
377            .roster
378            .as_ref()
379            .ok_or_else(|| unavailable("the configuration provider"))?
380            .load("")
381            .map_err(|_| unavailable("the configuration provider"))
382    }
383
384    /// The person `peer` acts as: the Directory's when it knows the subject, else the subject
385    /// alone, which access rules name as they would anyone's.
386    fn person(&self, peer: &LiaisonPeer) -> Option<Person> {
387        let access = self.inner.gateway.access.as_ref()?;
388        let subject: ai6::Subject = peer.principal.parse().ok()?;
389        let lookup = match subject.kind() {
390            "account" => Some(("name", subject.value())),
391            "person" => Some(("id", subject.value())),
392            _ => None,
393        };
394        let found = lookup.and_then(|(by, value)| {
395            access
396                .directory
397                .lookup(ai6::Lookup {
398                    by: by.to_owned(),
399                    value: value.to_owned(),
400                    ..Default::default()
401                })
402                .ok()
403                .flatten()
404        });
405        Some(found.unwrap_or_else(|| match subject.kind() {
406            "account" => Person {
407                name: subject.value().to_owned(),
408                ..Person::default()
409            },
410            "person" => Person {
411                id: subject.value().to_owned(),
412                ..Person::default()
413            },
414            _ => Person {
415                groups: vec![subject.value().to_owned()],
416                ..Person::default()
417            },
418        }))
419    }
420
421    /// Whether `peer`'s principal holds `action` on `operation` now: no, whenever that cannot be
422    /// read.
423    fn allowed(&self, peer: &LiaisonPeer, action: &str, operation: &str) -> bool {
424        let (Some(person), Some(registry), Ok(authorizer)) = (
425            self.person(peer),
426            self.inner.gateway.registry.clone(),
427            self.inner.gateway.authorizer(),
428        ) else {
429            return false;
430        };
431        let Ok(records) = registry.stations(Duration::MAX) else {
432            return false;
433        };
434        let tree = crate::tree::OperationTree::from_check_ins(&records);
435        authorizer
436            .authorize(crate::tree::operation_request(
437                person, action, operation, &tree,
438            ))
439            .is_ok_and(|decision| decision.allowed)
440    }
441
442    /// The Operations the Stations serve.
443    fn operations(&self) -> BTreeSet<String> {
444        let Ok(registry) = self.registry() else {
445            return BTreeSet::new();
446        };
447        registry
448            .stations(Duration::MAX)
449            .unwrap_or_default()
450            .into_iter()
451            .flat_map(|station| station.into_check_in().common.operations)
452            .collect()
453    }
454
455    /// The Agent an addressee is now.
456    fn resolve(roster: &ai6::Roster, addressee: &Addressee) -> Option<String> {
457        match addressee {
458            Addressee::Agent { operation, agent } => roster
459                .agents_for_operation(operation)
460                .ok()?
461                .into_iter()
462                .find(|candidate| &candidate.id == agent)
463                .map(|candidate| candidate.id),
464            Addressee::Role { operation, role } => {
465                let mut query = ai6::AgentQuery::new()
466                    .operation(Some(operation))
467                    .role(Some(role));
468                query.now = i64::try_from(now() as u64).ok();
469                roster.select_agent(&query).ok().map(|agent| agent.id)
470            }
471        }
472    }
473
474    /// The Cable relay over the shared Registry, as the `cables` record sets it, reaching
475    /// `endpoints`.
476    fn relay(
477        &self,
478        snapshot: &ai6::ConfigSnapshot,
479        endpoints: Vec<CableEndpoint>,
480    ) -> Result<CableRelay, A2aError> {
481        cable_relay(self.registry()?, snapshot, endpoints)
482            .ok_or_else(|| unavailable("the cables record"))
483    }
484
485    /// The principal a peer's Cables go as: its sender, acting for its principal, stamped with
486    /// `proof`, with `route` as its Run when replies are to come back to one.
487    fn principal_for(
488        peer: &LiaisonPeer,
489        proof: &str,
490        operation: &str,
491        route: Option<&str>,
492    ) -> Result<CablePrincipal, A2aError> {
493        CablePrincipal::try_new(
494            peer.sender(),
495            operation.to_owned(),
496            None,
497            LIAISON_STATION.to_owned(),
498            route.map(str::to_owned),
499            None,
500        )
501        .and_then(|principal| principal.with_on_behalf_of(peer.principal.clone()))
502        .and_then(|principal| principal.with_peer(proof.to_owned()))
503        .map_err(|_| A2aError::standard(ErrorKind::Internal))
504    }
505
506    /// Writes the audit record of one A2A call: the principal as actor, the peer and what it
507    /// asked as target. The relay writes its own record of each Cable before storing it; this
508    /// one is best effort.
509    fn audit(&self, peer: &LiaisonPeer, call: &str, operation: &str, target: &str) {
510        let Some(registry) = self.inner.gateway.registry.clone() else {
511            return;
512        };
513        let mut target = format!("peer:{} {target}", peer.name);
514        cut(&mut target, 500);
515        let record = AuditRecord {
516            id: format!("liaison-{}", uuid::Uuid::new_v4().simple()),
517            actor: peer.principal.clone(),
518            action: format!("liaison.{call}"),
519            operation: operation.to_owned(),
520            resource: operation.is_empty().then(|| "config:liaison".to_owned()),
521            target,
522            at: now(),
523        };
524        if let Err(error) = registry.record_audit(&record) {
525            eprintln!("universal-exports: Liaison's audit record of a {call} was lost: {error}");
526        }
527    }
528
529    /// The peer's own Cables: its messages, newest first, never the replies it carried back.
530    fn cables_of(&self, peer: &LiaisonPeer) -> Result<Vec<Cable>, A2aError> {
531        let registry = self.registry()?;
532        let page = registry.limits().cables.page.or_max();
533        let mut cables: Vec<Cable> = registry
534            .cables_from(&peer.sender(), page, None)
535            .map_err(|_| unavailable("the Registry"))?
536            .into_iter()
537            .filter(|cable| cable.reply_to().is_none() && cable.peer().is_some())
538            .collect();
539        cables.reverse();
540        Ok(cables)
541    }
542
543    /// Takes a peer's message: who it is for, that the principal may send there, and the Run
544    /// its context is bound to; then submits it to the relay as a Cable.
545    pub(crate) fn submit(
546        &self,
547        calling: &Calling<'_>,
548        request: &SendMessageRequest,
549    ) -> Result<Cable, A2aError> {
550        let peer = calling.peer;
551        request.validate()?;
552        let message = &request.message;
553        if let Some(task) = &message.task_id {
554            return Err(match self.exchange(peer, task) {
555                Ok(_) => A2aError::new(
556                    ErrorKind::UnsupportedOperation,
557                    "a task is one message and its replies: send a new message in its context",
558                ),
559                Err(error) => error,
560            });
561        }
562        // A message ID sent again is the Cable it made, as A2A asks of a resend.
563        let key = idempotency_key(&peer.name, &message.message_id);
564        if let Some(sent) = self
565            .registry()?
566            .find_cable(&peer.sender(), &key)
567            .map_err(|_| unavailable("the Registry"))?
568        {
569            return Ok(sent);
570        }
571        let text = message.joined_text();
572        if text.trim().is_empty() || message.parts.iter().any(|part| part.text.is_none()) {
573            return Err(A2aError::new(
574                ErrorKind::ContentTypeNotSupported,
575                "Liaison carries text parts only",
576            ));
577        }
578        // The context's first Cable decides its addressee, and the Run it is bound to.
579        let earlier = match &message.context_id {
580            Some(context) => Some(
581                self.cables_of(peer)?
582                    .into_iter()
583                    .rev()
584                    .find(|cable| cable.conversation_id() == Some(context.as_str()))
585                    .ok_or_else(|| A2aError::new(ErrorKind::InvalidParams, "unknown contextId"))?,
586            ),
587            None => None,
588        };
589        let named = [message.metadata.as_ref(), request.metadata.as_ref()]
590            .into_iter()
591            .flatten()
592            .find_map(Members::addressee_in);
593        let addressee: Addressee = match (named, &earlier, peer.addressees.as_slice()) {
594            (Some(named), _, _) => named.parse().map_err(|_| {
595                A2aError::new(
596                    ErrorKind::InvalidParams,
597                    "the addressee is not one of the card's skills",
598                )
599            })?,
600            (None, Some(earlier), _) => Addressee::Agent {
601                operation: earlier.sender_operation().to_owned(),
602                agent: earlier.target().name().unwrap_or_default().to_owned(),
603            },
604            (None, None, [only]) => only.clone(),
605            (None, None, _) => {
606                return Err(A2aError::new(
607                    ErrorKind::InvalidParams,
608                    "name the addressee in the message's metadata.addressee: one of the card's \
609                     skills",
610                ));
611            }
612        };
613        let operation = addressee.operation().to_owned();
614        let denied = || {
615            A2aError::new(
616                ErrorKind::PermissionDenied,
617                "that addressee is not reachable, or not for this peer",
618            )
619        };
620        let listed = peer.addressees.contains(&addressee)
621            || earlier.as_ref().is_some_and(|earlier| {
622                peer.addressees
623                    .iter()
624                    .any(|listed| listed.operation() == earlier.sender_operation())
625            });
626        if !listed || !self.allowed(peer, "cable.send", &operation) {
627            self.audit(
628                peer,
629                "send_message",
630                &operation,
631                &format!("{addressee} refused"),
632            );
633            return Err(denied());
634        }
635        let snapshot = self.snapshot()?;
636        let agent = match &earlier {
637            Some(earlier) => earlier.target().name().map(str::to_owned),
638            None => Self::resolve(&snapshot.roster, &addressee),
639        };
640        let Some(agent) = agent else {
641            self.audit(
642                peer,
643                "send_message",
644                &operation,
645                &format!("{addressee} refused"),
646            );
647            return Err(denied());
648        };
649        let context = earlier
650            .as_ref()
651            .and_then(|earlier| earlier.conversation_id().map(str::to_owned))
652            .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string());
653        let affinity = earlier.as_ref().and_then(|earlier| self.bound_run(earlier));
654        let endpoint = CableEndpoint::try_new(
655            agent.clone(),
656            operation.clone(),
657            None,
658            ADDRESSEE_STATION.to_owned(),
659            None,
660            None,
661        )
662        .map_err(|_| denied())?;
663        let relay = self.relay(&snapshot, vec![endpoint])?;
664        let principal =
665            Self::principal_for(peer, &calling.proof, &operation, Some(&route(&context)))?;
666        let target =
667            CableTarget::try_new(CableScope::Agent, Some(agent.clone())).map_err(|_| denied())?;
668        let mut cable = CableSendRequest::new(target, text, key).with_conversation(context);
669        if let Some(run) = affinity {
670            cable = cable.with_affinity(run);
671        }
672        let cable = relay.send(&principal, cable).map_err(|error| {
673            self.audit(
674                peer,
675                "send_message",
676                &operation,
677                &format!("{addressee} refused"),
678            );
679            match error {
680                CableRelayError::InvalidRequest => A2aError::new(
681                    ErrorKind::InvalidParams,
682                    "the message is not one a Cable carries",
683                ),
684                CableRelayError::RegistryUnavailable => unavailable("the Cable relay"),
685                _ => denied(),
686            }
687        })?;
688        self.audit(
689            peer,
690            "send_message",
691            &operation,
692            &format!("agent:{operation}/{agent} cable {}", cable.id()),
693        );
694        Ok(cable)
695    }
696
697    /// The Run a context is bound to: the one that took its first Cable, else the
698    /// one that first replied in it.
699    fn bound_run(&self, first: &Cable) -> Option<String> {
700        if let Some(run) = first.affinity() {
701            return Some(run.to_owned());
702        }
703        let current = self.registry().ok()?.get_cable(first.id()).ok()??;
704        current
705            .recipients()
706            .iter()
707            .find_map(|recipient| recipient.taken_by().map(str::to_owned))
708    }
709
710    /// The Task `id` as the Registry holds it now, when it is `peer`'s. Replies are read from the
711    /// relay as delivered to the thread's route, and stay there until their Cable expires.
712    fn exchange(&self, peer: &LiaisonPeer, id: &str) -> Result<Exchange, A2aError> {
713        let registry = self.registry()?;
714        let cable = registry
715            .get_cable(id)
716            .map_err(|_| unavailable("the Registry"))?
717            .filter(|cable| {
718                cable.sender_agent() == peer.sender()
719                    && cable.peer().is_some()
720                    && cable.reply_to().is_none()
721            })
722            .ok_or_else(|| A2aError::task_not_found(id))?;
723        let snapshot = self.snapshot()?;
724        let relay = self.relay(&snapshot, Vec::new())?;
725        let context = cable.conversation_id().unwrap_or_default().to_owned();
726        let principal = Self::principal_for(
727            peer,
728            cable.peer().unwrap_or_default(),
729            cable.sender_operation(),
730            Some(&route(&context)),
731        )?;
732        let page = registry.limits().cables.page.or_max();
733        let replies: Vec<CableDelivery> = relay
734            .inbox(&principal, page)
735            .map_err(|_| unavailable("the Cable relay"))?
736            .into_iter()
737            .filter(|delivery| delivery.reply_to.as_deref() == Some(cable.id()))
738            .collect();
739        let delivered = cable
740            .recipients()
741            .first()
742            .map(ai6::directorates::registry::cables::CableRecipient::state);
743        let expired = cable.expires_at() <= now();
744        let (state, reason) = if !replies.is_empty() {
745            (TaskState::Completed, None)
746        } else {
747            match delivered {
748                None => (TaskState::Failed, Some("it reached nobody")),
749                Some(CableState::Queued | CableState::Held) if expired => (
750                    TaskState::Failed,
751                    Some("it expired before the addressee had it"),
752                ),
753                Some(CableState::Queued | CableState::Held) => (TaskState::Submitted, None),
754                Some(CableState::Delivered | CableState::Acked) if expired => {
755                    (TaskState::Failed, Some("no reply came before it expired"))
756                }
757                Some(CableState::Delivered | CableState::Acked) => (TaskState::Working, None),
758                Some(CableState::Refused) => {
759                    (TaskState::Rejected, Some("the addressee does not take it"))
760                }
761                Some(CableState::Withdrawn) => (TaskState::Canceled, Some("withdrawn")),
762                Some(_) => (TaskState::Failed, Some("it was not delivered")),
763            }
764        };
765        Ok(Exchange {
766            cable,
767            replies,
768            state,
769            reason,
770        })
771    }
772
773    /// Waits until the Task ends, or the caller goes.
774    fn settle(&self, peer: &LiaisonPeer, id: &str, open: &Open) -> Result<Exchange, A2aError> {
775        loop {
776            let exchange = self.exchange(peer, id)?;
777            if exchange.state.is_terminal() || !open() {
778                return Ok(exchange);
779            }
780            pause(self.inner.config.poll, open);
781        }
782    }
783
784    /// The card `peer` sees: one skill for each addressee its principal may send to now.
785    pub(crate) fn card(&self, peer: Option<&LiaisonPeer>) -> AgentCard {
786        let skills = peer
787            .map(|peer| {
788                peer.addressees
789                    .iter()
790                    .filter(|addressee| self.allowed(peer, "cable.send", addressee.operation()))
791                    .map(|addressee| AgentSkill {
792                        id: addressee.to_string(),
793                        name: addressee.to_string(),
794                        description: match addressee {
795                            Addressee::Agent { operation, agent } => format!(
796                                "A message to Agent {agent} of Operation {operation}, as a Cable; \
797                                 its reply is the answer"
798                            ),
799                            Addressee::Role { operation, role } => format!(
800                                "A message to the Agent of role {role} in Operation {operation}, \
801                                 as a Cable; its reply is the answer"
802                            ),
803                        },
804                        tags: vec!["cable".to_owned()],
805                        ..AgentSkill::default()
806                    })
807                    .collect()
808            })
809            .unwrap_or_default();
810        AgentCard {
811            name: "AI6 Liaison".to_owned(),
812            description: format!(
813                "Messages to AI6 Agents, carried as Cables. Name the addressee in a message's \
814                 metadata.{ADDRESSEE_MEMBER}, one of the skills; a peer with one skill may leave \
815                 it out, and a message in a known context goes where that context went. A task \
816                 is one message and its replies."
817            ),
818            version: env!("CARGO_PKG_VERSION").to_owned(),
819            capabilities: AgentCapabilities {
820                streaming: Some(true),
821                push_notifications: Some(false),
822                extended_agent_card: Some(false),
823                ..AgentCapabilities::default()
824            },
825            default_input_modes: vec!["text/plain".to_owned()],
826            default_output_modes: vec!["text/plain".to_owned()],
827            skills,
828            ..AgentCard::default()
829        }
830    }
831
832    /// The Task as A2A shows it.
833    fn task(exchange: &Exchange, history_length: Option<u32>, artifacts: bool) -> Task {
834        let cable = &exchange.cable;
835        let context = cable.conversation_id().unwrap_or_default().to_owned();
836        let replies: Vec<Message> = exchange
837            .replies
838            .iter()
839            .map(|reply| reply_message(reply, &context, cable.id()))
840            .collect();
841        let mut history = vec![Message {
842            message_id: cable.id().to_owned(),
843            context_id: Some(context.clone()),
844            task_id: Some(cable.id().to_owned()),
845            role: Role::User,
846            parts: vec![Part::text(cable.body().to_owned())],
847            ..Message::default()
848        }];
849        history.extend(replies.iter().cloned());
850        if let Some(length) = history_length {
851            let keep = usize::try_from(length).unwrap_or(usize::MAX);
852            let skip = history.len().saturating_sub(keep);
853            history.drain(..skip);
854        }
855        let status_message = replies.last().cloned().or_else(|| {
856            exchange.reason.map(|reason| Message {
857                message_id: format!("{}-status", cable.id()),
858                context_id: Some(context.clone()),
859                task_id: Some(cable.id().to_owned()),
860                role: Role::Agent,
861                parts: vec![Part::text(reason)],
862                ..Message::default()
863            })
864        });
865        let metadata = Members {
866            addressee: Some(format!(
867                "agent:{}/{}",
868                cable.sender_operation(),
869                cable.target().name().unwrap_or_default()
870            )),
871            from: None,
872        }
873        .into_object();
874        Task {
875            id: cable.id().to_owned(),
876            context_id: Some(context),
877            status: TaskStatus {
878                state: exchange.state.clone(),
879                message: status_message,
880                timestamp: Some(timestamp(
881                    exchange
882                        .replies
883                        .last()
884                        .map_or(cable.created_at(), |reply| reply.created_at),
885                )),
886                ..TaskStatus::default()
887            },
888            artifacts: (artifacts && !replies.is_empty())
889                .then(|| replies.iter().map(reply_artifact).collect()),
890            history: Some(history),
891            metadata,
892            ..Task::default()
893        }
894    }
895
896    /// The items that follow a Task from where it is now.
897    fn follow(&self, peer: &LiaisonPeer, exchange: &Exchange, open: Open) -> Events {
898        Box::new(Follow {
899            liaison: self.clone(),
900            peer: peer.clone(),
901            id: exchange.cable.id().to_owned(),
902            context: exchange
903                .cable
904                .conversation_id()
905                .unwrap_or_default()
906                .to_owned(),
907            state: exchange.state.clone(),
908            replies: exchange.replies.len(),
909            pending: vec![StreamResponse::Task(Self::task(exchange, None, true))],
910            open,
911            done: false,
912        })
913    }
914
915    pub(crate) fn send_message(
916        &self,
917        calling: &Calling<'_>,
918        request: &SendMessageRequest,
919        open: &Open,
920    ) -> Result<SendMessageResponse, A2aError> {
921        let cable = self.submit(calling, request)?;
922        let configuration = request.configuration.as_ref();
923        let immediate = configuration
924            .and_then(|configuration| configuration.return_immediately)
925            .unwrap_or(false);
926        let history = configuration.and_then(|configuration| configuration.history_length);
927        let exchange = if immediate {
928            self.exchange(calling.peer, cable.id())?
929        } else {
930            self.settle(calling.peer, cable.id(), open)?
931        };
932        let context = cable.conversation_id().unwrap_or_default();
933        match (&exchange.state, exchange.replies.last()) {
934            (TaskState::Completed, Some(reply)) if !immediate => Ok(SendMessageResponse::Message(
935                reply_message(reply, context, cable.id()),
936            )),
937            _ => Ok(SendMessageResponse::Task(Self::task(
938                &exchange, history, true,
939            ))),
940        }
941    }
942
943    pub(crate) fn send_streaming(
944        &self,
945        calling: &Calling<'_>,
946        request: &SendMessageRequest,
947        open: Open,
948    ) -> Result<Events, A2aError> {
949        let cable = self.submit(calling, request)?;
950        let exchange = self.exchange(calling.peer, cable.id())?;
951        Ok(self.follow(calling.peer, &exchange, open))
952    }
953
954    pub(crate) fn get_task(
955        &self,
956        peer: &LiaisonPeer,
957        request: &GetTaskRequest,
958    ) -> Result<Task, A2aError> {
959        let exchange = self.exchange(peer, &request.id);
960        let operation = exchange
961            .as_ref()
962            .map(|exchange| exchange.cable.sender_operation().to_owned())
963            .unwrap_or_default();
964        let readable = exchange.is_ok() && self.allowed(peer, "cable.read", &operation);
965        self.audit(
966            peer,
967            "get_task",
968            &operation,
969            &format!(
970                "{} {}",
971                request.id,
972                if readable { "read" } else { "refused" }
973            ),
974        );
975        let exchange = exchange?;
976        if !readable {
977            return Err(A2aError::task_not_found(&request.id));
978        }
979        Ok(Self::task(&exchange, request.history_length, true))
980    }
981
982    pub(crate) fn list_tasks(
983        &self,
984        peer: &LiaisonPeer,
985        request: &ListTasksRequest,
986    ) -> Result<ListTasksResponse, A2aError> {
987        let size = request.page_size.unwrap_or(50).clamp(1, 100);
988        let start = match request.page_token.as_deref() {
989            None | Some("") => 0,
990            Some(token) => token
991                .parse::<usize>()
992                .map_err(|_| A2aError::new(ErrorKind::InvalidParams, "not a page token"))?,
993        };
994        let mut tasks = Vec::new();
995        let mut matched = 0usize;
996        for cable in self.cables_of(peer)? {
997            if request
998                .context_id
999                .as_deref()
1000                .is_some_and(|context| cable.conversation_id() != Some(context))
1001                || !self.allowed(peer, "cable.read", cable.sender_operation())
1002            {
1003                continue;
1004            }
1005            let Ok(exchange) = self.exchange(peer, cable.id()) else {
1006                continue;
1007            };
1008            if request
1009                .status
1010                .as_ref()
1011                .is_some_and(|state| state != &exchange.state)
1012            {
1013                continue;
1014            }
1015            matched += 1;
1016            if matched > start && tasks.len() < size as usize {
1017                tasks.push(Self::task(
1018                    &exchange,
1019                    request.history_length,
1020                    request.include_artifacts.unwrap_or(false),
1021                ));
1022            }
1023        }
1024        let next = start + tasks.len();
1025        self.audit(
1026            peer,
1027            "list_tasks",
1028            "",
1029            &format!("{} of {matched}", tasks.len()),
1030        );
1031        Ok(ListTasksResponse {
1032            page_size: size,
1033            total_size: u32::try_from(matched).unwrap_or(u32::MAX),
1034            next_page_token: if next < matched {
1035                next.to_string()
1036            } else {
1037                String::new()
1038            },
1039            tasks,
1040            ..ListTasksResponse::default()
1041        })
1042    }
1043
1044    pub(crate) fn cancel_task(
1045        &self,
1046        peer: &LiaisonPeer,
1047        request: &CancelTaskRequest,
1048    ) -> Result<Task, A2aError> {
1049        let exchange = self.exchange(peer, &request.id)?;
1050        let operation = exchange.cable.sender_operation().to_owned();
1051        let refused = || {
1052            self.audit(
1053                peer,
1054                "cancel_task",
1055                &operation,
1056                &format!("{} refused", request.id),
1057            );
1058            A2aError::new(
1059                ErrorKind::TaskNotCancelable,
1060                "only a message the addressee has not had yet can be withdrawn",
1061            )
1062            .with_metadata("taskId", &request.id)
1063        };
1064        if exchange.state != TaskState::Submitted {
1065            return Err(refused());
1066        }
1067        let snapshot = self.snapshot()?;
1068        let relay = self.relay(&snapshot, Vec::new())?;
1069        let context = exchange.cable.conversation_id().unwrap_or_default();
1070        let principal = Self::principal_for(
1071            peer,
1072            exchange.cable.peer().unwrap_or_default(),
1073            &operation,
1074            Some(&route(context)),
1075        )?;
1076        if relay.withdraw(&principal, exchange.cable.id()).is_err() {
1077            return Err(refused());
1078        }
1079        self.audit(
1080            peer,
1081            "cancel_task",
1082            &operation,
1083            &format!("{} withdrawn", request.id),
1084        );
1085        Ok(Self::task(&self.exchange(peer, &request.id)?, None, true))
1086    }
1087
1088    pub(crate) fn subscribe(
1089        &self,
1090        peer: &LiaisonPeer,
1091        request: &SubscribeToTaskRequest,
1092        open: Open,
1093    ) -> Result<Events, A2aError> {
1094        let exchange = self.exchange(peer, &request.id)?;
1095        let operation = exchange.cable.sender_operation().to_owned();
1096        self.audit(peer, "subscribe_to_task", &operation, &request.id);
1097        if !self.allowed(peer, "cable.read", &operation) {
1098            return Err(A2aError::task_not_found(&request.id));
1099        }
1100        if exchange.state.is_terminal() {
1101            return Err(A2aError::new(
1102                ErrorKind::UnsupportedOperation,
1103                "the task has ended",
1104            ));
1105        }
1106        Ok(self.follow(peer, &exchange, open))
1107    }
1108}
1109
1110/// A stream of one Task's changes: its replies as artifacts, then its state.
1111struct Follow {
1112    liaison: Liaison,
1113    peer: LiaisonPeer,
1114    id: String,
1115    context: String,
1116    state: TaskState,
1117    replies: usize,
1118    pending: Vec<StreamResponse>,
1119    open: Open,
1120    done: bool,
1121}
1122
1123impl Iterator for Follow {
1124    type Item = Result<StreamResponse, A2aError>;
1125
1126    fn next(&mut self) -> Option<Self::Item> {
1127        loop {
1128            if !self.pending.is_empty() {
1129                let item = self.pending.remove(0);
1130                if item.ends_task() {
1131                    self.done = true;
1132                    self.pending.clear();
1133                }
1134                return Some(Ok(item));
1135            }
1136            if self.done || !(self.open)() {
1137                return None;
1138            }
1139            let exchange = match self.liaison.exchange(&self.peer, &self.id) {
1140                Ok(exchange) => exchange,
1141                Err(error) => {
1142                    self.done = true;
1143                    return Some(Err(error));
1144                }
1145            };
1146            for reply in exchange.replies.iter().skip(self.replies) {
1147                self.pending
1148                    .push(StreamResponse::ArtifactUpdate(TaskArtifactUpdateEvent {
1149                        task_id: self.id.clone(),
1150                        context_id: self.context.clone(),
1151                        artifact: reply_artifact(&reply_message(reply, &self.context, &self.id)),
1152                        last_chunk: Some(true),
1153                        ..TaskArtifactUpdateEvent::default()
1154                    }));
1155            }
1156            self.replies = exchange.replies.len();
1157            if exchange.state != self.state {
1158                self.state = exchange.state.clone();
1159                let task = Liaison::task(&exchange, None, false);
1160                self.pending
1161                    .push(StreamResponse::StatusUpdate(TaskStatusUpdateEvent {
1162                        task_id: self.id.clone(),
1163                        context_id: self.context.clone(),
1164                        status: task.status,
1165                        ..TaskStatusUpdateEvent::default()
1166                    }));
1167            }
1168            if self.pending.is_empty() {
1169                pause(self.liaison.inner.config.poll, &self.open);
1170            }
1171        }
1172    }
1173}
1174
1175fn watching(caller: &Caller<'_>) -> Open {
1176    let watch = caller.watch();
1177    Arc::new(move || !watch.is_closed())
1178}
1179
1180impl Agent for Liaison {
1181    fn agent_card(&self, caller: &Caller<'_>) -> AgentCard {
1182        self.card(self.peer_by_id(caller.peer))
1183    }
1184
1185    fn send_message(
1186        &self,
1187        caller: &Caller<'_>,
1188        request: SendMessageRequest,
1189    ) -> Result<SendMessageResponse, A2aError> {
1190        let calling = self.calling(caller)?;
1191        Liaison::send_message(self, &calling, &request, &watching(caller))
1192    }
1193
1194    fn send_streaming_message(
1195        &self,
1196        caller: &Caller<'_>,
1197        request: SendMessageRequest,
1198    ) -> Result<Events, A2aError> {
1199        let calling = self.calling(caller)?;
1200        self.send_streaming(&calling, &request, watching(caller))
1201    }
1202
1203    fn get_task(&self, caller: &Caller<'_>, request: GetTaskRequest) -> Result<Task, A2aError> {
1204        Liaison::get_task(self, self.calling(caller)?.peer, &request)
1205    }
1206
1207    fn list_tasks(
1208        &self,
1209        caller: &Caller<'_>,
1210        request: ListTasksRequest,
1211    ) -> Result<ListTasksResponse, A2aError> {
1212        Liaison::list_tasks(self, self.calling(caller)?.peer, &request)
1213    }
1214
1215    fn cancel_task(
1216        &self,
1217        caller: &Caller<'_>,
1218        request: CancelTaskRequest,
1219    ) -> Result<Task, A2aError> {
1220        Liaison::cancel_task(self, self.calling(caller)?.peer, &request)
1221    }
1222
1223    fn subscribe_to_task(
1224        &self,
1225        caller: &Caller<'_>,
1226        request: SubscribeToTaskRequest,
1227    ) -> Result<Events, A2aError> {
1228        self.subscribe(self.calling(caller)?.peer, &request, watching(caller))
1229    }
1230}
1231
1232/// The Run a context's replies come back to: Liaison's own name for the thread, never the
1233/// A2A Task ID.
1234fn route(context: &str) -> String {
1235    format!("liaison-{context}")
1236}
1237
1238fn reply_message(reply: &CableDelivery, context: &str, task: &str) -> Message {
1239    let metadata = Members {
1240        addressee: None,
1241        from: Some(reply.from_agent.clone()),
1242    }
1243    .into_object();
1244    Message {
1245        message_id: reply.cable_id.clone(),
1246        context_id: Some(context.to_owned()),
1247        task_id: Some(task.to_owned()),
1248        role: Role::Agent,
1249        parts: vec![Part::text(reply.body.clone())],
1250        metadata,
1251        ..Message::default()
1252    }
1253}
1254
1255/// The Cable relay over `registry`, as the `cables` record of `snapshot` sets it, reaching
1256/// `endpoints`; every Cable it takes is audited with the principal it acts for as actor. `None`
1257/// when the record cannot be applied.
1258pub(crate) fn cable_relay(
1259    registry: Arc<dyn RegistryBackend>,
1260    snapshot: &ai6::ConfigSnapshot,
1261    endpoints: Vec<CableEndpoint>,
1262) -> Option<CableRelay> {
1263    let cables = &snapshot.settings.cables;
1264    let policy = cables.policy().ok()?;
1265    let (sender_rate, sender_burst, scope_rate, scope_burst) = cables.quota_limits();
1266    let roster = snapshot.roster.clone();
1267    let audit = registry.clone();
1268    CableRelay::new(
1269        registry,
1270        policy,
1271        move || endpoints.clone(),
1272        cables.channels().clone(),
1273    )
1274    .with_lineage(move |operation| {
1275        roster
1276            .lineage(operation)
1277            .into_iter()
1278            .map(str::to_owned)
1279            .collect()
1280    })
1281    .with_durable_audit(move |record| write_cable_audit(audit.as_ref(), record))
1282    .with_cross_operation(cables.cross_operation())
1283    .with_limits(
1284        cables.max_fanout(),
1285        sender_rate,
1286        sender_burst,
1287        scope_rate,
1288        scope_burst,
1289    )
1290    .and_then(|relay| relay.with_message_limits(cables.message_limits()))
1291    .ok()
1292}
1293
1294/// The audit log entry of a Cable sent or read for a principal: `cable.send` or `cable.read`,
1295/// the principal as actor.
1296fn write_cable_audit(
1297    registry: &dyn RegistryBackend,
1298    record: &CableAuditRecord,
1299) -> Result<(), String> {
1300    let scope = format!("{:?}", record.target_scope).to_lowercase();
1301    let mut target = format!(
1302        "{} {} {scope}:{} {}",
1303        record.agent,
1304        record.decision,
1305        record.target_name.as_deref().unwrap_or(""),
1306        record.cable_id.as_deref().unwrap_or("-")
1307    );
1308    cut(&mut target, 500);
1309    registry
1310        .record_audit(&AuditRecord {
1311            id: format!("liaison.cable-{}", uuid::Uuid::new_v4().simple()),
1312            actor: record
1313                .on_behalf_of
1314                .clone()
1315                .unwrap_or_else(|| record.agent.clone()),
1316            action: if record.event == "cable_read" {
1317                "cable.read"
1318            } else {
1319                "cable.send"
1320            }
1321            .to_owned(),
1322            operation: record.operation.clone(),
1323            resource: None,
1324            target,
1325            at: record.at,
1326        })
1327        .map_err(|error| error.to_string())
1328}
1329
1330/// A retry key for a peer's message: the same message ID from the same peer is the same Cable.
1331fn idempotency_key(peer: &str, message_id: &str) -> String {
1332    use sha2::{Digest, Sha256};
1333    let digest = Sha256::digest(format!("{peer}\n{message_id}").as_bytes());
1334    let hex: String = digest.iter().map(|byte| format!("{byte:02x}")).collect();
1335    format!("a2a-{hex}")
1336}
1337
1338fn reply_artifact(reply: &Message) -> Artifact {
1339    Artifact {
1340        artifact_id: reply.message_id.clone(),
1341        name: Some("reply".to_owned()),
1342        parts: reply.parts.clone(),
1343        ..Artifact::default()
1344    }
1345}
1346
1347fn unavailable(what: &str) -> A2aError {
1348    A2aError::new(ErrorKind::Internal, format!("{what} is unavailable"))
1349}
1350
1351/// Sleeps `poll`, in slices short enough that a caller who left ends it soon.
1352fn pause(poll: Duration, open: &Open) {
1353    let slice = Duration::from_millis(50);
1354    let mut left = poll;
1355    while !left.is_zero() && open() {
1356        let step = left.min(slice);
1357        std::thread::sleep(step);
1358        left -= step;
1359    }
1360}
1361
1362fn cut(text: &mut String, bytes: usize) {
1363    if text.len() > bytes {
1364        let mut end = bytes;
1365        while !text.is_char_boundary(end) {
1366            end -= 1;
1367        }
1368        text.truncate(end);
1369    }
1370}
1371
1372fn now() -> f64 {
1373    SystemTime::now()
1374        .duration_since(UNIX_EPOCH)
1375        .map_or(0.0, |elapsed| elapsed.as_secs_f64())
1376}
1377
1378/// Unix seconds as A2A writes a time: ISO 8601 in UTC, to the millisecond.
1379fn timestamp(at: f64) -> String {
1380    let millis = (at * 1000.0) as i128;
1381    time::OffsetDateTime::from_unix_timestamp_nanos(millis * 1_000_000)
1382        .ok()
1383        .and_then(|time| {
1384            time.format(&time::format_description::well_known::Rfc3339)
1385                .ok()
1386        })
1387        .unwrap_or_else(coqui_a2a::model::timestamp_now)
1388}