codex-sdk-rs 0.1.0

Rust SDK for the OpenAI Codex app server
Documentation
use std::sync::Arc;

use tokio::runtime::{Builder, Runtime};
use tokio_stream::StreamExt;

use crate::async_client::{
    AsyncChatgptLoginHandle, AsyncCodex, AsyncDeviceCodeLoginHandle, AsyncThread, AsyncTurnHandle,
    TurnStream,
};
use crate::config::CodexConfig;
use crate::error::{Error, Result};
use crate::options::{
    ThreadForkOptions, ThreadListOptions, ThreadResumeOptions, ThreadStartOptions, TurnOptions,
};
use crate::types::{
    AccountLoginCompletedNotification, CancelLoginAccountResponse, GetAccountResponse,
    InitializeResponse, Input, ModelListResponse, Notification, ThreadArchiveResponse,
    ThreadCompactStartResponse, ThreadListResponse, ThreadReadResponse, ThreadSetNameResponse,
    TurnInterruptResponse, TurnResult, TurnSteerResponse,
};

#[derive(Debug)]
struct BlockingCore {
    runtime: Runtime,
    client: AsyncCodex,
}

impl BlockingCore {
    fn block_on<F: FutureResult>(&self, future: F) -> F::Output {
        self.runtime.block_on(future)
    }
}

trait FutureResult: std::future::Future {}
impl<T: std::future::Future> FutureResult for T {}

/// Synchronous Codex client mirroring Python's `Codex`.
#[derive(Debug)]
pub struct Codex {
    core: Arc<BlockingCore>,
}

impl Codex {
    pub fn new(config: CodexConfig) -> Result<Self> {
        let runtime = Builder::new_multi_thread()
            .enable_all()
            .thread_name("codex-rust-sdk")
            .build()
            .map_err(|error| Error::BlockingRuntime(error.to_string()))?;
        let client = AsyncCodex::new(config);
        runtime.block_on(client.start())?;
        Ok(Self {
            core: Arc::new(BlockingCore { runtime, client }),
        })
    }

    pub fn with_defaults() -> Result<Self> {
        Self::new(CodexConfig::default())
    }

    pub fn metadata(&self) -> Result<InitializeResponse> {
        self.core.client.metadata()
    }

    pub fn close(&self) -> Result<()> {
        self.core.block_on(self.core.client.close())
    }

    pub fn login_api_key(&self, api_key: impl Into<String>) -> Result<()> {
        self.core
            .block_on(self.core.client.login_api_key(api_key.into()))
    }

    pub fn login_chatgpt(&self) -> Result<ChatgptLoginHandle> {
        let handle = self.core.block_on(self.core.client.login_chatgpt())?;
        Ok(ChatgptLoginHandle {
            core: Arc::clone(&self.core),
            login_id: handle.login_id.clone(),
            auth_url: handle.auth_url.clone(),
            handle,
        })
    }

    pub fn login_chatgpt_device_code(&self) -> Result<DeviceCodeLoginHandle> {
        let handle = self
            .core
            .block_on(self.core.client.login_chatgpt_device_code())?;
        Ok(DeviceCodeLoginHandle {
            core: Arc::clone(&self.core),
            login_id: handle.login_id.clone(),
            verification_url: handle.verification_url.clone(),
            user_code: handle.user_code.clone(),
            handle,
        })
    }

    pub fn account(&self) -> Result<GetAccountResponse> {
        self.core.block_on(self.core.client.account())
    }

    pub fn account_with_refresh(&self, refresh_token: bool) -> Result<GetAccountResponse> {
        self.core
            .block_on(self.core.client.account_with_refresh(refresh_token))
    }

    pub fn logout(&self) -> Result<()> {
        self.core.block_on(self.core.client.logout())
    }

    pub fn thread_start(&self) -> Result<Thread> {
        let thread = self.core.block_on(self.core.client.thread_start())?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_start_with(&self, options: &ThreadStartOptions) -> Result<Thread> {
        let thread = self
            .core
            .block_on(self.core.client.thread_start_with(options))?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_list(&self) -> Result<ThreadListResponse> {
        self.core.block_on(self.core.client.thread_list())
    }

    pub fn thread_list_with(&self, options: &ThreadListOptions) -> Result<ThreadListResponse> {
        self.core
            .block_on(self.core.client.thread_list_with(options))
    }

    pub fn thread_resume(&self, thread_id: impl Into<String>) -> Result<Thread> {
        let thread = self
            .core
            .block_on(self.core.client.thread_resume(thread_id.into()))?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_resume_with(
        &self,
        thread_id: impl Into<String>,
        options: &ThreadResumeOptions,
    ) -> Result<Thread> {
        let thread = self.core.block_on(
            self.core
                .client
                .thread_resume_with(thread_id.into(), options),
        )?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_fork(&self, thread_id: impl Into<String>) -> Result<Thread> {
        let thread = self
            .core
            .block_on(self.core.client.thread_fork(thread_id.into()))?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_fork_with(
        &self,
        thread_id: impl Into<String>,
        options: &ThreadForkOptions,
    ) -> Result<Thread> {
        let thread = self
            .core
            .block_on(self.core.client.thread_fork_with(thread_id.into(), options))?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn thread_archive(&self, thread_id: impl Into<String>) -> Result<ThreadArchiveResponse> {
        self.core
            .block_on(self.core.client.thread_archive(thread_id.into()))
    }

    pub fn thread_unarchive(&self, thread_id: impl Into<String>) -> Result<Thread> {
        let thread = self
            .core
            .block_on(self.core.client.thread_unarchive(thread_id.into()))?;
        Ok(Thread {
            core: Arc::clone(&self.core),
            id: thread.id.clone(),
            inner: thread,
        })
    }

    pub fn models(&self) -> Result<ModelListResponse> {
        self.core.block_on(self.core.client.models())
    }

    pub fn models_including_hidden(&self, include_hidden: bool) -> Result<ModelListResponse> {
        self.core
            .block_on(self.core.client.models_including_hidden(include_hidden))
    }

    pub fn next_notification(&self) -> Result<Notification> {
        self.core.block_on(self.core.client.next_notification())
    }
}

impl Drop for Codex {
    fn drop(&mut self) {
        let _ = self.core.block_on(self.core.client.close());
    }
}

/// Synchronous thread handle.
#[derive(Clone, Debug)]
pub struct Thread {
    core: Arc<BlockingCore>,
    inner: AsyncThread,
    pub id: String,
}

impl Thread {
    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn run(&self, input: impl Into<Input>) -> Result<TurnResult> {
        self.core.block_on(self.inner.run(input))
    }

    pub fn run_with(&self, input: impl Into<Input>, options: &TurnOptions) -> Result<TurnResult> {
        self.core.block_on(self.inner.run_with(input, options))
    }

    pub fn turn(&self, input: impl Into<Input>) -> Result<TurnHandle> {
        let handle = self.core.block_on(self.inner.turn(input))?;
        Ok(TurnHandle {
            core: Arc::clone(&self.core),
            thread_id: handle.thread_id.clone(),
            id: handle.id.clone(),
            handle,
        })
    }

    pub fn turn_with(&self, input: impl Into<Input>, options: &TurnOptions) -> Result<TurnHandle> {
        let handle = self.core.block_on(self.inner.turn_with(input, options))?;
        Ok(TurnHandle {
            core: Arc::clone(&self.core),
            thread_id: handle.thread_id.clone(),
            id: handle.id.clone(),
            handle,
        })
    }

    pub fn read(&self) -> Result<ThreadReadResponse> {
        self.core.block_on(self.inner.read())
    }

    pub fn read_with_turns(&self, include_turns: bool) -> Result<ThreadReadResponse> {
        self.core
            .block_on(self.inner.read_with_turns(include_turns))
    }

    pub fn set_name(&self, name: impl Into<String>) -> Result<ThreadSetNameResponse> {
        self.core.block_on(self.inner.set_name(name))
    }

    pub fn compact(&self) -> Result<ThreadCompactStartResponse> {
        self.core.block_on(self.inner.compact())
    }
}

/// Synchronous turn control handle.
#[derive(Debug)]
pub struct TurnHandle {
    core: Arc<BlockingCore>,
    handle: AsyncTurnHandle,
    pub thread_id: String,
    pub id: String,
}

impl TurnHandle {
    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn thread_id(&self) -> &str {
        &self.thread_id
    }

    pub fn steer(&self, input: impl Into<Input>) -> Result<TurnSteerResponse> {
        self.core.block_on(self.handle.steer(input))
    }

    pub fn interrupt(&self) -> Result<TurnInterruptResponse> {
        self.core.block_on(self.handle.interrupt())
    }

    pub fn stream(&self) -> Result<TurnIter> {
        Ok(TurnIter {
            core: Arc::clone(&self.core),
            stream: self.handle.stream()?,
        })
    }

    pub fn run(&self) -> Result<TurnResult> {
        self.core.block_on(self.handle.run())
    }
}

/// Blocking iterator over one turn's notifications.
#[derive(Debug)]
pub struct TurnIter {
    core: Arc<BlockingCore>,
    stream: TurnStream,
}

impl Iterator for TurnIter {
    type Item = Result<Notification>;

    fn next(&mut self) -> Option<Self::Item> {
        self.core.block_on(self.stream.next())
    }
}

/// Synchronous browser-login handle.
#[derive(Debug)]
pub struct ChatgptLoginHandle {
    core: Arc<BlockingCore>,
    handle: AsyncChatgptLoginHandle,
    pub login_id: String,
    pub auth_url: String,
}

impl ChatgptLoginHandle {
    pub fn login_id(&self) -> &str {
        &self.login_id
    }

    pub fn auth_url(&self) -> &str {
        &self.auth_url
    }

    pub fn wait(&self) -> Result<AccountLoginCompletedNotification> {
        self.core.block_on(self.handle.wait())
    }

    pub fn cancel(&self) -> Result<CancelLoginAccountResponse> {
        self.core.block_on(self.handle.cancel())
    }
}

/// Synchronous device-code login handle.
#[derive(Debug)]
pub struct DeviceCodeLoginHandle {
    core: Arc<BlockingCore>,
    handle: AsyncDeviceCodeLoginHandle,
    pub login_id: String,
    pub verification_url: String,
    pub user_code: String,
}

impl DeviceCodeLoginHandle {
    pub fn login_id(&self) -> &str {
        &self.login_id
    }

    pub fn verification_url(&self) -> &str {
        &self.verification_url
    }

    pub fn user_code(&self) -> &str {
        &self.user_code
    }

    pub fn wait(&self) -> Result<AccountLoginCompletedNotification> {
        self.core.block_on(self.handle.wait())
    }

    pub fn cancel(&self) -> Result<CancelLoginAccountResponse> {
        self.core.block_on(self.handle.cancel())
    }
}