waifu/workspace.py
2026-05-19 22:13:49 -06:00

208 lines
7.1 KiB
Python

"""Operaciones de workspace restringidas al directorio base del usuario."""
import os
import re
import subprocess
from pathlib import Path
MAX_FILE_BYTES = 512_000
MAX_CMD_OUTPUT = 8_000
CMD_TIMEOUT = 45
_BLOCKED_CMD = re.compile(
r"(?i)"
r"(\bsudo\b|\bsu\b|\bchmod\b|\bchown\b|\bmkfs\b|\bdd\s+if=|\bshutdown\b|\breboot\b|"
r">\s*/dev/|/\.\./|\|\s*bash|\|\s*sh\b|curl\s+.*\|\s*(ba)?sh|wget\s+.*\|\s*(ba)?sh|"
r"rm\s+-rf\s+/|rm\s+-rf\s+~|:\(\)\s*\{|>\s*/etc/)"
)
def normalize_workspace(path: str) -> str:
p = Path(path).expanduser().resolve()
if not p.is_dir():
raise ValueError(f"No es un directorio válido: {path}")
return str(p)
def resolve_path(workspace: str, rel: str = ".") -> Path:
base = Path(workspace).resolve()
target = (base / rel).resolve()
if not str(target).startswith(str(base)):
raise ValueError("Ruta fuera del directorio base")
return target
def _clip(text: str, limit: int = MAX_CMD_OUTPUT) -> str:
if len(text) <= limit:
return text
return text[:limit] + f"\n… ({len(text) - limit} caracteres omitidos)"
def tool_list_directory(workspace: str, path: str = ".") -> str:
target = resolve_path(workspace, path or ".")
if not target.exists():
return f"Error: no existe '{path}'"
if not target.is_dir():
return f"Error: '{path}' no es un directorio"
entries = sorted(target.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower()))
lines = []
for e in entries[:200]:
kind = "dir" if e.is_dir() else "file"
size = e.stat().st_size if e.is_file() else 0
lines.append(f"{kind}\t{e.name}\t{size}")
if len(entries) > 200:
lines.append(f"… y {len(entries) - 200} entradas más")
return "\n".join(lines) or "(vacío)"
def tool_read_file(workspace: str, path: str) -> str:
target = resolve_path(workspace, path)
if not target.is_file():
return f"Error: '{path}' no es un archivo"
if target.stat().st_size > MAX_FILE_BYTES:
return f"Error: archivo demasiado grande (>{MAX_FILE_BYTES} bytes)"
try:
return target.read_text(encoding="utf-8")
except UnicodeDecodeError:
return "Error: no es texto UTF-8"
def tool_write_file(workspace: str, path: str, content: str) -> str:
target = resolve_path(workspace, path)
target.parent.mkdir(parents=True, exist_ok=True)
if len(content.encode("utf-8")) > MAX_FILE_BYTES:
return f"Error: contenido demasiado grande (>{MAX_FILE_BYTES} bytes)"
target.write_text(content, encoding="utf-8")
return f"OK: escrito {path} ({len(content)} caracteres)"
def tool_create_directory(workspace: str, path: str) -> str:
target = resolve_path(workspace, path)
target.mkdir(parents=True, exist_ok=True)
return f"OK: directorio creado {path}"
def tool_run_command(workspace: str, command: str) -> str:
cmd = (command or "").strip()
if not cmd:
return "Error: comando vacío"
if _BLOCKED_CMD.search(cmd):
return "Error: comando bloqueado por seguridad"
try:
proc = subprocess.run(
cmd,
shell=True,
cwd=workspace,
capture_output=True,
text=True,
timeout=CMD_TIMEOUT,
env={**os.environ, "LANG": "C.UTF-8"},
)
except subprocess.TimeoutExpired:
return f"Error: timeout ({CMD_TIMEOUT}s)"
out = (proc.stdout or "") + (proc.stderr or "")
status = f"exit_code={proc.returncode}"
if not out.strip():
return status
return status + "\n" + _clip(out)
def execute_tool(name: str, args: dict, workspace: str) -> str:
try:
if name == "list_directory":
return tool_list_directory(workspace, args.get("path", "."))
if name == "read_file":
return tool_read_file(workspace, args.get("path", ""))
if name == "write_file":
return tool_write_file(workspace, args.get("path", ""), args.get("content", ""))
if name == "create_directory":
return tool_create_directory(workspace, args.get("path", ""))
if name == "run_command":
return tool_run_command(workspace, args.get("command", ""))
return f"Error: herramienta desconocida '{name}'"
except Exception as e:
return f"Error: {e}"
TERMINAL_TOOLS = [
{
"type": "function",
"function": {
"name": "list_directory",
"description": "Lista archivos y carpetas en una ruta relativa al workspace.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Ruta relativa, por defecto '.'"},
},
},
},
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Lee un archivo de texto del workspace.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Ruta relativa al archivo"},
},
"required": ["path"],
},
},
},
{
"type": "function",
"function": {
"name": "write_file",
"description": "Crea o sobrescribe un archivo de texto en el workspace.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Ruta relativa del archivo"},
"content": {"type": "string", "description": "Contenido completo del archivo"},
},
"required": ["path", "content"],
},
},
},
{
"type": "function",
"function": {
"name": "create_directory",
"description": "Crea un directorio (y padres si hace falta) en el workspace.",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Ruta relativa del directorio"},
},
"required": ["path"],
},
},
},
{
"type": "function",
"function": {
"name": "run_command",
"description": "Ejecuta un comando shell en el workspace (python, npm, git, ls, etc.).",
"parameters": {
"type": "object",
"properties": {
"command": {"type": "string", "description": "Comando shell a ejecutar"},
},
"required": ["command"],
},
},
},
]
TERMINAL_PROMPT = """
MODO TERMINAL ACTIVO — Workspace: {workspace}
Puedes usar herramientas para listar, leer, escribir archivos, crear carpetas y ejecutar comandos.
SOLO opera dentro del workspace. Usa rutas relativas.
Para crear programas: escribe archivos con write_file y prueba con run_command (python, node, etc.).
Tras usar herramientas, resume al usuario qué hiciste en 2-3 oraciones con personalidad kawaii.
Sigue incluyendo etiquetas ElevenLabs en tu respuesta final al usuario.
"""