-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.py
More file actions
69 lines (62 loc) · 2.35 KB
/
Copy pathtools.py
File metadata and controls
69 lines (62 loc) · 2.35 KB
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
import subprocess
import os
from typing import List, Dict, Any
from security import validate_path
# --- Tool Implementations ---
def read_file(file_path: str) -> str:
"""Reads the content of a file."""
try:
safe_path = validate_path(file_path)
if not os.path.exists(safe_path):
return f"Error: File '{file_path}' does not exist."
with open(safe_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
return f"Error reading file: {str(e)}"
def write_file(file_path: str, content: str) -> str:
"""Writes content to a file. Overwrites if exists."""
try:
safe_path = validate_path(file_path)
# Note: Actual writing happens after confirmation in the execution layer,
# but for the tool definition, we assume permission is granted if it reaches here.
with open(safe_path, 'w', encoding='utf-8') as f:
f.write(content)
return f"Successfully wrote to '{file_path}'."
except Exception as e:
return f"Error writing file: {str(e)}"
def list_directory(directory: str = ".") -> str:
"""Lists files and folders in the given directory."""
try:
safe_path = validate_path(directory)
items = os.listdir(safe_path)
return "\n".join(items) if items else "(Empty directory)"
except Exception as e:
return f"Error listing directory: {str(e)}"
def run_shell_command(command: str) -> str:
"""Executes a shell command."""
# SECURITY: This is handled by the Executor, but the function exists for the LLM schema.
try:
# Capture stdout and stderr
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=os.getcwd()
)
output = result.stdout
if result.stderr:
output += f"\n[STDERR]\n{result.stderr}"
return output.strip()
except Exception as e:
return f"Error executing command: {str(e)}"
# --- Tool Registry for Gemini ---
# We map function names to the actual callables
TOOL_MAP = {
"read_file": read_file,
"write_file": write_file,
"list_directory": list_directory,
"run_shell_command": run_shell_command
}
# The tools list passed to the API configuration
TOOLS_SCHEMA = [read_file, write_file, list_directory, run_shell_command]