How can an agent execute code safely?
An AI agent can execute code safely by running it inside a restricted execution environment instead of giving generated code direct access to the host system.
The model may decide what code should run, but a trusted runtime should control where it runs, what resources it can use, and what it is allowed to access.
Why code execution is risky
Generated code can:
- consume excessive CPU or memory
- read sensitive files
- make network requests
- modify data
- install packages
- create infinite loops
- expose credentials
- execute destructive commands
Even code that looks harmless can behave unexpectedly.
So code execution should be treated as a high-risk capability.
Use a sandbox
A sandbox is an isolated environment designed to limit what executed code can affect.
The sandbox may restrict:
- filesystem access
- network access
- available processes
- environment variables
- system calls
- installed libraries
- execution time
- CPU and memory
If the code fails or behaves badly, the damage should remain contained inside the sandbox.
Example
Suppose an agent needs to calculate statistics from a CSV file.
Instead of giving the model direct access to the server, the system can:
- copy the approved CSV into a temporary sandbox
- run generated analysis code there
- enforce CPU, memory, and time limits
- return only the result or generated artifact
- destroy the sandbox after execution
The code receives only what it needs.
Apply least privilege
The execution environment should expose the minimum capabilities required for the task.
For example, a data-analysis job may need:
- Python
- one uploaded dataset
- selected libraries
It probably does not need:
- production credentials
- SSH access
- unrestricted internet
- the server filesystem
- internal databases
Reducing capabilities limits the impact of mistakes.
Restrict filesystem access
Code should usually run in a temporary working directory.
The sandbox can prevent access to:
- system configuration
- application secrets
- other users' files
- production source code
- unrelated mounted drives
Only explicitly approved inputs should be mounted into the environment.
Restrict network access
Unrestricted network access can allow generated code to:
- send sensitive data elsewhere
- download malicious software
- contact internal services
- bypass normal tool permissions
Depending on the task, the safest default may be:
No network access.
If network access is needed, it can be limited to approved destinations.
Never place secrets directly in the code context
Sensitive values such as:
- API keys
- database passwords
- cloud credentials
- private tokens
should not be inserted into generated code unless absolutely necessary.
If a task needs an external service, it is often safer to expose a narrow authenticated tool rather than giving arbitrary code access to the credential.
Apply execution limits
The runtime should enforce limits such as:
- maximum execution time
- CPU quota
- memory quota
- disk quota
- process count
- output size
For example, an infinite loop should be terminated automatically rather than consuming resources indefinitely.
Control dependencies
Allowing generated code to install arbitrary packages introduces supply-chain risk.
Safer options include:
- preinstalled approved libraries
- package allowlists
- pinned package versions
- isolated package installation
- malware or policy checks
The agent should not automatically install any dependency it invents.
Validate inputs before execution
The system should control which files, parameters, and data are provided to the code.
For example:
Approved input: uploaded sales.csv
should not silently become:
Entire production storage directory
The execution environment should receive only the minimum necessary inputs.
Separate code generation from execution
A useful design is:
Model generates code → runtime checks policy → sandbox executes code → result returns to model
The model does not control the execution environment itself.
This separation creates a deterministic security boundary.
Consider static checks before execution
Some systems inspect generated code before running it.
Checks may look for:
- dangerous imports
- shell execution
- unauthorized file access
- prohibited network calls
- destructive commands
Static checks are useful but should not replace sandboxing because harmful behavior can be hidden or generated dynamically.
Shell access needs extra caution
A general shell is usually more powerful than a narrow code-execution interface.
Commands can:
- modify the filesystem
- spawn processes
- install software
- access environment variables
If shell access is available, it should be heavily restricted or isolated inside the sandbox.
Treat code output as untrusted
Executed code may return:
- text
- files
- JSON
- logs
- images
- errors
The agent should validate the result before using it downstream.
A successful process exit does not automatically mean the produced data is correct.
State-changing code needs stronger approval
Some code may modify:
- databases
- infrastructure
- production files
- cloud resources
For example:
deploy application
is very different from:
calculate average sales
High-impact code should require stronger permissions, deterministic policy checks, or human approval.
Keep executions isolated between users
In multi-user systems, one code execution should not see another user's:
- files
- memory
- environment variables
- processes
- credentials
- cached outputs
Each run should have isolated execution state.
Log important execution details
Useful audit information may include:
- who requested execution
- code or code hash
- inputs
- sandbox configuration
- start and end time
- resource usage
- exit status
- generated artifacts
This helps debug failures and investigate unexpected behavior.
Destroy temporary environments when finished
Ephemeral sandboxes reduce the amount of state that persists between executions.
After the task completes, the system can remove:
- temporary files
- processes
- cached data
- execution state
This reduces accidental leakage between runs.
A practical safe execution flow
A reliable code-execution path can look like:
- Agent decides code execution is necessary.
- Required inputs are identified.
- Permissions and policies are checked.
- A restricted sandbox is created.
- Only approved files and libraries are exposed.
- Resource and network limits are applied.
- Code executes.
- Output and errors are validated.
- Results return to the agent.
- The temporary environment is destroyed.
In short
An AI agent should execute code inside an isolated, least-privilege sandbox with strict controls over files, network access, dependencies, resources, credentials, and side effects.
The model can generate or select code, but trusted infrastructure should control execution. Sandboxing, isolation, resource limits, policy enforcement, and careful handling of inputs and outputs are what make agent code execution safer.
Learning Sequence
AI Agents Curriculum
Explore Related Questions
Deepen your understanding across related AI Agents topics.