返回 CodeWhale
tools.rs
根目录 / crates / engine / src / vision / tools.rs
1 //! `image_analyze` tool — analyze images using a dedicated vision model.
2
3 use std::path::{Component, Path, PathBuf};
4 use std::time::Duration;
5
6 use async_trait::async_trait;
7 use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
8 use serde_json::{Value, json};
9
10 use crate::client::CodewhaleClient;
11 use crate::llm_client::{LlmError, RetryConfig, sanitize_http_error_body, with_retry};
12 use crate::tools::spec::{
13 ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, required_str,
14 };
15 use codewhale_config::ProviderKind;
16 use codewhale_runtime::config::VisionModelConfig;
17
18 pub struct ImageAnalyzeTool {
19 config: VisionModelConfig,
20 client: anyhow::Result<reqwest::Client>,
21 route_client: Option<CodewhaleClient>,
22 }
23
24 /// Total envelope for one image_analyze call, retry attempts and response
25 /// body consumption included. reqwest's `read_timeout` is *not* a per-read
26 /// idle bound for the request phase: its timer starts at `send()` and is
27 /// never reset until the response headers arrive, so it silently acts as a
28 /// total deadline on the multi-MB upload plus the full non-streaming vision
29 /// generation — precisely the healthy work a 120s cap used to kill. The
30 /// client therefore bounds only the connect handshake, and this envelope
31 /// (the same 30-minute wall clock as engine streaming,
32 /// `DEFAULT_STREAM_MAX_DURATION_SECS`) is the sole total bound; a stalled
33 /// connection errors out through it instead of hanging.
34 const VISION_REQUEST_ENVELOPE: Duration = Duration::from_secs(1800);
35
36 fn vision_request_envelope() -> Duration {
37 if cfg!(any(test, feature = "test-support")) {
38 Duration::from_secs(2)
39 } else {
40 VISION_REQUEST_ENVELOPE
41 }
42 }
43
44 impl ImageAnalyzeTool {
45 #[cfg(any(test, feature = "test-support"))]
46 #[must_use]
47 pub fn new(config: VisionModelConfig) -> Self {
48 Self::new_with_route_client(config, None)
49 }
50
51 #[must_use]
52 pub fn new_with_route_client(
53 config: VisionModelConfig,
54 route_client: Option<CodewhaleClient>,
55 ) -> Self {
56 let client = (|| -> anyhow::Result<reqwest::Client> {
57 let builder = crate::platform_client_builder()
58 // Bound only the connect handshake. A client- or request-level
59 // `read_timeout` would start counting at `send()` and never
60 // reset before the response headers, quietly re-introducing a
61 // total deadline on the upload + long non-streaming generation;
62 // the total bound lives in VISION_REQUEST_ENVELOPE instead.
63 .connect_timeout(Duration::from_secs(10));
64 let builder = match config.model_http_policy.as_ref() {
65 Some(policy) => policy.configure(
66 builder,
67 config
68 .base_url
69 .as_deref()
70 .unwrap_or("https://api.openai.com/v1"),
71 )?,
72 None => builder,
73 };
74 Ok(builder.build()?)
75 })();
76 Self {
77 config,
78 client,
79 route_client,
80 }
81 }
82
83 async fn read_image_file(path: &Path) -> Result<(Vec<u8>, String), ToolError> {
84 let bytes = tokio::fs::read(path)
85 .await
86 .map_err(|e| ToolError::execution_failed(format!("Failed to read image file: {e}")))?;
87
88 let mime_type = Self::detect_mime_type(path)?;
89 Ok((bytes, mime_type))
90 }
91
92 fn resolve_image_path(workspace: &Path, image_path: &str) -> Result<PathBuf, ToolError> {
93 let image_path_buf = Path::new(image_path);
94 let workspace = workspace.canonicalize().map_err(|e| {
95 ToolError::execution_failed(format!("Failed to resolve workspace path: {e}"))
96 })?;
97 // An absolute spelling is admitted on the same terms as a relative
98 // one: it must canonicalize to a location inside the workspace (the
99 // containment check below). Screenshot and attachment receipts hand
100 // the model absolute paths, and refusing those outright sent it
101 // through a failed call to learn the relative form.
102 let candidate = if image_path_buf.is_absolute() {
103 // The same lexical traversal guard the relative branch applies
104 // (minus `Prefix`/`RootDir`, which are inherent to a valid
105 // absolute spelling — a Windows drive or UNC path always
106 // carries a prefix): judged before canonicalize so a
107 // non-existent escaping target gets the containment refusal
108 // too, not a resolve error.
109 if image_path_buf
110 .components()
111 .any(|c| matches!(c, Component::ParentDir))
112 {
113 return Err(ToolError::execution_failed(
114 "image_path must resolve within the workspace and cannot escape it.",
115 ));
116 }
117 image_path_buf.to_path_buf()
118 } else {
119 // `RootDir` cannot appear in a Unix-relative path but can in a
120 // Windows rooted one (`\foo`): keep it refused here so the
121 // containment check below is not the only line of defense.
122 if image_path_buf.components().any(|c| {
123 matches!(
124 c,
125 Component::Prefix(_) | Component::RootDir | Component::ParentDir
126 )
127 }) {
128 return Err(ToolError::execution_failed(
129 "image_path must resolve within the workspace and cannot escape it.",
130 ));
131 }
132 workspace.join(image_path_buf)
133 };
134 let resolved = candidate.canonicalize().map_err(|e| {
135 ToolError::execution_failed(format!("Failed to resolve image file: {e}"))
136 })?;
137 if !resolved.starts_with(&workspace) {
138 return Err(ToolError::execution_failed(
139 "image_path must resolve within the workspace and cannot escape it.",
140 ));
141 }
142 Ok(resolved)
143 }
144
145 /// Header-only dimensions of the same bytes sent to the vision model,
146 /// using the extension-derived MIME type. Run on a blocking worker; omit
147 /// metadata for unparsable containers (including unsupported BMP).
148 /// Animated GIF/WebP yield the first frame's size.
149 fn image_dimensions(bytes: &[u8], mime_type: &str) -> Option<(u32, u32, String)> {
150 let format = mime_type.strip_prefix("image/")?.to_string();
151 let reader = image::ImageReader::with_format(
152 std::io::Cursor::new(bytes),
153 image::ImageFormat::from_mime_type(mime_type)?,
154 );
155 let (width, height) = reader.into_dimensions().ok()?;
156 Some((width, height, format))
157 }
158
159 fn detect_mime_type(path: &Path) -> Result<String, ToolError> {
160 let extension = path
161 .extension()
162 .and_then(|e| e.to_str())
163 .unwrap_or("")
164 .to_lowercase();
165
166 match extension.as_str() {
167 "png" => Ok("image/png".to_string()),
168 "jpg" | "jpeg" => Ok("image/jpeg".to_string()),
169 "gif" => Ok("image/gif".to_string()),
170 "webp" => Ok("image/webp".to_string()),
171 "bmp" => Ok("image/bmp".to_string()),
172 _ => Err(ToolError::execution_failed(format!(
173 "Unsupported image format: {extension}"
174 ))),
175 }
176 }
177
178 fn base_url(&self) -> String {
179 self.config
180 .base_url
181 .clone()
182 .unwrap_or_else(|| "https://api.openai.com/v1".to_string())
183 }
184
185 fn api_key(&self) -> String {
186 self.config.api_key.clone().unwrap_or_default()
187 }
188
189 fn is_xiaomi_mimo_model(model: &str) -> bool {
190 let normalized = model.trim().to_ascii_lowercase();
191 let normalized = normalized.strip_prefix("xiaomi/").unwrap_or(&normalized);
192 normalized.starts_with("mimo-")
193 }
194
195 fn uses_max_completion_tokens(config: &VisionModelConfig) -> bool {
196 if Self::is_xiaomi_mimo_model(&config.model) {
197 return true;
198 }
199
200 let base_url = config.base_url.as_deref().unwrap_or_default();
201 let Ok(url) = reqwest::Url::parse(base_url) else {
202 return false;
203 };
204 let Some(domain) = url.domain() else {
205 return false;
206 };
207
208 domain.eq_ignore_ascii_case("xiaomimimo.com")
209 || domain.to_ascii_lowercase().ends_with(".xiaomimimo.com")
210 }
211
212 fn wire_model(&self) -> String {
213 let model = self.config.model.trim();
214 if !Self::is_xiaomi_mimo_model(model) || model.contains('/') {
215 return self.config.model.clone();
216 }
217 codewhale_config::route::resolve_model(
218 codewhale_config::ProviderKind::XiaomiMimo,
219 model,
220 None,
221 )
222 .map_or_else(|_| self.config.model.clone(), |resolved| resolved.wire_id)
223 }
224
225 fn request_payload(&self, prompt: &str, image_data: &str, mime_type: &str) -> Value {
226 let mut payload = json!({
227 "model": self.wire_model(),
228 "messages": [
229 {
230 "role": "user",
231 "content": [
232 {"type": "text", "text": prompt},
233 {
234 "type": "image_url",
235 "image_url": {
236 "url": format!("data:{};base64,{}", mime_type, image_data)
237 }
238 }
239 ]
240 }
241 ]
242 });
243
244 let token_limit_field = if Self::uses_max_completion_tokens(&self.config) {
245 "max_completion_tokens"
246 } else {
247 "max_tokens"
248 };
249 let configured_base = self.base_url();
250 let route_cap = self
251 .route_client
252 .as_ref()
253 .filter(|client| {
254 client.base_url().trim_end_matches('/') == configured_base.trim_end_matches('/')
255 })
256 .map_or_else(
257 || {
258 // A standalone `[vision_model]` route has no resolved
259 // max-model-len fact. Do not guess one or let a process
260 // override turn a capability maximum into an unbounded
261 // request; a matched active client above carries exact
262 // route limits when the vision route is shared.
263 crate::route_budget::effective_max_output_tokens_for_route(
264 ProviderKind::Custom,
265 &self.config.model,
266 None,
267 )
268 .min(65_536)
269 },
270 |client| client.effective_max_output_tokens(&self.config.model),
271 );
272 payload[token_limit_field] = json!(route_cap);
273 if let Some(client) = self.route_client.as_ref().filter(|client| {
274 client.base_url().trim_end_matches('/') == configured_base.trim_end_matches('/')
275 }) {
276 client.apply_provider_routing(&mut payload);
277 }
278
279 payload
280 }
281 }
282
283 #[async_trait]
284 impl ToolSpec for ImageAnalyzeTool {
285 fn name(&self) -> &str {
286 "image_analyze"
287 }
288
289 fn description(&self) -> &str {
290 "Analyze an image using the configured vision model. \
291 Supports PNG, JPEG, GIF, WebP, and BMP formats. \
292 When the runtime can determine them from the image container, the \
293 result includes the image's stored pixel width and height, plus a \
294 format label derived from the file extension — describe image size \
295 from that metadata instead of guessing by eye. The dimensions are \
296 as stored: camera rotation metadata is not applied, and the fields \
297 are omitted when the container cannot be sized."
298 }
299
300 fn input_schema(&self) -> Value {
301 json!({
302 "type": "object",
303 "properties": {
304 "image_path": {
305 "type": "string",
306 "description": "Path to the image file to analyze"
307 },
308 "prompt": {
309 "type": "string",
310 "description": "Optional prompt to guide the analysis."
311 }
312 },
313 "required": ["image_path"]
314 })
315 }
316
317 fn capabilities(&self) -> Vec<ToolCapability> {
318 vec![ToolCapability::ReadOnly]
319 }
320
321 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
322 let client = self.client.as_ref().map_err(|error| {
323 ToolError::execution_failed(format!("Vision HTTP transport unavailable: {error:#}"))
324 })?;
325 let image_path = required_str(&input, "image_path")?;
326 let prompt = input
327 .get("prompt")
328 .and_then(|v| v.as_str())
329 .unwrap_or("Describe this image in detail.");
330
331 let resolved_path = Self::resolve_image_path(&context.workspace, image_path)?;
332 let (image_bytes, mime_type) = Self::read_image_file(&resolved_path).await?;
333 let dimension_mime_type = mime_type.clone();
334 // Header parsing and encoding stay off the async worker and use one
335 // file snapshot. A failed probe omits metadata without failing vision.
336 let (image_data, dimensions) = tokio::task::spawn_blocking(move || {
337 let dimensions = Self::image_dimensions(&image_bytes, &dimension_mime_type);
338 (BASE64.encode(&image_bytes), dimensions)
339 })
340 .await
341 .map_err(|e| ToolError::execution_failed(format!("Failed to prepare image file: {e}")))?;
342
343 let payload = self.request_payload(prompt, &image_data, &mime_type);
344
345 let url = format!("{}/chat/completions", self.base_url());
346 let api_key = self.api_key();
347
348 let retry_config = RetryConfig {
349 max_retries: 3,
350 initial_delay: 1.0,
351 max_delay: 30.0,
352 enabled: true,
353 ..Default::default()
354 };
355 let _inference = match self.route_client.as_ref() {
356 Some(client) => client.acquire_remote_control_inference_permit().await,
357 None => Some(crate::client::acquire_remote_control_inference_participant().await),
358 };
359
360 let response_json = tokio::time::timeout(vision_request_envelope(), async {
361 let response = with_retry(
362 &retry_config,
363 || {
364 let client = client.clone();
365 let url = url.clone();
366 let api_key = api_key.clone();
367 let payload = payload.clone();
368 async move {
369 let response = client
370 .post(&url)
371 .header("Content-Type", "application/json")
372 .header("Authorization", format!("Bearer {api_key}"))
373 .json(&payload)
374 .send()
375 .await
376 .map_err(|e| LlmError::from_reqwest(&e))?;
377
378 let status = response.status();
379 if !status.is_success() {
380 let error_text = response
381 .text()
382 .await
383 .unwrap_or_else(|_| "Unknown error".to_string());
384 let error_text = sanitize_http_error_body(
385 Some("Vision provider"),
386 status.as_u16(),
387 &error_text,
388 );
389 return Err(LlmError::from_http_response(status.as_u16(), &error_text));
390 }
391 Ok(response)
392 }
393 },
394 None,
395 )
396 .await
397 .map_err(|e| ToolError::execution_failed(format!("Vision API request failed: {e}")))?;
398
399 let json: Value = response.json().await.map_err(|e| {
400 ToolError::execution_failed(format!("Failed to parse response: {e}"))
401 })?;
402 Ok::<Value, ToolError>(json)
403 })
404 .await
405 .map_err(|_| ToolError::Timeout {
406 seconds: vision_request_envelope().as_secs(),
407 })??;
408
409 let content = response_json
410 .get("choices")
411 .and_then(|c| c.get(0))
412 .and_then(|c| c.get("message"))
413 .and_then(|m| m.get("content"))
414 .and_then(|c| c.as_str())
415 .unwrap_or("")
416 .to_string();
417
418 let model = response_json
419 .get("model")
420 .and_then(|m| m.as_str())
421 .unwrap_or(&self.config.model)
422 .to_string();
423
424 let mut result = json!({
425 "analysis": content,
426 "model": model,
427 });
428 if let Some((width, height, format)) = dimensions {
429 result["width"] = json!(width);
430 result["height"] = json!(height);
431 result["format"] = json!(format);
432 }
433
434 ToolResult::json(&result)
435 .map_err(|e| ToolError::execution_failed(format!("Failed to serialize result: {e}")))
436 }
437 }
438
439 #[cfg(test)]
440 mod tests {
441 use super::*;
442 use tempfile::tempdir;
443 use wiremock::matchers::{method, path};
444 use wiremock::{Mock, MockServer, ResponseTemplate};
445
446 #[cfg(unix)]
447 fn create_file_symlink(
448 target: &std::path::Path,
449 link: &std::path::Path,
450 ) -> std::io::Result<()> {
451 std::os::unix::fs::symlink(target, link)
452 }
453
454 #[cfg(windows)]
455 fn create_file_symlink(
456 target: &std::path::Path,
457 link: &std::path::Path,
458 ) -> std::io::Result<()> {
459 std::os::windows::fs::symlink_file(target, link)
460 }
461
462 fn fake_config() -> VisionModelConfig {
463 VisionModelConfig {
464 model_http_policy: None,
465 model: "test-vision-model".to_string(),
466 api_key: Some("test-key".to_string()),
467 base_url: Some("https://example.invalid/v1".to_string()),
468 }
469 }
470
471 /// The cap reads the `*_MAX_OUTPUT_TOKENS` override from the process
472 /// environment, as the payload does. Tests that compare the two hold the
473 /// test env lock, so an engine test setting the override cannot land
474 /// between the two reads in a shared process.
475 fn standalone_vision_cap(model: &str) -> u64 {
476 u64::from(
477 crate::route_budget::effective_max_output_tokens_for_route(
478 ProviderKind::Custom,
479 model,
480 None,
481 )
482 .min(65_536),
483 )
484 }
485
486 #[test]
487 fn tool_metadata_is_read_only_and_named_image_analyze() {
488 let tool = ImageAnalyzeTool::new(fake_config());
489 assert_eq!(tool.name(), "image_analyze");
490 assert!(tool.capabilities().contains(&ToolCapability::ReadOnly));
491 }
492
493 /// Screenshot and attachment receipts hand the model absolute paths,
494 /// while the refusal demanded a relative spelling — so the first
495 /// `image_analyze` call with the absolute form of an in-workspace file
496 /// failed and the model paid one wasted call to learn the relative
497 /// form. An absolute spelling that resolves inside the workspace is
498 /// the same file as its relative form and is admitted on the same
499 /// containment terms.
500 #[test]
501 fn resolve_image_path_accepts_absolute_paths_inside_the_workspace() {
502 let tmp = tempdir().expect("tempdir");
503 let attachments = tmp.path().join("attachments").join("computer_use");
504 std::fs::create_dir_all(&attachments).expect("attachments dir");
505 let image = attachments.join("shot.png");
506 std::fs::write(&image, b"not a real png").expect("fixture");
507 let canonical_workspace = tmp.path().canonicalize().expect("canonical workspace");
508
509 let via_absolute =
510 ImageAnalyzeTool::resolve_image_path(tmp.path(), &image.to_string_lossy())
511 .expect("absolute in-workspace path resolves");
512 let via_relative =
513 ImageAnalyzeTool::resolve_image_path(tmp.path(), "attachments/computer_use/shot.png")
514 .expect("relative path resolves");
515 assert_eq!(via_absolute, via_relative);
516 assert!(via_absolute.starts_with(&canonical_workspace));
517
518 // A real file outside the workspace, reached by `..` traversal.
519 let outside = tempdir().expect("outside tempdir");
520 let outside_image = outside.path().join("outside.png");
521 std::fs::write(&outside_image, b"not a real png").expect("fixture");
522 let traversed = tmp
523 .path()
524 .join("..")
525 .join(outside.path().file_name().expect("named tempdir"))
526 .join("outside.png");
527 let err = ImageAnalyzeTool::resolve_image_path(tmp.path(), &traversed.to_string_lossy())
528 .expect_err("absolute traversal out of the workspace is refused");
529 assert!(err.to_string().contains("within the workspace"), "{err}");
530
531 // A traversal whose target does NOT exist must get the same
532 // containment refusal (judged lexically before canonicalize), not
533 // a resolve error — the boundary message is what tells the model
534 // how to fix the spelling.
535 let missing = tmp.path().join("..").join("no-such-dir").join("x.png");
536 let err = ImageAnalyzeTool::resolve_image_path(tmp.path(), &missing.to_string_lossy())
537 .expect_err("absolute traversal to a missing file is refused");
538 assert!(
539 err.to_string().contains("within the workspace"),
540 "the containment message fires even when canonicalize would fail: {err}"
541 );
542 }
543
544 /// Windows absolute spellings of the same in-workspace file: a
545 /// drive-absolute path and the canonical verbatim (`\\?\`) form both
546 /// necessarily carry a `Prefix` component, so the lexical guard must
547 /// not treat the prefix as an escape attempt — containment stays with
548 /// the canonicalized check, including the outside-workspace negative.
549 /// (Runs natively on Windows only; the non-gated test above exercises
550 /// the same admission with whatever absolute shape the platform
551 /// produces.)
552 #[cfg(windows)]
553 #[test]
554 fn resolve_image_path_accepts_windows_absolute_spellings_inside_the_workspace() {
555 let tmp = tempdir().expect("tempdir");
556 let attachments = tmp.path().join("attachments").join("computer_use");
557 std::fs::create_dir_all(&attachments).expect("attachments dir");
558 let image = attachments.join("shot.png");
559 std::fs::write(&image, b"not a real png").expect("fixture");
560 let canonical_workspace = tmp.path().canonicalize().expect("canonical workspace");
561
562 // Drive-absolute (`C:\…`), the shape screenshot receipts hand over.
563 let via_drive = ImageAnalyzeTool::resolve_image_path(tmp.path(), &image.to_string_lossy())
564 .expect("drive-absolute in-workspace path resolves");
565 assert!(via_drive.starts_with(&canonical_workspace));
566
567 // Canonical verbatim (`\\?\C:\…`), the shape `canonicalize` itself
568 // returns.
569 let verbatim = canonical_workspace
570 .join("attachments")
571 .join("computer_use")
572 .join("shot.png");
573 let via_verbatim =
574 ImageAnalyzeTool::resolve_image_path(tmp.path(), &verbatim.to_string_lossy())
575 .expect("verbatim in-workspace path resolves");
576 assert_eq!(via_verbatim, via_drive);
577
578 // The outside-workspace negative survives the prefix admission: a
579 // real file outside the workspace still gets the containment
580 // refusal, not a lexical one. The fixture is a second tempdir —
581 // outside the workspace by construction — so the negative hits the
582 // containment check deterministically instead of depending on a
583 // system file existing for `canonicalize` to reach.
584 let outside_dir = tempdir().expect("outside tempdir");
585 let outside_image = outside_dir.path().join("outside.png");
586 std::fs::write(&outside_image, b"not a real png").expect("outside fixture");
587 let outside =
588 ImageAnalyzeTool::resolve_image_path(tmp.path(), &outside_image.to_string_lossy())
589 .expect_err("absolute path outside the workspace must reject");
590 assert!(
591 outside.to_string().contains("within the workspace"),
592 "{outside}"
593 );
594 }
595
596 #[test]
597 fn mime_type_detection_covers_common_formats() {
598 for (ext, expected) in [
599 ("png", "image/png"),
600 ("PNG", "image/png"),
601 ("jpg", "image/jpeg"),
602 ("jpeg", "image/jpeg"),
603 ("gif", "image/gif"),
604 ("webp", "image/webp"),
605 ("bmp", "image/bmp"),
606 ] {
607 let path = std::path::PathBuf::from(format!("test.{ext}"));
608 let mime = ImageAnalyzeTool::detect_mime_type(&path)
609 .unwrap_or_else(|_| panic!("must detect {ext}"));
610 assert_eq!(mime, expected);
611 }
612 }
613
614 #[test]
615 fn mime_type_detection_rejects_unsupported_extension() {
616 let path = std::path::PathBuf::from("test.svg");
617 let err = ImageAnalyzeTool::detect_mime_type(&path)
618 .expect_err("svg is intentionally out of scope for vision tool");
619 assert!(err.to_string().contains("Unsupported image format"));
620 }
621
622 #[test]
623 fn generic_vision_payload_uses_max_tokens() {
624 let _env = crate::test_support::lock_test_env();
625 let tool = ImageAnalyzeTool::new(fake_config());
626
627 let payload = tool.request_payload("describe", "abc123", "image/png");
628
629 assert_eq!(
630 payload.get("max_tokens").and_then(Value::as_u64),
631 Some(standalone_vision_cap(&tool.config.model))
632 );
633 assert!(payload.get("temperature").is_none());
634 assert!(payload.get("max_completion_tokens").is_none());
635 }
636
637 #[test]
638 fn xiaomi_mimo_vision_payload_uses_max_completion_tokens() {
639 let _env = crate::test_support::lock_test_env();
640 let mut config = fake_config();
641 config.model = "mimo-v2.5".to_string();
642 config.base_url = Some("https://api.xiaomimimo.com/v1".to_string());
643 let tool = ImageAnalyzeTool::new(config);
644
645 let payload = tool.request_payload("describe", "abc123", "image/png");
646
647 assert_eq!(
648 payload.get("max_completion_tokens").and_then(Value::as_u64),
649 Some(standalone_vision_cap(&tool.config.model))
650 );
651 assert!(payload.get("temperature").is_none());
652 assert!(payload.get("max_tokens").is_none());
653 }
654
655 #[test]
656 fn xiaomi_mimo_vision_payload_uses_max_completion_tokens_with_custom_proxy() {
657 let _env = crate::test_support::lock_test_env();
658 let mut config = fake_config();
659 config.model = "mimo-v2.5".to_string();
660 config.base_url = Some("https://vision-proxy.example.invalid/v1".to_string());
661 let tool = ImageAnalyzeTool::new(config);
662
663 let payload = tool.request_payload("describe", "abc123", "image/png");
664
665 assert_eq!(
666 payload.get("max_completion_tokens").and_then(Value::as_u64),
667 Some(standalone_vision_cap(&tool.config.model))
668 );
669 assert!(payload.get("max_tokens").is_none());
670 }
671
672 #[test]
673 fn vision_vendor_pin_requires_the_matching_bound_route() {
674 let _lock = crate::test_support::lock_test_env();
675 let base_url = "http://127.0.0.1:18080/v1";
676 let client = CodewhaleClient::new(&{
677 let __cw_config_init_0_0 = Some("openrouter".to_string());
678 let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig {
679 openrouter: codewhale_runtime::config::ProviderConfig {
680 api_key: Some("fixture-openrouter-key".to_string()),
681 base_url: Some(base_url.to_string()),
682 model: Some("fixture/vision".to_string()),
683 vendor: Some("chutes/region-fixture".to_string()),
684 ..Default::default()
685 },
686 ..Default::default()
687 });
688 let mut __cw_config_init_0_value: codewhale_runtime::config::Config =
689 Default::default();
690 __cw_config_init_0_value.provider = __cw_config_init_0_0;
691 __cw_config_init_0_value.providers = __cw_config_init_0_1;
692 __cw_config_init_0_value
693 })
694 .unwrap();
695 for (vision_base, matched_client, pinned) in [
696 (base_url, Some(client.clone()), true),
697 ("http://127.0.0.1:18081/v1", Some(client.clone()), false),
698 (base_url, None, false),
699 ] {
700 let tool = ImageAnalyzeTool::new_with_route_client(
701 VisionModelConfig {
702 model_http_policy: None,
703 model: "fixture/vision".to_string(),
704 api_key: Some("fixture-vision-key".to_string()),
705 base_url: Some(vision_base.to_string()),
706 },
707 matched_client,
708 );
709 let body = tool.request_payload("describe", "abc123", "image/png");
710 if pinned {
711 assert_eq!(
712 body["provider"],
713 json!({
714 "order": ["chutes/region-fixture"], "allow_fallbacks": false
715 })
716 );
717 } else {
718 assert!(body.get("provider").is_none());
719 }
720 }
721 }
722
723 #[test]
724 fn matched_vision_route_uses_bound_client_window_cap() {
725 let _lock = crate::test_support::lock_test_env();
726 let _canonical =
727 crate::test_support::EnvVarGuard::set("CODEWHALE_MAX_OUTPUT_TOKENS", "384000");
728 let base_url = "http://127.0.0.1:18080/v1".to_string();
729 let model = "DeepSeek-V4-Flash".to_string();
730 let client = CodewhaleClient::new(&{
731 let __cw_config_init_1_0 = Some("vllm".to_string());
732 let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig {
733 vllm: codewhale_runtime::config::ProviderConfig {
734 base_url: Some(base_url.clone()),
735 model: Some(model.clone()),
736 context_window: Some(327_680),
737 ..codewhale_runtime::config::ProviderConfig::default()
738 },
739 ..codewhale_runtime::config::ProvidersConfig::default()
740 });
741 let mut __cw_config_init_1_value: codewhale_runtime::config::Config =
742 codewhale_runtime::config::Config::default();
743 __cw_config_init_1_value.provider = __cw_config_init_1_0;
744 __cw_config_init_1_value.providers = __cw_config_init_1_1;
745 __cw_config_init_1_value
746 })
747 .expect("bound vLLM client");
748 let tool = ImageAnalyzeTool::new_with_route_client(
749 VisionModelConfig {
750 model_http_policy: None,
751 model,
752 api_key: None,
753 base_url: Some(base_url),
754 },
755 Some(client),
756 );
757
758 let payload = tool.request_payload("describe", "abc123", "image/png");
759 assert_eq!(payload["max_tokens"], 325_632);
760 }
761
762 #[tokio::test]
763 async fn execute_rejects_absolute_path() {
764 // Trust-boundary pin: image_path must stay inside the workspace —
765 // an absolute path outside it must be rejected (as must a
766 // `..`-traversing path), while an absolute path resolving inside
767 // the workspace is admitted through the same canonical containment
768 // as the relative spelling of the same file.
769 let tmp = tempdir().expect("tempdir");
770 let ctx = ToolContext::new(tmp.path().to_path_buf());
771 let tool = ImageAnalyzeTool::new(fake_config());
772 let outside_workspace = if cfg!(windows) {
773 r"C:\Windows\System32\drivers\etc\hosts"
774 } else {
775 "/etc/hosts"
776 };
777 let err = tool
778 .execute(json!({"image_path": outside_workspace}), &ctx)
779 .await
780 .expect_err("absolute path outside the workspace must reject");
781 assert!(
782 err.to_string().contains("within the workspace"),
783 "error must call out the workspace boundary; got {err}"
784 );
785 }
786
787 #[tokio::test]
788 async fn execute_rejects_parent_dir_traversal() {
789 let tmp = tempdir().expect("tempdir");
790 let ctx = ToolContext::new(tmp.path().to_path_buf());
791 let tool = ImageAnalyzeTool::new(fake_config());
792 let err = tool
793 .execute(json!({"image_path": "../escape.png"}), &ctx)
794 .await
795 .expect_err("`..`-traversal must reject");
796 assert!(
797 err.to_string().contains("within the workspace"),
798 "error must call out the workspace boundary; got {err}"
799 );
800 }
801
802 #[tokio::test]
803 async fn execute_rejects_symlink_that_resolves_outside_workspace() {
804 let workspace = tempdir().expect("workspace tempdir");
805 let outside = tempdir().expect("outside tempdir");
806 let outside_image = outside.path().join("outside.png");
807 std::fs::write(&outside_image, b"not a real png").expect("write outside image");
808 let link = workspace.path().join("linked.png");
809 if let Err(err) = create_file_symlink(&outside_image, &link) {
810 eprintln!("skipping symlink assertion: {err}");
811 return;
812 }
813
814 let ctx = ToolContext::new(workspace.path().to_path_buf());
815 let tool = ImageAnalyzeTool::new(fake_config());
816 let err = tool
817 .execute(json!({"image_path": "linked.png"}), &ctx)
818 .await
819 .expect_err("symlink target outside workspace must reject before reading");
820 assert!(
821 err.to_string().contains("resolve within the workspace"),
822 "error must call out the canonical workspace boundary; got {err}"
823 );
824 }
825
826 fn vision_response_body() -> Value {
827 json!({
828 "model": "test-vision-model",
829 "choices": [
830 { "message": { "content": "a red square" } }
831 ]
832 })
833 }
834
835 fn tool_with_base_url(base_url: String) -> ImageAnalyzeTool {
836 ImageAnalyzeTool::new(VisionModelConfig {
837 model_http_policy: None,
838 model: "test-vision-model".to_string(),
839 api_key: Some("test-key".to_string()),
840 base_url: Some(base_url),
841 })
842 }
843
844 fn write_workspace_image(workspace: &std::path::Path) {
845 std::fs::write(workspace.join("sample.png"), b"not a real png")
846 .expect("write sample image");
847 }
848
849 #[tokio::test]
850 async fn envelope_bounds_a_stalled_vision_provider() {
851 let server = MockServer::start().await;
852 // The stalled provider never answers within the test envelope: the
853 // upload + non-streaming generation window must be cut off by the
854 // envelope, not by a client read timeout (which reqwest turns into
855 // a hidden total deadline from `send()`).
856 Mock::given(method("POST"))
857 .and(path("/chat/completions"))
858 .respond_with(
859 ResponseTemplate::new(200)
860 .set_body_json(vision_response_body())
861 .set_delay(Duration::from_secs(30)),
862 )
863 .mount(&server)
864 .await;
865
866 let workspace = tempdir().expect("workspace tempdir");
867 write_workspace_image(workspace.path());
868 let ctx = ToolContext::new(workspace.path().to_path_buf());
869 let tool = tool_with_base_url(server.uri());
870
871 let err = tool
872 .execute(json!({"image_path": "sample.png"}), &ctx)
873 .await
874 .expect_err("a provider that never answers must hit the envelope");
875 assert!(
876 err.to_string().contains("timed out after"),
877 "envelope timeout must be reported as such; got {err}"
878 );
879 }
880
881 #[tokio::test]
882 async fn prompt_answer_within_the_envelope_is_returned() {
883 let server = MockServer::start().await;
884 Mock::given(method("POST"))
885 .and(path("/chat/completions"))
886 .respond_with(ResponseTemplate::new(200).set_body_json(vision_response_body()))
887 .mount(&server)
888 .await;
889
890 let workspace = tempdir().expect("workspace tempdir");
891 write_workspace_image(workspace.path());
892 let ctx = ToolContext::new(workspace.path().to_path_buf());
893 let tool = tool_with_base_url(server.uri());
894
895 let result = tool
896 .execute(
897 json!({"image_path": "sample.png", "prompt": "what is this?"}),
898 &ctx,
899 )
900 .await
901 .expect("a prompt answer must flow through the envelope");
902 let payload: Value =
903 serde_json::from_str(&result.content).expect("tool result must carry json");
904 assert_eq!(payload["analysis"], "a red square");
905 }
906
907 fn create_test_png(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> {
908 let img = image::RgbaImage::from_pixel(width, height, image::Rgba(color));
909 let mut cursor = std::io::Cursor::new(Vec::new());
910 img.write_to(&mut cursor, image::ImageFormat::Png)
911 .expect("fixture png encodes");
912 cursor.into_inner()
913 }
914
915 fn create_test_jpeg(width: u32, height: u32) -> Vec<u8> {
916 let img = image::RgbImage::from_pixel(width, height, image::Rgb([120, 200, 50]));
917 let mut cursor = std::io::Cursor::new(Vec::new());
918 img.write_to(&mut cursor, image::ImageFormat::Jpeg)
919 .expect("fixture jpeg encodes");
920 cursor.into_inner()
921 }
922
923 /// Stand-in vision endpoint answering `/chat/completions` the way the
924 /// tool expects, so `execute` can be exercised end to end offline.
925 async fn mock_vision_endpoint() -> MockServer {
926 let server = MockServer::start().await;
927 Mock::given(method("POST"))
928 .and(path("/chat/completions"))
929 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
930 "model": "test-vision-model",
931 "choices": [{"message": {"content": "a tiny square"}}]
932 })))
933 .mount(&server)
934 .await;
935 server
936 }
937
938 #[tokio::test]
939 async fn execute_reports_real_pixel_dimensions_and_format() {
940 let server = mock_vision_endpoint().await;
941 let workspace = tempdir().expect("workspace tempdir");
942 std::fs::write(
943 workspace.path().join("tiny.png"),
944 create_test_png(64, 48, [12, 34, 56, 255]),
945 )
946 .expect("write fixture");
947 std::fs::write(workspace.path().join("tiny.jpg"), create_test_jpeg(30, 20))
948 .expect("write fixture");
949
950 let ctx = ToolContext::new(workspace.path().to_path_buf());
951 let tool = tool_with_base_url(server.uri());
952
953 let cases: [(&str, u32, u32, &str); 2] =
954 [("tiny.png", 64, 48, "png"), ("tiny.jpg", 30, 20, "jpeg")];
955 for (name, width, height, format) in cases {
956 let result = tool
957 .execute(json!({"image_path": name}), &ctx)
958 .await
959 .expect("tool must succeed");
960 assert!(result.success);
961 let payload: Value = serde_json::from_str(&result.content).expect("json tool content");
962 assert_eq!(
963 payload.get("width").and_then(Value::as_u64),
964 Some(u64::from(width)),
965 "{name} must report real pixel width"
966 );
967 assert_eq!(
968 payload.get("height").and_then(Value::as_u64),
969 Some(u64::from(height)),
970 "{name} must report real pixel height"
971 );
972 assert_eq!(
973 payload.get("format").and_then(Value::as_str),
974 Some(format),
975 "{name} format must match the mime-derived label"
976 );
977 let requests = server.received_requests().await.expect("recorded requests");
978 let request: Value = requests
979 .last()
980 .expect("vision request")
981 .body_json()
982 .unwrap();
983 let image_url = request["messages"][0]["content"][1]["image_url"]["url"]
984 .as_str()
985 .expect("uploaded image URL");
986 let uploaded = BASE64
987 .decode(
988 image_url
989 .strip_prefix(&format!("data:image/{format};base64,"))
990 .expect("uploaded image MIME type matches metadata"),
991 )
992 .expect("uploaded image base64");
993 assert_eq!(
994 ImageAnalyzeTool::image_dimensions(&uploaded, &format!("image/{format}")),
995 Some((width, height, format.to_string())),
996 "{name} metadata must describe the actual uploaded bytes"
997 );
998 }
999 }
1000
1001 #[tokio::test]
1002 async fn execute_omits_dimension_metadata_for_unparsable_bytes() {
1003 let server = mock_vision_endpoint().await;
1004 let workspace = tempdir().expect("workspace tempdir");
1005 std::fs::write(
1006 workspace.path().join("broken.png"),
1007 b"definitely not a png header",
1008 )
1009 .expect("write fixture");
1010
1011 let ctx = ToolContext::new(workspace.path().to_path_buf());
1012 let tool = tool_with_base_url(server.uri());
1013
1014 let result = tool
1015 .execute(json!({"image_path": "broken.png"}), &ctx)
1016 .await
1017 .expect("metadata failure must not fail the tool");
1018 assert!(result.success);
1019 let payload: Value = serde_json::from_str(&result.content).expect("json tool content");
1020 assert!(payload.get("width").is_none(), "width must be omitted");
1021 assert!(payload.get("height").is_none(), "height must be omitted");
1022 assert!(payload.get("format").is_none(), "format must be omitted");
1023 assert_eq!(
1024 payload.get("analysis").and_then(Value::as_str),
1025 Some("a tiny square")
1026 );
1027 }
1028
1029 #[test]
1030 fn image_dimensions_respects_the_available_bmp_decoder() {
1031 // Workspace feature unification can enable BMP on some platforms.
1032 // Report its dimensions when supported; otherwise omit metadata.
1033 const MINIMAL_BMP: &[u8] = &[
1034 b'B', b'M', //
1035 0x3a, 0x00, 0x00,
1036 0x00, // file size: 14-byte header + 40-byte DIB + 4-byte padded row
1037 0x00, 0x00, 0x00, 0x00, // reserved
1038 0x36, 0x00, 0x00, 0x00, // pixel data offset: 54
1039 0x28, 0x00, 0x00, 0x00, // DIB header size: 40
1040 0x01, 0x00, 0x00, 0x00, // width: 1
1041 0x01, 0x00, 0x00, 0x00, // height: 1
1042 0x01, 0x00, // planes
1043 0x18, 0x00, // bits per pixel: 24
1044 0x00, 0x00, 0x00, 0x00, // compression: none
1045 0x04, 0x00, 0x00, 0x00, // image size: one padded row
1046 0x00, 0x00, 0x00, 0x00, // x pixels per meter
1047 0x00, 0x00, 0x00, 0x00, // y pixels per meter
1048 0x00, 0x00, 0x00, 0x00, // colors used
1049 0x00, 0x00, 0x00, 0x00, // important colors
1050 0x00, 0x00, 0x00, 0x00, // single BGR pixel plus 1 pad byte
1051 ];
1052 let decoder = image::ImageReader::with_format(
1053 std::io::Cursor::new(MINIMAL_BMP),
1054 image::ImageFormat::Bmp,
1055 )
1056 .into_decoder();
1057 match decoder {
1058 Ok(decoder) => {
1059 assert_eq!(image::ImageDecoder::dimensions(&decoder), (1, 1));
1060 assert_eq!(
1061 ImageAnalyzeTool::image_dimensions(MINIMAL_BMP, "image/bmp"),
1062 Some((1, 1, "bmp".to_string()))
1063 );
1064 }
1065 Err(image::ImageError::Unsupported(error)) => {
1066 assert!(matches!(
1067 error.kind(),
1068 image::error::UnsupportedErrorKind::Format(
1069 image::error::ImageFormatHint::Exact(image::ImageFormat::Bmp)
1070 )
1071 ));
1072 assert_eq!(
1073 ImageAnalyzeTool::image_dimensions(MINIMAL_BMP, "image/bmp"),
1074 None
1075 );
1076 }
1077 Err(error) => panic!("invalid BMP fixture: {error}"),
1078 }
1079 }
1080 }
1081
1081 lines RUST