返回 CodeWhale
image_ocr.rs
根目录 / crates / engine / src / tools / image_ocr.rs
1 //! `image_ocr` tool — extract text from an image via local OCR.
2 //!
3 //! Tesseract is the cross-platform workhorse for "convert this image
4 //! to text". On macOS we also use the built-in Vision framework, so
5 //! screenshots keep working on a clean machine without making the
6 //! user install a separate OCR binary first.
7 //!
8 //! Surfacing OCR as a model-callable tool means the model can read an
9 //! asset the user drops into the workspace without bouncing through
10 //! `exec_shell`.
11
12 use std::ffi::OsString;
13 use std::path::{Path, PathBuf};
14 use std::time::Duration;
15 use tokio_util::sync::CancellationToken;
16
17 use async_trait::async_trait;
18 use serde_json::{Value, json};
19
20 use super::spec::{ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, required_str};
21
22 /// Tool implementing `image_ocr`. Runs a local OCR backend and returns the
23 /// extracted text on success.
24 pub struct ImageOcrTool;
25
26 #[async_trait]
27 impl ToolSpec for ImageOcrTool {
28 fn name(&self) -> &'static str {
29 "image_ocr"
30 }
31
32 fn description(&self) -> &'static str {
33 "Extract text from an image (PNG, JPEG, or TIFF) via local OCR. On macOS this uses the built-in Vision framework; otherwise it uses local tesseract when available. To look at an image, `read` it instead: a vision-capable model receives the image itself. Use OCR when the active model is text-only, or when you need the exact text of a scanned receipt/whiteboard or an image-only PDF. Returns the extracted text inline; no file is written."
34 }
35
36 fn input_schema(&self) -> Value {
37 json!({
38 "type": "object",
39 "properties": {
40 "path": {
41 "type": "string",
42 "description": "Path to the image file (relative to workspace or absolute). PNG / JPEG / TIFF supported."
43 }
44 },
45 "required": ["path"]
46 })
47 }
48
49 fn capabilities(&self) -> Vec<ToolCapability> {
50 vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable]
51 }
52
53 fn supports_parallel(&self) -> bool {
54 true
55 }
56
57 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
58 let path_str = required_str(&input, "path")?;
59 let plan =
60 crate::tools::file::resolve_read_open_plan(context, path_str, "image_ocr", true, true)
61 .await?;
62 let deadline = context
63 .turn_deadline
64 .unwrap_or_else(|| tokio::time::Instant::now() + OCR_TIMEOUT);
65 let captured = CapturedOcr::capture_from_plan(plan, context, deadline).await?;
66 let text = ocr_captured(captured, context, deadline).await?;
67 Ok(ToolResult::success(text))
68 }
69 }
70
71 fn local_ocr_disabled() -> bool {
72 let read = || std::env::var_os("CODEWHALE_LOCAL_OCR_UNAVAILABLE").is_some();
73 #[cfg(any(test, feature = "test-support"))]
74 {
75 crate::test_support::with_test_env_lock(read)
76 }
77 #[cfg(not(any(test, feature = "test-support")))]
78 {
79 read()
80 }
81 }
82
83 pub fn ocr_available() -> bool {
84 (!local_ocr_disabled()
85 && (codewhale_dependencies::resolve_tesseract().is_some() || native_ocr_available()))
86 || crate::deepseek_media::resolve_deepseek_ocr_auth().is_some()
87 }
88
89 const OCR_TIMEOUT: Duration = Duration::from_secs(120);
90 const MAX_OCR_TEXT: usize = 16 * 1024 * 1024;
91 const MAX_OCR_DIAGNOSTIC: usize = 32 * 1024;
92 const MIN_IMAGE_BYTES: usize = 12;
93 const NOT_AN_IMAGE: &str = "image_ocr: the file is not a PNG, JPEG, TIFF, BMP, GIF or WebP image";
94 const NO_BACKEND: &str = "image_ocr: no local OCR backend is available. On macOS, update to a version with the Vision framework; on Linux/Windows install tesseract and restart codewhale.";
95
96 /// Private bounded image snapshot staged before Host startup. Paths, image bytes,
97 /// full text and process diagnostics stay in Core. Native probing/resolution
98 /// happens only in the captured Core worker.
99 pub struct CapturedOcr {
100 path: PathBuf,
101 source_name: Option<String>,
102 captured_sha256: String,
103 _staged: Option<StagedInput>,
104 #[cfg(all(test, unix))]
105 overrides: Option<TestOverrides>,
106 }
107
108 struct StagedInput {
109 _root: tempfile::TempDir,
110 work_dir: PathBuf,
111 }
112
113 fn is_ocr_image(bytes: &[u8]) -> bool {
114 bytes.len() >= MIN_IMAGE_BYTES
115 && (crate::image_attach::sniff_media_type(bytes).is_some()
116 || matches!(
117 crate::image_attach::detect_rejected_format(bytes),
118 Some("BMP" | "TIFF")
119 ))
120 }
121
122 enum CaptureSource {
123 Plan(crate::tools::file::ReadOpenPlan),
124 Bytes {
125 bytes: Vec<u8>,
126 source_name: Option<String>,
127 },
128 }
129
130 impl CapturedOcr {
131 async fn capture(
132 path: &Path,
133 context: &ToolContext,
134 deadline: tokio::time::Instant,
135 ) -> Result<Self, ToolError> {
136 if !path.is_absolute() {
137 return Err(ToolError::execution_failed(
138 "Image OCR capture requires an authorized absolute path",
139 ));
140 }
141 if tokio::fs::symlink_metadata(path)
142 .await
143 .is_ok_and(|meta| codewhale_util::path_identity::metadata_is_link_or_reparse(&meta))
144 {
145 return Err(ToolError::permission_denied(format!(
146 "image_ocr refused symlink for {}",
147 path.display()
148 )));
149 }
150 let raw = path
151 .to_str()
152 .ok_or_else(|| ToolError::execution_failed("image_ocr: path is not valid UTF-8"))?;
153 let plan =
154 crate::tools::file::resolve_read_open_plan(context, raw, "image_ocr", true, true)
155 .await?;
156 Self::capture_from_plan(plan, context, deadline).await
157 }
158
159 async fn capture_from_plan(
160 plan: crate::tools::file::ReadOpenPlan,
161 context: &ToolContext,
162 deadline: tokio::time::Instant,
163 ) -> Result<Self, ToolError> {
164 Self::capture_staged(CaptureSource::Plan(plan), context, deadline).await
165 }
166
167 async fn capture_bytes(
168 bytes: Vec<u8>,
169 source_name: Option<String>,
170 context: &ToolContext,
171 deadline: tokio::time::Instant,
172 ) -> Result<Self, ToolError> {
173 Self::capture_staged(
174 CaptureSource::Bytes { bytes, source_name },
175 context,
176 deadline,
177 )
178 .await
179 }
180
181 async fn capture_staged(
182 source: CaptureSource,
183 context: &ToolContext,
184 deadline: tokio::time::Instant,
185 ) -> Result<Self, ToolError> {
186 let cancel = context.cancel_token.clone();
187 #[cfg(all(test, unix))]
188 let overrides = TEST_OVERRIDES.with(|slot| slot.borrow().clone());
189 let worker = tokio::task::spawn_blocking(move || {
190 if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) {
191 return Err(ToolError::cancelled("Image OCR was cancelled"));
192 }
193 let (bytes, source_name) = match source {
194 CaptureSource::Plan(plan) => {
195 let Some((mut file, fd_path)) =
196 crate::tools::file::open_verified_read_handle(&plan, true, true, false)?
197 else {
198 return Err(ToolError::execution_failed(format!(
199 "image_ocr: source path does not exist: {}",
200 plan.file_path.display()
201 )));
202 };
203 let bytes =
204 crate::tools::file::read_contract_source(&mut file, cancel.as_ref())?;
205 let source_name = fd_path
206 .file_name()
207 .or_else(|| plan.file_path.file_name())
208 .and_then(|name| name.to_str())
209 .map(str::to_string);
210 (bytes, source_name)
211 }
212 CaptureSource::Bytes { bytes, source_name } => (bytes, source_name),
213 };
214 if !is_ocr_image(&bytes) {
215 return Err(ToolError::invalid_input(NOT_AN_IMAGE));
216 }
217 let captured_sha256 = codewhale_runtime::hashing::sha256_hex(&bytes);
218 let stage_error = |error: std::io::Error| {
219 ToolError::execution_failed(format!("Failed to stage image OCR input: {error}"))
220 };
221 let root = tempfile::Builder::new()
222 .prefix("codewhale-ocr-")
223 .tempdir()
224 .map_err(stage_error)?;
225 let work_dir = root.path().join("work");
226 std::fs::create_dir(&work_dir).map_err(stage_error)?;
227 let staged_path = root.path().join("input");
228 std::fs::write(&staged_path, &bytes).map_err(stage_error)?;
229 let staged = StagedInput {
230 _root: root,
231 work_dir,
232 };
233 if cancel.as_ref().is_some_and(CancellationToken::is_cancelled) {
234 return Err(ToolError::cancelled("Image OCR was cancelled"));
235 }
236 Ok(Self {
237 path: staged_path,
238 source_name,
239 captured_sha256,
240 _staged: Some(staged),
241 #[cfg(all(test, unix))]
242 overrides,
243 })
244 });
245 tokio::select! {biased;
246 ()=wait_cancel(context.cancel_token.as_ref())=>Err(ToolError::cancelled("Image OCR was cancelled")),
247 ()=tokio::time::sleep_until(deadline)=>Err(ToolError::Timeout {seconds:OCR_TIMEOUT.as_secs()}),
248 result=worker=>result.map_err(|error|ToolError::execution_failed(format!("Image OCR capture task: {error}")))?,
249 }
250 }
251 #[cfg(all(test, unix))]
252 pub fn for_test(path: &Path, native: TestNativeOcr, tesseract: Option<OsString>) -> Self {
253 Self {
254 path: path.to_path_buf(),
255 source_name: path
256 .file_name()
257 .and_then(|name| name.to_str())
258 .map(str::to_string),
259 captured_sha256: codewhale_runtime::hashing::sha256_hex(
260 path.as_os_str().as_encoded_bytes(),
261 ),
262 _staged: None, // private broker test port; production always stages bytes
263 overrides: Some(TestOverrides { native, tesseract }),
264 }
265 }
266 pub fn digest(&self) -> String {
267 self.captured_sha256.clone()
268 }
269 pub fn native_step(self) -> OcrNativeStep {
270 #[cfg(all(test, unix))]
271 let result = self
272 .overrides
273 .as_ref()
274 .map(|value| (value.native)(&self.path));
275 #[cfg(all(test, unix))]
276 let mut result = result.unwrap_or_else(|| try_native_ocr(&self.path));
277 #[cfg(not(all(test, unix)))]
278 let mut result = try_native_ocr(&self.path);
279 if result
280 .as_ref()
281 .is_ok_and(|text| text.as_ref().is_some_and(|text| text.len() > MAX_OCR_TEXT))
282 {
283 result = Err(ToolError::execution_failed(
284 "native OCR output exceeded the 16777216 byte safety limit",
285 ));
286 }
287 // Preserve the legacy native-first resolver order. A working native
288 // backend does not gain a new Tesseract probe or process launch.
289 let fallback = if matches!(result, Ok(Some(_))) {
290 None
291 } else {
292 let resolve = || {
293 (!local_ocr_disabled())
294 .then(codewhale_dependencies::resolve_tesseract)
295 .flatten()
296 .map(OsString::from)
297 };
298 #[cfg(all(test, unix))]
299 let supplied = self.overrides.as_ref().map(|value| value.tesseract.clone());
300 #[cfg(all(test, unix))]
301 {
302 supplied.unwrap_or_else(resolve)
303 }
304 #[cfg(not(all(test, unix)))]
305 {
306 resolve()
307 }
308 };
309 OcrNativeStep {
310 input: self,
311 fallback,
312 outcome: OcrOutcome::Native(result),
313 }
314 }
315 }
316
317 pub struct OcrNativeStep {
318 input: CapturedOcr,
319 fallback: Option<OsString>,
320 outcome: OcrOutcome,
321 }
322 impl OcrNativeStep {
323 pub fn needs_tesseract(&self) -> bool {
324 self.fallback.is_some()
325 }
326 pub fn digest(&self) -> String {
327 let mut value = self.input.captured_sha256.as_bytes().to_vec();
328 value.push(0);
329 if let Some(binary) = &self.fallback {
330 value.extend_from_slice(binary.as_encoded_bytes());
331 }
332 codewhale_runtime::hashing::sha256_hex(&value)
333 }
334 pub fn projection(&self) -> Value {
335 let status = match &self.outcome {
336 OcrOutcome::Native(Ok(Some(_))) => "success",
337 OcrOutcome::Native(Ok(None)) => "unavailable",
338 _ => "error",
339 };
340 json!({"kind":"ocr_process","state":"native","status":status,"can_fallback":self.needs_tesseract()})
341 }
342 pub fn finish(self) -> OcrOutcome {
343 self.outcome
344 }
345 pub(crate) fn finish_with_input(self) -> (CapturedOcr, OcrOutcome) {
346 (self.input, self.outcome)
347 }
348 pub async fn tesseract(
349 self,
350 cancel: Option<&CancellationToken>,
351 deadline: tokio::time::Instant,
352 ) -> OcrOutcome {
353 let result=async {
354 if cancel.is_some_and(CancellationToken::is_cancelled) {return Err(ToolError::cancelled("Image OCR was cancelled"));}
355 if tokio::time::Instant::now()>=deadline {return Err(ToolError::Timeout {seconds:OCR_TIMEOUT.as_secs()});}
356 let binary=self.fallback.as_ref().ok_or_else(||ToolError::execution_failed("OCR fallback was not admitted"))?;
357 let mut command=tokio::process::Command::new(binary);
358 codewhale_util::utils::suppress_tokio_console_window(&mut command);
359 command.arg(&self.input.path).arg("-");
360 if let Some(staged) = &self.input._staged {
361 command.current_dir(&staged.work_dir);
362 }
363 codewhale_runtime::child_env::apply_to_tokio_command(&mut command,std::iter::empty::<(&str,&str)>());
364 let stop=async { tokio::select! {biased;()=wait_cancel(cancel)=>{},()=tokio::time::sleep_until(deadline)=>{},} };
365 let run=codewhale_runtime::process_tree::contained_output_with_input_bounded(&mut command,Vec::new(),MAX_OCR_TEXT,MAX_OCR_DIAGNOSTIC,stop).await
366 .map_err(|error|ToolError::execution_failed(format!("failed to launch tesseract: {error}")))?;
367 if cancel.is_some_and(CancellationToken::is_cancelled) {return Err(ToolError::cancelled("Image OCR was cancelled"));}
368 if run.stopped || tokio::time::Instant::now()>=deadline {return Err(ToolError::Timeout {seconds:OCR_TIMEOUT.as_secs()});}
369 Ok(run.output)
370 }.await;
371 OcrOutcome::Tesseract(result)
372 }
373 }
374
375 /// Full OCR text/process output is retained privately, never copied to Host.
376 pub enum OcrOutcome {
377 Native(Result<Option<String>, ToolError>),
378 Tesseract(Result<std::process::Output, ToolError>),
379 }
380 impl OcrOutcome {
381 pub fn projection(&self) -> Value {
382 match self {
383 Self::Native(_) => unreachable!("native projection is stage-bound"),
384 Self::Tesseract(Err(_)) => {
385 json!({"kind":"ocr_process","state":"tesseract","status":"fault"})
386 }
387 Self::Tesseract(Ok(output)) => {
388 json!({"kind":"ocr_process","state":"tesseract","status":"complete","success":output.status.success(),"exit_code":output.status.code()})
389 }
390 }
391 }
392 fn into_rust_text(self) -> Result<String, ToolError> {
393 match self {
394 Self::Native(Ok(Some(text))) => Ok(text),
395 Self::Native(Ok(None)) => Err(ToolError::execution_failed(NO_BACKEND)),
396 Self::Native(Err(error)) | Self::Tesseract(Err(error)) => Err(error),
397 Self::Tesseract(Ok(output)) if output.status.success() => {
398 Ok(String::from_utf8_lossy(&output.stdout)
399 .trim_end()
400 .to_string())
401 }
402 Self::Tesseract(Ok(output)) => Err(ToolError::execution_failed(format!(
403 "tesseract failed (exit {:?}): {}",
404 output.status.code(),
405 String::from_utf8_lossy(&output.stderr).trim()
406 ))),
407 }
408 }
409 fn into_host_text(self, result: ToolResult) -> Result<String, ToolError> {
410 #[derive(serde::Deserialize)]
411 #[serde(deny_unknown_fields)]
412 struct Decision {
413 kind: String,
414 code: String,
415 trim_end: bool,
416 message: Option<String>,
417 }
418 let invalid = || {
419 ToolError::execution_failed(
420 "OCR Host returned a malformed or inconsistent decision; no Rust fallback was attempted",
421 )
422 };
423 if !result.success {
424 return Err(invalid());
425 }
426 let decision: Decision =
427 serde_json::from_value(result.metadata.ok_or_else(invalid)?).map_err(|_| invalid())?;
428 if decision.kind != "ocr_decision" {
429 return Err(invalid());
430 }
431 match self {
432 Self::Native(Ok(Some(text)))
433 if decision.code == "native_success"
434 && !decision.trim_end
435 && decision.message.is_none() =>
436 {
437 Ok(text)
438 }
439 Self::Native(Ok(None))
440 if decision.code == "no_backend"
441 && !decision.trim_end
442 && decision.message.as_deref() == Some(NO_BACKEND) =>
443 {
444 Err(ToolError::execution_failed(NO_BACKEND))
445 }
446 Self::Native(Err(error))
447 if decision.code == "native_error"
448 && !decision.trim_end
449 && decision.message.is_none() =>
450 {
451 Err(error)
452 }
453 Self::Tesseract(Err(error))
454 if decision.code == "fault" && !decision.trim_end && decision.message.is_none() =>
455 {
456 Err(error)
457 }
458 Self::Tesseract(Ok(output))
459 if output.status.success()
460 && decision.code == "tesseract_success"
461 && decision.trim_end
462 && decision.message.is_none() =>
463 {
464 Ok(String::from_utf8_lossy(&output.stdout)
465 .trim_end()
466 .to_string())
467 }
468 Self::Tesseract(Ok(output))
469 if !output.status.success()
470 && decision.code == "execution"
471 && !decision.trim_end =>
472 {
473 let prefix = format!("tesseract failed (exit {:?}): ", output.status.code());
474 if decision.message.as_deref() != Some(prefix.as_str()) {
475 return Err(invalid());
476 }
477 Err(ToolError::execution_failed(format!(
478 "{prefix}{}",
479 String::from_utf8_lossy(&output.stderr).trim()
480 )))
481 }
482 _ => Err(invalid()),
483 }
484 }
485 }
486
487 pub async fn ocr_image_path(image_path: &Path, context: &ToolContext) -> Result<String, ToolError> {
488 let deadline = context
489 .turn_deadline
490 .unwrap_or_else(|| tokio::time::Instant::now() + OCR_TIMEOUT);
491 let input = CapturedOcr::capture(image_path, context, deadline).await?;
492 ocr_captured(input, context, deadline).await
493 }
494
495 pub(super) async fn ocr_image_bytes(
496 bytes: Vec<u8>,
497 source_name: Option<String>,
498 context: &ToolContext,
499 ) -> Result<String, ToolError> {
500 let deadline = context
501 .turn_deadline
502 .unwrap_or_else(|| tokio::time::Instant::now() + OCR_TIMEOUT);
503 let input = CapturedOcr::capture_bytes(bytes, source_name, context, deadline).await?;
504 ocr_captured(input, context, deadline).await
505 }
506
507 async fn ocr_captured(
508 input: CapturedOcr,
509 context: &ToolContext,
510 deadline: tokio::time::Instant,
511 ) -> Result<String, ToolError> {
512 if context
513 .features
514 .enabled(codewhale_runtime::features::Feature::OcrHost)
515 {
516 let mut captured_context = context.clone();
517 captured_context.turn_deadline = Some(deadline);
518 let (outcome, decision) = crate::extension_host::manager()
519 .execute_ocr(input, &captured_context)
520 .await?;
521 return outcome.into_host_text(decision);
522 }
523 // Native Vision remains on the existing blocking pool. Cancellation cannot
524 // preempt framework FFI; an abandoned worker keeps its own captured input.
525 #[cfg(any(test, feature = "test-support"))]
526 let scope = crate::test_support::env_scope_ticket();
527 let native = tokio::task::spawn_blocking(move || {
528 #[cfg(any(test, feature = "test-support"))]
529 let _scope = crate::test_support::join_env_scope(scope);
530 input.native_step()
531 });
532 let step = tokio::select! {biased;
533 ()=wait_cancel(context.cancel_token.as_ref())=>return Err(ToolError::cancelled("Image OCR was cancelled")),
534 ()=tokio::time::sleep_until(deadline)=>return Err(ToolError::Timeout {seconds:OCR_TIMEOUT.as_secs()}),
535 result=native=>result.map_err(|error|ToolError::execution_failed(format!("Image OCR task: {error}")))?,
536 };
537 if step.needs_tesseract() {
538 let output = step
539 .tesseract(context.cancel_token.as_ref(), deadline)
540 .await;
541 if context
542 .cancel_token
543 .as_ref()
544 .is_some_and(CancellationToken::is_cancelled)
545 {
546 return Err(ToolError::cancelled("Image OCR was cancelled"));
547 }
548 return output.into_rust_text();
549 }
550 let (captured, output) = step.finish_with_input();
551 if context
552 .cancel_token
553 .as_ref()
554 .is_some_and(CancellationToken::is_cancelled)
555 {
556 return Err(ToolError::cancelled("Image OCR was cancelled"));
557 }
558 if matches!(output, OcrOutcome::Native(Ok(None)))
559 && let Some((base_url, api_key)) = crate::deepseek_media::resolve_deepseek_ocr_auth()
560 {
561 return run_deepseek_ocr(
562 &captured.path,
563 captured.source_name.as_deref(),
564 &base_url,
565 &api_key,
566 context,
567 deadline,
568 )
569 .await;
570 }
571 output.into_rust_text()
572 }
573
574 fn check_ocr_network_policy(context: &ToolContext, base_url: &str) -> Result<(), ToolError> {
575 let Some(decider) = context.network_policy.as_ref() else {
576 return Ok(());
577 };
578 let Some(host) = codewhale_net::network_policy::host_from_url(base_url) else {
579 return Err(ToolError::invalid_input(format!(
580 "invalid DeepSeek OCR base URL '{base_url}'"
581 )));
582 };
583 match decider.evaluate(&host, "image_ocr") {
584 codewhale_net::network_policy::Decision::Allow => Ok(()),
585 codewhale_net::network_policy::Decision::Deny => Err(ToolError::permission_denied(
586 format!("image_ocr network call to '{host}' blocked by network policy"),
587 )),
588 codewhale_net::network_policy::Decision::Prompt => {
589 Err(ToolError::permission_denied(format!(
590 "image_ocr network call to '{host}' requires approval; re-run after `/network allow {host}` or set network.default = \"allow\" in config"
591 )))
592 }
593 }
594 }
595
596 async fn run_deepseek_ocr(
597 path: &Path,
598 source_name: Option<&str>,
599 base_url: &str,
600 api_key: &str,
601 context: &ToolContext,
602 deadline: tokio::time::Instant,
603 ) -> Result<String, ToolError> {
604 check_ocr_network_policy(context, base_url)?;
605 if context
606 .cancel_token
607 .as_ref()
608 .is_some_and(CancellationToken::is_cancelled)
609 {
610 return Err(ToolError::cancelled("Image OCR was cancelled"));
611 }
612 if tokio::time::Instant::now() >= deadline {
613 return Err(ToolError::Timeout {
614 seconds: OCR_TIMEOUT.as_secs(),
615 });
616 }
617 let bytes = tokio::fs::read(path).await.map_err(|err| {
618 ToolError::execution_failed(format!("failed to read image for OCR: {err}"))
619 })?;
620 if bytes.len() > crate::deepseek_media::DEEPSEEK_OCR_MAX_BYTES {
621 return Err(ToolError::invalid_input(format!(
622 "image exceeds DeepSeek OCR limit of {} bytes",
623 crate::deepseek_media::DEEPSEEK_OCR_MAX_BYTES
624 )));
625 }
626 let mime_path = source_name.map(Path::new).unwrap_or(path);
627 let mime = crate::deepseek_media::ocr_mime_for_path(mime_path, &bytes)
628 .map_err(ToolError::invalid_input)?;
629 let file_name = source_name
630 .filter(|value| !value.trim().is_empty())
631 .or_else(|| path.file_name().and_then(|value| value.to_str()))
632 .unwrap_or("image");
633 let text = tokio::select! {
634 biased;
635 () = wait_cancel(context.cancel_token.as_ref()) => {
636 return Err(ToolError::cancelled("Image OCR was cancelled"));
637 }
638 () = tokio::time::sleep_until(deadline) => {
639 return Err(ToolError::Timeout {
640 seconds: OCR_TIMEOUT.as_secs(),
641 });
642 }
643 result = crate::deepseek_media::ocr_deepseek_bytes(
644 base_url,
645 api_key,
646 &bytes,
647 file_name,
648 mime,
649 ) => {
650 result.map_err(ToolError::execution_failed)?
651 }
652 };
653 if text.len() > MAX_OCR_TEXT {
654 return Err(ToolError::execution_failed(
655 "DeepSeek OCR output exceeded size limit",
656 ));
657 }
658 Ok(text)
659 }
660 async fn wait_cancel(cancel: Option<&CancellationToken>) {
661 match cancel {
662 Some(cancel) => cancel.cancelled().await,
663 None => std::future::pending::<()>().await,
664 }
665 }
666
667 #[cfg(all(test, unix))]
668 type TestNativeOcr =
669 std::sync::Arc<dyn Fn(&Path) -> Result<Option<String>, ToolError> + Send + Sync>;
670
671 #[cfg(all(test, unix))]
672 #[derive(Clone)]
673 struct TestOverrides {
674 native: TestNativeOcr,
675 tesseract: Option<OsString>,
676 }
677 #[cfg(all(test, unix))]
678 thread_local! {static TEST_OVERRIDES:std::cell::RefCell<Option<TestOverrides>>=const {std::cell::RefCell::new(None)};}
679
680 #[cfg(target_os = "macos")]
681 fn native_ocr_available() -> bool {
682 // Classes can exist at link time while runtime Vision is unusable
683 // (restricted CI hosts); probe the ObjC class table once to match real use.
684 !local_ocr_disabled() && macos_vision::vision_runtime_available()
685 }
686
687 #[cfg(not(target_os = "macos"))]
688 fn native_ocr_available() -> bool {
689 false
690 }
691
692 #[cfg(not(target_os = "macos"))]
693 fn try_native_ocr(_image_path: &Path) -> Result<Option<String>, ToolError> {
694 Ok(None)
695 }
696
697 #[cfg(target_os = "macos")]
698 #[link(name = "Vision", kind = "framework")]
699 unsafe extern "C" {}
700
701 #[cfg(target_os = "macos")]
702 fn try_native_ocr(image_path: &Path) -> Result<Option<String>, ToolError> {
703 if !native_ocr_available() {
704 return Ok(None);
705 }
706 macos_vision::recognize_text(image_path).map(Some)
707 }
708
709 #[cfg(target_os = "macos")]
710 mod macos_vision {
711 use super::*;
712 use objc2::msg_send;
713 use objc2::rc::{Retained, autoreleasepool};
714 use objc2::runtime::{AnyClass, AnyObject};
715 use objc2_foundation::{NSArray, NSDictionary, NSError, NSString, NSURL};
716 use std::ptr;
717
718 pub(super) fn recognize_text(image_path: &Path) -> Result<String, ToolError> {
719 autoreleasepool(|_| recognize_text_inner(image_path))
720 }
721
722 /// True when the Vision text-recognition classes resolve at runtime.
723 /// Does not attempt a full OCR round-trip (that needs an image and can
724 /// fail for image-specific reasons); class resolution is the cheap probe
725 /// used by `ocr_available` / tool registration.
726 pub(super) fn vision_runtime_available() -> bool {
727 use std::sync::OnceLock;
728 static AVAILABLE: OnceLock<bool> = OnceLock::new();
729 *AVAILABLE.get_or_init(|| {
730 AnyClass::get(c"VNRecognizeTextRequest").is_some()
731 && AnyClass::get(c"VNImageRequestHandler").is_some()
732 })
733 }
734
735 fn recognize_text_inner(image_path: &Path) -> Result<String, ToolError> {
736 let url = NSURL::from_file_path(image_path).ok_or_else(|| {
737 ToolError::execution_failed(format!(
738 "image_ocr: failed to build file URL for {}",
739 image_path.display()
740 ))
741 })?;
742
743 let request_class = AnyClass::get(c"VNRecognizeTextRequest").ok_or_else(|| {
744 ToolError::execution_failed("image_ocr: macOS Vision text request is unavailable")
745 })?;
746 let handler_class = AnyClass::get(c"VNImageRequestHandler").ok_or_else(|| {
747 ToolError::execution_failed("image_ocr: macOS Vision image handler is unavailable")
748 })?;
749
750 let request = new_object(request_class, "VNRecognizeTextRequest")?;
751 // VNRequestTextRecognitionLevelAccurate is 0. Use accurate mode for
752 // screenshots and receipts; the tool is user-facing, not latency-critical.
753 // SAFETY: selectors and signatures match VNRecognizeTextRequest.
754 unsafe {
755 let _: () = msg_send![&*request, setRecognitionLevel: 0usize];
756 let _: () = msg_send![&*request, setUsesLanguageCorrection: true];
757 }
758
759 let requests = NSArray::from_slice(&[&*request]);
760 let options: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::new();
761
762 let handler_alloc = alloc_object(handler_class, "VNImageRequestHandler")?;
763 // SAFETY: selector and signature match VNImageRequestHandler; consumes the alloc.
764 let handler_raw: *mut AnyObject =
765 unsafe { msg_send![handler_alloc, initWithURL: &*url, options: &*options] };
766 // SAFETY: init returns +1; from_raw is null-checked.
767 let handler = unsafe { Retained::from_raw(handler_raw) }.ok_or_else(|| {
768 ToolError::execution_failed("image_ocr: failed to initialize Vision image handler")
769 })?;
770
771 let mut error: *mut NSError = ptr::null_mut();
772 // SAFETY: selector and signature match VNImageRequestHandler.
773 let ok: bool =
774 unsafe { msg_send![&*handler, performRequests: &*requests, error: &mut error] };
775 if !ok {
776 return Err(ToolError::execution_failed(format!(
777 "image_ocr: macOS Vision failed{}",
778 vision_error_suffix(error)
779 )));
780 }
781
782 collect_recognized_text(&request)
783 }
784
785 fn new_object(class: &AnyClass, label: &str) -> Result<Retained<AnyObject>, ToolError> {
786 // SAFETY: +1 or null; null handled by from_raw below.
787 let raw: *mut AnyObject = unsafe { msg_send![class, new] };
788 // SAFETY: takes the +1 from `new`; null maps to Err.
789 unsafe { Retained::from_raw(raw) }.ok_or_else(|| {
790 ToolError::execution_failed(format!("image_ocr: failed to create {label}"))
791 })
792 }
793
794 fn alloc_object(class: &AnyClass, label: &str) -> Result<*mut AnyObject, ToolError> {
795 // SAFETY: +1 or null; null checked below.
796 let raw: *mut AnyObject = unsafe { msg_send![class, alloc] };
797 if raw.is_null() {
798 Err(ToolError::execution_failed(format!(
799 "image_ocr: failed to allocate {label}"
800 )))
801 } else {
802 Ok(raw)
803 }
804 }
805
806 fn collect_recognized_text(request: &AnyObject) -> Result<String, ToolError> {
807 // SAFETY: autoreleased return; used synchronously, never stored.
808 let results: *mut AnyObject = unsafe { msg_send![request, results] };
809 if results.is_null() {
810 return Ok(String::new());
811 }
812
813 // SAFETY: selector and signature match NSArray.
814 let count: usize = unsafe { msg_send![results, count] };
815 let mut lines = Vec::new();
816 for idx in 0..count {
817 // SAFETY: idx < count.
818 let observation: *mut AnyObject = unsafe { msg_send![results, objectAtIndex: idx] };
819 if observation.is_null() {
820 continue;
821 }
822 // SAFETY: selector and signature match VNRecognizedTextObservation.
823 let candidates: *mut AnyObject =
824 unsafe { msg_send![observation, topCandidates: 1usize] };
825 if candidates.is_null() {
826 continue;
827 }
828 // SAFETY: selector and signature match NSArray.
829 let candidate_count: usize = unsafe { msg_send![candidates, count] };
830 if candidate_count == 0 {
831 continue;
832 }
833 // SAFETY: count > 0 checked above.
834 let candidate: *mut AnyObject = unsafe { msg_send![candidates, objectAtIndex: 0usize] };
835 if candidate.is_null() {
836 continue;
837 }
838 // SAFETY: selector and signature match VNRecognizedText.
839 let text: *mut NSString = unsafe { msg_send![candidate, string] };
840 if text.is_null() {
841 continue;
842 }
843 // SAFETY: `text` is non-null; used synchronously.
844 let line = unsafe { &*text }.to_string();
845 let trimmed = line.trim();
846 if !trimmed.is_empty() {
847 lines.push(trimmed.to_string());
848 }
849 }
850
851 Ok(lines.join("\n"))
852 }
853
854 fn vision_error_suffix(error: *mut NSError) -> String {
855 if error.is_null() {
856 return String::new();
857 }
858 // SAFETY: selector and signature match NSError.
859 let description: *mut NSString = unsafe { msg_send![error, localizedDescription] };
860 if description.is_null() {
861 String::new()
862 } else {
863 // SAFETY: `description` is non-null; used synchronously.
864 format!(": {}", unsafe { &*description })
865 }
866 }
867 }
868
869 #[cfg(test)]
870 mod tests {
871 use super::*;
872 use std::fs;
873 use tempfile::tempdir;
874
875 /// Resolve the checked-in OCR fixture path. The image lives at
876 /// `crates/engine/tests/fixtures/ocr_hello.png` (300x100 grayscale,
877 /// "HELLO OCR" rendered in Helvetica) and is committed for the
878 /// happy-path round-trip below.
879 fn ocr_fixture_path() -> std::path::PathBuf {
880 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ocr_hello.png")
881 }
882
883 #[test]
884 fn tool_metadata_marks_image_ocr_read_only_and_parallel() {
885 let tool = ImageOcrTool;
886 assert_eq!(tool.name(), "image_ocr");
887 assert!(tool.supports_parallel());
888 let caps = tool.capabilities();
889 assert!(caps.contains(&ToolCapability::ReadOnly));
890 assert!(!caps.contains(&ToolCapability::WritesFiles));
891 }
892
893 #[tokio::test]
894 async fn image_ocr_rejects_missing_path() {
895 let tmp = tempdir().expect("tempdir");
896 let ctx = ToolContext::new(tmp.path().to_path_buf());
897 let err = ImageOcrTool
898 .execute(json!({"path": "definitely-not-here.png"}), &ctx)
899 .await
900 .expect_err("nonexistent path must reject before tesseract spawn");
901 let msg = err.to_string();
902 assert!(
903 msg.contains("does not exist"),
904 "error must call out missing path; got {msg}"
905 );
906 }
907
908 #[tokio::test]
909 async fn image_ocr_refuses_deny_listed_paths() {
910 // `.env` is on the default read deny-list, so no global guard setup
911 // is needed; the refusal precedes any OCR backend.
912 let tmp = tempdir().expect("tempdir");
913 fs::copy(ocr_fixture_path(), tmp.path().join(".env")).unwrap();
914 #[cfg(unix)]
915 std::os::unix::fs::symlink(tmp.path().join(".env"), tmp.path().join("pic.png")).unwrap();
916 let ctx = ToolContext::new(tmp.path().to_path_buf());
917 let mut paths = vec![".env"];
918 if cfg!(unix) {
919 paths.push("pic.png");
920 }
921 for path in paths {
922 let err = ImageOcrTool
923 .execute(json!({ "path": path }), &ctx)
924 .await
925 .expect_err("a deny-listed image must be refused");
926 assert!(
927 matches!(err, ToolError::PermissionDenied { .. }),
928 "{path}: {err:?}"
929 );
930 }
931 }
932
933 #[tokio::test]
934 async fn image_ocr_refuses_files_without_an_image_signature() {
935 let tmp = tempdir().expect("tempdir");
936 let outside = tmp.path().join("elsewhere.png");
937 fs::copy(ocr_fixture_path(), &outside).unwrap();
938 let list = format!("{}\n", outside.display());
939 let mut png_prefix = fs::read(ocr_fixture_path()).unwrap();
940 png_prefix.truncate(11);
941 let cases: Vec<(&str, Vec<u8>)> = vec![
942 ("diagram.png", list.into_bytes()),
943 ("short.png", b"BMelsewher".to_vec()),
944 ("tiny.png", png_prefix),
945 ("empty.png", Vec::new()),
946 ("text.png", b"just some words in a file".to_vec()),
947 ];
948 for (name, bytes) in cases {
949 fs::write(tmp.path().join(name), bytes).unwrap();
950 let ctx = ToolContext::new(tmp.path().to_path_buf());
951 let err = ImageOcrTool
952 .execute(json!({ "path": name }), &ctx)
953 .await
954 .expect_err("a file without an image signature must be refused");
955 assert!(
956 err.to_string().contains("is not a PNG, JPEG, TIFF"),
957 "{name}: {err}"
958 );
959 }
960 }
961
962 #[tokio::test]
963 async fn image_ocr_recovers_hello_from_fixture_image() {
964 if !ocr_available() {
965 // Tool wouldn't be registered without a local OCR backend — mirror
966 // that here so the suite stays green on CI images that
967 // intentionally omit OCR tooling.
968 return;
969 }
970 let fixture = ocr_fixture_path();
971 if !fixture.exists() {
972 // Fixture not committed (sparse / shallow checkout). Skip
973 // silently rather than failing the suite.
974 return;
975 }
976 let tmp = tempdir().expect("tempdir");
977 // Stage the fixture under the workspace so the path resolver
978 // accepts the relative input — keeps the test independent of
979 // the workspace boundary check inside `resolve_path`.
980 let staged = tmp.path().join("ocr_hello.png");
981 fs::copy(&fixture, &staged).unwrap();
982 let ctx = ToolContext::new(tmp.path().to_path_buf());
983 let result = match ImageOcrTool
984 .execute(json!({"path": "ocr_hello.png"}), &ctx)
985 .await
986 {
987 Ok(result) => result,
988 Err(err) => {
989 // Backend probe can still disagree with a live OCR run
990 // (restricted Vision, broken tesseract install, sandbox).
991 // Name promises coverage only when the backend works.
992 let msg = err.to_string();
993 let _skip_reason = format!("OCR backend probe passed but execute failed: {msg}");
994 let _ = &_skip_reason;
995 return;
996 }
997 };
998 assert!(result.success);
999 // Tesseract reliably recovers "HELLO OCR" from the rendered
1000 // PNG; allow either spacing variant.
1001 let normalised = result.content.to_uppercase();
1002 assert!(
1003 normalised.contains("HELLO") && normalised.contains("OCR"),
1004 "expected OCR to recover HELLO OCR; got {:?}",
1005 result.content
1006 );
1007 }
1008
1009 #[tokio::test]
1010 async fn deepseek_ocr_fallback_runs_when_opted_in_and_respects_network_policy() {
1011 use crate::test_support::{EnvVarGuard, lock_test_env};
1012 use codewhale_net::network_policy::{NetworkPolicy, NetworkPolicyDecider};
1013 use wiremock::matchers::{method, path};
1014 use wiremock::{Mock, MockServer, ResponseTemplate};
1015
1016 let server = MockServer::start().await;
1017 Mock::given(method("POST"))
1018 .and(path("/v1/tools/ocr"))
1019 .respond_with(ResponseTemplate::new(200).set_body_string(
1020 "\n{\"id\":\"ocr-test\",\"object\":\"ocr\",\"page_count\":1,\"pages\":[{\"index\":0,\"text\":\"INVOICE 42\",\"finish_reason\":\"stop\"}]}",
1021 ))
1022 .mount(&server)
1023 .await;
1024
1025 let tmp = tempfile::tempdir().expect("tempdir");
1026 let tmp_root = tmp.path().canonicalize().expect("canonical tempdir");
1027 let image_path = tmp_root.join("sample.png");
1028 fs::write(&image_path, b"\x89PNG\r\n\x1a\nfake-png").unwrap();
1029 let spoof_path = tmp_root.join("spoof.png");
1030 fs::write(&spoof_path, b"plaintext workspace file with png extension").unwrap();
1031
1032 let _lock = lock_test_env();
1033 let _local_off = EnvVarGuard::set("CODEWHALE_LOCAL_OCR_UNAVAILABLE", "1");
1034 let _opt_in = EnvVarGuard::set("CODEWHALE_DEEPSEEK_OCR", "1");
1035 let _key = EnvVarGuard::set("DEEPSEEK_API_KEY", "ds-ocr-test-key");
1036 let _base = EnvVarGuard::set("DEEPSEEK_BASE_URL", server.uri());
1037
1038 assert!(ocr_available());
1039
1040 let blocked_ctx = ToolContext::new(tmp_root.clone())
1041 .with_network_policy(NetworkPolicyDecider::new(NetworkPolicy::default(), None));
1042 let blocked = ocr_image_path(&image_path, &blocked_ctx).await;
1043 assert!(
1044 matches!(blocked, Err(ToolError::PermissionDenied { .. })),
1045 "{blocked:?}"
1046 );
1047 let bad_url = check_ocr_network_policy(&blocked_ctx, "://bad");
1048 assert!(
1049 matches!(bad_url, Err(ToolError::InvalidInput { .. })),
1050 "{bad_url:?}"
1051 );
1052
1053 let allow_ctx = ToolContext::new(tmp_root);
1054 let spoof = ocr_image_path(&spoof_path, &allow_ctx).await;
1055 assert!(
1056 matches!(spoof, Err(ToolError::InvalidInput { .. })),
1057 "{spoof:?}"
1058 );
1059 assert!(
1060 server
1061 .received_requests()
1062 .await
1063 .expect("requests")
1064 .is_empty()
1065 );
1066 let recovered = ocr_image_path(&image_path, &allow_ctx)
1067 .await
1068 .expect("deepseek ocr fallback succeeds");
1069 assert_eq!(recovered, "INVOICE 42");
1070 let received = server.received_requests().await.expect("requests");
1071 let raw = String::from_utf8_lossy(&received[0].body);
1072 assert!(
1073 raw.contains("name=\"file\"; filename=\"sample.png\""),
1074 "{raw}"
1075 );
1076 }
1077
1078 #[allow(clippy::await_holding_lock)]
1079 #[tokio::test]
1080 async fn image_ocr_refuses_credential_path_and_outside_hardlink() {
1081 use crate::test_support::{EnvVarGuard, lock_test_env};
1082
1083 let _lock = lock_test_env();
1084 let workspace = tempdir().expect("workspace");
1085 let ws_canon = workspace.path().canonicalize().expect("canon ws");
1086 let cw_home = ws_canon.join("cw-home");
1087 fs::create_dir_all(&cw_home).expect("mkdir cw-home");
1088 let _cw_home_guard = EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
1089 let _cfg_guard = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
1090 let _legacy_cfg_guard = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
1091
1092 let config_file = cw_home.join("config.toml");
1093 fs::write(&config_file, b"\x89PNG\r\n\x1a\nfake-png").expect("write config");
1094 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
1095 let cred_err = ImageOcrTool
1096 .execute(json!({"path": config_file.to_string_lossy()}), &trusted_ctx)
1097 .await
1098 .expect_err("credential file must be refused by image_ocr");
1099 assert!(
1100 matches!(cred_err, ToolError::PermissionDenied { .. }),
1101 "{cred_err:?}"
1102 );
1103
1104 #[cfg(unix)]
1105 {
1106 let outside = tempdir().expect("outside");
1107 let orig = outside.path().join("orig.png");
1108 let linked = outside.path().join("alias.png");
1109 fs::write(&orig, b"\x89PNG\r\n\x1a\nfake-png").expect("write orig");
1110 fs::hard_link(&orig, &linked).expect("hardlink");
1111 let link_err = ImageOcrTool
1112 .execute(json!({"path": linked.to_string_lossy()}), &trusted_ctx)
1113 .await
1114 .expect_err("outside hardlink must be refused by image_ocr");
1115 assert!(
1116 matches!(link_err, ToolError::PermissionDenied { .. }),
1117 "{link_err:?}"
1118 );
1119 }
1120 }
1121 }
1122
1123 #[cfg(all(test, unix))]
1124 #[path = "image_ocr/host_tests.rs"]
1125 mod host_tests;
1126
1126 lines RUST