Skip to main content

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