llmman 0.1.689

Run any agent on any model, models stored as OCI images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! The last step of a route that reached a backend: the answer on its
//! way to the client, and — for the pass-through helpers — the request
//! on its way out.
//!
//! Three shapes, by how much of the body each has to read. [`relay`]
//! forwards the bytes untouched; the `*_rewriting_model` family reads
//! far enough to put the canonical name back in the `"model"` field a
//! backend addressed by another name echoes (see `backend_wire_model`);
//! [`convert_upstream`] rebuilds the whole stream through an
//! [`SseConverter`], so a chat-completions answer can come back on
//! `/v1/messages` or `/v1/responses`.
//!
//! Each of them moves the [`ActivityGuard`] into the stream it returns
//! rather than dropping it on the way out — see that guard's own doc
//! comment for what goes wrong otherwise.

use anyhow::Context;
use axum::body::{Body, Bytes};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use futures::StreamExt;
use reqwest::Client;

use super::openai::merged_after_refusal;
use super::sched::ActivityGuard;
use super::stream::bytes_to_lines;
use super::{
    messages, responses, AppError, ChatBody, ChatUpstream, Target, CHAT_COMPLETIONS_ROUTE,
};

/// POSTs `body` to `route` on `target` with the caller's `content-type`;
/// the request half of every `proxy*` helper. A local chat template that
/// refuses adjacent same-role messages is asked again with them merged.
async fn send_proxied(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
) -> Result<reqwest::Response, AppError> {
    let resp = post_proxied(client, target, route, headers, body.clone()).await?;
    if route != CHAT_COMPLETIONS_ROUTE
        || !matches!(target, Target::Local(_))
        || resp.status() != StatusCode::BAD_REQUEST
    {
        return Ok(resp);
    }
    // A refusal is small and ends before any output: read it, and hand it
    // back as it came unless it is this one.
    let (status, reply_headers) = (resp.status(), resp.headers().clone());
    let reply = resp
        .bytes()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?;
    if let Some(merged) = merged_after_refusal(target, status, &reply, &body) {
        return post_proxied(client, target, route, headers, merged).await;
    }
    let mut refusal = axum::http::Response::new(reply);
    *refusal.status_mut() = status;
    *refusal.headers_mut() = reply_headers;
    Ok(refusal.into())
}

async fn post_proxied(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
) -> Result<reqwest::Response, AppError> {
    // `Bytes` clones are refcounted, not copies — passing `body` straight
    // through (reqwest::Body: From<Bytes>) avoids an extra full-size
    // allocation that `body.to_vec()` would add on top of it, which
    // matters most for large multipart audio uploads.
    let mut req = target.authorize(client.post(target.url(route)).body(body));
    if let Some(ct) = headers.get("content-type") {
        req = req.header("content-type", ct);
    }
    Ok(req
        .send()
        .await
        .with_context(|| format!("proxy request to {}", target.describe()))?)
}

pub(super) async fn proxy(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
) -> Result<Response, AppError> {
    let resp = send_proxied(client, target, route, headers, body).await?;
    Ok(relay(resp, activity))
}

/// The relay half of [`proxy`], split out so `remote_responses` can
/// inspect the status before deciding to relay.
pub(super) fn relay(resp: reqwest::Response, activity: ActivityGuard) -> Response {
    let status = resp.status();
    let resp_headers = resp.headers().clone();

    // Moved into the stream below (see ActivityGuard's doc comment) so it
    // isn't dropped — resetting this model's idle clock — until the whole
    // response body has actually been relayed.
    let stream = resp.bytes_stream().map(move |item| {
        let _activity = &activity;
        item.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    });

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(stream)).unwrap()
}

// ---------------------------------------------------------------------------
// Proxy helpers – like `proxy` above, but for a request whose backend
// needed a *different* "model" name than the client itself asked for
// (see `backend_wire_model`'s own doc comment — only ever true for an
// `Engine::Mlx` backend, addressed by its real on-disk directory path
// rather than a human-readable name). `mlx_lm.server` echoes whatever
// "model" value it received straight back into every response it sends
// — the one non-streamed JSON body for `stream: false`, and *every*
// individual `data: {...}` SSE chunk for `stream: true` — so a plain
// byte-for-byte relay like `proxy` would leak that internal directory
// path back to the client instead of the name it actually asked for.
// These two rewrite just that one field back to the canonical name
// before any of it reaches the client; every other field, and (for the
// streaming variant) the SSE framing itself, passes through unchanged.
// ---------------------------------------------------------------------------

/// Sets `value["model"]` to `canonical_model` if that key is present at
/// all — shared by both helpers below so a response shape that happens
/// not to carry one (an error body, a future backend response this
/// doesn't recognize) is left alone rather than gaining a field it
/// never had.
fn set_response_model(value: &mut serde_json::Value, canonical_model: &str) {
    if value.get("model").is_some() {
        value["model"] = serde_json::Value::String(canonical_model.to_string());
    }
    // A Responses API event nests it: `response.created`'s `response`.
    // So does a Messages API stream: `message_start`'s `message`.
    for key in ["response", "message"] {
        if let Some(nested) = value.get_mut(key) {
            if nested.get("model").is_some() {
                nested["model"] = serde_json::Value::String(canonical_model.to_string());
            }
        }
    }
}

/// [`proxy_rewriting_model`]'s actual rewrite, split out as a pure
/// `bytes -> bytes` function so it's directly unit-testable without any
/// networking at all. Parses `raw` as JSON, rewrites its `"model"` field
/// (see [`set_response_model`]), and re-serializes — or returns `raw`
/// completely unchanged if it isn't valid JSON at all (an error body's
/// own shape, or a future backend response this doesn't recognize)
/// rather than mangling or dropping it.
fn rewrite_json_response_model(raw: &Bytes, canonical_model: &str) -> Bytes {
    match serde_json::from_slice::<serde_json::Value>(raw) {
        Ok(mut value) => {
            set_response_model(&mut value, canonical_model);
            serde_json::to_vec(&value)
                .map(Bytes::from)
                .unwrap_or_else(|_| raw.clone())
        }
        Err(_) => raw.clone(),
    }
}

/// [`stream_rewriting_model`]'s actual per-line rewrite, split out as a
/// pure `&str -> String` function so it's directly unit-testable without
/// any networking at all. `line` is one already-decoded logical line
/// from [`bytes_to_lines`] (its own line ending already stripped, not
/// yet restored here — the caller does that once, uniformly, since
/// every branch below needs it regardless of which one fires): a
/// `data: {...}` line whose payload parses as JSON gets its `"model"`
/// field rewritten (see [`set_response_model`]); `data: [DONE]`, a
/// blank SSE event-separator line, or a `data: ` line whose payload
/// *doesn't* parse as JSON all pass through byte-for-byte unchanged.
fn rewrite_sse_line_model(line: &str, canonical_model: &str) -> String {
    match line.strip_prefix("data: ") {
        Some(payload) if payload != "[DONE]" => match serde_json::from_str(payload) {
            Ok(mut value) => {
                set_response_model(&mut value, canonical_model);
                format!(
                    "data: {}",
                    serde_json::to_string(&value).unwrap_or_else(|_| payload.to_string())
                )
            }
            Err(_) => line.to_string(),
        },
        _ => line.to_string(),
    }
}

/// The non-streaming (`stream: false`, or no `stream` concept at all —
/// embeddings, the Responses API's token-counting endpoint) case:
/// buffers the whole response body (unlike `proxy`, which never does)
/// so its `"model"` field can be parsed, rewritten, and re-serialized
/// before forwarding it on. Every route that can reach this returns one
/// complete JSON object either way (never anything token-streamed a
/// client would notice the added latency of buffering first), so this
/// costs nothing a real client could observe.
///
/// `Content-Length`, if the backend sent one, is dropped rather than
/// forwarded: the rewritten body is a different size than the original
/// one that header described, and hyper/axum fill in the correct value
/// for a fixed (`Body::from(Bytes)`, not streamed) body on their own
/// when none is set explicitly.
pub(super) async fn proxy_rewriting_model(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
    canonical_model: &str,
) -> Result<Response, AppError> {
    let resp = send_proxied(client, target, route, headers, body).await?;
    relay_rewriting_model(resp, activity, canonical_model).await
}

/// [`proxy`] for a route whose reply is one JSON object that `rewrite`
/// changes on the way out. The body is read whole, as in
/// [`proxy_rewriting_model`]; an `Err` from `rewrite` is the reply.
pub(super) async fn proxy_buffered(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
    rewrite: impl FnOnce(&Bytes) -> Result<Bytes, AppError>,
) -> Result<Response, AppError> {
    let resp = send_proxied(client, target, route, headers, body).await?;
    relay_buffered(resp, activity, rewrite).await
}

/// The relay half of [`proxy_rewriting_model`]; see [`relay`].
pub(super) async fn relay_rewriting_model(
    resp: reqwest::Response,
    activity: ActivityGuard,
    canonical_model: &str,
) -> Result<Response, AppError> {
    relay_buffered(resp, activity, |raw| {
        Ok(rewrite_json_response_model(raw, canonical_model))
    })
    .await
}

/// The relay half of [`proxy_buffered`]; see [`relay`].
async fn relay_buffered(
    resp: reqwest::Response,
    activity: ActivityGuard,
    rewrite: impl FnOnce(&Bytes) -> Result<Bytes, AppError>,
) -> Result<Response, AppError> {
    let status = resp.status();
    let resp_headers = resp.headers().clone();
    let raw = resp
        .bytes()
        .await
        .context("read inference backend response")?;
    // The whole body is already collected by this point, so there's no
    // partial relay left for keeping this alive any longer to protect —
    // see `proxy`'s own comment on why it instead holds this open across
    // its whole (streamed) relay.
    drop(activity);

    let rewritten = rewrite(&raw)?;

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        if k == reqwest::header::CONTENT_LENGTH {
            continue;
        }
        builder = builder.header(k, v);
    }
    Ok(builder.body(Body::from(rewritten)).unwrap())
}

/// The streaming (`stream: true`) case: like `stream_ollama`/
/// `anthropic_messages_to`, uses `bytes_to_lines` so a `data: {...}` SSE line
/// split across two TCP reads is never parsed as JSON prematurely — but
/// unlike those two (which convert into a completely different wire
/// format, ndjson/Anthropic SSE, and so don't need to preserve the
/// original SSE framing at all), this must reproduce the exact original
/// OpenAI SSE shape byte-for-byte except for the one field being
/// rewritten: every blank line (an SSE event separator) and the
/// trailing `data: [DONE]` sentinel pass through completely unchanged;
/// only a `data: {...}` line whose payload actually parses as a JSON
/// object carrying a `model` field gets rewritten.
pub(super) async fn stream_rewriting_model(
    client: &Client,
    target: &Target,
    route: &str,
    headers: &HeaderMap,
    body: Bytes,
    activity: ActivityGuard,
    canonical_model: String,
) -> Result<Response, AppError> {
    let resp = send_proxied(client, target, route, headers, body).await?;
    Ok(relay_stream_rewriting_model(
        resp,
        activity,
        canonical_model,
    ))
}

/// The relay half of [`stream_rewriting_model`]; see [`relay`].
pub(super) fn relay_stream_rewriting_model(
    resp: reqwest::Response,
    activity: ActivityGuard,
    canonical_model: String,
) -> Response {
    let status = resp.status();
    // Every header but the ones describing a body about to be rewritten
    // line by line: a provider's `request-id`, rate limits and
    // `Retry-After` matter to the client.
    let mut resp_headers = resp.headers().clone();
    resp_headers.remove(reqwest::header::CONTENT_LENGTH);
    resp_headers.remove(reqwest::header::TRANSFER_ENCODING);

    // `bytes_to_lines` reads a transport error as EOF: hold it back and
    // send it after the last line, so a dying backend aborts the stream.
    let failure = std::sync::Arc::new(std::sync::Mutex::new(None));
    let record = failure.clone();
    let upstream = resp.bytes_stream().map(move |item| {
        item.or_else(|e| {
            *record.lock().unwrap_or_else(|e| e.into_inner()) = Some(e);
            Ok(Bytes::new())
        })
    });
    let lines = bytes_to_lines(upstream).map(move |line| {
        // See `proxy`'s own comment on this same pattern.
        let _activity = &activity;
        // bytes_to_lines strips the original line ending; restored here,
        // uniformly, regardless of which of rewrite_sse_line_model's own
        // branches actually fired.
        let out = rewrite_sse_line_model(&line, &canonical_model) + "\n";
        Ok::<_, reqwest::Error>(Bytes::from(out))
    });
    let error =
        futures::stream::once(
            async move { failure.lock().unwrap_or_else(|e| e.into_inner()).take() },
        )
        .filter_map(|e| async move { e.map(Err) });

    let mut builder = Response::builder().status(status.as_u16());
    for (k, v) in &resp_headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(lines.chain(error))).unwrap()
}

/// [`relay`] for a [`ChatUpstream`]: `activity` lives until the whole
/// body has been relayed (see `ActivityGuard`).
pub(super) fn relay_chat_upstream(upstream: ChatUpstream, activity: ActivityGuard) -> Response {
    let stream = upstream.body.map(move |item| {
        let _activity = &activity;
        item.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    });
    let mut builder = Response::builder().status(upstream.status.as_u16());
    for (k, v) in &upstream.headers {
        builder = builder.header(k, v);
    }
    builder.body(Body::from_stream(stream)).unwrap()
}

/// A converter of one upstream SSE stream into another, line by line:
/// `responses::StreamConverter` and `messages::StreamConverter`.
pub(super) trait SseConverter: Send + 'static {
    fn line(&mut self, line: &str) -> String;
    fn finish(&mut self) -> String;
    fn failed(&self) -> bool;
    fn fold(&mut self, lines: Vec<String>) -> serde_json::Value;
}

macro_rules! sse_converter {
    ($($t:ty),*) => {$(
        impl SseConverter for $t {
            fn line(&mut self, line: &str) -> String {
                Self::line(self, line)
            }
            fn finish(&mut self) -> String {
                Self::finish(self)
            }
            fn failed(&self) -> bool {
                Self::failed(self)
            }
            fn fold(&mut self, lines: Vec<String>) -> serde_json::Value {
                Self::fold(self, lines)
            }
        }
    )*};
}
sse_converter!(responses::StreamConverter, messages::StreamConverter);

/// `body` translated by `converter`: streamed as SSE, with a trailing
/// `None` so the converter can close a stream ended without `[DONE]`, or
/// folded into one JSON object (502 when the converter failed).
pub(super) async fn convert_upstream(
    body: ChatBody,
    activity: ActivityGuard,
    mut converter: impl SseConverter,
    streaming: bool,
) -> Response {
    if !streaming {
        let lines: Vec<String> = bytes_to_lines(body).collect().await;
        drop(activity);
        let response = converter.fold(lines);
        let status = if converter.failed() {
            StatusCode::BAD_GATEWAY
        } else {
            StatusCode::OK
        };
        return (status, Json(response)).into_response();
    }
    let sse_stream = bytes_to_lines(body)
        .map(Some)
        .chain(futures::stream::once(futures::future::ready(None)))
        .map(move |line| {
            let _activity = &activity;
            let out = match line {
                Some(line) => converter.line(&line),
                None => converter.finish(),
            };
            Ok::<_, std::convert::Infallible>(Bytes::from(out))
        });
    Response::builder()
        .header("content-type", "text/event-stream")
        .header("cache-control", "no-cache")
        .body(Body::from_stream(sse_stream))
        .unwrap()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Regression test guarding against exactly the leak CodeRabbit
    /// flagged in review: an `Engine::Mlx` backend is addressed by its
    /// real on-disk directory path (see `backend_wire_model`), and
    /// `mlx_lm.server` echoes whatever `"model"` value it received
    /// straight back into its own response — so a plain byte-for-byte
    /// relay would leak that internal path back to the client instead of
    /// the name it actually asked for. `set_response_model` is the one
    /// place both `rewrite_json_response_model` and
    /// `rewrite_sse_line_model` delegate the actual field substitution
    /// to.
    #[test]
    fn set_response_model_overwrites_an_existing_model_field_and_leaves_a_missing_one_alone() {
        let mut with_model = serde_json::json!({"model": "/abs/path/to/model", "id": "x"});
        set_response_model(&mut with_model, "gemma4:latest");
        assert_eq!(
            with_model,
            serde_json::json!({"model": "gemma4:latest", "id": "x"})
        );

        let mut without_model = serde_json::json!({"id": "x"});
        set_response_model(&mut without_model, "gemma4:latest");
        assert_eq!(without_model, serde_json::json!({"id": "x"}));

        // A Responses event carries it nested.
        let mut event =
            serde_json::json!({"type": "response.created", "response": {"model": "wire"}});
        set_response_model(&mut event, "canonical");
        assert_eq!(event["response"]["model"], "canonical");
    }

    #[test]
    fn rewrite_json_response_model_rewrites_a_json_body_and_leaves_every_other_field_alone() {
        let raw = Bytes::from(
            serde_json::to_vec(&serde_json::json!({
                "id": "chatcmpl-1",
                "model": "/home/user/.local/share/llmman/cache/abcd/model-dir",
                "choices": [{"message": {"content": "hi"}}]
            }))
            .unwrap(),
        );
        let rewritten = rewrite_json_response_model(&raw, "gemma4:latest");
        let value: serde_json::Value = serde_json::from_slice(&rewritten).unwrap();
        assert_eq!(value["model"], "gemma4:latest");
        assert_eq!(value["id"], "chatcmpl-1");
        assert_eq!(value["choices"][0]["message"]["content"], "hi");
    }

    #[test]
    fn rewrite_json_response_model_passes_non_json_bodies_through_unchanged() {
        // An error body, or any other shape this doesn't recognize —
        // must never be mangled or dropped just because it isn't JSON.
        let raw = Bytes::from_static(b"not json at all");
        assert_eq!(rewrite_json_response_model(&raw, "gemma4:latest"), raw);
    }

    #[test]
    fn rewrite_sse_line_model_rewrites_only_the_model_field_of_a_data_line() {
        let line = r#"data: {"id":"1","model":"/abs/path","choices":[{"delta":{"content":"h"}}]}"#;
        let rewritten = rewrite_sse_line_model(line, "gemma4:latest");
        let payload = rewritten.strip_prefix("data: ").expect("data: prefix");
        let value: serde_json::Value = serde_json::from_str(payload).unwrap();
        assert_eq!(value["model"], "gemma4:latest");
        assert_eq!(value["id"], "1");
        assert_eq!(value["choices"][0]["delta"]["content"], "h");
    }

    #[test]
    fn rewrite_sse_line_model_leaves_the_done_sentinel_and_blank_separators_untouched() {
        assert_eq!(
            rewrite_sse_line_model("data: [DONE]", "gemma4:latest"),
            "data: [DONE]"
        );
        assert_eq!(rewrite_sse_line_model("", "gemma4:latest"), "");
    }

    #[test]
    fn rewrite_sse_line_model_passes_a_non_json_data_line_through_unchanged() {
        assert_eq!(
            rewrite_sse_line_model("data: not json", "gemma4:latest"),
            "data: not json"
        );
    }

    /// `message_start` nests the model one level down.
    #[test]
    fn set_response_model_reaches_a_messages_stream_event() {
        let mut event = serde_json::json!({
            "type": "message_start",
            "message": { "id": "msg_1", "model": "claude-x" }
        });
        set_response_model(&mut event, "mine");
        assert_eq!(event["message"]["model"], "mine");
    }
}