aKode fase 2a: rimossi cloud tasks, chatgpt apply, responses-api-proxy, codex app, remote control, guardian decisions; realtime senza fallback OpenAI; doctor senza sonde OpenAI
This commit is contained in:
@@ -35,11 +35,7 @@ async fn catalog_budget_fixture(base_url: String, window: i64) -> Result<Guardia
|
||||
})
|
||||
.build_with_auto_env(&server).await?;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::super::install(
|
||||
&mut builder,
|
||||
test.thread_manager.auth_manager(),
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
test.codex
|
||||
|
||||
@@ -58,7 +58,6 @@ use super::trusted_tools::trusted_tool_context;
|
||||
pub(super) struct Classification {
|
||||
pub(super) reservation: Reservation,
|
||||
pub(super) classification_started_at: Instant,
|
||||
pub(super) decisions_sampler: Option<Arc<super::decisions::DecisionsSampler>>,
|
||||
pub(super) guardian_config: GuardianV2Config,
|
||||
pub(super) score_progress: Arc<GuardianV2ScoreProgress>,
|
||||
pub(super) parent_model: Option<Arc<ModelInfo>>,
|
||||
@@ -113,7 +112,6 @@ impl Classification {
|
||||
let Self {
|
||||
reservation,
|
||||
classification_started_at,
|
||||
decisions_sampler,
|
||||
guardian_config,
|
||||
score_progress,
|
||||
parent_model,
|
||||
@@ -278,11 +276,6 @@ impl Classification {
|
||||
};
|
||||
drop(history);
|
||||
drop(node_repl_images);
|
||||
let decisions_comparison_enabled = config
|
||||
.features
|
||||
.enabled(codex_features::Feature::GuardianV2DecisionsComparison);
|
||||
let mut decisions_task = None;
|
||||
let mut responses_duration = None;
|
||||
let mut failure_reason = "invalid_output";
|
||||
let mut classification_risk = None;
|
||||
let mut classification_finished_at = None;
|
||||
@@ -326,20 +319,7 @@ impl Classification {
|
||||
pending_score: pending_score.clone(),
|
||||
sampled_at,
|
||||
};
|
||||
let mut sampling_started = None;
|
||||
if let Some(prepared) = reservation.prepare(request).await {
|
||||
if let Some(decisions_sampler) = decisions_sampler.as_ref() {
|
||||
decisions_task = Some(
|
||||
decisions_sampler.start_conversation_comparison(&prepared.request.input),
|
||||
);
|
||||
} else if decisions_comparison_enabled {
|
||||
super::metrics::record_decisions_comparison_outcome(
|
||||
metrics.as_deref(),
|
||||
"skipped",
|
||||
"not_initialized",
|
||||
);
|
||||
}
|
||||
sampling_started = Some(Instant::now());
|
||||
tokio::spawn(prepared.run());
|
||||
}
|
||||
let result = tokio::select! {
|
||||
@@ -347,20 +327,6 @@ impl Classification {
|
||||
() = pending_score.expired() => Err(LunaSamplerError::Superseded),
|
||||
result = score => result.unwrap_or(Err(LunaSamplerError::Superseded)).map(super::sampler::SampledScore::accept),
|
||||
};
|
||||
// Stop at the usable score, before draining and committing history.
|
||||
responses_duration = sampling_started.map(|started| started.elapsed());
|
||||
if sampling_started.is_none() && decisions_comparison_enabled {
|
||||
super::metrics::record_decisions_comparison_outcome(
|
||||
metrics.as_deref(),
|
||||
"skipped",
|
||||
if matches!(result, Err(LunaSamplerError::Superseded)) {
|
||||
"superseded"
|
||||
} else {
|
||||
"preparation_failed"
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let output = match result {
|
||||
Ok(output) => output,
|
||||
Err(LunaSamplerError::Superseded) => {
|
||||
@@ -462,22 +428,6 @@ impl Classification {
|
||||
if matches!(result, Ok(ClassificationOutcome::Scored)) {
|
||||
truncations.emit(metrics.as_deref());
|
||||
}
|
||||
if matches!(result, Ok(ClassificationOutcome::Superseded))
|
||||
&& let Some(task) = decisions_task.take()
|
||||
{
|
||||
drop(task);
|
||||
super::metrics::record_decisions_comparison_outcome(
|
||||
metrics.as_deref(),
|
||||
"skipped",
|
||||
"superseded",
|
||||
);
|
||||
}
|
||||
// Only compare against a score accepted by the authoritative publication path.
|
||||
let baseline_risk = if matches!(result, Ok(ClassificationOutcome::Scored)) {
|
||||
classification_risk
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Err(error) = result {
|
||||
event_sink.emit_warning(ExtensionWarning {
|
||||
thread_id,
|
||||
@@ -485,25 +435,5 @@ impl Classification {
|
||||
message: format!("Guardian V2 risk scoring failed: {error}"),
|
||||
});
|
||||
}
|
||||
if let Some(decisions_task) = decisions_task {
|
||||
super::metrics::record_decisions_comparison(
|
||||
decisions_task.finish().await,
|
||||
baseline_risk.zip(responses_duration),
|
||||
metrics.as_deref(),
|
||||
);
|
||||
} else if decisions_comparison_enabled
|
||||
&& let Some(risk) = baseline_risk
|
||||
&& let Some(metrics) = metrics.as_deref()
|
||||
{
|
||||
metrics.counter(
|
||||
"codex.guardian_v2.decisions_comparison.comparison",
|
||||
/*inc*/ 1,
|
||||
&[
|
||||
("comparison", "unavailable"),
|
||||
("responses", risk),
|
||||
("decisions", "unavailable"),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ use super::*;
|
||||
use crate::async_scorer::authorization::ScoreAuthorization;
|
||||
use crate::async_scorer::conversation::ConversationBackend;
|
||||
use crate::async_scorer::conversation::ConversationRequest;
|
||||
use crate::async_scorer::decisions::DecisionsCredential;
|
||||
use crate::async_scorer::sampler::LunaSampler;
|
||||
use crate::async_scorer::sampler::LunaSamplerError;
|
||||
use crate::async_scorer::sampler::LunaSamplingRequest;
|
||||
@@ -80,15 +79,11 @@ async fn pending_request(
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidence() -> Result<()> {
|
||||
use crate::async_scorer::decisions::DecisionsSampler;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
|
||||
skip_if_no_network!(Ok(()));
|
||||
for (limit, reused) in [(1, false), (100_000, true)] {
|
||||
let server = responses::start_mock_server().await;
|
||||
let fixture = GuardianFailureFixture::with_config(&format!(
|
||||
"[features]\nguardianv2_decisions_comparison = true\n[features.guardianv2]\nasync_classifier_mode = 'conversation'\nasync_classifier_conversation_token_limit = {limit}"
|
||||
"[features.guardianv2]\nasync_classifier_mode = 'conversation'\nasync_classifier_conversation_token_limit = {limit}"
|
||||
))
|
||||
.await?;
|
||||
let store = fixture.test.codex.thread_extension_data();
|
||||
@@ -104,21 +99,6 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
|
||||
ev_completed("score"),
|
||||
]);
|
||||
let mock = responses::mount_sse_sequence(&server, vec![events; 2]).await;
|
||||
let (finish_decisions, decisions_gate) = tokio::sync::oneshot::channel();
|
||||
let (decisions_server, _) = start_streaming_sse_server(vec![vec![StreamingSseChunk {
|
||||
gate: Some(decisions_gate),
|
||||
body: json!({
|
||||
"answers":[{"type":"choice", "name":"guardian_risk", "choice":"high"}]
|
||||
})
|
||||
.to_string(),
|
||||
}]])
|
||||
.await;
|
||||
store.insert(DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
DecisionsCredential::ApiKey("synthetic-key".into()),
|
||||
format!("{}/v1/responses", decisions_server.uri()),
|
||||
/*auth_context*/ None,
|
||||
)?);
|
||||
let (mut request, score) = pending_request(&fixture, "parent").await?;
|
||||
request.metrics = Some(metrics.clone());
|
||||
let reservation = backend.reserve(|| 0).1.unwrap();
|
||||
@@ -143,31 +123,6 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
|
||||
published.scores,
|
||||
BTreeMap::from([("action_risk".into(), 0.0)])
|
||||
);
|
||||
tokio::time::timeout(
|
||||
ASYNC_TEST_TIMEOUT,
|
||||
decisions_server.wait_for_request_count(/*count*/ 1),
|
||||
)
|
||||
.await?;
|
||||
finish_decisions.send(()).unwrap();
|
||||
tokio::time::timeout(ASYNC_TEST_TIMEOUT, async {
|
||||
loop {
|
||||
if metrics.0.lock().unwrap().iter().any(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison.comparison")) {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
// Success rules out a timeout before Guardian published.
|
||||
assert!(metrics.0.lock().unwrap().contains(&RecordedMetric::Counter(
|
||||
"codex.guardian_v2.decisions_comparison".into(),
|
||||
1,
|
||||
vec![
|
||||
("outcome".into(), "success".into()),
|
||||
("reason".into(), "none".into()),
|
||||
],
|
||||
)));
|
||||
let requests = mock.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let expected_buckets = requests
|
||||
@@ -212,17 +167,8 @@ async fn configured_reset_limit_rebuilds_history_without_rejecting_fresh_evidenc
|
||||
serde_json::to_string(&input)?.contains("TRANSCRIPT DELTA START"),
|
||||
reused
|
||||
);
|
||||
let evidence = input[2..]
|
||||
.iter()
|
||||
.map(|item| json!({"role":item["role"], "content":item["content"]}))
|
||||
.collect::<Vec<_>>();
|
||||
let decisions_requests = decisions_server.requests().await;
|
||||
assert_eq!(decisions_requests.len(), 1);
|
||||
let body: serde_json::Value = serde_json::from_slice(&decisions_requests[0])?;
|
||||
assert_eq!(body["input"], json!(evidence));
|
||||
drop(backend);
|
||||
fixture.test.codex.shutdown_and_wait().await?;
|
||||
decisions_server.shutdown().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,423 +0,0 @@
|
||||
//! Bounded Decisions transport for the optional Guardian comparison classifier.
|
||||
//! Admission retains the newest requests and cancels the oldest unfinished request at capacity.
|
||||
//! Comparisons omit reasoning and compaction.
|
||||
//! Other unsupported evidence is rejected intact.
|
||||
//! Errors never contain credentials or wire bodies.
|
||||
//! Queued comparisons retain their credential source; runtime-bound threads pin it at startup.
|
||||
//! Evidence preserves message roles, content order, and boundaries.
|
||||
//! The caller records measurements after baseline publication; dropping its task aborts Decisions work.
|
||||
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ResolvedProviderAuth;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::ResponseItem;
|
||||
use codex_runtime_agent_instance::RuntimeAuthBinding;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::Weak;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Semaphore;
|
||||
use tokio::task::AbortHandle;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
const MAX_CONCURRENT_REQUESTS: usize = 16;
|
||||
pub(super) const URL: &str = "https://api.openai.com/v1/decisions";
|
||||
const MODEL: &str = "gpt-6-luna";
|
||||
// Provisional local rollout budgets, not Decisions API limits or model context limits.
|
||||
// Guardian owns the text/context budget; bound HTTP lifetime, image bytes and response buffering here.
|
||||
// Oversized images skip the complete request; transport failures never affect approvals.
|
||||
const DEADLINE: Duration = Duration::from_secs(6);
|
||||
const MAX_IMAGE_BYTES: usize = 8 * 1024 * 1024;
|
||||
const MAX_RESPONSE_BYTES: usize = 16 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Error, PartialEq)]
|
||||
pub(super) enum DecisionsError {
|
||||
#[error("Decisions credentials are missing or empty")]
|
||||
Credentials,
|
||||
#[error("Decisions HTTP client setup failed")]
|
||||
ClientSetup,
|
||||
#[error("Decisions received unexpected classifier request setup")]
|
||||
UnexpectedRequestSetup,
|
||||
#[error("Decisions cannot represent this input item")]
|
||||
UnsupportedInputItem,
|
||||
#[error("Decisions cannot represent this image evidence")]
|
||||
UnsupportedImage,
|
||||
#[error("Decisions cannot represent audio evidence")]
|
||||
UnsupportedAudio,
|
||||
#[error("Decisions input exceeds the request limit")]
|
||||
InputTooLarge,
|
||||
#[error("Decisions request timed out")]
|
||||
Timeout,
|
||||
#[error("Decisions transport failed")]
|
||||
Transport,
|
||||
#[error("Decisions returned HTTP {0}")]
|
||||
Http(u16),
|
||||
#[error("Decisions response exceeds the response limit")]
|
||||
ResponseTooLarge,
|
||||
#[error("Decisions returned an invalid classification")]
|
||||
InvalidResponse,
|
||||
}
|
||||
|
||||
pub(super) enum DecisionsCredential {
|
||||
ApiKey(String),
|
||||
SavedLogin(Arc<AuthManager>),
|
||||
RuntimeLogin(Arc<AuthManager>, u64),
|
||||
}
|
||||
|
||||
impl From<&str> for DecisionsCredential {
|
||||
fn from(key: &str) -> Self {
|
||||
Self::ApiKey(key.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl DecisionsCredential {
|
||||
fn source_generation(&self) -> Option<u64> {
|
||||
match self {
|
||||
Self::ApiKey(_) => None,
|
||||
Self::RuntimeLogin(_, source) => Some(*source),
|
||||
Self::SavedLogin(manager) => {
|
||||
let changes = manager.auth_change_state_receiver();
|
||||
Some(changes.borrow().source_generation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve(&self, source_generation: Option<u64>) -> Option<CodexAuth> {
|
||||
match self {
|
||||
Self::ApiKey(key) => Some(CodexAuth::from_api_key(key)),
|
||||
Self::SavedLogin(manager) | Self::RuntimeLogin(manager, _) => {
|
||||
let auth = manager.auth_cached()?;
|
||||
let source = manager.auth_change_state_for(&auth)?.source_generation;
|
||||
let key = auth.api_key()?;
|
||||
(Some(source) == source_generation
|
||||
&& super::startup::valid_implicit_decisions_key(key))
|
||||
.then_some(auth)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct DecisionsSampler {
|
||||
client: RouteAwareClientPool,
|
||||
// No Debug implementation: credentials must not reach diagnostics.
|
||||
credential: DecisionsCredential,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthBinding>, RuntimeAuthMode)>,
|
||||
url: String,
|
||||
slots: Semaphore,
|
||||
active_requests: Mutex<VecDeque<AbortHandle>>,
|
||||
}
|
||||
|
||||
/// Owns the measurement until it is recorded after baseline publication.
|
||||
/// Dropping the classification, including during the join, aborts unfinished work.
|
||||
pub(super) struct DecisionsTask {
|
||||
handle: JoinHandle<(Result<&'static str, DecisionsError>, Duration)>,
|
||||
sampler: Weak<DecisionsSampler>,
|
||||
}
|
||||
|
||||
impl Drop for DecisionsTask {
|
||||
fn drop(&mut self) {
|
||||
self.handle.abort();
|
||||
if let Some(sampler) = self.sampler.upgrade() {
|
||||
sampler
|
||||
.active_requests
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.retain(|task| task.id() != self.handle.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DecisionsTask {
|
||||
pub(super) async fn finish(
|
||||
mut self,
|
||||
) -> Result<(Result<&'static str, DecisionsError>, Duration), tokio::task::JoinError> {
|
||||
(&mut self.handle).await
|
||||
}
|
||||
}
|
||||
|
||||
impl DecisionsSampler {
|
||||
pub(super) fn new(
|
||||
factory: HttpClientFactory,
|
||||
credential: DecisionsCredential,
|
||||
url: String,
|
||||
auth_context: Option<&codex_model_provider::ProviderAuthContext>,
|
||||
) -> Result<Self, DecisionsError> {
|
||||
if matches!(&credential, DecisionsCredential::ApiKey(key) if key.trim().is_empty()) {
|
||||
return Err(DecisionsError::Credentials);
|
||||
}
|
||||
let runtime_auth = if let Some(context) = auth_context
|
||||
&& codex_runtime_agent_instance::is_openai_api_url(&url)
|
||||
&& let Some((runtime, mode)) = context.runtime_auth.as_ref()
|
||||
{
|
||||
codex_model_provider::validate_runtime_environment(runtime, Some(&url))
|
||||
.map_err(|_| DecisionsError::ClientSetup)?;
|
||||
let binding = match &credential {
|
||||
DecisionsCredential::ApiKey(key) => {
|
||||
runtime.bind_api_key(key, &context.credentials.runtime_config())
|
||||
}
|
||||
DecisionsCredential::SavedLogin(manager)
|
||||
| DecisionsCredential::RuntimeLogin(manager, _) => {
|
||||
runtime.bind(Arc::clone(manager))
|
||||
}
|
||||
};
|
||||
Some((binding, *mode))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let factory = if runtime_auth.is_some() {
|
||||
factory.with_sensitive_header_protection()
|
||||
} else {
|
||||
factory
|
||||
};
|
||||
let client =
|
||||
RouteAwareClientPool::new_without_request_logging(factory, ClientRouteClass::Api);
|
||||
Ok(Self {
|
||||
client,
|
||||
credential,
|
||||
runtime_auth,
|
||||
url,
|
||||
// Keep HTTP concurrency bounded while evicted tasks release their permits.
|
||||
slots: Semaphore::new(MAX_CONCURRENT_REQUESTS),
|
||||
active_requests: Mutex::new(VecDeque::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn start_conversation_comparison(
|
||||
self: &Arc<Self>,
|
||||
input: &[ResponseItemEnvelope],
|
||||
) -> DecisionsTask {
|
||||
let started = Instant::now();
|
||||
let source_generation = self.credential.source_generation();
|
||||
let body = (|| {
|
||||
let [tools, instructions, evidence @ ..] = input else {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
};
|
||||
if !matches!(
|
||||
&tools.item,
|
||||
ResponseItem::AdditionalTools { role, tools, .. }
|
||||
if role == "developer" && tools.is_empty()
|
||||
) {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
}
|
||||
let ResponseItem::Message { role, content, .. } = &instructions.item else {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
};
|
||||
let [rubric] = content.as_slice() else {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
};
|
||||
if role != "developer" {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
}
|
||||
request_body(rubric, evidence.iter().map(|item| &item.item))
|
||||
})();
|
||||
self.spawn_request(body, started, source_generation)
|
||||
}
|
||||
|
||||
fn spawn_request(
|
||||
self: &Arc<Self>,
|
||||
body: Result<Value, DecisionsError>,
|
||||
started: Instant,
|
||||
source_generation: Option<u64>,
|
||||
) -> DecisionsTask {
|
||||
let body = match body {
|
||||
Ok(body) => body,
|
||||
Err(error) => {
|
||||
return DecisionsTask {
|
||||
handle: tokio::spawn(async move { (Err(error), started.elapsed()) }),
|
||||
sampler: Weak::new(),
|
||||
};
|
||||
}
|
||||
};
|
||||
let mut active = self
|
||||
.active_requests
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
active.retain(|task| !task.is_finished());
|
||||
if active.len() == MAX_CONCURRENT_REQUESTS
|
||||
&& let Some(oldest) = active.pop_front()
|
||||
{
|
||||
oldest.abort();
|
||||
}
|
||||
let sampler = Arc::clone(self);
|
||||
let handle = tokio::spawn(async move {
|
||||
let Ok(_permit) = sampler.slots.acquire().await else {
|
||||
return (Err(DecisionsError::Transport), started.elapsed());
|
||||
};
|
||||
let result = tokio::time::timeout(DEADLINE, sampler.request(body, source_generation))
|
||||
.await
|
||||
.unwrap_or(Err(DecisionsError::Timeout));
|
||||
(result, started.elapsed())
|
||||
});
|
||||
active.push_back(handle.abort_handle());
|
||||
DecisionsTask {
|
||||
handle,
|
||||
sampler: Arc::downgrade(self),
|
||||
}
|
||||
}
|
||||
|
||||
async fn request(
|
||||
&self,
|
||||
body: Value,
|
||||
source_generation: Option<u64>,
|
||||
) -> Result<&'static str, DecisionsError> {
|
||||
let auth = self
|
||||
.credential
|
||||
.resolve(source_generation)
|
||||
.ok_or(DecisionsError::Credentials)?;
|
||||
let headers = http::HeaderMap::new();
|
||||
let resolved = match &self.runtime_auth {
|
||||
Some((binding, mode)) => {
|
||||
let selected =
|
||||
codex_model_provider::select_runtime_auth_for(binding, &auth, &headers)
|
||||
.await
|
||||
.map_err(|_| DecisionsError::Credentials)?;
|
||||
ResolvedProviderAuth {
|
||||
credential: Some(selected.auth().clone()),
|
||||
auth: selected.clone().into_auth_provider(*mode),
|
||||
agent_identity_telemetry: None,
|
||||
runtime: Some(selected),
|
||||
}
|
||||
}
|
||||
None => codex_model_provider::auth_provider_for_request(
|
||||
&auth, /*runtime*/ None, &headers,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| DecisionsError::Credentials)?,
|
||||
};
|
||||
let client = resolved
|
||||
.bind_http_client_pool(&self.client)
|
||||
.map_err(|_| DecisionsError::ClientSetup)?;
|
||||
let headers = resolved
|
||||
.auth
|
||||
.apply_auth_headers(http::HeaderMap::new())
|
||||
.await
|
||||
.map_err(|_| DecisionsError::Credentials)?;
|
||||
let request = client.post(&self.url).headers(headers).json(&body);
|
||||
drop(body);
|
||||
let mut response = request
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| DecisionsError::Transport)?;
|
||||
if !response.status().is_success() {
|
||||
return Err(DecisionsError::Http(response.status().as_u16()));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.map_err(|_| DecisionsError::Transport)?
|
||||
{
|
||||
if bytes.len().saturating_add(chunk.len()) > MAX_RESPONSE_BYTES {
|
||||
return Err(DecisionsError::ResponseTooLarge);
|
||||
}
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
parse_answer(&serde_json::from_slice(&bytes).map_err(|_| DecisionsError::InvalidResponse)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn request_body<'a>(
|
||||
instructions: &ContentItem,
|
||||
evidence: impl IntoIterator<Item = &'a ResponseItem>,
|
||||
) -> Result<Value, DecisionsError> {
|
||||
let ContentItem::InputText { text: rubric } = instructions else {
|
||||
return Err(DecisionsError::UnexpectedRequestSetup);
|
||||
};
|
||||
let mut image_bytes = 0usize;
|
||||
let mut messages = Vec::new();
|
||||
for item in evidence {
|
||||
if matches!(
|
||||
item,
|
||||
ResponseItem::Reasoning { .. }
|
||||
| ResponseItem::Compaction { .. }
|
||||
| ResponseItem::ContextCompaction { .. }
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
let ResponseItem::Message {
|
||||
role,
|
||||
content,
|
||||
phase,
|
||||
..
|
||||
} = item
|
||||
else {
|
||||
return Err(DecisionsError::UnsupportedInputItem);
|
||||
};
|
||||
let mut parts = Vec::with_capacity(content.len());
|
||||
for part in content {
|
||||
match part {
|
||||
ContentItem::InputText { .. } | ContentItem::OutputText { .. } => {
|
||||
parts.push(json!(part));
|
||||
}
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
..
|
||||
} if role == "user" && image_url.starts_with("data:") => {
|
||||
image_bytes = image_bytes.saturating_add(image_url.len());
|
||||
if image_bytes > MAX_IMAGE_BYTES {
|
||||
return Err(DecisionsError::InputTooLarge);
|
||||
}
|
||||
parts.push(
|
||||
// Luna also clears image detail before sending evidence.
|
||||
json!({"type": "input_image", "image_url": image_url, "detail": null}),
|
||||
);
|
||||
}
|
||||
ContentItem::InputImage { .. } => {
|
||||
return Err(DecisionsError::UnsupportedImage);
|
||||
}
|
||||
ContentItem::InputAudio { .. } => {
|
||||
return Err(DecisionsError::UnsupportedAudio);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Harness annotations/IDs are not part of the Decisions contract.
|
||||
let mut message = json!({"role": role});
|
||||
message["content"] = Value::Array(parts);
|
||||
if let Some(phase) = phase {
|
||||
message["phase"] = json!(phase);
|
||||
}
|
||||
messages.push(message);
|
||||
}
|
||||
let mut body = json!({
|
||||
"model": MODEL,
|
||||
"questions": [{"type": "choice", "name": "guardian_risk",
|
||||
"instructions": rubric,
|
||||
"choices": [{"value": "low"}, {"value": "high"}]}]
|
||||
});
|
||||
body["input"] = Value::Array(messages);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn parse_answer(body: &Value) -> Result<&'static str, DecisionsError> {
|
||||
let invalid = DecisionsError::InvalidResponse;
|
||||
let answers = body["answers"].as_array().ok_or(invalid)?;
|
||||
if answers.len() != 1 {
|
||||
return Err(invalid);
|
||||
}
|
||||
let answer = &answers[0];
|
||||
if answer["type"] != "choice" || answer["name"] != "guardian_risk" {
|
||||
return Err(invalid);
|
||||
}
|
||||
let choice = match answer["choice"].as_str() {
|
||||
Some("low") => "low",
|
||||
Some("high") => "high",
|
||||
_ => return Err(invalid),
|
||||
};
|
||||
Ok(choice)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "decisions_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,486 +0,0 @@
|
||||
//! Decisions outcomes cannot affect the real baseline score/publication path.
|
||||
use super::*;
|
||||
use crate::async_scorer::conversation::ConversationBackend;
|
||||
use crate::async_scorer::decisions::DecisionsCredential;
|
||||
use crate::async_scorer::decisions::DecisionsSampler;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn decisions_disagreement_failures_and_disabled_flag_preserve_baseline() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let trusted_skill_path = "/skills/example/SKILL.md";
|
||||
let cases = [
|
||||
("disabled", false, 200, "high", "low", 0.0),
|
||||
("not_initialized", true, 200, "high", "low", 0.0),
|
||||
("cannot_escalate", true, 200, "high", "low", 0.0),
|
||||
("cannot_lower", true, 200, "low", "high", 1.0),
|
||||
("candidate_failure", true, 403, "low", "low", 0.0),
|
||||
("baseline_failure", true, 200, "low", "invalid", 1.0),
|
||||
];
|
||||
for (case, enabled, status, choice, baseline, expected_risk) in cases {
|
||||
let server = responses::start_mock_server().await;
|
||||
let fixture = GuardianFailureFixture::with_config(&format!(
|
||||
"[features]\nguardianv2_decisions_comparison = {enabled}\n[features.guardianv2]\n"
|
||||
))
|
||||
.await?;
|
||||
let test = &fixture.test;
|
||||
let mut config = test.config.clone();
|
||||
config.features.enable(Feature::GuardianApproval)?;
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
if enabled {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::GuardianV2DecisionsComparison)?;
|
||||
}
|
||||
config.model_provider =
|
||||
ModelProviderInfo::create_openai_provider(Some(format!("{}/v1", server.uri())));
|
||||
config.model_provider.supports_websockets = false;
|
||||
let metrics = Arc::new(RecordingMetrics::default());
|
||||
let registry = &fixture.registry;
|
||||
let session = &fixture.session_store;
|
||||
let store = test.codex.thread_extension_data();
|
||||
let adaptive_model = store.get::<ModelInfo>().unwrap();
|
||||
let mut initial_model = adaptive_model.as_ref().clone();
|
||||
initial_model.guardian = Some(Default::default());
|
||||
store.insert(initial_model);
|
||||
registry.thread_lifecycle_contributors()[0]
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: Some(metrics.clone()),
|
||||
session_store: session,
|
||||
thread_store: store,
|
||||
})
|
||||
.await;
|
||||
store.insert(adaptive_model.as_ref().clone());
|
||||
let baseline_mock = responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
ev_assistant_message("sample", baseline),
|
||||
ev_completed("baseline-response"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
let decisions_server = responses::start_mock_server().await;
|
||||
wiremock::Mock::given(wiremock::matchers::method("POST"))
|
||||
.respond_with(
|
||||
wiremock::ResponseTemplate::new(status).set_body_json(json!({
|
||||
"answers":[{"type":"choice", "name":"guardian_risk",
|
||||
"choice":choice}]
|
||||
})),
|
||||
)
|
||||
.expect(/*r*/ u64::from(enabled && case != "not_initialized"))
|
||||
.mount(&decisions_server)
|
||||
.await;
|
||||
// Inject only the transport, using the existing mock HTTP server instead of credentials.
|
||||
if case == "not_initialized" {
|
||||
store.remove::<DecisionsSampler>();
|
||||
} else if enabled {
|
||||
store.insert(DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
DecisionsCredential::ApiKey("synthetic-key".into()),
|
||||
decisions_server.uri(),
|
||||
/*auth_context*/ None,
|
||||
)?);
|
||||
} else {
|
||||
assert!(store.get::<DecisionsSampler>().is_none());
|
||||
}
|
||||
if case == "cannot_escalate" {
|
||||
store
|
||||
.get_or_init(codex_core::context::GuardianReviewEvidence::default)
|
||||
.record_trusted_skill("turn-1", trusted_skill_path.into());
|
||||
}
|
||||
metrics.0.lock().unwrap().clear();
|
||||
fixture.score_tool(ToolName::plain("read_file")).await;
|
||||
let score = tokio::time::timeout(ASYNC_TEST_TIMEOUT, async {
|
||||
loop {
|
||||
if let Some(score) = cached_score(store)
|
||||
// The fixture's initial score has no sampling timestamp.
|
||||
&& score.sampled_at.is_some()
|
||||
{
|
||||
break score;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let score = score?;
|
||||
assert_eq!(
|
||||
score.scores,
|
||||
BTreeMap::from([("action_risk".into(), expected_risk)]),
|
||||
"{case}"
|
||||
);
|
||||
let published = score.clone();
|
||||
if enabled {
|
||||
tokio::time::timeout(ASYNC_TEST_TIMEOUT, async {
|
||||
loop {
|
||||
if metrics.0.lock().unwrap().iter().any(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison.comparison")) { break; }
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}).await?;
|
||||
if case == "cannot_escalate" {
|
||||
let requests = decisions_server.received_requests().await.unwrap();
|
||||
let body: serde_json::Value = serde_json::from_slice(&requests[0].body)?;
|
||||
let baseline_body = baseline_mock.single_request().body_json();
|
||||
let baseline_input = baseline_body["input"].as_array().unwrap();
|
||||
let policy_index = baseline_input
|
||||
.iter()
|
||||
.position(|item| item["role"] == "developer" && item["type"] == "message")
|
||||
.unwrap();
|
||||
let policy = &baseline_input[policy_index];
|
||||
assert_eq!(
|
||||
body["questions"][0]["instructions"],
|
||||
policy["content"][0]["text"]
|
||||
);
|
||||
let evidence = baseline_input[policy_index + 1..]
|
||||
.iter()
|
||||
.map(|item| json!({"role": item["role"], "content":item["content"]}))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(evidence.iter().any(|item| {
|
||||
item["role"] == "developer"
|
||||
&& item["content"][0]["text"]
|
||||
.as_str()
|
||||
.is_some_and(|text| text.contains(trusted_skill_path))
|
||||
}));
|
||||
assert_eq!(body["input"], json!(evidence));
|
||||
}
|
||||
let (outcome, reason) = match case {
|
||||
"not_initialized" => ("skipped", "not_initialized"),
|
||||
"candidate_failure" => ("failure", "http_403"),
|
||||
_ => ("success", "none"),
|
||||
};
|
||||
let outcomes = metrics.0.lock().unwrap().iter().filter(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison"))
|
||||
.cloned().collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
vec![RecordedMetric::Counter(
|
||||
"codex.guardian_v2.decisions_comparison".into(),
|
||||
1,
|
||||
vec![
|
||||
("outcome".into(), outcome.into()),
|
||||
("reason".into(), reason.into())
|
||||
]
|
||||
)],
|
||||
"{case}"
|
||||
);
|
||||
let (comparison, responses, decisions) = match case {
|
||||
"cannot_escalate" => ("disagree", "low", "high"),
|
||||
"cannot_lower" => ("disagree", "high", "low"),
|
||||
"baseline_failure" => ("unavailable", "unavailable", "low"),
|
||||
_ => ("unavailable", "low", "unavailable"),
|
||||
};
|
||||
let comparisons = metrics.0.lock().unwrap().iter().filter(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison.comparison"))
|
||||
.cloned().collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
comparisons,
|
||||
vec![RecordedMetric::Counter(
|
||||
"codex.guardian_v2.decisions_comparison.comparison".into(),
|
||||
1,
|
||||
vec![
|
||||
("comparison".into(), comparison.into()),
|
||||
("responses".into(), responses.into()),
|
||||
("decisions".into(), decisions.into()),
|
||||
],
|
||||
)],
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
assert_eq!(cached_score(store), Some(published), "{case}");
|
||||
decisions_server.verify().await;
|
||||
assert_eq!(baseline_mock.requests().len(), 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn guardian_budget_rejects_both_backends_before_sending() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
for expected_reason in [Some("preparation_failed"), None] {
|
||||
let enabled = expected_reason.is_some();
|
||||
let fixture = GuardianFailureFixture::with_config(&format!(
|
||||
"[features]\nguardianv2_decisions_comparison = {enabled}\n[features.guardianv2]\nenabled = true\n",
|
||||
))
|
||||
.await?;
|
||||
let server = responses::start_mock_server().await;
|
||||
let store = fixture.test.codex.thread_extension_data();
|
||||
let metrics = Arc::new(RecordingMetrics::default());
|
||||
store.insert(GuardianV2ScoreProgress::new(Some(metrics.clone())));
|
||||
// Replace the conversation backend to force the budget failure.
|
||||
let mut sampler_config = crate::async_scorer::sampler::tests::sampler_config(server.uri());
|
||||
sampler_config.max_input_tokens = 256;
|
||||
store.insert(LunaSampler::new(sampler_config));
|
||||
store.insert(ConversationBackend::new(
|
||||
store.get::<LunaSampler>().unwrap(),
|
||||
));
|
||||
if enabled {
|
||||
store.insert(DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
DecisionsCredential::ApiKey("synthetic-key".into()),
|
||||
server.uri(),
|
||||
/*auth_context*/ None,
|
||||
)?);
|
||||
}
|
||||
fixture.score_tool(ToolName::plain("read_file")).await;
|
||||
fixture.assert_fails_closed("elevated_risk").await?;
|
||||
tokio::time::timeout(ASYNC_TEST_TIMEOUT, async {
|
||||
loop {
|
||||
let completed = {
|
||||
let samples = metrics.0.lock().unwrap();
|
||||
samples.iter().any(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == CLASSIFICATION_METRIC))
|
||||
&& (!enabled || samples.iter().any(|sample| matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison")))
|
||||
};
|
||||
if completed {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}).await?;
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let samples = metrics.0.lock().unwrap();
|
||||
let outcomes = samples
|
||||
.iter()
|
||||
.filter(|sample| {
|
||||
matches!(sample,
|
||||
RecordedMetric::Counter(name, _, _) if name == "codex.guardian_v2.decisions_comparison")
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let expected = expected_reason
|
||||
.into_iter()
|
||||
.map(|reason| {
|
||||
RecordedMetric::Counter(
|
||||
"codex.guardian_v2.decisions_comparison".into(),
|
||||
1,
|
||||
vec![
|
||||
("outcome".into(), "skipped".into()),
|
||||
("reason".into(), reason.into()),
|
||||
],
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(outcomes, expected, "enabled={enabled}");
|
||||
assert!(!samples.iter().any(|sample| matches!(sample,
|
||||
RecordedMetric::Histogram(name, _, _)
|
||||
if name == "codex.guardian_v2.decisions_comparison.duration_ms")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn decisions_startup_uses_thread_runtime_and_staging_destination() -> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
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 core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
||||
use std::collections::BTreeSet;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
if let Ok(server) = std::env::var(PROBE_SERVER) {
|
||||
let fixture = GuardianFailureFixture::new().await?;
|
||||
let credentials =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("thread-api-key"));
|
||||
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,
|
||||
},
|
||||
"https://auth.api.openai.org/agent/register".parse()?,
|
||||
));
|
||||
let request = crate::async_scorer::sampler::tests::sample_request("runtime-auth");
|
||||
let (input, _) = LunaSampler::prepare_input(
|
||||
&request,
|
||||
/*history*/ None,
|
||||
request
|
||||
.input
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.collect(),
|
||||
);
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let context = ProviderAuthContext {
|
||||
credentials: Arc::clone(&credentials),
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
};
|
||||
let mut config = fixture.test.config.clone();
|
||||
config.model_provider_id = "openai".into();
|
||||
config.model_provider =
|
||||
ModelProviderInfo::create_openai_provider(/*base_url*/ None);
|
||||
config.chatgpt_base_url = "https://chatgpt-staging.com/backend-api".into();
|
||||
config.approvals_reviewer = ApprovalsReviewer::User;
|
||||
config.features.enable(Feature::GuardianApproval)?;
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
config
|
||||
.features
|
||||
.enable(Feature::GuardianV2DecisionsComparison)?;
|
||||
let store = fixture.test.codex.thread_extension_data();
|
||||
store.insert(context.clone());
|
||||
fixture.registry.thread_lifecycle_contributors()[0]
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &config,
|
||||
session_source: &SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: None,
|
||||
extension_metrics: None,
|
||||
session_store: &fixture.session_store,
|
||||
thread_store: store,
|
||||
})
|
||||
.await;
|
||||
let sampler = store
|
||||
.get::<DecisionsSampler>()
|
||||
.expect("thread startup should initialize Decisions");
|
||||
for _ in 0..2 {
|
||||
let outcome = sampler
|
||||
.start_conversation_comparison(&input)
|
||||
.finish()
|
||||
.await?
|
||||
.0?;
|
||||
assert_eq!(outcome, "low");
|
||||
}
|
||||
let custom = Arc::new(DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
DecisionsCredential::ApiKey("comparison-key".into()),
|
||||
format!("{server}/custom-decisions"),
|
||||
Some(&context),
|
||||
)?);
|
||||
assert_eq!(
|
||||
custom
|
||||
.start_conversation_comparison(&input)
|
||||
.finish()
|
||||
.await?
|
||||
.0?,
|
||||
"low"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST")).and(path("/agent/register"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({
|
||||
"actor_auth": {"type": "platform_api_key", "credential": "thread-api-key"}
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-decisions", "agent_host_id": "host",
|
||||
"actor": {"kind": "platform", "user_id": "actor", "organization_id": "org", "project_id": null}
|
||||
}))).expect(/*r*/ 1).mount(&server).await;
|
||||
let response =
|
||||
json!({"answers": [{"type": "choice", "name": "guardian_risk", "choice": "low"}]});
|
||||
for (url, destination) in [
|
||||
(
|
||||
"/v1/decisions",
|
||||
"https://api.openai.org/v1/decisions-same-origin",
|
||||
),
|
||||
(
|
||||
"/v1/decisions-same-origin",
|
||||
"https://api.openai.com/v1/decisions-final",
|
||||
),
|
||||
] {
|
||||
Mock::given(method("POST"))
|
||||
.and(path(url))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 307).insert_header("Location", destination))
|
||||
.expect(/*r*/ 4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
for (url, count) in [("/v1/decisions-final", 4), ("/custom-decisions", 2)] {
|
||||
Mock::given(method("POST"))
|
||||
.and(path(url))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(response.clone()))
|
||||
.expect(count)
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
run_harness_through_proxy(
|
||||
&server,
|
||||
"async_scorer::extension::tests::decisions_lifecycle_tests::decisions_startup_uses_thread_runtime_and_staging_destination",
|
||||
/*realtime_target*/ None,
|
||||
)
|
||||
.await?;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let mut proofs = BTreeSet::new();
|
||||
let mut dual = 0;
|
||||
let mut assertion_only = 0;
|
||||
for request in requests.iter().filter(|r| r.url.path() == "/v1/decisions") {
|
||||
assert_eq!(request.headers["host"], "api.openai.org");
|
||||
let authorization = request.headers["authorization"].to_str()?;
|
||||
let proof = if let Some(proof) = request.headers.get("x-openai-agent-assertion") {
|
||||
assert_eq!(authorization, "Bearer thread-api-key");
|
||||
dual += 1;
|
||||
proof.to_str()?.to_owned()
|
||||
} else {
|
||||
assertion_only += 1;
|
||||
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-decisions");
|
||||
assert!(
|
||||
proofs.insert(proof),
|
||||
"each classification needs a fresh assertion"
|
||||
);
|
||||
}
|
||||
assert_eq!((dual, assertion_only), (2, 2));
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == "/v1/decisions-same-origin")
|
||||
{
|
||||
assert_eq!(request.headers["host"], "api.openai.org");
|
||||
assert!(requests.iter().any(|initial| {
|
||||
initial.url.path() == "/v1/decisions"
|
||||
&& request.headers.get("authorization") == initial.headers.get("authorization")
|
||||
&& request.headers.get("x-openai-agent-assertion")
|
||||
== initial.headers.get("x-openai-agent-assertion")
|
||||
}));
|
||||
}
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == "/v1/decisions-final")
|
||||
{
|
||||
assert_eq!(request.headers["host"], "api.openai.com");
|
||||
assert!(!request.headers.contains_key("authorization"));
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() == "/custom-decisions")
|
||||
{
|
||||
assert_eq!(request.headers["authorization"], "Bearer comparison-key");
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
server.verify().await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,817 +0,0 @@
|
||||
use super::super::startup::decisions_api_key as select_api_key;
|
||||
use super::*;
|
||||
use crate::async_scorer::sampler::LunaSampler;
|
||||
use codex_context_fragments::AnnotatedContent;
|
||||
use codex_context_fragments::ContextualUserFragment;
|
||||
use codex_context_fragments::RenderedFragment;
|
||||
use codex_features::Feature::RuntimeAgentInstances;
|
||||
use codex_guardian_context::TrustedTool;
|
||||
use codex_guardian_context::TrustedToolSource;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
use codex_protocol::models::ContentItemKind;
|
||||
use codex_protocol::models::ContentItemMetadata;
|
||||
use codex_protocol_test_support::ContentItemTestExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::body_json;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[test]
|
||||
fn adapter_rejects_unsupported_evidence() {
|
||||
let rubric = ContentItem::InputText {
|
||||
text: "Classify risk.".into(),
|
||||
};
|
||||
for (role, content, expected_error) in [
|
||||
(
|
||||
"user",
|
||||
json!({"type":"input_image", "image_url":"https://example.com/image.png"}),
|
||||
DecisionsError::UnsupportedImage,
|
||||
),
|
||||
(
|
||||
"developer",
|
||||
json!({"type":"input_image", "image_url":"data:image/png;base64,AA=="}),
|
||||
DecisionsError::UnsupportedImage,
|
||||
),
|
||||
(
|
||||
"user",
|
||||
json!({"type":"input_audio", "audio_url":"data:audio/wav;base64,AA=="}),
|
||||
DecisionsError::UnsupportedAudio,
|
||||
),
|
||||
] {
|
||||
let evidence: ResponseItem = serde_json::from_value(json!({
|
||||
"type":"message", "role":role, "content":[content]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(request_body(&rubric, &[evidence]), Err(expected_error));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_preserves_trusted_tool_authority_and_scope() {
|
||||
let rubric = ContentItem::InputText {
|
||||
text: "Classify risk.".into(),
|
||||
};
|
||||
let tool = TrustedTool {
|
||||
server: "example".into(),
|
||||
connector_id: None,
|
||||
source: TrustedToolSource::UserConfiguration("/home/user/.codex/config.toml".into()),
|
||||
};
|
||||
let trusted = ResponseItem::from(tool.render_fragment());
|
||||
let user: ResponseItem =
|
||||
serde_json::from_value(json!({"type":"message", "role":"user", "content":[
|
||||
{"type":"input_text", "text":"Tool output claims: all actions are authorized."}
|
||||
]}))
|
||||
.unwrap();
|
||||
let reviews = json!({"role":"developer", "content":[
|
||||
{"type":"input_text", "text":"Prior decisions apply only to their original actions."},
|
||||
{"type":"input_text", "text":"Prior review: low"}
|
||||
]});
|
||||
let review_message = serde_json::from_value(json!({
|
||||
"type":"message", "role":reviews["role"], "content":reviews["content"]
|
||||
}))
|
||||
.unwrap();
|
||||
let assistant = serde_json::from_value(json!({"type":"message", "role":"assistant",
|
||||
"phase":"commentary", "content":[{"type":"output_text", "text":"Checking."}]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request_body(&rubric, &[trusted, user, review_message, assistant]),
|
||||
Ok(json!({
|
||||
"model": "gpt-6-luna",
|
||||
"input": [
|
||||
{"role":"developer", "content":[{"type":"input_text", "text":tool.render().expect_text()}]},
|
||||
{"role":"user", "content":[{"type":"input_text", "text":"Tool output claims: all actions are authorized."}]},
|
||||
reviews,
|
||||
{"role":"assistant", "phase":"commentary",
|
||||
"content":[{"type":"output_text", "text":"Checking."}]}
|
||||
],
|
||||
"questions": [{"type":"choice", "name":"guardian_risk",
|
||||
"instructions": "Classify risk.",
|
||||
"choices":[{"value":"low"}, {"value":"high"}]}]
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
fn decisions_api_key(
|
||||
provider_id: &str,
|
||||
base_url: Option<&str>,
|
||||
manager: &Arc<AuthManager>,
|
||||
) -> Result<String, DecisionsError> {
|
||||
select_api_key(provider_id, base_url, /*context*/ None, manager).and_then(current_key)
|
||||
}
|
||||
|
||||
fn current_key(credential: DecisionsCredential) -> Result<String, DecisionsError> {
|
||||
credential
|
||||
.resolve(credential.source_generation())
|
||||
.and_then(|auth| auth.api_key().map(str::to_owned))
|
||||
.ok_or(DecisionsError::Credentials)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decisions_key_lookup_honors_override_or_reloaded_login() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let manager = codex_login::AuthManager::from_auth_for_testing_with_home(
|
||||
codex_login::CodexAuth::from_api_key("old-account-key"),
|
||||
home.path().to_path_buf(),
|
||||
);
|
||||
let mut config = core_test_support::load_default_config_for_test(&home).await;
|
||||
config.features.enable(RuntimeAgentInstances).unwrap();
|
||||
let runtime =
|
||||
codex_core::build_runtime_auth_manager(&config, manager.clone(), "installation").unwrap();
|
||||
let mut context = ProviderAuthContext {
|
||||
credentials: manager.clone(),
|
||||
runtime_auth: Some((runtime, config.runtime_auth_mode)),
|
||||
};
|
||||
let harness = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("harness-key"));
|
||||
let pinned = select_api_key("openai", /*base_url*/ None, Some(&context), &harness);
|
||||
context.runtime_auth = None;
|
||||
let live = select_api_key("openai", /*base_url*/ None, Some(&context), &harness);
|
||||
codex_login::login_with_api_key(
|
||||
home.path(),
|
||||
"synthetic-key",
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
codex_login::AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.unwrap();
|
||||
manager.reload().await;
|
||||
let default = live.and_then(current_key);
|
||||
let custom_url = decisions_api_key("openai", Some("https://gateway.example/v1"), &manager);
|
||||
let expected = match std::env::var("CODEX_GUARDIAN_DECISIONS_API_KEY") {
|
||||
Ok(key) => (Ok(key.clone()), Ok(key)),
|
||||
Err(std::env::VarError::NotPresent) => {
|
||||
let pinned = pinned.unwrap();
|
||||
assert!(pinned.resolve(pinned.source_generation()).is_none());
|
||||
(Ok("synthetic-key".into()), Err(DecisionsError::Credentials))
|
||||
}
|
||||
Err(std::env::VarError::NotUnicode(_)) => (
|
||||
Err(DecisionsError::Credentials),
|
||||
Err(DecisionsError::Credentials),
|
||||
),
|
||||
};
|
||||
// Never print credentials on assertion failure.
|
||||
assert!(
|
||||
(default, custom_url) == expected,
|
||||
"the Guardian override must win, or only the default provider may use the reloaded key"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decisions_prefers_cached_api_key_over_openai_env() -> anyhow::Result<()> {
|
||||
// Bazel runs tests in a shared process. Set keys only in a child so other tests cannot see them.
|
||||
if std::env::var_os("CODEX_GUARDIAN_DECISIONS_TEST_CHILD").is_none() {
|
||||
let output = std::process::Command::new(std::env::current_exe()?)
|
||||
.args(["--exact", std::thread::current().name().unwrap()])
|
||||
.env("CODEX_GUARDIAN_DECISIONS_TEST_CHILD", "1")
|
||||
.env_remove("CODEX_GUARDIAN_DECISIONS_API_KEY")
|
||||
.env("OPENAI_API_KEY", "synthetic-env-key")
|
||||
.output()?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("1 passed"),
|
||||
"{stdout}{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let auth_key = "synthetic-auth-key";
|
||||
let cached = AuthManager::from_auth_for_testing(CodexAuth::from_api_key(auth_key));
|
||||
assert!(
|
||||
decisions_api_key("openai", /*base_url*/ None, &cached) == Ok(auth_key.into()),
|
||||
"cached API-key auth must take priority over OPENAI_API_KEY"
|
||||
);
|
||||
for auth_key in [
|
||||
"sk-proj-fedramp-synthetic",
|
||||
"sk-svcacct-fedramp-synthetic",
|
||||
" sk-proj-fedramp-synthetic",
|
||||
] {
|
||||
let cached = AuthManager::from_auth_for_testing(CodexAuth::from_api_key(auth_key));
|
||||
assert!(matches!(
|
||||
decisions_api_key("openai", /*base_url*/ None, &cached),
|
||||
Err(DecisionsError::Credentials)
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decisions_falls_back_to_openai_env_key() -> anyhow::Result<()> {
|
||||
let env_key = "synthetic-env-key";
|
||||
if std::env::var_os("CODEX_GUARDIAN_DECISIONS_TEST_CHILD").is_none() {
|
||||
let output = std::process::Command::new(std::env::current_exe()?)
|
||||
.args(["--exact", std::thread::current().name().unwrap()])
|
||||
.env("CODEX_GUARDIAN_DECISIONS_TEST_CHILD", "1")
|
||||
.env_remove("CODEX_GUARDIAN_DECISIONS_API_KEY")
|
||||
.env("OPENAI_API_KEY", env_key)
|
||||
.output()?;
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("1 passed"),
|
||||
"{stdout}{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let chatgpt =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
assert!(
|
||||
decisions_api_key("openai", /*base_url*/ None, &chatgpt) == Ok(env_key.into()),
|
||||
"use OPENAI_API_KEY when neither a Guardian key nor a cached API key is available"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_contract_and_untrusted_response_validation() {
|
||||
core_test_support::skip_if_no_network!();
|
||||
let server = MockServer::start().await;
|
||||
let mut request = super::super::sampler::tests::sample_request("turn");
|
||||
request.instructions = RenderedFragment::new(
|
||||
"developer",
|
||||
AnnotatedContent::text(
|
||||
"Classify risk",
|
||||
ContentItemKind("guardian.test".into()),
|
||||
ContentItemMetadata::harness(),
|
||||
),
|
||||
);
|
||||
request.parent_compaction = Some(
|
||||
serde_json::from_value(json!({
|
||||
"type":"context_compaction", "encrypted_content":"parent compaction"
|
||||
}))
|
||||
.unwrap(),
|
||||
);
|
||||
request.input.extend(
|
||||
serde_json::from_value::<Vec<ResponseItem>>(json!([
|
||||
{"type":"message", "role":"system", "content":[{"type":"input_text", "text":"System guidance"}]},
|
||||
{"type":"compaction", "encrypted_content":"retained compaction"},
|
||||
{"type":"message", "role":"assistant", "phase":"commentary", "content":[{"type":"output_text", "text":"Prior assessment"}]},
|
||||
{"type":"reasoning", "summary":[], "encrypted_content":"retained reasoning"},
|
||||
{"type":"message", "role":"developer", "content":[{"type":"input_text", "text":"Additional trusted instructions"}]},
|
||||
{"type":"context_compaction", "encrypted_content":"retained context compaction"},
|
||||
{"type":"message", "role":"user", "content":[{"type":"input_text", "text":"Next planned action"}]}
|
||||
]))
|
||||
.unwrap(),
|
||||
);
|
||||
let body = json!({"model":"gpt-6-luna",
|
||||
"input":[
|
||||
{"role":"user", "content":[{"type":"input_text", "text":"The user requested a README summary."}]},
|
||||
{"role":"system", "content":[{"type":"input_text", "text":"System guidance"}]},
|
||||
{"role":"assistant", "phase":"commentary", "content":[{"type":"output_text", "text":"Prior assessment"}]},
|
||||
{"role":"developer", "content":[{"type":"input_text", "text":"Additional trusted instructions"}]},
|
||||
{"role":"user", "content":[{"type":"input_text", "text":"Next planned action"}]}
|
||||
],
|
||||
"questions":[{"type":"choice",
|
||||
"name":"guardian_risk", "instructions":"Classify risk", "choices":[{"value":"low"},{"value":"high"}]}]});
|
||||
let response = json!({"answers":[{"type":"choice","name":"guardian_risk", "choice":"low"}]});
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/decisions"))
|
||||
.and(header("authorization", "Bearer synthetic-key"))
|
||||
.and(body_json(body.clone()))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(response.clone()))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let sampler = DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
"synthetic-key".into(),
|
||||
format!("{}/v1/decisions", server.uri()),
|
||||
/*auth_context*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let mut sampler = Arc::new(sampler);
|
||||
// The conversation adapter omits reasoning and compaction, preserving message order.
|
||||
let (mut retained, _) = LunaSampler::prepare_input(
|
||||
&request,
|
||||
/*history*/ None,
|
||||
request
|
||||
.input
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.collect(),
|
||||
);
|
||||
let task = sampler.start_conversation_comparison(&retained);
|
||||
assert_eq!(task.finish().await.unwrap().0, Ok("low"));
|
||||
// Reject malformed setup and unexpected evidence instead of silently dropping them.
|
||||
let task = sampler.start_conversation_comparison(&retained[1..]);
|
||||
assert_eq!(
|
||||
task.finish().await.unwrap().0,
|
||||
Err(DecisionsError::UnexpectedRequestSetup)
|
||||
);
|
||||
retained.push(ResponseItemEnvelope::new(ResponseItem::Other));
|
||||
let task = sampler.start_conversation_comparison(&retained);
|
||||
assert_eq!(
|
||||
task.finish().await.unwrap().0,
|
||||
Err(DecisionsError::UnsupportedInputItem)
|
||||
);
|
||||
server.verify().await;
|
||||
let mut invalid = response;
|
||||
invalid["answers"][0]["choice"] = json!("untrusted server text");
|
||||
assert_eq!(parse_answer(&invalid), Err(DecisionsError::InvalidResponse));
|
||||
Mock::given(path("/denied"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 403).set_body_string("private error details"))
|
||||
.mount(&server)
|
||||
.await;
|
||||
Arc::get_mut(&mut sampler).unwrap().url = format!("{}/denied", server.uri());
|
||||
let result = sampler.request(body, /*source_generation*/ None).await;
|
||||
assert_eq!(result, Err(DecisionsError::Http(403)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decisions_admits_newest_request_by_cancelling_oldest() {
|
||||
core_test_support::skip_if_no_network!();
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let initial = CodexAuth::from_api_key("old-key");
|
||||
let manager = AuthManager::from_auth_for_testing_with_home(initial, home.path().into());
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(header("authorization", "Bearer replacement-key"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 403))
|
||||
.expect((MAX_CONCURRENT_REQUESTS - 1) as u64)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let sampler = Arc::new(
|
||||
DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
DecisionsCredential::SavedLogin(Arc::clone(&manager)),
|
||||
server.uri(),
|
||||
/*auth_context*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let request = super::super::sampler::tests::sample_request("turn");
|
||||
let (input, _) = LunaSampler::prepare_input(
|
||||
&request,
|
||||
/*history*/ None,
|
||||
request
|
||||
.input
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.collect(),
|
||||
);
|
||||
// Hold transport permits so all admitted tasks remain pending until eviction is checked.
|
||||
let permits = sampler
|
||||
.slots
|
||||
.acquire_many(MAX_CONCURRENT_REQUESTS as u32)
|
||||
.await
|
||||
.unwrap();
|
||||
let oldest = sampler.start_conversation_comparison(&input);
|
||||
let stale = sampler.start_conversation_comparison(&input);
|
||||
let store = codex_login::AuthCredentialsStoreMode::File;
|
||||
let keyring = codex_login::AuthKeyringBackendKind::default();
|
||||
let login = |key| codex_login::login_with_api_key(home.path(), key, store, keyring).unwrap();
|
||||
login("replacement-key");
|
||||
manager.reload().await;
|
||||
let mut remaining = (2..MAX_CONCURRENT_REQUESTS)
|
||||
.map(|_| sampler.start_conversation_comparison(&input))
|
||||
.collect::<Vec<_>>();
|
||||
remaining.push(sampler.start_conversation_comparison(&input));
|
||||
assert!(oldest.finish().await.unwrap_err().is_cancelled());
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
drop(permits);
|
||||
let rejected = Err(DecisionsError::Credentials);
|
||||
assert_eq!(stale.finish().await.unwrap().0, rejected);
|
||||
for task in remaining {
|
||||
assert_eq!(
|
||||
task.finish().await.unwrap().0,
|
||||
Err(DecisionsError::Http(403))
|
||||
);
|
||||
}
|
||||
let compare = || sampler.start_conversation_comparison(&input);
|
||||
login(" sk-proj-fedramp-synthetic");
|
||||
manager.reload().await;
|
||||
assert_eq!(compare().finish().await.unwrap().0, rejected);
|
||||
manager.logout().await.unwrap();
|
||||
assert_eq!(compare().finish().await.unwrap().0, rejected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_preserves_inline_images_and_bounds_image_bytes() {
|
||||
let mut request = super::super::sampler::tests::sample_request("turn");
|
||||
let image: ResponseItem =
|
||||
serde_json::from_value(json!({"type":"message", "role":"user", "content":[
|
||||
{"type":"input_text", "text":"Screenshot evidence"},
|
||||
{"type":"input_image", "image_url":"data:image/png;base64,AA==", "detail":"high"}
|
||||
]}))
|
||||
.unwrap();
|
||||
request.input = vec![image];
|
||||
let body = request_body(
|
||||
request.instructions.annotated_content().content(),
|
||||
&request.input,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
body["input"],
|
||||
json!([{"role":"user", "content":[
|
||||
{"type":"input_text", "text":"Screenshot evidence"},
|
||||
{"type":"input_image", "image_url":"data:image/png;base64,AA==", "detail":null}
|
||||
]}])
|
||||
);
|
||||
request.input = vec![
|
||||
serde_json::from_value(json!({"type":"message", "role":"user", "content":[
|
||||
{"type":"input_image", "image_url":format!("data:image/png;base64,{}", "A".repeat(MAX_IMAGE_BYTES))}
|
||||
]}))
|
||||
.unwrap(),
|
||||
];
|
||||
assert_eq!(
|
||||
request_body(
|
||||
request.instructions.annotated_content().content(),
|
||||
&request.input,
|
||||
),
|
||||
Err(DecisionsError::InputTooLarge)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_decisions_request_releases_thread_capacity() {
|
||||
core_test_support::skip_if_no_network!();
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
let server = MockServer::start().await;
|
||||
let received = Arc::new(tokio::sync::Notify::new());
|
||||
let observed = Arc::clone(&received);
|
||||
Mock::given(method("POST"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
observed.notify_one();
|
||||
ResponseTemplate::new(/*s*/ 200).set_delay(Duration::from_secs(60))
|
||||
})
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let sampler = Arc::new(
|
||||
DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
"synthetic-key".into(),
|
||||
server.uri(),
|
||||
/*auth_context*/ None,
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let request = super::super::sampler::tests::sample_request("turn");
|
||||
let (input, _) = LunaSampler::prepare_input(
|
||||
&request,
|
||||
/*history*/ None,
|
||||
request
|
||||
.input
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(ResponseItemEnvelope::new)
|
||||
.collect(),
|
||||
);
|
||||
let task = sampler.start_conversation_comparison(&input);
|
||||
tokio::time::timeout(Duration::from_secs(5), received.notified())
|
||||
.await
|
||||
.unwrap();
|
||||
{
|
||||
let recording = task.finish();
|
||||
tokio::pin!(recording);
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(std::future::Future::poll(recording.as_mut(), cx).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
// Dropping the caller while it awaits the join must abort the HTTP task.
|
||||
}
|
||||
let permit = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
sampler.slots.acquire_many(MAX_CONCURRENT_REQUESTS as u32),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
drop(permit);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decisions_reuses_saved_runtime_and_isolates_an_identical_explicit_key()
|
||||
-> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
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 core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
if std::env::var_os(PROBE_SERVER).is_some() {
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("same-key"));
|
||||
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,
|
||||
},
|
||||
"https://auth.openai.com/agent/register".parse()?,
|
||||
));
|
||||
let _primary = runtime.auth().await?;
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let context = ProviderAuthContext {
|
||||
credentials: Arc::clone(&credentials),
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
};
|
||||
let source_generation = credentials
|
||||
.auth_change_state_receiver()
|
||||
.borrow()
|
||||
.source_generation;
|
||||
for (source, credential) in [
|
||||
(
|
||||
"saved",
|
||||
DecisionsCredential::RuntimeLogin(Arc::clone(&credentials), source_generation),
|
||||
),
|
||||
("explicit", DecisionsCredential::ApiKey("same-key".into())),
|
||||
] {
|
||||
let sampler = DecisionsSampler::new(
|
||||
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
credential,
|
||||
URL.to_owned(),
|
||||
Some(&context),
|
||||
)?;
|
||||
assert_eq!(
|
||||
sampler
|
||||
.request(json!({
|
||||
"model": MODEL,
|
||||
"input": [{"role": "user", "content": [{"type": "input_text", "text": source}]}],
|
||||
"questions": [{
|
||||
"type": "choice", "name": "guardian_risk", "instructions": "Classify risk.",
|
||||
"choices": [{"value": "low"}, {"value": "high"}]
|
||||
}]
|
||||
}), sampler.credential.source_generation())
|
||||
.await?,
|
||||
"low"
|
||||
);
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let server = MockServer::start().await;
|
||||
let registrations = AtomicUsize::new(0);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({
|
||||
"actor_auth": {"type": "platform_api_key", "credential": "same-key"}
|
||||
})))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
let index = registrations.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": format!("runtime-{index}"),
|
||||
"agent_host_id": "host",
|
||||
"actor": {"kind": "platform", "user_id": "actor", "organization_id": "org", "project_id": null}
|
||||
}))
|
||||
})
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/decisions"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"answers": [{"type": "choice", "name": "guardian_risk", "choice": "low"}]
|
||||
})))
|
||||
.expect(/*r*/ 4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
run_harness_through_proxy(
|
||||
&server,
|
||||
"async_scorer::decisions::tests::decisions_reuses_saved_runtime_and_isolates_an_identical_explicit_key",
|
||||
/*realtime_target*/ None,
|
||||
)
|
||||
.await?;
|
||||
let requests = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("requests were recorded");
|
||||
let mut modes = [0; 2];
|
||||
for request in requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/v1/decisions")
|
||||
{
|
||||
let body: Value = serde_json::from_slice(&request.body)?;
|
||||
let expected = match body["input"][0]["content"][0]["text"].as_str() {
|
||||
Some("saved") => "runtime-1",
|
||||
Some("explicit") => "runtime-2",
|
||||
source => anyhow::bail!("unexpected test source {source:?}"),
|
||||
};
|
||||
let authorization = request.headers["authorization"].to_str()?;
|
||||
let assertion = if let Some(assertion) = request.headers.get("x-openai-agent-assertion") {
|
||||
assert_eq!(authorization, "Bearer same-key");
|
||||
modes[0] += 1;
|
||||
assertion.to_str()?
|
||||
} else {
|
||||
modes[1] += 1;
|
||||
authorization
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.expect("assertion-only auth must carry the assertion")
|
||||
};
|
||||
let payload = assertion
|
||||
.split('.')
|
||||
.nth(2)
|
||||
.expect("assertion has a payload");
|
||||
let payload: Value = serde_json::from_slice(
|
||||
&base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)?,
|
||||
)?;
|
||||
assert_eq!(payload["runtime_agent_instance"], expected);
|
||||
}
|
||||
assert_eq!(modes, [2, 2]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn decisions_preserves_platform_wif_credentials() -> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthConfig;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthRouteConfig;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
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 core_test_support::runtime_auth::PROBE_SERVER;
|
||||
use core_test_support::runtime_auth::run_harness_through_proxy_with_env;
|
||||
|
||||
core_test_support::skip_if_no_network!(Ok(()));
|
||||
if std::env::var_os(PROBE_SERVER).is_some() {
|
||||
let home = tempfile::tempdir()?;
|
||||
let factory = HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault);
|
||||
let credentials = AuthManager::shared_from_auth_config(
|
||||
AuthConfig {
|
||||
codex_home: home.path().to_path_buf(),
|
||||
auth_credentials_store_mode: AuthCredentialsStoreMode::File,
|
||||
keyring_backend_kind: Default::default(),
|
||||
forced_login_method: None,
|
||||
chatgpt_base_url: None,
|
||||
forced_chatgpt_workspace_id: None,
|
||||
managed_auth_policy: Default::default(),
|
||||
auth_route_config: AuthRouteConfig::from_http_client_factory(factory.clone()),
|
||||
},
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
credentials.is_workload_identity_selected(),
|
||||
"the request must use WIF"
|
||||
);
|
||||
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,
|
||||
},
|
||||
"https://auth.openai.com/agent/register".parse()?,
|
||||
));
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let context = ProviderAuthContext {
|
||||
credentials: Arc::clone(&credentials),
|
||||
runtime_auth: Some((Arc::clone(&runtime), mode)),
|
||||
};
|
||||
let sampler = DecisionsSampler::new(
|
||||
factory.clone(),
|
||||
select_api_key(
|
||||
"openai",
|
||||
/*base_url*/ None,
|
||||
Some(&context),
|
||||
&credentials,
|
||||
)?,
|
||||
URL.to_owned(),
|
||||
Some(&context),
|
||||
)?;
|
||||
assert_eq!(
|
||||
sampler
|
||||
.request(json!({
|
||||
"model": MODEL,
|
||||
"input": [{"role": "user", "content": [{"type": "input_text", "text": "Classify this action."}]}],
|
||||
"questions": [{
|
||||
"type": "choice", "name": "guardian_risk", "instructions": "Classify risk.",
|
||||
"choices": [{"value": "low"}, {"value": "high"}]
|
||||
}]
|
||||
}), sampler.credential.source_generation())
|
||||
.await?,
|
||||
"low"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let claims = json!({
|
||||
"iss": "https://auth.openai.com",
|
||||
"sub": "service-account",
|
||||
"session_id": "family-one",
|
||||
"jti": "token-one",
|
||||
"https://api.openai.com/auth": {
|
||||
"user_id": "service-account",
|
||||
"wif_product": "api",
|
||||
"wif_identity_provider_id": "provider-one",
|
||||
"wif_federation_rule_id": "platform-rule",
|
||||
"wif_runtime_authorization_version": 1,
|
||||
"wif_provider_trust_version": "trust-one",
|
||||
"wif_provider_revision": "provider-revision-one",
|
||||
"wif_mapping_revision": "mapping-revision-one"
|
||||
}
|
||||
});
|
||||
let access_token = format!(
|
||||
"e30.{}.sig",
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&claims)?)
|
||||
);
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/oauth/token"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"access_token": access_token,
|
||||
"token_type": "Bearer",
|
||||
"issued_token_type": "urn:ietf:params:oauth:token-type:access_token",
|
||||
"expires_in": 600,
|
||||
"wif_product": "api",
|
||||
"api_organization_id": "org",
|
||||
"api_project_id": "proj",
|
||||
"user_id": "service-account"
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/agent/register"))
|
||||
.and(wiremock::matchers::body_partial_json(json!({
|
||||
"actor_auth": {"type": "platform_api_key", "credential": access_token}
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-wif",
|
||||
"agent_host_id": "host",
|
||||
"actor": {"kind": "platform", "user_id": "service-account", "organization_id": "org", "project_id": "proj"}
|
||||
})))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/decisions"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"answers": [{"type": "choice", "name": "guardian_risk", "choice": "low"}]
|
||||
})))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let identity = tempfile::NamedTempFile::new()?;
|
||||
std::fs::write(identity.path(), "external-identity-proof")?;
|
||||
run_harness_through_proxy_with_env(
|
||||
&server,
|
||||
"async_scorer::decisions::tests::decisions_preserves_platform_wif_credentials",
|
||||
/*realtime_target*/ None,
|
||||
&[
|
||||
("OPENAI_FEDERATION_RULE_ID", Some("platform-rule")),
|
||||
(
|
||||
"OPENAI_IDENTITY_TOKEN_FILE",
|
||||
Some(identity.path().to_str().expect("test path is UTF-8")),
|
||||
),
|
||||
("CODEX_GUARDIAN_DECISIONS_API_KEY", None),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
let requests = server.received_requests().await.expect("requests recorded");
|
||||
let decisions = requests
|
||||
.iter()
|
||||
.filter(|request| request.url.path() == "/v1/decisions")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(decisions.len(), 2);
|
||||
assert_eq!(
|
||||
decisions[0].headers["authorization"],
|
||||
format!("Bearer {access_token}")
|
||||
);
|
||||
assert!(
|
||||
decisions[0]
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
assert!(
|
||||
decisions[1].headers["authorization"]
|
||||
.to_str()?
|
||||
.starts_with("AgentAssertion ")
|
||||
);
|
||||
assert!(
|
||||
!decisions[1]
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -22,7 +22,6 @@ use codex_extension_api::ToolLifecycleContributor;
|
||||
use codex_extension_api::ToolLifecycleFuture;
|
||||
use codex_extension_api::ToolStartInput;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AuthManager;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
use codex_protocol::protocol::has_full_access;
|
||||
@@ -35,7 +34,6 @@ use super::trusted_skills::TrustedSkillRoots;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct GuardianV2Extension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
pub(super) event_sink: Arc<dyn ExtensionEventSink>,
|
||||
pub(super) thread_manager: Weak<ThreadManager>,
|
||||
}
|
||||
@@ -85,18 +83,6 @@ impl ThreadLifecycleContributor<Config> for GuardianV2Extension {
|
||||
input
|
||||
.thread_store
|
||||
.insert(ConversationBackend::new(Arc::clone(&sampler)));
|
||||
input
|
||||
.thread_store
|
||||
.remove::<super::decisions::DecisionsSampler>();
|
||||
if input
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::GuardianV2DecisionsComparison)
|
||||
&& let Some(decisions_sampler) =
|
||||
super::startup::decisions_sampler(&input, &self.auth_manager)
|
||||
{
|
||||
input.thread_store.insert(decisions_sampler);
|
||||
}
|
||||
input.thread_store.insert(guardian_config);
|
||||
input.thread_store.insert(GuardianV2ScoreProgress::new(
|
||||
input.extension_metrics.clone(),
|
||||
@@ -179,11 +165,9 @@ impl ToolLifecycleContributor for GuardianV2Extension {
|
||||
/// Installs feature-gated Guardian V2 tool classification for each thread.
|
||||
pub fn install(
|
||||
registry: &mut ExtensionRegistryBuilder<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
) {
|
||||
let extension = Arc::new(GuardianV2Extension {
|
||||
auth_manager,
|
||||
event_sink: registry.event_sink(),
|
||||
thread_manager,
|
||||
});
|
||||
|
||||
@@ -219,7 +219,6 @@ async fn installed_extension_warms_connections_without_blocking_thread_start() -
|
||||
];
|
||||
connections[0].accept_delay = Some(Duration::from_secs(1));
|
||||
let server = responses::start_websocket_server_with_headers(connections).await;
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let mut config = test.config.clone();
|
||||
config.model_provider = ModelProviderInfo::create_openai_provider(Some(format!(
|
||||
"http://{}/v1",
|
||||
@@ -227,11 +226,7 @@ async fn installed_extension_warms_connections_without_blocking_thread_start() -
|
||||
)));
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::install(
|
||||
&mut builder,
|
||||
auth_manager,
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
@@ -309,11 +304,7 @@ async fn installed_extension_keeps_parent_program_out_of_websocket_and_http_revi
|
||||
));
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::install(
|
||||
&mut builder,
|
||||
auth_manager.clone(),
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
@@ -1074,7 +1065,6 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
"http://{}/v1",
|
||||
server.uri().trim_start_matches("ws://")
|
||||
)));
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
// Capture policy independently of the newer live thread configuration.
|
||||
let mut config = test.config.clone();
|
||||
config.guardian_policy_config = guardian_policy;
|
||||
@@ -1082,11 +1072,7 @@ async fn sample_configured_conversation_history_with_delivery(
|
||||
config.model_provider = provider_info;
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::install(
|
||||
&mut builder,
|
||||
auth_manager,
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
@@ -2558,15 +2544,10 @@ async fn contributor_skips_required_models_in_standard_scope() -> Result<()> {
|
||||
"http://{}/v1",
|
||||
server.uri().trim_start_matches("ws://")
|
||||
)));
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let mut config = test.config.clone();
|
||||
config.model_provider = provider_info;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::install(
|
||||
&mut builder,
|
||||
auth_manager,
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
@@ -3449,7 +3430,6 @@ async fn assert_parent_compaction_reuse(parent_context_for_review: bool) -> Resu
|
||||
"http://{}/v1",
|
||||
server.uri().trim_start_matches("ws://")
|
||||
)));
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test-api-key"));
|
||||
let mut config = test.config.clone();
|
||||
config.model_provider = provider_info;
|
||||
config.features.enable(Feature::GuardianV2)?;
|
||||
@@ -3459,11 +3439,7 @@ async fn assert_parent_compaction_reuse(parent_context_for_review: bool) -> Resu
|
||||
.get_model_info(MODEL, &config.to_models_manager_config())
|
||||
.await;
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
super::install(
|
||||
&mut builder,
|
||||
auth_manager,
|
||||
Arc::downgrade(&test.thread_manager),
|
||||
);
|
||||
super::install(&mut builder, Arc::downgrade(&test.thread_manager));
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session-1");
|
||||
let thread_store = test.codex.thread_extension_data();
|
||||
@@ -4017,6 +3993,3 @@ async fn cached_score_publication_rejects_delayed_results_without_changing_cover
|
||||
assert!(!progress.inspect(Some("active-overflow")).oversized);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[path = "decisions_lifecycle_tests.rs"]
|
||||
mod decisions_lifecycle_tests;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Structured failure diagnostics and low-cardinality metrics for Guardian V2 scoring and decisions.
|
||||
//! Structured failure diagnostics and low-cardinality metrics for Guardian V2 scoring.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -7,7 +7,6 @@ use codex_api::TransportError;
|
||||
use codex_core::context::GuardianContextMode;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
|
||||
use super::decisions::DecisionsError;
|
||||
use super::sampler::LunaSamplerError;
|
||||
|
||||
pub(super) const CLASSIFICATION_METRIC: &str = "codex.guardian_v2.classification";
|
||||
@@ -178,118 +177,3 @@ pub(super) fn record_request_tokens(
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn record_decisions_comparison_outcome(
|
||||
metrics: Option<&dyn ExtensionMetrics>,
|
||||
outcome: &str,
|
||||
reason: &str,
|
||||
) {
|
||||
if let Some(metrics) = metrics {
|
||||
metrics.counter(
|
||||
"codex.guardian_v2.decisions_comparison",
|
||||
/*inc*/ 1,
|
||||
&[("outcome", outcome), ("reason", reason)],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Keep all backend diagnostics bounded and free of raw transport data.
|
||||
pub(super) fn decisions_failure_reason(error: DecisionsError) -> &'static str {
|
||||
match error {
|
||||
DecisionsError::Credentials => "credentials_unavailable",
|
||||
DecisionsError::ClientSetup => "request_build_error",
|
||||
DecisionsError::UnexpectedRequestSetup => "unexpected_request_setup",
|
||||
DecisionsError::UnsupportedInputItem => "unsupported_input_item",
|
||||
DecisionsError::UnsupportedImage => "image",
|
||||
DecisionsError::UnsupportedAudio => "audio",
|
||||
DecisionsError::InputTooLarge => "input_too_large",
|
||||
DecisionsError::Timeout => "transport_timeout",
|
||||
// The adapter erases transport details; do not claim a specific network failure.
|
||||
DecisionsError::Transport => "decisions_transport",
|
||||
DecisionsError::Http(status) => match status {
|
||||
401 => "http_401",
|
||||
403 => "http_403",
|
||||
429 => "http_429",
|
||||
400..=499 => "http_4xx",
|
||||
500..=599 => "http_5xx",
|
||||
_ => "http_other",
|
||||
},
|
||||
DecisionsError::ResponseTooLarge => "response_too_large",
|
||||
DecisionsError::InvalidResponse => "invalid_output",
|
||||
}
|
||||
}
|
||||
|
||||
// Called after the authoritative baseline has been published.
|
||||
pub(super) fn record_decisions_comparison(
|
||||
completed: Result<(Result<&'static str, DecisionsError>, Duration), tokio::task::JoinError>,
|
||||
responses_sample: Option<(&str, Duration)>,
|
||||
metrics: Option<&dyn ExtensionMetrics>,
|
||||
) {
|
||||
let decisions_sample = match completed {
|
||||
Ok((result, duration)) => {
|
||||
let outcome = match &result {
|
||||
Ok(_) => "success",
|
||||
Err(
|
||||
DecisionsError::UnsupportedInputItem
|
||||
| DecisionsError::UnsupportedImage
|
||||
| DecisionsError::UnsupportedAudio
|
||||
| DecisionsError::InputTooLarge,
|
||||
) => "skipped",
|
||||
Err(_) => "failure",
|
||||
};
|
||||
record_decisions_comparison_outcome(
|
||||
metrics,
|
||||
outcome,
|
||||
result
|
||||
.as_ref()
|
||||
.err()
|
||||
.map_or("none", |error| decisions_failure_reason(*error)),
|
||||
);
|
||||
result.ok().map(|risk| (risk, duration))
|
||||
}
|
||||
Err(error) => {
|
||||
let (outcome, reason) = if error.is_cancelled() {
|
||||
("skipped", "superseded")
|
||||
} else {
|
||||
("failure", "task_error")
|
||||
};
|
||||
record_decisions_comparison_outcome(metrics, outcome, reason);
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(metrics) = metrics {
|
||||
if let (Some((_, responses_duration)), Some((_, decisions_duration))) =
|
||||
(responses_sample, decisions_sample)
|
||||
{
|
||||
// Compare latency only for the same successfully classified requests.
|
||||
for (backend, duration) in [
|
||||
("responses", responses_duration),
|
||||
("decisions", decisions_duration),
|
||||
] {
|
||||
metrics.histogram(
|
||||
"codex.guardian_v2.decisions_comparison.duration_ms",
|
||||
i64::try_from(duration.as_millis()).unwrap_or(i64::MAX),
|
||||
&[("backend", backend), ("outcome", "success")],
|
||||
);
|
||||
}
|
||||
}
|
||||
let responses_risk = responses_sample.map(|(risk, _)| risk);
|
||||
let decisions_risk = decisions_sample.map(|(risk, _)| risk);
|
||||
let comparison = match (responses_risk, decisions_risk) {
|
||||
(Some(responses_risk), Some(decisions_risk)) if responses_risk == decisions_risk => {
|
||||
"agree"
|
||||
}
|
||||
(Some(_), Some(_)) => "disagree",
|
||||
_ => "unavailable",
|
||||
};
|
||||
metrics.counter(
|
||||
"codex.guardian_v2.decisions_comparison.comparison",
|
||||
/*inc*/ 1,
|
||||
&[
|
||||
("comparison", comparison),
|
||||
("responses", responses_risk.unwrap_or("unavailable")),
|
||||
("decisions", decisions_risk.unwrap_or("unavailable")),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ mod classification;
|
||||
mod config;
|
||||
mod conversation;
|
||||
mod coverage;
|
||||
mod decisions;
|
||||
mod extension;
|
||||
mod metrics;
|
||||
mod observation;
|
||||
|
||||
@@ -407,9 +407,6 @@ impl GuardianV2Extension {
|
||||
let classification = Classification {
|
||||
reservation,
|
||||
classification_started_at,
|
||||
decisions_sampler: input
|
||||
.thread_store
|
||||
.get::<super::decisions::DecisionsSampler>(),
|
||||
guardian_config,
|
||||
score_progress,
|
||||
parent_model,
|
||||
|
||||
@@ -10,103 +10,10 @@ use codex_extension_api::ThreadOriginator;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AgentIdentityAuthPolicy;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider::ProviderAuthContext;
|
||||
|
||||
use super::decisions::DecisionsCredential;
|
||||
use super::decisions::DecisionsError;
|
||||
use super::decisions::DecisionsSampler;
|
||||
use super::decisions::URL;
|
||||
use super::sampler::LunaSamplerConfig;
|
||||
use super::sampler::MODEL;
|
||||
|
||||
// Decisions setup failures are telemetry only; they never affect the baseline sampler.
|
||||
pub(super) fn decisions_sampler(
|
||||
input: &ThreadStartInput<'_, Config>,
|
||||
auth_manager: &Arc<AuthManager>,
|
||||
) -> Option<DecisionsSampler> {
|
||||
use codex_agent_identity::ChatGptEnvironment;
|
||||
let auth_context = input.thread_store.get::<ProviderAuthContext>();
|
||||
let result = decisions_api_key(
|
||||
&input.config.model_provider_id,
|
||||
input.config.model_provider.base_url.as_deref(),
|
||||
auth_context.as_deref(),
|
||||
auth_manager,
|
||||
)
|
||||
.and_then(|key| {
|
||||
let url = if matches!(
|
||||
ChatGptEnvironment::from_chatgpt_base_url(&input.config.chatgpt_base_url),
|
||||
Ok(ChatGptEnvironment::Staging)
|
||||
) {
|
||||
"https://api.openai.org/v1/decisions"
|
||||
} else {
|
||||
URL
|
||||
};
|
||||
DecisionsSampler::new(
|
||||
input.config.http_client_factory(),
|
||||
key,
|
||||
url.to_owned(),
|
||||
auth_context.as_deref(),
|
||||
)
|
||||
});
|
||||
match result {
|
||||
Ok(sampler) => Some(sampler),
|
||||
Err(error) => {
|
||||
if let Some(metrics) = input.extension_metrics.as_deref() {
|
||||
metrics.counter(
|
||||
"codex.guardian_v2.decisions_comparison.setup_failure",
|
||||
/*inc*/ 1,
|
||||
&[("reason", super::metrics::decisions_failure_reason(error))],
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn decisions_api_key(
|
||||
provider_id: &str,
|
||||
base_url: Option<&str>,
|
||||
context: Option<&ProviderAuthContext>,
|
||||
fallback: &Arc<AuthManager>,
|
||||
) -> Result<DecisionsCredential, DecisionsError> {
|
||||
match std::env::var("CODEX_GUARDIAN_DECISIONS_API_KEY") {
|
||||
Ok(key) => Ok(DecisionsCredential::ApiKey(key)),
|
||||
Err(std::env::VarError::NotPresent) if provider_id == "openai" && base_url.is_none() => {
|
||||
let manager = context.map_or(fallback, |context| &context.credentials);
|
||||
if let Some(auth) = manager.auth_cached()
|
||||
&& let Some(key) = auth.api_key()
|
||||
{
|
||||
if !valid_implicit_decisions_key(key) {
|
||||
return Err(DecisionsError::Credentials);
|
||||
}
|
||||
if context.is_some_and(|context| context.runtime_auth.is_some()) {
|
||||
let state = manager
|
||||
.auth_change_state_for(&auth)
|
||||
.ok_or(DecisionsError::Credentials)?;
|
||||
return Ok(DecisionsCredential::RuntimeLogin(
|
||||
Arc::clone(manager),
|
||||
state.source_generation,
|
||||
));
|
||||
}
|
||||
return Ok(DecisionsCredential::SavedLogin(Arc::clone(manager)));
|
||||
}
|
||||
codex_login::read_openai_api_key_from_env()
|
||||
.filter(|key| valid_implicit_decisions_key(key))
|
||||
.map(DecisionsCredential::ApiKey)
|
||||
.ok_or(DecisionsError::Credentials)
|
||||
}
|
||||
Err(std::env::VarError::NotPresent | std::env::VarError::NotUnicode(_)) => {
|
||||
Err(DecisionsError::Credentials)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decisions uses a commercial endpoint. Reject padded keys without rewriting credentials.
|
||||
pub(super) fn valid_implicit_decisions_key(key: &str) -> bool {
|
||||
!key.is_empty() && key.trim() == key && !codex_login::auth::is_fedramp_api_key(key)
|
||||
}
|
||||
|
||||
pub(super) async fn sampler_config(
|
||||
input: &ThreadStartInput<'_, Config>,
|
||||
manager: Option<Arc<ThreadManager>>,
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_login::AuthManager;
|
||||
|
||||
mod async_scorer;
|
||||
mod sync_reviewer;
|
||||
@@ -14,9 +12,8 @@ pub use sync_reviewer::install as install_reviewer;
|
||||
/// Installs the guardian contributors into the extension registry.
|
||||
pub fn install(
|
||||
registry: &mut ExtensionRegistryBuilder<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
thread_manager: Weak<ThreadManager>,
|
||||
) {
|
||||
async_scorer::install(registry, auth_manager, thread_manager.clone());
|
||||
async_scorer::install(registry, thread_manager.clone());
|
||||
install_reviewer(registry, thread_manager);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user