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}
159impl<'de> serde::Deserialize<'de> for ModelCatalog {
160    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
161        struct CatalogVisitor;
162        impl<'de> serde::de::Visitor<'de> for CatalogVisitor {
163            type Value = ModelCatalog;
164            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165                formatter.write_str("a model catalog object")
166            }
167            fn visit_map<M: serde::de::MapAccess<'de>>(
168                self,
169                mut map: M,
170            ) -> Result<Self::Value, M::Error> {
171                let mut catalog = ModelCatalog::default();
172                while let Some(field) = map.next_key::<String>()? {
173                    if field == "models" {
174                        catalog.models = map.next_value()?;
175                    } else {
176                        map.next_value::<crate::json::Ignored>()?;
177                    }
178                }
179                Ok(catalog)
180            }
181        }
182        deserializer.deserialize_map(CatalogVisitor)
183    }
184}
185impl<'de> serde::Deserialize<'de> for PickerModel {
186    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
187        struct ModelVisitor;
188        impl<'de> serde::de::Visitor<'de> for ModelVisitor {
189            type Value = PickerModel;
190            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191                formatter.write_str("a picker model object")
192            }
193            fn visit_map<M: serde::de::MapAccess<'de>>(
194                self,
195                mut map: M,
196            ) -> Result<Self::Value, M::Error> {
197                let mut model = PickerModel::default();
198                while let Some(field) = map.next_key::<String>()? {
199                    match field.as_str() {
200                        "visibility" => model.visibility = map.next_value()?,
201                        "slug" => model.slug = map.next_value()?,
202                        "display_name" => model.display_name = map.next_value()?,
203                        _ => {
204                            map.next_value::<crate::json::Ignored>()?;
205                        }
206                    }
207                }
208                Ok(model)
209            }
210        }
211        deserializer.deserialize_map(ModelVisitor)
212    }
213}
214fn picker_models(data: &[u8]) -> Result<Vec<super::models::ListedModel>, String> {
215    let invalid = || "Invalid Codex models response.".to_owned();
216    let crate::json::Object(catalog): crate::json::Object<ModelCatalog> =
217        serde_json::from_slice(data).map_err(|_| invalid())?;
218    catalog
219        .models
220        .0
221        .ok_or_else(invalid)?
222        .into_iter()
223        .filter_map(|model| model.0.map(|crate::json::Object(model)| model))
224        .filter(|model| model.visibility.0.as_deref() == Some("list"))
225        .map(|model| {
226            let slug: crate::config::ModelId = model
227                .slug
228                .0
229                .and_then(|slug| slug.parse().ok())
230                .ok_or_else(invalid)?;
231            Ok(super::models::ListedModel {
232                display_name: model.display_name.0.unwrap_or_else(|| slug.to_string()),
233                slug,
234            })
235        })
236        .collect()
237}
238
239/// The account's Codex models that the Codex picker lists (`visibility: "list"`), in
240/// server order, from `GET <root>/models?client_version=…` as the Codex CLI asks.
241pub(super) async fn models(
242    base: &reqwest::Url,
243    state: Option<&Path>,
244    repo: Option<&Path>,
245) -> Result<Vec<super::models::ListedModel>, String> {
246    let token = auth::access_token(state, repo)
247        .await
248        .map_err(|error| error.message)?;
249    let base = base.as_str().trim_end_matches('/');
250    let response = super::http_client()?
251        .get(format!("{base}/models?client_version={CLIENT_VERSION}"))
252        .bearer_auth(&token.access_token)
253        .header("ChatGPT-Account-Id", token.account_id.as_str())
254        .header("originator", ORIGINATOR)
255        .header(reqwest::header::USER_AGENT, user_agent())
256        .timeout(super::models::LIST_TIMEOUT)
257        .send()
258        .await
259        .map_err(|_| "Codex model listing failed; check your connection.".to_owned())?;
260    let status = response.status();
261    let data = response.bytes().await.unwrap_or_default();
262    if !status.is_success() {
263        // Provider error payloads vary by endpoint; the success catalog has a known shape.
264        let body = Body::parse(&data);
265        let now = auth::now().ok();
266        // The provider's text answers a request that carried the access token: the whole,
267        // unclipped text is checked before anything is cut.
268        let text = crate::secret::server_text(
269            &describe_text(
270                Some(status),
271                body.as_ref(),
272                || "Codex model listing failed.".to_owned(),
273                now,
274            ),
275            &[&token.access_token],
276            super::MAX_DIAGNOSTIC_CHARS,
277        );
278        return Err(if text == crate::secret::WITHHELD {
279            format!(
280                "Codex model listing failed (HTTP {}): {text}",
281                status.as_u16()
282            )
283        } else {
284            text
285        });
286    }
287    picker_models(&data)
288}
289
290/// A Codex provider error as text, cleaned for a terminal but not clipped: callers decide
291/// what of it may be shown ([`crate::secret::server_text`]) before cutting it.
292pub(super) fn diagnostic_text(
293    status: Option<StatusCode>,
294    body: Option<&Body>,
295    fallback: impl FnOnce() -> String,
296    now: Option<auth::Timestamp>,
297) -> String {
298    if body.is_none() {
299        return fallback();
300    }
301    describe_text(status, body, fallback, now)
302}
303
304/// The wait before a usage limit resets is shown in whole minutes, rounded up.
305const SECONDS_PER_MINUTE: u64 = 60;
306
307/// A bounded message with the provider's code, an HTTP status, and what to do next:
308/// usage limits name the plan and when they reset, as Pi words them, and rejected
309/// credentials say how to sign in again.
310#[cfg(test)]
311fn describe(
312    status: Option<StatusCode>,
313    body: Option<&Body>,
314    fallback: &str,
315    now: Option<auth::Timestamp>,
316) -> String {
317    describe_text(status, body, || fallback.to_owned(), now)
318        .chars()
319        .take(super::MAX_DIAGNOSTIC_CHARS)
320        .collect()
321}
322
323/// [`describe`] before clipping.
324fn describe_text(
325    status: Option<StatusCode>,
326    body: Option<&Body>,
327    fallback: impl FnOnce() -> String,
328    now: Option<auth::Timestamp>,
329) -> String {
330    let fields = body.map(Body::codex_fields);
331    let code = fields.and_then(super::error_body::Fields::code);
332    let mut message = if body.is_some_and(|body| body.usage_limit(status)) {
333        let plan = fields
334            .and_then(|fields| fields.plan_type.0.as_deref())
335            .map(|plan| format!(" ({} plan)", plan.to_lowercase()))
336            .unwrap_or_default();
337        let reset = fields
338            .and_then(|fields| fields.resets_at.0)
339            .zip(now)
340            .map(|(at, now)| {
341                format!(
342                    " Try again in ~{} min.",
343                    at.saturating_since(now)
344                        .as_secs()
345                        .div_ceil(SECONDS_PER_MINUTE)
346                )
347            })
348            .unwrap_or_default();
349        format!("You have hit your ChatGPT usage limit{plan}.{reset}")
350    } else {
351        body.and_then(Body::codex_message)
352            .map_or_else(fallback, str::to_owned)
353    };
354    if let Some(code) = code {
355        message = format!("{code}: {message}");
356    }
357    if let Some(status) = status {
358        message.push_str(&format!(" (HTTP {})", status.as_u16()));
359    }
360    if matches!(
361        status,
362        Some(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN)
363    ) {
364        message.push_str(
365            " Sign in again with `artifactize login codex`, or with Codex when ARTIFACTIZE_CODEX_AUTH_FILE is set.",
366        );
367    }
368    super::clean_text(&message)
369}
370
371#[cfg(test)]
372mod tests;