Move goal events out of extension API

This commit is contained in:
Eric Traut
2026-05-27 21:55:14 -07:00
parent 0471e80ece
commit 3e272a15cf
14 changed files with 107 additions and 128 deletions
+29 -33
View File
@@ -9,34 +9,35 @@ use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_extension_api::AgentSpawnFuture;
use codex_extension_api::AgentSpawner;
use codex_extension_api::ExtensionEvent;
use codex_extension_api::ExtensionEventFuture;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_features::Feature;
use codex_goal_extension::GoalEventFuture;
use codex_goal_extension::GoalEventSink;
use codex_login::AuthManager;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use codex_rollout::state_db::StateDbHandle;
use crate::outgoing_message::OutgoingMessageSender;
pub(crate) fn thread_extensions<S>(
guardian_agent_spawner: S,
event_sink: Arc<dyn ExtensionEventSink>,
goal_event_sink: Arc<dyn GoalEventSink>,
auth_manager: Arc<AuthManager>,
state_db: Option<StateDbHandle>,
) -> Arc<ExtensionRegistry<Config>>
where
S: AgentSpawner<StartThreadOptions, Spawned = NewThread, Error = CodexErr> + 'static,
{
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(event_sink);
let mut builder = ExtensionRegistryBuilder::<Config>::new();
codex_guardian::install(&mut builder, guardian_agent_spawner);
if let Some(state_db) = state_db {
codex_goal_extension::install_with_backend(
&mut builder,
state_db,
goal_event_sink,
codex_otel::global(),
|config: &Config| config.features.enabled(Feature::Goals),
);
@@ -46,30 +47,26 @@ where
Arc::new(builder.build())
}
pub(crate) fn app_server_extension_event_sink(
pub(crate) fn app_server_goal_event_sink(
outgoing: Arc<OutgoingMessageSender>,
) -> Arc<dyn ExtensionEventSink> {
Arc::new(AppServerExtensionEventSink { outgoing })
) -> Arc<dyn GoalEventSink> {
Arc::new(AppServerGoalEventSink { outgoing })
}
struct AppServerExtensionEventSink {
struct AppServerGoalEventSink {
outgoing: Arc<OutgoingMessageSender>,
}
impl ExtensionEventSink for AppServerExtensionEventSink {
fn emit<'a>(&'a self, event: ExtensionEvent) -> ExtensionEventFuture<'a> {
impl GoalEventSink for AppServerGoalEventSink {
fn thread_goal_updated<'a>(&'a self, event: ThreadGoalUpdatedEvent) -> GoalEventFuture<'a> {
Box::pin(async move {
match event {
ExtensionEvent::ThreadGoalUpdated(thread_goal_event) => {
let notification =
ServerNotification::ThreadGoalUpdated(ThreadGoalUpdatedNotification {
thread_id: thread_goal_event.thread_id.to_string(),
turn_id: thread_goal_event.turn_id,
goal: thread_goal_event.goal.into(),
});
self.outgoing.send_server_notification(notification).await;
}
}
let notification =
ServerNotification::ThreadGoalUpdated(ThreadGoalUpdatedNotification {
thread_id: event.thread_id.to_string(),
turn_id: event.turn_id,
goal: event.goal.into(),
});
self.outgoing.send_server_notification(notification).await;
})
}
}
@@ -102,7 +99,6 @@ mod tests {
use codex_app_server_protocol::ThreadGoalStatus as AppServerThreadGoalStatus;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use tokio::time::timeout;
@@ -112,7 +108,7 @@ mod tests {
use crate::outgoing_message::OutgoingMessage;
#[tokio::test]
async fn app_server_event_sink_waits_for_outgoing_capacity() {
async fn app_server_goal_event_sink_waits_for_outgoing_capacity() {
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(1);
let outgoing = Arc::new(OutgoingMessageSender::new(
outgoing_tx.clone(),
@@ -130,10 +126,10 @@ mod tests {
),
})
.expect("prefill should fit in one-slot channel");
let sink = app_server_extension_event_sink(outgoing);
let sink = app_server_goal_event_sink(outgoing);
let emit = tokio::spawn(async move {
sink.emit(thread_goal_update_event(
sink.thread_goal_updated(thread_goal_update_event(
thread_id,
"wait for capacity",
"turn-1",
@@ -152,18 +148,18 @@ mod tests {
}
#[tokio::test]
async fn app_server_event_sink_preserves_goal_update_order() {
async fn app_server_goal_event_sink_preserves_goal_update_order() {
let (outgoing_tx, mut outgoing_rx) = mpsc::channel(2);
let outgoing = Arc::new(OutgoingMessageSender::new(
outgoing_tx,
AnalyticsEventsClient::disabled(),
));
let thread_id = ThreadId::default();
let sink = app_server_extension_event_sink(outgoing);
let sink = app_server_goal_event_sink(outgoing);
sink.emit(thread_goal_update_event(thread_id, "first", "turn-1"))
sink.thread_goal_updated(thread_goal_update_event(thread_id, "first", "turn-1"))
.await;
sink.emit(thread_goal_update_event(thread_id, "second", "turn-2"))
sink.thread_goal_updated(thread_goal_update_event(thread_id, "second", "turn-2"))
.await;
assert_eq!(
@@ -180,8 +176,8 @@ mod tests {
thread_id: ThreadId,
objective: &str,
turn_id: &str,
) -> ExtensionEvent {
ExtensionEvent::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
) -> ThreadGoalUpdatedEvent {
ThreadGoalUpdatedEvent {
thread_id,
turn_id: Some(turn_id.to_string()),
goal: ThreadGoal {
@@ -194,7 +190,7 @@ mod tests {
created_at: 7,
updated_at: 8,
},
})
}
}
fn app_server_goal_update(
+2 -2
View File
@@ -114,7 +114,7 @@ mod tests {
use codex_core::init_state_db;
use codex_core::thread_store_from_config;
use codex_exec_server::EnvironmentManager;
use codex_extension_api::NoopExtensionEventSink;
use codex_goal_extension::NoopGoalEventSink;
use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::protocol::SessionSource;
@@ -189,7 +189,7 @@ mod tests {
Arc::new(EnvironmentManager::default_for_tests()),
thread_extensions(
guardian_agent_spawner(thread_manager.clone()),
Arc::new(NoopExtensionEventSink),
Arc::new(NoopGoalEventSink),
auth_manager.clone(),
Some(state_db.clone()),
),
+2 -2
View File
@@ -8,7 +8,7 @@ use crate::attestation::app_server_attestation_provider;
use crate::config_manager::ConfigManager;
use crate::connection_rpc_gate::ConnectionRpcGate;
use crate::error_code::invalid_request;
use crate::extensions::app_server_extension_event_sink;
use crate::extensions::app_server_goal_event_sink;
use crate::extensions::guardian_agent_spawner;
use crate::extensions::thread_extensions;
use crate::fs_watch::FsWatchManager;
@@ -313,7 +313,7 @@ impl MessageProcessor {
environment_manager,
thread_extensions(
guardian_agent_spawner(thread_manager.clone()),
app_server_extension_event_sink(outgoing.clone()),
app_server_goal_event_sink(outgoing.clone()),
auth_manager.clone(),
state_db.clone(),
),
+3 -1
View File
@@ -230,8 +230,10 @@ pub(crate) fn extension_tool_executors(
contributor.tools_for_turn(codex_extension_api::ToolContributionInput {
session_store: &session.services.session_extension_data,
thread_store: &session.services.thread_extension_data,
turn_store: turn_context.extension_data.as_ref(),
session_source: &turn_context.session_source,
persistent_thread: !turn_context.config.ephemeral && session.state_db().is_some(),
persistent_thread_state_available: !turn_context.config.ephemeral
&& session.state_db().is_some(),
})
})
.collect()
@@ -1,31 +0,0 @@
use std::future::Future;
use std::pin::Pin;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
pub type ExtensionEventFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
/// Events that extensions can ask the host to deliver.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExtensionEvent {
ThreadGoalUpdated(ThreadGoalUpdatedEvent),
}
/// Host-provided sink for extension-generated events.
///
/// Extensions construct typed extension events, then leave persistence,
/// ordering, transport fanout, and logging decisions to the host.
pub trait ExtensionEventSink: Send + Sync {
/// Queue one extension event for host-owned delivery.
fn emit<'a>(&'a self, event: ExtensionEvent) -> ExtensionEventFuture<'a>;
}
/// Event sink used when the host does not expose extension event emission.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopExtensionEventSink;
impl ExtensionEventSink for NoopExtensionEventSink {
fn emit<'a>(&'a self, _event: ExtensionEvent) -> ExtensionEventFuture<'a> {
Box::pin(std::future::ready(()))
}
}
@@ -1,13 +1,8 @@
mod agent;
mod events;
mod response_items;
pub use agent::AgentSpawnFuture;
pub use agent::AgentSpawner;
pub use events::ExtensionEvent;
pub use events::ExtensionEventFuture;
pub use events::ExtensionEventSink;
pub use events::NoopExtensionEventSink;
pub use response_items::NoopResponseItemInjector;
pub use response_items::ResponseInjectionItem;
pub use response_items::ResponseItemInjectionFuture;
@@ -194,10 +194,12 @@ pub struct ToolContributionInput<'a> {
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
pub thread_store: &'a ExtensionData,
/// Store scoped to the current turn runtime.
pub turn_store: &'a ExtensionData,
/// Source for the current turn's session.
pub session_source: &'a SessionSource,
/// Whether the current thread has persistent state available.
pub persistent_thread: bool,
/// Whether persistent state is available for the current thread.
pub persistent_thread_state_available: bool,
}
/// Contributor for host-owned tool lifecycle gates.
-4
View File
@@ -6,10 +6,6 @@ mod state;
pub use capabilities::AgentSpawnFuture;
pub use capabilities::AgentSpawner;
pub use capabilities::ExtensionEvent;
pub use capabilities::ExtensionEventFuture;
pub use capabilities::ExtensionEventSink;
pub use capabilities::NoopExtensionEventSink;
pub use capabilities::NoopResponseItemInjector;
pub use capabilities::ResponseInjectionItem;
pub use capabilities::ResponseItemInjectionFuture;
@@ -6,8 +6,6 @@ use crate::ApprovalReviewContributor;
use crate::ConfigContributor;
use crate::ContextContributor;
use crate::ExtensionData;
use crate::ExtensionEventSink;
use crate::NoopExtensionEventSink;
use crate::ThreadIdleTurnContributor;
use crate::ThreadLifecycleContributor;
use crate::TokenUsageContributor;
@@ -18,7 +16,6 @@ use crate::TurnLifecycleContributor;
/// Mutable registry used while hosts register typed runtime contributions.
pub struct ExtensionRegistryBuilder<C: Sync> {
event_sink: Arc<dyn ExtensionEventSink>,
thread_lifecycle_contributors: Vec<Arc<dyn ThreadLifecycleContributor<C>>>,
thread_idle_turn_contributors: Vec<Arc<dyn ThreadIdleTurnContributor>>,
turn_lifecycle_contributors: Vec<Arc<dyn TurnLifecycleContributor>>,
@@ -34,7 +31,6 @@ pub struct ExtensionRegistryBuilder<C: Sync> {
impl<C: Sync> Default for ExtensionRegistryBuilder<C> {
fn default() -> Self {
Self {
event_sink: Arc::new(NoopExtensionEventSink),
thread_lifecycle_contributors: Vec::new(),
thread_idle_turn_contributors: Vec::new(),
turn_lifecycle_contributors: Vec::new(),
@@ -55,19 +51,6 @@ impl<C: Sync> ExtensionRegistryBuilder<C> {
Self::default()
}
/// Creates an empty registry builder with a host-provided event sink.
pub fn with_event_sink(event_sink: Arc<dyn ExtensionEventSink>) -> Self {
Self {
event_sink,
..Self::default()
}
}
/// Returns the host event sink to pass into extension constructors.
pub fn event_sink(&self) -> Arc<dyn ExtensionEventSink> {
Arc::clone(&self.event_sink)
}
/// Registers one approval-review contributor.
pub fn approval_review_contributor(&mut self, contributor: Arc<dyn ApprovalReviewContributor>) {
self.approval_review_contributors.push(contributor);
+26 -6
View File
@@ -1,27 +1,47 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use codex_extension_api::ExtensionEvent;
use codex_extension_api::ExtensionEventSink;
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
/// Future returned when a host accepts a goal extension event.
pub type GoalEventFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
/// Host capability for goal-extension events that should be delivered outside
/// the extension runtime.
pub trait GoalEventSink: Send + Sync {
/// Queue a goal update for host-owned delivery.
fn thread_goal_updated<'a>(&'a self, event: ThreadGoalUpdatedEvent) -> GoalEventFuture<'a>;
}
/// Goal event sink used when the host does not expose goal event delivery.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopGoalEventSink;
impl GoalEventSink for NoopGoalEventSink {
fn thread_goal_updated<'a>(&'a self, _event: ThreadGoalUpdatedEvent) -> GoalEventFuture<'a> {
Box::pin(std::future::ready(()))
}
}
#[derive(Clone)]
pub(crate) struct GoalEventEmitter {
sink: Arc<dyn ExtensionEventSink>,
sink: Arc<dyn GoalEventSink>,
}
impl GoalEventEmitter {
pub(crate) fn new(sink: Arc<dyn ExtensionEventSink>) -> Self {
pub(crate) fn new(sink: Arc<dyn GoalEventSink>) -> Self {
Self { sink }
}
pub(crate) async fn thread_goal_updated(&self, turn_id: Option<String>, goal: ThreadGoal) {
self.sink
.emit(ExtensionEvent::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
.thread_goal_updated(ThreadGoalUpdatedEvent {
thread_id: goal.thread_id,
turn_id,
goal,
}))
})
.await;
}
}
+5 -4
View File
@@ -3,7 +3,6 @@ use std::sync::Arc;
use async_trait::async_trait;
use codex_extension_api::ConfigContributor;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::ThreadIdleInput;
use codex_extension_api::ThreadIdleTurnContributor;
@@ -35,6 +34,7 @@ use codex_protocol::protocol::TokenUsageInfo;
use crate::accounting::BudgetLimitedGoalDisposition;
use crate::accounting::GoalAccountingState;
use crate::events::GoalEventEmitter;
use crate::events::GoalEventSink;
use crate::metrics::GoalMetrics;
use crate::runtime::GoalRuntimeHandle;
use crate::spec::UPDATE_GOAL_TOOL_NAME;
@@ -58,7 +58,7 @@ impl<C> std::fmt::Debug for GoalExtension<C> {
impl<C> GoalExtension<C> {
pub(crate) fn new_with_host_capabilities(
state_dbs: Arc<codex_state::StateRuntime>,
event_sink: Arc<dyn ExtensionEventSink>,
event_sink: Arc<dyn GoalEventSink>,
metrics_client: Option<MetricsClient>,
goals_enabled: impl Fn(&C) -> bool + Send + Sync + 'static,
) -> Self {
@@ -371,7 +371,7 @@ where
&self,
input: ToolContributionInput<'_>,
) -> Vec<Arc<dyn codex_extension_api::ToolExecutor<codex_extension_api::ToolCall>>> {
if !input.persistent_thread
if !input.persistent_thread_state_available
|| matches!(
input.session_source,
SessionSource::SubAgent(SubAgentSource::Review)
@@ -427,6 +427,7 @@ where
pub fn install_with_backend<C>(
registry: &mut ExtensionRegistryBuilder<C>,
state_dbs: Arc<codex_state::StateRuntime>,
event_sink: Arc<dyn GoalEventSink>,
metrics_client: Option<MetricsClient>,
goals_enabled: impl Fn(&C) -> bool + Send + Sync + 'static,
) where
@@ -434,7 +435,7 @@ pub fn install_with_backend<C>(
{
let extension = Arc::new(GoalExtension::new_with_host_capabilities(
state_dbs,
registry.event_sink(),
event_sink,
metrics_client,
goals_enabled,
));
+3
View File
@@ -13,6 +13,9 @@ mod spec;
mod steering;
mod tool;
pub use events::GoalEventFuture;
pub use events::GoalEventSink;
pub use events::NoopGoalEventSink;
pub use extension::GoalExtension;
pub use extension::install_with_backend;
pub use runtime::GoalRuntimeHandle;
@@ -4,8 +4,6 @@ use std::sync::PoisonError;
use std::time::Duration;
use codex_extension_api::ExtensionData;
use codex_extension_api::ExtensionEvent;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::FunctionCallError;
use codex_extension_api::NoopResponseItemInjector;
@@ -24,7 +22,10 @@ use codex_extension_api::ToolPayload;
use codex_extension_api::TurnErrorInput;
use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStopInput;
use codex_goal_extension::GoalEventFuture;
use codex_goal_extension::GoalEventSink;
use codex_goal_extension::GoalRuntimeHandle;
use codex_goal_extension::NoopGoalEventSink;
use codex_goal_extension::install_with_backend;
use codex_protocol::ThreadId;
use codex_protocol::config_types::CollaborationMode;
@@ -34,6 +35,7 @@ use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::TruncationPolicy;
@@ -142,7 +144,7 @@ async fn goal_tools_hidden_for_review_turns() -> anyhow::Result<()> {
let tools = harness.tools_for_turn(
SessionSource::SubAgent(SubAgentSource::Review),
/*persistent_thread*/ true,
/*persistent_thread_state_available*/ true,
);
assert!(tools.is_empty());
@@ -150,13 +152,16 @@ async fn goal_tools_hidden_for_review_turns() -> anyhow::Result<()> {
}
#[tokio::test]
async fn goal_tools_hidden_without_persistent_thread() -> anyhow::Result<()> {
async fn goal_tools_hidden_without_persistent_thread_state() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
let harness = GoalExtensionHarness::new(runtime, thread_id).await?;
let tools = harness.tools_for_turn(SessionSource::Cli, /*persistent_thread*/ false);
let tools = harness.tools_for_turn(
SessionSource::Cli,
/*persistent_thread_state_available*/ false,
);
assert!(tools.is_empty());
Ok(())
@@ -1131,6 +1136,7 @@ async fn installed_tools(
install_with_backend(
&mut builder,
runtime,
Arc::new(NoopGoalEventSink),
/*metrics_client*/ None,
|_| true,
);
@@ -1153,11 +1159,13 @@ async fn installed_tools(
.iter()
.flat_map(|contributor| {
let session_source = SessionSource::Cli;
let turn_store = ExtensionData::new("turn-1");
contributor.tools_for_turn(ToolContributionInput {
session_store: &session_store,
thread_store: &thread_store,
turn_store: &turn_store,
session_source: &session_source,
persistent_thread: true,
persistent_thread_state_available: true,
})
})
.collect()
@@ -1176,10 +1184,11 @@ impl GoalExtensionHarness {
thread_id: ThreadId,
) -> anyhow::Result<Self> {
let sink = Arc::new(RecordingEventSink::default());
let mut builder = ExtensionRegistryBuilder::<()>::with_event_sink(sink.clone());
let mut builder = ExtensionRegistryBuilder::<()>::new();
install_with_backend(
&mut builder,
runtime,
sink.clone(),
/*metrics_client*/ None,
|_| true,
);
@@ -1205,14 +1214,18 @@ impl GoalExtensionHarness {
}
fn tools(&self) -> Vec<Arc<dyn ToolExecutor<ToolCall>>> {
self.tools_for_turn(SessionSource::Cli, /*persistent_thread*/ true)
self.tools_for_turn(
SessionSource::Cli,
/*persistent_thread_state_available*/ true,
)
}
fn tools_for_turn(
&self,
session_source: SessionSource,
persistent_thread: bool,
persistent_thread_state_available: bool,
) -> Vec<Arc<dyn ToolExecutor<ToolCall>>> {
let turn_store = ExtensionData::new("turn-1");
self.registry
.tool_contributors()
.iter()
@@ -1220,8 +1233,9 @@ impl GoalExtensionHarness {
contributor.tools_for_turn(ToolContributionInput {
session_store: &self.session_store,
thread_store: &self.thread_store,
turn_store: &turn_store,
session_source: &session_source,
persistent_thread,
persistent_thread_state_available,
})
})
.collect()
@@ -1409,20 +1423,17 @@ async fn seed_thread_metadata(
#[derive(Debug, Default)]
struct RecordingEventSink {
events: Mutex<Vec<ExtensionEvent>>,
events: Mutex<Vec<ThreadGoalUpdatedEvent>>,
}
impl RecordingEventSink {
fn goal_events(&self) -> Vec<CapturedGoalEvent> {
self.events()
.iter()
.map(|event| {
let ExtensionEvent::ThreadGoalUpdated(updated) = event;
CapturedGoalEvent {
turn_id: updated.turn_id.clone(),
status: updated.goal.status,
tokens_used: updated.goal.tokens_used,
}
.map(|updated| CapturedGoalEvent {
turn_id: updated.turn_id.clone(),
status: updated.goal.status,
tokens_used: updated.goal.tokens_used,
})
.collect()
}
@@ -1431,13 +1442,13 @@ impl RecordingEventSink {
self.events().clear();
}
fn events(&self) -> std::sync::MutexGuard<'_, Vec<ExtensionEvent>> {
fn events(&self) -> std::sync::MutexGuard<'_, Vec<ThreadGoalUpdatedEvent>> {
self.events.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl ExtensionEventSink for RecordingEventSink {
fn emit<'a>(&'a self, event: ExtensionEvent) -> codex_extension_api::ExtensionEventFuture<'a> {
impl GoalEventSink for RecordingEventSink {
fn thread_goal_updated<'a>(&'a self, event: ThreadGoalUpdatedEvent) -> GoalEventFuture<'a> {
self.events().push(event);
Box::pin(std::future::ready(()))
}
@@ -70,6 +70,7 @@ impl MessageProcessor {
codex_goal_extension::install_with_backend(
&mut extensions,
state_db,
Arc::new(codex_goal_extension::NoopGoalEventSink),
codex_otel::global(),
|config: &Config| config.features.enabled(Feature::Goals),
);