From ff2ee6212c05e0e53eb97c47d49f4a9e952816a1 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Tue, 24 Nov 2026 22:16:45 +0000 Subject: [PATCH] Track additional context in conversation world state (#63769) ## Why The baseline for comparing additional context submissions lived in memory, so resuming a conversation could append context that was already in its history. ## What changed Persist the rendered fingerprints and history item IDs for active context entries in world state. Reuse unchanged entries across turns and resumes, and use their IDs to restore active items during compaction. A client submission replaces the active set. Tool-provided context updates only its own keys and is recorded after tool results, before the next prompt. ## Testing Extend scenario coverage to check deduplication after resume for both message and tool-output rendering. Verify that edits in the truncated portion of application context do not produce duplicate developer messages. GitOrigin-RevId: 12a65a70d871f8dcefa082825c0ec4e9446efb56 --- .../src/additional_context.rs | 153 ------------ codex-rs/context-fragments/src/lib.rs | 5 - .../src/context/contextual_user_message.rs | 4 +- codex-rs/core/src/context/mod.rs | 3 - .../context/world_state/additional_context.rs | 233 ++++++++++++++++++ codex-rs/core/src/context/world_state/mod.rs | 24 ++ codex-rs/core/src/context_manager/history.rs | 27 +- .../core/src/context_manager/history_tests.rs | 12 +- .../src/session/compaction_replacement.rs | 14 +- codex-rs/core/src/session/mod.rs | 26 +- codex-rs/core/src/session/turn.rs | 36 ++- codex-rs/core/src/session/turn_input.rs | 34 +-- codex-rs/core/src/session/world_state.rs | 36 +++ codex-rs/core/src/state/additional_context.rs | 191 -------------- codex-rs/core/src/state/mod.rs | 3 - codex-rs/core/src/state/session.rs | 3 - codex-rs/core/src/tasks/mod.rs | 29 +-- .../core/tests/suite/additional_context.rs | 11 +- codex-rs/core/tests/suite/scenarios.rs | 37 ++- codex-rs/ext/guardian-v3/tests/evidence.rs | 11 +- 20 files changed, 433 insertions(+), 459 deletions(-) delete mode 100644 codex-rs/context-fragments/src/additional_context.rs create mode 100644 codex-rs/core/src/context/world_state/additional_context.rs delete mode 100644 codex-rs/core/src/state/additional_context.rs diff --git a/codex-rs/context-fragments/src/additional_context.rs b/codex-rs/context-fragments/src/additional_context.rs deleted file mode 100644 index 73ef89fc2b..0000000000 --- a/codex-rs/context-fragments/src/additional_context.rs +++ /dev/null @@ -1,153 +0,0 @@ -use codex_protocol::models::ContentItem; -use codex_protocol::models::ContentItemKind; -use codex_protocol::models::FunctionCallOutputPayload; -use codex_protocol::models::ResponseItem; -use codex_protocol::models::input_text; -use codex_utils_string::truncate_middle_with_token_budget; - -use crate::ContextualUserFragment; - -pub const MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS: usize = 1_000; -const MAX_DERIVED_TOOL_NAME_CHARS: usize = 128; -const ADDITIONAL_CONTEXT_TOOL_NAMESPACE: &str = "agent"; -const ADDITIONAL_CONTEXT_END_MARKER_SUFFIX: &str = ">"; -const ADDITIONAL_CONTEXT_START_MARKER_PREFIX: &str = ", value: &str) -> Self { - let name = name.unwrap_or_else(|| tool_name_from_key(key)); - Self { - name, - value: truncate_middle_with_token_budget(value, MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS).0, - } - } -} - -impl From for ResponseItem { - fn from(output: AdditionalContextToolOutput) -> Self { - Self::FunctionCallOutput { - id: None, - call_id: None, - name: Some(output.name), - namespace: Some(ADDITIONAL_CONTEXT_TOOL_NAMESPACE.to_owned()), - output: FunctionCallOutputPayload::from_text(output.value), - internal_chat_message_metadata_passthrough: None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AdditionalContextUserFragment { - key: String, - value: String, -} - -impl AdditionalContextUserFragment { - pub fn new(key: String, value: String) -> Self { - Self { key, value } - } -} - -impl ContextualUserFragment for AdditionalContextUserFragment { - fn role(&self) -> &'static str { - "user" - } - - fn content_kind(&self) -> ContentItemKind { - ContentItemKind(format!("additional_content.{}", self.key)) - } - - fn markers(&self) -> (&'static str, &'static str) { - Self::type_markers() - } - - fn type_markers() -> (&'static str, &'static str) { - ( - ADDITIONAL_CONTEXT_START_MARKER_PREFIX, - ADDITIONAL_CONTEXT_END_MARKER_SUFFIX, - ) - } - - fn matches_text(text: &str) -> bool { - let trimmed = text.trim(); - let Some(rest) = trimmed.strip_prefix(ADDITIONAL_CONTEXT_START_MARKER_PREFIX) else { - return false; - }; - let Some((key, value_and_close)) = rest.split_once(ADDITIONAL_CONTEXT_END_MARKER_SUFFIX) - else { - return false; - }; - - value_and_close.ends_with(&format!("")) - } - - fn body(&self) -> ContentItem { - input_text(additional_context_body(&self.key, &self.value)) - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct AdditionalContextDeveloperFragment { - key: String, - value: String, -} - -impl AdditionalContextDeveloperFragment { - pub fn new(key: String, value: String) -> Self { - Self { key, value } - } -} - -impl ContextualUserFragment for AdditionalContextDeveloperFragment { - fn role(&self) -> &'static str { - "developer" - } - - fn content_kind(&self) -> ContentItemKind { - ContentItemKind(format!("additional_content.{}", self.key)) - } - - fn markers(&self) -> (&'static str, &'static str) { - Self::type_markers() - } - - fn type_markers() -> (&'static str, &'static str) { - ("", "") - } - - fn body(&self) -> ContentItem { - input_text(additional_context_developer_body(&self.key, &self.value)) - } -} - -fn tool_name_from_key(key: &str) -> String { - let derived: String = key - .chars() - .map(|ch| if ch == ' ' { '_' } else { ch }) - .filter(|ch| ch.is_ascii_alphanumeric() || *ch == '_') - .take(MAX_DERIVED_TOOL_NAME_CHARS) - .collect(); - if derived.is_empty() { - "untrusted_content".to_owned() - } else { - derived - } -} - -fn additional_context_body(key: &str, value: &str) -> String { - let value = truncate_middle_with_token_budget(value, MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS).0; - format!("{key}>{value} String { - let value = truncate_middle_with_token_budget(value, MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS).0; - format!("<{key}>{value}") -} diff --git a/codex-rs/context-fragments/src/lib.rs b/codex-rs/context-fragments/src/lib.rs index f02dd2c375..edac32927e 100644 --- a/codex-rs/context-fragments/src/lib.rs +++ b/codex-rs/context-fragments/src/lib.rs @@ -1,15 +1,10 @@ mod answered_question; pub use answered_question::AnsweredQuestion; -mod additional_context; mod annotated_content; mod fragment; mod recap_prompt; mod side_conversation; -pub use additional_context::AdditionalContextDeveloperFragment; -pub use additional_context::AdditionalContextToolOutput; -pub use additional_context::AdditionalContextUserFragment; -pub use additional_context::MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS; pub use annotated_content::AnnotatedContent; pub use annotated_content::message_from_parts; pub use annotated_content::set_annotated_content; diff --git a/codex-rs/core/src/context/contextual_user_message.rs b/codex-rs/core/src/context/contextual_user_message.rs index 130fe03c56..0120c4e0a5 100644 --- a/codex-rs/core/src/context/contextual_user_message.rs +++ b/codex-rs/core/src/context/contextual_user_message.rs @@ -3,7 +3,6 @@ use codex_protocol::items::parse_hook_prompt_fragment; use codex_protocol::models::ContentItem; use codex_protocol::models::ResponseItem; -use super::AdditionalContextUserFragment; use super::AgentMessageBoardNotification; use super::ContextualUserFragment; use super::GuardianRetainedInstructions; @@ -18,13 +17,14 @@ use super::UnsupportedMedia; use super::UserGoalUpdate; use super::UserInstructions; use super::UserShellCommand; +use super::world_state::AdditionalContextState; use super::world_state::EnvironmentsState; use crate::image_preparation::ImagePreparationError; const CONTEXTUAL_USER_FRAGMENT_MATCHERS: &[fn(&str) -> bool] = &[ UserInstructions::matches_text, EnvironmentsState::matches_text, - AdditionalContextUserFragment::matches_text, + AdditionalContextState::matches_user_text, AgentMessageBoardNotification::matches_text, codex_skills_extension::is_skill_prompt_fragment, UserShellCommand::matches_text, diff --git a/codex-rs/core/src/context/mod.rs b/codex-rs/core/src/context/mod.rs index cd7b96b6ef..a030a18db4 100644 --- a/codex-rs/core/src/context/mod.rs +++ b/codex-rs/core/src/context/mod.rs @@ -63,9 +63,6 @@ pub(crate) use apps_instructions::AppsInstructions; pub(crate) use apps_instructions::CatalogAppsInstructions; pub(crate) use available_plugins_instructions::AvailablePluginsInstructions; pub(crate) use base_instructions::BaseInstructionsFragment; -pub(crate) use codex_context_fragments::AdditionalContextDeveloperFragment; -pub(crate) use codex_context_fragments::AdditionalContextToolOutput; -pub(crate) use codex_context_fragments::AdditionalContextUserFragment; pub use codex_context_fragments::AnsweredQuestion; pub use codex_context_fragments::ContextualUserFragment; pub(crate) use codex_guardian_context::PermissionContext as GuardianPermissionContext; diff --git a/codex-rs/core/src/context/world_state/additional_context.rs b/codex-rs/core/src/context/world_state/additional_context.rs new file mode 100644 index 0000000000..e61f3b641a --- /dev/null +++ b/codex-rs/core/src/context/world_state/additional_context.rs @@ -0,0 +1,233 @@ +//! Renders client input as standalone items. WorldState tracks their fingerprints and history IDs. + +use super::PreviousSectionState; +use super::SectionTransition; +use super::WorldStateHash; +use super::WorldStateSection; +use super::WorldStateSnapshot; +use super::WorldStateUpdate; +use codex_context_fragments::AnnotatedContent; +use codex_context_fragments::RenderedFragment; +use codex_history::ResponseItemEnvelope; +use codex_otel::ADDITIONAL_CONTEXT_COUNT_METRIC; +use codex_otel::ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS; +use codex_otel::ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC; +use codex_otel::SessionTelemetry; +use codex_protocol::ResponseItemId; +use codex_protocol::models::ContentItemKind; +use codex_protocol::models::ContentItemMetadata; +use codex_protocol::models::FunctionCallOutputPayload; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::AdditionalContextEntry; +use codex_protocol::protocol::AdditionalContextKind; +use codex_thread_context_ids::ThreadContextIds; +use codex_utils_string::truncate_middle_with_token_budget; +use serde::Deserialize; +use std::collections::BTreeMap; +use std::collections::HashMap; + +const MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS: usize = 1_000; +const MAX_DERIVED_TOOL_NAME_CHARS: usize = 128; + +/// A delivered client submission replaces the active sources. Extension inputs only update their own keys. +pub(crate) struct AdditionalContextState { + items: Vec<(String, ResponseItem)>, + ids: ThreadContextIds, + extend: bool, +} + +type Snapshot = BTreeMap; + +impl AdditionalContextState { + pub(crate) fn new( + entries: &BTreeMap, + tool_outputs: bool, + telemetry: &SessionTelemetry, + ids: &ThreadContextIds, + ) -> Self { + let items = entries + .iter() + .map(|(key, entry)| { + let (value, original_tokens) = truncate_middle_with_token_budget( + &entry.value, + MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS, + ); + Self::record_metrics(entry, value.len(), original_tokens.is_some(), telemetry); + let item = match entry.kind { + AdditionalContextKind::Untrusted if tool_outputs => { + ResponseItem::FunctionCallOutput { + id: None, + call_id: None, + name: Some( + entry + .name + .clone() + .unwrap_or_else(|| tool_name_from_key(key)), + ), + namespace: Some("agent".to_owned()), + output: FunctionCallOutputPayload::from_text(value), + internal_chat_message_metadata_passthrough: None, + } + } + AdditionalContextKind::Untrusted => message( + "user", + key, + format!("{value}"), + ), + AdditionalContextKind::Application => { + message("developer", key, format!("<{key}>{value}")) + } + }; + (key.clone(), item) + }) + .collect(); + Self { + items, + ids: ids.clone(), + extend: false, + } + } + + pub(crate) fn extending(mut self) -> Self { + self.extend = true; + self + } + + pub(crate) fn matches_user_text(text: &str) -> bool { + text.trim() + .strip_prefix("')) + .is_some_and(|(key, rest)| rest.ends_with(&format!(""))) + } + + fn record_metrics( + entry: &AdditionalContextEntry, + bounded_bytes: usize, + truncated: bool, + telemetry: &SessionTelemetry, + ) { + let kind = match entry.kind { + AdditionalContextKind::Untrusted => "untrusted", + AdditionalContextKind::Application => "application", + }; + let truncated = truncated.to_string(); + let mut tags = vec![("kind", kind), ("truncated", truncated.as_str())]; + if let Some(name) = entry.name.as_deref() { + tags.push(("name", name)); + } + telemetry.counter(ADDITIONAL_CONTEXT_COUNT_METRIC, /*inc*/ 1, &tags); + for (stage, bytes) in [("before", entry.value.len()), ("after", bounded_bytes)] { + let mut size_tags = tags.clone(); + size_tags.push(("stage", stage)); + telemetry.histogram_with_boundaries( + ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC, + i64::try_from(bytes).unwrap_or(i64::MAX), + ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS.as_slice(), + &size_tags, + ); + } + } +} + +impl WorldStateSection for AdditionalContextState { + const ID: &'static str = "additional_context"; + type Snapshot = Snapshot; + + fn should_persist(&self) -> bool { + !self.items.is_empty() + } + + fn render_diff( + &self, + previous: PreviousSectionState<'_, Self::Snapshot>, + ) -> SectionTransition { + let previous = match previous { + PreviousSectionState::Known(previous) => Some(previous), + PreviousSectionState::Absent | PreviousSectionState::Unknown => None, + }; + let mut snapshot = previous + .filter(|_| self.extend) + .cloned() + .unwrap_or_default(); + let mut updates = Vec::new(); + for (key, item) in &self.items { + let hash = WorldStateHash::from_json(&serde_json::json!(item)); + if let Some((old_hash, id)) = previous.and_then(|entries| entries.get(key)) + && *old_hash == hash + { + snapshot.insert(key.clone(), (hash, id.clone())); + continue; + } + let Some(prefix) = item.id_prefix() else { + unreachable!("additional context has an item ID") + }; + let id = self.ids.next_item(prefix); + let mut item = item.clone(); + item.set_id(Some(id.clone())); + updates.push(WorldStateUpdate::item(item)); + snapshot.insert(key.clone(), (hash, id)); + } + (Some(snapshot), updates) + } +} + +impl WorldStateSnapshot { + /// Steps have no new client submission. Carry the delivered section forward unchanged. + pub(crate) fn retain_input_context(&mut self, previous: &Self) { + if let Some(context) = previous.section(AdditionalContextState::ID) { + self.insert_section(AdditionalContextState::ID, context.clone()); + } + } + + /// Keep active items in history order, refreshing ones shortened by generic retention. + pub(crate) fn restore_input_context( + &self, + replaced: &[ResponseItemEnvelope], + retained: &mut [ResponseItemEnvelope], + ) -> Vec { + let Some(context) = self + .section(AdditionalContextState::ID) + .and_then(|section| Snapshot::deserialize(section).ok()) + else { + return Vec::new(); + }; + let mut active: HashMap<_, _> = context.into_values().map(|(_, id)| (id, None)).collect(); + for item in retained { + if let Some(slot) = item.id().and_then(|id| active.get_mut(id)) { + *slot = Some(item); + } + } + let mut missing = Vec::new(); + for item in replaced { + match item.id().and_then(|id| active.remove(id)) { + Some(Some(existing)) => existing.item.clone_from(&item.item), + Some(None) => missing.push(item.clone()), + None => {} + } + } + missing + } +} + +fn message(role: &'static str, key: &str, text: String) -> ResponseItem { + let content = AnnotatedContent::text( + text, + ContentItemKind(format!("additional_content.{key}")), + ContentItemMetadata::harness(), + ); + RenderedFragment::new(role, content).into() +} + +fn tool_name_from_key(key: &str) -> String { + let derived: String = key + .chars() + .map(|ch| if ch == ' ' { '_' } else { ch }) + .filter(|ch| ch.is_ascii_alphanumeric() || *ch == '_') + .take(MAX_DERIVED_TOOL_NAME_CHARS) + .collect(); + if derived.is_empty() { + "untrusted_content".to_owned() + } else { + derived + } +} diff --git a/codex-rs/core/src/context/world_state/mod.rs b/codex-rs/core/src/context/world_state/mod.rs index 481c20c57c..e3d64da9d8 100644 --- a/codex-rs/core/src/context/world_state/mod.rs +++ b/codex-rs/core/src/context/world_state/mod.rs @@ -1,3 +1,4 @@ +mod additional_context; mod agents_md; mod apps_instructions; mod collaboration_mode; @@ -41,6 +42,7 @@ use std::collections::BTreeSet; use std::fmt; use std::sync::Arc; +pub(crate) use additional_context::AdditionalContextState; pub(crate) use agents_md::AgentsMdState; pub(crate) use apps_instructions::AppsInstructionsState; pub(crate) use collaboration_mode::CollaborationModeState; @@ -133,6 +135,13 @@ impl WorldStateUpdate { self } + pub(crate) fn item(item: ResponseItem) -> Self { + Self { + placement: Placement::Standalone, + content: WorldStateUpdateContent::Item(Box::new(item)), + } + } + pub(crate) fn prefix_item(item: ResponseItem) -> Self { Self { placement: Placement::Prefix, @@ -650,6 +659,21 @@ impl WorldState { (snapshot, updates) } + /// Render a single input-driven section without dropping unrelated step state. + pub(crate) fn render_section<'a, S: WorldStateSection>( + section: S, + previous: Option<&WorldStateSnapshot>, + items: impl IntoIterator + Clone, + ) -> (WorldStateSnapshot, Vec) { + let mut state = Self::default(); + state.add_section(section); + let (current, updates) = state.render_history_diff(previous, items); + let mut snapshot = previous.cloned().unwrap_or_default(); + snapshot.remove_section(S::ID); + snapshot.sections.extend(current.sections); + (snapshot, updates) + } + pub(crate) fn render_full(&self) -> (WorldStateSnapshot, Vec) { self.render_with(RenderScope::FullContext, /*stored*/ None, |_, _| { (PreviousSectionState::Absent, None) diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 8282351db4..2363a800f3 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -22,6 +22,7 @@ use crate::context::ModelSwitchInstructions; use crate::context::is_guardian_context_message; use crate::context::world_state::PersistentModeState; use crate::context::world_state::WorldState; +use crate::context::world_state::WorldStateSection; use crate::context::world_state::WorldStateSnapshot; use crate::context::world_state::WorldStateUpdate; use crate::context_manager::normalize; @@ -626,6 +627,23 @@ impl ContextManager { self.reference_context_item.as_ref() } + pub(crate) fn render_input_world_state( + &self, + section: impl WorldStateSection, + ) -> ( + WorldStateSnapshot, + Vec, + Option, + ) { + let (snapshot, updates) = WorldState::render_section( + section, + self.world_state_baseline.as_ref(), + self.raw_items(), + ); + let rollout_item = self.world_state_item(&snapshot); + (snapshot, updates, rollout_item) + } + pub(crate) fn render_step_world_state( &self, world_state: &WorldState, @@ -634,8 +652,11 @@ impl ContextManager { Vec, Option, ) { - let (snapshot, fragments) = + let (mut snapshot, fragments) = world_state.render_history_diff(self.world_state_baseline.as_ref(), self.raw_items()); + if let Some(previous) = &self.world_state_baseline { + snapshot.retain_input_context(previous); + } let rollout_item = self.world_state_item(&snapshot); (snapshot, fragments, rollout_item) } @@ -655,6 +676,10 @@ impl ContextManager { self.world_state_baseline = Some(snapshot); } + pub(crate) fn world_state_baseline(&self) -> Option<&WorldStateSnapshot> { + self.world_state_baseline.as_ref() + } + pub(crate) fn world_state_checkpoint(&self) -> Option { self.world_state_baseline .clone() diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index ccc4dcd750..72a0ddb03a 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -599,20 +599,16 @@ fn guardian_checkpoint_applies_additional_context_policy_after_resume(include: b thread_context_ids(), /*retention*/ None, ); - let additional_context: ResponseItem = crate::context::AdditionalContextToolOutput::new( - "browser_info", - /*name*/ None, - "captured page", - ) - .into(); - let ordinary_output = ResponseItem::FunctionCallOutput { + let output = |value: &str| ResponseItem::FunctionCallOutput { id: None, call_id: None, name: Some("browser_info".to_owned()), namespace: Some("agent".to_owned()), - output: FunctionCallOutputPayload::from_text("ordinary result".to_owned()), + output: FunctionCallOutputPayload::from_text(value.to_owned()), internal_chat_message_metadata_passthrough: None, }; + let additional_context = output("captured page"); + let ordinary_output = output("ordinary result"); history.record_annotated_items( &mut [ ResponseItemEnvelope { diff --git a/codex-rs/core/src/session/compaction_replacement.rs b/codex-rs/core/src/session/compaction_replacement.rs index de658f8e8b..c16f78c101 100644 --- a/codex-rs/core/src/session/compaction_replacement.rs +++ b/codex-rs/core/src/session/compaction_replacement.rs @@ -51,11 +51,11 @@ impl<'a> PrefixCompactionInstallation<'a> { let current = state.history.annotated_items(); let (replaced, suffix) = current.split_at(self.prefix.len); let mut initial_context = self.initial_context; - initial_context.extend( - state - .additional_context - .restore_compacted_items(replaced, &mut items), - ); + // The unchanged suffix already contains updates through this baseline. + if let Some(previous) = state.history.world_state_baseline() { + world_state_baseline = previous.clone(); + } + initial_context.extend(world_state_baseline.restore_input_context(replaced, &mut items)); if suffix.iter().any(|envelope| { crate::compact_retained_tool_outputs::is_retained_tool_output(envelope) || compact::is_real_user_or_agent_message(&envelope.item) @@ -74,10 +74,6 @@ impl<'a> PrefixCompactionInstallation<'a> { .map(ResponseItemEnvelope::new), ); items.extend_from_slice(suffix); - // The unchanged suffix already contains updates through this baseline. - if let Some(checkpoint) = state.history.world_state_checkpoint() { - world_state_baseline = WorldStateSnapshot::from(&checkpoint.state); - } // Volatile sections must refresh in the new window even if their // previous messages and comparison state survived in the suffix. for section_id in self.reset_world_state_sections { diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index 265252d476..2535514753 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -39,7 +39,6 @@ use crate::context::world_state::Placement; use crate::context::world_state::WorldState; use crate::context::world_state::WorldStateSnapshot; use crate::context::world_state::WorldStateUpdate; -use crate::context::world_state::WorldStateUpdateContent; use crate::context::world_state::split_prefix_updates; use crate::current_time::TimeProvider; use crate::environment_selection::TurnEnvironmentSnapshot; @@ -4428,6 +4427,16 @@ impl Session { .await; } + self.commit_world_state(world_state_snapshot, world_state_item) + .await; + Ok(Arc::new(world_state)) + } + + async fn commit_world_state( + &self, + world_state_snapshot: WorldStateSnapshot, + world_state_item: Option, + ) { self.state .lock() .await @@ -4438,7 +4447,6 @@ impl Session { self.persist_rollout_items(&[RolloutItem::WorldState(world_state_item)]) .await; } - Ok(Arc::new(world_state)) } /// Retains the step captured for execution. @@ -5082,9 +5090,12 @@ impl Session { matches!(&installation, CompactedHistoryInstallation::Complete(..)); let replacement = match installation { CompactedHistoryInstallation::Complete(metadata, _) => { - let context = state - .additional_context - .restore_compacted_items(state.history.annotated_items(), &mut items); + let mut world_state_baseline = world_state_baseline; + if let Some(previous) = state.history.world_state_baseline() { + world_state_baseline.retain_input_context(previous); + } + let context = world_state_baseline + .restore_input_context(state.history.annotated_items(), &mut items); if !context.is_empty() { items = compact::insert_initial_context_before_last_real_user_or_summary( items, context, @@ -5594,10 +5605,7 @@ impl Session { let updates = prefix .into_iter() .map(WorldStateUpdate::prefix_item) - .chain(items.into_iter().map(|item| WorldStateUpdate { - placement: Placement::Standalone, - content: WorldStateUpdateContent::Item(Box::new(item)), - })) + .chain(items.into_iter().map(WorldStateUpdate::item)) .collect(); (updates, snapshot) } diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 9152fa054f..d2c98e60ab 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -19,6 +19,7 @@ use crate::compact_remote_v2::run_inline_remote_auto_compact_task as run_inline_ use crate::connectors; use crate::context::ContextualUserFragment; use crate::context::UserVerificationNotice; +use crate::context::world_state::AdditionalContextState; use crate::context_manager::rejected_audio; use crate::cyber_access_program; use crate::environment_selection::TurnEnvironmentSnapshot; @@ -1178,6 +1179,15 @@ pub(crate) async fn run_hooks_and_record_input_entries( pending_input: &[InputQueueEntry], persist_context: PersistContext, ) -> CodexResult { + if let Some(pending) = turn_context.extension_data.get::() + && can_record_input(sess) + { + let sections = std::mem::take(&mut *pending.lock().await); + for section in sections { + sess.record_input_world_state(turn_context, model_info, section) + .await; + } + } // A started turn owns one initial submission; consume its context exactly once. let initial_context = turn_context .extension_data @@ -1261,30 +1271,18 @@ pub(crate) async fn record_delivered_additional_context( model_info: &ModelInfo, context: &SubmittedAdditionalContext, ) { - let items = merge_submitted_context(sess, turn_context, context).await; - if !items.is_empty() { - sess.record_annotated_conversation_items(turn_context, model_info, items) - .await; - } -} - -pub(crate) async fn merge_submitted_context( - sess: &Session, - turn_context: &TurnContext, - context: &SubmittedAdditionalContext, -) -> Vec { - let items = sess.state.lock().await.additional_context.merge( - context.0.clone(), - sess.additional_context_format(), + let section = AdditionalContextState::new( + &context.0, + sess.enabled(Feature::UntrustedAsToolOutput), &turn_context.session_telemetry, &sess.context_ids, ); - items - .into_iter() - .map(|item| sess.annotate_client_response_item(item)) - .collect() + sess.record_input_world_state(turn_context, model_info, section) + .await; } +pub(super) type PendingToolContext = tokio::sync::Mutex>; + /// Yields usable input with its context in order, then reports unsupported audio after valid siblings can be recorded. pub(crate) fn recordable_inputs<'a>( sess: &Session, diff --git a/codex-rs/core/src/session/turn_input.rs b/codex-rs/core/src/session/turn_input.rs index bf9f54d1e5..23ff903a4a 100644 --- a/codex-rs/core/src/session/turn_input.rs +++ b/codex-rs/core/src/session/turn_input.rs @@ -28,8 +28,8 @@ use crate::WithTurnExtensionData; use crate::agent::helper_daybreak::turn::HelperTurnAdmission; use crate::context::ContextualUserFragment; use crate::context::GuardianSenderMessages; +use crate::context::world_state::AdditionalContextState; use crate::state::ActiveTurn; -use crate::state::AdditionalContextFormat; use crate::state::TurnState; use crate::tasks::RegularTask; use codex_features::Feature; @@ -870,31 +870,23 @@ impl Session { else { return; }; - let input = self.state.lock().await.additional_context.extend( - BTreeMap::from([( + let section = AdditionalContextState::new( + &BTreeMap::from([( key.to_owned(), AdditionalContextEntry::new(value, AdditionalContextKind::Untrusted), )]), - self.additional_context_format(), + self.enabled(Feature::UntrustedAsToolOutput), &task.turn_context.session_telemetry, &self.context_ids, - ); - if !input.is_empty() { - self.input_queue - .extend_pending_input_for_turn_state( - &turn.turn_state, - input.into_iter().map(TurnInput::ResponseItem).collect(), - ) - .await; - } - } - - pub(super) fn additional_context_format(&self) -> AdditionalContextFormat { - if self.enabled(Feature::UntrustedAsToolOutput) { - AdditionalContextFormat::ToolOutputs - } else { - AdditionalContextFormat::Messages - } + ) + .extending(); + // Tool-produced context belongs after tool results and before the next prompt. + task.turn_context + .extension_data + .get_or_init(super::turn::PendingToolContext::default) + .lock() + .await + .push(section); } /// Called under the active-turn lock when registering a task (or a realtime transcript turn). diff --git a/codex-rs/core/src/session/world_state.rs b/codex-rs/core/src/session/world_state.rs index a41894d146..6dcbba9ede 100644 --- a/codex-rs/core/src/session/world_state.rs +++ b/codex-rs/core/src/session/world_state.rs @@ -8,6 +8,7 @@ use crate::agent::host::AgentRuntimeServices; use crate::agent::host::AgentSessionReader; use crate::connectors; use crate::context::TokenBudgetContext; +use crate::context::world_state::AdditionalContextState; use crate::context::world_state::AgentsMdState; use crate::context::world_state::AppsInstructionsState; use crate::context::world_state::CollaborationModeState; @@ -34,6 +35,7 @@ use codex_connectors::AppToolPolicyEvaluator; use codex_extension_api::WorldStateContributionInput; use codex_features::Feature; use codex_file_system::FileSystemSandboxContext; +use codex_history::ResponseItemEnvelope; use codex_mcp::CODEX_APPS_MCP_SERVER_NAME; use codex_prompts::ApprovalPromptContext; use codex_prompts::ResolvedModelMessages; @@ -41,11 +43,45 @@ use codex_prompts::render_model_instructions; use codex_protocol::error::Result as CodexResult; use codex_protocol::models::BaseInstructionsProvenance; use codex_protocol::models::ContentItemNamespace; +use codex_protocol::models::ResponseItem; +use codex_protocol::openai_models::ModelInfo; use codex_protocol::protocol::MultiAgentVersion; use codex_tools::ToolName; use codex_tools::ToolSpec; impl Session { + pub(super) async fn record_input_world_state( + &self, + turn_context: &TurnContext, + model_info: &ModelInfo, + section: AdditionalContextState, + ) { + let (snapshot, updates, patch) = self + .state + .lock() + .await + .history + .render_input_world_state(section); + let items = crate::context_manager::updates::merge_world_state_updates(updates) + .into_iter() + .map(|item| { + let mut envelope = ResponseItemEnvelope::new(item); + if matches!(envelope.item, ResponseItem::FunctionCallOutput { .. }) { + envelope + .metadata + .get_or_insert_default() + .additional_context_tool_output = true; + } + self.annotate_client_response_item(envelope) + }) + .collect::>(); + if !items.is_empty() { + self.record_annotated_conversation_items(turn_context, model_info, items) + .await; + } + self.commit_world_state(snapshot, patch).await; + } + pub(super) fn host_roster_reader( &self, turn_context: &TurnContext, diff --git a/codex-rs/core/src/state/additional_context.rs b/codex-rs/core/src/state/additional_context.rs deleted file mode 100644 index 7116c5ce8b..0000000000 --- a/codex-rs/core/src/state/additional_context.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! Deduplicates active client context and tracks its history item IDs across compaction. - -use std::collections::BTreeMap; -use std::collections::HashMap; - -use crate::context::AdditionalContextDeveloperFragment; -use crate::context::AdditionalContextToolOutput; -use crate::context::AdditionalContextUserFragment; -use crate::context::ContextualUserFragment; -use codex_context_fragments::MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS; -use codex_history::CodexHarnessMetadata; -use codex_history::ResponseItemEnvelope; -use codex_otel::ADDITIONAL_CONTEXT_COUNT_METRIC; -use codex_otel::ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS; -use codex_otel::ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC; -use codex_otel::SessionTelemetry; -use codex_protocol::ResponseItemId; -use codex_protocol::protocol::AdditionalContextEntry; -use codex_protocol::protocol::AdditionalContextKind; -use codex_thread_context_ids::ThreadContextIds; -use codex_utils_string::truncate_middle_with_token_budget; - -pub(crate) enum AdditionalContextFormat { - Messages, - ToolOutputs, -} - -#[derive(Debug, Clone, Eq)] -enum StoredAdditionalContext { - Message(AdditionalContextEntry), - ToolOutput(AdditionalContextToolOutput), -} - -impl PartialEq for StoredAdditionalContext { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Self::Message(left), Self::Message(right)) => { - left.kind == right.kind && left.value == right.value - } - (Self::ToolOutput(left), Self::ToolOutput(right)) => left == right, - (Self::Message(_), Self::ToolOutput(_)) | (Self::ToolOutput(_), Self::Message(_)) => { - false - } - } - } -} - -impl StoredAdditionalContext { - fn new(key: &str, entry: AdditionalContextEntry, format: &AdditionalContextFormat) -> Self { - match (format, entry.kind) { - (AdditionalContextFormat::ToolOutputs, AdditionalContextKind::Untrusted) => { - Self::ToolOutput(AdditionalContextToolOutput::new( - key, - entry.name, - &entry.value, - )) - } - (AdditionalContextFormat::Messages, AdditionalContextKind::Untrusted) - | (_, AdditionalContextKind::Application) => Self::Message(entry), - } - } - - fn envelope(&self, key: &str) -> ResponseItemEnvelope { - match self { - Self::ToolOutput(output) => ResponseItemEnvelope { - item: output.clone().into(), - metadata: Some(CodexHarnessMetadata { - additional_context_tool_output: true, - ..Default::default() - }), - }, - Self::Message(entry) => ResponseItemEnvelope::new(match entry.kind { - AdditionalContextKind::Untrusted => ContextualUserFragment::into( - AdditionalContextUserFragment::new(key.to_owned(), entry.value.clone()), - ), - AdditionalContextKind::Application => ContextualUserFragment::into( - AdditionalContextDeveloperFragment::new(key.to_owned(), entry.value.clone()), - ), - }), - } - } -} - -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub(crate) struct AdditionalContextStore { - values: BTreeMap, -} - -impl AdditionalContextStore { - pub(crate) fn merge( - &mut self, - values: BTreeMap, - format: AdditionalContextFormat, - telemetry: &SessionTelemetry, - context_ids: &ThreadContextIds, - ) -> Vec { - self.values.retain(|key, _| values.contains_key(key)); - self.extend(values, format, telemetry, context_ids) - } - - /// Adds a producer's updates without dropping unrelated client context. - pub(crate) fn extend( - &mut self, - values: BTreeMap, - format: AdditionalContextFormat, - telemetry: &SessionTelemetry, - context_ids: &ThreadContextIds, - ) -> Vec { - let mut fragments = Vec::new(); - for (key, entry) in values { - Self::record_metrics(&entry, telemetry); - let value = StoredAdditionalContext::new(&key, entry, &format); - if self - .values - .get(&key) - .is_some_and(|(previous, _)| previous == &value) - { - continue; - } - let mut envelope = value.envelope(&key); - let Some(prefix) = envelope.id_prefix() else { - unreachable!("additional context has an item ID") - }; - let id = context_ids.next_item(prefix); - envelope.set_id(Some(id.clone())); - self.values.insert(key, (value, id)); - fragments.push(envelope); - } - fragments - } - - /// Refresh retained active items in place and return the missing ones in history order. - /// Queued updates are absent from the replaced prefix and arrive with their input. - pub(crate) fn restore_compacted_items( - &self, - replaced: &[ResponseItemEnvelope], - retained: &mut [ResponseItemEnvelope], - ) -> Vec { - if self.values.is_empty() { - return Vec::new(); - } - let mut active: HashMap<_, _> = self.values.values().map(|(_, id)| (id, None)).collect(); - for (index, item) in retained.iter().enumerate() { - if let Some(slot) = item.id().and_then(|id| active.get_mut(id)) { - *slot = Some(index); - } - } - let mut missing = Vec::new(); - for item in replaced { - let Some(slot) = item.id().and_then(|id| active.remove(id)) else { - continue; - }; - if let Some(index) = slot { - // Generic client-message retention may have shortened the active value. - // Keep its position and checkpoint metadata, with the original bounded payload. - retained[index].item.clone_from(&item.item); - } else { - missing.push(item.clone()); - } - } - missing - } - - fn record_metrics(entry: &AdditionalContextEntry, telemetry: &SessionTelemetry) { - let (bounded_value, original_tokens) = - truncate_middle_with_token_budget(&entry.value, MAX_ADDITIONAL_CONTEXT_VALUE_TOKENS); - let kind = match entry.kind { - AdditionalContextKind::Untrusted => "untrusted", - AdditionalContextKind::Application => "application", - }; - let truncated = original_tokens.is_some().to_string(); - let mut tags = vec![("kind", kind), ("truncated", truncated.as_str())]; - if let Some(name) = entry.name.as_deref() { - tags.push(("name", name)); - } - telemetry.counter(ADDITIONAL_CONTEXT_COUNT_METRIC, /*inc*/ 1, &tags); - for (stage, bytes) in [ - ("before", entry.value.len()), - ("after", bounded_value.len()), - ] { - let mut size_tags = tags.clone(); - size_tags.push(("stage", stage)); - telemetry.histogram_with_boundaries( - ADDITIONAL_CONTEXT_VALUE_BYTES_METRIC, - i64::try_from(bytes).unwrap_or(i64::MAX), - ADDITIONAL_CONTEXT_VALUE_BYTES_BUCKETS.as_slice(), - &size_tags, - ); - } - } -} diff --git a/codex-rs/core/src/state/mod.rs b/codex-rs/core/src/state/mod.rs index e3481670b3..36e95df920 100644 --- a/codex-rs/core/src/state/mod.rs +++ b/codex-rs/core/src/state/mod.rs @@ -1,4 +1,3 @@ -mod additional_context; mod auto_compact_window; mod service; mod session; @@ -6,8 +5,6 @@ mod turn; mod turn_token_usage; pub(crate) use crate::tools::ExecutedToolCalls; -pub(crate) use additional_context::AdditionalContextFormat; -pub(crate) use additional_context::AdditionalContextStore; pub(crate) use auto_compact_window::AutoCompactWindowIds; pub(crate) use auto_compact_window::AutoCompactWindowSnapshot; pub(crate) use service::SessionServices; diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 88d54042c0..62ed444935 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -11,7 +11,6 @@ use std::collections::VecDeque; use std::sync::Arc; use std::sync::Weak; -use super::AdditionalContextStore; use super::auto_compact_window::AutoCompactWindow; use super::auto_compact_window::AutoCompactWindowIds; use super::auto_compact_window::AutoCompactWindowSnapshot; @@ -97,7 +96,6 @@ pub(crate) struct SessionState { pub(crate) latest_rate_limits: Option, pub(crate) latest_token_usage_record: Option, pub(crate) mcp_dependency_prompted: HashSet, - pub(crate) additional_context: AdditionalContextStore, /// Settings used by the latest regular user turn, used for turn-to-turn /// model/realtime handling on subsequent regular turns (including full-context /// reinjection after resume or `/compact`). @@ -161,7 +159,6 @@ impl SessionState { latest_token_usage_record: None, last_sampling_cot_removed: None, mcp_dependency_prompted: HashSet::new(), - additional_context: AdditionalContextStore::default(), previous_turn_settings: None, last_started_turn_id: None, turn_attribution: None, diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index bd8b9dc078..9ea302d35a 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -37,7 +37,7 @@ use crate::session::SamplingInterrupt; use crate::session::TurnInput; use crate::session::session::Session; use crate::session::turn::McpStartupRequirements; -use crate::session::turn::merge_submitted_context; +use crate::session::turn::record_delivered_additional_context; use crate::session::turn::run_hooks_and_record_input_entries; use crate::session::turn_context::NewTurnContextOptions; use crate::session::turn_context::TurnContext; @@ -1265,7 +1265,7 @@ impl Session { if reason == TurnAbortReason::Interrupted { // Injection acknowledges queueing. Preserve accepted agent mail before // teardown discards pending input and the host observes TurnAborted. - let mut pending_mail = Vec::new(); + let model_info = task.turn_context.capture_current_model_info(); let mut remaining_input = Vec::new(); for input in self .input_queue @@ -1278,11 +1278,20 @@ impl Session { additional_context, } if matches!(item.item, ResponseItem::AgentMessage { .. }) => { if let Some(context) = additional_context { - pending_mail.extend( - merge_submitted_context(self, &task.turn_context, &context).await, - ); + record_delivered_additional_context( + self, + &task.turn_context, + &model_info, + &context, + ) + .await; } - pending_mail.push(item); + self.record_annotated_conversation_items( + &task.turn_context, + &model_info, + vec![item], + ) + .await; } input => remaining_input.push(input), } @@ -1291,14 +1300,6 @@ impl Session { self.input_queue .extend_pending_input_for_turn_state(turn_state, remaining_input) .await; - if !pending_mail.is_empty() { - self.record_annotated_conversation_items( - &task.turn_context, - &task.turn_context.capture_current_model_info(), - pending_mail, - ) - .await; - } self.record_interrupted_turn_history( &task.turn_context, error diff --git a/codex-rs/core/tests/suite/additional_context.rs b/codex-rs/core/tests/suite/additional_context.rs index be86847741..515b33303d 100644 --- a/codex-rs/core/tests/suite/additional_context.rs +++ b/codex-rs/core/tests/suite/additional_context.rs @@ -978,6 +978,8 @@ async fn additional_context_values_are_truncated_before_model_input( assert!(body.ends_with("browser-tail")); assert!(body.contains("tokens truncated")); assert!(body.len() <= MAX_EXPECTED_EXTERNAL_CONTEXT_TEXT_BYTES); + let mut hidden_edit = long_automation_value.clone(); + hidden_edit.replace_range(20_000..20_001, "c"); let mut changed_middle = long_browser_value.clone(); changed_middle.replace_range(20_000..20_001, "c"); let changed_prefix = changed_middle.replacen("browser-head", "browser-view", 1); @@ -994,7 +996,7 @@ async fn additional_context_values_are_truncated_before_model_input( "automation_info".to_owned(), AdditionalContextEntry { name: None, - value: long_automation_value.clone(), + value: hidden_edit.clone(), kind: AdditionalContextKind::Application, }, ), @@ -1014,6 +1016,13 @@ async fn additional_context_values_are_truncated_before_model_input( }) .await; let next = next.single_request(); + assert_eq!( + next.message_input_texts("developer") + .into_iter() + .filter(|text| text.starts_with("")) + .collect::>(), + developer_texts + ); let outputs = next.inputs_of_type("function_call_output"); assert_eq!(outputs.len(), expected_count); assert_eq!(outputs[0]["output"], body); diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs index cb7923ea2d..4a5be95824 100644 --- a/codex-rs/core/tests/suite/scenarios.rs +++ b/codex-rs/core/tests/suite/scenarios.rs @@ -613,17 +613,18 @@ async fn admitted_prompt_id_reaches_responses() -> Result<()> { async fn additional_context_tool_outputs(tool_outputs: bool) -> Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; - let test = test_codex() - .with_config(move |config| { - configure_scenario_catalog(config); - config.include_environment_context = false; - if !tool_outputs { - config - .features - .disable(Feature::UntrustedAsToolOutput) - .expect("test config should allow feature update"); - } - }) + let configure = move |config: &mut Config| { + configure_scenario_catalog(config); + config.include_environment_context = false; + if !tool_outputs { + config + .features + .disable(Feature::UntrustedAsToolOutput) + .expect("test config should allow feature update"); + } + }; + let mut test = test_codex() + .with_config(configure) .build_with_auto_env(&server) .await?; let mock = mount_sse_sequence( @@ -634,7 +635,7 @@ async fn additional_context_tool_outputs(tool_outputs: bool) -> Result<()> { ) .await; - for (prompt, name, value) in [ + for (index, (prompt, name, value)) in [ ( "Summarize the selected document.", Some("browser"), @@ -655,7 +656,17 @@ async fn additional_context_tool_outputs(tool_outputs: bool) -> Result<()> { None, "The launch is on Tuesday.", ), - ] { + ] + .into_iter() + .enumerate() + { + if index == 2 { + // The unchanged submission must use the baseline restored from the rollout. + test = test_codex() + .with_config(configure) + .restart_with_auto_env(&server, &test) + .await?; + } test.codex .start_or_steer_turn( TurnInputRequest::user_input(vec![text(prompt)]).with_additional_context( diff --git a/codex-rs/ext/guardian-v3/tests/evidence.rs b/codex-rs/ext/guardian-v3/tests/evidence.rs index f4cf1c5584..246b894db6 100644 --- a/codex-rs/ext/guardian-v3/tests/evidence.rs +++ b/codex-rs/ext/guardian-v3/tests/evidence.rs @@ -1,8 +1,6 @@ //! Captured originals preserve attribution, complete contents and a fixed history boundary. -use codex_context_fragments::AdditionalContextUserFragment; use codex_context_fragments::AnnotatedContent; -use codex_context_fragments::ContextualUserFragment; use codex_context_fragments::message_from_parts; use codex_guardian_v3::EvidenceCursor; use codex_guardian_v3::OriginalEvidence; @@ -103,8 +101,13 @@ async fn captures_originals_without_generated_context_or_later_appends() -> anyh let result = ResponseItemEnvelope::new(serde_json::from_value(json!({ "type":"function_call_output","call_id":"call-1","output":"/workspace" }))?); - let generated = ResponseItemEnvelope::new(ContextualUserFragment::into( - AdditionalContextUserFragment::new("environment".into(), "Generated context".into()), + let generated = ResponseItemEnvelope::new(message_from_parts( + "user", + vec![AnnotatedContent::text( + "Generated context", + ContentItemKind("additional_content.environment".into()), + ContentItemMetadata::harness(), + )], )); let mut summary = assistant.clone(); summary.metadata = Some(CodexHarnessMetadata {