aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT
- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser, device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity, runtime agent instance, backend-client e openapi-models, workspace routing. - Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin remoti (catalogo, sync, share), cyber access program, daybreak, cloud config e requirements (config_server ora fail-closed), attestation, frozen cloud skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/ routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime. - Messaggi d'errore senza link a chatgpt.com. - Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed. - Test: cancellati solo quelli del codice rimosso; test di sicurezza (sandbox estensioni, permessi, redazione, auth storage, requirements) adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents). - Istruzioni di sistema invariate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,8 +13,6 @@ doctest = false
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
codex-agent-identity = { workspace = true }
|
||||
codex-runtime-agent-instance = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
codex-api = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
|
||||
@@ -20,7 +20,7 @@ use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_protocol::approvals::GuardianReviewReason;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::mcp::is_node_repl_backed_connector;
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
use codex_protocol::openai_models::GuardianModelPolicy;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
@@ -269,14 +269,11 @@ async fn cached_evidence(
|
||||
action.get("tool_name").and_then(serde_json::Value::as_str),
|
||||
Some("js" | "browser_js")
|
||||
)
|
||||
&& is_node_repl_backed_connector(
|
||||
&& is_node_repl_backed_server(
|
||||
action
|
||||
.get("server")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_default(),
|
||||
action
|
||||
.get("connector_id")
|
||||
.and_then(serde_json::Value::as_str),
|
||||
)
|
||||
&& cached.js_executions == 1
|
||||
{
|
||||
|
||||
@@ -11,7 +11,6 @@ use std::time::SystemTime;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::GuardianAuthorizationVersion;
|
||||
use codex_core::GuardianRootSnapshot;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::context::ContextualUserFragment;
|
||||
use codex_core::context::GuardianContextMode;
|
||||
@@ -34,7 +33,6 @@ use codex_prompts::ResolvedModelMessages;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
|
||||
use super::authorization::ScoreAuthorization;
|
||||
use super::config::GuardianV2Config;
|
||||
@@ -65,9 +63,6 @@ pub(super) struct Classification {
|
||||
pub(super) thread_id: String,
|
||||
pub(super) turn_id: String,
|
||||
pub(super) root_turn_id: Option<String>,
|
||||
pub(super) cyber_access_program: Option<CyberAccessProgram>,
|
||||
pub(super) parent_response_id: Option<String>,
|
||||
pub(super) manager: Arc<ThreadManager>,
|
||||
pub(super) thread: Arc<CodexThread>,
|
||||
pub(super) config: Arc<Config>,
|
||||
pub(super) context_mode: GuardianContextMode,
|
||||
@@ -118,9 +113,6 @@ impl Classification {
|
||||
thread_id,
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
manager,
|
||||
thread,
|
||||
config,
|
||||
context_mode,
|
||||
@@ -149,7 +141,7 @@ impl Classification {
|
||||
metadata = async {
|
||||
let trusted_tool_context = match mcp_tool.as_ref() {
|
||||
Some(tool) => {
|
||||
trusted_tool_context(tool.tool_info(), tool.source(), &manager, &config).await
|
||||
trusted_tool_context(tool.tool_info(), tool.source(), &config).await
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
@@ -291,8 +283,6 @@ impl Classification {
|
||||
let instructions = guardian_config.render_classifier_instructions(policy, extra_policy);
|
||||
let sampling = LunaSamplingRequest {
|
||||
item_id_generator: Arc::clone(thread.item_id_generator()),
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
instructions,
|
||||
#[cfg(test)]
|
||||
input: Vec::new(),
|
||||
|
||||
@@ -39,7 +39,7 @@ async fn allow_messaging_guardian_review(server: &wiremock::MockServer) {
|
||||
.any(|item| {
|
||||
item["text"].as_str().is_some_and(|text| {
|
||||
text.contains("\"tool\": \"mcp_tool_call\"")
|
||||
&& text.contains("\"server\": \"codex_apps\"")
|
||||
&& text.contains("\"server\": \"messaging\"")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -88,7 +88,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
}),
|
||||
"tools/list" => json!({"tools": [{"name": TOOL, "inputSchema": {
|
||||
"type": "object", "properties": {"text": {"type": "string"}}
|
||||
}, "_meta": {"connector_id": "user_message", "connector_name": "user_message"}}]}),
|
||||
}}]}),
|
||||
"tools/call" => {
|
||||
assert_eq!(request["params"]["name"], TOOL);
|
||||
assert_eq!(
|
||||
@@ -123,7 +123,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
MessagingSetup::CodeMode(format!("{}/user-messaging", messaging_server.uri())),
|
||||
)
|
||||
.await?;
|
||||
wait_for_mcp_server(&test.codex, "codex_apps").await?;
|
||||
wait_for_mcp_server(&test.codex, "messaging").await?;
|
||||
allow_messaging_guardian_review(&thread_server).await;
|
||||
let root_store = test.codex.thread_extension_data();
|
||||
let root_progress = root_store.get::<GuardianV2ScoreProgress>().unwrap();
|
||||
@@ -165,7 +165,7 @@ async fn confirmed_root_delivery_invalidates_root_and_worker_cached_approvals()
|
||||
ev_custom_tool_call(
|
||||
"send-message",
|
||||
"exec",
|
||||
"text(await tools.mcp__codex_apps__user_message_send_message({text: 'May I deploy?'}));",
|
||||
"text(await tools.mcp__messaging__user_message_send_message({text: 'May I deploy?'}));",
|
||||
),
|
||||
ev_completed("send-message"),
|
||||
]),
|
||||
|
||||
@@ -59,7 +59,6 @@ use codex_protocol::protocol::TruncationPolicy;
|
||||
use codex_protocol::security_risk::SecurityRiskScore;
|
||||
use codex_protocol_test_support::uuid_v7_item_id_generator_for_test;
|
||||
use core_test_support::ThreadIdle;
|
||||
use core_test_support::apps_test_server::HostedMessagingServer;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
@@ -260,8 +259,7 @@ async fn installed_extension_warms_connections_without_blocking_thread_start() -
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_reviews() -> Result<()>
|
||||
{
|
||||
async fn installed_extension_reviews_over_websocket_and_http_after_auth_refresh() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("original"));
|
||||
@@ -269,19 +267,11 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
.set_external_auth(Arc::new(RefreshableAuth(std::sync::Mutex::new("original"))))
|
||||
.await?;
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let mut test = test_codex()
|
||||
let test = test_codex()
|
||||
.with_auth_manager(Arc::clone(&auth_manager))
|
||||
.with_config(|config| config.approvals_reviewer = ApprovalsReviewer::AutoReview)
|
||||
.build_with_auto_env(&thread_server)
|
||||
.await?;
|
||||
let mut options = test.start_thread_options().await;
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(codex_core::RequiredCyberAccessPrograms {
|
||||
allowed: vec![codex_protocol::turn_input::CyberAccessProgram::DaybreakRed],
|
||||
});
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
test.codex = test.thread_manager.start_thread(options).await?.thread;
|
||||
let events = vec![
|
||||
ev_assistant_message("sample", "low"),
|
||||
ev_completed("response-1"),
|
||||
@@ -308,8 +298,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
// An earlier extension cannot erase Core's captured enrollment policy.
|
||||
thread_store.remove::<codex_core::RequiredCyberAccessPrograms>();
|
||||
let mut model = test
|
||||
.thread_manager
|
||||
.get_models_manager()
|
||||
@@ -340,7 +328,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
.expect("Guardian v2 should initialize");
|
||||
let turn_store = ExtensionData::new("turn-1");
|
||||
turn_store.insert_arc(thread_store.get::<Config>().expect("captured test config"));
|
||||
turn_store.insert(codex_protocol::turn_input::CyberAccessProgram::DaybreakRed);
|
||||
let tool_name = ToolName::namespaced("mcp__node_repl__", "js");
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: r#"{"path":"README.md"}"#.to_owned(),
|
||||
@@ -410,7 +397,6 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
assert_eq!(requests.len(), 1);
|
||||
requests.push(http_request.body_json());
|
||||
for request in &requests {
|
||||
assert!(request.get("access_programs").is_none());
|
||||
responses::assert_parent_turn(request, Some("turn-1"))?;
|
||||
responses::assert_root_turn(request, /*expected*/ None)?;
|
||||
}
|
||||
@@ -969,19 +955,22 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
)> {
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let guardian_policy = guardian_policy.map(str::to_owned);
|
||||
let guardian_config = format!(
|
||||
let mut guardian_config = format!(
|
||||
"{guardian_config}\n[features.guardianv2.review_scope]\ncomputer_use_only = false\n"
|
||||
);
|
||||
if let MessagingSetup::CodeMode(url) = &messaging {
|
||||
// The messaging MCP is an ordinary user-configured server with auto-approved tools.
|
||||
guardian_config.push_str(&format!(
|
||||
"\n[mcp_servers.messaging]\nurl = \"{url}\"\ndefault_tools_approval_mode = \"approve\"\nsupports_parallel_tool_calls = true\n"
|
||||
));
|
||||
}
|
||||
let has_model_defaults = model_defaults.is_some();
|
||||
let code_mode = matches!(&messaging, MessagingSetup::CodeMode(_));
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle));
|
||||
if let MessagingSetup::CodeMode(url) = messaging {
|
||||
extensions.mcp_server_contributor(Arc::new(HostedMessagingServer(url)));
|
||||
}
|
||||
let builder = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_model_info_override("codex-auto-review", |model_info| {
|
||||
model_info
|
||||
.model_messages
|
||||
@@ -998,7 +987,6 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
config.guardian_policy_config = Some("Policy from the live thread.".to_owned());
|
||||
if code_mode {
|
||||
for feature in [
|
||||
Feature::Apps,
|
||||
Feature::CodeMode,
|
||||
Feature::CodeModeInterrupt,
|
||||
Feature::Collab,
|
||||
@@ -1035,7 +1023,8 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
let catalog = test.config.model_catalog.as_mut().expect("test catalog");
|
||||
for model in &mut catalog.models {
|
||||
let policy = match model.slug.as_str() {
|
||||
"codex-auto-review" => TEST_THREAD_REVIEWER_POLICY,
|
||||
// API-key auth (the only credential aKode supports) prefers the Luna reviewer.
|
||||
"codex-auto-review" | "gpt-5.6-luna" => TEST_THREAD_REVIEWER_POLICY,
|
||||
"gpt-5.5" => "Policy from the captured parent.",
|
||||
_ => continue,
|
||||
};
|
||||
|
||||
@@ -15,11 +15,10 @@ use codex_extension_api::ToolPayload;
|
||||
use codex_extension_api::ToolStartInput;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::mcp::is_node_repl_backed_connector;
|
||||
use codex_protocol::mcp::is_node_repl_backed_server;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
|
||||
use super::action::ActionRenderError;
|
||||
use super::action::GuardianAction;
|
||||
@@ -66,19 +65,7 @@ impl GuardianV2Extension {
|
||||
};
|
||||
let is_js_execution = input.mcp_tool.is_some_and(|tool| {
|
||||
let info = tool.tool_info();
|
||||
is_node_repl_backed_connector(&info.server_name, info.connector_id.as_deref())
|
||||
&& if info.server_name == "codex_apps" {
|
||||
info.tool
|
||||
.meta
|
||||
.as_ref()
|
||||
.and_then(|meta| meta.get("_codex_apps"))
|
||||
.and_then(|meta| meta.get("resource_uri"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|uri| uri.trim_matches('/').rsplit('/').next())
|
||||
== Some("js")
|
||||
} else {
|
||||
info.tool.name == "js"
|
||||
}
|
||||
is_node_repl_backed_server(&info.server_name) && info.tool.name == "js"
|
||||
});
|
||||
// Count execution attempts even when policy disables background scoring.
|
||||
if is_js_execution {
|
||||
@@ -105,7 +92,7 @@ impl GuardianV2Extension {
|
||||
.mcp_tool
|
||||
.map(|tool| {
|
||||
let info = tool.tool_info();
|
||||
GuardianScope::for_mcp_connector(&info.server_name, info.connector_id.as_deref())
|
||||
GuardianScope::for_mcp_server(&info.server_name)
|
||||
})
|
||||
.or_else(|| {
|
||||
if guardian_config.review_multi_agent_calls {
|
||||
@@ -189,14 +176,6 @@ impl GuardianV2Extension {
|
||||
let thread_id = input.thread_store.level_id().to_owned();
|
||||
let turn_id = input.turn_id.to_owned();
|
||||
let root_turn_id = input.root_turn_id.map(str::to_owned);
|
||||
let cyber_access_program = input
|
||||
.turn_store
|
||||
.get::<CyberAccessProgram>()
|
||||
.map(|program| *program);
|
||||
let parent_response_id = input
|
||||
.turn_store
|
||||
.get::<codex_api::ResponseId>()
|
||||
.map(|id| id.0.clone());
|
||||
let thread_context: Result<_, String> = async {
|
||||
let parsed_thread_id =
|
||||
ThreadId::from_string(&thread_id).map_err(|error| error.to_string())?;
|
||||
@@ -208,10 +187,10 @@ impl GuardianV2Extension {
|
||||
.get_thread(parsed_thread_id)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok((manager, thread))
|
||||
Ok(thread)
|
||||
}
|
||||
.await;
|
||||
let (manager, thread) = match thread_context {
|
||||
let thread = match thread_context {
|
||||
Ok(context) => context,
|
||||
Err(error) => {
|
||||
score_progress.invalidate(tool_call_index);
|
||||
@@ -415,9 +394,6 @@ impl GuardianV2Extension {
|
||||
thread_id,
|
||||
turn_id,
|
||||
root_turn_id,
|
||||
cyber_access_program,
|
||||
parent_response_id,
|
||||
manager,
|
||||
thread,
|
||||
config,
|
||||
context_mode,
|
||||
|
||||
@@ -19,19 +19,14 @@ use codex_api::Reasoning;
|
||||
use codex_api::ReasoningContext;
|
||||
use codex_api::ResponsesApiRequest;
|
||||
use codex_context_fragments::RenderedFragment;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_model_provider::WorkspaceRoutingContext;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::oneshot;
|
||||
use uuid::Uuid;
|
||||
@@ -47,18 +42,8 @@ const MAX_CONCURRENT_REQUESTS: usize = 16;
|
||||
pub struct LunaSamplerConfig {
|
||||
/// Provider and credentials selected for the owning thread.
|
||||
pub provider: SharedModelProvider,
|
||||
/// Provider and feature policy shared with ordinary model requests.
|
||||
pub api_key_cyber_access_programs: ApiKeyCyberAccessPrograms,
|
||||
/// False when the parent host confines its explicit program to that thread.
|
||||
pub inherit_parent_cyber_access_program: bool,
|
||||
/// Routing scope and retained configuration layers for the owning thread.
|
||||
pub workspace_routing: WorkspaceRoutingContext,
|
||||
/// Effective proxy, custom-CA, and cookie configuration.
|
||||
pub http_client_factory: HttpClientFactory,
|
||||
/// Agent-identity policy selected for the owning thread.
|
||||
pub agent_identity_policy: AgentIdentityAuthPolicy,
|
||||
/// Host-resolved source used to scope agent-identity authentication.
|
||||
pub session_source: SessionSource,
|
||||
/// Owning runtime session identifier.
|
||||
pub session_id: String,
|
||||
/// Owning thread identifier.
|
||||
@@ -79,10 +64,6 @@ pub struct LunaSamplerConfig {
|
||||
pub struct LunaSamplingRequest {
|
||||
/// Generator selected by the owning session for response items.
|
||||
pub item_id_generator: codex_protocol::ItemIdGenerator,
|
||||
/// Cyber selection captured from the owning turn; Daybreak reviews use Blue.
|
||||
pub cyber_access_program: Option<CyberAccessProgram>,
|
||||
/// ID of the response handling the classified tool.
|
||||
pub parent_response_id: Option<String>,
|
||||
/// Trusted classifier instructions with their role and content attribution.
|
||||
pub instructions: RenderedFragment,
|
||||
/// Composed evidence messages, with roles, annotations and content order intact.
|
||||
@@ -247,21 +228,14 @@ impl LunaSampler {
|
||||
prompt_cache_options: None,
|
||||
text: None,
|
||||
client_metadata: None,
|
||||
access_programs: None,
|
||||
};
|
||||
execution::SamplingExecution {
|
||||
auth_owner,
|
||||
cyber_access_program: codex_guardian_reviewer::guardian_cyber_access_program(
|
||||
request
|
||||
.cyber_access_program
|
||||
.filter(|_| self.config.inherit_parent_cyber_access_program),
|
||||
),
|
||||
config: Arc::clone(&self.config),
|
||||
connections: Arc::clone(&self.connections),
|
||||
request: api_request,
|
||||
// Retries keep the classification's inference turn identity.
|
||||
turn_id: Uuid::now_v7().to_string(),
|
||||
parent_response_id: request.parent_response_id.clone(),
|
||||
parent_turn_id: request.parent_turn_id.clone(),
|
||||
root_turn_id: request.root_turn_id.clone(),
|
||||
}
|
||||
|
||||
@@ -29,14 +29,10 @@ use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPolicy;
|
||||
use codex_login::AuthChangeState;
|
||||
use codex_login::AuthOwner;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::ClientRedirectPolicy;
|
||||
use codex_login::default_client::add_originator_header;
|
||||
use codex_login::default_client::create_client_for_route_async;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_model_provider::ACCOUNT_ROUTING_HEADER;
|
||||
use codex_model_provider::AgentIdentitySessionFallback;
|
||||
use codex_model_provider::ProviderAuthScope;
|
||||
use codex_model_provider::ResponsesConnectionKey;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_websocket_client::WebSocketConnector;
|
||||
@@ -59,12 +55,6 @@ const MAX_CONCURRENT_OPENS: usize = 4;
|
||||
const REFILL_LOW_WATERMARK: usize = INITIAL_WEBSOCKET_CONNECTIONS / 2;
|
||||
const RESPONSES_WEBSOCKETS_BETA: &str = "responses_websockets=2026-02-06";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum RequestMode {
|
||||
Regular,
|
||||
GuardianClassifier,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionPool {
|
||||
config: Arc<LunaSamplerConfig>,
|
||||
pub(super) idle_connections: Mutex<Vec<PooledConnection>>,
|
||||
@@ -86,13 +76,11 @@ struct HttpTransport {
|
||||
|
||||
pub(super) struct PooledConnection {
|
||||
connection: ResponsesWebsocketConnection,
|
||||
request_kind: RequestMode,
|
||||
// The bridge routes by thread ID, so each socket needs its own identity.
|
||||
pub(super) thread_id: String,
|
||||
pub(super) expires_at: Instant,
|
||||
auth_changes: Option<tokio::sync::watch::Receiver<AuthChangeState>>,
|
||||
key: ResponsesConnectionKey,
|
||||
runtime_id: Option<String>,
|
||||
auth_owner: Option<AuthOwner>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
}
|
||||
@@ -101,9 +89,7 @@ pub(super) struct PooledConnection {
|
||||
struct ClientSetup {
|
||||
provider: Provider,
|
||||
http_client_factory: HttpClientFactory,
|
||||
runtime_id: Option<String>,
|
||||
auth_owner: Option<AuthOwner>,
|
||||
request_kind: RequestMode,
|
||||
auth: SharedAuthProvider,
|
||||
redirect_policy: ClientRedirectPolicy,
|
||||
key: ResponsesConnectionKey,
|
||||
@@ -117,7 +103,6 @@ enum Connection {
|
||||
|
||||
pub(super) struct ConnectionLease {
|
||||
pub(super) thread_id: String,
|
||||
pub(super) request_kind: RequestMode,
|
||||
pub(super) auth_owner: Option<AuthOwner>,
|
||||
connection: Connection,
|
||||
pool: Arc<ConnectionPool>,
|
||||
@@ -160,10 +145,6 @@ impl ConnectionPool {
|
||||
}
|
||||
|
||||
fn start_refill(self: &Arc<Self>, guard: OwnedMutexGuard<()>) -> Option<JoinHandle<()>> {
|
||||
// Runtime sources must be reauthenticated when a classification is admitted.
|
||||
if self.config.provider.runtime_auth().is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut retry_after = self
|
||||
.retry_after
|
||||
.lock()
|
||||
@@ -232,48 +213,40 @@ impl ConnectionPool {
|
||||
.map_err(|error| LunaSamplerError::Api(ApiError::Stream(error.to_string())))?;
|
||||
let admitted = Instant::now();
|
||||
let setup = self.client_setup().await?;
|
||||
let fresh_connection = self.runtime_connection(&setup).await?;
|
||||
let ClientSetup {
|
||||
mut provider,
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
request_kind,
|
||||
redirect_policy,
|
||||
key,
|
||||
auth_changes,
|
||||
} = setup;
|
||||
let setup_finished = Instant::now();
|
||||
let connection = if runtime_id.is_some() {
|
||||
fresh_connection
|
||||
} else {
|
||||
loop {
|
||||
let idle = self
|
||||
.idle_connections
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.pop();
|
||||
match idle {
|
||||
Some(connection)
|
||||
if connection.key == key
|
||||
&& connection.runtime_id == runtime_id
|
||||
&& connection.auth_owner == auth_owner
|
||||
&& connection
|
||||
.auth_changes
|
||||
.as_ref()
|
||||
.is_none_or(|auth| !auth.has_changed().unwrap_or(true))
|
||||
&& Instant::now() < connection.expires_at
|
||||
&& !connection.connection.is_closed().await =>
|
||||
{
|
||||
break Some(connection);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
let connection = loop {
|
||||
let idle = self
|
||||
.idle_connections
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.pop();
|
||||
match idle {
|
||||
Some(connection)
|
||||
if connection.key == key
|
||||
&& connection.auth_owner == auth_owner
|
||||
&& connection
|
||||
.auth_changes
|
||||
.as_ref()
|
||||
.is_none_or(|auth| !auth.has_changed().unwrap_or(true))
|
||||
&& Instant::now() < connection.expires_at
|
||||
&& !connection.connection.is_closed().await =>
|
||||
{
|
||||
break Some(connection);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => break None,
|
||||
}
|
||||
};
|
||||
let (connection, thread_id, request_kind) = match connection {
|
||||
let (connection, thread_id) = match connection {
|
||||
Some(connection) => {
|
||||
if self
|
||||
.idle_connections
|
||||
@@ -285,19 +258,13 @@ impl ConnectionPool {
|
||||
self.replenish();
|
||||
}
|
||||
let thread_id = connection.thread_id.clone();
|
||||
let request_kind = connection.request_kind;
|
||||
(Connection::Websocket(connection), thread_id, request_kind)
|
||||
(Connection::Websocket(connection), thread_id)
|
||||
}
|
||||
None => {
|
||||
self.replenish();
|
||||
// Sampling owns the retry budget across both transports.
|
||||
provider.retry.max_attempts = 0;
|
||||
let url = provider.url_for_path("/responses");
|
||||
let redirect_policy = if provider.headers.contains_key(ACCOUNT_ROUTING_HEADER) {
|
||||
ClientRedirectPolicy::Reject
|
||||
} else {
|
||||
redirect_policy
|
||||
};
|
||||
let transport = {
|
||||
let mut cached = self
|
||||
.http_transport
|
||||
@@ -340,11 +307,7 @@ impl ConnectionPool {
|
||||
.await?
|
||||
.clone();
|
||||
let client = ResponsesClient::new(transport, provider, auth);
|
||||
(
|
||||
Connection::Http(client),
|
||||
ThreadId::new().to_string(),
|
||||
request_kind,
|
||||
)
|
||||
(Connection::Http(client), ThreadId::new().to_string())
|
||||
}
|
||||
};
|
||||
if auth_changes
|
||||
@@ -375,7 +338,6 @@ impl ConnectionPool {
|
||||
Ok(ConnectionLease {
|
||||
auth_owner,
|
||||
thread_id,
|
||||
request_kind,
|
||||
connection,
|
||||
pool: Arc::clone(self),
|
||||
_permit: permit,
|
||||
@@ -385,12 +347,6 @@ impl ConnectionPool {
|
||||
async fn client_setup(&self) -> Result<ClientSetup, LunaSamplerError> {
|
||||
let setup = codex_model_provider::resolve_request(
|
||||
self.config.provider.as_ref(),
|
||||
Some(ProviderAuthScope {
|
||||
agent_identity_policy: self.config.agent_identity_policy,
|
||||
session_source: self.config.session_source.clone(),
|
||||
agent_identity_session_fallback: AgentIdentitySessionFallback::default(),
|
||||
}),
|
||||
Some(&self.config.workspace_routing),
|
||||
self.config.http_client_factory.clone(),
|
||||
)
|
||||
.await
|
||||
@@ -406,32 +362,22 @@ impl ConnectionPool {
|
||||
)));
|
||||
}
|
||||
let key = ResponsesConnectionKey::new(&setup.api_provider, setup.auth_revision);
|
||||
let request_kind = self.responses_request_kind(setup.auth.as_ref());
|
||||
Ok(ClientSetup {
|
||||
provider: setup.api_provider,
|
||||
auth: setup.api_auth,
|
||||
redirect_policy: setup.redirect_policy,
|
||||
http_client_factory: setup.http_client_factory,
|
||||
runtime_id: setup.runtime_id,
|
||||
auth_owner: setup.auth_owner,
|
||||
request_kind,
|
||||
key,
|
||||
auth_changes,
|
||||
})
|
||||
}
|
||||
|
||||
fn headers(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
request_kind: RequestMode,
|
||||
) -> Result<HeaderMap, LunaSamplerError> {
|
||||
fn headers(&self, thread_id: &str) -> Result<HeaderMap, LunaSamplerError> {
|
||||
let mut headers = build_session_headers(
|
||||
Some(self.config.session_id.clone()),
|
||||
Some(thread_id.to_owned()),
|
||||
);
|
||||
if request_kind == RequestMode::GuardianClassifier {
|
||||
headers.insert("x-codex-guardian", HeaderValue::from_static("classifier"));
|
||||
}
|
||||
headers.insert("x-openai-subagent", HeaderValue::from_static("guardian"));
|
||||
headers.insert(
|
||||
"x-codex-window-id",
|
||||
@@ -453,69 +399,6 @@ impl ConnectionPool {
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
fn responses_request_kind(&self, auth: Option<&CodexAuth>) -> RequestMode {
|
||||
let provider = self.config.provider.info();
|
||||
if auth.is_some_and(CodexAuth::uses_codex_backend)
|
||||
&& provider.is_openai()
|
||||
&& provider.requires_openai_auth
|
||||
&& provider.env_key.is_none()
|
||||
&& provider.experimental_bearer_token.is_none()
|
||||
&& provider.auth.is_none()
|
||||
&& provider.aws.is_none()
|
||||
{
|
||||
RequestMode::GuardianClassifier
|
||||
} else {
|
||||
RequestMode::Regular
|
||||
}
|
||||
}
|
||||
|
||||
async fn runtime_connection(
|
||||
&self,
|
||||
setup: &ClientSetup,
|
||||
) -> Result<Option<PooledConnection>, LunaSamplerError> {
|
||||
if setup.runtime_id.is_none() || !self.config.provider.info().supports_websockets {
|
||||
return Ok(None);
|
||||
}
|
||||
if self
|
||||
.retry_after
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.is_some_and(|deadline| Instant::now() < deadline)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(permit) = Arc::clone(&self.sockets).try_acquire_owned() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match self.open_connection_with_setup(permit, setup.clone()).await {
|
||||
Ok(connection) => Ok(Some(connection)),
|
||||
Err(LunaSamplerError::ConnectionTimeout) => {
|
||||
*self
|
||||
.retry_after
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
Ok(None)
|
||||
}
|
||||
Err(
|
||||
error @ LunaSamplerError::Api(ApiError::Transport(
|
||||
TransportError::Policy(_) | TransportError::Build(_),
|
||||
)),
|
||||
) => Err(error),
|
||||
Err(
|
||||
error @ LunaSamplerError::Api(ApiError::Transport(TransportError::Http {
|
||||
status:
|
||||
http::StatusCode::UNAUTHORIZED
|
||||
| http::StatusCode::FORBIDDEN
|
||||
| http::StatusCode::TOO_MANY_REQUESTS,
|
||||
..
|
||||
})),
|
||||
) => Err(error),
|
||||
// Unsupported upgrades and connection failures can still use HTTP.
|
||||
Err(_) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn open_connection(
|
||||
&self,
|
||||
permit: OwnedSemaphorePermit,
|
||||
@@ -533,15 +416,13 @@ impl ConnectionPool {
|
||||
provider,
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
request_kind,
|
||||
redirect_policy: _,
|
||||
key,
|
||||
auth_changes,
|
||||
} = setup;
|
||||
let thread_id = ThreadId::new().to_string();
|
||||
let mut headers = self.headers(&thread_id, request_kind)?;
|
||||
let mut headers = self.headers(&thread_id)?;
|
||||
headers.insert(
|
||||
"openai-beta",
|
||||
HeaderValue::from_static(RESPONSES_WEBSOCKETS_BETA),
|
||||
@@ -611,12 +492,10 @@ impl ConnectionPool {
|
||||
|
||||
Ok(PooledConnection {
|
||||
connection,
|
||||
request_kind,
|
||||
thread_id,
|
||||
expires_at: Instant::now() + MAX_WEBSOCKET_AGE,
|
||||
auth_changes,
|
||||
key,
|
||||
runtime_id,
|
||||
auth_owner,
|
||||
_permit: permit,
|
||||
})
|
||||
@@ -650,7 +529,7 @@ impl ConnectionLease {
|
||||
thread_id: Some(self.thread_id.clone()),
|
||||
extra_headers: self
|
||||
.pool
|
||||
.headers(&self.thread_id, self.request_kind)
|
||||
.headers(&self.thread_id)
|
||||
.map_err(|error| ApiError::Stream(error.to_string()))?,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -664,7 +543,6 @@ impl ConnectionLease {
|
||||
|
||||
pub(super) async fn reuse(self) {
|
||||
if let Connection::Websocket(connection) = self.connection
|
||||
&& connection.runtime_id.is_none()
|
||||
&& !connection.connection.is_closed().await
|
||||
{
|
||||
self.pool
|
||||
|
||||
@@ -12,10 +12,7 @@ use anyhow::Result;
|
||||
use codex_guardian_context::TranscriptCursor;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_model_provider::ModelProviderFuture;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use core_test_support::responses;
|
||||
@@ -184,7 +181,7 @@ async fn replenishes_before_last_idle_socket_is_leased() -> Result<()> {
|
||||
#[tokio::test]
|
||||
async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for uses_codex_backend in [false, true] {
|
||||
for codex_style_base_path in [false, true] {
|
||||
let http = responses::start_mock_server().await;
|
||||
let events = vec![
|
||||
responses::ev_output_text_delta("low"),
|
||||
@@ -196,7 +193,7 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
connections.push(vec![events.clone()]);
|
||||
let ws = responses::start_websocket_server(connections).await;
|
||||
let gateway = Gateway::new(&http.uri(), ws.uri()).await?;
|
||||
let base_path = if uses_codex_backend {
|
||||
let base_path = if codex_style_base_path {
|
||||
"/backend-api/codex"
|
||||
} else {
|
||||
"/v1"
|
||||
@@ -205,11 +202,13 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(AuthManager::from_auth_for_testing(if uses_codex_backend {
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing()
|
||||
} else {
|
||||
CodexAuth::from_api_key("test-api-key")
|
||||
})),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
if codex_style_base_path {
|
||||
CodexAuth::from_api_key("Test API Key")
|
||||
} else {
|
||||
CodexAuth::from_api_key("test-api-key")
|
||||
},
|
||||
)),
|
||||
);
|
||||
config.service_tier = Some("priority".to_owned());
|
||||
let sampler = LunaSampler::new(config);
|
||||
@@ -220,10 +219,12 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
let mut request = sample_request("parent-turn");
|
||||
request.parent_response_id = Some("resp-parent".to_owned());
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), sampler.sample(request)).await??,
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
sampler.sample(sample_request("parent-turn"))
|
||||
)
|
||||
.await??,
|
||||
"low"
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -253,30 +254,17 @@ async fn cold_pool_uses_http_during_open_timeout_then_recovers_after_cooldown()
|
||||
|
||||
let requests = http_mock.requests();
|
||||
let first = &requests[0];
|
||||
let expected_path = if uses_codex_backend {
|
||||
let expected_path = if codex_style_base_path {
|
||||
"/backend-api/codex/responses"
|
||||
} else {
|
||||
"/v1/responses"
|
||||
};
|
||||
assert_eq!(first.path(), expected_path);
|
||||
assert_eq!(
|
||||
first.header("x-codex-guardian").as_deref(),
|
||||
uses_codex_backend.then_some("classifier")
|
||||
);
|
||||
assert_eq!(first.header("x-codex-guardian"), None);
|
||||
assert!(first.header("authorization").is_some());
|
||||
let body = first.body_json();
|
||||
assert_eq!(
|
||||
body["service_tier"].as_str(),
|
||||
if uses_codex_backend {
|
||||
None
|
||||
} else {
|
||||
Some("priority")
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
body["client_metadata"]["parent_response_id"].as_str(),
|
||||
uses_codex_backend.then_some("resp-parent")
|
||||
);
|
||||
assert_eq!(body["service_tier"].as_str(), Some("priority"));
|
||||
assert_eq!(body["client_metadata"].get("parent_response_id"), None);
|
||||
|
||||
gateway.allowed_opens.store(usize::MAX, Ordering::SeqCst);
|
||||
tokio::time::pause();
|
||||
@@ -502,17 +490,6 @@ async fn cancellation_closes_http_before_headers_and_while_draining_the_body() -
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct RoutingPolicy(Mutex<Option<WorkspaceRouting>>);
|
||||
|
||||
impl WorkspaceRoutingResolver for RoutingPolicy {
|
||||
fn resolve(
|
||||
&self,
|
||||
_request: WorkspaceRoutingRequest,
|
||||
) -> ModelProviderFuture<'_, std::io::Result<Option<WorkspaceRouting>>> {
|
||||
Box::pin(async { Ok(self.0.lock().unwrap().clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sampling_uses_new_credentials_after_logout_and_login() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -579,13 +556,9 @@ async fn sampling_uses_new_credentials_after_logout_and_login() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_headers() -> Result<()> {
|
||||
async fn http_cache_reuses_transport_with_default_redirect_policy() -> Result<()> {
|
||||
let base_url = "https://localhost:9/backend-api/codex".to_owned();
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let resolver = Arc::new(RoutingPolicy(Mutex::new(None)));
|
||||
let routing_owner: Arc<dyn WorkspaceRoutingResolver> = resolver.clone();
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&routing_owner));
|
||||
let auth = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
@@ -595,19 +568,9 @@ async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_heade
|
||||
// Exercise HTTP leases without starting a background WebSocket opener.
|
||||
*pool.retry_after.lock().unwrap() = Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
let mut previous: Option<Arc<HttpTransport>> = None;
|
||||
for (routing, expected_policy) in [
|
||||
(None, ClientRedirectPolicy::Default),
|
||||
(Some("NO_CONSTRAINT"), ClientRedirectPolicy::Reject),
|
||||
(Some("NO_CONSTRAINT"), ClientRedirectPolicy::Reject),
|
||||
(None, ClientRedirectPolicy::Default),
|
||||
] {
|
||||
*resolver.0.lock().unwrap() = routing.map(|account_routing_override| WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://localhost:9".into(),
|
||||
account_routing_override: account_routing_override.into(),
|
||||
});
|
||||
for _ in 0..2 {
|
||||
let setup = pool.client_setup().await?;
|
||||
assert!(!setup.provider.headers.contains_key(ACCOUNT_ROUTING_HEADER));
|
||||
assert_eq!(setup.redirect_policy, ClientRedirectPolicy::Default);
|
||||
let lease = pool.lease().await?;
|
||||
assert!(matches!(lease.connection, Connection::Http(_)));
|
||||
let cached = Arc::clone(pool.http_transport.lock().unwrap().as_ref().unwrap());
|
||||
@@ -615,293 +578,13 @@ async fn http_cache_preserves_no_constraint_redirect_policy_and_configured_heade
|
||||
(cached.url.as_str(), cached.redirect_policy),
|
||||
(
|
||||
"https://localhost:9/backend-api/codex/responses",
|
||||
expected_policy
|
||||
ClientRedirectPolicy::Default
|
||||
),
|
||||
);
|
||||
if let Some(previous) = previous {
|
||||
assert_eq!(
|
||||
Arc::ptr_eq(&previous, &cached),
|
||||
previous.redirect_policy == expected_policy,
|
||||
);
|
||||
assert!(Arc::ptr_eq(&previous, &cached));
|
||||
}
|
||||
previous = Some(cached);
|
||||
}
|
||||
|
||||
let mut config = sampler_config("https://localhost:9/v1".into());
|
||||
let mut info = config.provider.info().clone();
|
||||
info.http_headers = Some(std::collections::HashMap::from([(
|
||||
ACCOUNT_ROUTING_HEADER.into(),
|
||||
"us".into(),
|
||||
)]));
|
||||
config.provider = create_model_provider(info, config.provider.auth_manager());
|
||||
let pool = ConnectionPool::new(Arc::new(config));
|
||||
*pool.retry_after.lock().unwrap() = Some(Instant::now() + CONNECT_COOLDOWN);
|
||||
assert_eq!(
|
||||
pool.client_setup().await?.redirect_policy,
|
||||
ClientRedirectPolicy::Default
|
||||
);
|
||||
let lease = pool.lease().await?;
|
||||
assert!(matches!(lease.connection, Connection::Http(_)));
|
||||
assert_eq!(
|
||||
pool.http_transport
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.redirect_policy,
|
||||
ClientRedirectPolicy::Reject,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn runtime_transports_authenticate_each_classification() -> Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use serde_json::json;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
struct MutableAuth(Mutex<CodexAuth>);
|
||||
impl codex_login::ExternalAuth for MutableAuth {
|
||||
fn resolve(&self) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.lock().unwrap().clone()) })
|
||||
}
|
||||
|
||||
fn refresh(
|
||||
&self,
|
||||
_context: codex_login::ExternalAuthRefreshContext,
|
||||
) -> codex_login::ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for transport in [
|
||||
"http",
|
||||
"websocket",
|
||||
"upgrade_required",
|
||||
"legacy_endpoint",
|
||||
"changed_auth",
|
||||
"denied",
|
||||
] {
|
||||
let websocket = transport == "websocket";
|
||||
let denied = transport == "denied";
|
||||
let changed_auth = transport == "changed_auth";
|
||||
let source = Arc::new(MutableAuth(Mutex::new(CodexAuth::from_api_key(
|
||||
"guardian-key",
|
||||
))));
|
||||
let registration = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-guardian",
|
||||
"agent_host_id": "host-guardian",
|
||||
"actor": {"kind": "platform", "user_id": "actor", "organization_id": "org", "project_id": null},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(®istration)
|
||||
.await;
|
||||
let response = vec![
|
||||
responses::ev_output_text_delta("low"),
|
||||
responses::ev_completed("score"),
|
||||
];
|
||||
let ws = if websocket {
|
||||
// Each peer leaves another response available, so closure cannot force the retry.
|
||||
Some(
|
||||
responses::start_websocket_server(vec![
|
||||
vec![response.clone(), response.clone()],
|
||||
vec![response.clone(), response.clone()],
|
||||
])
|
||||
.await,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let http = MockServer::start().await;
|
||||
let upgrade_response = if denied {
|
||||
ResponseTemplate::new(403).set_body_json(json!({"error": {
|
||||
"code": "runtime_instance_paused", "type": "runtime_agent_error",
|
||||
"message": "The runtime agent instance is paused."
|
||||
}}))
|
||||
} else if transport == "legacy_endpoint" {
|
||||
ResponseTemplate::new(404)
|
||||
} else {
|
||||
ResponseTemplate::new(426)
|
||||
};
|
||||
let handshake_source = Arc::clone(&source);
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(move |_request: &wiremock::Request| {
|
||||
if changed_auth {
|
||||
*handshake_source.0.lock().unwrap() =
|
||||
CodexAuth::from_api_key("replacement-key");
|
||||
}
|
||||
upgrade_response.clone()
|
||||
})
|
||||
.expect(match transport {
|
||||
"upgrade_required" | "legacy_endpoint" => 2,
|
||||
"changed_auth" | "denied" => 1,
|
||||
_ => 0,
|
||||
})
|
||||
.mount(&http)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/responses"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200)
|
||||
.insert_header("content-type", "text/event-stream")
|
||||
.set_body_string(responses::sse(response)),
|
||||
)
|
||||
.expect(if websocket || denied {
|
||||
0
|
||||
} else if changed_auth {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
})
|
||||
.mount(&http)
|
||||
.await;
|
||||
let url = ws.as_ref().map_or_else(
|
||||
|| http.uri(),
|
||||
|ws| ws.uri().replacen("ws://", "http://", /*count*/ 1),
|
||||
);
|
||||
let mut config = sampler_config(url);
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("guardian-key"));
|
||||
if changed_auth {
|
||||
credentials.set_external_auth(source.clone()).await?;
|
||||
}
|
||||
let runtime = Arc::new(RuntimeAuthManager::new(
|
||||
Arc::clone(&credentials),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/register", registration.uri()).parse()?,
|
||||
));
|
||||
let mut info = config.provider.info().clone();
|
||||
info.supports_websockets = transport != "http";
|
||||
config.provider = codex_model_provider::test_support::runtime_model_provider(
|
||||
info,
|
||||
Arc::clone(&credentials),
|
||||
(runtime, mode),
|
||||
);
|
||||
let sampler = LunaSampler::new(config);
|
||||
sampler.prewarm().await;
|
||||
if let Some(ws) = &ws {
|
||||
assert!(
|
||||
ws.handshakes().is_empty(),
|
||||
"prewarming must not admit runtime work"
|
||||
);
|
||||
}
|
||||
if denied {
|
||||
let error = sampler.sample(sample_request("denied")).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
error,
|
||||
LunaSamplerError::Api(ApiError::Transport(TransportError::Http {
|
||||
status: http::StatusCode::FORBIDDEN,
|
||||
..
|
||||
}))
|
||||
),
|
||||
"{error:?}"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(sampler.sample(sample_request("first")).await?, "low");
|
||||
if changed_auth {
|
||||
assert_eq!(
|
||||
credentials.auth().await.unwrap().get_token()?,
|
||||
"replacement-key"
|
||||
);
|
||||
} else {
|
||||
assert_eq!(sampler.sample(sample_request("second")).await?, "low");
|
||||
}
|
||||
}
|
||||
let headers = if let Some(ws) = &ws {
|
||||
assert_eq!(
|
||||
ws.connections().iter().map(Vec::len).collect::<Vec<_>>(),
|
||||
vec![1, 1]
|
||||
);
|
||||
ws.handshakes()
|
||||
.iter()
|
||||
.map(|h| {
|
||||
(
|
||||
h.header("authorization").unwrap(),
|
||||
h.header("x-openai-agent-assertion"),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
http.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|request| {
|
||||
(
|
||||
request.headers["authorization"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned(),
|
||||
request
|
||||
.headers
|
||||
.get("x-openai-agent-assertion")
|
||||
.map(|value| value.to_str().unwrap().to_owned()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let expected_attempts = match transport {
|
||||
"upgrade_required" | "legacy_endpoint" => 4,
|
||||
"denied" => 1,
|
||||
_ => 2,
|
||||
};
|
||||
assert_eq!(headers.len(), expected_attempts);
|
||||
let mut proofs = std::collections::BTreeSet::new();
|
||||
for (authorization, supplemental) in headers {
|
||||
let proof = match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(authorization, "Bearer guardian-key");
|
||||
supplemental.unwrap()
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(supplemental.is_none());
|
||||
authorization
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
};
|
||||
let payload: serde_json::Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(proof.split('.').nth(/*n*/ 2).unwrap())?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], "runtime-guardian");
|
||||
assert!(
|
||||
proofs.insert(proof),
|
||||
"each attempt must authenticate afresh"
|
||||
);
|
||||
}
|
||||
registration.verify().await;
|
||||
http.verify().await;
|
||||
drop(sampler);
|
||||
if let Some(ws) = ws {
|
||||
ws.shutdown().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ use super::LunaSamplerConfig;
|
||||
use super::LunaSamplerError;
|
||||
use super::MAX_OUTPUT_BYTES;
|
||||
use super::SampledScore;
|
||||
use super::connection_pool::RequestMode;
|
||||
use super::response::PendingResponse;
|
||||
use super::telemetry::SamplingTelemetry;
|
||||
use super::telemetry::record_retry;
|
||||
@@ -18,14 +17,12 @@ use codex_api::ApiError;
|
||||
use codex_api::ResponseEvent;
|
||||
use codex_api::ResponsesApiRequest;
|
||||
use codex_api::TransportError;
|
||||
use codex_core::cyber_access_program;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_login::AuthOwner;
|
||||
use codex_login::UnauthorizedRecovery;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use http::StatusCode;
|
||||
use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
@@ -39,12 +36,10 @@ const TURN_METADATA_KEY: &str = "x-codex-turn-metadata";
|
||||
|
||||
pub(super) struct SamplingExecution {
|
||||
pub(super) auth_owner: Option<AuthOwner>,
|
||||
pub(super) cyber_access_program: Option<CyberAccessProgram>,
|
||||
pub(super) config: Arc<LunaSamplerConfig>,
|
||||
pub(super) connections: Arc<ConnectionPool>,
|
||||
pub(super) request: ResponsesApiRequest,
|
||||
pub(super) turn_id: String,
|
||||
pub(super) parent_response_id: Option<String>,
|
||||
pub(super) parent_turn_id: String,
|
||||
pub(super) root_turn_id: Option<String>,
|
||||
}
|
||||
@@ -243,29 +238,8 @@ impl SamplingExecution {
|
||||
{
|
||||
return Err(account_changed_error());
|
||||
}
|
||||
// Omitted programs need no auth lookup, which can refresh credentials.
|
||||
self.request.access_programs = match self.cyber_access_program {
|
||||
None => None,
|
||||
Some(program) => {
|
||||
let auth = tokio::select! {
|
||||
biased;
|
||||
_ = &mut owner_changed => return Err(account_changed_error()),
|
||||
auth = self.config.provider.auth() => auth,
|
||||
};
|
||||
cyber_access_program::for_auth(
|
||||
auth.as_ref(),
|
||||
Some(program),
|
||||
self.config.api_key_cyber_access_programs,
|
||||
)
|
||||
.map_err(LunaSamplerError::Provider)?
|
||||
}
|
||||
};
|
||||
ensure_account_owner()?;
|
||||
self.request.service_tier = if lease.request_kind == RequestMode::GuardianClassifier {
|
||||
None
|
||||
} else {
|
||||
self.config.service_tier.clone()
|
||||
};
|
||||
self.request.service_tier = self.config.service_tier.clone();
|
||||
let thread_id = &lease.thread_id;
|
||||
let mut turn_metadata = json!({
|
||||
"session_id": self.config.session_id,
|
||||
@@ -291,11 +265,6 @@ impl SamplingExecution {
|
||||
turn_metadata["root_turn_id"] = json!(root_turn_id);
|
||||
}
|
||||
client_metadata.insert(TURN_METADATA_KEY.to_owned(), turn_metadata.to_string());
|
||||
if lease.request_kind == RequestMode::GuardianClassifier
|
||||
&& let Some(parent_response_id) = &self.parent_response_id
|
||||
{
|
||||
client_metadata.insert("parent_response_id".to_owned(), parent_response_id.clone());
|
||||
}
|
||||
self.request.client_metadata = Some(client_metadata);
|
||||
let stream = match tokio::select! {
|
||||
biased;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Keeps classifier evidence within its owning account and thread routing binding.
|
||||
//! Keeps classifier evidence within the credential owner that started the request.
|
||||
|
||||
use super::connect_sampler;
|
||||
use super::proxy_websocket_servers;
|
||||
@@ -10,66 +10,23 @@ use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_login::WorkspaceRouting;
|
||||
use codex_login::WorkspaceRoutingRequest;
|
||||
use codex_login::WorkspaceRoutingResolver;
|
||||
use codex_model_provider::ModelProviderFuture;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
type RoutingFuture<'a> = ModelProviderFuture<'a, std::io::Result<Option<WorkspaceRouting>>>;
|
||||
|
||||
struct UnavailableRouting;
|
||||
|
||||
impl WorkspaceRoutingResolver for UnavailableRouting {
|
||||
fn resolve(&self, _request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async { Err(std::io::Error::other("discovery unavailable")) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_routing_blocks_a_prewarmed_classifier_connection() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let response = vec![vec![ev_assistant_message("r1", "low"), ev_completed("r1")]];
|
||||
let server = responses::start_websocket_server(vec![response.clone(), response]).await;
|
||||
let base_url = proxy_websocket_servers(&[&server, &server])
|
||||
.await?
|
||||
.replace("/v1", "/backend-api/codex");
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(auth.clone()),
|
||||
);
|
||||
let sampler = connect_sampler(config).await?;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = Arc::new(UnavailableRouting);
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let error = sampler.sample(sample_request("turn-1")).await.unwrap_err();
|
||||
assert!(
|
||||
error.to_string().contains("discovery unavailable"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(server.connections().iter().all(Vec::is_empty));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct AuthAfterRouting {
|
||||
/// Host-supplied credentials that switch to a different key once `resolved` is set.
|
||||
struct SwitchingAuth {
|
||||
initial: CodexAuth,
|
||||
updated: CodexAuth,
|
||||
resolved: AtomicBool,
|
||||
}
|
||||
|
||||
impl ExternalAuth for AuthAfterRouting {
|
||||
impl ExternalAuth for SwitchingAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async {
|
||||
Ok(if self.resolved.load(Ordering::SeqCst) {
|
||||
@@ -85,152 +42,9 @@ impl ExternalAuth for AuthAfterRouting {
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkspaceRoutingResolver for AuthAfterRouting {
|
||||
fn resolve(&self, _request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async {
|
||||
self.resolved.store(/*val*/ true, Ordering::SeqCst);
|
||||
Ok(None)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn classification_retries_refreshes_but_never_switches_accounts() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
// Both tokens identify the same user; their signatures differ after refresh.
|
||||
let token =
|
||||
"header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19";
|
||||
for account in ["workspace-a", "workspace-b"] {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
ev_assistant_message("score", "low"),
|
||||
ev_completed("score"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let home = tempfile::tempdir()?;
|
||||
let changes = Arc::new(AuthAfterRouting {
|
||||
initial: CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("{token}.initial"),
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
updated: CodexAuth::from_external_chatgpt_tokens(
|
||||
&format!("{token}.refreshed"),
|
||||
account,
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
resolved: AtomicBool::new(/*v*/ false),
|
||||
});
|
||||
let auth = AuthManager::from_auth_for_testing_with_home(
|
||||
changes.initial.clone(),
|
||||
home.path().to_owned(),
|
||||
);
|
||||
auth.set_external_auth(changes.clone()).await?;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> = changes;
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let mut config = sampler_config(format!("{}/backend-api/codex", server.uri()));
|
||||
config.provider = create_model_provider(config.provider.info().clone(), Some(auth));
|
||||
let sampler = super::LunaSampler::new(config);
|
||||
let result = sampler.sample(sample_request("turn-1")).await;
|
||||
if account == "workspace-a" {
|
||||
assert_eq!(result?, "low");
|
||||
let request = response.single_request();
|
||||
assert_eq!(
|
||||
(
|
||||
request.header("chatgpt-account-id"),
|
||||
request.header("authorization")
|
||||
),
|
||||
(
|
||||
Some("workspace-a".into()),
|
||||
Some(format!("Bearer {token}.refreshed"))
|
||||
),
|
||||
);
|
||||
} else {
|
||||
assert!(result.unwrap_err().to_string().contains("account changed"));
|
||||
assert!(
|
||||
response.requests().is_empty(),
|
||||
"evidence must not reach the new account"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ChangedBootstrap(AtomicBool);
|
||||
|
||||
impl WorkspaceRoutingResolver for ChangedBootstrap {
|
||||
fn resolve(&self, request: WorkspaceRoutingRequest) -> RoutingFuture<'_> {
|
||||
Box::pin(async move {
|
||||
if request.previously_routed {
|
||||
Err(std::io::Error::other(
|
||||
"bootstrap changed; start a new thread",
|
||||
))
|
||||
} else if self.0.swap(/*val*/ false, Ordering::SeqCst) {
|
||||
Ok(Some(WorkspaceRouting {
|
||||
chatgpt_account_id: "account_id".into(),
|
||||
backend_origin: "https://gov.chatgpt.com".into(),
|
||||
account_routing_override: "us_cr".into(),
|
||||
}))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn idle_classifier_retains_the_owning_threads_workspace_binding() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let thread_server = responses::start_mock_server().await;
|
||||
let test = core_test_support::test_codex::test_codex()
|
||||
.with_auth_manager(Arc::clone(&auth))
|
||||
.build_with_auto_env(&thread_server)
|
||||
.await?;
|
||||
let server = responses::start_mock_server().await;
|
||||
let resolver: Arc<dyn WorkspaceRoutingResolver> =
|
||||
Arc::new(ChangedBootstrap(AtomicBool::new(/*v*/ true)));
|
||||
auth.set_workspace_routing_resolver(Arc::downgrade(&resolver));
|
||||
let mut config = test.config.clone();
|
||||
config.model_provider = ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
server.uri()
|
||||
)));
|
||||
let session_store = codex_extension_api::ExtensionData::new("session-1");
|
||||
let input = codex_extension_api::ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &codex_protocol::protocol::SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: test.codex.thread_extension_data(),
|
||||
};
|
||||
let owning_context = input
|
||||
.thread_store
|
||||
.get::<codex_model_provider::WorkspaceRoutingContext>()
|
||||
.expect("Core seeds the owning thread's routing context before extensions start");
|
||||
let classifier = crate::async_scorer::startup::sampler_config(&input, /*manager*/ None).await;
|
||||
classifier
|
||||
.provider
|
||||
.responses_api_provider(&owning_context)
|
||||
.await?;
|
||||
let sampler = super::LunaSampler::new(classifier);
|
||||
let error = sampler.sample(sample_request("turn-1")).await.unwrap_err();
|
||||
assert!(error.to_string().contains("start a new thread"), "{error}");
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_switch_cancels_request_opening_and_first_token_waits() -> Result<()> {
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
let token = "header.eyJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF91c2VyX2lkIjoidXNlci1hIn19.signature";
|
||||
for transport in ["http", "websocket"] {
|
||||
let http = responses::start_mock_server().await;
|
||||
let opening = responses::mount_response_once(
|
||||
@@ -245,17 +59,9 @@ async fn account_switch_cancels_request_opening_and_first_token_waits() -> Resul
|
||||
close_after_requests: false,
|
||||
};
|
||||
let websocket = responses::start_websocket_server_with_headers(vec![stalled; 2]).await;
|
||||
let changes = Arc::new(AuthAfterRouting {
|
||||
initial: CodexAuth::from_external_chatgpt_tokens(
|
||||
token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
updated: CodexAuth::from_external_chatgpt_tokens(
|
||||
token,
|
||||
"workspace-b",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)?,
|
||||
let changes = Arc::new(SwitchingAuth {
|
||||
initial: CodexAuth::from_api_key("key-a"),
|
||||
updated: CodexAuth::from_api_key("key-b"),
|
||||
resolved: AtomicBool::new(/*v*/ false),
|
||||
});
|
||||
let home = tempfile::tempdir()?;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use anyhow::Result;
|
||||
use codex_api::ApiError;
|
||||
use codex_context_fragments::RenderedFragment;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ContextualUserFragment;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_guardian_context::PreviousReviews;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
use codex_login::AuthHeaders;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
@@ -23,16 +21,14 @@ use codex_protocol::TranscriptFormat;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::turn_input::CyberAccessProgram;
|
||||
use codex_protocol_test_support::uuid_v7_item_id_generator_for_test;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::responses::WebSocketConnectionConfig;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_completed_with_tokens;
|
||||
use core_test_support::responses::ev_model_verification_metadata;
|
||||
use core_test_support::responses::ev_output_text_delta;
|
||||
use core_test_support::responses::ev_response_metadata;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
@@ -241,11 +237,6 @@ pub(in crate::async_scorer) async fn proxy_websocket_servers_with_http(
|
||||
|
||||
pub(in crate::async_scorer) fn sampler_config(base_url: String) -> LunaSamplerConfig {
|
||||
LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider: create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(base_url)),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
@@ -253,8 +244,6 @@ pub(in crate::async_scorer) fn sampler_config(base_url: String) -> LunaSamplerCo
|
||||
))),
|
||||
),
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: Some("guardian-v2-test".to_owned()),
|
||||
@@ -308,8 +297,6 @@ fn assert_classifier_instructions(request: &serde_json::Value) {
|
||||
pub(in crate::async_scorer) fn sample_request(parent_turn_id: &str) -> LunaSamplingRequest {
|
||||
LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![responses::user_message_item(
|
||||
"The user requested a README summary.",
|
||||
@@ -322,60 +309,6 @@ pub(in crate::async_scorer) fn sample_request(parent_turn_id: &str) -> LunaSampl
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn classifier_preserves_api_key_cyber_program_policy() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for policy in [
|
||||
ApiKeyCyberAccessPrograms::Enabled,
|
||||
ApiKeyCyberAccessPrograms::Disabled,
|
||||
ApiKeyCyberAccessPrograms::UnsupportedProvider,
|
||||
] {
|
||||
let server = responses::start_mock_server().await;
|
||||
let response = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
ev_assistant_message("score", "low"),
|
||||
ev_completed("score"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let mut config = sampler_config(server.uri());
|
||||
config.api_key_cyber_access_programs = policy;
|
||||
let sampler = LunaSampler::new(config);
|
||||
let mut request = sample_request("parent");
|
||||
request.cyber_access_program = Some(CyberAccessProgram::DaybreakRed);
|
||||
let result = sampler.sample(request).await;
|
||||
match policy {
|
||||
ApiKeyCyberAccessPrograms::Disabled => {
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("Cyber access programs are disabled for this API-key session.")
|
||||
);
|
||||
assert!(response.requests().is_empty());
|
||||
}
|
||||
ApiKeyCyberAccessPrograms::Enabled | ApiKeyCyberAccessPrograms::UnsupportedProvider => {
|
||||
assert_eq!(result?, "low");
|
||||
let expected = match policy {
|
||||
ApiKeyCyberAccessPrograms::Enabled => Some(json!({"cyber": "daybreak_blue"})),
|
||||
ApiKeyCyberAccessPrograms::UnsupportedProvider => None,
|
||||
ApiKeyCyberAccessPrograms::Disabled => unreachable!(),
|
||||
};
|
||||
assert_eq!(
|
||||
response
|
||||
.single_request()
|
||||
.body_json()
|
||||
.get("access_programs")
|
||||
.cloned(),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type RecordedMetric = (String, i64, Vec<(String, String)>);
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -534,40 +467,23 @@ impl ExternalAuth for RefreshableAuth {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Result<()> {
|
||||
async fn classifier_never_sends_backend_classifier_header() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
for (auth, base_path, expected_header, expected_service_tier) in [
|
||||
// Every provider and credential uses the regular Responses route: no classifier header,
|
||||
// no routing hint, and the configured service tier is forwarded unchanged.
|
||||
for (auth, base_path) in [
|
||||
(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
CodexAuth::from_api_key("Test API Key"),
|
||||
"/backend-api/codex",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::Headers(AuthHeaders::new(http::HeaderMap::new())),
|
||||
"/api/codex",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
"/api/codex",
|
||||
None,
|
||||
Some("priority"),
|
||||
),
|
||||
(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
"/v1",
|
||||
Some("classifier"),
|
||||
None,
|
||||
),
|
||||
(
|
||||
CodexAuth::from_api_key("test-api-key"),
|
||||
"/v1",
|
||||
None,
|
||||
Some("priority"),
|
||||
),
|
||||
(CodexAuth::from_api_key("test-api-key"), "/api/codex"),
|
||||
(CodexAuth::from_api_key("Test API Key"), "/v1"),
|
||||
(CodexAuth::from_api_key("test-api-key"), "/v1"),
|
||||
] {
|
||||
let events = vec![
|
||||
ev_assistant_message("classification", "low"),
|
||||
@@ -591,10 +507,7 @@ async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Resu
|
||||
assert_eq!(sampler.sample(sample_request("turn-1")).await?, "low");
|
||||
for handshake in server.handshakes() {
|
||||
assert_eq!(handshake.uri(), format!("{base_path}/responses"));
|
||||
assert_eq!(
|
||||
handshake.header("x-codex-guardian").as_deref(),
|
||||
expected_header
|
||||
);
|
||||
assert_eq!(handshake.header("x-codex-guardian"), None);
|
||||
assert_eq!(handshake.header("x-codex-routing-hint"), None);
|
||||
}
|
||||
let request = server
|
||||
@@ -604,7 +517,8 @@ async fn classifier_sends_guardian_header_only_with_codex_backend_auth() -> Resu
|
||||
)
|
||||
.await
|
||||
.body_json();
|
||||
assert_eq!(request["service_tier"].as_str(), expected_service_tier);
|
||||
assert_eq!(request["service_tier"].as_str(), Some("priority"));
|
||||
assert_eq!(request["client_metadata"].get("parent_response_id"), None);
|
||||
|
||||
drop(sampler);
|
||||
server.shutdown().await;
|
||||
@@ -620,7 +534,7 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let scripted_requests = vec![
|
||||
vec![
|
||||
ev_output_text_delta("low"),
|
||||
ev_model_verification_metadata("response-1", vec!["trusted_access_for_cyber"]),
|
||||
ev_response_metadata("response-1", json!({"unrelated": ["ignored"]})),
|
||||
ev_assistant_message("sample-1", "low"),
|
||||
ev_completed("response-1"),
|
||||
],
|
||||
@@ -658,15 +572,8 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
);
|
||||
|
||||
let sampler = connect_sampler(LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: Some("guardian-v2-test".to_owned()),
|
||||
@@ -707,8 +614,6 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let first = sampler
|
||||
.sample(LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![ResponseItem::Message {
|
||||
status: None,
|
||||
@@ -754,8 +659,6 @@ async fn preconnected_sampler_reuses_authenticated_websocket_for_classifications
|
||||
let second = sampler
|
||||
.sample(LunaSamplingRequest {
|
||||
item_id_generator: uuid_v7_item_id_generator_for_test(),
|
||||
cyber_access_program: None,
|
||||
parent_response_id: None,
|
||||
instructions: classifier_instructions(),
|
||||
input: vec![responses::user_message_item(
|
||||
"The user requested a source review.",
|
||||
@@ -841,15 +744,8 @@ async fn sampler_returns_classification_token_before_terminal_response_events()
|
||||
))),
|
||||
);
|
||||
let sampler = connect_sampler(LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::Disabled,
|
||||
inherit_parent_cyber_access_program: true,
|
||||
workspace_routing: codex_model_provider::WorkspaceRoutingContext::new(
|
||||
"https://chatgpt.com/backend-api".into(),
|
||||
),
|
||||
provider,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
agent_identity_policy: AgentIdentityAuthPolicy::JwtOnly,
|
||||
session_source: SessionSource::Exec,
|
||||
session_id: "session-1".to_owned(),
|
||||
thread_id: "thread-1".to_owned(),
|
||||
originator: None,
|
||||
@@ -1210,9 +1106,9 @@ async fn sampler_limits_transient_recovery_attempts() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn parent_response_id_survives_classifier_transport_retry() -> Result<()> {
|
||||
async fn classifier_transport_retry_sends_no_backend_metadata() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for uses_codex_backend in [false, true] {
|
||||
for codex_style_base_path in [false, true] {
|
||||
let healthy = responses::start_websocket_server(vec![vec![vec![
|
||||
ev_assistant_message("resp-review", "low"),
|
||||
ev_completed("resp-review"),
|
||||
@@ -1224,15 +1120,15 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
})]]]).await;
|
||||
let base_url = proxy_websocket_servers(&[&healthy, &expired]).await?;
|
||||
let mut config = sampler_config(base_url.clone());
|
||||
if uses_codex_backend {
|
||||
if codex_style_base_path {
|
||||
config.provider = create_model_provider(
|
||||
ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"{}/backend-api/codex",
|
||||
base_url.trim_end_matches("/v1")
|
||||
))),
|
||||
Some(AuthManager::from_auth_for_testing(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
)),
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"Test API Key",
|
||||
))),
|
||||
);
|
||||
}
|
||||
let metrics = Arc::new(RecordingMetrics::default());
|
||||
@@ -1245,10 +1141,7 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
.lock()
|
||||
.unwrap()
|
||||
.sort_by_key(|connection| connection.thread_id == expired_id);
|
||||
let parent_response_id = "resp-parent";
|
||||
let mut request = sample_request("turn-1");
|
||||
request.parent_response_id = Some(parent_response_id.to_owned());
|
||||
assert_eq!(sampler.sample(request).await?, "low");
|
||||
assert_eq!(sampler.sample(sample_request("turn-1")).await?, "low");
|
||||
metrics.assert_outcome("success", /*attempts*/ 2, "none");
|
||||
for server in [&expired, &healthy] {
|
||||
let requests = server.single_connection();
|
||||
@@ -1256,12 +1149,11 @@ async fn parent_response_id_survives_classifier_transport_retry() -> Result<()>
|
||||
let body = requests[0].body_json();
|
||||
assert_eq!(
|
||||
(
|
||||
body["client_metadata"].get("parent_response_id").cloned(),
|
||||
body["client_metadata"].get("parent_response_id"),
|
||||
body["client_metadata"].get("guardian_credits_requested"),
|
||||
),
|
||||
(uses_codex_backend.then(|| json!(parent_response_id)), None)
|
||||
(None, None)
|
||||
);
|
||||
assert!(!body["input"].to_string().contains(parent_response_id));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,11 +5,8 @@ use std::sync::Arc;
|
||||
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::cyber_access_program::ApiKeyCyberAccessPrograms;
|
||||
use codex_extension_api::ThreadOriginator;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
|
||||
use super::sampler::LunaSamplerConfig;
|
||||
use super::sampler::MODEL;
|
||||
@@ -18,8 +15,6 @@ pub(super) async fn sampler_config(
|
||||
input: &ThreadStartInput<'_, Config>,
|
||||
manager: Option<Arc<ThreadManager>>,
|
||||
) -> LunaSamplerConfig {
|
||||
let inherit_parent_cyber_access_program =
|
||||
codex_core::RequiredCyberAccessPrograms::for_thread(input.thread_store).is_none();
|
||||
let luna_model = if let Some(thread_manager) = manager {
|
||||
let mut model_config = input.config.to_models_manager_config();
|
||||
model_config.model_context_window = None;
|
||||
@@ -47,21 +42,8 @@ pub(super) async fn sampler_config(
|
||||
.get::<codex_model_provider::ProviderAuthContext>()
|
||||
.expect("Core installs provider auth before starting Guardian");
|
||||
LunaSamplerConfig {
|
||||
api_key_cyber_access_programs: ApiKeyCyberAccessPrograms::from_config(input.config),
|
||||
inherit_parent_cyber_access_program,
|
||||
workspace_routing: input
|
||||
.thread_store
|
||||
.get_or_init(|| input.config.workspace_routing_context())
|
||||
.as_ref()
|
||||
.clone(),
|
||||
provider: auth.model_provider(input.config.model_provider.clone()),
|
||||
http_client_factory: input.config.http_client_factory(),
|
||||
agent_identity_policy: if input.config.features.enabled(Feature::UseAgentIdentity) {
|
||||
AgentIdentityAuthPolicy::ChatGptAuth
|
||||
} else {
|
||||
AgentIdentityAuthPolicy::JwtOnly
|
||||
},
|
||||
session_source: input.session_source.clone(),
|
||||
session_id: input.session_store.level_id().to_string(),
|
||||
thread_id: input.thread_store.level_id().to_string(),
|
||||
originator: input
|
||||
|
||||
@@ -3,81 +3,22 @@
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::McpToolInfo;
|
||||
use codex_extension_api::McpToolSource;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_context::TrustedTool;
|
||||
use codex_guardian_context::TrustedToolSource;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum PluginCapability {
|
||||
Connector,
|
||||
Mcp,
|
||||
}
|
||||
|
||||
pub(crate) async fn trusted_tool_context(
|
||||
tool: &McpToolInfo,
|
||||
source: &McpToolSource,
|
||||
manager: &ThreadManager,
|
||||
config: &Config,
|
||||
) -> Option<TrustedTool> {
|
||||
if source == &McpToolSource::Connector
|
||||
&& tool
|
||||
.connector_id
|
||||
.as_deref()
|
||||
.is_some_and(|connector_id| !connector_id.trim().is_empty())
|
||||
&& config
|
||||
.features
|
||||
.enabled(Feature::GuardianTrustOrchestratorConnectors)
|
||||
{
|
||||
return Some(TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
source: TrustedToolSource::PluginServiceOrchestrator,
|
||||
});
|
||||
}
|
||||
|
||||
let codex_home = config.codex_home.as_path().canonicalize().ok()?;
|
||||
let plugins = match source {
|
||||
McpToolSource::Connector => Some(
|
||||
manager
|
||||
.plugins_manager()
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await,
|
||||
),
|
||||
McpToolSource::Config | McpToolSource::Plugin { .. } => None,
|
||||
McpToolSource::SelectedPlugin | McpToolSource::Other => return None,
|
||||
};
|
||||
|
||||
let source = match source {
|
||||
McpToolSource::Connector => {
|
||||
let connector_id = tool.connector_id.as_deref()?;
|
||||
if let Some(plugin) = plugins.as_ref()?.plugins().iter().find(|plugin| {
|
||||
plugin.is_active()
|
||||
&& plugin
|
||||
.apps
|
||||
.iter()
|
||||
.any(|app| app.connector_id.0 == connector_id)
|
||||
&& is_home_owned_plugin_capability(
|
||||
plugin.root.as_path(),
|
||||
&codex_home,
|
||||
PluginCapability::Connector,
|
||||
)
|
||||
}) {
|
||||
plugin.root.as_path().display().to_string()
|
||||
} else {
|
||||
trusted_user_config_source(config, "apps", connector_id, &codex_home)?
|
||||
}
|
||||
}
|
||||
McpToolSource::Plugin { root, .. } => {
|
||||
let plugin_root = root.to_abs_path().ok()?;
|
||||
if !is_home_owned_plugin_capability(
|
||||
plugin_root.as_path(),
|
||||
&codex_home,
|
||||
PluginCapability::Mcp,
|
||||
) {
|
||||
if !is_home_owned_plugin_mcp(plugin_root.as_path(), &codex_home) {
|
||||
return None;
|
||||
}
|
||||
plugin_root.as_path().display().to_string()
|
||||
@@ -90,16 +31,12 @@ pub(crate) async fn trusted_tool_context(
|
||||
|
||||
Some(TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
connector_id: None,
|
||||
source: TrustedToolSource::UserConfiguration(source),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_home_owned_plugin_capability(
|
||||
plugin_root: &Path,
|
||||
codex_home: &Path,
|
||||
capability: PluginCapability,
|
||||
) -> bool {
|
||||
fn is_home_owned_plugin_mcp(plugin_root: &Path, codex_home: &Path) -> bool {
|
||||
if !is_home_owned_path(plugin_root, codex_home) {
|
||||
return false;
|
||||
}
|
||||
@@ -126,21 +63,12 @@ fn is_home_owned_plugin_capability(
|
||||
let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&manifest_contents) else {
|
||||
return false;
|
||||
};
|
||||
let declaration_path = match capability {
|
||||
PluginCapability::Connector => manifest
|
||||
.get("apps")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map_or_else(
|
||||
|| plugin_root.join(".app.json"),
|
||||
|path| plugin_root.join(path),
|
||||
),
|
||||
PluginCapability::Mcp => match manifest.get("mcpServers") {
|
||||
Some(serde_json::Value::Object(_)) => manifest_path,
|
||||
Some(serde_json::Value::String(path)) => plugin_root.join(path),
|
||||
Some(_) => return false,
|
||||
None if manifest_path == root_manifest => plugin_root.join("mcp.json"),
|
||||
None => plugin_root.join(".mcp.json"),
|
||||
},
|
||||
let declaration_path = match manifest.get("mcpServers") {
|
||||
Some(serde_json::Value::Object(_)) => manifest_path,
|
||||
Some(serde_json::Value::String(path)) => plugin_root.join(path),
|
||||
Some(_) => return false,
|
||||
None if manifest_path == root_manifest => plugin_root.join("mcp.json"),
|
||||
None => plugin_root.join(".mcp.json"),
|
||||
};
|
||||
|
||||
is_home_owned_path(&declaration_path, codex_home)
|
||||
|
||||
@@ -3,7 +3,6 @@ use std::path::Path;
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::McpToolInfo;
|
||||
use codex_extension_api::McpToolSource;
|
||||
use codex_features::Feature;
|
||||
use codex_guardian_context::TrustedTool;
|
||||
use codex_guardian_context::TrustedToolSource;
|
||||
use codex_login::CodexAuth;
|
||||
@@ -13,15 +12,13 @@ use core_test_support::test_codex::test_codex;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[cfg(unix)]
|
||||
use super::PluginCapability;
|
||||
#[cfg(unix)]
|
||||
use super::is_home_owned_path;
|
||||
#[cfg(unix)]
|
||||
use super::is_home_owned_plugin_capability;
|
||||
use super::is_home_owned_plugin_mcp;
|
||||
use super::trusted_tool_context;
|
||||
|
||||
fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
fn mcp_tool(server: &str) -> Result<McpToolInfo> {
|
||||
Ok(serde_json::from_value(json!({
|
||||
"server_name": server,
|
||||
"tool_name": "inspect",
|
||||
@@ -32,8 +29,6 @@ fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
"description": "Remote tool instructions",
|
||||
"inputSchema": {"type": "object", "properties": {}}
|
||||
},
|
||||
"connector_id": connector_id,
|
||||
"connector_name": connector_id.map(|_| "Remote connector"),
|
||||
"plugin_display_names": []
|
||||
}))?)
|
||||
}
|
||||
@@ -41,7 +36,7 @@ fn mcp_tool(server: &str, connector_id: Option<&str>) -> Result<McpToolInfo> {
|
||||
fn expected_context(tool: &McpToolInfo, source: &Path) -> TrustedTool {
|
||||
TrustedTool {
|
||||
server: tool.server_name.clone(),
|
||||
connector_id: tool.connector_id.clone(),
|
||||
connector_id: None,
|
||||
source: TrustedToolSource::UserConfiguration(source.display().to_string()),
|
||||
}
|
||||
}
|
||||
@@ -55,25 +50,18 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
.with_pre_build_hook(|home| {
|
||||
std::fs::write(
|
||||
home.join("config.toml"),
|
||||
"[mcp_servers.home_server]\nurl = \"http://127.0.0.1:9/mcp\"\n\n[apps.connector_home]\nenabled = true\n",
|
||||
"[mcp_servers.home_server]\nurl = \"http://127.0.0.1:9/mcp\"\n",
|
||||
)
|
||||
.expect("write user MCP and connector config");
|
||||
.expect("write user MCP config");
|
||||
})
|
||||
.build_with_auto_env(&server)
|
||||
.await?;
|
||||
for (tool, unrelated, source) in [
|
||||
(
|
||||
mcp_tool("home_server", /*connector_id*/ None)?,
|
||||
mcp_tool("other_server", /*connector_id*/ None)?,
|
||||
McpToolSource::Config,
|
||||
),
|
||||
(
|
||||
mcp_tool("codex_apps", Some("connector_home"))?,
|
||||
mcp_tool("codex_apps", Some("connector_other"))?,
|
||||
McpToolSource::Connector,
|
||||
),
|
||||
] {
|
||||
let context = trusted_tool_context(&tool, &source, &test.thread_manager, &test.config)
|
||||
for (tool, unrelated, source) in [(
|
||||
mcp_tool("home_server")?,
|
||||
mcp_tool("other_server")?,
|
||||
McpToolSource::Config,
|
||||
)] {
|
||||
let context = trusted_tool_context(&tool, &source, &test.config)
|
||||
.await
|
||||
.expect("home-configured tool should be trusted");
|
||||
assert_eq!(
|
||||
@@ -81,7 +69,7 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
expected_context(&tool, &test.home.path().join("config.toml")),
|
||||
);
|
||||
assert_eq!(
|
||||
trusted_tool_context(&unrelated, &source, &test.thread_manager, &test.config).await,
|
||||
trusted_tool_context(&unrelated, &source, &test.config).await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
@@ -90,39 +78,12 @@ async fn trusts_only_tools_configured_in_codex_home() -> Result<()> {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn rejects_blank_orchestrator_connector_ids() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let test = test_codex().build_with_auto_env(&server).await?;
|
||||
let mut config = test.config.clone();
|
||||
config
|
||||
.features
|
||||
.enable(Feature::GuardianTrustOrchestratorConnectors)?;
|
||||
for connector_id in [Some(""), Some(" \t\n "), None] {
|
||||
let tool = mcp_tool("codex_apps", connector_id)?;
|
||||
assert_eq!(
|
||||
trusted_tool_context(
|
||||
&tool,
|
||||
&McpToolSource::Connector,
|
||||
&test.thread_manager,
|
||||
&config,
|
||||
)
|
||||
.await,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
async fn trusts_mcp_server_declared_by_home_owned_plugin() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = responses::start_mock_server().await;
|
||||
let test = test_codex()
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.with_pre_build_hook(|home| {
|
||||
let plugin_root = home.join("plugins/cache/test/trusted/local");
|
||||
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))
|
||||
@@ -132,11 +93,6 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
r#"{"name":"trusted","description":"Trusted plugin instructions"}"#,
|
||||
)
|
||||
.expect("write plugin manifest");
|
||||
std::fs::write(
|
||||
plugin_root.join(".app.json"),
|
||||
r#"{"apps":{"calendar":{"id":"connector_calendar"}}}"#,
|
||||
)
|
||||
.expect("write plugin connector declaration");
|
||||
std::fs::write(
|
||||
plugin_root.join(".mcp.json"),
|
||||
r#"{"mcpServers":{"trusted_server":{"url":"http://127.0.0.1:9/mcp"}}}"#,
|
||||
@@ -158,18 +114,7 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
.join("test")
|
||||
.join("trusted")
|
||||
.join("local");
|
||||
let tool = mcp_tool("codex_apps", Some("connector_calendar"))?;
|
||||
let context = trusted_tool_context(
|
||||
&tool,
|
||||
&McpToolSource::Connector,
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await
|
||||
.expect("home-owned plugin connector should be trusted");
|
||||
assert_eq!(context, expected_context(&tool, &plugin_root));
|
||||
|
||||
let mcp = mcp_tool("trusted_server", /*connector_id*/ None)?;
|
||||
let mcp = mcp_tool("trusted_server")?;
|
||||
let mcp_context = trusted_tool_context(
|
||||
&mcp,
|
||||
&McpToolSource::Plugin {
|
||||
@@ -180,7 +125,6 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
.join("plugins/cache/test/trusted/local")
|
||||
.into(),
|
||||
},
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await
|
||||
@@ -194,20 +138,13 @@ async fn trusts_connector_declared_by_home_owned_plugin() -> Result<()> {
|
||||
id: "trusted@test".to_string(),
|
||||
root: test.config.cwd.clone().into(),
|
||||
},
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await,
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
trusted_tool_context(
|
||||
&mcp,
|
||||
&McpToolSource::SelectedPlugin,
|
||||
&test.thread_manager,
|
||||
&test.config,
|
||||
)
|
||||
.await,
|
||||
trusted_tool_context(&mcp, &McpToolSource::SelectedPlugin, &test.config,).await,
|
||||
None,
|
||||
);
|
||||
|
||||
@@ -233,23 +170,11 @@ async fn rejects_paths_that_escape_codex_home_through_symlinks() -> Result<()> {
|
||||
plugin_root.join(".codex-plugin").join("plugin.json"),
|
||||
r#"{"name":"trusted"}"#,
|
||||
)?;
|
||||
let outside_apps = test.cwd.path().join("outside-app.json");
|
||||
let outside_mcp = test.cwd.path().join("outside-mcp.json");
|
||||
std::fs::write(&outside_apps, r#"{"apps":{}}"#)?;
|
||||
std::fs::write(&outside_mcp, r#"{"mcpServers":{}}"#)?;
|
||||
std::os::unix::fs::symlink(&outside_apps, plugin_root.join(".app.json"))?;
|
||||
std::os::unix::fs::symlink(&outside_mcp, plugin_root.join(".mcp.json"))?;
|
||||
|
||||
assert!(!is_home_owned_plugin_capability(
|
||||
&plugin_root,
|
||||
&canonical_home,
|
||||
PluginCapability::Connector,
|
||||
));
|
||||
assert!(!is_home_owned_plugin_capability(
|
||||
&plugin_root,
|
||||
&canonical_home,
|
||||
PluginCapability::Mcp,
|
||||
));
|
||||
assert!(!is_home_owned_plugin_mcp(&plugin_root, &canonical_home));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
//! Exposes a narrow history capability backed by the parent's live MCP runtime.
|
||||
//! Guardian owns tool exposure and output limits, never a second Apps connection.
|
||||
|
||||
use std::num::NonZeroUsize;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_core::CodexThread;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ToolCall;
|
||||
use codex_extension_api::ToolContributor;
|
||||
use codex_extension_api::ToolExecutor;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
|
||||
pub(super) struct ConversationHistoryTools {
|
||||
pub parent: Weak<CodexThread>,
|
||||
}
|
||||
|
||||
struct HistoryTools(Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>);
|
||||
|
||||
impl TurnLifecycleContributor for ConversationHistoryTools {
|
||||
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let tools = match self.parent.upgrade() {
|
||||
Some(parent) => {
|
||||
let max_output_tokens = parent
|
||||
.config()
|
||||
.await
|
||||
.guardian_conversation_history_max_output_tokens
|
||||
.map_or(/*default*/ 4_000, NonZeroUsize::get);
|
||||
codex_core::guardian_review::conversation_history_tools(
|
||||
&parent,
|
||||
max_output_tokens,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
}
|
||||
None => Vec::new(),
|
||||
};
|
||||
input.thread_store.insert(HistoryTools(tools));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for ConversationHistoryTools {
|
||||
fn tools(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
) -> Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>> {
|
||||
thread_store
|
||||
.get::<HistoryTools>()
|
||||
.map(|tools| tools.0.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
use super::*;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
@@ -19,14 +18,14 @@ use core_test_support::wait_for_event_match;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
|
||||
struct StaleDenials(ModelInfo);
|
||||
struct StaleDenials;
|
||||
|
||||
impl TurnLifecycleContributor for StaleDenials {
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let denials = ReviewDenials::for_thread(input.thread_store);
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(input.turn_id, &self.0).await, None);
|
||||
assert_eq!(denials.record_denial(input.turn_id).await, None);
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -34,12 +33,9 @@ impl TurnLifecycleContributor for StaleDenials {
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let config = core_test_support::load_default_config_for_test(&home).await;
|
||||
let model = codex_core::test_support::construct_model_info_offline("gpt-5", &config);
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
|
||||
// Seed stale state before the production Guardian contributor runs its start hook.
|
||||
extensions.turn_lifecycle_contributor(Arc::new(StaleDenials(model.clone())));
|
||||
extensions.turn_lifecycle_contributor(Arc::new(StaleDenials));
|
||||
let mut releases = Vec::new();
|
||||
let streams = (0..3)
|
||||
.map(|_| {
|
||||
@@ -86,7 +82,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
.await;
|
||||
// An interruption event can precede its cleanup. The next turn starts after it.
|
||||
if let Some(previous) = previous_turn.replace(turn_id.clone()) {
|
||||
assert_eq!(denials.record_denial(&previous, &model).await, None);
|
||||
assert_eq!(denials.record_denial(&previous).await, None);
|
||||
}
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
@@ -95,7 +91,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
.await?;
|
||||
// Without start cleanup, these denials reach the three-denial limit.
|
||||
for _ in 0..2 {
|
||||
assert_eq!(denials.record_denial(&turn_id, &model).await, None);
|
||||
assert_eq!(denials.record_denial(&turn_id).await, None);
|
||||
}
|
||||
if index == 1 {
|
||||
test.codex.submit(Op::Interrupt).await?;
|
||||
@@ -116,10 +112,7 @@ async fn terminal_turn_clears_extension_owned_denials() -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
assert_eq!(
|
||||
denials.record_denial(&previous_turn.unwrap(), &model).await,
|
||||
None
|
||||
);
|
||||
assert_eq!(denials.record_denial(&previous_turn.unwrap()).await, None);
|
||||
streaming.shutdown().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_core::CodexResponsesHeaders;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::Constrained;
|
||||
@@ -34,7 +33,6 @@ use codex_protocol::protocol::InternalSessionSource;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
|
||||
mod conversation_history;
|
||||
mod reviewer_config;
|
||||
|
||||
/// Owns reviewer agents through the same thread manager as the parent conversation.
|
||||
@@ -58,7 +56,6 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
reviewer_config::build_reviewer_config,
|
||||
));
|
||||
let manager = self.thread_manager.clone();
|
||||
let parent_thread_id = input.thread_store.level_id().to_owned();
|
||||
let runtime = input.thread_store.get_or_init(ReviewerTasks::default);
|
||||
input.thread_store.get_or_init(ReviewBlocking::default);
|
||||
input.thread_store.get_or_init(|| {
|
||||
@@ -66,7 +63,6 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
Arc::clone(&runtime),
|
||||
move |context, key, kind, snapshot, cancel| {
|
||||
let manager = manager.clone();
|
||||
let parent_thread_id = parent_thread_id.clone();
|
||||
let runtime = Arc::clone(&runtime);
|
||||
Box::pin(async move {
|
||||
let history_reset = context.history_reset.clone();
|
||||
@@ -92,52 +88,10 @@ impl ThreadLifecycleContributor<Config> for GuardianExtension {
|
||||
options.session_source =
|
||||
Some(SessionSource::Internal(InternalSessionSource::Guardian));
|
||||
options.thread_source = Some(ThreadSource::GuardianReview);
|
||||
// This is the backend reviewer model, independent of current login.
|
||||
// Core checks the selected model and auth on each request attempt.
|
||||
let provider = codex_model_provider::create_model_provider(
|
||||
options.config.model_provider.clone(),
|
||||
/*auth_manager*/ None,
|
||||
);
|
||||
options.thread_extension_init.insert(CodexResponsesHeaders {
|
||||
model: provider.approval_review_preferred_model().to_owned(),
|
||||
headers: http::HeaderMap::from_iter([(
|
||||
http::HeaderName::from_static("x-codex-guardian"),
|
||||
http::HeaderValue::from_static("reviewer"),
|
||||
)]),
|
||||
});
|
||||
options
|
||||
.thread_extension_init
|
||||
.insert(SessionIsolation::Isolated);
|
||||
let mut tool_policy = codex_guardian_reviewer::reviewer_tool_policy();
|
||||
if options
|
||||
.config
|
||||
.features
|
||||
.enabled(codex_features::Feature::GuardianConversationHistoryTools)
|
||||
{
|
||||
let parent = manager
|
||||
.get_thread(ThreadId::from_string(&parent_thread_id)?)
|
||||
.await?;
|
||||
let mut extensions = ExtensionRegistryBuilder::<Config>::default();
|
||||
let history_tools =
|
||||
Arc::new(conversation_history::ConversationHistoryTools {
|
||||
parent: Arc::downgrade(&parent),
|
||||
});
|
||||
extensions.tool_contributor(history_tools.clone());
|
||||
extensions.turn_lifecycle_contributor(history_tools);
|
||||
options.thread_extension_init.insert(
|
||||
codex_extension_api::IsolatedSessionExtensions(Arc::new(
|
||||
extensions.build(),
|
||||
)),
|
||||
);
|
||||
tool_policy.allowed_tools.get_or_insert_default().extend(
|
||||
["search_messages", "read_messages"].map(|name| {
|
||||
codex_extension_api::ToolName::namespaced(
|
||||
"user_message",
|
||||
name,
|
||||
)
|
||||
}),
|
||||
);
|
||||
}
|
||||
let tool_policy = codex_guardian_reviewer::reviewer_tool_policy();
|
||||
options.thread_extension_init.insert(tool_policy);
|
||||
let session_cancel = cancel.clone();
|
||||
let until = async move {
|
||||
|
||||
@@ -36,9 +36,6 @@ pub(crate) fn build_reviewer_config(parent_config: &Config) -> anyhow::Result<Co
|
||||
config.mcp_servers.set(HashMap::new()).map_err(|err| {
|
||||
anyhow::anyhow!("guardian review session could not clear MCP servers: {err}")
|
||||
})?;
|
||||
let conversation_history_tools = config
|
||||
.features
|
||||
.enabled(Feature::GuardianConversationHistoryTools);
|
||||
for feature in [
|
||||
Feature::Collab,
|
||||
Feature::MultiAgentV2,
|
||||
@@ -51,9 +48,6 @@ pub(crate) fn build_reviewer_config(parent_config: &Config) -> anyhow::Result<Co
|
||||
Feature::WebSearchRequest,
|
||||
Feature::WebSearchCached,
|
||||
] {
|
||||
if feature == Feature::Apps && conversation_history_tools {
|
||||
continue;
|
||||
}
|
||||
config.features.disable(feature).map_err(|err| {
|
||||
anyhow::anyhow!(
|
||||
"guardian review session could not disable `features.{}`: {err}",
|
||||
|
||||
Reference in New Issue
Block a user