Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Rust ai-agentsai-gatewayclaude-codecodexcoding-agentcost-optimizationdeepseekllm-gatewayllm-routerlocal-firstmodel-routingrusttask-routingtauri
Discover Codex subscription models using the installed client version (#27)
澄潭0b00b42e988a
diff --git a/apps/desktop/src-tauri/development-cpa-artifacts.v1.json b/apps/desktop/src-tauri/development-cpa-artifacts.v1.jsonindex 6e0c746b..7797d038 100644--- a/apps/desktop/src-tauri/development-cpa-artifacts.v1.json+++ b/apps/desktop/src-tauri/development-cpa-artifacts.v1.json@@ -7,11 +7,11 @@"os": "macos","arch": "aarch64","binary_name": "cliproxyapi",- "version": "7.2.140-hiroute.2",- "commit": "c76dfd4e0edabab9000628b1560ab8ab379eadb8",- "built_at": "2026-09-18T00:00:00Z",- "size": 84827682,- "sha256": "5a51825066357c7d8b0bda23e852ac0f9df57139d7ef39348d0d741c4f8d8cb1",+ "version": "8.0.4-hiroute.1",+ "commit": "a270e7b9e57aaecd8f82555f44c2108518ad2330",+ "built_at": "2026-09-29T00:00:00Z",+ "size": 88121264,+ "sha256": "836834077b2d1d0c6b6e39fa836267fc249bddffdcaa6bf403be776ca7579b3f","file_description": "Mach-O 64-bit executable arm64","dynamic_dependencies": ["/usr/lib/libSystem.B.dylib",diff --git a/apps/desktop/src-tauri/src/development_cpa.rs b/apps/desktop/src-tauri/src/development_cpa.rsindex eb7ec151..42e0460e 100644--- a/apps/desktop/src-tauri/src/development_cpa.rs+++ b/apps/desktop/src-tauri/src/development_cpa.rs@@ -127,10 +127,10 @@ mod tests {serde_json::from_str(include_str!("../development-cpa-artifacts.v1.json")).unwrap();let artifact = artifact_for(&manifest, "macos", "aarch64").unwrap();assert_eq!(artifact.target, "aarch64-apple-darwin");- assert_eq!(artifact.version, "7.2.140-hiroute.2");+ assert_eq!(artifact.version, "8.0.4-hiroute.1");assert_eq!(artifact.sha256,- "5a51825066357c7d8b0bda23e852ac0f9df57139d7ef39348d0d741c4f8d8cb1"+ "836834077b2d1d0c6b6e39fa836267fc249bddffdcaa6bf403be776ca7579b3f");}}diff --git a/crates/cpa-bridge/src/accounts.rs b/crates/cpa-bridge/src/accounts.rsindex bb3a53cf..be91a8b6 100644--- a/crates/cpa-bridge/src/accounts.rs+++ b/crates/cpa-bridge/src/accounts.rs@@ -201,6 +201,7 @@ pub(crate) trait CpaControlPlane: Send + Sync {timeout: Duration,) -> Result<(), AccountDiscoveryError>;+ #[allow(clippy::too_many_arguments)]fn discover_and_pin(&self,address: SocketAddr,@@ -209,6 +210,7 @@ pub(crate) trait CpaControlPlane: Send + Sync {secrets: &InstanceSecrets,expected_version: &str,timeout: Duration,+ refresh_models: bool,) -> Result<Vec<AccountSnapshotRecord>, AccountDiscoveryError>;}diff --git a/crates/cpa-bridge/src/accounts/stock.rs b/crates/cpa-bridge/src/accounts/stock.rsindex ad5d8108..019c0ad7 100644--- a/crates/cpa-bridge/src/accounts/stock.rs+++ b/crates/cpa-bridge/src/accounts/stock.rs@@ -76,6 +76,7 @@ impl CpaControlPlane for StockCpaControlPlane {secrets: &InstanceSecrets,expected_version: &str,timeout: Duration,+ refresh_models: bool,) -> Result<Vec<AccountSnapshotRecord>, AccountDiscoveryError> {let deadline = Instant::now().checked_add(timeout)@@ -139,14 +140,22 @@ impl CpaControlPlane for StockCpaControlPlane {let prefix = format!("hiroute-{}", &digest[..24]);(digest, prefix, 1)};- patch_account_controls(- address,- secrets,- expected_version,- remaining_timeout(deadline)?,- &account.id,- &prefix,- )?;+ // PATCH also synchronously re-registers the account in CPA, including+ // remote model discovery. Ordinary compilation/preview is a read;+ // only repair changed controls or honor an explicit subscription check.+ if refresh_models+ || account.request_retry != Some(0)+ || !persisted_controls_match(auth_dir, &name, &prefix)?+ {+ patch_account_controls(+ address,+ secrets,+ expected_version,+ remaining_timeout(deadline)?,+ &account.id,+ &prefix,+ )?;+ }let models = wait_for_account_pin(address,auth_dir,@@ -501,7 +510,7 @@ fn validate_transport_model_id(value: &str) -> Result<(), AccountDiscoveryError>mod tests {use super::*;- fn oauth_response(extra: &str) -> Vec<u8> {+ pub(super) fn oauth_response(extra: &str) -> Vec<u8> {format!(r#"{{"files":[{{"id":"codex-a.json","auth_index":"idx-a","name":"codex-a.json","type":"codex","provider":"codex","status":"active","disabled":false,"unavailable":false,"runtime_only":false,"source":"file","account_type":"oauth","request_retry":0{extra}}}]}}"#)@@ -576,3 +585,6 @@ mod tests {assert!(strip_exact_prefix(&BTreeSet::from(["codex-model".into()]), &prefix).is_err());}}++#[cfg(test)]+mod pin_tests;diff --git a/crates/cpa-bridge/src/accounts/stock/pin_tests.rs b/crates/cpa-bridge/src/accounts/stock/pin_tests.rsnew file mode 100644index 00000000..847a815f--- /dev/null+++ b/crates/cpa-bridge/src/accounts/stock/pin_tests.rs@@ -0,0 +1,195 @@+//! Exercise the real stock control HTTP entry, not a mocked CpaControlPlane.+use super::*;+use std::io::{Read, Write};+use std::net::TcpListener;+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};++struct Fixture {+ root: tempfile::TempDir,+ address: SocketAddr,+ patches: Arc<AtomicUsize>,+ reject_patch: Arc<AtomicBool>,+ stop: Arc<AtomicBool>,+ worker: Option<thread::JoinHandle<()>>,+}++impl Fixture {+ fn new() -> Self {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("codex-a.json");+ fs::write(+ &path,+ br#"{"prefix":"hiroute-codex-current","request_retry":0,"disable_cooling":true}"#,+ )+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ fs::set_permissions(path, fs::Permissions::from_mode(0o600)).unwrap();+ }+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();+ let address = listener.local_addr().unwrap();+ let patches = Arc::new(AtomicUsize::new(0));+ let reject_patch = Arc::new(AtomicBool::new(false));+ let stop = Arc::new(AtomicBool::new(false));+ let (count, reject, stopped) = (patches.clone(), reject_patch.clone(), stop.clone());+ let worker = thread::spawn(move || {+ for stream in listener.incoming() {+ let mut stream = stream.unwrap();+ if stopped.load(Ordering::SeqCst) {+ break;+ }+ stream+ .set_read_timeout(Some(Duration::from_secs(2)))+ .unwrap();+ let mut bytes = Vec::new();+ let mut byte = [0];+ while !bytes.ends_with(b"\r\n\r\n") {+ stream.read_exact(&mut byte).unwrap();+ bytes.push(byte[0]);+ }+ let header = String::from_utf8(bytes).unwrap();+ let length: usize = header+ .lines()+ .find_map(|line| line.strip_prefix("Content-Length: "))+ .unwrap()+ .parse()+ .unwrap();+ let mut body = vec![0; length];+ stream.read_exact(&mut body).unwrap();+ let (status, body) = if header.starts_with("PATCH ") {+ count.fetch_add(1, Ordering::SeqCst);+ let body: Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(body["prefix"], "hiroute-codex-current");+ if reject.load(Ordering::SeqCst) {+ (503, "{}".to_owned())+ } else {+ (200, "{}".to_owned())+ }+ } else if header.starts_with("GET /v0/management/auth-files?name=") {+ (+ 200,+ String::from_utf8(super::tests::oauth_response("")).unwrap(),+ )+ } else if header.starts_with("GET /v0/management/auth-files/models?") {+ (+ 200,+ r#"{"models":[{"id":"hiroute-codex-current/future-model"}]}"#.to_owned(),+ )+ } else if header.starts_with("GET /v1/models ") {+ (+ 200,+ r#"{"data":[{"id":"hiroute-codex-current/future-model"}]}"#.to_owned(),+ )+ } else {+ panic!("unexpected request: {}", header.lines().next().unwrap());+ };+ write!(stream, "HTTP/1.1 {status} OK\r\nX-CPA-Version: 8.0.4-hiroute.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).unwrap();+ }+ });+ Self {+ root,+ address,+ patches,+ reject_patch,+ stop,+ worker: Some(worker),+ }+ }++ fn discover(&self, refresh: bool) -> Result<Vec<AccountSnapshotRecord>, AccountDiscoveryError> {+ StockCpaControlPlane.discover_and_pin(+ self.address,+ self.root.path(),+ &[ManagedAccountIdentity {+ account_kind: CpaAccountKind::Codex,+ stock_file_name: "codex-a.json".into(),+ account_digest: "a".repeat(64),+ generation: 1,+ }],+ &InstanceSecrets::generate().unwrap(),+ "8.0.4-hiroute.1",+ Duration::from_secs(2),+ refresh,+ )+ }+}++impl Drop for Fixture {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::SeqCst);+ let _ = std::net::TcpStream::connect(self.address);+ self.worker.take().unwrap().join().unwrap();+ }+}++#[test]+fn repeated_pin_reads_do_not_refresh_remote_catalog() {+ let fixture = Fixture::new();+ fixture.discover(true).unwrap();+ assert_eq!(fixture.patches.load(Ordering::SeqCst), 1);+ // The refresh path is now unavailable. All four compilation reads and+ // subsequent preview must still use the verified, already registered models.+ fixture.reject_patch.store(true, Ordering::SeqCst);+ for _ in 0..6 {+ let accounts = fixture.discover(false).unwrap();+ assert_eq!(+ accounts[0].observed_model_ids,+ BTreeSet::from(["future-model".into()])+ );+ }+ assert_eq!(fixture.patches.load(Ordering::SeqCst), 1);+ assert!(fixture.discover(true).is_err());+ assert_eq!(fixture.patches.load(Ordering::SeqCst), 2);+}++#[test]+fn changed_controls_still_require_a_patch_and_bad_pins_are_not_accepted() {+ let fixture = Fixture::new();+ fs::write(+ fixture.root.path().join("codex-a.json"),+ br#"{"prefix":"wrong","request_retry":0,"disable_cooling":true}"#,+ )+ .unwrap();+ fixture.reject_patch.store(true, Ordering::SeqCst);+ assert!(fixture.discover(false).is_err());+ assert_eq!(fixture.patches.load(Ordering::SeqCst), 1);+}++/// Opt-in smoke against a running isolated managed CPA. The manifest contains+/// paths, not credentials. A recording proxy can reject PATCH to prove reads+/// remain usable without the directory refresh path.+#[test]+#[ignore = "requires HIROUTE_CPA_PIN_SMOKE manifest and a live isolated CPA"]+fn live_managed_cpa_pin_reads() {+ let manifest = std::env::var("HIROUTE_CPA_PIN_SMOKE").expect("smoke manifest required");+ let value: Value = serde_json::from_slice(&fs::read(manifest).unwrap()).unwrap();+ let field = |key: &str| value[key].as_str().unwrap();+ let secrets = InstanceSecrets::read(Path::new(field("capability_file"))).unwrap();+ let identity = ManagedAccountIdentity {+ account_kind: CpaAccountKind::Codex,+ stock_file_name: field("stock_file_name").into(),+ account_digest: "a".repeat(64),+ generation: 1,+ };+ for _ in 0..6 {+ let accounts = StockCpaControlPlane+ .discover_and_pin(+ field("address").parse().unwrap(),+ Path::new(field("auth_dir")),+ std::slice::from_ref(&identity),+ &secrets,+ field("version"),+ Duration::from_secs(5),+ false,+ )+ .unwrap();+ assert_eq!(accounts.len(), 1);+ assert!(+ accounts[0]+ .observed_model_ids+ .contains(field("expected_model"))+ );+ }+}diff --git a/crates/cpa-bridge/src/borrowed_codex.rs b/crates/cpa-bridge/src/borrowed_codex.rsindex 8d4053d8..35168f28 100644--- a/crates/cpa-bridge/src/borrowed_codex.rs+++ b/crates/cpa-bridge/src/borrowed_codex.rs@@ -36,6 +36,7 @@ pub use evidence::BorrowedCodexEvidence;#[derive(Clone, Eq, PartialEq)]pub struct BorrowedCodexAuthSpec {source_path: PathBuf,+ executable: PathBuf,}impl std::fmt::Debug for BorrowedCodexAuthSpec {@@ -48,9 +49,15 @@ impl BorrowedCodexAuthSpec {pub fn new(source_path: impl Into<PathBuf>) -> Self {Self {source_path: source_path.into(),+ executable: PathBuf::from("codex"),}}+ pub fn with_executable(mut self, executable: PathBuf) -> Self {+ self.executable = executable;+ self+ }+pub fn source_path(&self) -> &Path {&self.source_path}@@ -112,6 +119,7 @@ impl ManagedAuthLease {struct BorrowedCodexLease {canonical_source: PathBuf,+ client_version: Option<String>,source_path_digest: String,_source_lock: File,flat_path: PathBuf,@@ -134,6 +142,9 @@ impl BorrowedCodexLease {let source_lock = acquire_lock(&lease_root.join(format!("{source_path_digest}.lock")))?;let mut lease = Self {canonical_source,+ client_version: hiroute_integrations::codex_subscription_client_version(+ &source.executable,+ ),source_path_digest,_source_lock: source_lock,flat_path: auth_dir.join(MANAGED_FILE_NAME),@@ -172,7 +183,7 @@ impl BorrowedCodexLease {}let prefix = "hiroute-codex-current".to_owned();- let rendered = render_access_only_auth(&source, &prefix)?;+ let rendered = render_access_only_auth(&source, &prefix, self.client_version.as_deref())?;let revision_digest = revision_digest(&source);let changed = previous.as_ref().is_none_or(|state| {@@ -195,7 +206,13 @@ impl BorrowedCodexLease {validate_private_file(&self.flat_path).map_err(|_| CpaLifecycleError::InvalidBorrowedCodexAuth)?;}- let flat_matches = flat_exists && private_file_matches(&self.flat_path, &source, &prefix)?;+ let flat_matches = flat_exists+ && private_file_matches(+ &self.flat_path,+ &source,+ &prefix,+ self.client_version.as_deref(),+ )?;if previous.is_none() && flat_exists && !flat_matches {return Err(CpaLifecycleError::InvalidBorrowedCodexAuth);}@@ -269,6 +286,7 @@ struct FlatAccessLease<'a> {prefix: &'a str,request_retry: u8,disable_cooling: bool,+ hiroute_client_version: Option<&'a str>,}#[derive(Deserialize)]@@ -288,6 +306,8 @@ struct ExistingFlatAccessLease<'a> {prefix: &'a str,request_retry: i64,disable_cooling: bool,+ #[serde(borrow)]+ hiroute_client_version: Option<&'a str>,#[serde(default, borrow)]refresh_token: Option<&'a str>,#[serde(default, borrow)]@@ -392,6 +412,7 @@ fn valid_text(value: &str, max: usize) -> bool {fn render_access_only_auth(source: &OwnedNestedSource,prefix: &str,+ client_version: Option<&str>,) -> Result<Zeroizing<Vec<u8>>, CpaLifecycleError> {serde_json::to_vec(&FlatAccessLease {kind: "codex",@@ -402,6 +423,7 @@ fn render_access_only_auth(prefix,request_retry: 0,disable_cooling: true,+ hiroute_client_version: client_version,}).map(Zeroizing::new).map_err(|_| CpaLifecycleError::InvalidBorrowedCodexAuth)@@ -619,6 +641,7 @@ fn private_file_matches(path: &Path,source: &OwnedNestedSource,prefix: &str,+ client_version: Option<&str>,) -> Result<bool, CpaLifecycleError> {let file = File::open(path).map_err(|_| CpaLifecycleError::BorrowedCodexAuthIo)?;let mut bytes = Zeroizing::new(Vec::new());@@ -631,6 +654,7 @@ fn private_file_matches(let existing: ExistingFlatAccessLease<'_> = serde_json::from_slice(bytes.as_slice()).map_err(|_| CpaLifecycleError::InvalidBorrowedCodexAuth)?;Ok(existing.kind == "codex"+ && existing.hiroute_client_version == client_version&& existing.access_token == source.access_token.as_str()&& existing.id_token == source.id_token.as_str()&& existing.account_id == source.account_id.as_str()diff --git a/crates/cpa-bridge/src/borrowed_codex/tests.rs b/crates/cpa-bridge/src/borrowed_codex/tests.rsindex 2a8844dd..a36be115 100644--- a/crates/cpa-bridge/src/borrowed_codex/tests.rs+++ b/crates/cpa-bridge/src/borrowed_codex/tests.rs@@ -43,6 +43,35 @@ fn flat_value(auth_dir: &Path) -> Value {serde_json::from_slice(&fs::read(auth_dir.join(MANAGED_FILE_NAME)).unwrap()).unwrap()}+#[cfg(unix)]+#[test]+fn selected_engine_version_is_carried_to_cpa_and_refreshed_on_reacquire() {+ use std::os::unix::fs::PermissionsExt;+ let (temp, auth_dir, source) = setup();+ let executable = temp.path().join("selected-codex");+ let spec = BorrowedCodexAuthSpec::new(&source).with_executable(executable.clone());+ for (version, expected) in [("0.158.0-alpha.2.1", "0.158.0"), ("0.999.1", "0.999.1")] {+ fs::write(+ &executable,+ format!("#!/bin/sh\nprintf 'codex-cli {version}\\n'\n"),+ )+ .unwrap();+ fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();+ let lease = ManagedAuthLease::acquire(&auth_dir, Some(&spec)).unwrap();+ assert_eq!(flat_value(&auth_dir)["hiroute_client_version"], expected);+ drop(lease);+ }+}++#[test]+fn missing_engine_does_not_invent_a_client_version() {+ let (temp, auth_dir, source) = setup();+ let spec =+ BorrowedCodexAuthSpec::new(&source).with_executable(temp.path().join("missing-codex"));+ let _lease = ManagedAuthLease::acquire(&auth_dir, Some(&spec)).unwrap();+ assert!(flat_value(&auth_dir)["hiroute_client_version"].is_null());+}+#[test]fn evidence_scan_is_read_only_and_redacts_the_source() {let temp = tempfile::tempdir().unwrap();diff --git a/crates/cpa-bridge/src/lib.rs b/crates/cpa-bridge/src/lib.rsindex f33e3b7a..cc5fc0a5 100644--- a/crates/cpa-bridge/src/lib.rs+++ b/crates/cpa-bridge/src/lib.rs@@ -47,4 +47,4 @@ pub use subscription::{/// Stock CPA release whose CLI/config/management contract this implementation was grounded on.pub const STOCK_CPA_CONTRACT_VERSION: &str = "7.2.140";/// Exact managed binary: upstream protocol contract plus the private parent-pipe bootstrap.-pub const MANAGED_CPA_ARTIFACT_VERSION: &str = "7.2.140-hiroute.2";+pub const MANAGED_CPA_ARTIFACT_VERSION: &str = "8.0.4-hiroute.1";diff --git a/crates/cpa-bridge/src/runtime/routing_batch.rs b/crates/cpa-bridge/src/runtime/routing_batch.rsindex 4394e918..97669d08 100644--- a/crates/cpa-bridge/src/runtime/routing_batch.rs+++ b/crates/cpa-bridge/src/runtime/routing_batch.rs@@ -124,6 +124,7 @@ impl ManagedCpaRuntime {&live.secrets,&live.artifact.version().to_string(),self.spec.control_timeout,+ expected.is_some(),) {Ok(discovered) => discovered,Err(error) => {diff --git a/crates/cpa-bridge/src/runtime/tests.rs b/crates/cpa-bridge/src/runtime/tests.rsindex 83644d37..44facc4d 100644--- a/crates/cpa-bridge/src/runtime/tests.rs+++ b/crates/cpa-bridge/src/runtime/tests.rs@@ -197,6 +197,7 @@ impl CpaControlPlane for FakeControl {secrets: &InstanceSecrets,expected_version: &str,timeout: Duration,+ _refresh_models: bool,) -> Result<Vec<AccountSnapshotRecord>, AccountDiscoveryError> {self.discoveries.fetch_add(1, Ordering::SeqCst);self.probe_ready(address, secrets, expected_version, timeout)?;diff --git a/crates/daemon/src/role_all.rs b/crates/daemon/src/role_all.rsindex 75baa659..ccf45132 100644--- a/crates/daemon/src/role_all.rs+++ b/crates/daemon/src/role_all.rs@@ -501,7 +501,14 @@ fn start_cpa(instance_id: "hiroute-codex".into(),state_root: config.storage_root.join("cpa/state"),auth_dir: config.storage_root.join("cpa/auth"),- borrowed_codex_auth: Some(BorrowedCodexAuthSpec::new(selected_codex_auth()?)),+ borrowed_codex_auth: Some(+ BorrowedCodexAuthSpec::new(selected_codex_auth()?).with_executable(+ config+ .codex_desktop_engine+ .clone()+ .unwrap_or_else(|| PathBuf::from("codex")),+ ),+ ),bindings: vec![CpaProfileBinding {account_kind: CpaAccountKind::Codex,connector_id: "connector.cpa.codex".into(),diff --git a/crates/daemon/tests/subscription_management_product.rs b/crates/daemon/tests/subscription_management_product.rsindex 448dda33..26d61d23 100644--- a/crates/daemon/tests/subscription_management_product.rs+++ b/crates/daemon/tests/subscription_management_product.rs@@ -35,7 +35,7 @@ import reimport sysimport urllib.parse-VERSION = "7.2.140-hiroute.2"+VERSION = "8.0.4-hiroute.1"MANAGED_NAME = "hiroute-managed-codex.json"MODEL_ID = "gpt-5.3-codex-spark"ADDED_MODEL_ID = "gpt-5.5"diff --git a/crates/daemon/tests/support/cpa_upstream.py b/crates/daemon/tests/support/cpa_upstream.pyindex c2ee734d..b3b4fd1a 100644--- a/crates/daemon/tests/support/cpa_upstream.py+++ b/crates/daemon/tests/support/cpa_upstream.py@@ -13,7 +13,7 @@ import threadingimport timefrom urllib.parse import parse_qs, urlparse-VERSION = '7.2.140-hiroute.2'+VERSION = '8.0.4-hiroute.1'controls = Path(__file__).resolve().parentmodel_override = controls / 'model-id'MODEL = (model_override.read_text().strip()diff --git a/crates/daemon/tests/support/standalone_headless_product.py b/crates/daemon/tests/support/standalone_headless_product.pyindex 3620d691..a82a1374 100644--- a/crates/daemon/tests/support/standalone_headless_product.py+++ b/crates/daemon/tests/support/standalone_headless_product.py@@ -342,7 +342,7 @@ for line in sys.stdin:'--version', '0.1.0-headless-product', '--revision', self.sha,'--hiroute', str(candidate_hiroute),'--hirouted', str(candidate_hirouted),- '--cpa-binary', str(cpa), '--cpa-version', '7.2.140-hiroute.2',+ '--cpa-binary', str(cpa), '--cpa-version', '8.0.4-hiroute.1','--cpa-license', str(license_path),'--notices', str(package_source / 'notices'), '--output', str(self.package),], cwd=self.repo, env=self.env, capture_output=True, timeout=90)diff --git a/crates/desktop-host-effects/src/workspace.rs b/crates/desktop-host-effects/src/workspace.rsindex 93dc4777..6c56720b 100644--- a/crates/desktop-host-effects/src/workspace.rs+++ b/crates/desktop-host-effects/src/workspace.rs@@ -14,7 +14,11 @@ pub(super) fn codex_desktop_engine() -> Option<std::path::PathBuf> {let bundle_identifier = NSString::from_str("com.openai.codex");let bundle =NSWorkspace::sharedWorkspace().URLForApplicationWithBundleIdentifier(&bundle_identifier)?;- Some(bundle.to_file_path()?.join("Contents/Resources/codex"))+ Some(+ bundle+ .to_file_path()?+ .join("Contents/Resources/codex-cli/bin/codex"),+ )}/// Opens this process's own confirmed .app bundle so the operating system delivers thediff --git a/crates/integrations/src/agents/executable.rs b/crates/integrations/src/agents/executable.rsindex b743ca2c..6a94390c 100644--- a/crates/integrations/src/agents/executable.rs+++ b/crates/integrations/src/agents/executable.rs@@ -5,6 +5,22 @@ use std::time::{Duration, Instant};const OUTPUT_LIMIT: usize = 64 * 1024;+/// Probe the selected native engine for subscription model discovery, not admission.+/// Reuses the bounded `--version` probe; never guesses a release or reads model caches.+pub fn codex_subscription_client_version(path: &Path) -> Option<String> {+ match executable_probe(path) {+ ExecutableProbe::Installed(observation) if !observation.version.is_empty() => {+ // Codex models-manager sends only MAJOR.MINOR.PATCH, including alpha builds.+ observation+ .version+ .split(['-', '+'])+ .next()+ .map(str::to_owned)+ }+ _ => None,+ }+}+pub(super) struct ExecutableObservationV1 {pub version: String,pub canonical_path: String,diff --git a/crates/integrations/src/agents/mod.rs b/crates/integrations/src/agents/mod.rsindex d32bd968..31fe4ee5 100644--- a/crates/integrations/src/agents/mod.rs+++ b/crates/integrations/src/agents/mod.rs@@ -16,6 +16,7 @@ mod collaboration_probe;mod discovery;mod emulator;mod executable;+pub use executable::codex_subscription_client_version;mod filesystem;mod filesystem_config;mod managed_launch;diff --git a/scripts/test-package-desktop.py b/scripts/test-package-desktop.pyindex 8a29cf6e..fc9568c1 100644--- a/scripts/test-package-desktop.py+++ b/scripts/test-package-desktop.py@@ -62,9 +62,9 @@ class BundleIdentityTests(unittest.TestCase):def test_cpa_is_explicitly_signed_before_release_probe(self):events = []- release = ("CLIProxyAPI Version: 7.2.140-hiroute.2, Commit: "- "c76dfd4e0edabab9000628b1560ab8ab379eadb8, "- "BuiltAt: 2026-09-18T00:00:00Z")+ release = ("CLIProxyAPI Version: 8.0.4-hiroute.1, Commit: "+ "a270e7b9e57aaecd8f82555f44c2108518ad2330, "+ "BuiltAt: 2026-09-29T00:00:00Z")with patch.object(package, "sign", side_effect=lambda *_: events.append("sign")), \patch.object(package, "run", side_effect=lambda *_args, **_kwargs:events.append("probe") or release):diff --git a/vendor/cpa/README.md b/vendor/cpa/README.mdnew file mode 100644index 00000000..8fe5fe12--- /dev/null+++ b/vendor/cpa/README.md@@ -0,0 +1,35 @@+# Managed CPA patch++`source.json` pins the upstream revision, artifact version and patch digest.+`local-management-stdin.patch` includes the parent-pipe management credential+bootstrap and Codex account model discovery. Build with `scripts/build-cpa.py`.++Codex OAuth registration queries `https://chatgpt.com/backend-api/codex/models`+using the account's access token and account ID over CPA's existing proxy/TLS+transport. `client_version` comes from the managed auth metadata+`hiroute_client_version`, populated by HiRoute's bounded native engine+`--version` probe. No fixed discovery version or local models-cache reader is+used. A new access lease re-probes the selected engine. Prerelease suffixes are+removed, matching Codex's models-manager.++Remote membership replaces the bundled membership for access-token accounts.+Existing bundled metadata can enrich matching IDs. Registration still applies+normal exclusions, OAuth aliases and account prefixes. Discovery has a five+second deadline and a 16 MiB response bound; redirects are rejected. Failure+leaves the existing registered catalog unchanged, without logging tokens or+upstream response bodies. An initial failure does not create model entries.+This does not add polling or a new catalog cache. Inference does not discover+models. Successful listing is not proof that inference succeeds.++HiRoute's ordinary routing compilation and Codex preview read and verify the+registered catalog without repeating an already-correct auth control PATCH.+An explicit subscription check refreshes it; credential/version changes use the+existing auth update path. This keeps remote directory availability out of+unchanged preview/publication reads while retaining all account pin checks.++Focused upstream tests are shipped in the patch:++```sh+go test ./sdk/cliproxy ./internal/runtime/executor ./cmd/server ./internal/api/handlers/management \+ -run 'TestCodexDiscovery|TestCodexModelDiscovery|TestRegisterModelsForAuth|TestLocalManagementPasswordPipeBounds|TestLocalMachinePasswordPreservesRemotePolicy'+```diff --git a/vendor/cpa/local-management-stdin.patch b/vendor/cpa/local-management-stdin.patchindex 66f3a45b..746c1adf 100644--- a/vendor/cpa/local-management-stdin.patch+++ b/vendor/cpa/local-management-stdin.patch@@ -33,8 +33,8 @@+ password = localPassword+ }- // Core application variables.- var err error+ if discoverGateways || discoverJSON {+ cfgInclude, cfgExclude := cmd.LoadDiscoveryScanFilters(configPath)@@ -752,6 +766,11 @@managementasset.StartAutoUpdater(context.Background(), configFilePath)misc.StartAntigravityVersionUpdater(context.Background())@@ -102,7 +102,7 @@+package management++import (-+ "github.com/router-for-me/CLIProxyAPI/v7/internal/config"++ "github.com/router-for-me/CLIProxyAPI/v8/internal/config"+ "golang.org/x/crypto/bcrypt"+ "net/http"+ "strings"@@ -137,3 +137,271 @@+ t.Fatal("old instance credential accepted")+ }+}+--- /dev/null++++ b/internal/runtime/executor/codex_models.go+@@ -0,0 +1,105 @@++package executor++++import (++ "context"++ "encoding/json"++ "fmt"++ "io"++ "net/http"++ "net/url"++ "strings"++ "time"++++ "github.com/router-for-me/CLIProxyAPI/v8/internal/registry"++ "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"++ cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"++)++++// DiscoverModels uses the same account, proxy and TLS transport as Codex requests.++// The remote list controls membership; bundled metadata only enriches matching IDs.++func (e *CodexExecutor) DiscoverModels(ctx context.Context, auth *cliproxyauth.Auth, known []*registry.ModelInfo) ([]*registry.ModelInfo, error) {++ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)++ defer cancel()++ token, _ := codexCreds(auth)++ if strings.TrimSpace(token) == "" {++ return nil, fmt.Errorf("codex model discovery: missing access token")++ }++ version, _ := auth.Metadata["hiroute_client_version"].(string)++ version = strings.TrimSpace(version)++ if version == "" || len(version) > 128 || strings.ContainsAny(version, "\r\n\x00") {++ return nil, fmt.Errorf("codex model discovery: local client version unavailable")++ }++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://chatgpt.com/backend-api/codex/models?client_version="+url.QueryEscape(version), nil)++ if err != nil {++ return nil, err++ }++ applyCodexHeadersFromSources(req, auth, token, false, e.cfg, nil)++ client := helps.NewUtlsHTTPClient(ctx, e.cfg, auth, 5*time.Second)++ // Never forward subscription credentials to a redirect target.++ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }++ resp, err := client.Do(req)++ if err != nil {++ return nil, fmt.Errorf("codex model discovery: transport failed")++ }++ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {++ return nil, fmt.Errorf("codex model discovery: HTTP %d", resp.StatusCode)++ }++ const limit = 16 << 20++ body, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))++ if err != nil || len(body) > limit {++ return nil, fmt.Errorf("codex model discovery: unreadable or oversized catalog")++ }++ var catalog struct {++ Models []struct {++ Slug string `json:"slug"`++ DisplayName string `json:"display_name"`++ Description string `json:"description"`++ ContextWindow int `json:"context_window"`++ MaxContextWindow int `json:"max_context_window"`++ InputModalities []string `json:"input_modalities"`++ Reasoning []struct {++ Effort string `json:"effort"`++ } `json:"supported_reasoning_levels"`++ } `json:"models"`++ }++ if json.Unmarshal(body, &catalog) != nil || catalog.Models == nil {++ return nil, fmt.Errorf("codex model discovery: invalid catalog")++ }++ byID := make(map[string]*registry.ModelInfo, len(known))++ for _, m := range known {++ if m != nil {++ byID[m.ID] = m++ }++ }++ models := make([]*registry.ModelInfo, 0, len(catalog.Models))++ seen := make(map[string]bool)++ for _, remote := range catalog.Models {++ id := strings.TrimSpace(remote.Slug)++ if id == "" || seen[id] {++ return nil, fmt.Errorf("codex model discovery: invalid or duplicate model ID")++ }++ seen[id] = true++ m := registry.ModelInfo{ID: id, Object: "model", OwnedBy: "openai", Type: "codex"}++ if base := byID[id]; base != nil {++ m = *base++ }++ m.DisplayName, m.Description = remote.DisplayName, remote.Description++ m.ContextLength, m.MaxContextLength = remote.ContextWindow, remote.MaxContextWindow++ if m.ContextLength == 0 {++ m.ContextLength = m.MaxContextLength++ }++ m.SupportedInputModalities = remote.InputModalities++ m.Thinking = nil++ if len(remote.Reasoning) > 0 {++ m.Thinking = ®istry.ThinkingSupport{}++ for _, level := range remote.Reasoning {++ if level.Effort != "" {++ m.Thinking.Levels = append(m.Thinking.Levels, level.Effort)++ }++ }++ }++ models = append(models, &m)++ }++ return models, nil++}+--- /dev/null++++ b/internal/runtime/executor/codex_models_test.go+@@ -0,0 +1,56 @@++package executor++++import (++ "context"++ "io"++ "net/http"++ "strings"++ "testing"++++ cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"++)++++type discoveryRoundTrip func(*http.Request) (*http.Response, error)++++func (f discoveryRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++++func TestCodexModelDiscoveryFailureBounds(t *testing.T) {++ a := &cliproxyauth.Auth{Metadata: map[string]any{"access_token": "secret", "hiroute_client_version": "0.999.0"}}++ for _, tc := range []struct {++ name string++ status int++ body string++ redirect bool++ }{++ {"redirect", 302, "", true},++ {"oversized", 200, strings.Repeat("x", (16<<20)+1), false},++ {"duplicate", 200, `{"models":[{"slug":"m"},{"slug":"m"}]}`, false},++ } {++ t.Run(tc.name, func(t *testing.T) {++ calls := 0++ ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", discoveryRoundTrip(func(r *http.Request) (*http.Response, error) {++ calls++++ h := make(http.Header)++ if tc.redirect {++ h.Set("Location", "https://example.com/stolen")++ }++ return &http.Response{StatusCode: tc.status, Header: h, Body: io.NopCloser(strings.NewReader(tc.body)), Request: r}, nil++ }))++ _, err := NewCodexExecutor(nil).DiscoverModels(ctx, a, nil)++ if err == nil || calls != 1 || strings.Contains(err.Error(), "secret") {++ t.Fatalf("unsafe failure handling: calls=%d err=%v", calls, err)++ }++ })++ }++}++++func TestCodexModelDiscoveryRequiresObservedVersion(t *testing.T) {++ ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", discoveryRoundTrip(func(r *http.Request) (*http.Response, error) {++ t.Fatal("must not query with an invented version")++ return nil, nil++ }))++ _, err := NewCodexExecutor(nil).DiscoverModels(ctx, &cliproxyauth.Auth{Metadata: map[string]any{"access_token": "secret"}}, nil)++ if err == nil || !strings.Contains(err.Error(), "local client version unavailable") {++ t.Fatalf("missing version: %v", err)++ }++}+--- a/sdk/cliproxy/service_models.go++++ b/sdk/cliproxy/service_models.go+@@ -9,8 +9,10 @@+ "github.com/router-for-me/CLIProxyAPI/v8/internal/constant"+ "github.com/router-for-me/CLIProxyAPI/v8/internal/modelconfig"+ "github.com/router-for-me/CLIProxyAPI/v8/internal/registry"++ "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor"+ coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"+ "github.com/router-for-me/CLIProxyAPI/v8/sdk/config"++ log "github.com/sirupsen/logrus"+ )++ // registerModelsForAuth (re)binds provider models in the global registry using the core auth ID as client identifier.+@@ -149,6 +151,22 @@+ default:+ models = registry.GetCodexProModels()+ }++ if token, _ := a.Metadata["access_token"].(string); strings.TrimSpace(token) != "" {++ discovered, err := executor.NewCodexExecutor(s.cfg).DiscoverModels(ctx, a, models)++ if err != nil {++ log.Warnf("Codex model discovery failed; retaining registered catalog: %v", err)++ return++ }++ // An auth removed or replaced during the bounded request must not reappear.++ if s.coreManager != nil {++ current, ok := s.coreManager.GetByID(a.ID)++ if !ok || current.Disabled || current.Generation != a.Generation || current.RegistrationEpoch != a.RegistrationEpoch {++ return++ }++ }++ models = discovered++ log.Infof("Codex account model discovery completed: %d models", len(models))++ }+ models = applyExcludedModels(models, excluded)+ case "kimi", "kimi-ai", "kimi.ai", "kimi.com":+ models = registry.GetKimiModels()+--- /dev/null++++ b/sdk/cliproxy/service_codex_discovery_test.go+@@ -0,0 +1,62 @@++package cliproxy++++import (++ "context"++ "io"++ "net/http"++ "strings"++ "testing"++++ coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"++ "github.com/router-for-me/CLIProxyAPI/v8/sdk/config"++)++++type discoveryTransport func(*http.Request) (*http.Response, error)++++func (f discoveryTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++++func TestCodexDiscoveryRegistration(t *testing.T) {++ s := &Service{cfg: &config.Config{}}++ s.cfg.ForceModelPrefix = true++ a := &coreauth.Auth{ID: "discovery-account", Provider: "codex", Prefix: "subscription", Metadata: map[string]any{"access_token": "test-token", "account_id": "test-account", "hiroute_client_version": "0.999.0"}, Attributes: map[string]string{"excluded_models": "excluded"}}++ defer GlobalModelRegistry().UnregisterClient(a.ID)++ status, body := 200, `{"models":[{"slug":"future-model-not-in-bundle","display_name":"Future","context_window":123456,"input_modalities":["text","image"],"supported_reasoning_levels":[{"effort":"max"}]},{"slug":"excluded"}]}`++ ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", discoveryTransport(func(r *http.Request) (*http.Response, error) {++ if r.URL.String() != "https://chatgpt.com/backend-api/codex/models?client_version=0.999.0" || r.Header.Get("Authorization") != "Bearer test-token" || r.Header.Get("ChatGPT-Account-ID") != "test-account" {++ t.Fatal("wrong discovery request")++ }++ if _, ok := r.Context().Deadline(); !ok {++ t.Fatal("missing deadline")++ }++ return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil++ }))++ s.registerModelsForAuth(ctx, a)++ check := func() {++ t.Helper()++ models := GlobalModelRegistry().GetModelsForClient(a.ID)++ if len(models) != 1 || models[0].ID != "subscription/future-model-not-in-bundle" || models[0].ContextLength != 123456 || models[0].Thinking.Levels[0] != "max" {++ t.Fatalf("unexpected registered models: %+v", models)++ }++ }++ check()++ for _, failure := range []struct {++ status int++ body string++ }{{401, `secret upstream error`}, {200, `{broken`}, {200, `{}`}, {200, `{"models":[{"slug":""}]}`}} {++ status, body = failure.status, failure.body++ s.registerModelsForAuth(ctx, a)++ check()++ }++ status, body = 200, `{"models":[]}`++ s.registerModelsForAuth(ctx, a)++ if len(GlobalModelRegistry().GetModelsForClient(a.ID)) != 0 {++ t.Fatal("empty authoritative list did not remove models")++ }++ status, body = 200, `{"models":[{"slug":"other-account-model"}]}`++ a.ID, a.Prefix = "other-account", "other"++ defer GlobalModelRegistry().UnregisterClient(a.ID)++ s.registerModelsForAuth(ctx, a)++ if len(GlobalModelRegistry().GetModelsForClient("discovery-account")) != 0 {++ t.Fatal("cross-account catalog leakage")++ }++}diff --git a/vendor/cpa/source.json b/vendor/cpa/source.jsonindex 19a26cfa..0bd3d80e 100644--- a/vendor/cpa/source.json+++ b/vendor/cpa/source.json@@ -1,8 +1,8 @@{"repository": "https://github.com/router-for-me/CLIProxyAPI",- "commit": "c76dfd4e0edabab9000628b1560ab8ab379eadb8",- "version": "7.2.140-hiroute.2",- "built_at": "2026-09-18T00:00:00Z",+ "commit": "a270e7b9e57aaecd8f82555f44c2108518ad2330",+ "version": "8.0.4-hiroute.1",+ "built_at": "2026-09-29T00:00:00Z","patch": "local-management-stdin.patch",- "patch_sha256": "94b06b19c66e1ce051ff252a953ddbf8baa660051ba8ce698453f3c663a90a78"+ "patch_sha256": "c04588a9606700810b192520712536437c44dcbf4d7cc4c5ef762dd76da23877"}