Craft Anything: understand how any software works, and craft your own.
Rust
Honor per-backend conversation context budgets (#559)
Afloatc4e3d79dda4d
diff --git a/crates/ai/src/agent.rs b/crates/ai/src/agent.rsindex f846d32e..f9a45d9b 100644--- a/crates/ai/src/agent.rs+++ b/crates/ai/src/agent.rs@@ -242,6 +242,8 @@ pub struct ModelSlot {pub local: bool,pub effort: Option<Effort>,pub max_turns: u32,+ /// The backend's conversation budget; zero uses the local/cloud default.+ pub context_tokens: u64,}/// Settings for one conversation.@@ -251,8 +253,8 @@ pub struct LoopConfig {pub prices: BTreeMap<String, crate::config::Price>,/// Keep the conversation in this file after every step, and continue it when it's there.pub transcript: Option<std::path::PathBuf>,- /// Input tokens the conversation may grow to before it's trimmed; 0 = by model (local or- /// cloud, see [`crate::context`]).+ /// Override the input tokens the conversation may grow to before it's trimmed. Zero uses+ /// the active backend's budget, or its local/cloud default (see [`crate::context`]).pub context_tokens: u64,}@@ -272,6 +274,8 @@ pub struct AgentLoop {pub meter: Meter,/// The last turn's real input size (tokens), 0 before the first or after making room.last_input: u64,+ /// Estimated history size sent with that turn, before its reply and tool results were added.+ last_history_estimate: u64,}impl AgentLoop {@@ -328,15 +332,9 @@ impl AgentLoop {turns += 1;let tools = self.tool_defs();let system = self.system.clone().unwrap_or_default();- if let Some((usage, cost)) = self.fit_context(&system) {- msg_usage.add(usage);- msg_cost = match (msg_cost, cost) {- (Some(a), Some(b)) => Some(a + b),- _ => None,- };- }- let Some(result) = self.one_turn(&system, &tools, effort) else { break };+ let Some(result) = self.one_turn(&system, &tools, effort, &mut msg_usage, &mut msg_cost) else { break };self.last_input = result.usage.input_tokens + result.usage.cache_read_tokens + result.usage.cache_write_tokens;+ self.last_history_estimate = context::estimate_tokens(&self.history).max(1);let (slot_name, local, model_id) = match self.chain.get(self.current) {Some(s) => (s.name.clone(), s.local, result.model.clone()),None => break,@@ -443,8 +441,10 @@ impl AgentLoop {/// Input tokens the conversation may take before room is made.fn context_budget(&self) -> u64 {- match self.cfg.context_tokens {- 0 if self.chain.get(self.current).is_some_and(|s| s.local) => context::LOCAL_CONTEXT_TOKENS,+ let slot = self.chain.get(self.current);+ let configured = if self.cfg.context_tokens == 0 { slot.map(|s| s.context_tokens).unwrap_or(0) } else { self.cfg.context_tokens };+ match configured {+ 0 if slot.is_some_and(|s| s.local) => context::LOCAL_CONTEXT_TOKENS,0 => context::CLOUD_CONTEXT_TOKENS,n => n,}@@ -456,17 +456,21 @@ impl AgentLoop {fn fit_context(&mut self, system: &str) -> Option<(Usage, Option<f64>)> {let budget = self.context_budget();let estimate = context::estimate_tokens(&self.history).max(1);- let size = if self.last_input > 0 { self.last_input } else { estimate };+ // Reported input includes prompt/tool overhead. Add the history accumulated since it+ // was measured; comparing only with the current estimate can miss that growth.+ let size = if self.last_input > 0 { self.last_input.saturating_add(estimate.saturating_sub(self.last_history_estimate)) } else { estimate };if size <= budget {return None;}- // Real tokens per estimated token, to judge the trimmed size before the next turn.+ // Use the same approximate scale to judge the trimmed history before the next turn.let scale = size as f64 / estimate as f64;let trimmed = context::trim_old(&mut self.history);let after = (context::estimate_tokens(&self.history) as f64 * scale) as u64;self.last_input = 0;+ self.last_history_estimate = 0;self.host.journal("context", json!({"action": "trim", "blocks": trimmed, "tokens_before": size, "tokens_after": after, "budget": budget}));- if trimmed > 0 && after <= budget * 3 / 4 {+ // floor(3 * budget / 4), without overflowing for a large configured budget.+ if trimmed > 0 && after <= budget - budget.div_ceil(4) {return None;}let cut = context::cut_point(&self.history)?;@@ -513,8 +517,23 @@ impl AgentLoop {}/// One model call, falling back along the chain when a backend fails before producing output.- fn one_turn(&mut self, system: &str, tools: &[ToolDef], effort: Effort) -> Option<crate::model::TurnResult> {+ fn one_turn(+ &mut self,+ system: &str,+ tools: &[ToolDef],+ effort: Effort,+ msg_usage: &mut Usage,+ msg_cost: &mut Option<f64>,+ ) -> Option<crate::model::TurnResult> {loop {+ // A fallback can have a smaller window than the backend that just failed.+ if let Some((usage, cost)) = self.fit_context(system) {+ msg_usage.add(usage);+ *msg_cost = match (*msg_cost, cost) {+ (Some(a), Some(b)) => Some(a + b),+ _ => None,+ };+ }let events = self.events.clone();let mut produced = false;let stop = self.stop.clone();@@ -709,6 +728,7 @@ impl ApiConversation {cancel: cancel.clone(),meter: Meter::default(),last_input: 0,+ last_history_estimate: 0,};let busy2 = busy.clone();std::thread::Builder::new()@@ -887,11 +907,14 @@ pub(crate) mod tests {_ => None,}}- fn call(&self, id: &str, _input: Value, consent: bool, _c: CancelToken) -> Result<ToolOutput, ToolError> {+ fn call(&self, id: &str, input: Value, consent: bool, _c: CancelToken) -> Result<ToolOutput, ToolError> {self.calls.lock().unwrap().push((id.to_string(), consent));if id == "danger" && !consent {return Err(ToolError::new(ErrorCode::ConsentRequired, "needs your OK"));}+ if id == "look" && input.get("large").and_then(Value::as_bool) == Some(true) {+ return Ok(ToolOutput::Value(json!({"content": "n".repeat(8000)})));+ }Ok(ToolOutput::Value(json!({"ran": id})))}fn journal(&self, kind: &str, entry: Value) {@@ -946,7 +969,7 @@ pub(crate) mod tests {]),seen: seen.clone(),};- let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10 };+ let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10, context_tokens: 0 };let mut c = ApiConversation::start(host.clone(), vec![slot], LoopConfig { beginner: true, ..LoopConfig::default() }).unwrap();c.send("How does it work?");assert!(c.is_busy());@@ -995,7 +1018,7 @@ pub(crate) mod tests {turns: VecDeque::from([look("a"), look("b"), Ok(summary), turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn)]),seen: seen.clone(),};- let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10 };+ let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10, context_tokens: 0 };// Ordinary turns report 10 input tokens, over this budget, so room is made before the third.let cfg = || LoopConfig {transcript: Some(path.clone()),@@ -1038,7 +1061,7 @@ pub(crate) mod tests {// A new conversation with the same file continues it.let seen2 = Arc::new(Mutex::new(Vec::new()));let script = Scripted { turns: VecDeque::from([turn(vec![Block::Text { text: "blue now".into() }], StopReason::EndTurn)]), seen: seen2.clone() };- let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10 };+ let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local: false, effort: None, max_turns: 10, context_tokens: 0 };let mut c = ApiConversation::start(host, vec![slot], LoopConfig { transcript: Some(path.clone()), ..LoopConfig::default() }).unwrap();assert!(c.resumed());c.send("Make it blue");@@ -1065,7 +1088,7 @@ pub(crate) mod tests {turns: VecDeque::from([look("a"), look("b"), summary, turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn)]),seen: seen.clone(),};- let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local, effort: None, max_turns: 10 };+ let slot = ModelSlot { name: "Fake".into(), model: Box::new(script), local, effort: None, max_turns: 10, context_tokens: 0 };let mut c = ApiConversation::start(host.clone(), vec![slot], LoopConfig { context_tokens: 5, ..LoopConfig::default() }).unwrap();c.send("Build it");let events = drain_until_done(&mut c, |_, _| {});@@ -1084,6 +1107,192 @@ pub(crate) mod tests {}}+ #[test]+ fn a_large_backend_budget_can_trim_without_overflow() {+ let budget = i64::MAX as u64;+ let dir = tempfile::tempdir().unwrap();+ let transcript = dir.path().join("transcript.json");+ let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });+ let seen = Arc::new(Mutex::new(Vec::new()));+ let mut history = vec![+ Msg::user_text("Build it"),+ Msg { role: Speaker::Assistant, blocks: vec![Block::ToolUse { id: "old".into(), name: "look".into(), input: json!({}) }] },+ Msg { role: Speaker::User, blocks: vec![Block::ToolResult { tool_use_id: "old".into(), content: "x".repeat(1000), is_error: false }] },+ ];+ for _ in 0..context::KEEP_RECENT / 2 {+ history.push(Msg { role: Speaker::Assistant, blocks: vec![Block::Text { text: "checked".into() }] });+ history.push(Msg::user_text("continue"));+ }+ context::save(&transcript, &history).unwrap();+ let mut first = turn(vec![Block::ToolUse { id: "new".into(), name: "look".into(), input: json!({}) }], StopReason::ToolUse).unwrap();+ first.usage.input_tokens = budget + 1;+ let script = Scripted { turns: VecDeque::from([Ok(first), turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn)]), seen: seen.clone() };+ let slot = ModelSlot { name: "Large".into(), model: Box::new(script), local: false, effort: None, max_turns: 5, context_tokens: budget };+ let mut conversation = ApiConversation::start(host.clone(), vec![slot], LoopConfig { transcript: Some(transcript), ..Default::default() }).unwrap();+ assert!(conversation.resumed());+ conversation.send("continue");+ let events = drain_until_done(&mut conversation, |event, _| {+ assert!(!matches!(event, AgentEvent::Error { .. }), "{event:?}");+ });+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 2, "trimming made enough room without a summary call");+ assert!(matches!(&seen[1][2].blocks[0], Block::ToolResult { tool_use_id, content, .. } if tool_use_id == "old" && content.len() < 1000));+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "done")), "{events:?}");+ let journal = host.journal.lock().unwrap();+ assert!(journal.iter().any(|(kind, entry)| kind == "context" && entry["budget"] == budget && entry["blocks"] == 1));+ }++ #[test]+ fn backend_context_budgets_and_conversation_overrides() {+ for (backend_budget, override_budget, local, summarises) in [+ (5, 0, false, true),+ (5, 0, true, true),+ (0, 5, false, true),+ (100, 5, false, true),+ (5, 100, false, false),+ (0, 0, false, false),+ (0, 0, true, false),+ ] {+ let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });+ let seen = Arc::new(Mutex::new(Vec::new()));+ let look = |id: &str| turn(vec![Block::ToolUse { id: id.into(), name: "look".into(), input: json!({}) }], StopReason::ToolUse);+ let mut turns = VecDeque::from([look("a"), look("b")]);+ if summarises {+ turns.push_back(turn(vec![Block::Text { text: "Earlier work kept.".into() }], StopReason::EndTurn));+ }+ turns.push_back(turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn));+ let slot = ModelSlot {+ name: "Configured".into(),+ model: Box::new(Scripted { turns, seen: seen.clone() }),+ local,+ effort: None,+ max_turns: 5,+ context_tokens: backend_budget,+ };+ let mut conversation = ApiConversation::start(host, vec![slot], LoopConfig { context_tokens: override_budget, ..Default::default() }).unwrap();+ conversation.send("Build it");+ let events = drain_until_done(&mut conversation, |_, _| {});+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), if summarises { 4 } else { 3 }, "backend {backend_budget}, override {override_budget}, local {local}");+ if summarises {+ assert!(seen[2].last().unwrap().text().contains("summary of the work so far"));+ assert!(seen[3][0].text().contains("Earlier work kept."));+ }+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "done")), "{events:?}");+ assert!(matches!(events.last(), Some(AgentEvent::TurnDone { input_tokens, .. }) if *input_tokens == if summarises { 40 } else { 30 }));+ }+ }++ #[test]+ fn fallback_refits_context_to_its_own_budget_and_accounts_for_the_summary() {+ let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });+ let seen = Arc::new(Mutex::new(Vec::new()));+ let look = |id: &str| turn(vec![Block::ToolUse { id: id.into(), name: "look".into(), input: json!({}) }], StopReason::ToolUse);+ let first = Scripted {+ turns: VecDeque::from([look("a"), look("b"), Err(ToolError::new(ErrorCode::EngineMissing, "temporarily unavailable"))]),+ seen: Arc::default(),+ };+ let fallback = Scripted {+ turns: VecDeque::from([+ turn(vec![Block::Text { text: "Earlier work kept.".into() }], StopReason::EndTurn),+ turn(vec![Block::Text { text: "done".into() }], StopReason::EndTurn),+ ]),+ seen: seen.clone(),+ };+ let chain = vec![+ ModelSlot { name: "Large".into(), model: Box::new(first), local: false, effort: None, max_turns: 5, context_tokens: 100 },+ ModelSlot { name: "Small".into(), model: Box::new(fallback), local: false, effort: None, max_turns: 5, context_tokens: 5 },+ ];+ let mut conversation = ApiConversation::start(host.clone(), chain, LoopConfig::default()).unwrap();+ conversation.send("Build it");+ let events = drain_until_done(&mut conversation, |_, _| {});+ let seen = seen.lock().unwrap();+ assert_eq!(seen.len(), 2, "the fallback summarises before answering");+ assert!(seen[0].last().unwrap().text().contains("summary of the work so far"));+ assert!(seen[1][0].text().contains("Earlier work kept."));+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "done")), "{events:?}");+ assert!(matches!(events.last(), Some(AgentEvent::TurnDone { input_tokens: 40, output_tokens: 20, backend, .. }) if backend == "Small"));+ let journal = host.journal.lock().unwrap();+ assert!(journal.iter().any(|(kind, entry)| kind == "context" && entry["budget"] == 5));+ assert!(journal.iter().any(|(kind, entry)| kind == "model_turn" && entry["purpose"] == "context_summary" && entry["backend"] == "Small"));+ }++ #[test]+ fn fallback_budget_counts_new_results_since_the_last_request() {+ let last_input = 10_000;+ let budget = 11_000;+ let dir = tempfile::tempdir().unwrap();+ let transcript = dir.path().join("transcript.json");+ let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });+ let mut history = vec![+ Msg::user_text("Build it"),+ Msg { role: Speaker::Assistant, blocks: vec![Block::ToolUse { id: "old".into(), name: "look".into(), input: json!({}) }] },+ Msg { role: Speaker::User, blocks: vec![Block::ToolResult { tool_use_id: "old".into(), content: "x".repeat(8000), is_error: false }] },+ ];+ for _ in 0..context::KEEP_RECENT / 2 {+ history.push(Msg { role: Speaker::Assistant, blocks: vec![Block::Text { text: "checked".into() }] });+ history.push(Msg::user_text("continue"));+ }+ context::save(&transcript, &history).unwrap();+ let mut first = turn(vec![Block::ToolUse { id: "new".into(), name: "look".into(), input: json!({"large": true}) }], StopReason::ToolUse).unwrap();+ first.usage.input_tokens = last_input;+ let primary_seen = Arc::new(Mutex::new(Vec::new()));+ let primary = Scripted {+ turns: VecDeque::from([Ok(first), Err(ToolError::new(ErrorCode::EngineMissing, "temporarily unavailable"))]),+ seen: primary_seen.clone(),+ };+ let answer = |text: &str| {+ let mut result = turn(vec![Block::Text { text: text.into() }], StopReason::EndTurn).unwrap();+ result.usage.input_tokens = last_input;+ Ok(result)+ };+ let fallback_seen = Arc::new(Mutex::new(Vec::new()));+ let fallback = Scripted { turns: VecDeque::from([answer("done"), answer("next done")]), seen: fallback_seen.clone() };+ let chain = vec![+ ModelSlot { name: "Large".into(), model: Box::new(primary), local: false, effort: None, max_turns: 5, context_tokens: 30_000 },+ ModelSlot { name: "Small".into(), model: Box::new(fallback), local: false, effort: None, max_turns: 5, context_tokens: budget },+ ];+ let mut conversation = ApiConversation::start(host.clone(), chain, LoopConfig { transcript: Some(transcript), ..Default::default() }).unwrap();+ conversation.send("continue");+ let events = drain_until_done(&mut conversation, |event, _| assert!(!matches!(event, AgentEvent::Error { .. }), "{event:?}"));+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "done")));+ {+ let seen = primary_seen.lock().unwrap();+ assert_eq!(seen.len(), 2);+ let before = context::estimate_tokens(&seen[0]);+ let grown = context::estimate_tokens(&seen[1]);+ assert!(grown < last_input && last_input < budget, "max(last_input, estimate) would still miss the growth");+ assert!(grown - before > budget - last_input, "the new result crosses the remaining budget");+ }+ let result_len = |history: &[Msg], id: &str| {+ history+ .iter()+ .flat_map(|message| &message.blocks)+ .find_map(|block| match block {+ Block::ToolResult { tool_use_id, content, .. } if tool_use_id == id => Some(content.len()),+ _ => None,+ })+ .unwrap()+ };+ {+ let seen = fallback_seen.lock().unwrap();+ assert_eq!(seen.len(), 1, "trimming makes room without a summary request");+ assert!(result_len(&seen[0], "old") < 8000, "the fallback must trim after new tool output grows the history");+ assert!(result_len(&seen[0], "new") >= 8000, "the latest tool result stays complete");+ }+ // The successful fallback records the history it actually received. A short follow-up+ // must not count the already-sent tool result as new growth and summarise it again.+ conversation.send("again");+ let events = drain_until_done(&mut conversation, |event, _| assert!(!matches!(event, AgentEvent::Error { .. }), "{event:?}"));+ assert!(events.iter().any(|event| matches!(event, AgentEvent::TextDelta { text } if text == "next done")));+ assert_eq!(fallback_seen.lock().unwrap().len(), 2);+ let journal = host.journal.lock().unwrap();+ let trims: Vec<_> = journal.iter().filter(|(kind, entry)| kind == "context" && entry["action"] == "trim").collect();+ assert_eq!(trims.len(), 1, "the short follow-up does not compact the same growth twice");+ assert_eq!(trims[0].1["budget"], budget);+ assert!(trims[0].1["tokens_before"].as_u64().unwrap() > budget);+ }+#[test]fn fallback_chain_and_refusal() {let host = Arc::new(FakeHost { calls: Mutex::default(), journal: Mutex::default() });@@ -1093,8 +1302,8 @@ pub(crate) mod tests {seen: Arc::default(),};let chain = vec![- ModelSlot { name: "A".into(), model: Box::new(failing), local: false, effort: None, max_turns: 5 },- ModelSlot { name: "B".into(), model: Box::new(refusing), local: true, effort: None, max_turns: 5 },+ ModelSlot { name: "A".into(), model: Box::new(failing), local: false, effort: None, max_turns: 5, context_tokens: 0 },+ ModelSlot { name: "B".into(), model: Box::new(refusing), local: true, effort: None, max_turns: 5, context_tokens: 0 },];let mut c = ApiConversation::start(host, chain, LoopConfig::default()).unwrap();c.send("q");diff --git a/crates/ai/src/config.rs b/crates/ai/src/config.rsindex e0d9065c..c6d73f98 100644--- a/crates/ai/src/config.rs+++ b/crates/ai/src/config.rs@@ -9,6 +9,8 @@//! kind = "anthropic"//! model = "claude-opus-5-5"//! effort = "high"+//! # Conversation trimming budget; does not set the server's context window.+//! context_tokens = 120000//!//! [ai.roles]//! lead = "Claude"@@ -43,6 +45,10 @@ pub struct BackendOptions {/// Most model turns per user message.#[serde(skip_serializing_if = "Option::is_none")]pub max_turns: Option<u32>,+ /// Input tokens before trimming and summarising the conversation. Omitted or zero uses the+ /// local/cloud default; this does not change the model server's own context window.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub context_tokens: Option<u64>,/// Agent CLIs: the program to run instead of the default for `model`.#[serde(skip_serializing_if = "Option::is_none")]pub command: Option<String>,@@ -248,6 +254,7 @@ mod tests {let mut a = entry("Claude", BackendKind::Anthropic);a.options.effort = Some(Effort::High);a.options.fallbacks_enabled = Some(false);+ a.options.context_tokens = Some(120_000);c.upsert(a);c.upsert(entry("Local", BackendKind::OpenaiCompatible));c.roles.insert("reviewer".into(), "Local".into());@@ -260,6 +267,27 @@ mod tests {assert_eq!(back, c);assert!(text.contains("[[ai.backends]]"), "{text}");assert!(text.contains("effort = \"high\""), "{text}");+ assert!(text.contains("context_tokens = 120000"), "{text}");+ }++ #[test]+ fn backend_context_budget_is_optional_and_validated() {+ let table = |line: &str| -> toml::Table {+ toml::from_str(&format!("[[backends]]\nname = \"Local\"\nkind = \"openai_compatible\"\nmodel = \"qwen3:8b\"\n{line}")).unwrap()+ };+ for (line, expected) in [+ ("", None),+ ("context_tokens = 0", Some(0)),+ ("context_tokens = 8000", Some(8000)),+ ("context_tokens = 9223372036854775807", Some(i64::MAX as u64)),+ ] {+ let config = AiConfig::from_table(&table(line)).unwrap();+ assert_eq!(config.backends[0].options.context_tokens, expected);+ assert_eq!(AiConfig::from_table(&config.to_table().unwrap()).unwrap(), config);+ }+ for line in ["context_tokens = -1", "context_tokens = \"8000\"", "context_tokens = 8.5"] {+ assert_eq!(AiConfig::from_table(&table(line)).unwrap_err().code, ErrorCode::BadSettings);+ }}#[test]diff --git a/crates/ai/src/lib.rs b/crates/ai/src/lib.rsindex 1502093e..d53dffb5 100644--- a/crates/ai/src/lib.rs+++ b/crates/ai/src/lib.rs@@ -587,7 +587,14 @@ impl AiHub {Some(t) => Box::new(Tunneled { inner: model, _tunnel: t }) as Box<dyn ChatModel>,None => model,};- Ok(ModelSlot { name: c.name.clone(), model, local, effort: e.options.effort, max_turns: e.options.max_turns.unwrap_or(agent::DEFAULT_MAX_TURNS) })+ Ok(ModelSlot {+ name: c.name.clone(),+ model,+ local,+ effort: e.options.effort,+ max_turns: e.options.max_turns.unwrap_or(agent::DEFAULT_MAX_TURNS),+ context_tokens: e.options.context_tokens.unwrap_or(0),+ })}fn project_root(&self) -> Option<PathBuf> {diff --git a/crates/ai/src/rebuild/tests.rs b/crates/ai/src/rebuild/tests.rsindex 3348cdb2..fccf31c5 100644--- a/crates/ai/src/rebuild/tests.rs+++ b/crates/ai/src/rebuild/tests.rs@@ -609,7 +609,7 @@ fn an_api_backend_builds_with_the_build_tools() {]),seen: Arc::default(),};- let slot = ModelSlot { name: "Scripted".into(), model: Box::new(script), local: false, effort: None, max_turns: 10 };+ let slot = ModelSlot { name: "Scripted".into(), model: Box::new(script), local: false, effort: None, max_turns: 10, context_tokens: 0 };let enabled = std::collections::BTreeSet::from([craft_anything_engine::Toolset::Core, craft_anything_engine::Toolset::Build]);let mut api = ApiConversation::start_with(Arc::new(EngineHost(engine)), vec![slot], LoopConfig::default(), enabled).unwrap();let reply = w.turn(&mut ws, &mut api, "Build it.", None).unwrap();diff --git a/crates/ai/src/tests.rs b/crates/ai/src/tests.rsindex 1c893abf..e43e367e 100644--- a/crates/ai/src/tests.rs+++ b/crates/ai/src/tests.rs@@ -275,6 +275,21 @@ fn a_server_is_added_by_its_address() {assert_eq!(h.backends().len(), 2, "only the ones that answered");}+#[test]+fn a_backend_context_budget_reaches_the_model() {+ let (hub, dir) = hub();+ let table: toml::Table = toml::from_str(+ "[[backends]]\nname = \"Local\"\nkind = \"openai_compatible\"\nmodel = \"qwen3:8b\"\nbase_url = \"http://127.0.0.1:9/v1\"\ncontext_tokens = 8000\n",+ )+ .unwrap();+ let entry = AiConfig::from_table(&table).unwrap().backends.remove(0);+ hub.add_backend_with(entry, None).unwrap();+ let slot = hub.build_model(&hub.entry("Local").unwrap()).unwrap();+ assert_eq!(slot.context_tokens, 8000);+ let saved = AiConfig::from_settings(&Settings::load_from(&dir.path().join("config.toml")));+ assert_eq!(saved.get("Local").unwrap().options.context_tokens, Some(8000));+}+/// #374: a remote OpenAI-compatible service was treated as a local model: a 24K-token context/// and a cost of nothing. Only a server on this computer or its network is local.#[test]diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex d41582eb..60c5fe79 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -204,8 +204,8 @@ been run live.- [ ] Find how each local server is told its context size and set it, or stop with a plain messagewhen the prompt won't fit. We assume 24k and send no `num_ctx`, which an OpenAI-style endpointmay ignore anyway; LM Studio refused a 12.6k prompt on its 8k default (#73)-- [ ] A per-backend context budget in `[[ai.backends]]` (`LoopConfig::context_tokens` exists), for- services whose real window differs from 150k (#374)+- [x] A per-backend context budget in `[[ai.backends]]` (`LoopConfig::context_tokens` exists), for+ services whose real window differs from 150k (#374) — implementation: `6bd94b84828ec89b805cb8a246f557d0a778c037`- [ ] Find LM Studio on another port (#73)- [ ] See why Bionic or LM Studio can't be picked (#140)diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 088d97a5..d5ed1dde 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -24,6 +24,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi| Electron window comparisons | `app_graphs_compare` retains every unassigned window and every construction with a reused local binding. Windows are paired by module, binding and occurrence, so inserting comments does not hide preference changes | Synthetic application graphs exercise changes in either anonymous window, unique and reused bindings, shifted source lines and unequal counts. Pairing remains positional within each binding group; reordered constructions and real application releases were not checked for this correction || Rebuild workflow (Study → Build → Check → Refine) | `crates/ai/src/rebuild/` (kinds, checks and stacks are pluggable: docs/extending.md). Three kinds: website, app, game (a project whose stack is a game engine is always a game). The request decides how to build: a language, framework, engine or platform it names wins over the kind's default stack (Rust + egui for apps, Unity for games, the original's for websites), and the build check, the recorded stack and Play follow what was built (an Electron app opens in its own Electron; a plain static site has nothing to build and passes the build check as it is). Websites: Study also captures up to 4 other pages of the site; menus are opened on a computer and on a phone; the check serves the build on loopback and compares every page at 1440, 768 and 390 px (likeness = mean of layout and perceptual detail, SSIM, averaged over pages, leaving out the parts of the original that change by themselves, found by photographing it three times; the note adds text, page structure, the colours, font, text sizes and spacing the build misses, and per width a page that scrolls sideways, heading sizes and sections whose padding, items per row or content column differ, the errors, failed requests and accessibility gaps the build adds, and the opened menus and pop-ups). A stack or library named in the request (Next.js, shadcn/ui, Tailwind CSS…, `stacks.toml`) is what the builder uses; with none named, a website's stack is the builder's choice (told to match what the original is built with) and the stack it used is recorded from app/package.json. The builder leads: it studies, asks the tools follow-up questions, records what it can't find out as unknowns (`core_unknown_add`; the run reports the open ones), and tests its own build mid-turn with `rebuild_check` (the same checks, for every kind); a check with anything it couldn't compare, or any claim that fails (a website page that scrolls sideways, logs new errors, fails to load a file, lacks a landmark, or a menu that doesn't open; for games each self-test step, for Deep-mode sheets each original number in the code, for console apps the same exit and output as the original's runs), isn't good enough; apps and games by whether they build. Up to 6 refinement rounds, or until a website reaches 90% likeness. A turn cut off by a time limit, crash or dropped connection resumes (up to 3 times); builder turns may run 24 h. A project copied from another computer (or moved to another folder) keeps building with Claude Code: the project keeps a copy of the builder's session (`agent-session.jsonl`) after every turn and puts it back where Claude Code finds it on a computer without it, so the same conversation carries on (#451); when the session still isn't there, a new one starts from the brief, what's in app/ and the kept requests and replies (or the last summary), and questions about the build put the kept session back too, else are answered from the files and forget the missing session (#452). Live runs with Claude Code 2.1.316 on one Mac (2026-11-02), a second computer stood in for by a separate signed-in `CLAUDE_CONFIG_DIR`: a copied project's session was put back and resumed (the builder recalled its first reply from memory); a kept copy of another session was refused and the new session used the handoff; a real project synced from Windows whose session was missing started afresh and reached Ready. Not yet run between two real computers | Unit tests for prompts, stack choice, site detection, feed folding; live runs reached Build and decompiling (below) || Context-summary usage | Successful API context summaries contribute to the message totals consumed by build usage and receive a `model_turn` journal entry with `purpose: context_summary`. Cached-token pricing is retained; an unknown summary price makes the total unknown, and a failed call adds no invented usage | Scripted-model tests exercise the real `ApiConversation`, transcript resumption, exact input/output and cache-price totals, journal entries, empty summaries, local zero cost, unknown prices and failed summaries. No live provider or end-to-end rebuild was used for this correction |+| Backend context budgets | `context_tokens` in `[[ai.backends]]` controls when an API conversation is trimmed and summarised. Zero or omission retains local/cloud defaults; a nonzero conversation override takes priority. Before each attempt, including a fallback, fitting adds estimated history growth since the last successful request to its reported input size. Trimming resets that reference, and successful requests refresh it; summary usage remains in message totals | Regressions cover settings and model construction, defaults/overrides, smaller fallback budgets, large-budget arithmetic and new tool output growing beyond a fallback budget even when the history estimate alone is below the reported input. The latest tool results are preserved, and a short follow-up does not count already-sent history twice. This does not set server context parameters or guarantee that a complete request fits; no live provider was used || Games | Engine detection for 12 engines (Unreal, Unity, Godot, Source, GameMaker, RPG Maker, Ren'Py, MonoGame, LÖVE, CryEngine, Cocos, Cube) with versions. Unreal and Godot games are rebuilt in the same engine, others in Unity; installed engines are found, Godot installs itself, others get guided installs. Picking an inner folder (Engine, Binaries, Paks…) finds the game's folder. Just look inside a game shows what it's made of (`core_target_triage` on its folder: engine and version, how its code ships, the libraries its Unity assembly names give away, its own code, scenes and size) and opens it in the chat to ask about it. The builder keeps `app/MECHANICS.md` and its structured twin `app/mechanics.json` (checked after each build), in Deep mode only, may reuse the original's readable files for private use (never decrypting; generated pictures and 3D models replace its art when the person turns them on; Clean room copies none of its files), lists them in `CREDITS.md` (checked, with the private-use line in `README.md`); a game is ready only when its `--self-test` shows the player moving, acting and the HUD drawn, and the result can be started from the project page | Unit tests; live runs on Windows || Clean room and Deep mode | Clean room (the default) runs only the tools in `engine/src/clean_room.rs`: ones that touch no target or watch from outside (the website as a visitor sees it, pictures of a window, its controls, recorded runs, a phone's screen). Every other tool, a plugin's included, is refused in the app, CLI, MCP and agents, with a way to turn on Deep mode. A Clean room build studies an app or a game only from the person's pictures and words (and a picture of its window when runtime study is on); its builder's reads and commands go through an approval rule that keeps it out of the original's folder and site (with Claude Code, and with ACP agents for what they ask about; other agents aren't held to it, see roadmap R2.2). Deep mode (`deep_mode` in Settings, `--deep` for one CLI run) uses every tool: the builder sees them all, and a website's study also reads its JavaScript and watches its start page for ten seconds (capture/how-it-works.md). Ghidra adds its decompiler in Deep mode when it's installed: it is found, or installed after asking. Study starts one analysis of the main program, saved and shared with the builder's tool server through a lock file (up to 8 h, Java gets half the machine's memory or the amount set in Settings → Engines, 4 to 31 GB, four slow passes skipped). The builder must decompile before the build is checked; addresses the built-in analysis can't place go to Ghidra, which makes a function on demand (for this run only) where its analysis has none, e.g. code reached only through tables of pointers. Without Ghidra, Deep mode uses the built-in engines | Live runs with Ghidra 12.1.4 on Windows (a shared analysis, and a decompile in seconds on a large program). Live runs with Ghidra 12.2 on Linux x86-64 (decompiles by name in position-independent programs and shared libraries, whose addresses Ghidra moves). The guided install of Ghidra and its Java is offered on Linux and macOS too, but has only been tried on Windows. Clean room and Deep mode: engine, AI, MCP, CLI and app tests; no live Clean room build run yet || Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget | Unit tests |