Skip to main content

tilo_model_client/
lib.rs

1//! Model RPC over capabilities supplied by an authenticated host.
2
3#[cfg(unix)]
4use std::io::Write;
5#[cfg(unix)]
6use std::os::fd::{FromRawFd, RawFd};
7#[cfg(unix)]
8use std::os::unix::net::UnixStream;
9use std::time::Duration;
10
11use serde::{Deserialize, Serialize};
12use thiserror::Error;
13#[cfg(unix)]
14use zeroize::Zeroizing;
15
16#[cfg(test)]
17mod error_tests;
18pub mod failure;
19#[cfg(feature = "runtime-client")]
20pub mod runtime_client;
21pub mod transport;
22pub mod validation;
23
24// Launcher and runtime-portal uppercase the service name without replacing '-'.
25pub const SERVICE_FD_ENV: &str = "TILO_SVC_MODEL-GATEWAY_FD";
26/// Stable ownership namespace used by origin-bound provider credentials.
27pub const SERVICE_NAME: &str = "model-gateway";
28pub const RPC_VERSION: u16 = 3;
29/// Every gateway request and response: a little-endian `u32` length, then
30/// JSON.
31pub const FRAMING: wire_frame::Framing = wire_frame::Framing::little_endian(2 * 1024 * 1024);
32
33pub use agent_provider_config::is_supervised_loopback;
34
35/// Whether `revision` names an immutable model revision: a full lowercase
36/// SHA-1 or SHA-256 commit id, never a branch or tag.
37#[must_use]
38pub fn is_pinned_revision(revision: &str) -> bool {
39    matches!(revision.len(), 40 | 64)
40        && revision
41            .bytes()
42            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
43}
44
45/// The only encoded-preview media types accepted by the local vision RPC.
46/// Keeping this vocabulary closed means a caller cannot ask the trusted
47/// gateway to fetch a URL or interpret an arbitrary document as an image.
48#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
49pub struct VisionImage {
50    /// `image/jpeg`, `image/png`, or `image/webp`.
51    pub media_type: String,
52    /// Standard base64 of a caller-decoded, downscaled preview.
53    pub data_base64: String,
54    /// SHA-256 of the original photo bytes, not of `data_base64`.
55    pub source_content_hash: String,
56}
57
58/// One deliberately small photograph reference supplied to the dedicated
59/// local face runtime.  `photo_id` is an app address, not a pathname; the
60/// runtime never receives an identity label or an instruction from Photos.
61#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
62pub struct FaceImage {
63    pub photo_id: String,
64    pub media_type: String,
65    pub data_base64: String,
66    pub source_content_hash: String,
67}
68
69/// A request that can cross the sandbox boundary. A server also authenticates
70/// the launcher-provided app preamble. No request carries a provider key:
71/// this computer keeps none.
72#[derive(Deserialize, Serialize)]
73#[serde(tag = "verb", rename_all = "snake_case")]
74pub enum Request {
75    /// Negotiate reusable, per-operation cancellation before starting work.
76    /// Older gateways reject this verb; clients must not start paid work then.
77    CancellationSupported,
78    /// Native connection-local operation identity. Not an authentication claim.
79    Cancellable { id: u64, request: Box<Request> },
80    /// Cancel only the matching operation on this authenticated connection.
81    /// The acknowledgement is a synchronization barrier, even after completion.
82    Cancel { id: u64 },
83    /// Provider-neutral completion, asked of the person's own model on their
84    /// workspace's server. The provider and model it names are this
85    /// computer's description of the caller's choice; the server answers with
86    /// the model the person chose there.
87    Complete {
88        profile_id: String,
89        model_id: String,
90        request: agent_provider_config::protocol::ModelRequest,
91        timeout_ms: u64,
92        #[serde(default)]
93        stream: bool,
94    },
95    /// Provider-neutral completion with the person's default model, asked on
96    /// their workspace's server.
97    CompleteDefault {
98        request: agent_provider_config::protocol::ModelRequest,
99        timeout_ms: u64,
100        #[serde(default)]
101        stream: bool,
102    },
103    /// A content-free timing mark from the agent (whose own stderr a managed
104    /// launch discards), written to the gateway's timing log. Older RPC3
105    /// servers reject this additive verb; callers ignore the refusal.
106    Trace {
107        trace: PlanTrace,
108        event: TraceEvent,
109        /// When the mark happened (Unix ms), if the caller had to hold it
110        /// while a streamed turn owned the channel. Absent: now.
111        #[serde(default, skip_serializing_if = "Option::is_none")]
112        at_unix_ms: Option<u64>,
113    },
114    /// Fixed-shape, device-local visual analysis for Photos. The gateway
115    /// owns the prompt and refuses hosted, unpinned, or non-vision profiles;
116    /// a sandboxed caller never obtains direct network access.
117    AnalyzeImage {
118        profile_id: String,
119        model_id: String,
120        image: VisionImage,
121    },
122    /// Fixed, consent-guarded face detection and clustering.  The gateway owns
123    /// the request schema and admits it only for the signed local face model.
124    /// It returns opaque cluster/photo membership; no embedding, crop, face
125    /// rectangle, identity name, or raw path can cross this boundary.
126    ClusterFaces {
127        profile_id: String,
128        model_id: String,
129        images: Vec<FaceImage>,
130    },
131    /// Find the subject of one bounded picture with the on-device
132    /// segmentation model the person installed (Settings › Models). The
133    /// gateway runs the model itself, on the CPU; no model file, path or
134    /// network reaches the caller, and nothing leaves the device. Answers a
135    /// [`SubjectMatte`] as JSON. Older servers reject this verb; callers
136    /// treat that as no model.
137    SegmentSubject { image: VisionImage },
138    /// The models a provider offers, asked with its stored key or sign-in:
139    /// Settings' model list and connection test. Answers the models as JSON
140    /// (`ModelDescriptor`s); a failure names its kind, never what the
141    /// provider wrote. Older gateways reject this verb.
142    ListModels { profile_id: String },
143}
144
145/// How much of each pixel of a [`Request::SegmentSubject`] picture is its
146/// subject, and what found it.
147#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
148pub struct SubjectMatte {
149    /// The matte's size: the picture's.
150    pub width: u32,
151    pub height: u32,
152    /// Standard base64 of a greyscale PNG, white where the subject is.
153    pub matte_png_base64: String,
154    /// The catalogue model and its pinned revision, for provenance.
155    pub model_id: String,
156    pub revision: String,
157    /// Milliseconds spent loading the model (0 when it was loaded already)
158    /// and running it.
159    pub load_ms: u64,
160    pub infer_ms: u64,
161}
162
163/// The message the gateway refuses [`Request::SegmentSubject`] with when no
164/// segmentation model is installed, so a caller can offer to set one up.
165pub const NO_SEGMENTATION_MODEL: &str = "no on-device subject model is installed";
166
167/// Correlates the model turns of one agent decision.
168#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
169pub struct PlanTrace {
170    /// Random per decision; carries no content.
171    pub id: u64,
172    /// Zero-based model turn within the decision, or a step index for marks.
173    pub turn: u32,
174}
175
176/// The closed vocabulary of agent timing marks.
177#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
178#[serde(rename_all = "snake_case")]
179pub enum TraceEvent {
180    /// The model's final plan was read and accepted by the agent.
181    PlanReady,
182    /// The decision failed (fallback, timeout, invalid answer).
183    PlanFailed,
184    /// The agent sent one planned action to the host.
185    ActionSubmitted,
186    ActionSettled,
187}
188
189/// The only streaming event kind: one completed provider tool call, as
190/// `{"id":..,"name":..,"arguments":<JSON string>}` in [`Response::output`].
191pub const EVENT_TOOL_CALL: &str = "tool_call";
192
193/// An intermediate streaming event requested with `deltas`: raw argument text
194/// appended to the tool call in progress, as
195/// `{"index":u32,"id":str|null,"name":str,"delta":str}` in
196/// [`Response::output`]. Every delta of a call precedes its `tool_call`.
197pub const EVENT_TOOL_CALL_DELTA: &str = "tool_call_delta";
198
199#[derive(Debug, Deserialize, Serialize)]
200pub struct Frame<T> {
201    pub version: u16,
202    #[serde(flatten)]
203    pub value: T,
204}
205
206#[derive(Clone, Debug, Deserialize, Serialize)]
207pub struct Response {
208    pub ok: bool,
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub output: Option<String>,
211    #[serde(skip_serializing_if = "Option::is_none")]
212    pub configured: Option<bool>,
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub error: Option<String>,
215    /// Additive RPC3 diagnostic. Older peers ignore this field; absent on older gateways.
216    #[serde(default, skip_serializing_if = "Option::is_none")]
217    pub model_error: Option<agent_provider_config::protocol::ModelError>,
218    /// Set only on intermediate streaming frames (see [`EVENT_TOOL_CALL`]).
219    /// A response without an event is the final frame of a request.
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub event: Option<String>,
222}
223
224impl Response {
225    /// Construct a redacted failure while retaining its machine-readable kind.
226    pub fn failure(mut error: agent_provider_config::protocol::ModelError) -> Self {
227        error.message = agent_provider_config::protocol::ModelError::new(error.kind).message;
228        Self {
229            ok: false,
230            output: None,
231            configured: None,
232            error: Some(error.message.clone()),
233            model_error: Some(error),
234            event: None,
235        }
236    }
237
238    /// Typed errors take precedence. English matching is only for old gateways.
239    pub fn failure_error(&self) -> ClientError {
240        match &self.model_error {
241            Some(error) => {
242                ClientError::Model(agent_provider_config::protocol::ModelError::new(error.kind))
243            }
244            None => ClientError::Rejected(self.error.clone().unwrap_or_default()),
245        }
246    }
247
248    pub fn into_result(self) -> Result<Self, ClientError> {
249        if self.ok {
250            Ok(self)
251        } else {
252            Err(self.failure_error())
253        }
254    }
255}
256
257#[derive(Error)]
258pub enum ClientError {
259    #[error("Tilo model gateway is unavailable")]
260    Unavailable,
261    #[error("{0}")]
262    Model(agent_provider_config::protocol::ModelError),
263    #[error("model gateway protocol error")]
264    Protocol(String),
265    #[error("model gateway refused request: {}", self.model_error())]
266    Rejected(String),
267}
268
269impl std::fmt::Debug for ClientError {
270    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271        std::fmt::Display::fmt(self, formatter)
272    }
273}
274
275impl ClientError {
276    /// A safe, actionable diagnostic for neutral streaming consumers.
277    pub fn model_error(&self) -> agent_provider_config::protocol::ModelError {
278        use agent_provider_config::protocol::{ErrorKind, ModelError};
279        let kind = match self {
280            Self::Model(error) => return error.clone(),
281            Self::Unavailable => ErrorKind::Unavailable,
282            Self::Protocol(_) => ErrorKind::InvalidResponse,
283            Self::Rejected(detail) => {
284                // RPC3 predates typed errors. Classify only at this compatibility
285                // boundary; never repeat the gateway's diagnostic to a frontend.
286                let detail = detail.to_ascii_lowercase();
287                let patterns: &[(ErrorKind, &[&str])] = &[
288                    (
289                        ErrorKind::CreditsExhausted,
290                        &["credits", "quota", "subscription_required"],
291                    ),
292                    (
293                        ErrorKind::ContextLimit,
294                        &["context limit", "context_length"],
295                    ),
296                    (ErrorKind::Authentication, &["authentication", "api key"]),
297                    (ErrorKind::PermissionDenied, &["permission denied"]),
298                    (ErrorKind::RateLimited, &["rate limit"]),
299                    (ErrorKind::TimedOut, &["timed out"]),
300                    (ErrorKind::Cancelled, &["cancelled"]),
301                    (
302                        ErrorKind::Truncated,
303                        &["truncated", "without a final response"],
304                    ),
305                    (
306                        ErrorKind::Transport,
307                        &["network", "transport failed", "stream interrupted"],
308                    ),
309                    (
310                        ErrorKind::Refused,
311                        &[
312                            "model declined",
313                            "model refused",
314                            "provider refusal",
315                            "content filter",
316                        ],
317                    ),
318                    (ErrorKind::InvalidRequest, &["unsupported image media type"]),
319                    (
320                        ErrorKind::InvalidResponse,
321                        &["malformed", "unreadable", "unsupported finish reason"],
322                    ),
323                ];
324                patterns
325                    .iter()
326                    .find(|(_, phrases)| phrases.iter().any(|phrase| detail.contains(phrase)))
327                    .map_or(ErrorKind::Provider, |(kind, _)| *kind)
328            }
329        };
330        ModelError::new(kind)
331    }
332}
333
334/// Whether this process has the launcher-issued service descriptor. This does
335/// not probe or connect to a pathname socket, so the sandbox cannot substitute
336/// a different same-UID service.
337#[cfg(unix)]
338pub fn available() -> bool {
339    std::env::var(SERVICE_FD_ENV)
340        .ok()
341        .and_then(|value| value.parse::<RawFd>().ok())
342        .is_some_and(|fd| fd >= 3 && unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1)
343}
344
345/// No launcher-issued gateway transport is implemented on this platform.
346/// Environment variables cannot manufacture a supported capability.
347#[cfg(not(unix))]
348pub fn available() -> bool {
349    false
350}
351
352/// Send a request over the launcher-provided service fd. The fd is duplicated
353/// for each RPC so a short-lived helper cannot close the parent app's channel.
354///
355/// # Errors
356///
357/// Returns [`ClientError::Unavailable`] when the launcher service descriptor or
358/// gateway connection is unavailable, [`ClientError::Protocol`] for malformed
359/// frames, and [`ClientError::Rejected`] when the gateway refuses the request.
360#[cfg(unix)]
361pub fn request(request: Request) -> Result<Response, ClientError> {
362    let turn = ChannelTurn::take()?;
363    let response = exchange(request);
364    drop(turn);
365    response
366}
367
368/// [`request`], on this thread's turn of the channel.
369#[cfg(unix)]
370fn exchange(request: Request) -> Result<Response, ClientError> {
371    exchange_on(service_stream()?, request)
372}
373
374/// `request` on the connection `stream`, written as one frame and answered.
375#[cfg(unix)]
376fn exchange_on(mut stream: UnixStream, request: Request) -> Result<Response, ClientError> {
377    write_frame(
378        &mut stream,
379        &Frame {
380            version: RPC_VERSION,
381            value: request,
382        },
383    )?;
384    let response: Response = read_frame(&mut stream)?;
385    response.into_result()
386}
387
388/// A duplicate of `descriptor` this side owns, for one exchange: the launcher
389/// handed the caller the service connection, and every RPC takes a duplicate
390/// so concurrent exchanges never interleave their frames.
391///
392/// # Errors
393/// [`ClientError::Unavailable`] when the descriptor cannot be duplicated.
394#[cfg(unix)]
395fn duplicate(descriptor: std::os::fd::BorrowedFd<'_>) -> Result<UnixStream, ClientError> {
396    let owned = descriptor
397        .try_clone_to_owned()
398        .map_err(|_| ClientError::Unavailable)?;
399    Ok(UnixStream::from(owned))
400}
401
402/// [`analyze_image`] on the connection `descriptor`, for a host that holds the
403/// model gateway's descriptor itself rather than through the launcher's
404/// environment (the session's own services).
405///
406/// # Errors
407/// [`ClientError::Unavailable`] when the descriptor cannot be used, else why
408/// the gateway did not answer.
409#[cfg(unix)]
410pub fn analyze_image_on(
411    descriptor: std::os::fd::BorrowedFd<'_>,
412    profile_id: &str,
413    model_id: &str,
414    image: VisionImage,
415) -> Result<String, ClientError> {
416    let response = exchange_on(
417        duplicate(descriptor)?,
418        Request::AnalyzeImage {
419            profile_id: profile_id.to_string(),
420            model_id: model_id.to_string(),
421            image,
422        },
423    )?;
424    response
425        .output
426        .ok_or_else(|| ClientError::Protocol("gateway returned no image analysis".into()))
427}
428
429/// [`cluster_faces`] on the connection `descriptor`; see [`analyze_image_on`].
430///
431/// # Errors
432/// [`ClientError::Unavailable`] when the descriptor cannot be used, else why
433/// the gateway did not answer.
434#[cfg(unix)]
435pub fn cluster_faces_on(
436    descriptor: std::os::fd::BorrowedFd<'_>,
437    profile_id: &str,
438    model_id: &str,
439    images: Vec<FaceImage>,
440) -> Result<String, ClientError> {
441    let response = exchange_on(
442        duplicate(descriptor)?,
443        Request::ClusterFaces {
444            profile_id: profile_id.to_string(),
445            model_id: model_id.to_string(),
446            images,
447        },
448    )?;
449    response
450        .output
451        .ok_or_else(|| ClientError::Protocol("gateway returned no face clusters".into()))
452}
453
454/// The process's one exchange on the launcher channel.
455///
456/// Every RPC duplicates the same connected socket, so the duplicates share
457/// one byte stream, and the gateway answers a connection's requests in the
458/// order they came. Two threads talking at once (a one-shot call beside a
459/// planning turn, two agents of one host) would read each
460/// other's frames: one caller handed another's answer, or a frame split
461/// between two readers. The gateway serves one request at a time anyway,
462/// so taking turns costs no throughput.
463#[cfg(unix)]
464static CHANNEL: std::sync::Mutex<()> = std::sync::Mutex::new(());
465
466#[cfg(unix)]
467thread_local! {
468    /// Whether this thread is in an exchange: a call from inside a stream's
469    /// event callback would otherwise wait on itself forever.
470    static IN_EXCHANGE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
471}
472
473/// This thread's turn on the launcher channel, until dropped.
474#[cfg(unix)]
475struct ChannelTurn {
476    _held: std::sync::MutexGuard<'static, ()>,
477}
478
479#[cfg(unix)]
480impl ChannelTurn {
481    /// Wait for the channel.
482    ///
483    /// # Errors
484    ///
485    /// [`ClientError::Protocol`] when this thread is already in an exchange
486    /// (a call from a stream's event callback): its frames would be read as
487    /// the stream's.
488    fn take() -> Result<Self, ClientError> {
489        if IN_EXCHANGE.get() {
490            return Err(ClientError::Protocol(
491                "a gateway call was made while this thread's call was in progress".into(),
492            ));
493        }
494        // The guard protects no data: a panic mid-exchange leaves nothing
495        // to repair, so a poisoned lock is taken as it is.
496        let held = CHANNEL
497            .lock()
498            .unwrap_or_else(std::sync::PoisonError::into_inner);
499        IN_EXCHANGE.set(true);
500        Ok(Self { _held: held })
501    }
502}
503
504#[cfg(unix)]
505impl Drop for ChannelTurn {
506    fn drop(&mut self) {
507        IN_EXCHANGE.set(false);
508    }
509}
510
511/// Duplicate the launcher-issued service descriptor for one RPC.
512#[cfg(unix)]
513fn service_stream() -> Result<UnixStream, ClientError> {
514    let fd = std::env::var(SERVICE_FD_ENV)
515        .ok()
516        .and_then(|value| value.parse::<RawFd>().ok())
517        .filter(|fd| *fd >= 3 && unsafe { libc::fcntl(*fd, libc::F_GETFD) } != -1)
518        .ok_or(ClientError::Unavailable)?;
519    // SAFETY: F_DUPFD_CLOEXEC duplicates a checked open descriptor; ownership
520    // of the duplicate transfers immediately to UnixStream.
521    let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
522    if duplicate < 0 {
523        return Err(ClientError::Unavailable);
524    }
525    Ok(unsafe { UnixStream::from_raw_fd(duplicate) })
526}
527
528/// Refuse gateway operations when the launcher capability transport is absent.
529///
530/// # Errors
531///
532/// Always returns [`ClientError::Unavailable`]. There is no direct-network or
533/// pathname-socket fallback for an unsupported host.
534#[cfg(not(unix))]
535pub fn request(_request: Request) -> Result<Response, ClientError> {
536    Err(ClientError::Unavailable)
537}
538
539/// Complete a neutral turn, delivering presentation-only deltas followed by
540/// its authoritative response. Deltas never authorize tool execution.
541///
542/// # Errors
543/// Rejects unavailable gateways, provider failures and malformed responses.
544/// Malformed event payloads are rejected after draining the response so the
545/// shared capability channel remains synchronized.
546pub fn complete_streaming(
547    profile_id: &str,
548    model_id: &str,
549    model_request: agent_provider_config::protocol::ModelRequest,
550    timeout: Duration,
551    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
552) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
553    complete_stream(
554        (profile_id, model_id),
555        model_request,
556        timeout,
557        on_event,
558        None,
559    )
560}
561
562/// [`complete_streaming`] for a caller that may stop wanting the answer:
563/// once `stop` says so (it is asked every [`STOP_POLL`] while the turn
564/// runs), the gateway is told to stop the provider call, so
565/// an abandoned turn is not paid for to its end and no longer holds the
566/// process's one gateway channel.
567///
568/// # Errors
569/// As [`complete_streaming`]; a stopped turn fails as
570/// [`ErrorKind::Cancelled`](agent_provider_config::protocol::ErrorKind::Cancelled),
571/// and a gateway that cannot stop calls refuses the turn before any work.
572pub fn complete_streaming_until(
573    profile_id: &str,
574    model_id: &str,
575    model_request: agent_provider_config::protocol::ModelRequest,
576    timeout: Duration,
577    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
578    stop: &(dyn Fn() -> bool + Sync),
579) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
580    complete_stream(
581        (profile_id, model_id),
582        model_request,
583        timeout,
584        on_event,
585        Some(stop),
586    )
587}
588
589fn complete_stream(
590    (profile_id, model_id): (&str, &str),
591    model_request: agent_provider_config::protocol::ModelRequest,
592    timeout: Duration,
593    on_event: &mut dyn FnMut(&agent_provider_config::protocol::StreamEvent),
594    stop: Option<&(dyn Fn() -> bool + Sync)>,
595) -> Result<agent_provider_config::protocol::ModelResponse, ClientError> {
596    let request = Request::Complete {
597        profile_id: profile_id.into(),
598        model_id: model_id.into(),
599        request: model_request,
600        timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
601        stream: true,
602    };
603    let mut invalid = false;
604    let output = streaming_request(
605        request,
606        true,
607        &mut |kind, payload| {
608            // Drain after a malformed event to preserve the shared legacy channel,
609            // but never deliver more deltas from a poisoned turn.
610            if invalid {
611                return;
612            }
613            match transport::decode_event(kind, payload) {
614                Ok(Some(event)) => on_event(&event),
615                Ok(None) => {}
616                Err(_) => invalid = true,
617            }
618        },
619        stop,
620    );
621    let result = if invalid {
622        Err(agent_provider_config::protocol::ModelError::invalid(
623            "invalid gateway stream event",
624        ))
625    } else {
626        output
627            .map_err(|error| error.model_error())
628            .and_then(|output| transport::decode_completion(&output))
629    };
630    transport::finish_stream(result, on_event).map_err(ClientError::Model)
631}
632
633/// How often a stoppable stream asks whether its caller still wants it.
634pub const STOP_POLL: Duration = Duration::from_millis(100);
635
636#[cfg(not(unix))]
637fn streaming_request(
638    _request: Request,
639    _deltas: bool,
640    _on_event: &mut dyn FnMut(&str, &str),
641    _stop: Option<&(dyn Fn() -> bool + Sync)>,
642) -> Result<String, ClientError> {
643    Err(ClientError::Unavailable)
644}
645
646#[cfg(unix)]
647fn streaming_request(
648    request: Request,
649    deltas: bool,
650    on_event: &mut dyn FnMut(&str, &str),
651    stop: Option<&(dyn Fn() -> bool + Sync)>,
652) -> Result<String, ClientError> {
653    let turn = ChannelTurn::take()?;
654    let output = streaming_exchange(request, deltas, on_event, stop);
655    drop(turn);
656    output
657}
658
659/// [`streaming_request`], on this thread's turn of the channel.
660#[cfg(unix)]
661fn streaming_exchange(
662    request: Request,
663    deltas: bool,
664    on_event: &mut dyn FnMut(&str, &str),
665    stop: Option<&(dyn Fn() -> bool + Sync)>,
666) -> Result<String, ClientError> {
667    let mut stream = service_stream()?;
668    let Some(stop) = stop else {
669        write_frame(
670            &mut stream,
671            &Frame {
672                version: RPC_VERSION,
673                value: request,
674            },
675        )?;
676        return read_stream(&mut stream, deltas, on_event, None);
677    };
678    let id = cancellable(&mut stream, request)?;
679    let writer = stream.try_clone().map_err(|error| io_error(&error))?;
680    let watch = StopWatch::default();
681    std::thread::scope(|scope| {
682        // Without a watcher the turn still runs, only unstoppable between
683        // its events.
684        let _ = std::thread::Builder::new()
685            .name("model-gateway-stop".into())
686            .spawn_scoped(scope, || watch.stop_when(stop, id, writer));
687        let output = read_stream(&mut stream, deltas, on_event, Some((&watch, id)));
688        watch.finish();
689        output
690    })
691}
692
693/// Start `request` as a cancellable operation on `stream`, after the
694/// gateway agreed to stop operations: its id.
695#[cfg(unix)]
696fn cancellable(stream: &mut UnixStream, request: Request) -> Result<u64, ClientError> {
697    use agent_provider_config::protocol::{ErrorKind, ModelError};
698    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
699    write_frame(
700        stream,
701        &Frame {
702            version: RPC_VERSION,
703            value: Request::CancellationSupported,
704        },
705    )?;
706    let supported: Response = read_frame(stream)?;
707    if !supported.ok
708        || supported.event.is_some()
709        || supported.output.as_deref() != Some("cancel-v1")
710    {
711        return Err(ClientError::Model(ModelError::new(ErrorKind::Unsupported)));
712    }
713    let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
714    write_frame(
715        stream,
716        &Frame {
717            version: RPC_VERSION,
718            value: Request::Cancellable {
719                id,
720                request: Box::new(request),
721            },
722        },
723    )?;
724    Ok(id)
725}
726
727/// Where a stoppable stream is: over (its answer read), or told to stop.
728#[cfg(unix)]
729#[derive(Default)]
730struct StopWatch {
731    state: std::sync::Mutex<Stopping>,
732    over: std::sync::Condvar,
733}
734
735#[cfg(unix)]
736#[derive(Default)]
737struct Stopping {
738    over: bool,
739    cancelled: bool,
740}
741
742#[cfg(unix)]
743impl StopWatch {
744    /// Until the stream is over, ask `stop` every [`STOP_POLL`]; once it
745    /// says so, tell the gateway to stop operation `id`.
746    fn stop_when(&self, stop: &(dyn Fn() -> bool + Sync), id: u64, mut writer: UnixStream) {
747        let mut state = self
748            .state
749            .lock()
750            .unwrap_or_else(std::sync::PoisonError::into_inner);
751        while !state.over && !stop() {
752            state = self
753                .over
754                .wait_timeout(state, STOP_POLL)
755                .unwrap_or_else(std::sync::PoisonError::into_inner)
756                .0;
757        }
758        if !state.over {
759            // Under the lock: the reader either sees the stream told to
760            // stop, or has taken its answer and this is not sent.
761            state.cancelled = write_frame(
762                &mut writer,
763                &Frame {
764                    version: RPC_VERSION,
765                    value: Request::Cancel { id },
766                },
767            )
768            .is_ok();
769        }
770        drop(state);
771    }
772
773    /// One frame was read; `last` when it is the stream's answer. Whether
774    /// the stream was told to stop, so the frame is not the caller's.
775    fn read(&self, last: bool) -> bool {
776        let mut state = self
777            .state
778            .lock()
779            .unwrap_or_else(std::sync::PoisonError::into_inner);
780        let cancelled = state.cancelled;
781        let over = last && !cancelled;
782        if over {
783            state.over = true;
784        }
785        drop(state);
786        if over {
787            self.over.notify_all();
788        }
789        cancelled
790    }
791
792    /// The stream ended, however it did: the watcher stops.
793    fn finish(&self) {
794        self.state
795            .lock()
796            .unwrap_or_else(std::sync::PoisonError::into_inner)
797            .over = true;
798        self.over.notify_all();
799    }
800}
801
802/// Read a streamed answer's frames from `stream`, delivering its events. A
803/// stoppable stream (`watch`) told to stop reads on, discarding, to the
804/// gateway's acknowledgement, so no frame of it is left on the channel.
805#[cfg(unix)]
806fn read_stream(
807    stream: &mut UnixStream,
808    deltas: bool,
809    on_event: &mut dyn FnMut(&str, &str),
810    watch: Option<(&StopWatch, u64)>,
811) -> Result<String, ClientError> {
812    // A bounded number of intermediate frames: one per completed tool call,
813    // and (only when asked for) a separately bounded number of deltas.
814    let mut calls = 0_usize;
815    let mut delta_frames = 0_usize;
816    let mut stopped = 0_usize;
817    loop {
818        let response: Response = read_frame(stream)?;
819        if let Some((watch, id)) = watch
820            && watch.read(response.event.is_none())
821        {
822            if response.event.is_none()
823                && response.ok
824                && response.output.as_deref() == Some(format!("cancelled:{id}").as_str())
825            {
826                return Err(ClientError::Model(
827                    agent_provider_config::protocol::ModelError::new(
828                        agent_provider_config::protocol::ErrorKind::Cancelled,
829                    ),
830                ));
831            }
832            stopped = stopped.saturating_add(1);
833            if stopped > MAX_STREAM_EVENTS + MAX_DELTA_EVENTS + 1 {
834                let _ = stream.shutdown(std::net::Shutdown::Both);
835                return Err(ClientError::Protocol(
836                    "gateway did not acknowledge the stop".into(),
837                ));
838            }
839            continue;
840        }
841        let response = response.into_result()?;
842        match response.event {
843            Some(event) => {
844                let count = if deltas
845                    && (matches!(
846                        event.as_str(),
847                        EVENT_TOOL_CALL_DELTA | "text_delta" | "reasoning_delta"
848                    )) {
849                    delta_frames = delta_frames.saturating_add(1);
850                    delta_frames > MAX_DELTA_EVENTS
851                } else {
852                    calls = calls.saturating_add(1);
853                    calls > MAX_STREAM_EVENTS
854                };
855                if count {
856                    // Do not leave unread frames on the shared launcher channel.
857                    let _ = stream.shutdown(std::net::Shutdown::Both);
858                    return Err(ClientError::Protocol(
859                        "gateway sent too many streaming events".into(),
860                    ));
861                }
862                on_event(&event, response.output.as_deref().unwrap_or(""));
863            }
864            None => {
865                return response.output.ok_or_else(|| {
866                    ClientError::Protocol("gateway returned no provider response".into())
867                });
868            }
869        }
870    }
871}
872
873/// The most intermediate frames one streamed turn may carry.
874pub const MAX_STREAM_EVENTS: usize = 64;
875
876/// The most `tool_call_delta` frames one streamed turn may carry; bounded
877/// separately from [`MAX_STREAM_EVENTS`]. A gateway stops sending deltas at
878/// this count (the completed `tool_call` events still follow).
879pub const MAX_DELTA_EVENTS: usize = 4096;
880
881/// Send a content-free timing mark. Best effort: a gateway that predates the
882/// verb refuses it, and that refusal is ignored by callers.
883///
884/// # Errors
885///
886/// As [`request`].
887pub fn trace(trace: PlanTrace, event: TraceEvent) -> Result<(), ClientError> {
888    trace_at(trace, event, None)
889}
890
891/// [`trace`] for a mark that happened at `at_unix_ms` and was held back while
892/// a streamed turn used the channel; the gateway logs that time.
893///
894/// # Errors
895///
896/// As [`trace`].
897pub fn trace_at(
898    trace: PlanTrace,
899    event: TraceEvent,
900    at_unix_ms: Option<u64>,
901) -> Result<(), ClientError> {
902    request(Request::Trace {
903        trace,
904        event,
905        at_unix_ms,
906    })
907    .map(|_| ())
908}
909
910/// Request a fixed-schema visual analysis through the launcher-issued gateway
911/// descriptor. This operation can only be authorized for Photos by the
912/// gateway; callers cannot provide a URL, arbitrary prompt, or timeout.
913pub fn analyze_image(
914    profile_id: &str,
915    model_id: &str,
916    image: VisionImage,
917) -> Result<String, ClientError> {
918    let response = request(Request::AnalyzeImage {
919        profile_id: profile_id.to_string(),
920        model_id: model_id.to_string(),
921        image,
922    })?;
923    response
924        .output
925        .ok_or_else(|| ClientError::Protocol("gateway returned no image analysis".into()))
926}
927
928/// Run the dedicated local face model against one bounded batch.  This is not
929/// a generic multimodal request and cannot be redirected to a hosted model.
930pub fn cluster_faces(
931    profile_id: &str,
932    model_id: &str,
933    images: Vec<FaceImage>,
934) -> Result<String, ClientError> {
935    let response = request(Request::ClusterFaces {
936        profile_id: profile_id.to_string(),
937        model_id: model_id.to_string(),
938        images,
939    })?;
940    response
941        .output
942        .ok_or_else(|| ClientError::Protocol("gateway returned no face clusters".into()))
943}
944
945/// Find the subject of one bounded picture with the installed on-device
946/// segmentation model.
947///
948/// # Errors
949///
950/// Returns [`ClientError`] if the launcher gateway is absent, no model is
951/// installed ([`ClientError::Rejected`] with [`NO_SEGMENTATION_MODEL`]), the
952/// picture is refused, or the answer is malformed.
953pub fn segment_subject(image: VisionImage) -> Result<SubjectMatte, ClientError> {
954    let response = request(Request::SegmentSubject { image })?;
955    let output = response
956        .output
957        .ok_or_else(|| ClientError::Protocol("gateway returned no subject".into()))?;
958    serde_json::from_str(&output)
959        .map_err(|error| ClientError::Protocol(format!("malformed subject: {error}")))
960}
961
962/// Write one size-bounded JSON frame to a gateway stream.
963///
964/// # Errors
965///
966/// Returns [`ClientError::Protocol`] when serialization fails or the frame is
967/// too large, and a typed transport/timeout error when writing fails.
968#[cfg(unix)]
969pub fn write_frame<T: Serialize>(stream: &mut UnixStream, value: &T) -> Result<(), ClientError> {
970    let body = Zeroizing::new(
971        serde_json::to_vec(value).map_err(|error| ClientError::Protocol(error.to_string()))?,
972    );
973    FRAMING.write(stream, &body).map_err(|error| match error {
974        wire_frame::FrameError::Io(error) => io_error(&error),
975        _ => ClientError::Protocol("request exceeds gateway frame limit".into()),
976    })?;
977    stream.flush().map_err(|error| io_error(&error))
978}
979
980#[cfg(unix)]
981fn io_error(error: &std::io::Error) -> ClientError {
982    use agent_provider_config::protocol::{ErrorKind, ModelError};
983    ClientError::Model(ModelError::new(match error.kind() {
984        std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock => ErrorKind::TimedOut,
985        _ => ErrorKind::Transport,
986    }))
987}
988
989/// Read and decode one size-bounded JSON frame from a gateway stream.
990///
991/// # Errors
992///
993/// Returns a typed transport/truncation error on stream loss and
994/// [`ClientError::Protocol`] for an invalid length or payload.
995#[cfg(unix)]
996pub fn read_frame<T: for<'a> Deserialize<'a>>(stream: &mut UnixStream) -> Result<T, ClientError> {
997    use agent_provider_config::protocol::{ErrorKind, ModelError};
998    let mut body = Zeroizing::new(Vec::new());
999    match FRAMING.read_into(stream, &mut body) {
1000        Ok(true) => {}
1001        Err(wire_frame::FrameError::TooLarge(_)) => {
1002            return Err(ClientError::Protocol("gateway frame exceeds limit".into()));
1003        }
1004        Ok(false) | Err(wire_frame::FrameError::Truncated | wire_frame::FrameError::Closed) => {
1005            return Err(ClientError::Model(ModelError::new(ErrorKind::Truncated)));
1006        }
1007        Err(wire_frame::FrameError::Io(error)) => return Err(io_error(&error)),
1008        Err(_) => return Err(ClientError::Protocol("invalid gateway frame".into())),
1009    }
1010    serde_json::from_slice(&body)
1011        .map_err(|_| ClientError::Protocol("invalid gateway response".into()))
1012}
1013
1014#[cfg(test)]
1015#[cfg(unix)]
1016mod wire_tests {
1017    use super::*;
1018
1019    /// The gateway socket's bytes: a little-endian `u32` length, then JSON.
1020    #[test]
1021    fn gateway_wire_bytes_are_pinned() {
1022        use std::io::Read as _;
1023        let (mut client, mut gateway) = UnixStream::pair().unwrap();
1024        write_frame(
1025            &mut client,
1026            &Response {
1027                ok: true,
1028                output: Some("x".into()),
1029                configured: None,
1030                error: None,
1031                model_error: None,
1032                event: None,
1033            },
1034        )
1035        .unwrap();
1036        let mut sent = [0_u8; 28];
1037        gateway.read_exact(&mut sent).unwrap();
1038        assert_eq!(sent[..4], [24, 0, 0, 0]);
1039        assert_eq!(&sent[4..], br#"{"ok":true,"output":"x"}"#);
1040
1041        gateway.write_all(&[12, 0, 0, 0]).unwrap();
1042        gateway.write_all(br#"{"ok":false}"#).unwrap();
1043        let response: Response = read_frame(&mut client).unwrap();
1044        assert!(!response.ok);
1045    }
1046
1047    fn answer(output: &str, event: Option<&str>) -> Response {
1048        Response {
1049            ok: true,
1050            output: Some(output.into()),
1051            configured: None,
1052            error: None,
1053            model_error: None,
1054            event: event.map(Into::into),
1055        }
1056    }
1057
1058    tilo_test_env::scenario! {
1059        /// The one launcher channel under a stream, a stop and a nested call. Each case hands the
1060        /// client a socket pair of its own through a scoped environment, and every exchange gives its
1061        /// turn back when it ends, so a case starts with the channel free.
1062        fn calls_on_the_shared_launcher_channel_take_turns_and_stop_cleanly;
1063
1064        phase a_call_beside_a_stream_on_the_shared_channel_gets_its_own_answer;
1065        // A one-shot call runs beside a streamed planning turn, over the one
1066        // launcher channel. A call asked while the turn's caller is still busy
1067        // with one of its events used to read the turn's next frame as its own
1068        // answer, and the turn then read the call's: it now waits its turn, and
1069        // each caller gets its own answer.
1070        {
1071            use std::os::fd::AsRawFd as _;
1072            let (app, mut gateway) = UnixStream::pair().unwrap();
1073            let mut env = tilo_test_env::ScopedEnv::new();
1074            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
1075            let (asked_by, asked) = std::sync::mpsc::channel();
1076            let server = std::thread::spawn(move || {
1077                // The stream: one event, then its answer, written at once, as a
1078                // gateway writes them whenever the provider has them.
1079                let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
1080                assert!(matches!(frame.value, Request::Complete { .. }));
1081                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
1082                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
1083                // Then each one-shot call, answered with what it carried.
1084                while let Ok(frame) = read_frame::<Frame<Request>>(&mut gateway) {
1085                    let _ = asked_by.send(());
1086                    write_frame(&mut gateway, &answer(&echoed(&frame.value), None)).unwrap();
1087                }
1088            });
1089            let (in_event, event_seen) = std::sync::mpsc::channel();
1090            let (go_on, go) = std::sync::mpsc::channel::<()>();
1091            let stream = std::thread::spawn(move || {
1092                streaming_request(
1093                    streamed_turn(),
1094                    false,
1095                    &mut |kind, _| {
1096                        assert_eq!(kind, EVENT_TOOL_CALL);
1097                        // The turn's caller is busy with the event (running the
1098                        // call) while the one-shot call is asked.
1099                        in_event.send(()).unwrap();
1100                        let _ = go.recv_timeout(tilo_test_env::hang_bound());
1101                    },
1102                    None,
1103                )
1104            });
1105            tilo_test_env::recv("the stream's event", &event_seen);
1106            let call = std::thread::spawn(|| one_shot(7));
1107            // Long enough for a call on the channel to have read a frame.
1108            let _ = asked.recv_timeout(Duration::from_millis(300));
1109            std::thread::sleep(Duration::from_millis(100));
1110            go_on.send(()).unwrap();
1111            assert_eq!(stream.join().unwrap().unwrap(), "the plan");
1112            assert_eq!(call.join().unwrap().unwrap(), "7");
1113            drop(env);
1114            drop(app);
1115            server.join().unwrap();
1116        }
1117
1118        phase a_stream_its_caller_gives_up_on_is_stopped_at_the_gateway;
1119        // The agent lets go of a planning turn when its task is stopped. The
1120        // turn used to run to its end at the provider, billed, holding the
1121        // channel: the gateway is now told to stop it, the turn ends as
1122        // cancelled, and the next call on the channel gets its own answer.
1123        {
1124            use std::os::fd::AsRawFd as _;
1125            let (app, gateway) = UnixStream::pair().unwrap();
1126            let mut env = tilo_test_env::ScopedEnv::new();
1127            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
1128            let server = stoppable_gateway(gateway, false);
1129            let (plan, after) = give_up_then_call();
1130            let Err(ClientError::Model(error)) = plan else {
1131                panic!("a stopped turn is cancelled, not answered: {plan:?}");
1132            };
1133            assert_eq!(
1134                error.kind,
1135                agent_provider_config::protocol::ErrorKind::Cancelled
1136            );
1137            assert_eq!(after.unwrap(), "9");
1138            drop(env);
1139            drop(app);
1140            server.join().unwrap();
1141        }
1142
1143        phase a_stop_that_crosses_the_answer_leaves_nothing_on_the_channel;
1144        // The stop can cross the answer: the gateway acknowledges it after
1145        // the answer went out, and that acknowledgement is read here, not
1146        // left on the channel as the next call's answer.
1147        {
1148            use std::os::fd::AsRawFd as _;
1149            let (app, gateway) = UnixStream::pair().unwrap();
1150            let mut env = tilo_test_env::ScopedEnv::new();
1151            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
1152            let server = stoppable_gateway(gateway, true);
1153            let (plan, after) = give_up_then_call();
1154            assert!(
1155                matches!(&plan, Err(ClientError::Model(error)) if error.kind == agent_provider_config::protocol::ErrorKind::Cancelled),
1156                "{plan:?}"
1157            );
1158            assert_eq!(after.unwrap(), "9");
1159            drop(env);
1160            drop(app);
1161            server.join().unwrap();
1162        }
1163
1164        phase a_call_from_inside_a_stream_is_refused_rather_than_waiting_on_itself;
1165        // A call from inside a stream's event callback, on the stream's own
1166        // thread, would read the stream's frames as its answer, and waiting
1167        // for the channel would wait on itself: it is refused instead.
1168        {
1169            use std::os::fd::AsRawFd as _;
1170            let (app, mut gateway) = UnixStream::pair().unwrap();
1171            let mut env = tilo_test_env::ScopedEnv::new();
1172            env.set(SERVICE_FD_ENV, app.as_raw_fd().to_string());
1173            let server = std::thread::spawn(move || {
1174                let _: Frame<Request> = read_frame(&mut gateway).unwrap();
1175                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
1176                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
1177            });
1178            let mut nested = None;
1179            let plan = streaming_request(
1180                streamed_turn(),
1181                false,
1182                &mut |_, _| {
1183                    nested = Some(request(Request::Trace {
1184                        trace: PlanTrace { id: 1, turn: 0 },
1185                        event: TraceEvent::ActionSubmitted,
1186                        at_unix_ms: None,
1187                    }));
1188                },
1189                None,
1190            );
1191            assert_eq!(plan.unwrap(), "the plan");
1192            assert!(matches!(nested, Some(Err(ClientError::Protocol(_)))));
1193            server.join().unwrap();
1194            drop(env);
1195        }
1196    }
1197
1198    /// A streamed neutral turn, as the agent asks for one.
1199    fn streamed_turn() -> Request {
1200        Request::Complete {
1201            profile_id: "hosted".into(),
1202            model_id: "model".into(),
1203            request: agent_provider_config::protocol::Conversation::new("system", "hello")
1204                .request(Vec::new(), 64),
1205            timeout_ms: 1000,
1206            stream: true,
1207        }
1208    }
1209
1210    /// A gateway that streams one event of a cancellable turn, then
1211    /// (when `answers_first`) its answer, and acknowledges the stop it is
1212    /// then sent; afterwards it answers each one-shot call with what it carried.
1213    /// Hands back the id the stop named.
1214    fn stoppable_gateway(
1215        mut gateway: UnixStream,
1216        answers_first: bool,
1217    ) -> std::thread::JoinHandle<u64> {
1218        std::thread::spawn(move || {
1219            gateway
1220                .set_read_timeout(Some(tilo_test_env::hang_bound()))
1221                .unwrap();
1222            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
1223            assert!(matches!(frame.value, Request::CancellationSupported));
1224            write_frame(&mut gateway, &answer("cancel-v1", None)).unwrap();
1225            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
1226            let Request::Cancellable { id, request } = frame.value else {
1227                panic!("a stoppable stream starts a cancellable operation");
1228            };
1229            assert!(matches!(*request, Request::Complete { .. }));
1230            write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
1231            if answers_first {
1232                write_frame(&mut gateway, &answer("the plan", None)).unwrap();
1233            }
1234            let frame: Frame<Request> = read_frame(&mut gateway).unwrap();
1235            let Request::Cancel { id: stopped } = frame.value else {
1236                panic!("the caller stops the operation");
1237            };
1238            if !answers_first {
1239                // A frame the provider produced before the stop arrived.
1240                write_frame(&mut gateway, &answer("{}", Some(EVENT_TOOL_CALL))).unwrap();
1241            }
1242            write_frame(&mut gateway, &answer(&format!("cancelled:{stopped}"), None)).unwrap();
1243            assert_eq!(stopped, id);
1244            while let Ok(frame) = read_frame::<Frame<Request>>(&mut gateway) {
1245                write_frame(&mut gateway, &answer(&echoed(&frame.value), None)).unwrap();
1246            }
1247            stopped
1248        })
1249    }
1250
1251    /// Ask a stoppable turn that its caller gives up on at its first event,
1252    /// then a one-shot call on the same channel.
1253    fn give_up_then_call() -> (Result<String, ClientError>, Result<String, ClientError>) {
1254        let stop = std::sync::atomic::AtomicBool::new(false);
1255        let mut events = 0_usize;
1256        let plan = streaming_request(
1257            streamed_turn(),
1258            false,
1259            &mut |_, _| {
1260                events = events.saturating_add(1);
1261                stop.store(true, std::sync::atomic::Ordering::Relaxed);
1262                // Long enough for the watcher to see it before the answer
1263                // is read.
1264                std::thread::sleep(Duration::from_millis(300));
1265            },
1266            Some(&|| stop.load(std::sync::atomic::Ordering::Relaxed)),
1267        );
1268        assert_eq!(events, 1, "nothing after the stop reaches the caller");
1269        (plan, one_shot(9))
1270    }
1271
1272    /// A one-shot call on the launcher channel, carrying `id`: the fake gateways answer it
1273    /// with that id ([`echoed`]).
1274    fn one_shot(id: u64) -> Result<String, ClientError> {
1275        request(Request::Trace {
1276            trace: PlanTrace { id, turn: 0 },
1277            event: TraceEvent::ActionSubmitted,
1278            at_unix_ms: None,
1279        })
1280        .map(|answered| answered.output.unwrap_or_default())
1281    }
1282
1283    /// What a fake gateway answers a one-shot call with: the id it carried.
1284    fn echoed(asked: &Request) -> String {
1285        let Request::Trace { trace, .. } = asked else {
1286            panic!("only one-shot calls follow the stream");
1287        };
1288        trace.id.to_string()
1289    }
1290}
1291
1292#[cfg(test)]
1293#[cfg(not(unix))]
1294mod unsupported_platform_tests {
1295    use super::*;
1296
1297    #[test]
1298    fn photos_and_secret_operations_require_a_supported_gateway_capability() {
1299        assert!(!available());
1300        assert!(matches!(
1301            analyze_image(
1302                "local",
1303                "vision",
1304                VisionImage {
1305                    media_type: "image/png".into(),
1306                    data_base64: String::new(),
1307                    source_content_hash: String::new(),
1308                }
1309            ),
1310            Err(ClientError::Unavailable)
1311        ));
1312        assert!(matches!(
1313            cluster_faces("local", "faces", Vec::new()),
1314            Err(ClientError::Unavailable)
1315        ));
1316        assert!(matches!(
1317            plan(
1318                "hosted",
1319                "model",
1320                serde_json::Value::Null,
1321                Duration::from_secs(1)
1322            ),
1323            Err(ClientError::Unavailable)
1324        ));
1325    }
1326}
1327
1328#[cfg(test)]
1329mod local_model_tests {
1330    use super::*;
1331
1332    #[test]
1333    fn local_vision_requires_an_immutable_model_revision() {
1334        assert!(is_pinned_revision(&"a".repeat(40)));
1335        assert!(is_pinned_revision(&"b".repeat(64)));
1336        assert!(!is_pinned_revision("main"));
1337        assert!(!is_pinned_revision(&"A".repeat(40)));
1338        assert!(!is_pinned_revision(&"g".repeat(40)));
1339    }
1340}