1use std::time::Duration;
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::{Extension, Json};
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::backend::context_reading;
21use crate::server::caller::Caller;
22use crate::server::state::AppState;
23
24const TURN_END_WAIT: Duration = Duration::from_secs(30 * 60);
26const TURN_END_POLL: Duration = Duration::from_millis(250);
27pub(crate) const FOCUS_MAX_CHARS: usize = 2_000;
29
30#[derive(Debug, Deserialize)]
31pub(crate) struct SelfContextRequest {
32 agent: String,
34 #[serde(default)]
36 focus: Option<String>,
37}
38
39fn no_pane() -> Response {
40 let error = "no pane for this agent token: Agents context and compact act only on the calling agent's own pane";
41 (StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))).into_response()
42}
43
44fn provider_of(state: &AppState, block_id: &str) -> Option<(String, bool)> {
46 let block = state.mstore.get::<crate::backend::obj::Block>(block_id).ok()??;
47 let raw = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
48 let provider = crate::backend::providers::resolve_provider_alias(&raw).to_string();
49 let container = crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container();
50 Some((provider, container))
51}
52
53fn hint_kind(block_id: &str) -> context_reading::HintFor {
56 use crate::backend::blockcontroller::acp::AcpController;
57 let ctrl = crate::backend::blockcontroller::get_controller(block_id);
58 match ctrl.as_ref().and_then(|c| c.as_any().downcast_ref::<AcpController>()) {
59 Some(acp) => context_reading::HintFor::acp(acp.offers_compaction()),
60 None => context_reading::HintFor::NATIVE,
61 }
62}
63
64pub(crate) async fn handle_context_self(
66 State(state): State<AppState>,
67 caller: Option<Extension<Caller>>,
68 Json(req): Json<SelfContextRequest>,
69) -> Response {
70 let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
71 return no_pane();
72 };
73 let provider = provider_of(&state, &block_id).map(|(p, _)| p);
74 let reading = context_reading::get(&block_id).unwrap_or_default();
75 let why_none = reading.tokens.is_none().then_some(
76 "no reading yet: srv reads it from the agent's calls (Claude), after each turn (Codex) or from its usage updates (an ACP harness)",
77 );
78 Json(json!({
79 "provider": provider,
80 "model": reading.model,
81 "tokens": reading.tokens,
82 "window": reading.window,
83 "auto_compact_at": reading.auto_compact_at,
84 "compacting": reading.compacting,
85 "calls_since_compaction": reading.calls_since_compaction,
86 "last_compaction_ms": reading.last_compaction_ms,
87 "hint": context_reading::hint_for(&block_id, hint_kind(&block_id)),
88 "note": why_none,
89 }))
90 .into_response()
91}
92
93fn compact_request(provider: &str, container: bool, focus: Option<&str>) -> Result<String, &'static str> {
97 match (provider, container) {
98 ("claude", _) => Ok(compact_message(focus)),
99 ("codex", true) => Err("unsupported: a Codex agent in a container can't compact yet"),
102 ("codex", false) => Ok("/compact".to_string()),
103 _ if speaks_acp(provider) => Err("unsupported: this harness has no compaction AgentMux can start; call Agents fresh with a handoff to start a new session instead"),
104 ("gemini", _) => Err("unsupported: Gemini's /compress does not run in the headless mode AgentMux drives it in (it starts the compression without waiting for it and sends the text to the model); call Agents fresh with a handoff to start a new session instead"),
105 ("muse", _) => Err("unsupported: this harness has no compaction AgentMux can start; call Agents fresh with a handoff to start a new session instead"),
106 _ => Err("unsupported: only Claude and Codex agents can compact"),
107 }
108}
109
110fn acp_compact_message(block_id: &str, focus: Option<&str>) -> Option<Result<String, &'static str>> {
114 use crate::backend::blockcontroller::acp::AcpController;
115 let ctrl = crate::backend::blockcontroller::get_controller(block_id)?;
116 let acp = ctrl.as_any().downcast_ref::<AcpController>()?;
117 Some(acp.compaction_request().map(|takes_input| if takes_input { compact_message(focus) } else { "/compact".to_string() }))
118}
119
120fn speaks_acp(provider: &str) -> bool {
122 crate::backend::providers::get_provider(provider).is_some_and(|p| p.controller_type_str() == "acp")
123}
124
125fn fresh_supported(provider: &str, container: bool) -> Result<(), &'static str> {
129 match (provider, container) {
130 ("claude" | "codex", _) => Ok(()),
131 (_, true) => Err("unsupported in containers: only Claude and Codex agents can start fresh there"),
132 ("gemini" | "muse", false) => Ok(()),
133 _ if speaks_acp(provider) => Ok(()),
134 _ => Err("unsupported: only Claude, Codex, Gemini, Muse and ACP agents can start fresh"),
135 }
136}
137
138pub(crate) async fn handle_compact_self(
141 State(state): State<AppState>,
142 caller: Option<Extension<Caller>>,
143 Json(req): Json<SelfContextRequest>,
144) -> Response {
145 let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
146 return no_pane();
147 };
148 let refused = |why: &str| Json(json!({ "status": "refused", "reason": why })).into_response();
149 let Some((provider, container)) = provider_of(&state, &block_id) else {
150 return refused("the pane can't be read");
151 };
152 let message = match acp_compact_message(&block_id, req.focus.as_deref()).unwrap_or_else(|| compact_request(&provider, container, req.focus.as_deref())) {
153 Ok(message) => message,
154 Err(why) => return refused(why),
155 };
156 if let Err(why) = context_reading::schedule_compact(&block_id, agentmux_common::time::now_ms_u64()) {
157 return refused(&why);
158 }
159 let focus_note = (message == "/compact" && req.focus.as_deref().is_some_and(|f| !f.trim().is_empty()))
160 .then_some("this harness takes no focus: it compacts with its own prompt");
161 tracing::info!(block_id = %block_id, provider = %provider, tokens = context_reading::tokens_now(&block_id), focus_chars = req.focus.as_deref().map_or(0, str::len), "self-compaction scheduled");
162 tokio::spawn(compact_when_turn_ends(state, block_id, message, container));
163 Json(json!({ "status": "scheduled", "runs": "when your current turn ends", "note": focus_note })).into_response()
164}
165
166pub(crate) const HANDOFF_MAX_CHARS: usize = 4_000;
168const EXIT_WAIT: Duration = Duration::from_secs(30);
170
171pub(crate) async fn handle_fresh_self(
175 State(state): State<AppState>,
176 caller: Option<Extension<Caller>>,
177 Json(req): Json<SelfContextRequest>,
178) -> Response {
179 let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
180 return no_pane();
181 };
182 let refused = |why: &str| Json(json!({ "status": "refused", "reason": why })).into_response();
183 let handoff = req.focus.as_deref().unwrap_or_default().trim().to_string();
184 if handoff.is_empty() {
185 return refused("a handoff is required: what your next session must know");
186 }
187 if handoff.chars().count() > HANDOFF_MAX_CHARS {
188 return refused("the handoff is over 4,000 characters: shorten it, with the next step in it");
189 }
190 let Some((provider, container)) = provider_of(&state, &block_id) else {
191 return refused("the pane can't be read");
192 };
193 if let Err(why) = fresh_supported(&provider, container) {
194 return refused(why);
195 }
196 if let Err(why) = context_reading::schedule_compact(&block_id, agentmux_common::time::now_ms_u64()) {
197 return refused(&why);
198 }
199 tracing::info!(block_id = %block_id, provider = %provider, handoff_chars = handoff.len(), "fresh session scheduled");
200 tokio::spawn(fresh_when_turn_ends(state, block_id, handoff_message(&handoff)));
201 Json(json!({ "status": "scheduled", "runs": "when your current turn ends" })).into_response()
202}
203
204pub(crate) fn handoff_message(handoff: &str) -> String {
207 format!(
208 "[AgentMux] This is the fresh session you asked for. Nothing of the previous conversation is in your \
209 context; it is in your record (Agents search_history finds it). Your handoff:\n\n{handoff}"
210 )
211}
212
213pub(crate) fn switch_message(place: &str, handoff: &str) -> String {
217 let said = match handoff.trim() {
218 "" => "Read your task list (Tasks list) and your last status to see what you were doing, then carry on.",
219 h => h,
220 };
221 format!(
222 "[AgentMux] You were moved to {place} and this is a fresh session: nothing of the earlier conversation is in your \
223 context, because a model that did not write a long conversation can read it badly. It is in your record \
224 (Agents search_history finds it).\n\n{said}"
225 )
226}
227
228fn with_previous_session(first_message: String, old: Option<&str>) -> String {
230 match old {
231 Some(id) => format!("{first_message}\n\n(The session before this one had the harness's session id {id}.)"),
232 None => first_message,
233 }
234}
235
236pub(crate) fn fresh_refusal(state: &AppState, block_id: &str) -> Result<(), &'static str> {
238 let (provider, container) = provider_of(state, block_id).ok_or("the pane can't be read")?;
239 fresh_supported(&provider, container)
240}
241
242pub(crate) fn start_fresh_after_switch(state: &AppState, block_id: &str, first_message: String) -> bool {
245 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
246 return false;
247 };
248 runtime.spawn(fresh_when_turn_ends(state.clone(), block_id.to_string(), first_message));
249 true
250}
251
252const FRESH_ATTEMPTS: usize = 5;
255const FRESH_FAILED_NOTE_KEY: &str = "fresh-failed";
257const TURN_RUNNING: &str = "a turn is running";
260const STOP_PENDING: &str = "the agent's process is already stopping or restarting";
261
262fn end_session(block_id: &str) -> Result<Option<String>, &'static str> {
265 use crate::backend::blockcontroller::acp::AcpController;
266 use crate::backend::blockcontroller::msp::MspController;
267 use crate::backend::blockcontroller::persistent::PersistentSubprocessController;
268 use crate::backend::blockcontroller::subprocess::SubprocessController;
269 let ctrl = crate::backend::blockcontroller::get_controller(block_id).ok_or("no controller for the pane")?;
270 if let Some(acp) = ctrl.as_any().downcast_ref::<AcpController>() {
272 return acp.start_fresh_session();
273 }
274 if let Some(muse) = ctrl.as_any().downcast_ref::<MspController>() {
276 return muse.start_fresh_session();
277 }
278 if let Some(codex) = ctrl.as_any().downcast_ref::<SubprocessController>() {
280 return codex.start_fresh_session().map(|_| None);
281 }
282 let p = ctrl.as_any().downcast_ref::<PersistentSubprocessController>().ok_or("the agent's controller can't start fresh")?;
283 context_reading::mark_fresh_by_choice(block_id);
284 p.start_fresh_session().map(|_| None).inspect_err(|_| {
285 context_reading::take_fresh_by_choice(block_id);
286 })
287}
288
289async fn fresh_when_turn_ends(state: AppState, block_id: String, first_message: String) {
292 let mut ended: Result<Option<String>, &str> = Err("the turn didn't end within 30 minutes");
293 for _ in 0..FRESH_ATTEMPTS {
296 if !wait_for_turn_end(&block_id).await {
297 break;
298 }
299 ended = end_session(&block_id);
300 if !matches!(ended, Err(TURN_RUNNING | STOP_PENDING)) {
301 break;
302 }
303 tokio::time::sleep(TURN_END_POLL).await;
304 }
305 if let Err(why) = &ended {
306 tracing::warn!(block_id = %block_id, reason = *why, "fresh session given up");
307 context_reading::fresh_sent(&block_id, false);
308 crate::backend::reactive::held_notes::hold(
309 &block_id,
310 FRESH_FAILED_NOTE_KEY,
311 &format!("[AgentMux] Your fresh session did not start ({why}); this session continues. Call Agents fresh again when you want it."),
312 );
313 return;
314 }
315 let old_session = ended.ok().flatten();
316 if let Some(old) = &old_session {
317 tracing::info!(block_id = %block_id, old_session = %old, "fresh session: the old session ended, the next message opens a new one");
318 }
319 let first_message = with_previous_session(first_message, old_session.as_deref());
320 let deadline = tokio::time::Instant::now() + EXIT_WAIT;
322 while crate::backend::blockcontroller::get_block_controller_status(&block_id)
323 .is_some_and(|s| s.shellprocstatus == crate::backend::blockcontroller::STATUS_RUNNING)
324 && tokio::time::Instant::now() < deadline
325 {
326 tokio::time::sleep(TURN_END_POLL).await;
327 }
328 let deps = crate::server::agent_handlers::AgentTurnDeps::from_state(&state);
329 let outcome = crate::server::agent_handlers::run_agent_turn(
330 &deps,
331 block_id.clone(),
332 first_message,
333 None,
334 crate::server::agent_handlers::TurnRegistration::Register,
335 crate::backend::message_origin::MessageOrigin::system(),
336 Vec::new(),
337 )
338 .await;
339 context_reading::fresh_sent(&block_id, outcome.is_ok());
340 match outcome {
341 Ok(()) => tracing::info!(block_id = %block_id, "fresh session started"),
342 Err(e) => tracing::warn!(block_id = %block_id, error = %e, "fresh session's handoff could not be sent"),
343 }
344}
345
346async fn wait_for_turn_end(block_id: &str) -> bool {
348 let deadline = tokio::time::Instant::now() + TURN_END_WAIT;
349 while crate::backend::blockcontroller::get_block_controller_status(block_id).is_some_and(|s| s.turn_active) {
350 if tokio::time::Instant::now() >= deadline {
351 return false;
352 }
353 tokio::time::sleep(TURN_END_POLL).await;
354 }
355 true
356}
357
358pub(crate) fn compact_message(focus: Option<&str>) -> String {
361 let focus: String = focus.unwrap_or_default().split_whitespace().collect::<Vec<_>>().join(" ").chars().take(FOCUS_MAX_CHARS).collect();
362 if focus.is_empty() { "/compact".to_string() } else { format!("/compact {focus}") }
363}
364
365pub(crate) fn compact_for_backstop(state: &AppState, block_id: &str) -> Result<(), String> {
368 let (provider, container) = provider_of(state, block_id).ok_or("the pane can't be read")?;
369 let message = compact_request(&provider, container, None)?;
370 context_reading::schedule_compact(block_id, agentmux_common::time::now_ms_u64())?;
371 tokio::runtime::Handle::current().spawn(compact_when_turn_ends(state.clone(), block_id.to_string(), message, container));
372 Ok(())
373}
374
375async fn compact_when_turn_ends(state: AppState, block_id: String, message: String, container: bool) {
381 let deps = crate::server::agent_handlers::AgentTurnDeps::from_state(&state);
382 let acp = crate::backend::blockcontroller::get_controller(&block_id).is_some_and(|c| c.as_any().is::<crate::backend::blockcontroller::acp::AcpController>());
383 let mut outcome = Err(TURN_RUNNING.to_string());
384 for _ in 0..FRESH_ATTEMPTS {
387 if !container && !wait_for_turn_end(&block_id).await {
388 tracing::warn!(block_id = %block_id, "self-compaction given up: the turn didn't end within 30 minutes");
389 context_reading::compact_sent(&block_id, false);
390 return;
391 }
392 if acp {
393 context_reading::begin_acp_compaction(&block_id);
394 }
395 outcome = crate::server::agent_handlers::run_agent_turn(
396 &deps,
397 block_id.clone(),
398 message.clone(),
399 None,
400 crate::server::agent_handlers::TurnRegistration::Register,
401 crate::backend::message_origin::MessageOrigin::system(),
402 Vec::new(),
403 )
404 .await;
405 if acp && outcome.is_err() {
406 context_reading::cancel_acp_compaction(&block_id);
407 }
408 if !(acp && outcome.as_ref().err().is_some_and(|e| e.to_string().contains(crate::backend::blockcontroller::acp::TURN_RUNNING))) {
409 break;
410 }
411 }
412 context_reading::compact_sent(&block_id, outcome.is_ok());
413 match outcome {
414 Ok(()) => tracing::info!(block_id = %block_id, tokens = context_reading::tokens_now(&block_id), "self-compaction sent"),
415 Err(e) => tracing::warn!(block_id = %block_id, error = %e, "self-compaction could not be sent"),
416 }
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422
423 #[test]
424 fn the_first_message_names_the_session_it_replaces() {
425 assert_eq!(with_previous_session("hello".to_string(), None), "hello");
426 let m = with_previous_session("hello".to_string(), Some("sess-42"));
427 assert!(m.starts_with("hello") && m.contains("session id sess-42"), "{m}");
428 }
429
430 #[test]
431 fn a_pane_without_an_acp_controller_gets_the_settings_own_hint_rules() {
432 assert_eq!(hint_kind("no-such-block"), context_reading::HintFor::NATIVE);
433 }
434
435 #[test]
436 fn the_handoff_is_the_new_sessions_first_message_from_agentmux() {
437 let m = handoff_message("Task #1791: PR 3 open as #5410; next: wait for review.");
438 assert!(m.starts_with("[AgentMux] This is the fresh session you asked for."));
439 assert!(m.contains("search_history"), "it points at the old session");
440 assert!(m.ends_with("Task #1791: PR 3 open as #5410; next: wait for review."));
441 }
442
443 #[test]
444 fn a_claude_agent_compacts_in_a_container_as_on_the_host() {
445 assert_eq!(compact_request("claude", true, None), Ok("/compact".to_string()));
446 assert_eq!(compact_request("claude", true, Some("keep: PR #1")), compact_request("claude", false, Some("keep: PR #1")));
447 assert_eq!(compact_request("codex", false, None), Ok("/compact".to_string()));
448 assert!(compact_request("codex", true, None).is_err_and(|why| why.contains("container")));
449 assert!(compact_request("copilot", false, None).is_err_and(|why| why.contains("Agents fresh")), "an ACP harness is told what to do instead");
450 assert!(compact_request("dsh", false, None).is_err_and(|why| why.contains("no compaction AgentMux can start")));
451 assert!(compact_request("nonesuch", false, None).is_err_and(|why| why.contains("only Claude and Codex")));
452 assert!(compact_request("gemini", false, None).is_err_and(|why| why.contains("/compress") && why.contains("Agents fresh")), "Gemini is told why and what to do instead");
453 assert!(compact_request("muse", false, None).is_err_and(|why| why.contains("Agents fresh")));
454 }
455
456 #[test]
457 fn gemini_and_muse_start_fresh_on_the_host_and_not_in_a_container() {
458 for provider in ["gemini", "muse"] {
459 assert_eq!(fresh_supported(provider, false), Ok(()), "{provider}");
460 assert!(fresh_supported(provider, true).is_err_and(|why| why.contains("containers")), "{provider}");
461 }
462 }
463
464 #[test]
465 fn fresh_is_offered_to_claude_codex_and_every_acp_harness_and_in_a_container_to_claude_and_codex() {
466 for provider in ["claude", "codex", "dsh", "copilot"] {
467 assert_eq!(fresh_supported(provider, false), Ok(()), "{provider}");
468 }
469 for provider in ["claude", "codex"] {
470 assert_eq!(fresh_supported(provider, true), Ok(()), "a container's {provider} agent starts fresh as a host's does");
471 }
472 for provider in ["dsh", "copilot"] {
473 assert!(fresh_supported(provider, true).is_err_and(|why| why.contains("containers") && why.contains("Claude and Codex")), "{provider}");
474 }
475 assert!(fresh_supported("nonesuch", false).is_err_and(|why| why.contains("ACP")));
476 }
477
478 #[test]
479 fn the_focus_rides_after_compact_on_one_line_within_its_limit() {
480 assert_eq!(compact_message(None), "/compact");
481 assert_eq!(compact_message(Some(" ")), "/compact");
482 assert_eq!(compact_message(Some("keep: PR #5401\n\nthe failing test")), "/compact keep: PR #5401 the failing test");
483 let long = "x".repeat(FOCUS_MAX_CHARS + 50);
484 assert_eq!(compact_message(Some(&long)).chars().count(), "/compact ".len() + FOCUS_MAX_CHARS);
485 }
486}