code-execution-sandbox
Skill0 starsChanged 6 months agoMITView on GitHub
Execute Python code in a restricted sandbox using exec() with limited builtins, stdout capture, and asyncio timeout. Use when an agent needs to run user-supplied or LLM-generated Python code safely without access to the filesystem or dangerous builtins.
In this repository65 other files it gives its agents.
- AGENTS.mdAGENTS.md
- skills/building-agents/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- llms-full.txtllms.txt
- llms.txtllms.txt
- adding-guardrailsSkill
- agent-health-timeoutSkill
- agent-permission-scopingSkill
- agent-session-isolationSkill
- agent-step-loggingSkill
- agent-supervisor-routerSkill
- agent-telemetrySkill
- async-agent-backgroundSkill
- building-agentsSkill
- building-teamsSkill
- building-toolsSkill
- calendar-scheduling-toolSkill
- callback-tracing-handlerSkill
- chain-of-thought-promptingSkill
- chat-model-configurationSkill
- common-agent-patternsSkill
- context-window-managementSkill
- conversation-memorySkill
- conversation-state-dbSkill
- database-query-toolSkill
- document-loadersSkill
- document-rerankingSkill
- email-notification-toolSkill
- embedding-model-ingestionSkill
- fallback-model-chainSkill
- few-shot-injectionSkill
- filesystem-toolSkill
- human-in-the-loopSkill
- hybrid-searchSkill
- inspecting-streamsSkill
- integrating-with-laurenSkill
- json-schema-enforcementSkill
- llm-provider-connectionSkill
- llm-rate-limitingSkill
- long-term-vector-memorySkill
- managing-memorySkill
- migrating-to-lauren-aiSkill
- multi-agent-delegationSkill
- multi-tool-orchestrationSkill
- multi-turn-tool-stateSkill
- output-guardrailsSkill
- plan-and-execute-agentSkill
- prompt-injection-defenseSkill
- prompt-versioningSkill
- rag-pipelineSkill
- react-agent-loopSkill
- response-validation-retrySkill
- rest-api-toolSkill
- securing-agentsSkill
- semantic-cacheSkill
- streaming-response-handlerSkill
- structured-output-parsingSkill
- sub-agent-spawningSkill
- system-prompt-templatingSkill
- testing-agentsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 10
Run Python code snippets inside a restricted exec() environment.
- Distinctive: line 116
Never allow network access inside the sandbox without explicit vetting.
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Use
codemap find "CodeExecutionTool"after adding the pattern to your project.
Code Execution Sandbox Tool
Run Python code snippets inside a restricted exec() environment. Blocks
dangerous builtins (open, exec, eval, __import__), captures stdout,
and enforces a configurable timeout.
Pattern
import asyncio
import io
import sys
from contextlib import redirect_stdout
from lauren_ai._tools import tool, ToolContext
# Build a safe builtins dict by excluding dangerous names
_BLOCKED = {"open", "exec", "eval", "__import__", "compile", "globals", "locals"}
def _safe_builtins() -> dict:
raw = __builtins__ if isinstance(__builtins__, dict) else vars(__builtins__)
return {k: v for k, v in raw.items() if k not in _BLOCKED}
SAFE_BUILTINS = _safe_builtins()
@tool()
class CodeExecutionTool:
"""Execute Python code in a restricted sandbox.
Args:
code: The Python code to execute.
timeout: Maximum execution time in seconds (capped by tool default).
"""
def __init__(self, timeout: float = 5.0):
self._timeout = timeout
async def run(self, ctx: ToolContext, code: str, timeout: float = 5.0) -> dict:
effective_timeout = min(timeout, self._timeout)
stdout_capture = io.StringIO()
local_vars: dict = {}
# exec() is synchronous and CPU-bound — run in a thread so the event
# loop can enforce the timeout even for tight loops that never yield.
def _exec_sync():
with redirect_stdout(stdout_capture):
exec(code, {"__builtins__": SAFE_BUILTINS}, local_vars)
try:
loop = asyncio.get_event_loop()
await asyncio.wait_for(
loop.run_in_executor(None, _exec_sync),
timeout=effective_timeout,
)
return {
"stdout": stdout_capture.getvalue(),
"locals": {
k: repr(v)
for k, v in local_vars.items()
if not k.startswith("_")
},
"success": True,
}
except asyncio.TimeoutError:
return {
"error": f"Execution timed out after {effective_timeout}s",
"success": False,
}
except Exception as e:
return {"error": str(e), "success": False}What is blocked
| Builtin | Risk |
open | Filesystem access |
exec / eval | Dynamic code execution escape |
__import__ | Arbitrary module imports |
compile | Bytecode manipulation |
globals / locals | Scope escape |
Math, string operations, list comprehensions, print, len, range, zip,
enumerate, sorted, sum, etc. all remain available.
Example safe code
code = """
x = [i**2 for i in range(10)]
print(sum(x))
"""
result = await tool.run(ctx, code)
# result == {"stdout": "285\n", "locals": {"x": "[0, 1, 4, ...]"}, "success": True}Example blocked code
result = await tool.run(ctx, "open('/etc/passwd').read()")
# result == {"error": "name 'open' is not defined", "success": False}Notes
asyncio.wait_forwraps a coroutine;execitself is synchronous but runs inside an async wrapper so the event loop can apply the timeout.- For CPU-bound loops that do not yield, consider using
anyio.to_thread.run_syncwith a real thread timeout. - Never allow network access inside the sandbox without explicit vetting.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
Reviews can't be read right now.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

