openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! The wire-format registry — the one place a provider protocol is named.
//!
//! The boundary forwards for more than one agent, and the agents do not share a
//! protocol: Claude Code speaks the Anthropic Messages API, Codex speaks the
//! OpenAI Responses API. Everything that differs between them — the upstream to
//! forward to, the provider name on the economics event, whether a decoder
//! exists, whether a transform may run, how a request names its own session,
//! where its user turns and tool results sit — is answered *here*, by the
//! format, so that shared decision code in [`super::proxy`] never has to name
//! one.
//!
//! **The format is resolved from the request ROUTE, never from agent identity**
//! (PRD D-7). A multi-provider agent picks its protocol from its own
//! configuration at session time, so no fixed agent→protocol mapping exists to
//! key on. [`WireFormat::resolve`] reads method + path off the request head
//! *before* the body is touched, which is why the registry costs no new parse
//! and cannot move TTFT.
//!
//! ## `Unknown` is the normal answer, not an error
//!
//! Every route the boundary does not capture — `GET /v1/models`,
//! `POST /v1/messages/count_tokens`, the batch endpoints — resolves to
//! [`WireFormat::Unknown`] and is forwarded opaquely, exactly as before this
//! registry existed: no permit, no materialization, and **no economics event**.
//! `Unknown` therefore answers `ANTHROPIC_BASE` for [`WireFormat::default_upstream`]:
//! that is today's forwarding target for those routes, and making it fail would
//! turn an opaque forward into a synthetic 502.
//!
//! One base for every uncaptured route was right while one agent was wired
//! here, and stopped being right when Codex arrived: `GET /v1/models` is
//! uncaptured, Codex issues it every session, and Anthropic is the wrong place
//! to send it. [`WireFormat::resolve_upstream`] is the narrow answer — it moves
//! an uncaptured route to the OpenAI side ONLY on a marker Claude Code never
//! sends, and leaves what it captures untouched.
//!
//! ## Auth mode is not a wire format
//!
//! Codex authenticates two ways — a ChatGPT subscription and a platform API
//! key — and both speak the Responses API on the same route. Same format, two
//! origins, and the credential valid at one is refused by the other. That
//! distinction lives in [`AuthMode`], resolved per request from the agent's own
//! headers, precisely so it never becomes a third [`WireFormat`] variant.

use axum::http::{request::Parts, HeaderMap, Method};

/// The OpenAI first-party base URL, the built-in upstream for
/// [`WireFormat::OpenAiResponses`].
///
/// A HOST, not a path — `Url::join` replaces the base's path with the incoming
/// absolute path, so a `/v1` suffix here would be discarded rather than
/// prefixed. See [`WireFormat::default_upstream`].
pub const OPENAI_BASE: &str = "https://api.openai.com";

/// The backend Codex speaks to on a **ChatGPT subscription**, and the built-in
/// upstream for [`WireFormat::OpenAiResponses`] when the request's own
/// credential names it.
///
/// A host **plus a path**, unlike the other two bases, and that is the point:
/// the subscription endpoint lives under `/backend-api/codex`. See
/// `proxy::join_upstream` for how a based upstream survives the forward — a
/// plain `Url::join` drops the prefix and posts to `chatgpt.com/v1/responses`,
/// which does not exist.
pub const CHATGPT_BASE: &str = "https://chatgpt.com/backend-api/codex";

/// The header Codex sends on every request made with a ChatGPT-subscription
/// credential, naming the account the plan belongs to.
const CHATGPT_ACCOUNT_HEADER: &str = "chatgpt-account-id";

/// Codex's own product tag, sent on every request it makes.
const ORIGINATOR_HEADER: &str = "originator";

/// What [`ORIGINATOR_HEADER`] starts with on every Codex surface —
/// `codex_exec`, `codex_cli_rs`, `codex_vscode`, `codex-tui`.
const CODEX_ORIGINATOR_PREFIX: &str = "codex";

/// Which OpenAI backend a request's own credential is addressed to.
///
/// **Not a wire format.** Codex authenticates two ways and both speak the
/// Responses API — same route, same body, same SSE frames. It is one format at
/// two origins, so it is not a third [`WireFormat`] variant and must not
/// become one. A ChatGPT-plan token carries `api.connectors.*` scopes only and
/// `api.openai.com` answers it with a 403; a platform key is not what the
/// ChatGPT backend accepts. One header separates them, and the agent sends it
/// unprompted.
///
/// Read from the request head, never from agent identity and never from
/// anything this install decided at wiring time: a developer can `codex login`
/// between two turns and change modes without restarting anything we own, so a
/// value resolved once would be stale by the next request.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMode {
    /// The request carries [`CHATGPT_ACCOUNT_HEADER`] — a subscription
    /// credential, valid only against [`CHATGPT_BASE`].
    ChatGptSubscription,
    /// Everything else: a platform API key, an Anthropic credential, or no
    /// credential at all. The default, and today's behaviour.
    Platform,
}

impl AuthMode {
    /// Resolved from the request's headers — one `contains_key` on the hot
    /// path, before the body is touched.
    pub fn resolve(headers: &HeaderMap) -> Self {
        if headers.contains_key(CHATGPT_ACCOUNT_HEADER) {
            Self::ChatGptSubscription
        } else {
            Self::Platform
        }
    }
}

/// True when the request carries a marker only Codex sends.
///
/// [`CHATGPT_ACCOUNT_HEADER`] names the ChatGPT backend outright.
/// [`ORIGINATOR_HEADER`] is Codex's product tag and rides on every request it
/// makes — the captured `POST /v1/responses` and the uncaptured
/// `GET /v1/models` alike.
///
/// Deliberately **not** the credential's shape. Claude Code on a subscription
/// sends `Authorization: Bearer …` exactly as Codex on a platform key does, so
/// keying on "carries a bearer token" would send Claude's own uncaptured
/// routes to OpenAI — the same cross-provider misroute this exists to fix,
/// pointed the other way.
fn is_codex_request(headers: &HeaderMap) -> bool {
    headers.contains_key(CHATGPT_ACCOUNT_HEADER)
        || headers
            .get(ORIGINATOR_HEADER)
            .and_then(|v| v.to_str().ok())
            .is_some_and(|v| v.starts_with(CODEX_ORIGINATOR_PREFIX))
}

/// Longest session id we will believe. Claude Code's is a 36-char UUID; the cap
/// is generous headroom that still refuses to turn an arbitrary blob into a
/// session label.
const MAX_DECLARED_SESSION_ID: usize = 128;

/// The provider protocol a request speaks, resolved from its route.
///
/// `#[non_exhaustive]`: PRD D-8 names four formats (`anthropic-messages`,
/// `openai-chat-completions`, `openai-responses`, `google-generate-content`)
/// and this unit builds two. The attribute is a downstream-semver affordance
/// only; every intra-crate `match` still breaks usefully when the third lands.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireFormat {
    /// Anthropic Messages API — `POST /v1/messages`. Claude Code.
    AnthropicMessages,
    /// OpenAI Responses API — `POST /v1/responses`. Codex CLI.
    OpenAiResponses,
    /// Every route we do not capture. Forwarded opaquely, never measured.
    Unknown,
}

impl WireFormat {
    /// Every variant, in one place.
    ///
    /// Independent sites must walk the full set — the daemon building the
    /// resolved upstream map, `BoundaryState`'s fan-out of a single URL across
    /// every key, and `boundary status` rendering the object. Three
    /// hand-written lists on a `#[non_exhaustive]` enum is how they drift; this
    /// is the one list.
    pub const ALL: [WireFormat; 3] = [
        Self::AnthropicMessages,
        Self::OpenAiResponses,
        Self::Unknown,
    ];

    /// Resolved from the request ROUTE. NEVER from agent identity (PRD D-7).
    ///
    /// This reads `parts` only — method and path — and is called BEFORE the
    /// body is touched, which is why the registry costs no new parse and cannot
    /// move TTFT. It is also the only key that stays correct: a multi-provider
    /// agent resolves its format from its own configuration at session time, so
    /// no fixed agent→protocol mapping exists to key on.
    pub fn resolve(parts: &Parts) -> Self {
        if parts.method != Method::POST {
            return Self::Unknown;
        }
        match parts.uri.path() {
            "/v1/messages" => Self::AnthropicMessages,
            "/v1/responses" => Self::OpenAiResponses,
            _ => Self::Unknown,
        }
    }

    /// The format whose UPSTREAM this request follows.
    ///
    /// [`resolve`](Self::resolve) answers what a request *speaks*, and that is
    /// the only thing capture, measurement and the envelope may key on. This
    /// answers the narrower question of where it must be **sent**, and differs
    /// for exactly one case: an uncaptured route that is provably Codex's.
    ///
    /// `Unknown`'s built-in upstream is Anthropic's. That was right while
    /// Claude Code was the only agent wired here and became wrong the moment
    /// Codex was — `GET /v1/models` is uncaptured and Codex issues it every
    /// session, so today every Codex install sends it, bearing the caller's
    /// OpenAI credential, to `api.anthropic.com`. That is not a graceful
    /// degradation; it is a cross-provider misroute.
    ///
    /// Promotion needs a marker only Codex sends ([`is_codex_request`]), which
    /// Claude Code emits under neither of its own auth modes. Anything else
    /// keeps today's answer exactly, so a route we cannot attribute still
    /// forwards opaquely instead of becoming a synthetic 502.
    ///
    /// **This never widens what is captured.** A promoted route resolves
    /// `Unknown` from [`resolve`](Self::resolve) still, so it takes no permit,
    /// materializes nothing and emits no economics event.
    pub fn resolve_upstream(parts: &Parts) -> Self {
        match Self::resolve(parts) {
            Self::Unknown if is_codex_request(&parts.headers) => Self::OpenAiResponses,
            resolved => resolved,
        }
    }

    /// True when this format is one we capture.
    pub fn is_captured(self) -> bool {
        !matches!(self, Self::Unknown)
    }

    /// The `wireformat` envelope attribute value, and the map key in
    /// `[boundary.upstream]`. Hyphenated, matching PRD D-8's names verbatim.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AnthropicMessages => "anthropic-messages",
            Self::OpenAiResponses => "openai-responses",
            Self::Unknown => "unknown",
        }
    }

    /// `gen_ai.provider.name`. Resolved from the FORMAT, not the upstream host:
    /// a customer pointing us at a corporate gateway is still speaking the
    /// provider's protocol, and reporting the gateway's hostname as the
    /// provider would be junk.
    pub fn provider(self) -> &'static str {
        match self {
            Self::AnthropicMessages => "anthropic",
            Self::OpenAiResponses => "openai",
            Self::Unknown => "unknown",
        }
    }

    /// The built-in upstream when `[boundary.upstream]` names none for this
    /// format. HOSTS, NOT PATHS — `Url::join` replaces the base's path.
    ///
    /// `Unknown` deliberately answers [`super::ANTHROPIC_BASE`]: that is the
    /// single base every unrecognised route is forwarded to today, and an
    /// unroutable `Unknown` would turn an opaque forward into a 502.
    pub fn default_upstream(self) -> &'static str {
        match self {
            Self::AnthropicMessages => super::ANTHROPIC_BASE,
            Self::OpenAiResponses => OPENAI_BASE,
            Self::Unknown => super::ANTHROPIC_BASE,
        }
    }

    /// True when this build can decode the format's response stream into token
    /// counts.
    ///
    /// A route can be *recognised* without being *decodable*. Measurement asks
    /// this rather than asking the route, so a captured but undecoded turn
    /// would report `unknown_wire_format` — the honest gap — instead of
    /// `stream_interrupted`, which describes the wrong failure.
    ///
    /// **Both captured formats are decoded today**, so no captured route
    /// currently answers `false` here: `/v1/responses` gained its decoder in
    /// the same commit that added this arm, and shipping the decoder without
    /// the arm would label every correct Codex measurement `unknown_wire_format`
    /// — a measurement that happened, reported as one that did not. The
    /// predicate stays because it is what a *third* format would arrive
    /// undecoded through.
    pub fn has_decoder(self) -> bool {
        matches!(self, Self::AnthropicMessages | Self::OpenAiResponses)
    }

    /// True when the request-transform step may run for this format.
    ///
    /// The bundle's request rules are Anthropic-authored and read an Anthropic
    /// body shape, so they must not be evaluated against another provider's
    /// request. `[boundary] transforms_act = true` already exists in the field,
    /// so default-off is not sufficient protection — the gate is on the format.
    ///
    /// The predicate lives here, with the format, so shared proxy code never
    /// names a format to decide with: adding a third format must not mean
    /// editing shared decision code.
    pub fn transforms_apply(self) -> bool {
        matches!(self, Self::AnthropicMessages)
    }
}

/// The session id the request declares about itself, or `None`.
///
/// Per format, because naming your own session inside the request body is an
/// agent's own convention and not a property of HTTP:
///
/// - **`AnthropicMessages`** — Claude Code sets the Messages API's
///   `metadata.user_id` to a JSON **string** holding `device_id`,
///   `account_uuid` and `session_id`, and that `session_id` is byte-for-byte
///   the one the hook reports as its subject. Reading it turns attribution from
///   an inference into a fact.
/// - **`OpenAiResponses`** — Codex sets `client_metadata.session_id` to a plain
///   string, and that string is byte-for-byte the id the hook reports as its
///   subject. This arm read `None` until the value was checked rather than
///   assumed: a real turn captured off codex-cli 0.150.1 on 2026-09-06 carried
///   the same id in four places — the `session-id` header, `thread-id`,
///   `client_metadata.session_id` and `prompt_cache_key` — all equal to the
///   `session_meta.session_id` that session wrote to its own rollout, which is
///   the same `Session::session_id()` the hook payload carries. `session_id` is
///   the one of the four named for what it *is*: `prompt_cache_key` is named
///   for the cache and is free to become a prefix digest, and the headers are
///   unreachable from a body-only signature.
/// - **`Unknown`** — `None`; an uncaptured route never reaches a parsed body.
///
/// **Deliberately total and silent.** The field is an agent's internal
/// convention, not a documented contract: it can change shape, drop the key, or
/// hold a plain opaque id for a different agent. Every one of those returns
/// `None` and the cascade carries on exactly as it did — the selector can stop
/// working without anything breaking, which is the only safe way to depend on
/// someone else's undocumented format.
///
/// We read `session_id` and nothing else. Both blobs carry more — Claude Code's
/// `account_uuid` and `device_id`, Codex's `installation_id`, `thread_id` and
/// `turn_id`; those are the caller's identity or a narrower scope than a
/// session, we have no use for either, and not extracting them is cheaper to
/// reason about than extracting and discarding them.
pub fn declared_session_id(fmt: WireFormat, body: &serde_json::Value) -> Option<String> {
    match fmt {
        WireFormat::AnthropicMessages => anthropic_declared_session_id(body),
        WireFormat::OpenAiResponses => codex_declared_session_id(body),
        WireFormat::Unknown => None,
    }
}

/// Accept an id only if it can be a session label without qualification.
///
/// Shared by both arms so one format cannot end up with a laxer rule than the
/// other: a session id becomes a label in the economics record and a key in the
/// registry, and neither wants a blank, an unbounded caller-controlled string,
/// or something carrying control characters.
fn usable_session_id(sid: &str) -> Option<String> {
    let sid = sid.trim();
    if sid.is_empty() || sid.len() > MAX_DECLARED_SESSION_ID {
        return None;
    }
    if sid.chars().any(char::is_control) {
        return None;
    }
    Some(sid.to_string())
}

/// The Messages-API convention, moved verbatim from `proxy.rs`.
fn anthropic_declared_session_id(body: &serde_json::Value) -> Option<String> {
    let raw = body.get("metadata")?.get("user_id")?.as_str()?;
    // Bound the parse: `user_id` is caller-controlled, and a megabyte of JSON
    // here would be work done on every request for no benefit.
    if raw.len() > 4096 {
        return None;
    }
    let parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
    usable_session_id(parsed.get("session_id")?.as_str()?)
}

/// The Responses convention.
///
/// A plain nested string, not JSON inside a string, so there is no inner parse
/// to bound — the outer body parse already happened and `as_str` cannot cost
/// more than the field is long.
fn codex_declared_session_id(body: &serde_json::Value) -> Option<String> {
    usable_session_id(body.get("client_metadata")?.get("session_id")?.as_str()?)
}

/// The conversation-shaped parts of a request body the attribution cascade reads.
///
/// The cascade's two content selectors ask the same two questions of every
/// request — *which user turns is this* and *which tool results is it carrying
/// back* — and the two formats answer them in different shapes. The Messages API
/// keeps its turns under `messages` and nests each `tool_result` inside the user
/// turn that answers it; the Responses API keeps its items under `input` and
/// lists every tool output as a **top-level item of its own**. Naming that
/// difference here is what keeps [`super::proxy`]'s signal derivation free of it:
/// the shared code hashes, dedupes and bounds, and the format supplies the shape.
pub struct ConversationView<'a> {
    /// The user turns, oldest first. Each is read through its `content`, which is
    /// either a bare string or an array of typed blocks.
    pub user_turns: Vec<&'a serde_json::Value>,
    /// The `type` a text block carries inside `content` for this format:
    /// `"text"` on the Messages API, `"input_text"` on the Responses API.
    pub text_block_type: &'static str,
    /// The tool-call ids this request is carrying back, newest first.
    pub tool_result_ids: Vec<String>,
}

/// Read a request body into the shared [`ConversationView`], or `None` when this
/// format has no conversation to read.
///
/// Per format, for the same reason [`declared_session_id`] is: the shapes below
/// are each one agent's protocol, and a body that does not match the shape its
/// route promised returns `None` rather than half a view.
pub fn conversation_view(
    fmt: WireFormat,
    body: &serde_json::Value,
) -> Option<ConversationView<'_>> {
    match fmt {
        WireFormat::AnthropicMessages => anthropic_conversation_view(body),
        WireFormat::OpenAiResponses => responses_conversation_view(body),
        // An uncaptured route never reaches a parsed body.
        WireFormat::Unknown => None,
    }
}

/// The Messages-API shape, moved verbatim from `proxy.rs`.
fn anthropic_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let messages = body.get("messages")?.as_array()?;
    let user_turns: Vec<&serde_json::Value> = messages
        .iter()
        .filter(|m| m.get("role").and_then(|r| r.as_str()) == Some("user"))
        .collect();

    // The ids this turn is answering. A `tool_result` block echoes the
    // `tool_use_id` of the call the agent just ran, which is exactly what the
    // hook recorded for the session that ran it. Only the LAST user turn's
    // blocks: an earlier turn's results belong to a turn already answered.
    let mut tool_result_ids = Vec::new();
    if let Some(blocks) = user_turns
        .last()
        .and_then(|last| last.get("content"))
        .and_then(|c| c.as_array())
    {
        for b in blocks {
            if b.get("type").and_then(|t| t.as_str()) != Some("tool_result") {
                continue;
            }
            if let Some(id) = b.get("tool_use_id").and_then(|v| v.as_str()) {
                if !id.is_empty() {
                    tool_result_ids.push(id.to_string());
                }
            }
        }
    }

    Some(ConversationView {
        user_turns,
        text_block_type: "text",
        tool_result_ids,
    })
}

/// The Responses-API shape.
///
/// Verified against codex-cli 0.150.1: `codex debug prompt-input <prompt>`
/// renders the typed prompt as its own `message` item, `role: "user"`, carrying a
/// single `input_text` block holding the prompt **verbatim** — byte-for-byte the
/// string the `UserPromptSubmit` hook reports as `prompt`, which is what makes
/// the prompt join an exact match rather than a resemblance.
///
/// The `input` array's bare-string form (`"input": "hello"`) is deliberately not
/// read. It is an API affordance no agent we forward for uses — Codex always
/// serializes the item array — and a branch for a shape we have never seen would
/// be paid on every request to serve a caller that does not exist.
fn responses_conversation_view(body: &serde_json::Value) -> Option<ConversationView<'_>> {
    let items = body.get("input")?.as_array()?;

    // `type` is absent on a plain `{role, content}` item and `"message"` on a
    // typed one; both are turns. The array also carries `developer` items —
    // Codex's instruction preamble — and those are the agent's own text, byte
    // identical across every session it starts, so hashing them would offer a
    // candidate that matches sessions having nothing to do with this request.
    let user_turns: Vec<&serde_json::Value> = items
        .iter()
        .filter(|m| {
            matches!(
                m.get("type").and_then(|t| t.as_str()),
                None | Some("message")
            ) && m.get("role").and_then(|r| r.as_str()) == Some("user")
        })
        .collect();

    // Every Responses item that carries a tool-call id names it `call_id` —
    // `function_call_output`, `custom_tool_call_output`, `mcp_tool_call_output`
    // and `tool_search_output`, plus the `*_call` items each of those answers.
    // Keying on the FIELD rather than on a list of type names is deliberate:
    // Codex has added output variants more than once, and a name list would stop
    // matching the day it adds the next one — silently, since a selector that
    // never fires degrades to the fallback instead of failing.
    //
    // Walked from the END and stopped at the registry's own retention bound. The
    // registry keeps that many ids per session, so a request's newest ids are the
    // only ones with anything left to match, and an `input` carrying a whole
    // conversation's history is not walked past the point of usefulness.
    let mut tool_result_ids: Vec<String> = Vec::new();
    for item in items.iter().rev() {
        if tool_result_ids.len() >= super::session::RECENT_TOOL_USE_IDS {
            break;
        }
        let Some(id) = item.get("call_id").and_then(|v| v.as_str()) else {
            continue;
        };
        // A call and the output answering it repeat one id; two of the eight
        // slots for one tool call would halve what the join can reach.
        if id.is_empty() || tool_result_ids.iter().any(|k| k == id) {
            continue;
        }
        tool_result_ids.push(id.to_string());
    }

    Some(ConversationView {
        user_turns,
        text_block_type: "input_text",
        tool_result_ids,
    })
}

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

    fn parts_of(method: Method, uri: &str) -> Parts {
        let req = Request::builder()
            .method(method)
            .uri(uri)
            .body(())
            .expect("build request");
        req.into_parts().0
    }

    /// Same, with headers — `(name, value)` pairs applied in order.
    fn parts_with(method: Method, uri: &str, headers: &[(&str, &str)]) -> Parts {
        let mut req = Request::builder().method(method).uri(uri);
        for (k, v) in headers {
            req = req.header(*k, *v);
        }
        req.body(()).expect("build request").into_parts().0
    }

    #[test]
    fn auth_mode_reads_the_account_header_and_nothing_else() {
        // The measured discriminator: ChatGPT-plan Codex sends this header on
        // every request, a platform key never does.
        assert_eq!(
            AuthMode::resolve(
                &parts_with(
                    Method::POST,
                    "/v1/responses",
                    &[("chatgpt-account-id", "ef1a0c98-317c-4a79-9ed0-9e75361027ed")],
                )
                .headers
            ),
            AuthMode::ChatGptSubscription
        );
        // A bearer credential alone is NOT the signal — Claude Code on a
        // subscription sends one too, and routing on it would send Anthropic
        // traffic to OpenAI.
        assert_eq!(
            AuthMode::resolve(
                &parts_with(
                    Method::POST,
                    "/v1/responses",
                    &[("authorization", "Bearer sk-proj-abc")],
                )
                .headers
            ),
            AuthMode::Platform
        );
        assert_eq!(
            AuthMode::resolve(&parts_of(Method::POST, "/v1/responses").headers),
            AuthMode::Platform
        );
    }

    #[test]
    fn an_uncaptured_codex_route_follows_codex_upstream() {
        // `GET /v1/models` is uncaptured and Codex issues it every session.
        // Before promotion it resolved `Unknown` and left for Anthropic.
        let models = parts_with(
            Method::GET,
            "/v1/models?client_version=0.150.1",
            &[("originator", "codex_exec")],
        );
        assert_eq!(WireFormat::resolve(&models), WireFormat::Unknown);
        assert_eq!(
            WireFormat::resolve_upstream(&models),
            WireFormat::OpenAiResponses
        );

        // The account header promotes on its own.
        let with_account = parts_with(
            Method::GET,
            "/v1/models",
            &[("chatgpt-account-id", "ef1a0c98")],
        );
        assert_eq!(
            WireFormat::resolve_upstream(&with_account),
            WireFormat::OpenAiResponses
        );
    }

    #[test]
    fn an_unmarked_uncaptured_route_still_resolves_unknown() {
        // Claude Code's own uncaptured routes carry neither marker under
        // either of its auth modes, so they keep today's destination.
        for headers in [
            &[][..],
            &[("authorization", "Bearer sk-ant-oat01-abc")][..],
            &[("x-api-key", "sk-ant-api03-abc")][..],
            // An originator that merely CONTAINS the tag is not Codex's.
            &[("originator", "not-codex")][..],
        ] {
            let parts = parts_with(Method::GET, "/v1/models", headers);
            assert_eq!(
                WireFormat::resolve_upstream(&parts),
                WireFormat::Unknown,
                "unmarked route promoted with headers {headers:?}"
            );
        }
    }

    #[test]
    fn promotion_never_widens_what_is_captured() {
        // `resolve_upstream` answers WHERE, never WHAT: a promoted route must
        // still be uncaptured, or it would take a permit and emit an event.
        let promoted = parts_with(Method::GET, "/v1/models", &[("originator", "codex_cli_rs")]);
        assert!(!WireFormat::resolve(&promoted).is_captured());
        // And a captured route is returned untouched by promotion.
        let turn = parts_with(
            Method::POST,
            "/v1/responses",
            &[("originator", "codex_exec")],
        );
        assert_eq!(
            WireFormat::resolve_upstream(&turn),
            WireFormat::resolve(&turn)
        );
    }

    #[test]
    fn resolve_keys_on_route_and_method_only() {
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages")),
            WireFormat::AnthropicMessages
        );
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/responses")),
            WireFormat::OpenAiResponses
        );
        // The method is half the key: a GET on a captured path is not a turn.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::GET, "/v1/responses")),
            WireFormat::Unknown
        );
        // A prefix of a captured path is a different route, not that route.
        assert_eq!(
            WireFormat::resolve(&parts_of(Method::POST, "/v1/messages/count_tokens")),
            WireFormat::Unknown
        );
    }

    #[test]
    fn all_names_every_variant_exactly_once() {
        // The single list the resolved-upstream map, the state's fan-out and
        // `boundary status` all walk. A variant missing from it is a silently
        // unrouted format, not a compile error — so the names are pinned.
        let names: Vec<_> = WireFormat::ALL.iter().map(|f| f.as_str()).collect();
        assert_eq!(
            names,
            vec!["anthropic-messages", "openai-responses", "unknown"]
        );
    }

    #[test]
    fn unknown_forwards_to_the_anthropic_base_as_it_does_today() {
        // Not an improvement target: failing here turns today's opaque forward
        // for `GET /v1/models` into a synthetic 502.
        assert_eq!(
            WireFormat::Unknown.default_upstream(),
            crate::boundary::ANTHROPIC_BASE
        );
        assert_eq!(WireFormat::OpenAiResponses.default_upstream(), OPENAI_BASE);
    }

    /// A Responses turn in the shape codex-cli 0.150.1 actually sends: a
    /// `developer` preamble, the `<environment_context>` block Codex prepends as
    /// a user turn of its own, the typed prompt verbatim, and the call/output
    /// pair for the tool it just ran. Captured from `codex debug prompt-input`
    /// and from a session rollout on 2026-09-06.
    fn codex_turn() -> serde_json::Value {
        serde_json::json!({
            "model": "gpt-5-codex",
            "input": [
                {"type": "message", "id": "msg_1", "role": "developer",
                 "content": [{"type": "input_text", "text": "<skills_instructions>…"}]},
                {"type": "message", "id": "msg_2", "role": "user",
                 "content": [{"type": "input_text", "text": "<environment_context>\n  <cwd>/repo</cwd>\n</environment_context>"}]},
                {"type": "message", "id": "msg_3", "role": "user",
                 "content": [{"type": "input_text", "text": "build the parser"}]},
                {"type": "function_call", "id": "fc_1", "call_id": "call_aaa",
                 "name": "shell", "arguments": "{}"},
                {"type": "function_call_output", "id": "fco_1", "call_id": "call_aaa",
                 "output": "ok"}
            ]
        })
    }

    #[test]
    fn the_responses_view_reads_input_and_leaves_the_preamble_alone() {
        let body = codex_turn();
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");

        // Two user turns, in order — and NOT the `developer` item. That item is
        // Codex's own instruction preamble: byte identical across every session
        // it starts, so hashing it would offer a candidate matching sessions that
        // have nothing to do with this request.
        assert_eq!(view.user_turns.len(), 2);
        assert_eq!(
            view.user_turns[1]["content"][0]["text"], "build the parser",
            "the typed prompt is the last user turn"
        );
        assert_eq!(view.text_block_type, "input_text");
        assert_eq!(view.tool_result_ids, vec!["call_aaa".to_string()]);
    }

    #[test]
    fn responses_call_ids_are_newest_first_deduped_and_bounded() {
        // A long conversation carries its whole history in `input`. The registry
        // keeps `RECENT_TOOL_USE_IDS` per session, so anything older has nothing
        // left to match and walking to it is work for no answer.
        let mut items = Vec::new();
        for i in 0..40 {
            items.push(serde_json::json!({
                "type": "function_call", "call_id": format!("call_{i:02}"), "name": "shell"
            }));
            // The call and the output answering it repeat one id; spending two
            // slots on one tool call would halve what the join can reach.
            items.push(serde_json::json!({
                "type": "function_call_output", "call_id": format!("call_{i:02}"), "output": "ok"
            }));
        }
        let body = serde_json::json!({ "input": items });
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");

        assert_eq!(
            view.tool_result_ids.len(),
            super::super::session::RECENT_TOOL_USE_IDS
        );
        assert_eq!(
            view.tool_result_ids[0], "call_39",
            "newest first — the request's newest ids are the ones still in the registry"
        );
        assert_eq!(view.tool_result_ids[7], "call_32");
    }

    #[test]
    fn every_responses_item_that_carries_an_id_names_it_call_id() {
        // Keyed on the FIELD, not on a list of type names: Codex has added output
        // variants more than once, and a name list would stop matching the day it
        // adds the next — silently, since a selector that never fires degrades to
        // the fallback rather than failing.
        let body = serde_json::json!({"input": [
            {"type": "custom_tool_call_output", "call_id": "call_custom", "output": "ok"},
            {"type": "mcp_tool_call_output", "call_id": "call_mcp", "output": {}},
            {"type": "tool_search_output", "call_id": "call_search", "status": "ok"},
            {"type": "a_variant_that_does_not_exist_yet", "call_id": "call_future"}
        ]});
        let view = conversation_view(WireFormat::OpenAiResponses, &body).expect("a view");
        assert_eq!(
            view.tool_result_ids,
            vec!["call_future", "call_search", "call_mcp", "call_custom"]
        );
    }

    #[test]
    fn each_format_reads_only_its_own_body_shape() {
        // The route picked the format; a body that does not match the shape that
        // route promised yields nothing rather than half a view. `input` read as
        // Messages and `messages` read as Responses are both None — which is what
        // keeps a mis-resolved route from inventing signals.
        let codex = codex_turn();
        let claude = serde_json::json!({"messages": [
            {"role": "user", "content": [{"type": "text", "text": "build the parser"}]}
        ]});

        assert!(conversation_view(WireFormat::AnthropicMessages, &codex).is_none());
        assert!(conversation_view(WireFormat::OpenAiResponses, &claude).is_none());
        // And an uncaptured route never reaches a parsed body at all.
        assert!(conversation_view(WireFormat::Unknown, &codex).is_none());
        assert!(conversation_view(WireFormat::Unknown, &claude).is_none());
    }

    #[test]
    fn the_messages_view_is_unchanged_by_the_move() {
        // The shape moved out of `proxy.rs`; its answers did not. Tool-result ids
        // come from the LAST user turn only — an earlier turn's results belong to
        // a turn already answered.
        let body = serde_json::json!({"messages": [
            {"role": "user", "content": [{"type": "text", "text": "build the parser"}]},
            {"role": "assistant", "content": [
                {"type": "tool_use", "id": "toolu_old", "name": "Bash", "input": {}}
            ]},
            {"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "toolu_old", "content": "ok"}
            ]},
            {"role": "assistant", "content": [
                {"type": "tool_use", "id": "toolu_new", "name": "Bash", "input": {}}
            ]},
            {"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "toolu_new", "content": "ok"},
                {"type": "text", "text": "and now the lexer"}
            ]}
        ]});
        let view = conversation_view(WireFormat::AnthropicMessages, &body).expect("a view");
        assert_eq!(view.user_turns.len(), 3);
        assert_eq!(view.text_block_type, "text");
        assert_eq!(view.tool_result_ids, vec!["toolu_new".to_string()]);
    }

    #[test]
    fn each_format_reads_only_its_own_declaration() {
        // Naming your own session in the body is a convention per agent, not a
        // property of HTTP — so each shape is read by exactly one format, and
        // reading a body under the other format yields nothing.
        let claude = serde_json::json!({
            "metadata": {"user_id": r#"{"session_id":"5c7d9833"}"#}
        });
        let codex = serde_json::json!({
            "client_metadata": {
                "session_id": "01a07677-988f-7901-af48-225c7386aabc",
                "thread_id": "01a07677-988f-7901-af48-225c7386aabc",
                "turn_id": "01a07677-7334-74a2-be87-bdd0bbe8fb77",
                "x-codex-installation-id": "5532dc79-4512-4bae-ab73-0dd3e814d329"
            }
        });

        assert_eq!(
            declared_session_id(WireFormat::AnthropicMessages, &claude).as_deref(),
            Some("5c7d9833")
        );
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &claude),
            None
        );

        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &codex).as_deref(),
            Some("01a07677-988f-7901-af48-225c7386aabc")
        );
        assert_eq!(
            declared_session_id(WireFormat::AnthropicMessages, &codex),
            None
        );

        // An uncaptured route never reaches a parsed body.
        assert_eq!(declared_session_id(WireFormat::Unknown, &claude), None);
        assert_eq!(declared_session_id(WireFormat::Unknown, &codex), None);
    }

    #[test]
    fn codex_reads_session_id_and_not_a_neighbouring_field() {
        // The same object carries `thread_id`, `turn_id` and an installation id.
        // `turn_id` is a NARROWER scope than a session — attributing a turn id as
        // a session would split one session into a new label every turn, which
        // looks like working attribution and is not.
        let body = serde_json::json!({
            "client_metadata": {"session_id": "sess-real", "turn_id": "turn-other",
                                "thread_id": "thread-other"}
        });
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &body).as_deref(),
            Some("sess-real")
        );

        // `prompt_cache_key` holds the same value today and is deliberately not
        // read: it is named for the cache, and is free to become a prefix digest
        // without Codex changing anything about its sessions.
        let cache_key_only = serde_json::json!({
            "prompt_cache_key": "01a07677-988f-7901-af48-225c7386aabc"
        });
        assert_eq!(
            declared_session_id(WireFormat::OpenAiResponses, &cache_key_only),
            None
        );
    }

    #[test]
    fn a_codex_declaration_that_is_not_usable_is_silently_ignored() {
        // Same doctrine as the Messages arm: the field is another program's
        // internal convention, so every malformed shape degrades to "no declared
        // id" and the cascade carries on — never an error, never a bogus label.
        let cases = [
            serde_json::json!({}),                      // no client_metadata
            serde_json::json!({"client_metadata": {}}), // no session_id
            serde_json::json!({"client_metadata": {"session_id": 42}}), // not a string
            serde_json::json!({"client_metadata": {"session_id": ""}}), // blank
            serde_json::json!({"client_metadata": {"session_id": "   "}}), // whitespace only
            serde_json::json!({"client_metadata": {"session_id": "a\u{0000}b"}}), // control char
            serde_json::json!({"client_metadata": {"session_id": "x".repeat(500)}}), // over the cap
        ];
        for body in cases {
            assert_eq!(
                declared_session_id(WireFormat::OpenAiResponses, &body),
                None,
                "must not trust {body}"
            );
        }
    }
}