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
//! `eclipse-gateway`: the dashboard, the OpenAI-compatible API and the scheduled upgrade
//! check, served from **one pid**.
//!
//! The dashboard's routes come from `eclipse_web` so the two binaries cannot drift; this
//! crate owns the API, the health extension's background probe and the schedule. The unit a
//! user installs (`eclipse gateway install`) runs this binary.

mod api;
mod schedule;

use axum::middleware;
use axum::routing::post;
use axum::Router;
use clap::Parser;
use eclipse_web::app::{self, Shared};
use eclipse_web::startup::{self, Options};
use std::path::PathBuf;

#[derive(Parser)]
#[command(
    name = "eclipse-gateway",
    version,
    about = "Dashboard, API and scheduled checks on one pid"
)]
struct Args {
    /// Path to config file (default: $XDG_CONFIG_HOME/eclipse/config.toml)
    #[arg(long, env = "ECLIPSE_CONFIG")]
    config: Option<PathBuf>,
    /// Override web.host (must be a loopback address)
    #[arg(long)]
    host: Option<String>,
    /// Override web.port
    #[arg(long)]
    port: Option<u16>,
    /// Use a profile: its config overlay, its own sessions, its own plugins
    #[arg(long, env = "ECLIPSE_PROFILE")]
    profile: Option<String>,
}

/// The dashboard's routes plus the API's, all behind the same loopback origin guard. The
/// dashboard's own layers already cover its routes; the API is merged in with its own copy of
/// the guard, because a layer applied before a merge does not reach what is merged after it.
fn gateway_router(state: Shared) -> Router {
    let api = Router::new()
        .route("/v1/chat/completions", post(api::chat_completions))
        .layer(middleware::from_fn_with_state(
            state.clone(),
            app::guard_local_origin,
        ));
    app::routes(state.clone()).merge(api).with_state(state)
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let args = Args::parse();
    let opts = Options {
        config: args.config,
        host: args.host,
        port: args.port,
        profile: args.profile,
    };
    let prepared = startup::prepare(&opts).await?;
    let state = prepared.state.clone();
    let addr = prepared.addr;
    schedule::spawn_model_probe(state.clone(), prepared.cfg.clone());
    // The plain state directory, not a profile's: the install marker and the update cache belong
    // to the machine user, and the dashboard reads the same two files.
    if let Some(dir) = eclipse_core::config::state_dir(&eclipse_core::config::process_env) {
        schedule::spawn_upgrade_check(prepared.cfg.clone(), dir);
    }
    schedule::spawn_session_prune(state.clone(), prepared.cfg.clone());
    startup::serve(
        prepared,
        gateway_router(state),
        &format!("eclipse gateway on http://{addr} — dashboard, /v1/chat/completions, health"),
    )
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use eclipse_core::error::Result as CoreResult;
    use eclipse_core::message::Message;
    use eclipse_core::provider::ChatProvider;
    use eclipse_core::runtime::Agent;
    use eclipse_core::session::SessionStore;
    use eclipse_core::tools::{ToolRegistry, ToolSpec};
    use eclipse_web::app::AppState;
    use std::sync::Arc;
    use tower::ServiceExt;

    const TOKEN: &str = "0123456789abcdef0123456789abcdef";

    struct Canned;

    #[async_trait]
    impl ChatProvider for Canned {
        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
            Ok(Message::assistant("canned reply"))
        }
    }

    /// A backend that never answers, with the two things a failure text carries that a caller must
    /// not be handed: the endpoint and whatever the server said.
    struct Unreachable;

    #[async_trait]
    impl ChatProvider for Unreachable {
        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
            Err(eclipse_core::Error::provider(
                "could not reach http://10.1.2.3:9/v1/chat/completions: connection refused",
            ))
        }
    }

    /// Counts how often the model was asked, so a test can assert a run *did not start* rather than
    /// infer it from a status two failures share.
    struct Counting(Arc<std::sync::atomic::AtomicUsize>);

    #[async_trait]
    impl ChatProvider for Counting {
        async fn chat(&self, _: &[Message], _: &[ToolSpec]) -> CoreResult<Message> {
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(Message::assistant("canned reply"))
        }
    }

    fn state(dir: &std::path::Path) -> Shared {
        state_with(dir, Arc::new(Canned))
    }

    fn state_with(dir: &std::path::Path, provider: Arc<dyn ChatProvider>) -> Shared {
        let store = SessionStore::new(dir.join("sessions"));
        let agent = Arc::new(Agent::new(
            provider,
            Arc::new(ToolRegistry::default()),
            store.clone(),
            "sys".into(),
            3,
        ));
        Arc::new(AppState::new(
            Some(agent),
            store,
            "test-<model>".into(),
            None,
            TOKEN.into(),
            std::time::Duration::from_secs(3600),
        ))
    }

    fn req(body: serde_json::Value, bearer: Option<&str>) -> Request<Body> {
        req_raw(&body.to_string(), bearer)
    }

    fn req_raw(body: &str, bearer: Option<&str>) -> Request<Body> {
        let mut b = Request::post("/v1/chat/completions")
            .header("host", "127.0.0.1:8787")
            .header("content-type", "application/json");
        if let Some(t) = bearer {
            b = b.header("authorization", format!("Bearer {t}"));
        }
        b.body(Body::from(body.to_string())).unwrap()
    }

    async fn body_text(r: axum::response::Response) -> String {
        let bytes = axum::body::to_bytes(r.into_body(), 64 * 1024)
            .await
            .unwrap_or_default();
        String::from_utf8_lossy(&bytes).into_owned()
    }

    #[tokio::test]
    async fn a_v1_call_with_the_bearer_token_gets_a_completion() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
        assert_eq!(v["object"], "chat.completion");
        assert_eq!(v["choices"][0]["message"]["content"], "canned reply");
    }

    /// `/bg` needs a composer to return to and a registry of its own. A headless caller has
    /// neither, so the line is refused here rather than answered as if it were a question.
    #[tokio::test]
    async fn a_v1_call_that_asks_for_a_background_task_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "/bg count the files"}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let said = body_text(resp).await;
        assert!(said.contains("/bg"), "{said}");
        assert!(said.contains("the gateway"), "{said}");
    }

    /// The call is a run, and the loop stores every turn, so a session is left behind whatever the
    /// docs used to say. What matters is that it is *tagged*: a headless call must not look like a
    /// conversation in the listing, in `--continue`, or to the sweep that bounds the store.
    #[tokio::test]
    async fn a_v1_call_leaves_a_session_tagged_as_the_api_s() {
        let dir = tempfile::tempdir().unwrap();
        let store = SessionStore::new(dir.path().join("sessions"));
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let sessions = store.list().unwrap();
        assert_eq!(sessions.len(), 1, "the run wrote one: {}", sessions.len());
        assert_eq!(sessions[0].origin, SessionStore::API_ORIGIN);
        assert!(
            sessions[0].subagent().is_none(),
            "an API call is not a subagent"
        );
    }

    #[tokio::test]
    async fn the_v1_route_takes_the_same_concurrency_slot_as_the_dashboard() {
        let dir = tempfile::tempdir().unwrap();
        let st = state(dir.path());
        // Everything the cap allows, held — as if four dashboard chats were in flight.
        let held: Vec<_> = (0..eclipse_web::app::MAX_CONCURRENT_CHATS)
            .map(|n| {
                st.try_chat_slot()
                    .unwrap_or_else(|| panic!("slot {n} is free"))
            })
            .collect();
        let body = serde_json::json!({"messages": [{"role": "user", "content": "hello"}]});
        let resp = gateway_router(st.clone())
            .oneshot(req(body.clone(), Some(TOKEN)))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
        let text = body_text(resp).await;
        assert!(text.contains("too many chats"), "{text}");

        // The permits come back when the runs end, and the route works again.
        drop(held);
        let resp = gateway_router(st)
            .oneshot(req(body, Some(TOKEN)))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn a_v1_call_without_a_bearer_token_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
                None,
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    /// `#393`: extractors run before the handler, so a `Json` body was parsed — and answered 422
    /// with serde's wording — before the bearer check could refuse the caller. An unauthenticated
    /// request is answered as one, whatever it sent.
    #[tokio::test]
    async fn a_body_that_will_not_parse_is_refused_for_its_token_not_its_json() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req_raw("{\"messages\": [", None))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let said = body_text(resp).await;
        assert!(said.contains("auth_error"), "{said}");

        // And a caller that does hold the token gets the parse failure, in the OpenAI shape.
        let resp = gateway_router(state(dir.path()))
            .oneshot(req_raw("{\"messages\": [", Some(TOKEN)))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
        assert_eq!(v["error"]["type"], "invalid_request_error", "{v}");
        assert!(
            v["error"]["message"]
                .as_str()
                .unwrap_or("")
                .contains("body"),
            "{v}"
        );
    }

    /// Valid JSON of the wrong shape is the case the extractor answered 422 about — serde's wording
    /// in no envelope a client can read. Without the token it is still the token that is wrong.
    #[tokio::test]
    async fn a_body_of_the_wrong_shape_is_a_400_in_the_openai_envelope() {
        let dir = tempfile::tempdir().unwrap();
        let wrong_shape = "{\"messages\": \"not a list\"}";
        let resp = gateway_router(state(dir.path()))
            .oneshot(req_raw(wrong_shape, None))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let resp = gateway_router(state(dir.path()))
            .oneshot(req_raw(wrong_shape, Some(TOKEN)))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let v: serde_json::Value = serde_json::from_str(&body_text(resp).await).unwrap();
        assert_eq!(v["error"]["type"], "invalid_request_error", "{v}");
        assert!(
            v["error"]["message"]
                .as_str()
                .unwrap_or("")
                .starts_with("the request body"),
            "{v}"
        );
    }

    /// `#394`: a backend that does not answer is the upstream's failure, and the answer to the caller
    /// names that much and nothing else — the endpoint and the server's own words stay in the log,
    /// where the operator can read them and no client can map the machine.
    #[tokio::test]
    async fn a_backend_that_does_not_answer_is_a_502_without_its_address() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state_with(dir.path(), Arc::new(Unreachable)))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
        let said = body_text(resp).await;
        let v: serde_json::Value = serde_json::from_str(&said).unwrap();
        assert_eq!(v["error"]["type"], "server_error", "{said}");
        assert!(!said.contains("10.1.2.3"), "the endpoint leaked: {said}");
        assert!(
            !said.contains("connection refused"),
            "the backend's words leaked: {said}"
        );
    }

    /// `#395`: the `api` tag is written before the run, and a call whose tag cannot be written is
    /// refused.
    ///
    /// **This test is cover, not a witness.** Reverting the guard does not fail it: a store broken
    /// enough to fail `begin_api` also fails the run's own first `append`, so the model is never
    /// asked either way and neither answer can be told from the other by a caller. The leak the
    /// issue describes needs a *transient* failure — a refused open or a locked database that has
    /// cleared by the time the loop writes — which no deterministic test can place between the two
    /// statements. What is worth pinning is the invariant: nothing runs that could end up untagged.
    #[tokio::test]
    async fn a_call_that_cannot_tag_its_session_is_refused_instead_of_run_untagged() {
        let dir = tempfile::tempdir().unwrap();
        // A file where the store's directory should be: opening it is an error, and it is an error
        // the caller must not be told the path of.
        std::fs::write(dir.path().join("sessions"), b"not a directory").unwrap();
        // What matters is that the run does not start: a status alone would not tell this apart
        // from a run that started and then failed to store what it had already spent the model on.
        let asked = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let resp = gateway_router(state_with(dir.path(), Arc::new(Counting(asked.clone()))))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(
            asked.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "the model was asked for a call that could not be tagged"
        );
        let said = body_text(resp).await;
        let v: serde_json::Value = serde_json::from_str(&said).unwrap();
        assert_eq!(v["error"]["type"], "server_error", "{said}");
        assert!(
            !said.contains("not a directory") && !said.contains(dir.path().to_str().unwrap()),
            "the store's complaint leaked: {said}"
        );
    }

    #[tokio::test]
    async fn a_v1_call_with_a_browser_cookie_only_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let mut r = req(
            serde_json::json!({"messages": [{"role": "user", "content": "hello"}]}),
            None,
        );
        r.headers_mut()
            .insert("cookie", "eclipse_session=whatever".parse().unwrap());
        let resp = gateway_router(state(dir.path())).oneshot(r).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn a_v1_call_asking_for_a_stream_is_refused_honestly() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "stream": true}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    /// `#425`: `n` was not even parsed, so a caller asking for three choices got one and no way to
    /// know. Refused in the request's own terms rather than answered with a number it did not ask
    /// for.
    #[tokio::test]
    async fn a_v1_call_asking_for_several_choices_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "n": 3}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = axum::body::to_bytes(resp.into_body(), 8192).await.unwrap();
        assert!(
            String::from_utf8_lossy(&body).contains("n = 3 is not supported"),
            "{}",
            String::from_utf8_lossy(&body)
        );
        // `n: 1` is what this build does, so it is not a refusal.
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": "hi"}], "n": 1}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_ne!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn a_v1_call_with_no_text_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(req(
                serde_json::json!({"messages": [{"role": "user", "content": ""}]}),
                Some(TOKEN),
            ))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn the_dashboard_is_still_served_from_the_same_router() {
        let dir = tempfile::tempdir().unwrap();
        let resp = gateway_router(state(dir.path()))
            .oneshot(
                Request::get("/healthz")
                    .header("host", "127.0.0.1:8787")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }
}