Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
delivery.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Claim → verify → deliver for one agent's pulled injections: the half of a
5//! pull that comes after the relay answered, shared by the single pull
6//! (`sync_agent_reactive`) and the batch pull (`sync_agents_batched`).
7
8use super::*;
9use crate::backend::message_flow::{self, MessageFlowOutcome, MessageFlowVia, Seen};
10use crate::backend::reactive::InjectionRequest;
11
12#[path = "delivery_steps.rs"]
13pub mod steps;
14
15#[path = "reagent_age.rs"]
16pub mod reagent_age;
17
18/// One agent's answer to a pending pull, single or batched.
19#[derive(Deserialize)]
20pub(super) struct PendingResp {
21    pub(super) injections: Vec<PendingInj>,
22    // What the relay dropped undelivered since the last pull. Absent
23    // from an older relay: nothing to report.
24    #[serde(default)]
25    pub(super) expired: Vec<delivery_status::notes::ExpiredItem>,
26}
27#[derive(Deserialize)]
28pub(super) struct PendingInj {
29    id: String,
30    source_agent: Option<String>,
31    message: String,
32    priority: Option<String>,
33    // When the relay received it (RFC 3339), for marking a late delivery.
34    #[serde(default)]
35    created_at: Option<String>,
36    // The sender's delivery deadline (RFC 3339), when one is carried
37    // (issue #3894): a short-lived notice is dropped, not delivered stale,
38    // if srv only gets to it after this. Optional: a sender that doesn't set
39    // it, or an older peer that doesn't send it, behaves exactly as before.
40    #[serde(default)]
41    expires_at: Option<String>,
42    // Present only for messages signed by an AgentMux-operated WAN
43    // sender (currently just the GitHub review-notification consumer,
44    // "reagent") — see agentmux_common::jekt_sign::verify_reagent_jekt.
45    // All four travel together; verification is attempted only when
46    // every one of them deserializes present (see below).
47    #[serde(default)]
48    reagent_sig: Option<String>,
49    #[serde(default)]
50    reagent_key_id: Option<String>,
51    #[serde(default)]
52    reagent_msg_id: Option<String>,
53    #[serde(default)]
54    reagent_ts_secs: Option<i64>,
55    // W3-S carried tuple + the cloud's same-account answer
56    // (SPEC_WAN_JEKT_VERIFICATION_2026_09_24.md §2.1). Absent from an
57    // older cloud and on unsigned rows; verified by `wan_verify` below.
58    #[serde(default)]
59    wan_sig: Option<String>,
60    #[serde(default)]
61    wan_msg_id: Option<String>,
62    #[serde(default)]
63    wan_ts_secs: Option<i64>,
64    #[serde(default)]
65    wan_source_agent: Option<String>,
66    #[serde(default)]
67    wan_target_agent: Option<String>,
68    #[serde(default)]
69    wan_source_host: Option<String>,
70    #[serde(default)]
71    wan_source_channel: Option<String>,
72    #[serde(default)]
73    wan_key_fp: Option<String>,
74    #[serde(default)]
75    sender_same_account: Option<bool>,
76    // Files sent with it, on the relay (server::jekt_cloud): the manifest as
77    // the sender signed it. Absent on a text jekt and from an older relay.
78    #[serde(default)]
79    files: Option<Vec<agentmux_common::jekt_files::CloudFile>>,
80    // The tier the sender declared (info|coord|sensitive), as the relay
81    // passed it on. Absent when none was declared and from an older relay.
82    #[serde(default)]
83    jekt_tier: Option<String>,
84    // What a review, CI or merge notice is, as the relay sends it beside the text (spec
85    // SPEC_REVIEW_AND_CHECKS_FLOW_EVENTS_2026_11_14.md). Not signed: kept as it came so a shape this build does
86    // not know cannot fail the pull, and read by `backend::pr_flow` (one object, or a short list), which applies it only
87    // with a verified notice.
88    #[serde(default)]
89    flow: Option<serde_json::Value>,
90}
91
92/// The sender's declared tier as the relay carries it. The tier is not part
93/// of the signed material, so only `sensitive` is taken: a carried tier can
94/// mark a message sensitive, never lower it below the default `coord`. A tier
95/// this build does not know (a newer AgentMux's) is read as sensitive, the
96/// most careful. The handler's trust rules apply on top as for any jekt.
97fn declared_tier(raw: Option<&str>) -> Option<crate::backend::reactive::types::JektTier> {
98    use crate::backend::reactive::types::JektTier;
99    raw.and_then(JektTier::from_wire).filter(|t| *t == JektTier::Sensitive)
100}
101
102/// What is noted when a relay message arrives: it is remembered (a bare "got it" back is refused), and,
103/// as it shows the sender is reachable, a message queued to it is no longer watched for a reply.
104fn note_arrival(mstore: &Store, req: &InjectionRequest) {
105    crate::backend::ack_policy::remember_arrival(mstore, req);
106    crate::muxbus::relay_watch::heard_from(req.source_agent.as_deref(), &req.target_agent);
107}
108
109/// The request a pulled injection is delivered as, before the signature
110/// checks below add their verdicts.
111fn wan_request(inj: &PendingInj, target: &str) -> InjectionRequest {
112    InjectionRequest {
113        target_agent: target.to_string(),
114        message: inj.message.clone(),
115        source_agent: inj.source_agent.clone(),
116        request_id: Some(inj.id.clone()),
117        priority: inj.priority.clone(),
118        // Keyword scanning in the handler still applies on top.
119        jekt_tier: declared_tier(inj.jekt_tier.as_deref()),
120        // The sender's deadline, when the relay passed it on: what the hold
121        // and the deferred queue then respect (issue #3894).
122        expires_at_ms: inj.expires_at.as_deref().and_then(delivery_status::notes::parse_created_at),
123        delivery_tier: Some("wan".to_string()),
124        forward_hops: 0,
125        reagent_key_id: inj.reagent_key_id.clone(),
126        ..Default::default()
127    }
128}
129#[derive(Deserialize)]
130pub(super) struct AckResp {
131    acknowledged: Vec<String>,
132    delivered_at: String,
133}
134
135/// Claim `body`'s injections for `agent_id` and deliver the ones this call
136/// won: the second half of [`sync_agent_reactive`], shared with
137/// [`sync_agents_batched`]. `agent_token` is the credential the pull used
138/// (`using_per_agent` when it is the agent's own), retried with the shared
139/// token on a rejection exactly as the pull is.
140#[allow(clippy::too_many_arguments)]
141pub(super) async fn claim_and_deliver(
142    base: &str,
143    agent_id: &str,
144    token: &str,
145    http: &reqwest::Client,
146    mstore: &Arc<Store>,
147    handler: &'static crate::backend::reactive::handler::ReactiveHandler,
148    mut body: PendingResp,
149    agent_token: String,
150    using_per_agent: bool,
151) -> AgentSyncOutcome {
152    if body.injections.is_empty() {
153        delivery_status::fetched(agent_id, 0, &body.expired);
154        tell_once_it_can_work(agent_id, mstore, handler).await;
155        return AgentSyncOutcome::Ok;
156    }
157    let Some(hooks) = crate::muxbus::server_hooks::installed() else { return AgentSyncOutcome::Ok }; // see `installed`
158
159    // A name the subscription holds through the pane's agent is delivered to the pane.
160    let target = super::live_names::delivery_target(handler, agent_id).await;
161    let limited = hooks.agent_unavailable(mstore, handler, &target);
162    if limited && leave_unsigned_at_relay(agent_id, &mut body) {
163        delivery_status::fetched(agent_id, 0, &body.expired);
164        return AgentSyncOutcome::Ok;
165    }
166
167    // Claim BEFORE delivering, not after: this is what prevents
168    // double-delivery when the same agent_id is concurrently registered by
169    // another AgentMux channel on this host (an intentionally-supported
170    // "two seats" workflow — see
171    // docs/specs/SPEC_MUXBUS_CROSS_CHANNEL_DUPLICATE_DELIVERY_2026_07_04.md).
172    // /reactive/ack now performs an atomic pending->delivered transition
173    // server-side; only injection ids that come back in `acknowledged` were
174    // actually won by this call and get delivered locally below. A
175    // previous version of this code delivered first and only acked
176    // successes afterward, which let two concurrent pollers both deliver
177    // the same injection.
178    let all_ids: Vec<String> = body.injections.iter().map(|inj| inj.id.clone()).collect();
179    let (claimed, agent_token) = match steps::claim(base, agent_id, token, http, mstore, &all_ids, agent_token, using_per_agent).await {
180        Ok(claimed) => claimed,
181        Err(outcome) => return outcome,
182    };
183
184    let delivered_at = claimed.delivered_at;
185    let claimed_ids: std::collections::HashSet<String> = claimed.acknowledged.into_iter().collect();
186    let mut delivered_count = 0usize;
187    for inj in &body.injections {
188        if !claimed_ids.contains(&inj.id) {
189            // Another concurrent poller (this account's other channel/seat)
190            // already won this claim — expected under the "two seats"
191            // workflow, not an error.
192            continue;
193        }
194
195        let checked = steps::verify(inj, agent_id, token, http, mstore).await;
196        if steps::is_repeat(inj, agent_id, &checked) {
197            continue;
198        }
199        let mut req = steps::request(inj, &target, &checked, mstore);
200        if steps::attach_files(base, http, &agent_token, agent_id, inj, &mut req, &delivered_at).await.is_err() {
201            continue;
202        }
203        // Remembered, so a bare "got it" back to this sender is refused (`backend::ack_policy`); the relay
204        // doesn't carry `reply` yet, so a WAN message never arrives marked `REPLY=none`.
205        note_arrival(mstore, &req);
206        let pr_flow = steps::pr_flow(inj, &checked, &req);
207        // Verified, and its agent can't work now: kept here until it can. Injected now it would be lost in
208        // a failed turn, or given back to the relay to come again. Or a routine message to a session gone
209        // cold, which waits for its next activity as a local or LAN one does (#2263).
210        if hooks.hold_wan_for_unavailable(mstore, handler, &req) || hooks.hold_relayed(&req).await {
211            note_flow(&req, MessageFlowOutcome::Held);
212            delivered_count += 1;
213            steps::record_delivered(&checked, &pr_flow);
214            continue;
215        }
216        // Not held, and its agent can't work now: injected it would start a turn that ends in an error (HTTP 429).
217        // The claim goes back to the relay, which offers the message again on a later pull; nothing is kept here.
218        if hooks.give_back_for_unavailable(mstore, handler, &req) {
219            delivery_status::left_at_relay(agent_id);
220            note_flow(&req, MessageFlowOutcome::Queued);
221            hooks.settle_files(&req, false);
222            release(base, http, &agent_token, agent_id, &inj.id, &delivered_at).await;
223            continue;
224        }
225        // W3-S §2.5: only now, after it landed, is this signature "seen" —
226        // a release-and-redeliver after a failed delivery must not read as
227        // a replay.
228        if inject_or_release(base, http, &agent_token, agent_id, inj, &delivered_at, handler, req).await {
229            delivered_count += 1;
230            steps::record_delivered(&checked, &pr_flow);
231        }
232    }
233
234    delivery_status::fetched(agent_id, delivered_count, &body.expired);
235    if !limited {
236        delivery_status::can_work_again(agent_id);
237    }
238    AgentSyncOutcome::Ok
239}
240
241/// An agent that can't work now (out of quota, signed out) is not given a relay notice: it would start a turn
242/// that ends in an error. A message with no signature of an install of this account can't be held for it (no
243/// proof of its sender, so a replay would raise its tier), and is not even claimed: it is taken out of `body`,
244/// stays at the relay, which offers it again on a later pull, and the agent is told once when it can work. A
245/// signed one stays in `body`, to be claimed and held as before. `true` when nothing is left to claim.
246fn leave_unsigned_at_relay(agent_id: &str, body: &mut PendingResp) -> bool {
247    let pulled = body.injections.len();
248    body.injections.retain(|inj| inj.wan_sig.is_some());
249    if body.injections.len() < pulled {
250        delivery_status::left_at_relay(agent_id);
251    }
252    body.injections.is_empty()
253}
254
255/// When relay messages were left at the relay for `agent_id` and it can work now: its one note about them.
256async fn tell_once_it_can_work(
257    agent_id: &str,
258    mstore: &Arc<Store>,
259    handler: &'static crate::backend::reactive::handler::ReactiveHandler,
260) {
261    if !delivery_status::has_left_at_relay(agent_id) {
262        return;
263    }
264    let Some(hooks) = crate::muxbus::server_hooks::installed() else { return };
265    let target = super::live_names::delivery_target(handler, agent_id).await;
266    if !hooks.agent_unavailable(mstore, handler, &target) {
267        delivery_status::can_work_again(agent_id);
268    }
269}
270
271/// Inject the request locally, settle its files, and tell the Atlas map. A delivery that failed (e.g. the agent
272/// is not ready) is released back to pending so it is retried, instead of silently dropped now that claiming
273/// already marked it "delivered". Whether it landed.
274#[allow(clippy::too_many_arguments)]
275async fn inject_or_release(
276    base: &str,
277    http: &reqwest::Client,
278    agent_token: &str,
279    agent_id: &str,
280    inj: &PendingInj,
281    delivered_at: &str,
282    handler: &'static crate::backend::reactive::handler::ReactiveHandler,
283    req: InjectionRequest,
284) -> bool {
285    let charged = req.files_delivery.is_some().then(|| req.clone());
286    let flow_req = (req.source_agent.clone(), req.target_agent.clone(), req.request_id.clone());
287    let delivery = handler.inject_message(req);
288    note_flow_of(&flow_req, if delivery.success { MessageFlowOutcome::Delivered } else { MessageFlowOutcome::Refused });
289    if let Some(charged) = &charged {
290        crate::muxbus::server_hooks::hooks().settle_files(charged, delivery.success);
291    }
292    tracing::debug!(
293        injection_id = %inj.id,
294        agent_id = %agent_id,
295        success = delivery.success,
296        "cloud_subscriber: delivered injection"
297    );
298    if !delivery.success {
299        release(base, http, agent_token, agent_id, &inj.id, delivered_at).await;
300    }
301    delivery.success
302}
303
304/// Tells the Atlas map a message that came through the cloud relay was handled here (`backend::message_flow`).
305fn note_flow(req: &InjectionRequest, outcome: MessageFlowOutcome) {
306    note_flow_of(&(req.source_agent.clone(), req.target_agent.clone(), req.request_id.clone()), outcome);
307}
308
309/// [`note_flow`] for a request already handed on: its sender, its receiver and its id.
310fn note_flow_of((from, to, msg_id): &(Option<String>, String, Option<String>), outcome: MessageFlowOutcome) {
311    let (Some(from), Some(msg_id)) = (from, msg_id) else { return };
312    let here = crate::backend::reactive::registry::local_host_label();
313    message_flow::note(&Seen { msg_id, from, from_host: None, to, to_host: Some(&here), via: MessageFlowVia::Wan, outcome });
314}
315
316/// Give a claimed injection back to pending, so it's delivered on a later
317/// pull. A release that fails strands it as delivered: logged loudly.
318async fn release(base: &str, http: &reqwest::Client, agent_token: &str, agent_id: &str, injection_id: &str, delivered_at: &str) {
319    let release_url = format!("{}/reactive/release", base);
320    match http
321        .post(&release_url)
322        .header("Authorization", format!("Bearer {}", agent_token))
323        .header("X-Agent-ID", agent_id)
324        .json(&serde_json::json!({
325            "injection_id": injection_id,
326            "delivered_at": delivered_at,
327        }))
328        .send()
329        .await
330    {
331        Ok(r) if r.status().is_success() => {}
332        Ok(r) => {
333            // Claim is stranded as "delivered" with no local delivery and no
334            // retry until this is visible — log loudly rather than discarding
335            // silently.
336            tracing::warn!(
337                injection_id = %injection_id,
338                agent_id = %agent_id,
339                status = %r.status(),
340                "cloud_subscriber: release request non-2xx — injection stranded as delivered, message lost"
341            );
342        }
343        Err(e) => {
344            tracing::warn!(
345                injection_id = %injection_id,
346                agent_id = %agent_id,
347                error = %e,
348                "cloud_subscriber: release request failed — injection stranded as delivered, message lost"
349            );
350        }
351    }
352}
353
354#[cfg(test)]
355#[path = "delivery_tests.rs"]
356mod tests;