From 706912ba33a331b3e34629629dc953c10c32c144 Mon Sep 17 00:00:00 2001 From: uiharuayako <2451602772@qq.com> Date: Mon, 23 Nov 2026 15:59:10 +0800 Subject: [PATCH 1/3] fix: budget tool images against the selected model context window --- Cargo.lock | 1 + .../cargo-dependency-boundaries.mjs | 7 + .../core-boundaries/rules/feature-rules.mjs | 1 + src/crates/adapters/ai-adapters/AGENTS.md | 6 +- src/crates/adapters/ai-adapters/Cargo.toml | 2 + src/crates/adapters/ai-adapters/src/client.rs | 91 ++- .../ai-adapters/src/client/image_budget.rs | 9 + .../src/client/image_budget/context.rs | 609 ++++++++++++++++++ .../src/client/image_budget/context_tests.rs | 579 +++++++++++++++++ src/crates/adapters/ai-adapters/src/lib.rs | 2 + .../src/providers/gemini/message_converter.rs | 68 +- .../src/providers/openai/message_converter.rs | 178 ++--- .../src/providers/openai/responses.rs | 2 + .../ai-adapters/src/providers/shared.rs | 3 + .../adapters/ai-adapters/src/vision_tokens.rs | 482 ++++++++++++++ .../src/vision_tokens/openai_patches.rs | 104 +++ src/crates/assembly/core/Cargo.toml | 1 + .../src/agentic/coordination/coordinator.rs | 2 + .../assembly/core/src/agentic/core/message.rs | 128 +++- .../core/src/agentic/core/messages_helper.rs | 16 +- .../src/agentic/execution/compression_job.rs | 8 +- .../src/agentic/execution/context_budget.rs | 8 +- .../src/agentic/execution/execution_engine.rs | 336 ++++++++-- .../agentic/execution/prompt_suggestion.rs | 17 +- .../src/agentic/execution/round_executor.rs | 32 +- .../assembly/core/src/util/token_counter.rs | 97 +-- .../contracts/config-contracts/src/types.rs | 17 +- src/crates/contracts/core-types/src/ai.rs | 6 + src/crates/contracts/core-types/src/lib.rs | 1 + .../core-types/src/token_estimate.rs | 114 ++++ 30 files changed, 2615 insertions(+), 312 deletions(-) create mode 100644 src/crates/adapters/ai-adapters/src/client/image_budget/context.rs create mode 100644 src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs create mode 100644 src/crates/adapters/ai-adapters/src/vision_tokens.rs create mode 100644 src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs create mode 100644 src/crates/contracts/core-types/src/token_estimate.rs diff --git a/Cargo.lock b/Cargo.lock index 8dfff09b2a..b1e1976ac2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5822,6 +5822,7 @@ dependencies = [ "fs2", "futures", "hex", + "image 0.25.10", "keyring-core", "libc", "log", diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index 97a60f5bdf..d5b970a021 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -546,6 +546,13 @@ const THIRD_PARTY_CAPABILITY_PROFILES = new Map([ ['image', { label: 'Image', packages: new Map([ + ['openbitfun-ai-adapters', dependencyProfile([], { + optional: true, + useDefaultFeatures: false, + ownerFeatureCapabilities: new Map([ + ['vision-input', ['bmp', 'gif', 'jpeg', 'png', 'webp']], + ]), + })], ['openbitfun-computer-use', dependencyProfile(['jpeg', 'png'], { useDefaultFeatures: false })], ['openbitfun-services-core', dependencyProfile([], { optional: true, diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index 97703a78a3..d49f8c4f4b 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -896,6 +896,7 @@ export const coreClosedFeatureProfileRules = [ requiredFeatureRefs: [ 'ai-adapter-runtime', 'openbitfun-ai-adapters/local-tokenizer', + 'openbitfun-ai-adapters/vision-input', 'dep:openbitfun-agent-runtime', 'openbitfun-agent-runtime/agent-runtime', 'dep:openbitfun-agent-content', diff --git a/src/crates/adapters/ai-adapters/AGENTS.md b/src/crates/adapters/ai-adapters/AGENTS.md index a20cf6c80d..76f9dc47bb 100644 --- a/src/crates/adapters/ai-adapters/AGENTS.md +++ b/src/crates/adapters/ai-adapters/AGENTS.md @@ -40,8 +40,10 @@ provider-neutral contracts owned by `openbitfun-agent-stream`. the shared AIClient send boundary, including single-attempt Responses calls. Count user image parts and tool attachments together; preserve durable history, tool-result identities, opaque tool text and non-image media. Newer messages - keep their pixels first, with explicit omission text for older pixels. Verify - with `cargo test --locked -p openbitfun-ai-adapters --lib client::image_budget::tests`. + keep their pixels first, with explicit omission text for older pixels. + With `vision-input`, the selected client's context window also determines + whether older pixels must be omitted or current screenshots resized. + Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens`. - Normalize explicitly reported response models into the typed stream `response_model` observation. Responses/Codex lifecycle metadata is emitted before an associated error, and Chat Completions model identifiers remain diff --git a/src/crates/adapters/ai-adapters/Cargo.toml b/src/crates/adapters/ai-adapters/Cargo.toml index 547888c604..7fd5a1c293 100644 --- a/src/crates/adapters/ai-adapters/Cargo.toml +++ b/src/crates/adapters/ai-adapters/Cargo.toml @@ -38,6 +38,7 @@ serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } hex = { workspace = true } +image = { workspace = true, optional = true } tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } tokio-stream = { workspace = true } tokio-tungstenite = { workspace = true, features = ["handshake"] } @@ -61,6 +62,7 @@ zbus-secret-service-keyring-store = { workspace = true, optional = true } [features] local-tokenizer = ["dep:tokenizers"] +vision-input = ["dep:base64", "dep:image", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/webp"] image-generation = ["dep:base64"] subscription-auth = [ "dep:apple-native-keyring-store", diff --git a/src/crates/adapters/ai-adapters/src/client.rs b/src/crates/adapters/ai-adapters/src/client.rs index 0c8e8055a8..9ad8f82e42 100644 --- a/src/crates/adapters/ai-adapters/src/client.rs +++ b/src/crates/adapters/ai-adapters/src/client.rs @@ -379,7 +379,10 @@ impl AIClient { extra_body: Option, trace: Option, ) -> Result { - self.send_message_stream_with_extra_body_and_max_attempts( + let messages = self + .prepare_message_inputs(messages, tools.as_deref(), None, extra_body.as_ref()) + .await?; + self.send_prepared_message_stream( messages, tools, extra_body, @@ -415,15 +418,16 @@ impl AIClient { trace: Option, ) -> Result { let custom_body = self.config.custom_request_body.clone(); - self.send_message_stream_with_extra_body_and_max_attempts( - messages, - tools, - custom_body, - 1, - trace, - request_context, - ) - .await + let messages = self + .prepare_message_inputs( + messages, + tools.as_deref(), + request_context.as_ref(), + custom_body.as_ref(), + ) + .await?; + self.send_prepared_message_stream(messages, tools, custom_body, 1, trace, request_context) + .await } pub async fn send_message( @@ -537,9 +541,17 @@ impl AIClient { ) -> Result { let request_context = crate::providers::shared::prepare_request_context(self, request_context); + let messages = self + .prepare_message_inputs( + messages, + tools.as_deref(), + request_context.as_ref(), + extra_body.as_ref(), + ) + .await?; for attempt in 0..max_attempts { let stream_response = match self - .send_message_stream_with_extra_body_and_max_attempts( + .send_prepared_message_stream( messages.clone(), tools.clone(), extra_body.clone(), @@ -608,7 +620,55 @@ impl AIClient { unreachable!("send_message retry loop always returns") } - async fn send_message_stream_with_extra_body_and_max_attempts( + async fn prepare_message_inputs( + &self, + messages: Vec, + tools: Option<&[ToolDefinition]>, + request_context: Option<&ModelRequestContext>, + extra_body: Option<&serde_json::Value>, + ) -> Result> { + #[cfg(not(feature = "vision-input"))] + let _ = (tools, request_context); + // Project only the outgoing copy, against the actual selected client. + responses_websocket::validate(self)?; + // Account/channel failover and direct analysis calls share this boundary. + let messages = image_budget::project(messages, self.config.max_images_per_request)?; + image_budget::validate_extra_body(self.config.max_images_per_request, extra_body)?; + #[cfg(feature = "vision-input")] + let replaced = image_budget::context::validate_override( + &self.config, + &messages, + tools, + request_context, + extra_body, + )?; + #[cfg(feature = "vision-input")] + let messages = if !replaced + && messages + .iter() + .any(image_budget::context::may_contain_images) + { + let budget = image_budget::context::Budget::for_request( + &self.config, + tools, + request_context, + extra_body, + ); + // Decoding and resampling a large screenshot can occupy a CPU for + // a full scheduling slice. Keep it off the async transport worker. + tokio::task::spawn_blocking(move || -> Result<_> { + let mut messages = messages; + image_budget::context::apply(&mut messages, budget)?; + Ok(messages) + }) + .await?? + } else { + messages + }; + Ok(messages) + } + + async fn send_prepared_message_stream( &self, messages: Vec, tools: Option>, @@ -617,11 +677,6 @@ impl AIClient { trace: Option, request_context: Option, ) -> Result { - // Project only the outgoing copy, against the actual selected client. - responses_websocket::validate(self)?; - // Account/channel failover and direct analysis calls share this boundary. - let messages = image_budget::project(messages, self.config.max_images_per_request)?; - image_budget::validate_extra_body(self.config.max_images_per_request, extra_body.as_ref())?; match ApiFormat::parse(&self.config.format)? { ApiFormat::OpenAIChat => { openai::chat::send_stream( @@ -953,6 +1008,7 @@ mod tests { "type": "object", "properties": { "summary": { "type": "string" } } })), + ..Default::default() } } @@ -962,6 +1018,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("lineage-1".to_string()), output_schema: None, + ..Default::default() }; let official = openai::chat::build_request_body_with_context( &make_test_client("openai", None), diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget.rs b/src/crates/adapters/ai-adapters/src/client/image_budget.rs index c9eeb8aa4a..7d679ade3c 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget.rs @@ -1,5 +1,10 @@ //! Model-specific image input budgets for an outgoing request copy. +#[cfg(feature = "vision-input")] +pub(super) mod context; +#[cfg(all(test, feature = "vision-input"))] +mod context_tests; + use crate::types::Message; use anyhow::Result; use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; @@ -480,6 +485,10 @@ mod tests { let mut selected = initial.clone(); selected.config.max_images_per_request = Some(3); let mut history = vec![tool_images("batch", 4)]; + // Use actual one-pixel images so the 4K window exercises the count limit. + for image in history[0].tool_image_attachments.as_mut().unwrap() { + image.data_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=".into(); + } tokio::time::timeout(std::time::Duration::from_secs(5), async { initial .send_message_once_with_trace_and_request_context(history.clone(), None, None, None) diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs new file mode 100644 index 0000000000..463b828f14 --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs @@ -0,0 +1,609 @@ +//! Pixel projection for one outgoing request. All positions refer to the +//! provider-neutral messages before the adapter merges roles and tool results. + +use super::{inline_media, is_content_part, is_image_part}; +use crate::client::format::ApiFormat; +use crate::providers::openai::OpenAIMessageConverter; +use crate::types::{AIConfig, Message, ModelRequestContext, ToolDefinition}; +use crate::vision_tokens::{ + inline_image_dimensions, ResizedInlineImage, VisionTokenPolicy, UNKNOWN_IMAGE_DIMENSIONS, +}; +use anyhow::Result; +use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; +use openbitfun_core_types::token_estimate::{ + automatic_max_output_tokens, TokenCounter, INPUT_SAFETY_RESERVE, +}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +const OMITTED: &str = "[Earlier image omitted to fit the context window.]"; + +struct Image { + message: usize, + part: usize, + dimensions: Option<(u32, u32)>, + policy: VisionTokenPolicy, + cost: usize, + minimum: usize, + target: usize, +} + +impl Image { + fn new( + policy: VisionTokenPolicy, + message: usize, + part: usize, + inline: Option<(&str, &str)>, + resizable: bool, + ) -> Self { + let dimensions = inline.and_then(|(mime, data)| inline_image_dimensions(mime, data)); + // Opaque URLs/file IDs are never fetched here. Budget an ordinary + // full-size input and retain it intact whenever it is current. + let (w, h) = dimensions.unwrap_or(UNKNOWN_IMAGE_DIMENSIONS); + let cost = policy.estimate(w, h); + let minimum = if dimensions.is_some() && resizable { + policy.min_readable_tokens(w, h) + } else { + cost + }; + Self { + message, + part, + dimensions, + policy, + cost, + minimum, + target: cost, + } + } + + fn preview_note(&self, width: u32, height: u32) -> String { + let (w, h) = self.dimensions.expect("resizable image dimensions"); + format!( + "[Image {} preview {width}x{height} from {w}x{h}.]", + self.part + 1 + ) + } +} + +fn part_policy(policy: VisionTokenPolicy, part: &Value) -> VisionTokenPolicy { + let detail = part["image_url"]["detail"] + .as_str() + .or_else(|| part["detail"].as_str()); + policy.with_detail(detail) +} + +fn part_payload(part: &Value) -> Option<(&str, &str)> { + if let Some(source) = part.get("source") { + if let (Some(mime), Some(data)) = (source["media_type"].as_str(), source["data"].as_str()) { + return Some((mime, data)); + } + } + if let Some(inline) = inline_media(part) { + return Some(inline); + } + let value = part + .get("image_url") + .or_else(|| part.get("source")?.get("url"))?; + let url = value.as_str().or_else(|| value.get("url")?.as_str())?; + let (mime, data) = url.strip_prefix("data:")?.split_once(";base64,")?; + Some((mime, data)) +} + +fn replace_payload(part: &mut Value, image: ResizedInlineImage) { + if let Some(source) = part + .get_mut("source") + .filter(|source| source.get("data").is_some()) + { + source["media_type"] = image.mime_type.into(); + source["data"] = image.data_base64.into(); + } else if let Some(key) = ["inline_data", "inlineData"] + .into_iter() + .find(|k| part.get(k).is_some()) + { + let data = &mut part[key]; + let mime_key = if data.get("mimeType").is_some() { + "mimeType" + } else { + "mime_type" + }; + data[mime_key] = image.mime_type.into(); + data["data"] = image.data_base64.into(); + } else { + let data_url = Value::String(format!( + "data:{};base64,{}", + image.mime_type, image.data_base64 + )); + if let Some(value) = part.get_mut("image_url") { + if value.is_object() { + value["url"] = data_url; + } else { + *value = data_url; + } + } else { + part["source"]["url"] = data_url; + } + } +} + +fn image_budget_error(message: String) -> anyhow::Error { + // Provider context overflows trigger session compaction. This request + // needs a different image or a smaller batch, so return the crop guidance. + AiProviderError::classified(message, ErrorCategory::InvalidRequest).into() +} + +fn resize_preview( + policy: VisionTokenPolicy, + mime: &str, + data: &str, + target: usize, +) -> Result { + policy.resize(mime, data, target).map_err(|error| { + AiProviderError::classified( + format!("Unable to prepare a smaller image preview: {error}. Supply a still image or a crop of the relevant region."), + ErrorCategory::InvalidRequest, + ).into() + }) +} + +fn output_reserve(config: &AIConfig, extra: Option<&Value>) -> usize { + let default = if config.format.eq_ignore_ascii_case("anthropic") { + 32_000 + } else { + automatic_max_output_tokens(config.context_window) + }; + let configured = config.max_tokens.unwrap_or(default) as usize; + // Custom request bodies can raise the wire output cap on compatible gateways. + [ + "/max_tokens", + "/max_completion_tokens", + "/max_output_tokens", + "/generationConfig/maxOutputTokens", + ] + .into_iter() + .filter_map(|path| extra?.pointer(path)?.as_u64()) + .fold(configured, |cap, value| { + cap.max(usize::try_from(value).unwrap_or(usize::MAX)) + }) +} + +/// Admission facts captured from the client selected for *this* send. +pub(in crate::client) struct Budget { + format: Option, + policy: VisionTokenPolicy, + limit: usize, + tools: usize, + schema: usize, + text_floor: usize, + turn_start: Option, +} + +impl Budget { + pub(in crate::client) fn for_request( + config: &AIConfig, + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + extra: Option<&Value>, + ) -> Self { + let window = config.context_window as usize; + // Leave input space for clients whose entire window is smaller than + // the ordinary compression safety reserve. + let limit = window + .saturating_sub(output_reserve(config, extra)) + .saturating_sub(INPUT_SAFETY_RESERVE.min(window / 3)); + let wire_overhead = |value: &Value| TokenCounter::estimate_tokens(&value.to_string()); + let schema = context + .and_then(|ctx| ctx.output_schema.as_ref()) + .map_or(0, wire_overhead); + let schema = schema + + [ + "/instructions", + "/system", + "/systemInstruction", + "/response_format", + "/text/format", + "/generationConfig/responseSchema", + ] + .into_iter() + .filter_map(|p| extra?.pointer(p)) + .map(wire_overhead) + .sum::(); + let tools = tools + .map_or(0, TokenCounter::estimate_tool_definitions_tokens) + .max( + extra + .and_then(|body| body.get("tools")) + .map_or(0, wire_overhead), + ); + let format = ApiFormat::parse(&config.format).ok(); + let body_selects_model = !crate::client::utils::is_trim_custom_request_body_mode(config) + && matches!( + format, + Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses | ApiFormat::Anthropic) + ); + let model = if body_selects_model { + extra + .and_then(|body| body["model"].as_str()) + .unwrap_or(&config.model) + } else { + &config.model + }; + let mut policy = VisionTokenPolicy::for_model(model); + if matches!( + format, + Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + ) { + let generation = extra.and_then(|body| { + body.get("generationConfig") + .or_else(|| body.get("generation_config")) + }); + policy = policy.with_gemini_media_resolution(generation.and_then(|config| { + config + .get("mediaResolution") + .or_else(|| config.get("media_resolution"))? + .as_str() + })); + } + Self { + format, + policy, + limit, + tools, + schema, + text_floor: context.map_or(0, |ctx| ctx.minimum_non_image_input_tokens), + turn_start: context.and_then(|ctx| ctx.image_turn_start), + } + } +} + +/// A raw provider message override has no application turn or attachment identity. +/// Keep it intact when it fits; report oversized image overrides before transport. +pub(in crate::client) fn validate_override( + config: &AIConfig, + messages: &[Message], + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + body: Option<&Value>, +) -> Result { + let Some(body) = body else { return Ok(false) }; + let (key, system_key) = match ApiFormat::parse(&config.format)? { + ApiFormat::OpenAIChat => ("messages", None), + ApiFormat::Anthropic => ("messages", Some("system")), + ApiFormat::OpenAIResponses => ("input", Some("instructions")), + ApiFormat::Gemini | ApiFormat::GeminiCodeAssist => ("contents", Some("systemInstruction")), + }; + let Some(override_messages) = body.get(key) else { + return Ok(false); + }; + if crate::client::utils::is_trim_custom_request_body_mode(config) { + return Ok(false); + } + fn count( + value: &Value, + policy: VisionTokenPolicy, + gemini: bool, + saw_image: &mut bool, + ) -> usize { + let file_image = gemini + && value + .get("fileData") + .or_else(|| value.get("file_data")) + .and_then(|file| file.get("mimeType").or_else(|| file.get("mime_type"))) + .and_then(Value::as_str) + .is_some_and(|mime| mime.starts_with("image/")); + if is_image_part(value) || file_image { + *saw_image = true; + let policy = if gemini { + let resolution = value + .get("mediaResolution") + .or_else(|| value.get("media_resolution")) + .and_then(|setting| setting["level"].as_str()); + policy.with_gemini_media_resolution(resolution) + } else { + part_policy(policy, value) + }; + return Image::new(policy, 0, 0, part_payload(value), false).cost; + } + match value { + Value::String(s) => TokenCounter::estimate_tokens(s) + 1, + Value::Array(items) => items + .iter() + .map(|item| count(item, policy, gemini, saw_image)) + .sum(), + Value::Object(fields) => fields + .iter() + .map(|(k, v)| { + TokenCounter::estimate_tokens(k) + 1 + count(v, policy, gemini, saw_image) + }) + .sum(), + _ => 1, + } + } + let budget = Budget::for_request(config, tools, context, Some(body)); + let mut saw_image = false; + let gemini = matches!( + budget.format, + Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + ); + let cost = count(override_messages, budget.policy, gemini, &mut saw_image); + if saw_image { + // Responses, Anthropic and Gemini send system messages in a separate + // field, which survives an override of just input/messages/contents. + let preserved_system = if system_key.is_some_and(|key| body.get(key).is_none()) { + messages + .iter() + .filter(|message| message.role == "system") + .map(TokenCounter::estimate_message_tokens) + .sum() + } else { + 0 + }; + if cost + .saturating_add(preserved_system) + .saturating_add(budget.tools + budget.schema + 3) + > budget.limit + { + return Err(image_budget_error("Custom image messages exceed the input budget after reserving output. Use ordinary image attachments to allow automatic resizing.".into())); + } + } + Ok(true) +} + +pub(in crate::client) fn may_contain_images(message: &Message) -> bool { + message + .tool_image_attachments + .as_ref() + .is_some_and(|images| !images.is_empty()) + || (message.role == "user" + && message + .content + .as_deref() + .is_some_and(|s| s.trim_start().starts_with('['))) +} + +#[cfg(test)] +pub(super) fn project( + messages: &mut [Message], + config: &AIConfig, + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + extra: Option<&Value>, +) -> Result<()> { + apply(messages, Budget::for_request(config, tools, context, extra)) +} + +// Desktop and browser control actions reuse the exact coordinates of their +// screenshots. A deferred call retains its gateway name on the wire. +fn can_resize_tool(message: &Message, history: &[Message]) -> bool { + let mut name = message.name.as_deref(); + if name == Some("CallDeferredTool") { + name = message.tool_call_id.as_deref().and_then(|id| { + history + .iter() + .rev() + .flat_map(|message| message.tool_calls.iter().flatten()) + .find(|call| call.id == id && call.name == "CallDeferredTool") + .and_then(|call| call.arguments["tool_name"].as_str()) + }); + } + !matches!(name, None | Some("ComputerUse" | "ControlHub")) +} + +pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Result<()> { + let mut users = BTreeMap::new(); + let mut images = Vec::new(); + for (index, message) in messages.iter().enumerate() { + if message.role == "tool" { + if message + .tool_image_attachments + .as_ref() + .is_none_or(Vec::is_empty) + { + continue; + } + let resizable = can_resize_tool(message, &messages[..index]); + for (part, image) in message.tool_image_attachments.iter().flatten().enumerate() { + images.push(Image::new( + budget.policy, + index, + part, + Some((&image.mime_type, &image.data_base64)), + resizable, + )); + } + } else if message.role == "user" { + let Some(content) = message + .content + .as_deref() + .filter(|text| text.trim_start().starts_with('[')) + else { + continue; + }; + let Ok(parts) = serde_json::from_str::>(content) else { + continue; + }; + if matches!( + budget.format, + Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses) + ) && !parts.iter().all(is_content_part) + { + // OpenAI renders unrecognized JSON arrays as literal user text. + continue; + } + let before = images.len(); + for (part, value) in parts + .iter() + .enumerate() + .filter(|(_, value)| is_image_part(value)) + { + images.push(Image::new( + part_policy(budget.policy, value), + index, + part, + part_payload(value), + true, + )); + } + if images.len() > before { + if let Some(format @ (ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses)) = + budget.format + { + if let Some(part) = parts.iter().position(|part| { + !OpenAIMessageConverter::can_render_user_part(part, format) + }) { + return Err(AiProviderError::classified( + format!("Unsupported user content part at index {part} in an OpenAI image message. Use supported text and image parts."), + ErrorCategory::InvalidRequest, + ).into()); + } + } + users.insert(index, parts); + } + } + } + if images.is_empty() { + return Ok(()); + } + + let mut text = 3 + budget.tools; + for (index, message) in messages.iter().enumerate() { + let tokens = match users.get(&index) { + None => TokenCounter::estimate_message_tokens(message), + Some(parts) => { + let text: usize = parts + .iter() + .filter(|p| !is_image_part(p)) + .map(|part| { + part["text"].as_str().map_or_else( + || TokenCounter::estimate_tokens(&part.to_string()), + TokenCounter::estimate_tokens, + ) + }) + .sum(); + TokenCounter::estimate_message_overhead(message) + text + } + }; + text = text.saturating_add(tokens); + } + let text = text.max(budget.text_floor).saturating_add(budget.schema); + let input_limit = budget.limit; + let mut total = images + .iter() + .fold(text, |n, img| n.saturating_add(img.cost)); + if total <= input_limit { + return Ok(()); + } + + let turn_start = budget + .turn_start + .or_else(|| messages.iter().rposition(|message| message.role == "user")) + .unwrap_or(0) + .min(messages.len()); + // Each assistant call batch starts a new model round, even when several + // rounds answer the same user. Older observations were already sent. + let current_start = messages[turn_start..] + .iter() + .rposition(|message| { + message.role == "assistant" + && message + .tool_calls + .as_ref() + .is_some_and(|calls| !calls.is_empty()) + }) + .map_or(turn_start, |index| turn_start + index); + let marker_cost = 4 + TokenCounter::estimate_tokens(OMITTED); + for image in images + .iter_mut() + .take_while(|img| img.message < current_start) + { + image.target = 0; + total = total.saturating_sub(image.cost).saturating_add(marker_cost); + if total <= input_limit { + break; + } + } + if total > input_limit { + // Reserve the readable minimum of each current image first, then share + // the remaining detail across them. Small images keep every pixel. + let mut adjustable = Vec::new(); + let mut required = total; + for (index, img) in images + .iter() + .enumerate() + .filter(|(_, img)| img.target > img.minimum) + { + required = required.saturating_sub(img.cost - img.minimum); + if messages[img.message].role == "tool" { + let (w, h) = img.dimensions.expect("resizable image dimensions"); + required += TokenCounter::estimate_tokens(&img.preview_note(w, h)) + 4; + } + adjustable.push(index); + } + if required > input_limit { + return Err(image_budget_error(format!( + "Cannot fit the images and conversation in the model's context window with the requested output reserved ({required} estimated input tokens needed, {input_limit} available). Crop the relevant area, use fewer images, or shorten the conversation." + ))); + } + let mut spare = input_limit - required; + adjustable.sort_by_key(|&i| images[i].cost - images[i].minimum); + let mut count = adjustable.len(); + for index in adjustable { + let image = &mut images[index]; + let extra = (spare / count).min(image.cost - image.minimum); + image.target = image.minimum + extra; + spare -= extra; + count -= 1; + } + } + + let mut edited_users = std::collections::BTreeSet::new(); + // Remove tool attachments from the back so original positions stay valid. + for image in images.iter().rev().filter(|img| img.target != img.cost) { + let message = &mut messages[image.message]; + if let Some(parts) = users.get_mut(&image.message) { + let part = &mut parts[image.part]; + if image.target == 0 { + *part = json!({"type": "text", "text": OMITTED}); + } else { + let (mime, data) = + part_payload(part).expect("resizable user image has inline data"); + replace_payload( + part, + resize_preview(image.policy, mime, data, image.target)?, + ); + } + edited_users.insert(image.message); + } else { + let attachments = message + .tool_image_attachments + .as_mut() + .expect("tool image group"); + let note = if image.target == 0 { + attachments.remove(image.part); + OMITTED.to_owned() + } else { + let attachment = &mut attachments[image.part]; + let preview = resize_preview( + image.policy, + &attachment.mime_type, + &attachment.data_base64, + image.target, + )?; + let note = image.preview_note(preview.width, preview.height); + attachment.mime_type = preview.mime_type; + attachment.data_base64 = preview.data_base64; + note + }; + if attachments.is_empty() { + message.tool_image_attachments = None; + } + let content = message.content.get_or_insert_with(String::new); + content.push('\n'); + content.push_str(¬e); + } + } + for index in edited_users { + messages[index].content = Some(serde_json::to_string(&users[&index])?); + } + Ok(()) +} diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs new file mode 100644 index 0000000000..d66705cd1f --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs @@ -0,0 +1,579 @@ +use super::context::project; +use crate::types::{AIConfig, Message, ModelRequestContext, ToolImageAttachment}; +use crate::vision_tokens::{inline_image_dimensions, VisionTokenPolicy}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use openbitfun_core_types::token_estimate::INPUT_SAFETY_RESERVE; +use serde_json::{json, Value}; +use std::io::Cursor; + +fn config() -> AIConfig { + serde_json::from_value(json!({ + "name": "vision", "base_url": "http://localhost", "request_url": "http://localhost", + "api_key": "synthetic", "model": "test-vl", "format": "openai", + "context_window": 262144, "max_tokens": 16384, + "inline_think_in_text": false, "skip_ssl_verify": false + })) + .unwrap() +} + +fn with_remaining_input( + config: &AIConfig, + turn_start: usize, + remaining: usize, +) -> ModelRequestContext { + ModelRequestContext { + image_turn_start: Some(turn_start), + minimum_non_image_input_tokens: config.context_window as usize + - config.max_tokens.unwrap() as usize + - INPUT_SAFETY_RESERVE + - remaining, + ..Default::default() + } +} + +fn png(width: u32, height: u32) -> String { + encode_png(image::GrayImage::new(width, height)) +} + +fn encode_png(pixels: image::GrayImage) -> String { + let mut bytes = Cursor::new(Vec::new()); + image::DynamicImage::ImageLuma8(pixels) + .write_to(&mut bytes, image::ImageFormat::Png) + .unwrap(); + STANDARD.encode(bytes.into_inner()) +} + +fn screenshot_with_small_text() -> String { + let mut page = image::GrayImage::from_pixel(2048, 2048, image::Luma([255])); + // Draw "Hi" in 15-pixel-high letters in the middle of the screenshot. + for (y, row) in ["# # #", "# # ", "### #", "# # #", "# # #"] + .iter() + .enumerate() + { + for (x, _) in row.bytes().enumerate().filter(|(_, c)| *c == b'#') { + for dy in 0..3 { + for dx in 0..3 { + page.put_pixel( + 1024 + 3 * x as u32 + dx, + 1024 + 3 * y as u32 + dy, + image::Luma([0]), + ); + } + } + } + } + encode_png(page) +} + +fn uploaded(data: &str) -> Message { + Message::user( + json!([ + {"type": "text", "text": "Inspect this page."}, + {"type": "image_url", "image_url": {"url": format!("data:image/png;base64,{data}")}} + ]) + .to_string(), + ) +} + +fn tool_result(name: &str, data: &str) -> Message { + let mut message = Message::user("Screenshot available.".into()); + message.role = "tool".into(); + message.name = Some(name.into()); + message.tool_call_id = Some("capture".into()); + message.tool_image_attachments = Some(vec![ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: data.into(), + }]); + message +} + +fn user_image_size(message: &Message) -> Option<(u32, u32)> { + let parts: Vec = serde_json::from_str(message.content.as_ref()?).ok()?; + let url = parts + .iter() + .find_map(|part| part["image_url"]["url"].as_str())?; + inline_image_dimensions("image/png", url.strip_prefix("data:image/png;base64,")?) +} + +#[test] +fn openai_preserves_literal_json_and_validates_explicit_image_parts() { + use crate::providers::openai::OpenAIMessageConverter; + let url = format!("data:image/png;base64,{}", png(4, 4)); + let image = json!({"type": "input_image", "image_url": url}); + for format in ["openai", "responses"] { + let mut config = config(); + config.format = format.into(); + let mut mixed = [Message::user( + json!([image, {"type":"unsupported"}]).to_string(), + )]; + let original = mixed[0].content.clone(); + project(&mut mixed, &config, None, None, None).unwrap(); + assert_eq!(mixed[0].content, original); + + let mut unsupported = [Message::user( + json!([image, {"type":"audio", "data":"audio"}]).to_string(), + )]; + let error = project(&mut unsupported, &config, None, None, None).unwrap_err(); + assert!(error + .to_string() + .contains("Unsupported user content part at index 1")); + assert!(!error.to_string().contains(&url)); + + let mut supported = vec![Message::user( + json!([image, {"type": "input_text", "text":"Inspect"}]).to_string(), + )]; + project(&mut supported, &config, None, None, None).unwrap(); + if format == "openai" { + let wire = OpenAIMessageConverter::convert_messages(supported); + assert_eq!(wire[0]["content"][0]["image_url"]["url"], url); + assert_eq!(wire[0]["content"][1]["text"], "Inspect"); + } else { + let (_, wire) = OpenAIMessageConverter::convert_messages_to_responses_input(supported); + assert_eq!(wire[0]["content"][0]["image_url"], url); + assert_eq!(wire[0]["content"][1]["text"], "Inspect"); + } + } +} + +#[test] +fn omit_history_before_resizing_the_current_screenshot_and_preserve_originals() { + let config = config(); + let data = screenshot_with_small_text(); + let original = vec![uploaded(&png(1536, 1536)), tool_result("view_image", &data)]; + let mut roomy = original.clone(); + project(&mut roomy, &config, None, None, None).unwrap(); + assert_eq!( + serde_json::to_value(roomy).unwrap(), + serde_json::to_value(&original).unwrap() + ); + + let mut limited = original.clone(); + let context = with_remaining_input( + &config, + 1, + VisionTokenPolicy::for_model("test-vl").estimate(2048, 2048) + 1000, + ); + project(&mut limited, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&limited[0]).is_none()); + assert!(limited[0] + .content + .as_deref() + .unwrap() + .contains("Inspect this page.")); + assert_eq!(limited[1].tool_call_id.as_deref(), Some("capture")); + assert_eq!( + limited[1].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); + let mut tight = original.clone(); + let remaining = 1200; + let context = with_remaining_input(&config, 1, remaining); + project(&mut tight, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&tight[0]).is_none()); + let preview = &tight[1].tool_image_attachments.as_ref().unwrap()[0]; + let (width, height) = + inline_image_dimensions(&preview.mime_type, &preview.data_base64).unwrap(); + assert_eq!(width, height); + assert!((512..2048).contains(&width)); + assert!(VisionTokenPolicy::for_model(&config.model).estimate(width, height) <= remaining); + assert_eq!(tight[1].tool_call_id.as_deref(), Some("capture")); + + let decoded = image::load_from_memory(&STANDARD.decode(&preview.data_base64).unwrap()) + .unwrap() + .into_luma8(); + let center = image::imageops::crop_imm(&decoded, width / 2, height / 2, 10, 10).to_image(); + assert!( + center.pixels().any(|p| p[0] < 96), + "the preview retains the dark letters" + ); + assert!( + center.pixels().any(|p| p[0] > 230), + "the preview retains the white background" + ); + assert_eq!(user_image_size(&original[0]), Some((1536, 1536))); + assert_eq!( + original[1].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); +} + +#[test] +fn earlier_tool_round_yields_before_the_latest_parallel_results() { + let config = config(); + let data = png(1024, 1024); + let call = |id: &str| crate::ToolCall { + id: id.into(), + name: "view_image".into(), + arguments: json!({}), + raw_arguments: None, + }; + let result = |id: &str| { + let mut result = tool_result("view_image", &data); + result.tool_call_id = Some(id.into()); + result + }; + let mut messages = vec![ + Message::user("Compare the screenshots.".into()), + Message::assistant_with_tools(vec![call("old")]), + result("old"), + Message::assistant_with_tools(vec![call("new-a"), call("new-b")]), + result("new-a"), + result("new-b"), + ]; + let pair = 2 * VisionTokenPolicy::for_model(&config.model).estimate(1024, 1024); + let context = with_remaining_input(&config, 0, pair + 100); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert!(messages[2].tool_image_attachments.is_none()); + assert_eq!(messages[2].tool_call_id.as_deref(), Some("old")); + for message in &messages[4..] { + assert_eq!( + message.tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); + } +} + +#[test] +fn text_only_tool_round_can_omit_the_upload_and_last_rounds_screenshot() { + let config = config(); + let data = png(1024, 1024); + let batch = |id: &str, tool: &str| { + Message::assistant_with_tools(vec![crate::ToolCall { + id: id.into(), + name: tool.into(), + arguments: json!({}), + raw_arguments: None, + }]) + }; + let mut text_result = Message::user("Done".into()); + text_result.role = "tool".into(); + text_result.name = Some("ExecCommand".into()); + text_result.tool_call_id = Some("exec".into()); + let mut messages = vec![ + uploaded(&data), + batch("capture", "view_image"), + tool_result("view_image", &data), + batch("exec", "ExecCommand"), + text_result, + ]; + // Both earlier images have already been seen. This round fits placeholders only. + let context = with_remaining_input(&config, 0, 100); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&messages[0]).is_none()); + assert!(messages[2].tool_image_attachments.is_none()); + assert_eq!(messages[2].tool_call_id.as_deref(), Some("capture")); + assert_eq!(messages[4].content.as_deref(), Some("Done")); +} + +#[test] +fn openai_low_detail_fits_at_the_selected_models_base_cost() { + let mut config = config(); + config.model = "gpt-4o".into(); + let data = png(1024, 1024); + let url = format!("data:image/png;base64,{data}"); + let context = with_remaining_input(&config, 0, 85); + for part in [ + json!({"type":"image_url","image_url":{"url": url,"detail":"low"}}), + json!({"type":"input_image","image_url":url,"detail":"low"}), + ] { + let content = json!([part]).to_string(); + let mut messages = [Message::user(content.clone())]; + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert_eq!(messages[0].content.as_deref(), Some(content.as_str())); + } + let extra = json!({"model":"gpt-4o"}); + config.model = "test-vl".into(); + let mut overridden = [Message::user( + json!([{"type":"image_url","image_url":{"url":url,"detail":"low"}}]).to_string(), + )]; + project(&mut overridden, &config, None, Some(&context), Some(&extra)).unwrap(); + config.custom_request_body_mode = Some("trim".into()); + assert!(project(&mut overridden, &config, None, Some(&context), Some(&extra)).is_err()); + config.model = "gpt-4o".into(); + let mut auto = [uploaded(&data)]; + let error = project(&mut auto, &config, None, Some(&context), None).unwrap_err(); + assert!(error.to_string().contains("Crop the relevant area")); + assert_eq!( + error + .downcast_ref::() + .unwrap() + .category, + openbitfun_core_types::ErrorCategory::InvalidRequest + ); +} + +#[test] +fn gemini_uses_global_resolution_for_projected_images_and_override_parts_on_the_wire() { + let mut config = config(); + config.model = "gemini-3.6-flash".into(); + config.format = "gemini".into(); + let context = with_remaining_input(&config, 0, 600); + let data = png(32, 32); + let messages = vec![Message::user( + json!([{ + "inlineData": {"mimeType": "image/png", "data": data}, + // Normal message conversion drops this field. + "mediaResolution": {"level": "MEDIA_RESOLUTION_LOW"} + }]) + .to_string(), + )]; + assert!(project(&mut messages.clone(), &config, None, Some(&context), None).is_err()); + let global = json!({"generationConfig": {"mediaResolution": "MEDIA_RESOLUTION_MEDIUM"}}); + project( + &mut messages.clone(), + &config, + None, + Some(&context), + Some(&global), + ) + .unwrap(); + + // A raw contents override goes to the provider as written. 1600 input + // tokens allow the default resolution but not an ultra-high image part. + config.context_window = 6000; + config.max_tokens = Some(2400); + let mut raw = json!({ + "generationConfig": {"mediaResolution": "MEDIA_RESOLUTION_MEDIUM"}, + "contents": [{"role":"user", "parts": [{ + "fileData": {"fileUri":"gs://test/screenshot.png", "mimeType":"image/png"}, + "mediaResolution": {"level":"MEDIA_RESOLUTION_ULTRA_HIGH"} + }]}] + }); + assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).is_err()); + raw["contents"][0]["parts"][0] + .as_object_mut() + .unwrap() + .remove("mediaResolution"); + assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).unwrap()); +} + +#[test] +fn current_upload_and_tool_share_remaining_visual_tokens() { + let config = config(); + let data = png(1920, 1080); + let mut messages = vec![uploaded(&data), tool_result("view_image", &data)]; + let remaining = 3000; + let context = with_remaining_input(&config, 0, remaining); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + let user = user_image_size(&messages[0]).expect("current user image kept"); + let tool_image = &messages[1] + .tool_image_attachments + .as_ref() + .expect("current tool image kept")[0]; + let tool = inline_image_dimensions(&tool_image.mime_type, &tool_image.data_base64).unwrap(); + assert!(user.0 >= 512 && tool.0 >= 512); + assert!( + VisionTokenPolicy::for_model("test-vl").estimate(user.0, user.1) + + VisionTokenPolicy::for_model("test-vl").estimate(tool.0, tool.1) + <= remaining + ); + assert_eq!(messages[1].tool_call_id.as_deref(), Some("capture")); +} + +#[test] +fn output_reserve_messages_and_tool_definitions_share_the_input_window() { + let config = config(); + let data = png(640, 640); + let mut messages = vec![uploaded(&data)]; + let context = with_remaining_input(&config, 0, 1); + assert!(project(&mut messages, &config, None, Some(&context), None).is_err()); + + let mut small = config.clone(); + small.context_window = 18000; + small.max_tokens = Some(4000); + let mut messages = vec![ + Message::user("review these details ".repeat(10000)), + uploaded(&data), + ]; + assert!(project(&mut messages, &small, None, None, None).is_err()); + + let tools = [crate::types::ToolDefinition { + name: "lookup".into(), + description: "Look up one of the available entries".into(), + parameters: json!({"type":"string", "enum": (0..5000).map(|index| format!("entry-{index}")).collect::>() }), + }]; + let mut image_only = [uploaded(&data)]; + project(&mut image_only, &small, None, None, None).unwrap(); + assert!(project(&mut image_only, &small, Some(&tools), None, None).is_err()); +} + +#[test] +fn current_computer_use_frame_keeps_its_coordinate_system() { + let config = config(); + let data = png(1920, 1080); + let mut messages = vec![tool_result("ComputerUse", &data)]; + project(&mut messages, &config, None, None, None).unwrap(); + let original = &messages[0].tool_image_attachments.as_ref().unwrap()[0]; + assert_eq!(original.data_base64, data); + assert_eq!( + inline_image_dimensions(&original.mime_type, &original.data_base64), + Some((1920, 1080)) + ); + let context = with_remaining_input(&config, 0, 1200); + assert!(project(&mut messages, &config, None, Some(&context), None).is_err()); + assert_eq!( + messages[0].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); +} + +#[test] +fn resized_native_image_parts_survive_anthropic_and_gemini_serialization() { + use crate::providers::{ + anthropic::message_converter::AnthropicMessageConverter, + gemini::message_converter::GeminiMessageConverter, + }; + + let data = png(1200, 900); + let remaining = 1000; + for (format, part) in [ + ( + "anthropic", + json!({"type":"image", "source":{"type":"base64","media_type":"image/png","data":data}}), + ), + ( + "gemini", + json!({"inline_data":{"mime_type":"image/png","data":data}}), + ), + ( + "gemini", + json!({"inlineData":{"mimeType":"image/png","data":data}}), + ), + ] { + let mut config = config(); + config.format = format.into(); + let context = with_remaining_input(&config, 0, remaining); + let mut messages = vec![Message::user(json!([part]).to_string())]; + project(&mut messages, &config, None, Some(&context), None).unwrap(); + let (encoded, mime_key) = if format == "anthropic" { + let (_, wire) = AnthropicMessageConverter::convert_messages(messages); + (wire[0]["content"][0]["source"].clone(), "media_type") + } else { + let (_, wire) = GeminiMessageConverter::convert_messages(messages, &config.model); + (wire[0]["parts"][0]["inlineData"].clone(), "mimeType") + }; + let mime = encoded[mime_key].as_str().unwrap(); + assert_eq!(mime, "image/png"); + let (w, h) = inline_image_dimensions(mime, encoded["data"].as_str().unwrap()).unwrap(); + assert!(w >= 512 && w < 1200); + assert!(VisionTokenPolicy::for_model("test-vl").estimate(w, h) <= remaining); + } +} + +#[tokio::test] +async fn selected_model_window_controls_pixels_on_the_wire() { + use axum::{routing::post, Json, Router}; + use std::sync::{Arc, Mutex}; + + let observed = Arc::new(Mutex::new(Vec::new())); + let received = observed.clone(); + let app = Router::new().route("/chat/completions", post(move |Json(body): Json| { + let received = received.clone(); + async move { + let data = body["messages"][0]["content"].as_array().unwrap().iter() + .find_map(|part| part["image_url"]["url"].as_str()).unwrap() + .strip_prefix("data:image/png;base64,").unwrap(); + let dimensions = inline_image_dimensions("image/png", data).unwrap(); + received.lock().unwrap().push(dimensions); + let chunk = json!({"id":"test","object":"chat.completion.chunk","created":1,"model":"test-vl", + "choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":"stop"}]}); + ([("content-type", "text/event-stream")], format!("data: {chunk}\n\ndata: [DONE]\n\n")) + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/chat/completions", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut roomy = config(); + roomy.base_url = url.clone(); + roomy.request_url = url; + let mut limited = roomy.clone(); + limited.context_window = 128_000; + let context = with_remaining_input(&limited, 0, 1500); + let impossible = with_remaining_input(&limited, 0, 1); + let messages = vec![uploaded(&png(1920, 1080))]; + for selected in [roomy, limited.clone()] { + crate::AIClient::new(selected) + .send_message_once_with_trace_and_request_context( + messages.clone(), + None, + Some(context.clone()), + None, + ) + .await + .unwrap(); + } + let result = crate::AIClient::new(limited) + .send_message_once_with_trace_and_request_context(messages, None, Some(impossible), None) + .await; + assert!(result.is_err()); + server.abort(); + let requests = observed.lock().unwrap(); + assert_eq!( + requests.len(), + 2, + "the infeasible third request must fail before HTTP" + ); + assert_eq!(requests[0], (1920, 1080)); + let (width, height) = requests[1]; + assert!( + width >= 512 && VisionTokenPolicy::for_model("test-vl").estimate(width, height) <= 1500 + ); +} + +#[test] +fn custom_image_payload_must_fit_the_actual_output_reserve() { + let mut config = config(); + config.context_window = 32_000; + config.max_tokens = Some(8_000); + let native: Value = + serde_json::from_str(uploaded(&png(1024, 1024)).content.as_deref().unwrap()).unwrap(); + let mut body = json!({"messages": [{"role": "user", "content": native}]}); + super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap(); + body["max_completion_tokens"] = json!(21_999); + let error = + super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap_err(); + assert_eq!( + error + .downcast_ref::() + .unwrap() + .category, + openbitfun_core_types::ErrorCategory::InvalidRequest + ); + config.format = "responses".into(); + let native = body["messages"].take(); + let responses = json!({"input": native, "max_output_tokens": 20_500}); + assert!(super::context::validate_override(&config, &[], None, None, Some(&responses)).unwrap()); + let system = Message::system("long instruction ".repeat(500)); + assert!( + super::context::validate_override(&config, &[system], None, None, Some(&responses)) + .is_err() + ); + config.format = "openai".into(); + body["messages"] = json!([{"role":"user","content":"hello"}]); + assert!(super::context::validate_override(&config, &[], None, None, Some(&body)).is_ok()); +} + +#[test] +fn deferred_tool_preserves_only_coordinate_bound_frames() { + let config = config(); + let pixels = png(1800, 900); + let budget = with_remaining_input(&config, 0, 1200); + for (name, should_fit) in [ + ("ComputerUse", false), + ("view_image", true), + ("DocumentPreview", true), + ] { + let call = crate::ToolCall { + id: "capture".into(), + name: "CallDeferredTool".into(), + arguments: json!({"tool_name":name}), + raw_arguments: None, + }; + let mut messages = vec![ + Message::assistant_with_tools(vec![call]), + tool_result("CallDeferredTool", &pixels), + ]; + let result = project(&mut messages, &config, None, Some(&budget), None); + assert_eq!(result.is_ok(), should_fit, "{name}: {result:?}"); + } +} diff --git a/src/crates/adapters/ai-adapters/src/lib.rs b/src/crates/adapters/ai-adapters/src/lib.rs index c7e6c273ec..62e9469792 100644 --- a/src/crates/adapters/ai-adapters/src/lib.rs +++ b/src/crates/adapters/ai-adapters/src/lib.rs @@ -16,6 +16,8 @@ pub mod subscription_auth; pub mod tool_call_accumulator; pub mod trace; pub mod types; +#[cfg(feature = "vision-input")] +pub mod vision_tokens; pub use client::{AIClient, StreamOptions, StreamResponse}; pub use model_selector::{ diff --git a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs index 4803645e84..5c7bc97e2d 100644 --- a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs +++ b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs @@ -385,17 +385,52 @@ impl GeminiMessageConverter { let mut parts = Vec::new(); if let Some(items) = parsed.as_array() { + // Untyped {text: ...} also occurs in ordinary user-supplied JSON. + // Interpret it as a native Gemini part only in a recognized part list. + let user_parts = !is_model_role + && items.iter().any(|item| { + item.get("inline_data").is_some() + || item.get("inlineData").is_some() + || matches!( + item["type"].as_str(), + Some( + "text" + | "input_text" + | "output_text" + | "image" + | "image_url" + | "input_image" + ) + ) + }); for item in items { let item_type = item.get("type").and_then(Value::as_str); match item_type { - Some("text") | Some("input_text") | Some("output_text") => { + Some("text" | "input_text" | "output_text") => { if let Some(text) = item.get("text").and_then(Value::as_str) { if !text.is_empty() { parts.push(json!({ "text": text })); } } } - Some("image_url") if !is_model_role => { + None if user_parts => { + if let Some(inline) = + item.get("inline_data").or_else(|| item.get("inlineData")) + { + let mime = inline + .get("mime_type") + .or_else(|| inline.get("mimeType")) + .and_then(Value::as_str); + if let (Some(mime), Some(data)) = (mime, inline["data"].as_str()) { + parts.push(json!({"inlineData": {"mimeType": mime, "data": data}})); + } + } else if let Some(text) = + item["text"].as_str().filter(|text| !text.is_empty()) + { + parts.push(json!({"text": text})); + } + } + Some("image_url" | "input_image") if !is_model_role => { if let Some(url) = item.get("image_url").and_then(|value| { value .get("url") @@ -885,6 +920,35 @@ mod tests { ); } + #[test] + fn native_user_images_stay_in_order_with_text_on_the_gemini_wire() { + let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1j8AAAAASUVORK5CYII="; + let message = Message::user( + json!([ + {"inline_data": {"mime_type": "image/png", "data": png}}, + {"text": "Compare the two images"}, + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Report the differences"} + ]) + .to_string(), + ); + let (_, contents) = GeminiMessageConverter::convert_messages(vec![message], "gemini"); + assert_eq!( + contents, + vec![json!({"role": "user", "parts": [ + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Compare the two images"}, + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Report the differences"} + ]})] + ); + + let literal = r#"[{"text":"example JSON"}]"#; + let (_, contents) = + GeminiMessageConverter::convert_messages(vec![Message::user(literal.into())], "gemini"); + assert_eq!(contents[0]["parts"], json!([{"text": literal}])); + } + #[test] fn converts_data_url_images_to_inline_data() { let messages = vec![Message { diff --git a/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs b/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs index a0b6e93b54..1d57f679c3 100644 --- a/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs +++ b/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs @@ -1,5 +1,6 @@ //! OpenAI message format converter +use crate::client::format::ApiFormat; use crate::stream::types::responses::OPENAI_RESPONSES_REPLAY_PROTOCOL; use crate::types::{Message, ToolDefinition}; use log::{error, warn}; @@ -9,6 +10,76 @@ use std::collections::{HashMap, HashSet}; pub struct OpenAIMessageConverter; +enum ContentPart<'a> { + Text(&'a str), + ImageUrl { + url: &'a str, + detail: Option<&'a str>, + }, + ImageFile { + id: &'a str, + detail: Option<&'a str>, + }, +} + +impl<'a> ContentPart<'a> { + fn parse(part: &'a Value, role: &str, format: ApiFormat) -> Option { + match part["type"].as_str()? { + "text" | "input_text" | "output_text" => Some(Self::Text(part["text"].as_str()?)), + "image_url" | "input_image" + if role == "user" + || (format == ApiFormat::OpenAIResponses && role != "assistant") => + { + let image = &part["image_url"]; + let detail = image["detail"].as_str().or_else(|| part["detail"].as_str()); + if let Some(url) = image["url"].as_str().or_else(|| image.as_str()) { + return Some(Self::ImageUrl { url, detail }); + } + if format == ApiFormat::OpenAIResponses && part["type"] == "input_image" { + return Some(Self::ImageFile { + id: part["file_id"].as_str()?, + detail, + }); + } + None + } + _ => None, + } + } + + fn wire(self, role: &str, format: ApiFormat) -> Value { + let responses = format == ApiFormat::OpenAIResponses; + let (mut item, detail) = match self { + Self::Text(text) => { + let kind = if responses { + OpenAIMessageConverter::responses_text_item_type(role) + } else { + "text" + }; + return json!({"type": kind, "text": text}); + } + Self::ImageUrl { url, detail } if responses => { + (json!({"type": "input_image", "image_url": url}), detail) + } + Self::ImageUrl { url, detail } => ( + json!({"type": "image_url", "image_url": {"url": url}}), + detail, + ), + Self::ImageFile { id, detail } => { + (json!({"type": "input_image", "file_id": id}), detail) + } + }; + if let Some(detail) = detail { + if responses { + item["detail"] = json!(detail); + } else { + item["image_url"]["detail"] = json!(detail); + } + } + item + } +} + impl OpenAIMessageConverter { pub fn convert_messages_to_responses_input( messages: Vec, @@ -328,12 +399,14 @@ impl OpenAIMessageConverter { } Some( - Self::parse_responses_content_parts(role, content).unwrap_or_else(|| { - vec![json!({ - "type": text_item_type, - "text": content, - })] - }), + Self::parse_content_parts(role, content, ApiFormat::OpenAIResponses).unwrap_or_else( + || { + vec![json!({ + "type": text_item_type, + "text": content, + })] + }, + ), ) } @@ -345,93 +418,24 @@ impl OpenAIMessageConverter { } } - fn parse_responses_content_parts(role: &str, content: &str) -> Option> { - let items = serde_json::from_str::(content) - .ok()? - .as_array()? - .clone(); - if items.is_empty() { - return None; - } - let text_item_type = Self::responses_text_item_type(role); - let mut content_items = Vec::with_capacity(items.len()); - - for item in items { - let item_type = item.get("type").and_then(Value::as_str)?; - match item_type { - "text" | "input_text" | "output_text" => { - let text = item.get("text").and_then(Value::as_str)?; - content_items.push(json!({ - "type": text_item_type, - "text": text, - })); - } - "image_url" if role != "assistant" => { - let image_url = Self::extract_image_url_value(item.get("image_url")?)?; - content_items.push(json!({ - "type": "input_image", - "image_url": image_url, - })); - } - _ => return None, - } - } - - Some(content_items) + #[cfg(feature = "vision-input")] + pub(crate) fn can_render_user_part(part: &Value, format: ApiFormat) -> bool { + ContentPart::parse(part, "user", format).is_some() } - fn parse_chat_completions_content_parts(role: &str, content: &str) -> Option> { - // Tool text is opaque, even when it happens to contain JSON content parts. - // Keeping it a string also works with providers that reject text arrays. + fn parse_content_parts(role: &str, content: &str, format: ApiFormat) -> Option> { + // Tool text is opaque, including JSON that happens to resemble content parts. if role == "tool" { return None; } - let items = serde_json::from_str::(content) - .ok()? - .as_array()? - .clone(); - if items.is_empty() { + let parts: Vec = serde_json::from_str(content).ok()?; + if parts.is_empty() { return None; } - let mut content_items = Vec::with_capacity(items.len()); - - for item in items { - let item_type = item.get("type").and_then(Value::as_str)?; - match item_type { - "text" | "input_text" | "output_text" => { - let text = item.get("text").and_then(Value::as_str)?; - content_items.push(json!({ - "type": "text", - "text": text, - })); - } - "image_url" if role == "user" => { - let image_url_value = item.get("image_url")?; - let image_url = Self::extract_image_url_value(image_url_value)?; - let mut content_item = json!({ - "type": "image_url", - "image_url": { - "url": image_url, - } - }); - if let Some(detail) = image_url_value.get("detail").and_then(Value::as_str) { - content_item["image_url"]["detail"] = Value::String(detail.to_string()); - } - content_items.push(content_item); - } - _ => return None, - } - } - - Some(content_items) - } - - fn extract_image_url_value(value: &Value) -> Option { - value - .get("url") - .and_then(Value::as_str) - .or_else(|| value.as_str()) - .map(ToString::to_string) + parts + .iter() + .map(|part| Some(ContentPart::parse(part, role, format)?.wire(role, format))) + .collect() } fn convert_single_message(mut msg: Message) -> Value { @@ -466,7 +470,7 @@ impl OpenAIMessageConverter { } } else { if let Some(content_parts) = - Self::parse_chat_completions_content_parts(&msg.role, &content) + Self::parse_content_parts(&msg.role, &content, ApiFormat::OpenAIChat) { openai_msg["content"] = Value::Array(content_parts); } else { diff --git a/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs b/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs index bb2eb66b02..700d260e26 100644 --- a/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs +++ b/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs @@ -535,6 +535,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("lineage-1".to_string()), output_schema: None, + ..Default::default() }; let request_body = build_request_body_with_context( &client, @@ -558,6 +559,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: None, output_schema: Some(schema.clone()), + ..Default::default() }; let request_body = build_request_body_with_context( &test_client(), diff --git a/src/crates/adapters/ai-adapters/src/providers/shared.rs b/src/crates/adapters/ai-adapters/src/providers/shared.rs index 173543ee5d..87e161f7f4 100644 --- a/src/crates/adapters/ai-adapters/src/providers/shared.rs +++ b/src/crates/adapters/ai-adapters/src/providers/shared.rs @@ -638,6 +638,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("runtime-lineage".into()), output_schema: Some(serde_json::json!({"type": "object"})), + ..Default::default() }), ] { assert_eq!( @@ -696,6 +697,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some(" ".into()), output_schema: Some(serde_json::json!({"type":"object"})), + ..Default::default() }), Some(ModelRequestContext { conversation_scope: None, @@ -864,6 +866,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some(" ".into()), output_schema: Some(serde_json::json!({"type": "object"})), + ..Default::default() }), ] { let schema = initial diff --git a/src/crates/adapters/ai-adapters/src/vision_tokens.rs b/src/crates/adapters/ai-adapters/src/vision_tokens.rs new file mode 100644 index 0000000000..3057db4e73 --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/vision_tokens.rs @@ -0,0 +1,482 @@ +//! Geometry-based estimates and resizing for inline vision inputs. + +use anyhow::{anyhow, ensure, Context, Result}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use image::codecs::{gif::GifDecoder, jpeg::JpegEncoder, png::PngDecoder, webp::WebPDecoder}; +use image::{ + imageops::FilterType, AnimationDecoder, DynamicImage, GenericImageView, ImageDecoder, + ImageFormat, ImageReader, Limits, +}; +use std::io::Cursor; + +mod openai_patches; +use openai_patches::OpenAiPatches; + +/// Size reserved for path-only history, opaque URLs or unreadable headers. +pub const UNKNOWN_IMAGE_DIMENSIONS: (u32, u32) = (2048, 2048); + +fn grid(width: u32, height: u32, edge: u32) -> u64 { + u64::from(width.div_ceil(edge)) * u64::from(height.div_ceil(edge)) +} + +/// Model-neutral estimate used before the runtime selects a provider. +pub fn estimate_image_tokens(width: u32, height: u32) -> usize { + usize::try_from(50 + 200 * grid(width, height, 512)).unwrap_or(usize::MAX) +} + +/// Estimates for known vision processors. A custom model ID retains the +/// model-neutral tile estimate when its processor is unknown. +#[derive(Clone, Copy)] +pub(crate) enum VisionTokenPolicy { + Generic, + OpenAiTiles { base: u64, tile: u64 }, + OpenAiPatches(OpenAiPatches), + Fixed(u64), + Gemini(u64), + Claude { max_edge: u32, max_tokens: u64 }, + Patches { edge: u32, max: u64, percent: u64 }, +} + +impl VisionTokenPolicy { + pub(crate) fn for_model(model: &str) -> Self { + let name = model + .rsplit('/') + .next() + .unwrap_or(model) + .to_ascii_lowercase(); + // OpenAI snapshot names end in a date, e.g. gpt-4o-2024-08-06. + let family = name.split_once("-20").map_or(name.as_str(), |(id, _)| id); + if let Some(patches) = OpenAiPatches::for_model(family) { + return Self::OpenAiPatches(patches); + } + match family { + // https://developers.openai.com/api/docs/guides/images-vision + "gpt-4.1" | "gpt-4o" => Self::OpenAiTiles { + base: 85, + tile: 170, + }, + "gpt-4o-mini" => Self::OpenAiTiles { + base: 2833, + tile: 5667, + }, + "gpt-5" | "gpt-5.1" => Self::OpenAiTiles { + base: 70, + tile: 140, + }, + "o1" | "o1-pro" | "o3" => Self::OpenAiTiles { + base: 75, + tile: 150, + }, + "gpt-4.1-nano" | "o4-mini" => { + let percent = if family == "gpt-4.1-nano" { 246 } else { 172 }; + Self::Patches { + edge: 32, + max: 1536, + percent, + } + } + // A patch upper bound before any deployment-specific resize. + // https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct + id if id.starts_with("qwen2.5-vl") || id.starts_with("qwen2-vl") => Self::Patches { + edge: 28, + max: u64::MAX, + percent: 100, + }, + // https://ai.google.dev/gemini-api/docs/media-resolution + id if id.starts_with("gemini-3.") + || id.starts_with("gemini-3-") + || id.starts_with("gemini-4.") + || id.starts_with("gemini-4-") => + { + Self::Gemini(1120) + } + // https://platform.claude.com/docs/en/build-with-claude/vision + id if id.starts_with("claude-") => { + let id = id.strip_suffix("-latest").unwrap_or(id); + let standard = id.starts_with("claude-3-") + || matches!( + id, + "claude-opus-4" + | "claude-sonnet-4" + | "claude-opus-4-1" + | "claude-opus-4-5" + | "claude-sonnet-4-5" + | "claude-haiku-4-5" + | "claude-opus-4-6" + | "claude-sonnet-4-6" + ); + let (max_edge, max_tokens) = if standard { (1568, 1568) } else { (2576, 4784) }; + Self::Claude { + max_edge, + max_tokens, + } + } + _ => Self::Generic, + } + } + + pub(crate) fn with_detail(self, detail: Option<&str>) -> Self { + match (self, detail) { + (Self::OpenAiPatches(patches), detail) => { + Self::OpenAiPatches(patches.with_detail(detail)) + } + (Self::OpenAiTiles { base, .. }, Some("low")) => Self::Fixed(base), + _ => self, + } + } + + pub(crate) fn with_gemini_media_resolution(self, resolution: Option<&str>) -> Self { + if !matches!(self, Self::Gemini(_)) { + return self; + } + match resolution { + Some("MEDIA_RESOLUTION_LOW") => Self::Gemini(280), + Some("MEDIA_RESOLUTION_MEDIUM") => Self::Gemini(560), + Some("MEDIA_RESOLUTION_HIGH" | "MEDIA_RESOLUTION_UNSPECIFIED") => Self::Gemini(1120), + Some("MEDIA_RESOLUTION_ULTRA_HIGH") => Self::Gemini(2240), + _ => self, + } + } + + pub(crate) fn estimate(self, width: u32, height: u32) -> usize { + let cost = match self { + Self::Generic => return estimate_image_tokens(width, height), + Self::OpenAiPatches(patches) => patches.estimate(width, height), + Self::Fixed(tokens) | Self::Gemini(tokens) => tokens, + Self::Claude { + max_edge, + max_tokens, + } => { + let longest = width.max(height); + let (w, h) = scale_long_edge(width, height, longest.min(max_edge)); + grid(w, h, 28).min(max_tokens) + } + + Self::Patches { edge, max, percent } => { + (grid(width, height, edge).min(max) * percent).div_ceil(100) + } + Self::OpenAiTiles { base, tile } => { + let scale = (2048.0 / f64::from(width.max(height))) + .min(768.0 / f64::from(width.min(height))) + .min(1.0); + let resize = |side| ((f64::from(side) * scale) as u32).max(1); + base + tile * grid(resize(width), resize(height), 512) + } + }; + usize::try_from(cost).unwrap_or(usize::MAX) + } +} + +/// Read header metadata without decoding a pixel buffer. Most screenshots and +/// photos expose dimensions near the start, even when their payload is large. +pub fn inline_image_dimensions(mime_type: &str, data_base64: &str) -> Option<(u32, u32)> { + let format = ImageFormat::from_mime_type(mime_type)?; + let dimensions = |bytes: &[u8]| { + ImageReader::with_format(Cursor::new(bytes), format) + .into_dimensions() + .ok() + .filter(|&(w, h)| w > 0 && h > 0) + }; + let encoded = data_base64.as_bytes(); + const PREFIX: usize = 4096; // Complete base64 quartets. + if encoded.len() > PREFIX { + if let Some(size) = dimensions(&STANDARD.decode(&encoded[..PREFIX]).ok()?) { + return Some(size); + } + } + dimensions(&STANDARD.decode(encoded).ok()?) +} + +pub(crate) struct ResizedInlineImage { + pub mime_type: String, + pub data_base64: String, + pub width: u32, + pub height: u32, +} + +fn scale_long_edge(width: u32, height: u32, edge: u32) -> (u32, u32) { + let longest = u64::from(width.max(height).max(1)); + let scale = |side| ((u64::from(side) * u64::from(edge) + longest / 2) / longest).max(1) as u32; + (scale(width), scale(height)) +} + +impl VisionTokenPolicy { + /// Reserve a preview with a 512-pixel long edge, or the entire smaller input. + pub(crate) fn min_readable_tokens(self, width: u32, height: u32) -> usize { + let (w, h) = scale_long_edge(width, height, width.max(height).min(512)); + self.estimate(w, h) + } + + /// Find the largest proportional pixel dimensions that fit before resampling. + fn fit_dimensions(self, width: u32, height: u32, budget: usize) -> Result<(u32, u32)> { + let minimum = self.min_readable_tokens(width, height); + ensure!( + budget >= minimum, + "A readable image preview needs at least {minimum} estimated tokens; {budget} available. Crop the image or shorten the context." + ); + let longest = width.max(height); + let (mut lo, mut hi) = (longest.min(512), longest); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + let (w, h) = scale_long_edge(width, height, mid); + if self.estimate(w, h) <= budget { + lo = mid; + } else { + hi = mid - 1; + } + } + Ok(scale_long_edge(width, height, lo)) + } +} + +/// Avoid silently substituting one animation frame for an entire visual input. +fn decode_still( + bytes: &[u8], + format: ImageFormat, +) -> Result<(DynamicImage, image::metadata::Orientation)> { + let input = Cursor::new(bytes); + let mut decoder: Box = match format { + ImageFormat::Png => { + let png = PngDecoder::with_limits(input, Limits::default())?; + ensure!( + !png.is_apng()?, + "Cannot resize an animated PNG as a still image" + ); + Box::new(png) + } + ImageFormat::WebP => { + let webp = WebPDecoder::new(input)?; + ensure!( + !webp.has_animation(), + "Cannot resize an animated WebP as a still image" + ); + Box::new(webp) + } + ImageFormat::Gif => { + let mut gif = GifDecoder::new(input)?; + gif.set_limits(Limits::default())?; + let mut frames = gif.into_frames(); + let first = frames.next().context("GIF has no frames")??; + ensure!( + frames.next().transpose()?.is_none(), + "Cannot resize an animated GIF as a still image" + ); + return Ok(( + first.into_buffer().into(), + image::metadata::Orientation::NoTransforms, + )); + } + ImageFormat::Jpeg | ImageFormat::Bmp => { + Box::new(ImageReader::with_format(input, format).into_decoder()?) + } + _ => anyhow::bail!("Unsupported inline image format {format:?}"), + }; + let orientation = decoder.orientation()?; + let mut limits = Limits::default(); + limits.reserve(decoder.total_bytes())?; + decoder.set_limits(limits)?; + Ok((DynamicImage::from_decoder(decoder)?, orientation)) +} + +impl VisionTokenPolicy { + /// Resize only the outgoing image, retaining text edges and transparency. + pub(crate) fn resize( + self, + mime_type: &str, + data_base64: &str, + target_tokens: usize, + ) -> Result { + let format = ImageFormat::from_mime_type(mime_type) + .ok_or_else(|| anyhow!("Unsupported inline image type {mime_type}"))?; + let (width, height) = inline_image_dimensions(mime_type, data_base64) + .context("Cannot read inline image dimensions")?; + if self.estimate(width, height) <= target_tokens { + return Ok(ResizedInlineImage { + mime_type: mime_type.to_owned(), + data_base64: data_base64.to_owned(), + width, + height, + }); + } + let (w, h) = self.fit_dimensions(width, height, target_tokens)?; + let bytes = STANDARD + .decode(data_base64) + .context("Invalid inline image base64")?; + let (source, orientation) = decode_still(&bytes, format)?; + let mut resized = source.resize_exact(w, h, FilterType::Lanczos3); + resized.apply_orientation(orientation); + let (width, height) = resized.dimensions(); + let mut output = Cursor::new(Vec::new()); + let output_format = match format { + ImageFormat::Jpeg => { + JpegEncoder::new_with_quality(&mut output, 90).encode_image(&resized)?; + ImageFormat::Jpeg + } + _ => { + let format = if format == ImageFormat::WebP { + ImageFormat::WebP + } else { + ImageFormat::Png + }; + resized.write_to(&mut output, format)?; + format + } + }; + Ok(ResizedInlineImage { + mime_type: output_format.to_mime_type().to_owned(), + data_base64: STANDARD.encode(output.into_inner()), + width, + height, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selected_model_and_image_detail_determine_the_visual_estimate() { + let tiles = VisionTokenPolicy::for_model("openai/gpt-4o-2024-08-06"); + assert_eq!(tiles.estimate(2048, 2048), 765); + assert_eq!(tiles.with_detail(Some("low")).estimate(2048, 2048), 85); + assert_eq!( + VisionTokenPolicy::for_model("gpt-4o-mini").estimate(512, 512), + 8500 + ); + assert_eq!( + VisionTokenPolicy::for_model("gpt-4.1-mini").estimate(1024, 1024), + 1659 + ); + assert_eq!( + VisionTokenPolicy::for_model("Qwen/Qwen2.5-VL-7B-Instruct").estimate(280, 560), + 200 + ); + assert_eq!( + VisionTokenPolicy::for_model("custom").estimate(2048, 2048), + 3250 + ); + } + + #[test] + fn openai_patch_models_apply_their_own_detail_defaults_and_patch_limits() { + let astra = VisionTokenPolicy::for_model("openai/gpt-6-astra-2026-01-01"); + assert_eq!(astra.estimate(2048, 2048), 4916); + assert_eq!(astra.with_detail(Some("auto")).estimate(2048, 2048), 4916); + assert_eq!(astra.with_detail(Some("low")).estimate(2048, 2048), 308); + assert_eq!(astra.with_detail(Some("high")).estimate(2048, 2048), 3000); + assert_eq!(astra.with_detail(Some("high")).estimate(4096, 512), 2458); + + for name in ["gpt-5.4", "gpt-5.4-mini"] { + let policy = VisionTokenPolicy::for_model(name); + assert_eq!(policy.estimate(2048, 2048), 3000); + assert_eq!(policy.with_detail(Some("low")).estimate(2048, 2048), 4916); + assert_eq!( + policy.with_detail(Some("original")).estimate(4096, 4096), + 12_000 + ); + // 2048x1536 exceeds 2500 patches. The scaled grid is 57x43. + assert_eq!(policy.estimate(2048, 1536), 2942); + } + let mini = VisionTokenPolicy::for_model("gpt-4.1-mini-2025-04-14"); + for detail in ["low", "high", "auto"] { + assert_eq!(mini.with_detail(Some(detail)).estimate(4096, 4096), 6636); + } + } + + #[test] + fn gemini_resolution_and_claude_tiers_bound_visual_tokens() { + for model in ["gemini-3.6-flash", "gemini-4-hydrogen"] { + let policy = VisionTokenPolicy::for_model(model); + assert_eq!(policy.estimate(32, 32), 1120); + for (level, expected) in [ + ("MEDIA_RESOLUTION_LOW", 280), + ("MEDIA_RESOLUTION_MEDIUM", 560), + ("MEDIA_RESOLUTION_HIGH", 1120), + ("MEDIA_RESOLUTION_ULTRA_HIGH", 2240), + ] { + assert_eq!( + policy + .with_gemini_media_resolution(Some(level)) + .estimate(2048, 1024), + expected + ); + } + } + let standard = VisionTokenPolicy::for_model("claude-haiku-4-5-20251001"); + assert_eq!(standard.estimate(4000, 4000), 1568); + assert_eq!(standard.estimate(8192, 128), 56); + let high = VisionTokenPolicy::for_model("claude-sonnet-5"); + assert_eq!(high.estimate(3840, 2160), 4784); + assert_eq!(high.estimate(1000, 1000), 1296); + } + + #[test] + fn oversized_screenshot_fits_at_largest_resolution_and_retains_alpha() { + let source = DynamicImage::new_rgba8(2048, 1024); + let mut bytes = Cursor::new(Vec::new()); + source.write_to(&mut bytes, ImageFormat::Png).unwrap(); + let data = STANDARD.encode(bytes.into_inner()); + assert_eq!( + inline_image_dimensions("image/png", &data), + Some((2048, 1024)) + ); + let budget = estimate_image_tokens(1024, 512); + let projected = VisionTokenPolicy::Generic + .resize("image/png", &data, budget) + .unwrap(); + assert!(estimate_image_tokens(projected.width, projected.height) <= budget); + assert!( + estimate_image_tokens(projected.width + 1, (projected.width + 1).div_ceil(2)) > budget + ); + let decoded = + image::load_from_memory(&STANDARD.decode(projected.data_base64).unwrap()).unwrap(); + assert_eq!(decoded.dimensions(), (projected.width, projected.height)); + assert_eq!(decoded.to_rgba8().get_pixel(0, 0)[3], 0); + let original = VisionTokenPolicy::Generic + .resize("image/png", &data, usize::MAX) + .unwrap(); + assert_eq!(original.data_base64, data); + } + + #[test] + fn invalid_input_and_infeasible_budgets_are_explicit() { + assert!(inline_image_dimensions("image/png", "@@").is_none()); + assert!(VisionTokenPolicy::Generic + .resize("image/png", "@@", 1000) + .is_err()); + assert!(VisionTokenPolicy::Generic + .fit_dimensions( + 1024, + 1024, + VisionTokenPolicy::Generic.min_readable_tokens(1024, 1024) - 1 + ) + .is_err()); + assert_eq!( + VisionTokenPolicy::Generic + .fit_dimensions(1, 10000, estimate_image_tokens(1, 512)) + .unwrap(), + (1, 512) + ); + } + + #[test] + fn shrinking_an_animation_does_not_silently_send_one_frame() { + let mut bytes = Vec::new(); + let frame = image::Frame::new(image::RgbaImage::new(640, 64)); + image::codecs::gif::GifEncoder::new(&mut bytes) + .encode_frames([frame.clone(), frame]) + .unwrap(); + let data = STANDARD.encode(bytes); + let budget = VisionTokenPolicy::Generic.min_readable_tokens(640, 64); + let error = VisionTokenPolicy::Generic + .resize("image/gif", &data, budget) + .err() + .expect("resizing an animated image must fail explicitly"); + assert!(error.to_string().contains("animated GIF")); + let original = VisionTokenPolicy::Generic + .resize("image/gif", &data, usize::MAX) + .unwrap(); + assert_eq!(original.data_base64, data); + } +} diff --git a/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs b/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs new file mode 100644 index 0000000000..12e131063e --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs @@ -0,0 +1,104 @@ +//! OpenAI's patch-based model sizing table and 32-pixel patch calculation. +//! https://developers.openai.com/api/docs/guides/images-vision#model-sizing-behavior + +use super::{grid, scale_long_edge}; + +#[derive(Clone, Copy)] +enum Family { + Astra6, + Gpt56, + Gpt55, + Gpt54, + Gpt52, + Gpt41Mini, +} + +#[derive(Clone, Copy)] +enum Detail { + Low, + High, + Original, +} + +#[derive(Clone, Copy)] +pub(crate) struct OpenAiPatches { + family: Family, + detail: Detail, +} + +impl OpenAiPatches { + pub(super) fn for_model(model: &str) -> Option { + use Family::*; + let family = match model { + "gpt-6-astra" => Astra6, + "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna" => Gpt56, + "gpt-5.5" => Gpt55, + "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-nano" => Gpt54, + "gpt-5.2" => Gpt52, + "gpt-4.1-mini" => Gpt41Mini, + _ => return None, + }; + let detail = match family { + Astra6 | Gpt56 | Gpt55 => Detail::Original, + Gpt54 | Gpt52 | Gpt41Mini => Detail::High, + }; + Some(Self { family, detail }) + } + + pub(super) fn with_detail(mut self, detail: Option<&str>) -> Self { + self.detail = match detail { + Some("low") => Detail::Low, + Some("high") => Detail::High, + Some("original") => Detail::Original, + _ => return self, + }; + self + } + + pub(super) fn estimate(self, width: u32, height: u32) -> u64 { + use Detail::*; + use Family::*; + let (max_edge, patch_budget) = match (self.family, self.detail) { + (Gpt52 | Gpt41Mini, _) | (Gpt54, Low) => (2048, 6144), + (_, Low) => (512, 256), + (Astra6, High) => (65_535, 2500), + (_, High) => (2048, 2500), + (Gpt54 | Gpt55, Original) => (6000, 10_000), + // This detail has no automatic patch-budget resize. In particular, + // do not cap the estimate at the provider's separate rejection limit. + (Astra6 | Gpt56, Original) => (65_535, u64::MAX), + }; + let patches = resized_patches(width, height, max_edge, patch_budget); + let percent = if matches!(self.family, Gpt41Mini) { + 162 + } else { + 120 + }; + (patches * percent).div_ceil(100) + } +} + +fn resized_patches(width: u32, height: u32, max_edge: u32, budget: u64) -> u64 { + let (width, height) = if width.max(height) > max_edge { + scale_long_edge(width, height, max_edge) + } else { + (width, height) + }; + let patches = grid(width, height, 32); + if patches <= budget { + return patches; + } + + // Scale to the target area, then snap the tighter axis to a whole patch. + let width = f64::from(width); + let height = f64::from(height); + let scale = ((budget as f64 * 32.0 * 32.0) / (width * height)).sqrt(); + let scaled_w = width * scale / 32.0; + let scaled_h = height * scale / 32.0; + if scaled_w < 1.0 || scaled_h < 1.0 { + // A panorama still needs one patch along its short axis. + return budget; + } + let scale = (scaled_w.floor() * 32.0 / width).min(scaled_h.floor() * 32.0 / height); + grid((width * scale) as u32, (height * scale) as u32, 32).min(budget) +} diff --git a/src/crates/assembly/core/Cargo.toml b/src/crates/assembly/core/Cargo.toml index 7867d6db7f..881a24db4d 100644 --- a/src/crates/assembly/core/Cargo.toml +++ b/src/crates/assembly/core/Cargo.toml @@ -214,6 +214,7 @@ agent-runtime = [ "openbitfun-services-core/session-event-format", "ai-adapter-runtime", "openbitfun-ai-adapters/local-tokenizer", + "openbitfun-ai-adapters/vision-input", "dep:openbitfun-agent-runtime", "openbitfun-agent-runtime/agent-runtime", "dep:openbitfun-agent-content", diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index a93f68512c..27438dd9b1 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -7187,6 +7187,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet } else { Vec::new() }; + let current_turn_start = image_input_messages.len(); image_input_messages.extend(additional_prepended_messages.iter().cloned()); image_input_messages.extend( wrapped_user_input_payload @@ -7211,6 +7212,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet ); let image_requirement = ExecutionEngine::resolve_image_input_requirement( &image_input_messages, + current_turn_start, session.config.enable_tools, &image_tool_context, ) diff --git a/src/crates/assembly/core/src/agentic/core/message.rs b/src/crates/assembly/core/src/agentic/core/message.rs index 47fbbdf4ff..e38f3f3195 100644 --- a/src/crates/assembly/core/src/agentic/core/message.rs +++ b/src/crates/assembly/core/src/agentic/core/message.rs @@ -3,6 +3,9 @@ use crate::util::types::{Message as AIMessage, ToolCall as AIToolCall, ToolImage use crate::util::TokenCounter; use log::warn; use openbitfun_agent_runtime::prompt_markup::is_system_reminder_only; +use openbitfun_ai_adapters::vision_tokens::{ + estimate_image_tokens, inline_image_dimensions, UNKNOWN_IMAGE_DIMENSIONS, +}; use openbitfun_core_types::{ModelResponseReplay, ReasoningContentKind}; pub use openbitfun_runtime_ports::{CompressionContract, CompressionContractItem}; use serde::{Deserialize, Serialize}; @@ -694,37 +697,54 @@ impl Message { tokens } - fn estimate_image_tokens(metadata: Option<&serde_json::Value>) -> usize { - let (width, height) = metadata - .and_then(|m| { - let w = m.get("width").and_then(|v| v.as_u64()); - let h = m.get("height").and_then(|v| v.as_u64()); - match (w, h) { - (Some(w), Some(h)) if w > 0 && h > 0 => Some((w as u32, h as u32)), - _ => None, - } - }) - .unwrap_or((1024, 1024)); + fn user_image_dimensions(image: &ImageContextData) -> Option<(u32, u32)> { + if let Some(size) = image + .data_url + .as_deref() + .and_then(|url| url.split_once(',')) + .and_then(|(_, data)| inline_image_dimensions(&image.mime_type, data)) + { + return Some(size); + } - let tiles_w = width.div_ceil(512); - let tiles_h = height.div_ceil(512); - let tiles = (tiles_w.max(1) * tiles_h.max(1)) as usize; - 50 + tiles * 200 + // Path-only images may live on another host. Use their saved dimensions. + let metadata = image.metadata.as_ref()?; + let dimension = |key: &str| { + u32::try_from(metadata.get(key)?.as_u64()?) + .ok() + .filter(|&size| size > 0) + }; + Some((dimension("width")?, dimension("height")?)) } pub fn estimate_tokens_with_reasoning(&self, include_reasoning: bool) -> usize { - let mut total = 0usize; - total += 4; + let text_tokens = self.estimate_non_image_tokens_with_reasoning(include_reasoning); + let add_image = |total: usize, dimensions: Option<(u32, u32)>| { + let (width, height) = dimensions.unwrap_or(UNKNOWN_IMAGE_DIMENSIONS); + total.saturating_add(estimate_image_tokens(width, height)) + }; + match &self.content { + MessageContent::Multimodal { images, .. } => images + .iter() + .map(Self::user_image_dimensions) + .fold(text_tokens, add_image), + MessageContent::ToolResult { + image_attachments: Some(images), + .. + } => images + .iter() + .map(|image| inline_image_dimensions(&image.mime_type, &image.data_base64)) + .fold(text_tokens, add_image), + _ => text_tokens, + } + } + + pub fn estimate_non_image_tokens_with_reasoning(&self, include_reasoning: bool) -> usize { + let mut total = 4; match &self.content { - MessageContent::Text(text) => { - total += TokenCounter::estimate_tokens(text); - } - MessageContent::Multimodal { text, images } => { + MessageContent::Text(text) | MessageContent::Multimodal { text, .. } => { total += TokenCounter::estimate_tokens(text); - for image in images { - total += Self::estimate_image_tokens(image.metadata.as_ref()); - } } MessageContent::Mixed { reasoning_content, @@ -756,7 +776,6 @@ impl Message { tool_name, result, result_for_assistant, - image_attachments, .. } => { if let Some(text) = result_for_assistant.as_ref().filter(|s| !s.is_empty()) { @@ -766,11 +785,6 @@ impl Message { } else { total += TokenCounter::estimate_tokens(tool_name); } - if let Some(imgs) = image_attachments { - for _ in imgs { - total += Self::estimate_image_tokens(None); - } - } } } @@ -842,6 +856,60 @@ mod tests { }; use serde_json::json; + #[test] + fn restored_tool_results_and_inline_uploads_use_the_encoded_image_dimensions() { + use super::{ImageContextData, ToolImageAttachment, ToolResult}; + use base64::{engine::general_purpose::STANDARD, Engine}; + use std::io::Cursor; + + for (size, expected_tokens) in [(512, 250), (2048, 3250)] { + let mut png = Cursor::new(Vec::new()); + image::DynamicImage::new_luma8(size, size) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + let data = STANDARD.encode(png.into_inner()); + let user = Message::user_multimodal( + "Screenshot".into(), + vec![ImageContextData { + id: "screenshot".into(), + image_path: None, + data_url: Some(format!("data:image/png;base64,{data}")), + mime_type: "image/png".into(), + metadata: None, + }], + ); + let mut result = ToolResult { + tool_id: "call".into(), + tool_name: "view_image".into(), + effective_tool_name: None, + result: json!({}), + result_for_assistant: Some("Screenshot".into()), + is_error: false, + duration_ms: None, + image_attachments: None, + }; + let text_tokens = + Message::tool_result(result.clone()).estimate_tokens_with_reasoning(false); + result.image_attachments = Some(vec![ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: data, + }]); + + let stored = serde_json::to_value(Message::tool_result(result)).unwrap(); + let restored: Message = serde_json::from_value(stored).unwrap(); + for message in [user, restored] { + assert_eq!( + message.estimate_non_image_tokens_with_reasoning(false), + text_tokens + ); + assert_eq!( + message.estimate_tokens_with_reasoning(false) - text_tokens, + expected_tokens + ); + } + } + } + #[test] fn ptc_specs_and_routed_execution_metadata_round_trip_together_with_legacy_defaults() { let mut message = Message::assistant("Synthetic reply".into()); diff --git a/src/crates/assembly/core/src/agentic/core/messages_helper.rs b/src/crates/assembly/core/src/agentic/core/messages_helper.rs index 58d4b9a52d..195f6892e9 100644 --- a/src/crates/assembly/core/src/agentic/core/messages_helper.rs +++ b/src/crates/assembly/core/src/agentic/core/messages_helper.rs @@ -71,6 +71,20 @@ impl MessageHelper { messages: &[Message], tools: Option<&[ToolDefinition]>, reasoning_policy: RequestReasoningTokenPolicy, + ) -> usize { + Self::estimate_request_tokens_with( + messages, + tools, + reasoning_policy, + Message::estimate_tokens_with_reasoning, + ) + } + + pub(crate) fn estimate_request_tokens_with( + messages: &[Message], + tools: Option<&[ToolDefinition]>, + reasoning_policy: RequestReasoningTokenPolicy, + estimate_message: fn(&Message, bool) -> usize, ) -> usize { let reasoning_frontier_start = match reasoning_policy { RequestReasoningTokenPolicy::FullHistory => Some(0), @@ -86,7 +100,7 @@ impl MessageHelper { .map(|(index, message)| { let include_reasoning = reasoning_frontier_start.is_some_and(|frontier_start| index >= frontier_start); - message.estimate_tokens_with_reasoning(include_reasoning) + estimate_message(message, include_reasoning) }) .sum::(); diff --git a/src/crates/assembly/core/src/agentic/execution/compression_job.rs b/src/crates/assembly/core/src/agentic/execution/compression_job.rs index f6b4967c45..c423cb99ea 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_job.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_job.rs @@ -220,7 +220,7 @@ impl CompressionJob { } async fn request_summary(&self, messages: &[Message]) -> OpenBitFunResult { - let mut messages = ExecutionEngine::build_ai_messages_for_send( + let (mut messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( messages, &self.client.config.format, self.workspace.as_ref(), @@ -244,11 +244,15 @@ impl CompressionJob { ); } messages.push(AIMessage::user(self.compressor.build_compact_prompt())); + let context = ModelRequestContext { + image_turn_start: Some(image_turn_start), + ..self.request_context.clone() + }; super::super::compression_request::request_summary( self.client.clone(), messages, self.tools.clone(), - &self.request_context, + &context, self.trace.clone(), ) .await diff --git a/src/crates/assembly/core/src/agentic/execution/context_budget.rs b/src/crates/assembly/core/src/agentic/execution/context_budget.rs index cfbab0b502..a472266e26 100644 --- a/src/crates/assembly/core/src/agentic/execution/context_budget.rs +++ b/src/crates/assembly/core/src/agentic/execution/context_budget.rs @@ -1,7 +1,7 @@ //! Input admission budgets shared by ordinary requests and pool routing. -use crate::service::config::types::automatic_max_output_tokens; use openbitfun_core_types::model_pool::ModelPoolContextBudget; +use openbitfun_core_types::token_estimate::{automatic_max_output_tokens, INPUT_SAFETY_RESERVE}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct CompressionTriggerBudget { @@ -12,8 +12,6 @@ pub(super) struct CompressionTriggerBudget { } impl CompressionTriggerBudget { - const SAFETY_RESERVE_TOKENS: usize = 10_000; - /// The active model or pool owns the request budget. Persisted session /// windows can describe a previous model or a legacy creation default. pub(super) fn for_request( @@ -30,7 +28,7 @@ impl CompressionTriggerBudget { let output_reserve_tokens = configured_max_tokens .map(|value| value as usize) .unwrap_or_else(|| automatic_max_output_tokens(context_window as u32) as usize); - let safety_reserve_tokens = Self::SAFETY_RESERVE_TOKENS; + let safety_reserve_tokens = INPUT_SAFETY_RESERVE; Self { context_window, input_limit: context_window @@ -43,7 +41,7 @@ impl CompressionTriggerBudget { pub(super) fn for_pool(budget: ModelPoolContextBudget) -> Self { let context_window = budget.context_window as usize; let input_limit = budget.input_limit as usize; - let safety_reserve_tokens = Self::SAFETY_RESERVE_TOKENS.min(context_window); + let safety_reserve_tokens = INPUT_SAFETY_RESERVE.min(context_window); Self { context_window, input_limit, diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs index 73cebf8205..d7b6e7ab00 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs @@ -747,6 +747,7 @@ impl ExecutionEngine { output_schema: context .get(openbitfun_runtime_ports::OUTPUT_SCHEMA_CONTEXT_KEY) .and_then(|schema| serde_json::from_str(schema).ok()), + ..Default::default() } } @@ -839,16 +840,18 @@ impl ExecutionEngine { messages: &[Message], tools: Option<&[ToolDefinition]>, ) -> usize { - MessageHelper::estimate_request_tokens( + MessageHelper::estimate_request_tokens_with( messages, tools, RequestReasoningTokenPolicy::LatestTurnOnly, + Message::estimate_non_image_tokens_with_reasoning, ) } /// Estimate request pressure for compression decisions. /// - /// `total_tokens` tracks the whole provider request input. The snapshot also + /// Pixels can be resized or omitted on the outgoing request. Only text pressure + /// warrants compressing the durable conversation. The snapshot also /// keeps the mutable conversation portion and fixed scaffold overhead /// available for diagnostics, while the trigger decision reserves output and /// safety budget from the full context window. @@ -996,7 +999,7 @@ impl ExecutionEngine { fn estimate_tail_tokens(messages: &[Message]) -> usize { messages .iter() - .map(|message| message.estimate_tokens_with_reasoning(true)) + .map(|message| message.estimate_non_image_tokens_with_reasoning(true)) .sum() } @@ -1226,7 +1229,7 @@ impl ExecutionEngine { .unwrap_or(0); let preserved_tokens: usize = preserved .iter() - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum::() + tool_tokens + prepended_reminder_tokens @@ -1237,13 +1240,13 @@ impl ExecutionEngine { + rounds .iter() .flat_map(|r| r.iter()) - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum::(); while total_tokens > context_window && kept_start < rounds.len() { let round_tokens: usize = rounds[kept_start] .iter() - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum(); total_tokens -= round_tokens; kept_start += 1; @@ -1954,10 +1957,12 @@ impl ExecutionEngine { /// checked separately by ImageInputRequirement::validate. pub(crate) async fn resolve_image_input_requirement( messages: &[Message], + current_turn_start: usize, tools_enabled: bool, tool_context: &ToolUseContext, ) -> ImageInputRequirement { - let requirement = Self::image_input_requirement(messages, tools_enabled); + let requirement = + Self::image_input_requirement(messages, current_turn_start, tools_enabled); if requirement != ImageInputRequirement::NativeOrAnalysisTool { return requirement; } @@ -1991,7 +1996,7 @@ impl ExecutionEngine { .iter() .chain(&visible.deferred_tools) .any(|tool| tool.name() == "analyze_image"); - Self::image_input_requirement(messages, analysis_available) + Self::image_input_requirement(messages, current_turn_start, analysis_available) } pub(crate) async fn resolve_model_id_for_turn( @@ -2168,7 +2173,10 @@ impl ExecutionEngine { attach_images: bool, ) -> openbitfun_core_types::UsageContextBreakdown { let kept_images = if attach_images { - Self::image_bearing_indices_to_keep(messages) + Self::image_bearing_indices_to_keep( + messages, + Self::image_turn_start(messages, current_turn_id), + ) } else { HashSet::new() }; @@ -2212,6 +2220,16 @@ impl ExecutionEngine { ) } + /// Provider usage for a prefix containing pixels cannot be split after the fact. + /// Earlier text-only anchors still calibrate the estimate of the remaining text. + fn text_only_anchor_prefix(messages: &[Message]) -> &[Message] { + let end = messages + .iter() + .position(Self::message_bears_images) + .unwrap_or(messages.len()); + &messages[..end] + } + /// True if this message would contribute at least one image to the model (before pruning). fn message_bears_images(msg: &Message) -> bool { if Self::skip_message_for_model_send(msg) { @@ -2246,9 +2264,10 @@ impl ExecutionEngine { pub(crate) fn image_input_requirement( messages: &[Message], + current_turn_start: usize, analysis_tool_available: bool, ) -> ImageInputRequirement { - let retained = Self::image_bearing_indices_to_keep(messages); + let retained = Self::image_bearing_indices_to_keep(messages, current_turn_start); if retained.is_empty() { return ImageInputRequirement::None; } @@ -2265,8 +2284,22 @@ impl ExecutionEngine { } } - /// Indices of the image-bearing messages that should keep image payloads. - fn image_bearing_indices_to_keep(messages: &[Message]) -> HashSet { + fn image_turn_start(messages: &[Message], current_turn_id: &str) -> usize { + messages + .iter() + .position(|message| { + message.metadata.turn_id.as_deref() == Some(current_turn_id) + && !Self::skip_message_for_model_send(message) + }) + .unwrap_or(messages.len()) + } + + /// History pixels are elided in cache-stable batches. Active-turn pixels + /// are kept for the selected model's outgoing token budget. + fn image_bearing_indices_to_keep( + messages: &[Message], + current_turn_start: usize, + ) -> HashSet { let with_images: Vec = messages .iter() .enumerate() @@ -2274,7 +2307,13 @@ impl ExecutionEngine { .map(|(i, _)| i) .collect(); let elided = Self::elided_image_message_count(with_images.len()); - with_images[elided..].iter().copied().collect() + with_images + .into_iter() + .enumerate() + .filter_map(|(rank, index)| { + (rank >= elided || index >= current_turn_start).then_some(index) + }) + .collect() } /// Number of oldest image-bearing messages whose pixels are elided. It only @@ -2302,7 +2341,7 @@ impl ExecutionEngine { let finalize_tool_names = Self::finalize_tool_names(input.tool_definitions.as_deref()); let finalize_runtime_tool_restrictions = Self::finalize_runtime_tool_restrictions(input.context, &finalize_tool_names); - let mut final_ai_messages = Self::build_ai_messages_for_send( + let (mut final_ai_messages, image_turn_start) = Self::build_ai_messages_for_send( input.messages, &input.ai_client.config.format, input.context.workspace.as_ref(), @@ -2341,7 +2380,10 @@ impl ExecutionEngine { loaded_deferred_tool_specs: Vec::new(), model_config_id: input.primary_model_facts.model_id.clone(), effective_model_name: input.ai_client.config.model.clone(), - model_request_context: input.model_request_context.clone(), + model_request_context: ModelRequestContext { + image_turn_start: Some(image_turn_start), + ..input.model_request_context.clone() + }, account_client_source: input.account_client_source.clone(), channel_client_source: input.channel_client_source.clone(), prepared_model: None, @@ -2379,7 +2421,7 @@ impl ExecutionEngine { current_turn_id: &str, attach_images: bool, prepended_reminders: &[&str], - ) -> OpenBitFunResult> { + ) -> OpenBitFunResult<(Vec, usize)> { let limits = ImageLimits::for_provider(provider); let image_context = ToolUseContext::for_tool_listing(workspace.cloned(), workspace_services.cloned()); @@ -2390,6 +2432,7 @@ impl ExecutionEngine { .filter(|text| !text.is_empty()) .collect::>(); let mut result = Vec::with_capacity(messages.len() + trimmed_reminders.len()); + let mut image_turn_start = None; let mut attached_image_count = 0usize; let first_non_system_index = messages .iter() @@ -2397,8 +2440,9 @@ impl ExecutionEngine { .unwrap_or(messages.len()); let mut prepended_reminders_injected = false; + let current_turn_start = Self::image_turn_start(messages, current_turn_id); let keep_image_messages = if attach_images { - Self::image_bearing_indices_to_keep(messages) + Self::image_bearing_indices_to_keep(messages, current_turn_start) } else { HashSet::new() }; @@ -2416,6 +2460,9 @@ impl ExecutionEngine { { continue; } + if msg_idx == current_turn_start { + image_turn_start = Some(result.len()); + } let keep_this_message_images = attach_images && keep_image_messages.contains(&msg_idx); match &msg.content { MessageContent::Multimodal { text, images } => { @@ -2552,7 +2599,8 @@ impl ExecutionEngine { } } - Ok(result) + let image_turn_start = image_turn_start.unwrap_or(result.len()); + Ok((result, image_turn_start)) } fn render_multimodal_as_text(text: &str, images: &[ImageContextData]) -> String { @@ -3419,6 +3467,7 @@ impl ExecutionEngine { ); Self::resolve_image_input_requirement( &initial_messages, + Self::image_turn_start(&initial_messages, &context.dialog_turn_id), enable_tools, &description_context, ) @@ -4224,6 +4273,7 @@ impl ExecutionEngine { let pool_attempt = if let Some(pool_id) = selected_pool.as_deref() { let image_requirement = Self::image_input_requirement( &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), enable_tools && available_tools.iter().any(|name| name == "analyze_image"), ); let (attempt, _next_client) = if let Some(prepared) = initial_pool_attempt.take() { @@ -4348,7 +4398,7 @@ impl ExecutionEngine { .session_manager .select_latest_matching_token_anchor_for_model( &context.session_id, - &messages, + Self::text_only_anchor_prefix(&messages), &model_id, ) .await; @@ -4605,9 +4655,14 @@ impl ExecutionEngine { .ordered_reminders(); let send_prepended_reminder_tokens = Self::prepended_reminder_tokens_for_pressure(&send_prepended_reminders); - let mut send_pressure = if send_pressure_reusable - && token_pressure.prepended_reminder_tokens == send_prepended_reminder_tokens - { + let same_pressure = send_pressure_reusable + && token_pressure.prepended_reminder_tokens == send_prepended_reminder_tokens; + let mut minimum_non_image_input_tokens = if same_pressure && anchor_details.is_some() { + token_pressure.total_tokens + } else { + 0 + }; + let mut send_pressure = if same_pressure { token_pressure } else { Self::estimate_auto_compression_pressure( @@ -4623,12 +4678,16 @@ impl ExecutionEngine { round_index, send_pressure.total_tokens, context_window ); let before_truncate_tokens = send_pressure.total_tokens; + let before_truncate_len = messages.len(); messages = Self::emergency_truncate_messages( messages, context_window, tool_definitions.as_deref(), send_prepended_reminder_tokens, ); + if messages.len() != before_truncate_len { + minimum_non_image_input_tokens = 0; + } self.session_manager .prune_token_anchors_to_messages(&context.session_id, &messages) .await; @@ -4726,7 +4785,11 @@ impl ExecutionEngine { let analysis_available = enable_tools && available_tools.iter().any(|name| name == "analyze_image"); let send_image_requirement = if selected_pool.is_some() { - Self::image_input_requirement(&messages, analysis_available) + Self::image_input_requirement( + &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), + analysis_available, + ) } else if !primary_supports_image_understanding && messages.iter().any(|message| { message.metadata.turn_id.as_deref() == Some(context.dialog_turn_id.as_str()) @@ -4760,7 +4823,7 @@ impl ExecutionEngine { &model_fingerprint, selected_pool.is_some(), ); - let ai_messages = Self::build_ai_messages_for_send( + let (ai_messages, image_turn_start) = Self::build_ai_messages_for_send( &request_messages, &ai_client.config.format, context.workspace.as_ref(), @@ -4771,6 +4834,11 @@ impl ExecutionEngine { ) .await?; + round_context.model_request_context.image_turn_start = Some(image_turn_start); + round_context + .model_request_context + .minimum_non_image_input_tokens = minimum_non_image_input_tokens; + let round_lifecycle = active_round_lifecycle.get_or_insert_with(ModelRoundLifecycle::new); round_lifecycle.routing = routing_decision; @@ -5603,6 +5671,26 @@ impl ExecutionEngine { &model_fingerprint, selected_pool.is_some(), ); + let anchor = self + .session_manager + .select_latest_matching_token_anchor_for_model( + &context.session_id, + Self::text_only_anchor_prefix(&finalize_messages), + &model_id, + ) + .await + .selected; + let mut finalize_request_context = model_request_context.clone(); + if let Some(anchor) = anchor { + let (pressure, _) = Self::estimate_auto_compression_pressure_with_anchor( + &finalize_messages, + tool_definitions.as_deref(), + compression_trigger_budget, + Some(&anchor), + Self::prepended_reminder_tokens_for_pressure(&finalize_prepended_reminders), + ); + finalize_request_context.minimum_non_image_input_tokens = pressure.total_tokens; + } let final_round_result = self .run_finalize_round(FinalizeRoundInput { permission_constraints: tool_policy.permission_constraints.clone(), @@ -5615,7 +5703,7 @@ impl ExecutionEngine { round_group_id: finalize_round_group_id.clone(), execution_context_vars: &execution_context_vars, primary_model_facts: &primary_model_facts, - model_request_context: &model_request_context, + model_request_context: &finalize_request_context, prepended_reminders: &finalize_prepended_reminders, messages: &finalize_messages, reminder_text: finalize_reminder, @@ -5649,7 +5737,7 @@ impl ExecutionEngine { round_group_id: finalize_round_group_id.clone(), execution_context_vars: &execution_context_vars, primary_model_facts: &primary_model_facts, - model_request_context: &model_request_context, + model_request_context: &finalize_request_context, prepended_reminders: &finalize_prepended_reminders, messages: &finalize_messages, reminder_text: finalize_reminder, @@ -6164,7 +6252,7 @@ mod tests { } } for provider in ["openai", "responses", "anthropic", "gemini"] { - let messages = ExecutionEngine::build_ai_messages_for_send( + let (messages, _) = ExecutionEngine::build_ai_messages_for_send( &[source.clone()], provider, None, @@ -6203,7 +6291,7 @@ mod tests { assert_eq!((decoded.width(), decoded.height()), (6, 4)); assert_eq!(find_geometry(&wire), Some(observation.clone()), "{provider}: screenshot ref and projection geometry must remain attached to these pixels"); } - let text_only = ExecutionEngine::build_ai_messages_for_send( + let (text_only, _) = ExecutionEngine::build_ai_messages_for_send( &[source.clone()], "openai", None, @@ -6293,7 +6381,7 @@ mod tests { if attempt > 0 { store.add_message("image-limit", Message::user("Continue".into())); } - let messages = ExecutionEngine::build_ai_messages_for_send( + let (messages, _) = ExecutionEngine::build_ai_messages_for_send( &store.get_context_messages("image-limit"), "openai", None, @@ -6361,17 +6449,17 @@ mod tests { let image = crate::agentic::image_analysis::attachments::test_image(); let mut messages = vec![Message::user("Text only".into())]; assert_eq!( - ExecutionEngine::image_input_requirement(&messages, false), + ExecutionEngine::image_input_requirement(&messages, messages.len(), false), Requirement::None ); let user_image = Message::user_multimodal("Inherited image".into(), vec![image.clone()]); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::NativeOrAnalysisTool ); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, false), + ExecutionEngine::image_input_requirement(&messages, messages.len(), false), Requirement::Native ); let tool_image = Message::tool_result(ToolResult { @@ -6389,12 +6477,12 @@ mod tests { }); messages.push(tool_image); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(Message::internal_reminder_multimodal( @@ -6404,13 +6492,13 @@ mod tests { )); // Elision advances in batches, so the tool pixels stay in the sent window. assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(user_image.clone()); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(Message::internal_reminder_multimodal( @@ -6421,14 +6509,14 @@ mod tests { // The seventh image-bearing message elides the oldest batch, including // the tool pixels, from the same window used for sending. assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::NativeOrAnalysisTool ); let mut hidden = user_image; hidden.metadata.semantic_kind = Some(super::MessageSemanticKind::ComputerUseVerificationScreenshot); assert_eq!( - ExecutionEngine::image_input_requirement(&[hidden], true), + ExecutionEngine::image_input_requirement(&[hidden], 0, true), Requirement::None ); } @@ -6444,7 +6532,7 @@ mod tests { crate::agentic::tools::framework::ToolUseContext::for_tool_listing(None, None); context.agent_type = Some("Claw".into()); assert_eq!( - ExecutionEngine::resolve_image_input_requirement(&messages, false, &context).await, + ExecutionEngine::resolve_image_input_requirement(&messages, 0, false, &context).await, Requirement::Native ); context @@ -6452,12 +6540,13 @@ mod tests { .denied_tool_names .insert("analyze_image".into()); assert_eq!( - ExecutionEngine::resolve_image_input_requirement(&messages, true, &context).await, + ExecutionEngine::resolve_image_input_requirement(&messages, 0, true, &context).await, Requirement::Native ); assert_eq!( ExecutionEngine::resolve_image_input_requirement( &[Message::user("No image".into())], + 0, true, &context ) @@ -6502,7 +6591,11 @@ mod tests { .chain(&visible.deferred_tools) .any(|tool| tool.name() == "analyze_image"); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, analysis_available), + ExecutionEngine::image_input_requirement( + &messages, + messages.len(), + analysis_available + ), super::ImageInputRequirement::NativeOrAnalysisTool, ); } @@ -6531,7 +6624,7 @@ mod tests { .with_turn_id("turn".into()), ]; for provider in ["openai", "anthropic", "responses", "gemini"] { - let native = ExecutionEngine::build_ai_messages_for_send( + let (native, _) = ExecutionEngine::build_ai_messages_for_send( &messages, provider, None, @@ -6561,7 +6654,7 @@ mod tests { ); } } - let text_only = ExecutionEngine::build_ai_messages_for_send( + let (text_only, _) = ExecutionEngine::build_ai_messages_for_send( &messages, "openai", None, @@ -6616,7 +6709,7 @@ mod tests { let image = crate::agentic::image_analysis::attachments::test_image(); let image_message = |index: usize| { Message::user_multimodal(format!("Screenshot {index}"), vec![image.clone()]) - .with_turn_id("turn".into()) + .with_turn_id("earlier".into()) }; let send = |messages: Vec| async move { serde_json::to_value( @@ -6630,7 +6723,8 @@ mod tests { &["stable reminder"], ) .await - .unwrap(), + .unwrap() + .0, ) .unwrap() }; @@ -7779,6 +7873,158 @@ mod tests { assert_eq!(details.expect("anchor details").tail_tokens, tail_tokens); } + #[test] + fn image_projection_reserves_text_using_a_clean_anchor_without_compressing_pixels() { + let image = crate::agentic::image_analysis::attachments::test_image(); + let prefix = vec![ + Message::system("instructions".into()), + Message::user("history".into()), + ]; + let anchor = TokenAnchor::from_request_prefix( + TokenAnchorInput { + session_id: "s".into(), + turn_id: "t".into(), + round_id: "r".into(), + model_id: "m".into(), + input_tokens: 900, + system_tokens_at_anchor: ExecutionEngine::system_tokens_for_pressure(&prefix), + tool_tokens_at_anchor: 0, + prepended_reminder_tokens_at_anchor: 0, + }, + &prefix, + ); + let mut messages = prefix; + messages.push(Message::user_multimodal("inspect".into(), vec![image; 30])); + let available = ExecutionEngine::text_only_anchor_prefix(&messages); + assert_eq!(available.len(), 2); + assert!(anchor.matches_prefix(available)); + let (pressure, _) = ExecutionEngine::estimate_auto_compression_pressure_with_anchor( + &messages, + None, + CompressionTriggerBudget::for_model(2_000, None), + Some(&anchor), + 0, + ); + assert_eq!( + pressure.total_tokens, + 900 + Message::user("inspect".into()).estimate_tokens_with_reasoning(false) + ); + assert!( + messages + .last() + .unwrap() + .estimate_tokens_with_reasoning(false) + > 2_000 + ); + let kept = ExecutionEngine::emergency_truncate_messages(messages.clone(), 2_000, None, 0); + assert_eq!(kept.len(), messages.len()); + } + + #[tokio::test] + async fn image_projection_preserves_all_active_turn_pixels_through_history_batch_elision() { + use super::ImageInputRequirement; + let image = crate::agentic::image_analysis::attachments::test_image(); + let mut messages = vec![ + Message::user_multimodal("earlier".into(), vec![image.clone()]) + .with_turn_id("old".into()), + ]; + messages.push( + Message::tool_result(ToolResult { + tool_id: "read-image".into(), + tool_name: "Read".into(), + effective_tool_name: None, + result_for_assistant: None, + is_error: false, + duration_ms: None, + result: serde_json::json!({}), + image_attachments: Some(vec![crate::util::types::ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: image + .data_url + .as_deref() + .unwrap() + .split_once(',') + .unwrap() + .1 + .into(), + }]), + }) + .with_turn_id("active".into()), + ); + for _ in 0..6 { + messages.push( + Message::user_multimodal("active image".into(), vec![image.clone()]) + .with_turn_id("active".into()), + ); + } + let start = ExecutionEngine::image_turn_start(&messages, "active"); + assert_eq!( + ExecutionEngine::image_input_requirement(&messages, start, true), + ImageInputRequirement::Native + ); + let (outgoing, boundary) = ExecutionEngine::build_ai_messages_for_send( + &messages, + "openai", + None, + None, + "active", + true, + &[], + ) + .await + .unwrap(); + assert_eq!(boundary, 1); + assert!(outgoing[0].content.as_deref().unwrap().contains("omitted")); + assert_eq!( + outgoing[1].tool_image_attachments.as_ref().unwrap().len(), + 1 + ); + assert!(outgoing[2..] + .iter() + .all(|m| m.content.as_deref().unwrap().contains("image_url"))); + } + + #[tokio::test] + async fn image_projection_turn_boundary_uses_emitted_messages_and_real_turn_identity() { + let messages = vec![ + Message::system("system".into()), + Message::internal_reminder(InternalReminderKind::InterruptedContinue, "stale") + .with_turn_id("older".into()), + Message::user("earlier request".into()).with_turn_id("older".into()), + Message::user("verification".into()) + .with_semantic_kind(MessageSemanticKind::ComputerUseVerificationScreenshot) + .with_turn_id("current".into()), + Message::user("inspect".into()).with_turn_id("current".into()), + Message::internal_reminder(InternalReminderKind::FinalizeCacheAnchor, "finish") + .with_turn_id("current".into()), + ]; + let (outgoing, boundary) = ExecutionEngine::build_ai_messages_for_send( + &messages, + "openai", + None, + None, + "current", + true, + &["injected reminder"], + ) + .await + .unwrap(); + assert_eq!(boundary, 3); + assert_eq!(outgoing[boundary].content.as_deref(), Some("inspect")); + let (history, history_only) = ExecutionEngine::build_ai_messages_for_send( + &messages[..3], + "openai", + None, + None, + "current", + true, + &["injected reminder"], + ) + .await + .unwrap(); + assert_eq!(history_only, history.len()); + } + #[test] fn auto_compression_pressure_applies_tool_definition_delta_to_anchor() { let messages = vec![ diff --git a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs index f8e1573636..60842d6eec 100644 --- a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs +++ b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs @@ -70,13 +70,13 @@ async fn prompt_suggestion_enabled() -> bool { /// unchanged, then the suggestion instruction as the only appended message. pub(super) async fn build_prompt_suggestion_messages( request: &PromptSuggestionRequest, -) -> crate::util::errors::OpenBitFunResult> { +) -> crate::util::errors::OpenBitFunResult<(Vec, usize)> { let reminders = request .prepended_reminders .iter() .map(String::as_str) .collect::>(); - let mut ai_messages = ExecutionEngine::build_ai_messages_for_send( + let (mut ai_messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( &request.messages, &request.ai_client.config.format, request.workspace.as_ref(), @@ -87,7 +87,7 @@ pub(super) async fn build_prompt_suggestion_messages( ) .await?; ai_messages.push(AIMessage::user(prompt_suggestion_instruction().to_string())); - Ok(ai_messages) + Ok((ai_messages, image_turn_start)) } async fn generate_prompt_suggestion( @@ -161,10 +161,11 @@ where async fn request_prompt_suggestion_response( request: &PromptSuggestionRequest, - ai_messages: Vec, + (ai_messages, image_turn_start): (Vec, usize), trace: Option, ) -> anyhow::Result> { - let context = suggestion_request_context(&request.model_request_context); + let mut context = suggestion_request_context(&request.model_request_context); + context.image_turn_start = Some(image_turn_start); let response = request .ai_client .send_message_once_with_trace_and_request_context( @@ -696,6 +697,7 @@ mod tests { output_schema: Some( serde_json::json!({"type": "object", "properties": {"report": {"type": "string"}}}), ), + ..Default::default() }; let suggestion = suggestion_request_context(&context); assert_eq!( @@ -740,7 +742,7 @@ mod tests { ]; let reminders = vec!["skill listing".to_string()]; let reminder_refs = reminders.iter().map(String::as_str).collect::>(); - let round_messages = ExecutionEngine::build_ai_messages_for_send( + let (round_messages, round_boundary) = ExecutionEngine::build_ai_messages_for_send( &messages, &ai_client.config.format, None, @@ -764,10 +766,11 @@ mod tests { workspace_services: None, attach_images: false, }; - let suggestion_messages = build_prompt_suggestion_messages(&request) + let (suggestion_messages, boundary) = build_prompt_suggestion_messages(&request) .await .expect("suggestion messages"); + assert_eq!(boundary, round_boundary); assert_eq!(suggestion_messages.len(), round_messages.len() + 1); assert_eq!( serde_json::to_value(&suggestion_messages[..round_messages.len()]).unwrap(), diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index 0cc214071f..9e01a9a1e1 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -789,6 +789,11 @@ impl RoundExecutor { .cancellation_tokens .get_or_insert_new(&context.dialog_turn_id); + // A calibrated text estimate belongs to the original model and prefix. + // Replay projection can strip signed reasoning before the send. + let calibrated_model = (context.model_request_context.minimum_non_image_input_tokens > 0 + && !crate::infrastructure::ai::channel_client_source::ChannelClientSource::has_nonportable_history(&ai_messages)) + .then(|| (context.model_config_id.clone(), ai_client.config.model.clone())); let channels = context.channel_client_source.clone(); let lineage = context.model_request_context.prompt_cache_route_key.clone(); let mut excluded_channels = Vec::new(); @@ -1121,10 +1126,16 @@ impl RoundExecutor { let request_trace_config = trace_config .clone() .map(|config| config.with_round_attempt(attempt_id.clone(), attempt_number)); + let mut request_context = context.model_request_context.clone(); + if !calibrated_model.as_ref().is_some_and(|(id, model)| { + id == &context.model_config_id && model == &ai_client.config.model + }) { + request_context.minimum_non_image_input_tokens = 0; + } let send_future = ai_client.send_message_stream_once_with_request_context( ai_messages.clone(), tool_definitions.clone(), - Some(context.model_request_context.clone()), + Some(request_context), request_trace_config, ); let send_result = tokio::select! { @@ -3528,11 +3539,25 @@ pub(super) mod tests { image_attachments: None, }) .into(); + let mut followup = super::AIMessage::user("Continue from that result".into()); + if manual { + // The primary's text calibration must not reject pixels on + // the selected backup before its transport is reached. + context.model_request_context.minimum_non_image_input_tokens = 64_000; + let image = crate::agentic::image_analysis::attachments::test_image(); + followup.content = Some( + json!([ + {"type": "text", "text": "Inspect the result"}, + {"type": "image_url", "image_url": {"url": image.data_url.unwrap()}} + ]) + .to_string(), + ); + } let history = vec![ super::AIMessage::user("Save the file".into()), previous, tool, - super::AIMessage::user("Continue from that result".into()), + followup, ]; let before = serde_json::to_value(&history).unwrap(); let mut lifecycle = ModelRoundLifecycle::new(); @@ -3579,6 +3604,9 @@ pub(super) mod tests { assert_eq!(primary.requests.lock().unwrap().len(), usize::from(!manual)); assert_eq!(backup.requests.lock().unwrap().len(), 1); let body = backup.requests.lock().unwrap()[0].to_string(); + if manual { + assert!(body.contains("data:image/png;base64,")); + } assert!( body.contains("channel-fixture"), "complete tool history must reach {format}: {body}" diff --git a/src/crates/assembly/core/src/util/token_counter.rs b/src/crates/assembly/core/src/util/token_counter.rs index 2a1ca12891..d70ae5a820 100644 --- a/src/crates/assembly/core/src/util/token_counter.rs +++ b/src/crates/assembly/core/src/util/token_counter.rs @@ -1,96 +1 @@ -//! Token estimation utility - -use crate::util::types::{Message, ToolDefinition}; - -/// Heuristic: ASCII chars 0.3 token, non-ASCII chars 0.6 token -pub struct TokenCounter; - -impl TokenCounter { - pub fn estimate_tokens(text: &str) -> usize { - if text.is_empty() { - return 0; - } - - let mut token_count: f32 = 0.; - - for c in text.chars() { - if c.is_ascii() { - token_count += 0.3; - } else { - token_count += 0.6; - } - } - - token_count as usize - } - - pub fn estimate_message_tokens(message: &Message) -> usize { - let mut total = 0; - - total += 4; - - if let Some(reasoning_content) = &message.reasoning_content { - total += Self::estimate_tokens(reasoning_content); - } - - if let Some(content) = &message.content { - total += Self::estimate_tokens(content); - } - - if let Some(tool_calls) = &message.tool_calls { - for tool_call in tool_calls { - total += Self::estimate_tokens(&tool_call.name); - total += Self::estimate_tokens(&tool_call.serialized_arguments()); - total += 10; - } - } - - if let Some(name) = &message.name { - total += Self::estimate_tokens(name); - } - - total - } - - pub fn estimate_messages_tokens(messages: &[Message]) -> usize { - let mut total: usize = messages.iter().map(Self::estimate_message_tokens).sum(); - - total += 3; - - total - } - - pub fn estimate_tool_definitions_tokens(tools: &[ToolDefinition]) -> usize { - let mut total = 0; - - for tool in tools { - total += Self::estimate_tokens(&tool.name); - total += Self::estimate_tokens(&tool.description); - - if let Ok(json_str) = serde_json::to_string(&tool.parameters) { - total += Self::estimate_tokens(&json_str); - } - - total += 15; - } - - if !tools.is_empty() { - total += 10; - } - - total - } - - pub fn estimate_request_tokens( - messages: &[Message], - tools: Option<&[ToolDefinition]>, - ) -> usize { - let mut total = Self::estimate_messages_tokens(messages); - - if let Some(tool_defs) = tools { - total += Self::estimate_tool_definitions_tokens(tool_defs); - } - - total - } -} +pub use openbitfun_core_types::token_estimate::TokenCounter; diff --git a/src/crates/contracts/config-contracts/src/types.rs b/src/crates/contracts/config-contracts/src/types.rs index a232ee2a1d..eebf49701d 100644 --- a/src/crates/contracts/config-contracts/src/types.rs +++ b/src/crates/contracts/config-contracts/src/types.rs @@ -2,6 +2,7 @@ //! //! Defines all configuration-related types shared between backend and frontend. +pub use openbitfun_core_types::token_estimate::automatic_max_output_tokens; use openbitfun_core_types::{product_identity, ToolPresentationMode, WorktreeSettings}; pub use openbitfun_core_types::{ ImageDialect, ReasoningConfig, ReasoningPreset, ReasoningPresetAction, @@ -1882,22 +1883,6 @@ pub type AgentSubagentOverrideConfig = HashMap u32 { - let quarter_context = context_window / 4; - AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS - .iter() - .rev() - .copied() - .filter(|tier| *tier != 64_000 || context_window >= MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW) - .find(|tier| *tier <= quarter_context) - .unwrap_or(quarter_context) -} /// A configured output cap may use up to 40% of the model context window. pub fn is_valid_configured_max_output_tokens(context_window: u32, max_tokens: u32) -> bool { diff --git a/src/crates/contracts/core-types/src/ai.rs b/src/crates/contracts/core-types/src/ai.rs index efc7224ea1..bb8bf8a151 100644 --- a/src/crates/contracts/core-types/src/ai.rs +++ b/src/crates/contracts/core-types/src/ai.rs @@ -660,6 +660,12 @@ pub struct AIConfig { /// in this contract. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ModelRequestContext { + /// First outgoing message in the active turn, after host-only messages and reminders + /// have been projected. A boundary at the end denotes a history-only request. + pub image_turn_start: Option, + /// Non-image input estimate calibrated from a matching text-only provider prefix. + /// Zero denotes that no comparable provider usage is available for this request. + pub minimum_non_image_input_tokens: usize, /// Opaque execution-lifetime identity, distinct from shareable prompt-cache lineage. /// Absence means a standalone request with no reusable transport continuation. pub conversation_scope: Option>, diff --git a/src/crates/contracts/core-types/src/lib.rs b/src/crates/contracts/core-types/src/lib.rs index 1f4d44fff1..d5c2559b97 100644 --- a/src/crates/contracts/core-types/src/lib.rs +++ b/src/crates/contracts/core-types/src/lib.rs @@ -19,6 +19,7 @@ pub mod session_usage; pub mod speech; pub mod subscription; pub mod surface; +pub mod token_estimate; pub mod tool_image_attachment; pub mod tool_presentation; pub mod worktree; diff --git a/src/crates/contracts/core-types/src/token_estimate.rs b/src/crates/contracts/core-types/src/token_estimate.rs new file mode 100644 index 0000000000..73f227cf44 --- /dev/null +++ b/src/crates/contracts/core-types/src/token_estimate.rs @@ -0,0 +1,114 @@ +//! Shared request token estimates and output reserves. + +use crate::{Message, ToolDefinition}; + +pub const INPUT_SAFETY_RESERVE: usize = 10_000; +const AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS: [u32; 5] = [8_000, 16_000, 24_000, 32_000, 64_000]; +const MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW: u32 = 400_000; + +/// Chooses the largest supported output tier that does not exceed one quarter +/// of the model context window. The 64k tier requires a context window of at +/// least 400k. +pub fn automatic_max_output_tokens(context_window: u32) -> u32 { + let quarter_context = context_window / 4; + AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS + .iter() + .rev() + .copied() + .filter(|tier| *tier != 64_000 || context_window >= MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW) + .find(|tier| *tier <= quarter_context) + .unwrap_or(quarter_context) +} + +/// Heuristic: ASCII chars 0.3 token, non-ASCII chars 0.6 token +pub struct TokenCounter; + +impl TokenCounter { + pub fn estimate_tokens(text: &str) -> usize { + if text.is_empty() { + return 0; + } + + let mut token_count: f32 = 0.; + + for c in text.chars() { + if c.is_ascii() { + token_count += 0.3; + } else { + token_count += 0.6; + } + } + + token_count as usize + } + + pub fn estimate_message_tokens(message: &Message) -> usize { + Self::estimate_message_overhead(message) + + message.content.as_deref().map_or(0, Self::estimate_tokens) + } + + /// Message envelope, reasoning, tool calls and name, excluding content. + pub fn estimate_message_overhead(message: &Message) -> usize { + let mut total = 4; + + if let Some(reasoning_content) = &message.reasoning_content { + total += Self::estimate_tokens(reasoning_content); + } + + if let Some(tool_calls) = &message.tool_calls { + for tool_call in tool_calls { + total += Self::estimate_tokens(&tool_call.name); + total += Self::estimate_tokens(&tool_call.serialized_arguments()); + total += 10; + } + } + + if let Some(name) = &message.name { + total += Self::estimate_tokens(name); + } + + total + } + + pub fn estimate_messages_tokens(messages: &[Message]) -> usize { + let mut total: usize = messages.iter().map(Self::estimate_message_tokens).sum(); + + total += 3; + + total + } + + pub fn estimate_tool_definitions_tokens(tools: &[ToolDefinition]) -> usize { + let mut total = 0; + + for tool in tools { + total += Self::estimate_tokens(&tool.name); + total += Self::estimate_tokens(&tool.description); + + if let Ok(json_str) = serde_json::to_string(&tool.parameters) { + total += Self::estimate_tokens(&json_str); + } + + total += 15; + } + + if !tools.is_empty() { + total += 10; + } + + total + } + + pub fn estimate_request_tokens( + messages: &[Message], + tools: Option<&[ToolDefinition]>, + ) -> usize { + let mut total = Self::estimate_messages_tokens(messages); + + if let Some(tool_defs) = tools { + total += Self::estimate_tool_definitions_tokens(tool_defs); + } + + total + } +} From c20865b1c66228b8201f67c3f54752dc7f2ee882 Mon Sep 17 00:00:00 2001 From: uiharuayako <2451602772@qq.com> Date: Wed, 25 Nov 2026 12:00:21 +0800 Subject: [PATCH 2/3] fix: send historical images by reference after inspection --- .../cache-friendly-message-structure.md | 13 +- src/crates/adapters/ai-adapters/AGENTS.md | 19 +- src/crates/adapters/ai-adapters/src/client.rs | 65 +- .../ai-adapters/src/client/image_budget.rs | 203 ++++- .../src/client/image_budget/context.rs | 161 ++-- .../src/client/image_budget/context_tests.rs | 88 +- .../adapters/ai-adapters/src/client/sse.rs | 16 +- .../src/agentic/coordination/coordinator.rs | 36 +- .../assembly/core/src/agentic/core/message.rs | 101 ++- .../core/src/agentic/execution/AGENTS.md | 4 +- .../src/agentic/execution/compression_job.rs | 15 +- .../agentic/execution/compression_tests.rs | 87 ++ .../src/agentic/execution/execution_engine.rs | 756 ++++++++++-------- .../src/agentic/execution/round_executor.rs | 40 +- .../src/agentic/image_analysis/attachments.rs | 208 ++++- .../image_analysis/image_processing.rs | 24 +- .../agentic/session/compression/compressor.rs | 72 +- .../implementations/analyze_image_tool.rs | 48 +- .../tools/implementations/view_image_tool.rs | 133 ++- src/crates/contracts/core-types/src/errors.rs | 62 +- src/web-ui/src/locales/en-US/errors.json | 4 + src/web-ui/src/locales/zh-CN/errors.json | 4 + src/web-ui/src/locales/zh-TW/errors.json | 4 + .../shared/ai-errors/aiErrorPresenter.test.ts | 12 + .../src/shared/ai-errors/aiErrorPresenter.ts | 5 +- 25 files changed, 1533 insertions(+), 647 deletions(-) diff --git a/docs/architecture/cache-friendly-message-structure.md b/docs/architecture/cache-friendly-message-structure.md index 5550ff3b72..dddcd49744 100644 --- a/docs/architecture/cache-friendly-message-structure.md +++ b/docs/architecture/cache-friendly-message-structure.md @@ -302,13 +302,12 @@ Important exceptions: context and older persisted context snapshots - context compression intentionally rewrites conversation history into a shorter summary form, then invalidates prompt cache and starts a new stable prefix -- image payloads are elided from older image-bearing messages at send time. - The latest two image-bearing messages always keep pixels; older ones are - elided four at a time (`MIN_RETAINED_IMAGE_MESSAGES`, - `IMAGE_ELISION_BATCH` in `execution_engine.rs`). Each elision rewrites an - already-sent message and invalidates the provider cache from that message - onward, so it must stay batched rather than sliding by one message per new - image. Model-pool image requirements use the same retained window. +- Each request sends pixels from pending user uploads and new tool observations, + including parallel tool results. After an assistant response, those messages + carry text and available image references on later requests. Reopening a + referenced image supplies a new observation. This changes the provider cache + prefix at the first replaced image. Model-pool image requirements use the same + pending observations. The session retains the original attachments. ## Session Storage Layout diff --git a/src/crates/adapters/ai-adapters/AGENTS.md b/src/crates/adapters/ai-adapters/AGENTS.md index 76f9dc47bb..d777cfc3d1 100644 --- a/src/crates/adapters/ai-adapters/AGENTS.md +++ b/src/crates/adapters/ai-adapters/AGENTS.md @@ -36,14 +36,17 @@ provider-neutral contracts owned by `openbitfun-agent-stream`. `cargo test --locked -p openbitfun-ai-adapters --lib providers::openai::chat::tests`. - Do not move provider-neutral stream DTOs, replay policy, or tool-call accumulation ownership back into this crate. -- Optional model image-input ceilings are applied to outgoing message copies at - the shared AIClient send boundary, including single-attempt Responses calls. - Count user image parts and tool attachments together; preserve durable history, - tool-result identities, opaque tool text and non-image media. Newer messages - keep their pixels first, with explicit omission text for older pixels. - With `vision-input`, the selected client's context window also determines - whether older pixels must be omitted or current screenshots resized. - Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens`. +- Project images on the outgoing message copy at the shared AIClient send + boundary, including single-attempt Responses calls. Once the assistant has + answered, historical uploads and tool images carry text and available + references. Preserve tool-result identities, opaque tool text, non-image + media and durable attachments. New uploads, parallel tool results and images + produced by an explicit reread share the selected model's optional image count + limit. With `vision-input`, fit these pending images to the context remaining + after text, tools, reserved output and the safety margin. + A gateway HTTP 413 stops retries of the same body. An explicit model context + error keeps its token-overflow classification. + Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens oversized_http_body`. - Normalize explicitly reported response models into the typed stream `response_model` observation. Responses/Codex lifecycle metadata is emitted before an associated error, and Chat Completions model identifiers remain diff --git a/src/crates/adapters/ai-adapters/src/client.rs b/src/crates/adapters/ai-adapters/src/client.rs index 9ad8f82e42..9853e76e90 100644 --- a/src/crates/adapters/ai-adapters/src/client.rs +++ b/src/crates/adapters/ai-adapters/src/client.rs @@ -566,7 +566,9 @@ impl AIClient { if attempt == max_attempts - 1 || error .downcast_ref::() - .is_some_and(|error| error.delivery_uncertain) + .is_some_and(|error| { + error.delivery_uncertain || error.http_status == Some(413) + }) { return Err(error); } @@ -600,7 +602,9 @@ impl AIClient { if attempt == max_attempts - 1 || error .downcast_ref::() - .is_some_and(|error| error.delivery_uncertain) + .is_some_and(|error| { + error.delivery_uncertain || error.http_status == Some(413) + }) { return Err(error); } @@ -628,11 +632,16 @@ impl AIClient { extra_body: Option<&serde_json::Value>, ) -> Result> { #[cfg(not(feature = "vision-input"))] - let _ = (tools, request_context); + let _ = tools; // Project only the outgoing copy, against the actual selected client. responses_websocket::validate(self)?; // Account/channel failover and direct analysis calls share this boundary. - let messages = image_budget::project(messages, self.config.max_images_per_request)?; + let messages = image_budget::project( + messages, + self.config.max_images_per_request, + request_context.and_then(|context| context.image_turn_start), + ApiFormat::parse(&self.config.format)?, + )?; image_budget::validate_extra_body(self.config.max_images_per_request, extra_body)?; #[cfg(feature = "vision-input")] let replaced = image_budget::context::validate_override( @@ -3013,6 +3022,54 @@ mod tests { assert_eq!(attempts.load(Ordering::SeqCst), 2); } + #[tokio::test] + async fn oversized_http_body_reaches_the_caller_without_a_retry() { + use axum::http::StatusCode; + use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; + let attempts = Arc::new(AtomicUsize::new(0)); + let observed = Arc::clone(&attempts); + let app = Router::new().route( + "/chat/completions", + post(move || { + observed.fetch_add(1, Ordering::SeqCst); + async { + ( + StatusCode::PAYLOAD_TOO_LARGE, + "413 Request Entity Too Large", + ) + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let mut client = make_test_client("openai", None); + client.config.request_url = + format!("http://{}/chat/completions", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let messages = vec![crate::types::Message::user( + "Inspect the attachment.".into(), + )]; + + let streamed = client + .send_message_stream(messages.clone(), None, None) + .await + .err() + .unwrap(); + let aggregated = client.send_message(messages, None).await.err().unwrap(); + server.abort(); + + for error in [streamed, aggregated] { + let detail = error.downcast_ref::().unwrap(); + assert_eq!(detail.http_status, Some(413)); + assert_eq!(detail.category, ErrorCategory::InvalidRequest); + assert!(detail.message.contains("Crop images")); + } + assert_eq!( + attempts.load(Ordering::SeqCst), + 2, + "one HTTP request per call" + ); + } + #[test] fn aggregated_retry_delay_grows_beyond_previous_four_second_cap() { assert_eq!(send_message_retry_delay_ms(0, "connection reset"), 500); diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget.rs b/src/crates/adapters/ai-adapters/src/client/image_budget.rs index 7d679ade3c..cce5e24114 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget.rs @@ -5,6 +5,7 @@ pub(super) mod context; #[cfg(all(test, feature = "vision-input"))] mod context_tests; +use crate::client::format::ApiFormat; use crate::types::Message; use anyhow::Result; use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; @@ -32,13 +33,17 @@ pub(super) fn validate_extra_body( Ok(()) } -/// Keep the newest image-bearing messages within the selected model's budget. +/// Send pixels for new inputs and retain references to images in history. +/// Keep the newest pending images within the selected model's count limit. /// Within one message, retain the first images in their original order. Tool /// identities, text, reasoning and replay state are otherwise left intact. pub(super) fn project( mut messages: Vec, max_images: Option, + turn_start: Option, + format: ApiFormat, ) -> Result> { + project_history(&mut messages, turn_start, format); let Some(mut remaining) = max_images else { return Ok(messages); }; @@ -76,25 +81,86 @@ pub(super) fn project( )); } } - "user" => project_user_content(&mut message.content, &mut remaining), + "user" => project_user_content(&mut message.content, &mut remaining, format), _ => {} } } Ok(messages) } -fn project_user_content(content: &mut Option, remaining: &mut usize) { - let Some(original) = content.as_deref() else { - return; - }; - let Ok(Value::Array(mut parts)) = serde_json::from_str::(original) else { +/// A response confirms receipt of all preceding inputs. Consecutive user +/// messages or parallel tool results after it may still await their first send. +fn project_history(messages: &mut [Message], turn_start: Option, format: ApiFormat) { + let turn_start = turn_start.unwrap_or(0).min(messages.len()); + let pending_start = messages[turn_start..] + .iter() + .rposition(|message| message.role == "assistant") + .map_or(turn_start, |index| turn_start + index + 1); + for message in &mut messages[..pending_start] { + match message.role.as_str() { + "tool" => { + if let Some(images) = message + .tool_image_attachments + .take() + .filter(|images| !images.is_empty()) + { + let text = message.content.get_or_insert_with(String::new); + text.push_str(&format!( + "\n[{} earlier tool image(s). Read the source again if pixels are needed.]", + images.len() + )); + } + } + "user" => { + let Some(mut parts) = user_parts(&message.content, format) else { + continue; + }; + let mut changed = false; + for part in parts.iter_mut().filter(|part| is_image_part(part)) { + let url = &part["image_url"]; + let reference = url["url"] + .as_str() + .or_else(|| url.as_str()) + .or_else(|| part["source"]["url"].as_str()) + .filter(|url| url.starts_with("https://") || url.starts_with("http://")) + .or_else(|| part["file_id"].as_str()); + let text = match reference { + Some(reference) => format!("[Earlier image reference: {reference}]"), + None => "[Earlier image. Reattach or read it again if pixels are needed.]" + .into(), + }; + *part = json!({"type":"text", "text":text}); + changed = true; + } + if changed { + message.content = Some(Value::Array(parts).to_string()); + } + } + _ => {} + } + } +} + +// OpenAI treats an unrecognized array as literal text. Gemini recognizes +// individual image parts alongside unknown siblings; Anthropic forwards the array. +fn user_parts(content: &Option, format: ApiFormat) -> Option> { + let content = content.as_deref()?.trim_start(); + if !content.starts_with('[') { + return None; + } + let parts: Vec = serde_json::from_str(content).ok()?; + if matches!(format, ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses) + && !parts.iter().all(is_content_part) + { + return None; + } + Some(parts) +} + +fn project_user_content(content: &mut Option, remaining: &mut usize, format: ApiFormat) { + let Some(mut parts) = user_parts(content, format) else { return; }; - // Ordinary JSON remains text. Require a recognizable content-part array, - // rather than recursively treating arbitrary image-looking fields as pixels. - if !parts.iter().all(is_content_part) { - return; - } let image_count = parts.iter().filter(|part| is_image_part(part)).count(); let keep = image_count.min(*remaining); *remaining -= keep; @@ -180,6 +246,10 @@ mod tests { use crate::providers::openai::message_converter::OpenAIMessageConverter; use crate::types::ToolImageAttachment; + fn project(messages: Vec, max_images: Option) -> Result> { + super::project(messages, max_images, None, ApiFormat::OpenAIChat) + } + fn image(id: &str) -> Value { json!({"type": "image_url", "image_url": {"url": format!("data:image/png;base64,{id}")}}) } @@ -331,16 +401,21 @@ mod tests { } #[test] - fn a_plain_continue_reprojects_old_history_with_the_actual_clients_limit() { + fn a_plain_continue_keeps_a_repeatable_text_reference() { let mut history = vec![tool_images("batch", 4)]; assert_eq!(count(&project(history.clone(), Some(5)).unwrap()), 4); assert_eq!(count(&project(history.clone(), Some(3)).unwrap()), 3); + history.push(Message::assistant("I have inspected the images.".into())); history.push(Message::user("Continue.".into())); let projected = project(history.clone(), Some(3)).unwrap(); - assert_eq!(count(&projected), 3); - assert_eq!(projected[1].content.as_deref(), Some("Continue.")); + assert_eq!(count(&projected), 0); + assert_eq!(projected[2].content.as_deref(), Some("Continue.")); assert_eq!(count(&history), 4); - assert_eq!(count(&project(projected, Some(3)).unwrap()), 3); + let expected = serde_json::to_value(&projected).unwrap(); + assert_eq!( + serde_json::to_value(project(projected, Some(3)).unwrap()).unwrap(), + expected + ); } #[test] @@ -498,6 +573,7 @@ mod tests { .send_message_once_with_trace_and_request_context(history.clone(), None, None, None) .await .unwrap(); + history.push(Message::assistant("I inspected the images.".into())); history.push(Message::user("Continue.".into())); selected .send_message_once_with_trace_and_request_context(history.clone(), None, None, None) @@ -511,10 +587,45 @@ mod tests { assert_eq!(requests.len(), 3); assert_eq!(wire_count(&requests[0]["messages"]), 4); assert_eq!(wire_count(&requests[1]["messages"]), 3); - assert_eq!(wire_count(&requests[2]["messages"]), 3); + assert_eq!(wire_count(&requests[2]["messages"]), 0); assert_eq!(count(&history), 4); } + #[test] + fn historical_image_parts_preserve_text_and_existing_references() { + let inline = image("unrepeatable-pixels"); + let url = "https://example.com/diagram.png"; + let known = Message::user( + json!([ + {"type":"text","text":"Compare these images"}, + inline, {"type":"image_url","image_url":{"url":url}}, + {"type":"input_image","file_id":"file-diagram"} + ]) + .to_string(), + ); + let literal = Message::user(json!([inline, {"record":"application data"}]).to_string()); + let messages = vec![ + known, + literal, + Message::assistant("Done".into()), + user_images(&["new"]), + Message::user("Review the details.".into()), + ]; + let original = serde_json::to_value(&messages).unwrap(); + let projected = + super::project(messages.clone(), None, None, ApiFormat::OpenAIResponses).unwrap(); + let old = projected[0].content.as_deref().unwrap(); + assert!( + old.contains(url) + && old.contains("file-diagram") + && old.contains("Compare these images") + ); + assert!(!old.contains("unrepeatable-pixels")); + assert_eq!(projected[1].content, messages[1].content); + assert_eq!(projected[3].content, messages[3].content); + assert_eq!(serde_json::to_value(messages).unwrap(), original); + } + #[test] fn tool_json_is_opaque_even_if_it_looks_like_image_content() { let mut message = tool_images("opaque", 0); @@ -577,6 +688,64 @@ mod tests { } } + #[test] + fn consumed_images_keep_their_user_and_tool_roles_on_the_wire() { + let call = crate::ToolCall { + id: "capture".into(), + name: "view_image".into(), + arguments: json!({"path":"screen.png"}), + raw_arguments: None, + }; + let history = vec![ + user_images(&["upload"]), + Message::assistant_with_tools(vec![call]), + tool_images("capture", 1), + Message::assistant("Reviewed both images.".into()), + Message::user("Continue.".into()), + ]; + for (format, model) in [ + (ApiFormat::OpenAIChat, "test"), + (ApiFormat::OpenAIResponses, "test"), + (ApiFormat::Anthropic, "test"), + (ApiFormat::Gemini, "gemini-3-pro"), + (ApiFormat::Gemini, "gemini-2.5-pro"), + ] { + let projected = super::project(history.clone(), None, None, format).unwrap(); + let wire = match format { + ApiFormat::OpenAIChat => OpenAIMessageConverter::convert_messages(projected), + ApiFormat::OpenAIResponses => { + OpenAIMessageConverter::convert_messages_to_responses_input(projected).1 + } + ApiFormat::Anthropic => AnthropicMessageConverter::convert_messages(projected).1, + _ => GeminiMessageConverter::convert_messages(projected, model).1, + }; + assert_eq!(wire[0]["role"], "user"); + assert!(wire[0].to_string().contains("Inspect these images")); + let result = &wire[2]; + match format { + ApiFormat::OpenAIChat => { + assert_eq!(result["role"], "tool"); + assert_eq!(result["tool_call_id"], "capture"); + } + ApiFormat::OpenAIResponses => { + assert_eq!(result["type"], "function_call_output"); + assert_eq!(result["call_id"], "capture"); + } + ApiFormat::Anthropic => { + assert_eq!(result["role"], "user"); + assert_eq!(result["content"][0]["type"], "tool_result"); + assert_eq!(result["content"][0]["tool_use_id"], "capture"); + } + _ => { + assert_eq!(result["role"], "user"); + assert_eq!(result["parts"][0]["functionResponse"]["name"], "view_image"); + } + } + assert!(result.to_string().contains("Image attached")); + assert_eq!(wire_count(&Value::Array(wire)), 0); + } + } + #[test] fn projected_pixels_stay_within_budget_in_every_provider_wire_format() { for format in ["openai", "responses", "anthropic", "gemini"] { diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs index 463b828f14..97696b662b 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs @@ -1,7 +1,7 @@ //! Pixel projection for one outgoing request. All positions refer to the //! provider-neutral messages before the adapter merges roles and tool results. -use super::{inline_media, is_content_part, is_image_part}; +use super::{inline_media, is_image_part, user_parts}; use crate::client::format::ApiFormat; use crate::providers::openai::OpenAIMessageConverter; use crate::types::{AIConfig, Message, ModelRequestContext, ToolDefinition}; @@ -13,11 +13,9 @@ use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; use openbitfun_core_types::token_estimate::{ automatic_max_output_tokens, TokenCounter, INPUT_SAFETY_RESERVE, }; -use serde_json::{json, Value}; +use serde_json::Value; use std::collections::BTreeMap; -const OMITTED: &str = "[Earlier image omitted to fit the context window.]"; - struct Image { message: usize, part: usize, @@ -175,7 +173,6 @@ pub(in crate::client) struct Budget { tools: usize, schema: usize, text_floor: usize, - turn_start: Option, } impl Budget { @@ -251,7 +248,6 @@ impl Budget { tools, schema, text_floor: context.map_or(0, |ctx| ctx.minimum_non_image_input_tokens), - turn_start: context.and_then(|ctx| ctx.image_turn_start), } } } @@ -369,6 +365,11 @@ pub(super) fn project( context: Option<&ModelRequestContext>, extra: Option<&Value>, ) -> Result<()> { + super::project_history( + messages, + context.and_then(|ctx| ctx.image_turn_start), + ApiFormat::parse(&config.format)?, + ); apply(messages, Budget::for_request(config, tools, context, extra)) } @@ -412,24 +413,12 @@ pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Resu )); } } else if message.role == "user" { - let Some(content) = message - .content - .as_deref() - .filter(|text| text.trim_start().starts_with('[')) + let Some(parts) = budget + .format + .and_then(|format| user_parts(&message.content, format)) else { continue; }; - let Ok(parts) = serde_json::from_str::>(content) else { - continue; - }; - if matches!( - budget.format, - Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses) - ) && !parts.iter().all(is_content_part) - { - // OpenAI renders unrecognized JSON arrays as literal user text. - continue; - } let before = images.len(); for (part, value) in parts .iter() @@ -487,116 +476,70 @@ pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Resu } let text = text.max(budget.text_floor).saturating_add(budget.schema); let input_limit = budget.limit; - let mut total = images + let total = images .iter() .fold(text, |n, img| n.saturating_add(img.cost)); if total <= input_limit { return Ok(()); } - let turn_start = budget - .turn_start - .or_else(|| messages.iter().rposition(|message| message.role == "user")) - .unwrap_or(0) - .min(messages.len()); - // Each assistant call batch starts a new model round, even when several - // rounds answer the same user. Older observations were already sent. - let current_start = messages[turn_start..] + // Reserve the readable minimum of each current image first, then share + // the remaining detail across them. Small images keep every pixel. + let mut adjustable = Vec::new(); + let mut required = total; + for (index, img) in images .iter() - .rposition(|message| { - message.role == "assistant" - && message - .tool_calls - .as_ref() - .is_some_and(|calls| !calls.is_empty()) - }) - .map_or(turn_start, |index| turn_start + index); - let marker_cost = 4 + TokenCounter::estimate_tokens(OMITTED); - for image in images - .iter_mut() - .take_while(|img| img.message < current_start) + .enumerate() + .filter(|(_, img)| img.target > img.minimum) { - image.target = 0; - total = total.saturating_sub(image.cost).saturating_add(marker_cost); - if total <= input_limit { - break; + required = required.saturating_sub(img.cost - img.minimum); + if messages[img.message].role == "tool" { + let (w, h) = img.dimensions.expect("resizable image dimensions"); + required += TokenCounter::estimate_tokens(&img.preview_note(w, h)) + 4; } + adjustable.push(index); } - if total > input_limit { - // Reserve the readable minimum of each current image first, then share - // the remaining detail across them. Small images keep every pixel. - let mut adjustable = Vec::new(); - let mut required = total; - for (index, img) in images - .iter() - .enumerate() - .filter(|(_, img)| img.target > img.minimum) - { - required = required.saturating_sub(img.cost - img.minimum); - if messages[img.message].role == "tool" { - let (w, h) = img.dimensions.expect("resizable image dimensions"); - required += TokenCounter::estimate_tokens(&img.preview_note(w, h)) + 4; - } - adjustable.push(index); - } - if required > input_limit { - return Err(image_budget_error(format!( + if required > input_limit { + return Err(image_budget_error(format!( "Cannot fit the images and conversation in the model's context window with the requested output reserved ({required} estimated input tokens needed, {input_limit} available). Crop the relevant area, use fewer images, or shorten the conversation." ))); - } - let mut spare = input_limit - required; - adjustable.sort_by_key(|&i| images[i].cost - images[i].minimum); - let mut count = adjustable.len(); - for index in adjustable { - let image = &mut images[index]; - let extra = (spare / count).min(image.cost - image.minimum); - image.target = image.minimum + extra; - spare -= extra; - count -= 1; - } + } + let mut spare = input_limit - required; + adjustable.sort_by_key(|&i| images[i].cost - images[i].minimum); + let mut count = adjustable.len(); + for index in adjustable { + let image = &mut images[index]; + let extra = (spare / count).min(image.cost - image.minimum); + image.target = image.minimum + extra; + spare -= extra; + count -= 1; } let mut edited_users = std::collections::BTreeSet::new(); - // Remove tool attachments from the back so original positions stay valid. - for image in images.iter().rev().filter(|img| img.target != img.cost) { + for image in images.iter().filter(|image| image.target < image.cost) { let message = &mut messages[image.message]; if let Some(parts) = users.get_mut(&image.message) { let part = &mut parts[image.part]; - if image.target == 0 { - *part = json!({"type": "text", "text": OMITTED}); - } else { - let (mime, data) = - part_payload(part).expect("resizable user image has inline data"); - replace_payload( - part, - resize_preview(image.policy, mime, data, image.target)?, - ); - } + let (mime, data) = part_payload(part).expect("resizable user image has inline data"); + replace_payload( + part, + resize_preview(image.policy, mime, data, image.target)?, + ); edited_users.insert(image.message); } else { - let attachments = message + let attachment = &mut message .tool_image_attachments .as_mut() - .expect("tool image group"); - let note = if image.target == 0 { - attachments.remove(image.part); - OMITTED.to_owned() - } else { - let attachment = &mut attachments[image.part]; - let preview = resize_preview( - image.policy, - &attachment.mime_type, - &attachment.data_base64, - image.target, - )?; - let note = image.preview_note(preview.width, preview.height); - attachment.mime_type = preview.mime_type; - attachment.data_base64 = preview.data_base64; - note - }; - if attachments.is_empty() { - message.tool_image_attachments = None; - } + .expect("tool image group")[image.part]; + let preview = resize_preview( + image.policy, + &attachment.mime_type, + &attachment.data_base64, + image.target, + )?; + let note = image.preview_note(preview.width, preview.height); + attachment.mime_type = preview.mime_type; + attachment.data_base64 = preview.data_base64; let content = message.content.get_or_insert_with(String::new); content.push('\n'); content.push_str(¬e); diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs index d66705cd1f..b1ea21b8fd 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs @@ -141,10 +141,15 @@ fn omit_history_before_resizing_the_current_screenshot_and_preserve_originals() let data = screenshot_with_small_text(); let original = vec![uploaded(&png(1536, 1536)), tool_result("view_image", &data)]; let mut roomy = original.clone(); - project(&mut roomy, &config, None, None, None).unwrap(); + let turn = ModelRequestContext { + image_turn_start: Some(1), + ..Default::default() + }; + project(&mut roomy, &config, None, Some(&turn), None).unwrap(); + assert!(user_image_size(&roomy[0]).is_none()); assert_eq!( - serde_json::to_value(roomy).unwrap(), - serde_json::to_value(&original).unwrap() + roomy[1].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data ); let mut limited = original.clone(); @@ -520,6 +525,83 @@ async fn selected_model_window_controls_pixels_on_the_wire() { ); } +#[tokio::test] +async fn later_http_rounds_send_only_fresh_pixels_under_a_gateway_body_limit() { + use axum::{body::Bytes, extract::DefaultBodyLimit, routing::post, Router}; + use std::sync::{Arc, Mutex}; + + // Incompressible screenshots of the same dimensions have comparable byte + // sizes. The gateway can accept one image with framing, but never both. + let screenshot = |mut seed: u32| { + encode_png(image::GrayImage::from_fn(256, 256, |_, _| { + seed = seed.wrapping_mul(1664525).wrapping_add(1013904223); + image::Luma([(seed >> 24) as u8]) + })) + }; + let a = screenshot(1); + let b = screenshot(2); + let limit = a.len().max(b.len()) + 8192; + assert!(a.len() + b.len() > limit); + let requests = Arc::new(Mutex::new(Vec::::new())); + let captured = requests.clone(); + let router = Router::new().route("/chat/completions", post(move |body: Bytes| { + let captured = captured.clone(); + async move { + captured.lock().unwrap().push(body); + let chunk = json!({"id":"test","object":"chat.completion.chunk","created":1,"model":"test-vl", + "choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":"stop"}]}); + ([("content-type", "text/event-stream")], format!("data: {chunk}\n\ndata: [DONE]\n\n")) + } + })).layer(DefaultBodyLimit::max(limit)); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/chat/completions", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); + let mut config = config(); + config.request_url = url.clone(); + config.base_url = url; + let client = crate::AIClient::new(config); + let mut history = vec![Message::user("Read screenshot A".into())]; + for next in [ + Some(("a", &a)), + None, + Some(("b", &b)), + Some(("a-again", &a)), + ] { + if let Some((id, data)) = next { + history.push(Message::assistant_with_tools(vec![crate::ToolCall { + id: id.into(), + name: "view_image".into(), + arguments: json!({"path":id}), + raw_arguments: None, + }])); + let mut result = tool_result("view_image", data); + result.tool_call_id = Some(id.into()); + history.push(result); + } else { + history.push(Message::assistant("A reviewed".into())); + history.push(Message::user("Continue".into())); + } + client + .send_message_once_with_trace_and_request_context(history.clone(), None, None, None) + .await + .unwrap(); + } + server.abort(); + let requests = requests.lock().unwrap(); + assert_eq!(requests.len(), 4); + for (wire, (expected_a, expected_b)) in requests.iter().zip([(1, 0), (0, 0), (0, 1), (1, 0)]) { + assert!(wire.len() <= limit); + let json = std::str::from_utf8(wire).unwrap(); + assert_eq!(json.matches(a.as_str()).count(), expected_a); + assert_eq!(json.matches(b.as_str()).count(), expected_b); + } + assert!(requests[1].len() < 8192); + assert_eq!( + history[2].tool_image_attachments.as_ref().unwrap()[0].data_base64, + a + ); +} + #[test] fn custom_image_payload_must_fit_the_actual_output_reserve() { let mut config = config(); diff --git a/src/crates/adapters/ai-adapters/src/client/sse.rs b/src/crates/adapters/ai-adapters/src/client/sse.rs index 2bcb810557..c1581f8637 100644 --- a/src/crates/adapters/ai-adapters/src/client/sse.rs +++ b/src/crates/adapters/ai-adapters/src/client/sse.rs @@ -538,7 +538,7 @@ where error_kind, provider_recovery_hint_ms(&headers, &error_text), ); - if error_body_timed_out { + if error_body_timed_out && status != StatusCode::PAYLOAD_TOO_LARGE { // Keep the HTTP status, but do not report a partially // received 403 as a confirmed credential failure. provider_error.category = ErrorCategory::Timeout; @@ -552,19 +552,17 @@ where max_tries, error ); - last_error = Some(error); if let Some(trace) = trace.as_ref() { trace .sink - .request_attempt_failed( - trace_handle.as_ref(), - &last_error - .as_ref() - .map(ToString::to_string) - .unwrap_or_else(|| "unknown error".to_string()), - ) + .request_attempt_failed(trace_handle.as_ref(), &error.to_string()) .await; } + // Repeating the same oversized body cannot make it fit. + if status == StatusCode::PAYLOAD_TOO_LARGE { + return Err(error); + } + last_error = Some(error); if !fallback_used && !error_body_timed_out { if let Some(adapted_body) = diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index 1276e62268..1cadab9504 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -6591,12 +6591,20 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet )?; } let workspace = Self::build_workspace_binding(&session.config).await; + let services = if images.iter().any(|image| { + image.data_url.is_none() + && image.image_path.as_deref().is_some_and(|path| { + !crate::agentic::tools::workspace_paths::is_openbitfun_tool_uri(path) + }) + }) { + Self::build_workspace_services(&workspace).await? + } else { + None + }; let context = - crate::agentic::tools::framework::ToolUseContext::for_tool_listing(workspace, None); - crate::agentic::image_analysis::attachments::prepare_inline_image_attachments( - images, &context, - ) - .await + crate::agentic::tools::framework::ToolUseContext::for_tool_listing(workspace, services); + crate::agentic::image_analysis::attachments::prepare_input_attachments(images, &context) + .await } fn input_image_pool_id(config: &SessionConfig) -> Option<&str> { @@ -7177,19 +7185,9 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet user_message_metadata = Some(metadata); } - // Pool admission sees the same image-bearing history as execution, - // including inherited BTW context. Fixed-model admission retains its - // existing current-input validation contract. - let mut image_input_messages = - if session.config.model_binding_policy == SessionModelBindingPolicy::Pool { - self.session_manager - .get_context_messages(&session_id) - .await? - } else { - Vec::new() - }; - let current_turn_start = image_input_messages.len(); - image_input_messages.extend(additional_prepended_messages.iter().cloned()); + // Only new input can require a visual model. Admission can check it + // without loading or cloning any images in the session's earlier turns. + let mut image_input_messages = additional_prepended_messages.clone(); image_input_messages.extend( wrapped_user_input_payload .prepended_messages @@ -7213,7 +7211,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet ); let image_requirement = ExecutionEngine::resolve_image_input_requirement( &image_input_messages, - current_turn_start, + 0, session.config.enable_tools, &image_tool_context, ) diff --git a/src/crates/assembly/core/src/agentic/core/message.rs b/src/crates/assembly/core/src/agentic/core/message.rs index e38f3f3195..36afab5012 100644 --- a/src/crates/assembly/core/src/agentic/core/message.rs +++ b/src/crates/assembly/core/src/agentic/core/message.rs @@ -66,6 +66,9 @@ pub struct MessageMetadata { pub turn_id: Option, pub round_id: Option, pub tokens: Option, + /// Runtime snapshots of tool output pixels, retained when inline bytes are redacted on disk. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tool_image_references: Vec, /// Anthropic extended thinking signature (for passing back in multi-turn conversations) #[serde(skip_serializing_if = "Option::is_none")] pub thinking_signature: Option, @@ -433,37 +436,45 @@ impl From for AIMessage { result_for_assistant, is_error, image_attachments, - } => { - // Tool messages must include tool_call_id - // Prefer result_for_assistant (text specifically for AI), if None or empty then use result (data field) - let content_for_ai = if let Some(assistant_text) = result_for_assistant { - // Check if empty string - if assistant_text.trim().is_empty() { - // If empty, use serialized result - serde_json::to_string(&result) - .unwrap_or(format!("Tool {} execution completed", tool_name)) - } else { - assistant_text - } - } else { - // If no result_for_assistant, use serialized result - serde_json::to_string(&result) - .unwrap_or(format!("Tool {} execution completed", tool_name)) - }; + } => Message::ai_tool_result( + tool_id, + tool_name, + &result, + result_for_assistant, + is_error, + image_attachments, + model_response_replay, + ), + } + } +} - Self { - role: "tool".to_string(), - content: Some(content_for_ai), - reasoning_content: None, - thinking_signature: None, - tool_calls: None, - tool_call_id: Some(tool_id), - name: Some(tool_name), - is_error: Some(is_error), - tool_image_attachments: image_attachments.clone(), - model_response_replay: model_response_replay.clone(), - } - } +impl Message { + /// Build the provider's tool reply without copying image bytes that this request omits. + pub(crate) fn ai_tool_result( + tool_id: String, + tool_name: String, + result: &serde_json::Value, + result_for_assistant: Option, + is_error: bool, + image_attachments: Option>, + model_response_replay: Option, + ) -> AIMessage { + AIMessage { + role: "tool".into(), + content: Some( + result_for_assistant + .filter(|text| !text.trim().is_empty()) + .unwrap_or_else(|| result.to_string()), + ), + reasoning_content: None, + thinking_signature: None, + tool_calls: None, + tool_call_id: Some(tool_id), + name: Some(tool_name), + is_error: Some(is_error), + tool_image_attachments: image_attachments, + model_response_replay, } } } @@ -476,6 +487,36 @@ impl From<&Message> for AIMessage { } impl Message { + pub(crate) fn skip_for_model_send(&self) -> bool { + matches!( + self.metadata.semantic_kind, + Some(MessageSemanticKind::ComputerUseVerificationScreenshot) + | Some(MessageSemanticKind::ComputerUsePostActionSnapshot) + ) + } + + pub(crate) fn image_turn_start(messages: &[Self], current_turn_id: &str) -> usize { + messages + .iter() + .position(|message| { + message.metadata.turn_id.as_deref() == Some(current_turn_id) + && !message.skip_for_model_send() + }) + .unwrap_or(messages.len()) + } + + /// An assistant response consumes preceding observations, including all + /// images returned by the previous parallel tool call batch. + pub(crate) fn fresh_image_start(messages: &[Self], turn_start: usize) -> usize { + let turn_start = turn_start.min(messages.len()); + messages[turn_start..] + .iter() + .rposition(|message| { + message.role == MessageRole::Assistant && !message.skip_for_model_send() + }) + .map_or(turn_start, |index| turn_start + index + 1) + } + pub fn system(text: String) -> Self { Self { id: Uuid::new_v4().to_string(), diff --git a/src/crates/assembly/core/src/agentic/execution/AGENTS.md b/src/crates/assembly/core/src/agentic/execution/AGENTS.md index 4787a5b4c9..0903045c25 100644 --- a/src/crates/assembly/core/src/agentic/execution/AGENTS.md +++ b/src/crates/assembly/core/src/agentic/execution/AGENTS.md @@ -398,8 +398,8 @@ and coordinate metadata through the provider wire converters: cargo test -p openbitfun-core --no-default-features --features agent-runtime,git,tools-computer-use --lib computer_use_pixels_and_geometry_reach_real_provider_wire ``` -For configured image limits, legacy tool-image history, plain continuation after -a provider rejection, and user attachment admission: +For configured limits on pending images, text references to earlier tool +observations on a plain continuation, and user attachment admission: ```bash cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib -- configured_image_limit input_image_count diff --git a/src/crates/assembly/core/src/agentic/execution/compression_job.rs b/src/crates/assembly/core/src/agentic/execution/compression_job.rs index c423cb99ea..44e52bf6c6 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_job.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_job.rs @@ -219,13 +219,16 @@ impl CompressionJob { } } - async fn request_summary(&self, messages: &[Message]) -> OpenBitFunResult { - let (mut messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( - messages, + async fn request_summary(&self, plan: &CompressionPlan) -> OpenBitFunResult { + let (mut messages, image_turn_start) = ExecutionEngine::build_ai_message_prefix_for_send( + &plan.summary_request_messages, &self.client.config.format, - self.workspace.as_ref(), - self.workspace_services.as_ref(), + ToolUseContext::for_tool_listing( + self.workspace.clone(), + self.workspace_services.clone(), + ), &self.turn_id, + plan.summary_pending_image_start, self.attach_images, &self.reminders.ordered_reminders(), ) @@ -340,7 +343,7 @@ impl CompressionJob { } } - let summary_result = self.request_summary(&plan.summary_request_messages).await; + let summary_result = self.request_summary(&plan).await; match summary_result { Ok(summary) => { diff --git a/src/crates/assembly/core/src/agentic/execution/compression_tests.rs b/src/crates/assembly/core/src/agentic/execution/compression_tests.rs index aaedfae769..ba98e5df08 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_tests.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_tests.rs @@ -152,6 +152,93 @@ async fn apply_prefetch( }) } +#[tokio::test] +async fn compression_summary_projects_images_using_the_full_conversation() { + use crate::agentic::core::{ToolCall, ToolResult}; + use crate::util::types::ToolImageAttachment; + + let (_temp, engine) = engine(); + let image = crate::agentic::image_analysis::attachments::test_image(); + let url = image.data_url.unwrap(); + let call = ToolCall { + tool_id: "read".into(), + tool_name: "view_image".into(), + arguments: serde_json::json!({"path": "screenshot.png"}), + raw_arguments: None, + is_error: false, + parse_error: None, + recovered_from_truncation: false, + repair_kind: Default::default(), + }; + let result = Message::tool_result(ToolResult { + tool_id: call.tool_id.clone(), + tool_name: call.tool_name.clone(), + effective_tool_name: None, + result: serde_json::json!({"path": "screenshot.png"}), + result_for_assistant: None, + is_error: false, + duration_ms: None, + image_attachments: Some(vec![ToolImageAttachment { + mime_type: image.mime_type, + data_base64: url.split_once(',').unwrap().1.into(), + }]), + }); + let messages = [ + Message::user("Inspect the screenshot".into()), + Message::assistant_with_tools(String::new(), vec![call]), + result, + Message::assistant("The screenshot shows a blue icon".into()), + ] + .map(|message| message.with_turn_id("turn".into())); + let observed_answer_tokens = messages[3].estimate_tokens_with_reasoning(true); + for (history, recent_tokens, pending) in [ + (&messages[..], observed_answer_tokens, false), + (&messages[..3], 0, true), + ] { + let server = RetryTestServer::new(vec![retry_test_success()]); + let job = CompressionJob::new( + engine.context_compressor.clone(), + "session", + 128_000, + recent_tokens, + CompressionModelSummaryInput { + ai_client: server.client(), + model_request_context: &ModelRequestContext::default(), + runtime_messages: history, + dialog_turn_id: "turn", + workspace: None, + workspace_services: None, + tool_definitions: &None, + prepended_prompt_reminders: &PrependedPromptReminders::default(), + primary_supports_image_understanding: true, + trace_config: None, + }, + ); + let candidate = job.run_manual().await.unwrap(); + assert_eq!( + candidate.plan.summary_messages.last().unwrap().id, + messages[2].id + ); + let requests = server.requests.lock().unwrap(); + assert_eq!(requests.len(), 1); + let wire = requests[0]["messages"].to_string(); + assert_eq!(wire.contains(&url), pending); + assert_eq!(wire.contains("Earlier image pixels omitted"), !pending); + } + + let tail_tokens = messages[1..] + .iter() + .map(|message| message.estimate_non_image_tokens_with_reasoning(true)) + .sum(); + let plan = engine + .context_compressor + .plan_compression_for_turn("session", "turn", &messages, 128_000, tail_tokens) + .unwrap() + .unwrap(); + assert_eq!(plan.recent_tail_messages.len(), 3); + assert_eq!(plan.recent_tail_tokens, tail_tokens); +} + #[tokio::test] async fn compression_skips_retained_history_and_reconsiders_after_large_tool_result() { use crate::agentic::core::{ToolCall, ToolResult}; diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs index d7b6e7ab00..ac7194aad5 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs @@ -92,7 +92,7 @@ use openbitfun_ai_adapters::ModelExchangeTraceConfig; use openbitfun_core_types::{ModelRequestContext, SessionModelBindingPolicy}; use openbitfun_runtime_ports::{resolve_permission_mode, PermissionMode, PermissionModeLayers}; use sha2::{Digest, Sha256}; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::Arc; use tokio_util::sync::CancellationToken; @@ -2152,11 +2152,7 @@ impl ExecutionEngine { /// Omit from model request: UI-only verification frames and legacy auto desktop snapshots. fn skip_message_for_model_send(msg: &Message) -> bool { - matches!( - msg.metadata.semantic_kind.as_ref(), - Some(MessageSemanticKind::ComputerUseVerificationScreenshot) - | Some(MessageSemanticKind::ComputerUsePostActionSnapshot) - ) + msg.skip_for_model_send() } fn is_stale_interrupted_continue(msg: &Message, current_turn_id: &str) -> bool { @@ -2172,14 +2168,8 @@ impl ExecutionEngine { current_turn_id: &str, attach_images: bool, ) -> openbitfun_core_types::UsageContextBreakdown { - let kept_images = if attach_images { - Self::image_bearing_indices_to_keep( - messages, - Self::image_turn_start(messages, current_turn_id), - ) - } else { - HashSet::new() - }; + let fresh = + Self::fresh_image_start(messages, Self::image_turn_start(messages, current_turn_id)); let estimates = messages .iter() .enumerate() @@ -2190,25 +2180,10 @@ impl ExecutionEngine { .map(|(index, message)| { // Use the same eligibility and image-retention policy as model sends; // omitted pixels must not inflate the conversation slice. - let tokens = if !kept_images.contains(&index) && Self::message_bears_images(message) - { - let mut projected = message.clone(); - match &mut projected.content { - MessageContent::Multimodal { text, images } => { - projected.content = MessageContent::Text(if attach_images { - text.clone() - } else { - Self::render_multimodal_as_text(text, images) - }); - } - MessageContent::ToolResult { - image_attachments, .. - } => *image_attachments = None, - _ => {} - } - projected.estimate_tokens_with_reasoning(true) - } else { + let tokens = if attach_images && index >= fresh { message.estimate_tokens_with_reasoning(true) + } else { + message.estimate_non_image_tokens_with_reasoning(true) }; (message, tokens as u64) }); @@ -2239,18 +2214,14 @@ impl ExecutionEngine { MessageContent::Multimodal { images, .. } => !images.is_empty(), MessageContent::ToolResult { image_attachments, .. - } => image_attachments.as_ref().is_some_and(|a| !a.is_empty()), + } => { + image_attachments.as_ref().is_some_and(|a| !a.is_empty()) + || !msg.metadata.tool_image_references.is_empty() + } _ => false, } } - /// The latest image-bearing messages that always keep their pixels. - const MIN_RETAINED_IMAGE_MESSAGES: usize = 2; - /// Eliding pixels rewrites an already-sent message and invalidates provider - /// prompt caches from that message onward, so older image-bearing messages - /// are elided this many at a time instead of one per new image. - const IMAGE_ELISION_BATCH: usize = 4; - fn routing_capability_fallback( messages: &[Message], primary: &PrimaryModelFacts, @@ -2267,16 +2238,15 @@ impl ExecutionEngine { current_turn_start: usize, analysis_tool_available: bool, ) -> ImageInputRequirement { - let retained = Self::image_bearing_indices_to_keep(messages, current_turn_start); - if retained.is_empty() { + let fresh = &messages[Self::fresh_image_start(messages, current_turn_start)..]; + if !fresh.iter().any(Self::message_bears_images) { return ImageInputRequirement::None; } - // Tool-result pixels have no analyze_image path contract. Preserve them - // by requiring native image support rather than silently dropping them. if !analysis_tool_available - || retained - .iter() - .any(|index| matches!(messages[*index].content, MessageContent::ToolResult { .. })) + || fresh.iter().any(|message| { + matches!(message.content, MessageContent::ToolResult { .. }) + && Self::message_bears_images(message) + }) { ImageInputRequirement::Native } else { @@ -2285,48 +2255,13 @@ impl ExecutionEngine { } fn image_turn_start(messages: &[Message], current_turn_id: &str) -> usize { - messages - .iter() - .position(|message| { - message.metadata.turn_id.as_deref() == Some(current_turn_id) - && !Self::skip_message_for_model_send(message) - }) - .unwrap_or(messages.len()) + Message::image_turn_start(messages, current_turn_id) } - /// History pixels are elided in cache-stable batches. Active-turn pixels - /// are kept for the selected model's outgoing token budget. - fn image_bearing_indices_to_keep( - messages: &[Message], - current_turn_start: usize, - ) -> HashSet { - let with_images: Vec = messages - .iter() - .enumerate() - .filter(|(_, m)| Self::message_bears_images(m)) - .map(|(i, _)| i) - .collect(); - let elided = Self::elided_image_message_count(with_images.len()); - with_images - .into_iter() - .enumerate() - .filter_map(|(rank, index)| { - (rank >= elided || index >= current_turn_start).then_some(index) - }) - .collect() - } - - /// Number of oldest image-bearing messages whose pixels are elided. It only - /// grows as history is appended, in steps of `IMAGE_ELISION_BATCH`, and - /// always leaves between `MIN_RETAINED_IMAGE_MESSAGES + 1` and - /// `MIN_RETAINED_IMAGE_MESSAGES + IMAGE_ELISION_BATCH` messages once it starts. - fn elided_image_message_count(image_bearing_messages: usize) -> usize { - let retained_ceiling = Self::MIN_RETAINED_IMAGE_MESSAGES + Self::IMAGE_ELISION_BATCH; - if image_bearing_messages <= retained_ceiling { - return 0; - } - (image_bearing_messages - Self::MIN_RETAINED_IMAGE_MESSAGES - 1) / Self::IMAGE_ELISION_BATCH - * Self::IMAGE_ELISION_BATCH + /// An assistant response consumes all preceding observations. The next request + /// carries new input and every result of the latest parallel tool call batch. + fn fresh_image_start(messages: &[Message], turn_start: usize) -> usize { + Message::fresh_image_start(messages, turn_start) } async fn run_finalize_round( @@ -2421,10 +2356,29 @@ impl ExecutionEngine { current_turn_id: &str, attach_images: bool, prepended_reminders: &[&str], + ) -> OpenBitFunResult<(Vec, usize)> { + Self::build_ai_message_prefix_for_send( + messages, + provider, + ToolUseContext::for_tool_listing(workspace.cloned(), workspace_services.cloned()), + current_turn_id, + Self::image_turn_start(messages, current_turn_id), + attach_images, + prepended_reminders, + ) + .await + } + + async fn build_ai_message_prefix_for_send( + messages: &[Message], + provider: &str, + image_context: ToolUseContext, + current_turn_id: &str, + current_turn_start: usize, + attach_images: bool, + prepended_reminders: &[&str], ) -> OpenBitFunResult<(Vec, usize)> { let limits = ImageLimits::for_provider(provider); - let image_context = - ToolUseContext::for_tool_listing(workspace.cloned(), workspace_services.cloned()); let trimmed_reminders = prepended_reminders .iter() @@ -2440,12 +2394,7 @@ impl ExecutionEngine { .unwrap_or(messages.len()); let mut prepended_reminders_injected = false; - let current_turn_start = Self::image_turn_start(messages, current_turn_id); - let keep_image_messages = if attach_images { - Self::image_bearing_indices_to_keep(messages, current_turn_start) - } else { - HashSet::new() - }; + let fresh = Self::fresh_image_start(messages, current_turn_start); for (msg_idx, msg) in messages.iter().enumerate() { if !prepended_reminders_injected && msg_idx == first_non_system_index { @@ -2463,49 +2412,33 @@ impl ExecutionEngine { if msg_idx == current_turn_start { image_turn_start = Some(result.len()); } - let keep_this_message_images = attach_images && keep_image_messages.contains(&msg_idx); + match &msg.content { MessageContent::Multimodal { text, images } => { + if msg_idx < fresh && !images.is_empty() { + let paths: Vec<&str> = images + .iter() + .filter_map(|image| image.image_path.as_deref()) + .collect(); + let note = + Self::historical_image_note(&paths, attach_images, &image_context); + result.push(AIMessage::user(format!("{text}\n\n{note}"))); + continue; + } if !attach_images { - // Primary model is text-only (or images are disabled). Convert to text-only - // placeholder so providers that don't support image inputs won't error. - let mut text_message = msg.clone(); - text_message.content = - MessageContent::Text(Self::render_multimodal_as_text(text, images)); - result.push(AIMessage::from(&text_message)); + result.push(AIMessage::user(Self::render_multimodal_as_text( + text, images, + ))); continue; } - - let (filtered_images, dropped_count): (Vec, usize) = - if images.is_empty() { - (Vec::new(), 0) - } else if keep_this_message_images { - (images.clone(), 0) - } else { - (Vec::new(), images.len()) - }; - let prompt = if text.trim().is_empty() { - "(image attached)".to_string() + "(image attached)" } else { - text.clone() - }; - let prompt = if dropped_count > 0 { - format!( - "{}\n\n[{} image(s) from this message omitted: only the most recent messages in the conversation that contain images are sent to the model.]", - prompt.trim_end(), - dropped_count - ) - } else { - prompt + text }; - match process_image_contexts_in_workspace( - &filtered_images, - provider, - &image_context, - ) - .await + match process_image_contexts_in_workspace(images, provider, &image_context) + .await { Ok(processed) => { let next_count = attached_image_count + processed.len(); @@ -2517,9 +2450,8 @@ impl ExecutionEngine { } attached_image_count = next_count; - let multimodal = build_multimodal_message_with_images( - &prompt, &processed, provider, - )?; + let multimodal = + build_multimodal_message_with_images(prompt, &processed, provider)?; result.extend(multimodal); } Err(err) => { @@ -2549,45 +2481,90 @@ impl ExecutionEngine { } } } - MessageContent::ToolResult { .. } => { - if !attach_images { - let mut ai = AIMessage::from(msg); - if ai - .tool_image_attachments - .take() - .is_some_and(|images| !images.is_empty()) - { - ai.content = Some(format!("{}\n\n[Tool image pixels were not sent: the resolved model does not support image inputs.]", ai.content.as_deref().unwrap_or(""))); - } - result.push(ai); - continue; + MessageContent::ToolResult { + tool_id, + tool_name, + effective_tool_name, + result: tool_data, + result_for_assistant, + is_error, + image_attachments, + } => { + let name = effective_tool_name.as_deref().unwrap_or(tool_name); + let view_data = (name == "view_image" && !is_error).then_some(tool_data); + let view_source = view_data + .and_then(|data| data.get("source_image_reference")) + .and_then(|v| v.as_str()); + let view_path = view_data + .and_then(|data| data.get("path")) + .and_then(|v| v.as_str()); + let view_image_reply = view_data.is_some() + && (view_source.is_some() + || view_path.is_some() + || result_for_assistant.as_deref() + == Some("Image attached for model vision.")); + let pending = attach_images && msg_idx >= fresh; + let references = &msg.metadata.tool_image_references; + let mut images = None; + if pending { + images = match image_attachments { + Some(images) if !images.is_empty() => Some(images.clone()), + _ if !references.is_empty() => Some( + crate::agentic::image_analysis::attachments::restore_tool_images( + references, + &image_context, + ) + .await?, + ), + _ => None, + }; } - let mut ai = AIMessage::from(msg.clone()); - if let Some(atts) = ai.tool_image_attachments.take() { - if !atts.is_empty() { - if keep_this_message_images { - let next_count = attached_image_count + atts.len(); - if next_count > limits.max_images_per_request { - return Err(OpenBitFunError::validation(format!( - "Too many images in one request: {} > {}", - next_count, limits.max_images_per_request - ))); - } - attached_image_count = next_count; - ai.tool_image_attachments = Some(atts); - } else { - let dropped = atts.len(); - let content_str = ai.content.as_deref().unwrap_or(""); - ai.content = Some(format!( - "{}\n\n[{} image(s) from this tool result omitted: only the most recent messages in the conversation that contain images are sent to the model.]", - content_str.trim_end(), - dropped - )); - ai.tool_image_attachments = None; - } + let mut assistant_text = result_for_assistant.clone(); + let mcp_image_marker = name.starts_with("mcp__") + && assistant_text.as_deref().is_some_and(|text| { + text.lines().any(|line| { + line.starts_with("[Image: image/") && line.ends_with(']') + }) + }); + if images.is_none() + && (view_image_reply || Self::message_bears_images(msg) || mcp_image_marker) + { + let paths: Vec<&str> = if let Some(source) = view_source { + vec![source] + } else if !references.is_empty() { + references.iter().map(String::as_str).collect() + } else { + view_path.into_iter().collect() + }; + let note = + Self::historical_image_note(&paths, attach_images, &image_context); + if view_image_reply { + assistant_text = Some(note); + } else { + let mut text = assistant_text + .filter(|text| !text.trim().is_empty()) + .unwrap_or_else(|| tool_data.to_string()); + text.push_str("\n\n"); + text.push_str(¬e); + assistant_text = Some(text); } } - result.push(ai); + attached_image_count += images.as_ref().map_or(0, Vec::len); + if attached_image_count > limits.max_images_per_request { + return Err(OpenBitFunError::validation(format!( + "Too many images in one request: {} > {}", + attached_image_count, limits.max_images_per_request + ))); + } + result.push(Message::ai_tool_result( + tool_id.clone(), + tool_name.clone(), + tool_data, + assistant_text, + *is_error, + images, + msg.metadata.model_response_replay.clone(), + )); } _ => result.push(AIMessage::from(msg)), } @@ -2603,6 +2580,52 @@ impl ExecutionEngine { Ok((result, image_turn_start)) } + fn historical_image_note( + paths: &[&str], + native_vision: bool, + context: &ToolUseContext, + ) -> String { + let mut note = String::from("[Earlier image pixels omitted."); + let paths: Vec<_> = paths + .iter() + .copied() + .filter(|path| { + if crate::agentic::tools::workspace_paths::is_openbitfun_tool_uri(path) { + context.resolve_tool_path(path).is_ok() + } else if context.is_remote() { + context.resolve_workspace_tool_path(path).is_ok() + } else { + !path.trim().is_empty() + } + }) + .collect(); + if paths.is_empty() { + note.push_str( + " This record has no saved image path. Ask for the image again if needed.", + ); + } else { + let tool = if native_vision { + "view_image" + } else { + "analyze_image" + }; + note.push_str(&format!( + " To inspect again, call {tool} with the exact path:" + )); + for path in paths { + if crate::agentic::image_analysis::attachments::is_saved_image(path, context) { + note.push_str(&format!("\n{path}")); + } else { + note.push_str(&format!( + "\n{path} (source file; its contents may have changed)" + )); + } + } + } + note.push(']'); + note + } + fn render_multimodal_as_text(text: &str, images: &[ImageContextData]) -> String { let mut content = text.to_string(); @@ -3983,30 +4006,27 @@ impl ExecutionEngine { context.workspace.clone(), context.workspace_services.clone(), ); - // Older turn metadata may still hold inline pixels even when its context - // snapshot predates durable attachments. Inline pixels also supersede - // old temporary/controller paths, which may no longer exist. Recover - // them without changing the record shape or requiring manual migration. - for message in &mut messages { + // Recover unconsumed input from older turn records without touching history. + let fresh = Self::fresh_image_start( + &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), + ); + for message in &mut messages[fresh..] { if let MessageContent::Multimodal { images, .. } = &mut message.content { - if !images.iter().any(|image| image.data_url.is_some()) { - continue; - } - if let Err(error) = + if images.iter().any(|image| { + image.data_url.is_some() + && !image.image_path.as_deref().is_some_and(|path| { + crate::agentic::image_analysis::attachments::is_saved_image( + path, + &attachment_context, + ) + }) + }) { crate::agentic::image_analysis::attachments::prepare_inline_image_attachments( images, &attachment_context, ) - .await - { - if message.metadata.turn_id.as_deref() == Some(context.dialog_turn_id.as_str()) - { - return Err(error); - } - warn!( - "Unable to recover historical image attachment: message_id={}, error={}", - message.id, error - ); + .await?; } } } @@ -4166,8 +4186,12 @@ impl ExecutionEngine { .await }; if route == RoundModelRoute::Economy { - if let Some(reason) = Self::routing_capability_fallback( + let fresh = Self::fresh_image_start( &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), + ); + if let Some(reason) = Self::routing_capability_fallback( + &messages[fresh..], &baseline_primary_model_facts, &model_facts, ) { @@ -4784,26 +4808,16 @@ impl ExecutionEngine { let analysis_available = enable_tools && available_tools.iter().any(|name| name == "analyze_image"); - let send_image_requirement = if selected_pool.is_some() { - Self::image_input_requirement( - &messages, - Self::image_turn_start(&messages, &context.dialog_turn_id), - analysis_available, - ) - } else if !primary_supports_image_understanding - && messages.iter().any(|message| { - message.metadata.turn_id.as_deref() == Some(context.dialog_turn_id.as_str()) - && matches!(&message.content, MessageContent::Multimodal { images, .. } if !images.is_empty()) - }) - { - if analysis_available { - ImageInputRequirement::NativeOrAnalysisTool + let send_image_requirement = + if selected_pool.is_some() || !primary_supports_image_understanding { + Self::image_input_requirement( + &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), + analysis_available, + ) } else { - ImageInputRequirement::Native - } - } else { - ImageInputRequirement::None - }; + ImageInputRequirement::None + }; if send_image_requirement != ImageInputRequirement::None { let config_service = get_global_config_service().await?; let ai_config = config_service.get_config(Some("ai")).await?; @@ -5339,9 +5353,11 @@ impl ExecutionEngine { let mut images = agent_dialog_turn_image_contexts(&injection.attachments) .map_err(|error| OpenBitFunError::validation(error.to_string()))? .unwrap_or_default(); - crate::agentic::image_analysis::attachments::prepare_inline_image_attachments( - &mut images, &attachment_context, - ).await?; + crate::agentic::image_analysis::attachments::prepare_input_attachments( + &mut images, + &attachment_context, + ) + .await?; let user_msg = if images.is_empty() { Message::internal_reminder(reminder_kind, wrapped) } else { @@ -6314,7 +6330,8 @@ mod tests { } #[tokio::test] - async fn configured_image_limit_recovers_legacy_tool_history_on_plain_continue() { + async fn configured_image_limit_applies_to_pending_tools_and_plain_continue_sends_only_references( + ) { use crate::agentic::execution::round_executor::tests::{ retry_test_success, RetryTestServer, }; @@ -6336,9 +6353,8 @@ mod tests { .unwrap() .1 .to_owned(); - let mut original = vec![Message::user("Inspect these files".into())]; - for index in 0..4 { - let call = ToolCall { + let calls: Vec<_> = (0..4) + .map(|index| ToolCall { tool_id: format!("view-{index}"), tool_name: "view_image".into(), arguments: json!({"path": format!("image-{index}.png")}), @@ -6347,11 +6363,14 @@ mod tests { parse_error: None, recovered_from_truncation: false, repair_kind: Default::default(), - }; - original.push(Message::assistant_with_tools( - String::new(), - vec![call.clone()], - )); + }) + .collect(); + let mut original = vec![ + Message::user("Inspect these files".into()).with_turn_id("inspect".into()), + Message::assistant_with_tools(String::new(), calls.clone()) + .with_turn_id("inspect".into()), + ]; + for (index, call) in calls.into_iter().enumerate() { original.push(Message::tool_result(ToolResult { tool_id: call.tool_id, tool_name: "view_image".into(), @@ -6378,15 +6397,21 @@ mod tests { capped.config.max_images_per_request = Some(3); for attempt in 0..3 { - if attempt > 0 { - store.add_message("image-limit", Message::user("Continue".into())); - } - let (messages, _) = ExecutionEngine::build_ai_messages_for_send( + let turn = if attempt == 2 { + store.add_message( + "image-limit", + Message::user("Continue".into()).with_turn_id("continue".into()), + ); + "continue" + } else { + "inspect" + }; + let (messages, boundary) = ExecutionEngine::build_ai_messages_for_send( &store.get_context_messages("image-limit"), "openai", None, None, - "continued-turn", + turn, true, &[], ) @@ -6399,7 +6424,15 @@ mod tests { }; let result = tokio::time::timeout( Duration::from_secs(5), - client.send_message_once_with_trace_and_request_context(messages, None, None, None), + client.send_message_once_with_trace_and_request_context( + messages, + None, + Some(openbitfun_core_types::ai::ModelRequestContext { + image_turn_start: Some(boundary), + ..Default::default() + }), + None, + ), ) .await .expect("image request must settle"); @@ -6410,13 +6443,13 @@ mod tests { ErrorCategory::InvalidRequest, ); } else { - result.expect("plain continuation must fit the configured image limit"); + result.expect("capped retry and plain continuation must succeed"); } } let requests = server.requests.lock().unwrap(); assert_eq!(requests.len(), 3); - for (request, expected) in requests.iter().zip([4, 3, 3]) { + for (request, expected) in requests.iter().zip([4, 3, 0]) { let images = request["messages"] .as_array() .unwrap() @@ -6426,15 +6459,21 @@ mod tests { .filter(|part| part["type"] == "image_url") .count(); assert_eq!(images, expected, "{request}"); - assert_eq!( - request["messages"] - .as_array() - .unwrap() - .iter() - .filter(|message| message["role"] == "tool") - .count(), - 4 - ); + let tool_results: Vec<_> = request["messages"] + .as_array() + .unwrap() + .iter() + .filter(|message| message["role"] == "tool") + .collect(); + assert_eq!(tool_results.len(), 4); + for (index, tool) in tool_results.iter().enumerate() { + assert_eq!(tool["tool_call_id"], format!("view-{index}")); + if expected == 0 { + let text = tool["content"].as_str().unwrap(); + assert!(text.contains(&format!("image-{index}.png"))); + assert!(text.contains("view_image")); + } + } } let preserved = store.get_context_messages("image-limit"); assert_eq!( @@ -6444,24 +6483,30 @@ mod tests { } #[test] - fn image_input_requirement_tracks_inherited_steered_and_retained_images() { + fn image_input_requirement_tracks_only_pending_observations() { use super::ImageInputRequirement as Requirement; let image = crate::agentic::image_analysis::attachments::test_image(); - let mut messages = vec![Message::user("Text only".into())]; + let user_image = + Message::user_multimodal("Inspect the attachment".into(), vec![image.clone()]); + let mut messages = vec![user_image.clone(), Message::user("Follow up".into())]; assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), false), + ExecutionEngine::image_input_requirement(&messages, 1, false), Requirement::None ); - let user_image = Message::user_multimodal("Inherited image".into(), vec![image.clone()]); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), + ExecutionEngine::image_input_requirement(&messages, 1, true), Requirement::NativeOrAnalysisTool ); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), false), + ExecutionEngine::image_input_requirement(&messages, 1, false), Requirement::Native ); + messages.push(Message::assistant("I see it".into())); + assert_eq!( + ExecutionEngine::image_input_requirement(&messages, 1, true), + Requirement::None + ); let tool_image = Message::tool_result(ToolResult { tool_id: "image-call".into(), tool_name: "view_image".into(), @@ -6477,39 +6522,17 @@ mod tests { }); messages.push(tool_image); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), - Requirement::Native - ); - messages.push(user_image.clone()); - assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), - Requirement::Native - ); - messages.push(Message::internal_reminder_multimodal( - InternalReminderKind::UserSteering, - "New image", - vec![image.clone()], - )); - // Elision advances in batches, so the tool pixels stay in the sent window. - assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), - Requirement::Native - ); - messages.push(user_image.clone()); - messages.push(user_image.clone()); - assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), + ExecutionEngine::image_input_requirement(&messages, 1, true), Requirement::Native ); + messages.push(Message::assistant("I inspected the tool result".into())); messages.push(Message::internal_reminder_multimodal( InternalReminderKind::UserSteering, - "Seventh image", + "Also look at this", vec![image], )); - // The seventh image-bearing message elides the oldest batch, including - // the tool pixels, from the same window used for sending. assert_eq!( - ExecutionEngine::image_input_requirement(&messages, messages.len(), true), + ExecutionEngine::image_input_requirement(&messages, 1, true), Requirement::NativeOrAnalysisTool ); let mut hidden = user_image; @@ -6591,11 +6614,7 @@ mod tests { .chain(&visible.deferred_tools) .any(|tool| tool.name() == "analyze_image"); assert_eq!( - ExecutionEngine::image_input_requirement( - &messages, - messages.len(), - analysis_available - ), + ExecutionEngine::image_input_requirement(&messages, 0, analysis_available), super::ImageInputRequirement::NativeOrAnalysisTool, ); } @@ -6681,70 +6700,143 @@ mod tests { assert!(messages.iter().all(|message| matches!(&message.content, crate::agentic::core::MessageContent::Multimodal { images, .. } if images[0].data_url.is_some()))); } - #[test] - fn image_elision_advances_in_batches_and_never_reverts() { - let min = ExecutionEngine::MIN_RETAINED_IMAGE_MESSAGES; - let batch = ExecutionEngine::IMAGE_ELISION_BATCH; - let mut previous = 0; - for count in 0..=40 { - let elided = ExecutionEngine::elided_image_message_count(count); - assert!(elided >= previous, "count={count}"); - assert_eq!(elided % batch, 0, "count={count}"); - let retained = count - elided; - if count <= min + batch { - assert_eq!(elided, 0, "count={count}"); - } else { - assert!(retained > min && retained <= min + batch, "count={count}"); + #[tokio::test] + async fn image_snapshot_restores_a_redacted_tool_result_as_a_reference_on_followup() { + use crate::agentic::image_analysis::attachments; + let dir = tempfile::tempdir().unwrap(); + let manager = PersistenceManager::new(Arc::new(PathManager::with_user_root_for_tests( + dir.path().join("user-data"), + ))) + .unwrap(); + let workspace = WorkspaceBinding::new(None, dir.path().to_owned()); + let mut context = + crate::agentic::tools::ToolUseContext::for_tool_listing(Some(workspace.clone()), None); + context.custom_data.insert( + "__openbitfun_test_runtime_root".into(), + json!(dir.path().join("attachments-root")), + ); + let pixels = attachments::test_image().data_url.unwrap(); + let frame = crate::util::types::ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: pixels.split_once(',').unwrap().1.to_owned(), + }; + let references = attachments::tool_image_references(std::slice::from_ref(&frame), &context) + .await + .unwrap(); + let mut message = Message::tool_result(ToolResult { + tool_id: "capture".into(), + tool_name: "screen_capture".into(), + effective_tool_name: None, + result: json!({"window": "Workspace"}), + result_for_assistant: Some("Workspace screenshot".into()), + is_error: false, + duration_ms: None, + image_attachments: Some(vec![frame.clone()]), + }) + .with_turn_id("inspection".into()); + message.metadata.tool_image_references = references.clone(); + let session = uuid::Uuid::new_v4().to_string(); + manager + .save_turn_context_snapshot(dir.path(), &session, 0, &[message]) + .await + .unwrap(); + let restored = manager + .load_turn_context_snapshot(dir.path(), &session, 0) + .await + .unwrap() + .unwrap(); + assert!(matches!( + restored[0].content, + crate::agentic::core::MessageContent::ToolResult { + image_attachments: None, + .. } - previous = elided; - } - assert_eq!(ExecutionEngine::elided_image_message_count(6), 0); - assert_eq!(ExecutionEngine::elided_image_message_count(7), 4); - assert_eq!(ExecutionEngine::elided_image_message_count(10), 4); - assert_eq!(ExecutionEngine::elided_image_message_count(11), 8); + )); + assert_eq!(restored[0].metadata.tool_image_references, references); + let (pending, _) = ExecutionEngine::build_ai_message_prefix_for_send( + &restored, + "openai", + context.clone(), + "inspection", + 0, + true, + &[], + ) + .await + .unwrap(); + assert_eq!( + pending[0].tool_image_attachments.as_ref().unwrap()[0].data_base64, + frame.data_base64 + ); + let (outgoing, _) = ExecutionEngine::build_ai_message_prefix_for_send( + &restored, + "openai", + context, + "followup", + restored.len(), + true, + &[], + ) + .await + .unwrap(); + assert!(outgoing[0].tool_image_attachments.is_none()); + assert_eq!(outgoing[0].tool_call_id.as_deref(), Some("capture")); + let text = outgoing[0].content.as_deref().unwrap(); + assert!(text.contains("Workspace screenshot")); + assert!(text.contains(&references[0])); + assert!(!text.contains("may have changed")); } #[tokio::test] - async fn new_images_keep_earlier_sent_messages_unchanged_between_elision_batches() { - let image = crate::agentic::image_analysis::attachments::test_image(); - let image_message = |index: usize| { - Message::user_multimodal(format!("Screenshot {index}"), vec![image.clone()]) - .with_turn_id("earlier".into()) - }; + async fn image_projection_reuses_the_reference_after_an_assistant_reads_the_image() { + let root = tempfile::tempdir().unwrap(); + let workspace = + WorkspaceBinding::new(Some("image-reference-test".into()), root.path().into()); + let mut context = + crate::agentic::tools::ToolUseContext::for_tool_listing(Some(workspace), None); + context + .custom_data + .insert("__openbitfun_test_runtime_root".into(), json!(root.path())); + let mut image = crate::agentic::image_analysis::attachments::test_image(); + crate::agentic::image_analysis::attachments::prepare_inline_image_attachments( + std::slice::from_mut(&mut image), + &context, + ) + .await + .unwrap(); + let path = image.image_path.clone().unwrap(); + let mut messages = + vec![ + Message::user_multimodal("Inspect this screenshot".into(), vec![image]) + .with_turn_id("turn".into()), + ]; let send = |messages: Vec| async move { - serde_json::to_value( - ExecutionEngine::build_ai_messages_for_send( - &messages, - "anthropic", - None, - None, - "turn", - true, - &["stable reminder"], - ) - .await - .unwrap() - .0, + ExecutionEngine::build_ai_messages_for_send( + &messages, + "anthropic", + None, + None, + "turn", + true, + &[], ) + .await .unwrap() + .0 }; - let mut messages = vec![Message::system("system".into())]; - let mut previous = send(messages.clone()).await; - for index in 1..=7 { - messages.push(image_message(index)); - let current = send(messages.clone()).await; - let previous_len = previous.as_array().unwrap().len(); - let prefix_kept = - current.as_array().unwrap()[..previous_len] == previous.as_array().unwrap()[..]; - // Only the seventh image-bearing message elides a batch and rewrites history. - assert_eq!(prefix_kept, index < 7, "image message {index}"); - previous = current; - } - let sent = previous.to_string(); - assert_eq!( - sent.matches("image(s) from this message omitted").count(), - 4 + let initial = send(messages.clone()).await; + assert!(initial[0].content.as_deref().unwrap().contains("base64")); + messages.push( + Message::assistant("I inspected the screenshot.".into()).with_turn_id("turn".into()), ); + let after_reply = send(messages.clone()).await; + let reference = after_reply[0].content.as_deref().unwrap(); + assert!(reference.contains(path.as_str())); + assert!(!reference.contains("base64")); + messages + .push(Message::user("Summarize the observations.".into()).with_turn_id("turn".into())); + let continued = send(messages).await; + assert_eq!(continued[0].content, after_reply[0].content); } #[tokio::test] @@ -7921,7 +8013,7 @@ mod tests { } #[tokio::test] - async fn image_projection_preserves_all_active_turn_pixels_through_history_batch_elision() { + async fn image_projection_preserves_all_pending_pixels_from_the_active_turn() { use super::ImageInputRequirement; let image = crate::agentic::image_analysis::attachments::test_image(); let mut messages = vec![ @@ -7974,7 +8066,11 @@ mod tests { .await .unwrap(); assert_eq!(boundary, 1); - assert!(outgoing[0].content.as_deref().unwrap().contains("omitted")); + assert!(!outgoing[0] + .content + .as_deref() + .unwrap() + .contains("image_url")); assert_eq!( outgoing[1].tool_image_attachments.as_ref().unwrap().len(), 1 diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index 9e01a9a1e1..0d29574ffa 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -2499,7 +2499,7 @@ impl RoundExecutor { // Create tool result messages (also need to set turn_id and round_id) let dialog_turn_id = context.dialog_turn_id.clone(); let round_id_clone = round_id.clone(); - let tool_result_messages: Vec = tool_results + let mut tool_result_messages: Vec = tool_results .iter() .map(|result| { let mut message = Message::tool_result(result.clone()) @@ -2514,6 +2514,44 @@ impl RoundExecutor { }) .collect(); + let image_context = tool_context_runtime::ToolUseContext::for_tool_listing( + context.workspace.clone(), + context.workspace_services.clone(), + ); + for message in &mut tool_result_messages { + if let MessageContent::ToolResult { + image_attachments: Some(images), + result_for_assistant, + result, + .. + } = &mut message.content + { + match crate::agentic::image_analysis::attachments::tool_image_references( + images, + &image_context, + ) + .await + { + Ok(references) => message.metadata.tool_image_references = references, + Err(error) => { + warn!( + "Failed to save tool image snapshots: message_id={}, error={error}", + message.id + ); + if result_for_assistant + .as_deref() + .is_none_or(|text| text.trim().is_empty()) + { + *result_for_assistant = Some(result.to_string()); + } + if let Some(text) = result_for_assistant { + text.push_str("\n[The runtime could not save an image snapshot for later inspection.]"); + } + } + } + } + } + let has_more_rounds = !tool_result_messages.is_empty(); debug!( diff --git a/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs b/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs index dadd0c6911..fd1ce24a50 100644 --- a/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs +++ b/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs @@ -3,9 +3,105 @@ use super::{decode_data_url, ImageContextData}; use crate::agentic::tools::framework::{build_tool_runtime_artifact_reference, ToolUseContext}; use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; +use base64::Engine; use openbitfun_services_core::json_store::JsonFileStore; use sha2::{Digest, Sha256}; -use std::path::Path; +use std::path::{Path, PathBuf}; + +fn image_runtime_root(context: &ToolUseContext) -> OpenBitFunResult { + if context.workspace.is_some() { + context.current_workspace_runtime_root() + } else { + Ok(crate::infrastructure::app_paths::try_get_path_manager_arc()?.user_data_dir()) + } +} + +fn image_reference(context: &ToolUseContext, name: &str) -> OpenBitFunResult { + build_tool_runtime_artifact_reference( + &format!("attachments/images/{name}"), + Some(&image_runtime_root(context)?), + context.current_workspace_scope().as_deref(), + context.should_emit_runtime_uri(), + ) + .map_err(|error| OpenBitFunError::validation(error.to_string())) +} + +pub(crate) fn is_saved_image(path: &str, context: &ToolUseContext) -> bool { + let name = path.rsplit(['/', '\\']).next().unwrap_or(""); + let Some((digest, _)) = name.split_once('.') else { + return false; + }; + digest.len() == 64 + && digest.bytes().all(|b| b.is_ascii_hexdigit()) + && image_reference(context, name).is_ok_and(|reference| reference == path) +} + +/// Save the exact frame, including observations that never had a source file. +pub(crate) async fn save_image(bytes: &[u8], context: &ToolUseContext) -> OpenBitFunResult { + let (reference, _) = save_in_root( + bytes, + &image_runtime_root(context)?, + context.current_workspace_scope().as_deref(), + context.should_emit_runtime_uri(), + ) + .await?; + Ok(reference) +} + +pub(crate) async fn tool_image_references( + images: &[crate::util::types::ToolImageAttachment], + context: &ToolUseContext, +) -> OpenBitFunResult> { + let mut references = Vec::with_capacity(images.len()); + for image in images { + let bytes = base64::engine::general_purpose::STANDARD + .decode(&image.data_base64) + .map_err(|error| { + OpenBitFunError::validation(format!("Invalid tool image data: {error}")) + })?; + references.push(save_image(&bytes, context).await?); + } + Ok(references) +} + +pub(crate) async fn restore_tool_images( + references: &[String], + context: &ToolUseContext, +) -> OpenBitFunResult> { + let mut images = Vec::with_capacity(references.len()); + for reference in references { + if !is_saved_image(reference, context) { + return Err(OpenBitFunError::validation( + "Tool image snapshot belongs to another runtime or workspace", + )); + } + let bytes = super::image_processing::read_image_in_context(reference, context).await?; + let mime_type = super::detect_mime_type_from_bytes(&bytes, None)?; + images.push(crate::util::types::ToolImageAttachment { + mime_type, + data_base64: base64::engine::general_purpose::STANDARD.encode(bytes), + }); + } + Ok(images) +} + +/// Freeze a path-only upload while its source still denotes the user's chosen image. +pub(crate) async fn prepare_input_attachments( + images: &mut [ImageContextData], + context: &ToolUseContext, +) -> OpenBitFunResult<()> { + for image in images.iter_mut().filter(|image| image.data_url.is_none()) { + let Some(path) = image.image_path.as_deref() else { + continue; + }; + if is_saved_image(path, context) { + continue; + } + let bytes = super::image_processing::read_image_in_context(path, context).await?; + image.image_path = Some(save_image(&bytes, context).await?); + } + prepare_inline_image_attachments(images, context).await +} /// Inline pixels belong to the receiving Runtime, even in an SSH workspace. /// Publish a stable artifact before admitting the message so text-only models @@ -18,7 +114,7 @@ pub(crate) async fn prepare_inline_image_attachments( if !images.iter().any(|image| image.data_url.is_some()) { return Ok(()); } - let runtime_root = context.current_workspace_runtime_root()?; + let runtime_root = image_runtime_root(context)?; prepare_in_runtime_root( images, &runtime_root, @@ -39,45 +135,50 @@ async fn prepare_in_runtime_root( continue; }; let (bytes, _) = decode_data_url(data_url)?; - let format = image::guess_format(&bytes).map_err(|error| { - OpenBitFunError::validation(format!("Invalid image attachment {}: {error}", image.id)) - })?; - let (extension, mime_type) = match format { - image::ImageFormat::Png => ("png", "image/png"), - image::ImageFormat::Jpeg => ("jpg", "image/jpeg"), - image::ImageFormat::Gif => ("gif", "image/gif"), - image::ImageFormat::WebP => ("webp", "image/webp"), - image::ImageFormat::Bmp => ("bmp", "image/bmp"), - _ => { - return Err(OpenBitFunError::validation(format!( + let (path, mime_type) = + save_in_root(&bytes, runtime_root, workspace_scope, emit_runtime_uri).await?; + image.image_path = Some(path); + image.mime_type = mime_type.to_string(); + } + Ok(()) +} + +async fn save_in_root( + bytes: &[u8], + runtime_root: &Path, + workspace_scope: Option<&str>, + emit_runtime_uri: bool, +) -> OpenBitFunResult<(String, &'static str)> { + let format = image::guess_format(bytes).map_err(|error| { + OpenBitFunError::validation(format!("Invalid image attachment: {error}")) + })?; + let (extension, mime_type) = match format { + image::ImageFormat::Png => ("png", "image/png"), + image::ImageFormat::Jpeg => ("jpg", "image/jpeg"), + image::ImageFormat::Gif => ("gif", "image/gif"), + image::ImageFormat::WebP => ("webp", "image/webp"), + image::ImageFormat::Bmp => ("bmp", "image/bmp"), + _ => { + return Err(OpenBitFunError::validation(format!( "Unsupported image attachment format: {format:?}. Use PNG, JPEG, GIF, WebP or BMP." ))) - } - }; - let relative_path = format!( - "attachments/images/{:x}.{extension}", - Sha256::digest(&bytes) - ); - let path = runtime_root.join(&relative_path); - // A replay or queued dispatch can prepare the same pixels twice. The - // content address lets it reuse a complete, unchanged artifact. - if tokio::fs::read(&path).await.ok().as_deref() != Some(bytes.as_slice()) { - persist_attachment(&path, bytes).await?; } - // Never reuse a controller-side path when pixels were supplied. A - // runtime URI explicitly selects host artifact IO in remote workspaces. - image.image_path = Some( - build_tool_runtime_artifact_reference( - &relative_path, - Some(runtime_root), - workspace_scope, - emit_runtime_uri, - ) - .map_err(|error| OpenBitFunError::validation(error.to_string()))?, - ); - image.mime_type = mime_type.to_string(); + }; + let relative_path = format!("attachments/images/{:x}.{extension}", Sha256::digest(bytes)); + let path = runtime_root.join(&relative_path); + // A replay or queued dispatch can prepare the same pixels twice. The + // content address lets it reuse a complete, unchanged artifact. + if tokio::fs::read(&path).await.ok().as_deref() != Some(bytes) { + persist_attachment(&path, bytes.to_vec()).await?; } - Ok(()) + let reference = build_tool_runtime_artifact_reference( + &relative_path, + Some(runtime_root), + workspace_scope, + emit_runtime_uri, + ) + .map_err(|error| OpenBitFunError::validation(error.to_string()))?; + Ok((reference, mime_type)) } #[cfg(test)] @@ -103,6 +204,39 @@ pub(crate) fn test_image() -> ImageContextData { mod tests { use super::*; + #[tokio::test] + async fn image_snapshot_freezes_path_uploads_within_the_submitting_workspace() { + use crate::agentic::workspace::WorkspaceBinding; + let root = tempfile::tempdir().unwrap(); + let mut image = test_image(); + let original = decode_data_url(&image.data_url.take().unwrap()).unwrap().0; + let source = root.path().join("selected.png"); + tokio::fs::write(&source, &original).await.unwrap(); + image.image_path = Some(source.to_str().unwrap().into()); + let images = std::slice::from_mut(&mut image); + let no_workspace = ToolUseContext::for_tool_listing(None, None); + assert!(prepare_input_attachments(images, &no_workspace) + .await + .is_err()); + + let workspace = WorkspaceBinding::new(Some("project".into()), root.path().into()); + let mut context = ToolUseContext::for_tool_listing(Some(workspace), None); + context.custom_data.insert( + "__openbitfun_test_runtime_root".into(), + serde_json::json!(root.path().join("runtime")), + ); + prepare_input_attachments(images, &context).await.unwrap(); + tokio::fs::remove_file(source).await.unwrap(); + let reference = image.image_path.as_deref().unwrap(); + assert!(is_saved_image(reference, &context)); + assert_eq!( + super::super::image_processing::read_image_in_context(reference, &context) + .await + .unwrap(), + original + ); + } + #[tokio::test] async fn inline_pixels_survive_redaction_and_reuse_the_same_artifact_on_retry() { let root = tempfile::tempdir().unwrap(); diff --git a/src/crates/assembly/core/src/agentic/image_analysis/image_processing.rs b/src/crates/assembly/core/src/agentic/image_analysis/image_processing.rs index d655433a5f..2dbce8263b 100644 --- a/src/crates/assembly/core/src/agentic/image_analysis/image_processing.rs +++ b/src/crates/assembly/core/src/agentic/image_analysis/image_processing.rs @@ -529,6 +529,21 @@ pub(crate) async fn process_image_contexts_in_workspace( .await } +pub(super) async fn read_image_in_context( + path: &str, + context: &ToolUseContext, +) -> OpenBitFunResult> { + if context.workspace.is_none() && super::attachments::is_saved_image(path, context) { + return load_image_from_path(Path::new(path), None).await; + } + let resolved = context.resolve_tool_path(path)?; + context + .file_system_for_path(&resolved)? + .read_file(&resolved.resolved_path) + .await + .map_err(|error| OpenBitFunError::io(format!("Failed to read image: {error}"))) +} + async fn process_image_contexts( image_contexts: &[ImageContextData], provider: &str, @@ -553,14 +568,7 @@ async fn process_image_contexts( (data, data_url_mime.or_else(|| Some(ctx.mime_type.clone()))) } else if let Some(path_str) = &ctx.image_path { let data = if let Some(context) = context { - let resolved = context.resolve_tool_path(path_str)?; - context - .file_system_for_path(&resolved)? - .read_file(&resolved.resolved_path) - .await - .map_err(|error| { - OpenBitFunError::io(format!("Failed to read image: {error}")) - })? + read_image_in_context(path_str, context).await? } else { let path = resolve_image_path(path_str, workspace_path)?; load_image_from_path(&path, workspace_path).await? diff --git a/src/crates/assembly/core/src/agentic/session/compression/compressor.rs b/src/crates/assembly/core/src/agentic/session/compression/compressor.rs index c60410bc04..59eef3f13e 100644 --- a/src/crates/assembly/core/src/agentic/session/compression/compressor.rs +++ b/src/crates/assembly/core/src/agentic/session/compression/compressor.rs @@ -25,6 +25,9 @@ pub struct CompressionResult { #[derive(Debug, Clone)] pub struct CompressionPlan { pub summary_request_messages: Vec, + /// The first pending observation in the summary prefix, located using the + /// complete conversation (the consuming response can be in the retained tail). + pub(crate) summary_pending_image_start: usize, pub summary_messages: Vec, pub retained_user_messages: Vec, pub recent_tail_messages: Vec, @@ -138,7 +141,11 @@ impl ContextCompressor { return Ok(None); } - let units = Self::atomic_message_units(conversation); + let turn_start = + current_turn_id.map_or(0, |turn| Message::image_turn_start(runtime_messages, turn)); + let pending_start = Message::fresh_image_start(runtime_messages, turn_start); + let pending_conversation_start = pending_start.saturating_sub(system_message_count); + let units = Self::atomic_message_units(conversation, pending_conversation_start); if units.is_empty() { return Ok(None); } @@ -175,10 +182,7 @@ impl ContextCompressor { } let recent_tail_messages = conversation[cutoff..].to_vec(); - let recent_tail_tokens = recent_tail_messages - .iter() - .map(|message| message.estimate_tokens_with_reasoning(true)) - .sum(); + let recent_tail_tokens = accumulated_tokens; let current_turn_todo_checkpoint = current_turn_id.and_then(|turn_id| { Self::latest_successful_todo_snapshot_for_turn(conversation, turn_id).and_then( |(source_message_index, snapshot)| { @@ -191,10 +195,14 @@ impl ContextCompressor { }); let mut summary_request_messages = runtime_messages[..system_message_count].to_vec(); summary_request_messages.extend(summary_messages.clone()); + let summary_pending_image_start = pending_start.min(summary_request_messages.len()); let retained_user_token_budget = (context_window / 10).min(Self::MAX_RETAINED_USER_TOKENS); - let (retained_user_messages, retained_user_tokens) = - Self::retain_historical_user_messages(&summary_messages, retained_user_token_budget); + let (retained_user_messages, retained_user_tokens) = Self::retain_historical_user_messages( + &summary_messages, + retained_user_token_budget, + pending_conversation_start, + ); debug!( "Compression plan: session_id={}, retained_user_token_budget={}, retained_user_tokens={}, retained_user_messages={}, recent_target_tokens={}, recent_tail_tokens={}, cutoff_message_index={}, summary_messages={}, recent_tail_messages={}, next_recent_target_tokens={:?}", session_id, @@ -211,6 +219,7 @@ impl ContextCompressor { Ok(Some(CompressionPlan { summary_request_messages, + summary_pending_image_start, summary_messages, retained_user_messages, recent_tail_messages, @@ -292,7 +301,15 @@ impl ContextCompressor { latest } - fn atomic_message_units(messages: &[Message]) -> Vec { + fn message_tokens(message: &Message, images_pending: bool) -> usize { + if images_pending { + message.estimate_tokens_with_reasoning(true) + } else { + message.estimate_non_image_tokens_with_reasoning(true) + } + } + + fn atomic_message_units(messages: &[Message], pending_start: usize) -> Vec { let mut units = Vec::new(); let mut index = 0usize; @@ -306,7 +323,10 @@ impl ContextCompressor { } let tokens = messages[start..index] .iter() - .map(|message| message.estimate_tokens_with_reasoning(true)) + .enumerate() + .map(|(offset, message)| { + Self::message_tokens(message, start + offset >= pending_start) + }) .sum(); units.push(AtomicMessageUnit { start, tokens }); } @@ -317,16 +337,18 @@ impl ContextCompressor { fn retain_historical_user_messages( summary_messages: &[Message], token_budget: usize, + pending_start: usize, ) -> (Vec, usize) { let mut retained = Vec::new(); let mut retained_tokens = 0usize; - for message in summary_messages + for (index, message) in summary_messages .iter() + .enumerate() .rev() - .filter(|message| message.is_actual_user_message()) + .filter(|(_, message)| message.is_actual_user_message()) { - let message_tokens = message.estimate_tokens_with_reasoning(true); + let message_tokens = Self::message_tokens(message, index >= pending_start); if retained_tokens.saturating_add(message_tokens) > token_budget { break; } @@ -349,24 +371,26 @@ impl ContextCompressor { let conversation = Self::canonical_conversation(runtime_messages) .cloned() .collect::>(); + let pending_start = Message::fresh_image_start( + &conversation, + Message::image_turn_start(&conversation, current_turn_id), + ); + let units = Self::atomic_message_units(&conversation, pending_start); let cutoff = plan.summary_messages.len(); if !Self::has_message_id_prefix( &conversation, plan.summary_messages .iter() .map(|message| message.id.as_str()), - ) || (cutoff < conversation.len() - && !Self::atomic_message_units(&conversation) - .iter() - .any(|unit| unit.start == cutoff)) + ) || (cutoff < conversation.len() && !units.iter().any(|unit| unit.start == cutoff)) { return Ok(None); } plan.recent_tail_messages = conversation[cutoff..].to_vec(); - plan.recent_tail_tokens = plan - .recent_tail_messages + plan.recent_tail_tokens = units .iter() - .map(|message| message.estimate_tokens_with_reasoning(true)) + .filter(|unit| unit.start >= cutoff) + .map(|unit| unit.tokens) .sum(); plan.current_turn_todo_checkpoint = Self::latest_successful_todo_snapshot_for_turn(&conversation, current_turn_id) @@ -1434,8 +1458,11 @@ mod tests { .map(|message| message.estimate_tokens_with_reasoning(true)) .sum(); - let (retained, retained_tokens) = - ContextCompressor::retain_historical_user_messages(&messages, total_tokens); + let (retained, retained_tokens) = ContextCompressor::retain_historical_user_messages( + &messages, + total_tokens, + messages.len(), + ); assert_eq!(retained.len(), 25); assert_eq!(retained_tokens, total_tokens); @@ -1475,6 +1502,7 @@ mod tests { let (retained, retained_tokens) = ContextCompressor::retain_historical_user_messages( &[oldest, too_large, newest.clone()], budget, + 3, ); assert_eq!(retained.len(), 1); @@ -1488,7 +1516,7 @@ mod tests { let newest = Message::user("newest".repeat(500)); let (retained, retained_tokens) = - ContextCompressor::retain_historical_user_messages(&[older, newest], 1); + ContextCompressor::retain_historical_user_messages(&[older, newest], 1, 2); assert!(retained.is_empty()); assert_eq!(retained_tokens, 0); diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/analyze_image_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/analyze_image_tool.rs index 3d7bd3a887..73d50f00af 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/analyze_image_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/analyze_image_tool.rs @@ -16,14 +16,23 @@ pub struct AnalyzeImageTool; #[derive(Debug, Clone)] enum ResolvedImagePath { - Local(PathBuf), - RemoteWorkspace { logical_path: String, path: String }, + Local { + path: PathBuf, + reference: Option, + }, + RemoteWorkspace { + logical_path: String, + path: String, + }, } impl ResolvedImagePath { fn display_path(&self) -> &str { match self { - Self::Local(path) => path.to_str().unwrap_or(""), + Self::Local { path, reference } => reference + .as_deref() + .or_else(|| path.to_str()) + .unwrap_or(""), Self::RemoteWorkspace { logical_path, .. } => logical_path, } } @@ -67,7 +76,10 @@ impl AnalyzeImageTool { && !crate::agentic::tools::workspace_paths::is_openbitfun_tool_uri(input_path) && !context.is_some_and(|ctx| ctx.is_remote()) { - return Ok(ResolvedImagePath::Local(local_path.to_path_buf())); + return Ok(ResolvedImagePath::Local { + path: local_path.to_path_buf(), + reference: None, + }); } match context.map(|ctx| ctx.resolve_tool_path(input_path)) { @@ -78,9 +90,12 @@ impl AnalyzeImageTool { path: resolved.resolved_path, }); } - Ok(ResolvedImagePath::Local(PathBuf::from( - resolved.resolved_path, - ))) + Ok(ResolvedImagePath::Local { + reference: resolved + .is_runtime_artifact() + .then_some(resolved.logical_path), + path: PathBuf::from(resolved.resolved_path), + }) } Some(Err(err)) => Err(err), None => { @@ -91,7 +106,10 @@ impl AnalyzeImageTool { input_path ))); } - Ok(ResolvedImagePath::Local(path.to_path_buf())) + Ok(ResolvedImagePath::Local { + path: path.to_path_buf(), + reference: None, + }) } } } @@ -101,25 +119,25 @@ impl AnalyzeImageTool { context: Option<&ToolUseContext>, ) -> OpenBitFunResult> { match resolved { - ResolvedImagePath::Local(path) => { + ResolvedImagePath::Local { path, .. } => { let metadata = fs::metadata(path).await.map_err(|err| { OpenBitFunError::tool(format!( "unable to locate image at {}: {}", - path.display(), + resolved.display_path(), err )) })?; if !metadata.is_file() { return Err(OpenBitFunError::tool(format!( "image path is not a file: {}", - path.display() + resolved.display_path() ))); } fs::read(path).await.map_err(|err| { OpenBitFunError::tool(format!( "unable to read image at {}: {}", - path.display(), + resolved.display_path(), err )) }) @@ -294,7 +312,9 @@ impl Tool for AnalyzeImageTool { }; match &resolved { - ResolvedImagePath::Local(local_path) => match std::fs::metadata(local_path) { + ResolvedImagePath::Local { + path: local_path, .. + } => match std::fs::metadata(local_path) { Ok(metadata) if metadata.is_file() => ValidationResult::default(), Ok(_) => ValidationResult { result: false, @@ -531,7 +551,7 @@ mod image_path_tests { let reference = images[0].image_path.as_deref().unwrap(); assert!(reference.starts_with("openbitfun://runtime/remote-workspace/")); let resolved = AnalyzeImageTool::resolve_path(reference, Some(&context)).unwrap(); - assert!(matches!(resolved, ResolvedImagePath::Local(_))); + assert!(matches!(resolved, ResolvedImagePath::Local { .. })); assert_eq!( AnalyzeImageTool::read_image_bytes(&resolved, Some(&context)) .await diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs index 9f85e0062e..e64848d4c0 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs @@ -14,14 +14,23 @@ pub struct ViewImageTool; #[derive(Debug, Clone)] enum ResolvedImagePath { - Local(PathBuf), - RemoteWorkspace { logical_path: String, path: String }, + Local { + path: PathBuf, + reference: Option, + }, + RemoteWorkspace { + logical_path: String, + path: String, + }, } impl ResolvedImagePath { fn display_path(&self) -> &str { match self { - Self::Local(path) => path.to_str().unwrap_or(""), + Self::Local { path, reference } => reference + .as_deref() + .or_else(|| path.to_str()) + .unwrap_or(""), Self::RemoteWorkspace { logical_path, .. } => logical_path, } } @@ -117,7 +126,10 @@ impl ViewImageTool { && local_path.is_absolute() && !crate::agentic::tools::workspace_paths::is_openbitfun_tool_uri(input_path) { - return Ok(ResolvedImagePath::Local(local_path.to_path_buf())); + return Ok(ResolvedImagePath::Local { + path: local_path.to_path_buf(), + reference: None, + }); } match context.map(|ctx| ctx.resolve_tool_path(input_path)) { @@ -128,9 +140,12 @@ impl ViewImageTool { path: resolved.resolved_path, }); } - Ok(ResolvedImagePath::Local(PathBuf::from( - resolved.resolved_path, - ))) + Ok(ResolvedImagePath::Local { + reference: resolved + .is_runtime_artifact() + .then_some(resolved.logical_path), + path: PathBuf::from(resolved.resolved_path), + }) } Some(Err(err)) => Err(err), None => { @@ -141,7 +156,10 @@ impl ViewImageTool { input_path ))); } - Ok(ResolvedImagePath::Local(path.to_path_buf())) + Ok(ResolvedImagePath::Local { + path: path.to_path_buf(), + reference: None, + }) } } } @@ -151,25 +169,25 @@ impl ViewImageTool { context: Option<&ToolUseContext>, ) -> OpenBitFunResult> { match resolved { - ResolvedImagePath::Local(path) => { + ResolvedImagePath::Local { path, .. } => { let metadata = fs::metadata(path).await.map_err(|err| { OpenBitFunError::tool(format!( "unable to locate image at {}: {}", - path.display(), + resolved.display_path(), err )) })?; if !metadata.is_file() { return Err(OpenBitFunError::tool(format!( "image path is not a file: {}", - path.display() + resolved.display_path() ))); } fs::read(path).await.map_err(|err| { OpenBitFunError::tool(format!( "unable to read image at {}: {}", - path.display(), + resolved.display_path(), err )) }) @@ -312,7 +330,9 @@ impl Tool for ViewImageTool { }; match &path { - ResolvedImagePath::Local(local_path) => match std::fs::metadata(local_path) { + ResolvedImagePath::Local { + path: local_path, .. + } => match std::fs::metadata(local_path) { Ok(metadata) if metadata.is_file() => ValidationResult::default(), Ok(_) => ValidationResult { result: false, @@ -397,6 +417,8 @@ impl Tool for ViewImageTool { let path = Self::resolve_path(input_path, Some(context))?; let bytes = Self::read_image_bytes(&path, Some(context)).await?; let original_mime_type = Self::mime_type_for_image(&bytes)?; + let source_reference = + crate::agentic::image_analysis::attachments::save_image(&bytes, context).await?; let provider = Self::primary_api_format(context); let processed = optimize_image_for_provider(bytes, &provider, Some(original_mime_type)) .map_err(|err| { @@ -421,6 +443,7 @@ impl Tool for ViewImageTool { // it is looking at. let data = json!({ "path": path.display_path(), + "source_image_reference": source_reference, "mime_type": mime_type.clone(), "width": processed.width, "height": processed.height, @@ -581,6 +604,90 @@ mod tests { context } + #[tokio::test] + async fn image_snapshot_reopens_the_original_after_a_source_is_overwritten() { + use base64::Engine; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("screenshot.png"); + let original = png_bytes(3, 2); + fs::write(&path, &original).unwrap(); + let mut context = local_workspace_context("openai", true, dir.path().into()); + context.custom_data.insert( + "__openbitfun_test_runtime_root".into(), + json!(dir.path().join("runtime")), + ); + let tool = ViewImageTool::new(); + let first = tool + .call_impl(&json!({ "path": path }), &context) + .await + .unwrap(); + let ToolResult::Result { data, .. } = &first[0] else { + panic!("expected image") + }; + let reference = data["source_image_reference"].as_str().unwrap(); + fs::write(&path, png_bytes(1, 1)).unwrap(); + let result = tool + .call_impl(&json!({ "path": reference }), &context) + .await + .unwrap(); + let ToolResult::Result { + data, + image_attachments: Some(images), + .. + } = &result[0] + else { + panic!("expected image") + }; + assert_eq!(data["source_image_reference"], reference); + assert_eq!( + base64::engine::general_purpose::STANDARD + .decode(&images[0].data_base64) + .unwrap(), + original + ); + } + + #[tokio::test] + async fn image_snapshot_reopens_a_pathless_tool_frame_on_its_runtime() { + use crate::agentic::image_analysis::attachments::{ + restore_tool_images, tool_image_references, + }; + use base64::Engine; + let root = tempfile::tempdir().unwrap(); + let mut context = remote_context("openai", true); + context + .custom_data + .insert("__openbitfun_test_runtime_root".into(), json!(root.path())); + let original = png_bytes(3, 2); + let frame = crate::util::types::ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: base64::engine::general_purpose::STANDARD.encode(&original), + }; + let references = tool_image_references(std::slice::from_ref(&frame), &context) + .await + .unwrap(); + let reference = &references[0]; + assert!(reference.starts_with("openbitfun://runtime/workspace-remote/attachments/images/")); + let restored = restore_tool_images(&references, &context).await.unwrap(); + assert_eq!(restored[0].data_base64, frame.data_base64); + let result = ViewImageTool::new() + .call_impl(&json!({ "path": reference }), &context) + .await + .unwrap(); + let ToolResult::Result { + data, + image_attachments: Some(images), + .. + } = &result[0] + else { + panic!("expected image") + }; + assert_eq!(data["path"], reference.as_str()); + assert_eq!(data["source_image_reference"], reference.as_str()); + assert_eq!(images[0].data_base64, frame.data_base64); + assert!(!data.to_string().contains(root.path().to_str().unwrap())); + } + #[tokio::test] async fn view_image_attaches_local_image() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/crates/contracts/core-types/src/errors.rs b/src/crates/contracts/core-types/src/errors.rs index c1503421cd..f3a2d10e6a 100644 --- a/src/crates/contracts/core-types/src/errors.rs +++ b/src/crates/contracts/core-types/src/errors.rs @@ -101,6 +101,11 @@ impl AiProviderError { http_status: Option, ) -> Self { let category = classify_ai_error_parts(&message, provider_code.as_deref(), http_status); + let message = if http_status == Some(413) && category == ErrorCategory::InvalidRequest { + format!("The request body is too large. Crop images or send attachments in smaller batches. {message}") + } else { + message + }; Self { message, category, @@ -184,6 +189,15 @@ pub fn classify_ai_error_parts( ) { return ErrorCategory::ContextOverflow; } + // Some model servers report a token limit with HTTP 413. A proxy returning + // the same status for a byte limit has no recoverable context-window error. + if http_status == Some(413) { + return if is_context_overflow_message(&message.to_ascii_lowercase()) { + ErrorCategory::ContextOverflow + } else { + ErrorCategory::InvalidRequest + }; + } match code.as_str() { "insufficient_quota" | "quota_exceeded" | "usage_limit_reached" => { return ErrorCategory::ProviderQuota; @@ -204,11 +218,14 @@ pub fn classify_ai_error_parts( return category; } - if matches!(code.as_str(), "invalid_request_error" | "invalid_prompt") { + if matches!( + code.as_str(), + "invalid_request_error" | "invalid_prompt" | "request_too_large" + ) { return ErrorCategory::InvalidRequest; } - if matches!(http_status, Some(400 | 404 | 409 | 413 | 422)) { + if matches!(http_status, Some(400 | 404 | 409 | 422)) { ErrorCategory::InvalidRequest } else { category @@ -365,6 +382,9 @@ pub fn classify_ai_error_message(msg: &str) -> ErrorCategory { "model not found", "unsupported model", "request too large", + "request_too_large", + "request entity too large", + "payload too large", "http 400", "error 400", "http 413", @@ -477,11 +497,9 @@ fn is_context_overflow_message(message: &str) -> bool { "greater than the context length", "prompt is too long", "prompt too long; exceeded", - "request_too_large", "input is too long for requested model", "tokens in request more than max tokens allowed", "reduce the length of the messages", - "request entity too large", ], ) || ((message.contains("input") || message.contains("prompt")) && message.contains("token") @@ -683,13 +701,45 @@ mod tests { } #[test] - fn classifies_common_provider_context_overflow_messages() { + fn http_413_distinguishes_body_size_from_an_explicit_model_token_limit() { for message in [ "request_too_large", + "Request Entity Too Large", + "Payload Too Large", + ] { + assert_eq!( + classify_ai_error_message(message), + ErrorCategory::InvalidRequest + ); + let error = AiProviderError::from_parts(message.into(), None, None, Some(413)); + assert_eq!(error.category, ErrorCategory::InvalidRequest); + assert_eq!(error.detail().retryable, Some(false)); + assert!(error.message.contains("smaller batches")); + } + for (message, code) in [ + ("request rejected", Some("context_length_exceeded")), + ( + "Input token count exceeds the model limit", + Some("request_too_large"), + ), + ] { + let error = AiProviderError::from_parts( + message.into(), + None, + code.map(str::to_owned), + Some(413), + ); + assert_eq!(error.category, ErrorCategory::ContextOverflow); + assert!(!error.message.contains("smaller batches")); + } + } + + #[test] + fn classifies_common_provider_context_overflow_messages() { + for message in [ "Input is too long for requested model", "tokens in request more than max tokens allowed", "Please reduce the length of the messages or completion", - "request entity too large", "model_context_window_exceeded", "context window exceeds limit", "maximum prompt length is 200000", diff --git a/src/web-ui/src/locales/en-US/errors.json b/src/web-ui/src/locales/en-US/errors.json index 3d1e3bc777..3b88b8edbb 100644 --- a/src/web-ui/src/locales/en-US/errors.json +++ b/src/web-ui/src/locales/en-US/errors.json @@ -86,6 +86,10 @@ "title": "Model permission denied", "message": "The API key does not have permission to use this model or endpoint. Check the model configuration or switch models." }, + "payloadTooLarge": { + "title": "Request body is too large", + "message": "Crop images to the area you need or send attachments in smaller batches." + }, "invalidRequest": { "title": "Model request invalid", "message": "The provider rejected the request format, parameters, model name, or payload size. Adjust the request or choose another model." diff --git a/src/web-ui/src/locales/zh-CN/errors.json b/src/web-ui/src/locales/zh-CN/errors.json index 4fde099c17..a44f612054 100644 --- a/src/web-ui/src/locales/zh-CN/errors.json +++ b/src/web-ui/src/locales/zh-CN/errors.json @@ -86,6 +86,10 @@ "title": "模型权限不足", "message": "当前 API Key 无权使用该模型或接口。请检查模型配置,或切换到其他模型。" }, + "payloadTooLarge": { + "title": "请求体过大", + "message": "请将图片裁剪到需要查看的区域,或分批发送附件。" + }, "invalidRequest": { "title": "模型请求无效", "message": "模型服务商拒绝了请求格式、参数、模型名称或负载大小。请调整请求或选择其他模型。" diff --git a/src/web-ui/src/locales/zh-TW/errors.json b/src/web-ui/src/locales/zh-TW/errors.json index bd286c29a1..52fd575e3e 100644 --- a/src/web-ui/src/locales/zh-TW/errors.json +++ b/src/web-ui/src/locales/zh-TW/errors.json @@ -86,6 +86,10 @@ "title": "模型權限不足", "message": "目前 API Key 無權使用該模型或接口。請檢查模型設定,或切換到其他模型。" }, + "payloadTooLarge": { + "title": "請求內容過大", + "message": "請將圖片裁切至需要查看的區域,或分批傳送附件。" + }, "invalidRequest": { "title": "模型請求無效", "message": "模型服務商拒絕了請求格式、參數、模型名稱或負載大小。請調整請求或選擇其他模型。" diff --git a/src/web-ui/src/shared/ai-errors/aiErrorPresenter.test.ts b/src/web-ui/src/shared/ai-errors/aiErrorPresenter.test.ts index 4ee3fa10c0..08f69c872a 100644 --- a/src/web-ui/src/shared/ai-errors/aiErrorPresenter.test.ts +++ b/src/web-ui/src/shared/ai-errors/aiErrorPresenter.test.ts @@ -67,6 +67,18 @@ describe('aiErrorPresenter', () => { } }); + it('shows attachment guidance for oversized bodies and keeps token recovery for model context errors', () => { + const oversized = getAiErrorPresentation({ category: 'invalid_request', httpStatus: 413 }); + expect(oversized.titleKey).toBe('errors:ai.payloadTooLarge.title'); + expect(oversized.messageKey).toBe('errors:ai.payloadTooLarge.message'); + expect(oversized.retryable).toBe(false); + + const overflow = getAiErrorPresentation({ category: 'context_overflow', httpStatus: 413 }); + expect(overflow.titleKey).toBe('errors:ai.contextOverflow'); + expect(overflow.messageKey).toBe('errors:ai.contextOverflowSuggestion'); + expect(overflow.actions.map((action) => action.code)).toContain('compress_context'); + }); + it('keeps overloaded provider errors retryable without exposing raw payloads', () => { const detail = normalizeAiErrorDetail({ category: 'unknown', diff --git a/src/web-ui/src/shared/ai-errors/aiErrorPresenter.ts b/src/web-ui/src/shared/ai-errors/aiErrorPresenter.ts index c7afba066d..044daf6cab 100644 --- a/src/web-ui/src/shared/ai-errors/aiErrorPresenter.ts +++ b/src/web-ui/src/shared/ai-errors/aiErrorPresenter.ts @@ -174,12 +174,13 @@ export function getAiErrorPresentation(detail: AiErrorDetail): AiErrorPresentati const normalized = normalizeAiErrorDetail(detail); const category = normalized.category ?? 'unknown'; const config = PRESENTATION_KEYS[category] ?? PRESENTATION_KEYS.unknown; + const payloadTooLarge = category === 'invalid_request' && normalized.httpStatus === 413; const actionCodes = normalized.actionHints?.length ? normalized.actionHints : DEFAULT_ACTIONS[category]; return { category, - titleKey: config.titleKey, - messageKey: config.messageKey, + titleKey: payloadTooLarge ? 'errors:ai.payloadTooLarge.title' : config.titleKey, + messageKey: payloadTooLarge ? 'errors:ai.payloadTooLarge.message' : config.messageKey, severity: config.severity, retryable: normalized.retryable ?? RETRYABLE_CATEGORIES.has(category), actions: actionCodes.map((code) => ({ code, labelKey: ACTION_LABEL_KEYS[code] })), From fdb6771cb85627fda56c7b20c3b2b02980d2cbff Mon Sep 17 00:00:00 2001 From: kev1n77 Date: Wed, 25 Nov 2026 16:44:52 +0800 Subject: [PATCH 3/3] fix: address image request review findings --- .../cache-friendly-message-structure.md | 10 +- src/crates/adapters/ai-adapters/src/client.rs | 72 ++++++- .../ai-adapters/src/client/image_budget.rs | 91 +++++++- .../src/client/image_budget/context.rs | 162 +++++++++----- .../src/client/image_budget/context_tests.rs | 185 ++++++++++++++-- .../src/providers/gemini/code_assist.rs | 30 ++- .../src/providers/gemini/message_converter.rs | 201 +++++++++--------- .../src/providers/gemini/request.rs | 57 +++++ .../src/agentic/execution/compression_job.rs | 11 +- .../src/agentic/execution/execution_engine.rs | 144 +++++++++++-- .../agentic/execution/prompt_suggestion.rs | 12 +- .../src/agentic/execution/round_executor.rs | 3 +- .../src/agentic/image_analysis/attachments.rs | 111 ++++++++-- .../core/src/agentic/persistence/manager.rs | 2 +- .../src/agentic/persistence/session_branch.rs | 65 +++++- .../session/session_manager/tests/deletion.rs | 91 ++++++++ .../tools/implementations/view_image_tool.rs | 13 +- src/crates/contracts/core-types/src/ai.rs | 2 + 18 files changed, 1020 insertions(+), 242 deletions(-) diff --git a/docs/architecture/cache-friendly-message-structure.md b/docs/architecture/cache-friendly-message-structure.md index dddcd49744..285d138f8b 100644 --- a/docs/architecture/cache-friendly-message-structure.md +++ b/docs/architecture/cache-friendly-message-structure.md @@ -304,10 +304,12 @@ Important exceptions: summary form, then invalidates prompt cache and starts a new stable prefix - Each request sends pixels from pending user uploads and new tool observations, including parallel tool results. After an assistant response, those messages - carry text and available image references on later requests. Reopening a - referenced image supplies a new observation. This changes the provider cache - prefix at the first replaced image. Model-pool image requirements use the same - pending observations. The session retains the original attachments. + carry text and available image references on later requests. A vision route + without `view_image` keeps the most recent user upload within the request + budget. Reopening a reference supplies a new observation and changes the + provider cache prefix at the first replaced image. Session-scoped tool image + snapshots follow session deletion. A fork copies the snapshots referenced by + the history it retains. ## Session Storage Layout diff --git a/src/crates/adapters/ai-adapters/src/client.rs b/src/crates/adapters/ai-adapters/src/client.rs index 9853e76e90..a9b979750d 100644 --- a/src/crates/adapters/ai-adapters/src/client.rs +++ b/src/crates/adapters/ai-adapters/src/client.rs @@ -26,7 +26,7 @@ use crate::types::*; use anyhow::Result; use format::ApiFormat; use log::warn; -use openbitfun_core_types::errors::AiProviderError; +use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; use reqwest::Client; use std::time::Duration; use std::{fmt, future::Future, pin::Pin, sync::Arc}; @@ -631,8 +631,6 @@ impl AIClient { request_context: Option<&ModelRequestContext>, extra_body: Option<&serde_json::Value>, ) -> Result> { - #[cfg(not(feature = "vision-input"))] - let _ = tools; // Project only the outgoing copy, against the actual selected client. responses_websocket::validate(self)?; // Account/channel failover and direct analysis calls share this boundary. @@ -641,11 +639,15 @@ impl AIClient { self.config.max_images_per_request, request_context.and_then(|context| context.image_turn_start), ApiFormat::parse(&self.config.format)?, + request_context.map_or_else( + || tools.is_none_or(<[_]>::is_empty), + |context| context.retain_latest_user_image, + ), )?; image_budget::validate_extra_body(self.config.max_images_per_request, extra_body)?; #[cfg(feature = "vision-input")] let replaced = image_budget::context::validate_override( - &self.config, + self, &messages, tools, request_context, @@ -658,11 +660,11 @@ impl AIClient { .any(image_budget::context::may_contain_images) { let budget = image_budget::context::Budget::for_request( - &self.config, + self, tools, request_context, extra_body, - ); + )?; // Decoding and resampling a large screenshot can occupy a CPU for // a full scheduling slice. Keep it off the async transport worker. tokio::task::spawn_blocking(move || -> Result<_> { @@ -685,6 +687,64 @@ impl AIClient { max_tries: usize, trace: Option, request_context: Option, + ) -> Result { + let can_reduce_batch = extra_body.as_ref().is_none_or(|body| { + ["messages", "input", "contents"] + .iter() + .all(|key| body.get(key).is_none()) + }); + let Some(smaller) = can_reduce_batch + .then(|| image_budget::smaller_tool_batch(&messages)) + .flatten() + else { + return self + .send_wire_message_stream( + messages, + tools, + extra_body, + max_tries, + trace, + request_context, + ) + .await; + }; + let outcome = self + .send_wire_message_stream( + messages, + tools.clone(), + extra_body.clone(), + max_tries, + trace.clone(), + request_context.clone(), + ) + .await; + if let Err(error) = &outcome { + if error + .downcast_ref::() + .is_some_and(|error| { + error.http_status == Some(413) + && error.category == ErrorCategory::InvalidRequest + && !error.delivery_uncertain + }) + { + // Only a confirmed byte-limit rejection is safe to resend. This + // retry changes the body and retains the tool-call protocol. + return self + .send_wire_message_stream(smaller, tools, extra_body, 1, trace, request_context) + .await; + } + } + outcome + } + + async fn send_wire_message_stream( + &self, + messages: Vec, + tools: Option>, + extra_body: Option, + max_tries: usize, + trace: Option, + request_context: Option, ) -> Result { match ApiFormat::parse(&self.config.format)? { ApiFormat::OpenAIChat => { diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget.rs b/src/crates/adapters/ai-adapters/src/client/image_budget.rs index cce5e24114..98fe16bef8 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget.rs @@ -42,8 +42,9 @@ pub(super) fn project( max_images: Option, turn_start: Option, format: ApiFormat, + retain_latest_user_image: bool, ) -> Result> { - project_history(&mut messages, turn_start, format); + project_history(&mut messages, turn_start, format, retain_latest_user_image); let Some(mut remaining) = max_images else { return Ok(messages); }; @@ -88,15 +89,73 @@ pub(super) fn project( Ok(messages) } +/// A gateway can reject a batch even when all its images fit the context window. +pub(super) fn smaller_tool_batch(messages: &[Message]) -> Option> { + let count = messages + .iter() + .filter(|message| message.role == "tool") + .map(|message| message.tool_image_attachments.as_ref().map_or(0, Vec::len)) + .sum::(); + if count < 2 { + return None; + } + let mut keep_one = true; + let mut reduced = Vec::with_capacity(messages.len()); + for message in messages.iter().rev() { + let attachments = message + .tool_image_attachments + .as_deref() + .unwrap_or_default(); + if message.role != "tool" || attachments.is_empty() { + reduced.push(message.clone()); + continue; + } + let keep = usize::from(std::mem::take(&mut keep_one)); + let mut adjusted = Message { + content: message.content.clone(), + role: message.role.clone(), + reasoning_content: message.reasoning_content.clone(), + thinking_signature: message.thinking_signature.clone(), + tool_calls: message.tool_calls.clone(), + tool_call_id: message.tool_call_id.clone(), + name: message.name.clone(), + is_error: message.is_error, + model_response_replay: message.model_response_replay.clone(), + tool_image_attachments: (keep > 0).then(|| attachments[..keep].to_vec()), + }; + if attachments.len() > keep { + let text = adjusted.content.get_or_insert_with(String::new); + text.push_str("\n[Some tool images were omitted to fit the request body. Read the images in separate calls if needed.]"); + } + reduced.push(adjusted); + } + reduced.reverse(); + Some(reduced) +} + /// A response confirms receipt of all preceding inputs. Consecutive user /// messages or parallel tool results after it may still await their first send. -fn project_history(messages: &mut [Message], turn_start: Option, format: ApiFormat) { +fn project_history( + messages: &mut [Message], + turn_start: Option, + format: ApiFormat, + retain_latest_user_image: bool, +) { let turn_start = turn_start.unwrap_or(0).min(messages.len()); let pending_start = messages[turn_start..] .iter() .rposition(|message| message.role == "assistant") .map_or(turn_start, |index| turn_start + index + 1); - for message in &mut messages[..pending_start] { + let retained = retain_latest_user_image + .then(|| { + messages.iter().rposition(|message| { + message.role == "user" + && user_parts(&message.content, format) + .is_some_and(|parts| parts.iter().any(is_image_part)) + }) + }) + .flatten(); + for (index, message) in messages[..pending_start].iter_mut().enumerate() { match message.role.as_str() { "tool" => { if let Some(images) = message @@ -111,7 +170,7 @@ fn project_history(messages: &mut [Message], turn_start: Option, format: )); } } - "user" => { + "user" if Some(index) != retained => { let Some(mut parts) = user_parts(&message.content, format) else { continue; }; @@ -123,7 +182,8 @@ fn project_history(messages: &mut [Message], turn_start: Option, format: .or_else(|| url.as_str()) .or_else(|| part["source"]["url"].as_str()) .filter(|url| url.starts_with("https://") || url.starts_with("http://")) - .or_else(|| part["file_id"].as_str()); + .or_else(|| part["file_id"].as_str()) + .or_else(|| part["source"]["file_id"].as_str()); let text = match reference { Some(reference) => format!("[Earlier image reference: {reference}]"), None => "[Earlier image. Reattach or read it again if pixels are needed.]" @@ -154,6 +214,11 @@ fn user_parts(content: &Option, format: ApiFormat) -> Option> { return None; } + if matches!(format, ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + && !crate::providers::GeminiMessageConverter::is_user_content_parts(&parts) + { + return None; + } Some(parts) } @@ -214,6 +279,8 @@ fn is_image_part(part: &Value) -> bool { } Some("image") => part.get("source").is_some_and(|source| { image_url(source.get("url")) + || (source["type"] == "file" + && source["file_id"].as_str().is_some_and(|id| !id.is_empty())) || (source .get("media_type") .and_then(Value::as_str) @@ -247,7 +314,7 @@ mod tests { use crate::types::ToolImageAttachment; fn project(messages: Vec, max_images: Option) -> Result> { - super::project(messages, max_images, None, ApiFormat::OpenAIChat) + super::project(messages, max_images, None, ApiFormat::OpenAIChat, false) } fn image(id: &str) -> Value { @@ -612,8 +679,14 @@ mod tests { Message::user("Review the details.".into()), ]; let original = serde_json::to_value(&messages).unwrap(); - let projected = - super::project(messages.clone(), None, None, ApiFormat::OpenAIResponses).unwrap(); + let projected = super::project( + messages.clone(), + None, + None, + ApiFormat::OpenAIResponses, + false, + ) + .unwrap(); let old = projected[0].content.as_deref().unwrap(); assert!( old.contains(url) @@ -710,7 +783,7 @@ mod tests { (ApiFormat::Gemini, "gemini-3-pro"), (ApiFormat::Gemini, "gemini-2.5-pro"), ] { - let projected = super::project(history.clone(), None, None, format).unwrap(); + let projected = super::project(history.clone(), None, None, format, false).unwrap(); let wire = match format { ApiFormat::OpenAIChat => OpenAIMessageConverter::convert_messages(projected), ApiFormat::OpenAIResponses => { diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs index 97696b662b..63b56cb63f 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs @@ -3,11 +3,15 @@ use super::{inline_media, is_image_part, user_parts}; use crate::client::format::ApiFormat; -use crate::providers::openai::OpenAIMessageConverter; +use crate::providers::{ + anthropic, gemini, + openai::{self, OpenAIMessageConverter}, +}; use crate::types::{AIConfig, Message, ModelRequestContext, ToolDefinition}; use crate::vision_tokens::{ inline_image_dimensions, ResizedInlineImage, VisionTokenPolicy, UNKNOWN_IMAGE_DIMENSIONS, }; +use crate::AIClient; use anyhow::Result; use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; use openbitfun_core_types::token_estimate::{ @@ -144,30 +148,61 @@ fn resize_preview( }) } -fn output_reserve(config: &AIConfig, extra: Option<&Value>) -> usize { - let default = if config.format.eq_ignore_ascii_case("anthropic") { - 32_000 - } else { - automatic_max_output_tokens(config.context_window) +fn request_options(client: &AIClient, format: ApiFormat, extra: Option<&Value>) -> Result { + let url = &client.config.request_url; + let extra = extra.and_then(Value::as_object).map(|fields| { + Value::Object( + fields + .iter() + .filter(|(key, _)| !matches!(key.as_str(), "messages" | "input" | "contents")) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(), + ) + }); + match format { + ApiFormat::OpenAIChat => { + openai::chat::try_build_request_body(client, url, vec![], None, extra) + } + ApiFormat::OpenAIResponses if openai::codex_chatgpt::is_codex_chatgpt_endpoint(url) => { + openai::codex_chatgpt::try_build_request_body(client, None, vec![], None, extra) + } + ApiFormat::OpenAIResponses => { + openai::responses::try_build_request_body(client, None, vec![], None, extra) + } + ApiFormat::Anthropic => { + anthropic::request::try_build_request_body(client, url, None, vec![], None, extra) + } + ApiFormat::Gemini => { + gemini::request::try_build_request_body(client, None, vec![], None, extra) + } + ApiFormat::GeminiCodeAssist => { + gemini::code_assist::image_budget_request_options(client, extra) + } + } +} + +fn output_reserve(config: &AIConfig, format: ApiFormat, options: &Value) -> usize { + let cap = match format { + ApiFormat::OpenAIChat => options["max_completion_tokens"] + .as_u64() + .or_else(|| options["max_tokens"].as_u64()), + ApiFormat::OpenAIResponses => options["max_output_tokens"].as_u64(), + ApiFormat::Anthropic => options["max_tokens"].as_u64(), + ApiFormat::Gemini | ApiFormat::GeminiCodeAssist => { + options["generationConfig"]["maxOutputTokens"].as_u64() + } }; - let configured = config.max_tokens.unwrap_or(default) as usize; - // Custom request bodies can raise the wire output cap on compatible gateways. - [ - "/max_tokens", - "/max_completion_tokens", - "/max_output_tokens", - "/generationConfig/maxOutputTokens", - ] - .into_iter() - .filter_map(|path| extra?.pointer(path)?.as_u64()) - .fold(configured, |cap, value| { - cap.max(usize::try_from(value).unwrap_or(usize::MAX)) - }) + cap.map_or_else( + || automatic_max_output_tokens(config.context_window) as usize, + |value| usize::try_from(value).unwrap_or(usize::MAX), + ) } /// Admission facts captured from the client selected for *this* send. pub(in crate::client) struct Budget { - format: Option, + format: ApiFormat, + model_override: bool, + external_history: bool, policy: VisionTokenPolicy, limit: usize, tools: usize, @@ -177,16 +212,19 @@ pub(in crate::client) struct Budget { impl Budget { pub(in crate::client) fn for_request( - config: &AIConfig, + client: &AIClient, tools: Option<&[ToolDefinition]>, context: Option<&ModelRequestContext>, extra: Option<&Value>, - ) -> Self { + ) -> Result { + let config = &client.config; + let format = ApiFormat::parse(&config.format)?; + // Use the same provider merge and reserved-field rules as transport, + // without converting or cloning the runtime messages and tool schema. + let options = request_options(client, format, extra)?; let window = config.context_window as usize; - // Leave input space for clients whose entire window is smaller than - // the ordinary compression safety reserve. let limit = window - .saturating_sub(output_reserve(config, extra)) + .saturating_sub(output_reserve(config, format, &options)) .saturating_sub(INPUT_SAFETY_RESERVE.min(window / 3)); let wire_overhead = |value: &Value| TokenCounter::estimate_tokens(&value.to_string()); let schema = context @@ -212,28 +250,25 @@ impl Budget { .and_then(|body| body.get("tools")) .map_or(0, wire_overhead), ); - let format = ApiFormat::parse(&config.format).ok(); - let body_selects_model = !crate::client::utils::is_trim_custom_request_body_mode(config) + let model = if format == ApiFormat::Gemini { + &config.model + } else { + options["model"].as_str().unwrap_or(&config.model) + }; + let model_override = model != config.model && matches!( format, - Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses | ApiFormat::Anthropic) + ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses | ApiFormat::Anthropic ); - let model = if body_selects_model { - extra - .and_then(|body| body["model"].as_str()) - .unwrap_or(&config.model) - } else { - &config.model - }; + let external_history = format == ApiFormat::OpenAIResponses + && ["previous_response_id", "conversation"] + .iter() + .any(|key| options.get(key).is_some_and(|value| !value.is_null())); let mut policy = VisionTokenPolicy::for_model(model); - if matches!( - format, - Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) - ) { - let generation = extra.and_then(|body| { - body.get("generationConfig") - .or_else(|| body.get("generation_config")) - }); + if matches!(format, ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) { + let generation = options + .get("generationConfig") + .or_else(|| options.get("generation_config")); policy = policy.with_gemini_media_resolution(generation.and_then(|config| { config .get("mediaResolution") @@ -241,27 +276,44 @@ impl Budget { .as_str() })); } - Self { + Ok(Self { format, + model_override, + external_history, policy, limit, tools, schema, text_floor: context.map_or(0, |ctx| ctx.minimum_non_image_input_tokens), + }) + } + + fn check_image_scope(&self) -> Result<()> { + if self.model_override { + return Err(image_budget_error( + "The custom request changes the model for an image input. Configure that model and its context window directly, and remove the model override.".into(), + )); } + if self.external_history { + return Err(image_budget_error( + "Image requests with a custom Responses conversation or previous_response_id cannot be budgeted locally. Send the full history or use managed Responses WebSocket continuation.".into(), + )); + } + Ok(()) } } /// A raw provider message override has no application turn or attachment identity. /// Keep it intact when it fits; report oversized image overrides before transport. pub(in crate::client) fn validate_override( - config: &AIConfig, + client: &AIClient, messages: &[Message], tools: Option<&[ToolDefinition]>, context: Option<&ModelRequestContext>, body: Option<&Value>, ) -> Result { let Some(body) = body else { return Ok(false) }; + let config = &client.config; let (key, system_key) = match ApiFormat::parse(&config.format)? { ApiFormat::OpenAIChat => ("messages", None), ApiFormat::Anthropic => ("messages", Some("system")), @@ -315,14 +367,15 @@ pub(in crate::client) fn validate_override( _ => 1, } } - let budget = Budget::for_request(config, tools, context, Some(body)); + let budget = Budget::for_request(client, tools, context, Some(body))?; let mut saw_image = false; let gemini = matches!( budget.format, - Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + ApiFormat::Gemini | ApiFormat::GeminiCodeAssist ); let cost = count(override_messages, budget.policy, gemini, &mut saw_image); if saw_image { + budget.check_image_scope()?; // Responses, Anthropic and Gemini send system messages in a separate // field, which survives an override of just input/messages/contents. let preserved_system = if system_key.is_some_and(|key| body.get(key).is_none()) { @@ -369,8 +422,12 @@ pub(super) fn project( messages, context.and_then(|ctx| ctx.image_turn_start), ApiFormat::parse(&config.format)?, + context.is_some_and(|ctx| ctx.retain_latest_user_image), ); - apply(messages, Budget::for_request(config, tools, context, extra)) + apply( + messages, + Budget::for_request(&AIClient::new(config.clone()), tools, context, extra)?, + ) } // Desktop and browser control actions reuse the exact coordinates of their @@ -413,10 +470,7 @@ pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Resu )); } } else if message.role == "user" { - let Some(parts) = budget - .format - .and_then(|format| user_parts(&message.content, format)) - else { + let Some(parts) = user_parts(&message.content, budget.format) else { continue; }; let before = images.len(); @@ -434,8 +488,7 @@ pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Resu )); } if images.len() > before { - if let Some(format @ (ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses)) = - budget.format + if let format @ (ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses) = budget.format { if let Some(part) = parts.iter().position(|part| { !OpenAIMessageConverter::can_render_user_part(part, format) @@ -453,6 +506,7 @@ pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Resu if images.is_empty() { return Ok(()); } + budget.check_image_scope()?; let mut text = 3 + budget.tools; for (index, message) in messages.iter().enumerate() { diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs index b1ea21b8fd..a7e7151097 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs @@ -291,7 +291,10 @@ fn openai_low_detail_fits_at_the_selected_models_base_cost() { let mut overridden = [Message::user( json!([{"type":"image_url","image_url":{"url":url,"detail":"low"}}]).to_string(), )]; - project(&mut overridden, &config, None, Some(&context), Some(&extra)).unwrap(); + let error = project(&mut overridden, &config, None, Some(&context), Some(&extra)).unwrap_err(); + assert!(error + .to_string() + .contains("custom request changes the model")); config.custom_request_body_mode = Some("trim".into()); assert!(project(&mut overridden, &config, None, Some(&context), Some(&extra)).is_err()); config.model = "gpt-4o".into(); @@ -344,12 +347,26 @@ fn gemini_uses_global_resolution_for_projected_images_and_override_parts_on_the_ "mediaResolution": {"level":"MEDIA_RESOLUTION_ULTRA_HIGH"} }]}] }); - assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).is_err()); + assert!(super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&raw) + ) + .is_err()); raw["contents"][0]["parts"][0] .as_object_mut() .unwrap() .remove("mediaResolution"); - assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).unwrap()); + assert!(super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&raw) + ) + .unwrap()); } #[test] @@ -586,15 +603,49 @@ async fn later_http_rounds_send_only_fresh_pixels_under_a_gateway_body_limit() { .await .unwrap(); } + let calls = ["batch-a", "batch-b"] + .into_iter() + .map(|id| crate::ToolCall { + id: id.into(), + name: "view_image".into(), + arguments: json!({"path":id}), + raw_arguments: None, + }) + .collect(); + let mut batch = vec![ + Message::user("Read both screenshots".into()), + Message::assistant_with_tools(calls), + ]; + for (id, pixels) in [("batch-a", &a), ("batch-b", &b)] { + let mut result = tool_result("view_image", pixels); + result.tool_call_id = Some(id.into()); + batch.push(result); + } + client + .send_message_once_with_trace_and_request_context(batch, None, None, None) + .await + .expect("a 413 must allow a smaller tool-image batch to succeed"); server.abort(); let requests = requests.lock().unwrap(); - assert_eq!(requests.len(), 4); + assert_eq!(requests.len(), 5); for (wire, (expected_a, expected_b)) in requests.iter().zip([(1, 0), (0, 0), (0, 1), (1, 0)]) { assert!(wire.len() <= limit); let json = std::str::from_utf8(wire).unwrap(); assert_eq!(json.matches(a.as_str()).count(), expected_a); assert_eq!(json.matches(b.as_str()).count(), expected_b); } + let recovered = std::str::from_utf8(&requests[4]).unwrap(); + assert!(!recovered.contains(&a)); + assert!(recovered.contains(&b)); + assert!(recovered.contains("omitted to fit the request body")); + let body: Value = serde_json::from_str(recovered).unwrap(); + let tool_ids: Vec<_> = body["messages"] + .as_array() + .unwrap() + .iter() + .filter_map(|part| part["tool_call_id"].as_str()) + .collect(); + assert_eq!(tool_ids, ["batch-a", "batch-b"]); assert!(requests[1].len() < 8192); assert_eq!( history[2].tool_image_attachments.as_ref().unwrap()[0].data_base64, @@ -610,10 +661,23 @@ fn custom_image_payload_must_fit_the_actual_output_reserve() { let native: Value = serde_json::from_str(uploaded(&png(1024, 1024)).content.as_deref().unwrap()).unwrap(); let mut body = json!({"messages": [{"role": "user", "content": native}]}); - super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap(); + super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&body), + ) + .unwrap(); body["max_completion_tokens"] = json!(21_999); - let error = - super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap_err(); + let error = super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&body), + ) + .unwrap_err(); assert_eq!( error .downcast_ref::() @@ -624,15 +688,33 @@ fn custom_image_payload_must_fit_the_actual_output_reserve() { config.format = "responses".into(); let native = body["messages"].take(); let responses = json!({"input": native, "max_output_tokens": 20_500}); - assert!(super::context::validate_override(&config, &[], None, None, Some(&responses)).unwrap()); + assert!(super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&responses) + ) + .unwrap()); let system = Message::system("long instruction ".repeat(500)); - assert!( - super::context::validate_override(&config, &[system], None, None, Some(&responses)) - .is_err() - ); + assert!(super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[system], + None, + None, + Some(&responses) + ) + .is_err()); config.format = "openai".into(); body["messages"] = json!([{"role":"user","content":"hello"}]); - assert!(super::context::validate_override(&config, &[], None, None, Some(&body)).is_ok()); + assert!(super::context::validate_override( + &crate::AIClient::new(config.clone()), + &[], + None, + None, + Some(&body) + ) + .is_ok()); } #[test] @@ -659,3 +741,80 @@ fn deferred_tool_preserves_only_coordinate_bound_frames() { assert_eq!(result.is_ok(), should_fit, "{name}: {result:?}"); } } + +#[test] +fn anthropic_preflight_uses_the_effective_output_override() { + let mut config = config(); + config.format = "anthropic".into(); + config.context_window = 32_000; + config.max_tokens = Some(8_000); + let extra = json!({"max_tokens":1024}); + let message = Message::user( + json!([ + {"type":"text","text":"some words ".repeat(4500)}, + {"type":"image","source":{"type":"base64","media_type":"image/png","data":png(512,512)}} + ]) + .to_string(), + ); + project(&mut [message.clone()], &config, None, None, Some(&extra)).unwrap(); + config.custom_request_body_mode = Some("trim".into()); + let error = project(&mut [message], &config, None, None, Some(&extra)).unwrap_err(); + assert!(error.to_string().contains("14000 available"), "{error}"); +} + +#[test] +fn anthropic_file_images_participate_in_preflight() { + let mut config = config(); + config.format = "anthropic".into(); + config.context_window = 32_000; + config.max_tokens = Some(8_000); + let context = with_remaining_input(&config, 0, 1); + let part = json!({"type":"image","source":{"type":"file","file_id":"file-fixture"}}); + let message = Message::user(json!([part.clone()]).to_string()); + assert!(project(&mut [message], &config, None, Some(&context), None).is_err()); + + let extra = json!({"messages":[{"role":"user","content":[part]}],"max_tokens":22_000}); + let client = crate::AIClient::new(config); + assert!(super::context::validate_override(&client, &[], None, None, Some(&extra)).is_err()); +} + +#[test] +fn responses_does_not_count_an_image_against_only_part_of_an_external_history() { + let mut config = config(); + config.format = "responses".into(); + let client = crate::AIClient::new(config); + let mut input = json!({"input":[{"role":"user","content":[{"type":"input_image", + "image_url":format!("data:image/png;base64,{}", png(512,512))}]}]}); + assert!(super::context::validate_override(&client, &[], None, None, Some(&input)).unwrap()); + for (key, value) in [ + ("previous_response_id", "resp_fixture"), + ("conversation", "conv_fixture"), + ] { + input[key] = json!(value); + let error = + super::context::validate_override(&client, &[], None, None, Some(&input)).unwrap_err(); + assert!(error.to_string().contains("cannot be budgeted locally")); + input.as_object_mut().unwrap().remove(key); + } +} + +#[cfg(feature = "subscription-auth")] +#[tokio::test] +async fn codex_preflight_ignores_output_fields_removed_by_the_subscription_route() { + let mut config = config(); + config.format = "responses".into(); + config.request_url = "https://chatgpt.com/backend-api/codex/responses".into(); + config.context_window = 32_000; + config.max_tokens = Some(8_000); + let client = crate::AIClient::new(config) + .with_subscription_provider(crate::subscription_auth::SubscriptionProvider::Codex); + client + .prepare_message_inputs( + vec![uploaded(&png(512, 512))], + None, + None, + Some(&json!({"max_output_tokens":22_000})), + ) + .await + .unwrap(); +} diff --git a/src/crates/adapters/ai-adapters/src/providers/gemini/code_assist.rs b/src/crates/adapters/ai-adapters/src/providers/gemini/code_assist.rs index 8c0273fa4d..6801e5ff35 100644 --- a/src/crates/adapters/ai-adapters/src/providers/gemini/code_assist.rs +++ b/src/crates/adapters/ai-adapters/src/providers/gemini/code_assist.rs @@ -678,6 +678,26 @@ async fn discover_project(client: &AIClient) -> Result { Ok(remember_project(client, project).await) } +fn wire_model(client: &AIClient, body: &mut serde_json::Value) -> String { + if is_antigravity(client) { + let route = resolve_antigravity_model(&client.config.model, body); + apply_antigravity_thinking(body, &route); + route.model + } else { + client.config.model.clone() + } +} + +#[cfg(feature = "vision-input")] +pub(crate) fn image_budget_request_options( + client: &AIClient, + extra: Option, +) -> Result { + let mut body = gemini_request::try_build_request_body(client, None, vec![], None, extra)?; + body["model"] = serde_json::Value::String(wire_model(client, &mut body)); + Ok(body) +} + pub(crate) async fn send_stream( client: &AIClient, messages: Vec, @@ -700,14 +720,10 @@ pub(crate) async fn send_stream( )?; let antigravity = is_antigravity(client); - let model = if antigravity { - let route = resolve_antigravity_model(&client.config.model, &inner); - apply_antigravity_thinking(&mut inner, &route); + let model = wire_model(client, &mut inner); + if antigravity { inner["sessionId"] = serde_json::json!(antigravity_session_id(&inner)); - route.model - } else { - client.config.model.clone() - }; + } let mut request_body = serde_json::json!({ "model": model, "project": project, diff --git a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs index 5c7bc97e2d..04b9c988eb 100644 --- a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs +++ b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs @@ -377,94 +377,22 @@ impl GeminiMessageConverter { return Vec::new(); } - let parsed = match serde_json::from_str::(content) { - Ok(parsed) if parsed.is_array() => parsed, - _ => return vec![json!({ "text": content })], + let Ok(Value::Array(items)) = serde_json::from_str::(content) else { + return vec![json!({ "text": content })]; }; - - let mut parts = Vec::new(); - - if let Some(items) = parsed.as_array() { - // Untyped {text: ...} also occurs in ordinary user-supplied JSON. - // Interpret it as a native Gemini part only in a recognized part list. - let user_parts = !is_model_role - && items.iter().any(|item| { - item.get("inline_data").is_some() - || item.get("inlineData").is_some() - || matches!( - item["type"].as_str(), - Some( - "text" - | "input_text" - | "output_text" - | "image" - | "image_url" - | "input_image" - ) - ) - }); - for item in items { - let item_type = item.get("type").and_then(Value::as_str); - match item_type { - Some("text" | "input_text" | "output_text") => { - if let Some(text) = item.get("text").and_then(Value::as_str) { - if !text.is_empty() { - parts.push(json!({ "text": text })); - } - } - } - None if user_parts => { - if let Some(inline) = - item.get("inline_data").or_else(|| item.get("inlineData")) - { - let mime = inline - .get("mime_type") - .or_else(|| inline.get("mimeType")) - .and_then(Value::as_str); - if let (Some(mime), Some(data)) = (mime, inline["data"].as_str()) { - parts.push(json!({"inlineData": {"mimeType": mime, "data": data}})); - } - } else if let Some(text) = - item["text"].as_str().filter(|text| !text.is_empty()) - { - parts.push(json!({"text": text})); - } - } - Some("image_url" | "input_image") if !is_model_role => { - if let Some(url) = item.get("image_url").and_then(|value| { - value - .get("url") - .and_then(Value::as_str) - .or_else(|| value.as_str()) - }) { - if let Some(part) = Self::convert_image_url_to_part(url) { - parts.push(part); - } - } - } - Some("image") if !is_model_role => { - let source = item.get("source"); - let mime_type = source - .and_then(|value| value.get("media_type")) - .and_then(Value::as_str); - let data = source - .and_then(|value| value.get("data")) - .and_then(Value::as_str); - - if let (Some(mime_type), Some(data)) = (mime_type, data) { - parts.push(json!({ - "inlineData": { - "mimeType": mime_type, - "data": data, - } - })); - } - } - _ => {} - } - } + if !Self::is_content_parts(&items, is_model_role) { + return vec![json!({ "text": content })]; } - + let parts: Vec<_> = items + .iter() + .filter_map(|item| { + if let Some(text) = item.get("text").and_then(Value::as_str) { + return (!text.is_empty()).then(|| json!({ "text": text })); + } + let (mime, data) = Self::inline_image_payload(item)?; + Some(json!({"inlineData": {"mimeType": mime, "data": data}})) + }) + .collect(); if parts.is_empty() { vec![json!({ "text": content })] } else { @@ -472,25 +400,79 @@ impl GeminiMessageConverter { } } - fn convert_image_url_to_part(url: &str) -> Option { - let prefix = "data:"; - if !url.starts_with(prefix) { - warn!("Gemini currently supports inline data URLs for image parts; skipping unsupported image URL"); - return None; - } + pub(crate) fn is_user_content_parts(items: &[Value]) -> bool { + Self::is_content_parts(items, false) + } - let rest = &url[prefix.len()..]; - let (mime_type, data) = rest.split_once(";base64,")?; - if mime_type.is_empty() || data.is_empty() { - return None; - } + fn is_content_parts(items: &[Value], is_model_role: bool) -> bool { + // A bare array of objects with a text property can be ordinary user JSON. + items + .iter() + .any(|item| item.get("type").is_some() || Self::inline_image_payload(item).is_some()) + && items.iter().all(|item| { + let Some(fields) = item.as_object() else { + return false; + }; + let kind = item["type"].as_str(); + let text = match kind { + Some("text" | "input_text" | "output_text") => fields.len() == 2, + None if !is_model_role => fields.len() == 1, + _ => false, + } && item["text"].is_string(); + text || (!is_model_role && Self::inline_image_payload(item).is_some()) + }) + } - Some(json!({ - "inlineData": { - "mimeType": mime_type, - "data": data, + fn inline_image_payload(item: &Value) -> Option<(&str, &str)> { + let fields = item.as_object()?; + let kind = item.get("type"); + let payload = match kind { + None if fields.keys().all(|key| { + matches!( + key.as_str(), + "inlineData" | "inline_data" | "mediaResolution" | "media_resolution" + ) + }) => + { + item.get("inlineData").or_else(|| item.get("inline_data"))? } - })) + Some(kind) if kind == "image" && fields.len() == 2 => item.get("source")?, + Some(kind) + if (kind == "image_url" || kind == "input_image") + && fields + .keys() + .all(|key| matches!(key.as_str(), "type" | "image_url" | "detail")) => + { + let value = item.get("image_url")?; + let url = value.as_str().or_else(|| { + let fields = value.as_object()?; + fields + .keys() + .all(|key| matches!(key.as_str(), "url" | "detail")) + .then(|| value["url"].as_str()) + .flatten() + })?; + let (mime, data) = url.strip_prefix("data:")?.split_once(";base64,")?; + return (!mime.is_empty() && !data.is_empty()).then_some((mime, data)); + } + _ => return None, + }; + let fields = payload.as_object()?; + if !fields.keys().all(|key| { + matches!( + key.as_str(), + "mimeType" | "mime_type" | "media_type" | "data" + ) || (kind.is_some() && key == "type" && payload["type"] == "base64") + }) { + return None; + } + let mime = payload + .get("mimeType") + .or_else(|| payload.get("mime_type")) + .or_else(|| payload.get("media_type"))? + .as_str()?; + let data = payload["data"].as_str()?; + (!mime.is_empty() && !data.is_empty()).then_some((mime, data)) } fn parse_tool_response(content: Option<&str>) -> Value { @@ -943,10 +925,17 @@ mod tests { ]})] ); - let literal = r#"[{"text":"example JSON"}]"#; - let (_, contents) = - GeminiMessageConverter::convert_messages(vec![Message::user(literal.into())], "gemini"); - assert_eq!(contents[0]["parts"], json!([{"text": literal}])); + for literal in [ + r#"[{"text":"example JSON"}]"#, + r#"[{"type":"text","text":""}]"#, + r#"[{"id":7,"text":"first item"},{"inlineData":{"reference":"attachment-1"}}]"#, + ] { + let (_, contents) = GeminiMessageConverter::convert_messages( + vec![Message::user(literal.into())], + "gemini", + ); + assert_eq!(contents[0]["parts"], json!([{"text": literal}])); + } } #[test] diff --git a/src/crates/adapters/ai-adapters/src/providers/gemini/request.rs b/src/crates/adapters/ai-adapters/src/providers/gemini/request.rs index f8f319df43..2d9290637b 100644 --- a/src/crates/adapters/ai-adapters/src/providers/gemini/request.rs +++ b/src/crates/adapters/ai-adapters/src/providers/gemini/request.rs @@ -12,7 +12,47 @@ use crate::types::{ }; use anyhow::{anyhow, Result}; use log::debug; +use openbitfun_core_types::errors::AiProviderError; use reqwest::RequestBuilder; +use std::io::{self, Write}; + +const GEMINI_INLINE_REQUEST_LIMIT: usize = 20_000_000; + +#[derive(Default)] +struct JsonByteCount(usize); + +impl Write for JsonByteCount { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0 = self.0.saturating_add(bytes.len()); + Ok(bytes.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +fn check_inline_request_size(url: &str, body: &serde_json::Value) -> Result<()> { + // The public Gemini API limits the whole inline request, including JSON + // framing and base64. Custom gateways can enforce their own HTTP limits. + if !reqwest::Url::parse(url).is_ok_and(|url| { + url.scheme() == "https" && url.host_str() == Some("generativelanguage.googleapis.com") + }) { + return Ok(()); + } + let mut size = JsonByteCount::default(); + serde_json::to_writer(&mut size, body)?; + if size.0 > GEMINI_INLINE_REQUEST_LIMIT { + return Err(AiProviderError::from_parts( + "The Gemini request exceeds the 20 MB inline request limit.".into(), + None, + None, + Some(413), + ) + .into()); + } + Ok(()) +} pub(crate) fn apply_headers( client: &AIClient, @@ -571,6 +611,7 @@ pub(crate) async fn send_stream( extra_body, request_context.as_ref(), )?; + check_inline_request_size(&url, &request_body)?; let idle_timeout = client.stream_options.idle_timeout; let ttft_timeout = client.stream_options.ttft_timeout; @@ -595,6 +636,22 @@ mod tests { use super::*; use crate::providers::gemini::{code_assist, discovery}; + #[test] + fn gemini_inline_request_limit_counts_serialized_json_only_on_public_api() { + let url = + "https://generativelanguage.googleapis.com/v1beta/models/test:streamGenerateContent"; + let mut data = "a".repeat(GEMINI_INLINE_REQUEST_LIMIT - 2); + assert!(check_inline_request_size(url, &data.clone().into()).is_ok()); + // A quote occupies two bytes when escaped in a JSON string. + data.pop(); + data.push('"'); + let body = data.into(); + let error = check_inline_request_size(url, &body).unwrap_err(); + let provider = error.downcast_ref::().unwrap(); + assert_eq!(provider.http_status, Some(413)); + assert!(check_inline_request_size("http://localhost:8080/gemini", &body).is_ok()); + } + fn api_key_client(base_url: &str) -> AIClient { AIClient::new( serde_json::from_value(serde_json::json!({ diff --git a/src/crates/assembly/core/src/agentic/execution/compression_job.rs b/src/crates/assembly/core/src/agentic/execution/compression_job.rs index 44e52bf6c6..2d23a0d625 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_job.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_job.rs @@ -220,16 +220,19 @@ impl CompressionJob { } async fn request_summary(&self, plan: &CompressionPlan) -> OpenBitFunResult { + let mut image_context = ToolUseContext::for_tool_listing( + self.workspace.clone(), + self.workspace_services.clone(), + ); + image_context.session_id = Some(self.session_id.clone()); let (mut messages, image_turn_start) = ExecutionEngine::build_ai_message_prefix_for_send( &plan.summary_request_messages, &self.client.config.format, - ToolUseContext::for_tool_listing( - self.workspace.clone(), - self.workspace_services.clone(), - ), + image_context, &self.turn_id, plan.summary_pending_image_start, self.attach_images, + false, &self.reminders.ordered_reminders(), ) .await?; diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs index ac7194aad5..53ff0a0e5d 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs @@ -2276,16 +2276,23 @@ impl ExecutionEngine { let finalize_tool_names = Self::finalize_tool_names(input.tool_definitions.as_deref()); let finalize_runtime_tool_restrictions = Self::finalize_runtime_tool_restrictions(input.context, &finalize_tool_names); - let (mut final_ai_messages, image_turn_start) = Self::build_ai_messages_for_send( + let mut image_context = ToolUseContext::for_tool_listing( + input.context.workspace.clone(), + input.context.workspace_services.clone(), + ); + image_context.session_id = Some(input.context.session_id.clone()); + let (mut final_ai_messages, image_turn_start) = Self::build_ai_message_prefix_for_send( input.messages, &input.ai_client.config.format, - input.context.workspace.as_ref(), - input.context.workspace_services.as_ref(), + image_context, &input.context.dialog_turn_id, + Self::image_turn_start(input.messages, &input.context.dialog_turn_id), input.primary_model_facts.supports_image_inputs, + true, input.prepended_reminders, ) .await?; + final_ai_messages.push(AIMessage::user(render_system_reminder(input.reminder_text))); final_ai_messages.push(AIMessage::user(Self::FINALIZE_USER_FOLLOWUP.to_string())); @@ -2317,6 +2324,7 @@ impl ExecutionEngine { effective_model_name: input.ai_client.config.model.clone(), model_request_context: ModelRequestContext { image_turn_start: Some(image_turn_start), + retain_latest_user_image: true, ..input.model_request_context.clone() }, account_client_source: input.account_client_source.clone(), @@ -2348,6 +2356,7 @@ impl ExecutionEngine { .await } + #[cfg(test)] pub(super) async fn build_ai_messages_for_send( messages: &[Message], provider: &str, @@ -2364,18 +2373,20 @@ impl ExecutionEngine { current_turn_id, Self::image_turn_start(messages, current_turn_id), attach_images, + false, prepended_reminders, ) .await } - async fn build_ai_message_prefix_for_send( + pub(super) async fn build_ai_message_prefix_for_send( messages: &[Message], provider: &str, image_context: ToolUseContext, current_turn_id: &str, current_turn_start: usize, attach_images: bool, + retain_latest_user_image: bool, prepended_reminders: &[&str], ) -> OpenBitFunResult<(Vec, usize)> { let limits = ImageLimits::for_provider(provider); @@ -2395,6 +2406,12 @@ impl ExecutionEngine { let mut prepended_reminders_injected = false; let fresh = Self::fresh_image_start(messages, current_turn_start); + let retained_user_image = retain_latest_user_image.then(|| { + messages.iter().rposition(|message| { + !Self::skip_message_for_model_send(message) + && matches!(&message.content, MessageContent::Multimodal { images, .. } if !images.is_empty()) + }) + }).flatten(); for (msg_idx, msg) in messages.iter().enumerate() { if !prepended_reminders_injected && msg_idx == first_non_system_index { @@ -2415,13 +2432,18 @@ impl ExecutionEngine { match &msg.content { MessageContent::Multimodal { text, images } => { - if msg_idx < fresh && !images.is_empty() { + if msg_idx < fresh && Some(msg_idx) != retained_user_image && !images.is_empty() + { let paths: Vec<&str> = images .iter() .filter_map(|image| image.image_path.as_deref()) .collect(); - let note = - Self::historical_image_note(&paths, attach_images, &image_context); + let note = Self::historical_image_note( + &paths, + attach_images, + retain_latest_user_image, + &image_context, + ); result.push(AIMessage::user(format!("{text}\n\n{note}"))); continue; } @@ -2536,8 +2558,12 @@ impl ExecutionEngine { } else { view_path.into_iter().collect() }; - let note = - Self::historical_image_note(&paths, attach_images, &image_context); + let note = Self::historical_image_note( + &paths, + attach_images, + retain_latest_user_image, + &image_context, + ); if view_image_reply { assistant_text = Some(note); } else { @@ -2583,9 +2609,16 @@ impl ExecutionEngine { fn historical_image_note( paths: &[&str], native_vision: bool, + view_image_unavailable: bool, context: &ToolUseContext, ) -> String { let mut note = String::from("[Earlier image pixels omitted."); + if view_image_unavailable { + note.push_str( + " Ask for a new attachment if the current task requires inspecting them.]", + ); + return note; + } let paths: Vec<_> = paths .iter() .copied() @@ -4837,16 +4870,34 @@ impl ExecutionEngine { &model_fingerprint, selected_pool.is_some(), ); - let (ai_messages, image_turn_start) = Self::build_ai_messages_for_send( + let retain_latest_user_image = primary_supports_image_understanding + && (!enable_tools + || context + .runtime_tool_restrictions + .denied_tool_names + .contains("view_image") + || !available_tools + .iter() + .chain(&deferred_tools) + .any(|name| name == "view_image")); + let mut image_context = ToolUseContext::for_tool_listing( + context.workspace.clone(), + context.workspace_services.clone(), + ); + image_context.session_id = Some(context.session_id.clone()); + let (ai_messages, image_turn_start) = Self::build_ai_message_prefix_for_send( &request_messages, &ai_client.config.format, - context.workspace.as_ref(), - context.workspace_services.as_ref(), + image_context, &context.dialog_turn_id, + Self::image_turn_start(&request_messages, &context.dialog_turn_id), primary_supports_image_understanding, + retain_latest_user_image, &send_prepended_reminders, ) .await?; + model_request_context.retain_latest_user_image = retain_latest_user_image; + round_context.model_request_context.retain_latest_user_image = retain_latest_user_image; round_context.model_request_context.image_turn_start = Some(image_turn_start); round_context @@ -6113,8 +6164,7 @@ mod tests { ContextCompressor, PromptCachePolicy, SessionContextStore, SessionManager, SessionManagerConfig, TokenAnchor, TokenAnchorInput, }; - use crate::agentic::tools::ResolvedToolManifest; - use crate::agentic::tools::ToolRuntimeRestrictions; + use crate::agentic::tools::{ResolvedToolManifest, ToolRuntimeRestrictions, ToolUseContext}; use crate::agentic::workspace::{local_workspace_services, WorkspaceBinding}; use crate::infrastructure::PathManager; @@ -6124,6 +6174,7 @@ mod tests { use crate::service::config::types::AIModelConfig; use crate::service::remote_ssh::workspace_state::workspace_session_identity; use crate::util::types::ToolDefinition; + use openbitfun_core_types::ModelRequestContext; use openbitfun_runtime_ports::{ PermissionMode, WorkspaceDirEntry, WorkspaceFileSystem, WorkspacePathKind, }; @@ -6760,6 +6811,7 @@ mod tests { "inspection", 0, true, + false, &[], ) .await @@ -6775,6 +6827,7 @@ mod tests { "followup", restored.len(), true, + false, &[], ) .await @@ -6787,6 +6840,69 @@ mod tests { assert!(!text.contains("may have changed")); } + #[tokio::test] + async fn image_projection_without_view_tool_keeps_the_latest_upload_on_the_wire() { + use crate::agentic::execution::round_executor::tests::{ + retry_test_success, RetryTestServer, + }; + let server = RetryTestServer::new(vec![retry_test_success(), retry_test_success()]); + let image = crate::agentic::image_analysis::attachments::test_image(); + let mut history = + vec![ + Message::user_multimodal("Look at this screenshot".into(), vec![image]) + .with_turn_id("initial".into()), + ]; + let client = server.client(); + for turn in ["initial", "followup"] { + let (messages, boundary) = ExecutionEngine::build_ai_message_prefix_for_send( + &history, + "openai", + ToolUseContext::for_tool_listing(None, None), + turn, + Message::image_turn_start(&history, turn), + true, + true, + &[], + ) + .await + .unwrap(); + let response = client + .send_message_once_with_trace_and_request_context( + messages, + None, + Some(ModelRequestContext { + image_turn_start: Some(boundary), + retain_latest_user_image: true, + ..Default::default() + }), + None, + ) + .await + .unwrap(); + if turn == "initial" { + history.push(Message::assistant(response.text).with_turn_id("initial".into())); + history.push( + Message::user("Read the value in the lower right".into()) + .with_turn_id("followup".into()), + ); + } + } + let requests = server.requests.lock().unwrap(); + assert_eq!(requests.len(), 2); + for body in requests.iter() { + assert!(body.get("tools").is_none()); + let image_count = body["messages"] + .as_array() + .unwrap() + .iter() + .filter_map(|message| message["content"].as_array()) + .flatten() + .filter(|part| part["type"] == "image_url") + .count(); + assert_eq!(image_count, 1); + } + } + #[tokio::test] async fn image_projection_reuses_the_reference_after_an_assistant_reads_the_image() { let root = tempfile::tempdir().unwrap(); diff --git a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs index 60842d6eec..3a6a7e76e3 100644 --- a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs +++ b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs @@ -76,13 +76,19 @@ pub(super) async fn build_prompt_suggestion_messages( .iter() .map(String::as_str) .collect::>(); - let (mut ai_messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( + let mut image_context = crate::agentic::tools::ToolUseContext::for_tool_listing( + request.workspace.clone(), + request.workspace_services.clone(), + ); + image_context.session_id = Some(request.session_id.clone()); + let (mut ai_messages, image_turn_start) = ExecutionEngine::build_ai_message_prefix_for_send( &request.messages, &request.ai_client.config.format, - request.workspace.as_ref(), - request.workspace_services.as_ref(), + image_context, &request.turn_id, + Message::image_turn_start(&request.messages, &request.turn_id), request.attach_images, + request.model_request_context.retain_latest_user_image, &reminders, ) .await?; diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index 0d29574ffa..681702d452 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -2514,10 +2514,11 @@ impl RoundExecutor { }) .collect(); - let image_context = tool_context_runtime::ToolUseContext::for_tool_listing( + let mut image_context = tool_context_runtime::ToolUseContext::for_tool_listing( context.workspace.clone(), context.workspace_services.clone(), ); + image_context.session_id = Some(context.session_id.clone()); for message in &mut tool_result_messages { if let MessageContent::ToolResult { image_attachments: Some(images), diff --git a/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs b/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs index fd1ce24a50..09b9d62b55 100644 --- a/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs +++ b/src/crates/assembly/core/src/agentic/image_analysis/attachments.rs @@ -16,9 +16,54 @@ fn image_runtime_root(context: &ToolUseContext) -> OpenBitFunResult { } } +const IMAGE_DIRECTORY: &str = "attachments/images"; + +fn snapshot_filename(name: &str) -> bool { + name.split_once('.').is_some_and(|(digest, extension)| { + digest.len() == 64 + && digest.bytes().all(|b| b.is_ascii_hexdigit()) + && matches!(extension, "png" | "jpg" | "gif" | "webp" | "bmp") + }) +} + +fn session_image_reference(relative: &str) -> OpenBitFunResult { + openbitfun_agent_tools::build_openbitfun_current_session_uri(relative) + .map_err(|error| OpenBitFunError::validation(error.to_string())) +} + +fn session_image_name(reference: &str) -> Option { + let parsed = openbitfun_agent_tools::parse_openbitfun_current_session_uri(reference).ok()?; + let name = parsed + .relative_path + .strip_prefix(IMAGE_DIRECTORY)? + .strip_prefix('/')?; + snapshot_filename(name).then(|| name.to_owned()) +} + +pub(crate) async fn copy_session_image_reference( + reference: &str, + source_session_dir: &Path, + target_session_dir: &Path, +) -> OpenBitFunResult<()> { + let Some(name) = session_image_name(reference) else { + return Ok(()); + }; + let source = source_session_dir.join(IMAGE_DIRECTORY).join(&name); + let target = target_session_dir.join(IMAGE_DIRECTORY).join(name); + if target.is_file() { + return Ok(()); + } + let bytes = match tokio::fs::read(&source).await { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(OpenBitFunError::io(error.to_string())), + }; + persist_attachment(&target, bytes).await +} + fn image_reference(context: &ToolUseContext, name: &str) -> OpenBitFunResult { build_tool_runtime_artifact_reference( - &format!("attachments/images/{name}"), + &format!("{IMAGE_DIRECTORY}/{name}"), Some(&image_runtime_root(context)?), context.current_workspace_scope().as_deref(), context.should_emit_runtime_uri(), @@ -28,21 +73,32 @@ fn image_reference(context: &ToolUseContext, name: &str) -> OpenBitFunResult bool { let name = path.rsplit(['/', '\\']).next().unwrap_or(""); - let Some((digest, _)) = name.split_once('.') else { - return false; - }; - digest.len() == 64 - && digest.bytes().all(|b| b.is_ascii_hexdigit()) + if session_image_name(path).is_some() { + return context.session_id.is_some() && context.workspace.is_some(); + } + snapshot_filename(name) && image_reference(context, name).is_ok_and(|reference| reference == path) } /// Save the exact frame, including observations that never had a source file. pub(crate) async fn save_image(bytes: &[u8], context: &ToolUseContext) -> OpenBitFunResult { + let session = context + .session_id + .as_deref() + .filter(|_| context.workspace.is_some()); + let root = if let Some(session_id) = session { + openbitfun_core_types::validate_session_id(session_id) + .map_err(OpenBitFunError::validation)?; + context.current_workspace_session_dir(session_id)? + } else { + image_runtime_root(context)? + }; let (reference, _) = save_in_root( bytes, - &image_runtime_root(context)?, + &root, context.current_workspace_scope().as_deref(), context.should_emit_runtime_uri(), + session.is_some(), ) .await?; Ok(reference) @@ -98,7 +154,15 @@ pub(crate) async fn prepare_input_attachments( continue; } let bytes = super::image_processing::read_image_in_context(path, context).await?; - image.image_path = Some(save_image(&bytes, context).await?); + let (reference, _) = save_in_root( + &bytes, + &image_runtime_root(context)?, + context.current_workspace_scope().as_deref(), + context.should_emit_runtime_uri(), + false, + ) + .await?; + image.image_path = Some(reference); } prepare_inline_image_attachments(images, context).await } @@ -135,8 +199,14 @@ async fn prepare_in_runtime_root( continue; }; let (bytes, _) = decode_data_url(data_url)?; - let (path, mime_type) = - save_in_root(&bytes, runtime_root, workspace_scope, emit_runtime_uri).await?; + let (path, mime_type) = save_in_root( + &bytes, + runtime_root, + workspace_scope, + emit_runtime_uri, + false, + ) + .await?; image.image_path = Some(path); image.mime_type = mime_type.to_string(); } @@ -148,6 +218,7 @@ async fn save_in_root( runtime_root: &Path, workspace_scope: Option<&str>, emit_runtime_uri: bool, + session_scoped: bool, ) -> OpenBitFunResult<(String, &'static str)> { let format = image::guess_format(bytes).map_err(|error| { OpenBitFunError::validation(format!("Invalid image attachment: {error}")) @@ -164,20 +235,24 @@ async fn save_in_root( ))) } }; - let relative_path = format!("attachments/images/{:x}.{extension}", Sha256::digest(bytes)); + let relative_path = format!("{IMAGE_DIRECTORY}/{:x}.{extension}", Sha256::digest(bytes)); let path = runtime_root.join(&relative_path); // A replay or queued dispatch can prepare the same pixels twice. The // content address lets it reuse a complete, unchanged artifact. if tokio::fs::read(&path).await.ok().as_deref() != Some(bytes) { persist_attachment(&path, bytes.to_vec()).await?; } - let reference = build_tool_runtime_artifact_reference( - &relative_path, - Some(runtime_root), - workspace_scope, - emit_runtime_uri, - ) - .map_err(|error| OpenBitFunError::validation(error.to_string()))?; + let reference = if session_scoped { + session_image_reference(&relative_path)? + } else { + build_tool_runtime_artifact_reference( + &relative_path, + Some(runtime_root), + workspace_scope, + emit_runtime_uri, + ) + .map_err(|error| OpenBitFunError::validation(error.to_string()))? + }; Ok((reference, mime_type)) } diff --git a/src/crates/assembly/core/src/agentic/persistence/manager.rs b/src/crates/assembly/core/src/agentic/persistence/manager.rs index 65a5435318..244a79cec2 100644 --- a/src/crates/assembly/core/src/agentic/persistence/manager.rs +++ b/src/crates/assembly/core/src/agentic/persistence/manager.rs @@ -849,7 +849,7 @@ impl PersistenceManager { self.session_layout(workspace_path).index_path() } - fn session_layout(&self, workspace_path: &Path) -> SessionStorageLayout { + pub(super) fn session_layout(&self, workspace_path: &Path) -> SessionStorageLayout { SessionStorageLayout::new(self.project_sessions_dir(workspace_path)) } diff --git a/src/crates/assembly/core/src/agentic/persistence/session_branch.rs b/src/crates/assembly/core/src/agentic/persistence/session_branch.rs index 9e0cb8a066..09292bdebd 100644 --- a/src/crates/assembly/core/src/agentic/persistence/session_branch.rs +++ b/src/crates/assembly/core/src/agentic/persistence/session_branch.rs @@ -168,6 +168,10 @@ impl PersistenceManager { self.save_session(workspace_path, &target_session).await?; let branch_result = async { + use crate::agentic::image_analysis::attachments::copy_session_image_reference; + let layout = self.session_layout(workspace_path); + let source_dir = layout.session_dir(&request.source_session_id); + let target_dir = layout.session_dir(&target_session_id); let branched_turns = source_turns .iter() .take(copied_turn_count) @@ -207,7 +211,15 @@ impl PersistenceManager { }; if let Some(mut messages) = context_snapshot { for message in &mut messages { + for reference in &message.metadata.tool_image_references { + copy_session_image_reference(reference, &source_dir, &target_dir) + .await?; + } if let MessageContent::ToolResult { result, .. } = &mut message.content { + if let Some(reference) = result["source_image_reference"].as_str() { + copy_session_image_reference(reference, &source_dir, &target_dir) + .await?; + } clear_inherited_snapshot_capability(result); } } @@ -245,6 +257,16 @@ impl PersistenceManager { } for turn in &branched_turns { + for result in turn + .model_rounds + .iter() + .flat_map(|round| &round.tool_items) + .filter_map(|tool| tool.tool_result.as_ref()) + { + if let Some(reference) = result.result["source_image_reference"].as_str() { + copy_session_image_reference(reference, &source_dir, &target_dir).await?; + } + } self.save_dialog_turn(workspace_path, turn).await?; } @@ -674,12 +696,38 @@ mod tests { .expect("omitted transcript should create") .expect("omitted transcript should exist"); + let runtime = workspace + .path_manager() + .project_runtime_root(workspace.path()); + let binding = + crate::agentic::workspace::WorkspaceBinding::new(None, workspace.path().into()); + let mut image_context = + crate::agentic::tools::ToolUseContext::for_tool_listing(Some(binding), None); + image_context.custom_data.insert( + "__openbitfun_test_runtime_root".into(), + serde_json::json!(runtime), + ); + image_context.session_id = Some(source_session.session_id.clone()); + let image = crate::agentic::image_analysis::attachments::test_image(); + let (image_bytes, _) = + crate::agentic::image_analysis::decode_data_url(image.data_url.as_deref().unwrap()) + .unwrap(); + let reference = + crate::agentic::image_analysis::attachments::save_image(&image_bytes, &image_context) + .await + .unwrap(); + let source_image = image_context + .resolve_tool_path(&reference) + .unwrap() + .resolved_path; + let mut context_message = Message::user("snapshot-0".to_string()); + context_message.metadata.tool_image_references = vec![reference.clone()]; manager .save_turn_context_snapshot( workspace.path(), &source_session.session_id, 0, - &[Message::user("snapshot-0".to_string())], + &[context_message], ) .await .expect("snapshot 0 should save"); @@ -818,6 +866,10 @@ mod tests { &branched_snapshot[0].content, crate::agentic::core::MessageContent::Text(text) if text == "snapshot-0" )); + assert_eq!( + branched_snapshot[0].metadata.tool_image_references, + [reference.as_str()] + ); let branched_prompt_cache = manager .load_prompt_cache(workspace.path(), &result.session_id) @@ -854,6 +906,17 @@ mod tests { "baseTitle": "Source Title" }) ); + manager + .delete_session(workspace.path(), &source_session.session_id) + .await + .unwrap(); + assert!(!Path::new(&source_image).exists()); + image_context.session_id = Some(result.session_id); + let target_image = image_context + .resolve_tool_path(&reference) + .unwrap() + .resolved_path; + assert_eq!(tokio::fs::read(target_image).await.unwrap(), image_bytes); } #[tokio::test] diff --git a/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs b/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs index f712e45187..5f19552fd6 100644 --- a/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs +++ b/src/crates/assembly/core/src/agentic/session/session_manager/tests/deletion.rs @@ -317,3 +317,94 @@ async fn cold_session_deletion_reclaims_persisted_file_snapshots() { .exists()); } } + +#[cfg(feature = "tools-image-analysis")] +#[tokio::test] +async fn delete_session_removes_its_persisted_tool_image_snapshot() { + use crate::agentic::image_analysis::attachments; + use crate::agentic::tools::{implementations::ViewImageTool, Tool, ToolResult, ToolUseContext}; + use crate::agentic::workspace::WorkspaceBinding; + + let workspace = TestWorkspace::new(); + let paths = workspace.path_manager(); + let runtime = paths.project_runtime_root(workspace.path()); + let persistence = Arc::new(PersistenceManager::new(paths).unwrap()); + let manager = test_manager(persistence.clone()); + let session = manager + .create_session( + "Screenshot session".into(), + "agent".into(), + SessionConfig { + workspace_path: Some(workspace.path().to_string_lossy().into_owned()), + ..Default::default() + }, + ) + .await + .unwrap(); + let binding = WorkspaceBinding::new( + Some(workspace.workspace_id().into()), + workspace.path().into(), + ); + let mut context = ToolUseContext::for_tool_listing(Some(binding), None); + context.custom_data.insert( + "__openbitfun_test_runtime_root".into(), + serde_json::json!(runtime), + ); + context.primary_model_facts = + tool_runtime::context::PrimaryModelFacts::new("test", "vision", "openai", true); + context.session_id = Some(session.session_id.clone()); + + let original = workspace.path().join("original.png"); + let image = attachments::test_image(); + let (bytes, _) = + crate::agentic::image_analysis::decode_data_url(image.data_url.as_deref().unwrap()) + .unwrap(); + tokio::fs::write(&original, &bytes).await.unwrap(); + let results = ViewImageTool::new() + .call_impl(&serde_json::json!({"path":original}), &context) + .await + .unwrap(); + let ToolResult::Result { + data, + image_attachments, + .. + } = &results[0] + else { + panic!("Expected a tool image"); + }; + let reference = data["source_image_reference"].as_str().unwrap(); + assert!(reference.starts_with("openbitfun://current-session/attachments/images/")); + let snapshot = + std::path::PathBuf::from(context.resolve_tool_path(reference).unwrap().resolved_path); + let mut result = Message::tool_result(crate::agentic::core::ToolResult { + tool_id: "capture".into(), + tool_name: "view_image".into(), + effective_tool_name: None, + result: data.clone(), + result_for_assistant: None, + is_error: false, + duration_ms: None, + image_attachments: image_attachments.clone(), + }); + result.metadata.tool_image_references = + attachments::tool_image_references(image_attachments.as_deref().unwrap(), &context) + .await + .unwrap(); + persistence + .save_turn_context_snapshot(workspace.path(), &session.session_id, 0, &[result]) + .await + .unwrap(); + assert_eq!(tokio::fs::read(&snapshot).await.unwrap(), bytes); + let restored = persistence + .load_turn_context_snapshot(workspace.path(), &session.session_id, 0) + .await + .unwrap() + .unwrap(); + assert_eq!(restored[0].metadata.tool_image_references, [reference]); + manager + .delete_session(workspace.path(), &session.session_id) + .await + .unwrap(); + assert!(!snapshot.exists()); + assert_eq!(tokio::fs::read(original).await.unwrap(), bytes); +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs index e64848d4c0..f04b93187a 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/view_image_tool.rs @@ -658,6 +658,7 @@ mod tests { context .custom_data .insert("__openbitfun_test_runtime_root".into(), json!(root.path())); + context.session_id = Some("screenshot-session".into()); let original = png_bytes(3, 2); let frame = crate::util::types::ToolImageAttachment { mime_type: "image/png".into(), @@ -667,7 +668,17 @@ mod tests { .await .unwrap(); let reference = &references[0]; - assert!(reference.starts_with("openbitfun://runtime/workspace-remote/attachments/images/")); + assert!(reference.starts_with("openbitfun://current-session/attachments/images/")); + assert!(context + .resolve_tool_path(reference) + .unwrap() + .resolved_path + .starts_with( + root.path() + .join("sessions/screenshot-session") + .to_str() + .unwrap() + )); let restored = restore_tool_images(&references, &context).await.unwrap(); assert_eq!(restored[0].data_base64, frame.data_base64); let result = ViewImageTool::new() diff --git a/src/crates/contracts/core-types/src/ai.rs b/src/crates/contracts/core-types/src/ai.rs index bb8bf8a151..c722cc3139 100644 --- a/src/crates/contracts/core-types/src/ai.rs +++ b/src/crates/contracts/core-types/src/ai.rs @@ -663,6 +663,8 @@ pub struct ModelRequestContext { /// First outgoing message in the active turn, after host-only messages and reminders /// have been projected. A boundary at the end denotes a history-only request. pub image_turn_start: Option, + /// Keep the latest user upload when the receiving model cannot reopen it. + pub retain_latest_user_image: bool, /// Non-image input estimate calibrated from a matching text-only provider prefix. /// Zero denotes that no comparable provider usage is available for this request. pub minimum_non_image_input_tokens: usize,