mobius-gateway 0.16.25

Headless authenticated gateway for möbius frontends
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
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
use std::sync::Arc;

use mobius::backend::model::provider::HostedWebSearch;

use crate::bots::BotStore;
use crate::config::{ConfigStore, CredentialStore};
use crate::wire::{ProviderEndpointAuth, ProviderTint};

use super::*;

fn selection(instance: &str, provider: &str, model: &str) -> ProviderConfig {
    ProviderConfig {
        instance: instance.into(),
        provider: provider.into(),
        model: model.into(),
        base_url: Some("https://gateway.example/v1".into()),
        endpoint_auth: ProviderEndpointAuth::Credentialless,
        reasoning_effort: None,
        service_tier: None,
        web_search: HostedWebSearch::Off,
    }
}

async fn gateway_with_providers(
    primary: ProviderConfig,
    secondary: Option<ProviderConfig>,
) -> (tempfile::TempDir, GatewayHost) {
    let root = tempfile::tempdir().expect("root");
    let (store, config) = ConfigStore::initialize(
        root.path().join("state"),
        "127.0.0.1:8741".parse().expect("listen"),
        None,
    )
    .expect("config");
    let mut config = config
        .registering_provider(
            primary.clone(),
            "Primary".into(),
            ProviderTint::default(),
            vec![primary.model.clone()],
            Vec::new(),
            Vec::new(),
        )
        .expect("primary provider");
    if let Some(secondary) = secondary {
        config = config
            .registering_provider(
                secondary.clone(),
                "Secondary".into(),
                ProviderTint::default(),
                vec![secondary.model.clone()],
                Vec::new(),
                Vec::new(),
            )
            .expect("secondary provider");
    }
    store.save(&config).expect("save config");
    let credentials =
        Arc::new(CredentialStore::open(store.credentials_path()).expect("credentials"));
    let bots = Arc::new(BotStore::open(store.state_dir()).expect("Bots"));
    let gateway = GatewayHost::start(store, config, credentials, bots)
        .await
        .expect("gateway");
    (root, gateway)
}

#[tokio::test]
async fn saved_explicit_custom_image_route_remains_available_after_restart() {
    let root = tempfile::tempdir().expect("root");
    let workspace = root.path().join("workspace");
    std::fs::create_dir(&workspace).expect("workspace");
    let (store, config) = ConfigStore::initialize(
        root.path().join("state"),
        "127.0.0.1:8741".parse().expect("listen"),
        None,
    )
    .expect("config");
    let mut provider = selection("images", "responses", "chat-model");
    provider.endpoint_auth = ProviderEndpointAuth::ProviderDefault;
    provider.base_url = Some("http://127.0.0.1:1/v1".into());
    let mut config = config
        .registering_provider(
            provider,
            "Custom".into(),
            Default::default(),
            vec!["chat-model".into()],
            Vec::new(),
            vec!["custom-image".into()],
        )
        .expect("explicit image opt-in");
    let default = &mut config.bot_defaults.as_mut().expect("defaults").config;
    default.middleware.set_enabled("image_generation", true);
    default.middleware.set_setting(
        "image_generation",
        "model",
        Some(mobius::protocol::FrontendSettingValue::String(
            "images::custom-image::default".into(),
        )),
    );
    store.save(&config).expect("saved image selection");
    let (store, config) = ConfigStore::open(store.state_dir().to_owned())
        .expect("saved configuration stays readable");
    let credentials =
        Arc::new(CredentialStore::open(store.credentials_path()).expect("credentials"));
    credentials
        .set(
            "images",
            "responses",
            "test-key",
            Some("http://127.0.0.1:1/v1"),
            None,
        )
        .expect("credential");
    let bots = Arc::new(BotStore::open(store.state_dir()).expect("Bots"));
    let gateway = GatewayHost::start(store, config, credentials, bots)
        .await
        .expect("saved image does not block startup");
    let ready = gateway.ready().await.expect("catalog");
    assert_eq!(
        ready
            .image_models
            .iter()
            .map(|model| model.route.as_str())
            .collect::<Vec<_>>(),
        ["images::custom-image::default"]
    );
    assert!(ready.voice_models.is_empty());
    let bot = ready.bots.into_iter().next().expect("Bot");
    let host = gateway
        .create_session(&workspace, &bot.id)
        .await
        .expect("selected image route assembles");
    assert!(host.is_alive());
    gateway.shutdown().await;
}

#[tokio::test]
async fn saved_unknown_voice_keeps_chat_usable_and_never_selects_a_different_voice() {
    let root = tempfile::tempdir().expect("root");
    let workspace = root.path().join("workspace");
    std::fs::create_dir(&workspace).expect("workspace");
    let (store, config) = ConfigStore::initialize(
        root.path().join("state"),
        "127.0.0.1:8741".parse().expect("listen"),
        None,
    )
    .expect("config");
    let selection = AgentComposition::default().provider;
    let config = config
        .registering_provider(
            selection,
            "Native".into(),
            Default::default(),
            Vec::new(),
            Vec::new(),
            Vec::new(),
        )
        .expect("native provider");
    let mut secondary = AgentComposition::default().provider;
    secondary.instance = "voice-proxy".into();
    let config = config
        .registering_provider(
            secondary,
            "Voice proxy".into(),
            Default::default(),
            Vec::new(),
            Vec::new(),
            Vec::new(),
        )
        .expect("voice provider");
    let mut config = config;
    config
        .bot_defaults
        .as_mut()
        .expect("defaults")
        .config
        .realtime_voice = Some("cedar".into());
    store.save(&config).expect("save gateway");
    let credentials =
        Arc::new(CredentialStore::open(store.credentials_path()).expect("credentials"));
    for configured in config.configured_providers.values() {
        let selected = &configured.selection;
        credentials
            .set(
                &selected.instance,
                &selected.provider,
                "test-key",
                selected.base_url.as_deref(),
                None,
            )
            .expect("credential");
    }
    let bots = Arc::new(BotStore::open(store.state_dir()).expect("Bots"));
    let mut composition = config
        .bot_defaults
        .as_ref()
        .expect("defaults")
        .config
        .clone();
    composition.realtime_voice = Some("cedar".into());
    let bot = bots
        .create_bot("Voice", "Test saved voice selection.", composition)
        .expect("saved bare voice");
    let gateway = GatewayHost::start(store, config, credentials, bots)
        .await
        .expect("gateway remains usable");
    let host = gateway
        .create_session(&workspace, &bot.id)
        .await
        .expect("chat remains usable");
    let error = host
        .realtime_model()
        .await
        .err()
        .expect("unknown voice is rejected");
    assert!(error.message.contains("cedar") && error.message.contains("select an available voice"));
    assert!(host.is_alive());
    let mut edited = bot.config.config.clone();
    edited.system_prompt.push_str("\nUpdated instructions.");
    gateway
        .configure_bot_defaults(1, edited.clone())
        .await
        .expect("unrelated defaults edit retains saved voice");
    assert!(
        gateway
            .create_bot("Invalid", "Test invalid voice defaults.")
            .await
            .is_err()
    );
    let mut bot = gateway
        .update_bot(
            &bot.id,
            bot.config.revision,
            crate::bots::BotIdentity {
                name: &bot.name,
                description: &bot.description,
                tint: bot.tint,
                shape: bot.shape,
            },
            edited,
        )
        .await
        .expect("unrelated Bot edit retains saved voice");
    assert_eq!(bot.config.config.realtime_voice.as_deref(), Some("cedar"));
    let mut invalid = bot.config.config.clone();
    invalid.realtime_voice = Some("invalid-new-voice".into());
    assert!(
        gateway
            .configure_bot_defaults(2, invalid.clone())
            .await
            .is_err()
    );
    assert!(
        gateway
            .update_bot(
                &bot.id,
                bot.config.revision,
                crate::bots::BotIdentity {
                    name: &bot.name,
                    description: &bot.description,
                    tint: bot.tint,
                    shape: bot.shape,
                },
                invalid
            )
            .await
            .is_err()
    );
    for voice in [
        Some("openai_socket::gpt-live-1::cedar"),
        None,
        Some("voice-proxy::gpt-live-1::cedar"),
    ] {
        let mut config = bot.config.config.clone();
        config.realtime_voice = voice.map(str::to_owned);
        bot = gateway
            .update_bot(
                &bot.id,
                bot.config.revision,
                crate::bots::BotIdentity {
                    name: &bot.name,
                    description: &bot.description,
                    tint: bot.tint,
                    shape: bot.shape,
                },
                config,
            )
            .await
            .expect("select voice");
        let model = host.realtime_model().await.expect("voice is available");
        assert_eq!(
            model.voice,
            voice.unwrap_or("openai_socket::gpt-live-1::marin")
        );
    }
    let error = gateway
        .remove_provider("voice-proxy".into())
        .await
        .expect_err("selected voice cannot be removed");
    assert_eq!(error.code, "provider_in_use");
    gateway.shutdown().await;
}

#[tokio::test]
async fn bot_updates_obey_operator_subagent_ceilings_and_persist_larger_trees() {
    let (root, gateway) =
        gateway_with_providers(selection("primary", "responses", "custom-model"), None).await;
    let bot = gateway.bots().await.expect("Bots").remove(0);
    let mut config = bot.config.config.clone();
    for (id, value) in [
        ("max_depth", 24),
        ("max_concurrency", 96),
        ("max_agents", 300),
    ] {
        config.middleware.set_setting(
            "subagents",
            id,
            Some(mobius::protocol::FrontendSettingValue::Integer(value)),
        );
    }
    let identity = || crate::bots::BotIdentity {
        name: &bot.name,
        description: &bot.description,
        tint: bot.tint,
        shape: bot.shape,
    };
    gateway
        .update_bot(&bot.id, bot.config.revision, identity(), config.clone())
        .await
        .expect_err("paired-client update cannot exceed default host ceilings");
    {
        let state = gateway.state.lock().await;
        let mut operator = state.config.lock().expect("gateway configuration");
        operator.execution.subagent_max_depth = 32;
        operator.execution.subagent_max_concurrency = 128;
        operator.execution.subagent_max_agents = 512;
        state
            .store
            .save(&operator)
            .expect("save trusted operator configuration");
    }
    let updated = gateway
        .update_bot(&bot.id, bot.config.revision, identity(), config.clone())
        .await
        .expect("trusted host ceiling permits larger tree");
    config.middleware.set_setting(
        "subagents",
        "max_depth",
        Some(mobius::protocol::FrontendSettingValue::Integer(33)),
    );
    gateway
        .update_bot(&bot.id, updated.config.revision, identity(), config)
        .await
        .expect_err("paired-client update cannot raise the host ceiling");
    let persisted = BotStore::open(&root.path().join("state")).expect("reopen Bot storage");
    assert_eq!(
        persisted.bot(&bot.id).expect("saved Bot").config,
        updated.config
    );
    gateway.shutdown().await;
}

#[tokio::test]
async fn saved_bot_routes_survive_missing_credentials_without_advertising_unavailable_models() {
    let root = tempfile::tempdir().expect("root");
    let (store, config) = ConfigStore::initialize(
        root.path().join("state"),
        "127.0.0.1:8741".parse().expect("listen"),
        None,
    )
    .expect("config");
    let mut primary = selection("managed", "openai_socket", "gpt-6-luna");
    primary.endpoint_auth = ProviderEndpointAuth::ProviderDefault;
    let config = config
        .registering_provider(
            primary.clone(),
            "Managed".into(),
            ProviderTint::default(),
            Vec::new(),
            Vec::new(),
            Vec::new(),
        )
        .expect("provider");
    store.save(&config).expect("save config");
    let route = "managed::gpt-6-luna::low";
    let mut composition = config
        .bot_defaults
        .as_ref()
        .expect("defaults")
        .config
        .clone();
    composition.middleware.set_setting(
        "subagents",
        "model_route",
        Some(mobius::protocol::FrontendSettingValue::String(route.into())),
    );
    composition.middleware.set_setting(
        "image_generation",
        "model",
        Some(mobius::protocol::FrontendSettingValue::String(
            "managed::gpt-image-2.5-sunburst::high".into(),
        )),
    );
    let bots = Arc::new(BotStore::open(store.state_dir()).expect("Bots"));
    let saved = bots
        .create_bot(
            "Saved route",
            "Keep the selected subagent model.",
            composition.clone(),
        )
        .expect("save Bot");
    let credentials =
        Arc::new(CredentialStore::open(store.credentials_path()).expect("credentials"));
    let gateway = GatewayHost::start(
        store.clone(),
        config.clone(),
        Arc::clone(&credentials),
        Arc::clone(&bots),
    )
    .await
    .expect("saved configured route must not require a credential to boot");
    crate::assembly::prepare_bot(
        &config,
        bots.bot(&saved.id).expect("saved Bot"),
        &store,
        &credentials,
        mobius::backend::session_files::SessionFileStore::new(store.state_dir(), None),
        0,
        Arc::new(crate::computer_runtime::ComputerConfig::default()),
    )
    .await
    .expect("saved image route survives unavailable credentials");
    let ready = gateway.ready().await.expect("ready without credentials");
    assert!(ready.models.is_empty());
    assert!(!ready.provider_instances[0].configured);
    assert_eq!(bots.bot(&saved.id).expect("unchanged Bot"), saved);
    assert!(
        gateway
            .configure_bot_defaults(1, composition.clone())
            .await
            .is_err()
    );

    gateway
        .set_credential(
            primary.instance.clone(),
            primary.provider.clone(),
            "restored-test-credential".into(),
            primary.base_url.clone(),
            None,
        )
        .await
        .expect("install credential");
    let ready = gateway.ready().await.expect("ready with credentials");
    assert!(ready.models.iter().any(|model| model.route == route));
    assert!(ready.provider_instances[0].configured);
    assert_eq!(bots.bot(&saved.id).expect("unchanged Bot"), saved);

    composition.middleware.set_setting(
        "subagents",
        "model_route",
        Some(mobius::protocol::FrontendSettingValue::String(
            "unconfigured::gpt-6-luna::low".into(),
        )),
    );
    bots.update_bot(
        &saved.id,
        saved.config.revision,
        crate::bots::BotIdentity {
            name: &saved.name,
            description: &saved.description,
            tint: saved.tint,
            shape: saved.shape,
        },
        composition,
    )
    .expect("persist invalid route for startup validation");
    let error = GatewayHost::start(store, config, credentials, bots)
        .await
        .err()
        .expect("unconfigured route must still fail boot");
    assert!(error.to_string().contains("subagents.model_route"));
}

#[tokio::test]
async fn provider_removal_rejects_a_bot_reference() {
    let primary = selection("primary", "openrouter", "openai/gpt-5");
    let removable = selection("secondary", "openrouter", "openai/gpt-5.1");
    let (_root, gateway) = gateway_with_providers(primary.clone(), Some(removable.clone())).await;
    let composition = AgentComposition {
        provider: removable.clone(),
        ..AgentComposition::default()
    };
    let bot = gateway
        .state
        .lock()
        .await
        .bots
        .create_bot("secondary", "Secondary", composition)
        .expect("Bot");

    let error = gateway
        .remove_provider(removable.instance.clone())
        .await
        .expect_err("referenced provider");

    assert_eq!(error.code, "provider_in_use");
    assert!(error.message.contains(&format!("@{}", bot.handle)));
    assert!(
        gateway
            .state
            .lock()
            .await
            .config
            .lock()
            .expect("config")
            .configured_providers
            .contains_key(&removable.instance)
    );
}

#[tokio::test]
async fn provider_replacement_rejects_a_bot_reference_without_changing_either_store() {
    let primary = selection("primary", "openrouter", "openai/gpt-5");
    let original = selection("secondary", "openrouter", "openai/gpt-5.1");
    let replacement = selection("secondary", "openrouter", "openai/gpt-5.2");
    let (root, gateway) = gateway_with_providers(primary, Some(original.clone())).await;
    let composition = AgentComposition {
        provider: original.clone(),
        ..AgentComposition::default()
    };
    let bot = gateway
        .state
        .lock()
        .await
        .bots
        .create_bot("secondary", "Secondary", composition)
        .expect("Bot");
    let state_dir = root.path().join("state");
    let gateway_path = state_dir.join("gateway.toml");
    let bots_path = state_dir.join("bots.sqlite3");
    let gateway_before = std::fs::read(&gateway_path).expect("gateway config before");
    let bots_before = std::fs::read(&bots_path).expect("Bot state before");

    let error = gateway
        .register_provider(
            false,
            crate::config::ConfiguredProvider {
                selection: replacement.clone(),
                label: "Secondary".into(),
                tint: ProviderTint::default(),
                model_ids: vec![replacement.model.clone()],
                reasoning_efforts: Vec::new(),
                image_model_ids: Vec::new(),
            },
        )
        .await
        .expect_err("referenced provider replacement");

    assert_eq!(error.code, "provider_in_use");
    assert!(error.message.contains("@secondary"));
    assert_eq!(
        std::fs::read(&gateway_path).expect("gateway config after"),
        gateway_before
    );
    assert_eq!(
        std::fs::read(&bots_path).expect("Bot state after"),
        bots_before
    );
    let (_, reopened_gateway) = ConfigStore::open(state_dir.clone()).expect("reopen gateway");
    assert_eq!(
        reopened_gateway.configured_providers["secondary"].selection,
        original
    );
    let reopened_bots = BotStore::open(&state_dir).expect("reopen Bots");
    assert_eq!(reopened_bots.bot(&bot.id).expect("Bot"), bot);
}