Skip to main content

artifactize_core/llm/
codex.rs

1//! The `codex` backend: the Codex Responses endpoint with ChatGPT/Codex sign-in
2//! credentials, the way Pi's `openai-codex` provider calls it
3//! (pi-mono `packages/ai/src/api/openai-codex-responses.ts`).
4//!
5//! rig's ChatGPT dialect speaks the Codex request contract: an always-streamed
6//! Responses turn with `store:false`, encrypted reasoning replay, function tools, all
7//! system messages as top-level `instructions`, and an event stream that may name no
8//! content type. artifactize adds the headers Pi sends (`OpenAI-Beta`, an event-stream
9//! `accept`, its own `originator` and user agent, the ChatGPT account), and drops
10//! rig's default instructions so the review's own system prompt is the only one.
11//!
12//! Every request of one review carries the review's session id, as `prompt_cache_key`
13//! and as the `session-id` header the backend keys its prompt cache on. rig 0.43 sends a
14//! fresh `session_id` per request instead (0xPlaygrounds/rig#2719), which artifactize
15//! turns off.
16
17use std::path::{Path, PathBuf};
18
19use reqwest::StatusCode;
20use rig_core::{
21    Model,
22    completion::CompletionRequest,
23    http_client::Builder,
24    providers::{
25        chatgpt,
26        openai::{
27            self,
28            wire::{CallerIdentity, DialectHooks},
29        },
30    },
31};
32mod output;
33pub(crate) use output::Responses;
34
35use super::error_body::Body;
36use crate::auth::codex::{self as auth, ORIGINATOR};
37
38/// The Codex API root; requests go to `<root>/responses` and `<root>/models`.
39pub const BASE_URL: &str = "https://chatgpt.com/backend-api/codex";
40
41/// The Codex backend filters its model catalog by client version. artifactize asks
42/// for the catalog of the Codex release whose Responses protocol it follows.
43pub const CLIENT_VERSION: &str = "0.169.0";
44
45static HOOKS: DialectHooks = DialectHooks {
46    default_endpoint: None,
47    model_route: None,
48    completion_envelope: Some(envelope),
49    modality_envelope: None,
50};
51
52fn envelope(_: &openai::OpenAIConfig, request: &CompletionRequest, builder: Builder) -> Builder {
53    let builder = builder
54        .header("OpenAI-Beta", "responses=experimental")
55        .header("accept", "text/event-stream");
56    // TODO: once rig ships `OpenAIConfig::with_session_id` (0xPlaygrounds/rig#2722), pin
57    // the session there and drop this header and the `session_ids` override in `model`.
58    match session(request) {
59        Some(session) => builder.header("session-id", session),
60        None => builder,
61    }
62}
63
64/// The review's session id: the request's `prompt_cache_key` ([`super::Client::parameters`]).
65fn session(request: &CompletionRequest) -> Option<&str> {
66    request
67        .additional_params
68        .as_ref()?
69        .get("prompt_cache_key")?
70        .as_str()
71}
72
73/// `artifactize/<version> (<os> <arch>; artifactize)`, the shape rig gives gateways.
74pub fn user_agent() -> String {
75    format!(
76        "artifactize/{} ({}; {ORIGINATOR})",
77        env!("CARGO_PKG_VERSION"),
78        crate::platform::label(),
79    )
80}
81
82pub struct Codex {
83    model: crate::config::ModelId,
84    /// The validated API root; text only where the HTTP adapter wants it.
85    base: reqwest::Url,
86    state: PathBuf,
87    repo: PathBuf,
88    http: reqwest::Client,
89    /// Every access token a turn of this client sent: a provider error may echo any of them.
90    sent: std::sync::Mutex<Vec<String>>,
91}
92
93impl Codex {
94    pub(super) fn new(
95        model: &crate::config::ModelId,
96        base: reqwest::Url,
97        state: &Path,
98        repo: &Path,
99    ) -> Result<Self, String> {
100        Ok(Self {
101            model: model.clone(),
102            base,
103            state: state.into(),
104            repo: repo.into(),
105            http: super::http_client()?,
106            sent: std::sync::Mutex::new(Vec::new()),
107        })
108    }
109
110    /// The access tokens this client's turns sent.
111    pub(super) fn sent(&self) -> Vec<String> {
112        self.sent.lock().expect("sent tokens lock").clone()
113    }
114
115    /// The Responses model for one turn, with credentials read (and refreshed) now.
116    /// Callers must never print or log the token it carries.
117    pub(super) async fn model(&self) -> Result<Model<Responses>, auth::TokenError> {
118        let token = auth::access_token(Some(&self.state), Some(&self.repo)).await?;
119        {
120            let mut sent = self.sent.lock().expect("sent tokens lock");
121            if !sent.contains(&token.access_token) {
122                sent.push(token.access_token.clone());
123            }
124        }
125        let mut dialect = chatgpt::DIALECT;
126        dialect.quirks.hooks = Some(&HOOKS);
127        // No fresh `session_id` per request, which the backend's cache ignores; the
128        // envelope sends the review's `session-id` instead.
129        if let Some(identity) = &mut dialect.quirks.identity {
130            identity.session_ids = false;
131        }
132        let mut config = openai::OpenAIConfig::with_key(&dialect, token.access_token)
133            .with_base_url(self.base.as_str().trim_end_matches('/'))
134            .with_account_id(token.account_id.to_string());
135        config.instructions = None;
136        config.identity = Some(CallerIdentity {
137            originator: ORIGINATOR.into(),
138            user_agent: user_agent(),
139        });
140        let model = config
141            .connect(super::delivery::Tap::new(self.http.clone()))
142            .responses(self.model.as_str());
143        Ok(Model::new(Responses(model.wire), model.transport))
144    }
145}
146
147/// The known model catalog fields. Maps retain last duplicate values, while absent/null
148/// or wrong-typed optional fields preserve the picker's existing skip/default behavior.
149#[derive(Default)]
150struct ModelCatalog {
151    models: crate::json::Optional<Vec<crate::json::Optional<crate::json::Object<PickerModel>>>>,
152}
153#[derive(Default)]
154struct PickerModel {
155    visibility: crate::json::Optional<String>,
156    slug: crate::json::Optional<String>,
157    display_name: crate::json::Optional<String>,
158    supported_reasoning_levels: crate::json::Optional<Vec<crate::json::Optional<PickerEffort>>>,
159    default_reasoning_level: crate::json::Optional<String>,
160}
161#[derive(serde::Deserialize)]
162struct PickerEffort {
163    effort: String,
164}
165impl<'de> serde::Deserialize<'de> for ModelCatalog {
166    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
167        struct CatalogVisitor;
168        impl<'de> serde::de::Visitor<'de> for CatalogVisitor {
169            type Value = ModelCatalog;
170            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171                formatter.write_str("a model catalog object")
172            }
173            fn visit_map<M: serde::de::MapAccess<'de>>(
174                self,
175                mut map: M,
176            ) -> Result<Self::Value, M::Error> {
177                let mut catalog = ModelCatalog::default();
178                while let Some(field) = map.next_key::<String>()? {
179                    if field == "models" {
180                        catalog.models = map.next_value()?;
181                    } else {
182                        map.next_value::<crate::json::Ignored>()?;
183                    }
184                }
185                Ok(catalog)
186            }
187        }
188        deserializer.deserialize_map(CatalogVisitor)
189    }
190}
191impl<'de> serde::Deserialize<'de> for PickerModel {
192    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
193        struct ModelVisitor;
194        impl<'de> serde::de::Visitor<'de> for ModelVisitor {
195            type Value = PickerModel;
196            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197                formatter.write_str("a picker model object")
198            }
199            fn visit_map<M: serde::de::MapAccess<'de>>(
200                self,
201                mut map: M,
202            ) -> Result<Self::Value, M::Error> {
203                let mut model = PickerModel::default();
204                while let Some(field) = map.next_key::<String>()? {
205                    match field.as_str() {
206                        "visibility" => model.visibility = map.next_value()?,
207                        "slug" => model.slug = map.next_value()?,
208                        "display_name" => model.display_name = map.next_value()?,
209                        "supported_reasoning_levels" => {
210                            model.supported_reasoning_levels = map.next_value()?
211                        }
212                        "default_reasoning_level" => {
213                            model.default_reasoning_level = map.next_value()?
214                        }
215                        _ => {
216                            map.next_value::<crate::json::Ignored>()?;
217                        }
218                    }
219                }
220                Ok(model)
221            }
222        }
223        deserializer.deserialize_map(ModelVisitor)
224    }
225}
226fn picker_models(data: &[u8]) -> Result<Vec<super::models::ListedModel>, String> {
227    let invalid = || "Invalid Codex models response.".to_owned();
228    let crate::json::Object(catalog): crate::json::Object<ModelCatalog> =
229        serde_json::from_slice(data).map_err(|_| invalid())?;
230    catalog
231        .models
232        .0
233        .ok_or_else(invalid)?
234        .into_iter()
235        .filter_map(|model| model.0.map(|crate::json::Object(model)| model))
236        .filter(|model| model.visibility.0.as_deref() == Some("list"))
237        .map(|model| {
238            let slug: crate::config::ModelId = model
239                .slug
240                .0
241                .and_then(|slug| slug.parse().ok())
242                .ok_or_else(invalid)?;
243            let name = model.display_name.0.unwrap_or_else(|| slug.to_string());
244            let efforts = model
245                .supported_reasoning_levels
246                .0
247                .into_iter()
248                .flatten()
249                .filter_map(|value| value.0.map(|level| level.effort));
250            Ok(super::models::ListedModel::new(slug, name)
251                .with_efforts(efforts, model.default_reasoning_level.0))
252        })
253        .collect()
254}
255
256/// The account's Codex models that the Codex picker lists (`visibility: "list"`), in
257/// server order, from `GET <root>/models?client_version=…` as the Codex CLI asks.
258pub(super) async fn models(
259    base: &reqwest::Url,
260    state: Option<&Path>,
261    repo: Option<&Path>,
262) -> Result<Vec<super::models::ListedModel>, String> {
263    let token = auth::access_token(state, repo)
264        .await
265        .map_err(|error| error.message)?;
266    let base = base.as_str().trim_end_matches('/');
267    let response = super::http_client()?
268        .get(format!("{base}/models?client_version={CLIENT_VERSION}"))
269        .bearer_auth(&token.access_token)
270        .header("ChatGPT-Account-Id", token.account_id.as_str())
271        .header("originator", ORIGINATOR)
272        .header(reqwest::header::USER_AGENT, user_agent())
273        .timeout(super::models::LIST_TIMEOUT)
274        .send()
275        .await
276        .map_err(|_| "Codex model listing failed; check your connection.".to_owned())?;
277    let status = response.status();
278    let data = response.bytes().await.unwrap_or_default();
279    if !status.is_success() {
280        // Provider error payloads vary by endpoint; the success catalog has a known shape.
281        let body = Body::parse(&data);
282        let now = auth::now().ok();
283        // The provider's text answers a request that carried the access token: the whole,
284        // unclipped text is checked before anything is cut.
285        let text = crate::secret::server_text(
286            &describe_text(
287                Some(status),
288                body.as_ref(),
289                || "Codex model listing failed.".to_owned(),
290                now,
291            ),
292            &[&token.access_token],
293            super::MAX_DIAGNOSTIC_CHARS,
294        );
295        return Err(if text == crate::secret::WITHHELD {
296            format!(
297                "Codex model listing failed (HTTP {}): {text}",
298                status.as_u16()
299            )
300        } else {
301            text
302        });
303    }
304    picker_models(&data)
305}
306
307/// A Codex provider error as text, cleaned for a terminal but not clipped: callers decide
308/// what of it may be shown ([`crate::secret::server_text`]) before cutting it.
309pub(super) fn diagnostic_text(
310    status: Option<StatusCode>,
311    body: Option<&Body>,
312    fallback: impl FnOnce() -> String,
313    now: Option<auth::Timestamp>,
314) -> String {
315    if body.is_none() {
316        return fallback();
317    }
318    describe_text(status, body, fallback, now)
319}
320
321/// The wait before a usage limit resets is shown in whole minutes, rounded up.
322const SECONDS_PER_MINUTE: u64 = 60;
323
324/// A bounded message with the provider's code, an HTTP status, and what to do next:
325/// usage limits name the plan and when they reset, as Pi words them, and rejected
326/// credentials say how to sign in again.
327#[cfg(test)]
328fn describe(
329    status: Option<StatusCode>,
330    body: Option<&Body>,
331    fallback: &str,
332    now: Option<auth::Timestamp>,
333) -> String {
334    describe_text(status, body, || fallback.to_owned(), now)
335        .chars()
336        .take(super::MAX_DIAGNOSTIC_CHARS)
337        .collect()
338}
339
340/// [`describe`] before clipping.
341fn describe_text(
342    status: Option<StatusCode>,
343    body: Option<&Body>,
344    fallback: impl FnOnce() -> String,
345    now: Option<auth::Timestamp>,
346) -> String {
347    let fields = body.map(Body::codex_fields);
348    let code = fields.and_then(super::error_body::Fields::code);
349    let mut message = if body.is_some_and(|body| body.usage_limit(status)) {
350        let plan = fields
351            .and_then(|fields| fields.plan_type.0.as_deref())
352            .map(|plan| format!(" ({} plan)", plan.to_lowercase()))
353            .unwrap_or_default();
354        let reset = fields
355            .and_then(|fields| fields.resets_at.0)
356            .zip(now)
357            .map(|(at, now)| {
358                format!(
359                    " Try again in ~{} min.",
360                    at.saturating_since(now)
361                        .as_secs()
362                        .div_ceil(SECONDS_PER_MINUTE)
363                )
364            })
365            .unwrap_or_default();
366        format!("You have hit your ChatGPT usage limit{plan}.{reset}")
367    } else {
368        body.and_then(Body::codex_message)
369            .map_or_else(fallback, str::to_owned)
370    };
371    if let Some(code) = code {
372        message = format!("{code}: {message}");
373    }
374    if let Some(status) = status {
375        message.push_str(&format!(" (HTTP {})", status.as_u16()));
376    }
377    if matches!(
378        status,
379        Some(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN)
380    ) {
381        message.push_str(
382            " Sign in again with `artifactize login codex`, or with Codex when ARTIFACTIZE_CODEX_AUTH_FILE is set.",
383        );
384    }
385    super::clean_text(&message)
386}
387
388#[cfg(test)]
389mod tests;