Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): --max-turns and --max-session-tokens flags for jan cli agent run (#9008)
Akarshan Biswas34259d957004
diff --git a/Makefile b/Makefileindex 10e8a0990..5bbd3f87c 100644--- a/Makefile+++ b/Makefile@@ -177,10 +177,18 @@ stub-resources:test-ci: test-prepare$(MAKE) test-rust-# Cheap compile guard for the CLI feature set. The `jan` CLI is no longer+# Compile and test guard for the CLI feature set. The `jan` CLI is no longer# bundled with the app; `make test` still builds the real binary via build-cli.+#+# This is the only job that compiles jan-cli at all: it is a standalone crate+# and not a dependency of src-tauri, so the rust-check `cli` matrix entry never+# reaches it (that entry's --all-targets covers app_lib's own+# cfg(feature = "cli") test modules, which is a different crate). A bare+# `cargo check` here built the bin but not the #[cfg(test)] module, which is+# how the fixture in `compact_plugin_list_omits_long_metadata` silently rotted.+# `cargo test` builds and runs those targets, so it subsumes that check.check-cli:- cd src-tauri/jan-cli && cargo check --locked --no-default-features --features cli+ cd src-tauri/jan-cli && cargo test --locked --no-default-features --features cli# Build MLX server (macOS Apple Silicon only) - always builds, unless# JAN_MLX_PREBUILT_DIR holds a cached build of the same inputsdiff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdxindex 38ce49bf6..9861844f9 100644--- a/docs/src/pages/docs/agent/cli.mdx+++ b/docs/src/pages/docs/agent/cli.mdx@@ -74,14 +74,21 @@ Run the agent without a UI. This is the form to use in scripts.### `run`-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.+Run to completion. There is no turn cap by default - the agent runs as many turns as the task needs,+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+`--max-turns` for a hard bound on an unattended run.+</Callout>```bashjan 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 "add unit tests for the parser"jan cli agent run --safe "run the migration" # approve each step+jan cli agent run --max-turns 5 --max-session-tokens 20000 "triage the build failure"```| Flag | Description |@@ -96,6 +103,8 @@ jan cli agent run --safe "run the migration" # approve each step| `--fork-session` | Open the resumed session as a new thread, leaving the original resumable || `--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 a non-zero exit; 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 || `--provider`, `--api-key` | Credential overrides for this run || `--output-format <FORMAT>` | `text` (default) streams the answer; `json` prints one result object; `stream-json` prints one JSON event per line || `--input-format <FORMAT>` | `text` (default) ignores stdin; `stream-json` reads client messages while the run is in flight. Requires `--output-format stream-json` |diff --git a/docs/src/pages/docs/agent/project-config.mdx b/docs/src/pages/docs/agent/project-config.mdxindex a92b5666b..dad6e0b9e 100644--- a/docs/src/pages/docs/agent/project-config.mdx+++ b/docs/src/pages/docs/agent/project-config.mdx@@ -124,10 +124,16 @@ Desktop. Most projects don't need it. See [Providers](/docs/agent/providers#per-| 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 |+| `max_tokens` | `128000` | Advisory token ceiling for one run (new spend across all turns). Set `0` to disable it. Overridden per invocation by `--max-session-tokens`. Defaults to `128000` when unset |-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).+A marker for how far one run has gone, distinct from the per-request context window. It tracks the+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+`--max-turns` (see the [CLI reference](/docs/agent/cli)), or cancel it.+</Callout>### `[tools]`diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex 82b1304f5..aa6f0ca49 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -162,6 +162,24 @@ impl ResumeArgs {}}+/// Per-invocation cost limits for `jan cli agent run`. Both mirror the engine's+/// own semantics: `0` means unbounded, and an unpassed flag leaves the config+/// files (or, for turns, nothing at all) in charge.+///+/// Only `--max-turns` ends a run. The token ceiling is advisory: passing it+/// compacts the conversation and records a note, then the run continues.+#[derive(Args, Clone, Copy)]+struct BudgetArgs {+ /// Fail the run after at most N agentic turns; bounds this run only, not+ /// its subagents (0 = unbounded, the default)+ #[arg(long, value_name = "N")]+ max_turns: Option<u64>,+ /// Advisory token ceiling overriding [budget].max_tokens: triggers+ /// compaction and a note, but does not stop the run (0 = no ceiling)+ #[arg(long, value_name = "N")]+ max_session_tokens: Option<u64>,+}+/// Same flags for `jan cli agent run`, which has a required positional TASK: a/// space-separated `--resume ID` would swallow the task, so the value form must/// be written `--resume=ID`.@@ -331,7 +349,7 @@ impl ProviderArgs {#[derive(Subcommand)]enum AgentCommands {- /// Run the agent loop to completion or the session token budget+ /// Run the agent loop to completion, or to a --max-turns capRun {/// Project root containing .jan/agent/agent.toml#[arg(long, default_value = ".")]@@ -352,6 +370,8 @@ enum AgentCommands {worktree: WorktreeArgs,#[command(flatten)]resume: ResumeRunArgs,+ #[command(flatten)]+ budget: BudgetArgs,/// `text` streams the answer as it arrives; `json` prints one result/// object on stdout when the run finishes; `stream-json` prints one/// JSON event per line as the run proceeds, ending with that object@@ -807,6 +827,7 @@ async fn handle_agent(cmd: AgentCommands) {sandbox,worktree,resume,+ budget,output_format,input_format,} => {@@ -819,6 +840,8 @@ async fn handle_agent(cmd: AgentCommands) {auto_approve: !safe,sandbox: sandbox.into_flag(),worktree: worktree.into_flag(),+ max_turns: budget.max_turns,+ max_session_tokens: budget.max_session_tokens,..Default::default()},resume.into_request(),@@ -1221,6 +1244,39 @@ mod tests {assert!(Cli::parse_from(["jan", "--safe"]).safe);}+ /// Parse `jan cli agent run <task> <extra...>` and pull out its budget args.+ fn parsed_budget(extra: &[&str]) -> BudgetArgs {+ let mut argv = vec!["jan", "cli", "agent", "run", "task"];+ argv.extend_from_slice(extra);+ match Cli::parse_from(argv).command {+ Some(Commands::Cli {+ cmd:+ CliCommands::Agent {+ cmd: AgentCommands::Run { budget, .. },+ },+ }) => budget,+ _ => panic!("expected `cli agent run`"),+ }+ }++ /// An unpassed limit is `None` so the config files (or nothing, for turns)+ /// decide; `0` must survive parsing as the engine's unbounded marker rather+ /// than collapsing into the same `None`.+ #[test]+ fn run_limits_parse_and_default_to_unset() {+ let none = parsed_budget(&[]);+ assert_eq!(none.max_turns, None);+ assert_eq!(none.max_session_tokens, None);++ let set = parsed_budget(&["--max-turns", "5", "--max-session-tokens", "20000"]);+ assert_eq!(set.max_turns, Some(5));+ assert_eq!(set.max_session_tokens, Some(20_000));++ let zero = parsed_budget(&["--max-turns", "0", "--max-session-tokens", "0"]);+ assert_eq!(zero.max_turns, Some(0));+ assert_eq!(zero.max_session_tokens, Some(0));+ }+/// Parse `jan cli agent run <task> <extra...>` and pull out its input format.fn parsed_input_format(extra: &[&str]) -> InputFormat {let mut argv = vec!["jan", "cli", "agent", "run", "task"];@@ -1484,6 +1540,8 @@ mod tests {skills: 2,commands: 1,agents: 3,+ tools: 4,+ hooks: 5,},InstalledPlugin {name: "beta".into(),@@ -1493,6 +1551,8 @@ mod tests {skills: 0,commands: 0,agents: 0,+ tools: 0,+ hooks: 0,},];@@ -1501,11 +1561,16 @@ mod tests {assert!(output.lines().next().unwrap().contains("PLUGIN"));assert!(output.lines().next().unwrap().contains("COMMANDS"));assert!(output.lines().next().unwrap().contains("AGENTS"));+ assert!(output.lines().next().unwrap().contains("TOOLS"));+ assert!(output.lines().next().unwrap().contains("HOOKS"));assert!(output.contains("alpha"));assert!(output.contains("1.2.3"));- assert!(output.contains("2"));- assert!(output.contains("1"));- assert!(output.contains("3"));+ // Every count alpha declares, in column order.+ let alpha = output.lines().nth(1).unwrap();+ assert_eq!(+ alpha.split_whitespace().collect::<Vec<_>>(),+ ["alpha", "1.2.3", "2", "1", "3", "4", "5"]+ );assert!(!output.contains("long description"));assert!(!output.contains("example.com"));}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 93499f48d..ec111b828 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -744,12 +744,40 @@ use tauri_plugin_agent_tools::tools::gate::PermissionDecision;use tokio::sync::{mpsc, Mutex};/// 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.+/// is unset. `0` disables the ceiling entirely. Counted marginally by+/// `SessionBudget`, so it tracks real new spend, not the context replayed on+/// every turn.+///+/// 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.const DEFAULT_MAX_SESSION_TOKENS: u64 = 128_000;+/// Where the session token ceiling in effect came from, so `agent status` can+/// say which source won.+///+/// `agent status` takes no budget flag and so always passes `None`, making+/// `"flag"` unreachable from the binary today. It is kept because the argument+/// mirrors `resolve_session_budget` below: a status surface that does accept+/// the flag (or any caller reporting an in-flight run's ceiling) would+/// otherwise report `agent.toml` for a value the flag had overridden.+fn session_budget_source(flag: Option<u64>, configured: Option<u64>) -> &'static str {+ match (flag, configured) {+ (Some(_), _) => "flag",+ (None, Some(_)) => "agent.toml",+ (None, None) => "default",+ }+}++/// Session token ceiling for one run. Precedence is the per-invocation+/// `--max-session-tokens` flag, then `agent.toml [budget].max_tokens`, then+/// `DEFAULT_MAX_SESSION_TOKENS` - the same flag/config/default shape the+/// sandbox setting resolves with. `0` from either source means unbounded and is+/// carried through as-is (see `body_session_budget`).+fn resolve_session_budget(flag: Option<u64>, configured: Option<u64>) -> u64 {+ flag.or(configured).unwrap_or(DEFAULT_MAX_SESSION_TOKENS)+}+/// 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/// working-directory block, so a bare "." must become the real cwd rather than@@ -820,7 +848,11 @@ 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_session_tokens": cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),+ // The effective ceiling with the config files resolved. A+ // `--max-session-tokens` flag is per-invocation and so, like+ // `--sandbox` below, cannot be reflected in a config dump.+ "max_session_tokens": resolve_session_budget(None, cfg.budget.max_tokens),+ "max_session_tokens_source": session_budget_source(None, cfg.budget.max_tokens),"tools": {"default": cfg.tools.default,"allow": cfg.tools.allow,@@ -937,8 +969,9 @@ pub async fn cli_plugin_search(crate::core::agent::plugins::search(&resolve_project_root(project), query).await}-/// Autonomous run: as many turns as the task needs, bounded only by the-/// session token budget.+/// Autonomous run: as many turns as the task needs, bounded by a `max_turns`+/// cap when one is set, and otherwise only by cancellation. The session token+/// budget is advisory and does not stop the run (see `body_session_budget`).#[allow(clippy::too_many_arguments)]pub async fn cli_agent_run(project: &str,@@ -964,8 +997,8 @@ pub async fn cli_agent_run(.await}-/// Single-turn run for debugging: the one place a turn cap is still applied,-/// and it is not user-configurable.+/// Single-turn run for debugging: the turn cap is pinned to 1 here and+/// outranks any `--max-turns`.pub async fn cli_agent_step(project: &str,task: &str,@@ -1089,9 +1122,17 @@ pub(crate) struct SessionLimits {/// 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.+ /// `--max-session-tokens`, else `[budget].max_tokens`, else the default:+ /// marginal token-spend ceiling for one run. `0` is no ceiling.+ ///+ /// Advisory: crossing it triggers compaction and a recorded note, it does+ /// not end the run. `max_turns` is the hard bound.pub max_session_tokens: u64,+ /// `--max-turns`: hard cap on agentic turns for this run, and the only+ /// setting that terminates one. `None` omits the field from the request+ /// body, which the engine reads as unbounded; `0` means unbounded too (see+ /// `body_turn_cap`).+ pub max_turns: Option<u64>,}/// Resolved engine handle for a chat session: the args are built once and the@@ -1133,24 +1174,43 @@ pub(crate) struct AgentSession {pub workspace_note: Option<String>,}+/// The request body for one turn, as a free function of the parts that shape+/// it. Split out of [`AgentSession::body`] so the wire contract is testable+/// without standing up an orchestration handle (MCP maps, HTTP client, tool+/// permissions), none of which this assembly reads.+fn request_body(+ model: &str,+ limits: &SessionLimits,+ send_reasoning: bool,+ messages: serde_json::Value,+) -> serde_json::Value {+ let mut body = serde_json::json!({+ "model": model,+ "messages": messages,+ "max_session_tokens": 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) = limits.max_tokens {+ body["max_tokens"] = serde_json::json!(max);+ }+ // Single place a turn cap enters the body: `agent step` pins 1 the same+ // way `--max-turns` pins N, so both go through `limits`. Absent rather+ // than 0 when unset, so the engine's own default applies.+ if let Some(turns) = limits.max_turns {+ body["max_turns"] = serde_json::json!(turns);+ }+ // Reasoning resend policy: the request-level flag the loop reads to+ // decide whether prior assistant `reasoning_content` goes back out.+ body["send_reasoning"] = serde_json::json!(send_reasoning);+ body+}+impl AgentSession {/// Build a streaming request body for the given conversation history.pub(crate) fn body(&self, messages: serde_json::Value) -> serde_json::Value {- let mut body = serde_json::json!({- "model": self.model,- "messages": messages,- "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.limits.max_tokens {- body["max_tokens"] = serde_json::json!(max);- }- // Reasoning resend policy: the request-level flag the loop reads to- // decide whether prior assistant `reasoning_content` goes back out.- body["send_reasoning"] = serde_json::json!(self.send_reasoning);- body+ request_body(&self.model, &self.limits, self.send_reasoning, messages)}}@@ -1176,6 +1236,14 @@ pub struct SessionFlags {/// defers to `[agent].worktree`, then the global `worktree`, then the CLI/// default of off.pub worktree: Option<bool>,+ /// `--max-turns`: hard cap on agentic turns, and the only setting that+ /// ends a run. `None` (not passed) leaves the run unbounded by turns; `0`+ /// is unbounded as well.+ pub max_turns: Option<u64>,+ /// `--max-session-tokens`: advisory session token ceiling, outranking+ /// `[budget].max_tokens`. `None` (not passed) defers to that, then to+ /// `DEFAULT_MAX_SESSION_TOKENS`.+ pub max_session_tokens: Option<u64>,}/// The desktop app's currently-selected model, adopted only when signed in to@@ -1486,7 +1554,11 @@ fn prepare_agent_session(compaction_ratio,compaction_reserve_tokens: cfg.agent.compaction_reserve_tokens,max_tokens: cfg.agent.max_tokens,- max_session_tokens: cfg.budget.max_tokens.unwrap_or(DEFAULT_MAX_SESSION_TOKENS),+ max_session_tokens: resolve_session_budget(+ flags.max_session_tokens,+ cfg.budget.max_tokens,+ ),+ max_turns: flags.max_turns,},show_reasoning: cfg.agent.show_reasoning.unwrap_or(false),stream_reasoning: crate::core::agent::global_config::stream_reasoning_enabled(),@@ -1545,6 +1617,9 @@ fn prepare_agent_run(SessionFlags {plan: false,require_model: true,+ // `agent step` is a single turn by definition and outranks any+ // flag; `agent run` carries whatever `--max-turns` asked for.+ max_turns: if single_turn { Some(1) } else { flags.max_turns },..flags},resume.as_ref(),@@ -1599,10 +1674,7 @@ 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 mut body = session.body(serde_json::json!(history.clone()));- if single_turn {- body["max_turns"] = serde_json::json!(1);- }+ let body = session.body(serde_json::json!(history.clone()));// Emit resolved references stderr so the user sees what was injectedif !injected.is_empty() {eprintln!("(resolved @path references)");@@ -3449,4 +3521,66 @@ mod tests {let snapped = serde_json::json!({ "id": "s", "metadata": { "base_snapshot": "cafe" } });assert_eq!(fork_base(Some(&snapped)).as_deref(), Some("cafe"));}++ /// `--max-session-tokens` outranks `[budget].max_tokens`, which outranks+ /// the built-in default; `0` from either source survives as the unbounded+ /// marker `body_session_budget` expects rather than falling through.+ #[test]+ fn session_budget_precedence_is_flag_then_config_then_default() {+ assert_eq!(+ resolve_session_budget(None, None),+ DEFAULT_MAX_SESSION_TOKENS+ );+ assert_eq!(resolve_session_budget(None, Some(50_000)), 50_000);+ assert_eq!(resolve_session_budget(Some(20_000), Some(50_000)), 20_000);+ assert_eq!(resolve_session_budget(Some(20_000), None), 20_000);+ assert_eq!(resolve_session_budget(Some(0), Some(50_000)), 0);+ assert_eq!(resolve_session_budget(None, Some(0)), 0);++ assert_eq!(session_budget_source(None, None), "default");+ assert_eq!(session_budget_source(None, Some(50_000)), "agent.toml");+ assert_eq!(session_budget_source(Some(0), Some(50_000)), "flag");+ }++ fn limits_with(max_turns: Option<u64>, max_session_tokens: u64) -> SessionLimits {+ SessionLimits {+ context_window: 128_000,+ context_window_source:+ crate::core::cli::model_capabilities::ContextWindowSource::Fallback,+ compaction_ratio: crate::core::agent::compaction::DEFAULT_COMPACTION_RATIO,+ compaction_reserve_tokens: None,+ max_tokens: None,+ max_session_tokens,+ max_turns,+ }+ }++ /// The write side of the caps: the limits have to reach the request body in+ /// the encoding `body_turn_cap` / `body_session_budget` read back, or the+ /// flags are inert. `max_turns` is absent (not `0`) when unset, so a caller+ /// that never passes it is byte-identical to before the flag existed.+ #[test]+ fn run_limits_reach_the_request_body() {+ let messages = serde_json::json!([]);++ let unset = request_body("m", &limits_with(None, 128_000), true, messages.clone());+ assert!(+ unset.get("max_turns").is_none(),+ "an unset cap must not write the field at all: {unset}"+ );+ assert_eq!(unset["max_session_tokens"], 128_000);++ // What `agent step` pins, and what `--max-turns 5` pins, by the same route.+ let stepped = request_body("m", &limits_with(Some(1), 128_000), true, messages.clone());+ assert_eq!(stepped["max_turns"], 1);+ let capped = request_body("m", &limits_with(Some(5), 20_000), true, messages.clone());+ assert_eq!(capped["max_turns"], 5);+ assert_eq!(capped["max_session_tokens"], 20_000);++ // An explicit 0 is the engine's "unbounded" encoding and must survive as+ // itself rather than being dropped back to the absent case.+ let zero = request_body("m", &limits_with(Some(0), 0), true, messages);+ assert_eq!(zero["max_turns"], 0);+ assert_eq!(zero["max_session_tokens"], 0);+ }}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 96c3f0a15..9c36b5633 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -19174,6 +19174,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,+ max_turns: None,};let app = App::new("m".into(),@@ -19677,6 +19678,7 @@ mod tests {compaction_reserve_tokens: Some(16_384),max_tokens: None,max_session_tokens: 128_000,+ max_turns: None,},false,agent_dir,