Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

[2 of 2] Finish moving goal runtime to extension (#26548)

Eric Traut479a14cf592d
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index b899222384..a61df434f1 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -1926,6 +1926,7 @@ dependencies = [
"codex-file-search",
"codex-file-watcher",
"codex-git-utils",
+ "codex-goal-extension",
"codex-guardian",
"codex-hooks",
"codex-image-generation-extension",
diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml
index 5d6d116049..5fe0104321 100644
--- a/codex-rs/Cargo.toml
+++ b/codex-rs/Cargo.toml
@@ -483,7 +483,6 @@ unwrap_used = "deny"
[workspace.metadata.cargo-shear]
ignored = [
"codex-agent-graph-store",
- "codex-goal-extension",
"icu_provider",
"openssl-sys",
"codex-v8-poc",
diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml
index 37cdf219bf..4bdc430a1a 100644
--- a/codex-rs/app-server/Cargo.toml
+++ b/codex-rs/app-server/Cargo.toml
@@ -41,6 +41,7 @@ codex-extension-api = { workspace = true }
codex-external-agent-migration = { workspace = true }
codex-external-agent-sessions = { workspace = true }
codex-features = { workspace = true }
+codex-goal-extension = { workspace = true }
codex-guardian = { workspace = true }
codex-git-utils = { workspace = true }
codex-file-watcher = { workspace = true }
diff --git a/codex-rs/app-server/src/extensions.rs b/codex-rs/app-server/src/extensions.rs
index 7b2673ca06..53f19997cd 100644
--- a/codex-rs/app-server/src/extensions.rs
+++ b/codex-rs/app-server/src/extensions.rs
@@ -2,6 +2,7 @@ use std::sync::Arc;
use std::sync::Weak;
use codex_app_server_protocol::ServerNotification;
+use codex_app_server_protocol::ThreadGoal;
use codex_app_server_protocol::ThreadGoalUpdatedNotification;
use codex_core::NewThread;
use codex_core::StartThreadOptions;
@@ -12,23 +13,40 @@ use codex_extension_api::AgentSpawner;
use codex_extension_api::ExtensionEventSink;
use codex_extension_api::ExtensionRegistry;
use codex_extension_api::ExtensionRegistryBuilder;
+use codex_goal_extension::GoalService;
use codex_login::AuthManager;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
+use codex_rollout::state_db::StateDbHandle;
use crate::outgoing_message::OutgoingMessageSender;
+use crate::thread_state::ThreadListenerCommand;
+use crate::thread_state::ThreadStateManager;
pub(crate) fn thread_extensions<S>(
guardian_agent_spawner: S,
event_sink: Arc<dyn ExtensionEventSink>,
auth_manager: Arc<AuthManager>,
+ state_db: Option<StateDbHandle>,
+ thread_manager: Weak<ThreadManager>,
+ goal_service: Arc<GoalService>,
) -> Arc<ExtensionRegistry<Config>>
where
S: AgentSpawner<StartThreadOptions, Spawned = NewThread, Error = CodexErr> + 'static,
{
let mut builder = ExtensionRegistryBuilder::<Config>::with_event_sink(event_sink);
+ if let Some(state_db) = state_db {
+ codex_goal_extension::install_with_backend(
+ &mut builder,
+ state_db,
+ codex_otel::global(),
+ thread_manager,
+ goal_service,
+ |config: &Config| config.features.enabled(codex_features::Feature::Goals),
+ );
+ }
codex_guardian::install(&mut builder, guardian_agent_spawner);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_web_search_extension::install(&mut builder, auth_manager.clone());
@@ -38,26 +56,53 @@ where
pub(crate) fn app_server_extension_event_sink(
outgoing: Arc<OutgoingMessageSender>,
+ thread_state_manager: ThreadStateManager,
) -> Arc<dyn ExtensionEventSink> {
- Arc::new(AppServerExtensionEventSink { outgoing })
+ Arc::new(AppServerExtensionEventSink {
+ outgoing,
+ thread_state_manager,
+ })
}
struct AppServerExtensionEventSink {
outgoing: Arc<OutgoingMessageSender>,
+ thread_state_manager: ThreadStateManager,
}
impl ExtensionEventSink for AppServerExtensionEventSink {
fn emit(&self, event: Event) {
match event.msg {
EventMsg::ThreadGoalUpdated(thread_goal_event) => {
- self.outgoing
- .try_send_server_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(),
- },
- ));
+ let thread_id = thread_goal_event.thread_id;
+ let turn_id = thread_goal_event.turn_id;
+ let goal: ThreadGoal = thread_goal_event.goal.into();
+ if let Some(listener_command_tx) = self
+ .thread_state_manager
+ .current_listener_command_tx(thread_id)
+ {
+ let command = ThreadListenerCommand::EmitThreadGoalUpdated {
+ turn_id: turn_id.clone(),
+ goal: goal.clone(),
+ };
+ if listener_command_tx.send(command).is_ok() {
+ return;
+ }
+ tracing::warn!(
+ "failed to enqueue extension goal update for {thread_id}: listener command channel is closed"
+ );
+ }
+ let outgoing = Arc::clone(&self.outgoing);
+ tokio::spawn(async move {
+ outgoing
+ .send_server_notification(ServerNotification::ThreadGoalUpdated(
+ ThreadGoalUpdatedNotification {
+ thread_id: thread_id.to_string(),
+ turn_id,
+ goal,
+ },
+ ))
+ .await;
+ });
}
msg => {
tracing::debug!(event_id = %event.id, ?msg, "dropping unsupported extension event");
@@ -89,10 +134,7 @@ mod tests {
use std::time::Duration;
use codex_analytics::AnalyticsEventsClient;
- use codex_app_server_protocol::ServerNotification;
- use codex_app_server_protocol::ThreadGoal as AppServerThreadGoal;
- use codex_app_server_protocol::ThreadGoalStatus as AppServerThreadGoalStatus;
- use codex_protocol::protocol::ThreadGoal;
+ use codex_protocol::protocol::ThreadGoal as CoreThreadGoal;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use pretty_assertions::assert_eq;
@@ -100,25 +142,61 @@ mod tests {
use tokio::time::timeout;
use super::*;
- use crate::outgoing_message::OutgoingEnvelope;
- use crate::outgoing_message::OutgoingMessage;
#[tokio::test]
- async fn app_server_event_sink_forwards_thread_goal_updates() {
- let (outgoing_tx, mut outgoing_rx) = mpsc::channel(4);
+ async fn app_server_event_sink_uses_listener_fifo_for_goal_updates_and_clears() {
+ let (outgoing_tx, _outgoing_rx) = mpsc::channel(4);
let outgoing = Arc::new(OutgoingMessageSender::new(
outgoing_tx,
AnalyticsEventsClient::disabled(),
));
- let sink = app_server_extension_event_sink(outgoing);
+ let thread_state_manager = ThreadStateManager::new();
let thread_id = ThreadId::default();
+ let (listener_command_tx, mut listener_command_rx) = mpsc::unbounded_channel();
+ thread_state_manager.register_listener_command_tx(thread_id, listener_command_tx.clone());
+ let sink = app_server_extension_event_sink(outgoing, thread_state_manager);
+
+ for turn_id in ["turn-1", "turn-2"] {
+ sink.emit(thread_goal_updated_event(thread_id, turn_id));
+ }
+ listener_command_tx
+ .send(ThreadListenerCommand::EmitThreadGoalCleared)
+ .expect("listener command channel should be open");
+
+ let mut observed = Vec::new();
+ for _ in 0..3 {
+ let command = timeout(Duration::from_secs(1), listener_command_rx.recv())
+ .await
+ .expect("timed out waiting for listener command")
+ .expect("listener command channel closed unexpectedly");
+ match command {
+ ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, .. } => {
+ observed.push(turn_id.expect("extension goal updates should include turn ids"));
+ }
+ ThreadListenerCommand::EmitThreadGoalCleared => {
+ observed.push("cleared".to_string())
+ }
+ _ => panic!("unexpected listener command"),
+ }
+ }
+
+ assert_eq!(
+ vec![
+ "turn-1".to_string(),
+ "turn-2".to_string(),
+ "cleared".to_string()
+ ],
+ observed
+ );
+ }
- sink.emit(Event {
- id: "call-1".to_string(),
+ fn thread_goal_updated_event(thread_id: ThreadId, turn_id: &str) -> Event {
+ Event {
+ id: turn_id.to_string(),
msg: EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
thread_id,
- turn_id: Some("turn-1".to_string()),
- goal: ThreadGoal {
+ turn_id: Some(turn_id.to_string()),
+ goal: CoreThreadGoal {
thread_id,
objective: "wire extension events".to_string(),
status: ThreadGoalStatus::Active,
@@ -129,38 +207,6 @@ mod tests {
updated_at: 8,
},
}),
- });
-
- let envelope = timeout(Duration::from_secs(1), outgoing_rx.recv())
- .await
- .expect("timed out waiting for forwarded extension event")
- .expect("outgoing channel closed unexpectedly");
- let OutgoingEnvelope::Broadcast { message } = envelope else {
- panic!("expected broadcast notification");
- };
- let OutgoingMessage::AppServerNotification(ServerNotification::ThreadGoalUpdated(
- notification,
- )) = message
- else {
- panic!("expected thread goal updated notification");
- };
-
- assert_eq!(
- ThreadGoalUpdatedNotification {
- thread_id: thread_id.to_string(),
- turn_id: Some("turn-1".to_string()),
- goal: AppServerThreadGoal {
- thread_id: thread_id.to_string(),
- objective: "wire extension events".to_string(),
- status: AppServerThreadGoalStatus::Active,
- token_budget: Some(123),
- tokens_used: 45,
- time_used_seconds: 6,
- created_at: 7,
- updated_at: 8,
- },
- },
- notification
- );
+ }
}
}
diff --git a/codex-rs/app-server/src/mcp_refresh.rs b/codex-rs/app-server/src/mcp_refresh.rs
index 0996c409bc..8c72533ba5 100644
--- a/codex-rs/app-server/src/mcp_refresh.rs
+++ b/codex-rs/app-server/src/mcp_refresh.rs
@@ -191,6 +191,9 @@ mod tests {
guardian_agent_spawner(thread_manager.clone()),
Arc::new(NoopExtensionEventSink),
auth_manager.clone(),
+ Some(state_db.clone()),
+ thread_manager.clone(),
+ Arc::new(codex_goal_extension::GoalService::new()),
),
/*analytics_events_client*/ None,
Arc::clone(&thread_store),
diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs
index 76f39663a0..b7e0ff258d 100644
--- a/codex-rs/app-server/src/message_processor.rs
+++ b/codex-rs/app-server/src/message_processor.rs
@@ -70,6 +70,7 @@ use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_exec_server::EnvironmentManager;
use codex_feedback::CodexFeedback;
+use codex_goal_extension::GoalService;
use codex_login::AuthManager;
use codex_login::auth::ExternalAuth;
use codex_login::auth::ExternalAuthRefreshContext;
@@ -305,6 +306,7 @@ impl MessageProcessor {
// resumed, or forked threads to a different persistence backend/root.
let thread_store = codex_core::thread_store_from_config(config.as_ref(), state_db.clone());
let environment_manager_for_requests = Arc::clone(&environment_manager);
+ let goal_service = Arc::new(GoalService::new());
let thread_manager = Arc::new_cyclic(|thread_manager| {
ThreadManager::new(
config.as_ref(),
@@ -313,8 +315,11 @@ impl MessageProcessor {
environment_manager,
thread_extensions(
guardian_agent_spawner(thread_manager.clone()),
- app_server_extension_event_sink(outgoing.clone()),
+ app_server_extension_event_sink(outgoing.clone(), thread_state_manager.clone()),
auth_manager.clone(),
+ state_db.clone(),
+ thread_manager.clone(),
+ Arc::clone(&goal_service),
),
Some(analytics_events_client.clone()),
Arc::clone(&thread_store),
@@ -416,6 +421,7 @@ impl MessageProcessor {
Arc::clone(&config),
thread_state_manager.clone(),
state_db.clone(),
+ Arc::clone(&goal_service),
);
let thread_processor = ThreadRequestProcessor::new(
auth_manager.clone(),
diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs
index 2e67e23398..ba75d0afd3 100644
--- a/codex-rs/app-server/src/outgoing_message.rs
+++ b/codex-rs/app-server/src/outgoing_message.rs
@@ -555,16 +555,6 @@ impl OutgoingMessageSender {
.await;
}
- pub(crate) fn try_send_server_notification(&self, notification: ServerNotification) {
- tracing::trace!("app-server event: {notification}");
- let outgoing_message = OutgoingMessage::AppServerNotification(notification);
- if let Err(err) = self.sender.try_send(OutgoingEnvelope::Broadcast {
- message: outgoing_message,
- }) {
- warn!("failed to send server notification to client without waiting: {err:?}");
- }
- }
-
pub(crate) async fn send_server_notification_to_connections(
&self,
connection_ids: &[ConnectionId],
diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs
index bfcf328c43..0266cb9d95 100644
--- a/codex-rs/app-server/src/request_processors.rs
+++ b/codex-rs/app-server/src/request_processors.rs
@@ -279,8 +279,6 @@ use codex_config::loader::project_trust_key;
use codex_config::types::McpServerTransportConfig;
use codex_core::CodexThread;
use codex_core::CodexThreadSettingsOverrides;
-use codex_core::ExternalGoalPreviousStatus;
-use codex_core::ExternalGoalSet;
use codex_core::ForkSnapshot;
use codex_core::NewThread;
#[cfg(test)]
diff --git a/codex-rs/app-server/src/request_processors/thread_goal_processor.rs b/codex-rs/app-server/src/request_processors/thread_goal_processor.rs
index c18806ea03..2f40ce6602 100644
--- a/codex-rs/app-server/src/request_processors/thread_goal_processor.rs
+++ b/codex-rs/app-server/src/request_processors/thread_goal_processor.rs
@@ -1,5 +1,9 @@
use super::*;
-use codex_protocol::protocol::validate_thread_goal_objective;
+use codex_goal_extension::GoalObjectiveUpdate;
+use codex_goal_extension::GoalService;
+use codex_goal_extension::GoalServiceError;
+use codex_goal_extension::GoalSetRequest;
+use codex_goal_extension::GoalTokenBudgetUpdate;
#[derive(Clone)]
pub(crate) struct ThreadGoalRequestProcessor {
@@ -8,6 +12,7 @@ pub(crate) struct ThreadGoalRequestProcessor {
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
+ goal_service: Arc<GoalService>,
}
impl ThreadGoalRequestProcessor {
@@ -17,6 +22,7 @@ impl ThreadGoalRequestProcessor {
config: Arc<Config>,
thread_state_manager: ThreadStateManager,
state_db: Option<StateDbHandle>,
+ goal_service: Arc<GoalService>,
) -> Self {
Self {
thread_manager,
@@ -24,6 +30,7 @@ impl ThreadGoalRequestProcessor {
config,
thread_state_manager,
state_db,
+ goal_service,
}
}
@@ -66,10 +73,8 @@ impl ThreadGoalRequestProcessor {
}
self.emit_thread_goal_snapshot(thread_id).await;
// App-server owns resume response and snapshot ordering, so wait until
- // those are sent before letting core start goal continuation.
- if let Err(err) = thread.continue_active_goal_if_idle().await {
- tracing::warn!("failed to continue active goal after resume: {err}");
- }
+ // those are sent before letting extensions react to the idle thread.
+ thread.emit_thread_idle_lifecycle_if_idle().await;
}
pub(crate) async fn pending_resume_goal_state(
@@ -100,140 +105,36 @@ impl ThreadGoalRequestProcessor {
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
- let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
- let rollout_path = match running_thread.as_ref() {
- Some(thread) => thread.rollout_path().ok_or_else(|| {
- invalid_request(format!(
- "ephemeral thread does not support goals: {thread_id}"
- ))
- })?,
- None => codex_rollout::find_thread_path_by_id_str(
- &self.config.codex_home,
- &thread_id.to_string(),
- self.state_db.as_deref(),
- )
- .await
- .map_err(|err| {
- internal_error(format!("failed to locate thread id {thread_id}: {err}"))
- })?
- .ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
- };
- reconcile_rollout(
- Some(&state_db),
- rollout_path.as_path(),
- self.config.model_provider_id.as_str(),
- /*builder*/ None,
- &[],
- /*archived_only*/ None,
- /*new_thread_memory_mode*/ None,
- )
- .await;
+ self.reconcile_thread_goal_rollout(thread_id, &state_db)
+ .await?;
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
- let status = params.status.map(thread_goal_status_to_state);
- let objective = params.objective.as_deref().map(str::trim);
-
- if let Some(objective) = objective {
- validate_thread_goal_objective(objective).map_err(invalid_request)?;
- }
- if objective.is_some() || params.token_budget.is_some() {
- validate_goal_budget(params.token_budget.flatten()).map_err(invalid_request)?;
- }
-
- if let Some(thread) = running_thread.as_ref() {
- thread.prepare_external_goal_mutation().await;
- }
+ let status = params.status.map(ThreadGoalStatus::to_core);
+ let objective = params.objective.as_deref();
- let should_set_thread_preview = objective.is_some();
- let (goal, previous_status) = (if let Some(objective) = objective {
- let existing_goal = state_db
- .thread_goals()
- .get_thread_goal(thread_id)
- .await
- .map_err(|err| invalid_request(err.to_string()))?;
- if let Some(goal) = existing_goal.as_ref() {
- let previous_status = ExternalGoalPreviousStatus::from(goal);
- state_db
- .thread_goals()
- .update_thread_goal(
- thread_id,
- codex_state::GoalUpdate {
- objective: Some(objective.to_string()),
- status,
- token_budget: params.token_budget,
- expected_goal_id: Some(goal.goal_id.clone()),
- },
- )
- .await
- .and_then(|goal| {
- goal.ok_or_else(|| {
- anyhow::anyhow!(
- "cannot update goal for thread {thread_id}: no goal exists"
- )
- })
- })
- .map(|goal| (goal, previous_status))
- } else {
- let previous_status = ExternalGoalPreviousStatus::NewGoal;
- state_db
- .thread_goals()
- .replace_thread_goal(
- thread_id,
- objective,
- status.unwrap_or(codex_state::ThreadGoalStatus::Active),
- params.token_budget.flatten(),
- )
- .await
- .map(|goal| (goal, previous_status))
- }
- } else {
- let existing_goal = state_db
- .thread_goals()
- .get_thread_goal(thread_id)
- .await
- .map_err(|err| invalid_request(err.to_string()))?;
- let Some(existing_goal) = existing_goal else {
- return Err(invalid_request(format!(
- "cannot update goal for thread {thread_id}: no goal exists"
- )));
- };
- let previous_status = ExternalGoalPreviousStatus::from(&existing_goal);
- state_db
- .thread_goals()
- .update_thread_goal(
+ let outcome = self
+ .goal_service
+ .set_thread_goal(
+ &state_db,
+ GoalSetRequest {
thread_id,
- codex_state::GoalUpdate {
- objective: None,
- status,
- token_budget: params.token_budget,
- expected_goal_id: None,
+ objective: objective
+ .map(GoalObjectiveUpdate::Set)
+ .unwrap_or(GoalObjectiveUpdate::Keep),
+ status,
+ token_budget: match params.token_budget {
+ Some(token_budget) => GoalTokenBudgetUpdate::Set(token_budget),
+ None => GoalTokenBudgetUpdate::Keep,
},
- )
- .await
- .and_then(|goal| {
- goal.ok_or_else(|| {
- anyhow::anyhow!("cannot update goal for thread {thread_id}: no goal exists")
- })
- })
- .map(|goal| (goal, previous_status))
- })
- .map_err(|err| invalid_request(err.to_string()))?;
- if should_set_thread_preview
- && let Err(err) = state_db
- .set_thread_preview_if_empty(thread_id, goal.objective.as_str())
- .await
- {
- warn!("failed to set empty thread preview from goal objective for {thread_id}: {err}");
- }
- let external_goal_set = ExternalGoalSet {
- goal: goal.clone(),
- previous_status,
- };
- let goal = api_thread_goal_from_state(goal);
+ },
+ )
+ .await
+ .map_err(goal_service_error)?;
+ let goal = ThreadGoal::from(outcome.goal.clone());
self.outgoing
.send_response(
request_id.clone(),
@@ -242,9 +143,7 @@ impl ThreadGoalRequestProcessor {
.await;
self.emit_thread_goal_updated_ordered(thread_id, goal, listener_command_tx)
.await;
- if let Some(thread) = running_thread.as_ref() {
- thread.apply_external_goal_set(external_goal_set).await;
- }
+ outcome.apply_runtime_effects(&self.goal_service).await;
Ok(())
}
@@ -258,12 +157,12 @@ impl ThreadGoalRequestProcessor {
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
- let goal = state_db
- .thread_goals()
- .get_thread_goal(thread_id)
+ let goal = self
+ .goal_service
+ .get_thread_goal(&state_db, thread_id)
.await
- .map_err(|err| internal_error(format!("failed to read thread goal: {err}")))?
- .map(api_thread_goal_from_state);
+ .map_err(goal_service_error)?
+ .map(ThreadGoal::from);
Ok(ThreadGoalGetResponse { goal })
}
@@ -278,53 +177,19 @@ impl ThreadGoalRequestProcessor {
let thread_id = parse_thread_id_for_request(params.thread_id.as_str())?;
let state_db = self.state_db_for_materialized_thread(thread_id).await?;
- let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
- let rollout_path = match running_thread.as_ref() {
- Some(thread) => thread.rollout_path().ok_or_else(|| {
- invalid_request(format!(
- "ephemeral thread does not support goals: {thread_id}"
- ))
- })?,
- None => codex_rollout::find_thread_path_by_id_str(
- &self.config.codex_home,
- &thread_id.to_string(),
- self.state_db.as_deref(),
- )
- .await
- .map_err(|err| {
- internal_error(format!("failed to locate thread id {thread_id}: {err}"))
- })?
- .ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
- };
- reconcile_rollout(
- Some(&state_db),
- rollout_path.as_path(),
- self.config.model_provider_id.as_str(),
- /*builder*/ None,
- &[],
- /*archived_only*/ None,
- /*new_thread_memory_mode*/ None,
- )
- .await;
-
- if let Some(thread) = running_thread.as_ref() {
- thread.prepare_external_goal_mutation().await;
- }
+ self.reconcile_thread_goal_rollout(thread_id, &state_db)
+ .await?;
let listener_command_tx = {
let thread_state = self.thread_state_manager.thread_state(thread_id).await;
let thread_state = thread_state.lock().await;
thread_state.listener_command_tx()
};
- let cleared = state_db
- .thread_goals()
- .delete_thread_goal(thread_id)
+ let cleared = self
+ .goal_service
+ .clear_thread_goal(&state_db, thread_id)
.await
- .map_err(|err| internal_error(format!("failed to clear thread goal: {err}")))?;
-
- if cleared && let Some(thread) = running_thread.as_ref() {
- thread.apply_external_goal_clear().await;
- }
+ .map_err(goal_service_error)?;
self.outgoing
.send_response(request_id, ThreadGoalClearResponse { cleared })
@@ -367,6 +232,42 @@ impl ThreadGoalRequestProcessor {
.ok_or_else(|| internal_error("sqlite state db unavailable for thread goals"))
}
+ async fn reconcile_thread_goal_rollout(
+ &self,
+ thread_id: ThreadId,
+ state_db: &StateDbHandle,
+ ) -> Result<(), JSONRPCErrorError> {
+ let running_thread = self.thread_manager.get_thread(thread_id).await.ok();
+ let rollout_path = match running_thread.as_ref() {
+ Some(thread) => thread.rollout_path().ok_or_else(|| {
+ invalid_request(format!(
+ "ephemeral thread does not support goals: {thread_id}"
+ ))
+ })?,
+ None => codex_rollout::find_thread_path_by_id_str(
+ &self.config.codex_home,
+ &thread_id.to_string(),
+ self.state_db.as_deref(),
+ )
+ .await
+ .map_err(|err| {
+ internal_error(format!("failed to locate thread id {thread_id}: {err}"))
+ })?
+ .ok_or_else(|| invalid_request(format!("thread not found: {thread_id}")))?,
+ };
+ reconcile_rollout(
+ Some(state_db),
+ rollout_path.as_path(),
+ self.config.model_provider_id.as_str(),
+ /*builder*/ None,
+ &[],
+ /*archived_only*/ None,
+ /*new_thread_memory_mode*/ None,
+ )
+ .await;
+ Ok(())
+ }
+
async fn emit_thread_goal_snapshot(&self, thread_id: ThreadId) {
let state_db = match self.state_db_for_materialized_thread(thread_id).await {
Ok(state_db) => state_db,
@@ -405,6 +306,7 @@ impl ThreadGoalRequestProcessor {
) {
if let Some(listener_command_tx) = listener_command_tx {
let command = crate::thread_state::ThreadListenerCommand::EmitThreadGoalUpdated {
+ turn_id: None,
goal: goal.clone(),
};
if listener_command_tx.send(command).is_ok() {
@@ -449,27 +351,20 @@ impl ThreadGoalRequestProcessor {
}
}
-fn validate_goal_budget(value: Option<i64>) -> Result<(), String> {
- if let Some(value) = value
- && value <= 0
- {
- return Err("goal budgets must be positive when provided".to_string());
- }
- Ok(())
-}
-
-fn thread_goal_status_to_state(status: ThreadGoalStatus) -> codex_state::ThreadGoalStatus {
- match status {
- ThreadGoalStatus::Active => codex_state::ThreadGoalStatus::Active,
- ThreadGoalStatus::Paused => codex_state::ThreadGoalStatus::Paused,
- ThreadGoalStatus::Blocked => codex_state::ThreadGoalStatus::Blocked,
- ThreadGoalStatus::UsageLimited => codex_state::ThreadGoalStatus::UsageLimited,
- ThreadGoalStatus::BudgetLimited => codex_state::ThreadGoalStatus::BudgetLimited,
- ThreadGoalStatus::Complete => codex_state::ThreadGoalStatus::Complete,
+pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
+ ThreadGoal {
+ thread_id: goal.thread_id.to_string(),
+ objective: goal.objective,
+ status: api_thread_goal_status_from_state(goal.status),
+ token_budget: goal.token_budget,
+ tokens_used: goal.tokens_used,
+ time_used_seconds: goal.time_used_seconds,
+ created_at: goal.created_at.timestamp(),
+ updated_at: goal.updated_at.timestamp(),
}
}
-fn thread_goal_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGoalStatus {
+fn api_thread_goal_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGoalStatus {
match status {
codex_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
codex_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
@@ -480,16 +375,10 @@ fn thread_goal_status_from_state(status: codex_state::ThreadGoalStatus) -> Threa
}
}
-pub(super) fn api_thread_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
- ThreadGoal {
- thread_id: goal.thread_id.to_string(),
- objective: goal.objective,
- status: thread_goal_status_from_state(goal.status),
- token_budget: goal.token_budget,
- tokens_used: goal.tokens_used,
- time_used_seconds: goal.time_used_seconds,
- created_at: goal.created_at.timestamp(),
- updated_at: goal.updated_at.timestamp(),
+fn goal_service_error(err: GoalServiceError) -> JSONRPCErrorError {
+ match err {
+ GoalServiceError::InvalidRequest(message) => invalid_request(message),
+ GoalServiceError::Internal(message) => internal_error(message),
}
}
diff --git a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
index f72cfb5a62..8bfb282ace 100644
--- a/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
+++ b/codex-rs/app-server/src/request_processors/thread_lifecycle.rs
@@ -244,12 +244,22 @@ pub(super) async fn ensure_listener_task_running(
if thread_state.listener_matches(&conversation) {
return Ok(());
}
- thread_state.set_listener(
+ let (listener_command_rx, listener_generation) = thread_state.set_listener(
cancel_tx,
&conversation,
watch_registration,
thread_settings_baseline,
- )
+ );
+ let Some(listener_command_tx) = thread_state.listener_command_tx() else {
+ tracing::warn!(
+ "thread listener command sender missing immediately after listener registration"
+ );
+ return Ok(());
+ };
+ listener_task_context
+ .thread_state_manager
+ .register_listener_command_tx(conversation_id, listener_command_tx);
+ (listener_command_rx, listener_generation)
};
let ListenerTaskContext {
outgoing,
@@ -378,6 +388,7 @@ pub(super) async fn ensure_listener_task_running(
let mut thread_state = thread_state.lock().await;
if thread_state.listener_generation == listener_generation {
+ thread_state_manager.unregister_listener_command_tx(conversation_id);
thread_state.clear_listener();
}
});
@@ -471,12 +482,12 @@ pub(super) async fn handle_thread_listener_command(
)
.await;
}
- ThreadListenerCommand::EmitThreadGoalUpdated { goal } => {
+ ThreadListenerCommand::EmitThreadGoalUpdated { turn_id, goal } => {
outgoing
.send_server_notification(ServerNotification::ThreadGoalUpdated(
ThreadGoalUpdatedNotification {
thread_id: conversation_id.to_string(),
- turn_id: None,
+ turn_id,
goal,
},
))
@@ -616,12 +627,6 @@ pub(super) async fn handle_pending_thread_resume_request(
}
}
- if pending.emit_thread_goal_update
- && let Err(err) = conversation.apply_goal_resume_runtime_effects().await
- {
- tracing::warn!("failed to apply goal resume runtime effects: {err}");
- }
-
let ThreadConfigSnapshot {
model,
model_provider_id,
@@ -691,11 +696,9 @@ pub(super) async fn handle_pending_thread_resume_request(
.replay_requests_to_connection_for_thread(connection_id, conversation_id)
.await;
// App-server owns resume response and snapshot ordering, so wait until
- // replay completes before letting core start goal continuation.
- if pending.emit_thread_goal_update
- && let Err(err) = conversation.continue_active_goal_if_idle().await
- {
- tracing::warn!("failed to continue active goal after running-thread resume: {err}");
+ // replay completes before letting extensions react to the idle thread.
+ if pending.emit_thread_goal_update {
+ conversation.emit_thread_idle_lifecycle_if_idle().await;
}
}
diff --git a/codex-rs/app-server/src/thread_state.rs b/codex-rs/app-server/src/thread_state.rs
index 2d932f0326..6d2b48a4c8 100644
--- a/codex-rs/app-server/src/thread_state.rs
+++ b/codex-rs/app-server/src/thread_state.rs
@@ -17,6 +17,7 @@ use codex_utils_absolute_path::AbsolutePathBuf;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
+use std::sync::Mutex as StdMutex;
use std::sync::Weak;
use tokio::sync::Mutex;
use tokio::sync::mpsc;
@@ -44,8 +45,9 @@ pub(crate) struct PendingThreadResumeRequest {
pub(crate) enum ThreadListenerCommand {
// SendThreadResumeResponse is used to resume an already running thread by sending the thread's history to the client and atomically subscribing for new updates.
SendThreadResumeResponse(Box<PendingThreadResumeRequest>),
- // EmitThreadGoalUpdated is used to order app-server goal updates with running-thread resume responses.
+ // EmitThreadGoalUpdated is used to order goal updates with running-thread resume responses and goal clears.
EmitThreadGoalUpdated {
+ turn_id: Option<String>,
goal: ThreadGoal,
},
// EmitThreadGoalCleared is used to order app-server goal clears with running-thread resume responses.
@@ -284,6 +286,10 @@ pub(crate) struct ConnectionCapabilities {
#[derive(Clone, Default)]
pub(crate) struct ThreadStateManager {
state: Arc<Mutex<ThreadStateManagerInner>>,
+ // Extension event sinks are synchronous, so they need an await-free way to
+ // enqueue work on the active per-thread listener.
+ listener_commands:
+ Arc<StdMutex<HashMap<ThreadId, mpsc::UnboundedSender<ThreadListenerCommand>>>>,
}
impl ThreadStateManager {
@@ -337,6 +343,35 @@ impl ThreadStateManager {
state.threads.entry(thread_id).or_default().state.clone()
}
+ pub(crate) fn current_listener_command_tx(
+ &self,
+ thread_id: ThreadId,
+ ) -> Option<mpsc::UnboundedSender<ThreadListenerCommand>> {
+ self.listener_commands
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(&thread_id)
+ .cloned()
+ }
+
+ pub(crate) fn register_listener_command_tx(
+ &self,
+ thread_id: ThreadId,
+ tx: mpsc::UnboundedSender<ThreadListenerCommand>,
+ ) {
+ self.listener_commands
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(thread_id, tx);
+ }
+
+ pub(crate) fn unregister_listener_command_tx(&self, thread_id: ThreadId) {
+ self.listener_commands
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .remove(&thread_id);
+ }
+
pub(crate) async fn remove_thread_state(&self, thread_id: ThreadId) {
let thread_state = {
let mut state = self.state.lock().await;
@@ -350,6 +385,7 @@ impl ThreadStateManager {
});
thread_state
};
+ self.unregister_listener_command_tx(thread_id);
if let Some(thread_state) = thread_state {
let mut thread_state = thread_state.lock().await;
@@ -375,6 +411,7 @@ impl ThreadStateManager {
};
for (thread_id, thread_state) in thread_states {
+ self.unregister_listener_command_tx(thread_id);
let mut thread_state = thread_state.lock().await;
tracing::debug!(
thread_id = %thread_id,
diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs
index d87b65e8ae..b3f9cb0e2e 100644
--- a/codex-rs/core/src/codex_thread.rs
+++ b/codex-rs/core/src/codex_thread.rs
@@ -1,7 +1,5 @@
use crate::agent::AgentStatus;
use crate::config::ConstraintResult;
-use crate::goals::ExternalGoalSet;
-use crate::goals::GoalRuntimeEvent;
use crate::session::Codex;
use crate::session::SessionSettingsUpdate;
use crate::session::SteerInputError;
@@ -205,51 +203,11 @@ impl CodexThread {
}
}
- pub async fn apply_goal_resume_runtime_effects(&self) -> anyhow::Result<()> {
+ pub async fn emit_thread_idle_lifecycle_if_idle(&self) {
self.codex
.session
- .goal_runtime_apply(GoalRuntimeEvent::ThreadResumed)
- .await
- }
-
- pub async fn continue_active_goal_if_idle(&self) -> anyhow::Result<()> {
- self.codex
- .session
- .goal_runtime_apply(GoalRuntimeEvent::MaybeContinueIfIdle)
- .await
- }
-
- pub async fn prepare_external_goal_mutation(&self) {
- if let Err(err) = self
- .codex
- .session
- .goal_runtime_apply(GoalRuntimeEvent::ExternalMutationStarting)
- .await
- {
- tracing::warn!("failed to prepare external goal mutation: {err}");
- }
- }
-
- pub async fn apply_external_goal_set(&self, external_set: ExternalGoalSet) {
- if let Err(err) = self
- .codex
- .session
- .goal_runtime_apply(GoalRuntimeEvent::ExternalSet { external_set })
- .await
- {
- tracing::warn!("failed to apply external goal status runtime effects: {err}");
- }
- }
-
- pub async fn apply_external_goal_clear(&self) {
- if let Err(err) = self
- .codex
- .session
- .goal_runtime_apply(GoalRuntimeEvent::ExternalClear)
- .await
- {
- tracing::warn!("failed to apply external goal clear runtime effects: {err}");
- }
+ .emit_thread_idle_lifecycle_if_idle()
+ .await;
}
#[doc(hidden)]
diff --git a/codex-rs/core/src/context/contextual_user_message_tests.rs b/codex-rs/core/src/context/contextual_user_message_tests.rs
index dc7cb0f534..c3f360772a 100644
--- a/codex-rs/core/src/context/contextual_user_message_tests.rs
+++ b/codex-rs/core/src/context/contextual_user_message_tests.rs
@@ -33,14 +33,14 @@ fn detects_subagent_notification_fragment_case_insensitively() {
#[test]
fn detects_internal_model_context_fragment() {
let text = InternalModelContextFragment::new(
- InternalContextSource::from_static("goal"),
- "Continue working toward the active thread goal.",
+ InternalContextSource::from_static("extension"),
+ "Internal steering.",
)
.render();
assert_eq!(
text,
- "<codex_internal_context source=\"goal\">\nContinue working toward the active thread goal.\n</codex_internal_context>"
+ "<codex_internal_context source=\"extension\">\nInternal steering.\n</codex_internal_context>"
);
assert!(is_contextual_user_fragment(&ContentItem::InputText {
text
@@ -65,7 +65,7 @@ fn does_not_hide_arbitrary_context_tags() {
#[test]
fn rejects_invalid_internal_model_context_source() {
assert!(!is_contextual_user_fragment(&ContentItem::InputText {
- text: "<codex_internal_context source=\"Goal\">\nbody\n</codex_internal_context>"
+ text: "<codex_internal_context source=\"Extension\">\nbody\n</codex_internal_context>"
.to_string(),
}));
}
@@ -73,13 +73,13 @@ fn rejects_invalid_internal_model_context_source() {
#[test]
fn contextual_user_fragment_is_dyn_compatible() {
let fragment: Box<dyn ContextualUserFragment> = Box::new(InternalModelContextFragment::new(
- InternalContextSource::from_static("goal"),
- "Continue working toward the active thread goal.",
+ InternalContextSource::from_static("extension"),
+ "Internal steering.",
));
assert_eq!(
fragment.render(),
- "<codex_internal_context source=\"goal\">\nContinue working toward the active thread goal.\n</codex_internal_context>"
+ "<codex_internal_context source=\"extension\">\nInternal steering.\n</codex_internal_context>"
);
}
diff --git a/codex-rs/core/src/event_mapping_tests.rs b/codex-rs/core/src/event_mapping_tests.rs
index 4cf1b72d5d..5f2ed66830 100644
--- a/codex-rs/core/src/event_mapping_tests.rs
+++ b/codex-rs/core/src/event_mapping_tests.rs
@@ -324,8 +324,8 @@ fn internal_model_context_does_not_parse_as_visible_turn_item() {
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: InternalModelContextFragment::new(
- InternalContextSource::from_static("goal"),
- "Continue working toward the active thread goal.",
+ InternalContextSource::from_static("extension"),
+ "Internal steering.",
)
.render(),
}],
diff --git a/codex-rs/core/src/goals.rs b/codex-rs/core/src/goals.rs
deleted file mode 100644
index 6e0663655c..0000000000
--- a/codex-rs/core/src/goals.rs
+++ /dev/null
@@ -1,1622 +0,0 @@
-//! Core support for persisted thread goals.
-//!
-//! This module bridges core sessions and the state-db goal table. It validates
-//! goal mutations, converts between state and protocol shapes, emits goal-update
-//! events, and owns helper hooks used by goal lifecycle behavior.
-
-use crate::StateDbHandle;
-use crate::context::ContextualUserFragment;
-use crate::context::InternalContextSource;
-use crate::context::InternalModelContextFragment;
-use crate::session::TurnInput;
-use crate::session::session::Session;
-use crate::session::turn_context::TurnContext;
-use crate::state::ActiveTurn;
-use crate::state::TurnState;
-use crate::tasks::RegularTask;
-use crate::tools::handlers::goal_spec::UPDATE_GOAL_TOOL_NAME;
-use anyhow::Context;
-use codex_features::Feature;
-use codex_otel::GOAL_BLOCKED_METRIC;
-use codex_otel::GOAL_BUDGET_LIMITED_METRIC;
-use codex_otel::GOAL_COMPLETED_METRIC;
-use codex_otel::GOAL_CREATED_METRIC;
-use codex_otel::GOAL_DURATION_SECONDS_METRIC;
-use codex_otel::GOAL_RESUMED_METRIC;
-use codex_otel::GOAL_TOKEN_COUNT_METRIC;
-use codex_otel::GOAL_USAGE_LIMITED_METRIC;
-use codex_prompts::budget_limit_prompt;
-use codex_prompts::continuation_prompt;
-use codex_prompts::objective_updated_prompt;
-use codex_protocol::ThreadId;
-use codex_protocol::config_types::ModeKind;
-use codex_protocol::models::ResponseItem;
-use codex_protocol::protocol::EventMsg;
-use codex_protocol::protocol::ThreadGoal;
-use codex_protocol::protocol::ThreadGoalStatus;
-use codex_protocol::protocol::ThreadGoalUpdatedEvent;
-use codex_protocol::protocol::TokenUsage;
-use codex_protocol::protocol::validate_thread_goal_objective;
-use codex_rollout::state_db::reconcile_rollout;
-use codex_thread_store::LocalThreadStore;
-use futures::future::BoxFuture;
-use std::sync::Arc;
-use std::time::Duration;
-use std::time::Instant;
-use tokio::sync::Mutex;
-use tokio::sync::Semaphore;
-use tokio::sync::SemaphorePermit;
-
-pub(crate) struct SetGoalRequest {
- pub(crate) objective: Option<String>,
- pub(crate) status: Option<ThreadGoalStatus>,
- pub(crate) token_budget: Option<Option<i64>>,
-}
-
-pub(crate) struct CreateGoalRequest {
- pub(crate) objective: String,
- pub(crate) token_budget: Option<i64>,
-}
-
-#[derive(Clone, Copy)]
-enum BudgetLimitSteering {
- Allowed,
- Suppressed,
-}
-
-#[derive(Clone, Copy)]
-enum TerminalMetricEmission {
- Emit,
- Suppress,
-}
-
-/// Describes whether an external goal mutation created a new logical goal or
-/// updated an existing one.
-#[derive(Clone)]
-pub enum ExternalGoalPreviousStatus {
- NewGoal,
- Existing(ExternalGoalPreviousGoal),
-}
-
-#[derive(Clone)]
-pub struct ExternalGoalPreviousGoal {
- goal_id: String,
- status: codex_state::ThreadGoalStatus,
- objective: String,
-}
-
-impl From<&codex_state::ThreadGoal> for ExternalGoalPreviousStatus {
- fn from(goal: &codex_state::ThreadGoal) -> Self {
- Self::Existing(ExternalGoalPreviousGoal::from(goal))
- }
-}
-
-impl From<&codex_state::ThreadGoal> for ExternalGoalPreviousGoal {
- fn from(goal: &codex_state::ThreadGoal) -> Self {
- Self {
- goal_id: goal.goal_id.clone(),
- status: goal.status,
- objective: goal.objective.clone(),
- }
- }
-}
-
-/// Runtime effects for an externally persisted goal mutation.
-#[derive(Clone)]
-pub struct ExternalGoalSet {
- pub goal: codex_state::ThreadGoal,
- pub previous_status: ExternalGoalPreviousStatus,
-}
-
-/// Runtime lifecycle events that can affect goal accounting, scheduling, or
-/// model-visible steering.
-///
-/// Callers report the session event they observed; this module owns the policy
-/// for how that event changes goal runtime state.
-pub(crate) enum GoalRuntimeEvent<'a> {
- TurnStarted {
- turn_context: &'a TurnContext,
- token_usage: TokenUsage,
- },
- ToolCompleted {
- turn_context: &'a TurnContext,
- tool_name: &'a str,
- },
- ToolCompletedGoal {
- turn_context: &'a TurnContext,
- },
- TurnFinished {
- turn_context: &'a TurnContext,
- turn_completed: bool,
- },
- MaybeContinueIfIdle,
- TaskAborted {
- turn_context: Option<&'a TurnContext>,
- },
- UsageLimitReached {
- turn_context: &'a TurnContext,
- },
- ExternalMutationStarting,
- ExternalSet {
- external_set: ExternalGoalSet,
- },
- ExternalClear,
- ThreadResumed,
-}
-
-pub(crate) struct GoalRuntimeState {
- pub(crate) state_db: Mutex<Option<StateDbHandle>>,
- pub(crate) budget_limit_reported_goal_id: Mutex<Option<String>>,
- accounting_lock: Semaphore,
- accounting: Mutex<GoalAccountingSnapshot>,
- pub(crate) continuation_lock: Semaphore,
-}
-
-struct GoalContinuationCandidate {
- goal_id: String,
- items: Vec<ResponseItem>,
-}
-
-impl GoalRuntimeState {
- pub(crate) fn new() -> Self {
- Self {
- state_db: Mutex::new(None),
- budget_limit_reported_goal_id: Mutex::new(None),
- accounting_lock: Semaphore::new(/*permits*/ 1),
- accounting: Mutex::new(GoalAccountingSnapshot::new()),
- continuation_lock: Semaphore::new(/*permits*/ 1),
- }
- }
-}
-
-#[derive(Debug)]
-struct GoalAccountingSnapshot {
- turn: Option<GoalTurnAccountingSnapshot>,
- wall_clock: GoalWallClockAccountingSnapshot,
-}
-
-#[derive(Debug)]
-struct GoalTurnAccountingSnapshot {
- turn_id: String,
- last_accounted_token_usage: TokenUsage,
- active_goal_id: Option<String>,
-}
-
-impl GoalRuntimeState {
- async fn accounting_permit(&self) -> anyhow::Result<SemaphorePermit<'_>> {
- self.accounting_lock
- .acquire()
- .await
- .context("goal accounting semaphore closed")
- }
-}
-
-impl GoalAccountingSnapshot {
- fn new() -> Self {
- Self {
- turn: None,
- wall_clock: GoalWallClockAccountingSnapshot::new(),
- }
- }
-}
-
-impl GoalTurnAccountingSnapshot {
- fn new(turn_id: impl Into<String>, token_usage: TokenUsage) -> Self {
- Self {
- turn_id: turn_id.into(),
- last_accounted_token_usage: token_usage,
- active_goal_id: None,
- }
- }
-
- fn mark_active_goal(&mut self, goal_id: impl Into<String>) {
- self.active_goal_id = Some(goal_id.into());
- }
-
- fn active_this_turn(&self) -> bool {
- self.active_goal_id.is_some()
- }
-
- fn active_goal_id(&self) -> Option<String> {
- self.active_goal_id.clone()
- }
-
- fn clear_active_goal(&mut self) {
- self.active_goal_id = None;
- }
-
- fn reset_baseline(&mut self, token_usage: TokenUsage) {
- self.last_accounted_token_usage = token_usage;
- }
-
- fn token_delta_since_last_accounting(&self, current: &TokenUsage) -> i64 {
- let last = &self.last_accounted_token_usage;
- let delta = TokenUsage {
- input_tokens: current.input_tokens.saturating_sub(last.input_tokens),
- cached_input_tokens: current
- .cached_input_tokens
- .saturating_sub(last.cached_input_tokens),
- output_tokens: current.output_tokens.saturating_sub(last.output_tokens),
- reasoning_output_tokens: current
- .reasoning_output_tokens
- .saturating_sub(last.reasoning_output_tokens),
- total_tokens: current.total_tokens.saturating_sub(last.total_tokens),
- };
- goal_token_delta_for_usage(&delta)
- }
-
- fn mark_accounted(&mut self, current: TokenUsage) {
- self.last_accounted_token_usage = current;
- }
-}
-
-#[derive(Debug)]
-struct GoalWallClockAccountingSnapshot {
- last_accounted_at: Instant,
- active_goal_id: Option<String>,
-}
-
-impl GoalWallClockAccountingSnapshot {
- fn new() -> Self {
- Self {
- last_accounted_at: Instant::now(),
- active_goal_id: None,
- }
- }
-
- fn time_delta_since_last_accounting(&self) -> i64 {
- let last = self.last_accounted_at;
- i64::try_from(last.elapsed().as_secs()).unwrap_or(i64::MAX)
- }
-
- fn mark_accounted(&mut self, accounted_seconds: i64) {
- if accounted_seconds <= 0 {
- return;
- }
- let advance = Duration::from_secs(u64::try_from(accounted_seconds).unwrap_or(u64::MAX));
- self.last_accounted_at = self
- .last_accounted_at
- .checked_add(advance)
- .unwrap_or_else(Instant::now);
- }
-
- fn reset_baseline(&mut self) {
- self.last_accounted_at = Instant::now();
- }
-
- fn mark_active_goal(&mut self, goal_id: impl Into<String>) {
- let goal_id = goal_id.into();
- if self.active_goal_id.as_deref() != Some(goal_id.as_str()) {
- self.reset_baseline();
- self.active_goal_id = Some(goal_id);
- }
- }
-
- fn clear_active_goal(&mut self) {
- self.active_goal_id = None;
- self.reset_baseline();
- }
-
- fn active_goal_id(&self) -> Option<String> {
- self.active_goal_id.clone()
- }
-}
-
-impl Session {
- /// Applies runtime policy for a goal lifecycle event.
- ///
- /// Goal data methods validate and persist state; this dispatcher owns the
- /// cross-cutting runtime behavior: plan mode ignores continuations, turn
- /// starts capture the active goal and token baseline, tool completions
- /// account usage and may inject budget steering, completion accounting
- /// suppresses that steering, external mutations account best-effort before
- /// changing state, thread resumes restore runtime state for already-active
- /// goals, explicit maybe-continue events
- /// start idle goal continuation turns, and continuation turns with no counted
- /// autonomous activity suppress the next automatic continuation until
- /// user/tool/external activity resets it.
- pub(crate) fn goal_runtime_apply<'a>(
- self: &'a Arc<Self>,
- event: GoalRuntimeEvent<'a>,
- ) -> BoxFuture<'a, anyhow::Result<()>> {
- match event {
- GoalRuntimeEvent::TurnStarted {
- turn_context,
- token_usage,
- } => Box::pin(async move {
- self.mark_thread_goal_turn_started(turn_context, token_usage)
- .await;
- Ok(())
- }),
- GoalRuntimeEvent::ToolCompleted {
- turn_context,
- tool_name,
- } => Box::pin(async move {
- if tool_name != UPDATE_GOAL_TOOL_NAME {
- self.account_thread_goal_progress(
- turn_context,
- BudgetLimitSteering::Allowed,
- TerminalMetricEmission::Emit,
- )
- .await?;
- }
- Ok(())
- }),
- GoalRuntimeEvent::ToolCompletedGoal { turn_context } => Box::pin(async move {
- self.account_thread_goal_progress(
- turn_context,
- BudgetLimitSteering::Suppressed,
- TerminalMetricEmission::Suppress,
- )
- .await?;
- Ok(())
- }),
- GoalRuntimeEvent::TurnFinished {
- turn_context,
- turn_completed,
- } => Box::pin(async move {
- self.finish_thread_goal_turn(turn_context, turn_completed)
- .await;
- Ok(())
- }),
- GoalRuntimeEvent::MaybeContinueIfIdle => Box::pin(async move {
- self.maybe_continue_goal_if_idle_runtime().await;
- Ok(())
- }),
- GoalRuntimeEvent::TaskAborted { turn_context } => Box::pin(async move {
- self.handle_thread_goal_task_abort(turn_context).await;
- Ok(())
- }),
- GoalRuntimeEvent::UsageLimitReached { turn_context } => Box::pin(async move {
- self.usage_limit_active_thread_goal_for_turn(turn_context)
- .await?;
- Ok(())
- }),
- GoalRuntimeEvent::ExternalMutationStarting => Box::pin(async move {
- if let Err(err) = self.account_thread_goal_before_external_mutation().await {
- tracing::warn!(
- "failed to account thread goal progress before external mutation: {err}"
- );
- }
- Ok(())
- }),
- GoalRuntimeEvent::ExternalSet { external_set } => Box::pin(async move {
- self.apply_external_thread_goal_status(external_set).await;
- Ok(())
- }),
- GoalRuntimeEvent::ExternalClear => Box::pin(async move {
- self.clear_stopped_thread_goal_runtime_state().await;
- Ok(())
- }),
- GoalRuntimeEvent::ThreadResumed => Box::pin(async move {
- self.restore_thread_goal_runtime_after_resume().await?;
- Ok(())
- }),
- }
- }
-
- pub(crate) async fn get_thread_goal(&self) -> anyhow::Result<Option<ThreadGoal>> {
- if !self.enabled(Feature::Goals) {
- anyhow::bail!("goals feature is disabled");
- }
-
- let state_db = self.require_state_db_for_thread_goals().await?;
- state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await
- .map(|goal| goal.map(protocol_goal_from_state))
- }
-
- pub(crate) async fn set_thread_goal(
- &self,
- turn_context: &TurnContext,
- request: SetGoalRequest,
- ) -> anyhow::Result<ThreadGoal> {
- if !self.enabled(Feature::Goals) {
- anyhow::bail!("goals feature is disabled");
- }
-
- let SetGoalRequest {
- objective,
- status,
- token_budget,
- } = request;
- validate_goal_budget(token_budget.flatten())?;
- let state_db = self.require_state_db_for_thread_goals().await?;
- let objective = objective.map(|objective| objective.trim().to_string());
- if let Some(objective) = objective.as_deref()
- && let Err(err) = validate_thread_goal_objective(objective)
- {
- anyhow::bail!("{err}");
- }
-
- self.account_thread_goal_wall_clock_usage(
- &state_db,
- codex_state::GoalAccountingMode::ActiveOnly,
- TerminalMetricEmission::Emit,
- )
- .await?;
- let mut replacing_goal = false;
- let previous_status;
- let goal = if let Some(objective) = objective.as_deref() {
- let existing_goal = state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await?;
- previous_status = existing_goal.as_ref().map(|goal| goal.status);
- if let Some(existing_goal) = existing_goal.as_ref() {
- state_db
- .thread_goals()
- .update_thread_goal(
- self.thread_id,
- codex_state::GoalUpdate {
- objective: Some(objective.to_string()),
- status: status.map(state_goal_status_from_protocol),
- token_budget,
- expected_goal_id: Some(existing_goal.goal_id.clone()),
- },
- )
- .await?
- .ok_or_else(|| {
- anyhow::anyhow!(
- "cannot update goal for thread {}: no goal exists",
- self.thread_id
- )
- })?
- } else {
- replacing_goal = true;
- state_db
- .thread_goals()
- .replace_thread_goal(
- self.thread_id,
- objective,
- status
- .map(state_goal_status_from_protocol)
- .unwrap_or(codex_state::ThreadGoalStatus::Active),
- token_budget.flatten(),
- )
- .await?
- }
- } else {
- let existing_goal = state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await?;
- previous_status = existing_goal.as_ref().map(|goal| goal.status);
- let expected_goal_id = existing_goal.map(|goal| goal.goal_id);
- let status = status.map(state_goal_status_from_protocol);
- state_db
- .thread_goals()
- .update_thread_goal(
- self.thread_id,
- codex_state::GoalUpdate {
- objective: None,
- status,
- token_budget,
- expected_goal_id,
- },
- )
- .await?
- .ok_or_else(|| {
- anyhow::anyhow!(
- "cannot update goal for thread {}: no goal exists",
- self.thread_id
- )
- })?
- };
-
- if objective.is_some() {
- set_thread_preview_from_goal_objective(
- &state_db,
- self.thread_id,
- goal.objective.as_str(),
- )
- .await;
- }
- let goal_status = goal.status;
- let goal_id = goal.goal_id.clone();
- let previous_status_for_goal = if replacing_goal {
- None
- } else {
- previous_status
- };
- if replacing_goal {
- self.emit_goal_created_metric();
- }
- self.emit_goal_resumed_metric_if_status_changed(previous_status_for_goal, goal_status);
- self.emit_goal_terminal_metrics_if_status_changed(previous_status_for_goal, &goal);
- let goal = protocol_goal_from_state(goal);
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
- let newly_active_goal = goal_status == codex_state::ThreadGoalStatus::Active
- && (replacing_goal
- || previous_status
- .is_some_and(|status| status != codex_state::ThreadGoalStatus::Active));
- if newly_active_goal {
- let current_token_usage = self.total_token_usage().await.unwrap_or_default();
- self.mark_active_goal_accounting(
- goal_id,
- Some(turn_context.sub_id.clone()),
- current_token_usage,
- )
- .await;
- } else if goal_status != codex_state::ThreadGoalStatus::Active {
- self.clear_active_goal_accounting(turn_context).await;
- }
- self.send_event(
- turn_context,
- EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
- thread_id: self.thread_id,
- turn_id: Some(turn_context.sub_id.clone()),
- goal: goal.clone(),
- }),
- )
- .await;
- Ok(goal)
- }
-
- pub(crate) async fn create_thread_goal(
- &self,
- turn_context: &TurnContext,
- request: CreateGoalRequest,
- ) -> anyhow::Result<ThreadGoal> {
- if !self.enabled(Feature::Goals) {
- anyhow::bail!("goals feature is disabled");
- }
-
- let CreateGoalRequest {
- objective,
- token_budget,
- } = request;
- validate_goal_budget(token_budget)?;
- let objective = objective.trim();
- validate_thread_goal_objective(objective).map_err(anyhow::Error::msg)?;
-
- let state_db = self.require_state_db_for_thread_goals().await?;
- self.account_thread_goal_wall_clock_usage(
- &state_db,
- codex_state::GoalAccountingMode::ActiveOnly,
- TerminalMetricEmission::Emit,
- )
- .await?;
- let goal = state_db
- .thread_goals()
- .insert_thread_goal(
- self.thread_id,
- objective,
- codex_state::ThreadGoalStatus::Active,
- token_budget,
- )
- .await?
- .ok_or_else(|| {
- anyhow::anyhow!(
- "cannot create a new goal because thread {} already has a goal",
- self.thread_id
- )
- })?;
-
- set_thread_preview_from_goal_objective(&state_db, self.thread_id, goal.objective.as_str())
- .await;
- let goal_id = goal.goal_id.clone();
- self.emit_goal_created_metric();
- let goal = protocol_goal_from_state(goal);
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
-
- let current_token_usage = self.total_token_usage().await.unwrap_or_default();
- self.mark_active_goal_accounting(
- goal_id,
- Some(turn_context.sub_id.clone()),
- current_token_usage,
- )
- .await;
-
- self.send_event(
- turn_context,
- EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
- thread_id: self.thread_id,
- turn_id: Some(turn_context.sub_id.clone()),
- goal: goal.clone(),
- }),
- )
- .await;
- Ok(goal)
- }
-
- async fn apply_external_thread_goal_status(self: &Arc<Self>, external_set: ExternalGoalSet) {
- let ExternalGoalSet {
- goal,
- previous_status,
- } = external_set;
- let previous_goal = match previous_status {
- ExternalGoalPreviousStatus::NewGoal => None,
- ExternalGoalPreviousStatus::Existing(goal) => Some(goal),
- };
- let replaced_existing_goal = previous_goal
- .as_ref()
- .is_some_and(|previous_goal| previous_goal.goal_id != goal.goal_id);
- if previous_goal.is_none() || replaced_existing_goal {
- self.emit_goal_created_metric();
- }
- let objective_changed = previous_goal
- .as_ref()
- .is_some_and(|previous_goal| previous_goal.objective != goal.objective);
- let previous_status = previous_goal
- .as_ref()
- .and_then(|previous_goal| (!replaced_existing_goal).then_some(previous_goal.status));
- self.emit_goal_resumed_metric_if_status_changed(previous_status, goal.status);
- self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
- let goal_for_steering = objective_changed.then(|| protocol_goal_from_state(goal.clone()));
- let goal_id = goal.goal_id;
- let status = goal.status;
- match status {
- codex_state::ThreadGoalStatus::Active => {
- let turn_id = self
- .active_turn_context()
- .await
- .map(|turn_context| turn_context.sub_id.clone());
- let current_token_usage = self.total_token_usage().await.unwrap_or_default();
- self.mark_active_goal_accounting(goal_id, turn_id, current_token_usage)
- .await;
- if let Some(goal) = goal_for_steering {
- let item = goal_context_input_item(objective_updated_prompt(&goal));
- if self.inject_if_running(vec![item]).await.is_err() {
- tracing::debug!(
- "skipping objective-updated goal steering because no turn is active"
- );
- }
- }
- self.maybe_continue_goal_if_idle_runtime().await;
- }
- codex_state::ThreadGoalStatus::BudgetLimited => {
- if self.active_turn_context().await.is_none() {
- self.clear_stopped_thread_goal_runtime_state().await;
- }
- }
- codex_state::ThreadGoalStatus::Paused
- | codex_state::ThreadGoalStatus::Blocked
- | codex_state::ThreadGoalStatus::UsageLimited
- | codex_state::ThreadGoalStatus::Complete => {
- self.clear_stopped_thread_goal_runtime_state().await;
- }
- }
- }
-
- async fn clear_stopped_thread_goal_runtime_state(&self) {
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if let Some(turn) = accounting.turn.as_mut() {
- turn.clear_active_goal();
- }
- accounting.wall_clock.clear_active_goal();
- }
-
- async fn clear_active_goal_accounting(&self, turn_context: &TurnContext) {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if let Some(turn) = accounting.turn.as_mut()
- && turn.turn_id == turn_context.sub_id
- {
- turn.clear_active_goal();
- }
- accounting.wall_clock.clear_active_goal();
- }
-
- async fn mark_active_goal_accounting(
- &self,
- goal_id: String,
- turn_id: Option<String>,
- token_usage: TokenUsage,
- ) {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if let Some(turn_id) = turn_id {
- match accounting.turn.as_mut() {
- Some(turn) if turn.turn_id == turn_id => {
- turn.reset_baseline(token_usage);
- turn.mark_active_goal(goal_id.clone());
- }
- _ => {
- let mut turn = GoalTurnAccountingSnapshot::new(turn_id, token_usage);
- turn.mark_active_goal(goal_id.clone());
- accounting.turn = Some(turn);
- }
- }
- }
- accounting.wall_clock.mark_active_goal(goal_id);
- }
-
- fn emit_goal_created_metric(&self) {
- self.services
- .session_telemetry
- .counter(GOAL_CREATED_METRIC, /*inc*/ 1, &[]);
- }
-
- fn emit_goal_resumed_metric(&self) {
- self.services
- .session_telemetry
- .counter(GOAL_RESUMED_METRIC, /*inc*/ 1, &[]);
- }
-
- fn emit_goal_resumed_metric_if_status_changed(
- &self,
- previous_status: Option<codex_state::ThreadGoalStatus>,
- goal_status: codex_state::ThreadGoalStatus,
- ) {
- if goal_status == codex_state::ThreadGoalStatus::Active
- && matches!(
- previous_status,
- Some(
- codex_state::ThreadGoalStatus::Paused
- | codex_state::ThreadGoalStatus::Blocked
- | codex_state::ThreadGoalStatus::UsageLimited
- )
- )
- {
- self.emit_goal_resumed_metric();
- }
- }
-
- fn emit_goal_terminal_metrics_if_status_changed(
- &self,
- previous_status: Option<codex_state::ThreadGoalStatus>,
- goal: &codex_state::ThreadGoal,
- ) {
- if previous_status == Some(goal.status) {
- return;
- }
-
- let counter = match goal.status {
- codex_state::ThreadGoalStatus::Blocked => GOAL_BLOCKED_METRIC,
- codex_state::ThreadGoalStatus::UsageLimited => GOAL_USAGE_LIMITED_METRIC,
- codex_state::ThreadGoalStatus::BudgetLimited => GOAL_BUDGET_LIMITED_METRIC,
- codex_state::ThreadGoalStatus::Complete => GOAL_COMPLETED_METRIC,
- codex_state::ThreadGoalStatus::Active | codex_state::ThreadGoalStatus::Paused => {
- return;
- }
- };
- let status_tag = [("status", goal.status.as_str())];
- self.services
- .session_telemetry
- .counter(counter, /*inc*/ 1, &[]);
- self.services.session_telemetry.histogram(
- GOAL_TOKEN_COUNT_METRIC,
- goal.tokens_used,
- &status_tag,
- );
- self.services.session_telemetry.histogram(
- GOAL_DURATION_SECONDS_METRIC,
- goal.time_used_seconds,
- &status_tag,
- );
- }
-
- async fn current_goal_status_for_metrics(
- &self,
- state_db: &StateDbHandle,
- expected_goal_id: Option<&str>,
- ) -> anyhow::Result<Option<codex_state::ThreadGoalStatus>> {
- let goal = state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await?;
- Ok(goal.and_then(|goal| {
- expected_goal_id
- .is_none_or(|expected_goal_id| goal.goal_id == expected_goal_id)
- .then_some(goal.status)
- }))
- }
-
- async fn active_turn_context(&self) -> Option<Arc<TurnContext>> {
- let active = self.active_turn.lock().await;
- active
- .as_ref()
- .and_then(|active_turn| active_turn.task.as_ref())
- .map(|task| Arc::clone(&task.turn_context))
- }
-
- async fn mark_thread_goal_turn_started(
- &self,
- turn_context: &TurnContext,
- token_usage: TokenUsage,
- ) {
- self.goal_runtime.accounting.lock().await.turn = Some(GoalTurnAccountingSnapshot::new(
- turn_context.sub_id.clone(),
- token_usage,
- ));
-
- if !self.enabled(Feature::Goals) {
- return;
- }
- if should_ignore_goal_for_mode(turn_context.collaboration_mode.mode) {
- self.clear_active_goal_accounting(turn_context).await;
- return;
- }
- let state_db = match self.state_db_for_thread_goals().await {
- Ok(Some(state_db)) => state_db,
- Ok(None) => return,
- Err(err) => {
- tracing::warn!("failed to open state db at turn start: {err}");
- return;
- }
- };
- match state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await
- {
- Ok(Some(goal))
- if matches!(
- goal.status,
- codex_state::ThreadGoalStatus::Active
- | codex_state::ThreadGoalStatus::BudgetLimited
- ) =>
- {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if let Some(turn) = accounting.turn.as_mut()
- && turn.turn_id == turn_context.sub_id
- {
- turn.mark_active_goal(goal.goal_id.clone());
- }
- accounting.wall_clock.mark_active_goal(goal.goal_id);
- }
- Ok(Some(_)) | Ok(None) => {
- self.goal_runtime
- .accounting
- .lock()
- .await
- .wall_clock
- .clear_active_goal();
- }
- Err(err) => {
- tracing::warn!("failed to read thread goal at turn start: {err}");
- }
- }
- }
-
- async fn clear_reserved_goal_continuation_turn(&self, turn_state: &Arc<Mutex<TurnState>>) {
- let mut active_turn_guard = self.active_turn.lock().await;
- if let Some(active_turn) = active_turn_guard.as_ref()
- && active_turn.task.is_none()
- && Arc::ptr_eq(&active_turn.turn_state, turn_state)
- {
- *active_turn_guard = None;
- }
- }
-
- async fn finish_thread_goal_turn(
- self: &Arc<Self>,
- turn_context: &TurnContext,
- turn_completed: bool,
- ) {
- if turn_completed
- && let Err(err) = self
- .account_thread_goal_progress(
- turn_context,
- BudgetLimitSteering::Suppressed,
- TerminalMetricEmission::Emit,
- )
- .await
- {
- tracing::warn!("failed to account thread goal progress at turn end: {err}");
- }
-
- if turn_completed {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if accounting
- .turn
- .as_ref()
- .is_some_and(|turn| turn.turn_id == turn_context.sub_id)
- {
- accounting.turn = None;
- }
- }
- }
-
- async fn handle_thread_goal_task_abort(&self, turn_context: Option<&TurnContext>) {
- if let Some(turn_context) = turn_context {
- if let Err(err) = self
- .account_thread_goal_progress(
- turn_context,
- BudgetLimitSteering::Suppressed,
- TerminalMetricEmission::Emit,
- )
- .await
- {
- tracing::warn!("failed to account thread goal progress after abort: {err}");
- }
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if accounting
- .turn
- .as_ref()
- .is_some_and(|turn| turn.turn_id == turn_context.sub_id)
- {
- accounting.turn = None;
- }
- }
- }
-
- async fn account_thread_goal_progress(
- &self,
- turn_context: &TurnContext,
- budget_limit_steering: BudgetLimitSteering,
- terminal_metric_emission: TerminalMetricEmission,
- ) -> anyhow::Result<()> {
- if !self.enabled(Feature::Goals) {
- return Ok(());
- }
- if should_ignore_goal_for_mode(turn_context.collaboration_mode.mode) {
- return Ok(());
- }
- let Some(state_db) = self.state_db_for_thread_goals().await? else {
- return Ok(());
- };
- let _accounting_permit = self.goal_runtime.accounting_permit().await?;
- let current_token_usage = self.total_token_usage().await.unwrap_or_default();
- let (token_delta, expected_goal_id, time_delta_seconds) = {
- let accounting = self.goal_runtime.accounting.lock().await;
- let Some(turn) = accounting
- .turn
- .as_ref()
- .filter(|turn| turn.turn_id == turn_context.sub_id)
- else {
- return Ok(());
- };
- if !turn.active_this_turn() {
- return Ok(());
- }
- (
- turn.token_delta_since_last_accounting(&current_token_usage),
- turn.active_goal_id(),
- accounting.wall_clock.time_delta_since_last_accounting(),
- )
- };
- if time_delta_seconds == 0 && token_delta <= 0 {
- return Ok(());
- }
- let previous_status = self
- .current_goal_status_for_metrics(&state_db, expected_goal_id.as_deref())
- .await?;
- let outcome = state_db
- .thread_goals()
- .account_thread_goal_usage(
- self.thread_id,
- time_delta_seconds,
- token_delta,
- codex_state::GoalAccountingMode::ActiveOnly,
- expected_goal_id.as_deref(),
- )
- .await?;
- let budget_limit_was_already_reported = {
- let reported_goal_id = self.goal_runtime.budget_limit_reported_goal_id.lock().await;
- expected_goal_id
- .as_deref()
- .is_some_and(|goal_id| reported_goal_id.as_deref() == Some(goal_id))
- };
- let goal = match outcome {
- codex_state::GoalAccountingOutcome::Updated(goal) => {
- let clear_active_goal = match goal.status {
- codex_state::ThreadGoalStatus::Active => false,
- codex_state::ThreadGoalStatus::BudgetLimited => {
- matches!(budget_limit_steering, BudgetLimitSteering::Suppressed)
- }
- codex_state::ThreadGoalStatus::Paused
- | codex_state::ThreadGoalStatus::Blocked
- | codex_state::ThreadGoalStatus::UsageLimited
- | codex_state::ThreadGoalStatus::Complete => true,
- };
- {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- if let Some(turn) = accounting
- .turn
- .as_mut()
- .filter(|turn| turn.turn_id == turn_context.sub_id)
- {
- turn.mark_accounted(current_token_usage);
- if clear_active_goal {
- turn.clear_active_goal();
- }
- }
- accounting.wall_clock.mark_accounted(time_delta_seconds);
- if clear_active_goal {
- accounting.wall_clock.clear_active_goal();
- }
- }
- if matches!(terminal_metric_emission, TerminalMetricEmission::Emit) {
- self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
- }
- goal
- }
- codex_state::GoalAccountingOutcome::Unchanged(_) => return Ok(()),
- };
- let should_steer_budget_limit =
- matches!(budget_limit_steering, BudgetLimitSteering::Allowed)
- && goal.status == codex_state::ThreadGoalStatus::BudgetLimited
- && !budget_limit_was_already_reported;
- let goal_status = goal.status;
- let goal_id = goal.goal_id.clone();
- if goal_status != codex_state::ThreadGoalStatus::BudgetLimited {
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
- }
- let goal = protocol_goal_from_state(goal);
- self.send_event(
- turn_context,
- EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
- thread_id: self.thread_id,
- turn_id: Some(turn_context.sub_id.clone()),
- goal: goal.clone(),
- }),
- )
- .await;
- if should_steer_budget_limit {
- let item = budget_limit_steering_item(&goal);
- if self.inject_if_running(vec![item]).await.is_err() {
- tracing::debug!("skipping budget-limit goal steering because no turn is active");
- }
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = Some(goal_id);
- }
- Ok(())
- }
-
- async fn account_thread_goal_before_external_mutation(&self) -> anyhow::Result<()> {
- if let Some(turn_context) = self.active_turn_context().await {
- return self
- .account_thread_goal_progress(
- turn_context.as_ref(),
- BudgetLimitSteering::Suppressed,
- TerminalMetricEmission::Emit,
- )
- .await;
- }
-
- let Some(state_db) = self.state_db_for_thread_goals().await? else {
- return Ok(());
- };
- self.account_thread_goal_wall_clock_usage(
- &state_db,
- codex_state::GoalAccountingMode::ActiveOnly,
- TerminalMetricEmission::Suppress,
- )
- .await?;
- Ok(())
- }
-
- async fn account_thread_goal_wall_clock_usage(
- &self,
- state_db: &StateDbHandle,
- mode: codex_state::GoalAccountingMode,
- terminal_metric_emission: TerminalMetricEmission,
- ) -> anyhow::Result<Option<ThreadGoal>> {
- let _accounting_permit = self.goal_runtime.accounting_permit().await?;
- let (time_delta_seconds, expected_goal_id) = {
- let accounting = self.goal_runtime.accounting.lock().await;
- (
- accounting.wall_clock.time_delta_since_last_accounting(),
- accounting.wall_clock.active_goal_id(),
- )
- };
- if time_delta_seconds == 0 {
- return Ok(None);
- }
- let previous_status = self
- .current_goal_status_for_metrics(state_db, expected_goal_id.as_deref())
- .await?;
-
- match state_db
- .thread_goals()
- .account_thread_goal_usage(
- self.thread_id,
- time_delta_seconds,
- /*token_delta*/ 0,
- mode,
- expected_goal_id.as_deref(),
- )
- .await?
- {
- codex_state::GoalAccountingOutcome::Updated(goal) => {
- if matches!(terminal_metric_emission, TerminalMetricEmission::Emit) {
- self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
- }
- self.goal_runtime
- .accounting
- .lock()
- .await
- .wall_clock
- .mark_accounted(time_delta_seconds);
- let goal = protocol_goal_from_state(goal);
- Ok(Some(goal))
- }
- codex_state::GoalAccountingOutcome::Unchanged(goal) => {
- {
- let mut accounting = self.goal_runtime.accounting.lock().await;
- accounting.wall_clock.reset_baseline();
- accounting.wall_clock.clear_active_goal();
- }
- if let Some(goal) = goal {
- let goal = protocol_goal_from_state(goal);
- return Ok(Some(goal));
- }
- Ok(None)
- }
- }
- }
-
- async fn usage_limit_active_thread_goal_for_turn(
- &self,
- turn_context: &TurnContext,
- ) -> anyhow::Result<()> {
- if should_ignore_goal_for_mode(turn_context.collaboration_mode.mode) {
- return Ok(());
- }
-
- if !self.enabled(Feature::Goals) {
- return Ok(());
- }
-
- let _continuation_guard = self
- .goal_runtime
- .continuation_lock
- .acquire()
- .await
- .context("goal continuation semaphore closed")?;
- let Some(state_db) = self.state_db_for_thread_goals().await? else {
- return Ok(());
- };
- self.account_thread_goal_progress(
- turn_context,
- BudgetLimitSteering::Suppressed,
- TerminalMetricEmission::Emit,
- )
- .await?;
- let previous_status = self
- .current_goal_status_for_metrics(&state_db, /*expected_goal_id*/ None)
- .await?;
- let Some(goal) = state_db
- .thread_goals()
- .usage_limit_active_thread_goal(self.thread_id)
- .await?
- else {
- return Ok(());
- };
- self.emit_goal_terminal_metrics_if_status_changed(previous_status, &goal);
- let goal = protocol_goal_from_state(goal);
- *self.goal_runtime.budget_limit_reported_goal_id.lock().await = None;
- self.clear_active_goal_accounting(turn_context).await;
- self.send_event(
- turn_context,
- EventMsg::ThreadGoalUpdated(ThreadGoalUpdatedEvent {
- thread_id: self.thread_id,
- turn_id: Some(turn_context.sub_id.clone()),
- goal,
- }),
- )
- .await;
- Ok(())
- }
-
- async fn restore_thread_goal_runtime_after_resume(&self) -> anyhow::Result<()> {
- if !self.enabled(Feature::Goals) {
- return Ok(());
- }
- if should_ignore_goal_for_mode(self.collaboration_mode().await.mode) {
- tracing::debug!(
- "skipping goal runtime restore while current collaboration mode ignores goals"
- );
- return Ok(());
- }
-
- let _continuation_guard = self
- .goal_runtime
- .continuation_lock
- .acquire()
- .await
- .context("goal continuation semaphore closed")?;
- let Some(state_db) = self.state_db_for_thread_goals().await? else {
- return Ok(());
- };
- let Some(goal) = state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await?
- else {
- self.clear_stopped_thread_goal_runtime_state().await;
- return Ok(());
- };
- match goal.status {
- codex_state::ThreadGoalStatus::Active => {
- self.goal_runtime
- .accounting
- .lock()
- .await
- .wall_clock
- .mark_active_goal(goal.goal_id);
- self.emit_goal_resumed_metric();
- }
- codex_state::ThreadGoalStatus::Paused
- | codex_state::ThreadGoalStatus::Blocked
- | codex_state::ThreadGoalStatus::UsageLimited
- | codex_state::ThreadGoalStatus::BudgetLimited
- | codex_state::ThreadGoalStatus::Complete => {
- self.clear_stopped_thread_goal_runtime_state().await;
- }
- }
- Ok(())
- }
-
- async fn maybe_continue_goal_if_idle_runtime(self: &Arc<Self>) {
- self.maybe_start_turn_for_pending_work().await;
- self.maybe_start_goal_continuation_turn().await;
- }
-
- async fn maybe_start_goal_continuation_turn(self: &Arc<Self>) {
- let Ok(_continuation_guard) = self.goal_runtime.continuation_lock.acquire().await else {
- tracing::warn!("goal continuation semaphore closed");
- return;
- };
- let Some(candidate) = self.goal_continuation_candidate_if_active().await else {
- return;
- };
-
- let turn_state = {
- let mut active_turn = self.active_turn.lock().await;
- if active_turn.is_some() {
- return;
- }
- let active_turn = active_turn.get_or_insert_with(ActiveTurn::default);
- Arc::clone(&active_turn.turn_state)
- };
- let goal_is_current = match self.state_db_for_thread_goals().await {
- Ok(Some(state_db)) => match state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await
- {
- Ok(Some(goal))
- if goal.goal_id == candidate.goal_id
- && goal.status == codex_state::ThreadGoalStatus::Active =>
- {
- true
- }
- Ok(Some(_)) | Ok(None) => {
- tracing::debug!(
- "skipping active goal continuation because the goal changed before launch"
- );
- false
- }
- Err(err) => {
- tracing::warn!("failed to re-read thread goal before continuation: {err}");
- false
- }
- },
- Ok(None) => {
- tracing::debug!("skipping active goal continuation for ephemeral thread");
- false
- }
- Err(err) => {
- tracing::warn!("failed to open state db before goal continuation: {err}");
- false
- }
- };
- if !goal_is_current {
- self.clear_reserved_goal_continuation_turn(&turn_state)
- .await;
- return;
- }
- self.input_queue
- .extend_pending_input_for_turn_state(
- turn_state.as_ref(),
- candidate
- .items
- .into_iter()
- .map(TurnInput::ResponseItem)
- .collect(),
- )
- .await;
-
- let turn_context = self
- .new_default_turn_with_sub_id(uuid::Uuid::new_v4().to_string())
- .await;
- self.maybe_emit_unknown_model_warning_for_turn(turn_context.as_ref())
- .await;
- let still_reserved = {
- let active_turn = self.active_turn.lock().await;
- active_turn.as_ref().is_some_and(|active_turn| {
- active_turn.task.is_none() && Arc::ptr_eq(&active_turn.turn_state, &turn_state)
- })
- };
- if !still_reserved {
- self.clear_reserved_goal_continuation_turn(&turn_state)
- .await;
- return;
- }
- self.start_task(turn_context, Vec::new(), RegularTask::new())
- .await;
- }
-
- async fn goal_continuation_candidate_if_active(
- self: &Arc<Self>,
- ) -> Option<GoalContinuationCandidate> {
- if !self.enabled(Feature::Goals) {
- return None;
- }
- if should_ignore_goal_for_mode(self.collaboration_mode().await.mode) {
- tracing::debug!("skipping active goal continuation while plan mode is active");
- return None;
- }
- if self.active_turn.lock().await.is_some() {
- tracing::debug!("skipping active goal continuation because a turn is already active");
- return None;
- }
- if self.input_queue.has_trigger_turn_mailbox_items().await {
- tracing::debug!(
- "skipping active goal continuation because trigger-turn mailbox input is pending"
- );
- return None;
- }
- let state_db = match self.state_db_for_thread_goals().await {
- Ok(Some(state_db)) => state_db,
- Ok(None) => {
- tracing::debug!("skipping active goal continuation for ephemeral thread");
- return None;
- }
- Err(err) => {
- tracing::warn!("failed to open state db for goal continuation: {err}");
- return None;
- }
- };
- let goal = match state_db
- .thread_goals()
- .get_thread_goal(self.thread_id)
- .await
- {
- Ok(Some(goal)) => goal,
- Ok(None) => {
- tracing::debug!("skipping active goal continuation because no goal is set");
- return None;
- }
- Err(err) => {
- tracing::warn!("failed to read thread goal for continuation: {err}");
- return None;
- }
- };
- if goal.status != codex_state::ThreadGoalStatus::Active {
- tracing::debug!(status = ?goal.status, "skipping inactive thread goal");
- return None;
- }
- if self.active_turn.lock().await.is_some()
- || self.input_queue.has_trigger_turn_mailbox_items().await
- {
- tracing::debug!("skipping active goal continuation because pending work appeared");
- return None;
- }
- let goal_id = goal.goal_id.clone();
- let goal = protocol_goal_from_state(goal);
- Some(GoalContinuationCandidate {
- goal_id,
- items: vec![goal_context_input_item(continuation_prompt(&goal))],
- })
- }
-}
-
-impl Session {
- async fn state_db_for_thread_goals(&self) -> anyhow::Result<Option<StateDbHandle>> {
- let config = self.get_config().await;
- if config.ephemeral {
- return Ok(None);
- }
-
- self.try_ensure_rollout_materialized()
- .await
- .context("failed to materialize rollout before opening state db for thread goals")?;
-
- let state_db = if let Some(state_db) = self.state_db() {
- state_db
- } else if let Some(state_db) = self.goal_runtime.state_db.lock().await.clone() {
- state_db
- } else if let Some(local_store) = self
- .services
- .thread_store
- .as_any()
- .downcast_ref::<LocalThreadStore>()
- {
- local_store.state_db().await.ok_or_else(|| {
- anyhow::anyhow!(
- "thread goals require a local persisted thread with a state database"
- )
- })?
- } else {
- anyhow::bail!("thread goals require a local persisted thread with a state database");
- };
-
- let thread_metadata_present = state_db
- .get_thread(self.thread_id)
- .await
- .context("failed to read thread metadata before reconciling thread goals")?
- .is_some();
- if !thread_metadata_present {
- let rollout_path = self
- .current_rollout_path()
- .await
- .context("failed to locate rollout before reconciling thread goals")?
- .ok_or_else(|| {
- anyhow::anyhow!("thread goals require materialized thread metadata")
- })?;
- reconcile_rollout(
- Some(&state_db),
- rollout_path.as_path(),
- config.model_provider_id.as_str(),
- /*builder*/ None,
- &[],
- /*archived_only*/ None,
- /*new_thread_memory_mode*/ None,
- )
- .await;
- let thread_metadata_present = state_db
- .get_thread(self.thread_id)
- .await
- .context("failed to read thread metadata after reconciling thread goals")?
- .is_some();
- if !thread_metadata_present {
- anyhow::bail!("thread metadata is unavailable after reconciling thread goals");
- }
- }
-
- *self.goal_runtime.state_db.lock().await = Some(state_db.clone());
- Ok(Some(state_db))
- }
-
- async fn require_state_db_for_thread_goals(&self) -> anyhow::Result<StateDbHandle> {
- self.state_db_for_thread_goals().await?.ok_or_else(|| {
- anyhow::anyhow!("thread goals require a persisted thread; this thread is ephemeral")
- })
- }
-}
-
-async fn set_thread_preview_from_goal_objective(
- state_db: &StateDbHandle,
- thread_id: ThreadId,
- objective: &str,
-) {
- if let Err(err) = state_db
- .set_thread_preview_if_empty(thread_id, objective)
- .await
- {
- tracing::warn!(
- "failed to set empty thread preview from goal objective for {thread_id}: {err}"
- );
- }
-}
-
-fn should_ignore_goal_for_mode(mode: ModeKind) -> bool {
- mode == ModeKind::Plan
-}
-
-fn budget_limit_steering_item(goal: &ThreadGoal) -> ResponseItem {
- goal_context_input_item(budget_limit_prompt(goal))
-}
-
-fn goal_context_input_item(prompt: String) -> ResponseItem {
- ContextualUserFragment::into(InternalModelContextFragment::new(
- InternalContextSource::from_static("goal"),
- prompt,
- ))
-}
-
-pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal {
- ThreadGoal {
- thread_id: goal.thread_id,
- objective: goal.objective,
- status: protocol_goal_status_from_state(goal.status),
- token_budget: goal.token_budget,
- tokens_used: goal.tokens_used,
- time_used_seconds: goal.time_used_seconds,
- created_at: goal.created_at.timestamp(),
- updated_at: goal.updated_at.timestamp(),
- }
-}
-
-pub(crate) fn protocol_goal_status_from_state(
- status: codex_state::ThreadGoalStatus,
-) -> ThreadGoalStatus {
- match status {
- codex_state::ThreadGoalStatus::Active => ThreadGoalStatus::Active,
- codex_state::ThreadGoalStatus::Paused => ThreadGoalStatus::Paused,
- codex_state::ThreadGoalStatus::Blocked => ThreadGoalStatus::Blocked,
- codex_state::ThreadGoalStatus::UsageLimited => ThreadGoalStatus::UsageLimited,
- codex_state::ThreadGoalStatus::BudgetLimited => ThreadGoalStatus::BudgetLimited,
- codex_state::ThreadGoalStatus::Complete => ThreadGoalStatus::Complete,
- }
-}
-
-pub(crate) fn state_goal_status_from_protocol(
- status: ThreadGoalStatus,
-) -> codex_state::ThreadGoalStatus {
- match status {
- ThreadGoalStatus::Active => codex_state::ThreadGoalStatus::Active,
- ThreadGoalStatus::Paused => codex_state::ThreadGoalStatus::Paused,
- ThreadGoalStatus::Blocked => codex_state::ThreadGoalStatus::Blocked,
- ThreadGoalStatus::UsageLimited => codex_state::ThreadGoalStatus::UsageLimited,
- ThreadGoalStatus::BudgetLimited => codex_state::ThreadGoalStatus::BudgetLimited,
- ThreadGoalStatus::Complete => codex_state::ThreadGoalStatus::Complete,
- }
-}
-
-pub(crate) fn validate_goal_budget(value: Option<i64>) -> anyhow::Result<()> {
- if let Some(value) = value
- && value <= 0
- {
- anyhow::bail!("goal budgets must be positive when provided");
- }
- Ok(())
-}
-
-pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 {
- usage
- .non_cached_input()
- .saturating_add(usage.output_tokens.max(0))
-}
-
-#[cfg(test)]
-mod tests {
- use super::goal_context_input_item;
- use super::goal_token_delta_for_usage;
- use super::should_ignore_goal_for_mode;
- use codex_protocol::config_types::ModeKind;
- use codex_protocol::models::ContentItem;
- use codex_protocol::models::ResponseItem;
- use codex_protocol::protocol::TokenUsage;
- use std::time::Duration;
- use std::time::Instant;
-
- #[test]
- fn goal_continuation_is_ignored_only_in_plan_mode() {
- assert!(should_ignore_goal_for_mode(ModeKind::Plan));
- assert!(!should_ignore_goal_for_mode(ModeKind::Default));
- assert!(!should_ignore_goal_for_mode(ModeKind::PairProgramming));
- assert!(!should_ignore_goal_for_mode(ModeKind::Execute));
- }
-
- #[test]
- fn goal_token_delta_excludes_cached_input_and_does_not_double_count_reasoning() {
- let usage = TokenUsage {
- input_tokens: 900,
- cached_input_tokens: 400,
- output_tokens: 80,
- reasoning_output_tokens: 20,
- total_tokens: 1_000,
- };
-
- assert_eq!(580, goal_token_delta_for_usage(&usage));
- }
-
- #[test]
- fn wall_clock_accounting_advances_by_persisted_seconds() {
- let mut snapshot = super::GoalWallClockAccountingSnapshot::new();
- let original = Instant::now() - Duration::from_millis(1500);
- snapshot.last_accounted_at = original;
-
- snapshot.mark_accounted(/*accounted_seconds*/ 1);
- assert_eq!(
- original + Duration::from_secs(1),
- snapshot.last_accounted_at
- );
-
- let token_only_original = snapshot.last_accounted_at;
- snapshot.mark_accounted(/*accounted_seconds*/ 0);
- assert_eq!(token_only_original, snapshot.last_accounted_at);
- }
-
- #[test]
- fn goal_context_input_item_is_hidden_user_context() {
- let item = goal_context_input_item("Continue working.".to_string());
-
- assert_eq!(
- item,
- ResponseItem::Message {
- id: None,
- role: "user".to_string(),
- content: vec![ContentItem::InputText {
- text: "<codex_internal_context source=\"goal\">\nContinue working.\n</codex_internal_context>".to_string(),
- }],
- phase: None,
- }
- );
- }
-}
diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs
index 4dc19de7e6..400c803680 100644
--- a/codex-rs/core/src/lib.rs
+++ b/codex-rs/core/src/lib.rs
@@ -39,9 +39,6 @@ pub mod exec_env;
mod exec_policy;
#[cfg(test)]
mod git_info_tests;
-mod goals;
-pub use goals::ExternalGoalPreviousStatus;
-pub use goals::ExternalGoalSet;
mod guardian;
mod hook_runtime;
mod installation_id;
diff --git a/codex-rs/core/src/session/review.rs b/codex-rs/core/src/session/review.rs
index ff4c77aab9..a3b23c6a78 100644
--- a/codex-rs/core/src/session/review.rs
+++ b/codex-rs/core/src/session/review.rs
@@ -26,7 +26,6 @@ pub(super) async fn spawn_review_thread(
let _ = review_features.disable(Feature::WebSearchCached);
let _ = review_features.disable(Feature::Goals);
let review_web_search_mode = WebSearchMode::Disabled;
- let goal_tools_supported = !config.ephemeral && parent_turn_context.goal_tools_enabled();
let available_models = sess
.services
.models_manager
@@ -126,7 +125,6 @@ pub(super) async fn spawn_review_thread(
environments: parent_turn_context.environments.clone(),
available_models,
unified_exec_shell_mode,
- goal_tools_supported,
features: review_features,
ghost_snapshot: parent_turn_context.ghost_snapshot.clone(),
current_date: parent_turn_context.current_date.clone(),
diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs
index e7ec3b98db..122ff6aeb9 100644
--- a/codex-rs/core/src/session/session.rs
+++ b/codex-rs/core/src/session/session.rs
@@ -2,7 +2,6 @@ use super::input_queue::InputQueue;
use super::*;
use crate::agents_md::LoadedAgentsMd;
use crate::config::ConstraintError;
-use crate::goals::GoalRuntimeState;
use crate::skills::SkillError;
use crate::state::ActiveTurn;
use codex_protocol::SessionId;
@@ -37,7 +36,6 @@ pub(crate) struct Session {
pub(crate) conversation: Arc<RealtimeConversationManager>,
pub(crate) active_turn: Mutex<Option<ActiveTurn>>,
pub(crate) input_queue: InputQueue,
- pub(crate) goal_runtime: GoalRuntimeState,
pub(crate) guardian_review_session: GuardianReviewSessionManager,
pub(crate) services: SessionServices,
pub(super) next_internal_sub_id: AtomicU64,
@@ -1059,7 +1057,6 @@ impl Session {
conversation: Arc::new(RealtimeConversationManager::new()),
active_turn: Mutex::new(None),
input_queue: InputQueue::new(),
- goal_runtime: GoalRuntimeState::new(),
guardian_review_session: GuardianReviewSessionManager::default(),
services,
next_internal_sub_id: AtomicU64::new(0),
diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs
index cf9c7c48d3..366cf6f22a 100644
--- a/codex-rs/core/src/session/tests.rs
+++ b/codex-rs/core/src/session/tests.rs
@@ -57,11 +57,6 @@ use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
use tracing::Span;
-use crate::goals::CreateGoalRequest;
-use crate::goals::ExternalGoalPreviousStatus;
-use crate::goals::ExternalGoalSet;
-use crate::goals::GoalRuntimeEvent;
-use crate::goals::SetGoalRequest;
use crate::rollout::recorder::RolloutRecorder;
use crate::state::ActiveTurn;
use crate::state::TaskKind;
@@ -72,11 +67,9 @@ use crate::tasks::execute_user_shell_command;
use crate::tools::ToolRouter;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
-use crate::tools::handlers::CreateGoalHandler;
use crate::tools::handlers::ExecCommandHandler;
use crate::tools::handlers::RequestPermissionsHandler;
use crate::tools::handlers::ShellCommandHandler;
-use crate::tools::handlers::UpdateGoalHandler;
use crate::tools::registry::ToolExecutor;
use crate::tools::router::ToolCallSource;
use crate::turn_diff_tracker::TurnDiffTracker;
@@ -128,7 +121,6 @@ use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SkillScope;
use codex_protocol::protocol::Submission;
-use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadRolledBackEvent;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::protocol::TokenCountEvent;
@@ -139,28 +131,21 @@ use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
use codex_protocol::protocol::W3cTraceContext;
-use codex_protocol::request_user_input::RequestUserInputAnswer;
-use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_rmcp_client::ElicitationAction;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::context_snapshot::ContextSnapshotRenderMode;
-use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
-use core_test_support::responses::ev_completed_with_tokens;
-use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once;
-use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::test_codex;
use core_test_support::test_path_buf;
use core_test_support::tracing::install_test_tracing;
use core_test_support::wait_for_event;
-use core_test_support::wait_for_event_match;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceId;
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
@@ -4898,7 +4883,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
session_configuration.cwd.clone(),
"turn_id".to_string(),
skills_outcome,
- /*goal_tools_supported*/ true,
);
let session = Session {
@@ -4915,7 +4899,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
conversation: Arc::new(RealtimeConversationManager::new()),
active_turn: Mutex::new(None),
input_queue: super::input_queue::InputQueue::new(),
- goal_runtime: crate::goals::GoalRuntimeState::new(),
guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(),
services,
next_internal_sub_id: AtomicU64::new(0),
@@ -6782,18 +6765,7 @@ where
let (tx_event, rx_event) = async_channel::unbounded();
let mut config = build_test_config(codex_home).await;
configure_config(&mut config);
- let state_db = if config.features.enabled(Feature::Goals) {
- Some(
- codex_state::StateRuntime::init(
- config.sqlite_home.clone(),
- config.model_provider_id.clone(),
- )
- .await
- .expect("goal tests should initialize sqlite state db"),
- )
- } else {
- None
- };
+ let state_db = None;
let config = Arc::new(config);
let thread_id = ThreadId::default();
let auth_manager = AuthManager::from_auth_for_testing(auth);
@@ -6988,7 +6960,6 @@ where
session_configuration.cwd.clone(),
"turn_id".to_string(),
skills_outcome,
- /*goal_tools_supported*/ true,
));
let session = Arc::new(Session {
@@ -7005,7 +6976,6 @@ where
conversation: Arc::new(RealtimeConversationManager::new()),
active_turn: Mutex::new(None),
input_queue: super::input_queue::InputQueue::new(),
- goal_runtime: crate::goals::GoalRuntimeState::new(),
guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(),
services,
next_internal_sub_id: AtomicU64::new(0),
@@ -7029,52 +6999,6 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx(
.await
}
-async fn make_goal_session_and_context_with_rx() -> (
- Arc<Session>,
- Arc<TurnContext>,
- async_channel::Receiver<Event>,
- tempfile::TempDir,
-) {
- let codex_home = tempfile::tempdir().expect("create temp dir");
- let (session, turn_context, rx) = make_session_and_context_with_auth_config_home_and_rx(
- CodexAuth::from_api_key("Test API Key"),
- Vec::new(),
- codex_home.path(),
- |config| {
- config
- .features
- .enable(Feature::Goals)
- .expect("goal mode should be enableable in tests");
- },
- )
- .await;
- upsert_goal_test_thread(session.as_ref()).await;
- (session, turn_context, rx, codex_home)
-}
-
-async fn upsert_goal_test_thread(session: &Session) {
- let config = session.get_config().await;
- let state_db = session
- .state_db()
- .expect("goal test session should have a state db");
- let mut builder = codex_state::ThreadMetadataBuilder::new(
- session.thread_id,
- config
- .codex_home
- .join("goal-test-rollout.jsonl")
- .to_path_buf(),
- chrono::Utc::now(),
- SessionSource::Cli,
- );
- builder.cwd = config.cwd.to_path_buf();
- builder.model_provider = Some(config.model_provider_id.clone());
- let metadata = builder.build(config.model_provider_id.as_str());
- state_db
- .upsert_thread(&metadata)
- .await
- .expect("goal test thread should be upserted");
-}
-
// Like make_session_and_context, but returns Arc<Session> and the event receiver
// so tests can assert on emitted events.
pub(crate) async fn make_session_and_context_with_rx() -> (
@@ -9131,926 +9055,113 @@ async fn abort_empty_active_turn_preserves_pending_input() {
);
}
-#[tokio::test]
-async fn interrupt_accounts_active_goal_without_pausing() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.set_thread_goal(
- tc.as_ref(),
- SetGoalRequest {
- objective: Some("Keep improving the benchmark".to_string()),
- status: None,
- token_budget: None,
- },
- )
- .await?;
+async fn set_total_token_usage(sess: &Session, total_token_usage: TokenUsage) {
+ let mut state = sess.state.lock().await;
+ state.set_token_info(Some(TokenUsageInfo {
+ total_token_usage,
+ last_token_usage: TokenUsage::default(),
+ model_context_window: None,
+ }));
+}
+#[tokio::test]
+async fn queue_only_mailbox_mail_waits_for_next_turn_after_answer_boundary() {
+ let (sess, tc, _rx) = make_session_and_context_with_rx().await;
+ let communication = InterAgentCommunication::new(
+ AgentPath::try_from("/root/worker").expect("worker path should parse"),
+ AgentPath::root(),
+ Vec::new(),
+ "late queue-only update".to_string(),
+ /*trigger_turn*/ false,
+ );
sess.spawn_task(
Arc::clone(&tc),
Vec::new(),
NeverEndingTask {
kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
+ listen_to_cancellation_token: true,
},
)
.await;
- set_total_token_usage(&sess, post_goal_token_usage()).await;
- sess.abort_all_tasks(TurnAbortReason::Interrupted).await;
+ sess.input_queue
+ .defer_mailbox_delivery_to_next_turn(&sess.active_turn, &tc.sub_id)
+ .await;
+ sess.input_queue
+ .enqueue_mailbox_communication(communication.clone())
+ .await;
- let goal = sess
- .get_thread_goal()
- .await?
- .expect("goal should remain persisted after interrupt");
+ assert!(
+ !sess.input_queue.has_pending_input(&sess.active_turn).await,
+ "queue-only mailbox mail should stay buffered once the current turn emitted its answer"
+ );
assert_eq!(
- codex_protocol::protocol::ThreadGoalStatus::Active,
- goal.status
+ sess.input_queue.get_pending_input(&sess.active_turn).await,
+ Vec::new()
);
- assert_eq!(70, goal.tokens_used);
-
- assert!(sess.active_turn.lock().await.is_none());
-
- Ok(())
-}
-
-#[tokio::test]
-async fn shutdown_without_active_turn_keeps_active_goal_active() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.set_thread_goal(
- tc.as_ref(),
- SetGoalRequest {
- objective: Some("Keep improving the benchmark".to_string()),
- status: None,
- token_budget: None,
- },
- )
- .await?;
- assert!(sess.active_turn.lock().await.is_none());
- assert!(handlers::shutdown(&sess, "shutdown".to_string()).await);
+ sess.abort_all_tasks(TurnAbortReason::Replaced).await;
- let goal = sess
- .get_thread_goal()
- .await?
- .expect("goal should remain persisted after shutdown");
assert_eq!(
- codex_protocol::protocol::ThreadGoalStatus::Active,
- goal.status
+ sess.input_queue.get_pending_input(&sess.active_turn).await,
+ vec![TurnInput::ResponseItem(ResponseItem::from(
+ communication.to_response_input_item()
+ ))],
);
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn active_goal_continuation_runs_again_after_no_tool_turn() -> anyhow::Result<()> {
- let server = start_mock_server().await;
- let mut builder = test_codex().with_config(|config| {
- config
- .features
- .enable(Feature::Goals)
- .expect("goal mode should be enableable in tests");
- });
- let test = builder.build(&server).await?;
- let responses = mount_sse_sequence(
- &server,
- vec![
- sse(vec![
- ev_response_created("resp-1"),
- ev_function_call(
- "call-create-goal",
- "create_goal",
- r#"{"objective":"write a benchmark note"}"#,
- ),
- ev_completed("resp-1"),
- ]),
- sse(vec![
- ev_assistant_message("msg-1", "Draft ready."),
- ev_completed("resp-2"),
- ]),
- sse(vec![
- ev_assistant_message("msg-2", "I am still working on the benchmark note."),
- ev_completed("resp-3"),
- ]),
- sse(vec![
- ev_response_created("resp-4"),
- ev_function_call(
- "call-complete-goal",
- "update_goal",
- r#"{"status":"complete"}"#,
- ),
- ev_completed("resp-4"),
- ]),
- sse(vec![
- ev_assistant_message("msg-3", "Goal complete."),
- ev_completed("resp-5"),
- ]),
- ],
- )
- .await;
-
- test.codex
- .submit(Op::UserInput {
- environments: None,
- items: vec![UserInput::Text {
- text: "write a benchmark note".into(),
- text_elements: Vec::new(),
- }],
- final_output_json_schema: None,
- responsesapi_client_metadata: None,
- additional_context: Default::default(),
- thread_settings: Default::default(),
- })
- .await?;
-
- let mut completed_turns = 0;
- tokio::time::timeout(std::time::Duration::from_secs(8), async {
- loop {
- let event = test.codex.next_event().await?;
- if matches!(event.msg, EventMsg::TurnComplete(_)) {
- completed_turns += 1;
- if completed_turns == 3 {
- return anyhow::Ok(());
- }
- }
- }
- })
- .await??;
-
- let goal_context_text = responses
- .requests()
- .into_iter()
- .flat_map(|request| request.message_input_texts("user"))
- .find(|text| text.contains("<codex_internal_context source=\"goal\">"))
- .expect("goal context message should be present");
- assert!(goal_context_text.contains("Continue working toward the active thread goal."));
-
- Ok(())
}
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn pending_request_user_input_does_not_spawn_extra_goal_continuation() -> anyhow::Result<()> {
- let server = start_mock_server().await;
- let mut builder = test_codex().with_config(|config| {
- config
- .features
- .enable(Feature::Goals)
- .expect("goal mode should be enableable in tests");
- config
- .features
- .enable(Feature::DefaultModeRequestUserInput)
- .expect("default-mode request_user_input should be enableable in tests");
- });
- let test = builder.build(&server).await?;
- let responses = mount_sse_sequence(
- &server,
- vec![
- sse(vec![
- ev_response_created("resp-1"),
- ev_function_call(
- "call-create-goal",
- "create_goal",
- r#"{"objective":"write a benchmark note"}"#,
- ),
- ev_completed("resp-1"),
- ]),
- sse(vec![
- ev_assistant_message("msg-1", "Draft ready."),
- ev_completed("resp-2"),
- ]),
- sse(vec![
- ev_response_created("resp-3"),
- ev_function_call(
- "call-ask-user",
- "request_user_input",
- r#"{"questions":[{"header":"Choice","id":"next_step","question":"Pick one","options":[{"label":"Outline","description":"Start with an outline."},{"label":"Draft","description":"Write a full draft."}]}]}"#,
- ),
- ev_completed("resp-3"),
- ]),
- sse(vec![
- ev_response_created("resp-4"),
- ev_function_call(
- "call-complete-goal",
- "update_goal",
- r#"{"status":"complete"}"#,
- ),
- ev_completed("resp-4"),
- ]),
- sse(vec![
- ev_assistant_message("msg-2", "Goal complete."),
- ev_completed("resp-5"),
- ]),
- ],
+#[tokio::test]
+async fn trigger_turn_mailbox_mail_waits_for_next_turn_after_answer_boundary() {
+ let (sess, tc, _rx) = make_session_and_context_with_rx().await;
+ sess.spawn_task(
+ Arc::clone(&tc),
+ Vec::new(),
+ NeverEndingTask {
+ kind: TaskKind::Regular,
+ listen_to_cancellation_token: true,
+ },
)
.await;
- test.codex
- .submit(Op::UserInput {
- environments: None,
- items: vec![UserInput::Text {
- text: "write a benchmark note".into(),
- text_elements: Vec::new(),
- }],
- final_output_json_schema: None,
- responsesapi_client_metadata: None,
- additional_context: Default::default(),
- thread_settings: Default::default(),
- })
- .await?;
+ sess.input_queue
+ .defer_mailbox_delivery_to_next_turn(&sess.active_turn, &tc.sub_id)
+ .await;
+ sess.input_queue
+ .enqueue_mailbox_communication(InterAgentCommunication::new(
+ AgentPath::try_from("/root/worker").expect("worker path should parse"),
+ AgentPath::root(),
+ Vec::new(),
+ "late trigger update".to_string(),
+ /*trigger_turn*/ true,
+ ))
+ .await;
- let request_user_input_event = wait_for_event_match(&test.codex, |event| match event {
- EventMsg::RequestUserInput(event) => Some(event.clone()),
- _ => None,
- })
- .await;
- assert_eq!(3, responses.requests().len());
assert!(
- timeout(Duration::from_millis(200), test.codex.next_event())
- .await
- .is_err(),
- "waiting for request_user_input should keep the turn open without emitting more events"
+ !sess.input_queue.has_pending_input(&sess.active_turn).await,
+ "trigger-turn mailbox mail should not extend the current turn after its answer boundary"
);
- assert_eq!(
- 3,
- responses.requests().len(),
- "waiting for request_user_input should not start another continuation request"
- );
-
- test.codex
- .submit(Op::UserInputAnswer {
- id: request_user_input_event.turn_id,
- response: RequestUserInputResponse {
- answers: std::collections::HashMap::from([(
- "next_step".to_string(),
- RequestUserInputAnswer {
- answers: vec!["Outline".to_string()],
- },
- )]),
- },
- })
- .await?;
-
- let mut completed_turns = 0;
- timeout(Duration::from_secs(8), async {
- loop {
- let event = test.codex.next_event().await?;
- if matches!(event.msg, EventMsg::TurnComplete(_)) {
- completed_turns += 1;
- if completed_turns == 1 {
- return anyhow::Ok(());
- }
- }
- }
- })
- .await??;
-
- assert_eq!(5, responses.requests().len());
-
- Ok(())
-}
-
-async fn set_total_token_usage(sess: &Session, total_token_usage: TokenUsage) {
- let mut state = sess.state.lock().await;
- state.set_token_info(Some(TokenUsageInfo {
- total_token_usage,
- last_token_usage: TokenUsage::default(),
- model_context_window: None,
- }));
-}
-fn post_goal_token_usage() -> TokenUsage {
- TokenUsage {
- input_tokens: 50,
- cached_input_tokens: 10,
- output_tokens: 30,
- reasoning_output_tokens: 5,
- total_tokens: 75,
- }
-}
+ sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-async fn goal_test_state_db(sess: &Session) -> anyhow::Result<crate::StateDbHandle> {
- if let Some(state_db) = sess.state_db() {
- return Ok(state_db);
- }
- let config = sess.get_config().await;
- codex_state::StateRuntime::init(config.sqlite_home.clone(), config.model_provider_id.clone())
- .await
+ assert!(sess.input_queue.has_trigger_turn_mailbox_items().await);
}
#[tokio::test]
-async fn create_thread_goal_fills_empty_thread_preview() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let state_db = goal_test_state_db(sess.as_ref()).await?;
-
- let page = state_db
- .list_threads(
- /*page_size*/ 10,
- codex_state::ThreadFilterOptions {
- archived_only: false,
- allowed_sources: &[],
- model_providers: None,
- cwd_filters: None,
- anchor: None,
- sort_key: codex_state::SortKey::UpdatedAt,
- sort_direction: codex_state::SortDirection::Desc,
- search_term: None,
- },
- )
- .await?;
- assert!(page.items.is_empty());
-
- sess.create_thread_goal(
- tc.as_ref(),
- CreateGoalRequest {
- objective: "Keep improving the benchmark".to_string(),
- token_budget: None,
- },
- )
- .await?;
-
- let page = state_db
- .list_threads(
- /*page_size*/ 10,
- codex_state::ThreadFilterOptions {
- archived_only: false,
- allowed_sources: &[],
- model_providers: None,
- cwd_filters: None,
- anchor: None,
- sort_key: codex_state::SortKey::UpdatedAt,
- sort_direction: codex_state::SortDirection::Desc,
- search_term: None,
- },
- )
- .await?;
- let ids = page
- .items
- .iter()
- .map(|thread| thread.id)
- .collect::<Vec<_>>();
- assert_eq!(vec![sess.thread_id], ids);
- assert_eq!(
- Some("Keep improving the benchmark"),
- page.items[0].preview.as_deref()
+async fn steered_input_reopens_mailbox_delivery_for_current_turn() {
+ let (sess, tc, _rx) = make_session_and_context_with_rx().await;
+ let communication = InterAgentCommunication::new(
+ AgentPath::try_from("/root/worker").expect("worker path should parse"),
+ AgentPath::root(),
+ Vec::new(),
+ "queued child update".to_string(),
+ /*trigger_turn*/ false,
);
-
- Ok(())
-}
-
-#[tokio::test]
-async fn budget_limited_accounting_steers_active_turn_without_aborting() -> anyhow::Result<()> {
- let (sess, tc, rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.set_thread_goal(
- tc.as_ref(),
- SetGoalRequest {
- objective: Some("Keep improving the benchmark".to_string()),
- status: None,
- token_budget: Some(Some(10)),
- },
- )
- .await?;
- sess.goal_runtime_apply(GoalRuntimeEvent::TurnStarted {
- turn_context: tc.as_ref(),
- token_usage: TokenUsage::default(),
- })
- .await?;
sess.spawn_task(
Arc::clone(&tc),
Vec::new(),
NeverEndingTask {
kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
- },
- )
- .await;
- while rx.try_recv().is_ok() {}
-
- set_total_token_usage(
- &sess,
- TokenUsage {
- input_tokens: 20,
- cached_input_tokens: 0,
- output_tokens: 5,
- reasoning_output_tokens: 0,
- total_tokens: 25,
- },
- )
- .await;
-
- sess.goal_runtime_apply(GoalRuntimeEvent::ToolCompleted {
- turn_context: tc.as_ref(),
- tool_name: "shell_command",
- })
- .await?;
-
- let pending_input = sess.input_queue.get_pending_input(&sess.active_turn).await;
- let [TurnInput::ResponseItem(ResponseItem::Message { role, content, .. })] =
- pending_input.as_slice()
- else {
- panic!("expected one budget-limit steering message, got {pending_input:#?}");
- };
- assert_eq!("user", role);
- let [ContentItem::InputText { text }] = content.as_slice() else {
- panic!("expected one text span in budget-limit steering message, got {content:#?}");
- };
- assert!(text.starts_with("<codex_internal_context source=\"goal\">"));
- assert!(text.trim_end().ends_with("</codex_internal_context>"));
- assert!(text.contains("budget_limited"));
- assert!(text.to_lowercase().contains("wrap up this turn soon"));
- assert!(sess.active_turn.lock().await.is_some());
- while let Ok(event) = rx.try_recv() {
- assert!(
- !matches!(event.msg, EventMsg::TurnAborted(_)),
- "budget limit should steer the active turn instead of aborting it"
- );
- }
-
- let state_db = goal_test_state_db(sess.as_ref()).await?;
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted after accounting");
- assert_eq!(codex_state::ThreadGoalStatus::BudgetLimited, goal.status);
- assert_eq!(25, goal.tokens_used);
-
- set_total_token_usage(
- &sess,
- TokenUsage {
- input_tokens: 30,
- cached_input_tokens: 0,
- output_tokens: 10,
- reasoning_output_tokens: 0,
- total_tokens: 40,
- },
- )
- .await;
- sess.goal_runtime_apply(GoalRuntimeEvent::ToolCompletedGoal {
- turn_context: tc.as_ref(),
- })
- .await?;
-
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted after follow-up accounting");
- assert_eq!(codex_state::ThreadGoalStatus::BudgetLimited, goal.status);
- assert_eq!(40, goal.tokens_used);
-
- sess.abort_all_tasks(TurnAbortReason::Interrupted).await;
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn usage_limit_runtime_stops_active_goal_and_prevents_idle_continuation() -> anyhow::Result<()>
-{
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.set_thread_goal(
- tc.as_ref(),
- SetGoalRequest {
- objective: Some("Keep improving the benchmark".to_string()),
- status: None,
- token_budget: Some(Some(50)),
- },
- )
- .await?;
- sess.goal_runtime_apply(GoalRuntimeEvent::TurnStarted {
- turn_context: tc.as_ref(),
- token_usage: TokenUsage::default(),
- })
- .await?;
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
- },
- )
- .await;
- set_total_token_usage(&sess, post_goal_token_usage()).await;
-
- sess.goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached {
- turn_context: tc.as_ref(),
- })
- .await?;
-
- let state_db = goal_test_state_db(sess.as_ref()).await?;
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted after usage limiting");
- assert_eq!(codex_state::ThreadGoalStatus::UsageLimited, goal.status);
- assert_eq!(70, goal.tokens_used);
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
- sess.goal_runtime_apply(GoalRuntimeEvent::MaybeContinueIfIdle)
- .await?;
- assert!(sess.active_turn.lock().await.is_none());
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn external_goal_mutation_accounts_active_turn_before_status_change() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.set_thread_goal(
- tc.as_ref(),
- SetGoalRequest {
- objective: Some("Keep improving the benchmark".to_string()),
- status: None,
- token_budget: None,
- },
- )
- .await?;
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
- },
- )
- .await;
- set_total_token_usage(&sess, post_goal_token_usage()).await;
-
- sess.goal_runtime_apply(GoalRuntimeEvent::ExternalMutationStarting)
- .await?;
-
- let state_db = goal_test_state_db(sess.as_ref()).await?;
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted");
- assert_eq!(70, goal.tokens_used);
-
- let previous_goal = goal.clone();
- let goal_id = goal.goal_id.clone();
- let updated_goal = state_db
- .thread_goals()
- .update_thread_goal(
- sess.thread_id,
- codex_state::GoalUpdate {
- objective: None,
- status: Some(codex_state::ThreadGoalStatus::Complete),
- token_budget: None,
- expected_goal_id: Some(goal_id),
- },
- )
- .await?
- .expect("goal status update should succeed");
- sess.goal_runtime_apply(GoalRuntimeEvent::ExternalSet {
- external_set: ExternalGoalSet {
- goal: updated_goal,
- previous_status: ExternalGoalPreviousStatus::from(&previous_goal),
- },
- })
- .await?;
-
- assert!(sess.active_turn.lock().await.is_some());
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted");
- assert_eq!(codex_state::ThreadGoalStatus::Complete, goal.status);
- assert_eq!(70, goal.tokens_used);
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn external_objective_change_steers_active_turn() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
- },
- )
- .await;
-
- let state_db = goal_test_state_db(sess.as_ref()).await?;
- let old_goal = state_db
- .thread_goals()
- .replace_thread_goal(
- sess.thread_id,
- "Keep improving the benchmark",
- codex_state::ThreadGoalStatus::Active,
- /*token_budget*/ Some(10_000),
- )
- .await?;
- let new_goal = state_db
- .thread_goals()
- .replace_thread_goal(
- sess.thread_id,
- "Write a concise benchmark summary",
- codex_state::ThreadGoalStatus::Active,
- /*token_budget*/ Some(10_000),
- )
- .await?;
-
- sess.goal_runtime_apply(GoalRuntimeEvent::ExternalSet {
- external_set: ExternalGoalSet {
- goal: new_goal,
- previous_status: ExternalGoalPreviousStatus::from(&old_goal),
- },
- })
- .await?;
-
- let pending_input = sess.input_queue.get_pending_input(&sess.active_turn).await;
- assert!(
- pending_input.iter().any(|item| {
- matches!(
- item,
- TurnInput::ResponseItem(ResponseItem::Message { role, content, .. })
- if role == "user"
- && content.iter().any(|content| matches!(
- content,
- ContentItem::InputText { text }
- if text.starts_with("<codex_internal_context source=\"goal\">")
- && text.trim_end().ends_with("</codex_internal_context>")
- && text.contains("The active thread goal objective was edited")
- && text.contains("Write a concise benchmark summary")
- ))
- )
- }),
- "expected objective-updated steering prompt in pending input: {pending_input:?}"
- );
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn external_active_goal_set_marks_current_turn_for_accounting() -> anyhow::Result<()> {
- let (sess, tc, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: false,
- },
- )
- .await;
- set_total_token_usage(&sess, post_goal_token_usage()).await;
-
- let state_db = goal_test_state_db(sess.as_ref()).await?;
- let goal = state_db
- .thread_goals()
- .replace_thread_goal(
- sess.thread_id,
- "Keep improving the benchmark",
- codex_state::ThreadGoalStatus::Active,
- /*token_budget*/ None,
- )
- .await?;
- sess.goal_runtime_apply(GoalRuntimeEvent::ExternalSet {
- external_set: ExternalGoalSet {
- goal,
- previous_status: ExternalGoalPreviousStatus::NewGoal,
- },
- })
- .await?;
-
- set_total_token_usage(
- &sess,
- TokenUsage {
- input_tokens: 65,
- cached_input_tokens: 10,
- output_tokens: 40,
- reasoning_output_tokens: 5,
- total_tokens: 110,
- },
- )
- .await;
- sess.goal_runtime_apply(GoalRuntimeEvent::ToolCompleted {
- turn_context: tc.as_ref(),
- tool_name: "shell_command",
- })
- .await?;
-
- let goal = state_db
- .thread_goals()
- .get_thread_goal(sess.thread_id)
- .await?
- .expect("goal should remain persisted");
- assert_eq!(codex_state::ThreadGoalStatus::Active, goal.status);
- assert_eq!(25, goal.tokens_used);
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-
- Ok(())
-}
-
-#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn completed_goal_accounts_current_turn_tokens_before_tool_response() -> anyhow::Result<()> {
- let server = start_mock_server().await;
- let mut builder = test_codex().with_config(|config| {
- config
- .features
- .enable(Feature::Goals)
- .expect("goal mode should be enableable in tests");
- });
- let test = builder.build(&server).await?;
- let responses = mount_sse_sequence(
- &server,
- vec![
- sse(vec![
- ev_response_created("resp-1"),
- ev_function_call(
- "call-create-goal",
- "create_goal",
- r#"{"objective":"write a report","token_budget":500}"#,
- ),
- ev_completed("resp-1"),
- ]),
- sse(vec![
- ev_response_created("resp-2"),
- ev_function_call(
- "call-complete-goal",
- "update_goal",
- r#"{"status":"complete"}"#,
- ),
- ev_completed_with_tokens("resp-2", /*total_tokens*/ 580),
- ]),
- sse(vec![
- ev_assistant_message("msg-1", "Goal complete."),
- ev_completed("resp-3"),
- ]),
- ],
- )
- .await;
-
- test.codex
- .submit(Op::UserInput {
- environments: None,
- items: vec![UserInput::Text {
- text: "write a report".into(),
- text_elements: Vec::new(),
- }],
- final_output_json_schema: None,
- responsesapi_client_metadata: None,
- additional_context: Default::default(),
- thread_settings: Default::default(),
- })
- .await?;
-
- tokio::time::timeout(std::time::Duration::from_secs(8), async {
- loop {
- let event = test.codex.next_event().await?;
- if matches!(event.msg, EventMsg::TurnComplete(_)) {
- return anyhow::Ok(());
- }
- }
- })
- .await??;
-
- let complete_output = responses
- .function_call_output_text("call-complete-goal")
- .expect("complete tool output should be sent to the model");
- let complete_output: serde_json::Value = serde_json::from_str(&complete_output)?;
- assert_eq!(complete_output["goal"]["tokensUsed"], 580);
- assert_eq!(complete_output["goal"]["status"], "complete");
- assert_eq!(complete_output["remainingTokens"], 0);
- assert_eq!(
- complete_output["completionBudgetReport"],
- "Goal achieved. Report final usage from this tool result's structured goal fields. If `goal.tokenBudget` is present, include token usage from `goal.tokensUsed` and `goal.tokenBudget`. If `goal.timeUsedSeconds` is greater than 0, summarize elapsed time in a concise, human-friendly form appropriate to the response language."
- );
- let requests = responses.requests();
- let completion_followup_request = requests
- .last()
- .expect("completion tool output should be sent in a follow-up request");
- assert!(
- !completion_followup_request.body_contains_text("budget_limited"),
- "completion follow-up should not include budget-limit steering"
- );
-
- let state_db = codex_state::StateRuntime::init(
- test.config.sqlite_home.clone(),
- test.config.model_provider_id.clone(),
- )
- .await?;
- let persisted_goal = state_db
- .thread_goals()
- .get_thread_goal(test.session_configured.thread_id)
- .await?
- .expect("goal should be persisted");
- assert_eq!(
- codex_state::ThreadGoalStatus::Complete,
- persisted_goal.status
- );
- assert_eq!(580, persisted_goal.tokens_used);
-
- Ok(())
-}
-
-#[tokio::test]
-async fn queue_only_mailbox_mail_waits_for_next_turn_after_answer_boundary() {
- let (sess, tc, _rx) = make_session_and_context_with_rx().await;
- let communication = InterAgentCommunication::new(
- AgentPath::try_from("/root/worker").expect("worker path should parse"),
- AgentPath::root(),
- Vec::new(),
- "late queue-only update".to_string(),
- /*trigger_turn*/ false,
- );
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: true,
- },
- )
- .await;
-
- sess.input_queue
- .defer_mailbox_delivery_to_next_turn(&sess.active_turn, &tc.sub_id)
- .await;
- sess.input_queue
- .enqueue_mailbox_communication(communication.clone())
- .await;
-
- assert!(
- !sess.input_queue.has_pending_input(&sess.active_turn).await,
- "queue-only mailbox mail should stay buffered once the current turn emitted its answer"
- );
- assert_eq!(
- sess.input_queue.get_pending_input(&sess.active_turn).await,
- Vec::new()
- );
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-
- assert_eq!(
- sess.input_queue.get_pending_input(&sess.active_turn).await,
- vec![TurnInput::ResponseItem(ResponseItem::from(
- communication.to_response_input_item()
- ))],
- );
-}
-
-#[tokio::test]
-async fn trigger_turn_mailbox_mail_waits_for_next_turn_after_answer_boundary() {
- let (sess, tc, _rx) = make_session_and_context_with_rx().await;
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: true,
- },
- )
- .await;
-
- sess.input_queue
- .defer_mailbox_delivery_to_next_turn(&sess.active_turn, &tc.sub_id)
- .await;
- sess.input_queue
- .enqueue_mailbox_communication(InterAgentCommunication::new(
- AgentPath::try_from("/root/worker").expect("worker path should parse"),
- AgentPath::root(),
- Vec::new(),
- "late trigger update".to_string(),
- /*trigger_turn*/ true,
- ))
- .await;
-
- assert!(
- !sess.input_queue.has_pending_input(&sess.active_turn).await,
- "trigger-turn mailbox mail should not extend the current turn after its answer boundary"
- );
-
- sess.abort_all_tasks(TurnAbortReason::Replaced).await;
-
- assert!(sess.input_queue.has_trigger_turn_mailbox_items().await);
-}
-
-#[tokio::test]
-async fn steered_input_reopens_mailbox_delivery_for_current_turn() {
- let (sess, tc, _rx) = make_session_and_context_with_rx().await;
- let communication = InterAgentCommunication::new(
- AgentPath::try_from("/root/worker").expect("worker path should parse"),
- AgentPath::root(),
- Vec::new(),
- "queued child update".to_string(),
- /*trigger_turn*/ false,
- );
- sess.spawn_task(
- Arc::clone(&tc),
- Vec::new(),
- NeverEndingTask {
- kind: TaskKind::Regular,
- listen_to_cancellation_token: true,
+ listen_to_cancellation_token: true,
},
)
.await;
@@ -10504,297 +9615,6 @@ async fn sample_rollout(
)
}
-#[tokio::test]
-async fn create_goal_tool_rejects_existing_goal() {
- let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new()));
- let handler = CreateGoalHandler;
-
- handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker: Arc::clone(&tracker),
- call_id: "create-goal-1".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Keep the watcher alive",
- "token_budget": 123,
- })
- .to_string(),
- },
- })
- .await
- .expect("initial create_goal should succeed");
-
- let response = handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker,
- call_id: "create-goal-2".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Replace the watcher",
- "token_budget": 456,
- })
- .to_string(),
- },
- })
- .await;
-
- let Err(FunctionCallError::RespondToModel(output)) = response else {
- panic!("expected create_goal to reject an existing goal");
- };
- assert_eq!(
- output,
- "cannot create a new goal because this thread already has a goal; use update_goal only when the existing goal is complete"
- );
-
- let goal = session
- .get_thread_goal()
- .await
- .expect("read thread goal")
- .expect("goal should still exist");
- assert_eq!(goal.objective, "Keep the watcher alive");
- assert_eq!(goal.token_budget, Some(123));
-}
-
-#[tokio::test]
-async fn update_goal_tool_rejects_pausing_goal() {
- let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new()));
- let create_handler = CreateGoalHandler;
- let update_handler = UpdateGoalHandler;
-
- create_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker: Arc::clone(&tracker),
- call_id: "create-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Keep the watcher alive",
- "token_budget": 123,
- })
- .to_string(),
- },
- })
- .await
- .expect("initial create_goal should succeed");
-
- let response = update_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker,
- call_id: "pause-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("update_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "status": "paused",
- })
- .to_string(),
- },
- })
- .await;
-
- let Err(FunctionCallError::RespondToModel(output)) = response else {
- panic!("expected update_goal to reject pausing a goal");
- };
- assert_eq!(
- output,
- "update_goal can only mark the existing goal complete or blocked; pause, resume, budget-limited, and usage-limited status changes are controlled by the user or system"
- );
-
- let goal = session
- .get_thread_goal()
- .await
- .expect("read thread goal")
- .expect("goal should still exist");
- assert_eq!(goal.status, ThreadGoalStatus::Active);
-}
-
-#[tokio::test]
-async fn update_goal_tool_marks_goal_blocked() {
- let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new()));
- let create_handler = CreateGoalHandler;
- let update_handler = UpdateGoalHandler;
-
- create_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker: Arc::clone(&tracker),
- call_id: "create-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Keep the watcher alive",
- "token_budget": 123,
- })
- .to_string(),
- },
- })
- .await
- .expect("initial create_goal should succeed");
-
- update_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker,
- call_id: "block-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("update_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "status": "blocked",
- })
- .to_string(),
- },
- })
- .await
- .expect("update_goal should mark the goal blocked");
-
- let goal = session
- .get_thread_goal()
- .await
- .expect("read thread goal")
- .expect("goal should still exist");
- assert_eq!(goal.status, ThreadGoalStatus::Blocked);
-}
-
-#[tokio::test]
-async fn update_goal_tool_rejects_usage_limited_goal() {
- let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new()));
- let create_handler = CreateGoalHandler;
- let update_handler = UpdateGoalHandler;
-
- create_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker: Arc::clone(&tracker),
- call_id: "create-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Keep the watcher alive",
- })
- .to_string(),
- },
- })
- .await
- .expect("initial create_goal should succeed");
-
- let response = update_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker,
- call_id: "usage-limit-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("update_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "status": "usageLimited",
- })
- .to_string(),
- },
- })
- .await;
-
- let Err(FunctionCallError::RespondToModel(output)) = response else {
- panic!("expected update_goal to reject usage-limiting a goal");
- };
- assert_eq!(
- output,
- "update_goal can only mark the existing goal complete or blocked; pause, resume, budget-limited, and usage-limited status changes are controlled by the user or system"
- );
-
- let goal = session
- .get_thread_goal()
- .await
- .expect("read thread goal")
- .expect("goal should still exist");
- assert_eq!(goal.status, ThreadGoalStatus::Active);
-}
-
-#[tokio::test]
-async fn update_goal_tool_marks_goal_complete() {
- let (session, turn_context, _rx, _codex_home) = make_goal_session_and_context_with_rx().await;
- let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new()));
- let create_handler = CreateGoalHandler;
- let update_handler = UpdateGoalHandler;
-
- create_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker: Arc::clone(&tracker),
- call_id: "create-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("create_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "objective": "Keep the watcher alive",
- "token_budget": 123,
- })
- .to_string(),
- },
- })
- .await
- .expect("initial create_goal should succeed");
-
- update_handler
- .handle(ToolInvocation {
- session: Arc::clone(&session),
- turn: Arc::clone(&turn_context),
- cancellation_token: CancellationToken::new(),
- tracker,
- call_id: "complete-goal".to_string(),
- tool_name: codex_tools::ToolName::plain("update_goal"),
- source: ToolCallSource::Direct,
- payload: ToolPayload::Function {
- arguments: serde_json::json!({
- "status": "complete",
- })
- .to_string(),
- },
- })
- .await
- .expect("update_goal should mark the goal complete");
-
- let goal = session
- .get_thread_goal()
- .await
- .expect("read thread goal")
- .expect("goal should still exist");
- assert_eq!(goal.status, ThreadGoalStatus::Complete);
-}
-
#[tokio::test]
async fn rejects_escalated_permissions_when_policy_not_on_request() {
use crate::exec_policy::ExecApprovalRequest;
diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs
index 76303345a7..9d4e7d1e82 100644
--- a/codex-rs/core/src/session/turn.rs
+++ b/codex-rs/core/src/session/turn.rs
@@ -18,7 +18,6 @@ use crate::compact_remote_v2::run_inline_remote_auto_compact_task as run_inline_
use crate::connectors;
use crate::context::ContextualUserFragment;
use crate::feedback_tags;
-use crate::goals::GoalRuntimeEvent;
use crate::hook_runtime::inspect_pending_input;
use crate::hook_runtime::record_additional_contexts;
use crate::hook_runtime::record_pending_input;
@@ -151,15 +150,6 @@ pub(crate) async fn run_turn(
let error = err.to_codex_protocol_error();
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
- if error == CodexErrorInfo::UsageLimitExceeded
- && let Err(err) = sess
- .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached {
- turn_context: turn_context.as_ref(),
- })
- .await
- {
- warn!("failed to usage-limit active goal after usage-limit error: {err}");
- }
error!("Failed to run pre-sampling compact");
return None;
}
@@ -294,17 +284,6 @@ pub(crate) async fn run_turn(
let error = err.to_codex_protocol_error();
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
- if error == CodexErrorInfo::UsageLimitExceeded
- && let Err(err) = sess
- .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached {
- turn_context: turn_context.as_ref(),
- })
- .await
- {
- warn!(
- "failed to usage-limit active goal after usage-limit error: {err}"
- );
- }
return None;
}
can_drain_pending_input = !model_needs_follow_up;
@@ -390,15 +369,6 @@ pub(crate) async fn run_turn(
let error = e.to_codex_protocol_error();
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
- if error == CodexErrorInfo::UsageLimitExceeded
- && let Err(err) = sess
- .goal_runtime_apply(GoalRuntimeEvent::UsageLimitReached {
- turn_context: turn_context.as_ref(),
- })
- .await
- {
- warn!("failed to usage-limit active goal after usage-limit error: {err}");
- }
sess.track_turn_codex_error(turn_context.as_ref(), &e);
let event = EventMsg::Error(e.to_error_event(/*message_prefix*/ None));
sess.send_event(&turn_context, event).await;
diff --git a/codex-rs/core/src/session/turn_context.rs b/codex-rs/core/src/session/turn_context.rs
index 66a32f2aa6..5f52912d59 100644
--- a/codex-rs/core/src/session/turn_context.rs
+++ b/codex-rs/core/src/session/turn_context.rs
@@ -91,7 +91,6 @@ pub struct TurnContext {
pub(crate) shell_environment_policy: ShellEnvironmentPolicy,
pub(crate) available_models: Vec<ModelPreset>,
pub(crate) unified_exec_shell_mode: UnifiedExecShellMode,
- pub(crate) goal_tools_supported: bool,
pub features: ManagedFeatures,
pub(crate) ghost_snapshot: GhostSnapshotConfig,
pub(crate) final_output_json_schema: Option<Value>,
@@ -170,10 +169,6 @@ impl TurnContext {
ToolEnvironmentMode::from_count(self.environments.turn_environments.len())
}
- pub(crate) fn goal_tools_enabled(&self) -> bool {
- self.goal_tools_supported && self.features.get().enabled(Feature::Goals)
- }
-
pub(crate) async fn with_model(
&self,
model: String,
@@ -264,7 +259,6 @@ impl TurnContext {
shell_environment_policy: self.shell_environment_policy.clone(),
available_models,
unified_exec_shell_mode: self.unified_exec_shell_mode.clone(),
- goal_tools_supported: self.goal_tools_supported,
features,
ghost_snapshot: self.ghost_snapshot.clone(),
final_output_json_schema: self.final_output_json_schema.clone(),
@@ -477,7 +471,6 @@ impl Session {
cwd: AbsolutePathBuf,
sub_id: String,
skills_outcome: Arc<SkillLoadOutcome>,
- goal_tools_supported: bool,
) -> TurnContext {
let reasoning_effort = session_configuration.collaboration_mode.reasoning_effort();
let reasoning_summary = session_configuration
@@ -568,7 +561,6 @@ impl Session {
shell_environment_policy: per_turn_config.permissions.shell_environment_policy.clone(),
available_models,
unified_exec_shell_mode,
- goal_tools_supported,
features: per_turn_config.features.clone(),
ghost_snapshot: per_turn_config.ghost_snapshot.clone(),
final_output_json_schema: None,
@@ -781,7 +773,6 @@ impl Session {
.skills_for_config(&skills_input, fs)
.await,
);
- let goal_tools_supported = !per_turn_config.ephemeral && self.state_db().is_some();
let mut turn_context: TurnContext = Self::make_turn_context(
self.thread_id(),
self.session_id(),
@@ -810,7 +801,6 @@ impl Session {
cwd,
sub_id,
skills_outcome,
- goal_tools_supported,
);
turn_context.realtime_active = self.conversation.running_state().await.is_some();
diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs
index 70466c9c2f..a9a664a505 100644
--- a/codex-rs/core/src/tasks/mod.rs
+++ b/codex-rs/core/src/tasks/mod.rs
@@ -23,7 +23,6 @@ use tracing::warn;
use crate::config::Config;
use crate::context::ContextualUserFragment;
-use crate::goals::GoalRuntimeEvent;
use crate::hook_runtime::inspect_pending_input;
use crate::hook_runtime::record_additional_contexts;
use crate::hook_runtime::record_pending_input;
@@ -342,15 +341,6 @@ impl Session {
.await
.clear_turn(&turn_context.sub_id);
- if let Err(err) = self
- .goal_runtime_apply(GoalRuntimeEvent::TurnStarted {
- turn_context: turn_context.as_ref(),
- token_usage: token_usage_at_turn_start.clone(),
- })
- .await
- {
- warn!("failed to apply goal runtime turn-start event: {err}");
- }
let pending_items = self.input_queue.get_pending_input(&self.active_turn).await;
let turn_state = {
let mut active = self.active_turn.lock().await;
@@ -504,15 +494,6 @@ impl Session {
self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref())
.await;
}
- if (aborted_turn || reason == TurnAbortReason::Interrupted)
- && let Err(err) = self
- .goal_runtime_apply(GoalRuntimeEvent::TaskAborted {
- turn_context: turn_context.as_deref(),
- })
- .await
- {
- warn!("failed to apply goal runtime abort event: {err}");
- }
if let Some(active_turn) = active_turn_to_clear {
// Let interrupted tasks observe cancellation before dropping pending approvals, or an
// in-flight approval wait can surface as a model-visible rejection before TurnAborted.
@@ -553,14 +534,6 @@ impl Session {
self.emit_turn_abort_lifecycle(reason.clone(), turn_context.extension_data.as_ref())
.await;
}
- if let Err(err) = self
- .goal_runtime_apply(GoalRuntimeEvent::TaskAborted {
- turn_context: turn_context.as_deref(),
- })
- .await
- {
- warn!("failed to apply goal runtime abort event: {err}");
- }
// Let interrupted tasks observe cancellation before dropping pending approvals, or an
// in-flight approval wait can surface as a model-visible rejection before TurnAborted.
self.input_queue.clear_pending(&active_turn).await;
@@ -760,15 +733,6 @@ impl Session {
});
self.emit_turn_stop_lifecycle(turn_context.extension_data.as_ref())
.await;
- if let Err(err) = self
- .goal_runtime_apply(GoalRuntimeEvent::TurnFinished {
- turn_context: turn_context.as_ref(),
- turn_completed: true,
- })
- .await
- {
- warn!("failed to apply goal runtime turn-finished event: {err}");
- }
let event = EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: turn_context.sub_id.clone(),
last_agent_message,
@@ -798,12 +762,6 @@ impl Session {
if !cleared_active_turn {
return;
}
- if let Err(err) = self
- .goal_runtime_apply(GoalRuntimeEvent::MaybeContinueIfIdle)
- .await
- {
- warn!("failed to apply goal runtime maybe-continue event: {err}");
- }
self.emit_thread_idle_lifecycle_if_idle().await;
}
diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs
index d130a35815..1cde8c9320 100644
--- a/codex-rs/core/src/thread_manager.rs
+++ b/codex-rs/core/src/thread_manager.rs
@@ -1343,9 +1343,6 @@ impl ThreadManagerState {
.await?;
if is_resumed_thread {
new_thread.thread.emit_thread_resume_lifecycle().await;
- if let Err(err) = new_thread.thread.apply_goal_resume_runtime_effects().await {
- warn!("failed to apply goal resume runtime effects: {err}");
- }
}
Ok(new_thread)
}
diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs
index 52a0f8eb3b..34ec682110 100644
--- a/codex-rs/core/src/thread_manager_tests.rs
+++ b/codex-rs/core/src/thread_manager_tests.rs
@@ -8,7 +8,6 @@ use crate::session::tests::make_session_and_context;
use crate::tasks::InterruptedTurnHistoryMarker;
use crate::tasks::interrupted_turn_history_marker;
use codex_extension_api::empty_extension_registry;
-use codex_features::Feature;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ReasoningItemReasoningSummary;
@@ -1501,103 +1500,3 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
1,
);
}
-
-#[tokio::test]
-async fn resumed_thread_keeps_paused_goal_paused() -> anyhow::Result<()> {
- let temp_dir = tempdir().expect("tempdir");
- let mut config = test_config().await;
- config.codex_home = temp_dir.path().join("codex-home").abs();
- config.cwd = config.codex_home.abs();
- config
- .features
- .enable(Feature::Goals)
- .expect("goals should be enableable in tests");
- std::fs::create_dir_all(&config.codex_home).expect("create codex home");
-
- let auth_manager =
- AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
- let state_db = init_state_db(&config).await;
- let manager = ThreadManager::new(
- &config,
- auth_manager.clone(),
- SessionSource::Exec,
- Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
- empty_extension_registry(),
- /*analytics_events_client*/ None,
- thread_store_from_config(&config, state_db.clone()),
- state_db.clone(),
- TEST_INSTALLATION_ID.to_string(),
- /*attestation_provider*/ None,
- );
-
- let source = manager
- .resume_thread_with_history(
- config.clone(),
- InitialHistory::Forked(vec![RolloutItem::ResponseItem(user_msg("keep working"))]),
- auth_manager.clone(),
- /*parent_trace*/ None,
- )
- .await
- .expect("create source thread");
- let source_path = source
- .thread
- .rollout_path()
- .expect("source rollout path should exist");
- source.thread.flush_rollout().await?;
- let state_db = source
- .thread
- .state_db()
- .expect("source thread should have a state db");
- state_db
- .thread_goals()
- .replace_thread_goal(
- source.thread_id,
- "Keep working until the task is done",
- codex_state::ThreadGoalStatus::Paused,
- /*token_budget*/ None,
- )
- .await?;
- source.thread.shutdown_and_wait().await?;
- manager.remove_thread(&source.thread_id).await;
-
- let resumed = manager
- .resume_thread_from_rollout(
- config.clone(),
- source_path,
- auth_manager,
- /*parent_trace*/ None,
- )
- .await
- .expect("resume source thread");
- let goal = state_db
- .thread_goals()
- .get_thread_goal(resumed.thread_id)
- .await?
- .expect("goal should still exist after resume");
- assert_eq!(codex_state::ThreadGoalStatus::Paused, goal.status);
- assert!(
- resumed
- .thread
- .codex
- .session
- .active_turn
- .lock()
- .await
- .is_none()
- );
-
- resumed.thread.continue_active_goal_if_idle().await?;
- assert!(
- resumed
- .thread
- .codex
- .session
- .active_turn
- .lock()
- .await
- .is_none()
- );
-
- resumed.thread.shutdown_and_wait().await?;
- Ok(())
-}
diff --git a/codex-rs/core/src/tools/handlers/goal.rs b/codex-rs/core/src/tools/handlers/goal.rs
deleted file mode 100644
index 694eafca65..0000000000
--- a/codex-rs/core/src/tools/handlers/goal.rs
+++ /dev/null
@@ -1,158 +0,0 @@
-//! Built-in model tool handlers for persisted thread goals.
-//!
-//! The public tool contract intentionally splits goal creation from stopped
-//! status updates: `create_goal` starts an active objective, while
-//! `update_goal` can only mark the existing goal complete or blocked.
-
-use crate::function_tool::FunctionCallError;
-use crate::tools::context::FunctionToolOutput;
-use codex_protocol::protocol::ThreadGoal;
-use codex_protocol::protocol::ThreadGoalStatus;
-use serde::Deserialize;
-use serde::Serialize;
-use std::fmt::Write as _;
-
-mod create_goal;
-mod get_goal;
-mod update_goal;
-
-pub use create_goal::CreateGoalHandler;
-pub use get_goal::GetGoalHandler;
-pub use update_goal::UpdateGoalHandler;
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "snake_case")]
-struct CreateGoalArgs {
- objective: String,
- token_budget: Option<i64>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "snake_case")]
-struct UpdateGoalArgs {
- status: ThreadGoalStatus,
-}
-
-#[derive(Debug, PartialEq, Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GoalToolResponse {
- goal: Option<ThreadGoal>,
- remaining_tokens: Option<i64>,
- completion_budget_report: Option<String>,
-}
-
-#[derive(Clone, Copy)]
-enum CompletionBudgetReport {
- Include,
- Omit,
-}
-
-impl GoalToolResponse {
- fn new(goal: Option<ThreadGoal>, report_mode: CompletionBudgetReport) -> Self {
- let remaining_tokens = goal.as_ref().and_then(|goal| {
- goal.token_budget
- .map(|budget| (budget - goal.tokens_used).max(0))
- });
- let completion_budget_report = match report_mode {
- CompletionBudgetReport::Include => goal
- .as_ref()
- .filter(|goal| goal.status == ThreadGoalStatus::Complete)
- .and_then(completion_budget_report),
- CompletionBudgetReport::Omit => None,
- };
- Self {
- goal,
- remaining_tokens,
- completion_budget_report,
- }
- }
-}
-
-fn format_goal_error(err: anyhow::Error) -> String {
- let mut message = err.to_string();
- for cause in err.chain().skip(1) {
- let _ = write!(message, ": {cause}");
- }
- message
-}
-
-fn goal_response(
- goal: Option<ThreadGoal>,
- completion_budget_report: CompletionBudgetReport,
-) -> Result<FunctionToolOutput, FunctionCallError> {
- let response =
- serde_json::to_string_pretty(&GoalToolResponse::new(goal, completion_budget_report))
- .map_err(|err| FunctionCallError::Fatal(err.to_string()))?;
- Ok(FunctionToolOutput::from_text(response, Some(true)))
-}
-
-fn completion_budget_report(goal: &ThreadGoal) -> Option<String> {
- if goal.token_budget.is_none() && goal.time_used_seconds <= 0 {
- None
- } else {
- Some(
- "Goal achieved. Report final usage from this tool result's structured goal fields. If `goal.tokenBudget` is present, include token usage from `goal.tokensUsed` and `goal.tokenBudget`. If `goal.timeUsedSeconds` is greater than 0, summarize elapsed time in a concise, human-friendly form appropriate to the response language."
- .to_string(),
- )
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use codex_protocol::ThreadId;
- use pretty_assertions::assert_eq;
-
- #[test]
- fn completed_budgeted_goal_response_reports_final_usage() {
- let goal = ThreadGoal {
- thread_id: ThreadId::new(),
- objective: "Keep optimizing".to_string(),
- status: ThreadGoalStatus::Complete,
- token_budget: Some(10_000),
- tokens_used: 3_250,
- time_used_seconds: 75,
- created_at: 1,
- updated_at: 2,
- };
-
- let response = GoalToolResponse::new(Some(goal.clone()), CompletionBudgetReport::Include);
-
- assert_eq!(
- response,
- GoalToolResponse {
- goal: Some(goal),
- remaining_tokens: Some(6_750),
- completion_budget_report: Some(
- "Goal achieved. Report final usage from this tool result's structured goal fields. If `goal.tokenBudget` is present, include token usage from `goal.tokensUsed` and `goal.tokenBudget`. If `goal.timeUsedSeconds` is greater than 0, summarize elapsed time in a concise, human-friendly form appropriate to the response language."
- .to_string()
- ),
- }
- );
- }
-
- #[test]
- fn completed_unbudgeted_goal_response_omits_budget_report() {
- let goal = ThreadGoal {
- thread_id: ThreadId::new(),
- objective: "Write a poem".to_string(),
- status: ThreadGoalStatus::Complete,
- token_budget: None,
- tokens_used: 120,
- time_used_seconds: 0,
- created_at: 1,
- updated_at: 2,
- };
-
- let response = GoalToolResponse::new(Some(goal.clone()), CompletionBudgetReport::Include);
-
- assert_eq!(
- response,
- GoalToolResponse {
- goal: Some(goal),
- remaining_tokens: None,
- completion_budget_report: None,
- }
- );
- }
-}
diff --git a/codex-rs/core/src/tools/handlers/goal/create_goal.rs b/codex-rs/core/src/tools/handlers/goal/create_goal.rs
deleted file mode 100644
index 1791a5e85f..0000000000
--- a/codex-rs/core/src/tools/handlers/goal/create_goal.rs
+++ /dev/null
@@ -1,78 +0,0 @@
-use crate::function_tool::FunctionCallError;
-use crate::goals::CreateGoalRequest;
-use crate::tools::context::ToolInvocation;
-use crate::tools::context::ToolPayload;
-use crate::tools::context::boxed_tool_output;
-use crate::tools::handlers::goal_spec::CREATE_GOAL_TOOL_NAME;
-use crate::tools::handlers::goal_spec::create_create_goal_tool;
-use crate::tools::handlers::parse_arguments;
-use crate::tools::registry::CoreToolRuntime;
-use crate::tools::registry::ToolExecutor;
-use codex_tools::ToolName;
-use codex_tools::ToolSpec;
-
-use super::CompletionBudgetReport;
-use super::CreateGoalArgs;
-use super::format_goal_error;
-use super::goal_response;
-
-pub struct CreateGoalHandler;
-
-#[async_trait::async_trait]
-impl ToolExecutor<ToolInvocation> for CreateGoalHandler {
- fn tool_name(&self) -> ToolName {
- ToolName::plain(CREATE_GOAL_TOOL_NAME)
- }
-
- fn spec(&self) -> ToolSpec {
- create_create_goal_tool()
- }
-
- async fn handle(
- &self,
- invocation: ToolInvocation,
- ) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
- let ToolInvocation {
- session,
- turn,
- payload,
- ..
- } = invocation;
-
- let arguments = match payload {
- ToolPayload::Function { arguments } => arguments,
- _ => {
- return Err(FunctionCallError::RespondToModel(
- "goal handler received unsupported payload".to_string(),
- ));
- }
- };
-
- let args: CreateGoalArgs = parse_arguments(&arguments)?;
- let goal = session
- .create_thread_goal(
- turn.as_ref(),
- CreateGoalRequest {
- objective: args.objective,
- token_budget: args.token_budget,
- },
- )
- .await
- .map_err(|err| {
- if err
- .chain()
- .any(|cause| cause.to_string().contains("already has a goal"))
- {
- FunctionCallError::RespondToModel(
- "cannot create a new goal because this thread already has a goal; use update_goal only when the existing goal is complete"
- .to_string(),
- )
- } else {
- FunctionCallError::RespondToModel(format_goal_error(err))
- }
- })?;
- goal_response(Some(goal), CompletionBudgetReport::Omit).map(boxed_tool_output)
- }
-}
-
-impl CoreToolRuntime for CreateGoalHandler {}
diff --git a/codex-rs/core/src/tools/handlers/goal/get_goal.rs b/codex-rs/core/src/tools/handlers/goal/get_goal.rs
deleted file mode 100644
index ff46070675..0000000000
--- a/codex-rs/core/src/tools/handlers/goal/get_goal.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-use crate::function_tool::FunctionCallError;
-use crate::tools::context::ToolInvocation;
-use crate::tools::context::ToolPayload;
-use crate::tools::context::boxed_tool_output;
-use crate::tools::handlers::goal_spec::GET_GOAL_TOOL_NAME;
-use crate::tools::handlers::goal_spec::create_get_goal_tool;
-use crate::tools::registry::CoreToolRuntime;
-use crate::tools::registry::ToolExecutor;
-use codex_tools::ToolName;
-use codex_tools::ToolSpec;
-
-use super::CompletionBudgetReport;
-use super::format_goal_error;
-use super::goal_response;
-
-pub struct GetGoalHandler;
-
-#[async_trait::async_trait]
-impl ToolExecutor<ToolInvocation> for GetGoalHandler {
- fn tool_name(&self) -> ToolName {
- ToolName::plain(GET_GOAL_TOOL_NAME)
- }
-
- fn spec(&self) -> ToolSpec {
- create_get_goal_tool()
- }
-
- async fn handle(
- &self,
- invocation: ToolInvocation,
- ) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
- let ToolInvocation {
- session, payload, ..
- } = invocation;
-
- match payload {
- ToolPayload::Function { .. } => {
- let goal = session
- .get_thread_goal()
- .await
- .map_err(|err| FunctionCallError::RespondToModel(format_goal_error(err)))?;
- goal_response(goal, CompletionBudgetReport::Omit).map(boxed_tool_output)
- }
- _ => Err(FunctionCallError::RespondToModel(
- "get_goal handler received unsupported payload".to_string(),
- )),
- }
- }
-}
-
-impl CoreToolRuntime for GetGoalHandler {}
diff --git a/codex-rs/core/src/tools/handlers/goal/update_goal.rs b/codex-rs/core/src/tools/handlers/goal/update_goal.rs
deleted file mode 100644
index 373c849fc2..0000000000
--- a/codex-rs/core/src/tools/handlers/goal/update_goal.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-use crate::function_tool::FunctionCallError;
-use crate::goals::GoalRuntimeEvent;
-use crate::goals::SetGoalRequest;
-use crate::tools::context::ToolInvocation;
-use crate::tools::context::ToolPayload;
-use crate::tools::context::boxed_tool_output;
-use crate::tools::handlers::goal_spec::UPDATE_GOAL_TOOL_NAME;
-use crate::tools::handlers::goal_spec::create_update_goal_tool;
-use crate::tools::handlers::parse_arguments;
-use crate::tools::registry::CoreToolRuntime;
-use crate::tools::registry::ToolExecutor;
-use codex_protocol::protocol::ThreadGoalStatus;
-use codex_tools::ToolName;
-use codex_tools::ToolSpec;
-
-use super::CompletionBudgetReport;
-use super::UpdateGoalArgs;
-use super::format_goal_error;
-use super::goal_response;
-
-pub struct UpdateGoalHandler;
-
-#[async_trait::async_trait]
-impl ToolExecutor<ToolInvocation> for UpdateGoalHandler {
- fn tool_name(&self) -> ToolName {
- ToolName::plain(UPDATE_GOAL_TOOL_NAME)
- }
-
- fn spec(&self) -> ToolSpec {
- create_update_goal_tool()
- }
-
- async fn handle(
- &self,
- invocation: ToolInvocation,
- ) -> Result<Box<dyn crate::tools::context::ToolOutput>, FunctionCallError> {
- let ToolInvocation {
- session,
- turn,
- payload,
- ..
- } = invocation;
-
- let arguments = match payload {
- ToolPayload::Function { arguments } => arguments,
- _ => {
- return Err(FunctionCallError::RespondToModel(
- "update_goal handler received unsupported payload".to_string(),
- ));
- }
- };
-
- let args: UpdateGoalArgs = parse_arguments(&arguments)?;
- if !matches!(
- args.status,
- ThreadGoalStatus::Complete | ThreadGoalStatus::Blocked
- ) {
- return Err(FunctionCallError::RespondToModel(
- "update_goal can only mark the existing goal complete or blocked; pause, resume, budget-limited, and usage-limited status changes are controlled by the user or system"
- .to_string(),
- ));
- }
- session
- .goal_runtime_apply(GoalRuntimeEvent::ToolCompletedGoal {
- turn_context: turn.as_ref(),
- })
- .await
- .map_err(|err| FunctionCallError::RespondToModel(format_goal_error(err)))?;
- let goal = session
- .set_thread_goal(
- turn.as_ref(),
- SetGoalRequest {
- objective: None,
- status: Some(args.status),
- token_budget: None,
- },
- )
- .await
- .map_err(|err| FunctionCallError::RespondToModel(format_goal_error(err)))?;
- let completion_budget_report = if args.status == ThreadGoalStatus::Complete {
- CompletionBudgetReport::Include
- } else {
- CompletionBudgetReport::Omit
- };
- goal_response(Some(goal), completion_budget_report).map(boxed_tool_output)
- }
-}
-
-impl CoreToolRuntime for UpdateGoalHandler {}
diff --git a/codex-rs/core/src/tools/handlers/goal_spec.rs b/codex-rs/core/src/tools/handlers/goal_spec.rs
deleted file mode 100644
index da8e23d305..0000000000
--- a/codex-rs/core/src/tools/handlers/goal_spec.rs
+++ /dev/null
@@ -1,120 +0,0 @@
-//! Responses API tool definitions for persisted thread goals.
-//!
-//! These specs expose goal read/update primitives to the model while keeping
-//! usage accounting system-managed.
-
-use codex_tools::JsonSchema;
-use codex_tools::ResponsesApiTool;
-use codex_tools::ToolSpec;
-use serde_json::json;
-use std::collections::BTreeMap;
-
-pub const GET_GOAL_TOOL_NAME: &str = "get_goal";
-pub const CREATE_GOAL_TOOL_NAME: &str = "create_goal";
-pub const UPDATE_GOAL_TOOL_NAME: &str = "update_goal";
-
-pub fn create_get_goal_tool() -> ToolSpec {
- ToolSpec::Function(ResponsesApiTool {
- name: GET_GOAL_TOOL_NAME.to_string(),
- description: "Get the current goal for this thread, including status, budgets, token and elapsed-time usage, and remaining token budget."
- .to_string(),
- strict: false,
- defer_loading: None,
- parameters: JsonSchema::object(BTreeMap::new(), Some(Vec::new()), Some(false.into())),
- output_schema: None,
- })
-}
-
-pub fn create_create_goal_tool() -> ToolSpec {
- let properties = BTreeMap::from([
- (
- "objective".to_string(),
- JsonSchema::string(Some(
- "Required. The concrete objective to start pursuing. This starts a new active goal only when no goal is currently defined; if a goal already exists, this tool fails."
- .to_string(),
- )),
- ),
- (
- "token_budget".to_string(),
- JsonSchema::integer(Some(
- "Positive token budget for the new goal. Omit unless explicitly requested."
- .to_string(),
- )),
- ),
- ]);
-
- ToolSpec::Function(ResponsesApiTool {
- name: CREATE_GOAL_TOOL_NAME.to_string(),
- description: format!(
- r#"Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks.
-Set token_budget only when an explicit token budget is requested. Fails if a goal exists; use {UPDATE_GOAL_TOOL_NAME} only for status."#
- ),
- strict: false,
- defer_loading: None,
- parameters: JsonSchema::object(
- properties,
- /*required*/ Some(vec!["objective".to_string()]),
- Some(false.into()),
- ),
- output_schema: None,
- })
-}
-
-pub fn create_update_goal_tool() -> ToolSpec {
- let properties = BTreeMap::from([(
- "status".to_string(),
- JsonSchema::string_enum(
- vec![json!("complete"), json!("blocked")],
- Some(
- "Required. Set to `complete` only when the objective is achieved and no required work remains. Set to `blocked` only after the same blocking condition has recurred for at least three consecutive goal turns and the agent is at an impasse. After a previously blocked goal is resumed, the resumed run starts a fresh blocked audit."
- .to_string(),
- ),
- ),
- )]);
-
- ToolSpec::Function(ResponsesApiTool {
- name: UPDATE_GOAL_TOOL_NAME.to_string(),
- description: r#"Update the existing goal.
-Use this tool only to mark the goal achieved or genuinely blocked.
-Set status to `complete` only when the objective has actually been achieved and no required work remains.
-Set status to `blocked` only when the same blocking condition has repeated for at least three consecutive goal turns, counting the original/user-triggered turn and any automatic continuations, and the agent cannot make meaningful progress without user input or an external-state change.
-If the user resumes a goal that was previously marked `blocked`, treat the resumed run as a fresh blocked audit. If the same blocking condition then repeats for at least three consecutive resumed goal turns, set status to `blocked` again.
-Once the blocked threshold is satisfied, do not keep reporting that you are still blocked while leaving the goal active; set status to `blocked`.
-Do not use `blocked` merely because the work is hard, slow, uncertain, incomplete, or would benefit from clarification.
-Do not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.
-You cannot use this tool to pause, resume, budget-limit, or usage-limit a goal; those status changes are controlled by the user or system.
-When marking a budgeted goal achieved with status `complete`, report the final token usage from the tool result to the user."#
- .to_string(),
- strict: false,
- defer_loading: None,
- parameters: JsonSchema::object(
- properties,
- /*required*/ Some(vec!["status".to_string()]),
- Some(false.into()),
- ),
- output_schema: None,
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn update_goal_tool_exposes_complete_and_blocked_statuses() {
- let ToolSpec::Function(tool) = create_update_goal_tool() else {
- panic!("update_goal should be a function tool");
- };
- let status = tool
- .parameters
- .properties
- .as_ref()
- .and_then(|properties| properties.get("status"))
- .expect("status property should exist");
-
- assert_eq!(
- status.enum_values,
- Some(vec![json!("complete"), json!("blocked")])
- );
- }
-}
diff --git a/codex-rs/core/src/tools/handlers/mod.rs b/codex-rs/core/src/tools/handlers/mod.rs
index d6963f0761..fdfb809965 100644
--- a/codex-rs/core/src/tools/handlers/mod.rs
+++ b/codex-rs/core/src/tools/handlers/mod.rs
@@ -4,8 +4,6 @@ pub(crate) mod apply_patch;
pub(crate) mod apply_patch_spec;
mod dynamic;
pub(crate) mod extension_tools;
-mod goal;
-pub(crate) mod goal_spec;
mod list_available_plugins_to_install;
pub(crate) mod list_available_plugins_to_install_spec;
mod mcp;
@@ -53,9 +51,6 @@ pub use apply_patch::ApplyPatchHandler;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::protocol::AskForApproval;
pub use dynamic::DynamicToolHandler;
-pub use goal::CreateGoalHandler;
-pub use goal::GetGoalHandler;
-pub use goal::UpdateGoalHandler;
pub use list_available_plugins_to_install::ListAvailablePluginsToInstallHandler;
pub use mcp::McpHandler;
pub use mcp_resource::ListMcpResourceTemplatesHandler;
diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs
index b2a0b7704a..1cc5e67eb5 100644
--- a/codex-rs/core/src/tools/registry.rs
+++ b/codex-rs/core/src/tools/registry.rs
@@ -5,7 +5,6 @@ use std::sync::atomic::Ordering;
use std::time::Duration;
use crate::function_tool::FunctionCallError;
-use crate::goals::GoalRuntimeEvent;
use crate::hook_runtime::PreToolUseHookResult;
use crate::hook_runtime::record_additional_contexts;
use crate::hook_runtime::run_post_tool_use_hooks;
@@ -34,7 +33,6 @@ use codex_tools::ToolSearchInfo;
use codex_tools::ToolSpec;
use futures::future::BoxFuture;
use serde_json::Value;
-use tracing::warn;
pub(crate) type ToolTelemetryTags = Vec<(&'static str, String)>;
@@ -649,25 +647,13 @@ impl ToolRegistry {
handler_executed: true,
},
};
- let finished = notify_tool_finish_if_unclaimed(
+ notify_tool_finish_if_unclaimed(
&invocation,
terminal_outcome_reached.as_deref(),
lifecycle_outcome,
)
.await;
- if finished
- && let Err(err) = invocation
- .session
- .goal_runtime_apply(GoalRuntimeEvent::ToolCompleted {
- turn_context: invocation.turn.as_ref(),
- tool_name: tool_name.name.as_str(),
- })
- .await
- {
- warn!("failed to account thread goal progress after tool call: {err}");
- }
-
match result {
Ok(_) => {
let mut guard = response_cell.lock().await;
diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs
index 47d2ac6726..514432c880 100644
--- a/codex-rs/core/src/tools/spec_plan.rs
+++ b/codex-rs/core/src/tools/spec_plan.rs
@@ -6,11 +6,9 @@ use crate::tools::context::ToolInvocation;
use crate::tools::handlers::ApplyPatchHandler;
use crate::tools::handlers::CodeModeExecuteHandler;
use crate::tools::handlers::CodeModeWaitHandler;
-use crate::tools::handlers::CreateGoalHandler;
use crate::tools::handlers::DynamicToolHandler;
use crate::tools::handlers::ExecCommandHandler;
use crate::tools::handlers::ExecCommandHandlerOptions;
-use crate::tools::handlers::GetGoalHandler;
use crate::tools::handlers::ListAvailablePluginsToInstallHandler;
use crate::tools::handlers::ListMcpResourceTemplatesHandler;
use crate::tools::handlers::ListMcpResourcesHandler;
@@ -24,7 +22,6 @@ use crate::tools::handlers::ShellCommandHandler;
use crate::tools::handlers::ShellCommandHandlerOptions;
use crate::tools::handlers::TestSyncHandler;
use crate::tools::handlers::ToolSearchHandler;
-use crate::tools::handlers::UpdateGoalHandler;
use crate::tools::handlers::ViewImageHandler;
use crate::tools::handlers::WriteStdinHandler;
use crate::tools::handlers::agent_jobs::ReportAgentJobResultHandler;
@@ -305,14 +302,6 @@ fn collab_tools_enabled(turn_context: &TurnContext) -> bool {
}
}
-fn goal_tools_enabled(turn_context: &TurnContext) -> bool {
- turn_context.goal_tools_enabled()
- && !matches!(
- turn_context.session_source,
- SessionSource::SubAgent(SubAgentSource::Review)
- )
-}
-
fn agent_jobs_tools_enabled(turn_context: &TurnContext) -> bool {
turn_context.features.get().enabled(Feature::SpawnCsv) && collab_tools_enabled(turn_context)
}
@@ -558,8 +547,8 @@ fn add_tool_sources(context: &CoreToolPlanContext<'_>, planned_tools: &mut Plann
add_core_utility_tools(context, planned_tools);
add_collaboration_tools(context, planned_tools);
add_mcp_runtime_tools(context, planned_tools);
- add_dynamic_tools(context, planned_tools);
add_extension_tools(context, planned_tools);
+ add_dynamic_tools(context, planned_tools);
for spec in hosted_model_tool_specs(context) {
planned_tools.add_hosted_spec(spec);
}
@@ -639,11 +628,6 @@ fn add_core_utility_tools(context: &CoreToolPlanContext<'_>, planned_tools: &mut
let environment_mode = turn_context.tool_environment_mode();
planned_tools.add(PlanHandler);
- if goal_tools_enabled(turn_context) {
- planned_tools.add(GetGoalHandler);
- planned_tools.add(CreateGoalHandler);
- planned_tools.add(UpdateGoalHandler);
- }
if turn_context.config.experimental_request_user_input_enabled {
planned_tools.add(RequestUserInputHandler {
diff --git a/codex-rs/core/src/tools/spec_plan_tests.rs b/codex-rs/core/src/tools/spec_plan_tests.rs
index 17dfdc7a74..5fe811b19e 100644
--- a/codex-rs/core/src/tools/spec_plan_tests.rs
+++ b/codex-rs/core/src/tools/spec_plan_tests.rs
@@ -619,36 +619,7 @@ async fn environment_count_controls_environment_backed_tools() {
}
#[tokio::test]
-async fn host_context_gates_goal_and_agent_job_tools() {
- let feature_disabled = probe(|turn| {
- set_feature(turn, Feature::Goals, /*enabled*/ false);
- turn.goal_tools_supported = true;
- })
- .await;
- feature_disabled.assert_visible_lacks(&["get_goal", "create_goal", "update_goal"]);
-
- let host_disabled = probe(|turn| {
- set_feature(turn, Feature::Goals, /*enabled*/ true);
- turn.goal_tools_supported = false;
- })
- .await;
- host_disabled.assert_visible_lacks(&["get_goal", "create_goal", "update_goal"]);
-
- let enabled = probe(|turn| {
- set_feature(turn, Feature::Goals, /*enabled*/ true);
- turn.goal_tools_supported = true;
- })
- .await;
- enabled.assert_visible_contains(&["get_goal", "create_goal", "update_goal"]);
-
- let review_thread = probe(|turn| {
- set_feature(turn, Feature::Goals, /*enabled*/ true);
- turn.goal_tools_supported = true;
- turn.session_source = SessionSource::SubAgent(SubAgentSource::Review);
- })
- .await;
- review_thread.assert_visible_lacks(&["get_goal", "create_goal", "update_goal"]);
-
+async fn host_context_gates_agent_job_tools() {
let normal_agent_job = probe(|turn| {
set_feature(turn, Feature::SpawnCsv, /*enabled*/ true);
})
diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs
index dddfd4af68..640c1c1db1 100644
--- a/codex-rs/core/tests/suite/prompt_caching.rs
+++ b/codex-rs/core/tests/suite/prompt_caching.rs
@@ -188,9 +188,6 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> {
};
expected_tools_names.extend([
"update_plan",
- "get_goal",
- "create_goal",
- "update_goal",
"request_user_input",
"apply_patch",
"view_image",