Skip to main content

agentmux_srv/server/reactive/
forward_tiers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The forwarding tiers of [`deliver`](super::deliver), for a target this instance does not
5//! run: a sidecar on this host, another channel's entry in the shared registry, a LAN
6//! peer, then the cloud relay or a hold. Moved out of `deliver` without a change in behaviour.
7
8use super::*;
9use crate::backend::message_flow::{MessageFlowOutcome, MessageFlowVia};
10use crate::backend::reactive::types::InjectionResponse;
11
12/// What the tiers share while one jekt looks for its target.
13pub(super) struct Tiers<'a> {
14    state: &'a AppState,
15    auth_via: crate::server::ReactiveAuthVia,
16    caller_uid: &'a str,
17    req: &'a InjectionRequest,
18    resp: &'a InjectionResponse,
19    forwarded_req: InjectionRequest,
20    same_host_req: InjectionRequest,
21    same_host_tier: &'a str,
22    /// Whether any forwarding tier found the target alive elsewhere. A target that is alive but
23    /// refused is not "absent" and is never held here (durable jekt spec §2.1, condition 3); a
24    /// same-host entry whose process is dead — every entry after an srv restart, which changes its
25    /// port — is not a candidate, so the first message after a restart is held.
26    candidate_seen: bool,
27    /// A candidate an older build registered can't take files (spec §3.4).
28    files_too_old: bool,
29    /// A former name's agent, or a display name's, runs as its slug (`former_slug`).
30    alias: Option<String>,
31    /// The LAN peer was sent the message and gave no answer in time.
32    silent_peer: bool,
33}
34
35impl<'a> Tiers<'a> {
36    pub(super) fn new(
37        state: &'a AppState,
38        auth_via: crate::server::ReactiveAuthVia,
39        caller_uid: &'a str,
40        req: &'a InjectionRequest,
41        resp: &'a InjectionResponse,
42    ) -> Self {
43        // Every forward below sends this hop-incremented request, not the
44        // original `req` — a peer that also fails to find the agent locally
45        // and forwards onward needs to see the accumulated hop count too.
46        let mut forwarded_req = req.clone();
47        forwarded_req.forward_hops = req.forward_hops.saturating_add(1);
48
49        // SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D4: a same-host hop to a
50        // DIFFERENT instance (Tier 2a/2b below) is labelled `channel`, not
51        // `host` — `host` is reserved for genuinely same-instance traffic, so
52        // the label finally matches the guarantee (the receiving instance holds
53        // no HMAC key for a sender it didn't spawn; §2.3 of the spec). The
54        // receiver can't tell a forward from a local call by auth alone (the
55        // forward authenticates with the receiver's own full `auth_key`), so
56        // the forwarding side says so here, and `resolve_delivery_tier` on the
57        // far side honours a full-key caller's claim as it always has.
58        //
59        // An already-`lan`/`wan` hop keeps its label: that's what lets the peer
60        // re-derive its own tier-specific verification on the second hop
61        // (`resolve_delivery_tier`'s doc comment, reagentx P0 on the LAN signing
62        // PR). A `channel` hop forwarded again stays `channel`. Tier 3 (LAN)
63        // sends `forwarded_req` untouched — the peer authenticates it via
64        // `lan_key` and forces `lan` regardless of the body.
65        let same_host_tier = same_host_forward_tier(req.delivery_tier.as_deref());
66        let mut same_host_req =
67            lan_v2::channel_sign_at_origin(&state.mstore, caller_uid, forwarded_req.clone());
68        same_host_req.delivery_tier = Some(same_host_tier.to_string());
69        let alias = former_slug::delivery_alias(state, &req.target_agent);
70        Self {
71            state,
72            auth_via,
73            caller_uid,
74            req,
75            resp,
76            forwarded_req,
77            same_host_req,
78            same_host_tier,
79            candidate_seen: false,
80            files_too_old: false,
81            alias,
82            silent_peer: false,
83        }
84    }
85
86    /// Tries each tier in turn; `Some` is the answer to send back. `None`: every tier
87    /// declined, so the caller returns the local error.
88    pub(super) async fn run(
89        mut self,
90        replay: &mut replay::Reservation,
91    ) -> Option<serde_json::Value> {
92        if let Some(body) = self.same_host_sidecar().await {
93            self.note_flow(MessageFlowVia::Channel, &body, None);
94            return Some(body);
95        }
96        if let Some(body) = self.other_channels().await {
97            self.note_flow(MessageFlowVia::Channel, &body, None);
98            return Some(body);
99        }
100        if let Some(body) = self.lan_peer().await {
101            let host = flow_notes::lan_host_of(self.state, &self.req.target_agent);
102            self.note_flow(MessageFlowVia::Lan, &body, host.as_deref());
103            return Some(body);
104        }
105        let body = self.relay_or_hold(replay).await?;
106        // A queued message was reported where the relay took it; what is left here is held or refused.
107        if flow_notes::answer_outcome(&body) != MessageFlowOutcome::Delivered {
108            self.note_flow(flow_notes::arrival_via(self.req), &body, None);
109        }
110        Some(body)
111    }
112
113    /// Tells the Atlas map what `body`, the answer of a forwarding tier, made of the message.
114    fn note_flow(&self, via: MessageFlowVia, body: &serde_json::Value, to_host: Option<&str>) {
115        flow_notes::note(self.state, self.req, via, flow_notes::answer_outcome(body), to_host);
116    }
117
118    /// Tier 2a: same host, a different sidecar of this channel (file registry → HTTP loopback).
119    async fn same_host_sidecar(&mut self) -> Option<serde_json::Value> {
120        let (state, req) = (self.state, self.req);
121        let data_dir = base::get_mux_data_dir();
122        if let Some((found_as, entry)) =
123            former_slug::registry_entry(&data_dir, &req.target_agent, self.alias.as_deref())
124        {
125            // Guard against self-forwarding loops.
126            if entry.local_url != state.local_web_url
127                && crate::server::jekt_files::entry_takes(req, &entry, &mut self.files_too_old)
128            {
129                match forward_inject_to_peer(
130                    state,
131                    req,
132                    &self.same_host_req,
133                    ForwardPeer {
134                        url: &entry.local_url,
135                        auth_key: &entry.auth_key,
136                        kind: "cross-instance",
137                        channel: None,
138                        trust: EchoTrust {
139                            delivery_tier: self.same_host_tier,
140                            sig_verified: req.sig_verified,
141                            reagent_verified: req.reagent_verified,
142                            lan_verified: req.lan_verified,
143                            channel_verified: req.channel_verified,
144                        },
145                    },
146                )
147                .await
148                {
149                    ForwardOutcome::Delivered(body) | ForwardOutcome::Refused(body) => {
150                        return Some(body)
151                    }
152                    // A non-delivery here is ambiguous: this entry may be
153                    // stale (agent unregistered without a clean shutdown), OR
154                    // the owning process may be alive and simply not have
155                    // registered this specific agent yet — e.g. right after
156                    // that channel's srv came up. Connection-level failure is
157                    // at least as plausible a transient trigger as a parsed
158                    // success:false body, which is why both land here.
159                    // `should_evict_on_forward_failure` combines PID-liveness
160                    // with the entry's age: a dead process always evicts; a
161                    // live process only protects a FRESH entry (the actual
162                    // startup race), not an old one — an old entry whose
163                    // process happens to still be alive for OTHER agents is
164                    // presumed to be its own genuinely-dead agent (reagent P1
165                    // round 2 on #2640: PID alone over-protects, since it
166                    // identifies the whole srv process, not this one agent).
167                    // See docs/retro/retro-cross-channel-jekt-eviction-2026-08-17.md.
168                    //
169                    // Falls through to Tier 2b/3 either way (reagent P1 on
170                    // #2350 — this previously returned unconditionally
171                    // whenever the body parsed, regardless of success, so a
172                    // stale same-channel entry never reached a later tier).
173                    ForwardOutcome::Stale | ForwardOutcome::NoAnswer => {
174                        if former_slug::may_evict(&found_as, req)
175                            && agent_registry::should_evict_on_forward_failure(&entry)
176                        {
177                            tracing::warn!(
178                                target = %req.target_agent,
179                                pid = entry.pid,
180                                "cross-instance forward: entry presumed dead — evicting and falling through"
181                            );
182                            agent_registry::remove(&data_dir, &found_as);
183                        } else {
184                            // Alive but did not take it: the target exists
185                            // elsewhere, so it is not held here.
186                            self.candidate_seen = true;
187                            tracing::warn!(
188                                target = %req.target_agent,
189                                pid = entry.pid,
190                                "cross-instance forward: entry is fresh and owning process is alive — NOT evicting, falling through"
191                            );
192                        }
193                    }
194                    // Says nothing about this entry's liveness — leave it be,
195                    // and do not treat the target as absent.
196                    ForwardOutcome::Inconclusive => self.candidate_seen = true,
197                }
198            }
199        }
200        None
201    }
202
203    async fn other_channels(&mut self) -> Option<serde_json::Value> {
204        let (state, req) = (self.state, self.req);
205        // Tier 2b: same host, DIFFERENT channel (host-global shared registry).
206        // Runs when Tier 2a had no same-channel entry or its forward already
207        // failed above — closes the gap issue #1916 tracked (Tier 2 previously
208        // only ever reached agents in the caller's own channel). Candidates are
209        // tried freshest-first (§4.3 of the cross-channel delivery spec);
210        // a failed forward evicts just that channel's entry and falls through
211        // to the next candidate, same evict-on-fail shape Tier 3 already uses.
212        if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
213            let (found_as, candidates) =
214                former_slug::shared_entries(&shared_dir, &req.target_agent, self.alias.as_deref());
215            for entry in candidates {
216                // Self-forward guard, matching Tier 2a. Also loopback-only
217                // (§5 of the spec): a poisoned registry entry can't redirect
218                // a forward off-box, since resolve_shared_reactive_dir() is a
219                // same-user local file, but defense in depth costs nothing here.
220                let is_loopback = entry.local_url.starts_with("http://127.0.0.1")
221                    || entry.local_url.starts_with("http://localhost")
222                    || entry.local_url.starts_with("http://[::1]");
223                if !is_loopback
224                    || entry.local_url == state.local_web_url
225                    || !crate::server::jekt_files::entry_takes(req, &entry, &mut self.files_too_old)
226                {
227                    continue;
228                }
229
230                match forward_inject_to_peer(
231                    state,
232                    req,
233                    &self.same_host_req,
234                    ForwardPeer {
235                        url: &entry.local_url,
236                        auth_key: &entry.auth_key,
237                        kind: "cross-channel",
238                        channel: Some(&entry.channel),
239                        trust: EchoTrust {
240                            delivery_tier: self.same_host_tier,
241                            sig_verified: req.sig_verified,
242                            reagent_verified: req.reagent_verified,
243                            lan_verified: req.lan_verified,
244                            channel_verified: req.channel_verified,
245                        },
246                    },
247                )
248                .await
249                {
250                    ForwardOutcome::Delivered(body) | ForwardOutcome::Refused(body) => {
251                        return Some(body)
252                    }
253                    // Same ambiguity and same should_evict_on_forward_failure
254                    // policy as Tier 2a — PID-liveness alone over-protects an
255                    // old, genuinely-dead individual agent whose srv process
256                    // another agent keeps alive (reagent P1 round 2 on #2640),
257                    // and a connection failure can be the same startup-race
258                    // transient (target channel's srv not listening yet). See
259                    // docs/retro/retro-cross-channel-jekt-eviction-2026-08-17.md.
260                    // Evicting only this channel's entry lets the loop try the
261                    // next candidate.
262                    ForwardOutcome::Stale | ForwardOutcome::NoAnswer => {
263                        if former_slug::may_evict(&found_as, req)
264                            && agent_registry::should_evict_on_forward_failure(&entry)
265                        {
266                            tracing::warn!(
267                                target = %req.target_agent,
268                                channel = %entry.channel,
269                                pid = entry.pid,
270                                "cross-channel forward: entry presumed dead — evicting and trying next candidate"
271                            );
272                            agent_registry::remove_shared(&shared_dir, &found_as, &entry.channel);
273                        } else {
274                            self.candidate_seen = true;
275                            tracing::warn!(
276                                target = %req.target_agent,
277                                channel = %entry.channel,
278                                pid = entry.pid,
279                                "cross-channel forward: entry is fresh and owning process is alive — NOT evicting, trying next candidate"
280                            );
281                        }
282                    }
283                    ForwardOutcome::Inconclusive => self.candidate_seen = true,
284                }
285            }
286        }
287        None
288    }
289
290    async fn lan_peer(&mut self) -> Option<serde_json::Value> {
291        let (state, req, caller_uid) = (self.state, self.req, self.caller_uid);
292        // Tier 3: LAN peer (mDNS lookup → HTTP). Runs when tier 2 had no registry
293        // entry or its forward failed. Queries each discovered LAN peer for the
294        // agent; result is cached for 60s to avoid per-inject mDNS fan-out.
295        let lan_peer = match state
296            .lan_discovery
297            .find_agent(&req.target_agent, &state.http_client)
298            .await
299        {
300            Some((url, key)) => match crate::server::jekt_files::lan_peer_takes(
301                &state.http_client,
302                req,
303                &url,
304                &key,
305                &mut self.files_too_old,
306                &mut self.candidate_seen,
307            )
308            .await
309            {
310                Ok(takes) => takes.then_some((url, key)),
311                Err(refusal) => return Some(refusal),
312            },
313            None => None,
314        };
315        if let Some((peer_url, peer_auth_key)) = lan_peer {
316            let lan_forwarded = lan_v2::sign_and_log(
317                &state.mstore,
318                caller_uid,
319                self.forwarded_req.clone(),
320                &peer_url,
321            );
322            let outcome = forward_inject_to_peer(
323                state,
324                req,
325                &lan_forwarded,
326                ForwardPeer {
327                    url: &peer_url,
328                    auth_key: &peer_auth_key,
329                    kind: "lan-peer",
330                    channel: None,
331                    trust: EchoTrust {
332                        delivery_tier: "lan",
333                        sig_verified: None,
334                        // reagent signing is WAN-only; it never applies on the
335                        // LAN forward path.
336                        reagent_verified: None,
337                        lan_verified: req.lan_verified,
338                        channel_verified: req.channel_verified,
339                    },
340                },
341            )
342            .await;
343            self.silent_peer = matches!(outcome, ForwardOutcome::NoAnswer);
344            match outcome {
345                ForwardOutcome::Delivered(body) | ForwardOutcome::Refused(body) => {
346                    return Some(body)
347                }
348                // The peer answered "not mine" (agent migrated away since we
349                // cached it) or was unreachable — either way the discovery
350                // cache entry is wrong. Unlike the registry tiers there is no
351                // freshness/PID guard to weigh: the cache is cheap to refill
352                // from mDNS, so evicting on any non-delivery is the right
353                // trade rather than an oversight.
354                // A stale route is evicted as wrong, so it is not a live
355                // candidate (Codex P1 on #3632): the message may still be
356                // held. Only an inconclusive answer leaves the target
357                // possibly alive there.
358                ForwardOutcome::Stale | ForwardOutcome::NoAnswer => {
359                    state.lan_discovery.evict_agent(&req.target_agent);
360                }
361                ForwardOutcome::Inconclusive => self.candidate_seen = true,
362            }
363        }
364        None
365    }
366
367    async fn relay_or_hold(
368        &mut self,
369        replay: &mut replay::Reservation,
370    ) -> Option<serde_json::Value> {
371        let (state, req, auth_via, caller_uid, resp) = (
372            self.state,
373            self.req,
374            self.auth_via,
375            self.caller_uid,
376            self.resp,
377        );
378        // Tier 4: cloud relay (muxbus store-and-forward). Runs when no local,
379        // same-host or LAN tier could place the message.
380        //
381        // This tier used to be a comment here delegating to a "muxbus-client"
382        // that the callers agents actually use are not — the MCP `Message`
383        // tool's send action POSTs to this very endpoint and bails on `success != true`, so
384        // the chain silently stopped at three while that tool's description
385        // promised "local → LAN → cloud". Owning it here means every caller
386        // inherits it. See `crate::muxbus::relay` and
387        // REPORT_NETWORK_ARCHITECTURE_DRYNESS_AND_ROBUST_LAN_2026_09_06.md §5.
388        //
389        // Except for an agent defined here that no tier found live: that one
390        // is held here unless the relay says another install of the account
391        // runs it (PLAN_JEKT_LOCAL_FIRST_ROUTING_2026_10_02.md §5). Before
392        // this, the relay came first for it too, so a same-computer agent got
393        // the relay's 30 min expiry instead of the 24 h hold, and only a
394        // sender NOT signed in to the cloud ever reached the hold.
395        if req.files.is_some() {
396            return Some(
397                crate::server::jekt_files::no_route(
398                    state,
399                    auth_via,
400                    caller_uid,
401                    req,
402                    resp,
403                    self.candidate_seen,
404                    self.files_too_old,
405                    &mut *replay,
406                )
407                .await,
408            );
409        }
410        // A peer that answers its polls but not this message: kept here and sent again by the replay
411        // (`peer_hold`), not left to the relay's 30 minutes (task #2512).
412        if self.silent_peer && !self.candidate_seen {
413            if let Some(held) = peer_hold::hold_for_silent_peer(state, auth_via, req, resp).await {
414                return Some(held);
415            }
416        }
417        if !self.candidate_seen
418            && route_for_absent(state, auth_via, req, resp).await == AbsentRoute::HoldHere
419        {
420            if let Some(held) = hold_for_absent_target(
421                state,
422                auth_via,
423                req,
424                resp,
425                HoldReason::NotRunning,
426                &mut *replay,
427            )
428            .await
429            {
430                return Some(held);
431            }
432        }
433        // An agent of a LAN peer that is down: kept here for 24 h, not left to the relay's 30 minutes
434        // (`peer_hold`).
435        if !self.candidate_seen {
436            if let Some(held) = peer_hold::hold_for_down_peer(state, auth_via, req, resp).await {
437                return Some(held);
438            }
439        }
440        if let Some(body) = try_cloud_relay(state, req, caller_uid).await {
441            return Some(body);
442        }
443        // 5. No tier knew the target: hold it for the agent's return, when
444        //    the durable jekt conditions hold.
445        if !self.candidate_seen {
446            if let Some(held) = hold_for_absent_target(
447                state,
448                auth_via,
449                req,
450                resp,
451                HoldReason::NotRunning,
452                &mut *replay,
453            )
454            .await
455            {
456                return Some(held);
457            }
458        }
459        None
460    }
461}