codex-codes 0.129.0

A tightly typed Rust interface for the OpenAI Codex CLI JSON protocol
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Codex app-server protocol coverage scorecard.
//!
//! Walks the upstream JSON Schema bundle (`codex_app_server_protocol.v2.schemas.json`)
//! and reports, for every method in `ServerNotification.oneOf` and
//! `ClientRequest.oneOf`:
//!
//!   ✓  modeled in `codex-codes` AND a hand-rolled sample validates against
//!      the schema's params definition (catches wire drift)
//!   ◐  modeled in `codex-codes` but we don't have a sample yet (so we don't
//!      know whether our struct's serde shape matches the wire — grow the
//!      sample registry below to fix)
//!   ✗  not modeled in `codex-codes` at all
//!
//! ## Run
//!
//! ```
//! cargo run --example schema_coverage
//! ```
//!
//! Uses the snapshot schema at `tests/schemas/codex_app_server_protocol.v2.schemas.json`
//! by default; override with `CODEX_SCHEMA_PATH=/path/to/freshly-generated.json`
//! (e.g. what `codex app-server generate-json-schema --out DIR` writes).
//!
//! ## Exit codes
//!
//! * `0` — no drift detected on any *validated* sample (unmodeled methods are
//!   informational, not failures)
//! * `1` — at least one modeled sample failed to validate; the wire shape has
//!   drifted from our typed struct
//!
//! ## Adding samples
//!
//! Each modeled method should have an entry in `samples::server_notification`
//! or `samples::client_request` that returns a representative serialized
//! payload constructed from real Rust types. New variants without samples
//! show up as ◐; that's a backlog item, not a failure.

use std::collections::BTreeMap;
use std::path::PathBuf;
use std::process::ExitCode;

use jsonschema::Validator;
use serde_json::Value;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
    /// Method modeled and a sample serialized JSON validates against the schema.
    Validated,
    /// Method modeled but no sample registered.
    NoSample,
    /// Method modeled, sample serialized, but did NOT match the schema.
    Drift,
    /// Method not modeled at all.
    NotModeled,
}

impl Status {
    fn glyph(self) -> &'static str {
        match self {
            Status::Validated => "",
            Status::NoSample => "",
            Status::Drift => "",
            Status::NotModeled => "",
        }
    }

    fn descr(self) -> &'static str {
        match self {
            Status::Validated => "modeled, sample validates",
            Status::NoSample => "modeled, no sample yet",
            Status::Drift => "modeled, sample does NOT validate (DRIFT)",
            Status::NotModeled => "not modeled",
        }
    }
}

#[derive(Debug)]
struct Row {
    method: String,
    params_def: String,
    status: Status,
    errors: Vec<String>,
}

fn main() -> ExitCode {
    let path = std::env::var("CODEX_SCHEMA_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("tests/schemas/codex_app_server_protocol.v2.schemas.json")
        });

    let bundle: Value = match std::fs::read_to_string(&path)
        .map_err(|e| format!("read: {}", e))
        .and_then(|s| serde_json::from_str(&s).map_err(|e| format!("parse: {}", e)))
    {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: could not load schema at {}: {}", path.display(), e);
            return ExitCode::from(2);
        }
    };

    let modeled_notifications = samples::modeled_notification_methods();
    let modeled_requests = samples::modeled_client_request_methods();
    let notif_samples = samples::server_notification_samples();
    let req_samples = samples::client_request_samples();

    let server_rows = walk_envelope(
        &bundle,
        "ServerNotification",
        &modeled_notifications,
        &notif_samples,
    );
    let request_rows = walk_envelope(&bundle, "ClientRequest", &modeled_requests, &req_samples);

    print_report(&path, &server_rows, &request_rows);

    let drift_any = server_rows
        .iter()
        .chain(&request_rows)
        .any(|r| r.status == Status::Drift);
    if drift_any {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn walk_envelope(
    bundle: &Value,
    envelope_name: &str,
    modeled: &std::collections::HashSet<&'static str>,
    sample_registry: &BTreeMap<&'static str, Value>,
) -> Vec<Row> {
    let envelope = match &bundle["definitions"][envelope_name] {
        Value::Object(o) => o,
        _ => {
            eprintln!("warning: schema has no definition for {}", envelope_name);
            return Vec::new();
        }
    };
    let Some(Value::Array(variants)) = envelope.get("oneOf") else {
        eprintln!(
            "warning: definitions.{}.oneOf missing or not an array",
            envelope_name
        );
        return Vec::new();
    };

    let mut rows: Vec<Row> = variants
        .iter()
        .filter_map(extract_envelope_variant)
        .collect();

    // Sort by method for stable output.
    rows.sort_by(|a, b| a.method.cmp(&b.method));

    for row in rows.iter_mut() {
        if !modeled.contains(row.method.as_str()) {
            row.status = Status::NotModeled;
            continue;
        }
        match sample_registry.get(row.method.as_str()) {
            None => {
                row.status = Status::NoSample;
            }
            Some(sample) => match validate_against_def(bundle, &row.params_def, sample) {
                Ok(()) => row.status = Status::Validated,
                Err(errs) => {
                    row.status = Status::Drift;
                    row.errors = errs;
                }
            },
        }
    }

    rows
}

fn extract_envelope_variant(v: &Value) -> Option<Row> {
    let obj = v.as_object()?;
    let props = obj.get("properties")?.as_object()?;

    // method: { enum: ["..."] }
    let method = props
        .get("method")?
        .get("enum")?
        .as_array()?
        .first()?
        .as_str()?
        .to_string();

    // params: { $ref: "#/definitions/SomeType" }  -- some variants omit params.
    let params_def = props
        .get("params")
        .and_then(|p| p.get("$ref"))
        .and_then(|r| r.as_str())
        .and_then(|s| s.strip_prefix("#/definitions/"))
        .unwrap_or("<no params>")
        .to_string();

    Some(Row {
        method,
        params_def,
        status: Status::NotModeled,
        errors: Vec::new(),
    })
}

/// Compile a single-definition schema against the full bundle's `definitions`
/// table so `$ref` lookups resolve, then validate `sample`.
fn validate_against_def(bundle: &Value, def_name: &str, sample: &Value) -> Result<(), Vec<String>> {
    let wrapped = serde_json::json!({
        "$ref": format!("#/definitions/{}", def_name),
        "definitions": bundle["definitions"].clone(),
    });
    let validator = match Validator::new(&wrapped) {
        Ok(v) => v,
        Err(e) => return Err(vec![format!("compile error: {}", e)]),
    };
    let errs: Vec<String> = validator
        .iter_errors(sample)
        .map(|e| format!("{} ({})", e, e.instance_path()))
        .collect();
    if errs.is_empty() {
        Ok(())
    } else {
        Err(errs)
    }
}

fn print_report(path: &std::path::Path, server: &[Row], requests: &[Row]) {
    println!("Codex app-server protocol coverage — codex-codes scorecard");
    println!("============================================================");
    println!("schema: {}", path.display());
    println!();
    print_section("Server → Client Notifications", server);
    print_section("Client → Server Requests", requests);

    let total = server.len() + requests.len();
    let modeled = server
        .iter()
        .chain(requests)
        .filter(|r| {
            matches!(
                r.status,
                Status::Validated | Status::NoSample | Status::Drift
            )
        })
        .count();
    let validated = server
        .iter()
        .chain(requests)
        .filter(|r| r.status == Status::Validated)
        .count();
    let drift = server
        .iter()
        .chain(requests)
        .filter(|r| r.status == Status::Drift)
        .count();
    println!("Overall:");
    println!(
        "  modeled:        {modeled}/{total} ({:.0}%)",
        100.0 * modeled as f32 / total.max(1) as f32
    );
    println!(
        "  with sample:    {validated}/{modeled} ({:.0}%)",
        100.0 * validated as f32 / modeled.max(1) as f32
    );
    if drift > 0 {
        println!("  DRIFT:          {drift}");
    }
}

fn print_section(title: &str, rows: &[Row]) {
    let total = rows.len();
    let modeled = rows
        .iter()
        .filter(|r| {
            matches!(
                r.status,
                Status::Validated | Status::NoSample | Status::Drift
            )
        })
        .count();
    let pct = 100.0 * modeled as f32 / total.max(1) as f32;
    println!("{title} ({modeled}/{total} modeled, {pct:.0}%)");
    println!("{}", "-".repeat(title.len() + 40));

    for r in rows {
        println!(
            "  {}  {:<46} → {:<40} {}",
            r.status.glyph(),
            r.method,
            r.params_def,
            r.status.descr()
        );
        for e in &r.errors {
            println!("     {}", e);
        }
    }
    println!();
}

/// Registry of which methods we model and representative wire samples.
///
/// Adding a sample is the cheap way to grow our drift-detection coverage:
/// instantiate the typed struct with realistic field values, return it as a
/// JSON `Value`. The schema validator then checks the wire shape matches.
mod samples {
    use codex_codes::protocol::methods;
    use codex_codes::ErrorNotification;
    use serde_json::Value;
    use std::collections::{BTreeMap, HashSet};

    /// Method strings our `Notification` enum has a typed variant for. Must
    /// stay in sync with [`codex_codes::messages::Notification`].
    pub(super) fn modeled_notification_methods() -> HashSet<&'static str> {
        [
            methods::THREAD_STARTED,
            methods::THREAD_STATUS_CHANGED,
            methods::THREAD_TOKEN_USAGE_UPDATED,
            methods::TURN_STARTED,
            methods::TURN_COMPLETED,
            methods::ITEM_STARTED,
            methods::ITEM_COMPLETED,
            methods::AGENT_MESSAGE_DELTA,
            methods::CMD_OUTPUT_DELTA,
            methods::FILE_CHANGE_OUTPUT_DELTA,
            methods::REASONING_DELTA,
            methods::ERROR,
            methods::ACCOUNT_RATE_LIMITS_UPDATED,
            methods::MCP_SERVER_STARTUP_STATUS_UPDATED,
            methods::MCP_SERVER_OAUTH_LOGIN_COMPLETED,
            methods::REMOTE_CONTROL_STATUS_CHANGED,
            methods::FILE_CHANGE_PATCH_UPDATED,
            methods::PLAN_DELTA,
            methods::TURN_PLAN_UPDATED,
            methods::TURN_DIFF_UPDATED,
            methods::REASONING_SUMMARY_PART_ADDED,
            methods::REASONING_TEXT_DELTA,
            methods::ACCOUNT_LOGIN_COMPLETED,
            methods::DEPRECATION_NOTICE,
            methods::GUARDIAN_WARNING,
            methods::WARNING,
            methods::THREAD_ARCHIVED,
            methods::THREAD_CLOSED,
            methods::THREAD_UNARCHIVED,
            methods::THREAD_GOAL_CLEARED,
            methods::THREAD_NAME_UPDATED,
            methods::SKILLS_CHANGED,
            methods::FS_CHANGED,
            methods::CONFIG_WARNING,
            methods::ACCOUNT_UPDATED,
            methods::APP_LIST_UPDATED,
            methods::COMMAND_EXEC_OUTPUT_DELTA,
            methods::EXTERNAL_AGENT_CONFIG_IMPORT_COMPLETED,
            methods::FUZZY_FILE_SEARCH_SESSION_COMPLETED,
            methods::FUZZY_FILE_SEARCH_SESSION_UPDATED,
            methods::HOOK_COMPLETED,
            methods::HOOK_STARTED,
            methods::ITEM_AUTO_APPROVAL_REVIEW_COMPLETED,
            methods::ITEM_AUTO_APPROVAL_REVIEW_STARTED,
            methods::ITEM_COMMAND_EXEC_TERMINAL_INTERACTION,
            methods::ITEM_MCP_TOOL_CALL_PROGRESS,
            methods::MODEL_REROUTED,
            methods::MODEL_VERIFICATION,
            methods::PROCESS_EXITED,
            methods::PROCESS_OUTPUT_DELTA,
            methods::SERVER_REQUEST_RESOLVED,
            methods::THREAD_COMPACTED,
            methods::THREAD_GOAL_UPDATED,
            methods::THREAD_REALTIME_CLOSED,
            methods::THREAD_REALTIME_ERROR,
            methods::THREAD_REALTIME_ITEM_ADDED,
            methods::THREAD_REALTIME_OUTPUT_AUDIO_DELTA,
            methods::THREAD_REALTIME_SDP,
            methods::THREAD_REALTIME_STARTED,
            methods::THREAD_REALTIME_TRANSCRIPT_DELTA,
            methods::THREAD_REALTIME_TRANSCRIPT_DONE,
            methods::WINDOWS_WORLD_WRITABLE_WARNING,
            methods::WINDOWS_SANDBOX_SETUP_COMPLETED,
        ]
        .into_iter()
        .collect()
    }

    /// Method strings our client request surface (Params/Response pairs) covers.
    /// Must stay in sync with `client_async.rs` / `client_sync.rs`.
    pub(super) fn modeled_client_request_methods() -> HashSet<&'static str> {
        [
            methods::INITIALIZE,
            methods::INITIALIZED,
            methods::THREAD_START,
            methods::THREAD_ARCHIVE,
            methods::TURN_START,
            methods::TURN_INTERRUPT,
            methods::TURN_STEER,
            methods::THREAD_RESUME,
            methods::THREAD_FORK,
            methods::THREAD_UNSUBSCRIBE,
            methods::THREAD_NAME_SET,
            methods::THREAD_METADATA_UPDATE,
            methods::THREAD_UNARCHIVE,
            methods::THREAD_COMPACT_START,
            methods::THREAD_SHELLCOMMAND,
            methods::THREAD_APPROVEGUARDIANDENIEDACTION,
            methods::THREAD_ROLLBACK,
            methods::THREAD_LIST,
            methods::THREAD_LOADED_LIST,
            methods::THREAD_READ,
            methods::THREAD_INJECT_ITEMS,
            methods::SKILLS_LIST,
            methods::HOOKS_LIST,
            methods::MARKETPLACE_ADD,
            methods::MARKETPLACE_REMOVE,
            methods::MARKETPLACE_UPGRADE,
            methods::PLUGIN_LIST,
            methods::PLUGIN_READ,
            methods::PLUGIN_SKILL_READ,
            methods::PLUGIN_SHARE_SAVE,
            methods::PLUGIN_SHARE_UPDATETARGETS,
            methods::PLUGIN_SHARE_LIST,
            methods::PLUGIN_SHARE_CHECKOUT,
            methods::PLUGIN_SHARE_DELETE,
            methods::APP_LIST,
            methods::FS_READFILE,
            methods::FS_WRITEFILE,
            methods::FS_CREATEDIRECTORY,
            methods::FS_GETMETADATA,
            methods::FS_READDIRECTORY,
            methods::FS_REMOVE,
            methods::FS_COPY,
            methods::FS_WATCH,
            methods::FS_UNWATCH,
            methods::SKILLS_CONFIG_WRITE,
            methods::PLUGIN_INSTALL,
            methods::PLUGIN_UNINSTALL,
            methods::REVIEW_START,
            methods::MODEL_LIST,
            methods::MODELPROVIDER_CAPABILITIES_READ,
            methods::EXPERIMENTALFEATURE_LIST,
            methods::EXPERIMENTALFEATURE_ENABLEMENT_SET,
            methods::MCPSERVER_OAUTH_LOGIN,
            methods::CONFIG_MCPSERVER_RELOAD,
            methods::MCPSERVERSTATUS_LIST,
            methods::MCPSERVER_RESOURCE_READ,
            methods::MCPSERVER_TOOL_CALL,
            methods::WINDOWSSANDBOX_SETUPSTART,
            methods::WINDOWSSANDBOX_READINESS,
            methods::ACCOUNT_LOGIN_START,
            methods::ACCOUNT_LOGIN_CANCEL,
            methods::ACCOUNT_LOGOUT,
            methods::ACCOUNT_RATELIMITS_READ,
            methods::ACCOUNT_SENDADDCREDITSNUDGEEMAIL,
            methods::FEEDBACK_UPLOAD,
            methods::COMMAND_EXEC,
            methods::COMMAND_EXEC_WRITE,
            methods::COMMAND_EXEC_TERMINATE,
            methods::COMMAND_EXEC_RESIZE,
            methods::CONFIG_READ,
            methods::EXTERNALAGENTCONFIG_DETECT,
            methods::EXTERNALAGENTCONFIG_IMPORT,
            methods::CONFIG_VALUE_WRITE,
            methods::CONFIG_BATCHWRITE,
            methods::CONFIGREQUIREMENTS_READ,
            methods::ACCOUNT_READ,
            methods::FUZZYFILESEARCH,
        ]
        .into_iter()
        .collect()
    }

    /// Hand-rolled wire samples for server-notification params. The map's key
    /// is the JSON-RPC `method`; the value is what `serde_json::to_value` on
    /// the corresponding typed struct produces.
    ///
    /// **Seed set only** — grow this as we add typed variants. Methods absent
    /// from this map show up as ◐ ("modeled, no sample") in the report.
    pub(super) fn server_notification_samples() -> BTreeMap<&'static str, Value> {
        let mut m: BTreeMap<&'static str, Value> = BTreeMap::new();

        // Seed sample: the wire shape of `ErrorNotification` is just `{message}`
        // and is the easiest first drift check.
        m.insert(
            methods::ERROR,
            serde_json::to_value(ErrorNotification {
                error: "something blew up".into(),
                thread_id: Some("th_abc".into()),
                turn_id: Some("tn_xyz".into()),
                will_retry: false,
            })
            .expect("ErrorNotification serializes"),
        );

        // Grow this map for every notification you'd like drift-protected.
        // Pattern:
        //
        //     m.insert(
        //         methods::THREAD_STARTED,
        //         serde_json::to_value(ThreadStartedNotification { thread: ThreadInfo { ... } })
        //             .expect("ThreadStartedNotification serializes"),
        //     );

        m
    }

    /// Hand-rolled wire samples for client-request params.
    pub(super) fn client_request_samples() -> BTreeMap<&'static str, Value> {
        // Seed: none yet — grow this for the request side.
        BTreeMap::new()
    }
}