sofos 0.2.11

An interactive AI coding agent for your terminal
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
use crate::api::MorphClient;
use crate::error::{DEFAULT_PARENT_DIR, Result, SofosError};
use crate::mcp::McpManager;
use crate::mcp::manager::{ImageData, ToolResult as McpToolResult};
use crate::tools::ToolName;
use crate::tools::bash::BashExecutor;
use crate::tools::codesearch::CodeSearchTool;
use crate::tools::filesystem::FileSystemTool;
use crate::tools::morph_validate;
use crate::tools::permissions::{self, PermissionManager};
use crate::tools::resolve::ResolvedPath;
use crate::tools::types::{
    add_code_search_tool, get_all_tools, get_all_tools_with_morph, get_read_only_tools,
};
use crate::tools::utils::{
    MAX_DIFF_TOKENS, MAX_FILE_READ_TOKENS, MAX_MCP_IMAGE_BYTES, MAX_MCP_IMAGE_COUNT,
    MAX_MCP_OUTPUT_TOKENS, MAX_PATH_LIST_TOKENS, TruncationKind, confirm_destructive,
    truncate_for_context,
};
use crate::ui::diff;
use colored::Colorize;
use serde_json::Value;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use std::time::Duration;

const SOFOS_USER_AGENT: &str = concat!("Sofos/", env!("CARGO_PKG_VERSION"));

/// Hard cap on the raw HTTP body `web_fetch` will accept. The post-fetch
/// pipeline runs HTML stripping and then truncates to ~64 KB of text
/// before handing anything to the model, so far less than 64 MB is ever
/// "visible". The cap exists to bound how much memory a single tool call
/// can pull in before that pipeline runs, so a pathological URL serving
/// gigabytes (or a misreported Content-Length) cannot OOM the process.
const MAX_WEB_FETCH_BODY_BYTES: usize = 64 * 1024 * 1024;

/// Result from tool execution that can contain text and/or images
#[derive(Debug, Clone)]
pub enum ToolExecutionResult {
    /// Simple text result (for most tools)
    Text(String),
    /// Structured result with optional images (for MCP tools)
    Structured(McpToolResult),
}

impl ToolExecutionResult {
    /// Get the text content
    pub fn text(&self) -> &str {
        match self {
            ToolExecutionResult::Text(s) => s,
            ToolExecutionResult::Structured(r) => &r.text,
        }
    }

    /// Get images if any
    pub fn images(&self) -> &[ImageData] {
        match self {
            ToolExecutionResult::Text(_) => &[],
            ToolExecutionResult::Structured(r) => &r.images,
        }
    }
}

/// ToolExecutor handles execution of tool calls from AI
#[derive(Clone)]
pub struct ToolExecutor {
    pub(super) fs_tool: FileSystemTool,
    code_search_tool: Option<CodeSearchTool>,
    bash_executor: BashExecutor,
    morph_client: Option<MorphClient>,
    mcp_manager: Option<McpManager>,
    safe_mode: bool,
    /// Whether interactive prompts (stdin) are available (false in tests/pipes)
    interactive: bool,
    // Not persisted across sessions.
    read_path_session_allowed: Arc<Mutex<HashSet<String>>>,
    read_path_session_denied: Arc<Mutex<HashSet<String>>>,
    write_path_session_allowed: Arc<Mutex<HashSet<String>>>,
    write_path_session_denied: Arc<Mutex<HashSet<String>>>,
}

/// Apply both MCP-response caps (image count/bytes and text tokens) in
/// the order the dispatcher needs. The drop note for images has to land
/// AFTER text truncation so the model always sees it — otherwise a
/// ~1 MB text response could push the note out past the truncation
/// boundary and the model would silently lose the "images dropped"
/// signal. The overage this adds to the text field is ~100 bytes,
/// immaterial compared with the 10 MB API ceiling this cap is really
/// protecting against. Factored out from the `execute` dispatcher so
/// the ordering can be pinned in unit tests.
pub(super) fn cap_mcp_response(result: &mut McpToolResult) {
    let dropped = cap_mcp_images(result);
    result.text = truncate_for_context(
        &result.text,
        MAX_MCP_OUTPUT_TOKENS,
        TruncationKind::McpOutput,
    );
    if dropped > 0 {
        result.text.push_str(&format!(
            "\n\n[{} image attachment(s) dropped: MCP image cap is {} images or ~{} MB total]",
            dropped,
            MAX_MCP_IMAGE_COUNT,
            MAX_MCP_IMAGE_BYTES / (1024 * 1024)
        ));
    }
}

/// Drop image attachments from an MCP result until both the per-call
/// count cap and the total-bytes cap are satisfied. Returns the number
/// of images that were dropped. Walks the list in order and keeps each
/// image that still fits under both caps — so a single oversized image
/// in the middle of the response is skipped without blocking smaller
/// images that come after it. Kept images retain their original order.
pub(super) fn cap_mcp_images(result: &mut McpToolResult) -> usize {
    let original = result.images.len();
    let mut kept = Vec::with_capacity(result.images.len().min(MAX_MCP_IMAGE_COUNT));
    let mut total_bytes: usize = 0;
    for img in std::mem::take(&mut result.images) {
        let size = img.base64_data.len();
        if kept.len() >= MAX_MCP_IMAGE_COUNT
            || total_bytes.saturating_add(size) > MAX_MCP_IMAGE_BYTES
        {
            continue;
        }
        total_bytes += size;
        kept.push(img);
    }
    result.images = kept;
    original - result.images.len()
}

/// Ensure `path`'s parent directory exists, creating it (and any missing
/// intermediates) if not. Used by move/copy when the destination is
/// outside the workspace — inside-workspace writes go through
/// `FileSystemTool::move_file` / `copy_file`, which already handle this.
fn ensure_parent_dir(path: &std::path::Path) -> Result<()> {
    if let Some(parent) = path.parent() {
        if !parent.exists() {
            std::fs::create_dir_all(parent).map_err(|e| {
                SofosError::ToolExecution(format!(
                    "Failed to create destination parent '{}': {}",
                    parent.display(),
                    e
                ))
            })?;
        }
    }
    Ok(())
}

/// Rename `src` → `dst` handling the four inside/outside combinations.
/// When both paths are inside the workspace we delegate to the
/// workspace-sandboxed `FileSystemTool::move_file`; any other combination
/// (inside→outside, outside→inside, outside→outside) uses `std::fs::rename`
/// on the canonical paths after the dispatcher has already verified the
/// required Read / Write grants.
fn move_between(
    source: &str,
    destination: &str,
    src: &ResolvedPath,
    dst: &ResolvedPath,
    fs_tool: &FileSystemTool,
) -> Result<()> {
    if src.is_inside_workspace && dst.is_inside_workspace {
        return fs_tool.move_file(source, destination);
    }
    ensure_parent_dir(&dst.canonical)?;
    std::fs::rename(&src.canonical, &dst.canonical).map_err(|e| {
        SofosError::ToolExecution(format!(
            "Failed to move '{}' to '{}': {}",
            source, destination, e
        ))
    })
}

/// Copy-file counterpart to [`move_between`]. Same inside/outside matrix;
/// uses `FileSystemTool::copy_file` when both are inside, `std::fs::copy`
/// otherwise.
fn copy_between(
    source: &str,
    destination: &str,
    src: &ResolvedPath,
    dst: &ResolvedPath,
    fs_tool: &FileSystemTool,
) -> Result<()> {
    if src.is_inside_workspace && dst.is_inside_workspace {
        return fs_tool.copy_file(source, destination);
    }
    ensure_parent_dir(&dst.canonical)?;
    std::fs::copy(&src.canonical, &dst.canonical)
        .map(|_| ())
        .map_err(|e| {
            SofosError::ToolExecution(format!(
                "Failed to copy '{}' to '{}': {}",
                source, destination, e
            ))
        })
}

impl ToolExecutor {
    pub fn new(
        workspace: std::path::PathBuf,
        morph_client: Option<MorphClient>,
        mcp_manager: Option<McpManager>,
        safe_mode: bool,
        interactive: bool,
    ) -> Result<Self> {
        let code_search_tool = match CodeSearchTool::new(workspace.clone()) {
            Ok(tool) => Some(tool),
            Err(_) => {
                crate::ui::UI::print_warning("ripgrep not found. Code search will be unavailable.");
                None
            }
        };

        let has_morph = morph_client.is_some();
        Ok(Self {
            fs_tool: FileSystemTool::new(workspace.clone())?,
            code_search_tool,
            bash_executor: BashExecutor::new(workspace, interactive, has_morph)?,
            morph_client,
            mcp_manager,
            safe_mode,
            interactive,
            read_path_session_allowed: Arc::new(Mutex::new(HashSet::new())),
            read_path_session_denied: Arc::new(Mutex::new(HashSet::new())),
            write_path_session_allowed: Arc::new(Mutex::new(HashSet::new())),
            write_path_session_denied: Arc::new(Mutex::new(HashSet::new())),
        })
    }

    pub fn has_morph(&self) -> bool {
        self.morph_client.is_some()
    }

    pub fn has_code_search(&self) -> bool {
        self.code_search_tool.is_some()
    }

    pub fn set_safe_mode(&mut self, safe_mode: bool) {
        self.safe_mode = safe_mode;
    }

    /// Check read permissions on a path (both original and canonical forms),
    /// and verify external access. Returns Ok if allowed, Err if denied.
    fn check_read_access(
        &self,
        path: &str,
        canonical: &std::path::Path,
        canonical_str: &str,
        is_inside_workspace: bool,
    ) -> Result<()> {
        let permission_manager = PermissionManager::new(self.fs_tool.workspace().to_path_buf())?;

        let (perm_original, matched_rule_original) =
            permission_manager.check_read_permission_with_source(path);
        let (perm_canonical, matched_rule_canonical) =
            permission_manager.check_read_permission_with_source(canonical_str);

        let (final_perm, matched_rule) = if perm_original == permissions::CommandPermission::Denied
        {
            (perm_original, matched_rule_original)
        } else if perm_canonical == permissions::CommandPermission::Denied {
            (perm_canonical, matched_rule_canonical)
        } else if perm_original == permissions::CommandPermission::Ask {
            (perm_original, None)
        } else if perm_canonical == permissions::CommandPermission::Ask {
            (perm_canonical, None)
        } else {
            (permissions::CommandPermission::Allowed, None)
        };

        match final_perm {
            permissions::CommandPermission::Denied => {
                let config_source = if let Some(ref rule) = matched_rule {
                    permission_manager.get_rule_source(rule)
                } else {
                    ".sofos/config.local.toml or ~/.sofos/config.toml".to_string()
                };
                return Err(SofosError::ToolExecution(format!(
                    "Read access denied for path '{}'\n\
                     Hint: Blocked by deny rule in {}",
                    path, config_source
                )));
            }
            permissions::CommandPermission::Ask => {
                return Err(SofosError::ToolExecution(format!(
                    "Path '{}' is in 'ask' list\n\
                     Hint: 'ask' only works for Bash commands. Use 'allow' or 'deny' for Read permissions.",
                    path
                )));
            }
            permissions::CommandPermission::Allowed => {}
        }

        if !is_inside_workspace {
            // Use ONLY the canonical (symlink-resolved) path for permission checks
            // to prevent symlink escape attacks
            let is_explicit_allow = permission_manager.is_read_explicit_allow(canonical_str);
            if !is_explicit_allow {
                let dir_to_grant = if canonical.is_dir() {
                    canonical_str.to_string()
                } else {
                    canonical
                        .parent()
                        .and_then(|p| p.to_str())
                        .unwrap_or(canonical_str)
                        .to_string()
                };
                self.check_external_path_access(
                    "Read",
                    canonical_str,
                    &dir_to_grant,
                    &self.read_path_session_allowed,
                    &self.read_path_session_denied,
                )?;
            }
        }

        Ok(())
    }

    /// Check Write permissions for an external path: enforce deny rules, then check allow/ask.
    fn check_write_access(
        &self,
        path: &str,
        canonical_str: &str,
        canonical: &std::path::Path,
    ) -> Result<()> {
        let permission_manager = PermissionManager::new(self.fs_tool.workspace().to_path_buf())?;

        // Enforce Write deny rules first
        if permission_manager.check_write_permission(canonical_str)
            == permissions::CommandPermission::Denied
        {
            return Err(SofosError::ToolExecution(format!(
                "Write access denied for path '{}'\n\
                 Hint: Blocked by deny rule in .sofos/config.local.toml or ~/.sofos/config.toml",
                path
            )));
        }

        // Check explicit allow (canonical only, for symlink safety)
        let is_explicit_allow = permission_manager.is_write_explicit_allow(canonical_str);
        if !is_explicit_allow {
            let dir_to_grant = canonical
                .parent()
                .and_then(|p| p.to_str())
                .unwrap_or(canonical_str);
            self.check_external_path_access(
                "Write",
                canonical_str,
                dir_to_grant,
                &self.write_path_session_allowed,
                &self.write_path_session_denied,
            )?;
        }

        Ok(())
    }

    /// Check if an external path is allowed for the given scope, asking the user if needed.
    /// Returns Ok(()) if access is granted, Err if denied.
    fn check_external_path_access(
        &self,
        scope: &str,
        canonical_path: &str,
        dir_to_grant: &str,
        session_allowed: &Arc<Mutex<HashSet<String>>>,
        session_denied: &Arc<Mutex<HashSet<String>>>,
    ) -> Result<()> {
        let path_obj = std::path::Path::new(canonical_path);

        // Check session allowed
        if let Ok(allowed_dirs) = session_allowed.lock() {
            for dir in allowed_dirs.iter() {
                if path_obj.starts_with(std::path::Path::new(dir)) {
                    return Ok(());
                }
            }
        }

        // Check session denied
        if let Ok(denied_dirs) = session_denied.lock() {
            for dir in denied_dirs.iter() {
                if path_obj.starts_with(std::path::Path::new(dir)) {
                    return Err(SofosError::ToolExecution(format!(
                        "{} access denied for '{}' (denied earlier this session)",
                        scope, canonical_path
                    )));
                }
            }
        }

        // Non-interactive mode (tests, piped input): deny with a config hint
        if !self.interactive {
            return Err(SofosError::ToolExecution(format!(
                "Path '{}' is outside workspace and not explicitly allowed\n\
                 Hint: Add {}({}/**) to 'allow' list in .sofos/config.local.toml",
                canonical_path, scope, dir_to_grant
            )));
        }

        // Ask user interactively
        let mut pm = PermissionManager::new(self.fs_tool.workspace().to_path_buf())?;
        let (allowed, remember) = pm.ask_user_path_permission(scope, dir_to_grant)?;

        if allowed {
            if !remember {
                if let Ok(mut dirs) = session_allowed.lock() {
                    dirs.insert(dir_to_grant.to_string());
                }
            }
            Ok(())
        } else {
            if !remember {
                if let Ok(mut dirs) = session_denied.lock() {
                    dirs.insert(dir_to_grant.to_string());
                }
            }
            Err(SofosError::ToolExecution(format!(
                "{} access denied by user for '{}'",
                scope, canonical_path
            )))
        }
    }

    pub async fn get_available_tools(&self) -> Vec<crate::api::Tool> {
        let mut tools = if self.safe_mode {
            get_read_only_tools()
        } else if self.has_morph() {
            get_all_tools_with_morph()
        } else {
            get_all_tools()
        };

        if self.has_code_search() {
            add_code_search_tool(&mut tools);
        }

        if let Some(mcp_manager) = &self.mcp_manager {
            if let Ok(mcp_tools) = mcp_manager.get_all_tools().await {
                tools.extend(mcp_tools);
            }
        }

        tools
    }

    pub async fn execute(&self, tool_name: &str, input: &Value) -> Result<ToolExecutionResult> {
        // Check if this is an MCP tool first
        if let Some(mcp_manager) = &self.mcp_manager {
            if mcp_manager.is_mcp_tool(tool_name) {
                let mut result = mcp_manager.execute_tool(tool_name, input).await?;
                cap_mcp_response(&mut result);
                return Ok(ToolExecutionResult::Structured(result));
            }
        }

        let tool = ToolName::from_str(tool_name)?;

        let text_result = match tool {
            ToolName::ReadFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let resolved = self.resolve_existing(path).map_err(|_| {
                    let parent_dir = std::path::Path::new(path)
                        .parent()
                        .and_then(|p| p.to_str())
                        .unwrap_or(DEFAULT_PARENT_DIR);
                    SofosError::ToolExecution(format!(
                        "File not found: '{}'. Suggestion: Use list_directory with path '{}' to see available files.",
                        path, parent_dir
                    ))
                })?;

                self.check_read_access(
                    path,
                    &resolved.canonical,
                    &resolved.canonical_str,
                    resolved.is_inside_workspace,
                )?;

                // Read raw file contents, then apply the model-facing
                // truncation cap here at the dispatcher. Truncation lives
                // in this layer (not inside `fs_tool.read_file`) so that
                // `edit_file` / `morph_edit_file` / the `write_file` diff
                // path — which all call the same fs_tool method — get the
                // full file and don't silently drop the tail past ~64 KB.
                let raw = if resolved.is_inside_workspace {
                    self.fs_tool.read_file(path)?
                } else {
                    self.fs_tool
                        .read_file_with_outside_access(&resolved.canonical_str)?
                };
                let content =
                    truncate_for_context(&raw, MAX_FILE_READ_TOKENS, TruncationKind::File);
                Ok(format!("File content of '{}':\n\n{}", path, content))
            }
            ToolName::WriteFile => {
                // Accept common parameter-name variations. OpenAI
                // models occasionally emit `file_path` / `file` /
                // `filename` (especially when the tool-argument JSON
                // gets repaired from a truncated payload), and
                // `text` / `body` / `data` in place of `content`.
                // Failing the call with a bare "missing parameter"
                // message forces the model to re-plan from scratch;
                // accepting the aliases lets the call proceed, and
                // when nothing matches we echo the keys that WERE
                // supplied so the model can self-correct.
                let path = input["path"]
                    .as_str()
                    .or_else(|| input["file_path"].as_str())
                    .or_else(|| input["file"].as_str())
                    .or_else(|| input["filepath"].as_str())
                    .or_else(|| input["filename"].as_str())
                    .ok_or_else(|| {
                        let keys: Vec<&String> = input
                            .as_object()
                            .map(|o| o.keys().collect())
                            .unwrap_or_default();
                        // If `content` is the only populated field, the
                        // model's previous response almost certainly got
                        // cut off mid-tool-call by `max_output_tokens`
                        // before it could emit `path`. Include a
                        // concrete, actionable recovery hint so the
                        // model doesn't just retry the same oversized
                        // write and hit the same truncation again.
                        let content_only = keys.len() == 1
                            && keys.first().map(|s| s.as_str()) == Some("content");
                        let hint = if content_only {
                            " Your previous response was likely truncated mid-call (content was emitted but the tool-call JSON was cut off before `path`). Split the file into smaller pieces, or use `edit_file` to append in chunks, rather than writing the full body in one call."
                        } else {
                            ""
                        };
                        SofosError::ToolExecution(format!(
                            "Missing 'path' parameter. Got keys: {:?}. \
                             Please retry with 'path' set to the destination file path.{}",
                            keys, hint
                        ))
                    })?;
                let content = input["content"]
                    .as_str()
                    .or_else(|| input["text"].as_str())
                    .or_else(|| input["body"].as_str())
                    .or_else(|| input["data"].as_str())
                    .ok_or_else(|| {
                        SofosError::ToolExecution(format!(
                            "Missing 'content' parameter. Got keys: {:?}. \
                             Please retry with 'content' set to the file body.",
                            input
                                .as_object()
                                .map(|o| o.keys().collect::<Vec<_>>())
                                .unwrap_or_default()
                        ))
                    })?;

                let resolved = self.resolve_for_write(path)?;

                if !resolved.is_inside_workspace {
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                // Append mode lets the model write a file larger than a
                // single `max_output_tokens` response in multiple calls:
                // first call (append=false or omitted) creates/
                // overwrites, later calls append to the growing file.
                // Default is false so `write_file` keeps its usual
                // "create or overwrite" semantics for non-chunked
                // writes.
                let append = input["append"].as_bool().unwrap_or(false);

                let original_content = if append {
                    // In append mode we don't compute a diff: the
                    // interesting delta is just the new chunk, which
                    // the model already has in front of it. Reading
                    // the whole file back for each chunk would scale
                    // quadratically with the number of chunks.
                    None
                } else if resolved.is_inside_workspace {
                    self.fs_tool.read_file(path).ok()
                } else {
                    self.fs_tool
                        .read_file_with_outside_access(&resolved.canonical_str)
                        .ok()
                };

                match (append, resolved.is_inside_workspace) {
                    (true, true) => self.fs_tool.append_file(path, content)?,
                    (true, false) => self
                        .fs_tool
                        .append_file_with_outside_access(&resolved.canonical_str, content)?,
                    (false, true) => self.fs_tool.write_file(path, content)?,
                    (false, false) => self
                        .fs_tool
                        .write_file_with_outside_access(&resolved.canonical_str, content)?,
                }

                if append {
                    Ok(format!(
                        "Successfully appended {} bytes to '{}'",
                        content.len(),
                        path
                    ))
                } else if let Some(original) = original_content {
                    let diff_output = diff::generate_compact_diff(&original, content, path);
                    let body = format!(
                        "Successfully wrote to file '{}'\n\nChanges:\n{}",
                        path, diff_output
                    );
                    Ok(truncate_for_context(
                        &body,
                        MAX_DIFF_TOKENS,
                        TruncationKind::DiffOutput,
                    ))
                } else {
                    Ok(format!("Successfully created file '{}'", path))
                }
            }
            ToolName::ListDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let resolved = self.resolve_existing(path)?;
                self.check_read_access(
                    path,
                    &resolved.canonical,
                    &resolved.canonical_str,
                    resolved.is_inside_workspace,
                )?;

                let entries = if resolved.is_inside_workspace {
                    self.fs_tool.list_directory(path)?
                } else {
                    let canonical_entries = std::fs::read_dir(&resolved.canonical)?;
                    let mut entries = Vec::new();
                    for entry in canonical_entries {
                        let entry = entry?;
                        let name = entry.file_name().to_string_lossy().to_string();
                        let is_dir = entry.file_type()?.is_dir();
                        entries.push(if is_dir { format!("{}/", name) } else { name });
                    }
                    entries.sort();
                    entries
                };

                let body = format!("Contents of '{}':\n{}", path, entries.join("\n"));
                Ok(truncate_for_context(
                    &body,
                    MAX_PATH_LIST_TOKENS,
                    TruncationKind::PathList,
                ))
            }
            ToolName::CreateDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                // Symmetry with `write_file` / `edit_file`: accept
                // absolute and `~/` paths gated by a Write grant, so a
                // user who's granted Write to an external directory can
                // create subfolders there without dropping to bash.
                let resolved = self.resolve_for_write(path)?;
                if !resolved.is_inside_workspace {
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                if resolved.is_inside_workspace {
                    self.fs_tool.create_directory(path)?;
                } else {
                    std::fs::create_dir_all(&resolved.canonical).map_err(|e| {
                        SofosError::ToolExecution(format!(
                            "Failed to create directory '{}': {}",
                            path, e
                        ))
                    })?;
                }
                Ok(format!("Successfully created directory '{}'", path))
            }
            ToolName::SearchCode => {
                let code_search = self.code_search_tool.as_ref()
                    .ok_or_else(|| SofosError::ToolExecution(
                        "Code search not available. Please install ripgrep: https://github.com/BurntSushi/ripgrep".to_string()
                    ))?;

                let pattern = input["pattern"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'pattern' parameter".to_string())
                })?;

                let file_type = input["file_type"].as_str();
                let max_results = input["max_results"].as_u64().map(|n| n as usize);
                let include_ignored = input["include_ignored"].as_bool().unwrap_or(false);

                let results =
                    code_search.search(pattern, file_type, max_results, include_ignored)?;
                Ok(format!(
                    "{}{}",
                    crate::tools::codesearch::SEARCH_RESULTS_PREFIX,
                    results
                ))
            }
            ToolName::GlobFiles => {
                let pattern = input["pattern"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'pattern' parameter".to_string())
                })?;
                let base = input["path"].as_str().unwrap_or(".");
                let include_ignored = input["include_ignored"].as_bool().unwrap_or(false);
                // Matches ripgrep's default: symlinks are not followed
                // unless the caller opts in. Prevents a workspace-internal
                // symlink pointing outside the workspace from leaking
                // filenames under the target directory. Set
                // `follow_symlinks: true` to walk them (equivalent to
                // `rg -L`).
                let follow_symlinks = input["follow_symlinks"].as_bool().unwrap_or(false);

                // Same shape as `list_directory` / `read_file`: resolve
                // the base path (tilde/abs/rel) and route through
                // `check_read_access`. External paths with a Read grant
                // proceed; unauthorised `base=".."` / `base="/etc"` hit
                // the permission gate.
                let resolved = self.resolve_existing(base)?;
                self.check_read_access(
                    base,
                    &resolved.canonical,
                    &resolved.canonical_str,
                    resolved.is_inside_workspace,
                )?;
                let search_dir = resolved.canonical;

                // `literal_separator(true)` keeps `*` from crossing `/`,
                // so `*.rs` matches only top-level Rust files and not
                // every Rust file in every subdirectory. Recursive matches
                // still work via `**`. The previous default let a casual
                // `*.rs` quietly walk arbitrary depths, which surprised
                // users and broadened any pattern based on the file name
                // alone into a workspace-wide hit.
                let glob = globset::GlobBuilder::new(pattern)
                    .literal_separator(true)
                    .build()
                    .map_err(|e| SofosError::ToolExecution(format!("Invalid glob pattern: {}", e)))?
                    .compile_matcher();

                // Skip descent into build / vendor directories by basename.
                // Matches the `search_code` policy and prevents a broad
                // pattern like `**/*` from walking a 2.5 GB `target/` tree.
                // `include_ignored=true` disables this and walks everything.
                let excluded_basenames: std::collections::HashSet<&str> = if include_ignored {
                    std::collections::HashSet::new()
                } else {
                    crate::tools::codesearch::DEFAULT_EXCLUDE_DIRS
                        .iter()
                        .copied()
                        .collect()
                };

                let mut matches = Vec::new();
                let mut stack = vec![search_dir.clone()];

                while let Some(dir) = stack.pop() {
                    let entries = match std::fs::read_dir(&dir) {
                        Ok(e) => e,
                        Err(_) => continue,
                    };
                    for entry in entries.flatten() {
                        // `file_type()` returns symlink info without
                        // following the link, so we can distinguish a
                        // real directory from a symlink-to-directory.
                        let file_type = match entry.file_type() {
                            Ok(ft) => ft,
                            Err(_) => continue,
                        };
                        if file_type.is_symlink() && !follow_symlinks {
                            continue;
                        }
                        let path = entry.path();
                        if path.is_dir() {
                            let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
                            if excluded_basenames.contains(dir_name) {
                                continue;
                            }
                            stack.push(path);
                        } else if let Ok(rel) = path.strip_prefix(&search_dir) {
                            let rel_str = rel.to_string_lossy();
                            if glob.is_match(rel_str.as_ref()) {
                                matches.push(rel_str.to_string());
                            }
                        }
                    }
                }

                matches.sort();

                let body = if matches.is_empty() {
                    format!("No files matching '{}' in '{}'", pattern, base)
                } else {
                    format!(
                        "Found {} file(s) matching '{}':\n{}",
                        matches.len(),
                        pattern,
                        matches.join("\n")
                    )
                };

                Ok(truncate_for_context(
                    &body,
                    MAX_PATH_LIST_TOKENS,
                    TruncationKind::PathList,
                ))
            }
            ToolName::EditFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;
                let old_string = input["old_string"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'old_string' parameter".to_string())
                })?;
                let new_string = input["new_string"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'new_string' parameter".to_string())
                })?;
                let replace_all = input["replace_all"].as_bool().unwrap_or(false);

                // Guard against truncation markers from conversation history compaction
                let truncation_markers = [
                    "...[truncated",
                    "// ... existing code ...",
                    "/* ... existing code ... */",
                    "# ... existing code ...",
                ];
                for marker in &truncation_markers {
                    if old_string.contains(marker) {
                        return Err(SofosError::ToolExecution(format!(
                            "old_string contains a truncation marker '{}'. This is not real file content. \
                             Use read_file to get the actual current content of '{}' before editing.",
                            marker, path
                        )));
                    }
                    if new_string.contains(marker) {
                        return Err(SofosError::ToolExecution(format!(
                            "new_string contains a truncation marker '{}'. You must provide the complete \
                             replacement text, not abbreviated content. Use read_file to get the current \
                             content of '{}' if needed.",
                            marker, path
                        )));
                    }
                }

                let resolved = self.resolve_existing(path).map_err(|_| {
                    SofosError::ToolExecution(format!(
                        "File not found: '{}'. The file must exist to edit it.",
                        path
                    ))
                })?;

                // External paths require BOTH a Read grant (we read the
                // file to compute the modified content and the diff) and
                // a Write grant (we write it back). Previously only
                // Write was checked, which silently granted Read as a
                // side effect — defensible ergonomically, but wrong if
                // the user explicitly shaped the permission model to
                // allow writes and block reads. Check both so the scopes
                // hold independently.
                if !resolved.is_inside_workspace {
                    self.check_read_access(
                        path,
                        &resolved.canonical,
                        &resolved.canonical_str,
                        resolved.is_inside_workspace,
                    )?;
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                let original = if resolved.is_inside_workspace {
                    self.fs_tool.read_file(path)?
                } else {
                    self.fs_tool
                        .read_file_with_outside_access(&resolved.canonical_str)?
                };

                if !original.contains(old_string) {
                    return Err(SofosError::ToolExecution(format!(
                        "old_string not found in '{}'. Make sure it matches the file content exactly, \
                         including whitespace and indentation. Use read_file first to see the current content.",
                        path
                    )));
                }

                let modified = if replace_all {
                    original.replace(old_string, new_string)
                } else {
                    original.replacen(old_string, new_string, 1)
                };

                if resolved.is_inside_workspace {
                    self.fs_tool.write_file(path, &modified)?;
                } else {
                    self.fs_tool
                        .write_file_with_outside_access(&resolved.canonical_str, &modified)?;
                }

                let diff_output = diff::generate_compact_diff(&original, &modified, path);
                let body = format!(
                    "Successfully edited '{}'\n\nChanges:\n{}",
                    path, diff_output
                );
                Ok(truncate_for_context(
                    &body,
                    MAX_DIFF_TOKENS,
                    TruncationKind::DiffOutput,
                ))
            }
            ToolName::MorphEditFile => {
                let morph = self.morph_client.as_ref().ok_or_else(|| {
                    SofosError::ToolExecution(
                        "Morph client not available. Set MORPH_API_KEY to use morph_edit_file"
                            .to_string(),
                    )
                })?;

                // Canonical schema (Morph docs) is `target_filepath` /
                // `instructions` / `code_edit`. Accept legacy `path` /
                // `instruction` (and a few common typos) so older
                // conversation history and models that diverge keep working.
                let path = input["target_filepath"]
                    .as_str()
                    .or_else(|| input["path"].as_str())
                    .or_else(|| input["file_path"].as_str())
                    .or_else(|| input["file"].as_str())
                    .ok_or_else(|| {
                        SofosError::ToolExecution(format!(
                            "Missing 'target_filepath' parameter. Got keys: {:?}. \
                             Please retry with the 'target_filepath' parameter set to the file path.",
                            input
                                .as_object()
                                .map(|o| o.keys().collect::<Vec<_>>())
                                .unwrap_or_default()
                        ))
                    })?;
                let instruction = input["instructions"]
                    .as_str()
                    .or_else(|| input["instruction"].as_str())
                    .ok_or_else(|| {
                        SofosError::ToolExecution("Missing 'instructions' parameter".to_string())
                    })?;
                let code_edit = input["code_edit"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'code_edit' parameter".to_string())
                })?;

                // Guard against truncation markers from conversation history compaction
                if code_edit.contains("...[truncated") {
                    return Err(SofosError::ToolExecution(format!(
                        "code_edit contains a truncation marker '...[truncated'. This is not real code. \
                         Use read_file to get the actual current content of '{}' before editing.",
                        path
                    )));
                }

                let resolved = self.resolve_existing(path).map_err(|_| {
                    SofosError::ToolExecution(format!(
                        "File not found: '{}'. The file must exist for morph_edit_file.",
                        path
                    ))
                })?;

                // External paths require BOTH Read (we send the file to
                // Morph as context) and Write (we write the merged
                // result back). Same rationale as `edit_file`.
                if !resolved.is_inside_workspace {
                    self.check_read_access(
                        path,
                        &resolved.canonical,
                        &resolved.canonical_str,
                        resolved.is_inside_workspace,
                    )?;
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                let original_code = if resolved.is_inside_workspace {
                    self.fs_tool.read_file(path)?
                } else {
                    self.fs_tool
                        .read_file_with_outside_access(&resolved.canonical_str)?
                };

                // Any Morph failure (timeout, transport, 4xx, 5xx) falls back to
                // a prompt-level `edit_file` hint rather than propagating and
                // stalling the tool loop.
                let morph_timeout = Duration::from_secs(600);
                let merged_code = match tokio::time::timeout(
                    morph_timeout,
                    morph.apply_edit(instruction, &original_code, code_edit),
                )
                .await
                {
                    Ok(Ok(code)) => code,
                    Err(_elapsed) => {
                        eprintln!(
                            "  {} Morph API timed out after {}s, use edit_file instead",
                            "âš ".bright_yellow(),
                            morph_timeout.as_secs()
                        );
                        return Ok(ToolExecutionResult::Text(format!(
                            "morph_edit_file timed out after {}s. The file '{}' was NOT modified. \
                             Please use read_file to get the current file content, then use edit_file \
                             with exact old_string/new_string to make this change.",
                            morph_timeout.as_secs(),
                            path
                        )));
                    }
                    Ok(Err(e)) => {
                        // Match only variants Morph produces; propagate anything
                        // else (Interrupted, Io, etc.) so it isn't silently masked.
                        let msg = match e {
                            SofosError::Api(m) | SofosError::NetworkError(m) => m,
                            SofosError::Http(err) => err.to_string(),
                            other => return Err(other),
                        };
                        eprintln!(
                            "  {} Morph API failed ({}), use edit_file instead",
                            "âš ".bright_yellow(),
                            msg
                        );
                        return Ok(ToolExecutionResult::Text(format!(
                            "morph_edit_file failed ({}). The file '{}' was NOT modified. \
                             Please use read_file to get the current file content, then use edit_file \
                             with exact old_string/new_string to make this change.",
                            msg, path
                        )));
                    }
                };

                // Sanity-check the Morph output before committing it to
                // disk. Morph has occasionally returned a valid-JSON
                // response whose `content` string was silently truncated
                // (the model stopped short without raising `finish_reason
                // = length`), which then got written as a corrupted file.
                // Reject the result instead — the caller still has the
                // original on disk and can retry with `edit_file`.
                if let Err(reason) =
                    morph_validate::validate_morph_output(&original_code, &merged_code)
                {
                    eprintln!(
                        "  {} Morph output rejected ({}), use edit_file instead",
                        "âš ".bright_yellow(),
                        reason
                    );
                    return Ok(ToolExecutionResult::Text(format!(
                        "morph_edit_file rejected Morph's response ({}). The file '{}' was NOT modified. \
                         Please use read_file to get the current file content, then use edit_file \
                         with exact old_string/new_string to make this change.",
                        reason, path
                    )));
                }

                if resolved.is_inside_workspace {
                    self.fs_tool.write_file(path, &merged_code)?;
                } else {
                    self.fs_tool
                        .write_file_with_outside_access(&resolved.canonical_str, &merged_code)?;
                }

                // Generate diff for display
                let diff_output = diff::generate_compact_diff(&original_code, &merged_code, path);

                let body = format!(
                    "Successfully applied Morph edit to '{}'\n\nChanges:\n{}",
                    path, diff_output
                );
                Ok(truncate_for_context(
                    &body,
                    MAX_DIFF_TOKENS,
                    TruncationKind::DiffOutput,
                ))
            }
            ToolName::DeleteFile => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                // Resolve before prompting so we can surface "file not
                // found" without first asking for confirmation, and so
                // the Write-access check on external paths happens
                // BEFORE the user types y/n (consistent with
                // `write_file` / `edit_file`).
                let resolved = self.resolve_existing(path)?;

                if !resolved.is_inside_workspace {
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                let confirmed = confirm_destructive(&format!("Delete file '{}'?", path))?;

                if !confirmed {
                    return Ok(ToolExecutionResult::Text(format!(
                        "File deletion cancelled by user. The file '{}' was not deleted.",
                        path
                    )));
                }

                if resolved.is_inside_workspace {
                    self.fs_tool.delete_file(path)?;
                } else {
                    self.fs_tool
                        .delete_file_with_outside_access(&resolved.canonical_str)?;
                }
                Ok(format!("Successfully deleted file '{}'", path))
            }
            ToolName::DeleteDirectory => {
                let path = input["path"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'path' parameter".to_string())
                })?;

                let resolved = self.resolve_existing(path)?;

                if !resolved.is_inside_workspace {
                    self.check_write_access(path, &resolved.canonical_str, &resolved.canonical)?;
                }

                let confirmed = confirm_destructive(&format!(
                    "Delete directory '{}' and all its contents?",
                    path
                ))?;

                if !confirmed {
                    return Ok(ToolExecutionResult::Text(format!(
                        "Directory deletion cancelled by user. The directory '{}' and its contents were not deleted. What would you like to do instead?",
                        path
                    )));
                }

                if resolved.is_inside_workspace {
                    self.fs_tool.delete_directory(path)?;
                } else {
                    self.fs_tool
                        .delete_directory_with_outside_access(&resolved.canonical_str)?;
                }
                Ok(format!("Successfully deleted directory '{}'", path))
            }
            ToolName::MoveFile => {
                let source = input["source"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'source' parameter".to_string())
                })?;
                let destination = input["destination"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'destination' parameter".to_string())
                })?;

                // Moving a file removes it from its source location, so
                // external sources need a Write grant (not just Read).
                // External destinations need Write as usual.
                let src_resolved = self.resolve_existing(source)?;
                let dst_resolved = self.resolve_for_write(destination)?;

                if !src_resolved.is_inside_workspace {
                    self.check_write_access(
                        source,
                        &src_resolved.canonical_str,
                        &src_resolved.canonical,
                    )?;
                }
                if !dst_resolved.is_inside_workspace {
                    self.check_write_access(
                        destination,
                        &dst_resolved.canonical_str,
                        &dst_resolved.canonical,
                    )?;
                }

                move_between(
                    source,
                    destination,
                    &src_resolved,
                    &dst_resolved,
                    &self.fs_tool,
                )?;
                Ok(format!(
                    "Successfully moved '{}' to '{}'",
                    source, destination
                ))
            }
            ToolName::CopyFile => {
                let source = input["source"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'source' parameter".to_string())
                })?;
                let destination = input["destination"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'destination' parameter".to_string())
                })?;

                // Copy leaves the source untouched, so external sources
                // only need a Read grant. External destinations still
                // need Write.
                let src_resolved = self.resolve_existing(source)?;
                let dst_resolved = self.resolve_for_write(destination)?;

                if !src_resolved.is_inside_workspace {
                    self.check_read_access(
                        source,
                        &src_resolved.canonical,
                        &src_resolved.canonical_str,
                        src_resolved.is_inside_workspace,
                    )?;
                }
                if !dst_resolved.is_inside_workspace {
                    self.check_write_access(
                        destination,
                        &dst_resolved.canonical_str,
                        &dst_resolved.canonical,
                    )?;
                }

                copy_between(
                    source,
                    destination,
                    &src_resolved,
                    &dst_resolved,
                    &self.fs_tool,
                )?;
                Ok(format!(
                    "Successfully copied '{}' to '{}'",
                    source, destination
                ))
            }
            ToolName::ExecuteBash => {
                let command = input["command"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'command' parameter".to_string())
                })?;

                let result = self.bash_executor.execute(command)?;
                Ok(result)
            }
            ToolName::WebFetch => {
                use futures::StreamExt;

                let url = input["url"].as_str().ok_or_else(|| {
                    SofosError::ToolExecution("Missing 'url' parameter".to_string())
                })?;

                if !url.starts_with("http://") && !url.starts_with("https://") {
                    return Err(SofosError::ToolExecution(
                        "URL must start with http:// or https://".to_string(),
                    ));
                }

                let client = reqwest::Client::builder()
                    .timeout(std::time::Duration::from_secs(30))
                    .build()
                    .map_err(|e| SofosError::ToolExecution(format!("HTTP client error: {}", e)))?;

                let response = client
                    .get(url)
                    .header("User-Agent", SOFOS_USER_AGENT)
                    .send()
                    .await
                    .map_err(|e| SofosError::ToolExecution(format!("Fetch failed: {}", e)))?;

                let status = response.status();
                if !status.is_success() {
                    return Err(SofosError::ToolExecution(format!(
                        "HTTP {} for {}",
                        status, url
                    )));
                }

                // Reject the request before downloading anything if the
                // server already announces an oversized body. The
                // streaming cap below catches the unreported case too.
                if let Some(announced) = response.content_length() {
                    if announced > MAX_WEB_FETCH_BODY_BYTES as u64 {
                        return Err(SofosError::ToolExecution(format!(
                            "Response from {} announces {} bytes, which exceeds the {} MB web_fetch cap; aborted before downloading.",
                            url,
                            announced,
                            MAX_WEB_FETCH_BODY_BYTES / (1024 * 1024)
                        )));
                    }
                }

                // Stream the body chunk-by-chunk and abort as soon as the
                // running total crosses the cap. Reading through
                // `response.text()` would buffer the whole body into
                // RAM first, so a pathological URL serving gigabytes
                // could OOM the process even though the trailing
                // truncation below would have shown only the first
                // ~64 KB of characters anyway.
                let mut stream = response.bytes_stream();
                let mut raw: Vec<u8> = Vec::new();
                while let Some(chunk) = stream.next().await {
                    let chunk = chunk.map_err(|e| {
                        SofosError::ToolExecution(format!("Read body failed: {}", e))
                    })?;
                    if raw.len().saturating_add(chunk.len()) > MAX_WEB_FETCH_BODY_BYTES {
                        return Err(SofosError::ToolExecution(format!(
                            "Response from {} exceeded the {} MB web_fetch cap mid-stream; aborted.",
                            url,
                            MAX_WEB_FETCH_BODY_BYTES / (1024 * 1024)
                        )));
                    }
                    raw.extend_from_slice(&chunk);
                }
                // The cap protects RAM; the downstream `html_to_text` +
                // truncation handles the eventual model-visible size.
                // Non-UTF-8 charsets fall through to lossy decoding,
                // which matches what the post-fetch `html_to_text`
                // pipeline expects.
                let body = String::from_utf8_lossy(&raw).into_owned();

                let text = crate::tools::utils::html_to_text(&body);

                let max_bytes = 64_000;
                let truncated = if text.len() > max_bytes {
                    let end = crate::api::utils::truncate_at_char_boundary(&text, max_bytes);
                    format!(
                        "{}\n\n[TRUNCATED: showing first ~{} chars of {}]",
                        &text[..end],
                        max_bytes,
                        text.len()
                    )
                } else {
                    text
                };

                Ok(format!("Content from {}:\n\n{}", url, truncated))
            }
            ToolName::WebSearch => Err(SofosError::ToolExecution(
                "web_search is handled server-side by the API and should not be executed locally"
                    .to_string(),
            )),
        };

        Ok(ToolExecutionResult::Text(text_result?))
    }
}