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
feat(simulators): add provider simulator service (#2014)
JD Davis2c9eb7c5f154
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.ymlindex 38ba308c3..4d1e28471 100644--- a/.github/workflows/rust.yml+++ b/.github/workflows/rust.yml@@ -61,6 +61,25 @@ jobs:- name: cargo testrun: cargo test --workspace+ simulator-e2e:+ name: simulator e2e (${{ matrix.os }})+ runs-on: ${{ matrix.os }}+ timeout-minutes: 30+ strategy:+ fail-fast: false+ matrix:+ os: [ubuntu-latest, macos-latest, windows-latest]+ steps:+ - uses: actions/checkout@v7+ - name: Install stable toolchain+ uses: dtolnay/rust-toolchain@stable+ with:+ toolchain: 1.95.0+ - name: Cache cargo registry + build+ uses: Swatinem/rust-cache@v2+ - name: cargo test simulator-backed proxy e2e+ run: cargo test -p headroom-proxy --test e2e_simulators+wheels:name: wheels (${{ matrix.target }})runs-on: ${{ matrix.os }}diff --git a/Cargo.lock b/Cargo.lockindex 522afa87a..e08356041 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1868,6 +1868,7 @@ dependencies = ["http 1.4.2","magika","md-5",+ "ort","proptest","rayon","redis",@@ -1915,6 +1916,7 @@ dependencies = ["futures-util","gcp_auth","headroom-core",+ "headroom-simulators","http 1.4.2","http-body-util","humantime",@@ -1954,6 +1956,26 @@ dependencies = ["serde_json",]+[[package]]+name = "headroom-simulators"+version = "0.1.0"+dependencies = [+ "axum",+ "bytes",+ "clap",+ "crc32fast",+ "http 1.4.2",+ "http-body-util",+ "reqwest",+ "serde",+ "serde_json",+ "thiserror 1.0.69",+ "tokio",+ "tower",+ "tracing",+ "tracing-subscriber",+]+[[package]]name = "heck"version = "0.5.0"diff --git a/Cargo.toml b/Cargo.tomlindex 7896c1589..07c308e1a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -3,6 +3,7 @@ resolver = "2"members = ["crates/headroom-core","crates/headroom-proxy",+ "crates/headroom-simulators","crates/headroom-py","crates/headroom-parity",]@@ -14,6 +15,7 @@ members = [default-members = ["crates/headroom-core","crates/headroom-proxy",+ "crates/headroom-simulators","crates/headroom-parity",]diff --git a/crates/headroom-core/Cargo.toml b/crates/headroom-core/Cargo.tomlindex 4b7731b48..e55e44f73 100644--- a/crates/headroom-core/Cargo.toml+++ b/crates/headroom-core/Cargo.toml@@ -140,6 +140,7 @@ fastembed = { version = "5", default-features = false, features = ["ort-load-dynamic","image-models",] }+ort = { version = "2.0.0-rc.12", default-features = false, features = ["load-dynamic"] }[target.'cfg(windows)'.dependencies]# `ort-download-binaries-*` emits DirectML link libs on Windows (`DXCORE`,@@ -150,6 +151,7 @@ fastembed = { version = "5", default-features = false, features = ["ort-load-dynamic","image-models",] }+ort = { version = "2.0.0-rc.12", default-features = false, features = ["load-dynamic"] }[features]default = []diff --git a/crates/headroom-core/src/transforms/detection.rs b/crates/headroom-core/src/transforms/detection.rsindex 3fabe96af..43b8d2f75 100644--- a/crates/headroom-core/src/transforms/detection.rs+++ b/crates/headroom-core/src/transforms/detection.rs@@ -92,7 +92,11 @@ pub fn detect(content: &str) -> ContentType {#[cfg(test)]mod tests {use super::*;- use crate::transforms::magika_detector::magika_onnx_runtime_supported_by_cpu;+ use crate::transforms::magika_detector::magika_runtime_available_for_session_init;++ fn magika_available() -> bool {+ magika_runtime_available_for_session_init().is_ok()+ }#[test]fn empty_input_short_circuits_to_plain_text() {@@ -102,37 +106,30 @@ mod tests {#[test]fn json_array_routes_via_tier_1() {let payload = r#"[{"id": 1}, {"id": 2}, {"id": 3}]"#;- if !magika_onnx_runtime_supported_by_cpu() {- // On no-AVX2 hosts, magika returns Err and the chain- // falls through to Tier 2 (unidiff — no match for JSON)- // then Tier 3 (PlainText).- assert_eq!(detect(payload), ContentType::PlainText);- } else {+ if magika_available() {assert_eq!(detect(payload), ContentType::JsonArray);+ } else {+ assert_eq!(detect(payload), ContentType::PlainText);}}#[test]fn source_code_routes_via_tier_1() {let py = "def hello():\n print('world')\n\nclass Foo:\n pass\n";- if !magika_onnx_runtime_supported_by_cpu() {- // Magika fallthrough — unidiff won't catch Python source,- // so the chain lands on PlainText.- assert_eq!(detect(py), ContentType::PlainText);- } else {+ if magika_available() {assert_eq!(detect(py), ContentType::SourceCode);+ } else {+ assert_eq!(detect(py), ContentType::PlainText);}}#[test]fn html_routes_via_tier_1() {let html = "<!DOCTYPE html><html><body><h1>x</h1></body></html>";- if !magika_onnx_runtime_supported_by_cpu() {- // Magika fallthrough — unidiff won't catch HTML,- // so the chain lands on PlainText.- assert_eq!(detect(html), ContentType::PlainText);- } else {+ if magika_available() {assert_eq!(detect(html), ContentType::Html);+ } else {+ assert_eq!(detect(html), ContentType::PlainText);}}@@ -224,12 +221,10 @@ mod tests {// YAML lives in magika's `code` group; the chain returns it// as SourceCode so the router picks the code-aware compressor.let yaml = "name: my-app\nversion: 1.0\ndependencies:\n - foo\n";- if !magika_onnx_runtime_supported_by_cpu() {- // Magika fallthrough — unidiff won't catch YAML,- // so the chain lands on PlainText.- assert_eq!(detect(yaml), ContentType::PlainText);- } else {+ if magika_available() {assert_eq!(detect(yaml), ContentType::SourceCode);+ } else {+ assert_eq!(detect(yaml), ContentType::PlainText);}}@@ -240,12 +235,10 @@ mod tests {impl Counter {\n \pub fn new() -> Self { Self { counts: HashMap::new() } }\n\}\n";- if !magika_onnx_runtime_supported_by_cpu() {- // Magika fallthrough — unidiff won't catch Rust source,- // so the chain lands on PlainText.- assert_eq!(detect(rs), ContentType::PlainText);- } else {+ if magika_available() {assert_eq!(detect(rs), ContentType::SourceCode);+ } else {+ assert_eq!(detect(rs), ContentType::PlainText);}}diff --git a/crates/headroom-core/src/transforms/magika_detector.rs b/crates/headroom-core/src/transforms/magika_detector.rsindex 1fb1d3dbf..b13419de7 100644--- a/crates/headroom-core/src/transforms/magika_detector.rs+++ b/crates/headroom-core/src/transforms/magika_detector.rs@@ -35,6 +35,11 @@//! error early instead of crashing with SIGILL; the detection chain then//! falls through to Tier 2 and Tier 3 normally.+#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+use std::path::{Path, PathBuf};use std::sync::mpsc;use std::sync::{Mutex, OnceLock};use std::time::Duration;@@ -61,6 +66,276 @@ pub(crate) fn magika_onnx_runtime_supported_by_cpu() -> bool {crate::onnx_cpu::onnx_runtime_supported_by_cpu()}+/// Check whether this process can safely initialize Magika's ONNX session.+///+/// This is stricter than the CPU check. On dynamic-ORT platforms, the runtime+/// loader must be pinned before `Session::new()` runs; otherwise Windows can+/// resolve the OS-provided `System32\onnxruntime.dll` and hang inside ORT+/// initialization. Python callers get the pin from `headroom._ort`; direct Rust+/// binaries/tests need this fail-fast guard.+pub(crate) fn magika_runtime_available_for_session_init() -> Result<(), String> {+ if !magika_onnx_runtime_supported_by_cpu() {+ return Err(+ "Magika ONNX Runtime backend requires AVX2 on this platform; \+ falling back to non-Magika detection"+ .to_string(),+ );+ }++ dynamic_ort_loader_ready()+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+static DYNAMIC_ORT_INIT: OnceLock<Result<PathBuf, String>> = OnceLock::new();++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn dynamic_ort_loader_ready() -> Result<(), String> {+ DYNAMIC_ORT_INIT+ .get_or_init(initialize_dynamic_ort)+ .as_ref()+ .map(|_| ())+ .map_err(Clone::clone)+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn initialize_dynamic_ort() -> Result<PathBuf, String> {+ let explicit = std::env::var("ORT_DYLIB_PATH")+ .ok()+ .map(|value| value.trim().to_string())+ .filter(|value| !value.is_empty());++ if let Some(path) = explicit {+ let path = PathBuf::from(path);+ if !path.is_file() {+ return Err(format!(+ "ORT_DYLIB_PATH points to a missing ONNX Runtime library: {}",+ path.display()+ ));+ }+ init_ort_from_path(&path)?;+ return Ok(path);+ }++ let mut errors = Vec::new();+ let candidates = discover_onnxruntime_libraries();+ for path in &candidates {+ match init_ort_from_path(path) {+ Ok(()) => {+ tracing::info!(+ ort_dylib_path = %path.display(),+ "initialized ONNX Runtime for Magika from discovered onnxruntime package"+ );+ return Ok(path.clone());+ }+ Err(error) => errors.push(format!("{}: {error}", path.display())),+ }+ }++ if candidates.is_empty() {+ Err(+ "no pip onnxruntime native library was found for Magika dynamic ONNX Runtime loading; \+ install headroom-ai[proxy], install onnxruntime, or set ORT_DYLIB_PATH"+ .to_string(),+ )+ } else {+ Err(format!(+ "failed to initialize ONNX Runtime for Magika from discovered libraries: {}",+ errors.join("; ")+ ))+ }+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn init_ort_from_path(path: &Path) -> Result<(), String> {+ let builder = ort::init_from(path).map_err(|error| {+ format!(+ "failed to load ONNX Runtime from `{}`: {error}",+ path.display()+ )+ })?;+ let _committed = builder.commit();+ Ok(())+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn discover_onnxruntime_libraries() -> Vec<PathBuf> {+ let mut roots = Vec::new();++ for var in ["VIRTUAL_ENV", "CONDA_PREFIX"] {+ if let Some(root) = env_path(var) {+ roots.push(root);+ }+ }++ if let Ok(cwd) = std::env::current_dir() {+ roots.push(cwd.join(".venv"));+ roots.push(cwd.join("venv"));+ }++ if let Some(user_profile) = env_path("USERPROFILE") {+ roots.extend(versioned_children(+ user_profile+ .join(".pyenv")+ .join("pyenv-win")+ .join("versions"),+ ));+ roots.extend(versioned_children(+ user_profile+ .join("AppData")+ .join("Local")+ .join("Programs")+ .join("Python"),+ ));+ roots.extend(versioned_children(+ user_profile.join("AppData").join("Roaming").join("Python"),+ ));+ }++ if let Some(home) = env_path("HOME") {+ roots.extend(versioned_children(home.join(".pyenv").join("versions")));+ roots.push(home.join(".local"));+ }++ let mut candidates = Vec::new();+ for root in roots {+ candidates.extend(onnxruntime_candidates_under(&root));+ }+ dedup_existing_files(candidates)+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn env_path(name: &str) -> Option<PathBuf> {+ std::env::var_os(name)+ .map(PathBuf::from)+ .filter(|path| !path.as_os_str().is_empty())+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn versioned_children(root: PathBuf) -> Vec<PathBuf> {+ let mut children = std::fs::read_dir(root)+ .ok()+ .into_iter()+ .flat_map(|entries| entries.filter_map(Result::ok))+ .map(|entry| entry.path())+ .filter(|path| path.is_dir())+ .collect::<Vec<_>>();+ children.sort_by(|a, b| b.cmp(a));+ children+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn onnxruntime_candidates_under(root: &Path) -> Vec<PathBuf> {+ #[cfg(target_os = "windows")]+ {+ vec![+ root.join("Lib")+ .join("site-packages")+ .join("onnxruntime")+ .join("capi")+ .join("onnxruntime.dll"),+ root.join("site-packages")+ .join("onnxruntime")+ .join("capi")+ .join("onnxruntime.dll"),+ ]+ }++ #[cfg(all(target_os = "macos", target_arch = "x86_64"))]+ {+ let mut candidates = Vec::new();+ for site_packages in python_site_packages_dirs(root) {+ let capi = site_packages.join("onnxruntime").join("capi");+ candidates.extend(onnxruntime_dylibs_in(&capi));+ }+ candidates+ }+}++#[cfg(all(target_os = "macos", target_arch = "x86_64"))]+fn python_site_packages_dirs(root: &Path) -> Vec<PathBuf> {+ let mut dirs = vec![root.join("lib").join("site-packages")];+ let lib = root.join("lib");+ dirs.extend(+ std::fs::read_dir(lib)+ .ok()+ .into_iter()+ .flat_map(|entries| entries.filter_map(Result::ok))+ .map(|entry| entry.path())+ .filter(|path| {+ path.is_dir()+ && path+ .file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("python"))+ })+ .map(|path| path.join("site-packages")),+ );+ dirs+}++#[cfg(all(target_os = "macos", target_arch = "x86_64"))]+fn onnxruntime_dylibs_in(capi: &Path) -> Vec<PathBuf> {+ let mut dylibs = std::fs::read_dir(capi)+ .ok()+ .into_iter()+ .flat_map(|entries| entries.filter_map(Result::ok))+ .map(|entry| entry.path())+ .filter(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("libonnxruntime") && name.ends_with(".dylib"))+ })+ .collect::<Vec<_>>();+ dylibs.sort();+ dylibs+}++#[cfg(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+))]+fn dedup_existing_files(paths: Vec<PathBuf>) -> Vec<PathBuf> {+ let mut out = Vec::new();+ for path in paths {+ if path.is_file() && !out.iter().any(|seen| seen == &path) {+ out.push(path);+ }+ }+ out+}++#[cfg(not(any(+ target_os = "windows",+ all(target_os = "macos", target_arch = "x86_64")+)))]+fn dynamic_ort_loader_ready() -> Result<(), String> {+ Ok(())+}+/// Errors from the magika detector. Wraps the underlying `magika::Error`/// so callers can match on whether init or inference broke without/// pulling magika types into their imports.@@ -124,15 +399,11 @@ fn magika_init_timeout() -> Duration {fn session() -> &'static Mutex<Result<Session, String>> {MAGIKA_SESSION.get_or_init(|| {- // Early-out if the CPU can't run the precompiled ONNX Runtime.- // Without this check the `onnxruntime` shared library will crash- // with SIGILL on x86 CPUs lacking AVX2.- if !magika_onnx_runtime_supported_by_cpu() {- return Mutex::new(Err(- "Magika ONNX Runtime backend requires AVX2 on this platform; \- falling back to non-Magika detection"- .to_string(),- ));+ // Early-out if ORT is known to be unsafe or unavailable in this+ // process. This avoids both SIGILL on unsupported CPUs and Windows+ // deadlocks from unpinned dynamic ONNX Runtime loading.+ if let Err(error) = magika_runtime_available_for_session_init() {+ return Mutex::new(Err(error));}let timeout = magika_init_timeout();@@ -267,18 +538,17 @@ mod tests {use super::*;fn assert_detect(content: &str, expected: ContentType, hint: &str) {- if !magika_onnx_runtime_supported_by_cpu() {- // On x86 hosts without AVX2 the magika session returns Err- // before any ONNX init — assert graceful degradation- // rather than panicking.+ if let Err(init_reason) = magika_runtime_available_for_session_init() {+ // On hosts where Magika cannot safely initialize, assert graceful+ // degradation rather than panicking or hanging.match magika_detect(content) {Err(MagikaDetectorError::Init(msg)) => {assert!(- msg.contains("AVX2"),- "{hint}: expected AVX2 error, got: {msg}"+ msg == init_reason,+ "{hint}: expected init error {init_reason:?}, got: {msg:?}");}- other => panic!("{hint}: on no-AVX2 host expected Init(AVX2) error, got {other:?}"),+ other => panic!("{hint}: expected Magika init error, got {other:?}"),}} else {match magika_detect(content) {@@ -419,25 +689,23 @@ index abc123..def456 100644#[test]fn singleton_session_is_reused_across_calls() {// Two back-to-back calls should reuse the same session- // (or same cached error). On AVX2 hosts the session is- // Ok and repeated calls succeed; on no-AVX2 hosts the- // session is Err and repeated calls return the same Err.- if !magika_onnx_runtime_supported_by_cpu() {- // On no-AVX2 the singleton caches the init error;- // repeated calls all return the same Init error.+ // (or same cached error). When the Magika runtime is available the+ // session is Ok and repeated calls succeed; otherwise the session is+ // Err and repeated calls return the same Err.+ if let Err(init_reason) = magika_runtime_available_for_session_init() {let r1 = magika_detect("hello world");let r2 = magika_detect("def f(): pass");let r3 = magika_detect(r#"{"a":1}"#);for r in [&r1, &r2, &r3] {match r {Err(MagikaDetectorError::Init(msg)) => {- assert!(msg.contains("AVX2"), "expected AVX2 error, got: {msg}");+ assert_eq!(msg, &init_reason);}- other => panic!("on no-AVX2 host expected Init(AVX2) error, got {other:?}"),+ other => panic!("expected Magika init error, got {other:?}"),}}} else {- // On AVX2 hosts the session loads once and all calls+ // On available hosts the session loads once and all calls// succeed. Wall-clock asymmetry (cold ~50 ms, warm// <1 ms) confirms reuse.magika_detect("hello world").unwrap();@@ -476,4 +744,29 @@ index abc123..def456 100644assert_eq!(map_magika_label("txt"), ContentType::PlainText);assert_eq!(map_magika_label("empty"), ContentType::PlainText);}++ #[cfg(target_os = "windows")]+ #[test]+ fn windows_onnxruntime_candidate_matches_pip_layout() {+ let root = std::env::temp_dir().join(format!(+ "headroom-ort-discovery-{}",+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_nanos()+ ));+ let dll = root+ .join("Lib")+ .join("site-packages")+ .join("onnxruntime")+ .join("capi")+ .join("onnxruntime.dll");+ std::fs::create_dir_all(dll.parent().unwrap()).unwrap();+ std::fs::write(&dll, b"not a real dll").unwrap();++ let candidates = dedup_existing_files(onnxruntime_candidates_under(&root));+ assert_eq!(candidates, vec![dll]);++ let _ = std::fs::remove_dir_all(root);+ }}diff --git a/crates/headroom-proxy/Cargo.toml b/crates/headroom-proxy/Cargo.tomlindex b5a3efbad..898645e9d 100644--- a/crates/headroom-proxy/Cargo.toml+++ b/crates/headroom-proxy/Cargo.toml@@ -117,3 +117,4 @@ sha2 = "0.10"# noise). 100K cases is the project default for "no panic" parser# invariants — see `feedback_realignment_build_constraints.md`.proptest = "1"+headroom-simulators = { path = "../headroom-simulators" }diff --git a/crates/headroom-proxy/tests/e2e_simulators.rs b/crates/headroom-proxy/tests/e2e_simulators.rsnew file mode 100644index 000000000..5542e9e03--- /dev/null+++ b/crates/headroom-proxy/tests/e2e_simulators.rs@@ -0,0 +1,577 @@+//! End-to-end proxy tests backed by the Rust provider simulators.+//!+//! These tests run Headroom and the simulator in-process. The client only+//! talks to Headroom; Headroom must reach every provider surface through the+//! simulator, never through live provider credentials.++mod common;++use std::net::SocketAddr;++use aws_credential_types::Credentials;+use common::{install_static_token_source, start_proxy_with_state};+use headroom_simulators::config::{ConfiguredResponse, SimulatorConfig, StubRule};+use headroom_simulators::{build_app as build_simulator_app, Simulator};+use serde_json::{json, Value};+use tokio::sync::oneshot;+use url::Url;++const BEDROCK_MODEL: &str = "anthropic.claude-3-haiku-20240307-v1:0";+const VERTEX_PROJECT: &str = "headroom-simulator-e2e";+const VERTEX_LOCATION: &str = "us-central1";+const VERTEX_MODEL: &str = "claude-3-5-sonnet@20240620";+const TEST_BEARER: &str = "ya29.simulator-e2e-token";++struct SimulatorHandle {+ addr: SocketAddr,+ shutdown: Option<oneshot::Sender<()>>,+ task: tokio::task::JoinHandle<()>,+}++impl SimulatorHandle {+ fn url(&self) -> String {+ format!("http://{}", self.addr)+ }++ async fn shutdown(mut self) {+ if let Some(tx) = self.shutdown.take() {+ let _ = tx.send(());+ }+ let _ = self.task.await;+ }+}++async fn start_simulator() -> SimulatorHandle {+ start_simulator_with_config(SimulatorConfig::default()).await+}++async fn start_simulator_with_config(config: SimulatorConfig) -> SimulatorHandle {+ let app = build_simulator_app(Simulator::new(config)).into_make_service();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind simulator");+ let addr = listener.local_addr().expect("simulator addr");+ let (tx, rx) = oneshot::channel::<()>();+ let task = tokio::spawn(async move {+ let _ = axum::serve(listener, app)+ .with_graceful_shutdown(async move {+ let _ = rx.await;+ })+ .await;+ });+ SimulatorHandle {+ addr,+ shutdown: Some(tx),+ task,+ }+}++fn test_credentials() -> Credentials {+ Credentials::new(+ "SIMULATOR_ACCESS_KEY_ID",+ "simulator-secret-key-not-real",+ None,+ None,+ "simulator-e2e",+ )+}++async fn start_simulator_proxy(simulator_url: &str) -> common::ProxyHandle {+ let bedrock_endpoint: Url = simulator_url.parse().expect("simulator url");+ start_proxy_with_state(+ simulator_url,+ |c| {+ c.compression = false;+ c.bedrock_endpoint = Some(bedrock_endpoint);+ c.enable_bedrock_native = true;+ c.enable_responses_streaming = true;+ c.enable_conversations_passthrough = true;+ },+ |s| {+ install_static_token_source(s.with_bedrock_credentials(test_credentials()), TEST_BEARER)+ },+ )+ .await+}++async fn start_simulator_proxy_without_bedrock_credentials(+ simulator_url: &str,+) -> common::ProxyHandle {+ let bedrock_endpoint: Url = simulator_url.parse().expect("simulator url");+ start_proxy_with_state(+ simulator_url,+ |c| {+ c.compression = false;+ c.bedrock_endpoint = Some(bedrock_endpoint);+ c.enable_bedrock_native = true;+ c.enable_responses_streaming = true;+ c.enable_conversations_passthrough = true;+ },+ |s| install_static_token_source(s, TEST_BEARER),+ )+ .await+}++fn assert_simulator_header(resp: &reqwest::Response) {+ assert_eq!(+ resp.headers()+ .get("x-headroom-simulator")+ .and_then(|v| v.to_str().ok()),+ Some("true"),+ "response must have come from the simulator"+ );+}++fn assert_not_simulator_response(resp: &reqwest::Response) {+ assert!(+ resp.headers().get("x-headroom-simulator").is_none(),+ "proxy-owned preflight errors must not be simulator responses"+ );+}++fn json_error_stub(+ name: &str,+ path: &str,+ body_contains: &str,+ status: u16,+ error_type: &str,+) -> StubRule {+ StubRule {+ name: name.to_string(),+ method: Some("POST".to_string()),+ path: path.to_string(),+ body_contains: Some(body_contains.to_string()),+ body_json_pointer: None,+ response: ConfiguredResponse {+ status,+ headers: [("x-simulator-error-path".to_string(), name.to_string())].into(),+ json: Some(json!({+ "error": {+ "type": error_type,+ "message": format!("simulated {name}")+ }+ })),+ body: None,+ sse: vec![],+ },+ }+}++async fn json_post(+ client: &reqwest::Client,+ url: impl Into<String>,+ body: Value,+) -> reqwest::Response {+ client+ .post(url.into())+ .header("content-type", "application/json")+ .json(&body)+ .send()+ .await+ .expect("request succeeds")+}++#[tokio::test]+async fn proxy_health_confirms_simulator_upstream() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();++ let own: Value = client+ .get(format!("{}/healthz", proxy.url()))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(own["ok"], json!(true));++ let upstream: Value = client+ .get(format!("{}/healthz/upstream", proxy.url()))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(upstream["ok"], json!(true));++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn anthropic_messages_json_and_stream_use_simulator() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();++ let resp = json_post(+ &client,+ format!("{}/v1/messages", proxy.url()),+ json!({"model":"claude-3-5-sonnet","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}),+ )+ .await;+ assert_eq!(resp.status(), 200);+ assert_simulator_header(&resp);+ let body: Value = resp.json().await.unwrap();+ assert_eq!(body["type"], json!("message"));+ assert_eq!(+ body["content"][0]["text"],+ json!("simulated anthropic response")+ );++ let stream = json_post(+ &client,+ format!("{}/v1/messages", proxy.url()),+ json!({"model":"claude-3-5-sonnet","max_tokens":32,"stream":true,"messages":[{"role":"user","content":"stream"}]}),+ )+ .await;+ assert_eq!(stream.status(), 200);+ assert_simulator_header(&stream);+ let text = stream.text().await.unwrap();+ assert!(text.contains("event: message_start"));+ assert!(text.contains("simulated anthropic stream"));++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn openai_chat_responses_and_conversations_use_simulator() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();++ let chat = json_post(+ &client,+ format!("{}/v1/chat/completions", proxy.url()),+ json!({"model":"gpt-4o","messages":[{"role":"user","content":"hi"}]}),+ )+ .await;+ assert_eq!(chat.status(), 200);+ assert_simulator_header(&chat);+ let chat_body: Value = chat.json().await.unwrap();+ assert_eq!(chat_body["object"], json!("chat.completion"));++ let chat_stream = json_post(+ &client,+ format!("{}/v1/chat/completions", proxy.url()),+ json!({"model":"gpt-4o","stream":true,"messages":[{"role":"user","content":"hi"}]}),+ )+ .await;+ assert_eq!(chat_stream.status(), 200);+ assert_simulator_header(&chat_stream);+ assert!(chat_stream.text().await.unwrap().contains("[DONE]"));++ let responses = json_post(+ &client,+ format!("{}/v1/responses", proxy.url()),+ json!({"model":"gpt-5","input":"hi"}),+ )+ .await;+ assert_eq!(responses.status(), 200);+ assert_simulator_header(&responses);+ let responses_body: Value = responses.json().await.unwrap();+ assert_eq!(responses_body["object"], json!("response"));++ let responses_stream = json_post(+ &client,+ format!("{}/v1/responses", proxy.url()),+ json!({"model":"gpt-5","input":"hi","stream":true}),+ )+ .await;+ assert_eq!(responses_stream.status(), 200);+ assert_simulator_header(&responses_stream);+ let responses_stream_text = responses_stream.text().await.unwrap();+ assert!(responses_stream_text.contains("event: response.created"));+ assert!(responses_stream_text.contains("event: response.completed"));++ let conversation = json_post(+ &client,+ format!("{}/v1/conversations", proxy.url()),+ json!({"metadata":{"suite":"simulator-e2e"}}),+ )+ .await;+ assert_eq!(conversation.status(), 200);+ assert_simulator_header(&conversation);+ let conversation_body: Value = conversation.json().await.unwrap();+ assert_eq!(conversation_body["id"], json!("conv_sim_0001"));++ let item = json_post(+ &client,+ format!("{}/v1/conversations/conv_sim_0001/items", proxy.url()),+ json!({"items":[{"type":"message","role":"user","content":"persist me"}]}),+ )+ .await;+ assert_eq!(item.status(), 200);+ assert_simulator_header(&item);+ let item_body: Value = item.json().await.unwrap();+ assert_eq!(item_body["object"], json!("conversation.item"));++ let listed: Value = client+ .get(format!(+ "{}/v1/conversations/conv_sim_0001/items",+ proxy.url()+ ))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(listed["object"], json!("list"));++ let delete = client+ .delete(format!(+ "{}/v1/conversations/conv_sim_0001/items/item_sim_0001",+ proxy.url()+ ))+ .send()+ .await+ .unwrap();+ assert_eq!(delete.status(), 200);+ assert_simulator_header(&delete);+ let delete_body: Value = delete.json().await.unwrap();+ assert_eq!(delete_body["deleted"], json!(true));++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn bedrock_invoke_converse_and_streaming_use_simulator() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();+ let body = json!({+ "anthropic_version":"bedrock-2023-05-31",+ "max_tokens":32,+ "messages":[{"role":"user","content":"hi"}]+ });++ for action in ["invoke", "converse"] {+ let resp = json_post(+ &client,+ format!("{}/model/{BEDROCK_MODEL}/{action}", proxy.url()),+ body.clone(),+ )+ .await;+ assert_eq!(resp.status(), 200, "{action}");+ assert_simulator_header(&resp);+ let json: Value = resp.json().await.unwrap();+ assert_eq!(json["role"], json!("assistant"));+ assert_eq!(+ json["content"][0]["text"],+ json!("simulated bedrock anthropic response")+ );+ }++ let sse = json_post(+ &client,+ format!(+ "{}/model/{BEDROCK_MODEL}/invoke-with-response-stream",+ proxy.url()+ ),+ body.clone(),+ )+ .await;+ assert_eq!(sse.status(), 200);+ assert_simulator_header(&sse);+ let sse_text = sse.text().await.unwrap();+ assert!(sse_text.contains("data: "));+ assert!(sse_text.contains("message_start"));++ let binary = client+ .post(format!(+ "{}/model/{BEDROCK_MODEL}/converse-stream",+ proxy.url()+ ))+ .header("content-type", "application/json")+ .header("accept", "application/vnd.amazon.eventstream")+ .json(&body)+ .send()+ .await+ .unwrap();+ assert_eq!(binary.status(), 200);+ assert_simulator_header(&binary);+ let bytes = binary.bytes().await.unwrap();+ assert!(bytes.len() > 16);+ let total_len = u32::from_be_bytes(bytes[0..4].try_into().unwrap()) as usize;+ assert_eq!(total_len, bytes.len());++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn vertex_raw_and_stream_predict_use_simulator() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();++ let raw_url = format!(+ "{}/v1beta1/projects/{VERTEX_PROJECT}/locations/{VERTEX_LOCATION}/publishers/anthropic/models/{VERTEX_MODEL}:rawPredict",+ proxy.url()+ );+ let stream_url = format!(+ "{}/v1beta1/projects/{VERTEX_PROJECT}/locations/{VERTEX_LOCATION}/publishers/anthropic/models/{VERTEX_MODEL}:streamRawPredict",+ proxy.url()+ );++ let raw = json_post(+ &client,+ raw_url,+ json!({"anthropic_version":"vertex-2023-10-16","max_tokens":32,"messages":[{"role":"user","content":"hi"}]}),+ )+ .await;+ assert_eq!(raw.status(), 200);+ assert_simulator_header(&raw);+ let raw_body: Value = raw.json().await.unwrap();+ assert_eq!(+ raw_body["model"],+ json!("headroom-simulator-vertex-anthropic")+ );++ let stream = json_post(+ &client,+ stream_url,+ json!({"anthropic_version":"vertex-2023-10-16","stream":true,"max_tokens":32,"messages":[{"role":"user","content":"hi"}]}),+ )+ .await;+ assert_eq!(stream.status(), 200);+ assert_simulator_header(&stream);+ let text = stream.text().await.unwrap();+ assert!(text.contains("event: message_start"));+ assert!(text.contains("simulated anthropic stream"));++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn simulator_provider_errors_flow_through_headroom() {+ let vertex_path = format!(+ "/v1beta1/projects/{VERTEX_PROJECT}/locations/{VERTEX_LOCATION}/publishers/anthropic/models/{VERTEX_MODEL}:rawPredict"+ );+ let simulator = start_simulator_with_config(SimulatorConfig {+ stubs: vec![+ json_error_stub(+ "openai-rate-limit",+ "/v1/chat/completions",+ "rate-limit-me",+ 429,+ "rate_limit_error",+ ),+ json_error_stub(+ "anthropic-overloaded",+ "/v1/messages",+ "server-error-me",+ 529,+ "overloaded_error",+ ),+ json_error_stub(+ "bedrock-upstream-fault",+ &format!("/model/{BEDROCK_MODEL}/invoke"),+ "bedrock-fail",+ 502,+ "bedrock_upstream_error",+ ),+ json_error_stub(+ "vertex-upstream-fault",+ &vertex_path,+ "vertex-fail",+ 503,+ "vertex_upstream_error",+ ),+ ],+ })+ .await;+ let proxy = start_simulator_proxy(&simulator.url()).await;+ let client = reqwest::Client::new();++ let cases = [+ (+ format!("{}/v1/chat/completions", proxy.url()),+ json!({"model":"gpt-4o","messages":[{"role":"user","content":"rate-limit-me"}]}),+ 429,+ "rate_limit_error",+ ),+ (+ format!("{}/v1/messages", proxy.url()),+ json!({"model":"claude-3-5-sonnet","max_tokens":32,"messages":[{"role":"user","content":"server-error-me"}]}),+ 529,+ "overloaded_error",+ ),+ (+ format!("{}/model/{BEDROCK_MODEL}/invoke", proxy.url()),+ json!({"anthropic_version":"bedrock-2023-05-31","max_tokens":32,"messages":[{"role":"user","content":"bedrock-fail"}]}),+ 502,+ "bedrock_upstream_error",+ ),+ (+ format!("{}{}", proxy.url(), vertex_path),+ json!({"anthropic_version":"vertex-2023-10-16","max_tokens":32,"messages":[{"role":"user","content":"vertex-fail"}]}),+ 503,+ "vertex_upstream_error",+ ),+ ];++ for (url, body, expected_status, expected_type) in cases {+ let resp = json_post(&client, url, body).await;+ assert_eq!(resp.status().as_u16(), expected_status);+ assert_simulator_header(&resp);+ assert!(+ resp.headers().get("x-simulator-error-path").is_some(),+ "configured simulator error path should survive Headroom response filtering"+ );+ let error_body: Value = resp.json().await.unwrap();+ assert_eq!(error_body["error"]["type"], json!(expected_type));+ }++ proxy.shutdown().await;+ simulator.shutdown().await;+}++#[tokio::test]+async fn headroom_preflight_errors_stop_before_simulator_fallback() {+ let simulator = start_simulator().await;+ let proxy = start_simulator_proxy_without_bedrock_credentials(&simulator.url()).await;+ let client = reqwest::Client::new();++ let bedrock = json_post(+ &client,+ format!("{}/model/{BEDROCK_MODEL}/invoke", proxy.url()),+ json!({+ "anthropic_version":"bedrock-2023-05-31",+ "max_tokens":32,+ "messages":[{"role":"user","content":"must not be forwarded unsigned"}]+ }),+ )+ .await;+ assert_eq!(bedrock.status(), 500);+ assert_not_simulator_response(&bedrock);+ let bedrock_body: Value = bedrock.json().await.unwrap();+ assert_eq!(+ bedrock_body["error"]["type"],+ json!("bedrock_credentials_missing")+ );++ let vertex = json_post(+ &client,+ format!(+ "{}/v1beta1/projects/{VERTEX_PROJECT}/locations/{VERTEX_LOCATION}/publishers/anthropic/models/{VERTEX_MODEL}:rawPredict",+ proxy.url()+ ),+ json!({"model":"must-not-be-in-vertex-envelope","messages":[]}),+ )+ .await;+ assert_eq!(vertex.status(), 400);+ assert_not_simulator_response(&vertex);+ let vertex_body = vertex.text().await.unwrap();+ assert_eq!(vertex_body, "vertex envelope invalid");++ proxy.shutdown().await;+ simulator.shutdown().await;+}diff --git a/crates/headroom-simulators/Cargo.toml b/crates/headroom-simulators/Cargo.tomlnew file mode 100644index 000000000..5f07dd5fd--- /dev/null+++ b/crates/headroom-simulators/Cargo.toml@@ -0,0 +1,34 @@+[package]+name = "headroom-simulators"+version = "0.1.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true+repository.workspace = true+description = "Configurable local provider simulators for Headroom validation pipelines."++[[bin]]+name = "headroom-simulators"+path = "src/main.rs"++[lib]+name = "headroom_simulators"+path = "src/lib.rs"++[dependencies]+axum = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "net"] }+clap = { workspace = true, features = ["derive", "env"] }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+bytes = { workspace = true }+tracing = { workspace = true }+tracing-subscriber = { version = "0.3", features = ["json", "env-filter", "fmt"] }+http = "1"+crc32fast = "1"++[dev-dependencies]+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json", "stream"] }+tower = { workspace = true, features = ["util"] }+http-body-util = "0.1"diff --git a/crates/headroom-simulators/Dockerfile b/crates/headroom-simulators/Dockerfilenew file mode 100644index 000000000..04f57f389--- /dev/null+++ b/crates/headroom-simulators/Dockerfile@@ -0,0 +1,11 @@+FROM rust:1.96-slim AS build+WORKDIR /workspace+COPY . .+RUN cargo build --release -p headroom-simulators++FROM debian:bookworm-slim+RUN useradd --create-home --uid 10001 headroom+COPY --from=build /workspace/target/release/headroom-simulators /usr/local/bin/headroom-simulators+USER headroom+EXPOSE 8789+ENTRYPOINT ["headroom-simulators"]diff --git a/crates/headroom-simulators/README.md b/crates/headroom-simulators/README.mdnew file mode 100644index 000000000..83edf4357--- /dev/null+++ b/crates/headroom-simulators/README.md@@ -0,0 +1,30 @@+# Headroom Simulators++`headroom-simulators` is a local, deterministic upstream for Headroom proxy tests.+It serves provider-shaped responses without contacting real LLM APIs.++```bash+cargo run -p headroom-simulators -- --listen 127.0.0.1:8789+```++Optional JSON config:++```json+{+ "stubs": [+ {+ "name": "exact chat smoke",+ "method": "POST",+ "path": "/v1/chat/completions",+ "body_contains": "ping",+ "response": {+ "status": 200,+ "headers": {"x-simulator": "configured"},+ "json": {"ok": true}+ }+ }+ ]+}+```++Point the proxy at `http://127.0.0.1:8789` to run local or CI validations.diff --git a/crates/headroom-simulators/src/application.rs b/crates/headroom-simulators/src/application.rsnew file mode 100644index 000000000..b29636cf4--- /dev/null+++ b/crates/headroom-simulators/src/application.rs@@ -0,0 +1,137 @@+use bytes::Bytes;++use crate::config::{ConfiguredResponse, SimulatorConfig, StubRule};+use crate::domain::{default_response, RequestFacts, SimulatedResponse};++#[derive(Debug, Clone)]+pub struct Simulator {+ config: SimulatorConfig,+}++impl Simulator {+ pub fn new(config: SimulatorConfig) -> Self {+ Self { config }+ }++ pub fn simulate(&self, facts: &RequestFacts) -> SimulatedResponse {+ if let Some(rule) = self.config.stubs.iter().find(|rule| rule.matches(facts)) {+ tracing::info!(+ event = "simulator_stub_matched",+ stub = %rule.name,+ path = %facts.path,+ provider_path = facts.provider_path.label(),+ "configured simulator stub matched request"+ );+ return configured_response(&rule.response);+ }+ tracing::info!(+ event = "simulator_default_response",+ path = %facts.path,+ provider_path = facts.provider_path.label(),+ "using bottled simulator response"+ );+ default_response(facts)+ }+}++trait MatchesRequest {+ fn matches(&self, facts: &RequestFacts) -> bool;+}++impl MatchesRequest for StubRule {+ fn matches(&self, facts: &RequestFacts) -> bool {+ if let Some(method) = &self.method {+ if !method.eq_ignore_ascii_case(&facts.method) {+ return false;+ }+ }+ if self.path != facts.path {+ return false;+ }+ if let Some(needle) = &self.body_contains {+ let haystack = String::from_utf8_lossy(&facts.body);+ if !haystack.contains(needle) {+ return false;+ }+ }+ if let Some(pointer_match) = &self.body_json_pointer {+ let Some(json) = &facts.json else {+ return false;+ };+ if json.pointer(&pointer_match.pointer) != Some(&pointer_match.equals) {+ return false;+ }+ }+ true+ }+}++fn configured_response(config: &ConfiguredResponse) -> SimulatedResponse {+ let mut response = if !config.sse.is_empty() {+ let mut body = String::new();+ for frame in &config.sse {+ if let Some(event) = &frame.event {+ body.push_str("event: ");+ body.push_str(event);+ body.push('\n');+ }+ body.push_str("data: ");+ body.push_str(&serde_json::to_string(&frame.data).expect("stub data serializes"));+ body.push_str("\n\n");+ }+ SimulatedResponse::text(config.status, "text/event-stream", body)+ } else if let Some(json) = &config.json {+ SimulatedResponse::json(config.status, json.clone())+ } else {+ SimulatedResponse::text(+ config.status,+ "text/plain; charset=utf-8",+ Bytes::from(config.body.clone().unwrap_or_default()),+ )+ };+ response.headers.extend(config.headers.clone());+ response+}++#[cfg(test)]+mod tests {+ use axum::http::HeaderMap;+ use serde_json::json;+ use serde_json::Value;++ use super::*;+ use crate::config::{ConfiguredResponse, JsonPointerMatch, StubRule};++ #[test]+ fn exact_stub_overrides_bottled_default() {+ let simulator = Simulator::new(SimulatorConfig {+ stubs: vec![StubRule {+ name: "chat-ping".to_string(),+ method: Some("POST".to_string()),+ path: "/v1/chat/completions".to_string(),+ body_contains: None,+ body_json_pointer: Some(JsonPointerMatch {+ pointer: "/messages/0/content".to_string(),+ equals: json!("ping"),+ }),+ response: ConfiguredResponse {+ status: 202,+ headers: Default::default(),+ json: Some(json!({"configured": true})),+ body: None,+ sse: vec![],+ },+ }],+ });+ let facts = RequestFacts::new(+ "POST",+ "/v1/chat/completions",+ &HeaderMap::new(),+ Bytes::from_static(br#"{"messages":[{"content":"ping"}]}"#),+ );+ let response = simulator.simulate(&facts);+ assert_eq!(response.status, 202);+ let body: Value = serde_json::from_slice(&response.body).unwrap();+ assert_eq!(body, json!({"configured": true}));+ }+}diff --git a/crates/headroom-simulators/src/config.rs b/crates/headroom-simulators/src/config.rsnew file mode 100644index 000000000..971709e8a--- /dev/null+++ b/crates/headroom-simulators/src/config.rs@@ -0,0 +1,80 @@+use std::collections::BTreeMap;+use std::fs;+use std::path::Path;++use serde::{Deserialize, Serialize};+use serde_json::Value;+use thiserror::Error;++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(default)]+pub struct SimulatorConfig {+ pub stubs: Vec<StubRule>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StubRule {+ pub name: String,+ #[serde(default)]+ pub method: Option<String>,+ pub path: String,+ #[serde(default)]+ pub body_contains: Option<String>,+ #[serde(default)]+ pub body_json_pointer: Option<JsonPointerMatch>,+ pub response: ConfiguredResponse,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct JsonPointerMatch {+ pub pointer: String,+ pub equals: Value,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ConfiguredResponse {+ #[serde(default = "default_status")]+ pub status: u16,+ #[serde(default)]+ pub headers: BTreeMap<String, String>,+ #[serde(default)]+ pub json: Option<Value>,+ #[serde(default)]+ pub body: Option<String>,+ #[serde(default)]+ pub sse: Vec<SseFrame>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SseFrame {+ #[serde(default)]+ pub event: Option<String>,+ pub data: Value,+}++#[derive(Debug, Error)]+pub enum ConfigError {+ #[error("failed to read simulator config {path}: {source}")]+ Read {+ path: String,+ #[source]+ source: std::io::Error,+ },+ #[error("simulator config is not valid JSON: {0}")]+ Parse(#[from] serde_json::Error),+}++pub fn load_config(path: Option<&Path>) -> Result<SimulatorConfig, ConfigError> {+ let Some(path) = path else {+ return Ok(SimulatorConfig::default());+ };+ let raw = fs::read_to_string(path).map_err(|source| ConfigError::Read {+ path: path.display().to_string(),+ source,+ })?;+ Ok(serde_json::from_str(&raw)?)+}++fn default_status() -> u16 {+ 200+}diff --git a/crates/headroom-simulators/src/domain.rs b/crates/headroom-simulators/src/domain.rsnew file mode 100644index 000000000..3e3f708b9--- /dev/null+++ b/crates/headroom-simulators/src/domain.rs@@ -0,0 +1,495 @@+use std::collections::BTreeMap;++use bytes::Bytes;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ProviderPath {+ Health,+ AnthropicMessages,+ OpenAiChatCompletions,+ OpenAiResponses,+ OpenAiConversations,+ OpenAiConversation,+ OpenAiConversationItems,+ OpenAiConversationItem,+ BedrockInvoke,+ BedrockConverse,+ BedrockInvokeStream,+ BedrockConverseStream,+ VertexRawPredict,+ VertexStreamRawPredict,+ Generic,+}++impl ProviderPath {+ pub fn classify(path: &str) -> Self {+ if path == "/healthz" {+ return Self::Health;+ }+ if path == "/v1/messages" {+ return Self::AnthropicMessages;+ }+ if path == "/v1/chat/completions" {+ return Self::OpenAiChatCompletions;+ }+ if path == "/v1/responses" {+ return Self::OpenAiResponses;+ }+ if path == "/v1/conversations" {+ return Self::OpenAiConversations;+ }+ if is_conversation_item(path) {+ return Self::OpenAiConversationItem;+ }+ if is_conversation_items(path) {+ return Self::OpenAiConversationItems;+ }+ if is_conversation(path) {+ return Self::OpenAiConversation;+ }+ if path.starts_with("/model/") {+ if path.ends_with("/invoke-with-response-stream") {+ return Self::BedrockInvokeStream;+ }+ if path.ends_with("/converse-stream") {+ return Self::BedrockConverseStream;+ }+ if path.ends_with("/invoke") {+ return Self::BedrockInvoke;+ }+ if path.ends_with("/converse") {+ return Self::BedrockConverse;+ }+ }+ if path.starts_with("/v1beta1/projects/")+ && path.contains("/publishers/anthropic/models/")+ && path.ends_with(":rawPredict")+ {+ return Self::VertexRawPredict;+ }+ if path.starts_with("/v1beta1/projects/")+ && path.contains("/publishers/anthropic/models/")+ && path.ends_with(":streamRawPredict")+ {+ return Self::VertexStreamRawPredict;+ }+ Self::Generic+ }++ pub fn label(&self) -> &'static str {+ match self {+ Self::Health => "health",+ Self::AnthropicMessages => "anthropic.messages",+ Self::OpenAiChatCompletions => "openai.chat_completions",+ Self::OpenAiResponses => "openai.responses",+ Self::OpenAiConversations => "openai.conversations",+ Self::OpenAiConversation => "openai.conversation",+ Self::OpenAiConversationItems => "openai.conversation_items",+ Self::OpenAiConversationItem => "openai.conversation_item",+ Self::BedrockInvoke => "bedrock.invoke",+ Self::BedrockConverse => "bedrock.converse",+ Self::BedrockInvokeStream => "bedrock.invoke_stream",+ Self::BedrockConverseStream => "bedrock.converse_stream",+ Self::VertexRawPredict => "vertex.raw_predict",+ Self::VertexStreamRawPredict => "vertex.stream_raw_predict",+ Self::Generic => "generic",+ }+ }+}++#[derive(Debug, Clone)]+pub struct SimulatedResponse {+ pub status: u16,+ pub content_type: &'static str,+ pub headers: BTreeMap<String, String>,+ pub body: Bytes,+}++impl SimulatedResponse {+ pub fn json(status: u16, value: Value) -> Self {+ let body = serde_json::to_vec(&value).expect("static simulator JSON serializes");+ Self {+ status,+ content_type: "application/json",+ headers: BTreeMap::new(),+ body: Bytes::from(body),+ }+ }++ pub fn text(status: u16, content_type: &'static str, body: impl Into<Bytes>) -> Self {+ Self {+ status,+ content_type,+ headers: BTreeMap::new(),+ body: body.into(),+ }+ }+}++#[derive(Debug, Clone)]+pub struct RequestFacts {+ pub method: String,+ pub path: String,+ pub provider_path: ProviderPath,+ pub body: Bytes,+ pub json: Option<Value>,+ pub wants_stream: bool,+ pub wants_bedrock_eventstream: bool,+}++impl RequestFacts {+ pub fn new(method: &str, path: &str, headers: &http::HeaderMap, body: Bytes) -> Self {+ let json = serde_json::from_slice::<Value>(&body).ok();+ let wants_stream = json+ .as_ref()+ .and_then(|v| v.get("stream"))+ .and_then(|v| v.as_bool())+ .unwrap_or(false)+ || header_contains(headers, http::header::ACCEPT.as_str(), "text/event-stream");+ let wants_bedrock_eventstream = header_contains(+ headers,+ http::header::ACCEPT.as_str(),+ "application/vnd.amazon.eventstream",+ );+ Self {+ method: method.to_ascii_uppercase(),+ path: path.to_string(),+ provider_path: ProviderPath::classify(path),+ body,+ json,+ wants_stream,+ wants_bedrock_eventstream,+ }+ }+}++pub fn default_response(facts: &RequestFacts) -> SimulatedResponse {+ match facts.provider_path {+ ProviderPath::Health => SimulatedResponse::text(200, "text/plain; charset=utf-8", "ok"),+ ProviderPath::AnthropicMessages => {+ if facts.wants_stream {+ anthropic_sse()+ } else {+ anthropic_message()+ }+ }+ ProviderPath::OpenAiChatCompletions => {+ if facts.wants_stream {+ openai_chat_sse()+ } else {+ openai_chat()+ }+ }+ ProviderPath::OpenAiResponses => {+ if facts.wants_stream {+ openai_responses_sse()+ } else {+ openai_responses()+ }+ }+ ProviderPath::OpenAiConversations => conversation_collection(&facts.method),+ ProviderPath::OpenAiConversation => conversation_object(&facts.method, &facts.path),+ ProviderPath::OpenAiConversationItems => conversation_items(&facts.method, &facts.path),+ ProviderPath::OpenAiConversationItem => conversation_item(&facts.method, &facts.path),+ ProviderPath::BedrockInvoke | ProviderPath::BedrockConverse => bedrock_invoke(),+ ProviderPath::BedrockInvokeStream | ProviderPath::BedrockConverseStream => {+ if facts.wants_bedrock_eventstream {+ bedrock_eventstream()+ } else {+ anthropic_sse()+ }+ }+ ProviderPath::VertexRawPredict => vertex_predict(),+ ProviderPath::VertexStreamRawPredict => anthropic_sse(),+ ProviderPath::Generic => generic(&facts.path),+ }+}++fn anthropic_message() -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "msg_sim_0001",+ "type": "message",+ "role": "assistant",+ "model": "headroom-simulator-anthropic",+ "content": [{"type": "text", "text": "simulated anthropic response"}],+ "stop_reason": "end_turn",+ "stop_sequence": null,+ "usage": {"input_tokens": 12, "output_tokens": 4}+ }),+ )+}++fn anthropic_sse() -> SimulatedResponse {+ let body = concat!(+ "event: message_start\n",+ "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_sim_stream\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"headroom-simulator-anthropic\",\"content\":[],\"stop_reason\":null,\"usage\":{\"input_tokens\":12,\"output_tokens\":0}}}\n\n",+ "event: content_block_start\n",+ "data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n",+ "event: content_block_delta\n",+ "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"simulated anthropic stream\"}}\n\n",+ "event: content_block_stop\n",+ "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",+ "event: message_delta\n",+ "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":4}}\n\n",+ "event: message_stop\n",+ "data: {\"type\":\"message_stop\"}\n\n"+ );+ SimulatedResponse::text(200, "text/event-stream", body)+}++fn openai_chat() -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "chatcmpl-sim-0001",+ "object": "chat.completion",+ "created": 1,+ "model": "headroom-simulator-openai-chat",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": "simulated openai chat response"},+ "finish_reason": "stop"+ }],+ "usage": {"prompt_tokens": 12, "completion_tokens": 5, "total_tokens": 17}+ }),+ )+}++fn openai_chat_sse() -> SimulatedResponse {+ let body = concat!(+ "data: {\"id\":\"chatcmpl-sim-stream\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"headroom-simulator-openai-chat\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\"},\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"chatcmpl-sim-stream\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"headroom-simulator-openai-chat\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"simulated openai chat stream\"},\"finish_reason\":null}]}\n\n",+ "data: {\"id\":\"chatcmpl-sim-stream\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"headroom-simulator-openai-chat\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n",+ "data: [DONE]\n\n"+ );+ SimulatedResponse::text(200, "text/event-stream", body)+}++fn openai_responses() -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "resp_sim_0001",+ "object": "response",+ "created_at": 1,+ "model": "headroom-simulator-openai-responses",+ "status": "completed",+ "output": [{+ "id": "msg_sim_0001",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "simulated openai responses response"}]+ }],+ "usage": {"input_tokens": 12, "output_tokens": 5, "total_tokens": 17}+ }),+ )+}++fn openai_responses_sse() -> SimulatedResponse {+ let body = concat!(+ "event: response.created\n",+ "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_sim_stream\",\"status\":\"in_progress\",\"model\":\"headroom-simulator-openai-responses\"}}\n\n",+ "event: output_item.added\n",+ "data: {\"type\":\"output_item.added\",\"item\":{\"id\":\"msg_sim_stream\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[]}}\n\n",+ "event: output_text.delta\n",+ "data: {\"type\":\"output_text.delta\",\"item_id\":\"msg_sim_stream\",\"output_index\":0,\"content_index\":0,\"delta\":\"simulated openai responses stream\"}\n\n",+ "event: output_item.done\n",+ "data: {\"type\":\"output_item.done\",\"item\":{\"id\":\"msg_sim_stream\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"simulated openai responses stream\"}]}}\n\n",+ "event: response.completed\n",+ "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_sim_stream\",\"status\":\"completed\",\"usage\":{\"input_tokens\":12,\"output_tokens\":5,\"total_tokens\":17}}}\n\n"+ );+ SimulatedResponse::text(200, "text/event-stream", body)+}++fn conversation_collection(method: &str) -> SimulatedResponse {+ match method {+ "POST" => SimulatedResponse::json(+ 200,+ json!({"id":"conv_sim_0001","object":"conversation","metadata":{}}),+ ),+ _ => SimulatedResponse::json(+ 200,+ json!({"object":"list","data":[{"id":"conv_sim_0001","object":"conversation"}]}),+ ),+ }+}++fn conversation_object(method: &str, path: &str) -> SimulatedResponse {+ let id = path.rsplit('/').next().unwrap_or("conv_sim_0001");+ if method == "DELETE" {+ SimulatedResponse::json(200, json!({"id": id, "deleted": true}))+ } else {+ SimulatedResponse::json(+ 200,+ json!({"id": id, "object": "conversation", "metadata": {}}),+ )+ }+}++fn conversation_items(method: &str, path: &str) -> SimulatedResponse {+ let id = path+ .trim_end_matches("/items")+ .rsplit('/')+ .next()+ .unwrap_or("conv_sim_0001");+ if method == "POST" {+ SimulatedResponse::json(+ 200,+ json!({"id":"item_sim_0001","object":"conversation.item","conversation_id": id}),+ )+ } else {+ SimulatedResponse::json(+ 200,+ json!({"object":"list","data":[{"id":"item_sim_0001","object":"conversation.item","conversation_id": id}]}),+ )+ }+}++fn conversation_item(method: &str, path: &str) -> SimulatedResponse {+ let item_id = path.rsplit('/').next().unwrap_or("item_sim_0001");+ if method == "DELETE" {+ SimulatedResponse::json(200, json!({"id": item_id, "deleted": true}))+ } else {+ SimulatedResponse::json(200, json!({"id": item_id, "object": "conversation.item"}))+ }+}++fn bedrock_invoke() -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "msg_bedrock_sim_0001",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "simulated bedrock anthropic response"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 12, "output_tokens": 5}+ }),+ )+}++fn vertex_predict() -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "msg_vertex_sim_0001",+ "type": "message",+ "role": "assistant",+ "model": "headroom-simulator-vertex-anthropic",+ "content": [{"type": "text", "text": "simulated vertex anthropic response"}],+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 12, "output_tokens": 5}+ }),+ )+}++fn generic(path: &str) -> SimulatedResponse {+ SimulatedResponse::json(+ 200,+ json!({+ "id": "sim_generic_0001",+ "object": "headroom.simulator.response",+ "path": path,+ "message": "generic simulated response"+ }),+ )+}++fn bedrock_eventstream() -> SimulatedResponse {+ let payload = br#"{"type":"message_start","message":{"id":"msg_bedrock_stream","type":"message","role":"assistant","model":"headroom-simulator-bedrock","content":[],"stop_reason":null,"usage":{"input_tokens":12,"output_tokens":0}}}"#;+ let frame = encode_eventstream_message("chunk", payload);+ SimulatedResponse::text(200, "application/vnd.amazon.eventstream", frame)+}++fn encode_eventstream_message(event_type: &str, payload: &[u8]) -> Bytes {+ let mut headers = Vec::new();+ push_string_header(&mut headers, ":message-type", "event");+ push_string_header(&mut headers, ":event-type", event_type);+ push_string_header(&mut headers, ":content-type", "application/json");+ let total_len = 12 + headers.len() + payload.len() + 4;+ let headers_len = headers.len();+ let mut out = Vec::with_capacity(total_len);+ out.extend_from_slice(&(total_len as u32).to_be_bytes());+ out.extend_from_slice(&(headers_len as u32).to_be_bytes());+ let prelude_crc = crc32fast::hash(&out[..8]);+ out.extend_from_slice(&prelude_crc.to_be_bytes());+ out.extend_from_slice(&headers);+ out.extend_from_slice(payload);+ let message_crc = crc32fast::hash(&out);+ out.extend_from_slice(&message_crc.to_be_bytes());+ Bytes::from(out)+}++fn push_string_header(out: &mut Vec<u8>, name: &str, value: &str) {+ out.push(name.len() as u8);+ out.extend_from_slice(name.as_bytes());+ out.push(7);+ out.extend_from_slice(&(value.len() as u16).to_be_bytes());+ out.extend_from_slice(value.as_bytes());+}++fn header_contains(headers: &http::HeaderMap, name: &str, needle: &str) -> bool {+ headers+ .get(name)+ .and_then(|v| v.to_str().ok())+ .map(|v| {+ v.to_ascii_lowercase()+ .contains(&needle.to_ascii_lowercase())+ })+ .unwrap_or(false)+}++fn is_conversation(path: &str) -> bool {+ let parts: Vec<&str> = path.trim_matches('/').split('/').collect();+ parts.len() == 3 && parts[0] == "v1" && parts[1] == "conversations"+}++fn is_conversation_items(path: &str) -> bool {+ let parts: Vec<&str> = path.trim_matches('/').split('/').collect();+ parts.len() == 4 && parts[0] == "v1" && parts[1] == "conversations" && parts[3] == "items"+}++fn is_conversation_item(path: &str) -> bool {+ let parts: Vec<&str> = path.trim_matches('/').split('/').collect();+ parts.len() == 5 && parts[0] == "v1" && parts[1] == "conversations" && parts[3] == "items"+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn classifies_supported_provider_paths() {+ assert_eq!(+ ProviderPath::classify("/v1/messages"),+ ProviderPath::AnthropicMessages+ );+ assert_eq!(+ ProviderPath::classify("/v1/chat/completions"),+ ProviderPath::OpenAiChatCompletions+ );+ assert_eq!(+ ProviderPath::classify("/v1/responses"),+ ProviderPath::OpenAiResponses+ );+ assert_eq!(+ ProviderPath::classify("/v1/conversations/c/items/i"),+ ProviderPath::OpenAiConversationItem+ );+ assert_eq!(+ ProviderPath::classify("/model/anthropic.claude-3-haiku/invoke-with-response-stream"),+ ProviderPath::BedrockInvokeStream+ );+ assert_eq!(+ ProviderPath::classify(+ "/v1beta1/projects/p/locations/us/publishers/anthropic/models/claude:rawPredict"+ ),+ ProviderPath::VertexRawPredict+ );+ }+}diff --git a/crates/headroom-simulators/src/lib.rs b/crates/headroom-simulators/src/lib.rsnew file mode 100644index 000000000..11fa4d57e--- /dev/null+++ b/crates/headroom-simulators/src/lib.rs@@ -0,0 +1,14 @@+//! Deterministic provider simulators for local and CI Headroom validation.+//!+//! The crate is intentionally standalone: it behaves like a provider upstream+//! that Headroom can proxy to, but it never calls a real LLM service.++pub mod application;+pub mod config;+pub mod domain;+pub mod presentation;++pub use application::Simulator;+pub use config::{load_config, SimulatorConfig};+pub use domain::{ProviderPath, SimulatedResponse};+pub use presentation::build_app;diff --git a/crates/headroom-simulators/src/main.rs b/crates/headroom-simulators/src/main.rsnew file mode 100644index 000000000..983fb0af3--- /dev/null+++ b/crates/headroom-simulators/src/main.rs@@ -0,0 +1,69 @@+use std::net::SocketAddr;+use std::path::PathBuf;++use clap::Parser;+use headroom_simulators::{build_app, load_config, Simulator};+use tracing_subscriber::layer::SubscriberExt;+use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::EnvFilter;++#[derive(Debug, Parser)]+#[command(about = "Deterministic local upstream simulators for Headroom tests")]+struct Cli {+ #[arg(+ long,+ env = "HEADROOM_SIMULATOR_LISTEN",+ default_value = "127.0.0.1:8789"+ )]+ listen: SocketAddr,+ #[arg(long, env = "HEADROOM_SIMULATOR_CONFIG")]+ config: Option<PathBuf>,+ #[arg(long, env = "HEADROOM_SIMULATOR_LOG", default_value = "info")]+ log_level: String,+}++#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let cli = Cli::parse();+ init_tracing(&cli.log_level);+ let config = load_config(cli.config.as_deref())?;+ let simulator = Simulator::new(config);+ let app = build_app(simulator);+ let listener = tokio::net::TcpListener::bind(cli.listen).await?;+ tracing::info!(addr = %listener.local_addr()?, "headroom simulator listening");+ axum::serve(listener, app)+ .with_graceful_shutdown(shutdown_signal())+ .await?;+ Ok(())+}++fn init_tracing(level: &str) {+ let filter = EnvFilter::try_new(level).unwrap_or_else(|_| EnvFilter::new("info"));+ let json_layer = tracing_subscriber::fmt::layer()+ .json()+ .with_current_span(false)+ .with_span_list(false);+ let _ = tracing_subscriber::registry()+ .with(filter)+ .with(json_layer)+ .try_init();+}++async fn shutdown_signal() {+ let ctrl_c = async {+ let _ = tokio::signal::ctrl_c().await;+ };+ #[cfg(unix)]+ let terminate = async {+ if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())+ {+ s.recv().await;+ }+ };+ #[cfg(not(unix))]+ let terminate = std::future::pending::<()>();+ tokio::select! {+ _ = ctrl_c => {},+ _ = terminate => {},+ }+}diff --git a/crates/headroom-simulators/src/presentation.rs b/crates/headroom-simulators/src/presentation.rsnew file mode 100644index 000000000..07746b41f--- /dev/null+++ b/crates/headroom-simulators/src/presentation.rs@@ -0,0 +1,90 @@+use std::sync::Arc;++use axum::body::{to_bytes, Body};+use axum::extract::State;+use axum::http::{HeaderName, Request, Response, StatusCode};+use axum::routing::{any, get};+use axum::Router;++use crate::application::Simulator;+use crate::domain::{RequestFacts, SimulatedResponse};++const MAX_BODY_BYTES: usize = 64 * 1024 * 1024;++pub fn build_app(simulator: Simulator) -> Router {+ let state = Arc::new(simulator);+ Router::new()+ .route("/healthz", get(healthz))+ .fallback(any(simulate))+ .with_state(state)+}++async fn healthz() -> &'static str {+ "ok"+}++async fn simulate(State(simulator): State<Arc<Simulator>>, req: Request<Body>) -> Response<Body> {+ let method = req.method().as_str().to_string();+ let path = req.uri().path().to_string();+ let headers = req.headers().clone();+ let body = match to_bytes(req.into_body(), MAX_BODY_BYTES).await {+ Ok(body) => body,+ Err(err) => {+ tracing::warn!(event = "simulator_body_read_failed", error = %err);+ return response_from(SimulatedResponse::text(+ 413,+ "application/json",+ r#"{"error":"request body too large or unreadable"}"#,+ ));+ }+ };+ let facts = RequestFacts::new(&method, &path, &headers, body);+ response_from(simulator.simulate(&facts))+}++fn response_from(simulated: SimulatedResponse) -> Response<Body> {+ let status = StatusCode::from_u16(simulated.status).unwrap_or(StatusCode::OK);+ let mut builder = Response::builder()+ .status(status)+ .header(http::header::CONTENT_TYPE, simulated.content_type)+ .header("x-headroom-simulator", "true");+ for (name, value) in simulated.headers {+ match HeaderName::from_bytes(name.as_bytes()) {+ Ok(header_name) => {+ builder = builder.header(header_name, value);+ }+ Err(err) => {+ tracing::warn!(+ event = "simulator_invalid_response_header",+ header = %name,+ error = %err,+ "configured simulator header ignored"+ );+ }+ }+ }+ builder+ .body(Body::from(simulated.body))+ .expect("simulator response builds")+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::SimulatorConfig;++ #[tokio::test]+ async fn health_route_returns_ok() {+ let app = build_app(Simulator::new(SimulatorConfig::default()));+ let response = tower::ServiceExt::oneshot(+ app,+ Request::builder()+ .uri("/healthz")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), StatusCode::OK);+ }+}diff --git a/crates/headroom-simulators/tests/simulator_http.rs b/crates/headroom-simulators/tests/simulator_http.rsnew file mode 100644index 000000000..d342b8033--- /dev/null+++ b/crates/headroom-simulators/tests/simulator_http.rs@@ -0,0 +1,161 @@+use std::net::SocketAddr;++use headroom_simulators::config::{+ ConfiguredResponse, JsonPointerMatch, SimulatorConfig, StubRule,+};+use headroom_simulators::{build_app, Simulator};+use serde_json::{json, Value};+use tokio::sync::oneshot;++struct TestServer {+ addr: SocketAddr,+ shutdown: Option<oneshot::Sender<()>>,+ task: tokio::task::JoinHandle<()>,+}++impl TestServer {+ fn url(&self) -> String {+ format!("http://{}", self.addr)+ }++ async fn shutdown(mut self) {+ if let Some(tx) = self.shutdown.take() {+ let _ = tx.send(());+ }+ let _ = self.task.await;+ }+}++async fn start(config: SimulatorConfig) -> TestServer {+ let app = build_app(Simulator::new(config)).into_make_service();+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0")+ .await+ .expect("bind");+ let addr = listener.local_addr().expect("addr");+ let (tx, rx) = oneshot::channel::<()>();+ let task = tokio::spawn(async move {+ let _ = axum::serve(listener, app)+ .with_graceful_shutdown(async move {+ let _ = rx.await;+ })+ .await;+ });+ TestServer {+ addr,+ shutdown: Some(tx),+ task,+ }+}++#[tokio::test]+async fn openai_chat_default_is_provider_shaped() {+ let server = start(SimulatorConfig::default()).await;+ let response: Value = reqwest::Client::new()+ .post(format!("{}/v1/chat/completions", server.url()))+ .json(&json!({"model":"gpt-4o","messages":[{"role":"user","content":"hi"}]}))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(response["object"], "chat.completion");+ assert_eq!(response["choices"][0]["message"]["role"], "assistant");+ server.shutdown().await;+}++#[tokio::test]+async fn configured_stub_overrides_default_response() {+ let server = start(SimulatorConfig {+ stubs: vec![StubRule {+ name: "configured chat".to_string(),+ method: Some("POST".to_string()),+ path: "/v1/chat/completions".to_string(),+ body_contains: None,+ body_json_pointer: Some(JsonPointerMatch {+ pointer: "/messages/0/content".to_string(),+ equals: json!("configured"),+ }),+ response: ConfiguredResponse {+ status: 209,+ headers: [("x-test-stub".to_string(), "yes".to_string())].into(),+ json: Some(json!({"stubbed": true})),+ body: None,+ sse: vec![],+ },+ }],+ })+ .await;+ let response = reqwest::Client::new()+ .post(format!("{}/v1/chat/completions", server.url()))+ .json(&json!({"messages":[{"content":"configured"}]}))+ .send()+ .await+ .unwrap();+ assert_eq!(response.status().as_u16(), 209);+ assert_eq!(response.headers()["x-test-stub"], "yes");+ assert_eq!(+ response.json::<Value>().await.unwrap(),+ json!({"stubbed": true})+ );+ server.shutdown().await;+}++#[tokio::test]+async fn responses_stream_returns_named_sse_events() {+ let server = start(SimulatorConfig::default()).await;+ let body = reqwest::Client::new()+ .post(format!("{}/v1/responses", server.url()))+ .json(&json!({"model":"gpt-5","input":"hi","stream":true}))+ .send()+ .await+ .unwrap()+ .text()+ .await+ .unwrap();+ assert!(body.contains("event: response.created"));+ assert!(body.contains("event: response.completed"));+ server.shutdown().await;+}++#[tokio::test]+async fn bedrock_stream_can_emit_binary_eventstream() {+ let server = start(SimulatorConfig::default()).await;+ let bytes = reqwest::Client::new()+ .post(format!(+ "{}/model/anthropic.claude-3-haiku/invoke-with-response-stream",+ server.url()+ ))+ .header("accept", "application/vnd.amazon.eventstream")+ .json(&json!({"messages":[{"role":"user","content":"hi"}]}))+ .send()+ .await+ .unwrap()+ .bytes()+ .await+ .unwrap();+ assert!(bytes.len() > 16);+ let total_len = u32::from_be_bytes(bytes[0..4].try_into().unwrap()) as usize;+ assert_eq!(total_len, bytes.len());+ server.shutdown().await;+}++#[tokio::test]+async fn vertex_raw_predict_default_is_anthropic_shaped() {+ let server = start(SimulatorConfig::default()).await;+ let response: Value = reqwest::Client::new()+ .post(format!(+ "{}/v1beta1/projects/p/locations/us/publishers/anthropic/models/claude:rawPredict",+ server.url()+ ))+ .json(&json!({"anthropic_version":"vertex-2023-10-16","messages":[]}))+ .send()+ .await+ .unwrap()+ .json()+ .await+ .unwrap();+ assert_eq!(response["type"], "message");+ assert_eq!(response["role"], "assistant");+ server.shutdown().await;+}