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) ->
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 ...
11//!   Cancel { id } ->                        (any time)
12//!                                           <- Done { finish } | Failed { error } | Cancelled
13//! ```
14//!
15//! Messages are CBOR. Infer/1 stays JSON and is served beside this protocol; the two can't
16//! share a stream id because a `/1` server would ignore `assistant_prefix` (and repeat the
17//! prefix) and a `/1` client fails on `Queued`.
18//!
19//! - **Queue:** requests wait in the node's [`Admission`] priority queue. Every change of place,
20//!   and every [`QUEUE_KEEPALIVE`] without one, sends `Queued`; each resets the asker's accept
21//!   timeout, so a queued request is not mistaken for a dead node.
22//! - **Offsets:** every `Delta` carries the number of characters (Unicode scalar values) of the
23//!   answer before it, and every `Reasoning` the same for the reasoning text. A receiver appends
24//!   a frame only where it continues its buffer, so a resumed stream never repeats text.
25//! - **Resume:** a request may carry the `assistant_prefix` already shown. A server whose
26//!   backend honours it ([`InferBackend::resumes`]) says `resume: true` and streams only what
27//!   comes after it, starting at offset = prefix length. Others say `resume: false` and start
28//!   over at 0; askers that need a resume move on.
29//! - **Continue:** the same prefix continues an answer the user stopped or that was cut off
30//!   (assistant prefill; [`Request::continuing`] makes one from a trailing assistant message).
31//!   The wire format is unchanged, so any 0.4 server whose backend resumes can serve it.
32//! - **Tool calls** are sent whole, never half-built.
33//! - **Raw prompts** ([`Input::Prompt`]) are for completions: the model continues the text, with
34//!   no chat template and no tools.
35//! - **Early metadata:** an asker that sets [`Request::early_meta`] may get a `Meta` frame before
36//!   the answer (a cache hit, say); `Done` carries the same metadata for everyone.
37//! - **Raw mode** is for inference node → model node calls: assembled messages only, no context
38//!   lookups, caches or stand-ins.
39//! - **Embeddings:** one `Embedding` frame per input, the vector as a CBOR byte string of
40//!   little-endian `f32`.
41
42use std::pin::pin;
43use std::sync::Arc;
44use std::time::Duration;
45
46use tokio::time::Instant;
47
48use async_trait::async_trait;
49use serde::{Deserialize, Serialize};
50use serde_json::Value;
51use tokio::sync::mpsc;
52
53use super::queue::{Admission, Turn};
54use super::{InferHost, model_error};
55use crate::cancel::CancelToken;
56use crate::model::{DeltaSink, Message, ModelBackend, Role, ToolCall};
57use crate::remote::{Caller, Channel, RemoteError, bytes, request_id};
58use crate::session::AgentEvent;
59use crate::tool::ToolSpec;
60
61/// Stream protocol id.
62pub const PROTOCOL: &str = "/weirdnet-agent/infer/2";
63
64/// How often a waiting request hears its place again when it has not changed.
65pub const QUEUE_KEEPALIVE: Duration = Duration::from_secs(3);
66
67/// Scheduling class: `interactive` before `batch` before `background` (prefix warming,
68/// re-placement). Classes never preempt a running request.
69#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71#[non_exhaustive]
72pub enum Priority {
73    #[default]
74    Interactive,
75    Batch,
76    Background,
77}
78
79/// A conversation kept by the inference node (synced context), instead of inline messages.
80#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
81#[non_exhaustive]
82pub struct ContextRef {
83    pub conversation: String,
84    /// The conversation head the answer follows; `None`: the latest.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub head: Option<String>,
87}
88
89impl ContextRef {
90    pub fn new(conversation: impl Into<String>, head: Option<String>) -> Self {
91        Self { conversation: conversation.into(), head }
92    }
93}
94
95/// What the model answers.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Input {
100    /// Fully assembled messages.
101    Messages(Vec<Message>),
102    /// A conversation the serving node holds.
103    Context(ContextRef),
104    /// A raw text prompt the model continues (OpenAI `/v1/completions`); no chat template,
105    /// no tools. Servers older than 0.4.1 can't read it and close the stream.
106    Prompt(String),
107}
108
109impl Default for Input {
110    fn default() -> Self {
111        Input::Messages(Vec::new())
112    }
113}
114
115/// The part of the answer already shown, for resume. Lengths are in characters.
116#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
117#[non_exhaustive]
118pub struct Prefix {
119    pub text: String,
120    pub len: u64,
121    #[serde(default, skip_serializing_if = "String::is_empty")]
122    pub reasoning: String,
123    #[serde(default)]
124    pub reasoning_len: u64,
125}
126
127impl Prefix {
128    pub fn new(text: impl Into<String>, reasoning: impl Into<String>) -> Self {
129        let (text, reasoning) = (text.into(), reasoning.into());
130        Self { len: chars(&text), reasoning_len: chars(&reasoning), text, reasoning }
131    }
132
133    /// The lengths match the texts.
134    pub fn is_consistent(&self) -> bool {
135        self.len == chars(&self.text) && self.reasoning_len == chars(&self.reasoning)
136    }
137
138    pub fn is_empty(&self) -> bool {
139        self.text.is_empty() && self.reasoning.is_empty()
140    }
141}
142
143/// Characters (Unicode scalar values) in `s`, the unit of offsets.
144pub fn chars(s: &str) -> u64 {
145    s.chars().count() as u64
146}
147
148/// Sampling settings; `None` leaves the backend's default.
149#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct Sampling {
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub temperature: Option<f32>,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub top_p: Option<f32>,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub top_k: Option<u32>,
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub min_p: Option<f32>,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub max_tokens: Option<u32>,
162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
163    pub stop: Vec<String>,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub presence_penalty: Option<f32>,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub frequency_penalty: Option<f32>,
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub repeat_penalty: Option<f32>,
170}
171
172/// The shape of the answer.
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
174#[serde(rename_all = "snake_case")]
175#[non_exhaustive]
176pub enum ResponseFormat {
177    Text,
178    /// Any JSON object.
179    Json,
180    /// JSON matching a schema.
181    JsonSchema {
182        name: String,
183        schema: Value,
184        #[serde(default)]
185        strict: bool,
186    },
187}
188
189/// One model turn to run on an infer/2 node.
190#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
191#[non_exhaustive]
192pub struct Request {
193    /// This attempt's id on the stream.
194    pub id: String,
195    /// Stable across attempts and nodes (the idempotency key of a job).
196    pub job_id: String,
197    /// 0 for the first try, then one more per retry or resume.
198    #[serde(default)]
199    pub attempt: u32,
200    /// The model wanted, by the serving app's id (`None`: the node's default).
201    #[serde(default, skip_serializing_if = "Option::is_none")]
202    pub model: Option<String>,
203    #[serde(default)]
204    pub priority: Priority,
205    pub input: Input,
206    /// Text already shown, to continue from (see [`Prefix`]).
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub assistant_prefix: Option<Prefix>,
209    #[serde(default)]
210    pub sampling: Sampling,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub seed: Option<u64>,
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub response_format: Option<ResponseFormat>,
215    #[serde(default, skip_serializing_if = "Vec::is_empty")]
216    pub tools: Vec<ToolSpec>,
217    /// Inference node → model node: assembled messages only, no context lookups, caches or
218    /// stand-ins.
219    #[serde(default)]
220    pub raw: bool,
221    /// Wait for the requested model to load rather than take a stand-in.
222    #[serde(default)]
223    pub wait_for_model: bool,
224    /// The certificate the asker presents (for Weirdnet a CBOR `NodeCert`), checked by the host
225    /// against the transport peer.
226    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
227    pub cert: Option<Vec<u8>>,
228    /// The asker reads [`ServerFrame::Meta`] (0.4.1 and later), so the server may send response
229    /// metadata it knows before the answer, such as a cache hit. Servers that predate it ignore
230    /// the flag; askers that don't set it never get the frame.
231    #[serde(default, skip_serializing_if = "is_false")]
232    pub early_meta: bool,
233}
234
235fn is_false(b: &bool) -> bool {
236    !*b
237}
238
239impl Request {
240    /// A request over assembled messages, with a fresh id and job id.
241    pub fn messages(messages: Vec<Message>) -> Self {
242        Self::with_input(Input::Messages(messages))
243    }
244
245    /// A request over a conversation the serving node holds.
246    pub fn context(context: ContextRef) -> Self {
247        Self::with_input(Input::Context(context))
248    }
249
250    /// A request over a raw text prompt (see [`Input::Prompt`]).
251    pub fn prompt(prompt: impl Into<String>) -> Self {
252        Self::with_input(Input::Prompt(prompt.into()))
253    }
254
255    fn with_input(input: Input) -> Self {
256        let id = request_id();
257        Self { job_id: id.clone(), id, input, ..Default::default() }
258    }
259
260    pub fn with_model(mut self, model: impl Into<String>) -> Self {
261        self.model = Some(model.into());
262        self
263    }
264
265    pub fn with_priority(mut self, priority: Priority) -> Self {
266        self.priority = priority;
267        self
268    }
269
270    pub fn with_tools(mut self, tools: Vec<ToolSpec>) -> Self {
271        self.tools = tools;
272        self
273    }
274
275    pub fn with_sampling(mut self, sampling: Sampling) -> Self {
276        self.sampling = sampling;
277        self
278    }
279
280    pub fn with_seed(mut self, seed: u64) -> Self {
281        self.seed = Some(seed);
282        self
283    }
284
285    pub fn with_response_format(mut self, format: ResponseFormat) -> Self {
286        self.response_format = Some(format);
287        self
288    }
289
290    pub fn with_job_id(mut self, job_id: impl Into<String>) -> Self {
291        self.job_id = job_id.into();
292        self
293    }
294
295    pub fn with_prefix(mut self, prefix: Prefix) -> Self {
296        self.assistant_prefix = Some(prefix);
297        self
298    }
299
300    /// Continue the last assistant message: a trailing assistant message with no tool calls
301    /// moves into `assistant_prefix` (prefill), so the model carries on from its text. Only
302    /// nodes that say `resume: true` take such a request; others answer `Unsupported`. A
303    /// request that ends any other way is returned unchanged.
304    pub fn continuing(mut self) -> Self {
305        if let Input::Messages(m) = &mut self.input
306            && m.last().is_some_and(|last| last.role == Role::Assistant && last.tool_calls.is_empty())
307            && let Some(last) = m.pop()
308        {
309            self.assistant_prefix = Some(Prefix::new(last.content, ""));
310        }
311        self
312    }
313
314    pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
315        self.cert = Some(cert);
316        self
317    }
318
319    /// Raw mode (inference node → model node).
320    pub fn raw(mut self) -> Self {
321        self.raw = true;
322        self
323    }
324
325    /// Inline messages, if the input is not a context reference.
326    pub fn inline_messages(&self) -> Option<&[Message]> {
327        match &self.input {
328            Input::Messages(m) => Some(m),
329            _ => None,
330        }
331    }
332
333    /// The raw prompt, if the input is one.
334    pub fn raw_prompt(&self) -> Option<&str> {
335        match &self.input {
336            Input::Prompt(p) => Some(p),
337            _ => None,
338        }
339    }
340
341    /// The next attempt: same job, a new id, `attempt + 1`.
342    pub fn next_attempt(&self) -> Self {
343        Self { id: request_id(), attempt: self.attempt + 1, ..self.clone() }
344    }
345}
346
347/// Embeddings for a list of inputs.
348#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
349#[non_exhaustive]
350pub struct EmbedRequest {
351    pub id: String,
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub model: Option<String>,
354    pub inputs: Vec<String>,
355    #[serde(default)]
356    pub priority: Priority,
357    #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
358    pub cert: Option<Vec<u8>>,
359}
360
361impl EmbedRequest {
362    pub fn new(inputs: Vec<String>) -> Self {
363        Self { id: request_id(), inputs, ..Default::default() }
364    }
365
366    pub fn with_model(mut self, model: impl Into<String>) -> Self {
367        self.model = Some(model.into());
368        self
369    }
370
371    pub fn with_priority(mut self, priority: Priority) -> Self {
372        self.priority = priority;
373        self
374    }
375}
376
377/// Token counts.
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
379#[non_exhaustive]
380pub struct Usage {
381    pub prompt_tokens: u64,
382    pub completion_tokens: u64,
383    #[serde(default)]
384    pub reasoning_tokens: u64,
385    /// Prompt tokens served from a prefix cache.
386    #[serde(default)]
387    pub cached_tokens: u64,
388}
389
390impl Usage {
391    pub fn new(prompt_tokens: u64, completion_tokens: u64) -> Self {
392        Self { prompt_tokens, completion_tokens, ..Default::default() }
393    }
394}
395
396/// Where time went, in milliseconds.
397#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
398#[non_exhaustive]
399pub struct Timings {
400    /// Waiting in the queue.
401    pub queued_ms: u64,
402    /// From acceptance to the first text or reasoning.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub first_token_ms: Option<u64>,
405    /// From the request to the end.
406    pub total_ms: u64,
407}
408
409/// An answer that continued elsewhere: from which offset, on which node.
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
411#[non_exhaustive]
412pub struct Resume {
413    pub offset: u64,
414    pub node: String,
415}
416
417impl Resume {
418    pub fn new(offset: u64, node: impl Into<String>) -> Self {
419        Self { offset, node: node.into() }
420    }
421}
422
423/// Response metadata.
424#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
425#[non_exhaustive]
426pub struct Meta {
427    /// The model node (or backend) that produced the answer.
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub served_by: Option<String>,
430    #[serde(default, skip_serializing_if = "Option::is_none")]
431    pub revision: Option<String>,
432    #[serde(default)]
433    pub cache_hit: bool,
434    /// Set when a stand-in answered for the requested model.
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub standin: Option<String>,
437    /// The prefix length this attempt continued from.
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub resumed_from: Option<u64>,
440    /// Resumes behind this answer (the inference node's, then the pool's).
441    #[serde(default, skip_serializing_if = "Vec::is_empty")]
442    pub resumes: Vec<Resume>,
443    #[serde(default)]
444    pub timings: Timings,
445}
446
447/// How a turn ended.
448#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
449#[non_exhaustive]
450pub struct Finish {
451    /// `stop`, `length`, `tool_calls`, ...
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub finish_reason: Option<String>,
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub usage: Option<Usage>,
456    #[serde(default)]
457    pub meta: Meta,
458}
459
460impl Finish {
461    pub fn new(finish_reason: impl Into<String>) -> Self {
462        Self { finish_reason: Some(finish_reason.into()), ..Default::default() }
463    }
464
465    pub fn with_usage(mut self, usage: Usage) -> Self {
466        self.usage = Some(usage);
467        self
468    }
469}
470
471/// Asking node to serving node.
472#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
473#[serde(rename_all = "snake_case")]
474#[non_exhaustive]
475#[allow(clippy::large_enum_variant)]
476pub enum ClientFrame {
477    Infer(Request),
478    Embed(EmbedRequest),
479    Cancel { id: String },
480}
481
482/// Serving node to asking node.
483#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484#[serde(rename_all = "snake_case")]
485#[non_exhaustive]
486pub enum ServerFrame {
487    Queued {
488        id: String,
489        position: u32,
490    },
491    Accepted {
492        id: String,
493        model: String,
494        attempt: u32,
495        resume: bool,
496    },
497    Delta {
498        id: String,
499        offset: u64,
500        text: String,
501    },
502    Reasoning {
503        id: String,
504        offset: u64,
505        text: String,
506    },
507    ToolCall {
508        id: String,
509        index: u32,
510        call: ToolCall,
511    },
512    Embedding {
513        id: String,
514        index: u32,
515        #[serde(with = "bytes")]
516        vector: Vec<u8>,
517    },
518    Usage {
519        id: String,
520        usage: Usage,
521    },
522    Done {
523        id: String,
524        finish: Finish,
525    },
526    Failed {
527        id: String,
528        error: RemoteError,
529    },
530    Cancelled {
531        id: String,
532    },
533    /// Response metadata known before the answer (a cache hit, a stand-in, the revision). Sent
534    /// only to askers that set [`Request::early_meta`]; `Done` carries it again.
535    Meta {
536        id: String,
537        meta: Meta,
538    },
539}
540
541impl ServerFrame {
542    /// The request id the frame belongs to.
543    pub fn id(&self) -> &str {
544        match self {
545            ServerFrame::Queued { id, .. }
546            | ServerFrame::Accepted { id, .. }
547            | ServerFrame::Delta { id, .. }
548            | ServerFrame::Reasoning { id, .. }
549            | ServerFrame::ToolCall { id, .. }
550            | ServerFrame::Embedding { id, .. }
551            | ServerFrame::Usage { id, .. }
552            | ServerFrame::Meta { id, .. }
553            | ServerFrame::Done { id, .. }
554            | ServerFrame::Failed { id, .. }
555            | ServerFrame::Cancelled { id } => id,
556        }
557    }
558}
559
560/// A vector as little-endian `f32` bytes.
561pub fn f32_bytes(v: &[f32]) -> Vec<u8> {
562    v.iter().flat_map(|x| x.to_le_bytes()).collect()
563}
564
565/// Little-endian `f32` bytes back to a vector.
566pub fn bytes_f32(b: &[u8]) -> Result<Vec<f32>, RemoteError> {
567    if !b.len().is_multiple_of(4) {
568        return Err(RemoteError::protocol(format!("an embedding of {} bytes is not whole f32s", b.len())));
569    }
570    Ok(b.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect())
571}
572
573/// One piece of a backend's output.
574#[derive(Debug, Clone, PartialEq)]
575pub(crate) enum Piece {
576    Text(String),
577    Reasoning(String),
578    ToolCall(ToolCall),
579    Usage(Usage),
580    Meta(Meta),
581}
582
583/// Where an [`InferBackend`] streams its output. The server turns it into frames with offsets.
584#[derive(Debug, Clone)]
585pub struct Output {
586    tx: mpsc::UnboundedSender<Piece>,
587}
588
589impl Output {
590    pub(crate) fn channel() -> (Self, mpsc::UnboundedReceiver<Piece>) {
591        let (tx, rx) = mpsc::unbounded_channel();
592        (Self { tx }, rx)
593    }
594
595    /// Answer text.
596    pub fn text(&self, delta: impl Into<String>) {
597        let d = delta.into();
598        if !d.is_empty() {
599            let _ = self.tx.send(Piece::Text(d));
600        }
601    }
602
603    /// Reasoning text.
604    pub fn reasoning(&self, delta: impl Into<String>) {
605        let d = delta.into();
606        if !d.is_empty() {
607            let _ = self.tx.send(Piece::Reasoning(d));
608        }
609    }
610
611    /// A complete tool call.
612    pub fn tool_call(&self, call: ToolCall) {
613        let _ = self.tx.send(Piece::ToolCall(call));
614    }
615
616    /// Token counts so far.
617    pub fn usage(&self, usage: Usage) {
618        let _ = self.tx.send(Piece::Usage(usage));
619    }
620
621    /// Response metadata known before the answer, such as [`Meta::cache_hit`] before replaying a
622    /// cached answer. Call it before the first text. The server passes it on to askers that read
623    /// it and folds it into the final [`Finish::meta`].
624    pub fn meta(&self, meta: Meta) {
625        let _ = self.tx.send(Piece::Meta(meta));
626    }
627}
628
629/// What serves an infer/2 request: a model, or an inference node's routing to model nodes.
630/// Implementations poll `cancel` and stream through `out`.
631#[async_trait]
632pub trait InferBackend: Send + Sync {
633    fn name(&self) -> String;
634
635    /// Honours `assistant_prefix`, generating only what comes after it (vLLM
636    /// `continue_final_message`, llama.cpp assistant prefill). Default: no.
637    fn resumes(&self) -> bool {
638        false
639    }
640
641    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError>;
642}
643
644/// What serves embeddings.
645#[async_trait]
646pub trait EmbedBackend: Send + Sync {
647    fn name(&self) -> String;
648
649    async fn embed(&self, input: &str, cancel: &CancelToken) -> Result<Vec<f32>, RemoteError>;
650
651    /// The vector and the prompt tokens it took, if the backend knows them. The server sums the
652    /// counts into the reply's [`Finish::usage`]. Default: [`embed`](Self::embed), no count.
653    async fn embed_counted(&self, input: &str, cancel: &CancelToken) -> Result<(Vec<f32>, Option<u64>), RemoteError> {
654        Ok((self.embed(input, cancel).await?, None))
655    }
656}
657
658/// An [`InferBackend`] over a [`ModelBackend`]: inline messages and tools only, no resume;
659/// sampling settings, seed and response format are left to the model's defaults.
660pub struct ModelAdapter {
661    backend: Arc<dyn ModelBackend>,
662}
663
664impl ModelAdapter {
665    pub fn new(backend: Arc<dyn ModelBackend>) -> Self {
666        Self { backend }
667    }
668}
669
670#[async_trait]
671impl InferBackend for ModelAdapter {
672    fn name(&self) -> String {
673        self.backend.name()
674    }
675
676    async fn infer(&self, request: &Request, out: &Output, cancel: &CancelToken) -> Result<Finish, RemoteError> {
677        let messages = match &request.input {
678            Input::Messages(m) => m,
679            Input::Prompt(_) => return Err(RemoteError::Unsupported { message: "this backend takes messages, not a raw prompt".into() }),
680            _ => return Err(RemoteError::unavailable("this node keeps no conversations; send the messages")),
681        };
682        let (tx, mut rx) = mpsc::unbounded_channel();
683        let sink = DeltaSink::new(Some(tx));
684        let forward = |ev: AgentEvent| match ev {
685            AgentEvent::TextDelta(t) => out.text(t),
686            AgentEvent::ReasoningDelta(t) => out.reasoning(t),
687            _ => {}
688        };
689        let mut run = pin!(self.backend.complete(messages, &request.tools, &sink, cancel));
690        let turn = loop {
691            tokio::select! {
692                r = &mut run => break r,
693                Some(ev) = rx.recv() => forward(ev),
694            }
695        };
696        while let Ok(ev) = rx.try_recv() {
697            forward(ev);
698        }
699        let turn = turn.map_err(model_error)?;
700        let calls = !turn.tool_calls.is_empty();
701        for call in turn.tool_calls {
702            out.tool_call(call);
703        }
704        Ok(Finish::new(if calls { "tool_calls" } else { "stop" }))
705    }
706}
707
708fn is_cancel(bytes: &[u8], id: &str) -> bool {
709    matches!(crate::remote::from_cbor::<ClientFrame>(bytes), Ok(ClientFrame::Cancel { id: c }) if c == id)
710}
711
712fn millis(d: Duration) -> u64 {
713    d.as_millis().min(u64::MAX as u128) as u64
714}
715
716enum Waited {
717    Go(super::queue::Permit),
718    /// The asker cancelled or went away while waiting; the reply (if any) has been sent.
719    Gone,
720}
721
722/// Waits for a slot, telling the asker its place.
723async fn wait_turn(ch: &mut Channel, id: &str, admission: &Admission, priority: Priority) -> Result<Waited, RemoteError> {
724    let mut ticket = match admission.enter(priority) {
725        Ok(t) => t,
726        Err(error) => {
727            ch.send_cbor(&ServerFrame::Failed { id: id.to_string(), error }).await?;
728            return Ok(Waited::Gone);
729        }
730    };
731    let mut last = None;
732    loop {
733        tokio::select! {
734            turn = ticket.turn(last, QUEUE_KEEPALIVE) => match turn {
735                Turn::Go(permit) => return Ok(Waited::Go(permit)),
736                Turn::Waiting(position) => {
737                    last = Some(position);
738                    ch.send_cbor(&ServerFrame::Queued { id: id.to_string(), position }).await?;
739                }
740            },
741            m = ch.rx.recv() => match m {
742                Ok(Some(bytes)) if is_cancel(&bytes, id) => {
743                    ch.send_cbor(&ServerFrame::Cancelled { id: id.to_string() }).await?;
744                    return Ok(Waited::Gone);
745                }
746                Ok(Some(_)) => {}
747                Ok(None) | Err(_) => return Ok(Waited::Gone),
748            },
749        }
750    }
751}
752
753/// Serve one infer/2 stream. `caller` is the transport-authenticated peer (plus a certificate
754/// if the transport carries one; otherwise the one the request presents is attached). The host
755/// authorizes the caller before anything else. Returns when the request is done, failed or
756/// cancelled; if the asker goes away it is cancelled.
757pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission) -> Result<(), RemoteError> {
758    match ch.recv_cbor::<ClientFrame>().await? {
759        Some(ClientFrame::Infer(request)) => serve_infer(ch, caller, host, admission, request).await,
760        Some(ClientFrame::Embed(request)) => serve_embed(ch, caller, host, admission, request).await,
761        Some(ClientFrame::Cancel { .. }) | None => Ok(()),
762    }
763}
764
765async fn serve_infer(mut ch: Channel, caller: Caller, host: &dyn InferHost, admission: &Admission, mut request: Request) -> Result<(), RemoteError> {
766    let started = Instant::now();
767    let id = request.id.clone();
768    let caller = caller.presenting(request.cert.take());
769    let checked = host.authorize(&caller).and_then(|()| {
770        if matches!(request.input, Input::Prompt(_)) && !request.tools.is_empty() {
771            return Err(RemoteError::BadRequest { message: "a raw prompt takes no tools".into() });
772        }
773        if request.raw && matches!(request.input, Input::Context(_)) {
774            return Err(RemoteError::BadRequest { message: "raw mode takes assembled messages, not a context_ref".into() });
775        }
776        if request.assistant_prefix.as_ref().is_some_and(|p| !p.is_consistent()) {
777            return Err(RemoteError::BadRequest { message: "assistant_prefix lengths do not match its text".into() });
778        }
779        host.open_request(&caller, &request)
780    });
781    let backend = match checked {
782        Ok(b) => b,
783        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
784    };
785    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
786        Waited::Go(p) => p,
787        Waited::Gone => return Ok(()),
788    };
789    let queued = started.elapsed();
790    let resume = backend.resumes();
791    let prefix = request.assistant_prefix.clone().filter(|_| resume);
792    if !resume {
793        request.assistant_prefix = None;
794    }
795    let (text_at, reasoning_at) = prefix.as_ref().map(|p| (p.len, p.reasoning_len)).unwrap_or((0, 0));
796    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: request.attempt, resume }).await?;
797    let accepted = Instant::now();
798
799    let (out, mut pieces) = Output::channel();
800    let cancel = CancelToken::new();
801    let mut framer =
802        Framer { id: id.clone(), text_at, reasoning_at, calls: 0, accepted, first_token: None, early_meta: request.early_meta, meta: None };
803    let mut run = pin!(backend.infer(&request, &out, &cancel));
804    let mut asker_open = true;
805    let mut send_failed = false;
806    let result = loop {
807        tokio::select! {
808            r = &mut run => break r,
809            Some(p) = pieces.recv() => {
810                let Some(f) = framer.frame(p) else { continue };
811                if !send_failed && ch.send_cbor(&f).await.is_err() {
812                    send_failed = true;
813                    cancel.cancel();
814                }
815            }
816            m = ch.rx.recv(), if asker_open => match m {
817                Ok(Some(bytes)) => {
818                    if is_cancel(&bytes, &id) {
819                        cancel.cancel();
820                    }
821                }
822                Ok(None) | Err(_) => {
823                    asker_open = false;
824                    cancel.cancel();
825                }
826            },
827        }
828    };
829    if send_failed || !asker_open {
830        return Ok(());
831    }
832    while let Ok(p) = pieces.try_recv() {
833        if let Some(f) = framer.frame(p) {
834            ch.send_cbor(&f).await?;
835        }
836    }
837    let reply = match result {
838        Ok(mut finish) => {
839            let meta = &mut finish.meta;
840            if let Some(early) = framer.meta.take() {
841                meta.cache_hit |= early.cache_hit;
842                if meta.served_by.is_none() {
843                    meta.served_by = early.served_by;
844                }
845                if meta.revision.is_none() {
846                    meta.revision = early.revision;
847                }
848                if meta.standin.is_none() {
849                    meta.standin = early.standin;
850                }
851            }
852            meta.served_by.get_or_insert_with(|| backend.name());
853            if let Some(p) = &prefix {
854                meta.resumed_from = Some(p.len);
855            }
856            meta.timings.queued_ms = millis(queued);
857            meta.timings.first_token_ms = framer.first_token.map(millis);
858            meta.timings.total_ms = millis(started.elapsed());
859            ServerFrame::Done { id, finish }
860        }
861        Err(_) if cancel.is_cancelled() => ServerFrame::Cancelled { id },
862        Err(error) => ServerFrame::Failed { id, error },
863    };
864    ch.send_cbor(&reply).await
865}
866
867/// Turns backend output into frames with offsets and tool-call indexes.
868struct Framer {
869    id: String,
870    text_at: u64,
871    reasoning_at: u64,
872    calls: u32,
873    accepted: Instant,
874    first_token: Option<Duration>,
875    /// The asker reads `Meta` frames.
876    early_meta: bool,
877    /// Early metadata from the backend, folded into the final `Done`.
878    meta: Option<Meta>,
879}
880
881impl Framer {
882    fn frame(&mut self, p: Piece) -> Option<ServerFrame> {
883        let id = self.id.clone();
884        Some(match p {
885            Piece::Text(text) => {
886                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
887                let offset = self.text_at;
888                self.text_at += chars(&text);
889                ServerFrame::Delta { id, offset, text }
890            }
891            Piece::Reasoning(text) => {
892                self.first_token.get_or_insert_with(|| self.accepted.elapsed());
893                let offset = self.reasoning_at;
894                self.reasoning_at += chars(&text);
895                ServerFrame::Reasoning { id, offset, text }
896            }
897            Piece::ToolCall(call) => {
898                self.calls += 1;
899                ServerFrame::ToolCall { id, index: self.calls - 1, call }
900            }
901            Piece::Usage(usage) => ServerFrame::Usage { id, usage },
902            Piece::Meta(meta) => {
903                self.meta = Some(meta.clone());
904                if !self.early_meta {
905                    return None;
906                }
907                ServerFrame::Meta { id, meta }
908            }
909        })
910    }
911}
912
913async fn serve_embed(
914    mut ch: Channel,
915    caller: Caller,
916    host: &dyn InferHost,
917    admission: &Admission,
918    mut request: EmbedRequest,
919) -> Result<(), RemoteError> {
920    let started = Instant::now();
921    let id = request.id.clone();
922    let caller = caller.presenting(request.cert.take());
923    let backend = match host.authorize(&caller).and_then(|()| host.open_embed(&caller, request.model.as_deref())) {
924        Ok(b) => b,
925        Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
926    };
927    let _permit = match wait_turn(&mut ch, &id, admission, request.priority).await? {
928        Waited::Go(p) => p,
929        Waited::Gone => return Ok(()),
930    };
931    let queued = started.elapsed();
932    ch.send_cbor(&ServerFrame::Accepted { id: id.clone(), model: backend.name(), attempt: 0, resume: false }).await?;
933    let cancel = CancelToken::new();
934    let mut tokens: Option<u64> = None;
935    for (index, input) in request.inputs.iter().enumerate() {
936        let vector = tokio::select! {
937            v = backend.embed_counted(input, &cancel) => v,
938            m = async { loop {
939                match ch.rx.recv().await {
940                    Ok(Some(bytes)) if is_cancel(&bytes, &id) => return true,
941                    Ok(Some(_)) => {}
942                    Ok(None) | Err(_) => return false,
943                }
944            } } => {
945                cancel.cancel();
946                return if m { ch.send_cbor(&ServerFrame::Cancelled { id }).await } else { Ok(()) };
947            }
948        };
949        match vector {
950            Ok((v, n)) => {
951                if let Some(n) = n {
952                    *tokens.get_or_insert(0) += n;
953                }
954                ch.send_cbor(&ServerFrame::Embedding { id: id.clone(), index: index as u32, vector: f32_bytes(&v) }).await?
955            }
956            Err(error) => return ch.send_cbor(&ServerFrame::Failed { id, error }).await,
957        }
958    }
959    let mut finish = Finish::new("stop");
960    finish.usage = tokens.map(|n| Usage::new(n, 0));
961    finish.meta.served_by = Some(backend.name());
962    finish.meta.timings.queued_ms = millis(queued);
963    finish.meta.timings.total_ms = millis(started.elapsed());
964    ch.send_cbor(&ServerFrame::Done { id, finish }).await
965}