Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): compact a subagent on its live context, not cumulative spend (#9489)

Akarshan Biswasab79bc8cd037
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 4c1bb5777..f7ce4ed19 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -81,7 +81,8 @@ bounded by `--max-turns` or by cancelling it.
<Callout type="warning">
`--max-session-tokens` and `[budget].max_tokens` do **not** stop a run. Crossing the ceiling is
-advisory: the run compacts its history, records a note, and carries on, tool calls included. Use
+advisory: the run records a note and carries on, tool calls included. It does not compact the
+history; only the context window does that. Use
`--max-budget-usd` to bound what an unattended run may spend, or `--max-turns` to bound how many
turns it may take.
</Callout>
@@ -108,7 +109,7 @@ jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build fai
| `--worktree` | Work in a dedicated git worktree instead of the project directory. Off by default |
| `--no-worktree` | Work in the project directory, overriding a persistent `worktree` setting |
| `--max-turns <N>` | Hard cap on agentic turns. If the model is still calling tools at N the run fails with `reached the N-turn limit...` and exits `53`; with `--output-format json` the partial answer is still in `result`. Bounds the parent run only - subagent turns are not counted. `0` means unbounded, which is the default |
-| `--max-session-tokens <N>` | Advisory token ceiling for this run, overriding `[budget].max_tokens`. Triggers compaction and a recorded note when passed; it does not terminate the run. `0` means no ceiling |
+| `--max-session-tokens <N>` | Advisory token ceiling for this run, overriding `[budget].max_tokens`. Records a note when passed (it does not compact); it does not terminate the run. `0` means no ceiling |
| `--max-budget-usd <USD>` | Stop the run once it has spent this much, overriding `[budget].max_usd`. Priced from the provider's published rates, so a model with no published price is **refused** rather than run uncapped - including a subagent whose definition names its own model. Subagents inherit the ceiling. Compaction is billed against it like any other request. Stopping this way exits `0` with `stop_reason: budget_exceeded`; `0` as a limit stops at the first billed request |
| `--provider`, `--api-key`, `--base-url` | Provider overrides for this run. `--base-url` requires `--provider`; see [Using a gateway](/docs/agent/providers#using-a-gateway) |
| `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line |
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdx
index b48dcff5a..a460e2f44 100644
--- a/docs/src/pages/docs/agent/context.mdx
+++ b/docs/src/pages/docs/agent/context.mdx
@@ -189,13 +189,14 @@ auto-compacted 84 -> 31 messages (ctx 96K/128K)
compacted 84 messages into a summary: the prompt neared the context window
```
-A run also compacts when it uses up its [session token budget](#budgets), and after a provider
-rejects a prompt as too long (see [Context overflow](#context-overflow)). Both report the same
-way, and so does a subagent's compaction, prefixed with its name.
+A run also compacts after a provider rejects a prompt as too long (see
+[Context overflow](#context-overflow)). That reports the same way, and so does a subagent's
+compaction, prefixed with its name. Using up the [session token budget](#budgets) does not compact:
+spend is not context size.
Headless and RPC clients get a `compaction` event: `phase` is `started`, then `finished` (with
-`messages`, the number summarized) or `failed`, and `reason` is `preflight`, `context_overflow` or
-`session_budget`.
+`messages`, the number summarized) or `failed`, and `reason` is `preflight` or `context_overflow`
+(`session_budget` is still in the schema but no longer sent).
## Compacting on purpose
@@ -214,8 +215,8 @@ preserves the thread of the conversation, including the parts that sent it off c
## Context overflow
If a request overflows anyway, the loop compacts and retries rather than erroring out. That path is
-still needed: a route served by a local engine carries no window the loop can read, and an estimate
-is an estimate. Each retry keeps a smaller tail of recent messages. If a pass fails to shrink the
+still needed: a route served by a local engine carries no window the loop can read, so this is the
+only compaction it gets, and an estimate is an estimate. Each retry keeps a smaller tail of recent messages. If a pass fails to shrink the
conversation at all, it gives up rather than looping.
## Capping output
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index a699d591a..c85176f46 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -200,8 +200,9 @@ A marker for how far one run has gone, distinct from the per-request context win
run's marginal token spend (replayed context is not recharged each turn).
<Callout type="warning">
-Passing this ceiling does not stop a run. The agent compacts its history, records a note that the
-ceiling was crossed, and carries on, tool calls included. For a hard bound on an unattended run use
+Passing this ceiling does not stop a run. The agent records a note that the ceiling was crossed and
+carries on, tool calls included. It does not compact the history: spend is not context size, and
+only the context window triggers [compaction](/docs/agent/context). For a hard bound on an unattended run use
`--max-turns` (see the [CLI reference](/docs/agent/cli)), or cancel it.
</Callout>
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index a34fa972e..b0e1cd87f 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -276,8 +276,8 @@ pub(crate) fn tail_start(rest: &[Value], target: usize) -> Option<usize> {
/// Compaction is the one lifecycle point that discards conversation, so a team
/// that wants a transcript archived or a summary pinned has to be told before
/// it happens rather than after. It lives here, beside the compaction itself,
-/// so every path that compacts fires it: the reactive overflow retry, the
-/// end-of-run budget pass, and the TUI's `/compact`.
+/// so every path that compacts fires it: the preflight, the reactive overflow
+/// retry, and the TUI's `/compact`.
///
/// A deny is not honored -- refusing to compact would leave the run wedged on
/// an oversized history it cannot send -- so only `context` and the failure
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index a0623c681..e5053547b 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -5041,48 +5041,17 @@ async fn run_turn_cycle(
continue;
}
}
- // Every turn is finished and the run passed its token ceiling, so
- // the conversation is both complete and oversized. Compact it here,
- // while nothing is waiting on the result: the ceiling no longer
- // stops a run, so without this the thread only grows, and the next
- // run resumes it by sending the whole oversized history upstream.
- // The reactive path above cannot help with that -- it only fires
- // once an upstream has already rejected a request.
- //
- // Only when there is something to drop: a plan that
- // covers nothing would spend a summarizer call to publish an
- // unchanged history.
- if budget.exhausted() {
- tools
- .pre_compact(projected_message_count(
- &transcript,
- volatile_system.as_deref(),
- send_reasoning,
- ))
- .await;
- match compact(
- &mut transcript,
- crate::core::agent::compaction::DEFAULT_KEEP_RECENT,
- model_id,
- model,
- budget,
- events,
- CompactionReason::SessionBudget,
- )
- .await
- {
- Ok(Some(dropped)) => {
- log::info!(
- "agent: budget exhausted at end of run, compacted {dropped} messages \
- into a summary"
- );
- }
- Ok(None) => {}
- Err(error) => {
- log::warn!("agent: budget exhausted but compaction failed: {error}");
- }
- }
- }
+ // A spent token ceiling does not compact here. Spend is not context
+ // size: every completion is charged in full, but thinking is not
+ // resent, so a long run on a reasoning model passes a window-sized
+ // ceiling while its prompt is a fraction of the window. Compacting
+ // then throws away live context and saves no spend. With a known
+ // window, a history that really is oversized is compacted by the
+ // preflight above, on the next request that would carry it. With
+ // none (`compaction` is `None`, only the desktop API-server proxy)
+ // nothing shrinks it proactively: the overflow path compacts once a
+ // provider rejects a request. A pass here would not help that route
+ // anyway, since its HTTP client owns the history and resends it.
let _ = events.send(StreamEvent::MessagesUpdated {
messages: client_history(&transcript, send_reasoning),
});
@@ -8080,48 +8049,57 @@ mod tests {
);
}
- /// Passing the ceiling no longer stops a run, so a long thread only grows.
- /// Once every turn is finished, the oversized conversation is compacted
- /// before it is published -- otherwise the next run resumes this thread by
- /// sending the whole thing upstream.
+ /// A long, well-cached run whose live prompt never nears the window must not
+ /// be compacted, however far its cumulative spend has gone. Spend outruns
+ /// the live context by design: every completion is charged in full, but a
+ /// reasoning model's thinking is not resent, so the next prompt grows by
+ /// far less than was charged. A subagent making ~180 tool calls crossed a
+ /// window-sized budget this way at a fraction of its window.
#[tokio::test]
- async fn an_exhausted_budget_compacts_the_conversation_once_turns_are_done() {
+ async fn a_long_cached_run_under_the_window_is_not_compacted_for_its_spend() {
let (tx, mut rx) = mpsc::unbounded_channel();
-
- // Comfortably longer than DEFAULT_KEEP_RECENT so there is a middle to drop.
- let convo: Vec<serde_json::Value> = (0..24)
- .map(|i| {
- json!({
- "role": if i % 2 == 0 { "user" } else { "assistant" },
- "content": format!("message {i}"),
- })
+ const WINDOW: u64 = 128_000;
+ const STEPS: u64 = 100;
+ let usage = |step: u64| {
+ // A 20K prompt growing by a 200-token tool result per step: 40K at
+ // the end, well under the 102.4K trigger. 98% of it is a cache hit,
+ // and each 1.5K completion is mostly thinking that is not resent.
+ let prompt = 20_000 + 200 * step;
+ json!({
+ "prompt_tokens": prompt,
+ "completion_tokens": 1_500,
+ "total_tokens": prompt + 1_500,
+ "prompt_tokens_details": { "cached_tokens": prompt * 98 / 100 },
+ })
+ };
+ let mut responses: Vec<serde_json::Value> = (0..STEPS)
+ .map(|step| {
+ let mut c = tool_call_completion();
+ c["usage"] = usage(step);
+ c
})
.collect();
- let original_len = convo.len();
-
- let mut over_budget = json!({
+ let mut done = json!({
"choices": [{ "message": { "content": "all done" }, "finish_reason": "stop" }]
});
- // The replayed prompt is the baseline; the 100-token reply is the spend.
- over_budget["usage"] =
- json!({ "prompt_tokens": 900, "completion_tokens": 100, "total_tokens": 1_000 });
- let summary = json!({
- "choices": [{ "message": { "content": "SUMMARY OF THE EARLIER WORK" } }]
- });
- // Second response is consumed by the summarizer inside compaction.
- let model = MockModel::new(vec![over_budget, summary]);
+ done["usage"] = usage(STEPS);
+ responses.push(done);
+ // Anything past the run's own turns is a summarizer call.
+ responses.push(json!({ "choices": [{ "message": { "content": "SUMMARY" } }] }));
+ let model = MockModel::new(responses);
let tool = MockTool::default();
- let mut budget = SessionBudget::new(Some(50));
+ // The child's default budget: its model's window.
+ let mut budget = SessionBudget::new(Some(WINDOW));
run_turn_cycle(
&tx,
&json!({}),
"m",
&[],
- Transcript::from_history(convo),
+ Transcript::from_history(vec![json!({ "role": "user", "content": "task" })]),
None,
true,
- 8,
+ 0,
&mut budget,
&model,
&tool,
@@ -8129,59 +8107,31 @@ mod tests {
None,
None,
None,
- None,
+ Some(crate::core::agent::compaction::CompactionBudget {
+ context_window: WINDOW,
+ ratio: crate::core::agent::compaction::DEFAULT_COMPACTION_RATIO,
+ reserve_tokens: None,
+ window_pinned: false,
+ }),
)
.await
.expect("run completes");
- assert!(budget.exhausted(), "precondition: the ceiling was passed");
- assert_eq!(
- model.requests.lock().unwrap().len(),
- 2,
- "one turn, plus the summarizer call compaction makes"
- );
-
- let events: Vec<StreamEvent> = std::iter::from_fn(|| rx.try_recv().ok()).collect();
- // The user is told: the TUI runs with logging off, so without an event
- // this compaction is invisible.
- let phases: Vec<CompactionPhase> = events
- .iter()
- .filter_map(|ev| match ev {
- StreamEvent::Compaction {
- phase,
- reason: CompactionReason::SessionBudget,
- ..
- } => Some(*phase),
- _ => None,
- })
+ // 101 completions of 1.5K, the 200-token growth absorbed by the
+ // previous completion each time: the cached share charges nothing.
+ assert_eq!(budget.spent(), (STEPS + 1) * 1_500);
+ assert!(budget.exhausted(), "precondition: spend passed the window");
+ let compactions: Vec<StreamEvent> = std::iter::from_fn(|| rx.try_recv().ok())
+ .filter(|ev| matches!(ev, StreamEvent::Compaction { .. }))
.collect();
- assert_eq!(
- phases,
- [CompactionPhase::Started, CompactionPhase::Finished],
- "the budget compaction is announced, start and end"
- );
- // The published history is the compacted one: shorter, and carrying the
- // summary in place of the dropped middle.
- let published = events
- .into_iter()
- .rev()
- .find_map(|ev| match ev {
- StreamEvent::MessagesUpdated { messages } => Some(messages),
- _ => None,
- })
- .expect("a MessagesUpdated is published");
assert!(
- published.len() < original_len,
- "history was compacted: {} -> {}",
- original_len,
- published.len()
+ compactions.is_empty(),
+ "a 40K prompt on a 128K window is not compacted: {compactions:?}"
);
- assert!(
- published.iter().any(|m| m["content"]
- .as_str()
- .unwrap_or_default()
- .contains("SUMMARY OF THE EARLIER WORK")),
- "the summary replaced the dropped middle: {published:#?}"
+ assert_eq!(
+ model.requests.lock().unwrap().len() as u64,
+ STEPS + 1,
+ "no summarizer call"
);
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 21fb1e858..a48086020 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -791,9 +791,9 @@ use tokio::sync::{mpsc, Mutex};
/// `agent.toml [budget].max_tokens` is set and the model's context window is
/// unknown. `0` disables the ceiling entirely.
///
-/// Advisory, not a bound: crossing it compacts the history and records a note,
-/// then the run carries on (see `body_session_budget`). `--max-turns` and
-/// cancellation are what actually stop a runaway loop.
+/// Advisory, not a bound: crossing it records a note and the run carries on
+/// (see `body_session_budget`). It never compacts: spend is not context size.
+/// `--max-turns` and cancellation are what actually stop a runaway loop.
const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;
/// How long `run` and `step` wait for the session-scoped provider's startup
@@ -854,9 +854,8 @@ impl SessionBudgetSource {
/// either explicit source means unbounded and is carried through as-is (see
/// `body_session_budget`).
///
-/// The window is the default because the ceiling compacts when crossed: a
-/// fixed 128K would compact a 1M-window model at an eighth of its capacity,
-/// long before the window-based trigger would.
+/// The window is the default so the advisory note scales with the model: a
+/// fixed 128K would flag a 1M-window run at an eighth of its capacity.
pub(crate) fn resolve_session_budget(
flag: Option<u64>,
configured: Option<u64>,