codex-helper-core 0.20.0

Core library for codex-helper.
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum CodexPatchMode {
    /// Keep the historical codex-helper patch behavior.
    #[default]
    Default,
    /// Keep Codex/ChatGPT account auth for app/mobile features while model traffic goes through
    /// codex-helper.
    ChatGptBridge,
    /// Use a minimal ChatGPT-looking auth facade to expose Codex hosted image generation while
    /// request credentials still come from codex-helper routing/upstream configuration.
    ImagegenBridge,
    /// Advertise the local relay as the official OpenAI Responses provider so Codex can use
    /// first-party HTTP features that helper can safely forward, starting with remote compaction
    /// v1. Request credentials still come from codex-helper routing/upstream configuration.
    #[serde(
        rename = "official-relay",
        alias = "official_relay",
        alias = "official-relay-bridge",
        alias = "official_relay_bridge"
    )]
    OfficialRelayBridge,
    /// Combine official relay provider identity for remote compaction with the image generation
    /// ChatGPT auth facade. Request credentials still come from codex-helper routing/upstream
    /// configuration.
    #[serde(
        rename = "official-imagegen",
        alias = "official_imagegen",
        alias = "official-imagegen-bridge",
        alias = "official_imagegen_bridge"
    )]
    OfficialImagegenBridge,
}

impl CodexPatchMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::ChatGptBridge => "chatgpt-bridge",
            Self::ImagegenBridge => "imagegen-bridge",
            Self::OfficialRelayBridge => "official-relay",
            Self::OfficialImagegenBridge => "official-imagegen",
        }
    }

    pub fn as_preset_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::ChatGptBridge => "chatgpt-bridge",
            Self::ImagegenBridge => "imagegen-bridge",
            Self::OfficialRelayBridge => "official-relay",
            Self::OfficialImagegenBridge => "official-imagegen",
        }
    }

    pub fn is_default(self) -> bool {
        matches!(self, Self::Default)
    }

    pub fn strips_codex_client_auth(self) -> bool {
        matches!(
            self,
            Self::ChatGptBridge
                | Self::ImagegenBridge
                | Self::OfficialRelayBridge
                | Self::OfficialImagegenBridge
        )
    }

    pub fn enables_official_relay_features(self) -> bool {
        matches!(
            self,
            Self::OfficialRelayBridge | Self::OfficialImagegenBridge
        )
    }

    pub fn enables_imagegen_facade(self) -> bool {
        matches!(self, Self::ImagegenBridge | Self::OfficialImagegenBridge)
    }
}

impl std::fmt::Display for CodexPatchMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum CodexCompactionStrategy {
    /// Keep the preset-derived behavior and do not rewrite Codex's existing
    /// `remote_compaction_v2` feature flag.
    #[default]
    Auto,
    /// Force Codex to see a helper-shaped provider so the client chooses local compaction.
    Local,
    /// Force remote compaction v1 through `/responses/compact`.
    #[serde(alias = "remote_v1")]
    RemoteV1,
    /// Force remote compaction v2 through `/responses` with `compaction_trigger`.
    #[serde(alias = "remote_v2")]
    RemoteV2,
}

impl CodexCompactionStrategy {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Local => "local",
            Self::RemoteV1 => "remote-v1",
            Self::RemoteV2 => "remote-v2",
        }
    }

    pub fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }

    pub fn provider_identity_for_mode(self, mode: CodexPatchMode) -> CodexPatchProviderIdentity {
        match self {
            Self::Auto => {
                if mode.enables_official_relay_features() {
                    CodexPatchProviderIdentity::OfficialOpenAi
                } else {
                    CodexPatchProviderIdentity::HelperRelay
                }
            }
            Self::Local => CodexPatchProviderIdentity::HelperRelay,
            Self::RemoteV1 | Self::RemoteV2 => CodexPatchProviderIdentity::OfficialOpenAi,
        }
    }

    pub fn remote_compaction_v2_feature_patch(self) -> CodexFeatureBoolPatch {
        match self {
            Self::Auto => CodexFeatureBoolPatch::Preserve,
            Self::Local | Self::RemoteV1 => CodexFeatureBoolPatch::Set(false),
            Self::RemoteV2 => CodexFeatureBoolPatch::Set(true),
        }
    }
}

impl std::fmt::Display for CodexCompactionStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum CodexHostedImageGenerationMode {
    /// Keep Codex's own feature flag and request tools unchanged.
    #[default]
    Auto,
    /// Explicitly enable Codex hosted image generation in the client config.
    Enabled,
    /// Hide Codex hosted image generation from the client config and outgoing Responses requests.
    Disabled,
}

impl CodexHostedImageGenerationMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Enabled => "enabled",
            Self::Disabled => "disabled",
        }
    }

    pub fn is_auto(&self) -> bool {
        matches!(self, Self::Auto)
    }

    pub fn feature_patch(self) -> CodexFeatureBoolPatch {
        match self {
            Self::Auto => CodexFeatureBoolPatch::Preserve,
            Self::Enabled => CodexFeatureBoolPatch::Set(true),
            Self::Disabled => CodexFeatureBoolPatch::Set(false),
        }
    }

    pub fn filters_request_tools(self) -> bool {
        matches!(self, Self::Disabled)
    }
}

impl std::fmt::Display for CodexHostedImageGenerationMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
pub struct CodexSwitchOptions {
    /// Advertise `model_providers.codex_proxy.supports_websockets = true` so Codex may choose
    /// Responses WebSocket transport. This is intentionally separate from `CodexPatchMode` to
    /// avoid mode-combination explosion.
    #[serde(default, skip_serializing_if = "bool_is_false")]
    pub responses_websocket: bool,
    /// Choose Codex's compaction path without adding more client presets.
    #[serde(default, skip_serializing_if = "CodexCompactionStrategy::is_auto")]
    pub compaction: CodexCompactionStrategy,
}

impl CodexSwitchOptions {
    pub fn validate_for_mode(self, mode: CodexPatchMode) -> Result<()> {
        if matches!(
            self.compaction,
            CodexCompactionStrategy::RemoteV1 | CodexCompactionStrategy::RemoteV2
        ) && !mode.enables_official_relay_features()
        {
            return Err(anyhow!(
                "remote compaction strategies require --preset official-relay or --preset official-imagegen"
            ));
        }

        let provider_identity = self.compaction.provider_identity_for_mode(mode);
        if self.responses_websocket
            && provider_identity != CodexPatchProviderIdentity::OfficialOpenAi
        {
            return Err(anyhow!(
                "Responses WebSocket transport requires remote compaction identity; use --preset official-relay or --preset official-imagegen without --compaction local"
            ));
        }
        Ok(())
    }
}

fn bool_is_false(value: &bool) -> bool {
    !*value
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexPatchProviderIdentity {
    HelperRelay,
    OfficialOpenAi,
}

impl CodexPatchProviderIdentity {
    pub fn provider_name(self) -> &'static str {
        match self {
            Self::HelperRelay => "codex-helper",
            Self::OfficialOpenAi => "OpenAI",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexTomlBoolPatch {
    Remove,
    Set(bool),
}

impl CodexTomlBoolPatch {
    pub fn value(self) -> Option<bool> {
        match self {
            Self::Remove => None,
            Self::Set(value) => Some(value),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexFeatureBoolPatch {
    Preserve,
    Set(bool),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CodexProviderPatchPlan {
    identity: CodexPatchProviderIdentity,
    requires_openai_auth: CodexTomlBoolPatch,
    supports_websockets: CodexTomlBoolPatch,
}

impl CodexProviderPatchPlan {
    pub fn identity(self) -> CodexPatchProviderIdentity {
        self.identity
    }

    pub fn provider_name(self) -> &'static str {
        self.identity.provider_name()
    }

    pub fn requires_openai_auth(self) -> CodexTomlBoolPatch {
        self.requires_openai_auth
    }

    pub fn supports_websockets(self) -> CodexTomlBoolPatch {
        self.supports_websockets
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexAuthPatchPlan {
    RestoreOriginalIfHelperPatched,
    PatchChatGptBridge,
    PatchImagegenFacade,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexSwitchOnEffectOrder {
    ConfigAuthState,
    StateConfigAuth,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CodexPatchPlan {
    mode: CodexPatchMode,
    options: CodexSwitchOptions,
    provider: CodexProviderPatchPlan,
    remote_compaction_v2: CodexFeatureBoolPatch,
    auth: CodexAuthPatchPlan,
    effect_order: CodexSwitchOnEffectOrder,
}

impl CodexPatchPlan {
    pub fn for_switch_on(mode: CodexPatchMode, options: CodexSwitchOptions) -> Result<Self> {
        options.validate_for_mode(mode)?;

        let provider = CodexProviderPatchPlan {
            identity: options.compaction.provider_identity_for_mode(mode),
            requires_openai_auth: match mode {
                CodexPatchMode::ChatGptBridge => CodexTomlBoolPatch::Set(true),
                CodexPatchMode::Default
                | CodexPatchMode::ImagegenBridge
                | CodexPatchMode::OfficialRelayBridge
                | CodexPatchMode::OfficialImagegenBridge => CodexTomlBoolPatch::Remove,
            },
            supports_websockets: match mode {
                CodexPatchMode::Default | CodexPatchMode::ImagegenBridge => {
                    CodexTomlBoolPatch::Remove
                }
                CodexPatchMode::ChatGptBridge => CodexTomlBoolPatch::Set(false),
                CodexPatchMode::OfficialRelayBridge | CodexPatchMode::OfficialImagegenBridge => {
                    CodexTomlBoolPatch::Set(options.responses_websocket)
                }
            },
        };

        let auth = match mode {
            CodexPatchMode::Default | CodexPatchMode::OfficialRelayBridge => {
                CodexAuthPatchPlan::RestoreOriginalIfHelperPatched
            }
            CodexPatchMode::ChatGptBridge => CodexAuthPatchPlan::PatchChatGptBridge,
            CodexPatchMode::ImagegenBridge | CodexPatchMode::OfficialImagegenBridge => {
                CodexAuthPatchPlan::PatchImagegenFacade
            }
        };

        let effect_order = match auth {
            CodexAuthPatchPlan::RestoreOriginalIfHelperPatched => {
                CodexSwitchOnEffectOrder::ConfigAuthState
            }
            CodexAuthPatchPlan::PatchChatGptBridge | CodexAuthPatchPlan::PatchImagegenFacade => {
                CodexSwitchOnEffectOrder::StateConfigAuth
            }
        };

        Ok(Self {
            mode,
            options,
            provider,
            remote_compaction_v2: options.compaction.remote_compaction_v2_feature_patch(),
            auth,
            effect_order,
        })
    }

    pub fn mode(self) -> CodexPatchMode {
        self.mode
    }

    pub fn options(self) -> CodexSwitchOptions {
        self.options
    }

    pub fn provider(self) -> CodexProviderPatchPlan {
        self.provider
    }

    pub fn remote_compaction_v2_feature(self) -> CodexFeatureBoolPatch {
        self.remote_compaction_v2
    }

    pub fn auth(self) -> CodexAuthPatchPlan {
        self.auth
    }

    pub fn effect_order(self) -> CodexSwitchOnEffectOrder {
        self.effect_order
    }

    pub fn requires_bridge_runtime_ready(self) -> bool {
        self.mode.strips_codex_client_auth() && self.mode != CodexPatchMode::ChatGptBridge
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn codex_patch_mode_serializes_current_official_preset_names() {
        assert_eq!(
            serde_json::to_string(&CodexPatchMode::OfficialRelayBridge).unwrap(),
            "\"official-relay\""
        );
        assert_eq!(
            serde_json::to_string(&CodexPatchMode::OfficialImagegenBridge).unwrap(),
            "\"official-imagegen\""
        );
    }

    #[test]
    fn codex_patch_mode_reads_legacy_official_bridge_state() {
        assert_eq!(
            serde_json::from_str::<CodexPatchMode>("\"official-relay-bridge\"").unwrap(),
            CodexPatchMode::OfficialRelayBridge
        );
        assert_eq!(
            serde_json::from_str::<CodexPatchMode>("\"official-imagegen-bridge\"").unwrap(),
            CodexPatchMode::OfficialImagegenBridge
        );
    }
}