stubb 0.1.0

A Rust library for embedding coding agents (Codex, Claude Code, Pi, and ACP agents) in your application
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
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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
use super::driver::CodexSession;
use super::{EffectivePermissions, Permissions, connection, history, types, usage};

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::catalog::{self, Catalog, FastMode, ProviderInfo};
use crate::process::Environment;
use crate::provider::BoxFuture;
use crate::session::{self, Session};
use crate::{Error, Provider, Result, turn};
use connection::AppServer;
use types::{ModelListParams, ModelListResponse, ThreadSettingsParams};

pub(crate) const PROVIDER_ID: &str = "codex";
pub(super) const PAGE_LIMIT: u32 = 100;
pub(super) const MAX_PAGES: usize = 50;
/// Thread sources included in session lists; sub-agent threads are left out.
const SESSION_SOURCES: [&str; 4] = ["cli", "vscode", "exec", "appServer"];

/// How to reach a Codex installation.
#[derive(Debug, Clone)]
pub struct CodexConfig {
    /// The `codex` executable; a bare name is resolved through `PATH`.
    pub executable: PathBuf,
    /// Include models Codex hides from its default picker.
    pub include_hidden: bool,
    /// Deadline for starting the app-server and completing the handshake.
    pub startup_timeout: Duration,
    /// Deadline for each request.
    pub request_timeout: Duration,
    /// How long the app-server may sit unused, with no live session and no
    /// request waiting, before it is closed; `None` keeps it until
    /// [`Codex::shutdown`]. The next call starts it again.
    pub idle_timeout: Option<Duration>,
    /// The environment of the app-server, and so of every command it runs:
    /// the host's whole environment by default.
    pub environment: Environment,
    /// The reasoning summary every turn asks for: `auto` (the default),
    /// `concise`, `detailed` or `none`. Codex reports a model's reasoning
    /// only as this summary, so without one its thinking items have no
    /// text; the model may still skip it for short reasoning. `None` sends
    /// nothing and keeps Codex's own setting (`model_reasoning_summary`).
    pub reasoning_summary: Option<String>,
}

impl Default for CodexConfig {
    fn default() -> Self {
        Self {
            executable: PathBuf::from("codex"),
            include_hidden: false,
            startup_timeout: Duration::from_secs(30),
            request_timeout: Duration::from_secs(30),
            idle_timeout: Some(Duration::from_secs(600)),
            environment: Environment::inherit(),
            reasoning_summary: Some("auto".to_owned()),
        }
    }
}

/// The Codex provider for one execution context.
pub struct Codex {
    config: CodexConfig,
    connection: Arc<tokio::sync::Mutex<Option<Arc<AppServer>>>>,
    /// Calls that used the connection, so a short request between two idle
    /// checks still counts as use.
    uses: Arc<AtomicU64>,
    /// Last catalog, used to validate settings and resolve fast-mode tiers.
    catalog: Mutex<Option<Catalog>>,
}

impl Codex {
    pub fn new(config: CodexConfig) -> Self {
        Self {
            config,
            connection: Arc::new(tokio::sync::Mutex::new(None)),
            uses: Arc::new(AtomicU64::new(0)),
            catalog: Mutex::new(None),
        }
    }

    pub fn config(&self) -> &CodexConfig {
        &self.config
    }

    /// Whether an app-server process is currently running.
    pub async fn is_connected(&self) -> bool {
        self.connection
            .lock()
            .await
            .as_ref()
            .is_some_and(|connection| connection.is_alive())
    }

    pub async fn catalog(&self) -> Result<Catalog> {
        let connection = self.connection().await?;
        let mut models = Vec::new();
        let mut cursor = None;
        for _ in 0..MAX_PAGES {
            let page: ModelListResponse = connection
                .request(
                    "model/list",
                    &ModelListParams {
                        cursor: cursor.take(),
                        limit: Some(PAGE_LIMIT),
                        include_hidden: Some(self.config.include_hidden),
                    },
                    self.config.request_timeout,
                )
                .await?;
            models.extend(page.data);
            match page.next_cursor {
                Some(next) => cursor = Some(next),
                None => break,
            }
        }
        let catalog = build_catalog(connection.user_agent().map(str::to_owned), models);
        *self.catalog.lock().expect("catalog lock") = Some(catalog.clone());
        Ok(catalog)
    }

    /// Account quotas through Codex's read-only `account/rateLimits/read`,
    /// over the shared app-server connection: no thread starts and no
    /// prompt is sent. Accounts without ChatGPT sign-in return an RPC error.
    pub async fn account_usage(&self) -> Result<crate::usage::Account> {
        let raw: Value = self
            .request("account/rateLimits/read", &serde_json::json!({}))
            .await?;
        Ok(usage::account(raw))
    }

    /// Stored sessions, most recently updated first.
    pub async fn list_sessions(&self, query: session::Query) -> Result<session::Page> {
        let response: types::ThreadListResponse = self
            .request(
                "thread/list",
                &types::ThreadListParams {
                    cursor: query.cursor,
                    limit: query.limit,
                    sort_key: "updated_at",
                    cwd: query.cwd.map(|cwd| cwd.to_string_lossy().into_owned()),
                    source_kinds: SESSION_SOURCES.to_vec(),
                    sort_direction: "desc",
                    parent_thread_id: None,
                    ancestor_thread_id: None,
                },
            )
            .await?;
        Ok(session::Page {
            sessions: response.data.into_iter().map(history::summary).collect(),
            next_cursor: response.next_cursor,
        })
    }

    pub async fn read_session(&self, id: &str) -> Result<session::Summary> {
        let response: types::ThreadReadResponse = self
            .request("thread/read", &types::ThreadIdParams { thread_id: id })
            .await
            .map_err(|error| unknown_session(id, error))?;
        Ok(history::summary(response.thread))
    }

    /// Stored turns, oldest first. Works without loading the session.
    pub async fn list_turns(&self, id: &str, query: turn::Query) -> Result<turn::Page> {
        let response: types::ThreadTurnsListResponse = self
            .request(
                "thread/turns/list",
                &types::ThreadTurnsListParams {
                    thread_id: id,
                    cursor: query.cursor,
                    limit: query.limit,
                    sort_direction: "asc",
                    items_view: "full",
                },
            )
            .await
            .map_err(|error| unknown_session(id, error))?;
        Ok(turn::Page {
            turns: response.data.into_iter().map(history::turn).collect(),
            next_cursor: response.next_cursor,
        })
    }

    /// Starts a new thread. Codex keeps it in memory until its first turn.
    pub async fn start_session(&self, spec: session::Spec) -> Result<Session> {
        let settings = self.settings_params(&spec.settings, true).await?;
        let connection = self.connection().await?;
        let response: types::ThreadSessionResponse = connection
            .request(
                "thread/start",
                &types::ThreadStartParams {
                    cwd: spec.cwd.to_string_lossy().into_owned(),
                    settings,
                },
                self.config.request_timeout,
            )
            .await?;
        Ok(self.open(connection, response, false, spec.settings.permissions))
    }

    /// Loads a stored thread into the app-server so it can take new turns.
    pub async fn resume_session(&self, id: &str, settings: session::Settings) -> Result<Session> {
        let requested_permissions = settings.permissions.clone();
        let settings = self.settings_params(&settings, false).await?;
        let connection = self.connection().await?;
        let response: types::ThreadSessionResponse = connection
            .request(
                "thread/resume",
                &types::ThreadResumeParams {
                    thread_id: id,
                    exclude_turns: true,
                    settings,
                },
                self.config.request_timeout,
            )
            .await
            .map_err(|error| match error {
                // Codex allows one writer per thread across all processes.
                Error::Rpc { message, .. } if message.contains("active writer") => {
                    Error::SessionInUse {
                        id: id.to_owned(),
                        message,
                    }
                }
                other => unknown_session(id, other),
            })?;
        let session = self.open(
            Arc::clone(&connection),
            response,
            true,
            requested_permissions,
        );
        if let Err(error) = self.discover_stored(&connection, id).await {
            connection.discovery_failed(id, &error.to_string());
        }
        Ok(session)
    }

    /// Forks a stored thread with Codex's own `thread/fork`, through
    /// `fork.at_turn` when given. The fork is written to disk at once with
    /// the original turn ids, and is not left loaded: resume it to continue.
    pub async fn fork_session(&self, id: &str, fork: session::Fork) -> Result<session::Summary> {
        let connection = self.connection().await?;
        let response: types::ThreadReadResponse = connection
            .request(
                "thread/fork",
                &types::ThreadForkParams {
                    thread_id: id,
                    last_turn_id: fork.at_turn.as_deref(),
                    ephemeral: false,
                    exclude_turns: true,
                },
                self.config.request_timeout,
            )
            .await
            .map_err(|error| match (error, &fork.at_turn) {
                (Error::Rpc { message, .. }, Some(turn))
                    if message.starts_with("turn not found") =>
                {
                    Error::TurnNotFound {
                        session_id: id.to_owned(),
                        id: turn.clone(),
                    }
                }
                (other, _) => unknown_session(id, other),
            })?;
        let mut summary = history::summary(response.thread);
        // `thread/fork` loads the fork and subscribes this connection to it;
        // the host resumes it when it wants to continue. The fork is stored
        // already, so a failure here does not undo it.
        let _ = connection
            .request::<_, Value>(
                "thread/unsubscribe",
                &types::ThreadIdParams {
                    thread_id: &summary.id,
                },
                self.config.request_timeout,
            )
            .await;
        summary.status = session::Status::NotLoaded;
        Ok(summary)
    }

    pub async fn shutdown(&self) {
        let connection = self.connection.lock().await.take();
        if let Some(connection) = connection {
            connection.shutdown().await;
        }
    }

    pub(super) async fn connection(&self) -> Result<Arc<AppServer>> {
        let mut slot = self.connection.lock().await;
        self.uses.fetch_add(1, Ordering::Relaxed);
        if let Some(connection) = slot.as_ref().filter(|connection| connection.is_alive()) {
            return Ok(Arc::clone(connection));
        }
        let timeout = self.config.startup_timeout;
        let connection = tokio::time::timeout(
            timeout,
            AppServer::start(
                &self.config.executable,
                &self.config.environment,
                self.config.request_timeout,
            ),
        )
        .await
        .map_err(|_| Error::Timeout(timeout))??;
        let connection = Arc::new(connection);
        *slot = Some(Arc::clone(&connection));
        if let Some(idle) = self.config.idle_timeout {
            close_when_idle(
                Arc::downgrade(&self.connection),
                Arc::clone(&self.uses),
                Arc::as_ptr(&connection) as usize,
                idle,
            );
        }
        Ok(connection)
    }

    pub(super) async fn request<P, R>(&self, method: &str, params: &P) -> Result<R>
    where
        P: Serialize,
        R: DeserializeOwned,
    {
        self.connection()
            .await?
            .request(method, params, self.config.request_timeout)
            .await
    }

    async fn known_catalog(&self) -> Result<Catalog> {
        let cached = self.catalog.lock().expect("catalog lock").clone();
        match cached {
            Some(catalog) => Ok(catalog),
            None => self.catalog().await,
        }
    }

    /// Validates requested settings against the catalog and translates them.
    /// Without an explicit model, a new thread is checked against the default
    /// model; a resumed thread keeps its stored model, so only an explicit
    /// fast-mode request needs one.
    async fn settings_params(
        &self,
        settings: &session::Settings,
        new_thread: bool,
    ) -> Result<ThreadSettingsParams> {
        let permissions = match &settings.permissions {
            None => None,
            Some(configuration) if configuration.is::<Permissions>() => {
                configuration.get::<Permissions>()?
            }
            Some(_) => {
                return Err(Error::Unsupported {
                    operation: "permission_configuration",
                });
            }
        };
        let permissions = permissions.as_ref();
        if let Some(permissions) = permissions {
            permissions.validate()?;
        }
        let needs_catalog = settings.model.is_some()
            || settings.fast_mode == Some(true)
            || (new_thread && settings.effort.is_some());
        let model = if needs_catalog {
            let catalog = self.known_catalog().await?;
            let model = match settings.model.as_deref() {
                Some(id) => catalog.models.iter().find(|model| model.id == id).cloned(),
                None if new_thread => catalog
                    .models
                    .iter()
                    .find(|model| model.is_default)
                    .cloned(),
                None => None,
            };
            if model.is_none() && (settings.model.is_some() || settings.fast_mode == Some(true)) {
                return Err(Error::InvalidSetting {
                    setting: "model",
                    value: settings.model.clone().unwrap_or_default(),
                    reason:
                        "not in Codex's model list; fast mode needs an explicit model when resuming"
                            .to_owned(),
                });
            }
            model
        } else {
            None
        };

        if let (Some(effort), Some(model)) = (&settings.effort, &model)
            && !model.efforts.iter().any(|option| &option.id == effort)
        {
            return Err(Error::InvalidSetting {
                setting: "effort",
                value: effort.clone(),
                reason: format!("{} does not support it", model.id),
            });
        }

        let service_tier = match settings.fast_mode {
            None => None,
            Some(false) => Some(None),
            Some(true) => match model.as_ref().map(|model| &model.fast_mode) {
                Some(FastMode::Available { tier_id, .. }) => Some(Some(tier_id.clone())),
                _ => {
                    return Err(Error::InvalidSetting {
                        setting: "fast_mode",
                        value: "true".to_owned(),
                        reason: "the model has no fast tier".to_owned(),
                    });
                }
            },
        };

        let mut config = HashMap::new();
        if let Some(effort) = &settings.effort {
            config.insert(
                "model_reasoning_effort".into(),
                Value::String(effort.clone()),
            );
        }
        if let Some(permissions) = permissions {
            permissions.apply_config(&mut config);
        }
        Ok(ThreadSettingsParams {
            model: settings.model.clone(),
            service_tier,
            approval_policy: permissions.and_then(|p| p.approval_policy.clone()),
            sandbox: permissions.and_then(Permissions::mode).map(str::to_owned),
            permissions: permissions.and_then(|p| p.profile.clone()),
            config: (!config.is_empty()).then_some(config),
        })
    }

    fn open(
        &self,
        connection: Arc<AppServer>,
        response: types::ThreadSessionResponse,
        restored: bool,
        requested_permissions: Option<crate::permission::Configuration>,
    ) -> Session {
        let fast_tier = self
            .catalog
            .lock()
            .expect("catalog lock")
            .as_ref()
            .and_then(|catalog| {
                catalog
                    .models
                    .iter()
                    .find(|model| model.id == response.model)
            })
            .and_then(|model| match &model.fast_mode {
                FastMode::Available { tier_id, .. } => Some(tier_id.clone()),
                FastMode::Unavailable => None,
            });
        let fast_mode = match (&response.service_tier, fast_tier) {
            (Some(tier), Some(fast_tier)) => *tier == fast_tier,
            (Some(_), None) => true,
            (None, _) => false,
        };

        let thread_id = response.thread.id.clone();
        let info = session::Info {
            model: response.model,
            effort: response.reasoning_effort,
            fast_mode,
            cwd: response.cwd,
            permissions: Some(crate::permission::Info {
                requested: requested_permissions,
                effective: crate::permission::Configuration::new(
                    &EffectivePermissions::from_native(
                        &response.approval_policy,
                        &response.sandbox,
                        &response.active_permission_profile,
                    ),
                ),
            }),
            approval_policy: history::describe(&response.approval_policy),
            sandbox: history::describe(&response.sandbox),
            restored,
            persisted: restored,
            summary: history::summary(response.thread),
        };
        let attachment = connection.observe(&info);
        let driver = CodexSession {
            connection,
            thread_id,
            attachment,
            request_timeout: self.config.request_timeout,
            overrides: std::sync::Mutex::new(None),
            reasoning_summary: self.config.reasoning_summary.clone(),
        };
        Session::new(info, Arc::new(driver))
    }
}

/// Closes the app-server `connection` (named by its address) once it has
/// been idle for `idle`: no session object holds it or no session is live,
/// no request waits, and no call used it meanwhile. Ends when the provider
/// is gone or holds another connection.
fn close_when_idle(
    slot: std::sync::Weak<tokio::sync::Mutex<Option<Arc<AppServer>>>>,
    uses: Arc<AtomicU64>,
    connection: usize,
    idle: Duration,
) {
    tokio::spawn(async move {
        let poll = (idle / 10).clamp(Duration::from_millis(10), Duration::from_secs(5));
        let mut since: Option<(tokio::time::Instant, u64)> = None;
        loop {
            tokio::time::sleep(poll).await;
            let Some(slot) = slot.upgrade() else {
                return;
            };
            let mut guard = slot.lock().await;
            let Some(current) = guard
                .as_ref()
                .filter(|current| Arc::as_ptr(current) as usize == connection)
            else {
                return;
            };
            if !current.is_alive() {
                return;
            }
            // The provider's slot holds one reference; sessions hold the rest.
            let used = uses.load(Ordering::Relaxed);
            if !current.is_idle(Arc::strong_count(current) > 1) {
                since = None;
                continue;
            }
            match since {
                Some((at, seen)) if seen == used => {
                    if at.elapsed() >= idle {
                        let closing = guard.take().expect("checked above");
                        drop(guard);
                        closing.shutdown().await;
                        return;
                    }
                }
                _ => since = Some((tokio::time::Instant::now(), used)),
            }
        }
    });
}

impl Provider for Codex {
    fn id(&self) -> &'static str {
        PROVIDER_ID
    }

    fn capabilities(&self) -> crate::provider::Capabilities {
        crate::provider::Capabilities { fork_session: true }
    }

    fn fork_session<'a>(
        &'a self,
        id: &'a str,
        fork: session::Fork,
    ) -> BoxFuture<'a, Result<session::Summary>> {
        Box::pin(Codex::fork_session(self, id, fork))
    }

    fn account_usage(&self) -> BoxFuture<'_, Result<crate::usage::Account>> {
        Box::pin(Codex::account_usage(self))
    }

    fn catalog(&self) -> BoxFuture<'_, Result<Catalog>> {
        Box::pin(Codex::catalog(self))
    }

    fn list_sessions(&self, query: session::Query) -> BoxFuture<'_, Result<session::Page>> {
        Box::pin(Codex::list_sessions(self, query))
    }

    fn read_session<'a>(&'a self, id: &'a str) -> BoxFuture<'a, Result<session::Summary>> {
        Box::pin(Codex::read_session(self, id))
    }

    fn list_turns<'a>(
        &'a self,
        id: &'a str,
        query: turn::Query,
    ) -> BoxFuture<'a, Result<turn::Page>> {
        Box::pin(Codex::list_turns(self, id, query))
    }

    fn list_agents<'a>(
        &'a self,
        root: &'a str,
        query: crate::observation::agent::Query,
    ) -> BoxFuture<'a, Result<crate::observation::agent::Page>> {
        Box::pin(Codex::list_agents(self, root, query))
    }
    fn list_agent_turns<'a>(
        &'a self,
        root: &'a str,
        id: &'a str,
        query: turn::Query,
    ) -> BoxFuture<'a, Result<crate::observation::agent::TurnPage>> {
        Box::pin(Codex::list_agent_turns(self, root, id, query))
    }

    fn start_session(&self, spec: session::Spec) -> BoxFuture<'_, Result<Session>> {
        Box::pin(Codex::start_session(self, spec))
    }

    fn resume_session<'a>(
        &'a self,
        id: &'a str,
        settings: session::Settings,
    ) -> BoxFuture<'a, Result<Session>> {
        Box::pin(Codex::resume_session(self, id, settings))
    }

    fn shutdown(&self) -> BoxFuture<'_, ()> {
        Box::pin(Codex::shutdown(self))
    }
}

/// Codex reports an unknown or malformed thread id only in its error
/// message; Stubb reports it as [`Error::SessionNotFound`].
pub(super) fn unknown_session(id: &str, error: Error) -> Error {
    const UNKNOWN: [&str; 4] = [
        "thread not loaded",
        "no rollout found",
        "invalid thread id",
        "invalid session id",
    ];
    match error {
        Error::Rpc { message, .. } if UNKNOWN.iter().any(|prefix| message.starts_with(prefix)) => {
            Error::SessionNotFound { id: id.to_owned() }
        }
        other => other,
    }
}

fn build_catalog(user_agent: Option<String>, models: Vec<types::Model>) -> Catalog {
    Catalog {
        provider: ProviderInfo {
            id: PROVIDER_ID.to_owned(),
            version: user_agent.as_deref().and_then(version_from_user_agent),
            user_agent,
        },
        models: models.into_iter().map(model_info).collect(),
    }
}

fn model_info(model: types::Model) -> catalog::Model {
    let fast_mode = fast_mode(&model);
    catalog::Model {
        id: model.id,
        label: model.display_name,
        description: model.description,
        is_default: model.is_default,
        efforts: model
            .supported_reasoning_efforts
            .into_iter()
            .map(|effort| catalog::Effort {
                id: effort.reasoning_effort,
                description: effort.description,
            })
            .collect(),
        default_effort: model.default_reasoning_effort,
        fast_mode,
    }
}

/// Codex advertises speed as service tiers; the tier named "Fast" (currently
/// id `priority`) is fast mode. Older releases only list `fast` in the
/// deprecated `additionalSpeedTiers` field.
fn fast_mode(model: &types::Model) -> FastMode {
    let tier = model
        .service_tiers
        .iter()
        .find(|tier| tier.name.eq_ignore_ascii_case("fast") || tier.id == "fast");
    if let Some(tier) = tier {
        return FastMode::Available {
            tier_id: tier.id.clone(),
            label: tier.name.clone(),
            description: tier.description.clone(),
            default_on: model.default_service_tier.as_deref() == Some(tier.id.as_str()),
        };
    }
    if model
        .additional_speed_tiers
        .iter()
        .any(|tier| tier == "fast")
    {
        return FastMode::Available {
            tier_id: "fast".to_owned(),
            label: "Fast".to_owned(),
            description: String::new(),
            default_on: model.default_service_tier.as_deref() == Some("fast"),
        };
    }
    FastMode::Unavailable
}

/// The user agent starts with `<client>/<codex version>`.
fn version_from_user_agent(user_agent: &str) -> Option<String> {
    let product = user_agent.split_whitespace().next()?;
    let (_, version) = product.split_once('/')?;
    Some(version.to_owned())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::codex::{ApprovalPolicy, Sandbox};

    const FIXTURE: &str = include_str!("fixtures/codex-model-list-0.159.3.json");

    #[test]
    fn reports_unknown_threads_as_not_found() {
        let rpc = |message: &str| Error::Rpc {
            method: "thread/read".to_owned(),
            code: -32600,
            message: message.to_owned(),
        };
        assert!(matches!(
            unknown_session("t1", rpc("thread not loaded: t1")),
            Error::SessionNotFound { id } if id == "t1"
        ));
        assert!(matches!(
            unknown_session("t1", rpc("no rollout found for thread id t1")),
            Error::SessionNotFound { .. }
        ));
        assert!(matches!(
            unknown_session("t1", rpc("rate limited")),
            Error::Rpc { .. }
        ));
    }

    fn fixture_catalog() -> Catalog {
        let page: ModelListResponse = serde_json::from_str(FIXTURE).expect("fixture decodes");
        build_catalog(
            Some("stubb/0.159.3 (NixOS 26.11.0; x86_64) unknown (stubb; 0.1.0)".to_owned()),
            page.data,
        )
    }

    fn model<'a>(catalog: &'a Catalog, id: &str) -> &'a catalog::Model {
        catalog
            .models
            .iter()
            .find(|model| model.id == id)
            .unwrap_or_else(|| panic!("model {id} present"))
    }

    fn effort_ids(model: &catalog::Model) -> Vec<&str> {
        model
            .efforts
            .iter()
            .map(|effort| effort.id.as_str())
            .collect()
    }

    #[test]
    fn maps_every_model_with_one_default() {
        let catalog = fixture_catalog();
        assert_eq!(catalog.models.len(), 8);
        let defaults: Vec<_> = catalog.models.iter().filter(|m| m.is_default).collect();
        assert_eq!(defaults.len(), 1);
        assert_eq!(defaults[0].id, "gpt-6.1-sol");
        assert_eq!(catalog.provider.version.as_deref(), Some("0.159.3"));
    }

    #[test]
    fn efforts_depend_on_the_model() {
        let catalog = fixture_catalog();
        assert_eq!(
            effort_ids(model(&catalog, "gpt-5.5")),
            ["low", "medium", "high", "xhigh"]
        );
        assert!(!effort_ids(model(&catalog, "gpt-6-luna")).contains(&"ultra"));
        assert!(effort_ids(model(&catalog, "gpt-6.1-sol")).contains(&"ultra"));
        assert_eq!(
            model(&catalog, "gpt-6-luna").default_effort.as_deref(),
            Some("medium")
        );
    }

    #[test]
    fn fast_mode_comes_from_service_tiers() {
        let catalog = fixture_catalog();
        match &model(&catalog, "gpt-6-sol").fast_mode {
            FastMode::Available {
                tier_id,
                label,
                default_on,
                ..
            } => {
                assert_eq!(tier_id, "priority");
                assert_eq!(label, "Fast");
                assert!(*default_on);
            }
            FastMode::Unavailable => panic!("gpt-6-sol supports fast mode"),
        }
        assert!(matches!(
            model(&catalog, "gpt-6.1-sol").fast_mode,
            FastMode::Available {
                default_on: false,
                ..
            }
        ));
    }

    #[test]
    fn reads_version_from_user_agent() {
        assert_eq!(version_from_user_agent("unknown").as_deref(), None);
        assert_eq!(
            version_from_user_agent("stubb/0.159.0 (Linux; x86_64)").as_deref(),
            Some("0.159.0")
        );
    }
    #[tokio::test]
    async fn permission_overrides_merge_with_effort_and_apply_to_start_and_resume() {
        let provider = Codex::new(CodexConfig::default());
        *provider.catalog.lock().unwrap() = Some(fixture_catalog());
        let settings = session::Settings {
            effort: Some("low".into()),
            fast_mode: Some(false),
            permissions: Some(
                Permissions {
                    approval_policy: Some(ApprovalPolicy::OnRequest),
                    sandbox: Some(Sandbox::WorkspaceWrite {
                        writable_roots: Some(vec!["/extra".into()]),
                        network_access: Some(false),
                        exclude_tmpdir_env_var: Some(true),
                        exclude_slash_tmp: Some(true),
                    }),
                    profile: None,
                }
                .into(),
            ),
            ..Default::default()
        };
        for new_thread in [true, false] {
            let params = provider
                .settings_params(&settings, new_thread)
                .await
                .unwrap();
            let value = serde_json::to_value(&params).unwrap();
            assert_eq!(value["approvalPolicy"], "on-request");
            assert_eq!(value["sandbox"], "workspace-write");
            assert!(value["serviceTier"].is_null());
            assert_eq!(
                value["config"],
                serde_json::json!({
                    "model_reasoning_effort":"low",
                    "sandbox_workspace_write.writable_roots":["/extra"],
                    "sandbox_workspace_write.network_access":false,
                    "sandbox_workspace_write.exclude_tmpdir_env_var":true,
                    "sandbox_workspace_write.exclude_slash_tmp":true
                })
            );
            let wire = if new_thread {
                serde_json::to_value(types::ThreadStartParams {
                    cwd: "/work".into(),
                    settings: params,
                })
                .unwrap()
            } else {
                serde_json::to_value(types::ThreadResumeParams {
                    thread_id: "stored",
                    exclude_turns: true,
                    settings: params,
                })
                .unwrap()
            };
            assert_eq!(wire["approvalPolicy"], "on-request");
            assert_eq!(wire["sandbox"], "workspace-write");
        }
        assert!(!provider.is_connected().await);
    }

    #[tokio::test]
    async fn omitted_permissions_leave_native_configuration_untouched() {
        let provider = Codex::new(CodexConfig::default());
        for new_thread in [true, false] {
            let params = provider
                .settings_params(&session::Settings::default(), new_thread)
                .await
                .unwrap();
            assert_eq!(serde_json::to_value(params).unwrap(), serde_json::json!({}));
        }
    }

    #[tokio::test]
    async fn invalid_permissions_fail_before_starting_codex() {
        let provider = Codex::new(CodexConfig {
            executable: "/missing/codex".into(),
            ..Default::default()
        });
        let settings = session::Settings {
            model: Some("not-in-catalog".into()),
            permissions: Some(
                Permissions {
                    profile: Some("named".into()),
                    sandbox: Some(Sandbox::ReadOnly),
                    ..Default::default()
                }
                .into(),
            ),
            ..Default::default()
        };
        assert!(matches!(
            provider
                .start_session(session::Spec {
                    cwd: "/work".into(),
                    settings: settings.clone()
                })
                .await,
            Err(Error::InvalidSetting {
                setting: "permissions",
                ..
            })
        ));
        assert!(matches!(
            provider.resume_session("missing", settings).await,
            Err(Error::InvalidSetting {
                setting: "permissions",
                ..
            })
        ));
        assert!(!provider.is_connected().await);
    }

    #[tokio::test]
    async fn named_profiles_are_forwarded_without_a_sandbox_override() {
        let provider = Codex::new(CodexConfig::default());
        let settings = session::Settings {
            permissions: Some(
                Permissions {
                    profile: Some("named".into()),
                    ..Default::default()
                }
                .into(),
            ),
            ..Default::default()
        };
        let value = serde_json::to_value(provider.settings_params(&settings, false).await.unwrap())
            .unwrap();
        assert_eq!(value, serde_json::json!({"permissions":"named"}));
    }
}