| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| use futures_util::future::BoxFuture; | |
| use maka_agent_ports::model::{Connect, Error as ModelError, Socket, TextStream, Transport}; | |
| use maka_agent_ports::provider::authentication::Credential; | |
| use maka_agent_ports::provider::{Connection, Context, Error, Provider, Resolve}; | |
| use maka_capabilities::http; | |
| use maka_providers::codex::Codex; | |
| use serde_json::json; | |
| use std::sync::{Arc, Mutex}; | |
| use tokio_util::sync::CancellationToken; | |
| struct DiscoveryTransport { | |
| requests: Mutex<Vec<String>>, | |
| response: serde_json::Value, | |
| } | |
| impl Transport for DiscoveryTransport { | |
| fn identity(&self) -> u64 { | |
| 1 | |
| } | |
| fn request( | |
| &self, | |
| request: http::Request, | |
| _cancellation: CancellationToken, | |
| ) -> BoxFuture<'_, Result<http::Response, ModelError>> { | |
| let url = request.url; | |
| self.requests.lock().unwrap().push(url.clone()); | |
| let payload = serde_json::to_vec(&self.response).unwrap(); | |
| Box::pin(async move { | |
| Ok(http::Response { | |
| head: http::Head { | |
| status: 200, | |
| url, | |
| headers: vec![], | |
| }, | |
| body: Arc::new(Body(Mutex::new(Some(payload)))), | |
| }) | |
| }) | |
| } | |
| fn connect(&self, _: Connect) -> BoxFuture<'_, Result<Arc<dyn Socket>, ModelError>> { | |
| Box::pin(async { Err(ModelError::Adapter("unexpected WebSocket".into())) }) | |
| } | |
| fn send_text( | |
| &self, | |
| _: Arc<dyn Socket>, | |
| _: TextStream, | |
| ) -> BoxFuture<'_, Result<(), ModelError>> { | |
| Box::pin(async { Err(ModelError::Adapter("unexpected WebSocket".into())) }) | |
| } | |
| } | |
| struct Body(Mutex<Option<Vec<u8>>>); | |
| impl http::Body for Body { | |
| fn next(&self) -> BoxFuture<'_, Result<Option<Vec<u8>>, http::Error>> { | |
| Box::pin(async { Ok(self.0.lock().unwrap().take()) }) | |
| } | |
| fn cancel(&self) {} | |
| fn close(&self) -> BoxFuture<'_, Result<(), http::Error>> { | |
| Box::pin(async { Ok(()) }) | |
| } | |
| } | |
| fn connection() -> Connection { | |
| Connection { | |
| id: "connection".into(), | |
| revision: 1, | |
| configuration: json!({"baseUrl":"https://chatgpt.com/backend-api/codex"}), | |
| } | |
| } | |
| #[tokio::test] | |
| async fn server_side_compaction_requires_connection_opt_in() { | |
| let provider = Codex::new(Arc::new( | |
| maka_providers::catalog::Snapshot::bundled().unwrap(), | |
| )); | |
| let discovered = maka_providers::codex::decode_model_inventory( | |
| br#"{"models":[{"slug":"gpt-6-luna","comp_hash":"3000"}]}"#, | |
| ) | |
| .unwrap() | |
| .remove(0); | |
| for (setting, expected) in [(None, false), (Some(true), true), (Some(false), false)] { | |
| let mut connection = connection(); | |
| if let Some(enabled) = setting { | |
| connection.configuration["serverSideCompaction"] = json!(enabled); | |
| } | |
| let model = provider | |
| .resolve(Resolve { | |
| service_tier: None, | |
| connection, | |
| model: discovered.clone(), | |
| overrides: None, | |
| thinking_level: None, | |
| }) | |
| .await | |
| .unwrap(); | |
| assert_eq!( | |
| model.info.capabilities.unwrap().native_compaction, | |
| Some(expected) | |
| ); | |
| } | |
| } | |
| #[tokio::test] | |
| async fn subscription_discovery_preserves_capacity_and_compaction_hash() { | |
| let provider = Codex::new(Arc::new( | |
| maka_providers::catalog::Snapshot::bundled().unwrap(), | |
| )); | |
| let discovered = maka_providers::codex::decode_model_inventory( | |
| br#"{"models":[{"slug":"gpt-6-luna","context_window":272000,"comp_hash":"3000"}]}"#, | |
| ) | |
| .unwrap() | |
| .remove(0); | |
| assert_eq!(discovered.max_output_tokens, Some(128_000)); | |
| assert_eq!(discovered.codex_compaction_hash.as_deref(), Some("3000")); | |
| let model = provider | |
| .resolve(Resolve { | |
| service_tier: None, | |
| connection: connection(), | |
| model: discovered, | |
| overrides: None, | |
| thinking_level: None, | |
| }) | |
| .await | |
| .unwrap(); | |
| assert_eq!(model.info.max_output_tokens, Some(128_000)); | |
| assert_eq!(model.info.context_window, Some(272_000)); | |
| assert_eq!(model.info.codex_compaction_hash.as_deref(), Some("3000")); | |
| let manual = provider | |
| .resolve(Resolve { | |
| service_tier: None, | |
| connection: connection(), | |
| model: maka_agent_facts::configuration::ModelInfo::new("gpt-6.2-sol"), | |
| overrides: None, | |
| thinking_level: Some(maka_agent_facts::execution::ThinkingLevel::High), | |
| }) | |
| .await | |
| .unwrap(); | |
| assert_eq!(manual.info.max_output_tokens, Some(128_000)); | |
| assert_eq!(manual.info.context_window, Some(500_000)); | |
| assert_eq!( | |
| manual.thinking_levels, | |
| [ | |
| maka_agent_facts::execution::ThinkingLevel::Low, | |
| maka_agent_facts::execution::ThinkingLevel::Medium, | |
| maka_agent_facts::execution::ThinkingLevel::High, | |
| maka_agent_facts::execution::ThinkingLevel::Xhigh, | |
| maka_agent_facts::execution::ThinkingLevel::Max, | |
| maka_agent_facts::execution::ThinkingLevel::Ultra, | |
| ] | |
| ); | |
| assert_eq!(manual.provider_options["openai"]["reasoningEffort"], "high"); | |
| assert!( | |
| maka_providers::codex::decode_model_inventory( | |
| br#"{"models":[{"slug":"unknown-future-model"}]}"#, | |
| ) | |
| .unwrap()[0] | |
| .max_output_tokens | |
| .is_none() | |
| ); | |
| } | |
| #[tokio::test] | |
| async fn discovery_and_preparation_share_account_facts_and_explicit_policy() { | |
| use base64::Engine; | |
| use maka_agent_facts::configuration::{ModelInfo, ModelOverride}; | |
| use maka_agent_facts::execution::ThinkingLevel::*; | |
| let transport = Arc::new(DiscoveryTransport { | |
| requests: Mutex::new(vec![]), | |
| response: json!({"models":[{ | |
| "slug":"future-model", "context_window":272000, | |
| "supported_reasoning_levels":[{"effort":"medium"},{"effort":"high"},{"effort":"max"},{"effort":"ultra"}], | |
| "supports_reasoning_summary_parameter":false, | |
| "input_modalities":["text"], "supports_parallel_tool_calls":false | |
| }]}), | |
| }); | |
| let provider = Codex::new(Arc::new( | |
| maka_providers::catalog::Snapshot::bundled().unwrap(), | |
| )); | |
| let access = format!( | |
| "header.{}.signature", | |
| base64::engine::general_purpose::URL_SAFE_NO_PAD | |
| .encode(serde_json::to_vec(&json!({"chatgpt_account_id":"account-a"})).unwrap()) | |
| ); | |
| let credential = Credential { | |
| secret: json!({ | |
| "access_token":access,"refresh_token":"refresh","expires_at":1,"id_token":null | |
| }) | |
| .to_string(), | |
| refresh_at: None, | |
| }; | |
| let inventory = provider | |
| .discover( | |
| maka_agent_ports::provider::Discovery { | |
| connection: connection(), | |
| credential: Some(credential.clone()), | |
| request_headers: [("ChatGPT-Account-ID".into(), "account-a".into())].into(), | |
| }, | |
| Context { | |
| transport: transport.clone(), | |
| cancellation: CancellationToken::new(), | |
| interaction: None, | |
| }, | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!(inventory.len(), 1); | |
| assert!(matches!( | |
| provider | |
| .discover( | |
| maka_agent_ports::provider::Discovery { | |
| connection: connection(), | |
| credential: Some(credential), | |
| request_headers: [("ChatGPT-Account-ID".into(), "account-b".into())].into(), | |
| }, | |
| Context { | |
| transport: transport.clone(), | |
| cancellation: CancellationToken::new(), | |
| interaction: None, | |
| } | |
| ) | |
| .await, | |
| Err(Error::Invalid(_)) | |
| )); | |
| let request = Resolve { | |
| service_tier: None, | |
| connection: connection(), | |
| model: inventory[0].clone(), | |
| overrides: None, | |
| thinking_level: None, | |
| }; | |
| let model = provider.resolve(request.clone()).await.unwrap(); | |
| assert_eq!(model.thinking_levels, vec![Medium, High, Max, Ultra]); | |
| assert_eq!(model.info.context_window, Some(272000)); | |
| assert_eq!(model.info.capabilities.unwrap().vision, Some(false)); | |
| assert_eq!( | |
| model.provider_options["openai"], | |
| json!({"store":false,"parallelToolCalls":false}) | |
| ); | |
| let mut declared = request.clone(); | |
| declared.overrides = Some(ModelOverride { | |
| default_thinking_level: Some(Ultra), | |
| ..Default::default() | |
| }); | |
| let model = provider.resolve(declared.clone()).await.unwrap(); | |
| assert_eq!(model.provider_options["openai"]["reasoningEffort"], "ultra"); | |
| assert!( | |
| model.provider_options["openai"] | |
| .get("reasoningSummary") | |
| .is_none() | |
| ); | |
| assert_eq!(wire(&model)["reasoning"], json!({"effort":"ultra"})); | |
| declared.thinking_level = Some(High); | |
| assert_eq!( | |
| provider | |
| .resolve(declared.clone()) | |
| .await | |
| .unwrap() | |
| .provider_options["openai"]["reasoningEffort"], | |
| "high" | |
| ); | |
| declared.thinking_level = Some(Low); | |
| assert!(matches!( | |
| provider.resolve(declared.clone()).await, | |
| Err(Error::Invalid(_)) | |
| )); | |
| declared.thinking_level = None; | |
| declared.overrides = Some(ModelOverride { | |
| thinking_levels: Some(vec![Off, Low]), | |
| default_thinking_level: Some(Off), | |
| ..Default::default() | |
| }); | |
| declared.model.supports_reasoning_summary = Some(true); | |
| let model = provider.resolve(declared).await.unwrap(); | |
| assert_eq!(model.thinking_levels, vec![Off, Low]); | |
| assert_eq!(model.provider_options["openai"]["reasoningEffort"], "none"); | |
| assert!( | |
| model.provider_options["openai"] | |
| .get("reasoningSummary") | |
| .is_none() | |
| ); | |
| let model = provider | |
| .resolve(Resolve { | |
| model: ModelInfo::new("unadvertised"), | |
| ..request | |
| }) | |
| .await | |
| .unwrap(); | |
| assert!(model.thinking_levels.is_empty()); | |
| assert!( | |
| model.provider_options["openai"] | |
| .get("reasoningEffort") | |
| .is_none() | |
| ); | |
| assert_eq!(model.provider_options["openai"]["reasoningSummary"], "auto"); | |
| assert_eq!(wire(&model)["reasoning"], json!({"summary":"auto"})); | |
| let requests = transport.requests.lock().unwrap(); | |
| assert_eq!(requests.len(), 1); | |
| assert!(requests[0].ends_with("/models?client_version=1.0.0")); | |
| } | |
| fn wire(model: &maka_agent_ports::provider::Model) -> serde_json::Value { | |
| maka_provider_protocol::responses::request::Request { | |
| model: &model.info.id, | |
| input: &[], | |
| tools: &[], | |
| tool_choice: Default::default(), | |
| options: &model.provider_options, | |
| max_output_tokens: None, | |
| reasoning: maka_provider_protocol::responses::ReasoningMode::Encrypted, | |
| } | |
| .encode() | |
| .unwrap() | |
| } | |
| #[test] | |
| fn subscription_inventory_rejects_invalid_compaction_hashes() { | |
| for hash in [json!(""), json!(" hash"), json!("hash\n"), json!(42)] { | |
| let bytes = | |
| serde_json::to_vec(&json!({"models":[{"slug":"fixture-model","comp_hash":hash}]})) | |
| .unwrap(); | |
| assert!(maka_providers::codex::decode_model_inventory(&bytes).is_err()); | |
| } | |
| } | |
| #[test] | |
| fn subscription_inventory_preserves_long_compaction_hashes() { | |
| let hash = "x".repeat(129); | |
| let bytes = | |
| serde_json::to_vec(&json!({"models":[{"slug":"fixture-model","comp_hash":hash}]})).unwrap(); | |
| let models = maka_providers::codex::decode_model_inventory(&bytes).unwrap(); | |
| assert_eq!( | |
| models[0].codex_compaction_hash.as_deref(), | |
| Some(hash.as_str()) | |
| ); | |
| } |