Skip to main content

weirdnet_agent/remote/infer/
v2.rs

1//! `/weirdnet-agent/infer/2`: remote inference with a queue, jobs, resume and richer frames.
2//!
3//! ```text
4//! asking node                               serving node
5//!   Infer(Request) | Embed(EmbedRequest) | Transcribe(TranscribeRequest) | Speak(SpeakRequest) ->
6//!                                           <- Queued { position } ...   (while waiting for a slot)
7//!                                           <- Accepted { model, attempt, resume }
8//!                                           <- Delta { offset, text } | Reasoning { offset, text }
9//!                                           <- Meta { meta }             (early_meta askers)
10//!                                           <- ToolCall { index, call } | Usage | Embedding | Transcript ...
11//!                                           <- Working ... | SpeechStart { format, .. } | Audio { offset, data } ...
12//!   Cancel { id } ->                        (any time)
13//!                                           <- Done { finish } | Failed { error } | Cancelled
14//! ```
15//!
16//! Messages are CBOR. Infer/1 stays JSON and is served beside this protocol; the two can't
17//! share a stream id because a `/1` server would ignore `assistant_prefix` (and repeat the
18//! prefix) and a `/1` client fails on `Queued`.
19//!
20//! - **Queue:** requests wait in the node's [`Admission`] priority queue. Every change of place,
21//!   and every [`QUEUE_KEEPALIVE`] without one, sends `Queued`; each resets the asker's accept
22//!   timeout, so a queued request is not mistaken for a dead node.
23//! - **Offsets:** every `Delta` carries the number of characters (Unicode scalar values) of the
24//!   answer before it, and every `Reasoning` the same for the reasoning text. A receiver appends
25//!   a frame only where it continues its buffer, so a resumed stream never repeats text.
26//! - **Resume:** a request may carry the `assistant_prefix` already shown. A server whose
27//!   backend honours it ([`InferBackend::resumes`]) says `resume: true` and streams only what
28//!   comes after it, starting at offset = prefix length. Others say `resume: false` and start
29//!   over at 0; askers that need a resume move on.
30//! - **Continue:** the same prefix continues an answer the user stopped or that was cut off
31//!   (assistant prefill; [`Request::continuing`] makes one from a trailing assistant message).
32//!   The wire format is unchanged, so any 0.4 server whose backend resumes can serve it.
33//! - **Tool calls** are sent whole, never half-built.
34//! - **Raw prompts** ([`Input::Prompt`]) are for completions: the model continues the text, with
35//!   no chat template and no tools.
36//! - **Early metadata:** an asker that sets [`Request::early_meta`] may get a `Meta` frame before
37//!   the answer (a cache hit, say); `Done` carries the same metadata for everyone.
38//! - **Raw mode** is for inference node → model node calls: assembled messages only, no context
39//!   lookups, caches or stand-ins.
40//! - **Answer cache:** [`Request::cache`] ([`CacheMode`]) lets an asker skip a node's answer
41//!   cache for one request without raw mode: `bypass` neither reads nor stores, `refresh` skips
42//!   the read and stores the fresh answer. The field is left off the wire when it is `use`, so
43//!   older nodes read the request as before; they don't know the field and may still answer from
44//!   their cache ([`Meta::cache_hit`] says so).
45//! - **Embeddings:** one `Embedding` frame per input, the vector as a CBOR byte string of
46//!   little-endian `f32`.
47//! - **Transcription** (since 0.5.8): a [`TranscribeRequest`] carries one audio clip as a CBOR
48//!   byte string with its format (`wav`, `mp3`, ... as in an `input_audio` part), optional
49//!   language and prompt hints and whether timed segments are wanted. It queues like any request;
50//!   the node answers `Accepted`, `Working` every [`QUEUE_KEEPALIVE`] while the backend runs, one
51//!   `Transcript` frame ([`Transcript`]: the text, the language,
52//!   the audio's length and timed [`Segment`]s when the backend gives them), then `Done` with
53//!   usage and timings. The host serves it through [`InferHost::open_transcribe`] and a
54//!   [`TranscribeBackend`]; an inference node routes it with
55//!   [`Catalog::route_transcribe`](crate::remote::catalog::Catalog::route_transcribe). Nodes
56//!   before 0.5.8 can't read the request and close the stream; the pool reports that as
57//!   `Unsupported` and tries the next node. The whole request must fit in one stream message
58//!   (32 MiB on Weirdnet), so long soundtracks are sent in pieces.
59//! - **Video** (since 0.5.10): a message may carry a whole clip as a
60//!   [`ContentPart::VideoUrl`](crate::model::ContentPart::VideoUrl) (a `data:video/...` URL, the
61//!   `video_url` part in CBOR as in JSON). It needs [`Modalities::VIDEO`]; the pool routes it with
62//!   [`Catalog::route`](crate::remote::catalog::Catalog::route) only to models whose catalog
63//!   entry says `inputs.video`. A node before 0.5.10 can't read such a request and closes the
64//!   stream, which the pool treats like any dropped node. The clip travels inside the request, so
65//!   it must fit in one stream message with everything else.
66//! - **Speech out** (since 0.5.11): a [`SpeakRequest`] carries text ([`SpeakInput::Text`]), a
67//!   multi-speaker script ([`SpeakInput::Script`]) or raw engine input ([`SpeakInput::Raw`]),
68//!   an optional [`Voice`] (a preset, a designed voice, or a voice cloned from a reference clip
69//!   sent as a CBOR byte string, with `consent`), per-speaker voices, instructions, language,
70//!   speed (per mille), seed, format ([`AudioFormat`]), sample rate and whether to stream. The
71//!   node answers `Accepted`, `Working` every [`QUEUE_KEEPALIVE`] until the audio starts, one
72//!   `SpeechStart` (format, and sample rate and channels when known), `Audio` frames of at most
73//!   [`MAX_AUDIO_CHUNK`] bytes in order (each with its byte offset), then `Done` with usage
74//!   ([`Usage::input_chars`], [`Usage::audio_ms`]) and metadata ([`Meta::ignored`] names fields
75//!   the model doesn't use). [`SpeakRequest::check`] refuses empty input, a clone without
76//!   consent and a reference over [`MAX_REFERENCE_BYTES`] before the host opens a backend
77//!   ([`InferHost::open_speak`], a [`SpeakBackend`] returning an [`AudioStream`]); an inference
78//!   node routes with [`Catalog::route_speak`](crate::remote::catalog::Catalog::route_speak).
79//!   The pool fails over to another node only before `SpeechStart`: once audio has left, a
80//!   failure is final (another node would speak with another voice draw). Nodes before 0.5.11
81//!   can't read the request and close the stream, which the pool treats as `Unsupported`.
82
83use std::pin::pin;
84use std::sync::Arc;
85use std::time::Duration;
86
87use tokio::time::Instant;
88
89use async_trait::async_trait;
90use serde::{Deserialize, Serialize};
91use serde_json::Value;
92use tokio::sync::mpsc;
93
94use super::queue::{Admission, Turn};
95use super::{InferHost, model_error};
96use crate::cancel::CancelToken;
97use crate::model::{DeltaSink, Message, Modalities, ModelBackend, Role, ToolCall};
98use crate::remote::{Caller, Channel, RemoteError, bytes, request_id};
99use crate::session::AgentEvent;
100use crate::speech::{AudioFormat, SpeechNeeds};
101use crate::tool::ToolSpec;
102
103/// Stream protocol id.
104pub const PROTOCOL: &str = "/weirdnet-agent/infer/2";
105
106/// How often a waiting request hears its place again when it has not changed.
107pub const QUEUE_KEEPALIVE: Duration = Duration::from_secs(3);
108
109/// Scheduling class: `interactive` before `batch` before `background` (prefix warming,
110/// re-placement). Classes never preempt a running request.
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
112#[serde(rename_all = "snake_case")]
113#[non_exhaustive]
114pub enum Priority {
115    #[default]
116    Interactive,
117    Batch,
118    Background,
119}
120
121/// Whether a node's answer cache may serve or keep this request's answer.
122#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum CacheMode {
126    /// Read and store as the cache sees fit.
127    #[default]
128    Use,
129    /// Neither read nor store: always run the model (evals, fresh weights).
130    Bypass,
131    /// Skip the read, run the model and store the fresh answer over the old one.
132    Refresh,
133}
134
135impl CacheMode {
136    pub fn is_use(&self) -> bool {
137        *self == CacheMode::Use
138    }
139
140    /// A stored answer may stand in for the model.
141    pub fn may_read(&self) -> bool {
142        *self == CacheMode::Use
143    }
144
145    /// The finished answer may be kept.
146    pub fn may_store(&self) -> bool {
147        matches!(self, CacheMode::Use | CacheMode::Refresh)
148    }
149}
150
151/// A conversation kept by the inference node (synced context), instead of inline messages.
152#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct ContextRef {
155    pub conversation: String,
156    /// The conversation head the answer follows; `None`: the latest.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub head: Option<String>,
159}
160
161impl ContextRef {
162    pub fn new(conversation: impl Into<String>, head: Option<String>) -> Self {
163        Self { conversation: conversation.into(), head }
164    }
165}
166
167/// What the model answers.
168#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
169#[serde(rename_all = "snake_case")]
170#[non_exhaustive]
171pub enum Input {
172    /// Fully assembled messages.
173    Messages(Vec<Message>),
174    /// A conversation the serving node holds.
175    Context(ContextRef),
176    /// A raw text prompt the model continues (OpenAI `/v1/completions`); no chat template,
177    /// no tools. Servers older than 0.4.1 can't read it and close the stream.
178    Prompt(String),
179}
180
181impl Default for Input {
182    fn default() -> Self {
183        Input::Messages(Vec::new())
184    }
185}
186
187/// The part of the answer already shown, for resume. Lengths are in characters.
188#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
189#[non_exhaustive]
190pub struct Prefix {
191    pub text: String,
192    pub len: u64,
193    #[serde(default, skip_serializing_if = "String::is_empty")]
194    pub reasoning: String,
195    #[serde(default)]
196    pub reasoning_len: u64,
197}
198
199impl Prefix {
200    pub fn new(text: impl Into<String>, reasoning: impl Into<String>) -> Self {
201        let (text, reasoning) = (text.into(), reasoning.into());
202        Self { len: chars(&text), reasoning_len: chars(&reasoning), text, reasoning }
203    }
204
205    /// The lengths match the texts.
206    pub fn is_consistent(&self) -> bool {
207        self.len == chars(&self.text) && self.reasoning_len == chars(&self.reasoning)
208    }
209
210    pub fn is_empty(&self) -> bool {
211        self.text.is_empty() && self.reasoning.is_empty()
212    }
213}
214
215/// Characters (Unicode scalar values) in `s`, the unit of offsets.
216pub fn chars(s: &str) -> u64 {
217    s.chars().count() as u64
218}
219
220/// Sampling settings; `None` leaves the backend's default.
221#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
222#[non_exhaustive]
223pub struct Sampling {
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub temperature: Option<f32>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub top_p: Option<f32>,
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub top_k: Option<u32>,
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub min_p: Option<f32>,
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    pub max_tokens: Option<u32>,
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub stop: Vec<String>,
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub presence_penalty: Option<f32>,
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub frequency_penalty: Option<f32>,
240    #[serde(default, skip_serializing_if = "Option::is_none")]
241    pub repeat_penalty: Option<f32>,
242}
243
244/// The shape of the answer.
245#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
246#[serde(rename_all = "snake_case")]
247#[non_exhaustive]
248pub enum ResponseFormat {
249    Text,
250    /// Any JSON object.
251    Json,
252    /// JSON matching a schema.
253    JsonSchema {
254        name: String,
255        schema: Value,
256        #[serde(default)]
257        strict: bool,
258    },
259}
260
261/// One model turn to run on an infer/2 node.
262#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
263#[non_exhaustive]
264pub struct Request {
265    /// This attempt's id on the stream.
266    pub id: String,
267    /// Stable across attempts and nodes (the idempotency key of a job).
268    pub job_id: String,
269    /// 0 for the first try, then one more per retry or resume.
270    #[serde(default)]
271    pub attempt: u32,
272    /// The model wanted, by the serving app's id (`None`: the node's default).
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub model: Option<String>,
275    #[serde(default)]
276    pub priority: Priority,
277    pub input: Input,
278    /// Text already shown, to continue from (see [`Prefix`]).
279    #[serde(default, skip_serializing_if = "Option::is_none")]
280    pub assistant_prefix: Option<Prefix>,
281    #[serde(default)]
282    pub sampling: Sampling,
283    #[serde(default, skip_serializing_if = "Option::is_none")]
284    pub seed: Option<u64>,
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub response_format: Option<ResponseFormat>,
287    #[serde(default, skip_serializing_if = "Vec::is_empty")]
288    pub tools: Vec<ToolSpec>,
289    /// Inference node → model node: assembled messages only, no context lookups, caches or
290    /// stand-ins.
291    #[serde(default)]
292    pub raw: bool,
293    /// Wait for the requested model to load rather than take a stand-in.
294    #[serde(default)]
295    pub wait_for_model: bool,
296    /// The certificate the asker presents (for Weirdnet a CBOR `NodeCert`), checked by the host
297    /// against the transport peer.
298    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
299    pub cert: Option<Vec<u8>>,
300    /// The asker reads [`ServerFrame::Meta`] (0.4.1 and later), so the server may send response
301    /// metadata it knows before the answer, such as a cache hit. Servers that predate it ignore
302    /// the flag; askers that don't set it never get the frame.
303    #[serde(default, skip_serializing_if = "is_false")]
304    pub early_meta: bool,
305    /// Answer cache use (0.5.1 and later; see [`CacheMode`]). Not sent when `use`; nodes that
306    /// predate it ignore it.
307    #[serde(default, skip_serializing_if = "CacheMode::is_use")]
308    pub cache: CacheMode,
309    /// How strongly a LoRA adapter applies for this request, when `model` names one on an engine
310    /// that scales adapters per request (llama.cpp). `None`: the adapter's configured scale.
311    /// Ignored for base models. Not sent when `None`; nodes that predate it (0.5.1 and earlier)
312    /// ignore it.
313    #[serde(default, skip_serializing_if = "Option::is_none")]
314    pub adapter_scale: Option<f32>,
315}
316
317fn is_false(b: &bool) -> bool {
318    !*b
319}
320
321impl Request {
322    /// A request over assembled messages, with a fresh id and job id.
323    pub fn messages(messages: Vec<Message>) -> Self {
324        Self::with_input(Input::Messages(messages))
325    }
326
327    /// A request over a conversation the serving node holds.
328    pub fn context(context: ContextRef) -> Self {
329        Self::with_input(Input::Context(context))
330    }
331
332    /// A request over a raw text prompt (see [`Input::Prompt`]).
333    pub fn prompt(prompt: impl Into<String>) -> Self {
334        Self::with_input(Input::Prompt(prompt.into()))
335    }
336
337    fn with_input(input: Input) -> Self {
338        let id = request_id();
339        Self { job_id: id.clone(), id, input, ..Default::default() }
340    }
341
342    pub fn with_model(mut self, model: impl Into<String>) -> Self {
343        self.model = Some(model.into());
344        self
345    }
346
347    pub fn with_priority(mut self, priority: Priority) -> Self {
348        self.priority = priority;
349        self
350    }
351
352    pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
353        self.tools = tools;
354        self
355    }
356
357    pub fn with_sampling(mut self, sampling: Sampling) -> Self {
358        self.sampling = sampling;
359        self
360    }
361
362    pub fn with_seed(mut self, seed: u64) -> Self {
363        self.seed = Some(seed);
364        self
365    }
366
367    pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
368        self.response_format = Some(format);
369        self
370    }
371
372    pub fn with_job_id(mut self, job_id: impl Into<String>) -> Self {
373        self.job_id = job_id.into();
374        self
375    }
376
377    pub fn with_prefix(mut self, prefix: Prefix) -> Self {
378        self.assistant_prefix = Some(prefix);
379        self
380    }
381
382    /// Continue the last assistant message: a trailing assistant message with no tool calls
383    /// moves into `assistant_prefix` (prefill), so the model carries on from its text. Only
384    /// nodes that say `resume: true` take such a request; others answer `Unsupported`. A
385    /// request that ends any other way is returned unchanged.
386    pub fn continuing(mut self) -> Self {
387        if let Input::Messages(m) = &mut self.input
388            && m.last().is_some_and(|last| last.role == Role::Assistant && last.tool_calls.is_empty() && last.content.as_text().is_some())
389            && let Some(last) = m.pop()
390        {
391            self.assistant_prefix = Some(Prefix::new(last.content.into_text(), ""));
392        }
393        self
394    }
395
396    pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
397        self.cert = Some(cert);
398        self
399    }
400
401    /// How the serving node's answer cache treats this request (see [`CacheMode`]).
402    pub fn with_cache(mut self, cache: CacheMode) -> Self {
403        self.cache = cache;
404        self
405    }
406
407    /// Applies the requested LoRA adapter at `scale` for this request (see
408    /// [`Request::adapter_scale`]).
409    pub fn with_adapter_scale(mut self, scale: f32) -> Self {
410        self.adapter_scale = Some(scale);
411        self
412    }
413
414    /// Wait for the requested model to load rather than take a stand-in.
415    pub fn with_wait_for_model(mut self, wait: bool) -> Self {
416        self.wait_for_model = wait;
417        self
418    }
419
420    /// Raw mode (inference node → model node).
421    pub fn raw(mut self) -> Self {
422        self.raw = true;
423        self
424    }
425
426    /// Inline messages, if the input is not a context reference.
427    pub fn inline_messages(&self) -> Option<&[Message]> {
428        match &self.input {
429            Input::Messages(m) => Some(m),
430            _ => None,
431        }
432    }
433
434    /// What a model needs to read the inline messages: [`Modalities::TEXT`] unless some carry
435    /// images, audio or video. Context references and raw prompts are text.
436    pub fn needs(&self) -> Modalities {
437        self.inline_messages().map(crate::model::needs).unwrap_or(Modalities::TEXT)
438    }
439
440    /// The raw prompt, if the input is one.
441    pub fn raw_prompt(&self) -> Option<&str> {
442        match &self.input {
443            Input::Prompt(p) => Some(p),
444            _ => None,
445        }
446    }
447
448    /// The next attempt: same job, a new id, `attempt + 1`.
449    pub fn next_attempt(&self) -> Self {
450        Self { id: request_id(), attempt: self.attempt + 1, ..self.clone() }
451    }
452}
453
454/// Embeddings for a list of inputs.
455#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
456#[non_exhaustive]
457pub struct EmbedRequest {
458    pub id: String,
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub model: Option<String>,
461    pub inputs: Vec<String>,
462    #[serde(default)]
463    pub priority: Priority,
464    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
465    pub cert: Option<Vec<u8>>,
466}
467
468impl EmbedRequest {
469    pub fn new(inputs: Vec<String>) -> Self {
470        Self { id: request_id(), inputs, ..Default::default() }
471    }
472
473    pub fn with_model(mut self, model: impl Into<String>) -> Self {
474        self.model = Some(model.into());
475        self
476    }
477
478    pub fn with_priority(mut self, priority: Priority) -> Self {
479        self.priority = priority;
480        self
481    }
482}
483
484/// Speech to text for one audio clip (since 0.5.8). The audio travels as raw bytes (a CBOR byte
485/// string), not base64.
486#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
487#[non_exhaustive]
488pub struct TranscribeRequest {
489    pub id: String,
490    /// A speech-to-text model by the serving app's id (`None`: the node picks its transcriber).
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub model: Option<String>,
493    /// The encoded audio.
494    #[serde(with = "bytes")]
495    pub audio: Vec<u8>,
496    /// Its format, as in an `input_audio` part: `wav`, `mp3`, `flac`, `ogg`, ...
497    pub format: String,
498    /// The spoken language (ISO 639-1, such as `en`), if the asker knows it; otherwise the model
499    /// detects it.
500    #[serde(default, skip_serializing_if = "Option::is_none")]
501    pub language: Option<String>,
502    /// Text to guide the transcript (names, terms, the previous piece's ending), as OpenAI's
503    /// `prompt`. Backends that take none ignore it.
504    #[serde(default, skip_serializing_if = "Option::is_none")]
505    pub prompt: Option<String>,
506    /// Ask for timed [`Segment`]s. Backends that can't time the text return none.
507    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
508    pub timestamps: bool,
509    #[serde(default)]
510    pub priority: Priority,
511    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
512    pub cert: Option<Vec<u8>>,
513}
514
515impl TranscribeRequest {
516    /// `audio` encoded as `format` (`wav`, `mp3`, ...).
517    pub fn new(audio: Vec<u8>, format: impl Into<String>) -> Self {
518        Self { id: request_id(), audio, format: format.into(), ..Default::default() }
519    }
520
521    pub fn with_model(mut self, model: impl Into<String>) -> Self {
522        self.model = Some(model.into());
523        self
524    }
525
526    /// The spoken language (ISO 639-1, such as `en`).
527    pub fn with_language(mut self, language: impl Into<String>) -> Self {
528        self.language = Some(language.into());
529        self
530    }
531
532    /// Text to guide the transcript.
533    pub fn with_prompt(mut self, prompt: impl Into<String>) -> Self {
534        self.prompt = Some(prompt.into());
535        self
536    }
537
538    /// Ask for timed segments.
539    pub fn with_timestamps(mut self, timestamps: bool) -> Self {
540        self.timestamps = timestamps;
541        self
542    }
543
544    pub fn with_priority(mut self, priority: Priority) -> Self {
545        self.priority = priority;
546        self
547    }
548
549    /// `BadRequest` unless there is audio and a format. The server checks this before the host
550    /// opens a backend.
551    pub fn check(&self) -> Result<(), RemoteError> {
552        if self.audio.is_empty() {
553            return Err(RemoteError::BadRequest { message: "a transcription request needs audio".into() });
554        }
555        if self.format.trim().is_empty() {
556            return Err(RemoteError::BadRequest { message: "a transcription request needs the audio format (wav, mp3, ...)".into() });
557        }
558        Ok(())
559    }
560}
561
562/// A transcript: the text, and what the backend knows about it.
563#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
564#[non_exhaustive]
565pub struct Transcript {
566    /// The whole text.
567    pub text: String,
568    /// The spoken language (ISO 639-1), when the backend says.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub language: Option<String>,
571    /// The audio's length in milliseconds, when the backend says.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub duration_ms: Option<u64>,
574    /// Timed pieces of the text, in order, when asked for and the backend can time them.
575    #[serde(default, skip_serializing_if = "Vec::is_empty")]
576    pub segments: Vec<Segment>,
577}
578
579impl Transcript {
580    pub fn new(text: impl Into<String>) -> Self {
581        Self { text: text.into(), ..Default::default() }
582    }
583
584    pub fn with_language(mut self, language: impl Into<String>) -> Self {
585        self.language = Some(language.into());
586        self
587    }
588
589    pub fn with_duration_ms(mut self, duration_ms: u64) -> Self {
590        self.duration_ms = Some(duration_ms);
591        self
592    }
593
594    pub fn with_segments(mut self, segments: Vec<Segment>) -> Self {
595        self.segments = segments;
596        self
597    }
598}
599
600/// A timed piece of a [`Transcript`], in milliseconds from the start of the audio.
601#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
602#[non_exhaustive]
603pub struct Segment {
604    pub start_ms: u64,
605    pub end_ms: u64,
606    pub text: String,
607}
608
609impl Segment {
610    pub fn new(start_ms: u64, end_ms: u64, text: impl Into<String>) -> Self {
611        Self { start_ms, end_ms, text: text.into() }
612    }
613}
614
615/// Largest reference clip a [`SpeakRequest`] may carry (30 MiB), checked before any backend
616/// opens. A model's [`SpeechProfile::max_reference_bytes`](crate::speech::SpeechProfile::max_reference_bytes) may be smaller. Since 0.5.11.
617pub const MAX_REFERENCE_BYTES: usize = 30 << 20;
618
619/// Largest [`ServerFrame::Audio`] chunk (256 KiB); the server splits bigger pieces. Since 0.5.11.
620pub const MAX_AUDIO_CHUNK: usize = 256 << 10;
621
622/// What a [`SpeakRequest`] speaks (since 0.5.11).
623#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
624#[serde(rename_all = "snake_case")]
625#[non_exhaustive]
626pub enum SpeakInput {
627    /// Plain text in the model's chat-free speech template.
628    Text(String),
629    /// A multi-speaker script, turn by turn (needs [`SpeechProfile::script_speakers`](crate::speech::SpeechProfile::script_speakers) above the
630    /// highest speaker number).
631    Script(Vec<ScriptTurn>),
632    /// Passed to the engine as is, with no template (phonemes for Kokoro, say; needs
633    /// [`SpeechProfile::raw`](crate::speech::SpeechProfile::raw)).
634    Raw(String),
635}
636
637impl Default for SpeakInput {
638    fn default() -> Self {
639        SpeakInput::Text(String::new())
640    }
641}
642
643impl SpeakInput {
644    /// Characters (Unicode scalar values) of input: the text, or the turns' text.
645    pub fn chars(&self) -> u64 {
646        match self {
647            SpeakInput::Text(t) | SpeakInput::Raw(t) => chars(t),
648            SpeakInput::Script(turns) => turns.iter().map(|t| chars(&t.text)).sum(),
649        }
650    }
651
652    /// The highest speaker number of a script; `None` for text or raw input.
653    pub fn highest_speaker(&self) -> Option<u8> {
654        match self {
655            SpeakInput::Script(turns) => turns.iter().map(|t| t.speaker).max(),
656            _ => None,
657        }
658    }
659}
660
661/// One turn of a multi-speaker script (since 0.5.11).
662#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
663#[non_exhaustive]
664pub struct ScriptTurn {
665    /// The speaker number, from 0.
666    pub speaker: u8,
667    pub text: String,
668}
669
670impl ScriptTurn {
671    pub fn new(speaker: u8, text: impl Into<String>) -> Self {
672        Self { speaker, text: text.into() }
673    }
674}
675
676/// The voice to speak with (since 0.5.11). Absent from a request: the model's default voice.
677#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
678#[serde(rename_all = "snake_case")]
679#[non_exhaustive]
680pub enum Voice {
681    /// One of the model's preset voices ([`SpeechProfile::presets`](crate::speech::SpeechProfile::presets)); any other name is refused
682    /// with the list, never mapped to another voice.
683    Preset { name: String },
684    /// A voice designed from a description (needs [`SpeechProfile::design`](crate::speech::SpeechProfile::design)).
685    Design { description: String },
686    /// A voice cloned from a reference clip (needs [`SpeechProfile::clone`](crate::speech::SpeechProfile::clone)). The clip travels
687    /// as a CBOR byte string, lives in memory for this request only and is never stored or
688    /// logged. `consent` must be true: the asker confirms the voice is theirs or they have
689    /// permission to use it.
690    Clone {
691        #[serde(with = "bytes")]
692        audio: Vec<u8>,
693        /// The clip's format, as in an `input_audio` part: `wav`, `mp3`, `flac`, ...
694        format: String,
695        /// What the clip says, for models that use it ([`CloneMode`](crate::speech::CloneMode)).
696        #[serde(default, skip_serializing_if = "Option::is_none")]
697        text: Option<String>,
698        #[serde(default)]
699        consent: bool,
700    },
701}
702
703impl Voice {
704    pub fn preset(name: impl Into<String>) -> Self {
705        Voice::Preset { name: name.into() }
706    }
707
708    pub fn design(description: impl Into<String>) -> Self {
709        Voice::Design { description: description.into() }
710    }
711
712    /// A cloned voice from `audio` in `format`, with `consent` as the asker gave it.
713    pub fn clone_from(audio: Vec<u8>, format: impl Into<String>, text: Option<String>, consent: bool) -> Self {
714        Voice::Clone { audio, format: format.into(), text, consent }
715    }
716}
717
718/// The voice for one speaker of a script (since 0.5.11).
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
720#[non_exhaustive]
721pub struct SpeakerVoice {
722    pub speaker: u8,
723    pub voice: Voice,
724}
725
726impl SpeakerVoice {
727    pub fn new(speaker: u8, voice: Voice) -> Self {
728        Self { speaker, voice }
729    }
730}
731
732/// Text to speech (infer/2 `Speak`, since 0.5.11): text or a script, the voice, and how the audio
733/// should come back. Nothing in it is cached, logged or stored by a node.
734#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
735#[non_exhaustive]
736pub struct SpeakRequest {
737    pub id: String,
738    /// A speaking model by the serving app's id (`None`: the node picks a speaker that covers
739    /// the request).
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub model: Option<String>,
742    pub input: SpeakInput,
743    /// The voice (for a script: the voice of speakers without their own). `None`: the model's
744    /// default.
745    #[serde(default, skip_serializing_if = "Option::is_none")]
746    pub voice: Option<Voice>,
747    /// Per-speaker voices for a script, at most one per speaker.
748    #[serde(default, skip_serializing_if = "Vec::is_empty")]
749    pub voices: Vec<SpeakerVoice>,
750    /// Style or emotion for the chosen voice (needs [`SpeechProfile::instructions`](crate::speech::SpeechProfile::instructions)).
751    #[serde(default, skip_serializing_if = "Option::is_none")]
752    pub instructions: Option<String>,
753    /// The language (ISO 639-1 or one of the engine's codes in [`SpeechProfile::languages`](crate::speech::SpeechProfile::languages)).
754    #[serde(default, skip_serializing_if = "Option::is_none")]
755    pub language: Option<String>,
756    /// Speaking speed in per mille of the model's pace (1000 = as is, 1200 = 20 % faster; needs
757    /// [`SpeechProfile::speed`](crate::speech::SpeechProfile::speed)). Per mille so the request keeps `Eq`.
758    #[serde(default, skip_serializing_if = "Option::is_none")]
759    pub speed: Option<u32>,
760    #[serde(default, skip_serializing_if = "Option::is_none")]
761    pub seed: Option<u64>,
762    /// The output format (`None`: the model's default, the first of
763    /// [`SpeechProfile::formats`](crate::speech::SpeechProfile::formats)).
764    #[serde(default, skip_serializing_if = "Option::is_none")]
765    pub format: Option<AudioFormat>,
766    /// The output sample rate in Hz (`None`: the model's own).
767    #[serde(default, skip_serializing_if = "Option::is_none")]
768    pub sample_rate: Option<u32>,
769    /// Send audio as the engine makes it (when it streams); otherwise the finished file comes in
770    /// chunks.
771    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
772    pub stream: bool,
773    #[serde(default)]
774    pub priority: Priority,
775    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
776    pub cert: Option<Vec<u8>>,
777}
778
779impl SpeakRequest {
780    /// Speak `text` in the model's default voice.
781    pub fn text(text: impl Into<String>) -> Self {
782        Self::with_input(SpeakInput::Text(text.into()))
783    }
784
785    /// Speak a multi-speaker script.
786    pub fn script(turns: Vec<ScriptTurn>) -> Self {
787        Self::with_input(SpeakInput::Script(turns))
788    }
789
790    /// Pass `input` to the engine with no template ([`SpeakInput::Raw`]).
791    pub fn raw(input: impl Into<String>) -> Self {
792        Self::with_input(SpeakInput::Raw(input.into()))
793    }
794
795    /// A request for `input` with a fresh id.
796    pub fn with_input(input: SpeakInput) -> Self {
797        Self { id: request_id(), input, ..Default::default() }
798    }
799
800    pub fn with_model(mut self, model: impl Into<String>) -> Self {
801        self.model = Some(model.into());
802        self
803    }
804
805    pub fn with_voice(mut self, voice: Voice) -> Self {
806        self.voice = Some(voice);
807        self
808    }
809
810    /// The voice of one speaker of a script (replacing one set before for that speaker).
811    pub fn with_speaker_voice(mut self, speaker: u8, voice: Voice) -> Self {
812        self.voices.retain(|v| v.speaker != speaker);
813        self.voices.push(SpeakerVoice::new(speaker, voice));
814        self
815    }
816
817    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
818        self.instructions = Some(instructions.into());
819        self
820    }
821
822    pub fn with_language(mut self, language: impl Into<String>) -> Self {
823        self.language = Some(language.into());
824        self
825    }
826
827    /// Speed in per mille of the model's pace (1000 = as is).
828    pub fn with_speed(mut self, per_mille: u32) -> Self {
829        self.speed = Some(per_mille);
830        self
831    }
832
833    pub fn with_seed(mut self, seed: u64) -> Self {
834        self.seed = Some(seed);
835        self
836    }
837
838    pub fn with_format(mut self, format: AudioFormat) -> Self {
839        self.format = Some(format);
840        self
841    }
842
843    pub fn with_sample_rate(mut self, hz: u32) -> Self {
844        self.sample_rate = Some(hz);
845        self
846    }
847
848    pub fn with_stream(mut self, stream: bool) -> Self {
849        self.stream = stream;
850        self
851    }
852
853    pub fn with_priority(mut self, priority: Priority) -> Self {
854        self.priority = priority;
855        self
856    }
857
858    pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
859        self.cert = Some(cert);
860        self
861    }
862
863    /// Every voice in the request: the voice, then the per-speaker voices.
864    pub fn all_voices(&self) -> impl Iterator<Item = &Voice> {
865        self.voice.iter().chain(self.voices.iter().map(|v| &v.voice))
866    }
867
868    /// Whether any voice is cloned from a reference clip.
869    pub fn clones(&self) -> bool {
870        self.all_voices().any(|v| matches!(v, Voice::Clone { .. }))
871    }
872
873    /// `BadRequest` for a request no model could serve: empty input (or an empty script turn),
874    /// per-speaker voices without a script or twice for one speaker, an empty preset name,
875    /// description or reference format, a reference clip that is empty, over
876    /// [`MAX_REFERENCE_BYTES`] or without `consent`, or a speed of 0. The server checks this
877    /// before the host opens a backend; the backend then checks the request against its profile.
878    pub fn check(&self) -> Result<(), RemoteError> {
879        let bad = |m: &str| Err(RemoteError::BadRequest { message: m.to_string() });
880        match &self.input {
881            SpeakInput::Text(t) | SpeakInput::Raw(t) if t.trim().is_empty() => return bad("a speech request needs text to speak"),
882            SpeakInput::Script(turns) if turns.is_empty() => return bad("a speech script needs at least one turn"),
883            SpeakInput::Script(turns) if turns.iter().any(|t| t.text.trim().is_empty()) => return bad("every turn of a speech script needs text"),
884            _ => {}
885        }
886        if !self.voices.is_empty() && !matches!(self.input, SpeakInput::Script(_)) {
887            return bad("per-speaker voices need a script input");
888        }
889        let mut seen = std::collections::BTreeSet::new();
890        if let Some(v) = self.voices.iter().find(|v| !seen.insert(v.speaker)) {
891            return Err(RemoteError::BadRequest { message: format!("speaker {} has more than one voice", v.speaker) });
892        }
893        for voice in self.all_voices() {
894            match voice {
895                Voice::Preset { name } if name.trim().is_empty() => return bad("a preset voice needs a name"),
896                Voice::Design { description } if description.trim().is_empty() => return bad("a designed voice needs a description"),
897                Voice::Clone { audio, format, consent, .. } => {
898                    if !consent {
899                        return bad("cloning a voice needs consent: confirm the voice is yours or you have permission to use it");
900                    }
901                    if audio.is_empty() {
902                        return bad("cloning a voice needs a reference clip");
903                    }
904                    if audio.len() > MAX_REFERENCE_BYTES {
905                        return Err(RemoteError::BadRequest {
906                            message: format!("the reference clip is {} bytes, over the {MAX_REFERENCE_BYTES}-byte limit", audio.len()),
907                        });
908                    }
909                    if format.trim().is_empty() {
910                        return bad("a reference clip needs its format (wav, mp3, ...)");
911                    }
912                }
913                _ => {}
914            }
915        }
916        if self.speed == Some(0) {
917            return bad("a speaking speed of 0 is not a speed (1000 is the model's pace)");
918        }
919        if self.sample_rate == Some(0) {
920            return bad("a sample rate of 0 Hz is not a rate");
921        }
922        Ok(())
923    }
924
925    /// What the request needs from a model's [`SpeechProfile`](crate::speech::SpeechProfile), for
926    /// [`SpeechProfile::covers`](crate::speech::SpeechProfile::covers) and
927    /// [`Catalog::route_speak`](crate::remote::catalog::Catalog::route_speak). A reference
928    /// clip's length is read from WAV headers; other formats leave it to the engine.
929    pub fn needs(&self) -> SpeechNeeds {
930        let mut n = SpeechNeeds::new().with_input_chars(self.input.chars().min(u64::from(u32::MAX)) as u32);
931        for voice in self.all_voices() {
932            n = match voice {
933                Voice::Preset { name } => n.with_preset(name.clone()),
934                Voice::Design { .. } => n.with_design(),
935                Voice::Clone { audio, format, text, .. } => {
936                    let ms = if format.eq_ignore_ascii_case("wav") { crate::speech::wav_duration_ms(audio) } else { None };
937                    n.with_clone(text.as_deref().is_some_and(|t| !t.trim().is_empty())).with_reference(audio.len() as u64, ms)
938                }
939            };
940        }
941        if let Some(h) = self.input.highest_speaker() {
942            n = n.with_script(h);
943        }
944        if matches!(self.input, SpeakInput::Raw(_)) {
945            n = n.with_raw();
946        }
947        if self.instructions.as_deref().is_some_and(|i| !i.trim().is_empty()) {
948            n = n.with_instructions();
949        }
950        if self.speed.is_some_and(|s| s != 1000) {
951            n = n.with_speed();
952        }
953        if let Some(f) = self.format {
954            n = n.with_format(f);
955        }
956        n
957    }
958}
959
960/// Token counts.
961#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
962#[non_exhaustive]
963pub struct Usage {
964    pub prompt_tokens: u64,
965    pub completion_tokens: u64,
966    #[serde(default)]
967    pub reasoning_tokens: u64,
968    /// Prompt tokens served from a prefix cache.
969    #[serde(default)]
970    pub cached_tokens: u64,
971    /// Characters of input spoken ([`SpeakRequest`]). Since 0.5.11; left off the wire when 0.
972    #[serde(default, skip_serializing_if = "is_zero")]
973    pub input_chars: u64,
974    /// Milliseconds of audio produced ([`SpeakRequest`]). Since 0.5.11; left off the wire when 0.
975    #[serde(default, skip_serializing_if = "is_zero")]
976    pub audio_ms: u64,
977}
978
979fn is_zero(n: &u64) -> bool {
980    *n == 0
981}
982
983impl Usage {
984    pub fn new(prompt_tokens: u64, completion_tokens: u64) -> Self {
985        Self { prompt_tokens, completion_tokens, ..Default::default() }
986    }
987
988    /// Speech usage: characters spoken and milliseconds of audio made (since 0.5.11).
989    pub fn speech(input_chars: u64, audio_ms: u64) -> Self {
990        Self { input_chars, audio_ms, ..Default::default() }
991    }
992}
993
994/// Where time went, in milliseconds.
995#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
996#[non_exhaustive]
997pub struct Timings {
998    /// Waiting in the queue.
999    pub queued_ms: u64,
1000    /// From acceptance to the first text or reasoning.
1001    #[serde(default, skip_serializing_if = "Option::is_none")]
1002    pub first_token_ms: Option<u64>,
1003    /// From the request to the end.
1004    pub total_ms: u64,
1005}
1006
1007/// An answer that continued elsewhere: from which offset, on which node.
1008#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1009#[non_exhaustive]
1010pub struct Resume {
1011    pub offset: u64,
1012    pub node: String,
1013}
1014
1015impl Resume {
1016    pub fn new(offset: u64, node: impl Into<String>) -> Self {
1017        Self { offset, node: node.into() }
1018    }
1019}
1020
1021/// Response metadata.
1022#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1023#[non_exhaustive]
1024pub struct Meta {
1025    /// The model node (or backend) that produced the answer.
1026    #[serde(default, skip_serializing_if = "Option::is_none")]
1027    pub served_by: Option<String>,
1028    #[serde(default, skip_serializing_if = "Option::is_none")]
1029    pub revision: Option<String>,
1030    #[serde(default)]
1031    pub cache_hit: bool,
1032    /// Set when a stand-in answered for the requested model.
1033    #[serde(default, skip_serializing_if = "Option::is_none")]
1034    pub standin: Option<String>,
1035    /// The prefix length this attempt continued from.
1036    #[serde(default, skip_serializing_if = "Option::is_none")]
1037    pub resumed_from: Option<u64>,
1038    /// Resumes behind this answer (the inference node's, then the pool's).
1039    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1040    pub resumes: Vec<Resume>,
1041    #[serde(default)]
1042    pub timings: Timings,
1043    /// Request fields the model received but does not use (such as `reference_text` for a model
1044    /// that clones from the clip alone), named rather than refused because sending them is
1045    /// harmless. Since 0.5.11; left off the wire when empty.
1046    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1047    pub ignored: Vec<String>,
1048}
1049
1050impl Meta {
1051    /// Names a request field the model received but does not use ([`Meta::ignored`]), once.
1052    /// Since 0.5.11.
1053    pub fn with_ignored(mut self, field: impl Into<String>) -> Self {
1054        let field = field.into();
1055        if !self.ignored.contains(&field) {
1056            self.ignored.push(field);
1057        }
1058        self
1059    }
1060}
1061
1062/// How a turn ended.
1063#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
1064#[non_exhaustive]
1065pub struct Finish {
1066    /// `stop`, `length`, `tool_calls`, ...
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub finish_reason: Option<String>,
1069    #[serde(default, skip_serializing_if = "Option::is_none")]
1070    pub usage: Option<Usage>,
1071    #[serde(default)]
1072    pub meta: Meta,
1073}
1074
1075impl Finish {
1076    pub fn new(finish_reason: impl Into<String>) -> Self {
1077        Self { finish_reason: Some(finish_reason.into()), ..Default::default() }
1078    }
1079
1080    pub fn with_usage(mut self, usage: Usage) -> Self {
1081        self.usage = Some(usage);
1082        self
1083    }
1084}
1085
1086/// Asking node to serving node.
1087#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1088#[serde(rename_all = "snake_case")]
1089#[non_exhaustive]
1090#[allow(clippy::large_enum_variant)]
1091pub enum ClientFrame {
1092    Infer(Request),
1093    Embed(EmbedRequest),
1094    Cancel {
1095        id: String,
1096    },
1097    /// Speech to text (since 0.5.8).
1098    Transcribe(TranscribeRequest),
1099    /// Text to speech (since 0.5.11).
1100    Speak(SpeakRequest),
1101}
1102
1103/// Serving node to asking node.
1104#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1105#[serde(rename_all = "snake_case")]
1106#[non_exhaustive]
1107pub enum ServerFrame {
1108    Queued {
1109        id: String,
1110        position: u32,
1111    },
1112    Accepted {
1113        id: String,
1114        model: String,
1115        attempt: u32,
1116        resume: bool,
1117    },
1118    Delta {
1119        id: String,
1120        offset: u64,
1121        text: String,
1122    },
1123    Reasoning {
1124        id: String,
1125        offset: u64,
1126        text: String,
1127    },
1128    ToolCall {
1129        id: String,
1130        index: u32,
1131        call: ToolCall,
1132    },
1133    Embedding {
1134        id: String,
1135        index: u32,
1136        #[serde(with = "bytes")]
1137        vector: Vec<u8>,
1138    },
1139    Usage {
1140        id: String,
1141        usage: Usage,
1142    },
1143    Done {
1144        id: String,
1145        finish: Finish,
1146    },
1147    Failed {
1148        id: String,
1149        error: RemoteError,
1150    },
1151    Cancelled {
1152        id: String,
1153    },
1154    /// Response metadata known before the answer (a cache hit, a stand-in, the revision). Sent
1155    /// only to askers that set [`Request::early_meta`]; `Done` carries it again.
1156    Meta {
1157        id: String,
1158        meta: Meta,
1159    },
1160    /// The answer to a [`TranscribeRequest`], before `Done` (since 0.5.8).
1161    Transcript {
1162        id: String,
1163        transcript: Transcript,
1164    },
1165    /// Still at work on an accepted request that streams nothing until it is done
1166    /// (transcription): sent every [`QUEUE_KEEPALIVE`] so the asker doesn't take the quiet for a
1167    /// stall (since 0.5.8).
1168    Working {
1169        id: String,
1170    },
1171    /// The audio of a [`SpeakRequest`] begins (since 0.5.11): sent once, before the first
1172    /// `Audio`. The sample rate and channel count are absent when the engine did not say.
1173    SpeechStart {
1174        id: String,
1175        format: AudioFormat,
1176        #[serde(default, skip_serializing_if = "Option::is_none")]
1177        sample_rate: Option<u32>,
1178        #[serde(default, skip_serializing_if = "Option::is_none")]
1179        channels: Option<u16>,
1180    },
1181    /// A piece of the audio (since 0.5.11): at most [`MAX_AUDIO_CHUNK`] bytes, at byte `offset`
1182    /// of the whole file, in order.
1183    Audio {
1184        id: String,
1185        offset: u64,
1186        #[serde(with = "bytes")]
1187        data: Vec<u8>,
1188    },
1189}
1190
1191impl ServerFrame {
1192    /// The request id the frame belongs to.
1193    pub fn id(&self) -> &str {
1194        match self {
1195            ServerFrame::Queued { id, .. }
1196            | ServerFrame::Accepted { id, .. }
1197            | ServerFrame::Delta { id, .. }
1198            | ServerFrame::Reasoning { id, .. }
1199            | ServerFrame::ToolCall { id, .. }
1200            | ServerFrame::Embedding { id, .. }
1201            | ServerFrame::Usage { id, .. }
1202            | ServerFrame::Meta { id, .. }
1203            | ServerFrame::Transcript { id, .. }
1204            | ServerFrame::Working { id }
1205            | ServerFrame::SpeechStart { id, .. }
1206            | ServerFrame::Audio { id, .. }
1207            | ServerFrame::Done { id, .. }
1208            | ServerFrame::Failed { id, .. }
1209            | ServerFrame::Cancelled { id } => id,
1210        }
1211    }
1212}
1213
1214/// A vector as little-endian `f32` bytes.
1215pub fn f32_bytes(v: &[f32]) -> Vec<u8> {
1216    v.iter().flat_map(|x| x.to_le_bytes()).collect()
1217}
1218
1219/// Little-endian `f32` bytes back to a vector.
1220pub fn bytes_f32(b: &[u8]) -> Result<Vec<f32>, RemoteError> {
1221    if !b.len().is_multiple_of(4) {
1222        return Err(RemoteError::protocol(format!("an embedding of {} bytes is not whole f32s", b.len())));
1223    }
1224    Ok(b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
1225}
1226
1227/// One piece of a backend's output.
1228#[derive(Debug, Clone, PartialEq)]
1229pub(crate) enum Piece {
1230    Text(String),
1231    Reasoning(String),
1232    ToolCall(ToolCall),
1233    Usage(Usage),
1234    Meta(Meta),
1235}
1236
1237/// Where an [`InferBackend`] streams its output. The server turns it into frames with offsets.
1238#[derive(Debug, Clone)]
1239pub struct Output {
1240    tx: mpsc::UnboundedSender<Piece>,
1241}
1242
1243impl Output {
1244    pub(crate) fn channel() -> (Self, mpsc::UnboundedReceiver<Piece>) {
1245        let (tx, rx) = mpsc::unbounded_channel();
1246        (Self { tx }, rx)
1247    }
1248
1249    /// Answer text.
1250    pub fn text(&self, delta: impl Into<String>) {
1251        let d = delta.into();
1252        if !d.is_empty() {
1253            let _ = self.tx.send(Piece::Text(d));
1254        }
1255    }
1256
1257    /// Reasoning text.
1258    pub fn reasoning(&self, delta: impl Into<String>) {
1259        let d = delta.into();
1260        if !d.is_empty() {
1261            let _ = self.tx.send(Piece::Reasoning(d));
1262        }
1263    }
1264
1265    /// A complete tool call.
1266    pub fn tool_call(&self, call: ToolCall) {
1267        let _ = self.tx.send(Piece::ToolCall(call));
1268    }
1269
1270    /// Token counts so far.
1271    pub fn usage(&self, usage: Usage) {
1272        let _ = self.tx.send(Piece::Usage(usage));
1273    }
1274
1275    /// Response metadata known before the answer, such as [`Meta::cache_hit`] before replaying a
1276    /// cached answer. Call it before the first text. The server passes it on to askers that read
1277    /// it and folds it into the final [`Finish::meta`].
1278    pub fn meta(&self, meta: Meta) {
1279        let _ = self.tx.send(Piece::Meta(meta));
1280    }
1281}
1282
1283/// What serves an infer/2 request: a model, or an inference node's routing to model nodes.
1284/// Implementations poll `cancel` and stream through `out`.
1285#[async_trait]
1286pub trait InferBackend: Send + Sync {
1287    fn name(&self) -> String;
1288
1289    /// Honours `assistant_prefix`, generating only what comes after it (vLLM
1290    /// `continue_final_message`, llama.cpp assistant prefill). Default: no.
1291    fn resumes(&self) -> bool {
1292        false
1293    }
1294
1295    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError>;
1296}
1297
1298/// What serves embeddings.
1299#[async_trait]
1300pub trait EmbedBackend: Send + Sync {
1301    fn name(&self) -> String;
1302
1303    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError>;
1304
1305    /// The vector and the prompt tokens it took, if the backend knows them. The server sums the
1306    /// counts into the reply's [`Finish::usage`]. Default: [`embed`](Self::embed), no count.
1307    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
1308        Ok((self.embed(input, cancel).await?, None))
1309    }
1310}
1311
1312/// What serves transcription (since 0.5.8): a speech-to-text model on this node, or an inference
1313/// node's routing to one.
1314#[async_trait]
1315pub trait TranscribeBackend: Send + Sync {
1316    fn name(&self) -> String;
1317
1318    /// The transcript of `request.audio`. Poll `cancel`.
1319    async fn transcribe(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<Transcript, RemoteError>;
1320
1321    /// The transcript and token counts, if the backend knows them; they go into the reply's
1322    /// [`Finish::usage`]. Default: [`transcribe`](Self::transcribe), no counts.
1323    async fn transcribe_counted(&self, request: &TranscribeRequest, cancel: &CancelToken) -> Result<(Transcript, Option<Usage>), RemoteError> {
1324        Ok((self.transcribe(request, cancel).await?, None))
1325    }
1326}
1327
1328/// How a speech answer's audio is encoded: the format, and the sample rate and channel count when
1329/// the engine says (since 0.5.11). Becomes [`ServerFrame::SpeechStart`].
1330#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1331#[non_exhaustive]
1332pub struct AudioHeader {
1333    pub format: AudioFormat,
1334    pub sample_rate: Option<u32>,
1335    pub channels: Option<u16>,
1336}
1337
1338impl AudioHeader {
1339    pub fn new(format: AudioFormat) -> Self {
1340        Self { format, ..Default::default() }
1341    }
1342
1343    pub fn with_sample_rate(mut self, hz: u32) -> Self {
1344        self.sample_rate = Some(hz);
1345        self
1346    }
1347
1348    pub fn with_channels(mut self, channels: u16) -> Self {
1349        self.channels = Some(channels);
1350        self
1351    }
1352}
1353
1354/// One piece of an [`AudioStream`] (since 0.5.11): the header once, then audio, with usage and
1355/// metadata whenever the backend knows them.
1356#[derive(Debug, Clone, PartialEq)]
1357#[non_exhaustive]
1358pub enum SpeechPiece {
1359    /// The audio begins; must come once, before any `Audio`.
1360    Start(AudioHeader),
1361    /// The next bytes of the file, any size (the server splits them into frames of at most
1362    /// [`MAX_AUDIO_CHUNK`]).
1363    Audio(Vec<u8>),
1364    /// Counts so far (the last one wins); the server fills in
1365    /// [`Usage::input_chars`] when the backend leaves it at 0.
1366    Usage(Usage),
1367    /// Metadata for `Done`: [`Meta::ignored`] fields are added, `served_by` and `revision` kept
1368    /// when set.
1369    Meta(Meta),
1370}
1371
1372/// What a [`SpeakBackend`] returns (since 0.5.11): the speech as it is made. A backend either
1373/// hands over a finished file ([`AudioStream::from_file`]) or streams through the
1374/// [`AudioSink`] of [`AudioStream::channel`] from a task it spawns (which should stop when
1375/// `cancel` fires or [`AudioSink::is_closed`]). An `Err` piece fails the request.
1376#[derive(Debug)]
1377pub struct AudioStream {
1378    rx: mpsc::Receiver<Result<SpeechPiece, RemoteError>>,
1379}
1380
1381/// The sending end of an [`AudioStream`] (since 0.5.11). Every send fails with `Cancelled` once
1382/// the stream is gone (the asker cancelled or went away).
1383#[derive(Debug, Clone)]
1384pub struct AudioSink {
1385    tx: mpsc::Sender<Result<SpeechPiece, RemoteError>>,
1386}
1387
1388impl AudioStream {
1389    /// A stream and its sink, holding up to `buffer` pieces (at least 1) before a send waits.
1390    pub fn channel(buffer: usize) -> (AudioSink, AudioStream) {
1391        let (tx, rx) = mpsc::channel(buffer.max(1));
1392        (AudioSink { tx }, AudioStream { rx })
1393    }
1394
1395    /// A finished file: the header, the audio and, if known, usage.
1396    pub fn from_file(header: AudioHeader, audio: Vec<u8>, usage: Option<Usage>) -> Self {
1397        let mut pieces = vec![Ok(SpeechPiece::Start(header)), Ok(SpeechPiece::Audio(audio))];
1398        pieces.extend(usage.map(|u| Ok(SpeechPiece::Usage(u))));
1399        Self::from_pieces(pieces)
1400    }
1401
1402    /// A stream of these pieces, in order.
1403    pub fn from_pieces(pieces: Vec<Result<SpeechPiece, RemoteError>>) -> Self {
1404        let (tx, rx) = mpsc::channel(pieces.len().max(1));
1405        for p in pieces {
1406            let _ = tx.try_send(p);
1407        }
1408        Self { rx }
1409    }
1410
1411    /// The next piece; `None` at the end.
1412    pub async fn next(&mut self) -> Option<Result<SpeechPiece, RemoteError>> {
1413        self.rx.recv().await
1414    }
1415}
1416
1417impl AudioSink {
1418    async fn send(&self, piece: Result<SpeechPiece, RemoteError>) -> Result<(), RemoteError> {
1419        self.tx.send(piece).await.map_err(|_| RemoteError::Cancelled)
1420    }
1421
1422    /// The audio begins (once, first).
1423    pub async fn start(&self, header: AudioHeader) -> Result<(), RemoteError> {
1424        self.send(Ok(SpeechPiece::Start(header))).await
1425    }
1426
1427    /// More audio; empty pieces are skipped.
1428    pub async fn audio(&self, data: Vec<u8>) -> Result<(), RemoteError> {
1429        if data.is_empty() {
1430            return Ok(());
1431        }
1432        self.send(Ok(SpeechPiece::Audio(data))).await
1433    }
1434
1435    pub async fn usage(&self, usage: Usage) -> Result<(), RemoteError> {
1436        self.send(Ok(SpeechPiece::Usage(usage))).await
1437    }
1438
1439    pub async fn meta(&self, meta: Meta) -> Result<(), RemoteError> {
1440        self.send(Ok(SpeechPiece::Meta(meta))).await
1441    }
1442
1443    /// Fails the request with `error` (after any audio already sent).
1444    pub async fn fail(&self, error: RemoteError) -> Result<(), RemoteError> {
1445        self.send(Err(error)).await
1446    }
1447
1448    /// The stream is gone: stop making audio.
1449    pub fn is_closed(&self) -> bool {
1450        self.tx.is_closed()
1451    }
1452}
1453
1454/// What serves speech out (since 0.5.11): a speaking model on this node, or an inference node's
1455/// routing to one.
1456#[async_trait]
1457pub trait SpeakBackend: Send + Sync {
1458    fn name(&self) -> String;
1459
1460    /// The speech for `request` (already [`check`](SpeakRequest::check)ed). Return
1461    /// `Unsupported` when this model can't serve the request but another node's copy might (a
1462    /// different engine), `BadRequest` naming what the model lacks when none could
1463    /// ([`SpeechProfile::covers`](crate::speech::SpeechProfile::covers)). Poll `cancel`; the
1464    /// server keeps the asker's stream alive with `Working` until the stream starts.
1465    async fn speak(&self, request: &SpeakRequest, cancel: &CancelToken) -> Result<AudioStream, RemoteError>;
1466}
1467
1468/// An [`InferBackend`] over a [`ModelBackend`]: inline messages and tools only, no resume;
1469/// sampling settings, seed and response format are left to the model's defaults.
1470pub struct ModelAdapter {
1471    backend: Arc<dyn ModelBackend>,
1472}
1473
1474impl ModelAdapter {
1475    pub fn new(backend: Arc<dyn ModelBackend>) -> Self {
1476        Self { backend }
1477    }
1478}
1479
1480#[async_trait]
1481impl InferBackend for ModelAdapter {
1482    fn name(&self) -> String {
1483        self.backend.name()
1484    }
1485
1486    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
1487        let messages = match &request.input {
1488            Input::Messages(m) => m,
1489            Input::Prompt(_) => return Err(RemoteError::Unsupported { message: "this backend takes messages, not a raw prompt".into() }),
1490            _ => return Err(RemoteError::unavailable("this node keeps no conversations; send the messages")),
1491        };
1492        let (tx, mut rx) = mpsc::unbounded_channel();
1493        let sink = DeltaSink::new(Some(tx));
1494        let forward = |ev: AgentEvent| match ev {
1495            AgentEvent::TextDelta(t) => out.text(t),
1496            AgentEvent::ReasoningDelta(t) => out.reasoning(t),
1497            _ => {}
1498        };
1499        let mut run = pin!(self.backend.complete(messages, &request.tools, &sink, cancel));
1500        let turn = loop {
1501            tokio::select! {
1502                r = &mut run => break r,
1503                Some(ev) = rx.recv() => forward(ev),
1504            }
1505        };
1506        while let Ok(ev) = rx.try_recv() {
1507            forward(ev);
1508        }
1509        let turn = turn.map_err(model_error)?;
1510        let calls = !turn.tool_calls.is_empty();
1511        for call in turn.tool_calls {
1512            out.tool_call(call);
1513        }
1514        Ok(Finish::new(if calls { "tool_calls" } else { "stop" }))
1515    }
1516}
1517
1518fn is_cancel(bytes: &[u8], id: &str) -> bool {
1519    matches!(crate::remote::from_cbor::<ClientFrame>(bytes), Ok(ClientFrame::Cancel { id: c }) if c == id)
1520}
1521
1522fn millis(d: Duration) -> u64 {
1523    d.as_millis().min(u64::MAX as u128) as u64
1524}
1525
1526enum Waited {
1527    Go(super::queue::Permit),
1528    /// The asker cancelled or went away while waiting; the reply (if any) has been sent.
1529    Gone,
1530}
1531
1532/// Waits for a slot, telling the asker its place.
1533async fn wait_turn(ch: &mut Channel, id: &str, admission: &Admission, priority: Priority) -> Result<Waited, RemoteError> {
1534    let mut ticket = match admission.enter(priority) {
1535        Ok(t) => t,
1536        Err(error) => {
1537            ch.send_cbor(&ServerFrame::Failed { id: id.to_string(), error }).await?;
1538            return Ok(Waited::Gone);
1539        }
1540    };
1541    let mut last = None;
1542    loop {
1543        tokio::select! {
1544            turn = ticket.turn(last, QUEUE_KEEPALIVE) => match turn {
1545                Turn::Go(permit) => return Ok(Waited::Go(permit)),
1546                Turn::Waiting(position) => {
1547                    last = Some(position);
1548                    ch.send_cbor(&ServerFrame::Queued { id: id.to_string(), position }).await?;
1549                }
1550            },
1551            m = ch.rx.recv() => match m {
1552                Ok(Some(bytes)) if is_cancel(&bytes, id) => {
1553                    ch.send_cbor(&ServerFrame::Cancelled { id: id.to_string() }).await?;
1554                    return Ok(Waited::Gone);
1555                }
1556                Ok(Some(_)) => {}
1557                Ok(None) | Err(_) => return Ok(Waited::Gone),
1558            },
1559        }
1560    }
1561}
1562
1563/// Serve one infer/2 stream. `caller` is the transport-authenticated peer (plus a certificate
1564/// if the transport carries one; otherwise the one the request presents is attached). The host
1565/// authorizes the caller before anything else. Returns when the request is done, failed or
1566/// cancelled; if the asker goes away it is cancelled.
1567pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission) -> Result<(), RemoteError> {
1568    match ch.recv_cbor::<ClientFrame>().await? {
1569        Some(ClientFrame::Infer(request)) => serve_infer(ch, caller, host, admission, request).await,
1570        Some(ClientFrame::Embed(request)) => serve_embed(ch, caller, host, admission, request).await,
1571        Some(ClientFrame::Transcribe(request)) => serve_transcribe(ch, caller, host, admission, request).await,
1572        Some(ClientFrame::Speak(request)) => serve_speak(ch, caller, host, admission, request).await,
1573        Some(ClientFrame::Cancel { .. }) | None => Ok(()),
1574    }
1575}
1576
1577async fn serve_infer(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission, mut request: Request) -> Result<(), RemoteError> {
1578    let started = Instant::now();
1579    let id = request.id.clone();
1580    let caller = caller.presenting(request.cert.take());
1581    let checked = host.authorize(&caller).and_then(|()| {
1582        if matches!(request.input, Input::Prompt(_)) && !request.tools.is_empty() {
1583            return Err(RemoteError::BadRequest { message: "a raw prompt takes no tools".into() });
1584        }
1585        if request.raw && matches!(request.input, Input::Context(_)) {
1586            return Err(RemoteError::BadRequest { message: "raw mode takes assembled messages, not a context_ref".into() });
1587        }
1588        if request.assistant_prefix.as_ref().is_some_and(|p| !p.is_consistent()) {
1589            return Err(RemoteError::BadRequest { message: "assistant_prefix lengths do not match its text".into() });
1590        }
1591        host.open_request(&caller, &request)
1592    });
1593    let backend = match checked {
1594        Ok(b) => b,
1595        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1596    };
1597    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1598        Waited::Go(p) => p,
1599        Waited::Gone => return Ok(()),
1600    };
1601    let queued = started.elapsed();
1602    let resume = backend.resumes();
1603    let prefix = request.assistant_prefix.clone().filter(|_| resume);
1604    if !resume {
1605        request.assistant_prefix = None;
1606    }
1607    let (text_at, reasoning_at) = prefix.as_ref().map(|p| (p.len, p.reasoning_len)).unwrap_or((0, 0));
1608    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: request.attempt, resume }).await?;
1609    let accepted = Instant::now();
1610
1611    let (out, mut pieces) = Output::channel();
1612    let cancel = CancelToken::new();
1613    let mut framer =
1614        Framer { id: id.clone(), text_at, reasoning_at, calls: 0, accepted, first_token: None, early_meta: request.early_meta, meta: None };
1615    let mut run = pin!(backend.infer(&request, &out, &cancel));
1616    let mut asker_open = true;
1617    let mut send_failed = false;
1618    let result = loop {
1619        tokio::select! {
1620            r = &mut run => break r,
1621            Some(p) = pieces.recv() => {
1622                let Some(f) = framer.frame(p) else { continue };
1623                if !send_failed && ch.send_cbor(&f).await.is_err() {
1624                    send_failed = true;
1625                    cancel.cancel();
1626                }
1627            }
1628            m = ch.rx.recv(), if asker_open => match m {
1629                Ok(Some(bytes)) => {
1630                    if is_cancel(&bytes, &id) {
1631                        cancel.cancel();
1632                    }
1633                }
1634                Ok(None) | Err(_) => {
1635                    asker_open = false;
1636                    cancel.cancel();
1637                }
1638            },
1639        }
1640    };
1641    if send_failed || !asker_open {
1642        return Ok(());
1643    }
1644    while let Ok(p) = pieces.try_recv() {
1645        if let Some(f) = framer.frame(p) {
1646            ch.send_cbor(&f).await?;
1647        }
1648    }
1649    let reply = match result {
1650        Ok(mut finish) => {
1651            let meta = &mut finish.meta;
1652            if let Some(early) = framer.meta.take() {
1653                meta.cache_hit |= early.cache_hit;
1654                if meta.served_by.is_none() {
1655                    meta.served_by = early.served_by;
1656                }
1657                if meta.revision.is_none() {
1658                    meta.revision = early.revision;
1659                }
1660                if meta.standin.is_none() {
1661                    meta.standin = early.standin;
1662                }
1663            }
1664            meta.served_by.get_or_insert_with(|| backend.name());
1665            if let Some(p) = &prefix {
1666                meta.resumed_from = Some(p.len);
1667            }
1668            meta.timings.queued_ms = millis(queued);
1669            meta.timings.first_token_ms = framer.first_token.map(millis);
1670            meta.timings.total_ms = millis(started.elapsed());
1671            ServerFrame::Done { id, finish }
1672        }
1673        Err(_) if cancel.is_cancelled() => ServerFrame::Cancelled { id },
1674        Err(error) => ServerFrame::Failed { id, error },
1675    };
1676    ch.send_cbor(&reply).await
1677}
1678
1679/// Turns backend output into frames with offsets and tool-call indexes.
1680struct Framer {
1681    id: String,
1682    text_at: u64,
1683    reasoning_at: u64,
1684    calls: u32,
1685    accepted: Instant,
1686    first_token: Option<Duration>,
1687    /// The asker reads `Meta` frames.
1688    early_meta: bool,
1689    /// Early metadata from the backend, folded into the final `Done`.
1690    meta: Option<Meta>,
1691}
1692
1693impl Framer {
1694    fn frame(&mut self, p: Piece) -> Option<ServerFrame> {
1695        let id = self.id.clone();
1696        Some(match p {
1697            Piece::Text(text) => {
1698                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
1699                let offset = self.text_at;
1700                self.text_at += chars(&text);
1701                ServerFrame::Delta { id, offset, text }
1702            }
1703            Piece::Reasoning(text) => {
1704                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
1705                let offset = self.reasoning_at;
1706                self.reasoning_at += chars(&text);
1707                ServerFrame::Reasoning { id, offset, text }
1708            }
1709            Piece::ToolCall(call) => {
1710                self.calls += 1;
1711                ServerFrame::ToolCall { id, index: self.calls - 1, call }
1712            }
1713            Piece::Usage(usage) => ServerFrame::Usage { id, usage },
1714            Piece::Meta(meta) => {
1715                self.meta = Some(meta.clone());
1716                if !self.early_meta {
1717                    return None;
1718                }
1719                ServerFrame::Meta { id, meta }
1720            }
1721        })
1722    }
1723}
1724
1725async fn serve_embed(
1726    mut ch: Channel,
1727    caller: Caller,
1728    host: &dyn InferHost,
1729    admission: &Admission,
1730    mut request: EmbedRequest,
1731) -> Result<(), RemoteError> {
1732    let started = Instant::now();
1733    let id = request.id.clone();
1734    let caller = caller.presenting(request.cert.take());
1735    let backend = match host.authorize(&caller).and_then(|()| host.open_embed(&caller, request.model.as_deref())) {
1736        Ok(b) => b,
1737        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1738    };
1739    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1740        Waited::Go(p) => p,
1741        Waited::Gone => return Ok(()),
1742    };
1743    let queued = started.elapsed();
1744    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1745    let cancel = CancelToken::new();
1746    let mut tokens: Option<u64> = None;
1747    for (index, input) in request.inputs.iter().enumerate() {
1748        let vector = tokio::select! {
1749            v = backend.embed_counted(input, &cancel) => v,
1750            m = async { loop {
1751                match ch.rx.recv().await {
1752                    Ok(Some(bytes)) if is_cancel(&bytes, &id) => return true,
1753                    Ok(Some(_)) => {}
1754                    Ok(None) | Err(_) => return false,
1755                }
1756            } } => {
1757                cancel.cancel();
1758                return if m { ch.send_cbor(&ServerFrame::Cancelled { id }).await } else { Ok(()) };
1759            }
1760        };
1761        match vector {
1762            Ok((v, n)) => {
1763                if let Some(n) = n {
1764                    *tokens.get_or_insert(0) += n;
1765                }
1766                ch.send_cbor(&ServerFrame::Embedding { id: id.clone(), index: index as u32, vector: f32_bytes(&v) }).await?
1767            }
1768            Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1769        }
1770    }
1771    let mut finish = Finish::new("stop");
1772    finish.usage = tokens.map(|n| Usage::new(n, 0));
1773    finish.meta.served_by = Some(backend.name());
1774    finish.meta.timings.queued_ms = millis(queued);
1775    finish.meta.timings.total_ms = millis(started.elapsed());
1776    ch.send_cbor(&ServerFrame::Done { id, finish }).await
1777}
1778
1779async fn serve_transcribe(
1780    mut ch: Channel,
1781    caller: Caller,
1782    host: &dyn InferHost,
1783    admission: &Admission,
1784    mut request: TranscribeRequest,
1785) -> Result<(), RemoteError> {
1786    let started = Instant::now();
1787    let id = request.id.clone();
1788    let caller = caller.presenting(request.cert.take());
1789    let opened = host.authorize(&caller).and_then(|()| request.check()).and_then(|()| host.open_transcribe(&caller, request.model.as_deref()));
1790    let backend = match opened {
1791        Ok(b) => b,
1792        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1793    };
1794    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1795        Waited::Go(p) => p,
1796        Waited::Gone => return Ok(()),
1797    };
1798    let queued = started.elapsed();
1799    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1800    let cancel = CancelToken::new();
1801    let mut run = pin!(backend.transcribe_counted(&request, &cancel));
1802    let mut keepalive = tokio::time::interval_at(Instant::now() + QUEUE_KEEPALIVE, QUEUE_KEEPALIVE);
1803    let result = loop {
1804        tokio::select! {
1805            r = &mut run => break r,
1806            _ = keepalive.tick() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1807            m = ch.rx.recv() => match m {
1808                Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1809                    cancel.cancel();
1810                    return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1811                }
1812                Ok(Some(_)) => {}
1813                Ok(None) | Err(_) => {
1814                    cancel.cancel();
1815                    return Ok(());
1816                }
1817            },
1818        }
1819    };
1820    let (transcript, usage) = match result {
1821        Ok(r) => r,
1822        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1823    };
1824    ch.send_cbor(&ServerFrame::Transcript { id: id.clone(), transcript }).await?;
1825    let mut finish = Finish::new("stop");
1826    finish.usage = usage;
1827    finish.meta.served_by = Some(backend.name());
1828    finish.meta.timings.queued_ms = millis(queued);
1829    finish.meta.timings.total_ms = millis(started.elapsed());
1830    ch.send_cbor(&ServerFrame::Done { id, finish }).await
1831}
1832
1833/// Cancels the token when dropped, so a backend task stops however the request ends.
1834struct CancelOnDrop(CancelToken);
1835
1836impl Drop for CancelOnDrop {
1837    fn drop(&mut self) {
1838        self.0.cancel();
1839    }
1840}
1841
1842async fn serve_speak(
1843    mut ch: Channel,
1844    caller: Caller,
1845    host: &dyn InferHost,
1846    admission: &Admission,
1847    mut request: SpeakRequest,
1848) -> Result<(), RemoteError> {
1849    let started = Instant::now();
1850    let id = request.id.clone();
1851    let caller = caller.presenting(request.cert.take());
1852    let opened = host.authorize(&caller).and_then(|()| request.check()).and_then(|()| host.open_speak(&caller, &request));
1853    let backend = match opened {
1854        Ok(b) => b,
1855        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1856    };
1857    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
1858        Waited::Go(p) => p,
1859        Waited::Gone => return Ok(()),
1860    };
1861    let queued = started.elapsed();
1862    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
1863    let accepted = Instant::now();
1864    let cancel = CancelToken::new();
1865    let _stop = CancelOnDrop(cancel.clone());
1866    let mut keepalive = tokio::time::interval_at(Instant::now() + QUEUE_KEEPALIVE, QUEUE_KEEPALIVE);
1867    let opened = {
1868        let mut run = pin!(backend.speak(&request, &cancel));
1869        loop {
1870            tokio::select! {
1871                r = &mut run => break r,
1872                _ = keepalive.tick() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1873                m = ch.rx.recv() => match m {
1874                    Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1875                        cancel.cancel();
1876                        return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1877                    }
1878                    Ok(Some(_)) => {}
1879                    Ok(None) | Err(_) => return Ok(()),
1880                },
1881            }
1882        }
1883    };
1884    let mut stream = match opened {
1885        Ok(s) => s,
1886        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1887    };
1888    let mut first_audio = None;
1889    let mut offset = 0u64;
1890    let mut usage: Option<Usage> = None;
1891    let mut meta = Meta::default();
1892    loop {
1893        tokio::select! {
1894            p = stream.next() => match p {
1895                None => break,
1896                Some(Err(error)) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
1897                Some(Ok(SpeechPiece::Start(h))) if first_audio.is_none() => {
1898                    first_audio = Some(accepted.elapsed());
1899                    ch.send_cbor(&ServerFrame::SpeechStart { id: id.clone(), format: h.format, sample_rate: h.sample_rate, channels: h.channels }).await?;
1900                }
1901                Some(Ok(SpeechPiece::Start(_))) => {
1902                    let error = RemoteError::protocol("the speech backend started the audio twice");
1903                    return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1904                }
1905                Some(Ok(SpeechPiece::Audio(data))) if first_audio.is_some() => {
1906                    for chunk in data.chunks(MAX_AUDIO_CHUNK) {
1907                        ch.send_cbor(&ServerFrame::Audio { id: id.clone(), offset, data: chunk.to_vec() }).await?;
1908                        offset += chunk.len() as u64;
1909                    }
1910                }
1911                Some(Ok(SpeechPiece::Audio(_))) => {
1912                    let error = RemoteError::protocol("the speech backend sent audio before its format");
1913                    return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1914                }
1915                Some(Ok(SpeechPiece::Usage(u))) => usage = Some(u),
1916                Some(Ok(SpeechPiece::Meta(m))) => {
1917                    for field in m.ignored {
1918                        if !meta.ignored.contains(&field) {
1919                            meta.ignored.push(field);
1920                        }
1921                    }
1922                    if m.served_by.is_some() {
1923                        meta.served_by = m.served_by;
1924                    }
1925                    if m.revision.is_some() {
1926                        meta.revision = m.revision;
1927                    }
1928                }
1929            },
1930            _ = keepalive.tick(), if first_audio.is_none() => ch.send_cbor(&ServerFrame::Working { id: id.clone() }).await?,
1931            m = ch.rx.recv() => match m {
1932                Ok(Some(bytes)) if is_cancel(&bytes, &id) => {
1933                    cancel.cancel();
1934                    return ch.send_cbor(&ServerFrame::Cancelled { id }).await;
1935                }
1936                Ok(Some(_)) => {}
1937                Ok(None) | Err(_) => return Ok(()),
1938            },
1939        }
1940    }
1941    if first_audio.is_none() {
1942        let error = RemoteError::Failed { message: "the speech backend finished without audio".into() };
1943        return ch.send_cbor(&ServerFrame::Failed { id, error }).await;
1944    }
1945    let mut usage = usage.unwrap_or_default();
1946    if usage.input_chars == 0 {
1947        usage.input_chars = request.input.chars();
1948    }
1949    let mut finish = Finish::new("stop").with_usage(usage);
1950    meta.served_by.get_or_insert_with(|| backend.name());
1951    meta.timings.queued_ms = millis(queued);
1952    meta.timings.first_token_ms = first_audio.map(millis);
1953    meta.timings.total_ms = millis(started.elapsed());
1954    finish.meta = meta;
1955    ch.send_cbor(&ServerFrame::Done { id, finish }).await
1956}