Add developer instructions for persistent mode (#41050)

## What changed

- Add bundled proactivity and follow-up guidance when `ReasoningEffort::Persistent` is selected.
- Allow model metadata to override or disable the guidance with `persistent_instructions`.
- Track the instructions as world state so effort and model changes replace or retire stale guidance without duplicating unchanged context.
- Tailor approval guidance to `send_user_message_async` availability, rebuild it for forked agents and rolled-back history, and exclude Guardian sessions.

## Testing

- Cover default, overridden, disabled, replaced, and retired instructions.
- Cover model changes, history transitions, agent forks, Guardian sessions, and asynchronous-message tool availability.

GitOrigin-RevId: 78e05d0335a70b385bd069b45edcd4ba570cef91
This commit is contained in:
brianz-openai
2026-08-27 04:58:21 +00:00
committed by copyberry
parent 72c96598c6
commit f1433fc71f
24 changed files with 565 additions and 9 deletions
+6 -2
View File
@@ -9,6 +9,7 @@ use crate::context::DeveloperInstructions;
use crate::context::ManagedDeveloperInstructions;
use crate::context::MultiAgentModeInstructions;
use crate::context::MultiAgentRoleInstructions;
use crate::context::world_state::PersistentModeState;
use crate::session::multi_agents::resolve_usage_hints;
use crate::tools::handlers::multi_agents_common::build_agent_resume_config;
use codex_context_fragments::set_annotated_content;
@@ -928,9 +929,12 @@ impl AgentControl {
let ContentItem::InputText { text } = content_item.content_mut() else {
return true;
};
if ManagedDeveloperInstructions::matches_text(text) {
if ManagedDeveloperInstructions::matches_text(text)
|| PersistentModeState::matches_text(text)
{
// If the child will rebuild its initial context, drop the inherited
// managed instructions; startup will add the current requirements once.
// instructions; startup will add the current requirements and effort
// instructions once.
return preserve_reference_context_item;
}
let (
+22 -2
View File
@@ -1461,6 +1461,8 @@ async fn spawn_agent_numeric_fork_from_compacted_paginated_parent_clamps_to_prov
#[tokio::test]
async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
let managed_fragment = "<managed_developer_instructions>\nParent developer instructions.\n</managed_developer_instructions>";
let persistent_fragment =
"<persistent_mode>\nParent developer instructions.\n</persistent_mode>";
let harness = AgentControlHarness::new().await;
let mut parent_config = harness.config.clone();
let _ = parent_config.features.enable(Feature::MultiAgentV2);
@@ -1558,6 +1560,9 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
ContentItem::InputText {
text: managed_fragment.to_string(),
},
ContentItem::InputText {
text: persistent_fragment.to_string(),
},
],
phase: None,
internal_chat_message_metadata_passthrough: Some(
@@ -1567,6 +1572,7 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
ContentItemKind("multi_agent.mode_instructions".to_string()),
ContentItemKind("generic.developer_policy".to_string()),
ContentItemKind("managed_config.developer_instructions".to_string()),
ContentItemKind("persistent_mode.instructions".to_string()),
]),
..Default::default()
},
@@ -1677,6 +1683,9 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
ContentItem::InputText {
text: managed_fragment.to_string(),
},
ContentItem::InputText {
text: persistent_fragment.to_string(),
},
],
phase: None,
internal_chat_message_metadata_passthrough: Some(
@@ -1685,6 +1694,7 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
ContentItemKind("generic.developer_instructions".to_string()),
ContentItemKind("generic.developer_policy".to_string()),
ContentItemKind("managed_config.developer_instructions".to_string()),
ContentItemKind("persistent_mode.instructions".to_string()),
]),
..Default::default()
},
@@ -1769,8 +1779,9 @@ async fn spawn_agent_can_fork_parent_thread_history_with_sanitized_items() {
"empty child developer instructions should remove parent developer instructions"
);
assert!(
history_contains_text(no_hint_history.raw_items(), managed_fragment),
"clearing child instructions must preserve an overlapping managed policy"
history_contains_text(no_hint_history.raw_items(), managed_fragment)
&& history_contains_text(no_hint_history.raw_items(), persistent_fragment),
"clearing child instructions must preserve overlapping managed and persistent instructions"
);
assert!(
history_contains_text(
@@ -2660,6 +2671,8 @@ async fn spawn_agent_fork_last_n_turns_drops_parent_startup_prefix_when_under_li
#[tokio::test]
async fn spawn_agent_fork_last_n_turns_strips_parent_usage_hints() {
let persistent_fragment =
"<persistent_mode>\nParent persistent instructions.\n</persistent_mode>";
let harness = AgentControlHarness::new().await;
let mut parent_config = harness.config.clone();
let _ = parent_config.features.enable(Feature::MultiAgentV2);
@@ -2710,6 +2723,9 @@ async fn spawn_agent_fork_last_n_turns_strips_parent_usage_hints() {
ContentItem::InputText {
text: "Preserved bounded developer context.".to_string(),
},
ContentItem::InputText {
text: persistent_fragment.to_string(),
},
],
phase: None,
internal_chat_message_metadata_passthrough: None,
@@ -2772,6 +2788,10 @@ async fn spawn_agent_fork_last_n_turns_strips_parent_usage_hints() {
!history_contains_text(history.raw_items(), "Child developer instructions."),
"bounded fork should not inject child instructions before its canonical context rebuild"
);
assert!(
!history_contains_text(history.raw_items(), persistent_fragment),
"bounded fork should remove persistent instructions before rebuilding context for the child's effort"
);
assert!(
history_contains_text(history.raw_items(), "Preserved bounded developer context."),
"bounded fork should preserve unrelated developer fragments"
@@ -10,6 +10,7 @@ mod model;
mod multi_agent_mode;
mod multi_agent_usage_hint;
mod permissions;
mod persistent_mode;
mod personality;
mod plugins_instructions;
mod realtime;
@@ -49,6 +50,7 @@ pub(crate) use model::ModelInstructionsState;
pub(crate) use multi_agent_mode::MultiAgentModeState;
pub(crate) use multi_agent_usage_hint::MultiAgentUsageHintState;
pub(crate) use permissions::PermissionsState;
pub(crate) use persistent_mode::PersistentModeState;
pub(crate) use personality::PersonalityState;
pub(crate) use plugins_instructions::PluginsInstructionsState;
pub(crate) use realtime::RealtimeState;
@@ -0,0 +1,124 @@
//! Keeps persistent-mode developer instructions current without repeating unchanged context.
//! Mode changes retire prior instructions; missing catalog values use the bundled default.
use super::PreviousSectionState;
use super::WorldStateHash;
use super::WorldStateSection;
use crate::context::ContextualUserFragment;
use codex_protocol::models::ContentItemKind;
use codex_protocol::openai_models::ReasoningEffort;
use serde::Deserialize;
use serde::Serialize;
const DEFAULT_INSTRUCTIONS: &str = include_str!("../../../templates/persistent_mode.md");
const REPLACEMENT_NOTICE: &str = "These persistent-mode instructions replace all previously provided persistent-mode instructions.";
const REMOVAL_NOTICE: &str =
"The previously provided persistent-mode instructions no longer apply.";
#[derive(Clone, Debug)]
pub(crate) struct PersistentModeState {
instructions: String,
}
impl ContextualUserFragment for PersistentModeState {
fn content_kind(&self) -> ContentItemKind {
ContentItemKind("persistent_mode.instructions".to_string())
}
fn role(&self) -> &'static str {
"developer"
}
fn markers(&self) -> (&'static str, &'static str) {
Self::type_markers()
}
fn type_markers() -> (&'static str, &'static str) {
("<persistent_mode>", "</persistent_mode>")
}
fn body(&self) -> String {
format!("\n{}\n", self.instructions)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct PersistentModeSnapshot {
// Keep an object: JSON null would delete the section and lose its disabled state.
instructions: Option<WorldStateHash>,
}
impl PersistentModeState {
pub(crate) fn new(
reasoning_effort: Option<&ReasoningEffort>,
catalog_instructions: Option<&str>,
send_user_message_async_available: bool,
) -> Self {
let instructions = if reasoning_effort == Some(&ReasoningEffort::Persistent) {
catalog_instructions
.unwrap_or(DEFAULT_INSTRUCTIONS)
.trim()
.replace(
"{{ approval_request_channel }}",
if send_user_message_async_available {
" via functions.send_user_message_async"
} else {
""
},
)
} else {
String::new()
};
Self { instructions }
}
}
impl WorldStateSection for PersistentModeState {
const ID: &'static str = "persistent_mode";
type Snapshot = PersistentModeSnapshot;
fn snapshot(&self) -> Self::Snapshot {
PersistentModeSnapshot {
instructions: (!self.instructions.is_empty())
.then(|| WorldStateHash::from_fragment(self)),
}
}
fn matches_legacy_fragment(role: &str, text: &str) -> bool {
role == "developer" && Self::matches_text(text)
}
fn has_retained_fragment_matcher() -> bool {
true
}
fn matches_retained_fragment(role: &str, text: &str) -> bool {
Self::matches_legacy_fragment(role, text)
}
fn render_diff(
&self,
previous: PreviousSectionState<'_, Self::Snapshot>,
) -> Option<Box<dyn ContextualUserFragment>> {
if matches!(previous, PreviousSectionState::Known(previous) if previous == &self.snapshot())
{
return None;
}
let previous_had_instructions = match previous {
PreviousSectionState::Absent => false,
PreviousSectionState::Unknown => true,
PreviousSectionState::Known(previous) => previous.instructions.is_some(),
};
let instructions = match (self.instructions.as_str(), previous_had_instructions) {
("", false) => return None,
("", true) => REMOVAL_NOTICE.to_string(),
(instructions, true) => format!("{REPLACEMENT_NOTICE}\n\n{instructions}"),
(instructions, false) => instructions.to_string(),
};
Some(Box::new(Self { instructions }))
}
}
#[cfg(test)]
#[path = "persistent_mode_tests.rs"]
mod tests;
@@ -0,0 +1,90 @@
//! Covers effort selection, catalog overrides, and persistent-context transitions.
use super::*;
use crate::context::world_state::WorldState;
use pretty_assertions::assert_eq;
#[test]
fn persistent_instructions_follow_effort_and_catalog_updates_without_duplicates() {
let mut history = Vec::new();
let mut previous = None;
let persistent = Some(ReasoningEffort::Persistent);
let medium = Some(ReasoningEffort::Medium);
let replacement = format!("{REPLACEMENT_NOTICE}\n\nupdated instructions");
for (effort, instructions, expected) in [
(None, None, None),
(
persistent.clone(),
Some("instructions"),
Some("instructions"),
),
(persistent.clone(), Some("instructions"), None),
(
persistent.clone(),
Some("updated instructions"),
Some(replacement.as_str()),
),
(persistent.clone(), Some(""), Some(REMOVAL_NOTICE)),
(persistent.clone(), Some(""), None),
(persistent, Some("instructions"), Some("instructions")),
(medium.clone(), None, Some(REMOVAL_NOTICE)),
(medium, None, None),
] {
let mut world_state = WorldState::default();
world_state.add_section(PersistentModeState::new(
effort.as_ref(),
instructions,
/*send_user_message_async_available*/ false,
));
let updates = world_state
.render_history_diff(previous.as_ref(), &history)
.into_iter()
.map(ContextualUserFragment::into_boxed_response_item)
.collect::<Vec<_>>();
assert_eq!(
updates,
expected
.map(|instructions| {
ContextualUserFragment::into(PersistentModeState {
instructions: instructions.to_string(),
})
})
.into_iter()
.collect::<Vec<_>>()
);
history.extend(updates);
previous = Some(world_state.snapshot());
}
}
#[test]
fn retained_persistent_instructions_are_replaced_or_retired_without_a_snapshot() {
let retained = ContextualUserFragment::into(PersistentModeState {
instructions: "previous instructions".to_string(),
});
for (effort, expected) in [
(
ReasoningEffort::Persistent,
format!("{REPLACEMENT_NOTICE}\n\ncurrent instructions"),
),
(ReasoningEffort::Medium, REMOVAL_NOTICE.to_string()),
] {
let mut world_state = WorldState::default();
world_state.add_section(PersistentModeState::new(
Some(&effort),
Some("current instructions"),
/*send_user_message_async_available*/ false,
));
assert_eq!(
world_state
.render_history_diff(/*previous*/ None, std::slice::from_ref(&retained))
.into_iter()
.map(ContextualUserFragment::into_boxed_response_item)
.collect::<Vec<_>>(),
vec![ContextualUserFragment::into(PersistentModeState {
instructions: expected,
})]
);
}
}
@@ -1,5 +1,6 @@
use crate::context::ContextualUserFragment;
use crate::context::ModelSwitchInstructions;
use crate::context::world_state::PersistentModeState;
use crate::context::world_state::WorldState;
use crate::context::world_state::WorldStateSnapshot;
use crate::context_manager::normalize;
@@ -356,10 +357,12 @@ impl ContextManager {
return false;
};
content.retain(|content| {
// Rebuild these from the next step's model and effort after rollback.
!matches!(
content.content(),
ContentItem::InputText { text }
if ModelSwitchInstructions::matches_text(text)
|| PersistentModeState::matches_text(text)
)
});
!content.is_empty() && set_annotated_content(&mut item.item, content).is_some()
@@ -1265,6 +1265,10 @@ fn drop_last_n_user_turns_preserves_annotations_for_surviving_developer_fragment
text: "persistent developer instructions".to_string(),
},
ContentItem::InputText { text: model_switch },
ContentItem::InputText {
text: "<persistent_mode>\nFollow up on the completed task.\n</persistent_mode>"
.to_string(),
},
ContentItem::InputText {
text: "persistent environment instructions".to_string(),
},
@@ -1275,6 +1279,7 @@ fn drop_last_n_user_turns_preserves_annotations_for_surviving_developer_fragment
content_item_kinds: Some(vec![
ContentItemKind("generic.developer_instructions".to_string()),
ContentItemKind("model_switch.instructions".to_string()),
ContentItemKind("persistent_mode.instructions".to_string()),
ContentItemKind("environments.instructions".to_string()),
]),
..Default::default()
+1
View File
@@ -42,6 +42,7 @@ const CONTEXTUAL_DEVELOPER_PREFIXES: &[&str] = &[
APPROVED_COMMAND_PREFIX_SAVED_MESSAGE_PREFIX,
"<model_switch>",
"<managed_developer_instructions>",
"<persistent_mode>",
APPS_INSTRUCTIONS_OPEN_TAG,
COLLABORATION_MODE_OPEN_TAG,
"<multi_agent_role>",
@@ -1907,6 +1907,7 @@ mod tests {
let catalog_template = "Catalog Guardian template:\n{{ tenant_policy_config }}";
parent_config.guardian_policy_config = Some(managed_policy.to_string());
let model_messages = ModelMessages {
persistent_instructions: None,
instructions_template: None,
instructions_variables: None,
approvals: None,
@@ -1945,6 +1946,7 @@ mod tests {
async fn guardian_review_session_config_preserves_explicit_empty_catalog_policy() {
let parent_config = crate::config::test_config().await;
let model_messages = ModelMessages {
persistent_instructions: None,
instructions_template: None,
instructions_variables: None,
approvals: None,
@@ -1991,6 +1993,7 @@ mod tests {
let parent_config = crate::config::test_config().await;
let catalog_policy = "Use the catalog Guardian policy.";
let model_messages = ModelMessages {
persistent_instructions: None,
instructions_template: None,
instructions_variables: None,
approvals: None,
@@ -1051,6 +1051,12 @@ async fn guardian_allows_unified_exec_additional_permissions_requests_past_polic
#[tokio::test]
async fn process_compacted_history_preserves_separate_guardian_developer_message() {
let (session, mut turn_context) = make_session_and_context().await;
update_turn_settings_for_test(&mut turn_context, |settings| {
update_selected_settings_for_test(settings, |selected| {
selected.collaboration_mode.settings.reasoning_effort =
Some(ReasoningEffortConfig::Persistent);
});
});
let guardian_policy = "guardian policy".to_string();
let guardian_source =
SessionSource::SubAgent(SubAgentSource::Other(GUARDIAN_REVIEWER_NAME.to_string()));
@@ -1121,6 +1127,12 @@ async fn process_compacted_history_preserves_separate_guardian_developer_message
.iter()
.any(|(message, _)| message.contains("stale developer message"))
);
assert!(
!developer_messages
.iter()
.any(|(message, _)| message.contains("<persistent_mode>")),
"guardian context must not inherit persistent-mode proactivity"
);
assert!(developer_messages.len() >= 2);
assert_eq!(
developer_messages.last(),
+21
View File
@@ -17,6 +17,7 @@ use crate::context::world_state::ModelInstructionsState;
use crate::context::world_state::MultiAgentModeState;
use crate::context::world_state::MultiAgentUsageHintState;
use crate::context::world_state::PermissionsState;
use crate::context::world_state::PersistentModeState;
use crate::context::world_state::PersonalityState;
use crate::context::world_state::PluginsInstructionsState;
use crate::context::world_state::RealtimeState;
@@ -189,6 +190,26 @@ impl Session {
.and_then(|messages| messages.collaboration_modes.as_ref()),
));
}
if !crate::guardian::is_basic_session_source(&turn_context.session_source) {
let send_user_message_async_available =
!turn_context.session_source.is_non_root_agent()
&& step_context
.settings
.model_info
.experimental_supported_tools
.iter()
.any(|tool| tool == "send_user_message_async");
world_state.add_section(PersistentModeState::new(
step_context.settings.effective_reasoning_effort().as_ref(),
step_context
.settings
.model_info
.model_messages
.as_ref()
.and_then(|messages| messages.persistent_instructions.as_deref()),
send_user_message_async_available,
));
}
if turn_context.config.include_environment_context {
let current_date = self
.services