mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Move Guardian review reporting and denial accounting into the extension (#45677)
## What changed - Make `SynchronousReview` own assessment events, telemetry, warnings, evidence-recording decisions, and consecutive-denial accounting. - Keep action preparation, stale-approval validation, evidence storage, and event publication in the host adapter. - Extract `Session::interrupt_turn_with_warning` to apply extension-requested interruptions to the selected active turn and emit the interrupted thread-idle lifecycle event. ## Testing Adapt session tests to verify that extension interruptions emit the thread-idle lifecycle event and survive shutdown of the calling runtime. GitOrigin-RevId: b234ad86206fedc2434f48fc44dc57679443c69f
This commit is contained in:
1 parent
40f01fbe08
commit
0265dd7b45
9 files changed
+231
-230
No files matched your search
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user