From 59507b849126f598ed7c624bbaf75d7ebc5588c2 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 20 May 2026 15:54:29 +0200 Subject: [PATCH 1/6] feat: expose turn-start metadata to extensions (#23688) ## Why The goal extension needs more context when a turn starts than `turn_store` alone provides. In particular, goal accounting needs the stable turn id, the effective collaboration mode, and the cumulative token-usage baseline captured at turn start so it can: - suppress goal accounting for plan-mode turns - compute exact per-turn deltas from cumulative `total_token_usage` snapshots instead of relying on the most recent usage event alone - keep the extension-owned accounting path aligned with the host turn lifecycle ## What - extend `codex_extension_api::TurnStartInput` to expose `turn_id`, `collaboration_mode`, and `token_usage_at_turn_start` - pass the full `TurnContext` plus the captured token-usage baseline through the turn-start lifecycle emission path - initialize goal turn accounting from the turn-start baseline and collaboration mode - switch goal token accounting to compute deltas from cumulative `total_token_usage` snapshots - add coverage for the new turn-start lifecycle fields and for goal-accounting baseline behavior ## Testing - added `turn_start_lifecycle_exposes_turn_metadata_and_token_baseline` in `codex-rs/core/src/session/tests.rs` - added `ext/goal/tests/accounting.rs` coverage for baseline-aware goal accounting and plan-mode suppression --- codex-rs/core/src/session/tests.rs | 102 ++++++++++++++++++ codex-rs/core/src/tasks/lifecycle.rs | 13 ++- codex-rs/core/src/tasks/mod.rs | 4 +- .../src/contributors/turn_lifecycle.rs | 8 ++ codex-rs/ext/goal/BUILD.bazel | 1 + codex-rs/ext/goal/src/accounting.rs | 52 +++++++-- codex-rs/ext/goal/src/extension.rs | 11 +- codex-rs/ext/goal/tests/accounting.rs | 68 ++++++++++++ 8 files changed, 242 insertions(+), 17 deletions(-) create mode 100644 codex-rs/ext/goal/tests/accounting.rs diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 175f022289..5318b72151 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1911,6 +1911,108 @@ async fn record_token_usage_info_notifies_extension_contributors() { assert_eq!(expected, actual); } +#[tokio::test] +async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { + struct SessionTurnStartMarker; + struct ThreadTurnStartMarker; + + #[derive(Debug, PartialEq, Eq)] + struct RecordedTurnStart { + turn_id: String, + collaboration_mode: CollaborationMode, + token_usage_at_turn_start: TokenUsage, + saw_session_store: bool, + saw_thread_store: bool, + } + + struct TurnStartRecorder { + records: Arc>>, + } + + #[async_trait::async_trait] + impl codex_extension_api::TurnLifecycleContributor for TurnStartRecorder { + async fn on_turn_start(&self, input: codex_extension_api::TurnStartInput<'_>) { + self.records + .lock() + .expect("turn start records lock") + .push(RecordedTurnStart { + turn_id: input.turn_id.to_string(), + collaboration_mode: input.collaboration_mode.clone(), + token_usage_at_turn_start: input.token_usage_at_turn_start.clone(), + saw_session_store: input + .session_store + .get::() + .is_some(), + saw_thread_store: input.thread_store.get::().is_some(), + }); + } + } + + let (mut session, turn_context) = make_session_and_context().await; + let records = Arc::new(std::sync::Mutex::new(Vec::new())); + let mut builder = codex_extension_api::ExtensionRegistryBuilder::::new(); + builder.turn_lifecycle_contributor(Arc::new(TurnStartRecorder { + records: Arc::clone(&records), + })); + session.services.extensions = Arc::new(builder.build()); + session + .services + .session_extension_data + .insert(SessionTurnStartMarker); + session + .services + .thread_extension_data + .insert(ThreadTurnStartMarker); + + let token_usage_at_turn_start = TokenUsage { + input_tokens: 120, + cached_input_tokens: 15, + output_tokens: 40, + reasoning_output_tokens: 9, + total_tokens: 169, + }; + session + .state + .lock() + .await + .set_token_info(Some(TokenUsageInfo { + total_token_usage: token_usage_at_turn_start.clone(), + last_token_usage: TokenUsage::default(), + model_context_window: turn_context.model_context_window(), + })); + + let turn_context = Arc::new(turn_context); + let session = Arc::new(session); + session + .spawn_task( + Arc::clone(&turn_context), + Vec::new(), + NeverEndingTask { + kind: TaskKind::Regular, + listen_to_cancellation_token: true, + }, + ) + .await; + + session.abort_all_tasks(TurnAbortReason::Interrupted).await; + + let actual = records + .lock() + .expect("turn start records lock") + .drain(..) + .collect::>(); + assert_eq!( + vec![RecordedTurnStart { + turn_id: turn_context.sub_id.clone(), + collaboration_mode: turn_context.collaboration_mode.clone(), + token_usage_at_turn_start, + saw_session_store: true, + saw_thread_store: true, + }], + actual + ); +} + #[tokio::test] async fn config_change_contributor_observes_effective_config_changes() { struct SessionConfigMarker; diff --git a/codex-rs/core/src/tasks/lifecycle.rs b/codex-rs/core/src/tasks/lifecycle.rs index 94b51647c9..8b934175cf 100644 --- a/codex-rs/core/src/tasks/lifecycle.rs +++ b/codex-rs/core/src/tasks/lifecycle.rs @@ -1,16 +1,25 @@ use codex_extension_api::ExtensionData; +use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; use crate::session::session::Session; +use crate::session::turn_context::TurnContext; impl Session { - pub(super) async fn emit_turn_start_lifecycle(&self, turn_store: &ExtensionData) { + pub(super) async fn emit_turn_start_lifecycle( + &self, + turn_context: &TurnContext, + token_usage_at_turn_start: &TokenUsage, + ) { for contributor in self.services.extensions.turn_lifecycle_contributors() { contributor .on_turn_start(codex_extension_api::TurnStartInput { + turn_id: turn_context.sub_id.as_str(), + collaboration_mode: &turn_context.collaboration_mode, + token_usage_at_turn_start, session_store: &self.services.session_extension_data, thread_store: &self.services.thread_extension_data, - turn_store, + turn_store: turn_context.extension_data.as_ref(), }) .await; } diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 164e65f07c..80ddfee897 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -357,7 +357,7 @@ impl Session { debug_assert!(turn.tasks.is_empty()); Arc::clone(&turn.turn_state) }; - turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start; + turn_state.lock().await.token_usage_at_turn_start = token_usage_at_turn_start.clone(); let mut pending_items = queued_response_items .into_iter() .map(TurnInput::ResponseInputItem) @@ -366,7 +366,7 @@ impl Session { self.input_queue .extend_pending_input_for_turn_state(turn_state.as_ref(), pending_items) .await; - self.emit_turn_start_lifecycle(turn_context.extension_data.as_ref()) + self.emit_turn_start_lifecycle(turn_context.as_ref(), &token_usage_at_turn_start) .await; let turn_extension_data = Arc::clone(&turn_context.extension_data); diff --git a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs index 0b53183e28..bbd3ae8f39 100644 --- a/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs +++ b/codex-rs/ext/extension-api/src/contributors/turn_lifecycle.rs @@ -1,9 +1,17 @@ +use codex_protocol::config_types::CollaborationMode; +use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TurnAbortReason; use crate::ExtensionData; /// Input supplied when the host starts a turn. pub struct TurnStartInput<'a> { + /// Stable host-owned turn identifier. + pub turn_id: &'a str, + /// Effective collaboration mode for this turn. + pub collaboration_mode: &'a CollaborationMode, + /// Total token usage snapshot captured when the turn started. + pub token_usage_at_turn_start: &'a TokenUsage, /// Store scoped to the host session runtime. pub session_store: &'a ExtensionData, /// Store scoped to this thread runtime. diff --git a/codex-rs/ext/goal/BUILD.bazel b/codex-rs/ext/goal/BUILD.bazel index 037313da37..05b80c3706 100644 --- a/codex-rs/ext/goal/BUILD.bazel +++ b/codex-rs/ext/goal/BUILD.bazel @@ -3,4 +3,5 @@ load("//:defs.bzl", "codex_rust_crate") codex_rust_crate( name = "goal", crate_name = "codex_goal_extension", + integration_compile_data_extra = ["src/accounting.rs"], ) diff --git a/codex-rs/ext/goal/src/accounting.rs b/codex-rs/ext/goal/src/accounting.rs index 712e325849..cc04684169 100644 --- a/codex-rs/ext/goal/src/accounting.rs +++ b/codex-rs/ext/goal/src/accounting.rs @@ -1,3 +1,4 @@ +use codex_protocol::config_types::ModeKind; use codex_protocol::protocol::TokenUsage; use std::collections::HashMap; use std::sync::Mutex; @@ -17,6 +18,8 @@ struct GoalAccountingInner { #[derive(Debug, Default)] struct GoalTurnAccounting { token_delta: i64, + last_accounted_token_usage: TokenUsage, + account_tokens: bool, stopped: bool, } @@ -27,24 +30,42 @@ pub(crate) struct RecordedTokenDelta { } impl GoalAccountingState { - pub(crate) fn start_turn(&self, turn_id: impl Into) { + pub(crate) fn start_turn( + &self, + turn_id: impl Into, + collaboration_mode: ModeKind, + token_usage_at_turn_start: &TokenUsage, + ) { let turn_id = turn_id.into(); - self.inner().turns.entry(turn_id).or_default().stopped = false; + self.inner().turns.insert( + turn_id, + GoalTurnAccounting { + token_delta: 0, + last_accounted_token_usage: token_usage_at_turn_start.clone(), + account_tokens: !matches!(collaboration_mode, ModeKind::Plan), + stopped: false, + }, + ); } pub(crate) fn record_token_usage( &self, turn_id: impl Into, - usage: &TokenUsage, + total_usage: &TokenUsage, ) -> Option { - let delta = goal_token_delta_for_usage(usage); - if delta <= 0 { + let turn_id = turn_id.into(); + let mut inner = self.inner(); + let turn = inner.turns.get_mut(&turn_id)?; + if turn.stopped || !turn.account_tokens { return None; } - let turn_id = turn_id.into(); - let mut inner = self.inner(); - let turn = inner.turns.entry(turn_id).or_default(); + let delta = + token_delta_since_last_accounting(&turn.last_accounted_token_usage, total_usage); + turn.last_accounted_token_usage = total_usage.clone(); + if delta <= 0 { + return None; + } turn.token_delta = turn.token_delta.saturating_add(delta); let turn_delta = turn.token_delta; inner.unflushed_token_delta = inner.unflushed_token_delta.saturating_add(delta); @@ -65,6 +86,21 @@ impl GoalAccountingState { } } +fn token_delta_since_last_accounting(last: &TokenUsage, current: &TokenUsage) -> i64 { + 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) +} + pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 { usage .input_tokens diff --git a/codex-rs/ext/goal/src/extension.rs b/codex-rs/ext/goal/src/extension.rs index 657d285f74..6d8eb42f0e 100644 --- a/codex-rs/ext/goal/src/extension.rs +++ b/codex-rs/ext/goal/src/extension.rs @@ -108,10 +108,11 @@ where return; } - // TODO: TurnStartInput should expose collaboration mode and token usage - // at turn start. Goals need mode to suppress plan-mode accounting and - // the token baseline to account deltas exactly. - accounting_state(input.thread_store).start_turn(input.turn_store.level_id()); + accounting_state(input.thread_store).start_turn( + input.turn_id, + input.collaboration_mode.mode, + input.token_usage_at_turn_start, + ); } async fn on_turn_stop(&self, input: TurnStopInput<'_>) { @@ -158,7 +159,7 @@ where } let Some(_recorded) = accounting_state(thread_store) - .record_token_usage(turn_store.level_id(), &token_usage.last_token_usage) + .record_token_usage(turn_store.level_id(), &token_usage.total_token_usage) else { return; }; diff --git a/codex-rs/ext/goal/tests/accounting.rs b/codex-rs/ext/goal/tests/accounting.rs new file mode 100644 index 0000000000..99e9c93005 --- /dev/null +++ b/codex-rs/ext/goal/tests/accounting.rs @@ -0,0 +1,68 @@ +#![allow(dead_code)] + +#[path = "../src/accounting.rs"] +mod accounting; + +use accounting::GoalAccountingState; +use codex_protocol::config_types::ModeKind; +use codex_protocol::protocol::TokenUsage; +use pretty_assertions::assert_eq; + +#[test] +fn goal_accounting_uses_turn_start_baseline_for_exact_deltas() { + let state = GoalAccountingState::default(); + state.start_turn( + "turn-1", + ModeKind::Default, + &token_usage( + /*input_tokens*/ 100, /*cached_input_tokens*/ 10, /*output_tokens*/ 30, + /*reasoning_output_tokens*/ 5, /*total_tokens*/ 135, + ), + ); + + let recorded = state + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 120, /*cached_input_tokens*/ 14, + /*output_tokens*/ 42, /*reasoning_output_tokens*/ 8, + /*total_tokens*/ 162, + ), + ) + .expect("token delta should be recorded"); + + assert_eq!(28, recorded.turn_delta); + assert_eq!(28, recorded.thread_unflushed_delta); +} + +#[test] +fn goal_accounting_ignores_plan_mode_turns() { + let state = GoalAccountingState::default(); + state.start_turn("turn-1", ModeKind::Plan, &TokenUsage::default()); + + let recorded = state.record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8, + /*reasoning_output_tokens*/ 2, /*total_tokens*/ 30, + ), + ); + + assert_eq!(None, recorded); +} + +fn token_usage( + input_tokens: i64, + cached_input_tokens: i64, + output_tokens: i64, + reasoning_output_tokens: i64, + total_tokens: i64, +) -> TokenUsage { + TokenUsage { + input_tokens, + cached_input_tokens, + output_tokens, + reasoning_output_tokens, + total_tokens, + } +} From a52c91d8b59601d1b01e8ccfffc2ae0d5dde31df Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Wed, 20 May 2026 08:09:45 -0700 Subject: [PATCH 2/6] [codex] Hide deferred tools from code mode prompt (#23605) ## Why `code_mode_only_guides_all_tools_search_and_calls_deferred_app_tools` was failing because code-mode prompt generation used the same nested tool spec list for both the model-visible `exec` guide and the runtime `ALL_TOOLS` surface. That allowed deferred MCP/app tools, such as `calendar_timezone_option_99`, to leak into the `exec` description even though they should only be discoverable through `ALL_TOOLS` at runtime. ## What changed Split code-mode nested tool planning into two sets in `core/src/tools/spec_plan.rs`: - runtime nested tool specs still include deferred tools, so `tools[...]` and `ALL_TOOLS` can call them - `exec` prompt docs only render non-deferred tools, so deferred app tools stay out of the model-visible guide ## Validation - `cargo test -p codex-core --test all code_mode_only_guides_all_tools_search_and_calls_deferred_app_tools -- --nocapture` - looped the same focused test 5 additional times with `cargo test -q -p codex-core --test all code_mode_only_guides_all_tools_search_and_calls_deferred_app_tools` --- codex-rs/core/src/tools/spec_plan.rs | 30 ++++++++++++++++++---------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs index ab9d02f97c..a47ed9da34 100644 --- a/codex-rs/core/src/tools/spec_plan.rs +++ b/codex-rs/core/src/tools/spec_plan.rs @@ -367,19 +367,27 @@ fn build_code_mode_executors( return vec![]; } - let code_mode_nested_tool_specs = executors - .iter() - .filter_map(|executor| { - if executor.exposure() == ToolExposure::DirectModelOnly { - return None; - } + let mut code_mode_nested_tool_specs = Vec::new(); + let mut exec_prompt_tool_specs = Vec::new(); + for executor in executors { + let exposure = executor.exposure(); + if exposure == ToolExposure::DirectModelOnly { + continue; + } - executor.spec() - }) - .collect::>(); - let namespace_descriptions = code_mode_namespace_descriptions(&code_mode_nested_tool_specs); + let Some(spec) = executor.spec() else { + continue; + }; + + if exposure != ToolExposure::Deferred { + exec_prompt_tool_specs.push(spec.clone()); + } + code_mode_nested_tool_specs.push(spec); + } + + let namespace_descriptions = code_mode_namespace_descriptions(&exec_prompt_tool_specs); let mut enabled_tools = - collect_code_mode_exec_prompt_tool_definitions(code_mode_nested_tool_specs.iter()); + collect_code_mode_exec_prompt_tool_definitions(exec_prompt_tool_specs.iter()); enabled_tools .sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions)); From b0b383bea3ba7830e6c9af4bbb6224d5ab1a2fe5 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 20 May 2026 08:24:43 -0700 Subject: [PATCH 3/6] runtime: use install context for bundled bwrap (#23634) ## Summary The Linux sandbox should find bundled `bwrap` through the same package-layout abstraction as the rest of the runtime, instead of maintaining a separate standalone-specific lookup path. This adds an `InstallContext` helper for bundled resources and updates `codex-linux-sandbox` to ask the current install context for `codex-resources/bwrap` before falling back to the old executable-relative probes. The tests cover npm-style, standalone, and canonical package layouts so `bwrap` lookup follows the package structure introduced earlier in the stack. ## Test plan - `cargo test -p codex-install-context` - `cargo test -p codex-linux-sandbox --lib` - `just fix -p codex-install-context -p codex-linux-sandbox` - `just bazel-lock-check` --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/23634). * #23638 * #23637 * #23636 * #23635 * __->__ #23634 --- codex-rs/Cargo.lock | 1 + codex-rs/install-context/src/lib.rs | 76 +++++++++++++++++++-- codex-rs/linux-sandbox/Cargo.toml | 1 + codex-rs/linux-sandbox/src/bundled_bwrap.rs | 56 ++++++++++++--- 4 files changed, 121 insertions(+), 13 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 6dfc44d844..7ea7dce4d4 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -3024,6 +3024,7 @@ version = "0.0.0" dependencies = [ "clap", "codex-core", + "codex-install-context", "codex-process-hardening", "codex-protocol", "codex-sandboxing", diff --git a/codex-rs/install-context/src/lib.rs b/codex-rs/install-context/src/lib.rs index d1f8d3839b..ec5c5217ca 100644 --- a/codex-rs/install-context/src/lib.rs +++ b/codex-rs/install-context/src/lib.rs @@ -124,7 +124,7 @@ impl InstallContext { && let Some(path_dir) = &package_layout.path_dir { let bundled_rg = path_dir.join(default_rg_command()); - if bundled_rg.exists() { + if bundled_rg.is_file() { return bundled_rg.into_path_buf(); } } @@ -135,13 +135,37 @@ impl InstallContext { } = &self.method { let bundled_rg = resources_dir.join(default_rg_command()); - if bundled_rg.exists() { + if bundled_rg.is_file() { return bundled_rg.into_path_buf(); } } default_rg_command() } + + pub fn bundled_resource(&self, file_name: impl AsRef) -> Option { + if let Some(package_layout) = &self.package_layout + && let Some(resources_dir) = &package_layout.resources_dir + { + let resource = resources_dir.join(file_name.as_ref()); + if resource.is_file() { + return Some(resource); + } + } + + if let InstallMethod::Standalone { + resources_dir: Some(resources_dir), + .. + } = &self.method + { + let resource = resources_dir.join(file_name); + if resource.is_file() { + return Some(resource); + } + } + + None + } } impl CodexPackageLayout { @@ -242,6 +266,8 @@ mod tests { use pretty_assertions::assert_eq; use std::fs; + const TEST_RESOURCE_NAME: &str = "codex-test-helper"; + #[test] fn detects_standalone_install_from_release_layout() -> std::io::Result<()> { let codex_home = tempfile::tempdir()?; @@ -253,6 +279,7 @@ mod tests { let exe_path = release_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" }); fs::write(&exe_path, "")?; fs::write(resources_dir.join(default_rg_command()), "")?; + fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?; let canonical_release_dir = AbsolutePathBuf::from_absolute_path(release_dir.canonicalize()?)?; let canonical_resources_dir = @@ -270,12 +297,16 @@ mod tests { InstallContext { method: InstallMethod::Standalone { release_dir: canonical_release_dir, - resources_dir: Some(canonical_resources_dir), + resources_dir: Some(canonical_resources_dir.clone()), platform: standalone_platform(), }, package_layout: None, } ); + assert_eq!( + context.bundled_resource(TEST_RESOURCE_NAME), + Some(canonical_resources_dir.join(TEST_RESOURCE_NAME)) + ); Ok(()) } @@ -312,6 +343,7 @@ mod tests { fs::write(package_dir.path().join(PACKAGE_METADATA_FILENAME), "{}")?; let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" }); fs::write(&exe_path, "")?; + fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?; fs::write(path_dir.join(default_rg_command()), "")?; let canonical_package_dir = AbsolutePathBuf::from_absolute_path(package_dir.path().canonicalize()?)?; @@ -322,7 +354,7 @@ mod tests { let package_layout = CodexPackageLayout { package_dir: canonical_package_dir, bin_dir: canonical_bin_dir, - resources_dir: Some(canonical_resources_dir), + resources_dir: Some(canonical_resources_dir.clone()), path_dir: Some(canonical_path_dir.clone()), }; @@ -346,6 +378,10 @@ mod tests { .join(default_rg_command()) .into_path_buf() ); + assert_eq!( + context.bundled_resource(TEST_RESOURCE_NAME), + Some(canonical_resources_dir.join(TEST_RESOURCE_NAME)) + ); Ok(()) } @@ -364,6 +400,7 @@ mod tests { fs::write(package_dir.join(PACKAGE_METADATA_FILENAME), "{}")?; let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" }); fs::write(&exe_path, "")?; + fs::write(resources_dir.join(TEST_RESOURCE_NAME), "")?; fs::write(path_dir.join(default_rg_command()), "")?; let canonical_package_dir = AbsolutePathBuf::from_absolute_path(package_dir.canonicalize()?)?; @@ -390,7 +427,7 @@ mod tests { package_layout: Some(CodexPackageLayout { package_dir: canonical_package_dir, bin_dir: canonical_bin_dir, - resources_dir: Some(canonical_resources_dir), + resources_dir: Some(canonical_resources_dir.clone()), path_dir: Some(canonical_path_dir.clone()), }), } @@ -401,6 +438,10 @@ mod tests { .join(default_rg_command()) .into_path_buf() ); + assert_eq!( + context.bundled_resource(TEST_RESOURCE_NAME), + Some(canonical_resources_dir.join(TEST_RESOURCE_NAME)) + ); Ok(()) } @@ -455,6 +496,31 @@ mod tests { Ok(()) } + #[test] + fn bundled_file_lookups_ignore_directories() -> std::io::Result<()> { + let package_dir = tempfile::tempdir()?; + let bin_dir = package_dir.path().join(BIN_DIRNAME); + let resources_dir = package_dir.path().join(RESOURCES_DIRNAME); + let path_dir = package_dir.path().join(PATH_DIRNAME); + fs::create_dir_all(&bin_dir)?; + fs::create_dir_all(resources_dir.join(TEST_RESOURCE_NAME))?; + fs::create_dir_all(path_dir.join(default_rg_command()))?; + fs::write(package_dir.path().join(PACKAGE_METADATA_FILENAME), "{}")?; + let exe_path = bin_dir.join(if cfg!(windows) { "codex.exe" } else { "codex" }); + fs::write(&exe_path, "")?; + + let context = InstallContext::from_exe_with_codex_home( + /*is_macos*/ false, + /*current_exe*/ Some(&exe_path), + /*managed_by_npm*/ false, + /*managed_by_bun*/ false, + /*codex_home*/ None, + ); + assert_eq!(context.rg_command(), default_rg_command()); + assert_eq!(context.bundled_resource(TEST_RESOURCE_NAME), None); + Ok(()) + } + #[test] fn npm_and_bun_take_precedence() { let npm_context = InstallContext::from_exe_with_codex_home( diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index 1ae2e6b5f5..fc7937536c 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -18,6 +18,7 @@ workspace = true [target.'cfg(target_os = "linux")'.dependencies] clap = { workspace = true, features = ["derive"] } +codex-install-context = { workspace = true } codex-process-hardening = { workspace = true } codex-protocol = { workspace = true } codex-sandboxing = { workspace = true } diff --git a/codex-rs/linux-sandbox/src/bundled_bwrap.rs b/codex-rs/linux-sandbox/src/bundled_bwrap.rs index 505377907f..972be9dac3 100644 --- a/codex-rs/linux-sandbox/src/bundled_bwrap.rs +++ b/codex-rs/linux-sandbox/src/bundled_bwrap.rs @@ -12,6 +12,7 @@ use std::sync::OnceLock; use crate::bazel_bwrap; use crate::exec_util::argv_to_cstrings; use crate::exec_util::make_files_inheritable; +use codex_install_context::InstallContext; use codex_utils_absolute_path::AbsolutePathBuf; use sha2::Digest as _; use sha2::Sha256; @@ -26,7 +27,9 @@ pub(crate) struct BundledBwrapLauncher { pub(crate) fn launcher() -> Option { let current_exe = std::env::current_exe().ok()?; - find_for_exe(¤t_exe).map(|program| BundledBwrapLauncher { program }) + find_for_install_context(InstallContext::current()) + .or_else(|| find_legacy_for_exe(¤t_exe)) + .map(|program| BundledBwrapLauncher { program }) } impl BundledBwrapLauncher { @@ -66,8 +69,14 @@ impl BundledBwrapLauncher { } } -fn find_for_exe(exe: &Path) -> Option { - candidates_for_exe(exe) +fn find_for_install_context(context: &InstallContext) -> Option { + context + .bundled_resource("bwrap") + .filter(|path| is_executable_file(path)) +} + +fn find_legacy_for_exe(exe: &Path) -> Option { + legacy_candidates_for_exe(exe) .into_iter() .find(|candidate| is_executable_file(candidate)) .map(|path| { @@ -80,7 +89,7 @@ fn find_for_exe(exe: &Path) -> Option { }) } -fn candidates_for_exe(exe: &Path) -> Vec { +fn legacy_candidates_for_exe(exe: &Path) -> Vec { let Some(exe_dir) = exe.parent() else { return Vec::new(); }; @@ -180,13 +189,44 @@ fn bytes_to_hex(bytes: &[u8; 32]) -> String { #[cfg(test)] mod tests { use super::*; + use codex_install_context::CodexPackageLayout; + use codex_install_context::InstallContext; + use codex_install_context::InstallMethod; use pretty_assertions::assert_eq; use std::fs; use tempfile::NamedTempFile; use tempfile::tempdir; #[test] - fn finds_standalone_bundled_bwrap_next_to_exe_resources() { + fn finds_package_layout_bwrap_from_install_context() { + let temp_dir = tempdir().expect("temp dir"); + let package_dir = temp_dir.path(); + let bin_dir = package_dir.join("bin"); + let resources_dir = package_dir.join("codex-resources"); + let expected_bwrap = resources_dir.join("bwrap"); + fs::create_dir_all(&bin_dir).expect("create bin dir"); + write_executable(&expected_bwrap); + + let context = InstallContext { + method: InstallMethod::Other, + package_layout: Some(CodexPackageLayout { + package_dir: AbsolutePathBuf::from_absolute_path(package_dir).expect("absolute"), + bin_dir: AbsolutePathBuf::from_absolute_path(&bin_dir).expect("absolute"), + resources_dir: Some( + AbsolutePathBuf::from_absolute_path(&resources_dir).expect("absolute"), + ), + path_dir: None, + }), + }; + + assert_eq!( + find_for_install_context(&context), + Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute")) + ); + } + + #[test] + fn finds_legacy_standalone_bundled_bwrap_next_to_exe_resources() { let temp_dir = tempdir().expect("temp dir"); let exe = temp_dir.path().join("codex"); let expected_bwrap = temp_dir.path().join("codex-resources").join("bwrap"); @@ -194,7 +234,7 @@ mod tests { write_executable(&expected_bwrap); assert_eq!( - find_for_exe(&exe), + find_legacy_for_exe(&exe), Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute")) ); } @@ -209,7 +249,7 @@ mod tests { write_executable(&expected_bwrap); assert_eq!( - find_for_exe(&exe), + find_legacy_for_exe(&exe), Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute")) ); } @@ -223,7 +263,7 @@ mod tests { write_executable(&expected_bwrap); assert_eq!( - find_for_exe(&exe), + find_legacy_for_exe(&exe), Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute")) ); } From e9f59e30d9aea0d6f6d7cb17bd1417b4ea222262 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Wed, 20 May 2026 08:48:04 -0700 Subject: [PATCH 4/6] release: publish Codex package archive checksums (#23635) ## Summary Standalone installers and other downstream package consumers need a stable checksum source for the canonical package archives. Relying on per-asset metadata makes that harder to consume uniformly, especially when several package archives are produced in the same release. This keeps the `codex-package-*.tar.gz` and `codex-app-server-package-*.tar.gz` assets in the GitHub Release upload set and adds `codex-package_SHA256SUMS` to `dist/` before the release is created. The manifest contains one SHA-256 line per package archive and fails the release job if no package archives are present. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/23635). * #23638 * #23637 * #23636 * __->__ #23635 --- .github/workflows/rust-release.yml | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/.github/workflows/rust-release.yml b/.github/workflows/rust-release.yml index c55337ecfe..93e23b8fd7 100644 --- a/.github/workflows/rust-release.yml +++ b/.github/workflows/rust-release.yml @@ -1107,15 +1107,33 @@ jobs: # If included in files: dist/**, release upload races on duplicate # asset names and can fail with 404s. find dist -type f -name 'cargo-timing.html' -delete - # Keep package-builder sidecar archives as workflow artifacts only - # until distribution channels are ready to consume them. - find dist -type f \ - \( -name 'codex-package-*' -o -name 'codex-app-server-package-*' \) \ - -delete find dist -type d -empty -delete ls -R dist/ + - name: Add Codex package checksum manifest + run: | + set -euo pipefail + + manifest="dist/codex-package_SHA256SUMS" + tmp_manifest="$(mktemp)" + find dist -type f \ + \( -name 'codex-package-*.tar.gz' -o -name 'codex-app-server-package-*.tar.gz' \) \ + -print | + sort | + while IFS= read -r archive; do + sha256sum "$archive" | + awk -v name="$(basename "$archive")" '{ print $1 " " name }' + done > "$tmp_manifest" + + if [[ ! -s "$tmp_manifest" ]]; then + echo "No Codex package archives found for checksum manifest" + exit 1 + fi + + mv "$tmp_manifest" "$manifest" + cat "$manifest" + - name: Add config schema release asset run: | cp codex-rs/core/config.schema.json dist/config-schema.json From f198ca115b74a7c8deccddd106393ce0c167da4e Mon Sep 17 00:00:00 2001 From: anp-oai Date: Wed, 20 May 2026 08:49:35 -0700 Subject: [PATCH 5/6] feat: Add btw alias for side slash command (#23592) --- codex-rs/tui/src/bottom_pane/chat_composer.rs | 108 +++++++++++++++++ codex-rs/tui/src/bottom_pane/command_popup.rs | 17 ++- ..._chat_composer__tests__slash_popup_bt.snap | 9 ++ ..._chat_composer__tests__slash_popup_si.snap | 9 ++ codex-rs/tui/src/chatwidget/slash_dispatch.rs | 30 +++-- codex-rs/tui/src/chatwidget/tests/side.rs | 113 ++++++++++++++++++ codex-rs/tui/src/slash_command.rs | 9 +- 7 files changed, 279 insertions(+), 16 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_bt.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_si.snap diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 2176e7762e..ef870c6776 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -7699,6 +7699,114 @@ mod tests { } } + #[test] + fn slash_popup_btw_for_bt_ui() { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + type_chars_humanlike(&mut composer, &['/', 'b', 't']); + + let mut terminal = Terminal::new(TestBackend::new(60, 5)).expect("terminal"); + terminal + .draw(|f| composer.render(f.area(), f.buffer_mut())) + .expect("draw composer"); + + insta::assert_snapshot!("slash_popup_bt", terminal.backend()); + } + + #[test] + fn slash_popup_btw_for_bt_logic() { + use super::super::command_popup::CommandItem; + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + type_chars_humanlike(&mut composer, &['/', 'b', 't']); + + match &composer.popups.active { + ActivePopup::Command(popup) => match popup.selected_item() { + Some(CommandItem::Builtin(cmd)) => { + assert_eq!(cmd.command(), "btw") + } + Some(CommandItem::ServiceTier(command)) => { + panic!("expected btw command, got service tier {command:?}") + } + None => panic!("no selected command for '/bt'"), + }, + _ => panic!("slash popup not active after typing '/bt'"), + } + } + + #[test] + fn slash_popup_side_for_si_ui() { + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + + type_chars_humanlike(&mut composer, &['/', 's', 'i']); + + let mut terminal = Terminal::new(TestBackend::new(60, 5)).expect("terminal"); + terminal + .draw(|f| composer.render(f.area(), f.buffer_mut())) + .expect("draw composer"); + + insta::assert_snapshot!("slash_popup_si", terminal.backend()); + } + + #[test] + fn slash_popup_side_for_si_logic() { + use super::super::command_popup::CommandItem; + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + /*has_input_focus*/ true, + sender, + /*enhanced_keys_supported*/ false, + "Ask Codex to do anything".to_string(), + /*disable_paste_burst*/ false, + ); + type_chars_humanlike(&mut composer, &['/', 's', 'i']); + + match &composer.popups.active { + ActivePopup::Command(popup) => match popup.selected_item() { + Some(CommandItem::Builtin(cmd)) => { + assert_eq!(cmd.command(), "side") + } + Some(CommandItem::ServiceTier(command)) => { + panic!("expected side command, got service tier {command:?}") + } + None => panic!("no selected command for '/si'"), + }, + _ => panic!("slash popup not active after typing '/si'"), + } + } + #[test] fn service_tier_slash_command_dispatches_from_catalog_name() { let (tx, _rx) = unbounded_channel::(); diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index 080f320f5e..f6e6b4929c 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -18,8 +18,9 @@ use crate::render::RectExt; use crate::slash_command::SlashCommand; // Hide alias commands in the default popup list so each unique action appears once. -// `quit` is an alias of `exit`, so we skip `quit` here. -const ALIAS_COMMANDS: &[SlashCommand] = &[SlashCommand::Quit]; +// `quit` is an alias of `exit`, and `btw` is an alias of `side`, so we skip +// those aliases here. +const ALIAS_COMMANDS: &[SlashCommand] = &[SlashCommand::Quit, SlashCommand::Btw]; const COMMAND_COLUMN_WIDTH: ColumnWidthConfig = ColumnWidthConfig::new( ColumnWidthMode::AutoAllRows, /*name_column_width*/ None, @@ -418,6 +419,18 @@ mod tests { assert!(items.contains(&CommandItem::Builtin(SlashCommand::Quit))); } + #[test] + fn btw_hidden_in_empty_filter_but_shown_for_prefix() { + let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new()); + popup.on_composer_text_change("/".to_string()); + let items = popup.filtered_items(); + assert!(!items.contains(&CommandItem::Builtin(SlashCommand::Btw))); + + popup.on_composer_text_change("/bt".to_string()); + let items = popup.filtered_items(); + assert!(items.contains(&CommandItem::Builtin(SlashCommand::Btw))); + } + #[test] fn plan_command_hidden_when_collaboration_modes_disabled() { let mut popup = CommandPopup::new(CommandPopupFlags::default(), Vec::new()); diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_bt.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_bt.snap new file mode 100644 index 0000000000..5aee8ff4d8 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_bt.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› /bt " +" " +" " +" /btw start a side conversation in an ephemeral fork " diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_si.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_si.snap new file mode 100644 index 0000000000..50a89ae1ab --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_si.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/chat_composer.rs +expression: terminal.backend() +--- +" " +"› /si " +" " +" " +" /side start a side conversation in an ephemeral fork " diff --git a/codex-rs/tui/src/chatwidget/slash_dispatch.rs b/codex-rs/tui/src/chatwidget/slash_dispatch.rs index 9d8d49a77c..dcf0486822 100644 --- a/codex-rs/tui/src/chatwidget/slash_dispatch.rs +++ b/codex-rs/tui/src/chatwidget/slash_dispatch.rs @@ -30,8 +30,6 @@ struct PreparedSlashCommandArgs { } const SIDE_STARTING_CONTEXT_LABEL: &str = "Side starting..."; -const SIDE_REVIEW_UNAVAILABLE_MESSAGE: &str = - "'/side' is unavailable while code review is running."; const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str = "Press Ctrl+C to return to the main thread first."; const GOAL_USAGE: &str = "Usage: /goal "; @@ -114,9 +112,12 @@ impl ChatWidget { }); } - fn request_empty_side_conversation(&mut self) { + fn request_empty_side_conversation(&mut self, cmd: SlashCommand) { let Some(parent_thread_id) = self.thread_id else { - self.add_error_message("'/side' is unavailable before the session starts.".to_string()); + let command = cmd.command(); + self.add_error_message(format!( + "'/{command}' is unavailable before the session starts." + )); return; }; @@ -239,8 +240,8 @@ impl ChatWidget { ); } } - SlashCommand::Side => { - self.request_empty_side_conversation(); + SlashCommand::Side | SlashCommand::Btw => { + self.request_empty_side_conversation(cmd); } SlashCommand::Agent | SlashCommand::MultiAgents => { self.app_event_tx.send(AppEvent::OpenAgentPicker); @@ -745,11 +746,12 @@ impl ChatWidget { self.bottom_pane.drain_pending_submission_state(); } } - SlashCommand::Side if !trimmed.is_empty() => { + SlashCommand::Side | SlashCommand::Btw if !trimmed.is_empty() => { let Some(parent_thread_id) = self.thread_id else { - self.add_error_message( - "'/side' is unavailable before the session starts.".to_string(), - ); + let command = cmd.command(); + self.add_error_message(format!( + "'/{command}' is unavailable before the session starts." + )); return; }; let user_message = self.prepared_inline_user_message( @@ -957,6 +959,7 @@ impl ChatWidget { | SlashCommand::Plan | SlashCommand::Goal | SlashCommand::Side + | SlashCommand::Btw | SlashCommand::Keymap | SlashCommand::Agent | SlashCommand::MultiAgents @@ -1017,11 +1020,14 @@ impl ChatWidget { } fn ensure_side_command_allowed_outside_review(&mut self, cmd: SlashCommand) -> bool { - if cmd != SlashCommand::Side || !self.review.is_review_mode { + if !matches!(cmd, SlashCommand::Side | SlashCommand::Btw) || !self.review.is_review_mode { return true; } - self.add_error_message(SIDE_REVIEW_UNAVAILABLE_MESSAGE.to_string()); + let command = cmd.command(); + self.add_error_message(format!( + "'/{command}' is unavailable while code review is running." + )); self.bottom_pane.drain_pending_submission_state(); false } diff --git a/codex-rs/tui/src/chatwidget/tests/side.rs b/codex-rs/tui/src/chatwidget/tests/side.rs index 906deb3b56..39a0cb9d73 100644 --- a/codex-rs/tui/src/chatwidget/tests/side.rs +++ b/codex-rs/tui/src/chatwidget/tests/side.rs @@ -173,6 +173,59 @@ async fn slash_side_is_rejected_during_review_mode() { ); } +#[tokio::test] +async fn slash_btw_is_rejected_during_review_mode() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.review.is_review_mode = true; + + chat.dispatch_command(SlashCommand::Btw); + + let event = rx + .try_recv() + .expect("expected review-mode btw conversation error"); + match event { + AppEvent::InsertHistoryCell(cell) => { + let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80)); + assert!( + rendered.contains("'/btw' is unavailable while code review is running."), + "expected review-mode btw conversation error, got {rendered:?}" + ); + } + other => panic!("expected InsertHistoryCell error, got {other:?}"), + } + assert!(rx.try_recv().is_err(), "expected no follow-up events"); + assert!( + op_rx.try_recv().is_err(), + "expected no side conversation op" + ); +} + +#[tokio::test] +async fn slash_btw_is_rejected_before_the_session_starts() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + + chat.dispatch_command(SlashCommand::Btw); + + let event = rx + .try_recv() + .expect("expected pre-session btw conversation error"); + match event { + AppEvent::InsertHistoryCell(cell) => { + let rendered = lines_to_single_string(&cell.display_lines(/*width*/ 80)); + assert!( + rendered.contains("'/btw' is unavailable before the session starts."), + "expected pre-session btw conversation error, got {rendered:?}" + ); + } + other => panic!("expected InsertHistoryCell error, got {other:?}"), + } + assert!(rx.try_recv().is_err(), "expected no follow-up events"); + assert!( + op_rx.try_recv().is_err(), + "expected no side conversation op" + ); +} + #[tokio::test] async fn submit_user_message_as_plain_user_turn_does_not_run_shell_commands() { let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -219,6 +272,31 @@ async fn slash_side_without_args_starts_empty_side_conversation() { assert!(chat.input_queue.queued_user_messages.is_empty()); } +#[tokio::test] +async fn slash_btw_without_args_starts_empty_side_conversation() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let parent_thread_id = ThreadId::new(); + chat.thread_id = Some(parent_thread_id); + chat.on_task_started(); + chat.bottom_pane + .set_composer_text("/btw".to_string(), Vec::new(), Vec::new()); + + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::StartSide { + parent_thread_id: emitted_parent_thread_id, + user_message: None, + }) if emitted_parent_thread_id == parent_thread_id + ); + assert!( + op_rx.try_recv().is_err(), + "bare /btw should not submit an op on the parent thread" + ); + assert!(chat.input_queue.queued_user_messages.is_empty()); +} + #[tokio::test] async fn slash_side_requests_forked_side_question_while_task_running() { let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; @@ -268,6 +346,41 @@ async fn slash_side_requests_forked_side_question_while_task_running() { ); } +#[tokio::test] +async fn slash_btw_requests_forked_side_question_while_task_running() { + let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + let parent_thread_id = ThreadId::new(); + chat.thread_id = Some(parent_thread_id); + chat.on_task_started(); + chat.bottom_pane.set_composer_text( + "/btw explore the codebase".to_string(), + Vec::new(), + Vec::new(), + ); + + chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); + + assert_matches!( + rx.try_recv(), + Ok(AppEvent::StartSide { + parent_thread_id: emitted_parent_thread_id, + user_message: Some(user_message), + }) if emitted_parent_thread_id == parent_thread_id + && user_message + == UserMessage { + text: "explore the codebase".to_string(), + local_images: Vec::new(), + remote_image_urls: Vec::new(), + text_elements: Vec::new(), + mention_bindings: Vec::new(), + } + ); + assert!( + op_rx.try_recv().is_err(), + "expected no op on the parent thread" + ); +} + #[tokio::test] async fn side_context_label_preserves_status_line_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 970d1cbd5a..4a43409296 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -38,6 +38,7 @@ pub enum SlashCommand { Goal, Agent, Side, + Btw, Copy, Raw, Diff, @@ -114,7 +115,9 @@ impl SlashCommand { SlashCommand::Plan => "switch to Plan mode", SlashCommand::Goal => "set or view the goal for a long-running task", SlashCommand::Agent | SlashCommand::MultiAgents => "switch the active agent thread", - SlashCommand::Side => "start a side conversation in an ephemeral fork", + SlashCommand::Side | SlashCommand::Btw => { + "start a side conversation in an ephemeral fork" + } SlashCommand::Permissions => "choose what Codex is allowed to do", SlashCommand::Keymap => "remap TUI shortcuts", SlashCommand::Vim => "toggle Vim mode for the composer", @@ -154,6 +157,7 @@ impl SlashCommand { | SlashCommand::Raw | SlashCommand::Pets | SlashCommand::Side + | SlashCommand::Btw | SlashCommand::Resume | SlashCommand::SandboxReadRoot ) @@ -217,7 +221,8 @@ impl SlashCommand { | SlashCommand::Ide | SlashCommand::Quit | SlashCommand::Exit - | SlashCommand::Side => true, + | SlashCommand::Side + | SlashCommand::Btw => true, SlashCommand::Rollout => true, SlashCommand::TestApproval => true, SlashCommand::Realtime => true, From d4f842f3b38595ea348d2a9bc7ed386b74e71a1c Mon Sep 17 00:00:00 2001 From: jif-oai Date: Wed, 20 May 2026 18:36:37 +0200 Subject: [PATCH 6/6] feat: account active goal progress in the goal extension (#23696) ## Why The goal extension can create and surface goals, but the live turn-accounting path still stopped short of persisting active-goal progress. That leaves token and wall-clock usage, plus `ThreadGoalUpdated` events, out of sync with the extension boundary once work actually advances or a goal transitions out of active state. ## What changed - Teach `GoalAccountingState` to track the current turn, active goal, token deltas, and wall-clock progress snapshots against the persisted goal id. - Flush active-goal accounting from tool-finish, turn-stop, and turn-abort lifecycle hooks, and emit `ThreadGoalUpdated` events when persisted progress changes. - Route `create_goal` and `update_goal` through the same accounting state so new goals start from the right baseline, final progress is flushed before status changes, and `update_goal` can mark a goal `blocked` as well as `complete`. - Keep budget-limited goals accruing through the end of the turn while clearing local active-goal state once a turn or explicit update is finished. - Expand backend and lifecycle coverage around store ids, baseline reset, tool-finish accounting, budget-limited carry-through, and blocked-goal updates. ## Testing - Added focused backend coverage in `codex-rs/ext/goal/tests/goal_extension_backend.rs` for baseline reset, tool-finish accounting, budget-limited turns, and blocked-goal updates. - Extended `codex-rs/core/src/session/tests.rs` to assert that lifecycle inputs expose the expected session, thread, and turn store ids. --- codex-rs/core/src/session/tests.rs | 71 ++- codex-rs/ext/goal/src/accounting.rs | 260 +++++++++- codex-rs/ext/goal/src/extension.rs | 139 ++++- codex-rs/ext/goal/src/spec.rs | 7 +- codex-rs/ext/goal/src/tool.rs | 128 ++++- .../ext/goal/tests/goal_extension_backend.rs | 484 +++++++++++++++++- 6 files changed, 978 insertions(+), 111 deletions(-) diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 5318b72151..a08243701c 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -1918,6 +1918,9 @@ async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { #[derive(Debug, PartialEq, Eq)] struct RecordedTurnStart { + session_level_id: String, + thread_level_id: String, + turn_level_id: String, turn_id: String, collaboration_mode: CollaborationMode, token_usage_at_turn_start: TokenUsage, @@ -1936,6 +1939,9 @@ async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { .lock() .expect("turn start records lock") .push(RecordedTurnStart { + session_level_id: input.session_store.level_id().to_string(), + thread_level_id: input.thread_store.level_id().to_string(), + turn_level_id: input.turn_store.level_id().to_string(), turn_id: input.turn_id.to_string(), collaboration_mode: input.collaboration_mode.clone(), token_usage_at_turn_start: input.token_usage_at_turn_start.clone(), @@ -1965,52 +1971,43 @@ async fn turn_start_lifecycle_exposes_turn_metadata_and_token_baseline() { .insert(ThreadTurnStartMarker); let token_usage_at_turn_start = TokenUsage { - input_tokens: 120, - cached_input_tokens: 15, - output_tokens: 40, - reasoning_output_tokens: 9, - total_tokens: 169, + input_tokens: 100, + cached_input_tokens: 40, + output_tokens: 25, + reasoning_output_tokens: 5, + total_tokens: 130, }; - session - .state - .lock() - .await - .set_token_info(Some(TokenUsageInfo { - total_token_usage: token_usage_at_turn_start.clone(), - last_token_usage: TokenUsage::default(), - model_context_window: turn_context.model_context_window(), - })); + set_total_token_usage(&session, token_usage_at_turn_start.clone()).await; - let turn_context = Arc::new(turn_context); - let session = Arc::new(session); - session - .spawn_task( - Arc::clone(&turn_context), - Vec::new(), - NeverEndingTask { - kind: TaskKind::Regular, - listen_to_cancellation_token: true, - }, - ) - .await; + let expected = RecordedTurnStart { + session_level_id: session.session_id().to_string(), + thread_level_id: session.conversation_id.to_string(), + turn_level_id: turn_context.sub_id.clone(), + turn_id: turn_context.sub_id.clone(), + collaboration_mode: turn_context.collaboration_mode.clone(), + token_usage_at_turn_start, + saw_session_store: true, + saw_thread_store: true, + }; - session.abort_all_tasks(TurnAbortReason::Interrupted).await; + let sess = Arc::new(session); + sess.spawn_task( + Arc::new(turn_context), + Vec::new(), + NeverEndingTask { + kind: TaskKind::Regular, + listen_to_cancellation_token: true, + }, + ) + .await; + sess.abort_all_tasks(TurnAbortReason::Interrupted).await; let actual = records .lock() .expect("turn start records lock") .drain(..) .collect::>(); - assert_eq!( - vec![RecordedTurnStart { - turn_id: turn_context.sub_id.clone(), - collaboration_mode: turn_context.collaboration_mode.clone(), - token_usage_at_turn_start, - saw_session_store: true, - saw_thread_store: true, - }], - actual - ); + assert_eq!(vec![expected], actual); } #[tokio::test] diff --git a/codex-rs/ext/goal/src/accounting.rs b/codex-rs/ext/goal/src/accounting.rs index cc04684169..b4fa14669d 100644 --- a/codex-rs/ext/goal/src/accounting.rs +++ b/codex-rs/ext/goal/src/accounting.rs @@ -1,26 +1,50 @@ use codex_protocol::config_types::ModeKind; use codex_protocol::protocol::TokenUsage; +use codex_state::ThreadGoalStatus; use std::collections::HashMap; use std::sync::Mutex; use std::sync::PoisonError; +use std::time::Duration; +use std::time::Instant; #[derive(Debug, Default)] pub(crate) struct GoalAccountingState { inner: Mutex, } -#[derive(Debug, Default)] +#[derive(Debug)] struct GoalAccountingInner { + current_turn_id: Option, turns: HashMap, - unflushed_token_delta: i64, + wall_clock: GoalWallClockAccounting, } -#[derive(Debug, Default)] +#[derive(Debug)] struct GoalTurnAccounting { - token_delta: i64, + current_token_usage: TokenUsage, last_accounted_token_usage: TokenUsage, + active_goal_id: Option, account_tokens: bool, - stopped: bool, +} + +#[derive(Debug)] +struct GoalWallClockAccounting { + last_accounted_at: Instant, + active_goal_id: Option, +} + +#[derive(Debug, Clone)] +pub(crate) struct GoalProgressSnapshot { + pub(crate) current_token_usage: TokenUsage, + pub(crate) expected_goal_id: String, + pub(crate) time_delta_seconds: i64, + pub(crate) token_delta: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum BudgetLimitedGoalDisposition { + KeepActive, + ClearActive, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -37,17 +61,21 @@ impl GoalAccountingState { token_usage_at_turn_start: &TokenUsage, ) { let turn_id = turn_id.into(); - self.inner().turns.insert( + let mut inner = self.inner(); + inner.current_turn_id = Some(turn_id.clone()); + inner.turns.insert( turn_id, - GoalTurnAccounting { - token_delta: 0, - last_accounted_token_usage: token_usage_at_turn_start.clone(), - account_tokens: !matches!(collaboration_mode, ModeKind::Plan), - stopped: false, - }, + GoalTurnAccounting::new( + token_usage_at_turn_start.clone(), + !matches!(collaboration_mode, ModeKind::Plan), + ), ); } + pub(crate) fn current_turn_id(&self) -> Option { + self.inner().current_turn_id.clone() + } + pub(crate) fn record_token_usage( &self, turn_id: impl Into, @@ -56,28 +84,107 @@ impl GoalAccountingState { let turn_id = turn_id.into(); let mut inner = self.inner(); let turn = inner.turns.get_mut(&turn_id)?; - if turn.stopped || !turn.account_tokens { + turn.current_token_usage = total_usage.clone(); + if !turn.account_tokens { return None; } - let delta = - token_delta_since_last_accounting(&turn.last_accounted_token_usage, total_usage); - turn.last_accounted_token_usage = total_usage.clone(); + let delta = turn.token_delta_since_last_accounting(); if delta <= 0 { return None; } - turn.token_delta = turn.token_delta.saturating_add(delta); - let turn_delta = turn.token_delta; - inner.unflushed_token_delta = inner.unflushed_token_delta.saturating_add(delta); Some(RecordedTokenDelta { - turn_delta, - thread_unflushed_delta: inner.unflushed_token_delta, + turn_delta: delta, + thread_unflushed_delta: inner.thread_unflushed_token_delta(), }) } - pub(crate) fn stop_turn(&self, turn_id: &str) { - if let Some(turn) = self.inner().turns.get_mut(turn_id) { - turn.stopped = true; + pub(crate) fn mark_turn_goal_active(&self, turn_id: &str, goal_id: impl Into) { + let mut inner = self.inner(); + let goal_id = goal_id.into(); + if let Some(turn) = inner.turns.get_mut(turn_id) { + turn.active_goal_id = Some(goal_id.clone()); + if inner.current_turn_id.as_deref() == Some(turn_id) { + inner.wall_clock.mark_active_goal(goal_id); + } + } + } + + pub(crate) fn mark_current_turn_goal_active( + &self, + goal_id: impl Into, + ) -> Option { + let mut inner = self.inner(); + let turn_id = inner.current_turn_id.clone()?; + let goal_id = goal_id.into(); + let turn = inner.turns.get_mut(turn_id.as_str())?; + turn.active_goal_id = Some(goal_id.clone()); + turn.reset_baseline_to_current(); + inner.wall_clock.mark_active_goal(goal_id); + Some(turn_id) + } + + pub(crate) fn clear_current_turn_goal(&self) -> Option { + let mut inner = self.inner(); + let turn_id = inner.current_turn_id.clone()?; + if let Some(turn) = inner.turns.get_mut(turn_id.as_str()) { + turn.active_goal_id = None; + } + inner.wall_clock.clear_active_goal(); + Some(turn_id) + } + + pub(crate) fn progress_snapshot(&self, turn_id: &str) -> Option { + let inner = self.inner(); + let turn = inner.turns.get(turn_id)?; + if !turn.account_tokens { + return None; + } + let expected_goal_id = turn.active_goal_id()?; + let token_delta = turn.token_delta_since_last_accounting(); + let time_delta_seconds = + if inner.wall_clock.active_goal_id.as_deref() == Some(expected_goal_id.as_str()) { + inner.wall_clock.time_delta_since_last_accounting() + } else { + 0 + }; + if time_delta_seconds == 0 && token_delta <= 0 { + return None; + } + Some(GoalProgressSnapshot { + current_token_usage: turn.current_token_usage.clone(), + expected_goal_id, + time_delta_seconds, + token_delta, + }) + } + + pub(crate) fn mark_progress_accounted_for_status( + &self, + turn_id: &str, + snapshot: &GoalProgressSnapshot, + status: ThreadGoalStatus, + budget_limited_goal_disposition: BudgetLimitedGoalDisposition, + ) { + let clear_active_goal = should_clear_active_goal(status, budget_limited_goal_disposition); + let mut inner = self.inner(); + if let Some(turn) = inner.turns.get_mut(turn_id) { + turn.last_accounted_token_usage = snapshot.current_token_usage.clone(); + if clear_active_goal { + turn.active_goal_id = None; + } + } + inner.wall_clock.mark_accounted(snapshot.time_delta_seconds); + if clear_active_goal { + inner.wall_clock.clear_active_goal(); + } + } + + pub(crate) fn finish_turn(&self, turn_id: &str) { + let mut inner = self.inner(); + inner.turns.remove(turn_id); + if inner.current_turn_id.as_deref() == Some(turn_id) { + inner.current_turn_id = None; } } @@ -107,3 +214,108 @@ pub(crate) fn goal_token_delta_for_usage(usage: &TokenUsage) -> i64 { .saturating_sub(usage.cached_input_tokens) .saturating_add(usage.output_tokens.max(0)) } + +impl Default for GoalAccountingInner { + fn default() -> Self { + Self { + current_turn_id: None, + turns: HashMap::new(), + wall_clock: GoalWallClockAccounting::new(), + } + } +} + +impl GoalAccountingInner { + fn thread_unflushed_token_delta(&self) -> i64 { + self.turns + .values() + .filter(|turn| turn.account_tokens) + .fold(0_i64, |total, turn| { + total.saturating_add(turn.token_delta_since_last_accounting().max(0)) + }) + } +} + +impl GoalTurnAccounting { + fn new(current_token_usage: TokenUsage, account_tokens: bool) -> Self { + Self { + last_accounted_token_usage: current_token_usage.clone(), + current_token_usage, + active_goal_id: None, + account_tokens, + } + } + + fn active_goal_id(&self) -> Option { + self.active_goal_id.clone() + } + + fn reset_baseline_to_current(&mut self) { + self.last_accounted_token_usage = self.current_token_usage.clone(); + } + + fn token_delta_since_last_accounting(&self) -> i64 { + token_delta_since_last_accounting( + &self.last_accounted_token_usage, + &self.current_token_usage, + ) + } +} + +impl GoalWallClockAccounting { + fn new() -> Self { + Self { + last_accounted_at: Instant::now(), + active_goal_id: None, + } + } + + fn time_delta_since_last_accounting(&self) -> i64 { + i64::try_from(self.last_accounted_at.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) { + 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 should_clear_active_goal( + status: ThreadGoalStatus, + budget_limited_goal_disposition: BudgetLimitedGoalDisposition, +) -> bool { + match status { + ThreadGoalStatus::Active => false, + ThreadGoalStatus::BudgetLimited => matches!( + budget_limited_goal_disposition, + BudgetLimitedGoalDisposition::ClearActive + ), + ThreadGoalStatus::Paused + | ThreadGoalStatus::Blocked + | ThreadGoalStatus::UsageLimited + | ThreadGoalStatus::Complete => true, + } +} diff --git a/codex-rs/ext/goal/src/extension.rs b/codex-rs/ext/goal/src/extension.rs index 6d8eb42f0e..61114bf57e 100644 --- a/codex-rs/ext/goal/src/extension.rs +++ b/codex-rs/ext/goal/src/extension.rs @@ -18,13 +18,15 @@ use codex_extension_api::TurnLifecycleContributor; use codex_extension_api::TurnStartInput; use codex_extension_api::TurnStopInput; use codex_protocol::ThreadId; +use codex_protocol::protocol::ThreadGoal; use codex_protocol::protocol::TokenUsageInfo; -use codex_protocol::protocol::TurnAbortReason; +use crate::accounting::BudgetLimitedGoalDisposition; use crate::accounting::GoalAccountingState; use crate::events::GoalEventEmitter; use crate::spec::UPDATE_GOAL_TOOL_NAME; use crate::tool::GoalToolExecutor; +use crate::tool::protocol_goal_from_state; #[derive(Clone, Debug)] pub struct GoalExtensionConfig { @@ -108,11 +110,39 @@ where return; } - accounting_state(input.thread_store).start_turn( + let accounting = accounting_state(input.thread_store); + accounting.start_turn( input.turn_id, input.collaboration_mode.mode, input.token_usage_at_turn_start, ); + if matches!( + input.collaboration_mode.mode, + codex_protocol::config_types::ModeKind::Plan + ) { + accounting.clear_current_turn_goal(); + return; + } + let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else { + return; + }; + let Ok(goal) = self + .state_dbs + .thread_goals() + .get_thread_goal(thread_id) + .await + else { + return; + }; + if let Some(goal) = goal + && matches!( + goal.status, + codex_state::ThreadGoalStatus::Active + | codex_state::ThreadGoalStatus::BudgetLimited + ) + { + accounting.mark_turn_goal_active(input.turn_id, goal.goal_id); + } } async fn on_turn_stop(&self, input: TurnStopInput<'_>) { @@ -120,13 +150,16 @@ where return; } - // TODO: this should flush wall-clock and any unflushed token usage to - // persisted goal storage, emit ThreadGoalUpdated, and optionally inject - // budget-limit steering through a host event/input capability. - // TODO: the host also needs an idle/next-turn wake capability so an - // active goal can enqueue continuation context after the turn is fully - // cleared, only when there is no pending user or mailbox work. - accounting_state(input.thread_store).stop_turn(input.turn_store.level_id()); + let turn_id = input.turn_store.level_id(); + self.account_active_goal_progress( + input.thread_store, + turn_id, + &format!("{turn_id}:turn-stop"), + codex_state::GoalAccountingMode::ActiveOnly, + BudgetLimitedGoalDisposition::ClearActive, + ) + .await; + accounting_state(input.thread_store).finish_turn(turn_id); } async fn on_turn_abort(&self, input: TurnAbortInput<'_>) { @@ -134,11 +167,16 @@ where return; } - accounting_state(input.thread_store).stop_turn(input.turn_store.level_id()); - if input.reason == TurnAbortReason::Interrupted { - // TODO: interrupted turns should pause the active goal via persisted - // goal storage and emit ThreadGoalUpdated with turn_id None. - } + let turn_id = input.turn_store.level_id(); + self.account_active_goal_progress( + input.thread_store, + turn_id, + &format!("{turn_id}:turn-abort"), + codex_state::GoalAccountingMode::ActiveOnly, + BudgetLimitedGoalDisposition::ClearActive, + ) + .await; + accounting_state(input.thread_store).finish_turn(turn_id); } } @@ -163,11 +201,6 @@ where else { return; }; - - // TODO: TokenUsageContributor needs a host goal storage capability so - // this recorded delta can be committed to the active persisted goal. - // It also needs an event/input capability to emit ThreadGoalUpdated and - // inject budget-limit steering when accounting changes goal status. } } @@ -177,15 +210,21 @@ where { fn on_tool_finish<'a>(&'a self, input: ToolFinishInput<'a>) -> ToolLifecycleFuture<'a> { Box::pin(async move { - let _should_count_for_goal_progress = goal_enabled(input.thread_store) + let should_count_for_goal_progress = goal_enabled(input.thread_store) && tool_attempt_counts_for_goal_progress(input.outcome) && !(input.tool_name.namespace.is_none() && input.tool_name.name == UPDATE_GOAL_TOOL_NAME); - - // TODO: commit active goal progress through host goal storage and emit - // ThreadGoalUpdated when the persisted goal changes. This replaces - // GoalRuntimeEvent::ToolCompleted once the goal extension owns runtime - // accounting. + if !should_count_for_goal_progress { + return; + } + self.account_active_goal_progress( + input.thread_store, + input.turn_id, + input.call_id, + codex_state::GoalAccountingMode::ActiveOnly, + BudgetLimitedGoalDisposition::KeepActive, + ) + .await; }) } } @@ -216,16 +255,19 @@ where Arc::new(GoalToolExecutor::get( thread_id, Arc::clone(&self.state_dbs), + accounting_state(thread_store), self.event_emitter.clone(), )), Arc::new(GoalToolExecutor::create( thread_id, Arc::clone(&self.state_dbs), + accounting_state(thread_store), self.event_emitter.clone(), )), Arc::new(GoalToolExecutor::update( thread_id, Arc::clone(&self.state_dbs), + accounting_state(thread_store), self.event_emitter.clone(), )), ] @@ -275,3 +317,50 @@ fn tool_attempt_counts_for_goal_progress(outcome: ToolCallOutcome) -> bool { | ToolCallOutcome::Aborted => false, } } + +impl GoalExtension { + async fn account_active_goal_progress( + &self, + thread_store: &ExtensionData, + turn_id: &str, + event_id: &str, + mode: codex_state::GoalAccountingMode, + budget_limited_goal_disposition: BudgetLimitedGoalDisposition, + ) -> Option { + let Ok(thread_id) = ThreadId::from_string(thread_store.level_id()) else { + return None; + }; + let accounting = accounting_state(thread_store); + let snapshot = accounting.progress_snapshot(turn_id)?; + let outcome = self + .state_dbs + .thread_goals() + .account_thread_goal_usage( + thread_id, + snapshot.time_delta_seconds, + snapshot.token_delta, + mode, + Some(snapshot.expected_goal_id.as_str()), + ) + .await + .ok()?; + match outcome { + codex_state::GoalAccountingOutcome::Updated(goal) => { + accounting.mark_progress_accounted_for_status( + turn_id, + &snapshot, + goal.status, + budget_limited_goal_disposition, + ); + let goal = protocol_goal_from_state(goal); + self.event_emitter.thread_goal_updated( + event_id.to_string(), + Some(turn_id.to_string()), + goal.clone(), + ); + Some(goal) + } + codex_state::GoalAccountingOutcome::Unchanged(_) => None, + } + } +} diff --git a/codex-rs/ext/goal/src/spec.rs b/codex-rs/ext/goal/src/spec.rs index e127846ab5..70e89e4fbb 100644 --- a/codex-rs/ext/goal/src/spec.rs +++ b/codex-rs/ext/goal/src/spec.rs @@ -60,9 +60,9 @@ pub fn create_update_goal_tool() -> ToolSpec { let properties = BTreeMap::from([( "status".to_string(), JsonSchema::string_enum( - vec![json!("complete")], + vec![json!("complete"), json!("blocked")], Some( - "Required. Set to complete only when the objective is achieved and no required work remains." + "Required. Set to complete only when the objective is achieved and no required work remains. Set to blocked only when the goal cannot currently proceed without a user decision, missing dependency, or external unblock." .to_string(), ), ), @@ -71,8 +71,9 @@ pub fn create_update_goal_tool() -> ToolSpec { 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. +Use this tool only to mark the goal achieved or 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 goal cannot currently proceed until something external changes. 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, or budget-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."# diff --git a/codex-rs/ext/goal/src/tool.rs b/codex-rs/ext/goal/src/tool.rs index 96b160f938..fa3b7d5089 100644 --- a/codex-rs/ext/goal/src/tool.rs +++ b/codex-rs/ext/goal/src/tool.rs @@ -15,6 +15,8 @@ use codex_protocol::protocol::validate_thread_goal_objective; use serde::Deserialize; use serde::Serialize; +use crate::accounting::BudgetLimitedGoalDisposition; +use crate::accounting::GoalAccountingState; use crate::events::GoalEventEmitter; use crate::spec::CREATE_GOAL_TOOL_NAME; use crate::spec::GET_GOAL_TOOL_NAME; @@ -28,6 +30,7 @@ pub(crate) struct GoalToolExecutor { kind: GoalToolKind, thread_id: ThreadId, state_db: Arc, + accounting_state: Arc, event_emitter: GoalEventEmitter, } @@ -69,12 +72,14 @@ impl GoalToolExecutor { pub(crate) fn get( thread_id: ThreadId, state_db: Arc, + accounting_state: Arc, event_emitter: GoalEventEmitter, ) -> Self { Self { kind: GoalToolKind::Get, thread_id, state_db, + accounting_state, event_emitter, } } @@ -82,12 +87,14 @@ impl GoalToolExecutor { pub(crate) fn create( thread_id: ThreadId, state_db: Arc, + accounting_state: Arc, event_emitter: GoalEventEmitter, ) -> Self { Self { kind: GoalToolKind::Create, thread_id, state_db, + accounting_state, event_emitter, } } @@ -95,12 +102,14 @@ impl GoalToolExecutor { pub(crate) fn update( thread_id: ThreadId, state_db: Arc, + accounting_state: Arc, event_emitter: GoalEventEmitter, ) -> Self { Self { kind: GoalToolKind::Update, thread_id, state_db, + accounting_state, event_emitter, } } @@ -179,8 +188,11 @@ impl GoalToolExecutor { ) })?; fill_empty_thread_preview_if_possible(self.state_db.as_ref(), self.thread_id, &goal).await; + let turn_id = self + .accounting_state + .mark_current_turn_goal_active(goal.goal_id.clone()); let goal = protocol_goal_from_state(goal); - self.emit_goal_updated_from_tool_call(&invocation, goal.clone()); + self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone()); goal_response(Some(goal), CompletionBudgetReport::Omit) } @@ -189,15 +201,29 @@ impl GoalToolExecutor { invocation: ToolCall, ) -> Result, FunctionCallError> { let args: UpdateGoalArgs = parse_arguments(invocation.function_arguments()?)?; - if args.status != ThreadGoalStatus::Complete { + if !matches!( + args.status, + ThreadGoalStatus::Complete | ThreadGoalStatus::Blocked + ) { return Err(FunctionCallError::RespondToModel( - "update_goal can only mark the existing goal complete; pause, resume, and budget-limited status changes are controlled by the user or system" + "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(), )); } - // TODO: update_goal needs a host callback before completion to flush - // final active-turn accounting with budget steering suppressed. + self.account_active_goal_progress( + match args.status { + ThreadGoalStatus::Complete => codex_state::GoalAccountingMode::ActiveOrComplete, + ThreadGoalStatus::Blocked => codex_state::GoalAccountingMode::ActiveOrStopped, + ThreadGoalStatus::Active + | ThreadGoalStatus::Paused + | ThreadGoalStatus::UsageLimited + | ThreadGoalStatus::BudgetLimited => unreachable!("status validated above"), + }, + invocation.call_id.as_str(), + BudgetLimitedGoalDisposition::ClearActive, + ) + .await?; let goal = self .state_db .thread_goals() @@ -205,14 +231,14 @@ impl GoalToolExecutor { self.thread_id, codex_state::GoalUpdate { objective: None, - status: Some(codex_state::ThreadGoalStatus::Complete), + status: Some(state_status_from_protocol(args.status)), token_budget: None, expected_goal_id: None, }, ) .await .map_err(|err| { - FunctionCallError::RespondToModel(format!("failed to complete goal: {err}")) + FunctionCallError::RespondToModel(format!("failed to update goal: {err}")) })? .map(protocol_goal_from_state) .ok_or_else(|| { @@ -220,19 +246,72 @@ impl GoalToolExecutor { "cannot update goal because this thread has no goal".to_string(), ) })?; - self.emit_goal_updated_from_tool_call(&invocation, goal.clone()); - goal_response(Some(goal), CompletionBudgetReport::Include) + let turn_id = self.accounting_state.clear_current_turn_goal(); + self.emit_goal_updated_from_tool_call(&invocation, turn_id, goal.clone()); + goal_response( + Some(goal), + if args.status == ThreadGoalStatus::Complete { + CompletionBudgetReport::Include + } else { + CompletionBudgetReport::Omit + }, + ) } - fn emit_goal_updated_from_tool_call(&self, invocation: &ToolCall, goal: ThreadGoal) { - // TODO: ToolCall should expose the current turn submission id so goal - // tool events can set ThreadGoalUpdatedEvent.turn_id exactly as core - // does today. Until then, correlate the event with the tool call id. - self.event_emitter.thread_goal_updated( - invocation.call_id.clone(), - /*turn_id*/ None, - goal, - ); + fn emit_goal_updated_from_tool_call( + &self, + invocation: &ToolCall, + turn_id: Option, + goal: ThreadGoal, + ) { + self.event_emitter + .thread_goal_updated(invocation.call_id.clone(), turn_id, goal); + } + + async fn account_active_goal_progress( + &self, + mode: codex_state::GoalAccountingMode, + event_id: &str, + budget_limited_goal_disposition: BudgetLimitedGoalDisposition, + ) -> Result, FunctionCallError> { + let Some(turn_id) = self.accounting_state.current_turn_id() else { + return Ok(None); + }; + let Some(snapshot) = self.accounting_state.progress_snapshot(turn_id.as_str()) else { + return Ok(None); + }; + let outcome = self + .state_db + .thread_goals() + .account_thread_goal_usage( + self.thread_id, + snapshot.time_delta_seconds, + snapshot.token_delta, + mode, + Some(snapshot.expected_goal_id.as_str()), + ) + .await + .map_err(|err| { + FunctionCallError::RespondToModel(format!("failed to account goal progress: {err}")) + })?; + Ok(match outcome { + codex_state::GoalAccountingOutcome::Updated(goal) => { + self.accounting_state.mark_progress_accounted_for_status( + turn_id.as_str(), + &snapshot, + goal.status, + budget_limited_goal_disposition, + ); + let goal = protocol_goal_from_state(goal); + self.event_emitter.thread_goal_updated( + event_id.to_string(), + Some(turn_id), + goal.clone(), + ); + Some(goal) + } + codex_state::GoalAccountingOutcome::Unchanged(_) => None, + }) } } @@ -298,7 +377,7 @@ async fn fill_empty_thread_preview_if_possible( } } -fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal { +pub(crate) fn protocol_goal_from_state(goal: codex_state::ThreadGoal) -> ThreadGoal { ThreadGoal { thread_id: goal.thread_id, objective: goal.objective, @@ -322,6 +401,17 @@ fn protocol_status_from_state(status: codex_state::ThreadGoalStatus) -> ThreadGo } } +fn state_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, + } +} + fn completion_budget_report(goal: &ThreadGoal) -> Option { if goal.token_budget.is_none() && goal.time_used_seconds <= 0 { None diff --git a/codex-rs/ext/goal/tests/goal_extension_backend.rs b/codex-rs/ext/goal/tests/goal_extension_backend.rs index a79c69c633..d04dbe6021 100644 --- a/codex-rs/ext/goal/tests/goal_extension_backend.rs +++ b/codex-rs/ext/goal/tests/goal_extension_backend.rs @@ -1,16 +1,32 @@ use std::sync::Arc; +use std::sync::Mutex; +use std::sync::PoisonError; use codex_extension_api::ExtensionData; +use codex_extension_api::ExtensionEventSink; use codex_extension_api::ExtensionRegistryBuilder; use codex_extension_api::FunctionCallError; use codex_extension_api::ThreadStartInput; use codex_extension_api::ToolCall; +use codex_extension_api::ToolCallOutcome; +use codex_extension_api::ToolCallSource; use codex_extension_api::ToolExecutor; +use codex_extension_api::ToolFinishInput; +use codex_extension_api::ToolName; use codex_extension_api::ToolPayload; +use codex_extension_api::TurnStartInput; +use codex_extension_api::TurnStopInput; use codex_goal_extension::install_with_backend; use codex_protocol::ThreadId; -use codex_protocol::ToolName; +use codex_protocol::config_types::CollaborationMode; +use codex_protocol::config_types::ModeKind; +use codex_protocol::config_types::Settings; +use codex_protocol::protocol::Event; +use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::SessionSource; +use codex_protocol::protocol::ThreadGoalStatus; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; use pretty_assertions::assert_eq; use serde_json::json; use tempfile::TempDir; @@ -70,7 +86,8 @@ async fn installed_goal_tools_reject_duplicate_goal_creation() -> anyhow::Result let runtime = test_runtime().await?; let thread_id = test_thread_id()?; seed_thread_metadata(runtime.as_ref(), thread_id).await?; - let tools = installed_tools(runtime, thread_id).await; + let harness = GoalExtensionHarness::new(runtime, thread_id).await?; + let tools = harness.tools(); let create_tool = tool_by_name(&tools, "create_goal"); let first = tool_call( @@ -100,6 +117,273 @@ async fn installed_goal_tools_reject_duplicate_goal_creation() -> anyhow::Result Ok(()) } +#[tokio::test] +async fn create_goal_resets_baseline_before_turn_stop_accounting() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + seed_thread_metadata(runtime.as_ref(), thread_id).await?; + let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?; + harness + .start_turn( + "turn-1", + &token_usage( + /*input_tokens*/ 100, /*cached_input_tokens*/ 10, + /*output_tokens*/ 30, /*reasoning_output_tokens*/ 5, + /*total_tokens*/ 135, + ), + ) + .await; + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 120, /*cached_input_tokens*/ 14, + /*output_tokens*/ 42, /*reasoning_output_tokens*/ 8, + /*total_tokens*/ 162, + ), + ) + .await; + + let tools = harness.tools(); + let create_tool = tool_by_name(&tools, "create_goal"); + create_tool + .handle(tool_call( + "create_goal", + "call-create-goal", + json!({ "objective": "ship goal extension backend" }), + )) + .await?; + + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 127, /*cached_input_tokens*/ 16, + /*output_tokens*/ 52, /*reasoning_output_tokens*/ 10, + /*total_tokens*/ 189, + ), + ) + .await; + harness.stop_turn("turn-1").await; + + let goal = runtime + .thread_goals() + .get_thread_goal(thread_id) + .await? + .ok_or_else(|| anyhow::anyhow!("goal should exist"))?; + assert_eq!(15, goal.tokens_used); + assert_eq!(ThreadGoalStatus::Active, protocol_status(goal.status)); + Ok(()) +} + +#[tokio::test] +async fn tool_finish_accounts_active_goal_progress_and_emits_event() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + seed_thread_metadata(runtime.as_ref(), thread_id).await?; + let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?; + harness.start_turn("turn-1", &TokenUsage::default()).await; + + let tools = harness.tools(); + let create_tool = tool_by_name(&tools, "create_goal"); + create_tool + .handle(tool_call( + "create_goal", + "call-create-goal", + json!({ "objective": "ship goal extension backend" }), + )) + .await?; + harness.sink.clear(); + + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8, + /*reasoning_output_tokens*/ 2, /*total_tokens*/ 30, + ), + ) + .await; + harness + .notify_tool_finish("turn-1", "call-shell", "shell") + .await; + + let goal = runtime + .thread_goals() + .get_thread_goal(thread_id) + .await? + .ok_or_else(|| anyhow::anyhow!("goal should exist"))?; + assert_eq!(23, goal.tokens_used); + + assert_eq!( + vec![CapturedGoalEvent { + event_id: "call-shell".to_string(), + turn_id: Some("turn-1".to_string()), + status: ThreadGoalStatus::Active, + tokens_used: 23, + }], + harness.sink.goal_events() + ); + Ok(()) +} + +#[tokio::test] +async fn budget_limited_goal_keeps_accruing_until_turn_stop() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + seed_thread_metadata(runtime.as_ref(), thread_id).await?; + let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?; + harness.start_turn("turn-1", &TokenUsage::default()).await; + + let tools = harness.tools(); + let create_tool = tool_by_name(&tools, "create_goal"); + create_tool + .handle(tool_call( + "create_goal", + "call-create-goal", + json!({ + "objective": "ship goal extension backend", + "token_budget": 25, + }), + )) + .await?; + harness.sink.clear(); + + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 20, /*cached_input_tokens*/ 5, + /*output_tokens*/ 10, /*reasoning_output_tokens*/ 0, + /*total_tokens*/ 30, + ), + ) + .await; + harness + .notify_tool_finish("turn-1", "call-shell", "shell") + .await; + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 24, /*cached_input_tokens*/ 5, + /*output_tokens*/ 16, /*reasoning_output_tokens*/ 0, + /*total_tokens*/ 40, + ), + ) + .await; + harness.stop_turn("turn-1").await; + + let goal = runtime + .thread_goals() + .get_thread_goal(thread_id) + .await? + .ok_or_else(|| anyhow::anyhow!("goal should exist"))?; + assert_eq!(35, goal.tokens_used); + assert_eq!(codex_state::ThreadGoalStatus::BudgetLimited, goal.status); + + assert_eq!( + vec![ + CapturedGoalEvent { + event_id: "call-shell".to_string(), + turn_id: Some("turn-1".to_string()), + status: ThreadGoalStatus::BudgetLimited, + tokens_used: 25, + }, + CapturedGoalEvent { + event_id: "turn-1:turn-stop".to_string(), + turn_id: Some("turn-1".to_string()), + status: ThreadGoalStatus::BudgetLimited, + tokens_used: 35, + }, + ], + harness.sink.goal_events() + ); + Ok(()) +} + +#[tokio::test] +async fn update_goal_can_block_and_accounts_final_progress() -> anyhow::Result<()> { + let runtime = test_runtime().await?; + let thread_id = test_thread_id()?; + seed_thread_metadata(runtime.as_ref(), thread_id).await?; + let harness = GoalExtensionHarness::new(runtime.clone(), thread_id).await?; + harness.start_turn("turn-1", &TokenUsage::default()).await; + + let tools = harness.tools(); + let create_tool = tool_by_name(&tools, "create_goal"); + create_tool + .handle(tool_call( + "create_goal", + "call-create-goal", + json!({ "objective": "ship goal extension backend" }), + )) + .await?; + harness.sink.clear(); + + harness + .record_token_usage( + "turn-1", + &token_usage( + /*input_tokens*/ 20, /*cached_input_tokens*/ 5, /*output_tokens*/ 8, + /*reasoning_output_tokens*/ 2, /*total_tokens*/ 30, + ), + ) + .await; + let update_tool = tool_by_name(&tools, "update_goal"); + let invocation = tool_call( + "update_goal", + "call-update-goal", + json!({ "status": "blocked" }), + ); + let output = update_tool.handle(invocation.clone()).await?; + let result = output.code_mode_result(&invocation.payload); + + assert_eq!( + result, + json!({ + "goal": { + "threadId": thread_id, + "objective": "ship goal extension backend", + "status": "blocked", + "tokensUsed": 23, + "timeUsedSeconds": 0, + "createdAt": result["goal"]["createdAt"], + "updatedAt": result["goal"]["updatedAt"], + }, + "remainingTokens": serde_json::Value::Null, + "completionBudgetReport": serde_json::Value::Null, + }) + ); + + let goal = runtime + .thread_goals() + .get_thread_goal(thread_id) + .await? + .ok_or_else(|| anyhow::anyhow!("goal should exist"))?; + assert_eq!(23, goal.tokens_used); + assert_eq!(codex_state::ThreadGoalStatus::Blocked, goal.status); + + assert_eq!( + vec![ + CapturedGoalEvent { + event_id: "call-update-goal".to_string(), + turn_id: Some("turn-1".to_string()), + status: ThreadGoalStatus::Active, + tokens_used: 23, + }, + CapturedGoalEvent { + event_id: "call-update-goal".to_string(), + turn_id: Some("turn-1".to_string()), + status: ThreadGoalStatus::Blocked, + tokens_used: 23, + }, + ], + harness.sink.goal_events() + ); + Ok(()) +} + async fn installed_tools( runtime: Arc, thread_id: ThreadId, @@ -126,6 +410,118 @@ async fn installed_tools( .collect() } +struct GoalExtensionHarness { + registry: codex_extension_api::ExtensionRegistry<()>, + session_store: ExtensionData, + thread_store: ExtensionData, + sink: Arc, +} + +impl GoalExtensionHarness { + async fn new( + runtime: Arc, + thread_id: ThreadId, + ) -> anyhow::Result { + let sink = Arc::new(RecordingEventSink::default()); + let mut builder = ExtensionRegistryBuilder::<()>::with_event_sink(sink.clone()); + install_with_backend(&mut builder, runtime, |_| true); + let registry = builder.build(); + let session_store = ExtensionData::new("session-1"); + let thread_store = ExtensionData::new(thread_id.to_string()); + for contributor in registry.thread_lifecycle_contributors() { + contributor + .on_thread_start(ThreadStartInput { + config: &(), + session_store: &session_store, + thread_store: &thread_store, + }) + .await; + } + Ok(Self { + registry, + session_store, + thread_store, + sink, + }) + } + + fn tools(&self) -> Vec>> { + self.registry + .tool_contributors() + .iter() + .flat_map(|contributor| contributor.tools(&self.session_store, &self.thread_store)) + .collect() + } + + async fn start_turn(&self, turn_id: &str, usage: &TokenUsage) { + let turn_store = ExtensionData::new(turn_id); + let collaboration_mode = default_collaboration_mode(); + for contributor in self.registry.turn_lifecycle_contributors() { + contributor + .on_turn_start(TurnStartInput { + turn_id, + collaboration_mode: &collaboration_mode, + token_usage_at_turn_start: usage, + session_store: &self.session_store, + thread_store: &self.thread_store, + turn_store: &turn_store, + }) + .await; + } + } + + async fn stop_turn(&self, turn_id: &str) { + let turn_store = ExtensionData::new(turn_id); + for contributor in self.registry.turn_lifecycle_contributors() { + contributor + .on_turn_stop(TurnStopInput { + session_store: &self.session_store, + thread_store: &self.thread_store, + turn_store: &turn_store, + }) + .await; + } + } + + async fn record_token_usage(&self, turn_id: &str, usage: &TokenUsage) { + let turn_store = ExtensionData::new(turn_id); + let token_usage = TokenUsageInfo { + total_token_usage: usage.clone(), + last_token_usage: TokenUsage::default(), + model_context_window: None, + }; + for contributor in self.registry.token_usage_contributors() { + contributor + .on_token_usage( + &self.session_store, + &self.thread_store, + &turn_store, + &token_usage, + ) + .await; + } + } + + async fn notify_tool_finish(&self, turn_id: &str, call_id: &str, tool_name: &str) { + let turn_store = ExtensionData::new(turn_id); + let tool_name = codex_extension_api::ToolName::plain(tool_name); + for contributor in self.registry.tool_lifecycle_contributors() { + contributor + .on_tool_finish(ToolFinishInput { + session_store: &self.session_store, + thread_store: &self.thread_store, + turn_store: &turn_store, + turn_id, + call_id, + tool_name: &tool_name, + source: ToolCallSource::Direct, + outcome: ToolCallOutcome::Completed { success: true }, + }) + .await; + } + } +} + fn tool_by_name<'a>( tools: &'a [Arc>], name: &str, @@ -139,7 +535,7 @@ fn tool_by_name<'a>( fn tool_call(tool_name: &str, call_id: &str, arguments: serde_json::Value) -> ToolCall { ToolCall { call_id: call_id.to_string(), - tool_name: ToolName::plain(tool_name), + tool_name: codex_extension_api::ToolName::plain(tool_name), payload: ToolPayload::Function { arguments: arguments.to_string(), }, @@ -169,3 +565,85 @@ async fn seed_thread_metadata( ); runtime.upsert_thread(&builder.build("test-provider")).await } + +#[derive(Debug, Default)] +struct RecordingEventSink { + events: Mutex>, +} + +impl RecordingEventSink { + fn goal_events(&self) -> Vec { + self.events() + .iter() + .filter_map(|event| match &event.msg { + EventMsg::ThreadGoalUpdated(updated) => Some(CapturedGoalEvent { + event_id: event.id.clone(), + turn_id: updated.turn_id.clone(), + status: updated.goal.status, + tokens_used: updated.goal.tokens_used, + }), + _ => None, + }) + .collect() + } + + fn clear(&self) { + self.events().clear(); + } + + fn events(&self) -> std::sync::MutexGuard<'_, Vec> { + self.events.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +impl ExtensionEventSink for RecordingEventSink { + fn emit(&self, event: Event) { + self.events().push(event); + } +} + +#[derive(Debug, PartialEq, Eq)] +struct CapturedGoalEvent { + event_id: String, + turn_id: Option, + status: ThreadGoalStatus, + tokens_used: i64, +} + +fn default_collaboration_mode() -> CollaborationMode { + CollaborationMode { + mode: ModeKind::Default, + settings: Settings { + model: "gpt-5".to_string(), + reasoning_effort: None, + developer_instructions: None, + }, + } +} + +fn token_usage( + input_tokens: i64, + cached_input_tokens: i64, + output_tokens: i64, + reasoning_output_tokens: i64, + total_tokens: i64, +) -> TokenUsage { + TokenUsage { + input_tokens, + cached_input_tokens, + output_tokens, + reasoning_output_tokens, + total_tokens, + } +} + +fn protocol_status(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, + } +}