Description
The FileSystem class provides methods for file operations within an AgentBay cloud environment session. These operations include managing folders and performing actions on files, such as reading, writing, editing, and searching.
Method | Description | Environment | ||||
Linux Computer Use | Windows Computer Use | Browser Use | Mobile Use | Code Space | ||
| Reads file content. Supports offset and length limits. Note Only supports UTF-8 encoded files. | Supported | Supported | Supported | Not supported | Supported |
| Writes a large file by block size. | Supported | Supported | Supported | Not supported | Supported |
| Reads a large file by block size. | Supported | Supported | Supported | Not supported | Supported |
| Reads multiple files at the same time. | Supported | Supported | Supported | Not supported | Supported |
| Creates or writes to a file. Supports overwrite and append modes. Note Only supports UTF-8 encoded files. | Supported | Supported | Supported | Not supported | Supported |
| Performs line-based file editing. | Supported | Supported | Supported | Not supported | Supported |
| Creates a folder. Supports nested creation. | Supported | Supported | Supported | Not supported | Supported |
| Lists the contents of a folder. | Supported | Supported | Supported | Not supported | Supported |
| Recursively searches for files and folders. | Supported | Supported | Supported | Not supported | Supported |
| Moves or renames a file or folder. | Supported | Supported | Supported | Not supported | Supported |
| Gets detailed metadata for a file or folder. | Supported | Supported | Supported | Not supported | Supported |
Methods
create_directory / createDirectory / CreateDirectory - Create a folder
Golang
func (fs *FileSystem) CreateDirectory(path string) (bool, error)Parameter:
path (string): The path of the folder to create.
Return values:
bool: Returnstrueif the folder is created successfully.error: Returns an error message if the folder creation fails.
Example:
// Create a folder
success, err := session.FileSystem.CreateDirectory("/tmp/test")
if err != nil {
log.Printf("Error creating folder: %v", err)
} else {
fmt.Printf("Folder created: %t\n", success)
}Python
create_directory(path: str) -> BoolResultParameter:
path (str): The path of the folder to create.
Return value:
BoolResult: A result object containing a Boolean success status (Trueindicates success), the request ID, and any error message.
The return value type was updated from a Boolean value to a structured BoolResult object to provide more detailed information in the response.
TypeScript
createDirectory(path: string): Promise<string>Parameter:
path (string): The path of the folder to create.
Return value:
Promise<string>: Returns the response text if the folder is created successfully.
Exception:
APIError: Throws an error if the folder creation fails.
EditFile - Edit a file
Golang
func (fs *FileSystem) EditFile(path string, edits []map[string]string, dryRun bool) (bool, error)Parameters:
path (string): The path of the file to edit.
edits ([]map[string]string): An array of edit operations, each containing
oldTextandnewText.dryRun (bool): If
true, previews the changes without applying them.
Return values:
bool: Returnstrueif the file is edited successfully.error: Returns an error message if the file editing fails.
Example:
// Edit the file
edits := []map[string]string{
{"oldText": "Hello", "newText": "Hi"},
}
success, err := session.FileSystem.EditFile("/tmp/test/example.txt", edits, false)
if err != nil {
log.Printf("Error editing file: %v", err)
} else {
fmt.Printf("File edited successfully: %t\n", success)
}Python
edit_file(path: str, edits: List[Dict[str, str]], dry_run: bool = False) -> BoolResultParameters:
path (str): The path of the file to edit.edits (List[Dict[str, str]]): A list of edit operations. Each operation containsoldTextandnewText.dry_run (bool, optional): Specifies whether to preview the changes without applying them. The default isFalse.
Return value:
BoolResult: A result object containing a Boolean value that is set toTrueon success, a request ID, and an error message if an error occurs.
TypeScript
editFile(
path: string,
edits: Array<{ oldText: string, newText: string }>,
dryRun?: boolean
): Promise<string>Parameters:
path (string): The path of the file to edit.
edits (Array<{ oldText: string, newText: string }>): An array of edit operations, each containing
oldTextandnewText.dryRun (boolean, optional): If
true, previews the changes without applying them. The default isfalse.
Return value:
Promise<string>: Returns the response text if the file is edited successfully.
Exception:
APIError: Throws an error if the file editing fails.
GetFileInfo - Get file information
Golang
func (fs *FileSystem) GetFileInfo(path string) (string, error)Parameter:
path (string): The path of the file or folder to query.
Return values:
string: The text information of the file or folder, such as size and permissions.error: Returns an error message if the information retrieval fails.
Example:
// Get file information
fileInfo, err := session.FileSystem.GetFileInfo("/tmp/test/example.txt")
if err != nil {
log.Printf("Error getting file info: %v", err)
} else {
fmt.Printf("File info: %s\n", fileInfo)
}Python
get_file_info(path: str) -> OperationResultParameter:
path (str): The path of the file or folder to query.
Return value:
OperationResult: A result object that contains file information such as size and modification time, the success status, the request ID, and an error message if the operation failed.
TypeScript
getFileInfo(path: string): Promise<string>Parameter:
path (string): The path of the file or folder to query.
Return value:
Promise<string>: Returns the text information of the file or folder, such as size and permissions.
Exception:
APIError: Throws an error if the information retrieval fails.
ListDirectory - List a folder
Golang
func (fs *FileSystem) ListDirectory(path string) (*DirectoryListResult, error)Parameter:
path (string): The path of the folder to list.
Return values:
*DirectoryListResult: A result object that contains folder entries and the request ID.error: Returns an error message if listing the folder fails.
DirectoryListResult struct:
type DirectoryListResult struct {
RequestID string // A unique request identifier for debugging.
Entries []*DirectoryEntry // An array of folder entries.
}
type DirectoryEntry struct {
Name string // The name of the file or folder.
IsDirectory bool // Specifies whether an entry is a folder.
}Example:
// List the folder
listResult, err := session.FileSystem.ListDirectory("/tmp/test")
if err != nil {
log.Printf("Error listing folder: %v", err)
} else {
for _, entry := range listResult.Entries {
entryType := "Folder"
if !entry.IsDirectory {
entryType = "File"
}
fmt.Printf("%s: %s\n", entryType, entry.Name)
}
}Python
list_directory(path: str) -> OperationResultParameter:
path (str): The path of the folder to list.
Return value:
OperationResult: A result object that contains a list of folder entries, such as file and subdirectory names, the success status, the request ID, and an error message if the operation failed.
TypeScript
listDirectory(path: string): Promise<any>Parameter:
path (string): The path of the folder to list.
Return value:
Promise<any>: Returns an array of folder entries if parsing is successful. Otherwise, returns the original text content.
Exception:
APIError: Throws an error if listing the folder fails.
MoveFile - Move a file
Golang
func (fs *FileSystem) MoveFile(source, destination string) (*FileDirectoryResult, error)Parameters:
source (string): The source file or folder path.
destination (string): The destination file or folder path.
Return values:
*FileDirectoryResult: A result object that contains the operation status and request ID.error: Returns an error message if the file move fails.
FileDirectoryResult struct:
type FileDirectoryResult struct {
RequestID string // A unique request identifier for debugging.
Success bool // Specifies whether the operation is successful.
}Python
move_file(source: str, destination: str) -> BoolResultParameters:
source (str): The source file or folder path.destination (str): The destination file or folder path.
Return value:
BoolResult: A result object that contains the operation status, a Boolean value (which isTrueon success), the request ID, and an error message (if any).
TypeScript
moveFile(source: string, destination: string): Promise<string>Parameters:
source (string): The source file or folder path.
destination (string): The destination file or folder path.
Return value:
Promise<string>: Returns the response text if the file is moved successfully.
Exception:
APIError: Throws an error if the file move fails.
ReadFile - Read a file
Golang
func (fs *FileSystem) ReadFile(path string, optionalParams ...int) (*FileReadResult, error)Parameters:
path (string): The path of the file to read.
optionalParams (int, optional): Optional parameters for offset and length.
Return values:
*FileReadResult: A result object that contains the file content and request ID.error: Returns an error message if the file read fails.
FileReadResult struct:
type FileReadResult struct {
RequestID string // A unique request identifier for debugging.
Content string // The file content.
}Example:
// Read the file
readResult, err := session.FileSystem.ReadFile("/etc/hosts")
if err != nil {
log.Printf("Error reading file: %v", err)
} else {
fmt.Printf("File content: %s\n", readResult.Content)
}Python
read_file(path: str, offset: int = 0, length: int = 0) -> OperationResultParameters:
path (str): The path of the file to read.offset (int, optional): The byte offset from which to start reading. The default is 0.length (int, optional): The number of bytes to read. If 0, reads to the end of the file. The default is 0.
Return value:
OperationResult: A result object that contains the file content as a string, the success status, the request ID, and an error message if the operation failed.
TypeScript
readFile(path: string, offset?: number, length?: number): Promise<string>Parameters:
path (string): The path of the file to read.
offset (number, optional): The byte offset from which to start reading. The default is
0.length (number, optional): The number of bytes to read. If
0, reads to the end of the file. The default is0.
Return value:
Promise<string>: Returns the file content.
Exception:
APIError: Throws an error if the file read fails.
ReadMultipleFiles - Read multiple files
Golang
func (fs *FileSystem) ReadMultipleFiles(paths []string) (string, error)Parameter:
paths ([]string): An array of file paths to read.
Return values:
string: A text mapping of file paths to their content.error: Returns an error message if the file read fails.
Python
read_multiple_files(paths: List[str]) -> OperationResultParameter:
paths (List[str]): A list of file paths to read.
Return value:
OperationResult: A result object that contains a dictionary mapping file paths to their content, the success status, the request ID, and an error message if the operation failed.
TypeScript
readMultipleFiles(paths: string[]): Promise<string>Parameter:
paths (string[]): An array of file paths to read.
Return value:
Promise<string>: Returns a text mapping of file paths to their content.
Exception:
APIError: Throws an error if the file read fails.
SearchFiles - Search for files
Golang
func (fs *FileSystem) SearchFiles(path, pattern string, excludePatterns []string) (*SearchFilesResult, error)Parameters:
path (string): The starting folder path for the search.
pattern (string): The matching pattern.
excludePatterns ([]string): An array of exclusion patterns.
Return values:
*SearchFilesResult: A result object that contains the search results and request ID.error: Returns an error message if the search fails.
SearchFilesResult struct:
type SearchFilesResult struct {
RequestID string // A unique request identifier for debugging.
Results []string // An array of search results.
}Python
search_files(path: str, pattern: str, exclude_patterns: Optional[List[str]] = None) -> OperationResultParameters:
path (str): The folder path to start the search from.pattern (str): The pattern to match, such as wildcard match.exclude_patterns (List[str], optional): A list of patterns to exclude. The default isNone.
Return value:
OperationResult: A result object that contains the search results (a list of matching file paths), the success status, the request ID, and an error message if the operation failed.
TypeScript
searchFiles(
path: string,
pattern: string,
excludePatterns?: string[]
): Promise<any[]>Parameters:
path (string): The starting folder path for the search.
pattern (string): The matching pattern.
excludePatterns (string[], optional): An array of exclusion patterns. The default is an empty array.
Return value:
Promise<any[]>: Returns an array of search results.
Exception:
APIError: Throws an error if the search fails.
WriteFile - Write to a file
Golang
func (fs *FileSystem) WriteFile(path, content string, mode string) (*FileWriteResult, error)Parameters:
path (string): The path of the file to write to.
content (string): The content to write.
mode (string): The mode, which can be
"overwrite"(default),"append", or"create_new".
Return values:
*FileWriteResult: A result object that contains the operation status and request ID.error: Returns an error message if the write operation fails.
FileWriteResult struct:
type FileWriteResult struct {
RequestID string // A unique request identifier for debugging.
Success bool // Specifies whether the file was written successfully.
}Example:
// Write to the file
writeResult, err := session.FileSystem.WriteFile("/tmp/test/example.txt", "Hello, world!", "overwrite")
if err != nil {
log.Printf("Error writing file: %v", err)
} else {
fmt.Printf("File written successfully: %t\n", writeResult.Success)
}Python
write_file(path: str, content: str, mode: str = "overwrite") -> boolParameters:
path (str): The path of the file to write to.content (str): The content to write.mode (str, optional): The write mode, which can be"overwrite"(default) or"append".
Return value:
bool: Indicates whether the file was written successfully.
Exception:
FileError: Throws an exception if the write operation fails.
TypeScript
writeFile(path: string, content: string, mode?: string): Promise<string>Parameters:
path (string): The path of the file to write to.
content (string): The content to write.
mode (string, optional): The mode, which can be
"overwrite"(default),"append", or"create_new".
Return value:
Promise<string>: Returns the response text if the file is written successfully.
Exception:
APIError: Throws an error if the write operation fails.
ReadLargeFile - Read a large file
Golang
func (fs *FileSystem) ReadLargeFile(path string, chunkSize int) (string, error)Parameters:
path (string): The path of the file to read.
chunkSize (int): The size of each data block in bytes.
Return values:
string: The full content of the file.error: Returns an error message if the file read fails.
Python
read_large_file_in_chunks(path: str, chunk_size: int) -> Generator[OperationResult, None, None]Parameters:
path (str): The path of the large file to read.chunk_size (int): The size of the block to read for each iteration, in bytes.
Return value:
Generator[OperationResult, None, None]: A generator that returns a result object containing the file block content for each iteration.
Purpose:
Works around the file size limitations of the underlying API by processing the file in chunks.
TypeScript
readLargeFile(path: string, chunkSize?: number): Promise<string>Parameters:
path (string): The path of the file to read.
chunkSize (number, optional): The size of each data block in bytes. The default is
60 KB.
Return value:
Promise<string>: Returns the full content of the file.
Exception:
APIError: Throws an error if the file read fails.
WriteLargeFile - Write to a large file
Golang
func (fs *FileSystem) WriteLargeFile(path, content string, chunkSize int) (bool, error)Parameters:
path (string): The path of the file to write to.
content (string): The content to write.
chunkSize (int): The size of each data block in bytes.
Return values:
bool: Returnstrueif the file is written successfully.error: Returns an error message if the write operation fails.
Basic file operation example:
package main
import (
"fmt"
"log"
)
func main() {
// Create a session
agentBay := agentbay.NewAgentBay("your-api-key")
sessionResult, err := agentBay.Create(nil)
if err != nil {
log.Fatal(err)
}
session := sessionResult.Session
// Read the file
readResult, err := session.FileSystem.ReadFile("/etc/hosts")
if err != nil {
log.Printf("Error reading file: %v", err)
} else {
fmt.Printf("File content: %s\n", readResult.Content)
}
// Create a folder
success, err := session.FileSystem.CreateDirectory("/tmp/test")
if err != nil {
log.Printf("Error creating folder: %v", err)
} else {
fmt.Printf("Folder created: %t\n", success)
}
// Write to the file
writeResult, err := session.FileSystem.WriteFile("/tmp/test/example.txt", "Hello, world!", "overwrite")
if err != nil {
log.Printf("Error writing file: %v", err)
} else {
fmt.Printf("File written successfully: %t\n", writeResult.Success)
}
// Edit the file
edits := []map[string]string{
{"oldText": "Hello", "newText": "Hi"},
}
success, err = session.FileSystem.EditFile("/tmp/test/example.txt", edits, false)
if err != nil {
log.Printf("Error editing file: %v", err)
} else {
fmt.Printf("File edited successfully: %t\n", success)
}
// Get file information
fileInfo, err := session.FileSystem.GetFileInfo("/tmp/test/example.txt")
if err != nil {
log.Printf("Error getting file info: %v", err)
} else {
fmt.Printf("File info: %s\n", fileInfo)
}
// List the folder
listResult, err := session.FileSystem.ListDirectory("/tmp/test")
if err != nil {
log.Printf("Error listing folder: %v", err)
} else {
for _, entry := range listResult.Entries {
entryType := "Folder"
if !entry.IsDirectory {
entryType = "File"
}
fmt.Printf("%s: %s\n", entryType, entry.Name)
}
}
}TypeScript
writeLargeFile(path: string, content: string, chunkSize?: number): Promise<boolean>Parameters:
path (string): The path of the file to write to.
content (string): The content to write.
chunkSize (number, optional): The size of each data block in bytes. The default is
60 KB.
Return value:
Promise<boolean>: Returnstrueif the file is written successfully.
Exception:
APIError: Throws an error if the write operation fails.