artifactize-provider 0.27.2

Managed credentials, model discovery and direct HTTP turns for Artifactize.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! The `codex` backend: the Codex Responses endpoint with ChatGPT/Codex sign-in
//! credentials, the way Pi's `openai-codex` provider calls it
//! (pi-mono `packages/ai/src/api/openai-codex-responses.ts`).
//!
//! rig's ChatGPT dialect speaks the Codex request contract: an always-streamed
//! Responses turn with `store:false`, encrypted reasoning replay, function tools, all
//! system messages as top-level `instructions`, and an event stream that may name no
//! content type. artifactize adds the headers Pi sends (`OpenAI-Beta`, an event-stream
//! `accept`, its own `originator` and user agent, the ChatGPT account), and drops
//! rig's default instructions so the review's own system prompt is the only one.
//!
//! Every request of one review carries the review's session id, as `prompt_cache_key`
//! and as the `session-id` header the backend keys its prompt cache on. rig 0.43 sends a
//! fresh `session_id` per request instead (0xPlaygrounds/rig#2719), which artifactize
//! turns off.

use reqwest::StatusCode;
use rig_core::{
    Model,
    completion::CompletionRequest,
    http_client::Builder,
    providers::{
        chatgpt,
        openai::{
            self,
            wire::{CallerIdentity, DialectHooks},
        },
    },
};
mod output;
pub(crate) use output::Responses;

use super::error_body::Body;
use crate::auth::codex::{self as auth, ORIGINATOR};

/// The Codex API root; requests go to `<root>/responses` and `<root>/models`.
pub const BASE_URL: &str = "https://chatgpt.com/backend-api/codex";

/// The Codex backend filters its model catalog by client version. artifactize asks
/// for the catalog of the Codex release whose Responses protocol it follows.
pub const CLIENT_VERSION: &str = "0.169.0";

static HOOKS: DialectHooks = DialectHooks {
    default_endpoint: None,
    model_route: None,
    completion_envelope: Some(envelope),
    modality_envelope: None,
};

fn envelope(_: &openai::OpenAIConfig, request: &CompletionRequest, builder: Builder) -> Builder {
    let builder = builder
        .header("OpenAI-Beta", "responses=experimental")
        .header("accept", "text/event-stream");
    // TODO: once rig ships `OpenAIConfig::with_session_id` (0xPlaygrounds/rig#2722), pin
    // the session there and drop this header and the `session_ids` override in `model`.
    match session(request) {
        Some(session) => builder.header("session-id", session),
        None => builder,
    }
}

/// The review's session id: the request's `prompt_cache_key` ([`super::Client::parameters`]).
fn session(request: &CompletionRequest) -> Option<&str> {
    request
        .additional_params
        .as_ref()?
        .get("prompt_cache_key")?
        .as_str()
}

/// `artifactize/<version> (<os> <arch>; artifactize)`, the shape rig gives gateways.
pub fn user_agent() -> String {
    format!(
        "artifactize/{} ({}; {ORIGINATOR})",
        env!("CARGO_PKG_VERSION"),
        crate::platform::label(),
    )
}

pub struct Codex {
    model: crate::names::ModelId,
    /// The validated API root; text only where the HTTP adapter wants it.
    base: reqwest::Url,
    location: Result<crate::auth::Location, String>,
    http: reqwest::Client,
    /// Keep used and rotated credentials protected even after a later rotation removes them.
    known: std::sync::Mutex<crate::secret::Inventory>,
}

impl Codex {
    pub(super) fn new(
        model: &crate::names::ModelId,
        base: reqwest::Url,
        location: Result<crate::auth::Location, String>,
    ) -> Result<Self, String> {
        Ok(Self {
            model: model.clone(),
            base,
            location,
            http: super::http_client()?,
            known: std::sync::Mutex::default(),
        })
    }

    pub(super) fn known(&self) -> crate::secret::Inventory {
        self.known.lock().expect("known credentials lock").clone()
    }

    /// The Responses model for one turn, with credentials read (and refreshed) now.
    /// Callers must never print or log the token it carries.
    pub(super) async fn model(&self) -> Result<Model<Responses>, auth::TokenError> {
        let location = self.location.as_ref().map_err(String::as_str);
        let before = crate::secret::Inventory::read(None, location.ok());
        self.known
            .lock()
            .expect("known credentials lock")
            .merge(before);
        let token = auth::access_token(location).await?;
        {
            let mut known = self.known.lock().expect("known credentials lock");
            known.include(token.access_token.clone());
            if let Some(refresh) = token.refresh_token {
                known.include(refresh);
            }
        }
        let mut dialect = chatgpt::DIALECT;
        dialect.quirks.hooks = Some(&HOOKS);
        // No fresh `session_id` per request, which the backend's cache ignores; the
        // envelope sends the review's `session-id` instead.
        if let Some(identity) = &mut dialect.quirks.identity {
            identity.session_ids = false;
        }
        let mut config = openai::OpenAIConfig::with_key(&dialect, token.access_token)
            .with_base_url(self.base.as_str().trim_end_matches('/'))
            .with_account_id(token.account_id.to_string());
        config.instructions = None;
        config.identity = Some(CallerIdentity {
            originator: ORIGINATOR.into(),
            user_agent: user_agent(),
        });
        let model = config
            .connect(super::delivery::Tap::new(self.http.clone()))
            .responses(self.model.as_str());
        Ok(Model::new(Responses(model.wire), model.transport))
    }
}

/// The known model catalog fields. Maps retain last duplicate values, while absent/null
/// or wrong-typed optional fields preserve the picker's existing skip/default behavior.
#[derive(Default)]
struct ModelCatalog {
    models: crate::json::Optional<Vec<crate::json::Optional<crate::json::Object<PickerModel>>>>,
}
#[derive(Default)]
struct PickerModel {
    visibility: crate::json::Optional<String>,
    slug: crate::json::Optional<String>,
    display_name: crate::json::Optional<String>,
    supported_reasoning_levels: crate::json::Optional<Vec<crate::json::Optional<PickerEffort>>>,
    default_reasoning_level: crate::json::Optional<String>,
}
#[derive(serde::Deserialize)]
struct PickerEffort {
    effort: String,
}
impl<'de> serde::Deserialize<'de> for ModelCatalog {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct CatalogVisitor;
        impl<'de> serde::de::Visitor<'de> for CatalogVisitor {
            type Value = ModelCatalog;
            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a model catalog object")
            }
            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                mut map: M,
            ) -> Result<Self::Value, M::Error> {
                let mut catalog = ModelCatalog::default();
                while let Some(field) = map.next_key::<String>()? {
                    if field == "models" {
                        catalog.models = map.next_value()?;
                    } else {
                        map.next_value::<crate::json::Ignored>()?;
                    }
                }
                Ok(catalog)
            }
        }
        deserializer.deserialize_map(CatalogVisitor)
    }
}
impl<'de> serde::Deserialize<'de> for PickerModel {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct ModelVisitor;
        impl<'de> serde::de::Visitor<'de> for ModelVisitor {
            type Value = PickerModel;
            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a picker model object")
            }
            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                mut map: M,
            ) -> Result<Self::Value, M::Error> {
                let mut model = PickerModel::default();
                while let Some(field) = map.next_key::<String>()? {
                    match field.as_str() {
                        "visibility" => model.visibility = map.next_value()?,
                        "slug" => model.slug = map.next_value()?,
                        "display_name" => model.display_name = map.next_value()?,
                        "supported_reasoning_levels" => {
                            model.supported_reasoning_levels = map.next_value()?
                        }
                        "default_reasoning_level" => {
                            model.default_reasoning_level = map.next_value()?
                        }
                        _ => {
                            map.next_value::<crate::json::Ignored>()?;
                        }
                    }
                }
                Ok(model)
            }
        }
        deserializer.deserialize_map(ModelVisitor)
    }
}
fn picker_models(data: &[u8]) -> Result<Vec<super::models::ListedModel>, String> {
    let invalid = || "Invalid Codex models response.".to_owned();
    let crate::json::Object(catalog): crate::json::Object<ModelCatalog> =
        serde_json::from_slice(data).map_err(|_| invalid())?;
    catalog
        .models
        .0
        .ok_or_else(invalid)?
        .into_iter()
        .filter_map(|model| model.0.map(|crate::json::Object(model)| model))
        .filter(|model| model.visibility.0.as_deref() == Some("list"))
        .map(|model| {
            let slug: crate::names::ModelId = model
                .slug
                .0
                .and_then(|slug| slug.parse().ok())
                .ok_or_else(invalid)?;
            let name = model.display_name.0.unwrap_or_else(|| slug.to_string());
            let efforts = model
                .supported_reasoning_levels
                .0
                .into_iter()
                .flatten()
                .filter_map(|value| value.0.map(|level| level.effort));
            Ok(super::models::ListedModel::new(slug, name)
                .with_efforts(efforts, model.default_reasoning_level.0))
        })
        .collect()
}

/// The account's Codex models that the Codex picker lists (`visibility: "list"`), in
/// server order, from `GET <root>/models?client_version=…` as the Codex CLI asks.
pub(super) async fn models(
    base: &reqwest::Url,
    location: Result<&crate::auth::Location, &str>,
    current: impl Fn() -> crate::secret::Inventory,
) -> Result<Vec<super::models::ListedModel>, String> {
    let token = auth::access_token(location)
        .await
        .map_err(|error| current().scrub(&error.message))?;
    let inventory = || {
        let mut managed = current();
        managed.include(token.access_token.clone());
        if let Some(refresh) = &token.refresh_token {
            managed.include(refresh.clone());
        }
        managed
    };
    let base = base.as_str().trim_end_matches('/');
    let response = super::http_client()
        .map_err(|error| inventory().scrub(&error))?
        .get(format!("{base}/models?client_version={CLIENT_VERSION}"))
        .bearer_auth(&token.access_token)
        .header("ChatGPT-Account-Id", token.account_id.as_str())
        .header("originator", ORIGINATOR)
        .header(reqwest::header::USER_AGENT, user_agent())
        .timeout(super::models::LIST_TIMEOUT)
        .send()
        .await
        .map_err(|_| inventory().scrub("Codex model listing failed; check your connection."))?;
    let status = response.status();
    let data = response.bytes().await.unwrap_or_default();
    let managed = inventory();
    if !status.is_success() {
        // Provider error payloads vary by endpoint; the success catalog has a known shape.
        let body = Body::parse(&data);
        let now = auth::now().ok();
        // The provider's text answers a request that carried the access token: the whole,
        // unclipped text is checked before anything is cut.
        let text = managed.diagnostic(
            &describe_text(
                Some(status),
                body.as_ref(),
                || "Codex model listing failed.".to_owned(),
                now,
                &managed,
            ),
            super::MAX_DIAGNOSTIC_CHARS,
        );
        return Err(if text == crate::secret::WITHHELD {
            managed.scrub(&format!(
                "Codex model listing failed (HTTP {}): {text}",
                status.as_u16()
            ))
        } else {
            text
        });
    }
    picker_models(&data)
        .map(|models| super::models::scrub_models(models, &managed))
        .map_err(|error| managed.scrub(&error))
}

/// A Codex provider error as text, cleaned for a terminal but not clipped: callers decide
/// what of it may be shown ([`crate::secret::server_text`]) before cutting it.
pub(super) fn diagnostic_text(
    status: Option<StatusCode>,
    body: Option<&Body>,
    fallback: impl FnOnce() -> String,
    now: Option<auth::Timestamp>,
    managed: &crate::secret::Inventory,
) -> String {
    if body.is_none() {
        return fallback();
    }
    describe_text(status, body, fallback, now, managed)
}

/// The wait before a usage limit resets is shown in whole minutes, rounded up.
const SECONDS_PER_MINUTE: u64 = 60;

/// A bounded message with the provider's code, an HTTP status, and what to do next:
/// usage limits name the plan and when they reset, as Pi words them, and rejected
/// credentials say how to sign in again.
#[cfg(test)]
fn describe(
    status: Option<StatusCode>,
    body: Option<&Body>,
    fallback: &str,
    now: Option<auth::Timestamp>,
) -> String {
    describe_text(
        status,
        body,
        || fallback.to_owned(),
        now,
        &Default::default(),
    )
    .chars()
    .take(super::MAX_DIAGNOSTIC_CHARS)
    .collect()
}

/// [`describe`] before clipping.
fn describe_text(
    status: Option<StatusCode>,
    body: Option<&Body>,
    fallback: impl FnOnce() -> String,
    now: Option<auth::Timestamp>,
    managed: &crate::secret::Inventory,
) -> String {
    let fields = body.map(Body::codex_fields);
    let code = fields.and_then(super::error_body::Fields::code);
    let mut message = if body.is_some_and(|body| body.usage_limit(status)) {
        let plan = fields.and_then(|fields| fields.plan_type.0.as_deref());
        // Check server text before normalizing its spelling; lowercasing can mask a token.
        if plan.is_some_and(|plan| managed.contains_piece(plan)) {
            return crate::secret::WITHHELD.to_owned();
        }
        let plan = plan
            .map(|plan| format!(" ({} plan)", plan.to_lowercase()))
            .unwrap_or_default();
        let reset = fields
            .and_then(|fields| fields.resets_at.0)
            .zip(now)
            .map(|(at, now)| {
                format!(
                    " Try again in ~{} min.",
                    at.saturating_since(now)
                        .as_secs()
                        .div_ceil(SECONDS_PER_MINUTE)
                )
            })
            .unwrap_or_default();
        format!("You have hit your ChatGPT usage limit{plan}.{reset}")
    } else {
        body.and_then(Body::codex_message)
            .map_or_else(fallback, str::to_owned)
    };
    if let Some(code) = code {
        message = format!("{code}: {message}");
    }
    if let Some(status) = status {
        message.push_str(&format!(" (HTTP {})", status.as_u16()));
    }
    if matches!(
        status,
        Some(StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN)
    ) {
        message.push_str(
            " Sign in again with `artifactize login codex`, or with Codex when ARTIFACTIZE_CODEX_AUTH_FILE is set.",
        );
    }
    super::clean_text(&message)
}

#[cfg(test)]
mod tests;