kernex-providers 0.3.0

AI backend providers for Kernex (Claude Code, Anthropic, OpenAI, Ollama, OpenRouter, Gemini, MCP)
Documentation
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
//! Shared tool executor for HTTP-based providers.
//!
//! Provides 4 built-in tools (Bash, Read, Write, Edit) with sandbox enforcement,
//! plus MCP server tool routing. Used by all agentic loops.

use crate::mcp_client::McpClient;
use kernex_core::context::{McpServer, Toolbox};
use kernex_core::message::{CompletionMeta, Response};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tracing::{debug, warn};

/// Maximum characters for bash tool output before truncation.
const MAX_BASH_OUTPUT: usize = 30_000;
/// Maximum characters for read tool output before truncation.
const MAX_READ_OUTPUT: usize = 50_000;
/// Default bash command timeout in seconds.
const BASH_TIMEOUT_SECS: u64 = 120;
/// Default toolbox script timeout in seconds.
const TOOLBOX_TIMEOUT_SECS: u64 = 120;

/// A tool definition in provider-agnostic format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDef {
    /// Tool name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// JSON Schema for parameters.
    pub parameters: Value,
}

/// Result of executing a tool.
#[derive(Debug, Clone)]
pub struct ToolResult {
    /// Text output from the tool.
    pub content: String,
    /// Whether the tool call failed.
    pub is_error: bool,
}

/// Executes built-in tools, script-based toolboxes, and MCP tool calls.
pub struct ToolExecutor {
    workspace_path: PathBuf,
    data_dir: PathBuf,
    config_path: Option<PathBuf>,
    mcp_clients: HashMap<String, McpClient>,
    mcp_tool_map: HashMap<String, String>,
    toolboxes: HashMap<String, Toolbox>,
}

impl ToolExecutor {
    /// Create a new tool executor.
    ///
    /// `workspace_path` is the working directory.
    /// `data_dir` is derived as the parent of `workspace_path`.
    pub fn new(workspace_path: PathBuf) -> Self {
        // data_dir = parent of workspace
        let data_dir = workspace_path
            .parent()
            .unwrap_or(&workspace_path)
            .to_path_buf();
        Self {
            workspace_path,
            data_dir,
            config_path: None,
            mcp_clients: HashMap::new(),
            mcp_tool_map: HashMap::new(),
            toolboxes: HashMap::new(),
        }
    }

    /// Set the config file path for read protection.
    ///
    /// When set, the sandbox will block AI tool reads to this path,
    /// protecting API keys and secrets even when config lives outside `data_dir`.
    /// Standard `{data_dir}/config.toml` is always protected regardless.
    #[allow(dead_code)]
    pub fn with_config_path(mut self, config_path: PathBuf) -> Self {
        self.config_path = Some(config_path);
        self
    }

    /// Register script-based toolbox tools.
    pub fn register_toolboxes(&mut self, toolboxes: &[Toolbox]) {
        for tb in toolboxes {
            debug!("toolbox: registered '{}'", tb.name);
            self.toolboxes.insert(tb.name.clone(), tb.clone());
        }
    }

    /// Connect to MCP servers and discover their tools.
    pub async fn connect_mcp_servers(&mut self, servers: &[McpServer]) {
        for server in servers {
            match McpClient::connect(&server.name, &server.command, &server.args, &server.env).await
            {
                Ok(client) => {
                    // Map each tool name to this server.
                    for tool in &client.tools {
                        self.mcp_tool_map
                            .insert(tool.name.clone(), server.name.clone());
                    }
                    self.mcp_clients.insert(server.name.clone(), client);
                }
                Err(e) => {
                    warn!("mcp: failed to connect to '{}': {e}", server.name);
                }
            }
        }
    }

    /// Return all available tool definitions (built-in + toolbox + MCP).
    pub fn all_tool_defs(&self) -> Vec<ToolDef> {
        let mut defs = builtin_tool_defs();

        // Add toolbox tools.
        for tb in self.toolboxes.values() {
            defs.push(ToolDef {
                name: tb.name.clone(),
                description: tb.description.clone(),
                parameters: tb.parameters.clone(),
            });
        }

        // Add MCP tools.
        for client in self.mcp_clients.values() {
            for mcp_tool in &client.tools {
                defs.push(ToolDef {
                    name: mcp_tool.name.clone(),
                    description: mcp_tool.description.clone(),
                    parameters: mcp_tool.input_schema.clone(),
                });
            }
        }

        defs
    }

    /// Execute a tool call by name, routing to built-in or MCP.
    pub async fn execute(&mut self, tool_name: &str, args: &Value) -> ToolResult {
        match tool_name.to_lowercase().as_str() {
            "bash" => self.exec_bash(args).await,
            "read" => self.exec_read(args).await,
            "write" => self.exec_write(args).await,
            "edit" => self.exec_edit(args).await,
            _ => {
                // Try toolbox routing.
                if let Some(tb) = self.toolboxes.get(tool_name).cloned() {
                    return self.exec_toolbox(&tb, args).await;
                }

                // Try MCP routing.
                if let Some(server_name) = self.mcp_tool_map.get(tool_name).cloned() {
                    if let Some(client) = self.mcp_clients.get_mut(&server_name) {
                        match client.call_tool(tool_name, args).await {
                            Ok(r) => ToolResult {
                                content: r.content,
                                is_error: r.is_error,
                            },
                            Err(e) => ToolResult {
                                content: format!("MCP error: {e}"),
                                is_error: true,
                            },
                        }
                    } else {
                        ToolResult {
                            content: format!("MCP server '{server_name}' not connected"),
                            is_error: true,
                        }
                    }
                } else {
                    ToolResult {
                        content: format!("Unknown tool: {tool_name}"),
                        is_error: true,
                    }
                }
            }
        }
    }

    /// Shut down all MCP server connections.
    pub async fn shutdown_mcp(&mut self) {
        for (name, client) in self.mcp_clients.drain() {
            debug!("mcp: shutting down '{name}'");
            client.shutdown().await;
        }
        self.mcp_tool_map.clear();
    }

    /// Resolve a path string to a normalized absolute path.
    ///
    /// Relative paths are joined against `workspace_path` and then
    /// lexically normalized (removing `.` and `..` components) to
    /// prevent sandbox bypass via traversal (e.g., `../../data/memory.db`).
    fn resolve_path(&self, path_str: &str) -> PathBuf {
        let p = Path::new(path_str);
        let joined = if p.is_absolute() {
            p.to_path_buf()
        } else {
            self.workspace_path.join(p)
        };
        normalize_path(&joined)
    }

    // --- Built-in tool implementations ---

    async fn exec_bash(&self, args: &Value) -> ToolResult {
        let command = args.get("command").and_then(|v| v.as_str()).unwrap_or("");
        if command.is_empty() {
            return ToolResult {
                content: "Error: 'command' parameter is required".to_string(),
                is_error: true,
            };
        }

        debug!("tool/bash: {command}");

        let mut cmd = kernex_sandbox::protected_command("bash", &self.data_dir);
        cmd.arg("-c").arg(command);
        cmd.current_dir(&self.workspace_path);
        // Kill the child process when the handle is dropped (e.g. on timeout).
        cmd.kill_on_drop(true);

        // Capture output with timeout. kill_on_drop ensures no orphan processes.
        match tokio::time::timeout(
            std::time::Duration::from_secs(BASH_TIMEOUT_SECS),
            cmd.output(),
        )
        .await
        {
            Ok(Ok(output)) => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);
                let mut result = String::new();
                if !stdout.is_empty() {
                    result.push_str(&stdout);
                }
                if !stderr.is_empty() {
                    if !result.is_empty() {
                        result.push('\n');
                    }
                    result.push_str(&stderr);
                }
                if result.is_empty() {
                    result = format!("(exit code: {})", output.status.code().unwrap_or(-1));
                }
                let is_error = !output.status.success();
                ToolResult {
                    content: truncate_output(&result, MAX_BASH_OUTPUT),
                    is_error,
                }
            }
            Ok(Err(e)) => ToolResult {
                content: format!("Failed to execute command: {e}"),
                is_error: true,
            },
            Err(_) => ToolResult {
                content: format!("Command timed out after {BASH_TIMEOUT_SECS}s"),
                is_error: true,
            },
        }
    }

    async fn exec_read(&self, args: &Value) -> ToolResult {
        let path_str = args.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
        if path_str.is_empty() {
            return ToolResult {
                content: "Error: 'file_path' parameter is required".to_string(),
                is_error: true,
            };
        }

        // Resolve relative paths against workspace to prevent sandbox bypass.
        let path = self.resolve_path(path_str);
        let path = path.as_path();
        if kernex_sandbox::is_read_blocked(path, &self.data_dir, self.config_path.as_deref()) {
            return ToolResult {
                content: format!("Read denied: {} is a protected path", path.display()),
                is_error: true,
            };
        }

        debug!("tool/read: {}", path.display());

        match tokio::fs::read_to_string(path).await {
            Ok(content) => ToolResult {
                content: truncate_output(&content, MAX_READ_OUTPUT),
                is_error: false,
            },
            Err(e) => ToolResult {
                content: format!("Error reading {}: {e}", path.display()),
                is_error: true,
            },
        }
    }

    async fn exec_write(&self, args: &Value) -> ToolResult {
        let path_str = args.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
        let content = args.get("content").and_then(|v| v.as_str()).unwrap_or("");
        if path_str.is_empty() {
            return ToolResult {
                content: "Error: 'file_path' parameter is required".to_string(),
                is_error: true,
            };
        }

        // Resolve relative paths against workspace to prevent sandbox bypass.
        let path = self.resolve_path(path_str);
        let path = path.as_path();
        if kernex_sandbox::is_write_blocked(path, &self.data_dir) {
            return ToolResult {
                content: format!("Write denied: {} is a protected path", path.display(),),
                is_error: true,
            };
        }

        debug!("tool/write: {}", path.display());

        // Ensure parent directory exists.
        if let Some(parent) = path.parent() {
            if let Err(e) = tokio::fs::create_dir_all(parent).await {
                return ToolResult {
                    content: format!("Failed to create parent directory: {e}"),
                    is_error: true,
                };
            }
        }

        match tokio::fs::write(path, content).await {
            Ok(()) => ToolResult {
                content: format!("Wrote {} bytes to {}", content.len(), path.display()),
                is_error: false,
            },
            Err(e) => ToolResult {
                content: format!("Error writing {}: {e}", path.display()),
                is_error: true,
            },
        }
    }

    async fn exec_toolbox(&self, tb: &Toolbox, args: &Value) -> ToolResult {
        debug!("toolbox/{}: running", tb.name);

        let mut cmd = kernex_sandbox::protected_command(&tb.command, &self.data_dir);
        cmd.args(&tb.args);
        cmd.current_dir(&self.workspace_path);
        cmd.kill_on_drop(true);
        cmd.stdin(std::process::Stdio::piped());
        cmd.stdout(std::process::Stdio::piped());
        cmd.stderr(std::process::Stdio::piped());
        for (k, v) in &tb.env {
            cmd.env(k, v);
        }

        let mut child = match cmd.spawn() {
            Ok(c) => c,
            Err(e) => {
                return ToolResult {
                    content: format!("Failed to spawn toolbox '{}': {e}", tb.name),
                    is_error: true,
                };
            }
        };

        // Write arguments as JSON to stdin.
        if let Some(mut stdin) = child.stdin.take() {
            let json = serde_json::to_string(args).unwrap_or_default();
            let _ = tokio::io::AsyncWriteExt::write_all(&mut stdin, json.as_bytes()).await;
            // Drop stdin to signal EOF.
        }

        match tokio::time::timeout(
            std::time::Duration::from_secs(TOOLBOX_TIMEOUT_SECS),
            child.wait_with_output(),
        )
        .await
        {
            Ok(Ok(output)) => {
                let stdout = String::from_utf8_lossy(&output.stdout);
                let stderr = String::from_utf8_lossy(&output.stderr);
                let mut result = String::new();
                if !stdout.is_empty() {
                    result.push_str(&stdout);
                }
                if !stderr.is_empty() {
                    if !result.is_empty() {
                        result.push('\n');
                    }
                    result.push_str(&stderr);
                }
                if result.is_empty() {
                    result = format!("(exit code: {})", output.status.code().unwrap_or(-1));
                }
                ToolResult {
                    content: truncate_output(&result, MAX_BASH_OUTPUT),
                    is_error: !output.status.success(),
                }
            }
            Ok(Err(e)) => ToolResult {
                content: format!("Toolbox '{}' execution failed: {e}", tb.name),
                is_error: true,
            },
            Err(_) => ToolResult {
                content: format!(
                    "Toolbox '{}' timed out after {TOOLBOX_TIMEOUT_SECS}s",
                    tb.name
                ),
                is_error: true,
            },
        }
    }

    async fn exec_edit(&self, args: &Value) -> ToolResult {
        let path_str = args.get("file_path").and_then(|v| v.as_str()).unwrap_or("");
        let old_string = args
            .get("old_string")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let new_string = args
            .get("new_string")
            .and_then(|v| v.as_str())
            .unwrap_or("");

        if path_str.is_empty() {
            return ToolResult {
                content: "Error: 'file_path' parameter is required".to_string(),
                is_error: true,
            };
        }
        if old_string.is_empty() {
            return ToolResult {
                content: "Error: 'old_string' parameter is required".to_string(),
                is_error: true,
            };
        }

        // Resolve relative paths against workspace to prevent sandbox bypass.
        let path = self.resolve_path(path_str);
        let path = path.as_path();
        if kernex_sandbox::is_write_blocked(path, &self.data_dir) {
            return ToolResult {
                content: format!("Write denied: {} is a protected path", path.display(),),
                is_error: true,
            };
        }

        debug!("tool/edit: {}", path.display());

        let content = match tokio::fs::read_to_string(path).await {
            Ok(c) => c,
            Err(e) => {
                return ToolResult {
                    content: format!("Error reading {}: {e}", path.display()),
                    is_error: true,
                }
            }
        };

        let count = content.matches(old_string).count();
        if count == 0 {
            return ToolResult {
                content: "Error: old_string not found in file".to_string(),
                is_error: true,
            };
        }

        let new_content = content.replacen(old_string, new_string, 1);
        match tokio::fs::write(path, &new_content).await {
            Ok(()) => ToolResult {
                content: format!(
                    "Edited {} ({count} occurrence(s) of pattern, replaced first)",
                    path.display()
                ),
                is_error: false,
            },
            Err(e) => ToolResult {
                content: format!("Error writing {}: {e}", path.display()),
                is_error: true,
            },
        }
    }
}

/// Lexically normalize a path by resolving `.` and `..` components.
///
/// Unlike `fs::canonicalize`, this works on non-existent paths. Essential
/// for preventing sandbox bypass via `../../` traversal on paths that
/// don't exist on disk.
fn normalize_path(path: &Path) -> PathBuf {
    use std::path::Component;
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                normalized.pop();
            }
            Component::CurDir => {}
            other => normalized.push(other),
        }
    }
    normalized
}

/// Truncate output to at most `max_bytes` bytes at a valid UTF-8 char boundary,
/// appending a note if truncated.
fn truncate_output(s: &str, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        s.to_string()
    } else {
        let boundary = s.floor_char_boundary(max_bytes);
        let truncated = &s[..boundary];
        format!(
            "{truncated}\n\n... (output truncated: {} total bytes, showing first {boundary})",
            s.len()
        )
    }
}

/// Return the definitions of the 4 built-in tools.
pub fn builtin_tool_defs() -> Vec<ToolDef> {
    vec![
        ToolDef {
            name: "bash".to_string(),
            description: "Execute a bash command and return its output.".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "The bash command to execute"
                    }
                },
                "required": ["command"]
            }),
        },
        ToolDef {
            name: "read".to_string(),
            description: "Read the contents of a file.".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Absolute path to the file to read"
                    }
                },
                "required": ["file_path"]
            }),
        },
        ToolDef {
            name: "write".to_string(),
            description: "Write content to a file (creates or overwrites).".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Absolute path to the file to write"
                    },
                    "content": {
                        "type": "string",
                        "description": "The content to write"
                    }
                },
                "required": ["file_path", "content"]
            }),
        },
        ToolDef {
            name: "edit".to_string(),
            description:
                "Edit a file by replacing the first occurrence of old_string with new_string."
                    .to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file_path": {
                        "type": "string",
                        "description": "Absolute path to the file to edit"
                    },
                    "old_string": {
                        "type": "string",
                        "description": "The exact string to find and replace"
                    },
                    "new_string": {
                        "type": "string",
                        "description": "The replacement string"
                    }
                },
                "required": ["file_path", "old_string", "new_string"]
            }),
        },
    ]
}

// --- Shared provider utilities ---

/// Build the standard Response for agentic loop responses.
///
/// Used by all HTTP provider agentic loops (success path and max-turns path).
pub(crate) fn build_response(
    text: String,
    provider_name: &str,
    total_tokens: u64,
    elapsed_ms: u64,
    model: Option<String>,
) -> Response {
    Response {
        text,
        metadata: CompletionMeta {
            provider_used: provider_name.to_string(),
            tokens_used: if total_tokens > 0 {
                Some(total_tokens)
            } else {
                None
            },
            processing_time_ms: elapsed_ms,
            model,
            session_id: None,
        },
    }
}

/// Check whether tools are enabled for this request context.
pub(crate) fn tools_enabled(context: &kernex_core::context::Context) -> bool {
    context
        .allowed_tools
        .as_ref()
        .map(|t| !t.is_empty())
        .unwrap_or(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builtin_tool_defs_count() {
        let defs = builtin_tool_defs();
        assert_eq!(defs.len(), 4);
        let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
        assert!(names.contains(&"bash"));
        assert!(names.contains(&"read"));
        assert!(names.contains(&"write"));
        assert!(names.contains(&"edit"));
    }

    #[test]
    fn test_tool_def_serialization() {
        let defs = builtin_tool_defs();
        for def in &defs {
            let json = serde_json::to_value(def).unwrap();
            assert!(json.get("name").is_some());
            assert!(json.get("description").is_some());
            assert!(json.get("parameters").is_some());
        }
    }

    #[test]
    fn test_truncate_output_short() {
        let s = "hello world";
        assert_eq!(truncate_output(s, 100), "hello world");
    }

    #[test]
    fn test_truncate_output_exact() {
        let s = "abcde";
        assert_eq!(truncate_output(s, 5), "abcde");
    }

    #[test]
    fn test_truncate_output_long() {
        let s = "a".repeat(100);
        let result = truncate_output(&s, 50);
        assert!(result.starts_with(&"a".repeat(50)));
        assert!(result.contains("output truncated"));
        assert!(result.contains("100 total bytes"));
    }

    #[tokio::test]
    async fn test_exec_bash_empty_command() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let result = executor.exec_bash(&serde_json::json!({})).await;
        assert!(result.is_error);
        assert!(result.content.contains("required"));
    }

    #[tokio::test]
    async fn test_exec_bash_echo() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let result = executor
            .exec_bash(&serde_json::json!({"command": "echo hello"}))
            .await;
        assert!(!result.is_error);
        assert!(result.content.contains("hello"));
    }

    #[tokio::test]
    async fn test_exec_read_nonexistent() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let result = executor
            .exec_read(&serde_json::json!({"file_path": "/tmp/kernex_test_nonexistent_xyz"}))
            .await;
        assert!(result.is_error);
    }

    #[tokio::test]
    async fn test_exec_write_and_read() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let path = "/tmp/kernex_tool_test_write.txt";
        let write_result = executor
            .exec_write(&serde_json::json!({"file_path": path, "content": "test content"}))
            .await;
        assert!(!write_result.is_error);

        let read_result = executor
            .exec_read(&serde_json::json!({"file_path": path}))
            .await;
        assert!(!read_result.is_error);
        assert_eq!(read_result.content, "test content");

        // Cleanup.
        let _ = tokio::fs::remove_file(path).await;
    }

    #[tokio::test]
    async fn test_exec_edit() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let path = "/tmp/kernex_tool_test_edit.txt";
        tokio::fs::write(path, "hello world").await.unwrap();

        let result = executor
            .exec_edit(&serde_json::json!({
                "file_path": path,
                "old_string": "world",
                "new_string": "kernex"
            }))
            .await;
        assert!(!result.is_error);

        let content = tokio::fs::read_to_string(path).await.unwrap();
        assert_eq!(content, "hello kernex");

        let _ = tokio::fs::remove_file(path).await;
    }

    #[tokio::test]
    async fn test_exec_read_denied_protected_path() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let result = executor
            .exec_read(&serde_json::json!({"file_path": "/home/user/.kernex/data/memory.db"}))
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("denied"));
    }

    #[tokio::test]
    async fn test_exec_read_denied_config() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let result = executor
            .exec_read(&serde_json::json!({"file_path": "/home/user/.kernex/config.toml"}))
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("denied"));
    }

    #[tokio::test]
    async fn test_exec_write_denied_protected_path() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let result = executor
            .exec_write(&serde_json::json!({"file_path": "/home/user/.kernex/data/memory.db", "content": "x"}))
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("denied"));
    }

    #[test]
    fn test_tool_executor_mcp_tool_map_routing() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        assert!(executor.mcp_tool_map.is_empty());
        assert!(executor.mcp_clients.is_empty());
    }

    #[tokio::test]
    async fn test_execute_unknown_tool() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let result = executor
            .execute("nonexistent_tool", &serde_json::json!({}))
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("Unknown tool"));
    }

    #[test]
    fn test_register_toolboxes() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let toolboxes = vec![Toolbox {
            name: "lint".into(),
            description: "Run linter.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "bash".into(),
            args: vec!["lint.sh".into()],
            env: std::collections::HashMap::new(),
        }];
        executor.register_toolboxes(&toolboxes);
        assert!(executor.toolboxes.contains_key("lint"));
    }

    #[test]
    fn test_all_tool_defs_includes_toolboxes() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let toolboxes = vec![Toolbox {
            name: "lint".into(),
            description: "Run linter.".into(),
            parameters: serde_json::json!({"type": "object", "properties": {"file": {"type": "string"}}}),
            command: "bash".into(),
            args: vec!["lint.sh".into()],
            env: std::collections::HashMap::new(),
        }];
        executor.register_toolboxes(&toolboxes);
        let defs = executor.all_tool_defs();
        assert!(defs.iter().any(|d| d.name == "lint"));
        assert_eq!(defs.len(), 5); // 4 built-in + 1 toolbox
    }

    #[tokio::test]
    async fn test_exec_toolbox_echo() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let tb = Toolbox {
            name: "greet".into(),
            description: "Echo greeting.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "echo".into(),
            args: vec!["hello from toolbox".into()],
            env: std::collections::HashMap::new(),
        };
        executor.register_toolboxes(&[tb]);
        let result = executor.execute("greet", &serde_json::json!({})).await;
        assert!(!result.is_error);
        assert!(result.content.contains("hello from toolbox"));
    }

    #[tokio::test]
    async fn test_exec_toolbox_receives_stdin_json() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let tb = Toolbox {
            name: "cat-input".into(),
            description: "Cat stdin.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "cat".into(),
            args: Vec::new(),
            env: std::collections::HashMap::new(),
        };
        executor.register_toolboxes(&[tb]);
        let result = executor
            .execute("cat-input", &serde_json::json!({"file": "test.rs"}))
            .await;
        assert!(!result.is_error);
        assert!(result.content.contains("test.rs"));
    }

    #[tokio::test]
    async fn test_exec_toolbox_nonzero_exit() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let tb = Toolbox {
            name: "fail".into(),
            description: "Always fails.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "bash".into(),
            args: vec!["-c".into(), "echo error >&2; exit 1".into()],
            env: std::collections::HashMap::new(),
        };
        executor.register_toolboxes(&[tb]);
        let result = executor.execute("fail", &serde_json::json!({})).await;
        assert!(result.is_error);
        assert!(result.content.contains("error"));
    }

    #[tokio::test]
    async fn test_exec_toolbox_with_env() {
        let mut executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let mut env = std::collections::HashMap::new();
        env.insert("GREETING".into(), "hola".into());
        let tb = Toolbox {
            name: "env-test".into(),
            description: "Print env var.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "bash".into(),
            args: vec!["-c".into(), "echo $GREETING".into()],
            env,
        };
        executor.register_toolboxes(&[tb]);
        let result = executor.execute("env-test", &serde_json::json!({})).await;
        assert!(!result.is_error);
        assert!(result.content.contains("hola"));
    }

    #[tokio::test]
    async fn test_exec_toolbox_spawn_failure() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"));
        let tb = Toolbox {
            name: "bad".into(),
            description: "Bad command.".into(),
            parameters: serde_json::json!({"type": "object"}),
            command: "__nonexistent_cmd_xyz__".into(),
            args: Vec::new(),
            env: std::collections::HashMap::new(),
        };
        let result = executor.exec_toolbox(&tb, &serde_json::json!({})).await;
        assert!(result.is_error);
    }

    #[test]
    fn test_resolve_path_absolute() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let resolved = executor.resolve_path("/tmp/test.txt");
        assert_eq!(resolved, PathBuf::from("/tmp/test.txt"));
    }

    #[test]
    fn test_resolve_path_relative() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let resolved = executor.resolve_path("test.txt");
        assert_eq!(
            resolved,
            PathBuf::from("/home/user/.kernex/workspace/test.txt")
        );
    }

    #[test]
    fn test_resolve_path_traversal_normalized() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let resolved = executor.resolve_path("../data/memory.db");
        assert_eq!(resolved, PathBuf::from("/home/user/.kernex/data/memory.db"));

        let resolved2 = executor.resolve_path("../../data/memory.db");
        assert_eq!(resolved2, PathBuf::from("/home/user/data/memory.db"));
    }

    #[tokio::test]
    async fn test_exec_read_denied_relative_traversal() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let result = executor
            .exec_read(&serde_json::json!({"file_path": "../data/memory.db"}))
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("denied"));
    }

    #[tokio::test]
    async fn test_exec_write_denied_config_toml() {
        let executor = ToolExecutor::new(PathBuf::from("/home/user/.kernex/workspace"));
        let result = executor
            .exec_write(
                &serde_json::json!({"file_path": "/home/user/.kernex/config.toml", "content": "x"}),
            )
            .await;
        assert!(result.is_error);
        assert!(result.content.contains("denied"));
    }

    #[test]
    fn test_with_config_path() {
        let executor = ToolExecutor::new(PathBuf::from("/tmp"))
            .with_config_path(PathBuf::from("/opt/kernex/config.toml"));
        assert_eq!(
            executor.config_path,
            Some(PathBuf::from("/opt/kernex/config.toml"))
        );
    }

    #[test]
    fn test_truncate_output_multibyte_boundary() {
        let s = "\u{041f}\u{0440}\u{0438}\u{0432}\u{0435}\u{0442} \u{043c}\u{0438}\u{0440}!";
        let result = truncate_output(s, 5);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_truncate_output_emoji_boundary() {
        let s = "Hello \u{1f30d} World";
        let result = truncate_output(s, 8);
        assert!(!result.is_empty());
    }
}