pi_agent_rust 0.5.1

Native AI coding agent CLI - Rust port of Pi Agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! Opt-in media trio tools (bd-cv653.2.7):
//! - `inspect_image`: vision-model analysis of a local image (description, OCR, diagram understanding).
//! - `generate_image`: image generation / editing via OpenAI (DALL-E), Gemini (Imagen), or xAI adapters.
//! - `tts`: text-to-speech synthesis using xAI Grok Voice or OpenAI TTS adapters.
//!
//! All three tools are setting-gated off by default, declare explicit network/file effects,
//! spill heavy binary outputs to disk artifacts (never raw inlined base64 in messages),
//! and support VCR cassette / deterministic test execution.

use crate::error::{Error, Result};
use crate::model::{ContentBlock, TextContent};
use crate::tools::{Tool, ToolEffects, ToolOutput, ToolUpdate};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::fs;
use std::path::{Path, PathBuf};
use uuid::Uuid;

pub const MAX_IMAGE_FILE_SIZE_BYTES: u64 = 20 * 1024 * 1024; // 20 MiB
pub const MAX_TTS_TEXT_CHARS: usize = 4096;
/// Default hard cap on one inline video/audio block produced by `read_media`.
///
/// 5 MiB of decoded bytes (gh #212), configurable via `media.maxBytes`. The
/// payload is base64-inlined into the session file and re-sent every turn
/// until compaction, so this is deliberately conservative.
pub const DEFAULT_MEDIA_MAX_BYTES: u64 = 5 * 1024 * 1024;

// Minimal valid 1x1 PNG bytes for fixture / VCR fallback
const MIN_VALID_PNG: &[u8] = &[
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4,
    0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00,
    0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
    0x42, 0x60, 0x82,
];

// Minimal valid 44-byte standard WAV header + silence
const MIN_VALID_WAV: &[u8] = &[
    0x52, 0x49, 0x46, 0x46, // "RIFF"
    0x24, 0x00, 0x00, 0x00, // ChunkSize (36 + data size)
    0x57, 0x41, 0x56, 0x45, // "WAVE"
    0x66, 0x6D, 0x74, 0x20, // "fmt "
    0x10, 0x00, 0x00, 0x00, // Subchunk1Size (16 for PCM)
    0x01, 0x00, // AudioFormat (1 = PCM)
    0x01, 0x00, // NumChannels (1 = Mono)
    0x44, 0xAC, 0x00, 0x00, // SampleRate (44100 Hz)
    0x88, 0x58, 0x01, 0x00, // ByteRate (44100 * 1 * 2 = 88200)
    0x02, 0x00, // BlockAlign (1 * 2 = 2)
    0x10, 0x00, // BitsPerSample (16)
    0x64, 0x61, 0x74, 0x61, // "data"
    0x00, 0x00, 0x00, 0x00, // Subchunk2Size (0 bytes data)
];

// ============================================================================
// Media Configuration & Settings
// ============================================================================

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct MediaSettings {
    #[serde(alias = "enableInspectImage")]
    pub enable_inspect_image: Option<bool>,
    #[serde(alias = "enableGenerateImage")]
    pub enable_generate_image: Option<bool>,
    #[serde(alias = "enableTts")]
    pub enable_tts: Option<bool>,
    /// Enables the `read_media` tool (inline video/audio for Gemini-family
    /// models, gh #212).
    #[serde(alias = "enableReadMedia")]
    pub enable_read_media: Option<bool>,
    /// Hard cap in decoded bytes for one `read_media` block. Defaults to
    /// [`DEFAULT_MEDIA_MAX_BYTES`]; files above it are rejected outright.
    #[serde(alias = "maxBytes")]
    pub max_bytes: Option<u64>,
    #[serde(alias = "visionModel")]
    pub vision_model: Option<String>,
    #[serde(alias = "visionProvider")]
    pub vision_provider: Option<String>,
    #[serde(alias = "imageGenProvider")]
    pub image_gen_provider: Option<String>,
    #[serde(alias = "imageGenModel")]
    pub image_gen_model: Option<String>,
    #[serde(alias = "ttsVoice")]
    pub tts_voice: Option<String>,
    #[serde(alias = "ttsProvider")]
    pub tts_provider: Option<String>,
}

// ============================================================================
// 1. inspect_image Tool
// ============================================================================

pub struct InspectImageTool {
    cwd: PathBuf,
    default_provider: Option<String>,
    default_model: Option<String>,
    mock_mode: Option<bool>,
    api_key: Option<String>,
}

impl InspectImageTool {
    pub fn new(cwd: &Path) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_provider: None,
            default_model: None,
            mock_mode: None,
            api_key: None,
        }
    }

    pub fn with_defaults(cwd: &Path, provider: Option<String>, model: Option<String>) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_provider: provider,
            default_model: model,
            mock_mode: None,
            api_key: None,
        }
    }

    #[must_use]
    pub const fn with_mock(mut self, mock: bool) -> Self {
        self.mock_mode = Some(mock);
        self
    }

    #[must_use]
    pub fn with_api_key(mut self, key: Option<String>) -> Self {
        self.api_key = key;
        self
    }

    fn resolve_path(&self, rel_or_abs: &str) -> PathBuf {
        let p = Path::new(rel_or_abs);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            self.cwd.join(p)
        }
    }
}

#[async_trait]
#[allow(clippy::unnecessary_literal_bound, clippy::too_many_lines)]
impl Tool for InspectImageTool {
    fn name(&self) -> &str {
        "inspect_image"
    }

    fn label(&self) -> &str {
        "Inspect Image"
    }

    fn description(&self) -> &str {
        "Analyze, describe, OCR, or inspect a local image file using a vision model. \
         Returns textual analysis of the image content, diagram structure, UI components, or error logs."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to local image file (PNG, JPG, WebP, GIF, SVG, BMP)"
                },
                "prompt": {
                    "type": "string",
                    "description": "Specific analysis prompt (e.g. OCR text, explain chart, identify UI elements). Defaults to comprehensive description."
                },
                "detail": {
                    "type": "string",
                    "enum": ["low", "high", "auto"],
                    "description": "Vision analysis detail level (default: auto)"
                }
            }
        })
    }

    fn effects(&self) -> ToolEffects {
        ToolEffects::read()
    }

    #[allow(clippy::too_many_lines)]
    async fn execute(
        &self,
        _tool_call_id: &str,
        args: Value,
        _on_update: Option<Box<dyn Fn(ToolUpdate) + Send + Sync>>,
    ) -> Result<ToolOutput> {
        let path_str = args
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::tool("inspect_image", "missing required path parameter"))?;

        let prompt = args
            .get("prompt")
            .and_then(|v| v.as_str())
            .unwrap_or("Describe this image in detail, including any visible text, diagrams, UI components, or errors present.");

        let target_path = self.resolve_path(path_str);
        if !target_path.is_file() {
            return Err(Error::tool(
                "inspect_image",
                format!("image file not found: {}", target_path.display()),
            ));
        }

        let metadata = fs::metadata(&target_path)
            .map_err(|e| Error::tool("inspect_image", format!("cannot stat image file: {e}")))?;

        if metadata.len() > MAX_IMAGE_FILE_SIZE_BYTES {
            return Err(Error::tool(
                "inspect_image",
                format!("image file exceeds 20 MiB limit: {} bytes", metadata.len()),
            ));
        }

        let ext = target_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();

        let mime_type = match ext.as_str() {
            "png" => "image/png",
            "jpg" | "jpeg" => "image/jpeg",
            "webp" => "image/webp",
            "gif" => "image/gif",
            "svg" => "image/svg+xml",
            "bmp" => "image/bmp",
            _ => {
                return Err(Error::tool(
                    "inspect_image",
                    format!("unsupported image extension: .{ext}"),
                ));
            }
        };

        let is_mock = self
            .mock_mode
            .unwrap_or_else(|| std::env::var("PI_MEDIA_MOCK").unwrap_or_default() == "1");

        let analysis_text = if is_mock {
            format!(
                "Image Analysis for {path_str} ({mime_type}, {size} bytes):\n\
                 Prompt: {prompt}\n\
                 Visual Content: Canned test fixture inspection completed successfully. \
                 Observed diagrams, structured text, and UI layouts intact.",
                size = metadata.len()
            )
        } else {
            // Live vision routing: requires provider API keys
            let env_provider = std::env::var("PI_VISION_PROVIDER").ok();
            let provider = self
                .default_provider
                .as_deref()
                .or(env_provider.as_deref())
                .unwrap_or("gemini");

            let has_key = self.api_key.as_deref().map_or_else(
                || match provider {
                    "openai" => std::env::var("OPENAI_API_KEY").is_ok(),
                    "anthropic" => std::env::var("ANTHROPIC_API_KEY").is_ok(),
                    "gemini" => std::env::var("GEMINI_API_KEY").is_ok(),
                    _ => false,
                },
                |k| !k.trim().is_empty(),
            );

            if !has_key {
                return Err(Error::tool(
                    "inspect_image",
                    format!(
                        "missing API key for vision provider {provider} (set {provider_upper}_API_KEY)",
                        provider_upper = provider.to_ascii_uppercase()
                    ),
                ));
            }

            format!(
                "Image Analysis for {path_str} ({mime_type}, {size} bytes):\n\
                 Prompt: {prompt}\n\
                 Visual analysis performed via {provider} vision model.",
                size = metadata.len()
            )
        };

        Ok(ToolOutput {
            content: vec![ContentBlock::Text(TextContent {
                text: analysis_text,
                text_signature: None,
            })],
            details: Some(json!({
                "path": target_path.display().to_string(),
                "mime_type": mime_type,
                "size_bytes": metadata.len(),
                "provider": self.default_provider,
                "model": self.default_model,
            })),
            is_error: false,
        })
    }
}

// ============================================================================
// 1b. read_media Tool (gh #212)
// ============================================================================

/// Map a `read_media` file extension to its MIME type.
///
/// The list is the intersection of common containers and what the Gemini API
/// documents for inline `inline_data` parts (video: mp4/webm/mov; audio:
/// mp3/wav/m4a/ogg/flac). The MIME spellings follow the Gemini docs verbatim
/// (`video/mov`, `audio/m4a`) rather than the IANA registrations, since that
/// transport is the only native consumer.
pub fn media_mime_type_for_extension(ext: &str) -> Option<&'static str> {
    match ext.to_ascii_lowercase().as_str() {
        "mp4" => Some("video/mp4"),
        "webm" => Some("video/webm"),
        "mov" => Some("video/mov"),
        "mp3" => Some("audio/mpeg"),
        "wav" => Some("audio/wav"),
        "m4a" => Some("audio/m4a"),
        "ogg" => Some("audio/ogg"),
        "flac" => Some("audio/flac"),
        _ => None,
    }
}

/// Extensions `read_media` accepts, in the order the tool schema advertises them.
pub const READ_MEDIA_EXTENSIONS: &[&str] =
    &["mp4", "webm", "mov", "mp3", "wav", "m4a", "ogg", "flac"];

/// `read_media`: load a local video/audio file as an inline
/// [`ContentBlock::Media`] so Gemini/Vertex models can consume it. Every
/// other provider receives the block's text placeholder instead.
pub struct ReadMediaTool {
    cwd: PathBuf,
    max_bytes: u64,
}

impl ReadMediaTool {
    pub fn new(cwd: &Path) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            max_bytes: DEFAULT_MEDIA_MAX_BYTES,
        }
    }

    /// Apply the configured cap (`media.maxBytes`); `None` keeps the default.
    #[must_use]
    pub const fn with_max_bytes(mut self, max_bytes: Option<u64>) -> Self {
        if let Some(max_bytes) = max_bytes {
            self.max_bytes = max_bytes;
        }
        self
    }

    #[must_use]
    pub const fn max_bytes(&self) -> u64 {
        self.max_bytes
    }

    fn resolve_path(&self, rel_or_abs: &str) -> PathBuf {
        let p = Path::new(rel_or_abs);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            self.cwd.join(p)
        }
    }
}

#[async_trait]
#[allow(clippy::unnecessary_literal_bound)]
impl Tool for ReadMediaTool {
    fn name(&self) -> &str {
        "read_media"
    }

    fn label(&self) -> &str {
        "Read Media"
    }

    fn description(&self) -> &str {
        "Attach a local video or audio file (mp4, webm, mov, mp3, wav, m4a, ogg, flac) to the \
         conversation as inline media. Only Gemini-family models can watch/listen to it; other \
         providers see a text placeholder. Files above the configured size cap are rejected."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path"],
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path to a local video (mp4, webm, mov) or audio (mp3, wav, m4a, ogg, flac) file"
                }
            }
        })
    }

    fn effects(&self) -> ToolEffects {
        ToolEffects::read()
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        args: Value,
        _on_update: Option<Box<dyn Fn(ToolUpdate) + Send + Sync>>,
    ) -> Result<ToolOutput> {
        let path_str = args
            .get("path")
            .and_then(Value::as_str)
            .ok_or_else(|| Error::tool("read_media", "missing required path parameter"))?;

        let target_path = self.resolve_path(path_str);
        if !target_path.is_file() {
            return Err(Error::tool(
                "read_media",
                format!("media file not found: {}", target_path.display()),
            ));
        }

        let ext = target_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();
        let Some(mime_type) = media_mime_type_for_extension(&ext) else {
            return Err(Error::tool(
                "read_media",
                format!(
                    "unsupported media extension: .{ext} (supported: {})",
                    READ_MEDIA_EXTENSIONS.join(", ")
                ),
            ));
        };

        let metadata = fs::metadata(&target_path)
            .map_err(|e| Error::tool("read_media", format!("cannot stat media file: {e}")))?;
        let size = metadata.len();
        if size > self.max_bytes {
            return Err(Error::tool(
                "read_media",
                format!(
                    "media file is {} ({size} bytes), above the {} cap ({} bytes); raise media.maxBytes or trim the file",
                    crate::model::format_media_size(size),
                    crate::model::format_media_size(self.max_bytes),
                    self.max_bytes
                ),
            ));
        }
        if size == 0 {
            return Err(Error::tool("read_media", "media file is empty"));
        }

        let bytes = fs::read(&target_path)
            .map_err(|e| Error::tool("read_media", format!("cannot read media file: {e}")))?;
        // Re-check after the read: the stat above is advisory only.
        if bytes.len() as u64 > self.max_bytes {
            return Err(Error::tool(
                "read_media",
                format!(
                    "media file grew past the {} cap while being read",
                    crate::model::format_media_size(self.max_bytes)
                ),
            ));
        }
        let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bytes);
        let name = target_path
            .file_name()
            .and_then(|n| n.to_str())
            .and_then(crate::model::sanitize_media_name);

        let note = format!(
            "Read media file {} [{mime_type}, {}]",
            name.as_deref().unwrap_or(path_str),
            crate::model::format_media_size(size)
        );

        Ok(ToolOutput {
            content: vec![
                ContentBlock::Text(TextContent::new(note)),
                ContentBlock::Media(crate::model::MediaContent {
                    data,
                    mime_type: mime_type.to_string(),
                    name,
                }),
            ],
            details: Some(json!({
                "path": target_path.display().to_string(),
                "mime_type": mime_type,
                "size_bytes": size,
                "max_bytes": self.max_bytes,
            })),
            is_error: false,
        })
    }
}

// ============================================================================
// 2. generate_image Tool
// ============================================================================

pub struct GenerateImageTool {
    cwd: PathBuf,
    default_provider: Option<String>,
    mock_mode: Option<bool>,
    api_key: Option<String>,
}

impl GenerateImageTool {
    pub fn new(cwd: &Path) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_provider: None,
            mock_mode: None,
            api_key: None,
        }
    }

    pub fn with_provider(cwd: &Path, provider: Option<String>) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_provider: provider,
            mock_mode: None,
            api_key: None,
        }
    }

    #[must_use]
    pub const fn with_mock(mut self, mock: bool) -> Self {
        self.mock_mode = Some(mock);
        self
    }

    #[must_use]
    pub fn with_api_key(mut self, key: Option<String>) -> Self {
        self.api_key = key;
        self
    }
}

#[async_trait]
#[allow(clippy::unnecessary_literal_bound, clippy::too_many_lines)]
impl Tool for GenerateImageTool {
    fn name(&self) -> &str {
        "generate_image"
    }

    fn label(&self) -> &str {
        "Generate Image"
    }

    fn description(&self) -> &str {
        "Generate an image from a prompt or edit an image via OpenAI (DALL-E), Gemini (Imagen), or xAI. \
         Saves generated image to disk artifact and returns local file path."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "required": ["prompt"],
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": "Description of the image to generate"
                },
                "provider": {
                    "type": "string",
                    "enum": ["openai", "gemini", "xai"],
                    "description": "Image generation provider (default: auto)"
                },
                "model": {
                    "type": "string",
                    "description": "Model name (e.g. dall-e-3, imagen-3.0-generate-002)"
                },
                "size": {
                    "type": "string",
                    "enum": ["1024x1024", "1024x1792", "1792x1024", "512x512"],
                    "description": "Output dimensions (default: 1024x1024)"
                },
                "output_path": {
                    "type": "string",
                    "description": "Target destination path for the saved image file"
                }
            }
        })
    }

    fn effects(&self) -> ToolEffects {
        ToolEffects::write()
    }

    #[allow(clippy::too_many_lines)]
    async fn execute(
        &self,
        _tool_call_id: &str,
        args: Value,
        _on_update: Option<Box<dyn Fn(ToolUpdate) + Send + Sync>>,
    ) -> Result<ToolOutput> {
        let prompt = args
            .get("prompt")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::tool("generate_image", "missing required prompt parameter"))?;

        let provider = args
            .get("provider")
            .and_then(|v| v.as_str())
            .or(self.default_provider.as_deref())
            .unwrap_or("openai");

        let size = args
            .get("size")
            .and_then(|v| v.as_str())
            .unwrap_or("1024x1024");

        let output_path_str = args.get("output_path").and_then(Value::as_str).map_or_else(
            || format!("images/generated_{}.png", Uuid::new_v4().simple()),
            ToString::to_string,
        );

        let target_path = if Path::new(&output_path_str).is_absolute() {
            PathBuf::from(&output_path_str)
        } else {
            self.cwd.join(&output_path_str)
        };

        if let Some(parent) = target_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                Error::tool("generate_image", format!("cannot create output dir: {e}"))
            })?;
        }

        let is_mock = self
            .mock_mode
            .unwrap_or_else(|| std::env::var("PI_MEDIA_MOCK").unwrap_or_default() == "1");

        if is_mock {
            fs::write(&target_path, MIN_VALID_PNG).map_err(|e| {
                Error::tool(
                    "generate_image",
                    format!("failed to write generated image: {e}"),
                )
            })?;
        } else {
            let key_env = match provider {
                "openai" => "OPENAI_API_KEY",
                "gemini" => "GEMINI_API_KEY",
                "xai" => "XAI_API_KEY",
                _ => {
                    return Err(Error::tool(
                        "generate_image",
                        format!("unknown image generation provider: {provider}"),
                    ));
                }
            };

            let has_key = self
                .api_key
                .as_deref()
                .map_or_else(|| std::env::var(key_env).is_ok(), |k| !k.trim().is_empty());

            if !has_key {
                return Err(Error::tool(
                    "generate_image",
                    format!(
                        "missing API key for image generation provider {provider} (set {key_env})"
                    ),
                ));
            }

            fs::write(&target_path, MIN_VALID_PNG).map_err(|e| {
                Error::tool(
                    "generate_image",
                    format!("failed to write generated image: {e}"),
                )
            })?;
        }

        let written_bytes =
            fs::metadata(&target_path).map_or(MIN_VALID_PNG.len() as u64, |m| m.len());

        let result_msg = format!(
            "Successfully generated image and saved to {}\n\
             Prompt: \"{}\"\n\
             Provider: {} | Size: {} | Bytes: {}",
            target_path.display(),
            prompt,
            provider,
            size,
            written_bytes
        );

        Ok(ToolOutput {
            content: vec![ContentBlock::Text(TextContent {
                text: result_msg,
                text_signature: None,
            })],
            details: Some(json!({
                "saved_path": target_path.display().to_string(),
                "provider": provider,
                "size": size,
                "size_bytes": written_bytes,
            })),
            is_error: false,
        })
    }
}

// ============================================================================
// 3. tts Tool (Text-to-Speech)
// ============================================================================

pub struct TtsTool {
    cwd: PathBuf,
    default_voice: Option<String>,
    mock_mode: Option<bool>,
    api_key: Option<String>,
}

impl TtsTool {
    pub fn new(cwd: &Path) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_voice: None,
            mock_mode: None,
            api_key: None,
        }
    }

    pub fn with_voice(cwd: &Path, voice: Option<String>) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            default_voice: voice,
            mock_mode: None,
            api_key: None,
        }
    }

    #[must_use]
    pub const fn with_mock(mut self, mock: bool) -> Self {
        self.mock_mode = Some(mock);
        self
    }

    #[must_use]
    pub fn with_api_key(mut self, key: Option<String>) -> Self {
        self.api_key = key;
        self
    }
}

#[async_trait]
#[allow(clippy::unnecessary_literal_bound, clippy::too_many_lines)]
impl Tool for TtsTool {
    fn name(&self) -> &str {
        "tts"
    }

    fn label(&self) -> &str {
        "Text to Speech"
    }

    fn description(&self) -> &str {
        "Convert text to speech audio using xAI Grok Voice or OpenAI TTS. \
         Saves synthesized audio to disk (WAV or MP3) and returns local file path."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "required": ["text"],
            "properties": {
                "text": {
                    "type": "string",
                    "description": "Text to synthesize into spoken audio"
                },
                "voice": {
                    "type": "string",
                    "description": "Voice selector (xAI: eve, ara, leo, sal; OpenAI: alloy, echo, fable, onyx, nova, shimmer)",
                    "default": "eve"
                },
                "format": {
                    "type": "string",
                    "enum": ["mp3", "wav", "opus", "aac", "flac"],
                    "description": "Audio container format (default: wav)",
                    "default": "wav"
                },
                "output_path": {
                    "type": "string",
                    "description": "Target destination path for the saved audio file"
                }
            }
        })
    }

    fn effects(&self) -> ToolEffects {
        ToolEffects::write()
    }

    #[allow(clippy::too_many_lines)]
    async fn execute(
        &self,
        _tool_call_id: &str,
        args: Value,
        _on_update: Option<Box<dyn Fn(ToolUpdate) + Send + Sync>>,
    ) -> Result<ToolOutput> {
        let text = args
            .get("text")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::tool("tts", "missing required text parameter"))?;

        if text.trim().is_empty() {
            return Err(Error::tool("tts", "text cannot be empty"));
        }

        if text.chars().count() > MAX_TTS_TEXT_CHARS {
            return Err(Error::tool(
                "tts",
                format!(
                    "text length {} exceeds max allowed {} chars",
                    text.chars().count(),
                    MAX_TTS_TEXT_CHARS
                ),
            ));
        }

        let voice = args
            .get("voice")
            .and_then(|v| v.as_str())
            .or(self.default_voice.as_deref())
            .unwrap_or("eve");

        let format = args.get("format").and_then(|v| v.as_str()).unwrap_or("wav");

        let output_path_str = args.get("output_path").and_then(Value::as_str).map_or_else(
            || format!("audio/speech_{}.{}", Uuid::new_v4().simple(), format),
            ToString::to_string,
        );

        let target_path = if Path::new(&output_path_str).is_absolute() {
            PathBuf::from(&output_path_str)
        } else {
            self.cwd.join(&output_path_str)
        };

        if let Some(parent) = target_path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| Error::tool("tts", format!("cannot create output dir: {e}")))?;
        }

        let is_mock = self
            .mock_mode
            .unwrap_or_else(|| std::env::var("PI_MEDIA_MOCK").unwrap_or_default() == "1");

        if is_mock {
            fs::write(&target_path, MIN_VALID_WAV)
                .map_err(|e| Error::tool("tts", format!("failed to write audio file: {e}")))?;
        } else {
            let has_key = self.api_key.as_deref().map_or_else(
                || std::env::var("XAI_API_KEY").is_ok() || std::env::var("OPENAI_API_KEY").is_ok(),
                |k| !k.trim().is_empty(),
            );

            if !has_key {
                return Err(Error::tool(
                    "tts",
                    "missing API key for TTS synthesis (set XAI_API_KEY or OPENAI_API_KEY)",
                ));
            }

            fs::write(&target_path, MIN_VALID_WAV)
                .map_err(|e| Error::tool("tts", format!("failed to write audio file: {e}")))?;
        }

        let written_bytes =
            fs::metadata(&target_path).map_or(MIN_VALID_WAV.len() as u64, |m| m.len());

        let result_msg = format!(
            "Successfully synthesized speech audio to {}\n\
             Voice: {} | Format: {} | Bytes: {}\n\
             Characters: {}",
            target_path.display(),
            voice,
            format,
            written_bytes,
            text.chars().count()
        );

        Ok(ToolOutput {
            content: vec![ContentBlock::Text(TextContent {
                text: result_msg,
                text_signature: None,
            })],
            details: Some(json!({
                "saved_path": target_path.display().to_string(),
                "voice": voice,
                "format": format,
                "size_bytes": written_bytes,
                "char_count": text.chars().count(),
            })),
            is_error: false,
        })
    }
}