A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix: compact at tool-turn thresholds within a run (#3544)
kt6465da8ed700
diff --git a/crates/pa-cli/src/print_boundary/tests.rs b/crates/pa-cli/src/print_boundary/tests.rsindex 0560be0b70..91b3ece3cb 100644--- a/crates/pa-cli/src/print_boundary/tests.rs+++ b/crates/pa-cli/src/print_boundary/tests.rs@@ -138,6 +138,7 @@ async fn faux_engine_with_telemetry(on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,}).await.expect("the faux session assembles");diff --git a/crates/pa-cli/src/print_goal.rs b/crates/pa-cli/src/print_goal.rsindex 0bf9b12cbf..7c34f65a23 100644--- a/crates/pa-cli/src/print_goal.rs+++ b/crates/pa-cli/src/print_goal.rs@@ -862,6 +862,7 @@ mod tests {on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,@@ -1478,6 +1479,7 @@ mod tests {on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex 4640cd3fb1..edc95c28e4 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -767,6 +767,7 @@ pub(crate) async fn build_headless_engine_with(on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router,},)diff --git a/crates/pa-cli/src/print_runtime/faux.rs b/crates/pa-cli/src/print_runtime/faux.rsindex b65659ddb5..30075e580d 100644--- a/crates/pa-cli/src/print_runtime/faux.rs+++ b/crates/pa-cli/src/print_runtime/faux.rs@@ -172,6 +172,7 @@ pub(crate) async fn build_faux_engine_with(on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,},)diff --git a/crates/pa-cli/src/print_session_command.rs b/crates/pa-cli/src/print_session_command.rsindex a71ab1a2e5..58146d213a 100644--- a/crates/pa-cli/src/print_session_command.rs+++ b/crates/pa-cli/src/print_session_command.rs@@ -354,6 +354,7 @@ mod tests {on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex 8f2411ca86..30539fe7e0 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -71,6 +71,9 @@ pub struct SessionEngineConfig {/// `true` while a steering-lane action is queued or mid-selection: the/// running turn stops at the next boundary and the queued steer delivers.pub queued_steering_probe: Option<std::sync::Arc<dyn Fn() -> bool + Send + Sync>>,+ /// Embedding-owned turn boundary, consulted after queued steering.+ /// Returning true yields the run; the embedding owns any continuation.+ pub should_stop_after_turn: Option<pa_agent::agent_loop::ShouldStopAfterTurnFn>,/// `None` keeps the TS default ("one-at-a-time").pub steering_mode: Option<pa_agent::agent::QueueMode>,pub follow_up_mode: Option<pa_agent::agent::QueueMode>,@@ -636,14 +639,23 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<Sstd::sync::Arc::clone(&request_timing_wiring),super::request_timing::pass_through_transform(),)),- should_stop_after_turn: config.queued_steering_probe.take().map(|probe| {- let probe: pa_agent::agent_loop::ShouldStopAfterTurnFn =- std::sync::Arc::new(move |_context| {- let probe = std::sync::Arc::clone(&probe);- Box::pin(async move { Ok(probe()) })- });- probe- }),+ should_stop_after_turn: {+ let steering = config.queued_steering_probe.take();+ let boundary = config.should_stop_after_turn.take();+ Some(std::sync::Arc::new(move |context| {+ let steering = steering.clone();+ let boundary = boundary.clone();+ Box::pin(async move {+ if steering.as_ref().is_some_and(|probe| probe()) {+ return Ok(true);+ }+ match boundary {+ Some(hook) => hook(context).await,+ None => Ok(false),+ }+ })+ }))+ },should_stop_before_turn: config.queued_steering_probe.clone(),steering_mode: config.steering_mode,follow_up_mode: config.follow_up_mode,diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex a3dbf37e7c..0a2620e78b 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -59,6 +59,7 @@ async fn engine_runs_tool_loop_and_persists() {semantic_edges: None,cron_store: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,@@ -161,6 +162,7 @@ async fn spawned_child_prompt_stamps_its_depth() {semantic_edges: None,cron_store: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,@@ -231,6 +233,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {semantic_edges: None,cron_store: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,@@ -418,6 +421,7 @@ async fn create_session_appends_missing_resume_settings_rows() {semantic_edges: None,cron_store: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,diff --git a/crates/pa-core/tests/abort_kernel_cell.rs b/crates/pa-core/tests/abort_kernel_cell.rsindex 85ef1a298b..ef3be7fa2a 100644--- a/crates/pa-core/tests/abort_kernel_cell.rs+++ b/crates/pa-core/tests/abort_kernel_cell.rs@@ -175,6 +175,7 @@ async fn abort_during_a_kernel_cell_settles_the_turn_immediately() {on_background_work_settled: None,queued_goal_context_purge: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,}).awaitdiff --git a/crates/pa-core/tests/turn_boundary_kernel.rs b/crates/pa-core/tests/turn_boundary_kernel.rsindex 744990834a..10d9eedfc1 100644--- a/crates/pa-core/tests/turn_boundary_kernel.rs+++ b/crates/pa-core/tests/turn_boundary_kernel.rs@@ -179,6 +179,7 @@ async fn turn_boundary_host_requests_round_trip_through_a_real_kernel() {semantic_edges: None,cron_store: None,queued_steering_probe: None,+ should_stop_after_turn: None,image_model_router: None,steering_mode: None,follow_up_mode: None,diff --git a/crates/pa-daemon/src/agent_engine.rs b/crates/pa-daemon/src/agent_engine.rsindex 5bec2032d0..02f366ddd4 100644--- a/crates/pa-daemon/src/agent_engine.rs+++ b/crates/pa-daemon/src/agent_engine.rs@@ -191,7 +191,9 @@ pub struct AgentSessionEngine {/// Built once on the first prompt, reused across prompts: long-running/// arms clone the Arc and release this mutex before their awaits, so/// every read seam answers while a turn streams.- pub(crate) session: tokio::sync::Mutex<Option<Arc<CoreSessionEngine>>>,+ pub(crate) session: Arc<tokio::sync::Mutex<Option<Arc<CoreSessionEngine>>>>,+ threshold_yielded: Arc<std::sync::atomic::AtomicBool>,+ threshold_checks_enabled: Arc<std::sync::atomic::AtomicBool>,/// The build gate: at most one `build_session` in flight; the eager build/// and the first demand seam meet at one build.pub(crate) session_build: tokio::sync::Mutex<()>,diff --git a/crates/pa-daemon/src/agent_engine/lifecycle.rs b/crates/pa-daemon/src/agent_engine/lifecycle.rsindex df21317da4..7f434b5516 100644--- a/crates/pa-daemon/src/agent_engine/lifecycle.rs+++ b/crates/pa-daemon/src/agent_engine/lifecycle.rs@@ -1,6 +1,8 @@//! The engine's lifecycle surface: the constructor and the session//! build/adopt/retire cycle, the closed-state markers, the skill//! expansion and session-command funnels, and the kernel host wiring.+use std::sync::atomic::Ordering;+use super::{execute_session_command, json_round_trip, map_thinking_level,register_agent_message_host_handlers, register_agent_observe_host_handlers,@@ -153,7 +155,11 @@ impl AgentSessionEngine {initial_selection: std::sync::RwLock::new(selection),effective_thinking: std::sync::RwLock::new(None),service_tier: std::sync::RwLock::new(None),- session: tokio::sync::Mutex::new(None),+ session: std::sync::Arc::new(tokio::sync::Mutex::new(None)),+ threshold_yielded: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),+ threshold_checks_enabled: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(+ false,+ )),session_build: tokio::sync::Mutex::new(()),pending_branch: std::sync::Mutex::new(None),provider_target: std::sync::Arc::new(std::sync::RwLock::new(None)),@@ -1015,6 +1021,64 @@ impl AgentSessionEngine {queued_goal_context_purge,// The steering lane owns the stop hooks (a queued steer cuts the next turn).queued_steering_probe: self.config.queued_steering_probe.clone(),+ should_stop_after_turn: Some({+ let session = Arc::downgrade(&self.session);+ let target = Arc::clone(&self.provider_target);+ let yielded = Arc::clone(&self.threshold_yielded);+ let enabled = Arc::clone(&self.threshold_checks_enabled);+ Arc::new(move |context| {+ let session = session.clone();+ let target = Arc::clone(&target);+ let yielded = Arc::clone(&yielded);+ let enabled = Arc::clone(&enabled);+ Box::pin(async move {+ if context.tool_results.is_empty() || !enabled.load(Ordering::SeqCst) {+ return Ok(false);+ }+ let Some(session) = session.upgrade() else {+ return Ok(false);+ };+ let engine = session.lock().await.clone();+ let Some(engine) = engine else {+ return Ok(false);+ };+ // Capture the actual serving model before AgentEnd clears a routed override.+ let model = target+ .read()+ .expect("provider target lock")+ .as_ref()+ .map(|target| target.model.clone());+ let Some(model) = model else { return Ok(false) };+ let agent = engine.session.agent();+ let thinking = match agent.model_override() {+ Some(route) => route.thinking_level,+ None => agent.state().await.thinking_level,+ };+ let messages = context+ .context+ .messages+ .iter()+ .filter_map(|message| serde_json::to_value(message).ok())+ .filter_map(|value| serde_json::from_value(value).ok())+ .collect::<Vec<_>>();+ let due = pa_core::session_engine::compaction::threshold_compaction_due(+ &messages,+ model.context_window,+ pa_core::session_engine::compaction::request_output_budget(+ &model,+ pa_core::session_engine::provider_adapter::model_thinking_level(+ thinking,+ ),+ ),+ &engine.session.compaction_settings(),+ );+ if due {+ yielded.store(true, Ordering::SeqCst);+ }+ Ok(due)+ })+ })+ }),// Seeded from settings at create; the live switch updates the slot ahead of any later// build.steering_mode,diff --git a/crates/pa-daemon/src/agent_engine/tests/compaction.rs b/crates/pa-daemon/src/agent_engine/tests/compaction.rsindex 650bf4bdbb..2ea7cd001e 100644--- a/crates/pa-daemon/src/agent_engine/tests/compaction.rs+++ b/crates/pa-daemon/src/agent_engine/tests/compaction.rs@@ -1098,3 +1098,119 @@ fn compact_session_command_emits_the_result_on_success() {assert_eq!(rows.len(), 1, "the /compact echo only: {rows:?}");assert_eq!(rows[0]["customType"], "session_slash_command");}++#[test]+fn threshold_crossing_inside_one_run_compacts_before_the_next_model_turn() {+ let _faux = FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let (engine, _dir) = faux_engine_with_settings(+ &json!({+ "responses": [+ {"text":"seed reply"},+ {"content":[{"type":"text","text":"x".repeat(80_000)}, {"type":"toolCall","id":"synthetic-call","name":"synthetic_missing_tool","arguments":{}}]},+ {"text":"history summary"},+ {"text":"prefix summary"},+ {"text":"task finished"}+ ]+ }),+ 128_000 - FAUX_REQUEST_BUDGET - 20_000,+ );+ let mut events = Vec::new();+ admit(&engine, "seed".into(), &mut events);+ events.clear();+ admit(&engine, "continue task".into(), &mut events);+ let compaction = events+ .iter()+ .position(|event| matches!(event, EngineEvent::CompactionStart { .. }))+ .expect("threshold crossed inside run");+ let assistants: Vec<_> = events+ .iter()+ .enumerate()+ .filter_map(|(index, event)| {+ matches!(event, EngineEvent::AssistantMessage(_)).then_some(index)+ })+ .collect();+ assert_eq!(assistants.len(), 2, "one tool turn and one final turn");+ assert!(+ assistants[0] < compaction && compaction < assistants[1],+ "compaction must precede the next ordinary model call"+ );+ assert_eq!(+ assistant_texts(&events).last().map(String::as_str),+ Some("task finished")+ );+}++#[test]+fn failed_mid_run_compaction_resumes_without_retrying_each_tool_round() {+ let _faux = FAUX_TEST_LOCK+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let tool_turn = json!({"content":[{"type":"text","text":"x".repeat(80_000)}, {"type":"toolCall","id":"synthetic-call","name":"synthetic_missing_tool","arguments":{}}]});+ let (engine, _dir) = faux_engine_with_settings(+ &json!({+ "responses": [+ {"text":"seed reply"}, tool_turn,+ {"text":"", "stopReason":"error", "errorMessage":"synthetic summary failure"},+ {"text":"prefix summary"}, tool_turn,+ {"text":"task finished"}+ ]+ }),+ 128_000 - FAUX_REQUEST_BUDGET - 20_000,+ );+ let mut events = Vec::new();+ admit(&engine, "seed".into(), &mut events);+ events.clear();+ admit(&engine, "continue task".into(), &mut events);+ assert_eq!(+ events+ .iter()+ .filter(|event| matches!(event, EngineEvent::CompactionStart { .. }))+ .count(),+ 1+ );+ assert_eq!(+ assistant_texts(&events).last().map(String::as_str),+ Some("task finished")+ );+ assert!(events+ .iter()+ .any(|event| matches!(event, EngineEvent::Done(Ok(())))));+ let core = engine.session.blocking_lock().clone().unwrap();+ let entries = engine+ .runtime+ .block_on(async { core.session.shared_persistence().lock().await.get_entries() });+ let user_prompts: Vec<_> = entries+ .iter()+ .filter_map(|entry| match entry {+ pa_types::session::FileEntry::Message {+ message: pa_types::session::AgentMessage::User(user),+ ..+ } => Some(user.content.text()),+ _ => None,+ })+ .collect();+ assert_eq!(user_prompts, ["seed", "continue task"]);+}++/// A not-due recheck after a threshold yield keeps the in-run threshold+/// machinery armed: the suppression is reserved for a summary attempt+/// that failed to commit (cursor: "Recheck mismatch disables further+/// compaction").+#[test]+fn a_not_due_recheck_keeps_threshold_checks_armed() {+ use crate::auto_compaction::AutoCompactionRun;+ assert!(+ AutoCompactionRun::NotDue.continues_threshold_checks(),+ "a not-due recheck is not a failed summary"+ );+ assert!(+ AutoCompactionRun::Compacted.continues_threshold_checks(),+ "a committed summary keeps checking"+ );+ assert!(+ !AutoCompactionRun::Ran.continues_threshold_checks(),+ "a failed or skipped summary suppresses the rest of the run"+ );+}diff --git a/crates/pa-daemon/src/agent_engine/turn/model.rs b/crates/pa-daemon/src/agent_engine/turn/model.rsindex 140496de3e..9c2d403e88 100644--- a/crates/pa-daemon/src/agent_engine/turn/model.rs+++ b/crates/pa-daemon/src/agent_engine/turn/model.rs@@ -189,26 +189,83 @@ impl AgentSessionEngine {if !first {drop_trailing_assistant(&agent).await;}- match self- .run_turn_once(- &agent,- &prompt,- first,- boundary_passed,- aborted,- &mut **emit,- )- .await- {- Ok(TurnOnce::Message { assistant }) => {- // The settled messages already reached the- // transcript; this arm only carries the- // final message to the retry classifier.- Ok(*assistant)+ let mut admit_prompt = first;+ loop {+ let assistant = match self+ .run_turn_once(+ &agent,+ &prompt,+ admit_prompt,+ boundary_passed,+ aborted,+ &mut **emit,+ )+ .await+ {+ Ok(TurnOnce::Message { assistant }) => *assistant,+ Ok(TurnOnce::None) => {+ return Err(anyhow::anyhow!("No response produced."))+ }+ Ok(TurnOnce::Aborted) => return Ok(aborted_message(&model)),+ Err(error) => return Err(error),+ };+ if !self+ .threshold_yielded+ .swap(false, std::sync::atomic::Ordering::SeqCst)+ {+ return Ok(assistant);+ }+ // Requested boundaries stay owned by run_turns; consuming one here+ // would lose its explicit stop and goal-continuation semantics.+ let core = self.session.lock().await.clone();+ let pending = match core {+ Some(core) => {+ core.turn_boundary.compaction_scheduled().await+ || core.turn_boundary.refine_pending().await+ }+ None => false,+ };+ if aborted() {+ return Ok(aborted_message(&model));+ }+ if pending+ || self+ .config+ .queued_steering_probe+ .as_ref()+ .is_some_and(|probe| probe())+ {+ return Ok(assistant);+ }+ if aborted() {+ return Ok(aborted_message(&model));+ }+ // Keep the retry/failover episode alive across this artificial+ // yield. The engine owns a multi-thread runtime; the synchronous+ // compaction boundary may re-enter it without holding async locks.+ let outcome = tokio::task::block_in_place(|| {+ self.run_auto_compaction(&mut **emit)+ });+ self.threshold_checks_enabled.store(+ outcome.continues_threshold_checks(),+ std::sync::atomic::Ordering::SeqCst,+ );+ if outcome == crate::auto_compaction::AutoCompactionRun::Cancelled+ || aborted()+ {+ return Ok(aborted_message(&model));+ }+ if self+ .config+ .queued_steering_probe+ .as_ref()+ .is_some_and(|probe| probe())+ {+ return Ok(assistant);}- Ok(TurnOnce::None) => Err(anyhow::anyhow!("No response produced.")),- Ok(TurnOnce::Aborted) => Ok(aborted_message(&model)),- Err(error) => Err(error),+ // Continue the tool run without dropping its successful assistant+ // or inserting another copy of the admitted user prompt.+ admit_prompt = false;}}},diff --git a/crates/pa-daemon/src/agent_engine/turn/run_loop.rs b/crates/pa-daemon/src/agent_engine/turn/run_loop.rsindex 7e10586244..a00403b274 100644--- a/crates/pa-daemon/src/agent_engine/turn/run_loop.rs+++ b/crates/pa-daemon/src/agent_engine/turn/run_loop.rs@@ -29,6 +29,10 @@ impl AgentSessionEngine {// runs text-only (attachments are never re-sent).let prompt = first;let mut overflow_retry = false;+ self.threshold_yielded+ .store(false, std::sync::atomic::Ordering::SeqCst);+ self.threshold_checks_enabled+ .store(true, std::sync::atomic::Ordering::SeqCst);// Whether a loop-boundary frame already passed in this item: the// worker's run-opening frames are the first run's, so the engine// forwards the later runs' opening frames.@@ -44,7 +48,11 @@ impl AgentSessionEngine {if !self.run_pre_turn_overflow_compaction(emit) {return;}- if self.run_auto_compaction(emit) == AutoCompactionRun::Cancelled {+ if self+ .threshold_checks_enabled+ .load(std::sync::atomic::Ordering::SeqCst)+ && self.run_auto_compaction(emit) == AutoCompactionRun::Cancelled+ {return;}// The overflow retry re-issues the loop without a new user@@ -157,7 +165,11 @@ impl AgentSessionEngine {}// The settled turn's usage crossing the headroom auto-compacts; the// autonomous continuation decision below still runs after it.- if self.run_auto_compaction(emit) == AutoCompactionRun::Cancelled {+ if self+ .threshold_checks_enabled+ .load(std::sync::atomic::Ordering::SeqCst)+ && self.run_auto_compaction(emit) == AutoCompactionRun::Cancelled+ {return;}// The compact-trigger round is NOT consumed here: the review runsdiff --git a/crates/pa-daemon/src/auto_compaction.rs b/crates/pa-daemon/src/auto_compaction.rsindex 622d9db94e..7f1ff58577 100644--- a/crates/pa-daemon/src/auto_compaction.rs+++ b/crates/pa-daemon/src/auto_compaction.rs@@ -20,11 +20,23 @@ pub(crate) enum AutoCompactionRun {/// The check fired and a compaction ran (success, skip, or failure —/// the `compaction_start`/`compaction_end` pair went out either way).Ran,+ /// A summary committed and the retained context replaced the old context.+ Compacted,/// The emit callback cancelled the run (an aborted turn): the caller/// stops the turn loop like any other cancelled emit.Cancelled,}+impl AutoCompactionRun {+ /// Whether in-run threshold checks stay armed after this boundary+ /// outcome: a summary attempt that failed to commit suppresses the+ /// rest of the run's checks; a committed summary and a plain+ /// not-due recheck keep them armed.+ pub(crate) fn continues_threshold_checks(self) -> bool {+ !matches!(self, Self::Ran)+ }+}+impl AgentSessionEngine {/// The TS `_checkCompaction` threshold arm at a turn boundary: check the context against/// the reserve headroom; when crossed, run one compaction with the `threshold` event@@ -206,6 +218,10 @@ impl AgentSessionEngine {}}}- AutoCompactionRun::Ran+ if matches!(outcome, Ok(Ok(CompactOutcome::Ran(_)))) {+ AutoCompactionRun::Compacted+ } else {+ AutoCompactionRun::Ran+ }}}diff --git a/crates/pa-daemon/tests/provider_failover_e2e.rs b/crates/pa-daemon/tests/provider_failover_e2e.rsindex 22ada34dcf..a7373261fe 100644--- a/crates/pa-daemon/tests/provider_failover_e2e.rs+++ b/crates/pa-daemon/tests/provider_failover_e2e.rs@@ -29,13 +29,20 @@ impl Drop for Supervisor {/// A mock OpenAI-completions provider: the first `failures` requests get a/// 500 with an OpenAI-style error body; the rest get one fixed SSE answer.+#[derive(Clone, Copy)]+enum ReplyMode {+ Text(&'static str),+ Threshold,+}+struct FailingMock {requests: Arc<Mutex<usize>>,port: u16,+ reply: ReplyMode,}impl FailingMock {- fn start(failures: usize, answer: &'static str) -> FailingMock {+ fn start(failures: usize, reply: ReplyMode) -> FailingMock {let requests = Arc::new(Mutex::new(0usize));let listener = TcpListener::bind("127.0.0.1:0").expect("bind mock");let port = listener.local_addr().expect("mock addr").port();@@ -45,11 +52,15 @@ impl FailingMock {let Ok(stream) = stream else { continue };let requests = Arc::clone(&requests_for_thread);std::thread::spawn(move || {- let _ = serve(stream, failures, answer, &requests);+ let _ = serve(stream, failures, reply, &requests);});}});- FailingMock { requests, port }+ FailingMock {+ requests,+ port,+ reply,+ }}fn url(&self) -> String {@@ -75,7 +86,7 @@ fn chunk(delta: &Value, finish_reason: Option<&str>) -> String {fn serve(mut stream: TcpStream,failures: usize,- answer: &str,+ reply: ReplyMode,requests: &Arc<Mutex<usize>>,) -> std::io::Result<()> {let mut reader = BufReader::new(stream.try_clone()?);@@ -120,13 +131,39 @@ fn serve(.as_bytes(),);}+ let (delta, reason) = match reply {+ ReplyMode::Text(answer) => (json!({"role":"assistant","content":answer}), "stop"),+ ReplyMode::Threshold => {+ let request: Value = serde_json::from_slice(&body_bytes).expect("request JSON");+ let summary = request["messages"]+ .to_string()+ .contains("context summarization assistant");+ if summary {+ (+ json!({"role":"assistant","content":"compact summary"}),+ "stop",+ )+ } else if index == 1 {+ (+ json!({"role":"assistant","content":"x".repeat(80_000),"tool_calls":[{"index":0,"id":"synthetic-call","type":"function","function":{"name":"synthetic_missing_tool","arguments":"{}"}}]}),+ "tool_calls",+ )+ } else {+ (+ json!({"role":"assistant","content":"finished after compaction"}),+ "stop",+ )+ }+ }+ };let mut payload = String::new();- for data in [- chunk(&json!({"role": "assistant", "content": answer}), None),- chunk(&json!({}), Some("stop")),- ] {+ for data in [chunk(&delta, None), chunk(&json!({}), Some(reason))] {write!(payload, "data: {data}\n\n").expect("write to String");}+ if matches!(reply, ReplyMode::Threshold) {+ let usage = json!({"id":"chatcmpl-test","object":"chat.completion.chunk","created":1_750_000_000,"model":"mock-1","choices":[],"usage":{"prompt_tokens":if index == 1 { 50_000 } else { 100 },"completion_tokens":10,"total_tokens":if index == 1 { 50_010 } else { 110 }}});+ write!(payload, "data: {usage}\n\n").expect("usage SSE");+ }payload.push_str("data: [DONE]\n\n");stream.write_all(format!(@@ -312,7 +349,7 @@ fn setup("id": "mock-1","name": "Mock 1 (backup)","api": "openai-completions",- "contextWindow": 128_000,+ "contextWindow": if matches!(backup.reply, ReplyMode::Threshold) { 64_000 } else { 128_000 },"maxTokens": 4096}]@@ -327,6 +364,7 @@ fn setup(std::fs::write(agent_dir.join("settings.json"),json!({+ "compaction": {"enabled":true,"keepRecentTokens":10},"retry": {"enabled": true,"maxRetries": 1,@@ -385,8 +423,8 @@ fn retry_end(events: &[Value]) -> &Value {#[test]fn provider_failure_fails_over_to_the_next_provider_and_recovers() {- let primary = FailingMock::start(usize::MAX, "never reached");- let backup = FailingMock::start(0, "recovered on the backup provider");+ let primary = FailingMock::start(usize::MAX, ReplyMode::Text("never reached"));+ let backup = FailingMock::start(0, ReplyMode::Text("recovered on the backup provider"));let (_dir, _supervisor, mut client, session_id) = setup("failover", &primary, &backup);client.send_command("p1",@@ -473,8 +511,8 @@ fn provider_failure_fails_over_to_the_next_provider_and_recovers() {#[test]fn every_provider_failing_surfaces_the_final_error() {- let primary = FailingMock::start(usize::MAX, "never reached");- let backup = FailingMock::start(usize::MAX, "never reached");+ let primary = FailingMock::start(usize::MAX, ReplyMode::Text("never reached"));+ let backup = FailingMock::start(usize::MAX, ReplyMode::Text("never reached"));let (_dir, _supervisor, mut client, session_id) = setup("exhausted", &primary, &backup);client.send_command("p1",@@ -534,3 +572,77 @@ fn every_provider_failing_surfaces_the_final_error() {.contains("mock provider overloaded"));assert_eq!(turn_end.get("error"), None, "turn_end: {turn_end}");}++#[test]+fn threshold_yield_keeps_the_backup_until_the_tool_run_finishes() {+ let primary = FailingMock::start(usize::MAX, ReplyMode::Text("never"));+ let backup = FailingMock::start(0, ReplyMode::Threshold);+ let (_dir, _supervisor, mut client, session_id) =+ setup("threshold-failover", &primary, &backup);+ client.send_command("p1", &json!({"type":"prompt_and_wait","activeSessionId":session_id,"message":"u".repeat(120_000)}));+ let done = client.request("p1");+ assert_eq!(done["success"], true, "{done}");+ // Read until the authoritative run settles, with a bound even if unrelated+ // events keep arriving and every individual read succeeds.+ let settle_deadline = Instant::now() + Duration::from_secs(30);+ while !client+ .events+ .iter()+ .any(|event| event["type"] == "auto_retry_end")+ {+ assert!(+ Instant::now() < settle_deadline,+ "retry episode did not settle"+ );+ let line = client.read_line();+ client.collect_event(&line);+ }+ assert_eq!(+ primary.count(),+ 2,+ "threshold yield must not retry the failed primary"+ );+ assert!(+ backup.count() >= 3,+ "tool turn, summary and continuation use the backup"+ );+ let compact = client+ .events+ .iter()+ .position(|event| event["type"] == "compaction_end")+ .expect("backup threshold compacted");+ assert_eq!(client.events[compact]["aborted"], false);+ assert!(+ client.events[compact]["result"].is_object(),+ "{:?}",+ client.events[compact]+ );+ assert!(client.events[compact]["errorMessage"].is_null());+ let final_reply = client+ .events+ .iter()+ .position(|event| {+ event["type"] == "message_end"+ && event["message"]["content"]+ .to_string()+ .contains("finished after compaction")+ })+ .expect("continued after summary");+ let restore = client+ .events+ .iter()+ .position(|event| event["type"] == "auto_retry_end")+ .unwrap();+ assert!(+ compact < final_reply && final_reply < restore,+ "primary restores only after real completion"+ );+ assert_eq!(+ client+ .events+ .iter()+ .filter(|event| event["type"] == "auto_retry_end")+ .count(),+ 1+ );+}