Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Move Guardian review reporting and denial accounting into the extension (#45677)

jif0265dd7b4547
diff --git a/codex-rs/core/src/guardian/decision.rs b/codex-rs/core/src/guardian/decision.rs
index 2779900d97..0f9332d2fc 100644
--- a/codex-rs/core/src/guardian/decision.rs
+++ b/codex-rs/core/src/guardian/decision.rs
@@ -132,18 +132,23 @@ pub(crate) async fn decide_approval(
));
}
};
- let runtime = codex_guardian_reviewer::SynchronousReview::new(ReviewRuntime {
- session: Arc::clone(&session),
- history_reset: history_reset.clone(),
- context: context.clone(),
- review_id: review_id.clone(),
- request: request.clone(),
- reasons,
- options: GuardianReviewOptions {
- require_guardian,
- ..options
+ let runtime = codex_guardian_reviewer::SynchronousReview {
+ host: ReviewRuntime {
+ session: Arc::clone(&session),
+ history_reset: history_reset.clone(),
+ context: context.clone(),
+ review_id: review_id.clone(),
+ request: request.clone(),
+ reasons,
+ options,
},
- });
+ thread_store: &session.services.thread_extension_data,
+ // Keep the existing turn-level reporting policy during this ownership move.
+ model: turn.model_info(),
+ require_guardian,
+ telemetry: &session.services.session_telemetry,
+ analytics: &session.services.analytics_events_client,
+ };
let input = ApprovalDecisionInput {
approval_id: &review_id,
tool_call_id: request
diff --git a/codex-rs/core/src/guardian/mod.rs b/codex-rs/core/src/guardian/mod.rs
index a4e0e1429a..875e550bb3 100644
--- a/codex-rs/core/src/guardian/mod.rs
+++ b/codex-rs/core/src/guardian/mod.rs
@@ -53,8 +53,6 @@ pub(crate) use prompt::guardian_truncate_text;
pub(crate) use review::GuardianReviewOptions;
pub(crate) use review::is_basic_session_source;
pub(crate) use review::new_guardian_review_id;
-#[cfg(test)]
-pub(crate) use review::record_guardian_denial_for_test;
pub(crate) use review::routes_approval_policy_to_guardian;
pub use review_session::GuardianReviewSession;
pub(crate) use review_session::GuardianReviewSessionManager;
diff --git a/codex-rs/core/src/guardian/review.rs b/codex-rs/core/src/guardian/review.rs
index fc7960d547..e8e7cae725 100644
--- a/codex-rs/core/src/guardian/review.rs
+++ b/codex-rs/core/src/guardian/review.rs
@@ -1,5 +1,5 @@
-//! Supplies host review preparation, interruption and runtime configuration.
-//! Guardian's extension owns the synchronous review loop and pool.
+//! Supplies host review preparation and context-dependent configuration.
+//! Guardian's extension owns execution, reporting and denial accounting.
#[path = "review_request.rs"]
mod request;
@@ -8,7 +8,6 @@ use crate::context::GuardianContextMode;
use codex_analytics::GuardianApprovalRequestSource;
use codex_analytics::GuardianReviewAnalyticsResult;
use codex_core_plugins::PluginCommandAttribution;
-use codex_extension_api::ThreadIdleCause;
use codex_features::Feature;
use codex_guardian_reviewer::GuardianReviewError;
use codex_guardian_reviewer::GuardianReviewOutcome;
@@ -21,8 +20,6 @@ use codex_protocol::protocol::InternalSessionSource;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
-use codex_protocol::protocol::TurnAbortReason;
-use codex_protocol::protocol::WarningEvent;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
@@ -31,8 +28,6 @@ use tokio_util::sync::CancellationToken;
use crate::context::GuardianNodeReplPolicy;
use crate::context::GuardianReviewEvidence;
use crate::session::session::Session;
-use crate::session::turn_context::TurnContext;
-use crate::turn_timing::now_unix_timestamp_ms;
use super::ApprovalRequestReasons;
#[cfg(test)]
@@ -134,56 +129,6 @@ pub(super) async fn record_guardian_non_denial(session: &Arc<Session>) {
.await;
}
-async fn record_guardian_denial(session: &Arc<Session>) {
- let turn = {
- let active = session.active_turn.lock().await;
- let Some(task) = active.as_ref().and_then(|active| active.task.as_ref()) else {
- return;
- };
- Arc::clone(&task.turn_context)
- };
- let turn_id = &turn.sub_id;
- let Some(message) =
- codex_guardian_reviewer::ReviewDenials::for_thread(&session.services.thread_extension_data)
- .record_denial(turn_id, turn.model_info())
- .await
- else {
- return;
- };
-
- if session.turn_context_for_sub_id(turn_id).await.is_none() {
- return;
- }
-
- session
- .send_event(
- turn.as_ref(),
- EventMsg::GuardianWarning(WarningEvent { message }),
- )
- .await;
-
- let runtime_handle = session.services.runtime_handle.clone();
- let session = Arc::clone(session);
- let turn_id = turn_id.to_string();
- let _abort_task = runtime_handle.spawn(async move {
- let aborted = session
- .abort_turn_if_active(&turn_id, TurnAbortReason::Interrupted)
- .await;
- if aborted {
- // Guardian aborts bypass normal task completion, so emit its idle lifecycle here.
- // User interrupts deliberately do not take this path.
- session
- .emit_thread_idle_lifecycle_if_idle(ThreadIdleCause::Interrupted)
- .await;
- }
- });
-}
-
-#[cfg(test)]
-pub(crate) async fn record_guardian_denial_for_test(session: &Arc<Session>) {
- record_guardian_denial(session).await;
-}
-
#[derive(Clone)]
pub(crate) struct GuardianReviewOptions {
/// Requires Guardian rather than a manual approval; cached evidence may still satisfy it.
diff --git a/codex-rs/core/src/guardian/review_request.rs b/codex-rs/core/src/guardian/review_request.rs
index ce6c9c3f64..37aa7df4fb 100644
--- a/codex-rs/core/src/guardian/review_request.rs
+++ b/codex-rs/core/src/guardian/review_request.rs
@@ -1,5 +1,5 @@
-//! Captures and reports one review on the host's original action and authorization state.
-//! Guardian's extension owns orchestration; this adapter preserves event and evidence behavior.
+//! Captures a review on the host's original action and authorization state.
+//! The extension chooses effects; this adapter supplies evidence, validation and publication.
use super::*;
use crate::codex_thread::GuardianAuthorizationVersion;
@@ -8,8 +8,6 @@ use codex_protocol::approvals::GuardianReviewReason;
pub(in crate::guardian) struct PreparedApproval {
request: GuardianApprovalRequest,
- turn: Arc<TurnContext>,
- report: codex_guardian_reviewer::ReviewReport,
root_authorization_version: Option<GuardianAuthorizationVersion>,
user_message_revision: u64,
review_evidence: Option<(
@@ -27,11 +25,19 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
self.options.external_cancel.as_ref()
}
+ async fn servicing_turn(
+ &self,
+ ) -> Option<(String, Arc<codex_protocol::openai_models::ModelInfo>)> {
+ let active = self.session.active_turn.lock().await;
+ let turn = &active.as_ref()?.task.as_ref()?.turn_context;
+ Some((turn.sub_id.clone(), Arc::clone(turn.model_info())))
+ }
+
async fn prepare(
&self,
review_reason: GuardianReviewReason,
deadline: Instant,
- ) -> Result<PreparedApproval, ReviewDecision> {
+ ) -> Result<(PreparedApproval, codex_guardian_reviewer::ReviewReport), ReviewDecision> {
let super::super::runtime::ReviewRuntime {
session,
history_reset: _,
@@ -105,37 +111,6 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
review_reason,
model_context,
});
- session
- .send_event(
- turn.as_ref(),
- EventMsg::GuardianAssessment(report.started_event()),
- )
- .await;
- if external_cancel
- .as_ref()
- .is_some_and(CancellationToken::is_cancelled)
- {
- let completed_at_ms = now_unix_timestamp_ms();
- let completed = report.complete(
- GuardianReviewOutcome::Error(GuardianReviewError::Cancelled),
- turn.model_info(),
- self.options.require_guardian,
- GuardianReviewAnalyticsResult::without_session(),
- completed_at_ms,
- );
- report.track(
- &session.services.session_telemetry,
- &session.services.analytics_events_client,
- completed.analytics,
- completed_at_ms.try_into().unwrap_or_default(),
- );
- session
- .send_event(turn.as_ref(), EventMsg::GuardianAssessment(completed.event))
- .await;
- record_guardian_non_denial(&session).await;
- return Err(ReviewDecision::Abort);
- }
-
let root_authorization_version = session
.services
.agent_control
@@ -163,14 +138,15 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
None
};
drop(history);
- Ok(PreparedApproval {
- request,
- turn,
+ Ok((
+ PreparedApproval {
+ request,
+ root_authorization_version,
+ user_message_revision,
+ review_evidence,
+ },
report,
- root_authorization_version,
- user_message_revision,
- review_evidence,
- })
+ ))
}
async fn attempt(
@@ -178,7 +154,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
prepared: &PreparedApproval,
deadline: Instant,
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
- run_guardian_review_session_before_deadline(
+ let (mut outcome, analytics) = run_guardian_review_session_before_deadline(
Arc::clone(&self.session),
self.context.clone(),
prepared.request.clone(),
@@ -187,24 +163,10 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
self.options.external_cancel.clone(),
deadline,
)
- .await
- }
-
- async fn complete(
- &self,
- prepared: PreparedApproval,
- mut outcome: GuardianReviewOutcome,
- analytics_result: GuardianReviewAnalyticsResult,
- ) -> Option<ReviewDecision> {
- let PreparedApproval {
- request: _,
- turn,
- report,
- root_authorization_version,
- user_message_revision,
- review_evidence,
- } = prepared;
- let session = Arc::clone(&self.session);
+ .await;
+ let session = &self.session;
+ let root_authorization_version = prepared.root_authorization_version;
+ let user_message_revision = prepared.user_message_revision;
if matches!(&outcome, GuardianReviewOutcome::Completed(assessment) if assessment.outcome == GuardianAssessmentOutcome::Allow)
&& ((session.guardian_context_mode == GuardianContextMode::ThreadOwned
&& (root_authorization_version
@@ -231,47 +193,33 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
outcome = GuardianReviewOutcome::Error(GuardianReviewError::Cancelled);
}
- let completed_at_ms = now_unix_timestamp_ms();
- let completed = report.complete(
- outcome,
- turn.model_info(),
- self.options.require_guardian,
- analytics_result,
- completed_at_ms,
- );
- report.track(
- &session.services.session_telemetry,
- &session.services.analytics_events_client,
- completed.analytics,
- completed_at_ms.try_into().unwrap_or_default(),
- );
- if let Some(message) = completed.warning {
- session
- .send_event(
- turn.as_ref(),
- EventMsg::GuardianWarning(WarningEvent { message }),
- )
- .await;
- }
- if completed.assessment_outcome.is_some()
- && let Some((evidence, action, authorization_version, root_authorization_version)) =
- review_evidence
+ (outcome, analytics)
+ }
+
+ async fn emit(&self, event: EventMsg) {
+ self.session.send_event(self.context.turn(), event).await;
+ }
+
+ async fn record_evidence(
+ &self,
+ prepared: &PreparedApproval,
+ event: &codex_protocol::protocol::GuardianAssessmentEvent,
+ ) {
+ if let Some((evidence, action, authorization_version, root_authorization_version)) =
+ &prepared.review_evidence
{
evidence.record(
- &completed.event,
- &action,
- authorization_version,
- root_authorization_version,
+ event,
+ action,
+ *authorization_version,
+ *root_authorization_version,
);
}
- session
- .send_event(turn.as_ref(), EventMsg::GuardianAssessment(completed.event))
+ }
+
+ async fn interrupt(&self, turn_id: &str, warning: EventMsg) {
+ self.session
+ .interrupt_turn_with_warning(turn_id, warning)
.await;
- if completed.assessment_outcome == Some(GuardianAssessmentOutcome::Deny) {
- record_guardian_denial(&session).await;
- } else {
- record_guardian_non_denial(&session).await;
- }
- completed.decision
}
}
diff --git a/codex-rs/core/src/session/extension_interruption.rs b/codex-rs/core/src/session/extension_interruption.rs
new file mode 100644
index 0000000000..e244750db9
--- /dev/null
+++ b/codex-rs/core/src/session/extension_interruption.rs
@@ -0,0 +1,35 @@
+//! Applies extension-requested interruption only if the selected turn is still active.
+//! The caller selects the warning; the host owns task cancellation and idle notification.
+
+use super::session::Session;
+use codex_extension_api::ThreadIdleCause;
+use codex_protocol::protocol::EventMsg;
+use codex_protocol::protocol::TurnAbortReason;
+use std::sync::Arc;
+
+impl Session {
+ pub(crate) async fn interrupt_turn_with_warning(
+ self: &Arc<Self>,
+ turn_id: &str,
+ warning: EventMsg,
+ ) {
+ let Some(turn) = self.turn_context_for_sub_id(turn_id).await else {
+ return;
+ };
+ self.send_event(turn.as_ref(), warning).await;
+ let runtime = self.services.runtime_handle.clone();
+ let session = Arc::clone(self);
+ let turn_id = turn_id.to_owned();
+ drop(runtime.spawn(async move {
+ if session
+ .abort_turn_if_active(&turn_id, TurnAbortReason::Interrupted)
+ .await
+ {
+ // Extension aborts bypass normal task completion; user interrupts do not.
+ session
+ .emit_thread_idle_lifecycle_if_idle(ThreadIdleCause::Interrupted)
+ .await;
+ }
+ }));
+ }
+}
diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs
index affecf42d5..3272ecbf6e 100644
--- a/codex-rs/core/src/session/mod.rs
+++ b/codex-rs/core/src/session/mod.rs
@@ -228,6 +228,7 @@ use codex_protocol::exec_output::StreamOutput;
mod code_mode_warning;
pub(crate) mod context_window;
mod environment;
+mod extension_interruption;
pub(crate) mod extension_metrics;
mod handlers;
mod inject;
diff --git a/codex-rs/core/src/session/step_activation.rs b/codex-rs/core/src/session/step_activation.rs
index 8dc090315a..7af13b412c 100644
--- a/codex-rs/core/src/session/step_activation.rs
+++ b/codex-rs/core/src/session/step_activation.rs
@@ -95,7 +95,7 @@ fn check_legacy_model_safety(
return Err("the destination model has only fallback metadata".to_string());
}
let retained_models = [admitted, current];
- // guardian::review::record_guardian_denial still selects its circuit-breaker
+ // The Guardian reviewer extension still selects its circuit-breaker
// policy from the admitted model's Cyber classification.
let destination_is_cyber =
destination.model_specialty.as_deref() == Some(MODEL_SPECIALTY_CYBER);
diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs
index f2d047d0ea..1955065c72 100644
--- a/codex-rs/core/src/session/tests.rs
+++ b/codex-rs/core/src/session/tests.rs
@@ -10604,27 +10604,32 @@ impl SessionTask for NeverEndingTask {
}
#[derive(Clone, Copy)]
-struct GuardianDeniedApprovalTask;
+struct ExtensionInterruptedTask;
-impl SessionTask for GuardianDeniedApprovalTask {
+impl SessionTask for ExtensionInterruptedTask {
fn kind(&self) -> TaskKind {
TaskKind::Regular
}
fn span_name(&self) -> &'static str {
- "session_task.guardian_denied_approval"
+ "session_task.extension_interrupted"
}
async fn run(
self: Arc<Self>,
session: Arc<Session>,
- _ctx: Arc<TurnContext>,
+ ctx: Arc<TurnContext>,
_input: Vec<TurnInput>,
cancellation_token: CancellationToken,
) -> SessionTaskResult {
- for _ in 0..3 {
- crate::guardian::record_guardian_denial_for_test(&session).await;
- }
+ session
+ .interrupt_turn_with_warning(
+ &ctx.sub_id,
+ EventMsg::Warning(codex_protocol::protocol::WarningEvent {
+ message: "extension interrupted this turn".into(),
+ }),
+ )
+ .await;
cancellation_token.cancelled().await;
Ok(None)
@@ -10938,7 +10943,7 @@ async fn interrupting_compaction_fallback_retains_last_known_step_context() {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn guardian_auto_review_emits_thread_idle_after_interrupt() {
+async fn extension_interrupt_emits_thread_idle() {
struct ThreadIdleRecorder(async_channel::Sender<()>);
impl codex_extension_api::ThreadLifecycleContributor<crate::config::Config> for ThreadIdleRecorder {
@@ -10959,26 +10964,22 @@ async fn guardian_auto_review_emits_thread_idle_after_interrupt() {
session.services.extensions = Arc::new(builder.build());
Arc::new(session)
- .spawn_task(
- Arc::new(turn_context),
- Vec::new(),
- GuardianDeniedApprovalTask,
- )
+ .spawn_task(Arc::new(turn_context), Vec::new(), ExtensionInterruptedTask)
.await;
timeout(StdDuration::from_secs(5), idle_rx.recv())
.await
- .expect("guardian interrupt should emit thread idle lifecycle")
+ .expect("extension interrupt should emit thread idle lifecycle")
.expect("idle receiver open");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn guardian_helper_review_interrupts_after_three_consecutive_denials() {
+async fn extension_interrupt_survives_the_calling_runtime() {
let (sess, tc, rx) = make_session_and_context_with_rx().await;
let input = vec![TurnInput::UserInput {
acceptance_order: None,
content: vec![UserInput::Text {
- text: "keep turn active for helper reviews".to_string(),
+ text: "keep turn active for extension interruption".to_string(),
text_elements: Vec::new(),
}],
client_id: None,
@@ -11000,9 +11001,14 @@ async fn guardian_helper_review_interrupts_after_three_consecutive_denials() {
.build()
.expect("helper review runtime");
runtime.block_on(async move {
- for _ in 0..3 {
- crate::guardian::record_guardian_denial_for_test(&session_for_review).await;
- }
+ session_for_review
+ .interrupt_turn_with_warning(
+ &tc.sub_id,
+ EventMsg::Warning(codex_protocol::protocol::WarningEvent {
+ message: "extension interrupted this turn".into(),
+ }),
+ )
+ .await;
});
});
review_thread.join().expect("helper review thread");
@@ -11021,9 +11027,7 @@ async fn guardian_helper_review_interrupts_after_three_consecutive_denials() {
})
.await
.unwrap_or_else(|_| {
- panic!(
- "helper review circuit breaker should interrupt the turn; observed events: {observed:?}"
- )
+ panic!("extension should interrupt the turn; observed events: {observed:?}")
});
assert_eq!(aborted.reason, TurnAbortReason::Interrupted);
}
diff --git a/codex-rs/ext/guardian-reviewer/src/review.rs b/codex-rs/ext/guardian-reviewer/src/review.rs
index bf0704ad15..2e5bbf72f8 100644
--- a/codex-rs/ext/guardian-reviewer/src/review.rs
+++ b/codex-rs/ext/guardian-reviewer/src/review.rs
@@ -1,74 +1,139 @@
-//! Orchestrates one synchronous approval review over a host-bound action.
-//! All callers share this policy; the host captures evidence and enforces the result.
-
-use std::future::Future;
+//! Owns synchronous review orchestration, reporting and outcome accounting.
+//! The host binds the original action, captures evidence and enforces authorization.
+use crate::GuardianReviewError;
+use crate::GuardianReviewOutcome;
+use crate::GuardianReviewSessionLimits;
+use crate::ReviewDenials;
+use crate::ReviewReport;
+use codex_analytics::AnalyticsEventsClient;
use codex_analytics::GuardianReviewAnalyticsResult;
+use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::SynchronousApprovalReviewer;
+use codex_otel::SessionTelemetry;
use codex_protocol::approvals::GuardianReviewReason;
+use codex_protocol::openai_models::ModelInfo;
+use codex_protocol::protocol::EventMsg;
+use codex_protocol::protocol::GuardianAssessmentEvent;
+use codex_protocol::protocol::GuardianAssessmentOutcome;
use codex_protocol::protocol::ReviewDecision;
+use codex_protocol::protocol::WarningEvent;
+use std::future::Future;
+use std::sync::Arc;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
-use crate::GuardianReviewOutcome;
-use crate::GuardianReviewSessionLimits;
-
-/// Runtime operations bound to one immutable approval action and its issuing context.
-/// Preparation captures trusted evidence. Completion must invalidate stale approvals
-/// and may only satisfy the review gate, never expand the action's execution authority.
-/// Completion may return `None` for user approval only when host policy permits it.
+/// Operations bound to one immutable action and its issuing context.
+/// Hosts validate authority, publish supplied events and interrupt only the selected turn;
+/// they do not select Guardian outcomes, retry policy or reporting effects.
pub trait ReviewHost: Send + Sync {
type Prepared: Send + Sync;
-
fn cancellation(&self) -> Option<&CancellationToken>;
+ /// Captures the turn currently servicing reviews, which may differ from a yielded cell's origin.
+ fn servicing_turn(&self) -> impl Future<Output = Option<(String, Arc<ModelInfo>)>> + Send;
fn prepare(
&self,
reason: GuardianReviewReason,
deadline: Instant,
- ) -> impl Future<Output = Result<Self::Prepared, ReviewDecision>> + Send;
+ ) -> impl Future<Output = Result<(Self::Prepared, ReviewReport), ReviewDecision>> + Send;
+ /// Rejects stale approvals before returning the attempt's outcome.
fn attempt(
&self,
prepared: &Self::Prepared,
deadline: Instant,
) -> impl Future<Output = (GuardianReviewOutcome, GuardianReviewAnalyticsResult)> + Send;
- fn complete(
+ fn emit(&self, event: EventMsg) -> impl Future<Output = ()> + Send;
+ fn record_evidence(
&self,
- prepared: Self::Prepared,
- outcome: GuardianReviewOutcome,
- analytics: GuardianReviewAnalyticsResult,
- ) -> impl Future<Output = Option<ReviewDecision>> + Send;
+ prepared: &Self::Prepared,
+ event: &GuardianAssessmentEvent,
+ ) -> impl Future<Output = ()> + Send;
+ fn interrupt(&self, turn_id: &str, warning: EventMsg) -> impl Future<Output = ()> + Send;
}
/// One review bound by the host before Guardian's approval policy chooses to run it.
-pub struct SynchronousReview<H> {
- host: H,
+pub struct SynchronousReview<'a, H> {
+ pub host: H,
+ pub thread_store: &'a ExtensionData,
+ pub model: &'a ModelInfo,
+ pub require_guardian: bool,
+ pub telemetry: &'a SessionTelemetry,
+ pub analytics: &'a AnalyticsEventsClient,
}
-impl<H: ReviewHost> SynchronousReview<H> {
- pub fn new(host: H) -> Self {
- Self { host }
- }
-}
-
-impl<H: ReviewHost> SynchronousApprovalReviewer for SynchronousReview<H> {
+impl<H: ReviewHost> SynchronousApprovalReviewer for SynchronousReview<'_, H> {
fn review(&self, reason: GuardianReviewReason) -> ExtensionFuture<'_, Option<ReviewDecision>> {
Box::pin(async move {
let deadline = Instant::now() + crate::REVIEW_TIMEOUT;
- let prepared = match self.host.prepare(reason, deadline).await {
+ let (context, report) = match self.host.prepare(reason, deadline).await {
Ok(prepared) => prepared,
Err(decision) => return Some(decision),
};
- let (outcome, analytics) = Box::pin(crate::run_with_retry(
- GuardianReviewSessionLimits {
- max_attempts: crate::MAX_REVIEW_ATTEMPTS,
- deadline,
- },
- self.host.cancellation(),
- |deadline| self.host.attempt(&prepared, deadline),
- ))
- .await;
- self.host.complete(prepared, outcome, analytics).await
+ self.host
+ .emit(EventMsg::GuardianAssessment(report.started_event()))
+ .await;
+ let (outcome, analytics) = if self
+ .host
+ .cancellation()
+ .is_some_and(CancellationToken::is_cancelled)
+ {
+ (
+ GuardianReviewOutcome::Error(GuardianReviewError::Cancelled),
+ GuardianReviewAnalyticsResult::without_session(),
+ )
+ } else {
+ Box::pin(crate::run_with_retry(
+ GuardianReviewSessionLimits {
+ max_attempts: crate::MAX_REVIEW_ATTEMPTS,
+ deadline,
+ },
+ self.host.cancellation(),
+ |deadline| self.host.attempt(&context, deadline),
+ ))
+ .await
+ };
+ let completed_at_ms = codex_analytics::now_unix_millis();
+ let completed = report.complete(
+ outcome,
+ self.model,
+ self.require_guardian,
+ analytics,
+ completed_at_ms.try_into().unwrap_or_default(),
+ );
+ report.track(
+ self.telemetry,
+ self.analytics,
+ completed.analytics,
+ completed_at_ms,
+ );
+ if let Some(message) = completed.warning {
+ self.host
+ .emit(EventMsg::GuardianWarning(WarningEvent { message }))
+ .await;
+ }
+ if completed.assessment_outcome.is_some() {
+ self.host.record_evidence(&context, &completed.event).await;
+ }
+ self.host
+ .emit(EventMsg::GuardianAssessment(completed.event))
+ .await;
+ if let Some((turn_id, model)) = self.host.servicing_turn().await {
+ let denials = ReviewDenials::for_thread(self.thread_store);
+ if completed.assessment_outcome == Some(GuardianAssessmentOutcome::Deny) {
+ if let Some(message) = denials.record_denial(&turn_id, &model).await {
+ self.host
+ .interrupt(
+ &turn_id,
+ EventMsg::GuardianWarning(WarningEvent { message }),
+ )
+ .await;
+ }
+ } else {
+ denials.record_non_denial(&turn_id).await;
+ }
+ }
+ completed.decision
})
}
}