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
+214
-213
No files matched your search
@@ -132,18 +132,23 @@ pub(crate) async fn decide_approval(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let runtime = codex_guardian_reviewer::SynchronousReview::new(ReviewRuntime {
|
let runtime = codex_guardian_reviewer::SynchronousReview {
|
||||||
|
host: ReviewRuntime {
|
||||||
session: Arc::clone(&session),
|
session: Arc::clone(&session),
|
||||||
history_reset: history_reset.clone(),
|
history_reset: history_reset.clone(),
|
||||||
context: context.clone(),
|
context: context.clone(),
|
||||||
review_id: review_id.clone(),
|
review_id: review_id.clone(),
|
||||||
request: request.clone(),
|
request: request.clone(),
|
||||||
reasons,
|
reasons,
|
||||||
options: GuardianReviewOptions {
|
options,
|
||||||
require_guardian,
|
|
||||||
..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 {
|
let input = ApprovalDecisionInput {
|
||||||
approval_id: &review_id,
|
approval_id: &review_id,
|
||||||
tool_call_id: request
|
tool_call_id: request
|
||||||
|
|||||||
@@ -53,8 +53,6 @@ pub(crate) use prompt::guardian_truncate_text;
|
|||||||
pub(crate) use review::GuardianReviewOptions;
|
pub(crate) use review::GuardianReviewOptions;
|
||||||
pub(crate) use review::is_basic_session_source;
|
pub(crate) use review::is_basic_session_source;
|
||||||
pub(crate) use review::new_guardian_review_id;
|
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(crate) use review::routes_approval_policy_to_guardian;
|
||||||
pub use review_session::GuardianReviewSession;
|
pub use review_session::GuardianReviewSession;
|
||||||
pub(crate) use review_session::GuardianReviewSessionManager;
|
pub(crate) use review_session::GuardianReviewSessionManager;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Supplies host review preparation, interruption and runtime configuration.
|
//! Supplies host review preparation and context-dependent configuration.
|
||||||
//! Guardian's extension owns the synchronous review loop and pool.
|
//! Guardian's extension owns execution, reporting and denial accounting.
|
||||||
|
|
||||||
#[path = "review_request.rs"]
|
#[path = "review_request.rs"]
|
||||||
mod request;
|
mod request;
|
||||||
@@ -8,7 +8,6 @@ use crate::context::GuardianContextMode;
|
|||||||
use codex_analytics::GuardianApprovalRequestSource;
|
use codex_analytics::GuardianApprovalRequestSource;
|
||||||
use codex_analytics::GuardianReviewAnalyticsResult;
|
use codex_analytics::GuardianReviewAnalyticsResult;
|
||||||
use codex_core_plugins::PluginCommandAttribution;
|
use codex_core_plugins::PluginCommandAttribution;
|
||||||
use codex_extension_api::ThreadIdleCause;
|
|
||||||
use codex_features::Feature;
|
use codex_features::Feature;
|
||||||
use codex_guardian_reviewer::GuardianReviewError;
|
use codex_guardian_reviewer::GuardianReviewError;
|
||||||
use codex_guardian_reviewer::GuardianReviewOutcome;
|
use codex_guardian_reviewer::GuardianReviewOutcome;
|
||||||
@@ -21,8 +20,6 @@ use codex_protocol::protocol::InternalSessionSource;
|
|||||||
use codex_protocol::protocol::ReviewDecision;
|
use codex_protocol::protocol::ReviewDecision;
|
||||||
use codex_protocol::protocol::SessionSource;
|
use codex_protocol::protocol::SessionSource;
|
||||||
use codex_protocol::protocol::SubAgentSource;
|
use codex_protocol::protocol::SubAgentSource;
|
||||||
use codex_protocol::protocol::TurnAbortReason;
|
|
||||||
use codex_protocol::protocol::WarningEvent;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
@@ -31,8 +28,6 @@ use tokio_util::sync::CancellationToken;
|
|||||||
use crate::context::GuardianNodeReplPolicy;
|
use crate::context::GuardianNodeReplPolicy;
|
||||||
use crate::context::GuardianReviewEvidence;
|
use crate::context::GuardianReviewEvidence;
|
||||||
use crate::session::session::Session;
|
use crate::session::session::Session;
|
||||||
use crate::session::turn_context::TurnContext;
|
|
||||||
use crate::turn_timing::now_unix_timestamp_ms;
|
|
||||||
|
|
||||||
use super::ApprovalRequestReasons;
|
use super::ApprovalRequestReasons;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -134,56 +129,6 @@ pub(super) async fn record_guardian_non_denial(session: &Arc<Session>) {
|
|||||||
.await;
|
.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)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct GuardianReviewOptions {
|
pub(crate) struct GuardianReviewOptions {
|
||||||
/// Requires Guardian rather than a manual approval; cached evidence may still satisfy it.
|
/// 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.
|
//! Captures a review on the host's original action and authorization state.
|
||||||
//! Guardian's extension owns orchestration; this adapter preserves event and evidence behavior.
|
//! The extension chooses effects; this adapter supplies evidence, validation and publication.
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::codex_thread::GuardianAuthorizationVersion;
|
use crate::codex_thread::GuardianAuthorizationVersion;
|
||||||
@@ -8,8 +8,6 @@ use codex_protocol::approvals::GuardianReviewReason;
|
|||||||
|
|
||||||
pub(in crate::guardian) struct PreparedApproval {
|
pub(in crate::guardian) struct PreparedApproval {
|
||||||
request: GuardianApprovalRequest,
|
request: GuardianApprovalRequest,
|
||||||
turn: Arc<TurnContext>,
|
|
||||||
report: codex_guardian_reviewer::ReviewReport,
|
|
||||||
root_authorization_version: Option<GuardianAuthorizationVersion>,
|
root_authorization_version: Option<GuardianAuthorizationVersion>,
|
||||||
user_message_revision: u64,
|
user_message_revision: u64,
|
||||||
review_evidence: Option<(
|
review_evidence: Option<(
|
||||||
@@ -27,11 +25,19 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
self.options.external_cancel.as_ref()
|
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(
|
async fn prepare(
|
||||||
&self,
|
&self,
|
||||||
review_reason: GuardianReviewReason,
|
review_reason: GuardianReviewReason,
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
) -> Result<PreparedApproval, ReviewDecision> {
|
) -> Result<(PreparedApproval, codex_guardian_reviewer::ReviewReport), ReviewDecision> {
|
||||||
let super::super::runtime::ReviewRuntime {
|
let super::super::runtime::ReviewRuntime {
|
||||||
session,
|
session,
|
||||||
history_reset: _,
|
history_reset: _,
|
||||||
@@ -105,37 +111,6 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
review_reason,
|
review_reason,
|
||||||
model_context,
|
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
|
let root_authorization_version = session
|
||||||
.services
|
.services
|
||||||
.agent_control
|
.agent_control
|
||||||
@@ -163,14 +138,15 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
drop(history);
|
drop(history);
|
||||||
Ok(PreparedApproval {
|
Ok((
|
||||||
|
PreparedApproval {
|
||||||
request,
|
request,
|
||||||
turn,
|
|
||||||
report,
|
|
||||||
root_authorization_version,
|
root_authorization_version,
|
||||||
user_message_revision,
|
user_message_revision,
|
||||||
review_evidence,
|
review_evidence,
|
||||||
})
|
},
|
||||||
|
report,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn attempt(
|
async fn attempt(
|
||||||
@@ -178,7 +154,7 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
prepared: &PreparedApproval,
|
prepared: &PreparedApproval,
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
|
) -> (GuardianReviewOutcome, GuardianReviewAnalyticsResult) {
|
||||||
run_guardian_review_session_before_deadline(
|
let (mut outcome, analytics) = run_guardian_review_session_before_deadline(
|
||||||
Arc::clone(&self.session),
|
Arc::clone(&self.session),
|
||||||
self.context.clone(),
|
self.context.clone(),
|
||||||
prepared.request.clone(),
|
prepared.request.clone(),
|
||||||
@@ -187,24 +163,10 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
self.options.external_cancel.clone(),
|
self.options.external_cancel.clone(),
|
||||||
deadline,
|
deadline,
|
||||||
)
|
)
|
||||||
.await
|
.await;
|
||||||
}
|
let session = &self.session;
|
||||||
|
let root_authorization_version = prepared.root_authorization_version;
|
||||||
async fn complete(
|
let user_message_revision = prepared.user_message_revision;
|
||||||
&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);
|
|
||||||
if matches!(&outcome, GuardianReviewOutcome::Completed(assessment) if assessment.outcome == GuardianAssessmentOutcome::Allow)
|
if matches!(&outcome, GuardianReviewOutcome::Completed(assessment) if assessment.outcome == GuardianAssessmentOutcome::Allow)
|
||||||
&& ((session.guardian_context_mode == GuardianContextMode::ThreadOwned
|
&& ((session.guardian_context_mode == GuardianContextMode::ThreadOwned
|
||||||
&& (root_authorization_version
|
&& (root_authorization_version
|
||||||
@@ -231,47 +193,33 @@ impl ReviewHost for super::super::runtime::ReviewRuntime {
|
|||||||
outcome = GuardianReviewOutcome::Error(GuardianReviewError::Cancelled);
|
outcome = GuardianReviewOutcome::Error(GuardianReviewError::Cancelled);
|
||||||
}
|
}
|
||||||
|
|
||||||
let completed_at_ms = now_unix_timestamp_ms();
|
(outcome, analytics)
|
||||||
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)) =
|
async fn emit(&self, event: EventMsg) {
|
||||||
review_evidence
|
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(
|
evidence.record(
|
||||||
&completed.event,
|
event,
|
||||||
&action,
|
action,
|
||||||
authorization_version,
|
*authorization_version,
|
||||||
root_authorization_version,
|
*root_authorization_version,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
session
|
|
||||||
.send_event(turn.as_ref(), EventMsg::GuardianAssessment(completed.event))
|
|
||||||
.await;
|
|
||||||
if completed.assessment_outcome == Some(GuardianAssessmentOutcome::Deny) {
|
|
||||||
record_guardian_denial(&session).await;
|
|
||||||
} else {
|
|
||||||
record_guardian_non_denial(&session).await;
|
|
||||||
}
|
}
|
||||||
completed.decision
|
|
||||||
|
async fn interrupt(&self, turn_id: &str, warning: EventMsg) {
|
||||||
|
self.session
|
||||||
|
.interrupt_turn_with_warning(turn_id, warning)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
mod code_mode_warning;
|
||||||
pub(crate) mod context_window;
|
pub(crate) mod context_window;
|
||||||
mod environment;
|
mod environment;
|
||||||
|
mod extension_interruption;
|
||||||
pub(crate) mod extension_metrics;
|
pub(crate) mod extension_metrics;
|
||||||
mod handlers;
|
mod handlers;
|
||||||
mod inject;
|
mod inject;
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ fn check_legacy_model_safety(
|
|||||||
return Err("the destination model has only fallback metadata".to_string());
|
return Err("the destination model has only fallback metadata".to_string());
|
||||||
}
|
}
|
||||||
let retained_models = [admitted, current];
|
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.
|
// policy from the admitted model's Cyber classification.
|
||||||
let destination_is_cyber =
|
let destination_is_cyber =
|
||||||
destination.model_specialty.as_deref() == Some(MODEL_SPECIALTY_CYBER);
|
destination.model_specialty.as_deref() == Some(MODEL_SPECIALTY_CYBER);
|
||||||
|
|||||||
@@ -10604,27 +10604,32 @@ impl SessionTask for NeverEndingTask {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
struct GuardianDeniedApprovalTask;
|
struct ExtensionInterruptedTask;
|
||||||
|
|
||||||
impl SessionTask for GuardianDeniedApprovalTask {
|
impl SessionTask for ExtensionInterruptedTask {
|
||||||
fn kind(&self) -> TaskKind {
|
fn kind(&self) -> TaskKind {
|
||||||
TaskKind::Regular
|
TaskKind::Regular
|
||||||
}
|
}
|
||||||
|
|
||||||
fn span_name(&self) -> &'static str {
|
fn span_name(&self) -> &'static str {
|
||||||
"session_task.guardian_denied_approval"
|
"session_task.extension_interrupted"
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run(
|
async fn run(
|
||||||
self: Arc<Self>,
|
self: Arc<Self>,
|
||||||
session: Arc<Session>,
|
session: Arc<Session>,
|
||||||
_ctx: Arc<TurnContext>,
|
ctx: Arc<TurnContext>,
|
||||||
_input: Vec<TurnInput>,
|
_input: Vec<TurnInput>,
|
||||||
cancellation_token: CancellationToken,
|
cancellation_token: CancellationToken,
|
||||||
) -> SessionTaskResult {
|
) -> SessionTaskResult {
|
||||||
for _ in 0..3 {
|
session
|
||||||
crate::guardian::record_guardian_denial_for_test(&session).await;
|
.interrupt_turn_with_warning(
|
||||||
}
|
&ctx.sub_id,
|
||||||
|
EventMsg::Warning(codex_protocol::protocol::WarningEvent {
|
||||||
|
message: "extension interrupted this turn".into(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
cancellation_token.cancelled().await;
|
cancellation_token.cancelled().await;
|
||||||
Ok(None)
|
Ok(None)
|
||||||
@@ -10938,7 +10943,7 @@ async fn interrupting_compaction_fallback_retains_last_known_step_context() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
#[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<()>);
|
struct ThreadIdleRecorder(async_channel::Sender<()>);
|
||||||
|
|
||||||
impl codex_extension_api::ThreadLifecycleContributor<crate::config::Config> for ThreadIdleRecorder {
|
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());
|
session.services.extensions = Arc::new(builder.build());
|
||||||
|
|
||||||
Arc::new(session)
|
Arc::new(session)
|
||||||
.spawn_task(
|
.spawn_task(Arc::new(turn_context), Vec::new(), ExtensionInterruptedTask)
|
||||||
Arc::new(turn_context),
|
|
||||||
Vec::new(),
|
|
||||||
GuardianDeniedApprovalTask,
|
|
||||||
)
|
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
timeout(StdDuration::from_secs(5), idle_rx.recv())
|
timeout(StdDuration::from_secs(5), idle_rx.recv())
|
||||||
.await
|
.await
|
||||||
.expect("guardian interrupt should emit thread idle lifecycle")
|
.expect("extension interrupt should emit thread idle lifecycle")
|
||||||
.expect("idle receiver open");
|
.expect("idle receiver open");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
#[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 (sess, tc, rx) = make_session_and_context_with_rx().await;
|
||||||
let input = vec![TurnInput::UserInput {
|
let input = vec![TurnInput::UserInput {
|
||||||
acceptance_order: None,
|
acceptance_order: None,
|
||||||
content: vec![UserInput::Text {
|
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(),
|
text_elements: Vec::new(),
|
||||||
}],
|
}],
|
||||||
client_id: None,
|
client_id: None,
|
||||||
@@ -11000,9 +11001,14 @@ async fn guardian_helper_review_interrupts_after_three_consecutive_denials() {
|
|||||||
.build()
|
.build()
|
||||||
.expect("helper review runtime");
|
.expect("helper review runtime");
|
||||||
runtime.block_on(async move {
|
runtime.block_on(async move {
|
||||||
for _ in 0..3 {
|
session_for_review
|
||||||
crate::guardian::record_guardian_denial_for_test(&session_for_review).await;
|
.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");
|
review_thread.join().expect("helper review thread");
|
||||||
@@ -11021,9 +11027,7 @@ async fn guardian_helper_review_interrupts_after_three_consecutive_denials() {
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| {
|
.unwrap_or_else(|_| {
|
||||||
panic!(
|
panic!("extension should interrupt the turn; observed events: {observed:?}")
|
||||||
"helper review circuit breaker should interrupt the turn; observed events: {observed:?}"
|
|
||||||
)
|
|
||||||
});
|
});
|
||||||
assert_eq!(aborted.reason, TurnAbortReason::Interrupted);
|
assert_eq!(aborted.reason, TurnAbortReason::Interrupted);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,74 +1,139 @@
|
|||||||
//! Orchestrates one synchronous approval review over a host-bound action.
|
//! Owns synchronous review orchestration, reporting and outcome accounting.
|
||||||
//! All callers share this policy; the host captures evidence and enforces the result.
|
//! The host binds the original action, captures evidence and enforces authorization.
|
||||||
|
|
||||||
use std::future::Future;
|
|
||||||
|
|
||||||
|
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_analytics::GuardianReviewAnalyticsResult;
|
||||||
|
use codex_extension_api::ExtensionData;
|
||||||
use codex_extension_api::ExtensionFuture;
|
use codex_extension_api::ExtensionFuture;
|
||||||
use codex_extension_api::SynchronousApprovalReviewer;
|
use codex_extension_api::SynchronousApprovalReviewer;
|
||||||
|
use codex_otel::SessionTelemetry;
|
||||||
use codex_protocol::approvals::GuardianReviewReason;
|
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::ReviewDecision;
|
||||||
|
use codex_protocol::protocol::WarningEvent;
|
||||||
|
use std::future::Future;
|
||||||
|
use std::sync::Arc;
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
use crate::GuardianReviewOutcome;
|
/// Operations bound to one immutable action and its issuing context.
|
||||||
use crate::GuardianReviewSessionLimits;
|
/// Hosts validate authority, publish supplied events and interrupt only the selected turn;
|
||||||
|
/// they do not select Guardian outcomes, retry policy or reporting effects.
|
||||||
/// 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.
|
|
||||||
pub trait ReviewHost: Send + Sync {
|
pub trait ReviewHost: Send + Sync {
|
||||||
type Prepared: Send + Sync;
|
type Prepared: Send + Sync;
|
||||||
|
|
||||||
fn cancellation(&self) -> Option<&CancellationToken>;
|
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(
|
fn prepare(
|
||||||
&self,
|
&self,
|
||||||
reason: GuardianReviewReason,
|
reason: GuardianReviewReason,
|
||||||
deadline: Instant,
|
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(
|
fn attempt(
|
||||||
&self,
|
&self,
|
||||||
prepared: &Self::Prepared,
|
prepared: &Self::Prepared,
|
||||||
deadline: Instant,
|
deadline: Instant,
|
||||||
) -> impl Future<Output = (GuardianReviewOutcome, GuardianReviewAnalyticsResult)> + Send;
|
) -> impl Future<Output = (GuardianReviewOutcome, GuardianReviewAnalyticsResult)> + Send;
|
||||||
fn complete(
|
fn emit(&self, event: EventMsg) -> impl Future<Output = ()> + Send;
|
||||||
|
fn record_evidence(
|
||||||
&self,
|
&self,
|
||||||
prepared: Self::Prepared,
|
prepared: &Self::Prepared,
|
||||||
outcome: GuardianReviewOutcome,
|
event: &GuardianAssessmentEvent,
|
||||||
analytics: GuardianReviewAnalyticsResult,
|
) -> impl Future<Output = ()> + Send;
|
||||||
) -> impl Future<Output = Option<ReviewDecision>> + 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.
|
/// One review bound by the host before Guardian's approval policy chooses to run it.
|
||||||
pub struct SynchronousReview<H> {
|
pub struct SynchronousReview<'a, H> {
|
||||||
host: 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> {
|
impl<H: ReviewHost> SynchronousApprovalReviewer for SynchronousReview<'_, H> {
|
||||||
pub fn new(host: H) -> Self {
|
|
||||||
Self { host }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<H: ReviewHost> SynchronousApprovalReviewer for SynchronousReview<H> {
|
|
||||||
fn review(&self, reason: GuardianReviewReason) -> ExtensionFuture<'_, Option<ReviewDecision>> {
|
fn review(&self, reason: GuardianReviewReason) -> ExtensionFuture<'_, Option<ReviewDecision>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let deadline = Instant::now() + crate::REVIEW_TIMEOUT;
|
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,
|
Ok(prepared) => prepared,
|
||||||
Err(decision) => return Some(decision),
|
Err(decision) => return Some(decision),
|
||||||
};
|
};
|
||||||
let (outcome, analytics) = Box::pin(crate::run_with_retry(
|
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 {
|
GuardianReviewSessionLimits {
|
||||||
max_attempts: crate::MAX_REVIEW_ATTEMPTS,
|
max_attempts: crate::MAX_REVIEW_ATTEMPTS,
|
||||||
deadline,
|
deadline,
|
||||||
},
|
},
|
||||||
self.host.cancellation(),
|
self.host.cancellation(),
|
||||||
|deadline| self.host.attempt(&prepared, deadline),
|
|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;
|
.await;
|
||||||
self.host.complete(prepared, outcome, analytics).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
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user