商业产业 Hacker News AI 2026-07-23T01:54 正文 ok 999 words

Show HN:AgentNest,面向 AI Agent 的自托管沙箱

英文标题:🔶 Show HN: AgentNest, self-hosted sandboxes for AI agents

AgentNest 是一个开源、自托管的 AI Agent 运行时,为 Python、Shell、文件、浏览器、GPU 和 Git 操作提供可丢弃、受策略控制的沙箱环境。它默认采用非 root、只读根文件系统、禁用网络、资源限制和自动清理等安全配置,并支持按域名限制出站网络访问、审计事件、密钥脱敏及审批钩子。项目强调有状态 Python 会话、沙箱状态分叉、流式执行和非破坏性超时等 Agent 原生能力,同时可运行于 Docker、Kubernetes 及可插拔的第三方后端。对开发者而言,AgentNest 可通过 LangChain、smolagents、MCP 等方式接入现有 Agent,并计划提供面向团队的大规模自托管沙箱管理服务。
打开原文相关 3 · 机会 1
media121.4 KB media1.3 KB media1.3 KB media1.3 KB media129.0 KB

中文

AgentNest

用于安全执行 AI Agent 的开源运行时。

CI Python 许可证

AgentNest 为 AI Agent 提供可丢弃、受策略控制的环境,用于执行 Python、Shell 命令、文件操作、包管理、浏览器、GPU 和 Git 工作流。它采用自托管、Python 优先的设计,并有意避免成为又一个云服务或集群编排器。

from agentnest import Sandbox

with Sandbox("python:3.12-slim", timeout=60) as sandbox:
    sandbox.write_file("main.py", "print('Hello from isolation')")
    result = sandbox.exec_shell("python main.py")
    print(result.stdout)
  • **安全默认配置:**非 root、只读根文件系统、无 capabilities、禁止网络、资源限制和自动清理
  • **出站访问白名单:**允许代码访问 pypi.org 而不访问其他地址,并记录每一条连接
  • **Agent 原生:**有状态 Python 会话、可分叉状态、异步、流式处理、密钥、审批和审计事件
  • **非破坏性超时:**运行缓慢的命令会被单独终止;沙箱及其状态仍会保留
  • **崩溃安全:**每项资源都会标记截止期限,因此 agentnest prune 可以回收孤儿资源
  • **经过验证,而非口头承诺:**每次提交都会运行一套逃逸尝试测试
  • **自托管且可扩展:**使用你的 Docker 或 Kubernetes;通过 entry points 支持第三方后端

只需一条命令即可试用(需要 Docker):

pip install agentnest
agentnest demo

警告

容器共享主机内核。请根据你的威胁模型选择合适的隔离边界。在运行敌对的多租户工作负载前,请阅读安全模型。

pip install agentnest
agentnest doctor

可选扩展:

pip install 'agentnest[kubernetes]'
pip install 'agentnest[server]'
pip install 'agentnest[mcp]'
pip install 'agentnest[all]'

from agentnest import NetworkPolicy, Sandbox, Secret, SecurityPolicy

policy = SecurityPolicy(
    network=NetworkPolicy.denied(),
    max_output_bytes=2_000_000,
    require_image_digest=True,
)

with Sandbox(
    "python@sha256:<digest>",
    security_policy=policy,
    environment={"TOKEN": Secret("redacted-in-output")},
    memory="512m",
    cpus=1.0,
) as sandbox:
    for event in sandbox.stream_shell("python main.py"):
        print(event.data, end="")

    checkpoint = sandbox.snapshot("workspace.tar")
    for artifact in sandbox.artifacts("output/**/*"):
        print(artifact.path, artifact.sha256)

只向代码提供它所需的网络访问,别无其他。默认仍然是拒绝访问;白名单会将流量路由到过滤代理,后者只允许已获批准的域名通过。

from agentnest import NetworkPolicy, Sandbox, SecurityPolicy

policy = SecurityPolicy(network=NetworkPolicy.allowlist(domains=("pypi.org", "files.pythonhosted.org")))
with Sandbox("python:3.12-slim", security_policy=policy) as sandbox:
    sandbox.exec_shell("pip install --user requests").check()   # reaches PyPI
    blocked = sandbox.exec_python("import urllib.request; urllib.request.urlopen('https://evil.example')")
    assert not blocked.ok                                       # everything else is refused

持久化解释器会在多次调用之间保留变量和导入内容——这是一种可自托管的代码解释器模型。

with Sandbox("python:3.12-slim") as sandbox:
    session = sandbox.python_session()
    session.run("import pandas as pd; df = pd.DataFrame({'x': [1, 2, 3]})")
    print(session.run("df['x'].sum()").check().result)   # -> 6

对正在运行的沙箱状态进行分支,探索多个后续路径,并保留成功的那个——无需从头重新执行,即可完成并行 A/B 尝试和 Agent 树搜索。

with Sandbox("python:3.12-slim") as base:
    base.write_file("state.json", "{}")
    attempt_a = base.fork()
    attempt_b = base.fork()   # independent copies; neither sees the other's writes

还包括:AsyncSandbox、确定性的 Template 构建、受限的 SandboxPool、Git 工作区辅助工具、浏览器/GPU 预设、MCP 工具、YAML 配置文件、CLI,以及经过身份验证的远程 API。

AgentNest 是一个自托管控制层,而不是托管式沙箱服务。关键区别在于:无论你运行何种后端,它决定 Agent 的代码允许做什么,并记录代码实际做了什么。

AgentNest E2B Modal Sandboxes microsandbox llm-sandbox
自托管,无需账户 ✅ ⚠️ 托管 ⚠️ 托管 ✅
域名出站访问白名单 ✅ ❌ ❌ ❌
有状态 REPL 会话 ✅ ✅ ✅ ✅
可分叉状态 ✅ ❌ ❌ ❌
审批钩子 + 审计事件 ✅ ❌ ❌ ❌
可插拔隔离后端 ✅ ❌ ❌ ❌
可在一个下午内完成审计(约 4k LOC) ✅ ❌ ❌ ⚠️

有关实测冷启动和往返延迟,请参阅基准测试。

在不改变既有安全模型的情况下,为现有 Agent 添加沙箱化代码工具:

from agentnest.integrations.langchain import build_langchain_tool

tool = build_langchain_tool(network_enabled=False)   # a LangChain StructuredTool

此外还提供 smolagents 执行器和框架无关的 SandboxRunner。或者通过 Model Context Protocol 暴露 AgentNest,使 Claude Code、Cursor 或 Claude Desktop 只需一行配置就能安全运行代码:

{ "mcpServers": { "agentnest": { "command": "agentnest", "args": ["mcp"] } } }

请参阅集成指南。

flowchart LR
    App["Agent application"] --> API["Sandbox API"]
    API --> Guard["Policy · approvals · events"]
    Guard --> Contract["RuntimeBackend"]
    Contract --> Docker["Docker / gVisor / Kata"]
    Contract --> K8s["Kubernetes"]
    Contract --> Remote["Remote / Firecracker"]
    Contract --> Plugins["Third-party plugins"]

阅读快速入门、架构文档、部署指南和完整文档。

自托管沙箱管理器

计划推出:一项面向需要同时运行大量沙箱的团队的可选服务。应用程序将向其发送沙箱请求,管理器会在团队现有的 Kubernetes 集群上创建、跟踪并删除临时环境。

该管理器将提供:

  • 队列和按用户划分的限制,防止一个应用耗尽所有可用资源
  • 当应用断开连接或崩溃时自动清理
  • 用于沙箱工作负载的专用 Kubernetes namespace
  • 由 gVisor 支持的沙箱,以实现更强隔离
  • 集中式日志、审计历史、使用指标和健康检查
  • 用于加快启动速度的预热沙箱池

这将始终是可选功能。开发者仍可通过 Docker 或 Kubernetes 直接使用当前的 Sandbox API。AgentNest 将利用现有基础设施,而非取代 Docker 或 Kubernetes。

pip install -e '.[dev,docs]'
ruff check .
ruff format --check .
mypy agentnest
pytest --cov=agentnest --cov-report=term-missing
mkdocs build --strict

Docker 集成测试需手动启用:

AGENTNEST_DOCKER_TESTS=1 pytest -m integration

Apache License 2.0。参见 LICENSE。

English / 原文

AgentNest

The open-source runtime for secure AI agent execution.

CI Python License

AgentNest gives AI agents disposable, policy-controlled environments for Python, shell commands, files, packages, browsers, GPUs, and Git work. It is self-hosted, Python-first, and deliberately not another cloud or cluster orchestrator.

from agentnest import Sandbox

with Sandbox("python:3.12-slim", timeout=60) as sandbox:
    sandbox.write_file("main.py", "print('Hello from isolation')")
    result = sandbox.exec_shell("python main.py")
    print(result.stdout)
  • Secure defaults: non-root, read-only root, no capabilities, denied networking, limits, cleanup
  • Egress allowlisting: let code reach pypi.org and nothing else, with every connection logged
  • Agent-native: stateful Python sessions, forkable state, async, streaming, secrets, approvals, audit events
  • Non-destructive timeouts: a slow command is killed on its own; the sandbox and its state survive
  • Crash-safe: every resource is labelled with a deadline, so agentnest prune reaps orphans
  • Proven, not promised: a suite of escape attempts runs on every commit
  • Self-hosted & extensible: your Docker or Kubernetes; third-party backends via entry points

Try it in one command (needs Docker):

pip install agentnest
agentnest demo

Warning

Containers share the host kernel. Choose an isolation boundary appropriate for your threat model. Read the security model before running hostile multi-tenant workloads.

pip install agentnest
agentnest doctor

Optional extras:

pip install 'agentnest[kubernetes]'
pip install 'agentnest[server]'
pip install 'agentnest[mcp]'
pip install 'agentnest[all]'


from agentnest import NetworkPolicy, Sandbox, Secret, SecurityPolicy

policy = SecurityPolicy(
    network=NetworkPolicy.denied(),
    max_output_bytes=2_000_000,
    require_image_digest=True,
)

with Sandbox(
    "python@sha256:<digest>",
    security_policy=policy,
    environment={"TOKEN": Secret("redacted-in-output")},
    memory="512m",
    cpus=1.0,
) as sandbox:
    for event in sandbox.stream_shell("python main.py"):
        print(event.data, end="")

    checkpoint = sandbox.snapshot("workspace.tar")
    for artifact in sandbox.artifacts("output/**/*"):
        print(artifact.path, artifact.sha256)

Give code the network it needs and nothing more. Denied is still the default; an allowlist routes traffic through a filtering proxy that only lets approved domains through.

from agentnest import NetworkPolicy, Sandbox, SecurityPolicy

policy = SecurityPolicy(network=NetworkPolicy.allowlist(domains=("pypi.org", "files.pythonhosted.org")))
with Sandbox("python:3.12-slim", security_policy=policy) as sandbox:
    sandbox.exec_shell("pip install --user requests").check()   # reaches PyPI
    blocked = sandbox.exec_python("import urllib.request; urllib.request.urlopen('https://evil.example')")
    assert not blocked.ok                                       # everything else is refused

A persistent interpreter keeps variables and imports across calls — the code interpreter model, self-hosted.

with Sandbox("python:3.12-slim") as sandbox:
    session = sandbox.python_session()
    session.run("import pandas as pd; df = pd.DataFrame({'x': [1, 2, 3]})")
    print(session.run("df['x'].sum()").check().result)   # -> 6

Branch a running sandbox's state, explore several continuations, keep the one that worked — parallel A/B attempts and agent tree search without re-running from scratch.

with Sandbox("python:3.12-slim") as base:
    base.write_file("state.json", "{}")
    attempt_a = base.fork()
    attempt_b = base.fork()   # independent copies; neither sees the other's writes

Also included: AsyncSandbox, deterministic Template builds, bounded SandboxPool, Git workspace helpers, browser/GPU presets, MCP tools, YAML profiles, a CLI, and an authenticated remote API.

AgentNest is a self-hosted control layer, not a hosted sandbox service. The distinction that matters: it decides what an agent's code is allowed to do and records what it did , across whatever backend you run.

| AgentNest | E2B | Modal Sandboxes | microsandbox | llm-sandbox
---|---|---|---|---|---
Self-hosted, no account | ✅ | ⚠️ hosted | ⚠️ hosted | ✅ | ✅
Domain egress allowlist | ✅ | ❌ | ❌ | ❌ | ❌
Stateful REPL sessions | ✅ | ✅ | ✅ | ✅ | ⚠️ partial
Forkable state | ✅ | ❌ | ❌ | ❌ | ❌
Approval hooks + audit events | ✅ | ❌ | ❌ | ❌ | ❌
Pluggable isolation backend | ✅ | ❌ | ❌ | ❌ | ⚠️
Auditable in an afternoon (~4k LOC) | ✅ | ❌ | ❌ | ⚠️ | ✅

See benchmarks for measured cold-start and round-trip latencies.

Give an existing agent a sandboxed code tool without changing its security story:

from agentnest.integrations.langchain import build_langchain_tool

tool = build_langchain_tool(network_enabled=False)   # a LangChain StructuredTool

There is a smolagents executor and a framework-neutral SandboxRunner too. Or expose AgentNest over the Model Context Protocol so Claude Code, Cursor, or Claude Desktop can run code safely in one line of config:

{ "mcpServers": { "agentnest": { "command": "agentnest", "args": ["mcp"] } } }

See the integration guide.

flowchart LR
    App["Agent application"] --> API["Sandbox API"]
    API --> Guard["Policy · approvals · events"]
    Guard --> Contract["RuntimeBackend"]
    Contract --> Docker["Docker / gVisor / Kata"]
    Contract --> K8s["Kubernetes"]
    Contract --> Remote["Remote / Firecracker"]
    Contract --> Plugins["Third-party plugins"]

Loading

Read the quickstart, architecture, deployment guide, and complete documentation.

Self-hosted sandbox manager

Planned: an optional service for teams that need to run many sandboxes at once. Applications will send it a sandbox request, and the manager will create, track, and delete the temporary environments on the team's existing Kubernetes cluster.

The manager will provide:

  • Queues and per-user limits so one application cannot consume every available resource
  • Automatic cleanup if an application disconnects or crashes
  • A dedicated Kubernetes namespace for sandbox workloads
  • gVisor-backed sandboxes for stronger isolation
  • Central logs, audit history, usage metrics, and health checks
  • Warm sandbox pools for faster startup

This will remain optional. Developers will still be able to use the current Sandbox API directly with Docker or Kubernetes. AgentNest will use existing infrastructure rather than replace Docker or Kubernetes.

pip install -e '.[dev,docs]'
ruff check .
ruff format --check .
mypy agentnest
pytest --cov=agentnest --cov-report=term-missing
mkdocs build --strict

Docker integration tests are opt-in:

AGENTNEST_DOCKER_TESTS=1 pytest -m integration

Apache License 2.0. See LICENSE.