Spaces:
Paused
Paused
File size: 10,273 Bytes
ef271cc | 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 | """
agent_tools.py β Implementasi tools untuk Gemini coding agent.
Tools yang tersedia: read_file, write_file, edit_file, bash, glob, grep, ls.
Workspace bersifat per-thread agar setiap sesi user terisolasi.
"""
from __future__ import annotations
import os
import re
import subprocess
import threading
from pathlib import Path
MAX_FILE_SIZE = 200_000 # ~200KB batas baca file
MAX_OUTPUT = 20_000 # potong output bash jika terlalu panjang
# ββ Per-thread workspace βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
_local = threading.local()
def get_workspace() -> Path:
"""Kembalikan workspace root untuk thread saat ini."""
if hasattr(_local, "root"):
return _local.root
ws = os.environ.get("CLAW_WORKSPACE", "")
base = Path(ws) if ws else Path("/tmp/workspace")
base.mkdir(parents=True, exist_ok=True)
return base
def set_workspace(path: str | Path) -> Path:
"""Set workspace root untuk thread saat ini dan buat direktorinya."""
p = Path(path)
p.mkdir(parents=True, exist_ok=True)
_local.root = p
return p
# ββ helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _truncate(text: str, limit: int = MAX_OUTPUT) -> str:
if len(text) <= limit:
return text
half = limit // 2
return text[:half] + f"\n\n... [terpotong {len(text) - limit} karakter] ...\n\n" + text[-half:]
def _safe_path(raw: str) -> Path:
"""Pastikan path berada di dalam workspace."""
ws = get_workspace()
p = (ws / raw).resolve()
if not str(p).startswith(str(ws)):
raise PermissionError(f"Akses ditolak: path di luar workspace ({raw})")
return p
# ββ read_file βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def read_file(path: str, offset: int = 1, limit: int = 500) -> str:
try:
p = _safe_path(path)
if not p.exists():
return f"[Error] File tidak ditemukan: {path}"
if p.stat().st_size > MAX_FILE_SIZE:
return f"[Error] File terlalu besar (>{MAX_FILE_SIZE//1000}KB): {path}"
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
total = len(lines)
start = max(0, offset - 1)
end = min(total, start + limit)
selected = lines[start:end]
numbered = "\n".join(f"{start + i + 1:6}β{line}" for i, line in enumerate(selected))
note = f"[Baris {start+1}β{end} dari total {total} baris]"
return f"{note}\n{numbered}"
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal membaca file: {e}"
# ββ write_file ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def write_file(path: str, content: str) -> str:
try:
p = _safe_path(path)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
lines = content.count("\n") + 1
return f"[OK] File ditulis: {path} ({lines} baris)"
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal menulis file: {e}"
# ββ edit_file βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def edit_file(path: str, old_string: str, new_string: str) -> str:
try:
p = _safe_path(path)
if not p.exists():
return f"[Error] File tidak ditemukan: {path}"
original = p.read_text(encoding="utf-8")
count = original.count(old_string)
if count == 0:
return f"[Error] String tidak ditemukan dalam file:\n{old_string!r}"
if count > 1:
return f"[Error] String ditemukan {count} kali β harus unik agar edit aman."
updated = original.replace(old_string, new_string, 1)
p.write_text(updated, encoding="utf-8")
return f"[OK] Edit berhasil pada {path}"
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal mengedit file: {e}"
# ββ bash ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def bash(command: str, timeout: int = 30) -> str:
try:
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
cwd=str(get_workspace()),
)
out = result.stdout
err = result.stderr
combined = ""
if out:
combined += out
if err:
combined += ("\n[stderr]\n" + err) if out else err
if not combined:
combined = "(tidak ada output)"
combined = _truncate(combined)
if result.returncode != 0:
combined += f"\n[exit code: {result.returncode}]"
return combined
except subprocess.TimeoutExpired:
return f"[Error] Perintah melebihi batas waktu ({timeout} detik)"
except Exception as e:
return f"[Error] Gagal menjalankan perintah: {e}"
# ββ glob ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def glob(pattern: str, path: str = ".") -> str:
try:
base = _safe_path(path)
matches = sorted(base.glob(pattern))
if not matches:
return f"(tidak ada file yang cocok dengan pola: {pattern})"
ws = get_workspace()
lines = [str(m.relative_to(ws)) for m in matches[:200]]
result = "\n".join(lines)
if len(matches) > 200:
result += f"\n... dan {len(matches) - 200} file lainnya"
return result
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal melakukan glob: {e}"
# ββ grep ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def grep(pattern: str, path: str = ".", file_glob: str = "*", context_lines: int = 0) -> str:
try:
base = _safe_path(path)
ws = get_workspace()
regex = re.compile(pattern, re.IGNORECASE)
results: list[str] = []
for fp in sorted(base.rglob(file_glob)):
if not fp.is_file():
continue
if fp.stat().st_size > MAX_FILE_SIZE:
continue
try:
lines = fp.read_text(encoding="utf-8", errors="replace").splitlines()
except Exception:
continue
rel = str(fp.relative_to(ws))
for i, line in enumerate(lines):
if regex.search(line):
if context_lines:
start = max(0, i - context_lines)
end = min(len(lines), i + context_lines + 1)
block = "\n".join(
f" {rel}:{j+1}: {lines[j]}" for j in range(start, end)
)
results.append(block)
else:
results.append(f"{rel}:{i+1}: {line}")
if len(results) > 300:
break
if not results:
return f"(tidak ada hasil untuk: {pattern!r})"
return _truncate("\n".join(results))
except re.error as e:
return f"[Error] Regex tidak valid: {e}"
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal melakukan grep: {e}"
# ββ ls ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def ls(path: str = ".") -> str:
try:
p = _safe_path(path)
if not p.exists():
return f"[Error] Direktori tidak ditemukan: {path}"
if not p.is_dir():
return f"[Error] Bukan direktori: {path}"
entries = sorted(p.iterdir(), key=lambda x: (not x.is_dir(), x.name.lower()))
lines = []
for e in entries:
kind = "π" if e.is_dir() else "π"
size = ""
if e.is_file():
s = e.stat().st_size
size = f" ({s:,} B)" if s < 1024 else f" ({s//1024:,} KB)"
lines.append(f"{kind} {e.name}{size}")
return "\n".join(lines) if lines else "(direktori kosong)"
except PermissionError as e:
return f"[Error] {e}"
except Exception as e:
return f"[Error] Gagal listing direktori: {e}"
# ββ dispatcher ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
TOOL_REGISTRY: dict[str, callable] = {
"read_file": read_file,
"write_file": write_file,
"edit_file": edit_file,
"bash": bash,
"glob": glob,
"grep": grep,
"ls": ls,
}
def dispatch(tool_name: str, args: dict) -> str:
fn = TOOL_REGISTRY.get(tool_name)
if fn is None:
return f"[Error] Tool tidak dikenal: {tool_name}"
try:
return fn(**args)
except TypeError as e:
return f"[Error] Parameter salah untuk {tool_name}: {e}"
|