File Operations API

The File Operations API provides comprehensive file system access for reading, writing, searching, and manipulating files within the AIO Sandbox environment.

Base URL

All file operations are available at:

http://localhost:8080/v1/file/

API Endpoints

Read File

Read file contents with optional line range selection.

Endpoint: POST /v1/file/read

Request Body:

{
  "file": "/path/to/file",
  "start_line": 0,
  "end_line": 100,
  "sudo": false
}

Parameters:

Field Type Required Description
file string Yes Absolute file path
start_line integer No Starting line (0-indexed)
end_line integer No Ending line (exclusive)
sudo boolean No Use sudo privileges

Response:

{
  "success": true,
  "message": "File read successfully",
  "data": {
    "content": "File contents here...",
    "line_count": 100,
    "file": "/path/to/file"
  }
}

Example:

curl -X POST http://localhost:8080/v1/file/read \
  -H "Content-Type: application/json" \
  -d '{
    "file": "/etc/passwd",
    "start_line": 0,
    "end_line": 5
  }'

Write File

Write content to a file with various options.

Endpoint: POST /v1/file/write

Request Body:

{
  "file": "/path/to/file",
  "content": "Content to write",
  "append": false,
  "leading_newline": false,
  "trailing_newline": true,
  "sudo": false
}

Parameters:

Field Type Required Description
file string Yes Absolute file path
content string Yes Content to write
append boolean No Append to existing file
leading_newline boolean No Add newline before content
trailing_newline boolean No Add newline after content
sudo boolean No Use sudo privileges

Response:

{
  "success": true,
  "message": "File written successfully",
  "data": {
    "file": "/path/to/file",
    "bytes_written": 123
  }
}

Example:

curl -X POST http://localhost:8080/v1/file/write \
  -H "Content-Type: application/json" \
  -d '{
    "file": "/tmp/example.txt",
    "content": "Hello AIO Sandbox!",
    "trailing_newline": true
  }'

Replace Text

Replace occurrences of text within a file.

Endpoint: POST /v1/file/replace

Request Body:

{
  "file": "/path/to/file",
  "old_str": "text to replace",
  "new_str": "replacement text",
  "sudo": false
}

Parameters:

Field Type Required Description
file string Yes Absolute file path
old_str string Yes Text to find and replace
new_str string Yes Replacement text
sudo boolean No Use sudo privileges

Response:

{
  "success": true,
  "message": "Replacement completed, replaced 5 occurrences",
  "data": {
    "file": "/path/to/file",
    "replaced_count": 5
  }
}

Search File Content

Search file contents using regular expressions.

Endpoint: POST /v1/file/search

Request Body:

{
  "file": "/path/to/file",
  "regex": "search.*pattern",
  "sudo": false
}

Response:

{
  "success": true,
  "message": "Search completed, found 3 matches",
  "data": {
    "file": "/path/to/file",
    "matches": [
      {
        "line_number": 10,
        "line": "Line containing search pattern",
        "match": "search pattern"
      }
    ]
  }
}

Find Files

Find files by glob pattern in specified directories.

Endpoint: POST /v1/file/find

Request Body:

{
  "path": "/path/to/search",
  "glob": "*.txt"
}

Response:

{
  "success": true,
  "message": "Search completed, found 5 files",
  "data": {
    "files": [
      "/path/to/search/file1.txt",
      "/path/to/search/subdir/file2.txt"
    ]
  }
}

Python SDK Example

Here's how to use the File API with Python:

import requests
import json

class AIOSandboxFileClient:
    def __init__(self, base_url="http://localhost:8080"):
        self.base_url = base_url
    
    def read_file(self, file_path, start_line=None, end_line=None, sudo=False):
        """Read file contents"""
        data = {"file": file_path, "sudo": sudo}
        if start_line is not None:
            data["start_line"] = start_line
        if end_line is not None:
            data["end_line"] = end_line
            
        response = requests.post(
            f"{self.base_url}/v1/file/read",
            json=data
        )
        return response.json()
    
    def write_file(self, file_path, content, append=False, sudo=False):
        """Write content to file"""
        data = {
            "file": file_path,
            "content": content,
            "append": append,
            "sudo": sudo
        }
        response = requests.post(
            f"{self.base_url}/v1/file/write",
            json=data
        )
        return response.json()
    
    def search_file(self, file_path, pattern, sudo=False):
        """Search file contents with regex"""
        data = {
            "file": file_path,
            "regex": pattern,
            "sudo": sudo
        }
        response = requests.post(
            f"{self.base_url}/v1/file/search",
            json=data
        )
        return response.json()
    
    def find_files(self, search_path, glob_pattern):
        """Find files by glob pattern"""
        data = {
            "path": search_path,
            "glob": glob_pattern
        }
        response = requests.post(
            f"{self.base_url}/v1/file/find",
            json=data
        )
        return response.json()

# Usage example
client = AIOSandboxFileClient()

# Create a file
result = client.write_file("/tmp/test.txt", "Hello World!\\n")
print(f"Write result: {result}")

# Read the file
result = client.read_file("/tmp/test.txt")
print(f"File content: {result['data']['content']}")

# Search for pattern
result = client.search_file("/tmp/test.txt", r"Hello.*")
print(f"Search results: {result['data']['matches']}")

# Find all .txt files in /tmp
result = client.find_files("/tmp", "*.txt")
print(f"Found files: {result['data']['files']}")

JavaScript SDK Example

For web applications and Node.js:

class AIOSandboxFileClient {
    constructor(baseUrl = 'http://localhost:8080') {
        this.baseUrl = baseUrl;
    }
    
    async readFile(filePath, options = {}) {
        const data = {
            file: filePath,
            sudo: options.sudo || false,
            ...(options.startLine !== undefined && { start_line: options.startLine }),
            ...(options.endLine !== undefined && { end_line: options.endLine })
        };
        
        const response = await fetch(`${this.baseUrl}/v1/file/read`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        return await response.json();
    }
    
    async writeFile(filePath, content, options = {}) {
        const data = {
            file: filePath,
            content,
            append: options.append || false,
            sudo: options.sudo || false,
            leading_newline: options.leadingNewline || false,
            trailing_newline: options.trailingNewline || false
        };
        
        const response = await fetch(`${this.baseUrl}/v1/file/write`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        return await response.json();
    }
    
    async searchFile(filePath, regex, sudo = false) {
        const data = { file: filePath, regex, sudo };
        
        const response = await fetch(`${this.baseUrl}/v1/file/search`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        return await response.json();
    }
    
    async findFiles(searchPath, globPattern) {
        const data = { path: searchPath, glob: globPattern };
        
        const response = await fetch(`${this.baseUrl}/v1/file/find`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        return await response.json();
    }
}

// Usage example
const client = new AIOSandboxFileClient();

async function example() {
    // Write a file
    const writeResult = await client.writeFile('/tmp/demo.js', `
console.log('Hello from AIO Sandbox!');
const message = 'File operations are easy!';
console.log(message);
    `);
    
    // Read it back
    const readResult = await client.readFile('/tmp/demo.js');
    console.log('File content:', readResult.data.content);
    
    // Search for console.log statements
    const searchResult = await client.searchFile('/tmp/demo.js', 'console\\.log.*');
    console.log('Found console.log statements:', searchResult.data.matches);
}

example().catch(console.error);

Error Handling

Common error responses:

File Not Found

{
  "success": false,
  "message": "File not found: /nonexistent/file.txt",
  "error_code": "FILE_NOT_FOUND",
  "data": null
}

Permission Denied

{
  "success": false,
  "message": "Permission denied: /root/secret.txt",
  "error_code": "PERMISSION_DENIED", 
  "data": null
}

Invalid Path

{
  "success": false,
  "message": "Invalid file path",
  "error_code": "INVALID_PATH",
  "data": null
}

Best Practices

  1. Use Absolute Paths: Always provide full file paths starting with /
  2. Handle Permissions: Use sudo: true for system files when necessary
  3. Validate Inputs: Check file paths and content before API calls
  4. Error Handling: Always check the success field in responses
  5. Large Files: Use start_line and end_line for reading large files in chunks

Security Considerations

  • File operations respect system permissions
  • The sudo flag requires appropriate container privileges
  • File paths are validated to prevent directory traversal attacks
  • Content is sanitized to prevent injection attacks

Next Steps

  • Terminal Integration: Combine with shell commands → Shell API
  • Code Execution: Execute code on created files → Code Execution API
  • Practical Examples: See file operations in action → Examples