prux 1.3.0

A minimal terminal coding agent: TUI, built-in coding tools, and an extension system
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
//! read 工具:文本/图片读取 + 行偏移分页 + 截断。

use crate::{
    core::tools::{
        index::{
            ToolError, ToolResult, ToolResultAttachment, detect_supported_image_mime_type,
            resolve_tool_path,
        },
        operations::{DEFAULT_TOOL_OPS, ToolOperations},
    },
    utils::{
        image::format_dimension_note,
        image::{ImageResizeLimits, format_conversion_note, prepare_image},
        truncate::{self, DEFAULT_MAX_BYTES, TruncatedBy},
    },
};
use std::{io::Cursor, path::PathBuf};
use unicode_normalization::UnicodeNormalization;

/// read 工具图片选项
#[derive(Debug, Clone, Copy)]
pub struct ReadImageOptions {
    /// 模型输入是否含 image(决定是否附加 vision 提示)
    pub model_supports_images: bool,
    /// 是否自动缩放(settings images.autoResize,默认 true)
    pub auto_resize: bool,
    /// 是否阻止向模型发送图片(settings images.blockImages,默认 false)
    pub block_images: bool,
    /// 该模型的内联限制(目录 `inputLimits.images.resize`)
    pub resize_limits: ImageResizeLimits,
}

impl Default for ReadImageOptions {
    /// 默认图片选项:模型不支持图片、开启自动缩放、不阻止图片,内联限制取默认值。
    fn default() -> Self {
        Self {
            model_supports_images: false,
            auto_resize: true,
            block_images: false,
            resize_limits: ImageResizeLimits::default(),
        }
    }
}

/// read 工具入口:按行范围(`offset`/`limit`,`offset` 从 1 起)读取文件,图片按默认选项处理。
/// 路径会先尝试若干变体(空格/NFD/弯引号)定位实际文件;文件不存在或不可读时返回 `ToolError`。
pub async fn execute_read(
    path: &str,
    offset: Option<i64>,
    limit: Option<i64>,
    cwd: &str,
) -> Result<ToolResult, ToolError> {
    execute_read_with_options(path, offset, limit, cwd, ReadImageOptions::default()).await
}

/// 带图片选项的读取(agent 调用方按模型/设置注入选项)
pub async fn execute_read_with_options(
    path: &str,
    offset: Option<i64>,
    limit: Option<i64>,
    cwd: &str,
    image_opts: ReadImageOptions,
) -> Result<ToolResult, ToolError> {
    execute_read_with_ops(path, offset, limit, cwd, image_opts, &DEFAULT_TOOL_OPS).await
}

/// 带后端注入的读取
pub async fn execute_read_with_ops(
    path: &str,
    offset: Option<i64>,
    limit: Option<i64>,
    cwd: &str,
    image_opts: ReadImageOptions,
    ops: &dyn ToolOperations,
) -> Result<ToolResult, ToolError> {
    let absolute_path = resolve_read_path_variant(path, cwd, ops);
    let abs = absolute_path.to_string_lossy().to_string();
    ops.access(&abs).map_err(|e| {
        ToolError(format!(
            "Error reading file: {}. {}",
            absolute_path.display(),
            e
        ))
    })?;
    let bytes = match ops.read_file(&abs) {
        Ok(b) => b,
        Err(e) => {
            return Err(ToolError(format!(
                "Error reading file: {}. {}",
                absolute_path.display(),
                e
            )));
        }
    };
    let mime_type = detect_supported_image_mime_type(&bytes);
    if let Some(mime) = mime_type {
        return Ok(read_image_result(mime, &bytes, &image_opts));
    }

    // 非 UTF-8 用 U+FFFD 替换(尽力渲染乱码文本)
    let text_content = String::from_utf8_lossy(&bytes).to_string();
    let all_lines: Vec<&str> = text_content.split('\n').collect();
    let total_file_lines = all_lines.len();
    let start_line = match offset {
        Some(o) => (o - 1).max(0) as usize,
        None => 0,
    };
    let start_line_display = start_line + 1;
    if start_line >= all_lines.len() {
        return Err(ToolError(format!(
            "Offset {} is beyond end of file ({} lines total)",
            offset.unwrap_or(0),
            all_lines.len()
        )));
    }

    let selected_content: String;
    let mut user_limited_lines: Option<usize> = None;
    if let Some(limit) = limit {
        let end_line = (start_line + limit as usize).min(all_lines.len());
        selected_content = all_lines[start_line..end_line].join("\n");
        user_limited_lines = Some(end_line - start_line);
    } else {
        selected_content = all_lines[start_line..].join("\n");
    }

    let truncation = truncate::truncate_head(&selected_content, (None, None));
    let mut output_text: String;
    if truncation.first_line_exceeds_limit {
        let first_line_size = truncate::format_size(all_lines[start_line].len());
        output_text = format!(
            "[Line {} is {}, exceeds {} limit. Use bash: sed -n '{}p' {} | head -c {}]",
            start_line_display,
            first_line_size,
            truncate::format_size(DEFAULT_MAX_BYTES),
            start_line_display,
            path,
            DEFAULT_MAX_BYTES
        );
    } else if truncation.truncated {
        let end_line_display = start_line_display + truncation.output_lines - 1;
        let next_offset = end_line_display + 1;
        output_text = truncation.content.clone();
        match truncation.truncated_by {
            TruncatedBy::Lines => {
                output_text.push_str(&format!(
                    "\n\n[Showing lines {}-{} of {}. Use offset={} to continue.]",
                    start_line_display, end_line_display, total_file_lines, next_offset
                ));
            }
            _ => {
                output_text.push_str(&format!(
                    "\n\n[Showing lines {}-{} of {} ({} limit). Use offset={} to continue.]",
                    start_line_display,
                    end_line_display,
                    total_file_lines,
                    truncate::format_size(DEFAULT_MAX_BYTES),
                    next_offset
                ));
            }
        }
    } else if let Some(limited) = user_limited_lines {
        if start_line + limited < all_lines.len() {
            let remaining = all_lines.len() - (start_line + limited);
            let next_offset = start_line + limited + 1;
            output_text = format!(
                "{}\n\n[{} more lines in file. Use offset={} to continue.]",
                truncation.content, remaining, next_offset
            );
        } else {
            output_text = truncation.content;
        }
    } else {
        output_text = truncation.content;
    }

    Ok(with_read_output(ToolResult::text(output_text)))
}

/// 路径变体解析:原路径存在则直接用;否则尝试 5 个变体后取第一个存在的
fn resolve_read_path_variant(path: &str, cwd: &str, ops: &dyn ToolOperations) -> PathBuf {
    let base = resolve_tool_path(path, cwd);
    let base_str = base.to_string_lossy().to_string();
    if ops.exists(&base_str) {
        return base;
    }
    let mut variants: Vec<String> = Vec::new();

    // 1) " (AM|PM)." 窄无断空格替换
    if let Some(idx) = find_am_pm(&base_str) {
        let mut v = String::new();
        v.push_str(&base_str[..idx]);
        v.push('\u{202F}');
        v.push_str(&base_str[idx + 1..]);
        variants.push(v);
    }

    // 2) NFD 归一
    let nfd: String = base_str.nfd().collect();
    if nfd != base_str {
        variants.push(nfd.clone());
    }

    // 3) 弯引号替换(U+2018/2019/201B → ',U+201C/201D/201F → ")
    let curly: String = base_str
        .chars()
        .map(|c| match c {
            '\u{2018}' | '\u{2019}' | '\u{201B}' => '\'',
            '\u{201C}' | '\u{201D}' | '\u{201F}' => '"',
            _ => c,
        })
        .collect();

    if curly != base_str {
        variants.push(curly.clone());
    }

    // 4) NFD + 弯引号
    let nfd_curly: String = curly.nfd().collect();
    if nfd_curly != base_str && nfd_curly != nfd && nfd_curly != curly {
        variants.push(nfd_curly);
    }

    for v in variants {
        if ops.exists(&v) {
            return PathBuf::from(v);
        }
    }

    base
}

/// 返回首个「空格 + 两个点」的起始下标(macOS 截图文件名里 AM/PM 前的空格变体);
/// 调用方据此把该空格换成窄无断空格 U+202F;无匹配返回 None。
fn find_am_pm(s: &str) -> Option<usize> {
    let bytes = s.as_bytes();
    (0..bytes.len().saturating_sub(2))
        .find(|&i| bytes[i] == b' ' && bytes[i + 1] == b'.' && bytes.get(i + 2) == Some(&b'.'))
}

/// 图片读取结果:缩放/转换 + base64 附件
/// read 工具面向程序化调用方(codemode 脚本等)的输出契约:
/// 文本文件是字符串;图片是 `{ type, data, mimeType, note }`。
///
/// 与 [`with_read_output`] 构造的载荷同形,两者必须同步修改。
/// 属性不写 description(让类型在工具描述里只占一行)。
pub(crate) fn output_schema() -> serde_json::Value {
    serde_json::json!({
        "anyOf": [
            { "type": "string" },
            {
                "type": "object",
                "properties": {
                    "type": { "const": "image" },
                    "data": { "type": "string" },
                    "mimeType": { "type": "string" },
                    "note": { "type": "string" }
                },
                "required": ["type", "data", "mimeType", "note"],
                "additionalProperties": false
            }
        ]
    })
}

/// read 调用头的行范围标签:`:start` 或 `:start-end`(如 `:12`、`:12-20`)。
///
/// 宽松解析:数值与数字字符串都接受,`null` / 缺失按未给出处理(`offset` 缺省为 1);
/// 两侧都缺省、或值畸形时返回空串,调用方据此不显示标签。
/// `end` 算成 0 时也只显示起点(`offset=1, limit=0` → `:1`)。
/// 导出 HTML 的模板里有一段同语义的 `formatReadLineRange`,两处口径必须保持一致。
pub fn format_line_range(args: &serde_json::Value) -> String {
    let offset = args.get("offset").filter(|v| !v.is_null());
    let limit = args.get("limit").filter(|v| !v.is_null());
    if offset.is_none() && limit.is_none() {
        return String::new();
    }

    let start = match offset {
        Some(v) => match parse_line_number(v) {
            Some(n) => n,
            None => return String::new(),
        },
        None => 1.0,
    };

    let Some(limit) = limit else {
        return format!(":{}", format_line_number(start));
    };
    let Some(count) = parse_line_number(limit) else {
        return String::new();
    };

    let end = start + count - 1.0;
    if end == 0.0 {
        format!(":{}", format_line_number(start))
    } else {
        format!(":{}-{}", format_line_number(start), format_line_number(end))
    }
}

/// 解析行号:数字、或去首尾空白后非空的数字字符串;其余(`null` / 布尔 / 非数字文本 / NaN)为 `None`。
fn parse_line_number(value: &serde_json::Value) -> Option<f64> {
    let parsed = match value {
        serde_json::Value::Number(n) => n.as_f64(),
        serde_json::Value::String(s) if !s.trim().is_empty() => s.trim().parse::<f64>().ok(),
        _ => None,
    };
    parsed.filter(|n| n.is_finite())
}

/// 行号标签里的数字:整数值去掉小数点(`12.0` → `12`),非整数保留小数。
fn format_line_number(value: f64) -> String {
    if value.fract() == 0.0 {
        format!("{}", value as i64)
    } else {
        format!("{value}")
    }
}

/// 给 read 的结果补上结构化输出:文本文件是字符串本体,图片是
/// `{ type, data, mimeType, note }`(`note` 是随图的提示文本,如缩放/不支持视觉的说明)。
///
/// codemode 脚本因此能拿到 `image()` 能直接展示的图片块,而不只是一段文本。
fn with_read_output(result: ToolResult) -> ToolResult {
    let value = match result.attachments.first() {
        Some(attachment) => serde_json::json!({
            "type": "image",
            "data": attachment.data_base64,
            "mimeType": attachment.mime_type,
            "note": result.text,
        }),
        None => serde_json::Value::String(result.text.clone()),
    };
    result.with_structured_content(value)
}

/// 图片读取:解析尺寸 → 阻止发送/无法处理/不支持视觉/超限时退化成文本,否则带附件返回。
fn read_image_result(mime: &str, bytes: &[u8], opts: &ReadImageOptions) -> ToolResult {
    with_read_output(read_image_result_inner(mime, bytes, opts))
}

/// [`read_image_result`] 的实际实现(结构化输出由外层统一补上)。
fn read_image_result_inner(mime: &str, bytes: &[u8], opts: &ReadImageOptions) -> ToolResult {
    let original_size = image::ImageReader::new(Cursor::new(bytes))
        .with_guessed_format()
        .ok()
        .and_then(|r| r.into_dimensions().ok());
    let (_w, _h) = original_size.unwrap_or((0, 0));

    if opts.block_images {
        let mut r = ToolResult::text(format!("Read image file [{}]", mime));
        if let Some((w, h)) = original_size {
            r.details = Some(serde_json::json!({
                "blocked": true,
                "size": { "width": w, "height": h },
                "mimeType": mime,
            }));
        }
        return r;
    }

    let prepared = match prepare_image(bytes, mime, opts.resize_limits, opts.auto_resize) {
        Some(p) => p,
        None => {
            return ToolResult::text(format!(
                "Read image file [{mime}]\n[Image file could not be processed: unsupported or corrupt image.]"
            ));
        }
    };

    let mut text = format!("Read image file [{mime}]");
    if let (Some(original), Some(displayed)) = (prepared.original_size, prepared.displayed_size)
        && let Some(note) = format_dimension_note(original, displayed)
    {
        text.push('\n');
        text.push_str(&note);
    }

    if let Some(note) =
        format_conversion_note(prepared.converted_from.as_deref(), &prepared.mime_type)
    {
        text.push('\n');
        text.push_str(&note);
    }

    if !opts.model_supports_images {
        return ToolResult::text(format!(
            "{text}\n[Image content omitted: image attachments are not supported by this model.]"
        ));
    }

    // 兜底:规范化后仍超限(例如 auto_resize 关闭且原图过大)→ 不发送图片
    if prepared.data_base64.len() > opts.resize_limits.max_bytes {
        return ToolResult::text(format!(
            "Read image file [{mime}]\n[Image content omitted: image too large to send to model.]"
        ));
    }

    ToolResult::text(text).with_attachment(ToolResultAttachment {
        data_base64: prepared.data_base64,
        mime_type: prepared.mime_type,
        original_size: prepared.original_size,
        converted_from: prepared.converted_from,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use base64::Engine as _;

    fn make_png(w: u32, h: u32) -> Vec<u8> {
        let mut buf = Vec::new();
        image::RgbaImage::from_pixel(w, h, image::Rgba([10, 20, 30, 255]))
            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();
        buf
    }

    fn make_bmp(w: u32, h: u32) -> Vec<u8> {
        let mut buf = Vec::new();
        image::RgbImage::from_pixel(w, h, image::Rgb([200, 100, 50]))
            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Bmp)
            .unwrap();
        buf
    }

    #[test]
    fn line_range_tag_follows_pi_format() {
        // 缺省 / 畸形 / null 都不显示标签
        assert_eq!(format_line_range(&serde_json::json!({})), "");
        assert_eq!(
            format_line_range(&serde_json::json!({"offset": null, "limit": null})),
            ""
        );
        assert_eq!(format_line_range(&serde_json::json!({"offset": "abc"})), "");
        assert_eq!(
            format_line_range(&serde_json::json!({"offset": 5, "limit": "x"})),
            ""
        );

        // 只给 offset 时只显示起点;offset 缺省按 1 算
        assert_eq!(format_line_range(&serde_json::json!({"offset": 12})), ":12");
        assert_eq!(format_line_range(&serde_json::json!({"limit": 5})), ":1-5");

        // 数字字符串宽松解析;`end` 算成 0 时只显示起点(对齐 pi)
        assert_eq!(
            format_line_range(&serde_json::json!({"offset": "12", "limit": "8"})),
            ":12-19"
        );
        assert_eq!(
            format_line_range(&serde_json::json!({"offset": 1, "limit": 0})),
            ":1"
        );
    }

    #[test]
    fn read_png_attaches_image_block() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("pic.png");
        std::fs::write(&p, make_png(64, 32)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();
        assert_eq!(r.attachments.len(), 1);
        assert_eq!(r.attachments[0].mime_type, "image/png");
        assert_eq!(r.attachments[0].original_size, Some((64, 32)));
        assert!(r.attachments[0].converted_from.is_none());
        let dec = base64::engine::general_purpose::STANDARD
            .decode(&r.attachments[0].data_base64)
            .unwrap();
        assert_eq!(dec.len(), make_png(64, 32).len()); // 尺寸相同(未缩放)
    }

    /// 图片的 read 结果带结构化输出,形状与 `output_schema()` 一致,
    /// codemode 脚本因此能拿到可直接展示的图片块(对齐 pi `toReadOutput()`)。
    #[test]
    fn read_image_structured_output_matches_the_schema() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("pic.png");
        std::fs::write(&p, make_png(8, 8)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();

        let structured = r
            .structured_content
            .clone()
            .expect("图片结果应带结构化输出");
        assert_eq!(structured["type"], "image");
        assert_eq!(structured["mimeType"], "image/png");
        assert_eq!(structured["data"], r.attachments[0].data_base64);
        assert_eq!(structured["note"], r.text, "note 应是随图的提示文本");
        for field in ["type", "data", "mimeType", "note"] {
            assert!(structured.get(field).is_some(), "缺少字段 {field}");
        }
        assert!(output_schema()["anyOf"].is_array());
    }

    /// 文本文件的 read 结果的结构化输出就是文本本体。
    #[test]
    fn read_text_structured_output_is_the_text() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("note.txt");
        std::fs::write(&p, "hello\n").unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions::default(),
            ))
            .unwrap();
        assert_eq!(
            r.structured_content,
            Some(serde_json::Value::String(r.text.clone()))
        );
    }

    #[test]
    fn read_bmp_converts_to_png() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("pic.bmp");
        std::fs::write(&p, make_bmp(16, 16)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();
        assert_eq!(r.attachments.len(), 1);
        assert_eq!(r.attachments[0].mime_type, "image/png");
        assert_eq!(
            r.attachments[0].converted_from.as_deref(),
            Some("image/bmp")
        );
        assert!(r.text.contains("Read image file [image/bmp]"));
        assert!(
            r.text
                .contains("Image converted from image/bmp to image/png")
        );
    }

    /// 模型目录的 inputLimits 生效:更小的 maxWidth 直接作用于 read 附件。
    #[test]
    fn read_respects_per_model_resize_limits() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("wide.png");
        std::fs::write(&p, make_png(400, 200)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    resize_limits: ImageResizeLimits {
                        max_width: 64,
                        max_height: 64,
                        ..Default::default()
                    },
                    ..Default::default()
                },
            ))
            .unwrap();
        assert_eq!(r.attachments.len(), 1);
        let dec = base64::engine::general_purpose::STANDARD
            .decode(&r.attachments[0].data_base64)
            .unwrap();
        let dims = image::ImageReader::new(std::io::Cursor::new(&dec))
            .with_guessed_format()
            .unwrap()
            .into_dimensions()
            .unwrap();
        assert_eq!(dims, (64, 32), "应按模型 maxWidth=64 等比缩放");
        assert!(r.text.contains("original 400x200, displayed at 64x32"));
    }

    #[test]
    fn read_large_png_resizes_to_2000() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("big.png");
        std::fs::write(&p, make_png(4000, 2000)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();
        assert_eq!(r.attachments.len(), 1);
        let dec = base64::engine::general_purpose::STANDARD
            .decode(&r.attachments[0].data_base64)
            .unwrap();
        let dims = image::ImageReader::new(std::io::Cursor::new(&dec))
            .with_guessed_format()
            .unwrap()
            .into_dimensions()
            .unwrap();
        let limits = ImageResizeLimits::default();
        assert!(
            dims.0 <= limits.max_width && dims.1 <= limits.max_height,
            "{dims:?}"
        );
        assert!(r.text.contains("[Image: original 4000x2000,"), "{}", r.text);
    }

    #[test]
    fn read_block_images_returns_text() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("pic.png");
        std::fs::write(&p, make_png(8, 8)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    block_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();
        assert!(r.attachments.is_empty());
        assert!(r.text.contains("Read image file [image/png]"));
    }

    #[test]
    fn read_non_vision_model_omits_attachment() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("pic.png");
        std::fs::write(&p, make_png(8, 8)).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions::default(), // model_supports_images=false
            ))
            .unwrap();
        assert!(r.attachments.is_empty());
        assert!(
            r.text
                .contains("image attachments are not supported by this model")
        );
    }

    #[test]
    fn read_gif_stays_inline() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("anim.gif");
        let mut buf = Vec::new();
        let frame = image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]));
        image::codecs::gif::GifEncoder::new(&mut buf)
            .encode_frame(image::Frame::new(frame))
            .unwrap();
        std::fs::write(&p, &buf).unwrap();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let r = rt
            .block_on(execute_read_with_options(
                p.to_str().unwrap(),
                None,
                None,
                dir.path().to_str().unwrap(),
                ReadImageOptions {
                    model_supports_images: true,
                    ..Default::default()
                },
            ))
            .unwrap();
        assert_eq!(r.attachments.len(), 1);
        // GIF 是内联格式(pi 0.87.0 语义):原样保留,不做 PNG 转换
        assert_eq!(r.attachments[0].mime_type, "image/gif");
        assert_eq!(r.attachments[0].converted_from, None);
    }
}