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.

feat(agent): drop turn caps, make the session token budget the only bound (#8617)

Akarshan Biswase4ac1f5e70f2
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 40455e2a2..2f3294518 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -34,7 +34,6 @@ jan <COMMAND>
| `--project <PATH>` | Project root containing `.jan/agent/agent.toml`. Defaults to `.` |
| `--task <TEXT>` | Seed the session with a first message |
| `--model <ID>` | Model id, overriding `[agent].model` |
-| `--max-turns <N>` | Turns per message, clamped to 1-400 |
| `--image <PATH>` | Attach an image to the first message. Repeatable |
| `--plan` | Start in read-only plan mode |
| `--safe` | Ask for approval before writes, shell commands, and MCP tool calls |
@@ -66,12 +65,13 @@ Run the agent without a UI. This is the form to use in scripts.
### `run`
-Run to completion, or until the turn/token budget is spent.
+Run to completion, or until the session token budget is spent. There is no turn cap - the agent
+runs as many turns as the task needs, bounded only by `[budget].max_tokens`, or by cancelling it.
```bash
jan cli agent run "fix the failing test in tests/auth"
jan cli agent run --project ~/code/app "update the changelog"
-jan cli agent run --model gpt-4o --max-turns 20 "add unit tests for the parser"
+jan cli agent run --model gpt-4o "add unit tests for the parser"
jan cli agent run --safe "run the migration" # approve each step
```
@@ -79,7 +79,6 @@ jan cli agent run --safe "run the migration" # approve each step
| --- | --- |
| `--project <PATH>` | Project root. Defaults to `.` |
| `--model <ID>` | Model id, overriding `[agent].model` |
-| `--max-turns <N>` | Turns, overriding `[agent].max_turns`. Clamped to 1-400 |
| `--safe` | Ask for approval before writes, shell commands, and MCP tool calls |
| `--resume[=ID]` | Resume the most recent session, or one by id |
| `-c`, `--continue` | Resume the most recent session |
@@ -203,7 +202,6 @@ export ANTHROPIC_API_KEY="$SECRET_KEY"
jan cli agent run \
--project . \
--provider anthropic \
- --max-turns 30 \
"update the changelog for the current release"
```
diff --git a/docs/src/pages/docs/agent/context.mdx b/docs/src/pages/docs/agent/context.mdx
index be2a11aa8..bdd5fd9ba 100644
--- a/docs/src/pages/docs/agent/context.mdx
+++ b/docs/src/pages/docs/agent/context.mdx
@@ -85,9 +85,9 @@ Separately from the context window, a project can bound how far one run goes:
```toml
[budget]
-max_steps = 40
-max_tokens = 200000
+# max_tokens = 128000 # token-spend ceiling per run; 0 disables the cap
```
-That's a stop point for the run as a whole, not a per-request limit. See
+That's a stop point for the run as a whole, not a per-request limit. There is no turn cap - the
+agent runs as many turns as the task needs, bounded only by this budget (or by cancelling it). See
[Project config](/docs/agent/project-config).
diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdx
index cd174101b..4e09f6860 100644
--- a/docs/src/pages/docs/agent/project-config.mdx
+++ b/docs/src/pages/docs/agent/project-config.mdx
@@ -58,7 +58,6 @@ Point at a different file with `instructions_file` if you already keep conventio
```toml
[agent]
# model = "Jan-V4"
-max_turns = 400
# context_window = 128000
# compaction_reserve_tokens = 16384
# max_tokens = 4096
@@ -71,9 +70,11 @@ instructions_file = "AGENT.md"
# base_url = "https://api.openai.com/v1"
# models = ["gpt-4o"]
+# The run's only cap: new token spend across all turns (replayed context is not
+# recharged each turn). There is no turn limit. Defaults to 128000 when unset;
+# 0 disables the cap.
[budget]
-max_steps = 40
-max_tokens = 200000
+# max_tokens = 128000
[tools]
default = "read-only"
@@ -91,7 +92,6 @@ inject = "always"
| Key | Default | Description |
| --- | --- | --- |
| `model` | inherited | Model id. Overridden by `--model` |
-| `max_turns` | `400` | Turns per message, clamped to 1-400 |
| `context_window` | `128000` | Context limit in tokens |
| `compaction_reserve_tokens` | `16384` | Headroom kept free before [compaction](/docs/agent/context) |
| `max_tokens` | unset | Cap on tokens generated per response. Omitted from the request when unset |
@@ -105,12 +105,12 @@ Desktop. Most projects don't need it. See [Providers](/docs/agent/providers#per-
### `[budget]`
-| Key | Description |
-| --- | --- |
-| `max_steps` | Stop the run after this many steps |
-| `max_tokens` | Stop the run after this many tokens |
+| Key | Default | Description |
+| --- | --- | --- |
+| `max_tokens` | `128000` | Token-spend ceiling for one run (new spend across all turns). The only cap on run length - there is no turn limit. Set `0` to disable the cap. Defaults to `128000` when unset |
-A bound on how far one run goes, distinct from the per-request context window.
+A bound on how far one run goes, distinct from the per-request context window. It bounds the run's
+marginal token spend (replayed context is not recharged each turn).
### `[tools]`
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 7cf1860fa..d17fb47a3 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -43,7 +43,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| `/mcp` | Enable or disable MCP servers |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
-| `/settings [max_parallel_subagents N]` | Edit `agent.toml` settings in an interactive menu - `[agent]` knobs (`max_turns`, `context_window`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`), `[budget]` limits, and the `[tools]` / `[skills]` toggles (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run |
+| `/settings [max_parallel_subagents N]` | Edit `agent.toml` settings in an interactive menu - `[agent]` knobs (`context_window`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`), `[budget]` limits, and the `[tools]` / `[skills]` toggles (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run |
See [Providers](/docs/agent/providers) and [MCP](/docs/agent/mcp).
diff --git a/docs/src/pages/docs/agent/spec-max-parallel-subagents.md b/docs/src/pages/docs/agent/spec-max-parallel-subagents.md
index 1cdf5c7fb..af6d69d80 100644
--- a/docs/src/pages/docs/agent/spec-max-parallel-subagents.md
+++ b/docs/src/pages/docs/agent/spec-max-parallel-subagents.md
@@ -82,10 +82,10 @@ tool-call window. Add a distinct `queued` state:
Today `/config` is read-only and shows only `~/.jan/config.toml` providers.
Extend it (or add `/settings`) to edit `[agent]` keys, starting with
-`max_parallel_subagents`, ideally the full set (`max_turns`,
-`context_window`, `compaction_reserve_tokens`, `max_tokens`,
-`instructions_file`). Writes go through the same `agent.toml` writer the CLI
-uses; input validated (integer, >= 1).
+`max_parallel_subagents`, ideally the full set (`context_window`,
+`compaction_reserve_tokens`, `max_tokens`, `instructions_file`). Writes go
+through the same `agent.toml` writer the CLI uses; input validated (integer,
+>= 1).
## Out of scope
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index 8ef952d76..77d5dde13 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -51,9 +51,6 @@ struct Cli {
/// Model ID overriding [agent].model in agent.toml (bare TUI only)
#[arg(long)]
model: Option<String>,
- /// Max turns per message, clamped 1..=400 (bare TUI only)
- #[arg(long)]
- max_turns: Option<u32>,
/// Image file to attach to the first message, repeatable (bare TUI only)
#[arg(long = "image")]
images: Vec<String>,
@@ -194,7 +191,7 @@ impl ProviderArgs {
#[derive(Subcommand)]
enum AgentCommands {
- /// Run the agent loop to completion or the turn/token budget
+ /// Run the agent loop to completion or the session token budget
Run {
/// Project root containing .jan/agent/agent.toml
#[arg(long, default_value = ".")]
@@ -204,9 +201,6 @@ enum AgentCommands {
/// Model ID (overrides [agent].model in agent.toml)
#[arg(long)]
model: Option<String>,
- /// Max turns (overrides [agent].max_turns; clamped 1..=400)
- #[arg(long)]
- max_turns: Option<u32>,
/// Prompt for approval before writes, shell commands, and MCP tool calls
#[arg(long)]
safe: bool,
@@ -385,7 +379,6 @@ async fn main() {
&cli.project,
cli.task,
cli.model,
- cli.max_turns,
cli.images,
overrides,
!cli.safe,
@@ -474,7 +467,6 @@ async fn handle_agent(cmd: AgentCommands) {
project,
task,
model,
- max_turns,
safe,
providers,
resume,
@@ -483,7 +475,6 @@ async fn handle_agent(cmd: AgentCommands) {
&project,
&task,
model,
- max_turns,
providers.into_overrides(),
!safe,
resume.into_target(),
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 4e44ac6c8..1857a5b52 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -9,7 +9,8 @@
pub enum StreamEvent {
/// A streamed content delta from the model.
Token { text: String },
- /// A new orchestration turn began (`index` is 1-based, `max` = max_turns).
+ /// A new orchestration turn began (`index` is 1-based; `max` is the turn
+ /// cap, `0` when the run is unbounded, which is the normal case).
Step { index: u32, max: u32 },
/// A tool call started streaming: emitted mid-stream the instant the model's
/// tool-call `id` and `name` are known, before its arguments finish
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 6c1545f54..79c423c4a 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -844,6 +844,10 @@ impl ToolInvoker for CompositeToolInvoker {
/// API-server entry point. Preserves the original single-final-JSON contract by
/// running the streamed loop with a discarded event sink. Desktop-only: the
/// `cli` build has no proxy server.
+///
+/// An HTTP client has no way to cancel mid-run, so this is the one path that
+/// keeps a turn cap: a body that doesn't ask for one gets
+/// [`PROXY_DEFAULT_MAX_TURNS`] rather than the unbounded default.
#[cfg(not(feature = "cli"))]
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_server_side_openai_orchestration(
@@ -876,9 +880,27 @@ pub(crate) async fn run_server_side_openai_orchestration(
auto_approve: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
};
- run_orchestration_streamed(&tx, json_body, &args).await
+ let body = match json_body.get("max_turns") {
+ Some(_) => std::borrow::Cow::Borrowed(json_body),
+ None => {
+ let mut b = json_body.clone();
+ if let Some(map) = b.as_object_mut() {
+ map.insert(
+ "max_turns".to_string(),
+ serde_json::json!(PROXY_DEFAULT_MAX_TURNS),
+ );
+ }
+ std::borrow::Cow::Owned(b)
+ }
+ };
+ run_orchestration_streamed(&tx, &body, &args).await
}
+/// Turn cap applied to an API-server run whose body doesn't set one. Small on
+/// purpose: nothing on that path can interrupt a loop that never converges.
+#[cfg(not(feature = "cli"))]
+const PROXY_DEFAULT_MAX_TURNS: u64 = 8;
+
/// Streaming entry point. Emits `Step`/`ToolCall`/`ToolResult` progress events
/// and exactly one terminal `Done`/`Error` derived from the final result, while
/// still returning the completion JSON (or error) to the caller.
@@ -1339,13 +1361,7 @@ async fn orchestrate_inner(
)
.await?;
- // Explicit values pass through unclamped; `0` means unbounded (guarded by
- // the session token budget and cancellation). Absent falls back to 8 for
- // the proxy path, which has no interactive cancel.
- let max_turns = json_body
- .get("max_turns")
- .and_then(|v| v.as_u64())
- .unwrap_or(8) as usize;
+ let max_turns = body_turn_cap(json_body);
let http_model = HttpModelInvoker {
client: client.clone(),
@@ -1358,7 +1374,7 @@ async fn orchestrate_inner(
mcp_settings: mcp_settings.clone(),
};
- let max_session_tokens = json_body.get("max_session_tokens").and_then(|v| v.as_u64());
+ let max_session_tokens = body_session_budget(json_body);
let mut budget = SessionBudget::new(max_session_tokens);
if let Some(root) = project_root {
@@ -1555,6 +1571,26 @@ async fn open_todo_summary(
todo_registry?.lock().await.open_summary()
}
+/// Turn cap for a request body. No cap by default: the agent runs as long as
+/// the task needs, guarded by the session token budget and cancellation.
+/// `max_turns` survives only for callers that have neither guard (`jan cli
+/// agent step`, the API-server proxy); `0` and absent both mean unbounded.
+fn body_turn_cap(json_body: &serde_json::Value) -> usize {
+ json_body
+ .get("max_turns")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(0) as usize
+}
+
+/// Token-spend ceiling for a request body, the real bound on run length.
+/// `0` is the explicit "no ceiling" encoding, matching `max_turns`.
+fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {
+ json_body
+ .get("max_session_tokens")
+ .and_then(|v| v.as_u64())
+ .filter(|v| *v > 0)
+}
+
#[allow(clippy::too_many_arguments)]
async fn run_turn_cycle(
events: &mpsc::UnboundedSender<StreamEvent>,
@@ -1573,9 +1609,9 @@ async fn run_turn_cycle(
// instead of an easily-ignored suggestion. `None` for every later turn.
force_first_tool: Option<&str>,
) -> Result<serde_json::Value, String> {
- // `max_turns == 0` means unbounded: the session token budget and user
- // cancellation are the real guards, so an interactive run isn't cut off
- // mid-task by a fixed turn cap.
+ // `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
+ // fixed turn cap.
let unlimited = max_turns == 0;
let mut turn: usize = 0;
// Mid-run todo upkeep: after a long uninterrupted run of mutating tool
@@ -1868,7 +1904,7 @@ async fn run_turn_cycle(
}
Err(format!(
- "reached the {max_turns}-turn limit while the model was still calling tools; raise --max-turns (or set 0 for unbounded) to let it finish"
+ "reached the {max_turns}-turn limit while the model was still calling tools"
))
}
@@ -2614,6 +2650,23 @@ mod tests {
assert_eq!(result["choices"][0]["message"]["content"], "done");
}
+ #[test]
+ fn absent_turn_cap_is_unbounded() {
+ assert_eq!(body_turn_cap(&json!({})), 0);
+ assert_eq!(body_turn_cap(&json!({ "max_turns": 0 })), 0);
+ assert_eq!(body_turn_cap(&json!({ "max_turns": 3 })), 3);
+ }
+
+ #[test]
+ fn session_budget_treats_zero_and_absent_as_no_ceiling() {
+ assert_eq!(body_session_budget(&json!({})), None);
+ assert_eq!(body_session_budget(&json!({ "max_session_tokens": 0 })), None);
+ assert_eq!(
+ body_session_budget(&json!({ "max_session_tokens": 128_000 })),
+ Some(128_000)
+ );
+ }
+
#[test]
fn stop_reason_reads_first_choice() {
let completion = json!({ "choices": [{ "finish_reason": "tool_calls" }] });
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index efc3ac01a..e2e26e216 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -6,9 +6,8 @@ use serde::Deserialize;
use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};
-/// `[tools]` is always modeled. `[agent]` is only compiled for the CLI (its
-/// sole consumer, via `jan cli agent run/step/status`); serde still ignores the
-/// remaining deferred sections (`[budget]`/`[skills]`).
+/// `[tools]`/`[skills]` are always modeled. `[agent]` and `[budget]` are only
+/// compiled for the CLI (their sole consumer, via `jan cli agent run/step/status`).
#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct AgentToml {
#[cfg(feature = "cli")]
@@ -16,6 +15,9 @@ pub(crate) struct AgentToml {
pub agent: AgentSection,
#[cfg(feature = "cli")]
#[serde(default)]
+ pub budget: BudgetSection,
+ #[cfg(feature = "cli")]
+ #[serde(default)]
pub provider: Option<ProviderSection>,
#[serde(default)]
pub tools: ToolsSection,
@@ -50,15 +52,24 @@ pub(crate) struct SkillsSection {
pub enabled: Vec<String>,
}
-/// `[agent]` — resolves the model and default turn cap for CLI agent runs.
-/// `max_turns` is a soft default; the loop clamps it to 1..=400.
+/// `[budget]` — the only cap on how long a run may go. The agent takes as many
+/// turns as the task needs; `max_tokens` bounds the run's *marginal* token
+/// spend (see `SessionBudget`: replayed context is not recharged each turn).
+/// Unset applies `DEFAULT_MAX_SESSION_TOKENS`; an explicit `0` disables the
+/// ceiling, leaving cancellation as the only guard.
+#[cfg(feature = "cli")]
+#[derive(Debug, Clone, Default, Deserialize)]
+pub(crate) struct BudgetSection {
+ #[serde(default)]
+ pub max_tokens: Option<u64>,
+}
+
+/// `[agent]` — resolves the model and per-run knobs for CLI agent runs.
#[cfg(feature = "cli")]
#[derive(Debug, Clone, Default, Deserialize)]
pub(crate) struct AgentSection {
#[serde(default)]
pub model: Option<String>,
- #[serde(default)]
- pub max_turns: Option<u32>,
/// Context window limit in tokens for the model (defaults to 128K if unset).
/// Set this to match your model's actual context length so compaction
/// triggers at the right threshold.
@@ -115,7 +126,6 @@ pub(crate) struct ToolsSection {
const AGENT_TOML_TEMPLATE: &str = r#"[agent]
# model = "Jan-V4"
-max_turns = 400
# context_window = 128000 # tokens; defaults to 128K if unset
# compaction_reserve_tokens = 16384 # headroom before auto-compaction; defaults to 16K
# max_tokens = 4096 # cap on tokens the model generates per response (OpenAI max_tokens); omitted if unset
@@ -132,9 +142,11 @@ instructions_file = "AGENT.md"
# base_url = "https://api.openai.com/v1"
# models = ["gpt-4o"]
+# The run's only cap: new token spend across all turns (replayed context is not
+# recharged each turn). There is no turn limit. Defaults to 128000 when unset;
+# 0 disables the cap so the agent runs until the task is done or cancelled.
[budget]
-max_steps = 40
-max_tokens = 200000
+# max_tokens = 128000
[tools]
# read-only | deny | allow. read-only (default) exposes MCP tools and built-in
@@ -344,9 +356,14 @@ mod tests {
static COUNTER: AtomicU32 = AtomicU32::new(0);
+ /// The pid keeps the path unique across concurrently-running test binaries
+ /// (the `cli` and `tauri` feature configs both compile this module), which a
+ /// per-process counter alone does not: a leftover root from one run makes
+ /// `ensure_project` skip scaffolding in the next.
fn unique_root(tag: &str) -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
- let root = std::env::temp_dir().join(format!("jan_agent_test_{tag}_{n}"));
+ let pid = std::process::id();
+ let root = std::env::temp_dir().join(format!("jan_agent_test_{tag}_{pid}_{n}"));
std::fs::create_dir_all(&root).expect("create test project root");
root
}
@@ -535,33 +552,50 @@ mod tests {
let _ = std::fs::remove_dir_all(&root);
}
+ #[cfg(feature = "cli")]
#[test]
fn dotted_keys_write_and_remove_under_their_section() {
let root = unique_root("dotted");
ensure_project(&root).expect("scaffold");
let path = agent_toml_path(&root);
- set_agent_key(&path, "budget.max_steps", Some(toml_edit::value(60i64))).expect("write");
+ set_agent_key(&path, "budget.max_tokens", Some(toml_edit::value(60i64))).expect("write");
let raw = std::fs::read_to_string(&path).unwrap();
- assert!(raw.contains("max_steps = 60"), "written under [budget]: {raw}");
+ assert!(raw.contains("max_tokens = 60"), "written under [budget]: {raw}");
- set_agent_key(&path, "budget.max_steps", None).expect("unset");
+ set_agent_key(&path, "budget.max_tokens", None).expect("unset");
let raw = std::fs::read_to_string(&path).unwrap();
- assert!(!raw.contains("max_steps = 60"), "removed: {raw}");
+ assert!(!raw.contains("max_tokens = 60"), "removed: {raw}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
- fn full_template_parses_ignoring_deferred_sections() {
+ fn full_template_parses() {
let root = unique_root("full");
ensure_project(&root).expect("scaffold");
- // The template carries [agent]/[budget]/[skills] we don't model yet;
- // parsing must succeed and read [tools].
let cfg = load_agent_config(&root).expect("load");
assert_eq!(cfg.tools.default.as_deref(), Some("read-only"));
let _ = std::fs::remove_dir_all(&root);
}
+ /// The scaffold leaves the key commented out, so a fresh project picks up
+ /// `DEFAULT_MAX_SESSION_TOKENS` rather than a hardcoded template value.
+ #[cfg(feature = "cli")]
+ #[test]
+ fn scaffold_template_leaves_session_budget_unset() {
+ let cfg: AgentToml =
+ toml::from_str(AGENT_TOML_TEMPLATE).expect("scaffold template parses");
+ assert_eq!(cfg.budget.max_tokens, None);
+ }
+
+ #[cfg(feature = "cli")]
+ #[test]
+ fn budget_max_tokens_parses_when_set() {
+ let cfg: AgentToml =
+ toml::from_str("[budget]\nmax_tokens = 200000\n").expect("parses");
+ assert_eq!(cfg.budget.max_tokens, Some(200_000));
+ }
+
#[cfg(feature = "cli")]
#[test]
fn context_window_defaults_to_none_when_unset() {
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 83fc7b2c0..b45af6c4d 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -375,11 +375,12 @@ use std::collections::HashMap;
use std::io::Write as _;
use tokio::sync::{mpsc, Mutex};
-/// Default turn cap when neither `--max-turns` nor `agent.toml [agent].max_turns`
-/// is set. `0` means unbounded: the session token budget and user cancellation
-/// guard the loop instead of a fixed step count, so runs aren't cut off
-/// mid-task. Set an explicit cap to bound it.
-const DEFAULT_MAX_TURNS: u32 = 0;
+/// Token-spend ceiling for one agent run when `agent.toml [budget].max_tokens`
+/// is unset. There is no turn cap: the agent takes as many turns as the task
+/// needs and this budget (or cancellation) is what stops a runaway loop. `0`
+/// disables the ceiling entirely. Counted marginally by `SessionBudget`, so
+/// this bounds real new spend, not the context replayed on every turn.
+const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;
/// Resolve the `--project` flag (default `"."`) to an absolute path. The raw
/// value is what the model would otherwise see verbatim in the system prompt's
@@ -422,7 +423,7 @@ pub fn cli_agent_status(
"project": project_root.to_string_lossy(),
"data_folder": resolve_jan_data_folder().to_string_lossy(),
"model": cfg.agent.model,
- "max_turns": cfg.agent.max_turns.unwrap_or(DEFAULT_MAX_TURNS),
+ "max_session_tokens": cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),
"tools": {
"default": cfg.tools.default,
"allow": cfg.tools.allow,
@@ -491,20 +492,21 @@ pub fn cli_agent_config_list() -> Result<serde_json::Value, String> {
}))
}
-/// Autonomous multi-turn run to completion or the turn/token budget.
+/// Autonomous run: as many turns as the task needs, bounded only by the
+/// session token budget.
pub async fn cli_agent_run(
project: &str,
task: &str,
model: Option<String>,
- max_turns: Option<u32>,
overrides: ProviderOverrides,
auto_approve: bool,
resume: Option<ResumeTarget>,
) -> Result<(), String> {
- run_agent_loop(project, task, model, max_turns, overrides, auto_approve, resume).await
+ run_agent_loop(project, task, model, false, overrides, auto_approve, resume).await
}
-/// Single-turn run for debugging (`max_turns = 1`).
+/// Single-turn run for debugging: the one place a turn cap is still applied,
+/// and it is not user-configurable.
pub async fn cli_agent_step(
project: &str,
task: &str,
@@ -512,7 +514,7 @@ pub async fn cli_agent_step(
overrides: ProviderOverrides,
auto_approve: bool,
) -> Result<(), String> {
- run_agent_loop(project, task, model, Some(1), overrides, auto_approve, None).await
+ run_agent_loop(project, task, model, true, overrides, auto_approve, None).await
}
#[allow(clippy::too_many_arguments)]
@@ -572,16 +574,10 @@ struct PersistTarget {
history: Vec<serde_json::Value>,
}
-/// Resolved engine handle for a chat session: the args are built once and the
-/// request body is assembled per turn (the TUI reuses this across many turns;
-/// the plain CLI builds a single body). `model`/`max_turns` seed each body.
-pub(crate) struct AgentSession {
- pub args: OrchestrationArgs,
- pub permission_requests: PermissionRegistry,
- pub model: String,
- /// Fast model for the `smol` role (goal evaluation). Falls back to `model`.
- pub smol_model: String,
- pub max_turns: u32,
+/// Per-run limits resolved from agent.toml. Grouped rather than passed as a
+/// run of bare numbers, which would be trivial to transpose at a call site.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct SessionLimits {
/// Context window limit in tokens for the model. Defaults to 128K if agent.toml
/// doesn't set it. Used to display `ctx N/K` in the header and trigger compaction.
pub context_window: u64,
@@ -591,6 +587,21 @@ pub(crate) struct AgentSession {
/// Per-request output cap forwarded to the model as OpenAI `max_tokens`.
/// `None` omits the field (model default).
pub max_tokens: Option<u64>,
+ /// `[budget].max_tokens`: marginal token-spend ceiling for one run, the
+ /// only cap on run length. `0` is unbounded.
+ pub max_session_tokens: u64,
+}
+
+/// Resolved engine handle for a chat session: the args are built once and the
+/// request body is assembled per turn (the TUI reuses this across many turns;
+/// the plain CLI builds a single body). `model`/`limits` seed each body.
+pub(crate) struct AgentSession {
+ pub args: OrchestrationArgs,
+ pub permission_requests: PermissionRegistry,
+ pub model: String,
+ /// Fast model for the `smol` role (goal evaluation). Falls back to `model`.
+ pub smol_model: String,
+ pub limits: SessionLimits,
/// Whether the TUI expands `<think>` reasoning blocks (default false).
pub show_reasoning: bool,
/// Shared MCP connection map (same Arc held by `args`), so the TUI can
@@ -607,12 +618,12 @@ impl AgentSession {
let mut body = serde_json::json!({
"model": self.model,
"messages": messages,
- "max_turns": self.max_turns,
+ "max_session_tokens": self.limits.max_session_tokens,
"stream": true,
});
// Forward the per-request output cap only when configured; it flows to
// the upstream via `copy_optional_chat_params`.
- if let Some(max) = self.max_tokens {
+ if let Some(max) = self.limits.max_tokens {
body["max_tokens"] = serde_json::json!(max);
}
body
@@ -624,7 +635,6 @@ impl AgentSession {
fn prepare_agent_session(
project: &str,
model_override: Option<String>,
- max_turns_override: Option<u32>,
overrides: ProviderOverrides,
auto_approve: bool,
plan: bool,
@@ -668,10 +678,6 @@ fn prepare_agent_session(
.to_string(),
);
}
- let max_turns = max_turns_override
- .or(cfg.agent.max_turns)
- .unwrap_or(DEFAULT_MAX_TURNS);
-
// The `smol` role (used by /goal evaluation): an explicit smol_model in
// ~/.jan/config.toml, else reuse the main model so evaluation always works.
let smol_model = crate::core::agent::global_config::smol_model()
@@ -737,10 +743,12 @@ fn prepare_agent_session(
permission_requests,
model,
smol_model,
- max_turns,
- context_window: cfg.agent.context_window.unwrap_or(128_000),
- reserve_tokens: cfg.agent.compaction_reserve_tokens.unwrap_or(16_384),
- max_tokens: cfg.agent.max_tokens,
+ limits: SessionLimits {
+ context_window: cfg.agent.context_window.unwrap_or(128_000),
+ reserve_tokens: cfg.agent.compaction_reserve_tokens.unwrap_or(16_384),
+ max_tokens: cfg.agent.max_tokens,
+ max_session_tokens: cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),
+ },
show_reasoning: cfg.agent.show_reasoning.unwrap_or(false),
mcp_servers,
mcp_task,
@@ -789,7 +797,7 @@ fn prepare_agent_run(
project: &str,
task: &str,
model_override: Option<String>,
- max_turns_override: Option<u32>,
+ single_turn: bool,
overrides: ProviderOverrides,
auto_approve: bool,
resume: Option<ResumeTarget>,
@@ -799,7 +807,6 @@ fn prepare_agent_run(
let session = prepare_agent_session(
project,
model_override,
- max_turns_override,
overrides,
auto_approve,
false,
@@ -829,7 +836,10 @@ fn prepare_agent_run(
let mut history = resumed.as_ref().map(|r| r.history.clone()).unwrap_or_default();
history.push(serde_json::json!({ "role": "user", "content": final_task }));
- let body = session.body(serde_json::json!(history.clone()));
+ let mut body = session.body(serde_json::json!(history.clone()));
+ if single_turn {
+ body["max_turns"] = serde_json::json!(1);
+ }
// Emit resolved references stderr so the user sees what was injected
if !injected.is_empty() {
eprintln!("(resolved @path references)");
@@ -859,7 +869,7 @@ async fn run_agent_loop(
project: &str,
task: &str,
model_override: Option<String>,
- max_turns_override: Option<u32>,
+ single_turn: bool,
overrides: ProviderOverrides,
auto_approve: bool,
resume: Option<ResumeTarget>,
@@ -874,7 +884,7 @@ async fn run_agent_loop(
project,
task,
model_override,
- max_turns_override,
+ single_turn,
overrides,
auto_approve,
resume,
@@ -941,7 +951,6 @@ pub async fn cli_agent_ui(
project: &str,
task: Option<String>,
model: Option<String>,
- max_turns: Option<u32>,
images: Vec<String>,
overrides: ProviderOverrides,
auto_approve: bool,
@@ -958,15 +967,7 @@ pub async fn cli_agent_ui(
// Fresh install with a terminal attached: launch with no model rather than
// forcing sign-in here. The TUI shows a one-line notice and `/login` (or
// `jan login`) picks a model up once the user is ready.
- let session = prepare_agent_session(
- project,
- model,
- max_turns,
- overrides,
- auto_approve,
- plan,
- false,
- )?;
+ let session = prepare_agent_session(project, model, overrides, auto_approve, plan, false)?;
// TUI threads persist under the project's .jan/agent dir, separate from the
// desktop store, so continuing here never mutates desktop threads.
let agent_dir = agent_dir_for(&project_root);
@@ -987,7 +988,10 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
print!("{text}");
let _ = std::io::stdout().flush();
}
- StreamEvent::Step { index, max } => eprintln!("\n\x1b[2m[turn {index}/{max}]\x1b[0m"),
+ StreamEvent::Step { index, max } => match max {
+ 0 => eprintln!("\n\x1b[2m[turn {index}]\x1b[0m"),
+ m => eprintln!("\n\x1b[2m[turn {index}/{m}]\x1b[0m"),
+ },
// In-progress signal is for the live TUI; the piped log stays quiet
// until the full call (with args) arrives just below.
// Headless prints one line per completed call; the in-progress signal
@@ -1364,7 +1368,6 @@ mod tests {
let session = prepare_agent_session(
dir.path().to_str().unwrap(),
None,
- None,
ProviderOverrides::default(),
false,
false,
@@ -1400,7 +1403,6 @@ mod tests {
let session = prepare_agent_session(
dir.path().to_str().unwrap(),
None,
- None,
ProviderOverrides::default(),
false,
false,
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 9b6cfeeb8..ccbbcf86d 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -39,7 +39,7 @@ use markdown::{
format_markdown_lines, live_assistant_lines, reasoning_detail_lines, reasoning_summary_row,
};
-use super::{sort_threads_recent, AgentSession, ResumeTarget};
+use super::{sort_threads_recent, AgentSession, ResumeTarget, SessionLimits};
use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};
use crate::core::agent::git;
use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};
@@ -526,7 +526,6 @@ struct App {
/// Orchestration handle for out-of-run model calls (the `/compact` command).
/// `None` in unit tests, set by `run` for the live session.
args: Option<Arc<OrchestrationArgs>>,
- max_turns: u32,
/// Context window limit for the current model (default 128K).
context_window: u64,
/// Tokens to reserve for the model's response (compaction triggers at limit - reserve).
@@ -534,6 +533,9 @@ struct App {
/// Per-request output cap forwarded to the model as OpenAI `max_tokens`.
/// `None` omits the field (model default).
max_tokens: Option<u64>,
+ /// Token-spend ceiling for one message's run; `0` is unbounded. The only
+ /// cap on run length -- there is no turn limit.
+ max_session_tokens: u64,
/// Repo top-level when the project is a git repo; enables workspace snapshots.
/// Cleared if git setup fails, permanently disabling snapshots this session.
repo_root: Option<PathBuf>,
@@ -836,10 +838,7 @@ impl App {
#[allow(clippy::too_many_arguments)]
fn new(
model: String,
- max_turns: u32,
- context_window: u64,
- reserve_tokens: u64,
- max_tokens: Option<u64>,
+ limits: SessionLimits,
show_reasoning: bool,
agent_dir: std::path::PathBuf,
project_root: PathBuf,
@@ -852,10 +851,10 @@ impl App {
goal_eval_pending: false,
run_mode: crate::core::agent::plan::RunMode::Normal,
args: None,
- max_turns,
- context_window,
- reserve_tokens,
- max_tokens,
+ context_window: limits.context_window,
+ reserve_tokens: limits.reserve_tokens,
+ max_tokens: limits.max_tokens,
+ max_session_tokens: limits.max_session_tokens,
repo_root,
git_branch: git::current_branch(&project_root),
project_root,
@@ -1606,7 +1605,7 @@ impl App {
let mut body = serde_json::json!({
"model": self.model,
"messages": self.history,
- "max_turns": self.max_turns,
+ "max_session_tokens": self.max_session_tokens,
"stream": true,
});
// Forward the per-request output cap only when configured; it reaches
@@ -3481,10 +3480,7 @@ pub async fn run(
permission_requests,
model,
smol_model,
- max_turns,
- context_window,
- reserve_tokens,
- max_tokens,
+ limits,
show_reasoning,
mcp_servers,
mcp_task,
@@ -3522,7 +3518,14 @@ pub async fn run(
// A git repo enables workspace snapshots (rewind can restore files); a
// non-repo runs exactly as before with conversation-only rewind.
let repo_root = git::repo_root(&project_root);
- let mut app = App::new(model, max_turns, context_window, reserve_tokens, max_tokens, show_reasoning, agent_dir, project_root, repo_root);
+ let mut app = App::new(
+ model,
+ limits,
+ show_reasoning,
+ agent_dir,
+ project_root,
+ repo_root,
+ );
app.smol_model = smol_model;
app.args = Some(args.clone());
// Adopt the session's startup run mode (e.g. `--plan`) so the header badge
@@ -4818,12 +4821,6 @@ enum AgentSettingKind {
}
const AGENT_SETTINGS: &[AgentSettingDef] = &[
- AgentSettingDef {
- key: "max_turns",
- label: "max_turns",
- desc: "turns per message, clamped 1-400",
- kind: AgentSettingKind::Int { default: Some(400), min: 1 },
- },
AgentSettingDef {
key: "context_window",
label: "context_window",
@@ -4854,17 +4851,11 @@ const AGENT_SETTINGS: &[AgentSettingDef] = &[
desc: "markdown injected into the system prompt",
kind: AgentSettingKind::Text { default: "AGENT.md" },
},
- AgentSettingDef {
- key: "budget.max_steps",
- label: "budget.max_steps",
- desc: "max tool-call steps per run",
- kind: AgentSettingKind::Int { default: Some(40), min: 1 },
- },
AgentSettingDef {
key: "budget.max_tokens",
label: "budget.max_tokens",
- desc: "max tokens budget per run",
- kind: AgentSettingKind::Int { default: Some(200000), min: 1 },
+ desc: "token-spend ceiling per run; the only cap on run length",
+ kind: AgentSettingKind::Int { default: Some(128000), min: 0 },
},
AgentSettingDef {
key: "tools.default",
@@ -7571,6 +7562,7 @@ fn footer(app: &App) -> Paragraph<'static> {
#[cfg(test)]
mod tests {
+ use super::SessionLimits;
use super::{
age_closed_todos, apply_resume, assistant_is_awaiting_user_answer, build_user_message,
clipboard_path,
@@ -7616,7 +7608,20 @@ mod tests {
std::process::id(),
uuid::Uuid::new_v4()
));
- App::new("m".into(), 8, 128_000, 16_384, None, false, agent_dir, std::path::PathBuf::from("/tmp/repo"), None)
+ let limits = SessionLimits {
+ context_window: 128_000,
+ reserve_tokens: 16_384,
+ max_tokens: None,
+ max_session_tokens: 128_000,
+ };
+ App::new(
+ "m".into(),
+ limits,
+ false,
+ agent_dir,
+ std::path::PathBuf::from("/tmp/repo"),
+ None,
+ )
}
/// Draw `app` into an off-screen terminal and return its rows as strings.
@@ -9291,7 +9296,7 @@ mod tests {
// A minimal agent.toml so the picker shows a real current value.
std::fs::create_dir_all(&app.agent_dir).unwrap();
let toml_path = app.agent_dir.join("agent.toml");
- std::fs::write(&toml_path, "[agent]\nmax_turns = 8\n").unwrap();
+ std::fs::write(&toml_path, "[agent]\ncontext_window = 64000\n").unwrap();
super::settings_command(&mut app, "max_parallel_subagents 20");
let doc = std::fs::read_to_string(&toml_path).unwrap();
@@ -9299,7 +9304,10 @@ mod tests {
doc.contains("max_parallel_subagents = 20"),
"key written: {doc}"
);
- assert!(doc.contains("max_turns = 8"), "other keys preserved: {doc}");
+ assert!(
+ doc.contains("context_window = 64000"),
+ "other keys preserved: {doc}"
+ );
// Zero is invalid: rejected, file unchanged.
super::settings_command(&mut app, "max_parallel_subagents 0");
@@ -9319,9 +9327,9 @@ mod tests {
let row = picker
.items
.iter()
- .find(|i| i.value == "max_turns")
- .expect("max_turns row present");
- assert_eq!(row.hint.as_deref(), Some("= 8"));
+ .find(|i| i.value == "context_window")
+ .expect("context_window row present");
+ assert_eq!(row.hint.as_deref(), Some("= 64000"));
let row = picker
.items
.iter()
@@ -9336,21 +9344,21 @@ mod tests {
let mut app = test_app();
std::fs::create_dir_all(&app.agent_dir).unwrap();
let toml_path = app.agent_dir.join("agent.toml");
- std::fs::write(&toml_path, "[agent]\nmax_turns = 8\n").unwrap();
+ std::fs::write(&toml_path, "[agent]\ncontext_window = 64000\n").unwrap();
super::settings_command(&mut app, "");
- // Select the max_turns row (index 0) and press x: the key must be
+ // Select the context_window row (index 0) and press x: the key must be
// removed, the row hint flip back to (unset), the note rendered.
press(&mut app, KeyCode::Char('x'), KeyModifiers::NONE).await;
let doc = std::fs::read_to_string(&toml_path).unwrap();
- assert!(!doc.contains("max_turns = 8"), "key removed: {doc}");
- assert!(transcript_text(&app).contains("max_turns unset"));
+ assert!(!doc.contains("context_window = 64000"), "key removed: {doc}");
+ assert!(transcript_text(&app).contains("context_window unset"));
let picker = app.picker.as_ref().expect("picker stays open");
let row = picker
.items
.iter()
- .find(|i| i.value == "max_turns")
- .expect("max_turns row present");
+ .find(|i| i.value == "context_window")
+ .expect("context_window row present");
assert_eq!(row.hint.as_deref(), Some("(unset)"));
let _ = std::fs::remove_dir_all(&app.agent_dir);
}
@@ -9415,16 +9423,19 @@ mod tests {
let mut app = test_app();
std::fs::create_dir_all(&app.agent_dir).unwrap();
let toml_path = app.agent_dir.join("agent.toml");
- std::fs::write(&toml_path, "[agent]\nmax_turns = 8\n").unwrap();
+ std::fs::write(&toml_path, "[agent]\ncontext_window = 8\n").unwrap();
- let def = AGENT_SETTINGS.iter().find(|d| d.key == "max_turns").unwrap();
+ let def = AGENT_SETTINGS
+ .iter()
+ .find(|d| d.key == "context_window")
+ .unwrap();
app.settings_prompt = Some(super::SettingsPrompt::new(def, Some("8")));
super::handle_settings_key(&mut app, key(KeyCode::Backspace), false);
super::handle_settings_key(&mut app, key(KeyCode::Enter), false);
assert!(app.settings_prompt.is_none());
let doc = std::fs::read_to_string(&toml_path).unwrap();
- assert!(!doc.contains("max_turns = 8"), "key removed: {doc}");
- assert!(transcript_text(&app).contains("max_turns unset"));
+ assert!(!doc.contains("context_window = 8"), "key removed: {doc}");
+ assert!(transcript_text(&app).contains("context_window unset"));
let _ = std::fs::remove_dir_all(&app.agent_dir);
}
@@ -12679,6 +12690,20 @@ mod tests {
let body = app.body();
assert_eq!(body.get("max_tokens").and_then(|v| v.as_u64()), Some(4096));
}
+
+ /// The session token budget is the only cap: it is always forwarded, and no
+ /// turn limit is sent at all.
+ #[test]
+ fn body_forwards_session_budget_and_no_turn_cap() {
+ let mut app = test_app();
+ app.max_session_tokens = 64_000;
+ let body = app.body();
+ assert_eq!(
+ body.get("max_session_tokens").and_then(|v| v.as_u64()),
+ Some(64_000)
+ );
+ assert!(body.get("max_turns").is_none());
+ }
}