package builtin import ( "os" "path/filepath" "strings" "sync" ) const ( // maxReadBytes is the maximum file size the read tool will load into memory. maxReadBytes = 5 * 1024 * 1024 // 5MB // maxWriteBytes is the maximum content size the write tool will accept. maxWriteBytes = 5 * 1024 * 1024 // 5MB ) // resolvePath resolves a potentially relative path against the working directory. // It also strips a leading @ (some LLMs include this). func resolvePath(cwd, path string) string { path = strings.TrimPrefix(path, "@") if filepath.IsAbs(path) { return filepath.Clean(path) } return filepath.Clean(filepath.Join(cwd, path)) } // goModCacheDir returns the Go module cache root, or "". var goModCacheDir = sync.OnceValue(func() string { if v := os.Getenv("GOMODCACHE"); v != "" { return filepath.Clean(v) } if v := os.Getenv("GOPATH"); v != "" { // GOPATH may be a list; cmd/go uses the first entry. if first, _, _ := strings.Cut(v, string(os.PathListSeparator)); first != "" { return filepath.Join(filepath.Clean(first), "pkg", "mod") } } home, err := os.UserHomeDir() if err != nil { return "" } return filepath.Join(home, "go", "pkg", "mod") }) // Jail is the path policy one set of file tools runs under. It is a value // owned by its caller, so two providers in one process cannot disagree about // it. type Jail struct { // Root is the workspace directory. Relative paths resolve against it. Root string // Unrestricted lifts the jail: any absolute path is allowed. Unrestricted bool } // Confines reports whether target is within (or equal to) j.Root. It returns // false when target escapes via ../ or is an unrelated absolute path. func (j Jail) Confines(target string) bool { if j.Unrestricted || j.Root == "" { return true // no jail when unrestricted, or when no root is set } rootAbs, err := filepath.Abs(j.Root) if err != nil { return false } targetAbs, err := filepath.Abs(target) if err != nil { return false } rel, err := filepath.Rel(rootAbs, targetAbs) if err != nil { return false } return !strings.HasPrefix(rel, "..") && rel != ".." } // ReadConfines reports whether a read may touch target: the jail root or the // Go module cache. func (j Jail) ReadConfines(target string) bool { if j.Confines(target) { return true } cache := goModCacheDir() return cache != "" && Jail{Root: cache}.Confines(target) }