diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index c871145413..6f5eb2b1d4 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5573,6 +5573,14 @@ dependencies = [ "zbus", ] +[[package]] +name = "codex-turn-milestones" +version = "0.0.0" +dependencies = [ + "codex-protocol", + "pretty_assertions", +] + [[package]] name = "codex-uds" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 7820314824..5808a45c4e 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -119,6 +119,7 @@ members = [ "otel-trace-websocket", "tcp-tunnel", "tui", + "turn-milestones", "user-input", "user-verification", "tool-call-id", diff --git a/codex-rs/turn-milestones/BUILD.bazel b/codex-rs/turn-milestones/BUILD.bazel new file mode 100644 index 0000000000..efa3e20549 --- /dev/null +++ b/codex-rs/turn-milestones/BUILD.bazel @@ -0,0 +1,6 @@ +load("//:defs.bzl", "codex_rust_crate") + +codex_rust_crate( + name = "turn-milestones", + crate_name = "codex_turn_milestones", +) diff --git a/codex-rs/turn-milestones/Cargo.toml b/codex-rs/turn-milestones/Cargo.toml new file mode 100644 index 0000000000..077ba5530d --- /dev/null +++ b/codex-rs/turn-milestones/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "codex-turn-milestones" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[lib] +doctest = false + +[dependencies] +codex-protocol = { workspace = true } + +[dev-dependencies] +pretty_assertions.workspace = true diff --git a/codex-rs/turn-milestones/src/lib.rs b/codex-rs/turn-milestones/src/lib.rs new file mode 100644 index 0000000000..83847657a1 --- /dev/null +++ b/codex-rs/turn-milestones/src/lib.rs @@ -0,0 +1,173 @@ +//! One optional watch per milestone source on a turn. The caller evaluates a +//! predicate before taking its timing lock, claims the watch while freezing +//! the snapshot, and delivers the owned observation after releasing the lock. + +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use std::time::Duration; +use std::time::Instant; + +use codex_protocol::ThreadId; + +/// Assistant text at publication, with its stream or finalized item identity. +#[derive(Clone, Copy)] +pub struct AssistantTextCandidate<'a> { + pub text: &'a str, + pub response_id: Option<&'a str>, + pub item_id: &'a str, +} + +/// Host predicates should be fast and side-effect free. Concurrent candidates +/// may both pass a predicate before one claims the watch. +#[derive(Default)] +pub struct MilestoneWatches { + pub assistant_text: Option, + pub direct_apps_tool_start: Option, +} + +pub struct AssistantText(Box) -> bool + Send + Sync>); + +impl AssistantText { + pub fn new( + predicate: impl Fn(AssistantTextCandidate<'_>) -> bool + Send + Sync + 'static, + ) -> Self { + Self(Box::new(predicate)) + } +} + +/// Matches the resolved resource URI at direct Apps dispatch. +pub struct DirectAppsToolStart(Box bool + Send + Sync>); + +impl DirectAppsToolStart { + pub fn new(predicate: impl Fn(&str) -> bool + Send + Sync + 'static) -> Self { + Self(Box::new(predicate)) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum MilestoneSourceId { + AssistantText { + response_id: Option, + item_id: String, + }, + DirectToolStart { + call_id: String, + resource_uri: String, + /// Local stream identity for correlation when the provider response ID arrives later. + response_attempt_id: Option, + }, +} + +/// Timing through the source cutoff, owned independently of the running turn. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MilestoneObservation { + pub thread_id: ThreadId, + pub turn_id: String, + pub source: MilestoneSourceId, + /// Monotonic and meaningful only in the current process. + pub cutoff: Instant, + pub elapsed: Duration, + pub critical_path: T, +} + +/// Attach a fresh registration to each opted-in turn's input extension data. +/// Only the first regular turn to bind the registration uses its watches. +#[derive(Debug)] +pub struct TurnMilestoneWatches(Mutex>>>); + +/// Watches and observer owned by the turn that took the registration. +pub struct ActiveMilestoneWatches { + assistant_text: Option>, + direct_apps_tool_start: Option>, + observer: Box) + Send + Sync>, +} + +impl std::fmt::Debug for ActiveMilestoneWatches { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ActiveMilestoneWatches") + .finish_non_exhaustive() + } +} + +impl TurnMilestoneWatches { + /// The observer runs synchronously outside the timing locks. It should + /// return promptly and queue any asynchronous work. + pub fn new( + watches: MilestoneWatches, + observer: impl Fn(MilestoneObservation) + Send + Sync + 'static, + ) -> Self { + Self(Mutex::new(Some(Box::new(ActiveMilestoneWatches { + assistant_text: watches.assistant_text.map(Watch::new), + direct_apps_tool_start: watches.direct_apps_tool_start.map(Watch::new), + observer: Box::new(observer), + })))) + } + + /// Transfers this registration to at most one turn. + pub fn take(&self) -> Option>> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } +} + +impl ActiveMilestoneWatches { + pub fn assistant_text(&self) -> Option<&Watch> { + self.assistant_text + .as_ref() + .filter(|watch| watch.is_pending()) + } + + pub fn direct_apps_tool_start(&self) -> Option<&Watch> { + self.direct_apps_tool_start + .as_ref() + .filter(|watch| watch.is_pending()) + } + + pub fn deliver(&self, observation: MilestoneObservation) { + (self.observer)(observation); + } +} + +/// A configured predicate and its independent one-shot latch. +pub struct Watch

{ + predicate: P, + pending: AtomicBool, +} + +impl

Watch

{ + fn new(predicate: P) -> Self { + Self { + predicate, + pending: AtomicBool::new(true), + } + } + + fn is_pending(&self) -> bool { + self.pending.load(Ordering::Relaxed) + } + + /// Claim a matching candidate under the caller's timing lock, after + /// validating its cutoff. The latch only arbitrates ownership. + pub fn try_claim(&self) -> bool { + self.pending.swap(false, Ordering::Relaxed) + } +} + +impl Watch { + pub fn matches(&self, candidate: AssistantTextCandidate<'_>) -> bool { + (self.predicate.0)(candidate) + } +} + +impl Watch { + pub fn matches(&self, resource_uri: &str) -> bool { + (self.predicate.0)(resource_uri) + } +} + +#[cfg(test)] +#[path = "milestones_tests.rs"] +mod tests; diff --git a/codex-rs/turn-milestones/src/milestones_tests.rs b/codex-rs/turn-milestones/src/milestones_tests.rs new file mode 100644 index 0000000000..2ced48979f --- /dev/null +++ b/codex-rs/turn-milestones/src/milestones_tests.rs @@ -0,0 +1,64 @@ +#![cfg(test)] + +use std::sync::Barrier; + +use pretty_assertions::assert_eq; + +use super::*; + +const TEXT: AssistantTextCandidate<'static> = AssistantTextCandidate { + text: "answer", + response_id: Some("response-a"), + item_id: "message", +}; + +#[test] +fn unspent_watches_can_only_be_taken_by_one_turn() { + let registration = TurnMilestoneWatches::<()>::new( + MilestoneWatches { + assistant_text: Some(AssistantText::new(|_| true)), + direct_apps_tool_start: None, + }, + |_| {}, + ); + let watches = registration.take().unwrap(); + assert!(watches.assistant_text().is_some()); + assert!(watches.direct_apps_tool_start().is_none()); + assert!(registration.take().is_none()); +} + +#[test] +fn concurrent_matching_uris_claim_one_tool_watch_and_leave_text_pending() { + let watches = TurnMilestoneWatches::<()>::new( + MilestoneWatches { + assistant_text: Some(AssistantText::new(|candidate| candidate.text == TEXT.text)), + direct_apps_tool_start: Some(DirectAppsToolStart::new(|uri| { + matches!(uri, "app://link-a/send" | "app://link-b/send") + })), + }, + |_| {}, + ) + .take() + .unwrap(); + + let tool = watches.direct_apps_tool_start().unwrap(); + assert!(!tool.matches("app://link-a/read")); + let barrier = Barrier::new(2); + let attempt = |uri| { + let matches = tool.matches(uri); + barrier.wait(); + (matches, matches && tool.try_claim()) + }; + let ((first_match, first_claim), (second_match, second_claim)) = std::thread::scope(|scope| { + let other = scope.spawn(|| attempt("app://link-b/send")); + (attempt("app://link-a/send"), other.join().unwrap()) + }); + assert_eq!((first_match, second_match), (true, true)); + assert_ne!(first_claim, second_claim); + assert!(watches.direct_apps_tool_start().is_none()); + + let text = watches.assistant_text().unwrap(); + assert!(text.matches(TEXT)); + assert!(text.try_claim()); + assert!(watches.assistant_text().is_none()); +}