Action Restrictions and Permissions › Sandboxing the Agent's Environment

Michael BrenndoerferAugust 14, 20253 min read
AI Agent HandbookAll chapters
Part 13 of 15Safety and Governance - Keeping the Agent Aligned
Chapter 37Action Restrictions and Permissions › Sandboxing the Agent's Environment
Reading section 5 of 11 · Sandboxing the Agent's Environment · 3 minSection 5 of 11 · 3 min

Book contents

Section 5 of 11 · 3 min read

Action Restrictions and Permissions › Sandboxing the Agent's EnvironmentOne section · Sections in this chapter5 / 11 ↓

Even with restrictions and confirmations, you might want an extra layer of protection: running the agent in a sandbox. A sandbox is a restricted environment where the agent can operate without affecting the rest of your system.

Think of it like a playground with a fence. The agent can do whatever it wants inside the sandbox, but it can't get out and affect anything beyond the fence.

Here's a simple example using Docker to sandbox file operations:

In[2]:
Code
## Using Claude Sonnet 4.5 with sandboxed file operations
import docker
import tempfile
import os

class SandboxedAgent:
    def __init__(self):
        self.client = docker.from_env()
        # Create a temporary directory for the sandbox
        self.sandbox_dir = tempfile.mkdtemp()
        
    def execute_file_operation(self, code):
        """Execute Python code in a sandboxed Docker container"""
        # Create a Python script with the code
        script_path = os.path.join(self.sandbox_dir, 'script.py')
        with open(script_path, 'w') as f:
            f.write(code)
        
        # Run the code in a Docker container with limited permissions
        container = self.client.containers.run(
            'python:3.9-slim',
            f'python /sandbox/script.py',
            volumes={
                self.sandbox_dir: {'bind': '/sandbox', 'mode': 'rw'}
            },
            network_disabled=True,  # No network access
            mem_limit='256m',  # Limited memory
            cpu_period=100000,
            cpu_quota=50000,  # Limited CPU
            remove=True,
            detach=False
        )
        
        return container.decode('utf-8')
    
    def cleanup(self):
        """Clean up the sandbox directory"""
        import shutil
        shutil.rmtree(self.sandbox_dir)

This sandbox provides several protections:

Isolated filesystem: The agent can only access files in the sandbox directory. It can't read or modify anything else on your system.

No network access: The agent can't make network requests, preventing it from sending data to external servers.

Resource limits: The agent gets limited CPU and memory, preventing it from consuming all your system resources.

Automatic cleanup: When you're done, you can delete the entire sandbox, removing any files the agent created.

For most personal assistants, full Docker sandboxing might be overkill. But the principle is valuable: isolate risky operations so they can't affect the rest of your system.

A lighter-weight approach is to use Python's built-in restrictions:

In[8]:
Code
import os
import sys

def run_restricted_code(code):
    """Run Python code with restricted built-ins"""
    # Create a restricted environment
    restricted_globals = {
        '__builtins__': {
            'print': print,
            'len': len,
            'range': range,
            'str': str,
            'int': int,
            'float': float,
            'list': list,
            'dict': dict,
            # Add only safe built-ins
        }
    }
    
    # Execute the code in the restricted environment
    try:
        exec(code, restricted_globals)
        return "Code executed successfully"
    except Exception as e:
        return f"Error: {str(e)}"

## Example: This will work
result = run_restricted_code("print('Hello, world!')")
print(result)  # "Code executed successfully"

## Example: This will fail (no file access)
result = run_restricted_code("open('/etc/passwd', 'r')")
print(result)  # "Error: name 'open' is not defined"
Out[8]:
Console
Hello, world!
Code executed successfully
Error: name 'open' is not defined

This approach removes dangerous built-ins like open, eval, and __import__, preventing the agent from accessing files or importing modules. It's not as secure as Docker, but it's much simpler and works for many use cases.