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