Skip to main content

agentmux_srv_core/muxbus/
server_hooks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the relay's delivery path asks of the server layer.
5//!
6//! A message pulled from the relay is checked, its files fetched and the message held or injected,
7//! and a few of those steps (the holds, the files, the transcript-request tier rules) live in
8//! `server/` because they read the server's state and handlers. This module is the seam: muxbus
9//! names the [`ServerHooks`] it needs, and the server registers them once at startup
10//! ([`install`]), the way `server::jekt_cold::install` hands the cold hold its state. It is also
11//! the one place `muxbus` stops naming `server`, which the srv core split needs (Area54 #1350).
12
13use std::future::Future;
14use std::pin::Pin;
15use std::sync::{Arc, OnceLock};
16
17use agentmux_common::jekt_files::CloudFile;
18
19use crate::backend::reactive::handler::ReactiveHandler;
20use crate::backend::reactive::types::InjectionRequest;
21use crate::backend::storage::store::Store;
22
23pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
24
25/// The server-side steps of delivering a relayed message.
26pub trait ServerHooks: Send + Sync {
27    /// Verified and its agent can't work now: keep it here until it can. `true` when it is kept.
28    fn hold_wan_for_unavailable(&self, mstore: &Store, handler: &ReactiveHandler, req: &InjectionRequest) -> bool;
29
30    /// Not held, and its agent can't work now (out of quota, signed out): injecting it would start a turn that
31    /// ends in an error. `true` when the caller gives the claim back to the relay instead.
32    fn give_back_for_unavailable(&self, mstore: &Store, handler: &ReactiveHandler, req: &InjectionRequest) -> bool;
33
34    /// The agent here that `target` names can't work now (out of quota, signed out).
35    fn agent_unavailable(&self, mstore: &Store, handler: &ReactiveHandler, target: &str) -> bool;
36
37    /// A routine message to a session gone cold waits for its next activity. `true` when it is kept.
38    fn hold_relayed<'a>(&'a self, req: &'a InjectionRequest) -> BoxFuture<'a, bool>;
39
40    /// A message's inline files are charged until it is delivered; give the charge back when it was not.
41    fn settle_files(&self, req: &InjectionRequest, delivered: bool);
42
43    /// The two tier fields a transcript request carries, from the responding agent's own definition.
44    fn resolve_transcript_request_tier_fields(&self, mstore: &Arc<Store>, req: &mut InjectionRequest);
45
46    /// Check a cloud manifest, then fetch, decrypt and store each file. `Err` when the relay could
47    /// not be reached, so the caller releases the claim.
48    #[allow(clippy::too_many_arguments)]
49    fn fetch_files<'a>(
50        &'a self,
51        base: &'a str,
52        http: &'a reqwest::Client,
53        token: &'a str,
54        agent_id: &'a str,
55        req: &'a mut InjectionRequest,
56        files: Vec<CloudFile>,
57        wan_msg_id: Option<&'a str>,
58    ) -> BoxFuture<'a, Result<(), String>>;
59
60    /// List the fetched files in the message the agent reads.
61    fn prepare_files<'a>(&'a self, req: &'a mut InjectionRequest) -> BoxFuture<'a, ()>;
62}
63
64static HOOKS: OnceLock<&'static dyn ServerHooks> = OnceLock::new();
65
66/// Register the server's steps. Later calls change nothing.
67pub fn install(hooks: &'static dyn ServerHooks) {
68    let _ = HOOKS.set(hooks);
69}
70
71/// The registered steps, or `None` before the server has registered them. A delivery round that finds `None`
72/// claims nothing, so the relay offers the same messages again on the next pull. Under test, steps that leave
73/// every message alone stand in until something registers (the server's own are tested in the server layer).
74pub(crate) fn installed() -> Option<&'static dyn ServerHooks> {
75    #[cfg(any(test, feature = "test-support"))]
76    {
77        Some(HOOKS.get().copied().unwrap_or(&PlainSteps))
78    }
79    #[cfg(not(any(test, feature = "test-support")))]
80    {
81        HOOKS.get().copied()
82    }
83}
84
85/// The registered steps, or ones that do nothing and report the relay as unreachable. A delivery
86/// round checks [`installed`] before it claims anything, so this is only what a step reads if the
87/// server's registration is somehow lost mid-round.
88pub(crate) fn hooks() -> &'static dyn ServerHooks {
89    installed().unwrap_or(&NotReady)
90}
91
92struct NotReady;
93
94impl ServerHooks for NotReady {
95    fn hold_wan_for_unavailable(&self, _: &Store, _: &ReactiveHandler, _: &InjectionRequest) -> bool {
96        false
97    }
98    fn give_back_for_unavailable(&self, _: &Store, _: &ReactiveHandler, _: &InjectionRequest) -> bool {
99        false
100    }
101    fn agent_unavailable(&self, _: &Store, _: &ReactiveHandler, _: &str) -> bool {
102        false
103    }
104    fn hold_relayed<'a>(&'a self, _: &'a InjectionRequest) -> BoxFuture<'a, bool> {
105        Box::pin(async { false })
106    }
107    fn settle_files(&self, _: &InjectionRequest, _: bool) {}
108    fn resolve_transcript_request_tier_fields(&self, _: &Arc<Store>, _: &mut InjectionRequest) {}
109    fn fetch_files<'a>(
110        &'a self,
111        _: &'a str,
112        _: &'a reqwest::Client,
113        _: &'a str,
114        _: &'a str,
115        _: &'a mut InjectionRequest,
116        _: Vec<CloudFile>,
117        _: Option<&'a str>,
118    ) -> BoxFuture<'a, Result<(), String>> {
119        Box::pin(async { Err("AgentMux isn't ready to fetch files yet".to_string()) })
120    }
121    fn prepare_files<'a>(&'a self, _: &'a mut InjectionRequest) -> BoxFuture<'a, ()> {
122        Box::pin(async {})
123    }
124}
125
126/// The agents a delivery test declares out of quota: the plain steps give their messages back to the relay.
127#[cfg(any(test, feature = "test-support"))]
128pub(crate) static TEST_LIMITED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
129
130/// What a delivery test gets when nothing registered: no hold, no files, no transcript request, and no agent
131/// out of quota unless the test says so ([`TEST_LIMITED`]).
132#[cfg(any(test, feature = "test-support"))]
133struct PlainSteps;
134
135#[cfg(any(test, feature = "test-support"))]
136impl ServerHooks for PlainSteps {
137    fn hold_wan_for_unavailable(&self, _: &Store, _: &ReactiveHandler, _: &InjectionRequest) -> bool {
138        false
139    }
140    fn give_back_for_unavailable(&self, _: &Store, _: &ReactiveHandler, req: &InjectionRequest) -> bool {
141        TEST_LIMITED.lock().unwrap().contains(&req.target_agent)
142    }
143    fn agent_unavailable(&self, _: &Store, _: &ReactiveHandler, target: &str) -> bool {
144        TEST_LIMITED.lock().unwrap().iter().any(|a| a == target)
145    }
146    fn hold_relayed<'a>(&'a self, _: &'a InjectionRequest) -> BoxFuture<'a, bool> {
147        Box::pin(async { false })
148    }
149    fn settle_files(&self, _: &InjectionRequest, _: bool) {}
150    fn resolve_transcript_request_tier_fields(&self, _: &Arc<Store>, _: &mut InjectionRequest) {}
151    fn fetch_files<'a>(
152        &'a self,
153        _: &'a str,
154        _: &'a reqwest::Client,
155        _: &'a str,
156        _: &'a str,
157        _: &'a mut InjectionRequest,
158        _: Vec<CloudFile>,
159        _: Option<&'a str>,
160    ) -> BoxFuture<'a, Result<(), String>> {
161        Box::pin(async { Ok(()) })
162    }
163    fn prepare_files<'a>(&'a self, _: &'a mut InjectionRequest) -> BoxFuture<'a, ()> {
164        Box::pin(async {})
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn req() -> InjectionRequest {
173        InjectionRequest { target_agent: "hook-target".into(), request_id: Some("hook-msg".into()), ..Default::default() }
174    }
175
176    #[tokio::test]
177    async fn the_steps_a_lost_registration_falls_back_to_hold_nothing_and_fetch_nothing() {
178        let not_ready: &dyn ServerHooks = &NotReady;
179        let store = Arc::new(Store::open_in_memory().unwrap());
180        let mut r = req();
181        assert!(!not_ready.hold_relayed(&r).await);
182        not_ready.settle_files(&r, false);
183        not_ready.resolve_transcript_request_tier_fields(&store, &mut r);
184        not_ready.prepare_files(&mut r).await;
185        assert!(!r.is_transcript_request && r.files.is_none() && r.files_delivery.is_none());
186        let http = reqwest::Client::new();
187        let err = not_ready.fetch_files("http://127.0.0.1:1", &http, "t", "a", &mut r, Vec::new(), None).await;
188        assert!(err.is_err(), "a fetch with no registered steps gives the claim back");
189    }
190
191    #[test]
192    fn under_test_plain_steps_stand_in_until_something_registers() {
193        assert!(installed().is_some());
194    }
195
196    #[tokio::test]
197    async fn the_steps_leave_a_message_with_no_files_and_no_transcript_request_alone() {
198        let steps = installed().unwrap();
199        let store = Arc::new(Store::open_in_memory().unwrap());
200        let mut r = req();
201        r.message = "plain words".into();
202        steps.resolve_transcript_request_tier_fields(&store, &mut r);
203        steps.settle_files(&r, false);
204        steps.prepare_files(&mut r).await;
205        assert!(!r.is_transcript_request);
206        assert!(r.files.is_none() && r.files_delivery.is_none());
207    }
208}