Skip to main content

weirdnet_openai/
lib.rs

1//! A loopback-only OpenAI-compatible bridge over a `weirdnet-agent` [`Pool`].
2//!
3//! Local tools that speak the OpenAI API (editors, notebooks, `curl`) reach the user's
4//! inference nodes through it: `/v1/chat/completions` and `/v1/completions` (streaming or not),
5//! `/v1/models` (the pool catalog), `/v1/embeddings`, `/v1/audio/speech` and
6//! `/v1/audio/transcriptions`, plus Prometheus `/metrics`.
7//!
8//! It binds `127.0.0.1` only, checks the `Host` header against its own address (DNS rebinding),
9//! requires a bearer token of at least 16 characters (compared in constant time), and sends no
10//! CORS headers, so web pages can't use it. Answers carry `x-weirdnet-model`, and
11//! `x-weirdnet-cache: hit` and `x-weirdnet-standin` when the pool says so; a request with
12//! `x-wait: 1` waits for its model instead of a stand-in. A request skips the nodes' answer cache
13//! with `"cache": false` or `x-weirdnet-cache: off`, and refreshes it with `"cache": "refresh"`
14//! or `x-weirdnet-cache: refresh` (infer/2 `Request::cache`, `weirdnet-agent` 0.5.1).
15//!
16//! Chat messages may carry image (`image_url`, a `data:image/...` URL), audio (`input_audio`) and
17//! video (`video_url`, a `data:video/...` URL; remote URLs are refused, never fetched) parts. They
18//! go to the pool unchanged, which sends them only to a model whose catalog entry takes them; when
19//! none does the answer is 400. `/v1/models` lists `weirdnet.vision`, `weirdnet.audio` and
20//! `weirdnet.video` per model (also together as `weirdnet.inputs`), `weirdnet.purpose` (`chat`,
21//! `embed`, `transcribe`, `speak`, ...), `weirdnet.speech` for a speaking model that reports a
22//! profile (catalog/1 `CatalogModel::speech`, `weirdnet-agent` 0.5.11), `weirdnet.base` for a LoRA adapter (its base model), and
23//! `weirdnet.origin` (`hub`, `upload` or `train`) and `weirdnet.license` when the node says
24//! (catalog/1 `CatalogModel::origin`/`license`, `weirdnet-agent` 0.5.4; `null` otherwise). A body's
25//! `"adapter_scale"` sets how strongly an adapter applies for that request (infer/2
26//! `Request::adapter_scale`, `weirdnet-agent` 0.5.2; llama.cpp nodes only).
27//!
28//! Bodies may be up to [`DEFAULT_MAX_REQUEST_BYTES`] (32 MiB) unless the bridge is set otherwise
29//! ([`Bridge::with_max_request_bytes`]). A larger body is refused with 413
30//! (`request_too_large`) whose message names the limit, and the `x-weirdnet-max-request-bytes`
31//! header carries it. `/v1/models` reports it per model as `weirdnet.max_request_bytes` (the
32//! smaller of the bridge's and the node's), with the model's media limits under
33//! `weirdnet.limits` (catalog/1 `CatalogModel::limits`, `weirdnet-agent` 0.5.7; only the limits the
34//! node knows).
35//!
36//! `POST /v1/audio/speech` speaks text over infer/2 `Speak` ([`request::speech`] lists the body):
37//! the request is checked against the catalog first, so a voice the model lacks (OpenAI's `alloy`,
38//! say) is a 400 that lists the model's presets, never mapped to another voice. The answer's
39//! `Content-Type` is the real format (`audio/pcm;rate=24000` for raw PCM), with
40//! `x-audio-sample-rate` when the node knows it; `stream_format: "audio"` streams the bytes as they
41//! come. `POST /v1/audio/transcriptions` (multipart: `file`, `model`, `language`, `prompt`,
42//! `response_format` `json`, `verbose_json`, `text`, `srt` or `vtt`, and
43//! `timestamp_granularities[]=segment`) runs infer/2 `Transcribe`. Both are bounded by the same
44//! request limit (a 413 with `x-weirdnet-max-request-bytes`); neither is cached.
45//!
46//! `/v1/completions` sends the prompt as an infer/2 raw prompt (`weirdnet-agent` 0.4.1); nodes
47//! that can't take one answer 501. A streamed answer waits up to [`EARLY_META_WAIT`] after a node
48//! accepts it for early metadata, so `x-weirdnet-cache: hit` is sent on streams too.
49
50mod audio;
51pub mod request;
52
53use std::convert::Infallible;
54use std::future::Future;
55use std::net::SocketAddr;
56use std::sync::Arc;
57use std::sync::atomic::{AtomicU64, Ordering};
58use std::time::{Duration, SystemTime, UNIX_EPOCH};
59
60use axum::Router;
61use axum::body::Bytes;
62use axum::extract::{DefaultBodyLimit, Request, State};
63use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header};
64use axum::middleware::{self, Next};
65use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
66use axum::response::{IntoResponse, Response};
67use axum::routing::{get, post};
68use futures::StreamExt;
69use serde_json::{Value, json};
70use tokio::sync::mpsc;
71use weirdnet_agent::CancelToken;
72use weirdnet_agent::remote::RemoteError;
73use weirdnet_agent::remote::infer::v2::{Meta, Usage};
74use weirdnet_agent::remote::pool::{Answer, EventSink, Interrupted, NoEvents, Pool, PoolEvent};
75
76/// How long a streamed answer's headers wait, after a node accepted it, for early metadata (a
77/// cache hit) or the first output. A node that sends neither in time gets headers without it.
78pub const EARLY_META_WAIT: Duration = Duration::from_millis(1500);
79
80/// The largest request body a bridge accepts unless set otherwise: 32 MiB.
81pub const DEFAULT_MAX_REQUEST_BYTES: usize = 32 << 20;
82
83/// Where the bridge listens and the token it requires.
84#[derive(Clone)]
85pub struct BridgeOptions {
86    /// Port on 127.0.0.1; 0 picks a free one (tests).
87    pub port: u16,
88    pub token: String,
89}
90
91impl BridgeOptions {
92    pub fn new(port: u16, token: impl Into<String>) -> Self {
93        Self { port, token: token.into() }
94    }
95}
96
97impl std::fmt::Debug for BridgeOptions {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_struct("BridgeOptions").field("port", &self.port).field("token", &"<redacted>").finish()
100    }
101}
102
103/// A bound, not yet serving, bridge.
104pub struct Bridge {
105    listener: tokio::net::TcpListener,
106    token: String,
107    max_request_bytes: usize,
108}
109
110#[derive(Default)]
111struct Metrics {
112    requests: AtomicU64,
113    errors: AtomicU64,
114    cache_hits: AtomicU64,
115    standins: AtomicU64,
116}
117
118struct AppState {
119    pool: Arc<Pool>,
120    token: String,
121    port: u16,
122    max_request_bytes: usize,
123    metrics: Metrics,
124}
125
126impl Bridge {
127    /// Binds `127.0.0.1:port`. Refuses a token shorter than 16 characters.
128    pub async fn bind(opts: BridgeOptions) -> std::io::Result<Self> {
129        if opts.token.len() < 16 {
130            return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the bridge token must be at least 16 characters"));
131        }
132        let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], opts.port))).await?;
133        Ok(Self { listener, token: opts.token, max_request_bytes: DEFAULT_MAX_REQUEST_BYTES })
134    }
135
136    /// The largest request body accepted, in bytes (at least 1; default
137    /// [`DEFAULT_MAX_REQUEST_BYTES`]). Larger bodies get 413 naming the limit. infer/2 carries at
138    /// most `weirdnet_agent::remote::codec::MAX_FRAME` (32 MiB) per message, so a higher limit
139    /// only helps bodies that shrink on the way to the pool.
140    pub fn with_max_request_bytes(mut self, bytes: usize) -> Self {
141        self.max_request_bytes = bytes.max(1);
142        self
143    }
144
145    /// See [`Bridge::with_max_request_bytes`].
146    pub fn max_request_bytes(&self) -> usize {
147        self.max_request_bytes
148    }
149
150    pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
151        self.listener.local_addr()
152    }
153
154    /// Serves until `shutdown` resolves.
155    pub async fn serve(self, pool: Arc<Pool>, shutdown: impl Future<Output = ()> + Send + 'static) -> std::io::Result<()> {
156        let port = self.listener.local_addr()?.port();
157        let state = Arc::new(AppState { pool, token: self.token, port, max_request_bytes: self.max_request_bytes, metrics: Metrics::default() });
158        axum::serve(self.listener, router(state)).with_graceful_shutdown(shutdown).await
159    }
160}
161
162fn router(state: Arc<AppState>) -> Router {
163    Router::new()
164        .route("/v1/models", get(models))
165        .route("/v1/chat/completions", post(chat))
166        .route("/v1/completions", post(completions))
167        .route("/v1/embeddings", post(embeddings))
168        .route("/v1/audio/speech", post(audio::speech))
169        .route("/v1/audio/transcriptions", post(audio::transcriptions))
170        .route("/metrics", get(metrics))
171        .fallback(not_found)
172        .layer(DefaultBodyLimit::max(state.max_request_bytes))
173        .layer(middleware::from_fn_with_state(state.clone(), size_limit))
174        .layer(middleware::from_fn_with_state(state.clone(), guard))
175        .with_state(state)
176}
177
178/// Host check, then the token, on every request.
179async fn guard(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
180    let host = req.headers().get(header::HOST).and_then(|h| h.to_str().ok()).unwrap_or("");
181    if host != format!("127.0.0.1:{}", st.port) && host != format!("localhost:{}", st.port) {
182        return error(StatusCode::FORBIDDEN, "forbidden_host", "the bridge answers only 127.0.0.1 and localhost");
183    }
184    let presented = req.headers().get(header::AUTHORIZATION).and_then(|h| h.to_str().ok()).and_then(|h| h.strip_prefix("Bearer ")).unwrap_or("");
185    if !same(presented.as_bytes(), st.token.as_bytes()) {
186        return error(StatusCode::UNAUTHORIZED, "invalid_api_key", "missing or wrong bridge token");
187    }
188    st.metrics.requests.fetch_add(1, Ordering::Relaxed);
189    next.run(req).await
190}
191
192/// How much of a body over the limit is still read (and dropped), so the client finishes sending
193/// and reads the 413 instead of a broken connection; past this the connection is just closed.
194const DRAIN_BYTES: u64 = 64 << 20;
195
196/// Bodies over the limit get a 413 that names it: the body is read up to the limit (or not at
197/// all when `Content-Length` is over it), the rest is drained, and handlers only ever see bodies
198/// that fit.
199async fn size_limit(State(st): State<Arc<AppState>>, req: Request, next: Next) -> Response {
200    let limit = st.max_request_bytes;
201    let declared = req.headers().get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.trim().parse::<u64>().ok());
202    let mut over = declared.is_some_and(|n| n > limit as u64);
203    let (parts, body) = req.into_parts();
204    let mut stream = body.into_data_stream();
205    let mut buf: Vec<u8> = Vec::with_capacity(declared.map_or(0, |n| n.min(limit as u64) as usize));
206    let mut seen: u64 = 0;
207    while let Some(chunk) = stream.next().await {
208        let Ok(chunk) = chunk else {
209            return error(StatusCode::BAD_REQUEST, "bad_request", "could not read the request body");
210        };
211        seen += chunk.len() as u64;
212        if !over && buf.len() + chunk.len() > limit {
213            over = true;
214            buf = Vec::new();
215        }
216        if over {
217            if seen > (limit as u64).saturating_add(DRAIN_BYTES) {
218                break;
219            }
220            continue;
221        }
222        buf.extend_from_slice(&chunk);
223    }
224    if over {
225        return too_large(&st);
226    }
227    next.run(Request::from_parts(parts, axum::body::Body::from(buf))).await
228}
229
230fn too_large(st: &AppState) -> Response {
231    st.metrics.errors.fetch_add(1, Ordering::Relaxed);
232    let limit = st.max_request_bytes;
233    let message = format!(
234        "the request body is larger than this bridge's limit of {limit} bytes ({}); send less, or raise the bridge's max_request_bytes",
235        human_bytes(limit)
236    );
237    let mut r = error(StatusCode::PAYLOAD_TOO_LARGE, "request_too_large", &message);
238    r.headers_mut().insert(HeaderName::from_static("x-weirdnet-max-request-bytes"), HeaderValue::from(limit as u64));
239    r
240}
241
242/// `32 MiB`, `512 KiB` or `1000 bytes`.
243fn human_bytes(n: usize) -> String {
244    match n {
245        n if n >= 1 << 20 && n % (1 << 20) == 0 => format!("{} MiB", n >> 20),
246        n if n >= 1 << 20 => format!("{:.1} MiB", n as f64 / f64::from(1 << 20)),
247        n if n >= 1 << 10 && n % (1 << 10) == 0 => format!("{} KiB", n >> 10),
248        n => format!("{n} bytes"),
249    }
250}
251
252fn same(a: &[u8], b: &[u8]) -> bool {
253    if a.len() != b.len() {
254        return false;
255    }
256    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
257}
258
259fn error(status: StatusCode, code: &str, message: &str) -> Response {
260    let kind = if status.is_server_error() { "server_error" } else { "invalid_request_error" };
261    (status, axum::Json(json!({"error": {"message": message, "type": kind, "code": code}}))).into_response()
262}
263
264/// The HTTP status and code for a pool error.
265pub fn status_of(e: &RemoteError) -> (StatusCode, &'static str) {
266    match e {
267        RemoteError::Unavailable { message } if message.starts_with("unknown model") => (StatusCode::NOT_FOUND, "model_not_found"),
268        RemoteError::BadRequest { .. } => (StatusCode::BAD_REQUEST, "bad_request"),
269        RemoteError::Busy => (StatusCode::SERVICE_UNAVAILABLE, "busy"),
270        RemoteError::Unavailable { .. } | RemoteError::Unreachable { .. } => (StatusCode::SERVICE_UNAVAILABLE, "unavailable"),
271        RemoteError::Refused { .. } => (StatusCode::FORBIDDEN, "refused"),
272        RemoteError::Unsupported { .. } => (StatusCode::NOT_IMPLEMENTED, "unsupported"),
273        RemoteError::Timeout | RemoteError::Stalled { .. } => (StatusCode::GATEWAY_TIMEOUT, "timeout"),
274        _ => (StatusCode::BAD_GATEWAY, "engine_error"),
275    }
276}
277
278fn pool_error(st: &AppState, e: &RemoteError) -> Response {
279    st.metrics.errors.fetch_add(1, Ordering::Relaxed);
280    let (status, code) = status_of(e);
281    let mut r = error(status, code, &e.to_string());
282    if matches!(e, RemoteError::Busy) {
283        r.headers_mut().insert(header::RETRY_AFTER, HeaderValue::from(1));
284    }
285    r
286}
287
288async fn not_found() -> Response {
289    error(StatusCode::NOT_FOUND, "not_found", "no such endpoint")
290}
291
292async fn metrics(State(st): State<Arc<AppState>>) -> Response {
293    let m = &st.metrics;
294    let body = format!(
295        "# TYPE weirdnet_bridge_requests_total counter\nweirdnet_bridge_requests_total {}\n# TYPE weirdnet_bridge_errors_total counter\nweirdnet_bridge_errors_total {}\n# TYPE weirdnet_bridge_cache_hits_total counter\nweirdnet_bridge_cache_hits_total {}\n# TYPE weirdnet_bridge_standin_total counter\nweirdnet_bridge_standin_total {}\n",
296        m.requests.load(Ordering::Relaxed),
297        m.errors.load(Ordering::Relaxed),
298        m.cache_hits.load(Ordering::Relaxed),
299        m.standins.load(Ordering::Relaxed)
300    );
301    ([(header::CONTENT_TYPE, "text/plain; version=0.0.4")], body).into_response()
302}
303
304async fn models(State(st): State<Arc<AppState>>) -> Response {
305    match st.pool.catalog().await {
306        Ok(catalog) => {
307            let data: Vec<Value> = catalog
308                .models
309                .iter()
310                .map(|m| {
311                    let max_request_bytes = m.limits.max_request_bytes.map_or(st.max_request_bytes as u64, |n| n.min(st.max_request_bytes as u64));
312                    let mut limits = m.limits;
313                    limits.max_request_bytes = Some(max_request_bytes);
314                    let mut v = json!({
315                        "id": m.id,
316                        "object": "model",
317                        "created": 0,
318                        "owned_by": "weirdnet",
319                        "weirdnet": {
320                            "state": m.state, "purpose": m.purpose, "replicas": m.replicas, "context": m.context, "revision": m.revision,
321                            "vision": m.inputs.vision, "audio": m.inputs.audio, "video": m.inputs.video,
322                            "inputs": {"vision": m.inputs.vision, "audio": m.inputs.audio, "video": m.inputs.video},
323                            "base": m.base, "origin": m.origin, "license": m.license,
324                            "max_request_bytes": max_request_bytes, "limits": limits,
325                        },
326                    });
327                    if let Some(speech) = &m.speech {
328                        v["weirdnet"]["speech"] = json!(speech);
329                    }
330                    v
331                })
332                .collect();
333            axum::Json(json!({"object": "list", "data": data})).into_response()
334        }
335        Err(e) => pool_error(&st, &e),
336    }
337}
338
339/// The `x-weirdnet-cache` header with the body's `cache`: the stricter wins. A bad header is a
340/// 400 (the returned response), so an eval that asked to skip the cache never silently reads it.
341fn apply_cache_header(h: &HeaderMap, req: &mut weirdnet_agent::remote::infer::v2::Request) -> Option<Response> {
342    let v = h.get("x-weirdnet-cache")?;
343    match v.to_str().ok().map(request::cache_header) {
344        Some(Ok(mode)) => {
345            req.cache = request::stricter(req.cache, mode);
346            None
347        }
348        Some(Err(e)) => Some(error(StatusCode::BAD_REQUEST, "bad_request", &e.0)),
349        None => Some(error(StatusCode::BAD_REQUEST, "bad_request", "`x-weirdnet-cache` must be off, refresh or use")),
350    }
351}
352
353/// `x-wait: 1` asks to wait for the requested model instead of a stand-in.
354fn wants_wait(h: &HeaderMap) -> bool {
355    h.get("x-wait").and_then(|v| v.to_str().ok()).is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes"))
356}
357
358fn json_body(body: &Bytes) -> Result<Value, String> {
359    serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {e}"))
360}
361
362fn header_value(v: &str) -> Option<HeaderValue> {
363    HeaderValue::from_str(v).ok()
364}
365
366/// `x-weirdnet-*` headers.
367fn reply_headers(st: &AppState, model: &str, cache_hit: bool, standin: Option<&str>) -> HeaderMap {
368    let mut headers = HeaderMap::new();
369    if let Some(v) = header_value(model) {
370        headers.insert(HeaderName::from_static("x-weirdnet-model"), v);
371    }
372    if cache_hit {
373        st.metrics.cache_hits.fetch_add(1, Ordering::Relaxed);
374        headers.insert(HeaderName::from_static("x-weirdnet-cache"), HeaderValue::from_static("hit"));
375    }
376    if let Some(v) = standin.and_then(header_value) {
377        st.metrics.standins.fetch_add(1, Ordering::Relaxed);
378        headers.insert(HeaderName::from_static("x-weirdnet-standin"), v);
379    }
380    headers
381}
382
383fn usage_json(u: Option<Usage>) -> Value {
384    let u = u.unwrap_or_default();
385    let mut v =
386        json!({"prompt_tokens": u.prompt_tokens, "completion_tokens": u.completion_tokens, "total_tokens": u.prompt_tokens + u.completion_tokens});
387    if u.cached_tokens > 0 {
388        v["prompt_tokens_details"] = json!({"cached_tokens": u.cached_tokens});
389    }
390    if u.reasoning_tokens > 0 {
391        v["completion_tokens_details"] = json!({"reasoning_tokens": u.reasoning_tokens});
392    }
393    v
394}
395
396fn weirdnet_json(meta: &Meta, standin: Option<&str>) -> Value {
397    json!({"standin": standin.or(meta.standin.as_deref()), "cache_hit": meta.cache_hit, "served_by": meta.served_by})
398}
399
400/// `/v1/completions`: a raw prompt over infer/2.
401async fn completions(State(st): State<Arc<AppState>>, h: HeaderMap, body: Bytes) -> Response {
402    let body = match json_body(&body) {
403        Ok(v) => v,
404        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e),
405    };
406    let (mut req, stream) = match request::completion(body) {
407        Ok(r) => r,
408        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e.0),
409    };
410    req.wait_for_model |= wants_wait(&h);
411    if let Some(r) = apply_cache_header(&h, &mut req) {
412        return r;
413    }
414    answer(st, req, stream, Shape::Text).await
415}
416
417async fn embeddings(State(st): State<Arc<AppState>>, body: Bytes) -> Response {
418    let body = match json_body(&body) {
419        Ok(v) => v,
420        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e),
421    };
422    let req = match request::embed(body) {
423        Ok(r) => r,
424        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e.0),
425    };
426    match st.pool.embed(req, &CancelToken::new()).await {
427        Ok(e) => {
428            let headers = reply_headers(&st, &e.model, e.meta.cache_hit, e.meta.standin.as_deref());
429            let data: Vec<Value> = e.vectors.iter().enumerate().map(|(i, v)| json!({"object": "embedding", "index": i, "embedding": v})).collect();
430            // Nodes before weirdnet-agent 0.4.1 report no count: 0.
431            let tokens = e.usage.map(|u| u.prompt_tokens).unwrap_or(0);
432            let body = json!({"object": "list", "model": e.model, "data": data, "usage": {"prompt_tokens": tokens, "total_tokens": tokens}});
433            (headers, axum::Json(body)).into_response()
434        }
435        Err(e) => pool_error(&st, &e),
436    }
437}
438
439/// Cancels the pool request when the HTTP response (or stream) is dropped.
440struct CancelOnDrop(CancelToken);
441
442impl Drop for CancelOnDrop {
443    fn drop(&mut self) {
444        self.0.cancel();
445    }
446}
447
448/// Pool events into a channel, for streaming.
449struct Forward(mpsc::UnboundedSender<Step>);
450
451enum Step {
452    Event(PoolEvent),
453    End(Box<Result<Answer, Interrupted>>),
454}
455
456impl EventSink for Forward {
457    fn event(&self, event: PoolEvent) {
458        let _ = self.0.send(Step::Event(event));
459    }
460}
461
462fn now_secs() -> u64 {
463    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
464}
465
466async fn chat(State(st): State<Arc<AppState>>, h: HeaderMap, body: Bytes) -> Response {
467    let body = match json_body(&body) {
468        Ok(v) => v,
469        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e),
470    };
471    let (mut req, stream) = match request::chat(body) {
472        Ok(r) => r,
473        Err(e) => return error(StatusCode::BAD_REQUEST, "bad_request", &e.0),
474    };
475    req.wait_for_model |= wants_wait(&h);
476    if let Some(r) = apply_cache_header(&h, &mut req) {
477        return r;
478    }
479    answer(st, req, stream, Shape::Chat).await
480}
481
482/// Which OpenAI answer shape: chat completions or text completions.
483#[derive(Clone, Copy, PartialEq, Eq)]
484enum Shape {
485    Chat,
486    Text,
487}
488
489impl Shape {
490    fn id(self) -> String {
491        match self {
492            Shape::Chat => format!("chatcmpl-{}", random_hex(12)),
493            Shape::Text => format!("cmpl-{}", random_hex(12)),
494        }
495    }
496
497    fn whole(self, id: &str, created: u64, a: &Answer) -> Value {
498        match self {
499            Shape::Chat => completion(id, created, a),
500            Shape::Text => text_completion(id, created, a),
501        }
502    }
503}
504
505/// Runs `req` on the pool and answers in `shape`, whole or streamed.
506async fn answer(st: Arc<AppState>, req: weirdnet_agent::remote::infer::v2::Request, stream: bool, shape: Shape) -> Response {
507    let id = shape.id();
508    let created = now_secs();
509    let cancel = CancelToken::new();
510    if !stream {
511        let guard = CancelOnDrop(cancel.clone());
512        let answer = st.pool.infer(req, &NoEvents, &cancel).await;
513        drop(guard);
514        return match answer {
515            Ok(a) => {
516                let headers = reply_headers(&st, &a.model, a.meta.cache_hit, a.meta.standin.as_deref());
517                let mut v = shape.whole(&id, created, &a);
518                v["weirdnet"] = weirdnet_json(&a.meta, None);
519                (headers, axum::Json(v)).into_response()
520            }
521            Err(i) => pool_error(&st, &i.error),
522        };
523    }
524
525    // Streaming: run the pool request in a task; answer once a node accepted it (so failures
526    // before that are proper HTTP errors and `x-weirdnet-model` is known), and the node sent
527    // early metadata or its first output, or EARLY_META_WAIT passed.
528    let requested = req.model.clone();
529    let (tx, mut rx) = mpsc::unbounded_channel();
530    let pool = st.pool.clone();
531    let c = cancel.clone();
532    tokio::spawn(async move {
533        let sink = Forward(tx.clone());
534        let r = pool.infer(req, &sink, &c).await;
535        let _ = tx.send(Step::End(Box::new(r)));
536    });
537    let guard = CancelOnDrop(cancel);
538    let mut pending = Vec::new();
539    let mut ended = false;
540    let model = loop {
541        match rx.recv().await {
542            Some(Step::Event(PoolEvent::Accepted { model, .. })) => break model,
543            Some(Step::Event(ev)) => pending.push(Step::Event(ev)),
544            Some(Step::End(r)) => match *r {
545                Ok(a) => {
546                    let model = a.model.clone();
547                    pending.push(Step::End(Box::new(Ok(a))));
548                    ended = true;
549                    break model;
550                }
551                Err(i) => return pool_error(&st, &i.error),
552            },
553            None => return pool_error(&st, &RemoteError::Closed),
554        }
555    };
556    let mut early = Meta::default();
557    if ended {
558        if let Some(Step::End(r)) = pending.last()
559            && let Ok(a) = r.as_ref()
560        {
561            early = a.meta.clone();
562        }
563    } else {
564        let deadline = tokio::time::Instant::now() + EARLY_META_WAIT;
565        loop {
566            let step = match tokio::time::timeout_at(deadline, rx.recv()).await {
567                Err(_) | Ok(None) => break,
568                Ok(Some(s)) => s,
569            };
570            match step {
571                Step::Event(PoolEvent::Meta(m)) => {
572                    early = m;
573                    break;
574                }
575                Step::Event(ev @ (PoolEvent::Text(_) | PoolEvent::Reasoning(_) | PoolEvent::ToolCall(_))) => {
576                    pending.push(Step::Event(ev));
577                    break;
578                }
579                Step::End(r) => {
580                    if let Ok(a) = r.as_ref() {
581                        early = a.meta.clone();
582                    }
583                    pending.push(Step::End(r));
584                    break;
585                }
586                other => pending.push(other),
587            }
588        }
589    }
590    let standin = requested.as_deref().filter(|r| *r != model).map(|_| model.clone()).or_else(|| early.standin.clone());
591    let headers = reply_headers(&st, &model, early.cache_hit, standin.as_deref());
592    let counted = early.cache_hit;
593    let chunk = {
594        let (id, model) = (id.clone(), model.clone());
595        move |delta: Value, finish: Option<&str>, extra: Option<(Value, Value)>| -> Result<SseEvent, Infallible> {
596            let mut v = match shape {
597                Shape::Chat => {
598                    json!({"id": id, "object": "chat.completion.chunk", "created": created, "model": model, "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]})
599                }
600                Shape::Text => {
601                    let text = delta.get("content").and_then(Value::as_str).unwrap_or("");
602                    json!({"id": id, "object": "text_completion", "created": created, "model": model, "choices": [{"index": 0, "text": text, "logprobs": null, "finish_reason": finish}]})
603                }
604            };
605            if let Some((usage, weirdnet)) = extra {
606                v["usage"] = usage;
607                v["weirdnet"] = weirdnet;
608            }
609            Ok(SseEvent::default().data(v.to_string()))
610        }
611    };
612    let st2 = st.clone();
613    let body = async_stream(move |out| async move {
614        let _guard = guard;
615        let mut tool_index = 0usize;
616        let mut usage = None;
617        if shape == Shape::Chat {
618            out(chunk(json!({"role": "assistant", "content": ""}), None, None));
619        }
620        let mut steps = pending.into_iter();
621        loop {
622            let step = match steps.next() {
623                Some(s) => s,
624                None => match rx.recv().await {
625                    Some(s) => s,
626                    None => break,
627                },
628            };
629            match step {
630                Step::Event(PoolEvent::Text(t)) => out(chunk(json!({"content": t}), None, None)),
631                Step::Event(PoolEvent::Reasoning(t)) if shape == Shape::Chat => out(chunk(json!({"reasoning_content": t}), None, None)),
632                Step::Event(PoolEvent::ToolCall(call)) if shape == Shape::Chat => {
633                    let call = json!({"index": tool_index, "id": call.id, "type": "function", "function": {"name": call.name, "arguments": call.arguments.to_string()}});
634                    tool_index += 1;
635                    out(chunk(json!({"tool_calls": [call]}), None, None));
636                }
637                Step::Event(PoolEvent::Usage(u)) => usage = Some(u),
638                Step::Event(_) => {}
639                Step::End(r) => {
640                    match *r {
641                        Ok(a) => {
642                            if a.meta.cache_hit && !counted {
643                                st2.metrics.cache_hits.fetch_add(1, Ordering::Relaxed);
644                            }
645                            let finish = a.finish_reason.as_deref().unwrap_or("stop");
646                            let extra = (usage_json(a.usage.or(usage)), weirdnet_json(&a.meta, standin.as_deref()));
647                            out(chunk(json!({}), Some(finish), Some(extra)));
648                            out(Ok(SseEvent::default().data("[DONE]")));
649                        }
650                        Err(i) => {
651                            st2.metrics.errors.fetch_add(1, Ordering::Relaxed);
652                            let (_, code) = status_of(&i.error);
653                            let e = json!({"error": {"message": i.error.to_string(), "type": "server_error", "code": code}});
654                            out(Ok(SseEvent::default().data(e.to_string())));
655                        }
656                    }
657                    break;
658                }
659            }
660        }
661    });
662    (headers, Sse::new(body).keep_alive(KeepAlive::default())).into_response()
663}
664
665/// A stream fed by an async producer through a channel.
666fn async_stream<F, Fut>(produce: F) -> impl futures::Stream<Item = Result<SseEvent, Infallible>> + Send
667where
668    F: FnOnce(Box<dyn Fn(Result<SseEvent, Infallible>) + Send + Sync>) -> Fut + Send + 'static,
669    Fut: Future<Output = ()> + Send + 'static,
670{
671    let (tx, rx) = mpsc::unbounded_channel();
672    let task = tokio::spawn(produce(Box::new(move |ev| {
673        let _ = tx.send(ev);
674    })));
675    // Dropping the response stream aborts the producer, which cancels the pool request.
676    struct Abort(tokio::task::JoinHandle<()>);
677    impl Drop for Abort {
678        fn drop(&mut self) {
679            self.0.abort();
680        }
681    }
682    let abort = Abort(task);
683    futures::stream::unfold((rx, abort), |(mut rx, abort)| async move { rx.recv().await.map(|ev| (ev, (rx, abort))) })
684}
685
686fn completion(id: &str, created: u64, a: &Answer) -> Value {
687    // A continued answer (`continue_final_message`) returns only the new text, as vLLM does.
688    let mut message = json!({"role": "assistant", "content": a.continuation()});
689    if !a.reasoning.is_empty() {
690        message["reasoning_content"] = a.reasoning.clone().into();
691    }
692    if !a.tool_calls.is_empty() {
693        message["tool_calls"] = a
694            .tool_calls
695            .iter()
696            .map(|c| json!({"id": c.id, "type": "function", "function": {"name": c.name, "arguments": c.arguments.to_string()}}))
697            .collect::<Vec<_>>()
698            .into();
699    }
700    json!({
701        "id": id,
702        "object": "chat.completion",
703        "created": created,
704        "model": a.model,
705        "choices": [{"index": 0, "message": message, "finish_reason": a.finish_reason.as_deref().unwrap_or("stop")}],
706        "usage": usage_json(a.usage),
707    })
708}
709
710fn text_completion(id: &str, created: u64, a: &Answer) -> Value {
711    json!({
712        "id": id,
713        "object": "text_completion",
714        "created": created,
715        "model": a.model,
716        "choices": [{"index": 0, "text": a.text, "logprobs": null, "finish_reason": a.finish_reason.as_deref().unwrap_or("stop")}],
717        "usage": usage_json(a.usage),
718    })
719}
720
721/// A new random bridge token (32 bytes, hex).
722pub fn new_token() -> String {
723    random_hex(32)
724}
725
726fn random_hex(bytes: usize) -> String {
727    let mut buf = vec![0u8; bytes];
728    getrandom::fill(&mut buf).expect("the OS RNG is available");
729    buf.iter().map(|b| format!("{b:02x}")).collect()
730}