Skip to main content

troupekit_kit/
route.rs

1use crate::agent::Agent;
2use crate::error::KitError;
3use crate::graph::Graph;
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use troupekit_agent::{ModelHandle, Persona, UsageLedger};
8use troupekit_core::error::{ProviderError, ProviderErrorKind};
9use troupekit_providers::request::{CompletionRequest, CompletionResponse, Delta};
10use troupekit_providers::route::{
11    DeviceState, NetworkState, RouteError, RoutePolicy, RouteTags, RoutedModel,
12};
13use troupekit_providers::{Model, Price};
14
15const LOCAL: &str = "local";
16const CLOUD: &str = "cloud";
17const NO_ON_DEVICE: &str = "a private agent needs an on-device model: call .local(..), \
18     or .route(..) with a `local` target and .local(..)";
19
20#[derive(Clone, Default)]
21pub(crate) struct RouteConfig {
22    policy: Option<RoutePolicy>,
23    file: Option<PathBuf>,
24    pub(crate) private: bool,
25    pub(crate) tier: Option<String>,
26    network: Option<Arc<NetworkState>>,
27    device: Option<Arc<DeviceState>>,
28    pub(crate) on_device: Option<(Arc<dyn Model>, Price)>,
29    pub(crate) local_only: bool,
30    #[cfg(feature = "local")]
31    pub(crate) local_model: Option<Arc<dyn troupekit_local::LocalModel>>,
32}
33
34fn same_arc<T: ?Sized>(a: &Option<Arc<T>>, b: &Option<Arc<T>>) -> bool {
35    match (a, b) {
36        (None, None) => true,
37        (Some(a), Some(b)) => Arc::ptr_eq(a, b),
38        _ => false,
39    }
40}
41
42fn read_policy(owner: &str, path: &Path) -> Result<RoutePolicy, KitError> {
43    let shown = path.display().to_string();
44    let fail = |m: String| KitError::config(owner, format!("route file `{shown}` {m}"));
45    let file = std::fs::File::open(path).map_err(|e| fail(format!("cannot be read: {e}")))?;
46    let limit = u64::try_from(RoutePolicy::MAX_BYTES).expect("64 KiB fits in u64");
47    let mut text = String::new();
48    file.take(limit + 1)
49        .read_to_string(&mut text)
50        .map_err(|e| fail(format!("cannot be read as UTF-8: {e}")))?;
51    if text.len() > RoutePolicy::MAX_BYTES {
52        return Err(fail(format!("is over {} bytes", RoutePolicy::MAX_BYTES)));
53    }
54    assert!(text.len() <= RoutePolicy::MAX_BYTES, "the read is bounded");
55    Ok(RoutePolicy::parse(&shown, &text)?)
56}
57
58impl RouteConfig {
59    pub(crate) fn same(&self, other: &RouteConfig) -> bool {
60        let same_local = match (&self.on_device, &other.on_device) {
61            (None, None) => true,
62            (Some((a, pa)), Some((b, pb))) => {
63                (Arc::ptr_eq(a, b) || self.same_loaded(other)) && pa == pb
64            }
65            _ => false,
66        };
67        self.policy == other.policy
68            && self.file == other.file
69            && self.private == other.private
70            && self.tier == other.tier
71            && same_arc(&self.network, &other.network)
72            && same_arc(&self.device, &other.device)
73            && same_local
74            && self.local_only == other.local_only
75    }
76
77    #[cfg(feature = "local")]
78    fn same_loaded(&self, other: &RouteConfig) -> bool {
79        match (&self.local_model, &other.local_model) {
80            (Some(a), Some(b)) => Arc::ptr_eq(a, b),
81            _ => false,
82        }
83    }
84
85    #[cfg(not(feature = "local"))]
86    fn same_loaded(&self, _other: &RouteConfig) -> bool {
87        false
88    }
89
90    pub(crate) fn has_route(&self) -> bool {
91        self.policy.is_some() || self.file.is_some()
92    }
93
94    pub(crate) fn check_judges(&self, owner: &str, persona: &Persona) -> Result<(), KitError> {
95        if !self.private {
96            return Ok(());
97        }
98        for eval in persona.evals.iter().filter(|e| e.name == "judge") {
99            let named = eval.args.get(2).and_then(serde_json::Value::as_str);
100            if let Some(model) = named.filter(|m| !m.starts_with("local/")) {
101                return Err(KitError::config(
102                    owner,
103                    format!(
104                        "a private agent cannot send answers to judge model `{model}`: \
105                         name a local/.. model or leave the judge on the agent's model"
106                    ),
107                ));
108            }
109        }
110        Ok(())
111    }
112
113    /// Picks the model handle the agent runs on; a route keeps its daily
114    /// cloud spend in `ledger`. `cloud` resolves the `.model(..)` selector
115    /// and is called only when the result can use it, so a private or
116    /// local-only agent needs no cloud key. Output: the handle or an error.
117    pub(crate) fn handle(
118        &self,
119        owner: &str,
120        ledger: &Arc<dyn UsageLedger>,
121        cloud: impl FnOnce() -> Result<ModelHandle, KitError>,
122    ) -> Result<ModelHandle, KitError> {
123        let policy = match (&self.policy, &self.file) {
124            (Some(policy), _) => Some(policy.clone()),
125            (None, Some(path)) => Some(read_policy(owner, path)?),
126            (None, None) => None,
127        };
128        let Some(policy) = policy else {
129            return self.unrouted(owner, cloud);
130        };
131        if let Some(tier) = self.tier.as_ref().filter(|t| !policy.tiers().contains(t)) {
132            return Err(KitError::config(
133                owner,
134                format!(
135                    "tier `{tier}` is served by no target of route `{}`",
136                    policy.name()
137                ),
138            ));
139        }
140        let has_local = policy.target(LOCAL).is_some();
141        let mut builder = RoutedModel::builder(policy.clone()).ledger(ledger.clone());
142        let mut cloud = Some(cloud);
143        for target in policy.targets() {
144            builder = match target.id() {
145                LOCAL => match &self.on_device {
146                    Some((model, price)) => builder.on_device(LOCAL, model.clone(), *price),
147                    None => {
148                        return Err(KitError::config(
149                            owner,
150                            "route target `local` needs an on-device model: call .local(..)",
151                        ))
152                    }
153                },
154                CLOUD if self.local_only => {
155                    return Err(KitError::config(
156                        owner,
157                        "route target `cloud` needs a cloud model: call .model(\"vendor/model\")",
158                    ))
159                }
160                CLOUD if self.private => builder.remote(CLOUD, Arc::new(Unreachable), Price::FREE),
161                CLOUD => {
162                    let resolve = cloud.take().expect("route target ids are unique");
163                    let handle = resolve()?;
164                    builder.remote(CLOUD, handle.model, handle.price)
165                }
166                other => {
167                    return Err(KitError::config(
168                        owner,
169                        format!(
170                        "route target `{other}` is not a kit target: name them `local` and `cloud`"
171                    ),
172                    ))
173                }
174            };
175        }
176        if let Some(network) = &self.network {
177            builder = builder.network(Arc::new(NetworkState::clone(network)));
178        }
179        if let Some(device) = &self.device {
180            builder = builder.device(DeviceState::clone(device));
181        }
182        if self.private && !has_local {
183            return Err(KitError::config(owner, NO_ON_DEVICE));
184        }
185        let mut tags = RouteTags::default().with_private(self.private);
186        tags.tier = self.tier.clone();
187        let view = builder.build()?.view(tags);
188        let price = view.price();
189        Ok(ModelHandle {
190            model: Arc::new(view),
191            price,
192        })
193    }
194
195    fn unrouted(
196        &self,
197        owner: &str,
198        cloud: impl FnOnce() -> Result<ModelHandle, KitError>,
199    ) -> Result<ModelHandle, KitError> {
200        if self.tier.is_some() {
201            return Err(KitError::config(
202                owner,
203                "a tier needs a policy: call .route(..)",
204            ));
205        }
206        if !self.private && !self.local_only {
207            return cloud();
208        }
209        match &self.on_device {
210            Some((model, price)) => Ok(ModelHandle {
211                model: model.clone(),
212                price: *price,
213            }),
214            None => Err(KitError::config(owner, NO_ON_DEVICE)),
215        }
216    }
217}
218
219/// Stand-in for route target `cloud` in a private agent's route. The
220/// private view never plans a remote target, so no call reaches it;
221/// binding it this way needs no cloud key. Every call returns an error.
222struct Unreachable;
223
224#[async_trait::async_trait]
225impl Model for Unreachable {
226    fn id(&self) -> &str {
227        "route/unreachable-cloud"
228    }
229
230    async fn complete(
231        &self,
232        _req: &CompletionRequest,
233    ) -> Result<CompletionResponse, ProviderError> {
234        Err(unreachable_call())
235    }
236
237    async fn stream(
238        &self,
239        _req: &CompletionRequest,
240        _on_delta: &mut (dyn for<'d> FnMut(&'d Delta) + Send),
241    ) -> Result<CompletionResponse, ProviderError> {
242        Err(unreachable_call())
243    }
244}
245
246fn unreachable_call() -> ProviderError {
247    ProviderError::new(
248        ProviderErrorKind::Network,
249        "a private agent never calls route target `cloud`",
250    )
251}
252
253impl From<RouteError> for KitError {
254    fn from(err: RouteError) -> Self {
255        KitError::Route(err)
256    }
257}
258
259impl Agent {
260    /// Routes each model call by `policy`: target `cloud` is the
261    /// `.model(..)` selector, target `local` the `.local(..)` model; any
262    /// other target id fails `build`. Replaces `route_file`.
263    pub fn route(mut self, policy: RoutePolicy) -> Self {
264        self.route.policy = Some(policy);
265        self.route.file = None;
266        self
267    }
268
269    /// Routes by the policy in TOML file `path`, read and checked at
270    /// `build` (at most 64 KiB). Same targets as `route`.
271    /// Replaces `route`.
272    pub fn route_file(mut self, path: impl AsRef<Path>) -> Self {
273        self.route.file = Some(path.as_ref().to_path_buf());
274        self.route.policy = None;
275        self
276    }
277
278    /// Keeps the agent's model requests on the device, even on fallback.
279    /// Default false. `build` refuses a private agent with no on-device
280    /// model, a cloud knowledge embedder, or a judge eval naming a cloud
281    /// model. Tools are not covered: `web_fetch`, `web_search` and HTTP
282    /// tools still send their requests over the network.
283    pub fn private(mut self, on: bool) -> Self {
284        self.route.private = on;
285        self
286    }
287
288    /// Sends requests only to route targets that list task tier `name`.
289    /// Needs `.route(..)`; a tier no target serves fails `build`.
290    /// Default: no tier.
291    pub fn tier(mut self, name: impl Into<String>) -> Self {
292        self.route.tier = Some(name.into());
293        self
294    }
295
296    /// Reads the network state for routing from `state`, which the app
297    /// keeps a clone of and sets. Without it a passive probe infers the
298    /// state from network errors.
299    pub fn network(mut self, state: NetworkState) -> Self {
300        self.route.network = Some(Arc::new(state));
301        self
302    }
303
304    /// Reads battery and thermal state for routing from `state`, which the
305    /// app keeps a clone of and sets. Without it both are unknown and the
306    /// policy's device rules are skipped.
307    pub fn device(mut self, state: DeviceState) -> Self {
308        self.route.device = Some(Arc::new(state));
309        self
310    }
311}
312
313impl Graph {
314    /// Makes every agent node private, as `Agent::private(true)` does.
315    /// Default false. Routes, local models and tiers stay per agent,
316    /// since a graph has no model of its own.
317    pub fn private(mut self, on: bool) -> Self {
318        self.private = on;
319        self
320    }
321}