Files
AgentLab/backend/app/sandbox/bubblewrap_sandbox.py
T
ThearchyHelios 03c18c4d78 界面文案整改:口语改书面、术语统一、不再露出实现细节;修掉几处说错的提示;新增文案检查防回潮
一、文案(前端约 1600 处,后端传到界面的约 880 处)
- 术语统一:工作流层面用「运行」(继续运行、重新运行、试运行),节点和工具层面用「执行」,不再用「跑」;
  总时长 / 执行时长 / 等待审批;服务端;助手;Agent;token;工作流;固定版本;模型接入;系统提示;批准 / 驳回;受管级别
- 口语改书面:取不到、没取回来、读不懂、连不上、多半、照样、兜底、揉成这类说法改成「无法 / 未能 / 失败 / 请」;去掉拟人写法
- 不再露出实现细节:界面上不写 checkpoint、同一拍、哈希(凭证处除外),不写改版历史(「以前…」「老数据」);
  报错、校验、门禁、自动修复里裸写的配置键名和枚举值换成界面上的中文标签,由新的 backend/app/engine/labels.py 统一提供;
  发布弹窗里结论句的选项不再是 off / require_citation
- 同一件事只留一种说法:生成阶段文案、出具档位说明、画布锁定提示各合成一份
- 去掉界面上的工业场景示例(MES、ERP、「张工」「王工」)和真实产品名,换成通用示例

二、说错的提示(都有测试证明)
- 数据库测连接失败时的专用提示以前从不出现(按报错文字全等比较,永远比不上):改为按错误类型判断,不再拼出重复的前缀
- 「设置 → 供应商」改指「设置 → 模型接入」;「在设置里建数据源」改指「数据」页
- 缺少 API Key、模型接入已停用的报错不再夹英文,写明去哪里填
- 两处原因说错(「这种引用在后续版本支持」「这一版还不支持」)改成真实原因
- 节点说明里不准确的说法改正:代码节点在 microVM 或系统沙箱中执行;报告撰写、口径卡的说明不再说过头
- 导出的证据 CSV 里两列同名,第三列改为「片段编号」

三、前后端对齐
- 前端按后端原文识别日志、报错的地方,新旧两种写法都认得(历史运行里存的是旧文字),逐条补了新旧原文的核对
- 后端交回模型的原指令放进单独的 for_model 字段,前端在解析响应时去掉,不会显示到界面上

四、检查
- 检查脚本里按原文匹配的断言改成新文案;改完会变成永远成立的反向断言逐条修正,并做了变异验证
- 新增 check-copy(静态扫描前端界面字符串和后端上界面的文案):再出现「跑」「后端」「多半」「令牌」、
  界面上的 Copilot、裸写的配置键名、半角标点等就报错;确需保留的写进 scripts/copy-allow.json 并注明理由
2026-09-30 08:05:15 +08:00

184 lines
7.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import asyncio
import logging
import os
import resource
import shutil
import sys
import time
from pathlib import Path
from app.core.config import settings, sanitize_session
from app.core.errors import describe_exception, raw
from app.sandbox import interpreter
from app.sandbox.base import ENTRY_PREFIX, ExecResult, Sandbox, SandboxLimits, entry_name, truncate
logger = logging.getLogger(__name__)
# 入口脚本后缀 + 执行命令前缀(沙箱内路径在运行时拼)。文件名不能写死:
# 同会话并发执行都写 main.py 会互相覆盖。
_LANG = {
"python": (".py", None), # 运行时用 interpreter.python_argv()
"bash": (".sh", ["/bin/bash"]),
"sh": (".sh", ["/bin/sh"]),
"node": (".js", ["node"]),
"javascript": (".js", ["node"]),
}
# 只读挂进沙箱的系统目录,存在才挂
_RO_BINDS = ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/alternatives", "/etc/ssl"]
class BubblewrapSandbox(Sandbox):
"""Linux 上的对等方案:bubblewrap(Flatpak 的沙箱内核)。
一个几百 KB 的二进制,直接用 namespace + seccomp 建隔离环境,
不需要 daemon、不需要 root、不需要镜像。相比 Seatbelt 它还多隔离了
PID、IPC 和挂载视图,隔离强度更接近容器。
"""
name = "bubblewrap"
def __init__(self) -> None:
self._root = settings.workspace_dir / "bwrap"
self._bwrap = shutil.which("bwrap")
@staticmethod
def available() -> bool:
return sys.platform.startswith("linux") and shutil.which("bwrap") is not None
async def health(self) -> dict[str, object]:
ok = self.available()
return {
"backend": self.name,
"available": ok,
"isolated": ok,
"isolation": "Linux namespace(mount/pid/ipc/uts/net)+ 只读根",
"limits_note": "内存与 CPU 由 rlimit 限制;如需 cgroups 级配额请配合 systemd-run",
"enforced": {"timeout": True, "cpu": True, "memory": True, "network": True, "fsize": True},
"root": str(self._root),
"interpreter": interpreter.describe(),
**({} if ok else {"error": "未找到 bwrap,可执行 apt install bubblewrap 安装"}),
}
def _session_dir(self, session_id: str) -> Path:
# 净化规则统一在 config.sanitize_session 里,四个后端和文件工具共用一份:
# 这段逻辑以前各抄各的,文件工具那份漏抄了,就成了越界读取的口子。
path = self._root / sanitize_session(session_id)
path.mkdir(parents=True, exist_ok=True)
return path
@staticmethod
def _preexec(limits: SandboxLimits): # pragma: no cover - 子进程里执行
def _apply() -> None:
resource.setrlimit(resource.RLIMIT_CPU, (limits.timeout, limits.timeout + 2))
# Linux 上 RLIMIT_AS 是真正生效的(macOS 不是)
nbytes = limits.memory_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (nbytes, nbytes))
resource.setrlimit(resource.RLIMIT_FSIZE, (256 * 1024 * 1024,) * 2)
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
os.setsid()
return _apply
def _argv(self, workdir: Path, limits: SandboxLimits, cmd: list[str]) -> list[str]:
argv = [
self._bwrap or "bwrap",
"--unshare-all", # mount/pid/ipc/uts/cgroup/net 全部隔离
*(["--share-net"] if limits.network else []),
"--die-with-parent", # 父进程没了,沙箱跟着走
"--new-session", # 摘掉控制终端,防 TIOCSTI 注入
"--proc", "/proc",
"--dev", "/dev",
"--tmpfs", "/tmp",
"--bind", str(workdir), "/work",
"--chdir", "/work",
"--setenv", "HOME", "/work",
"--setenv", "TMPDIR", "/tmp",
"--setenv", "PATH", "/usr/bin:/bin",
"--setenv", "PYTHONDONTWRITEBYTECODE", "1",
]
for path in _RO_BINDS:
if Path(path).exists():
argv += ["--ro-bind", path, path]
return argv + ["--", *cmd]
async def run(
self,
code: str,
*,
language: str = "python",
limits: SandboxLimits | None = None,
session_id: str | None = None,
env: dict[str, str] | None = None,
files: dict[str, str] | None = None,
) -> ExecResult:
limits = limits or SandboxLimits()
language = (language or "python").lower()
if language not in _LANG:
return ExecResult(ok=False, backend=self.name, error=f"不支持的语言:{language}")
if not self.available():
return ExecResult(ok=False, backend=self.name, error="bwrap 不可用")
ext, cmd_prefix = _LANG[language]
# python 的命令前缀运行时才定:要挑一个看不见后端依赖的解释器
cmd_prefix = cmd_prefix if cmd_prefix is not None else interpreter.python_argv()
entry = entry_name(ext)
cmd = [*cmd_prefix, f"/work/{entry}"]
workdir = self._session_dir(session_id or f"tmp-{int(time.time() * 1000)}")
(workdir / entry).write_text(code)
for rel, content in (files or {}).items():
target = (workdir / rel).resolve()
if not str(target).startswith(str(workdir.resolve())):
return ExecResult(ok=False, backend=self.name, error=f"非法文件路径:{rel}")
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content)
argv = self._argv(workdir, limits, cmd)
for key, value in (env or {}).items():
argv[1:1] = ["--setenv", key, value]
started = time.perf_counter()
try:
proc = await asyncio.create_subprocess_exec(
*argv,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
preexec_fn=self._preexec(limits),
)
out, err = await asyncio.wait_for(proc.communicate(), timeout=limits.timeout)
except asyncio.TimeoutError:
try:
os.killpg(os.getpgid(proc.pid), 9)
except (ProcessLookupError, PermissionError):
proc.kill()
await proc.wait()
return ExecResult(
ok=False, backend=self.name, timed_out=True, exit_code=124,
duration_ms=int((time.perf_counter() - started) * 1000),
error=f"执行超过 {limits.timeout} 秒,已终止",
)
except Exception as e: # noqa: BLE001
# 起进程和收输出在同一个 try 里。首行只说原因,类名和 errno 这些留给日志
logger.warning("%s 沙箱进程出错:%s", self.name, raw(e))
return ExecResult(ok=False, backend=self.name, error=f"沙箱进程出错:{describe_exception(e)}")
stdout, t1 = truncate(out.decode(errors="replace"), limits.max_output)
stderr, t2 = truncate(err.decode(errors="replace"), limits.max_output)
code_ = proc.returncode or 0
return ExecResult(
ok=code_ == 0,
exit_code=code_,
stdout=stdout,
stderr=stderr,
truncated=t1 or t2,
timed_out=code_ in (-24, 152),
backend=self.name,
duration_ms=int((time.perf_counter() - started) * 1000),
files_written=[p.name for p in workdir.iterdir() if p.is_file() and not p.name.startswith(ENTRY_PREFIX)][:50],
)
async def cleanup(self, session_id: str) -> None:
await asyncio.to_thread(shutil.rmtree, self._session_dir(session_id), True)