mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Add opt-in synchronous Guardian review for native tool calls (#57433)
## What changed - Add `CoreToolRuntime::requires_guardian_review` to review opted-in function calls before dispatch and stop execution when review rejects the call. - Deliver proposed calls as native review evidence, preserving encrypted argument metadata. When hooks rewrite arguments, review the updated arguments and discard the original encrypted replay content. - Deduplicate native call evidence against reviewer history and include paired evidence outputs in input budgets. - Keep review accounting and metrics for native calls without emitting action-specific client assessment events, and omit approval payloads from debug output. ## Testing Extend regression coverage for rewritten native calls across review retries, denied calls that never execute their handlers, oversized native evidence, and review metrics without client events. GitOrigin-RevId: c3b22c0220344581c2b38f233001abaed49cba34
This commit is contained in:
@@ -28,7 +28,8 @@ const INPUT_BUDGET_MESSAGE: &str =
|
||||
pub struct ReviewCompletion {
|
||||
/// `None` requests user approval after optional review exhausts its input budget.
|
||||
pub decision: Option<ReviewDecision>,
|
||||
pub event: GuardianAssessmentEvent,
|
||||
/// Absent for actions reviewed without an action-specific client report.
|
||||
pub event: Option<GuardianAssessmentEvent>,
|
||||
pub warning: Option<String>,
|
||||
pub analytics: GuardianReviewAnalyticsResult,
|
||||
/// Only completed assessments may enter the evidence cache or count as policy denials.
|
||||
@@ -39,7 +40,7 @@ pub fn complete_review(
|
||||
outcome: GuardianReviewOutcome,
|
||||
model: &ModelInfo,
|
||||
require_guardian: bool,
|
||||
mut event: GuardianAssessmentEvent,
|
||||
mut event: Option<GuardianAssessmentEvent>,
|
||||
mut analytics: GuardianReviewAnalyticsResult,
|
||||
) -> ReviewCompletion {
|
||||
let completed_assessment = match &outcome {
|
||||
@@ -48,9 +49,11 @@ pub fn complete_review(
|
||||
};
|
||||
let assessment = match outcome {
|
||||
GuardianReviewOutcome::CachedApproval => {
|
||||
event.status = GuardianAssessmentStatus::Approved;
|
||||
event.decision_source = None;
|
||||
event.rationale = Some("Approved using a current low-risk async score.".to_owned());
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Approved;
|
||||
event.decision_source = None;
|
||||
event.rationale = Some("Approved using a current low-risk async score.".to_owned());
|
||||
}
|
||||
analytics.decision = GuardianReviewDecision::Approved;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Approved;
|
||||
analytics.failure_reason = None;
|
||||
@@ -88,8 +91,10 @@ pub fn complete_review(
|
||||
format!("Automatic approval review failed: {INPUT_BUDGET_MESSAGE}");
|
||||
analytics.decision = GuardianReviewDecision::Aborted;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
event.rationale = Some(rationale.clone());
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
event.rationale = Some(rationale.clone());
|
||||
}
|
||||
return ReviewCompletion {
|
||||
decision: None,
|
||||
event,
|
||||
@@ -102,8 +107,10 @@ pub fn complete_review(
|
||||
let rationale = "Automatic approval review timed out while evaluating the requested approval.".to_string();
|
||||
analytics.decision = GuardianReviewDecision::Denied;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::TimedOut;
|
||||
event.status = GuardianAssessmentStatus::TimedOut;
|
||||
event.rationale = Some(rationale.clone());
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::TimedOut;
|
||||
event.rationale = Some(rationale.clone());
|
||||
}
|
||||
return ReviewCompletion {
|
||||
decision: Some(ReviewDecision::TimedOut),
|
||||
event,
|
||||
@@ -115,7 +122,9 @@ pub fn complete_review(
|
||||
GuardianReviewError::Cancelled => {
|
||||
analytics.decision = GuardianReviewDecision::Aborted;
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::Aborted;
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Aborted;
|
||||
}
|
||||
return ReviewCompletion {
|
||||
decision: Some(ReviewDecision::Abort),
|
||||
event,
|
||||
@@ -145,8 +154,10 @@ pub fn complete_review(
|
||||
analytics.terminal_status = GuardianReviewTerminalStatus::FailedClosed;
|
||||
let rationale = format!("Automatic approval review failed: {message}");
|
||||
// Keep the existing blocked status for client compatibility.
|
||||
event.status = GuardianAssessmentStatus::Denied;
|
||||
event.rationale = Some(rationale.clone());
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = GuardianAssessmentStatus::Denied;
|
||||
event.rationale = Some(rationale.clone());
|
||||
}
|
||||
return ReviewCompletion {
|
||||
decision: Some(ReviewDecision::denied(format!(
|
||||
"{rationale}\n{REVIEW_FAILURE_INSTRUCTIONS}"
|
||||
@@ -178,14 +189,16 @@ pub fn complete_review(
|
||||
"Automatic approval review {verdict} (risk: {risk}, authorization: {authorization}): {}",
|
||||
assessment.rationale
|
||||
);
|
||||
event.status = if approved {
|
||||
GuardianAssessmentStatus::Approved
|
||||
} else {
|
||||
GuardianAssessmentStatus::Denied
|
||||
};
|
||||
event.risk_level = Some(assessment.risk_level);
|
||||
event.user_authorization = Some(assessment.user_authorization);
|
||||
event.rationale = Some(assessment.rationale.clone());
|
||||
if let Some(event) = event.as_mut() {
|
||||
event.status = if approved {
|
||||
GuardianAssessmentStatus::Approved
|
||||
} else {
|
||||
GuardianAssessmentStatus::Denied
|
||||
};
|
||||
event.risk_level = Some(assessment.risk_level);
|
||||
event.user_authorization = Some(assessment.user_authorization);
|
||||
event.rationale = Some(assessment.rationale.clone());
|
||||
}
|
||||
let decision = if approved {
|
||||
ReviewDecision::Approved
|
||||
} else {
|
||||
|
||||
@@ -216,6 +216,7 @@ fn approval_request_source_tag(source: GuardianApprovalRequestSource) -> &'stati
|
||||
|
||||
fn reviewed_action_tag(action: &GuardianReviewedAction) -> &'static str {
|
||||
match action {
|
||||
GuardianReviewedAction::NativeToolCall {} => "native_tool_call",
|
||||
GuardianReviewedAction::Shell { .. } => "shell",
|
||||
GuardianReviewedAction::UnifiedExec { .. } => "unified_exec",
|
||||
GuardianReviewedAction::WriteStdin { .. } => "write_stdin",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Owns review reporting and the per-thread denial window. The host publishes
|
||||
//! events and enforces interruption only on the still-active owning turn. Review
|
||||
//! events and enforces interruption only on the still-active owning turn.
|
||||
//! Internal accounting runs even when no client event is available. Review
|
||||
//! completion captures one monotonic duration for latency reporting while retaining
|
||||
//! the actual wall-clock completion timestamp for event ordering.
|
||||
|
||||
@@ -39,7 +40,8 @@ pub struct ReviewMetadata {
|
||||
pub script_path: Option<String>,
|
||||
pub approval_request_source: GuardianApprovalRequestSource,
|
||||
pub reviewed_action: GuardianReviewedAction,
|
||||
pub action: GuardianAssessmentAction,
|
||||
/// Absent when the action has no client-facing representation.
|
||||
pub action: Option<GuardianAssessmentAction>,
|
||||
pub review_reason: GuardianReviewReason,
|
||||
pub model_context: ModelInvocationContext,
|
||||
/// Configured review budget; None is reported as zero (unlimited).
|
||||
@@ -47,7 +49,7 @@ pub struct ReviewMetadata {
|
||||
}
|
||||
|
||||
pub struct ReviewReport {
|
||||
started: GuardianAssessmentEvent,
|
||||
started: Option<GuardianAssessmentEvent>,
|
||||
started_instant: Instant,
|
||||
tracking: GuardianReviewTrackContext,
|
||||
approval_request_source: GuardianApprovalRequestSource,
|
||||
@@ -68,7 +70,7 @@ impl ReviewReport {
|
||||
.timeout
|
||||
.map_or(0, |timeout| timeout.as_millis() as u64),
|
||||
);
|
||||
let started = GuardianAssessmentEvent {
|
||||
let started = metadata.action.map(|action| GuardianAssessmentEvent {
|
||||
review_reason: Some(metadata.review_reason),
|
||||
model_context: Some(metadata.model_context),
|
||||
id: metadata.review_id,
|
||||
@@ -83,8 +85,8 @@ impl ReviewReport {
|
||||
user_authorization: None,
|
||||
rationale: None,
|
||||
decision_source: None,
|
||||
action: metadata.action,
|
||||
};
|
||||
action,
|
||||
});
|
||||
Self {
|
||||
started,
|
||||
started_instant,
|
||||
@@ -94,11 +96,7 @@ impl ReviewReport {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn turn_id(&self) -> &str {
|
||||
&self.started.turn_id
|
||||
}
|
||||
|
||||
pub fn started_event(&self) -> GuardianAssessmentEvent {
|
||||
pub fn started_event(&self) -> Option<GuardianAssessmentEvent> {
|
||||
self.started.clone()
|
||||
}
|
||||
|
||||
@@ -113,8 +111,10 @@ impl ReviewReport {
|
||||
) -> (ReviewCompletion, Duration) {
|
||||
let elapsed = self.started_instant.elapsed();
|
||||
let mut event = self.started.clone();
|
||||
event.completed_at_ms = Some(completed_at_ms);
|
||||
event.decision_source = Some(GuardianAssessmentDecisionSource::Agent);
|
||||
if let Some(event) = &mut event {
|
||||
event.completed_at_ms = Some(completed_at_ms);
|
||||
event.decision_source = Some(GuardianAssessmentDecisionSource::Agent);
|
||||
}
|
||||
(
|
||||
crate::complete_review(outcome, model, require_guardian, event, analytics),
|
||||
elapsed,
|
||||
|
||||
@@ -1,22 +1,40 @@
|
||||
//! Regression coverage for capturing one review interval despite wall-clock skew.
|
||||
//! Review accounting with and without client events, including wall-clock skew.
|
||||
|
||||
use super::*;
|
||||
use codex_otel::GUARDIAN_REVIEW_COUNT_METRIC;
|
||||
use codex_otel::GUARDIAN_REVIEW_DURATION_METRIC;
|
||||
use codex_otel::GUARDIAN_REVIEW_TOKEN_USAGE_METRIC;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::TokenUsage;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::Metric;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn review_completion_uses_one_monotonic_duration() {
|
||||
#[test_case::test_case(
|
||||
Some(GuardianAssessmentAction::NetworkAccess {
|
||||
target: "example.com".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
port: 443,
|
||||
}),
|
||||
GuardianReviewedAction::NetworkAccess { protocol: NetworkApprovalProtocol::Https, port: 443 };
|
||||
"with client event"
|
||||
)]
|
||||
#[test_case::test_case(None, GuardianReviewedAction::NativeToolCall {}; "without client event")]
|
||||
fn review_completion_uses_one_monotonic_duration(
|
||||
action: Option<GuardianAssessmentAction>,
|
||||
reviewed_action: GuardianReviewedAction,
|
||||
) {
|
||||
let has_client_event = action.is_some();
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
let metrics = MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "codex-core", env!("CARGO_PKG_VERSION"), exporter)
|
||||
@@ -44,16 +62,8 @@ fn review_completion_uses_one_monotonic_duration() {
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
reviewed_action: GuardianReviewedAction::NetworkAccess {
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
port: 443,
|
||||
},
|
||||
action: GuardianAssessmentAction::NetworkAccess {
|
||||
target: "example.com".to_string(),
|
||||
host: "example.com".to_string(),
|
||||
protocol: NetworkApprovalProtocol::Https,
|
||||
port: 443,
|
||||
},
|
||||
reviewed_action,
|
||||
action,
|
||||
review_reason: GuardianReviewReason::Policy,
|
||||
timeout: Some(crate::REVIEW_TIMEOUT),
|
||||
model_context: ModelInvocationContext {
|
||||
@@ -62,8 +72,11 @@ fn review_completion_uses_one_monotonic_duration() {
|
||||
},
|
||||
});
|
||||
report.tracking.started_at_ms = 1_654_073_807_000;
|
||||
report.started.started_at_ms =
|
||||
i64::try_from(report.tracking.started_at_ms).expect("start timestamp");
|
||||
if let Some(event) = &mut report.started {
|
||||
event.started_at_ms =
|
||||
i64::try_from(report.tracking.started_at_ms).expect("start timestamp");
|
||||
}
|
||||
assert_eq!(report.started_event().is_some(), has_client_event);
|
||||
report.started_instant = Instant::now() - Duration::from_millis(456);
|
||||
let model: ModelInfo = serde_json::from_value(json!({
|
||||
"slug": "test-model",
|
||||
@@ -81,21 +94,29 @@ fn review_completion_uses_one_monotonic_duration() {
|
||||
|
||||
let before = report.started_instant.elapsed();
|
||||
let (completed, elapsed) = report.complete(
|
||||
GuardianReviewOutcome::CachedApproval,
|
||||
GuardianReviewOutcome::Error(crate::GuardianReviewError::Timeout),
|
||||
&model,
|
||||
/*require_guardian*/ true,
|
||||
GuardianReviewAnalyticsResult::without_session(),
|
||||
GuardianReviewAnalyticsResult {
|
||||
attempt_count: 2,
|
||||
token_usage: Some(TokenUsage {
|
||||
input_tokens: 10,
|
||||
total_tokens: 10,
|
||||
..Default::default()
|
||||
}),
|
||||
..GuardianReviewAnalyticsResult::without_session()
|
||||
},
|
||||
/*completed_at_ms*/ 1_792_141_011_000,
|
||||
);
|
||||
let after = report.started_instant.elapsed();
|
||||
assert!((before..=after).contains(&elapsed));
|
||||
let elapsed_ms = u64::try_from(elapsed.as_millis()).expect("elapsed milliseconds");
|
||||
assert_eq!(
|
||||
(
|
||||
completed.event.started_at_ms,
|
||||
completed.event.completed_at_ms
|
||||
),
|
||||
(1_654_073_807_000, Some(1_792_141_011_000),)
|
||||
completed
|
||||
.event
|
||||
.as_ref()
|
||||
.map(|event| (event.started_at_ms, event.completed_at_ms)),
|
||||
has_client_event.then_some((1_654_073_807_000, Some(1_792_141_011_000)))
|
||||
);
|
||||
|
||||
// Simulate tracking later: the captured interval must not be measured again.
|
||||
@@ -109,6 +130,20 @@ fn review_completion_uses_one_monotonic_duration() {
|
||||
);
|
||||
|
||||
let snapshot = telemetry.snapshot_metrics().expect("metrics snapshot");
|
||||
let names = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.map(Metric::name)
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
for name in [
|
||||
GUARDIAN_REVIEW_COUNT_METRIC,
|
||||
GUARDIAN_REVIEW_DURATION_METRIC,
|
||||
GUARDIAN_REVIEW_TOKEN_USAGE_METRIC,
|
||||
"codex.guardian.review.attempt_count",
|
||||
"codex.guardian.review.retry_outcome",
|
||||
] {
|
||||
assert!(names.contains(name), "missing {name}");
|
||||
}
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
|
||||
@@ -42,6 +42,7 @@ pub trait ReviewHost: Clone + Send + Sync + 'static {
|
||||
fn servicing_turn(&self) -> impl Future<Output = Option<(String, Arc<ModelInfo>)>> + Send;
|
||||
/// Returns the owning turn and optional target item after validating the action.
|
||||
fn validate_action(&self) -> Result<(&str, Option<&str>), ReviewDecision>;
|
||||
/// Prepares evidence and accounting, with a client event only for supported actions.
|
||||
fn prepare(
|
||||
&self,
|
||||
approval_id: &str,
|
||||
@@ -115,9 +116,9 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
Ok(prepared) => prepared,
|
||||
Err(decision) => return Some(decision),
|
||||
};
|
||||
self.host
|
||||
.emit(EventMsg::GuardianAssessment(report.started_event()))
|
||||
.await;
|
||||
if let Some(event) = report.started_event() {
|
||||
self.host.emit(EventMsg::GuardianAssessment(event)).await;
|
||||
}
|
||||
let prepared = Arc::new(prepared);
|
||||
let cancellation = self.cancellation.child_token();
|
||||
let attempts = Arc::new(AtomicI64::new(/*v*/ 0));
|
||||
@@ -186,9 +187,12 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
analytics,
|
||||
completed_at_ms.try_into().unwrap_or_default(),
|
||||
);
|
||||
if self.log_assessments && !cached_approval {
|
||||
if self.log_assessments
|
||||
&& !cached_approval
|
||||
&& let Some(event) = &completed.event
|
||||
{
|
||||
self.telemetry
|
||||
.guardian_assessment(&completed.event, completed.assessment_outcome);
|
||||
.guardian_assessment(event, completed.assessment_outcome);
|
||||
}
|
||||
report.track(
|
||||
self.telemetry,
|
||||
@@ -204,14 +208,13 @@ impl<H: ReviewHost> SynchronousApprovalReviewer for ReviewRequest<'_, H> {
|
||||
}
|
||||
if completed.assessment_outcome.is_some()
|
||||
&& let Some(evidence) = evidence
|
||||
&& let Some(event) = &completed.event
|
||||
{
|
||||
self.host
|
||||
.record_evidence(&prepared, evidence, &completed.event)
|
||||
.await;
|
||||
self.host.record_evidence(&prepared, evidence, event).await;
|
||||
}
|
||||
if let Some(event) = completed.event {
|
||||
self.host.emit(EventMsg::GuardianAssessment(event)).await;
|
||||
}
|
||||
self.host
|
||||
.emit(EventMsg::GuardianAssessment(completed.event))
|
||||
.await;
|
||||
if cached_approval {
|
||||
return Some(self.cached_approval().await);
|
||||
}
|
||||
|
||||
@@ -64,10 +64,10 @@ impl ReviewHost for GatedHost {
|
||||
script_path: None,
|
||||
approval_request_source: GuardianApprovalRequestSource::MainTurn,
|
||||
reviewed_action: GuardianReviewedAction::RequestPermissions {},
|
||||
action: GuardianAssessmentAction::RequestPermissions {
|
||||
action: Some(GuardianAssessmentAction::RequestPermissions {
|
||||
reason: None,
|
||||
permissions: Default::default(),
|
||||
},
|
||||
}),
|
||||
review_reason: reason,
|
||||
timeout: Some(crate::REVIEW_TIMEOUT),
|
||||
model_context: ModelInvocationContext {
|
||||
|
||||
@@ -213,9 +213,10 @@ impl Classification {
|
||||
..score_authorization
|
||||
};
|
||||
let action_section = PlannedAction {
|
||||
json: planned_action.clone(),
|
||||
tool_descriptions: None,
|
||||
kind: PlannedActionKind::Command,
|
||||
kind: PlannedActionKind::Command {
|
||||
json: planned_action.clone(),
|
||||
},
|
||||
reason: None,
|
||||
};
|
||||
let review_fragments = sync_reviews
|
||||
|
||||
@@ -34,9 +34,10 @@ impl ConversationHistorySnapshot for History {
|
||||
|
||||
fn collect(history: &History, images: &[ContentItem]) -> CollectedTranscript {
|
||||
let action = PlannedAction {
|
||||
json: r#"{"tool":"read_file","path":"README.md"}"#.to_owned(),
|
||||
tool_descriptions: None,
|
||||
kind: PlannedActionKind::Command,
|
||||
kind: PlannedActionKind::Command {
|
||||
json: r#"{"tool":"read_file","path":"README.md"}"#.to_owned(),
|
||||
},
|
||||
reason: None,
|
||||
};
|
||||
let reviews =
|
||||
|
||||
@@ -190,7 +190,7 @@ impl CollectedTranscript {
|
||||
};
|
||||
let transcript = self.profile.prepare_transcript(entries, offset);
|
||||
let mut context = self.context.compose(presentation, transcript)?;
|
||||
context.retain_new_agent_messages(reviewer_history)?;
|
||||
context.retain_new_native_messages(reviewer_history)?;
|
||||
Ok((context, next))
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user