Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: C3 — /v1/responses Rust HTTP handler + per-item-type passthrough
chopratejas57c3e38cb3cc
diff --git a/crates/headroom-core/src/transforms/live_zone.rs b/crates/headroom-core/src/transforms/live_zone.rsindex 15abfdf6f..4131a15e8 100644--- a/crates/headroom-core/src/transforms/live_zone.rs+++ b/crates/headroom-core/src/transforms/live_zone.rs@@ -1972,3 +1972,614 @@ mod openai_chat_tests {assert_eq!(user_block.message_index, 2);}}++// ─── OpenAI Responses live-zone dispatcher (Phase C PR-C3) ────────────+//+// Sibling of `compress_openai_chat_live_zone`. The Responses API+// (`/v1/responses`) keys the request under `input` rather than+// `messages`, and the array carries explicitly-typed items (not+// role-tagged messages).+//+// Live zone, per spec PR-C3 (`REALIGNMENT/05-phase-C-rust-proxy.md`):+//+// - latest `function_call_output.output`+// - latest `local_shell_call_output.output`+// - latest `apply_patch_call_output.output`+// - latest `message` (text content) OR `user`-role message+//+// Earlier `*_output` items are FROZEN (cached prefix) — never touched.+// All other item types (`reasoning`, `compaction`, `mcp_*`,+// `computer_*`, `web_search_call`, `file_search_call`,+// `code_interpreter_call`, `image_generation_call`, `tool_search_call`,+// `custom_tool_call`, `function_call`, `local_shell_call`,+// `apply_patch_call`, future-unknown) are passthrough — the dispatcher+// records a `NoCompressionApplied` outcome but never plans a+// replacement.+//+// Output items must additionally clear a 2 KiB minimum (per spec line+// 167) before the per-content-type byte threshold even runs.++/// Output-item floor below which the Responses dispatcher does not+/// even attempt compression. Per spec PR-C3 §scope. Matches+/// `responses_items::OUTPUT_ITEM_MIN_BYTES`; pinned here too because+/// `headroom-core` is independent of the proxy crate.+const RESPONSES_OUTPUT_MIN_BYTES: usize = 2 * 1024;++/// Compress live-zone blocks of an OpenAI Responses request.+///+/// # Provider scope+///+/// `/v1/responses` only. The body shape is:+///+/// ```json+/// {+/// "model": "...",+/// "input": [+/// {"type": "message", "role": "user", "content": "..."},+/// {"type": "function_call", "call_id": "c1", "name": "...", "arguments": "..."},+/// {"type": "function_call_output", "call_id": "c1", "output": "..."},+/// {"type": "local_shell_call", ...},+/// {"type": "apply_patch_call", "operation": {...}},+/// ...+/// ]+/// }+/// ```+///+/// Live zone = the latest item of each compressible kind:+/// `function_call_output`, `local_shell_call_output`,+/// `apply_patch_call_output`, plus the latest `message` text. Earlier+/// items of those kinds are frozen (cached prefix); never rewritten.+/// All other item types pass through verbatim.+///+/// Cache-safety invariant matches the Anthropic / Chat dispatchers:+/// bytes outside the rewritten ranges are *literally copied* from the+/// input, never re-serialized.+pub fn compress_openai_responses_live_zone(+ body_raw: &[u8],+ _auth_mode: AuthMode,+ model: &str,+) -> Result<LiveZoneOutcome, LiveZoneError> {+ let parsed: Value = serde_json::from_slice(body_raw).map_err(LiveZoneError::BodyNotJson)?;++ // Responses uses `input`. We accept both `input` and `messages`+ // for forward-compat (some clients alias) — but `input` is the+ // canonical name. If neither field is present, surface+ // `NoMessagesArray` so the proxy can passthrough with a named+ // reason.+ let items = parsed+ .get("input")+ .or_else(|| parsed.get("messages"))+ .and_then(Value::as_array)+ .ok_or(LiveZoneError::NoMessagesArray)?;++ if items.is_empty() {+ return Ok(LiveZoneOutcome::NoChange {+ manifest: CompressionManifest::empty(),+ });+ }++ let items_total = items.len();++ // Walk items from the back, tagging the first occurrence of each+ // compressible kind. This naturally yields "latest" semantics.+ let mut latest_function_output: Option<usize> = None;+ let mut latest_local_shell_output: Option<usize> = None;+ let mut latest_apply_patch_output: Option<usize> = None;+ let mut latest_message: Option<usize> = None;++ for (idx, item) in items.iter().enumerate().rev() {+ let type_tag = item.get("type").and_then(Value::as_str).unwrap_or("");+ match type_tag {+ "function_call_output" if latest_function_output.is_none() => {+ latest_function_output = Some(idx);+ }+ "local_shell_call_output" if latest_local_shell_output.is_none() => {+ latest_local_shell_output = Some(idx);+ }+ "apply_patch_call_output" if latest_apply_patch_output.is_none() => {+ latest_apply_patch_output = Some(idx);+ }+ // Only consider user-role messages for compression.+ // Assistant messages are part of the cache hot zone+ // (next-turn continuation context).+ "message"+ if latest_message.is_none()+ && item.get("role").and_then(Value::as_str) == Some("user") =>+ {+ latest_message = Some(idx);+ }+ _ => {}+ }+ // Early-exit if we've found everything we care about.+ if latest_function_output.is_some()+ && latest_local_shell_output.is_some()+ && latest_apply_patch_output.is_some()+ && latest_message.is_some()+ {+ break;+ }+ }++ let candidates: &[(Option<usize>, &str)] = &[+ (latest_function_output, "function_call_output"),+ (latest_local_shell_output, "local_shell_call_output"),+ (latest_apply_patch_output, "apply_patch_call_output"),+ (latest_message, "message"),+ ];++ if candidates.iter().all(|(idx, _)| idx.is_none()) {+ return Ok(LiveZoneOutcome::NoChange {+ manifest: CompressionManifest {+ messages_total: items_total,+ messages_below_frozen_floor: 0,+ latest_user_message_index: latest_message,+ block_outcomes: Vec::new(),+ },+ });+ }++ // Plan replacements per candidate kind. Each plan returns at most+ // one slot (output items have a single string field; messages+ // have a single text content slot).+ let mut all_slots: Vec<(usize, ResponsesPlanSlot)> = Vec::new();+ for (maybe_idx, kind_tag) in candidates {+ let Some(idx) = maybe_idx else { continue };+ match plan_responses_item(body_raw, *idx, kind_tag) {+ Ok(Some(slot)) => all_slots.push((*idx, slot)),+ Ok(None) => {}+ Err(_) => {+ // Body shape doesn't match what we expect for this+ // item — skip it but keep going for the others.+ continue;+ }+ }+ }++ if all_slots.is_empty() {+ return Ok(LiveZoneOutcome::NoChange {+ manifest: CompressionManifest {+ messages_total: items_total,+ messages_below_frozen_floor: 0,+ latest_user_message_index: latest_message,+ block_outcomes: Vec::new(),+ },+ });+ }++ let tokenizer = get_tokenizer(model);+ let mut block_outcomes: Vec<BlockOutcome> = Vec::with_capacity(all_slots.len());+ let mut replacements: Vec<Replacement> = Vec::new();++ for (msg_idx, slot) in all_slots {+ // Output items must clear the 2 KiB floor BEFORE the+ // per-content-type threshold even runs. This is on top of the+ // existing per-block byte-threshold gate.+ if slot.is_output_item && slot.content_text.len() < RESPONSES_OUTPUT_MIN_BYTES {+ block_outcomes.push(BlockOutcome {+ message_index: msg_idx,+ block_index: slot.block_index,+ block_type: slot.block_type.clone(),+ action: BlockAction::BelowByteThreshold {+ content_type: "output_item",+ byte_count: slot.content_text.len(),+ threshold_bytes: RESPONSES_OUTPUT_MIN_BYTES,+ },+ });+ continue;+ }+ let detected = detect_content_type(&slot.content_text);+ let outcome = compress_one_block(+ &slot.content_text,+ detected.content_type,+ slot.content_byte_range,+ msg_idx,+ slot.block_index,+ slot.block_type,+ tokenizer.as_ref(),+ &mut replacements,+ None, // PR-C3: no CCR store on the Responses path yet.+ );+ block_outcomes.push(outcome);+ }++ let manifest = CompressionManifest {+ messages_total: items_total,+ messages_below_frozen_floor: 0,+ latest_user_message_index: latest_message,+ block_outcomes,+ };++ if !manifest.has_compressed_block() || replacements.is_empty() {+ return Ok(LiveZoneOutcome::NoChange { manifest });+ }++ let new_bytes = apply_replacements(body_raw, &mut replacements);+ let new_body_str = match std::str::from_utf8(&new_bytes) {+ Ok(s) => s,+ Err(_) => return Ok(LiveZoneOutcome::NoChange { manifest }),+ };+ let raw = match RawValue::from_string(new_body_str.to_string()) {+ Ok(r) => r,+ Err(_) => return Ok(LiveZoneOutcome::NoChange { manifest }),+ };++ Ok(LiveZoneOutcome::Modified {+ new_body: raw,+ manifest,+ })+}++/// Per-kind plan slot for the Responses dispatcher. Mirrors+/// `OpenAiPlanSlot` but tracks whether the slot is an `*_output` item+/// (so the 2 KiB floor only applies there, not to `message` text).+struct ResponsesPlanSlot {+ block_index: Option<usize>,+ block_type: String,+ content_text: String,+ content_byte_range: (usize, usize),+ /// True when the slot is one of `function_call_output`,+ /// `local_shell_call_output`, `apply_patch_call_output`. Used to+ /// gate the 2 KiB output-item floor.+ is_output_item: bool,+}++/// Body view for the Responses request; accepts both `input` (canonical)+/// and `messages` (alias).+#[derive(Deserialize)]+struct ResponsesBodyView<'a> {+ #[serde(borrow, default)]+ input: Option<Vec<&'a RawValue>>,+ #[serde(borrow, default)]+ messages: Option<Vec<&'a RawValue>>,+}++impl<'a> ResponsesBodyView<'a> {+ fn items(&self) -> Option<&Vec<&'a RawValue>> {+ self.input.as_ref().or(self.messages.as_ref())+ }+}++#[derive(Deserialize)]+struct OutputItemView<'a> {+ #[serde(borrow, default)]+ output: Option<&'a RawValue>,+}++#[derive(Deserialize)]+struct MessageItemView<'a> {+ #[serde(borrow, default)]+ content: Option<&'a RawValue>,+}++/// Plan a single replacement slot for a Responses item at index+/// `item_idx`. Returns `Ok(None)` when the item exists but has no+/// compressible payload (e.g. message with array content where every+/// part is non-text).+fn plan_responses_item(+ body_raw: &[u8],+ item_idx: usize,+ kind_tag: &str,+) -> Result<Option<ResponsesPlanSlot>, PlanError> {+ let body_str = std::str::from_utf8(body_raw).map_err(|_| PlanError::ParseFailed)?;+ let body: ResponsesBodyView<'_> =+ serde_json::from_str(body_str).map_err(|_| PlanError::ParseFailed)?;+ let items = body.items().ok_or(PlanError::ParseFailed)?;+ let item_raw = items.get(item_idx).ok_or(PlanError::TargetOutOfBounds)?;+ let item_offset_in_body =+ bytes_offset_of(body_str, item_raw.get()).ok_or(PlanError::OffsetMissing)?;++ match kind_tag {+ "function_call_output" | "local_shell_call_output" | "apply_patch_call_output" => {+ let view: OutputItemView<'_> =+ serde_json::from_str(item_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let Some(output_raw) = view.output else {+ return Ok(None);+ };+ let output_offset_in_item = bytes_offset_of(item_raw.get(), output_raw.get())+ .ok_or(PlanError::OffsetMissing)?;+ let output_offset_in_body = item_offset_in_body + output_offset_in_item;+ let output_str = output_raw.get();+ // `output` must be a JSON string for compression to apply.+ // Nested-object `output` (rare) falls through.+ if !output_str.starts_with('"') {+ return Ok(None);+ }+ let unescaped: String =+ serde_json::from_str(output_str).map_err(|_| PlanError::ParseFailed)?;+ Ok(Some(ResponsesPlanSlot {+ block_index: None,+ block_type: kind_tag.to_string(),+ content_text: unescaped,+ content_byte_range: (+ output_offset_in_body,+ output_offset_in_body + output_str.len(),+ ),+ is_output_item: true,+ }))+ }+ "message" => {+ let view: MessageItemView<'_> =+ serde_json::from_str(item_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let Some(content_raw) = view.content else {+ return Ok(None);+ };+ let content_offset_in_item = bytes_offset_of(item_raw.get(), content_raw.get())+ .ok_or(PlanError::OffsetMissing)?;+ let content_offset_in_body = item_offset_in_body + content_offset_in_item;+ let content_str = content_raw.get();++ // Case A: stringly-typed content.+ if content_str.starts_with('"') {+ let unescaped: String =+ serde_json::from_str(content_str).map_err(|_| PlanError::ParseFailed)?;+ return Ok(Some(ResponsesPlanSlot {+ block_index: None,+ block_type: "message_string".to_string(),+ content_text: unescaped,+ content_byte_range: (+ content_offset_in_body,+ content_offset_in_body + content_str.len(),+ ),+ is_output_item: false,+ }));+ }++ // Case B: array of typed content parts. The Responses+ // spec uses `{type: "input_text", text: "..."}` and+ // `{type: "output_text", text: "..."}`. Both are+ // compressible. Anything else (image, file, etc.) is+ // skipped.+ let parts: Vec<&RawValue> =+ serde_json::from_str(content_str).map_err(|_| PlanError::ParseFailed)?;++ // Pick the first text-shaped part for compression. The+ // common Codex shape has exactly one input_text per+ // user message; the assistant final-answer shape has+ // exactly one output_text. If a future shape carries+ // multiple, we compress the first only — the rest still+ // round-trip byte-equal because we never plan a second+ // slot.+ for (part_idx, part_raw) in parts.iter().enumerate() {+ let header: BlockHeader<'_> =+ serde_json::from_str(part_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let block_type = header.r#type.unwrap_or("unknown");+ let is_text = block_type == "input_text"+ || block_type == "output_text"+ || block_type == "text";+ if !is_text {+ continue;+ }++ #[derive(Deserialize)]+ struct TextHeader<'a> {+ #[serde(borrow, default)]+ text: Option<&'a RawValue>,+ }+ let h: TextHeader<'_> =+ serde_json::from_str(part_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let Some(text_raw) = h.text else { continue };++ let part_offset_in_content =+ bytes_offset_of(content_str, part_raw.get()).ok_or(PlanError::OffsetMissing)?;+ let part_offset_in_body = content_offset_in_body + part_offset_in_content;+ let text_offset_in_part = bytes_offset_of(part_raw.get(), text_raw.get())+ .ok_or(PlanError::OffsetMissing)?;++ let text_str = text_raw.get();+ if !text_str.starts_with('"') {+ continue;+ }+ let unescaped: String =+ serde_json::from_str(text_str).map_err(|_| PlanError::ParseFailed)?;++ let text_start_in_body = part_offset_in_body + text_offset_in_part;+ let text_end_in_body = text_start_in_body + text_str.len();++ return Ok(Some(ResponsesPlanSlot {+ block_index: Some(part_idx),+ block_type: format!("message_{block_type}"),+ content_text: unescaped,+ content_byte_range: (text_start_in_body, text_end_in_body),+ is_output_item: false,+ }));+ }+ Ok(None)+ }+ _ => Ok(None),+ }+}++#[cfg(test)]+mod openai_responses_tests {+ use super::*;+ use serde_json::json;++ fn body(value: Value) -> Vec<u8> {+ serde_json::to_vec(&value).unwrap()+ }++ #[test]+ fn empty_input_yields_no_change() {+ let b = body(json!({"model": "gpt-4o", "input": []}));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, DEFAULT_MODEL).unwrap();+ assert!(matches!(out, LiveZoneOutcome::NoChange { .. }));+ }++ #[test]+ fn no_input_field_errors() {+ let b = body(json!({"model": "gpt-4o"}));+ let err =+ compress_openai_responses_live_zone(&b, AuthMode::Payg, DEFAULT_MODEL).unwrap_err();+ assert!(matches!(err, LiveZoneError::NoMessagesArray));+ }++ #[test]+ fn invalid_json_errors() {+ let err = compress_openai_responses_live_zone(b"not json", AuthMode::Payg, DEFAULT_MODEL)+ .unwrap_err();+ assert!(matches!(err, LiveZoneError::BodyNotJson(_)));+ }++ #[test]+ fn output_below_2kb_skipped() {+ // 1 KB output → below the output-item floor.+ let small = "x".repeat(1024);+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "function_call_output", "call_id": "c1", "output": small}+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ match &out {+ LiveZoneOutcome::NoChange { manifest } => {+ assert_eq!(manifest.block_outcomes.len(), 1);+ match &manifest.block_outcomes[0].action {+ BlockAction::BelowByteThreshold {+ content_type,+ byte_count,+ threshold_bytes,+ } => {+ assert_eq!(*content_type, "output_item");+ assert_eq!(*byte_count, 1024);+ assert_eq!(*threshold_bytes, 2048);+ }+ other => panic!("expected BelowByteThreshold, got {other:?}"),+ }+ }+ _ => panic!("expected NoChange"),+ }+ }++ #[test]+ fn picks_latest_function_output_only() {+ // Two function_call_output items; only the latest is in the+ // live zone. Both small, so neither compresses, but the+ // manifest must show one slot, not two.+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "function_call_output", "call_id": "c1", "output": "early"},+ {"type": "function_call", "call_id": "c2", "name": "f", "arguments": "{}"},+ {"type": "function_call_output", "call_id": "c2", "output": "late"},+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ let manifest = match &out {+ LiveZoneOutcome::NoChange { manifest } => manifest,+ LiveZoneOutcome::Modified { manifest, .. } => manifest,+ };+ let outputs: Vec<_> = manifest+ .block_outcomes+ .iter()+ .filter(|b| b.block_type == "function_call_output")+ .collect();+ assert_eq!(outputs.len(), 1);+ assert_eq!(outputs[0].message_index, 2);+ }++ #[test]+ fn unknown_item_types_passthrough_no_slot() {+ // Items the dispatcher doesn't compress — no replacement.+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "reasoning", "id": "r1", "encrypted_content": "opaque"},+ {"type": "compaction", "id": "k1", "encrypted_content": "opaque"},+ {"type": "future_item_v2", "novel": true},+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ match &out {+ LiveZoneOutcome::NoChange { manifest } => {+ assert!(manifest.block_outcomes.is_empty());+ }+ _ => panic!("expected NoChange"),+ }+ }++ #[test]+ fn large_log_output_compressed() {+ // Compressible build-output style log block with repeated+ // template lines. Above 2 KB so the output floor passes;+ // LogCompressor handles BuildOutput content type.+ let mut log = String::new();+ for i in 0..400 {+ log.push_str(&format!(+ "[2024-01-01 00:00:00] INFO compile.rs:42 building module foo_{i}\n"+ ));+ }+ assert!(log.len() > 2048);+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "local_shell_call_output", "call_id": "c1", "output": log}+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ match &out {+ LiveZoneOutcome::Modified { new_body, manifest } => {+ let new = new_body.get();+ assert!(new.len() < b.len());+ assert!(manifest+ .block_outcomes+ .iter()+ .any(|b| matches!(b.action, BlockAction::Compressed { .. })));+ }+ LiveZoneOutcome::NoChange { manifest } => {+ // RejectedNotSmaller is also an acceptable outcome+ // for the test fixture; what matters is that the+ // dispatcher *attempted* the compression.+ let attempted = manifest.block_outcomes.iter().any(|b| {+ matches!(+ b.action,+ BlockAction::Compressed { .. } | BlockAction::RejectedNotSmaller { .. }+ )+ });+ assert!(+ attempted,+ "expected dispatcher to attempt compression on a 2KB+ log fixture: {manifest:?}"+ );+ }+ }+ }++ #[test]+ fn message_user_content_planned() {+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "message", "role": "user",+ "content": [{"type": "input_text", "text": "describe this"}]}+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ match &out {+ LiveZoneOutcome::NoChange { manifest } => {+ assert_eq!(manifest.block_outcomes.len(), 1);+ assert_eq!(manifest.block_outcomes[0].block_type, "message_input_text");+ }+ _ => panic!("expected NoChange"),+ }+ }++ #[test]+ fn assistant_message_not_in_live_zone() {+ // Only user messages are eligible. An assistant `message`+ // item is never planned.+ let b = body(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "message", "role": "assistant",+ "content": [{"type": "output_text", "text": "answer"}]}+ ]+ }));+ let out = compress_openai_responses_live_zone(&b, AuthMode::Payg, "gpt-4o").unwrap();+ match &out {+ LiveZoneOutcome::NoChange { manifest } => {+ assert!(manifest.block_outcomes.is_empty());+ }+ _ => panic!("expected NoChange"),+ }+ }+}diff --git a/crates/headroom-core/src/transforms/mod.rs b/crates/headroom-core/src/transforms/mod.rsindex f262ca249..5546d45b8 100644--- a/crates/headroom-core/src/transforms/mod.rs+++ b/crates/headroom-core/src/transforms/mod.rs@@ -39,8 +39,9 @@ pub use diff_compressor::{DiffCompressionResult, DiffCompressor, DiffCompressorConfig, DiffCompressorStats,};pub use live_zone::{- compress_anthropic_live_zone, compress_openai_chat_live_zone, AuthMode, BlockAction,- BlockOutcome, CompressionManifest, ExclusionReason, LiveZoneError, LiveZoneOutcome,+ compress_anthropic_live_zone, compress_openai_chat_live_zone,+ compress_openai_responses_live_zone, AuthMode, BlockAction, BlockOutcome, CompressionManifest,+ ExclusionReason, LiveZoneError, LiveZoneOutcome,};pub use log_compressor::{LogCompressionResult, LogCompressor, LogCompressorConfig, LogCompressorStats, LogFormat,diff --git a/crates/headroom-proxy/src/compression/live_zone_responses.rs b/crates/headroom-proxy/src/compression/live_zone_responses.rsnew file mode 100644index 000000000..0d4797d76--- /dev/null+++ b/crates/headroom-proxy/src/compression/live_zone_responses.rs@@ -0,0 +1,404 @@+//! OpenAI Responses `/v1/responses` request compression — live-zone+//! dispatcher entry point (Phase C PR-C3).+//!+//! # Provider scope+//!+//! Sibling of [`super::live_zone_openai`] (Chat Completions) and+//! [`super::live_zone_anthropic`] (Messages). Same per-content-type+//! compressor backend, same byte-threshold gate, same+//! tokenizer-validated rejection check, same byte-range surgery.+//!+//! Differences from the Chat Completions dispatcher:+//!+//! - Request shape: items are keyed under `input` (canonical) or+//! `messages` (legacy alias) and are explicitly typed by the+//! `type` field, not role-tagged.+//! - Live zone: latest of each compressible kind —+//! `function_call_output`, `local_shell_call_output`,+//! `apply_patch_call_output`, plus the latest `message` (user role)+//! text content. Earlier *_output items are FROZEN.+//! - Output items must clear a 2 KiB minimum BEFORE the+//! per-content-type byte threshold even runs (per spec PR-C3+//! §scope, line 167 of the realignment plan).+//! - Cache hot zone: every other item type passes through verbatim.+//! This includes `reasoning.encrypted_content`, `compaction.*`,+//! MCP / computer-use / web-search / file-search /+//! code-interpreter / image-generation / tool-search /+//! custom-tool calls, and any future-unknown `type` value.+//!+//! Failure-mode contract matches every other live-zone dispatcher:+//! every error path returns the original body unchanged. Per-block+//! compressor errors surface via the manifest at warn-level; only the+//! failing block reverts.++use bytes::Bytes;+use headroom_core::transforms::live_zone::DEFAULT_MODEL;+use headroom_core::transforms::{+ compress_openai_responses_live_zone, AuthMode, BlockAction, LiveZoneError, LiveZoneOutcome,+};++use crate::compression::{Outcome, PassthroughReason};+use crate::config::CompressionMode;++/// OpenAI Responses live-zone compression entry point.+///+/// # Behaviour+///+/// - `mode == Off` → [`Outcome::Passthrough { ModeOff }`].+/// - Body parses but neither `input` nor `messages` is an array →+/// `Passthrough { NoMessages }`.+/// - Body doesn't parse → `Passthrough { NotJson }`.+/// - At least one live-zone block compressed → [`Outcome::Compressed`].+/// - Otherwise → [`Outcome::NoCompression`].+pub fn compress_openai_responses_request(+ body: &Bytes,+ mode: CompressionMode,+ request_id: &str,+) -> Outcome {+ if matches!(mode, CompressionMode::Off) {+ tracing::info!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "passthrough",+ reason = "mode_off",+ body_bytes = body.len(),+ "openai responses compression decision"+ );+ return Outcome::Passthrough {+ reason: PassthroughReason::ModeOff,+ };+ }++ // Lightweight gate before the full dispatcher walk: parse only+ // enough to determine `input` (or `messages`) shape and the+ // model name. The dispatcher does its own parse — keeping this+ // gate light avoids double-walking the tree on the common+ // no-compression path.+ let parsed: serde_json::Value = match serde_json::from_slice(body) {+ Ok(v) => v,+ Err(_) => {+ tracing::warn!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "passthrough",+ reason = "not_json",+ body_bytes = body.len(),+ "openai responses compression decision"+ );+ return Outcome::Passthrough {+ reason: PassthroughReason::NotJson,+ };+ }+ };++ let has_array_field = parsed+ .get("input")+ .or_else(|| parsed.get("messages"))+ .and_then(|v| v.as_array())+ .is_some();+ if !has_array_field {+ tracing::info!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "passthrough",+ reason = "no_messages",+ body_bytes = body.len(),+ "openai responses compression decision"+ );+ return Outcome::Passthrough {+ reason: PassthroughReason::NoMessages,+ };+ }++ // Walk every item once for telemetry — log unknown item types at+ // warn level (no-silent-fallbacks) and redact image_data fields+ // from the logged shape (no PII / no megabytes of base64). The+ // upstream-bound bytes are NEVER mutated by this loop; the body+ // is forwarded byte-for-byte as the live-zone dispatcher decides.+ log_item_telemetry(&parsed, request_id);++ let model = parsed+ .get("model")+ .and_then(serde_json::Value::as_str)+ .unwrap_or(DEFAULT_MODEL);++ match compress_openai_responses_live_zone(body, AuthMode::Payg, model) {+ Ok(LiveZoneOutcome::NoChange { manifest }) => {+ tracing::info!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "no_change",+ reason = "no_block_compressed",+ body_bytes = body.len(),+ items_total = manifest.messages_total,+ latest_user_message_index = ?manifest.latest_user_message_index,+ live_zone_blocks = manifest.block_outcomes.len(),+ model = model,+ "openai responses live-zone dispatch"+ );+ Outcome::NoCompression+ }+ Ok(LiveZoneOutcome::Modified { new_body, manifest }) => {+ // Aggregate per-block savings for the structured log.+ // Mirrors the Chat Completions sibling so dashboards+ // don't need provider-specific shapes.+ let mut original_bytes_total: usize = 0;+ let mut compressed_bytes_total: usize = 0;+ let mut original_tokens_total: usize = 0;+ let mut compressed_tokens_total: usize = 0;+ let mut strategies: Vec<&'static str> = Vec::new();+ let mut had_compressor_error = false;+ for entry in &manifest.block_outcomes {+ match entry.action {+ BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ original_tokens,+ compressed_tokens,+ } => {+ original_bytes_total += original_bytes;+ compressed_bytes_total += compressed_bytes;+ original_tokens_total += original_tokens;+ compressed_tokens_total += compressed_tokens;+ if !strategies.contains(&strategy) {+ strategies.push(strategy);+ }+ }+ BlockAction::CompressorError {+ strategy,+ ref error,+ } => {+ had_compressor_error = true;+ tracing::error!(+ event = "compression_error",+ request_id = %request_id,+ path = "/v1/responses",+ strategy = strategy,+ error = %error,+ "openai responses compressor error on a block; that block reverts to original"+ );+ }+ _ => {}+ }+ }+ let body_bytes_in = body.len();+ let new_body_bytes = Bytes::copy_from_slice(new_body.get().as_bytes());+ let body_bytes_out = new_body_bytes.len();+ tracing::info!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "compressed",+ reason = "live_zone_blocks_rewritten",+ body_bytes_in = body_bytes_in,+ body_bytes_out = body_bytes_out,+ bytes_freed = body_bytes_in.saturating_sub(body_bytes_out),+ items_total = manifest.messages_total,+ latest_user_message_index = ?manifest.latest_user_message_index,+ live_zone_blocks = manifest.block_outcomes.len(),+ live_zone_strategies = ?strategies,+ live_zone_block_original_bytes = original_bytes_total,+ live_zone_block_compressed_bytes = compressed_bytes_total,+ live_zone_block_original_tokens = original_tokens_total,+ live_zone_block_compressed_tokens = compressed_tokens_total,+ had_compressor_error = had_compressor_error,+ model = model,+ "openai responses live-zone dispatch"+ );+ Outcome::Compressed {+ body: new_body_bytes,+ tokens_before: original_tokens_total,+ tokens_after: compressed_tokens_total,+ strategies_applied: strategies,+ markers_inserted: Vec::new(),+ }+ }+ Err(LiveZoneError::BodyNotJson(_)) => {+ tracing::warn!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ "openai responses live-zone dispatcher rejected JSON body; falling back to passthrough"+ );+ Outcome::Passthrough {+ reason: PassthroughReason::NotJson,+ }+ }+ Err(LiveZoneError::NoMessagesArray) => {+ tracing::info!(+ event = "compression_decision",+ request_id = %request_id,+ path = "/v1/responses",+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "passthrough",+ reason = "no_messages",+ body_bytes = body.len(),+ "openai responses compression decision"+ );+ Outcome::Passthrough {+ reason: PassthroughReason::NoMessages,+ }+ }+ }+}++/// Walk the items array once and emit per-item telemetry. Recognised+/// item types are tallied; unknown `type` values trigger a+/// `tracing::warn!` `event = responses_unknown_item_type` but never+/// alter the upstream-bound bytes. `image_generation_call.image_data`+/// is never logged verbatim — only its byte length, per spec.+fn log_item_telemetry(parsed: &serde_json::Value, request_id: &str) {+ let items = match parsed+ .get("input")+ .or_else(|| parsed.get("messages"))+ .and_then(|v| v.as_array())+ {+ Some(items) => items,+ None => return,+ };++ use crate::responses_items::{classify_items, ResponseItem};+ use serde_json::value::RawValue;++ // Build a `RawValue` from the items array so we can use the+ // typed classifier. We're already past the gate; one additional+ // serialize is fine (telemetry path, not hot path for body bytes).+ let items_string = match serde_json::to_string(items) {+ Ok(s) => s,+ Err(_) => return,+ };+ let items_raw = match RawValue::from_string(items_string) {+ Ok(r) => r,+ Err(_) => return,+ };+ let classified = match classify_items(&items_raw) {+ Ok(c) => c,+ Err(e) => {+ tracing::warn!(+ event = "responses_classify_error",+ request_id = %request_id,+ error = %e,+ "could not classify Responses items array; passthrough preserves bytes"+ );+ return;+ }+ };++ let mut by_type: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();+ for c in &classified {+ match &c.typed {+ None => {+ // No-silent-fallbacks: log the unknown type at warn,+ // preserving the type tag so operators can grep for it.+ tracing::warn!(+ event = "responses_unknown_item_type",+ request_id = %request_id,+ type_tag = %c.type_tag,+ raw_bytes = c.raw.get().len(),+ "responses item with unknown `type` — preserving verbatim"+ );+ *by_type.entry("unknown").or_insert(0) += 1;+ }+ Some(item) => {+ let tag = item.type_tag();+ *by_type.entry(tag).or_insert(0) += 1;+ // Image-generation log redaction. The upstream-bound+ // body is NOT mutated; this only keeps `image_data`+ // out of the structured-log path. We log the tag and+ // a size estimate (the raw item byte length).+ if matches!(item, ResponseItem::ImageGenerationCall { .. }) {+ tracing::debug!(+ event = "responses_image_generation_call",+ request_id = %request_id,+ item_bytes = c.raw.get().len(),+ // image_data is intentionally omitted —+ // base64 image payloads can be megabytes.+ "image_generation_call seen (image bytes redacted from log)"+ );+ }+ }+ }+ }+ tracing::info!(+ event = "responses_item_summary",+ request_id = %request_id,+ items_total = classified.len(),+ breakdown = ?by_type,+ "responses item type breakdown"+ );+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn body_of(value: serde_json::Value) -> Bytes {+ Bytes::from(serde_json::to_vec(&value).unwrap())+ }++ #[test]+ fn mode_off_short_circuits() {+ let body = Bytes::from_static(b"not valid json");+ let out = compress_openai_responses_request(&body, CompressionMode::Off, "req-1");+ assert!(matches!(+ out,+ Outcome::Passthrough {+ reason: PassthroughReason::ModeOff+ }+ ));+ }++ #[test]+ fn invalid_json_passthrough() {+ let body = Bytes::from_static(b"\x01\x02 not json");+ let out = compress_openai_responses_request(&body, CompressionMode::LiveZone, "req-2");+ assert!(matches!(+ out,+ Outcome::Passthrough {+ reason: PassthroughReason::NotJson+ }+ ));+ }++ #[test]+ fn no_input_passthrough() {+ let body = body_of(json!({"model": "gpt-4o"}));+ let out = compress_openai_responses_request(&body, CompressionMode::LiveZone, "req-3");+ assert!(matches!(+ out,+ Outcome::Passthrough {+ reason: PassthroughReason::NoMessages+ }+ ));+ }++ #[test]+ fn small_body_no_change() {+ let body = body_of(json!({+ "model": "gpt-4o",+ "input": [+ {"type": "message", "role": "user",+ "content": [{"type": "input_text", "text": "hi"}]}+ ]+ }));+ let out = compress_openai_responses_request(&body, CompressionMode::LiveZone, "req-4");+ assert!(matches!(out, Outcome::NoCompression));+ }+}diff --git a/crates/headroom-proxy/src/compression/mod.rs b/crates/headroom-proxy/src/compression/mod.rsindex fd20aa7b7..24bcbb512 100644--- a/crates/headroom-proxy/src/compression/mod.rs+++ b/crates/headroom-proxy/src/compression/mod.rs@@ -35,6 +35,7 @@pub mod anthropic;pub mod live_zone_anthropic;pub mod live_zone_openai;+pub mod live_zone_responses;pub mod model_limits;// PR-A4 helper for cache-control floor derivation lives on the@@ -47,17 +48,21 @@ pub use live_zone_anthropic::{compress_anthropic_request, Outcome, PassthroughRepub use live_zone_openai::{compress_openai_chat_request, should_skip_compression, SkipCompressionReason,};+pub use live_zone_responses::compress_openai_responses_request;/// Which provider's compression dispatcher should run for a request-/// path. PR-C2 wires `/v1/chat/completions`; future PRs add-/// `/v1/responses`, Gemini, etc. Returning an enum (rather than a-/// bare bool + string later) keeps the routing explicit.+/// path. PR-C2 wired `/v1/chat/completions`; PR-C3 adds+/// `/v1/responses`. Future PRs add Gemini etc. Returning an enum+/// (rather than a bare bool + string later) keeps the routing+/// explicit.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum CompressibleEndpoint {/// Anthropic `/v1/messages`.AnthropicMessages,/// OpenAI Chat Completions `/v1/chat/completions`.OpenAiChatCompletions,+ /// OpenAI Responses `/v1/responses`.+ OpenAiResponses,}/// Does this request path target an LLM endpoint we know how to@@ -73,6 +78,7 @@ pub fn classify_compressible_path(path: &str) -> Option<CompressibleEndpoint> {match path {"/v1/messages" => Some(CompressibleEndpoint::AnthropicMessages),"/v1/chat/completions" => Some(CompressibleEndpoint::OpenAiChatCompletions),+ "/v1/responses" => Some(CompressibleEndpoint::OpenAiResponses),_ => None,}}@@ -99,13 +105,21 @@ mod tests {);}+ #[test]+ fn openai_responses_path_matches() {+ assert!(is_compressible_path("/v1/responses"));+ assert_eq!(+ classify_compressible_path("/v1/responses"),+ Some(CompressibleEndpoint::OpenAiResponses)+ );+ }+#[test]fn other_paths_skip() {assert!(!is_compressible_path("/v1/messages/123"));- assert!(!is_compressible_path("/v1/responses"));+ assert!(!is_compressible_path("/v1/responses/123"));assert!(!is_compressible_path("/healthz"));assert!(!is_compressible_path("/"));assert!(!is_compressible_path(""));- assert!(classify_compressible_path("/v1/responses").is_none());}}diff --git a/crates/headroom-proxy/src/handlers/mod.rs b/crates/headroom-proxy/src/handlers/mod.rsindex e6fb54d49..bf1d8ffee 100644--- a/crates/headroom-proxy/src/handlers/mod.rs+++ b/crates/headroom-proxy/src/handlers/mod.rs@@ -9,3 +9,4 @@//! based on `classify_compressible_path`.pub mod chat_completions;+pub mod responses;diff --git a/crates/headroom-proxy/src/handlers/responses.rs b/crates/headroom-proxy/src/handlers/responses.rsnew file mode 100644index 000000000..8acf36fe7--- /dev/null+++ b/crates/headroom-proxy/src/handlers/responses.rs@@ -0,0 +1,182 @@+//! POST `/v1/responses` handler — Phase C PR-C3.+//!+//! # Why an explicit handler?+//!+//! The Python proxy currently flattens Responses-shape items into+//! Chat-Completions-shape via+//! `headroom/proxy/responses_converter.py` — a fragile shim that+//! silently breaks every time OpenAI lands a new item type. C3 ports+//! this path to Rust with first-class per-item-type handling.+//!+//! The handler buffers the request body (so the live-zone dispatcher+//! can inspect it) and re-injects it into [`crate::proxy::forward_http`].+//! `forward_http`'s compression gate dispatches on the path+//! classification (`CompressibleEndpoint::OpenAiResponses`) added by+//! this PR.+//!+//! # Streaming+//!+//! When the request carries `Accept: text/event-stream`, this handler+//! defers to PR-C4's streaming wiring. For now we forward+//! byte-for-byte and emit+//! `event = responses_streaming_passthrough_until_c4` so we can+//! measure the volume in production. C4 wires the+//! [`crate::sse::openai_responses::ResponseState`] machine PR-C1+//! shipped.+//!+//! # Per-item-type behaviour+//!+//! See [`crate::responses_items`] for the typed enum. Briefly:+//!+//! - `function_call_output` / `local_shell_call_output` /+//! `apply_patch_call_output` — output strings are eligible for+//! live-zone compression when the latest of each kind, above the+//! 2 KiB output-item floor.+//! - `message` (user role) — text content is eligible.+//! - `reasoning.encrypted_content`, `compaction.*`, MCP / computer /+//! web-search / file-search / code-interpreter / image-generation /+//! tool-search / custom-tool calls — passthrough byte-equal.+//! - `function_call.arguments` is a STRING the model emitted; never+//! parsed by the proxy.+//! - `local_shell_call.action.command` is an argv array; never+//! joined into a string.+//! - `apply_patch_call.operation.diff` is a V4A diff payload; never+//! re-serialized.+//! - Unknown `type` values log+//! `event = responses_unknown_item_type` at warn level and pass+//! through verbatim.++use axum::body::Body;+use axum::extract::{ConnectInfo, State};+use axum::http::{HeaderMap, Method, Request, Uri};+use axum::response::Response;+use bytes::Bytes;+use std::net::SocketAddr;++use crate::proxy::{forward_http, AppState};++/// Axum POST handler for `/v1/responses`. Buffers the body, stitches+/// a fresh `Request<Body>` together, and forwards via+/// [`forward_http`]. Compression dispatch + SSE telemetry is handled+/// inside `forward_http`'s shared gate (PR-C1 + PR-C2 + PR-C3).+pub async fn handle_responses(+ State(state): State<AppState>,+ ConnectInfo(client_addr): ConnectInfo<SocketAddr>,+ method: Method,+ uri: Uri,+ headers: HeaderMap,+ body: Bytes,+) -> Response {+ // Streaming detection: when the client asks for SSE, log the+ // volume so we can plan the C4 cut-over. The body still flows+ // through `forward_http` — compression is gated by content-type+ // (application/json) and SSE responses are streamed back via the+ // existing tee in `forward_http` (already wired for the+ // `OpenAIResponsesStreamState` parser by PR-C1).+ if accepts_sse(&headers) {+ tracing::warn!(+ event = "responses_streaming_passthrough_until_c4",+ method = %method,+ path = %uri.path(),+ "/v1/responses called with Accept: text/event-stream — \+ passthrough until PR-C4 wires the streaming state machine"+ );+ }++ // Reconstruct the Request<Body> shape forward_http expects.+ let mut builder = Request::builder().method(method).uri(uri);+ if let Some(hs) = builder.headers_mut() {+ *hs = headers;+ }+ let req = match builder.body(Body::from(body)) {+ Ok(r) => r,+ Err(e) => {+ tracing::error!(+ event = "handler_error",+ handler = "responses",+ error = %e,+ "failed to reconstruct request from buffered body"+ );+ return Response::builder()+ .status(http::StatusCode::INTERNAL_SERVER_ERROR)+ .body(Body::from("internal handler error"))+ .expect("static response");+ }+ };++ forward_http(state, client_addr, req)+ .await+ .unwrap_or_else(|e| {+ use axum::response::IntoResponse;+ e.into_response()+ })+}++/// Cheap check: is this request asking for an SSE response? Compares+/// `Accept` against `text/event-stream` (case-insensitive on the+/// media-type token, RFC 7231 §3.1.1.1). Multiple media types in+/// `Accept` are split on `,`; any match wins.+fn accepts_sse(headers: &HeaderMap) -> bool {+ let Some(v) = headers.get(http::header::ACCEPT) else {+ return false;+ };+ let Ok(s) = v.to_str() else {+ return false;+ };+ s.split(',').any(|piece| {+ let mt = piece.split(';').next().unwrap_or("").trim();+ mt.eq_ignore_ascii_case("text/event-stream")+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use http::HeaderValue;++ #[test]+ fn accepts_sse_explicit() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ HeaderValue::from_static("text/event-stream"),+ );+ assert!(accepts_sse(&h));+ }++ #[test]+ fn accepts_sse_case_insensitive() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ HeaderValue::from_static("Text/Event-Stream"),+ );+ assert!(accepts_sse(&h));+ }++ #[test]+ fn accepts_sse_among_others() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ HeaderValue::from_static("application/json, text/event-stream;q=0.9"),+ );+ assert!(accepts_sse(&h));+ }++ #[test]+ fn accepts_json_only_returns_false() {+ let mut h = HeaderMap::new();+ h.insert(+ http::header::ACCEPT,+ HeaderValue::from_static("application/json"),+ );+ assert!(!accepts_sse(&h));+ }++ #[test]+ fn no_accept_header_returns_false() {+ let h = HeaderMap::new();+ assert!(!accepts_sse(&h));+ }+}diff --git a/crates/headroom-proxy/src/lib.rs b/crates/headroom-proxy/src/lib.rsindex fc04093a7..d5f094ece 100644--- a/crates/headroom-proxy/src/lib.rs+++ b/crates/headroom-proxy/src/lib.rs@@ -8,6 +8,7 @@ pub mod handlers;pub mod headers;pub mod health;pub mod proxy;+pub mod responses_items;pub mod sse;pub mod websocket;diff --git a/crates/headroom-proxy/src/proxy.rs b/crates/headroom-proxy/src/proxy.rsindex caf649e51..9037f287e 100644--- a/crates/headroom-proxy/src/proxy.rs+++ b/crates/headroom-proxy/src/proxy.rs@@ -75,6 +75,14 @@ pub fn build_app(state: AppState) -> Router {"/v1/chat/completions",post(crate::handlers::chat_completions::handle_chat_completions),)+ // PR-C3: explicit POST route for /v1/responses. Same forward+ // pattern as /v1/chat/completions — the handler buffers the+ // body, then `forward_http`'s gate dispatches to the+ // Responses live-zone walker via `compress_openai_responses_request`.+ .route(+ "/v1/responses",+ post(crate::handlers::responses::handle_responses),+ ).fallback(any(catch_all)).with_state(state)}@@ -383,6 +391,18 @@ pub(crate) async fn forward_http()}}+ // PR-C3: OpenAI Responses (`/v1/responses`). The Responses+ // dispatcher walks an explicitly-typed `input` array and+ // only rewrites the latest of each compressible `*_output`+ // kind plus the latest `message` text. Cache hot zone is+ // every other item type (passthrough verbatim).+ compression::CompressibleEndpoint::OpenAiResponses => {+ compression::compress_openai_responses_request(+ &buffered,+ state.config.compression_mode,+ &request_id,+ )+ }};let body_to_send = match outcome {diff --git a/crates/headroom-proxy/src/responses_items.rs b/crates/headroom-proxy/src/responses_items.rsnew file mode 100644index 000000000..4aabd710a--- /dev/null+++ b/crates/headroom-proxy/src/responses_items.rs@@ -0,0 +1,566 @@+//! Per-item-type parsing for the OpenAI Responses API+//! (`/v1/responses`) — Phase C PR-C3.+//!+//! # Why an explicit enum?+//!+//! The `input` array of a `/v1/responses` request carries items whose+//! shapes diverge sharply by `type`. The Python proxy currently+//! flattens these into Chat-Completions-shape via+//! `headroom/proxy/responses_converter.py` — every new OpenAI item+//! type (Codex `phase`, encrypted reasoning, MCP server-side tools,+//! `apply_patch_call`, V4A diffs, …) silently breaks the converter+//! until someone updates it.+//!+//! C3 ports the request path to Rust with **first-class per-item-type+//! handling**. The rules are:+//!+//! - Items whose payloads are *opaque to the proxy* (encrypted+//! reasoning, compaction blobs, MCP / computer / web-search /+//! file-search / code-interpreter call results, image generation+//! results) are **passthrough** — the bytes flow upstream unchanged+//! and the proxy never re-serializes them. Re-serializing risks+//! busting whitespace / key-order / Unicode-escape invariants the+//! provider's prompt cache may already have keyed against.+//! - Items whose payloads are *output strings* of stateful tool calls+//! (`function_call_output`, `local_shell_call_output`,+//! `apply_patch_call_output`) are eligible for live-zone+//! compression — but only the *latest* of each kind, only above the+//! 2 KiB output-item floor, and only when the per-content-type+//! compressor agrees the result shrinks the token count.+//! - **Unknown item types** are logged at warn level and preserved+//! byte-for-byte via `serde_json::value::RawValue`. This is the+//! no-silent-fallbacks contract — we never strip an item we don't+//! recognise; a future OpenAI release that lands a new `type` value+//! keeps flowing through this proxy without any code change.+//!+//! # `RawValue` strategy+//!+//! `serde(other)` on an enum *does* drop the data (it only stores the+//! tag). For byte-faithful preservation we deserialize each item in+//! two passes: first as `&RawValue` so we hold the original byte+//! slice, then as a typed `ResponseItem<'a>` against the same slice.+//! When we want to emit the unknown-warning log we still hold the+//! `RawValue` alongside it — see [`ClassifiedItem`].+//!+//! Per `feedback_realignment_build_constraints.md`: the parser uses+//! serde, not regex; the dispatcher honors per-content-type thresholds+//! from `transforms::live_zone`; structured `tracing` logs name every+//! decision.++use std::borrow::Cow;++use serde::{Deserialize, Serialize};+use serde_json::value::RawValue;+use serde_json::Value;++/// Wire-shape `local_shell_call.action` payload. The `command` is the+/// argv array — preserving the array structure (rather than joining+/// into a string) is load-bearing for execution-side parity with how+/// the Codex CLI actually invokes processes.+///+/// Note: this typed struct is for **telemetry / decision-making**,+/// not byte preservation. Byte fidelity is provided by the+/// accompanying `&RawValue` slice in [`ClassifiedItem`]. We use+/// `serde_json::Value` for the nested object/array fields here+/// (instead of `RawValue`) because `RawValue`-as-a-struct-field has+/// finicky deserializer-token requirements when nested two levels+/// deep; `Value` always works and the typed struct is never+/// re-serialized to the wire (the outer `RawValue` is what flows+/// upstream).+#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct LocalShellAction<'a> {+ /// Always `"exec"` today; future shells (e.g. `"powershell"`) will+ /// land as new variants and we must not collapse them.+ #[serde(default, borrow)]+ pub r#type: Option<Cow<'a, str>>,+ /// argv of the process to launch. **Must remain a JSON array**+ /// upstream — joining into a string changes shell-quoting+ /// semantics. Stored here as `Value` (typed-only); the original+ /// bytes flow through the parent `RawValue`.+ #[serde(default)]+ pub command: Option<Value>,+ /// Working directory.+ #[serde(default, borrow)]+ pub working_directory: Option<Cow<'a, str>>,+ /// Timeout in milliseconds (Codex sets ~5 min default).+ #[serde(default)]+ pub timeout_ms: Option<u64>,+ /// Environment variables, key/value object.+ #[serde(default)]+ pub env: Option<Value>,+ /// Catch-all for forward-compatibility — any new field on+ /// `action` is preserved through the parent's `RawValue`.+ #[serde(default, rename = "with")]+ pub with: Option<Value>,+}++/// `apply_patch_call.operation` carries a V4A unified diff string. The+/// only field we name is `diff`; everything else round-trips via the+/// parent `RawValue`. Concretely, `diff` is the V4A patch body+/// **verbatim** — re-serializing it would change indentation and break+/// the apply.+///+/// As with [`LocalShellAction`], this typed struct is for telemetry;+/// byte preservation comes from the parent `RawValue`.+#[derive(Debug, Deserialize, Serialize, Clone)]+pub struct ApplyPatchOperation<'a> {+ /// Currently always `"apply_patch"`.+ #[serde(default, borrow)]+ pub r#type: Option<Cow<'a, str>>,+ /// V4A diff payload as a JSON string.+ #[serde(default, borrow)]+ pub diff: Option<Cow<'a, str>>,+}++/// Typed view over a `/v1/responses` request input item. The variants+/// we name are the ones whose handling diverges; everything else falls+/// to a [`ClassifiedItem`] with `typed = None` and is preserved+/// byte-for-byte via the accompanying `RawValue`.+///+/// Notes:+/// - `arguments` on `function_call` is a JSON-encoded **string** on+/// the wire; never parse it as JSON inside the proxy. The model+/// built it; the model parses it.+/// - `output` on `*_output` items is a string. Compressors run only+/// on the latest of each kind, and only above the 2 KiB output-item+/// floor (see [`OUTPUT_ITEM_MIN_BYTES`]).+/// - String fields use `Cow<'a, str>` so escape-bearing JSON values+/// (e.g. `"{\"q\":\"hello\"}"`) succeed without allocation on the+/// non-escaped common path.+#[derive(Debug, Deserialize, Serialize, Clone)]+#[serde(tag = "type")]+pub enum ResponseItem<'a> {+ /// Conversational message item. `phase` (Codex) is preserved+ /// verbatim — values like `"commentary"` and `"final_answer"` are+ /// load-bearing for Codex routing.+ #[serde(rename = "message")]+ Message {+ #[serde(default, borrow)]+ role: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ phase: Option<Cow<'a, str>>,+ /// Stringly-typed `content` is rare on Responses; arrays of+ /// content parts are the common shape. Telemetry-only here;+ /// the byte path uses the parent `RawValue`.+ #[serde(default)]+ content: Option<Value>,+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Reasoning item. `encrypted_content` is opaque — passthrough+ /// only. We do not even peek inside.+ #[serde(rename = "reasoning")]+ Reasoning {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ encrypted_content: Option<Cow<'a, str>>,+ #[serde(default)]+ summary: Option<Value>,+ },++ /// Function tool call. `arguments` is a **string** the model+ /// emitted; never JSON-parsed by the proxy.+ #[serde(rename = "function_call")]+ FunctionCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ name: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ arguments: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Function tool output. `output` is the string the proxy may+ /// compress when this is the latest `function_call_output` and+ /// the bytes exceed the 2 KiB floor.+ #[serde(rename = "function_call_output")]+ FunctionCallOutput {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ output: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Local shell call. `action.command` is an argv array; the+ /// dispatcher must NOT join it into a string.+ #[serde(rename = "local_shell_call")]+ LocalShellCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ action: Option<LocalShellAction<'a>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Local shell output (stdout / stderr / exit).+ #[serde(rename = "local_shell_call_output")]+ LocalShellCallOutput {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ output: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Apply-patch call (V4A unified-diff). The diff bytes must NEVER+ /// be re-serialized.+ #[serde(rename = "apply_patch_call")]+ ApplyPatchCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ operation: Option<ApplyPatchOperation<'a>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Apply-patch output (the result string after applying the+ /// patch — typically the new file content or an error message).+ #[serde(rename = "apply_patch_call_output")]+ ApplyPatchCallOutput {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ call_id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ output: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ status: Option<Cow<'a, str>>,+ },++ /// Compaction blob — encrypted, opaque, sticky to cache.+ #[serde(rename = "compaction")]+ Compaction {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ #[serde(default, borrow)]+ encrypted_content: Option<Cow<'a, str>>,+ },++ /// Server-side MCP call (function-shaped). Passthrough.+ #[serde(rename = "mcp_call")]+ McpCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Server-side MCP list-tools call. Passthrough.+ #[serde(rename = "mcp_list_tools")]+ McpListTools {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Server-side MCP approval request. Passthrough.+ #[serde(rename = "mcp_approval_request")]+ McpApprovalRequest {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Computer-use call — passthrough.+ #[serde(rename = "computer_call")]+ ComputerCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Computer-use call output — screenshot + status. Passthrough+ /// on the wire.+ #[serde(rename = "computer_call_output")]+ ComputerCallOutput {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Hosted web-search tool call. Passthrough.+ #[serde(rename = "web_search_call")]+ WebSearchCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Hosted file-search tool call. Passthrough.+ #[serde(rename = "file_search_call")]+ FileSearchCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Hosted code-interpreter tool call. Passthrough.+ #[serde(rename = "code_interpreter_call")]+ CodeInterpreterCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Hosted image-generation tool call. Passthrough on the wire;+ /// log path redacts `image_data` (size-only) — see+ /// `compression::live_zone_responses::log_item_telemetry`.+ #[serde(rename = "image_generation_call")]+ ImageGenerationCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Hosted tool-search tool call. Passthrough.+ #[serde(rename = "tool_search_call")]+ ToolSearchCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },++ /// Customer-defined custom tool call. Passthrough — we don't+ /// know the argument schema.+ #[serde(rename = "custom_tool_call")]+ CustomToolCall {+ #[serde(default, borrow)]+ id: Option<Cow<'a, str>>,+ },+}++impl<'a> ResponseItem<'a> {+ /// Tag of the variant — useful for structured logs.+ pub fn type_tag(&self) -> &'static str {+ match self {+ ResponseItem::Message { .. } => "message",+ ResponseItem::Reasoning { .. } => "reasoning",+ ResponseItem::FunctionCall { .. } => "function_call",+ ResponseItem::FunctionCallOutput { .. } => "function_call_output",+ ResponseItem::LocalShellCall { .. } => "local_shell_call",+ ResponseItem::LocalShellCallOutput { .. } => "local_shell_call_output",+ ResponseItem::ApplyPatchCall { .. } => "apply_patch_call",+ ResponseItem::ApplyPatchCallOutput { .. } => "apply_patch_call_output",+ ResponseItem::Compaction { .. } => "compaction",+ ResponseItem::McpCall { .. } => "mcp_call",+ ResponseItem::McpListTools { .. } => "mcp_list_tools",+ ResponseItem::McpApprovalRequest { .. } => "mcp_approval_request",+ ResponseItem::ComputerCall { .. } => "computer_call",+ ResponseItem::ComputerCallOutput { .. } => "computer_call_output",+ ResponseItem::WebSearchCall { .. } => "web_search_call",+ ResponseItem::FileSearchCall { .. } => "file_search_call",+ ResponseItem::CodeInterpreterCall { .. } => "code_interpreter_call",+ ResponseItem::ImageGenerationCall { .. } => "image_generation_call",+ ResponseItem::ToolSearchCall { .. } => "tool_search_call",+ ResponseItem::CustomToolCall { .. } => "custom_tool_call",+ }+ }++ /// Is this an `*_output` item the live-zone dispatcher considers+ /// for compression?+ pub fn is_output_item(&self) -> bool {+ matches!(+ self,+ ResponseItem::FunctionCallOutput { .. }+ | ResponseItem::LocalShellCallOutput { .. }+ | ResponseItem::ApplyPatchCallOutput { .. }+ )+ }+}++/// Per-item-type minimum bytes before the live-zone dispatcher even+/// inspects an `*_output` payload. Per spec PR-C3 §scope: 2 KiB.+/// Per-content-type thresholds from `transforms::live_zone` still+/// apply on top of this floor (e.g. logs at 512 B → still skipped+/// because output items must clear 2 KiB first).+pub const OUTPUT_ITEM_MIN_BYTES: usize = 2 * 1024;++/// Two-pass result: a typed view alongside the byte-faithful raw+/// slice. Lifetime ties to the underlying request body. Always+/// preserve the `raw` alongside the typed view; emitting the raw+/// upstream is what guarantees byte-fidelity for unknown / opaque+/// items.+#[derive(Debug)]+pub struct ClassifiedItem<'a> {+ /// Typed parse, when the `type` tag matches a known variant.+ /// `None` for unknown / future item types — those keep flowing+ /// upstream via [`Self::raw`].+ pub typed: Option<ResponseItem<'a>>,+ /// Type tag string (the literal `"type"` field on the JSON+ /// object). Used to log unknown variants by name.+ pub type_tag: &'a str,+ /// Original byte slice for the item. Owned by the request body.+ pub raw: &'a RawValue,+}++/// Helper: extract the `type` tag from a JSON object slice without+/// fully parsing the payload. Returns the borrowed string slice into+/// the input.+#[derive(Deserialize)]+struct TypeOnly<'a> {+ #[serde(borrow, default)]+ r#type: Option<&'a str>,+}++/// Two-pass classification: each item is parsed first as `&RawValue`,+/// then we read the `type` tag and try the typed parse. Errors on the+/// typed parse demote to `Unknown` (we still have the raw slice).+///+/// # Errors+///+/// Returns an error only when the `items` array shape is wrong (not a+/// JSON array) or we couldn't even pluck the `type` tag — in that+/// case the caller falls through to passthrough (no compression).+pub fn classify_items<'a>(+ items_raw: &'a RawValue,+) -> Result<Vec<ClassifiedItem<'a>>, ClassifyError> {+ let raw_items: Vec<&'a RawValue> =+ serde_json::from_str(items_raw.get()).map_err(|_| ClassifyError::ItemsNotArray)?;++ let mut out = Vec::with_capacity(raw_items.len());+ for raw in raw_items {+ let type_only: TypeOnly<'a> =+ serde_json::from_str(raw.get()).map_err(|_| ClassifyError::ItemMissingTypeTag)?;+ let type_tag = type_only.r#type.unwrap_or("");+ // Try typed parse. If it fails (unknown type, or known type+ // with a malformed payload), demote to typed=None — the raw+ // slice still flows upstream verbatim.+ let typed: Option<ResponseItem<'a>> = serde_json::from_str(raw.get()).ok();+ out.push(ClassifiedItem {+ typed,+ type_tag,+ raw,+ });+ }+ Ok(out)+}++/// Classification failure. Both variants imply the proxy falls back+/// to passthrough — we never strip items we can't classify.+#[derive(Debug, thiserror::Error)]+pub enum ClassifyError {+ /// `input` (or `items`) is not a JSON array.+ #[error("response items field is not a JSON array")]+ ItemsNotArray,+ /// One of the items is missing the `type` tag entirely. Without+ /// a tag we cannot even log a useful warn message.+ #[error("response item missing `type` tag")]+ ItemMissingTypeTag,+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn raw(v: serde_json::Value) -> Box<RawValue> {+ RawValue::from_string(v.to_string()).unwrap()+ }++ #[test]+ fn function_call_arguments_string() {+ let r = raw(json!({+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_1",+ "name": "search",+ "arguments": "{\"q\":\"hello\"}",+ }));+ let parsed: ResponseItem = serde_json::from_str(r.get()).unwrap();+ match parsed {+ ResponseItem::FunctionCall { arguments, .. } => {+ // Critical: arguments stays as STRING (the model's+ // serialized JSON, not parsed).+ assert_eq!(arguments.as_deref(), Some("{\"q\":\"hello\"}"));+ }+ other => panic!("expected FunctionCall, got {other:?}"),+ }+ }++ #[test]+ fn local_shell_command_array_preserved() {+ // Wire-shape preservation: the BYTES on the wire keep the+ // command as a JSON array. The typed view exposes a Value+ // (telemetry path); the byte path uses ClassifiedItem.raw.+ let r = raw(json!({+ "type": "local_shell_call",+ "id": "ls_1",+ "call_id": "call_1",+ "action": {+ "type": "exec",+ "command": ["bash", "-c", "ls -la"],+ }+ }));+ // Byte-level: r.get() must contain the command array+ // verbatim (not stringified).+ let bytes = r.get();+ assert!(bytes.contains(r#""command":["bash","-c","ls -la"]"#));+ // Typed-level: the command is parsed as a JSON array.+ let parsed: ResponseItem = serde_json::from_str(bytes).unwrap();+ match parsed {+ ResponseItem::LocalShellCall { action, .. } => {+ let cmd = action.unwrap().command.unwrap();+ assert!(cmd.is_array(), "command must be a JSON array, got: {cmd}");+ let arr = cmd.as_array().unwrap();+ assert_eq!(arr.len(), 3);+ assert_eq!(arr[0], json!("bash"));+ assert_eq!(arr[1], json!("-c"));+ assert_eq!(arr[2], json!("ls -la"));+ }+ other => panic!("expected LocalShellCall, got {other:?}"),+ }+ }++ #[test]+ fn unknown_type_demotes_to_none() {+ let body = json!({+ "input": [+ {"type": "future_item_type_v2", "novel_field": "value"}+ ]+ });+ let raw_input = raw(body["input"].clone());+ let classified = classify_items(&raw_input).unwrap();+ assert_eq!(classified.len(), 1);+ assert_eq!(classified[0].type_tag, "future_item_type_v2");+ assert!(classified[0].typed.is_none());+ }++ #[test]+ fn classify_message_with_phase() {+ let body = json!({+ "input": [+ {"type": "message", "role": "assistant", "phase": "commentary",+ "content": [{"type": "output_text", "text": "thinking"}]}+ ]+ });+ let raw_input = raw(body["input"].clone());+ let classified = classify_items(&raw_input).unwrap();+ match classified[0].typed.as_ref().unwrap() {+ ResponseItem::Message { phase, .. } => {+ assert_eq!(phase.as_deref(), Some("commentary"));+ }+ _ => panic!("expected message"),+ }+ }++ #[test]+ fn is_output_item_correct() {+ let r = raw(json!({"type": "function_call_output", "output": "x"}));+ let p: ResponseItem = serde_json::from_str(r.get()).unwrap();+ assert!(p.is_output_item());++ let r = raw(json!({"type": "reasoning"}));+ let p: ResponseItem = serde_json::from_str(r.get()).unwrap();+ assert!(!p.is_output_item());+ }+}diff --git a/crates/headroom-proxy/tests/integration_responses.rs b/crates/headroom-proxy/tests/integration_responses.rsnew file mode 100644index 000000000..04dc52835--- /dev/null+++ b/crates/headroom-proxy/tests/integration_responses.rs@@ -0,0 +1,780 @@+//! Integration tests for the `/v1/responses` Rust handler (Phase C+//! PR-C3).+//!+//! These tests boot the real Rust proxy in front of a wiremock+//! upstream and exercise the OpenAI Responses API request shape+//! end-to-end. Per spec PR-C3:+//!+//! - V4A patch bodies, `local_shell_call.action.command` argv arrays,+//! Codex `phase`, `compaction`, MCP / computer-use / image+//! generation items, `function_call.arguments` (string form),+//! `reasoning.encrypted_content` round-trip BYTE-EQUAL upstream.+//! - `function_call_output.output` / `local_shell_call_output.output`+//! / `apply_patch_call_output.output` compress only when the+//! latest of each kind AND above the 2 KiB output-item floor.+//! - Unknown `type` values trigger+//! `event = responses_unknown_item_type` warn logs and pass+//! through verbatim.+//!+//! Where compression is expected NOT to run, we assert SHA-256 byte+//! equality between the bytes the client sent and the bytes the+//! upstream received.++mod common;++use common::start_proxy_with;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::sync::{Arc, Mutex};+use wiremock::matchers::{method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++/// Mount a /v1/responses handler that captures the upstream request body.+async fn mount_capture(upstream: &MockServer) -> Arc<Mutex<Option<Vec<u8>>>> {+ let captured: Arc<Mutex<Option<Vec<u8>>>> = Arc::new(Mutex::new(None));+ let captured_clone = captured.clone();+ Mock::given(method("POST"))+ .and(path("/v1/responses"))+ .respond_with(move |req: &wiremock::Request| {+ *captured_clone.lock().unwrap() = Some(req.body.clone());+ ResponseTemplate::new(200).set_body_string(r#"{"ok":true}"#)+ })+ .mount(upstream)+ .await;+ captured+}++fn sha256_hex(bytes: &[u8]) -> String {+ let mut hasher = Sha256::new();+ hasher.update(bytes);+ hasher+ .finalize()+ .iter()+ .fold(String::with_capacity(64), |mut acc, b| {+ use std::fmt::Write as _;+ let _ = write!(acc, "{b:02x}");+ acc+ })+}++#[track_caller]+fn assert_byte_equal_sha256(inbound: &[u8], received: &[u8]) {+ let inbound_hash = sha256_hex(inbound);+ let received_hash = sha256_hex(received);+ assert_eq!(+ inbound.len(),+ received.len(),+ "byte length mismatch: inbound={}, upstream-received={}",+ inbound.len(),+ received.len(),+ );+ assert_eq!(+ inbound_hash, received_hash,+ "SHA-256 mismatch: inbound={inbound_hash}, upstream-received={received_hash}",+ );+}++/// V4A diff fixture used for apply_patch_* tests. The exact byte+/// sequence (including trailing whitespace) must round-trip.+const V4A_DIFF: &str = "*** Begin Patch\n*** Update File: src/main.rs\n@@ -1,3 +1,4 @@\n fn main() {\n+ println!(\"hello\");\n run();\n }\n*** End Patch\n";++#[tokio::test]+async fn v4a_patch_byte_equal_through_proxy() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "apply_patch_call",+ "id": "ap_1",+ "call_id": "call_1",+ "operation": {"type": "apply_patch", "diff": V4A_DIFF},+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ // Defensive: the diff arrives intact as a string field.+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ assert_eq!(parsed["input"][0]["operation"]["diff"], json!(V4A_DIFF));+ proxy.shutdown().await;+}++#[tokio::test]+async fn local_shell_call_command_argv_array_preserved() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "local_shell_call",+ "id": "ls_1",+ "call_id": "call_1",+ "action": {+ "type": "exec",+ "command": ["bash", "-c", "ls -la"],+ "working_directory": "/tmp",+ "timeout_ms": 60000+ }+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ // Critical assertion: command stays as a JSON ARRAY, not a string.+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ let cmd = &parsed["input"][0]["action"]["command"];+ assert!(cmd.is_array(), "command must remain an array on the wire");+ assert_eq!(cmd[0], json!("bash"));+ assert_eq!(cmd[1], json!("-c"));+ assert_eq!(cmd[2], json!("ls -la"));+ proxy.shutdown().await;+}++#[tokio::test]+async fn codex_phase_commentary_preserved() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "message",+ "role": "assistant",+ "phase": "commentary",+ "content": [{"type": "output_text", "text": "thinking step"}]+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ assert_eq!(parsed["input"][0]["phase"], json!("commentary"));+ proxy.shutdown().await;+}++#[tokio::test]+async fn codex_phase_final_answer_preserved() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "message",+ "role": "assistant",+ "phase": "final_answer",+ "content": [{"type": "output_text", "text": "the answer is 42"}]+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ assert_eq!(parsed["input"][0]["phase"], json!("final_answer"));+ proxy.shutdown().await;+}++#[tokio::test]+async fn compaction_item_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // Opaque encrypted blob — must round-trip verbatim. Simulate+ // ~3 KiB of base64-ish payload.+ let blob = "A".repeat(3000);+ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {"type": "compaction", "id": "k1", "encrypted_content": blob}+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}++#[tokio::test]+async fn reasoning_encrypted_content_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let blob = "encrypted-reasoning-blob-".repeat(150); // ~3.6 KiB+ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {"type": "reasoning", "id": "r1", "encrypted_content": blob}+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}++#[tokio::test]+async fn function_call_arguments_string_preserved() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // arguments is a JSON-ENCODED STRING (the model emitted it). We+ // never parse it inside the proxy.+ let args_str = r#"{"q": "hello world", "max": 10}"#;+ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "function_call",+ "id": "fc_1",+ "call_id": "call_xyz",+ "name": "search",+ "arguments": args_str+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ // arguments must arrive as a STRING (not a parsed object).+ assert_eq!(parsed["input"][0]["arguments"], json!(args_str));+ assert!(parsed["input"][0]["arguments"].is_string());+ proxy.shutdown().await;+}++#[tokio::test]+async fn call_id_referenced_not_id() {+ // The plan specifies: outputs reference parents via `call_id`,+ // not `id`. This test pins that semantic — both fields are+ // distinct and both round-trip.+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "function_call",+ "id": "fc_internal_1",+ "call_id": "call_external_99",+ "name": "search",+ "arguments": "{}"+ },+ {+ "type": "function_call_output",+ "id": "fco_internal_1",+ "call_id": "call_external_99",+ "output": "result-data"+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ // The `call_id` field on call and output must MATCH.+ let call_id_call = &parsed["input"][0]["call_id"];+ let call_id_output = &parsed["input"][1]["call_id"];+ assert_eq!(call_id_call, call_id_output);+ // And the `id` fields are DISTINCT.+ assert_ne!(parsed["input"][0]["id"], parsed["input"][1]["id"]);+ proxy.shutdown().await;+}++#[tokio::test]+async fn apply_patch_output_below_2kb_no_compression() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // ~1 KiB payload — under the 2 KiB output-item floor.+ let small = "x".repeat(1024);+ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "apply_patch_call_output",+ "id": "apo_1",+ "call_id": "call_1",+ "output": small+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}++#[tokio::test]+async fn apply_patch_output_above_2kb_compressed() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // ~8 KiB build-output style log. Repetitive lines so the+ // LogCompressor recognizes a template and produces savings.+ let mut log = String::new();+ for i in 0..200 {+ log.push_str(&format!(+ "[2024-01-01 00:00:00] INFO build.rs:42 compiled module foo_{i}\n"+ ));+ }+ assert!(log.len() > 4096, "log fixture must clearly exceed 2 KiB");++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "apply_patch_call_output",+ "id": "apo_1",+ "call_id": "call_1",+ "output": log+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ // The dispatcher should have mutated the body — either it+ // shrank or (for some fixtures) the tokenizer rejected the+ // compression. We assert it AT LEAST attempted the rewrite by+ // checking either the body shrank, or it stayed byte-equal+ // (rejected). The "above 2KB" gate is what's being tested —+ // the path was not skipped pre-dispatch.+ if got.len() == body.len() {+ // Token-validated rejection — accept.+ assert_byte_equal_sha256(&body, &got);+ } else {+ assert!(+ got.len() < body.len(),+ "body did not shrink: in={}, out={}",+ body.len(),+ got.len()+ );+ }+ proxy.shutdown().await;+}++#[tokio::test]+async fn local_shell_output_compressed() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // ~5 KiB shell-style log lines.+ let mut log = String::new();+ for i in 0..120 {+ log.push_str(&format!(+ "[2024-01-01 12:00:00] INFO daemon.rs:88 task_{i} completed in 12ms\n"+ ));+ }+ assert!(log.len() > 4096);++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "local_shell_call_output",+ "id": "lso_1",+ "call_id": "call_1",+ "output": log+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ // Either the body shrank (LogCompressor took it) or the+ // token-validated rejection kept it byte-equal. Both are valid+ // outcomes; what matters is the floor was cleared.+ if got.len() == body.len() {+ assert_byte_equal_sha256(&body, &got);+ } else {+ assert!(+ got.len() < body.len(),+ "expected shrink, got: in={}, out={}",+ body.len(),+ got.len()+ );+ }+ proxy.shutdown().await;+}++#[tokio::test]+async fn mcp_tool_call_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "mcp_call",+ "id": "mc_1",+ "server": "atlas",+ "tool": "lookup",+ "arguments": {"key": "value"},+ "result": {"ok": true, "rows": [1, 2, 3]}+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}++#[tokio::test]+async fn computer_call_byte_equal() {+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "computer_call",+ "id": "cc_1",+ "action": {"type": "click", "x": 100, "y": 200}+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}++#[tokio::test]+async fn image_generation_call_no_log_redaction_in_test_mode() {+ // Per spec: redaction is a LOG-PATH concern only. The+ // upstream-bound bytes must NOT be redacted.+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ // Synthetic small base64 payload.+ let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";+ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "image_generation_call",+ "id": "img_1",+ "status": "completed",+ "image_data": image_data+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ // Critical: image_data flows through verbatim. Redaction is+ // log-only.+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ assert_eq!(parsed["input"][0]["image_data"], json!(image_data));+ proxy.shutdown().await;+}++#[tokio::test]+async fn unknown_item_type_logged_warning_byte_equal() {+ // No-silent-fallbacks: unknown `type` logs at warn but never+ // mutates the bytes. We can't easily intercept tracing in this+ // test (the harness doesn't install a custom subscriber); we+ // assert the byte-equality contract and rely on the unit test+ // inside `live_zone_responses` for the warn-event coverage.+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {+ "type": "future_item_type_v2",+ "novel_field": "preserve me",+ "nested": {"deep": [1, 2, 3]}+ },+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "describe"}]+ }+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ let parsed: Value = serde_json::from_slice(&got).unwrap();+ assert_eq!(parsed["input"][0]["type"], json!("future_item_type_v2"));+ assert_eq!(parsed["input"][0]["novel_field"], json!("preserve me"));+ assert_eq!(parsed["input"][0]["nested"]["deep"], json!([1, 2, 3]));+ proxy.shutdown().await;+}++#[tokio::test]+async fn representative_request_round_trip() {+ // Acceptance criterion: a representative request with reasoning+ // + function_call + local_shell + apply_patch + custom items+ // round-trips byte-equal modulo compressed live-zone outputs.+ // None of the items here are above the 2 KiB output-item floor,+ // so we expect zero compression and full byte-equality.+ let upstream = MockServer::start().await;+ let captured = mount_capture(&upstream).await;+ let proxy = start_proxy_with(&upstream.uri(), |c| {+ c.compression = true;+ c.compression_mode = headroom_proxy::config::CompressionMode::LiveZone;+ })+ .await;++ let payload = json!({+ "model": "gpt-4o",+ "input": [+ {"type": "message", "role": "user",+ "content": [{"type": "input_text", "text": "fix the bug"}]},+ {"type": "reasoning", "id": "r1", "encrypted_content": "opaque-reasoning"},+ {"type": "function_call", "id": "fc_1", "call_id": "c1",+ "name": "search", "arguments": "{\"q\":\"bug\"}"},+ {"type": "function_call_output", "id": "fco_1", "call_id": "c1",+ "output": "found 3 matches"},+ {"type": "local_shell_call", "id": "ls_1", "call_id": "c2",+ "action": {"type": "exec", "command": ["cargo", "test"], "timeout_ms": 60000}},+ {"type": "local_shell_call_output", "id": "lso_1", "call_id": "c2",+ "output": "ok 12 tests passed"},+ {"type": "apply_patch_call", "id": "ap_1", "call_id": "c3",+ "operation": {"type": "apply_patch", "diff": V4A_DIFF}},+ {"type": "apply_patch_call_output", "id": "apo_1", "call_id": "c3",+ "output": "patch applied"},+ {"type": "custom_tool_call", "id": "ct_1", "tool": "myorg.foo",+ "input": {"x": 1}},+ ]+ });+ let body = serde_json::to_vec(&payload).unwrap();+ let resp = reqwest::Client::new()+ .post(format!("{}/v1/responses", proxy.url()))+ .header("content-type", "application/json")+ .body(body.clone())+ .send()+ .await+ .unwrap();+ assert_eq!(resp.status(), 200);++ let got = captured.lock().unwrap().clone().expect("upstream got body");+ assert_byte_equal_sha256(&body, &got);+ proxy.shutdown().await;+}