Skip to main content

tilo_model_client/
transport.rs

1//! Transport-neutral asynchronous RPC to the model gateway, over the descriptor
2//! its launcher hands an app. Install this transport in the host's
3//! `ModelBackend`, not a process global.
4#[path = "administration_client.rs"]
5mod administration;
6#[cfg(test)]
7#[path = "client_fixture_tests.rs"]
8mod fixtures;
9#[cfg(test)]
10#[path = "transport_tests.rs"]
11mod tests;
12use crate::{Request, Response};
13pub use administration::AdministrationClient;
14use agent_provider_config::protocol::{ErrorKind, ModelError, ModelResponse, StreamEvent};
15use std::{future::Future, pin::Pin, time::Duration};
16
17pub type CallFuture<'a> = Pin<Box<dyn Future<Output = Result<Response, ModelError>> + Send + 'a>>;
18pub trait Transport: Send + Sync {
19    /// Intermediate events go to `event`; false cancels the operation. Dropping
20    /// this future cancels its response. Transports synchronize cancellation or
21    /// invalidate the connection so unread frames cannot contaminate another call.
22    fn call<'a>(
23        &'a self,
24        request: Request,
25        event: &'a mut (dyn FnMut(Response) -> bool + Send),
26    ) -> CallFuture<'a>;
27}
28
29#[cfg(unix)]
30#[path = "transport_fd.rs"]
31mod fd;
32#[cfg(unix)]
33pub use fd::FdTransport;
34
35/// Decode the gateway's public event wire once for synchronous and async clients.
36/// Completed-call compatibility events are inert: only the final turn can dispatch.
37pub fn decode_event(kind: &str, payload: &str) -> Result<Option<StreamEvent>, ModelError> {
38    let event = match kind {
39        crate::EVENT_TOOL_CALL => return Ok(None),
40        "text_delta" | "reasoning_delta" => {
41            let text = serde_json::from_str(payload)
42                .map_err(|_| ModelError::invalid("invalid gateway text delta"))?;
43            if kind == "text_delta" {
44                StreamEvent::TextDelta { text }
45            } else {
46                StreamEvent::ReasoningDelta { text }
47            }
48        }
49        crate::EVENT_TOOL_CALL_DELTA => {
50            #[derive(serde::Deserialize)]
51            struct Fragment {
52                index: u32,
53                id: Option<String>,
54                name: Option<String>,
55                delta: String,
56            }
57            let delta: Fragment = serde_json::from_str(payload)
58                .map_err(|_| ModelError::invalid("invalid gateway tool delta"))?;
59            StreamEvent::ToolCallDelta {
60                index: delta.index,
61                id: delta.id,
62                name: delta.name,
63                arguments: delta.delta,
64            }
65        }
66        _ => return Err(ModelError::invalid("unknown gateway stream event")),
67    };
68    Ok(Some(event))
69}
70
71pub(crate) fn decode_completion(output: &str) -> Result<ModelResponse, ModelError> {
72    let response: ModelResponse = serde_json::from_str(output)
73        .map_err(|_| ModelError::invalid("invalid gateway completion"))?;
74    // Refusal and output limits are valid terminal responses. StreamState keeps
75    // their prose, but never exposes their calls. Malformed finals fail here.
76    match response.tool_calls() {
77        Err(error) if !matches!(error.kind, ErrorKind::Refused | ErrorKind::Truncated) => {
78            Err(error)
79        }
80        _ => Ok(response),
81    }
82}
83
84fn completion(response: &Response) -> Result<ModelResponse, ModelError> {
85    if !response.ok {
86        return Err(response.failure_error().model_error());
87    }
88    if response.event.is_some() {
89        return Err(ModelError::invalid("missing gateway final response"));
90    }
91    decode_completion(response.output.as_deref().unwrap_or_default())
92}
93
94pub(crate) fn finish_stream(
95    result: Result<ModelResponse, ModelError>,
96    event: &mut dyn FnMut(&StreamEvent),
97) -> Result<ModelResponse, ModelError> {
98    match &result {
99        Ok(response) => event(&StreamEvent::Finished {
100            response: response.clone(),
101        }),
102        Err(error) => event(&StreamEvent::Failed {
103            error: error.clone(),
104        }),
105    }
106    result
107}
108
109/// A selected-model backend suitable for host-scoped installation. Selection
110/// travels as public profile/model identifiers; provider URLs and keys do not.
111///
112/// `FdTransport` negotiates cancellation before starting work and preserves its
113/// launcher connection after a synchronized Stop. Older gateways fail closed;
114/// corrupt or unresponsive connections require relaunch, never a socket fallback.
115pub struct ModelClient<T> {
116    transport: T,
117    profile_id: String,
118    model_id: String,
119    timeout_ms: u64,
120    use_default: bool,
121}
122impl<T: Transport> ModelClient<T> {
123    /// A Send-safe single completion over this client's selected route.
124    pub async fn complete_once(
125        &self,
126        request: &agent_provider_config::protocol::ModelRequest,
127    ) -> Result<ModelResponse, ModelError> {
128        let response = self
129            .transport
130            .call(self.request(request, false), &mut |_| true)
131            .await?;
132        completion(&response)
133    }
134
135    /// Resolve the gateway's current deliberate default at each inference start.
136    pub fn default_model(transport: T, timeout: Duration) -> Self {
137        Self {
138            transport,
139            profile_id: String::new(),
140            model_id: String::new(),
141            timeout_ms: timeout.as_millis().min(120_000) as u64,
142            use_default: true,
143        }
144    }
145
146    fn request(
147        &self,
148        request: &agent_provider_config::protocol::ModelRequest,
149        stream: bool,
150    ) -> Request {
151        if self.use_default {
152            Request::CompleteDefault {
153                request: request.clone(),
154                timeout_ms: self.timeout_ms,
155                stream,
156            }
157        } else {
158            Request::Complete {
159                profile_id: self.profile_id.clone(),
160                model_id: self.model_id.clone(),
161                request: request.clone(),
162                timeout_ms: self.timeout_ms,
163                stream,
164            }
165        }
166    }
167    /// Presentation deltas survive terminal failure in the caller's `StreamState`.
168    /// Returning false cancels the request; partial tools never authorize actions.
169    pub async fn complete_streaming(
170        &self,
171        request: &agent_provider_config::protocol::ModelRequest,
172        event: &mut (dyn FnMut(&agent_provider_config::protocol::StreamEvent) -> bool + Send),
173    ) -> Result<
174        agent_provider_config::protocol::ModelResponse,
175        agent_provider_config::protocol::ModelError,
176    > {
177        let mut invalid = false;
178        let response = self
179            .transport
180            .call(self.request(request, true), &mut |item| {
181                if invalid {
182                    return false;
183                }
184                if !item.ok {
185                    invalid = true;
186                    return false;
187                }
188                match decode_event(
189                    item.event.as_deref().unwrap_or_default(),
190                    item.output.as_deref().unwrap_or_default(),
191                ) {
192                    Ok(Some(parsed)) => event(&parsed),
193                    Ok(None) => true,
194                    Err(_) => {
195                        invalid = true;
196                        false
197                    }
198                }
199            })
200            .await;
201        let result = match response {
202            _ if invalid => Err(ModelError::invalid("invalid gateway stream event")),
203            Err(error) => Err(error),
204            Ok(response) => completion(&response),
205        };
206        finish_stream(result, &mut |item| {
207            event(item);
208        })
209    }
210
211    pub fn new(transport: T, profile_id: String, model_id: String, timeout: Duration) -> Self {
212        Self {
213            transport,
214            profile_id,
215            model_id,
216            timeout_ms: timeout.as_millis().min(120_000) as u64,
217            use_default: false,
218        }
219    }
220}
221impl<T: Transport> agent_provider_config::protocol::ModelBackend for ModelClient<T> {
222    fn stream<'a>(
223        &'a self,
224        request: &'a agent_provider_config::protocol::ModelRequest,
225        mut sink: agent_provider_config::protocol::StreamSink<'a>,
226    ) -> agent_provider_config::protocol::CompletionFuture<'a> {
227        use agent_provider_config::protocol::{ErrorKind, ModelError, StreamEvent};
228        Box::pin(async move {
229            // The transport callback must be Send, but the host sink may own Rc
230            // or UI state. Poll both halves here, without spawning or marking
231            // the local sink Send. Bound a synchronous burst by the protocol's
232            // event budget; a misbehaving transport fails rather than losing a
233            // delta or blocking this same-thread consumer on a full queue.
234            let (sender, receiver) =
235                std::sync::mpsc::sync_channel(crate::MAX_STREAM_EVENTS + crate::MAX_DELTA_EVENTS);
236            let mut overflow = false;
237            let mut forward = |event: &StreamEvent| {
238                // complete_streaming also reports its result as an event. Emit
239                // the terminal locally, after all queued presentation deltas.
240                if matches!(
241                    event,
242                    StreamEvent::Finished { .. } | StreamEvent::Failed { .. }
243                ) {
244                    return true;
245                }
246                if sender.try_send(event.clone()).is_err() {
247                    overflow = true;
248                    return false;
249                }
250                true
251            };
252            let result = {
253                let mut operation = Box::pin(self.complete_streaming(request, &mut forward));
254                std::future::poll_fn(|cx| {
255                    let result = operation.as_mut().poll(cx);
256                    while let Ok(event) = receiver.try_recv() {
257                        sink(event);
258                    }
259                    result
260                })
261                .await
262            };
263            let result = if overflow {
264                Err(ModelError {
265                    kind: ErrorKind::Transport,
266                    message: "model stream exceeded the presentation queue capacity".into(),
267                })
268            } else {
269                result
270            };
271            finish_stream(result, &mut |event| sink(event.clone()))
272        })
273    }
274
275    fn complete<'a>(
276        &'a self,
277        request: &'a agent_provider_config::protocol::ModelRequest,
278    ) -> agent_provider_config::protocol::CompletionFuture<'a> {
279        Box::pin(self.complete_once(request))
280    }
281}