Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,233 @@
//! Holds the current speculative request, polled at checkpoints or awaited when compaction is due.
//! Discarded requests still charge completed usage; session shutdown cancels remaining network work.
//! Snapshot capture and launch registration hold session state; prompt preparation does not.
use akode_login::AuthOwner;
use std::sync::Arc;
use crate::compact_remote_v2::BackgroundCompactionCandidate;
use crate::compact_remote_v2::capture_background_input;
use crate::compact_remote_v2::run_background_compaction;
use crate::compaction_metadata::CompactionPhase;
use crate::context::world_state::WorldState;
use crate::session::context_window::ContextWindowTokenStatus;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use crate::session::turn_context::TurnContext;
use akode_features::Feature;
use akode_model_provider::RemoteCompactionSupport;
use akode_otel::auth_storage::AuthStorageOriginator;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tracing::debug;
#[derive(PartialEq, Eq)]
struct CompactionAttempt {
history_version: u64,
model_slug: String,
compaction_hash: Option<String>,
auth_owner: Option<AuthOwner>,
}
#[derive(Default)]
pub(crate) struct AsyncCompactionState {
last_attempt: Option<CompactionAttempt>,
// Keep prepared request state off the turn stack while checkpoints await adoption.
result: Option<oneshot::Receiver<Box<BackgroundCompactionCandidate>>>,
tasks: TaskTracker,
shutdown_cancellation: CancellationToken,
}
pub(super) fn enabled(turn_context: &TurnContext) -> bool {
let features = &turn_context.config.features;
features.enabled(Feature::AsyncCompaction)
&& !(features.enabled(Feature::AsyncCompactionRootOnly)
&& turn_context.session_source.is_non_root_agent())
&& !features.enabled(Feature::TokenBudget)
&& matches!(
turn_context.provider.capabilities().remote_compaction,
RemoteCompactionSupport::V2
)
}
pub(super) async fn maybe_start(
sess: &Arc<Session>,
step_context: &Arc<StepContext>,
world_state: &Arc<WorldState>,
phase: CompactionPhase,
turn_cancellation: &CancellationToken,
token_status: &ContextWindowTokenStatus,
(turn_state, auth_owner): (Option<String>, Option<AuthOwner>),
) {
let turn_context = &step_context.turn;
// Let the foreground establish the backend's model pin before starting a parallel request.
if matches!(phase, CompactionPhase::PreTurn) && turn_state.is_none() {
return;
}
if !enabled(turn_context)
|| token_status.token_limit_reached
|| (matches!(phase, CompactionPhase::PostTurn)
&& token_status.turn_end_compaction_threshold_reached)
|| step_context
.settings
.model_info
.resolved_context_window()
.is_none_or(|limit| {
i128::from(token_status.active_context_tokens) * 100
< i128::from(limit)
* i128::from(turn_context.config.async_compaction_threshold_percent)
})
{
return;
}
let base_instructions = sess.get_prompt_base_instructions().await;
let (prepared_input, tasks, shutdown_cancellation, launch, send) = {
let mut state = sess.state.lock().await;
let model_info = &step_context.settings.model_info;
let attempt = CompactionAttempt {
history_version: state.history.history_version(),
model_slug: model_info.slug.clone(),
compaction_hash: model_info.comp_hash.clone(),
auth_owner: auth_owner.clone(),
};
// Stop blocks new launches; already-running compaction remains session-owned.
if turn_cancellation.is_cancelled()
|| state.shutting_down
|| state.async_compaction.last_attempt.as_ref() == Some(&attempt)
|| state.history.annotated_items().is_empty()
|| sess.services.model_client.auth_owner() != auth_owner
{
return;
}
// Capture the arguments now; the async preparation body runs after the lock is released.
let prepared_input = capture_background_input(
sess,
step_context,
state.history.clone(),
base_instructions,
turn_state,
auth_owner,
sess.current_window_from_state(&state),
);
let tasks = state.async_compaction.tasks.clone();
let shutdown_cancellation = state.async_compaction.shutdown_cancellation.clone();
// Register before unlocking so shutdown cannot finish between capture and spawning.
let launch = tasks.token();
state.async_compaction.last_attempt = Some(attempt);
let (send, result) = oneshot::channel();
state.async_compaction.result = Some(result);
(prepared_input, tasks, shutdown_cancellation, launch, send)
};
// Prepare outside the lock on the foreground task so its step cannot advance before tool
// attribution is captured. Keep normalization before attribution capture.
let prepared_input = prepared_input.await;
let task_session = Arc::clone(sess);
let task_step = Arc::clone(step_context);
let cutoff_world_state = Arc::clone(world_state);
let storage_originator = AuthStorageOriginator::from_client_name(&turn_context.originator);
let task = async move {
match run_background_compaction(
&task_session,
task_step,
cutoff_world_state,
phase,
prepared_input,
&shutdown_cancellation,
)
.await
{
Ok(candidate) => {
let _ = send.send(Box::new(candidate));
}
Err(error) => {
debug!(%error, "discarding unsuccessful background compaction");
}
}
};
tasks.spawn(storage_originator.scope(task));
drop(launch);
}
pub(super) async fn take_ready(
sess: &Session,
turn_context: &TurnContext,
) -> Option<Box<BackgroundCompactionCandidate>> {
if !enabled(turn_context) {
return None;
}
let mut state = sess.state.lock().await;
let mut result = state.async_compaction.result.take()?;
let candidate = match result.try_recv() {
Ok(candidate) => candidate,
Err(oneshot::error::TryRecvError::Empty) => {
state.async_compaction.result = Some(result);
return None;
}
// try_recv consumes a closed receiver; awaiting it later would panic.
Err(oneshot::error::TryRecvError::Closed) => return None,
};
(candidate.prefix.generation == state.history.history_version()).then_some(candidate)
}
pub(crate) async fn wait_for_pending(
sess: &Session,
step_context: &StepContext,
) -> Option<Box<BackgroundCompactionCandidate>> {
if !enabled(&step_context.turn) {
return None;
}
let result = {
let mut state = sess.state.lock().await;
let result = state.async_compaction.result.take()?;
let model = &step_context.settings.model_info;
let attempt = state.async_compaction.last_attempt.as_ref()?;
if attempt.history_version != state.history.history_version()
|| attempt.model_slug != model.slug
|| attempt.compaction_hash != model.comp_hash
|| attempt.auth_owner != sess.services.model_client.auth_owner()
{
return None;
}
result
};
// Release session state while the request finishes and charges its usage.
result.await.ok()
}
pub(crate) async fn shutdown_cancellation(sess: &Session) -> CancellationToken {
sess.state
.lock()
.await
.async_compaction
.shutdown_cancellation
.clone()
}
pub(super) async fn shutdown(sess: &Session) {
let tasks = {
let mut state = sess.state.lock().await;
let async_compaction = &mut state.async_compaction;
async_compaction.result = None;
async_compaction.tasks.close();
async_compaction.shutdown_cancellation.cancel();
async_compaction.tasks.clone()
};
// Drain completed usage charging before shutdown finishes.
tasks.wait().await;
}
/// Test barrier: callers must gate foreground work so it cannot launch another attempt.
pub(crate) async fn wait_for_background_compaction_for_test(sess: &Session) {
let tasks = sess.state.lock().await.async_compaction.tasks.clone();
// Closing only enables waiting; it neither cancels tasks nor prevents future launches.
tasks.close();
tasks.wait().await;
}
#[cfg(test)]
#[path = "async_compaction_tests.rs"]
mod tests;

View File

@@ -0,0 +1,242 @@
//! Background compaction eligibility and cancellation.
use super::*;
use crate::compaction_metadata::CompactionReason;
use crate::compaction_metadata::CompactionTrigger;
use akode_login::CodexAuth;
use akode_protocol::models::AudioReference;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::InputModality;
use akode_protocol::protocol::InternalSessionSource;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use akode_protocol::protocol::TokenUsage;
use core_test_support::responses;
use pretty_assertions::assert_eq;
#[test_case::test_case(CompactionTrigger::Auto; "optional ready adoption")]
#[test_case::test_case(CompactionTrigger::Manual; "manual ready reuse")]
#[tokio::test]
async fn cancelled_turn_skips_launch_but_preserves_existing_work(trigger: CompactionTrigger) {
let phase = CompactionPhase::MidTurn;
let server = responses::start_mock_server().await;
let mut provider = crate::config::test_model_provider_info_with_base_url(None).clone();
provider.base_url = Some(format!("{}/v1", server.uri()));
provider.supports_websockets = false;
let server_uri = server.uri();
let (sess, mut turn, _events) =
crate::session::tests::make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
move |config| {
config.model = Some("gpt-5.2".to_string());
config.model_context_window = Some(100_000);
config.model_auto_compact_token_limit = Some(90_000);
config.async_compaction_threshold_percent = 50;
config.model_provider = provider;
config.chatgpt_base_url = server_uri;
config.features.enable(Feature::AsyncCompaction).unwrap();
config.features.disable(Feature::TokenBudget).unwrap();
},
)
.await;
crate::session::tests::update_turn_settings_for_test(
Arc::get_mut(&mut turn).expect("unshared turn context"),
|settings| {
Arc::make_mut(&mut settings.model_info)
.input_modalities
.push(InputModality::Audio);
},
);
let request = responses::mount_response_sequence(
&server,
vec![
wiremock::ResponseTemplate::new(404).set_body_json(serde_json::json!({
"error": {"message": "Invalid input: Unknown `file_id` in input content."}
})),
responses::sse_response(responses::sse(vec![
serde_json::json!({"type":"response.output_item.done", "item": {
"type":"compaction", "encrypted_content":"prepared-summary"
}}),
responses::ev_completed("prepared"),
])),
],
)
.await;
let turn_cancellation = CancellationToken::new();
let step = sess
.capture_step_context(Arc::clone(&turn), &turn_cancellation)
.await
.expect("capture step");
let rejected_file_id = "file_rejected_background_compaction";
let original = ResponseItem::Message {
encrypted_content: None,
status: None,
id: None,
role: "user".to_string(),
content: vec![
ContentItem::InputText {
text: "original turn".to_string(),
},
ContentItem::InputAudio {
audio: AudioReference::File {
file_id: rejected_file_id.to_string(),
},
},
ContentItem::InputAudio {
audio: AudioReference::File {
file_id: "file_expired_since_last_turn".to_string(),
},
},
],
phase: None,
internal_chat_message_metadata_passthrough: None,
};
sess.replace_history(vec![original], /*reference_context_item*/ None)
.await;
sess.state
.lock()
.await
.history
.restore_rejected_audio_file_ids(std::collections::BTreeSet::from([
rejected_file_id.to_string()
]));
sess.update_token_usage_info(
&turn,
Some(&TokenUsage {
input_tokens: 60_000,
total_tokens: 60_000,
..Default::default()
}),
/*includes_reasoning*/ false,
)
.await
.expect("record usage");
let status = super::super::context_window::context_window_token_status(&sess, &turn).await;
assert!(!status.token_limit_reached);
let world_state = Arc::new(WorldState::default());
let cancelled = CancellationToken::new();
cancelled.cancel();
let auth = sess.services.model_client.auth_owner();
maybe_start(
&sess,
&step,
&world_state,
phase,
&cancelled,
&status,
(Some("routing".to_string()), auth.clone()),
)
.await;
assert!(
sess.state
.lock()
.await
.async_compaction
.last_attempt
.is_none()
);
assert_eq!(request.requests().len(), 0);
// The same eligible work can launch on a live turn, then outlive its cancellation.
maybe_start(
&sess,
&step,
&world_state,
phase,
&turn_cancellation,
&status,
(Some("routing".to_string()), auth.clone()),
)
.await;
turn_cancellation.cancel();
maybe_start(
&sess,
&step,
&world_state,
phase,
&turn_cancellation,
&status,
(Some("routing".to_string()), auth),
)
.await;
// Wait for client publication before exercising either ready-result consumer.
wait_for_background_compaction_for_test(&sess).await;
assert_eq!(request.requests().len(), 2, "background retry completed");
let next_step = sess
.capture_step_context(Arc::clone(&turn), &CancellationToken::new())
.await
.expect("capture next step");
match trigger {
CompactionTrigger::Auto => {
let candidate = take_ready(&sess, &turn).await.expect("published candidate");
let mut client_session = sess.services.model_client.new_session();
assert!(
crate::compact_remote_v2::run_inline_remote_auto_compact_task(
Arc::clone(&sess),
Arc::clone(&next_step),
next_step,
&mut client_session,
world_state,
CompactionReason::ContextLimit,
phase,
Some(candidate),
crate::compact_remote_v2::CompactionFallback::Skip,
)
.await
.expect("optional adoption")
);
}
CompactionTrigger::Manual => {
crate::compact_remote_v2::run_remote_compact_task(
Arc::clone(&sess),
next_step,
world_state,
)
.await
.expect("manual compaction reuses the completed request");
}
}
let history = sess.clone_history().await;
let summaries = history
.raw_items()
.filter_map(|item| match item {
ResponseItem::Compaction {
encrypted_content, ..
} => Some(encrypted_content.as_str()),
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(summaries, ["prepared-summary"]);
let requests = request.requests();
assert_eq!(requests.len(), 2);
for (index, request) in requests.into_iter().enumerate() {
let body = request.body_json().to_string();
assert!(body.contains("original turn"));
assert!(!body.contains(rejected_file_id));
assert_eq!(body.contains("file_expired_since_last_turn"), index == 0);
}
shutdown(&sess).await;
}
#[test_case::test_case(false; "all agents")]
#[test_case::test_case(true; "root only")]
#[tokio::test]
async fn root_only_controls_child_eligibility(root_only: bool) {
let (_, mut turn) = crate::session::tests::make_session_and_context().await;
let features = &mut Arc::make_mut(&mut turn.config).features;
features.enable(Feature::AsyncCompaction).unwrap();
features
.set_enabled(Feature::AsyncCompactionRootOnly, root_only)
.unwrap();
assert!(enabled(&turn));
for source in [
SessionSource::SubAgent(SubAgentSource::Review),
SessionSource::Internal(InternalSessionSource::Guardian),
] {
turn.session_source = source;
assert_eq!(enabled(&turn), !root_only);
}
}

View File

@@ -0,0 +1,27 @@
use akode_features::Feature;
use akode_features::Features;
use akode_protocol::openai_models::CatalogModel;
use akode_protocol::openai_models::ModelOrigin;
pub(super) fn unsupported_code_mode_warning(
model_info: &CatalogModel,
features: &Features,
) -> Option<String> {
let code_mode_enabled =
features.enabled(Feature::CodeMode) || features.enabled(Feature::CodeModeOnly);
if !code_mode_enabled
|| model_info.tool_mode.is_some()
|| model_info.origin == ModelOrigin::Synthetic
{
return None;
}
let model = &model_info.slug;
Some(format!(
"Code Mode is enabled in configuration, but model `{model}` does not advertise Code Mode support. This may degrade model performance. Disable `features.code_mode` and `features.code_mode_only`, or select a model whose metadata enables Code Mode."
))
}
#[cfg(test)]
#[path = "code_mode_warning_tests.rs"]
mod tests;

View File

@@ -0,0 +1,75 @@
use super::unsupported_code_mode_warning;
use akode_features::Feature;
use akode_features::Features;
use akode_models_manager::model_info::model_info_from_slug;
use akode_protocol::openai_models::CatalogModel;
use akode_protocol::openai_models::ModelOrigin;
use akode_protocol::openai_models::ToolMode;
use pretty_assertions::assert_eq;
const MODEL_SLUG: &str = "test-model";
fn known_model_info() -> CatalogModel {
CatalogModel {
model: model_info_from_slug(MODEL_SLUG).into(),
origin: ModelOrigin::Provider,
}
}
#[test]
fn warns_when_code_mode_is_enabled_without_model_selector() {
let mut features = Features::with_defaults();
features.enable(Feature::CodeMode);
assert_eq!(
unsupported_code_mode_warning(&known_model_info(), &features),
Some(format!(
"Code Mode is enabled in configuration, but model `{MODEL_SLUG}` does not advertise Code Mode support. This may degrade model performance. Disable `features.code_mode` and `features.code_mode_only`, or select a model whose metadata enables Code Mode."
))
);
}
#[test]
fn warns_when_code_mode_only_is_enabled_without_model_selector() {
let mut features = Features::with_defaults();
features.enable(Feature::CodeModeOnly);
assert!(unsupported_code_mode_warning(&known_model_info(), &features).is_some());
}
#[test]
fn does_not_warn_when_code_mode_is_disabled() {
assert_eq!(
unsupported_code_mode_warning(&known_model_info(), &Features::with_defaults()),
None
);
}
#[test]
fn does_not_warn_when_model_has_tool_mode_selector() {
let mut features = Features::with_defaults();
features.enable(Feature::CodeModeOnly);
for tool_mode in [ToolMode::Direct, ToolMode::CodeMode, ToolMode::CodeModeOnly] {
let mut model_info = known_model_info();
model_info.tool_mode = Some(tool_mode);
assert_eq!(unsupported_code_mode_warning(&model_info, &features), None);
}
}
#[test]
fn fallback_metadata_only_uses_existing_warning() {
let mut features = Features::with_defaults();
features.enable(Feature::CodeMode);
assert_eq!(
unsupported_code_mode_warning(
&CatalogModel {
model: model_info_from_slug(MODEL_SLUG).into(),
origin: ModelOrigin::Synthetic
},
&features
),
None
);
}

View File

@@ -0,0 +1,95 @@
//! Checks reconstructed history against live compaction and persisted replacement items.
#![cfg(test)]
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn reconstruct_history_matches_live_compactions() {
let (session, turn_context) = make_session_and_context().await;
let (rollout_items, expected) = sample_rollout(&session, &turn_context).await;
let reconstruction_turn = session.new_default_turn().await;
let reconstructed = session
.reconstruct_history_from_rollout(reconstruction_turn.as_ref(), &rollout_items)
.await;
assert_eq!(expected, raw_envelopes(&reconstructed.history));
assert_eq!(2, reconstructed.window_number);
assert_eq!(
reconstructed
.window_id
.map(|window_id| Uuid::parse_str(&window_id.to_string())
.unwrap()
.get_version_num()),
Some(7)
);
}
#[tokio::test]
async fn reconstruct_history_uses_replacement_history_verbatim() {
let (session, turn_context) = make_session_and_context().await;
let summary_item = ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: "summary".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: Some(InternalChatMessageMetadataPassthrough {
turn_id: Some("compact-turn".to_string()),
..Default::default()
}),
};
let mut replacement_history = vec![
ResponseItemEnvelope {
item: summary_item.clone(),
metadata: Some(CodexHarnessMetadata::default()),
},
ResponseItemEnvelope::new(ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "developer".to_string(),
content: vec![ContentItem::InputText {
text: "stale developer instructions".to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}),
];
let first_window_id = ContextWindowId::new_uuid_v7();
let previous_window_id = ContextWindowId::new_uuid_v7();
let window_id = ContextWindowId::new_uuid_v7();
let rollout_items = vec![RolloutItem::Compacted(Box::new(CompactedItem {
message: String::new(),
replacement_history: Some(replacement_history.clone()),
retained_context: None,
guardian_history: None,
mcp_resource_origins: None,
window_number: Some(42),
first_window_id: Some(first_window_id.to_string()),
previous_window_id: Some(previous_window_id.to_string()),
window_id: Some(window_id.to_string()),
compaction_response_id: None,
latest_token_usage_record: None,
resume_metadata: None,
}))];
let reconstructed = session
.reconstruct_history_from_rollout(&turn_context, &rollout_items)
.await;
for (index, envelope) in replacement_history.iter_mut().enumerate() {
let metadata = envelope.metadata.get_or_insert_default();
metadata.history_sequence = Some(index as u64 + 1);
metadata.sampled_through_sequence = Some(0);
}
assert_eq!(reconstructed.history, replacement_history);
assert_eq!(42, reconstructed.window_number);
assert_eq!(Some(first_window_id), reconstructed.first_window_id);
assert_eq!(Some(previous_window_id), reconstructed.previous_window_id);
assert_eq!(Some(window_id), reconstructed.window_id);
}

View File

@@ -0,0 +1,124 @@
//! Publishes resolved MCP configuration and host timing rollouts for future turns.
use std::sync::Arc;
use crate::ConfigRefreshOutcome;
use crate::config::Config;
use crate::config::Constrained;
use crate::config::RuntimeConfigRefresh;
use crate::session::Session;
use akode_features::Feature;
use tracing::warn;
impl Session {
pub(crate) async fn refresh_runtime_config(
&self,
expected_config: Arc<Config>,
next_config: Config,
) -> ConfigRefreshOutcome {
self.refresh_config(expected_config, next_config, RuntimeConfigRefresh::User)
.await
}
pub(crate) async fn refresh_mcp_config(
&self,
expected_config: Arc<Config>,
next_config: Config,
) -> ConfigRefreshOutcome {
self.refresh_config(expected_config, next_config, RuntimeConfigRefresh::Mcp)
.await
}
pub(super) async fn refresh_config(
&self,
expected_config: Arc<Config>,
next_config: Config,
scope: RuntimeConfigRefresh,
) -> ConfigRefreshOutcome {
let (mut config, outcome, rejection_kind) =
match expected_config.resolve_runtime_refresh(&next_config, scope) {
Ok(config) => (config, ConfigRefreshOutcome::Published, None),
Err(error) => {
let mut config = expected_config.as_ref().clone();
if matches!(scope, RuntimeConfigRefresh::Mcp) {
// The host-resolved map already carries fresh requirements and
// preserved session overrides. Keep ordinary-server revocations even
// when retained layers make the merge invalid.
config.mcp_servers = next_config.mcp_servers.clone();
}
config.config_layer_stack = config
.config_layer_stack
.with_mcp_requirements_from(&next_config.config_layer_stack);
if let Err(err) = config.features.refresh_mcp_features(&next_config.features) {
warn!(%err, "failed to apply managed MCP feature restrictions");
config.mcp_servers = Constrained::allow_any(Default::default());
}
(config, ConfigRefreshOutcome::Rejected, Some(error.kind()))
}
};
if !matches!(scope, RuntimeConfigRefresh::UserFiles) {
for (feature, description) in [(Feature::Mcp20260728, "MCP protocol")] {
if let Err(err) = config
.features
.set_enabled(feature, next_config.features.enabled(feature))
{
warn!("failed to refresh {description} config: {err}");
}
}
}
// Publish host rollout changes only to future turn snapshots. Active turns
// must retain one capture policy across tool dispatch and Guardian review.
if matches!(scope, RuntimeConfigRefresh::User)
&& let Err(err) = config.features.set_enabled(
Feature::CriticalPathTiming,
next_config.features.enabled(Feature::CriticalPathTiming),
)
{
warn!("failed to refresh critical path timing config: {err}");
}
let config = Arc::new(config);
let notify_contributors = !matches!(scope, RuntimeConfigRefresh::Mcp)
&& !self.services.extensions.config_contributors().is_empty();
let (previous_config, new_config) = {
let mut state = self.state.lock().await;
// Loaded snapshots can publish only while their captured owner is current.
if !Arc::ptr_eq(
&state.session_configuration.original_config_do_not_use,
&expected_config,
) {
return ConfigRefreshOutcome::Stale;
}
if let Some(rejection_kind) = rejection_kind {
warn!(
?rejection_kind,
"keeping previous configuration after rejected refresh"
);
}
if matches!(scope, RuntimeConfigRefresh::UserFiles) {
self.services.skills_service.clear_cache();
self.services.plugins_manager.clear_cache();
}
// A host refresh carries current rollout settings for recording. A
// legacy file reload uses its original snapshot and bypasses this path.
if matches!(scope, RuntimeConfigRefresh::User) {
self.services
.executed_tool_calls
.refresh(&next_config.features);
}
let previous_config = notify_contributors
.then(|| self.build_effective_session_config(&state.session_configuration));
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
if matches!(scope, RuntimeConfigRefresh::Mcp) {
self.services.mcp_runtime.invalidate_resource_caches();
}
self.mark_mcp_runtime_dirty();
let new_config = notify_contributors
.then(|| self.build_effective_session_config(&state.session_configuration));
(previous_config, new_config)
};
self.emit_config_changed_contributors(previous_config.as_ref(), new_config.as_ref());
self.schedule_mcp_prewarm();
self.refresh_hooks(config).await;
outcome
}
}

View File

@@ -0,0 +1,304 @@
//! Runtime-refresh regressions; pure authority resolution is tested with Config.
use super::*;
use pretty_assertions::assert_eq;
async fn runtime_servers(session: &Session) -> HashMap<String, McpServerConfig> {
let config = session.get_config().await;
akode_mcp::configured_mcp_servers(
&config
.to_mcp_config(session.services.plugins_manager.as_ref())
.await,
)
}
#[test_case::test_case(true; "host enabled")]
#[test_case::test_case(false; "host disabled")]
#[tokio::test]
async fn file_reload_restores_host_feature_defaults_after_override_removal(host_default: bool) {
let (session, _) = make_session_and_context().await;
let home = session.codex_home().await;
let file = home.join(CONFIG_TOML_FILE);
std::fs::create_dir_all(&home).unwrap();
std::fs::write(&file, "").unwrap();
let mut initial = ConfigBuilder::without_managed_config_for_tests()
.codex_home(home.to_path_buf())
.build()
.await
.unwrap();
let features = [
Feature::SecretAuthStorage,
Feature::McpOAuthRefreshCoordination,
];
initial.runtime_feature_defaults = features
.into_iter()
.map(|feature| (feature, host_default))
.collect();
for feature in features {
initial.features.set_enabled(feature, host_default).unwrap();
}
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::new(initial);
for override_value in [None, Some(true), Some(false), None] {
let contents = override_value.map_or_else(String::new, |enabled| {
format!("[features]\nsecret_auth_storage = {enabled}\nmcp_oauth_refresh_coordination = {enabled}\n")
});
std::fs::write(&file, contents).unwrap();
session.reload_user_config_layer().await;
let config = session.get_config().await;
assert_eq!(
features.map(|feature| config.features.enabled(feature)),
[override_value.unwrap_or(host_default); 2]
);
}
}
#[test_case::test_case("config.toml"; "user config")]
#[test_case::test_case("profiles/work.toml"; "profile config")]
#[tokio::test]
async fn reload_user_config_layer_resolves_paths_without_resetting_runtime_settings(
config_file: &str,
) {
let (session, _) = make_session_and_context().await;
let home = session.codex_home().await;
let file = home.join(config_file);
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let ordinary =
"[mcp_servers.ordinary]\nurl = 'https://ordinary.example/mcp'\nenabled = false\n";
std::fs::write(
&file,
format!("model = 'original-model'\nnotify = ['original-notify']\n{ordinary}"),
)
.unwrap();
let mut initial = ConfigBuilder::without_managed_config_for_tests()
.codex_home(home.to_path_buf())
.loader_overrides(LoaderOverrides {
user_config_path: Some(file.clone()),
user_config_profile: (config_file != CONFIG_TOML_FILE).then(|| "work".parse().unwrap()),
..LoaderOverrides::without_managed_config_for_tests()
})
.build()
.await
.unwrap();
let mut servers = initial.mcp_servers.get().clone();
let McpServerTransportConfig::StreamableHttp { http_headers, .. } =
&mut servers.get_mut("ordinary").unwrap().transport
else {
unreachable!()
};
*http_headers = Some(HashMap::from([(
"Authorization".into(),
"Bearer synthetic-host".into(),
)]));
initial.mcp_servers.set(servers).unwrap();
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::new(initial.clone());
let original_servers = runtime_servers(&session).await;
std::fs::write(
&file,
format!(
"model = 'new-model'\nnotify = ['new-notify']\nlog_dir = 'relative-logs'\n{ordinary}"
),
)
.unwrap();
session.reload_user_config_layer().await;
let config = session.get_config().await;
assert_eq!(
config.config_layer_stack.effective_config()["log_dir"].as_str(),
file.parent()
.unwrap()
.join("relative-logs")
.as_path()
.to_str()
);
assert_eq!(config.log_dir, initial.log_dir);
assert_eq!(config.model, initial.model);
assert_eq!(config.notify, initial.notify);
assert_eq!(runtime_servers(&session).await, original_servers);
}
#[tokio::test]
async fn hook_refresh_retries_current_plugin_policy_after_owner_replacement() -> anyhow::Result<()>
{
let (session, _) = make_session_and_context().await;
let home = session.codex_home().await;
let file = home.join(CONFIG_TOML_FILE);
let source = tempfile::tempdir()?;
std::fs::create_dir_all(source.path().join(".codex-plugin"))?;
std::fs::write(
source.path().join(".codex-plugin/plugin.json"),
r#"{"name":"sample","hooks":{"hooks":{"SessionStart":[{"hooks":[{"type":"command","command":"echo sample"}]}]}}}"#,
)?;
akode_core_plugins::store::PluginStore::new(home.to_path_buf()).install(
AbsolutePathBuf::try_from(source.path().to_path_buf())?,
akode_plugin::PluginId::parse("sample@test")?,
)?;
let user_config = "[features]\nplugins = true\nhooks = true\n[plugins.\"sample@test\"]\n";
std::fs::write(&file, user_config)?;
let mut initial = load_latest_config_for_session(&session).await;
initial.bypass_hook_trust = true;
let initial = Arc::new(initial);
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::clone(&initial);
session.refresh_hooks(Arc::clone(&initial)).await;
let request = akode_hooks::SessionStartRequest {
session_id: session.thread_id,
cwd: initial.cwd.clone(),
transcript_path: None,
model: "gpt-5.2".to_string(),
permission_mode: "default".to_string(),
target: akode_hooks::StartHookTarget::SessionStart {
source: akode_hooks::SessionStartSource::Startup,
},
};
assert_eq!(session.hooks().preview_session_start(&request).len(), 1);
let mut incoming = initial.as_ref().clone();
incoming.config_layer_stack = initial.config_layer_stack.with_user_config(
&file,
toml::from_str(&format!(
"{user_config}[plugins._default]\nenabled = false\n"
))?,
)?;
let denied = Arc::new(initial.resolve_runtime_refresh(&incoming, RuntimeConfigRefresh::User)?);
// A concurrent refresh publishes its policy before its hook rebuild completes.
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::clone(&denied);
assert_eq!(session.hooks().preview_session_start(&request).len(), 1);
// Another publication replaces the owner before the pending hook rebuild completes.
{
let mut state = session.state.lock().await;
let replacement = state
.session_configuration
.original_config_do_not_use
.as_ref()
.clone();
state.session_configuration.original_config_do_not_use = Arc::new(replacement);
}
let published = session.get_config().await;
assert!(!Arc::ptr_eq(&published, &denied));
assert_eq!(published.plugins, denied.plugins);
assert_eq!(session.hooks().preview_session_start(&request).len(), 1);
// Complete the pending deny rebuild after its owner was replaced.
session.refresh_hooks(denied).await;
assert!(Arc::ptr_eq(&session.get_config().await, &published));
assert!(session.hooks().preview_session_start(&request).is_empty());
// Finishing a hook rebuild from the previous allow policy must not restore it.
session.refresh_hooks(initial).await;
assert!(session.hooks().preview_session_start(&request).is_empty());
Ok(())
}
#[test_case::test_case(RuntimeConfigRefresh::User, false; "host enables")]
#[test_case::test_case(RuntimeConfigRefresh::User, true; "host disables")]
#[test_case::test_case(RuntimeConfigRefresh::Mcp, false; "MCP retains disabled")]
#[test_case::test_case(RuntimeConfigRefresh::Mcp, true; "MCP retains enabled")]
#[test_case::test_case(RuntimeConfigRefresh::UserFiles, false; "file retains disabled")]
#[test_case::test_case(RuntimeConfigRefresh::UserFiles, true; "file retains enabled")]
#[tokio::test]
async fn critical_path_refresh_changes_only_future_turns(
scope: RuntimeConfigRefresh,
initially_enabled: bool,
) {
let (session, _) = make_session_and_context().await;
let mut initial = session.get_config().await.as_ref().clone();
initial
.features
.set_enabled(Feature::CriticalPathTiming, initially_enabled)
.unwrap();
let original = Arc::new(initial);
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::clone(&original);
let active_turn = session.new_default_turn().await;
let mut next_config = original.as_ref().clone();
next_config
.features
.set_enabled(Feature::CriticalPathTiming, !initially_enabled)
.unwrap();
assert_eq!(
session.refresh_config(original, next_config, scope).await,
crate::ConfigRefreshOutcome::Published
);
let next_turn = session.new_default_turn().await;
assert_eq!(
active_turn
.config
.features
.enabled(Feature::CriticalPathTiming),
initially_enabled
);
assert_eq!(
next_turn
.config
.features
.enabled(Feature::CriticalPathTiming),
initially_enabled != matches!(scope, RuntimeConfigRefresh::User)
);
}
#[tokio::test]
async fn critical_path_refresh_respects_managed_disable() {
let (session, _) = make_session_and_context().await;
let mut initial = session.get_config().await.as_ref().clone();
initial.features = crate::config::ManagedFeatures::from_configured(
initial.features.get().clone(),
Some(Sourced::new(
serde_json::from_value(json!({"critical_path_timing": false})).unwrap(),
RequirementSource::LegacyManagedConfigTomlFromMdm,
)),
)
.unwrap();
let original = Arc::new(initial);
session
.state
.lock()
.await
.session_configuration
.original_config_do_not_use = Arc::clone(&original);
let mut next_config = original.as_ref().clone();
let mut incoming_features = original.features.get().clone();
incoming_features.enable(Feature::CriticalPathTiming);
next_config.features = incoming_features.into();
assert_eq!(
session.refresh_runtime_config(original, next_config).await,
crate::ConfigRefreshOutcome::Published
);
assert!(
!session
.new_default_turn()
.await
.config
.features
.enabled(Feature::CriticalPathTiming)
);
}

View File

@@ -0,0 +1,130 @@
use super::session::Session;
use super::turn_context::TurnContext;
use crate::config::Config;
use akode_protocol::config_types::AutoCompactTokenLimitScope;
use akode_protocol::openai_models::ModelInfo;
#[derive(Debug)]
pub(crate) struct ContextWindowTokenStatus {
// Full active context usage, independent of the configured auto-compact scope.
pub(crate) active_context_tokens: i64,
// Usage counted against `model_auto_compact_token_limit` for the current scope.
pub(crate) auto_compact_scope_tokens: i64,
pub(crate) auto_compact_scope_limit: Option<i64>,
pub(crate) full_context_window_limit: Option<i64>,
pub(crate) base_window_tokens_remaining: Option<i64>,
pub(crate) auto_compact_window_prefill_tokens: Option<i64>,
pub(crate) full_context_window_limit_reached: bool,
pub(crate) token_limit_reached: bool,
pub(crate) turn_end_compaction_threshold_reached: bool,
}
fn tokens_remaining(limit: Option<i64>, used: i64) -> Option<i64> {
limit.map(|limit| limit.saturating_sub(used).max(0))
}
pub(crate) async fn context_window_token_status(
sess: &Session,
turn_context: &TurnContext,
) -> ContextWindowTokenStatus {
context_window_token_status_with_config(
sess,
turn_context.config.as_ref(),
turn_context.model_info().as_ref(),
)
.await
}
pub(crate) async fn context_window_token_status_for_model(
sess: &Session,
config: &Config,
turn_context: &TurnContext,
model_info: &ModelInfo,
) -> ContextWindowTokenStatus {
let mut config = config.clone();
config.token_budget = super::token_budget::resolve_token_budget(
turn_context.configured_token_budget.as_ref(),
turn_context.use_model_token_budget_defaults,
model_info,
);
context_window_token_status_with_config(sess, &config, model_info).await
}
async fn context_window_token_status_with_config(
sess: &Session,
config: &Config,
model_info: &ModelInfo,
) -> ContextWindowTokenStatus {
let active_context_tokens = sess.get_total_token_usage().await;
// Count either the full active context or only the tokens added after the initial prefix.
let (auto_compact_scope_tokens, auto_compact_scope_limit, auto_compact_window_prefill_tokens) =
match config.model_auto_compact_token_limit_scope {
AutoCompactTokenLimitScope::Total => (
active_context_tokens,
model_info.auto_compact_token_limit(),
None,
),
AutoCompactTokenLimitScope::BodyAfterPrefix => {
let window = sess.auto_compact_window_snapshot().await;
let baseline = window.prefill_input_tokens.unwrap_or(active_context_tokens);
let scope_limit = config
.model_auto_compact_token_limit
.or_else(|| model_info.auto_compact_token_limit());
(
active_context_tokens.saturating_sub(baseline),
scope_limit,
window.prefill_input_tokens,
)
}
};
// The model's full context window is a hard cap, independent of the auto-compaction scope.
let full_context_window_limit = model_info.resolved_context_window().map(|context_window| {
context_window.saturating_mul(model_info.effective_context_window_percent) / 100
});
// Report remaining tokens against the base (unbuffered) window, capped by the full context.
let base_window_tokens_remaining = [
tokens_remaining(auto_compact_scope_limit, auto_compact_scope_tokens),
tokens_remaining(full_context_window_limit, active_context_tokens),
]
.into_iter()
.flatten()
.min();
// Only reserve the fallback buffer when there is a fallback prompt to use it.
let auto_compact_fallback_buffer_tokens = config
.token_budget
.as_ref()
.map_or(0, crate::config::TokenBudgetConfig::fallback_buffer_tokens);
let buffered_auto_compact_limit = auto_compact_scope_limit
.map(|limit| limit.saturating_add(auto_compact_fallback_buffer_tokens));
// Force compaction once the buffered window or the model's full context window is reached.
let full_context_window_limit_reached =
full_context_window_limit.is_some_and(|limit| active_context_tokens >= limit);
let token_limit_reached = buffered_auto_compact_limit
.is_some_and(|limit| auto_compact_scope_tokens >= limit)
|| full_context_window_limit_reached;
let post_turn_percent = config.model_post_turn_compact_threshold_percent;
let turn_end_compaction_threshold_reached = post_turn_percent > 0
&& (token_limit_reached
|| full_context_window_limit.is_some_and(|limit| {
i128::from(active_context_tokens) * 100
>= i128::from(limit) * i128::from(post_turn_percent)
}));
ContextWindowTokenStatus {
active_context_tokens,
auto_compact_scope_tokens,
auto_compact_scope_limit,
full_context_window_limit,
base_window_tokens_remaining,
auto_compact_window_prefill_tokens,
full_context_window_limit_reached,
token_limit_reached,
turn_end_compaction_threshold_reached,
}
}

View File

@@ -0,0 +1,56 @@
//! Captures interrupted turns for daemon recovery and restores persisted turn attribution.
//! Callers must flush the rollout after capturing a live turn before persisting its snapshot.
use super::Session;
use akode_protocol::protocol::EnvironmentConfigState;
use akode_protocol::protocol::TurnEnvironmentSelection;
/// Turn input and turn-start injections have entered the rollout writer.
pub(super) struct RecordedTurnInput;
impl Session {
pub(crate) async fn recovered_turn_start_options(
&self,
turn_id: &str,
) -> crate::TurnStartOptions {
self.state
.lock()
.await
.recovered_turn_start_options(turn_id)
}
/// Captures a regular turn only after its input is recorded. The caller must flush the rollout.
pub(crate) async fn interrupted_turn(
&self,
) -> Option<(String, crate::TurnStartOptions, TurnEnvironmentSelection)> {
let active = self.active_turn.lock().await;
let task = active.as_ref()?.task.as_ref()?;
if task.kind != crate::state::TaskKind::Regular || task.cancellation_token.is_cancelled() {
return None;
}
let context = &task.turn_context;
context.extension_data.get::<RecordedTurnInput>()?;
let settings = context.next_step_settings.load();
let environments = self.services.turn_environments.snapshot_now();
// Remote identities/configuration are not persisted across daemon restarts.
if environments.environments.len() != 1 {
return None;
}
let environment = environments.single_local_environment()?.selection();
if environment.config != EnvironmentConfigState::FromThread {
return None;
}
Some((
context.sub_id.clone(),
crate::TurnStartOptions {
final_output_json_schema: context.final_output_json_schema.clone(),
service_tier: Some(settings.service_tier.clone().unwrap_or_else(|| {
akode_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string()
})),
prompt_cache_ttl: context.prompt_cache_ttl,
..Default::default()
},
environment,
))
}
}

View File

@@ -0,0 +1,143 @@
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn dynamic_tools_updates_preserve_submission_order_after_caller_stops_waiting() {
let (mut session, turn_context, rx_event) =
make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| config.allow_persistent_dynamic_tool_updates = true,
)
.await;
let rollout_path =
attach_thread_persistence(Arc::get_mut(&mut session).expect("unique session")).await;
let (thread, rx_sub) = make_thread_for_session(
Arc::clone(&session),
&turn_context,
rx_event,
SessionSource::Exec,
)
.await;
let replacement = vec![DynamicToolSpec::Function(
akode_protocol::dynamic_tools::DynamicToolFunctionSpec {
name: "check_release".into(),
description: "Check the release.".into(),
input_schema: json!({"type": "object", "properties": {}}),
defer_loading: false,
},
)];
let persistence = thread_settings::acquire_persistence_lock(&session).await;
let mut first = Box::pin(tokio::task::unconstrained(
thread.replace_dynamic_tools(Vec::new()),
));
assert!(futures::poll!(first.as_mut()).is_pending());
drop(first);
let mut submissions = Box::pin(tokio::task::unconstrained(submission_loop(
Arc::clone(&session),
Arc::clone(&turn_context.config),
rx_sub,
)));
assert!(futures::poll!(submissions.as_mut()).is_pending());
let mut last = Box::pin(tokio::task::unconstrained(
thread.replace_dynamic_tools(replacement.clone()),
));
assert!(futures::poll!(last.as_mut()).is_pending());
let mut shutdown = Box::pin(tokio::task::unconstrained(thread.submit(Op::Shutdown)));
// Shutdown cannot overtake the accepted replacements while persistence is blocked.
assert!(futures::poll!(shutdown.as_mut()).is_pending());
assert_eq!(session.dynamic_tools().await.as_ref(), &[]);
drop(persistence);
let ((), updated, stopped) = tokio::join!(submissions, last, shutdown);
updated.expect("replace dynamic tools before shutdown");
stopped.expect("submit shutdown");
assert_eq!(
session.dynamic_tools().await.as_ref(),
replacement.as_slice()
);
let restored = RolloutRecorder::get_rollout_history(&rollout_path)
.await
.expect("read persisted catalog");
let catalogs: Vec<_> = restored
.get_rollout_items()
.iter()
.filter_map(|item| match item {
RolloutItem::DynamicToolsUpdated { tools, .. } => Some(tools.clone()),
_ => None,
})
.collect();
assert_eq!(catalogs, vec![Vec::new(), replacement.clone()]);
assert_eq!(restored.get_dynamic_tools(), Some(replacement));
assert!(matches!(
thread
.replace_dynamic_tools(Vec::new())
.await
.unwrap_err()
.details(),
akode_protocol::error::CodexErrorDetails::InternalAgentDied
));
}
#[tokio::test]
async fn dynamic_tools_update_requires_host_opt_in_only_for_persistent_threads() {
let (mut session, _) = make_session_and_context().await;
let initial_tools = vec![DynamicToolSpec::Function(
akode_protocol::dynamic_tools::DynamicToolFunctionSpec {
name: "check_release".into(),
description: "Check the release.".into(),
input_schema: json!({"type": "object", "properties": {}}),
defer_loading: false,
},
)];
session
.replace_dynamic_tools(initial_tools.clone())
.await
.unwrap();
let path = attach_thread_persistence(&mut session).await;
let error = session.replace_dynamic_tools(Vec::new()).await.unwrap_err();
assert!(matches!(
error.details(),
akode_protocol::error::CodexErrorDetails::UnsupportedOperation(_)
));
assert_eq!(
session.dynamic_tools().await.as_ref(),
initial_tools.as_slice()
);
session.flush_rollout().await.unwrap();
let history = RolloutRecorder::get_rollout_history(&path).await.unwrap();
assert_eq!(history.get_dynamic_tools(), Some(initial_tools));
}
#[tokio::test]
async fn dynamic_tools_update_keeps_catalog_when_persistence_fails() {
let (mut session, _, _rx) = make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| config.allow_persistent_dynamic_tool_updates = true,
)
.await;
attach_thread_persistence(Arc::get_mut(&mut session).expect("unique session")).await;
session
.live_thread()
.expect("live thread")
.shutdown()
.await
.expect("close persistence");
let replacement = vec![akode_protocol::dynamic_tools::DynamicToolSpec::Function(
akode_protocol::dynamic_tools::DynamicToolFunctionSpec {
name: "check_release".into(),
description: "Check the release.".into(),
input_schema: json!({"type": "object", "properties": {}}),
defer_loading: false,
},
)];
let error = session
.replace_dynamic_tools(replacement)
.await
.unwrap_err();
assert!(matches!(
error.details(),
akode_protocol::error::CodexErrorDetails::Fatal(_)
));
assert_eq!(session.dynamic_tools().await.as_ref(), &[]);
}

View File

@@ -0,0 +1,302 @@
use akode_direct_tool_timing::ToolBatchTiming;
use akode_direct_tool_timing::ToolTimingGuard;
use akode_features::Feature;
use akode_utils_critical_path::CriticalPath;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use crate::tools::handlers::PreparedPermissionRequest;
use akode_core_plugins::PluginCommandAttribution;
use akode_plugin::PluginId;
use akode_protocol::approvals::ExecApprovalKind;
use akode_protocol::protocol::ReviewDecision;
use akode_protocol::request_permissions::PermissionGrantScope;
use akode_protocol::request_permissions::RequestPermissionProfile;
use akode_protocol::request_permissions::RequestPermissionsResponse;
use akode_protocol::request_user_input::RequestUserInputArgs;
use akode_protocol::request_user_input::RequestUserInputResponse;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use super::tests::make_session_and_context_with_rx;
use crate::session::step_context::StepContext;
use crate::state::ActiveTurn;
fn start_timing(
turn: &mut Arc<super::turn_context::TurnContext>,
enabled: bool,
) -> (Arc<ToolTimingGuard>, Instant) {
Arc::make_mut(&mut Arc::get_mut(turn).expect("unique test turn").config)
.features
.set_enabled(Feature::CriticalPathTiming, enabled)
.unwrap();
let start = Instant::now();
let owner = turn
.turn_timing_state
.direct_tool_timings
.start_turn_direct_call(
"call-1",
&turn.sub_id,
ToolBatchTiming::default(),
start,
Some(CriticalPath::default()),
);
(owner, start)
}
fn assert_user_wait(owner: &ToolTimingGuard, start: Instant, enabled: bool) {
let completed = owner.finish().unwrap();
let totals = completed.path.unwrap().durations(start, completed.ended_at);
assert_eq!(totals.user_wait > Duration::ZERO, enabled);
}
async fn wait_until_held(pause_state: &mut watch::Receiver<bool>) {
pause_state
.wait_for(|paused| *paused)
.await
.expect("elicitation service should remain available");
}
async fn wait_until_released(pause_state: &mut watch::Receiver<bool>) {
pause_state
.wait_for(|paused| !*paused)
.await
.expect("elicitation service should remain available");
}
#[test_case::test_case(true, "call-1"; "capture_on")]
#[test_case::test_case(false, "call-1"; "capture_off")]
#[test_case::test_case(true, "network-prompt"; "distinct_network_prompt_identity")]
#[tokio::test]
async fn command_approval_holds_an_elicitation_until_response(capture: bool, prompt_id: &str) {
let (session, mut turn_context, events) = make_session_and_context_with_rx().await;
let (timing, timing_start) = start_timing(&mut turn_context, capture);
*session.active_turn.lock().await = Some(ActiveTurn::default());
let mut pause_state = session.subscribe_elicitation_pause_state();
#[allow(deprecated)]
let cwd = turn_context.cwd.clone();
let plugin_attribution = PluginCommandAttribution {
plugin_id: PluginId::parse("sample@openai-curated").expect("valid plugin id"),
normalized_relative_path: "scripts/run.py".to_string(),
};
let request = tokio::spawn({
let prompt_id = prompt_id.to_owned();
let session = session.clone();
let turn_context = turn_context.clone();
async move {
session
.request_command_approval(
turn_context.as_ref(),
ExecApprovalKind::Command,
crate::guardian::GuardianReviewContext::from(turn_context.clone())
.model_context(),
prompt_id,
Some("call-1"),
/*approval_id*/ None,
/*environment_id*/ None,
vec!["echo".to_string()],
cwd.into(),
/*reason*/ None,
/*network_approval*/ None,
/*proposed_execpolicy_amendment*/ None,
/*additional_permissions*/ None,
/*available_decisions*/ None,
/*plugin_attribution_override*/ Some(plugin_attribution),
)
.await
}
});
let event = events.recv().await.expect("approval event");
let akode_protocol::protocol::EventMsg::ExecApprovalRequest(event) = event.msg else {
panic!("expected command approval event");
};
assert_eq!(event.plugin_id.as_deref(), Some("sample@openai-curated"));
assert_eq!(event.script_path.as_deref(), Some("scripts/run.py"));
wait_until_held(&mut pause_state).await;
session
.notify_approval(prompt_id, ReviewDecision::Approved)
.await;
request.await.expect("approval task");
wait_until_released(&mut pause_state).await;
assert_user_wait(&timing, timing_start, capture);
}
#[test_case::test_case(true; "capture_on")]
#[test_case::test_case(false; "capture_off")]
#[tokio::test]
async fn patch_approval_holds_an_elicitation_until_response(capture: bool) {
let (session, mut turn_context, events) = make_session_and_context_with_rx().await;
let (timing, timing_start) = start_timing(&mut turn_context, capture);
*session.active_turn.lock().await = Some(ActiveTurn::default());
let mut pause_state = session.subscribe_elicitation_pause_state();
let request = tokio::spawn({
let session = session.clone();
let turn_context = turn_context.clone();
async move {
session
.request_patch_approval(
turn_context.as_ref(),
"call-1".to_string(),
HashMap::new(),
/*reason*/ None,
/*grant_root*/ None,
)
.await
}
});
events.recv().await.expect("approval event");
wait_until_held(&mut pause_state).await;
session
.notify_approval("call-1", ReviewDecision::Approved)
.await;
request.await.expect("approval task");
wait_until_released(&mut pause_state).await;
assert_user_wait(&timing, timing_start, capture);
}
#[test_case::test_case(true; "capture_on")]
#[test_case::test_case(false; "capture_off")]
#[tokio::test]
async fn permission_request_holds_an_elicitation_until_response(capture: bool) {
let (session, mut turn_context, events) = make_session_and_context_with_rx().await;
let (timing, timing_start) = start_timing(&mut turn_context, capture);
*session.active_turn.lock().await = Some(ActiveTurn::default());
let mut pause_state = session.subscribe_elicitation_pause_state();
let request = tokio::spawn({
let session = session.clone();
let turn_context = turn_context.clone();
async move {
let environment = turn_context
.initial_environments
.primary()
.expect("primary environment")
.selection();
session
.request_permissions_for_environment(
&StepContext::for_test(Arc::clone(&turn_context)),
"call-1".to_string(),
PreparedPermissionRequest {
environment_id: environment.environment_id,
reason: None,
permissions: RequestPermissionProfile::default(),
},
CancellationToken::new(),
)
.await
}
});
events.recv().await.expect("permission request event");
wait_until_held(&mut pause_state).await;
session
.notify_request_permissions_response(
"call-1",
RequestPermissionsResponse {
permissions: RequestPermissionProfile::default(),
scope: PermissionGrantScope::Turn,
strict_auto_review: false,
},
)
.await;
request.await.expect("permission request task");
wait_until_released(&mut pause_state).await;
assert_user_wait(&timing, timing_start, capture);
}
#[test_case::test_case(true, true, false; "blocking")]
#[test_case::test_case(true, false, false; "nonblocking_ui_label")]
#[test_case::test_case(true, true, true; "cancelled")]
#[test_case::test_case(false, true, false; "capture_off")]
#[tokio::test]
async fn request_user_input_holds_an_elicitation_until_response(
capture: bool,
blocking: bool,
cancel: bool,
) {
let (session, mut turn_context, events) = make_session_and_context_with_rx().await;
let (timing, timing_start) = start_timing(&mut turn_context, capture);
*session.active_turn.lock().await = Some(ActiveTurn::default());
let mut pause_state = session.subscribe_elicitation_pause_state();
let request = tokio::spawn({
let session = session.clone();
let turn_context = turn_context.clone();
async move {
session
.request_user_input(
turn_context.as_ref(),
"call-1".to_string(),
RequestUserInputArgs {
questions: Vec::new(),
is_blocking: blocking,
auto_resolution_ms: None,
},
)
.await
}
});
events.recv().await.expect("request user input event");
wait_until_held(&mut pause_state).await;
if cancel {
request.abort();
assert!(matches!(request.await, Err(error) if error.is_cancelled()));
wait_until_released(&mut pause_state).await;
assert_user_wait(&timing, timing_start, capture);
return;
}
let response = RequestUserInputResponse {
answers: HashMap::new(),
};
session
.notify_user_input_response(&turn_context.sub_id, response)
.await;
request.await.expect("request user input task");
wait_until_released(&mut pause_state).await;
assert_user_wait(&timing, timing_start, capture);
}
#[test_case::test_case(true; "enabled_unowned_wait_is_incomplete")]
#[test_case::test_case(false; "disabled_unowned_wait_is_unchanged")]
#[tokio::test]
async fn unowned_human_wait_does_not_claim_a_complete_path(capture: bool) {
let (session, mut turn_context, _rx) = make_session_and_context_with_rx().await;
let (_tool_timing, _) = start_timing(&mut turn_context, capture);
turn_context.turn_timing_state.enable_critical_path();
turn_context
.turn_timing_state
.mark_turn_started(Instant::now())
.await;
assert!(
turn_context
.turn_timing_state
.snapshot_path(Instant::now())
.is_some()
);
assert!(
session
.user_wait_timing_owner(&turn_context, Some("unknown-call"))
.is_none()
);
assert!(
session
.start_user_wait_timing(&turn_context, /*owner*/ None)
.is_none()
);
assert_eq!(
turn_context
.turn_timing_state
.snapshot_path(Instant::now())
.is_none(),
capture
);
}

View File

@@ -0,0 +1,384 @@
use std::collections::HashSet;
use std::sync::Arc;
use akode_exec_server::LOCAL_ENVIRONMENT_ID;
use akode_exec_server::MAX_SELECTED_CAPABILITY_ROOTS;
use akode_exec_server::SelectedCapabilityRootsStatus;
use akode_execpolicy::Policy;
use akode_features::Feature;
use akode_protocol::capabilities::CapabilityRootLocation;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::AgentStatus;
use akode_protocol::protocol::EnvironmentConfig;
use akode_protocol::protocol::EnvironmentConfigState;
use akode_protocol::protocol::TurnEnvironmentSelection;
use akode_protocol::sandbox::SandboxType;
use crate::config::ConstraintError;
use crate::config::ConstraintResult;
use crate::config::ManagedFeatures;
use crate::config::NetworkProxySpec;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::session::session::Session;
use crate::session::session::SessionConfiguration;
use crate::session::session::SessionSettingsUpdate;
/// Defaults for environments that inherit their configuration from the running turn.
#[derive(Clone)]
pub(crate) struct ThreadEnvironmentDefaults {
pub(crate) common: EnvironmentConfig,
// Chosen once when the session starts; it does not apply to remote environments.
local_windows_sandbox_type: SandboxType,
}
impl ThreadEnvironmentDefaults {
pub(crate) fn new(common: EnvironmentConfig, local_windows_sandbox_type: SandboxType) -> Self {
Self {
common,
local_windows_sandbox_type,
}
}
pub(crate) fn for_selection(&self, selection: &TurnEnvironmentSelection) -> EnvironmentConfig {
let mut config = self.common.clone();
config.workspace_roots = selection.workspace_roots.clone();
if selection.environment_id == LOCAL_ENVIRONMENT_ID {
config.windows_sandbox_type = self.local_windows_sandbox_type;
}
config
}
}
pub(super) fn validate_environment_configs(
selections: &[TurnEnvironmentSelection],
features: &ManagedFeatures,
) -> ConstraintResult<()> {
for selection in selections {
match &selection.config {
EnvironmentConfigState::FromThread
| EnvironmentConfigState::Pending
| EnvironmentConfigState::Failed(_) => {}
EnvironmentConfigState::Ready(config) => {
validate_environment_config(selection, config, features).map_err(|error| {
ConstraintError::InvalidValue {
field_name: "environments",
candidate: "environment configuration".to_string(),
allowed: format!("valid environment configuration ({error})"),
requirement_source: akode_config::RequirementSource::Unknown,
}
})?;
}
}
}
Ok(())
}
pub(super) fn ensure_configs_stay_owner_provided(
current: &[TurnEnvironmentSelection],
proposed: &[TurnEnvironmentSelection],
) -> ConstraintResult<()> {
if let Some(environment) = proposed.iter().find(|environment| {
environment.config == EnvironmentConfigState::FromThread
&& current.iter().any(|current| {
current.environment_id == environment.environment_id
&& current.config != EnvironmentConfigState::FromThread
})
}) {
return Err(ConstraintError::InvalidValue {
field_name: "environments",
candidate: environment.environment_id.clone(),
allowed: "owner-provided environment configuration".to_string(),
requirement_source: akode_config::RequirementSource::Unknown,
});
}
Ok(())
}
fn validate_environment_config(
selection: &TurnEnvironmentSelection,
config: &EnvironmentConfig,
features: &ManagedFeatures,
) -> CodexResult<()> {
if features.enabled(Feature::CodexHooks) {
akode_hooks::validate_environment_hooks(
&selection.environment_id,
&selection.cwd,
&config.environment_hooks,
)
.map_err(|error| CodexErr::InvalidRequest(error.to_string()))?;
}
if let Some(policy) = config.network_policy.as_ref() {
if selection.environment_id == LOCAL_ENVIRONMENT_ID {
return Err(CodexErr::InvalidRequest(
"attachment-owned network policy requires a remote executor".to_string(),
));
}
if config
.exec_policy
.as_ref()
.is_some_and(|policy| !policy.as_ref().network_rules().is_empty())
{
return Err(CodexErr::InvalidRequest(
"environment network restrictions must use network_policy".to_string(),
));
}
// Validate owner policy on its own; controller compatibility is checked at execution.
NetworkProxySpec::for_environment(
/*controller*/ None,
policy,
config.permission_profile.permission_profile(),
&Policy::empty(),
akode_network_proxy::LocalBindingPolicy::DefaultFalse,
)
.map_err(|error| {
CodexErr::InvalidRequest(format!("invalid environment network policy: {error}"))
})?;
}
if config.selected_capability_roots.len() > MAX_SELECTED_CAPABILITY_ROOTS {
return Err(CodexErr::InvalidRequest(format!(
"environment readiness contains more than {MAX_SELECTED_CAPABILITY_ROOTS} selected capability roots"
)));
}
if config
.exec_policy
.as_ref()
.is_some_and(|policy| !policy.as_ref().get_allowed_prefixes().is_empty())
{
return Err(CodexErr::InvalidRequest(
"environment command policy cannot contain allow rules".to_string(),
));
}
let mut root_ids = HashSet::with_capacity(config.selected_capability_roots.len());
for root in &config.selected_capability_roots {
let CapabilityRootLocation::Environment { environment_id, .. } = &root.location;
if root.id.trim().is_empty()
|| environment_id != &selection.environment_id
|| !root_ids.insert(root.id.as_str())
{
return Err(CodexErr::InvalidRequest(format!(
"selected capability roots must have unique non-empty IDs and belong to environment `{}`",
selection.environment_id
)));
}
}
Ok(())
}
enum ConfigUpdateSource {
Direct,
Inherited,
}
impl Session {
pub(super) fn apply_session_settings(
&self,
current: &SessionConfiguration,
updates: &SessionSettingsUpdate,
) -> ConstraintResult<SessionConfiguration> {
let current_environments = &current.environments;
if let Some(environments) = &updates.environments {
ensure_configs_stay_owner_provided(current_environments, &environments.environments)?;
}
current.apply(updates, current_environments)
}
/// Activates the environments accepted for a new task. Configuration may have arrived for
/// those same environments while its settings were being prepared.
#[expect(
clippy::await_holding_invalid_type,
reason = "do not change environments while another task is running"
)]
pub(super) async fn activate_turn_environments(
&self,
configuration: &SessionConfiguration,
) -> TurnEnvironmentSnapshot {
let snapshot = {
let active = self.active_turn.lock().await;
let state = self.state.lock().await;
// Another task may have started while this one was preparing its settings.
if active.as_ref().is_none_or(|turn| turn.task.is_none()) {
let mut environments = configuration.environments.clone();
let latest_environments = &state.session_configuration.environments;
for environment in &mut environments {
if let Some(latest) = latest_environments
.iter()
.find(|latest| latest.has_same_workspace(environment))
{
environment.config = latest.config.clone();
}
}
// Apply the saved defaults even if this turn selects the same environments.
self.services
.turn_environments
.set_active_thread_defaults(configuration.inferred_environment_config());
self.services
.turn_environments
.activate_selections(&environments);
}
self.services.turn_environments.snapshot()
};
snapshot.await
}
pub(crate) async fn environment_ready(
&self,
selection: &TurnEnvironmentSelection,
config: EnvironmentConfig,
) -> CodexResult<()> {
self.update_environment_configuration(selection, Ok(config), ConfigUpdateSource::Direct)
.await
}
pub(crate) async fn environment_failed(
&self,
selection: &TurnEnvironmentSelection,
error: String,
) -> CodexResult<()> {
self.update_environment_configuration(selection, Err(error), ConfigUpdateSource::Direct)
.await
}
/// Installs the original owner's first result through this session's usual configuration checks.
pub(super) fn follow_inherited_environment_configurations(
self: &Arc<Self>,
inherited: &TurnEnvironmentSnapshot,
selected: &[TurnEnvironmentSelection],
) {
for starting in inherited.starting().filter(|starting| {
selected.iter().any(|selection| {
selection.has_same_workspace(&starting.selection)
&& matches!(selection.config, EnvironmentConfigState::Pending)
})
}) {
let Some(configuration) = starting.owner_configuration() else {
continue;
};
let selection = starting.selection.clone();
let session = Arc::downgrade(self);
let mut status = self.agent_status.subscribe();
drop(tokio::spawn(async move {
let result = tokio::select! {
result = configuration => result,
_ = status.wait_for(|status| matches!(status, AgentStatus::Shutdown)) => return,
};
let Some(session) = session.upgrade() else {
return;
};
let apply = |result| {
session.update_environment_configuration(
&selection,
result,
ConfigUpdateSource::Inherited,
)
};
if let Err(error) = apply(result).await {
// Unlike the external owner, no one will retry this child's one-time update.
let _ = apply(Err(error.to_string())).await;
}
}));
}
}
/// Records configuration, or a failure to obtain it, for this environment and workspace.
/// The running turn and future turns may use different environments. Update the matching
/// selection or selections so work already waiting can still finish, and check successful
/// configuration before saving either list.
async fn update_environment_configuration(
&self,
selection: &TurnEnvironmentSelection,
result: Result<EnvironmentConfig, String>,
source: ConfigUpdateSource,
) -> CodexResult<()> {
let mut state = self.state.lock().await;
let mut current = self.services.turn_environments.selections();
let mut future = state.session_configuration.environments.clone();
let inherited = matches!(source, ConfigUpdateSource::Inherited);
let matches = |environment: &TurnEnvironmentSelection| {
environment.has_same_workspace(selection)
&& (!inherited || matches!(environment.config, EnvironmentConfigState::Pending))
};
let environments = (
current.iter_mut().find(|environment| matches(environment)),
future.iter_mut().find(|environment| matches(environment)),
);
// Ignore the parent's result if neither the running turn nor future turns are still
// waiting for this environment's configuration.
if inherited && matches!(environments, (None, None)) {
return Ok(());
}
if let Ok(config) = &result {
// Return the specific readiness error before applying session-level constraints.
validate_environment_config(selection, config, &self.features)?;
}
let (current_environment, future_environment) = match environments {
(None, None) => {
return Err(CodexErr::InvalidRequest(format!(
"environment `{}` is not selected on this thread with the requested workspace",
selection.environment_id
)));
}
(Some(current), Some(future)) if current.config != future.config => {
// Update the selection still waiting for configuration. If neither is waiting,
// keep the existing behavior of updating the current one.
if matches!(future.config, EnvironmentConfigState::Pending) {
(None, Some(future))
} else {
(Some(current), None)
}
}
(Some(current), future) => (Some(current), future),
(None, Some(future)) => (None, Some(future)),
};
let successful = result.is_ok();
let config = match result {
Ok(config) => EnvironmentConfigState::Ready(config),
Err(error) => EnvironmentConfigState::Failed(error),
};
let update_current = current_environment.is_some();
let update_future = future_environment.is_some();
if let Some(environment) = current_environment {
environment.config = config.clone();
}
if let Some(environment) = future_environment {
environment.config = config;
}
if successful {
let validate = |environments: &[TurnEnvironmentSelection]| {
state
.session_configuration
.validate(environments)
.map_err(|error| CodexErr::InvalidRequest(error.to_string()))
};
if update_current {
validate(&current)?;
}
if update_future && (!update_current || current != future) {
validate(&future)?;
}
}
if update_future {
self.services
.turn_environments
.update_configured_selections(&future);
}
state.session_configuration.environments = future;
if update_current {
// Invalidate MCP before installed configuration can wake a waiting turn.
self.mark_mcp_runtime_dirty();
self.services.turn_environments.update_selections(&current);
}
Ok(())
}
/// Combines this session's persisted roots with ready environment attachments.
pub(crate) fn inspect_selected_capability_roots(&self) -> SelectedCapabilityRootsStatus {
self.services
.turn_environments
.inspect_selected_capability_roots(&self.services.selected_capability_roots)
}
}

View File

@@ -0,0 +1,129 @@
//! Applies extension-requested interruption only if the selected turn is still active.
//! Conditional interruption preserves queued input and acknowledges before joining the task.
use super::session::Session;
use crate::codex_thread::CodexThread;
use akode_extension_api::ThreadIdleCause;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::ErrorEvent;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::Op;
use akode_protocol::protocol::TurnAbortReason;
use std::sync::Arc;
use tokio::sync::oneshot;
use tokio::sync::oneshot::error::TryRecvError;
use tracing::Instrument;
#[cfg(test)]
#[path = "extension_interruption_tests.rs"]
mod tests;
impl CodexThread {
/// Interrupts the named active turn unless it has queued input.
/// Returns the decision before joining cancellation, so tool callbacks can await it.
/// Like [`Op::Interrupt`], this does not notify idle contributors; the caller owns wakeup.
pub async fn interrupt_if_no_pending_input(&self, turn_id: &str) -> CodexResult<bool> {
let cancellation_token = {
let active = self.session.active_turn.lock().await;
let Some(task) = active.as_ref().and_then(|turn| turn.task.as_ref()) else {
return Ok(false);
};
if task.turn_context.sub_id != turn_id {
return Ok(false);
}
task.cancellation_token.clone()
};
let (reply, mut result) = oneshot::channel();
tokio::select! {
biased;
result = async {
self.submit(Op::InterruptIfNoPendingInput {
turn_id: turn_id.to_owned(),
reply,
}).await?;
(&mut result).await.map_err(|_| CodexErr::InternalAgentDied)
} => result,
// An earlier interrupt may already be waiting for this tool callback to finish.
// Cancellation can also race with a decision sent by this request.
_ = cancellation_token.cancelled() => match result.try_recv() {
Ok(decision) => Ok(decision),
Err(TryRecvError::Empty | TryRecvError::Closed) => Ok(false),
},
}
}
}
impl Session {
#[expect(
clippy::await_holding_invalid_type,
reason = "the turn identity and pending input check must be atomic with taking the task"
)]
pub(crate) async fn interrupt_turn_if_no_pending_input(
self: &Arc<Self>,
turn_id: &str,
reply: oneshot::Sender<bool>,
) {
let active_turn = {
let mut active = self.active_turn.lock().await;
let Some(turn) = active.as_ref().filter(|turn| {
turn.task
.as_ref()
.is_some_and(|task| task.turn_context.sub_id == turn_id)
}) else {
let _ = reply.send(false);
return;
};
if !turn.turn_state.lock().await.pending_input.is_empty()
|| self.input_queue.has_pending_mailbox_items().await
|| reply.is_closed()
{
let _ = reply.send(false);
return;
}
self.mark_interrupted();
active.take()
};
// The caller may be inside the task that cancellation must join.
let _ = reply.send(active_turn.is_some());
if let Some(active_turn) = active_turn {
self.finish_turn_abort(
active_turn,
TurnAbortReason::Interrupted,
/*error*/ None,
)
.await;
}
}
pub(crate) async fn interrupt_turn_with_warning(
self: &Arc<Self>,
turn_id: &str,
warning: EventMsg,
error: Option<ErrorEvent>,
) {
let Some(turn) = self.turn_context_for_sub_id(turn_id).await else {
return;
};
self.send_event(turn.as_ref(), warning).await;
let runtime = self.services.runtime_handle.clone();
let session = Arc::clone(self);
let turn_id = turn_id.to_owned();
drop(
runtime.spawn(
async move {
if session
.abort_turn_if_active(&turn_id, TurnAbortReason::Interrupted, error)
.await
{
// Extension aborts bypass normal task completion; user interrupts do not.
session
.emit_thread_idle_lifecycle_if_idle(ThreadIdleCause::Interrupted)
.await;
}
}
.in_current_span(),
),
);
}
}

View File

@@ -0,0 +1,156 @@
//! Regression coverage for conditional interruption and detached abort tracing.
#![cfg(test)]
use super::*;
use crate::session::tests::HeldStepTask;
use crate::session::tests::make_session_and_context_with_rx;
use crate::session::tests::make_thread_for_session;
use crate::state::TaskKind;
use akode_protocol::protocol::SessionSource;
use opentelemetry::trace::TracerProvider;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use std::time::Duration;
use tokio::sync::Notify;
use tracing::Instrument;
use tracing_subscriber::prelude::*;
#[tokio::test]
async fn interrupt_with_warning_exports_turn_profile_under_caller_span() -> anyhow::Result<()> {
let exported = InMemorySpanExporter::default();
let provider = SdkTracerProvider::builder()
.with_simple_exporter(exported.clone())
.build();
let subscriber = tracing_subscriber::registry().with(
tracing_opentelemetry::layer()
.with_tracer(provider.tracer("guardian-interrupt-test"))
.with_filter(tracing_subscriber::filter::filter_fn(
akode_otel::trace_export_filter,
)),
);
let _interest_cache_guard =
tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default());
let _subscriber_guard = tracing::subscriber::set_default(subscriber);
let (session, turn, events) = make_session_and_context_with_rx().await;
session
.spawn_task(
Arc::clone(&turn),
Vec::new(),
HeldStepTask {
kind: TaskKind::Regular,
finish: Arc::new(Notify::new()),
},
)
.await;
turn.turn_timing_state
.mark_turn_started(std::time::Instant::now())
.await;
drop(turn.turn_timing_state.begin_sampling());
turn.turn_timing_state.record_sampling_retry();
// Guardian uses this detached abort path rather than submitting Op::Interrupt.
session
.interrupt_turn_with_warning(
&turn.sub_id,
EventMsg::Warning(akode_protocol::protocol::WarningEvent {
message: "Guardian denial limit reached".into(),
}),
/*error*/ None,
)
.instrument(tracing::info_span!("guardian_review"))
.await;
tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
while !matches!(events.recv().await?.msg, EventMsg::TurnAborted(_)) {}
anyhow::Ok(())
})
.await??;
let profile = tokio::time::timeout(Duration::from_secs(/*secs*/ 5), async {
loop {
let spans = exported.get_finished_spans()?;
for span in spans {
if span.name == "guardian_review"
&& let Some(event) = span
.events
.iter()
.find(|event| event.name == "codex.turn_profile")
{
return anyhow::Ok(event.clone());
}
}
tokio::task::yield_now().await;
}
})
.await??;
let attributes: std::collections::BTreeMap<_, _> = profile
.attributes
.iter()
.filter(|attribute| {
matches!(
attribute.key.as_str(),
"conversation.id" | "turn_id" | "sampling_request_count" | "sampling_retry_count"
)
})
.map(|attribute| (attribute.key.as_str(), attribute.value.to_string()))
.collect();
assert_eq!(
attributes,
std::collections::BTreeMap::from([
("conversation.id", session.thread_id.to_string()),
("turn_id", turn.sub_id.clone()),
("sampling_request_count", "1".into()),
("sampling_retry_count", "1".into()),
])
);
Ok(())
}
#[tokio::test]
async fn interrupt_if_no_pending_input_handles_cancelled_submission() {
let (session, turn_context, rx_event) = make_session_and_context_with_rx().await;
session
.spawn_task(
Arc::clone(&turn_context),
Vec::new(),
HeldStepTask {
kind: TaskKind::Regular,
finish: Arc::new(Notify::new()),
},
)
.await;
let cancellation_token = session
.active_turn
.lock()
.await
.as_ref()
.expect("active turn")
.task
.as_ref()
.expect("active task")
.cancellation_token
.clone();
let (thread, rx_sub) = make_thread_for_session(
Arc::clone(&session),
&turn_context,
rx_event,
SessionSource::Cli,
)
.await;
thread.submit(Op::Interrupt).await.expect("fill the queue");
let interrupt = thread.interrupt_if_no_pending_input(&turn_context.sub_id);
tokio::pin!(interrupt);
assert!(futures::poll!(interrupt.as_mut()).is_pending());
// The pending submission still owns its reply sender when cancellation wins.
cancellation_token.cancel();
assert_eq!(
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), interrupt)
.await
.expect("cancellation should unblock the submission")
.expect("cancelling a submission does not mean the agent died"),
false,
);
assert!(!rx_sub.is_closed());
assert_eq!(rx_sub.len(), 1);
session.abort_all_tasks(TurnAbortReason::Interrupted).await;
}

View File

@@ -0,0 +1,35 @@
use std::sync::Arc;
use akode_extension_api::ExtensionMetrics;
use akode_otel::SessionTelemetry;
struct SessionTelemetryExtensionMetrics {
session_telemetry: SessionTelemetry,
}
impl ExtensionMetrics for SessionTelemetryExtensionMetrics {
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
self.session_telemetry.counter(name, inc, tags);
}
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
self.session_telemetry.histogram(name, value, tags);
}
fn histogram_with_boundaries(
&self,
name: &str,
value: i64,
boundaries: &[f64],
tags: &[(&str, &str)],
) {
self.session_telemetry
.histogram_with_boundaries(name, value, boundaries, tags);
}
}
pub(crate) fn from_session_telemetry(
session_telemetry: SessionTelemetry,
) -> Arc<dyn ExtensionMetrics> {
Arc::new(SessionTelemetryExtensionMetrics { session_telemetry })
}

View File

@@ -0,0 +1,100 @@
//! Caches trusted file-audio durations for one session. Metadata lookup is best effort
//! and time-bounded. Accepted input is recorded before lookup, and unmeasured
//! files reserve the full audio token budget.
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use akode_attachment_store::FormatSpecificMetadata;
use akode_attachment_store::ResolveRequest;
use akode_history::ResponseItemEnvelope;
use akode_protocol::models::AudioReference;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_utils_audio::estimate_file_audio_tokens;
use futures::StreamExt;
use futures::stream;
use crate::session::Session;
/// Thread-local metadata. It is never serialized into a rollout or a provider request.
#[derive(Clone, Debug, Default)]
pub(crate) struct FileAudioDurations(BTreeMap<String, Duration>);
impl FileAudioDurations {
pub(crate) fn tokens(&self, file_id: &str) -> usize {
estimate_file_audio_tokens(self.0.get(file_id).copied())
}
}
pub(crate) async fn snapshot(session: &Session) -> Arc<FileAudioDurations> {
Arc::clone(&session.state.lock().await.history.file_audio_durations)
}
pub(super) fn file_ids(items: &[ResponseItemEnvelope]) -> impl Iterator<Item = &String> {
items
.iter()
.filter_map(|envelope| match &envelope.item {
ResponseItem::Message { content, .. } => Some(content),
_ => None,
})
.flatten()
.filter_map(|part| match part {
ContentItem::InputAudio {
audio: AudioReference::File { file_id },
} => Some(file_id),
_ => None,
})
}
pub(super) async fn resolve(session: &Session, mut file_ids: BTreeSet<String>) {
if file_ids.is_empty() {
return;
}
{
let state = session.state.lock().await;
file_ids.retain(|id| !state.history.file_audio_durations.0.contains_key(id));
}
let mut lookups = stream::iter(file_ids)
.map(|id| async move {
let result = session
.services
.image_store
.resolve(ResolveRequest {
file_id: &id,
tags: HashMap::new(),
download_url_ttl: None,
})
.await;
(id, result)
})
.buffer_unordered(8);
let mut resolved = BTreeMap::new();
// Metadata is optional. Bound the entire batch, keep completed lookups on timeout,
// and allow future attachments to retry a missing value.
let _ = tokio::time::timeout(Duration::from_millis(250), async {
while let Some((id, result)) = lookups.next().await {
if let Ok(metadata) = result
&& let Some(FormatSpecificMetadata::Audio(audio)) = metadata.format_specific
&& let Some(duration_ms) = audio.duration_ms
&& duration_ms > 0
{
resolved.insert(id, Duration::from_millis(duration_ms));
}
}
})
.await;
if !resolved.is_empty() {
let mut state = session.state.lock().await;
Arc::make_mut(&mut state.history.file_audio_durations)
.0
.extend(resolved);
}
}
#[cfg(test)]
#[path = "file_audio_tests.rs"]
mod tests;

View File

@@ -0,0 +1,46 @@
//! Checks history estimates with and without trusted file-audio durations.
#![cfg(test)]
use super::*;
use crate::context_manager::ContextManager;
use akode_protocol::models::BaseInstructions;
use akode_protocol::models::ResponseInputItem;
use akode_protocol::user_input::UserInput;
use akode_protocol_test_support::uuid_v7_item_id_generator_for_test;
use akode_utils_output_truncation::TruncationPolicy;
use pretty_assertions::assert_eq;
#[test]
fn history_sums_measured_and_unknown_file_audio() {
let mut history = ContextManager::new(uuid_v7_item_id_generator_for_test());
let item = ResponseInputItem::from(
["short", "unknown"]
.map(|file_id| UserInput::Audio {
audio: AudioReference::File {
file_id: file_id.into(),
},
})
.to_vec(),
);
history.record_items(
[&ResponseItem::from(item)],
TruncationPolicy::Tokens(10_000),
);
let base = BaseInstructions {
text: String::new(),
provenance: None,
};
assert_eq!(
history.estimate_token_count_with_base_instructions(&base),
Some(24_000)
);
history.file_audio_durations = Arc::new(FileAudioDurations(BTreeMap::from([(
"short".into(),
Duration::from_secs(30),
)])));
assert_eq!(
history.estimate_token_count_with_base_instructions(&base),
Some(12_300)
);
assert_eq!(history.estimated_tokens_since_last_usage(), 12_300);
}

View File

@@ -0,0 +1,50 @@
//! Captures a completed Guardian model context using the existing fork replay format.
//! This snapshot is in memory only; transcript durability remains part of turn completion.
use super::session::Session;
use akode_history::CompactedItem;
use akode_history::RolloutItem;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::TokenCountEvent;
impl Session {
pub(crate) async fn guardian_fork_history(&self) -> Vec<RolloutItem> {
let state = self.state.lock().await;
let history = &state.history;
let window_ids = state.auto_compact_window_ids();
let mut items = vec![RolloutItem::Compacted(Box::new(CompactedItem {
message: String::new(),
replacement_history: Some(history.annotated_items().to_vec()),
guardian_history: history.guardian_history_checkpoint(),
retained_context: Some(history.retained_context().clone()),
mcp_resource_origins: None,
window_number: Some(state.auto_compact_window_number()),
first_window_id: Some(window_ids.first_window_id.to_string()),
previous_window_id: window_ids
.previous_window_id
.as_ref()
.map(ToString::to_string),
window_id: Some(window_ids.window_id.to_string()),
compaction_response_id: None,
latest_token_usage_record: state.latest_token_usage_record.clone(),
resume_metadata: None,
}))];
if let Some(world_state) = history.world_state_checkpoint() {
items.push(RolloutItem::WorldState(world_state));
}
if let Some(context) = history.reference_context_item() {
items.push(RolloutItem::TurnContext(context));
}
items.push(RolloutItem::EventMsg(EventMsg::TokenCount(
TokenCountEvent {
info: history.token_info(),
rate_limits: None,
},
)));
items
}
}
#[cfg(test)]
#[path = "guardian_checkpoint_tests.rs"]
mod tests;

View File

@@ -0,0 +1,138 @@
use crate::context::GuardianContextMode;
use crate::context::world_state::WorldStateSnapshot;
use crate::context_manager::ContextManager;
use crate::session::tests::make_session_and_context;
use akode_history::InitialHistory;
use akode_protocol::models::ResponseItem;
use akode_protocol::protocol::ThreadHistoryMode;
use akode_protocol::protocol::TokenUsage;
use akode_protocol_test_support::uuid_v7_item_id_generator_for_test;
use pretty_assertions::assert_eq;
use serde_json::json;
use test_case::test_case;
#[test_case(GuardianContextMode::Legacy, ThreadHistoryMode::Legacy; "legacy_context_legacy_storage")]
#[test_case(GuardianContextMode::ThreadOwned, ThreadHistoryMode::Legacy; "thread_owned_context_legacy_storage")]
#[test_case(GuardianContextMode::Legacy, ThreadHistoryMode::Paginated; "legacy_context_paginated_storage")]
#[test_case(GuardianContextMode::ThreadOwned, ThreadHistoryMode::Paginated; "thread_owned_context_paginated_storage")]
#[tokio::test]
async fn guardian_checkpoint_preserves_live_context_without_storage(
mode: GuardianContextMode,
history_mode: ThreadHistoryMode,
) {
let (session, turn) = make_session_and_context().await;
// This session has no live store. A checkpoint must still capture the complete context.
assert!(session.live_thread().is_none());
let instruction: ResponseItem = serde_json::from_value(json!({
"type": "message", "id": "user-restriction", "role": "user", "content": [
{"type": "input_text", "text": "Do not publish the private report."}
],
"internal_chat_message_metadata_passthrough": {"content_item_kinds": ["unknown"]}
}))
.unwrap();
let context = turn.to_turn_context_item();
let baseline = json!({"test": "baseline"});
let world_state = WorldStateSnapshot::from(baseline.as_object().unwrap());
{
let mut state = session.state.lock().await;
state.history = ContextManager::for_session(
/*root_capabilities_restricted*/ false,
&crate::config::ManagedFeatures::from(akode_features::Features::with_defaults()),
akode_guardian_context::ContextBudgeting::Fixed,
uuid_v7_item_id_generator_for_test(),
);
state
.history
.record_items([&instruction], turn.model_info().truncation_policy.into());
// The model window no longer contains the old restriction. Legacy review must
// preserve it in its retained transcript when this checkpoint is forked.
if mode == GuardianContextMode::Legacy {
let compacted: ResponseItem = serde_json::from_value(json!({
"type": "compaction", "id": "compaction-1", "encrypted_content": "summary",
}))
.unwrap();
let retained = state.history.retained_context().clone();
state.history.replace_annotated(vec![compacted.into()]);
state.history.restore_review_context(
Some(&retained),
Some(&akode_history::GuardianHistoryCheckpoint(vec![
instruction.clone().into(),
])),
/*reviewer_compaction_hash*/ None,
);
}
let followup: ResponseItem = serde_json::from_value(json!({
"type": "message", "id": "user-followup", "role": "user", "content": [
{"type": "input_text", "text": "Review the next action."}
],
"internal_chat_message_metadata_passthrough": {"content_item_kinds": ["unknown"]}
}))
.unwrap();
state
.history
.record_items([&followup], turn.model_info().truncation_policy.into());
state.history.set_reference_context_item(Some(context));
state.history.set_world_state_baseline(world_state.clone());
state.history.update_token_info(
&TokenUsage {
input_tokens: 123,
total_tokens: 123,
..Default::default()
},
Some(32_000),
/*includes_reasoning*/ true,
/*input_item_count*/ 0,
);
}
let expected = session.clone_history().await;
if mode == GuardianContextMode::Legacy {
assert!(
expected
.guardian_history_checkpoint()
.unwrap()
.0
.iter()
.any(|entry| entry.item == instruction)
);
}
let items = session.guardian_fork_history().await;
assert!(
crate::thread_rollout_truncation::initial_history_has_prior_user_turns(
&InitialHistory::Forked(items.clone()),
)
);
// Mutating the live reviewer must not change the previously completed checkpoint.
session
.replace_history(Vec::new(), /*reference_context_item*/ None)
.await;
// Replay into a fresh session so preserved live state cannot mask missing checkpoint data.
let (fork, _) = make_session_and_context().await;
fork.state.lock().await.session_configuration.history_mode = history_mode;
fork.state.lock().await.history = ContextManager::for_session(
/*root_capabilities_restricted*/ false,
&crate::config::ManagedFeatures::from(akode_features::Features::with_defaults()),
akode_guardian_context::ContextBudgeting::Fixed,
uuid_v7_item_id_generator_for_test(),
);
fork.record_initial_history(InitialHistory::Forked(items))
.await;
let restored = fork.clone_history().await;
assert_eq!(restored.annotated_items(), expected.annotated_items());
assert_eq!(restored.retained_context(), expected.retained_context());
assert_eq!(
restored.guardian_history_checkpoint(),
expected.guardian_history_checkpoint()
);
assert_eq!(
restored.world_state_checkpoint(),
expected.world_state_checkpoint()
);
assert_eq!(
serde_json::to_value(restored.reference_context_item()).unwrap(),
serde_json::to_value(expected.reference_context_item()).unwrap()
);
assert_eq!(
serde_json::to_value(restored.token_info()).unwrap(),
serde_json::to_value(expected.token_info()).unwrap()
);
}

View File

@@ -0,0 +1,900 @@
use super::Submission;
use crate::WithTurnExtensionData;
use crate::realtime_conversation::handle_audio as handle_realtime_conversation_audio;
use crate::realtime_conversation::handle_close as handle_realtime_conversation_close;
use crate::realtime_conversation::handle_speech as handle_realtime_conversation_speech;
use crate::realtime_conversation::handle_start as handle_realtime_conversation_start;
use crate::realtime_conversation::handle_text as handle_realtime_conversation_text;
use async_channel::Receiver;
use akode_features::Feature;
use akode_otel::set_parent_from_w3c_trace_context;
use tracing::Instrument;
use tracing::debug_span;
use tracing::info_span;
use crate::session::session::Session;
use crate::session::thread_settings;
use crate::session::turn_input;
use crate::config::Config;
use crate::context::ContextualUserFragment;
use crate::context::GuardianApprovedAction;
use crate::review_prompts::resolve_review_request;
use crate::session::spawn_review_thread;
use crate::tasks::CompactTask;
use crate::tasks::UserShellCommandMode;
use crate::tasks::UserShellCommandTask;
use crate::tasks::execute_user_shell_command;
use crate::thread_manager::AgentTreeShutdownFailure;
use crate::thread_manager::thread_store_error_kind;
use akode_protocol::approvals::ExecApprovalKind;
use akode_protocol::error::CodexErr;
use akode_protocol::protocol::CodexErrorInfo;
use akode_protocol::protocol::ErrorEvent;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::GuardianAssessmentEvent;
use akode_protocol::protocol::GuardianAssessmentStatus;
use akode_protocol::protocol::Op;
use akode_protocol::protocol::RealtimeConversationListVoicesResponseEvent;
use akode_protocol::protocol::RealtimeVoicesList;
use akode_protocol::protocol::ReviewDecision;
use akode_protocol::protocol::ReviewRequest;
use akode_protocol::protocol::ThreadMemoryMode;
use akode_protocol::protocol::TurnAbortReason;
use akode_protocol::protocol::WarningEvent;
use akode_protocol::request_permissions::RequestPermissionsResponse;
use akode_protocol::request_user_input::RequestUserInputResponse;
use akode_thread_store::PersistContext;
use crate::context_manager::is_user_turn_boundary;
use akode_protocol::dynamic_tools::DynamicToolResponse;
use akode_protocol::mcp::RequestId as ProtocolRequestId;
use akode_rmcp_client::ElicitationAction;
use akode_rmcp_client::ElicitationResponse;
use serde_json::Value;
use std::sync::Arc;
use tracing::debug;
use tracing::info;
use tracing::warn;
pub async fn interrupt(sess: &Arc<Session>) {
sess.interrupt_task().await;
}
pub async fn clean_background_terminals(sess: &Arc<Session>) {
sess.close_unified_exec_processes().await;
}
pub async fn realtime_conversation_list_voices(sess: &Session, sub_id: String) {
sess.send_event_raw(Event {
id: sub_id,
msg: EventMsg::RealtimeConversationListVoicesResponse(
RealtimeConversationListVoicesResponseEvent {
voices: RealtimeVoicesList::builtin(),
},
),
})
.await;
}
/// Queues an inter-agent message, then lets the shared pending-work scheduler
/// decide whether an idle session should start a regular turn.
pub async fn inter_agent_communication(
sess: &Arc<Session>,
sub_id: String,
communication: crate::PendingAgentMessage,
start_options: akode_protocol::turn_input::TurnStartOptions,
) {
let trigger_turn = communication.trigger_turn;
sess.input_queue
.enqueue_mailbox_communication(communication, start_options)
.await;
crate::agent_communication::emit_agent_communication_receive(&sub_id);
if trigger_turn
|| sess.features.enabled(Feature::WakeOnAgentMessages)
|| sess.has_outstanding_durable_sleep()
{
sess.maybe_start_turn_for_pending_work_with_sub_id(sub_id)
.await;
}
}
pub async fn run_user_shell_command(
sess: &Arc<Session>,
sub_id: String,
command: String,
timeout_ms: Option<u64>,
) {
if let Some((turn_context, cancellation_token)) =
sess.active_turn_context_and_cancellation_token().await
{
let session = Arc::clone(sess);
tokio::spawn(async move {
execute_user_shell_command(
session,
turn_context,
command,
timeout_ms,
cancellation_token,
UserShellCommandMode::ActiveTurnAuxiliary,
)
.await;
});
return;
}
let turn_context = sess
.new_turn_with_default_settings(sub_id, Default::default())
.await;
sess.spawn_task(
turn_context,
Vec::new(),
UserShellCommandTask::new(command, timeout_ms),
)
.await;
}
pub async fn resolve_elicitation(
sess: &Arc<Session>,
server_name: String,
request_id: ProtocolRequestId,
decision: akode_protocol::approvals::ElicitationAction,
content: Option<Value>,
meta: Option<Value>,
) {
let action = match decision {
akode_protocol::approvals::ElicitationAction::Accept => ElicitationAction::Accept,
akode_protocol::approvals::ElicitationAction::Decline => ElicitationAction::Decline,
akode_protocol::approvals::ElicitationAction::Cancel => ElicitationAction::Cancel,
};
let content = match action {
// Preserve the legacy fallback for clients that only send an action.
ElicitationAction::Accept => Some(content.unwrap_or_else(|| serde_json::json!({}))),
ElicitationAction::Decline | ElicitationAction::Cancel => None,
_ => None,
};
let response = ElicitationResponse {
action,
content,
meta,
};
let request_id = match request_id {
ProtocolRequestId::String(value) => {
rmcp::model::NumberOrString::String(std::sync::Arc::from(value))
}
ProtocolRequestId::Integer(value) => rmcp::model::NumberOrString::Number(value),
};
if let Err(err) = sess
.resolve_elicitation(server_name, request_id, response)
.await
{
warn!(
error = %err,
"failed to resolve elicitation request in session"
);
}
}
impl Session {
/// Claim the prompt before applying a decision that can outlive the requesting execution.
pub(crate) async fn resolve_exec_approval(
self: &Arc<Self>,
approval_id: String,
turn_id: Option<String>,
decision: ReviewDecision,
) {
let Some((pending, active_turn_id)) = self
.take_pending_approval(&approval_id, turn_id.as_deref())
.await
else {
return;
};
let decision = pending.validate(decision);
if decision == ReviewDecision::Abort {
let turn_id = if pending.kind == ExecApprovalKind::HumanCommand {
Some(&pending.turn_id)
} else {
active_turn_id.as_ref()
};
if let Some(turn_id) = turn_id {
self.abort_turn_if_active(
turn_id,
TurnAbortReason::Interrupted,
/*error*/ None,
)
.await;
}
} else if let ReviewDecision::ApprovedExecpolicyAmendment {
proposed_execpolicy_amendment,
} = &decision
&& let Err(err) = self
.persist_execpolicy_amendment(proposed_execpolicy_amendment)
.await
{
let message = format!("Failed to apply execpolicy amendment: {err}");
tracing::warn!("{message}");
self.send_event_raw(Event {
id: turn_id.unwrap_or(approval_id),
msg: EventMsg::Warning(WarningEvent { message }),
})
.await;
}
let _ = pending.sender.send(decision);
}
}
async fn cancel_patch_approval(sess: &Arc<Session>, id: &str, expected_turn_id: Option<&str>) {
let Some((pending, _)) = sess.take_pending_approval(id, expected_turn_id).await else {
return;
};
sess.abort_turn_if_active(
&pending.turn_id,
TurnAbortReason::Interrupted,
/*error*/ None,
)
.await;
let _ = pending.sender.send(ReviewDecision::Abort);
}
pub async fn request_user_input_response(
sess: &Arc<Session>,
id: String,
response: RequestUserInputResponse,
) {
sess.notify_user_input_response(&id, response).await;
}
pub async fn request_permissions_response(
sess: &Arc<Session>,
id: String,
response: RequestPermissionsResponse,
) {
sess.notify_request_permissions_response(&id, response)
.await;
}
pub async fn dynamic_tool_response(sess: &Arc<Session>, id: String, response: DynamicToolResponse) {
sess.notify_dynamic_tool_response(&id, response).await;
}
pub fn refresh_mcp_servers(sess: &Session) {
sess.services.mcp_runtime.reconnect_on_next_refresh();
sess.request_mcp_runtime_refresh();
}
pub async fn reload_user_config(sess: &Arc<Session>) {
Box::pin(sess.reload_user_config_layer()).await;
}
pub async fn compact(sess: &Arc<Session>, sub_id: String) {
// Stop the old turn before the compact task picks up the next turn's environments.
sess.abort_all_tasks(TurnAbortReason::Replaced).await;
let turn_context = sess
.new_turn_with_default_settings(sub_id, Default::default())
.await;
sess.spawn_task(turn_context, Vec::new(), CompactTask).await;
}
pub(super) async fn persist_thread_memory_mode_update(
sess: &Arc<Session>,
mode: ThreadMemoryMode,
) -> anyhow::Result<()> {
let live_thread = sess.live_thread_for_persistence("update thread memory mode")?;
live_thread.persist(PersistContext::Standard).await?;
live_thread.flush().await?;
live_thread
.update_memory_mode(mode, /*include_archived*/ false)
.await?;
live_thread.flush().await?;
Ok(())
}
/// Persists thread-level memory mode metadata for the active session.
///
/// This does not involve the model and only affects whether the thread is
/// eligible for future memory generation.
pub async fn set_thread_memory_mode(sess: &Arc<Session>, sub_id: String, mode: ThreadMemoryMode) {
if let Err(err) = persist_thread_memory_mode_update(sess, mode).await {
warn!("Failed to persist thread memory mode update to rollout: {err}");
let event = Event {
id: sub_id,
msg: EventMsg::Error(ErrorEvent {
misalignment: None,
message: err.to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
rejected_audio_file_ids: Vec::new(),
}),
};
sess.send_event_raw(event).await;
}
}
pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
if let Some(reporting) = &sess.outcome_reporting {
reporting.handoffs.close();
}
let startup_prewarm = {
let mut state = sess.state.lock().await;
// Stop admission and take the current warmup together so resume cannot replace it.
state.shutting_down = true;
state.take_session_startup_prewarm()
};
if let Some(startup_prewarm) = startup_prewarm {
startup_prewarm.abort().await;
}
let _ = sess.conversation.shutdown().await;
sess.abort_all_tasks(TurnAbortReason::Interrupted).await;
if let Some(reporting) = &sess.outcome_reporting {
reporting.handoffs.wait().await;
}
super::async_compaction::shutdown(sess).await;
let shell_snapshot_prewarm = sess.state.lock().await.shell_snapshot_prewarm.take();
if let Some(shell_snapshot_prewarm) = shell_snapshot_prewarm {
shell_snapshot_prewarm.abort();
let _ = shell_snapshot_prewarm.await;
}
sess.hooks().shutdown().await;
sess.async_hook_results.close();
while sess.async_hook_results.try_recv().is_ok() {}
sess.services
.unified_exec_manager
.terminate_all_processes()
.await;
if let Err(err) = sess.services.code_mode_service.shutdown().await {
sess.services.local_agent_runtime.record_shutdown_failure(
AgentTreeShutdownFailure::operation_failed(
"session_shutdown",
"code_mode",
Some(sess.thread_id),
"code_mode_error",
),
);
warn!("failed to shutdown code mode session: {err}");
}
sess.stop_mcp_prewarm_worker().await;
{
let _refresh = sess.mcp_refresh.acquire().await;
sess.mcp_refresh.close();
sess.services.mcp_runtime.shutdown().await;
}
sess.drain_code_mode_messages().await;
crate::hook_runtime::run_session_end_hooks(sess).await;
emit_thread_stop_lifecycle(sess).await;
}
async fn emit_thread_stop_lifecycle(sess: &Session) {
for contributor in sess.services.extensions.thread_lifecycle_contributors() {
contributor
.on_thread_stop(akode_extension_api::ThreadStopInput {
session_store: &sess.services.session_extension_data,
thread_store: &sess.services.thread_extension_data,
})
.await;
}
}
pub async fn shutdown(sess: &Arc<Session>, sub_id: String) -> bool {
shutdown_session_runtime(sess).await;
info!("Shutting down Codex instance");
let history = sess.clone_history().await;
let turn_count = history
.raw_items()
.filter(|item| is_user_turn_boundary(item))
.count();
sess.services.session_telemetry.counter(
"codex.conversation.turn.count",
i64::try_from(turn_count).unwrap_or(0),
&[],
);
// Gracefully flush and shutdown thread persistence on session end so tests
// that inspect durable state do not race with the background writer.
if let Some(live_thread) = sess.live_thread()
&& let Err(e) = live_thread.shutdown().await
{
sess.services.local_agent_runtime.record_shutdown_failure(
AgentTreeShutdownFailure::operation_failed(
"session_shutdown",
"close_persistence",
Some(sess.thread_id),
thread_store_error_kind(&e),
),
);
warn!("failed to shutdown thread persistence: {e}");
let event = Event {
id: sub_id.clone(),
msg: EventMsg::Error(ErrorEvent {
misalignment: None,
message: "Failed to shutdown thread persistence".to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
rejected_audio_file_ids: Vec::new(),
}),
};
sess.send_event_raw(event).await;
}
let event = Event {
id: sub_id,
msg: EventMsg::ShutdownComplete,
};
sess.services
.rollout_thread_trace
.record_protocol_event(&event.msg);
sess.services
.rollout_thread_trace
.record_ended(akode_rollout_trace::RolloutStatus::Completed);
sess.deliver_event_raw(event).await;
true
}
pub async fn review(
sess: &Arc<Session>,
config: &Arc<Config>,
sub_id: String,
review_request: ReviewRequest,
) {
let turn_context = sess
.new_turn_with_default_settings(sub_id.clone(), Default::default())
.await;
sess.maybe_emit_model_warnings_for_turn(turn_context.as_ref())
.await;
#[allow(deprecated)]
match resolve_review_request(review_request, &turn_context.cwd) {
Ok(resolved) => {
spawn_review_thread(
Arc::clone(sess),
Arc::clone(config),
turn_context.clone(),
sub_id,
resolved,
)
.await;
}
Err(err) => {
let event = Event {
id: sub_id,
msg: EventMsg::Error(ErrorEvent {
misalignment: None,
message: err.to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
rejected_audio_file_ids: Vec::new(),
}),
};
sess.send_event(&turn_context, event.msg).await;
}
}
}
pub(super) async fn submission_loop(
sess: Arc<Session>,
config: Arc<Config>,
rx_sub: Receiver<Submission>,
) {
// Session shutdown and tree shutdown both use the existing teardown handler.
let mut shutdown_received = false;
let mut catalog_updates = sess.services.models_manager.model_catalog_updates();
if let Some(updates) = &mut catalog_updates {
// A resumed chat must also consume a catalog fetched before it was opened.
updates.mark_changed();
}
let mut mailbox = sess.input_queue.mailbox_updates();
if let Some(updates) = &mut mailbox {
updates.mark_changed();
}
loop {
let sub = tokio::select! {
biased;
_ = sess.services.local_agent_runtime.shutdown.cancelled() => {
shutdown_received = shutdown(&sess, super::new_submission_id()).await;
break;
}
update = async {
match &mut catalog_updates {
Some(updates) => updates.changed().await,
None => std::future::pending().await,
}
} => {
if update.is_err() {
catalog_updates = None;
} else {
super::model_catalog_settings::apply(&sess).await;
}
continue;
}
sub = rx_sub.recv() => match sub {
Ok(sub) => sub,
Err(_) => break,
},
update = async {
match &mut mailbox {
Some(updates) => updates.changed().await.map(|()| *updates.borrow_and_update()),
None => std::future::pending().await,
}
} => {
match update {
Ok(true) => {
sess.input_queue.notify_mailbox();
if sess.features.enabled(Feature::WakeOnAgentMessages)
|| sess.has_outstanding_durable_sleep()
{
sess.maybe_start_turn_for_pending_work().await;
}
}
Ok(false) => {}
Err(_) => mailbox = None,
}
continue;
}
};
debug!(
thread_id = %sess.thread_id(),
submission_id = %sub.id,
operation = sub.op.kind(),
parent_turn_id = ?sub.parent_turn_id,
root_turn_id = ?sub.root_turn_id,
op = ?sub.op,
"Submission"
);
let dispatch_span = submission_dispatch_span(&sub);
let should_exit = async {
match sub.op {
Op::Interrupt => {
interrupt(&sess).await;
false
}
Op::InterruptIfNoPendingInput { turn_id, reply } => {
sess.interrupt_turn_if_no_pending_input(&turn_id, reply)
.await;
false
}
Op::CleanBackgroundTerminals => {
clean_background_terminals(&sess).await;
false
}
Op::RealtimeConversationStart(params) => {
if let Err(err) =
handle_realtime_conversation_start(&sess, sub.id.clone(), params).await
{
sess.send_event_raw(Event {
id: sub.id.clone(),
msg: EventMsg::Error(ErrorEvent {
misalignment: None,
message: err.to_string(),
codex_error_info: Some(CodexErrorInfo::Other),
rejected_audio_file_ids: Vec::new(),
}),
})
.await;
}
false
}
Op::RealtimeConversationAttach { params, reply } => {
let result =
crate::realtime_conversation::handle_attach(&sess, sub.id, params).await;
let _ = reply.send(result);
false
}
Op::RealtimeConversationAttachStream {
params,
transport,
reply,
} => {
let result = crate::realtime_conversation::handle_attach_stream(
&sess, sub.id, params, transport,
)
.await;
let _ = reply.send(result);
false
}
Op::RealtimeConversationDetach {
realtime_session_id,
reply,
} => {
crate::realtime_conversation::handle_detach(
&sess,
Some(&realtime_session_id),
&sub.id,
)
.await;
let _ = reply.send(Ok(()));
false
}
Op::RealtimeConversationAudio(params) => {
handle_realtime_conversation_audio(&sess, sub.id.clone(), params).await;
false
}
Op::RealtimeConversationText(params) => {
handle_realtime_conversation_text(&sess, sub.id.clone(), params).await;
false
}
Op::RealtimeConversationSpeech(params) => {
handle_realtime_conversation_speech(&sess, sub.id.clone(), params).await;
false
}
Op::RealtimeConversationClose => {
handle_realtime_conversation_close(&sess, sub.id.clone()).await;
false
}
Op::RealtimeConversationListVoices => {
realtime_conversation_list_voices(&sess, sub.id.clone()).await;
false
}
Op::TurnInput {
request,
mode,
reply,
} => {
let request = WithTurnExtensionData {
request: *request,
turn_extension_init: sub.turn_extension_init,
};
let result = turn_input::handle(&sess, request, mode, sub.id.clone()).await;
let _ = reply.send(result);
false
}
Op::RecoverTurn {
thread_settings,
start_options,
reply,
} => {
let result = turn_input::handle_recovery(
&sess,
WithTurnExtensionData {
request: thread_settings,
turn_extension_init: sub.turn_extension_init,
},
start_options,
sub.id.clone(),
)
.await;
let _ = reply.send(result);
false
}
Op::SuspendTurnAndShutdown { reply } => {
let result =
super::turn_suspension::suspend_turn_and_shutdown(&sess, sub.id.clone())
.await;
// Exit only after history is durable and its writer has closed; an error
// must leave responsibility for the thread with the current worker.
let should_exit = matches!(
&result,
Ok(akode_protocol::turn_input::SuspendTurnOutcome::Suspended { .. })
);
let _ = reply.send(result);
should_exit
}
Op::ThreadSettings {
thread_settings,
reply,
} => {
let _settings_guard = thread_settings::acquire_persistence_lock(&sess).await;
let thread_settings = WithTurnExtensionData {
request: thread_settings,
turn_extension_init: sub.turn_extension_init,
};
match thread_settings::update(&sess, thread_settings).await {
Ok(snapshot) => {
// Reply first: the caller may hold a lock its event consumer needs.
if let Some(reply) = reply {
let _ = reply.send(Ok(()));
}
thread_settings::emit_applied(&sess, sub.id.clone(), snapshot).await;
}
Err(error) => {
let message = format!("invalid thread settings override: {error}");
if let Some(reply) = reply {
let _ = reply.send(Err(CodexErr::InvalidRequest(message)));
} else {
sess.send_event_raw(Event {
id: sub.id.clone(),
msg: EventMsg::Error(ErrorEvent {
misalignment: None,
message,
codex_error_info: Some(CodexErrorInfo::BadRequest),
rejected_audio_file_ids: Vec::new(),
}),
})
.await;
}
}
}
false
}
Op::ReplaceDynamicTools { tools, reply } => {
let _ = reply.send(sess.replace_dynamic_tools(tools).await);
false
}
Op::TurnSettings {
turn_id,
update,
reply,
} => {
let outcome = sess.apply_turn_settings(&turn_id, update).await;
let _ = reply.send(outcome);
false
}
Op::InterAgentCommunication {
communication,
start_options,
} => {
let communication =
crate::PendingAgentMessage::new(communication, sub.message_delivery);
inter_agent_communication(&sess, sub.id.clone(), communication, start_options)
.await;
false
}
Op::ExecApproval {
id: approval_id,
turn_id,
decision,
} => {
sess.resolve_exec_approval(approval_id, turn_id, decision)
.await;
false
}
Op::CancelPatchApproval { id, turn_id } => {
cancel_patch_approval(&sess, &id, Some(&turn_id)).await;
false
}
Op::PatchApproval {
id,
decision: ReviewDecision::Abort,
} => {
cancel_patch_approval(&sess, &id, /*expected_turn_id*/ None).await;
false
}
Op::PatchApproval { id, decision } => {
sess.notify_approval(&id, decision).await;
false
}
Op::UserInputAnswer { id, response } => {
request_user_input_response(&sess, id, response).await;
false
}
Op::RequestPermissionsResponse { id, response } => {
request_permissions_response(&sess, id, response).await;
false
}
Op::DynamicToolResponse { id, response } => {
dynamic_tool_response(&sess, id, response).await;
false
}
Op::RefreshMcpServers => {
refresh_mcp_servers(&sess);
false
}
Op::ReloadUserConfig => {
reload_user_config(&sess).await;
false
}
Op::Compact => {
compact(&sess, sub.id.clone()).await;
false
}
Op::SetThreadMemoryMode { mode } => {
set_thread_memory_mode(&sess, sub.id.clone(), mode).await;
false
}
Op::RunUserShellCommand {
command,
timeout_ms,
} => {
run_user_shell_command(&sess, sub.id.clone(), command, timeout_ms).await;
false
}
Op::ResolveElicitation {
server_name,
request_id,
decision,
content,
meta,
} => {
resolve_elicitation(&sess, server_name, request_id, decision, content, meta)
.await;
false
}
Op::Shutdown => shutdown(&sess, sub.id.clone()).await,
Op::Review { review_request } => {
review(&sess, &config, sub.id.clone(), review_request).await;
false
}
Op::ApproveGuardianDeniedAction { event } => {
approve_guardian_denied_action(&sess, event).await;
false
}
_ => false, // Ignore unknown ops; enum is non_exhaustive to allow extensions.
}
}
.instrument(dispatch_span)
.await;
drop(sub.residency_guard);
if should_exit {
shutdown_received = true;
break;
}
}
// If the submission loop exits because the channel closed without an
// explicit shutdown op, still run session teardown.
if !shutdown_received {
shutdown_session_runtime(&sess).await;
if let Some(live_thread) = sess.live_thread()
&& let Err(err) = live_thread.shutdown().await
{
sess.services.local_agent_runtime.record_shutdown_failure(
AgentTreeShutdownFailure::operation_failed(
"session_shutdown",
"close_persistence_after_channel_closed",
Some(sess.thread_id),
thread_store_error_kind(&err),
),
);
warn!("failed to shutdown thread persistence after submission channel closed: {err}");
}
sess.services
.rollout_thread_trace
.record_ended(akode_rollout_trace::RolloutStatus::Aborted);
}
debug!("Agent loop exited");
}
async fn approve_guardian_denied_action(sess: &Arc<Session>, event: GuardianAssessmentEvent) {
if event.status != GuardianAssessmentStatus::Denied {
warn!(
review_id = event.id.as_str(),
"ignoring approval for non-denied Guardian assessment"
);
return;
}
let approved_action = serde_json::json!({
"action": &event.action,
"outcome": "allowed",
});
let approved_action_json = match serde_json::to_string_pretty(&approved_action) {
Ok(approved_action_json) => approved_action_json,
Err(error) => {
warn!(%error, review_id = event.id.as_str(), "failed to serialize approved Guardian action");
return;
}
};
let items = vec![ContextualUserFragment::into(GuardianApprovedAction::new(
approved_action_json,
))];
sess.inject_no_new_turn(items, /*current_turn_context*/ None)
.await;
}
pub(super) fn submission_dispatch_span(sub: &Submission) -> tracing::Span {
let op_name = sub.op.kind();
let span_name = format!("op.dispatch.{op_name}");
let dispatch_span = match &sub.op {
Op::RealtimeConversationAudio(_) => {
debug_span!(
"submission_dispatch",
otel.name = span_name.as_str(),
submission.id = sub.id.as_str(),
codex.op = op_name
)
}
_ => info_span!(
"submission_dispatch",
otel.name = span_name.as_str(),
submission.id = sub.id.as_str(),
codex.op = op_name
),
};
if let Some(trace) = sub.trace.as_ref()
&& !set_parent_from_w3c_trace_context(&dispatch_span, trace)
{
warn!(
submission.id = sub.id.as_str(),
"ignoring invalid submission trace carrier"
);
}
dispatch_span
}

View File

@@ -0,0 +1,220 @@
use super::TurnInput as PendingTurnInput;
use super::session::Session;
use super::turn_context::TurnContext;
use akode_features::Feature;
use akode_history::ResponseItemEnvelope;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::models::AudioReference;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::ModelInfo;
/// Uploaded files need the admission checks on typed turn input before entering history.
pub(crate) fn validate_injected_response_item(item: &ResponseItem) -> CodexResult<()> {
if let ResponseItem::Message { content, .. } = item
&& content.iter().any(|part| {
matches!(
part,
ContentItem::InputAudio {
audio: AudioReference::File { .. }
}
)
})
{
return Err(CodexErr::InvalidRequest(
"Uploaded audio files must be submitted as turn input.".to_string(),
));
}
Ok(())
}
impl Session {
/// Returns the input if there is no active turn to inject into.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
)]
pub(crate) async fn inject_if_running<T: Into<ResponseItemEnvelope>>(
&self,
input: Vec<T>,
) -> Result<(), Vec<T>> {
let mut active = self.active_turn.lock().await;
match active.as_mut().filter(|turn| turn.finishing.is_none()) {
Some(active_turn) => {
self.input_queue
.extend_pending_input_and_notify_for_turn_state(
active_turn.turn_state.as_ref(),
input
.into_iter()
.map(Into::into)
.map(PendingTurnInput::ResponseItem)
.collect(),
)
.await;
Ok(())
}
None => Err(input),
}
}
/// Injects hook context into the running turn atomically.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn provenance and turn state updates must remain atomic"
)]
pub(crate) async fn inject_hook_context_if_running(
&self,
input: Vec<ResponseItem>,
) -> Result<(), Vec<ResponseItem>> {
let mut active = self.active_turn.lock().await;
let Some(active_turn) = active.as_mut() else {
return Err(input);
};
if active_turn.task.is_none() {
return Err(input);
}
self.input_queue
.extend_pending_input_and_notify_for_turn_state(
active_turn.turn_state.as_ref(),
input
.into_iter()
.map(ResponseItemEnvelope::new)
.map(PendingTurnInput::ResponseItem)
.collect(),
)
.await;
Ok(())
}
/// Preserves trusted client provenance while items wait for an active turn.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
)]
pub(crate) async fn inject_client_response_items(
&self,
items: Vec<ResponseItem>,
turn_context: &TurnContext,
) {
let items = items
.into_iter()
.map(ResponseItemEnvelope::new)
.map(|item| self.annotate_client_response_item(item))
.collect::<Vec<_>>();
let mut active = self.active_turn.lock().await;
if let Some(active_turn) = active.as_mut().filter(|turn| turn.finishing.is_none()) {
self.input_queue
.extend_pending_input_and_notify_for_turn_state(
active_turn.turn_state.as_ref(),
items
.into_iter()
.map(PendingTurnInput::ResponseItem)
.collect(),
)
.await;
return;
}
let finishing = active.as_ref().and_then(|turn| turn.finishing.clone());
drop(active);
if let Some(finishing) = finishing {
finishing.cancelled().await;
}
self.record_annotated_conversation_items(turn_context, turn_context.model_info(), items)
.await;
}
pub(crate) fn annotate_client_response_item(
&self,
mut envelope: ResponseItemEnvelope,
) -> ResponseItemEnvelope {
if self.enabled(Feature::RetainClientDeveloperMessages)
&& matches!(&envelope.item, ResponseItem::Message { role, .. } if role == "developer")
{
envelope.metadata.get_or_insert_default().client_authored = true;
}
envelope
}
pub(crate) async fn record_annotated_conversation_items(
&self,
turn_context: &TurnContext,
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
) {
if items.iter().all(|item| item.metadata.is_none()) {
let items = items
.into_iter()
.map(ResponseItemEnvelope::into_item)
.collect::<Vec<_>>();
self.record_conversation_items(turn_context, model_info, &items)
.await;
return;
}
let annotated_items = self
.prepare_annotated_conversation_items_for_history(turn_context, model_info, items)
.await;
self.record_prepared_conversation_items(turn_context, model_info, annotated_items)
.await;
}
pub(crate) async fn prepare_annotated_conversation_items_for_history(
&self,
turn_context: &TurnContext,
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
) -> Vec<ResponseItemEnvelope> {
let mut annotated_items = Vec::with_capacity(items.len());
for envelope in items {
let prepared_items = self
.prepare_conversation_items_for_history(
turn_context,
model_info,
std::slice::from_ref(&envelope.item),
)
.await;
let mut metadata = envelope.metadata;
annotated_items.extend(prepared_items.into_iter().map(|item| ResponseItemEnvelope {
item,
metadata: metadata.take(),
}));
}
annotated_items
}
/// Injects items into active work, or records them without starting a turn.
pub(crate) async fn inject_no_new_turn(
&self,
items: Vec<ResponseItem>,
current_turn_context: Option<&TurnContext>,
) {
let Err(items) = self.inject_if_running(items).await else {
return;
};
let finishing = self
.active_turn
.lock()
.await
.as_ref()
.and_then(|turn| turn.finishing.clone());
if let Some(finishing) = finishing {
finishing.cancelled().await;
}
let default_turn_context;
let turn_context = match current_turn_context {
Some(turn_context) => turn_context,
None => {
default_turn_context = self.new_default_turn().await;
default_turn_context.as_ref()
}
};
self.record_conversation_items(turn_context, turn_context.model_info(), &items)
.await;
}
}
#[cfg(test)]
#[path = "inject_tests.rs"]
mod tests;

View File

@@ -0,0 +1,65 @@
use crate::session::tests::make_session_and_context_with_rx;
use akode_features::Feature;
use akode_history::CodexHarnessMetadata;
use akode_history::ResponseItemEnvelope;
use akode_history::RolloutItem;
use akode_protocol::models::ConfigurationReasoning;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::protocol::EventMsg;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn harness_authored_configuration_updates_preserve_metadata_and_resume() {
let (session, turn_context, rx_event) = make_session_and_context_with_rx().await;
assert!(!session.enabled(Feature::RetainClientDeveloperMessages));
let mut expected = ResponseItemEnvelope {
item: ResponseItem::ConfigurationUpdate {
reasoning: ConfigurationReasoning {
effort: ReasoningEffort::High,
},
},
metadata: Some(CodexHarnessMetadata {
harness_authored_configuration: true,
..Default::default()
}),
};
session
.record_annotated_conversation_items(
&turn_context,
turn_context.model_info(),
vec![expected.clone()],
)
.await;
let metadata = expected.metadata.as_mut().unwrap();
metadata.history_sequence = Some(1);
metadata.sampled_through_sequence = Some(0);
metadata.mcp_attribution = Some(
session
.services
.executed_tool_calls
.mcp_attribution_snapshot(),
);
let recorded = session.clone_history().await.into_annotated_items();
assert_eq!(recorded, vec![expected.clone()]);
let mut raw_items = Vec::new();
while let Ok(event) = rx_event.try_recv() {
if let EventMsg::RawResponseItem(event) = event.msg {
raw_items.push(event.item);
}
}
assert_eq!(raw_items, vec![expected.item]);
let rollout_items = recorded
.iter()
.cloned()
.map(RolloutItem::ResponseItem)
.collect::<Vec<_>>();
let reconstructed = session
.reconstruct_history_from_rollout(&turn_context, &rollout_items)
.await;
assert_eq!(reconstructed.history, recorded);
}

View File

@@ -0,0 +1,898 @@
use crate::agent::api::AgentControl;
use crate::agent_communication::PENDING_MAILBOX_MESSAGES;
use crate::state::ActiveTurn;
use crate::state::MailboxDeliveryPhase;
use crate::state::TurnState;
use akode_diagnostics::GaugeGuard;
use akode_history::ResponseItemEnvelope;
use akode_protocol::ThreadId;
use akode_protocol::models::ResponseItem;
use akode_protocol::turn_input::TurnStartOptions;
use akode_protocol::user_input::UserInput;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::VecDeque;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::watch;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
/// Host capture metadata belonging to one input, including steers within another turn.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserInputMetadata {
/// Private extension data carried with this queued input through completion.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub extension_data: BTreeMap<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub acceptance_order: Option<u64>,
/// Optional host-assigned UUID for this particular Responses user item.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_item_uuid: Option<uuid::Uuid>,
#[serde(
default,
skip_serializing_if = "akode_history::UserInputOrigin::is_user"
)]
pub origin: akode_history::UserInputOrigin,
}
/// Input consumed by a regular turn.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum TurnInput {
UserInput {
content: Vec<UserInput>,
client_id: Option<String>,
#[serde(flatten)]
metadata: UserInputMetadata,
},
FunctionCallOutput(#[serde(with = "turn_input_response_item")] ResponseItemEnvelope),
// Preserve the existing serialized format while carrying injection API metadata
// through the in-memory queue.
ResponseItem(#[serde(with = "turn_input_response_item")] ResponseItemEnvelope),
InterAgentCommunication(crate::PendingAgentMessage),
}
mod turn_input_response_item {
use super::ResponseItem;
use super::ResponseItemEnvelope;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::ser::Error as _;
pub(super) fn serialize<S>(
item: &ResponseItemEnvelope,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if item.metadata.is_some() {
return Err(S::Error::custom(
"annotated response items cannot cross the turn-input serialization boundary",
));
}
item.item.serialize(serializer)
}
pub(super) fn deserialize<'de, D>(deserializer: D) -> Result<ResponseItemEnvelope, D::Error>
where
D: Deserializer<'de>,
{
ResponseItem::deserialize(deserializer).map(ResponseItemEnvelope::new)
}
}
/// Steering takes precedence when several kinds of input are pending together.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) enum InputQueueActivity {
Mailbox,
Steer,
}
impl TurnInput {
fn is_queue_only_mail(&self) -> bool {
match self {
Self::InterAgentCommunication(communication) => !communication.trigger_turn,
Self::ResponseItem(ResponseItemEnvelope {
item: ResponseItem::AgentMessage { .. },
..
}) => true,
Self::UserInput { .. } | Self::FunctionCallOutput(_) | Self::ResponseItem(_) => false,
}
}
fn wait_activity(&self) -> InputQueueActivity {
match self {
Self::InterAgentCommunication(_)
| Self::ResponseItem(ResponseItemEnvelope {
item: ResponseItem::AgentMessage { .. },
..
}) => InputQueueActivity::Mailbox,
Self::UserInput { .. } | Self::FunctionCallOutput(_) | Self::ResponseItem(_) => {
InputQueueActivity::Steer
}
}
}
}
/// Turn-local pending input storage owned by the input queue flow.
#[derive(Default)]
pub(crate) struct TurnInputQueue {
items: Vec<TurnInput>,
/// Activity from notifying writes. Passive response items do not wake a wait.
notified_activity: Option<InputQueueActivity>,
}
/// Session-scoped pending input storage and active-turn mailbox delivery coordination.
pub(crate) struct InputQueue {
activity_tx: watch::Sender<InputQueueActivity>,
controller: Option<(ThreadId, Arc<dyn AgentControl>, watch::Receiver<bool>)>,
mailbox_pending_mails: Mutex<VecDeque<PendingMailboxCommunication>>,
}
pub(crate) struct PendingMailboxCommunication {
pub(crate) communication: crate::PendingAgentMessage,
start_options: TurnStartOptions,
_diagnostics_guard: GaugeGuard,
}
impl InputQueue {
pub(crate) fn new() -> Self {
let (activity_tx, _) = watch::channel(InputQueueActivity::Mailbox);
Self {
activity_tx,
controller: None,
mailbox_pending_mails: Mutex::new(VecDeque::new()),
}
}
pub(crate) fn with_controller(thread_id: ThreadId, control: Arc<dyn AgentControl>) -> Self {
let updates = control.watch_mailbox(thread_id);
Self {
controller: Some((thread_id, control, updates)),
..Self::new()
}
}
pub(crate) fn mailbox_updates(&self) -> Option<watch::Receiver<bool>> {
self.controller
.as_ref()
.map(|(_, _, updates)| updates.clone())
}
pub(crate) fn notify_mailbox(&self) {
self.activity_tx.send_replace(InputQueueActivity::Mailbox);
}
fn read_mailbox(&self, pending: &mut VecDeque<PendingMailboxCommunication>) {
if let Some((thread_id, control, _)) = &self.controller {
pending.extend(
control
.take_mailbox(*thread_id)
.into_iter()
.map(|communication| PendingMailboxCommunication {
communication,
start_options: TurnStartOptions::default(),
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
}),
);
}
}
pub(crate) async fn subscribe_activity(
&self,
turn_state: Option<&Mutex<TurnState>>,
) -> (
watch::Receiver<InputQueueActivity>,
Option<InputQueueActivity>,
) {
let activity_rx = self.activity_tx.subscribe();
let turn_activity = if let Some(turn_state) = turn_state {
turn_state.lock().await.pending_input.pending_activity()
} else {
None
};
let pending_activity = if let Some(activity) = turn_activity {
Some(activity)
} else if self.has_pending_mailbox_items().await {
Some(InputQueueActivity::Mailbox)
} else {
None
};
(activity_rx, pending_activity)
}
pub(crate) async fn enqueue_mailbox_communication(
&self,
communication: crate::PendingAgentMessage,
start_options: TurnStartOptions,
) {
let mut pending = self.mailbox_pending_mails.lock().await;
// Mail retained while unloaded precedes new submissions to the loaded session.
self.read_mailbox(&mut pending);
pending.push_back(PendingMailboxCommunication {
communication,
start_options,
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
});
self.activity_tx.send_replace(InputQueueActivity::Mailbox);
}
pub(crate) async fn has_pending_mailbox_items(&self) -> bool {
!self.mailbox_pending_mails.lock().await.is_empty()
|| self
.controller
.as_ref()
.is_some_and(|(_, _, updates)| *updates.borrow())
}
/// Native mailbox backlog qualifies regardless of turn ID or delivery phase.
/// Injected mail qualifies only while its matching turn still accepts mail.
pub(crate) async fn should_preempt_sampling_for_mail(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
sub_id: &str,
) -> bool {
if self.has_pending_mailbox_items().await {
return true;
}
let Some(turn_state) = self.turn_state_for_sub_id(active_turn, sub_id).await else {
return false;
};
let turn_state = turn_state.lock().await;
turn_state.accepts_mailbox_delivery_for_current_turn()
&& turn_state.pending_input.items.iter().any(|input| {
matches!(
input,
TurnInput::ResponseItem(ResponseItemEnvelope {
item: ResponseItem::AgentMessage { .. },
..
})
)
})
}
pub(crate) async fn has_trigger_turn_mailbox_items(&self) -> bool {
self.mailbox_pending_mails
.lock()
.await
.iter()
.any(|mail| mail.communication.trigger_turn)
}
pub(crate) async fn drain_mailbox(&self) -> Vec<PendingMailboxCommunication> {
let mut pending = self.mailbox_pending_mails.lock().await;
self.read_mailbox(&mut pending);
pending.drain(..).collect()
}
pub(crate) async fn drain_mailbox_input_items(&self) -> (Vec<TurnInput>, TurnStartOptions) {
let pending_mails = self.drain_mailbox().await;
// A later follow-up supersedes the earlier choice, including an omitted choice.
let mut start_options = pending_mails
.iter()
.rev()
.find(|mail| mail.communication.trigger_turn)
.map(|mail| mail.start_options.clone())
.unwrap_or_default();
start_options.parent_turn_id = pending_mails
.iter()
.filter(|mail| mail.communication.trigger_turn)
.map(|mail| mail.start_options.parent_turn_id.as_deref())
.reduce(|expected, candidate| expected.filter(|id| candidate == Some(*id)))
.and_then(|id| id.filter(|id| !id.trim().is_empty()).map(str::to_string));
start_options.root_turn_id = pending_mails
.iter()
.find(|mail| mail.communication.trigger_turn)
.and_then(|mail| {
mail.start_options
.parent_turn_id
.as_deref()
.filter(|id| !id.trim().is_empty())
.and(mail.start_options.root_turn_id.as_deref())
.filter(|id| !id.trim().is_empty())
})
.map(str::to_string);
let items = pending_mails
.into_iter()
.map(|mail| TurnInput::InterAgentCommunication(mail.communication))
.collect();
(items, start_options)
}
pub(crate) async fn turn_state_for_sub_id(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
sub_id: &str,
) -> Option<Arc<Mutex<TurnState>>> {
let active = active_turn.lock().await;
active.as_ref().and_then(|active_turn| {
active_turn
.task
.as_ref()
.is_some_and(|task| task.turn_context.sub_id == sub_id)
.then(|| Arc::clone(&active_turn.turn_state))
})
}
/// Signal once a user message is queued for this sampling request.
pub(crate) async fn watch_user_input(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
sub_id: &str,
interrupt: CancellationToken,
) -> Option<AbortOnDropHandle<()>> {
let turn_state = self.turn_state_for_sub_id(active_turn, sub_id).await?;
// Subscribe before inspecting the queue so an arrival cannot be missed.
let mut activity = self.activity_tx.subscribe();
Some(AbortOnDropHandle::new(tokio::spawn(async move {
loop {
if turn_state.lock().await.pending_input.has_user_input() {
interrupt.cancel();
return;
}
if activity.changed().await.is_err() {
return;
}
}
})))
}
/// Clear any pending waiters and input buffered for the current turn.
pub(crate) async fn clear_pending(&self, active_turn: &ActiveTurn) {
let mut turn_state = active_turn.turn_state.lock().await;
turn_state.clear_pending_waiters();
// Pending mail can own extension attachments whose destructors need the lock released.
let pending_input = std::mem::take(&mut turn_state.pending_input);
drop(turn_state);
drop(pending_input);
}
pub(crate) async fn defer_mailbox_delivery_to_next_turn(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
sub_id: &str,
) {
let turn_state = self.turn_state_for_sub_id(active_turn, sub_id).await;
let Some(turn_state) = turn_state else {
return;
};
let mut turn_state = turn_state.lock().await;
// Explicit same-turn work still needs a follow-up. Queue-only agent mail does not: keep
// it pending so task completion records it for the next turn without sampling again.
if turn_state
.pending_input
.items
.iter()
.any(|input| !input.is_queue_only_mail())
{
return;
}
turn_state.set_mailbox_delivery_phase(MailboxDeliveryPhase::NextTurn);
}
pub(crate) async fn accept_mailbox_delivery_for_current_turn(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
sub_id: &str,
) {
let turn_state = self.turn_state_for_sub_id(active_turn, sub_id).await;
let Some(turn_state) = turn_state else {
return;
};
self.accept_mailbox_delivery_for_turn_state(turn_state.as_ref())
.await;
}
pub(super) async fn accept_mailbox_delivery_for_turn_state(
&self,
turn_state: &Mutex<TurnState>,
) {
turn_state
.lock()
.await
.accept_mailbox_delivery_for_current_turn();
}
pub(super) async fn extend_pending_input_and_notify_for_turn_state(
&self,
turn_state: &Mutex<TurnState>,
input: Vec<TurnInput>,
) {
let activity = input.iter().map(TurnInput::wait_activity).max();
let queue_only_mail = !input.is_empty() && input.iter().all(TurnInput::is_queue_only_mail);
{
let mut turn_state = turn_state.lock().await;
turn_state.pending_input.notified_activity =
turn_state.pending_input.notified_activity.max(activity);
turn_state.pending_input.items.extend(input);
if !queue_only_mail {
turn_state.accept_mailbox_delivery_for_current_turn();
}
}
self.activity_tx
.send_replace(activity.unwrap_or(InputQueueActivity::Steer));
}
pub(crate) async fn extend_pending_input_for_turn_state(
&self,
turn_state: &Mutex<TurnState>,
input: Vec<TurnInput>,
) {
turn_state.lock().await.pending_input.items.extend(input);
}
pub(crate) async fn take_pending_input_for_turn_state(
&self,
turn_state: &Mutex<TurnState>,
) -> Vec<TurnInput> {
std::mem::take(&mut turn_state.lock().await.pending_input).items
}
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
)]
pub(crate) async fn get_pending_input(
&self,
active_turn: &Mutex<Option<ActiveTurn>>,
) -> (Vec<TurnInput>, TurnStartOptions) {
let (pending_input, accepts_mailbox_delivery) = {
let mut active = active_turn.lock().await;
match active.as_mut() {
Some(active_turn) => {
let mut turn_state = active_turn.turn_state.lock().await;
let accepts_mailbox_delivery =
turn_state.accepts_mailbox_delivery_for_current_turn();
let pending_input = if accepts_mailbox_delivery {
std::mem::take(&mut turn_state.pending_input).items
} else {
Vec::new()
};
(pending_input, accepts_mailbox_delivery)
}
None => (Vec::new(), true),
}
};
if !accepts_mailbox_delivery {
return (pending_input, TurnStartOptions::default());
}
let (mailbox_items, start_options) = self.drain_mailbox_input_items().await;
if pending_input.is_empty() {
(mailbox_items, start_options)
} else {
let mut pending_input = pending_input;
pending_input.extend(mailbox_items);
(pending_input, start_options)
}
}
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state reads must remain atomic"
)]
pub(crate) async fn has_pending_input(&self, active_turn: &Mutex<Option<ActiveTurn>>) -> bool {
let (has_turn_pending_input, accepts_mailbox_delivery) = {
let active = active_turn.lock().await;
match active.as_ref() {
Some(active_turn) => {
let turn_state = active_turn.turn_state.lock().await;
(
!turn_state.pending_input.is_empty(),
turn_state.accepts_mailbox_delivery_for_current_turn(),
)
}
None => (false, true),
}
};
if !accepts_mailbox_delivery {
return false;
}
if has_turn_pending_input {
return true;
}
self.has_pending_mailbox_items().await
}
}
impl TurnInputQueue {
fn has_user_input(&self) -> bool {
self.items
.iter()
.any(|input| matches!(input, TurnInput::UserInput { .. }))
}
pub(crate) fn is_empty(&self) -> bool {
self.items.is_empty()
}
fn pending_activity(&self) -> Option<InputQueueActivity> {
if self.notified_activity == Some(InputQueueActivity::Steer) {
return self.notified_activity;
}
self.items
.iter()
.filter(|input| !matches!(input, TurnInput::ResponseItem(_)))
.map(TurnInput::wait_activity)
.chain(self.notified_activity)
.max()
}
}
#[cfg(test)]
mod tests {
use super::*;
use akode_history::CodexHarnessMetadata;
use akode_protocol::AgentPath;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::user_input::UserInput;
use pretty_assertions::assert_eq;
#[test]
fn user_input_extension_data_round_trips_without_changing_legacy_input() {
let legacy = serde_json::json!({"UserInput": {"content": [], "client_id": "m"}});
let input: TurnInput = serde_json::from_value(legacy.clone()).unwrap();
assert_eq!(serde_json::to_value(input).unwrap(), legacy);
let mut annotated = legacy;
annotated["UserInput"]["extension_data"] = serde_json::json!({"example": ["private"]});
let input: TurnInput = serde_json::from_value(annotated.clone()).unwrap();
assert_eq!(serde_json::to_value(input).unwrap(), annotated);
}
#[test_case::test_case("ResponseItem", TurnInput::ResponseItem)]
#[test_case::test_case("FunctionCallOutput", TurnInput::FunctionCallOutput)]
fn response_item_serde_preserves_legacy_shape_and_rejects_metadata(
variant: &str,
wrap: fn(ResponseItemEnvelope) -> TurnInput,
) {
let item = ResponseItem::Other;
let input = wrap(item.clone().into());
let value = serde_json::json!({variant: item});
assert_eq!(serde_json::to_value(&input).unwrap(), value);
assert_eq!(serde_json::from_value::<TurnInput>(value).unwrap(), input);
let annotated = wrap(ResponseItemEnvelope {
item: ResponseItem::Other,
metadata: Some(CodexHarnessMetadata {
client_authored: true,
..Default::default()
}),
});
assert!(serde_json::to_value(annotated).is_err());
let forged = serde_json::json!({
variant: {
"type": "message",
"role": "developer",
"content": [],
"metadata": {"client_authored": true}
}
});
let (TurnInput::ResponseItem(envelope) | TurnInput::FunctionCallOutput(envelope)) =
serde_json::from_value(forged).unwrap()
else {
panic!("expected response item");
};
assert!(envelope.metadata.is_none());
let forged_configuration = serde_json::json!({
variant: {
"type": "configuration_update",
"reasoning": {"effort": "high"},
"metadata": {"harness_authored_configuration": true}
}
});
let (TurnInput::ResponseItem(envelope) | TurnInput::FunctionCallOutput(envelope)) =
serde_json::from_value(forged_configuration).unwrap()
else {
panic!("expected response item");
};
assert!(envelope.metadata.is_none());
}
fn make_mail(
author: AgentPath,
recipient: AgentPath,
content: &str,
trigger_turn: bool,
) -> InterAgentCommunication {
InterAgentCommunication::new(
author,
recipient,
Vec::new(),
content.to_string(),
trigger_turn,
)
}
#[tokio::test]
async fn input_queue_notifies_mailbox_subscribers() {
let input_queue = InputQueue::new();
let (mut activity_rx, pending_activity) =
input_queue.subscribe_activity(/*turn_state*/ None).await;
assert_eq!(pending_activity, None);
let mail_one = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"one",
/*trigger_turn*/ false,
);
input_queue
.enqueue_mailbox_communication(mail_one.into(), Default::default())
.await;
let mail_two = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"two",
/*trigger_turn*/ false,
);
input_queue
.enqueue_mailbox_communication(mail_two.into(), Default::default())
.await;
activity_rx.changed().await.expect("mailbox update");
assert_eq!(
*activity_rx.borrow_and_update(),
InputQueueActivity::Mailbox
);
}
#[tokio::test]
async fn input_queue_distinguishes_new_agent_input_from_pending_steering() {
let input_queue = InputQueue::new();
let turn_state = Mutex::new(TurnState::default());
let (mut activity_rx, pending_activity) =
input_queue.subscribe_activity(Some(&turn_state)).await;
assert_eq!(pending_activity, None);
input_queue
.extend_pending_input_and_notify_for_turn_state(
&turn_state,
vec![TurnInput::UserInput {
metadata: Default::default(),
content: vec![UserInput::Text {
text: "steer".to_string(),
text_elements: Vec::new(),
}],
client_id: None,
}],
)
.await;
activity_rx.changed().await.expect("steer update");
assert_eq!(*activity_rx.borrow_and_update(), InputQueueActivity::Steer);
let mail = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"follow-up",
/*trigger_turn*/ true,
);
input_queue
.extend_pending_input_and_notify_for_turn_state(
&turn_state,
vec![TurnInput::InterAgentCommunication(mail.into())],
)
.await;
activity_rx.changed().await.expect("mailbox update");
assert_eq!(
*activity_rx.borrow_and_update(),
InputQueueActivity::Mailbox
);
assert_eq!(
input_queue.subscribe_activity(Some(&turn_state)).await.1,
Some(InputQueueActivity::Steer)
);
}
#[tokio::test]
async fn input_queue_reports_already_pending_steer() {
let input_queue = InputQueue::new();
let turn_state = Mutex::new(TurnState::default());
let passive_output: TurnInput = serde_json::from_value(serde_json::json!({
"ResponseItem": {"type": "function_call_output", "name": "notify", "output": "passive"}
}))
.unwrap();
input_queue
.extend_pending_input_for_turn_state(&turn_state, vec![passive_output.clone()])
.await;
assert_eq!(
input_queue.subscribe_activity(Some(&turn_state)).await.1,
None
);
input_queue
.extend_pending_input_and_notify_for_turn_state(
&turn_state,
vec![passive_output.clone()],
)
.await;
assert_eq!(
input_queue.subscribe_activity(Some(&turn_state)).await.1,
Some(InputQueueActivity::Steer)
);
// Consuming the injection must not make later passive context wake a wait.
input_queue
.take_pending_input_for_turn_state(&turn_state)
.await;
input_queue
.extend_pending_input_for_turn_state(&turn_state, vec![passive_output])
.await;
assert_eq!(
input_queue.subscribe_activity(Some(&turn_state)).await.1,
None
);
let communication = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"already pending mail",
/*trigger_turn*/ false,
);
input_queue
.extend_pending_input_for_turn_state(
&turn_state,
vec![TurnInput::InterAgentCommunication(communication.into())],
)
.await;
assert_eq!(
input_queue.subscribe_activity(Some(&turn_state)).await.1,
Some(InputQueueActivity::Mailbox)
);
input_queue
.extend_pending_input_and_notify_for_turn_state(
&turn_state,
vec![TurnInput::UserInput {
metadata: Default::default(),
content: vec![UserInput::Text {
text: "already pending".to_string(),
text_elements: Vec::new(),
}],
client_id: None,
}],
)
.await;
let (_activity_rx, pending_activity) =
input_queue.subscribe_activity(Some(&turn_state)).await;
assert_eq!(pending_activity, Some(InputQueueActivity::Steer));
}
#[tokio::test]
async fn input_queue_drains_mailbox_in_delivery_order() {
let input_queue = InputQueue::new();
let mail_one = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"one",
/*trigger_turn*/ false,
);
let mail_two = make_mail(
AgentPath::try_from("/root/worker").expect("agent path"),
AgentPath::root(),
"two",
/*trigger_turn*/ true,
);
input_queue
.enqueue_mailbox_communication(mail_one.clone().into(), Default::default())
.await;
input_queue
.enqueue_mailbox_communication(mail_two.clone().into(), Default::default())
.await;
assert_eq!(
input_queue.drain_mailbox_input_items().await.0,
vec![
TurnInput::InterAgentCommunication(mail_one.into()),
TurnInput::InterAgentCommunication(mail_two.into())
]
);
assert!(!input_queue.has_pending_mailbox_items().await);
}
#[tokio::test]
async fn input_queue_uses_unambiguous_trigger_parent_and_first_root() {
let (parent, peer, root, root2) = (Some("a"), Some("b"), Some("r"), Some("s"));
for (pending_mails, expected_parent_turn_id, expected_root_turn_id) in [
(Vec::new(), None, None),
(vec![(false, Some("q"), root)], None, None),
(vec![(true, Some(""), root)], None, None),
(vec![(true, Some(" "), root)], None, None),
(vec![(true, None, root)], None, None),
(vec![(true, parent, None)], parent, None),
(vec![(true, parent, Some(""))], parent, None),
(vec![(true, parent, root), (true, peer, root)], None, root),
(vec![(true, parent, root), (true, peer, root2)], None, root),
(vec![(true, parent, root), (true, None, root)], None, root),
(
vec![(true, parent, root), (true, parent, root)],
parent,
root,
),
(
vec![(false, Some("q"), root2), (true, parent, root)],
parent,
root,
),
] {
let input_queue = InputQueue::new();
for (trigger_turn, parent_turn_id, root_turn_id) in pending_mails {
input_queue
.enqueue_mailbox_communication(
make_mail(AgentPath::root(), AgentPath::root(), "task", trigger_turn)
.into(),
TurnStartOptions {
parent_turn_id: parent_turn_id.map(str::to_string),
root_turn_id: root_turn_id.map(str::to_string),
..Default::default()
},
)
.await;
}
let (_, start_options) = input_queue.drain_mailbox_input_items().await;
assert_eq!(
start_options.parent_turn_id.as_deref(),
expected_parent_turn_id
);
assert_eq!(start_options.root_turn_id.as_deref(), expected_root_turn_id);
}
}
#[tokio::test]
async fn input_queue_uses_latest_followup_choice_and_ignores_queue_only_mail() {
for latest in [Some("latest"), None] {
let input_queue = InputQueue::new();
for (trigger_turn, service_tier) in [
(true, Some("first")),
(true, latest),
(false, Some("queue-only")),
] {
input_queue
.enqueue_mailbox_communication(
make_mail(AgentPath::root(), AgentPath::root(), "task", trigger_turn)
.into(),
TurnStartOptions {
service_tier: service_tier.map(str::to_owned),
..Default::default()
},
)
.await;
}
let (_, start_options) = input_queue.drain_mailbox_input_items().await;
assert_eq!(start_options.service_tier.as_deref(), latest);
}
}
#[tokio::test]
async fn input_queue_tracks_pending_trigger_turn_mail() {
let input_queue = InputQueue::new();
let queued_mail = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"queued",
/*trigger_turn*/ false,
);
input_queue
.enqueue_mailbox_communication(queued_mail.into(), Default::default())
.await;
assert!(!input_queue.has_trigger_turn_mailbox_items().await);
let trigger_mail = make_mail(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("agent path"),
"wake",
/*trigger_turn*/ true,
);
input_queue
.enqueue_mailbox_communication(trigger_mail.into(), Default::default())
.await;
assert!(input_queue.has_trigger_turn_mailbox_items().await);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
//! Best-effort MCP prewarming.
//!
//! A bounded channel coalesces refresh requests. The worker only prepares the
//! newest thread state; exact model steps remain the correctness path.
use super::*;
impl Session {
pub(crate) fn request_mcp_runtime_refresh(&self) {
// Plugin changes can reuse connections but still change their skill resources.
self.services.mcp_runtime.invalidate_resource_caches();
self.request_mcp_runtime_reprojection();
}
/// Reproject contributor state without invalidating cached MCP resources.
pub(crate) fn request_mcp_runtime_reprojection(&self) {
self.mark_mcp_runtime_dirty();
self.schedule_mcp_prewarm();
}
pub(super) fn start_mcp_prewarm_worker(
self: &Arc<Self>,
requests: async_channel::Receiver<()>,
mut auth_changes: tokio::sync::watch::Receiver<u64>,
) {
let session = Arc::downgrade(self);
let shutdown = self.mcp_prewarm_shutdown.clone();
let worker = self.services.runtime_handle.spawn(async move {
loop {
let auth_changed = tokio::select! {
biased;
_ = shutdown.cancelled() => break,
request = requests.recv() => {
if request.is_err() {
break;
}
false
},
auth_change = auth_changes.changed() => {
if auth_change.is_err() {
break;
}
true
},
};
let Some(session) = session.upgrade() else {
break;
};
if auth_changed {
session.mark_mcp_runtime_dirty();
}
tokio::select! {
biased;
_ = shutdown.cancelled() => break,
_ = session.refresh_mcp_if_dirty() => {},
}
}
});
*self
.mcp_prewarm_task
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(worker);
}
pub(super) fn schedule_mcp_prewarm(&self) {
let _ = self.mcp_prewarm_tx.try_send(());
}
pub(super) async fn stop_mcp_prewarm_worker(&self) {
self.mcp_prewarm_shutdown.cancel();
let worker = self
.mcp_prewarm_task
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
if let Some(worker) = worker
&& let Err(error) = worker.await
{
warn!(%error, "MCP prewarm worker stopped unexpectedly");
}
}
}

View File

@@ -0,0 +1,60 @@
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use tokio::sync::AcquireError;
use tokio::sync::Semaphore;
use tokio::sync::SemaphorePermit;
/// Owns MCP invalidation and the single gate used to publish runtime updates.
pub(super) struct McpRefresh {
pending: AtomicBool,
gate: Semaphore,
}
impl McpRefresh {
pub(super) fn new() -> Self {
Self {
pending: AtomicBool::new(false),
gate: Semaphore::new(/*permits*/ 1),
}
}
pub(super) fn invalidate(&self) {
self.pending.store(true, Ordering::Release);
}
#[cfg(test)]
pub(super) fn is_pending(&self) -> bool {
self.pending.load(Ordering::Acquire)
}
pub(super) fn claim(&self) -> bool {
self.pending.swap(false, Ordering::AcqRel)
}
#[tracing::instrument(name = "mcp.runtime.refresh_wait", skip_all)]
pub(super) async fn acquire(&self) -> Result<SemaphorePermit<'_>, AcquireError> {
self.gate.acquire().await
}
pub(super) fn close(&self) {
self.gate.close();
}
}
/// Restores a claimed refresh when its task is cancelled before publication.
pub(super) struct McpRefreshInvalidationGuard<'a> {
pub(super) refresh: &'a McpRefresh,
pub(super) published: bool,
}
impl Drop for McpRefreshInvalidationGuard<'_> {
fn drop(&mut self) {
if !self.published {
self.refresh.invalidate();
}
}
}
#[cfg(test)]
#[path = "mcp_refresh_tests.rs"]
mod tests;

View File

@@ -0,0 +1,27 @@
//! Checks that successful refreshes preserve newly pending work.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn successful_manual_claim_consumes_only_preexisting_work() {
for initially_pending in [false, true] {
for invalidated_during_refresh in [false, true] {
let refresh = McpRefresh::new();
if initially_pending {
refresh.invalidate();
}
assert_eq!(refresh.claim(), initially_pending);
let mut guard = McpRefreshInvalidationGuard {
refresh: &refresh,
published: false,
};
if invalidated_during_refresh {
refresh.invalidate();
}
guard.published = true;
drop(guard);
assert_eq!(refresh.is_pending(), invalidated_during_refresh);
}
}
}

View File

@@ -0,0 +1,396 @@
//! Thread MCP runtime projection and publication.
//!
//! This module owns the small correctness boundary between immutable session
//! inputs and the mutable [`akode_mcp::McpRuntime`]. Background scheduling
//! belongs elsewhere.
use super::session::SessionConfiguration;
use super::*;
use crate::mcp::McpRuntimeProjection;
use akode_config::McpServerDisabledReason;
use akode_config::McpServerTransportConfig;
use akode_file_system::WindowsSandboxSelection;
use akode_mcp::ElicitationReviewerHandle;
use akode_mcp::McpServerRegistration;
use akode_mcp::McpServerSource;
use akode_mcp::McpStartupPolicy;
use akode_mcp::PreparedMcpCall;
use akode_mcp::ToolInfo;
use akode_otel::auth_storage::AuthStorageOriginator;
use akode_protocol::capabilities::SelectedCapabilityRoot;
use std::collections::HashSet;
pub(super) struct McpDesiredState {
pub(super) config: Arc<Config>,
pub(super) auth: Option<CodexAuth>,
pub(super) submit_id: String,
pub(super) originator: String,
pub(super) session_source: SessionSource,
pub(super) environments: TurnEnvironmentSnapshot,
pub(super) local_process_cwd: PathBuf,
pub(super) disabled_plugin_ids: Vec<String>,
}
impl Session {
pub(super) fn mcp_inputs_differ(
&self,
current: &SessionConfiguration,
next: &SessionConfiguration,
) -> bool {
current.cwd() != next.cwd()
|| current.runtime_workspace_roots != next.runtime_workspace_roots
|| current.step_settings.approval_policy.value()
!= next.step_settings.approval_policy.value()
|| current.step_settings.approvals_reviewer != next.step_settings.approvals_reviewer
|| current.permission_profile() != next.permission_profile()
|| current.windows_sandbox_level != next.windows_sandbox_level
}
/// Waits on this session's refreshed server before tool execution is admitted.
pub(crate) async fn wait_for_mcp_server(self: &Arc<Self>, server: &str) {
self.refresh_mcp_if_dirty().await;
self.services
.mcp_runtime
.wait_for_server_startup(server)
.await;
}
/// Captures this session's current MCP client and catalog for one tool call.
pub(crate) async fn prepare_mcp_call(
self: &Arc<Self>,
advertised_tool: &ToolInfo,
) -> anyhow::Result<PreparedMcpCall> {
self.refresh_mcp_if_dirty().await;
self.services
.mcp_runtime
.prepare_call(advertised_tool)
.await
}
pub(super) async fn latest_mcp_desired_state(
&self,
auth: Option<CodexAuth>,
environments: TurnEnvironmentSnapshot,
) -> McpDesiredState {
let (session_configuration, disabled_plugin_ids) = {
let state = self.state.lock().await;
(
state.session_configuration.clone(),
state.active_disabled_plugin_ids.clone(),
)
};
let config =
self.build_per_turn_config(&session_configuration, environments.local_selection());
let local_process_cwd = config.cwd.to_path_buf();
McpDesiredState {
config: Arc::new(config),
auth,
submit_id: self.next_internal_sub_id(),
originator: session_configuration.originator,
session_source: session_configuration.session_source,
environments,
local_process_cwd,
disabled_plugin_ids,
}
}
pub(super) async fn install_initial_mcp_runtime(
self: &Arc<Self>,
session_configuration: &SessionConfiguration,
auth: Option<CodexAuth>,
mcp_projection: McpRuntimeProjection,
resolved_environments: &TurnEnvironmentSnapshot,
) -> anyhow::Result<()> {
let config = self.build_per_turn_config(
session_configuration,
resolved_environments.local_selection(),
);
let local_process_cwd = config.cwd.to_path_buf();
let desired = McpDesiredState {
config: Arc::new(config),
auth,
submit_id: INITIAL_SUBMIT_ID.to_owned(),
originator: session_configuration.originator.clone(),
session_source: session_configuration.session_source.clone(),
environments: resolved_environments.clone(),
local_process_cwd,
disabled_plugin_ids: session_configuration.disabled_plugin_ids.clone(),
};
self.publish_mcp_runtime(
&desired,
mcp_projection,
/*ready_selected_capability_roots*/ &[],
Some(self.mcp_elicitation_reviewer()),
)
.instrument(info_span!(
"session_init.mcp_manager_init",
otel.name = "session_init.mcp_manager_init",
))
.await;
self.services.mcp_runtime.validate_required_servers().await
}
/// Adds effective executor-owned configuration from this exact thread snapshot.
pub(super) fn project_selected_environment_mcp_servers<'a>(
&'a self,
config: &'a Config,
environments: &'a TurnEnvironmentSnapshot,
mut projection: McpRuntimeProjection,
) -> BoxFuture<'a, McpRuntimeProjection> {
Box::pin(async move {
if self.isolation == akode_extension_api::SessionIsolation::Isolated
|| self
.services
.mcp_thread_init
.get::<crate::mcp::McpServersDisabled>()
.is_some()
{
return projection;
}
let mut catalog = None;
let mut registered = HashSet::new();
for selected in environments.turn_environments() {
let environment = selected.environment();
if !environment.is_remote() {
continue;
}
let environment_id = &selected.selection.environment_id;
let discovery = environment
.discover_http_mcp_servers(selected.cwd().clone())
.await;
let outcome = if discovery.is_ok() {
"success"
} else {
"error"
};
// Count completed discovery attempts, including refreshes, before host policy
// or MCP startup determines whether the server's tools become available.
self.services.session_telemetry.counter(
"codex.mcp.executor_discovery",
/*inc*/ 1,
&[("outcome", outcome)],
);
let servers = match discovery {
Ok(servers) => servers,
Err(error) => {
tracing::warn!(
environment_id,
%error,
"failed to discover executor-local MCP servers"
);
continue;
}
};
for (name, mut server) in servers {
let outcome = if server.enabled {
"found"
} else {
"unavailable"
};
self.services.session_telemetry.counter(
"codex.mcp.executor_discovery.server",
/*inc*/ 1,
&[("server_name", name.as_str()), ("outcome", outcome)],
);
if !server.is_local_environment()
|| projection
.config
.mcp_server_catalog
.server(&name)
.is_some_and(|existing| {
existing.config().environment_id != *environment_id
|| !matches!(
existing.source(),
McpServerSource::Plugin(_)
| McpServerSource::SelectedPlugin(_)
)
})
|| registered.contains(&name)
{
continue;
}
let McpServerTransportConfig::StreamableHttp {
env_http_headers,
http_headers_helper,
..
} = &server.transport
else {
continue;
};
if http_headers_helper.is_some()
|| env_http_headers
.as_ref()
.is_some_and(|headers| !headers.is_empty())
{
tracing::warn!(
environment_id,
server = name,
"executor-local HTTP header helpers are not supported"
);
continue;
}
server.environment_id = environment_id.clone();
if let Some(requirements) = config
.config_layer_stack
.requirements()
.mcp_servers
.as_ref()
&& !requirements
.value
.get(&name)
.is_some_and(|requirement| server.matches_requirement(requirement))
{
server.enabled = false;
server.disabled_reason = Some(McpServerDisabledReason::Requirements {
source: requirements.source.clone(),
});
}
registered.insert(name.clone());
catalog
.get_or_insert_with(|| projection.config.mcp_server_catalog.to_builder())
.register(McpServerRegistration::from_executor_config(name, server));
}
}
if let Some(catalog) = catalog {
let selections = environments.all_selections();
let environment_scope = McpEnvironmentScope::Selected(&selections);
projection.config.mcp_server_catalog =
catalog.build_with_environment_authority(|environment_id| {
environment_scope.authority_for(environment_id)
});
}
projection
})
}
#[tracing::instrument(name = "mcp.runtime.refresh", skip_all)]
pub(super) async fn publish_mcp_runtime(
&self,
desired: &McpDesiredState,
mcp_projection: McpRuntimeProjection,
ready_selected_capability_roots: &[SelectedCapabilityRoot],
elicitation_reviewer: Option<ElicitationReviewerHandle>,
) {
let mcp_projection = self
.project_selected_environment_mcp_servers(
&desired.config,
&desired.environments,
mcp_projection,
)
.await;
let selected_plugins = mcp_projection.selected_plugins.clone();
let input = self.build_mcp_runtime_input(
desired,
mcp_projection,
ready_selected_capability_roots,
elicitation_reviewer,
);
AuthStorageOriginator::from_client_name(&desired.originator)
.scope(self.services.mcp_runtime.replace(input))
.await;
self.services.thread_extension_data.insert(selected_plugins);
}
pub(super) fn build_mcp_runtime_input(
&self,
desired: &McpDesiredState,
mcp_projection: McpRuntimeProjection,
ready_selected_capability_roots: &[SelectedCapabilityRoot],
elicitation_reviewer: Option<ElicitationReviewerHandle>,
) -> McpRuntimeInput {
let auth = desired.auth.clone();
let McpRuntimeProjection {
mut config,
plugins_available,
selected_plugins: _,
} = mcp_projection;
config.approval_policy = desired.config.permissions.approval_policy.clone();
config.permission_profile = desired.config.permissions.effective_permission_profile();
config.host_cwd = desired.config.cwd.clone();
config.approvals_reviewer = desired.config.approvals_reviewer;
config.environment_cwds = desired
.environments
.turn_environments()
.map(|environment| {
(
environment.selection.environment_id.clone(),
environment.cwd().clone(),
)
})
.collect();
config
.environment_cwds
.entry(akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string())
.or_insert_with(|| PathUri::from_abs_path(&desired.config.cwd));
config.environment_use_mxc = desired
.environments
.turn_environments()
.map(|environment| {
(
environment.selection.environment_id.clone(),
environment.windows_sandbox_selection_for_turn_metadata()
== WindowsSandboxSelection::Mxc,
)
})
.collect();
config
.environment_use_mxc
.entry(akode_config::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string())
.or_insert(
cfg!(windows)
&& desired.config.effective_local_windows_sandbox_type()
== SandboxType::WindowsMxc,
);
let mcp_servers = effective_mcp_servers(&config, auth.as_ref());
config.set_server_permissions(
&mcp_servers,
desired.environments.turn_environments().map(|environment| {
// Freeze the executor paths used to interpret this profile with the MCP call.
let mut sandbox = environment.sandbox_context(/*additional_permissions*/ None);
sandbox.permissions = sandbox
.permissions
.materialize_project_roots_with_path_uris(&sandbox.workspace_roots);
(
environment.selection.environment_id.clone(),
Arc::new(sandbox),
)
}),
);
let mcp_config = Arc::new(config);
let runtime_context =
self.mcp_runtime_context(&desired.environments, &desired.local_process_cwd);
McpRuntimeInput {
network_policy_metadata: None,
startup_policy: if matches!(desired.session_source, SessionSource::SubAgent(_)) {
McpStartupPolicy::DeferCachedServers
} else if desired
.config
.features
.enabled(Feature::McpLazyStdioStartup)
{
McpStartupPolicy::DeferCachedStdio
} else {
McpStartupPolicy::Eager
},
config: mcp_config,
plugins_available,
ready_selected_capability_roots: ready_selected_capability_roots.to_vec(),
mcp_servers,
submit_id: desired.submit_id.clone(),
tx_event: Some(self.get_tx_event()),
startup_cancellation_token: CancellationToken::new(),
runtime_context,
tool_catalog_cache: self.services.mcp_manager.tool_catalog_cache(),
client_mcp_extensions: self.services.client_mcp_extensions.for_mcp_servers(),
auth,
auth_manager: Some(Arc::clone(&self.services.auth_manager)),
elicitation_reviewer,
elicitation_lifecycle: Some(self.mcp_elicitation_lifecycle()),
}
}
}

View File

@@ -0,0 +1,60 @@
use super::*;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn plugin_install_elicitation_telemetry_metadata_requires_install_tool_suggestion() {
let event = EventMsg::ElicitationRequest(ElicitationRequestEvent {
turn_id: Some("turn-1".to_string()),
server_name: "codex_apps".to_string(),
id: akode_protocol::mcp::RequestId::String("request-1".to_string()),
request: akode_protocol::approvals::ElicitationRequest::Form {
meta: Some(json!({
"codex_approval_kind": "tool_suggestion",
"suggest_type": "install",
"tool_type": "plugin",
"tool_id": "slack@openai-curated",
"tool_name": "Slack",
})),
message: "Install Slack?".to_string(),
requested_schema: json!({
"type": "object",
"properties": {},
}),
},
});
assert_eq!(
plugin_install_elicitation_telemetry_metadata(&event),
Some(PluginInstallElicitationTelemetryMetadata {
tool_type: "plugin".to_string(),
tool_id: "slack@openai-curated".to_string(),
tool_name: "Slack".to_string(),
})
);
let enable_event = EventMsg::ElicitationRequest(ElicitationRequestEvent {
turn_id: Some("turn-1".to_string()),
server_name: "codex_apps".to_string(),
id: akode_protocol::mcp::RequestId::String("request-2".to_string()),
request: akode_protocol::approvals::ElicitationRequest::Form {
meta: Some(json!({
"codex_approval_kind": "tool_suggestion",
"suggest_type": "enable",
"tool_type": "plugin",
"tool_id": "slack@openai-curated",
"tool_name": "Slack",
})),
message: "Enable Slack?".to_string(),
requested_schema: json!({
"type": "object",
"properties": {},
}),
},
});
assert_eq!(
plugin_install_elicitation_telemetry_metadata(&enable_event),
None
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,88 @@
//! Keep saved chat choices within the latest successfully fetched provider catalog.
//! Running steps retain their captured settings; changes apply to the next turn.
use super::session::Session;
use super::session::SessionSettingsUpdate;
use super::step_settings::StepSettings;
use super::thread_settings;
use akode_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ReasoningEffort;
use std::sync::Arc;
pub(super) async fn apply(session: &Session) {
let _settings_guard = thread_settings::acquire_persistence_lock(session).await;
let Ok(Some(commit)) = session
.update_settings_if(SessionSettingsUpdate::default(), |current, updated| {
current.step_settings != updated.step_settings
})
.await
else {
return;
};
thread_settings::emit_applied(session, super::new_submission_id(), commit.snapshot).await;
}
pub(super) fn normalize(settings: &mut Arc<StepSettings>, catalog: &[ModelInfo]) {
let Some(model) = catalog
.iter()
.find(|model| model.slug == settings.collaboration_mode.model())
else {
return;
};
let effort = settings.collaboration_mode.reasoning_effort();
let allowed = &model.supported_reasoning_levels;
if let Some(effort) = effort
&& !allowed.is_empty()
&& !allowed.iter().any(|preset| preset.effort == effort)
{
let replacement = effort_rank(&effort)
.and_then(|previous| {
allowed
.iter()
.filter_map(|preset| {
effort_rank(&preset.effort)
.filter(|rank| *rank <= previous)
.map(|rank| (rank, &preset.effort))
})
.max_by_key(|(rank, _)| *rank)
.map(|(_, effort)| effort)
})
.or_else(|| {
matches!(effort, ReasoningEffort::Ultra | ReasoningEffort::Persistent)
.then(|| model.default_reasoning_level.as_ref())
.flatten()
.filter(|default| allowed.iter().any(|preset| &preset.effort == *default))
});
if let Some(replacement) = replacement {
Arc::make_mut(settings)
.collaboration_mode
.settings
.reasoning_effort = Some(replacement.clone());
}
}
if let Some(tier) = settings.service_tier.as_deref()
&& matches!(tier, "priority" | "ultrafast")
&& !model.supports_service_tier(tier)
{
Arc::make_mut(settings).service_tier = Some(SERVICE_TIER_DEFAULT_REQUEST_VALUE.into());
}
}
fn effort_rank(effort: &ReasoningEffort) -> Option<usize> {
match effort {
ReasoningEffort::None => Some(0),
ReasoningEffort::Minimal => Some(1),
ReasoningEffort::Low => Some(2),
ReasoningEffort::Medium => Some(3),
ReasoningEffort::High => Some(4),
ReasoningEffort::XHigh => Some(5),
ReasoningEffort::Max => Some(6),
ReasoningEffort::Ultra | ReasoningEffort::Persistent | ReasoningEffort::Custom(_) => None,
}
}
#[cfg(test)]
#[path = "model_catalog_settings_tests.rs"]
mod tests;

View File

@@ -0,0 +1,66 @@
//! The catalog correction policy preserves valid choices and avoids guessing special modes.
use super::normalize;
use crate::session::tests::make_session_configuration_for_tests;
use akode_models_manager::bundled_models_response;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::openai_models::ReasoningEffortPreset;
use pretty_assertions::assert_eq;
use std::sync::Arc;
#[test_case::test_case("lower")]
#[test_case::test_case("valid")]
#[test_case::test_case("missing-model")]
#[test_case::test_case("no-efforts")]
#[test_case::test_case("only-higher")]
#[test_case::test_case("special")]
#[test_case::test_case("invalid-persistent")]
#[test_case::test_case("invalid-ultra")]
#[test_case::test_case("unknown")]
#[tokio::test]
async fn correction_changes_only_supported_bounded_choices(scenario: &str) {
let mut settings = make_session_configuration_for_tests().await.step_settings;
let previous = match scenario {
"special" | "invalid-persistent" => ReasoningEffort::Persistent,
"invalid-ultra" => ReasoningEffort::Ultra,
"unknown" => ReasoningEffort::Custom("future-effort".into()),
_ => ReasoningEffort::High,
};
Arc::make_mut(&mut settings)
.collaboration_mode
.settings
.reasoning_effort = Some(previous);
Arc::make_mut(&mut settings).service_tier = Some("priority".into());
let mut expected = settings.clone();
let mut model = bundled_models_response().unwrap().models.remove(0);
model.slug = settings.collaboration_mode.model().into();
model.service_tiers.clear();
model.default_reasoning_level = Some(ReasoningEffort::Low);
let allowed = match scenario {
"valid" => ReasoningEffort::High,
"only-higher" => ReasoningEffort::Max,
"special" => ReasoningEffort::Persistent,
_ => ReasoningEffort::Low,
};
model.supported_reasoning_levels = vec![ReasoningEffortPreset {
description: allowed.to_string(),
effort: allowed,
}];
if scenario == "missing-model" {
model.slug = "another-model".into();
}
if scenario == "no-efforts" {
model.supported_reasoning_levels.clear();
}
if matches!(scenario, "lower" | "invalid-persistent" | "invalid-ultra") {
Arc::make_mut(&mut expected)
.collaboration_mode
.settings
.reasoning_effort = Some(ReasoningEffort::Low);
}
if scenario != "missing-model" {
Arc::make_mut(&mut expected).service_tier = Some("default".into());
}
normalize(&mut settings, &[model]);
assert_eq!(settings, expected);
}

View File

@@ -0,0 +1,138 @@
use crate::agent::types::ResolvedMultiAgentV2UsageHints;
use crate::config::MultiAgentV2Config;
use crate::context::MultiAgentRoleInstructions;
use crate::session::step_context::StepContext;
use akode_prompts::ResolvedMessage;
use akode_prompts::ResolvedModelMessages;
use akode_prompts::ResolvedMultiAgentMessages;
use akode_protocol::config_types::MultiAgentMode;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::protocol::MultiAgentVersion;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
const HOSTED_MULTI_AGENT_SKILL_GUIDANCE: &str = "Before calling any multi-agent tool, read the full multi-agent skill using its listed package locator. Skip the read only if the full skill text is already in your current context. If the read fails, make note of the blocker.";
pub(super) fn usage_hint_text(step_context: &StepContext) -> Option<MultiAgentRoleInstructions> {
let turn_context = step_context.turn.as_ref();
if turn_context.multi_agent_version != MultiAgentVersion::V2 {
return None;
}
let multi_agent_messages =
ResolvedModelMessages::from_model(&step_context.settings.model_info).multi_agent();
let snapshot = resolve_usage_hints(
&turn_context.config.multi_agent_v2,
multi_agent_messages,
!turn_context.config.update_plan_enabled && turn_context.config.model_catalog.is_none(),
);
match &turn_context.session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. }) => snapshot.subagent,
SessionSource::Cli
| SessionSource::VSCode
| SessionSource::Exec
| SessionSource::Mcp
| SessionSource::Custom(_)
| SessionSource::Unknown => snapshot.root,
SessionSource::Internal(_) | SessionSource::SubAgent(_) => None,
}
}
pub(crate) fn resolve_usage_hints(
config: &MultiAgentV2Config,
multi_agent_messages: ResolvedMultiAgentMessages<'_>,
omit_update_plan_instructions: bool,
) -> ResolvedMultiAgentV2UsageHints {
let resolve_role = |configured: Option<&str>, message: ResolvedMessage<'_>| {
// Configured roles take precedence; empty configured or catalog roles suppress fallback.
if let Some(configured) = configured {
return (!configured.is_empty())
.then(|| MultiAgentRoleInstructions::Configured(configured.to_owned()));
}
let base = message.text();
if base.is_empty() {
return None;
}
if config.disable_native_tools {
return None;
}
Some(MultiAgentRoleInstructions::Composed {
base: base.to_owned(),
marked: message.catalog_override().is_some(),
omit_update_plan_instructions,
max_concurrency: config.max_concurrent_threads_per_session,
wait_agent_enabled: config.wait_agent_enabled,
expose_model_overrides: config.expose_spawn_agent_model_overrides,
})
};
ResolvedMultiAgentV2UsageHints {
root: resolve_role(
config.root_agent_usage_hint_text.as_deref(),
multi_agent_messages.root,
),
subagent: resolve_role(
config.subagent_usage_hint_text.as_deref(),
multi_agent_messages.subagent,
),
}
}
pub(crate) fn effective_multi_agent_mode(step_context: &StepContext) -> Option<MultiAgentMode> {
let turn_context = step_context.turn.as_ref();
let settings = &step_context.settings;
if turn_context.multi_agent_version != MultiAgentVersion::V2 {
return None;
}
let config = &turn_context.config.multi_agent_v2;
let model_messages = if config.disable_native_tools {
ResolvedModelMessages::bundled()
} else {
ResolvedModelMessages::from_model(&settings.model_info)
};
let multi_agent_messages = model_messages.multi_agent();
let hint = config
.multi_agent_mode_hint_text
.as_deref()
.or(multi_agent_messages.hint);
let multi_agent_mode = match hint {
Some(text) => MultiAgentMode::Custom(text.to_owned()),
None => {
let (message, builtin) =
if settings.effective_reasoning_effort() == Some(ReasoningEffort::Ultra) {
(multi_agent_messages.proactive, MultiAgentMode::Proactive)
} else {
(
multi_agent_messages.explicit,
MultiAgentMode::ExplicitRequestOnly,
)
};
if config.disable_native_tools {
let policy = message
.text()
.replace("collaboration tools", "multi-agent tools");
MultiAgentMode::Custom(format!(
"\n{policy}\n\n{HOSTED_MULTI_AGENT_SKILL_GUIDANCE}\n"
))
} else {
match message {
ResolvedMessage::Catalog(text) => MultiAgentMode::Custom(text.to_owned()),
ResolvedMessage::Bundled(_) => builtin,
}
}
}
};
match &turn_context.session_source {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
| SessionSource::Cli
| SessionSource::VSCode
| SessionSource::Exec
| SessionSource::Mcp
| SessionSource::Custom(_)
| SessionSource::Unknown => Some(multi_agent_mode),
SessionSource::Internal(_) | SessionSource::SubAgent(_) => None,
}
}

View File

@@ -0,0 +1,188 @@
#![cfg(test)]
//! Compares session network enforcement with the policy sent to MCP servers.
use super::*;
use pretty_assertions::assert_eq;
use test_case::test_case;
#[test_case("1.1.1.1", "8.8.8.8", Decision::Allow; "stale grant")]
#[test_case("1.1.1.1.", "8.8.8.8", Decision::Allow; "equivalent managed spelling")]
#[test_case("1.1.1.1", "bad{host}", Decision::Forbidden; "malformed denial")]
#[tokio::test]
async fn stale_saved_grant_keeps_valid_denial_on_native_proxy_and_mcp(
configured: &str,
host: &str,
decision: Decision,
) -> anyhow::Result<()> {
let permission_profile = PermissionProfile::workspace_write();
let spec = crate::config::NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig::default(),
Some(NetworkConstraints {
enabled: Some(true),
domains: Some(NetworkDomainPermissionsToml {
entries: std::collections::BTreeMap::from([(
configured.to_string(),
NetworkDomainPermissionToml::Allow,
)]),
}),
managed_allowed_domains_only: Some(true),
..Default::default()
}),
&permission_profile,
)?;
let mut exec_policy = Policy::empty();
exec_policy.add_network_rule(
host,
NetworkRuleProtocol::Https,
decision,
/*justification*/ None,
)?;
exec_policy.add_network_rule(
"1.1.1.1",
NetworkRuleProtocol::Https,
Decision::Forbidden,
/*justification*/ None,
)?;
let (started_proxy, _) = Session::start_managed_network_proxy(
&spec,
&exec_policy,
&permission_profile,
SandboxType::None,
/*network_policy_decider*/ None,
/*blocked_request_observer*/ None,
/*managed_network_requirements_enabled*/ false,
crate::config::NetworkProxyAuditMetadata::default(),
)
.await?;
let native = started_proxy.proxy().current_cfg().await?;
let mcp = crate::config::NetworkProxySpec::mcp_network_policy(
Some(&spec),
&permission_profile,
crate::config::McpNetworkRoute {
primary_allows_proxy: true,
local_binding: akode_network_proxy::LocalBindingPolicy::DefaultFalse,
owner: None,
},
&permission_profile,
AskForApproval::OnRequest,
&exec_policy,
)?;
let native_domains = (
native.allowed_domains().unwrap_or_default(),
native.denied_domains().unwrap_or_default(),
);
assert_eq!(native_domains.1, ["1.1.1.1"]);
assert!(native_domains.0.iter().all(|host| host == configured));
assert!(mcp.enabled && mcp.hard_deny_allowlist_misses);
assert_eq!((mcp.allowed_domains, mcp.denied_domains), native_domains);
Ok(())
}
#[test_case(true; "shared proxy")]
#[test_case(false; "owner proxy without controller")]
#[tokio::test]
async fn failed_network_rule_write_keeps_native_denial_in_mcp_policy(
shared_proxy: bool,
) -> anyhow::Result<()> {
const DENIED: &str = "denied.example";
const GRANTED: &str = "granted.example";
let home = tempfile::tempdir()?;
let profile = PermissionProfile::workspace_write();
let mut network = NetworkProxyConfig {
enabled: true,
allow_local_binding: Some(true),
..Default::default()
};
network.set_allowed_domains(vec![DENIED.to_owned()]);
let spec = crate::config::NetworkProxySpec::from_config_and_constraints(
network, /*requirements*/ None, &profile,
)?;
let controller = shared_proxy.then_some(&spec);
let owner = (!shared_proxy).then(|| spec.environment_policy());
let binding = akode_network_proxy::LocalBindingPolicy::DefaultFalse;
let session = make_session_with_config(|config| {
config.codex_home = home.path().abs();
config
.permissions
.set_permission_profile(profile.clone())
.expect("set profile");
config.permissions.network = controller.cloned();
})
.await?;
let policy_file = crate::exec_policy::default_policy_path(home.path());
std::fs::create_dir_all(&policy_file)?;
for (host, action) in [
(GRANTED, NetworkPolicyRuleAction::Allow),
(DENIED, NetworkPolicyRuleAction::Deny),
] {
let mut at_apply = None;
let error = session
.persist_network_policy_amendment(
&NetworkPolicyAmendment {
host: host.to_owned(),
action,
},
&NetworkApprovalContext {
host: host.to_owned(),
protocol: NetworkApprovalProtocol::Https,
},
|| at_apply = Some(session.services.exec_policy.current()),
)
.await
.expect_err("a directory cannot be opened for appending a rule");
assert!(
matches!(error.downcast_ref::<ExecPolicyUpdateError>(),
Some(ExecPolicyUpdateError::AppendRule { path, .. }) if path == &policy_file
),
"{error}"
);
// A shared proxy notifies at installation. With no shared proxy a failed save never notifies.
let denied = match action {
NetworkPolicyRuleAction::Allow => vec![],
NetworkPolicyRuleAction::Deny => vec![host.to_owned()],
};
assert_eq!(
at_apply.map(|policy| policy.compiled_network_domains()),
shared_proxy.then_some((Vec::new(), denied))
);
}
let policy = session.services.exec_policy.current();
let native_domains = if let Some(proxy) = session.services.network_proxy.load_full() {
proxy.proxy().current_cfg().await?.domains
} else {
crate::config::NetworkProxySpec::for_environment(
controller,
owner.as_ref().expect("owner policy"),
&profile,
&policy,
binding,
)?
.environment_policy()
.domains
};
let mcp = crate::config::NetworkProxySpec::mcp_network_policy(
controller,
&profile,
crate::config::McpNetworkRoute {
primary_allows_proxy: shared_proxy,
local_binding: binding,
owner: owner.as_ref(),
},
&profile,
AskForApproval::OnRequest,
&policy,
)?;
let mut expected = json!({ (DENIED): "deny" });
if shared_proxy {
expected[GRANTED] = json!("allow");
}
assert_eq!(serde_json::to_value(native_domains)?, expected);
assert_eq!(
(mcp.allowed_domains, mcp.denied_domains),
(vec![], vec![DENIED.to_owned()])
);
Ok(())
}

View File

@@ -0,0 +1,89 @@
//! Task completion preserves a queued notification's budget alongside real user input.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn task_finish_preserves_notification_budget_and_queued_user_input() {
let (session, turn, _rx) = make_session_and_context_with_rx().await;
session
.spawn_task(
Arc::clone(&turn),
Vec::new(),
NeverEndingTask {
kind: TaskKind::Regular,
listen_to_cancellation_token: false,
},
)
.await;
let text = "notification diagnostic line\n".repeat(500);
let notification = |text| ResponseItem::CustomToolCallOutput {
id: None,
call_id: "call-a".to_string(),
name: Some("exec".to_string()),
output: FunctionCallOutputPayload::from_text(text),
internal_chat_message_metadata_passthrough: None,
};
session
.inject_if_running(vec![ResponseItemEnvelope {
item: notification(text.clone()),
metadata: Some(CodexHarnessMetadata {
history_truncation_token_limit: Some(120),
..Default::default()
}),
}])
.await
.unwrap();
let user_input = vec![UserInput::Text {
text: "keep this queued user input".to_string(),
text_elements: Vec::new(),
}];
assert!(matches!(
submit_steer_only(&session, user_input.clone(), &turn.sub_id).await,
TurnInputSubmission::Steered { .. }
));
let mut current = turn.initial_settings.as_ref().clone();
Arc::make_mut(&mut current.model_info).truncation_policy =
akode_protocol::openai_models::TruncationPolicyConfig::tokens(/*limit*/ 400);
turn.next_step_settings.store(Arc::new(current));
// Stall recording the first batch, then inject while finalization is in progress.
let state = session.state.lock().await;
let finish = session.on_task_finished(Arc::clone(&turn), /*task_result*/ Ok(None));
let late = vec![notification("late notification".to_string())];
tokio::join!(finish, async {
while session
.active_turn
.lock()
.await
.as_ref()
.expect("turn remains active while final recording is blocked")
.finishing
.is_none()
{
tokio::task::yield_now().await;
}
// Admission is closed even if recording has not yet reached the history lock.
let notice = vec![notification("producer still running".to_string())];
assert_eq!(session.inject_if_running(notice.clone()).await, Err(notice));
let inject = session.inject_client_response_items(late.clone(), &turn);
tokio::pin!(inject);
assert!(futures::poll!(inject.as_mut()).is_pending());
drop(state);
inject.await;
});
let expected = vec![
notification(akode_utils_output_truncation::truncate_text(
&text,
akode_utils_output_truncation::TruncationPolicy::Tokens(120),
)),
session.response_item_from_user_input(user_input),
late[0].clone(),
];
let history = session.clone_history().await;
assert_eq!(
strip_response_item_ids(&strip_metadata_from_items(&raw_history_items(&history))),
strip_response_item_ids(&strip_metadata_from_items(&expected)),
);
}

View File

@@ -0,0 +1,91 @@
//! File change approval replies are scoped to their requesting turn.
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn patch_approval_cancel_only_interrupts_its_requesting_turn() -> anyhow::Result<()> {
const CALL_ID: &str = "patch";
let (session, first, events) = make_session_and_context_with_rx().await;
let (thread, submissions) = make_thread_for_session(
Arc::clone(&session),
&first,
events.clone(),
SessionSource::Exec,
)
.await;
let dispatcher = tokio::spawn(submission_loop(
Arc::clone(&session),
Arc::clone(&first.config),
submissions,
));
let request_patch = |turn: Arc<TurnContext>| {
let session = Arc::clone(&session);
tokio::spawn(async move {
session
.spawn_task(
Arc::clone(&turn),
Vec::new(),
NeverEndingTask {
kind: TaskKind::Regular,
listen_to_cancellation_token: true,
},
)
.await;
session
.request_patch_approval(
&turn,
CALL_ID.into(),
HashMap::new(),
/*reason*/ None,
/*grant_root*/ None,
)
.await
})
};
let cancel_first_at_next_prompt = async || {
loop {
if matches!(
events.recv().await.expect("approval event").msg,
EventMsg::ApplyPatchApprovalRequest(_)
) {
break;
}
}
thread
.submit(Op::CancelPatchApproval {
id: CALL_ID.into(),
turn_id: first.sub_id.clone(),
})
.await
};
let first_waiter = request_patch(Arc::clone(&first));
cancel_first_at_next_prompt().await?;
assert_eq!(first_waiter.await?, ReviewDecision::Abort);
let aborted = recv_terminal_event(&events, TerminalEventKind::TurnAborted).await;
assert_eq!(aborted.id, first.sub_id);
let second = session
.new_turn_with_default_settings("next".into(), Default::default())
.await;
let second_waiter = request_patch(Arc::clone(&second));
// Both turns used the same call ID. Replay the first reply while the second prompt is open.
cancel_first_at_next_prompt().await?;
thread
.submit(Op::PatchApproval {
id: CALL_ID.into(),
decision: ReviewDecision::Approved,
})
.await?;
assert_eq!(second_waiter.await?, ReviewDecision::Approved);
assert!(
session
.turn_context_for_sub_id(&second.sub_id)
.await
.is_some()
);
drop(thread);
dispatcher.await?;
Ok(())
}

View File

@@ -0,0 +1,32 @@
//! Activates an admitted task's plugin selection without changing pending settings.
use std::sync::Arc;
use super::Session;
use super::turn_context::TurnContext;
impl Session {
pub(crate) async fn activate_plugin_selection(&self, turn_context: &TurnContext) {
let config = {
let mut state = self.state.lock().await;
if state.active_disabled_plugin_ids != turn_context.disabled_plugin_ids {
state.active_disabled_plugin_ids = turn_context.disabled_plugin_ids.clone();
self.mark_mcp_runtime_dirty();
}
Arc::clone(&state.session_configuration.original_config_do_not_use)
};
let plugin_outcome = self
.services
.plugins_manager
.plugins_for_config(&config.plugins_config_input())
.await
.without_plugins(&turn_context.disabled_plugin_ids);
// Cache changes from another process do not notify this session's hook runtime.
if !self.hooks().matches_plugin_hooks(
plugin_outcome.iter_effective_plugin_hook_sources(),
plugin_outcome.iter_effective_plugin_hook_warnings(),
) {
self.refresh_hooks(config).await;
}
}
}

View File

@@ -0,0 +1,56 @@
use super::session::Session;
use crate::realtime_history::RealtimeEventEffects;
use akode_history::RolloutItem;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::RealtimeConversationRealtimeEvent;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::realtime::RealtimeItemContent;
impl Session {
pub(super) async fn send_realtime_history_effects(
&self,
submission_id: &str,
effects: RealtimeEventEffects,
) -> anyhow::Result<()> {
let event = |payload| Event {
id: submission_id.to_string(),
msg: EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent {
payload,
}),
};
if let Some(stream) = effects.transcript_stream {
if let Some(item) = stream.started_item {
self.deliver_event_raw(event(RealtimeEvent::HistoryItemStarted(item)))
.await;
}
self.deliver_event_raw(event(RealtimeEvent::HistoryTranscriptDelta {
item_id: stream.item_id,
delta: stream.delta,
}))
.await;
}
if effects.items.is_empty() {
return Ok(());
}
self.live_thread_for_persistence("append realtime history")?
.append_items(
&effects
.items
.iter()
.cloned()
.map(RolloutItem::RealtimeItem)
.collect::<Vec<_>>(),
)
.await?;
for item in effects.items {
if !matches!(&item.content, RealtimeItemContent::TranscriptSegment { .. }) {
self.deliver_event_raw(event(RealtimeEvent::HistoryItemStarted(item.clone())))
.await;
}
self.deliver_event_raw(event(RealtimeEvent::HistoryItemCompleted(item)))
.await;
}
Ok(())
}
}

View File

@@ -0,0 +1,172 @@
//! Cache-preserving effort updates and the request-effort baseline for a context window.
//!
//! Only trusted harness items establish overrides. Replay preserves startup prewarm's
//! baseline while it is retained.
//! Successful compaction retires the overrides and allows a fresh request baseline.
//! Fixed-effort workers always use their selected request-level effort.
//! Unsupported models use selected request effort without rewriting saved updates.
//! A provider catalog can retire a request pin that is invalid for a new step.
use super::session::Session;
use super::step_context::StepContext;
use super::step_settings::ResolvedStepSettings;
use crate::state::ReasoningEffortPin;
use akode_history::CodexHarnessMetadata;
use akode_history::ResponseItemEnvelope;
use akode_protocol::models::ConfigurationReasoning;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::ModelOrigin;
use akode_protocol::openai_models::ReasoningEffort;
/// Sampling can establish a pin; compaction must not change live state before it succeeds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RequestEffortUsage {
Sampling,
Compaction,
}
impl Session {
/// Establishes the selected effort in surviving history, independent of replayed settings.
pub(crate) async fn record_reasoning_effort_override(&self, step_context: &StepContext) {
let settings = &step_context.settings;
let Some(effort) = self.effort_for_configuration_update(settings) else {
return;
};
let should_skip = {
let mut state = self.state.lock().await;
if matches!(state.reasoning_effort_pin, ReasoningEffortPin::Compacted) {
// Only successful compaction allows the request baseline to establish
// the selection without another update.
state
.reasoning_effort_pin
.pin(&settings.model_info.slug, effort.clone());
}
let latest_override = state
.history
.annotated_items()
.iter()
.rev()
.enumerate()
.find_map(|(index, envelope)| {
if !envelope
.metadata
.as_ref()
.is_some_and(|metadata| metadata.harness_authored_configuration)
{
return None;
}
match &envelope.item {
ResponseItem::ConfigurationUpdate { reasoning } => {
Some((index, &reasoning.effort))
}
_ => None,
}
});
// Recovery adds no user message. Reuse a matching trusted tail update even
// before this runtime establishes its pin, rather than append adjacent updates.
latest_override.is_some_and(|(index, established)| index == 0 && established == &effort)
|| state
.reasoning_effort_pin
.get(&settings.model_info.slug)
.is_some_and(|pinned| {
latest_override.map_or(&pinned, |(_, established)| established) == &effort
})
};
if should_skip {
return;
}
self.record_annotated_conversation_items(
step_context.turn.as_ref(),
&step_context.settings.model_info,
vec![ResponseItemEnvelope {
item: ResponseItem::ConfigurationUpdate {
reasoning: ConfigurationReasoning { effort },
},
metadata: Some(CodexHarnessMetadata {
harness_authored_configuration: true,
..Default::default()
}),
}],
)
.await;
}
/// Sampling and compaction share the original request effort for this context window.
pub(crate) async fn reasoning_effort_for_request(
&self,
settings: &ResolvedStepSettings,
usage: RequestEffortUsage,
) -> Option<ReasoningEffort> {
let selected_effort = settings.reasoning_effort().cloned();
if !self
.services
.model_client
.reasoning_effort_override_enabled(&settings.model_info)
{
if usage == RequestEffortUsage::Sampling {
self.state.lock().await.reasoning_effort_pin = ReasoningEffortPin::Unset;
}
return selected_effort;
}
let effort = self.effort_for_configuration_update(settings);
let mut state = self.state.lock().await;
if let Some(pinned) = state.reasoning_effort_pin.get(&settings.model_info.slug) {
let model = &settings.model_info;
let disallowed = model.origin == ModelOrigin::Provider
&& !model.supported_reasoning_levels.is_empty()
&& !model
.supported_reasoning_levels
.iter()
.any(|preset| model.resolve_reasoning_effort(preset.effort.clone()) == pinned);
if disallowed {
// Check the step's captured metadata, so a refresh cannot change a running
// step. Failed compaction must not mutate the live request baseline.
if usage == RequestEffortUsage::Sampling {
state.reasoning_effort_pin = ReasoningEffortPin::Unset;
}
} else if usage == RequestEffortUsage::Compaction {
return Some(pinned);
}
}
let Some(effort) = effort else {
if usage == RequestEffortUsage::Sampling {
state.reasoning_effort_pin = ReasoningEffortPin::Unset;
}
return selected_effort;
};
Some(match usage {
RequestEffortUsage::Sampling => state
.reasoning_effort_pin
.pin(&settings.model_info.slug, effort),
// Failed compaction and fallback-model lookups must not mutate the live pin.
RequestEffortUsage::Compaction => effort,
})
}
fn effort_for_configuration_update(
&self,
settings: &ResolvedStepSettings,
) -> Option<ReasoningEffort> {
if !self
.services
.model_client
.reasoning_effort_override_enabled(&settings.model_info)
{
return None;
}
let effort = settings
.model_info
.resolve_reasoning_effort(settings.effective_reasoning_effort()?);
// Persistent normalizes to "disabled". Keep unknown custom values out of
// durable updates so injected items stay bounded to known backend modes.
if matches!(&effort, ReasoningEffort::Custom(value) if value != "disabled") {
return None;
}
Some(effort)
}
}
#[cfg(test)]
#[path = "reasoning_effort_tests.rs"]
mod tests;

View File

@@ -0,0 +1,251 @@
//! Request-effort pins across initial replay and compaction lookups.
use super::RequestEffortUsage;
use crate::session::step_settings::ResolvedStepSettings;
use crate::session::tests::make_session_and_context_with_auth_and_config_and_rx;
use akode_features::Feature;
use akode_history::InitialHistory;
use akode_history::ResumedHistory;
use akode_login::CodexAuth;
use akode_protocol::ThreadId;
use akode_protocol::openai_models::ModelOrigin;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::openai_models::ReasoningEffortPreset;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use test_case::test_case;
#[test_case(ReasoningEffort::High, ReasoningEffort::Low; "disallowed_high")]
#[test_case(ReasoningEffort::Ultra, ReasoningEffort::Low; "valid_ultra")]
#[test_case(ReasoningEffort::Persistent, ReasoningEffort::Low; "valid_persistent")]
#[tokio::test]
async fn fresh_step_metadata_retires_only_incompatible_pins(
previous: ReasoningEffort,
selected: ReasoningEffort,
) {
let (session, turn, _events) = make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| {
config
.features
.enable(Feature::ReasoningEffortOverride)
.unwrap();
},
)
.await;
let mut model = (*turn.initial_settings.model_info).clone();
model.origin = ModelOrigin::Provider;
model.supports_reasoning_effort_updates = true;
model.supported_reasoning_levels = [previous.clone(), selected.clone(), ReasoningEffort::Max]
.into_iter()
.map(|effort| ReasoningEffortPreset {
description: effort.to_string(),
effort,
})
.collect();
let original = model.resolve_reasoning_effort(previous.clone());
let mut choice = turn.initial_settings.selected().clone();
choice.collaboration_mode.settings.reasoning_effort = Some(previous.clone());
let old_step = ResolvedStepSettings::new(
Arc::new(choice.clone()),
Arc::new(model.clone()),
&Default::default(),
);
assert_eq!(
session
.reasoning_effort_for_request(&old_step, RequestEffortUsage::Sampling)
.await,
Some(original.clone())
);
if previous == ReasoningEffort::High {
model.supported_reasoning_levels = vec![ReasoningEffortPreset {
description: selected.to_string(),
effort: selected.clone(),
}];
}
choice.collaboration_mode.settings.reasoning_effort = Some(selected.clone());
let expected = if previous == ReasoningEffort::High {
model.resolve_reasoning_effort(selected)
} else {
original.clone()
};
let fresh_step =
ResolvedStepSettings::new(Arc::new(choice), Arc::new(model), &Default::default());
assert_eq!(
session
.reasoning_effort_for_request(&fresh_step, RequestEffortUsage::Compaction)
.await,
Some(expected.clone())
);
assert_eq!(
session
.state
.lock()
.await
.reasoning_effort_pin
.get(&old_step.model_info.slug),
Some(original.clone())
);
assert_eq!(
session
.reasoning_effort_for_request(&old_step, RequestEffortUsage::Sampling)
.await,
Some(original)
);
assert_eq!(
session
.reasoning_effort_for_request(&fresh_step, RequestEffortUsage::Sampling)
.await,
Some(expected)
);
}
#[test_case(InitialHistory::Forked(Vec::new()); "fork")]
#[test_case(InitialHistory::Resumed(ResumedHistory {
history_revision: None,
conversation_id: ThreadId::default(),
history: Arc::new(Vec::new()),
rollout_path: None,
}); "resume")]
#[tokio::test]
async fn initial_replay_preserves_prewarmed_effort(history: InitialHistory) {
let (session, turn_context, _events) = make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| {
config
.features
.enable(Feature::ReasoningEffortOverride)
.unwrap();
},
)
.await;
let mut model_info = Arc::clone(&turn_context.initial_settings.model_info);
Arc::make_mut(&mut model_info).supports_reasoning_effort_updates = true;
let mut selected = turn_context.initial_settings.selected().clone();
selected.collaboration_mode.settings.reasoning_effort = Some(ReasoningEffort::Medium);
let prewarm_settings = ResolvedStepSettings::new(
Arc::new(selected.clone()),
Arc::clone(&model_info),
&akode_features::Features::default(),
);
// Force the ordering where prewarm pins its request before initial replay finishes.
assert_eq!(
session
.reasoning_effort_for_request(&prewarm_settings, RequestEffortUsage::Sampling)
.await,
Some(ReasoningEffort::Medium),
);
session.record_initial_history(history).await;
selected.collaboration_mode.settings.reasoning_effort = Some(ReasoningEffort::High);
let turn_settings = ResolvedStepSettings::new(
Arc::new(selected),
model_info,
&akode_features::Features::default(),
);
assert_eq!(
session
.reasoning_effort_for_request(&turn_settings, RequestEffortUsage::Sampling)
.await,
Some(ReasoningEffort::Medium),
);
}
#[tokio::test]
async fn compaction_effort_lookup_preserves_pin_for_fallback_models() {
let (session, turn_context, _events) = make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| {
config
.features
.enable(Feature::ReasoningEffortOverride)
.unwrap();
},
)
.await;
session
.state
.lock()
.await
.reasoning_effort_pin
.pin("original", ReasoningEffort::Low);
let mut settings = (*turn_context.initial_settings).clone();
let effort = ReasoningEffort::Medium;
let model = Arc::make_mut(&mut settings.model_info);
model.slug = "fallback".to_string();
model.supports_reasoning_effort_updates = true;
model.default_reasoning_level = Some(effort.clone());
assert_eq!(
session
.reasoning_effort_for_request(&settings, RequestEffortUsage::Compaction)
.await,
Some(effort)
);
assert_eq!(
session
.state
.lock()
.await
.reasoning_effort_pin
.get("original"),
Some(ReasoningEffort::Low)
);
}
#[tokio::test]
async fn unsupported_model_compaction_uses_selected_effort_without_mutating_pin() {
let (session, turn_context, _events) = make_session_and_context_with_auth_and_config_and_rx(
CodexAuth::from_api_key("Test API Key"),
Vec::new(),
|config| {
config
.features
.enable(Feature::ReasoningEffortOverride)
.unwrap();
config.model_reasoning_effort = Some(ReasoningEffort::High);
},
)
.await;
let mut settings = (*turn_context.initial_settings).clone();
Arc::make_mut(&mut settings.model_info).supports_reasoning_effort_updates = false;
session
.state
.lock()
.await
.reasoning_effort_pin
.pin(&settings.model_info.slug, ReasoningEffort::Low);
assert_eq!(
session
.reasoning_effort_for_request(&settings, RequestEffortUsage::Compaction)
.await,
Some(ReasoningEffort::High),
);
assert_eq!(
session
.state
.lock()
.await
.reasoning_effort_pin
.get(&settings.model_info.slug),
Some(ReasoningEffort::Low),
);
// Sampling retires the old baseline, so a later supported request starts afresh.
assert_eq!(
session
.reasoning_effort_for_request(&settings, RequestEffortUsage::Sampling)
.await,
Some(ReasoningEffort::High),
);
Arc::make_mut(&mut settings.model_info).supports_reasoning_effort_updates = true;
assert_eq!(
session
.reasoning_effort_for_request(&settings, RequestEffortUsage::Sampling)
.await,
Some(ReasoningEffort::High),
);
}

View File

@@ -0,0 +1,191 @@
//! Orders retained inputs at acceptance, assistant messages at stream start,
//! and Code Mode messages at confirmed delivery.
//! Explicit goal authorization becomes live only after its persistence barrier succeeds.
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use crate::context::ContextualUserFragment;
use crate::context::UserGoalUpdate;
use akode_history::CodexHarnessMetadata;
use akode_history::ResponseItemEnvelope;
use akode_history::RetainedContextEvent;
use akode_history::RolloutItem;
use akode_protocol::models::ResponseItem;
use akode_thread_store::PersistContext;
use tokio::sync::Semaphore;
use tokio::sync::watch;
use tokio_util::task::TaskTracker;
use tokio_util::task::task_tracker::TaskTrackerToken;
use super::Session;
use super::TurnContext;
use super::thread_settings;
/// Only unrecorded starts need a reservation; abandoned entries expire with the turn.
#[derive(Default)]
pub(super) struct PendingAssistantMessageOrders(pub(super) Mutex<HashMap<String, u64>>);
pub(super) struct CodeModeMessageTasks {
tasks: Mutex<TaskTracker>,
pending_persistence: Mutex<Vec<watch::Receiver<()>>>,
pub(super) communication_boundary: Arc<Semaphore>,
}
impl Default for CodeModeMessageTasks {
fn default() -> Self {
Self {
tasks: Mutex::default(),
pending_persistence: Mutex::default(),
communication_boundary: Arc::new(Semaphore::new(1)),
}
}
}
impl Session {
/// Reserve before deriving display items, including plans, from the source message.
/// Completion-only responses use the same path before publishing their text.
pub(super) async fn reserve_assistant_message_order(
&self,
turn_context: &TurnContext,
item: &ResponseItem,
) {
if let ResponseItem::Message {
id: Some(id), role, ..
} = item
&& role == "assistant"
{
let mut state = self.state.lock().await;
if !state
.history
.raw_items()
.any(|item| item.id().is_some_and(|recorded_id| recorded_id == id))
{
turn_context
.extension_data
.get_or_init(PendingAssistantMessageOrders::default)
.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.entry(id.to_string())
.or_insert_with(|| state.history.reserve_input_order());
}
}
}
/// Records authorization without adding pending input or reopening an active turn.
pub(crate) async fn record_user_goal_update(
&self,
update: UserGoalUpdate,
) -> std::io::Result<()> {
// Goal metadata must not initialize a model step, even on a goal-first thread.
// Keep context construction off callers' stacks, including the TUI RPC dispatcher.
let context = Box::pin(self.new_inject_items_context()).await;
// Earlier Code Mode messages may need the persistence lock before this can return.
let user_input_order = self.reserve_user_input_order().await;
let _guard = thread_settings::acquire_persistence_lock(self).await;
let mut item = ContextualUserFragment::into(update);
Self::stamp_response_item_for_history(&mut item, &context.sub_id);
self.assign_missing_response_item_id(&mut item);
let mut item = ResponseItemEnvelope {
item,
metadata: Some(CodexHarnessMetadata {
user_input_order: Some(user_input_order),
..Default::default()
}),
};
if let Some(live_thread) = self.live_thread() {
// Capture settings under the same permit as the instruction, including when a
// goal creates the rollout. No fallible settings catch-up runs after publication.
live_thread
.append_items(&[
RolloutItem::EventMsg(thread_settings::applied_event(self).await),
RolloutItem::ResponseItem(item.clone()),
])
.await
.map_err(std::io::Error::other)?;
}
// A failed append or checkpoint must not change live authorization or its revision.
self.try_ensure_rollout_materialized(PersistContext::ThreadPreparation)
.await?;
self.state.lock().await.history.record_annotated_items(
std::slice::from_mut(&mut item),
context.model_info().truncation_policy.into(),
);
self.send_raw_response_items(&context, std::slice::from_ref(&item.item))
.await;
Ok(())
}
pub(crate) async fn reserve_user_input_order(&self) -> u64 {
let _boundary = self
.code_mode_message_tasks
.communication_boundary
.acquire()
.await
.unwrap_or_else(|_| unreachable!("communication boundary remains open"));
let (order, pending) = {
let mut state = self.state.lock().await;
let order = state.history.reserve_input_order();
(order, self.pending_code_mode_message_recordings())
};
// Older readers assign assistant records to physical instruction boundaries.
// Keep a later user steer from reaching the rollout ahead of an earlier send.
for mut recording in pending {
let _ = recording.changed().await;
}
order
}
/// Snapshot while holding `state` so earlier confirmed delivery reservations are included.
pub(super) fn pending_code_mode_message_recordings(&self) -> Vec<watch::Receiver<()>> {
let mut pending = self
.code_mode_message_tasks
.pending_persistence
.lock()
.unwrap_or_else(PoisonError::into_inner);
pending.retain(|recording| recording.has_changed().is_ok());
pending.clone()
}
pub(crate) async fn record_retained_context(&self, mut event: RetainedContextEvent) {
event.bound();
// Share the checkpoint persistence lock so a fact cannot land on the wrong side
// of the checkpoint/suffix boundary. Ephemeral threads use the same live state.
let _guard = thread_settings::acquire_persistence_lock(self).await;
if self
.state
.lock()
.await
.history
.record_retained_context(&event)
{
self.persist_rollout_items(&[RolloutItem::RetainedContext(event)])
.await;
}
}
pub(crate) fn track_code_mode_message(&self) -> Option<TaskTrackerToken> {
let tasks = self
.code_mode_message_tasks
.tasks
.lock()
.unwrap_or_else(PoisonError::into_inner);
(!tasks.is_closed()).then(|| tasks.token())
}
pub(super) async fn drain_code_mode_messages(&self) {
let tasks = {
let tasks = self
.code_mode_message_tasks
.tasks
.lock()
.unwrap_or_else(PoisonError::into_inner);
tasks.close();
tasks.clone()
};
tasks.wait().await;
}
}

View File

@@ -0,0 +1,178 @@
use super::step_settings::ResolvedStepSettings;
use super::*;
use akode_protocol::openai_models::ModelOrigin;
/// Spawn a review thread using the given prompt.
pub(super) async fn spawn_review_thread(
sess: Arc<Session>,
config: Arc<Config>,
parent_turn_context: Arc<TurnContext>,
sub_id: String,
resolved: crate::review_prompts::ResolvedReviewRequest,
) {
let model = config
.review_model
.clone()
.unwrap_or_else(|| parent_turn_context.model_info().slug.clone());
let available_models = sess
.services
.models_manager
.list_models(
RefreshStrategy::OnlineIfUncached,
config.http_client_factory(),
)
.await;
let review_model_info = sess
.services
.models_manager
.get_model_info(&model, &config.to_models_manager_config())
.await;
// For reviews, disable web_search and view_image regardless of global settings.
let mut review_features = sess.features.clone();
let _ = review_features.disable(Feature::WebSearchRequest);
let _ = review_features.disable(Feature::WebSearchCached);
let _ = review_features.disable(Feature::Goals);
let review_web_search_mode = WebSearchMode::Disabled;
let review_prompt = resolved.prompt.clone();
let model_info = review_model_info.clone();
let mut selected = parent_turn_context.initial_settings.selected().clone();
let mut reasoning_effort = selected.collaboration_mode.reasoning_effort();
// Build per‑turn client with the requested model/family.
let mut per_turn_config = (*parent_turn_context.config).clone();
// Preserve configured overrides without carrying over the parent model's defaults.
per_turn_config.token_budget = config.token_budget.clone();
per_turn_config.features = review_features.clone();
if let Some(current_effort) = reasoning_effort.as_ref()
&& review_model_info.slug != parent_turn_context.model_info().slug
&& review_model_info.origin != ModelOrigin::Synthetic
&& !review_model_info
.supported_reasoning_levels
.iter()
.any(|preset| &preset.effort == current_effort)
{
let supported_reasoning_levels = &review_model_info.supported_reasoning_levels;
reasoning_effort = supported_reasoning_levels
.get(supported_reasoning_levels.len().saturating_sub(1) / 2)
.map(|preset| preset.effort.clone())
.or_else(|| review_model_info.default_reasoning_level.clone());
}
if let Err(err) = per_turn_config.web_search_mode.set(review_web_search_mode) {
let fallback_value = per_turn_config.web_search_mode.value();
tracing::warn!(
error = %err,
?review_web_search_mode,
?fallback_value,
"review web_search_mode is disallowed by requirements; keeping constrained value"
);
}
let session_source = parent_turn_context.session_source.clone();
let (forked_from_thread_id, thread_source, service_tier) = {
let state = sess.state.lock().await;
(
state.session_configuration.forked_from_thread_id,
state.session_configuration.thread_source.clone(),
state
.session_configuration
.step_settings
.service_tier
.clone()
.or_else(|| config.service_tier.clone()),
)
};
let auto_review_enabled = crate::guardian::routes_approval_policy_to_guardian(
per_turn_config.permissions.approval_policy.value(),
per_turn_config.approvals_reviewer,
);
// The original config may retain a requested tier unsupported by the parent
// model. Resolve it against the review model and the shared feature gate.
selected.collaboration_mode.settings.model = model.clone();
selected.collaboration_mode.settings.reasoning_effort = reasoning_effort.clone();
selected.service_tier = service_tier;
let step_settings = Arc::new(ResolvedStepSettings::new(
Arc::new(selected),
Arc::new(model_info.clone()),
&review_features,
));
per_turn_config.model = Some(model);
per_turn_config.model_reasoning_effort = reasoning_effort;
per_turn_config.service_tier = step_settings.service_tier.clone();
let per_turn_config = Arc::new(per_turn_config);
let review_turn_id = sub_id.to_string();
#[allow(deprecated)]
let windows_sandbox_selection = parent_turn_context
.initial_environments
.primary()
.map(TurnEnvironment::windows_sandbox_selection_for_turn_metadata)
.unwrap_or_else(|| {
crate::tools::sandboxing::configured_windows_sandbox_selection(
parent_turn_context
.config
.effective_local_windows_sandbox_type(),
parent_turn_context.windows_sandbox_level,
&akode_utils_path_uri::PathUri::from_abs_path(&parent_turn_context.cwd),
)
});
let turn_metadata_state = Arc::new(TurnMetadataState::new(
sess.session_id().to_string(),
sess.thread_id().to_string(),
forked_from_thread_id,
parent_turn_context.parent_thread_id,
&session_source,
thread_source,
review_turn_id.clone(),
#[allow(deprecated)]
parent_turn_context.cwd.clone(),
&parent_turn_context.permission_profile(),
windows_sandbox_selection,
parent_turn_context.network.is_some(),
auto_review_enabled,
&model_info,
));
let review_turn_context = parent_turn_context.for_review(
review_turn_id,
per_turn_config,
step_settings,
available_models,
turn_metadata_state,
);
// Seed the child task with the review prompt as the initial user message.
let input = vec![TurnInput::UserInput {
metadata: Default::default(),
content: vec![UserInput::Text {
text: review_prompt,
// Review prompt is synthesized; no UI element ranges to preserve.
text_elements: Vec::new(),
}],
client_id: None,
}];
let tc = Arc::new(review_turn_context);
if tc
.initial_environments
.single_local_environment_cwd()
.is_some()
{
tc.turn_metadata_state
.spawn_git_enrichment_task(Arc::clone(&sess.services.git_root_discovery));
}
sess.abort_all_tasks(TurnAbortReason::Replaced).await;
// Announce entering review mode so UIs can switch modes.
let item = TurnItem::EnteredReviewMode(EnteredReviewModeItem {
id: uuid::Uuid::now_v7().to_string(),
target: resolved.target,
user_facing_hint: resolved.user_facing_hint,
});
sess.emit_turn_item_started(&tc, &item).await;
sess.emit_turn_item_completed(&tc, item).await;
// TODO(ccunningham): Review turns currently rely on `spawn_task` for TurnComplete but do not
// emit a parent TurnStarted. Consider giving review a full parent turn lifecycle
// (TurnStarted + TurnComplete) for consistency with other standalone tasks.
sess.start_task(Arc::clone(&tc), input, ReviewTask::new())
.await;
}

View File

@@ -0,0 +1,75 @@
use super::session::Session;
use super::turn_context::TurnContext;
use crate::agent::host::AgentRuntimeServices;
use crate::agent::host::AgentUsageReport;
use crate::agent::host::UsageAccountingDecision;
use crate::context::ContextualUserFragment;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::TokenUsage;
pub(super) async fn maybe_record_reminder(
sess: &Session,
turn_context: &TurnContext,
window_id: &str,
) {
// Host runtimes own budget policy, including whether accounting is enabled.
if matches!(&sess.agent_runtime, AgentRuntimeServices::Host(_)) {
return;
}
let agent_control = &sess.services.agent_control;
let Some(reminder) = agent_control
.pending_budget_reminder(sess.thread_id(), window_id)
.await
else {
return;
};
let response_item = ContextualUserFragment::into(crate::context::RolloutBudgetContext {
remaining_tokens: reminder.remaining_tokens,
});
sess.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&response_item),
)
.await;
agent_control
.mark_budget_reminder_delivered(sess.thread_id(), window_id, reminder)
.await;
}
impl Session {
pub(crate) async fn record_rollout_budget_usage(
&self,
turn_id: &str,
usage: &TokenUsage,
) -> CodexResult<()> {
match &self.agent_runtime {
AgentRuntimeServices::Controller => {
self.services
.agent_control
.record_usage(usage.clone())
.await
}
AgentRuntimeServices::Host(services) => {
let Some(accounting) = &services.usage_accounting else {
return Ok(());
};
let decision = accounting
.report_usage(AgentUsageReport {
thread_id: self.thread_id(),
turn_id: turn_id.to_owned(),
usage: usage.clone(),
})
.await
.map_err(|error| {
CodexErr::Fatal(format!("Host usage accounting failed: {error}"))
})?;
match decision {
UsageAccountingDecision::Continue => Ok(()),
UsageAccountingDecision::Exhausted => Err(CodexErr::SessionBudgetExceeded),
}
}
}
}
}

View File

@@ -0,0 +1,684 @@
use super::*;
use crate::context::world_state::WorldStateSnapshot;
use crate::context_manager::is_user_turn_boundary;
use akode_history::ResponseItemEnvelope;
use akode_history::TurnAttribution;
use akode_protocol::ContextWindowId;
use akode_protocol::protocol::SessionContextWindow;
use akode_protocol::protocol::ThreadHistoryMode;
use akode_utils_output_truncation::TruncationPolicy;
use std::collections::BTreeSet;
// Return value of `Session::reconstruct_history_from_rollout`, bundling the rebuilt history with
// the resume/fork hydration metadata derived from the same replay.
#[derive(Debug, PartialEq)]
pub(crate) struct RolloutReconstruction {
pub(super) history: Vec<ResponseItemEnvelope>,
pub(super) rejected_audio_file_ids: BTreeSet<String>,
pub(crate) retained_context: akode_history::RetainedContext,
pub(super) guardian_history: Option<akode_history::GuardianHistoryCheckpoint>,
pub(super) last_started_turn_id: Option<String>,
pub(super) previous_turn_settings: Option<PreviousTurnSettings>,
pub(super) reference_context_item: Option<TurnContextItem>,
pub(super) turn_attribution: Option<TurnAttribution>,
pub(super) world_state_baseline: Option<WorldStateSnapshot>,
pub(super) window_number: u64,
pub(super) first_window_id: Option<ContextWindowId>,
pub(super) previous_window_id: Option<ContextWindowId>,
pub(super) window_id: Option<ContextWindowId>,
}
#[derive(Debug, Clone)]
struct ReconstructedWindow {
number: u64,
first_id: Option<ContextWindowId>,
previous_id: Option<ContextWindowId>,
id: Option<ContextWindowId>,
}
#[derive(Debug, Default)]
enum TurnReferenceContextItem {
/// No `TurnContextItem` has been seen for this replay span yet.
///
/// This differs from `Cleared`: `NeverSet` means there is no evidence this turn ever
/// established a baseline, while `Cleared` means a baseline existed and a later compaction
/// invalidated it. Only the latter must emit an explicit clearing segment for resume/fork
/// hydration.
#[default]
NeverSet,
/// A previously established baseline was invalidated by later compaction.
Cleared,
/// The latest baseline established by this replay span.
Latest(Box<TurnContextItem>),
}
#[derive(Debug, Clone, Copy)]
// The selected compaction and its replay tail must belong to the same surviving segment.
struct ReplayCheckpoint<'a> {
compacted: &'a CompactedItem,
suffix: &'a [RolloutItem],
}
/// Selects the newest compaction that can safely bound replay.
///
/// Returns `None` when reconstruction must replay all supplied items, either because there is no
/// compaction or the newest compaction cannot bound replay.
fn select_input_compaction(
rollout_items: &[RolloutItem],
history_mode: ThreadHistoryMode,
) -> Option<ReplayCheckpoint<'_>> {
// Only the newest compaction can bound replay. If it is incomplete, an older compaction
// cannot replace the history or window state that the newer one may have changed.
let (index, compacted) = rollout_items
.iter()
.enumerate()
.rev()
.find_map(|(index, item)| match item {
RolloutItem::Compacted(compacted) => Some((index, compacted)),
_ => None,
})?;
// Paginated histories always honor this boundary. Other histories only do so when resume
// metadata identifies a compaction written under the newer resume contract.
if compacted.replacement_history.is_none()
|| compacted.window_number.is_none()
|| (compacted.resume_metadata.is_none()
&& !matches!(history_mode, ThreadHistoryMode::Paginated))
{
return None;
}
Some(ReplayCheckpoint {
compacted,
suffix: &rollout_items[index + 1..],
})
}
#[derive(Debug, Default)]
struct ActiveReplaySegment<'a> {
turn_id: Option<String>,
turn_completed: bool,
counts_as_user_turn: bool,
previous_turn_settings: Option<PreviousTurnSettings>,
reference_context_item: TurnReferenceContextItem,
turn_attribution: Option<TurnAttribution>,
world_state_replay: Vec<&'a RolloutItem>,
history_checkpoint: Option<ReplayCheckpoint<'a>>,
window: Option<ReconstructedWindow>,
}
impl ActiveReplaySegment<'_> {
fn take_checkpoint_attribution(&mut self, checkpoint: &mut Option<TurnAttribution>) {
if checkpoint.as_ref().is_some_and(|attribution| {
self.turn_id
.as_ref()
.is_none_or(|id| id == &attribution.turn_id)
}) {
// Consume a matching checkpoint even when rollback discards this segment.
self.turn_attribution = self.turn_attribution.take().or(checkpoint.take());
}
}
}
fn turn_ids_are_compatible(active_turn_id: Option<&str>, item_turn_id: Option<&str>) -> bool {
active_turn_id
.is_none_or(|turn_id| item_turn_id.is_none_or(|item_turn_id| item_turn_id == turn_id))
}
fn finalize_active_segment<'a>(
active_segment: ActiveReplaySegment<'a>,
history_checkpoint: &mut Option<ReplayCheckpoint<'a>>,
previous_turn_settings: &mut Option<PreviousTurnSettings>,
reference_context_item: &mut TurnReferenceContextItem,
world_state_replay: &mut Vec<&'a RolloutItem>,
window: &mut Option<ReconstructedWindow>,
pending_rollback_turns: &mut usize,
) -> Option<TurnAttribution> {
// Thread rollback drops the newest surviving real user-message boundaries. In replay, that
// means skipping the next finalized segments that contain a non-contextual
// `EventMsg::UserMessage`.
if *pending_rollback_turns > 0 {
if active_segment.counts_as_user_turn {
*pending_rollback_turns -= 1;
}
return None;
}
// Full world-state snapshots are persisted after installing initial context. They still
// establish a baseline when a child fork removes the parent turn's agent message. Do not
// count these context-only segments as user turns for rollback, or use a snapshot from
// before the segment's latest compaction.
let has_context_baseline = active_segment.counts_as_user_turn
|| active_segment
.world_state_replay
.iter()
.take_while(|item| !matches!(item, RolloutItem::Compacted(_)))
.any(|item| matches!(item, RolloutItem::WorldState(state) if state.full));
world_state_replay.extend(active_segment.world_state_replay);
// A surviving replacement-history compaction is a complete history base. Once we
// know the newest surviving one, older rollout items do not affect rebuilt history.
if history_checkpoint.is_none()
&& let Some(segment_history_checkpoint) = active_segment.history_checkpoint
{
*history_checkpoint = Some(segment_history_checkpoint);
}
if window.is_none() {
*window = active_segment.window;
}
// Restore settings from the newest surviving context baseline.
if previous_turn_settings.is_none() && has_context_baseline {
*previous_turn_settings = active_segment.previous_turn_settings;
}
// `reference_context_item` comes from the newest surviving context baseline, or
// from a surviving compaction that explicitly cleared that baseline.
if matches!(reference_context_item, TurnReferenceContextItem::NeverSet)
&& (has_context_baseline
|| matches!(
active_segment.reference_context_item,
TurnReferenceContextItem::Cleared
))
{
*reference_context_item = active_segment.reference_context_item;
}
// Automatic turns can persist attribution without establishing a model-context baseline.
// Select recovery metadata from the same surviving segments, independently of that baseline.
active_segment.turn_attribution
}
impl Session {
pub(super) async fn reconstruct_history_from_rollout(
&self,
turn_context: &TurnContext,
rollout_items: &[RolloutItem],
) -> RolloutReconstruction {
ContextManager::reconstruct_rollout(
rollout_items,
turn_context.history_mode,
ContextManager::for_session(
turn_context.root_capabilities_restricted,
&turn_context.config.features,
turn_context.config.guardian_context_budgeting(),
std::sync::Arc::clone(&self.item_id_generator),
),
turn_context.model_info().truncation_policy.into(),
)
}
}
impl ContextManager {
/// Replays stored history without starting a session or acquiring its writer.
pub(crate) fn reconstruct_rollout(
rollout_items: &[RolloutItem],
history_mode: ThreadHistoryMode,
mut history: Self,
truncation_policy: TruncationPolicy,
) -> RolloutReconstruction {
// Rejection facts are durable across compaction boundaries. File IDs are immutable,
// so retaining a fact after rollback is conservative and cannot suppress a different
// future upload.
let mut rejected_audio_file_ids = BTreeSet::new();
for item in rollout_items {
match item {
RolloutItem::Compacted(compacted) => {
if let Some(metadata) = &compacted.resume_metadata {
rejected_audio_file_ids
.extend(metadata.rejected_audio_file_ids.iter().cloned());
}
}
RolloutItem::EventMsg(EventMsg::TurnComplete(completed)) => {
if let Some(error) = &completed.error {
rejected_audio_file_ids
.extend(error.rejected_audio_file_ids.iter().cloned());
}
}
_ => {}
}
}
// Select the compaction and suffix that can affect reconstruction.
let has_legacy_compaction_without_window_number =
rollout_items.iter().any(|item| {
matches!(item, RolloutItem::Compacted(compacted) if compacted.window_number.is_none())
});
let initial_window = if has_legacy_compaction_without_window_number {
None
} else {
rollout_items.iter().find_map(|item| match item {
RolloutItem::SessionMeta(session_meta) => session_meta
.meta
.context_window
.as_ref()
.and_then(reconstructed_window_from_session_context_window),
_ => None,
})
};
let input_checkpoint = select_input_compaction(rollout_items, history_mode);
let replay_items = input_checkpoint.map_or(rollout_items, |checkpoint| checkpoint.suffix);
let resume_metadata =
input_checkpoint.and_then(|checkpoint| checkpoint.compacted.resume_metadata.as_ref());
let mut history_checkpoint = input_checkpoint;
let mut window = input_checkpoint
.and_then(|checkpoint| reconstructed_window_from_compaction(checkpoint.compacted));
// Scan the selected items backward to find the newest surviving turn state.
let mut started_turn_ids = replay_items
.iter()
.rev()
.filter_map(|item| match item {
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => Some(event.turn_id.as_str()),
RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::TurnContext(_)
| RolloutItem::WorldState(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::Compacted(_)
| RolloutItem::EventMsg(_) => None,
})
.peekable();
let last_started_turn_id = started_turn_ids
.peek()
.map(|id| (*id).to_owned())
.or_else(|| resume_metadata.and_then(|metadata| metadata.last_started_turn_id.clone()));
// Saved attribution still identifies the turn when continuation eligibility was cleared.
let checkpoint_turn_id = resume_metadata.and_then(|metadata| {
metadata.last_started_turn_id.as_deref().or_else(|| {
metadata
.turn_attribution
.as_ref()
.map(|attribution| attribution.turn_id.as_str())
})
});
let mut previous_turn_settings = None;
let mut reference_context_item = TurnReferenceContextItem::NeverSet;
let mut turn_attribution = None;
let mut world_state_replay = Vec::new();
// Rollback is "drop the newest N user turns". While scanning in reverse, that becomes
// "skip the next N user-turn segments we finalize".
let mut pending_rollback_turns = 0usize;
// Reverse replay accumulates rollout items into the newest in-progress turn segment until
// we hit its matching `TurnStarted`, at which point the segment can be finalized.
let mut checkpoint_attribution =
resume_metadata.and_then(|metadata| metadata.turn_attribution.clone());
let mut late_completed_turn_ids = HashSet::new();
let mut active_segment: Option<ActiveReplaySegment<'_>> = None;
for (index, item) in replay_items.iter().enumerate().rev() {
let preceding_turn_id = started_turn_ids.peek().copied().or(checkpoint_turn_id);
match item {
RolloutItem::Compacted(compacted) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.world_state_replay.push(item);
if active_segment.window.is_none()
&& let Some(compaction_window) =
reconstructed_window_from_compaction(compacted)
{
active_segment.window = Some(compaction_window);
}
// Looking backward, compaction clears any older baseline unless a newer
// `TurnContextItem` in this same segment has already re-established it.
if matches!(
active_segment.reference_context_item,
TurnReferenceContextItem::NeverSet
) {
active_segment.reference_context_item = TurnReferenceContextItem::Cleared;
}
if active_segment.history_checkpoint.is_none()
&& compacted.replacement_history.is_some()
{
active_segment.history_checkpoint = Some(ReplayCheckpoint {
compacted,
suffix: &replay_items[index + 1..],
});
}
}
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
pending_rollback_turns = pending_rollback_turns
.saturating_add(usize::try_from(rollback.num_turns).unwrap_or(usize::MAX));
}
RolloutItem::EventMsg(EventMsg::TurnComplete(event)) => {
// Stop hooks can finish after a newer turn has started.
if !turn_ids_are_compatible(preceding_turn_id, Some(event.turn_id.as_str())) {
late_completed_turn_ids.insert(event.turn_id.as_str());
continue;
}
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.turn_completed = true;
// Reverse replay often sees `TurnComplete` before any turn-scoped metadata.
// Capture the turn id early so later `TurnContext` / abort items can match it.
if active_segment.turn_id.is_none() {
active_segment.turn_id = Some(event.turn_id.clone());
}
}
RolloutItem::EventMsg(EventMsg::TurnAborted(event)) => {
if !turn_ids_are_compatible(preceding_turn_id, event.turn_id.as_deref()) {
continue;
}
if let Some(active_segment) = active_segment.as_mut() {
if active_segment.turn_id.is_none()
&& let Some(turn_id) = &event.turn_id
{
active_segment.turn_id = Some(turn_id.clone());
}
} else if let Some(turn_id) = &event.turn_id {
active_segment = Some(ActiveReplaySegment {
turn_id: Some(turn_id.clone()),
..Default::default()
});
}
}
RolloutItem::EventMsg(EventMsg::UserMessage(_)) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.counts_as_user_turn = true;
}
RolloutItem::TurnContext(ctx) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
// `TurnContextItem` can attach metadata to an existing segment, but only a
// real `UserMessage` event should make the segment count as a user turn.
if active_segment.turn_id.is_none() {
active_segment.turn_id = ctx.turn_id.clone();
}
if turn_ids_are_compatible(
active_segment.turn_id.as_deref(),
ctx.turn_id.as_deref(),
) {
active_segment.previous_turn_settings = Some(PreviousTurnSettings {
model: ctx.model.clone(),
comp_hash: ctx.comp_hash.clone(),
realtime_active: ctx.realtime_active,
});
if matches!(
active_segment.reference_context_item,
TurnReferenceContextItem::NeverSet
) {
active_segment.reference_context_item =
TurnReferenceContextItem::Latest(Box::new(ctx.clone()));
}
}
}
RolloutItem::WorldState(_) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.world_state_replay.push(item);
}
RolloutItem::EventMsg(EventMsg::TurnStarted(event)) => {
started_turn_ids.next();
// Startup can be suspended before any input or context is written.
// Explicit start attribution is authoritative, including unknown fields.
if let Some(attribution) = &event.turn_attribution
&& attribution.turn_id == event.turn_id
{
let segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
if turn_ids_are_compatible(
segment.turn_id.as_deref(),
Some(event.turn_id.as_str()),
) {
segment.turn_attribution = Some(attribution.clone());
}
}
// `TurnStarted` is the oldest boundary of the active reverse segment.
if active_segment.as_ref().is_some_and(|active_segment| {
turn_ids_are_compatible(
active_segment.turn_id.as_deref(),
Some(event.turn_id.as_str()),
)
}) && let Some(mut active_segment) = active_segment.take()
{
active_segment
.turn_id
.get_or_insert_with(|| event.turn_id.clone());
active_segment.take_checkpoint_attribution(&mut checkpoint_attribution);
let segment_context = finalize_active_segment(
active_segment,
&mut history_checkpoint,
&mut previous_turn_settings,
&mut reference_context_item,
&mut world_state_replay,
&mut window,
&mut pending_rollback_turns,
);
turn_attribution = turn_attribution.or(segment_context);
}
}
RolloutItem::ResponseItem(response_item) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.counts_as_user_turn |=
is_user_turn_boundary(&response_item.item);
}
RolloutItem::InterAgentCommunication(_) => {
let active_segment =
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.counts_as_user_turn = true;
}
RolloutItem::EventMsg(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::InterAgentCommunicationMetadata { .. } => {}
}
}
if let Some(mut active_segment) = active_segment.take() {
active_segment.take_checkpoint_attribution(&mut checkpoint_attribution);
active_segment.turn_completed |= active_segment
.turn_id
.as_deref()
.or(checkpoint_turn_id)
.is_some_and(|turn_id| late_completed_turn_ids.contains(turn_id));
// A companion turn context only restores the context baseline. Once that turn
// completes, its settings are newer than the compaction metadata.
if resume_metadata.is_some() && !active_segment.turn_completed {
active_segment.previous_turn_settings = None;
}
let segment_context = finalize_active_segment(
active_segment,
&mut history_checkpoint,
&mut previous_turn_settings,
&mut reference_context_item,
&mut world_state_replay,
&mut window,
&mut pending_rollback_turns,
);
turn_attribution = turn_attribution.or(segment_context);
}
if pending_rollback_turns == 0 {
turn_attribution = turn_attribution.or(checkpoint_attribution);
}
if previous_turn_settings.is_none() {
previous_turn_settings =
resume_metadata.and_then(|metadata| metadata.previous_turn_settings.clone());
}
let fallback_window_number = u64::try_from(
rollout_items
.iter()
.filter(|item| matches!(item, RolloutItem::Compacted(_)))
.count(),
)
.unwrap_or(u64::MAX);
// Build model-visible history from the selected compaction and its newer suffix.
let mut saw_legacy_compaction_without_replacement_history = false;
if let Some(checkpoint) = history_checkpoint
&& let Some(items) = &checkpoint.compacted.replacement_history
{
history.replace_annotated(items.clone());
history.restore_review_context(
checkpoint.compacted.retained_context.as_ref(),
checkpoint.compacted.guardian_history.as_ref(),
// Keep the backup during replay; the installing session resolves its reviewer.
/*reviewer_compaction_hash*/
None,
);
}
let rollout_suffix =
history_checkpoint.map_or(rollout_items, |checkpoint| checkpoint.suffix);
for item in rollout_suffix {
match item {
RolloutItem::RetainedContext(event) => {
history.record_retained_context(event);
}
RolloutItem::ResponseItem(response_item) => {
history.replay_annotated_item(response_item, truncation_policy);
}
RolloutItem::InterAgentCommunication(communication) => {
let response_item = communication.to_model_input_item();
history.record_items(std::iter::once(&response_item), truncation_policy);
}
RolloutItem::InterAgentCommunicationMetadata { .. } => {}
RolloutItem::Compacted(compacted) => {
// Reverse replay already chose the newest surviving compaction. Any newer
// replacement compaction belongs to a rolled-back turn; replay its original
// items so the rollback can still find the removed user boundary.
if compacted.replacement_history.is_none() {
saw_legacy_compaction_without_replacement_history = true;
// Legacy rollouts without `replacement_history` should rebuild the
// historical TurnContext at the correct insertion point from persisted
// `TurnContextItem`s. These are rare enough that we currently just clear
// `reference_context_item`, reinject canonical context at the end of the
// resumed conversation, and accept the temporary out-of-distribution
// prompt shape.
// TODO(ccunningham): if we drop support for None replacement_history compaction items,
// we can get rid of this second loop entirely and just build `history` directly in the first loop.
let user_messages =
compact::collect_annotated_user_messages(history.annotated_items());
let rebuilt = compact::build_compacted_history(
Vec::new(),
&user_messages,
&compacted.message,
);
let retained_context = history.retained_context().clone();
history.replace_annotated(rebuilt);
history.restore_retained_context(Some(&retained_context));
}
}
RolloutItem::EventMsg(EventMsg::ThreadRolledBack(rollback)) => {
history.drop_last_n_user_turns(rollback.num_turns);
}
RolloutItem::EventMsg(_)
| RolloutItem::TurnContext(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::WorldState(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_) => {}
}
}
let reference_context_item = match reference_context_item {
TurnReferenceContextItem::NeverSet | TurnReferenceContextItem::Cleared => None,
TurnReferenceContextItem::Latest(turn_reference_context_item) => {
Some(*turn_reference_context_item)
}
};
let reference_context_item = if saw_legacy_compaction_without_replacement_history {
None
} else {
reference_context_item
};
// Replay the collected world-state records chronologically so compaction resets and merge
// patches keep their original meaning.
world_state_replay.reverse();
let mut world_state_baseline: Option<WorldStateSnapshot> = None;
for item in world_state_replay {
match item {
RolloutItem::Compacted(_) => world_state_baseline = None,
RolloutItem::WorldState(world_state) if world_state.full => {
world_state_baseline = Some(WorldStateSnapshot::from(&world_state.state));
}
RolloutItem::WorldState(world_state) => {
let Some(baseline) = world_state_baseline.as_mut() else {
tracing::warn!("ignored world-state patch without a full snapshot");
continue;
};
baseline.apply_merge_patch(&world_state.state);
}
RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::TurnContext(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::EventMsg(_) => {
unreachable!("only world-state replay items are collected")
}
}
}
let window = window.or(initial_window).unwrap_or(ReconstructedWindow {
number: fallback_window_number,
first_id: None,
previous_id: None,
id: None,
});
RolloutReconstruction {
retained_context: history.retained_context().clone(),
guardian_history: history.guardian_history_checkpoint(),
last_started_turn_id,
history: history.into_annotated_items(),
rejected_audio_file_ids,
previous_turn_settings,
reference_context_item,
turn_attribution,
world_state_baseline,
window_number: window.number,
first_window_id: window.first_id,
previous_window_id: window.previous_id,
window_id: window.id,
}
}
}
fn reconstructed_window_from_compaction(compacted: &CompactedItem) -> Option<ReconstructedWindow> {
Some(ReconstructedWindow {
number: compacted.window_number?,
first_id: compacted
.first_window_id
.as_deref()
.and_then(ContextWindowId::parse),
previous_id: compacted
.previous_window_id
.as_deref()
.and_then(ContextWindowId::parse),
id: compacted
.window_id
.as_deref()
.and_then(ContextWindowId::parse),
})
}
fn reconstructed_window_from_session_context_window(
context_window: &SessionContextWindow,
) -> Option<ReconstructedWindow> {
let id = ContextWindowId::parse(&context_window.window_id)?;
Some(ReconstructedWindow {
number: 0,
first_id: Some(id.clone()),
previous_id: None,
id: Some(id),
})
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
---
source: core/src/session/tests.rs
expression: snapshot
---
Scenario: First request after fork when startup preserves the parent baseline, the fork changes approval policy, and the first forked turn enters plan mode.
## Window 1
-- request 1 (turn; First Forked Turn Request) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/user:
fork seed
04:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <COLLABORATION_MODE>
05:message/user:
after fork

View File

@@ -0,0 +1,148 @@
//! Retains agent-tree membership and resources throughout managed startup.
//! Cleanup releases membership only after acquisition and partial session teardown finish;
//! abandoning that ownership marks tree shutdown as failed.
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::sync::MutexGuard;
use std::sync::OnceLock;
use std::sync::PoisonError;
use crate::agent::control::AgentTreeMembership;
use crate::agent::control::AgentTreeTeardownGuard;
use crate::thread_manager::thread_store_error_kind;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrKind;
use akode_protocol::protocol::Op;
use akode_thread_store::LiveThreadInitGuard;
use futures::future::BoxFuture;
use tokio::sync::Mutex;
use super::SessionIo;
use super::session::Session;
#[derive(Default)]
pub(crate) struct SessionStartup {
teardown: StdMutex<Option<AgentTreeTeardownGuard>>,
pub(crate) persistence: Mutex<LiveThreadInitGuard>,
pub(crate) session: OnceLock<Arc<Session>>,
pub(crate) io: OnceLock<SessionIo>,
}
impl SessionStartup {
fn lock_teardown(&self) -> MutexGuard<'_, Option<AgentTreeTeardownGuard>> {
self.teardown.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn hold_membership(&self, membership: AgentTreeMembership) {
let teardown = membership.into_teardown_guard("session_startup", /*thread_id*/ None);
let previous = self.lock_teardown().replace(teardown);
assert!(previous.is_none(), "agent-tree membership already set");
}
pub(crate) fn set_session(&self, session: Arc<Session>) {
let thread_id = session.thread_id;
let mut teardown = self.lock_teardown();
if self.session.set(session).is_ok()
&& let Some(teardown) = teardown.as_mut()
{
teardown.set_thread_id(thread_id);
}
}
pub(crate) fn session_teardown(&self, thread_id: ThreadId) -> Option<AgentTreeTeardownGuard> {
let teardown = self.lock_teardown();
let teardown = teardown.as_ref()?;
Some(teardown.clone_for_teardown("session_loop", Some(thread_id)))
}
pub(crate) fn release_membership(&self) {
if let Some(teardown) = self.lock_teardown().take() {
teardown.complete();
}
}
pub(crate) async fn cleanup(&self) {
let mut teardown = self.lock_teardown().take();
if let Some(teardown) = teardown.as_mut()
&& let Some(session) = self.session.get()
{
teardown.set_thread_id(session.thread_id);
}
if let Some(io) = self.io.get() {
// The session loop owns persistence now. Preserve its shutdown semantics even
// if registration or the caller's handoff was interrupted after the loop started.
self.persistence.lock().await.commit();
let _ = io.submit(Op::Interrupt).await;
if let Err(error) = io.shutdown_and_wait().await {
if let Some(teardown) = teardown.as_ref() {
teardown.record_shutdown_failure(
"stop_session_io",
CodexErrKind::from(&error).into(),
);
}
tracing::warn!("failed to stop cancelled session init: {error}");
}
} else {
if let Some(session) = self.session.get() {
super::handlers::shutdown_session_runtime(session).await;
// The session loop never started, so it cannot close the trace itself.
session
.services
.rollout_thread_trace
.record_ended(akode_rollout_trace::RolloutStatus::Aborted);
}
let mut persistence = std::mem::take(&mut *self.persistence.lock().await);
if let Err(error) = persistence.discard().await {
if let Some(teardown) = teardown.as_ref() {
teardown.record_shutdown_failure(
"discard_persistence",
thread_store_error_kind(&error),
);
}
tracing::warn!(
"failed to discard thread persistence for failed session init: {error}"
);
}
}
if let Some(teardown) = teardown {
teardown.complete();
}
}
}
/// Cleans up a cancelled session start before releasing its agent-tree membership.
pub(crate) struct SessionStartupGuard {
startup: Option<Arc<SessionStartup>>,
}
impl SessionStartupGuard {
pub(crate) fn new(startup: Arc<SessionStartup>) -> Self {
Self {
startup: Some(startup),
}
}
pub(crate) fn disarm(mut self) {
self.startup = None;
}
pub(crate) fn cleanup(mut self) -> BoxFuture<'static, ()> {
Box::pin(async move {
if let Some(startup) = self.startup.take() {
startup.cleanup().await;
}
})
}
}
impl Drop for SessionStartupGuard {
fn drop(&mut self) {
let Some(startup) = self.startup.take() else {
return;
};
drop(tokio::spawn(async move {
startup.cleanup().await;
}));
}
}

View File

@@ -0,0 +1,457 @@
//! Background model warmup shared by startup and idle-thread resume.
//! One scheduled task owns the prepared client session until the next regular
//! turn consumes it; shutdown and turn cancellation use the same handoff.
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use futures::FutureExt;
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::AbortOnDropHandle;
use tracing::Instrument;
use tracing::info;
use tracing::instrument;
use tracing::trace_span;
use tracing::warn;
use crate::client::ModelClientSession;
use crate::responses_metadata::CodexResponsesRequestKind;
use crate::session::INITIAL_SUBMIT_ID;
use crate::session::RequestEffortUsage;
use crate::session::session::Session;
use crate::session::turn::build_prompt;
use akode_features::Feature;
use akode_otel::STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC;
use akode_otel::STARTUP_PREWARM_DURATION_METRIC;
use akode_otel::SessionTelemetry;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::models::BaseInstructions;
#[derive(Clone, Copy, Debug)]
pub(crate) enum PrewarmInput {
Base,
History,
}
impl PrewarmInput {
fn as_str(self) -> &'static str {
match self {
Self::Base => "base",
Self::History => "history",
}
}
}
pub(crate) struct SessionStartupPrewarmHandle {
task: AbortOnDropHandle<CodexResult<ModelClientSession>>,
started_at: Instant,
timeout: Duration,
}
pub(crate) enum SessionStartupPrewarmResolution {
Cancelled,
Ready(Box<ModelClientSession>),
Unavailable {
status: &'static str,
prewarm_duration: Option<Duration>,
},
}
impl SessionStartupPrewarmHandle {
pub(crate) fn new(
task: JoinHandle<CodexResult<ModelClientSession>>,
started_at: Instant,
timeout: Duration,
) -> Self {
Self {
task: AbortOnDropHandle::new(task),
started_at,
timeout,
}
}
pub(crate) async fn abort(self) {
self.task.abort();
let _ = self.task.await;
}
#[instrument(name = "startup_prewarm.resolve", level = "trace", skip_all)]
async fn resolve(
self,
session_telemetry: &SessionTelemetry,
cancellation_token: &CancellationToken,
) -> SessionStartupPrewarmResolution {
let resolve_started_at = Instant::now();
let Self {
mut task,
started_at,
timeout,
} = self;
let age_at_first_turn = started_at.elapsed();
let remaining = timeout.saturating_sub(age_at_first_turn);
let resolution = if task.is_finished() {
Self::resolution_from_join_result(task.await, started_at)
} else {
match tokio::select! {
_ = cancellation_token.cancelled() => None,
result = tokio::time::timeout(remaining, &mut task) => Some(result),
} {
Some(Ok(result)) => Self::resolution_from_join_result(result, started_at),
Some(Err(_elapsed)) => {
task.abort();
info!("startup websocket prewarm timed out before the first turn could use it");
SessionStartupPrewarmResolution::Unavailable {
status: "timed_out",
prewarm_duration: Some(started_at.elapsed()),
}
}
None => {
task.abort();
session_telemetry.record_startup_phase(
"startup_prewarm_resolve",
resolve_started_at.elapsed(),
Some("cancelled"),
);
session_telemetry.record_duration(
STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC,
age_at_first_turn,
&[("status", "cancelled")],
);
session_telemetry.record_duration(
STARTUP_PREWARM_DURATION_METRIC,
started_at.elapsed(),
&[("status", "cancelled")],
);
return SessionStartupPrewarmResolution::Cancelled;
}
}
};
let status = match &resolution {
SessionStartupPrewarmResolution::Cancelled => "cancelled",
SessionStartupPrewarmResolution::Ready(_) => "ready",
SessionStartupPrewarmResolution::Unavailable { status, .. } => status,
};
session_telemetry.record_startup_phase(
"startup_prewarm_resolve",
resolve_started_at.elapsed(),
Some(status),
);
match resolution {
SessionStartupPrewarmResolution::Cancelled => {
SessionStartupPrewarmResolution::Cancelled
}
SessionStartupPrewarmResolution::Ready(prewarmed_session) => {
session_telemetry.record_duration(
STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC,
age_at_first_turn,
&[("status", "consumed")],
);
SessionStartupPrewarmResolution::Ready(prewarmed_session)
}
SessionStartupPrewarmResolution::Unavailable {
status,
prewarm_duration,
} => {
session_telemetry.record_duration(
STARTUP_PREWARM_AGE_AT_FIRST_TURN_METRIC,
age_at_first_turn,
&[("status", status)],
);
if let Some(prewarm_duration) = prewarm_duration {
session_telemetry.record_duration(
STARTUP_PREWARM_DURATION_METRIC,
prewarm_duration,
&[("status", status)],
);
}
SessionStartupPrewarmResolution::Unavailable {
status,
prewarm_duration,
}
}
}
}
fn resolution_from_join_result(
result: std::result::Result<CodexResult<ModelClientSession>, tokio::task::JoinError>,
started_at: Instant,
) -> SessionStartupPrewarmResolution {
match result {
Ok(Ok(prewarmed_session)) => {
SessionStartupPrewarmResolution::Ready(Box::new(prewarmed_session))
}
Ok(Err(err)) => {
warn!("startup websocket prewarm setup failed: {err:#}");
SessionStartupPrewarmResolution::Unavailable {
status: "failed",
prewarm_duration: None,
}
}
Err(err) => {
warn!("startup websocket prewarm setup join failed: {err}");
SessionStartupPrewarmResolution::Unavailable {
status: "join_failed",
prewarm_duration: Some(started_at.elapsed()),
}
}
}
}
}
impl Session {
pub(crate) async fn schedule_startup_prewarm(self: &Arc<Self>, input: PrewarmInput) {
let websocket_connect_timeout = self.provider().await.websocket_connect_timeout();
let mut state = self.state.lock().await;
if state.shutting_down {
return;
}
// Publish the warmup before another turn can be admitted. No network work
// or awaits occur while these guards are held.
let Ok(active_turn) = self.active_turn.try_lock() else {
return;
};
if active_turn.is_some() {
return;
}
if let Some(prewarm) = state.startup_prewarm.as_mut() {
let Some(completed) = (&mut prewarm.task).now_or_never() else {
return;
};
// Return a completed warmup's client to the existing cache before
// rechecking its socket: it may have closed since the last resume.
drop(completed);
state.startup_prewarm = None;
}
if self.features().enabled(Feature::CodeModePrewarm)
&& self.services.code_mode_service.is_available()
{
let session = Arc::clone(self);
tokio::spawn(async move {
if session.services.code_mode_service.session().await.is_err() {
warn!("code-mode host startup prewarm failed");
}
});
}
if !self.services.model_client.responses_websocket_enabled() {
// Without websocket prewarm, resolve auth once so Agent Identity bootstrap can
// register or engage this session's bearer fallback before the first user request.
let model_client = self.services.model_client.clone();
tokio::spawn(async move {
if let Err(err) = model_client.prewarm_auth().await {
warn!("startup auth prewarm failed: {err:#}");
}
});
return;
}
let session_telemetry = self.services.session_telemetry.clone();
let started_at = Instant::now();
let startup_prewarm_session = Arc::clone(self);
let startup_prewarm = tokio::spawn(
async move {
let result = schedule_startup_prewarm_inner(startup_prewarm_session, input).await;
let status = if result.is_ok() { "ready" } else { "failed" };
session_telemetry.record_startup_phase(
"startup_prewarm_total",
started_at.elapsed(),
Some(status),
);
session_telemetry.record_duration(
STARTUP_PREWARM_DURATION_METRIC,
started_at.elapsed(),
&[("status", status), ("input", input.as_str())],
);
result
}
.instrument(trace_span!(
"startup_prewarm",
otel.name = "startup_prewarm",
thread.id = %self.thread_id(),
prewarm.input = input.as_str(),
)),
);
state.set_session_startup_prewarm(SessionStartupPrewarmHandle::new(
startup_prewarm,
started_at,
websocket_connect_timeout,
));
}
#[tracing::instrument(level = "trace", skip_all)]
pub(crate) async fn consume_startup_prewarm_for_regular_turn(
&self,
cancellation_token: &CancellationToken,
) -> SessionStartupPrewarmResolution {
let Some(startup_prewarm) = self.take_session_startup_prewarm().await else {
return SessionStartupPrewarmResolution::Unavailable {
status: "not_scheduled",
prewarm_duration: None,
};
};
startup_prewarm
.resolve(&self.services.session_telemetry, cancellation_token)
.await
}
}
async fn schedule_startup_prewarm_inner(
session: Arc<Session>,
input: PrewarmInput,
) -> CodexResult<ModelClientSession> {
let prewarm_started_at = Instant::now();
let mut client_session = session.services.model_client.new_session();
let websocket_ready = client_session.is_websocket_prewarmed().await;
// Count the decision before preparation can fail; fresh clients also need prewarm.
session.services.session_telemetry.counter(
"codex.startup_prewarm.websocket_check",
/*inc*/ 1,
&[
(
"outcome",
if websocket_ready {
"ready"
} else {
"needs_prewarm"
},
),
("input", input.as_str()),
],
);
if websocket_ready {
return Ok(client_session);
}
let base_instructions = session.get_prompt_base_instructions().await.text;
let startup_turn_context = session
.new_startup_prewarm_turn_with_sub_id(INITIAL_SUBMIT_ID.to_owned())
.await;
startup_turn_context.session_telemetry.record_startup_phase(
"startup_prewarm_create_turn_context",
prewarm_started_at.elapsed(),
/*status*/ None,
);
let startup_cancellation_token = CancellationToken::new();
let preconnect_model_info = Arc::clone(startup_turn_context.model_info());
// Spawned subagents inherit the root's selection, with the same feature and model filtering
// that capture applies to the actual request.
let inherits_root_service_tier =
session.inherits_root_service_tier(&startup_turn_context.session_source);
let preconnect_service_tier = if inherits_root_service_tier {
crate::session::get_service_tier(
crate::agent::host::service_tier(
&session,
startup_turn_context.initial_settings.service_tier.clone(),
)
.await,
&session.features(),
&preconnect_model_info,
)
} else {
startup_turn_context.initial_settings.service_tier.clone()
};
// The handshake precedes tool capture; attach the finalized step metadata to the warmup.
let (window_id, window_number, context_window_id) = session.current_window().await;
let mut handshake_metadata = startup_turn_context
.turn_metadata_state
.to_responses_metadata(
session.installation_id.clone(),
window_id,
CodexResponsesRequestKind::Prewarm,
);
crate::turn_metadata::ExecutionMetadata::from_settings(&startup_turn_context.initial_settings)
.apply_to(&mut handshake_metadata);
let handshake_metadata =
session.with_window_and_fork_metadata(handshake_metadata, window_number, context_window_id);
// Start the handshake with the expected route while capturing tools for generate=false.
let (step_context, ()) = tokio::try_join!(
async {
let built_tools_started_at = Instant::now();
let step_context = session
.capture_step_context(
Arc::clone(&startup_turn_context),
&startup_cancellation_token,
)
.await?;
startup_turn_context.session_telemetry.record_startup_phase(
"startup_prewarm_build_tools",
built_tools_started_at.elapsed(),
/*status*/ None,
);
Ok(step_context)
},
client_session.preconnect_websocket(
&preconnect_model_info,
preconnect_service_tier,
&startup_turn_context.session_telemetry,
&handshake_metadata,
),
)?;
let build_prompt_started_at = Instant::now();
let prompt_input = match input {
PrewarmInput::Base => Vec::new(),
PrewarmInput::History => {
// Use the same history projection and tool metadata as a sampling request.
// The real turn still checks this prefix before reusing the prepared response.
let mut history = session
.clone_history()
.await
.for_prompt(
&step_context.settings.model_info.input_modalities,
session.services.image_store.as_ref(),
)
.await;
session
.services
.executed_tool_calls
.attach_to_prompt(&mut history, &mut HashMap::new());
history
}
};
let startup_prompt = build_prompt(
prompt_input,
step_context.as_ref(),
BaseInstructions {
text: base_instructions,
provenance: None,
},
session
.current_window_uses_incremental_tools(&step_context)
.await,
);
startup_turn_context.session_telemetry.record_startup_phase(
"startup_prewarm_build_prompt",
build_prompt_started_at.elapsed(),
/*status*/ None,
);
// Tool discovery may have updated Responses Lite metadata since the eager handshake.
let responses_metadata = session
.responses_metadata(step_context.as_ref(), CodexResponsesRequestKind::Prewarm)
.await;
let websocket_warmup_started_at = Instant::now();
// Prewarm establishes the request baseline before the first turn can change effort.
client_session
.prewarm_websocket(
&startup_prompt,
&step_context.settings.model_info,
&step_context.session_telemetry,
session
.reasoning_effort_for_request(&step_context.settings, RequestEffortUsage::Sampling)
.await,
step_context.settings.reasoning_summary,
step_context.settings.service_tier.clone(),
&responses_metadata,
)
.await?;
startup_turn_context.session_telemetry.record_startup_phase(
"startup_prewarm_websocket_warmup",
websocket_warmup_started_at.elapsed(),
/*status*/ None,
);
Ok(client_session)
}

View File

@@ -0,0 +1,476 @@
//! Restricted updates to a running turn's immutable settings snapshots.
use super::environment::ensure_configs_stay_owner_provided;
use super::environment::validate_environment_configs;
use super::session::Session;
use super::session::SessionConfiguration;
use super::step_settings::ResolvedStepSettings;
use super::step_settings::StepSettingsConstraints;
use super::step_settings::StepSettingsUpdate;
use super::turn_context::TurnContext;
use crate::config::Config;
use crate::config::ConstraintResult;
use crate::environment_selection::validate_environment_ids_and_cwds;
use crate::exec_policy::AllowPrefixRules;
use akode_features::Feature;
use akode_prompts::ResolvedModelMessages;
use akode_protocol::openai_models::CatalogModel;
use akode_protocol::openai_models::GuardianV2ModelConfig;
use akode_protocol::openai_models::GuardianV2TranscriptModelConfig;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ModelOrigin;
use akode_protocol::protocol::EnvironmentConfigState;
use akode_protocol::protocol::TurnEnvironmentSelection;
use akode_protocol::protocol::TurnSettingsUpdate;
use akode_protocol::protocol::TurnSettingsUpdateOutcome;
use std::sync::Arc;
/// Temporary restrictions while approvals and Guardian still read the admitted
/// `TurnContext`. Ordinary live authorization is validated separately. Remove
/// these restrictions as their consumers migrate to captured step settings.
fn check_legacy_turn_safety(
turn_context: &TurnContext,
current: &ResolvedStepSettings,
destination: &ResolvedStepSettings,
live_config: &Config,
) -> Result<(), String> {
let stack = &live_config.config_layer_stack;
let requirements = stack.requirements();
let required_review = requirements
.auto_review_required_for_model(destination.selected_collaboration_mode().model());
let admitted_required_review = turn_context
.config
.config_layer_stack
.requirements()
.auto_review_required_for_model(&turn_context.model_info().slug);
let ignored_models = stack
.requirements_toml()
.auto_review
.as_ref()
.and_then(|review| review.ignore_rules.as_ref());
let ignores_prefix_rules =
|model: &ModelInfo| ignored_models.is_some_and(|models| models.contains(&model.slug));
// Approval policy and required-model classification still have consumers
// using the originating turn. The reviewer is captured separately.
if destination.constrained_approval_policy() != current.constrained_approval_policy()
|| destination.approval_policy() != turn_context.approval_policy()
{
return Err("the destination changes the admitted approval policy".to_string());
}
if required_review
!= requirements
.auto_review_required_for_model(current.selected_collaboration_mode().model())
|| required_review != admitted_required_review
{
return Err("the destination changes model-required approval authority".to_string());
}
// Command approval continues to use TurnContext::allow_prefix_rules.
if ignores_prefix_rules(&destination.model_info) != ignores_prefix_rules(&current.model_info)
|| ignores_prefix_rules(&destination.model_info)
!= (turn_context.allow_prefix_rules() == AllowPrefixRules::Ignore)
{
return Err("the destination changes the admitted prefix-rule policy".to_string());
}
check_legacy_model_safety(
turn_context.model_info(),
&current.model_info,
&destination.model_info,
&turn_context.config,
live_config,
)
}
/// Model-owned portion of the temporary legacy-turn safety check. Ordinary
/// model metadata may differ so diagnostics can expose unmigrated consumers.
fn check_legacy_model_safety(
admitted: &CatalogModel,
current: &CatalogModel,
destination: &CatalogModel,
admitted_config: &Config,
live_config: &Config,
) -> Result<(), String> {
if admitted.origin == ModelOrigin::Synthetic || current.origin == ModelOrigin::Synthetic {
return Err("the active model has only fallback metadata".to_string());
}
if destination.origin == ModelOrigin::Synthetic {
return Err("the destination model has only fallback metadata".to_string());
}
let retained_models = [admitted, current];
// TurnMetadataState pins both node REPL flags. Guardian prompt/evidence
// construction also reads node_repl_auto_review_required from the turn.
if retained_models.iter().any(|model| {
model.computer_use_review_required() != destination.computer_use_review_required()
}) {
return Err(
"the destination changes the admitted node REPL review requirement".to_string(),
);
}
if retained_models
.iter()
.any(|model| model.guardian != destination.guardian)
{
return Err("the destination changes the admitted Guardian coverage".to_string());
}
if retained_models
.iter()
.any(|model| model.node_repl_disabled != destination.node_repl_disabled)
{
return Err(
"the destination changes the admitted node REPL availability restriction".to_string(),
);
}
// guardian::review::guardian_review_session_config and Guardian V2 still
// select the reviewer from the retained parent metadata.
if retained_models
.iter()
.any(|model| model.auto_review_model_override != destination.auto_review_model_override)
{
return Err("the destination changes the explicit Guardian reviewer model".to_string());
}
if (admitted_config.features.enabled(Feature::GuardianV2) || destination.guardian.is_some())
&& admitted_config.features.enabled(Feature::GuardianApproval)
{
// GuardianV2Extension::on_tool_start reads the parent ModelInfo from
// thread_store. Its classifier settings are independent of the reviewer
// override. Local overrides may mask differences, but resolving those
// overrides remains the extension's responsibility.
let classification_settings =
|model: &ModelInfo| -> GuardianV2ModelConfig {
let mut settings = model
.model_messages
.as_ref()
.and_then(|messages| messages.guardian_v2.clone())
.unwrap_or_default();
// The legacy mode is accepted for compatibility but no longer selects behavior.
settings.async_classifier_mode = None;
// Missing and empty transcript records supply the same defaults.
if settings.transcript.as_ref().is_some_and(|transcript| {
*transcript == GuardianV2TranscriptModelConfig::default()
}) {
settings.transcript = None;
}
settings
};
let destination_settings = classification_settings(destination);
if retained_models
.iter()
.any(|model| classification_settings(model) != destination_settings)
{
return Err(
"the destination changes the admitted Guardian V2 classification settings"
.to_string(),
);
}
}
// guardian_review_session_config and Guardian V2 can fall back to parent
// metadata if their preferred reviewer is unavailable, including after a
// catalog refresh. V1 uses the admitted config; V2 can use the live config.
// An unchanged explicit reviewer override prevents both fallback paths.
if destination.auto_review_model_override.is_none() {
let destination_model_messages = ResolvedModelMessages::from_model(destination);
let destination_auto_review = destination_model_messages.auto_review();
let retained_model_messages =
retained_models.map(|model| ResolvedModelMessages::from_model(model));
let retained_auto_review = retained_model_messages
.each_ref()
.map(ResolvedModelMessages::auto_review);
if retained_auto_review.iter().any(|auto_review| {
auto_review.node_repl_policy != destination_auto_review.node_repl_policy
}) {
return Err(
"the destination changes the Guardian parent-fallback node REPL policy".to_string(),
);
}
for config in [admitted_config, live_config] {
let destination_policy = config.resolve_guardian_policy(destination_model_messages);
if retained_model_messages.iter().any(|model_messages| {
config.resolve_guardian_policy(*model_messages) != destination_policy
}) {
return Err(
"the destination changes the Guardian parent-fallback policy".to_string(),
);
}
}
let destination_template = destination_auto_review.policy_template.trim_end();
if retained_auto_review
.iter()
.any(|auto_review| auto_review.policy_template.trim_end() != destination_template)
{
return Err(
"the destination changes the Guardian parent-fallback policy template".to_string(),
);
}
}
Ok(())
}
impl Session {
/// Publishes settings to the named, originally captured live task, regardless
/// of task kind. Publication does not propagate to child sessions or require
/// the task to sample; consumers using initial settings remain unchanged.
///
/// Callers must serialize updates through completion, including model
/// resolution, so each sparse patch sees the preceding publication.
#[expect(
clippy::await_holding_invalid_type,
reason = "the final managed-policy check and active settings publication must remain atomic"
)]
pub(super) async fn apply_turn_settings(
&self,
turn_id: &str,
update: TurnSettingsUpdate,
) -> TurnSettingsUpdateOutcome {
let updates_model_settings = update.model.is_some()
|| update.effort.is_some()
|| update.summary.is_some()
|| update.service_tier.is_some();
let requires_model_switching = updates_model_settings
|| (update.approvals_reviewer.is_none() && update.environments.is_none());
if requires_model_switching && !self.features.enabled(Feature::StepModelSwitching) {
return TurnSettingsUpdateOutcome::Rejected {
reason: "turn settings updates require the step_model_switching feature"
.to_string(),
};
}
// Capture the running task named by this update and its settings, then release the lock.
// A task that starts during preparation is never a new target.
let target = {
let active = self.active_turn.lock().await;
active.as_ref().and_then(|active| {
active.task.as_ref().and_then(|task| {
(task.turn_context.sub_id == turn_id && !task.cancellation_token.is_cancelled())
.then(|| {
(
Arc::clone(&task.turn_context),
Arc::clone(&task.done),
task.turn_context.next_step_settings.load_full(),
)
})
})
})
};
let Some((turn_context, task_done, current)) = target else {
return TurnSettingsUpdateOutcome::TargetUnavailable;
};
let TurnSettingsUpdate {
approvals_reviewer,
environments: environment_requests,
model,
effort,
summary,
service_tier,
} = update;
let environments = environment_requests.map(|requests| {
requests
.into_iter()
.map(|request| {
TurnEnvironmentSelection::new(request, &self.services.selected_capability_roots)
})
.collect::<Vec<_>>()
});
let updates_step_settings = updates_model_settings || approvals_reviewer.is_some();
let update = StepSettingsUpdate {
approvals_reviewer,
model,
effort,
reasoning_summary: summary,
service_tier,
..Default::default()
};
// Build the proposed model and reviewer settings.
// Apply only the fields the caller supplied to the settings captured above. The task can
// progress, finish, or be cancelled while this awaits; we don't hold the update locks here.
let prepared = if updates_step_settings {
let current_environments = self.services.turn_environments.selections();
let proposed = environments.as_deref().unwrap_or(&current_environments);
self.prepare_step_settings_activation(&turn_context, &current, &update, proposed)
.await
.map(Some)
} else {
Ok(None)
};
// Validate the environment configuration supplied in the update.
let environment_config_validation = environments
.as_deref()
.map(|environments| validate_environment_configs(environments, &self.features));
// Confirm the task we originally targeted is still running.
let active = self.active_turn.lock().await;
let Some(task) = active.as_ref().and_then(|active| active.task.as_ref()) else {
return TurnSettingsUpdateOutcome::TargetUnavailable;
};
// A later task may reuse the same context and turn ID. `done` is a completion signal
// created for each task, so matching only the ID/context is insufficient. A mismatch
// abandons the update without retrying or applying it to the replacement.
if !Arc::ptr_eq(&task.done, &task_done)
|| !Arc::ptr_eq(&task.turn_context, &turn_context)
|| task.cancellation_token.is_cancelled()
{
return TurnSettingsUpdateOutcome::TargetUnavailable;
}
let updated_settings = match prepared {
Ok(settings) => settings,
Err(reason) => return TurnSettingsUpdateOutcome::Rejected { reason },
};
let candidate_settings = updated_settings.as_ref().unwrap_or(current.as_ref());
// Recheck the latest rules before applying the update.
// Managed requirements can change during model lookup. Keep the live authorization and
// safety checks together with applying the update under state and active_turn; no model
// lookup or other preparation runs under these locks.
let state = self.state.lock().await;
// Environment configuration can arrive before its executor connects. If this update
// omits environments, use what the running turn's manager knows now.
let current_environments = self.services.turn_environments.selections();
let proposed = environments.as_deref().unwrap_or(&current_environments);
let validation = (|| {
if let Some(configs) = environment_config_validation {
validate_environment_ids_and_cwds(
&self.services.turn_environments.environment_manager(),
proposed
.iter()
.map(|selection| (selection.environment_id.as_str(), &selection.cwd)),
)
.map_err(|error| error.to_string())?;
ensure_configs_stay_owner_provided(&current_environments, proposed)
.map_err(|error| error.to_string())?;
configs.map_err(|error| error.to_string())?;
}
self.validate_active_step_settings(
&turn_context,
candidate_settings,
&state.session_configuration,
proposed,
)
.map_err(|error| error.to_string())?;
// Neither a reviewer nor an environment change changes model-owned authority.
if requires_model_switching {
check_legacy_turn_safety(
&turn_context,
&current,
candidate_settings,
&state.session_configuration.original_config_do_not_use,
)?;
}
Ok::<_, String>(())
})();
if let Err(reason) = validation {
return TurnSettingsUpdateOutcome::Rejected { reason };
}
// Save changed settings first. The manager then installs any new environment list before
// waking waiting work. The next step cannot read either until we release this lock.
if let Some(settings) = updated_settings {
task.turn_context
.next_step_settings
.store(Arc::new(settings));
}
if environments.is_some() {
self.services.turn_environments.update_selections(proposed);
}
TurnSettingsUpdateOutcome::Applied
}
async fn prepare_step_settings_activation(
&self,
turn_context: &TurnContext,
current: &ResolvedStepSettings,
update: &StepSettingsUpdate,
environments: &[TurnEnvironmentSelection],
) -> Result<ResolvedStepSettings, String> {
let (requirements, overrides, trusted_guardian_reviewer) = {
let state = self.state.lock().await;
let configuration = &state.session_configuration;
let stack = &configuration.original_config_do_not_use.config_layer_stack;
(
stack.requirements().clone(),
configuration.model_info_overrides.clone(),
configuration.trusted_guardian_reviewer,
)
};
let constraints = StepSettingsConstraints {
requirements: &requirements,
guardian_approval_enabled: self.features.enabled(Feature::GuardianApproval),
trusted_guardian_reviewer,
has_full_disk_write_access: any_environment_has_full_disk_write(
turn_context,
environments,
),
};
current
.apply_update(
update,
&constraints,
self.services.models_manager.as_ref(),
&overrides,
&self.features,
)
.await
.map_err(|error| error.to_string())
}
/// Rechecks ordinary managed authorization after asynchronous resolution.
/// Unlike the temporary legacy-turn check, these requirements also apply
/// once all execution consumers read their captured `StepContext`.
fn validate_active_step_settings(
&self,
turn_context: &TurnContext,
settings: &ResolvedStepSettings,
configuration: &SessionConfiguration,
environments: &[TurnEnvironmentSelection],
) -> ConstraintResult<()> {
let requirements = configuration
.original_config_do_not_use
.config_layer_stack
.requirements();
settings.revalidate(&StepSettingsConstraints {
requirements,
guardian_approval_enabled: self.features.enabled(Feature::GuardianApproval),
trusted_guardian_reviewer: configuration.trusted_guardian_reviewer,
has_full_disk_write_access: any_environment_has_full_disk_write(
turn_context,
environments,
),
})
}
}
fn any_environment_has_full_disk_write(
turn: &TurnContext,
environments: &[TurnEnvironmentSelection],
) -> bool {
let fallback = turn.config.permissions.permission_profile();
let mut known = environments.iter().filter_map(|environment| {
let (profile, roots) = match &environment.config {
EnvironmentConfigState::FromThread => (fallback, &environment.workspace_roots),
EnvironmentConfigState::Ready(config) => (
config.permission_profile.permission_profile(),
&config.workspace_roots,
),
EnvironmentConfigState::Pending | EnvironmentConfigState::Failed(_) => return None,
};
Some(
profile
.clone()
.materialize_project_roots_with_path_uris(roots)
.file_system_sandbox_policy()
.has_full_disk_write_access_for_convention(environment.cwd.infer_path_convention()),
)
});
match known.next() {
Some(first) => first || known.any(|full_write| full_write),
None => fallback
.file_system_sandbox_policy()
.has_full_disk_write_access(),
}
}
#[cfg(test)]
#[path = "step_activation_tests.rs"]
mod tests;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,107 @@
//! Request-scoped settings and capabilities, with live grants bound to the originating turn.
use std::sync::Arc;
use crate::agents_md::LoadedAgentsMd;
use crate::config::TokenBudgetConfig;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::realtime_conversation::RealtimeConversationSnapshot;
use crate::session::step_settings::ResolvedStepSettings;
use crate::session::turn_context::TurnContext;
use crate::session::turn_context::TurnEnvironment;
use crate::tools::router::ToolRouter;
use akode_extension_api::ExtensionData;
use akode_features::Feature;
use akode_file_system::EnvironmentAccess;
use akode_mcp::McpBinding;
use akode_otel::SessionTelemetry;
use akode_plugin::ExecutorPluginHookSource;
use akode_protocol::items::ModelInvocationContext;
use akode_protocol::protocol::TurnContextItem;
use tokio_util::sync::CancellationToken;
/// Request-scoped state that may change between model sampling requests.
#[derive(Clone)]
pub(crate) struct StepContext {
/// Input prefix captured for this normal inference attempt, acknowledged with its output.
pub(crate) sampled_through_sequence: Option<u64>,
/// Final serving value for this invocation; retained by its code cell across waits.
pub(crate) serving_assessment: Option<Arc<crate::guardian::ServingAssessment>>,
pub(crate) turn: Arc<TurnContext>,
/// Preempts this request and yields its code-mode observations when user input arrives.
pub(crate) preempt: Option<CancellationToken>,
/// Realtime call activity and instructions captured for this sampling request.
pub(crate) realtime: RealtimeConversationSnapshot,
/// One immutable settings version captured before request preparation.
pub(crate) settings: Arc<ResolvedStepSettings>,
/// Frozen turn preferences resolved against this step's captured model.
pub(crate) token_budget: Option<TokenBudgetConfig>,
/// Telemetry context tagged with this sampling request's model.
pub(crate) session_telemetry: SessionTelemetry,
pub(crate) environments: TurnEnvironmentSnapshot,
/// Child bindings captured with this step; configured-only when opted in.
pub(crate) inherited_environments: TurnEnvironmentSnapshot,
/// Admitted executor hooks bound to this step's discovery, plugin policy, and MCP routing.
pub(crate) executor_hook_sources: Vec<ExecutorPluginHookSource>,
/// Keeps the extension inputs used to build this step's tools for its World State as well.
pub(crate) extension_data: Arc<ExtensionData>,
/// The exact MCP connections, configuration, and catalog captured for this step.
pub(crate) mcp: Arc<McpBinding>,
/// The finalized tool plan advertised and executed for this exact sampling request.
pub(crate) tool_router: Arc<ToolRouter>,
/// The canonical AGENTS.md value observed with this environment snapshot.
pub(crate) loaded_agents_md: Option<Arc<LoadedAgentsMd>>,
}
impl StepContext {
/// Feature that selects the tool layout of new windows on this route.
pub(crate) fn incremental_tools_feature(&self) -> Option<Feature> {
if self.settings.model_info.use_responses_lite {
Some(Feature::IncrementalTools)
} else {
// The legacy layout was only used by the removed Amazon Bedrock providers.
None
}
}
/// Whether new context windows should record tool declarations in history.
pub(crate) fn incremental_tools_enabled(&self) -> bool {
self.incremental_tools_feature()
.is_some_and(|feature| self.turn.config.features.enabled(feature))
}
/// Pairs the step's environments with access using current session and originating-turn grants.
pub(crate) fn environments(&self) -> Vec<(&TurnEnvironment, impl EnvironmentAccess + '_)> {
self.environments
.turn_environments()
.map(|environment| (environment, self.fs_accessor(environment)))
.collect()
}
pub(crate) fn fs_accessor<'a>(
&self,
environment: &'a TurnEnvironment,
) -> impl EnvironmentAccess + 'a + use<'a> {
let grants = self
.turn
.granted_permissions(&environment.selection.environment_id);
environment.fs_accessor(grants)
}
/// Persist the context captured for this request, even after a live update.
pub(crate) fn to_turn_context_item(&self) -> TurnContextItem {
let mut item = self.turn.to_turn_context_item();
item.realtime_active = Some(self.realtime.active);
item
}
pub(crate) fn model_context(&self) -> ModelInvocationContext {
ModelInvocationContext {
model_slug: self.settings.model_info.slug.clone(),
reasoning_effort: self
.settings
.effective_reasoning_effort()
.map(|effort| effort.to_string()),
}
}
}

View File

@@ -0,0 +1,342 @@
//! Configured inputs retained independently of future thread settings.
use crate::config::Constrained;
use crate::config::ConstraintError;
use crate::config::ConstraintResult;
use akode_config::ConfigRequirements;
use akode_features::Features;
use akode_models_manager::ModelsManagerConfig;
use akode_models_manager::manager::ModelsManager;
use akode_otel::SessionTelemetry;
use akode_protocol::config_types::ApprovalsReviewer;
use akode_protocol::config_types::CollaborationMode;
use akode_protocol::config_types::Personality;
use akode_protocol::config_types::ReasoningSummary;
use akode_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
use akode_protocol::config_types::ServiceTier;
use akode_protocol::openai_models::CatalogModel;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::protocol::AskForApproval;
use std::sync::Arc;
/// Model and execution settings selected for an individual model step within
/// a turn. A turn may contain several steps, each using its own captured settings.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct StepSettings {
pub(crate) collaboration_mode: CollaborationMode,
/// `None` follows the pinned model's default.
pub(crate) reasoning_summary: Option<ReasoningSummary>,
/// Normalized requested tier; resolution filters it against the pinned model.
pub(crate) service_tier: Option<String>,
pub(crate) personality: Option<Personality>,
pub(crate) approval_policy: Constrained<AskForApproval>,
pub(crate) approvals_reviewer: ApprovalsReviewer,
}
/// Immutable configured choices, pinned model metadata, and effective request values.
///
/// One snapshot may produce several fresh `StepContext`s. Replacing the
/// snapshot does not change steps or actions that have already captured it.
#[derive(Clone, Debug)]
pub(crate) struct ResolvedStepSettings {
/// Inputs for later sparse patches. Unset defaults and unsupported requested
/// tiers must not be reconstructed from the effective values below.
selected: Arc<StepSettings>,
pub(crate) model_info: Arc<CatalogModel>,
/// Effective request summary: the configured value or the pinned model's default.
pub(crate) reasoning_summary: ReasoningSummary,
/// Tier sent on requests, filtered by feature and model support.
pub(crate) service_tier: Option<String>,
/// MCP historically follows refreshed thread defaults. Preserve that behavior
/// for older clients until this turn receives an explicit live reviewer update.
pub(crate) mcp_approvals_reviewer_override: Option<ApprovalsReviewer>,
}
impl ResolvedStepSettings {
/// Derives request values from selected settings and pinned metadata.
pub(super) fn new(
selected: Arc<StepSettings>,
model_info: Arc<CatalogModel>,
features: &Features,
) -> Self {
let reasoning_summary = selected
.reasoning_summary
.unwrap_or(model_info.default_reasoning_summary);
let service_tier =
super::get_service_tier(selected.service_tier.clone(), features, &model_info);
Self {
selected,
model_info,
reasoning_summary,
service_tier,
mcp_approvals_reviewer_override: None,
}
}
pub(crate) fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
self.selected
.collaboration_mode
.settings
.reasoning_effort
.as_ref()
}
pub(crate) fn effective_reasoning_effort(&self) -> Option<ReasoningEffort> {
self.reasoning_effort()
.or(self.model_info.default_reasoning_level.as_ref())
.cloned()
}
pub(crate) fn effective_collaboration_mode(&self) -> CollaborationMode {
let mut collaboration_mode = self.selected.collaboration_mode.clone();
collaboration_mode.settings.model = self.model_info.slug.clone();
collaboration_mode
}
pub(crate) fn approval_policy(&self) -> AskForApproval {
self.selected.approval_policy.value()
}
pub(crate) fn approvals_reviewer(&self) -> ApprovalsReviewer {
self.selected.approvals_reviewer
}
/// Retained inputs for constructing a snapshot against different model metadata.
pub(super) fn selected(&self) -> &StepSettings {
&self.selected
}
pub(super) fn selected_collaboration_mode(&self) -> &CollaborationMode {
&self.selected.collaboration_mode
}
pub(crate) fn personality(&self) -> Option<Personality> {
self.selected.personality
}
pub(super) fn constrained_approval_policy(&self) -> &Constrained<AskForApproval> {
&self.selected.approval_policy
}
/// Applies sparse edits to the retained selection, preserving pinned metadata
/// unless the model changes, then resolves request values.
pub(super) async fn apply_update(
&self,
update: &StepSettingsUpdate,
constraints: &StepSettingsConstraints<'_>,
models_manager: &dyn ModelsManager,
overrides: &ModelInfoOverrides,
features: &Features,
) -> ConstraintResult<Self> {
let selected = self.selected.apply(update, constraints)?;
let model_info =
if selected.collaboration_mode.model() == self.selected.collaboration_mode.model() {
Arc::clone(&self.model_info)
} else {
Arc::new(selected.resolve_model_info(models_manager, overrides).await)
};
let mut next = Self::new(Arc::new(selected), model_info, features);
next.mcp_approvals_reviewer_override = update
.approvals_reviewer
.or(self.mcp_approvals_reviewer_override);
Ok(next)
}
/// Rechecks the retained selection against current managed constraints.
pub(super) fn revalidate(
&self,
constraints: &StepSettingsConstraints<'_>,
) -> ConstraintResult<()> {
// TODO: Revisit the split with StepSettings::validate, which does not
// check inherited approval values against the supplied managed allow-lists.
// Sharing these checks would also make ordinary settings updates stricter
// after a requirements refresh.
self.selected.validate(constraints)?;
constraints
.requirements
.approval_policy
.can_set(&self.approval_policy())?;
constraints
.requirements
.approvals_reviewer
.can_set(&self.approvals_reviewer())
}
pub(super) fn telemetry(&self, base: &SessionTelemetry) -> SessionTelemetry {
base.clone().with_model(
self.selected.collaboration_mode.model(),
&self.model_info.slug,
)
}
}
/// Explicit startup overrides applied to catalog-derived model metadata.
/// Construct from `Config::to_models_manager_config()` so model-derived base
/// instructions are not mistaken for explicit overrides.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ModelInfoOverrides {
pub(crate) context_window: Option<i64>,
pub(crate) auto_compact_token_limit: Option<i64>,
pub(crate) tool_output_token_limit: Option<usize>,
pub(crate) base_instructions: Option<String>,
}
impl From<ModelsManagerConfig> for ModelInfoOverrides {
fn from(config: ModelsManagerConfig) -> Self {
Self {
context_window: config.model_context_window,
auto_compact_token_limit: config.model_auto_compact_token_limit,
tool_output_token_limit: config.tool_output_token_limit,
base_instructions: config.base_instructions,
}
}
}
impl ModelInfoOverrides {
pub(crate) fn models_manager_config(
&self,
personality: Option<Personality>,
) -> ModelsManagerConfig {
ModelsManagerConfig {
model_context_window: self.context_window,
model_auto_compact_token_limit: self.auto_compact_token_limit,
tool_output_token_limit: self.tool_output_token_limit,
base_instructions: self.base_instructions.clone(),
personality,
// The models manager already owns its catalog.
model_catalog: None,
}
}
}
/// Sparse edits applied independently to each settings owner.
///
/// Do not materialize a partial update against one settings owner and reuse
/// that full value for another. Merge the requested edits with each target.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct StepSettingsUpdate {
pub(crate) model: Option<String>,
pub(crate) effort: Option<Option<ReasoningEffort>>,
/// A complete collaboration mode takes precedence over model and effort edits.
pub(crate) collaboration_mode: Option<CollaborationMode>,
pub(crate) reasoning_summary: Option<ReasoningSummary>,
pub(crate) service_tier: Option<Option<String>>,
pub(crate) personality: Option<Personality>,
pub(crate) approval_policy: Option<AskForApproval>,
pub(crate) approvals_reviewer: Option<ApprovalsReviewer>,
}
/// Constraints used when applying and validating a candidate settings version.
/// Each caller supplies the permissions of the target environment selection.
pub(crate) struct StepSettingsConstraints<'a> {
pub(crate) requirements: &'a ConfigRequirements,
pub(crate) guardian_approval_enabled: bool,
pub(crate) trusted_guardian_reviewer: bool,
pub(crate) has_full_disk_write_access: bool,
}
impl StepSettings {
/// Resolves the selected model using the session's explicit startup overrides.
pub(super) async fn resolve_model_info(
&self,
models_manager: &dyn ModelsManager,
overrides: &ModelInfoOverrides,
) -> CatalogModel {
let config = overrides.models_manager_config(self.personality);
models_manager
.get_model_info(self.collaboration_mode.model(), &config)
.await
}
/// Applies edits and validates the result against the supplied constraints.
/// Callers must supply the constraints of the proposed target environment.
pub(crate) fn apply(
&self,
update: &StepSettingsUpdate,
constraints: &StepSettingsConstraints<'_>,
) -> ConstraintResult<Self> {
let mut next = self.clone();
next.collaboration_mode = update.collaboration_mode.clone().unwrap_or_else(|| {
self.collaboration_mode.with_updates(
update.model.clone(),
update.effort.clone(),
/*developer_instructions*/ None,
)
});
if let Some(summary) = update.reasoning_summary {
next.reasoning_summary = Some(summary);
}
if let Some(service_tier) = update.service_tier.clone() {
// TODO(aibrahim): Remove once v2 clients no longer send the legacy
// "fast" service tier value.
next.service_tier = Some(match service_tier {
Some(service_tier) => ServiceTier::from_request_value(&service_tier)
.map_or(service_tier, |service_tier| {
service_tier.request_value().to_string()
}),
None => SERVICE_TIER_DEFAULT_REQUEST_VALUE.to_string(),
});
}
if let Some(personality) = update.personality {
next.personality = Some(personality);
}
if let Some(approval_policy) = update.approval_policy {
next.approval_policy.set(approval_policy)?;
}
if let Some(approvals_reviewer) = update.approvals_reviewer {
constraints
.requirements
.approvals_reviewer
.can_set(&approvals_reviewer)?;
next.approvals_reviewer = approvals_reviewer;
}
if !constraints.trusted_guardian_reviewer
&& self.collaboration_mode.model() != next.collaboration_mode.model()
&& constraints
.requirements
.auto_review_required_for_model(next.collaboration_mode.model())
&& update.approvals_reviewer.is_none()
{
constraints
.requirements
.approvals_reviewer
.can_set(&ApprovalsReviewer::AutoReview)?;
next.approvals_reviewer = ApprovalsReviewer::AutoReview;
}
next.validate(constraints)?;
Ok(next)
}
/// Checks directly constructed settings or rechecks changed constraints.
pub(super) fn validate(
&self,
constraints: &StepSettingsConstraints<'_>,
) -> ConstraintResult<()> {
if constraints.trusted_guardian_reviewer {
return Ok(());
}
let model = self.collaboration_mode.model();
if !constraints
.requirements
.auto_review_required_for_model(model)
{
return Ok(());
}
if self.approvals_reviewer == ApprovalsReviewer::AutoReview
&& !constraints.has_full_disk_write_access
&& constraints.guardian_approval_enabled
{
return Ok(());
}
Err(ConstraintError::AutoReviewRequired {
model: model.to_string(),
})
}
}
#[cfg(test)]
#[path = "step_settings_tests.rs"]
pub(super) mod tests;

View File

@@ -0,0 +1,490 @@
use super::*;
use crate::config::PermissionProfileState;
use crate::config::test_config;
use crate::session::session::SessionConfiguration;
use crate::session::session::SessionSettingsUpdate;
use crate::session::tests::make_session_configuration_for_tests;
use akode_config::ConfigLayerStack;
use akode_config::RequirementSource;
use akode_config::Sourced;
use akode_features::Feature;
use akode_models_manager::manager::StaticModelsManager;
use akode_models_manager::model_info::model_info_from_slug;
use akode_prompts::render_model_instructions;
use akode_protocol::config_types::ModeKind;
use akode_protocol::config_types::Settings;
use akode_protocol::models::BaseInstructionsProvenance;
use akode_protocol::models::PermissionProfile;
use akode_protocol::openai_models::AutoReviewMessages;
use akode_protocol::openai_models::GuardianV2ModelConfig;
use akode_protocol::openai_models::ModelsResponse;
use akode_protocol::openai_models::TruncationPolicyConfig;
use akode_protocol::permissions::FileSystemAccessMode;
use akode_protocol::permissions::FileSystemPath;
use akode_protocol::permissions::FileSystemSandboxEntry;
use akode_protocol::permissions::FileSystemSandboxKind;
use akode_protocol::permissions::FileSystemSandboxPolicy;
use akode_protocol::permissions::FileSystemSpecialPath;
use akode_protocol::permissions::NetworkSandboxPolicy;
use akode_protocol::protocol::TurnEnvironmentSelections;
use core_test_support::test_codex::local;
use pretty_assertions::assert_eq;
use std::collections::BTreeSet;
use std::sync::Arc;
use test_case::test_case;
pub(crate) fn update_selected_settings_for_test(
settings: &mut ResolvedStepSettings,
update: impl FnOnce(&mut StepSettings),
) {
update(Arc::make_mut(&mut settings.selected));
}
fn set_requirements(configuration: &mut SessionConfiguration, requirements: ConfigRequirements) {
let config = Arc::make_mut(&mut configuration.original_config_do_not_use);
config.config_layer_stack = ConfigLayerStack::new(
config
.config_layer_stack
.all_layers_low_to_high()
.cloned()
.collect(),
requirements,
config.config_layer_stack.requirements_toml().clone(),
)
.expect("replace test requirements");
}
#[tokio::test]
async fn proposed_permission_profile_is_checked_before_step_settings() {
let mut configuration = make_session_configuration_for_tests().await;
let permission = Constrained::allow_only(PermissionProfile::read_only());
let permission_error = permission
.can_set(&PermissionProfile::Disabled)
.unwrap_err();
configuration.permission_profile_state =
PermissionProfileState::from_constrained_legacy(permission).unwrap();
let approval = Constrained::allow_only(AskForApproval::OnRequest);
let approval_error = approval.can_set(&AskForApproval::Never).unwrap_err();
Arc::make_mut(&mut configuration.step_settings).approval_policy = approval;
let mut requirements = configuration
.original_config_do_not_use
.config_layer_stack
.requirements()
.clone();
requirements.approvals_reviewer.value = Constrained::allow_only(ApprovalsReviewer::User);
let reviewer_error = requirements
.approvals_reviewer
.can_set(&ApprovalsReviewer::AutoReview)
.unwrap_err();
requirements.auto_review_required_models = Some(Sourced::new(
BTreeSet::from(["protected-model".to_string()]),
RequirementSource::Unknown,
));
set_requirements(&mut configuration, requirements);
let protected_mode = configuration.step_settings.collaboration_mode.with_updates(
Some("protected-model".to_string()),
/*effort*/ None,
/*developer_instructions*/ None,
);
let invalid_profile = SessionSettingsUpdate {
permission_profile: Some(PermissionProfile::Disabled),
..Default::default()
};
assert_eq!(
configuration.apply(&invalid_profile, &[]).err().as_ref(),
Some(&permission_error)
);
for (step_settings, expected) in [
(
StepSettingsUpdate {
approval_policy: Some(AskForApproval::Never),
..Default::default()
},
&approval_error,
),
(
StepSettingsUpdate {
approvals_reviewer: Some(ApprovalsReviewer::AutoReview),
..Default::default()
},
&reviewer_error,
),
(
StepSettingsUpdate {
collaboration_mode: Some(protected_mode),
..Default::default()
},
&reviewer_error,
),
] {
assert_eq!(
configuration
.step_settings
.apply(
&step_settings,
&configuration.step_settings_constraints(&[]),
)
.err()
.as_ref(),
Some(expected),
);
assert_eq!(
configuration
.apply(
&SessionSettingsUpdate {
step_settings,
..invalid_profile.clone()
},
&[]
)
.err()
.as_ref(),
Some(&permission_error),
);
}
}
#[tokio::test]
async fn model_review_requirement_uses_the_proposed_permission_profile() {
let mut configuration = make_session_configuration_for_tests().await;
configuration.permission_profile_state = PermissionProfileState::from_constrained_legacy(
Constrained::allow_any(PermissionProfile::Disabled),
)
.unwrap();
Arc::make_mut(&mut configuration.step_settings).approvals_reviewer = ApprovalsReviewer::User;
Arc::make_mut(&mut configuration.original_config_do_not_use)
.features
.enable(Feature::GuardianApproval)
.unwrap();
let mut requirements = configuration
.original_config_do_not_use
.config_layer_stack
.requirements()
.clone();
requirements.auto_review_required_models = Some(Sourced::new(
BTreeSet::from(["protected-model".to_string()]),
RequirementSource::Unknown,
));
set_requirements(&mut configuration, requirements);
let collaboration_mode = configuration.step_settings.collaboration_mode.with_updates(
Some("protected-model".to_string()),
/*effort*/ None,
/*developer_instructions*/ None,
);
let updates = SessionSettingsUpdate {
step_settings: StepSettingsUpdate {
collaboration_mode: Some(collaboration_mode.clone()),
..Default::default()
},
..Default::default()
};
assert_eq!(
configuration.apply(&updates, &[]).err(),
Some(ConstraintError::AutoReviewRequired {
model: "protected-model".to_string()
}),
);
let updated = configuration
.apply(
&SessionSettingsUpdate {
permission_profile: Some(PermissionProfile::read_only()),
..updates
},
&[],
)
.expect("the proposed restricted profile permits the protected model");
assert_eq!(
updated.step_settings.as_ref(),
&StepSettings {
collaboration_mode,
approvals_reviewer: ApprovalsReviewer::AutoReview,
..configuration.step_settings.as_ref().clone()
}
);
assert_eq!(updated.permission_profile(), PermissionProfile::read_only());
assert_eq!(
updated
.apply(
&SessionSettingsUpdate {
permission_profile: Some(PermissionProfile::Disabled),
..Default::default()
},
&[],
)
.err(),
Some(ConstraintError::AutoReviewRequired {
model: "protected-model".to_string(),
}),
);
}
#[tokio::test]
async fn environment_only_update_revalidates_existing_step_settings() {
let mut configuration = make_session_configuration_for_tests().await;
let profile = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy {
kind: FileSystemSandboxKind::Restricted,
glob_scan_max_depth: None,
entries: vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Write,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
FileSystemAccessMode::Read,
),
],
},
NetworkSandboxPolicy::Restricted,
);
configuration.permission_profile_state =
PermissionProfileState::from_constrained_legacy(Constrained::allow_any(profile)).unwrap();
let settings = Arc::make_mut(&mut configuration.step_settings);
settings.collaboration_mode = settings.collaboration_mode.with_updates(
Some("protected-model".to_string()),
/*effort*/ None,
/*developer_instructions*/ None,
);
settings.approvals_reviewer = ApprovalsReviewer::AutoReview;
Arc::make_mut(&mut configuration.original_config_do_not_use)
.features
.enable(Feature::GuardianApproval)
.unwrap();
let mut requirements = configuration
.original_config_do_not_use
.config_layer_stack
.requirements()
.clone();
requirements.auto_review_required_models = Some(Sourced::new(
BTreeSet::from(["protected-model".to_string()]),
RequirementSource::Unknown,
));
set_requirements(&mut configuration, requirements);
let environments = vec![local(configuration.cwd().clone())];
assert_eq!(configuration.validate(&environments), Ok(()));
// Removing the selected workspace also removes its read-only carveout,
// leaving this profile with full-disk write access.
assert_eq!(
configuration
.apply(
&SessionSettingsUpdate {
environments: Some(TurnEnvironmentSelections::new(
configuration.cwd().clone(),
Vec::new(),
)),
..Default::default()
},
&environments,
)
.err(),
Some(ConstraintError::AutoReviewRequired {
model: "protected-model".to_string(),
}),
);
}
fn configured_settings() -> StepSettings {
StepSettings {
collaboration_mode: CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "model-a".to_string(),
reasoning_effort: Some(ReasoningEffort::Low),
developer_instructions: Some("keep these instructions".to_string()),
},
},
reasoning_summary: Some(ReasoningSummary::Concise),
service_tier: None,
personality: Some(Personality::Friendly),
approval_policy: Constrained::allow_any(AskForApproval::OnRequest),
approvals_reviewer: ApprovalsReviewer::User,
}
}
fn step_settings_constraints(requirements: &ConfigRequirements) -> StepSettingsConstraints<'_> {
StepSettingsConstraints {
requirements,
guardian_approval_enabled: false,
trusted_guardian_reviewer: false,
has_full_disk_write_access: false,
}
}
#[test]
fn sparse_patch_uses_the_settings_version_being_updated() {
let requirements = ConfigRequirements::default();
let constraints = step_settings_constraints(&requirements);
let initial = configured_settings();
let tier_update = StepSettingsUpdate {
service_tier: Some(Some("fast".to_string())),
..Default::default()
};
let latest = initial
.apply(
&StepSettingsUpdate {
model: Some("model-b".to_string()),
effort: Some(Some(ReasoningEffort::High)),
..Default::default()
},
&constraints,
)
.expect("model update should apply");
let updated = latest
.apply(&tier_update, &constraints)
.expect("a previously prepared sparse update should apply");
let expected = StepSettings {
service_tier: Some(ServiceTier::Fast.request_value().to_string()),
..latest
};
assert_eq!(updated, expected);
}
#[test]
fn collaboration_replacement_wins_and_effort_clear_remains_sparse() {
let requirements = ConfigRequirements::default();
let constraints = step_settings_constraints(&requirements);
let initial = configured_settings();
let replacement = CollaborationMode {
mode: ModeKind::Plan,
settings: Settings {
model: "model-b".to_string(),
reasoning_effort: Some(ReasoningEffort::Medium),
developer_instructions: None,
},
};
let replaced = initial
.apply(
&StepSettingsUpdate {
model: Some("ignored-model".to_string()),
effort: Some(Some(ReasoningEffort::High)),
collaboration_mode: Some(replacement.clone()),
..Default::default()
},
&constraints,
)
.expect("collaboration mode should replace model and effort edits");
assert_eq!(
replaced,
StepSettings {
collaboration_mode: replacement.clone(),
..initial
}
);
let cleared = replaced
.apply(
&StepSettingsUpdate {
effort: Some(None),
..Default::default()
},
&constraints,
)
.expect("effort clear should apply");
assert_eq!(
cleared,
StepSettings {
collaboration_mode: replacement.with_updates(
/*model*/ None,
Some(None),
/*developer_instructions*/ None,
),
..replaced
}
);
}
#[test_case(BaseInstructionsProvenance::Custom; "explicit instructions")]
#[test_case(BaseInstructionsProvenance::Model { model: "model-a".to_string() }; "model-derived instructions")]
#[tokio::test]
async fn model_resolution_preserves_startup_overrides_and_instruction_provenance(
provenance: BaseInstructionsProvenance,
) {
let configured_instructions = "explicit instructions";
let auto_review = AutoReviewMessages {
policy: Some("catalog review policy".to_string()),
policy_template: Some("catalog review template".to_string()),
node_repl_policy: None,
rejection_instructions: None,
timeout_instructions: None,
};
let guardian_v2 = GuardianV2ModelConfig {
classifier_instructions: Some("catalog classifier".to_string()),
review_threshold_basis_points: Some(7_500),
..Default::default()
};
let mut model = model_info_from_slug("model-b");
model.context_window = Some(90_000);
model.max_context_window = Some(100_000);
model.auto_compact_token_limit = Some(80_000);
model.truncation_policy = TruncationPolicyConfig::tokens(/*limit*/ 1_000);
let messages = model
.model_messages
.as_mut()
.expect("test model should have instruction metadata");
messages.instructions_template =
Some("Catalog B.\n# Personality\nfixed\n# Rules\nKeep the rules.".to_string());
messages.auto_review = Some(auto_review);
messages.guardian_v2 = Some(guardian_v2);
let catalog = ModelsResponse {
models: vec![model],
};
let models_manager = StaticModelsManager::new(
/*auth_manager*/ None,
catalog.clone(),
akode_models_manager::ModelOrigin::ExplicitConfig,
);
let mut config = test_config().await;
config.model = Some("model-a".to_string());
config.model_catalog = Some(catalog);
config.model_context_window = Some(160_000);
config.model_auto_compact_token_limit = Some(70_000);
config.tool_output_token_limit = Some(777);
config.base_instructions = Some(configured_instructions.to_string());
let explicit_instructions = matches!(&provenance, BaseInstructionsProvenance::Custom);
config.base_instructions_provenance = Some(provenance);
// Capture the same filtered explicit overrides that session startup owns.
let overrides = ModelInfoOverrides::from(config.to_models_manager_config());
for (personality, catalog_instructions) in [
(
Personality::Friendly,
"Catalog B.\n# Personality\nfixed\n# Rules\nKeep the rules.",
),
(Personality::None, "Catalog B.\n# Rules\nKeep the rules."),
] {
config.personality = Some(personality);
let mut settings = configured_settings();
settings.collaboration_mode = settings.collaboration_mode.with_updates(
Some("model-b".to_string()),
/*effort*/ None,
/*developer_instructions*/ None,
);
settings.personality = config.personality;
let legacy = models_manager
.get_model_info("model-b", &config.to_models_manager_config())
.await;
let resolved = settings
.resolve_model_info(&models_manager, &overrides)
.await;
assert_eq!(resolved, legacy);
assert_eq!(
render_model_instructions(&resolved),
if explicit_instructions {
configured_instructions
} else {
catalog_instructions
},
);
}
}

View File

@@ -0,0 +1,22 @@
//! Core-owned queue metadata; forwarding transfers the residency guard with the operation.
use akode_extension_api::ExtensionDataInit;
use akode_protocol::protocol::Op;
use akode_protocol::protocol::W3cTraceContext;
use tokio::sync::OwnedRwLockReadGuard;
#[derive(Debug)]
pub(crate) struct Submission {
pub id: String,
pub op: Op,
/// Accepted with settings, never separately from the request that supplied them.
pub turn_extension_init: Option<ExtensionDataInit>,
/// Optional W3C trace carrier propagated across async submission handoffs.
pub trace: Option<W3cTraceContext>,
pub parent_turn_id: Option<String>,
pub root_turn_id: Option<String>,
/// Keeps a V2 recipient resident until this submission is handled or dropped.
pub residency_guard: Option<OwnedRwLockReadGuard<()>>,
/// Owns delivery until dispatch; failed or abandoned submissions discard it.
pub message_delivery: Option<crate::agent_communication::MessageDelivery>,
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,191 @@
//! Handles persistent thread-settings updates and serializes their persistence
//! with checkpoints written directly to storage.
use super::session::Session;
use super::session::SessionSettingsUpdate;
use super::step_settings::StepSettingsUpdate;
use crate::WithTurnExtensionData;
use crate::config::ConstraintResult;
use akode_history::RolloutItem;
use akode_protocol::capabilities::SelectedCapabilityRoot;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::protocol::ThreadSettingsAppliedEvent;
use akode_protocol::protocol::ThreadSettingsOverrides;
use akode_protocol::protocol::ThreadSettingsSnapshot;
use akode_thread_store::ThreadStoreError;
use akode_thread_store::ThreadStoreResult;
use std::sync::Arc;
use tokio::sync::SemaphorePermit;
impl Session {
/// Persist before publishing so a failed write cannot change the running catalog.
pub(crate) async fn replace_dynamic_tools(
&self,
tools: Vec<akode_protocol::dynamic_tools::DynamicToolSpec>,
) -> CodexResult<()> {
let _settings_guard = acquire_persistence_lock(self).await;
if let Some(live_thread) = self.live_thread() {
let config = self.get_config().await;
if !config.allow_persistent_dynamic_tool_updates {
return Err(CodexErr::UnsupportedOperation(
"The host has disabled dynamic tool updates for persistent threads.".into(),
));
}
let persistence_error = |error: ThreadStoreError| match error {
ThreadStoreError::Unsupported { .. } => {
CodexErr::UnsupportedOperation(error.to_string())
}
_ => CodexErr::Fatal(format!("failed to replace dynamic tools: {error}")),
};
live_thread
.append_items(&[RolloutItem::DynamicToolsUpdated {
thread_id: self.thread_id(),
tools: tools.clone(),
}])
.await
.map_err(persistence_error)?;
live_thread.flush().await.map_err(persistence_error)?;
}
let tools = Arc::from(tools);
let mut state = self.state.lock().await;
state.persisted_dynamic_tools = Arc::clone(&tools);
state.session_configuration.dynamic_tools = tools;
Ok(())
}
/// Captures and flushes current settings under the shared persistence permit.
pub(crate) async fn checkpoint_thread_settings(&self) -> ThreadStoreResult<()> {
let _settings_guard = acquire_persistence_lock(self).await;
if let Some(live_thread) = self.live_thread() {
live_thread
.append_items(&[RolloutItem::EventMsg(applied_event(self).await)])
.await?;
live_thread.flush().await?;
}
Ok(())
}
}
/// Applies standalone thread settings. The caller holds the persistence permit through notification.
#[expect(
clippy::await_holding_invalid_type,
reason = "the active-turn guard makes continuation invalidation atomic with turn admission"
)]
pub(super) async fn update(
session: &Session,
overrides: impl Into<WithTurnExtensionData<ThreadSettingsOverrides>>,
) -> ConstraintResult<ThreadSettingsSnapshot> {
let updates = prepare_update(overrides, &session.services.selected_capability_roots);
let commit = session.update_settings(updates).await?;
let active_turn = session.active_turn.lock().await;
// A registered running task retains its lineage so it can be recovered after a daemon
// restart. Reservations and finishing turns have no interrupted work to continue.
if active_turn
.as_ref()
.is_none_or(|active_turn| active_turn.task.is_none())
{
session.state.lock().await.last_started_turn_id = None;
}
Ok(commit.snapshot)
}
/// Converts protocol overrides into the internal settings update shape.
pub(super) fn prepare_update(
overrides: impl Into<WithTurnExtensionData<ThreadSettingsOverrides>>,
roots: &[SelectedCapabilityRoot],
) -> SessionSettingsUpdate {
let WithTurnExtensionData {
request: overrides,
turn_extension_init,
} = overrides.into();
let ThreadSettingsOverrides {
environments: environment_requests,
runtime_workspace_roots,
profile_workspace_roots,
approval_policy,
approvals_reviewer,
sandbox_policy,
permission_profile,
active_permission_profile,
windows_sandbox_level,
model,
effort,
summary,
service_tier,
collaboration_mode,
personality,
disabled_plugin_ids,
} = overrides;
SessionSettingsUpdate {
turn_extension_init,
step_settings: StepSettingsUpdate {
model,
effort,
collaboration_mode,
reasoning_summary: summary,
service_tier,
personality,
approval_policy,
approvals_reviewer,
},
environments: environment_requests.map(|requests| requests.select(roots)),
runtime_workspace_roots,
profile_workspace_roots,
sandbox_policy,
permission_profile,
active_permission_profile,
windows_sandbox_level,
disabled_plugin_ids,
..Default::default()
}
}
/// Acquires the shared permit before capturing or changing persistent settings.
pub(super) async fn acquire_persistence_lock(session: &Session) -> SemaphorePermit<'_> {
session
.thread_settings_persistence
.acquire()
.await
.unwrap_or_else(|_| unreachable!("thread settings persistence semaphore is never closed"))
}
/// Applies persistent settings and emits the resulting thread-owned snapshot.
pub(super) async fn apply_update(
session: &Session,
submission_id: String,
updates: SessionSettingsUpdate,
) -> ConstraintResult<()> {
let _settings_guard = acquire_persistence_lock(session).await;
let commit = session.update_settings(updates).await?;
emit_applied(session, submission_id, commit.snapshot).await;
Ok(())
}
/// Emits the snapshot published by one successful settings update.
pub(super) async fn emit_applied(
session: &Session,
submission_id: String,
snapshot: ThreadSettingsSnapshot,
) {
let msg = EventMsg::ThreadSettingsApplied(ThreadSettingsAppliedEvent {
thread_id: Some(session.thread_id()),
thread_settings: snapshot,
});
session
.send_event_raw_without_materializing_rollout(Event {
id: submission_id,
msg,
})
.await;
}
/// Builds a current thread-owned snapshot for storage checkpoints.
pub(super) async fn applied_event(session: &Session) -> EventMsg {
EventMsg::ThreadSettingsApplied(ThreadSettingsAppliedEvent {
thread_id: Some(session.thread_id()),
thread_settings: session.thread_settings_snapshot().await,
})
}

View File

@@ -0,0 +1,202 @@
use chrono::DateTime;
use chrono::Utc;
use akode_features::CurrentTimeReminderDeliveryMode;
use akode_features::Feature;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::models::ResponseItem;
use super::session::Session;
use super::turn_context::TurnContext;
use crate::config::Config;
use crate::config::CurrentTimeReminderConfig;
use crate::context::ContextualUserFragment;
use crate::context::CurrentTimeUnavailable;
use crate::context_manager::is_user_turn_boundary;
pub(super) fn apply_persistent_defaults(config: &mut Config) {
if config.current_time_reminder.is_some()
|| config
.config_layer_stack
.effective_config()
.get("features")
.and_then(|features| features.get("current_time_reminder"))
.is_some()
{
return;
}
// Apply defaults only to this turn; explicit settings and managed policy win.
if config.features.enable(Feature::CurrentTimeReminder).is_ok()
&& config.features.enabled(Feature::CurrentTimeReminder)
{
config.current_time_reminder = Some(CurrentTimeReminderConfig {
sleep_tool: true,
..CurrentTimeReminderConfig::default()
});
}
}
#[derive(Default)]
pub(crate) struct CurrentTimeReminderState {
last_delivery_time: Option<DateTime<Utc>>,
last_window_id: Option<String>,
last_clock_failure: Option<(String, akode_protocol::ContextWindowId)>,
pending_user_or_tool_output_boundary: bool,
}
impl CurrentTimeReminderState {
pub(super) fn note_recorded_items(&mut self, items: &[ResponseItem]) {
if items.iter().any(|item| {
is_user_turn_boundary(item)
|| matches!(
item,
ResponseItem::FunctionCallOutput { .. }
| ResponseItem::CustomToolCallOutput { .. }
| ResponseItem::ToolSearchOutput { .. }
)
}) {
self.pending_user_or_tool_output_boundary = true;
}
}
fn take_reminder_due(
&mut self,
window_id: &str,
current_time: DateTime<Utc>,
interval_seconds: u64,
delivery_mode: CurrentTimeReminderDeliveryMode,
) -> bool {
let is_new_window = self.last_window_id.as_deref() != Some(window_id);
// Consume the boundary for this inference even if the interval suppresses delivery.
let follows_user_or_tool_output =
std::mem::take(&mut self.pending_user_or_tool_output_boundary);
if delivery_mode == CurrentTimeReminderDeliveryMode::AfterUserOrToolOutput
&& !is_new_window
&& !follows_user_or_tool_output
{
return false;
}
let reminder_is_due = is_new_window
|| interval_seconds == 0
|| self.last_delivery_time.is_none_or(|last_delivery_time| {
current_time
.signed_duration_since(last_delivery_time)
.num_seconds()
>= i64::try_from(interval_seconds).unwrap_or(i64::MAX)
});
if reminder_is_due {
self.last_delivery_time = Some(current_time);
self.last_window_id = Some(window_id.to_string());
}
reminder_is_due
}
}
impl Session {
pub(super) async fn read_clock_for_context(
&self,
turn_context: &TurnContext,
clock_read: &'static str,
) -> CodexResult<Option<DateTime<Utc>>> {
let error = match self
.services
.time_provider
.current_time(self.thread_id)
.await
{
Ok(time) => {
let mut state = self.state.lock().await;
state.current_time_reminder.last_clock_failure = None;
return Ok(Some(time));
}
Err(error) => error,
};
if !turn_context
.config
.features
.enabled(Feature::NonfatalClockReadErrors)
{
return Err(CodexErr::Fatal(format!(
"failed to read current time: {error:#}"
)));
}
tracing::error!(
clock_read,
thread_id = %self.thread_id,
turn_id = %turn_context.sub_id,
"failed to read current time; the clock provider may be stalled"
);
{
let mut state = self.state.lock().await;
let failure = (
turn_context.sub_id.clone(),
state.auto_compact_window_ids().window_id.clone(),
);
// A compacted window may no longer contain the earlier notice.
if state.current_time_reminder.last_clock_failure.as_ref() == Some(&failure) {
return Ok(None);
}
state.current_time_reminder.last_clock_failure = Some(failure);
}
let response_item = ContextualUserFragment::into(CurrentTimeUnavailable);
self.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&response_item),
)
.await;
Ok(None)
}
}
pub(super) async fn maybe_record_current_time_reminder(
sess: &Session,
turn_context: &TurnContext,
window_id: &str,
) -> CodexResult<()> {
if !turn_context
.config
.features
.enabled(Feature::CurrentTimeReminder)
{
return Ok(());
}
let Some(config) = turn_context.config.current_time_reminder else {
return Ok(());
};
let Some(current_time) = sess
.read_clock_for_context(turn_context, "reminder")
.await?
else {
return Ok(());
};
let reminder_is_due = {
let mut state = sess.state.lock().await;
state.current_time_reminder.take_reminder_due(
window_id,
current_time,
config.reminder_interval_seconds,
config.delivery_mode,
)
};
if !reminder_is_due {
return Ok(());
}
let response_item =
ContextualUserFragment::into(crate::context::CurrentTimeReminder::new(current_time));
sess.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&response_item),
)
.await;
Ok(())
}

View File

@@ -0,0 +1,167 @@
use super::session::Session;
use super::turn_context::TurnContext;
use crate::config::Config;
use crate::config::TokenBudgetConfig;
use crate::context::ContextualUserFragment;
use akode_features::Feature;
use akode_protocol::openai_models::ModelInfo;
/// Detects explicit preferences before model defaults are applied to the turn config.
pub(super) fn has_explicit_settings(config: &Config) -> bool {
config
.config_layer_stack
.effective_config()
.get("features")
.and_then(|features| features.get("token_budget"))
.and_then(|token_budget| token_budget.as_table())
.is_some_and(|settings| {
settings
.keys()
.any(|key| !matches!(key.as_str(), "enabled" | "use_history_notes_extension"))
})
|| config
.token_budget
.as_ref()
.is_some_and(|token_budget| *token_budget != TokenBudgetConfig::default())
}
/// Resolves user-configured token-budget preferences against the current model's defaults.
pub(super) fn resolve_token_budget(
configured_token_budget: Option<&TokenBudgetConfig>,
use_model_defaults: bool,
model_info: &ModelInfo,
) -> Option<TokenBudgetConfig> {
if !use_model_defaults {
return configured_token_budget.cloned();
}
let Some(model_defaults) = model_info
.model_messages
.as_ref()
.and_then(|messages| messages.token_budget.as_ref())
else {
return configured_token_budget.cloned();
};
let token_budget = TokenBudgetConfig {
reminder_threshold_tokens: Some(model_defaults.reminder_threshold_tokens),
reminder_message_template: model_defaults.reminder_message_template.clone(),
guidance_message: Some(model_defaults.guidance_message.clone()),
auto_compact_fallback_prompt: Some(model_defaults.auto_compact_fallback_prompt.clone()),
auto_compact_fallback_buffer_tokens: Some(
model_defaults.auto_compact_fallback_buffer_tokens,
),
};
if let Err(error) = token_budget.validate() {
tracing::warn!(
model = %model_info.slug,
%error,
"ignoring invalid model-owned token-budget defaults"
);
return configured_token_budget.cloned();
}
Some(token_budget)
}
/// Applies model activation defaults before thread extensions are initialized.
pub(super) fn apply_model_defaults(config: &mut Config, model_info: &ModelInfo) {
let Some(model_defaults) = model_info
.model_messages
.as_ref()
.and_then(|messages| messages.token_budget.as_ref())
else {
return;
};
if !model_defaults.enabled {
return;
}
let has_explicit_config = config.token_budget.is_some()
|| config
.config_layer_stack
.effective_config()
.get("features")
.and_then(|features| features.get("token_budget"))
.is_some();
if has_explicit_config {
return;
}
if config.features.enable(Feature::TokenBudget).is_err() {
return;
}
// Managed requirements can pin the feature off even when enable() succeeds.
if !config.features.enabled(Feature::TokenBudget) {
return;
}
// Keep prompts unresolved so later turns and model switches use their own defaults.
config.token_budget = Some(TokenBudgetConfig::default());
}
pub(super) async fn maybe_record(
sess: &Session,
turn_context: &TurnContext,
base_window_tokens_remaining: Option<i64>,
allow_auto_compact_fallback: bool,
) {
if !turn_context.config.features.enabled(Feature::TokenBudget) {
return;
}
let Some(base_window_tokens_remaining) = base_window_tokens_remaining else {
return;
};
let Some(config) = turn_context.config.token_budget.as_ref() else {
return;
};
if config
.reminder_threshold_tokens
.is_some_and(|threshold| base_window_tokens_remaining <= threshold)
{
let reminder_due = {
let mut state = sess.state.lock().await;
state.claim_token_budget_reminder()
};
if reminder_due {
let response_item =
ContextualUserFragment::into(crate::context::TokenBudgetReminder::new(
&config.reminder_message_template,
base_window_tokens_remaining,
));
sess.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&response_item),
)
.await;
}
}
if !allow_auto_compact_fallback || base_window_tokens_remaining != 0 {
return;
}
let Some(prompt) = config.auto_compact_fallback_prompt.as_deref() else {
return;
};
let fallback_due = {
let mut state = sess.state.lock().await;
state.claim_auto_compact_fallback()
};
if !fallback_due {
return;
}
let response_item =
ContextualUserFragment::into(crate::context::AutoCompactFallbackPrompt::new(prompt));
sess.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&response_item),
)
.await;
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
//! Admits reply-bearing agent follow-ups through native message delivery.
//! Acceptance means queued by Core; the recipient can consume the input in a later turn.
//! Follow-ups retain the recipient's settings and pass turn-start metadata to native delivery.
use crate::PendingAgentMessage;
use crate::WithTurnExtensionData;
use crate::agent::types::AgentMessage;
use crate::agent::types::MessageDeliveryMode;
use crate::session::handlers;
use crate::session::session::Session;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::turn_input::NotSubmittedReason;
use akode_protocol::turn_input::TurnInput;
use akode_protocol::turn_input::TurnInputRequest;
use akode_protocol::turn_input::TurnInputSubmission;
use std::sync::Arc;
pub(super) async fn submit(
session: &Arc<Session>,
request: WithTurnExtensionData<TurnInputRequest>,
submission_id: String,
) -> CodexResult<TurnInputSubmission> {
let WithTurnExtensionData { request, .. } = request;
let TurnInputRequest { input, start, .. } = request;
let TurnInput::InterAgentCommunication(mut communication) = input else {
unreachable!("agent submission requires an agent message");
};
// CodexThread already checks local agent capacity before submitting this operation.
// Preserve the host's drain gate when accepting work for an idle recipient.
let _admission = if session.active_turn.lock().await.is_none() {
let Some(admission) = session.services.extensions.admit_turn_start() else {
return Ok(TurnInputSubmission::NotSubmitted {
reason: NotSubmittedReason::ServerDraining,
});
};
Some(admission)
} else {
None
};
if communication.encrypted_content.is_none() {
communication.content = AgentMessage::Plaintext(std::mem::take(&mut communication.content))
.into_communication(
communication.author.clone(),
communication.recipient.clone(),
MessageDeliveryMode::TriggerTurn,
)
.content;
}
// Calling start-or-steer requests work.
communication.trigger_turn = true;
let pending = PendingAgentMessage::from(communication);
// Bound the future layout depth of this additional native-delivery path.
Box::pin(handlers::inter_agent_communication(
session,
submission_id,
pending,
start,
))
.await;
Ok(TurnInputSubmission::Accepted)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,159 @@
//! Turn-start MCP reconciliation, discovery cancellation, and prewarm refresh boundaries.
use super::*;
use akode_mcp::McpResourceClient;
use akode_mcp::McpResourceClientCacheKey;
use pretty_assertions::assert_eq;
struct Recorder {
client: McpResourceClient,
requires_mcp: std::sync::atomic::AtomicBool,
keys: std::sync::Mutex<Vec<McpResourceClientCacheKey>>,
discovered: tokio::sync::Notify,
}
impl akode_extension_api::TurnLifecycleContributor for Recorder {
fn turn_start_phase(
&self,
_thread_store: &akode_extension_api::ExtensionData,
) -> akode_extension_api::TurnStartPhase {
akode_extension_api::TurnStartPhase::RegularTaskStart
}
fn requires_mcp_runtime(&self, _thread_store: &akode_extension_api::ExtensionData) -> bool {
self.requires_mcp.load(std::sync::atomic::Ordering::Relaxed)
}
fn on_turn_start<'a>(
&'a self,
_input: akode_extension_api::TurnStartInput<'a>,
) -> akode_extension_api::ExtensionFuture<'a, ()> {
Box::pin(async move {
self.keys
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(self.client.cache_key());
self.discovered.notify_one();
std::future::pending::<()>().await;
})
}
fn refresh_catalog_for_step<'a>(
&'a self,
_input: akode_extension_api::CatalogRefreshInput<'a>,
) -> akode_extension_api::ExtensionFuture<'a, bool> {
panic!("prewarm must not start cloud discovery");
}
}
#[tokio::test]
async fn turn_start_refreshes_dirty_mcp_reuses_clean_runtime_and_cancels_discovery() {
let (mut session, turn_context) = make_session_and_context().await;
let recorder = Arc::new(Recorder {
client: McpResourceClient::new(Arc::clone(&session.services.mcp_runtime)),
requires_mcp: Default::default(),
keys: Default::default(),
discovered: Default::default(),
});
let mut builder = akode_extension_api::ExtensionRegistryBuilder::new();
builder.turn_lifecycle_contributor(recorder.clone());
session.services.extensions = Arc::new(builder.build());
let session = Arc::new(session);
let turn_context = Arc::new(turn_context);
let prewarm = session
.new_startup_prewarm_turn_with_sub_id(INITIAL_SUBMIT_ID.to_owned())
.await;
session
.mcp_runtime_for_step(&prewarm, &[], &[], &HashSet::new())
.await;
let initial_key = recorder.client.cache_key();
for turn in 0..4 {
recorder
.requires_mcp
.store(turn > 0, std::sync::atomic::Ordering::Relaxed);
if turn == 0 {
session.mark_mcp_runtime_dirty();
} else if turn == 3 {
session.services.mcp_runtime.reconnect_on_next_refresh();
session.request_mcp_runtime_refresh();
}
session
.spawn_task(
Arc::clone(&turn_context),
Vec::new(),
crate::tasks::RegularTask::new(),
)
.await;
tokio::time::timeout(
std::time::Duration::from_secs(5),
recorder.discovered.notified(),
)
.await
.expect("regular-task contributor should run");
assert_eq!(session.mcp_refresh.is_pending(), turn == 0);
assert_eq!(
recorder
.keys
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.len(),
turn + 1
);
if turn > 0 {
session.refresh_mcp_if_dirty().await;
assert!(
recorder.client.cache_key()
== recorder
.keys
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)[turn],
"a clean refresh must reuse the published MCP runtime"
);
// Prewarm must also skip discovery while a regular turn is active.
session
.mcp_runtime_for_step(&prewarm, &[], &[], &HashSet::new())
.await;
}
let (cancellation_token, done) = {
let active_turn = session.active_turn.lock().await;
let task = active_turn
.as_ref()
.and_then(|turn| turn.task.as_ref())
.expect("discovery should run inside the registered task");
(task.cancellation_token.clone(), Arc::clone(&task.done))
};
let completed = done.notified();
tokio::pin!(completed);
completed.as_mut().enable();
cancellation_token.cancel();
tokio::time::timeout(std::time::Duration::from_secs(5), completed)
.await
.expect("discovery cancellation must finish the task without forced abort");
assert!(
session.mcp_refresh.is_pending(),
"cancelled discovery must request an MCP refresh before the task completes"
);
session.abort_all_tasks(TurnAbortReason::Interrupted).await;
}
let keys = recorder
.keys
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
assert!(
keys[0] == initial_key,
"unrelated contributors must not reconcile MCP"
);
assert!(
keys[1] != initial_key,
"discovery must observe the reconciled generation"
);
assert!(
keys[2] != keys[1],
"cancelled cloud preparation must request reprojection on the next turn"
);
assert!(
keys[3] != keys[2],
"the next turn must consume a pending reconnect before discovery"
);
}

View File

@@ -0,0 +1,122 @@
use super::handlers;
use super::session::Session;
use crate::state::TaskKind;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::protocol::Event;
use akode_protocol::protocol::EventMsg;
use akode_protocol::turn_input::SuspendTurnOutcome;
use std::sync::Arc;
use std::time::Duration;
use tracing::warn;
pub(super) async fn suspend_turn_and_shutdown(
session: &Arc<Session>,
submission_id: String,
) -> CodexResult<SuspendTurnOutcome> {
{
let active = session.active_turn.lock().await;
let Some(task) = active.as_ref().and_then(|turn| turn.task.as_ref()) else {
return Ok(SuspendTurnOutcome::NotActive);
};
if task.kind != TaskKind::Regular {
return Ok(SuspendTurnOutcome::UnsupportedTask);
}
}
let live_thread = session
.live_thread_for_persistence("suspend an unfinished root turn")
.map_err(|error| CodexErr::Fatal(error.to_string()))?;
// Flush before canceling execution so a persistence failure leaves the original turn running.
live_thread.flush().await.map_err(|error| {
CodexErr::Fatal(format!("flush before root turn suspension failed: {error}"))
})?;
// The flush can yield while the active turn completes or changes. Recheck its
// kind under the same lock used to remove it.
let mut turn = {
let mut active = session.active_turn.lock().await;
let Some(active_turn) = active.as_ref() else {
return Ok(SuspendTurnOutcome::NotActive);
};
let Some(task) = active_turn.task.as_ref() else {
return Ok(SuspendTurnOutcome::NotActive);
};
if task.kind != TaskKind::Regular {
return Ok(SuspendTurnOutcome::UnsupportedTask);
}
active.take().ok_or_else(|| {
CodexErr::Fatal("accepted root turn suspension had no running turn".to_string())
})?
};
let task = turn.task.take().ok_or_else(|| {
CodexErr::Fatal("accepted root turn suspension had no running task".to_string())
})?;
let turn_id = task.turn_context.sub_id.clone();
// A suspended task emits no terminal outcome.
drop(task.outcome_handoff);
// Normal shutdown records a terminal turn event, preventing another worker from
// recovering this turn under its original ID. Cancel the task without that event.
task.cancellation_token.cancel();
task.turn_context
.turn_metadata_state
.cancel_git_enrichment_task();
let mut task_handle = task.handle.detach();
match tokio::time::timeout(
Duration::from_millis(crate::tasks::GRACEFULL_INTERRUPTION_TIMEOUT_MS),
&mut task_handle,
)
.await
{
Ok(Ok(())) => {}
Ok(Err(error)) => {
warn!(thread_id = %session.thread_id, %error, "suspended turn task exited abnormally");
}
Err(_) => {
warn!(
thread_id = %session.thread_id,
"suspended turn task did not stop gracefully; aborting it"
);
task_handle.abort();
let _ = task_handle.await;
}
}
// Save any initial input the task had not claimed so a new worker can recover the turn.
let recorded = session
.record_pending_initial_input(
&task.turn_context,
&turn.turn_state,
task.pending_initial_input,
/*abort_reason*/ None,
)
.await;
// Other pending input and interactive waiters remain best effort across handoff.
session.input_queue.clear_pending(&turn).await;
// The root task has stopped without a terminal event. Fence new starts and stop every
// other local session, even if the suspension caller disconnects during cleanup.
// The host owns the separate tree-cleanup wait and any persistence-writer fencing.
session.services.local_agent_runtime.request_shutdown();
// Stop all producers before flushing their final history and closing its writer.
// If either persistence step fails, do not report success: the current worker
// retains ownership until worker-failure recovery can take responsibility.
handlers::shutdown_session_runtime(session).await;
live_thread.flush().await.map_err(|error| {
CodexErr::Fatal(format!("flush after root turn suspension failed: {error}"))
})?;
live_thread.shutdown().await.map_err(|error| {
CodexErr::Fatal(format!("close suspended root turn writer failed: {error}"))
})?;
recorded?;
// Announce completion only after extension cleanup and writer closure so a
// replacement worker cannot write the same thread concurrently.
session
.deliver_event_raw(Event {
id: submission_id,
msg: EventMsg::ShutdownComplete,
})
.await;
Ok(SuspendTurnOutcome::Suspended { turn_id })
}

View File

@@ -0,0 +1,118 @@
use super::*;
use akode_extension_api::ExtensionData;
use akode_extension_api::TurnItemContributor;
use akode_protocol::ResponseItemId;
use akode_protocol::items::AgentMessageContent;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use tracing_subscriber::prelude::*;
struct RewriteAgentMessageContributor;
impl TurnItemContributor for RewriteAgentMessageContributor {
fn contribute<'a>(
&'a self,
_thread_store: &'a ExtensionData,
_turn_store: &'a ExtensionData,
item: &'a mut TurnItem,
) -> akode_extension_api::ExtensionFuture<'a, Result<(), String>> {
Box::pin(async move {
if let TurnItem::AgentMessage(agent_message) = item {
agent_message.content = vec![AgentMessageContent::Text {
text: "plan contributed assistant text".to_string(),
}];
}
Ok(())
})
}
}
fn assistant_output_text(text: &str) -> ResponseItem {
ResponseItem::Message {
status: None,
encrypted_content: None,
id: Some(ResponseItemId::with_suffix("msg", "1")),
role: "assistant".to_string(),
content: vec![ContentItem::OutputText {
annotations: None,
logprobs: None,
text: text.to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
}
#[test]
fn post_sampling_token_estimate_is_disabled_by_always_on_sinks() {
let feedback = akode_feedback::CodexFeedback::new();
let subscriber = tracing_subscriber::registry()
.with(feedback.logger_layer())
.with(tracing_subscriber::fmt::layer().with_filter(akode_state::log_db::default_filter()));
static METADATA: tracing::Metadata<'static> = tracing::metadata! {
name: "post sampling token estimate filter probe",
target: POST_SAMPLING_TOKEN_ESTIMATE_TARGET,
level: tracing::Level::TRACE,
fields: &["turn_id", "estimated_token_count", "message"],
callsite: &CALLSITE,
kind: tracing::metadata::Kind::EVENT.hint(),
};
static CALLSITE: tracing::callsite::DefaultCallsite =
tracing::callsite::DefaultCallsite::new(&METADATA);
assert!(tracing::Subscriber::register_callsite(&subscriber, &METADATA).is_never());
}
#[tokio::test]
async fn plan_mode_uses_contributed_turn_item_for_last_agent_message() {
let (mut session, turn_context) = crate::session::tests::make_session_and_context().await;
let mut builder = akode_extension_api::ExtensionRegistryBuilder::new();
builder.turn_item_contributor(Arc::new(RewriteAgentMessageContributor));
session.services.extensions = Arc::new(builder.build());
let turn_store = ExtensionData::new(turn_context.sub_id.clone());
let mut state = PlanModeStreamState::new(&turn_context.sub_id);
let mut last_agent_message = None;
let item = assistant_output_text("original assistant text");
let step_context = StepContext::for_test(Arc::new(turn_context));
let handled = handle_assistant_item_done_in_plan_mode(
&session,
&step_context,
&turn_store,
&item,
&mut state,
/*previously_active_item*/ None,
&mut last_agent_message,
/*moderation*/ None,
)
.await;
assert!(handled);
assert_eq!(
last_agent_message.as_deref(),
Some("plan contributed assistant text")
);
}
#[test]
fn realtime_user_verification_notice_excludes_request_payload() {
let event = EventMsg::ElicitationRequest(akode_protocol::approvals::ElicitationRequestEvent {
turn_id: None,
server_name: "private-server-name".to_string(),
id: akode_protocol::mcp::RequestId::String("private-request-id".to_string()),
request: akode_protocol::approvals::ElicitationRequest::UserVerification {
meta: None,
title: "private-title".to_string(),
description: "private-description".to_string(),
challenge: "private-challenge".to_string(),
},
});
assert_eq!(
realtime_text_for_event(&event),
Some(RealtimeEventText::Handoff(
"<user_verification_notice>User verification is required. Please respond in the app.</user_verification_notice>".to_string(),
None,
)),
);
}

View File

@@ -0,0 +1,470 @@
use std::sync::Arc;
use super::session::Session;
use super::step_context::StepContext;
use super::turn_context::TurnContext;
use crate::agent::host::AgentRuntimeServices;
use crate::agent::host::AgentSessionReader;
use crate::context::TokenBudgetContext;
use crate::context::world_state::AgentsMdState;
use crate::context::world_state::CollaborationModeState;
use crate::context::world_state::CompactPermissionsState;
use crate::context::world_state::ContextWindowGuidanceState;
use crate::context::world_state::EnvironmentsInstructionsState;
use crate::context::world_state::EnvironmentsState;
use crate::context::world_state::ManagedDeveloperInstructionsState;
use crate::context::world_state::ModelCatalogState;
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::PluginsInstructionsState;
use crate::context::world_state::RealtimeState;
use crate::context::world_state::ToolsState;
use crate::context::world_state::TopLevelToolsState;
use crate::context::world_state::WorldState;
use crate::context::world_state::format_agent_paths;
use crate::tools::handlers::multi_agents_spec::MULTI_AGENT_V1_NAMESPACE;
use akode_extension_api::WorldStateContributionInput;
use akode_features::Feature;
use akode_file_system::FileSystemSandboxContext;
use akode_prompts::ApprovalPromptContext;
use akode_prompts::ResolvedModelMessages;
use akode_prompts::render_model_instructions;
use akode_protocol::error::Result as CodexResult;
use akode_protocol::models::BaseInstructionsProvenance;
use akode_protocol::models::ContentItemNamespace;
use akode_protocol::protocol::MultiAgentVersion;
use akode_tools::ToolName;
use akode_tools::ToolSpec;
impl Session {
pub(super) fn host_roster_reader(
&self,
turn_context: &TurnContext,
) -> Option<&Arc<dyn AgentSessionReader>> {
if turn_context.config.include_environment_context
&& turn_context.multi_agent_version == MultiAgentVersion::V2
&& let AgentRuntimeServices::Host(services) = &self.agent_runtime
{
services.session_reader.as_ref()
} else {
None
}
}
pub(crate) async fn current_window_uses_incremental_tools(
&self,
step_context: &StepContext,
) -> bool {
if step_context.incremental_tools_feature().is_none() {
return false;
}
let state = self.state.lock().await;
if state.history.annotated_items().is_empty() {
return step_context.incremental_tools_enabled();
}
state.history.has_tool_declarations()
}
#[tracing::instrument(name = "world_state.build", level = "info", skip_all)]
pub(crate) async fn build_world_state_for_step(
&self,
step_context: &StepContext,
new_window: bool,
) -> CodexResult<WorldState> {
let incremental_tools = if new_window {
step_context.incremental_tools_enabled()
} else {
self.current_window_uses_incremental_tools(step_context)
.await
};
let turn_context = step_context.turn.as_ref();
let settings = &step_context.settings;
let model_info = settings.model_info.as_ref();
let model_messages = ResolvedModelMessages::from_model(model_info);
tracing::trace!(
selected_capability_root_count = step_context
.extension_data
.get::<Vec<akode_exec_server::ResolvedSelectedCapabilityRoot>>()
.map_or(0, |roots| roots.len()),
"building step world state"
);
let render_current_instructions = || {
let instructions = render_model_instructions(model_info);
if !turn_context.config.update_plan_enabled
&& turn_context.config.model_catalog.is_none()
&& (incremental_tools
|| turn_context.config.base_instructions.is_none()
|| matches!(
turn_context.config.base_instructions_provenance,
Some(BaseInstructionsProvenance::Model { .. })
))
{
akode_prompts::without_update_plan_instructions(&instructions)
} else {
instructions
}
};
let model_state = if incremental_tools {
let base_instructions = self.get_base_instructions().await;
let instructions = match base_instructions.provenance {
Some(BaseInstructionsProvenance::Model { .. }) => render_current_instructions(),
Some(BaseInstructionsProvenance::Custom) | None => base_instructions.text,
};
ModelInstructionsState::for_incremental_tools(
&model_info.slug,
instructions,
turn_context
.config
.features
.enabled(Feature::SuppressModelChangeAnnouncements),
)
} else {
let model_instructions = render_current_instructions();
let base_instructions = self.get_prompt_base_instructions().await.text;
let previous_model = {
let state = self.state.lock().await;
state
.previous_turn_settings()
.map(|previous| previous.model)
.or_else(|| {
state
.base_instructions_provenance
.as_ref()
.and_then(|provenance| match provenance {
BaseInstructionsProvenance::Model { model } => Some(model),
BaseInstructionsProvenance::Custom => None,
})
.filter(|_| base_instructions != model_instructions)
.cloned()
})
};
ModelInstructionsState::new(
&model_info.slug,
previous_model.as_deref(),
model_instructions,
)
};
let environment_subagents = if turn_context.config.include_environment_context
&& matches!(self.agent_runtime, AgentRuntimeServices::Controller)
{
match turn_context.multi_agent_version {
MultiAgentVersion::V2 => format_agent_paths(
self.services
.agent_control
.child_agent_paths(self.thread_id)
.await
.into_iter(),
),
MultiAgentVersion::Disabled | MultiAgentVersion::V1 => {
self.services
.local_agent_runtime
.format_legacy_environment_context_subagents(self.thread_id)
.await
}
}
} else {
String::new()
};
let mut world_state = WorldState::default();
if turn_context
.config
.features
.enabled(Feature::CommandSessionsWorldState)
{
let mut sessions =
crate::unified_exec::command_sessions_state(&self.services.unified_exec_manager)
.await;
if step_context
.tool_router
.exposes_tool(&ToolName::plain("write_stdin"))
{
world_state.add_section(sessions);
} else {
sessions.polling_unavailable = true;
world_state.add_section(crate::context::world_state::DisabledCommandSessionsState(
sessions,
));
}
} else {
world_state
.add_section(crate::context::world_state::DisabledCommandSessionsState::default());
}
let extension_metrics = super::extension_metrics::from_session_telemetry(
step_context.session_telemetry.clone(),
);
let preserve_parent_tool_declarations =
!new_window && self.preserve_parent_tool_declarations();
if incremental_tools && !preserve_parent_tool_declarations {
let specs = step_context.tool_router.model_visible_specs();
let specs = specs
.iter()
.filter(|tool| !matches!(tool, ToolSpec::WebSearch { .. }))
.cloned()
.collect::<Vec<_>>();
let definitions = akode_tools::create_tools_json_for_responses_lite(&specs)?;
let mut top_level = TopLevelToolsState::new(
model_messages.incremental_tools(),
definitions,
Some(Arc::clone(&extension_metrics)),
)?;
if let Some(entries) = step_context.tool_router.exec_definitions() {
top_level = top_level.with_incremental_exec_tools(Some(entries));
}
world_state.add_section(top_level);
}
world_state.add_section(model_state);
let token_budget_enabled = turn_context.config.features.enabled(Feature::TokenBudget)
&& step_context
.settings
.model_info
.resolved_context_window()
.is_some();
if token_budget_enabled {
let window_ids = self.state.lock().await.auto_compact_window_ids().clone();
world_state.add_section(TokenBudgetContext::new(
turn_context
.session_source
.get_agent_path()
.unwrap_or_else(akode_protocol::AgentPath::root),
window_ids.first_window_id,
window_ids.previous_window_id,
window_ids.window_id,
));
}
let guidance = step_context
.token_budget
.as_ref()
.and_then(|config| config.guidance_message.as_deref())
.filter(|_| token_budget_enabled);
world_state.add_section(ContextWindowGuidanceState::new(guidance));
let realtime = &step_context.realtime;
world_state.add_section(RealtimeState::new(
realtime.active,
realtime
.mode_instructions
.as_ref()
.and_then(|instructions| instructions.start.as_deref())
.or(turn_context
.config
.experimental_realtime_start_instructions
.as_deref()),
realtime
.mode_instructions
.as_ref()
.and_then(|instructions| instructions.end.as_deref()),
));
world_state.add_section(AgentsMdState::new(step_context.loaded_agents_md.as_deref()));
let exec_policy = self
.services
.exec_policy
.current_for_prefix_rules(turn_context.allow_prefix_rules());
let approval_context =
ApprovalPromptContext::new(settings.approvals_reviewer(), model_messages);
if turn_context.config.include_permissions_instructions {
let environment = step_context.environments.primary();
let sandbox = environment
.filter(|environment| environment.environment().is_remote())
.map(|environment| {
environment.sandbox_context(/*additional_permissions*/ None)
});
let paths = sandbox
.as_ref()
.map(FileSystemSandboxContext::policy_context);
let permission_profile =
turn_context.permission_profile_for_environments(&step_context.environments);
#[allow(deprecated)]
let cwd = environment
.and_then(|environment| environment.cwd().to_abs_path().ok())
.unwrap_or_else(|| turn_context.cwd.clone());
world_state.add_section(PermissionsState::new(
&permission_profile,
settings.approval_policy(),
approval_context,
exec_policy.as_ref(),
&cwd,
paths.as_ref(),
turn_context
.config
.features
.enabled(Feature::ExecPermissionApprovals),
turn_context
.config
.features
.enabled(Feature::RequestPermissionsTool),
));
} else {
world_state.add_section(CompactPermissionsState::new(
exec_policy.as_ref(),
approval_context.approved_command_prefix_saved_heading(),
));
}
if turn_context.config.include_collaboration_mode_instructions {
world_state.add_section(CollaborationModeState::from_collaboration_mode(
&settings.effective_collaboration_mode(),
model_messages.collaboration_modes(),
turn_context.config.update_plan_enabled,
turn_context.config.model_catalog.is_some(),
));
}
if !crate::guardian::is_basic_session_source(&turn_context.session_source) {
let send_user_message_async_available = !turn_context.root_capabilities_restricted
&& step_context
.settings
.model_info
.experimental_supported_tools
.iter()
.any(|tool| tool == "send_user_message_async");
world_state.add_section(PersistentModeState::new(
turn_context.config.features.persistent_execution_enabled(
step_context.settings.effective_reasoning_effort().as_ref(),
),
model_messages.persistent_instructions(),
send_user_message_async_available,
));
}
if turn_context.config.include_environment_context {
world_state.host_roster_reader = self.host_roster_reader(turn_context).cloned();
let current_date = if turn_context.config.include_environment_context_time {
self.read_clock_for_context(turn_context, "environment_date")
.await?
.map(|current_time| {
current_time
.with_timezone(&chrono::Local)
.format("%Y-%m-%d")
.to_string()
})
} else {
None
};
world_state.add_section(
EnvironmentsState::from_turn_context_with_environments(
turn_context,
&step_context.environments,
current_date,
)
.await
.with_subagents(environment_subagents),
);
}
world_state.add_section(EnvironmentsInstructionsState::new(
turn_context.config.include_environment_context
&& turn_context
.config
.features
.enabled(Feature::DeferredExecutor),
));
let plugins_usage_instructions_available =
step_context.mcp.plugins_available() && model_info.include_plugin_usage_instructions;
let plugins_state = {
let state = self.state.lock().await;
PluginsInstructionsState::new(
plugins_usage_instructions_available,
model_messages.generic_plugin(),
state.history.raw_items(),
)
};
world_state.add_section(plugins_state);
if turn_context
.config
.features
.enabled(Feature::DeferredToolWorldState)
{
world_state.add_section(ToolsState::new(
step_context.tool_router.deferred_tool_namespaces(),
Arc::clone(&extension_metrics),
));
}
let environments = step_context.environments.to_selections();
let previous_world_state = self.state.lock().await.history.world_state_checkpoint();
for contributor in self.services.extensions.context_contributors() {
for section in contributor
.contribute_world_state(WorldStateContributionInput {
thread_id: self.thread_id(),
turn_id: turn_context.sub_id.as_str(),
model_info: &step_context.settings.model_info,
environments: &environments,
extension_metrics: Some(Arc::clone(&extension_metrics)),
session_store: &self.services.session_extension_data,
thread_store: &self.services.thread_extension_data,
turn_store: turn_context.extension_data.as_ref(),
step_store: &step_context.extension_data,
previous_world_state: previous_world_state.as_ref().map(|state| &state.state),
})
.await
{
world_state.add_extension_section(section);
}
}
let v2_namespace = turn_context
.config
.multi_agent_v2
.tool_namespace
.clone()
.map(ContentItemNamespace::from)
.unwrap_or(ContentItemNamespace::Functions);
let mut multi_agent_mode = MultiAgentModeState::new(
super::multi_agents::effective_multi_agent_mode(step_context),
)
.with_namespace(v2_namespace.clone());
if let Some(usage_hint_text) = super::multi_agents::usage_hint_text(step_context) {
let usage_hint =
MultiAgentUsageHintState::new(usage_hint_text).with_namespace(v2_namespace.clone());
multi_agent_mode = multi_agent_mode.with_usage_hint(&usage_hint);
world_state.add_section(usage_hint);
}
world_state.add_section(multi_agent_mode);
let spawn_tool = match turn_context.multi_agent_version {
MultiAgentVersion::Disabled => None,
MultiAgentVersion::V1 => Some(ToolName::new(
Some(MULTI_AGENT_V1_NAMESPACE.to_string()),
"spawn_agent",
)),
MultiAgentVersion::V2 => turn_context
.config
.multi_agent_v2
.expose_spawn_agent_model_overrides
.then(|| {
ToolName::new(
turn_context.config.multi_agent_v2.tool_namespace.clone(),
"spawn_agent",
)
}),
};
let model_overrides_available =
spawn_tool.is_some_and(|name| step_context.tool_router.exposes_tool(&name));
world_state.add_section(
if model_overrides_available
&& turn_context
.config
.features
.enabled(Feature::ModelCatalogInContext)
{
ModelCatalogState::new(
&turn_context.available_models,
turn_context.multi_agent_version,
)
} else {
ModelCatalogState::default()
}
.with_namespace(match turn_context.multi_agent_version {
MultiAgentVersion::Disabled => None,
MultiAgentVersion::V1 => Some(ContentItemNamespace::MultiAgentV1),
MultiAgentVersion::V2 => Some(v2_namespace),
}),
);
if !crate::guardian::is_basic_session_source(&turn_context.session_source) {
world_state.add_section(ManagedDeveloperInstructionsState::new(
turn_context
.config
.config_layer_stack
.requirements()
.additional_developer_instructions
.as_ref(),
));
}
Ok(world_state)
}
}

View File

@@ -0,0 +1,124 @@
//! Verifies prefix placement and item boundaries in initial session context assembly.
use super::step_context::StepContext;
use super::tests::make_session_and_context;
use crate::context::BaseInstructionsFragment;
use crate::context::ContextualUserFragment;
use crate::context::DeveloperInstructions;
use crate::context::UserInstructions;
use crate::context::world_state::Placement;
use crate::context::world_state::PreviousSectionState;
use crate::context::world_state::SectionTransition;
use crate::context::world_state::WorldState;
use crate::context::world_state::WorldStateSection;
use crate::context::world_state::WorldStateUpdate;
use crate::context::world_state::WorldStateUpdateContent;
use crate::context::world_state::split_prefix_updates;
use crate::context_manager::updates::merge_world_state_updates;
use akode_protocol::models::ResponseItem;
use core_test_support::responses::strip_metadata_from_items;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
struct ItemSection;
impl WorldStateSection for ItemSection {
const ID: &'static str = "items";
type Snapshot = bool;
fn render_diff(
&self,
_: PreviousSectionState<'_, Self::Snapshot>,
) -> SectionTransition<Self::Snapshot> {
(
Some(true),
vec![
WorldStateUpdate {
placement: Placement::Prefix,
content: WorldStateUpdateContent::Item(Box::new(additional_tools("example"))),
},
WorldStateUpdate {
placement: Placement::Prefix,
..WorldStateUpdate::fragment(BaseInstructionsFragment(
"base instructions".to_string(),
))
},
WorldStateUpdate::fragment(DeveloperInstructions::new("before item")),
WorldStateUpdate::fragment(UserInstructions {
directory: None,
text: "user before item".to_string(),
}),
WorldStateUpdate::fragment(DeveloperInstructions::new("separate before item"))
.standalone(),
WorldStateUpdate {
placement: Placement::Standalone,
content: WorldStateUpdateContent::Item(Box::new(additional_tools("middle"))),
},
WorldStateUpdate {
placement: Placement::Mergeable,
content: WorldStateUpdateContent::Item(Box::new(additional_tools("adjacent"))),
},
WorldStateUpdate::fragment(DeveloperInstructions::new("after item")),
WorldStateUpdate::fragment(UserInstructions {
directory: None,
text: "user after item".to_string(),
}),
WorldStateUpdate {
placement: Placement::Standalone,
content: WorldStateUpdateContent::Item(Box::new(additional_tools("trailing"))),
},
],
)
}
}
fn additional_tools(name: &str) -> ResponseItem {
ResponseItem::AdditionalTools {
id: None,
role: "developer".to_string(),
tools: Arc::from([json!({"type": "function", "name": name})]),
}
}
#[tokio::test]
async fn initial_context_preserves_world_state_items_and_snapshot() {
let (session, turn_context) = make_session_and_context().await;
let step_context = StepContext::for_test(Arc::new(turn_context));
let mut world_state = WorldState::default();
world_state.add_section(ItemSection);
let (updates, snapshot) = session
.build_initial_context_with_world_state(&step_context, &world_state)
.await;
let (prefix, context) = split_prefix_updates(updates);
assert_eq!(
strip_metadata_from_items(&prefix),
strip_metadata_from_items(&[
additional_tools("example"),
ContextualUserFragment::into(BaseInstructionsFragment("base instructions".to_string())),
]),
);
assert_eq!(
strip_metadata_from_items(&merge_world_state_updates(context)),
strip_metadata_from_items(&[
ContextualUserFragment::into(DeveloperInstructions::new("before item")),
ContextualUserFragment::into(DeveloperInstructions::new("separate before item")),
ContextualUserFragment::into(UserInstructions {
directory: None,
text: "user before item".to_string(),
}),
additional_tools("middle"),
additional_tools("adjacent"),
ContextualUserFragment::into(DeveloperInstructions::new("after item")),
ContextualUserFragment::into(UserInstructions {
directory: None,
text: "user after item".to_string(),
}),
additional_tools("trailing"),
]),
);
assert_eq!(
serde_json::to_value(snapshot).unwrap(),
json!({"items": true})
);
}