Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): compact a prompt that outgrows the route's window before dispatching
thinhlpg4d56c8db9459
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rsindex 2bdaa1d64..cca968f61 100644--- a/src-tauri/src/core/agent/compaction.rs+++ b/src-tauri/src/core/agent/compaction.rs@@ -1,11 +1,21 @@-//! Reactive context compaction. The agent loop has no reliable view of a-//! model's context window at request time (local windows live inside the-//! llamacpp plugin/preset; remote windows are unknown), so compaction is-//! triggered by an upstream context-overflow error rather than a proactive-//! token estimate. Given the conversation, we preserve the leading system-//! message(s) and a recent tail, summarize the dropped middle via one model-//! call, and splice the summary back in. If summarization fails the middle is-//! replaced with a short note, so the run always makes forward progress.+//! Context compaction, in two layers.+//!+//! Before a request is dispatched, the loop estimates the prompt and compares+//! it to the route's [`CompactionBudget`]; past the trigger it compacts *then*,+//! so the prefix break happens at a point the run chose instead of at one the+//! provider forced with a rejection. The estimate is a chars-per-token+//! approximation ([`estimate_token_count`]), and a route whose window is+//! unknown - a local engine keeps its window inside the llamacpp+//! plugin/preset - carries no budget, which leaves it on the second layer.+//!+//! The second layer is reactive: a provider that rejects the request as too+//! long is caught by the caller, which compacts and retries. It stays because+//! an estimate is an estimate.+//!+//! Either way, given the conversation we preserve the leading system message(s)+//! and a recent tail, summarize the dropped middle via one model call, and+//! splice the summary back in. If summarization fails the middle is replaced+//! with a short note, so the run always makes forward progress.use serde_json::{json, Value};use tokio::sync::mpsc;@@ -16,6 +26,145 @@ use crate::core::agent::upstream::extract_choice_message;/// Default number of most-recent non-system messages kept verbatim.pub(crate) const DEFAULT_KEEP_RECENT: usize = 8;+/// Per-message envelope (role, delimiters) in [`estimate_token_count`], the+/// usual OpenAI-accounting constant. CLI-only, like the estimator that reads it:+/// nothing in the desktop config estimates a history, since the providers+/// report the real prompt count there.+#[cfg(feature = "cli")]+const TOKENS_PER_MESSAGE: u64 = 4;++/// Share of the context window a prompt may fill before a run compacts ahead of+/// dispatching. `[agent].compaction_ratio` overrides it, per route if the+/// provider entry carries its own.+pub(crate) const DEFAULT_COMPACTION_RATIO: f64 = 0.80;++/// Ratios outside this range are clamped: below it a run would compact on+/// almost every turn, above it the trigger sits at or past the window, where+/// the preflight can never fire in time to be worth having.+const RATIO_RANGE: (f64, f64) = (0.10, 0.99);++/// Prompt tokens at which a preflight compaction fires.+///+/// The ratio is the primary expression because it scales with the window. A+/// fixed reserve does not: 16K is 12% of a 128K window and 1.6% of a 1M one, so+/// the same config compacts far too late on the large window, leaving the+/// prompt to grow into a rejection. An explicit `compaction_reserve_tokens`+/// still wins, so a config that asked for absolute headroom keeps the number it+/// asked for rather than having the ratio silently override it.+///+/// A non-finite ratio falls back to [`DEFAULT_COMPACTION_RATIO`] rather than+/// propagating into the comparison, where a NaN would make every prompt look+/// over the trigger.+pub(crate) fn trigger_tokens(context_window: u64, ratio: f64, reserve_tokens: Option<u64>) -> u64 {+ match reserve_tokens {+ Some(reserve) => context_window.saturating_sub(reserve),+ None => {+ let ratio = if ratio.is_finite() {+ ratio.clamp(RATIO_RANGE.0, RATIO_RANGE.1)+ } else {+ DEFAULT_COMPACTION_RATIO+ };+ (context_window as f64 * ratio).floor() as u64+ }+ }+}++/// Where a run compacts before dispatching: the route's window, the share of it+/// a prompt may fill, and whether the user pinned an absolute reserve instead.+///+/// Optional on a run because the window is not always knowable - local engines+/// keep theirs inside the llamacpp plugin/preset - and an unknown window must+/// leave compaction reactive rather than guess.+#[derive(Debug, Clone, Copy)]+pub(crate) struct CompactionBudget {+ pub(crate) context_window: u64,+ pub(crate) ratio: f64,+ /// An explicit `[agent].compaction_reserve_tokens`, which wins over `ratio`.+ pub(crate) reserve_tokens: Option<u64>,+}++impl CompactionBudget {+ /// Prompt tokens at which this run compacts ahead of dispatching.+ pub(crate) fn trigger_tokens(&self) -> u64 {+ trigger_tokens(self.context_window, self.ratio, self.reserve_tokens)+ }+}++/// Rough token count for a whole request body (~4 chars per token), tool+/// schemas and system prompt included.+///+/// The preflight measures the body it is about to send rather than the message+/// list alone: a handful of MCP servers adds several thousand tokens of schemas+/// that sit *behind* the prompt, and ignoring them would let a run sail past+/// the trigger it thinks it is respecting.+pub(crate) fn estimate_request_tokens(request: &Value) -> u64 {+ (json_text_len(request) as u64 / 4).max(1)+}++/// Total length of every string in `value`, at any depth. Walks the value+/// instead of serializing it: this runs on the first dispatch of every turn,+/// and the request is already the largest allocation in the loop.+fn json_text_len(value: &Value) -> usize {+ match value {+ Value::String(text) => text.len(),+ Value::Array(items) => items.iter().map(json_text_len).sum(),+ Value::Object(fields) => fields.values().map(json_text_len).sum(),+ _ => 0,+ }+}++/// Rough token count (~4 chars per token) for a history the provider has not+/// reported usage for. Counts what actually goes on the wire -- text content+/// including multimodal text parts, tool-call names and arguments, tool-result+/// ids -- so a tool-heavy history is not scored as empty. Image parts are left+/// out: their cost is a provider-specific function of resolution, and inventing+/// a number there is worse than omitting one.+///+/// CLI-only: it backs the feed's fill indicator, the `/context` view and the+/// TUI's auto-compact, all of which must agree with [`trigger_tokens`] - a fill+/// reading under the trigger while the loop compacts would be a bug the user+/// sees as "it compacted for no reason". The desktop reads the provider's own+/// `prompt_tokens` instead, so it has no caller for this.+#[cfg(feature = "cli")]+pub(crate) fn estimate_token_count(messages: &[Value]) -> u64 {+ let mut total_chars: usize = 0;+ for msg in messages {+ match msg.get("content") {+ Some(Value::String(text)) => total_chars += text.len(),+ Some(Value::Array(parts)) => {+ for part in parts {+ total_chars += part+ .get("text")+ .and_then(|t| t.as_str())+ .map_or(0, str::len);+ }+ }+ _ => {}+ }+ for call in msg+ .get("tool_calls")+ .and_then(|c| c.as_array())+ .into_iter()+ .flatten()+ {+ // Arguments live under `function`, not on the call itself.+ if let Some(f) = call.get("function") {+ total_chars += f.get("name").and_then(|n| n.as_str()).map_or(0, str::len);+ total_chars += f+ .get("arguments")+ .and_then(|a| a.as_str())+ .map_or(0, str::len);+ }+ }+ total_chars += msg+ .get("tool_call_id")+ .and_then(|v| v.as_str())+ .map_or(0, str::len);+ }+ let envelope = TOKENS_PER_MESSAGE * messages.len() as u64;+ ((total_chars / 4) as u64 + envelope).max(1)+}+/// Recent tail kept when the user explicitly runs `/compact`. Smaller than the/// automatic threshold so a deliberate compaction is honoured on short threads.#[cfg(feature = "cli")]@@ -612,4 +761,65 @@ mod tests {"kept tail must not start with a tool result");}++ #[test]+ fn the_ratio_scales_the_trigger_with_the_window() {+ assert_eq!(+ trigger_tokens(128_000, DEFAULT_COMPACTION_RATIO, None),+ 102_400+ );+ assert_eq!(+ trigger_tokens(1_000_000, DEFAULT_COMPACTION_RATIO, None),+ 800_000+ );+ }++ #[test]+ fn an_explicit_reserve_wins_over_the_ratio() {+ // 16K is 12% of a 128K window but 1.6% of a 1M one, so a config that+ // pinned absolute headroom keeps the number it asked for on both.+ assert_eq!(trigger_tokens(128_000, 0.5, Some(16_384)), 111_616);+ assert_eq!(trigger_tokens(1_000_000, 0.5, Some(16_384)), 983_616);+ }++ #[test]+ fn an_unusable_ratio_still_yields_a_sane_trigger() {+ // A ratio at or past 1 puts the trigger at the window itself, where the+ // preflight can never fire in time; a NaN would make every prompt look+ // over the trigger and compact on the first turn of every run.+ assert_eq!(trigger_tokens(100_000, 1.5, None), 99_000);+ assert_eq!(trigger_tokens(100_000, 0.0, None), 10_000);+ assert_eq!(trigger_tokens(100_000, f64::NAN, None), 80_000);+ }++ #[test]+ fn a_reserve_larger_than_the_window_does_not_underflow() {+ assert_eq!(+ trigger_tokens(1_000, DEFAULT_COMPACTION_RATIO, Some(5_000)),+ 0+ );+ }++ #[test]+ fn the_request_estimate_counts_the_tool_schemas() {+ let bare = json!({+ "model": "m",+ "messages": [{ "role": "user", "content": "hi" }],+ });+ let with_schemas = json!({+ "model": "m",+ "messages": [{ "role": "user", "content": "hi" }],+ "tools": [{+ "type": "function",+ "function": { "name": "read", "description": "x".repeat(8_000) },+ }],+ });+ // The schemas sit in the request prefix, ahead of the conversation:+ // measuring the message list alone would let a run sail past the+ // trigger it believes it is respecting.+ assert!(+ estimate_request_tokens(&with_schemas) > estimate_request_tokens(&bare) + 1_000,+ "tool schemas must count toward the preflight estimate"+ );+ }}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex ab0d47927..71bea227b 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -114,6 +114,15 @@ pub(crate) struct OrchestrationArgs {/// child) scopes monitors to the run, which then parks on them. Never/// inherited by a child run, which gets its own per-run set.pub monitors: Option<std::sync::Arc<tauri_plugin_agent_tools::tools::monitor::MonitorSet>>,+ /// When this run compacts ahead of dispatching: the route's context window,+ /// the share of it a prompt may fill, and any explicitly configured reserve.+ ///+ /// `None` when the window cannot be sized - local engines keep theirs inside+ /// the llamacpp plugin/preset - which leaves those runs on the reactive+ /// path, compacting only after a provider rejects the request. An unknown+ /// window must not be guessed at, so this is an `Option` rather than a+ /// default budget.+ pub compaction: Option<crate::core::agent::compaction::CompactionBudget>,}#[async_trait]@@ -1505,6 +1514,9 @@ pub(crate) async fn run_server_side_openai_orchestration(session_id: None,sandbox: None,monitors: None,+ // Server-side runs take whatever window the proxy's route reports+ // through its own path, so the loop has none to size against here.+ compaction: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -1941,6 +1953,7 @@ async fn orchestrate_inner(session_id,monitors: session_monitors,sandbox,+ compaction,} = args;// Per-turn override: the TUI toggles plan mode live via the request body@@ -2241,6 +2254,7 @@ async fn orchestrate_inner(todo_registry.as_ref(),force_first_tool,steering,+ *compaction,).await;// On a clean exit, wait for any subagents the model dispatched but never@@ -2276,6 +2290,7 @@ async fn orchestrate_inner(todo_registry.as_ref(),force_first_tool,steering,+ *compaction,).await}@@ -2510,6 +2525,10 @@ async fn run_turn_cycle(// instead of an easily-ignored suggestion. `None` for every later turn.force_first_tool: Option<&str>,steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,+ // Compacts the conversation before dispatching when the request would+ // outgrow this budget. `None` leaves compaction to a provider rejection,+ // the only signal a route with an unknown window can give.+ compaction: Option<crate::core::agent::compaction::CompactionBudget>,) -> Result<serde_json::Value, String> {// `max_turns == 0` is the normal case: the session token budget and user// cancellation are the real guards, so a run isn't cut off mid-task by a@@ -2577,9 +2596,15 @@ async fn run_turn_cycle(publish_monitors(tools, events, &mut shown_monitors);}+ // A prompt already past the route's trigger is compacted *before* the+ // request goes out, so the prefix break lands at a point this run chose+ // instead of one a provider rejection forced - which costs a round trip+ // and a summarizer call, and reads to the user as a stall.+ let mut preflighted = false;// On a context-overflow error, compact the conversation and retry.// Compaction runs progressively (a smaller kept tail each attempt) and- // the loop gives up if a pass fails to shrink the message list.+ // the loop gives up if a pass fails to shrink the message list. Kept as+ // the fallback, and the only path for a route whose window is unknown.let completion = {let mut keep_recent = crate::core::agent::compaction::DEFAULT_KEEP_RECENT;let mut attempts = 0usize;@@ -2591,6 +2616,56 @@ async fn run_turn_cycle(json_body,(turn == 0).then_some(force_first_tool).flatten(),);+ // Once per turn, on the request about to be sent. A prompt still+ // over the trigger after compacting is sent anyway:+ // `compact_conversation` returns its input unchanged when there+ // is nothing safe to drop, and retrying here would spin.+ if !preflighted {+ preflighted = true;+ if let Some(budget) = compaction {+ let estimate =+ crate::core::agent::compaction::estimate_request_tokens(&request_value);+ if estimate > budget.trigger_tokens() {+ let compacted = crate::core::agent::compaction::compact_conversation(+ &conversation_messages,+ model_id,+ model,+ crate::core::agent::compaction::DEFAULT_KEEP_RECENT,+ )+ .await?;+ if compacted.len() < conversation_messages.len() {+ let dropped = conversation_messages.len() - compacted.len();+ log::info!(+ "agent: prompt estimated at {estimate} tokens against a {} \+ token trigger on a {} token window, compacted {} -> {} \+ messages before dispatch",+ budget.trigger_tokens(),+ budget.context_window,+ conversation_messages.len(),+ compacted.len()+ );+ conversation_messages = compacted;+ // Published for the same reason the overflow+ // path below publishes: a client holding the+ // oversized history would send it again next turn.+ let _ = events.send(StreamEvent::MessagesUpdated {+ messages: conversation_messages.clone(),+ });+ // The one legitimate cache break in a session,+ // and the only way the user can tell it apart+ // from a stall: say it happened, and why.+ let _ = events.send(StreamEvent::Notice {+ text: format!(+ "compacted {dropped} messages into a summary before sending \+ ({estimate} tokens against a {} token budget)",+ budget.trigger_tokens()+ ),+ });+ continue;+ }+ }+ }+ }match model.invoke(&request_value, events).await {Ok(c) => break c,Err(e)@@ -3329,6 +3404,7 @@ mod tests {None,None,Some(&steering),+ None,).await.unwrap();@@ -3381,6 +3457,7 @@ mod tests {None,None,Some(&steering),+ None,).await.unwrap();@@ -3439,6 +3516,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -3466,6 +3544,175 @@ mod tests {assert!(saw_tool_call && saw_tool_result);}+ /// The preflight exists so an oversized prompt is compacted *before* it is+ /// sent: the provider never sees the request it would reject, and the user+ /// gets one notice instead of a stall followed by a silent retry.+ #[tokio::test]+ async fn a_prompt_over_the_trigger_is_compacted_before_the_request_goes_out() {+ /// Rejects an oversized request the way a real provider does (HTTP 400+ /// `context_length_exceeded`), counted so the test can assert it was+ /// never given the chance. `limit` is measured with the same estimator+ /// the preflight uses, on the same request body.+ struct OverflowRejectingModel {+ limit: u64,+ requests: StdMutex<Vec<serde_json::Value>>,+ rejections: StdMutex<usize>,+ }+ #[async_trait]+ impl ModelInvoker for OverflowRejectingModel {+ async fn invoke(+ &self,+ request: &serde_json::Value,+ _events: &mpsc::UnboundedSender<StreamEvent>,+ ) -> Result<serde_json::Value, String> {+ // The summarizer call is tiny by construction; answer it.+ let summarizing = request["messages"][0]["content"]+ .as_str()+ .is_some_and(|c| c.starts_with("Summarize the AI agent"));+ if !summarizing {+ self.requests.lock().unwrap().push(request.clone());+ let estimate = crate::core::agent::compaction::estimate_request_tokens(request);+ if estimate > self.limit {+ *self.rejections.lock().unwrap() += 1;+ return Err(+ "Upstream returned HTTP 400: context_length_exceeded".to_string()+ );+ }+ }+ let content = if summarizing {+ "CONDENSED"+ } else {+ "final answer"+ };+ Ok(json!({+ "choices": [{ "message": { "content": content }, "finish_reason": "stop" }]+ }))+ }+ }++ let (tx, mut rx) = mpsc::unbounded_channel();+ // The provider's own ceiling sits between the compacted and the+ // uncompacted prompt: reachable only after the preflight runs.+ let model = OverflowRejectingModel {+ limit: 800,+ requests: StdMutex::new(Vec::new()),+ rejections: StdMutex::new(0),+ };+ let tool = MockTool::default();+ let mut budget = SessionBudget::new(None);+ let mut convo = vec![json!({ "role": "system", "content": "sys" })];+ for i in 0..20 {+ convo.push(json!({+ "role": "user",+ "content": format!("message {i} {}", "x".repeat(200)),+ }));+ }++ let result = run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ convo,+ 8,+ &mut budget,+ &model,+ &tool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ None,+ Some(crate::core::agent::compaction::CompactionBudget {+ context_window: 1_000,+ ratio: 0.5,+ reserve_tokens: None,+ }),+ )+ .await+ .unwrap();++ assert_eq!(result["choices"][0]["message"]["content"], "final answer");+ assert_eq!(+ *model.rejections.lock().unwrap(),+ 0,+ "the compacted request must fit, so the provider never rejects"+ );+ // Scoped: the guard is not held across the awaits below, and `sent`+ // borrows through it.+ {+ let requests = model.requests.lock().unwrap();+ assert_eq!(+ requests.len(),+ 1,+ "one dispatch, after the preflight -- never a rejected send"+ );+ let sent = requests[0]["messages"].as_array().unwrap();+ assert!(+ sent.len() < 20,+ "the oversized history must be gone before dispatch, sent {} messages",+ sent.len()+ );+ assert!(+ sent.iter()+ .any(|m| m["content"].as_str().unwrap_or("").contains("CONDENSED")),+ "the summary must replace the dropped middle: {sent:?}"+ );+ }++ drop(tx);+ let mut notices = Vec::new();+ while let Some(ev) = rx.recv().await {+ if let StreamEvent::Notice { text } = ev {+ notices.push(text);+ }+ }+ assert!(+ notices.iter().any(|n| n.contains("before sending")),+ "a prefix break the user did not ask for has to be announced: {notices:?}"+ );+ }++ /// The other half of the contract: under the trigger nothing is compacted+ /// and no summarizer call is spent.+ #[tokio::test]+ async fn a_prompt_under_the_trigger_is_sent_untouched() {+ let (tx, _rx) = mpsc::unbounded_channel();+ let model = MockModel::new(vec![+ json!({ "choices": [{ "message": { "content": "final answer" }, "finish_reason": "stop" }] }),+ ]);+ let tool = MockTool::default();+ let mut budget = SessionBudget::new(None);++ run_turn_cycle(+ &tx,+ &json!({}),+ "m",+ &[],+ vec![json!({ "role": "user", "content": "hi" })],+ 8,+ &mut budget,+ &model,+ &tool,+ crate::core::agent::plan::RunMode::Normal,+ None,+ None,+ None,+ Some(crate::core::agent::compaction::CompactionBudget {+ context_window: 128_000,+ ratio: crate::core::agent::compaction::DEFAULT_COMPACTION_RATIO,+ reserve_tokens: None,+ }),+ )+ .await+ .unwrap();++ assert_eq!(+ model.requests.lock().unwrap().len(),+ 1,+ "no summarizer call under the trigger"+ );+ }+/// Reads the tool message the loop wrote into the next request's/// conversation. The image case must land there as an OpenAI content-part/// array (text note + `image_url`) rather than a plain string, or the@@ -3523,6 +3770,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -3582,6 +3830,7 @@ mod tests {Some(®istry),None,None,+ None,).await.expect("the run continues from clean history");@@ -3702,6 +3951,7 @@ mod tests {None,None,None,+ None,).await.expect("sanitized history must be accepted so the session can continue");@@ -3738,6 +3988,7 @@ mod tests {None,Some("todo"),None,+ None,).await.unwrap();@@ -3933,6 +4184,7 @@ mod tests {Some(®istry),None,None,+ None,).await.unwrap();@@ -4010,6 +4262,7 @@ mod tests {Some(®istry),None,None,+ None,).await.unwrap();@@ -4055,6 +4308,7 @@ mod tests {Some(®istry),None,None,+ None,).await.unwrap();@@ -4091,6 +4345,7 @@ mod tests {Some(®istry),None,None,+ None,).await.unwrap();@@ -4143,6 +4398,7 @@ mod tests {Some(®istry),None,None,+ None,).await.unwrap();@@ -4231,6 +4487,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4284,6 +4541,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4382,6 +4640,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4430,6 +4689,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4523,6 +4783,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4579,6 +4840,7 @@ mod tests {None,None,None,+ None,).await.expect("passing the ceiling is not an error");@@ -4683,6 +4945,7 @@ mod tests {None,None,None,+ None,).await.expect("run completes");@@ -4750,6 +5013,7 @@ mod tests {None,None,None,+ None,).await.expect("run completes");@@ -4829,6 +5093,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4877,6 +5142,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -4930,6 +5196,7 @@ mod tests {None,None,None,+ None,).await;@@ -4994,6 +5261,7 @@ mod tests {None,None,None,+ None,).await;@@ -5051,6 +5319,7 @@ mod tests {None,None,None,+ None,).await;@@ -5102,6 +5371,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -5140,6 +5410,7 @@ mod tests {None,None,None,+ None,).await.unwrap();@@ -5927,6 +6198,7 @@ mod tests {None,None,None,+ None,).await}diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 543737f8c..2363281b0 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -2600,6 +2600,7 @@ mod tests {run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,+ compaction: None,}}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 745c2df1d..78ecb5b05 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -997,6 +997,11 @@ fn build_cli_orchestration_args(// `--sandbox` only when passed; unset falls through to the project's// `[tools].sandbox` and then the user's global `sandbox`.sandbox,+ // Filled in by `prepare_agent_session`, which is where the route's+ // context window is resolved. The desktop paths leave it `None`: their+ // window lives in the local engine's preset, not in a catalog this+ // builder can read.+ compaction: None,}}