4ab879e461
Expande el paquete tools/file/ con 4 operaciones nuevas para que los agentes puedan interactuar con carpetas de trabajo (workspaces, outputs). Cambios: - Extraer validatePath() y resolveReal() a validate.go para reutilizarlos - Agregar validateWritePath() que verifica ReadOnly == false - write_file: crea/sobreescribe archivos, crea dirs padre, limite 1MB - list_directory: lista archivos con metadata, modo recursivo, limite 500 entries - append_file: agrega contenido al final, crea si no existe, limite 10MB total - delete_file: borra solo archivos (nunca directorios), previene rm -rf accidental - Registrar las 4 tools nuevas en runtime.go condicionalmente: - list_directory: siempre (no requiere escritura) - write/append/delete: solo si ReadOnly == false Seguridad: todas las tools reutilizan validatePath() con deny-by-default, resolucion de symlinks y proteccion contra path traversal.
55 lines
1.4 KiB
Go
55 lines
1.4 KiB
Go
package file
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"github.com/enmanuel/agents/internal/config"
|
|
"github.com/enmanuel/agents/tools"
|
|
)
|
|
|
|
// NewReadFile creates a read_file tool that reads local files.
|
|
// Deny-by-default: if AllowedPaths is empty, all reads are rejected.
|
|
// Resolves symlinks and normalizes paths to prevent traversal attacks.
|
|
func NewReadFile(cfg config.FileOpsCfg) tools.Tool {
|
|
return tools.Tool{
|
|
Def: tools.Def{
|
|
Name: "read_file",
|
|
Description: "Read the contents of a local file.",
|
|
Parameters: []tools.Param{
|
|
{Name: "path", Type: "string", Description: "Absolute path to the file to read", Required: true},
|
|
},
|
|
},
|
|
Exec: func(ctx context.Context, args map[string]any) tools.Result {
|
|
path := tools.GetString(args, "path")
|
|
if path == "" {
|
|
return tools.Result{Err: fmt.Errorf("read_file: path is required")}
|
|
}
|
|
|
|
absPath, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return tools.Result{Err: fmt.Errorf("read_file: %w", err)}
|
|
}
|
|
|
|
if err := validatePath(absPath, cfg.AllowedPaths); err != nil {
|
|
return tools.Result{Err: err}
|
|
}
|
|
|
|
data, err := os.ReadFile(absPath)
|
|
if err != nil {
|
|
return tools.Result{Err: fmt.Errorf("read_file: %w", err)}
|
|
}
|
|
|
|
// Limit output to 64 KB
|
|
content := string(data)
|
|
if len(content) > 64*1024 {
|
|
content = content[:64*1024] + "\n... (truncated)"
|
|
}
|
|
|
|
return tools.Result{Output: content}
|
|
},
|
|
}
|
|
}
|