Skip to main content

codex_sdk_rs/
async_client.rs

1use std::future::Future;
2use std::pin::Pin;
3use std::sync::{Arc, Mutex, RwLock};
4use std::task::{Context, Poll};
5use std::time::Duration;
6
7use futures_core::Stream;
8use serde::Deserialize;
9use serde_json::{Map, Value, json};
10use tokio::sync::Mutex as AsyncMutex;
11use tokio_stream::StreamExt;
12use tokio_stream::wrappers::UnboundedReceiverStream;
13
14use crate::config::CodexConfig;
15use crate::error::{Error, Result, is_retryable_error};
16use crate::options::{
17    ThreadForkOptions, ThreadListOptions, ThreadResumeOptions, ThreadStartOptions, TurnOptions,
18    apply_approval_mode, apply_sandbox_mode, apply_sandbox_policy, serialize_options,
19};
20use crate::transport::{NotificationReceiver, Transport};
21use crate::types::{
22    AccountLoginCompletedNotification, CancelLoginAccountResponse, GetAccountResponse,
23    InitializeResponse, Input, ModelListResponse, Notification, NotificationPayload, RetryPolicy,
24    ServerInfo, ThreadArchiveResponse, ThreadCompactStartResponse, ThreadData, ThreadListResponse,
25    ThreadReadResponse, ThreadSetNameResponse, Turn, TurnInterruptResponse, TurnResult,
26    TurnSteerResponse,
27};
28
29#[derive(Debug, Default)]
30struct ClientState {
31    transport: RwLock<Option<Transport>>,
32    metadata: RwLock<Option<InitializeResponse>>,
33    initialize_lock: AsyncMutex<()>,
34}
35
36/// Asynchronous Codex client mirroring Python's `AsyncCodex`.
37#[derive(Clone, Debug)]
38pub struct AsyncCodex {
39    config: Arc<CodexConfig>,
40    state: Arc<ClientState>,
41}
42
43impl AsyncCodex {
44    pub fn new(config: CodexConfig) -> Self {
45        Self {
46            config: Arc::new(config),
47            state: Arc::new(ClientState::default()),
48        }
49    }
50
51    pub fn with_defaults() -> Self {
52        Self::new(CodexConfig::default())
53    }
54
55    pub async fn connect(config: CodexConfig) -> Result<Self> {
56        let client = Self::new(config);
57        client.start().await?;
58        Ok(client)
59    }
60
61    /// Start the process and complete the initialize handshake.
62    pub async fn start(&self) -> Result<()> {
63        self.transport().await.map(|_| ())
64    }
65
66    pub fn metadata(&self) -> Result<InitializeResponse> {
67        self.state
68            .metadata
69            .read()
70            .expect("metadata lock poisoned")
71            .clone()
72            .ok_or_else(|| {
73                Error::InvalidConfiguration(
74                    "AsyncCodex is not initialized; call start() or an API method first".into(),
75                )
76            })
77    }
78
79    pub async fn close(&self) -> Result<()> {
80        let _initializing = self.state.initialize_lock.lock().await;
81        let transport = self
82            .state
83            .transport
84            .write()
85            .expect("transport lock poisoned")
86            .take();
87        self.state
88            .metadata
89            .write()
90            .expect("metadata lock poisoned")
91            .take();
92        if let Some(transport) = transport {
93            transport.close().await?;
94        }
95        Ok(())
96    }
97
98    pub async fn login_api_key(&self, api_key: impl Into<String>) -> Result<()> {
99        let _: LoginStartResponse = self
100            .request(
101                "account/login/start",
102                Some(json!({"type": "apiKey", "apiKey": api_key.into()})),
103            )
104            .await?;
105        Ok(())
106    }
107
108    pub async fn login_chatgpt(&self) -> Result<AsyncChatgptLoginHandle> {
109        let response: LoginStartResponse = self
110            .request("account/login/start", Some(json!({"type": "chatgpt"})))
111            .await?;
112        let LoginStartResponse::Chatgpt { login_id, auth_url } = response else {
113            return Err(Error::InvalidResponse {
114                method: "account/login/start",
115                message: format!("expected chatgpt response, got {response:?}"),
116            });
117        };
118        let receiver = self.transport().await?.subscribe_login(&login_id)?;
119        Ok(AsyncChatgptLoginHandle {
120            codex: self.clone(),
121            login_id,
122            auth_url,
123            receiver: Mutex::new(Some(receiver)),
124        })
125    }
126
127    pub async fn login_chatgpt_device_code(&self) -> Result<AsyncDeviceCodeLoginHandle> {
128        let response: LoginStartResponse = self
129            .request(
130                "account/login/start",
131                Some(json!({"type": "chatgptDeviceCode"})),
132            )
133            .await?;
134        let LoginStartResponse::ChatgptDeviceCode {
135            login_id,
136            verification_url,
137            user_code,
138        } = response
139        else {
140            return Err(Error::InvalidResponse {
141                method: "account/login/start",
142                message: format!("expected chatgptDeviceCode response, got {response:?}"),
143            });
144        };
145        let receiver = self.transport().await?.subscribe_login(&login_id)?;
146        Ok(AsyncDeviceCodeLoginHandle {
147            codex: self.clone(),
148            login_id,
149            verification_url,
150            user_code,
151            receiver: Mutex::new(Some(receiver)),
152        })
153    }
154
155    pub async fn account(&self) -> Result<GetAccountResponse> {
156        self.account_with_refresh(false).await
157    }
158
159    pub async fn account_with_refresh(&self, refresh_token: bool) -> Result<GetAccountResponse> {
160        self.request("account/read", Some(json!({"refreshToken": refresh_token})))
161            .await
162    }
163
164    pub async fn logout(&self) -> Result<()> {
165        let _: EmptyObject = self.request("account/logout", None).await?;
166        Ok(())
167    }
168
169    pub async fn thread_start(&self) -> Result<AsyncThread> {
170        self.thread_start_with(&ThreadStartOptions::default()).await
171    }
172
173    pub async fn thread_start_with(&self, options: &ThreadStartOptions) -> Result<AsyncThread> {
174        let mut params = serialize_options(options)?;
175        apply_approval_mode(&mut params, Some(options.approval_mode));
176        apply_sandbox_mode(&mut params, options.sandbox);
177        let response: ThreadEnvelope = self
178            .request("thread/start", Some(Value::Object(params)))
179            .await?;
180        Ok(AsyncThread {
181            codex: self.clone(),
182            id: response.thread.id,
183        })
184    }
185
186    pub async fn thread_list(&self) -> Result<ThreadListResponse> {
187        self.thread_list_with(&ThreadListOptions::default()).await
188    }
189
190    pub async fn thread_list_with(
191        &self,
192        options: &ThreadListOptions,
193    ) -> Result<ThreadListResponse> {
194        self.request(
195            "thread/list",
196            Some(Value::Object(serialize_options(options)?)),
197        )
198        .await
199    }
200
201    pub async fn thread_resume(&self, thread_id: impl Into<String>) -> Result<AsyncThread> {
202        self.thread_resume_with(thread_id, &ThreadResumeOptions::default())
203            .await
204    }
205
206    pub async fn thread_resume_with(
207        &self,
208        thread_id: impl Into<String>,
209        options: &ThreadResumeOptions,
210    ) -> Result<AsyncThread> {
211        let mut params = serialize_options(options)?;
212        apply_approval_mode(&mut params, options.approval_mode);
213        apply_sandbox_mode(&mut params, options.sandbox);
214        params.insert("threadId".into(), Value::String(thread_id.into()));
215        let response: ThreadEnvelope = self
216            .request("thread/resume", Some(Value::Object(params)))
217            .await?;
218        Ok(AsyncThread {
219            codex: self.clone(),
220            id: response.thread.id,
221        })
222    }
223
224    pub async fn thread_fork(&self, thread_id: impl Into<String>) -> Result<AsyncThread> {
225        self.thread_fork_with(thread_id, &ThreadForkOptions::default())
226            .await
227    }
228
229    pub async fn thread_fork_with(
230        &self,
231        thread_id: impl Into<String>,
232        options: &ThreadForkOptions,
233    ) -> Result<AsyncThread> {
234        let mut params = serialize_options(options)?;
235        apply_approval_mode(&mut params, options.approval_mode);
236        apply_sandbox_mode(&mut params, options.sandbox);
237        params.insert("threadId".into(), Value::String(thread_id.into()));
238        let response: ThreadEnvelope = self
239            .request("thread/fork", Some(Value::Object(params)))
240            .await?;
241        Ok(AsyncThread {
242            codex: self.clone(),
243            id: response.thread.id,
244        })
245    }
246
247    pub async fn thread_archive(
248        &self,
249        thread_id: impl Into<String>,
250    ) -> Result<ThreadArchiveResponse> {
251        self.request(
252            "thread/archive",
253            Some(json!({"threadId": thread_id.into()})),
254        )
255        .await
256    }
257
258    pub async fn thread_unarchive(&self, thread_id: impl Into<String>) -> Result<AsyncThread> {
259        let response: ThreadEnvelope = self
260            .request(
261                "thread/unarchive",
262                Some(json!({"threadId": thread_id.into()})),
263            )
264            .await?;
265        Ok(AsyncThread {
266            codex: self.clone(),
267            id: response.thread.id,
268        })
269    }
270
271    pub async fn models(&self) -> Result<ModelListResponse> {
272        self.models_including_hidden(false).await
273    }
274
275    pub async fn models_including_hidden(&self, include_hidden: bool) -> Result<ModelListResponse> {
276        self.request("model/list", Some(json!({"includeHidden": include_hidden})))
277            .await
278    }
279
280    pub async fn next_notification(&self) -> Result<Notification> {
281        self.transport().await?.next_global_notification().await
282    }
283
284    async fn request<T: serde::de::DeserializeOwned>(
285        &self,
286        method: &'static str,
287        params: Option<Value>,
288    ) -> Result<T> {
289        self.transport().await?.request(method, params).await
290    }
291
292    async fn transport(&self) -> Result<Transport> {
293        if let Some(transport) = self
294            .state
295            .transport
296            .read()
297            .expect("transport lock poisoned")
298            .clone()
299        {
300            return Ok(transport);
301        }
302
303        let _initializing = self.state.initialize_lock.lock().await;
304        if let Some(transport) = self
305            .state
306            .transport
307            .read()
308            .expect("transport lock poisoned")
309            .clone()
310        {
311            return Ok(transport);
312        }
313
314        let transport = Transport::start(&self.config)?;
315        let initialized = async {
316            let metadata: InitializeResponse = transport
317                .request(
318                    "initialize",
319                    Some(json!({
320                        "clientInfo": {
321                            "name": self.config.client_name,
322                            "title": self.config.client_title,
323                            "version": self.config.client_version,
324                        },
325                        "capabilities": {
326                            "experimentalApi": self.config.experimental_api,
327                        },
328                    })),
329                )
330                .await?;
331            transport.notify("initialized", None).await?;
332            validate_initialize_metadata(metadata)
333        }
334        .await;
335
336        match initialized {
337            Ok(metadata) => {
338                *self.state.metadata.write().expect("metadata lock poisoned") = Some(metadata);
339                *self
340                    .state
341                    .transport
342                    .write()
343                    .expect("transport lock poisoned") = Some(transport.clone());
344                Ok(transport)
345            }
346            Err(error) => {
347                let _ = transport.close().await;
348                Err(error)
349            }
350        }
351    }
352}
353
354impl Default for AsyncCodex {
355    fn default() -> Self {
356        Self::with_defaults()
357    }
358}
359
360/// Asynchronous thread handle.
361#[derive(Clone, Debug)]
362pub struct AsyncThread {
363    codex: AsyncCodex,
364    pub id: String,
365}
366
367impl AsyncThread {
368    pub async fn run(&self, input: impl Into<Input>) -> Result<TurnResult> {
369        self.run_with(input, &TurnOptions::default()).await
370    }
371
372    pub async fn run_with(
373        &self,
374        input: impl Into<Input>,
375        options: &TurnOptions,
376    ) -> Result<TurnResult> {
377        self.turn_with(input, options).await?.run().await
378    }
379
380    pub async fn turn(&self, input: impl Into<Input>) -> Result<AsyncTurnHandle> {
381        self.turn_with(input, &TurnOptions::default()).await
382    }
383
384    pub async fn turn_with(
385        &self,
386        input: impl Into<Input>,
387        options: &TurnOptions,
388    ) -> Result<AsyncTurnHandle> {
389        let transport = self.codex.transport().await?;
390        let mut params = serialize_options(options)?;
391        apply_approval_mode(&mut params, options.approval_mode);
392        apply_sandbox_policy(&mut params, options.sandbox);
393        params.insert("threadId".into(), Value::String(self.id.clone()));
394        params.insert("input".into(), serde_json::to_value(input.into())?);
395        let response: TurnStartResponse = transport
396            .request("turn/start", Some(Value::Object(params)))
397            .await?;
398        let receiver = transport.subscribe_turn(&response.turn.id)?;
399        Ok(AsyncTurnHandle {
400            codex: self.codex.clone(),
401            thread_id: self.id.clone(),
402            id: response.turn.id,
403            receiver: Mutex::new(Some(receiver)),
404        })
405    }
406
407    pub async fn read(&self) -> Result<ThreadReadResponse> {
408        self.read_with_turns(false).await
409    }
410
411    pub async fn read_with_turns(&self, include_turns: bool) -> Result<ThreadReadResponse> {
412        self.codex
413            .request(
414                "thread/read",
415                Some(json!({"threadId": self.id, "includeTurns": include_turns})),
416            )
417            .await
418    }
419
420    pub async fn set_name(&self, name: impl Into<String>) -> Result<ThreadSetNameResponse> {
421        self.codex
422            .request(
423                "thread/name/set",
424                Some(json!({"threadId": self.id, "name": name.into()})),
425            )
426            .await
427    }
428
429    pub async fn compact(&self) -> Result<ThreadCompactStartResponse> {
430        self.codex
431            .request("thread/compact/start", Some(json!({"threadId": self.id})))
432            .await
433    }
434}
435
436/// Control handle for an active asynchronous turn.
437#[derive(Debug)]
438pub struct AsyncTurnHandle {
439    codex: AsyncCodex,
440    pub thread_id: String,
441    pub id: String,
442    receiver: Mutex<Option<NotificationReceiver>>,
443}
444
445impl AsyncTurnHandle {
446    pub async fn steer(&self, input: impl Into<Input>) -> Result<TurnSteerResponse> {
447        self.codex
448            .request(
449                "turn/steer",
450                Some(json!({
451                    "threadId": self.thread_id,
452                    "expectedTurnId": self.id,
453                    "input": input.into(),
454                })),
455            )
456            .await
457    }
458
459    pub async fn interrupt(&self) -> Result<TurnInterruptResponse> {
460        self.codex
461            .request(
462                "turn/interrupt",
463                Some(json!({"threadId": self.thread_id, "turnId": self.id})),
464            )
465            .await
466    }
467
468    pub fn stream(&self) -> Result<TurnStream> {
469        let receiver = self
470            .receiver
471            .lock()
472            .expect("turn receiver lock poisoned")
473            .take()
474            .ok_or(Error::StreamConsumed)?;
475        let transport = self
476            .codex
477            .state
478            .transport
479            .read()
480            .expect("transport lock poisoned")
481            .clone()
482            .ok_or_else(|| Error::TransportClosed("client is not running".into()))?;
483        Ok(TurnStream {
484            receiver: UnboundedReceiverStream::new(receiver),
485            transport,
486            turn_id: self.id.clone(),
487            completed: false,
488        })
489    }
490
491    pub async fn run(&self) -> Result<TurnResult> {
492        let mut stream = self.stream()?;
493        let mut events = Vec::new();
494        while let Some(event) = stream.next().await {
495            events.push(event?);
496        }
497        TurnResult::from_events(&self.id, events)
498    }
499}
500
501impl Drop for AsyncTurnHandle {
502    fn drop(&mut self) {
503        let receiver_is_pending = self
504            .receiver
505            .get_mut()
506            .expect("turn receiver lock poisoned")
507            .is_some();
508        if receiver_is_pending {
509            if let Some(transport) = self
510                .codex
511                .state
512                .transport
513                .read()
514                .expect("transport lock poisoned")
515                .as_ref()
516            {
517                transport.unsubscribe_turn(&self.id);
518            }
519        }
520    }
521}
522
523/// Stream of notifications routed to one turn.
524#[derive(Debug)]
525pub struct TurnStream {
526    receiver: UnboundedReceiverStream<Result<Notification>>,
527    transport: Transport,
528    turn_id: String,
529    completed: bool,
530}
531
532impl Stream for TurnStream {
533    type Item = Result<Notification>;
534
535    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
536        if self.completed {
537            return Poll::Ready(None);
538        }
539        match Pin::new(&mut self.receiver).poll_next(context) {
540            Poll::Ready(Some(Ok(notification))) => {
541                if matches!(
542                    &notification.payload,
543                    NotificationPayload::TurnCompleted(value) if value.turn.id == self.turn_id
544                ) {
545                    self.completed = true;
546                }
547                Poll::Ready(Some(Ok(notification)))
548            }
549            value => value,
550        }
551    }
552}
553
554impl Drop for TurnStream {
555    fn drop(&mut self) {
556        self.transport.unsubscribe_turn(&self.turn_id);
557    }
558}
559
560/// Live browser-based login attempt.
561#[derive(Debug)]
562pub struct AsyncChatgptLoginHandle {
563    codex: AsyncCodex,
564    pub login_id: String,
565    pub auth_url: String,
566    receiver: Mutex<Option<NotificationReceiver>>,
567}
568
569impl AsyncChatgptLoginHandle {
570    pub async fn wait(&self) -> Result<AccountLoginCompletedNotification> {
571        wait_for_login(&self.codex, &self.login_id, &self.receiver).await
572    }
573
574    pub async fn cancel(&self) -> Result<CancelLoginAccountResponse> {
575        let response = self
576            .codex
577            .request(
578                "account/login/cancel",
579                Some(json!({"loginId": self.login_id})),
580            )
581            .await?;
582        unsubscribe_login(&self.codex, &self.login_id);
583        Ok(response)
584    }
585}
586
587impl Drop for AsyncChatgptLoginHandle {
588    fn drop(&mut self) {
589        unsubscribe_login_if_pending(&self.codex, &self.login_id, &mut self.receiver);
590    }
591}
592
593/// Live device-code login attempt.
594#[derive(Debug)]
595pub struct AsyncDeviceCodeLoginHandle {
596    codex: AsyncCodex,
597    pub login_id: String,
598    pub verification_url: String,
599    pub user_code: String,
600    receiver: Mutex<Option<NotificationReceiver>>,
601}
602
603impl AsyncDeviceCodeLoginHandle {
604    pub async fn wait(&self) -> Result<AccountLoginCompletedNotification> {
605        wait_for_login(&self.codex, &self.login_id, &self.receiver).await
606    }
607
608    pub async fn cancel(&self) -> Result<CancelLoginAccountResponse> {
609        let response = self
610            .codex
611            .request(
612                "account/login/cancel",
613                Some(json!({"loginId": self.login_id})),
614            )
615            .await?;
616        unsubscribe_login(&self.codex, &self.login_id);
617        Ok(response)
618    }
619}
620
621impl Drop for AsyncDeviceCodeLoginHandle {
622    fn drop(&mut self) {
623        unsubscribe_login_if_pending(&self.codex, &self.login_id, &mut self.receiver);
624    }
625}
626
627async fn wait_for_login(
628    codex: &AsyncCodex,
629    login_id: &str,
630    receiver: &Mutex<Option<NotificationReceiver>>,
631) -> Result<AccountLoginCompletedNotification> {
632    let _subscription = LoginSubscription::new(codex, login_id);
633    let mut receiver = receiver
634        .lock()
635        .expect("login receiver lock poisoned")
636        .take()
637        .ok_or(Error::StreamConsumed)?;
638    while let Some(event) = receiver.recv().await {
639        let event = event?;
640        if let NotificationPayload::AccountLoginCompleted(completed) = event.payload {
641            if completed.login_id.as_deref() == Some(login_id) {
642                return Ok(completed);
643            }
644        }
645    }
646    Err(Error::TransportClosed(
647        "login notification stream stopped".into(),
648    ))
649}
650
651struct LoginSubscription {
652    transport: Option<Transport>,
653    login_id: String,
654}
655
656impl LoginSubscription {
657    fn new(codex: &AsyncCodex, login_id: &str) -> Self {
658        Self {
659            transport: codex
660                .state
661                .transport
662                .read()
663                .expect("transport lock poisoned")
664                .clone(),
665            login_id: login_id.to_owned(),
666        }
667    }
668}
669
670impl Drop for LoginSubscription {
671    fn drop(&mut self) {
672        if let Some(transport) = &self.transport {
673            transport.unsubscribe_login(&self.login_id);
674        }
675    }
676}
677
678fn unsubscribe_login(codex: &AsyncCodex, login_id: &str) {
679    if let Some(transport) = codex
680        .state
681        .transport
682        .read()
683        .expect("transport lock poisoned")
684        .as_ref()
685    {
686        transport.unsubscribe_login(login_id);
687    }
688}
689
690fn unsubscribe_login_if_pending(
691    codex: &AsyncCodex,
692    login_id: &str,
693    receiver: &mut Mutex<Option<NotificationReceiver>>,
694) {
695    let receiver_is_pending = receiver
696        .get_mut()
697        .expect("login receiver lock poisoned")
698        .is_some();
699    if receiver_is_pending {
700        unsubscribe_login(codex, login_id);
701    }
702}
703
704/// Retry an asynchronous operation when the runtime reports overload.
705pub async fn retry_on_overload<T, F, Fut>(policy: RetryPolicy, mut operation: F) -> Result<T>
706where
707    F: FnMut() -> Fut,
708    Fut: Future<Output = Result<T>>,
709{
710    if policy.max_attempts == 0 {
711        return Err(Error::InvalidConfiguration(
712            "max_attempts must be at least 1".into(),
713        ));
714    }
715
716    let mut delay = policy.initial_delay;
717    for attempt in 1..=policy.max_attempts {
718        match operation().await {
719            Ok(value) => return Ok(value),
720            Err(error) if attempt < policy.max_attempts && is_retryable_error(&error) => {
721                let capped = delay.min(policy.max_delay);
722                let jitter = capped.as_secs_f64()
723                    * policy.jitter_ratio
724                    * (rand::random::<f64>() * 2.0 - 1.0);
725                let sleep = (capped.as_secs_f64() + jitter).max(0.0);
726                if sleep > 0.0 {
727                    tokio::time::sleep(Duration::from_secs_f64(sleep)).await;
728                }
729                delay = (delay * 2).min(policy.max_delay);
730            }
731            Err(error) => return Err(error),
732        }
733    }
734    unreachable!("nonzero retry policy always returns from the loop")
735}
736
737fn validate_initialize_metadata(mut response: InitializeResponse) -> Result<InitializeResponse> {
738    let user_agent = response.user_agent.as_deref().unwrap_or("").trim();
739    let mut server_name = response
740        .server_info
741        .as_ref()
742        .and_then(|server| server.name.as_deref())
743        .map(str::trim)
744        .filter(|value| !value.is_empty());
745    let mut server_version = response
746        .server_info
747        .as_ref()
748        .and_then(|server| server.version.as_deref())
749        .map(str::trim)
750        .filter(|value| !value.is_empty());
751
752    let parsed = split_user_agent(user_agent);
753    server_name = server_name.or(parsed.0.as_deref());
754    server_version = server_version.or(parsed.1.as_deref());
755    if user_agent.is_empty() || server_name.is_none() || server_version.is_none() {
756        return Err(Error::InvalidResponse {
757            method: "initialize",
758            message: format!(
759                "missing required metadata (user_agent={user_agent:?}, server_name={server_name:?}, server_version={server_version:?})"
760            ),
761        });
762    }
763    response.server_info = Some(ServerInfo {
764        name: server_name.map(str::to_owned),
765        version: server_version.map(str::to_owned),
766    });
767    Ok(response)
768}
769
770fn split_user_agent(user_agent: &str) -> (Option<String>, Option<String>) {
771    let user_agent = user_agent.trim();
772    if user_agent.is_empty() {
773        return (None, None);
774    }
775    if let Some((name, version)) = user_agent.split_once('/') {
776        return (
777            (!name.is_empty()).then(|| name.to_owned()),
778            (!version.is_empty()).then(|| version.to_owned()),
779        );
780    }
781    if let Some((name, version)) = user_agent.split_once(char::is_whitespace) {
782        return (Some(name.into()), Some(version.trim().into()));
783    }
784    (Some(user_agent.into()), None)
785}
786
787#[derive(Debug, Deserialize)]
788#[serde(tag = "type")]
789enum LoginStartResponse {
790    #[serde(rename = "apiKey")]
791    ApiKey,
792    #[serde(rename = "chatgpt")]
793    Chatgpt {
794        #[serde(rename = "loginId")]
795        login_id: String,
796        #[serde(rename = "authUrl")]
797        auth_url: String,
798    },
799    #[serde(rename = "chatgptDeviceCode")]
800    ChatgptDeviceCode {
801        #[serde(rename = "loginId")]
802        login_id: String,
803        #[serde(rename = "verificationUrl")]
804        verification_url: String,
805        #[serde(rename = "userCode")]
806        user_code: String,
807    },
808    #[serde(rename = "chatgptAuthTokens")]
809    ChatgptAuthTokens,
810}
811
812#[derive(Debug, Deserialize)]
813struct ThreadEnvelope {
814    thread: ThreadData,
815}
816
817#[derive(Debug, Deserialize)]
818struct TurnStartResponse {
819    turn: Turn,
820}
821
822#[derive(Debug, Deserialize)]
823struct EmptyObject {
824    #[serde(flatten)]
825    _extra: Map<String, Value>,
826}
827
828#[cfg(test)]
829mod tests {
830    use super::*;
831
832    #[test]
833    fn splits_supported_user_agent_shapes() {
834        assert_eq!(
835            split_user_agent("codex-cli/1.2.3"),
836            (Some("codex-cli".into()), Some("1.2.3".into()))
837        );
838        assert_eq!(
839            split_user_agent("codex-cli 1.2.3"),
840            (Some("codex-cli".into()), Some("1.2.3".into()))
841        );
842        assert_eq!(split_user_agent("codex"), (Some("codex".into()), None));
843        assert_eq!(split_user_agent(""), (None, None));
844    }
845
846    #[test]
847    fn validates_and_backfills_initialize_metadata() {
848        let response = validate_initialize_metadata(InitializeResponse {
849            user_agent: Some("codex-cli/1.2.3".into()),
850            ..InitializeResponse::default()
851        })
852        .unwrap();
853        assert_eq!(
854            response.server_info.unwrap().name.as_deref(),
855            Some("codex-cli")
856        );
857
858        assert!(validate_initialize_metadata(InitializeResponse::default()).is_err());
859    }
860
861    #[test]
862    fn default_async_client_is_lazy() {
863        let explicit = AsyncCodex::with_defaults();
864        let defaulted = AsyncCodex::default();
865        assert!(matches!(
866            explicit.metadata(),
867            Err(Error::InvalidConfiguration(_))
868        ));
869        assert!(matches!(
870            defaulted.metadata(),
871            Err(Error::InvalidConfiguration(_))
872        ));
873    }
874
875    #[tokio::test]
876    async fn login_wait_reports_a_closed_notification_channel() {
877        let client = AsyncCodex::default();
878        let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
879        drop(sender);
880        assert!(matches!(
881            wait_for_login(&client, "login-1", &Mutex::new(Some(receiver))).await,
882            Err(Error::TransportClosed(message))
883                if message == "login notification stream stopped"
884        ));
885    }
886
887    #[tokio::test(start_paused = true)]
888    async fn retry_retries_overload_and_rejects_invalid_policy() {
889        let mut attempts = 0;
890        let value = retry_on_overload(
891            RetryPolicy {
892                max_attempts: 3,
893                initial_delay: Duration::ZERO,
894                max_delay: Duration::ZERO,
895                jitter_ratio: 0.0,
896            },
897            || {
898                attempts += 1;
899                async move {
900                    if attempts < 3 {
901                        Err(Error::JsonRpc(crate::JsonRpcError::new(
902                            -32001,
903                            "busy".into(),
904                            Some(json!("server_overloaded")),
905                        )))
906                    } else {
907                        Ok(42)
908                    }
909                }
910            },
911        )
912        .await
913        .unwrap();
914        assert_eq!(value, 42);
915        assert_eq!(attempts, 3);
916
917        assert!(
918            retry_on_overload(
919                RetryPolicy {
920                    max_attempts: 0,
921                    ..RetryPolicy::default()
922                },
923                || async { Ok::<_, Error>(()) },
924            )
925            .await
926            .is_err()
927        );
928
929        let exhausted = retry_on_overload(
930            RetryPolicy {
931                max_attempts: 2,
932                initial_delay: Duration::from_millis(1),
933                max_delay: Duration::from_millis(2),
934                jitter_ratio: 0.0,
935            },
936            || async {
937                Err::<(), _>(Error::JsonRpc(crate::JsonRpcError::new(
938                    -32001,
939                    "busy".into(),
940                    Some(json!("server_overloaded")),
941                )))
942            },
943        )
944        .await;
945        assert!(matches!(exhausted, Err(Error::JsonRpc(_))));
946
947        let non_retryable = retry_on_overload(RetryPolicy::default(), || async {
948            Err::<(), _>(Error::InvalidConfiguration("stop".into()))
949        })
950        .await;
951        assert!(matches!(
952            non_retryable,
953            Err(Error::InvalidConfiguration(message)) if message == "stop"
954        ));
955    }
956}