Skip to main content

codex_sdk_rs/
blocking.rs

1use std::sync::Arc;
2
3use tokio::runtime::{Builder, Runtime};
4use tokio_stream::StreamExt;
5
6use crate::async_client::{
7    AsyncChatgptLoginHandle, AsyncCodex, AsyncDeviceCodeLoginHandle, AsyncThread, AsyncTurnHandle,
8    TurnStream,
9};
10use crate::config::CodexConfig;
11use crate::error::{Error, Result};
12use crate::options::{
13    ThreadForkOptions, ThreadListOptions, ThreadResumeOptions, ThreadStartOptions, TurnOptions,
14};
15use crate::types::{
16    AccountLoginCompletedNotification, CancelLoginAccountResponse, GetAccountResponse,
17    InitializeResponse, Input, ModelListResponse, Notification, ThreadArchiveResponse,
18    ThreadCompactStartResponse, ThreadListResponse, ThreadReadResponse, ThreadSetNameResponse,
19    TurnInterruptResponse, TurnResult, TurnSteerResponse,
20};
21
22#[derive(Debug)]
23struct BlockingCore {
24    runtime: Runtime,
25    client: AsyncCodex,
26}
27
28impl BlockingCore {
29    fn block_on<F: FutureResult>(&self, future: F) -> F::Output {
30        self.runtime.block_on(future)
31    }
32}
33
34trait FutureResult: std::future::Future {}
35impl<T: std::future::Future> FutureResult for T {}
36
37/// Synchronous Codex client mirroring Python's `Codex`.
38#[derive(Debug)]
39pub struct Codex {
40    core: Arc<BlockingCore>,
41}
42
43impl Codex {
44    pub fn new(config: CodexConfig) -> Result<Self> {
45        let runtime = Builder::new_multi_thread()
46            .enable_all()
47            .thread_name("codex-rust-sdk")
48            .build()
49            .map_err(|error| Error::BlockingRuntime(error.to_string()))?;
50        let client = AsyncCodex::new(config);
51        runtime.block_on(client.start())?;
52        Ok(Self {
53            core: Arc::new(BlockingCore { runtime, client }),
54        })
55    }
56
57    pub fn with_defaults() -> Result<Self> {
58        Self::new(CodexConfig::default())
59    }
60
61    pub fn metadata(&self) -> Result<InitializeResponse> {
62        self.core.client.metadata()
63    }
64
65    pub fn close(&self) -> Result<()> {
66        self.core.block_on(self.core.client.close())
67    }
68
69    pub fn login_api_key(&self, api_key: impl Into<String>) -> Result<()> {
70        self.core
71            .block_on(self.core.client.login_api_key(api_key.into()))
72    }
73
74    pub fn login_chatgpt(&self) -> Result<ChatgptLoginHandle> {
75        let handle = self.core.block_on(self.core.client.login_chatgpt())?;
76        Ok(ChatgptLoginHandle {
77            core: Arc::clone(&self.core),
78            login_id: handle.login_id.clone(),
79            auth_url: handle.auth_url.clone(),
80            handle,
81        })
82    }
83
84    pub fn login_chatgpt_device_code(&self) -> Result<DeviceCodeLoginHandle> {
85        let handle = self
86            .core
87            .block_on(self.core.client.login_chatgpt_device_code())?;
88        Ok(DeviceCodeLoginHandle {
89            core: Arc::clone(&self.core),
90            login_id: handle.login_id.clone(),
91            verification_url: handle.verification_url.clone(),
92            user_code: handle.user_code.clone(),
93            handle,
94        })
95    }
96
97    pub fn account(&self) -> Result<GetAccountResponse> {
98        self.core.block_on(self.core.client.account())
99    }
100
101    pub fn account_with_refresh(&self, refresh_token: bool) -> Result<GetAccountResponse> {
102        self.core
103            .block_on(self.core.client.account_with_refresh(refresh_token))
104    }
105
106    pub fn logout(&self) -> Result<()> {
107        self.core.block_on(self.core.client.logout())
108    }
109
110    pub fn thread_start(&self) -> Result<Thread> {
111        let thread = self.core.block_on(self.core.client.thread_start())?;
112        Ok(Thread {
113            core: Arc::clone(&self.core),
114            id: thread.id.clone(),
115            inner: thread,
116        })
117    }
118
119    pub fn thread_start_with(&self, options: &ThreadStartOptions) -> Result<Thread> {
120        let thread = self
121            .core
122            .block_on(self.core.client.thread_start_with(options))?;
123        Ok(Thread {
124            core: Arc::clone(&self.core),
125            id: thread.id.clone(),
126            inner: thread,
127        })
128    }
129
130    pub fn thread_list(&self) -> Result<ThreadListResponse> {
131        self.core.block_on(self.core.client.thread_list())
132    }
133
134    pub fn thread_list_with(&self, options: &ThreadListOptions) -> Result<ThreadListResponse> {
135        self.core
136            .block_on(self.core.client.thread_list_with(options))
137    }
138
139    pub fn thread_resume(&self, thread_id: impl Into<String>) -> Result<Thread> {
140        let thread = self
141            .core
142            .block_on(self.core.client.thread_resume(thread_id.into()))?;
143        Ok(Thread {
144            core: Arc::clone(&self.core),
145            id: thread.id.clone(),
146            inner: thread,
147        })
148    }
149
150    pub fn thread_resume_with(
151        &self,
152        thread_id: impl Into<String>,
153        options: &ThreadResumeOptions,
154    ) -> Result<Thread> {
155        let thread = self.core.block_on(
156            self.core
157                .client
158                .thread_resume_with(thread_id.into(), options),
159        )?;
160        Ok(Thread {
161            core: Arc::clone(&self.core),
162            id: thread.id.clone(),
163            inner: thread,
164        })
165    }
166
167    pub fn thread_fork(&self, thread_id: impl Into<String>) -> Result<Thread> {
168        let thread = self
169            .core
170            .block_on(self.core.client.thread_fork(thread_id.into()))?;
171        Ok(Thread {
172            core: Arc::clone(&self.core),
173            id: thread.id.clone(),
174            inner: thread,
175        })
176    }
177
178    pub fn thread_fork_with(
179        &self,
180        thread_id: impl Into<String>,
181        options: &ThreadForkOptions,
182    ) -> Result<Thread> {
183        let thread = self
184            .core
185            .block_on(self.core.client.thread_fork_with(thread_id.into(), options))?;
186        Ok(Thread {
187            core: Arc::clone(&self.core),
188            id: thread.id.clone(),
189            inner: thread,
190        })
191    }
192
193    pub fn thread_archive(&self, thread_id: impl Into<String>) -> Result<ThreadArchiveResponse> {
194        self.core
195            .block_on(self.core.client.thread_archive(thread_id.into()))
196    }
197
198    pub fn thread_unarchive(&self, thread_id: impl Into<String>) -> Result<Thread> {
199        let thread = self
200            .core
201            .block_on(self.core.client.thread_unarchive(thread_id.into()))?;
202        Ok(Thread {
203            core: Arc::clone(&self.core),
204            id: thread.id.clone(),
205            inner: thread,
206        })
207    }
208
209    pub fn models(&self) -> Result<ModelListResponse> {
210        self.core.block_on(self.core.client.models())
211    }
212
213    pub fn models_including_hidden(&self, include_hidden: bool) -> Result<ModelListResponse> {
214        self.core
215            .block_on(self.core.client.models_including_hidden(include_hidden))
216    }
217
218    pub fn next_notification(&self) -> Result<Notification> {
219        self.core.block_on(self.core.client.next_notification())
220    }
221}
222
223impl Drop for Codex {
224    fn drop(&mut self) {
225        let _ = self.core.block_on(self.core.client.close());
226    }
227}
228
229/// Synchronous thread handle.
230#[derive(Clone, Debug)]
231pub struct Thread {
232    core: Arc<BlockingCore>,
233    inner: AsyncThread,
234    pub id: String,
235}
236
237impl Thread {
238    pub fn id(&self) -> &str {
239        &self.id
240    }
241
242    pub fn run(&self, input: impl Into<Input>) -> Result<TurnResult> {
243        self.core.block_on(self.inner.run(input))
244    }
245
246    pub fn run_with(&self, input: impl Into<Input>, options: &TurnOptions) -> Result<TurnResult> {
247        self.core.block_on(self.inner.run_with(input, options))
248    }
249
250    pub fn turn(&self, input: impl Into<Input>) -> Result<TurnHandle> {
251        let handle = self.core.block_on(self.inner.turn(input))?;
252        Ok(TurnHandle {
253            core: Arc::clone(&self.core),
254            thread_id: handle.thread_id.clone(),
255            id: handle.id.clone(),
256            handle,
257        })
258    }
259
260    pub fn turn_with(&self, input: impl Into<Input>, options: &TurnOptions) -> Result<TurnHandle> {
261        let handle = self.core.block_on(self.inner.turn_with(input, options))?;
262        Ok(TurnHandle {
263            core: Arc::clone(&self.core),
264            thread_id: handle.thread_id.clone(),
265            id: handle.id.clone(),
266            handle,
267        })
268    }
269
270    pub fn read(&self) -> Result<ThreadReadResponse> {
271        self.core.block_on(self.inner.read())
272    }
273
274    pub fn read_with_turns(&self, include_turns: bool) -> Result<ThreadReadResponse> {
275        self.core
276            .block_on(self.inner.read_with_turns(include_turns))
277    }
278
279    pub fn set_name(&self, name: impl Into<String>) -> Result<ThreadSetNameResponse> {
280        self.core.block_on(self.inner.set_name(name))
281    }
282
283    pub fn compact(&self) -> Result<ThreadCompactStartResponse> {
284        self.core.block_on(self.inner.compact())
285    }
286}
287
288/// Synchronous turn control handle.
289#[derive(Debug)]
290pub struct TurnHandle {
291    core: Arc<BlockingCore>,
292    handle: AsyncTurnHandle,
293    pub thread_id: String,
294    pub id: String,
295}
296
297impl TurnHandle {
298    pub fn id(&self) -> &str {
299        &self.id
300    }
301
302    pub fn thread_id(&self) -> &str {
303        &self.thread_id
304    }
305
306    pub fn steer(&self, input: impl Into<Input>) -> Result<TurnSteerResponse> {
307        self.core.block_on(self.handle.steer(input))
308    }
309
310    pub fn interrupt(&self) -> Result<TurnInterruptResponse> {
311        self.core.block_on(self.handle.interrupt())
312    }
313
314    pub fn stream(&self) -> Result<TurnIter> {
315        Ok(TurnIter {
316            core: Arc::clone(&self.core),
317            stream: self.handle.stream()?,
318        })
319    }
320
321    pub fn run(&self) -> Result<TurnResult> {
322        self.core.block_on(self.handle.run())
323    }
324}
325
326/// Blocking iterator over one turn's notifications.
327#[derive(Debug)]
328pub struct TurnIter {
329    core: Arc<BlockingCore>,
330    stream: TurnStream,
331}
332
333impl Iterator for TurnIter {
334    type Item = Result<Notification>;
335
336    fn next(&mut self) -> Option<Self::Item> {
337        self.core.block_on(self.stream.next())
338    }
339}
340
341/// Synchronous browser-login handle.
342#[derive(Debug)]
343pub struct ChatgptLoginHandle {
344    core: Arc<BlockingCore>,
345    handle: AsyncChatgptLoginHandle,
346    pub login_id: String,
347    pub auth_url: String,
348}
349
350impl ChatgptLoginHandle {
351    pub fn login_id(&self) -> &str {
352        &self.login_id
353    }
354
355    pub fn auth_url(&self) -> &str {
356        &self.auth_url
357    }
358
359    pub fn wait(&self) -> Result<AccountLoginCompletedNotification> {
360        self.core.block_on(self.handle.wait())
361    }
362
363    pub fn cancel(&self) -> Result<CancelLoginAccountResponse> {
364        self.core.block_on(self.handle.cancel())
365    }
366}
367
368/// Synchronous device-code login handle.
369#[derive(Debug)]
370pub struct DeviceCodeLoginHandle {
371    core: Arc<BlockingCore>,
372    handle: AsyncDeviceCodeLoginHandle,
373    pub login_id: String,
374    pub verification_url: String,
375    pub user_code: String,
376}
377
378impl DeviceCodeLoginHandle {
379    pub fn login_id(&self) -> &str {
380        &self.login_id
381    }
382
383    pub fn verification_url(&self) -> &str {
384        &self.verification_url
385    }
386
387    pub fn user_code(&self) -> &str {
388        &self.user_code
389    }
390
391    pub fn wait(&self) -> Result<AccountLoginCompletedNotification> {
392        self.core.block_on(self.handle.wait())
393    }
394
395    pub fn cancel(&self) -> Result<CancelLoginAccountResponse> {
396        self.core.block_on(self.handle.cancel())
397    }
398}