agent-sandbox
БесплатноБез исполняемых скриптовНе проверенRun AI agent code safely in isolated sandboxes with resource limits, audit trails, and kill switches. Use when someone asks to "sandbox my agent", "run agent…
Об этом скилле
Agent Sandbox
Overview
AI agents execute code, modify files, and run shell commands. Without guardrails, a bad prompt or hallucination can delete your database, overwrite production configs, or exfiltrate secrets. This skill builds safety layers — sandboxed execution, filesystem restrictions, network policies, audit trails, and kill switches.
When to Use
- Running untrusted or AI-generated code in production
- Adding safety controls to coding agents that modify your codebase
- Restricting which files, directories, or commands an agent can access
- Logging every agent action for compliance or debugging
- Building multi-tenant agent platforms where agents need isolation
Instructions
Three layers, from cheapest to strongest. Pick by threat: a clumsy agent needs layer 1; hostile or untrusted code needs layer 2 or 3.
Layer 0: Use the sandbox your agent already ships
Claude Code has an OS-enforced Bash sandbox (Seatbelt on macOS, bubblewrap + socat on Linux/WSL2). It is off by default: run /sandbox in a session or set sandbox.enabled to true in ~/.claude/settings.json. Commands may write only to the working directory and temp, the network goes through a proxy that allows only sandbox.network.allowedDomains, and sandbox.filesystem.denyRead / allowWrite tune the rest. It covers shell commands only; file tools, MCP servers and hooks run outside it. Set allowUnsandboxedCommands: false to stop the retry-outside-sandbox escape. The engine is the open-source @anthropic-ai/sandbox-runtime, usable to wrap your own agent process. Check what other agent CLIs offer before writing your own wrapper.
Layer 1: Filesystem + Command Guard (no Docker)
A policy layer for agents whose tools you control (your own agent loop). It stops mistakes, not attackers: a string blocklist is easy to bypass (r""m, base64, scripts written then executed), so route exec into Layer 2 for anything untrusted.
// sandbox.ts
import { execSync } from "node:child_process";
import { appendFileSync, existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { dirname, relative, resolve } from "node:path";
interface SandboxConfig {
workDir: string;
allowedPaths: string[]; // globs relative to workDir; a path must match one to be touched
deniedPaths: string[]; // globs that always win
blockedCommands: RegExp[];
maxFileSize: number; // bytes per write
auditLog: string; // keep OUTSIDE workDir
readOnly: boolean;
}
const DEFAULT_BLOCKED = [
/\brm\s+-[a-z]*r[a-z]*f?\s+(\/|~|\.)(\s|$)/i,
/\b(mkfs|dd\s+if=)/i,
/\b(drop|truncate)\s+(database|table)\b/i,
/(curl|wget)[^|]*\|\s*(sudo\s+)?(ba|z)?sh\b/i,
/\bchmod\s+(-R\s+)?777\b/,
/(env|printenv)\s*\|\s*(curl|nc)/i,
];
export class SandboxError extends Error {}
function globToRegExp(glob: string): RegExp {
const re = glob
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
.replace(/\*\*\//g, "\u0000")
.replace(/\*\*/g, "\u0001")
.replace(/\*/g, "[^/]*")
.replace(/\u0000/g, "(?:.*/)?")
.replace(/\u0001/g, ".*");
return new RegExp(`^${re}$`);
}
export class AgentSandbox {
private cfg: SandboxConfig;
private killed = false;
constructor(cfg: Partial<SandboxConfig> & { workDir: string }) {
this.cfg = {
allowedPaths: ["**"],
deniedPaths: ["**/.env*", "**/.ssh/**", "**/*.pem", ".git/config"],
blockedCommands: DEFAULT_BLOCKED,
maxFileSize: 1024 * 1024,
auditLog: "/var/log/agent-audit.jsonl",
readOnly: false,
...cfg,
};
this.cfg.workDir = realpathSync(this.cfg.workDir);
}
readFile(path: string): string {
const abs = this.guard(path, "read");
this.audit("read", path);
return readFileSync(abs, "utf-8");
}
writeFile(path: string, content: string): void {
if (this.cfg.readOnly) throw new SandboxError("write blocked: sandbox is read-only");
const abs = this.guard(path, "write");
if (Buffer.byteLength(content) > this.cfg.maxFileSize) throw new SandboxError("write blocked: file too large");
this.audit("write", path, { bytes: Buffer.byteLength(content) });
writeFileSync(abs, content);
}
exec(command: string, timeoutMs = 30_000): string {
this.alive();
if (this.cfg.blockedCommands.some((re) => re.test(command))) {
this.audit("exec_blocked", command);
throw new SandboxError("command blocked by policy");
}
this.audit("exec", command);
return execSync(command, { cwd: this.cfg.workDir, encoding: "utf-8", timeout: timeoutMs, maxBuffer: 10 * 1024 * 1024 });
}
kill(reason: string): void {
this.killed = true;
this.audit("killed", reason);
}
private alive() {
if (this.killed) throw new SandboxError("agent has been killed");
}
// Resolve symlinks first so a link inside workDir cannot point outside it.
private guard(path: string, op: string): string {
this.alive();
const abs = resolve(this.cfg.workDir, path);
const re
Установить agent-sandbox в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл agent-sandbox?
Run AI agent code safely in isolated sandboxes with resource limits, audit trails, and kill switches. Use when someone asks to "sandbox my agent", "run agent code safely", "add guardrails to AI agent", "isolate agent execution", "audit agent actions", "prevent agent from deleting files", "restrict agent permissions", or "add safety controls to AI coding agent". Covers Docker isolation, filesystem restrictions, network policies, resource locking, and comprehensive audit logging.
Как установить скилл agent-sandbox?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл agent-sandbox запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic