eclipse-gateway 0.13.4

The Eclipse gateway: the dashboard, the OpenAI-compatible API and the scheduled check, on one pid
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! The OpenAI-compatible API (`/v1/*`), served from the same process as the dashboard.
//!
//! One endpoint for now: `POST /v1/chat/completions`. It is a **headless** door into the same
//! agent the dashboard runs — each call is one run, not a session the caller resumes. The
//! conversation is flattened into a single prompt (roles are told to the model, not trusted
//! as real roles), and tools that need approval are **declined** (a non-interactive run never
//! answers).
//!
//! **Each call does leave a session behind.** The loop stores every turn, so there is no
//! stateless path through it; what the API does instead is tag the row with origin `api` before
//! the run, which keeps it out of `--continue` and lets the gateway prune its own leavings after
//! `[gateway] api_session_ttl_hours`. Nothing is written *under the caller's name* — there is no
//! name to write it under.
//!
//! Auth is a bearer token — the same `web.auth_token` the dashboard login uses. The loopback
//! origin guard applies to `/v1/*` exactly as to everything else. `stream: true` is refused
//! with an honest 400: a partial stream wearing an OpenAI shape is worse than a flat one.

use axum::extract::State;
use axum::http::HeaderMap;
use axum::response::{IntoResponse, Response};
use axum::Json;
use eclipse_core::tools::DenyAll;
use eclipse_web::app::Shared;
use serde::Deserialize;
use serde_json::{json, Value};

#[derive(Deserialize)]
#[allow(dead_code)] // the OpenAI shape is the contract; the agent does not use the extras
pub struct ChatCompletionsRequest {
    pub model: Option<String>,
    pub messages: Vec<ApiMessage>,
    pub max_completion_tokens: Option<u32>,
    pub max_tokens: Option<u32>,
    /// How many choices the caller wants. One is all this build answers, and asking for more used
    /// to be ignored in silence — a client that reads `choices[0]` and counts three gets one and no
    /// way to know (`#425`).
    pub n: Option<u32>,
    pub stream: Option<bool>,
}

#[derive(Deserialize)]
pub struct ApiMessage {
    pub role: String,
    pub content: Option<Value>,
}

/// A content either as a string, or as the array of parts OpenAI sends. Only text parts are
/// kept; anything else is dropped rather than guessed at.
fn text_of(content: Option<Value>) -> String {
    match content {
        None => String::new(),
        Some(Value::String(s)) => s,
        Some(Value::Array(parts)) => parts
            .iter()
            .filter_map(|p| {
                let ty = p.get("type").and_then(|t| t.as_str())?;
                if ty != "text" {
                    return None;
                }
                p.get("text")
                    .and_then(|t| t.as_str())
                    .map(|t| t.to_string())
            })
            .collect::<Vec<_>>()
            .join("\n"),
        Some(Value::Object(_)) => String::new(),
        Some(other) => other.to_string(),
    }
}

/// The `image_url` parts of a content, as parts the message can carry (`#364`).
///
/// A client sending a picture to an OpenAI-shaped endpoint sends it here, and this endpoint used to
/// throw the part away — the request succeeded and the model answered about a picture it never saw,
/// which is the worst shape a bug can take. The rule is the core's, the same one the dashboard's
/// composer applies, so both surfaces refuse the same thing in the same words.
fn images_of(content: Option<&Value>) -> Result<Vec<eclipse_core::message::ImagePart>, String> {
    let Some(Value::Array(parts)) = content else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for part in parts {
        if part.get("type").and_then(|ty| ty.as_str()) != Some("image_url") {
            continue;
        }
        let url = part
            .get("image_url")
            .and_then(|value| value.get("url"))
            .and_then(|value| value.as_str())
            .ok_or_else(|| {
                "an `image_url` part has no `url`; send {\"type\": \"image_url\", \"image_url\":                  {\"url\": \"data:image/png;base64,...\"}}"
                    .to_string()
            })?;
        out.push(eclipse_core::message::ImagePart::from_data_url("", url)?);
    }
    Ok(out)
}

/// How many `image_url` parts a content declares, without reading them. Used only to say what did
/// not travel, so a malformed part is reported by `images_of` rather than counted twice.
fn picture_count(content: Option<&Value>) -> usize {
    match content {
        Some(Value::Array(parts)) => parts
            .iter()
            .filter(|part| part.get("type").and_then(|ty| ty.as_str()) == Some("image_url"))
            .count(),
        _ => 0,
    }
}

/// Flatten an OpenAI conversation into one prompt. System content is kept as its prefix so a
/// caller's system instruction is not silently dropped; everything else keeps its role label.
/// This is not a message list — the model sees one instruction, and the roles are told rather
/// than trusted.
///
/// `carried` is the message whose pictures ride this call (`#364`). One flattened prompt cannot
/// tell a picture attached now from one attached ten minutes ago, so only that message's pictures
/// travel as pictures; a picture on any other message is named in the text where it stood. Either
/// way it is not dropped without a word.
pub fn flatten_carrying(messages: &[ApiMessage], carried: Option<usize>) -> String {
    let mut out = String::new();
    for (index, m) in messages.iter().enumerate() {
        let mut text = text_of(m.content.clone());
        let pictures = picture_count(m.content.as_ref());
        if pictures > 0 {
            if Some(index) == carried {
                if text.trim().is_empty() {
                    text = "(the attached picture)".to_string();
                }
            } else {
                if !text.trim().is_empty() {
                    text.push('\n');
                }
                text.push_str(&format!(
                    "[{pictures} picture(s) attached to this message did not travel: one flattened \
                     prompt can only carry the last message's pictures]"
                ));
            }
        }
        if text.trim().is_empty() {
            continue;
        }
        let role = match m.role.as_str() {
            "system" => "system",
            "assistant" => "assistant",
            _ => "user",
        };
        if role == "system" {
            if !out.is_empty() {
                out.push_str("\n\n");
            }
            out.push_str(&format!("[system instruction]\n{text}"));
        } else {
            out.push_str(&format!("\n\n[{role}]\n{text}"));
        }
    }
    out.trim().to_string()
}

/// Authorization: Bearer <web.auth_token>, constant-time. The dashboard login cookie is not
/// accepted here: an API call that silently rides a browser session is a surprise for a
/// script that should send its own credential.
pub fn bearer_ok(headers: &HeaderMap, token: &str) -> bool {
    let Some(value) = headers.get("authorization").and_then(|v| v.to_str().ok()) else {
        return false;
    };
    // `#425`: RFC 7235 makes the scheme case-insensitive, and `bearer <token>` is what curl
    // examples and several SDKs produce. Matching only the capitalised form answered them 401.
    let Some((scheme, rest)) = value.split_once(' ') else {
        return false;
    };
    if !scheme.eq_ignore_ascii_case("bearer") {
        return false;
    }
    let stripped = rest;
    eclipse_core::token::constant_time_eq(stripped.trim(), token)
}

/// Whether the caller may be answered as `answering`.
///
/// An absent, empty or matching `model` is fine; a different one is a 400, because answering with
/// another model and calling it the requested one is the sort of lie a client cannot detect.
fn model_ok(asked: Option<&str>, answering: &str) -> Result<(), String> {
    match asked.map(str::trim) {
        Some(name) if !name.is_empty() && name != answering => Err(format!(
            "this gateway answers as `{answering}`; the request asked for `{name}`. Omit `model` to \
             use the configured one"
        )),
        _ => Ok(()),
    }
}

/// `#394`: how a failed run is answered.
///
/// Every failure used to be a 502 carrying `e.to_string()`, which said three wrong things at once:
/// that this process's own failure (a store, a config, a file) is the upstream's fault; that a
/// refusal the core words for a person is a server error; and — in the text — the provider's URL,
/// whatever the model server answered with, and paths on this machine. The class is what a caller
/// can act on, the sentence the core wrote for a refusal is what it needs to read, and everything
/// else is the operator's business in the log.
fn failure(err: &eclipse_core::Error) -> (axum::http::StatusCode, &'static str, String) {
    match err {
        // The model did not answer: the caller's request was fine and nothing else can be said
        // about it without handing out the endpoint or the server's body.
        eclipse_core::Error::Provider(_) => (
            axum::http::StatusCode::BAD_GATEWAY,
            "server_error",
            "the model backend failed to answer; the gateway log has the detail".to_string(),
        ),
        // Not a failure of the machinery at all: the turn was refused before it ran, and the
        // sentence exists so every surface prints it word for word (`#346`).
        eclipse_core::Error::Vision(sentence) => (
            axum::http::StatusCode::BAD_REQUEST,
            "invalid_request_error",
            sentence.clone(),
        ),
        // The model's own doing, and the number is the only thing that explains it.
        eclipse_core::Error::MaxIterations(iterations) => (
            axum::http::StatusCode::BAD_GATEWAY,
            "server_error",
            format!("the model did not produce a final answer within {iterations} iterations"),
        ),
        _ => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            "server_error",
            "the gateway could not run the request; the gateway log has the detail".to_string(),
        ),
    }
}

/// `#393`: the body arrives as bytes, not as a parsed `Json`.
///
/// Extractors run before the handler does, in argument order, so `Json<…>` parsed (and answered
/// 415 without a JSON content-type, 400 on a syntax error, 422 on the wrong shape, each with
/// serde's own wording and no envelope) before the bearer check could run — an unauthenticated
/// caller was told its JSON was wrong by an endpoint it had not authenticated to, and no OpenAI
/// client could read the answer. The token is now the first thing consulted and the parse is the
/// caller's own business afterwards.
pub async fn chat_completions(
    State(st): State<Shared>,
    headers: HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    if !bearer_ok(&headers, st.token()) {
        return (
            axum::http::StatusCode::UNAUTHORIZED,
            Json(json!({"error": {"message": "missing or invalid bearer token", "type": "auth_error"}})),
        )
            .into_response();
    }
    let body: ChatCompletionsRequest = match serde_json::from_slice(&body) {
        Ok(body) => body,
        Err(e) => {
            return (
                axum::http::StatusCode::BAD_REQUEST,
                Json(json!({"error": {"message": format!("the request body is not a chat-completions request: {e}"), "type": "invalid_request_error"}})),
            )
                .into_response();
        }
    };
    if body.stream == Some(true) {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            Json(json!({"error": {"message": "streaming is not supported yet; omit stream or set it to false", "type": "invalid_request_error"}})),
        )
            .into_response();
    }
    if let Some(n) = body.n.filter(|n| *n != 1) {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            Json(json!({"error": {"message": format!("n = {n} is not supported: this build answers one choice, so omit n or set it to 1"), "type": "invalid_request_error"}})),
        )
            .into_response();
    }
    let Some(agent) = st.agent.clone() else {
        return (
            axum::http::StatusCode::SERVICE_UNAVAILABLE,
            Json(json!({"error": {"message": st.config_error.clone().unwrap_or_else(|| "provider not configured".to_string()), "type": "server_error"}})),
        )
            .into_response();
    };
    // Which model answers, and whether that is the one that was asked for. `st.model` is fixed at
    // startup, so a dashboard switch left every `/v1` reply naming the model that used to answer —
    // and a caller asking for a name the gateway does not serve got a different one, silently.
    let answering = st.current_model().unwrap_or_else(|| st.model.clone());
    if let Err(why) = model_ok(body.model.as_deref(), &answering) {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            Json(json!({"error": {"message": why, "type": "invalid_request_error"}})),
        )
            .into_response();
    }
    // A `/bg` line is a composer's verb: it returns to a prompt, and a headless caller has none.
    // Checked against the caller's own question rather than the flattened prompt, which carries
    // a `[user]` label in front of every message.
    let carried = body
        .messages
        .iter()
        .rposition(|m| m.role != "assistant" && m.role != "system");
    let asked = carried
        .map(|index| text_of(body.messages[index].content.clone()))
        .unwrap_or_default();
    if eclipse_core::tasks::bg_prompt(&asked).is_some() {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            Json(json!({"error": {"message": eclipse_core::tasks::bg_refusal("the gateway"), "type": "invalid_request_error"}})),
        )
            .into_response();
    }
    // `#364`: a caller's `image_url` part rides the turn instead of being dropped. Refused with a
    // sentence naming the part when it is not a picture this build can carry, because a client that
    // sent a bad attachment and got a confident answer about it has no way to find out.
    let images = match carried.map(|index| images_of(body.messages[index].content.as_ref())) {
        Some(Ok(images)) => images,
        Some(Err(sentence)) => {
            return (
                axum::http::StatusCode::BAD_REQUEST,
                Json(json!({"error": {"message": sentence, "type": "invalid_request_error"}})),
            )
                .into_response();
        }
        None => Vec::new(),
    };
    let prompt = flatten_carrying(&body.messages, carried);
    if prompt.trim().is_empty() {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            Json(json!({"error": {"message": "messages must contain non-empty text", "type": "invalid_request_error"}})),
        )
            .into_response();
    }
    // The same cap the dashboard route takes, from the same semaphore: this call drives a full
    // agent run, and a bearer-token holder firing N of them must queue like any other client
    // rather than starve the one local model. The permit lives until the response is ready.
    let Some(_slot) = st.try_chat_slot() else {
        return (
            axum::http::StatusCode::TOO_MANY_REQUESTS,
            Json(json!({"error": {"message": "too many chats in progress; try again shortly", "type": "rate_limit_error"}})),
        )
            .into_response();
    };
    // A fresh session per call: the API is stateless in shape, and reusing a browser session
    // id would leak one caller's conversation into another's by id. The row is tagged `api`
    // first, because the loop's own `append` would create it as a conversation and a headless
    // call is not one — that tag is what keeps `--continue` off it and lets the gateway sweep
    // its own leavings.
    let session_id = agent.store().new_id();
    if let Err(e) = agent.store().begin_api(&session_id) {
        // `#395`: the tag is the only thing that keeps this call's session out of the user's
        // conversation list and inside `prune_api_sessions`, and the loop's `append` would create
        // the row untagged if the run started anyway. A call that cannot be tagged is not worth
        // running: it would leave a conversation nobody can tell from one a person had.
        let (status, kind, message) = failure(&e);
        eprintln!("[api] could not tag session {session_id} as api: {e}");
        return (
            status,
            Json(json!({"error": {"message": message, "type": kind}})),
        )
            .into_response();
    }
    let opts = eclipse_core::runtime::RunOptions {
        // `max_completion_tokens` is a token budget, not an iteration budget; the agent's own
        // iteration budget is kept rather than mapped onto a number that means something else.
        max_iterations: None,
        resume: false,
        output_schema: None,
        // A headless call: the session is tagged `api` and named from its opening message, and no
        // naming call is spent on a turn nobody is going to read in a list.
        title: false,
        // `#364`: the last message's `image_url` parts, already checked by the core's rule. From
        // here on the turn is an ordinary one — the same sight plan, the same describe route, the
        // same refusal when the answering model cannot see.
        images,
    };
    let result = agent
        .run_with(Some(&session_id), &prompt, &DenyAll, &|_event| {}, &opts)
        .await;
    match result {
        Ok(run) => {
            let created = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let body = json!({
                "id": format!("chatcmpl-{}", session_id),
                "object": "chat.completion",
                "created": created,
                "model": answering,
                "choices": [{
                    "index": 0,
                    "message": {
                        "role": "assistant",
                        "content": run.reply,
                    },
                    // `#425`: always `stop`, because nothing here can tell a truncated reply from a
                    // finished one — the agent's reply is whatever the model said last, and the
                    // provider's own `finish_reason` is not carried out of the loop. Documented
                    // rather than guessed: a client that branches on `length` gets no `length`,
                    // never a wrong `stop` from a reply this endpoint cut.
                    "finish_reason": "stop",
                }],
                // No `usage`: this endpoint drives a whole agent run, so the tokens spent are the
                // run's (several requests, tool calls, a compaction) and not one completion's. An
                // estimate here would be a number a client meters against that is not the bill.
                // Omitted on purpose — `usage` is optional in the shape.
            });
            (axum::http::StatusCode::OK, Json(body)).into_response()
        }
        Err(e) => {
            let (status, kind, message) = failure(&e);
            // The detail a caller must not have: the provider's URL, whatever the model server
            // answered with, a path on this machine.
            eprintln!("[api] the run failed: {e}");
            (
                status,
                Json(json!({"error": {"message": message, "type": kind}})),
            )
                .into_response()
        }
    }
}

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

    #[test]
    fn flatten_keeps_roles_and_system_prefix() {
        let messages = vec![
            ApiMessage {
                role: "system".into(),
                content: Some(json!("be brief")),
            },
            ApiMessage {
                role: "user".into(),
                content: Some(json!("hi")),
            },
            ApiMessage {
                role: "assistant".into(),
                content: Some(json!("hello")),
            },
            ApiMessage {
                role: "user".into(),
                content: Some(json!("again")),
            },
        ];
        let out = flatten_carrying(&messages, None);
        assert!(out.starts_with("[system instruction]\nbe brief"));
        assert!(out.contains("[user]\nhi"));
        assert!(out.contains("[assistant]\nhello"));
        assert!(out.ends_with("[user]\nagain"));
    }

    #[test]
    fn flatten_drops_empty_parts() {
        let messages = vec![
            ApiMessage {
                role: "user".into(),
                content: None,
            },
            ApiMessage {
                role: "user".into(),
                content: Some(json!("real")),
            },
        ];
        assert_eq!(flatten_carrying(&messages, None), "[user]\nreal");
    }

    #[test]
    fn flatten_text_parts_only() {
        let messages = vec![ApiMessage {
            role: "user".into(),
            content: Some(json!([
                {"type": "text", "text": "one"},
                {"type": "image_url", "image_url": {"url": "x"}},
                {"type": "text", "text": "two"},
            ])),
        }];
        // The text parts are joined in order and the picture part never leaks in as text. Since no
        // message here is the one carrying pictures (`#364`), the part is named as left behind —
        // it is not text, and it is not silently nothing either.
        let out = flatten_carrying(&messages, None);
        assert!(out.starts_with("[user]\none\ntwo\n"), "{out}");
        assert!(
            out.contains("1 picture(s) attached to this message did not travel"),
            "{out}"
        );
        assert!(!out.contains("\"x\""), "the part's url is not text: {out}");
        // And when this message is the one carrying them, the note is gone.
        assert_eq!(flatten_carrying(&messages, Some(0)), "[user]\none\ntwo");
    }

    #[test]
    fn a_request_for_another_model_is_refused() {
        let why = model_ok(Some("gpt-4"), "qwen-3.8-27b").expect_err("a different model is a no");
        assert!(why.contains("gpt-4"), "{why}");
        assert!(why.contains("qwen-3.8-27b"), "{why}");
    }

    #[test]
    fn the_model_that_answers_may_be_named_and_omitting_it_is_fine() {
        assert!(model_ok(Some("qwen-3.8-27b"), "qwen-3.8-27b").is_ok());
        assert!(
            model_ok(Some("  qwen-3.8-27b  "), "qwen-3.8-27b").is_ok(),
            "trimmed"
        );
        assert!(model_ok(None, "qwen-3.8-27b").is_ok());
        assert!(
            model_ok(Some(""), "qwen-3.8-27b").is_ok(),
            "an empty name is not a request"
        );
        assert!(model_ok(Some("   "), "qwen-3.8-27b").is_ok());
    }

    /// `#425`: RFC 7235 makes the scheme case-insensitive, and `bearer` lowercase is what curl
    /// examples and several SDKs emit. It was a 401.
    #[test]
    fn the_bearer_scheme_is_case_insensitive_and_the_token_is_not() {
        use axum::http::HeaderMap;
        for scheme in ["Bearer", "bearer", "BEARER", "BeArEr"] {
            let mut h = HeaderMap::new();
            h.insert("authorization", format!("{scheme} tok").parse().unwrap());
            assert!(bearer_ok(&h, "tok"), "{scheme} must authenticate");
            assert!(!bearer_ok(&h, "TOK"), "the token itself is exact");
        }
        for bad in ["Bearer", "BearerX tok", "Basic tok", ""] {
            let mut h = HeaderMap::new();
            h.insert("authorization", bad.parse().unwrap());
            assert!(!bearer_ok(&h, "tok"), "{bad:?} must not authenticate");
        }
    }

    #[test]
    fn bearer_requires_the_token() {
        use axum::http::HeaderMap;
        let mut h = HeaderMap::new();
        assert!(!bearer_ok(&h, "tok"));
        h.insert("authorization", "Bearer wrong".parse().unwrap());
        assert!(!bearer_ok(&h, "tok"));
        h.insert("authorization", "Bearer tok".parse().unwrap());
        assert!(bearer_ok(&h, "tok"));
    }

    /// `#394`: the class of a failed run is the status, and none of the text is something a caller
    /// can use to map the machine or read a backend's answer.
    #[test]
    fn a_failed_run_is_answered_by_its_class_and_not_by_its_payload() {
        use eclipse_core::Error;

        let (status, kind, message) = failure(&Error::provider(
            "could not reach http://10.1.2.3:9/v1: refused",
        ));
        assert_eq!(status, axum::http::StatusCode::BAD_GATEWAY);
        assert_eq!(kind, "server_error");
        assert!(
            !message.contains("10.1.2.3"),
            "the endpoint is not the caller's business: {message}"
        );

        let (status, _, message) = failure(&Error::Session(
            "no such table: messages at /home/someone/x.db".into(),
        ));
        assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR);
        assert!(
            !message.contains("messages") && !message.contains("/home/"),
            "a store failure is this process's own: {message}"
        );

        // A refusal is not a server error, and its sentence is written to be printed as it is.
        let (status, kind, message) =
            failure(&Error::Vision("say why, then what to change".into()));
        assert_eq!(status, axum::http::StatusCode::BAD_REQUEST);
        assert_eq!(kind, "invalid_request_error");
        assert_eq!(message, "say why, then what to change");

        let (status, _, message) = failure(&Error::MaxIterations(3));
        assert_eq!(status, axum::http::StatusCode::BAD_GATEWAY);
        assert!(message.contains('3'), "{message}");
    }

    /// `#364`: a caller's picture is not text and must not go through the text path. This is the
    /// shape an OpenAI client sends, and the endpoint used to answer about a picture it never saw.
    #[test]
    fn an_image_part_becomes_a_picture_the_turn_carries() {
        let content = json!([
            {"type": "text", "text": "what does the sign say?"},
            {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
        ]);
        let images = images_of(Some(&content)).expect("a data URL is a picture");
        assert_eq!(images.len(), 1);
        assert_eq!(images[0].mime, "image/png");
        assert_eq!(images[0].url, "data:image/png;base64,iVBORw0KGgo=");
        // Named, not invented: the part carries no filename, and the description block needs one.
        assert_eq!(images[0].name, "picture");

        let messages: Vec<ApiMessage> = vec![ApiMessage {
            role: "user".to_string(),
            content: Some(content),
        }];
        let prompt = flatten_carrying(&messages, Some(0));
        assert!(prompt.contains("what does the sign say?"), "{prompt}");
        assert!(
            !prompt.contains("data:image/png"),
            "the bytes are the part's, not the prompt's: {prompt}"
        );
    }

    /// A picture the endpoint will not carry is refused in the same words the dashboard uses,
    /// rather than being answered about as if it had been seen.
    #[test]
    fn a_picture_that_is_not_a_data_url_is_refused_not_dropped() {
        let content =
            json!([{"type": "image_url", "image_url": {"url": "https://example.com/a.png"}}]);
        let sentence = images_of(Some(&content)).expect_err("a link is not a picture");
        assert!(sentence.contains("base64 data: URL"), "{sentence}");

        let content = json!([{"type": "image_url", "image_url": {"url": "data:application/pdf;base64,iVBORw0KGgo="}}]);
        let sentence = images_of(Some(&content)).expect_err("a PDF is not a picture");
        assert!(
            sentence.contains("not a picture this build can carry"),
            "{sentence}"
        );

        let content = json!([{"type": "image_url"}]);
        let sentence = images_of(Some(&content)).expect_err("no url at all");
        assert!(sentence.contains("has no `url`"), "{sentence}");
    }

    /// One flattened prompt cannot carry two pictures from two messages without lying about when
    /// they arrived: the last message's travel, and an earlier one is named where it stood.
    #[test]
    fn only_the_last_messages_pictures_travel_and_the_rest_are_named() {
        let with = |text: &str| ApiMessage {
            role: "user".to_string(),
            content: Some(json!([
                {"type": "text", "text": text},
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
            ])),
        };
        let messages = vec![with("earlier"), with("now")];
        let prompt = flatten_carrying(&messages, Some(1));
        assert!(prompt.contains("earlier"), "{prompt}");
        assert!(prompt.contains("did not travel"), "{prompt}");
        assert!(
            prompt.matches("did not travel").count() == 1,
            "the carried message is not named as left behind: {prompt}"
        );

        // A picture-only message is not skipped: the prompt says the turn had one.
        let bare = vec![ApiMessage {
            role: "user".to_string(),
            content: Some(json!([
                {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
            ])),
        }];
        let prompt = flatten_carrying(&bare, Some(0));
        assert!(prompt.contains("(the attached picture)"), "{prompt}");
    }
}