A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
honor an explicitly configured max tokens (#3362)
kt767cb53d21f7
diff --git a/.changes/fix-models-json-max-tokens.md b/.changes/fix-models-json-max-tokens.mdnew file mode 100644index 0000000000..024973e480--- /dev/null+++ b/.changes/fix-models-json-max-tokens.md@@ -0,0 +1 @@+- A `maxTokens` configured in models.json (or a per-model override) now reaches the provider unchanged instead of being silently clamped to the 32000 default output ceiling; catalog models keep the default ceiling ([#755](https://github.com/PrimeIntellect-ai/prime-agent/issues/755)).diff --git a/crates/pa-agent/src/agent.rs b/crates/pa-agent/src/agent.rsindex 974d3e1bfc..ef97948697 100644--- a/crates/pa-agent/src/agent.rs+++ b/crates/pa-agent/src/agent.rs@@ -1421,6 +1421,7 @@ mod tests {cost: crate::types::UsageCost::default(),context_window: 200_000,max_tokens: 8_192,+ max_tokens_explicit: false,}}@@ -1529,6 +1530,7 @@ mod tests {cost: crate::types::UsageCost::default(),context_window: 200_000,max_tokens: 8_192,+ max_tokens_explicit: false,}}@@ -1589,6 +1591,7 @@ mod tests {cost: crate::types::UsageCost::default(),context_window: 200_000,max_tokens: 8_192,+ max_tokens_explicit: false,}}diff --git a/crates/pa-agent/src/proxy.rs b/crates/pa-agent/src/proxy.rsindex 293e869437..4fdc6e76ea 100644--- a/crates/pa-agent/src/proxy.rs+++ b/crates/pa-agent/src/proxy.rs@@ -1102,6 +1102,7 @@ mod tests {cost: crate::types::UsageCost::default(),context_window: 128_000,max_tokens: 8_192,+ max_tokens_explicit: false,}}diff --git a/crates/pa-agent/src/types.rs b/crates/pa-agent/src/types.rsindex 955d879363..b88fa521cc 100644--- a/crates/pa-agent/src/types.rs+++ b/crates/pa-agent/src/types.rs@@ -430,6 +430,22 @@ pub struct Model {pub context_window: u64,#[serde(rename = "maxTokens", default)]pub max_tokens: u64,+ /// Set when `maxTokens` came from explicit configuration: rides the+ /// wire-shape round-trips with the pa-ai model so the flag survives+ /// the crate boundary and the persisted session state.+ #[serde(+ rename = "maxTokensExplicit",+ default,+ skip_serializing_if = "is_false"+ )]+ pub max_tokens_explicit: bool,+}++/// `skip_serializing_if` predicate for [`Model::max_tokens_explicit`]: the+/// persisted/proxied JSON stays byte-identical when the flag is unset.+#[allow(clippy::trivially_copy_pass_by_ref)] // serde's skip predicate ABI takes the field by reference+fn is_false(value: &bool) -> bool {+ !*value}impl Model {@@ -445,6 +461,7 @@ impl Model {cost: UsageCost::default(),context_window: 0,max_tokens: 0,+ max_tokens_explicit: false,}}}diff --git a/crates/pa-agent/tests/agent_loop_scripted.rs b/crates/pa-agent/tests/agent_loop_scripted.rsindex 756b9d53d2..ee1adca182 100644--- a/crates/pa-agent/tests/agent_loop_scripted.rs+++ b/crates/pa-agent/tests/agent_loop_scripted.rs@@ -32,6 +32,7 @@ fn test_model() -> Model {cost: pa_agent::types::UsageCost::default(),context_window: 100_000,max_tokens: 4_096,+ max_tokens_explicit: false,}}diff --git a/crates/pa-ai/src/models.rs b/crates/pa-ai/src/models.rsindex 828511e2dc..413dd94f3f 100644--- a/crates/pa-ai/src/models.rs+++ b/crates/pa-ai/src/models.rs@@ -79,6 +79,7 @@ mod tests {},context_window: 128_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/models_generated.rs b/crates/pa-ai/src/models_generated.rsindex d2fdafecc9..9f7b308a4b 100644--- a/crates/pa-ai/src/models_generated.rs+++ b/crates/pa-ai/src/models_generated.rs@@ -4436,6 +4436,7 @@ fn model_from_raw(raw: &RawModel) -> Model {},context_window: raw.context_window,max_tokens: raw.max_tokens,+ max_tokens_explicit: false,featured: raw.featured,headers,compat: raw.compat.as_ref().map(compat_from_raw),diff --git a/crates/pa-ai/src/prime_inference_differential_test.rs b/crates/pa-ai/src/prime_inference_differential_test.rsindex fae0149944..feb7d8bd83 100644--- a/crates/pa-ai/src/prime_inference_differential_test.rs+++ b/crates/pa-ai/src/prime_inference_differential_test.rs@@ -47,6 +47,7 @@ fn glm_53_flash(base_url: &str) -> Model {},context_window: 1_310_720,max_tokens: 131_072,+ max_tokens_explicit: false,featured: None,headers: None,compat: Some(crate::types::ModelCompat::from_kind(diff --git a/crates/pa-ai/src/providers/anthropic/mod.rs b/crates/pa-ai/src/providers/anthropic/mod.rsindex a1b745ae0f..1d622149dd 100644--- a/crates/pa-ai/src/providers/anthropic/mod.rs+++ b/crates/pa-ai/src/providers/anthropic/mod.rs@@ -609,6 +609,7 @@ mod subscription_identity_tests {cost: zero_model_cost(),context_window: 200_000,max_tokens: 32_000,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/bedrock/events.rs b/crates/pa-ai/src/providers/bedrock/events.rsindex 06a377e421..b491a13dd5 100644--- a/crates/pa-ai/src/providers/bedrock/events.rs+++ b/crates/pa-ai/src/providers/bedrock/events.rs@@ -444,6 +444,7 @@ mod tests {cost: zero_model_cost(),context_window: 200_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/bedrock/mod.rs b/crates/pa-ai/src/providers/bedrock/mod.rsindex cfd1f79c89..f2a1882fe8 100644--- a/crates/pa-ai/src/providers/bedrock/mod.rs+++ b/crates/pa-ai/src/providers/bedrock/mod.rs@@ -1038,6 +1038,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 200_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/faux/mod.rs b/crates/pa-ai/src/providers/faux/mod.rsindex 570be7aa6c..6533a6a5dc 100644--- a/crates/pa-ai/src/providers/faux/mod.rs+++ b/crates/pa-ai/src/providers/faux/mod.rs@@ -943,6 +943,7 @@ pub fn register_faux_provider(options: RegisterFauxProviderOptions) -> FauxProvicost: definition.cost.unwrap_or_else(zero_model_cost),context_window: definition.context_window.unwrap_or(128_000),max_tokens: definition.max_tokens.unwrap_or(16_384),+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/mistral/mod.rs b/crates/pa-ai/src/providers/mistral/mod.rsindex 75c98ef45f..94e2e256c3 100644--- a/crates/pa-ai/src/providers/mistral/mod.rs+++ b/crates/pa-ai/src/providers/mistral/mod.rs@@ -276,6 +276,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 128_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/mistral/stream.rs b/crates/pa-ai/src/providers/mistral/stream.rsindex 78d2e59b3d..4c85139491 100644--- a/crates/pa-ai/src/providers/mistral/stream.rs+++ b/crates/pa-ai/src/providers/mistral/stream.rs@@ -860,6 +860,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 128_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/openai_codex_responses/mod.rs b/crates/pa-ai/src/providers/openai_codex_responses/mod.rsindex f0f8281eb0..ec81d7e437 100644--- a/crates/pa-ai/src/providers/openai_codex_responses/mod.rs+++ b/crates/pa-ai/src/providers/openai_codex_responses/mod.rs@@ -908,6 +908,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 400_000,max_tokens: 128_000,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/openai_completions/convert.rs b/crates/pa-ai/src/providers/openai_completions/convert.rsindex 894a37dba7..22bd60a375 100644--- a/crates/pa-ai/src/providers/openai_completions/convert.rs+++ b/crates/pa-ai/src/providers/openai_completions/convert.rs@@ -553,6 +553,7 @@ mod tests {},context_window: 128_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/openai_completions/stream.rs b/crates/pa-ai/src/providers/openai_completions/stream.rsindex 3931165d4a..62134a3882 100644--- a/crates/pa-ai/src/providers/openai_completions/stream.rs+++ b/crates/pa-ai/src/providers/openai_completions/stream.rs@@ -780,6 +780,10 @@ mod tests {#[path = "stream_pins.rs"]mod stream_pins;+ // The #755 output-budget wire pins (the captured request bodies).+ #[path = "stream_max_tokens.rs"]+ mod stream_max_tokens;+// The wire-level pins (the request head on the wire) live in their// own child module with this file's test harness.#[path = "stream_wire.rs"]diff --git a/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_max_tokens.rs b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_max_tokens.rsnew file mode 100644index 0000000000..449ab26b83--- /dev/null+++ b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_max_tokens.rs@@ -0,0 +1,167 @@+//! The #755 output-budget wire pins: the request body's output budget+//! carries an explicitly configured `maxTokens` unchanged, a catalog+//! value stays capped at the default 32000 ceiling, and a model with no+//! declared max output sends no budget field at all (issue #755's+//! captured bodies; the TS fix PR's `max-tokens.test.ts` behavior, pinned+//! at the provider wire instead of the option assembly).++use super::*;+use std::sync::{Arc, Mutex};++/// The reporter's model (issue #755: a vLLM-served GLM configured in+/// models.json with `"maxTokens": 131072` and the OpenAI-completions+/// compat the captured bodies show). The `maxTokensExplicit` flag is what+/// the models.json parse attaches to a configured value.+fn glm_model(max_tokens: u64, explicit: bool) -> Value {+ json!({+ "id": "glm-5.2", "name": "GLM 5.2", "api": "openai-completions",+ "provider": "glm-h200", "reasoning": true, "input": ["text"],+ "cost": { "input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0 },+ "contextWindow": 393_216, "maxTokens": max_tokens,+ "compat": {+ "supportsDeveloperRole": false, "supportsReasoningEffort": false,+ "maxTokensField": "max_tokens", "thinkingFormat": "qwen-chat-template"+ },+ "maxTokensExplicit": explicit,+ })+}++/// Serve one SSE response body for the provider's POST, capturing the raw+/// request bytes it sent (the issue's logging-proxy capture, in-process).+async fn serve_sse_capturing(body: String) -> (SocketAddr, Arc<Mutex<Vec<u8>>>) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let captured: Arc<Mutex<Vec<u8>>> = Arc::new(Mutex::new(Vec::new()));+ let sink = Arc::clone(&captured);+ tokio::spawn(async move {+ let (mut socket, _) = listener.accept().await.unwrap();+ let mut request = Vec::new();+ let mut chunk = [0u8; 4096];+ let mut head_end = None;+ let mut content_length = 0usize;+ loop {+ let read = socket.read(&mut chunk).await.unwrap();+ if read == 0 {+ break;+ }+ request.extend_from_slice(&chunk[..read]);+ if head_end.is_none() {+ if let Some(pos) = request.windows(4).position(|w| w == b"\r\n\r\n") {+ head_end = Some(pos + 4);+ let head = String::from_utf8_lossy(&request[..pos]).to_lowercase();+ content_length = head+ .lines()+ .find_map(|line| {+ line.strip_prefix("content-length:")+ .and_then(|value| value.trim().parse().ok())+ })+ .unwrap_or(0);+ }+ }+ if let Some(end) = head_end {+ if request.len() >= end + content_length {+ break;+ }+ }+ }+ *sink.lock().unwrap() = request;+ let response = format!(+ "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",+ body.len()+ );+ socket.write_all(response.as_bytes()).await.unwrap();+ });+ (addr, captured)+}++/// One SSE body ending in the terminal marker, over `chunks`.+fn sse_body(chunks: &[Value]) -> String {+ use std::fmt::Write as _;+ let mut body = String::new();+ for chunk in chunks {+ let _ = write!(body, "data: {chunk}\n\n");+ }+ let _ = write!(body, "data: [DONE]\n\n");+ body+}++/// The captured POST body as JSON (the request head stripped).+fn request_body_json(request: &[u8]) -> Value {+ let text = String::from_utf8_lossy(request);+ let (_, body) = text+ .split_once("\r\n\r\n")+ .expect("the captured request carries its head");+ serde_json::from_str(body).expect("the captured request body is JSON")+}++/// Stream one minimal completion against `model` and return the JSON body+/// the provider put on the wire.+async fn wire_body_for(model: Value) -> Value {+ let body = sse_body(&[json!({+ "id": "m", "object": "chat.completion.chunk", "model": model["id"],+ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }],+ "usage": { "prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2 }+ })]);+ let (addr, captured) = serve_sse_capturing(body).await;+ let mut model = model;+ model["baseUrl"] = json!(format!("http://{addr}"));+ let model: Model = serde_json::from_value(model).unwrap();+ // The product path: the daemon's stream call goes through the SIMPLE+ // provider entry (`build_base_options` fills the per-model default+ // output budget there), so this is the request shape a real turn sends.+ let simple = crate::types::SimpleStreamOptions {+ base: crate::types::StreamOptions {+ api_key: Some("test".into()),+ ..Default::default()+ },+ ..Default::default()+ };+ let mut reader = crate::providers::openai_completions::stream_simple_openai_completions(+ &model,+ &Context {+ system_prompt: None,+ messages: vec![],+ tools: None,+ },+ Some(&simple),+ );+ loop {+ match reader.next_event().await.unwrap() {+ AssistantMessageEvent::Done { .. } => break,+ AssistantMessageEvent::Error { error, .. } => {+ panic!("stream failed: {:?}", error.error_message)+ }+ _ => {}+ }+ }+ let request = captured.lock().unwrap().clone();+ request_body_json(&request)+}++#[tokio::test]+async fn an_explicitly_configured_max_tokens_reaches_the_wire_unchanged() {+ // Issue #755's exact configuration: a models.json entry asking for+ // `"maxTokens": 131072`. The configured cap reaches the provider+ // unchanged — the captured body must not show the silent 32000.+ let body = wire_body_for(glm_model(131_072, true)).await;+ assert_eq!(body["max_tokens"], json!(131_072));+}++#[tokio::test]+async fn a_catalog_model_stays_capped_at_the_default_output_ceiling() {+ // The untouched default: a catalog model's declared maxTokens is a+ // ceiling the request clamps to 32000 (TS `DEFAULT_MAX_OUTPUT_TOKENS`)+ // — most catalog models declare far more than a turn needs, so their+ // request size must not change.+ let body = wire_body_for(glm_model(131_072, false)).await;+ assert_eq!(body["max_tokens"], json!(32_000));+}++#[tokio::test]+async fn a_model_without_max_tokens_sends_no_output_budget() {+ // A model that declares no max output (0) sends neither budget field:+ // the provider defaults server-side.+ let body = wire_body_for(glm_model(0, false)).await;+ assert!(body.get("max_tokens").is_none());+ assert!(body.get("max_completion_tokens").is_none());+}diff --git a/crates/pa-ai/src/providers/openai_responses_shared.rs b/crates/pa-ai/src/providers/openai_responses_shared.rsindex 74daa2d6f4..3359765a81 100644--- a/crates/pa-ai/src/providers/openai_responses_shared.rs+++ b/crates/pa-ai/src/providers/openai_responses_shared.rs@@ -412,6 +412,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 400_000,max_tokens: 128_000,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/providers/simple_options.rs b/crates/pa-ai/src/providers/simple_options.rsindex 0b1fc78318..08a4cd50df 100644--- a/crates/pa-ai/src/providers/simple_options.rs+++ b/crates/pa-ai/src/providers/simple_options.rs@@ -5,20 +5,29 @@ use crate::types::{Model, ModelThinkingLevel, SimpleStreamOptions, StreamOptions, ThinkingBudgets,};-/// The per-request output cap when the caller sets no `max_tokens` (TS-/// `buildBaseOptions`: `Math.min(model.maxTokens, 32000)`).+/// The default ceiling on requested output tokens (TS+/// `DEFAULT_MAX_OUTPUT_TOKENS`): most catalog models advertise a far larger+/// `maxTokens` than a turn needs, so requests are capped unless the value+/// was configured explicitly.pub const REQUEST_MAX_TOKENS_CAP: u64 = 32_000;/// The smallest output budget a request may keep after clamping (TS/// `adjustMaxTokensForThinking`: `minOutputTokens`).pub const MIN_OUTPUT_TOKENS: u64 = 1_024;-/// The default per-request output budget for a model (TS `buildBaseOptions`):-/// the model's max output capped at [`REQUEST_MAX_TOKENS_CAP`], or `None` when-/// the model declares no max output (providers that default server-side).+/// The default per-request output budget for a model (TS `resolveMaxTokens`):+/// an explicitly configured `maxTokens` passes through unchanged; a catalog+/// value is capped at [`REQUEST_MAX_TOKENS_CAP`]; `None` when the model+/// declares no max output (providers that default server-side).#[must_use]pub fn default_request_max_tokens(model: &Model) -> Option<u64> {- (model.max_tokens > 0).then(|| model.max_tokens.min(REQUEST_MAX_TOKENS_CAP))+ if model.max_tokens == 0 {+ return None;+ }+ if model.max_tokens_explicit {+ return Some(model.max_tokens);+ }+ Some(model.max_tokens.min(REQUEST_MAX_TOKENS_CAP))}pub fn build_base_options(@@ -102,7 +111,12 @@ pub fn adjust_max_tokens_for_thinking(}.unwrap_or(min_thinking_tokens);let mut thinking_budget = level_budget.max(min_thinking_tokens);- let max_tokens = (base_max_tokens + thinking_budget).min(model_max_tokens);+ // Saturating: an explicitly configured `maxTokens` may be any nonzero+ // u64, so the base + budget sum can reach the integer ceiling before+ // the model-max clamp ever runs.+ let max_tokens = base_max_tokens+ .saturating_add(thinking_budget)+ .min(model_max_tokens);if max_tokens <= min_thinking_tokens {return Err("Budget-based thinking requires at least 1024 thinking tokens plus room for the response"@@ -167,6 +181,108 @@ mod tests {.expect("test model")}+ fn explicit_model(api: &str, id: &str, max_tokens: u64) -> Model {+ serde_json::from_value(json!({+ "id": id, "name": id, "api": api, "provider": "p",+ "baseUrl": "http://localhost", "reasoning": true, "input": ["text"],+ "cost": {"input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0},+ "contextWindow": 200_000, "maxTokens": max_tokens,+ "maxTokensExplicit": true,+ }))+ .expect("test model")+ }++ #[test]+ fn a_catalog_model_is_capped_at_the_default_output_ceiling() {+ // TS resolveMaxTokens: a catalog value above the ceiling clamps to+ // 32000 — most catalog models advertise far more than a turn needs.+ let catalog = model("openai-completions", "gpt-x", 131_072);+ assert_eq!(default_request_max_tokens(&catalog), Some(32_000));+ assert_eq!(+ build_base_options(&catalog, None, None).max_tokens,+ Some(32_000)+ );+ }++ #[test]+ fn an_explicitly_configured_max_tokens_passes_through_unchanged() {+ // The #755 fix: a configured value bypasses the ceiling — the+ // reporter's models.json entry asking for 131072 arrives whole.+ let explicit = explicit_model("openai-completions", "glm-5.2", 131_072);+ assert_eq!(default_request_max_tokens(&explicit), Some(131_072));+ assert_eq!(+ build_base_options(&explicit, None, None).max_tokens,+ Some(131_072)+ );+ }++ #[test]+ fn an_explicit_model_below_the_ceiling_keeps_its_value() {+ // min semantics: an explicit 8000 stays 8000.+ let small = explicit_model("openai-completions", "glm-5.2", 8_000);+ assert_eq!(+ build_base_options(&small, None, None).max_tokens,+ Some(8_000)+ );+ }++ #[test]+ fn a_model_without_max_tokens_has_no_output_budget_even_when_flagged() {+ // maxTokens <= 0 sends no cap field (providers default server-side).+ let bare = model("openai-completions", "gpt-x", 0);+ assert_eq!(default_request_max_tokens(&bare), None);+ assert_eq!(build_base_options(&bare, None, None).max_tokens, None);+ let flagged = explicit_model("openai-completions", "glm-5.2", 0);+ assert_eq!(build_base_options(&flagged, None, None).max_tokens, None);+ }++ #[test]+ fn the_effective_budget_reserves_an_explicit_output_ceiling_too() {+ // The compaction threshold consumer (`effective_request_max_tokens`)+ // must reserve the LARGER explicit budget, or a request can claim+ // input + 131072 > contextWindow while the trigger says "not due".+ // The thinking fold still caps at the model's declared max output.+ let explicit = explicit_model("anthropic", "claude-sonnet-4-5", 131_072);+ assert_eq!(+ effective_request_max_tokens(&explicit, ModelThinkingLevel::Off),+ 131_072+ );+ assert_eq!(+ effective_request_max_tokens(&explicit, ModelThinkingLevel::High),+ 131_072+ );+ // The fold itself still caps at the model's declared max output:+ // an explicit base IS the model's max (the flag rides the same+ // value), so the thinking fold cannot exceed it.+ let roomy = explicit_model("anthropic", "claude-sonnet-4-5", 96_000);+ assert_eq!(+ effective_request_max_tokens(&roomy, ModelThinkingLevel::Medium),+ 96_000+ );+ }++ #[test]+ fn an_explicit_budget_at_the_integer_ceiling_never_overflows_the_fold() {+ // An explicitly configured maxTokens may be any nonzero u64, so the+ // thinking fold's base + budget addition must saturate before the+ // model-max clamp.+ let huge = explicit_model("anthropic", "claude-sonnet-4-5", u64::MAX);+ assert_eq!(+ effective_request_max_tokens(&huge, ModelThinkingLevel::High),+ u64::MAX+ );+ // The fold itself stays bounded at the model's declared max: the+ // wrapped sum (a few thousand) must never stand in for a huge one.+ let (max_tokens, _) = adjust_max_tokens_for_thinking(+ u64::MAX - 100,+ u64::MAX - 100,+ ModelThinkingLevel::High,+ None,+ )+ .unwrap();+ assert_eq!(max_tokens, u64::MAX - 100);+ }+#[test]fn budget_folding_providers_add_the_thinking_budget_on_top() {// A non-adaptive Anthropic model: `high` folds 16_384 thinking@@ -213,6 +329,26 @@ mod tests {);}+ #[test]+ fn a_per_request_max_tokens_wins_over_the_model_value_and_the_ceiling() {+ // TS `buildBaseOptions`: a per-request `options.maxTokens` keeps+ // precedence over both the model's declared value and the default+ // ceiling (the bypass #755's reporter observed, unchanged by the+ // explicit-flag fix).+ let openai = model("openai-completions", "gpt-x", 65_536);+ let options = SimpleStreamOptions {+ base: crate::types::StreamOptions {+ max_tokens: Some(64_000),+ ..Default::default()+ },+ ..Default::default()+ };+ assert_eq!(+ build_base_options(&openai, Some(&options), None).max_tokens,+ Some(64_000)+ );+ }+#[test]fn a_model_without_a_declared_max_output_has_no_budget_to_fold() {let bare = model("anthropic", "claude-sonnet-4-5", 0);diff --git a/crates/pa-ai/src/providers/transform_messages.rs b/crates/pa-ai/src/providers/transform_messages.rsindex 2a66c10b83..d99a9158e0 100644--- a/crates/pa-ai/src/providers/transform_messages.rs+++ b/crates/pa-ai/src/providers/transform_messages.rs@@ -307,6 +307,7 @@ mod tests {cost: crate::types::zero_model_cost(),context_window: 128_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-ai/src/stream.rs b/crates/pa-ai/src/stream.rsindex 9b72b3dd8f..a44959f3d1 100644--- a/crates/pa-ai/src/stream.rs+++ b/crates/pa-ai/src/stream.rs@@ -168,9 +168,10 @@ pub fn stream_simple(let provider = resolve_provider(&model.api)?;let mut options = options;// A `None` caller still gets the default output budget downstream- // (`build_base_options` fills `min(model.maxTokens, 32000)`), so- // materialize the options to clamp that default too. The materialized- // default builds the same request otherwise.+ // (`build_base_options` fills the per-model default: an explicit+ // `maxTokens` unchanged, a catalog value `min(model.maxTokens, 32000)`),+ // so materialize the options to clamp that default too. The+ // materialized default builds the same request otherwise.let simple = options.get_or_insert_with(SimpleStreamOptions::default);clamp_output_budget(model, context, Some(&mut simple.base));Ok(provider.stream_simple(model, context, options.as_ref()))diff --git a/crates/pa-cli/src/print_runtime.rs b/crates/pa-cli/src/print_runtime.rsindex 9fc625607c..efee2695c4 100644--- a/crates/pa-cli/src/print_runtime.rs+++ b/crates/pa-cli/src/print_runtime.rs@@ -1811,6 +1811,7 @@ mod tests {},context_window: 200_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-core/src/models/custom.rs b/crates/pa-core/src/models/custom.rsindex 54a498fe5b..e31bb74d2f 100644--- a/crates/pa-core/src/models/custom.rs+++ b/crates/pa-core/src/models/custom.rs@@ -341,6 +341,9 @@ pub fn apply_model_override(model: &Model, over: &ModelOverride) -> Model {}if let Some(max_tokens) = over.max_tokens {result.max_tokens = max_tokens;+ // An override-supplied `maxTokens` is configuration: it bypasses+ // the default output ceiling.+ result.max_tokens_explicit = true;}if let Some(cost) = &over.cost {let base = &result.cost;@@ -453,6 +456,9 @@ pub fn load_custom_models(),context_window: model_def.context_window.unwrap_or(128_000),max_tokens: model_def.max_tokens.unwrap_or(16_384),+ // A configured `maxTokens` is explicit; the 16_384+ // default is not, so a defaulted model stays capped.+ max_tokens_explicit: model_def.max_tokens.is_some(),featured: None,headers: None,compat,@@ -543,6 +549,75 @@ mod tests {);}+ /// TS `755-configured-max-tokens.test.ts`: a models.json `maxTokens`+ /// is explicit — the configured value reaches the provider unchanged+ /// instead of being clamped to the 32000 default ceiling.+ #[test]+ fn a_models_json_max_tokens_is_explicit() {+ let result = load_custom_models(+ r#"{ "providers": { "glm-h200": {+ "baseUrl": "http://vllm.example.test:8000/v1",+ "api": "openai-completions",+ "apiKey": "TEST_KEY",+ "models": [ { "id": "glm-5.2", "reasoning": true,+ "contextWindow": 393216, "maxTokens": 131072 } ]+ } } }"#,+ &|_| false,+ &|_| None,+ );+ assert!(result.error.is_none());+ let model = &result.models[0];+ assert_eq!(model.max_tokens, 131_072);+ assert!(model.max_tokens_explicit);+ }++ /// A custom model that omits `maxTokens` defaults to 16384 and stays+ /// catalog-like (capped): the flag marks a CONFIGURED value only.+ #[test]+ fn a_custom_model_without_max_tokens_stays_unmarked() {+ let result = load_custom_models(+ r#"{ "providers": { "ollama": {+ "baseUrl": "http://localhost:11434",+ "apiKey": "none",+ "api": "openai-completions",+ "models": [ { "id": "llama3" } ]+ } } }"#,+ &|_| false,+ &|_| None,+ );+ assert!(result.error.is_none());+ let model = &result.models[0];+ assert_eq!(model.max_tokens, 16_384);+ assert!(!model.max_tokens_explicit);+ }++ /// TS `applyModelOverride`: an override-supplied `maxTokens` is+ /// configuration too — the flag flips true so the value bypasses the+ /// ceiling (a per-model override of a built-in model is the #755+ /// shape with no custom provider involved).+ #[test]+ fn a_per_model_override_marks_max_tokens_explicit() {+ let base: Model = serde_json::from_value(serde_json::json!({+ "id": "claude-sonnet-4-5", "name": "Claude", "api": "anthropic",+ "provider": "anthropic", "baseUrl": "https://x", "reasoning": false,+ "input": [],+ "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },+ "contextWindow": 200_000, "maxTokens": 65_536+ }))+ .unwrap();+ assert!(!base.max_tokens_explicit);+ let over = ModelOverride {+ max_tokens: Some(200_000),+ ..Default::default()+ };+ let merged = apply_model_override(&base, &over);+ assert_eq!(merged.max_tokens, 200_000);+ assert!(merged.max_tokens_explicit);+ // An override that does not touch maxTokens leaves the flag alone.+ let untouched = apply_model_override(&base, &ModelOverride::default());+ assert!(!untouched.max_tokens_explicit);+ }+#[test]fn model_overrides_merge() {let base = serde_json::from_value(serde_json::json!({diff --git a/crates/pa-core/src/models/image_model_routing.rs b/crates/pa-core/src/models/image_model_routing.rsindex 6215c19dd6..a5e41c3539 100644--- a/crates/pa-core/src/models/image_model_routing.rs+++ b/crates/pa-core/src/models/image_model_routing.rs@@ -139,6 +139,7 @@ mod tests {},context_window: 200_000,max_tokens: 8192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-core/src/models/prime_inference.rs b/crates/pa-core/src/models/prime_inference.rsindex 0b91edf336..3687616926 100644--- a/crates/pa-core/src/models/prime_inference.rs+++ b/crates/pa-core/src/models/prime_inference.rs@@ -42,6 +42,7 @@ pub fn private_prime_inference_models() -> Vec<Model> {},context_window: 400_000,max_tokens: 131_072,+ max_tokens_explicit: false,featured: Some(true),compat: Some(ModelCompat::from_kind(CompatKind::OpenAiCompletions(Box::new(pa_types::ai::OpenAiCompletionsCompat {diff --git a/crates/pa-core/src/models/prime_inference_catalog.rs b/crates/pa-core/src/models/prime_inference_catalog.rsindex e7554ac391..191bdfc2f9 100644--- a/crates/pa-core/src/models/prime_inference_catalog.rs+++ b/crates/pa-core/src/models/prime_inference_catalog.rs@@ -298,6 +298,9 @@ pub fn build_prime_inference_models_with_minimum(},context_window,max_tokens,+ // Catalog chain models stay capped: only explicit+ // configuration flips the flag.+ max_tokens_explicit: false,featured: template.and_then(|t| t.featured),headers: None,compat: Some(compat),diff --git a/crates/pa-core/src/models/registry/tests.rs b/crates/pa-core/src/models/registry/tests.rsindex 5b79263d33..6e551f6365 100644--- a/crates/pa-core/src/models/registry/tests.rs+++ b/crates/pa-core/src/models/registry/tests.rs@@ -40,6 +40,20 @@ fn in_memory_loads_built_in_catalog() {.any(|m| m.id == "internal/glm-5.2-fast"));}+/// TS `755-configured-max-tokens.test.ts`: built-in catalog models stay+/// unmarked when no override configures `maxTokens` — the default 32000+/// ceiling keeps applying to them (901 of the catalog's models declare+/// more than 32000 and their request size must not change).+#[test]+fn built_in_catalog_models_stay_unmarked() {+ let registry = ModelRegistry::in_memory(auth_with(&serde_json::json!({})));+ assert!(!registry.get_all().is_empty());+ assert!(registry+ .get_all()+ .iter()+ .all(|model| !model.max_tokens_explicit));+}+#[test]fn available_filters_by_configured_auth() {let auth = auth_with(&serde_json::json!({diff --git a/crates/pa-core/src/refinement/executor.rs b/crates/pa-core/src/refinement/executor.rsindex 95504dabd4..79f306fdec 100644--- a/crates/pa-core/src/refinement/executor.rs+++ b/crates/pa-core/src/refinement/executor.rs@@ -655,6 +655,7 @@ mod tests {},context_window: 100_000,max_tokens: 8_000,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-core/src/session_engine/compaction.rs b/crates/pa-core/src/session_engine/compaction.rsindex 5d5c430b5e..9daca652a5 100644--- a/crates/pa-core/src/session_engine/compaction.rs+++ b/crates/pa-core/src/session_engine/compaction.rs@@ -194,13 +194,14 @@ pub fn should_compact(}/// The effective requested output budget of the session's next model call:-/// the per-request default `min(model.maxTokens, 32000)`, plus the thinking-/// budget budget-folding providers (Anthropic/Bedrock models without-/// adaptive thinking) add on top of it for the session's reasoning level,-/// capped at the model's declared max output; 0 when the model declares no-/// max output. The combined input+output ceiling reserves what the request-/// will actually claim, or a budget-folded request can overflow while the-/// trigger still says "not due".+/// the per-request default output budget (an explicitly configured+/// `maxTokens` unchanged; a catalog value `min(model.maxTokens, 32000)`),+/// plus the thinking budget budget-folding providers (Anthropic/Bedrock+/// models without adaptive thinking) add on top of it for the session's+/// reasoning level, capped at the model's declared max output; 0 when the+/// model declares no max output. The combined input+output ceiling reserves+/// what the request will actually claim, or a budget-folded request can+/// overflow while the trigger still says "not due".#[must_use]pub fn request_output_budget(model: &pa_types::ai::Model,diff --git a/crates/pa-core/src/session_engine/engine/tests.rs b/crates/pa-core/src/session_engine/engine/tests.rsindex ab94a8a112..76b9dcdaa1 100644--- a/crates/pa-core/src/session_engine/engine/tests.rs+++ b/crates/pa-core/src/session_engine/engine/tests.rs@@ -42,6 +42,7 @@ async fn engine_runs_tool_loop_and_persists() {cost: pa_agent::types::UsageCost::default(),context_window: 1_000,max_tokens: 100,+ max_tokens_explicit: false,};let provider = Arc::new(ScriptedProvider::new(model.clone()));// First turn: call the tool. Second turn: final text.@@ -150,6 +151,7 @@ async fn spawned_child_prompt_stamps_its_depth() {cost: pa_agent::types::UsageCost::default(),context_window: 1_000,max_tokens: 100,+ max_tokens_explicit: false,};let provider = Arc::new(ScriptedProvider::new(model.clone()));let tmp = tempfile::tempdir().unwrap();@@ -215,6 +217,7 @@ async fn oauth_creds_unlock_generic_mcp_gating_in_new_sessions() {cost: pa_agent::types::UsageCost::default(),context_window: 1_000,max_tokens: 100,+ max_tokens_explicit: false,}}diff --git a/crates/pa-core/src/session_engine/factory_host.rs b/crates/pa-core/src/session_engine/factory_host.rsindex c3e12f0fd1..e0f37aa390 100644--- a/crates/pa-core/src/session_engine/factory_host.rs+++ b/crates/pa-core/src/session_engine/factory_host.rs@@ -334,6 +334,7 @@ fn agent_model_to_ai_model(model: &pa_agent::types::Model) -> AiModel {},context_window: model.context_window,max_tokens: model.max_tokens,+ max_tokens_explicit: model.max_tokens_explicit,featured: None,headers: None,compat: None,diff --git a/crates/pa-core/src/session_engine/refine.rs b/crates/pa-core/src/session_engine/refine.rsindex a2954251d3..907a91c8b4 100644--- a/crates/pa-core/src/session_engine/refine.rs+++ b/crates/pa-core/src/session_engine/refine.rs@@ -734,6 +734,7 @@ mod tests {},context_window: 100_000,max_tokens: 8_000,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-core/src/session_engine/request_timing/payload/tests.rs b/crates/pa-core/src/session_engine/request_timing/payload/tests.rsindex 6701fc1698..58441dc8f2 100644--- a/crates/pa-core/src/session_engine/request_timing/payload/tests.rs+++ b/crates/pa-core/src/session_engine/request_timing/payload/tests.rs@@ -85,6 +85,7 @@ fn agent_model() -> pa_agent::types::Model {cost: pa_agent::types::UsageCost::default(),context_window: 1_000_000,max_tokens: 128_000,+ max_tokens_explicit: false,}}diff --git a/crates/pa-core/src/session_engine/request_timing/tests.rs b/crates/pa-core/src/session_engine/request_timing/tests.rsindex a5c0be3ea2..ca89d48b3c 100644--- a/crates/pa-core/src/session_engine/request_timing/tests.rs+++ b/crates/pa-core/src/session_engine/request_timing/tests.rs@@ -25,6 +25,7 @@ fn test_model() -> pa_agent::types::Model {cost: UsageCost::default(),context_window: 1_000_000,max_tokens: 128_000,+ max_tokens_explicit: false,}}diff --git a/crates/pa-core/src/session_engine/turn_boundary/tests.rs b/crates/pa-core/src/session_engine/turn_boundary/tests.rsindex 7034583402..aca5f59111 100644--- a/crates/pa-core/src/session_engine/turn_boundary/tests.rs+++ b/crates/pa-core/src/session_engine/turn_boundary/tests.rs@@ -39,6 +39,7 @@ fn agent_model() -> pa_agent::types::Model {cost: pa_agent::types::UsageCost::default(),context_window: 100_000,max_tokens: 1_000,+ max_tokens_explicit: false,}}diff --git a/crates/pa-daemon/src/acp/config_options.rs b/crates/pa-daemon/src/acp/config_options.rsindex 0cb2ca65c6..07823fa1f6 100644--- a/crates/pa-daemon/src/acp/config_options.rs+++ b/crates/pa-daemon/src/acp/config_options.rs@@ -219,6 +219,7 @@ mod tests {},context_window: 128_000,max_tokens: 4_096,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-models/src/pinning.rs b/crates/pa-models/src/pinning.rsindex 66b96c042a..2aec163c23 100644--- a/crates/pa-models/src/pinning.rs+++ b/crates/pa-models/src/pinning.rs@@ -136,6 +136,7 @@ mod tests {cost: pa_ai::types::zero_model_cost(),context_window: 1,max_tokens: 1,+ max_tokens_explicit: false,featured: None,headers,compat: None,diff --git a/crates/pa-models/src/prime_inference.rs b/crates/pa-models/src/prime_inference.rsindex a2c84406fd..543bb5df70 100644--- a/crates/pa-models/src/prime_inference.rs+++ b/crates/pa-models/src/prime_inference.rs@@ -555,6 +555,9 @@ pub fn build_prime_inference_models(},context_window,max_tokens,+ // Catalog chain models (the live Prime Inference snapshot)+ // stay capped: only explicit configuration flips the flag.+ max_tokens_explicit: false,featured: template.and_then(|t| t.featured),headers: None,compat: Some(compat),@@ -1062,6 +1065,7 @@ mod tests {},context_window: 100_000,max_tokens: 10_000,+ max_tokens_explicit: false,featured: Some(true),headers: None,compat: Some(ModelCompat::from_kind(CompatKind::OpenAiCompletions(diff --git a/crates/pa-models/src/schema.rs b/crates/pa-models/src/schema.rsindex 018878b66e..9811052fde 100644--- a/crates/pa-models/src/schema.rs+++ b/crates/pa-models/src/schema.rs@@ -169,6 +169,7 @@ fn parse_entry(candidate: &serde_json::Value) -> Result<Model, String> {},context_window: entry.context_window,max_tokens: entry.max_tokens,+ max_tokens_explicit: false,featured: entry.featured,headers: None,compat: entry.compat.map(|raw| ModelCompat { raw }),diff --git a/crates/pa-types/src/ai/mod.rs b/crates/pa-types/src/ai/mod.rsindex bbf68de8f6..ac907ff35a 100644--- a/crates/pa-types/src/ai/mod.rs+++ b/crates/pa-types/src/ai/mod.rs@@ -751,6 +751,14 @@ pub use routing::{DataCollection, NumOrString, OpenRouterMaxPrice, OpenRouterRouting, OpenRouterSort,OpenRouterThreshold, VercelGatewayRouting,};+/// `skip_serializing_if` predicate for [`Model::max_tokens_explicit`]: the+/// wire/catalog JSON stays byte-identical for catalog models (the flag+/// serializes only when set).+#[allow(clippy::trivially_copy_pass_by_ref)] // serde's skip predicate ABI takes the field by reference+fn is_false(value: &bool) -> bool {+ !*value+}+/// Unified model descriptor for the model registry.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -770,6 +778,12 @@ pub struct Model {pub context_window: u64,#[serde(rename = "maxTokens")]pub max_tokens: u64,+ /// Set when `maxTokens` came from explicit configuration rather than the+ /// model catalog (a models.json entry, a per-model override). An explicit+ /// value bypasses the 32 000 default output ceiling so a configured cap+ /// reaches the provider unchanged; catalog values stay capped.+ #[serde(default, skip_serializing_if = "is_false")]+ pub max_tokens_explicit: bool,/// Flagship model surfaced above non-featured models of the same provider.#[serde(default, skip_serializing_if = "Option::is_none")]pub featured: Option<bool>,diff --git a/crates/pa-types/src/ai/tests.rs b/crates/pa-types/src/ai/tests.rsindex bf275968e1..2166cb18a8 100644--- a/crates/pa-types/src/ai/tests.rs+++ b/crates/pa-types/src/ai/tests.rs@@ -23,6 +23,7 @@ fn tier_model(provider: &str, api: &str, id: &str) -> Model {cost: zero_cost(),context_window: 0,max_tokens: 0,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,diff --git a/crates/pa-types/src/ai/thinking_levels.rs b/crates/pa-types/src/ai/thinking_levels.rsindex 0b28d5a919..3a6846908c 100644--- a/crates/pa-types/src/ai/thinking_levels.rs+++ b/crates/pa-types/src/ai/thinking_levels.rs@@ -155,6 +155,7 @@ mod tests {},context_window: 128_000,max_tokens: 8_192,+ max_tokens_explicit: false,featured: None,headers: None,compat: None,